diff --git a/LeanPool/ExactMatrixExponents.lean b/LeanPool/ExactMatrixExponents.lean new file mode 100644 index 0000000000..853e85f380 --- /dev/null +++ b/LeanPool/ExactMatrixExponents.lean @@ -0,0 +1,29 @@ +/- +Copyright (c) 2026 Lean Pool contributors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Lean Pool contributors +-/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.ExactExponent + +/-! +# Exact square, dual and rectangular matrix multiplication exponents + +Source: url:https://github.com/openai/math/blob/3344da59991ed94f9ba711217b29c1d760badfa6/lean/OAI/LinearAlgebra/SpectralBooks/ExactExponent.lean +Authors: OpenAI +Status: verified +Main declarations: `MatrixMultiplicationAllFields.SpectralBooks.square_exponent`, + `MatrixMultiplicationAllFields.SpectralBooks.dual_exponent`, + `MatrixMultiplicationAllFields.SpectralBooks.rectangular_exponent` +Tags: matrix-multiplication, arithmetic-complexity, tensor-rank, rectangular-exponents +MSC: 68Q17, 15A69, 68Q25 +-/ + +/-! +## Arithmetic model and sources + +The pinned Lean file states all three exact results for division-free programs. +The November 24, 2026 preprint states the square equality for formal circuits +allowing division, bounds the dual exponent, and gives rectangular rank lower bounds. +-/ diff --git a/LeanPool/ExactMatrixExponents/Imports.lean b/LeanPool/ExactMatrixExponents/Imports.lean new file mode 100644 index 0000000000..4ae2e2d5fa --- /dev/null +++ b/LeanPool/ExactMatrixExponents/Imports.lean @@ -0,0 +1,608 @@ +/- +Copyright (c) 2026 Lean Pool contributors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Lean Pool contributors +-/ +module -- shake: keep-all --deprecated_module: ignore + +-- Generated project imports; run `lake exe mk_all`. +public import LeanPool.ExactMatrixExponents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.AdjacentDuplicates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Apply +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Carry +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Factor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.ShortNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.ChannelPlan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Fragments +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.FreezeInput.Cost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.FreezeInput.Retain +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.ChildPaths +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.BoardPush +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Checks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Entry +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Length +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Prefix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Radius +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Reads +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.State +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Merge.Program +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Mixer.Apply +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Mixer.Choice +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.PayloadProgram +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Contacts +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Parcel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Rate.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Sheet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Status +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Attachment.WriteNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Described +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Headers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Width +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Move +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Ports.Correspondence +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Ports.Eval +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Raw.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Repost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Routes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Answer +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Exterior +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Rate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Spans +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Travel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.RetagStore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Shipment.Bound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanSupplies +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanTiles +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Issue +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.ContractRates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.DictionaryHeaders +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.Outer +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.OuterRows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.HeaderCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.Rule +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.TemplateCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Compilation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Encoded +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Encoding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Exterior.Fields +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Exterior.Strips +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Exterior.Supply +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Hard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Header +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Observed +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Phase.ResetRate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Pieces +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Plan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.PortRelay +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Carry +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Elect +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.MixCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Rule +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Stack.StartBound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Hop +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.One +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.TraceNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Transform +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Batcher +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Bilinearize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BitonicMerge +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BitonicSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BlockProducts +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BlockRecursion +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CircuitCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Add +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Chart +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Edges +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Formula +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Run +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Shift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Address +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Named +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Ranks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Derivatives +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Descent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.AlphabetCode +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Bounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Broadcast +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Cuts +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Fixing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Input +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Physical +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Replay +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.TemplateSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Canonical +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Normalize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Present +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Substitute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Wide +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Distinctness +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldExtension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldFormula +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Flattening +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Fourier +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FunctionNetwork +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Growth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Close +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.ControlWeight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.SumOut +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Interpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Nodes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.RingFormula +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.ChargedSeparation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Degeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.DirectSum +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Dots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.DotsPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Permutations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.PolynomialDegeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.PolynomialValues +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Tag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.TagFinite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialDegeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialFiltration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialFiltrationFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialSectorFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialSectors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialWeightFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Separation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.SeparationInterpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.TagHeterogeneous +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.TagOptimized +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.TagTensorWords +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Base +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Blocks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Matrix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Powers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.RankOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.UpperBound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.WeightedGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Iteration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.ListBounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.LocalTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Counter +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Scan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.ShortTag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Single +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Mixer.Score +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Matrix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Obstruction +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.BadBases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Beat +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Budget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Delivery +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.FieldLift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.HostReset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Reservations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.ResetLocation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.RestoreCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.TetherHost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Chord +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Fields +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Finite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.FourArms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.Rigidity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.ScaleSlope +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.TreePrice +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.Tripod +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.Zoom +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.MovingForms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Padding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Sync +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Tensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.WireRecovery +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.PrimeFields +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.AddressSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Capacity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.DispatchSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.FetchSlot +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Handle +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.LocalBank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.LocalReceive +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.PacketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.PinIndexRead +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Resistance +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Skip +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Slots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Vector.Cases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.WindowSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Alignment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Focus +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Replay +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.ReplayRel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Wired +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Budget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Estimate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Protocol +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Short +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.WideTag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.RankCriterion +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.RankPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.RationalCircuits +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Realization +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Surplus +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.WeightedModel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Bounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.CharacterRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Face.Contact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.FiniteModel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Folding.Swap +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Folding.Transfer +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Interior.Convert +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Interior.Fill +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Interior.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Mask +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Minimum.FaceZero +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Multi.Count +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Multi.Radial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Poly +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Arms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Binary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Pairing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Root +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Degree +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Entropy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Directions +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Strict +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sums.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Support +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Threshold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Threshold.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Threshold.Square +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Gaps +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Cuts +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Energy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Jacobian +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Ray +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.SimpleLift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Lower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Possible +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.TreePossible +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weighted +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Bins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Construct +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Beat.Fanout +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Beat.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Pass +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Plan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Reset.Label +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Reset.WindowCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Restart +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Subround +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Costs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Downstream +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Installation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Majorants +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Passage +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Recovery.Run +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Stack.Mates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Algorithm.Computability +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Compatible +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Decor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Keys +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Rig +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Fixed +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryComparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryControl +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryEfficient +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryJets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryPrices +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometrySector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometrySharp +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryTerms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Packets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Parameters +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Partitions +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.PartitionsPlane +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Round +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.SortSpec +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Square +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Uniform.System +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Design +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.FieldStage +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Specialization +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.CubeGadget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Extra +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Packets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rule +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Span +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Wire +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Comparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Constrained +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Extension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Gadget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Block +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Concentration.Kits +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Depth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Initial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Reorder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Update +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.View +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Coupled +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Crossing.Form +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Debit.Legs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Footprint.Load +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.FusedTerms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.General.Ballot +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.General.Pruned +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.General.Scales +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Decoding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Exterior +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Origin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Ledger +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Owners +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Interpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Angular +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Encode +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Host +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Load +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Sharing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Squares +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Trie +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Ledger.Quota +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.History +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.Hub +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Border +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Pattern +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Shapes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Payload.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Plant.Decoded +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Price.Allowance +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Price.Run +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Capacity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Correct +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Traces +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Pins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Presentation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Seating +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Wiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Work +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Proof.Initial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Scalar.Term +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Ledger +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Pull +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Remnants +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.TableMotion +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Verifier.Caps +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Scenario +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Window +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Width +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.ColumnNetwork +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Hard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Reduction +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortBack +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortOne +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Tags +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Runs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.RAM.Calls +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Choices +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Graph +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Packets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Restore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.System +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.Table +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.ChargedSeparation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Degeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.DirectSum +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Dots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.DotsPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.PermutationPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Permutations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.PolynomialDegeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.PolynomialValues +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Tag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.TagFinite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialDegeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialFiltration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialFiltrationFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialSectorFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialSectors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialWeightFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Separation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.SeparationInterpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.TagHeterogeneous +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.TagTensorWords +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Base +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Blocks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Flattening +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.FlatteningOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Matrix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Powers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.RankOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.UpperBound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Continuity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Extension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Extra +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Restriction +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Shared +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.StarWeights +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Uniform +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.AbsoluteTensorRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.AlgebraicExtensionRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.ArithmeticExponent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Asymptotic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Circuit +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.DualExponent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Elongated +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.ExactExponent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FiniteExtensionRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Flattening +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalBlockFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalBlockStep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalCircuit +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalLinearExpr +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalPadding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalRecursion +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalSubstitute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.MatrixMinors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.MatrixPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.PowerRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.RankCoefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.RankLimit +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.RectangularCircuitModel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Scaling +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.SquareExponent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.SquareRankModel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Tensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Additive.Catalyst +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Additive.Finite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Additive.RankAnalysis +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Additive.States +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Denominators +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Encoding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Integer +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Interval +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Rational +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Stable +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.StableGroup +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Blocks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterDegeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Growth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.GrowthRow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.MatrixRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Averages +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Character +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Compactness +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Error +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Finite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.FixedPoint +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Growth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Projective +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.States +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialCharacterBounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialFiltration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialFiltrationFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialSectorFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialSectors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.RankDescent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.RectangularRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.RestrictionInterpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationFourier +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationPolynomial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationWeights +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagEntropy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagFiberBounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagHeterogeneous +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagOptimized +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagPolynomialBranches +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagTensorWords +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagWords +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPermutationPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClass +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassCharacter +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDirectSum +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPermutations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRankOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassSemiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.WeightedPolynomials diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/AdjacentDuplicates.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/AdjacentDuplicates.lean new file mode 100644 index 0000000000..0b49c159a7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/AdjacentDuplicates.lean @@ -0,0 +1,112 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FunctionNetwork + +/-! +# Testing a sorted list for duplicates + +Each internal node checks the boundary between its two sublists. Even +copying the input at every level costs only a logarithmic factor. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {a : Wire} + +theorem wd_tree (w : ℕ) (a : Wire) : wd (tree w a) = 2 ^ w * wd a := by + induction w with + | zero => simp [tree] + | succ w ih => + change wd (tree w a) + wd (tree w a) = _ + rw [ih, pow_succ] + ring + +/-- Selects the leftmost or rightmost leaf of a binary input tree. -/ +def edge (right : Bool) : (w : ℕ) → Val (tree w a) → Val a + | 0, x => x + | w + 1, x => edge right w (if right then x.2 else x.1) + +private theorem edge_net (F : Type) [Field F] (right : Bool) (w : ℕ) : + DNet F (tree w a) a (edge right w) (2 * wd (tree w a)) := by + induction w with + | zero => exact (DNet.id F a).mono (by change wd a ≤ 2 * wd a; omega) + | succ w ih => + have h : DNet F (tree (w + 1) a) (tree w a) + (fun x => if right then x.2 else x.1) (wd (tree (w + 1) a)) := by + cases right + · exact DNet.fst F _ _ + · exact DNet.snd F _ _ + apply (h.comp ih).mono + change _ + 2 * wd (tree w a) ≤ 2 * (wd (tree w a) + wd (tree w a)) + simp only [wd] + omega + +variable [LinearOrder (Val a)] + +private theorem edges (w : ℕ) (x : Val (tree w a)) + (hs : (flatten w x).Pairwise (· ≤ ·)) : + edge false w x ∈ flatten w x ∧ edge true w x ∈ flatten w x ∧ + ∀ z ∈ flatten w x, edge false w x ≤ z ∧ z ≤ edge true w x := by + induction w with + | zero => simp [edge, flatten] + | succ w ih => + obtain ⟨hl, hr, hcross⟩ := List.pairwise_append.mp hs + obtain ⟨hmin, _, hb⟩ := ih x.1 hl + obtain ⟨_, hmax, hc⟩ := ih x.2 hr + refine ⟨List.mem_append_left _ hmin, List.mem_append_right _ hmax, ?_⟩ + intro z hz + rcases List.mem_append.mp hz with hz | hz + · exact ⟨(hb z hz).1, hcross _ hz _ hmax⟩ + · exact ⟨hcross _ hmin _ hz, (hc z hz).2⟩ + +/-- Tests strict increase between consecutive leaves in the left-to-right order. -/ +def adjacent : (w : ℕ) → Val (tree w a) → Bool + | 0, _ => true + | w + 1, x => (adjacent w x.1 && adjacent w x.2) && + decide (edge true w x.1 < edge false w x.2) + +theorem adjacent_iff (w : ℕ) (x : Val (tree w a)) + (hs : (flatten w x).Pairwise (· ≤ ·)) : + adjacent w x = true ↔ (flatten w x).Nodup := by + induction w with + | zero => simp [adjacent, flatten] + | succ w ih => + obtain ⟨hl, hr, hcross⟩ := List.pairwise_append.mp hs + obtain ⟨_, hmax, hb⟩ := edges w x.1 hl + obtain ⟨hmin, _, hc⟩ := edges w x.2 hr + rw [adjacent, Bool.and_eq_true, Bool.and_eq_true, decide_eq_true_eq, ih _ hl, ih _ hr, + flatten, List.nodup_append, and_assoc] + apply and_congr_right' + apply and_congr_right' + constructor + · intro h z hz y hy + exact ne_of_lt (((hb z hz).2.trans_lt h).trans_le (hc y hy).1) + · intro h + exact lt_of_le_of_ne (hcross _ hmax _ hmin) (h _ hmax _ hmin) + +theorem adjacent_net {F : Type} [Field F] {k : ℕ} + (h : DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) k) (w : ℕ) : + DNet F (tree w a) .bit (adjacent w) (2 ^ w * (w + 1) * (8 * wd a + k + 4)) := by + induction w with + | zero => + apply ((DNet.discard F a).comp (DNet.table F .unit .bit (fun _ => true) (by decide))).mono + simp + omega + | succ w ih => + let gate := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 && x.2) (by decide) + have children := (ih.par ih).comp gate + have boundary := ((edge_net (a := a) F true w).par (edge_net F false w)).comp h + apply ((children.pair boundary).comp gate).mono + simp only [wd, wd_tree, pow_succ] + have hp : 1 ≤ 2 ^ w := Nat.one_le_pow _ _ (by decide) + nlinarith [Nat.mul_le_mul_right k hp] + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/AppendAddress.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/AppendAddress.lean new file mode 100644 index 0000000000..9f9fa5ef31 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/AppendAddress.lean @@ -0,0 +1,968 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Add +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Shift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.FieldLift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Packets + +/-! # An exact binary reduction with one additional carry bit per level -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Finset + +/-- The total of type `B (k + h)` for the given inputs. -/ +def total (h k : ℕ) (x : B h → B k) : B (k + h) := + ⟨∑ i, (x i).val, by + have H := sum_lt_sum_of_nonempty (s := univ) univ_nonempty (fun i _ => (x i).isLt) + simpa [pow_add, mul_comm] using H⟩ + +private def plus (k : ℕ) (x : B k × B k) : B (k + 1) := + ⟨x.1.val + x.2.val, by have := x.1.isLt; have := x.2.isLt; rw [pow_succ]; omega⟩ + +variable (F : Type) [Field F] + +private theorem plus_net (k : ℕ) : + Circuit F (.pair (.addr k) (.addr k)) (.addr (k + 1)) (plus k) (20000 * (k + 2)) := by + have t := numeric_extend F k + have s := (t.par t).comp (numeric_add F (k + 1)) + convert s.mono (n := 20000 * (k + 2)) (by omega) using 1 + funext x + apply Fin.ext + exact (Nat.mod_eq_of_lt (plus k x).isLt).symm + +private def pairs (h k : ℕ) (x : B (h + 1) → B k) (i : B h) := + (x (halves h (.inl i)), x (halves h (.inr i))) + +private theorem total_net (h k n : ℕ) (hn : n = k + h) : + ∃ f : (B h → B k) → B n, + Circuit F (.vec h (.addr k)) (.addr n) f (2 ^ h * 50000 * (k + 3)) ∧ + ∀ x, (f x).val = ∑ i, (x i).val := by + induction h generalizing k with + | zero => + simp only [add_zero] at hn + subst n + have t := Circuit.project (F := F) (A := .vec 0 (.addr k)) (D := .addr k) + (f := fun x => x 0) (fun i => (0, i)) (fun _ _ => rfl) + refine ⟨_, t.mono (by simp; omega), fun x => ?_⟩ + exact (Fin.sum_univ_one (fun i => (x i).val)).symm + | succ h ih => + obtain ⟨f, hf, he⟩ := ih (k + 1) (by omega) + have t := Circuit.project (F := F) (A := .vec (h + 1) (.addr k)) + (D := .vec h (.pair (.addr k) (.addr k))) (f := pairs h k) + (fun p => p.2.elim (fun j => (halves h (.inl p.1), j)) (fun j => (halves h (.inr p.1), j))) + (by rintro x ⟨i, j|j⟩ <;> rfl) + have s := Circuit.map (A := .pair (.addr k) (.addr k)) (D := .addr (k + 1)) + (fun _ : B h => plus k) (fun _ => plus_net F k) + refine ⟨_, ((t.comp s).comp hf).mono ?_, fun x => ?_⟩ + · simp only [Format.width_vec, Format.width_pair, Format.width_addr, pow_succ] + ring_nf + omega + · simp only [Function.comp_apply, he, pairs, plus, sum_add_distrib] + rw [← (halves h).sum_comp (fun i => (x i).val), Fintype.sum_sum_type] + +/-- The cost grows linearly with the number of entries for fixed input width. -/ +theorem cheap_total (h k : ℕ) : + Cheap F h k (.vec h (.addr k)) (.addr (k + h)) (total h k) 5 := by + obtain ⟨f, hf, he⟩ := total_net F h k (k + h) rfl + have eq : f = total h k := funext fun x => Fin.ext (he x) + rw [eq] at hf + refine ⟨_, hf, ?_⟩ + simp only [Format.width_vec, Format.width_addr] + have hpow : h < 2 ^ h := Nat.lt_pow_self (by decide) + have hk : k ≤ 2 ^ h * k := Nat.le_mul_of_pos_left _ (by positivity) + ring_nf at hk ⊢ + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Electing a common choice from local scores + +Rows have short scores even when the number of rows is large. +Accumulate each column along a carry tree before comparing the totals. +Sort with a deterministic tie break by candidate number. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Finset + +variable {h k d : ℕ} + +open scoped Classical in +/-- The indexed operation `permutation x (fun _ => true) i`. -/ +def rankAt (i : B k) (x : B k → B d) := permutation x (fun _ => true) i + +open scoped Classical in +theorem rankAt_le (x : B k → B d) (i j : B k) (hij : i ≤ j) : + x (rankAt i x) ≤ x (rankAt j x) := by + have he := Tuple.monotone_sort (fun j => toLex (false, toLex (x j, j))) hij + change toLex (false, toLex (x (rankAt i x), rankAt i x)) ≤ + toLex (false, toLex (x (rankAt j x), rankAt j x)) at he + rw [Prod.Lex.toLex_le_toLex] at he + rcases he with hh | ⟨_, hh⟩ + · exact (lt_irrefl _ hh).elim + · rw [Prod.Lex.toLex_le_toLex] at hh + exact hh.elim (fun h => h.le) (fun h => h.1.le) + +open scoped Classical in +/-- The indexed operation `rankAt i (fun j => total h d (x j))`. -/ +def elect (i : B k) (x : B k → B h → B d) := rankAt i (fun j => total h d (x j)) + +open scoped Classical in +theorem elect_min (x : B k → B h → B d) (j : B k) : + (∑ v, (x (elect ⊥ x) v).val) ≤ ∑ v, (x j v).val := by + let y i := total h d (x i) + have hx := rankAt_le y _ ((permutation y (fun _ => true)).symm j) bot_le + rw [show rankAt _ y = j from (permutation y _).apply_symm_apply j] at hx + exact hx + +open scoped Classical in +theorem elect_max (x : B k → B h → B d) (j : B k) : + (∑ v, (x j v).val) ≤ ∑ v, (x (elect ⊤ x) v).val := by + let y i := total h d (x i) + have hx := rankAt_le y ((permutation y (fun _ => true)).symm j) _ le_top + rw [show rankAt _ y = j from (permutation y _).apply_symm_apply j] at hx + exact hx + +variable (F : Type) [Field F] + +open scoped Classical in +private theorem cheap_rankAt (k d : ℕ) (i : B k) : + Cheap F k (k + d) (.vec k (.addr d)) (.addr k) (rankAt i) 42 := by + have addr (m : ℕ) (hm : m ≤ k + d) : + (Format.vec k (.addr m)).width ≤ 2 ^ k * (100 + (k + d)) ^ 1 := by + simp only [Format.width_vec, Format.width_addr, pow_one] + gcongr + omega + have hv := addr d (by omega) + have hf : (Format.vec k .bit).width ≤ 2 ^ k * (100 + (k + d)) ^ 1 := by + rw [Format.width_vec, Format.width_bit, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have ho : (Format.addr k).width ≤ 2 ^ k * (100 + (k + d)) ^ 1 := by + rw [Format.width_addr, pow_one] + exact le_trans (by omega : k ≤ 100 + (k + d)) (Nat.le_mul_of_pos_left _ (by positivity)) + have flags := (Cheap.id F hv).pair (Cheap.const F hv hf (fun _ => true)) + have get := Cheap.project F (A := .vec k (.addr k)) (D := .addr k) (f := fun x + => x i) (addr k (by omega)) ho (fun j => (i, j)) + (fun _ _ => rfl) + exact (flags.comp (cheap_permutation F k d)).comp get + +open scoped Classical in +/-- The polynomial in the host address length is incurred just once per +candidate. Per host and candidate the cost only depends on the score width. -/ +theorem election (h k d : ℕ) (i : B k) : + Circuit F (.vec k (.vec h (.addr d))) (.addr k) (elect i) + (2 ^ k * (2 ^ h * (100 + d) ^ 5 + (100 + (k + (d + h))) ^ 42)) := by + obtain ⟨m, hm, hm'⟩ := cheap_total F h d + obtain ⟨n, hn, hn'⟩ := cheap_rankAt F k (d + h) i + have net := Circuit.map (A := .vec h (.addr d)) (D := .addr (d + h)) (fun _ : B k => total h d) + (fun _ => hm) + refine (net.comp hn).mono ?_ + rw [mul_add] + exact Nat.add_le_add (Nat.mul_le_mul_left _ (by omega)) (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Applying a common weighted table at each occurrence + +Carry the graph once per host. A product of the local weights both +rejects invalid choices and withdraws any prescribed scalar factors. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] {I : Type*} {A D : Format} {u m d h : ℕ} {L : Set (Table F)} + +open scoped Classical in +/-- Evaluates `((x.1 i).1, fun j => ((x.1 i).2 j, x.2 i j))` at the input `i`. -/ +def Fmt.zip (x : (Fmt.rows m d h A).obj × (Format.vec m (.vec h D)).obj) : + (Fmt.rows m d h (.pair A D)).obj := fun i => ((x.1 i).1, fun j => ((x.1 i).2 j, x.2 i j)) + +open scoped Classical in +theorem map_zip (hu : 3 ≤ u) : + Map F u L (.pair (Fmt.rows m d h A) (.vec m (.vec h D))) (Fmt.rows m d h (.pair A D)) + Fmt.zip (12 * (Fmt.rows m d h (.pair A D)).width) := by + let X := Format.pair (Fmt.rows m d h A) (.vec m (.vec h D)) + let Y := Fmt.rows m d h (.pair A D) + let pin : Y.pins → X.pins + | (i, .inl j) => .inl (i, .inl j) + | (i, .inr (j, .inl k)) => .inl (i, .inr (j, k)) + | (i, .inr (j, .inr k)) => .inr (i, j, k) + have hp : Circuit F X Y Fmt.zip (X.width + 2 * Y.width) := + Circuit.project pin (by rintro x ⟨i, j|⟨j, k|k⟩⟩ <;> rfl) + have hw : X.width = Y.width := by simp [X, Y, Fmt.rows, mul_add, add_assoc] + exact (Map.circuit hu hp).mono (by change _ ≤ 12 * Y.width; omega) + +variable (f : A.obj → D.obj) (g : A.obj → F) + +open scoped Classical in +/-- Evaluates `((x i).1, fun j => f ((x i).2 j))` at the input `i`. -/ +def Fmt.update (x : (Fmt.rows m d h A).obj) : (Fmt.rows m d h D).obj := + fun i => ((x i).1, fun j => f ((x i).2 j)) + +open scoped Classical in +/-- The value specified by `∏ i, ∏ j, g ((x i).2 j)`. -/ +def Fmt.weight (x : (Fmt.rows m d h A).obj) := ∏ i, ∏ j, g ((x i).2 j) + +open scoped Classical in +/-- The quantity computed by `2 ^ m * (4 * (2 ^ d * m) + 2 ^ h * (1 + A.width + D.width))`. -/ +def updateCost (m d h : ℕ) (A D : Format) := 2 ^ m * (4 * (2 ^ d * m) + 2 ^ h * (1 + A.width + + D.width)) + +open scoped Classical in +/-- The value specified by `lookup F A D (fun x y => if f x = y then g x else 0)`. -/ +def weightTable := lookup F A D (fun x y => if f x = y then g x else 0) + +open scoped Classical in +theorem update (hu : 3 ≤ u) (hw : A.width + D.width ≤ u) (hg : weightTable f g ∈ L) : + Action F u L (Fmt.rows m d h A) (Fmt.rows m d h D) (Fmt.update f) (Fmt.weight g) + (updateCost m d h A D) := by + have hk : Action F u L A D f g (1 + A.width + D.width) := Kernel.lookup hw hg + let P := Format.vec d (.addr m) + have hP := Action.of_map (Map.circuit (L := L) hu (Circuit.id F P)) + have hb := Action.vec _ _ (fun _ : B h => hk) + have hr := Action.vec _ _ (fun _ : B m => hP.par hb) + have hp : P.width = 2 ^ d * m := by simp [P] + simp only [one_mul, hp] at hr + exact hr + +open scoped Classical in +theorem computes_update (hu : 3 ≤ u) (hw : A.width + D.width ≤ u) (hg : weightTable f g ∈ L) + (x : I → (Fmt.rows m d h A).obj) : + Computes F u L (Fmt.rows m d h A) (Fmt.rows m d h D) x + (Fmt.update f ∘ x) (Fmt.weight g ∘ x) (updateCost m d h A D) := + Computes.of_action (update f g hu hw hg) (fun _ => rfl) (fun _ => rfl) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Computing a layout from the selected profile tags + +Each row presents an activity bit and a short selector. Inactive rows +contribute zero. The comparison is global, but the cost per row depends +only on the size of the profile dictionary. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Side + +open Coloring Finset + +open scoped Classical in +/-- Computes the entry by the application `Format.pair .bit (.addr a)`. -/ +abbrev Entry (a : ℕ) := Format.pair .bit (.addr a) +open scoped Classical in +/-- Computes the input by the application `Format.vec n (Entry a)`. -/ +abbrev Input (n a : ℕ) := Format.vec n (Entry a) + +variable {a n t : ℕ} (profile : B a → Fin 8 → ℕ) + +open scoped Classical in +/-- Returns `Packing.profileScore col (profile q.2)` when `q.1` holds, and `0` otherwise. -/ +def value (col : Bool) (q : (Entry a).obj) := + if q.1 then Packing.profileScore col (profile q.2) else 0 + +open scoped Classical in +/-- Tests whether `(∑ i, value profile true (x i)) < ∑ i, value profile false (x i)` holds. -/ +def pick (x : (Input n a).obj) : Bool := + decide ((∑ i, value profile true (x i)) < ∑ i, value profile false (x i)) + +open scoped Classical in +/-- Any order and padding of the selected profiles give the same decision. -/ +theorem pick_eq_side {I : Type} [Fintype I] (f : I → Fin 8 → ℕ) + (x : (Input n a).obj) (row : I ↪ B n) + (active : ∀ i, (x i).1 = true ↔ i ∈ Set.range row) + (code : ∀ e, profile (x (row e)).2 = f e) : + pick profile x = Packing.side f := by + have score (c : Bool) : ∑ i, value profile c (x i) = ∑ e, Packing.profileScore c (f e) := by + unfold value + rw [← sum_filter] + have rows : (univ.filter fun i => (x i).1 = true) = univ.image row := by + ext i + simp only [mem_filter_univ, active, mem_image, mem_univ, true_and, Set.mem_range] + rw [rows, sum_image row.injective.injOn] + simp only [code] + simp only [pick, Packing.side, score] + +open scoped Classical in +private theorem value_bound (hc : ∀ p, ∑ j, profile p j < 2 ^ t) + (c : Bool) (q : (Entry a).obj) : value profile c q < 2 ^ t := by + have he := Packing.score_sum (profile q.2) + have ht := hc q.2 + unfold value + split_ifs + · cases c <;> omega + · exact Nat.two_pow_pos _ + +open scoped Classical in +private theorem cheap_row (F : Type) [Field F] (ha : 2 ^ a ≤ t) (f : (Entry a).obj → B t) : + Cheap F 0 t (Entry a) (.addr t) f 3 := by + have h : Install.Depends ((Format.addr t).code ∘ f ∘ (Entry a).code.symm) (1 + a) := by + intro i + refine ⟨univ, ?_, fun x y he => ?_⟩ + · change (Entry a).width ≤ _ + simp [Entry] + · rw [funext (fun j => he j (mem_univ _))] + refine ⟨_, h.bnet F, ?_⟩ + change (Entry a).width + (Format.addr t).width + + ((Entry a).width + Install.localCost (1 + a) * (Format.addr t).width) ≤ _ + have hat : a ≤ t := (Nat.lt_pow_self (by decide : 1 < 2)).le.trans ha + have hp : Install.localCost (1 + a) ≤ 2 * (1 + t) + 32 * t := by + unfold Install.localCost + rw [show 1 + a + 1 = a + 1 + 1 by omega, pow_succ, pow_succ] + omega + have hs := Nat.mul_le_mul_right t hp + simp only [Entry, Format.width_pair, Format.width_addr, pow_zero, one_mul] + rw [Format.width_bit] + ring_nf at hs ⊢ + omega + +open scoped Classical in +private theorem cheap_lt (F : Type) [Field F] (n t : ℕ) : + Cheap F n t (.pair (.addr (t + n)) (.addr (t + n))) .bit (fun x => decide (x.1 < x.2)) 4 := by + refine ⟨_, numeric_lt F _, ?_⟩ + simp only [Format.width_pair, Format.width_addr] + have hn := Nat.lt_pow_self (n := n) (by decide : 1 < 2) + have ht := Nat.le_mul_of_pos_left t (Nat.two_pow_pos n) + rw [Format.width_bit] + ring_nf at ht ⊢ + omega + +open scoped Classical in +theorem cheap_pick (F : Type) [Field F] (n t : ℕ) (ha : 2 ^ a ≤ t) + (hc : ∀ p, ∑ j, profile p j < 2 ^ t) : + Cheap F n t (Input n a) .bit (pick profile) 8 := by + let score c q : B t := ⟨value profile c q, value_bound profile hc c q⟩ + have sum (c : Bool) : Cheap F n t (Input n a) (.addr (t + n)) + (fun x => total n t (fun i => score c (x i))) 6 := + (Cheap.map (A := Entry a) (D := .addr t) (h := n) (fun _ => score c) + (fun _ => cheap_row F ha (score c))).comp (cheap_total F n t) + exact ((sum true).pair (sum false)).comp (cheap_lt F n t) + +open scoped Classical in +theorem map_pick (F : Type) [Field F] {u : ℕ} (hu : 3 ≤ u) (L : Set (Table F)) + (n t : ℕ) (ha : 2 ^ a ≤ t) (hc : ∀ p, ∑ j, profile p j < 2 ^ t) : + Map F u L (Input n a) .bit (pick profile) (4 * (2 ^ n * (100 + t) ^ 8)) := by + obtain ⟨m, hm, hbound⟩ := cheap_pick profile F n t ha hc + exact (Map.circuit hu hm).mono (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Side +end + +/- +# Computing the global layout from short local records + +At each host, pair the mask with one selector per row. Inactive +positions can contain arbitrary data and are normalized to zero. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Side + +open Coloring + +/-- The quantity computed by `Format.pair (Match.Input d h e k ℓ) (.vec (h + e) (.addr a))`. -/ +abbrev Tagged (d h e k ℓ a : ℕ) := Format.pair (Match.Input d h e k ℓ) (.vec (h + e) (.addr a)) + +variable {m d h e k ℓ n a t : ℕ} + +/-- The value specified by `(x.1, if x.1 then x.2 else 0)`. -/ +def clean (x : (Entry a).obj) : (Entry a).obj := (x.1, if x.1 then x.2 else 0) + +/-- Evaluates `clean ((Match.rows x.1).control.1 i, x.2 i)` at the input `i`. -/ +def collect (x : (Tagged d h e k ℓ a).obj) : (Input (h + e) a).obj := + fun i => clean ((Match.rows x.1).control.1 i, x.2 i) + +/-- Evaluates `collect (x (Match.rowIndex m (h + e) i).1) (Match.rowIndex m (h + e) i).2` at the +input `i`. -/ +def extract (x : B m → (Tagged d h e k ℓ a).obj) : (Input (m + (h + e)) a).obj := + fun i => collect (x (Match.rowIndex m (h + e) i).1) (Match.rowIndex m (h + e) i).2 + +variable (F : Type) [Field F] + +private theorem cheap_clean (ha : a ≤ t) : Cheap F 0 t (Entry a) (Entry a) clean 10 := by + have hw : (Entry a).width ≤ 2 ^ 0 * (100 + t) ^ 1 := by + rw [Format.width_pair, Format.width_bit, Format.width_addr] + simp only [pow_zero, one_mul, pow_one]; omega + have hv : (Format.addr a).width ≤ 2 ^ 0 * (100 + t) ^ 1 := by + rw [Format.width_addr]; simp only [pow_zero, one_mul, pow_one]; omega + have x := Cheap.id F hw + have z := Cheap.const F hw hv (0 : B a) + have y := ((x.snd.pair z).pair x.fst).comp ((cheap_select F a).widen ha) + exact (x.fst.pair y).mono (by decide) + +private theorem cheap_tag {A D V : Format} {f : A.obj → D.obj} {c : ℕ} + (hf : Cheap F n t A D f c) (hv : V.width ≤ 2 ^ n * (100 + t)) : + Cheap F n t (.pair A V) (.pair D V) (fun x => (f x.1, x.2)) (c + 2) := by + obtain ⟨p, hp, hb⟩ := hf.mono (d := c + 1) (by omega) + have hh : V.width ≤ 2 ^ n * (100 + t) ^ (c + 1) := by + apply hv.trans + rw [pow_succ] + exact Nat.mul_le_mul_left _ (Nat.le_mul_of_pos_left _ (by positivity)) + refine ⟨_, hp.par (Circuit.id F V), ?_⟩ + rw [Format.width_pair, Format.width_pair] + have ht : 4 * (2 ^ n * (100 + t) ^ (c + 1)) ≤ 2 ^ n * (100 + t) ^ (c + 2) := by + rw [mul_comm 4, show c + 2 = (c + 1) + 1 by omega, pow_succ (100 + t) (c + 1), ← mul_assoc] + exact Nat.mul_le_mul_left _ (by omega) + omega + +theorem cheap_collect (ht : Rows.overhead (h + e) (Match.Labels h ℓ d).width ≤ t) + (hk : k ≤ t) (hd : 2 ^ d ≤ t) (ha : a ≤ t) : + Cheap F (h + e) t (Tagged d h e k ℓ a) (Input (h + e) a) collect 156 := by + have mask := (Match.cheap_match F d h e k ℓ t ht hk hd).fst + have hv : (Format.vec (h + e) (.addr a)).width ≤ 2 ^ (h + e) * (100 + t) := by + rw [Format.width_vec, Format.width_addr] + exact Nat.mul_le_mul_left _ (by omega) + have tag := (cheap_tag F mask hv).zip + exact (tag.comp (Cheap.map (A := Entry a) (D := Entry a) (h := h + e) + (fun _ => clean) (fun _ => cheap_clean F ha))).mono (by decide) + +private theorem batch {A D : Format} {f : A.obj → D.obj} {c : ℕ} + (hf : Cheap F n t A D f c) : + Cheap F (m + n) t (.vec m A) (.vec m D) (fun x i => f (x i)) c := by + obtain ⟨p, hp, hb⟩ := hf + refine ⟨_, Circuit.map _ (fun _ : B m => hp), ?_⟩ + simpa only [Format.width_vec, ← mul_add, pow_add, mul_assoc] using Nat.mul_le_mul_left (2 ^ m) hb + +private theorem flatten (A : Format) (hw : A.width ≤ 100 + t) : + Cheap F (m + n) t (.vec m (.vec n A)) (.vec (m + n) A) + (fun x i => x (Match.rowIndex m n i).1 (Match.rowIndex m n i).2) 2 := by + have hb : (Format.vec (m + n) A).width ≤ 2 ^ (m + n) * (100 + t) ^ 1 := by + rw [Format.width_vec, pow_one] + exact Nat.mul_le_mul_left _ hw + have he : (Format.vec m (.vec n A)).width = (Format.vec (m + n) A).width := by + simp only [Format.width_vec, pow_add, mul_assoc] + exact Cheap.project F (he.le.trans hb) hb + (fun i => ((Match.rowIndex m n i.1).1, (Match.rowIndex m n i.1).2, i.2)) (fun _ _ => rfl) + +theorem cheap_extract (ht : Rows.overhead (h + e) (Match.Labels h ℓ d).width ≤ t) + (hk : k ≤ t) (hd : 2 ^ d ≤ t) (ha : a ≤ t) : + Cheap F (m + (h + e)) t (.vec m (Tagged d h e k ℓ a)) (Input (m + (h + e)) a) extract 157 := by + have hw : (Entry a).width ≤ 100 + t := by + rw [Format.width_pair, Format.width_bit, Format.width_addr] + omega + exact ((batch F (m := m) (cheap_collect F ht hk hd ha)).comp + (flatten F (Entry a) (m := m) (n := h + e) hw)).mono (by decide) + +theorem map_layout {u : ℕ} (hu : 3 ≤ u) (L : Set (Table F)) (profile : B a → Fin 8 → ℕ) + (ht : Rows.overhead (h + e) (Match.Labels h ℓ d).width ≤ t) + (hk : k ≤ t) (hd : 2 ^ d ≤ t) (ha : 2 ^ a ≤ t) (hc : ∀ p, ∑ j, profile p j < 2 ^ t) : + Map F u L (.vec m (Tagged d h e k ℓ a)) .bit (pick profile ∘ extract) + (4 * (2 ^ (m + (h + e)) * (100 + t) ^ 158)) := by + have hat : a ≤ t := (Nat.lt_pow_self (by decide : 1 < 2)).le.trans ha + obtain ⟨s, hs, hb⟩ := (cheap_extract F (m := m) ht hk hd hat).comp + (cheap_pick profile F _ t ha hc) + exact (Map.circuit hu hs).mono (Nat.mul_le_mul_left 4 ((Nat.le_add_left _ _).trans hb)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Side +end + +section +/- # Selecting one marked stub at each block -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +open Coloring +variable {h e t : ℕ} + +/-- The indexed operation `permutation (fun _ => (0 : B 0)) x`. -/ +abbrev orderMask (x : B e → Bool) := permutation (fun _ => (0 : B 0)) x + +/-- Computes the pick by the application `orderMask x 0`. -/ +def pick (x : B e → Bool) := orderMask x 0 + +theorem pick_marked (x : B e → Bool) (h : ∃ i, x i = true) : x (pick x) = true := by + obtain ⟨i, hi⟩ := h + let σ := orderMask x + have he := Tuple.monotone_sort (fun j => toLex (!x j, toLex ((0 : B 0), j))) + (show 0 ≤ σ.symm i from bot_le) + change toLex (!x (σ 0), toLex ((0 : B 0), σ 0)) ≤ + toLex (!x (σ (σ.symm i)), toLex ((0 : B 0), σ (σ.symm i))) at he + rw [Equiv.apply_symm_apply, hi, Prod.Lex.toLex_le_toLex] at he + change x (σ 0) = true + rcases Bool.dichotomy (x (σ 0)) with h | h + · have hl : true < false := by simpa [h] using he + exact ((by decide : ¬ (true < false)) hl).elim + · exact h + +variable (F : Type) [Field F] + +private theorem bit_width (h t : ℕ) : (Format.vec h .bit).width ≤ 2 ^ h * (100 + t) ^ 1 := by + rw [Format.width_vec, Format.width_bit, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + +private theorem cheap_orderMask (he : e ≤ t) : + Cheap F e t (.vec e .bit) (Perm e) (fun x => ⇑(orderMask x)) 42 := by + have hw := bit_width e t + have hk := column_width e (Nat.zero_le t) + have flags := (Cheap.const F hw hk (fun _ => 0)).pair (Cheap.id F hw) + exact (flags.comp ((cheap_permutation F e 0).widen he)).mono (by decide) + +private theorem cheap_pick (he : e ≤ t) (A : Format) (ha : A.width ≤ t) : + Cheap F e t (.pair (.vec e .bit) (.vec e A)) A (fun x => x.2 (pick x.1)) 47 := by + have hv : (Format.vec e A).width ≤ 2 ^ e * (100 + t) ^ 1 := by + rw [Format.width_vec, pow_one]; exact Nat.mul_le_mul_left _ (by omega) + have hw : (Format.pair (.vec e .bit) (.vec e A)).width ≤ 2 ^ e * (100 + t) ^ 1 := by + rw [Format.width_pair, Format.width_vec, Format.width_bit, Format.width_vec, ← mul_add, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have h₀ : A.width ≤ 2 ^ e * (100 + t) ^ 1 := by + rw [Format.width_vec] at hv + exact (Nat.le_mul_of_pos_left _ (by positivity)).trans hv + have head : Cheap F e t (.vec e A) A (fun x => x 0) 2 := + Cheap.project F hv h₀ (fun i => (0, i)) (fun _ _ => rfl) + have x := Cheap.id F hw + have gather := (x.snd.pair (x.fst.comp (cheap_orderMask F he))).comp (Cheap.lookup F e t A he ha) + exact (gather.comp head).mono (by decide) + +private theorem copies {A D : Format} {f : A.obj → D.obj} {n : ℕ} + (hf : Cheap F e t A D f n) (h : ℕ) : + Cheap F (h + e) t (.vec h A) (.vec h D) (fun x i => f (x i)) n := by + obtain ⟨m, hm, hb⟩ := hf + refine ⟨_, Circuit.map (fun _ => f) (fun _ => hm), ?_⟩ + simpa only [Format.width_vec, ← mul_add, pow_add, mul_assoc] using Nat.mul_le_mul_left (2 ^ h) hb + +/-- The indexed operation `(rowIndex h e).symm (i, pick (fun j => x ((rowIndex h e).symm (i, +j))))`. -/ +noncomputable def sampleRow (x : B (h + e) → Bool) (i : B h) := + (rowIndex h e).symm (i, pick (fun j => x ((rowIndex h e).symm (i, j)))) + +theorem sampleRow_block (x : B (h + e) → Bool) (i : B h) : (rowIndex h e (sampleRow x i)).1 = i + := by + simp [sampleRow] + +theorem sampleRow_marked (x : B (h + e) → Bool) {i : B (h + e)} (hi : x i = true) : + x (sampleRow x (rowIndex h e i).1) = true := by + unfold sampleRow + apply pick_marked (fun j => x ((rowIndex h e).symm ((rowIndex h e i).1, j))) + exact ⟨(rowIndex h e i).2, by simpa using hi⟩ + +theorem cheap_sample (he : e ≤ t) (A : Format) (ha : A.width ≤ t) : + Cheap F (h + e) t (.pair (.vec (h + e) .bit) (.vec (h + e) A)) (.vec h A) + (fun x i => x.2 (sampleRow x.1 i)) 48 := by + let L := Format.pair (.vec (h + e) .bit) (.vec (h + e) A) + let R := Format.vec h (.pair (.vec e .bit) (.vec e A)) + have hl : L.width ≤ 2 ^ (h + e) * (100 + t) ^ 1 := by + unfold L + rw [Format.width_pair, Format.width_vec, Format.width_vec, Format.width_bit, ← mul_add, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have hr : R.width ≤ 2 ^ (h + e) * (100 + t) ^ 1 := by + refine le_trans ?_ hl + simp only [L, R, Format.width_vec, Format.width_pair, pow_add, mul_add, mul_assoc] + exact le_rfl + have prep : Cheap F (h + e) t L R (fun x i => + (fun j => x.1 ((rowIndex h e).symm (i, j)), fun j => x.2 ((rowIndex h e).symm (i, j)))) 2 + := by + apply Cheap.project F hl hr (fun p => Sum.elim + (fun q => .inl ((rowIndex h e).symm (p.1, q.1), q.2)) + (fun q => .inr ((rowIndex h e).symm (p.1, q.1), q.2)) p.2) + rintro x ⟨i, j|j⟩ <;> rfl + exact (prep.comp (copies F (cheap_pick F he A ha) h)).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +section +/- # Concatenating the high and low parts of a row address -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match + +open Coloring Control Transcript.Messages + +private theorem append_value (a b : ℕ) (x : Val (word a)) (y : Val (word b)) : + Lookup.value (a + b) (appendWord a b y x) = Lookup.value b y + 2 ^ b * Lookup.value a x := by + induction b with + | zero => simp [appendWord, Lookup.value] + | succ b ih => + change y.1.toNat + 2 * Lookup.value (a + b) (appendWord a b y.2 x) = + y.1.toNat + 2 * Lookup.value b y.2 + 2 ^ (b + 1) * Lookup.value a x + rw [ih] + ring + +private theorem append_wire (a b : ℕ) : + Rewire (.pair (word b) (word a)) (word (a + b)) (fun x => appendWord a b x.1 x.2) := by + induction b with + | zero => exact (Rewire.swap _ _).comp (.unit _) + | succ b ih => exact (Rewire.assoc _ _ _).comp ((Rewire.id .bit).par ih) + +theorem append_address (F : Type) [Field F] (a b : ℕ) : + Circuit F (.pair (.addr a) (.addr b)) (.addr (a + b)) (rowIndex a b).symm (a + b) := by + have h := (DNet.id F (word (a + b))).pre ((Rewire.swap _ _).comp (append_wire a b)) + rw [wd_word] at h + refine Circuit.of_dnet (.refl _) (.refl _) h (fun x => ?_) + simp only [Equiv.coe_refl, Function.comp_id] + have he : (Format.pair (.addr a) (.addr b)).code.symm (bits (.pair (word a) (word b)) x) = + (index a x.1, index b x.2) := Prod.ext (decode_addr a x.1) (decode_addr b x.2) + rw [he, ← code_addr] + congr 1 + exact Fin.ext (append_value a b x.1 x.2) + +/-- Each bit of the concatenation is a fixed bit of one input address. -/ +theorem append_pin (a b : ℕ) (i : slots (word (a + b))) : + ∃ k : slots (word a) ⊕ slots (word b), ∀ x y, + (Format.addr (a + b)).code ((rowIndex a b).symm (x, y)) i = + Sum.elim ((Format.addr a).code x) ((Format.addr b).code y) k := by + obtain ⟨e, he⟩ := ((Rewire.swap _ _).comp (append_wire a b)).reindex_exists + refine ⟨e i, fun x y => ?_⟩ + obtain ⟨r, rfl⟩ := (index a).surjective x + obtain ⟨s, rfl⟩ := (index b).surjective y + have hp : index (a + b) (appendWord a b s r) = (rowIndex a b).symm (index a r, index b s) := + Fin.ext (append_value a b r s) + rw [← hp, code_addr, code_addr, code_addr, + show appendWord a b s r = reindex e (r, s) from congrFun he (r, s), bits_reindex] + cases e i <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +/- +# Simultaneous expansion of host neighborhoods + +For one fixed walk use one batched indirect read per step. Add the +costs before estimating the degree, so the exponent of the overhead +is independent of the walk length. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +open Coloring + +variable (F : Type) [Field F] {m d q t : ℕ} + +theorem width (hm : m ≤ t) (hd : 2 ^ d ≤ t) : + (Rows m d).width ≤ 2 ^ m * (100 + t) ^ 2 := by + simp only [Rows, Format.width_vec, Format.width_addr] + apply Nat.mul_le_mul_left + nlinarith only [Nat.mul_le_mul hd hm] + +private theorem perm_width (hm : m ≤ t) : + (Perm m).width ≤ 2 ^ m * (100 + t) ^ 2 := by + simp only [Perm, Format.width_vec, Format.width_addr] + apply Nat.mul_le_mul_left + nlinarith + +theorem column (hm : m ≤ t) (hd : 2 ^ d ≤ t) (i : B d) : + Cheap F m t (Rows m d) (Perm m) (fun g x => g x i) 3 := by + exact Cheap.project F (width hm hd) (perm_width hm) (fun z => (z.1, i, z.2)) fun _ _ => rfl + +private theorem walk_cost (hm : m ≤ t) (hd : 2 ^ d ≤ t) (r : ℕ) (hr : r ≤ t) (w : Walk d r) : + Cheap F m t (Rows m d) (Perm m) (fun g => run g r w) 10 := by + let c := 2 ^ m * (100 + t) ^ 8 + have col (i : B d) : Cheap F m t (Rows m d) (Perm m) (fun g x => g x i) 8 := + (column F hm hd i).mono (by decide) + obtain ⟨_, _, hc⟩ := col 0 + have hw : (Rows m d).width + (Perm m).width ≤ c := by unfold c; omega + have bound {A D : Format} {f : A.obj → D.obj} (k : Cheap F m t A D f 8) : + Circuit F A D f c := by + obtain ⟨_, hk, hc⟩ := k + exact hk.mono (by unfold c; omega) + have get := bound (Cheap.lookup F m t (.addr m) hm (by simpa)) + have aux (a : ℕ) (l : Walk d a) : + Circuit F (Rows m d) (Perm m) (fun g => run g a l) ((1 + 7 * a) * c) := by + induction a with + | zero => + rw [Nat.mul_zero, Nat.add_zero, Nat.one_mul] + exact bound ((Cheap.const F (width hm hd) (perm_width hm) id).mono (by decide)) + | succ a ih => + obtain ⟨_|i, l⟩ := l + · exact (ih l).mono (by gcongr; omega) + · refine (((ih l).pair (bound (col i))).comp get).mono ?_ + rw [show (1 + 7 * (a + 1)) * c = (1 + 7 * a) * c + 7 * c by ring] + omega + refine ⟨_, aux r w, ?_⟩ + calc + _ ≤ c + (1 + 7 * r) * c := Nat.add_le_add_right hw _ + _ = c * (2 + 7 * r) := by ring + _ ≤ c * (100 + t) ^ 2 := Nat.mul_le_mul_left _ (by nlinarith) + _ = _ := by unfold c; rw [mul_assoc, ← pow_add] + +private theorem dedup_cheap (ht : q + m ≤ t) (hq : 2 ^ q ≤ t) (x : B m) : + Cheap F 0 t (Column q m) (Column q m) (dedup x) 120 := by + have hm : m ≤ t := by omega + have hj : q ≤ t := by omega + have a := column_width q hm + have b := column_width q hj + have first := (cheap_first F q m).widen ht + have mask := (first.pair (Cheap.const F a b id)).zip.comp + (Cheap.map _ (fun _ => cheap_eq F hj)) + have pair := ((Cheap.id F a).pair (Cheap.const F a a (fun _ => x))).zip + have pick := (pair.pair mask).zip.comp (Cheap.map _ (fun _ => (cheap_select F m).widen hm)) + have h : Cheap F q t (Column q m) (Column q m) (dedup x) 119 := by + convert pick.mono (d := 119) (by decide) using 1 + funext a i + simp [dedup] + obtain ⟨s, hs, hc⟩ := h + refine ⟨s, hs, hc.trans ?_⟩ + rw [pow_zero, one_mul, show (100 + t) ^ 120 = (100 + t) * (100 + t) ^ 119 from pow_succ' _ _] + exact Nat.mul_le_mul_right _ (by omega) + +theorem cheap_walks (m d r : ℕ) (hr : 0 < r) : + Cheap F m (m + 2 ^ ((d + 1) * r)) (Rows m d) (Rows m ((d + 1) * r)) (walks r) 20 := by + let q := (d + 1) * r + let t := m + 2 ^ q + have hm : m ≤ t := Nat.le_add_right _ _ + have hq : 2 ^ q ≤ t := Nat.le_add_left _ _ + have hd : 2 ^ d ≤ t := (Nat.pow_le_pow_right (by decide) (show d ≤ q from + (Nat.le_succ d).trans (Nat.le_mul_of_pos_right _ hr))).trans hq + have ht : q + m ≤ t := by have := Nat.lt_pow_self (n := q) (by decide : 1 < 2); omega + have hr' : r ≤ t := (Nat.le_mul_of_pos_left r (by omega : 0 < d + 1)).trans (by omega) + have all := Cheap.share _ (fun i => walk_cost F hm hd r hr' (path d r i)) hq + have a : (Format.vec q (Perm m)).width ≤ 2 ^ m * (100 + t) ^ 2 := by + simpa only [Rows, Perm, Format.width_vec, mul_left_comm (2 ^ q)] using width hm hq + have transpose : Cheap F m t (.vec q (Perm m)) (Rows m q) (fun g i j => g j i) 3 := + Cheap.project F a (width hm hq) (fun z => (z.2.1, z.1, z.2.2)) fun _ _ => rfl + exact (all.comp transpose).mono (by decide) + +theorem cheap (m d r : ℕ) (hr : 0 < r) : + Cheap F m (m + 2 ^ ((d + 1) * r)) (Rows m d) (Rows m ((d + 1) * r)) (expand r) 200 := by + let q := (d + 1) * r + let t := m + 2 ^ q + have hq : 2 ^ q ≤ t := Nat.le_add_left _ _ + have ht : q + m ≤ t := by have := Nat.lt_pow_self (n := q) (by decide : 1 < 2); omega + exact ((cheap_walks F m d r hr).comp (Cheap.map _ (dedup_cheap F ht hq))).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +end + +/- +# Neighborhood expansion without replicating long names at each block +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] {I : Type*} {A : Format} {u m d h v n : ℕ} + {L : Set (Table F)} (r : ℕ) + +local notation "q" => ((d + 1) * r) +local notation "Data" => (Format.vec h A) +local notation "Old" => (Fmt.rows m d h A) +local notation "New" => (Fmt.rows m d h (Format.vec q A)) +local notation "Names" => (Neighborhood.Rows m d) +local notation "Bank" => (Fmt.bank m q Data) +local notation "Views" => (Format.vec m (Format.vec q Data)) + +/-- Evaluates `((x i).1, fun b j => (x (Neighborhood.expand r (fun k => (x k).1) i j)).2 b)` at +the input `i`. -/ +def Fmt.expand (x : (Old).obj) : (New).obj := + fun i => ((x i).1, fun b j => (x (Neighborhood.expand r (fun k => (x k).1) i j)).2 b) + +private def rebank (x : (Old).obj) : (Bank).obj := + fun i => (Neighborhood.expand r (fun k => (x k).1) i, (x i).2) + +private theorem prepare (hr : 0 < r) : + Circuit F Old (.pair Names Bank) (fun x => (fun i => (x i).1, rebank r x)) + (40 * ((Old).width + 2 ^ m * (100 + (m + 2 ^ q)) ^ 200)) := by + let E := Neighborhood.Rows m q + let D := Format.vec m Data + have a : Circuit F Old Names (fun x i => (x i).1) ((Old).width + 2 * (Names).width) := + Circuit.project (fun x => (x.1, .inl x.2)) (fun _ _ => rfl) + have b : Circuit F Old D (fun x i => (x i).2) ((Old).width + 2 * D.width) := + Circuit.project (fun x => (x.1, .inr x.2)) (fun _ _ => rfl) + have zip : Circuit F (.pair E D) Bank (fun x i => (x.1 i, x.2 i)) + ((E.pair D).width + 2 * (Bank).width) := + Circuit.project (Equiv.prodSumDistrib _ _ _) (by rintro x ⟨i, j|j⟩ <;> rfl) + obtain ⟨s, hs, h⟩ := Neighborhood.cheap F m d r hr + have hX : (Old).width = (Names).width + D.width := by + simp only [Fmt.rows, D, Neighborhood.Rows, Format.width_vec, Format.width_pair, mul_add] + have hB : (Bank).width = E.width + D.width := by + simp only [Fmt.bank, E, D, Neighborhood.Rows, Format.width_vec, Format.width_pair, mul_add] + change (Names).width + E.width + s ≤ _ at h + refine (a.pair (((a.comp hs).pair b).comp zip)).mono ?_ + rw [Format.width_pair] + omega + +private def receive (x : (Format.pair Names Views).obj) : (New).obj := + fun i => (x.1 i, fun b j => x.2 i j b) + +private theorem receive_circuit : Circuit F (.pair Names Views) New (receive r) + ((Format.pair Names Views).width + 2 * (New).width) := by + let e (i : (New).pins) : (Format.pair Names Views).pins := + i.2.elim (fun j => .inl (i.1, j)) (fun j => .inr (i.1, j.2.1, j.1, j.2.2)) + exact Circuit.project e (by rintro x ⟨i, j|j⟩ <;> rfl) + +/-- The expand cost used in the `Assembly` construction. -/ +def expandCost (m d h r v n : ℕ) (A : Format) := + 200 * ((Fmt.rows m d h A).width + (Fmt.rows m d h (.vec ((d + 1) * r) A)).width + + 2 ^ m * (100 + (m + 2 ^ ((d + 1) * r))) ^ 200) + gatherCost m ((d + 1) * r) v n + +theorem computes_expand (hu : 3 ≤ u) (hr : 0 < r) (ht : Access F u L (m + q) v n) + (hv : (Data).width ≤ v) (X : I → (Old).obj) (hx : ∀ i, Fmt.Reciprocal Data (X i)) : + Computes F u L Old New X (fun i => Fmt.expand r (X i)) (fun _ => 1) + (expandCost m d h r v n A) := by + have pre := Computes.of_map (L := L) (x := X) (Map.circuit hu + (prepare (F := F) (m := m) (d := d) (h := h) (A := A) r hr)) (fun _ => rfl) + have hget := gather_neighbors (L := L) Data hu ht hv (fun i => rebank r (X i)) + (fun i => Neighborhood.reciprocal (hx i) r (fun j => (X i j).2)) + have keep := Computes.of_map (L := L) (x := fun i j => (X i j).1) + (Map.circuit hu (Circuit.id F Names)) (fun _ => rfl) + have xy := pre.comp (keep.par hget) + have hpost := xy.comp (Computes.of_map (Map.circuit hu (receive_circuit r)) (fun _ => rfl)) + simp only [mul_one] at hpost + refine hpost.mono ?_ + have hN : (New).width = (Names).width + (Views).width := by + simp only [Fmt.rows, Neighborhood.Rows, Format.width_vec, Format.width_pair, mul_add] + rw [mul_left_comm (2 ^ h)] + unfold expandCost + rw [Format.width_pair] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Short adjacency masks + +Each entry compares a neighbor of a listed host against a second +listed host. Batched reads pay for the long addresses only while +preparing the masks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +open Coloring + +/-- Computes the mask by the application `Format.vec m (.vec q (.vec d (.vec q .bit)))`. -/ +abbrev Mask (m q d : ℕ) := Format.vec m (.vec q (.vec d (.vec q .bit))) + +variable {m q d t : ℕ} + +/-- Tests whether `g (u x i) j = u x k` holds. -/ +def maskRows (u : B m → B q → B m) (g : B m → B d → B m) (x : B m) + (i : B q) (j : B d) (k : B q) := decide (g (u x i) j = u x k) + +/-- Computes the mask by the application `maskRows (expand r g) g`. -/ +def mask (r : ℕ) (g : B m → B d → B m) := maskRows (expand r g) g + +variable (F : Type) [Field F] + +theorem cheap_maskRows (hm : m ≤ t) (hq : 2 ^ q ≤ t) (hd : 2 ^ d ≤ t) : + Cheap F m t (.pair (Rows m q) (Rows m d)) (Mask m q d) + (fun x => maskRows x.1 x.2) 24 := by + let A := Format.pair (Rows m q) (Rows m d) + have ha : A.width ≤ 2 ^ m * (100 + t) ^ 3 := by + have h := Nat.add_le_add (width hm hq) (width hm hd) + rw [← Format.width_pair, ← mul_add] at h + apply h.trans + apply Nat.mul_le_mul_left + ring_nf + omega + have base := Cheap.id F ha + have col (i : B q) := base.fst.comp (column F hm hq i) + have atHost (j : B d) := base.snd.comp (column F hm hd j) + have get := Cheap.lookup F m t (.addr m) hm (by simpa) + have bit (i : B q) (j : B d) (k : B q) : + Cheap F m t A (.vec m .bit) (fun a x => maskRows a.1 a.2 x i j k) 14 := by + have name := ((atHost j).pair (col i)).comp get + exact ((name.pair (col k)).zip.comp (Cheap.map _ (fun _ => cheap_eq F hm))).mono (by decide) + have all := Cheap.share _ (fun i => Cheap.share _ (fun j => Cheap.share _ (bit i j) hq) hd) hq + let D := Format.vec q (.vec d (.vec q (.vec m .bit))) + have hw : (Mask m q d).width ≤ 2 ^ m * (100 + t) ^ 3 := by + simp only [Mask, Format.width_vec] + rw [Format.width_bit, mul_one] + apply Nat.mul_le_mul_left + calc + _ ≤ t * (t * t) := Nat.mul_le_mul hq (Nat.mul_le_mul hd hq) + _ ≤ _ := by ring_nf; omega + have he : D.width = (Mask m q d).width := by + simp only [D, Mask, Format.width_vec] + ring + have reorder : Cheap F m t D (Mask m q d) (fun a x i j k => a i j k x) 4 := + Cheap.project F (he.le.trans hw) hw (fun z => (z.2.1, z.2.2.1, z.2.2.2.1, z.1, z.2.2.2.2)) + fun _ _ => rfl + exact (all.comp reorder).mono (by decide) + +theorem cheap_mask (m d r : ℕ) (hr : 0 < r) : + Cheap F m (m + 2 ^ ((d + 1) * r)) (Rows m d) (Mask m ((d + 1) * r) d) (mask r) 220 := by + let q := (d + 1) * r + let t := m + 2 ^ q + have hm : m ≤ t := Nat.le_add_right _ _ + have hq : 2 ^ q ≤ t := Nat.le_add_left _ _ + have hd : 2 ^ d ≤ t := (Nat.pow_le_pow_right (by decide) (show d ≤ q from + (Nat.le_succ d).trans (Nat.le_mul_of_pos_right _ hr))).trans hq + have args := (cheap F m d r hr).pair (Cheap.id F (width hm hd)) + exact (args.comp (cheap_maskRows F hm hq hd)).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +end + +/- +# Weighted updates on two nested neighborhoods + +Use one lookup table shared at every occurrence. Expanded views +are temporary; only the output records and original host graph +are carried across the stage boundary. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] {I : Type*} {A C D : Format} {m d h u r t v n v' n' : ℕ} + {L : Set (Table F)} + +open scoped Classical in +/-- The quantity computed by `Format.vec ((d + 1) * r) A`. -/ +abbrev Fmt.view (d r : ℕ) (A : Format) := Format.vec ((d + 1) * r) A +open scoped Classical in +/-- Computes the wave by the application `view d t (view d r (A.pair C))`. -/ +abbrev Fmt.wave (d r t : ℕ) (A C : Format) := view d t (view d r (A.pair C)) +open scoped Classical in +/-- The value specified by `(rows m d h A).pair (.vec m (.vec h C))`. -/ +abbrev Fmt.waveIn (m d h : ℕ) (A C : Format) := (rows m d h A).pair (.vec m (.vec h C)) + +open scoped Classical in +/-- Computes the around by the application `expand t (expand r (zip x))`. -/ +def Fmt.around (r t : ℕ) (x : (waveIn m d h A C).obj) : + (rows m d h (wave d r t A C)).obj := expand t (expand r (zip x)) + +open scoped Classical in +/-- The wave cost used in the `Assembly` construction. -/ +def waveCost (m d h r t v n v' n' : ℕ) (A C D : Format) := + 12 * (Fmt.rows m d h (A.pair C)).width + expandCost m d h r v n (A.pair C) + + expandCost m d h t v' n' (Fmt.view d r (A.pair C)) + updateCost m d h (Fmt.wave d r t A C) D + +open scoped Classical in +theorem computes_wave (hu : 3 ≤ u) (hr : 0 < r) (ht : 0 < t) + (h₁ : Access F u L (m + (d + 1) * r) v n) (h₂ : Access F u L (m + (d + 1) * t) v' n') + (hv : (Format.vec h (A.pair C)).width ≤ v) + (hv' : (Format.vec h (Fmt.view d r (A.pair C))).width ≤ v') + (f : (Fmt.wave d r t A C).obj → D.obj) (g : (Fmt.wave d r t A C).obj → F) + (hw : (Fmt.wave d r t A C).width + D.width ≤ u) (hg : weightTable f g ∈ L) + (X : I → (Fmt.waveIn m d h A C).obj) (hx : ∀ i, Fmt.Reciprocal (.vec h A) (X i).1) : + Computes F u L (Fmt.waveIn m d h A C) (Fmt.rows m d h D) + X (fun i => Fmt.update f (Fmt.around r t (X i))) (fun i + => Fmt.weight g (Fmt.around r t (X i))) + (waveCost m d h r t v n v' n' A C D) := by + have p := Computes.of_map (L := L) (x := X) + (map_zip (m := m) (d := d) (h := h) (A := A) (D := C) hu) (fun _ => rfl) + have q := computes_expand (L := L) r hu hr h₁ hv (fun i => Fmt.zip (X i)) hx + have w := computes_expand (L := L) t hu ht h₂ hv' (fun i => Fmt.expand r (Fmt.zip (X i))) hx + have a := computes_update f g hu hw hg (fun i => Fmt.around r t (X i)) + have out := ((p.comp q).comp w).comp a + simp only [one_mul, Function.comp_def] at out + exact out + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Apply.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Apply.lean new file mode 100644 index 0000000000..b9d35b537a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Apply.lean @@ -0,0 +1,976 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.FreezeInput.Retain +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.BoardPush +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Factor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.ShortNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.OuterRows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.Outer +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.ContractRates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Issue +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.TraceNet + +/-! # Fetching ordered labels after changing the host and block sets -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Receive +open Coloring + +/-- Computes the input by the application `Format.pair (Fmt.rows m d n (.addr l)) (Fmt.bank m' +d' (.vec a (A.pair (.vec t (.pair (.addr p) (.addr n))))))`. -/ +abbrev Input (m d n l m' d' a p t : ℕ) (A : Format) := + Format.pair (Fmt.rows m d n (.addr l)) + (Fmt.bank m' d' (.vec a (A.pair (.vec t (.pair (.addr p) (.addr n)))))) + +/-- Computes the output by the application `Fmt.bank m' d' (.pair (.vec p (.addr m)) (.pair +(.vec p (.vec d (.addr m))) (.vec a (A.pair (.vec t (.addr l))))))`. -/ +abbrev Output (m d _n l m' d' a p t : ℕ) (A : Format) := + Fmt.bank m' d' (.pair (.vec p (.addr m)) + (.pair (.vec p (.vec d (.addr m))) (.vec a (A.pair (.vec t (.addr l)))))) + +/-- The cost used in the `Receive` construction. -/ +def cost (m d n l m' d' a p t : ℕ) (A : Format) (v c : ℕ) := + gatherCost m d v c + 500 * ((Input m d n l m' d' a p t A).width + + (Output m d n l m' d' a p t A).width + 2 ^ (m + d) * (2 ^ d * m + 2 ^ n * l) + + 2 ^ m' * (2 ^ p * (2 ^ n * l) + 2 ^ n * (100 + n + 2 ^ p + 2 ^ t + l) ^ 100)) + +variable {m d n l m' d' a p t : ℕ} {A : Format} +variable (parent : B m' → B m) (step : B p → Option (B d)) + +local notation "X" => Input m d n l m' d' a p t A +local notation "Y" => Output m d n l m' d' a p t A + +/-- The value specified by `(step j).elim (parent i) (x.1 (parent i)).1`. -/ +def nav (x : (X).obj) (i : B m') (j : B p) : B m := + (step j).elim (parent i) (x.1 (parent i)).1 + +/-- The receive of type `(Y).obj`, constructed using `((x.2 i).2 k).2 b`. -/ +def receive (x : (X).obj) : (Y).obj := fun i => + ((x.2 i).1, nav parent step x i, fun j => (x.1 (nav parent step x i j)).1, + fun k => (((x.2 i).2 k).1, fun b => + let e := ((x.2 i).2 k).2 b + (x.1 (nav parent step x i e.1)).2 e.2)) + +local notation "R" => Format.pair (Format.vec d (Format.addr m)) (Format.vec n (Format.addr l)) +local notation "G" => Format.vec m (Format.vec d R) +local notation "Side" => Fmt.bank m' d' (Format.pair (Format.vec p (Format.addr m)) + (Format.pair (Format.vec p (Format.vec d (Format.addr m))) (Format.vec a A))) +local notation "Ask" => Format.vec m' (Format.pair (Format.vec p (Format.vec n (Format.addr l))) + (Format.vec a (Format.vec t (Format.pair (Format.addr p) (Format.addr n))))) +local notation "Got" => Format.vec m' (Format.vec a (Format.vec t (Format.addr l))) + +private def prep (x : (X).obj) : ((X).pair (Fmt.bank m d R)).obj := + (x, fun i => ((x.1 i).1, x.1 i)) + +private def remote (x : ((X).pair G).obj) (i : B m') (j : B p) : (R).obj := + (step j).elim (x.1.1 (parent i)) (x.2 (parent i)) + +private def spread (x : ((X).pair G).obj) : ((Side).pair Ask).obj := + (fun i => ((x.1.2 i).1, nav parent step x.1 i, fun j => (remote parent step x i j).1, + fun k => ((x.1.2 i).2 k).1), + fun i => (fun j => (remote parent step x i j).2, fun k => ((x.1.2 i).2 k).2)) + +private def join (x : ((Side).pair Got).obj) : (Y).obj := fun i => + ((x.1 i).1, (x.1 i).2.1, (x.1 i).2.2.1, fun k => ((x.1 i).2.2.2 k, x.2 i k)) + +variable {F : Type} [Field F] + +private theorem prep_net : Circuit F X ((X).pair (Fmt.bank m d R)) prep + ((X).width + 2 * ((X).pair (Fmt.bank m d R)).width) := by + let tap : ((X).pair (Fmt.bank m d R)).pins → (X).pins + | .inl z => z + | .inr (i, .inl z) => .inl (i, .inl z) + | .inr (i, .inr z) => .inl (i, z) + exact Circuit.project tap (by rintro x (z|⟨i, z|z⟩) <;> rfl) + +private theorem spread_net : Circuit F ((X).pair G) ((Side).pair Ask) (spread parent step) + (((X).pair G).width + 34 * ((Side).pair Ask).width) := by + have tap (i : B m') (j : B p) (z : (R).pins) : + ∃ w, ∀ x, (R).code (remote parent step x i j) z = ((X).pair G).code x w := by + cases h : step j with + | none => exact ⟨.inl (.inl (parent i, z)), fun _ => by rw [remote, h]; rfl⟩ + | some k => exact ⟨.inr (parent i, k, z), fun _ => by rw [remote, h]; rfl⟩ + apply Window.Tile.project_const + rintro (⟨i, z|⟨j, z⟩|⟨j, z⟩|⟨k, z⟩⟩|⟨i, ⟨j, z⟩|⟨k, z⟩⟩) + · exact .inl ⟨.inl (.inr (i, .inl z)), fun _ => rfl⟩ + · change (∃ w, ∀ x, (Format.addr m).code (nav parent step x.1 i j) z = ((X).pair G).code x w) ∨ + ∃ b, ∀ x : ((X).pair G).obj, (Format.addr m).code (nav parent step x.1 i j) z = b + cases h : step j with + | none => exact .inr ⟨(Format.addr m).code (parent i) z, fun _ => by rw [nav, h]; rfl⟩ + | some k => exact .inl ⟨.inl (.inl (parent i, .inl (k, z))), fun _ => by rw [nav, h]; rfl⟩ + · exact .inl (tap i j (.inl z)) + · exact .inl ⟨.inl (.inr (i, .inr (k, .inl z))), fun _ => rfl⟩ + · exact .inl (tap i j (.inr z)) + · exact .inl ⟨.inl (.inr (i, .inr (k, .inr z))), fun _ => rfl⟩ + +private theorem join_net : Circuit F ((Side).pair Got) Y join + (((Side).pair Got).width + 2 * (Y).width) := by + let tap : (Y).pins → ((Side).pair Got).pins + | (i, .inl z) => .inl (i, .inl z) + | (i, .inr (.inl z)) => .inl (i, .inr (.inl z)) + | (i, .inr (.inr (.inl z))) => .inl (i, .inr (.inr (.inl z))) + | (i, .inr (.inr (.inr (k, .inl z)))) => .inl (i, .inr (.inr (.inr (k, z)))) + | (i, .inr (.inr (.inr (k, .inr z)))) => .inr (i, k, z) + exact Circuit.project tap (by rintro x ⟨i, z|z|z|⟨k, z|z⟩⟩ <;> rfl) + +variable {u v c : ℕ} {L : Set (Table F)} {I : Type*} + +/-- Only the old graph needs to be reciprocal. Each old host sends its neighbor +list and block labels together. The fixed parent and step maps then place the +required lists at the new hosts before any block requests are resolved. -/ +theorem run (hu : 3 ≤ u) (ha : a ≤ n) (ht : Access F u L (m + d) v c) + (hv : 2 ^ d * m + 2 ^ n * l ≤ v) (x : I → (X).obj) + (hx : ∀ i, Fmt.Reciprocal (.vec n (.addr l)) (x i).1) : + Computes F u L X Y x (fun i => receive parent step (x i)) (fun _ => 1) + (cost m d n l m' d' a p t A v c) := by + have start := Computes.of_map (L := L) (x := x) (Map.circuit hu (prep_net (F := F))) (fun _ + => rfl) + have keep := Computes.of_map (L := L) (x := x) (Map.circuit hu (Circuit.id F X)) (fun _ => rfl) + have move := gather_neighbors R hu ht (by simpa using hv) + (fun i => (prep (x i)).2) hx + let y (i : I) : ((X).pair G).obj := (x i, Fmt.gather R (prep (x i)).2) + have pick (i : I) (j : B m') (k : B p) : + remote parent step (y i) j k = (x i).1 (nav parent step (x i) j k) := by + unfold remote nav + cases step k <;> rfl + have read := Circuit.map (fun _ : B m' => _) (fun _ => local_read F n a p t l ha) + have endNet := ((spread_net (F := F) (d' := d') (A := A) parent step).comp + ((Circuit.id F Side).par read)).comp (join_net (n := n)) + have stop := Computes.of_map (L := L) (x := y) (y := fun i => receive parent step (x i)) + (Map.circuit hu endNet) (by + intro i + simp only [Function.comp_apply, Prod.map, id_eq, spread, pick] + rfl) + have done := (start.comp (keep.par move)).comp stop + simp only [mul_one] at done + refine done.mono ?_ + have hb : (Fmt.bank m d R).width ≤ 2 * (X).width := by + simp only [Input, Fmt.bank, Fmt.rows, Format.width_pair, Format.width_vec, mul_add] + omega + have hg : (G).width = 2 ^ (m + d) * (2 ^ d * m + 2 ^ n * l) := by + simp only [Format.width_pair, Format.width_vec, Format.width_addr, pow_add, mul_assoc] + have hs : (Side).width + (Got).width = (Y).width := by + simp only [Output, Fmt.bank, Format.width_pair, Format.width_vec, mul_add] + omega + have hq : (Ask).width ≤ 2 ^ m' * (2 ^ p * (2 ^ n * l)) + (X).width := by + simp only [Input, Fmt.bank, Format.width_pair, Format.width_vec, Format.width_addr, mul_add] + omega + unfold cost + rw [Format.width_pair X (Fmt.bank m d R), Format.width_pair X G, Format.width_pair Side Ask, + Format.width_pair Side Got, mul_add (2 ^ m')] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Receive +end + +/- # Wiring the requests for old attachment labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring + +variable {F : Type} {D Y : Template F} (A : Attachment D) (Y : Template F) (k p : ℕ) + +open scoped Classical in +/-- Computes the requests by the application `A.format.pair (Y.format.pair (.vec Y.scheme.m +(.vec Y.scheme.h (.pair .bit (A.orders Y k p)))))`. -/ +abbrev Requests := A.format.pair + (Y.format.pair (.vec Y.scheme.m (.vec Y.scheme.h (.pair .bit (A.orders Y k p))))) + +open scoped Classical in +/-- The value specified by `Receive.Input D.scheme.m D.scheme.d D.scheme.h A.ℓ Y.scheme.m +Y.scheme.d Y.scheme.h p (depth Y k) (A.ticket Y k p)`. -/ +abbrev Inputs := Receive.Input D.scheme.m D.scheme.d D.scheme.h A.ℓ + Y.scheme.m Y.scheme.d Y.scheme.h p (depth Y k) (A.ticket Y k p) + +variable {A Y k p} + +open scoped Classical in +private theorem question_pin (self : B p) (b : (ask (D := D) Y k p).pins) : + (∃ w, ∀ x, (ask (D := D) Y k p).code (A.question self x) b = + (A.ticket Y k p).code x w) ∨ + ∃ c, ∀ x : (A.ticket Y k p).obj, (ask (D := D) Y k p).code (A.question self x) b = c := by + let H := Format.pair (.addr p) (.addr D.scheme.h) + obtain ⟨i, z⟩ := b + change (∃ w, ∀ x, H.code (A.question self x i) z = (A.ticket Y k p).code x w) ∨ + ∃ c, ∀ x : (A.ticket Y k p).obj, H.code (A.question self x i) z = c + by_cases hi : ∃ j, request Y k j = i + · obtain ⟨l|l, rfl⟩ := hi + · simp only [question, (request Y k).injective.extend_apply, Sum.elim_inl] + rcases z with z|z + · exact .inl ⟨.inr (.inr (.inl (l, .inr (.inl z)))), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inr (.inl (l, .inr (.inr (.inl z))))), fun _ => rfl⟩ + · simp only [question, (request Y k).injective.extend_apply, Sum.elim_inr] + rcases z with z|z + · exact .inr ⟨(Format.addr p).code self z, fun _ => rfl⟩ + · exact .inl ⟨.inr (.inr (.inr (l, .inr (.inl z)))), fun _ => rfl⟩ + · exact .inr ⟨H.code (self, 0) z, fun _ => by rw [question, Function.extend_apply' _ _ _ hi]⟩ + +namespace Query +variable (q : Query A Y k p) (self : B p) + +open scoped Classical in +/-- The indexed operation `(q.old, q.fresh, fun i j => (q.ticketAt i j).2)`. -/ +def requests : (A.Requests Y k p).obj := (q.old, q.fresh, fun i j => (q.ticketAt i j).2) + +open scoped Classical in +/-- The indexed operation `(A.rows q.old, fun i => (Y.nav q.fresh i, fun j => (q.ticketAt i j, +A.question self (q.ticketAt i j))))`. -/ +def inputs : (A.Inputs Y k p).obj := + (A.rows q.old, fun i => (Y.nav q.fresh i, fun j => (q.ticketAt i j, + A.question self (q.ticketAt i j)))) + +open scoped Classical in +theorem inputs_net [Field F] {u : ℕ} {L : Set (Table F)} {I : Type*} + (hu : 3 ≤ u) (q : I → Query A Y k p) (self : B p) : + Computes F u L (A.Requests Y k p) (A.Inputs Y k p) + (fun i => (q i).requests) (fun i => (q i).inputs self) (fun _ => 1) + (4 * ((A.Requests Y k p).width + 34 * (A.Inputs Y k p).width)) := by + let X := A.Requests Y k p + let Z := A.Inputs Y k p + let T := A.ticket Y k p + let pull (i : B Y.scheme.m) (j : B Y.scheme.h) (x : X.obj) : T.obj := + ((x.2.1.1 i).2 j, x.2.2 i j) + let f (x : X.obj) : Z.obj := + (A.rows x.1, fun i => (Y.nav x.2.1 i, fun j => (pull i j x, A.question self (pull i j x)))) + have ht (i : B Y.scheme.m) (j : B Y.scheme.h) (z : T.pins) : + ∃ w, ∀ x, T.code (pull i j x) z = X.code x w := by + rcases z with z|z + · exact ⟨.inr (.inl (.inl (i, .inr (j, z)))), fun _ => rfl⟩ + · exact ⟨.inr (.inr (i, j, z)), fun _ => rfl⟩ + have net : Circuit F X Z f (X.width + 34 * Z.width) := by + apply Window.Tile.project_const + rintro (⟨i, z|z⟩ | ⟨i, z|⟨j, z|z⟩⟩) + · exact .inl ⟨.inl (.inl (.inl (i, .inl z))), fun _ => rfl⟩ + · exact .inl ⟨.inl (.inr (i, z)), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inl (.inl (i, .inl z))), fun _ => rfl⟩ + · exact .inl (ht i j z) + · rcases question_pin (A := A) (Y := Y) (k := k) self z with ⟨w, hw⟩ | ⟨b, hb⟩ + · obtain ⟨l, hl⟩ := ht i j w + exact .inl ⟨l, fun x => (hw (pull i j x)).trans (hl x)⟩ + · exact .inr ⟨b, fun x => hb (pull i j x)⟩ + exact Computes.of_map (Map.circuit hu net) (fun _ => rfl) + +end Query +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Computing the inspection records for a family of attachment queries -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring + +variable {F : Type} {D Y : Template F} (A : Attachment D) (Y : Template F) (k p : ℕ) + +/-- The review cost used in the `Attachment` construction. -/ +def reviewCost (v c v' c' : ℕ) := + 4 * ((A.Requests Y k p).width + 34 * (A.Inputs Y k p).width) + + Receive.cost D.scheme.m D.scheme.d D.scheme.h A.ℓ Y.scheme.m Y.scheme.d Y.scheme.h p + (depth Y k) (A.ticket Y k p) v c + + Inspect.cost D.scheme.m D.scheme.d Y.scheme.m Y.scheme.d p Y.scheme.h (A.bundle Y k p) v' c' + +variable {A Y k p} [Field F] {u v c v' c' : ℕ} {L : Set (Table F)} {I : Type*} + +/-- The two exchanges use the old and new host graphs respectively. +The parent map and the choice of steps are fixed across the family. -/ +theorem Query.review_net (hu : 3 ≤ u) (ha : Y.scheme.h ≤ D.scheme.h) + (ht : Access F u L (D.scheme.m + D.scheme.d) v c) + (hv : 2 ^ D.scheme.d * D.scheme.m + 2 ^ D.scheme.h * A.ℓ ≤ v) + (ht' : Access F u L (Y.scheme.m + Y.scheme.d) v' c') + (hv' : (Inspect.Packet D.scheme.m D.scheme.d p Y.scheme.h (A.bundle Y k p)).width ≤ v') + (parent : B Y.scheme.m → B D.scheme.m) (step : B p → Option (B D.scheme.d)) + (Q : I → Query A Y k p) (self : B p) + (nav : ∀ i j l, (Q i).M.nav j l = (step l).elim (parent j) (D.nav (Q i).old.1 (parent j))) + (oldRecip : ∀ i, Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) (Q i).old.1.1) + (newRecip : ∀ i, Fmt.Reciprocal (.vec Y.scheme.h (.addr Y.scheme.ℓ)) (Q i).fresh.1) : + Computes F u L (A.Requests Y k p) (.vec Y.scheme.m (.vec Y.scheme.h (A.Review Y k p))) + (fun i => (Q i).requests) (fun i => (Q i).review self) (fun _ => 1) + (A.reviewCost Y k p v c v' c') := by + let X i := (Q i).inputs self + let Z i := Receive.receive parent step (X i) + have pre := Query.inputs_net (L := L) hu Q self + have fetch := Receive.run parent step hu ha ht hv X oldRecip + have post := Inspect.run hu ht' hv' Z newRecip + have he (i : I) : Inspect.view (Z i) = (Q i).review self := by + have hn : (Q i).M.nav = Receive.nav parent step (X i) := + funext fun j => funext fun l => nav i j l + funext j l + unfold Query.review Query.received + rw [hn] + rfl + have done := (pre.comp fetch).comp post + simp only [he, mul_one] at done + exact done + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- +# Rebuilding the attached network with one short dictionary + +The same dictionary reads the two local records and the shared +address mask at each occurrence. Its arity does not include the +width of a global host name. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (Y : Template F) (k p : ℕ) + +open scoped Classical in +/-- The quantity computed by `(A.Review Y k p).width + (A.transport Y k).ℓ`. -/ +def rebuildWidth := (A.Review Y k p).width + (A.transport Y k).ℓ + +open scoped Classical in +/-- The value specified by `(A.record Y k).serial (rebuild self x)`. -/ +def rebuildLabel (self : B p) (x : (A.Review Y k p).obj) : B (A.transport Y k).ℓ := + (A.record Y k).serial (rebuild self x) + +open scoped Classical in +/-- The indexed operation `weightTable (A := A.Review Y k p) (D := .addr (A.transport Y k).ℓ) +(A.rebuildLabel Y k p self) (fun _ => (1 : F))`. -/ +def rebuildGate (self : B p) := + weightTable (A := A.Review Y k p) (D := .addr (A.transport Y k).ℓ) + (A.rebuildLabel Y k p self) (fun _ => (1 : F)) + +open scoped Classical in +/-- The bound obtained by adding the component charges `24 * (A.Requests Y k p).width + 8 * +Y.format.width + A.reviewCost Y k p v c v' c' + 2 ^ Y.scheme.m * (2 ^ Y.scheme.h * (1 + +A.rebuildWidth Y k p))`. -/ +def rebuildCost (v c v' c' : ℕ) := + 24 * (A.Requests Y k p).width + 8 * Y.format.width + A.reviewCost Y k p v c v' c' + + 2 ^ Y.scheme.m * (2 ^ Y.scheme.h * (1 + A.rebuildWidth Y k p)) + +open scoped Classical in +theorem rebuild_arity (self : B p) : wd (A.rebuildGate Y k p self).1 + + wd (A.rebuildGate Y k p self).2.1 = + A.rebuildWidth Y k p := by + simp only [rebuildGate, weightTable, lookup, wd_word, rebuildWidth] + rw [Format.width_addr] + +variable {A Y k p} + +open scoped Classical in +/-- Computes the result by the application `q.R.write q.old q.fresh q.active (q.R.links q.old +q.fresh q.M)`. -/ +abbrev Query.result (q : Query A Y k p) := q.R.write q.old q.fresh q.active (q.R.links q.old + q.fresh q.M) + +open scoped Classical in +theorem Query.rebuild_net {u v c v' c' : ℕ} {L : Set (Table F)} {I : Type*} + (hu : 3 ≤ u) (ha : Y.scheme.h ≤ D.scheme.h) + (ht : Access F u L (D.scheme.m + D.scheme.d) v c) + (hv : 2 ^ D.scheme.d * D.scheme.m + 2 ^ D.scheme.h * A.ℓ ≤ v) + (ht' : Access F u L (Y.scheme.m + Y.scheme.d) v' c') + (hv' : (Inspect.Packet D.scheme.m D.scheme.d p Y.scheme.h (A.bundle Y k p)).width ≤ v') + (parent : B Y.scheme.m → B D.scheme.m) (step : B p → Option (B D.scheme.d)) + (Q : I → Query A Y k p) (self : B p) + (nav : ∀ i j l, (Q i).M.nav j l = (step l).elim (parent j) (D.nav (Q i).old.1 (parent j))) + (oldRecip : ∀ i, Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) (Q i).old.1.1) + (newRecip : ∀ i, Fmt.Reciprocal (.vec Y.scheme.h (.addr Y.scheme.ℓ)) (Q i).fresh.1) + (back : ∀ i j, (Q i).M.nav j self = (Q i).R.parent j) + (fit : A.rebuildWidth Y k p ≤ u) (allow : A.rebuildGate Y k p self ∈ L) : + Computes F u L (A.Requests Y k p) (A.transport Y k).format + (fun i => (Q i).requests) (fun i => (Q i).result) (fun _ => 1) + (A.rebuildCost Y k p v c v' c') := by + let X := A.Requests Y k p + let E := A.Review Y k p + let H := Format.addr (A.transport Y k).ℓ + let μ := A.rebuildLabel Y k p self + have hwidth : E.width + H.width = A.rebuildWidth Y k p + := by rw [show H.width = _ from Format.width_addr _]; rfl + have localMap : Map F u L E H μ (1 + A.rebuildWidth Y k p) := by + rw [← hwidth, ← add_assoc] + exact Kernel.lookup (hwidth.le.trans fit) allow + have inspect := review_net hu ha ht hv ht' hv' parent step Q self nav oldRecip newRecip + have decode := Map.vec (t := Y.scheme.m) _ (fun _ => + Map.vec (t := Y.scheme.h) _ (fun _ => localMap)) + have codes := inspect.comp (Computes.of_map decode (y := fun i => (Q i).result.2) (by + intro i + funext j t + exact congrArg (A.record Y k).serial ((Q i).rebuild_eq self (back i) j t))) + have keep : Circuit F X Y.format (fun r => r.2.1) (X.width + 2 * Y.format.width) := + Circuit.project (Sum.inr ∘ Sum.inl) (fun _ _ => rfl) + have view := Computes.of_map (x := fun i => (Q i).requests) (L := L) (Map.circuit hu keep) (fun _ + => rfl) + have h := view.pair hu codes + simp only [mul_one] at h + exact h.mono (by unfold rebuildCost; unfold X; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Withdrawing core scalars while preserving attachment requests -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Coloring Packing + +variable {F : Type} [Field F] + +namespace BatchDescent.Trail.Move +variable {S U : Scheme F} {k : ℕ} + +open scoped Classical in +/-- Uses `⟨M.nav, M.read⟩` as the representation. -/ +abbrev sweep (M : Move S U k) : Move S U.sweep k := ⟨M.nav, M.read⟩ + +open scoped Classical in +theorem Agrees.sweep {x y : Wire} {G H : Diagram F x y} + {r : S.format.obj} {s : U.format.obj} {M : Move S U k} + {p : S.Presentation r G} {q : U.Presentation s H} + (h : M.Agrees p q) : M.sweep.Agrees p q.sweep := by + have hb (j : slots x ⊕ slots y) : (q.sweep.boundary j).val = (q.boundary j).val := by + cases j with + | inl i => exact q.sweep_end (.inl (.inl i)) + | inr i => exact q.sweep_end (.inr (.inl i)) + constructor + · intro j + rw [hb] + exact h.mapped j + · intro w hw + obtain ⟨j, hj⟩ := h.active w hw + exact ⟨j, by rw [hb]; exact hj⟩ + +end BatchDescent.Trail.Move + +namespace Assembly.Attachment +variable {D Y : Template F} {A : Attachment D} {k p : ℕ} + +namespace Relocation + +open scoped Classical in +/-- Uses `⟨R.parent, R.prev⟩` as the representation. -/ +abbrev sweep (R : A.Relocation Y k) : A.Relocation Y.sweep k := ⟨R.parent, R.prev⟩ + +variable {T : Type} [Fintype T] {x y a b : Wire} {u v : ℕ} {L : Fringe x y T} + {G : HostNet F L D.scheme.h u} {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} + {r : A.format.obj} {s : Y.format.obj} {q : A.Encloses r G Z} {e : Y.Encodes s H} + +open scoped Classical in +theorem Moves.sweep {R : A.Relocation Y k} {slot : T → B k} (h : R.Moves q e slot) : + R.sweep.Moves q e.sweep slot := ⟨h.positive, h.iff⟩ + +open scoped Classical in +theorem WriteActive.sweep {live : B Y.scheme.m → B Y.scheme.h → Bool} (h : WriteActive e live) : + WriteActive e.sweep live := h + +end Relocation + +open scoped Classical in +/-- Uses `⟨q.R.sweep, q.M.sweep, q.old, q.fresh, q.active⟩` as the representation. -/ +abbrev Query.sweep (q : A.Query Y k p) : A.Query Y.sweep k p := + ⟨q.R.sweep, q.M.sweep, q.old, q.fresh, q.active⟩ + +open scoped Classical in +/-- Computes the sweep weight by the application `Fmt.weight Y.scheme.scalar q.fresh.1`. -/ +def Query.sweepWeight (q : A.Query Y k p) : F := Fmt.weight Y.scheme.scalar q.fresh.1 + +open scoped Classical in +/-- The sweep cost used in the `Attachment` construction. -/ +def sweepCost (A : Attachment D) (Y : Template F) (k p : ℕ) := + 4 * A.format.width + + (updateCost Y.scheme.m Y.scheme.d Y.scheme.h (.addr Y.scheme.ℓ) (.addr Y.scheme.ℓ) + + 4 * (Format.vec Y.scheme.m Y.header).width + + 4 * (Format.vec Y.scheme.m (.vec Y.scheme.h (.pair .bit (A.orders Y k p)))).width) + +open scoped Classical in +theorem Query.sweep_net {u : ℕ} {L : Set (Table F)} {I : Type*} + (q : I → A.Query Y k p) (hu : 3 ≤ u) (ha : 2 * Y.scheme.ℓ ≤ u) + (hl : BatchDescent.Snapshot.sweepTable Y ∈ L) : + Computes F u L (A.Requests Y k p) (A.Requests Y.sweep k p) + (fun i => (q i).requests) (fun i => (q i).sweep.requests) + (fun i => (q i).sweepWeight) (A.sweepCost Y k p) := by + let B := Format.addr Y.scheme.ℓ + let V := Format.vec Y.scheme.m (.vec Y.scheme.h (.pair .bit (A.orders Y k p))) + have step := update (m := Y.scheme.m) (d := Y.scheme.d) (h := Y.scheme.h) (A := B) (D := B) + id Y.scheme.scalar hu (by simpa [B, two_mul] using ha) hl + have keep (X : Format) := Action.of_map (Map.circuit (L := L) hu (Circuit.id F X)) + have run := (keep A.format).par ((step.par (keep (.vec Y.scheme.m Y.header))).par (keep V)) + simp only [one_mul, mul_one] at run + exact Computes.of_action run (fun _ => rfl) (fun _ => rfl) + +end Assembly.Attachment +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- # Applying a validated move and core sweep to an attached frame -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Query +open Packing Coloring BatchDescent + +variable {F : Type} [Field F] {T : Type} [Fintype T] + {x y a b : Wire} {D Y : Template F} {A : Attachment D} + {k m u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} {H : HostNet F L Y.scheme.h v} + {Z : Border F T a b x y} (q : A.Query Y k m) + {old : A.Encloses q.old G Z} {fresh : Y.Encodes q.fresh H} {slot : T → B k} + (h : q.R.Moves old fresh slot) (ok : Relocation.WriteActive fresh q.active) + (move : q.M.Agrees old.core.post.toPresentation fresh.post.toPresentation) (full : Y.full = true) + +open scoped Classical in +/-- Uses `⟨T, x, y, L, H.sweep, Z, q.sweep.result, h.sweep.enclose ok.sweep move.sweep full⟩` as +the representation. -/ +def apply : (A.transport Y.sweep k).Data a b v := + ⟨T, x, y, L, H.sweep, Z, q.sweep.result, h.sweep.enclose ok.sweep move.sweep full⟩ + +open scoped Classical in +theorem fits {height : ℕ} (fit : A.scheme.Fits (A.rows q.old) (volume a b D.scheme.m) height) : + (q.apply h ok move full).Fits height := + h.sweep.fits ok.sweep move.sweep full fit + +open scoped Classical in +theorem floor {w : ℕ} (low : ∀ j, w ≤ fresh.post.toPresentation.borderWidth j) : + ∀ j, w ≤ (q.apply h ok move full).q.core.post.toPresentation.borderWidth j := low + +open scoped Classical in +theorem spare {δ : ℝ} {N : ℕ} (hd : 0 < δ) (charge : ∀ t, δ ≤ L.scale * L.charge t) + (bound : ∀ v i, H.load v i ≤ (N : ℝ) * δ) : + A.Sparse Y.sweep k N (q.apply h ok move full).raw := + q.sweep.R.sparse (q.apply h ok move full).q hd charge bound + +open scoped Classical in +theorem exterior (j : slots a ⊕ slots b) : + let v := ((q.apply h ok move full).q.pres.boundary j).val + let w := (old.pres.boundary j).val + q.sweep.R.kept q.old v.1.1 = some w.1.1 ∧ v.1.2 = A.outer Y.sweep w.1.2 ∧ v.2.val = w.2.val := + h.sweep.exterior_pin ok.sweep move.sweep full j + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Query +end + +/- # Control and contraction share the same three cost scales -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +open Coloring + +private theorem localWidth : Short (fun i => Prepare.arity i.S i.w) := by + have base : Short Size.T := BatchDescent.Phase.Poly.of_le Size.t_two fun _ => le_rfl + refine ((num 64).short.mul base).mono fun i => ?_ + have h := arity_le i + unfold arity Dictionary.arity at h + omega + +private theorem key : Short (fun i => (Prepare.key i.S).width) := + localWidth.mono fun _ => Nat.le_add_right .. +private theorem answer : Short (fun i => (Prepare.answer i.S i.w).width) := + localWidth.mono fun _ => Nat.le_add_left .. + +private theorem pair {A D : Size → Format} + (a : Work (fun i => (A i).width)) (b : Work (fun i => (D i).width)) : + Work (fun i => ((A i).pair (D i)).width) := + (a.add b).mono fun _ => (Format.width_pair ..).le + +private theorem grid {A : Size → Format} (h : Short (fun i => (A i).width)) : + Work (fun i => (Format.vec i.S.m (.vec i.n (A i))).width) := + (Work.spans h).mono fun _ => by rw [Format.width_vec, Format.width_vec, Size.spans, mul_assoc] + +private theorem bothWidths : Work (fun i => (Prepare.both i.S i.w).width) := by + have split (A D : Format) : A.width ≤ (A.pair (A.pair D)).width ∧ + D.width ≤ (A.pair (A.pair D)).width := by simp only [Format.width_pair]; omega + have left : Short (fun i => (SpanPlan.header i.w i.p i.n).width) := + answer.mono fun _ => (split _ _).1 + have right : Short (fun i => (SpanPlan.header i.w 0 i.n).width) := + answer.mono fun _ => (split _ _).2 + exact pair (pair names (pair (grid left) (grid left))) (pair (grid left) (grid right)) + +private theorem traffic : Work (fun i => linkCost i.S) := by + have f := ((num 100).long.add (m.add links.long)).pow 24 + exact format.add ((Work.hosts f).scale (num 512)) + +private theorem prepare : Work (fun i => Prepare.cost i.S i.w (linkCost i.S)) := by + have mask : Work (fun i => (Flags i.S).width) := + (Work.hosts neighbors.long).mono fun _ => by + rw [Flags, Format.width_vec, Format.width_vec, Format.width_bit, mul_one] + have src := (pair format (pair names mask)).add ((pair names (grid key)).scale (num 34)) + have q := (((format.scale (num 5)).add format).add traffic).add src + have slot := Work.spans (((num 1).short.add key).add answer) + refine ((q.scale (num 4)).add ((names.scale (num 4)).add slot)).mono fun i => ?_ + unfold Prepare.cost Size.spans + rw [mul_assoc i.hosts] + +theorem order : Work orderCost := by + have stage := ((pair names (grid answer)).add (bothWidths.scale (num 2))).add (emit.add project) + exact ((format.scale (num 20)).add (prepare.add (stage.scale (num 4)))).add header + +theorem terminal : Work (fun i => 8 * i.S.format.width + orderCost i + i.price) := + ((format.scale (num 8)).add order).add price + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +end + +/- # Checking internal and exterior wires when contracting the terminal network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring + +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} {t V V' k' w z : ℕ} + {peer : B (S.m + z) → B (S.m + z)} {send take : SpanPlan.Entries S.m w z S.spanRows} + {b : SpanPlan.Entries S.m w 0 S.spanRows} + +local notation "I" => PeerLayout.S S.m V (height S t) S.m V (height S t) (2 ^ z) +local notation "O" => PeerLayout.S S.m V (height S t) S.m V' k' 1 +local notation "P" => Payload.Script.decode le_rfl (SpanPlan.emit peer (send, take)) +local notation "Q" => Payload.Script.decode le_rfl (Outer.script (send, b)) + +open scoped Classical in +theorem shipment (h : Fits S r V t) (hx : S.Fits r V' k') (ok : S.Proper r) (hn : Neutral S r) + (hw : height S t < w) (hw' : k' < w) (inner : Inner S r t peer send take) + (hb : ∀ i j, (b i j).2.1.val = S.extent r i j) (ho : ∀ i j, (b i j).2.2 = j) + (x : S.exposed r → Bool) : + ∑ a, ((I).kernel F (P, a) a * (O).kernel F (Q, a) (S.store r hx x)) * localValue h a + = S.eval r x := by + apply contract h hn x + · intro a ha + have hh : (I).Carries P a a := by + by_contra he + simp only [Channels.kernel, ite_eq_right he, zero_mul, ne_eq, not_true_eq_false] at ha + exact ((inner.carries ok h hw a).mp hh).1 + · intro v + have hi := inner.carries_store ok h hw v + have he := Outer.correct h hx send b hw hw' inner.lengths hb ho v x + simp only [Channels.kernel, hi, he, Scheme.Agrees] + by_cases hext : ∀ i : S.exposed r, v i.val = x i + · simp [hext] + · simp only [hext, false_and, ite_false, mul_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- # Evaluating the generated command on a valid presentation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal + +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} {V t w V' k : ℕ} + +open scoped Classical in +theorem value_orders (h : Fits S r V t) (hx : S.Fits r V' k) + (hp : S.Proper r) (hr : Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) r) + (hn : Neutral S r) (hw : height S t < w) (hk : k < w) (x : S.exposed r → Bool) : + value S V t V' k (S.d + 1) w S.spanRows (orders S V t w r) (S.store r hx x) = S.eval r x := by + have ht : t < w := (by unfold height at hw; omega) + have he := shipment h hx hp hn hw hk (inner_plan S r hp hr ht) (outer_length S r h ht) + (fun _ _ => rfl) x + unfold value orders + simp only [Header.correct h, Dictionary.weight_encode] + exact he + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- +# Frozen station addresses in a grouping + +A frozen station stays in its own colony. The old within-group block +suffix and the old seat identify the station even if its colony has +many blocks. Zero remains reserved for the new core station. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Packing Coloring History + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) + {P : Gadget F} {a : ℕ} {ha : a ≤ D.scheme.h} {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} + {hu : 0 < P.b * z} {hz : 0 < z} {e : ℕ} + (t : D.Branch P a ha b k cost Δ C z σ hu) (M : Book D.scheme P z hz) (e cap : ℕ) (K : + Template.Meter) + +local notation "n" => (D.scheme.h - a) +local notation "Y" => D.after a Δ C M e cap K + +open scoped Classical in +/-- The lookup seat of type `Option (B D.scheme.h × B A.k)`, constructed using `Match.rowIndex n +A.k l`. -/ +def lookupSeat (g : B a) (iv : B (n + 1)) (live : Bool) (tags : B n → B (n + 1)) + (l : B (n + A.k)) : Option (B D.scheme.h × B A.k) := + let p := Match.rowIndex n A.k l + if live = true ∧ tags p.1 = iv then some (D.position a ha g p.1, p.2) else none + +open scoped Classical in +/-- Builds `A.Relocation Y (n + A.k) where parent` with the specified `parent`, `prev`. -/ +def grouped : A.Relocation Y (n + A.k) where + parent := D.parent a + prev i j := A.lookupSeat (ha := ha) j (Match.rowIndex _ _ i).2 (D.childLive a t.r i) + (D.tags a ha k cost Δ C t.r (D.parent a i) j) + +open scoped Classical in +/-- The value specified by `(Match.rowIndex n A.k).symm (cellIndex _ (suffix a (t.G.park i).2), +s i)`. -/ +def newSlot (s : t.T → B A.k) (i : t.T) : B (n + A.k) := + (Match.rowIndex n A.k).symm (cellIndex _ (suffix a (t.G.park i).2), s i) + +open scoped Classical in +theorem slot_pos (s : t.T → B A.k) (hs : ∀ i, s i ≠ 0) (i : t.T) : A.newSlot t s i ≠ 0 := by + intro he + have hf : (Match.rowIndex n A.k 0).2 = 0 := by apply Fin.ext; simp [Match.rowIndex] + have hit := congrArg (fun w => (Match.rowIndex n A.k w).2) he + rw [newSlot, Equiv.apply_symm_apply, hf] at hit + exact hs i hit + +omit [Field F] in +open scoped Classical in +private theorem position_iff (i : B a) (j : B n) (t : Cell D.scheme.h) : + D.position a ha i j = cellIndex _ t ↔ + i = cellIndex _ (ancestor ha t) ∧ j = cellIndex _ (suffix a t) := by + unfold Template.position + rw [(cellIndex _).injective.eq_iff, Equiv.symm_apply_eq] + change (_, _) = (ancestor ha t, suffix a t) ↔ _ + rw [Prod.mk.injEq, Equiv.symm_apply_eq, Equiv.symm_apply_eq] + +open scoped Classical in +private theorem sameHost (i : t.T) : + let w := splitAddr t.G.V a ha (t.G.park i) + t.s.group.route t.s.matching (t.s.group.layout t.s.matching P t.i) w.1 w.2 = + t.s.group.here w.1 w.2 := by + intro w + rcases t.s.group.route_cases t.s.matching (t.s.group.layout t.s.matching P t.i) w.1 w.2 with + h|⟨f, h, _⟩ + · exact h + · have hfixed : (t.G.regroup a ha).frozen w.1 := t.G.kept i + exact (((t.G.regroup a ha).core f.val).1 (h.symm ▸ hfixed)).elim + +variable (hc : Δ ≤ C) + +open scoped Classical in +theorem frozen_address (i : t.T) : + let w := t.G.park i + let g := ancestor ha w.2 + let j := suffix a w.2 + (t.layout hc).park i = ((w.1, (t.s.group.here (w.1, g) j).2), g) := by + intro w g j + exact congrArg (t.G.project a ha Δ C hc).place (sameHost t i) + +open scoped Classical in +theorem back_iff (slot : t.T → B A.k) (i : t.T) (u : B (D.size a)) (g : B a) (l : B (n + A.k)) : + (A.grouped t M e cap K).back (u, g, l) = + some (t.p.post.host (t.G.park i).1, t.p.post.block (t.G.park i).2, slot i) ↔ + (u, g, l) = (Child.host t.p.post.host n ((t.layout hc).park i).1, + cellIndex a ((t.layout hc).park i).2, A.newSlot t slot i) := by + let w := t.G.park i + let host := t.p.post.host w.1 + let block := cellIndex _ (ancestor ha w.2) + let suf := cellIndex _ (suffix a w.2) + let iv := (t.s.group.here (w.1, ancestor ha w.2) (suffix a w.2)).2 + let dest := Child.host t.p.post.host n (w.1, iv) + let s := Match.rowIndex n A.k + let r := Match.rowIndex D.scheme.m (n + 1) + have he : r dest = (host, intervalCode n iv) := Child.host_parts _ _ + have ht : D.tags a ha k cost Δ C t.r host block suf = intervalCode n iv := t.s.tags _ _ _ + have hv : D.childLive a t.r dest = true := (D.child_live a t.p _).mpr ⟨_, rfl⟩ + rw [frozen_address t hc i, t.p.block] + change Option.map (Prod.mk (r u).1) + (if D.childLive a t.r u = true ∧ D.tags a ha k cost Δ C t.r (r u).1 g (s l).1 = (r u).2 + then some (D.position a ha g (s l).1, (s l).2) else none) = + some (host, cellIndex _ w.2, slot i) ↔ (u, g, l) = (dest, block, s.symm (suf, slot i)) + constructor + · intro h + split_ifs at h with hh + · obtain ⟨hu, hg, hslot⟩ := (by simpa only [Option.map_some, Option.some.injEq, Prod.mk.injEq] + using h) + obtain ⟨hg', hs'⟩ := (position_iff g _ _).mp hg + have hi : (r u).2 = intervalCode n iv := by rw [← hh.2, hu, hg', hs']; exact ht + exact Prod.ext (r.injective ((Prod.ext hu hi).trans he.symm)) + (Prod.ext hg' (s.eq_symm_apply.mpr (Prod.ext hs' hslot))) + · cases h + · intro eq + simp only [Prod.mk.injEq] at eq + rw [eq.1, eq.2.1, eq.2.2, he, Equiv.apply_symm_apply] + simp only [ht, hv, and_self, ite_true, Option.map_some, Option.some.injEq, Prod.mk.injEq, + true_and, and_true] + exact (position_iff _ _ _).mpr ⟨rfl, rfl⟩ + +variable (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (hd : 0 < Δ) + (rm : (t.state hb).Room e) (ready : t.Ready hb hc M rm cap) (valid : K.Valid (t.layout hc)) + {x y : Wire} {Z : Border F t.T x y t.x t.y} {labels : A.label.obj} + (q : A.Encloses (t.r, labels) t.G Z) + +open scoped Classical in +theorem grouped_moves (h : q.core = t.p) : + (A.grouped t M e cap K).Moves q (t.encodes hb hc M rm cap K hd ready valid) (A.newSlot t + q.slot) where + positive := A.slot_pos t q.slot q.positive + iff := by + rintro ⟨u, g, l⟩ i + rw [q.frozen, h] + exact A.back_iff t M e cap K hc q.slot i u g l + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Issuing the frozen predecessor and the core predecessor together -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Packing Coloring History Window State.Board + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) + {P : Gadget F} {a : ℕ} {ha : a ≤ D.scheme.h} {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} + {hu : 0 < P.b * z} {hz : 0 < z} {e : ℕ} + (M : Book D.scheme P z hz) (cap : ℕ) (K : Template.Meter) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (hc : Δ ≤ C) + +local notation "n" => (D.scheme.h - a) +local notation "Y" => D.after a Δ C M e cap K +local notation "I" => D.Branch P a ha b k cost Δ C z σ hu + +open scoped Classical in +/-- The quantity computed by `(D.Pointers e).pair (.vec (D.scheme.h - a + A.k) A.pointer)`. -/ +abbrev Supplement (a e : ℕ) := (D.Pointers e).pair (.vec (D.scheme.h - a + A.k) A.pointer) + +open scoped Classical in +/-- Evaluates `((t.move hb hc M rm cap).commands i j, (A.grouped t M e cap K).flags i j)` at the +input `i j`. -/ +def supplement (t : I) (rm : (t.state hb).Room e) : + (Tile.output D.scheme.m a n (A.Supplement a e)).obj := + fun i j => ((t.move hb hc M rm cap).commands i j, (A.grouped t M e cap K).flags i j) + +open scoped Classical in +private theorem tag_eq (s t : I) (v : Site (s.G.V × Cell a) n) (w : Site (t.G.V × Cell a) n) + (he : ((s.board hb).recenter v).look = ((t.board hb).recenter w).look) : + D.tags a ha k cost Δ C s.r (s.p.post.host v.1.1) (cellIndex a v.1.2) = + D.tags a ha k cost Δ C t.r (t.p.post.host w.1.1) (cellIndex a w.1.2) := by + have hh := source_eq he (related_root.widen (by decide : 0 ≤ 2)) + exact congrArg (fun z : (D.WithCount a b).obj => fun i => (z.1.2.2.2.1 i).1) hh + +open scoped Classical in +theorem flags_eq (s t : I) (v : Site (s.G.V × Cell a) n) (w : Site (t.G.V × Cell a) n) + (he : ((s.board hb).recenter v).look = ((t.board hb).recenter w).look) : + (A.grouped s M e cap K).flags (Child.host s.p.post.host n (v.1.1, v.2)) (cellIndex a v.1.2) = + (A.grouped t M e cap K).flags (Child.host t.p.post.host n (w.1.1, w.2)) (cellIndex a w.1.2) + := by + have hv := (D.child_live a s.p _).mpr ⟨(v.1.1, v.2), rfl⟩ + have hw := (D.child_live a t.p _).mpr ⟨(w.1.1, w.2), rfl⟩ + have hblock : v.1.2 = w.1.2 := (agrees he).2 + have hiv : intervalCode n v.2 = intervalCode n w.2 := (agrees he).1.key + funext l + simp only [Relocation.flags, grouped, Template.parent, Child.host_parts, hv, hw] + rw [tag_eq hb s t v w he, hblock, hiv] + +open scoped Classical in +theorem flags_vacant (t : I) (i : B (D.size a)) (j : B a) (hi : D.childLive a t.r i = false) : + (A.grouped t M e cap K).flags i j = fun _ => A.tag none := by + funext l + simp [Relocation.flags, grouped, lookupSeat, hi] + +variable {J : Type*} (ts : J → D.Branch P a ha b k cost Δ C z σ hu) + (rm : ∀ i, ((ts i).state hb).Room e) +local notation "W" => A.Supplement a e + +open scoped Classical in +theorem issue (ready : ∀ i, (ts i).Ready hb hc M (rm i) cap) : + ∃ table : Table F, wd table.1 + wd table.2.1 = D.issueWidth a b Δ C M e cap K W ∧ + ∀ {u v N l : ℕ} {L : Set (Table F)}, + 3 ≤ u → table ∈ L → D.issueWidth a b Δ C M e cap K W ≤ u → + Access F u L (D.scheme.m + D.scheme.d) v N → 2 ^ a * (Walks 8 D.scheme.d (D.WithCount a + b)).width ≤ v → + D.size a ≤ l → 2 ^ (Tile.radius D.scheme.d + ((D.scheme.h - a) + 1)) + ≤ l → 2 ^ (D.degree a Δ C) ≤ l → + Computes F u L (D.Headed a b Δ C) (D.Issued a Δ C M e cap K W) + (fun i => (ts i).head hb) + (fun i => ((ts i).output hb hc M (rm i) cap K, A.supplement M cap K hb hc (ts i) (rm i))) + (fun _ => 1) (D.issueCost a b Δ C M e cap K W v N l) := + D.issue_net hb M cap K W hc ts rm ready (fun i => A.supplement M cap K hb hc (ts i) (rm i)) + ((fun _ _ => BatchDescent.Trail.point D.scheme none), fun _ => A.tag none) + (fun i j v w he => Prod.ext (Template.Branch.commands_eq (ready i) (ready j) he) + (A.flags_eq M cap K hb _ _ v w he)) + (fun i x y hi => Prod.ext ((ts i).commands_vacant hb hc M (rm i) cap x y hi) + (A.flags_vacant M cap K (ts i) x y hi)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Preparing a grouped query from the issued labels and predecessors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Packing Coloring History Window + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) + {P : Gadget F} {a : ℕ} {ha : a ≤ D.scheme.h} {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} + {hu : 0 < P.b * z} {hz : 0 < z} {e : ℕ} + (M : Book D.scheme P z hz) (cap : ℕ) (K : Template.Meter) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (hc : Δ ≤ C) + +local notation "Y" => D.after a Δ C M e cap K +local notation "I" => D.Branch P a ha b k cost Δ C z σ hu +local notation "W" => A.Supplement a e +local notation "Z" => A.Requests Y (D.scheme.h - a + A.k) (D.scheme.d + 1) + +open scoped Classical in +/-- Builds `Query A Y (D.scheme.h - a + A.k) (D.scheme.d + 1) where R` with the specified +`Query`, `old`, `fresh`, `active`. -/ +def query (t : I) (rm : (t.state hb).Room e) (labels : A.label.obj) : + Query A Y (D.scheme.h - a + A.k) (D.scheme.d + 1) where + R := A.grouped t M e cap K + M := t.move hb hc M rm cap + old := (t.r, labels) + fresh := t.output hb hc M rm cap K + active i _ := D.childLive a t.r i + +open scoped Classical in +/-- The grouped cost used in the `Attachment` construction. -/ +def groupedCost (a b Δ C : ℕ) (M : Book D.scheme P z hz) (e cap : ℕ) + (K : Template.Meter) (v N l : ℕ) := + 4 * A.format.width + D.issueCost a b Δ C M e cap K (A.Supplement a e) v N l + + 4 * ((A.format.pair (D.Issued a Δ C M e cap K (A.Supplement a e))).width + + 2 * (A.Requests (D.after a Δ C M e cap K) (D.scheme.h - a + A.k) (D.scheme.d + 1)).width) + +open scoped Classical in +theorem grouped_net {J : Type*} (ts : J → I) (rm : ∀ i, + ((ts i).state hb).Room e) (f : J → A.label.obj) + (ready : ∀ i, (ts i).Ready hb hc M (rm i) cap) : + ∃ table : Table F, wd table.1 + wd table.2.1 = D.issueWidth a b Δ C M e cap K W ∧ + ∀ {u v N l : ℕ} {L : Set (Table F)}, + 3 ≤ u → table ∈ L → D.issueWidth a b Δ C M e cap K W ≤ u → + Access F u L (D.scheme.m + D.scheme.d) v N → 2 ^ a * (Walks 8 D.scheme.d (D.WithCount a + b)).width ≤ v → + D.size a ≤ l → 2 ^ (Tile.radius D.scheme.d + ((D.scheme.h - a) + 1)) + ≤ l → 2 ^ (D.degree a Δ C) ≤ l → + Computes F u L (A.format.pair (D.Headed a b Δ C)) Z + (fun i => (((ts i).r, f i), (ts i).head hb)) + (fun i => (A.query M cap K hb hc (ts i) (rm i) (f i)).requests) + (fun _ => 1) (A.groupedCost a b Δ C M e cap K v N l) := by + obtain ⟨t, wt, run⟩ := A.issue M cap K hb hc ts rm ready + refine ⟨t, wt, ?_⟩ + intro u v N l L h₃ ht hw access hv size radius degree + have send := run h₃ ht hw access hv size radius degree + let old (i : J) : A.format.obj := ((ts i).r, f i) + have keep := Computes.of_map (x := old) (L := L) (Map.circuit h₃ (Circuit.id F A.format)) + (fun _ => rfl) + let X := A.format.pair (D.Issued a Δ C M e cap K W) + let wire (x : X.obj) : (Z).obj := + (x.1, x.2.1, fun i j => ((Y).live x.2.1 i, (x.2.2 i j).1 0, (x.2.2 i j).2)) + have pack : Circuit F X Z wire (X.width + 2 * (Z).width) := by + let pin : (Z).pins → X.pins + | .inl w => .inl w + | .inr (.inl w) => .inr (.inl w) + | .inr (.inr (i, _, .inl w)) => .inr (.inl (.inr (i, .inl (.inl w)))) + | .inr (.inr (i, j, .inr (.inl w))) => .inr (.inr (i, j, .inl (0, w))) + | .inr (.inr (i, j, .inr (.inr w))) => .inr (.inr (i, j, .inr w)) + exact Circuit.project pin (by rintro x (w|w|⟨i, j, w|w|w⟩) <;> rfl) + have h := (keep.par send).comp (Computes.of_map (Map.circuit h₃ pack) + (y := fun i => (A.query M cap K hb hc (ts i) (rm i) (f i)).requests) (fun _ => rfl)) + simp only [one_mul] at h + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Carry.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Carry.lean new file mode 100644 index 0000000000..c16c7b5952 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Carry.lean @@ -0,0 +1,996 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Apply +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanTiles +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanSupplies +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Merge.Program +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Rate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Sweep + +/-! +A map on border spans that respects the named bits and their offsets +must be a bijection on positive lengths. Offset zero proves uniqueness. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Coloring + +variable {F : Type} [Field F] {S U : Scheme F} {x : S.format.obj} {y : U.format.obj} + {a b : Wire} {G H : Diagram F a b} (p : S.Presentation x G) (q : U.Presentation y H) + +open scoped Classical in +private theorem bit_exists (t : S.Span) (j : ℕ) (hj : j < S.borderLen x t) : + ∃ i, (p.boundary i).val.1 = t ∧ (p.boundary i).val.2.val = j := by + unfold borderLen at hj + split_ifs at hj with he + · obtain ⟨i, hi⟩ := p.boundary.surjective ⟨⟨t, ⟨j, hj⟩⟩, he⟩ + exact ⟨i, by rw [hi], by rw [hi]⟩ + · omega + +open scoped Classical in +private theorem bit_lt (i : slots a ⊕ slots b) : + (p.boundary i).val.2.val < S.borderLen x (p.boundary i).val.1 := by + rw [S.len_at] + exact (p.boundary i).val.2.isLt + +open scoped Classical in +/-- The data for the pull construction, including `span`, `bit`. -/ +structure Pull (f : U.Span → S.Span) : Prop where + span : ∀ i, f (q.boundary i).val.1 = (p.boundary i).val.1 + bit : ∀ i, (q.boundary i).val.2.val = (p.boundary i).val.2.val + +namespace Pull +variable {p q} {f : U.Span → S.Span} (h : p.Pull q f) + +include h in +open scoped Classical in +theorem inj {s t : U.Span} (hs : 0 < U.borderLen y s) (ht : 0 < U.borderLen y t) (e : f s = f t) : + s = t := by + obtain ⟨i, rfl, hi⟩ := bit_exists q s 0 hs + obtain ⟨j, rfl, hj⟩ := bit_exists q t 0 ht + rw [h.span, h.span] at e + have hb := (h.bit i).symm.trans (hi.trans (hj.symm.trans (h.bit j))) + have he : p.boundary i = p.boundary j := + Subtype.ext (Sigma.ext e ((Fin.heq_ext_iff (congrArg _ e)).mpr hb)) + rw [p.boundary.injective he] + +open scoped Classical in +/-- Returns `(q.boundary ((p.border_pos t).mp ht).choose).val.1` when `ht : 0 < S.borderLen x t` +holds, and `((0, 0, 0), 0)` otherwise. -/ +def shift (_ : p.Pull q f) (t : S.Span) : U.Span := + if ht : 0 < S.borderLen x t then (q.boundary ((p.border_pos t).mp ht).choose).val.1 else ((0, 0, + 0), 0) + +open scoped Classical in +theorem shift_pos (t : S.Span) (ht : 0 < S.borderLen x t) : + 0 < U.borderLen y (h.shift t) := by + rw [shift, dite_eq_left ht] + exact (q.border_pos _).mpr ⟨_, rfl⟩ + +open scoped Classical in +theorem left_inv (t : S.Span) (ht : 0 < S.borderLen x t) : f (h.shift t) = t := by + rw [shift, dite_eq_left ht, h.span] + exact ((p.border_pos t).mp ht).choose_spec + +include h in +open scoped Classical in +theorem pos (s : U.Span) (hs : 0 < U.borderLen y s) : 0 < S.borderLen x (f s) := by + obtain ⟨i, rfl⟩ := (q.border_pos s).mp hs + exact (p.border_pos _).mpr ⟨i, (h.span i).symm⟩ + +open scoped Classical in +theorem right_inv (s : U.Span) (hs : 0 < U.borderLen y s) : h.shift (f s) = s := + h.inj (h.shift_pos _ (h.pos s hs)) hs (h.left_inv _ (h.pos s hs)) + +open scoped Classical in +theorem at_pin (i : slots a ⊕ slots b) : + h.shift (p.boundary i).val.1 = (q.boundary i).val.1 := by + rw [← h.span i] + exact h.right_inv _ ((q.border_pos _).mpr ⟨i, rfl⟩) + +open scoped Classical in +theorem length (t : S.Span) (ht : 0 < S.borderLen x t) : + U.borderLen y (h.shift t) = S.borderLen x t := by + apply le_antisymm <;> apply le_of_not_gt + · intro hh + obtain ⟨i, hi, hj⟩ := bit_exists q _ _ hh + have hb := p.bit_lt i + rw [← h.bit i, hj, ← h.span i, hi, h.left_inv t ht] at hb + exact hb.false + · intro hh + obtain ⟨i, hi, hj⟩ := bit_exists p _ _ hh + have hb := q.bit_lt i + rw [h.bit i, hj, ← h.at_pin i, hi] at hb + exact hb.false + +end Pull +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- A destination block advertises its exposed spans by their old local addresses. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (Y : Template F) + (k z height : ℕ) + +open scoped Classical in +/-- The maximum of the quantities in `(D.scheme.h + (A.k + A.e)) (Y.scheme.h + (k + A.spanBits +Y))`. -/ +abbrev carryRows := max (D.scheme.h + (A.k + A.e)) (Y.scheme.h + (k + A.spanBits Y)) + +namespace Carry + +open scoped Classical in +/-- The value specified by `Format.pair (.addr (A.transport Y k).ℓ) (.vec k A.pointer)`. -/ +abbrev Ask := Format.pair (.addr (A.transport Y k).ℓ) (.vec k A.pointer) +open scoped Classical in +/-- The quantity computed by `Format.vec k (.vec (A.spanBits Y) (SpanPlan.header (height + 1) z +(A.carryRows Y k)))`. -/ +abbrev Reply := Format.vec k (.vec (A.spanBits Y) (SpanPlan.header (height + + 1) z (A.carryRows Y k))) +open scoped Classical in +/-- Computes the grid by the application `Format.vec Y.scheme.m (.vec Y.scheme.h M)`. -/ +abbrev Grid (M : Format) := Format.vec Y.scheme.m (.vec Y.scheme.h M) +open scoped Classical in +/-- The quantity computed by `SpanPlan.entries (height + 1) z (A.carryRows Y k)`. -/ +abbrev Entry := SpanPlan.entries (height + 1) z (A.carryRows Y k) + +open scoped Classical in +/-- The value specified by `(A.scheme.spanOrd i).castLE (Nat.pow_le_pow_right (by decide) +(le_max_left ..))`. -/ +def left (i : A.scheme.Span) : B (A.carryRows Y k) := + (A.scheme.spanOrd i).castLE (Nat.pow_le_pow_right (by decide) (le_max_left ..)) + +open scoped Classical in +/-- The value specified by `((A.transport Y k).scheme.spanOrd i).castLE (Nat.pow_le_pow_right +(by decide) (le_max_right ..))`. -/ +def right (i : (A.transport Y k).scheme.Span) : B (A.carryRows Y k) := + ((A.transport Y k).scheme.spanOrd i).castLE (Nat.pow_le_pow_right (by decide) (le_max_right ..)) + +open scoped Classical in +/-- The value specified by `((s, v.2), Fin.ofNat _ b.val)`. -/ +def source (s : B D.scheme.m) (v : A.pointer.obj) (b : B (A.spanBits Y)) : A.scheme.Span := + ((s, v.2), Fin.ofNat _ b.val) + +open scoped Classical in +/-- The reply of type `(Reply A Y k z height).obj`, constructed using `(A.transport Y k).decode +x.1`. -/ +def reply (x : (Ask A Y k).obj) : (Reply A Y k z height).obj := fun j b => + let r := (A.transport Y k).decode x.1 + let w := if r.peer j b = none then r.width j b else 0 + (0, Fin.ofNat _ w, left A Y k (source A Y 0 (x.2 j) b)) + +end Carry +open Carry + +open scoped Classical in +/-- The quantity computed by `(Ask A Y k).width + (Reply A Y k z height).width`. -/ +def carryWidth := (Ask A Y k).width + (Reply A Y k z height).width + +open scoped Classical in +/-- The indexed operation `weightTable (A := Ask A Y k) (D := Reply A Y k z height) (reply A Y k +z height) (fun _ => (1 : F))`. -/ +def carryGate := weightTable (A := Ask A Y k) (D := Reply A Y k z height) + (reply A Y k z height) (fun _ => (1 : F)) + +open scoped Classical in +theorem carry_arity : wd (A.carryGate Y k z height).1 + wd (A.carryGate Y k z height).2.1 = + A.carryWidth Y k z height := by + simp only [carryGate, carryWidth, weightTable, lookup, wd_word] + +open scoped Classical in +/-- The value specified by `(A.Requests Y k p).pair (A.transport Y k).format`. -/ +abbrev carryInput (p : ℕ) := (A.Requests Y k p).pair (A.transport Y k).format + +open scoped Classical in +/-- The construction uses `A.carryRows Y k` for its intermediate `n`. -/ +def carryPrep (p : ℕ) := + let n := A.carryRows Y k + 1000 * ((A.carryInput Y k p).width + 2 ^ Y.scheme.m * 2 ^ Y.scheme.h * (1 + + A.carryWidth Y k z height) + + (2 ^ Y.scheme.m + 2 ^ D.scheme.m * 2 ^ z) * 2 ^ n * (110 + 4 * (z + n + height)) ^ 200 + + SpanPlan.emitCost D.scheme.m Y.scheme.m (height + 1) z n) + +open scoped Classical in +/-- The carry cost used in the `Attachment` construction. -/ +def carryCost (A : Attachment D) (Y : Template F) (k p z : ℕ) + (x y : Wire) (height : ℕ) (W : Rounds.Contraction.Prices F) := + A.carryPrep Y k z height p + + W.shipment (A.transport Y k).format.width D.scheme.m (volume x y D.scheme.m) height + Y.scheme.m (volume x y Y.scheme.m) height z (height + 1) (A.carryRows Y k) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- Exterior span addresses read directly from the relocation tickets. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Carry +open Coloring + +variable {F : Type} [Field F] {D Y : Template F} {A : Attachment D} {k p z height : ℕ} +local notation "U" => A.transport Y k +local notation "V" => scheme (A.transport Y k) +local notation "n" => A.carryRows Y k + +open scoped Classical in +/-- Evaluates `(x.2.2 v b, (x.1.2.2 v b).2.2)` at the input `v b`. -/ +def ask (x : (A.carryInput Y k p).obj) : (Grid Y (Ask A Y k)).obj := + fun v b => (x.2.2 v b, (x.1.2.2 v b).2.2) + +open scoped Classical in +/-- The list of type `SpanPlan.Entries Y.scheme.m (height + 1) z n`, constructed using +`(V).spanItem v ⟨j.val, h⟩`. -/ +def list (x : (Grid Y (Reply A Y k z height)).obj) : SpanPlan.Entries Y.scheme.m (height + 1) z n := + fun v j => if h : j.val < 2 ^ (Y.scheme.h + (k + A.spanBits Y)) then + let t := (V).spanItem v ⟨j.val, h⟩ + x v t.1.2.1 t.1.2.2 t.2 + else (0, 0, 0) + +open scoped Classical in +/-- The indexed operation `list (A := A) (Y := Y) (k := k) (z := z) (height := height) (fun v b +=> reply A Y k z height (ask x v b))`. -/ +def take (z height : ℕ) (x : (A.carryInput Y k p).obj) := + list (A := A) (Y := Y) (k := k) (z := z) (height := height) + (fun v b => reply A Y k z height (ask x v b)) + +open scoped Classical in +theorem list_at (x : (Grid Y (Reply A Y k z height)).obj) (t : (V).Span) : + list x t.1.1 (right A Y k t) = x t.1.1 t.1.2.1 t.1.2.2 t.2 := by + unfold list + have ht : (right A Y k t).val < 2 ^ (Y.scheme.h + (k + A.spanBits Y)) := ((V).spanOrd t).isLt + rw [dite_eq_left ht] + change (let s := (V).spanItem t.1.1 ((V).spanOrd t); x t.1.1 s.1.2.1 s.1.2.2 s.2) = _ + rw [Scheme.spanItem_spanOrd] + +open scoped Classical in +theorem list_cover (x : (Grid Y (Reply A Y k z height)).obj) (v : B Y.scheme.m) (i : B n) + (hi : 0 < (list x v i).2.1.val) : ∃ t : (V).Span, t.1.1 = v ∧ right A Y k t = i := by + unfold list at hi + split at hi + · rename_i he + refine ⟨(V).spanItem v ⟨i.val, he⟩, rfl, ?_⟩ + apply Fin.ext + change ((V).spanOrd _).val = _ + rw [Scheme.spanOrd_spanItem] + · simp at hi + +open scoped Classical in +/-- Computes the pull by the application `source A Y (R.parent t.1.1) (R.flags t.1.1 t.1.2.1 +t.1.2.2) t.2`. -/ +def pull (R : A.Relocation Y k) (t : (V).Span) : A.scheme.Span := + source A Y (R.parent t.1.1) (R.flags t.1.1 t.1.2.1 t.1.2.2) t.2 + +open scoped Classical in +theorem pull_at (R : A.Relocation Y k) (old : A.format.obj) (t : (V).Span) (s : A.scheme.Span) + (hk : R.kept old t.1 = some s.1) (hs : t.2 = A.outer Y s.2) : pull R t = s := by + obtain ⟨v, hv, hp⟩ := Option.map_eq_some_iff.mp (Option.filter_eq_some_iff.mp hk).1 + unfold pull source Relocation.flags + apply Prod.ext + · rw [hv] + exact hp + · apply Fin.ext + change t.2.val % 2 ^ A.e = s.2.val + rw [hs] + exact Nat.mod_eq_of_lt s.2.isLt + +open scoped Classical in +theorem message (Q : A.Query Y k p) (r : (U).format.obj) + {size : ℕ} (fit : (V).Fits ((U).rows r) size height) (t : (V).Span) : + let v := take z height (Q.requests, r) t.1.1 (right A Y k t) + v.1 = 0 ∧ v.2.1.val = (V).borderLen ((U).rows r) t ∧ v.2.2 = left A Y k (pull Q.R t) := by + have len : (V).borderLen ((U).rows r) t < 2 ^ (height + 1) := + (((V).border_le _ t).trans (fit.2 _)).trans_lt (Nat.pow_lt_pow_right (by decide) + (Nat.lt_succ_self _)) + unfold take + rw [list_at] + refine ⟨rfl, ?_, rfl⟩ + let label := (U).decode (r.2 t.1.1 t.1.2.1) + let w := if label.peer t.1.2.2 t.2 = none then label.width t.1.2.2 t.2 else 0 + have eq : (V).borderLen ((U).rows r) t = w := by + unfold Scheme.borderLen Scheme.peer + simp only [Option.map_eq_none_iff] + rfl + change w % 2 ^ (height + 1) = _ + rw [← eq, Nat.mod_eq_of_lt len] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Carry +end + +/- A destination declaration determines the two lists of span headers. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring + +variable {F : Type} [Field F] {S U : Scheme F} {x : S.format.obj} {y : U.format.obj} + {a b : Wire} {G H : Diagram F a b} {p : S.Presentation x G} {q : U.Presentation y H} + {m m' w z n : ℕ} + +/-- Evaluates `take (child.symm (v, c))` at the input `c`. -/ +def family (child : B m' ≃ B m × B z) (take : Entries m' w z n) (v : B m) : + (Scatter.Family w z n).obj := fun c => take (child.symm (v, c)) + +/-- Evaluates `Scatter.run (family child take v)` at the input `v`. -/ +def returnTo (child : B m' ≃ B m × B z) (take : Entries m' w z n) : Entries m w z n := + fun v => Scatter.run (family child take v) + +theorem spec_of_pull {f : U.Span → S.Span} (h : p.Pull q f) + (child : B U.m ≃ B S.m × B z) (left : S.Span → B n) (right : U.Span → B n) + (take : Entries U.m w z n) + (hl : ∀ i, (left i).val = (S.spanOrd i).val) (hr : ∀ i, (right i).val = (U.spanOrd i).val) + (parent : ∀ t, (child t.1.1).1 = (f t).1.1) + (message : ∀ t, let v := take t.1.1 (right t) + v.1 = 0 ∧ v.2.1.val = U.borderLen y t ∧ v.2.2 = left (f t)) + (cover : ∀ v i, 0 < (take v i).2.1.val → ∃ t, t.1.1 = v ∧ right t = i) : + Spec p q child h.shift (fun _ => 0) left (right ∘ h.shift) (returnTo child take) take := by + have owner (t) (ht : 0 < S.borderLen x t) : (child (h.shift t).1.1).1 = t.1.1 := by + rw [parent, h.left_inv t ht] + have incoming (v i) (hi : 0 < (take v i).2.1.val) : + ∃ t, 0 < S.borderLen x t ∧ (h.shift t).1.1 = v ∧ right (h.shift t) = i := by + obtain ⟨s, rfl, rfl⟩ := cover v i hi + rw [(message s).2.1] at hi + exact ⟨f s, h.pos s hi, by rw [h.right_inv s hi], by rw [h.right_inv s hi]⟩ + have msg (t) (ht : 0 < S.borderLen x t) : + let v := take (h.shift t).1.1 (right (h.shift t)) + v.1 = 0 ∧ v.2.1.val = S.borderLen x t ∧ v.2.2 = left t := by + simpa only [h.left_inv t ht, h.length t ht] using message (h.shift t) + have source (v i) (hi : 0 < (returnTo child take v i).2.1.val) : + ∃ t, 0 < S.borderLen x t ∧ t.1.1 = v ∧ left t = i ∧ + returnTo child take v i = ((child (h.shift t).1.1).2, + (take (h.shift t).1.1 (right (h.shift t))).2) := by + obtain ⟨c, j, hj, hk, he⟩ := Scatter.origin (family child take v) i hi + obtain ⟨t, ht, hv, hj'⟩ := incoming _ _ hj + have eq : child (h.shift t).1.1 = (v, c) := (congrArg child hv).trans (child.apply_symm_apply _) + refine ⟨t, ht, (owner t ht).symm.trans (congrArg Prod.fst eq), ?_, ?_⟩ + · rw [← (msg t ht).2.2, hv, hj'] + exact hk + · rw [eq, hv, hj'] + exact he + refine ⟨owner, fun i => ⟨(h.at_pin i).symm, by simpa using h.bit i⟩, ?_, ?_, ?_, msg, ?_, + incoming⟩ + · intro i j _ _ _ he + change (left i).val < (left j).val + rwa [hl, hl] + · intro i j _ _ _ he + left + change (right (h.shift i)).val < (right (h.shift j)).val at he + rwa [hr, hr] at he + · intro t ht + let c := (child (h.shift t).1.1).2 + have he : child.symm (t.1.1, c) = (h.shift t).1.1 := by + rw [← owner t ht] + exact child.symm_apply_apply _ + have hm := msg t ht + have hv : 0 < (returnTo child take t.1.1 (left t)).2.1.val := by + rw [← hm.2.2, ← he] + apply Scatter.positive (family child take t.1.1) c (right (h.shift t)) + unfold family + rw [he, hm.2.1] + exact ht + obtain ⟨s, hs, ho, hl', hi⟩ := source _ _ hv + have eq : s = t := S.ext_span ho (Fin.ext ((hl s).symm.trans ((congrArg Fin.val hl').trans (hl + t)))) + subst s + rw [hi] + exact ⟨rfl, hm.2⟩ + · intro v i hi + obtain ⟨t, ht, hv, hj, _⟩ := source v i hi + exact ⟨t, ht, hv, hj⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- Running a single scatter at each parent. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring + +/-- The quantity computed by `(2 ^ m' + 2 ^ m * 2 ^ z) * 2 ^ n * (110 + 4 * (z + n + w)) ^ 200`. -/ +def returnBudget (m m' w z n : ℕ) := + (2 ^ m' + 2 ^ m * 2 ^ z) * 2 ^ n * (110 + 4 * (z + n + w)) ^ 200 + +variable (F : Type) [Field F] {m m' w z n : ℕ} (child : B m' ≃ B m × B z) +local notation "H" => entries (w + 1) z n +local notation "I" => Format.vec m' H +local notation "P" => Format.vec m (Scatter.Family (w + 1) z n) +local notation "O" => Ports m m' H H +local notation "Bgt" => returnBudget m m' w z n + +private theorem cap_header : (header (w + 1) z n).width ≤ (110 + 4 * (z + n + w)) ^ 200 := by + calc + _ ≤ 110 + 4 * (z + n + w) := by + rw [header, Format.width_pair, Format.width_pair, Format.width_addr z, + Format.width_addr (w + 1), Format.width_addr n] + omega + _ ≤ _ := by exact Nat.le_self_pow (by decide) _ + +theorem return_width : (I).width ≤ Bgt := by + simp only [entries, Format.width_vec, returnBudget, ← mul_assoc] + exact Nat.mul_le_mul (Nat.mul_le_mul_right _ (Nat.le_add_right ..)) cap_header + +private theorem family_width : (P).width ≤ Bgt := by + simp only [Scatter.Family, entries, Format.width_vec, returnBudget, ← mul_assoc] + exact Nat.mul_le_mul (Nat.mul_le_mul_right _ (Nat.le_add_left ..)) cap_header + +theorem return_net : Circuit F I O (fun x => (returnTo child x, x)) (16 * Bgt) := by + let budget := 2 ^ (Scatter.depth z n) * (110 + 4 * (z + n + w)) ^ 200 + have one : Circuit F (Scatter.Family (w + 1) z n) H Scatter.run budget := by + obtain ⟨c, hc, ht⟩ := Scatter.cheap F (w + 1) z n + apply hc.mono + calc + _ ≤ 2 ^ (Scatter.depth z n) * (100 + (4 + 3 * (z + n + (w + 1)))) ^ 200 + := (Nat.le_add_left _ _).trans ht + _ ≤ budget := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) _) + have split : Circuit F I P (family child) ((I).width + 2 * (P).width) := by + exact Circuit.project (fun i => (child.symm (i.1, i.2.1), i.2.2)) (fun _ _ => rfl) + have move := (split.comp (Circuit.map _ (fun _ : B m => one))).pair (Circuit.id F I) + have hw : 2 ^ m * budget ≤ 2 * Bgt := by + simp only [budget, Scatter.depth, returnBudget, pow_add, pow_one] + rw [show ∀ v : ℕ, 2 ^ m * (2 * (2 ^ z * 2 ^ n) * v) + = 2 * ((2 ^ m * 2 ^ z) * 2 ^ n * v) by intro v; ac_rfl] + gcongr + exact Nat.le_add_left .. + have hi : (I).width ≤ Bgt := return_width + have hp : (P).width ≤ Bgt := family_width + exact move.mono (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- # Correctness of the two fragment orders -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring + +variable {F : Type} (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +/-- Computes the skip by the application `start S r q.1 q.2`. -/ +abbrev skip (q : S.Span) := start S r q.1 q.2 + +open scoped Classical in +private theorem left_order (t u : S.Span) (h : S.spanOrd t < S.spanOrd u) : + pos S r false t < pos S r false u := by + simpa [pos, slot, cat, Scheme.rowIndex_lt, Scheme.spanOrd, Scheme.row] using h + +open scoped Classical in +private theorem right_order (t u : S.Span) (ht : 0 < S.borderLen r t) (hu : 0 < S.borderLen r u) + (he : t.1.1 = u.1.1) (h : pos S r true t < pos S r true u) : + (scheme S).spanOrd (span S r t) < (scheme S).spanOrd (span S r u) ∨ + (span S r t = span S r u ∧ skip S r t + S.borderLen r t ≤ skip S r u) := by + obtain ⟨v, i⟩ := t + obtain ⟨w, j⟩ := u + simp only [pos, slot, cat, Scheme.rowIndex_lt, ite_true] at h + have go : v.2.1 < w.2.1 ∨ v.2.1 = w.2.1 ∧ + (v.2.2 < w.2.2 ∨ v.2.2 = w.2.2 ∧ band S r v i < band S r w j) → + (scheme S).spanOrd (span S r (v, i)) < (scheme S).spanOrd (span S r (w, j)) := by + intro h + simpa [Scheme.spanOrd, Scheme.row, Scheme.rowIndex_lt, span] using h + rcases h with h|⟨a, h|⟨b, h|⟨c, h⟩⟩⟩ + · exact .inl (go (.inl h)) + · exact .inl (go (.inr ⟨a, .inl h⟩)) + · exact .inl (go (.inr ⟨a, .inr ⟨b, h⟩⟩)) + · have he' : v = w := Prod.ext he (Prod.ext a b) + subst w + have border (q : S.Span) (hq : 0 < S.borderLen r q) : S.peer r q = none := by + by_contra hh; simp [Scheme.borderLen, hh] at hq + refine .inr ⟨Prod.ext rfl c, ?_⟩ + rw [Scheme.borderLen, ite_eq_left (border _ ht)] + exact ordered S r (border _ ht) (border _ hu) c h + +variable [Field F] {x y : Wire} {D : Template F} {data : D.format.obj} + {P : Rounds.Board F x y D.scheme.h} (p : D.Presents data P) + (hl : ∀ e, P.diagram.source e ≠ P.diagram.target e) (hk : D.scheme.k = 0) + +open scoped Classical in +theorem boundary (i : slots x ⊕ slots y) : + let a := (p.pres.boundary i).val + let b := ((present p hl hk).pres.boundary i).val + b.1 = span D.scheme data.1 a.1 ∧ b.2.val = skip D.scheme data.1 a.1 + a.2.val := by + cases i with + | inl i => exact ends p hl hk (.inl (.inl i)) + | inr i => exact ends p hl hk (.inr (.inl i)) + +include p hl hk in +open scoped Classical in +theorem load (i : B D.scheme.m) : + (scheme D.scheme).load (rows D.scheme data.1) i = D.scheme.load data.1 i := by + let e := ((present p hl hk).pres.boundary.symm.trans p.pres.boundary) + apply Fintype.card_congr + apply Equiv.subtypeEquiv e + intro a + obtain ⟨t, rfl⟩ := (present p hl hk).pres.boundary.surjective a + have he := congrArg (fun p => p.1.1) (boundary p hl hk t).1 + simp only [e, Equiv.trans_apply, Equiv.symm_apply_apply] + exact Iff.of_eq (congrArg (· = i) he) + +open scoped Classical in +theorem spec {w K V : ℕ} (fit : D.scheme.Fits data.1 V K) (hw : K < w) : + SpanPlan.Spec p.pres (present p hl hk).pres (Match.rowIndex D.scheme.m 0) + (span D.scheme data.1) (skip D.scheme data.1) (pos D.scheme data.1 false) (pos D.scheme + data.1 true) + ((program D.scheme w).send data.1) ((program D.scheme w).take data.1) := by + let S := D.scheme + let r := data.1 + have width (q : S.Span) : S.borderLen r q < 2 ^ w := (S.border_le r q).trans_lt + ((fit.2 _).trans_lt (Nat.pow_lt_pow_right (by decide) hw)) + rw [send, take] + refine ⟨?_, boundary p hl hk, fun t u _ _ _ => left_order _ _ t u, right_order S r, ?_, ?_, ?_, + ?_⟩ + · intro t _; rw [no_suffix]; rfl + · intro t _ + rw [row_entry, no_suffix] + exact ⟨rfl, Nat.mod_eq_of_lt (width t), rfl⟩ + · intro t _ + change let a := list S r w true t.1.1 (pos S r true t) + a.1 = 0 ∧ a.2.1.val = S.borderLen r t ∧ a.2.2 = pos S r false t + rw [row_entry] + exact ⟨rfl, Nat.mod_eq_of_lt (width t), rfl⟩ + · exact row_cover S r w false + · exact row_cover S r w true + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- # Implementing the span merge as an exact layer transformation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring Rounds + +variable {F : Type} [Field F] {x y : Wire} (L : Layer F x y) + (hl : L.Loopless) (hk : L.template.scheme.k = 0) + +local notation "D" => L.template +local notation "S" => L.template.scheme +local notation "m" => L.template.scheme.m + +open scoped Classical in +/-- The layer changes its presentation and dictionary while preserving +the state, the board and the space allocated for exterior bits. -/ +abbrev layer : Layer F x y where + template := template (D) + volume := L.volume + height := L.height + State := L.State + board := L.board + data i := record (D) (L.data i) + presents i := present (L.presents i) (hl i) hk + fits i := by + have he := funext (load (L.presents i) (hl i) hk) + change (scheme (S)).Fits (rows (S) (L.data i).1) _ _ + unfold Scheme.Fits + rw [he] + exact L.fits i + +open scoped Classical in +theorem ready {g T : ℕ} {H θ : ℝ} (h : L.Ready g T H θ) : + (layer L hl hk).Ready g T H θ := h + +open scoped Classical in +theorem loopless : (layer L hl hk).Loopless := hl + +open scoped Classical in +/-- The quantity computed by `program (S) (L.height + 1)`. -/ +abbrev script := program (S) (L.height + 1) + +open scoped Classical in +theorem supplies (i : L.State) : + (L.presents i).pres.Supplies ((layer L hl hk).presents i).pres + (L.fits i) ((layer L hl hk).fits i) ((script L).commands (L.data i).1) := by + have hd := spec (L.presents i) (hl i) hk (L.fits i) (Nat.lt_succ_self _) + have h := hd.supplies (L.fits i) ((layer L hl hk).fits i) + (Nat.lt_succ_self _) (Nat.lt_succ_self _) + simp only [Equiv.symm_apply_apply] at h + exact h + +variable (W : Contraction.Prices F) + +open scoped Classical in +/-- The bound obtained by adding the component charges `20 * (D).format.width + (4 * cost (D) + +(4 * ((D).format.width + 2 * (S).format.width) + SpanProgram.cost (S) 0 (L.height + 1) (dim +(S))))`. -/ +def controlCost := 20 * (D).format.width + (4 * cost (D) + + (4 * ((D).format.width + 2 * (S).format.width) + SpanProgram.cost (S) 0 (L.height + 1) (dim (S)))) + +open scoped Classical in +/-- The bound obtained by adding the component charges `controlCost L + W.shipment (template +(D)).format.width m L.volume L.height m L.volume L.height 0 (L.height + 1) ((S).h + dim +(S))`. -/ +def layerCost := controlCost L + W.shipment (template (D)).format.width + m L.volume L.height m L.volume L.height 0 (L.height + 1) ((S).h + dim (S)) + +variable {u : ℕ} {A : Set (Table F)} (hu : 3 ≤ u) + (size : SpanProgram.size L.template.scheme 0 (L.height + 1) (dim L.template.scheme) ≤ u) + (gate : (script L).gate ∈ A) + +include hu size gate in +open scoped Classical in +private theorem controls : + Computes F u A (D).format + ((template (D)).format.pair (Payload.Script m m 0 (L.height + 1) ((S).h + dim (S)))) + L.data (fun i => (record (D) (L.data i), (script L).commands (L.data i).1)) + (fun _ => 1) (controlCost L) := by + have rows : Circuit F (D).format (S).format Prod.fst ((D).format.width + 2 * (S).format.width) := + Circuit.project Sum.inl (fun _ _ => rfl) + have metaNet := Map.circuit (L := A) hu (record_net (D)) + have cmd := (Map.circuit (L := A) hu rows).comp ((script L).action hu size gate) + have h := Computes.pair hu (Computes.of_map (x := L.data) (y + := record (D) ∘ L.data) metaNet (fun _ => rfl)) + (Computes.of_map (x := L.data) (y := fun i => (script L).commands (L.data i).1) cmd (fun _ + => rfl)) + simp only [mul_one] at h + exact h + +include hu size gate in +open scoped Classical in +theorem transforms (hm : 1 ≤ m) (ht : (L.height + 1) * (2 ^ m + 2 ^ m) < 2 ^ W.w) : + Transforms F u A L.snapshot (layer L hl hk).snapshot (layerCost L W) := by + let J := L.State × Val x × Val y + let Q := layer L hl hk + have hp := (controls L hu size gate).restrict (fun i : J => i.1) + have hs := W.ship (p := 0) (k := L.height) (k' := L.height) + (V := L.volume) (V' := L.volume) hu hm hm (by simpa using ht) + (y := fun i : J => Q.data i.1) (cmd := fun i : J => (script L).commands (L.data i.1).1) + (f := fun i : J => (L.encoding.frame i.1 i.2.1 i.2.2).2) + (g := fun i : J => (Q.encoding.frame i.1 i.2.1 i.2.2).2) + hp (fun i b => (supplies L hl hk i.1).carries i.2.1 i.2.2 b) + exact Transforms.deterministic id (fun _ => rfl) hs + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- The commands generated by the relocation agree with the named boundaries. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Carry +open Coloring + +variable {F : Type} [Field F] {D Y : Template F} {A : Attachment D} {k p z height : ℕ} +local notation "U" => A.transport Y k +local notation "n" => A.carryRows Y k + +open scoped Classical in +/-- The value specified by `(Match.rowIndex m' z).symm (child.symm (Match.rowIndex m z i), 0)`. -/ +def peer {m m' z : ℕ} (child : B m' ≃ B m × B z) (i : B (m + z)) := + (Match.rowIndex m' z).symm (child.symm (Match.rowIndex m z i), 0) + +variable (child : B Y.scheme.m ≃ B D.scheme.m × B z) + +open scoped Classical in +/-- The commands of type `(Payload.Script D.scheme.m Y.scheme.m z (height + 1) n).obj`, +constructed using `take z height i`. -/ +def commands (height : ℕ) (i : (A.carryInput Y k p).obj) : + (Payload.Script D.scheme.m Y.scheme.m z (height + 1) n).obj := + let t := take z height i + SpanPlan.emit (peer child) (SpanPlan.returnTo child t, t) + +variable {x y : Wire} {v v' : ℕ} (Q : A.Query Y k p) (X : A.Data x y v) (Z : Data (A.transport Y k) + x y v') + +open scoped Classical in +/-- The preserved of type `Prop` for the given inputs. -/ +def Preserved : Prop := ∀ i, let j := (Z.q.pres.boundary i).val; let t := (X.q.pres.boundary i).val + Q.R.kept Q.old j.1.1 = some t.1.1 ∧ j.1.2 = A.outer Y t.1.2 ∧ j.2.val = t.2.val + +open scoped Classical in +theorem supplies (hx : X.Fits height) (hz : Z.Fits height) + (parent : ∀ i, Q.R.parent i = (child i).1) (ok : Preserved Q X Z) : + X.q.pres.Supplies Z.q.pres hx hz (commands child height (Q.requests, Z.raw)) := by + have h : X.q.pres.Pull Z.q.pres (pull Q.R) := + ⟨fun i => pull_at Q.R Q.old _ _ (ok i).1 (ok i).2.1, fun i => (ok i).2.2⟩ + have spec := SpanPlan.spec_of_pull h child (left A Y k) (right A Y k) + (take z height (Q.requests, Z.raw)) (fun _ => rfl) (fun _ => rfl) + (fun t => (parent t.1.1).symm) (message Q _ hz) (list_cover _) + exact spec.supplies hx hz (Nat.lt_succ_self _) (Nat.lt_succ_self _) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Carry +end + +/- Wiring the relocation records into a single dictionary and two prefix scans. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Carry +open Coloring + +variable {F : Type} [Field F] {D Y : Template F} {A : Attachment D} {k p z height : ℕ} +local notation "U" => A.transport Y k +local notation "N" => A.carryRows Y k +local notation "X" => A.carryInput Y k p +local notation "I" => Ask A Y k +local notation "O" => Reply A Y k z height +local notation "T" => Format.vec Y.scheme.m (Entry A Y k z height) +local notation "C" => Payload.Script D.scheme.m Y.scheme.m z (height + 1) N + +open scoped Classical in +private theorem ask_net : Circuit F X (Grid Y I) ask ((X).width + 2 * (Grid Y I).width) := by + let tap : (Grid Y I).pins → (X).pins + | (v, b, .inl i) => .inr (.inr (v, b, i)) + | (v, b, .inr i) => .inl (.inr (.inr (v, b, .inr (.inr i)))) + exact Circuit.project tap (by rintro _ ⟨v, b, i|i⟩ <;> rfl) + +open scoped Classical in +private theorem list_net : Circuit F (Grid Y O) T list ((Grid Y O).width + 34 * (T).width) := by + let H := SpanPlan.header (height + 1) z N + apply Window.Tile.project_const + rintro ⟨v, j, i⟩ + by_cases h : j.val < 2 ^ (Y.scheme.h + (k + A.spanBits Y)) + · let t := (U).scheme.spanItem v ⟨j.val, h⟩ + refine .inl ⟨(v, t.1.2.1, t.1.2.2, t.2, i), ?_⟩ + intro x + change H.code (list x v j) i = _ + rw [list, dite_eq_left h] + rfl + · refine .inr ⟨H.code (0, 0, 0) i, ?_⟩ + intro x + change H.code (list x v j) i = _ + rw [list, dite_eq_right h] + +omit [Field F] in +open scoped Classical in +private theorem grid_width (R : Format) : (Grid Y R).width + = 2 ^ Y.scheme.m * 2 ^ Y.scheme.h * R.width := by + rw [Grid, Format.width_vec, Format.width_vec, mul_assoc] + +open scoped Classical in +theorem prepare {J : Type*} {u : ℕ} {L : Set (Table F)} + (child : B Y.scheme.m ≃ B D.scheme.m × B z) (x : J → (X).obj) + (hu : 3 ≤ u) (hw : A.carryWidth Y k z height ≤ u) (hg : A.carryGate Y k z height ∈ L) : + Computes F u L X (.pair (U).format C) x (fun i => ((x i).2, commands child height (x i))) + (fun _ => 1) (A.carryPrep Y k z height p) := by + let r := SpanPlan.returnBudget D.scheme.m Y.scheme.m height z N + let e := SpanPlan.emitCost D.scheme.m Y.scheme.m (height + 1) z N + let a := 2 ^ Y.scheme.m * 2 ^ Y.scheme.h + have one : Map F u L I O (reply A Y k z height) (1 + (I).width + (O).width) := + Kernel.lookup hw hg + have all := Map.vec _ (fun _ : B Y.scheme.m => Map.vec _ (fun _ : B Y.scheme.h => one)) + have start := Map.circuit (L := L) hu (ask_net (A := A) (Y := Y) (k := k) (p := p)) + have end' := (list_net (A := A) (Y := Y) (k := k) (z := z) (height := height)).comp + ((SpanPlan.return_net F (w := height) (n := N) child).comp (SpanPlan.emit_net (peer child) F)) + have map' := (start.comp all).comp (Map.circuit hu end') + have cmd := Computes.of_map (x := x) (y := fun i => commands child height (x i)) map' (fun _ + => rfl) + have back : Circuit F X (U).format Prod.snd ((X).width + 2 * (U).format.width) := + Circuit.project Sum.inr (fun _ _ => rfl) + have keep := Computes.of_map (x := x) (L := L) (Map.circuit hu back) (fun _ => rfl) + have both := keep.pair hu cmd + simp only [mul_one] at both + refine both.mono ?_ + have he : (T).width ≤ r := SpanPlan.return_width + have hy : (U).format.width ≤ (X).width := + (Nat.le_add_left _ _).trans_eq (Format.width_pair (A.Requests Y k p) (U).format).symm + rw [grid_width, grid_width, ← mul_assoc (2 ^ Y.scheme.m)] + change 20 * (X).width + (4 * ((X).width + 2 * (U).format.width)+ + (4 * ((X).width + 2 * (a * (I).width)) + a * (1 + (I).width + (O).width)+ + 4 * (a * (O).width + 34 * (T).width + (16 * r + e)))) ≤ + 1000 * ((X).width + a * (1 + ((I).width + (O).width)) + r + e) + simp only [mul_add, mul_one] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Carry +end + +/- # Transporting exterior bits through a change of attachment -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring + +variable {F : Type} [Field F] {D Y : Template F} {A : Attachment D} {k p z height : ℕ} + {x y : Wire} {v v' u : ℕ} {L : Set (Table F)} {W : Rounds.Contraction.Prices F} + +theorem carry {I : Type*} (Q : I → A.Query Y k p) (X : I → A.Data x y v) + (Z : I → Data (A.transport Y k) x y v') + (hx : ∀ i, (X i).Fits height) (hz : ∀ i, (Z i).Fits height) + (child : B Y.scheme.m ≃ B D.scheme.m × B z) + (new : ∀ i, (Z i).raw = (Q i).result) + (parent : ∀ i t, (Q i).R.parent t = (child t).1) + (pins : ∀ i, Carry.Preserved (Q i) (X i) (Z i)) + (hu : 3 ≤ u) (hm : 1 ≤ D.scheme.m) (hm' : 1 ≤ Y.scheme.m) + (ht : 2 ^ z * ((height + 1) * (2 ^ D.scheme.m + 2 ^ Y.scheme.m)) < 2 ^ W.w) + (hw : A.carryWidth Y k z height ≤ u) (gate : A.carryGate Y k z height ∈ L) : + Computes F u L ((A.carryInput Y k p).pair (payload x y height D.scheme.m)) + ((A.transport Y k).port x y height) + (fun i : I × Val x × Val y => (((Q i.1).requests, (Q i.1).result), + (X i.1).data (hx i.1) i.2.1 i.2.2)) + (fun i => ((Z i.1).raw, (Z i.1).data (hz i.1) i.2.1 i.2.2)) + (fun _ => 1) (A.carryCost Y k p z x y height W) := by + let src (i : I × Val x × Val y) : (A.carryInput Y k p).obj := ((Q i.1).requests, (Z i.1).raw) + let a (i : I × Val x × Val y) := (X i.1).data (hx i.1) i.2.1 i.2.2 + let b (i : I × Val x × Val y) := (Z i.1).data (hz i.1) i.2.1 i.2.2 + have prep := Carry.prepare child src hu hw gate + have ok (i : I) := Carry.supplies child (Q i) (X i) (Z i) (hx i) (hz i) (parent i) (pins i) + have run := W.ship (f := a) (g := b) hu hm hm' (by simpa only [max_self] using ht) prep + (fun i out => (ok i.1).carries i.2.1 i.2.2 out) + simp only [← new] + exact run + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- +# Cost of merging the restored layer + +Charge global address comparisons once per host. The block charge +uses only local labels and widths, and the coefficient on exterior +volume is independent of the label alphabet. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Rounds Rounds.Contraction BatchDescent.Phase + +variable (i : Restore.Measure) +private abbrev sites := i.m + i.l +private abbrev bits := i.h + i.snd + 1 +private abbrev lanes := 5 + (1 + i.A.e) +private abbrev rank := i.h + lanes i +private abbrev label := (Restore.script i.A.scheme).width + +private def gateSize := label i + i.h + 2 * 2 ^ (lanes i) * (bits i + rank i) + +private def hostCost := 776 * sites i + 1224 + 8 * (100 + sites i + 8) ^ 24 + 560 * bits i + +private def blockCost := + 285 * label i + 289 + 137 * i.h + 26 * 2 ^ (lanes i) * (bits i + rank i) + + 8 * 2 ^ (lanes i) * (100 + (2 * rank i + bits i)) ^ 140 + 840 * 2 ^ (lanes i) * bits i + +private theorem costs {x y : Wire} (L : Layer i.F x y) (u : ℕ) + (ht : L.template = (Restore.result i.A i.N i.r i.s u).sweep) (hh : L.height = i.h + i.snd) : + SpanProgram.size L.template.scheme 0 (L.height + 1) (dim L.template.scheme) = gateSize i ∧ + controlCost L + 4 * (template L.template).format.width = + 2 ^ (sites i) * hostCost i + 2 ^ (sites i + i.h) * blockCost i := by + have hm : L.template.scheme.m = sites i := by rw [ht] + have hH : L.template.scheme.h = i.h := by rw [ht] + have hd : L.template.scheme.d = 3 := by rw [ht] + have he : dim L.template.scheme = lanes i := by + rw [ht]; change 0 + (3 + 2 + (1 + i.A.e)) = _; rw [zero_add] + have hL : L.template.scheme.ℓ = label i := by rw [ht] + have hc : L.template.count = label i := by rw [ht] + have hbits : L.height + 1 = bits i := by rw [hh] + constructor + · simp only [SpanProgram.size_eq, hL, hbits, he, hH, pow_zero, zero_add, gateSize, rank]; rfl + have width : (template L.template).format.width = + 2 ^ (sites i) * (8 * (sites i + 2) + 2 + 2 ^ i.h * (label i + 24 + label i)) := by + rw [Template.width] + change 2 ^ L.template.scheme.m * + (2 ^ L.template.scheme.d * (L.template.scheme.m + 2) + 2 + + 2 ^ L.template.scheme.h * ((scheme L.template.scheme).ℓ + L.template.count)) = _ + rw [label_width, hm, hd, hH, hL, hc] + rfl + unfold controlCost cost + rw [width, Template.width, SpanProgram.price, SpanPlan.emit_price] + have form : L.template.scheme.format.width = + 2 ^ L.template.scheme.m * (2 ^ L.template.scheme.d * L.template.scheme.m + + 2 ^ L.template.scheme.h * L.template.scheme.ℓ) := by + simp [Scheme.format, Fmt.rows] + rw [form, he, hL, hc, hbits, hm, hH, hd] + simp only [hostCost, blockCost, rank, zero_add, add_zero, pow_add, pow_zero, + show 2 ^ 3 = 8 by decide] + generalize (100 + sites i + 8) ^ 24 = a, (100 + (2 * (i.h + lanes i) + bits i)) ^ 140 = b + ring + +private def outer := 1000 + i.c.W + (i.h + i.snd) + (i.h + i.snd) + bits i + rank i +private def long := outer i + sites i + sites i + i.c.w + i.c.w ^ i.c.power +private def host (j : ℕ) := 2 ^ i.l * (hostCost i + 2 * (long i) ^ j + 2 * (outer i) ^ j) +private def block (j : ℕ) := 2 ^ i.l * (blockCost i + 2 * 2 ^ (lanes i) * (outer i) ^ j) + +private theorem certificate : ∃ j, ∀ (i : Restore.Measure) {x y : Wire} (L : Layer i.F x y) (u : ℕ), + L.template = (Restore.result i.A i.N i.r i.s u).sweep → + L.volume = Attachment.volume x y (i.m + i.l) → L.height = i.h + i.snd → + layerCost L i.c ≤ 2 ^ i.m * host i j + 2 ^ (i.m + i.h) * block i j + (wd x + + wd y) * (2 * (outer i) ^ j) := by + obtain ⟨j, hj⟩ := Prices.shipment_bound + refine ⟨j, fun i {x y} L u ht hv hh => ?_⟩ + let w := (template L.template).format.width + have hm : L.template.scheme.m = sites i := by rw [ht] + have hH : L.template.scheme.h = i.h := by rw [ht] + have he : dim L.template.scheme = lanes i := by + rw [ht]; change 0 + (3 + 2 + (1 + i.A.e)) = _; rw [zero_add] + have hc := (costs i L u ht hh).2 + have h := hj i.F i.c w (sites i) L.volume (i.h + i.snd) (sites i) L.volume (i.h + i.snd) + 0 (bits i) (rank i) + simp only [add_zero, pow_zero, mul_one] at h + unfold layerCost + rw [he, hm, hH, hh] + refine (Nat.add_le_add_left h _).trans_eq ?_ + rw [←add_assoc, ←add_assoc, hc] + change 2 ^ (sites i) * hostCost i + 2 ^ (sites i + i.h) * blockCost i + + (2 ^ (sites i) + 2 ^ (sites i)) * ((long i) ^ j + 2 ^ (rank i) * (outer i) ^ j) + + (L.volume + L.volume) * (outer i) ^ j = _ + rw [hv] + unfold host block sites rank Attachment.volume + simp only [pow_add] + ring + +open Restore.Measure + +private theorem sizes : Fast gateSize ∧ Slow hostCost ∧ Fast blockCost ∧ Fast (fun i + => 2 ^ (lanes i)) := by + have a : Fast bits := small_num fun i => by unfold bits Restore.Measure.outer; omega + have b : Fast (fun i => 2 ^ (lanes i)) := by + have hh : Fast (fun i => 2 ^ (1 + i.A.e)) := lines.mono fun i => + Nat.pow_le_pow_right (by decide) (Nat.le_add_left ..) + exact Poly.exp_add (f := fun _ => 5) (constantValue 32) hh + have c : Fast rank := height.add b.of_exp + have d : Slow sites := hosts.add hardware.slow + have C := constantValue + have L j := (constantValue j).slow + refine ⟨(script_size.add height).add (((C 2).mul b).mul (a.add c)), ?_, ?_, b⟩ + · have t := ((L 776).mul d).add (L 1224) + exact (t.add ((L 8).mul ((((L 100).add d).add (L 8)).pow 24))).add ((L 560).mul a.slow) + · have t := (((C 285).mul script_size).add (C 289)).add ((C 137).mul height) + have y := ((C 26).mul b).mul (a.add c) + have z := ((C 8).mul b).mul (((C 100).add (((C 2).mul c).add a)).pow 140) + exact ((t.add y).add z).add (((C 840).mul b).mul a) + +private theorem bounds (j : ℕ) : + Slow (fun i => host i j) ∧ Fast (fun i => block i j) ∧ Poly Restore.Measure.outer (fun i + => 2 * (outer i) ^ j) := by + have s : Poly Restore.Measure.outer outer := by + have t := (Poly.const two 5).mul (Poly.of_le two (fun _ => le_rfl)) + apply t.mono + intro i + unfold outer bits rank lanes Restore.Measure.outer Restore.Measure.n Restore.lineBits + omega + have sf : Fast outer := s.grow small + have r : Slow long := by + have t := (constantValue 8).slow.mul (Poly.of_le long_two (fun _ => le_rfl)) + apply t.mono + intro i + have h := i.small + have h' := Nat.zero_le (i.c.w ^ i.c.power) + unfold long outer bits rank lanes sites Restore.Measure.long + unfold Restore.Measure.outer Restore.Measure.n Restore.lineBits at h + omega + have C := constantValue 2 + have h := sizes + exact ⟨Restore.Measure.copies.slow.mul ((h.2.1.add (C.slow.mul (r.pow j))).add (C.slow.mul + (sf.slow.pow j))), + Restore.Measure.copies.mul (h.2.2.1.add ((C.mul h.2.2.2).mul (sf.pow j))), + (Poly.const two 2).mul (s.pow j)⟩ + +/-- A common polynomial suffices for labeling, control and transport. -/ +theorem price : ∃ K, ∀ (i : Restore.Measure) {x y : Wire} (L : Layer i.F x y) (u : ℕ), + L.template = (Restore.result i.A i.N i.r i.s u).sweep → + L.volume = Attachment.volume x y (i.m + i.l) → L.height = i.h + i.snd → + SpanProgram.size L.template.scheme 0 (L.height + 1) (dim L.template.scheme) ≤ i.short ^ K ∧ + layerCost L i.c ≤ 2 ^ i.m * i.long ^ K + 2 ^ (i.m + i.h) * i.short ^ K + (wd x + + wd y) * i.outer ^ K := by + obtain ⟨j, hj⟩ := certificate + obtain ⟨f, hf⟩ := sizes.1.bound + obtain ⟨t, ht⟩ := (bounds j).1.bound + obtain ⟨s, hs⟩ := (bounds j).2.1.bound + obtain ⟨o, ho⟩ := (bounds j).2.2.bound + refine ⟨f + t + s + o, fun i {x y} L u h hv hh => ?_⟩ + have hl := i.long_two + have hb := i.short_two + have he := i.two + rw [(costs i L u h hh).1] + refine ⟨(hf i).trans (Nat.pow_le_pow_right (by omega) (by omega)), (hj i L u h hv hh).trans ?_⟩ + gcongr + · exact (ht i).trans (Nat.pow_le_pow_right (by omega) (by omega)) + · exact (hs i).trans (Nat.pow_le_pow_right (by omega) (by omega)) + · exact (ho i).trans (Nat.pow_le_pow_right (by omega) (by omega)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Factor.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Factor.lean new file mode 100644 index 0000000000..d7cc17ae9e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Factor.lean @@ -0,0 +1,1050 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Hop +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames + +/-! # Pulling a scalar factor through the attached border -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Border + +variable {F T : Type} [Field F] [Fintype T] {a b x y : Wire} + (Z : Border F T x y a b) {G : Diagram F a b} + {S : Assembly.Scheme F} {r : S.format.obj} + +theorem attach_factor (q : S.Presentation r G) (v : Val x) (w : Val y) : + (Z.attach G).eval v w = Assembly.Fmt.weight S.scalar r * (Z.attach G.sweep).eval v w := by + rw [Z.eval_attach, Z.eval_attach] + simp only [q.sweep_eval, Finset.mul_sum, mul_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Border +end + +/- +# Addresses of the frozen stations after a change of host + +The parent host is shared by all blocks of a child. Within a block, +a short pair of indices suffices to recover the old table and pins. +Unused candidates and the core station require no frozen record. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Packing Coloring + +variable {F T : Type} {D : Template F} (A : Attachment D) (Y : Template F) (k : ℕ) + +open scoped Classical in +/-- Indexes the place by the coordinates of `B Y.scheme.m × B Y.scheme.h × B k`. -/ +abbrev Place (Y : Template F) (k : ℕ) := B Y.scheme.m × B Y.scheme.h × B k + +open scoped Classical in +/-- Computes the pointer by the application `Format.pair .bit (.pair (.addr D.scheme.h) (.addr +A.k))`. -/ +abbrev pointer := Format.pair .bit (.pair (.addr D.scheme.h) (.addr A.k)) + +open scoped Classical in +/-- In the case `none`, this construction gives `(false, 0, 0)`. -/ +def tag : Option (B D.scheme.h × B A.k) → A.pointer.obj + | none => (false, 0, 0) + | some t => (true, t) + +open scoped Classical in +/-- Returns `some x.2` when `x.1` holds, and `none` otherwise. -/ +def untag (x : A.pointer.obj) := if x.1 then some x.2 else none + +open scoped Classical in +theorem untag_tag (x : Option (B D.scheme.h × B A.k)) : A.untag (A.tag x) = x := by + cases x <;> rfl + +open scoped Classical in +/-- The data for the relocation construction, including `parent`, `prev`. -/ +structure Relocation where + /-- The `Relocation` component of type `B Y.scheme.m → B D.scheme.m`. -/ + parent : B Y.scheme.m → B D.scheme.m + /-- The predecessor data of type `B Y.scheme.m → B Y.scheme.h → B k → Option (B D.scheme.h × B + A.k)`. -/ + prev : B Y.scheme.m → B Y.scheme.h → B k → Option (B D.scheme.h × B A.k) + +namespace Relocation +variable {A Y k} (R : A.Relocation Y k) + +open scoped Classical in +/-- Evaluates `A.tag (R.prev i j l)` at the input `i j l`. -/ +def flags : (Format.vec Y.scheme.m (.vec Y.scheme.h (.vec k A.pointer))).obj := + fun i j l => A.tag (R.prev i j l) + +open scoped Classical in +/-- Transforms the indexed data by `(R.prev j.1 j.2.1 j.2.2).map (Prod.mk (R.parent j.1))`. -/ +def back (j : Place Y k) : Option A.scheme.Vtx := + (R.prev j.1 j.2.1 j.2.2).map (Prod.mk (R.parent j.1)) + +open scoped Classical in +/-- Selects the elements of `(R.back j)` satisfying `(fun u => A.live (r.2 u.1 u.2.1) u.2.2 && +decide (u.2.2 ≠ 0))`. -/ +def kept (r : A.format.obj) (j : Place Y k) := + (R.back j).filter (fun u => A.live (r.2 u.1 u.2.1) u.2.2 && decide (u.2.2 ≠ 0)) + +variable [Field F] [Fintype T] {x y a b : Wire} {u v : ℕ} {L : Fringe x y T} + {G : HostNet F L D.scheme.h u} {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} + {r : A.format.obj} {s : Y.format.obj} + (q : A.Encloses r G Z) (p : Y.Encodes s H) (slot : T → B k) + +open scoped Classical in +/-- The data for the moves construction, including `positive`, `iff`. -/ +structure Moves : Prop where + positive : ∀ t, slot t ≠ 0 + iff : ∀ j t, R.back j = some (q.pres.vertex (.inr t)) ↔ + j = (p.post.host (H.park t).1, p.post.block (H.park t).2, slot t) + +open scoped Classical in +theorem active (j : Place Y k) (w : A.scheme.Vtx) (h : R.kept r j = some w) : + ∃ t, w = q.pres.vertex (.inr t) := by + simp only [kept, Option.filter_eq_some_iff, Bool.and_eq_true, decide_eq_true_eq] at h + obtain ⟨t|t, ht⟩ := (q.occupied w).mp h.2.1 + · exact (h.2.2 (by rw [← ht, q.internal])).elim + · exact ⟨t, ht.symm⟩ + +open scoped Classical in +theorem kept_iff (h : R.Moves q p slot) (j : Place Y k) (t : T) : + R.kept r j = some (q.pres.vertex (.inr t)) ↔ + j = (p.post.host (H.park t).1, p.post.block (H.park t).2, slot t) := by + have he := (q.occupied _).mpr ⟨.inr t, rfl⟩ + have hn : (q.pres.vertex (.inr t)).2.2 ≠ 0 := by rw [q.frozen]; exact q.positive t + simp only [kept, Option.filter_eq_some_iff, Bool.and_eq_true, decide_eq_true_eq, he, true_and, + h.iff] + exact and_iff_left hn + +end Relocation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Bounding the number of live frozen stations at one occurrence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment + +open Coloring Packing Finset + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun j => j ≠ 0 ∧ live j = true`. -/ +def occupiedSeats {k : ℕ} (live : B k → Bool) : Finset (B k) := + univ.filter fun j => j ≠ 0 ∧ live j = true + +variable {F T : Type} [Field F] [Fintype T] {x y a b : Wire} {D : Template F} + {A : Attachment D} {r : A.format.obj} {u N : ℕ} {L : Fringe x y T} + {G : HostNet F L D.scheme.h u} {Z : Border F T a b x y} {δ : ℝ} + +open scoped Classical in +/-- Every occupied seat apart from the core pays at least one charge +of size `δ`, and all its charges occur at the same parked location. -/ +theorem Encloses.slot_count (q : A.Encloses r G Z) (hd : 0 < δ) + (charge : ∀ t, δ ≤ L.scale * L.charge t) + (bound : ∀ v i, G.load v i ≤ (N : ℝ) * δ) (v : B D.scheme.m) (i : B D.scheme.h) : + (occupiedSeats (A.live (r.2 v i))).card ≤ N := by + let seats := occupiedSeats (A.live (r.2 v i)) + have image (j) (hj : j ∈ seats) : + ∃ t, q.core.post.host (G.park t).1 = v ∧ q.core.post.block (G.park t).2 = i ∧ q.slot t = j + := by + obtain ⟨hn, hl⟩ := (mem_filter.mp hj).2 + obtain ⟨t | t, ht⟩ := (q.occupied (v, i, j)).mp hl + · rw [q.internal] at ht + exact (hn (congrArg (fun p => p.2.2) ht).symm).elim + · rw [q.frozen] at ht + exact ⟨t, (Prod.mk.inj ht).1, Prod.mk.inj (Prod.mk.inj ht).2⟩ + change seats.card ≤ N + by_cases he : seats.Nonempty + swap + · simp [not_nonempty_iff_eq_empty.mp he] + obtain ⟨j, hj⟩ := he + obtain ⟨t, ht, ht', _⟩ := image j hj + let p := G.park t + let s := univ.filter fun y => G.park y = p + have hsub : seats ⊆ s.image q.slot := by + intro k hk + obtain ⟨y, hy, hy', hslot⟩ := image k hk + have hp : G.park y = p := Prod.ext (q.core.post.host.injective (hy.trans ht.symm)) + (q.core.post.block.injective (hy'.trans ht'.symm)) + exact mem_image.mpr ⟨y, mem_filter.mpr ⟨mem_univ _, hp⟩, hslot⟩ + refine ((card_le_card hsub).trans card_image_le).trans ?_ + have hcost : (s.card : ℝ) * δ ≤ (N : ℝ) * δ := calc + _ = ∑ _ ∈ s, δ := by simp + _ ≤ ∑ y ∈ s, L.scale * L.charge y := sum_le_sum fun y _ => charge y + _ = L.scale * push G.park L.charge p := by + rw [← mul_sum, push] + simp only [s, sum_filter] + congr 1 + apply sum_congr rfl + intro i _ + split <;> rfl + _ ≤ G.load p.1 p.2 := by + unfold HostNet.load + have := G.rate_nonneg + exact (le_add_of_nonneg_left (by positivity)).trans (le_add_of_nonneg_right (by positivity)) + _ ≤ _ := bound _ _ + exact_mod_cast le_of_mul_le_mul_right hcost hd + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Relabeling attachment records without changing any port order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment + +open Coloring Packing + +variable {F T : Type} {D : Template F} (A : Attachment D) (n : ℕ) (read : B n → B A.ℓ) + +/-- Only the label code changes. All local station and span indices are preserved. -/ +abbrev recode : Attachment D where + k := A.k + e := A.e + ℓ := n + decode := A.decode ∘ read + live := A.live ∘ read + charge := A.charge ∘ read + coreSpan := A.coreSpan + +variable [Field F] [Fintype T] {x y a b : Wire} {u : ℕ} {L : Fringe x y T} + {G : HostNet F L D.scheme.h u} {Z : Border F T a b x y} {A n read} + {core : D.format.obj} {old : A.label.obj} {fresh : (A.recode n read).label.obj} + +/-- The recode of type `(A.recode n read).Encloses (core, fresh) G Z` for the given inputs. -/ +def Encloses.recode (q : A.Encloses (core, old) G Z) (h : old = fun i j => read (fresh i j)) : + (A.recode n read).Encloses (core, fresh) G Z := by + subst old + exact { + full := q.full + tether := q.tether + core := q.core + pres := { + vertex := q.pres.vertex + pin := q.pres.pin + cover := q.pres.cover + sample := q.pres.sample + vacant := q.pres.vacant + proper := q.pres.proper + internal := q.pres.internal + input := q.pres.input + output := q.pres.output } + directed := q.directed + occupied := q.occupied + slot := q.slot + positive := q.positive + internal := q.internal + frozen := q.frozen + charge := q.charge + ordered := q.ordered } + +variable (q : A.Encloses (core, old) G Z) (h : old = fun i j => read (fresh i j)) + +@[simp] theorem Encloses.recode_core : (q.recode h).core = q.core := by subst old; rfl +@[simp] theorem Encloses.recode_slot : (q.recode h).slot = q.slot := by subst old; rfl +@[simp] theorem Encloses.recode_vertex : (q.recode h).pres.vertex = q.pres.vertex + := by subst old; rfl + +variable {width height : ℕ} + +omit [Field F] in +include h in +theorem recode_fits (fit : A.scheme.Fits (A.rows (core, old)) width height) : + (A.recode n read).scheme.Fits ((A.recode n read).rows (core, fresh)) width height := by + subst old + exact fit + +theorem Encloses.recode_store (fit : A.scheme.Fits (A.rows (core, old)) width height) + (i : Val a) (j : Val b) : + (A.recode n read).scheme.store _ (recode_fits h fit) ((q.recode h).pres.exterior i j) = + A.scheme.store _ fit (q.pres.exterior i j) := by + subst old + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Enlarging a station's span index without changing its bits or value -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring + +open scoped Classical in +/-- The data for the station construction, including `width`, `value`. -/ +structure Station (F : Type) (e : ℕ) where + /-- The width parameter carried by `Station`, with type `B e → ℕ`. -/ + width : B e → ℕ + /-- The evaluation map carried by `Station`, with type `((Σ j, Fin (width j)) → Bool) → F`. -/ + value : ((Σ j, Fin (width j)) → Bool) → F + +namespace Station +variable {F : Type} {d k e f : ℕ} + +open scoped Classical in +/-- Uses `⟨p.width t, fun x => p.value t (fun s i => x ⟨s, i⟩)⟩` as the representation. -/ +def ofPattern (p : Pattern F d k e) (t : B k) : Station F e := + ⟨p.width t, fun x => p.value t (fun s i => x ⟨s, i⟩)⟩ + +open scoped Classical in +/-- Uses `⟨fun _ => 0, fun _ => 1⟩` as the representation. -/ +def blank [One F] : Station F e := ⟨fun _ => 0, fun _ => 1⟩ + +open scoped Classical in +/-- Indexes the pins by the coordinates of `Σ j, Fin (s.width j)`. -/ +abbrev Pins (s : Station F e) := Σ j, Fin (s.width j) + +variable (s : Station F e) (index : B e ↪ B f) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def size := Function.extend index s.width (fun _ => 0) + +open scoped Classical in +theorem size_at (i : B e) : s.size index (index i) = s.width i := + index.injective.extend_apply _ _ _ + +open scoped Classical in +/-- Reindexes `s.Pins` and `(Σ j, Fin (s.size index j))` by an equivalence. -/ +def embed : s.Pins ≃ (Σ j, Fin (s.size index j)) := by + let g : s.Pins ↪ (Σ j, Fin (s.size index j)) := + Function.Embedding.sigmaMap index (fun i => (finCongr (s.size_at index i).symm).toEmbedding) + refine Equiv.ofBijective g ⟨g.injective, ?_⟩ + rintro ⟨j, i⟩ + by_cases h : j ∈ Set.range index + · obtain ⟨t, rfl⟩ := h + exact ⟨⟨t, i.cast (s.size_at index t)⟩, rfl⟩ + · have hz : s.size index j = 0 := Function.extend_apply' _ _ _ h + exact Fin.elim0 (i.cast hz) + +open scoped Classical in +/-- Uses `⟨s.size index, fun x => s.value (x ∘ s.embed index)⟩` as the representation. -/ +def enlarge : Station F f := ⟨s.size index, fun x => s.value (x ∘ s.embed index)⟩ + +variable {s index} {t : Station F f} (h : t = s.enlarge index) + +open scoped Classical in +/-- Reindexes `s.Pins` and `t.Pins` by an equivalence. -/ +def ports : s.Pins ≃ t.Pins := h.symm ▸ s.embed index + +open scoped Classical in +theorem ports_at (j : s.Pins) : + (ports h j).1 = index j.1 ∧ (ports h j).2.val = j.2.val := by + subst t + exact ⟨rfl, rfl⟩ + +open scoped Classical in +theorem eval_at (x : t.Pins → Bool) : t.value x = s.value (x ∘ ports h) := by + subst t + rfl + +include h in +open scoped Classical in +theorem width_at (j : B e) : t.width (index j) = s.width j := by rw [h]; exact s.size_at index j + +end Station +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- +# The label of a reattached occurrence + +One core table is selected per occurrence. Each frozen station keeps +its old table selector and station number. New peer indices refer to +a common neighbor list and carry no global host names. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring Packing + +variable {F : Type} {D : Template F} (A : Attachment D) (Y : Template F) (k : ℕ) + +open scoped Classical in +/-- The maximum of the quantities in `A.e Y.scheme.e`. -/ +abbrev spanBits := max A.e Y.scheme.e +open scoped Classical in +/-- Computes the inner by the application `Fin.castLEEmb (Nat.pow_le_pow_right (by decide) +(le_max_right ..))`. -/ +def inner : B Y.scheme.e ↪ B (A.spanBits Y) := Fin.castLEEmb (Nat.pow_le_pow_right (by decide) + (le_max_right ..)) +open scoped Classical in +/-- Computes the outer by the application `Fin.castLEEmb (Nat.pow_le_pow_right (by decide) +(le_max_left ..))`. -/ +def outer : B A.e ↪ B (A.spanBits Y) := Fin.castLEEmb (Nat.pow_le_pow_right (by decide) + (le_max_left ..)) + +open scoped Classical in +/-- The value specified by `Format.pair .bit (.pair (.addr A.ℓ) (.addr A.k))`. -/ +abbrev member := Format.pair .bit (.pair (.addr A.ℓ) (.addr A.k)) +open scoped Classical in +/-- Computes the endpoint by the application `Format.pair (.addr Y.scheme.d) (.pair (.addr k) +(.addr (A.spanBits Y)))`. -/ +abbrev endpoint := Format.pair (.addr Y.scheme.d) (.pair (.addr k) (.addr (A.spanBits Y))) +open scoped Classical in +/-- Computes the contact by the application `Format.pair .bit (.pair .bit (A.endpoint Y k))`. -/ +abbrev contact := Format.pair .bit (.pair .bit (A.endpoint Y k)) +open scoped Classical in +/-- The value specified by `Format.pair (.addr Y.scheme.ℓ) (.vec k (A.member.pair (.vec +(A.spanBits Y) (A.contact Y k))))`. -/ +abbrev record := Format.pair (.addr Y.scheme.ℓ) (.vec k (A.member.pair (.vec (A.spanBits Y) + (A.contact Y k)))) + +open scoped Classical in +/-- Indexes the links by the coordinates of `Place Y k × B (A.spanBits Y) → Bool × Option +(A.endpoint Y k).obj`. -/ +abbrev Links := Place Y k × B (A.spanBits Y) → Bool × Option (A.endpoint Y k).obj + +open scoped Classical in +/-- The value specified by `(p.1, p.2.isSome, p.2.getD (0, 0, 0))`. -/ +def point (p : Bool × Option (A.endpoint Y k).obj) : (A.contact Y k).obj := + (p.1, p.2.isSome, p.2.getD (0, 0, 0)) + +variable [Field F] + +open scoped Classical in +/-- The station of type `Station F (A.spanBits Y)`, constructed using `(r.2 j).1`. -/ +def station (r : (A.record Y k).obj) (j : B k) : Station F (A.spanBits Y) := + let t := (r.2 j).1 + if t.1 then + if j = 0 then (Station.ofPattern (Y.scheme.decode r.1) 0).enlarge (A.inner Y) + else (Station.ofPattern (A.decode t.2.1) t.2.2).enlarge (A.outer Y) + else Station.blank + +open scoped Classical in +/-- Builds `Pattern F Y.scheme.d k (A.spanBits Y) where width j` with the specified `width`, +`direction`, `peer`, `let`. -/ +def pattern (r : (A.record Y k).obj) : Pattern F Y.scheme.d k (A.spanBits Y) where + width j := (A.station Y k r j).width + direction j l := ((r.2 j).2 l).1 + peer j l := + let p := (r.2 j).2 l + if p.2.1 ∧ 0 < (A.station Y k r j).width l then some p.2.2 else none + value j x := (A.station Y k r j).value (fun p => x p.1 p.2) + +open scoped Classical in +/-- Builds `Attachment Y where k` with the specified `decode`, `live`, `charge`, `let`. -/ +abbrev transport : Attachment Y where + k := k + e := A.spanBits Y + ℓ := (A.record Y k).width + decode := A.pattern Y k ∘ (A.record Y k).serial.symm + live i j := (((A.record Y k).serial.symm i).2 j).1.1 + charge i j := + let t := (((A.record Y k).serial.symm i).2 j).1 + if j ≠ 0 ∧ t.1 then A.charge t.2.1 t.2.2 else 0 + coreSpan := A.inner Y + +namespace Relocation +variable {A Y k} (R : A.Relocation Y k) (r : A.format.obj) (s : Y.format.obj) + (active : B Y.scheme.m → B Y.scheme.h → Bool) (links : A.Links Y k) + +open scoped Classical in +/-- Selects the appropriate branch of `if j.2.2 = 0 then (active j.1 j.2.1, 0, 0) else (R.kept r +j).elim (false, 0, 0) (fun v => (true, r.2 v.1 v.2.1, v.2.2))`. -/ +def origin (j : Place Y k) : A.member.obj := + if j.2.2 = 0 then (active j.1 j.2.1, 0, 0) else + (R.kept r j).elim (false, 0, 0) (fun v => (true, r.2 v.1 v.2.1, v.2.2)) + +open scoped Classical in +/-- The indexed operation `((s.1 i).2 t, fun j => (R.origin r active (i, t, j), fun l => A.point +Y k (links ((i, t, j), l))))`. -/ +def localRecord (i : B Y.scheme.m) (t : B Y.scheme.h) : (A.record Y k).obj := + ((s.1 i).2 t, fun j => (R.origin r active (i, t, j), fun l => A.point Y k (links ((i, t, j), l)))) + +open scoped Classical in +/-- The indexed operation `(s, fun i t => (A.record Y k).serial (R.localRecord r s active links +i t))`. -/ +def write : (A.transport Y k).format.obj := + (s, fun i t => (A.record Y k).serial (R.localRecord r s active links i t)) + +local notation "U" => A.transport Y k +local notation "w" => R.write r s active links +local notation "out" => rows U w + +open scoped Classical in +theorem shape (j : Place Y k) : + Station.ofPattern ((U).scheme.pattern out j) j.2.2 = + A.station Y k (R.localRecord r s active links j.1 j.2.1) j.2.2 := by + change Station.ofPattern (A.pattern Y k ((A.record Y k).serial.symm ((A.record Y k).serial _))) _ + = _ + rw [Equiv.symm_apply_apply] + rfl + +open scoped Classical in +theorem live_at (j : Place Y k) : + (U).live ((w).2 j.1 j.2.1) j.2.2 = (R.origin r active j).1 := by + simp only [transport, write, Equiv.symm_apply_apply] + rfl + +open scoped Classical in +theorem direction_at (j : (U).scheme.Span) : (U).scheme.direction out j = (links j).1 := by + simp only [Scheme.direction, Scheme.pattern, scheme, rows, transport, write, Function.comp_apply, + Equiv.symm_apply_apply] + rfl + +open scoped Classical in +/-- The value specified by `((Y.nav s j.1 p.1, j.2.1, p.2.1), p.2.2)`. -/ +def resolve (j : Place Y k) (p : (A.endpoint Y k).obj) : (U).scheme.Span := + ((Y.nav s j.1 p.1, j.2.1, p.2.1), p.2.2) + +open scoped Classical in +theorem peer_at (j : (U).scheme.Span) : (U).scheme.peer out j = + if 0 < (U).scheme.width out j then (links j).2.map (resolve s j.1) else none := by + simp only [Scheme.peer, Scheme.width, Scheme.pattern, scheme, rows, transport, write, + Function.comp_apply, Equiv.symm_apply_apply] + let u := A.station Y k (R.localRecord r s active links j.1.1 j.1.2.1) j.1.2.2 + change (if (links j).2.isSome ∧ 0 < u.width j.2 then some ((links j).2.getD (0, 0, + 0)) else none).map + (resolve s j.1) = if 0 < u.width j.2 then (links j).2.map (resolve s j.1) else none + cases (links j).2 <;> by_cases h : 0 < u.width j.2 <;> simp [h] + +end Relocation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- +# Finding the new peer of a tether + +A core exterior span points to its previous core span. A frozen +span points to its previous station and keeps its span number. +Compare these names to the old peer name over the new neighbor list. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring Packing BatchDescent + +variable {F : Type} {D Y : Template F} (A : Attachment D) {k m : ℕ} + +open scoped Classical in +/-- The value specified by `((j.1.1, j.1.2.1, 0), A.coreSpan j.2)`. -/ +def fromCore (j : D.scheme.Span) : A.scheme.Span := + ((j.1.1, j.1.2.1, 0), A.coreSpan j.2) + +namespace Relocation +variable [Field F] {A} (R : A.Relocation Y k) (r : A.format.obj) (s : Y.format.obj) + (M : Trail.Move D.scheme Y.scheme m) + +local notation "U" => A.transport Y k +local notation "Sp" => Scheme.Span (scheme U) + +open scoped Classical in +/-- The previous of type `Option A.scheme.Span` for the given inputs. -/ +def previous (j : Sp) : Option A.scheme.Span := + if j.1.2.2 = 0 then + Function.extend (A.inner Y) (fun t => (M.previous ((j.1.1, j.1.2.1, 0), t)).map A.fromCore) + (fun _ => none) j.2 + else Function.extend (A.outer Y) (fun t => (R.kept r j.1).map (fun z => (z, t))) (fun _ + => none) j.2 + +open scoped Classical in +/-- Returns `some h.choose` when `h : ∃ i, test i = true` holds, and `none` otherwise. -/ +def seek {X : Type} (test : X → Bool) : Option X := + if h : ∃ i, test i = true then some h.choose else none + +open scoped Classical in +/-- The internal of type `Bool × Option (A.endpoint Y k).obj`, constructed using +`Y.scheme.decode ((s.1 j.1.1).2 j.1.2.1)`. -/ +def internal (j : Sp) : Bool × Option (A.endpoint Y k).obj := + let p := Y.scheme.decode ((s.1 j.1.1).2 j.1.2.1) + Function.extend (A.inner Y) (fun t => + (p.direction 0 t, (p.peer 0 t).map (fun x => (x.1, 0, A.inner Y x.2.2)))) (fun _ => (false, + none)) j.2 + +open scoped Classical in +/-- In the case `none`, this construction gives `internal s j`. -/ +def links : A.Links Y k := fun j => + match R.previous r M j with + | none => internal s j + | some w => (A.scheme.direction (A.rows r) w, (A.scheme.peer (A.rows r) w).bind fun v => + seek (fun i => decide (R.previous r M (resolve s j.1 i) = some v))) + +open scoped Classical in +theorem previous_core (j : Y.scheme.Span) (h : j.1.2.2 = 0) : + R.previous r M ((U).fromCore j) = (M.previous j).map A.fromCore := by + rcases j with ⟨⟨x, y, z⟩, t⟩ + change z = 0 at h + subst z + simp only [previous, fromCore, ↓reduceIte, transport, (A.inner Y).injective.extend_apply] + +open scoped Classical in +theorem previous_frozen (j : Place Y k) (t : B A.e) (h : j.2.2 ≠ 0) : + R.previous r M (j, A.outer Y t) = (R.kept r j).map (fun z => (z, t)) := by + unfold previous + rw [ite_eq_right h, (A.outer Y).injective.extend_apply] + +open scoped Classical in +theorem native (j : Y.scheme.Span) (hz : j.1.2.2 = 0) (he : M.previous j = none) : + let p := (U).fromCore j + (R.links r s M p).1 = Y.scheme.direction s.1 j ∧ + (R.links r s M p).2.map (resolve s p.1) = (Y.scheme.peer s.1 j).map (U).fromCore := by + intro p + have hp : R.previous r M p = none := by + rw [show p = (U).fromCore j from rfl, previous_core _ _ _ _ hz, he] + rfl + simp only [links, hp, internal] + rcases j with ⟨⟨x, y, z⟩, t⟩ + change z = 0 at hz + subst z + simp only [p, fromCore, transport, (A.inner Y).injective.extend_apply, Scheme.direction, + Scheme.pattern, Scheme.peer] + cases (Y.scheme.decode ((s.1 x).2 y)).peer 0 t <;> exact ⟨True.intro, rfl⟩ + +open scoped Classical in +theorem detached {j : Sp} {w : A.scheme.Span} (hj : R.previous r M j = some w) + (he : A.scheme.peer (A.rows r) w = none) : + R.links r s M j = (A.scheme.direction (A.rows r) w, none) := by + simp only [links, hj, he, Option.bind_none] + +open scoped Classical in +theorem linked {j l : Sp} {w v : A.scheme.Span} (hj : R.previous r M j = some w) + (he : A.scheme.peer (A.rows r) w = some v) + (hl : ∀ x, R.previous r M x = some v ↔ x = l) + (reach : ∃ i, resolve s j.1 i = l) : + (R.links r s M j).1 = A.scheme.direction (A.rows r) w ∧ + (R.links r s M j).2.map (resolve s j.1) = some l := by + simp only [links, hj, he, Option.bind_some, true_and] + have hit : ∃ i, decide (R.previous r M (resolve s j.1 i) = some v) = true := by + simpa only [decide_eq_true_eq, hl] using reach + rw [seek, dite_eq_left hit, Option.map_some] + exact congrArg some ((hl _).mp (of_decide_eq_true hit.choose_spec)) + +end Relocation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Occupied station slots in a moved attachment -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Relocation +open Coloring Packing + +variable {F T : Type} [Field F] [Fintype T] {D Y : Template F} {A : Attachment D} {k : ℕ} + {x y a b : Wire} {u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} + {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} {r : A.format.obj} {s : Y.format.obj} + {R : A.Relocation Y k} {q : A.Encloses r G Z} (p : Y.Encodes s H) (slot : T → B k) + +open scoped Classical in +/-- The condition `∀ i j, live i j = true ↔ (i, j, 0) ∈ Set.range p.post.vertex` on the +specified data. -/ +def WriteActive (live : B Y.scheme.m → B Y.scheme.h → Bool) : Prop := + ∀ i j, live i j = true ↔ (i, j, 0) ∈ Set.range p.post.vertex + +open scoped Classical in +/-- The value specified by `(p.post.host (H.units.place i).1, p.post.block (H.units.place i).2, +0)`. -/ +def core (i : H.diagram.V) : Place Y k := (p.post.host (H.units.place i).1, + p.post.block (H.units.place i).2, 0) +open scoped Classical in +/-- The value specified by `(p.post.host (H.park t).1, p.post.block (H.park t).2, slot t)`. -/ +def frozen (t : T) : Place Y k := (p.post.host (H.park t).1, p.post.block (H.park t).2, slot t) + +namespace Moves +variable {p slot} (h : R.Moves q p slot) + +include h in +open scoped Classical in +theorem kept_at (t : T) : R.kept r (frozen p slot t) = some (q.pres.vertex (.inr t)) := + (R.kept_iff q p slot h _ t).mpr rfl + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def vertex : (Z.attach H.diagram).V ↪ Place Y k where + toFun := Sum.elim (core p) (frozen p slot) + inj' := by + rintro (i|t) (j|w) he + · have hi := congrArg (fun x : Place Y k => (x.1, x.2.1, (0 : B Y.scheme.k))) he + exact congrArg Sum.inl (p.post.vertex.injective ((p.post.vertex_eq i).trans (hi.trans + (p.post.vertex_eq j).symm))) + · exact (h.positive w (congrArg (fun x => x.2.2) he).symm).elim + · exact (h.positive t (congrArg (fun x => x.2.2) he)).elim + · exact congrArg Sum.inr (Sum.inr.inj (q.pres.vertex.injective (Option.some.inj + ((h.kept_at t).symm.trans ((congrArg (R.kept r) he).trans (h.kept_at w)))))) + +variable {live : B Y.scheme.m → B Y.scheme.h → Bool} (ok : WriteActive p live) + (links : A.Links Y k) + +include ok in +open scoped Classical in +theorem core_origin (i : H.diagram.V) : R.origin r live (h.vertex (.inl i)) = (true, 0, 0) := by + have he := (ok _ _).mpr ⟨i, p.post.vertex_eq i⟩ + change R.origin r live (core p i) = _ + simp only [origin, core, ↓reduceIte, he] + +open scoped Classical in +theorem frozen_origin (t : T) : + R.origin r live (h.vertex (.inr t)) = + (true, r.2 (q.pres.vertex (.inr t)).1 (q.pres.vertex (.inr t)).2.1, + (q.pres.vertex (.inr t)).2.2) := by + change R.origin r live (frozen p slot t) = _ + rw [origin, ite_eq_right (show (frozen p slot t).2.2 ≠ 0 from h.positive t), h.kept_at] + rfl + +include ok in +open scoped Classical in +theorem in_range (j : Place Y k) : (R.origin r live j).1 = true ↔ j ∈ Set.range h.vertex := by + constructor + · intro hj + by_cases hz : j.2.2 = 0 + · rw [origin, ite_eq_left hz] at hj + obtain ⟨i, hi⟩ := (ok _ _).mp hj + rw [p.post.vertex_eq] at hi + have hi₁ := congrArg Prod.fst hi + have hi₂ := congrArg (fun x => x.2.1) hi + exact ⟨.inl i, Prod.ext hi₁ (Prod.ext hi₂ hz.symm)⟩ + · rw [origin, ite_eq_right hz] at hj + cases he : R.kept r j with + | none => rw [he] at hj; cases hj + | some z => + obtain ⟨t, rfl⟩ := R.active q j z he + exact ⟨.inr t, ((R.kept_iff q p slot h j t).mp he).symm⟩ + · rintro ⟨i|t, rfl⟩ + · rw [h.core_origin ok] + · rw [h.frozen_origin] + +include h in +open scoped Classical in +theorem charge (t : T) : (A.transport Y k).charge ((R.write r s live links).2 + (p.post.host (H.park t).1) (p.post.block (H.park t).2)) (slot t) = L.charge t := by + simp only [transport, write, Equiv.symm_apply_apply, localRecord] + have he := h.frozen_origin (live := live) t + rw [q.frozen] at he + change R.origin r live (_, _, _) = _ at he + rw [he, ite_eq_left ⟨h.positive t, rfl⟩] + exact q.charge t + +end Moves +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Relocation +end + +/- +# Short queries for the old attachment records + +Each new core span and each candidate frozen station reads at most +one old label. A host index on a query refers to a shared list of +sources, including the parent itself. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring Packing BatchDescent + +variable {F : Type} {D Y : Template F} (A : Attachment D) (Y : Template F) (k p : ℕ) + +open scoped Classical in +/-- The maximum of the quantities in `Y.scheme.e k + 1`. -/ +abbrev depth := max Y.scheme.e k + 1 +open scoped Classical in +/-- Indexes the item by the coordinates of `B Y.scheme.e ⊕ B k`. -/ +abbrev Item := B Y.scheme.e ⊕ B k + +open scoped Classical in +/-- Embeds `Item Y k` into `B (depth Y k)`. -/ +def request : Item Y k ↪ B (depth Y k) := + Classical.choice (Function.Embedding.nonempty_of_card_le (by + simp only [Fintype.card_sum, Fintype.card_fin, depth, pow_succ] + rw [Nat.mul_two] + exact Nat.add_le_add (Nat.pow_le_pow_right (by decide) (le_max_left ..)) + (Nat.pow_le_pow_right (by decide) (le_max_right ..)))) + +open scoped Classical in +/-- Computes the orders by the application `Format.pair (.vec Y.scheme.e (Trail.pointer D.scheme +p)) (.vec k A.pointer)`. -/ +abbrev orders := Format.pair (.vec Y.scheme.e (Trail.pointer D.scheme p)) (.vec k A.pointer) +open scoped Classical in +/-- The value specified by `Format.pair (.addr Y.scheme.ℓ) (.pair .bit (A.orders Y k p))`. -/ +abbrev ticket := Format.pair (.addr Y.scheme.ℓ) (.pair .bit (A.orders Y k p)) +open scoped Classical in +/-- Computes the ask by the application `Format.vec (depth Y k) (.pair (.addr p) (.addr +D.scheme.h))`. -/ +abbrev ask := Format.vec (depth Y k) (.pair (.addr p) (.addr D.scheme.h)) +open scoped Classical in +/-- The value specified by `(A.ticket Y k p).pair (.vec (depth Y k) (.addr A.ℓ))`. -/ +abbrev bundle := (A.ticket Y k p).pair (.vec (depth Y k) (.addr A.ℓ)) + +variable {Y k p} + +open scoped Classical in +/-- Extends the data along the indexing map with a default elsewhere. -/ +def question (self : B p) (x : (A.ticket Y k p).obj) : (ask (D := D) Y k p).obj := + Function.extend (request Y k) (Sum.elim + (fun i => ((x.2.2.1 i).2.1, (x.2.2.1 i).2.2.1)) + (fun j => (self, (x.2.2.2 j).2.1))) (fun _ => (self, 0)) + +variable {A} + +open scoped Classical in +/-- The data for the query construction, including `R`, `M`, `old`, `fresh`, `active`. -/ +structure Query (A : Attachment D) (Y : Template F) (k p : ℕ) where + /-- The `Query` component of type `A.Relocation Y k`. -/ + R : A.Relocation Y k + /-- The `Query` component of type `Trail.Move D.scheme Y.scheme p`. -/ + M : Trail.Move D.scheme Y.scheme p + /-- The `Query` component of type `A.format.obj`. -/ + old : A.format.obj + /-- The `Query` component of type `Y.format.obj`. -/ + fresh : Y.format.obj + /-- The active indices of type `B Y.scheme.m → B Y.scheme.h → Bool`. -/ + active : B Y.scheme.m → B Y.scheme.h → Bool + +namespace Query +variable (q : Query A Y k p) (self : B p) (i : B Y.scheme.m) (j : B Y.scheme.h) + +open scoped Classical in +/-- The value specified by `((q.fresh.1 i).2 j, q.active i j, q.M.commands i j 0, q.R.flags i +j)`. -/ +def ticketAt : (A.ticket Y k p).obj := + ((q.fresh.1 i).2 j, q.active i j, q.M.commands i j 0, q.R.flags i j) + +open scoped Classical in +/-- The indexed operation `(q.ticketAt i j, fun a => let b := A.question self (q.ticketAt i j) a +q.old.2 (q.M.nav i b.1) b.2)`. -/ +def received : (A.bundle Y k p).obj := + (q.ticketAt i j, fun a => + let b := A.question self (q.ticketAt i j) a + q.old.2 (q.M.nav i b.1) b.2) + +open scoped Classical in +theorem answer_core (l : B Y.scheme.e) (w : B p × Trail.Stub D.scheme) + (hw : q.M.read ((i, j, 0), l) = some w) : + (q.received self i j).2 (request Y k (.inl l)) = q.old.2 (q.M.nav i w.1) w.2.1 := by + simp only [received, question, (request Y k).injective.extend_apply, Sum.elim_inl, ticketAt, + Trail.Move.commands, hw] + rfl + +open scoped Classical in +theorem answer_slot (hl : q.M.nav i self = q.R.parent i) (l : B k) (w : B D.scheme.h × B A.k) + (hw : q.R.prev i j l = some w) : + (q.received self i j).2 (request Y k (.inr l)) = q.old.2 (q.R.parent i) w.1 := by + simp only [received, question, (request Y k).injective.extend_apply, Sum.elim_inr, ticketAt, + Relocation.flags, hw, hl] + rfl + +end Query +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Pin bijections for the retained border and the new core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring Packing + +open scoped Classical in +/-- Computes the at vertex by the application `Station.ofPattern (S.pattern s i) i.2.2`. -/ +def atVertex {F : Type} (S : Scheme F) (s : S.format.obj) (i : S.Vtx) := + Station.ofPattern (S.pattern s i) i.2.2 + +namespace Relocation.Moves +variable {F T : Type} [Field F] [Fintype T] {D Y : Template F} {A : Attachment D} {k : ℕ} + {x y a b : Wire} {u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} + {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} {r : A.format.obj} {s : Y.format.obj} + {R : A.Relocation Y k} {q : A.Encloses r G Z} {p : Y.Encodes s H} {slot : T → B k} + (h : R.Moves q p slot) {live : B Y.scheme.m → B Y.scheme.h → Bool} + (ok : WriteActive p live) (links : A.Links Y k) + +local notation "W" => scheme (A.transport Y k) +local notation "out" => rows (A.transport Y k) (R.write r s live links) + +include ok in +open scoped Classical in +theorem core_shape (i : H.diagram.V) : + atVertex W out (h.vertex (.inl i)) = + (atVertex Y.scheme s.1 (p.post.vertex i)).enlarge (A.inner Y) := by + unfold atVertex + rw [R.shape, p.post.vertex_eq] + simp only [station, localRecord, Prod.mk.eta, h.core_origin ok, ↓reduceIte] + rfl + +open scoped Classical in +theorem outer_shape (i : T) : + atVertex W out (h.vertex (.inr i)) = + (atVertex A.scheme (A.rows r) (q.pres.vertex (.inr i))).enlarge (A.outer Y) := by + unfold atVertex + rw [R.shape] + have hi : (h.vertex (.inr i)).2.2 ≠ 0 := h.positive i + simp only [station, localRecord, Prod.mk.eta, h.frozen_origin, ite_eq_right hi, ↓reduceIte] + rfl + +include ok in +open scoped Classical in +theorem blank_shape (j : Place Y k) (hj : j ∉ Set.range h.vertex) : + atVertex W out j = Station.blank := by + unfold atVertex + rw [R.shape] + have hf := mt (h.in_range ok j).mp hj + simp only [station, localRecord, Prod.mk.eta, ite_eq_right hf] + +open scoped Classical in +/-- Builds `(W).Seating out (Z.attach H.diagram) where vertex` with the specified `vertex`, +`pin`, `have`, `exact`. -/ +def seating : (W).Seating out (Z.attach H.diagram) where + vertex := h.vertex + pin + | .inl i => (p.post.pin i).trans (Station.ports (h.core_shape ok links i)) + | .inr i => (q.pres.pin (.inr i)).trans (Station.ports (h.outer_shape links i)) + cover j := by + by_contra! he + have ht := h.blank_shape ok links j.1.1 (by rintro ⟨a, ha⟩; exact he a ha) + have hw : (W).width out j.1 = 0 := congrArg (fun c => c.width j.1.2) ht + exact Fin.elim0 (j.2.cast hw) + sample := by + rintro (v|t) q' + · exact (Station.eval_at (h.core_shape ok links v) q').trans (p.post.sample v _) + · exact (Station.eval_at (h.outer_shape links t) q').trans (q.pres.sample (.inr t) _) + vacant j hj := by + change ∀ t, (atVertex W out j).value t = 1 + rw [h.blank_shape ok links j hj] + exact fun _ => rfl + +open scoped Classical in +theorem core_pin (i : H.diagram.V) (j : H.diagram.Port i) : + ((h.seating ok links).pin (.inl i) j).1 = A.inner Y (p.post.pin i j).1 ∧ + ((h.seating ok links).pin (.inl i) j).2.val = (p.post.pin i j).2.val := + Station.ports_at (h.core_shape ok links i) (p.post.pin i j) + +open scoped Classical in +theorem outer_pin (i : T) (j : (Z.attach G.diagram).Port (.inr i)) : + ((h.seating ok links).pin (.inr i) j).1 = A.outer Y (q.pres.pin (.inr i) j).1 ∧ + ((h.seating ok links).pin (.inr i) j).2.val = (q.pres.pin (.inr i) j).2.val := + Station.ports_at (h.outer_shape links i) (q.pres.pin (.inr i) j) + +end Relocation.Moves +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Following the ordered bits from both sides of an attachment -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Coloring Packing + +variable {F T : Type} [Fintype T] {x y a b : Wire} + +namespace Packing.Border +variable (Z : Border F T a b x y) (G : Diagram F x y) + +open scoped Classical in +/-- In the case `.inl (.inl i)`, this construction gives `.inl (.inr (.inr (.inl i)))`. -/ +def coreEnd : G.End → (Z.attach G).End + | .inl (.inl i) => .inl (.inr (.inr (.inl i))) + | .inr (.inl i) => .inr (.inr (.inr (.inr i))) + | .inl (.inr e) => .inl (.inr (.inl e)) + | .inr (.inr e) => .inr (.inr (.inl e)) + +open scoped Classical in +theorem core_port (i : G.V) (j : G.Port i) : + Z.coreEnd G (G.portEquiv ⟨i, j⟩) = (Z.attach G).portEquiv ⟨.inl i, j⟩ := by + rcases j with j|j + · change Z.coreEnd G (.inl (G.src ⟨i, j⟩)) = .inl (merge _ _ _ _ (.inl (G.src ⟨i, j⟩))) + cases G.src ⟨i, j⟩ <;> rfl + · change Z.coreEnd G (.inr (G.dst ⟨i, j⟩)) = + .inr (Sum.map id (Sum.map id Sum.swap) (merge _ _ _ _ (.inl (G.dst ⟨i, j⟩)))) + cases G.dst ⟨i, j⟩ <;> rfl + +open scoped Classical in +/-- Indexes the ends by the coordinates of `(slots a ⊕ slots y) ⊕ (slots b ⊕ slots x)`. -/ +abbrev Ends (a b x y : Wire) := (slots a ⊕ slots y) ⊕ (slots b ⊕ slots x) + +open scoped Classical in +/-- In the case `.inl (.inl i)`, this construction gives `.inl (.inl i)`. -/ +def outerEnd : Ends a b x y → (Z.attach G).End + | .inl (.inl i) => .inl (.inl i) + | .inr (.inl i) => .inr (.inl i) + | .inl (.inr i) => .inl (.inr (.inr (.inr i))) + | .inr (.inr i) => .inr (.inr (.inr (.inl i))) + +open scoped Classical in +/-- Reindexes `(Σ i, Transcript.Ports (Z.table i))` and `Ends a b x y` by an equivalence. -/ +def ports : (Σ i, Transcript.Ports (Z.table i)) ≃ Ends a b x y := + (Equiv.sigmaSumDistrib _ _).trans (Z.src.sumCongr Z.dst) + +open scoped Classical in +/-- The value specified by `(Z.ports.symm i).1`. -/ +def owner (i : Ends a b x y) := (Z.ports.symm i).1 + +open scoped Classical in +theorem outer_port (i : T) (j : Transcript.Ports (Z.table i)) : + Z.outerEnd G (Z.ports ⟨i, j⟩) = (Z.attach G).portEquiv ⟨.inr i, j⟩ := by + rcases j with j|j + · change Z.outerEnd G (.inl (Z.src ⟨i, j⟩)) = .inl (merge _ _ _ _ (.inr (Z.src ⟨i, j⟩))) + cases Z.src ⟨i, j⟩ <;> rfl + · change Z.outerEnd G (.inr (Z.dst ⟨i, j⟩)) = + .inr (Sum.map id (Sum.map id Sum.swap) (merge _ _ _ _ (.inr (Z.dst ⟨i, j⟩)))) + cases Z.dst ⟨i, j⟩ <;> rfl + +open scoped Classical in +/-- In the case `.inl i`, this construction gives `.inr (.inr i)`. -/ +def other : slots x ⊕ slots y → Ends a b x y + | .inl i => .inr (.inr i) + | .inr i => .inl (.inr i) + +omit [Fintype T] in +open scoped Classical in +theorem owner_other (i : slots x ⊕ slots y) : Z.owner (other i) = Z.tensor i := by cases i <;> rfl + +end Packing.Border + +namespace Assembly.Attachment +variable [Field F] {D Y : Template F} {A : Attachment D} {k : ℕ} + {u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} + {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} {r : A.format.obj} {s : Y.format.obj} + {R : A.Relocation Y k} (q : A.Encloses r G Z) {p : Y.Encodes s H} {slot : T → B k} + +open scoped Classical in +theorem Encloses.core_end (i : G.diagram.End) : + let e := q.pres.toSeating.ends (Z.coreEnd G.diagram i) + let f := q.core.post.toSeating.ends i + e.1 = A.fromCore f.1 ∧ e.2.val = f.2.val := by + obtain ⟨⟨w, j⟩, rfl⟩ := G.diagram.portEquiv.surjective i + erw [Z.core_port, q.pres.toSeating.ends_at, q.core.post.toSeating.ends_at] + have hv := q.internal w + have hp := q.core.post.vertex_eq w + exact ⟨Prod.ext (hv.trans (congrArg (fun z => (z.1, z.2.1, (0 : B A.k))) hp.symm)) + (q.ordered w j).1, (q.ordered w j).2⟩ + +open scoped Classical in +theorem Encloses.outer_end (i : Border.Ends a b x y) : + (q.pres.toSeating.ends (Z.outerEnd G.diagram i)).1.1 = q.pres.vertex (.inr (Z.owner i)) := by + obtain ⟨⟨w, j⟩, rfl⟩ := Z.ports.surjective i + erw [Z.outer_port, q.pres.toSeating.ends_at, Border.owner, Equiv.symm_apply_apply] + rfl + +namespace Relocation.Moves +variable {q} (h : R.Moves q p slot) {live : B Y.scheme.m → B Y.scheme.h → Bool} + (ok : WriteActive p live) (links : A.Links Y k) + +open scoped Classical in +theorem core_end (i : H.diagram.End) : + let e := (h.seating ok links).ends (Z.coreEnd H.diagram i) + let f := p.post.toSeating.ends i + e.1 = (A.transport Y k).fromCore f.1 ∧ e.2.val = f.2.val := by + obtain ⟨⟨w, j⟩, rfl⟩ := H.diagram.portEquiv.surjective i + erw [Z.core_port, (h.seating ok links).ends_at, p.post.toSeating.ends_at] + have hv := congrArg (fun z => (z.1, z.2.1, (0 : B k))) (p.post.vertex_eq w).symm + exact ⟨Prod.ext hv (h.core_pin ok links w j).1, (h.core_pin ok links w j).2⟩ + +open scoped Classical in +theorem outer_end (i : Border.Ends a b x y) : + let e := (h.seating ok links).ends (Z.outerEnd H.diagram i) + let f := q.pres.toSeating.ends (Z.outerEnd G.diagram i) + e.1 = (frozen p slot (Z.owner i), A.outer Y f.1.2) ∧ e.2.val = f.2.val := by + obtain ⟨⟨w, j⟩, rfl⟩ := Z.ports.surjective i + erw [Z.outer_port, Z.outer_port, (h.seating ok links).ends_at, q.pres.toSeating.ends_at, + Border.owner, Equiv.symm_apply_apply] + exact ⟨Prod.ext rfl (h.outer_pin ok links w j).1, (h.outer_pin ok links w j).2⟩ + +end Relocation.Moves +end Assembly.Attachment +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Frame.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Frame.lean new file mode 100644 index 0000000000..3d14f4c40b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/Frame.lean @@ -0,0 +1,169 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial + +/-! +# Keeping frozen tables while the core moves + +A second local record contains the full border and the tether endpoints. +Host addresses and the block number are shared with the core record. The +first station slot is reserved for the core, even if it is empty. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing + +/-- The data for the attachment construction, including `k`, `e`, `ℓ`, `decode`, `live`. -/ +structure Attachment {F : Type} (D : Template F) where + /-- The `Attachment` field of type `ℕ`. -/ + k : ℕ + /-- The `Attachment` field of type `ℕ`. -/ + e : ℕ + /-- The `Attachment` field of type `ℕ`. -/ + ℓ : ℕ + /-- The `Attachment` component of type `B ℓ → Pattern F D.scheme.d k e`. -/ + decode : B ℓ → Pattern F D.scheme.d k e + /-- The `Attachment` component of type `B ℓ → B k → Bool`. -/ + live : B ℓ → B k → Bool + /-- The `Attachment` component of type `B ℓ → B k → ℝ`. -/ + charge : B ℓ → B k → ℝ + /-- Embeds the coordinates as `B D.scheme.e ↪ B e`. -/ + coreSpan : B D.scheme.e ↪ B e + +namespace Attachment + +variable {F T : Type} {D : Template F} (A : Attachment D) + +/-- Uses `⟨D.scheme.m, D.scheme.d, D.scheme.h, A.k, A.e, A.ℓ, A.decode⟩` as the representation. -/ +abbrev scheme : Scheme F := + ⟨D.scheme.m, D.scheme.d, D.scheme.h, A.k, A.e, A.ℓ, A.decode⟩ + +/-- The value specified by `Format.vec D.scheme.m (.vec D.scheme.h (.addr A.ℓ))`. -/ +abbrev label := Format.vec D.scheme.m (.vec D.scheme.h (.addr A.ℓ)) + +/-- Computes the format by the application `D.format.pair A.label`. -/ +abbrev format := D.format.pair A.label + +/-- Evaluates `(D.nav r.1 v, r.2 v)` at the input `v`. -/ +def rows (r : A.format.obj) : A.scheme.format.obj := + fun v => (D.nav r.1 v, r.2 v) + +theorem width : A.format.width = D.format.width + 2 ^ D.scheme.m * (2 ^ D.scheme.h * A.ℓ) := by + simp only [format, label, Format.width_pair, Format.width_vec, Format.width_addr] + +variable [Field F] [Fintype T] {x y a b : Wire} {u : ℕ} {L : Fringe x y T} +variable (r : A.format.obj) (G : HostNet F L D.scheme.h u) (Z : Border F T a b x y) + +/-- The core and the border records must describe the same individual +core bits, in order. A frozen table is kept on its own assigned slot. -/ +structure Encloses where + full : D.full = true + tether : L.tensor = Z.tensor + /-- The `Encloses` component of type `D.Encodes r.1 G`. -/ + core : D.Encodes r.1 G + /-- The `Encloses` component of type `A.scheme.Presentation (A.rows r) (Z.attach G.diagram)`. -/ + pres : A.scheme.Presentation (A.rows r) (Z.attach G.diagram) + directed : pres.Directed + occupied : ∀ v : A.scheme.Vtx, A.live (r.2 v.1 v.2.1) v.2.2 = true ↔ v ∈ Set.range pres.vertex + /-- The `Encloses` component of type `T → B A.k`. -/ + slot : T → B A.k + positive : ∀ t, slot t ≠ 0 + internal : ∀ v, pres.vertex (.inl v) = + (core.post.host (G.units.place v).1, core.post.block (G.units.place v).2, 0) + frozen : ∀ t, pres.vertex (.inr t) = + (core.post.host (G.park t).1, core.post.block (G.park t).2, slot t) + charge : ∀ t, A.charge (r.2 (core.post.host (G.park t).1) (core.post.block (G.park t).2)) + (slot t) = L.charge t + ordered : ∀ v (j : G.diagram.Port v), + (pres.pin (.inl v) j).1 = A.coreSpan (core.post.pin v j).1 ∧ + (pres.pin (.inl v) j).2.val = (core.post.pin v j).2.val + +variable {r G Z A} + +theorem Encloses.distinct (q : A.Encloses r G Z) {v w : T} + (h : G.park v = G.park w) (hs : q.slot v = q.slot w) : v = w := by + apply Sum.inr.inj + apply q.pres.vertex.injective + rw [q.frozen, q.frozen, h, hs] + +end Attachment +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Common stage boundary while the border is retained -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) + (x y : Wire) (u height : ℕ) + +/-- The data for the data construction, including `T`, `[finite`, `a`, `b`, `L`. -/ +structure Data where + /-- The `Data` component of type `Type`. -/ + T : Type + [finite : Fintype T] + /-- The left component of type `Wire`. -/ + a : Wire + /-- The right component of type `Wire`. -/ + b : Wire + /-- The `Data` component of type `Fringe a b T`. -/ + L : Fringe a b T + /-- The `Data` component of type `HostNet F L D.scheme.h u`. -/ + G : HostNet F L D.scheme.h u + /-- The `Data` component of type `Border F T x y a b`. -/ + Z : Border F T x y a b + /-- The `Data` component of type `A.format.obj`. -/ + raw : A.format.obj + /-- The `Data` component of type `A.Encloses raw G Z`. -/ + q : A.Encloses raw G Z + +attribute [instance] Data.finite + +/-- The quantity computed by `2 ^ m + wd x + wd y`. -/ +abbrev volume (m : ℕ) := 2 ^ m + wd x + wd y +/-- The value specified by `Fmt.payload m (volume x y m) height`. -/ +abbrev payload (m : ℕ) := Fmt.payload m (volume x y m) height +/-- Computes the port by the application `A.format.pair (payload x y height D.scheme.m)`. -/ +abbrev port := A.format.pair (payload x y height D.scheme.m) + +namespace Data +variable {A x y u height} (X : Data A x y u) + +/-- Computes the diagram by the application `X.Z.attach X.G.diagram`. -/ +abbrev diagram := X.Z.attach X.G.diagram +/-- The value specified by `A.scheme.Fits (A.rows X.raw) (volume x y D.scheme.m) height`. -/ +abbrev Fits (height : ℕ) := A.scheme.Fits (A.rows X.raw) (volume x y D.scheme.m) height + +/-- Computes the data by the application `A.scheme.store _ fit (X.q.pres.exterior i j)`. -/ +def data (fit : X.Fits height) (i : Val x) (j : Val y) : (payload x y height D.scheme.m).obj := + A.scheme.store _ fit (X.q.pres.exterior i j) + +/-- The condition `∀ v, X.G.diagram.arity v = 0 → ∀ t, Transcript.sample (X.G.diagram.table v) t += 1` on the specified data. -/ +def Neutral := ∀ v, X.G.diagram.arity v = 0 → ∀ t, Transcript.sample (X.G.diagram.table v) t = 1 + +end Data + +/-- Builds `Assembly.Snapshot.{1} F x y where state` with the specified `state`, `eval`, `port`, +`encode`. -/ +def frame (P : Data A x y u → Prop) : Assembly.Snapshot.{1} F x y where + state := {X : Data A x y u // P X ∧ X.Fits height} + eval i := i.val.diagram.eval + port := A.port x y height + encode i a b := (i.val.raw, i.val.data i.property.2 a b) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/ShortNet.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/ShortNet.lean new file mode 100644 index 0000000000..0139f7106a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Attachment/ShortNet.lean @@ -0,0 +1,1047 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Factor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.FreezeInput.Retain +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Frame + +/-! # Uniqueness of the moved span corresponding to a given old span -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing BatchDescent + +variable {F T : Type} [Field F] {x y a b : Wire} {D Y : Template F} {A : Attachment D} {k m : ℕ} + {u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} + {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} {r : A.format.obj} {s : Y.format.obj} + +namespace Scheme.Posting +variable {S : Scheme F} {w : S.format.obj} (p : S.Posting w G) + +open scoped Classical in +theorem end_zero (j : G.diagram.End) : (p.toSeating.ends j).1.1.2.2 = 0 := by + obtain ⟨⟨v, i⟩, rfl⟩ := G.diagram.portEquiv.surjective j + rw [p.toSeating.ends_at] + exact congrArg (fun x => x.2.2) (p.vertex_eq v) + +open scoped Classical in +theorem boundary_zero (j : slots x ⊕ slots y) : (p.toPresentation.boundary j).val.1.1.2.2 = 0 := by + cases j <;> exact p.end_zero _ + +end Scheme.Posting + +namespace Attachment.Relocation.Moves +variable [Fintype T] {R : A.Relocation Y k} {q : A.Encloses r G Z} {p : Y.Encodes s H} {slot : T → + B k} + (h : R.Moves q p slot) {M : Trail.Move D.scheme Y.scheme m} + (move : M.Agrees q.core.post.toPresentation p.post.toPresentation) + +local notation "U" => A.transport Y k +local notation "Sp" => Scheme.Span (scheme U) +local notation "src" => q.core.post.toPresentation.boundary +local notation "dst" => p.post.toPresentation.boundary + +include h move in +open scoped Classical in +private theorem previous_cases {j : Sp} {w : A.scheme.Span} (he : R.previous r M j = some w) : + (∃ i, j = (U).fromCore (dst i).val.1 ∧ w = A.fromCore (src i).val.1) ∨ + (∃ t l, j = (frozen p slot t, A.outer Y l) ∧ w = (q.pres.vertex (.inr t), l)) := by + rcases j with ⟨⟨v, c, d⟩, z⟩ + by_cases hd : d = 0 + · subst d + simp only [previous, ↓reduceIte] at he + by_cases hz : z ∈ Set.range (A.inner Y) + · obtain ⟨l, rfl⟩ := hz + rw [(A.inner Y).injective.extend_apply] at he + let x : Y.scheme.Span := ((v, c, 0), l) + have hx : (M.read x).isSome := by + by_contra! hn + have he' : (M.previous x).map A.fromCore = some w := he + cases hm : M.read x <;> simp [Trail.Move.previous, hm] at he' hn + obtain ⟨i, hi⟩ := move.active _ hx + change (M.previous x).map A.fromCore = some w at he + rw [← hi, (move.mapped i).1] at he + exact .inl ⟨i, congrArg (U).fromCore hi.symm, (Option.some.inj he).symm⟩ + · rw [Function.extend_apply' _ _ _ hz] at he + cases he + · simp only [previous, ite_eq_right hd] at he + by_cases hz : z ∈ Set.range (A.outer Y) + · obtain ⟨l, rfl⟩ := hz + rw [(A.outer Y).injective.extend_apply] at he + obtain ⟨i, hi, hw⟩ := Option.map_eq_some_iff.mp he + obtain ⟨t, rfl⟩ := R.active q _ _ hi + exact .inr ⟨t, l, Prod.ext ((R.kept_iff q p slot h _ t).mp hi) rfl, hw.symm⟩ + · rw [Function.extend_apply' _ _ _ hz] at he + cases he + +open scoped Classical in +private theorem separate (t : T) (l : B A.e) (x : D.scheme.Span) : + (q.pres.vertex (.inr t), l) ≠ A.fromCore x := by + rw [q.frozen] + exact fun he => q.positive t (congrArg (fun y => y.1.2.2) he) + +include h move in +open scoped Classical in +theorem previous_inner (i : slots x ⊕ slots y) (j : Sp) : + R.previous r M j = some (A.fromCore (src i).val.1) ↔ j = (U).fromCore (dst i).val.1 := by + constructor + · intro he + rcases h.previous_cases move he with ⟨u, rfl, hu⟩ | ⟨t, l, _, ht⟩ + · have hs : (src i).val.1 = (src u).val.1 := by + have h₁ := congrArg (fun t => t.1.1) hu + have h₂ := congrArg (fun t => t.1.2.1) hu + have h₃ := (q.core.post.boundary_zero i).trans (q.core.post.boundary_zero u).symm + exact Prod.ext (Prod.ext h₁ (Prod.ext h₂ h₃)) (A.coreSpan.injective (congrArg Prod.snd hu)) + exact congrArg (U).fromCore (move.same hs).symm + · exact (separate t l _ ht.symm).elim + · rintro rfl + rw [R.previous_core _ _ _ (p.post.boundary_zero i), (move.mapped i).1] + rfl + +include h move in +open scoped Classical in +theorem previous_outer (t : T) (l : B A.e) (j : Sp) : + R.previous r M j = some (q.pres.vertex (.inr t), l) ↔ j = (frozen p slot t, A.outer Y l) := by + constructor + · intro he + rcases h.previous_cases move he with ⟨i, _, hi⟩ | ⟨w, z, rfl, eqw⟩ + · exact (separate t l _ hi).elim + · obtain ⟨hv, rfl⟩ := Prod.mk.inj eqw + rw [Sum.inr.inj (q.pres.vertex.injective hv)] + · rintro rfl + rw [R.previous_frozen r M (frozen p slot t) l (h.positive t), h.kept_at] + rfl + +end Attachment.Relocation.Moves +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Reading the old peer through canonical neighboring stations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring Packing BatchDescent + +variable {F T : Type} [Field F] [Fintype T] {x y a b : Wire} {D Y : Template F} {A : Attachment D} + {k m : ℕ} + {u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} + {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} {r : A.format.obj} {s : Y.format.obj} + {R : A.Relocation Y k} {q : A.Encloses r G Z} {p : Y.Encodes s H} {slot : T → B k} + +namespace Relocation +variable {live : B Y.scheme.m → B Y.scheme.h → Bool} {M : Trail.Move D.scheme Y.scheme m} +local notation "U" => A.transport Y k +local notation "W" => scheme U +local notation "edges" => R.links r s M +local notation "out" => rows U (R.write r s live edges) + +open scoped Classical in +theorem peer_pin (j : (W).Pin out) : + (W).peer out j.1 = (edges j.1).2.map (resolve s j.1.1) := by + rw [peer_at, ite_eq_left (Nat.zero_lt_of_lt j.2.isLt)] + +open scoped Classical in +/-- The condition `∃ i, resolve s j.1 i = l` on the specified data. -/ +def Hops (s : Y.format.obj) (j l : (W).Span) : Prop := ∃ i, resolve s j.1 i = l + +open scoped Classical in +private theorem hops (full : Y.full = true) (c t : H.V × Cell Y.scheme.h) (ht : t.1 ∈ H.N c.1) + (eq : c.2 = t.2) {j l : (W).Span} + (hj : (j.1.1, j.1.2.1) = (p.post.host c.1, p.post.block c.2)) + (hl : (l.1.1, l.1.2.1) = (p.post.host t.1, p.post.block t.2)) : Hops s j l := by + have hn : t.1 ∈ Y.adj H c.1 := by simpa only [Template.adj, full, ↓reduceIte] using ht + obtain ⟨n, he, _⟩ := (p.edge _ _).mp hn + obtain ⟨h₁, h₂⟩ := Prod.mk.inj hj + obtain ⟨h₃, h₄⟩ := Prod.mk.inj hl + refine ⟨(n, l.1.2.2, l.2), ?_⟩ + simp only [resolve, h₁, h₂, eq, he, ← h₃, ← h₄, Prod.mk.eta] + +namespace Moves +variable (h : R.Moves q p slot) (ok : WriteActive p live) + (move : M.Agrees q.core.post.toPresentation p.post.toPresentation) + +local notation "seated" => h.seating ok edges +local notation "new" => Scheme.Seating.ends seated +local notation "old" => q.pres.toSeating.ends + +include move in +open scoped Classical in +theorem old_outer (i : Border.Ends a b x y) (j : (W).Span) : + R.previous r M j = some (old (Z.outerEnd G.diagram i)).1 ↔ j = (new (Z.outerEnd H.diagram i)).1 + := by + rw [(h.outer_end ok edges i).1] + have hw := q.outer_end i + conv_lhs => rhs; arg 1; rw [← Prod.mk.eta (p := (old (Z.outerEnd G.diagram i)).1), hw] + exact h.previous_outer move _ _ _ + +include move in +open scoped Classical in +theorem old_inner (i : slots x ⊕ slots y) (j : (W).Span) : + R.previous r M j = some (old (Z.coreEnd G.diagram (boundaryEnd G.diagram i))).1 ↔ + j = (new (Z.coreEnd H.diagram (boundaryEnd H.diagram i))).1 := by + rw [(q.core_end _).1, (h.core_end ok edges _).1] + have hh := h.previous_inner move i j + cases i <;> exact hh + +open scoped Classical in +theorem tether_hops (full : Y.full = true) (i : slots x ⊕ slots y) : + let c := (new (Z.coreEnd H.diagram (boundaryEnd H.diagram i))).1 + let t := (new (Z.outerEnd H.diagram (Border.other i))).1 + Hops s c t ∧ Hops s t c := by + intro c t + let v := H.units.place (portEnd H.diagram i) + let w := H.park (L.tensor i) + have hv : (c.1.1, c.1.2.1) = (p.post.host v.1, p.post.block v.2) := by + have ht (j : H.diagram.End) : (p.post.toSeating.ends j).1.1 + = p.post.vertex (H.diagram.station j) := by + obtain ⟨⟨u, z⟩, rfl⟩ := H.diagram.portEquiv.surjective j + rw [p.post.toSeating.ends_at, H.diagram.station_port] + rfl + unfold c + rw [(h.core_end ok edges _).1] + simp only [fromCore, ht, station_boundary, p.post.vertex_eq] + rfl + have hw : (t.1.1, t.1.2.1) = (p.post.host w.1, p.post.block w.2) := by + unfold t + rw [(h.outer_end ok edges _).1, Z.owner_other, ← q.tether] + rfl + obtain ⟨_, he, hn⟩ := H.tether i + exact ⟨hops full v w hn he hv hw, hops full w v (H.ns _ _ hn) he.symm hw hv⟩ + +end Moves +end Relocation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Internal connections are read directly from the new core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Relocation.Moves +open Coloring Packing BatchDescent + +variable {F T : Type} [Field F] [Fintype T] {x y a b : Wire} {D Y : Template F} {A : Attachment D} + {k m : ℕ} + {u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} + {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} {r : A.format.obj} {s : Y.format.obj} + {R : A.Relocation Y k} {q : A.Encloses r G Z} {p : Y.Encodes s H} {slot : T → B k} + (h : R.Moves q p slot) {live : B Y.scheme.m → B Y.scheme.h → Bool} + (ok : WriteActive p live) {M : Trail.Move D.scheme Y.scheme m} + (move : M.Agrees q.core.post.toPresentation p.post.toPresentation) + +local notation "U" => A.transport Y k +local notation "W" => scheme U +local notation "edges" => R.links r s M +local notation "out" => rows U (R.write r s live edges) +local notation "seated" => h.seating ok edges +local notation "new" => Scheme.Seating.ends seated +local notation "orig" => p.post.toSeating.ends + +include move in +open scoped Classical in +private theorem forward {i j : H.diagram.End} + (hp : Y.scheme.Joins s.1 (orig i) (orig j)) : + (W).Joins out (new (Z.coreEnd H.diagram i)) (new (Z.coreEnd H.diagram j)) ∧ + (W).direction out (new (Z.coreEnd H.diagram i)).1 = Y.scheme.direction s.1 (orig i).1 := by + have hn : M.previous (orig i).1 = none := by + cases he : M.read (orig i).1 with + | none => rw [Trail.Move.previous, he]; rfl + | some x => + obtain ⟨t, ht⟩ := move.active _ (show (M.read (orig i).1).isSome = true by rw [he]; rfl) + have hh := (p.post.toPresentation.boundary t).property + rw [ht, hp.1] at hh + cases hh + obtain ⟨hd, he⟩ := R.native r s M _ (p.post.end_zero i) hn + have hi := h.core_end ok edges i + have hj := h.core_end ok edges j + refine ⟨⟨?_, hi.2.trans (hp.2.trans hj.2.symm)⟩, ?_⟩ + · rw [peer_pin, hi.1, hj.1, he, hp.1] + rfl + · rw [R.direction_at, hi.1] + exact hd + +include move in +open scoped Classical in +theorem core_bond (j : H.diagram.E) : + (seated).Bond (.inl (.inr (.inl j))) (.inr (.inr (.inl j))) := by + have hp := p.post.internal j + have a := h.forward ok move hp + have b := h.forward ok move (hp.symm p.post.proper) + have hd (t : Bool) : Y.scheme.direction s.1 (orig (cond t (.inr (.inr j)) (.inl (.inr j)))).1 = t + := by + obtain ⟨⟨i, l⟩, rfl⟩ := H.units.bits.symm.surjective j + change Y.scheme.direction s.1 (orig (Scheme.endBit H i t l)).1 = t + rw [(p.post.ordered i t l).1, p.post.dir] + exact ⟨a.1, b.1, a.2.trans (hd false), b.2.trans (hd true)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Relocation.Moves +end + +/- +# A compact code for transported attachment labels + +The station mask determines where to read each old selector. Only +occupied frozen seats need space for selectors. The core selector, +station numbers, and link fields remain unchanged. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment + +open Coloring Packing + +variable {k N ℓ : ℕ} + +open scoped Classical in +/-- Computes the seats by the application `s.equivFin.toEmbedding.trans (Fin.castLEEmb h)`. -/ +def seats (s : Finset (B k)) (h : s.card ≤ N) : s ↪ Fin N := + s.equivFin.toEmbedding.trans (Fin.castLEEmb h) + +open scoped Classical in +/-- Returns `Function.extend (seats s h) (fun i => f i.val) (fun _ => 0)` when `h : s.card ≤ N` +holds, and `fun _ => 0` otherwise. -/ +def save (N : ℕ) (s : Finset (B k)) (f : B k → B ℓ) : Fin N → B ℓ := + if h : s.card ≤ N then Function.extend (seats s h) (fun i => f i.val) (fun _ => 0) else fun _ => 0 + +open scoped Classical in +/-- Returns `f (seats s h.1 ⟨i, h.2⟩)` when `h : s.card ≤ N ∧ i ∈ s` holds, and `0` otherwise. -/ +def loadSeats (s : Finset (B k)) (f : Fin N → B ℓ) (i : B k) : B ℓ := + if h : s.card ≤ N ∧ i ∈ s then f (seats s h.1 ⟨i, h.2⟩) else 0 + +open scoped Classical in +private theorem load_save (s : Finset (B k)) (f : B k → B ℓ) (h : s.card ≤ N) + (hz : ∀ i ∉ s, f i = 0) (i : B k) : loadSeats s (save N s f) i = f i := by + by_cases hi : i ∈ s + · simp only [loadSeats, dite_eq_left (And.intro h hi), save, dite_eq_left h] + exact (seats s h).injective.extend_apply _ _ _ + · simp [loadSeats, hi, hz i hi] + +variable {F : Type} {D : Template F} (A : Attachment D) (Y : Template F) (k N : ℕ) + +open scoped Classical in +/-- The short record used in the `Attachment` construction. -/ +abbrev shortRecord := + Format.pair (.addr Y.scheme.ℓ) (.pair (Fmt.pi (fun _ : Fin N => Format.addr A.ℓ)) + (.vec k (.pair (.pair .bit (.addr A.k)) (.vec (A.spanBits Y) (A.contact Y k))))) + +open scoped Classical in +theorem short_width : + (A.shortRecord Y k N).width = Y.scheme.ℓ + N * A.ℓ + + 2 ^ k * (1 + A.k + 2 ^ (A.spanBits Y) * (2 + Y.scheme.d + k + A.spanBits Y)) := by + simp only [shortRecord, contact, endpoint, Format.width_pair, Format.width_addr, + Format.width_vec, Fmt.width_pi, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + smul_eq_mul] + rw [Format.width_bit] + ring + +open scoped Classical in +/-- The indexed operation `(r.1, save N (occupiedSeats fun j => (r.2 j).1.1) (fun j => (r.2 +j).1.2.1), fun j => (((r.2 j).1.1, (r.2 j).1.2.2), (r.2 j).2))`. -/ +def storeRow (r : (A.record Y k).obj) : (A.shortRecord Y k N).obj := + (r.1, save N (occupiedSeats fun j => (r.2 j).1.1) (fun j => (r.2 j).1.2.1), + fun j => (((r.2 j).1.1, (r.2 j).1.2.2), (r.2 j).2)) + +open scoped Classical in +/-- The indexed operation `(r.1, fun j => (((r.2.2 j).1.1, loadSeats (occupiedSeats fun j => +(r.2.2 j).1.1) r.2.1 j, (r.2.2 j).1.2), (r.2.2 j).2))`. -/ +def readRow (r : (A.shortRecord Y k N).obj) : (A.record Y k).obj := + (r.1, fun j => (((r.2.2 j).1.1, loadSeats (occupiedSeats fun j => (r.2.2 j).1.1) r.2.1 j, + (r.2.2 j).1.2), (r.2.2 j).2)) + +open scoped Classical in +/-- Requires `let s := occupiedSeats fun j => (r.2 j).1.1 s.card ≤ N ∧ ∀ j ∉ s, (r.2 j).1.2.1 = +0`. -/ +def fitsRow (r : (A.record Y k).obj) : Prop := + let s := occupiedSeats fun j => (r.2 j).1.1 + s.card ≤ N ∧ ∀ j ∉ s, (r.2 j).1.2.1 = 0 + +open scoped Classical in +private theorem read_store (r : (A.record Y k).obj) (h : A.fitsRow Y k N r) : + A.readRow Y k N (A.storeRow Y k N r) = r := by + refine Prod.ext rfl (funext fun j => Prod.ext (Prod.ext rfl (Prod.ext ?_ rfl)) rfl) + exact load_save _ _ h.1 h.2 j + +open scoped Classical in +/-- The value specified by `(A.shortRecord Y k N).serial ∘ A.storeRow Y k N ∘ (A.record Y +k).serial.symm`. -/ +def writeShort := + (A.shortRecord Y k N).serial ∘ A.storeRow Y k N ∘ (A.record Y k).serial.symm + +open scoped Classical in +/-- The value specified by `(A.record Y k).serial ∘ A.readRow Y k N ∘ (A.shortRecord Y k +N).serial.symm`. -/ +def readShort := + (A.record Y k).serial ∘ A.readRow Y k N ∘ (A.shortRecord Y k N).serial.symm + +variable [Field F] + +open scoped Classical in +/-- The value specified by `(A.transport Y k).recode (A.shortRecord Y k N).width (A.readShort Y +k N)`. -/ +abbrev shrink : Attachment Y := (A.transport Y k).recode (A.shortRecord Y k N).width (A.readShort Y + k N) + +open scoped Classical in +/-- The indexed operation `(r.1, fun i j => A.writeShort Y k N (r.2 i j))`. -/ +def shorten (r : (A.transport Y k).format.obj) : (A.shrink Y k N).format.obj := + (r.1, fun i j => A.writeShort Y k N (r.2 i j)) + +open scoped Classical in +/-- The condition `∀ i j, A.fitsRow Y k N ((A.record Y k).serial.symm (r.2 i j))` on the +specified data. -/ +def Sparse (r : (A.transport Y k).format.obj) : Prop := + ∀ i j, A.fitsRow Y k N ((A.record Y k).serial.symm (r.2 i j)) + +variable {A Y k N} {r : (A.transport Y k).format.obj} + +open scoped Classical in +theorem Sparse.restore (h : A.Sparse Y k N r) : + r.2 = fun i j => A.readShort Y k N ((A.shorten Y k N r).2 i j) := by + funext i j + simp only [shorten, readShort, writeShort, Function.comp_apply, Equiv.symm_apply_apply, + read_store _ _ _ _ _ (h i j), Equiv.apply_symm_apply] + +variable {T : Type} [Fintype T] {x y a b : Wire} {u : ℕ} {L : Fringe x y T} + {G : HostNet F L Y.scheme.h u} {Z : Border F T a b x y} + +open scoped Classical in +/-- Computes the shrink by the application `q.recode h.restore`. -/ +def Encloses.shrink (q : (A.transport Y k).Encloses r G Z) (h : A.Sparse Y k N r) : + (A.shrink Y k N).Encloses (A.shorten Y k N r) G Z := q.recode h.restore + +open scoped Classical in +@[simp] theorem Encloses.shrink_core (q : (A.transport Y k).Encloses r G Z) (h : A.Sparse Y k N r) : + (q.shrink h).core = q.core := q.recode_core h.restore + +open scoped Classical in +@[simp] theorem Encloses.shrink_vertex (q : (A.transport Y k).Encloses r G Z) (h : A.Sparse Y k N + r) : + (q.shrink h).pres.vertex = q.pres.vertex := q.recode_vertex h.restore + +open scoped Classical in +@[simp] theorem Encloses.shrink_slot (q : (A.transport Y k).Encloses r G Z) (h : A.Sparse Y k N r) : + (q.shrink h).slot = q.slot := q.recode_slot h.restore + +open scoped Classical in +theorem Relocation.sparse (R : A.Relocation Y k) {src : A.format.obj} {s : Y.format.obj} + {live : B Y.scheme.m → B Y.scheme.h → Bool} {links : A.Links Y k} + (q : (A.transport Y k).Encloses (R.write src s live links) G Z) + {δ : ℝ} (hd : 0 < δ) (charge : ∀ t, δ ≤ L.scale * L.charge t) + (bound : ∀ v i, G.load v i ≤ (N : ℝ) * δ) : + A.Sparse Y k N (R.write src s live links) := by + intro i j + refine ⟨q.slot_count hd charge bound i j, ?_⟩ + simp only [write, Equiv.symm_apply_apply, localRecord] + intro t ht + change (R.origin src live (i, j, t)).2.1 = 0 + by_cases hzero : t = 0 + · simp [origin, hzero] + have hoff : (R.origin src live (i, j, t)).1 ≠ true := by + intro h + exact ht (Finset.mem_filter.mpr ⟨Finset.mem_univ _, hzero, h⟩) + unfold origin at hoff ⊢ + cases he : R.kept src (i, j, t) <;> simp [hzero, he] at hoff ⊢ + +namespace Data +variable (s : (A.transport Y k).Data a b u) (h : A.Sparse Y k N s.raw) + +open scoped Classical in +/-- Uses `⟨s.T, s.a, s.b, s.L, s.G, s.Z, A.shorten Y k N s.raw, s.q.shrink h⟩` as the +representation. -/ +def shrink : (A.shrink Y k N).Data a b u := + ⟨s.T, s.a, s.b, s.L, s.G, s.Z, A.shorten Y k N s.raw, s.q.shrink h⟩ + +open scoped Classical in +theorem shrink_fits {t : ℕ} (fit : s.Fits t) : (s.shrink h).Fits t := + recode_fits h.restore fit + +open scoped Classical in +theorem shrink_data {t : ℕ} (fit : s.Fits t) (i : Val a) (j : Val b) : + (s.shrink h).data (s.shrink_fits h fit) i j = s.data fit i j := + s.q.recode_store h.restore fit i j + +end Data +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # One common label-compression table for a whole frame -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment + +open Coloring + +variable {F : Type} [Field F] {D : Template F} + (A : Attachment D) (Y : Template F) (k N : ℕ) + +/-- The quantity computed by `(A.transport Y k).ℓ + (A.shrink Y k N).ℓ`. -/ +def shrinkWidth := (A.transport Y k).ℓ + (A.shrink Y k N).ℓ + +/-- The indexed operation `weightTable (A := .addr (A.transport Y k).ℓ) (D := .addr (A.shrink Y +k N).ℓ) (A.writeShort Y k N) (fun _ => (1 : F))`. -/ +def shrinkGate := + weightTable (A := .addr (A.transport Y k).ℓ) (D := .addr (A.shrink Y k N).ℓ) + (A.writeShort Y k N) (fun _ => (1 : F)) + +theorem shrink_arity : wd (A.shrinkGate Y k N).1 + wd (A.shrinkGate Y k N).2.1 + = A.shrinkWidth Y k N := by + simp only [shrinkGate, shrinkWidth, weightTable, lookup, wd_word, Format.width_addr] + +/-- The quantity computed by `4 * Y.format.width + 2 ^ Y.scheme.m * (2 ^ Y.scheme.h * (1 + +A.shrinkWidth Y k N))`. -/ +def shortenCost := + 4 * Y.format.width + 2 ^ Y.scheme.m * (2 ^ Y.scheme.h * (1 + A.shrinkWidth Y k N)) + +/-- The quantity computed by `A.shortenCost Y k N + 4 * (payload x y height Y.scheme.m).width`. -/ +def shrinkCost (x y : Wire) (height : ℕ) := + A.shortenCost Y k N + 4 * (payload x y height Y.scheme.m).width + +variable {A Y k N} {u v : ℕ} {L : Set (Table F)} + (hu : 3 ≤ u) (hf : A.shrinkWidth Y k N ≤ u) (hl : A.shrinkGate Y k N ∈ L) + +include hu hf hl + +theorem shorten_net : Map F u L (A.transport Y k).format (A.shrink Y k N).format + (A.shorten Y k N) (A.shortenCost Y k N) := by + let X := Format.addr (A.transport Y k).ℓ + let W := Format.addr (A.shrink Y k N).ℓ + have he : X.width + W.width = A.shrinkWidth Y k N := by + rw [Format.width_addr, Format.width_addr] + rfl + have row : Map F u L X W (A.writeShort Y k N) (1 + A.shrinkWidth Y k N) := by + rw [← he, ← add_assoc] + exact Kernel.lookup (he.le.trans hf) hl + have codes := Map.vec (t := Y.scheme.m) _ (fun _ => Map.vec (t := Y.scheme.h) _ (fun _ => row)) + exact (Map.circuit hu (Circuit.id F Y.format)).par codes + +/-- The payload stays in its original order and the diagram is unchanged. -/ +theorem shrink_frames {x y : Wire} {height : ℕ} + {P : (A.transport Y k).Data x y v → Prop} {Q : (A.shrink Y k N).Data x y v → Prop} + (hs : ∀ s, P s → A.Sparse Y k N s.raw) + (hq : ∀ s (h : P s), Q (s.shrink (hs s h))) : + Transforms F u L ((A.transport Y k).frame x y v height P) ((A.shrink Y k N).frame x y v height + Q) + (A.shrinkCost Y k N x y height) := by + let X := (A.transport Y k).frame x y v height P + let W := (A.shrink Y k N).frame x y v height Q + let send (s : X.state) : W.state := + ⟨s.val.shrink (hs s.val s.property.1), hq s.val s.property.1, + s.val.shrink_fits (hs s.val s.property.1) s.property.2⟩ + have net := (shorten_net hu hf hl).par (Map.circuit hu (Circuit.id F (payload x y height + Y.scheme.m))) + refine Transforms.of_map _ send net (fun _ => rfl) (fun s i j => Prod.ext rfl ?_) + exact (s.val.shrink_data (hs s.val s.property.1) s.property.2 i j).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Locating the predecessor of a span using only short indices -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring Packing BatchDescent + +variable {F : Type} {D Y : Template F} (A : Attachment D) {k p : ℕ} + +open scoped Classical in +/-- The data for the source construction, including `hop`, `block`, `seat`, `label`. -/ +structure Source (p : ℕ) where + /-- The `Source` field of type `B p`. -/ + hop : B p + /-- The `Source` component of type `B D.scheme.h`. -/ + block : B D.scheme.h + /-- The `Source` component of type `B A.k`. -/ + seat : B A.k + /-- The label at each coordinate of type `B A.ℓ`. -/ + label : B A.ℓ + +open scoped Classical in +/-- Indexes the key by the coordinates of `A.Source p × B A.e`. -/ +abbrev Key (p : ℕ) := A.Source p × B A.e + +variable (self : B p) (x : (A.bundle Y k p).obj) + +open scoped Classical in +/-- The frozen of type `Option (A.Source p)`, constructed using `x.1.2.2.2 j`. -/ +def frozen (j : B k) : Option (A.Source p) := + let w := x.1.2.2.2 j + let z := x.2 (request Y k (.inr j)) + if w.1 = true ∧ A.live z w.2.2 = true ∧ w.2.2 ≠ 0 then some ⟨self, w.2.1, w.2.2, z⟩ else none + +open scoped Classical in +/-- The core key of type `Option (A.Key p)`, constructed using `x.1.2.2.1 j`. -/ +def coreKey (j : B Y.scheme.e) : Option (A.Key p) := + let w := x.1.2.2.1 j + let z := x.2 (request Y k (.inl j)) + if w.1 then some (⟨w.2.1, w.2.2.1, 0, z⟩, A.coreSpan w.2.2.2.2) else none + +open scoped Classical in +/-- The key of type `Option (A.Key p)` for the given inputs. -/ +def key (i : B k) (j : B (A.spanBits Y)) : Option (A.Key p) := + if i = 0 then Function.extend (A.inner Y) (A.coreKey x) (fun _ => none) j + else Function.extend (A.outer Y) (fun t => (A.frozen self x i).map (fun s => (s, t))) (fun _ + => none) j + +open scoped Classical in +/-- Selects the appropriate branch of `if i = 0 then (x.1.2.1, 0, 0) else (A.frozen self x +i).elim (false, 0, 0) (fun t => (true, t.label, t.seat))`. -/ +def memberAt (i : B k) : A.member.obj := + if i = 0 then (x.1.2.1, 0, 0) + else (A.frozen self x i).elim (false, 0, 0) (fun t => (true, t.label, t.seat)) + +namespace Query +variable {A} (q : Query A Y k p) (self : B p) (i : B Y.scheme.m) (j : B Y.scheme.h) + +open scoped Classical in +/-- The value specified by `(q.M.nav i o.hop, o.block, o.seat)`. -/ +def relocate (o : A.Source p) : A.scheme.Vtx := (q.M.nav i o.hop, o.block, o.seat) + +open scoped Classical in +/-- The value specified by `(q.relocate i w.1, w.2)`. -/ +def name (w : A.Key p) : A.scheme.Span := (q.relocate i w.1, w.2) + +open scoped Classical in +/-- Computes the letter by the application `q.old.2 j.1 j.2.1`. -/ +def letter (j : A.scheme.Vtx) := q.old.2 j.1 j.2.1 + +local notation "X" => q.received self i j + +open scoped Classical in +theorem frozen_eq (hs : q.M.nav i self = q.R.parent i) (l : B k) : + (A.frozen self X l).map (fun w => (q.relocate i w, w.label)) = + (q.R.kept q.old (i, j, l)).map (fun v => (v, q.letter v)) := by + have key : (X).1.2.2.2 l = A.tag (q.R.prev i j l) := rfl + unfold frozen Relocation.kept Relocation.back + rw [key] + cases hw : q.R.prev i j l with + | none => simp [tag] + | some w => + rw [q.answer_slot self i j hs l w hw] + simp only [tag, true_and, Option.map_some] + by_cases h : A.live (q.old.2 (q.R.parent i) w.1) w.2 = true ∧ w.2 ≠ 0 + · have present : ∃ a b, + (w = (a, b) ∧ A.live (q.old.2 (q.R.parent i) a) b = true ∧ b ≠ 0) ∧ + (a, b) = w ∧ q.old.2 (q.R.parent i) a = q.old.2 (q.R.parent i) w.1 := + ⟨w.1, w.2, ⟨rfl, h⟩, rfl, rfl⟩ + simpa [h.1, h.2, hs, relocate, letter] using present + · have absent : A.live (q.old.2 (q.R.parent i) w.1) w.2 = true → w.2 = 0 := + fun u => not_ne_iff.mp (fun v => h ⟨u, v⟩) + simpa [h] using absent + +open scoped Classical in +theorem core_eq (l : B Y.scheme.e) : + (A.coreKey X l).map (fun w => (q.name i w, w.1.label)) = + ((q.M.previous ((i, j, 0), l)).map A.fromCore).map (fun w => (w, q.letter w.1)) := by + have key : (X).1.2.2.1 l = Trail.point D.scheme (q.M.read ((i, j, 0), l)) := rfl + unfold coreKey Trail.Move.previous + rw [key] + cases hw : q.M.read ((i, j, 0), l) with + | none => rfl + | some w => rw [q.answer_core self i j l w hw]; rfl + +variable [Field F] (hs : q.M.nav i self = q.R.parent i) + +include hs in +open scoped Classical in +theorem key_eq (t : B k) (l : B (A.spanBits Y)) : + (A.key self X t l).map (fun w => (q.name i w, w.1.label)) = + (q.R.previous q.old q.M ((i, j, t), l)).map (fun w => (w, q.letter w.1)) := by + unfold key Relocation.previous + by_cases ht : t = 0 + · simp only [ht, ite_true] + by_cases h : l ∈ Set.range (A.inner Y) + · obtain ⟨v, rfl⟩ := h + erw [(A.inner Y).injective.extend_apply, (A.inner Y).injective.extend_apply] + exact q.core_eq self i j v + · erw [Function.extend_apply' _ _ _ h, Function.extend_apply' _ _ _ h]; rfl + · simp only [ht, ite_false] + by_cases h : l ∈ Set.range (A.outer Y) + · obtain ⟨v, rfl⟩ := h + erw [(A.outer Y).injective.extend_apply, (A.outer Y).injective.extend_apply] + have hh := congrArg (Option.map (fun z : A.scheme.Vtx × B A.ℓ => ((z.1, v), z.2))) + (q.frozen_eq self i j hs t) + simp only [Option.map_map] at hh ⊢ + exact hh + · erw [Function.extend_apply' _ _ _ h, Function.extend_apply' _ _ _ h]; rfl + +omit [Field F] in +include hs in +open scoped Classical in +theorem member_eq (t : B k) : A.memberAt self X t = q.R.origin q.old q.active (i, j, t) := by + unfold memberAt Relocation.origin + by_cases ht : t = 0 + · rw [ite_eq_left ht, ite_eq_left ht]; rfl + · rw [ite_eq_right ht, ite_eq_right ht] + have hh := q.frozen_eq self i j hs t + cases h : A.frozen self X t <;> cases h' : q.R.kept q.old (i, j, t) + all_goals simp only [h, h', Option.map_none, Option.map_some, Option.some.injEq] at hh + · rfl + · cases hh + · cases hh + · exact congrArg (fun z : A.scheme.Vtx × B A.ℓ => (true, z.2, z.1.2.2)) hh + +end Query +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Inspecting endpoint labels without long host names in any block -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring +variable {F : Type} {D Y : Template F} (A : Attachment D) (Y : Template F) (k p : ℕ) + +/-- Computes the review by the application `Inspect.Row D.scheme.d Y.scheme.d p (A.bundle Y k +p)`. -/ +abbrev Review := Inspect.Row D.scheme.d Y.scheme.d p (A.bundle Y k p) + +variable {A Y k p} + +/-- The review of type `(A.Review Y k p).obj` for the given inputs. -/ +def Query.review (q : A.Query Y k p) (self : B p) (i : B Y.scheme.m) (j : B Y.scheme.h) : (A.Review + Y k p).obj := + (Alias.mask ((fun t => D.nav q.old.1 (q.M.nav i t)), (fun t => q.M.nav (Y.nav q.fresh i t))), + q.received self i j, fun t => q.received self (Y.nav q.fresh i t) j) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- +# Identifying the remote tether endpoint + +A shared Boolean mask compares the old host names. Block, seat +and span comparisons take place entirely on the short records. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Packing Coloring BatchDescent + +variable {F : Type} [Field F] {D Y : Template F} {A : Attachment D} {k p : ℕ} + (self : B p) (x : (A.Review Y k p).obj) + +open scoped Classical in +/-- Indexes the old end by the coordinates of `B D.scheme.d × B A.k × B A.e`. -/ +abbrev OldEnd (A : Attachment D) := B D.scheme.d × B A.k × B A.e + +open scoped Classical in +/-- In the case `none`, this construction gives `false`. -/ +def detect (w : A.Source p) (dst : A.OldEnd) (t : (A.endpoint Y k).obj) : Bool := + match A.key self (x.2.2 t.1) t.2.1 t.2.2 with + | none => false + | some u => x.1 w.hop dst.1 t.1 u.1.hop && decide ((u.1.block, u.1.seat, u.2) = (w.block, dst.2)) + +open scoped Classical in +/-- In the case `none`, this construction gives `let r := Y.scheme.decode x.2.1.1.1`. -/ +def contactAt (v : B k) (j : B (A.spanBits Y)) : Bool × Option (A.endpoint Y k).obj := + match A.key self x.2.1 v j with + | none => + let r := Y.scheme.decode x.2.1.1.1 + Function.extend (A.inner Y) (fun t => + (r.direction 0 t, (r.peer 0 t).map (fun p => (p.1, 0, A.inner Y p.2.2)))) (fun _ => (false, + none)) j + | some w => + let r := A.decode w.1.label + (r.direction w.1.seat w.2, (r.peer w.1.seat w.2).bind (fun dst + => Relocation.seek (detect self x w.1 dst))) + +open scoped Classical in +/-- The indexed operation `(x.2.1.1.1, fun j => (A.memberAt self x.2.1 j, fun l => A.point Y k +(contactAt self x j l)))`. -/ +def rebuild : (A.record Y k).obj := + (x.2.1.1.1, fun j => (A.memberAt self x.2.1 j, fun l => A.point Y k (contactAt self x j l))) + +namespace Query +variable (q : Query A Y k p) (self : B p) (hs : ∀ i, q.M.nav i self = q.R.parent i) + (i : B Y.scheme.m) (j : B Y.scheme.h) + +local notation "X" => q.review self i j +local notation "W" => q.received self i j + +include hs in +open scoped Classical in +theorem previous_eq (v : B k) (l : B (A.spanBits Y)) : + q.R.previous q.old q.M ((i, j, v), l) = (A.key self W v l).map (q.name i) := by + have h := congrArg (Option.map Prod.fst) (q.key_eq self i j (hs i) v l) + simpa only [Option.map_map, Function.comp_def, Option.map_id'] using h.symm + +open scoped Classical in +/-- The value specified by `((D.nav q.old.1 (q.M.nav i w.hop) dst.1, w.block, dst.2.1), +dst.2.2)`. -/ +def remote (w : A.Source p) (dst : A.OldEnd) : A.scheme.Span := + ((D.nav q.old.1 (q.M.nav i w.hop) dst.1, w.block, dst.2.1), dst.2.2) + +include hs in +open scoped Classical in +theorem detect_eq (w : A.Source p) (dst : A.OldEnd) (v : B k) (t : (A.endpoint Y k).obj) : + detect self X w dst t = + decide (q.R.previous q.old q.M (Relocation.resolve q.fresh (i, j, v) t) + = some (q.remote i w dst)) := by + unfold Relocation.resolve + rw [q.previous_eq self hs] + unfold detect review + dsimp only + cases A.key self (q.received self (Y.nav q.fresh i t.1) j) t.2.1 t.2.2 with + | none => simp + | some u => + obtain ⟨h, s, l⟩ := dst + apply Bool.eq_iff_iff.mpr + simp only [Alias.mask, Bool.and_eq_true, decide_eq_true_eq, Prod.mk.injEq, Option.map_some, + Option.some.injEq, name, relocate, remote] + tauto + +include hs in +open scoped Classical in +theorem contact_eq (v : B k) (l : B (A.spanBits Y)) : + contactAt self X v l = q.R.links q.old q.fresh q.M ((i, j, v), l) := by + unfold contactAt Relocation.links + have hk := q.key_eq self i j (hs i) v l + have hr := q.previous_eq self hs i j v l + rw [hr] at hk ⊢ + change (match A.key self W v l with | none => _ | some t => _) = _ + cases h : A.key self W v l with + | none => rfl + | some w => + simp only [h, Option.map_some, Option.some.injEq] at hk + have hv : w.1.label = q.letter (q.name i w).1 := congrArg Prod.snd hk + let r := A.decode w.1.label + have hd : A.scheme.direction (A.rows q.old) (q.name i w) = r.direction w.1.seat w.2 := + congrArg (fun t => (A.decode t).direction w.1.seat w.2) hv.symm + have hp : A.scheme.peer (A.rows q.old) (q.name i w) = + (r.peer w.1.seat w.2).map (q.remote i w.1) := + congrArg (fun t => ((A.decode t).peer w.1.seat w.2).map (q.remote i w.1)) hv.symm + simp only [Option.map_some, hd, hp] + refine Prod.ext ?_ ?_ + · rfl + change (r.peer w.1.seat w.2).bind _ = ((r.peer w.1.seat w.2).map _).bind _ + cases r.peer w.1.seat w.2 with + | none => rfl + | some dst => exact congrArg Relocation.seek (funext fun t + => q.detect_eq self hs i j w.1 dst v t) + +include hs in +open scoped Classical in +theorem rebuild_eq : + rebuild self X = q.R.localRecord q.old q.fresh q.active (q.R.links q.old q.fresh q.M) i j := by + unfold rebuild Relocation.localRecord + refine Prod.ext rfl (funext fun v => Prod.ext (q.member_eq self i j (hs i) v) ?_) + exact funext fun l => congrArg (A.point Y k) (q.contact_eq self hs i j v l) + +end Query +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Tether connections and untouched exterior pins after reattachment -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring Packing BatchDescent + +variable {F T : Type} [Field F] [Fintype T] {x y a b : Wire} {D Y : Template F} {A : Attachment D} + {k m : ℕ} + {u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} + {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} {r : A.format.obj} {s : Y.format.obj} + {R : A.Relocation Y k} {q : A.Encloses r G Z} {p : Y.Encodes s H} {slot : T → B k} + +open scoped Classical in +private theorem Encloses.bond (q : A.Encloses r G Z) (j : (Z.attach G.diagram).E) : + q.pres.toSeating.Bond (.inl (.inr j)) (.inr (.inr j)) := + ⟨q.pres.internal j, (q.pres.internal j).symm q.pres.proper, q.directed _, q.directed _⟩ + +open scoped Classical in +private theorem Encloses.tether_bond (q : A.Encloses r G Z) (i : slots x ⊕ slots y) : + q.pres.toSeating.Bond (Z.coreEnd G.diagram (boundaryEnd G.diagram i)) (Z.outerEnd G.diagram + (Border.other i)) := by + cases i with + | inl i => exact q.bond (.inr (.inl i)) + | inr i => exact (q.bond (.inr (.inr i))).swap + +namespace Relocation.Moves +variable (h : R.Moves q p slot) {live : B Y.scheme.m → B Y.scheme.h → Bool} + (ok : WriteActive p live) {M : Trail.Move D.scheme Y.scheme m} + (move : M.Agrees q.core.post.toPresentation p.post.toPresentation) + +local notation "U" => A.transport Y k +local notation "W" => scheme U +local notation "edges" => R.links r s M +local notation "out" => rows U (R.write r s live edges) +local notation "seated" => h.seating ok edges +local notation "new" => Scheme.Seating.ends seated +local notation "old" => q.pres.toSeating.ends + +open scoped Classical in +private theorem transfer {j l : (Z.attach H.diagram).End} {w t : (Z.attach G.diagram).End} + (bond : q.pres.toSeating.Bond w t) + (hj : ∀ z, R.previous r M z = some (old w).1 ↔ z = (new j).1) + (hl : ∀ z, R.previous r M z = some (old t).1 ↔ z = (new l).1) + (ej : (new j).2.val = (old w).2.val) (el : (new l).2.val = (old t).2.val) + (dj : w.isRight = j.isRight) (dl : t.isRight = l.isRight) + (hop : Hops s (new j).1 (new l).1 ∧ Hops s (new l).1 (new j).1) : (seated).Bond j l := by + have a := R.linked r s M ((hj _).mpr rfl) bond.1.1 hl hop.1 + have b := R.linked r s M ((hl _).mpr rfl) bond.2.1.1 hj hop.2 + have offset := ej.trans (bond.1.2.trans el.symm) + exact ⟨⟨(peer_pin _).trans a.2, offset⟩, ⟨(peer_pin _).trans b.2, offset.symm⟩, + (R.direction_at _ _ _ _ _).trans (a.1.trans (bond.2.2.1.trans dj)), + (R.direction_at _ _ _ _ _).trans (b.1.trans (bond.2.2.2.trans dl))⟩ + +include move in +open scoped Classical in +theorem tether_bond (full : Y.full = true) (i : slots x ⊕ slots y) : + (seated).Bond (Z.coreEnd H.diagram (boundaryEnd H.diagram i)) (Z.outerEnd H.diagram + (Border.other i)) := by + apply h.transfer ok (q.tether_bond i) (h.old_inner ok move i) (h.old_outer ok move (Border.other + i)) _ + (h.outer_end ok edges _).2 (by cases i <;> rfl) (by cases i <;> rfl) (h.tether_hops ok full i) + rw [(h.core_end ok edges _).2, (q.core_end _).2] + have eq := (move.mapped i).2.2 + cases i <;> exact eq + +include move in +open scoped Classical in +theorem outer_free (i : Border.Ends a b x y) + (hi : A.scheme.peer (A.rows r) (old (Z.outerEnd G.diagram i)).1 = none) : + (seated).Free (Z.outerEnd H.diagram i) := by + have he := R.detached r s M ((h.old_outer ok move i _).mpr rfl) hi + constructor + · rw [peer_pin, he] + rfl + · rw [R.direction_at, he, q.directed] + rcases i with (i|i)|(i|i) <;> rfl + +end Relocation.Moves +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Reattaching the unchanged border after moving the core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Relocation.Moves +open Coloring Packing BatchDescent + +variable {F T : Type} [Field F] [Fintype T] {x y a b : Wire} {D Y : Template F} {A : Attachment D} + {k m : ℕ} + {u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} + {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} {r : A.format.obj} {s : Y.format.obj} + {R : A.Relocation Y k} {q : A.Encloses r G Z} {p : Y.Encodes s H} {slot : T → B k} + (h : R.Moves q p slot) {live : B Y.scheme.m → B Y.scheme.h → Bool} + (ok : WriteActive p live) {M : Trail.Move D.scheme Y.scheme m} + (move : M.Agrees q.core.post.toPresentation p.post.toPresentation) (full : Y.full = true) + +local notation "links" => R.links r s M + +include move full in +open scoped Classical in +theorem connected : (h.seating ok links).Connected where + used j he := by + rw [R.peer_at] at he + by_contra! hn + exact he (ite_eq_right (not_lt.mpr hn)) + bond + | .inl e => h.core_bond ok move e + | .inr (.inl i) => h.tether_bond ok move full (.inl i) + | .inr (.inr i) => (h.tether_bond ok move full (.inr i)).swap + input i := h.outer_free ok move (.inl (.inl i)) (q.pres.input i) + output i := h.outer_free ok move (.inr (.inl i)) (q.pres.output i) + +open scoped Classical in +/-- The emitted attachment presents exactly the new core and the old +border, with the same exterior bit order and the same parked charges. -/ +def enclose : (A.transport Y k).Encloses (R.write r s live links) H Z where + full := full + tether := q.tether + core := p + pres := (h.connected ok move full).presentation + directed := (h.connected ok move full).directed + occupied j := by rw [R.live_at]; exact h.in_range ok j + slot := slot + positive := h.positive + internal _ := rfl + frozen _ := rfl + charge := h.charge links + ordered := h.core_pin ok links + +open scoped Classical in +theorem exterior_pin (i : slots a ⊕ slots b) : + let j := ((h.enclose ok move full).pres.boundary i).val + let z := (q.pres.boundary i).val + R.kept r j.1.1 = some z.1.1 ∧ j.1.2 = A.outer Y z.1.2 ∧ j.2.val = z.2.val := by + have aux (i : Border.Ends a b x y) : + let j := (h.seating ok links).ends (Z.outerEnd H.diagram i) + let z := q.pres.toSeating.ends (Z.outerEnd G.diagram i) + R.kept r j.1.1 = some z.1.1 ∧ j.1.2 = A.outer Y z.1.2 ∧ j.2.val = z.2.val := by + have ht := h.outer_end ok links i + refine ⟨?_, congrArg Prod.snd ht.1, ht.2⟩ + rw [ht.1, q.outer_end, h.kept_at] + cases i with + | inl i => exact aux (.inl (.inl i)) + | inr i => exact aux (.inr (.inl i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Relocation.Moves +end + +/- +# Preserving the height of the exterior bit bank + +Each exterior bit belongs to a frozen member. All the bits stored +at a new host came from its one parent, so the old height suffices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Relocation +open Coloring Packing BatchDescent + +variable {F T : Type} [Field F] [Fintype T] {x y a b : Wire} {D Y : Template F} {A : Attachment D} + {k m : ℕ} + {u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} + {H : HostNet F L Y.scheme.h v} {Z : Border F T a b x y} {r : A.format.obj} {s : Y.format.obj} + {R : A.Relocation Y k} {q : A.Encloses r G Z} {p : Y.Encodes s H} {slot : T → B k} + (h : R.Moves q p slot) {live : B Y.scheme.m → B Y.scheme.h → Bool} + (ok : WriteActive p live) {M : Trail.Move D.scheme Y.scheme m} + (move : M.Agrees q.core.post.toPresentation p.post.toPresentation) (full : Y.full = true) + +omit [Field F] in +open scoped Classical in +theorem parent_of_kept (j : Place Y k) (w : A.scheme.Vtx) (hw : R.kept r j = some w) : + R.parent j.1 = w.1 := by + have hh := (Option.filter_eq_some_iff.mp hw).1 + obtain ⟨t, _, ht⟩ := Option.map_eq_some_iff.mp hh + exact congrArg Prod.fst ht + +namespace Moves +local notation "U" => A.transport Y k +local notation "r'" => R.write r s live (R.links r s M) + +include h ok move full in +open scoped Classical in +theorem volume_le (i : B Y.scheme.m) : + (U).scheme.load ((U).rows r') i ≤ A.scheme.load (A.rows r) (R.parent i) := by + let p' := (h.enclose ok move full).pres + let e := p'.boundary.symm.trans q.pres.boundary + have he (j : (U).scheme.exposed ((U).rows r')) : + R.parent ((U).scheme.owner _ j) = A.scheme.owner _ (e j) := by + obtain ⟨x, rfl⟩ := p'.boundary.surjective j + rw [show e (p'.boundary x) = q.pres.boundary x from congrArg q.pres.boundary + (p'.boundary.symm_apply_apply x)] + exact parent_of_kept _ _ (h.exterior_pin ok move full x).1 + let f (j : (U).scheme.fiber ((U).rows r') i) : A.scheme.fiber (A.rows r) (R.parent i) := + ⟨e j.val, (he j.val).symm.trans (congrArg R.parent j.property)⟩ + exact Fintype.card_le_of_injective f (fun _ _ h + => Subtype.ext (e.injective (congrArg Subtype.val h))) + +include h ok move full in +open scoped Classical in +theorem fits {V height : ℕ} (fit : A.scheme.Fits (A.rows r) V height) : + (U).scheme.Fits ((U).rows r') (volume a b Y.scheme.m) height := + (h.enclose ok move full).pres.fits le_rfl (fun i => (h.volume_le ok move full i).trans (fit.2 _)) + +end Moves +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Relocation +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Boundary.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Boundary.lean new file mode 100644 index 0000000000..fa3d6ab5a9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Boundary.lean @@ -0,0 +1,1057 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress + +/-! +# Representing a diagram by short records + +A local port bijection may change the order of the arguments of a +table. The table in the decoding menu reads the reordered arguments. +Only the normalized spans are required to align at both ends. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme + +variable {F : Type} [Field F] {x y : Wire} (S : Scheme F) (r : S.format.obj) (G : Diagram F x y) + +open scoped Classical in +/-- The data for the seating construction, including `vertex`, `pin`, `cover`, `sample`, +`vacant`. -/ +structure Seating where + /-- The placement of the vertices carried by `Seating`, with type `G.V ↪ S.Vtx`. -/ + vertex : G.V ↪ S.Vtx + /-- Reindexes the data using `∀ v, G.Port v ≃ S.LocalPin r (vertex v)`. -/ + pin : ∀ v, G.Port v ≃ S.LocalPin r (vertex v) + cover : ∀ p : S.Pin r, ∃ v, vertex v = p.1.1 + sample : ∀ v t, S.table r (vertex v) t = Transcript.sample (G.table v) (t ∘ pin v) + vacant : ∀ v ∉ Set.range vertex, ∀ t, S.table r v t = 1 + +variable {S r G} + +namespace Seating +variable (a : S.Seating r G) + +open scoped Classical in +/-- Computes the at pin by the application `S.port r (a.vertex i.1) (a.pin i.1 i.2)`. -/ +def atPin (i : Σ v, G.Port v) := S.port r (a.vertex i.1) (a.pin i.1 i.2) + +open scoped Classical in +theorem atPin_bijective : Function.Bijective a.atPin := by + constructor + · rintro ⟨v, i⟩ ⟨w, j⟩ h + have h' : v = w := a.vertex.injective (congrArg (fun p => p.1.1) h) + subst w + have hs : (a.pin v i).1 = (a.pin v j).1 := congrArg (fun p => p.1.2) h + have hn : (a.pin v i).2.val = (a.pin v j).2.val := congrArg (fun p => p.2.val) h + have ht : a.pin v i = a.pin v j := + Sigma.ext hs ((Fin.heq_ext_iff (congrArg (fun z => S.width r (a.vertex v, z)) hs)).mpr hn) + rw [(a.pin v).injective ht] + · rintro ⟨⟨v, j⟩, i⟩ + obtain ⟨u, hu⟩ := a.cover ⟨(v, j), i⟩ + change a.vertex u = v at hu + subst v + refine ⟨⟨u, (a.pin u).symm ⟨j, i⟩⟩, ?_⟩ + simp only [atPin, Equiv.apply_symm_apply] + rfl + +open scoped Classical in +/-- Computes the ends by the application `G.portEquiv.symm.trans (Equiv.ofBijective a.atPin +a.atPin_bijective)`. -/ +def ends : G.End ≃ S.Pin r := G.portEquiv.symm.trans (Equiv.ofBijective a.atPin a.atPin_bijective) + +open scoped Classical in +theorem ends_at (v : G.V) (p : G.Port v) : + a.ends (G.portEquiv ⟨v, p⟩) = S.port r (a.vertex v) (a.pin v p) := by + simp [ends, atPin] + + +open scoped Classical in +theorem ends_eq_of_port {v : G.V} {i : G.Port v} {e : G.End} {q : S.Pin r} + (location : G.portEquiv ⟨v, i⟩ = e) + (pin : S.port r (a.vertex v) (a.pin v i) = q) : a.ends e = q := by + rw [← location, a.ends_at] + exact pin + +end Seating + +variable (S r G) + +open scoped Classical in +/-- The data for the presentation construction, including `proper`, `internal`, `input`, +`output`. -/ +structure Presentation extends Seating S r G where + proper : S.Proper r + internal : ∀ e : G.E, S.Joins r (toSeating.ends (.inl (.inr e))) (toSeating.ends (.inr (.inr e))) + input : ∀ i : slots x, S.peer r (toSeating.ends (.inl (.inl i))).1 = none + output : ∀ i : slots y, S.peer r (toSeating.ends (.inr (.inl i))).1 = none + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- +# Evaluating an ordered-span presentation + +The extension of each internal assignment to all the pins is unique. +The proof includes loops and empty stations and does not divide by +the number of possible encodings. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {a b c : S.Pin r} + +open scoped Classical in +theorem Joins.symm (h : S.Joins r a b) (p : S.Proper r) : S.Joins r b a := + ⟨(p _ _ h.1).1, h.2.symm⟩ + +open scoped Classical in +theorem Joins.unique (h : S.Joins r a b) (k : S.Joins r a c) : b = c := by + have he := Option.some.inj (h.1.symm.trans k.1) + exact Sigma.ext he ((Fin.heq_ext_iff (congrArg (S.width r) he)).mpr (h.2.symm.trans k.2)) + +namespace Presentation +variable [Field F] {x y : Wire} {G : Diagram F x y} (p : S.Presentation r G) + (u : Val x) (v : Val y) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def read (z : G.E → Bool) : S.Pin r → Bool := + Sum.elim (Sum.elim (bits x u) z) (Sum.elim (bits y v) z) ∘ p.toSeating.ends.symm + +open scoped Classical in +theorem read_end (z : G.E → Bool) (t : G.End) : + p.read u v z (p.toSeating.ends t) = Sum.elim (Sum.elim (bits x u) z) (Sum.elim (bits y v) z) t + := by + simp only [read, Function.comp_apply, Equiv.symm_apply_apply] + +open scoped Classical in +/-- The indexed operation `p.read u v (fun _ => false) q.val`. -/ +def exterior (q : S.exposed r) := p.read u v (fun _ => false) q.val + +open scoped Classical in +theorem read_agrees (z : G.E → Bool) : S.Agrees r (p.exterior u v) (p.read u v z) := by + constructor + · rintro ⟨q, h⟩ + obtain ⟨t, rfl⟩ := p.toSeating.ends.surjective q + change p.read u v z (p.toSeating.ends t) = p.read u v _ (p.toSeating.ends t) + rw [read_end, read_end] + rcases t with (i|e)|(i|e) + · rfl + · rw [(p.internal e).1] at h + contradiction + · rfl + · rw [((p.internal e).symm p.proper).1] at h + contradiction + · intro q t h + obtain ⟨i, rfl⟩ := p.toSeating.ends.surjective q + rcases i with (i|e)|(i|e) + · exact (by simpa [p.input i] using h.1 : False).elim + · rw [h.unique (p.internal e), read_end, read_end] + rfl + · exact (by simpa [p.output i] using h.1 : False).elim + · rw [h.unique ((p.internal e).symm p.proper), read_end, read_end] + rfl + +open scoped Classical in +theorem read_injective : Function.Injective (p.read u v) := by + intro z w h + funext e + have he := congrFun h (p.toSeating.ends (.inl (.inr e))) + simpa only [read_end, Sum.elim_inl, Sum.elim_inr] using he + +open scoped Classical in +theorem read_surjective (w : S.Pin r → Bool) (hw : S.Agrees r (p.exterior u v) w) : + ∃ z, p.read u v z = w := by + let z e := w (p.toSeating.ends (.inl (.inr e))) + refine ⟨z, funext fun q => ?_⟩ + obtain ⟨t, rfl⟩ := p.toSeating.ends.surjective q + rcases t with (i|e)|(i|e) + · exact ((p.read_agrees u v z).1 ⟨_, p.input i⟩).trans (hw.1 ⟨_, p.input i⟩).symm + · rw [read_end]; rfl + · exact ((p.read_agrees u v z).1 ⟨_, p.output i⟩).trans (hw.1 ⟨_, p.output i⟩).symm + · rw [read_end] + exact hw.2 _ _ (p.internal e) + +open scoped Classical in +theorem table_eq (z : G.E → Bool) (w : G.V) : + S.table r (p.vertex w) (p.read u v z ∘ S.port r (p.vertex w)) = G.vertex u v z w := by + rw [p.sample, ← Transcript.sample_wires] + apply congrArg (Transcript.sample _) + funext i + simp only [Function.comp_apply, ← p.toSeating.ends_at, read_end] + rcases i with i | i + · change Sum.elim _ _ (G.src ⟨w, i⟩) = _ + simp only [Transcript.wires] + cases G.src ⟨w, i⟩ <;> rfl + · change Sum.elim _ _ (G.dst ⟨w, i⟩) = _ + simp only [Transcript.wires] + cases G.dst ⟨w, i⟩ <;> rfl + +open scoped Classical in +theorem eval : S.eval r (p.exterior u v) = G.eval u v := by + unfold Scheme.eval Diagram.eval + symm + refine Fintype.sum_of_injective (p.read u v) (p.read_injective u v) _ _ ?_ ?_ + · intro w hw + exact ite_eq_right fun h => hw (p.read_surjective u v w h) + · intro z + rw [ite_eq_left (p.read_agrees u v z)] + exact Fintype.prod_of_injective p.vertex p.vertex.injective _ _ + (fun i hi => p.vacant i hi _) (fun w => (p.table_eq u v z w).symm) + +end Presentation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- +# Reordering a presented diagram + +The original vertex names, internal edge names and exterior ends +are retained. Only the order of ports at each vertex changes. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Transcript + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {r : S.format.obj} + {G : Diagram F x y} (p : S.Presentation r G) + +/-- The condition `∀ t : G.End, S.direction r (p.toSeating.ends t).1 = t.isRight` on the +specified data. -/ +def Directed : Prop := + ∀ t : G.End, S.direction r (p.toSeating.ends t).1 = t.isRight + +theorem side (h : p.Directed) (v : G.V) (i : G.Port v) : + S.direction r (p.vertex v, (p.pin v i).1) = i.isRight := by + have he := h (G.portEquiv ⟨v, i⟩) + rw [p.toSeating.ends_at] at he + cases i <;> exact he + +theorem split {A B C D : Type} (e : A ⊕ B ≃ C ⊕ D) + (h : ∀ i, (e i).isRight = i.isRight) : + ∃ f : A ≃ C, ∃ g : B ≃ D, f.sumCongr g = e := by + have l (a : A) : ∃ c, e (.inl a) = .inl c := by + have hi := h (.inl a) + cases he : e (.inl a) <;> simp_all + have r (b : B) : ∃ d, e (.inr b) = .inr d := by + have hi := h (.inr b) + cases he : e (.inr b) <;> simp_all + choose f hf using l + choose g hg using r + have he : Sum.map f g = e := by funext i; cases i <;> simp [hf, hg] + have hk : Function.Bijective (Sum.map f g) := he.symm ▸ e.bijective + obtain ⟨h₁, h₂⟩ := Sum.map_bijective.mp hk + exact ⟨Equiv.ofBijective f h₁, Equiv.ofBijective g h₂, Equiv.ext (congrFun he)⟩ + +/-- The value specified by `(S.pattern r (p.vertex v)).orderedTable (p.vertex v).2.2`. -/ +def stationTable (v : G.V) := (S.pattern r (p.vertex v)).orderedTable (p.vertex v).2.2 + +/-- Reindexes `Ports (p.stationTable v)` and `S.LocalPin r (p.vertex v)` by an equivalence. -/ +def stationPin (v : G.V) : Ports (p.stationTable v) ≃ S.LocalPin r (p.vertex v) := + (S.pattern r (p.vertex v)).orderedPin (p.vertex v).2.2 + +variable (h : p.Directed) + +include h in +theorem split_pin (v : G.V) : + ∃ f : slots (p.stationTable v).1 ≃ slots (G.table v).1, + ∃ g : slots (p.stationTable v).2.1 ≃ slots (G.table v).2.1, + f.sumCongr g = (p.stationPin v).trans (p.pin v).symm := by + apply split + intro i + rw [← p.side h, Equiv.trans_apply, Equiv.apply_symm_apply] + exact (S.pattern r (p.vertex v)).pin_side _ i + +/-- The value specified by `(p.split_pin h v).choose`. -/ +def left (v : G.V) := (p.split_pin h v).choose +/-- The value specified by `(p.split_pin h v).choose_spec.choose`. -/ +def right (v : G.V) := (p.split_pin h v).choose_spec.choose + +/-- Builds `Diagram F x y where V` with the specified `table`, `src`, `dst`. -/ +def ordered : Diagram F x y where + V := G.V + E := G.E + table := p.stationTable + src := (Equiv.sigmaCongrRight (p.left h)).trans G.src + dst := (Equiv.sigmaCongrRight (p.right h)).trans G.dst + +/-- Builds `S.Seating r (p.ordered h) where vertex` with the specified `vertex`, `pin`, `cover`, +`sample`. -/ +def seatOrdered : S.Seating r (p.ordered h) where + vertex := p.vertex + pin := p.stationPin + cover := p.cover + sample v t := ((S.pattern r (p.vertex v)).sample_ordered (p.vertex v).2.2 t).symm + vacant := p.vacant + +theorem same_ends : (p.seatOrdered h).ends = p.toSeating.ends := by + apply Equiv.ext + intro t + obtain ⟨⟨v, i⟩, rfl⟩ := (p.ordered h).portEquiv.surjective t + rw [Seating.ends_at] + let a := (p.left h v).sumCongr (p.right h v) + have eq : (p.ordered h).portEquiv ⟨v, i⟩ = G.portEquiv ⟨v, a i⟩ := by cases i <;> rfl + rw [eq] + refine Eq.trans ?_ (p.toSeating.ends_at v (a i)).symm + change S.port r (p.vertex v) (p.stationPin v i) = S.port r (p.vertex v) (p.pin v (a i)) + have ha : a = (p.stationPin v).trans (p.pin v).symm := (p.split_pin h v).choose_spec.choose_spec + rw [ha] + exact congrArg _ ((p.pin v).apply_symm_apply (p.stationPin v i)).symm + +/-- Builds `S.Presentation r (p.ordered h) where toSeating` with the specified `toSeating`, +`proper`, `internal`, `input`. -/ +def toOrdered : S.Presentation r (p.ordered h) where + toSeating := p.seatOrdered h + proper := p.proper + internal := by rw [same_ends]; exact p.internal + input := by rw [same_ends]; exact p.input + output := by rw [same_ends]; exact p.output + +theorem ordered_ends : (p.toOrdered h).toSeating.ends = p.toSeating.ends := p.same_ends h + +theorem ordered_eval (a : Val x) (b : Val y) : (p.ordered h).eval a b = G.eval a b := by + rw [← (p.toOrdered h).eval, ← p.eval] + unfold exterior read + rw [ordered_ends] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- +# Port order of a canonical presentation + +On internal spans the two ends have the same offset. Consecutive +local offsets therefore advance the position on the remote side. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +open Transcript + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {r : S.format.obj} + +private def startFromOrdered (S : Scheme F) (r : S.format.obj) (s : S.Span) := + (S.pattern r s.1).start s.1.2.2 s.2 + +private def location (z : S.Pin r) : S.Vtx × ℕ := + (z.1.1, S.startFromOrdered r z.1 + z.2.val) + +private def remote (z : S.Pin r) : Option (S.Vtx × ℕ) := + (S.peer r z.1).map fun t => (t.1, S.startFromOrdered r t + z.2.val) + +omit [Field F] in +private theorem Joins.remote_eq {z w : S.Pin r} (h : S.Joins r z w) : + remote z = some (location w) := by + simp only [remote, location, h.1, h.2, Option.map_some] + +namespace Presentation +variable {G : Diagram F x y} (p : S.Presentation r G) + +private def pinAt (v : G.V) (i : G.Port v) := S.port r (p.vertex v) (p.pin v i) + +private def offset (G : Diagram F x y) (v : G.V) : G.Port v → ℕ := + Sum.elim (fun i => (positions (G.table v).1 i).val) + (fun i => (positions (G.table v).2.1 i).val) + +private def Aligned : Prop := + ∀ v i, offset G v i = S.startFromOrdered r (p.pinAt v i).1 + (p.pinAt v i).2.val + +private def relabel (t : G.V × ℕ) : S.Vtx × ℕ := (p.vertex t.1, t.2) + +private theorem relabel_inj : Function.Injective p.relabel := by + intro i j h + exact Prod.ext (p.vertex.injective (congrArg Prod.fst h)) (congrArg (Prod.snd (α := S.Vtx)) h) + +private theorem loc_src (ha : p.Aligned) (e : slots x ⊕ G.E) : + location (p.toSeating.ends (.inl e)) = + p.relabel ((G.src.symm e).1, (positions (G.table (G.src.symm e).1).1 (G.src.symm e).2).val) + := by + obtain ⟨⟨v, i⟩, rfl⟩ := G.src.surjective e + rw [Equiv.symm_apply_apply] + have he : p.toSeating.ends (.inl (G.src ⟨v, i⟩)) = p.pinAt v (.inl i) := + p.toSeating.ends_at v (.inl i) + rw [he, location, ← ha] + rfl + +private theorem loc_dst (ha : p.Aligned) (e : slots y ⊕ G.E) : + location (p.toSeating.ends (.inr e)) = + p.relabel ((G.dst.symm e).1, (positions (G.table (G.dst.symm e).1).2.1 (G.dst.symm e).2).val) + := by + obtain ⟨⟨v, i⟩, rfl⟩ := G.dst.surjective e + rw [Equiv.symm_apply_apply] + have he : p.toSeating.ends (.inr (G.dst ⟨v, i⟩)) = p.pinAt v (.inr i) := + p.toSeating.ends_at v (.inr i) + rw [he, location, ← ha] + rfl + +private theorem mapped_peer (ha : p.Aligned) (v : G.V) (i : G.Port v) : + (G.portPeer v i).2.map p.relabel = remote (p.pinAt v i) := by + rcases i with i | i + · have he : p.pinAt v (.inl i) = p.toSeating.ends (.inl (G.src ⟨v, i⟩)) := + (p.toSeating.ends_at v (.inl i)).symm + rw [he] + unfold Diagram.portPeer + dsimp only + cases G.src ⟨v, i⟩ with + | inl i => simp only [remote, p.input, Sum.elim_inl, Option.map_none] + | inr e => rw [(p.internal e).remote_eq, p.loc_dst ha]; rfl + · have he : p.pinAt v (.inr i) = p.toSeating.ends (.inr (G.dst ⟨v, i⟩)) := + (p.toSeating.ends_at v (.inr i)).symm + rw [he] + unfold Diagram.portPeer + dsimp only + cases G.dst ⟨v, i⟩ with + | inl i => simp only [remote, p.output, Sum.elim_inl, Option.map_none] + | inr e => rw [((p.internal e).symm p.proper).remote_eq, p.loc_src ha]; rfl + +private theorem adjacent (ha : p.Aligned) (v : G.V) (i j : G.Port v) + (hb : i.isRight = j.isRight) (hs : (p.pinAt v i).1 = (p.pinAt v j).1) + (hn : offset G v i + 1 = offset G v j) : + G.portPeer v j = Diagram.advance (G.portPeer v i) := by + have he : (p.pinAt v i).2.val + 1 = (p.pinAt v j).2.val := by + rw [ha, ha] at hn + have := congrArg (S.startFromOrdered r) hs + omega + apply Prod.ext + · cases i <;> cases j <;> exact hb.symm + · have inj : Function.Injective (Option.map p.relabel) := by + rintro (_|a) (_|b) he <;> simp_all [p.relabel_inj.eq_iff] + apply inj + let a : S.Vtx × ℕ → S.Vtx × ℕ := fun t => (t.1, t.2 + 1) + have eq : (Diagram.advance (G.portPeer v i)).2.map p.relabel = + ((G.portPeer v i).2.map p.relabel).map a := by + unfold Diagram.advance + cases (G.portPeer v i).2 <;> rfl + rw [eq, p.mapped_peer ha, p.mapped_peer ha] + unfold remote + rw [← he, ← hs] + cases S.peer r (p.pinAt v i).1 <;> rfl + +private def position (G : Diagram F x y) (v : G.V) : G.Port v ≃ Fin (G.arity v) := + positions (.pair (G.table v).1 (G.table v).2.1) + +omit [Field F] in +private theorem position_val (v : G.V) (i : G.Port v) : + (position G v i).val = (if i.isRight then wd (G.table v).1 else 0) + offset G v i := by + cases i + · exact (Nat.zero_add _).symm + · rfl + +/-- The value specified by `⟨(if i.isRight then 2 ^ S.e else 0) + (p.pin v i).1.val, by have := +(p.pin v i).1.isLt rw [pow_succ] split <;> omega⟩`. -/ +def block (v : G.V) (i : G.Port v) : Fin (2 ^ (S.e + 1)) := + ⟨(if i.isRight then 2 ^ S.e else 0) + (p.pin v i).1.val, by + have := (p.pin v i).1.isLt + rw [pow_succ] + split <;> omega⟩ + +private theorem block_mono (h : p.Directed) (ha : p.Aligned) (v : G.V) (i j : G.Port v) + (hn : (position G v i).val ≤ (position G v j).val) : p.block v i ≤ p.block v j := by + simp only [position_val] at hn + by_cases hb : i.isRight = j.isRight + · rw [hb, ha, ha] at hn + suffices he : (p.pin v i).1 ≤ (p.pin v j).1 by + simp only [block, Fin.mk_le_mk, hb] + exact Nat.add_le_add_left he _ + by_contra! he + have hd := (p.side h v j).trans (hb.symm.trans (p.side h v i).symm) + have ht : S.startFromOrdered r (p.pinAt v j).1 + S.width r (p.pinAt v j).1 + ≤ S.startFromOrdered r (p.pinAt v i).1 := + (S.pattern r (p.vertex v)).start_left (p.vertex v).2.2 hd he + have := (p.pinAt v j).2.isLt + omega + · rcases i with i | i <;> rcases j with j | j + · exact (hb rfl).elim + · have := (p.pin v (.inl i)).1.isLt + change 0 + _ ≤ 2 ^ S.e + _ + omega + · have : offset G v (.inl j) < wd (G.table v).1 := Fin.isLt _ + change wd _ + _ ≤ 0 + _ at hn + omega + · exact (hb rfl).elim + +private theorem block_next (ha : p.Aligned) (v : G.V) (i j : G.Port v) + (hn : (position G v i).val + 1 = (position G v j).val) (he : p.block v i = p.block v j) : + G.portPeer v j = Diagram.advance (G.portPeer v i) := by + have he' := congrArg Fin.val he + simp only [block] at he' + have hb : i.isRight = j.isRight := by + have hi := (p.pin v i).1.isLt + have hj := (p.pin v j).1.isLt + cases hi' : i.isRight <;> cases hj' : j.isRight <;> + simp [hi', hj'] at he' ⊢ <;> omega + have hs : (p.pin v i).1 = (p.pin v j).1 := by + rw [hb] at he' + exact Fin.ext (Nat.add_left_cancel he') + simp only [position_val, hb] at hn + exact p.adjacent ha v i j hb (congrArg (Prod.mk (p.vertex v)) hs) (by omega) + +private theorem portOrder (h : p.Directed) (ha : p.Aligned) : G.PortOrder (2 ^ (S.e + 1)) := by + intro v + let e := position G v + refine ⟨p.block v ∘ e.symm, ?_, ?_⟩ + · intro i j hn + apply p.block_mono h ha + simpa only [e, Equiv.apply_symm_apply] using (show i.val ≤ j.val from hn) + · intro i j hn he + apply p.block_next ha v (e.symm i) (e.symm j) _ he + simpa only [e, Equiv.apply_symm_apply] using hn + +private theorem ordered_aligned (h : p.Directed) : (p.toOrdered h).Aligned := by + rintro v (i|i) + · exact (S.pattern r (p.vertex v)).position_left (p.vertex v).2.2 i + · exact (S.pattern r (p.vertex v)).position_right (p.vertex v).2.2 i + +theorem ordered_order (h : p.Directed) : (p.ordered h).PortOrder (2 ^ (S.e + 1)) := by + apply (p.toOrdered h).portOrder + · unfold Directed + rw [p.ordered_ends h] + exact h + · exact p.ordered_aligned h + +/-- Read the peer and its offset using only this pattern, neighbor +patterns, and their local station names. -/ +def route {d k e : ℕ} (A : Pattern F d k e) (j : Coloring.B k) (near : Coloring.B d → Pattern F d k + e) + (name : Coloring.B d → Coloring.B k → ℕ) : List (Bool × Option (ℕ × ℕ)) := + List.ofFn fun i : Fin (wd (A.wire j false) + wd (A.wire j true)) => + let arg := (positions (.pair (A.wire j false) (A.wire j true))).symm i + let pin := A.orderedPin j arg + (arg.isRight, (A.peer j pin.1).map (fun t => + (name t.1 t.2.1, (near t.1).start t.2.1 t.2.2 + pin.2.val))) + +/-- The indexed operation `route (S.pattern r v) v.2.2 (fun j => S.pattern r ((r v.1).1 j, +v.2.1, v.2.2)) (fun j k => f ((r v.1).1 j, v.2.1, k))`. -/ +def peerRows (v : S.Vtx) (f : S.Vtx → ℕ) (r : S.format.obj) := + route (S.pattern r v) v.2.2 (fun j => S.pattern r ((r v.1).1 j, v.2.1, v.2.2)) + (fun j k => f ((r v.1).1 j, v.2.1, k)) + +/-- Every station sees exactly the table and peer sequence specified +by its pattern. No external bit names are involved. -/ +def Canonical : Prop := + ∀ v, G.table v = p.stationTable v ∧ ∀ f : S.Vtx → ℕ, + List.ofFn (fun i : Fin (G.arity v) => + ((G.peer v i).1, (G.peer v i).2.map (Prod.map (f ∘ p.vertex) id))) = + peerRows (p.vertex v) f r + +theorem canonical_ordered (h : p.Directed) : (p.toOrdered h).Canonical := by + let q := p.toOrdered h + have hq : q.Aligned := p.ordered_aligned h + intro v + refine ⟨rfl, fun f => ?_⟩ + let A := S.pattern r (p.vertex v) + let j := (p.vertex v).2.2 + let G' := p.ordered h + unfold peerRows route + refine congrArg List.ofFn (funext fun i : Fin (G'.arity v) => ?_) + let x := (position G' v).symm i + have he := q.mapped_peer hq v x + apply Prod.ext + · change (G'.portPeer v x).1 = x.isRight + cases x <;> rfl + · have e : (G'.peer v i).2.map (Prod.map (f ∘ q.vertex) id) = + (remote (q.pinAt v x)).map (Prod.map f id) := by + rw [← he, Option.map_map] + rfl + change (G'.peer v i).2.map (Prod.map (f ∘ q.vertex) id) = _ + rw [e] + let s := A.orderedPin j x + change (((A.peer j s.1).map _).map _).map _ = (A.peer j s.1).map _ + cases A.peer j s.1 <;> rfl + +end Presentation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- +# Presenting a core with ordered unit bundles + +One core station fits at a live occurrence. Opposite spans use the +same ordering of bits in the unit. The longer host names are shared +by all blocks, while each span uses only local indices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +open Coloring Packing + +variable {F T : Type} [Field F] {x y : Wire} {L : Fringe x y T} {h u : ℕ} + (S : Scheme F) (r : S.format.obj) (G : HostNet F L h u) + +open scoped Classical in +/-- Computes the side by the application `cond t (G.dst i) (G.src i)`. -/ +def side (i : G.E) (t : Bool) := cond t (G.dst i) (G.src i) + +open scoped Classical in +/-- The end bit of type `G.diagram.End`, constructed using `G.units.bits.symm (i, j)`. -/ +def endBit (i : G.E) (t : Bool) (j : Fin u) : G.diagram.End := + let q := G.units.bits.symm (i, j) + cond t (.inr (.inr q)) (.inl (.inr q)) + +open scoped Classical in +/-- The value specified by `((host (side G i t), block (G.ix i), 0), stub i t)`. -/ +def spanAt (host : G.V ↪ B S.m) (block : Cell h ↪ B S.h) (stub : G.E → Bool → B S.e) + (i : G.E) (t : Bool) : S.Span := + ((host (side G i t), block (G.ix i), 0), stub i t) + +open scoped Classical in +/-- Requires `0 < S.width r p ∧ S.direction r p = false ∧ (S.peer r p).isSome`. -/ +def outgoing (p : S.Span) : Prop := + 0 < S.width r p ∧ S.direction r p = false ∧ (S.peer r p).isSome + +open scoped Classical in +/-- The data for the posting construction, including `host`, `block`, `stub`, `index`, +`ordered`. -/ +structure Posting extends S.Presentation r G.diagram where + /-- Embeds the coordinates as `G.V ↪ B S.m`. -/ + host : G.V ↪ B S.m + /-- Embeds the coordinates as `Cell h ↪ B S.h`. -/ + block : Cell h ↪ B S.h + /-- The `Posting` component of type `G.E → Bool → B S.e`. -/ + stub : G.E → Bool → B S.e + /-- The identification of the indices of type `G.V → G.V → B S.d`. -/ + index : G.V → G.V → B S.d + vertex_eq : ∀ v, vertex v = (host (G.units.place v).1, block (G.units.place v).2, 0) + ordered : ∀ i t j, let p := toSeating.ends (endBit G i t j) + p.1 = S.spanAt G host block stub i t ∧ p.2.val = j.val + length : ∀ i t, S.width r (S.spanAt G host block stub i t) = u + dir : ∀ i t, S.direction r (S.spanAt G host block stub i t) = t + link : ∀ i t, let p := S.spanAt G host block stub i t + (S.pattern r p.1).peer p.1.2.2 p.2 = + some (index (side G i t) (side G i (!t)), 0, stub i (!t)) + +namespace Posting + +variable {S r G} (p : S.Posting r G) (hu : 0 < u) + +open scoped Classical in +/-- Computes the span by the application `S.spanAt G p.host p.block p.stub`. -/ +abbrev span := S.spanAt G p.host p.block p.stub + +open scoped Classical in +theorem span_end (j : S.Span) (hj : 0 < S.width r j) (hp : S.peer r j ≠ none) : + ∃ e t, p.span e t = j := by + obtain ⟨q, hq⟩ := p.toSeating.ends.surjective ⟨j, ⟨0, hj⟩⟩ + have he : (p.toSeating.ends q).1 = j := congrArg Sigma.fst hq + rcases q with (t|e)|(t|e) + · exact (hp (he ▸ p.input t)).elim + · obtain ⟨⟨e, n⟩, rfl⟩ := G.units.bits.symm.surjective e + exact ⟨e, false, (p.ordered e false n).1.symm.trans he⟩ + · exact (hp (he ▸ p.output t)).elim + · obtain ⟨⟨e, n⟩, rfl⟩ := G.units.bits.symm.surjective e + exact ⟨e, true, (p.ordered e true n).1.symm.trans he⟩ + +open scoped Classical in +theorem place_of_span {w : G.diagram.V} {j : B S.e} {e : G.E} {t : Bool} + (he : p.span e t = (p.vertex w, j)) : G.units.place w = (side G e t, G.ix e) := by + rw [p.vertex_eq] at he + have h₁ := p.host.injective (congrArg (fun i : S.Span => i.1.1) he) + have h₂ := p.block.injective (congrArg (fun i : S.Span => i.1.2.1) he) + exact Prod.ext h₁.symm h₂.symm + +open scoped Classical in +theorem ends_symm_span {s : S.Span} {e : G.E} {t : Bool} + (he : p.span e t = s) (b : Fin (S.width r s)) : + p.toSeating.ends.symm ⟨s, b⟩ = + endBit G e t (b.cast ((congrArg (S.width r) he.symm).trans (p.length e t))) := by + let c := b.cast ((congrArg (S.width r) he.symm).trans (p.length e t)) + apply p.toSeating.ends.symm_apply_eq.mpr + symm + have he' := (p.ordered e t c).1.trans he + exact Sigma.ext he' ((Fin.heq_ext_iff (congrArg (S.width r) he')).mpr (p.ordered e t c).2) + +include hu in +open scoped Classical in +theorem target (i : G.E) : + (r (p.host (G.src i))).1 (p.index (G.src i) (G.dst i)) = p.host (G.dst i) := by + let t : Fin u := ⟨0, hu⟩ + have he := (p.internal (G.units.bits.symm (i, t))).1 + change S.peer r (p.toSeating.ends (endBit G i false t)).1 = + some (p.toSeating.ends (endBit G i true t)).1 at he + rw [(p.ordered _ _ _).1, (p.ordered _ _ _).1, peer, p.link] at he + exact congrArg (fun q : S.Span => q.1.1) (Option.some.inj he) + +include hu in +open scoped Classical in +theorem distinct {i j : G.E} (h : p.span i false = p.span j false) : i = j := by + let t : Fin u := ⟨0, hu⟩ + have hi := p.ordered i false t + have hj := p.ordered j false t + have ht : p.toSeating.ends (endBit G i false t) = p.toSeating.ends (endBit G j false t) := by + have hf := hi.1.trans (h.trans hj.1.symm) + exact Sigma.ext hf ((Fin.heq_ext_iff (congrArg (S.width r) hf)).mpr (hi.2.trans hj.2.symm)) + have he := Sum.inr.inj (Sum.inl.inj (p.toSeating.ends.injective ht)) + exact (Prod.mk.inj (G.units.bits.symm.injective he)).1 + +include hu in +open scoped Classical in +theorem enumerates (w : S.Span) : S.outgoing r w ↔ ∃ i, p.span i false = w := by + constructor + · rintro ⟨hl, hd, hp⟩ + obtain ⟨i, t, he⟩ := p.span_end w hl (by intro h; simp [h] at hp) + cases t + · exact ⟨i, he⟩ + · rw [← he, p.dir] at hd + cases hd + · rintro ⟨i, rfl⟩ + unfold outgoing span + rw [p.length, p.dir, peer, p.link] + exact ⟨hu, rfl, rfl⟩ + +end Posting +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- +# Withdrawing zero-arity tables between contractions + +Replace every such table by the scalar one. The original scalars +are multiplied into the transition weight, including when one is +zero. All wire, station and host indices remain unchanged. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {F : Type} [Field F] {x y : Wire} + +open scoped Classical in +/-- The value specified by `{G with table := fun v => ⟨(G.table v).1, (G.table v).2.1, fun a b +=> if G.arity v = 0 then 1 else (G.table v).2.2 a b⟩}`. -/ +abbrev Diagram.sweep (G : Diagram F x y) : Diagram F x y := + {G with table := fun v => ⟨(G.table v).1, (G.table v).2.1, + fun a b => if G.arity v = 0 then 1 else (G.table v).2.2 a b⟩} + +open scoped Classical in +theorem Diagram.sweep_neutral (G : Diagram F x y) (v : G.V) + (h : G.arity v = 0) (t : Transcript.Ports (G.table v) → Bool) : + Transcript.sample (G.sweep.table v) t = 1 := + ite_eq_left h + +namespace Packing + +open scoped Classical in +/-- The value specified by `{G with diagram := G.diagram.sweep, units := ⟨G.units.place, +G.units.bits, G.units.left, G.units.right⟩}`. -/ +abbrev HostNet.sweep {T : Type} {L : Fringe x y T} {h u : ℕ} + (G : HostNet F L h u) : HostNet F L h u := + {G with diagram := G.diagram.sweep, units := + ⟨G.units.place, G.units.bits, G.units.left, G.units.right⟩} + +end Packing + +namespace Assembly +open Coloring Packing + +namespace Pattern +variable {d e k : ℕ} (P : Pattern F d k e) + +open scoped Classical in +/-- The condition `∀ s, P.width j s = 0` on the specified data. -/ +def empty (j : B k) := ∀ s, P.width j s = 0 + +open scoped Classical in +/-- Returns `P.value j (fun _ _ => false)` when `P.empty j` holds, and `1` otherwise. -/ +def charge (j : B k) := if P.empty j then P.value j (fun _ _ => false) else 1 + +open scoped Classical in +/-- Uses `{P with value := fun j t => if P.empty j then 1 else P.value j t}` as the +representation. -/ +abbrev sweep := {P with value := fun j t => if P.empty j then 1 else P.value j t} + +open scoped Classical in +theorem after_sweep (j : B k) (t : (s : B e) → Fin (P.width j s) → Bool) : + P.value j t = P.charge j * P.sweep.value j t := by + by_cases h : P.empty j + · simp only [charge, ite_eq_left h, mul_one] + apply congrArg (P.value j) + funext s i + exact (Nat.not_lt_zero _ (i.isLt.trans_eq (h s))).elim + · simp only [charge, ite_eq_right h, one_mul] + +end Pattern + +namespace Scheme +variable (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +/-- Uses `{S with decode := fun i => (S.decode i).sweep}` as the representation. -/ +abbrev sweep := {S with decode := fun i => (S.decode i).sweep} + +open scoped Classical in +/-- The product of `(S.decode i).charge j` indexed by `j`. -/ +def scalar (i : B S.ℓ) := ∏ j, (S.decode i).charge j + +open scoped Classical in +theorem sweep_eval (u : S.exposed r → Bool) : + S.eval r u = Fmt.weight S.scalar r * S.sweep.eval r u := by + have hc : Fmt.weight S.scalar r = ∏ v : S.Vtx, (S.pattern r v).charge v.2.2 := by + simp only [Vtx, Fintype.prod_prod_type, pattern, Fmt.weight, scalar] + unfold eval + rw [hc, Finset.mul_sum] + refine Finset.sum_congr rfl fun y _ => ?_ + by_cases h : S.Agrees r u y + · rw [ite_eq_left h, ite_eq_left (show S.sweep.Agrees r u y from h), ← Finset.prod_mul_distrib] + exact Finset.prod_congr rfl fun j _ => (S.pattern r j).after_sweep j.2.2 _ + · rw [ite_eq_right h, ite_eq_right (show ¬ S.sweep.Agrees r u y from h), mul_zero] + +variable {S r} {G : Diagram F x y} (p : S.Presentation r G) + +open scoped Classical in +theorem Presentation.empty_iff (v : G.V) : + (S.pattern r (p.vertex v)).empty (p.vertex v).2.2 ↔ G.arity v = 0 := by + have hc := Fintype.card_congr (p.pin v) + simp only [Diagram.Port, LocalPin, Fintype.card_sigma, Fintype.card_sum, card_slots, + Fintype.card_fin] at hc + change G.arity v = ∑ s, S.width r (p.vertex v, s) at hc + rw [hc, Finset.sum_eq_zero_iff] + simp [Pattern.empty, width] + +open scoped Classical in +/-- Builds `S.sweep.Seating r G.sweep where vertex` with the specified `vertex`, `pin`, `cover`, +`sample`. -/ +def Presentation.sweepSeats : S.sweep.Seating r G.sweep where + vertex := p.vertex + pin := p.pin + cover := p.cover + sample v t := by + change (if (S.pattern r (p.vertex v)).empty (p.vertex v).2.2 then 1 else S.table r _ t) = + if G.arity v = 0 then 1 else Transcript.sample _ _ + simp only [p.empty_iff] + exact congrArg (fun z => if G.arity v = 0 then 1 else z) (p.sample v t) + vacant v hv t := by + change (if (S.pattern r v).empty v.2.2 then 1 else S.table r v t) = 1 + exact ite_eq_left_iff.mpr (fun _ => p.vacant v hv t) + +open scoped Classical in +theorem Presentation.sweep_end (t : G.End) : p.sweepSeats.ends t = p.toSeating.ends t := by + obtain ⟨⟨v, i⟩, rfl⟩ := G.portEquiv.surjective t + change p.sweepSeats.ends (G.sweep.portEquiv ⟨v, i⟩) = _ + rw [Seating.ends_at, Seating.ends_at] + rfl + +open scoped Classical in +/-- Builds `S.sweep.Presentation r G.sweep where toSeating` with the specified `toSeating`, +`proper`, `internal`, `input`. -/ +def Presentation.sweep : S.sweep.Presentation r G.sweep where + toSeating := p.sweepSeats + proper := p.proper + internal e := by erw [p.sweep_end, p.sweep_end]; exact p.internal e + input i := by erw [p.sweep_end]; exact p.input i + output i := by erw [p.sweep_end]; exact p.output i + +open scoped Classical in +/-- The value specified by `⟨p.toPresentation.sweep, p.host, p.block, p.stub, p.index, +p.vertex_eq, p.ordered, p.length, p.dir, p.link⟩`. -/ +def Posting.sweep {T : Type} {L : Fringe x y T} {h u : ℕ} {G : HostNet F L h u} + (p : S.Posting r G) : S.sweep.Posting r G.sweep := + ⟨p.toPresentation.sweep, p.host, p.block, p.stub, p.index, p.vertex_eq, p.ordered, p.length, + p.dir, p.link⟩ + +include p in +open scoped Classical in +theorem Presentation.sweep_eval (a : Val x) (b : Val y) : + G.eval a b = Fmt.weight S.scalar r * G.sweep.eval a b := by + rw [← p.eval, ← p.sweep.eval] + exact Scheme.sweep_eval S r _ + +end Scheme +end Assembly +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- +# Taking the displayed spans as the core bundles + +An arbitrary bijection grouping parallel edges can scramble the two +ends of a packet. Instead use the source span and its local bit +ordinal as the new bundle name and bit index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation + +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} {x y : Wire} + {G : Diagram F x y} (p : S.Presentation r G) + +open scoped Classical in +/-- Computes the wire pin by the application `p.toSeating.ends (cond t (.inr (.inr e)) (.inl +(.inr e)))`. -/ +def wirePin (e : G.E) (t : Bool) : S.Pin r := + p.toSeating.ends (cond t (.inr (.inr e)) (.inl (.inr e))) + +open scoped Classical in +theorem wirePin_at (e : G.E) (t : Bool) : + (p.wirePin e t).1.1 = p.vertex (cond t (G.target e) (G.source e)) := by + have h (a : G.End) : (p.toSeating.ends a).1.1 = p.vertex (G.station a) := by + obtain ⟨⟨v, i⟩, rfl⟩ := G.portEquiv.surjective a + rw [Seating.ends_at, G.station_port] + rfl + cases t <;> exact h _ + +open scoped Classical in +theorem wirePin_peer (e : G.E) (t : Bool) : + S.peer r (p.wirePin e t).1 = some (p.wirePin e (!t)).1 := by + cases t + · exact (p.internal e).1 + · exact (p.proper _ _ (p.internal e).1).1 + +open scoped Classical in +theorem wirePin_dir (h : p.Directed) (e : G.E) (t : Bool) : + S.direction r (p.wirePin e t).1 = t := by cases t <;> exact h _ + +open scoped Classical in +/-- The condition `∀ e, S.width r (p.wirePin e false).1 = u` on the specified data. -/ +def Uniform (u : ℕ) : Prop := ∀ e, S.width r (p.wirePin e false).1 = u + +open scoped Classical in +theorem wirePin_width {u : ℕ} (h : p.Uniform u) (e : G.E) (t : Bool) : + S.width r (p.wirePin e t).1 = u := by + cases t + · exact h e + · exact (p.proper _ _ (p.internal e).1).2.1.symm.trans (h e) + +open scoped Classical in +/-- The indexed operation `↥(Set.range (fun e => (p.wirePin e false).1))`. -/ +abbrev Bundle := ↥(Set.range (fun e => (p.wirePin e false).1)) + +open scoped Classical in +/-- Uses `i.property.choose` as the representation. -/ +def root (i : p.Bundle) : G.E := i.property.choose + +open scoped Classical in +theorem origin (i : p.Bundle) : (p.wirePin (p.root i) false).1 = i.val := i.property.choose_spec + +variable {u : ℕ} (hd : p.Directed) (hu : p.Uniform u) + +open scoped Classical in +/-- The value specified by `(⟨(p.wirePin e false).1, ⟨e, rfl⟩⟩, (p.wirePin e false).2.cast (hu +e))`. -/ +def locate (e : G.E) : p.Bundle × Fin u := + (⟨(p.wirePin e false).1, ⟨e, rfl⟩⟩, (p.wirePin e false).2.cast (hu e)) + +open scoped Classical in +theorem located (e : G.E) (t : Bool) : + (p.wirePin e t).1 = (p.wirePin (p.root (p.locate hu e).1) t).1 ∧ + (p.wirePin e t).2.val = (p.locate hu e).2.val := by + have h := (p.origin (p.locate hu e).1).symm + cases t + · exact ⟨h, rfl⟩ + · refine ⟨Option.some.inj ?_, (p.internal e).2.symm⟩ + exact (p.wirePin_peer e false).symm.trans ((congrArg (S.peer r) h).trans (p.wirePin_peer _ + false)) + +include hd in +open scoped Classical in +theorem locate_bijective : Function.Bijective (p.locate hu) := by + constructor + · intro i j h + have he : (p.wirePin i false).1 = (p.wirePin j false).1 := congrArg (fun z => z.1.val) h + have ht : (p.wirePin i false).2.val = (p.wirePin j false).2.val := congrArg (fun z => z.2.val) h + have hp : p.wirePin i false = p.wirePin j false := + Sigma.ext he ((Fin.heq_ext_iff (congrArg (S.width r) he)).mpr ht) + exact Sum.inr.inj (Sum.inl.inj (p.toSeating.ends.injective hp)) + · rintro ⟨⟨_, e, rfl⟩, j⟩ + let a : S.Pin r := ⟨(p.wirePin e false).1, j.cast (hu e).symm⟩ + obtain ⟨t, ht⟩ := p.toSeating.ends.surjective a + have hdir : t.isRight = false := (hd t).symm.trans + ((congrArg (fun x => S.direction r x.1) ht).trans (p.wirePin_dir hd e false)) + rcases t with (i|k)|i + · have hh := p.input i + rw [ht] at hh + exact (Option.some_ne_none _ ((p.wirePin_peer e false).symm.trans hh)).elim + · have hspan := congrArg Sigma.fst ht + have hbit := congrArg (fun x => x.2.val) ht + exact ⟨k, Prod.ext (Subtype.ext hspan) (Fin.ext hbit)⟩ + · contradiction + +open scoped Classical in +/-- Builds `Packing.Packets G u where E` with the specified `src`, `dst`, `bits`, `left`. -/ +def packets : Packing.Packets G u where + E := p.Bundle + src i := G.source (p.root i) + dst i := G.target (p.root i) + bits := Equiv.ofBijective (p.locate hu) (p.locate_bijective hd hu) + left e := p.vertex.injective ((p.wirePin_at _ false).symm.trans + ((congrArg Prod.fst (p.located hu e false).1.symm).trans (p.wirePin_at e false))) + right e := p.vertex.injective ((p.wirePin_at _ true).symm.trans + ((congrArg Prod.fst (p.located hu e true).1.symm).trans (p.wirePin_at e true))) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- +# The named exterior boundary of a presented diagram +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation + +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} + {x y : Wire} {G : Diagram F x y} (p : S.Presentation r G) + +open scoped Classical in +/-- In the case `.inl i`, this construction gives `⟨_, p.input i⟩`. -/ +def outer : slots x ⊕ slots y → S.exposed r + | .inl i => ⟨_, p.input i⟩ + | .inr i => ⟨_, p.output i⟩ + +open scoped Classical in +theorem outer_bijective : Function.Bijective p.outer := by + constructor + · intro i j h + have e := congrArg (fun z => p.toSeating.ends.symm z.val) h + cases i <;> cases j <;> simp [outer] at e <;> simp [e] + · rintro ⟨a, ha⟩ + obtain ⟨t, rfl⟩ := p.toSeating.ends.surjective a + rcases t with (i|e)|(i|e) + · exact ⟨.inl i, rfl⟩ + · rw [(p.internal e).1] at ha + contradiction + · exact ⟨.inr i, rfl⟩ + · rw [((p.internal e).symm p.proper).1] at ha + contradiction + +open scoped Classical in +/-- The equivalence obtained by `Equiv.ofBijective p.outer p.outer_bijective`. -/ +def boundary := Equiv.ofBijective p.outer p.outer_bijective + +open scoped Classical in +@[simp] theorem exterior_boundary (a : Val x) (b : Val y) (i : slots x ⊕ slots y) : + p.exterior a b (p.boundary i) = Sum.elim (bits x a) (bits y b) i := by + cases i <;> simp [boundary, outer, exterior, read_end] + +include p in +open scoped Classical in +theorem exposed_card : Fintype.card (S.exposed r) = wd x + wd y := by + rw [← Fintype.card_congr p.boundary, Fintype.card_sum, card_slots, card_slots] + +include p in +open scoped Classical in +theorem fits {V k : ℕ} (h : 2 ^ S.m + wd x + wd y ≤ V) (hl : ∀ i, S.load r i ≤ 2 ^ k) : + S.Fits r V k := by + refine ⟨le_trans ?_ h, hl⟩ + have he : ∑ i, S.load r i = wd x + wd y := by + rw [← p.exposed_card, ← Fintype.card_congr (Equiv.sigmaFiberEquiv (S.owner r))] + exact Fintype.card_sigma.symm + calc + _ ≤ ∑ i, (1 + S.load r i) := Finset.sum_le_sum fun i _ => by omega + _ = _ := by simp [Finset.sum_add_distrib, he, add_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/ChannelPlan.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/ChannelPlan.lean new file mode 100644 index 0000000000..164be4379f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/ChannelPlan.lean @@ -0,0 +1,1037 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import Mathlib.GroupTheory.Perm.ViaEmbedding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Graph +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products + +/-! +# A controlled payload transfer + +Local pointers gather bits from a bank into packets. A permutation +of packets at each scale pairs their ends, and the mask pins unused +output bits to zero. Only the packet indices are global addresses. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring + +/-- The indexing data represented by `⟨I → Bool, I, Equiv.refl _⟩`. -/ +abbrev Fmt.raw (I : Type) [Fintype I] : Format := ⟨I → Bool, I, Equiv.refl _⟩ + +/-- The data for the channels construction, including `I`, `[fi`, `localWidth`, `bank`, +`Levels`. -/ +structure Channels (A D : Format) where + /-- The `Channels` component of type `Type`. -/ + I : Type + [fi : Fintype I] + /-- The `Channels` component of type `I → ℕ`. -/ + localWidth : I → ℕ + /-- The `Channels` component of type `∀ i, B (localWidth i) → Option (A.pins ⊕ D.pins)`. -/ + bank : ∀ i, B (localWidth i) → Option (A.pins ⊕ D.pins) + /-- The `Channels` component of type `Type`. -/ + Levels : Type + [fl : Fintype Levels] + /-- The number of entries of type `Levels → ℕ`. -/ + count : Levels → ℕ + /-- The size parameter carried by `Channels`, with type `Levels → ℕ`. -/ + size : Levels → ℕ + /-- The `Channels` component of type `∀ k, B (count k) → Fin (size k) → Option (Σ i, B + (localWidth i))`. -/ + tap : ∀ k, B (count k) → Fin (size k) → Option (Σ i, B (localWidth i)) + +attribute [instance] Channels.fi Channels.fl + +namespace Channels +variable {A D : Format} (S : Channels A D) + +/-- Indexes the index by the coordinates of `Σ i, B (S.localWidth i)`. -/ +abbrev Index := Σ i, B (S.localWidth i) + +/-- The indexed operation `.pair (Fmt.pi (fun i => Perm (S.localWidth i))) (.pair (Fmt.pi (fun k +=> Perm (S.count k))) (Fmt.raw D.pins))`. -/ +abbrev control : Format := + .pair (Fmt.pi (fun i => Perm (S.localWidth i))) + (.pair (Fmt.pi (fun k => Perm (S.count k))) (Fmt.raw D.pins)) + +/-- Computes the point by the application `S.bank i.1 (q.1 i.1 i.2)`. -/ +def point (q : S.control.obj) (i : S.Index) := S.bank i.1 (q.1 i.1 i.2) + +/-- The value specified by `(S.tap k i b).bind (S.point q)`. -/ +def atPort (q : S.control.obj) (k : S.Levels) (i : B (S.count k)) (b : Fin (S.size k)) := + (S.tap k i b).bind (S.point q) + +/-- Evaluates `i.elim false (Sum.elim (A.code x) (D.code y))` at the input `i`. -/ +def value (x : A.obj) (y : D.obj) : Option (A.pins ⊕ D.pins) → Bool := + fun i => i.elim false (Sum.elim (A.code x) (D.code y)) + +/-- The carries of type `Prop` for the given inputs. -/ +def Carries (q : S.control.obj) (x : A.obj) (y : D.obj) : Prop := + (∀ i, q.2.2 i = true → D.code y i = false) ∧ + ∀ k, Function.Bijective (q.2.1 k) ∧ + ∀ i b, value x y (S.atPort q k i b) = value x y (S.atPort q k (q.2.1 k i) b) + +/-- Read the named input bit, or zero for padding. Repetition of an +input name is allowed. -/ +def copy (f : D.pins → Option A.pins) (x : A.obj) : D.obj := + D.code.symm (fun i => (f i).elim false (A.code x)) + +/-- In the case `none`, this construction gives `none`. -/ +def origin (f : D.pins → Option A.pins) : Option (A.pins ⊕ D.pins) → Option A.pins + | none => none + | some (.inl i) => some i + | some (.inr i) => f i + +end Channels +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Channel slots at variable capacities + +A slot of depth `s` participates at every packet width `2^i` +with `i ≤ s`. Each endpoint reserves at most twice its capacity at +each scale, regardless of the number of neighbors. The extra local +address bit allows padding. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring + +open scoped Classical in +/-- The data for the bank construction, including `Slot`, `[finite`, `depth`, `atBit`. -/ +structure Bank (A D : Format) where + /-- The `Bank` component of type `Type`. -/ + Slot : Type + [finite : Fintype Slot] + /-- The depth of each indexed node carried by `Bank`, with type `Slot → ℕ`. -/ + depth : Slot → ℕ + /-- The `Bank` component of type `∀ i, B (depth i) → A.pins ⊕ D.pins`. -/ + atBit : ∀ i, B (depth i) → A.pins ⊕ D.pins + +attribute [instance] Bank.finite + +namespace Bank +variable {A D : Format} (P : Bank A D) (k d : ℕ) + +open scoped Classical in +/-- The subtype of `s` satisfying `i ≤ P.depth s`. -/ +abbrev AtDepth (i : ℕ) := {s // i ≤ P.depth s} +open scoped Classical in +/-- The minimum of the quantities in `d (2 ^ (P.depth s.val + 1 - i))`. -/ +abbrev lanes (i : ℕ) (s : P.AtDepth i) := min d (2 ^ (P.depth s.val + 1 - i)) +open scoped Classical in +/-- Indexes the port by the coordinates of `Σ s : P.AtDepth i, Fin (P.lanes d i s)`. -/ +abbrev Port (i : ℕ) := Σ s : P.AtDepth i, Fin (P.lanes d i s) +open scoped Classical in +/-- The subtype of `i : Fin (k + 1)` satisfying `Nonempty (P.Port d i)`. -/ +abbrev Level := {i : Fin (k + 1) // Nonempty (P.Port d i)} +open scoped Classical in +/-- Indexes the endpoint by the coordinates of `Σ i : P.Level k d, P.AtDepth i.1.val`. -/ +abbrev Endpoint := Σ i : P.Level k d, P.AtDepth i.1.val + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def count (i : P.Level k d) : ℕ := Nat.clog 2 (Fintype.card (P.Port d i.1.val) + 1) + +open scoped Classical in +/-- Embeds `P.Port d i.1.val` into `B (P.count k d i)`. -/ +def index (i : P.Level k d) : P.Port d i.1.val ↪ B (P.count k d i) := + (Fintype.equivFin _).toEmbedding.trans (Fin.castLEEmb + ((Nat.le_succ _).trans (Nat.le_pow_clog (by decide) _))) + +open scoped Classical in +/-- The quantity computed by `P.depth i.2.val + 1`. -/ +def localWidth (i : P.Endpoint k d) := P.depth i.2.val + 1 + +open scoped Classical in +/-- In the case `none`, this construction gives `⟨2 ^ n, by rw [pow_succ]; have := +Nat.two_pow_pos n; omega⟩`. -/ +def encode {n : ℕ} : Option (B n) → B (n + 1) + | none => ⟨2 ^ n, by rw [pow_succ]; have := Nat.two_pow_pos n; omega⟩ + | some i => i.castLE (Nat.pow_le_pow_right (by decide) (by omega)) + +open scoped Classical in +/-- Returns `some ⟨i.val, h⟩` when `h : i.val < 2 ^ n` holds, and `none` otherwise. -/ +def decode {n : ℕ} (i : B (n + 1)) : Option (B n) := + if h : i.val < 2 ^ n then some ⟨i.val, h⟩ else none + +open scoped Classical in +private theorem decode_encode {n : ℕ} (i : Option (B n)) : decode (encode i) = i := by + cases i <;> simp [decode, encode, Fin.is_lt] + +open scoped Classical in +theorem lanes_fit (i : ℕ) (s : P.AtDepth i) : + P.lanes d i s * 2 ^ i ≤ 2 ^ (P.depth s.val + 1) := by + calc + _ ≤ 2 ^ (P.depth s.val + 1 - i) * 2 ^ i := Nat.mul_le_mul_right _ (min_le_right _ _) + _ = _ := by rw [← pow_add, Nat.sub_add_cancel (Nat.le_succ_of_le s.2)] + +open scoped Classical in +/-- Computes the bit index by the application `finProdFinEquiv.toEmbedding.trans (Fin.castLEEmb +(P.lanes_fit d i.1.1.val i.2))`. -/ +def bitIndex (i : P.Endpoint k d) : + Fin (P.lanes d i.1.1.val i.2) × B i.1.1.val ↪ B (P.localWidth k d i) := + finProdFinEquiv.toEmbedding.trans (Fin.castLEEmb (P.lanes_fit d i.1.1.val i.2)) + +open scoped Classical in +/-- Builds `Channels A D where I` with the specified `localWidth`, `bank`, `Levels`, `count`. -/ +def channels : Channels A D where + I := P.Endpoint k d + localWidth := P.localWidth k d + bank i a := (decode a).map (P.atBit i.2.val) + Levels := P.Level k d + count := P.count k d + size i := 2 ^ i.1.val + tap i a b := Function.extend (P.index k d i) + (fun x => some ⟨⟨i, x.1⟩, P.bitIndex k d ⟨i, x.1⟩ (x.2, b)⟩) (fun _ => none) a + +open scoped Classical in +/-- Pointers and peers are control data, independent of the bit values. -/ +structure Plan where + /-- The `Plan` component of type `∀ i : P.Level k d, Equiv.Perm (P.Port d i.1.val)`. -/ + peer : ∀ i : P.Level k d, Equiv.Perm (P.Port d i.1.val) + /-- The `Plan` component of type `∀ (i : P.Level k d) (e : P.Port d i.1.val), B i.1.val → + Option (B (P.depth e.1.val))`. -/ + pointer : ∀ (i : P.Level k d) (e : P.Port d i.1.val), + B i.1.val → Option (B (P.depth e.1.val)) + /-- The `Plan` component of type `D.pins → Bool`. -/ + pad : D.pins → Bool + +variable {P k d} (M : P.Plan k d) + +open scoped Classical in +/-- The control of type `(P.channels k d).control.obj` for the given inputs. -/ +def Plan.control : (P.channels k d).control.obj := + (fun i a => encode (Function.extend (P.bitIndex k d i) + (fun t => M.pointer i.1 ⟨i.2, t.1⟩ t.2) (fun _ => none) a), + fun i => ⇑((M.peer i).viaEmbedding (P.index k d i)), M.pad) + +open scoped Classical in +/-- Transforms the indexed data by `(M.pointer i e b).map (P.atBit e.1.val)`. -/ +def Plan.atBit (i : P.Level k d) (e : P.Port d i.1.val) (b : B i.1.val) := + (M.pointer i e b).map (P.atBit e.1.val) + +open scoped Classical in +theorem Plan.atPort (i : P.Level k d) (e : P.Port d i.1.val) (b : B i.1.val) : + (P.channels k d).atPort M.control i (P.index k d i e) b = M.atBit i e b := by + have h : (P.channels k d).tap i (P.index k d i e) b = + some ⟨⟨i, e.1⟩, P.bitIndex k d ⟨i, e.1⟩ (e.2, b)⟩ := by + unfold channels + dsimp only + exact (P.index k d i).injective.extend_apply _ _ e + change ((P.channels k d).tap i (P.index k d i e) b).bind _ = _ + rw [h, Option.bind_some] + change (decode (encode (Function.extend (P.bitIndex k d ⟨i, e.1⟩) + (fun t => M.pointer i ⟨e.1, t.1⟩ t.2) + (fun _ => none) (P.bitIndex k d ⟨i, e.1⟩ (e.2, b))))).map (P.atBit e.1.val) = _ + rw [decode_encode, (P.bitIndex k d _).injective.extend_apply] + rfl + +open scoped Classical in +theorem Plan.carries (x : A.obj) (y : D.obj) : + (P.channels k d).Carries M.control x y ↔ + (∀ i, M.pad i = true → D.code y i = false) ∧ + ∀ i e b, Channels.value x y (M.atBit i e b) = Channels.value x y (M.atBit i (M.peer i e) b) + := by + have he (i : P.Level k d) (e : P.Port d i.1.val) : + M.control.2.1 i (P.index k d i e) = P.index k d i (M.peer i e) := + Equiv.Perm.viaEmbedding_apply _ _ _ + constructor + · rintro ⟨h₁, h₂⟩ + refine ⟨h₁, fun i e b => ?_⟩ + have h := (h₂ i).2 (P.index k d i e) b + rwa [he, M.atPort, M.atPort] at h + · rintro ⟨h₁, h₂⟩ + refine ⟨h₁, fun i => ⟨((M.peer i).viaEmbedding _).bijective, fun e b => ?_⟩⟩ + by_cases hh : e ∈ Set.range (P.index k d i) + · obtain ⟨a, rfl⟩ := hh + rw [he i a, M.atPort i a b, M.atPort i (M.peer i a) b] + exact h₂ _ _ _ + · rw [show M.control.2.1 i e = e from Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ hh] + +end Bank +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Packing disjoint contacts of one size + +The length class and ordinal determine the physical lane. Disjoint +use of bits bounds the number of occupied lanes of each size. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank + +open Coloring +variable {A D : Format} (P : Bank A D) (k d : ℕ) + +open scoped Classical in +/-- The data for the links construction, including `E`, `place`, `length`, `pointer`, `small`. -/ +structure Links where + /-- The type of edges. -/ + E : Type + /-- Embeds the coordinates as `E × Bool ↪ P.Slot × Fin d`. -/ + place : E × Bool ↪ P.Slot × Fin d + /-- The length of the indexed record carried by `Links`, with type `E → ℕ`. -/ + length : E → ℕ + /-- The `Links` component of type `∀ e b, Fin (length e) → B (P.depth (place (e, b)).1)`. -/ + pointer : ∀ e b, Fin (length e) → B (P.depth (place (e, b)).1) + small : ∀ e b, length e ≤ 2 ^ P.depth (place (e, b)).1 + bounded : ∀ e b, P.depth (place (e, b)).1 ≤ k + distinct : ∀ (p q : E × Bool) (i : Fin (length p.1)) (j : Fin (length q.1)), + (place p).1 = (place q).1 → (pointer p.1 p.2 i).val = (pointer q.1 q.2 j).val → + p = q ∧ i.val = j.val + /-- The `Links` component of type `D.pins → Bool`. -/ + pad : D.pins → Bool + +namespace Links +variable {P k d} (L : P.Links k d) + +open scoped Classical in +instance : Fintype L.E := by + have : Finite L.E := Finite.of_injective (fun e => L.place (e, false)) + (fun _ _ h => (Prod.mk.inj (L.place.injective h)).1) + exact Fintype.ofFinite _ + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def depth (e : L.E) := Nat.clog 2 (L.length e) + +open scoped Classical in +theorem depth_le (e : L.E) (b : Bool) : L.depth e ≤ P.depth (L.place (e, b)).1 := + Nat.clog_le_of_le_pow (L.small e b) + +open scoped Classical in +theorem fits (e : L.E) : L.length e ≤ 2 ^ L.depth e := Nat.le_pow_clog (by decide) _ + +open scoped Classical in +/-- The level of type `P.Level k d`, constructed using `⟨_, L.depth_le e false⟩`. -/ +def level (e : L.E) : P.Level k d := by + have hd := (L.place (e, false)).2.isLt + let t : P.AtDepth (L.depth e) := ⟨_, L.depth_le e false⟩ + exact ⟨⟨L.depth e, Nat.lt_succ_of_le ((L.depth_le e false).trans (L.bounded e false))⟩, + ⟨⟨t, 0, lt_min (by omega) (by positivity)⟩⟩⟩ + +open scoped Classical in +/-- The subtype of `e` satisfying `L.level e = i ∧ 0 < L.length e`. -/ +abbrev At (i : P.Level k d) := {e // L.level e = i ∧ 0 < L.length e} + +open scoped Classical in +/-- The indexed operation `⟨(L.place (e.1.val, e.2)).1, (congrArg (fun i : P.Level k d => +i.1.val) e.1.2.1).symm.le.trans (L.depth_le _ _)⟩`. -/ +def site (i : P.Level k d) (e : L.At i × Bool) : P.AtDepth i.1.val := + ⟨(L.place (e.1.val, e.2)).1, + (congrArg (fun i : P.Level k d => i.1.val) e.1.2.1).symm.le.trans (L.depth_le _ _)⟩ + +variable (i : P.Level k d) (s : P.AtDepth i.1.val) + +open scoped Classical in +/-- The subtype of `e : L.At i × Bool` satisfying `L.site i e = s`. -/ +abbrev Here := {e : L.At i × Bool // L.site i e = s} + +open scoped Classical in +/-- The value specified by `(a.val.1.val, a.val.2)`. -/ +def item (a : L.Here i s) : L.E × Bool := (a.val.1.val, a.val.2) + +open scoped Classical in +private theorem item_inj : Function.Injective (L.item i s) := by + intro a b h + exact Subtype.ext (Prod.ext (Subtype.ext (Prod.mk.inj h).1) (Prod.mk.inj h).2) + +open scoped Classical in +private theorem here_eq (a : L.Here i s) : (L.place (L.item i s a)).1 = s.val := + congrArg Subtype.val a.property + +open scoped Classical in +/-- The value specified by `(L.place (L.item i s a)).2`. -/ +def serial (a : L.Here i s) := (L.place (L.item i s a)).2 + +open scoped Classical in +theorem serial_inj : Function.Injective (L.serial i s) := by + intro a b h + exact L.item_inj i s (L.place.injective (Prod.ext ((L.here_eq _ _ _).trans (L.here_eq _ _ + _).symm) h)) + +open scoped Classical in +private theorem total_length : (∑ a : L.Here i s, L.length (L.item i s a).1) ≤ 2 ^ P.depth s.val + := by + let t := L.item i s + let X := Σ a, Fin (L.length (t a).1) + let f : X → B (P.depth s.val) := fun p => + (L.pointer (t p.1).1 (t p.1).2 p.2).cast (congrArg (fun z => 2 ^ P.depth z) (L.here_eq _ _ _)) + have hi : Function.Injective f := by + rintro ⟨a, x⟩ ⟨b, y⟩ h + obtain ⟨he, h'⟩ := L.distinct (t a) (t b) x y ((L.here_eq _ _ a).trans (L.here_eq _ _ b).symm) + (congrArg Fin.val h) + have : a = b := L.item_inj i s he + subst b + rw [Fin.ext h'] + simpa only [X, t, Fintype.card_sigma, Fintype.card_fin] using Fintype.card_le_of_injective f hi + +open scoped Classical in +private theorem strict_round (t : ℕ) (ht : 0 < t) : 2 ^ (Nat.clog 2 t) < 2 * t := by + cases he : Nat.clog 2 t with + | zero => simp; omega + | succ j => + rw [pow_succ'] + exact Nat.mul_lt_mul_of_pos_left (Nat.pow_lt_of_lt_clog (by omega : j + < Nat.clog 2 t)) (by decide) + +open scoped Classical in +private theorem active_lanes : Fintype.card (L.Here i s) * 2 ^ i.1.val < 2 ^ (P.depth s.val + 1) + := by + cases isEmpty_or_nonempty (L.Here i s) with + | inl h => simp + | inr h => + rw [pow_succ'] + calc + _ = ∑ _ : L.Here i s, 2 ^ i.1.val := by simp + _ < ∑ a : L.Here i s, 2 * L.length (L.item i s a).1 := by + refine Finset.sum_lt_sum_of_nonempty Finset.univ_nonempty fun a _ => ?_ + have he : L.depth (L.item i s a).1 = i.1.val := + congrArg (fun j : P.Level k d => j.1.val) a.val.1.2.1 + exact he ▸ strict_round _ a.val.1.2.2 + _ ≤ _ := by rw [← Finset.mul_sum]; exact Nat.mul_le_mul_left 2 (L.total_length i s) + +open scoped Classical in +theorem lanes_enough : Fintype.card (L.Here i s) ≤ P.lanes d i.1.val s := by + apply le_min + · simpa using Fintype.card_le_of_injective _ (L.serial_inj i s) + apply Nat.le_of_mul_le_mul_right _ (Nat.two_pow_pos i.1.val) + rw [← pow_add, Nat.sub_add_cancel (Nat.le_succ_of_le s.2)] + exact (L.active_lanes i s).le + +open scoped Classical in +/-- Embeds `L.Here i s` into `Fin (P.lanes d i.1.val s)`. -/ +def lane : L.Here i s ↪ Fin (P.lanes d i.1.val s) := + letI : LinearOrder (L.Here i s) := LinearOrder.lift' _ (L.serial_inj i s) + (Fintype.orderIsoFinOfCardEq _ rfl).symm.toEquiv.toEmbedding.trans + (Fin.castLEEmb (L.lanes_enough i s)) + +open scoped Classical in +/-- Embeds `L.At i × Bool` into `P.Port d i.1.val`. -/ +def location : L.At i × Bool ↪ P.Port d i.1.val := + (Equiv.sigmaFiberEquiv (L.site i)).symm.toEmbedding.trans + (Function.Embedding.sigmaMap (Function.Embedding.refl _) (L.lane i)) + +open scoped Classical in +/-- The exclusive end of any active lane fits in the address word. -/ +theorem lane_end (e : L.At i × Bool) : + 2 ^ i.1.val * ((L.location i e).2.val + 1) < 2 ^ (P.depth (L.site i e).val + 1) := by + let s := L.site i e + let a : L.Here i s := ⟨e, rfl⟩ + let : LinearOrder (L.Here i s) := LinearOrder.lift' _ (L.serial_inj i s) + have h : (L.location i e).2.val < Fintype.card (L.Here i s) := + ((Fintype.orderIsoFinOfCardEq (L.Here i s) rfl).symm a).isLt + rw [mul_comm] + exact (Nat.mul_le_mul_right (2 ^ i.1.val) (Nat.succ_le_of_lt h)).trans_lt (L.active_lanes i s) + +end Links +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank +end + +/- +# Reserving a packet for a pair of ports + +Round the actual transmission length up to a power of two. The unused packet +positions read zero. Ports outside the pairing match themselves. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank + +open Coloring +variable {A D : Format} (P : Bank A D) (k d : ℕ) + +namespace Links +variable {P k d} (L : P.Links k d) + +open scoped Classical in +/-- The value specified by `(Equiv.refl _).prodCongr (Equiv.mk Bool.not Bool.not Bool.not_not +Bool.not_not)`. -/ +def opposite (i : P.Level k d) : Equiv.Perm (L.At i × Bool) := + (Equiv.refl _).prodCongr (Equiv.mk Bool.not Bool.not Bool.not_not Bool.not_not) + +open scoped Classical in +/-- Returns `some (L.pointer e b ⟨j, h⟩).val` when `h : j < L.length e` holds, and `none` +otherwise. -/ +def address (e : L.E) (b : Bool) (j : ℕ) : Option ℕ := + if h : j < L.length e then some (L.pointer e b ⟨j, h⟩).val else none + +open scoped Classical in +/-- Returns `some ⟨z, h⟩` when `h : z < 2 ^ w` holds, and `none` otherwise. -/ +def limit (w z : ℕ) : Option (B w) := if h : z < 2 ^ w then some ⟨z, h⟩ else none + +open scoped Classical in +/-- Builds `P.Plan k d where peer i` with the specified `peer`, `pointer`, `pad`. -/ +def plan : P.Plan k d where + peer i := (L.opposite i).viaEmbedding (L.location i) + pointer i e b := (Function.extend (L.location i) (fun q => L.address q.1.val q.2 b.val) + (fun _ => none) e).bind (limit (P.depth e.1.val)) + pad := L.pad + +open scoped Classical in +/-- The value specified by `P.atBit (L.place (e, b)).1 (L.pointer e b j)`. -/ +def atBit (e : L.E) (b : Bool) (j : Fin (L.length e)) := + P.atBit (L.place (e, b)).1 (L.pointer e b j) + +open scoped Classical in +theorem peer_at (i : P.Level k d) (e : L.At i) (b : Bool) : + L.plan.peer i (L.location i (e, b)) = L.location i (e, !b) := + Equiv.Perm.viaEmbedding_apply (L.opposite i) (L.location i) (e, b) + +open scoped Classical in +theorem pointer_at (i : P.Level k d) (e : L.At i × Bool) (j : B i.1.val) : + (encode (L.plan.pointer i (L.location i e) j)).val = + if h : j.val < L.length e.1.val then (L.pointer e.1.val e.2 ⟨j.val, h⟩).val + else 2 ^ P.depth (L.place (e.1.val, e.2)).1 := by + unfold plan + dsimp only + rw [(L.location i).injective.extend_apply] + change (encode ((L.address e.1.val e.2 j.val).bind + (limit (P.depth (L.place (e.1.val, e.2)).1)))).val = _ + unfold address + split + · rename_i hj + simp only [Option.bind_some, limit, dite_eq_left (L.pointer e.1.val e.2 ⟨j.val, hj⟩).isLt] + rfl + · rfl + +open scoped Classical in +theorem bit_at (i : P.Level k d) (e : L.At i) (b : Bool) (j : B i.1.val) : + L.plan.atBit i (L.location i (e, b)) j = + if h : j.val < L.length e.val then some (L.atBit e.val b ⟨j.val, h⟩) else none := by + unfold Plan.atBit plan + dsimp only + rw [(L.location i).injective.extend_apply] + change ((L.address e.val b j.val).bind (limit (P.depth (L.place (e.val, b)).1))).map _ = _ + unfold address + split + · rename_i hj + simp only [Option.bind_some, limit, dite_eq_left (L.pointer e.val b ⟨j.val, hj⟩).isLt] + rfl + · rfl + +open scoped Classical in +/-- The matches of type `Prop` for the given inputs. -/ +def Matches (x : A.obj) (y : D.obj) : Prop := + (∀ i, L.pad i = true → D.code y i = false) ∧ ∀ e j, + Sum.elim (A.code x) (D.code y) (L.atBit e false j) = + Sum.elim (A.code x) (D.code y) (L.atBit e true j) + +open scoped Classical in +theorem carries (x : A.obj) (y : D.obj) : + (P.channels k d).Carries L.plan.control x y ↔ L.Matches x y := by + rw [L.plan.carries] + constructor + · rintro ⟨hm, h⟩ + refine ⟨hm, fun e j => ?_⟩ + let i := L.level e + let t : L.At i := ⟨e, rfl, lt_of_le_of_lt (Nat.zero_le _) j.isLt⟩ + let a : B i.1.val := j.castLE (L.fits e) + have he := h i (L.location i (t, false)) a + have hj : a.val < L.length t.val := j.isLt + rw [L.peer_at, L.bit_at, L.bit_at, dite_eq_left hj, dite_eq_left hj] at he + exact he + · rintro ⟨hm, h⟩ + refine ⟨hm, fun i t j => ?_⟩ + by_cases ht : t ∈ Set.range (L.location i) + · obtain ⟨⟨e, b⟩, rfl⟩ := ht + rw [L.peer_at, L.bit_at, L.bit_at] + split + · cases b + · exact h _ _ + · exact (h _ _).symm + · rfl + · rw [show L.plan.peer i t = t from Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ ht] + +end Links +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank +end + +/- +# Assigning active channel lanes + +Unlike payload hosts, empty channels do not take a seat. +The largest address is never a positive length's level, so it can +serve as the bucket for every inactive or padded channel. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +namespace PackRank + +variable {p w : ℕ} + +open scoped Classical in +/-- Returns `code x` when `0 < x` holds, and `⊤` otherwise. -/ +def bucket (x : B w) : B w := if 0 < x then code x else ⊤ + +open scoped Classical in +theorem code_ne_top (x : B w) (hx : 0 < x.val) : code x ≠ ⊤ := by + have h : x.val ≤ 2 ^ (x.val - 1) := by + have := Nat.lt_two_pow_self (n := x.val - 1) + omega + have he : code x < x := by + change Nat.clog 2 x.val < x.val + have := Nat.clog_le_of_le_pow h + omega + exact (he.trans_le le_top).ne + +open scoped Classical in +theorem bucket_eq (x y : B w) (hy : 0 < y.val) : + bucket x = bucket y ↔ 0 < x.val ∧ (code x).val = (code y).val := by + have hy' : 0 < y := hy + by_cases h : 0 < x + · simp [bucket, h, hy', show 0 < x.val from h, Fin.ext_iff] + · simp [bucket, h, hy', show ¬ 0 < x.val from h, Ne.symm (code_ne_top y hy)] + +open scoped Classical in +/-- The value specified by `(code (x i), groupRank (bucket ∘ x) i)`. -/ +def lanes (x : B p → B w) (i : B p) := (code (x i), groupRank (bucket ∘ x) i) + +open scoped Classical in +private theorem cheap_bucket (F : Type) [Field F] (w : ℕ) : + Cheap F 0 w (.addr w) (.addr w) bucket 20 := by + have hw : (Format.addr w).width ≤ 2 ^ 0 * (100 + w) ^ 1 := by simp + have lt := ((Cheap.const F hw hw 0).pair (Cheap.id F hw)).comp (Intervals.cheap_compare F le_rfl) + have h := (((cheap_code F w).pair (Cheap.const F hw hw ⊤)).pair lt).comp (cheap_select F w) + convert h.mono (d := 20) (by decide) using 1 + funext x + by_cases he : 0 < x <;> simp [bucket, he] + +open scoped Classical in +theorem cheap_lanes (F : Type) [Field F] (p w : ℕ) : + Cheap F p (p + w) (.vec p (.addr w)) (.vec p (.pair (.addr w) (.addr p))) lanes 110 := by + have h : w ≤ p + w := by omega + have levels := Cheap.map _ (fun _ : B p => (cheap_code F w).widen h) + have buckets := Cheap.map _ (fun _ : B p => (cheap_bucket F w).widen h) + exact (levels.pair (buckets.comp (cheap_groupRank F p w))).zip.mono (by decide) + +end PackRank + +namespace Bank.Links + +variable {A D : Format} {P : Bank A D} {k d p w : ℕ} (L : P.Links k d) + +open scoped Classical in +/-- The fits lengths of type `Prop` for the given inputs. -/ +def FitsLengths (s : P.Slot) (hd : d ≤ 2 ^ p) (x : B p → B w) : Prop := + (∀ e : L.E × Bool, (L.place e).1 = s → (x ((L.place e).2.castLE hd)).val = L.length e.1) ∧ + ∀ i, 0 < (x i).val → ∃ e : L.E × Bool, (L.place e).1 = s ∧ (L.place e).2.castLE hd = i + +open scoped Classical in +theorem lanes_correct (i : P.Level k d) (e : L.At i × Bool) {hd : d ≤ 2 ^ p} {x : B p → B w} + (h : L.FitsLengths (L.site i e).val hd x) : + (PackRank.lanes x ((L.place (e.1.val, e.2)).2.castLE hd)).1.val = i.1.val ∧ + (PackRank.lanes x ((L.place (e.1.val, e.2)).2.castLE hd)).2.val = (L.location i e).2.val := by + let s := L.site i e + let S := L.Here i s + let e₀ : S := ⟨e, rfl⟩ + let name (a : S) := (a.val.1.val, a.val.2) + let serial (a : S) := (L.place (name a)).2 + let idx (a : S) := (serial a).castLE hd + have slot (a : S) : (L.place (name a)).1 = s.val := congrArg Subtype.val a.2 + have length (a : S) : (x (idx a)).val = L.length a.val.1.val := h.1 _ (slot a) + have pos (a : S) : 0 < (x (idx a)).val := (length a).symm ▸ a.val.1.property.2 + have code (a : S) : (PackRank.code (x (idx a))).val = i.1.val := by + change Nat.clog 2 (x (idx a)).val = _ + rw [length] + exact congrArg (fun i : P.Level k d => i.1.val) a.val.1.property.1 + refine ⟨code e₀, ?_⟩ + let z := PackRank.bucket ∘ x + have eq (a b : S) : z (idx a) = z (idx b) := + (PackRank.bucket_eq _ _ (pos b)).mpr ⟨pos a, (code a).trans (code b).symm⟩ + let f (a : S) : {u // z u = z (idx e₀)} := ⟨idx a, eq a e₀⟩ + have onto : Function.Surjective f := by + rintro ⟨u, hu⟩ + obtain ⟨hp, he⟩ := (PackRank.bucket_eq _ _ (pos e₀)).mp hu + obtain ⟨a, ha, hidx⟩ := h.2 u hp + have hlen : (x u).val = L.length a.1 := by rw [← hidx]; exact h.1 a ha + have hl : L.level a.1 = i := by + apply Subtype.ext + apply Fin.ext + change Nat.clog 2 (L.length a.1) = _ + rw [← hlen] + exact he.trans (code e₀) + let v : L.At i × Bool := (⟨a.1, hl, hlen ▸ hp⟩, a.2) + exact ⟨⟨v, Subtype.ext ha⟩, Subtype.ext hidx⟩ + have hinj : Function.Injective serial := by + intro a b hab + have he := L.place.injective (Prod.ext ((slot a).trans (slot b).symm) hab) + exact Subtype.ext (Prod.ext (Subtype.ext (Prod.mk.inj he).1) (Prod.mk.inj he).2) + let _ : LinearOrder S := LinearOrder.lift' serial hinj + let E := Fintype.orderIsoFinOfCardEq S rfl + let rank (a : S) : Fin (Fintype.card S) := ⟨Control.rank z (idx a), by + have hb := Fintype.card_le_of_surjective f onto + rw [Fintype.card_subtype, ← Control.histogram_none] at hb + exact (Control.rank_lt z (idx a)).trans_le ((eq a e₀) ▸ hb)⟩ + have hm : StrictMono rank := fun a b hab => Control.rank_mono z (eq a b) hab + have he := congrFun (hm.comp E.strictMono).eq_id (E.symm e₀) + simp only [Function.comp_apply, OrderIso.apply_symm_apply, id_eq] at he + change (groupRank z (idx e₀)).val = (E.symm e₀).val + rw [groupRank_val] + exact congrArg Fin.val he + +end Bank.Links +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Local gathers and global checks + +The addresses of a gather refer only to the local bank. A single +hidden bit is shared by all constant-zero taps. Every other hidden +bit is the output of exactly one deterministic gather. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Channels + +open Coloring Install + +variable {A D : Format} (S : Channels A D) + +open scoped Classical in +/-- Computes the gather in by the application `Format.pair (.vec k .bit) (Perm k)`. -/ +abbrev gatherIn (k : ℕ) := Format.pair (.vec k .bit) (Perm k) +open scoped Classical in +/-- Computes the gather out by the application `Format.vec k .bit`. -/ +abbrev gatherOut (k : ℕ) := Format.vec k .bit + +open scoped Classical in +/-- The value specified by `x.1 ∘ x.2`. -/ +def gather (k : ℕ) (x : (gatherIn k).obj) : (gatherOut k).obj := x.1 ∘ x.2 + +open scoped Classical in +/-- Computes the row by the application `Fmt.raw (Fin (S.size k))`. -/ +abbrev row (k : S.Levels) := Fmt.raw (Fin (S.size k)) + +open scoped Classical in +/-- Indexes the tasks by the coordinates of `Option (S.I ⊕ S.Levels ⊕ D.pins)`. -/ +abbrev Tasks := Option (S.I ⊕ S.Levels ⊕ D.pins) +open scoped Classical in +/-- Computes the hidden by the application `Option S.Index`. -/ +abbrev Hidden := Option S.Index +open scoped Classical in +/-- Indexes the name by the coordinates of `((S.control.pins ⊕ A.pins) ⊕ D.pins) ⊕ S.Hidden`. -/ +abbrev Name := ((S.control.pins ⊕ A.pins) ⊕ D.pins) ⊕ S.Hidden + +open scoped Classical in +/-- In the case `none`, this construction gives `Unit`. -/ +abbrev pins : S.Tasks → Type + | none => Unit + | some (.inl i) => (gatherIn (S.localWidth i)).pins ⊕ (gatherOut (S.localWidth i)).pins + | some (.inr (.inl k)) => (exchangeIn (S.row k) (S.count k)).pins ⊕ (exchangeOut (S.row k) + (S.count k)).pins + | some (.inr (.inr _)) => Bool + +open scoped Classical in +private instance (i : S.Tasks) : Fintype (S.pins i) := by + rcases i with _ | (i | k | a) <;> unfold pins <;> infer_instance + +open scoped Classical in +/-- In the case `none`, this construction gives `.inr none`. -/ +def port : Option (A.pins ⊕ D.pins) → S.Name + | none => .inr none + | some (.inl i) => .inl (.inl (.inr i)) + | some (.inr i) => .inl (.inr i) + +open scoped Classical in +/-- In the case `none, _`, this construction gives `.inr none`. -/ +def wiring : (i : S.Tasks) → S.pins i → S.Name + | none, _ => .inr none + | some (.inl i), .inl (.inl (a, _)) => S.port (S.bank i a) + | some (.inl i), .inl (.inr a) => .inl (.inl (.inl (.inl ⟨i, a⟩))) + | some (.inl i), .inr (a, _) => .inr (some ⟨i, a⟩) + | some (.inr (.inl k)), .inl (.inl a) => .inl (.inl (.inl (.inr (.inl ⟨k, a⟩)))) + | some (.inr (.inl k)), .inl (.inr (i, b)) => .inr (S.tap k i b) + | some (.inr (.inl k)), .inr (i, b) => .inr (S.tap k i b) + | some (.inr (.inr a)), true => .inl (.inl (.inl (.inr (.inr a)))) + | some (.inr (.inr a)), false => .inl (.inr a) + +open scoped Classical in +/-- In the case `none, z`, this construction gives `z () = false`. -/ +def agrees : (i : S.Tasks) → (S.pins i → Bool) → Prop + | none, z => z () = false + | some (.inl i), z => gather _ ((gatherIn _).code.symm (z ∘ Sum.inl)) = + (gatherOut (S.localWidth i)).code.symm (z ∘ Sum.inr) + | some (.inr (.inl k)), z => + let x := (exchangeIn (S.row k) (S.count k)).code.symm (z ∘ Sum.inl) + let y := (exchangeOut (S.row k) (S.count k)).code.symm (z ∘ Sum.inr) + Function.Bijective x.1 ∧ y = x.2 ∘ x.1 + | some (.inr (.inr _)), z => z true = true → z false = false + +open scoped Classical in +/-- Evaluates `value x y (i.bind (S.point q))` at the input `i`. -/ +def trace (q : S.control.obj) (x : A.obj) (y : D.obj) : S.Hidden → Bool := + fun i => value x y (i.bind (S.point q)) + +variable (q : S.control.obj) (x : A.obj) (y : D.obj) (z : S.Hidden → Bool) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def run : S.Name → Bool := + Sum.elim (Sum.elim ((S.control.pair A).code (q, x)) (D.code y)) z + +open scoped Classical in +private theorem read_port (h : z none = false) (i : Option (A.pins ⊕ D.pins)) : + S.run q x y z (S.port i) = value x y i := by + rcases i with _ | (i | i) + · exact h + · rfl + · rfl + +open scoped Classical in +private theorem gather_iff (h : z none = false) (i : S.I) : + S.agrees (some (.inl i)) (S.run q x y z ∘ S.wiring (some (.inl i))) ↔ + ∀ a, z (some ⟨i, a⟩) = S.trace q x y (some ⟨i, a⟩) := by + let u := S.run q x y z ∘ S.wiring (some (.inl i)) + let v := (gatherIn (S.localWidth i)).code.symm (u ∘ Sum.inl) + have hs (a) : v.1 a = value x y (S.bank i a) := S.read_port q x y z h _ + have ht (a) : v.2 a = q.1 i a := (Format.addr (S.localWidth i)).code.symm_apply_apply (q.1 i a) + change (fun a => v.1 (v.2 a)) = (fun a => z (some ⟨i, a⟩)) ↔ _ + simp only [funext_iff, hs, ht, trace, Option.bind_some, point, eq_comm] + +open scoped Classical in +private theorem exchange_iff (k : S.Levels) : + S.agrees (some (.inr (.inl k))) (S.run q x y z ∘ S.wiring (some (.inr (.inl k)))) ↔ + Function.Bijective (q.2.1 k) ∧ ∀ i b, z (S.tap k i b) = z (S.tap k (q.2.1 k i) b) := by + let u := S.run q x y z ∘ S.wiring (some (.inr (.inl k))) + let v := (exchangeIn (S.row k) (S.count k)).code.symm (u ∘ Sum.inl) + have ht : v.1 = q.2.1 k := funext fun a => (Format.addr (S.count k)).code.symm_apply_apply (q.2.1 + k a) + change Function.Bijective v.1 ∧ + (fun i b => z (S.tap k i b)) = (fun i b => z (S.tap k (v.1 i) b)) ↔ _ + rw [ht] + simp only [funext_iff] + +open scoped Classical in +private theorem agrees_iff : + (∀ i, S.agrees i (S.run q x y z ∘ S.wiring i)) ↔ z = S.trace q x y ∧ S.Carries q x y := by + constructor + · intro h + have h₀ : z none = false := h none + have hz : z = S.trace q x y := by + funext i + rcases i with _ | ⟨i, a⟩ + · exact h₀ + · exact (S.gather_iff q x y z h₀ i).mp (h _) a + refine ⟨hz, fun i => h (some (.inr (.inr i))), fun k => ?_⟩ + have he := (S.exchange_iff q x y z k).mp (h _) + rw [hz] at he + exact he + · rintro ⟨rfl, h₀, h₁⟩ (_ | (i | k | a)) + · rfl + · exact (S.gather_iff q x y _ rfl i).mpr (fun _ => rfl) + · exact (S.exchange_iff q x y _ k).mpr (h₁ k) + · exact h₀ a + +variable (F : Type) [Field F] + +open scoped Classical in +/-- Returns `1` when `S.Carries x.1 x.2 y` holds, and `0` otherwise. -/ +def kernel (x : (S.control.pair A).obj) (y : D.obj) : F := + if S.Carries x.1 x.2 y then 1 else 0 + +open scoped Classical in +/-- Returns `1` when `S.agrees i z` holds, and `0` otherwise. -/ +def check (i : S.Tasks) (z : S.pins i → Bool) : F := if S.agrees i z then 1 else 0 + +open scoped Classical in +theorem all_checks : + (∏ i, S.check F i (S.run q x y z ∘ S.wiring i)) = + if z = S.trace q x y then S.kernel F (q, x) y else 0 := by + by_cases he : ∀ i, S.agrees i (S.run q x y z ∘ S.wiring i) + · obtain ⟨h₁, h₂⟩ := (S.agrees_iff q x y z).mp he + simp only [check, he, ite_true, Finset.prod_const_one, ite_eq_left h₁, kernel, h₂] + · have hn := mt (S.agrees_iff q x y z).mpr he + obtain ⟨i, hi⟩ := not_forall.mp he + rw [Finset.prod_eq_zero (Finset.mem_univ i) (show S.check F i (S.run q x y z ∘ S.wiring i) + = 0 from ite_eq_right hi)] + simp only [kernel, ← ite_and, hn, ite_false] + +open scoped Classical in +/-- The quantity computed by `2 ^ n * (100 + (n + 1)) ^ 8`. -/ +def localCost (n : ℕ) := 2 ^ n * (100 + (n + 1)) ^ 8 + +open scoped Classical in +/-- The quantity computed by `m + 100 * 2 ^ n * (n + v + 1)`. -/ +def globalCost (m n v : ℕ) := m + 100 * 2 ^ n * (n + v + 1) + +open scoped Classical in +/-- The cost used in the `Channels` construction. -/ +def cost (v m : S.Levels → ℕ) := + 8 * ((S.control.pair A).width + D.width + (∑ i, 2 ^ (S.localWidth i)) + 1) + + 36 * (16 + (∑ i, localCost (S.localWidth i)) + + (∑ k, globalCost (m k) (S.count k) (v k)) + 32 * D.width) + 4 * D.width + +open scoped Classical in +/-- One tagged permutation per packet scale suffices. -/ +theorem realize {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + (v m : S.Levels → ℕ) (hv : ∀ k, S.size k ≤ v k) + (ht : ∀ k, Radix.Tag F (S.count k) (v k) (m k)) : + Kernel F u L (S.control.pair A) D (S.kernel F) (S.cost v m) := by + let c : S.Tasks → ℕ + | none => 16 + | some (.inl i) => localCost (S.localWidth i) + | some (.inr (.inl k)) => globalCost (m k) (S.count k) (v k) + | some (.inr (.inr _)) => 32 + have hc (i) : Weight F (S.check F i) (c i) := by + rcases i with _ | (i | k | a) + · exact Weight.dense F Unit _ + · let n := S.localWidth i + have hg : Cheap F n (n + 1) (gatherIn n) (gatherOut n) (gather n) 8 := + Cheap.lookup F n (n + 1) .bit (by omega) (by rw [Format.width_bit]; omega) + exact hg.weight + · have he := exchange_weight (S.row k) (ht k) (by simpa [row, Fmt.raw, Format.width] using hv k) + convert he using 1 + · funext z + simp only [check, agrees, exchangeCheck, exchange] + congr 1 + · rfl + · exact Weight.dense F Bool _ + have hw := Kernel.factors (A := S.control.pair A) (B := D) (L := L) (S.check F) S.wiring + (fun i => 4 * c i) hu (fun i => Transcript.of_weight hu (hc i)) + have he (a : (S.control.pair A).obj) (b : D.obj) : + Transcript.weightedSum (S.check F) S.wiring (Sum.elim ((S.control.pair A).code a) (D.code b)) + = + S.kernel F a b := by + rcases a with ⟨q, x⟩ + have eq (z : S.Hidden → Bool) : + (∏ i, S.check F i (Sum.elim (Sum.elim ((S.control.pair A).code (q, + x)) (D.code b)) z ∘ S.wiring i)) = + if z = S.trace q x b then S.kernel F (q, x) b else 0 := S.all_checks q x b z F + unfold Transcript.weightedSum + simp only [eq, Finset.sum_ite_eq', Finset.mem_univ, ite_true] + simp only [he] at hw + refine hw.mono ?_ + rw [← Finset.mul_sum, Fintype.sum_option, Fintype.sum_sum_type, Fintype.sum_sum_type] + simp only [c, cost, Hidden, Index, Fintype.card_option, Fintype.card_sigma, Fintype.card_fin, + Finset.sum_const, Finset.card_univ, Nat.nsmul_eq_mul] + unfold Format.width + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Channels +end + +/- +# Total cost of reserving all the smaller channels + +Global addresses are paid per endpoint. The bit volume, including +dummy packets in the dyadic lists, is bounded by the total capacity +times the number of levels and ports. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank + +open Coloring + +variable {A D : Format} (P : Bank A D) (k d : ℕ) + +open scoped Classical in +/-- The sum of `2 ^ P.depth i` indexed by `i`. -/ +def capacity := ∑ i, 2 ^ P.depth i + +open scoped Classical in +theorem port_count (s : ℕ) : Fintype.card (P.Port d s) ≤ d * Fintype.card P.Slot := by + rw [Fintype.card_sigma] + calc + _ ≤ ∑ _ : P.AtDepth s, d := Finset.sum_le_sum fun i _ => by + rw [Fintype.card_fin]; exact min_le_left _ _ + _ ≤ _ := by + rw [Finset.sum_const, Finset.card_univ, Nat.nsmul_eq_mul, mul_comm] + exact Nat.mul_le_mul_left _ (Fintype.card_subtype_le _) + +open scoped Classical in +theorem level_count : Fintype.card (P.Level k d) ≤ k + 1 := + (Fintype.card_subtype_le _).trans_eq (Fintype.card_fin _) + +open scoped Classical in +theorem count_range {n : ℕ} (h : d * Fintype.card P.Slot < 2 ^ n) (i : P.Level k d) : + 1 ≤ P.count k d i ∧ P.count k d i ≤ n := by + have := i.property + have hp : 0 < Fintype.card (P.Port d i.1.val) := Fintype.card_pos + have hc := P.port_count d i.1.val + exact ⟨Nat.clog_pos (by decide) (by omega), Nat.clog_le_of_le_pow (by omega)⟩ + +open scoped Classical in +private theorem count_bound (i : P.Level k d) : + 2 ^ (P.count k d i) ≤ 4 * Fintype.card (P.Port d i.1.val) := by + have := i.property + have hp : 0 < Fintype.card (P.Port d i.1.val) := Fintype.card_pos + have h := Transcript.pow_clog_le_twice (x := Fintype.card (P.Port d i.1.val) + 1) (by omega) + unfold count + omega + +open scoped Classical in +private theorem slot_sum (s : ℕ) : + (∑ i : P.AtDepth s, 2 ^ P.depth i.val) ≤ P.capacity := by + rw [← Finset.sum_subtype (Finset.univ.filter (fun i => s ≤ P.depth i)) Finset.mem_filter_univ + (fun i => 2 ^ P.depth i)] + exact Finset.sum_le_sum_of_subset (Finset.subset_univ _) + +open scoped Classical in +private theorem level_sum (f : P.Level k d → ℕ) {Q : ℕ} (h : ∀ i, f i ≤ Q) : + ∑ i, f i ≤ (k + 1) * Q := by + refine (Finset.sum_le_sum (s := Finset.univ) (fun i _ => h i)).trans ?_ + simpa only [Finset.sum_const, Finset.card_univ, Nat.nsmul_eq_mul] using + Nat.mul_le_mul_right Q (P.level_count k d) + +open scoped Classical in +theorem local_volume : + (∑ i, 2 ^ P.localWidth k d i) ≤ (k + 1) * (2 * P.capacity) := by + rw [Fintype.sum_sigma] + apply P.level_sum k d + intro i + simp only [localWidth, pow_succ', ← Finset.mul_sum] + exact Nat.mul_le_mul_left 2 (P.slot_sum i.1.val) + +open scoped Classical in +theorem packet_count : + (∑ i, 2 ^ P.count k d i) ≤ (k + 1) * (4 * d * Fintype.card P.Slot) := by + apply P.level_sum k d + intro i + rw [mul_assoc] + exact (P.count_bound k d i).trans (Nat.mul_le_mul_left 4 (P.port_count d i.1.val)) + +open scoped Classical in +theorem packet_volume : + (∑ i, 2 ^ P.count k d i * 2 ^ i.1.val) ≤ (k + 1) * (8 * P.capacity) := by + apply P.level_sum k d + intro i + let j := i.1.val + have ha : Fintype.card (P.Port d j) * 2 ^ j ≤ 2 * P.capacity := by + simp only [Port, Fintype.card_sigma, Fintype.card_fin, Finset.sum_mul] + calc + _ ≤ ∑ s : P.AtDepth j, 2 ^ (P.depth s.val + 1) := + Finset.sum_le_sum (fun s _ => P.lanes_fit d j s) + _ ≤ _ := by + simp only [pow_succ', ← Finset.mul_sum] + exact Nat.mul_le_mul_left 2 (P.slot_sum j) + calc + _ ≤ 4 * Fintype.card (P.Port d j) * 2 ^ j := Nat.mul_le_mul_right _ (P.count_bound k d i) + _ ≤ _ := by linarith only [ha] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Compute.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Compute.lean new file mode 100644 index 0000000000..28c83fc107 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Compute.lean @@ -0,0 +1,648 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import Mathlib.Data.Fintype.Option +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.WideTag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array + +/-! # Navigation on a symmetric host -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +open scoped Classical in +/-- Unused entries point to their own host. Flags distinguish padding +from actual self contacts. -/ +structure Directory {V : Type} (N : V → Finset V) (m : ℕ) (d : ℕ := 3) where + /-- Injects graph vertices into the fixed-width host address space. -/ + host : V ↪ B m + /-- The destination address for each host and local navigation port. -/ + nav : B m → B d → B m + /-- The local navigation port for an ordered pair of vertices. -/ + index : V → V → B d + nav_link : ∀ v u, u ∈ N v → nav (host v) (index v u) = host u + reciprocal : ∀ i j, nav i j ≠ i → ∃! k, nav (nav i j) k = i + closed : ∀ v j, nav (host v) j ∈ Set.range host + /-- Indicates whether each host port represents an actual contact. -/ + flags : B m → B d → Bool + marks : ∀ v u, u ∈ N v ↔ ∃ k, nav (host v) k = host u ∧ flags (host v) k = true + +open scoped Classical in +/-- Builds the directory from injections numbering hosts and each host's neighbors. -/ +def Directory.numbered {V : Type} (N : V → Finset V) {m d : ℕ} + (hs : ∀ v u, u ∈ N v → v ∈ N u) (host : V ↪ B m) + (link : ∀ v, ↥(N v) ↪ B d) : Directory N m d := by + let index (v u : V) := if h : u ∈ N v then link v ⟨u, h⟩ else 0 + let edge i j u := ∃ v, host v = i ∧ u ∈ N v ∧ index v u = j + let nav i j := if h : ∃ u, edge i j u then host h.choose else i + have found {i j} (h : ∃ u, edge i j u) : ∃ u, edge i j u ∧ nav i j = host u := + ⟨h.choose, h.choose_spec, dite_eq_left h⟩ + have moving {i j} (h : nav i j ≠ i) : ∃ u, edge i j u ∧ nav i j = host u := + found (by by_contra hn; exact h (dite_eq_right hn)) + have follow v u (h : u ∈ N v) : nav (host v) (index v u) = host u := by + obtain ⟨w, ⟨v', hv, hw, he⟩, hn⟩ := found (i := host v) (j := index v u) ⟨u, v, rfl, h, rfl⟩ + have := host.injective hv + subst v' + simp only [index, dite_eq_left hw, dite_eq_left h] at he + have : w = u := congrArg Subtype.val ((link v).injective he) + rwa [this] at hn + refine ⟨host, nav, index, follow, ?_, ?_, fun i j => decide (∃ u, edge i j u), ?_⟩ + · intro i j h + obtain ⟨u, ⟨v, hv, hu, _⟩, hn⟩ := moving h + refine ⟨index u v, by rw [hn]; exact (follow _ _ (hs _ _ hu)).trans hv, ?_⟩ + intro k hk + obtain ⟨w, ⟨z, hz, _, he⟩, hw⟩ := moving (show nav (nav i j) k ≠ nav i j by + rw [hk]; exact h.symm) + rw [host.injective (hz.trans hn), host.injective (hw.symm.trans (hk.trans hv.symm))] at he + exact he.symm + · intro v j + by_cases h : nav (host v) j = host v + · exact ⟨v, h.symm⟩ + obtain ⟨u, _, hu⟩ := moving h + exact ⟨u, hu.symm⟩ + · intro v u + constructor + · intro h + exact ⟨index v u, follow _ _ h, decide_eq_true ⟨u, v, rfl, h, rfl⟩⟩ + · rintro ⟨j, hn, hf⟩ + obtain ⟨w, ⟨z, hz, hw, _⟩, he⟩ := found (of_decide_eq_true hf) + rwa [host.injective hz, host.injective (he.symm.trans hn)] at hw + +open scoped Classical in +theorem Directory.numbered_moving {V : Type} (N : V → Finset V) {m d : ℕ} + (hs : ∀ v u, u ∈ N v → v ∈ N u) (host : V ↪ B m) (link : ∀ v, ↥(N v) ↪ B d) : + let A := Directory.numbered N hs host link + ∀ i j, A.nav i j ≠ i → A.flags i j = true := by + intro A i j h + dsimp only [A, Directory.numbered] at h ⊢ + apply decide_eq_true + exact Classical.byContradiction (fun hn => h (dite_eq_right hn)) + +open scoped Classical in +theorem directory {V : Type} [Fintype V] (N : V → Finset V) (m : ℕ) + (hs : ∀ v u, u ∈ N v → v ∈ N u) (hd : ∀ v, (N v).card ≤ 8) + (hm : Fintype.card V ≤ 2 ^ m) : Nonempty (Directory N m) := by + obtain ⟨host⟩ : Nonempty (V ↪ B m) := + Function.Embedding.nonempty_of_card_le (by simpa using hm) + let link (v : V) : ↥(N v) ↪ B 3 := + Classical.choice (Function.Embedding.nonempty_of_card_le (by simpa using hd v)) + exact ⟨Directory.numbered N hs host link⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Parallel networks on dependent families + +Inputs and outputs carry disjoint named bit sets for each component. +Parallel realization uses the sum of the component budgets. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring + +variable {I : Type} [Fintype I] + +open scoped Classical in +/-- The construction of type `Format` for the given inputs. -/ +abbrev Fmt.pi (A : I → Format) : Format := + ⟨∀ i, (A i).obj, Σ i, (A i).pins, + (Equiv.piCongrRight (fun i => (A i).code)).trans + (Equiv.piCurry (fun i (_ : (A i).pins) => Bool)).symm⟩ + +open scoped Classical in +@[simp] theorem Fmt.width_pi (A : I → Format) : + (Fmt.pi A).width = ∑ i, (A i).width := Fintype.card_sigma + +variable {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} + +open scoped Classical in +theorem Kernel.renamePins {A B C D : Format} {f : A.obj → B.obj → F} + {g : C.obj → D.obj → F} {n : ℕ} (h : Kernel F u L A B f n) + (e : A.pins ≃ C.pins) (d : B.pins ≃ D.pins) + (hg : ∀ x y, f (A.code.symm (x ∘ e)) (B.code.symm (y ∘ d)) = + g (C.code.symm x) (D.code.symm y)) : Kernel F u L C D g n := by + intro a b i j + have k := h a b (e.trans i) (d.trans j) + simp only [view_apply, Equiv.coe_trans, ← Function.comp_assoc, hg] at k + exact k + +open scoped Classical in +private def optionPins (A : Option I → Format) : + (A none).pins ⊕ (Σ i, (A (some i)).pins) ≃ Σ i, (A i).pins where + toFun + | .inl x => ⟨none, x⟩ + | .inr ⟨i, x⟩ => ⟨some i, x⟩ + invFun + | ⟨none, x⟩ => .inl x + | ⟨some i, x⟩ => .inr ⟨i, x⟩ + left_inv := by rintro (x | ⟨i, x⟩) <;> rfl + right_inv := by rintro ⟨_ | i, x⟩ <;> rfl + +open scoped Classical in +theorem Kernel.family {A B : I → Format} {f : (i : I) → (A i).obj → (B i).obj → F} + {m : I → ℕ} (h : ∀ i, Kernel F u L (A i) (B i) (f i) (m i)) : + Kernel F u L (Fmt.pi A) (Fmt.pi B) (fun x y => ∏ i, f i (x i) (y i)) (∑ i, m i) := by + refine Fintype.induction_empty_option (P := fun I => ∀ (A B : I → Format) + (f : (i : I) → (A i).obj → (B i).obj → F) (m : I → ℕ), + (∀ i, Kernel F u L (A i) (B i) (f i) (m i)) → + Kernel F u L (Fmt.pi A) (Fmt.pi B) (fun x y => ∏ i, f i (x i) (y i)) (∑ i, m i)) + ?_ ?_ ?_ I A B f m h + · intro J I _ e ih A B f m h + let _ := Fintype.ofEquiv I e.symm + have k := ih (fun j => A (e j)) (fun j => B (e j)) (fun j => f (e j)) + (fun j => m (e j)) (fun j => h (e j)) + rw [e.sum_comp] at k + refine k.renamePins (e.sigmaCongrLeft (β := fun i => (A i).pins)) + (e.sigmaCongrLeft (β := fun i => (B i).pins)) ?_ + intro x y + exact e.prod_comp (fun i => f i ((Fmt.pi A).code.symm x i) ((Fmt.pi B).code.symm y i)) + · intro A B f m h + let emp (C : PEmpty → Format) : (Fmt.pi C).pins ≃ slots .unit := + ⟨fun x => x.1.elim, Empty.elim, fun x => x.1.elim, fun x => Empty.elim x⟩ + refine Kernel.of_layout (emp A) (emp B) ⟨0, Nat.zero_le _, ?_⟩ + simpa using (Wide.empty (K := F) (u := u) (labels := L)) + · intro J _ ih A B f m h + have k := ih (fun j => A (some j)) (fun j => B (some j)) (fun j => f (some j)) + (fun j => m (some j)) (fun j => h (some j)) + rw [Fintype.sum_option] + refine ((h none).par k).renamePins (optionPins A) (optionPins B) ?_ + intro x y + rw [Fintype.prod_option] + rfl + +open scoped Classical in +theorem Map.family {A B : I → Format} {f : (i : I) → (A i).obj → (B i).obj} + {m : I → ℕ} (h : ∀ i, Map F u L (A i) (B i) (f i) (m i)) : + Map F u L (Fmt.pi A) (Fmt.pi B) (fun x i => f i (x i)) (∑ i, m i) := by + unfold Map at h ⊢ + convert Kernel.family h using 1 + funext x y + by_cases he : (fun i => f i (x i)) = y + · subst y + simp + · rw [ite_eq_right he] + obtain ⟨i, hi⟩ := Function.ne_iff.mp he + exact (Finset.prod_eq_zero (Finset.mem_univ i) (ite_eq_right hi)).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Weighted deterministic maps on a common set of labels + +Weights can encode rejection as well as field scalars withdrawn +during intermediate contractions. They multiply under composition. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring +variable {F : Type} [Field F] {A B C D : Format} {u m n : ℕ} {L : Set (Table F)} + +open scoped Classical in +/-- Requires `Kernel F u L A B (fun x y => if f x = y then w x else 0) m`. -/ +def Action (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) + (A B : Format) (f : A.obj → B.obj) (w : A.obj → F) (m : ℕ) : Prop := + Kernel F u L A B (fun x y => if f x = y then w x else 0) m + +open scoped Classical in +/-- Uses `⟨word A.width, word B.width, fun x y => f (view A (names A) x) (view B (names B) y)⟩` +as the representation. -/ +def lookup (F : Type) (A B : Format) (f : A.obj → B.obj → F) : Table F := + ⟨word A.width, word B.width, fun x y => f (view A (names A) x) (view B (names B) y)⟩ + +open scoped Classical in +theorem Kernel.lookup {f : A.obj → B.obj → F} (hu : A.width + B.width ≤ u) + (hl : Assembly.lookup F A B f ∈ L) : Kernel F u L A B f (1 + A.width + B.width) := by + apply Kernel.of_layout (names A) (names B) + exact ⟨_, by simp [add_assoc], .table _ _ _ (by simpa using hu) (.inr hl)⟩ + +open scoped Classical in +theorem Kernel.vec {t : ℕ} (f : Coloring.B t → A.obj → B.obj → F) + (h : ∀ i, Kernel F u L A B (f i) m) : + Kernel F u L (.vec t A) (.vec t B) (fun x y => ∏ i, f i (x i) (y i)) (2 ^ t * m) := by + have hs := Kernel.family (A := fun _ => A) (B := fun _ => B) h + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, Nat.nsmul_eq_mul] at hs + exact hs.renamePins (Equiv.sigmaEquivProd _ _) (Equiv.sigmaEquivProd _ _) fun _ _ => rfl + +namespace Action +variable {f : A.obj → B.obj} {w : A.obj → F} + +open scoped Classical in +theorem mono (h : Action F u L A B f w m) (hm : m ≤ n) : Action F u L A B f w n := + Kernel.mono h hm + +open scoped Classical in +theorem of_map (h : Map F u L A B f m) : Action F u L A B f (fun _ => 1) m := h + +open scoped Classical in +theorem comp {g : B.obj → C.obj} {v : B.obj → F} + (h : Action F u L A B f w m) (k : Action F u L B C g v n) : + Action F u L A C (g ∘ f) (fun x => w x * v (f x)) (m + n) := by + let _ := Fintype.ofFinite B.obj + have hh := Kernel.comp h k + simp only [ite_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] at hh + simpa only [Action, Function.comp_apply, mul_ite, mul_zero] using hh + +open scoped Classical in +theorem par {g : C.obj → D.obj} {v : C.obj → F} (h : Action F u L A B f w m) + (k : Action F u L C D g v n) : + Action F u L (.pair A C) (.pair B D) (Prod.map f g) (fun x => w x.1 * v x.2) (m + n) := by + have hh := Kernel.par h k + simp only [ite_mul, zero_mul] at hh + simpa only [Action, Prod.ext_iff, Prod.map_fst, Prod.map_snd, ite_and, mul_ite, mul_zero] using hh + +open scoped Classical in +theorem pre {g : C.obj → A.obj} (h : Action F u L A B f w m) (k : Map F u L C A g n) : + Action F u L C B (f ∘ g) (w ∘ g) (n + m) := k.then_kernel h + +open scoped Classical in +theorem post {g : B.obj → C.obj} (h : Action F u L A B f w m) (k : Map F u L B C g n) : + Action F u L A C (g ∘ f) w (m + n) := by + simpa only [mul_one] using h.comp (of_map k) + +open scoped Classical in +theorem vec {t : ℕ} (f : Coloring.B t → A.obj → B.obj) (w : Coloring.B t → A.obj → F) + (h : ∀ i, Action F u L A B (f i) (w i) m) : + Action F u L (.vec t A) (.vec t B) (fun x i => f i (x i)) (fun x => ∏ i, w i (x i)) (2 ^ t * m) + := by + have hk := Kernel.vec _ h + unfold Action + convert hk using 1 + funext x y + by_cases he : (fun i => f i (x i)) = y + · subst y + simp + · rw [ite_eq_right he] + obtain ⟨i, hi⟩ := Function.ne_iff.mp he + exact (Finset.prod_eq_zero (Finset.mem_univ i) (ite_eq_right hi)).symm + +end Action + +open scoped Classical in +theorem Map.vec {t : ℕ} (f : Coloring.B t → A.obj → B.obj) (h : ∀ i, Map F u L A B (f i) m) : + Map F u L (.vec t A) (.vec t B) (fun x i => f i (x i)) (2 ^ t * m) := by + have he := Action.vec f _ (fun i => Action.of_map (h i)) + simp only [Finset.prod_const_one] at he + exact he + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Partial computation on encoded states + +Only reachable records need to be checked. Auxiliary data may be +kept by charging its actual width. Zero weight rejects a branch. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] {u m n : ℕ} {L : Set (Table F)} {I J : Type*} + {A B C D : Format} + +open scoped Classical in +/-- The condition `∃ f, Kernel F u L A B f m ∧ ∀ i v, f (x i) v = if y i = v then w i else 0` on +the specified data. -/ +def Computes (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) + (A B : Format) (x : I → A.obj) (y : I → B.obj) (w : I → F) (m : ℕ) : Prop := + ∃ f, Kernel F u L A B f m ∧ ∀ i v, f (x i) v = if y i = v then w i else 0 + +namespace Computes + +variable {x : I → A.obj} {y : I → B.obj} {z : I → C.obj} + {w v : I → F} + +open scoped Classical in +theorem restrict (h : Computes F u L A B x y w m) (j : J → I) : + Computes F u L A B (x ∘ j) (y ∘ j) (w ∘ j) m := + let ⟨f, k, he⟩ := h + ⟨f, k, fun i => he (j i)⟩ + +open scoped Classical in +theorem mono (h : Computes F u L A B x y w m) (hm : m ≤ n) : + Computes F u L A B x y w n := + let ⟨f, k, he⟩ := h + ⟨f, k.mono hm, he⟩ + +open scoped Classical in +theorem comp (h : Computes F u L A B x y w m) (k : Computes F u L B C y z v n) : + Computes F u L A C x z (fun i => w i * v i) (m + n) := by + let _ := Fintype.ofFinite B.obj + obtain ⟨f, hf, he⟩ := h + obtain ⟨g, hg, hg'⟩ := k + refine ⟨_, hf.comp hg, fun i t => ?_⟩ + simp only [he, ite_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, + hg', mul_ite, mul_zero] + +open scoped Classical in +theorem par {q : I → D.obj} (h : Computes F u L A B x y w m) (k : Computes F u L C D z q v n) : + Computes F u L (.pair A C) (.pair B D) (fun i => (x i, z i)) (fun i => (y i, q i)) + (fun i => w i * v i) (m + n) := by + obtain ⟨f, hf, he⟩ := h + obtain ⟨g, hg, hg'⟩ := k + refine ⟨_, hf.par hg, fun i t => ?_⟩ + simp only [he, hg', ite_mul, zero_mul] + simp only [Prod.ext_iff, ite_and, mul_ite, mul_zero] + +open scoped Classical in +theorem of_action {f : A.obj → B.obj} {p : A.obj → F} (h : Action F u L A B f p m) + (hf : ∀ i, f (x i) = y i) (hp : ∀ i, p (x i) = w i) : Computes F u L A B x y w m := + ⟨_, h, fun i t => by simp only [hf, hp]⟩ + +open scoped Classical in +theorem of_map {f : A.obj → B.obj} (h : Map F u L A B f m) + (hf : ∀ i, f (x i) = y i) : Computes F u L A B x y (fun _ => 1) m := + of_action (Action.of_map h) hf (fun _ => rfl) + +open scoped Classical in +theorem pair (hu : 3 ≤ u) (h : Computes F u L A B x y w m) (k : Computes F u L A C x z v n) : + Computes F u L A (.pair B C) x (fun i => (y i, z i)) (fun i => w i * v i) + (20 * A.width + (m + n)) := by + have c : Circuit F A (.pair A A) (fun a => (a, a)) (5 * A.width) := by + refine (Circuit.project (D := .pair A A) (Sum.elim id id) ?_).mono ?_ + · rintro a (i|i) <;> rfl + · simp only [Format.width_pair]; omega + have cp := of_map (L := L) (x := x) (Map.circuit hu c) (fun _ => rfl) + have hh := cp.comp (h.par k) + simpa only [one_mul, ← mul_assoc, show 4 * 5 = 20 by decide] using hh + +end Computes +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# A controlled permutation of wide records + +The tag order on the binary tree may differ from the numerical +order of addresses. A fixed permutation of the source slots +reconciles the two orders without any gates. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring Install + +variable {F : Type} [Field F] {j v m : ℕ} + +open scoped Classical in +theorem labeled_perm {A D : Type} (name : B j ≃ A) (a : B j → A) + (x y : B j → D) : + (List.ofFn (fun i => (a i, y i))).Perm (List.ofFn (fun i => (name i, x i))) ↔ + Function.Bijective a ∧ ∀ i, y i = x (name.symm (a i)) := by + constructor + · intro h + have he := h.map Prod.fst + simp only [List.map_ofFn, Function.comp_def] at he + have hi := List.nodup_ofFn.mp (he.symm.nodup (List.nodup_ofFn.mpr name.injective)) + have hh : Function.Surjective a := by + intro k + exact List.mem_ofFn.mp (he.symm.subset (List.mem_ofFn.mpr ⟨name.symm k, + name.apply_symm_apply _⟩)) + refine ⟨⟨hi, hh⟩, fun i => ?_⟩ + obtain ⟨l, hl⟩ := List.mem_ofFn.mp (h.subset (List.mem_ofFn.mpr ⟨i, rfl⟩)) + rw [← (Prod.mk.inj hl).1, name.symm_apply_apply] + exact (Prod.mk.inj hl).2.symm + · rintro ⟨ha, h⟩ + let e := (Equiv.ofBijective a ha).trans name.symm + have he : (fun i => (a i, y i)) = (fun i => (name i, x i)) ∘ e := by + funext i + exact Prod.ext (name.apply_symm_apply _).symm (h i) + rw [he] + exact Equiv.Perm.ofFn_comp_perm _ _ + +open scoped Classical in +/-- Indexes the perm bus by the coordinates of `(B j × slots (word v)) ⊕ (B j × (slots (word j) +⊕ slots (word v)))`. -/ +abbrev PermBus (j v : ℕ) := + (B j × slots (word v)) ⊕ (B j × (slots (word j) ⊕ slots (word v))) + +open scoped Classical in +/-- The indexed operation `Control.decode j (fun p => z (.inr (i, .inl p)))`. -/ +def PermBus.address (z : PermBus j v → Bool) (i : B j) := + Control.decode j (fun p => z (.inr (i, .inl p))) + +open scoped Classical in +/-- Requires `Function.Bijective (address z) ∧ ∀ i p, z (.inr (i, .inr p)) = z (.inl (address z +i, p))`. -/ +def PermBus.valid (z : PermBus j v → Bool) : Prop := + Function.Bijective (address z) ∧ ∀ i p, z (.inr (i, .inr p)) = z (.inl (address z i, p)) + +open scoped Classical in +theorem permutation_weight (ht : Radix.Tag F j v m) : + Weight F (fun z : PermBus j v → Bool => if PermBus.valid z then 1 else 0) m := by + obtain ⟨A, hA⟩ := Layout.exists_tree (word j) j + obtain ⟨B, hB⟩ := Layout.exists_tree (word v) j + obtain ⟨C, hC⟩ := Layout.exists_tree (Tagged.row j (word v)) j + let a := A.read (Tagged.indices j) + have hi : Function.Injective a := List.nodup_ofFn.mp (by rw [hA]; exact Tagged.indices_nodup _) + let π := Equiv.ofBijective (Control.index j ∘ a) + (Finite.injective_iff_bijective.mp ((Control.index j).injective.comp hi)) + let e := ((π.symm.prodCongr (.refl _)).trans B.positions).sumCongr C.positions + apply Weight.of_layout (a := Tagged.inputs j (word v)) e + refine ⟨m, le_rfl, ?_⟩ + unfold Radix.Tag at ht + convert ht using 1 + funext ⟨x, y⟩ _ + let z := bits (Tagged.inputs j (word v)) (x, y) ∘ e + let n := π.trans (Control.index j).symm + let s := fun i => (C.read y i).1 + let t := fun i => (C.read y i).2 + have hn : ⇑n = a := by funext i; exact (Control.index j).symm_apply_apply _ + have hL : flatten j (Tagged.label j x) = List.ofFn (fun i => (n i, B.read x i)) := by + rw [Tagged.label, Control.flatten_zip, ← hB, ← hA, Control.zip_ofFn, hn] + have hR : flatten j y = List.ofFn (fun i => (s i, t i)) := (hC y).symm + have he (i : Coloring.B j) : PermBus.address z i = Control.index j (s i) := rfl + have hb : Function.Bijective (PermBus.address z) ↔ Function.Bijective s := by + constructor + · intro h + have h' := (Control.index j).symm.bijective.comp h + simpa only [Function.comp_def, he, Equiv.symm_apply_apply] using h' + · exact fun h => (Control.index j).bijective.comp h + have hy (i : Coloring.B j) : (∀ p, z (.inr (i, .inr p)) = z (.inl (PermBus.address z i, p))) ↔ + t i = B.read x (n.symm (s i)) := by + change _ ↔ (bits (word v)).symm _ = (bits (word v)).symm _ + rw [(bits (word v)).symm.injective.eq_iff, funext_iff] + rfl + have hv : PermBus.valid z ↔ (flatten j y).Perm (flatten j (Tagged.label j x)) := by + rw [hL, hR, labeled_perm, PermBus.valid, hb] + simp only [hy] + change (if PermBus.valid z then (1 : F) else 0) = Tagged.tag F j (word v) (x, y) () + simp only [Tagged.tag, Tagged.permuted, hv] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Tagged exchange on a vector of records with an arbitrary bit format -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring Install + +variable {F : Type} [Field F] {j v m u : ℕ} {L : Set (Table F)} (A : Format) + +open scoped Classical in +/-- The value specified by `(Perm j).pair (.vec j A)`. -/ +abbrev exchangeIn (j : ℕ) := (Perm j).pair (.vec j A) +open scoped Classical in +/-- Computes the exchange out by the application `Format.vec j A`. -/ +abbrev exchangeOut (j : ℕ) := Format.vec j A + +open scoped Classical in +/-- Returns `1` when `Function.Bijective x.1 ∧ y = x.2 ∘ x.1` holds, and `0` otherwise. -/ +def exchange (F : Type) [Field F] (x : (exchangeIn A j).obj) (y : (exchangeOut A j).obj) : F := + if Function.Bijective x.1 ∧ y = x.2 ∘ x.1 then 1 else 0 + +open scoped Classical in +/-- The value specified by `exchange A F ((exchangeIn A j).code.symm (z ∘ Sum.inl)) +((exchangeOut A j).code.symm (z ∘ Sum.inr))`. -/ +def exchangeCheck (F : Type) [Field F] (z : (exchangeIn A j).pins ⊕ (exchangeOut A j).pins → Bool) + := + exchange A F ((exchangeIn A j).code.symm (z ∘ Sum.inl)) ((exchangeOut A j).code.symm (z ∘ + Sum.inr)) + +open scoped Classical in +private def namesIn (e : A.pins ↪ slots (word v)) : + (exchangeIn A j).pins ⊕ (exchangeOut A j).pins ↪ PermBus j v := + ((Equiv.sumComm _ _).sumCongr (.refl _)).toEmbedding.trans + ((Equiv.sumAssoc _ _ _).toEmbedding.trans + (((Function.Embedding.refl _).prodMap e).sumMap + ((Equiv.prodSumDistrib _ _ _).symm.toEmbedding.trans + ((Function.Embedding.refl _).prodMap ((Function.Embedding.refl _).sumMap e))))) + +open scoped Classical in +private theorem pad_weight {I T : Type} [Fintype I] [Fintype T] (e : I ↪ T) + {f : (T → Bool) → F} (h : Weight F f m) : + Weight F (fun x => f (Function.extend e x (fun _ => false))) + (Fintype.card I + 34 * Fintype.card T + m) := by + have hd : Depends (fun x => Function.extend e x (fun _ => false)) 1 := by + intro k + by_cases hk : k ∈ Set.range e + · obtain ⟨a, rfl⟩ := hk + exact ⟨{a}, by simp, fun x y h => by simpa [e.injective.extend_apply] using h a (by simp)⟩ + · exact ⟨∅, by simp, fun x y _ => by simp only [Function.extend_apply' _ _ _ hk]⟩ + exact (hd.bnet F).weight h + +open scoped Classical in +theorem exchange_weight (ht : Radix.Tag F j v m) (ha : A.width ≤ v) : + Weight F (exchangeCheck (j := j) A F) (m + 100 * 2 ^ j * (j + v + 1)) := by + obtain ⟨e⟩ : Nonempty (A.pins ↪ slots (word v)) := + Function.Embedding.nonempty_of_card_le (by simpa [Format.width] using ha) + let k := namesIn (j := j) A e + have h := pad_weight k (permutation_weight ht) + have hn : Fintype.card ((exchangeIn A j).pins ⊕ (exchangeOut A j).pins) + + 34 * Fintype.card (PermBus j v) + m ≤ m + 100 * 2 ^ j * (j + v + 1) := by + have hh := Fintype.card_le_of_embedding k + change Fintype.card ((exchangeIn A j).pins ⊕ (exchangeOut A j).pins) + ≤ Fintype.card (PermBus j v) at hh + have he : Fintype.card (PermBus j v) = 2 ^ j * v + 2 ^ j * (j + v) := by simp [PermBus] + rw [he] at hh ⊢ + generalize Fintype.card ((exchangeIn A j).pins ⊕ (exchangeOut A j).pins) = n at hh ⊢ + ring_nf at hh ⊢ + omega + convert h.mono hn using 1 + funext z + let t := Function.extend k z (fun _ => false) + let x := (exchangeIn A j).code.symm (z ∘ Sum.inl) + let y := (exchangeOut A j).code.symm (z ∘ Sum.inr) + have h₁ (i : B j) (s : A.pins) : t (.inl (i, e s)) = z (.inl (.inr (i, s))) := + k.injective.extend_apply _ _ (.inl (.inr (i, s))) + have h₂ (i : B j) (s : A.pins) : t (.inr (i, .inr (e s))) = z (.inr (i, s)) := + k.injective.extend_apply _ _ (.inr (i, s)) + have haddr : PermBus.address t = x.1 := by + funext i + apply congrArg (Control.decode j) + funext s + exact k.injective.extend_apply _ _ (.inl (.inl (i, s))) + have hp (i l : B j) : + y i = x.2 l ↔ ∀ s, t (.inr (i, .inr s)) = t (.inl (l, s)) := by + change A.code.symm _ = A.code.symm _ ↔ _ + rw [A.code.symm.injective.eq_iff, funext_iff] + constructor + · intro he s + by_cases hs : s ∈ Set.range e + · obtain ⟨a, rfl⟩ := hs + rw [h₁, h₂] + exact he _ + have he₁ : Sum.inr (i, Sum.inr s) ∉ Set.range k := by + rintro ⟨(a | a) | a, hh⟩ <;> first + | solve | cases hh + | exact hs ⟨a.2, Sum.inr.inj (Prod.mk.inj (Sum.inr.inj hh)).2⟩ + have he₂ : Sum.inl (l, s) ∉ Set.range k := by + rintro ⟨(a | a) | a, hh⟩ <;> first + | solve | cases hh + | exact hs ⟨a.2, (Prod.mk.inj (Sum.inl.inj hh)).2⟩ + simp only [t, Function.extend_apply' _ _ _ he₁, Function.extend_apply' _ _ _ he₂] + · intro h s + exact (h₂ i s).symm.trans ((h (e s)).trans (h₁ l s)) + have he : PermBus.valid t ↔ Function.Bijective x.1 ∧ y = x.2 ∘ x.1 := by + simp only [PermBus.valid, haddr, funext_iff, Function.comp_apply, hp] + change (if Function.Bijective x.1 ∧ y = x.2 ∘ x.1 then (1 : F) else 0) = + if PermBus.valid t then 1 else 0 + simp only [he] + +open scoped Classical in +theorem permutation_kernel (hu : 3 ≤ u) (ht : Radix.Tag F j v m) (ha : A.width ≤ v) : + Kernel F u L (exchangeIn A j) (exchangeOut A j) (exchange A F) + (4 * m + 1000 * 2 ^ j * (j + v + 1)) := by + have h := Kernel.of_weight hu (Transcript.of_weight (L := L) hu (exchange_weight A ht ha)) + have hh : 4 * (m + 100 * 2 ^ j * (j + v + 1)) + 4 * (exchangeOut A j).width ≤ 4 * m + + 1000 * 2 ^ j * (j + v + 1) := by + rw [Format.width_vec] + have := Nat.mul_le_mul_left (2 ^ j) ha + ring_nf at this ⊢ + omega + simpa [exchangeCheck, Function.comp_def] using h.mono hh + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# A common interface for exchanging wide records + +The compression argument uses a trivalent tagged permutation. +The many-list descent can instead spend a sorting table. Both +realizations have the same bit-level correctness condition. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +/-- The defining condition `∀ A : Format, A.width ≤ v → Kernel F u L (exchangeIn A j) +(exchangeOut A j) (exchange A F) (4 * n + 1000 * 2 ^ j * (j + v + 1))`. -/ +def Access (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) (j v n : ℕ) : Prop := + ∀ A : Format, A.width ≤ v → + Kernel F u L (exchangeIn A j) (exchangeOut A j) (exchange A F) (4 * n + 1000 * 2 ^ j * (j + v + + 1)) + +variable {F : Type} [Field F] {u j v n : ℕ} {L : Set (Table F)} + +theorem Access.tag (h : 3 ≤ u) (ht : Radix.Tag F j v n) : Access F u L j v n := + fun A => permutation_kernel A h ht + +theorem Access.widen {u' : ℕ} {L' : Set (Table F)} (h : Access F u L j v n) + (hu : u ≤ u') (hL : L ⊆ L') : Access F u' L' j v n := + fun A ha => (h A ha).widen hu hL + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Fragments.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Fragments.lean new file mode 100644 index 0000000000..a4a5177f96 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Fragments.lean @@ -0,0 +1,896 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.RetagStore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.ChannelPlan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood + +/-! Truncate or zero-extend little-endian addresses. -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +open Coloring + +private def resize : (n m : ℕ) → Val (word n) → Val (word m) + | 0, m, _ => Lookup.bits m 0 + | _ + 1, 0, _ => () + | n + 1, m + 1, x => (x.1, resize n m x.2) + +private theorem resize_value (n m : ℕ) (x : Val (word n)) : + Lookup.value m (resize n m x) = Lookup.value n x % 2 ^ m := by + induction n generalizing m with + | zero => simp [resize, Lookup.value_bits, Lookup.value] + | succ n ih => + cases m with + | zero => simp [Lookup.value, Nat.mod_one] + | succ m => + have hh := Nat.mod_add_div (Lookup.value n x.2) (2 ^ m) + rw [← ih] at hh + have e : Lookup.value (n + 1) x = Lookup.value (m + 1) (resize (n + 1) (m + 1) x) + + 2 ^ (m + 1) * (Lookup.value n x.2 / 2 ^ m) := by + change x.1.toNat + 2 * Lookup.value n x.2 = + x.1.toNat + 2 * Lookup.value m (resize n m x.2) + _ + rw [pow_succ'] + nlinarith only [hh] + rw [e, Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt (Control.value_lt _ _)] + +variable (F : Type) [Field F] + +private theorem resize_net (n m : ℕ) : DNet F (word n) (word m) (resize n m) (n + m) := by + induction n generalizing m with + | zero => simpa [resize] using Lookup.const_net F (word m) (Lookup.bits m 0) + | succ n ih => + cases m with + | zero => have h := DNet.discard F (word (n + 1)); rw [wd_word] at h; exact h + | succ m => exact ((DNet.id F .bit).par (ih m)).mono (by simp [wd]; omega) + +theorem cheap_shrink {n m t : ℕ} (hn : n ≤ t) (hm : m ≤ t) : + Cheap F 0 t (.addr n) (.addr m) (shrink m) 2 := by + refine ⟨n + m, ?_, by simp; ring_nf; omega⟩ + apply Circuit.of_dnet (.refl _) (.refl _) (resize_net F n m) + intro x + simp only [Equiv.coe_refl, Function.comp_id] + rw [decode_addr, ← code_addr] + congr 1 + exact Fin.ext (resize_value n m x) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +end + +/- Read both endpoints in the port table, then expand each dyadic level in parallel. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +namespace Peers +variable {p q : ℕ} + +/-- Computes the desc by the application `Format.pair .bit (.pair R R)`. -/ +abbrev desc (R : Format) := Format.pair .bit (.pair R R) + +/-- The value specified by `(x.1, v x.2.1, v x.2.2)`. -/ +def indexRow {R : Format} (v : R.obj → B q) (x : (desc R).obj) : (row q).obj := + (x.1, v x.2.1, v x.2.2) + +/-- The value specified by `eval (indexRow v ∘ x)`. -/ +def decode {R : Format} (v : R.obj → B q) (x : B p → (desc R).obj) := eval (indexRow v ∘ x) + +/-- The maximum of the quantities in `p (max q R.width)`. -/ +def height (p q : ℕ) (R : Format) := max p (max q R.width) +/-- The quantity computed by `height p q R + 3 * q + 1`. -/ +def width (p q : ℕ) (R : Format) := height p q R + 3 * q + 1 + +theorem zipper (F : Type) [Field F] (p : ℕ) {n t : ℕ} (hp : p ≤ n) + (A D : Format) (h : A.width + D.width ≤ (100 + t) ^ 2) : + Cheap F n t (.pair (.vec p A) (.vec p D)) (.vec p (.pair A D)) + (fun x i => (x.1 i, x.2 i)) 4 := by + have hw : (Format.pair (.vec p A) (.vec p D)).width ≤ 2 ^ p * (100 + t) ^ 2 := by + rw [Format.width_pair, Format.width_vec, Format.width_vec, ← mul_add] + exact Nat.mul_le_mul_left _ h + exact lift F (Cheap.id F hw).zip hp + +private theorem index_rows (F : Type) [Field F] (p : ℕ) (R : Format) (v : R.obj → B q) : + ∀ (n t : ℕ), p ≤ n → max p R.width ≤ n → max p R.width + q + 1 ≤ t → + Cheap F n t (.vec p (desc R)) (.vec p (row q)) (fun x => indexRow v ∘ x) 25 := by + intro n t hp hv hu + have hr : R.width ≤ t := by omega + have hd : (desc R).width ≤ 2 ^ 0 * (100 + t) ^ 2 := by simp [desc]; ring_nf; omega + have h := Cheap.id F hd + have flag₀ := Cheap.map (h := p) (A := desc R) (D := .bit) (fun _ z => z.1) (fun _ => h.fst) + have src₀ := Cheap.map (h := p) (A := desc R) (D := R) (fun _ z => z.2.1) (fun _ => h.snd.fst) + have dst₀ := Cheap.map (h := p) (A := desc R) (D := R) (fun _ z => z.2.2) (fun _ => h.snd.snd) + have tab := (lift F (cheap_table F p R v) hv).widen hu + have src := (lift F src₀ hp).comp tab + have dst := (lift F dst₀ hp).comp tab + have hq : q ≤ t := by omega + have both := (src.pair dst).comp (zipper F p (t := t) hp (.addr q) (.addr q) + (by simp; ring_nf; omega)) + have rows := ((lift F flag₀ hp).pair both).comp (zipper F p (t := t) hp .bit + (.pair (.addr q) (.addr q)) (by simp; ring_nf; omega)) + have result := rows.mono (d := 25) (by decide) + exact result + +theorem cheap_decode (F : Type) [Field F] (p : ℕ) (R : Format) (v : R.obj → B q) : + Cheap F (height p q R) (width p q R) (.vec p (desc R)) (Perm q) (decode v) 111 := by + let n := height p q R + let t := width p q R + have hq : max p q ≤ n := by unfold n height; omega + have rows := index_rows F p R v n t (le_max_left _ _) (by unfold n height; omega) + (by unfold t width height; omega) + have endp := (lift F (cheap F p q) hq).widen (show max p q + 3 * q ≤ t by + change _ ≤ n + 3 * q + 1; omega) + have hr := (rows.comp endp).mono (d := 111) (by decide) + rw [show eval ∘ (fun x : B p → (desc R).obj => indexRow v ∘ x) = decode v from rfl] at hr + exact hr + +end Peers + +namespace Channels +variable {A D : Format} (S : Channels A D) (n : S.Levels → ℕ) (R : S.Levels → Format) + +/-- The indexed operation `Fmt.pi (fun i => .vec (n i) (Peers.desc (R i)))`. -/ +abbrev commands := Fmt.pi (fun i => .vec (n i) (Peers.desc (R i))) +/-- The indexed operation `Fmt.pi (fun i => Perm (S.count i))`. -/ +abbrev peers := Fmt.pi (fun i => Perm (S.count i)) + +/-- Maps the coordinate `i` to `Peers.decode (v i) (x i)`. -/ +def readCommands (v : ∀ i, (R i).obj → B (S.count i)) (x : (S.commands n R).obj) : S.peers.obj := + fun i => Peers.decode (v i) (x i) + +/-- The bound obtained by adding the component charges `∑ i, 4 * (2 ^ Peers.height (n i) +(S.count i) (R i) * (100 + Peers.width (n i) (S.count i) (R i)) ^ 111)`. -/ +def commandsCost := ∑ i, 4 * (2 ^ Peers.height (n i) (S.count i) (R i) * + (100 + Peers.width (n i) (S.count i) (R i)) ^ 111) + +theorem peer_commands {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} + (v : ∀ i, (R i).obj → B (S.count i)) (hu : 3 ≤ u) : + Map F u L (S.commands n R) S.peers (S.readCommands n R v) (S.commandsCost n R) := by + apply Map.family + intro i + obtain ⟨m, hm, hcost⟩ := Peers.cheap_decode F (n i) (R i) (v i) + exact (Map.circuit hu hm).mono (Nat.mul_le_mul_left _ (by omega)) + +theorem commands_bound {t : ℕ} (hn : ∀ i, n i ≤ t) (hr : ∀ i, (R i).width ≤ t) + (hc : ∀ i, S.count i ≤ t) : + S.commandsCost n R ≤ Fintype.card S.Levels * (4 * (2 ^ t * (101 + 4 * t) ^ 111)) := by + unfold commandsCost + rw [← smul_eq_mul, ← Finset.card_univ, ← Finset.sum_const] + refine Finset.sum_le_sum fun i _ => ?_ + have hh : Peers.height (n i) (S.count i) (R i) ≤ t := max_le (hn i) (max_le (hc i) (hr i)) + have hw : 100 + Peers.width (n i) (S.count i) (R i) ≤ 101 + 4 * t := by + have := hc i + unfold Peers.width + omega + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul (Nat.pow_le_pow_right (by decide) hh) + (Nat.pow_le_pow_left hw _)) + +end Channels +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- Parallel indirect reads with different numbers of rows and queries. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Peers +open Coloring Intervals + +variable (F : Type) [Field F] {a b n t : ℕ} + +theorem bound_vec (R : Format) (hr : R.width ≤ t) (ha : a ≤ n) : + (Format.vec a R).width ≤ 2 ^ n * (100 + t) ^ 1 := + (vec_bound a (hr.trans (Nat.le_add_left _ _))).trans + (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) ha)) + +theorem reindex (R : Format) (hr : R.width ≤ t) (ha : a ≤ n) (hb : b ≤ n) (f : B b → B a) : + Cheap F n t (.vec a R) (.vec b R) (fun x => x ∘ f) 2 := + Cheap.project F (bound_vec R hr ha) (bound_vec R hr hb) (fun y => (f y.1, y.2)) (fun _ _ => rfl) + +theorem read (R : Format) (hr : R.width ≤ t) (ha : a ≤ n) (hb : b ≤ n) (hn : n ≤ t) : + Cheap F n t (.pair (.vec a R) (.vec b (.addr a))) (.vec b R) (fun u => u.1 ∘ u.2) 12 := by + let A := Format.pair (.vec a R) (.vec b (.addr a)) + have hh : (Format.addr a).width ≤ t := by simpa using ha.trans hn + have hw : A.width ≤ 2 ^ n * (100 + t) ^ 2 := by + rw [show A.width = _ from Format.width_pair ..] + refine (Nat.add_le_add (bound_vec R hr ha) (bound_vec _ hh hb)).trans ?_ + rw [← mul_add] + exact Nat.mul_le_mul_left _ (by ring_nf; omega) + have x := Cheap.id F hw + have table := x.fst.comp (reindex F R hr ha le_rfl (shrink a)) + have idx := x.snd.comp (reindex F (.addr a) hh hb le_rfl (shrink b)) + have resize := Cheap.map (h := n) _ (fun _ => cheap_shrink F (ha.trans hn) hn) + have fetch := (table.pair (idx.comp resize)).comp (Cheap.lookup F n t R hn hr) + have out := fetch.comp (reindex F R hr le_rfl hb (extend hb)) + convert out.mono (d := 12) (by decide) using 1 + funext y i + simp only [Function.comp_apply, id_eq, shrink_extend] + have e (x : B a) : shrink n x = extend ha x := + Fin.ext (Nat.mod_eq_of_lt (x.isLt.trans_le (Nat.pow_le_pow_right (by decide) ha))) + rw [e, shrink_extend] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Peers +end + +/- +# Placing logical fragments in a packet buffer + +A fragment specifies the contact, offset on the contact, length +and starting bank address. Group ranks determine the physical lane. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Fragments + +open Coloring +variable {p w n t : ℕ} + +/-- Computes the rank by the application `Format.pair (.addr w) (.addr p)`. -/ +abbrev Rank (w p : ℕ) := Format.pair (.addr w) (.addr p) +/-- Computes the entry by the application `Format.pair (.addr p) (Intervals.span w)`. -/ +abbrev Entry (w p : ℕ) := Format.pair (.addr p) (Intervals.span w) +/-- Computes the item by the application `Format.pair (Rank w p) (Intervals.span w)`. -/ +abbrev Item (w p : ℕ) := Format.pair (Rank w p) (Intervals.span w) +/-- Computes the input by the application `Format.pair (.vec p (.addr w)) (.vec n (Entry w p))`. -/ +abbrev Input (w p n : ℕ) := Format.pair (.vec p (.addr w)) (.vec n (Entry w p)) + +/-- The value specified by `(PackRank.lanes x.1 (x.2 i).1, (x.2 i).2)`. -/ +def items (x : (Input w p n).obj) (i : B n) : (Item w p).obj := + (PackRank.lanes x.1 (x.2 i).1, (x.2 i).2) + +/-- The quantity computed by `(fun y : B t => y + y)^[s] x`. -/ +def shift (s : ℕ) (x : B t) := (fun y : B t => y + y)^[s] x + +private theorem shift_val (s : ℕ) (x : B t) : (shift s x).val = (2 ^ s * x.val) % 2 ^ t := by + induction s with + | zero => simp [shift, Nat.mod_eq_of_lt x.isLt] + | succ s ih => + rw [shift, Function.iterate_succ_apply', ← shift, Fin.val_add, ih, ← Nat.add_mod, + pow_succ', mul_assoc, two_mul] + +/-- The adjust of type `(Intervals.span t).obj` for the given inputs. -/ +def adjust (s t : ℕ) (x : (Item w p).obj) : (Intervals.span t).obj := + (Intervals.shrink t x.2.1 + shift s (Intervals.shrink t x.1.2), + if x.1.1.val = s then Intervals.shrink t x.2.2.1 else 0, + Intervals.shrink t x.2.2.2) + +/-- The value specified by `adjust s t ∘ items x`. -/ +def runs (s t : ℕ) (x : (Input w p n).obj) := adjust s t ∘ items x + +theorem adjust_val (s t : ℕ) (x : (Item w p).obj) : + (adjust s t x).1.val = (x.2.1.val + 2 ^ s * x.1.2.val) % 2 ^ t ∧ + (adjust s t x).2.1.val = (if x.1.1.val = s then x.2.2.1.val % 2 ^ t else 0) ∧ + (adjust s t x).2.2.val = x.2.2.2.val % 2 ^ t := by + simp only [adjust, Fin.val_add, shift_val, Intervals.shrink] + constructor + · simp only [Nat.mul_mod_mod, ← Nat.add_mod] + · split <;> simp + +variable (F : Type) [Field F] {b s : ℕ} + +private theorem cheap_shift (hs : s ≤ b) (ht : t ≤ b) : + Cheap F 0 b (.addr t) (.addr t) (shift s) 6 := by + have hi := Cheap.id F (show (Format.addr t).width ≤ 2 ^ 0 * (100 + b) ^ 1 by simp; omega) + have hd := (hi.pair hi).comp (Intervals.cheap_add F ht) + exact hd.iterate hs + +private theorem cheap_adjust (hs : s ≤ b) (hh : 4 * w + p + t ≤ b) : + Cheap F 0 b (Item w p) (Intervals.span t) (adjust s t) 24 := by + have hw : w ≤ b := by omega + have ht : t ≤ b := by omega + have hp : p ≤ b := by omega + have h : (Item w p).width ≤ 2 ^ 0 * (100 + b) ^ 1 := by + simp [Item, Rank, Intervals.span]; omega + have h' : (Format.addr t).width ≤ 2 ^ 0 * (100 + b) ^ 1 := by simp; omega + have x := Cheap.id F h + have same : Cheap F 0 b (Item w p) .bit (fun x => decide (x.1.1.val = s)) 7 := by + by_cases he : s < 2 ^ w + · have k := Cheap.const F h (show (Format.addr w).width ≤ 2 ^ 0 * (100 + + b) ^ 1 by simp; omega) ⟨s, he⟩ + have a := (x.fst.fst.pair k).comp (cheap_eq F hw) + convert a.mono (d := 7) (by decide) using 1 + funext i + simp [Fin.ext_iff] + · have k := Cheap.const F h (show Format.bit.width ≤ 2 ^ 0 * (100 + b) ^ 1 by simp; omega) false + convert k.mono (d := 7) (by decide) using 1 + funext i + simp only [decide_eq_false_iff_not] + have := i.1.1.isLt + omega + have resize := Intervals.cheap_shrink F hw ht + have lane := (x.fst.snd.comp (Intervals.cheap_shrink F hp ht)).comp (cheap_shift F hs ht) + have start := ((x.snd.fst.comp resize).pair lane).comp (Intervals.cheap_add F ht) + have len := (x.snd.snd.fst.comp resize).pair (Cheap.const F h h' 0) + have size := (len.pair same).comp ((cheap_select F t).widen ht) + have z := start.pair (size.pair (x.snd.snd.snd.comp resize)) + convert z.mono (d := 24) (by decide) using 1 + funext i + simp only [adjust, Function.comp_apply, id_eq, decide_eq_true_eq] + +theorem cheap (s t : ℕ) (hs : s ≤ b) (hb : n + 4 * w + 2 * p + t + 1 ≤ b) : + Cheap F (max p n) b (Input w p n) (.vec n (Intervals.span t)) (runs s t) 118 := by + have hr : (Rank w p).width ≤ b := by simp [Rank]; omega + have he : (Entry w p).width ≤ b := by simp [Entry, Intervals.span]; omega + have hv : (Intervals.span w).width ≤ b := by simp [Intervals.span]; omega + have ha : (Input w p n).width ≤ 2 ^ max p n * (100 + b) ^ 2 := by + rw [Format.width_pair] + refine (Nat.add_le_add (Peers.bound_vec (t := b) (.addr w) (by simp; omega) (le_max_left p n)) + (Peers.bound_vec _ he (le_max_right p n))).trans ?_ + rw [← mul_add] + exact Nat.mul_le_mul_left _ (by nlinarith) + have x := Cheap.id F ha + have rank := Peers.lift F ((PackRank.cheap_lanes F p w).widen (l + := b) (by omega)) (le_max_left p n) + have u := Cheap.id F (show (Entry w p).width ≤ 2 ^ 0 * (100 + + b) ^ 1 by simp only [pow_zero, pow_one, one_mul]; omega) + have key := Peers.lift F (Cheap.map (h := n) _ (fun _ => u.fst)) (le_max_right p n) + have cost := Peers.lift F (Cheap.map (h := n) _ (fun _ => u.snd)) (le_max_right p n) + have v := ((x.fst.comp rank).pair (x.snd.comp key)).comp + (Peers.read F (Rank w p) hr (le_max_left p n) (le_max_right p n) (by omega)) + have get := (v.pair (x.snd.comp cost)).comp (Peers.zipper F n (le_max_right p n) _ _ (by + nlinarith)) + have conv := Cheap.map (h := n) _ (fun _ => cheap_adjust (w := w) (p := p) (t + := t) F hs (by omega)) + exact (get.comp (Peers.lift F conv (le_max_right p n))).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Fragments +end + +/- Translating a lane's local ordinal into its global packet address. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank.Links + +open Coloring +variable {A D : Format} {P : Bank A D} {k d h p w : ℕ} (L : P.Links k d) + (i : P.Level k d) (host : P.Slot ↪ B h) (hd : d ≤ 2 ^ p) + +/-- The value specified by `(true, P.codePort i host hd (L.location i e), P.codePort i host hd +(L.location i (L.opposite i e)))`. -/ +def descriptor (e : L.At i × Bool) : (Peers.desc (pairCode h p)).obj := + (true, P.codePort i host hd (L.location i e), P.codePort i host hd (L.location i (L.opposite i + e))) + +theorem index_descriptor (e : L.At i × Bool) : + Peers.indexRow (P.portTable i host hd) (L.descriptor i host hd e) = L.peerRow i e := by + exact Prod.ext rfl (Prod.ext (P.portTable_at i host hd _) (P.portTable_at i host hd _)) + +theorem codePort_of_fits (e : L.At i × Bool) (x : B p → B w) + (he : L.FitsLengths (L.site i e).val hd x) : + P.codePort i host hd (L.location i e) = + (host (L.place (e.1.val, e.2)).1, (PackRank.lanes x ((L.place (e.1.val, + e.2)).2.castLE hd)).2) := + Prod.ext rfl (Fin.ext (L.lanes_correct i e he).2.symm) + +theorem decoded {t : ℕ} (x : B t → (Peers.desc (pairCode h p)).obj) + (ok : ∀ j, (x j).1 = true → ∃ a, x j = L.descriptor i host hd a) + (cover : ∀ a, ∃ j, x j = L.descriptor i host hd a) : + Peers.decode (P.portTable i host hd) x = L.plan.control.2.1 i := by + apply L.peers_correct + · intro j h + obtain ⟨a, ha⟩ := ok j h + exact ⟨a, by rw [Function.comp_apply, ha, index_descriptor]⟩ + · intro a + obtain ⟨j, hj⟩ := cover a + exact ⟨j, by rw [Function.comp_apply, hj, index_descriptor]⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank.Links +end + +/- # Uniform size allowance for a bank of controlled transfers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring +variable {A D : Format} + +open scoped Classical in +theorem Channels.width (S : Channels A D) : + S.control.width = (∑ i, 2 ^ S.localWidth i * S.localWidth i) + + (∑ i, 2 ^ S.count i * S.count i) + D.width := by + simp only [Channels.control, Format.width_pair, Fmt.width_pi, Format.width_vec, Format.width_addr, + add_assoc] + +open scoped Classical in +private theorem Channels.budget (S : Channels A D) {T : ℕ} (hT : 0 < T) + (v m : S.Levels → ℕ) (hi : ∀ i, (101 + S.localWidth i) ^ 8 ≤ T) + (hv : ∀ i, S.count i + 1 ≤ v i) (hm : ∀ i, m i ≤ T * (2 ^ (S.count i) * v i)) : + S.cost v m ≤ 20000 * T * (1 + A.width + D.width + (∑ i, 2 ^ S.localWidth i) + (∑ i, + 2 ^ S.count i * v i)) := by + let X := ∑ i, 2 ^ S.localWidth i + let Y := ∑ i, 2 ^ S.count i * v i + have hl : (∑ i, Channels.localCost (S.localWidth i)) ≤ T * X := by + unfold X + rw [Finset.mul_sum] + refine Finset.sum_le_sum fun i _ => ?_ + rw [Channels.localCost, show 100 + (S.localWidth i + 1) = 101 + + S.localWidth i by omega, mul_comm] + exact Nat.mul_le_mul_right _ (hi i) + have hg : (∑ i, Channels.globalCost (m i) (S.count i) (v i)) ≤ 201 * T * Y := by + unfold Y + rw [Finset.mul_sum] + refine Finset.sum_le_sum fun i _ => ?_ + unfold Channels.globalCost + have hb := Nat.mul_le_mul_left (2 ^ S.count i) (hv i) + have hh := Nat.le_mul_of_pos_left (2 ^ S.count i * v i) hT + linarith only [hm i, hb, hh] + have hw : S.control.width ≤ T * X + Y + D.width := by + rw [S.width, show T * X = ∑ i, T * 2 ^ S.localWidth i from Finset.mul_sum ..] + refine Nat.add_le_add_right (Nat.add_le_add ?_ ?_) _ + · apply Finset.sum_le_sum + intro i _ + rw [mul_comm] + apply Nat.mul_le_mul_right + exact le_trans (by omega : S.localWidth i ≤ 101 + S.localWidth i) + ((Nat.le_pow (by decide)).trans (hi i)) + · exact Finset.sum_le_sum fun i _ => Nat.mul_le_mul_left _ (le_trans (by omega) (hv i)) + unfold cost + rw [Format.width_pair] + change 8 * (S.control.width + A.width + D.width + X + 1) + 36 * (16 + _ + _ + 32 * D.width) + + 4 * D.width ≤ + 20000 * T * (1 + A.width + D.width + X + Y) + have ht (n : ℕ) : n ≤ T * n := Nat.le_mul_of_pos_left n hT + linarith only [hw, hl, hg, ht A.width, ht D.width, ht X, ht Y, hT, Nat.zero_le X, Nat.zero_le Y, + Nat.zero_le A.width, Nat.zero_le D.width] + +namespace Bank + +open scoped Classical in +/-- Separate the cost of wide payloads from the allowance per +participating host. `v` is the threshold width for global permutations. -/ +theorem realize {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} (P : Bank A D) (k d n T v : ℕ) + (hu : 3 ≤ u) (hk : ∀ i, P.depth i ≤ k) (hn : d * Fintype.card P.Slot < 2 ^ n) + (hT : (102 + k) ^ 8 ≤ T) (hv : n + 1 ≤ v) + (ht : ∀ j w, 1 ≤ j → j ≤ n → v ≤ w → ∃ s ≤ T * (2 ^ j * w), Radix.Tag F j w s) : + let S := P.channels k d + Kernel F u L (S.control.pair A) D (S.kernel F) + (20000 * T * (1 + A.width + D.width + (k + 1) * (10 * P.capacity + + 4 * d * Fintype.card P.Slot * v))) := by + intro S + let w := fun i : P.Level k d => 2 ^ i.1.val + v + choose m hm ht using fun i => ht (P.count k d i) (w i) (P.count_range k d hn i).1 + (P.count_range k d hn i).2 (Nat.le_add_left v _) + have hb := S.realize F (L := L) hu w m (fun _ => Nat.le_add_right _ _) ht + refine hb.mono (le_trans (Channels.budget S (lt_of_lt_of_le (by positivity) hT) w m ?_ ?_ hm) ?_) + · intro i + apply le_trans _ hT + apply Nat.pow_le_pow_left + change 101 + (P.depth i.2.val + 1) ≤ 102 + k + have := hk i.2.val + omega + · intro i + exact ((Nat.add_le_add_right (P.count_range k d hn i).2 1).trans hv).trans (Nat.le_add_left _ _) + apply Nat.mul_le_mul_left + change 1 + A.width + D.width + (∑ i, 2 ^ P.localWidth k d i) + + (∑ i, 2 ^ P.count k d i * (2 ^ i.1.val + v)) ≤ _ + simp only [mul_add, Finset.sum_add_distrib, ← Finset.sum_mul] + linarith only [P.local_volume k d, P.packet_volume k d, + Nat.mul_le_mul_right v (P.packet_count k d)] + +end Bank +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Realizing a bounded number of payload contacts per host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring Transcript + +open scoped Classical in +/-- Builds `Bank (Fmt.payload m V k) (Fmt.payload m' V' k') where Slot` with the specified +`Slot`, `depth`. -/ +def payloadBank (m V k m' V' k' : ℕ) : Bank (Fmt.payload m V k) (Fmt.payload m' V' k') where + Slot := Slot (2 ^ m) V k ⊕ Slot (2 ^ m') V' k' + depth := Sum.elim (fun s => s.1.val) (fun s => s.1.val) + atBit + | .inl s, i => .inl ⟨s, i⟩ + | .inr s, i => .inr ⟨s, i⟩ + +variable {m V k m' V' k' d : ℕ} {x : Payload m V k} {y : Payload m' V' k'} + +namespace Payload + +open scoped Classical in +/-- Within a contact, positions at each end are listed in common +transmission order. Each bit belongs to at most one contact. -/ +structure Traffic (x : Payload m V k) (y : Payload m' V' k') (d : ℕ) where + /-- The type of edges. -/ + E : Type + /-- Assigns the source of each connection. -/ + src : E ↪ B m × Fin d + /-- Assigns the destination of each connection. -/ + dst : E ↪ B m' × Fin d + /-- The length of the indexed record carried by `Traffic`, with type `E → ℕ`. -/ + length : E → ℕ + /-- Embeds the coordinates as `∀ i, Fin (length i) ↪ Fin (x.length (src i).1)`. -/ + send : ∀ i, Fin (length i) ↪ Fin (x.length (src i).1) + /-- Embeds the coordinates as `∀ i, Fin (length i) ↪ Fin (y.length (dst i).1)`. -/ + get : ∀ i, Fin (length i) ↪ Fin (y.length (dst i).1) + disjoint_send : ∀ e e' i j, (src e).1 = (src e').1 → + (send e i).val = (send e' j).val → e = e' ∧ i.val = j.val + disjoint_get : ∀ e e' i j, (dst e).1 = (dst e').1 → + (get e i).val = (get e' j).val → e = e' ∧ i.val = j.val + covers : ∀ j : y.Bit, ∃ e t, (⟨(dst e).1, get e t⟩ : y.Bit) = j + +namespace Traffic +variable (p : Traffic x y d) + +open scoped Classical in +/-- Uses `⟨(p.src e).1, p.send e i⟩` as the representation. -/ +def source (e : p.E) (i : Fin (p.length e)) : x.Bit := ⟨(p.src e).1, p.send e i⟩ +open scoped Classical in +/-- Uses `⟨(p.dst e).1, p.get e i⟩` as the representation. -/ +def target (e : p.E) (i : Fin (p.length e)) : y.Bit := ⟨(p.dst e).1, p.get e i⟩ + +open scoped Classical in +/-- In the case `(e, false)`, this construction gives `(.inl (x.seat.write (p.src e).1), (p.src +e).2)`. -/ +def place : p.E × Bool ↪ (payloadBank m V k m' V' k').Slot × Fin d where + toFun + | (e, false) => (.inl (x.seat.write (p.src e).1), (p.src e).2) + | (e, true) => (.inr (y.seat.write (p.dst e).1), (p.dst e).2) + inj' := by + rintro ⟨a, _ | _⟩ ⟨b, _ | _⟩ h + · have he := x.seat.injective (Sum.inl.inj (Prod.mk.inj h).1) + exact Prod.ext (p.src.injective (Prod.ext he (Prod.mk.inj h).2)) rfl + · cases (Prod.mk.inj h).1 + · cases (Prod.mk.inj h).1 + · have he := y.seat.injective (Sum.inr.inj (Prod.mk.inj h).1) + exact Prod.ext (p.dst.injective (Prod.ext he (Prod.mk.inj h).2)) rfl + +open scoped Classical in +/-- Builds `(payloadBank m V k m' V' k').Links (max k k') d where E` with the specified `place`, +`length`, `pointer`, `small`. -/ +def links : (payloadBank m V k m' V' k').Links (max k k') d where + E := p.E + place := p.place + length := p.length + pointer e b i := match b with + | false => (p.send e i).castLE (x.fits _) + | true => (p.get e i).castLE (y.fits _) + small e b := by + cases b + · have he : p.length e ≤ x.length (p.src e).1 := by + simpa only [Fintype.card_fin] using Fintype.card_le_of_embedding (p.send e) + exact he.trans (x.fits _) + · have he : p.length e ≤ y.length (p.dst e).1 := by + simpa only [Fintype.card_fin] using Fintype.card_le_of_embedding (p.get e) + exact he.trans (y.fits _) + bounded e b := by + cases b + · exact (Nat.lt_succ_iff.mp (x.seat.write (p.src e).1).1.isLt).trans (le_max_left _ _) + · exact (Nat.lt_succ_iff.mp (y.seat.write (p.dst e).1).1.isLt).trans (le_max_right _ _) + distinct := by + rintro ⟨e, _ | _⟩ ⟨e', _ | _⟩ i j hs ht + · obtain ⟨he, hj⟩ := p.disjoint_send _ _ i j (x.seat.injective (Sum.inl.inj hs)) ht + exact ⟨congrArg (fun z => (z, false)) he, hj⟩ + · cases hs + · cases hs + · obtain ⟨he, hj⟩ := p.disjoint_get _ _ i j (y.seat.injective (Sum.inr.inj hs)) ht + exact ⟨congrArg (fun z => (z, true)) he, hj⟩ + pad i := decide (i ∉ Set.range y.wire) + +open scoped Classical in +theorem matches_iff (f : y.Bit → x.Bit) (h : ∀ e t, f (p.target e t) = p.source e t) + (a : x.Bit → Bool) (b : (Fmt.payload m' V' k').obj) : + p.links.Matches (x.store a) b ↔ b = y.store (a ∘ f) := by + have he : p.links.Matches (x.store a) b ↔ + (∀ i ∉ Set.range y.wire, b i = false) ∧ + ∀ e i, x.store a (x.wire (p.source e i)) = b (y.wire (p.target e i)) := by + unfold Bank.Links.Matches + simp only [show ∀ i, p.links.pad i = true ↔ i ∉ Set.range y.wire from + fun _ => decide_eq_true_iff] + rfl + rw [he] + constructor + · rintro ⟨hp, hb⟩ + refine y.store_unique _ _ ?_ hp + intro i + obtain ⟨e, t, ht⟩ := p.covers i + change p.target e t = i at ht + rw [← ht, ← hb, read_store, Function.comp_apply, h] + · rintro rfl + exact ⟨y.padding _, fun e t => by rw [read_store, read_store, Function.comp_apply, h]⟩ + +open scoped Classical in +theorem kernel (F : Type) [Field F] (f : y.Bit → x.Bit) + (h : ∀ e t, f (p.target e t) = p.source e t) + (a : x.Bit → Bool) (b : (Fmt.payload m' V' k').obj) : + ((payloadBank m V k m' V' k').channels (max k k') d).kernel F (p.links.plan.control, + x.store a) b = + if b = y.store (a ∘ f) then 1 else 0 := by + simp only [Channels.kernel, p.links.carries, p.matches_iff f h] + +end Traffic +end Payload +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Reindexing exterior coordinates across snapshots -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring + +namespace Scheme +variable {F : Type} (S S' : Scheme F) {r : S.format.obj} {r' : S'.format.obj} {V k V' k' d : ℕ} + (h : S.Fits r V k) (h' : S'.Fits r' V' k') (f : S'.exposed r' → S.exposed r) + +open scoped Classical in +/-- The value specified by `S.index r h ∘ f ∘ (S'.index r' h').symm`. -/ +def transfer := S.index r h ∘ f ∘ (S'.index r' h').symm + +end Scheme +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Logical endpoint addresses + +An address contains the side, dyadic host level, ordinal in that +level and ordinal of the contact at its packet level. Both directions +of a contact are generated from a single forward peer index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout +open Coloring + +variable {m m' V V' k k' d p w : ℕ} + +open scoped Classical in +/-- Computes the lengths by the application `Format.pair (.vec m (.addr w)) (.vec m (.vec p +(.addr w)))`. -/ +abbrev lengths (m p w : ℕ) := Format.pair (.vec m (.addr w)) (.vec m (.vec p (.addr w))) +open scoped Classical in +/-- The quantity computed by `Format.pair (.pair (lengths m p w) (lengths m' p w)) (.vec (m + p) +(.addr (m' + p)))`. -/ +abbrev input (m m' p w : ℕ) := Format.pair (.pair (lengths m p w) (lengths m' p w)) + (.vec (m + p) (.addr (m' + p))) + +open scoped Classical in +/-- Computes the host fmt by the application `Format.pair .bit (.pair (.addr b) (.addr a))`. -/ +abbrev hostFmt (a b : ℕ) := Format.pair .bit (.pair (.addr b) (.addr a)) +open scoped Classical in +/-- Computes the key fmt by the application `Bank.pairCode (hostFmt a b).width p`. -/ +abbrev keyFmt (a b p : ℕ) := Bank.pairCode (hostFmt a b).width p +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev bits (k k' : ℕ) := Nat.clog 2 (max k k' + 1) + +open scoped Classical in +/-- The value specified by `(hostFmt a b).serial (side, Intervals.shrink b v.1, Intervals.shrink +a v.2)`. -/ +def hostCode (a b : ℕ) (side : Bool) (v : B w × B m) : B (hostFmt a b).width := + (hostFmt a b).serial (side, Intervals.shrink b v.1, Intervals.shrink a v.2) + +open scoped Classical in +/-- The address of type `(keyFmt a b p).obj`, constructed using `Match.rowIndex m p i`. -/ +def address (a b : ℕ) (side : Bool) (x : (lengths m p w).obj) (i : B (m + p)) : + (keyFmt a b p).obj := + let h := Match.rowIndex m p i + (hostCode a b side (PackRank.assign x.1 h.1), (PackRank.lanes (x.2 h.1) h.2).2) + +open scoped Classical in +/-- Tests whether `0 < v.val ∧ Nat.clog 2 v.val = l` holds. -/ +def enabled (l : ℕ) (v : B w) := decide (0 < v.val ∧ Nat.clog 2 v.val = l) + +open scoped Classical in +/-- Computes the active by the application `enabled l (x.2 (Match.rowIndex m p i).1 +(Match.rowIndex m p i).2)`. -/ +def active (l : ℕ) (x : (lengths m p w).obj) (i : B (m + p)) := + enabled l (x.2 (Match.rowIndex m p i).1 (Match.rowIndex m p i).2) + +open scoped Classical in +/-- The rows of type `(Peers.desc (keyFmt a b p)).obj`, constructed using `Match.rowIndex (m + +p) 1 j`. -/ +def rows (a b l : ℕ) (x : (input m m' p w).obj) (j : B (m + p + 1)) : + (Peers.desc (keyFmt a b p)).obj := + let i := Match.rowIndex (m + p) 1 j + let L := address a b false x.1.1 i.1 + let R := address a b true x.1.2 (x.2 i.1) + (active l x.1.1 i.1, if i.2 = 0 then (L, R) else (R, L)) + +open scoped Classical in +/-- The quantity computed by `(hostFmt a b).serial (side, Fin.ofNat (2 ^ b) u.1.val, Fin.ofNat +(2 ^ a) u.2.val)`. -/ +def slotCode (a b : ℕ) (side : Bool) (u : Transcript.Slot (2 ^ m) V k) : B (hostFmt a b).width := + (hostFmt a b).serial (side, Fin.ofNat (2 ^ b) u.1.val, Fin.ofNat (2 ^ a) u.2.val) + +open scoped Classical in +theorem slotCode_inj (a b : ℕ) (side : Bool) (hm : m ≤ a) (hk : k < 2 ^ b) : + Function.Injective (slotCode (m := m) (V := V) (k := k) a b side) := by + rintro ⟨i, s⟩ ⟨j, t⟩ he + have h := (Prod.mk.inj ((hostFmt a b).serial.injective he)).2 + have hi : i.val < 2 ^ b := (Nat.le_of_lt_succ i.isLt).trans_lt hk + have hj : j.val < 2 ^ b := (Nat.le_of_lt_succ j.isLt).trans_lt hk + have hij : i = j := by + apply Fin.ext + have hv := congrArg (fun z => z.1.val) h + change i.val % 2 ^ b = j.val % 2 ^ b at hv + rwa [Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt hj] at hv + subst j + have hr : Transcript.seats (2 ^ m) V i.val ≤ 2 ^ a := + (min_le_left _ _).trans (Nat.pow_le_pow_right (by decide) hm) + have hst : s = t := by + apply Fin.ext + have hv := congrArg (fun z => z.2.val) h + change s.val % 2 ^ a = t.val % 2 ^ a at hv + rwa [Nat.mod_eq_of_lt (s.isLt.trans_le hr), Nat.mod_eq_of_lt (t.isLt.trans_le hr)] at hv + rw [hst] + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def host (m V k m' V' k' : ℕ) : + (payloadBank m V k m' V' k').Slot ↪ B (hostFmt (max m m') (bits k k')).width where + toFun := Sum.elim (slotCode _ _ false) (slotCode _ _ true) + inj' := by + have h : max k k' < 2 ^ bits k k' := Nat.le_pow_clog (by decide : 1 < 2) (max k k' + 1) + rintro (s|s) (t|t) he + · exact congrArg Sum.inl (slotCode_inj _ _ _ (le_max_left _ _) ((le_max_left _ _).trans_lt h) + he) + · exact Bool.false_ne_true (Prod.mk.inj ((hostFmt _ _).serial.injective he)).1 |>.elim + · exact Bool.false_ne_true (Prod.mk.inj ((hostFmt _ _).serial.injective he.symm)).1 |>.elim + · exact congrArg Sum.inr (slotCode_inj _ _ _ (le_max_right _ _) ((le_max_right _ _).trans_lt h) + he) + +open scoped Classical in +theorem assigned_slot (a b : ℕ) (side : Bool) (v : Payload m V k) (x : B m → B w) + (h : ∀ i, (x i).val = v.length i) (i : B m) : + hostCode a b side (PackRank.assign x i) = slotCode a b side (v.seat.write i) := by + obtain ⟨h₁, h₂⟩ := PackRank.correct v x h i + unfold hostCode slotCode + exact congrArg _ (Prod.ext rfl (Prod.ext (Fin.ext (congrArg (· % 2 ^ b) h₁)) (Fin.ext (congrArg + (· % 2 ^ a) h₂)))) + +open scoped Classical in +/-- The value specified by `(Match.rowIndex m p).symm (e.1, e.2.castLE hd)`. -/ +def post (hd : d ≤ 2 ^ p) (e : B m × Fin d) := (Match.rowIndex m p).symm (e.1, e.2.castLE hd) + +variable {x : Payload m V k} {y : Payload m' V' k'} (L : Payload.Traffic x y d) (hd : d ≤ 2 ^ p) + +open scoped Classical in +/-- The data for the fits construction, including `from_size`, `to_size`, `send`, `receive`, +`all_send`. -/ +structure Fits (v : (input m m' p w).obj) : Prop where + from_size : ∀ i, (v.1.1.1 i).val = x.length i + to_size : ∀ i, (v.1.2.1 i).val = y.length i + send : ∀ e, (v.1.1.2 (L.src e).1 ((L.src e).2.castLE hd)).val = L.length e + receive : ∀ e, (v.1.2.2 (L.dst e).1 ((L.dst e).2.castLE hd)).val = L.length e + all_send : ∀ i j, 0 < (v.1.1.2 i j).val → ∃ e, (L.src e).1 = i ∧ (L.src e).2.castLE hd = j + all_receive : ∀ i j, 0 < (v.1.2.2 i j).val → ∃ e, (L.dst e).1 = i ∧ (L.dst e).2.castLE hd = j + peer : ∀ e, 0 < L.length e → v.2 (post hd (L.src e)) = post hd (L.dst e) + +open scoped Classical in +/-- Computes the p by the application `payloadBank m V k m' V' k'`. -/ +abbrev P (m V k m' V' k' : ℕ) := payloadBank m V k m' V' k' +open scoped Classical in +/-- The value specified by `(P m V k m' V' k').channels (max k k') d`. -/ +abbrev S (m V k m' V' k' d : ℕ) := (P m V k m' V' k').channels (max k k') d + +open scoped Classical in +/-- The indexed operation `fun i => Peers.decode ((P m V k m' V' k').portTable i (host _ _ _ _ _ +_) hd) (rows (max m m') (bits k k') i.1.val v)`. -/ +def control (hd : d ≤ 2 ^ p) (v : (input m m' p w).obj) : (S m V k m' V' k' d).peers.obj := + fun i => Peers.decode ((P m V k m' V' k').portTable i (host _ _ _ _ _ _) hd) + (rows (max m m') (bits k k') i.1.val v) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout +end + +/- Local addresses and activity flags in parallel at every host and contact. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout + +open Coloring +variable (F : Type) [Field F] {p m w a b t : ℕ} + +private theorem cheap_host (side : Bool) (ht : m + w + a + b + 1 ≤ t) : + Cheap F 0 t (.pair (.addr w) (.addr m)) (.addr (hostFmt a b).width) + (hostCode a b side) 10 := by + let X := Format.pair (.addr w) (.addr m) + have hw : X.width ≤ 2 ^ 0 * (100 + t) ^ 1 := by simp [X]; omega + have x := Cheap.id F hw + have first := x.fst.comp (Intervals.cheap_shrink F (show w ≤ t by omega) (show b ≤ t by omega)) + have second := x.snd.comp (Intervals.cheap_shrink F (show m ≤ t by omega) (show a ≤ t by omega)) + have flag := Cheap.const F hw (show Format.bit.width ≤ 2 ^ 0 * (100 + t) ^ 1 by simp; omega) side + let V := hostFmt a b + have hV : V.width ≤ t := by simp [V, hostFmt]; omega + have hserial : Cheap F 0 t V (.addr V.width) V.serial 5 := by + have hi : V.width ≤ 2 ^ 0 * (100 + t) ^ 1 := by simp; omega + have hj : (Format.addr V.width).width ≤ 2 ^ 0 * (100 + t) ^ 1 := by simp; omega + have input := Cheap.project F hi (Intervals.vec_bound 0 (show V.width ≤ 100 + t by omega)) + (f := fun (x : V.obj) (_ : B 0) => x) (fun i => i.2) (fun _ _ => rfl) + have output := Cheap.project F (A := Column 0 V.width) (D + := .addr V.width) (column_width 0 hV) hj (f := fun x => x 0) + (fun i => (0, i)) (fun _ _ => rfl) + exact ((input.comp (cheap_keys V F 0 hV)).comp output).mono (by decide) + exact ((flag.pair (first.pair second)).comp hserial).mono (by decide) + +private theorem cheap_enabled (l : ℕ) (hw : w ≤ t) : + Cheap F 0 t (.addr w) .bit (enabled l) 24 := by + have ha : (Format.addr w).width ≤ 2 ^ 0 * (100 + t) ^ 1 := by simp; omega + have hc : Format.bit.width ≤ 2 ^ 0 * (100 + t) ^ 1 := by simp; omega + by_cases h : l < 2 ^ w + · let c : B w := ⟨l, h⟩ + have hp := ((Cheap.const F ha ha 0).pair (Cheap.id F ha)).comp (Intervals.cheap_compare F hw) + have he := (((PackRank.cheap_code F w).widen hw).pair (Cheap.const F ha ha c)).comp (cheap_eq F + hw) + have hand : Cheap F 0 t (.pair .bit .bit) .bit (fun z => z.1 && z.2) 2 := by + refine ⟨_, small (by simp) _, ?_⟩ + simp; ring_nf; omega + convert ((hp.pair he).comp hand).mono (d := 24) (by decide) using 1 + funext x + simp [enabled, c, PackRank.code, Fin.ext_iff] + · convert (Cheap.const F ha hc false).mono (d := 24) (by decide) using 1 + funext x + have he : Nat.clog 2 x.val ≠ l := ne_of_lt ((PackRank.code x).isLt.trans_le (le_of_not_gt h)) + simp [enabled, he] + +theorem lengths_bound (h : w ≤ t) : (lengths m p w).width ≤ 2 ^ (m + p) * (100 + t) ^ 2 := by + simp only [lengths, Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add, pow_add, + mul_assoc] + apply Nat.mul_le_mul_left + calc + _ ≤ 2 ^ p * (w + w) := by + rw [mul_add] + exact Nat.add_le_add_right (Nat.le_mul_of_pos_left _ (by positivity)) _ + _ ≤ 2 ^ p * (100 + t) ^ 2 := Nat.mul_le_mul_left _ (by ring_nf; omega) + +theorem cheap_active (l : ℕ) (h : w ≤ t) : + Cheap F (m + p) t (lengths m p w) (.vec (m + p) .bit) (active l) 28 := by + have ha := lengths_bound (m := m) (p := p) h + have hw : (Column (m + p) w).width ≤ 2 ^ (m + p) * (100 + t) ^ 2 := by + simp only [Column, Format.width_vec, Format.width_addr] + exact Nat.mul_le_mul_left _ (by ring_nf; omega) + have get := Cheap.project F (A := lengths m p w) (D := Column (m + p) w) ha hw + (f := fun x i => x.2 (Match.rowIndex m p i).1 (Match.rowIndex m p i).2) + (fun z => .inr ((Match.rowIndex m p z.1).1, (Match.rowIndex m p z.1).2, z.2)) (fun _ _ => rfl) + exact (get.comp (Cheap.map _ (fun _ : B (m + p) => cheap_enabled F l h))).mono (by decide) + +theorem cheap_address (side : Bool) (ht : m + p + w + a + b + 1 ≤ t) : + Cheap F (m + p) t (lengths m p w) (.vec (m + p) (keyFmt a b p)) (address a b side) 120 := by + have x := Cheap.id F (lengths_bound (m := m) (p := p) (show w ≤ t by omega)) + have name := ((PackRank.cheap F m w).widen (show m + w ≤ t by omega)).comp + (Cheap.map _ (fun _ : B m => cheap_host F side (show m + w + a + b + 1 ≤ t by omega))) + have host := x.fst.comp (Peers.lift F name (by omega : m ≤ m + p)) + have hw : (hostFmt a b).width ≤ t := by simp [hostFmt]; omega + have ha : (Column m (hostFmt a b).width).width ≤ 2 ^ (m + p) * (100 + t) ^ 1 := + (column_width _ hw).trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (by omega))) + have spread := Cheap.project F (A := Column m (hostFmt a b).width) (D := Column (m + + p) (hostFmt a b).width) ha (column_width (m + p) hw) + (f := fun x i => x (Match.rowIndex m p i).1) (fun z => ((Match.rowIndex m p z.1).1, z.2)) + (fun _ _ => rfl) + let K := Format.vec m (.vec p (.pair (.addr w) (.addr p))) + have ranks : Cheap F (m + p) t (.vec m (.vec p (.addr w))) K (fun x i + => PackRank.lanes (x i)) 110 := by + obtain ⟨l, hl, hb⟩ := (PackRank.cheap_lanes F p w).widen (show p + w ≤ t by omega) + refine ⟨_, Circuit.map (A := .vec p (.addr w)) (D + := .vec p (.pair (.addr w) (.addr p))) (fun _ : B m => PackRank.lanes) (fun _ => hl), ?_⟩ + simpa only [K, Format.width_vec, ← mul_add, pow_add, mul_assoc] + using Nat.mul_le_mul_left (2 ^ m) hb + have hK : K.width ≤ 2 ^ (m + p) * (100 + t) ^ 1 := by + simp only [K, Format.width_vec, Format.width_pair, Format.width_addr, ← mul_assoc, ← pow_add, + pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have lane := Cheap.project F (A := K) (D := Column (m + p) p) hK (column_width (m + p) (show p + ≤ t by omega)) + (f := fun x i => (x (Match.rowIndex m p i).1 (Match.rowIndex m p i).2).2) + (fun z => ((Match.rowIndex m p z.1).1, (Match.rowIndex m p z.1).2, .inr z.2)) (fun _ _ => rfl) + exact ((host.comp spread).pair ((x.snd.comp ranks).comp lane)).zip.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/FreezeInput/Cost.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/FreezeInput/Cost.lean new file mode 100644 index 0000000000..d867f7850f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/FreezeInput/Cost.lean @@ -0,0 +1,264 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Pass +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.FreezeInput.Retain +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels + +/-! # Withdrawing arity-zero factors from a concentrated term -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Packing Rounds + +variable {F : Type} [Field F] {x y : Wire} {h u : ℕ} + +/-- The sweep of type `LocalTerm F x y h u` for the given inputs. -/ +abbrev Rounds.LocalTerm.sweep (Q : LocalTerm F x y h u) : LocalTerm F x y h u := + { Q with diagram := Q.diagram.sweep + freeze := ⟨Q.freeze.frozen, Q.freeze.exterior, Q.freeze.separate⟩ + frame := ⟨Q.frame.place, Q.frame.frozen, Q.frame.keep, Q.frame.N, Q.frame.C, Q.frame.ns, + Q.frame.cs, Q.frame.sub, Q.frame.group, Q.frame.edge, Q.frame.full⟩ } + +namespace Assembly.Template.Shows +variable {D : Template F} {r : D.format.obj} {Q : LocalTerm F x y D.scheme.h u} (p : D.Shows r Q) + +/-- Builds `D.sweep.Shows r Q.sweep where pres` with the specified `pres`, `host`, `vertex`, +`directed`. -/ +def sweep : D.sweep.Shows r Q.sweep where + pres := p.pres.sweep + host := p.host + vertex := p.vertex + directed t := by + change D.scheme.direction r.1 (p.pres.sweepSeats.ends t).1 = _ + rw [p.pres.sweep_end]; exact p.directed t + uniform t := by + change D.scheme.width r.1 (p.pres.sweepSeats.ends (.inl (.inr t))).1 = _ + rw [p.pres.sweep_end]; exact p.uniform t + index := p.index + neighbor := p.neighbor + live := p.live + frozen := p.frozen + closed := p.closed + reciprocal := p.reciprocal + edge := p.edge + core := p.core + charge := p.charge + amount := p.amount + +end Assembly.Template.Shows + +namespace Rounds.Contraction.Publication +variable {D : Template F} {s : Plan} {T z payload : ℕ} {L : ℝ} + (X : Publication (x := x) (y := y) D s T L z payload) + +/-- The sweep of type `Publication (x := x) (y := y) D.sweep s T L z payload where R` for the +given inputs. -/ +def sweep : Publication (x := x) (y := y) D.sweep s T L z payload where + R := X.R + g := X.g + P := X.P + Q := X.Q.sweep + ready := ⟨X.ready.cells, X.ready.coreDegree, X.ready.fullDegree, X.ready.frozenCount, + X.ready.frozenMax, X.ready.frozenSquare, X.ready.coreMax, X.ready.coreSum⟩ + live := X.live + r := X.r + showing := X.showing.sweep + fits := X.fits + +/-- The condition `∀ v, X.Q.diagram.arity v = 0 → ∀ t, Transcript.sample (X.Q.diagram.table v) t += 1` on the specified data. -/ +def Neutral : Prop := + ∀ v, X.Q.diagram.arity v = 0 → ∀ t, Transcript.sample (X.Q.diagram.table v) t = 1 + +theorem neutral : X.sweep.Neutral := X.Q.diagram.sweep_neutral + +end Rounds.Contraction.Publication +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- # Admission of a neutralized concentrated diagram -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Publication +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} {s : Plan} {T z payload : ℕ} {L : ℝ} + (X : Publication (x := x) (y := y) D s T L z payload) (h : D.scheme.k = 0) + (hs : s.Fits) (hz : 0 < s.b * z) (hL : 1 ≤ L) (hT : 0 < T) + +local notation "u" => s.b * z +local notation "A" => D.border u (1 / (s.D : ℝ) ^ 4) +local notation "Z" => frozen hs L X.Q + +/-- Computes the packet by the application `X.showing.encloses h hz Z rfl rfl`. -/ +abbrev packet := X.showing.encloses h hz Z rfl rfl + +/-- Computes the entry by the application `incoming hs L X.Q hz X.showing.packets (X.packet h hs +hz)`. -/ +abbrev entry : Attachment.Data (A) x y u := + incoming hs L X.Q hz X.showing.packets (X.packet h hs hz) + +include hL hT in +theorem ready_entry (hn : X.Neutral) : + Ready (A) (fringe s T L) z s.c (s.D ^ s.c) (origin s T L) (X.entry h hs hz) := by + refine incoming_ready hs (X.packet h hs hz) X.ready hL hT X.live (fun i => hn i.val) ?_ ?_ + · intro j + exact (X.showing.span hz Z rfl rfl j).ge + · intro i + exact ⟨_, (X.showing.charge i.val).trans (Nat.cast_add ..).symm⟩ + +theorem fit_entry : (X.entry h hs hz).Fits payload := (X.showing.retag h Z).fits X.fits + +theorem eval_entry : (X.entry h hs hz).diagram.eval = X.Q.diagram.eval := + funext fun i => funext fun j => X.Q.freeze.reconstruct i j + +theorem store_entry (i : Val x) (j : Val y) : + (X.entry h hs hz).data (X.fit_entry h hs hz) i j + = D.scheme.store X.r.1 X.fits (X.showing.pres.exterior i j) := + eq_of_heq ((X.showing.retag h Z).store X.fits i j) + +/-- Uses `⟨X.sweep.entry h hs hz, X.sweep.ready_entry h hs hz hL hT X.neutral, X.sweep.fit_entry +h hs hz⟩` as the representation. -/ +def out : (initial (x := x) (y := y) (border D s z) s T L z payload).state := + ⟨X.sweep.entry h hs hz, X.sweep.ready_entry h hs hz hL hT X.neutral, X.sweep.fit_entry h hs hz⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Publication +end + +/- # Converting concentrated terms into attached cores -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Coloring Packing + +variable {F : Type} [Field F] {x y : Wire} (D : Template F) (s : Plan) (z payload : ℕ) + +open scoped Classical in +/-- The value specified by `weightTable (A := .addr D.scheme.ℓ) (D := .addr D.scheme.ℓ) id +D.scheme.scalar`. -/ +abbrev admitLabel := weightTable (A := .addr D.scheme.ℓ) (D := .addr D.scheme.ℓ) id D.scheme.scalar + +open scoped Classical in +theorem admitLabel_arity : Processor.arity (admitLabel D) = 2 * D.scheme.ℓ := by + simp only [admitLabel, weightTable, Processor.arity, lookup, wd_word, Format.width_addr, two_mul] + +open scoped Classical in +/-- The admit cost of type `ℕ`, constructed using `(Attachment.payload x y payload +D.scheme.m).width`. -/ +def admitCost (x y : Wire) : ℕ := + let width := (Attachment.payload x y payload D.scheme.m).width + updateCost D.scheme.m D.scheme.d D.scheme.h (.addr D.scheme.ℓ) (.addr D.scheme.ℓ) + + 4 * (Format.vec D.scheme.m D.header).width + 4 * width + + (D.sweep.encloseCost (s.b * z) (1 / (s.D : ℝ) ^ 4) + 4 * width) + +variable {D s z payload} {L : ℝ} {T : ℕ} +local notation "E" => publicEncoding (x := x) (y := y) D s T L z payload +local notation "A" => border D s z + +open scoped Classical in +theorem admit_transfer (hs : s.Fits) (hz : 0 < s.b * z) (hL : 1 ≤ L) (hT : 0 < T) + (h : D.scheme.k = 0) : Transforms F (3 + 2 * D.scheme.ℓ) {admitLabel D} + (publication (x := x) (y := y) D s T L z payload) (initial A s T L z payload) + (admitCost D s z payload x y) := by + let u := 3 + 2 * D.scheme.ℓ + let G : Set (Table F) := {admitLabel D} + have hu : 3 ≤ u := Nat.le_add_right .. + have hE := (E).sweep_stage (L := G) hu (Nat.le_add_left ..) (Set.mem_singleton _) + let f := D.sweep.enclose (s.b * z) (1 / (s.D : ℝ) ^ 4) + have build := D.sweep.enclose_net (s.b * z) (1 / (s.D : ℝ) ^ 4) (L := G) hu + have keep := Map.circuit (L := G) hu (Circuit.id F (E).payload) + have net := build.par keep + let out := fun i : Publication (x := x) (y := y) D s T L z payload => i.out h hs hz hL hT + have after := Transforms.of_map (X := (E).sweep.snapshot) (Y := initial A s T L z payload) + (Prod.map f id) out net + (fun i => (Publication.eval_entry (Publication.sweep i) h hs hz).symm) + (fun i a b => Prod.ext rfl (Publication.store_entry (Publication.sweep i) h hs hz a b).symm) + exact hE.comp after + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Host, cell, and exterior-bit charges of the input stage -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Coloring + +private theorem budget14 {n : ℕ} (hn : 100 ≤ n) : + 4 * n ^ 2 + 24 * n + 24 + n ^ 13 ≤ n ^ 14 := by + have h₁ : n ≤ n ^ 13 := Nat.le_self_pow (by decide) n + have h₂ : n ^ 2 ≤ n ^ 13 := Nat.pow_le_pow_right (by omega) (by decide) + calc + _ ≤ n ^ 13 * 100 := by omega + _ ≤ n ^ 13 * n := Nat.mul_le_mul_left _ hn + _ = _ := (pow_succ ..).symm + +variable {F : Type} [Field F] (D : Template F) (s : Plan) (z payload : ℕ) (x y : Wire) +local notation "m" => D.scheme.m +local notation "h" => D.scheme.h +local notation "p" => (2 ^ D.scheme.d) +local notation "ℓ" => D.scheme.ℓ + +theorem admit_cost : + let short := 10000 + p + ℓ + D.count + payload + admitCost D s z payload x y ≤ 2 ^ m * (short + m) ^ 14 + 2 ^ (m + h) * short ^ 14 + + (wd x + wd y) * (100 + payload) ^ 14 := by + intro short + let t := short + m + have hshort : 10000 + p + ℓ + D.count ≤ short := Nat.le_add_right .. + have hp : p ≤ short := by unfold short; omega + have hmin : 10000 ≤ short := by unfold short; generalize p = n; omega + have hlong : short ≤ t := Nat.le_add_right .. + have hw : payload ≤ short := Nat.le_add_left .. + have hm : m ≤ t := Nat.le_add_left .. + have hcost : D.sweep.encloseCost (s.b * z) (1 / (s.D : ℝ) ^ 4) ≤ 2 ^ m * t ^ 13 + 2 ^ (m + + h) * short ^ 2 := + D.sweep.enclose_bound _ _ hshort + have hh : (Format.vec D.scheme.m D.header).width = 2 ^ m * (2 + p * 2 + 2 ^ h * D.count) := by + simp only [Template.header, Group.Flags, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit] + ring + have hwidth : (Attachment.payload x y payload m).width ≤ (payload + 1) * (2 * (2 ^ m + wd x + + wd y)) := + Fmt.width_payload .. + have main : 4 * (p * m) + 8 * p + 16 * payload + 24 + t ^ 13 ≤ t ^ 14 := by + have hu : p * m ≤ t ^ 2 := (Nat.mul_le_mul (hp.trans hlong) hm).trans_eq (pow_two t).symm + have hb := budget14 (show 100 ≤ t by omega) + omega + have cell : 1 + 2 * ℓ + 4 * D.count + short ^ 2 ≤ short ^ 14 := by + have hb := budget14 (show 100 ≤ short by omega) + generalize p = n at hshort + omega + have bit : 16 * (payload + 1) ≤ (100 + payload) ^ 14 := by + have hb := budget14 (show 100 ≤ 100 + payload by omega) + omega + unfold admitCost updateCost + dsimp only + rw [hh, Format.width_addr] + calc + _ ≤ 2 ^ m * (4 * (p * m) + 2 ^ h * (1 + ℓ + ℓ)) + 4 * (2 ^ m * (2 + p * 2 + 2 ^ h * D.count)) + + 4 * ((payload + 1) * (2 * (2 ^ m + wd x + wd y))) + + (2 ^ m * t ^ 13 + 2 ^ (m + h) * short ^ 2 + 4 * ((payload + 1) * (2 * (2 ^ m + wd x + + wd y)))) := by + exact Nat.add_le_add (Nat.add_le_add_left (Nat.mul_le_mul_left _ hwidth) _) + (Nat.add_le_add hcost (Nat.mul_le_mul_left _ hwidth)) + _ = 2 ^ m * (4 * (p * m) + 8 * p + 16 * payload + 24 + t ^ 13) + + 2 ^ (m + h) * (1 + 2 * ℓ + 4 * D.count + short ^ 2) + (wd x + wd y) * (16 * (payload + 1)) + := by + rw [pow_add] + generalize t ^ 13 = T, short ^ 2 = S + ring + _ ≤ _ := Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ main) + (Nat.mul_le_mul_left _ cell)) (Nat.mul_le_mul_left _ bit) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/FreezeInput/Retain.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/FreezeInput/Retain.lean new file mode 100644 index 0000000000..7fef67e60e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/FreezeInput/Retain.lean @@ -0,0 +1,999 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.RetagStore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Parcel + +/-! # Certifying a directed presentation by checking individual bits -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Seating + +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} {a b : Wire} + {G : Diagram F a b} (p : S.Seating r G) + +open scoped Classical in +/-- The defining condition `S.Joins r (p.ends x) (p.ends y) ∧ S.Joins r (p.ends y) (p.ends x) ∧ +S.direction r (p.ends x).1 = x.isRight ∧ S.direction r (p.ends y).1 = y.isRight`. -/ +def Bond (x y : G.End) : Prop := + S.Joins r (p.ends x) (p.ends y) ∧ S.Joins r (p.ends y) (p.ends x) ∧ + S.direction r (p.ends x).1 = x.isRight ∧ S.direction r (p.ends y).1 = y.isRight + +open scoped Classical in +theorem Bond.swap {p} {x y : G.End} (h : Bond (S := S) (r := r) p x y) : p.Bond y x := + ⟨h.2.1, h.1, h.2.2.2, h.2.2.1⟩ + +open scoped Classical in +/-- Requires `S.peer r (p.ends x).1 = none ∧ S.direction r (p.ends x).1 = x.isRight`. -/ +def Free (x : G.End) : Prop := S.peer r (p.ends x).1 = none ∧ S.direction r (p.ends x).1 = x.isRight + +open scoped Classical in +/-- The data for the connected construction, including `used`, `bond`, `input`, `output`. -/ +structure Connected : Prop where + used : ∀ i, S.peer r i ≠ none → 0 < S.width r i + bond : ∀ e, p.Bond (.inl (.inr e)) (.inr (.inr e)) + input : ∀ i, p.Free (.inl (.inl i)) + output : ∀ i, p.Free (.inr (.inl i)) + +namespace Connected +variable {p} (h : p.Connected) +include h + +open scoped Classical in +private theorem other {q : S.Pin r} {j : S.Span} (he : S.peer r q.1 = some j) : + S.peer r j = some q.1 ∧ q.2.val < S.width r j ∧ S.direction r q.1 ≠ S.direction r j := by + obtain ⟨x, rfl⟩ := p.ends.surjective q + have aux {y : G.End} (b : p.Bond x y) (hn : x.isRight ≠ y.isRight) : + S.peer r j = some (p.ends x).1 ∧ (p.ends x).2.val < S.width r j ∧ + S.direction r (p.ends x).1 ≠ S.direction r j := by + rw [b.1.1, Option.some.injEq] at he + subst j + rw [b.1.2, b.2.2.1, b.2.2.2] + exact ⟨b.2.1.1, (p.ends y).2.isLt, hn⟩ + rcases x with (i|e)|(i|e) + · rw [(h.input i).1] at he + cases he + · exact aux (h.bond e) Bool.false_ne_true + · rw [(h.output i).1] at he + cases he + · exact aux (h.bond e).swap Bool.false_ne_true.symm + +open scoped Classical in +private theorem size {i j : S.Span} (he : S.peer r i = some j) : S.width r i ≤ S.width r j := by + by_contra! hn + exact (lt_irrefl _) (h.other (q := ⟨i, ⟨_, hn⟩⟩) he).2.1 + +open scoped Classical in +theorem proper : S.Proper r := by + intro i j he + have hi := h.used i (by rw [he]; simp) + obtain ⟨hj, _, hd⟩ := h.other (q := ⟨i, ⟨0, hi⟩⟩) he + exact ⟨hj, le_antisymm (h.size he) (h.size hj), hd⟩ + +open scoped Classical in +/-- Uses `⟨p, h.proper, fun i => (h.bond i).1, fun i => (h.input i).1, fun i => (h.output i).1⟩` +as the representation. -/ +def presentation : S.Presentation r G := + ⟨p, h.proper, fun i => (h.bond i).1, fun i => (h.input i).1, fun i => (h.output i).1⟩ + +open scoped Classical in +theorem directed : h.presentation.Directed := by + rintro ((i|e)|(i|e)) + · exact (h.input i).2 + · exact (h.bond e).2.2.1 + · exact (h.output i).2 + · exact (h.bond e).2.2.2 + +end Connected +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Seating +end + +section +/- # Comparing the two address lists at one host -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Alias +open Coloring + +/-- The value specified by `.pair (.vec p (.vec d (.addr m))) (.vec d' (.vec p (.addr m)))`. -/ +abbrev Input (m d d' p : ℕ) : Format := + .pair (.vec p (.vec d (.addr m))) (.vec d' (.vec p (.addr m))) + +/-- The value specified by `.vec p (.vec d (.vec d' (.vec p .bit)))`. -/ +abbrev Output (d d' p : ℕ) : Format := + .vec p (.vec d (.vec d' (.vec p .bit))) + +/-- Evaluates `decide (x.1 i j = x.2 y t)` at the input `i j y t`. -/ +def mask {m d d' p : ℕ} (x : (Input m d d' p).obj) : (Output d d' p).obj := + fun i j y t => decide (x.1 i j = x.2 y t) + +theorem mask_circuit (F : Type) [Field F] (m d d' p : ℕ) : + Circuit F (Input m d d' p) (Output d d' p) mask ((100 + m + 2 ^ d + 2 ^ d' + 2 ^ p) ^ 100) := by + let A := Input m d d' p + let D := Format.vec p (.vec d (.vec d' (.vec p (.pair (.addr m) (.addr m))))) + let f : A.obj → D.obj := fun x i j y t => (x.1 i j, x.2 y t) + have wire : Circuit F A D f (A.width + 2 * D.width) := by + apply Circuit.project (A := A) (D := D) (fun (i, j, y, t, b) => + Sum.elim (fun z => Sum.inl (i, j, z)) (fun z => Sum.inr (y, t, z)) b) + rintro x ⟨i, j, y, t, z|z⟩ <;> rfl + have eqs := Circuit.map (h := p) _ (fun _ => + Circuit.map (h := d) _ (fun _ => + Circuit.map (h := d') _ (fun _ => + Circuit.map (h := p) _ (fun _ => numeric_eq F m)))) + refine (wire.comp eqs).mono ?_ + simp only [A, D, Input, Format.width_vec, Format.width_pair, Format.width_addr] + let s := 100 + m + 2 ^ d + 2 ^ d' + 2 ^ p + have h₁ : 0 ≤ 2 ^ d := Nat.zero_le _ + have h₂ : 0 ≤ 2 ^ d' := Nat.zero_le _ + have h₃ : 0 ≤ 2 ^ p := Nat.zero_le _ + have hs : 100 ≤ s := by dsimp [s]; omega + have hm : m ≤ s := by dsimp [s]; omega + have hd : 2 ^ d ≤ s := by dsimp [s]; omega + have hd' : 2 ^ d' ≤ s := by dsimp [s]; omega + have hp : 2 ^ p ≤ s := by dsimp [s]; omega + calc + _ ≤ s * (s * s) + s * (s * s) + 2 * (s * (s * (s * (s * (s + s))))) + s * (s * (s * (s * (2 * s + + s)))) := by + gcongr; omega + _ = 2 * s ^ 3 + 7 * s ^ 5 := by ring + _ ≤ 9 * s ^ 5 := by + have := Nat.pow_le_pow_right (show 0 < s by omega) (show 3 ≤ 5 by decide) + omega + _ ≤ s ^ 6 := by rw [show s ^ 6 = s * s ^ 5 by ring]; gcongr; omega + _ ≤ s ^ 100 := Nat.pow_le_pow_right (by omega) (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Alias +end + +/- # Ordered reads from the short records of neighboring hosts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +open Coloring + +private theorem read_budget (n u v l : ℕ) : + (100 + (n + u + v + l + u * l)) ^ 50 ≤ (100 + n + u + v + l) ^ 100 := by + rw [show 100 = 2 * 50 from rfl, pow_mul] + gcongr + ring_nf + omega + +/-- For each request column, gather the whole neighbor list at the requested block, +then select the requested neighbor. Padding repeats existing rows and is removed +by a fixed projection, so arbitrary repetitions and order are preserved. -/ +theorem local_read (F : Type) [Field F] (n a d p l : ℕ) (ha : a ≤ n) : + Circuit F (.pair (.vec d (.vec n (.addr l))) (.vec a (.vec p (.pair (.addr d) (.addr n))))) + (.vec a (.vec p (.addr l))) (fun x i j => x.1 (x.2 i j).1 (x.2 i j).2) + (2 ^ n * (100 + n + 2 ^ d + 2 ^ p + l) ^ 100) := by + let A := Format.pair (.vec d (.vec n (.addr l))) (.vec a (.vec p (.pair (.addr d) (.addr n)))) + let U := Format.vec d (.addr l) + let k := n + 2 ^ d + 2 ^ p + l + 2 ^ d * l + have := Nat.lt_two_pow_self (n := d) + have := Nat.lt_two_pow_self (n := p) + have hn : n ≤ k := by unfold k; omega + have hd : 2 ^ d ≤ k := by unfold k; omega + have hp : 2 ^ p ≤ k := by unfold k; omega + have hl : l ≤ k := by unfold k; omega + have hdn : d + n ≤ k := by unfold k; omega + have hu : U.width ≤ k := by rw [Format.width_vec, Format.width_addr]; unfold k; omega + have hrows : 2 ^ a ≤ 2 ^ n := Nat.pow_le_pow_right (by decide) ha + let up := Fin.castLEEmb hrows + let down := Function.invFun up + have cancel (i : B a) : down (up i) = i := Function.leftInverse_invFun up.injective i + have hA : A.width ≤ 2 ^ n * (100 + k) ^ 2 := by + simp only [A, Format.width_pair, Format.width_vec, Format.width_addr] + rw [mul_left_comm (2 ^ d)] + calc + _ ≤ 2 ^ n * k + 2 ^ n * (k * k) := by + have h : 2 ^ d * l ≤ k := by unfold k; omega + gcongr + _ ≤ _ := by rw [← mul_add]; gcongr; ring_nf; omega + have hv (V : Format) (hv : V.width ≤ k) : (Format.vec n V).width ≤ 2 ^ n * (100 + k) ^ 2 := by + rw [Format.width_vec] + exact Nat.mul_le_mul_left _ (by nlinarith only [hv]) + have table : Cheap F n k A (.vec n U) (fun x i t => x.1 t i) 3 := + Cheap.project F hA (hv U hu) (fun z => .inl (z.2.1, z.1, z.2.2)) (fun _ _ => rfl) + have each (j : B p) : Cheap F n k A (.vec n (.addr l)) + (fun x i => x.1 (x.2 (down i) j).1 (x.2 (down i) j).2) 13 := by + have block : Cheap F n k A (Perm n) (fun x i => (x.2 (down i) j).2) 3 := + Cheap.project F hA (hv (.addr n) (by simpa)) + (fun z => .inr (down z.1, j, .inr z.2)) (fun _ _ => rfl) + have near : Cheap F n k A (.vec n (.addr d)) (fun x i => (x.2 (down i) j).1) 3 := + Cheap.project F hA (hv (.addr d) (by rw [Format.width_addr]; omega)) + (fun z => .inr (down z.1, j, .inl z.2)) (fun _ _ => rfl) + have records := (table.pair block).comp (Cheap.lookup F n k U hn hu) + have paired := Cheap.pair near records + have zipped := Cheap.zip (D := .addr d) (B := U) paired + have read : Cheap F n k (.vec n (.pair (.addr d) U)) (.vec n (.addr l)) + (fun q i => (q i).2 (q i).1) 12 := + Cheap.map (A := .pair (.addr d) U) (D := .addr l) (fun _ q => q.2 q.1) + (fun _ => Match.read_one F (.addr l) + (by omega) (by simpa only [Format.width_addr]) hd) + have composed := Cheap.comp zipped read + have price : max (max 3 (max (max 3 3 + 1) 8 + 1) + 1 + 1) 12 + 1 = 13 := rfl + rw [price] at composed + simpa only [Function.comp_def] using composed + let Z := Format.vec p (.vec n (.addr l)) + let W := Format.vec a (.vec p (.addr l)) + have hz : Z.width ≤ 2 ^ n * (100 + k) ^ 2 := by + simp only [Z, Format.width_vec, Format.width_addr, pow_two] + rw [mul_left_comm (2 ^ p)] + gcongr <;> omega + have hw : W.width ≤ 2 ^ n * (100 + k) ^ 2 := by + simp only [W, Format.width_vec, Format.width_addr, pow_two] + gcongr <;> omega + have out : Cheap F n k Z W (fun x i j => x j (up i)) 3 := + Cheap.project F hz hw (fun z => (z.2.1, up z.1, z.2.2)) (fun _ _ => rfl) + have ans := (Cheap.share _ each hp).comp out + simp only [Function.comp_def, cancel] at ans + obtain ⟨m, hm, hcost⟩ := ans.mono (d := 50) (by decide) + refine hm.mono ((show m ≤ 2 ^ n * (100 + k) ^ 50 by omega).trans ?_) + exact Nat.mul_le_mul_left _ (read_budget n (2 ^ d) (2 ^ p) l) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment +end + +/- # Reattaching the frozen tables in their original port order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Packing + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {r : S.format.obj} + {G : Diagram F x y} (p : S.Presentation r G) (Z : Freeze G) + +local notation "J" => Z.border.attach Z.core + +open scoped Classical in +/-- Reindexes `(J).V` and `G.V` by an equivalence. -/ +def original : (J).V ≃ G.V := + (Equiv.sumComm _ _).trans (Equiv.sumCompl Z.frozen) + +open scoped Classical in +/-- Reindexes `(J).Port i` and `S.LocalPin r (p.vertex (original Z i))` by an equivalence. -/ +def joinedPin (i : (J).V) : (J).Port i ≃ S.LocalPin r (p.vertex (original Z i)) := + match i with + | .inl v => p.pin v.val + | .inr v => p.pin v.val + +open scoped Classical in +/-- Builds `S.Seating r J where vertex` with the specified `vertex`, `pin`, `cover`, `obtain`. -/ +def joinedSeat : S.Seating r J where + vertex := (original Z).toEmbedding.trans p.vertex + pin := p.joinedPin Z + cover i := by + obtain ⟨v, hv⟩ := p.cover i + obtain ⟨u, rfl⟩ := (original Z).surjective v + exact ⟨u, hv⟩ + sample v t := by rcases v with v|v <;> exact p.sample v.val t + vacant v hv t := p.vacant v (by + rintro ⟨i, rfl⟩ + obtain ⟨u, rfl⟩ := (original Z).surjective i + exact hv ⟨u, rfl⟩) t + +open scoped Classical in +/-- Reindexes `(J).End` and `G.End` by an equivalence. -/ +def joinedEnd : (J).End ≃ G.End := + ((Equiv.refl _).sumCongr Z.edges).sumCongr ((Equiv.refl _).sumCongr Z.edges) + +open scoped Classical in +theorem joined_at (i : (J).End) : + (p.joinedSeat Z).ends i = p.toSeating.ends (joinedEnd Z i) := by + rcases i with (_|_|_|_)|(_|_|_|_) <;> rfl + +open scoped Classical in +/-- Builds `S.Presentation r J where toSeating` with the specified `toSeating`, `proper`, +`input`, `output`. -/ +def joined : S.Presentation r J where + toSeating := p.joinedSeat Z + proper := p.proper + input i := by rw [joined_at]; exact p.input i + output i := by rw [joined_at]; exact p.output i + internal i := by rw [joined_at, joined_at]; exact p.internal (Z.edges i) + +open scoped Classical in +theorem joined_directed (hd : p.Directed) : (p.joined Z).Directed := by + intro i + change S.direction r ((p.joinedSeat Z).ends i).1 = _ + rw [joined_at, hd] + cases i <;> rfl + +open scoped Classical in +theorem joined_boundary (i : slots x ⊕ slots y) : + (p.joined Z).boundary i = p.boundary i := by + apply Subtype.ext + cases i <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +section +/- +# Reading neighboring rows and comparing old host addresses + +The comparison bits are computed once per host and reused in every row. +The width of an address therefore contributes independently of the row count. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Inspect +open Coloring + +/-- The value specified by `.pair (.vec p (.addr m)) (.pair (.vec p (.vec d (.addr m))) (.vec a +A))`. -/ +abbrev Packet (m d p a : ℕ) (A : Format) : Format := + .pair (.vec p (.addr m)) (.pair (.vec p (.vec d (.addr m))) (.vec a A)) + +/-- Computes the input by the application `Fmt.bank m' d' (Packet m d p a A)`. -/ +abbrev Input (m d m' d' p a : ℕ) (A : Format) := + Fmt.bank m' d' (Packet m d p a A) + +/-- The value specified by `.pair (Alias.Output d d' p) (.pair A (.vec d' A))`. -/ +abbrev Row (d d' p : ℕ) (A : Format) : Format := + .pair (Alias.Output d d' p) (.pair A (.vec d' A)) + +/-- The value specified by `.vec m' (.vec a (Row d d' p A))`. -/ +abbrev Output (d m' d' p a : ℕ) (A : Format) : Format := + .vec m' (.vec a (Row d d' p A)) + +/-- The cost used in the `Inspect` construction. -/ +def cost (m d m' d' p a : ℕ) (A : Format) (v N : ℕ) := + gatherCost m' d' v N + + 56 * (Input m d m' d' p a A).width + + 32 * (Format.vec m' (.vec d' (Packet m d p a A))).width + + 8 * (Format.vec m' (Alias.Input m d d' p)).width + + 4 * (Format.vec m' (Alias.Output d d' p)).width + + 8 * (Output d m' d' p a A).width + + 4 * (2 ^ m' * (100 + m + 2 ^ d + 2 ^ d' + 2 ^ p) ^ 100) + +variable {F : Type} [Field F] {u v N m d m' d' p a : ℕ} + {A : Format} {L : Set (Table F)} {I : Type*} + +/-- The indexed operation `fun i j => (Alias.mask ((x i).2.2.1, fun t => (x ((x i).1 t)).2.1), +(x i).2.2.2 j, fun t => (x ((x i).1 t)).2.2.2 j)`. -/ +def view (x : (Input m d m' d' p a A).obj) : (Output d m' d' p a A).obj := + fun i j => + (Alias.mask ((x i).2.2.1, fun t => (x ((x i).1 t)).2.1), + (x i).2.2.2 j, fun t => (x ((x i).1 t)).2.2.2 j) + +theorem run (hu : 3 ≤ u) (ht : Access F u L (m' + d') v N) + (hc : (Packet m d p a A).width ≤ v) (X : I → (Input m d m' d' p a A).obj) + (hx : ∀ i, Fmt.Reciprocal (Packet m d p a A) (X i)) : + Computes F u L (Input m d m' d' p a A) (Output d m' d' p a A) + X (fun i => view (X i)) (fun _ => 1) (cost m d m' d' p a A v N) := by + let T := Input m d m' d' p a A + let R := Format.vec m' (.vec d' (Packet m d p a A)) + let U := Format.vec m' (Alias.Input m d d' p) + let V := Format.vec m' (Alias.Output d d' p) + let W := Format.pair T R + let Y := Format.pair V W + let Z := Output d m' d' p a A + let select : W.obj → U.obj := fun x i => ((x.1 i).2.2.1, fun t => (x.2 i t).1) + have pre : Circuit F W U select (W.width + 2 * U.width) := by + apply Circuit.project (A := W) (D := U) (fun (i, b) => + Sum.elim (fun y => .inl (i, .inr (.inr (.inl y)))) + (fun t => .inr (i, t.1, .inl t.2)) b) + rintro x ⟨i, b|b⟩ <;> rfl + have cmp := pre.comp (Circuit.map (h := m') _ (fun _ => Alias.mask_circuit F m d d' p)) + let arrange : Y.obj → Z.obj := fun x i j => + (x.1 i, (x.2.1 i).2.2.2 j, fun t => (x.2.2 i t).2.2 j) + have post : Circuit F Y Z arrange (Y.width + 2 * Z.width) := by + apply Circuit.project (A := Y) (D := Z) (fun (i, j, b) => + Sum.elim (fun y => .inl (i, y)) (Sum.elim + (fun y => .inr (.inl (i, .inr (.inr (.inr (j, y)))))) + (fun t => .inr (.inr (i, t.1, .inr (.inr (j, t.2)))))) b) + rintro x ⟨i, j, b|b|b⟩ <;> rfl + have read := (cmp.pair (Circuit.id F W)).comp post + have keep := Computes.of_map (L := L) (x := X) (Map.circuit hu (Circuit.id F T)) (fun _ => rfl) + have both := keep.pair hu (gather_neighbors (Packet m d p a A) hu ht hc X hx) + have h := both.comp (Computes.of_map (Map.circuit hu read) + (y := fun i => view (X i)) (fun _ => rfl)) + simp only [one_mul] at h + refine h.mono ?_ + unfold cost + simp only [W, Y, Format.width_pair, T, R, U, V, Z] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Inspect +end + +/- +# Keeping a full presentation beside a frozen core + +The status mask sends mobile vertices to lane zero and frozen +vertices to lane one. The bit order within each span is unchanged. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] + +namespace Pattern +variable {d k e : ℕ} (P : Pattern F d k e) (mobile : Bool) (peerMobile : B d → Bool) + +open scoped Classical in +/-- Returns `0` when `mobile` holds, and `1` otherwise. -/ +def lane (mobile : Bool) : B 1 := if mobile then 0 else 1 + +open scoped Classical in +/-- Builds `Pattern F d 1 e where width j s` with the specified `width`, `direction`, `peer`, +`then`. -/ +def reseat : Pattern F d 1 e where + width j s := if j = lane mobile then P.width 0 s else 0 + direction _ s := P.direction 0 s + peer j s := if j = lane mobile + then (P.peer 0 s).map (fun a => (a.1, lane (peerMobile a.1), a.2.2)) else none + value j z := if h : j = lane mobile + then P.value 0 (fun s i => z s (i.cast (ite_eq_left h).symm)) else 1 + +end Pattern + +namespace Template +variable (D : Template F) (u : ℕ) (scale : ℝ) + +open scoped Classical in +/-- Computes the border code by the application `Format.pair (.addr D.scheme.cutCode.width) +(.addr D.count)`. -/ +abbrev borderCode := Format.pair (.addr D.scheme.cutCode.width) (.addr D.count) + +open scoped Classical in +/-- Builds `Attachment (D.cut u scale) where k` with the specified `decode`, `let`, `live`, +`let`. -/ +abbrev border : Attachment (D.cut u scale) where + k := 1 + e := D.scheme.e + ℓ := D.borderCode.width + decode i := + let k := D.scheme.cutCode.serial.symm (D.borderCode.serial.symm i).1 + (D.scheme.decode k.1).reseat k.2.1 k.2.2 + live i j := + let c := D.borderCode.serial.symm i + decide (0 < D.load c.2 ∧ j = Pattern.lane (D.scheme.cutCode.serial.symm c.1).2.1) + charge i _ := D.load (D.borderCode.serial.symm i).2 + coreSpan := Function.Embedding.refl _ + +open scoped Classical in +/-- The indexed operation `(D.remove u scale r, fun v i => D.borderCode.serial ((((D.remove u +scale r).1 v).2 i), D.counter r v i))`. -/ +def enclose (r : D.format.obj) : (D.border u scale).format.obj := + (D.remove u scale r, fun v i => D.borderCode.serial ((((D.remove u scale r).1 v).2 i), + D.counter r v i)) + +open scoped Classical in +theorem border_length : (D.border u scale).ℓ = D.scheme.ℓ + 1 + 2 ^ D.scheme.d + D.count := by + change D.borderCode.width = _ + rw [borderCode, Format.width_pair, Format.width_addr, Format.width_addr] + exact congrArg (·+D.count) D.scheme.cut_length + +end Template +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Widths, peers and table values under the two-lane placement -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.FreezeInput +open Coloring +variable {F : Type} [Field F] (D : Template F) (u : ℕ) (scale : ℝ) (r : D.format.obj) +local notation "S" => D.scheme +local notation "A" => D.border u scale +local notation "U" => Attachment.scheme (D.border u scale) +local notation "out" => Attachment.rows (D.border u scale) (D.enclose u scale r) + +open scoped Classical in +/-- The value specified by `(v.1, v.2.1, Pattern.lane (D.mobile r v.1))`. -/ +def dest (v : (S).Vtx) : (U).Vtx := (v.1, v.2.1, Pattern.lane (D.mobile r v.1)) +open scoped Classical in +/-- The value specified by `(dest D u scale r t.1, t.2)`. -/ +abbrev newSpan (t : (S).Span) : (U).Span := (dest D u scale r t.1, t.2) +open scoped Classical in +/-- The value specified by `(v.1, v.2.1, 0)`. -/ +def src (v : (U).Vtx) : (S).Vtx := (v.1, v.2.1, 0) + +open scoped Classical in +theorem pattern (v : (U).Vtx) : + (U).pattern out v = ((S).pattern r.1 (src D u scale v)).reseat (D.mobile r v.1) (D.mobile r ∘ + D.nav r v.1) := by + simp only [Scheme.pattern, Attachment.rows, Attachment.scheme, border, enclose, remove, + Scheme.remove, + Equiv.symm_apply_apply, src, nav] + +open scoped Classical in +theorem width (v : (U).Vtx) (i : B D.scheme.e) : + (U).width out (v, i) = if v.2.2 = Pattern.lane (D.mobile r v.1) then (S).width r.1 (src D u + scale v, i) else 0 := by + rw [Scheme.width, pattern] + rfl + +open scoped Classical in +theorem peer (v : (U).Vtx) (i : B D.scheme.e) : + (U).peer out (v, i) = if v.2.2 = Pattern.lane (D.mobile r v.1) + then ((S).peer r.1 (src D u scale v, i)).map (newSpan D u scale r) else none := by + rw [Scheme.peer, pattern] + unfold Pattern.reseat + dsimp only + split + · simp only [Scheme.peer, Option.map_map] + rfl + · rfl + +open scoped Classical in +theorem untouched (v : (U).Vtx) (h : v.2.2 ≠ Pattern.lane (D.mobile r v.1)) + (t : (U).LocalPin out v → Bool) : (U).table out v t = 1 := by + have aux (q : Pattern F D.scheme.d 1 D.scheme.e) + (he : q = ((S).pattern r.1 (src D u scale v)).reseat (D.mobile r v.1) (D.mobile r ∘ D.nav r + v.1)) + (x : ∀ j, Fin (q.width v.2.2 j) → Bool) : q.value v.2.2 x = 1 := by + subst q; exact dite_eq_right h + exact aux _ (pattern D u scale r v) _ + +variable (h : D.scheme.k = 0) + +include h in +omit [Field F] in +open scoped Classical in +theorem slot (v : (S).Vtx) : v.2.2 = 0 := by + apply Fin.ext + have hv := v.2.2.isLt + simp only [h, pow_zero, Fin.val_zero] at * + omega + +include h in +open scoped Classical in +theorem src_dest (v : (S).Vtx) : src D u scale (dest D u scale r v) = v := + Prod.ext rfl (Prod.ext rfl (slot D h v).symm) + +open scoped Classical in +theorem dest_src (v : (U).Vtx) (hv : v.2.2 = Pattern.lane (D.mobile r v.1)) : + dest D u scale r (src D u scale v) = v := Prod.ext rfl (Prod.ext rfl hv.symm) + +include h in +open scoped Classical in +theorem width_at (t : (S).Span) : (U).width out (newSpan D u scale r t) = (S).width r.1 t := by + rw [newSpan, width, src_dest _ _ _ _ h] + simp only [dest, ite_true] + +include h in +open scoped Classical in +theorem peer_at (t : (S).Span) : + (U).peer out (newSpan D u scale r t) = ((S).peer r.1 t).map (newSpan D u scale r) := by + rw [newSpan, peer, src_dest _ _ _ _ h] + simp only [dest, ite_true] + +include h in +open scoped Classical in +theorem direction_at (t : (S).Span) : + (U).direction out (newSpan D u scale r t) = (S).direction r.1 t := by + rw [Scheme.direction, pattern] + change ((S).pattern r.1 t.1).direction 0 t.2 = _ + rw [Scheme.direction, slot D h t.1] + +open scoped Classical in +/-- The equivalence obtained by `Equiv.sigmaCongrRight fun j => finCongr (width_at D u scale r h +(v, j)).symm`. -/ +def pin (v : (S).Vtx) : (S).LocalPin r.1 v ≃ (U).LocalPin out (dest D u scale r v) := + Equiv.sigmaCongrRight fun j => finCongr (width_at D u scale r h (v, j)).symm + +open scoped Classical in +private theorem preserved {d k e : ℕ} (P : Pattern F d k e) (q : Pattern F d 1 e) + (j : B k) (hj : j = 0) (b : Bool) (f : B d → Bool) (he : q = P.reseat b f) + (hw : ∀ i, P.width j i = q.width (Pattern.lane b) i) + (z : ∀ i, Fin (q.width (Pattern.lane b) i) → Bool) : + q.value (Pattern.lane b) z = P.value j (fun i t => z i (t.cast (hw i))) := by + subst q; subst j + exact dite_eq_left rfl + +open scoped Classical in +theorem table_at (v : (S).Vtx) (t : (U).LocalPin out (dest D u scale r v) → Bool) : + (U).table out (dest D u scale r v) t = (S).table r.1 v (t ∘ pin D u scale r h v) := + preserved _ _ _ (slot D h v) _ _ (pattern D u scale r (dest D u scale r v)) + (fun i => (width_at D u scale r h (v, i)).symm) (fun j k => t ⟨j, k⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.FreezeInput +end + +/- +# Computing both records at the input to a frozen round + +Ask for the cut on the first copy and carry the status bits and +original labels on the second. Serializing a short label only +reindexes its positions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring +variable {F : Type} [Field F] (D : Template F) + +open scoped Classical in +private theorem serial_bits (A : Format) : + ∃ e : (Format.addr A.width).pins → A.pins, + ∀ x i, (Format.addr A.width).code (A.serial x) i = A.code x (e i) := by + refine ⟨@Fintype.equivOfCardEq _ _ (slotsFintype _) A.finite + ((card_slots _).trans (wd_word _)), fun x i => ?_⟩ + rw [Format.serial, Equiv.trans_apply, Equiv.apply_symm_apply] + rfl + +open scoped Classical in +private abbrev RequestCut := D.scheme.cutInput.pair D.format +open scoped Classical in +private abbrev CutReply := D.scheme.cut.format.pair D.format + +open scoped Classical in +private def requestCut (s : D.format.obj) : D.RequestCut.obj := ((s.1, D.mobile s), s) + +open scoped Classical in +private theorem ask_cut : + Circuit F D.format D.RequestCut D.requestCut (D.format.width + 34 * D.RequestCut.width) := by + have h : Install.Depends (D.RequestCut.code ∘ D.requestCut ∘ D.format.code.symm) 1 := by + have pin (i : D.RequestCut.pins) (j : D.format.pins) (f : Bool → Bool) + (he : ∀ t, D.RequestCut.code (D.requestCut t) i = f (D.format.code t j)) : + ∃ s : Finset D.format.pins, s.card ≤ 1 ∧ ∀ x y, (∀ l ∈ s, x l = y l) → + (D.RequestCut.code ∘ D.requestCut ∘ D.format.code.symm) x i = + (D.RequestCut.code ∘ D.requestCut ∘ D.format.code.symm) y i := by + refine ⟨{j}, by simp, fun x y h => ?_⟩ + simp only [Function.comp_apply, he, Equiv.apply_symm_apply, h j (by simp)] + rintro ((i|⟨v, b⟩)|i) + · exact pin _ (.inl i) id (fun _ => rfl) + · exact pin _ (.inr (v, .inl (.inr b))) Bool.not (fun _ => rfl) + · exact pin _ i id (fun _ => rfl) + exact h.bnet F + +variable (u : ℕ) (scale : ℝ) + +open scoped Classical in +private def emitCut (s : D.CutReply.obj) : (D.border u scale).format.obj := + ((s.1, fun v => ((s.2.2 v).1, D.flags s.2 v, fun j => + D.cutCounter.serial (D.frozen s.2 v, D.counter s.2 v j))), + fun v j => D.borderCode.serial ((s.1 v).2 j, D.counter s.2 v j)) + +open scoped Classical in +private theorem emit_cut : + Circuit F D.CutReply (D.border u scale).format (D.emitCut u scale) + (D.CutReply.width + 2 * (D.border u scale).format.width) := by + obtain ⟨k, hk⟩ := serial_bits D.cutCounter + obtain ⟨l, hl⟩ := serial_bits D.borderCode + let counter (v : B D.scheme.m) (j : B D.scheme.h) : D.cutCounter.pins → D.CutReply.pins + | .inl b => .inr (.inr (v, .inl (.inr b))) + | .inr b => .inr (.inr (v, .inr (.inr (j, b)))) + let border (v : B D.scheme.m) (j : B D.scheme.h) : D.borderCode.pins → D.CutReply.pins + | .inl b => .inl (v, .inr (j, b)) + | .inr b => .inr (.inr (v, .inr (.inr (j, b)))) + let pin : (D.border u scale).format.pins → D.CutReply.pins + | .inl (.inl i) => .inl i + | .inl (.inr (v, .inl i)) => .inr (.inr (v, .inl i)) + | .inl (.inr (v, .inr (.inl i))) => .inr (.inr (v, .inr (.inl i))) + | .inl (.inr (v, .inr (.inr (j, i)))) => counter v j (k i) + | .inr (v, j, i) => border v j (l i) + refine Circuit.project pin ?_ + rintro s ((i | ⟨v, i|i|⟨j, i⟩⟩) | ⟨v, j, i⟩) + · rfl + · rfl + · rfl + · refine (hk (D.frozen s.2 v, D.counter s.2 v j) i).trans ?_ + change _ = D.CutReply.code s (counter v j (k i)) + cases k i <;> rfl + · refine (hl ((s.1 v).2 j, D.counter s.2 v j) i).trans ?_ + change _ = D.CutReply.code s (border v j (l i)) + cases l i <;> rfl + +open scoped Classical in +/-- The bound obtained by adding the component charges `D.scheme.cutCost + 200 * (D.format.width ++ D.scheme.cutInput.width + D.scheme.cut.format.width + (D.border u scale).format.width)`. -/ +def encloseCost := D.scheme.cutCost + 200 * (D.format.width + D.scheme.cutInput.width + + D.scheme.cut.format.width + (D.border u scale).format.width) + +open scoped Classical in +theorem enclose_net {w : ℕ} {L : Set (Table F)} (hw : 3 ≤ w) : + Map F w L D.format (D.border u scale).format (D.enclose u scale) (D.encloseCost u scale) := by + have cut := (D.scheme.map_remove (L := L) hw).par (Map.circuit hw (Circuit.id F D.format)) + have network := ((Map.circuit hw D.ask_cut).comp cut).comp (Map.circuit hw (D.emit_cut u scale)) + refine network.mono ?_ + unfold encloseCost RequestCut CutReply + rw [Format.width_pair D.scheme.cutInput D.format, Format.width_pair D.scheme.cut.format D.format] + omega + +local notation "m" => D.scheme.m +local notation "p" => (2 ^ D.scheme.d) +local notation "ℓ" => D.scheme.ℓ +local notation "h" => D.scheme.h + +open scoped Classical in +private theorem enclose_price : + D.encloseCost u scale = + 2 ^ m * (848 * (p * m) + 800 * p + 1040 + 12 * (100 + (m + p)) ^ 12) + + 2 ^ (m + h) * (1048 * ℓ + 600 * D.count + 608 * p + 808) := by + have hc : (D.cut u scale).count = 1 + D.count := by + change D.cutCounter.width = _ + rw [cutCounter, Format.width_pair, Format.width_bit, Format.width_addr] + have hi : D.scheme.cutInput.width = 2 ^ m * (p * m + 2 ^ h * ℓ) + 2 ^ m := by + rw [Scheme.cutInput, Format.width_pair, Scheme.format, Fmt.width_rows, Format.width_addr, + Format.width_vec, Format.width_bit, mul_one] + have hr : D.scheme.cut.format.width = 2 ^ m * (p * m + 2 ^ h * (ℓ + 1 + p)) := by + rw [Scheme.format, Fmt.width_rows, Format.width_addr, Scheme.cut_length] + have ho : (D.border u scale).format.width = + 2 ^ m * (p * (m + 2) + 2 + 2 ^ h * ((ℓ + 1 + p) + (1 + D.count))) + 2 ^ m * (2 ^ h * (ℓ + 1 + + p + D.count)) := by + rw [Attachment.width, border_length, Template.width, hc] + change 2 ^ m * (p * (m + 2) + 2 + 2 ^ h * (D.scheme.cut.ℓ + (1 + D.count))) + _ = _ + rw [Scheme.cut_length] + rw [encloseCost, Scheme.cutCost, hi, hr, ho, D.width, pow_add] + generalize (100 + (m + p)) ^ 12 = w + ring + +open scoped Classical in +/-- The charge repeated in every cell is independent of the host address. -/ +theorem enclose_bound {s : ℕ} (hs : 10000 + p + ℓ + D.count ≤ s) : + D.encloseCost u scale ≤ 2 ^ m * (s + m) ^ 13 + 2 ^ (m + h) * s ^ 2 := by + rw [enclose_price] + generalize p = n at * + have hs' : 10000 ≤ s := by omega + let t := s + m + have hn : n ≤ t := by unfold t; omega + have hm : m ≤ t := Nat.le_add_left .. + have ht : 10000 ≤ t := hs'.trans (Nat.le_add_right ..) + have hpow : (100 + (m + n)) ^ 12 ≤ t ^ 12 := Nat.pow_le_pow_left (by unfold t; omega) _ + have hprod : n * m ≤ t ^ 12 := by + refine (Nat.mul_le_mul hn hm).trans ?_ + rw [← pow_two] + exact Nat.pow_le_pow_right (by omega) (by decide) + have ht' : t ≤ t ^ 12 := Nat.le_self_pow (by decide) t + have h₁ : 848 * (n * m) + 800 * n + 1040 + 12 * (100 + (m + n)) ^ 12 ≤ t ^ 13 := calc + _ ≤ t ^ 12 * 3000 := by omega + _ ≤ t ^ 12 * t := Nat.mul_le_mul_left _ (by omega) + _ = _ := (pow_succ ..).symm + have h₂ : 1048 * ℓ + 600 * D.count + 608 * n + 808 ≤ s ^ 2 := calc + _ ≤ s * 4000 := by omega + _ ≤ s * s := Nat.mul_le_mul_left _ (by omega) + _ = _ := (pow_two _).symm + exact Nat.add_le_add (Nat.mul_le_mul_left _ h₁) (Nat.mul_le_mul_left _ h₂) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Presenting the attached diagram on two station lanes -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.FreezeInput +open Coloring +variable {F : Type} [Field F] (D : Template F) (u : ℕ) (scale : ℝ) (r : D.format.obj) +local notation "S" => D.scheme +local notation "A" => D.border u scale +local notation "U" => Attachment.scheme (D.border u scale) +local notation "out" => Attachment.rows (D.border u scale) (D.enclose u scale r) +variable (h : D.scheme.k = 0) {x y : Wire} {G : Diagram F x y} + (p : D.scheme.Presentation r.1 G) + +local notation "toLane" => dest D u scale r +local notation "toSpan" => newSpan D u scale r + +open scoped Classical in +/-- Embeds `(S).Vtx` into `(U).Vtx`. -/ +def position : (S).Vtx ↪ (U).Vtx := + ⟨toLane, (show Function.LeftInverse (src D u scale) toLane from src_dest D u scale r h).injective⟩ + +open scoped Classical in +/-- Builds `(U).Seating out G where vertex` with the specified `vertex`, `pin`, `sample`, +`cover`. -/ +def seat : (U).Seating out G where + vertex := p.vertex.trans (position D u scale r h) + pin i := (p.pin i).trans (pin D u scale r h (p.vertex i)) + sample v t := (table_at D u scale r h _ t).trans (p.sample _ _) + cover := by + rintro ⟨⟨v, j⟩, k⟩ + have hw := k.pos + rw [width] at hw + split at hw + · rename_i hv + obtain ⟨a, ha⟩ := p.cover ⟨(src D u scale v, j), ⟨0, hw⟩⟩ + exact ⟨a, (congrArg toLane ha).trans (dest_src D u scale r v hv)⟩ + · exact (lt_irrefl _ hw).elim + vacant v hv t := by + by_cases e : v.2.2 = Pattern.lane (D.mobile r v.1) + · obtain ⟨w, rfl⟩ : v ∈ Set.range toLane := ⟨_, dest_src _ _ _ _ v e⟩ + apply (table_at D u scale r h w t).trans + exact p.vacant w (fun ⟨i, he⟩ => hv ⟨i, congrArg toLane he⟩) _ + · exact untouched D u scale r v e t + +local notation "q" => seat D u scale r h p + +open scoped Classical in +/-- Uses `⟨toSpan j.1, j.2.cast (width_at D u scale r h j.1).symm⟩` as the representation. -/ +def put (j : (S).Pin r.1) : (U).Pin out := ⟨toSpan j.1, j.2.cast (width_at D u scale r h j.1).symm⟩ + +open scoped Classical in +theorem ends (i : G.End) : (q).ends i = put D u scale r h (p.toSeating.ends i) := by + obtain ⟨⟨v, j⟩, rfl⟩ := G.portEquiv.surjective i + rw [Scheme.Seating.ends_at, Scheme.Seating.ends_at] + rfl + +include h p in +open scoped Classical in +theorem proper : (U).Proper out := by + rintro ⟨v, i⟩ t ht + rw [peer] at ht + split at ht + swap + · contradiction + rename_i he + obtain ⟨k, hk, rfl⟩ := Option.map_eq_some_iff.mp ht + have hv : (v, i) = toSpan (src D u scale v, i) := Prod.ext (dest_src D u scale r v he).symm rfl + obtain ⟨hb, hw, hd⟩ := p.proper _ _ hk + rw [hv, peer_at _ _ _ _ h, hb, Option.map_some, width_at _ _ _ _ h, width_at _ _ _ _ h, + direction_at _ _ _ _ h, direction_at _ _ _ _ h] + exact ⟨rfl, hw, hd⟩ + +open scoped Classical in +/-- Builds `(U).Presentation out G where toSeating` with the specified `toSeating`, `proper`, +`internal`, `rw`. -/ +def present : (U).Presentation out G where + toSeating := q + proper := proper D u scale r h p + internal i := by + rw [ends, ends] + refine ⟨?_, (p.internal i).2⟩ + rw [put, peer_at _ _ _ _ h, (p.internal i).1] + rfl + input i := by rw [ends, put, peer_at _ _ _ _ h, p.input]; rfl + output i := by rw [ends, put, peer_at _ _ _ _ h, p.output]; rfl + +open scoped Classical in +theorem directed (hd : p.Directed) : (present D u scale r h p).Directed := by + intro i + change (U).direction out ((q).ends i).1 = _ + rw [ends, put, direction_at _ _ _ _ h, hd] + +open scoped Classical in +theorem boundary (i : slots x ⊕ slots y) : + ((present D u scale r h p).boundary i).val = put D u scale r h (p.boundary i).val := by + cases i + · exact ends D u scale r h p _ + · exact ends D u scale r h p _ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.FreezeInput +end + +/- +# The two presentations of a concentrated term + +The mobile part retains the order of each unit packet. The full +presentation restores the frozen tables and their tethers. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Shows +open Coloring Packing Rounds + +variable {F : Type} [Field F] {x y : Wire} {u : ℕ} + {D : Template F} {r : D.format.obj} {Q : LocalTerm F x y D.scheme.h u} + (s : D.Shows r Q) (h : D.scheme.k = 0) (hu : 0 + < u) (L : Fringe Q.freeze.x Q.freeze.y Q.freeze.Fixed) + (hL : L.tensor = Q.freeze.border.tensor) (hc : L.charge = fun i => Q.charge i.val) +local notation "G" => Q.frame.hostOf hu L hL s.packets +local notation "A" => D.border u L.scale +local notation "rows" => D.enclose u L.scale r +local notation "old" => Scheme.Presentation.original Q.freeze + +open scoped Classical in +/-- Computes the attached by the application `FreezeInput.present D u L.scale r h (s.pres.joined +Q.freeze)`. -/ +abbrev attached := FreezeInput.present D u L.scale r h (s.pres.joined Q.freeze) + +open scoped Classical in +theorem vertex_at (v : Q.freeze.Core ⊕ Q.freeze.Fixed) : + (s.attached h L).vertex v = FreezeInput.dest D u L.scale r (s.pres.vertex (old v)) := rfl + +open scoped Classical in +theorem mobile_lane (v : Q.freeze.Core) : Pattern.lane (D.mobile r (s.pres.vertex v.val).1) = 0 := + ite_eq_left ((s.kept _).mpr v.property) + +open scoped Classical in +theorem frozen_lane (v : Q.freeze.Fixed) : Pattern.lane (D.mobile r (s.pres.vertex v.val).1) = 1 := + ite_eq_right (fun h => (s.kept _).mp h v.property) + +open scoped Classical in +private theorem active (v : (A).scheme.Vtx) : + (A).live ((rows).2 v.1 v.2.1) v.2.2 = true ↔ + 0 < D.load (D.counter r v.1 v.2.1) ∧ v.2.2 = Pattern.lane (D.mobile r v.1) := by + simp only [border, enclose, remove, Scheme.remove, Equiv.symm_apply_apply, decide_eq_true_eq] + +include hu in +open scoped Classical in +theorem occupied_lane (v : (A).scheme.Vtx) : + (A).live ((rows).2 v.1 v.2.1) v.2.2 = true ↔ v ∈ Set.range (s.attached h L).vertex := by + rw [active, s.occupied hu] + constructor + · rintro ⟨⟨j, hj⟩, he⟩ + obtain ⟨i, rfl⟩ := (old).surjective j + refine ⟨i, ?_⟩ + rw [s.vertex_at, hj] + exact Prod.ext rfl (Prod.ext rfl he.symm) + · rintro ⟨i, rfl⟩ + rw [s.vertex_at] + refine ⟨⟨old i, ?_⟩, rfl⟩ + rw [s.vertex] + rfl + +open scoped Classical in +/-- Builds `(A).Encloses rows G Q.freeze.border where full` with the specified `full`, `tether`, +`core`, `pres`. -/ +def encloses : (A).Encloses rows G Q.freeze.border where + full := rfl + tether := hL + core := s.encode hu L hL hc + pres := s.attached h L + directed := FreezeInput.directed D u L.scale r h (s.pres.joined Q.freeze) + (s.pres.joined_directed Q.freeze s.directed) + occupied := s.occupied_lane h hu L + slot _ := 1 + positive _ := by exact (by decide : (1 : B 1) ≠ 0) + internal v := by + change FreezeInput.dest D u L.scale r (s.pres.vertex v.val) = _ + unfold FreezeInput.dest + rw [s.mobile_lane v, s.vertex] + rfl + frozen v := by + change FreezeInput.dest D u L.scale r (s.pres.vertex v.val) = _ + unfold FreezeInput.dest + rw [s.frozen_lane v, s.vertex] + rfl + charge v := by + have hm := s.weight_at v.val + simp only [border, enclose, Equiv.symm_apply_apply] + exact hm.trans (congrFun hc v).symm + ordered v j := ⟨rfl, rfl⟩ + +open scoped Classical in +theorem attached_boundary (i : slots x ⊕ slots y) : + ((s.attached h L).boundary i).val = + FreezeInput.put D u L.scale r h (s.pres.boundary i).val := by + rw [attached, FreezeInput.boundary, s.pres.joined_boundary] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Shows +end + +/- # The retained exterior payload needs no further permutation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Shows +open Coloring Packing Rounds + +variable {F : Type} [Field F] {x y : Wire} {u : ℕ} + {D : Template F} {r : D.format.obj} {Q : LocalTerm F x y D.scheme.h u} + (s : D.Shows r Q) (h : D.scheme.k = 0) (L : Fringe Q.freeze.x Q.freeze.y Q.freeze.Fixed) + +theorem outer_lane (i : slots x ⊕ slots y) : ((s.attached h L).boundary i).val.1.1.2.2 = (1 : B 1) + := by + have he : (s.pres.boundary i).val.1.1 = s.pres.vertex (portEnd Q.diagram i) := by + cases i <;> exact s.pres.end_station _ + rw [s.attached_boundary] + change Pattern.lane (D.mobile r (s.pres.boundary i).val.1.1.1) = _ + rw [he] + exact s.frozen_lane ⟨_, Q.freeze.exterior i⟩ + +theorem retag : s.pres.Retag (s.attached h L) where + m := rfl + owner i := by unfold Scheme.owner; rw [attached_boundary]; rfl + block i := by rw [attached_boundary]; rfl + span i := by rw [attached_boundary]; rfl + offset i := by rw [attached_boundary]; rfl + left i j := (FreezeInput.slot D h _).trans (FreezeInput.slot D h _).symm + right i j := (s.outer_lane h L i).trans (s.outer_lane h L j).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Shows +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Group/ChildPaths.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Group/ChildPaths.lean new file mode 100644 index 0000000000..69dd8c5904 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Group/ChildPaths.lean @@ -0,0 +1,593 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Reads + +/-! # Local adjacency from slot equality masks and edge flags -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +open Coloring + +/-- Computes the checks by the application `Format.pair (.vec q (.vec d (.vec q .bit))) (.vec q +(Flags d))`. -/ +abbrev Checks (q d : ℕ) := Format.pair (.vec q (.vec d (.vec q .bit))) (.vec q (Flags d)) +/-- Computes the adjacency by the application `Format.vec q (Flags q)`. -/ +abbrev Adjacency (q : ℕ) := Format.vec q (Flags q) + +variable {q d t : ℕ} + +/-- The value specified by `(decide (∃ j, x.1 i j k = true ∧ (x.2 i j).1 = true), decide (∃ j, +x.1 i j k = true ∧ (x.2 i j).2 = true))`. -/ +def adjacency (x : (Checks q d).obj) (i k : B q) : Bool × Bool := + (decide (∃ j, x.1 i j k = true ∧ (x.2 i j).1 = true), + decide (∃ j, x.1 i j k = true ∧ (x.2 i j).2 = true)) + +variable (F : Type) [Field F] + +private theorem any_flags (hd : 2 ^ d ≤ t) : + Cheap F 0 t (Flags d) .bit + (fun a => decide (∃ j, (a j).1 = true ∧ (a j).2 = true)) 3 := by + let f (z : Bool × Bool) := z.1 && z.2 + have both := Circuit.map (A := .pair .bit .bit) (D := .bit) (fun _ : B d => f) + (fun _ => Coloring.small (F := F) (A := .pair .bit .bit) (by simp) f) + have one : Circuit F (.vec d .bit) .bit (fun x => decide (∃ j, x j = true)) (5 * 2 ^ d + 1) := by + have net := (Install.BNet.any F (B d)).pull (fun i => (i, ())) + unfold Circuit + convert net using 1 + · funext a i + change decide (∃ j, a (j, ()) = true) = _ + simp [Function.comp_apply] + · simp + omega + have net : Circuit F (Flags d) .bit + (fun a => decide (∃ j, (a j).1 = true ∧ (a j).2 = true)) + (2 ^ d * 200 + (5 * 2 ^ d + 1)) := by + convert both.comp one using 1 + funext x + simp [f] + refine ⟨_, net, ?_⟩ + simp only [Flags, Format.width_vec, Format.width_pair] + rw [Format.width_bit] + ring_nf + omega + +theorem cheap_adjacency (hq : 2 ^ q ≤ t) (hd : 2 ^ d ≤ t) : + Cheap F 0 t (Checks q d) (Adjacency q) adjacency 16 := by + have ha : (Checks q d).width ≤ 2 ^ 0 * (100 + t) ^ 3 := by + simp only [Checks, Flags, Format.width_pair, Format.width_vec] + rw [Format.width_bit] + calc + _ ≤ t * (t * (t * 1)) + t * (t * (1 + 1)) := by gcongr + _ ≤ _ := by ring_nf; omega + have hb : (Flags d).width ≤ 2 ^ 0 * (100 + t) ^ 3 := by + simp only [Flags, Format.width_pair, Format.width_vec] + rw [Format.width_bit] + ring_nf + omega + have edge (i k : B q) : Cheap F 0 t (Checks q d) (.pair .bit .bit) (fun x => adjacency x i k) 6 + := by + have l : Cheap F 0 t (Checks q d) (Flags d) (fun x j => (x.1 i j k, (x.2 i j).1)) 4 := + Cheap.project F ha hb (fun p => p.2.elim (fun z => .inl (i, p.1, k, z)) + (fun z => .inr (i, p.1, .inl z))) (by rintro x ⟨j, z|z⟩ <;> rfl) + have r : Cheap F 0 t (Checks q d) (Flags d) (fun x j => (x.1 i j k, (x.2 i j).2)) 4 := + Cheap.project F ha hb (fun p => p.2.elim (fun z => .inl (i, p.1, k, z)) + (fun z => .inr (i, p.1, .inr z))) (by rintro x ⟨j, z|z⟩ <;> rfl) + exact (l.comp (any_flags F hd)).pair (r.comp (any_flags F hd)) + exact (Cheap.share _ (fun i => Cheap.share _ (edge i) hq) hq).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end + +/- # Graph and core flags for child hosts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child + +open Coloring Install Packing + +variable {m d a h b q t : ℕ} {V : Type} + +open scoped Classical in +/-- Select a graph mask and suppress every slot of an idle parent. -/ +def fromGroup (X : (Group.Input m d a h b).obj) (core : Bool) : (Input m d).obj := + fun i j => ((X i).2.1 && (if core then ((X i).2.2.1 j).2 else ((X i).2.2.1 j).1), (X i).1 j) + +open scoped Classical in +theorem presents {X : (Group.Input m d a h b).obj} {g : V ↪ B m} + {E C : V → Finset V} {l : V × Cell a → Cell h → ℝ} {f : B b → ℝ} + (H : Group.Presents X g E C l f) (core : Bool) : + Presents (if core then C else E) g (fromGroup X core) := by + constructor + · intro v u + have live := (H.live (g v)).mpr ⟨v, rfl⟩ + have mask (y : V) : y ∈ (if core then C else E) v ↔ + ∃ j, (X (g v)).1 j = g y ∧ (fromGroup X core (g v) j).1 = true := by + cases core + · simpa [fromGroup, live] using H.edge v y + · simpa [fromGroup, live] using H.core v y + constructor + · rintro ⟨j, hj⟩ + obtain ⟨y, hy⟩ := H.closed v j + exact ⟨y, (mask y).mpr ⟨j, hy.symm, congrArg Prod.fst hj⟩, hy.trans (congrArg Prod.snd hj)⟩ + · rintro ⟨y, hy, rfl⟩ + obtain ⟨j, he, hj⟩ := (mask y).mp hy + exact ⟨j, Prod.ext hj he⟩ + · intro v hv j + have he : (X v).2.1 = false := Bool.eq_false_iff.mpr (fun h => hv ((H.live v).mp h)) + simp [fromGroup, he] + +open scoped Classical in +private theorem mask_depends (core : Bool) : + Depends ((Input m d).code ∘ (fun x => fromGroup x core) ∘ (Group.Input m d a h b).code.symm) 2 + := by + let T := Group.Input m d a h b + rintro ⟨i, j, k | k⟩ + · let live : T.pins := (i, .inr (.inl ())) + let bit : T.pins := (i, .inr (.inr (.inl (j, if core then .inr () else .inl ())))) + refine ⟨{live, bit}, Finset.card_le_two, fun x y he => ?_⟩ + have hl := he live (by simp) + have hb := he bit (by simp) + cases core <;> exact congrArg₂ (· && ·) hl hb + · let pin : T.pins := (i, .inl (j, k)) + refine ⟨{pin}, by simp, fun x y he => ?_⟩ + exact (congrFun (T.code.apply_symm_apply x) pin).trans + ((he pin (by simp)).trans (congrFun (T.code.apply_symm_apply y) pin).symm) + +variable (F : Type) [Field F] + +open scoped Classical in +theorem fromGroup_circuit (core : Bool) : + Circuit F (Group.Input m d a h b) (Input m d) (fun X => fromGroup X core) + ((Group.Input m d a h b).width + 68 * (Input m d).width) := + (mask_depends core).bnet F + +open scoped Classical in +theorem cheap_fromGroup (core : Bool) (hm : m ≤ t) (hd : 2 ^ d ≤ t) + (ha : 2 ^ a ≤ t) (hh : 2 ^ h ≤ t) (hb : b ≤ t) : + Cheap F m t (Group.Input m d a h b) (Input m d) (fun X => fromGroup X core) 5 := by + refine ⟨_, fromGroup_circuit F core, ?_⟩ + let A := Group.Input m d a h b + let E := Input m d + change A.width + E.width + (A.width + 68 * E.width) ≤ _ + have hi : A.width ≤ 2 ^ m * (100 + t) ^ 4 := by + simp only [A, Group.Input, Fmt.bank, Group.Parcel, Group.Flags, + Format.width_vec, Format.width_pair, Format.width_addr] + rw [Format.width_bit] + apply Nat.mul_le_mul_left + calc + _ ≤ t * t + (1 + (t * (1 + 1) + t * (t * t))) := by gcongr + _ ≤ _ := by ring_nf; omega + have ho : E.width ≤ 2 ^ m * (100 + t) ^ 4 := by + simp only [E, Input, Format.width_vec, Format.width_pair, Format.width_addr] + rw [Format.width_bit] + apply Nat.mul_le_mul_left + calc + _ ≤ t * (1 + t) := by gcongr + _ ≤ _ := by ring_nf; omega + calc + _ ≤ 100 * (2 ^ m * (100 + t) ^ 4) := by omega + _ ≤ _ := by + rw [mul_comm 100, pow_succ (100 + t) 4, ← mul_assoc] + exact Nat.mul_le_mul_left _ (Nat.le_add_right 100 t) + +open scoped Classical in +/-- The short core list and the full list need not use the same slot indices. -/ +def coreFlags (g : B m → B d → B m) (c : B m → B q → B m) (x : B m) (i : B d) := + decide (∃ k, c x k = g x i) + +open scoped Classical in +private theorem any_net (hq : 2 ^ q ≤ t) : + Cheap F 0 t (.vec q .bit) .bit (fun x => decide (∃ i, x i = true)) 2 := by + have net := (BNet.any F (B q)).rename (Equiv.prodUnique (B q) Unit).symm (.refl _) + refine ⟨2 * Fintype.card (B q) + 1, ?_, ?_⟩ + · unfold Circuit + convert net using 1 + funext x u + change decide (∃ i, x (i, ()) = true) = _ + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply, decide_eq_true_eq] + rfl + · rw [Format.width_vec, Format.width_bit, Fintype.card_fin] + ring_nf + omega + +open scoped Classical in +theorem cheap_coreFlags (hm : m ≤ t) (hd : 2 ^ d ≤ t) (hq : 2 ^ q ≤ t) : + Cheap F m t (.pair (Neighborhood.Rows m d) (Neighborhood.Rows m q)) + (.vec m (.vec d .bit)) (fun x => coreFlags x.1 x.2) 16 := by + let A := Format.pair (.vec d (.addr m)) (.vec q (.addr m)) + have ha : A.width ≤ 2 ^ 0 * (100 + t) ^ 3 := by + rw [Format.width_pair, Format.width_vec, Format.width_vec, Format.width_addr] + calc + _ ≤ t * t + t * t := by gcongr + _ ≤ _ := by ring_nf; omega + have hb : (Format.pair (.addr m) (.addr m)).width ≤ 2 ^ 0 * (100 + t) ^ 3 := by + rw [Format.width_pair, Format.width_addr] + ring_nf + omega + have cmp (i : B d) (j : B q) : + Cheap F 0 t A .bit (fun x => decide (x.2 j = x.1 i)) 5 := by + have h : Cheap F 0 t A (.pair (.addr m) (.addr m)) (fun x => (x.2 j, x.1 i)) 4 := + Cheap.project F ha hb (Sum.elim (fun k => .inr (j, k)) (fun k => .inl (i, k))) + (by rintro x (k | k) <;> rfl) + exact h.comp (cheap_eq F hm) + have one (i : B d) : Cheap F 0 t A .bit (fun x => decide (∃ j, x.2 j = x.1 i)) 8 := by + have h := (Cheap.share _ (cmp i) hq).comp (any_net F hq) + convert h using 1 <;> try rfl + funext x + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply, decide_eq_true_eq] + have pairWidth : (Format.pair (Neighborhood.Rows m d) (Neighborhood.Rows m q)).width ≤ + 2 ^ m * (100 + t) ^ 3 := by + rw [Format.width_pair, Format.width_vec m, Format.width_vec m, ← mul_add, ← Format.width_pair] + exact Nat.mul_le_mul_left _ (by simpa only [pow_zero, one_mul] using ha) + have net := (Cheap.id F pairWidth).zip.comp + (Cheap.map (h := m) _ (fun _ => Cheap.share _ one hd)) + exact net.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child +end + +/- +# Resolving short child contacts from an old window + +Both endpoints are specified relative to a common old host by a +window index and an interval code. Only the mask preparation reads +long host names. The same mask works for every block of that host. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child + +open Coloring hiding Rows +open Install Neighborhood +variable {m e q k t : ℕ} + +open scoped Classical in +/-- The indexed operation `fun x i => (Match.rowIndex m e).symm (u (Match.rowIndex m e x).1 +(Match.rowIndex q e i).1, (Match.rowIndex q e i).2)`. -/ +def extend (e : ℕ) (u : (Rows m q).obj) : (Rows (m + e) (q + e)).obj := + fun x i => (Match.rowIndex m e).symm + (u (Match.rowIndex m e x).1 (Match.rowIndex q e i).1, (Match.rowIndex q e i).2) + +open scoped Classical in +/-- Evaluates `maskRows (extend e u) g ((Match.rowIndex m e).symm (x, 0))` at the input `x`. -/ +def mask (u : (Rows m q).obj) (g : (Rows (m + e) k).obj) : (Mask m (q + e) k).obj := + fun x => maskRows (extend e u) g ((Match.rowIndex m e).symm (x, 0)) + +open scoped Classical in +theorem index_eq (u : (Rows m q).obj) (g : (Rows (m + e) k).obj) (x : B m) (i j : B q) (v w : B e) : + index g ((Match.rowIndex m e).symm (u x i, v)) ((Match.rowIndex m e).symm (u x j, w)) = + select (fun s => mask u g x ((Match.rowIndex q e).symm (i, + v)) s ((Match.rowIndex q e).symm (j, w))) := by + simp only [index, mask, maskRows, extend, Equiv.apply_symm_apply] + +open scoped Classical in +private theorem extend_depends : + Depends ((Rows (m + e) (q + e)).code ∘ extend e ∘ (Rows m q).code.symm) 1 := by + rintro ⟨x, i, b⟩ + obtain ⟨z, hz⟩ := Match.append_pin m e b + let p := (Match.rowIndex m e x).1 + let j := Match.rowIndex q e i + have key (a : (Rows m q).pins → Bool) : + ((Rows (m + e) (q + e)).code ∘ extend e ∘ (Rows m q).code.symm) a (x, i, b) = + Sum.elim (fun l => a (p, j.1, l)) ((Format.addr e).code j.2) z := by + refine (hz _ _).trans ?_ + cases z with + | inl l => exact congrFun ((Rows m q).code.apply_symm_apply a) (p, j.1, l) + | inr _ => rfl + cases z with + | inl l => + refine ⟨{(p, j.1, l)}, by simp, fun a b h => ?_⟩ + rw [key, key] + exact h _ (by simp) + | inr l => exact ⟨∅, by simp, fun a b _ => (key a).trans (key b).symm⟩ + +open scoped Classical in +private theorem mask_width (hq : 2 ^ q ≤ t) (hk : 2 ^ k ≤ t) : + (Mask m q k).width ≤ 2 ^ m * (100 + t) ^ 3 := by + simp only [Mask, Format.width_vec] + rw [Format.width_bit, mul_one] + rw [pow_succ, pow_two, mul_assoc] + gcongr <;> omega + +open scoped Classical in +/-- Cost is independent of the number of blocks per child site. -/ +theorem cheap_mask (F : Type) [Field F] (hm : m + e ≤ t) (hq : 2 ^ (q + e) ≤ t) (hk : 2 ^ k ≤ t) : + Cheap F (m + e) t (.pair (Rows m q) (Rows (m + e) k)) (Mask m (q + e) k) + (fun x => mask x.1 x.2) 40 := by + let M := m + e + let Q := q + e + have hQ : 2 ^ Q ≤ t := hq + have hp : 2 ^ m ≤ 2 ^ M := Nat.pow_le_pow_right (by decide) (Nat.le_add_right _ _) + have hq' : 2 ^ q ≤ t := (Nat.pow_le_pow_right (by decide) (Nat.le_add_right _ _)).trans hq + have h₁ : (Rows m q).width ≤ 2 ^ M * (100 + t) ^ 2 := by + rw [Format.width_vec, Format.width_vec, Format.width_addr, pow_two] + gcongr <;> omega + have h₂ : (Rows M Q).width ≤ 2 ^ M * (100 + t) ^ 2 := by + rw [Format.width_vec, Format.width_vec, Format.width_addr, pow_two] + gcongr <;> omega + have h₃ : (Rows M k).width ≤ 2 ^ M * (100 + t) ^ 2 := by + rw [Format.width_vec, Format.width_vec, Format.width_addr, pow_two] + gcongr <;> omega + have ha : Cheap F M t (Rows m q) (Rows M Q) (extend e) 3 := by + refine ⟨_, extend_depends.bnet F, ?_⟩ + change (Rows m q).width + (Rows M Q).width + + ((Rows m q).width + 34 * (Rows M Q).width) ≤ _ + have hb : 100 * (2 ^ M * (100 + t) ^ 2) ≤ 2 ^ M * (100 + t) ^ 3 := by + rw [pow_succ' (100 + t) 2, mul_left_comm 100] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ (Nat.le_add_right _ _)) + omega + let A := Mask M Q k + let D := Mask m Q k + have hd : D.width ≤ 2 ^ M * (100 + t) ^ 3 := (mask_width hq hk).trans (Nat.mul_le_mul_right _ hp) + have pr : Cheap F M t A D (fun a x => a ((Match.rowIndex m e).symm (x, 0))) 4 := + Cheap.project F (mask_width hq hk) hd (fun j => ((Match.rowIndex m e).symm (j.1, 0), j.2)) + (fun _ _ => rfl) + have mid := cheap_maskRows F hm hq hk + have hi : (Format.pair (Rows m q) (Rows M k)).width ≤ 2 ^ M * (100 + t) ^ 3 := by + rw [Format.width_pair, pow_succ (100 + t) 2, ← mul_assoc] + have hle := Nat.mul_le_mul_left (2 ^ M * (100 + t) ^ 2) (show 2 ≤ 100 + t by omega) + omega + let base := Cheap.id F hi + exact ((((base.fst.comp ha).pair base.snd).comp mid).comp pr).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child +end + +/- # Comparing child IDs along two short paths -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child +open Coloring hiding Rows +open Neighborhood Window + +variable {d r : ℕ} + +private theorem walkOfList (p : List (B d)) (hp : p.length ≤ r) : + ∃ u : Walk d r, ∀ m (g : (Rows m d).obj) x, run g r u x = visit g x p := by + induction r generalizing p with + | zero => + have : p = [] := List.length_eq_zero_iff.mp (by omega) + subst p + exact ⟨(), fun _ _ _ => rfl⟩ + | succ r ih => + induction p using List.reverseRecOn with + | nil => + obtain ⟨u, hu⟩ := ih [] (by simp) + exact ⟨(none, u), fun m g x => hu m g x⟩ + | append_singleton p i _ => + obtain ⟨u, hu⟩ := ih p (by simpa using hp) + refine ⟨(some i, u), fun m g x => ?_⟩ + simpa [run, visit] using hu m g (g x i) + +/-- The slot for each path is independent of the navigation table. -/ +theorem visit_slot (p : List (B d)) (hp : p.length ≤ r) : + ∃ j : B ((d + 1) * r), ∀ m (g : (Rows m d).obj) x, walks r g x j = visit g x p := by + obtain ⟨u, hu⟩ := walkOfList p hp + obtain ⟨j, hj⟩ := path_surjective d r u + exact ⟨j, fun m g x => by rw [walks, hj, hu]⟩ + +variable {m m' e k : ℕ} {g : (Rows m d).obj} {g' : (Rows m' d).obj} + {a : (Rows (m + e) k).obj} {a' : (Rows (m' + e) k).obj} {x : B m} {x' : B m'} + (he : mask (walks r g) a x = mask (walks r g') a' x') + {p q : List (B d)} (hp : p.length ≤ r) (hq : q.length ≤ r) +include he hp hq + +theorem index_agree (v w : B e) : + index a ((Match.rowIndex m e).symm (visit g x p, v)) ((Match.rowIndex m e).symm (visit g x q, + w)) = + index a' ((Match.rowIndex m' e).symm (visit g' x' p, + v)) ((Match.rowIndex m' e).symm (visit g' x' q, w)) := by + obtain ⟨i, hi⟩ := visit_slot p hp + obtain ⟨j, hj⟩ := visit_slot q hq + rw [← hi, ← hj, ← hi, ← hj, index_eq, index_eq, he] + +/-- Slot zero names the host itself, so the mask also remembers +equality of parent names along arbitrary short walks. -/ +theorem visit_agree (ha : ∀ i, a i 0 = i) (ha' : ∀ i, a' i 0 = i) : + visit g x p = visit g x q ↔ visit g' x' p = visit g' x' q := by + obtain ⟨i, hi⟩ := visit_slot p hp + obtain ⟨j, hj⟩ := visit_slot q hq + let u := (Match.rowIndex ((d + 1) * r) e).symm (i, 0) + let v := (Match.rowIndex ((d + 1) * r) e).symm (j, 0) + have hv := congrFun (congrFun (congrFun he u) 0) v + simpa only [mask, maskRows, ha, ha', extend, u, v, Equiv.apply_symm_apply, Equiv.apply_eq_iff_eq, + Prod.mk.injEq, and_true, decide_eq_decide, hi, hj] using hv + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child +end + +/- +# Delivering patches + +The expensive long-address masks are shared across groups. The load +records for all groups are sent together in a single tagged exchange. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +open Coloring + +variable {F : Type} [Field F] {m d a h b : ℕ} +local notation "Q" => ((d + 1) * h) +local notation "X₀" => Input m d a h b +local notation "Y₀" => Patches m d a h b +local notation "P₀" => Parcel d a h b +local notation "Mask" => Neighborhood.Mask m Q d +local notation "Bank" => Fmt.bank m Q P₀ +local notation "Views" => Format.vec m (Format.vec Q P₀) +local notation "Overhead" => (2 ^ m * (100 + (m + 2 ^ Q)) ^ 220) + +private def preview (x : (X₀).obj) := Neighborhood.mask h (fun i => (x i).1) +private def rebank (x : (X₀).obj) : (Bank).obj := fun i => (hosts x i, (x i).2) + +private theorem prepare (hh : 0 < h) : + (Mask).width ≤ Overhead ∧ Circuit F X₀ (.pair Mask Bank) + (fun x => (preview x, rebank x)) (40 * ((X₀).width + Overhead)) := by + let U := Neighborhood.Rows m d + let V := Neighborhood.Rows m Q + let L := Format.vec m P₀ + have l : Circuit F X₀ U (fun x i => (x i).1) ((X₀).width + 2 * U.width) := + Circuit.project (fun z => (z.1, .inl z.2)) (fun _ _ => rfl) + have r : Circuit F X₀ L (fun x i => (x i).2) ((X₀).width + 2 * L.width) := + Circuit.project (fun z => (z.1, .inr z.2)) (fun _ _ => rfl) + have zip : Circuit F (.pair V L) Bank (fun x i => (x.1 i, x.2 i)) + ((V.pair L).width + 2 * (Bank).width) := + Circuit.project (Equiv.prodSumDistrib _ _ _) (by rintro x ⟨i, j|j⟩ <;> rfl) + obtain ⟨s, hs, h₁⟩ := (Neighborhood.cheap F m d h hh).mono (d := 220) (by decide) + obtain ⟨t, ht, h₂⟩ := Neighborhood.cheap_mask F m d h hh + change U.width + V.width + s ≤ Overhead at h₁ + change U.width + (Mask).width + t ≤ Overhead at h₂ + have hX : (X₀).width = U.width + L.width := by + simp only [Input, Fmt.bank, U, L, Neighborhood.Rows, Format.width_vec, Format.width_pair, + mul_add] + have hB : (Bank).width = V.width + L.width := by + simp only [Fmt.bank, V, L, Neighborhood.Rows, Format.width_vec, Format.width_pair, mul_add] + refine ⟨by omega, ((l.comp ht).pair (((l.comp hs).pair r).comp zip)).mono ?_⟩ + rw [Format.width_pair] + omega + +private abbrev Source (m d a h b : ℕ) := + Format.pair (Neighborhood.Mask m ((d + 1) * h) d) (.vec m (.vec ((d + 1) * h) (Parcel d a h b))) + +local notation "Z₀" => Source m d a h b + +private def inspect (x : (Z₀).obj) (i : B m) : (Checks Q d).obj := + (x.1 i, fun j => (x.2 i j).2.1) + +private def arrange (x : (Format.pair (.vec m (Adjacency Q)) Views).obj) : (Y₀).obj := fun t => + let i := Match.rowIndex m a t + ((x.2 i.1 0).1, x.1 i.1, fun j => (x.2 i.1 j).2.2 i.2) + +private def finish (x : (Z₀).obj) : (Y₀).obj := arrange (fun i => adjacency (inspect x i), x.2) + +private theorem finish_eq (x : (X₀).obj) : + finish (preview x, Fmt.gather P₀ (rebank x)) = patches x := by + funext t + apply Prod.ext + · change (x (hosts x (Match.rowIndex m a t).1 0)).2.1 = _ + rw [hosts, Neighborhood.origin] + rfl + apply Prod.ext + · funext i k + apply Prod.ext <;> apply Bool.eq_iff_iff.mpr <;> + simp only [finish, arrange, inspect, adjacency, preview, Neighborhood.mask, + Neighborhood.maskRows, + Fmt.gather, rebank, patches, hosts, links, decide_eq_true_eq] <;> + exact ⟨decide_eq_true, of_decide_eq_true⟩ + · rfl + +private theorem post (hh : 0 < h) (hm : (Mask).width ≤ Overhead) : + Circuit F Z₀ Y₀ finish (40 * ((Views).width + (Y₀).width + Overhead)) := by + let C := Format.vec m (Checks Q d) + let D := Format.vec m (Adjacency Q) + have first : Circuit F Z₀ C inspect ((Z₀).width + 2 * C.width) := + Circuit.project (fun z => z.2.elim (fun p => .inl (z.1, p)) + (fun p => .inr (z.1, p.1, .inr (.inl p.2)))) (by rintro x ⟨i, j|j⟩ <;> rfl) + have b' : Circuit F Z₀ Views Prod.snd ((Z₀).width + 2 * (Views).width) := + Circuit.project Sum.inr fun _ _ => rfl + have c : Circuit F (.pair D Views) Y₀ arrange ((D.pair Views).width + 2 * (Y₀).width) := by + let pin (p : (Y₀).pins) : (D.pair Views).pins := + let i := Match.rowIndex m a p.1 + p.2.elim (fun z => .inr (i.1, 0, .inl z)) + (Sum.elim (fun z => .inl (i.1, z)) + (fun z => .inr (i.1, z.1, .inr (.inr (i.2, z.2))))) + exact Circuit.project pin (by rintro x ⟨i, j|(j|j)⟩ <;> rfl) + have hq : 2 ^ Q ≤ m + 2 ^ Q := Nat.le_add_left _ _ + have hd : 2 ^ d ≤ m + 2 ^ Q := (Nat.pow_le_pow_right (by decide) + ((Nat.le_succ d).trans (Nat.le_mul_of_pos_right _ hh))).trans hq + obtain ⟨t, ht, he⟩ := (Cheap.map _ (fun _ : B m => cheap_adjacency F hq hd)).mono + (d := 220) (by decide) + change C.width + D.width + t ≤ Overhead at he + refine (((first.comp ht).pair b').comp c).mono ?_ + rw [Format.width_pair D Views, show (Z₀).width = (Mask).width + + (Views).width from Format.width_pair _ _] + omega + +/-- The patch cost used in the `Group` construction. -/ +def patchCost (m d a h b v n : ℕ) := + 1000 * ((Input m d a h b).width + (Patches m d a h b).width + + (Format.vec m (.vec ((d + 1) * h) (Parcel d a h b))).width + 2 ^ m * (100 + (m + 2 ^ ((d + + 1) * h))) ^ 220) + + gatherCost m ((d + 1) * h) v n + +theorem compute_patches {u v n : ℕ} {L : Set (Table F)} {I : Type*} (hu : 3 ≤ u) + (hh : 0 < h) (ht : Access F u L (m + Q) v n) (hv : (P₀).width ≤ v) + (X : I → (X₀).obj) (hx : ∀ i, Fmt.Reciprocal P₀ (X i)) : + Computes F u L X₀ Y₀ X (fun i => patches (X i)) (fun _ => 1) (patchCost m d a h b v n) := by + obtain ⟨hm, hp⟩ := prepare (F := F) (m := m) (d := d) (a := a) (b := b) hh + have h₁ := Computes.of_map (L := L) (x := X) (Map.circuit hu hp) (fun _ => rfl) + have hg := gather_neighbors (L := L) P₀ hu ht hv (fun i => rebank (X i)) + (fun i => Neighborhood.reciprocal (hx i) h (fun j => (X i j).2)) + have hi := Computes.of_map (L := L) (x := fun i => preview (X i)) + (Map.circuit hu (Circuit.id F Mask)) (fun _ => rfl) + have h₂ := h₁.comp (hi.par hg) + have k := h₂.comp (Computes.of_map (Map.circuit hu (post hh hm)) (fun i => finish_eq (X i))) + simp only [one_mul] at k + refine k.mono ?_ + unfold patchCost + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end + +/- # Grouping from the shared contact array and short loads -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group + +open Coloring Packing +variable {m d a h b : ℕ} + +/-- The value specified by `decideAll Δ D f (patches x)`. -/ +def labels (Δ D : ℕ) (f : B b → ℝ) (x : (Input m d a h b).obj) := + decideAll Δ D f (patches x) + +theorem labels_net {F : Type} [Field F] {I : Type*} {Δ D v n u : ℕ} + {L : Set (Table F)} {f : B b → ℝ} (hu : 3 ≤ u) (hh : 0 < h) + (ht : Access F u L (m + (d + 1) * h) v n) (hv : (Parcel d a h b).width ≤ v) + (X : I → (Input m d a h b).obj) (hx : ∀ i, Fmt.Reciprocal (Parcel d a h b) (X i)) + (hb : arity ((d + 1) * h) h b ≤ u) (hL : (keys F ((d + 1) * h) h b Δ D f : Set _) ⊆ L) : + Computes F u L (Input m d a h b) (.vec (m + a) (Labels h)) X + (fun i => labels Δ D f (X i)) (fun _ => 1) + (patchCost m d a h b v n + cost (m + a) ((d + 1) * h) h b) := by + have H := (compute_patches (L := L) hu hh ht hv X hx).comp + (Computes.of_map (compute F (m + a) hu hb hL) (fun _ => rfl)) + simpa only [one_mul, labels] using H + +theorem Presents.grouping {V : Type} [Fintype V] {E C : V → Finset V} {Δ D k : ℕ} + {x : (Input m d a h b).obj} {host : V ↪ B m} + {l : V × Cell a → Cell h → ℝ} {B' : ℝ} {f : B b → ℝ} + (H : Presents x host E C (relative k B' l) f) + (hΔ : 0 < Δ) (hD : 0 < D) (hk : 1 ≤ k) (hkh : k ≤ h) (hB : 0 < B') + (eSym : ∀ v u, u ∈ E v → v ∈ E u) (cSym : ∀ v u, u ∈ C v → v ∈ C u) + (sub : ∀ v, C v ⊆ E v) (eDeg : ∀ v, (E v).card ≤ D) (cDeg : ∀ v, (C v).card ≤ Δ) + (hl : ∀ v i, 0 ≤ l v i ∧ l v i ≤ B') : + ∃ g : Grouping (inGroup a E) (inGroup a C) Δ D k B' l, ∀ v i, + labels Δ D f x (embed host a v) (cellIndex h i) = intervalCode h (g.here v i).2 := by + have sym (N : V → Finset V) (hs : ∀ v u, u ∈ N v → v ∈ N u) + (v u : V × Cell a) (hu : u ∈ inGroup a N v) : v ∈ inGroup a N u := by + simp only [mem_inGroup] at hu ⊢ + exact ⟨hs _ _ hu.1, hu.2.symm⟩ + apply (H.represents hΔ hD).grouping hΔ hD hk hkh hB (sym E eSym) (sym C cSym) _ _ _ hl + · intro v u hu + simp only [mem_inGroup] at hu ⊢ + exact ⟨sub _ hu.1, hu.2⟩ + · intro v + simpa [inGroup] using eDeg v.1 + · intro v + simpa [inGroup] using cDeg v.1 + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Group/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Group/Model.lean new file mode 100644 index 0000000000..b105f98530 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Group/Model.lean @@ -0,0 +1,888 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.BadBases +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.ResetLocation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection + +/-! # Locality of dyadic marks -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +open Packing + +variable {V U : Type} (E : V → Finset V) (d : V → V → ℕ) + +/-- The index records the accumulated change of depth. -/ +inductive Walk (v : V) : ℕ → V → Prop + | root : Walk v 0 v + | edge {i a b} : Walk v i a → b ∈ E a → Walk v (i + 2 * d a b) b + +variable (A : U → Finset U) (c : U → U → ℕ) (p : U → V) (v : U) (h : ℕ) + +/-- Slots may repeat a host. Edges that can only act above the height +budget need not be stored. -/ +structure Window : Prop where + edge : ∀ i j, j ∈ A i → p j ∈ E (p i) ∧ c i j = d (p i) (p j) + full : ∀ i j k, Walk E d (p v) k (p i) → j ∈ E (p i) → k + 2 * d (p i) j < h → + ∃ t ∈ A i, p t = j + +variable {E d A c p v h} {M : V → (i : ℕ) → Cell i → Prop} + +private theorem shift {x y : V} {i k : ℕ} (he : y ∈ E x) (hk : k = d x y) + (j : Cell (i + 2 * k)) (hj : Spread E d M y _ j) : + Spread E d M x i (ancestor (by omega) j) := by + subst k + exact .move he j hj + +variable (w : Window E d A c p v h) +include w + +private theorem push {u i z} (m : Spread A c (fun a => M (p a)) u i z) : + Spread E d M (p u) i z := by + induction m with + | start m => exact .start m + | @move x y i e z _ ih => + obtain ⟨he, hd⟩ := w.edge _ _ e + exact shift he hd z ih + +private theorem pull (hb : ∀ t i z, M t i z → i < h) {x i z} (m : Spread E d M x i z) : + ∀ {a k}, p a = x → Walk E d (p v) k x → k ≤ i → Spread A c (fun a => M (p a)) a i z := by + induction m with + | start m => rintro a k rfl _ _; exact .start m + | @move x y i e z hm ih => + rintro a k rfl hpath hk + obtain ⟨b, he, hy⟩ := w.full a y k hpath e (lt_of_le_of_lt (Nat.add_le_add_right hk _) + (hm.depth hb)) + have hs := ih hy (hpath.edge e) (Nat.add_le_add_right hk _) + have hd : d (p a) y = c a b := by rw [← hy, (w.edge a b he).2] + exact shift he hd z hs + +theorem Window.spread (hb : ∀ t i z, M t i z → i < h) : + Spread A c (fun a => M (p a)) v = Spread E d M (p v) := by + funext i z + exact propext ⟨push w, fun m => pull w hb m rfl .root (Nat.zero_le _)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end + +section +/- # Bounded records for local grouping decisions -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +open Coloring + +/-- Live bit, the two neighbor masks, then loads of all group members +at the visible hosts. Position zero is the center. -/ +abbrev Patch (q h b : ℕ) := Format.pair .bit (.pair + (.vec q (.vec q (.pair .bit .bit))) (.vec q (.vec h (.addr b)))) + +/-- The quantity computed by `Format.vec h (.addr (h + 1))`. -/ +abbrev Labels (h : ℕ) := Format.vec h (.addr (h + 1)) + +/-- Split counts and all candidate labelings. -/ +abbrev Summary (h : ℕ) := Format.pair (.vec h (.addr h)) (.vec h (Labels h)) + +theorem width_patch (q h b : ℕ) : (Patch q h b).width = 1 + 2 ^ q * (2 ^ q * 2 + 2 ^ h * b) := by + simp [Patch, mul_add] + +theorem width_summary (h : ℕ) : (Summary h).width = 2 ^ h * (h + 2 ^ h * (h + 1)) := by + simp only [Summary, Labels, Format.width_pair, Format.width_vec, Format.width_addr, mul_add] + rw [Format.width_addr (h + 1), mul_add, mul_add] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end + +/- +# Electing the common mixer and recovering dyadic leaf labels + +Only local load and incidence records index the table of candidates. +The common mixer is elected by summing the split counts over live hosts. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +open Coloring Finset Packing + +variable {V : Type} {q h b m : ℕ} + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun j => (x.2.1 i j).1`. -/ +def graph (x : (Patch q h b).obj) (i : B q) : Finset (B q) := + univ.filter fun j => (x.2.1 i j).1 + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun j => (x.2.1 i j).2`. -/ +def core (x : (Patch q h b).obj) (i : B q) : Finset (B q) := + univ.filter fun j => (x.2.1 i j).2 + +open scoped Classical in +/-- Computes the load by the application `f (x.2.2 i (cellIndex h u))`. -/ +def load (f : B b → ℝ) (x : (Patch q h b).obj) (i : B q) (u : Cell h) := + f (x.2.2 i (cellIndex h u)) + +open scoped Classical in +/-- The value specified by `intervalCode h ⟨⟨leafDepth M x, Nat.lt_succ_of_le (leafDepth_le M +x)⟩, ancestor (leafDepth_le M x) x⟩`. -/ +def atLeaf (M : (i : ℕ) → Cell i → Prop) (x : Cell h) : B (h + 1) := + intervalCode h ⟨⟨leafDepth M x, Nat.lt_succ_of_le (leafDepth_le M x)⟩, + ancestor (leafDepth_le M x) x⟩ + +open scoped Classical in +/-- The summarize of type `(Summary h).obj`, constructed using `graph x`. -/ +def summarize (Δ D : ℕ) (f : B b → ℝ) (x : (Patch q h b).obj) : (Summary h).obj := + let E := graph x + let d := delay (core x) Δ D + let l := load f x + (fun t => if x.1 then ⟨splits E d l t 0, splits_le E d l t 0⟩ else 0, + fun t i => atLeaf (marks E d l t 0) (menu h t ((cellIndex h).symm i))) + +open scoped Classical in +/-- The indexed operation `elect ⊥ (fun t i => (x i).1 t)`. -/ +def winner (x : B m → (Summary h).obj) : B h := + elect ⊥ (fun t i => (x i).1 t) + +open scoped Classical in +/-- The decide all of type `B m → (Labels h).obj`, constructed using `summarize Δ D f ∘ x`. -/ +def decideAll (Δ D : ℕ) (f : B b → ℝ) (x : B m → (Patch q h b).obj) : + B m → (Labels h).obj := + let y := summarize Δ D f ∘ x + fun i => (y i).2 (winner y) + +variable (E : V → Finset V) (d : V → V → ℕ) (l : V → Cell h → ℝ) + (Δ D : ℕ) (f : B b → ℝ) (x : B m → (Patch q h b).obj) (host : V ↪ B m) + +open scoped Classical in +/-- The data for the represents construction, including `live`, `patch`. -/ +structure Represents : Prop where + live : ∀ i, (x i).1 = true ↔ i ∈ Set.range host + patch : ∀ v, ∃ p : B q → V, p 0 = v ∧ + Window E d (graph (x (host v))) (delay (core (x (host v))) Δ D) p 0 h ∧ + load f (x (host v)) = l ∘ p + +variable {E d l Δ D f x host} + (H : Represents E d l Δ D f x host) (hb : ∀ v u, l v u ≤ 1) +include H hb + +open scoped Classical in +theorem Represents.marks (v : V) (t : B h) : + Packing.marks (graph (x (host v))) (delay (core (x (host v))) Δ D) + (load f (x (host v))) t 0 = Packing.marks E d l t v := by + obtain ⟨p, hp, w, he⟩ := H.patch v + rw [he] + let M i := heavy (l i) (menu h t).toEquiv + have ht := w.spread (M := M) (fun v _ _ z => heavy.lt (hb v) z) + rw [hp] at ht + exact ht + +open scoped Classical in +theorem Represents.best [Fintype V] : best E d l (winner (summarize Δ D f ∘ x)) := by + let y := summarize Δ D f ∘ x + have eq (t : B h) : ∑ i, ((y i).1 t).val = ∑ v, splits E d l t v := by + rw [← sum_subset (subset_univ (univ.map host))] + · rw [sum_map] + apply sum_congr rfl + intro v _ + have he := (H.live (host v)).mpr ⟨v, rfl⟩ + simp only [y, Function.comp_apply, summarize, he, ↓reduceIte, splits, H.marks hb] + · intro i _ hi + have he : (x i).1 ≠ true := fun e => by + obtain ⟨v, rfl⟩ := (H.live _).mp e + exact hi (mem_map.mpr ⟨v, mem_univ _, rfl⟩) + simp [y, summarize, he] + intro t + rw [← eq, ← eq] + exact elect_min (fun t i => (y i).1 t) t + +open scoped Classical in +theorem Represents.label (v : V) (u : Cell h) : + let pick := winner (summarize Δ D f ∘ x) + decideAll Δ D f x (host v) (cellIndex h u) = + atLeaf (Packing.marks E d l pick v) (menu h pick u) := by + simp only [decideAll, Function.comp_apply, summarize, Equiv.symm_apply_apply, H.marks hb] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end + +/- +# Uniform grouping network + +There are two table labels. Their arities are independent of the number +of hosts and the number of groups. The only long-range operation is +the election on columns of short split counts. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +open Coloring + +open scoped Classical in +/-- The quantity computed by `2 ^ h * (2 ^ m * (100 + h) ^ 5 + (100 + (h + (h + m))) ^ 42)`. -/ +def electionCost (m h : ℕ) := + 2 ^ h * (2 ^ m * (100 + h) ^ 5 + (100 + (h + (h + m))) ^ 42) + +open scoped Classical in +/-- Computes the query by the application `Format.pair (.addr h) (Summary h)`. -/ +abbrev Query (h : ℕ) := Format.pair (.addr h) (Summary h) + +open scoped Classical in +/-- Computes the result by the application `x.2.2 x.1`. -/ +def result (h : ℕ) (x : (Query h).obj) : (Labels h).obj := x.2.2 x.1 + +variable (F : Type) [Field F] + +open scoped Classical in +private theorem query_net (m h : ℕ) : + Circuit F (.vec m (Summary h)) (.vec m (Query h)) (fun x i => (winner x, x i)) + (16 * (2 ^ m * (h + (Summary h).width)) + electionCost m h) := by + let R := Format.vec m (Summary h) + let D := Format.vec h (.vec m (.addr h)) + have pr : Circuit F R D (fun x t i => (x i).1 t) (R.width + 2 * D.width) := by + apply Circuit.project (A := R) (D := D) (fun i => (i.2.1, .inl (i.1, i.2.2))) + exact fun _ _ => rfl + have hd : D.width ≤ R.width := by + simp only [R, D, Format.width_vec, Format.width_addr] + rw [width_summary h, mul_left_comm] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ (Nat.le_add_right _ _)) + let A := Format.pair (.addr h) R + let B := Format.vec m (Query h) + have post : Circuit F A B (fun y i => (y.1, y.2 i)) (A.width + 2 * B.width) := by + apply Circuit.project (A := A) (D := B) (fun i => Sum.elim Sum.inl (fun t => Sum.inr (i.1, + t)) i.2) + rintro x ⟨i, t | t⟩ <;> rfl + have hn := ((pr.comp (election F m h h ⊥)).pair (Circuit.id F R)).comp post + refine hn.mono ?_ + change 5 * R.width + (R.width + 2 * D.width + electionCost m h) + R.width + + (A.width + 2 * B.width) ≤ _ + have hpos : h ≤ 2 ^ m * h := Nat.le_mul_of_pos_left _ (by positivity) + rw [show A.width = h + R.width by simp [A], + show B.width = 2 ^ m * (h + (Summary h).width) by simp only [B, Query, Format.width_vec, + Format.width_pair, Format.width_addr]] + rw [show R.width = 2 ^ m * (Summary h).width from Format.width_vec _ _] at hd ⊢ + rw [mul_add] + omega + +open scoped Classical in +/-- The keys of type `Finset (Table F)` for the given inputs. -/ +def keys (q h b Δ D : ℕ) (f : B b → ℝ) : Finset (Table F) := + {lookup F (Patch q h b) (Summary h) (fun x y => @ite F (summarize Δ D f x + = y) (Classical.propDecidable _) 1 0), + lookup F (Query h) (Labels h) (fun x y => @ite F (result h x + = y) (Classical.propDecidable _) 1 0)} + +open scoped Classical in +/-- The quantity computed by `(Patch q h b).width + (Summary h).width + h + (Labels h).width`. -/ +def arity (q h b : ℕ) := (Patch q h b).width + (Summary h).width + h + (Labels h).width + +open scoped Classical in +/-- The quantity computed by `100 * (2 ^ m * (1 + arity q h b)) + 4 * electionCost m h`. -/ +def cost (m q h b : ℕ) := 100 * (2 ^ m * (1 + arity q h b)) + 4 * electionCost m h + +variable {q h b Δ D : ℕ} {f : B b → ℝ} + +open scoped Classical in +theorem card_keys : (keys F q h b Δ D f).card ≤ 2 := Finset.card_le_two + +open scoped Classical in +theorem arity_keys {T : Table F} (ht : T ∈ keys F q h b Δ D f) : + Processor.arity T ≤ arity q h b := by + simp only [keys, Finset.mem_insert, Finset.mem_singleton] at ht + rcases ht with rfl | rfl <;> + simp only [Processor.arity, lookup, wd_word, arity, Query, Format.width_pair, + Format.width_addr] <;> omega + +open scoped Classical in +theorem compute {u : ℕ} {L : Set (Table F)} (m : ℕ) (hu : 3 ≤ u) + (hb : arity q h b ≤ u) (hL : (keys F q h b Δ D f : Set _) ⊆ L) : + Map F u L (.vec m (Patch q h b)) (.vec m (Labels h)) (decideAll Δ D f) (cost m q h b) := by + have ht : Map F u L (Patch q h b) (Summary h) (summarize Δ D f) (1 + arity q h b) := by + apply Kernel.mono (Kernel.lookup (by unfold arity at hb; omega) (hL (by simp [keys]))) + unfold arity + omega + have hr : Map F u L (Query h) (Labels h) (result h) (1 + arity q h b) := by + have he : (Query h).width = h + (Summary h).width := by simp only [Query, + Format.width_pair, Format.width_addr] + apply Kernel.mono (Kernel.lookup (by unfold arity at hb; omega) (hL (by simp [keys]))) + unfold arity + omega + have first := Map.vec (t := m) _ (fun _ => ht) + have last := Map.vec (t := m) _ (fun _ => hr) + refine ((first.comp (Map.circuit hu (query_net F m h))).comp last).mono ?_ + unfold cost + have ha := Nat.mul_le_mul_left (2 ^ m) (show h + (Summary h).width ≤ 1 + arity q h b by + unfold arity; omega) + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end + +/- # The computed labels certify a balanced partition -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group + +open Coloring Packing + +variable {V : Type} [Fintype V] {q h b m k Δ D : ℕ} {E C : V → Finset V} + {l : V → Cell h → ℝ} {B' : ℝ} {f : B b → ℝ} {x : B m → (Patch q h b).obj} {host : V ↪ B m} + +theorem Represents.grouping + (H : Represents E (delay C Δ D) (relative k B' l) Δ D f x host) + (hΔ : 0 < Δ) (hD : 0 < D) (hk : 1 ≤ k) (hkh : k ≤ h) (hB : 0 < B') + (eSym : ∀ v u, u ∈ E v → v ∈ E u) (cSym : ∀ v u, u ∈ C v → v ∈ C u) + (sub : ∀ v, C v ⊆ E v) (eDeg : ∀ v, (E v).card ≤ D) (cDeg : ∀ v, (C v).card ≤ Δ) + (hl : ∀ v i, 0 ≤ l v i ∧ l v i ≤ B') : + ∃ g : Grouping E C Δ D k B' l, ∀ v i, + decideAll Δ D f x (host v) (cellIndex h i) = intervalCode h (g.here v i).2 := by + have hb (v : V) (i : Cell h) : relative k B' l v i ≤ 1 := by + apply (div_le_one (mul_pos (by positivity) hB)).mpr + exact (hl v i).2.trans (le_mul_of_one_le_left hB.le (one_le_pow₀ (by norm_num))) + let pick := winner (summarize Δ D f ∘ x) + let g := groupBy E C Δ D hΔ hD eSym cSym sub eDeg cDeg hk hkh B' hB l hl pick (H.best hb) + exact ⟨g, fun v i => H.label hb v i⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end + +/- +# Names and neighbors of child hosts + +An address consists of a parent host and a dyadic interval. Only +intersecting intervals at nearby depths need neighbor slots. Their +enumeration is fixed by the height and degree, independently of the +parent graph. A third neighborhood gives the post-contraction graph. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child +open Packing Coloring +variable {V : Type} {m h D d : ℕ} + +open scoped Classical in +/-- Indexes the interval by the coordinates of `Σ i : Fin (h + 1), Cell i.val`. -/ +abbrev Interval (h : ℕ) := Σ i : Fin (h + 1), Cell i.val + +open scoped Classical in +/-- Embeds `Site V h` into `B (m + (h + 1))`. -/ +def host (p : V ↪ B m) (h : ℕ) : Site V h ↪ B (m + (h + 1)) := + (p.prodMap (intervalCode h)).trans (Match.rowIndex m (h + 1)).symm.toEmbedding + +open scoped Classical in +@[simp] theorem host_parts (p : V ↪ B m) (v : Site V h) : + Match.rowIndex m (h + 1) (host p h v) = (p v.1, intervalCode h v.2) := + (Match.rowIndex m (h + 1)).apply_symm_apply _ + +open scoped Classical in +/-- The indexed operation `near (fun _ => {()}) D ((), x)`. -/ +def close (D : ℕ) (x : Interval h) : Finset (Site Unit h) := + near (fun _ => {()}) D ((), x) + +open scoped Classical in +private theorem interval_contains (x : Interval h) : ∃ i, Site.contains ((), x) i := by + let f (i : Fin h) := if e : i.val < x.1 then x.2 ⟨i.val, e⟩ else 0 + refine ⟨f, funext fun i => ?_⟩ + simp [ancestor, f, show i.val < x.1.val from i.isLt] + rfl + +open scoped Classical in +theorem near_iff [Fintype V] (N : V → Finset V) (D : ℕ) (x y : Site V h) : + y ∈ near N D x ↔ y = x ∨ y.1 ∈ N x.1 ∧ ((), y.2) ∈ close D x.2 := by + rw [mem_near, close, mem_near] + constructor + · rintro (rfl | ⟨ha, hb, hc, hd⟩) + · exact .inl rfl + · exact .inr ⟨ha, .inr ⟨by simp, hb, hc, hd⟩⟩ + · rintro (rfl | ⟨ha, he | ⟨_, hb, hc, hd⟩⟩) + · exact .inl rfl + · have hj : y.2 = x.2 := congrArg (fun p : Site Unit h => p.2) he + rcases x with ⟨v, j⟩ + rcases y with ⟨w, k⟩ + change k = j at hj + subst k + obtain ⟨i, hi⟩ := interval_contains j + exact .inr ⟨ha, ⟨i, hi, hi⟩, Nat.le_add_right _ _, Nat.le_add_right _ _⟩ + · exact .inr ⟨ha, hb, hc, hd⟩ + +open scoped Classical in +/-- The minimum of the quantities in `(h + 1) (Nat.clog 2 ((4 * D) ^ 300))`. -/ +def width (h D : ℕ) := min (h + 1) (Nat.clog 2 ((4 * D) ^ 300)) + +open scoped Classical in +private theorem close_card (hD : 0 < D) (x : Interval h) : + (close D x).card ≤ 2 ^ width h D := by + unfold width + rcases min_choice (h + 1) (Nat.clog 2 ((4 * D) ^ 300)) with e | e <;> rw [e] + · refine (Finset.card_le_univ _).trans ?_ + simpa [pow_succ'] using Site.card Unit h + · exact (near_card _ _ hD (by simp; omega) _).trans (Nat.le_pow_clog (by decide) _) + +open scoped Classical in +/-- The seat of type `Option (B (h + 1))`, constructed using `close D hx.choose`. -/ +def seat (h D : ℕ) (x : B (h + 1)) (j : B (width h D)) : Option (B (h + 1)) := + if hx : x ∈ Set.range (intervalCode h) then + let S := close D hx.choose + if hj : j.val < S.card then some (intervalCode h (S.equivFin.symm ⟨j.val, hj⟩).val.2) + else none + else none + +open scoped Classical in +private theorem seat_at (x : Interval h) (j : B (width h D)) : + seat h D (intervalCode h x) j = + if e : j.val < (close D x).card then + some (intervalCode h ((close D x).equivFin.symm ⟨j.val, e⟩).val.2) else none := by + have hx : intervalCode h x ∈ Set.range (intervalCode h) := ⟨x, rfl⟩ + have eq := (intervalCode h).injective hx.choose_spec + rw [seat, dite_eq_left hx, eq] + +open scoped Classical in +theorem hits (hD : 0 < D) (x : Interval h) (y : B (h + 1)) : + (∃ j, seat h D (intervalCode h x) j = some y) ↔ + ∃ w : Interval h, ((), w) ∈ close D x ∧ intervalCode h w = y := by + let S := close D x + constructor + · rintro ⟨j, hj⟩ + rw [seat_at] at hj + split at hj + next h => + let p := S.equivFin.symm ⟨j.val, h⟩ + exact ⟨p.val.2, p.property, Option.some.inj hj⟩ + next => contradiction + · rintro ⟨w, hw, rfl⟩ + let j := S.equivFin ⟨((), w), hw⟩ + refine ⟨Fin.castLE (close_card hD x) j, ?_⟩ + rw [seat_at, dite_eq_left (show (Fin.castLE (close_card hD x) j).val + < (close D x).card from j.isLt)] + change some (intervalCode h (S.equivFin.symm j).val.2) = _ + rw [show S.equivFin.symm j = _ from S.equivFin.symm_apply_apply _] + +open scoped Classical in +/-- Computes the input by the application `Format.vec m (.vec d (.pair .bit (.addr m)))`. -/ +abbrev Input (m d : ℕ) := Format.vec m (.vec d (.pair .bit (.addr m))) +open scoped Classical in +/-- The quantity computed by `(d + width h D + 1) * 3`. -/ +abbrev nextWidth (h D d : ℕ) := (d + width h D + 1) * 3 + +/-- A uniform upper bound on the degree of a child with bounded parent degree. -/ +abbrev degreeLimit (budget degree : ℕ) := (degree + Nat.clog 2 ((4 * budget) ^ 300) + 1) * 3 + +theorem nextWidth_le_degreeLimit (height budget : ℕ) {degree upper : ℕ} (h : degree ≤ upper) : + nextWidth height budget degree ≤ degreeLimit budget upper := + Nat.mul_le_mul_right 3 (Nat.add_le_add_right (Nat.add_le_add h (min_le_right ..)) 1) + +open scoped Classical in +/-- The construction uses `Match.rowIndex m (h + 1) i` for its intermediate `p`. -/ +def step (h D : ℕ) (x : (Input m d).obj) (i : B (m + (h + 1))) (j : B (d + width h D)) := + let p := Match.rowIndex m (h + 1) i + let q := Match.rowIndex d (width h D) j + let r := x p.1 q.1 + if r.1 then (seat h D p.2 q.2).elim i (fun z => (Match.rowIndex m (h + 1)).symm (r.2, z)) else i + +open scoped Classical in +/-- Computes the neighbors by the application `Neighborhood.expand 3 (step h D x)`. -/ +def neighbors (h D : ℕ) (x : (Input m d).obj) : (Neighborhood.Rows (m + (h + + 1)) (nextWidth h D d)).obj := + Neighborhood.expand 3 (step h D x) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child +end + +/- # Exact support of the child host dictionary -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child +open Packing Coloring Neighborhood +variable {V : Type} {m d h D : ℕ} {N : V → Finset V} {p : V ↪ B m} {X : (Input m d).obj} + +open scoped Classical in +/-- The data for the presents construction, including `live`, `idle`. -/ +structure Presents (N : V → Finset V) (p : V ↪ B m) (X : (Input m d).obj) : Prop where + live : ∀ v u, (∃ i, X (p v) i = (true, u)) ↔ ∃ w ∈ N v, p w = u + idle : ∀ v ∉ Set.range p, ∀ i, (X v i).1 = false + +open scoped Classical in +theorem Presents.step_idle (H : Presents N p X) {x : B (m + (h + 1))} + (hx : x ∉ Set.range (host p h)) (i : B (d + width h D)) : step h D X x i = x := by + let y := Match.rowIndex m (h + 1) x + by_cases hp : y.1 ∈ Set.range p + · obtain ⟨v, hv⟩ := hp + have hi : y.2 ∉ Set.range (intervalCode h) := by + rintro ⟨k, hk⟩ + refine hx ⟨(v, k), (Match.rowIndex m (h + 1)).injective ?_⟩ + rw [host_parts] + exact Prod.ext hv hk + have hs (j) : seat h D y.2 j = none := dite_eq_right hi + unfold step + simp only [show (Match.rowIndex m (h + 1)) x = y from rfl, hs, Option.elim_none, ite_self] + · unfold step + simp only [show (Match.rowIndex m (h + 1)) x = y from rfl, H.idle _ hp, Bool.false_eq_true, + ↓reduceIte] + +open scoped Classical in +theorem Presents.idle_neighbors (H : Presents N p X) {x : B (m + (h + 1))} + (hx : x ∉ Set.range (host p h)) (i : B (nextWidth h D d)) : neighbors h D X x i = x := by + have go {k y} (hy : Reach (step h D X) k x y) : y = x := by + induction k with + | zero => exact Eq.symm hy + | succ k ih => + obtain ⟨z, hz, he⟩ := hy + have eq : z = x := hz.elim id (fun ⟨j, hj⟩ => hj.symm.trans (H.step_idle hx j)) + exact ih (eq ▸ he) + exact go (k := 3) (Neighborhood.mem.mp ⟨i, rfl⟩) + +variable [Fintype V] (H : Presents N p X) (hD : 0 < D) +include H hD + +open scoped Classical in +theorem Presents.step_mem (v : Site V h) (y : B (m + (h + 1))) : + (y = host p h v ∨ ∃ i, step h D X (host p h v) i = y) ↔ + ∃ u ∈ near N D v, host p h u = y := by + have idle : ∃ u ∈ near N D v, host p h u = host p h v := ⟨v, near_self .., rfl⟩ + constructor + · rintro (rfl | ⟨i, rfl⟩) + · exact idle + let t := Match.rowIndex d (width h D) i + simp only [step, host_parts] + change ∃ u ∈ _, host p h u = if (X (p v.1) t.1).1 then + (seat h D (intervalCode h v.2) t.2).elim _ _ else _ + cases he : X (p v.1) t.1 with + | mk b z => + cases b + · exact idle + cases hz : seat h D (intervalCode h v.2) t.2 with + | none => exact idle + | some w => + obtain ⟨a, ha, rfl⟩ := (H.live v.1 z).mp ⟨t.1, he⟩ + obtain ⟨b, hb, rfl⟩ := (hits hD v.2 w).mp ⟨t.2, hz⟩ + exact ⟨(a, b), (near_iff _ _ _ _).mpr (.inr ⟨ha, hb⟩), rfl⟩ + · rintro ⟨u, hu, rfl⟩ + rcases (near_iff _ _ _ _).mp hu with rfl | ⟨ha, hb⟩ + · exact .inl rfl + obtain ⟨i, hi⟩ := (H.live _ _).mpr ⟨_, ha, rfl⟩ + obtain ⟨j, hj⟩ := (hits hD _ _).mpr ⟨_, hb, rfl⟩ + refine .inr ⟨(Match.rowIndex d (width h D)).symm (i, j), ?_⟩ + simp only [step, host_parts, Equiv.apply_symm_apply, hi, hj, ↓reduceIte, Option.elim_some] + rfl + +open scoped Classical in +theorem Presents.mem (v : Site V h) (y : B (m + (h + 1))) : + (∃ i, neighbors h D X (host p h v) i = y) ↔ ∃ u ∈ cube (near N D) v, host p h u = y := by + unfold neighbors + rw [Neighborhood.mem] + constructor + · rintro ⟨a, ha, b, hb, c, hc, rfl⟩ + obtain ⟨a, hva, rfl⟩ := (H.step_mem hD _ _).mp ha + obtain ⟨b, hab, rfl⟩ := (H.step_mem hD _ _).mp hb + obtain ⟨c, hbc, rfl⟩ := (H.step_mem hD _ _).mp hc + exact ⟨c, (mem_cube ..).mpr ⟨a, hva, b, hab, hbc⟩, rfl⟩ + · rintro ⟨u, hu, rfl⟩ + obtain ⟨a, ha, b, hb, he⟩ := (mem_cube ..).mp hu + exact ⟨_, (H.step_mem hD _ _).mpr ⟨a, ha, rfl⟩, _, (H.step_mem hD _ _).mpr ⟨b, hb, rfl⟩, + _, (H.step_mem hD _ _).mpr ⟨u, he, rfl⟩, rfl⟩ + +open scoped Classical in +omit [Fintype V] in +theorem Presents.reciprocal [Finite V] (hs : ∀ v u, u ∈ N v → v ∈ N u) + (A : Format) (f : B (m + (h + 1)) → A.obj) : + Fmt.Reciprocal A (fun i => (neighbors h D X i, f i)) := by + let : Fintype V := Fintype.ofFinite V + intro x j hj + by_cases hx : x ∈ Set.range (host p h) + · obtain ⟨v, rfl⟩ := hx + obtain ⟨u, hu, he⟩ := (H.mem hD v _).mp ⟨j, rfl⟩ + obtain ⟨i, hi⟩ := (H.mem hD u _).mpr ⟨v, cube_symm _ (near_symm hs D) _ _ hu, rfl⟩ + rw [he] at hi + exact ⟨i, hi, fun _ hk => Neighborhood.unique hk hi hj.symm⟩ + · exact (hj (H.idle_neighbors hx j)).elim + +omit H hD + +open scoped Classical in +/-- Selects the appropriate branch of `if test 0 then 0 else if h : ∃ i, test i = true then +h.choose else 0`. -/ +def select (test : B d → Bool) : B d := + if test 0 then 0 else if h : ∃ i, test i = true then h.choose else 0 + +open scoped Classical in +theorem select_spec (test : B d → Bool) (h : ∃ i, test i = true) : test (select test) = true := by + unfold select + split + · assumption + · exact h.choose_spec + +open scoped Classical in +/-- The indexed operation `select (fun i => decide (g x i = y))`. -/ +def index (g : B m → B d → B m) (x y : B m) : B d := + select (fun i => decide (g x i = y)) + +include H hD in +open scoped Classical in +theorem Presents.nav (x y : Site V h) (hy : y ∈ cube (near N D) x) : + let g := neighbors h D X + g (host p h x) (index g (host p h x) (host p h y)) = host p h y := by + obtain ⟨i, hi⟩ := (H.mem hD x _).mpr ⟨y, hy, rfl⟩ + exact of_decide_eq_true (select_spec (fun i => decide (neighbors h D X (host p h x) i + = host p h y)) ⟨i, decide_eq_true hi⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child +end + +/- # The grouping record at a host and group index -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +open Coloring + +/-- Computes the flags by the application `Format.vec d (.pair .bit .bit)`. -/ +abbrev Flags (d : ℕ) := Format.vec d (.pair .bit .bit) +/-- Computes the parcel by the application `Format.pair .bit (.pair (Flags d) (.vec a (.vec h +(.addr b))))`. -/ +abbrev Parcel (d a h b : ℕ) := Format.pair .bit (.pair (Flags d) (.vec a (.vec h (.addr b)))) +/-- Computes the input by the application `Fmt.bank m d (Parcel d a h b)`. -/ +abbrev Input (m d a h b : ℕ) := Fmt.bank m d (Parcel d a h b) +/-- The quantity computed by `Format.vec (m + a) (Patch ((d + 1) * h) h b)`. -/ +abbrev Patches (m d a h b : ℕ) := Format.vec (m + a) (Patch ((d + 1) * h) h b) + +variable {m d a h b : ℕ} (X : (Input m d a h b).obj) + +/-- The indexed operation `Neighborhood.expand h (fun j => (X j).1)`. -/ +def hosts := Neighborhood.expand h (fun j => (X j).1) + +/-- The value specified by `(decide (∃ j, (X y).1 j = z ∧ ((X y).2.2.1 j).1 = true), decide (∃ +j, (X y).1 j = z ∧ ((X y).2.2.1 j).2 = true))`. -/ +def links (y z : B m) : Bool × Bool := + (decide (∃ j, (X y).1 j = z ∧ ((X y).2.2.1 j).1 = true), + decide (∃ j, (X y).1 j = z ∧ ((X y).2.2.1 j).2 = true)) + +/-- The indexed operation `fun t => let i := Match.rowIndex m a t let p := hosts X i.1 ((X +i.1).2.1, fun j k => links X (p j) (p k), fun j => (X (p j)).2.2.2 i.2)`. -/ +def patches : (Patches m d a h b).obj := fun t => + let i := Match.rowIndex m a t + let p := hosts X i.1 + ((X i.1).2.1, fun j k => links X (p j) (p k), fun j => (X (p j)).2.2.2 i.2) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end + +/- # Interpreting the live rows of a grouping controller -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group + +open Coloring Packing Neighborhood + +variable {V : Type} {m d a h b Δ D : ℕ} + +open scoped Classical in +/-- Embeds `V × Cell a` into `B (m + a)`. -/ +def embed (g : V ↪ B m) (a : ℕ) : V × Cell a ↪ B (m + a) := + (g.prodMap (cellIndex a).toEmbedding).trans (Match.rowIndex m a).symm.toEmbedding + +open scoped Classical in +@[simp] theorem row_embed (g : V ↪ B m) (x : V × Cell a) : + Match.rowIndex m a (embed g a x) = (g x.1, cellIndex a x.2) := + (Match.rowIndex m a).apply_symm_apply _ + +open scoped Classical in +private theorem pad_reach {q : B m → B d → B m} {x y : B m} {r t : ℕ} + (hp : Reach q r x y) (h : r ≤ t) : Reach q t x y := by + induction t, h using Nat.le_induction with + | base => exact hp + | succ _ _ ih => exact ih.tail (.inl rfl) + +open scoped Classical in +private theorem delay_pos (C : V → Finset V) (hΔ : 0 < Δ) (hD : 0 < D) (x y : V) : + 0 < delay C Δ D x y := by + apply Nat.mul_pos (by decide : 0 < 32) + apply Nat.clog_pos (by decide) + split_ifs <;> omega + +variable (X : (Input m d a h b).obj) (g : V ↪ B m) + (E C : V → Finset V) (l : V × Cell a → Cell h → ℝ) (f : B b → ℝ) + +open scoped Classical in +/-- The two masks distinguish graph edges and core edges from padding. +The address of every neighbor of a live host is itself live. -/ +structure Presents : Prop where + live : ∀ i, (X i).2.1 = true ↔ i ∈ Set.range g + closed : ∀ v j, (X (g v)).1 j ∈ Set.range g + edge : ∀ v y, y ∈ E v ↔ ∃ j, (X (g v)).1 j = g y ∧ ((X (g v)).2.2.1 j).1 = true + core : ∀ v y, y ∈ C v ↔ ∃ j, (X (g v)).1 j = g y ∧ ((X (g v)).2.2.1 j).2 = true + load : ∀ v i j, f ((X (g v)).2.2.2 (cellIndex a i) (cellIndex h j)) = l (v, i) j + +variable {X g E C l f} (H : Presents X g E C l f) +include H + +open scoped Classical in +private theorem live_reach {k : ℕ} {x y : B m} + (hw : Reach (fun i => (X i).1) k x y) (hx : x ∈ Set.range g) : y ∈ Set.range g := by + induction k generalizing x with + | zero => exact hw ▸ hx + | succ k ih => + obtain ⟨z, hz, hw⟩ := hw + refine ih hw ?_ + rcases hz with rfl | ⟨i, rfl⟩ + · exact hx + · obtain ⟨v, rfl⟩ := hx + exact H.closed v i + +open scoped Classical in +private theorem walk_reach (hΔ : 0 < Δ) (hD : 0 < D) {v y : V × Cell a} {k : ℕ} + (hw : Walk (inGroup a E) (delay (inGroup a C) Δ D) v k y) : + Reach (fun i => (X i).1) k (g v.1) (g y.1) := by + induction hw with + | root => rfl + | @edge k p q _ he ih => + obtain ⟨j, hj, _⟩ := (H.edge _ _).mp ((mem_inGroup ..).mp he).1 + have := delay_pos (inGroup a C) hΔ hD p q + exact pad_reach (ih.tail (.inr ⟨j, hj⟩)) (by omega) + +open scoped Classical in +theorem Presents.represents (hΔ : 0 < Δ) (hD : 0 < D) : + Represents (inGroup a E) (delay (inGroup a C) Δ D) l Δ D f (patches X) (embed g a) := by + constructor + · intro i + change (X (Match.rowIndex m a i).1).2.1 = true ↔ _ + rw [H.live] + constructor + · rintro ⟨v, hv⟩ + refine ⟨(v, (cellIndex a).symm (Match.rowIndex m a i).2), (Match.rowIndex m a).injective ?_⟩ + simp [hv] + · rintro ⟨v, rfl⟩ + exact ⟨v.1, by rw [row_embed]⟩ + intro v + have hs (i) : hosts X (g v.1) i ∈ Set.range g := + live_reach H (Neighborhood.mem.mp ⟨i, rfl⟩) ⟨v.1, rfl⟩ + choose y hy using hs + let p i := (y i, v.2) + have hp : p 0 = v := Prod.ext (g.injective ((hy 0).trans Neighborhood.origin)) rfl + let q := patches X (embed g a v) + have ha (i j) : j ∈ graph q i ↔ p j ∈ inGroup a E (p i) := by + simp only [graph, Finset.mem_filter, Finset.mem_univ, true_and, q, patches, row_embed, + ← hy, links, decide_eq_true_eq, mem_inGroup, p, and_true] + exact (H.edge _ _).symm + have hc (i j) : j ∈ Group.core q i ↔ p j ∈ inGroup a C (p i) := by + simp only [Group.core, Finset.mem_filter, Finset.mem_univ, true_and, q, patches, row_embed, + ← hy, links, decide_eq_true_eq, mem_inGroup, p, and_true] + exact (H.core _ _).symm + refine ⟨p, hp, ⟨?_, ?_⟩, ?_⟩ + · intro i j hj + refine ⟨(ha i j).mp hj, ?_⟩ + change delay (Group.core q) Δ D i j = _ + simp only [delay, hc] + split <;> rfl + · intro i j k hw he hk + have hr := pad_reach (walk_reach H hΔ hD (hw.edge he)) hk.le + rw [hp] at hr + obtain ⟨t, ht⟩ := Neighborhood.mem.mpr hr + have eq : p t = j := + Prod.ext (g.injective ((hy t).trans ht)) ((mem_inGroup ..).mp he).2.symm + exact ⟨t, (ha i t).mpr (eq ▸ he), eq⟩ + · funext i j + simp only [Group.load, patches, row_embed, ← hy, H.load, Function.comp_apply, p] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Group +end + +/- # Computing the child contact lists -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child + +open Coloring Install + +variable {m d h D : ℕ} + +open scoped Classical in +/-- The seat of a candidate is fixed by the output index. Each output +bit reads an activity flag and at most one parent-address bit. -/ +theorem step_depends : + Depends ((Neighborhood.Rows (m + (h + 1)) (d + width h D)).code ∘ + step h D ∘ (Input m d).code.symm) 2 := by + rintro ⟨i, j, b⟩ + let p := Match.rowIndex m (h + 1) i + let q := Match.rowIndex d (width h D) j + let T := Input m d + let r (x : T.pins → Bool) := T.code.symm x p.1 q.1 + let flag : T.pins := (p.1, q.1, .inl ()) + obtain ⟨k, hk⟩ := Match.append_pin m (h + 1) b + let bit : T.pins := k.elim (fun z => (p.1, q.1, .inr z)) (fun _ => flag) + refine ⟨{flag, bit}, Finset.card_le_two, fun x y he => ?_⟩ + have flags (v : T.pins → Bool) : (r v).1 = v flag := + congrFun (T.code.apply_symm_apply v) flag + have parent (v : T.pins → Bool) (z : slots (word m)) : + (Format.addr m).code (r v).2 z = v (p.1, q.1, .inr z) := + congrFun (T.code.apply_symm_apply v) (p.1, q.1, .inr z) + have selected : (r x).1 = (r y).1 := by rw [flags, flags, he flag (by simp)] + let out (v : T.pins → Bool) := + if (r v).1 then (seat h D p.2 q.2).elim i (fun z => (Match.rowIndex m (h + 1)).symm ((r v).2, + z)) + else i + change (Format.addr _).code (out x) b = (Format.addr _).code (out y) b + unfold out + rw [selected] + split + · cases seat h D p.2 q.2 with + | none => rfl + | some z => + simp only [Option.elim_some, hk] + have hbit := he bit (by simp) + cases k with + | inl k => simpa only [Sum.elim_inl, parent, bit] using hbit + | inr k => rfl + · rfl + +variable (F : Type) [Field F] + +open scoped Classical in +/-- Construct the one-step graph and then enumerate the third neighborhood. -/ +theorem cheap (m d h D : ℕ) : + Cheap F (m + (h + 1)) (m + (h + 1) + 2 ^ nextWidth h D d) + (Input m d) (Neighborhood.Rows (m + (h + 1)) (nextWidth h D d)) (neighbors h D) 201 := by + let M := m + (h + 1) + let n := d + width h D + let t := M + 2 ^ nextWidth h D d + have hn : 2 ^ n ≤ 100 + t := by + have h' := Nat.pow_le_pow_right (by decide : 0 < 2) + (show n ≤ nextWidth h D d by unfold n nextWidth; omega) + unfold t + omega + have hd : 2 ^ d ≤ 100 + t := + (Nat.pow_le_pow_right (by decide) (Nat.le_add_right d _)).trans hn + have hM : M ≤ 100 + t := (Nat.le_add_right M _).trans (Nat.le_add_left _ _) + have hm : 1 + m ≤ 100 + t := (show 1 + m ≤ M by unfold M; omega).trans hM + have hm' : 2 ^ m ≤ 2 ^ M := Nat.pow_le_pow_right (by decide) (Nat.le_add_right _ _) + have hi : (Input m d).width ≤ 2 ^ M * (100 + t) ^ 2 := by + rw [Format.width_vec, Format.width_vec, Format.width_pair, Format.width_bit, Format.width_addr, + pow_two] + exact Nat.mul_le_mul hm' (Nat.mul_le_mul hd hm) + have ho : (Neighborhood.Rows M n).width ≤ 2 ^ M * (100 + t) ^ 2 := by + rw [Format.width_vec, Format.width_vec, Format.width_addr, pow_two] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul hn hM) + have stepCheap : Cheap F M t (Input m d) (Neighborhood.Rows M n) (step h D) 3 := by + refine ⟨_, step_depends.bnet F, ?_⟩ + change (Input m d).width + (Neighborhood.Rows M n).width + + ((Input m d).width + 68 * (Neighborhood.Rows M n).width) ≤ _ + calc + _ ≤ 100 * (2 ^ M * (100 + t) ^ 2) := by omega + _ ≤ _ := by + rw [mul_comm 100, pow_succ (100 + t) 2, ← mul_assoc] + exact Nat.mul_le_mul_left _ (Nat.le_add_right 100 t) + exact stepCheap.comp (Neighborhood.cheap F M n 3 (by decide)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Child +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/BoardPush.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/BoardPush.lean new file mode 100644 index 0000000000..b7c7ccf0d3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/BoardPush.lean @@ -0,0 +1,901 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Reads +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.ChildPaths +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Length + +/-! +# A short dictionary input at a child occurrence + +An interval code and group index specify the occurrence within the +parent. Equality tests on the surrounding addresses are encoded in +the common mask. No global host name enters the dictionary. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window.Tile +open Coloring + +/-- The quantity computed by `(d + 1) * 8`. -/ +abbrev radius (d : ℕ) := (d + 1) * 8 + +theorem exp_radius_mono {d upper : ℕ} (h : d ≤ upper) : 2 ^ radius d ≤ 2 ^ radius upper := + Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ (Nat.add_le_add_right h 1)) + +/-- The quantity computed by `Format.vec (radius d + (n + 1)) (.vec k (.vec (radius d + (n + 1)) +.bit))`. -/ +abbrev mask (d n k : ℕ) := Format.vec (radius d + (n + 1)) (.vec k (.vec (radius d + (n + 1)) .bit)) +/-- The value specified by `Format.pair .bit (.pair .bit (.pair (.addr a) (.pair (.addr (n + 1)) +(.pair (mask d n k) (.vec (radius d) A)))))`. -/ +abbrev word (d a n k : ℕ) (A : Format) := + Format.pair .bit (.pair .bit (.pair (.addr a) + (.pair (.addr (n + 1)) (.pair (mask d n k) (.vec (radius d) A))))) + +/-- The value specified by `Format.pair (.vec (m + (n + 1)) .bit) (.pair .bit (.pair (.vec m +(mask d n k)) (Fmt.groups m d a (.vec (radius d) A))))`. -/ +abbrev incoming (m d a n k : ℕ) (A : Format) := + Format.pair (.vec (m + (n + 1)) .bit) (.pair .bit + (.pair (.vec m (mask d n k)) (Fmt.groups m d a (.vec (radius d) A)))) + +variable {m d a n k : ℕ} {A : Format} + +/-- The tile of type `(word d a n k A).obj`, constructed using `Match.rowIndex m (n + 1) v`. -/ +def tile (x : (incoming m d a n k A).obj) (v : B (m + (n + 1))) (b : B a) : (word d a n k A).obj := + let p := Match.rowIndex m (n + 1) v + (x.1 v, x.2.1, b, p.2, x.2.2.1 p.1, (x.2.2.2 p.1).2 b) + +/-- The indexed operation `(live, col, Child.mask (Neighborhood.walks 8 (fun v => (x v).1)) nav, +reads 8 x)`. -/ +def bank (live : B (m + (n + 1)) → Bool) (col : Bool) (nav : (Neighborhood.Rows (m + (n + + 1)) k).obj) + (x : (Fmt.groups m d a A).obj) : (incoming m d a n k A).obj := + (live, col, Child.mask (Neighborhood.walks 8 (fun v => (x v).1)) nav, reads 8 x) + +theorem width : (word d a n k A).width = 2 + a + (n + 1) + + 2 ^ (radius d + (n + 1)) * (2 ^ k * 2 ^ (radius d + (n + 1))) + 2 ^ (radius d) * A.width := by + simp only [word, mask, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit, Format.width_addr (n + 1)] + ring + +/-- The quantity computed by `(Match.rowIndex m (n + 1)).symm (p.1, label)`. -/ +def atHost (p : B m × B a) (label : B (n + 1)) : B (m + (n + 1)) := + (Match.rowIndex m (n + 1)).symm (p.1, label) + +theorem tile_at (x : (incoming m d a n k A).obj) (p : B m × B a) (label : B (n + 1)) : + tile x (atHost p label) p.2 = + (x.1 (atHost p label), x.2.1, p.2, label, x.2.2.1 p.1, (x.2.2.2 p.1).2 p.2) := by + simp only [tile, atHost, Equiv.apply_symm_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window.Tile +end + +/- # One shared dictionary gate per child and group -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window.Tile +open Coloring + +variable {F : Type} [Field F] {u m d a n k : ℕ} {A H : Format} {L : Set (Table F)} + +open scoped Classical in +theorem project_const {f : A.obj → H.obj} + (hf : ∀ i, (∃ j, ∀ x, H.code (f x) i = A.code x j) ∨ ∃ b, ∀ x, H.code (f x) i = b) : + Circuit F A H f (A.width + 34 * H.width) := by + have h : Install.Depends (H.code ∘ f ∘ A.code.symm) 1 := by + intro i + rcases hf i with ⟨j, hj⟩ | ⟨b, hb⟩ + · refine ⟨{j}, by simp, fun x y e => ?_⟩ + simpa only [Function.comp_apply, hj, Equiv.apply_symm_apply] using e j (by simp) + · exact ⟨∅, by simp, fun x y _ => (hb _).trans (hb _).symm⟩ + exact h.bnet F + +open scoped Classical in +/-- The quantity computed by `Format.vec (m + (n + 1)) (.vec a H)`. -/ +abbrev output (m a n : ℕ) (H : Format) := Format.vec (m + (n + 1)) (.vec a H) + +open scoped Classical in +private theorem prepare : + Circuit F (incoming m d a n k A) (output m a n (word d a n k A)) tile + ((incoming m d a n k A).width + 34 * (output m a n (word d a n k A)).width) := by + apply project_const + rintro ⟨v, b, i | i | i | i | i | i⟩ + · exact .inl ⟨.inl (v, i), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inl i), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr a).code b i, fun _ => rfl⟩ + · exact .inr ⟨(Format.addr (n + 1)).code (Match.rowIndex m (n + 1) v).2 i, fun _ => rfl⟩ + · exact .inl ⟨.inr (.inr (.inl ((Match.rowIndex m (n + 1) v).1, i))), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inr (.inr ((Match.rowIndex m (n + 1) v).1, .inr (b, i)))), fun _ => rfl⟩ + +open scoped Classical in +/-- The value specified by `4 * (incoming m d a n k A).width + 2 ^ (m + (n + 1)) * 2 ^ a * (1 + +137 * (word d a n k A).width + H.width)`. -/ +def cost (m d a n k : ℕ) (A H : Format) := + 4 * (incoming m d a n k A).width + + 2 ^ (m + (n + 1)) * 2 ^ a * (1 + 137 * (word d a n k A).width + H.width) + +open scoped Classical in +/-- The value specified by `lookup F (word d a n k A) H (fun x y => if g x = y then 1 else 0)`. -/ +def gate (F : Type) [Field F] (g : (word d a n k A).obj → H.obj) := + lookup F (word d a n k A) H (fun x y => if g x = y then 1 else 0) + +open scoped Classical in +theorem computes (hu : 3 ≤ u) (g : (word d a n k A).obj → H.obj) + (fit : (word d a n k A).width + H.width ≤ u) (allowed : gate F g ∈ L) : + Map F u L (incoming m d a n k A) (output m a n H) + (fun x v b => g (tile x v b)) (cost m d a n k A H) := by + have one : Map F u L (word d a n k A) H g (1 + (word d a n k A).width + H.width) := + Kernel.lookup fit allowed + have run := Map.vec _ (fun _ : B (m + (n + 1)) => Map.vec _ (fun _ : B a => one)) + refine ((Map.circuit hu prepare).comp run).mono ?_ + simp only [cost, output, Format.width_vec] + exact le_of_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window.Tile +end + +/- +# Printing child records from their parent bank + +The walk table and the mask of address coincidences are computed once +per host. Eight grouped reads share the long addresses across all groups. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window.Tile + +open Coloring + +/-- The value specified by `Format.pair (.vec (m + (n + 1)) .bit) (.pair .bit (.pair +(Neighborhood.Rows (m + (n + 1)) k) (Fmt.groups m d a A)))`. -/ +abbrev raw (m d a n k : ℕ) (A : Format) := + Format.pair (.vec (m + (n + 1)) .bit) (.pair .bit + (.pair (Neighborhood.Rows (m + (n + 1)) k) (Fmt.groups m d a A))) + +/-- The bound obtained by adding the component charges `24 * (raw m d a n k A).width + 4 * (2 ^ +m * (100 + (m + 2 ^ radius d)) ^ 20 + 2 ^ (m + (n + 1)) * (100 + t) ^ 40) + 9 * readCost m d +v N`. -/ +def bankCost (m d a n k : ℕ) (A : Format) (v N t : ℕ) := + 24 * (raw m d a n k A).width + + 4 * (2 ^ m * (100 + (m + 2 ^ radius d)) ^ 20 + 2 ^ (m + (n + 1)) * (100 + t) ^ 40) + + 9 * readCost m d v N + +variable {F : Type} [Field F] {u m d a n k v N t : ℕ} {L : Set (Table F)} {A H : Format} + +/-- Computes the fill by the application `bank x.1 x.2.1 x.2.2.1 x.2.2.2`. -/ +def fill (x : (raw m d a n k A).obj) : (incoming m d a n k A).obj := + bank x.1 x.2.1 x.2.2.1 x.2.2.2 + +variable {I : Type*} (hu : 3 ≤ u) (ht : Access F u L (m + d) v N) + (cap : 2 ^ a * (Walks 8 d A).width ≤ v) + (hm : m + (n + 1) ≤ t) (hq : 2 ^ (radius d + (n + 1)) ≤ t) (hk : 2 ^ k ≤ t) + (X : I → (raw m d a n k A).obj) + (recip : ∀ i, Fmt.Reciprocal (.vec a A) (X i).2.2.2) + +include hu ht cap hm hq hk recip + +theorem bank_net : + Computes F u L (raw m d a n k A) (incoming m d a n k A) X (fill ∘ X) (fun _ => 1) + (bankCost m d a n k A v N t) := by + let R := raw m d a n k A + let T := Format.vec (m + (n + 1)) .bit + let W := Neighborhood.Rows m d + let C := Neighborhood.Rows (m + (n + 1)) k + let G := Fmt.groups m d a A + let M := Format.pair T (.pair .bit (.pair (.pair W C) G)) + let nav (x : R.obj) : W.obj := fun i => (x.2.2.2 i).1 + let prepare (x : R.obj) : M.obj := (x.1, x.2.1, (nav x, x.2.2.1), x.2.2.2) + have pre : Circuit F R M prepare (R.width + 2 * M.width) := by + let idx : M.pins → R.pins + | .inl i => .inl i + | .inr (.inl i) => .inr (.inl i) + | .inr (.inr (.inl (.inl (i, j)))) => .inr (.inr (.inr (i, .inl j))) + | .inr (.inr (.inl (.inr i))) => .inr (.inr (.inl i)) + | .inr (.inr (.inr i)) => .inr (.inr (.inr i)) + exact Circuit.project idx (by rintro x (i | i | (⟨i, j⟩ | i) | i) <;> rfl) + obtain ⟨s, hs, h₁⟩ := Neighborhood.cheap_walks F m d 8 (by decide) + obtain ⟨p, hp, h₂⟩ := Child.cheap_mask F hm hq hk + have run := (hs.par (Circuit.id F C)).comp hp + have moves := reads_net hu ht (fun i => (X i).2.2.2) recip cap + have mask := Computes.of_map (x := fun i => (nav (X i), (X i).2.2.1)) + (Map.circuit (L := L) hu run) (fun _ => rfl) + have live := Computes.of_map (x := fun i => (X i).1) + (Map.circuit (L := L) hu (Circuit.id F T)) (fun _ => rfl) + have col := Computes.of_map (x := fun i => (X i).2.1) + (Map.circuit (L := L) hu (Circuit.id F .bit)) (fun _ => rfl) + have post := live.par (col.par (mask.par moves)) + have done := (Computes.of_map (x := X) (Map.circuit hu pre) (fun _ => rfl)).comp post + simp only [one_mul] at done + refine done.mono ?_ + have hr : R.width = T.width + Format.bit.width + C.width + G.width := by + simp only [R, raw, T, C, G, Format.width_pair] + omega + have hd : M.width = R.width + W.width := by + simp only [M, Format.width_pair, hr] + omega + have hv : W.width ≤ G.width := by + unfold W G Neighborhood.Rows Fmt.groups Fmt.bank + simp only [Format.width_vec, Format.width_pair] + exact Nat.mul_le_mul_left _ (Nat.le_add_right _ _) + change _ ≤ 24 * R.width + 4 * (2 ^ m * (100 + (m + 2 ^ ((d + 1) * 8))) ^ 20 + + 2 ^ (m + (n + 1)) * (100 + t) ^ 40) + 9 * readCost m d v N + omega + +theorem print_net (g : (word d a n k A).obj → H.obj) + (fit : (word d a n k A).width + H.width ≤ u) (ok : gate F g ∈ L) : + Computes F u L (raw m d a n k A) (output m a n H) X + (fun i w j => g (tile (fill (X i)) w j)) (fun _ => 1) + (bankCost m d a n k A v N t + cost m d a n k A H) := by + have b := bank_net hu ht cap hm hq hk X recip + have p := Computes.of_map (x := fill ∘ X) (y := fun i w j => g (tile (fill (X i)) w j)) + (computes hu g fit ok) (fun _ => rfl) + simpa only [mul_one] using b.comp p + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window.Tile +end + +/- # Comparing local windows from gathered records and child masks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window + +open Coloring + +variable {V W X : Type} {A : Format} {d h e ℓ a m m' k t r : ℕ} + +/-- The group coordinate stays fixed along each walk. The record +decoders are common to all host names and both environments. -/ +structure View (α : Env V X d h e ℓ) (loc : V ↪ B m × B a) (T : (Fmt.groups m d a A).obj) + (D : A.obj → (Match.Input d h e e ℓ).obj) (R : A.obj → B h → B e → Option (B d)) + (Z : A.obj → X) : Prop where + nav : ∀ v j, loc (α.nav v j) = ((T (loc v).1).1 j, (loc v).2) + data : ∀ v, α.data v = D ((T (loc v).1).2 (loc v).2) + recv : ∀ v, α.recv v = R ((T (loc v).1).2 (loc v).2) + extra : ∀ v, α.extra v = Z ((T (loc v).1).2 (loc v).2) + +variable {α : Env V X d h e ℓ} {β : Env W X d h e ℓ} {loc : V ↪ B m × B a} {loc' : W ↪ B m' × B a} + {T : (Fmt.groups m d a A).obj} {T' : (Fmt.groups m' d a A).obj} + {D : A.obj → (Match.Input d h e e ℓ).obj} {R : A.obj → B h → B e → Option (B d)} {Z : A.obj → X} + (H : View α loc T D R Z) (H' : View β loc' T' D R Z) + +include H in +theorem View.node (p : List (B d)) : + loc (α.node p) = (visit (fun v => (T v).1) (loc α.root).1 p, (loc α.root).2) := by + induction p with + | nil => rfl + | cons j p ih => rw [show α.node (j :: p) = α.nav (α.node p) j from rfl, H.nav, ih]; rfl + +variable {b : (Neighborhood.Rows (m + t) k).obj} {b' : (Neighborhood.Rows (m' + t) k).obj} + (hmask : Child.mask (Neighborhood.walks r (fun v => (T v).1)) b (loc α.root).1 = + Child.mask (Neighborhood.walks r (fun v => (T' v).1)) b' (loc' β.root).1) + +include H H' hmask + +theorem View.index_agree {v v' : V} {w w' : W} (hv : Related α β r v w) + (hv' : Related α β r v' w') (i j : B t) : + Child.index b ((Match.rowIndex m t).symm ((loc v).1, + i)) ((Match.rowIndex m t).symm ((loc v').1, j)) = + Child.index b' ((Match.rowIndex m' t).symm ((loc' w).1, i)) + ((Match.rowIndex m' t).symm ((loc' w').1, j)) := by + obtain ⟨p, hp, rfl, rfl⟩ := hv + obtain ⟨q, hq, rfl, rfl⟩ := hv' + simp only [H.node, H'.node] + exact Child.index_agree hmask hp hq i j + +theorem View.agree (hself : ∀ i, b i 0 = i) (hself' : ∀ i, b' i 0 = i) + (hr : (reads r T (loc α.root).1).2 (loc α.root).2 = + (reads r T' (loc' β.root).1).2 (loc' β.root).2) : Agree α β r := by + have recs (p : List (B d)) (hp : p.length ≤ r) : + (T (loc (α.node p)).1).2 (loc (α.node p)).2 = + (T' (loc' (β.node p)).1).2 (loc' (β.node p)).2 := by + obtain ⟨i, hi⟩ := Child.visit_slot p hp + simpa only [reads, hi, H.node, H'.node] using congrFun hr i + refine ⟨fun p q hp hq => ?_, fun p hp => ?_, fun p hp => ?_, fun p hp => ?_⟩ + · rw [← loc.injective.eq_iff, ← loc'.injective.eq_iff] + simp only [H.node, H'.node, Prod.mk.injEq, and_true] + exact Child.visit_agree hmask hp hq hself hself' + · rw [H.data, H'.data, recs p hp] + · rw [H.recv, H'.recv, recs p hp] + · rw [H.extra, H'.extra, recs p hp] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +end + +/- +# The window input for a grouped contraction + +The host record keeps the original pattern codes, the local selectors +and one matching input. The latter contains the neighboring interval +labels, with no long host name in a block record. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +open Coloring Packing + +variable {F : Type} (S : Scheme F) (a n b : ℕ) + +/-- The quantity computed by `Format.vec S.m (.vec a (.vec n (.addr (n + 1))))`. -/ +abbrev Tags := Format.vec S.m (.vec a (.vec n (.addr (n + 1)))) +/-- The quantity computed by `Format.pair S.format (.pair (Tags S a n) (.pair (.vec n .bit) +(Branches.format S.m a (n + S.e) b)))`. -/ +abbrev Fields := Format.pair S.format + (.pair (Tags S a n) (.pair (.vec n .bit) (Branches.format S.m a (n + S.e) b))) + +/-- The value specified by `Format.pair (.vec n (.addr S.ℓ)) (.pair (.vec (n + S.e) (.addr b)) +(Match.Input S.d n S.e S.e (n + 1)))`. -/ +abbrev Source := Format.pair (.vec n (.addr S.ℓ)) (.pair (.vec (n + S.e) (.addr b)) + (Match.Input S.d n S.e S.e (n + 1))) + +/-- The gather of type `(Fmt.groups S.m S.d a (Source S n b)).obj`, constructed using `(x.1 +v).1`. -/ +def gather (order : B a → B n → B S.h) (x : (Fields S a n b).obj) : + (Fmt.groups S.m S.d a (Source S n b)).obj := + fun v => + let nav := (x.1 v).1 + (nav, fun i => + let atom j := (x.1 v).2 (order i j) + (atom, fun j => x.2.2.2 ((v, i), j), x.2.2.1, + fun j => (x.2.1 v i j, (S.decode (atom j)).outgoing), + fun j w => x.2.1 (nav w) i j)) + +variable {n b} + +/-- Uses `x.2.2` as the representation. -/ +def matching (x : (Source S n b).obj) := x.2.2 + +/-- Transforms the indexed data by `((S.decode (x.1 j)).peer 0 i).map Prod.fst`. -/ +def receiving (x : (Source S n b).obj) (j : B n) (i : B S.e) := + ((S.decode (x.1 j)).peer 0 i).map Prod.fst + +/-- The indexed operation `(x.1, fun j => Branches.read P (x.2.1 j))`. -/ +def detail [Field F] (P : Gadget F) (x : (Source S n b).obj) : + Scheme.Posting.Detail S (ChoiceTag P) n := + (x.1, fun j => Branches.read P (x.2.1 j)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +end + +/- +# Forming the grouped window records + +Use one exchange for all neighboring labels. Pattern decoding is local +to one old occurrence. The other operations only copy or permute bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +open Coloring + +variable {F : Type} (S : Scheme F) (a n b : ℕ) + +open scoped Classical in +/-- Computes the outgoing by the application `Format.vec S.e (.pair .bit (.pair (.addr S.d) +(.addr S.e)))`. -/ +abbrev Outgoing := Format.vec S.e (.pair .bit (.pair (.addr S.d) (.addr S.e))) +open scoped Classical in +/-- The quantity computed by `Format.vec a (.vec n (.addr (n + 1)))`. -/ +abbrev LabelSet := Format.vec a (.vec n (.addr (n + 1))) +open scoped Classical in +private abbrev ByBlock (A : Format) := Format.vec S.m (.vec a (.vec n A)) +open scoped Classical in +private abbrev Remote := Format.vec S.m (.vec S.d (LabelSet a n)) + +open scoped Classical in +/-- Evaluates `((x.1 i).1, x.2.1 i)` at the input `i`. -/ +def labelBank (x : (Fields S a n b).obj) : (Fmt.bank S.m S.d (LabelSet a n)).obj := + fun i => ((x.1 i).1, x.2.1 i) + +open scoped Classical in +/-- The bound obtained by adding the component charges `gatherCost S.m S.d v N + 100 * ((Fields +S a n b).width + (Fmt.groups S.m S.d a (Source S n b)).width) + 2 ^ S.m * 2 ^ a * 2 ^ n * +p`. -/ +def collectCost (v N p : ℕ) := + gatherCost S.m S.d v N + 100 * ((Fields S a n b).width + + (Fmt.groups S.m S.d a (Source S n b)).width) + + 2 ^ S.m * 2 ^ a * 2 ^ n * p + +variable [Field F] {u v N p : ℕ} {L : Set (Table F)} {I : Type*} + +open scoped Classical in +/-- The outgoing gate of type `Table F` for the given inputs. -/ +def outgoingGate : Table F := + letI : DecidableEq (Outgoing S).obj := Classical.typeDecidableEq _ + lookup F (.addr S.ℓ) (Outgoing S) (fun i y => if (S.decode i).outgoing = y then 1 else 0) + +open scoped Classical in +theorem map_outgoing (fit : S.ℓ + (Outgoing S).width ≤ u) (ok : outgoingGate S ∈ L) : + Map F u L (.addr S.ℓ) (Outgoing S) (fun i => (S.decode i).outgoing) + (1 + S.ℓ + (Outgoing S).width) := by + have hw : (Format.addr S.ℓ).width + (Outgoing S).width ≤ u := by rwa [Format.width_addr] + have hg := Kernel.lookup hw ok + rw [Format.width_addr] at hg + exact hg + +open scoped Classical in +/-- The arbitrary function in the hypothesis is evaluated on one old +pattern code, independently of the number of hosts and blocks. -/ +theorem computes_gather (hu : 3 ≤ u) (ht : Access F u L (S.m + S.d) v N) + (cap : (LabelSet a n).width ≤ v) + (out : Map F u L (.addr S.ℓ) (Outgoing S) (fun i => (S.decode i).outgoing) p) + (order : B a → B n → B S.h) (X : I → (Fields S a n b).obj) + (recip : ∀ i, Fmt.Reciprocal (LabelSet a n) (labelBank S a n b (X i))) : + Computes F u L (Fields S a n b) (Fmt.groups S.m S.d a (Source S n b)) + X (gather S a n b order ∘ X) (fun _ => 1) (collectCost S a n b v N p) := by + let A := Fields S a n b + let H := Fmt.bank S.m S.d (LabelSet a n) + let C := ByBlock S a n (.addr S.ℓ) + let O := ByBlock S a n (Outgoing S) + let R := Remote S a n + let D := Fmt.groups S.m S.d a (Source S n b) + have label : Circuit F A H (labelBank S a n b) (A.width + 2 * H.width) := by + let pins : H.pins → A.pins + | (i, .inl t) => .inl (i, .inl t) + | (i, .inr t) => .inr (.inl (i, t)) + apply Circuit.project pins + rintro x ⟨i, t|t⟩ <;> rfl + let pattern (x : A.obj) : C.obj := fun i j k => (x.1 i).2 (order j k) + have locate : Circuit F A C pattern (A.width + 2 * C.width) := + Circuit.project (fun z => .inl (z.1, .inr (order z.2.1 z.2.2.1, z.2.2.2))) (fun _ _ => rfl) + have expand : Map F u L C O (fun x i j k => (S.decode (x i j k)).outgoing) + (2 ^ S.m * (2 ^ a * (2 ^ n * p))) := + Map.vec _ fun _ => Map.vec _ fun _ => Map.vec _ fun _ => out + let Y := labelBank S a n b ∘ X + have relay := (Computes.of_map (x := X) (y := Y) (Map.circuit (L := L) hu label) (fun _ + => rfl)).comp + (gather_neighbors (LabelSet a n) hu ht cap Y recip) + have keep := Computes.of_map (x := X) (y := X) (Map.circuit (L := L) hu (Circuit.id F A)) (fun _ + => rfl) + have localMap := (Map.circuit hu locate).comp expand + have middle := keep.pair hu ((Computes.of_map (x := X) localMap (fun _ => rfl)).pair hu relay) + let W := Format.pair A (.pair O R) + let join (x : W.obj) : D.obj := fun i => + ((x.1.1 i).1, fun j => + (pattern x.1 i j, fun t => x.1.2.2.2 ((i, j), t), x.1.2.2.1, + fun k => (x.1.2.1 i j k, x.2.1 i j k), fun k w => x.2.2 i w j k)) + have post : Circuit F W D join (W.width + 2 * D.width) := by + let pins : D.pins → W.pins + | (i, .inl s) => .inl (.inl (i, .inl s)) + | (i, .inr (j, .inl (k, s))) => .inl (.inl (i, .inr (order j k, s))) + | (i, .inr (j, .inr (.inl (t, s)))) => .inl (.inr (.inr (.inr ⟨((i, j), t), s⟩))) + | (_, .inr (_, .inr (.inr (.inl s)))) => .inl (.inr (.inr (.inl s))) + | (i, .inr (j, .inr (.inr (.inr (.inl (k, .inl s)))))) => .inl (.inr (.inl (i, j, k, s))) + | (i, .inr (j, .inr (.inr (.inr (.inl (k, .inr s)))))) => .inr (.inl (i, j, k, s)) + | (i, .inr (j, .inr (.inr (.inr (.inr (k, w, s)))))) => .inr (.inr (i, w, j, k, s)) + apply Circuit.project pins + rintro x ⟨i, s | ⟨j, ⟨k, s⟩ | ⟨t, s⟩ | s | ⟨k, s | s⟩ | ⟨k, w, s⟩⟩⟩ <;> rfl + have H' := middle.comp (Computes.of_map (Map.circuit hu post) (y := gather S a n b order ∘ X) + (fun _ => rfl)) + simp only [one_mul] at H' + refine H'.mono ?_ + have hsize : H.width + C.width + O.width + R.width ≤ D.width := by + simp only [H, C, O, R, D, Remote, LabelSet, ByBlock, Fmt.groups, Fmt.bank, Source, + Match.Input, Fmt.occ, Outgoing, Format.width_vec, Format.width_pair] + ring_nf + omega + change _ ≤ gatherCost _ _ _ _ + 100 * (A.width + D.width) + _ + rw [show W.width = A.width + (O.width + R.width) by simp only [W, Format.width_pair]] + simp only [mul_assoc, A] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +end + +/- +# Reading a state from its window tape + +The block permutation and the letter decoders are common to all terms. +The state supplies the chosen grouping, color and selectors. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing Window + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k b : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') + (order : B a → B (h - a) → B S.h) (x : (Fields S a (h - a) b).obj) + +open scoped Classical in +/-- The data for the supplied construction, including `old`, `closed`, `index`, `label`, +`color`. -/ +structure Supplied : Prop where + old : x.1 = u.r + closed : ∀ v j, (u.r (u.p.host v)).1 j ∈ Set.range u.p.host + index : ∀ v i, order (cellIndex a v) i = u.p.block ((splitCell a u.ha).symm (v, + (cellIndex _).symm i)) + label : ∀ v i j, x.2.1 (u.p.host v) (cellIndex a i) j = + Scheme.Posting.label a u.g (v, i) ((cellIndex _).symm j) + color : ∀ i, x.2.2.1 i = decide (thick u.m.color ((cellIndex _).symm i)) + choice : ∀ v i, Branches.read P (x.2.2.2 (u.p.placeGroup a v, i)) = u.selector (v, i) + +variable {u order x} (hs : u.Supplied order x) +include hs + +open scoped Classical in +theorem Supplied.navigate (v : u.G.V) (j : B S.d) : + u.p.host (u.p.nav v j) = (u.r (u.p.host v)).1 j := by + have h : ∃ w, u.p.host w = (u.r (u.p.host v)).1 j := hs.closed v j + rw [Scheme.Posting.nav, dite_eq_left h] + exact h.choose_spec + +open scoped Classical in +theorem Supplied.view : + Window.View u.env (u.p.placeGroup a) (Window.gather S a (h - a) b order x) + (Window.matching S) (Window.receiving S) (Window.detail S P) := by + let tape := Window.gather S a (h - a) b order x + have layer v i j : ((tape (u.p.host v)).2 (cellIndex a i)).1 j = + (u.r (u.p.host v)).2 (u.p.block ((splitCell a u.ha).symm (i, (cellIndex _).symm j))) := by + change (x.1 (u.p.host v)).2 (order (cellIndex a i) j) = _ + rw [hs.old, hs.index] + constructor + · rintro ⟨v, i⟩ j + change (u.p.host (u.p.nav v j), cellIndex a i) = ((x.1 (u.p.host v)).1 j, cellIndex a i) + rw [hs.old, hs.navigate] + · rintro ⟨v, i⟩ + change u.p.records a u.ha u.g u.m.color (v, i) = + (x.2.2.1, fun j => (x.2.1 (u.p.host v) (cellIndex a i) j, + (S.decode (((tape (u.p.host v)).2 (cellIndex a i)).1 j)).outgoing), + fun j w => x.2.1 ((x.1 (u.p.host v)).1 w) (cellIndex a i) j) + simp only [layer, hs.old, ← hs.navigate, hs.label, show x.2.2.1 = _ from funext hs.color] + rfl + · rintro ⟨v, i⟩ + funext j t + change _ = ((S.decode (((tape (u.p.host v)).2 (cellIndex a i)).1 j)).peer 0 t).map Prod.fst + rw [layer] + rfl + · rintro ⟨v, i⟩ + exact Prod.ext (funext fun j => (layer v i j).symm) (funext fun j => (hs.choice (v, i) j).symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # The short inputs that determine a local contraction record -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing Window + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k b : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') + +open scoped Classical in +/-- A parent-group record may include additional counters along with +the source packet. The last field allows the long host names to be +compared using short masks. -/ +structure Board (d : ℕ) (A : Format) (read : A.obj → (Source S (h - a) b).obj) where + /-- The `Board` component of type `(Fmt.groups S.m S.d a A).obj`. -/ + parent : (Fmt.groups S.m S.d a A).obj + /-- The `Board` component of type `(Neighborhood.Rows (S.m + ((h - a) + 1)) d).obj`. -/ + child : (Neighborhood.Rows (S.m + ((h - a) + 1)) d).obj + /-- The `Board` component of type `B (S.m + ((h - a) + 1)) → Bool`. -/ + live : B (S.m + ((h - a) + 1)) → Bool + self : ∀ i, child i 0 = i + view : Window.View u.env (u.p.placeGroup a) parent + (matching S ∘ read) (receiving S ∘ read) (detail S P ∘ read) + +variable {u} {v : State S P a h z Δ D k B'} {d : ℕ} {A : Format} + {read : A.obj → (Source S (h - a) b).obj} + +namespace Board +variable (p : u.Board d A read) + +open scoped Classical in +/-- Computes the tape by the application `Tile.bank p.live u.col p.child p.parent`. -/ +abbrev tape := Tile.bank p.live u.col p.child p.parent + +open scoped Classical in +/-- The quantity computed by `Child.host u.p.host (h - a) (t.1.1, t.2)`. -/ +def childAt (t : Site (u.G.V × Cell a) (h - a)) := + Child.host u.p.host (h - a) (t.1.1, t.2) + +open scoped Classical in +/-- Computes the look by the application `Tile.tile p.tape (childAt u.v) (cellIndex a u.v.1.2)`. -/ +def look := Tile.tile p.tape (childAt u.v) (cellIndex a u.v.1.2) + +open scoped Classical in +private theorem look_eq : + p.look = (p.live (childAt u.v), u.col, cellIndex a u.v.1.2, intervalCode _ u.v.2, + Child.mask (Neighborhood.walks 8 (fun w => (p.parent w).1)) p.child (u.p.host u.v.1.1), + (reads 8 p.parent (u.p.host u.v.1.1)).2 (cellIndex a u.v.1.2)) := + Tile.tile_at p.tape (u.p.placeGroup a u.v.1) (intervalCode _ u.v.2) + +variable {p} {q : v.Board d A read} + +open scoped Classical in +theorem agrees (he : p.look = q.look) : u.Same v 8 ∧ u.v.1.2 = v.v.1.2 := by + rw [look_eq, look_eq] at he + simp only [Prod.mk.injEq] at he + obtain ⟨_, hc, hg, hl, hm, hr⟩ := he + exact ⟨⟨p.view.agree q.view hm p.self q.self hr, hc, hl⟩, (cellIndex a).injective hg⟩ + +open scoped Classical in +theorem index_eq (he : p.look = q.look) + (x : Site (u.G.V × Cell a) (h - a)) (y : Site (v.G.V × Cell a) (h - a)) + (hr : Related u.env v.env 4 x.1 y.1) (hk : intervalCode _ x.2 = intervalCode _ y.2) : + Child.index p.child (childAt u.v) (childAt x) = Child.index q.child (childAt v.v) (childAt y) + := by + rw [look_eq, look_eq] at he + simp only [Prod.mk.injEq] at he + obtain ⟨_, _, _, hl, hm, _⟩ := he + have hi := p.view.index_agree q.view hm (related_root.widen (by decide)) (hr.widen (by decide)) + (intervalCode _ u.v.2) (intervalCode _ x.2) + exact hi.trans (congrArg₂ (fun i j => Child.index q.child (Tile.atHost (v.p.placeGroup a v.v.1) i) + (Tile.atHost (v.p.placeGroup a y.1) j)) hl hk) + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Canonical host, block, and span addresses for a contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State.Board +open Coloring Packing History Window + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k b : ℕ} {B' : ℝ} + {u : State S P a h z Δ D k B'} {d : ℕ} {A : Format} + {read : A.obj → (Source S (h - a) b).obj} + (p : u.Board d A read) + +open scoped Classical in +/-- Uses `⟨p.parent, p.child, p.live, p.self, ⟨p.view.nav, p.view.data, p.view.recv, +p.view.extra⟩⟩` as the representation. -/ +def recenter (v : Site (u.G.V × Cell a) (h - a)) : (u.recenter v).Board d A read := + ⟨p.parent, p.child, p.live, p.self, ⟨p.view.nav, p.view.data, p.view.recv, p.view.extra⟩⟩ + +open scoped Classical in +/-- The condition `∀ i, p.live i = true ↔ i ∈ Set.range (Child.host u.p.host (h - a))` on the +specified data. -/ +def Live : Prop := ∀ i, p.live i = true ↔ i ∈ Set.range (Child.host u.p.host (h - a)) + +variable {hz : 0 < z} {e : ℕ} (M : Book S P z hz) (room : u.Room e) (cap : ℕ) (le : Δ ≤ D) + +open scoped Classical in +/-- The assign of type `u.Assignment le (M.scheme (S.m + ((h - a) + 1)) d a e cap)`, constructed +using `Child.host u.p.host (h - a)`. -/ +abbrev assign : u.Assignment le (M.scheme (S.m + ((h - a) + 1)) d a e cap) := + let address := Child.host u.p.host (h - a) + ⟨address, (cellIndex a).toEmbedding, fun v w => Child.index p.child (address v) (address w), + fun v => (room.recenter v).visible⟩ + +open scoped Classical in +theorem look_at (v : Site (u.G.V × Cell a) (h - a)) : + Tile.tile p.tape ((p.assign M room cap le).vertex v).1 ((p.assign M room cap le).vertex v).2.1 = + (p.recenter v).look := rfl + +open scoped Classical in +theorem live_at (live : p.Live) (i : B (S.m + ((h - a) + 1))) (j : B a) : + p.live i = true ↔ (i, j, 0) ∈ Set.range (p.assign M room cap le).vertex := by + rw [live] + constructor + · rintro ⟨⟨v, w⟩, rfl⟩ + obtain ⟨b, rfl⟩ := (cellIndex a).surjective j + exact ⟨((v, b), w), rfl⟩ + · rintro ⟨v, hv⟩ + exact ⟨(v.1.1, v.2), congrArg Prod.fst hv⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State.Board +end + +/- +# Transport of charges to a contracted occurrence + +Agreement on the local records identifies the contributors to an +occurrence, counting each host once even if several walks reach it. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing Window Finset + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k b : ℕ} {B' : ℝ} + {u v : State S P a h z Δ D k B'} + +open scoped Classical in +theorem Same.route_iff (e : u.Same v 8) {i : u.H.V} {j : v.H.V} + (hr : Related u.env v.env 2 i j) (t : Cell (h - a)) : + u.g.route u.m u.col i t = u.v ↔ v.g.route v.m v.col j t = v.v := by + let w := e.agree.restrict (by decide : 4 ≤ 8) + have center : Names u.env v.env (u.c.site u.v) (v.c.site v.v) := + ⟨related_root.widen (by decide), e.key⟩ + have move : Names u.env v.env + (u.c.site (u.g.route u.m u.col i t)) (v.c.site (v.g.route v.m v.col j t)) := by + have hm := w.motion hr u.col (cellIndex _ t) + have hv := v.c.moved v.col j t + rw [← e.layout] at hv + rw [← e.layout] + exact (u.c.moved u.col i t) ▸ hv ▸ hm + have same_site := w.identical move center + exact u.c.site.injective.eq_iff.symm.trans (same_site.trans v.c.site.injective.eq_iff) + +namespace Board +variable {d : ℕ} {A : Format} {read : A.obj → (Source S (h - a) b).obj} + {p : u.Board d A read} {q : v.Board d A read} + +open scoped Classical in +/-- Agreement preserves the complete parent record, including any counters +in addition to the fields consumed by the history decoder. -/ +theorem source_eq (he : p.look = q.look) {i : u.H.V} {j : v.H.V} + (hr : Related u.env v.env 2 i j) : + (p.parent (u.p.placeGroup a i).1).2 (u.p.placeGroup a i).2 = + (q.parent (v.p.placeGroup a j).1).2 (v.p.placeGroup a j).2 := by + obtain ⟨path, hp, rfl, rfl⟩ := hr + have ha := Tile.tile_at p.tape (u.p.placeGroup a u.v.1) (intervalCode _ u.v.2) + have hb := Tile.tile_at q.tape (v.p.placeGroup a v.v.1) (intervalCode _ v.v.2) + have hrec := congrArg (fun z => z.2.2.2.2.2) (ha.symm.trans (he.trans hb)) + change (reads 8 p.parent (u.p.placeGroup a u.env.root).1).2 (u.p.placeGroup a u.env.root).2 = + (reads 8 q.parent (v.p.placeGroup a v.env.root).1).2 (v.p.placeGroup a v.env.root).2 at hrec + obtain ⟨t, ht⟩ := Child.visit_slot path (hp.trans (by decide : 2 ≤ 8)) + simpa only [reads, ht, p.view.node, q.view.node] using congrFun hrec t + +open scoped Classical in +private def inbound (u : State S P a h z Δ D k B') := + univ.filter fun t : u.H.V × Cell (h - a) => u.g.route u.m u.col t.1 t.2 = u.v + +open scoped Classical in +private theorem inbound_eq (u : State S P a h z Δ D k B') (l : u.H.V × Cell (h - a) → ℝ) : + push (Function.uncurry (u.g.route u.m u.col)) l u.v = ∑ i ∈ inbound u, l i := by + unfold Packing.push inbound + rw [sum_filter] + apply sum_congr rfl + rintro ⟨i, b⟩ _ + by_cases he : u.g.route u.m u.col i b = u.v <;> simp [he] + +open scoped Classical in +private theorem counterpart (e : u.Same v 8) (i : u.H.V × Cell (h - a)) (hi : i ∈ inbound u) : + ∃ j ∈ inbound v, Related u.env v.env 2 i.1 j.1 ∧ i.2 = j.2 := by + have hloc := (mem_filter.mp hi).2 + have place : (u.g.route u.m u.col i.1 i.2).1 = u.v.1 := congrArg Prod.fst hloc + have win : i.1 ∈ u.env.issuers := + (congrArg (fun x => i.1 ∈ u.q.neighborhood x) place).mp (u.q.window_move u.g u.m u.col i.1 i.2) + obtain ⟨j, _, hj⟩ := Related.issuers (β := v.env) win + exact ⟨(j, i.2), mem_filter.mpr ⟨mem_univ _, (e.route_iff hj _).mp hloc⟩, hj, rfl⟩ + +open scoped Classical in +/-- Pushforward adds the charges on the entire fiber of the receiving site. -/ +theorem push_eq (he : p.look = q.look) (l : u.H.V × Cell (h - a) → ℝ) (r : v.H.V × Cell (h - a) → ℝ) + (agree : ∀ i j, Related u.env v.env 2 i j → ∀ t, l (i, t) = r (j, t)) : + push (Function.uncurry (u.g.route u.m u.col)) l u.v = + push (Function.uncurry (v.g.route v.m v.col)) r v.v := by + have e := (agrees he).1 + have same {i i' : u.H.V} {j j' : v.H.V} + (hi : Related u.env v.env 2 i j) (hj : Related u.env v.env 2 i' j') : + i = i' ↔ j = j' := (e.agree.restrict (by decide : 2 ≤ 8)).equal hi hj + choose f hf hrel hblk using counterpart e + rw [inbound_eq, inbound_eq] + apply sum_bij f hf + · intro i hi j hj eq + exact Prod.ext ((same (hrel _ hi) (hrel _ hj)).mpr (congrArg Prod.fst eq)) + ((hblk _ hi).trans ((congrArg Prod.snd eq).trans (hblk _ hj).symm)) + · intro j hj + obtain ⟨i, hi, ⟨path, hs, hj', hi'⟩, hb⟩ := counterpart e.symm j hj + have h : Related u.env v.env 2 i.1 j.1 := ⟨path, hs, hi', hj'⟩ + exact ⟨i, hi, Prod.ext ((same (hrel _ hi) h).mp rfl) ((hblk _ hi).symm.trans hb.symm)⟩ + · intro i hi + exact (agree _ _ (hrel i hi) i.2).trans (congrArg (fun b => r ((f i hi).1, b)) (hblk i hi)) + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # One local lookup table for every reachable contraction branch -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State.Board +open Coloring Packing History Window + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k b : ℕ} {B' : ℝ} + {d : ℕ} {A : Format} {read : A.obj → (Source S (h - a) b).obj} + {hz : 0 < z} {e : ℕ} (M : Book S P z hz) (cap : ℕ) (le : Δ ≤ D) + {I : Type*} (U : I → State S P a h z Δ D k B') + (board : ∀ i, (U i).Board d A read) (room : ∀ i, (U i).Room e) + {Y : Type} (blank : Y) + (post : I → B (S.m + ((h - a) + 1)) → B a → (Post.record d e M.d (.addr cap)).obj → Y) + +open scoped Classical in +theorem print_table (live : ∀ i, (board i).Live) + (agree : ∀ i j t u, ((board i).recenter t).look = ((board j).recenter u).look → + ∀ v, post i (childAt t) (cellIndex a t.1.2) v = post j (childAt u) (cellIndex a u.1.2) v) + (vacant : ∀ i x y, (board i).live x = false → post i x y Post.vacant = blank) : + ∃ f : (Tile.word S.d a (h - a) d A).obj → Y, ∀ i x y, + f (Tile.tile (board i).tape x y) = + post i x y ((U i).records M (room i) cap ((board i).assign M (room i) cap le) x y) := by + let g i := (board i).assign M (room i) cap le + have ranked (i : I) : (U i).Ranked (g i) := + fun v j => visible_index ((room i).recenter v) j + let J := Σ i : I, Site ((U i).G.V × Cell a) (h - a) + let key (x : J) := ((board x.1).recenter x.2).look + let value (x : J) := post x.1 (childAt x.2) (cellIndex a x.2.1.2) + (((U x.1).recenter x.2).localRecord M ((room x.1).recenter x.2) cap (g x.1)) + have eqn : Function.FactorsThrough value key := by + rintro ⟨i, t⟩ ⟨j, u⟩ he + change ((board i).recenter t).look = ((board j).recenter u).look at he + have H := (agrees he).1.localRecord (le_refl 8) M ((room i).recenter t) ((room j).recenter u) + cap (g i) (g j) (index_eq he) (ranked i) (ranked j) + exact (congrArg _ H).trans (agree i j t u he _) + let f := Function.extend key value (fun _ => blank) + refine ⟨f, fun i x y => ?_⟩ + have ht := (board i).live_at M (room i) cap le (live i) x y + by_cases hl : (board i).live x = true + · obtain ⟨t, he⟩ := ht.mp hl + have h₁ : ((g i).vertex t).1 = x := congrArg Prod.fst he + have h₂ : ((g i).vertex t).2.1 = y := congrArg (fun z => z.2.1) he + rw [← h₁, ← h₂] + exact (eqn.extend_apply (fun _ => blank) ⟨i, t⟩).trans + (congrArg _ ((U i).record_at M (room i) cap (g i) t).symm) + · have he : Tile.tile (board i).tape x y ∉ Set.range key := by + rintro ⟨⟨j, t⟩, hq⟩ + have hq' : (board j).live (childAt t) = (board i).live x := congrArg Prod.fst hq + exact hl (hq' ▸ (live j _).mpr ⟨(t.1.1, t.2), rfl⟩) + have hv : (U i).records M (room i) cap (g i) x y = Post.vacant := + (g i).record_vacant _ _ (x, y, 0) (mt ht.mpr hl) + exact (Function.extend_apply' _ _ _ he).trans + ((congrArg _ hv).trans (vacant i x y (Bool.eq_false_iff.mpr hl))).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State.Board +end + +/- # Cost of producing every child record with one additional table label -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State.Board +open Coloring Packing History Window + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k b : ℕ} {B' : ℝ} + {u : State S P a h z Δ D k B'} {d : ℕ} {A : Format} + {read : A.obj → (Source S (h - a) b).obj} + +open scoped Classical in +/-- The value specified by `(p.live, u.col, p.child, p.parent)`. -/ +def raw (p : u.Board d A read) : (Tile.raw S.m S.d a (h - a) d A).obj := + (p.live, u.col, p.child, p.parent) + +variable {hz : 0 < z} {e : ℕ} (M : Book S P z hz) (cap : ℕ) (le : Δ ≤ D) + {I : Type*} (U : I → State S P a h z Δ D k B') + (board : ∀ i, (U i).Board d A read) (room : ∀ i, (U i).Room e) + (Y : Format) (blank : Y.obj) + (post : I → B (S.m + ((h - a) + 1)) → B a → (Post.record d e M.d (.addr cap)).obj → Y.obj) + +open scoped Classical in +/-- The table is fixed for the entire family, before choosing the +routing bound or admissible dictionary. -/ +theorem print_net (live : ∀ i, (board i).Live) + (agree : ∀ i j t u, ((board i).recenter t).look = ((board j).recenter u).look → + ∀ v, post i (childAt t) (cellIndex a t.1.2) v = post j (childAt u) (cellIndex a u.1.2) v) + (vacant : ∀ i x y, (board i).live x = false → post i x y Post.vacant = blank) + (recip : ∀ i, Fmt.Reciprocal (.vec a A) (board i).parent) : + ∃ table : Table F, wd table.1 + wd table.2.1 = (Tile.word S.d a (h - a) d A).width + Y.width ∧ + ∀ {u v N t : ℕ} {L : Set (Table F)}, + 3 ≤ u → table ∈ L → (Tile.word S.d a (h - a) d A).width + Y.width ≤ u → + Access F u L (S.m + S.d) v N → 2 ^ a * (Walks 8 S.d A).width ≤ v → + S.m + ((h - a) + 1) ≤ t → 2 ^ (Tile.radius S.d + ((h - a) + 1)) ≤ t → 2 ^ d ≤ t → + Computes F u L (Tile.raw S.m S.d a (h - a) d A) (Tile.output S.m a (h - a) Y) + (fun i => (board i).raw) + (fun i x y => post i x y ((U i).records M (room i) cap ((board i).assign M (room i) cap le) + x y)) + (fun _ => 1) (Tile.bankCost S.m S.d a (h - a) d A v N t + + Tile.cost S.m S.d a (h - a) d A Y) := by + obtain ⟨f, hf⟩ := print_table M cap le U board room blank post live agree vacant + refine ⟨Tile.gate F (H := Y) f, by simp only [Tile.gate, lookup, wd_word], ?_⟩ + intro u v N t L hu allowed fit access send hm hq hd + have H := Tile.print_net hu access send hm hq hd (fun i => (board i).raw) recip f fit allowed + have eqn : (fun i x y => f (Tile.tile (Tile.fill (board i).raw) x y)) = + fun i x y => post i x y ((U i).records M (room i) cap ((board i).assign M (room i) cap le) x + y) := + funext fun i => funext fun x => funext fun y => hf i x y + rwa [eqn] at H + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State.Board +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Checks.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Checks.lean new file mode 100644 index 0000000000..19a1cca839 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Checks.lean @@ -0,0 +1,918 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Entry +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.FieldLift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.RestoreCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.Model + +/-! +# Standardized factors of a wire-saving step + +An old station is named by its pattern and its station index. A +six-party role is named by one selector and a site number. A product +of untouched wire checks only needs its number of incidences. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +open Coloring Packing Spectral.Tensor + +variable {F : Type} [Field F] (S : Scheme F) (P : Gadget F) (z : ℕ) (hz : 0 < z) + +open Classical in +/-- Indexes the role by the coordinates of `(Fin P.copies × ↥P.shapes) × Fin 6`. -/ +abbrev Role := (Fin P.copies × ↥P.shapes) × Fin 6 +open Classical in +/-- Indexes the kind by the coordinates of `(B S.ℓ × B S.k) ⊕ Role P ⊕ B c`. -/ +abbrev Kind (c : ℕ) := (B S.ℓ × B S.k) ⊕ Role P ⊕ B c + +open Classical in +/-- Builds `Atom F where Span` with the specified `Span`, `width`, `weight`. -/ +def original (p : B S.ℓ × B S.k) : Atom F where + Span := B S.e + width := (S.decode p.1).width p.2 + weight := (S.decode p.1).value p.2 + +namespace Role +variable {P} (r : Role P) + +open Classical in +/-- The subtype of `q : Fin 2 × Bool` satisfying `(if q.2 then (sixDemandPair q.1).2 else +(sixDemandPair q.1).1) = r.2`. -/ +abbrev Demand := {q : Fin 2 × Bool // + (if q.2 then (sixDemandPair q.1).2 else (sixDemandPair q.1).1) = r.2} + +open Classical in +/-- The subtype of `q : Σ j : Fin 8, Fin (r.1.2.val j)` satisfying `(sixPair q.1).1 = r.2 ∨ +(sixPair q.1).2 = r.2`. -/ +abbrev Supply := {q : Σ j : Fin 8, Fin (r.1.2.val j) // + (sixPair q.1).1 = r.2 ∨ (sixPair q.1).2 = r.2} + +open Classical in +/-- Indexes the port by the coordinates of `r.Demand ⊕ r.Supply`. -/ +abbrev Port := r.Demand ⊕ r.Supply +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def width : r.Port → ℕ := Sum.elim (fun _ => P.b * z) (fun _ => z) + +variable {z} + +open Classical in +/-- Selects the appropriate branch of `if h : (if s then (sixDemandPair q.1).2 else +(sixDemandPair q.1).1) = r.2 then x (.inl ⟨(q.1, s), h⟩) q.2 else false`. -/ +def demands (x : ∀ j : r.Port, Fin (width z r j) → Bool) (s : Bool) + (q : Fin 2 × Fin (P.b * z)) : Bool := + if h : (if s then (sixDemandPair q.1).2 else (sixDemandPair q.1).1) = r.2 + then x (.inl ⟨(q.1, s), h⟩) q.2 else false + +open Classical in +/-- The supplies of type `Bool` for the given inputs. -/ +def supplies (x : ∀ j : r.Port, Fin (width z r j) → Bool) + (q : Σ j : Fin 8, Fin (r.1.2.val j * z)) : Bool := + if h : (sixPair q.1).1 = r.2 ∨ (sixPair q.1).2 = r.2 + then x (.inr ⟨⟨q.1, (finProdFinEquiv.symm q.2).1⟩, h⟩) (finProdFinEquiv.symm q.2).2 + else false + +open Classical in +/-- Builds `Atom F where Span` with the specified `Span`, `width`, `weight`. -/ +def atom (hz : 0 < z) : Atom F where + Span := r.Port + width := width z r + weight x := (P.packet z hz).rule.entry r.1 r.2 (r.demands x false) (r.demands x true) (r.supplies + x) + +open Classical in +theorem eval (hz : 0 < z) (x : ∀ j : r.Port, Fin (width z r j) → Bool) + (L R : Fin 2 × Fin (P.b * z) → Bool) (U : (Σ j : Fin 8, Fin (r.1.2.val j * z)) → Bool) + (hd : ∀ (p : r.Demand) t, x (.inl p) t = (if p.1.2 then R else L) (p.1.1, t)) + (hs : ∀ (p : r.Supply) t, x (.inr p) t = U ⟨p.1.1, finProdFinEquiv (p.1.2, t)⟩) : + (r.atom hz).weight x = (P.packet z hz).rule.entry r.1 r.2 L R U := by + apply (P.packet z hz).rule.local' + · rintro ⟨j, t⟩ h + simp only [demands, Bool.false_eq_true, ite_false, dite_eq_left h] + exact hd ⟨(j, false), h⟩ t + · rintro ⟨j, t⟩ h + simp only [demands, ite_true, dite_eq_left h] + exact hd ⟨(j, true), h⟩ t + · rintro ⟨j, t⟩ h + simp only [supplies, dite_eq_left h] + refine (hs ⟨⟨j, (finProdFinEquiv.symm t).1⟩, h⟩ (finProdFinEquiv.symm t).2).trans ?_ + exact congrArg (fun t => U ⟨j, t⟩) (finProdFinEquiv.apply_symm_apply t) + +end Role + +open Classical in +/-- Builds `Atom F where Span` with the specified `Span`, `width`, `weight`. -/ +def checks (n : ℕ) : Atom F where + Span := Fin n × Option (Fin P.b) + width j := j.2.elim (P.b * z) (fun _ => z) + weight x := if ∀ (j : Fin n) (b : Fin P.b) (t : Fin z), + x (j, none) (finProdFinEquiv (b, t)) = x (j, some b) t then 1 else 0 + +open Classical in +/-- In the case `.inl p`, this construction gives `original S p`. -/ +def kind {c : ℕ} : Kind S P c → Atom F + | .inl p => original S p + | .inr (.inl r) => r.atom hz + | .inr (.inr q) => checks P z q.val + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +end + +/- # A live tether carries at least one complete exterior span -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Packing +variable {F T : Type} [Field F] {x y : Wire} {L : Fringe x y T} + {h u : ℕ} {H : HostNet F L h u} {S : Scheme F} {r : S.format.obj} + (p : S.Presentation r H.diagram) + +open scoped Classical in +theorem contacts {n : ℕ} (h : ∀ j, n ≤ p.borderWidth j) (i : slots x ⊕ slots y) : + n ≤ H.tetherLoad (H.far i) := by + obtain ⟨⟨j, t⟩, rfl⟩ := p.exteriorBits.surjective i + have eqn (t) : H.far (p.exteriorBits ⟨j, t⟩) = H.units.place j.val.1 := + congrArg H.units.place (p.border_station _) + rw [eqn] + let w := H.units.place j.val.1 + let e (t : Fin (p.borderWidth j)) : {q // H.far q = w} := ⟨p.exteriorBits ⟨j, t⟩, eqn t⟩ + have he : Function.Injective e := by + intro l k hh + exact eq_of_heq (Sigma.mk.inj (p.exteriorBits.injective (congrArg Subtype.val hh))).2 + have hc := Fintype.card_le_of_injective e he + rw [Fintype.card_fin] at hc + refine ((h j).trans hc).trans_eq ?_ + apply Nat.cast_injective (R := ℝ) + rw [HostNet.tetherLoad, port_load] + change _ = push H.far (fun _ => 1) w + simp only [push, Finset.sum_boole, Fintype.card_subtype] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- # Assigning the exposed spans and arguments to a new record -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +open Coloring Packing + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z a : ℕ} + (P : Gadget F) (G : HostNet F L h (P.b * z)) + {Δ D k : ℕ} {B' : ℝ} (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (i : g.Choice m P) + {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G.diagram) + (q : G.Projection Δ D a) (U : Scheme F) + +open scoped Classical in +/-- Outgoing and incoming spans share one local address list. -/ +structure Allocation where + /-- Embeds the coordinates as `q.W ↪ B U.m`. -/ + host : q.W ↪ B U.m + /-- Embeds the coordinates as `Cell a ↪ B U.h`. -/ + block : Cell a ↪ B U.h + /-- The identification of the indices of type `q.W → q.W → B U.d`. -/ + index : q.W → q.W → B U.d + /-- Embeds the coordinates as `∀ v, Visible g m P G.units i p v ↪ B U.e`. -/ + seat : ∀ v, Visible g m P G.units i p v ↪ B U.e + +namespace Allocation +variable {P G g m i p q U} (A : Allocation P G g m i p q U) + +open scoped Classical in +/-- Embeds `Site G.V h` into `U.Vtx where toFun v`. -/ +def vertex : Site G.V h ↪ U.Vtx where + toFun v := (A.host (q.place v).1, A.block (q.place v).2, 0) + inj' _ _ he := q.place.injective (Prod.ext (A.host.injective (Prod.mk.inj he).1) + (A.block.injective (Prod.mk.inj (Prod.mk.inj he).2).1)) + +local notation "atSite" => whereAt g m P G.units i p + +open scoped Classical in +/-- The value specified by `A.seat (atSite j) ⟨j, rfl⟩`. -/ +def slot (j : Face g m P i p) := A.seat (atSite j) ⟨j, rfl⟩ + +open scoped Classical in +theorem slot_eq (v : Site G.V h) (j : Visible g m P G.units i p v) : + A.slot j.val = A.seat v j := by + obtain ⟨j, rfl⟩ := j + rfl + +open scoped Classical in +/-- The value specified by `(A.vertex (atSite j), A.slot j)`. -/ +def span (j : Face g m P i p) : U.Span := (A.vertex (atSite j), A.slot j) + +open scoped Classical in +theorem span_injective : Function.Injective A.span := + U.span_injective atSite A.vertex A.seat A.slot A.slot_eq + +open scoped Classical in +/-- The data for the lengths construction, including `used`, `idle`. -/ +structure Lengths (out : U.format.obj) : Prop where + used : ∀ j, U.width out (A.span j) = visibleWidth g m P i p z j + idle : ∀ t ∉ Set.range A.span, U.width out t = 0 + +variable {out : U.format.obj} (l : A.Lengths out) + +include l in +open scoped Classical in +theorem length_at (v : Site G.V h) (j : Visible g m P G.units i p v) : + U.width out (A.vertex v, A.seat v j) = visibleWidth g m P i p z j.val := by + obtain ⟨j, rfl⟩ := j + exact l.used j + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def orderPins (v : Site G.V h) : + (Σ j : Visible g m P G.units i p v, Fin (visibleWidth g m P i p z j.val)) ≃ + U.LocalPin out (A.vertex v) := + U.orderPins out atSite A.vertex A.seat A.slot A.slot_eq (visibleWidth g m P i p z) + v (A.length_at l v) l.idle + +open scoped Classical in +/-- Reindexes `(g.contract m P G.units hz i).Port v` and `U.LocalPin out (A.vertex v)` by an +equivalence. -/ +def pin (hz : 0 < z) (v : Site G.V h) : + (g.contract m P G.units hz i).Port v ≃ U.LocalPin out (A.vertex v) := + (visibleBits g m P G.units hz i p v).symm.trans (A.orderPins l v) + +open scoped Classical in +theorem pin_at (hz : 0 < z) (v : Site G.V h) (j : Visible g m P G.units i p v) + (k : Fin (visibleWidth g m P i p z j.val)) : + A.pin l hz v (visibleBits g m P G.units hz i p v ⟨j, k⟩) = + ⟨A.seat v j, k.cast (A.length_at l v j).symm⟩ := by + rw [pin, Equiv.trans_apply, Equiv.symm_apply_apply] + rfl + +end Allocation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +end + +/- +# Span addresses in a matched subround + +Demands and merged supplies have the same hidden address at both +ends. A surviving supply and an exterior span keep their visible +offsets. These statements also cover wires whose ends coincide. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.PortMap + +open Packing + +variable {F V E : Type} [Field F] [Fintype V] [Fintype E] {a b : Wire} + {N C : V → Finset V} {Δ D h k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (P : Gadget F) {G : Diagram F a b} {z : ℕ} + (s : Bundles G src dst ix (P.b * z)) (i : g.Choice m P) + {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G) (v : Site V h) + +open scoped Classical in +/-- Indexes the port by the coordinates of `Visible g m P s i p v ⊕ Hidden g m P i v`. -/ +abbrev Port := Visible g m P s i p v ⊕ Hidden g m P i v + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def width : Port g m P s i p v → ℕ := + Sum.elim (fun j => visibleWidth g m P i p z j.val) (fun j => segmentWidth g m P i z j.val) + +open scoped Classical in +/-- In the case `.inl q, b`, this construction gives `.inl (faceBits g m P s hz i p ⟨q.val, +b⟩)`. -/ +def bit (hz : 0 < z) : (j : Port g m P s i p v) → Fin (width g m P s i p v j) → + Bit (cluster g m P s hz i) + | .inl q, b => .inl (faceBits g m P s hz i p ⟨q.val, b⟩) + | .inr q, b => .inr ⟨v, hiddenBits g m P s hz i v ⟨q, b⟩⟩ + +open scoped Classical in +/-- The value specified by `.inl ⟨.inl x, he⟩`. -/ +def exterior (x : p.BorderSpan) (he : g.assign m P s i x.val.1 = v) : Port g m P s i p v := + .inl ⟨.inl x, he⟩ + +open scoped Classical in +theorem width_exterior (x : p.BorderSpan) (he : g.assign m P s i x.val.1 = v) : + width g m P s i p v (exterior g m P s i p v x he) = p.borderWidth x := rfl + +open scoped Classical in +/-- The value specified by `.inr ⟨cond t (.inr (.inl e)) (.inl e), by cases t <;> exact Prod.ext +he he⟩`. -/ +def demand (e : E) (t : Bool) + (he : g.route m (g.layout m P i) (cond t (dst e) (src e)) (ix e) = v) : Port g m P s i p v := + .inr ⟨cond t (.inr (.inl e)) (.inl e), by cases t <;> exact Prod.ext he he⟩ + +open scoped Classical in +theorem width_demand (e : E) (t : Bool) + (he : g.route m (g.layout m P i) (cond t (dst e) (src e)) (ix e) = v) : + width g m P s i p v (demand g m P s i p v e t he) = P.b * z := by cases t <;> rfl + +open scoped Classical in +/-- Computes the supply site by the application `cond t (g.contact m (g.layout m P i) e).2 +(g.contact m (g.layout m P i) e).1`. -/ +abbrev supplySite (e : g.Supply m P i) (t : Bool) := + cond t (g.contact m (g.layout m P i) e).2 (g.contact m (g.layout m P i) e).1 + +open scoped Classical in +/-- The supply of type `Port g m P s i p v` for the given inputs. -/ +def supply (e : g.Supply m P i) (t : Bool) (he : supplySite g m P i e t = v) : + Port g m P s i p v := + if h : (g.contact m (g.layout m P i) e).1 = (g.contact m (g.layout m P i) e).2 + then .inr ⟨.inr (.inr e), by + cases t + · exact Prod.ext he (h.symm.trans he) + · exact Prod.ext (h.trans he) he⟩ + else .inl ⟨.inr (⟨e, h⟩, t), he⟩ + +open scoped Classical in +theorem width_supply (e : g.Supply m P i) (t : Bool) (he : supplySite g m P i e t = v) : + width g m P s i p v (supply g m P s i p v e t he) = z := by + unfold supply + split <;> rfl + +variable (hz : 0 < z) +local notation "H" => cluster g m P s hz i + +open scoped Classical in +theorem address_exterior (x : p.BorderSpan) (he : g.assign m P s i x.val.1 = v) + (j : Fin (p.borderWidth x)) : + address H (old g m P s hz i (boundaryEnd G (p.exteriorBits ⟨x, j⟩))) = + bit g m P s i p v hz (exterior g m P s i p v x he) (j.cast (width_exterior g m P s i p v x + he).symm) := by + change _ = (Sum.inl (boundaryEnd (g.contract m P s hz i) (p.exteriorBits ⟨x, j⟩)) : Bit H) + cases p.exteriorBits ⟨x, j⟩ <;> rfl + +open scoped Classical in +private theorem address_internal (q : Hidden g m P i v) (j : Fin (segmentWidth g m P i z q.val)) + (t : Bool) : + let b := segmentBits g m P s hz i ⟨q.val, j⟩ + address H (cond t (.inr (.inr b)) (.inl (.inr b))) = + .inr ⟨v, hiddenBits g m P s hz i v ⟨q, j⟩⟩ := by + have e : (H).edges.symm (segmentBits g m P s hz i ⟨q.val, j⟩) = + .inr ⟨v, hiddenBits g m P s hz i v ⟨q, j⟩⟩ := + (H).edges.symm_apply_eq.mpr rfl + cases t <;> simp only [cond, address, e, Sum.map_inr, id_eq] + +open scoped Classical in +theorem address_demand_old (e : E) (t : Bool) + (he : g.route m (g.layout m P i) (cond t (dst e) (src e)) (ix e) = v) (j : Fin (P.b * z)) : + let b := s.bits.symm (e, j) + address H (old g m P s hz i (cond t (.inr (.inr b)) (.inl (.inr b)))) = + bit g m P s i p v hz (demand g m P s i p v e t he) (j.cast (width_demand g m P s i p v e t + he).symm) := by + cases t + · exact address_internal g m P s i v hz ⟨.inl e, Prod.ext he he⟩ j false + · exact address_internal g m P s i v hz ⟨.inr (.inl e), Prod.ext he he⟩ j true + +open scoped Classical in +theorem address_demand_new (e : E) (t : Bool) + (he : g.route m (g.layout m P i) (cond t (dst e) (src e)) (ix e) = v) (j : Fin (P.b * z)) : + let b := s.bits.symm (e, j) + address H (cond t (right g m P s hz i b) (left g m P s hz i b)) = + bit g m P s i p v hz (demand g m P s i p v e t he) (j.cast (width_demand g m P s i p v e t + he).symm) := by + cases t + · exact address_internal g m P s i v hz ⟨.inl e, Prod.ext he he⟩ j true + · exact address_internal g m P s i v hz ⟨.inr (.inl e), Prod.ext he he⟩ j false + +open scoped Classical in +theorem bit_congr {x y : Port g m P s i p v} (h : x = y) + {u : Fin (width g m P s i p v x)} {w : Fin (width g m P s i p v y)} (e : u.val = w.val) : + bit g m P s i p v hz x u = bit g m P s i p v hz y w := by + subst y + rw [Fin.ext e] + +open scoped Classical in +theorem address_supply (e : g.Supply m P i) (t : Bool) (he : supplySite g m P i e t + = v) (j : Fin z) : + address H (Subround.supply g m P s hz i (cond t (g.supplies m e).2 (g.supplies m e).1) (e, j)) = + bit g m P s i p v hz (supply g m P s i p v e t he) (j.cast (width_supply g m P s i p v e t + he).symm) := by + let c := g.layout m P i + by_cases h : (g.contact m c e).1 = (g.contact m c e).2 + · have hh : g.contact m c e = (v, v) := by + cases t + · exact Prod.ext he (h.symm.trans he) + · exact Prod.ext (h.trans he) he + let q : Hidden g m P i v := ⟨.inr (.inr e), hh⟩ + have eq : supply g m P s i p v e t he = .inr q := dite_eq_left h + refine Eq.trans ?_ (bit_congr g m P s i p v hz eq.symm (u := j) rfl) + unfold Subround.supply + split + · exact address_internal g m P s i v hz q j false + · exact address_internal g m P s i v hz q j true + · let r : g.Survivors m P i := ⟨e, h⟩ + let q : Visible g m P s i p v := ⟨.inr (r, t), he⟩ + have eq : supply g m P s i p v e t he = .inl q := dite_eq_right h + refine Eq.trans ?_ (bit_congr g m P s i p v hz eq.symm (u := j) rfl) + have hn : (g.supplies m e).1 ≠ (g.supplies m e).2 := by + rw [← g.locate_supply m c e] at h + exact fun hh => h (congrArg (g.locate m c) hh) + have hx : (H).edges.symm (.inr (.inr (e, j))) = .inl (g.remaining m P s hz i (r, j)) := + (H).edges.symm_apply_eq.mpr rfl + cases t <;> simp only [cond, Subround.supply, hn, ↓reduceIte, address, hx] <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.PortMap +end + +/- # Local argument maps for a contraction code -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +open Packing + +variable {F V E : Type} [Field F] [Fintype V] [Fintype E] {x y : Wire} + {N C : V → Finset V} {Δ D h k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (P : Gadget F) {G : Diagram F x y} {z : ℕ} + (s : Bundles G src dst ix (P.b * z)) (hz : 0 < z) (i : g.Choice m P) + {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G) (v : Site V h) + +open scoped Classical in +/-- Every nonempty span of the atom reads one full span in the new +station, either visible or summed over internally. -/ +structure AtomMap (a : History.Atom F) (u : (before g m P s hz i).V) where + /-- The `AtomMap` component of type `PortMap.Port g m P s i p v`. -/ + slot (j : a.Span) (h : 0 < a.width j) : PortMap.Port g m P s i p v + size (j) (h) : PortMap.width g m P s i p v (slot j h) = a.width j + value (w : Bit (cluster g m P s hz i) → Bool) : + a.weight (fun j t => w (PortMap.bit g m P s i p v hz + (slot j (Nat.zero_lt_of_lt t.isLt)) (t.cast (size _ _).symm))) = + factor (cluster g m P s hz i) u w + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +end + +/- # Span links for an actual six-party gadget -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +open Packing Spectral.Tensor + +variable {F : Type} [Field F] {P : Gadget F} + +open Classical in +/-- Tests whether `(sixPair p.val.1).2 = r.2` holds. -/ +def Role.side (r : Role P) (p : r.Supply) : Bool := + decide ((sixPair p.val.1).2 = r.2) + +open Classical in +theorem Role.end_eq (r : Role P) (p : r.Supply) : + cond (r.side p) (sixPair p.val.1).2 (sixPair p.val.1).1 = r.2 := by + by_cases h : (sixPair p.val.1).2 = r.2 + · simp [side, h] + · simpa [side, h] using p.property.resolve_right h + +namespace Subround + +variable {V E : Type} [Fintype V] [Fintype E] {a b : Wire} + {N C : V → Finset V} {Δ D h k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (P : Gadget F) {G : Diagram F a b} {z : ℕ} + (s : Bundles G src dst ix (P.b * z)) (i : g.Choice m P) + {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G) (v : Site V h) + +local notation "col" => g.layout m P i + +open Classical in +theorem supply_at (e : g.Supply m P i) (t : Bool) : + PortMap.supplySite g m P i e t = + g.locate m col (cond t (g.supplies m e).2 (g.supplies m e).1) := by + have he := g.locate_supply m col e + cases t + · exact congrArg Prod.fst he.symm + · exact congrArg Prod.snd he.symm + +variable (e : m.items) (j : Fin 6) (hv : g.party m (g.layout m P i) e j = v) + +open Classical in +/-- The value specified by `(i e, j)`. -/ +abbrev role : Role P := (i e, j) +local notation "R" => role g m P i e j + +open Classical in +/-- The value specified by `.inl ⟨e, u.val⟩`. -/ +def roleEdge (u : (R).Supply) : g.Supply m P i := .inl ⟨e, u.val⟩ + +open Classical in +theorem match_demand (q : (R).Demand) : + let f := m.pairEdge (e, q.val.1) + g.route m col (cond q.val.2 (dst f) (src f)) (ix f) = g.party m col e j := by + rcases q with ⟨⟨q, d⟩, hq⟩ + have he := g.rep_demand m col e q + cases d + · change (sixDemandPair q).1 = j at hq + subst j + exact congrArg (fun p => g.route m col p.1 p.2) (congrArg Prod.fst he.symm) + · change (sixDemandPair q).2 = j at hq + subst j + exact congrArg (fun p => g.route m col p.1 p.2) (congrArg Prod.snd he.symm) + +omit [Fintype E] in +open Classical in +theorem match_supply (u : (R).Supply) : + let f := g.supplies m (roleEdge g m P i e j u) + cond ((R).side u) f.2 f.1 = .inl ⟨e, j⟩ := by + have he := (R).end_eq u + cases h : (R).side u <;> rw [h] at he <;> + exact congrArg (fun j : Fin 6 => (.inl ⟨e, j⟩ : g.Parties m)) he + +include hv in +open Classical in +theorem match_site (u : (R).Supply) : + PortMap.supplySite g m P i (roleEdge g m P i e j u) ((R).side u) = v := by + rw [supply_at, match_supply] + exact hv + +open Classical in +/-- In the case `.inl q`, this construction gives `PortMap.demand g m P s i p v (m.pairEdge (e, +q.val.1)) q.val.2`. -/ +def matchLinks : (R).Port → PortMap.Port g m P s i p v + | .inl q => PortMap.demand g m P s i p v (m.pairEdge (e, q.val.1)) q.val.2 + ((match_demand g m P i e j q).trans hv) + | .inr u => PortMap.supply g m P s i p v (roleEdge g m P i e j u) ((R).side u) + (match_site g m P i v e j hv u) + +open Classical in +theorem match_width (q : (R).Port) : + PortMap.width g m P s i p v (matchLinks g m P s i p v e j hv q) = Role.width z (R) q := by + rcases q with q | u + · exact PortMap.width_demand g m P s i p v _ _ ((match_demand g m P i e j q).trans hv) + · exact PortMap.width_supply g m P s i p v _ _ (match_site g m P i v e j hv u) + +open Classical in +theorem match_weight (hz : 0 < z) (w : Bit (cluster g m P s hz i) → Bool) : + ((R).atom hz).weight (fun q t => w (PortMap.bit g m P s i p v hz + (matchLinks g m P s i p v e j hv q) (t.cast (match_width g m P s i p v e j hv q).symm))) = + factor (cluster g m P s hz i) (.inr (.inl ⟨e, j⟩)) w := by + rw [paired_factor] + refine Role.eval (R) hz _ _ _ _ ?_ ?_ + · intro q t + have he := PortMap.address_demand_new g m P s i p v hz (m.pairEdge (e, q.val.1)) q.val.2 + ((match_demand g m P i e j q).trans hv) t + rcases q with ⟨⟨q, d⟩, hq⟩ + cases d <;> exact congrArg w he.symm + · intro u t + let f := roleEdge g m P i e j u + have he := PortMap.address_supply g m P s i p v hz f ((R).side u) (match_site g m P i v e j hv + u) t + rw [match_supply] at he + have eb : inserted g m P i e ⟨u.val.1, finProdFinEquiv (u.val.2, t)⟩ = (f, t) := by + simp only [inserted, Equiv.symm_apply_apply] + rfl + exact (congrArg w he.symm).trans + (congrArg (read g m P s hz i w ∘ supply g m P s hz i (.inl ⟨e, j⟩)) eb.symm) + +open Classical in +/-- Builds `AtomMap g m P s hz i p v ((R).atom hz) (.inr (.inl ⟨e, j⟩)) where slot q _` with the +specified `AtomMap`, `size`, `value`. -/ +def matchMap (hz : 0 < z) : + AtomMap g m P s hz i p v ((R).atom hz) (.inr (.inl ⟨e, j⟩)) where + slot q _ := matchLinks g m P s i p v e j hv q + size q _ := match_width g m P s i p v e j hv q + value := match_weight g m P s i p v e j hv hz + +end Subround +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +end + +/- # One checker row per incidence of an untouched wire -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +open Packing + +variable {F V E : Type} [Field F] [Fintype V] [Fintype E] {a b : Wire} + {N C : V → Finset V} {Δ D h k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (P : Gadget F) {G : Diagram F a b} {z : ℕ} + (s : Bundles G src dst ix (P.b * z)) (i : g.Choice m P) + +open Classical in +/-- The subtype of `q : m.unpaired × Bool` satisfying `(cond q.2 (dst q.1.val) (src q.1.val), ix +q.1.val) = v`. -/ +abbrev CheckRow (v : V × Cell h) := + {q : m.unpaired × Bool // (cond q.2 (dst q.1.val) (src q.1.val), ix q.1.val) = v} + +open Classical in +theorem checks_eval {v : V × Cell h} {n : ℕ} (e : Fin n ≃ CheckRow g m v) + (x : ∀ j : Fin n × Option (Fin P.b), Fin ((checks P z n).width j) → Bool) + (L R U : m.unpaired × Fin (P.b * z) → Bool) + (hd : ∀ j (t : Fin (P.b * z)), x (j, none) t = cond (e j).val.2 (R ((e j).val.1, + t)) (L ((e j).val.1, t))) + (hs : ∀ j b (t : Fin z), x (j, some b) t = U ((e j).val.1, finProdFinEquiv (b, t))) : + (checks P z n).weight x = + Spectral.Packet.checkAt F (fun r => (src r.1, ix r.1)) v L U * + Spectral.Packet.checkAt F (fun r => (dst r.1, ix r.1)) v R U := by + have he : (∀ (j : Fin n) (b : Fin P.b) (t : Fin z), + x (j, none) (finProdFinEquiv (b, t)) = x (j, some b) t) ↔ + (∀ q : m.unpaired × Fin (P.b * z), (src q.1, ix q.1) = v → L q = U q) ∧ + (∀ q : m.unpaired × Fin (P.b * z), (dst q.1, ix q.1) = v → R q = U q) := by + simp only [hd, hs] + constructor + · intro H + have hall (j : CheckRow g m v) (t : Fin (P.b * z)) : + cond j.val.2 (R (j.val.1, t)) (L (j.val.1, t)) = U (j.val.1, t) := by + obtain ⟨j, rfl⟩ := e.surjective j + obtain ⟨⟨b, t⟩, rfl⟩ := finProdFinEquiv.surjective t + exact H j b t + exact ⟨fun q h => hall ⟨(q.1, false), h⟩ q.2, fun q h => hall ⟨(q.1, true), h⟩ q.2⟩ + · rintro ⟨hl, hr⟩ j b t + obtain ⟨⟨q, s⟩, hq⟩ := e j + cases s + · exact hl _ hq + · exact hr _ hq + simp only [checks, Spectral.Packet.checkAt, he, ite_and, ite_mul, one_mul, zero_mul] + split_ifs <;> rfl + +variable {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G) (v : Site V h) + (o : V × Cell h) (hv : g.route m (g.layout m P i) o.1 o.2 = v) + {n : ℕ} (e : Fin n ≃ CheckRow g m o) + +open Classical in +/-- The value specified by `.inr (q.val.1, b)`. -/ +def checkEdge (q : CheckRow g m o) (b : Fin P.b) : g.Supply m P i := .inr (q.val.1, b) + +omit [Fintype E] in +open Classical in +theorem check_supply (q : CheckRow g m o) (b : Fin P.b) : + let f := g.supplies m (checkEdge g m P i o q b) + cond q.val.2 f.2 f.1 = .inr o := by + rcases q with ⟨⟨q, _|_⟩, h⟩ <;> exact congrArg Sum.inr h + +include hv in +open Classical in +theorem check_site (q : CheckRow g m o) (b : Fin P.b) : + PortMap.supplySite g m P i (checkEdge g m P i o q b) q.val.2 = v := by + rw [supply_at, check_supply] + exact hv + +include hv in +open Classical in +theorem check_demand (q : CheckRow g m o) : + g.route m (g.layout m P i) (cond q.val.2 (dst q.val.1) (src q.val.1)) (ix q.val.1) = v := + (congrArg (fun t => g.route m (g.layout m P i) t.1 t.2) q.property).trans hv + +open Classical in +/-- In the case `(j, none)`, this construction gives `PortMap.demand g m P s i p v (e j).val.1 +(e j).val.2`. -/ +def checkLinks : Fin n × Option (Fin P.b) → PortMap.Port g m P s i p v + | (j, none) => PortMap.demand g m P s i p v (e j).val.1 (e j).val.2 + (check_demand g m P i v o hv (e j)) + | (j, some b) => PortMap.supply g m P s i p v (checkEdge g m P i o (e j) b) (e j).val.2 + (check_site g m P i v o hv (e j) b) + +open Classical in +theorem check_width (q : Fin n × Option (Fin P.b)) : + PortMap.width g m P s i p v (checkLinks g m P s i p v o hv e q) = (checks P z n).width q := by + rcases q with ⟨j, _|b⟩ + · exact PortMap.width_demand g m P s i p v _ _ (check_demand g m P i v o hv (e j)) + · exact PortMap.width_supply g m P s i p v _ _ (check_site g m P i v o hv (e j) b) + +open Classical in +theorem check_weight (hz : 0 < z) (w : Bit (cluster g m P s hz i) → Bool) : + (checks P z n).weight (fun q t => w (PortMap.bit g m P s i p v hz + (checkLinks g m P s i p v o hv e q) (t.cast (check_width g m P s i p v o hv e q).symm))) = + factor (cluster g m P s hz i) (.inr (.inr o)) w := by + rw [unpaired_factor] + refine checks_eval g m P e _ _ _ _ ?_ ?_ + · intro j t + have he := PortMap.address_demand_new g m P s i p v hz (e j).val.1 (e j).val.2 + (check_demand g m P i v o hv (e j)) t + refine (congrArg w he.symm).trans ?_ + cases (e j).val.2 <;> rfl + · intro j b t + let f := checkEdge g m P i o (e j) b + have he := PortMap.address_supply g m P s i p v hz f (e j).val.2 + (check_site g m P i v o hv (e j) b) t + rw [check_supply] at he + have eb : carry g m P i ((e j).val.1, finProdFinEquiv (b, t)) = (f, t) := by + simp only [carry, Equiv.symm_apply_apply] + rfl + exact (congrArg w he.symm).trans + (congrArg (read g m P s hz i w ∘ supply g m P s hz i (.inr o)) eb.symm) + +open Classical in +/-- Builds `AtomMap g m P s hz i p v (checks P z n) (.inr (.inr o)) where slot q _` with the +specified `AtomMap`, `size`, `value`. -/ +def checkMap (hz : 0 < z) : + AtomMap g m P s hz i p v (checks P z n) (.inr (.inr o)) where + slot q _ := checkLinks g m P s i p v o hv e q + size q _ := check_width g m P s i p v o hv e q + value := check_weight g m P s i p v o hv e hz + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +end + +/- # Certifying a posting from its local records and visible span names -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Allocation +open Coloring Packing + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z a : ℕ} + {P : Gadget F} {G : HostNet F L h (P.b * z)} + {Δ D k : ℕ} {B' : ℝ} {g : Grouping G.N G.C Δ D k B' G.load} + {m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix} {i : g.Choice m P} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r G.diagram} + {q : G.Projection Δ D a} {U : Scheme F} + (A : Allocation P G g m i p q U) {out : U.format.obj} (l : A.Lengths out) (hz : 0 < z) + +open scoped Classical in +/-- The value specified by `A.slot (.inr (e, t))`. -/ +abbrev unitSeat (e : g.Survivors m P i) (t : Bool) := A.slot (.inr (e, t)) + +open scoped Classical in +/-- The value specified by `(q.place (whereAt g m P G.units i p (.inr (e, t)))).1`. -/ +abbrev endHost (e : g.Survivors m P i) (t : Bool) := + (q.place (whereAt g m P G.units i p (.inr (e, t)))).1 + +open scoped Classical in +private theorem site_end (e : g.Survivors m P i) (t : Bool) : + (A.span (.inr (e, t))).1 = + (A.host (endHost (p := p) (q := q) e t), A.block (q.place (g.ends' m P i e).1).2, 0) := by + cases t + · rfl + · have eq := (q.core _ _ (g.contact_mem m G.cs G.sub G.edge (g.layout m P i) e.val)).1 + change (q.place (g.ends' m P i e).1).2 = (q.place (g.ends' m P i e).2).2 at eq + rw [eq] + rfl + +open scoped Classical in +/-- Conditions on decoded local patterns. No names of remote hosts +are needed by a station's tensor table. -/ +structure Agrees : Prop where + sample : ∀ v t, U.table out (A.vertex v) t = + Transcript.sample ((g.contract m P G.units hz i).table v) (t ∘ A.pin l hz v) + vacant : ∀ v ∉ Set.range A.vertex, ∀ t, U.table out v t = 1 + outside : ∀ j, U.peer out (A.span (.inl j)) = none + idle : ∀ t ∉ Set.range A.span, U.peer out t = none + dir : ∀ e t, U.direction out (A.span (.inr (e, t))) = t + link : ∀ e t, let v := A.span (.inr (e, t)) + (U.pattern out v.1).peer v.1.2.2 v.2 = + some (A.index (endHost (p := p) (q := q) e t) (endHost (p := p) (q := q) e (!t)), + 0, A.unitSeat e (!t)) + nav : ∀ (e : g.Survivors m P i) t, let v := endHost (p := p) (q := q) e t + let w := endHost (p := p) (q := q) e (!t) + (out (A.host v)).1 (A.index v w) = A.host w + +variable (H : A.Agrees l hz) + +open scoped Classical in +/-- Builds `U.Seating out (g.contract m P G.units hz i) where vertex` with the specified +`vertex`, `pin`, `cover`, `exact`. -/ +def seating : U.Seating out (g.contract m P G.units hz i) where + vertex := A.vertex + pin := A.pin l hz + cover := U.cover_of_span out A.span A.vertex (whereAt g m P G.units i p) + (fun _ => rfl) l.idle + sample := H.sample + vacant := H.vacant + +open scoped Classical in +theorem end_pin (j : Face g m P i p) (b : Fin (visibleWidth g m P i p z j)) : + let y := faceBits g m P G.units hz i p ⟨j, b⟩ + (A.seating l hz H).ends y = ⟨A.span j, b.cast (l.used j).symm⟩ := by + let v := whereAt g m P G.units i p j + let r : Visible g m P G.units i p v := ⟨j, rfl⟩ + let o := visibleBits g m P G.units hz i p v ⟨r, b⟩ + have he := visible_pin g m P G.units hz i p v ⟨r, b⟩ + change (g.contract m P G.units hz i).portEquiv ⟨v, o⟩ = faceBits g m P G.units hz i p ⟨j, b⟩ at he + apply (A.seating l hz H).ends_eq_of_port he + change U.port out (A.vertex v) (A.pin l hz v o) = _ + rw [show A.pin l hz v o = _ from A.pin_at l hz v r b] + rfl + +include H in +open scoped Classical in +theorem peer_end (e : g.Survivors m P i) (t : Bool) : + U.peer out (A.span (.inr (e, t))) = some (A.span (.inr (e, !t))) := + U.peer_of_link out (A.site_end e t) (A.site_end e (!t)) (H.link e t) (H.nav e t) + +include H in +open scoped Classical in +theorem proper : U.Proper out := + U.proper_of_span out A.span z H.idle H.outside (A.peer_end l hz H) + (fun e t => l.used (.inr (e, t))) H.dir + +open scoped Classical in +theorem exposed_pin (j : p.BorderBit) : + let G' := g.contract m P G.units hz i + (A.seating l hz H).ends (boundaryEnd G' (p.exteriorBits j)) = + ⟨A.span (.inl j.1), j.2.cast (l.used (.inl j.1)).symm⟩ := + A.end_pin l hz H (.inl j.1) j.2 + +open scoped Classical in +theorem unit_pin (e : g.Survivors m P i) (b : Bool) (j : Fin z) : + let e' := g.remaining m P G.units hz i (e, j) + (A.seating l hz H).ends (cond b (.inr (.inr e')) (.inl (.inr e'))) = + ⟨A.span (.inr (e, b)), j.cast (l.used (.inr (e, b))).symm⟩ := + A.end_pin l hz H (.inr (e, b)) j + +open scoped Classical in +theorem exposed_none (j : slots x ⊕ slots y) : + U.peer out ((A.seating l hz H).ends (boundaryEnd _ j)).1 = none := by + obtain ⟨t, rfl⟩ := p.exteriorBits.surjective j + rw [A.exposed_pin] + exact H.outside t.1 + +open scoped Classical in +/-- Builds `U.Presentation out (g.contract m P G.units hz i) where toSeating` with the specified +`toSeating`, `proper`, `input`, `output`. -/ +def presentation : U.Presentation out (g.contract m P G.units hz i) where + toSeating := A.seating l hz H + proper := A.proper l hz H + input t := A.exposed_none l hz H (.inl t) + output t := A.exposed_none l hz H (.inr t) + internal e := by + obtain ⟨⟨a, j⟩, rfl⟩ := (g.remaining m P G.units hz i).surjective e + have hs := A.unit_pin l hz H a false j + have ht := A.unit_pin l hz H a true j + dsimp only [cond] at hs ht + rw [hs, ht] + exact ⟨A.peer_end l hz H a false, rfl⟩ + +variable (hle : Δ ≤ D) + +open scoped Classical in +theorem unit_span (e : g.Survivors m P i) (b : Bool) : + U.spanAt (HostNet.contracted q g m hz hle i) A.host A.block A.unitSeat e b = A.span (.inr (e, + b)) := by + refine Prod.ext ?_ rfl + cases b + · exact (A.site_end e false).symm + · exact (A.site_end e true).symm + +open scoped Classical in +/-- Builds `U.Posting out (HostNet.contracted q g m hz hle i) where toPresentation` with the +specified `toPresentation`, `host`, `block`, `stub`. -/ +def posting : U.Posting out (HostNet.contracted q g m hz hle i) where + toPresentation := A.presentation l hz H + host := A.host + block := A.block + stub := A.unitSeat + index := A.index + vertex_eq _ := rfl + ordered e b j := by + change g.Survivors m P i at e + let s := (A.seating l hz H).ends (Scheme.endBit (HostNet.contracted q g m hz hle i) e b j) + have he : s = ⟨A.span (.inr (e, b)), j.cast (l.used (.inr (e, b))).symm⟩ + := A.unit_pin l hz H e b j + change s.1 = _ ∧ s.2.val = j.val + rw [he] + exact ⟨(A.unit_span hz hle e b).symm, rfl⟩ + length e t := (congrArg (U.width out) (A.unit_span hz hle e t)).trans (l.used _) + dir e t := (congrArg (U.direction out) (A.unit_span hz hle e t)).trans (H.dir e t) + link e t := by + change g.Survivors m P i at e + rw [unit_span] + cases t + · exact H.link e false + · exact H.link e true + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Allocation +end + +/- # Projected endpoints are covered by the common host lists -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Allocation +open Coloring Packing + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z a : ℕ} + {P : Gadget F} {G : HostNet F L h (P.b * z)} {Δ D k : ℕ} {B' : ℝ} + {g : Grouping G.N G.C Δ D k B' G.load} + {m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix} {i : g.Choice m P} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r G.diagram} {q : G.Projection Δ D a} + +open scoped Classical in +theorem end_contact (e : g.Survivors m P i) (t : Bool) : + endHost (p := p) (q := q) e (!t) ∈ q.C (endHost (p := p) (q := q) e t) := by + have h := (q.core _ _ (g.contact_mem m G.cs G.sub G.edge (g.layout m P i) e.val)).2 + cases t + · exact h + · exact q.cs _ _ h + +open scoped Classical in +theorem end_nav {U : Scheme F} (A : Allocation P G g m i p q U) (nav : B U.m → B U.d → B U.m) + (cover : ∀ v w, w ∈ q.C v → nav (A.host v) (A.index v w) = A.host w) + (e : g.Survivors m P i) (t : Bool) : + let v := endHost (p := p) (q := q) e t + let w := endHost (p := p) (q := q) e (!t) + nav (A.host v) (A.index v w) = A.host w := + cover _ _ (end_contact e t) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Allocation +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Dense.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Dense.lean new file mode 100644 index 0000000000..fdf8673c1d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Dense.lean @@ -0,0 +1,471 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import Mathlib.Data.Nat.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Runs + +/-! +# Decoding the weight of a contracted station + +Atom arguments refer either to exposed arguments of the new station +or to wires summed out inside it. Neither the decoder nor the atom +values need the absolute names of any exterior or internal wires. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Classical in +/-- The data for the history construction, including `A`, `E`, `[atoms`, `[internal`, `I`. -/ +structure History (F X : Type) where + /-- The `History` component of type `Type`. -/ + A : Type + /-- The type of edges. -/ + E : Type + [atoms : Fintype A] + [internal : Fintype E] + /-- The `History` component of type `A → Type`. -/ + I : A → Type + /-- The evaluation map carried by `History`, with type `∀ a, (I a → Bool) → F`. -/ + value : ∀ a, (I a → Bool) → F + /-- The read operation of type `∀ a, I a → X ⊕ E`. -/ + read : ∀ a, I a → X ⊕ E + +attribute [instance] History.atoms History.internal + +namespace History +variable {F X V E : Type} [Field F] [Fintype V] [Fintype E] {a b : Wire} + +open Classical in +/-- The indexing data represented by `∑ z : H.E → Bool, ∏ t, H.value t (Sum.elim x z ∘ H.read +t)`. -/ +def eval (H : History F X) (x : X → Bool) := + ∑ z : H.E → Bool, ∏ t, H.value t (Sum.elim x z ∘ H.read t) + +variable {G : Diagram F a b} (C : G.Clustering V E) + +open Classical in +/-- Track a port all the way through a cluster. Both ends of a hidden +wire give the very same address. -/ +def address : G.End → C.collapse.End ⊕ (Σ v, C.hidden v) + | .inl (.inl x) => .inl (.inl (.inl x)) + | .inr (.inl y) => .inl (.inr (.inl y)) + | .inl (.inr e) => (C.edges.symm e).map (fun i => .inl (.inr i)) id + | .inr (.inr e) => (C.edges.symm e).map (fun i => .inr (.inr i)) id + +open Classical in +/-- Embeds `G.Port v` into `G.End where toFun i`. -/ +def named (G : Diagram F a b) (v : G.V) : G.Port v ↪ G.End where + toFun i := G.portEquiv ⟨v, i⟩ + inj' _ _ h := eq_of_heq (Sigma.mk.inj_iff.mp (G.portEquiv.injective h)).2 + +omit [Field F] in +open Classical in +theorem sample (G : Diagram F a b) (v : G.V) (x y) : + Transcript.sample (G.table v) (Sum.elim x y ∘ named G v) = G.weight v x y := rfl + +open Classical in +private theorem read_address (w : C.collapse.End → Bool) (z : C.Inside) (p : G.End) : + Sum.elim w (fun e => z e.1 e.2) (address C p) = + Sum.elim (C.lift (w ∘ Sum.inl) z) (C.lift (w ∘ Sum.inr) z) p := by + rcases p with (i|e)|(j|e) + · rfl + · change Sum.elim _ _ ((C.edges.symm e).map _ _) = Sum.elim _ _ (C.edges.symm e) + cases C.edges.symm e <;> rfl + · rfl + · change Sum.elim _ _ ((C.edges.symm e).map _ _) = Sum.elim _ _ (C.edges.symm e) + cases C.edges.symm e <;> rfl + +variable (H : History F X) (v : V) (out : C.collapse.Port v ≃ X) + +open Classical in +/-- Indexes the bit by the coordinates of `C.collapse.End ⊕ (Σ u, C.hidden u)`. -/ +abbrev Bit := C.collapse.End ⊕ (Σ u, C.hidden u) + +open Classical in +/-- Transforms the indexed data by `Sum.map (fun p => named C.collapse v (out.symm p)) (fun e => +⟨v, hidden e⟩)`. -/ +def embed (hidden : H.E ≃ C.hidden v) : X ⊕ H.E → Bit C := + Sum.map (fun p => named C.collapse v (out.symm p)) (fun e => ⟨v, hidden e⟩) + +open Classical in +/-- The value specified by `G.weight t (w ∘ address C ∘ Sum.inl) (w ∘ address C ∘ Sum.inr)`. -/ +def factor (t : G.V) (w : Bit C → Bool) : F := + G.weight t (w ∘ address C ∘ Sum.inl) (w ∘ address C ∘ Sum.inr) + +open Classical in +/-- A local correspondence may omit idle factors. Its tests need no +choice of an ordering of the old atom arguments. -/ +structure Traces where + /-- Embeds the coordinates as `H.A ↪ {t // C.owner t = v}`. -/ + atom : H.A ↪ {t // C.owner t = v} + /-- The private coordinates at each index of type `H.E ≃ C.hidden v`. -/ + hidden : H.E ≃ C.hidden v + entry : ∀ i w, H.value i (w ∘ embed C H v out hidden ∘ H.read i) = factor C (atom i) w + idle : ∀ t ∉ Set.range atom, ∀ w, factor C t.val w = 1 + +variable {C H v out} + +open Classical in +theorem Traces.correct (p : Traces C H v out) (x : X → Bool) : + H.eval x = Transcript.sample (C.collapse.table v) (x ∘ out) := by + let f := named C.collapse v + let w := Function.extend f (x ∘ out) (fun _ => false) + have hw (t : C.collapse.Port v) : w (named C.collapse v t) = x (out t) := + f.injective.extend_apply _ _ _ + have eqn : x ∘ out = Sum.elim (w ∘ Sum.inl) (w ∘ Sum.inr) ∘ f := by + funext t; rw [Function.comp_apply, ← hw] + change w (f t) = Sum.elim _ _ (f t) + cases f t <;> rfl + rw [eqn, sample, C.weight_collapse] + unfold eval + refine Fintype.sum_equiv (p.hidden.arrowCongr (Equiv.refl Bool)) _ _ ?_ + intro z + let Z : C.Inside := Function.update (fun _ _ => false) v (z ∘ p.hidden.symm) + let tape : Bit C → Bool := Sum.elim w (fun e => Z e.1 e.2) + have hread : Sum.elim x z = tape ∘ embed C H v out p.hidden := by + funext t + cases t with + | inl t => simp [tape, embed, hw] + | inr e => simp [tape, embed, Z] + have ha : tape ∘ address C = Sum.elim (C.lift (w ∘ Sum.inl) Z) (C.lift (w ∘ Sum.inr) Z) := + funext (read_address C w Z) + have hf (i : G.V) : + G.weight i (C.lift (w ∘ Sum.inl) Z) (C.lift (w ∘ Sum.inr) Z) = factor C i tape := by + unfold factor + simp only [← Function.comp_assoc, ha] + rfl + change _ = ∏ t : {t // C.owner t = v}, G.weight t (C.lift _ Z) (C.lift _ Z) + simp only [hf, hread, Function.comp_assoc, p.entry] + rw [← Finset.prod_subset (Finset.subset_univ (Finset.univ.image p.atom))] + · rw [Finset.prod_image p.atom.injective.injOn] + · intro j _ hj + exact p.idle j (by simpa only [Finset.mem_image, Finset.mem_univ, true_and, Set.mem_range] + using hj) tape + +end History +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Local contraction codes + +A port reference describes an entire contiguous fragment. The bit +width of a bundle may exceed the size of the code. A common length +table can, for example, give lengths and offsets in bundle units. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +open Coloring + +open Classical in +/-- Indexes the positions by the coordinates of `Σ i, Fin (w i)`. -/ +abbrev Positions {e : ℕ} (w : B e → ℕ) := Σ i, Fin (w i) + +open Classical in +/-- The dictionary and the length scale are fixed across all sites. -/ +structure Menu (F : Type) (l s d : ℕ) where + /-- The width parameter carried by `Menu`, with type `B l → B s → ℕ`. -/ + width : B l → B s → ℕ + /-- The evaluation map carried by `Menu`, with type `(i : B l) → (Positions (width i) → Bool) + → F`. -/ + value : (i : B l) → (Positions (width i) → Bool) → F + /-- The length of the indexed record carried by `Menu`, with type `B d → ℕ`. -/ + length : B d → ℕ + +open Classical in +/-- The flag is set for a hidden span. -/ +abbrev pointer (e d : ℕ) : Format := .pair .bit (.pair (.addr e) (.addr d)) + +open Classical in +/-- The value specified by `.pair (.vec e (.addr d)) (.vec m (.pair .bit (.pair (.addr l) (.vec +s (pointer e d)))))`. -/ +abbrev code (m e l s d : ℕ) : Format := + .pair (.vec e (.addr d)) (.vec m (.pair .bit (.pair (.addr l) (.vec s (pointer e d))))) + +open Classical in +theorem width_code (m e l s d : ℕ) : + (code m e l s d).width = 2 ^ e * d + 2 ^ m * (1 + (l + 2 ^ s * (1 + (e + d)))) := by + simp [code, pointer] + +namespace Menu +variable {F : Type} {m e l s d : ℕ} (M : Menu F l s d) +variable (w : B e → ℕ) (c : (code m e l s d).obj) + +open Classical in +/-- The subtype of `i : B m` satisfying `(c.2 i).1 = true`. -/ +abbrev Atom := {i : B m // (c.2 i).1 = true} +open Classical in +/-- The value specified by `(c.2 i).2.1`. -/ +abbrev label (i : Atom c) := (c.2 i).2.1 +open Classical in +/-- The value specified by `(c.2 i).2.2 j`. -/ +abbrev ref (i : Atom c) (j : B s) := (c.2 i).2.2 j +open Classical in +/-- Computes the hidden by the application `M.length (c.1 j)`. -/ +abbrev hidden (j : B e) := M.length (c.1 j) + +open Classical in +/-- Returns `M.hidden c p.2.1` when `p.1` holds, and `w p.2.1` otherwise. -/ +def capacity (p : (pointer e d).obj) := + if p.1 then M.hidden c p.2.1 else w p.2.1 + +open Classical in +/-- The condition `∀ (i : Atom c) (j : B s) (t : Fin (M.width (label c i) j)), M.length (ref c i +j).2.2 + t.val < M.capacity w c (ref c i j)` on the specified data. -/ +def Fits : Prop := + ∀ (i : Atom c) (j : B s) (t : Fin (M.width (label c i) j)), + M.length (ref c i j).2.2 + t.val < M.capacity w c (ref c i j) + +open Classical in +/-- Returns `.inr ⟨p.2.1, ⟨t.val, by simpa [capacity, h] using t.isLt⟩⟩` when `h : p.1` holds, +and `.inl ⟨p.2.1, ⟨t.val, by simpa [capacity, h] using t.isLt⟩⟩` otherwise. -/ +def resolve (p : (pointer e d).obj) (t : Fin (M.capacity w c p)) : + Positions w ⊕ Positions (M.hidden c) := + if h : p.1 then .inr ⟨p.2.1, ⟨t.val, by simpa [capacity, h] using t.isLt⟩⟩ + else .inl ⟨p.2.1, ⟨t.val, by simpa [capacity, h] using t.isLt⟩⟩ + +open Classical in +/-- Builds `History F (Positions w) where A` with the specified `value`, `read`. -/ +def history (h : M.Fits w c) : History F (Positions w) where + A := Atom c + E := Positions (M.hidden c) + I i := Positions (M.width (label c i)) + value i := M.value (label c i) + read i p := M.resolve w c (ref c i p.1) ⟨_, h i p.1 p.2⟩ + +open Classical in +/-- A table is decoded without access to its global station number. -/ +def decode [Field F] (x : Positions w → Bool) : F := + if h : M.Fits w c then (M.history w c h).eval x else 0 + +open Classical in +theorem decode_eq [Field F] {V E : Type} [Fintype V] [Fintype E] {a b : Wire} + {G : Diagram F a b} (C : G.Clustering V E) (v : V) + (p : C.collapse.Port v ≃ Positions w) (h : M.Fits w c) + (trace : Traces C (M.history w c h) v p) (x : Positions w → Bool) : + M.decode w c x = Transcript.sample (C.collapse.table v) (x ∘ p) := by + rw [decode, dite_eq_left h] + exact trace.correct x + +end Menu +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +end + +/- +# Packing local histories at their actual widths + +Every tag is a nonnegative integer. Its length is the number of bits +needed to represent it, with zero using no bits. Store a short length +at every slot and enumerate the truncated tags in the corresponding +product space. The long part of the new tag is bounded by the *sum* +of the occupied lengths, with coefficient one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Dense +open Coloring + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def used (n : ℕ) := Nat.clog 2 (n + 1) + +open scoped Classical in +theorem used_le {n d : ℕ} : used n ≤ d ↔ n < 2 ^ d := by + exact Nat.clog_le_iff_le_pow (by decide) + +open scoped Classical in +@[simp] theorem used_zero : used 0 = 0 := by simp [used] + +variable {I : Type} [Fintype I] [DecidableEq I] {l k : ℕ} + +open scoped Classical in +/-- The sum of `used (x i).val` indexed by `i`. -/ +def cost (x : I → B l) := ∑ i, used (x i).val + +open scoped Classical in +/-- Uses `⟨used (x i).val, (used_le.mpr (x i).isLt).trans_lt (used_le.mp le_rfl)⟩` as the +representation. -/ +def widths (x : I → B l) (i : I) : B (used l) := + ⟨used (x i).val, (used_le.mpr (x i).isLt).trans_lt (used_le.mp le_rfl)⟩ + +open scoped Classical in +/-- The indexing data represented by `(i : I) → B (b i).val`. -/ +abbrev values (b : I → B (used l)) := (i : I) → B (b i).val + +open scoped Classical in +/-- Evaluates `⟨(x i).val, used_le.mp le_rfl⟩` at the input `i`. -/ +def trim (x : I → B l) : values (widths x) := + fun i => ⟨(x i).val, used_le.mp le_rfl⟩ + +open scoped Classical in +/-- The quantity computed by `k + Fintype.card I * used l`. -/ +def header (I : Type) [Fintype I] (k l : ℕ) := k + Fintype.card I * used l + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def heads : B k × (I → B (used l)) ≃ B (header I k l) := + Fintype.equivOfCardEq (by + simp only [B, Fintype.card_fin, Fintype.card_prod, Fintype.card_fun, ← pow_mul, header, pow_add] + rw [Nat.mul_comm (used l) (Fintype.card I)]) + +open scoped Classical in +/-- The value specified by `(Fintype.equivFin (values b) v).val`. -/ +def number {b : I → B (used l)} (v : values b) : ℕ := + (Fintype.equivFin (values b) v).val + +open scoped Classical in +/-- The quantity computed by `(heads (z.1, widths z.2)).val + 2 ^ (header I k l) * number (trim +z.2)`. -/ +def pack (z : B k × (I → B l)) : ℕ := + (heads (z.1, widths z.2)).val + 2 ^ (header I k l) * number (trim z.2) + +open scoped Classical in +theorem length (z : B k × (I → B l)) : used (pack z) ≤ header I k l + cost z.2 := by + classical + have hn : number (trim z.2) < 2 ^ cost z.2 := by + have h := (Fintype.equivFin (values (widths z.2)) (trim z.2)).isLt + change number (trim z.2) < Fintype.card (values (widths z.2)) at h + change number (trim z.2) < Fintype.card ((i : I) → B ((widths z.2) i).val) at h + rw [Fintype.card_pi] at h + simp only [B, Fintype.card_fin, Finset.prod_pow_eq_pow_sum] at h + exact h + rw [used_le, pow_add] + unfold pack + calc + _ < 2 ^ (header I k l) + 2 ^ (header I k l) * number (trim z.2) := + Nat.add_lt_add_right (heads (z.1, widths z.2)).isLt _ + _ = 2 ^ (header I k l) * (number (trim z.2) + 1) := by rw [mul_add, mul_one, add_comm] + _ ≤ _ := Nat.mul_le_mul_left _ hn + +open scoped Classical in +private theorem number_eq {a b : I → B (used l)} {v : values a} {w : values b} + (h : a = b) (e : number v = number w) : ∀ i, (v i).val = (w i).val := by + subst b + have hh : v = w := (Fintype.equivFin _).injective (Fin.ext e) + simp only [hh, implies_true] + +open scoped Classical in +theorem injective : Function.Injective (pack (I := I) (k := k) (l := l)) := by + classical + rintro ⟨a, x⟩ ⟨b, y⟩ h + have he := congrArg (· % 2 ^ (header I k l)) h + simp only [pack, Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt (Fin.isLt _)] at he + have hh := heads.injective (Fin.ext he) + obtain ⟨rfl, hw⟩ := Prod.mk.inj hh + have he' : number (trim x) = number (trim y) := by + unfold pack at h + rw [he] at h + exact Nat.eq_of_mul_eq_mul_left (Nat.two_pow_pos _) (Nat.add_left_cancel h) + have hxy : x = y := funext fun i => Fin.ext (number_eq hw he' i) + rw [hxy] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Dense +end + +/- +# Interpreting the local stub arrays + +A colony label is unique only inside its host. A neighbor index is +local to the source host. Neither field needs global address bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +open Coloring Packing + +variable {V E P : Type} {r d h e k ℓ : ℕ} + +/-- Common indexing of all local arrays. Source and destination use +the same convention for colony labels. -/ +structure Stubs (src dst : E → P) (ix : E → Cell r) (owner : P → V) (d h e ℓ : ℕ) where + /-- Embeds the coordinates as `Cell r ↪ B h`. -/ + block : Cell r ↪ B h + /-- The `Stubs` component of type `P → B ℓ`. -/ + tag : P → B ℓ + separate : ∀ p q, owner p = owner q → tag p = tag q → p = q + /-- The `Stubs` component of type `E → B e`. -/ + stub : E → B e + unique : ∀ i j, src i = src j → ix i = ix j → stub i = stub j → i = j + /-- The `Stubs` component of type `E → B d`. -/ + near : E → B d + neighbor : ∀ i j, src i = src j → (near i = near j ↔ owner (dst i) = owner (dst j)) + +namespace Stubs +variable {src dst : E → P} {ix : E → Cell r} {owner : P → V} + (f : Stubs src dst ix owner d h e ℓ) + +/-- The value specified by `(rowIndex h e).symm (f.block (ix i), f.stub i)`. -/ +def pos (i : E) := (rowIndex h e).symm (f.block (ix i), f.stub i) +/-- The value specified by `(Labels h ℓ d).serial (0, f.tag p, 0)`. -/ +def key (p : P) := (Labels h ℓ d).serial (0, f.tag p, 0) + +variable (x : V → (Input d h e k ℓ).obj) (c : Color r) + +/-- The active records enumerate exactly the outgoing units. Only the +local and remote colony keys on those units must be correct. -/ +structure Records : Prop where + active : ∀ v b j, (((x v).2.1 b).2 j).1 = true ↔ + ∃ i, owner (src i) = v ∧ f.block (ix i) = b ∧ f.stub i = j + color : ∀ i, (x (owner (src i))).1 (f.block (ix i)) = true ↔ thick c (ix i) + label : ∀ i, ((x (owner (src i))).2.1 (f.block (ix i))).1 = f.tag (src i) + slot : ∀ i, (((x (owner (src i))).2.1 (f.block (ix i))).2 (f.stub i)).2.1 = f.near i + remote : ∀ i, (x (owner (src i))).2.2 (f.block (ix i)) (f.near i) = f.tag (dst i) + +theorem represents (rec : f.Records x c) (p : P) : + (rows (x (owner p))).Represents src dst ix c p f.pos (f.key p) := by + have addr (i : E) : rowIndex h e (f.pos i) = (f.block (ix i), f.stub i) := + (rowIndex h e).apply_symm_apply _ + have source (i : E) : (rows (x (owner (src i)))).src (f.pos i) = f.key (src i) := by + simp only [Rows.src, rows, addr, rec.label, key] + have dest (i : E) : (rows (x (owner (src i)))).dest (f.pos i) = + (Labels h ℓ d).serial (0, f.tag (dst i), f.near i) := by + simp only [Rows.dest, rows, addr, rec.slot, rec.remote] + constructor + · intro i j hi hj eq + have hr := congrArg (rowIndex h e) eq + rw [addr, addr] at hr + exact f.unique i j (hi.trans hj.symm) (f.block.injective (Prod.mk.inj hr).1) (Prod.mk.inj hr).2 + · intro i hi + simp only [Rows.active, rows, addr] + exact (rec.active _ _ _).mpr ⟨i, congrArg owner hi, rfl, rfl⟩ + · intro j hj ht + obtain ⟨i, ho, hb, hs⟩ := (rec.active (owner p) _ _).mp hj + have hp : f.pos i = j := (rowIndex h e).injective ((addr i).trans (Prod.ext hb hs)) + rw [← ho, ← hp, source] at ht + have he := (Labels h ℓ d).serial.injective ht + exact ⟨i, f.separate _ _ ho (congrArg (fun z => z.2.1) he), hp⟩ + · intro i hi + simpa only [hi] using source i + · intro i hi + subst p + simpa only [Rows.thick, rows, addr] using rec.color i + · intro i j hi hj + have ht := dest i + have hu := dest j + rw [hi] at ht + rw [hj] at hu + rw [ht, hu, Equiv.apply_eq_iff_eq] + have hn := f.neighbor i j (hi.trans hj.symm) + constructor + · intro eq + exact f.separate _ _ (hn.mp (congrArg (fun z => z.2.2) eq)) (congrArg (fun z => z.2.1) eq) + · intro eq + rw [eq, hn.mpr (congrArg owner eq)] + · intro i j _ _ + simp only [Rows.item, rows, addr, Equiv.apply_eq_iff_eq, Prod.mk.injEq, and_true, + f.block.injective.eq_iff] + +end Stubs +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Entry.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Entry.lean new file mode 100644 index 0000000000..ee5152bd73 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Entry.lean @@ -0,0 +1,300 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Dense + +/-! +# Encoding the active atoms and local wire spans + +Unused atom slots are turned off. Unused hidden slots have zero +width. Counting them as unused but positive-width wires would +multiply a contraction by an unwanted power of two. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +open Coloring + +open Classical in +/-- The data for the packed construction, including `tag`, `width`, `ptr`. -/ +structure Packed (A T : Type) (e l s d : ℕ) where + /-- The `Packed` component of type `A → B l`. -/ + tag : A → B l + /-- The width parameter carried by `Packed`, with type `T → B d`. -/ + width : T → B d + /-- The `Packed` component of type `A → B s → (B e ⊕ T) × B d`. -/ + ptr : A → B s → (B e ⊕ T) × B d + +namespace Packed +variable {A T F : Type} {m e l s d : ℕ} + (p : Packed A T e l s d) (g : A ↪ B m) (f : T ↪ B e) + +open Classical in +/-- The value specified by `(r.1.isRight, Sum.elim id f r.1, r.2)`. -/ +def link (r : (B e ⊕ T) × B d) : (pointer e d).obj := + (r.1.isRight, Sum.elim id f r.1, r.2) + +open Classical in +/-- The encode of type `(code m e l s d).obj` for the given inputs. -/ +def encode : (code m e l s d).obj := + (Function.extend f p.width (fun _ => 0), + Function.extend g (fun i => (true, p.tag i, link f ∘ p.ptr i)) + (fun _ => (false, 0, fun _ => (false, 0, 0)))) + +open Classical in +theorem store (i : A) : + ((p.encode g f).2 (g i)) = (true, p.tag i, link f ∘ p.ptr i) := + by simp only [encode, g.injective.extend_apply] + +open Classical in +/-- Bundles the indexing function as an equivalence. -/ +def atoms : A ≃ Menu.Atom (p.encode g f) := Equiv.ofBijective + (fun i => ⟨g i, by rw [store]⟩) ⟨fun _ _ h => g.injective (congrArg Subtype.val h), by + rintro ⟨j, hj⟩ + by_cases he : j ∈ Set.range g + · obtain ⟨i, rfl⟩ := he + exact ⟨i, rfl⟩ + · simp only [encode] at hj + rw [Function.extend_apply' _ _ _ he] at hj + cases hj⟩ + +open Classical in +@[simp] theorem tag_eq (i : A) : Menu.label (p.encode g f) (p.atoms g f i) = p.tag i := + congrArg (fun a => a.2.1) (p.store g f i) + +open Classical in +@[simp] theorem ref_eq (i : A) (j : B s) : + Menu.ref (p.encode g f) (p.atoms g f i) j = link f (p.ptr i j) := + congrArg (fun a => a.2.2 j) (p.store g f i) + +variable (M : Menu F l s d) (w : B e → ℕ) + +open Classical in +/-- Indexes the inner by the coordinates of `Σ t : T, Fin (M.length (p.width t))`. -/ +abbrev Inner := Σ t : T, Fin (M.length (p.width t)) + +open Classical in +@[simp] theorem hidden_eq (t : T) : + M.hidden (p.encode g f) (f t) = M.length (p.width t) := + by simp only [Menu.hidden, encode, f.injective.extend_apply] + +open Classical in +/-- Bundles the indexing function as an equivalence. -/ +def inner (h₀ : M.length 0 = 0) : p.Inner M ≃ Positions (M.hidden (p.encode g f)) := + Equiv.ofBijective (fun t => ⟨f t.1, (t.2.cast (p.hidden_eq g f M t.1).symm)⟩) ⟨by + rintro ⟨i, n⟩ ⟨j, r⟩ h + have hi : i = j := f.injective (congrArg Sigma.fst h) + subst j + have hr : n.val = r.val := congrArg (fun x => x.2.val) h + rw [Fin.ext hr], by + rintro ⟨j, r⟩ + by_cases he : j ∈ Set.range f + · obtain ⟨i, rfl⟩ := he + exact ⟨⟨i, r.cast (p.hidden_eq g f M i)⟩, rfl⟩ + · have ht : M.hidden (p.encode g f) j = 0 := by + simp only [Menu.hidden, encode] + rw [Function.extend_apply' _ _ _ he, h₀] + exact (Fin.elim0 (r.cast ht))⟩ + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def cap (r : (B e ⊕ T) × B d) := Sum.elim w (M.length ∘ p.width) r.1 + +open Classical in +theorem cap_eq (r : (B e ⊕ T) × B d) : + M.capacity w (p.encode g f) (link f r) = p.cap M w r := by + rcases r with ⟨i|t, x⟩ + · rfl + · exact p.hidden_eq g f M t + +open Classical in +/-- The condition `∀ i j (t : Fin (M.width (p.tag i) j)), M.length (p.ptr i j).2 + t.val < p.cap +M w (p.ptr i j)` on the specified data. -/ +def Fits := ∀ i j (t : Fin (M.width (p.tag i) j)), + M.length (p.ptr i j).2 + t.val < p.cap M w (p.ptr i j) + +open Classical in +theorem fits_code (h : p.Fits M w) : M.Fits w (p.encode g f) := by + intro i + obtain ⟨t, rfl⟩ := (p.atoms g f).surjective i + intro j + rw [tag_eq, ref_eq, cap_eq] + exact h t j + +open Classical in +/-- In the case `(.inl b, _)`, this construction gives `.inl ⟨b, i⟩`. -/ +def resolve (r : (B e ⊕ T) × B d) (i : Fin (p.cap M w r)) : Positions w ⊕ p.Inner M := + match r with + | (.inl b, _) => .inl ⟨b, i⟩ + | (.inr t, _) => .inr ⟨t, i⟩ + +open Classical in +theorem resolve_eq (h₀ : M.length 0 = 0) (r : (B e ⊕ T) × B d) + (i : Fin (p.cap M w r)) : + M.resolve w (p.encode g f) (link f r) (i.cast (p.cap_eq g f M w r).symm) = + (p.resolve M w r i).map id (p.inner g f M h₀) := by + rcases r with ⟨b|t, x⟩ <;> rfl + +variable [Fintype A] [Fintype T] + +open Classical in +/-- Builds `History F (Positions w) where A` with the specified `value`, `read`. -/ +def history (h : p.Fits M w) : History F (Positions w) where + A := A + E := p.Inner M + I i := Positions (M.width (p.tag i)) + value i := M.value (p.tag i) + read i t := p.resolve M w (p.ptr i t.1) ⟨_, h i t.1 t.2⟩ + +open Classical in +private theorem value_congr {a b : B l} (he : a = b) + {x : Positions (M.width a) → Bool} {y : Positions (M.width b) → Bool} + (h : ∀ j t, x ⟨j, t⟩ = y ⟨j, t.cast (congrArg (fun a => M.width a j) he)⟩) : + M.value a x = M.value b y := by + subst b + exact congrArg _ (funext (fun ⟨j, t⟩ => h j t)) + +omit [Fintype A] [Fintype T] in +open Classical in +private theorem resolve_congr {i j : (pointer e d).obj} (he : i = j) + {v : Fin (M.capacity w (p.encode g f) i)} {u : Fin (M.capacity w (p.encode g f) j)} + (hv : v.val = u.val) : + M.resolve w (p.encode g f) i v = M.resolve w (p.encode g f) j u := by + subst j + rw [Fin.ext hv] + +open Classical in +private theorem eval_equiv [Field F] {X : Type} (U V : History F X) + (a : U.A ≃ V.A) (t : U.E ≃ V.E) (x : X → Bool) + (h : ∀ z i, U.value i (Sum.elim x z ∘ U.read i) = + V.value (a i) (Sum.elim x (z ∘ t.symm) ∘ V.read (a i))) : + U.eval x = V.eval x := by + unfold eval + apply Fintype.sum_equiv (t.arrowCongr (Equiv.refl Bool)) + intro z + exact Fintype.prod_equiv a _ _ (h z) + +open Classical in +theorem decode [Field F] (h₀ : M.length 0 = 0) (h : p.Fits M w) (x : Positions w → Bool) : + M.decode w (p.encode g f) x = (p.history M w h).eval x := by + let c := p.encode g f + let e := p.inner g f M h₀ + let hc := p.fits_code g f M w h + rw [Menu.decode, dite_eq_left hc] + symm + refine eval_equiv (p.history M w h) (M.history w c hc) (p.atoms g f) e x ?_ + intro z i + apply value_congr M (p.tag_eq g f i).symm + intro j t + let r := p.ptr i j + let q : Fin (p.cap M w r) := ⟨_, h i j t⟩ + let u := Menu.ref c (p.atoms g f i) j + have hu : u = link f r := p.ref_eq g f i j + let k := t.cast (congrArg (fun a => M.width a j) (p.tag_eq g f i).symm) + let o : Fin (M.capacity w c u) := ⟨_, hc (p.atoms g f i) j k⟩ + have ho : M.resolve w c u o = (p.resolve M w r q).map id e := by + rw [← p.resolve_eq g f M w h₀] + apply p.resolve_congr g f M w hu + change M.length u.2.2 + t.val = M.length r.2 + t.val + rw [hu]; rfl + change Sum.elim x z (p.resolve M w r q) = + Sum.elim x (z ∘ e.symm) (M.resolve w c u o) + rw [ho] + cases p.resolve M w r q with + | inl a => rfl + | inr a => exact (congrArg z (e.symm_apply_apply a)).symm + +end Packed +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +end + +/- +# A common menu for heterogeneous atomic factors + +Spans of different types share one address space. The description +contains no array of scalar coefficients. A label fixes both the +span widths and the function of their bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +open Coloring + +open Classical in +/-- The data for the atom construction, including `Span`, `width`, `weight`. -/ +structure Atom (F : Type) where + /-- The `Atom` component of type `Type`. -/ + Span : Type + /-- The width parameter carried by `Atom`, with type `Span → ℕ`. -/ + width : Span → ℕ + /-- The weight function carried by `Atom`, with type `((j : Span) → Fin (width j) → Bool) → + F`. -/ + weight : ((j : Span) → Fin (width j) → Bool) → F + +variable {F : Type} {s l d : ℕ} + +open Classical in +/-- The data for the entry construction, including `width`, `weight`. -/ +structure Entry (F : Type) (s : ℕ) where + /-- The width parameter carried by `Entry`, with type `B s → ℕ`. -/ + width : B s → ℕ + /-- The weight function carried by `Entry`, with type `(Positions width → Bool) → F`. -/ + weight : (Positions width → Bool) → F + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def Atom.pack (a : Atom F) (index : a.Span ↪ B s) : Entry F s where + width := Function.extend index a.width (fun _ => 0) + weight x := a.weight fun j t => x ⟨index j, t.cast (index.injective.extend_apply _ _ _).symm⟩ + +open Classical in +/-- The indexed operation `e.weight fun j => x j.1 j.2.val`. -/ +def Entry.eval (e : Entry F s) (x : B s → ℕ → Bool) := e.weight fun j => x j.1 j.2.val + +open Classical in +theorem Atom.eval_pack (a : Atom F) (index : a.Span ↪ B s) (x : B s → ℕ → Bool) : + (a.pack index).eval x = a.weight (fun j t => x (index j) t.val) := rfl + +variable {L : Type} [Field F] (a : L → Atom F) + (names : L ↪ B l) (index : ∀ i, (a i).Span ↪ B s) (len : B d → ℕ) + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def entries := Function.extend names (fun i => (a i).pack (index i)) + (fun _ => (⟨fun _ => 0, fun _ => 1⟩ : Entry F s)) + +open Classical in +/-- Builds `Menu F l s d where width i` with the specified `width`, `value`, `length`. -/ +def menu : Menu F l s d where + width i := (entries a names index i).width + value i := (entries a names index i).weight + length := len + +open Classical in +theorem menu_width (i : L) (j : (a i).Span) : + (menu a names index len).width (names i) (index i j) = (a i).width j := by + simp only [menu, entries, names.injective.extend_apply, Atom.pack, + (index i).injective.extend_apply] + +open Classical in +theorem menu_empty (i : L) (j : B s) (hj : j ∉ Set.range (index i)) : + (menu a names index len).width (names i) j = 0 := by + simp only [menu, entries, names.injective.extend_apply, Atom.pack] + exact Function.extend_apply' _ _ _ hj + +open Classical in +theorem menu_value (i : L) (x : B s → ℕ → Bool) : + (menu a names index len).value (names i) (fun j => x j.1 j.2.val) = + (a i).weight (fun j t => x (index i j) t.val) := by + change (entries a names index (names i)).eval x = _ + rw [entries, names.injective.extend_apply, Atom.eval_pack] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/FaceNames.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/FaceNames.lean new file mode 100644 index 0000000000..3136ae7c82 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/FaceNames.lean @@ -0,0 +1,1059 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Budget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.RestoreCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.FieldLift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Runs + +/-! # Retaining the original ordering of exposed spans -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing + +variable {F : Type} [Field F] {x y : Wire} + +open scoped Classical in +/-- Embeds `slots x ⊕ slots y` into `G.End where toFun`. -/ +def boundaryEnd (G : Diagram F x y) : slots x ⊕ slots y ↪ G.End where + toFun := Sum.map Sum.inl Sum.inl + inj' := by rintro (i|i) (j|j) h <;> cases h <;> rfl + +omit [Field F] in +open scoped Classical in +theorem station_boundary (G : Diagram F x y) (i : slots x ⊕ slots y) : + G.station (boundaryEnd G i) = portEnd G i := by cases i <;> rfl + +namespace Scheme.Presentation +variable {S : Scheme F} {r : S.format.obj} {G : Diagram F x y} (p : S.Presentation r G) + +open scoped Classical in +/-- The subtype of `q : G.V × B S.e` satisfying `0 < S.width r (p.vertex q.1, q.2) ∧ S.peer r +(p.vertex q.1, q.2) = none`. -/ +abbrev BorderSpan := {q : G.V × B S.e // + 0 < S.width r (p.vertex q.1, q.2) ∧ S.peer r (p.vertex q.1, q.2) = none} + +open scoped Classical in +/-- The value specified by `S.width r (p.vertex q.val.1, q.val.2)`. -/ +def borderWidth (q : p.BorderSpan) := S.width r (p.vertex q.val.1, q.val.2) + +open scoped Classical in +/-- Indexes the border bit by the coordinates of `Σ q : p.BorderSpan, Fin (p.borderWidth q)`. -/ +abbrev BorderBit := Σ q : p.BorderSpan, Fin (p.borderWidth q) + +open scoped Classical in +/-- Uses `⟨(p.vertex b.1.val.1, b.1.val.2), b.2⟩` as the representation. -/ +def borderPin (b : p.BorderBit) : S.Pin r := ⟨(p.vertex b.1.val.1, b.1.val.2), b.2⟩ + +open scoped Classical in +theorem injective : Function.Injective p.borderPin := by + rintro ⟨i, a⟩ ⟨j, b⟩ he + obtain ⟨hs, ht⟩ := Sigma.mk.inj he + obtain ⟨hv, hi⟩ := Prod.mk.inj hs + have h : i = j := Subtype.ext (Prod.ext (p.vertex.injective hv) hi) + subst j + exact Sigma.ext rfl ht + +open scoped Classical in +theorem no_peer (e : G.End) : + S.peer r (p.toSeating.ends e).1 = none ↔ e ∈ Set.range (boundaryEnd G) := by + rcases e with (i|j)|(i|j) + · exact iff_of_true (p.input i) ⟨.inl i, rfl⟩ + · refine iff_of_false (by rw [(p.internal j).1]; simp) ?_ + rintro ⟨_|_, h⟩ <;> cases h + · exact iff_of_true (p.output i) ⟨.inr i, rfl⟩ + · refine iff_of_false (by rw [(p.proper _ _ (p.internal j).1).1]; simp) ?_ + rintro ⟨_|_, h⟩ <;> cases h + +open scoped Classical in +theorem side_bijection : + ∃ e : p.BorderBit ≃ slots x ⊕ slots y, ∀ b, + p.toSeating.ends (boundaryEnd G (e b)) = p.borderPin b := by + have ex (b : p.BorderBit) : ∃ t, p.toSeating.ends (boundaryEnd G t) = p.borderPin b := by + let i := p.toSeating.ends.symm (p.borderPin b) + have hp : S.peer r (p.toSeating.ends i).1 = none := by + rw [show p.toSeating.ends i = p.borderPin b from p.toSeating.ends.apply_symm_apply _] + exact b.1.property.2 + obtain ⟨t, ht⟩ := (p.no_peer i).mp hp + exact ⟨t, p.toSeating.ends.eq_symm_apply.mp ht⟩ + choose f hf using ex + have bij : Function.Bijective f := by + constructor + · intro i j he + apply p.injective + rw [← hf, ← hf, he] + · intro i + have cover (a : S.Pin r) (ha : S.peer r a.1 = none) : ∃ b, p.borderPin b = a := by + obtain ⟨⟨v, n⟩, j⟩ := a + obtain ⟨w, rfl⟩ := p.cover ⟨(v, n), j⟩ + exact ⟨⟨⟨(w, n), j.pos, ha⟩, j⟩, rfl⟩ + obtain ⟨b, hb⟩ := cover _ ((p.no_peer _).mpr ⟨i, rfl⟩) + exact ⟨b, (boundaryEnd G).injective (p.toSeating.ends.injective ((hf b).trans hb))⟩ + exact ⟨Equiv.ofBijective f bij, hf⟩ + +open scoped Classical in +/-- Reindexes `p.BorderBit` and `slots x ⊕ slots y` by an equivalence. -/ +def exteriorBits : p.BorderBit ≃ slots x ⊕ slots y := p.side_bijection.choose + +open scoped Classical in +theorem border_pin (b : p.BorderBit) : + p.toSeating.ends (boundaryEnd G (p.exteriorBits b)) = p.borderPin b := + p.side_bijection.choose_spec b + +open scoped Classical in +theorem boundary_val (i : slots x ⊕ slots y) : + (p.boundary i).val = p.toSeating.ends (boundaryEnd G i) := by cases i <;> rfl + +open scoped Classical in +theorem ends_symm_borderPin (b : p.BorderBit) : + p.toSeating.ends.symm (p.borderPin b) = boundaryEnd G (p.exteriorBits b) := + p.toSeating.ends.symm_apply_eq.mpr (p.border_pin b).symm + +open scoped Classical in +theorem border_station (b : p.BorderBit) : portEnd G (p.exteriorBits b) = b.1.val.1 := by + have he (i : G.End) : p.vertex (G.station i) = (p.toSeating.ends i).1.1 := by + obtain ⟨⟨v, j⟩, rfl⟩ := G.portEquiv.surjective i + rw [G.station_port, p.toSeating.ends_at] + rfl + apply p.vertex.injective + rw [← station_boundary, he, p.border_pin] + rfl + +end Scheme.Presentation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Anchors for a local history + +Slots of an old table, a matched gadget or an unmatched equality +constraint are identified before the contraction. This lets a +short description name slots by bundle and offset. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +open Packing + +variable {F V E : Type} [Field F] [Fintype V] [Fintype E] {a b : Wire} + {N C : V → Finset V} {Δ D h k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (P : Gadget F) {G : Diagram F a b} {z : ℕ} + (s : Bundles G src dst ix (P.b * z)) (hz : 0 < z) (i : g.Choice m P) + +open Classical in +/-- Computes the before by the application `G.expanded (g.expansion m P s hz) i`. -/ +abbrev before := G.expanded (g.expansion m P s hz) i + +open Classical in +/-- The value specified by `(before g m P s hz i).partition (Sum.elim (g.assign m P s i) +(g.locate m (g.layout m P i)))`. -/ +abbrev cluster := + (before g m P s hz i).partition (Sum.elim (g.assign m P s i) (g.locate m (g.layout m P i))) + +open Classical in +/-- In the case `.inl t`, this construction gives `.inl (t.map id Sum.inl)`. -/ +def old : G.End → (before g m P s hz i).End + | .inl t => .inl (t.map id Sum.inl) + | .inr t => .inr (t.map id (fun e => .inr (.inl e))) + +open Classical in +/-- The value specified by `.inr (.inr (.inl e))`. -/ +def left (e : G.E) : (before g m P s hz i).End := .inr (.inr (.inl e)) +open Classical in +/-- The value specified by `.inl (.inr (.inr (.inl e)))`. -/ +def right (e : G.E) : (before g m P s hz i).End := .inl (.inr (.inr (.inl e))) + +open Classical in +/-- Returns `.inl (.inr (.inr (.inr j)))` when `(g.supplies m j.1).1 = v` holds, and `.inr (.inr +(.inr (.inr j)))` otherwise. -/ +def supply (v : g.Parties m) (j : g.Supply m P i × Fin z) : (before g m P s hz i).End := + if (g.supplies m j.1).1 = v then .inl (.inr (.inr (.inr j))) else .inr (.inr (.inr (.inr j))) + +variable (w : by + classical + exact Bit (cluster g m P s hz i) → Bool) + +open Classical in +/-- The value specified by `w ∘ address (cluster g m P s hz i)`. -/ +abbrev read := w ∘ address (cluster g m P s hz i) + +open Classical in +theorem old_factor (v : G.V) : + factor (cluster g m P s hz i) (.inl v) w = + Transcript.sample (G.table v) (read g m P s hz i w ∘ old g m P s hz i ∘ named G v) := by + rw [factor, Diagram.weight_expanded] + unfold Diagram.Expansion.entry Diagram.weight Transcript.sample + apply congrArg₂ (G.table v).2.2 <;> apply congrArg <;> funext t + · change Sum.elim _ _ (G.src ⟨v, t⟩) = read g m P s hz i w (old g m P s hz i (.inl (G.src ⟨v, + t⟩))) + cases G.src ⟨v, t⟩ <;> rfl + · change Sum.elim _ _ (G.dst ⟨v, t⟩) = read g m P s hz i w (old g m P s hz i (.inr (G.dst ⟨v, + t⟩))) + cases G.dst ⟨v, t⟩ <;> rfl + +open Classical in +theorem new_factor (v : g.Parties m) : + factor (cluster g m P s hz i) (.inr v) w = + (g.expansion m P s hz).entry i v (read g m P s hz i w ∘ left g m P s hz i) + (read g m P s hz i w ∘ right g m P s hz i) (read g m P s hz i w ∘ supply g m P s hz i v) + := by + rw [factor, Diagram.weight_expanded] + unfold Diagram.Expansion.entry + apply congrArg ((g.expansion m P s hz).entry i v (read g m P s hz i w ∘ left g m P s hz i) + (read g m P s hz i w ∘ right g m P s hz i)) + funext j + unfold supply + simp only [Function.comp_apply] + split_ifs <;> rfl + +open Classical in +/-- The value specified by `s.bits.symm (m.pairEdge (e, q.1), q.2)`. -/ +def original (e : m.items) (q : Fin 2 × Fin (P.b * z)) := + s.bits.symm (m.pairEdge (e, q.1), q.2) + +open Classical in +/-- The value specified by `(.inl ⟨e, r.1, (finProdFinEquiv.symm r.2).1⟩, (finProdFinEquiv.symm +r.2).2)`. -/ +def inserted (e : m.items) (r : Σ j : Fin 8, Fin ((i e).2.1 j * z)) : g.Supply m P i × Fin z := + (.inl ⟨e, r.1, (finProdFinEquiv.symm r.2).1⟩, (finProdFinEquiv.symm r.2).2) + +open Classical in +theorem paired_factor (e : m.items) (j : Fin 6) : + factor (cluster g m P s hz i) (.inr (.inl ⟨e, j⟩)) w = + (P.packet z hz).rule.entry (i e) j + (read g m P s hz i w ∘ left g m P s hz i ∘ original g m P s e) + (read g m P s hz i w ∘ right g m P s hz i ∘ original g m P s e) + (read g m P s hz i w ∘ supply g m P s hz i (.inl ⟨e, j⟩) ∘ inserted g m P i e) := by + rw [new_factor, g.expansion_pair] + rfl + +open Classical in +/-- The value specified by `(.inr (r.1, (finProdFinEquiv.symm r.2).1), (finProdFinEquiv.symm +r.2).2)`. -/ +def carry (r : m.unpaired × Fin (P.b * z)) : g.Supply m P i × Fin z := + (.inr (r.1, (finProdFinEquiv.symm r.2).1), (finProdFinEquiv.symm r.2).2) + +open Classical in +theorem unpaired_factor (v : V × Cell h) : + factor (cluster g m P s hz i) (.inr (.inr v)) w = + Spectral.Packet.checkAt F (fun r : m.unpaired × Fin (P.b * z) => (src r.1, ix r.1)) v + (fun r => read g m P s hz i w (left g m P s hz i (s.bits.symm (r.1, r.2)))) + (read g m P s hz i w ∘ supply g m P s hz i (.inr v) ∘ carry g m P i) * + Spectral.Packet.checkAt F (fun r : m.unpaired × Fin (P.b * z) => (dst r.1, ix r.1)) v + (fun r => read g m P s hz i w (right g m P s hz i (s.bits.symm (r.1, r.2)))) + (read g m P s hz i w ∘ supply g m P s hz i (.inr v) ∘ carry g m P i) := by + rw [new_factor, g.expansion_single] + rfl + +open Classical in +theorem unpaired_idle (v : V × Cell h) (hs : ∀ e : m.unpaired, (src e, ix e) ≠ v) + (ht : ∀ e : m.unpaired, (dst e, ix e) ≠ v) : + factor (cluster g m P s hz i) (.inr (.inr v)) w = 1 := by + rw [unpaired_factor] + simp [Spectral.Packet.checkAt, hs, ht] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +end + +/- +# Hidden spans of a wire-saving subround + +The two halves of each old bundle are internal at their own station. +A supply bundle is internal only if its two parties have merged. +Both kinds retain their original offset ordering. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround + +open Packing + +variable {F V E : Type} [Field F] [Fintype V] [Fintype E] {a b : Wire} + {N C : V → Finset V} {Δ D h k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (P : Gadget F) {G : Diagram F a b} {z : ℕ} + (s : Bundles G src dst ix (P.b * z)) (hz : 0 < z) (i : g.Choice m P) + +open scoped Classical in +/-- Indexes the segment by the coordinates of `E ⊕ E ⊕ g.Supply m P i`. -/ +abbrev Segment := E ⊕ E ⊕ g.Supply m P i + +open scoped Classical in +/-- In the case `.inl _ | .inr (.inl _)`, this construction gives `P.b * z`. -/ +def segmentWidth (z : ℕ) : Segment g m P i → ℕ + | .inl _ | .inr (.inl _) => P.b * z + | .inr (.inr _) => z + +open scoped Classical in +/-- In the case `.inl e`, this construction gives `let v := g.route m (g.layout m P i) (src e) +(ix e); (v, v)`. -/ +def ends : Segment g m P i → Site V h × Site V h + | .inl e => let v := g.route m (g.layout m P i) (src e) (ix e); (v, v) + | .inr (.inl e) => let v := g.route m (g.layout m P i) (dst e) (ix e); (v, v) + | .inr (.inr e) => g.contact m (g.layout m P i) e + +open scoped Classical in +/-- Reindexes `(Σ j, Fin (segmentWidth g m P i z j))` and `(before g m P s hz i).E` by an +equivalence. -/ +def segmentBits : (Σ j, Fin (segmentWidth g m P i z j)) ≃ (before g m P s hz i).E := + let e := (Equiv.sigmaEquivProd E (Fin (P.b * z))).trans s.bits.symm + (Equiv.sumSigmaDistrib _).trans (e.sumCongr + ((Equiv.sumSigmaDistrib _).trans (e.sumCongr (Equiv.sigmaEquivProd _ (Fin z))))) + +open scoped Classical in +theorem endpoints (j : Σ q, Fin (segmentWidth g m P i z q)) : + let D := before g m P s hz i + let H := cluster g m P s hz i + let e := segmentBits g m P s hz i j + (H.owner (D.source e), H.owner (D.target e)) = ends g m P i j.1 := by + let col := g.layout m P i + have old (e : E × Fin (P.b * z)) : + g.assign m P s i (G.source (s.bits.symm e)) = g.route m col (src e.1) (ix e.1) ∧ + g.assign m P s i (G.target (s.bits.symm e)) = g.route m col (dst e.1) (ix e.1) := by + simp only [Grouping.assign, s.left, s.right, Equiv.apply_symm_apply, col, and_self] + rcases j with ⟨j|j|j, t⟩ + · let e : E × Fin (P.b * z) := (j, t) + change (g.assign m P s i (G.source (s.bits.symm e)), + g.locate m col (g.demand m (s.bits (s.bits.symm e))).1) = _ + rw [Equiv.apply_symm_apply] + exact Prod.ext (old e).1 (congrArg Prod.fst (g.locate_demand m col e)) + · let e : E × Fin (P.b * z) := (j, t) + change (g.locate m col (g.demand m (s.bits (s.bits.symm e))).2, + g.assign m P s i (G.target (s.bits.symm e))) = _ + rw [Equiv.apply_symm_apply] + exact Prod.ext (congrArg Prod.snd (g.locate_demand m col e)) (old e).2 + · exact g.locate_supply m col j + +open scoped Classical in +/-- The subtype of `q : Segment g m P i` satisfying `ends g m P i q = (v, v)`. -/ +abbrev Hidden (v : Site V h) := {q : Segment g m P i // ends g m P i q = (v, v)} + +open scoped Classical in +/-- Reindexes `(Σ j : Hidden g m P i v, Fin (segmentWidth g m P i z j.val))` and `(cluster g m P +s hz i).hidden v` by an equivalence. -/ +def hiddenBits (v : Site V h) : + (Σ j : Hidden g m P i v, Fin (segmentWidth g m P i z j.val)) ≃ + (cluster g m P s hz i).hidden v := by + let D := before g m P s hz i + let H := cluster g m P s hz i + let E := segmentBits g m P s hz i + let f (j : Σ j : Hidden g m P i v, Fin (segmentWidth g m P i z j.val)) := E ⟨j.1.val, j.2⟩ + have he (j : Σ j : Hidden g m P i v, Fin (segmentWidth g m P i z j.val)) : + H.owner (D.source (f j)) = v ∧ H.owner (D.target (f j)) = v := + Prod.mk.inj ((endpoints g m P s hz i _).trans j.1.property) + refine Equiv.ofBijective (fun j => ⟨⟨f j, (he j).1.trans (he j).2.symm⟩, (he j).1⟩) ⟨?_, ?_⟩ + · rintro ⟨⟨q, hq⟩, t⟩ ⟨⟨r, hr⟩, u⟩ hh + have eq := E.injective (congrArg (fun x => x.val.val) hh) + cases eq + rfl + · rintro ⟨⟨j, hj⟩, hv⟩ + obtain ⟨⟨q, t⟩, rfl⟩ := E.surjective j + have ht : ends g m P i q = (v, v) := + (endpoints g m P s hz i ⟨q, t⟩).symm.trans (Prod.ext hv (hj.symm.trans hv)) + exact ⟨⟨⟨q, ht⟩, t⟩, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +end + +/- +# Exposed spans of a contracted station + +A surviving unit supplies one new span at each end. The old exterior +spans keep all their own offsets. These are exactly the arguments of +the new station, up to reordering. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround + +open Packing + +open scoped Classical in +/-- In the case `.inl p`, this construction gives `boundaryEnd G p`. -/ +def endIndex {F : Type} {a b : Wire} (G : Diagram F a b) : + (slots a ⊕ slots b) ⊕ (G.E × Bool) ≃ G.End where + toFun + | .inl p => boundaryEnd G p + | .inr (e, t) => cond t (.inr (.inr e)) (.inl (.inr e)) + invFun + | .inl (.inl p) => .inl (.inl p) + | .inr (.inl p) => .inl (.inr p) + | .inl (.inr e) => .inr (e, false) + | .inr (.inr e) => .inr (e, true) + left_inv := by rintro ((_|_)|⟨_, _|_⟩) <;> rfl + right_inv := by rintro ((_|_)|(_|_)) <;> rfl + +variable {F V E : Type} [Field F] [Fintype V] [Fintype E] {a b : Wire} + {N C : V → Finset V} {Δ D h k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (P : Gadget F) {G : Diagram F a b} {z : ℕ} + (s : Bundles G src dst ix (P.b * z)) (hz : 0 < z) (i : g.Choice m P) + {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G) + +open scoped Classical in +/-- Indexes the face by the coordinates of `p.BorderSpan ⊕ (g.Survivors m P i × Bool)`. -/ +abbrev Face := p.BorderSpan ⊕ (g.Survivors m P i × Bool) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def visibleWidth (z : ℕ) : Face g m P i p → ℕ := Sum.elim p.borderWidth (fun _ => z) + +open scoped Classical in +/-- In the case `.inl q`, this construction gives `g.assign m P s i q.val.1`. -/ +def whereAt : Face g m P i p → Site V h + | .inl q => g.assign m P s i q.val.1 + | .inr (e, t) => cond t (g.ends' m P i e).2 (g.ends' m P i e).1 + +open scoped Classical in +/-- Reindexes `(Σ q, Fin (visibleWidth g m P i p z q))` and `(g.contract m P s hz i).End` by an +equivalence. -/ +def faceBits : (Σ q, Fin (visibleWidth g m P i p z q)) ≃ (g.contract m P s hz i).End := + let swap : (g.Survivors m P i × Bool) × Fin z ≃ (g.Survivors m P i × Fin z) × Bool := + ⟨fun q => ((q.1.1, q.2), q.1.2), fun q => ((q.1.1, q.2), q.1.2), fun _ => rfl, fun _ => rfl⟩ + let cut := ((Equiv.sigmaEquivProd _ _).trans swap).trans + ((g.remaining m P s hz i).prodCongr (Equiv.refl Bool)) + ((Equiv.sumSigmaDistrib _).trans (p.exteriorBits.sumCongr cut)).trans (endIndex _) + +open scoped Classical in +theorem face_location (q : Σ j, Fin (visibleWidth g m P i p z j)) : + (g.contract m P s hz i).station (faceBits g m P s hz i p q) = whereAt g m P s i p q.1 := by + rcases q with ⟨q|⟨e, t⟩, j⟩ + · let b : p.BorderBit := ⟨q, j⟩ + have he (b : slots a ⊕ slots _) : + (g.contract m P s hz i).station (boundaryEnd _ b) = g.assign m P s i (portEnd G b) := by + cases b <;> rfl + exact (he (p.exteriorBits b)).trans (congrArg _ (p.border_station b)) + · have he := g.contact_contract m P s hz i (e, j) + cases t + · exact congrArg Prod.fst he + · exact congrArg Prod.snd he + +open scoped Classical in +/-- The subtype of `q : Face g m P i p` satisfying `whereAt g m P s i p q = v`. -/ +abbrev Visible (v : Site V h) := {q : Face g m P i p // whereAt g m P s i p q = v} + +open scoped Classical in +/-- Reindexes `(Σ q : Visible g m P s i p v, Fin (visibleWidth g m P i p z q.val))` and +`(g.contract m P s hz i).Port v` by an equivalence. -/ +def visibleBits (v : Site V h) : + (Σ q : Visible g m P s i p v, Fin (visibleWidth g m P i p z q.val)) ≃ + (g.contract m P s hz i).Port v := by + let D := g.contract m P s hz i + let e := faceBits g m P s hz i p + let f (j : Σ q : Visible g m P s i p v, Fin (visibleWidth g m P i p z q.val)) : + {q : D.End // D.station q = v} := + ⟨e ⟨j.1.val, j.2⟩, (face_location g m P s hz i p _).trans j.1.property⟩ + refine (Equiv.ofBijective f ⟨?_, ?_⟩).trans (D.incident v).symm + · rintro ⟨⟨q, hq⟩, t⟩ ⟨⟨r, hr⟩, u⟩ hh + have eq := e.injective (congrArg Subtype.val hh) + cases eq + rfl + · rintro ⟨j, hj⟩ + obtain ⟨⟨q, t⟩, rfl⟩ := e.surjective j + have hq := (face_location g m P s hz i p ⟨q, t⟩).symm.trans hj + exact ⟨⟨⟨q, hq⟩, t⟩, rfl⟩ + +open scoped Classical in +theorem visible_pin (v : Site V h) (j : Σ q : Visible g m P s i p v, + Fin (visibleWidth g m P i p z q.val)) : + named (g.contract m P s hz i) v (visibleBits g m P s hz i p v j) = + faceBits g m P s hz i p ⟨j.1.val, j.2⟩ := by + let D := g.contract m P s hz i + change ((D.incident v) ((D.incident v).symm _)).val = _ + rw [Equiv.apply_symm_apply] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +end + +/- # Positive occurrences contain a whole unit or a full tether span -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +open Finset + +variable {T F : Type} {x y : Wire} {L : Fringe x y T} {h u : ℕ} + (G : HostNet F L h u) + +open scoped Classical in +theorem parallel_le_tether (i : slots x ⊕ slots y) : G.parallelBits i ≤ G.tetherLoad (G.far i) := by + let _ : DecidableEq (G.V × Cell h) := Classical.typeDecidableEq _ + apply (Nat.cast_le (α := ℝ)).mp + rw [tetherLoad, port_load] + change (G.parallelBits i : ℝ) ≤ push G.far (fun _ => 1) (G.far i) + simp only [parallelBits, Fintype.card_subtype, push, sum_boole, Nat.cast_le] + apply card_le_card + intro j hj + simp only [mem_filter, mem_univ, true_and] at hj ⊢ + exact hj.2 + +open scoped Classical in +theorem incident_floor [Fintype T] (p : G.V × Cell h) (i : G.E) + (hi : (G.pair i).1 = p ∨ (G.pair i).2 = p) : (u : ℝ) ≤ G.load p.1 p.2 := by + have hd : 1 ≤ degree G.pair p := by + rw [degree_sum] + apply le_trans _ (single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ i)) + rcases hi with hi|hi <;> simp [arityCost, hi] + have hh : (u : ℝ) ≤ (degree G.pair p : ℝ) * u := + le_mul_of_one_le_left (Nat.cast_nonneg _) (by exact_mod_cast hd) + exact hh.trans ((le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load _ _)) + +open scoped Classical in +theorem station_floor [Fintype T] (contacts : ∀ i, u ≤ G.tetherLoad (G.far i)) + (v : G.diagram.V) (hv : 0 < G.diagram.arity v) : + (u : ℝ) ≤ G.load (G.units.place v).1 (G.units.place v).2 := by + let p := G.units.place v + have port (i : slots x ⊕ slots y) (hi : portEnd G.diagram i = v) : + (u : ℝ) ≤ G.load p.1 p.2 := by + have hs : G.far i = p := congrArg G.units.place hi + have hh := contacts i + rw [hs] at hh + exact (Nat.cast_le.mpr hh).trans + ((le_add_of_nonneg_right (by positivity)).trans (G.core_le_load _ _)) + rw [← G.diagram.degree] at hv + obtain ⟨⟨q, hq⟩⟩ := Fintype.card_pos_iff.mp hv + rcases q with (i|e)|(i|e) + · exact port (.inl i) hq + · exact G.incident_floor p _ (.inl ((G.units.left e).symm.trans (congrArg G.units.place hq))) + · exact port (.inr i) hq + · exact G.incident_floor p _ (.inr ((G.units.right e).symm.trans (congrArg G.units.place hq))) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- +# Counting the active atoms at a contracted station + +A nonempty old station and an unmatched equality constraint each +consume at least one unit of the old load. Each role of a matched +gadget charges to a distinct wire incidence. Scalar stations may +instead be evaluated when their last port is removed. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +open Finset + +open scoped Classical in +private theorem sum_embedding {A B : Type} [Fintype A] [Fintype B] + (e : A ↪ B) (f : B → ℝ) (hf : ∀ i, 0 ≤ f i) : + ∑ i, f (e i) ≤ ∑ i, f i := by + rw [← sum_map univ e] + exact sum_le_sum_of_subset_of_nonneg (subset_univ _) (fun i _ _ => hf i) + +variable {T F : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} {h u : ℕ} + (G : HostNet F L h u) + {Δ D k : ℕ} {B : ℝ} (g : Grouping G.N G.C Δ D k B G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) + +open scoped Classical in +/-- Indexes the atom by the coordinates of `G.diagram.V ⊕ g.Parties m`. -/ +abbrev Atom := G.diagram.V ⊕ g.Parties m + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `0 < G.diagram.arity v`. -/ +def live : G.Atom g m → Prop + | .inl v => 0 < G.diagram.arity v + | .inr (.inl _) => True + | .inr (.inr p) => ∃ i : m.unpaired, (G.pair i.val).1 = p ∨ (G.pair i.val).2 = p + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `G.units.place v`. -/ +def receipt (col : Bool) : G.Atom g m → G.V × Cell h + | .inl v => G.units.place v + | .inr (.inl q) => g.rep m col q.1 q.2 + | .inr (.inr p) => p + +open scoped Classical in +/-- The construction uses `G.receipt g m col i` for its intermediate `p`. -/ +def anchor (col : Bool) (i : G.Atom g m) := + let p := G.receipt g m col i + g.route m col p.1 p.2 + +open scoped Classical in +/-- The value specified by `![(0, false), (0, true), (1, false), (1, true), if col then (1, +true) else (0, false), if col then (0, true) else (1, true)]`. -/ +def roleCode (col : Bool) : Fin 6 → Fin 2 × Bool := + ![(0, false), (0, true), (1, false), (1, true), + if col then (1, true) else (0, false), if col then (0, true) else (1, true)] + +open scoped Classical in +/-- Embeds `m.items` into `G.E where toFun i`. -/ +def via (col : Bool) (j : Fin 6) : m.items ↪ G.E where + toFun i := m.pairEdge (i, (roleCode col j).1) + inj' _ _ h := (Prod.mk.inj (m.pairEdge.injective h)).1 + +open scoped Classical in +theorem role (col : Bool) (j : Fin 6) (i : m.items) : + g.rep m col i j = cond (roleCode col j).2 (G.pair (G.via g m col j i)).2 + (G.pair (G.via g m col j i)).1 := by + fin_cases j <;> cases col <;> rfl + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun i => G.live g m i ∧ G.anchor g m col i = +z`. -/ +def receipts (col : Bool) (z : Site G.V h) := + univ.filter fun i => G.live g m i ∧ G.anchor g m col i = z + +open scoped Classical in +theorem receipts_bound (contacts : ∀ i, u ≤ G.tetherLoad (G.far i)) + (one : Function.Injective G.units.place) (hB : 0 ≤ B) (col : Bool) (z : Site G.V h) : + (G.receipts g m col z).card * (u : ℝ) ≤ 8 * (near G.C Δ z).card * ((2 : ℝ) ^ k * B) := by + let f (t : G.V × Cell h) := g.route m col t.1 t.2 + let load t := if f t = z then G.load t.1 t.2 else 0 + let hit t := if f t = z then (u : ℝ) else 0 + let value (i : G.Atom g m) := if G.live g m i then hit (G.receipt g m col i) else 0 + have h₀ t : 0 ≤ load t := by unfold load; split_ifs <;> first | exact G.load_nonneg _ _ | rfl + have h₁ t : 0 ≤ hit t := by unfold hit; split_ifs <;> positivity + have hl t (ht : (u : ℝ) ≤ G.load t.1 t.2) : hit t ≤ load t := by + unfold hit load; split_ifs <;> first | exact ht | rfl + have old : ∑ v, value (.inl v) ≤ ∑ t, load t := by + refine le_trans ?_ (sum_embedding ⟨G.units.place, one⟩ load h₀) + apply sum_le_sum + intro v _ + unfold value + split_ifs with hv + · exact hl _ (G.station_floor contacts v hv) + · exact h₀ _ + have check : ∑ t, value (.inr (.inr t)) ≤ ∑ t, load t := by + apply sum_le_sum + intro t _ + unfold value + split_ifs with ht + · obtain ⟨e, he⟩ := ht + exact hl _ (G.incident_floor _ _ he) + · exact h₀ _ + let endpt (p : G.E × Bool) := cond p.2 (G.pair p.1).2 (G.pair p.1).1 + have all : ∑ i, hit (endpt i) ≤ ∑ t, load t := by + have hb t : push endpt (fun _ => (u : ℝ)) t ≤ G.load t.1 t.2 := by + rw [show push endpt _ t = degree G.pair t * (u : ℝ) from + (degree_push (fun i s => endpt (i, s)) u t).symm] + exact (le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load _ _) + unfold hit load + rw [← test_push endpt (fun _ => (u : ℝ)) (fun t => f t = z)] + exact sum_le_sum fun t _ => by split_ifs <;> first | exact hb t | rfl + have gadget (j : Fin 6) : ∑ i, value (.inr (.inl ⟨i, j⟩)) ≤ ∑ t, load t := by + let e := G.via g m col j + let s := (roleCode col j).2 + have he := G.role g m col j + let q : m.items ↪ G.E × Bool := ⟨fun i => (e i, s), fun _ _ eq + => e.injective (Prod.mk.inj eq).1⟩ + refine le_trans ?_ ((sum_embedding q (fun i => hit (endpt i)) (fun i => h₁ _)).trans all) + exact sum_le_sum fun i _ => by simp only [value, live, ite_true, receipt, he]; exact le_rfl + have hsum : (∑ i, value i) ≤ 8 * (∑ t, load t) := by + rw [Fintype.sum_sum_type, Fintype.sum_sum_type, Fintype.sum_sigma, sum_comm] + have hh := sum_le_sum (s := univ) (fun j _ => gadget j) + simp only [sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul, Nat.cast_ofNat] at hh + linarith only [old, check, hh] + have eq : (G.receipts g m col z).card * (u : ℝ) = ∑ i, value i := by + simp only [receipts, ← nsmul_eq_mul, ← sum_const, sum_filter, ite_and] + rfl + rw [eq, mul_assoc] + exact hsum.trans (mul_le_mul_of_nonneg_left (g.route_load m G.cs G.sub G.edge G.load_nonneg hB + col z) + (by norm_num)) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- # Short names for wire ends across adjacent host positions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing + +variable {F T : Type} {x y : Wire} {L : Fringe x y T} {h u : ℕ} + +open scoped Classical in +/-- The short names at a core occurrence need not be unique elsewhere. -/ +structure Navigation (G : HostNet F L h u) (d w : ℕ) where + one : Function.Injective G.units.place + /-- The `Navigation` component of type `G.E → Bool → B w`. -/ + stub : G.E → Bool → B w + separate : ∀ i j b, Scheme.side G i b = Scheme.side G j b → G.ix i = G.ix j → + stub i b = stub j b → i = j + /-- The `Navigation` component of type `G.V → G.V → B d`. -/ + slot : G.V → G.V → B d + /-- The `Navigation` component of type `G.V → B d → G.V`. -/ + nav : G.V → B d → G.V + back : ∀ i, nav (G.dst i) (slot (G.dst i) (G.src i)) = G.src i + +namespace Scheme.Posting +variable [Field F] {S : Scheme F} {r : S.format.obj} {G : HostNet F L h u} + (p : S.Posting r G) (hu : 0 < u) + +include hu + +open scoped Classical in +theorem return_target (i : G.E) : + (r (p.host (G.dst i))).1 (p.index (G.dst i) (G.src i)) = p.host (G.src i) := by + let t : Fin u := ⟨0, hu⟩ + have he := (p.internal (G.units.bits.symm (i, t))).1 + change S.peer r (p.toSeating.ends (endBit G i false t)).1 = + some (p.toSeating.ends (endBit G i true t)).1 at he + rw [(p.ordered _ _ _).1, (p.ordered _ _ _).1] at he + have ht := (p.proper _ _ he).1 + rw [peer, p.link] at ht + exact congrArg (fun q : S.Span => q.1.1) (Option.some.inj ht) + +open scoped Classical in +theorem return_nav (i : G.E) : p.nav (G.dst i) (p.index (G.dst i) (G.src i)) = G.src i := by + have hh : ∃ w, p.host w = (r (p.host (G.dst i))).1 (p.index (G.dst i) (G.src i)) := + ⟨G.src i, (p.return_target hu i).symm⟩ + rw [nav, dite_eq_left hh] + exact p.host.injective (hh.choose_spec.trans (p.return_target hu i)) + +open scoped Classical in +theorem stub_unique (i j : G.E) (b : Bool) (hs : side G i b = side G j b) + (hb : G.ix i = G.ix j) (he : p.stub i b = p.stub j b) : i = j := by + have eq : p.span i b = p.span j b := by simp only [span, spanAt, hs, hb, he] + cases b + · exact p.distinct hu eq + · let t : Fin u := ⟨0, hu⟩ + have peer (i : G.E) : S.peer r (p.span i true) = some (p.span i false) := by + have he := (p.internal (G.units.bits.symm (i, t))).1 + change S.peer r (p.toSeating.ends (endBit G i false t)).1 = + some (p.toSeating.ends (endBit G i true t)).1 at he + rw [(p.ordered _ _ _).1, (p.ordered _ _ _).1] at he + exact (p.proper _ _ he).1 + exact p.distinct hu (Option.some.inj ((peer i).symm.trans ((congrArg _ eq).trans (peer j)))) + +open scoped Classical in +/-- Builds `Navigation (G.regroup a ha) S.d S.e where one v w eq` with the specified `one`, +`have`, `apply`, `separate`. -/ +def navigation (a : ℕ) (ha : a ≤ h) : Navigation (G.regroup a ha) S.d S.e where + one v w eq := by + have ht := (splitAddr G.V a ha).injective eq + apply p.vertex.injective + change G.diagram.V at v w + rw [p.vertex_eq, p.vertex_eq, ht] + stub := p.stub + separate i j b hv hx he := by + have ht : (side G i b, ancestor ha (G.ix i)) = (side G j b, ancestor ha (G.ix j)) := by + cases b <;> exact hv + exact p.stub_unique hu _ _ b (Prod.mk.inj ht).1 + ((splitCell a ha).injective (Prod.ext (Prod.mk.inj ht).2 hx)) he + slot v w := p.index v.1 w.1 + nav := p.groupNav a + back i := Prod.ext (p.return_nav hu i) rfl + +end Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Local identifiers inside a contracted cell + +An atom is specified by a reverse hop to the occurrence that paid for +it, its block, and either a station tag, a gadget role and stub, or +an equality tag. The same short names can be reused at other cells. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +open Coloring Packing HostNet + +open scoped Classical in +/-- Indexes the role by the coordinates of `Unit ⊕ (B w × Fin 6) ⊕ Unit`. -/ +abbrev Role (w : ℕ) := Unit ⊕ (B w × Fin 6) ⊕ Unit +open scoped Classical in +/-- Indexes the atom key by the coordinates of `(Option (B d) × B h) × Role w`. -/ +abbrev AtomKey (d w h : ℕ) := (Option (B d) × B h) × Role w + +variable {T F : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} {h u d w : ℕ} + {G : HostNet F L h u} (p : Navigation G d w) + {Δ D k : ℕ} {B' : ℝ} (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (col : Bool) + +open scoped Classical in +/-- Returns `none` when `v = v'` holds, and `some (p.slot v v')` otherwise. -/ +def reverse (v v' : G.V) : Option (B d) := + if v = v' then none else some (p.slot v v') + +open scoped Classical in +/-- Computes the recover by the application `i.elim v (p.nav v)`. -/ +def recover (v : G.V) (i : Option (B d)) := i.elim v (p.nav v) + +open scoped Classical in +theorem recover_reverse (v : G.V) (b : Cell h) : + let z := (g.route m col v b).1 + p.recover z (p.reverse z v) = v := by + rcases g.route_cases m col v b with he | ⟨i, hi, _, hs, ht⟩ + · rw [he] + change p.recover v (p.reverse v v) = v + simp [reverse, recover] + · have hh : G.src (m.mate i) = v := congrArg Prod.fst hs + rw [ht, ← hh] + change p.recover (G.dst (m.mate i)) (p.reverse (G.dst (m.mate i)) (G.src (m.mate i))) = _ + unfold reverse + split_ifs with eq + · exact eq + · exact p.back _ + +open scoped Classical in +/-- In the case `.inl _`, this construction gives `.inl ()`. -/ +def role : G.Atom g m → Role w + | .inl _ => .inl () + | .inr (.inl i) => .inr (.inl (p.stub (G.via g m col i.2 i.1) (roleCode col i.2).2, i.2)) + | .inr (.inr _) => .inr (.inr ()) + +open scoped Classical in +/-- The atom key of type `AtomKey d w h`, constructed using `G.receipt g m col i`. -/ +def atomKey (i : G.Atom g m) : AtomKey d w h := + let origin := G.receipt g m col i + let toSite := G.anchor g m col i + ((p.reverse toSite.1 origin.1, cellIndex h origin.2), p.role g m col i) + +open scoped Classical in +theorem atom_unique {i j : G.Atom g m} (ha : G.anchor g m col i = G.anchor g m col j) + (hk : p.atomKey g m col i = p.atomKey g m col j) : i = j := by + obtain ⟨hc, hr⟩ := Prod.mk.inj hk + obtain ⟨hv, hb⟩ := Prod.mk.inj hc + have hrec (i : G.Atom g m) : p.recover (G.anchor g m col i).1 + (p.reverse (G.anchor g m col i).1 (G.receipt g m col i).1) = (G.receipt g m col i).1 := + p.recover_reverse g m col _ _ + have hs : G.receipt g m col i = G.receipt g m col j := by + refine Prod.ext ?_ ((cellIndex h).injective hb) + rw [← hrec i, ← hrec j, hv, ha] + rcases i with i|⟨i, a⟩|i <;> rcases j with j|⟨j, b⟩|j <;> + simp only [role, Sum.inl.injEq, Sum.inr.injEq, reduceCtorEq, Prod.mk.injEq] at hr + · exact congrArg Sum.inl (p.one hs) + · obtain ⟨ht, rfl⟩ := hr + have hd (t : m.items) : g.rep m col t a = + (Scheme.side G (G.via g m col a t) (roleCode col a).2, G.ix (G.via g m col a t)) := by + rw [G.role] + cases (roleCode col a).2 <;> rfl + change g.rep m col i a = g.rep m col j a at hs + rw [hd, hd] at hs + have he := p.separate _ _ _ (Prod.mk.inj hs).1 (Prod.mk.inj hs).2 ht + rw [(G.via g m col a).injective he] + · exact congrArg (fun v => Sum.inr (Sum.inr v)) hs + +open scoped Classical in +/-- Embeds `↥(G.receipts g m col z)` into `AtomKey d w h where toFun i`. -/ +def atomNames (z : Site G.V h) : ↥(G.receipts g m col z) ↪ AtomKey d w h where + toFun i := p.atomKey g m col i.val + inj' i j he := Subtype.ext (p.atom_unique g m col + ((Finset.mem_filter.mp i.property).2.2.trans (Finset.mem_filter.mp j.property).2.2.symm) he) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +end + +/- # Short local names for incident and hidden spans -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +open Coloring Packing HostNet History.Subround Spectral.Tensor + +/-- Indexes the stub key by the coordinates of `(AtomKey d w h × Bool) × B w`. -/ +abbrev StubKey (d w h : ℕ) := (AtomKey d w h × Bool) × B w +/-- Indexes the supply key by the coordinates of `Bool × ((AtomKey d w h × Fin 8 × Fin (4 * b)) +⊕ (StubKey d w h × Fin b))`. -/ +abbrev SupplyKey (d w h b : ℕ) := + Bool × ((AtomKey d w h × Fin 8 × Fin (4 * b)) ⊕ (StubKey d w h × Fin b)) +/-- Indexes the span key by the coordinates of `StubKey d w h ⊕ SupplyKey d w h b`. -/ +abbrev SpanKey (d w h b : ℕ) := StubKey d w h ⊕ SupplyKey d w h b + +variable {T F : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} {h u d w : ℕ} + {G : HostNet F L h u} (p : Navigation G d w) + {Δ D k : ℕ} {B' : ℝ} (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (col : Bool) + +/-- The value specified by `.inr (.inr (Scheme.side G e b, G.ix e))`. -/ +def stubAtom (e : G.E) (b : Bool) : G.Atom g m := .inr (.inr (Scheme.side G e b, G.ix e)) + +/-- The value specified by `((p.atomKey g m col (stubAtom g m e b), b), p.stub e b)`. -/ +def stubKey (e : G.E) (b : Bool) : StubKey d w h := + ((p.atomKey g m col (stubAtom g m e b), b), p.stub e b) + +theorem stub_unique {e f : G.E} {a b : Bool} + (hs : G.anchor g m col (stubAtom g m e a) = G.anchor g m col (stubAtom g m f b)) + (he : p.stubKey g m col e a = p.stubKey g m col f b) : (e, a) = (f, b) := by + obtain ⟨he, ht⟩ := Prod.mk.inj he + obtain ⟨he, rfl⟩ := Prod.mk.inj he + have hv := p.atom_unique g m col hs he + obtain ⟨h₁, h₂⟩ := Prod.mk.inj (Sum.inr.inj (Sum.inr.inj hv)) + rw [p.separate e f _ h₁ h₂ ht] + +variable [Field F] (P : Gadget F) (i : g.Choice m P) + +/-- The value specified by `.inr (cond b (g.supplies m e).2 (g.supplies m e).1)`. -/ +def supplyAtom (e : g.Supply m P i) (b : Bool) : G.Atom g m := + .inr (cond b (g.supplies m e).2 (g.supplies m e).1) + +theorem supply_anchor (e : g.Supply m P i) (b : Bool) : + G.anchor g m col (supplyAtom g m P i e b) = + cond b (g.contact m col e).2 (g.contact m col e).1 := by + cases b <;> rcases e with ⟨t, j, k⟩ | ⟨z, k⟩ <;> rfl + +theorem profile_bound (e : m.items) (j : Fin 8) : g.profile m i e j ≤ 4 * P.b := + (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ j)).trans + (P.cost _ (i e).2.property).le + +/-- The supply key of type `SupplyKey d w h P.b` for the given inputs. -/ +def supplyKey (e : g.Supply m P i) (b : Bool) : SupplyKey d w h P.b := + (b, match e with + | .inl ⟨t, j, k⟩ => .inl (p.atomKey g m col (supplyAtom g m P i (.inl ⟨t, j, k⟩) b), + j, k.castLE (profile_bound g m P i t j)) + | .inr (e, k) => .inr (p.stubKey g m col e.val b, k)) + +theorem supply_unique {e f : g.Supply m P i} {a b : Bool} + (hs : G.anchor g m col (supplyAtom g m P i e a) = + G.anchor g m col (supplyAtom g m P i f b)) + (he : p.supplyKey g m col P i e a = p.supplyKey g m col P i f b) : (e, a) = (f, b) := by + obtain ⟨rfl, he⟩ := Prod.mk.inj he + rcases e with ⟨r, j, k⟩ | ⟨r, k⟩ <;> rcases f with ⟨t, j', k'⟩ | ⟨t, k'⟩ + · obtain ⟨ha, hj⟩ := Prod.mk.inj (Sum.inl.inj he) + have ht := p.atom_unique g m col hs ha + have hrt : r = t := by + cases a <;> exact congrArg Sigma.fst (Sum.inl.inj (Sum.inr.inj ht)) + subst t + obtain ⟨rfl, hk⟩ := Prod.mk.inj hj + have hkk : k = k' := Fin.ext (congrArg (fun j : Fin (4 * P.b) => j.val) hk) + subst k' + rfl + · cases he + · cases he + · obtain ⟨ha, rfl⟩ := Prod.mk.inj (Sum.inr.inj he) + have hh : G.anchor g m col (stubAtom g m r.val a) = + G.anchor g m col (stubAtom g m t.val a) := by cases a <;> exact hs + have hrt : r = t := Subtype.ext (Prod.mk.inj (p.stub_unique g m col hh ha)).1 + subst t + rfl + +/-- In the case `.inl e`, this construction gives `.inl (p.stubKey g m (g.layout m P i) e +false)`. -/ +def hiddenKey : Segment g m P i → SpanKey d w h P.b + | .inl e => .inl (p.stubKey g m (g.layout m P i) e false) + | .inr (.inl e) => .inl (p.stubKey g m (g.layout m P i) e true) + | .inr (.inr e) => .inr (p.supplyKey g m (g.layout m P i) P i e false) + +/-- Embeds `Hidden g m P i v` into `SpanKey d w h P.b where toFun e`. -/ +def hiddenNames (v : Site G.V h) : Hidden g m P i v ↪ SpanKey d w h P.b where + toFun e := p.hiddenKey g m P i e.val + inj' := by + rintro ⟨e, he⟩ ⟨f, hf⟩ hk + have hs := congrArg Prod.fst (he.trans hf.symm) + apply Subtype.ext + change e = f + let col := g.layout m P i + rcases e with e|e|e <;> rcases f with f|f|f + · rw [(Prod.mk.inj (p.stub_unique g m col (e := e) (f := f) (a := false) (b := false) hs + (Sum.inl.inj hk))).1] + · have h := (Prod.mk.inj (p.stub_unique g m col (e := e) (f := f) (a := false) (b := true) hs + (Sum.inl.inj hk))).2 + cases h + · cases hk + · have h := (Prod.mk.inj (p.stub_unique g m col (e := e) (f := f) (a := true) (b := false) hs + (Sum.inl.inj hk))).2 + cases h + · rw [(Prod.mk.inj (p.stub_unique g m col (e := e) (f := f) (a := true) (b := true) hs + (Sum.inl.inj hk))).1] + · cases hk + · cases hk + · cases hk + · have hr : G.anchor g m col (supplyAtom g m P i e false) = + G.anchor g m col (supplyAtom g m P i f false) := by + rw [supply_anchor, supply_anchor] + exact hs + rw [(Prod.mk.inj (p.supply_unique g m col P i hr (Sum.inr.inj hk))).1] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +end + +/- # Naming and counting output spans in a local record -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing HostNet History.Subround + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z d : ℕ} + (P : Gadget F) (G : HostNet F L h (P.b * z)) + {Δ D k : ℕ} {B' : ℝ} (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (i : g.Choice m P) + {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G.diagram) + (v : Site G.V h) + +namespace Navigation + +variable (q : Navigation G d S.e) + +open scoped Classical in +/-- The face key used in the `Navigation` construction. -/ +def faceKey : Face g m P i p → SpanKey d S.e h P.b + | .inl e => .inl ((q.atomKey g m (g.layout m P i) (.inl e.val.1), false), e.val.2) + | .inr (e, t) => .inr (q.supplyKey g m (g.layout m P i) P i e.val t) + +open scoped Classical in +/-- Embeds `Visible g m P G.units i p v` into `SpanKey d S.e h P.b where toFun e`. -/ +def visibleNames : Visible g m P G.units i p v ↪ SpanKey d S.e h P.b where + toFun e := faceKey P G g m i p q e.val + inj' := by + rintro ⟨e, he⟩ ⟨f, hf⟩ hkey + apply Subtype.ext + change e = f + let col := g.layout m P i + rcases e with e|⟨e, a⟩ <;> rcases f with f|⟨f, b⟩ + · obtain ⟨hk, hl⟩ := Prod.mk.inj (Sum.inl.inj hkey) + have ha : G.anchor g m col (.inl e.val.1) = G.anchor g m col (.inl f.val.1) + := he.trans hf.symm + have h := q.atom_unique g m col ha (Prod.mk.inj hk).1 + exact congrArg Sum.inl (Subtype.ext (Prod.ext (Sum.inl.inj h) hl)) + · cases hkey + · cases hkey + · have ha : G.anchor g m col (supplyAtom g m P i e.val a) = + G.anchor g m col (supplyAtom g m P i f.val b) := by + rw [supply_anchor, supply_anchor] + exact he.trans hf.symm + obtain ⟨hh, rfl⟩ := Prod.mk.inj (q.supply_unique g m col P i ha (Sum.inr.inj hkey)) + rw [Subtype.ext hh] + +end Navigation + +namespace History.Subround + +open scoped Classical in +theorem visible_bound (hz : 0 < z) (hB : 0 ≤ B') (hw : ∀ q, z ≤ p.borderWidth q) : + Fintype.card (Visible g m P G.units i p v) * (z : ℝ) + ≤ 9 * (near G.C Δ v).card * ((2 : ℝ) ^ k * B') := by + let A := Visible g m P G.units i p v + let C := g.contract m P G.units hz i + have hlen (q : A) : z ≤ visibleWidth g m P i p z q.val := by + rcases q with ⟨q|q, _⟩ + · exact hw q + · exact le_rfl + have he : Fintype.card A * z ≤ C.arity v := by + have eq := Fintype.card_congr (visibleBits g m P G.units hz i p v) + simp only [Fintype.card_sigma, Fintype.card_fin, Diagram.Port, Fintype.card_sum, card_slots] + at eq + have := Finset.sum_le_sum (s := Finset.univ) (fun q _ => hlen q) + rw [Finset.sum_const, Finset.card_univ, Nat.nsmul_eq_mul] at this + exact this.trans_eq eq + have hi (t : G.V × Cell h) : (P.b * z : ℕ) * (degree G.pair t : ℝ) ≤ G.load t.1 t.2 := by + rw [mul_comm] + exact (le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load _ _) + have ho (t : G.V × Cell h) : (exterior G.diagram G.units.place t : ℝ) ≤ G.load t.1 t.2 := + (le_add_of_nonneg_right (by positivity)).trans (G.core_le_load _ _) + refine le_trans ?_ (g.load_contract m P G.units hz G.cs G.sub G.edge G.load_nonneg hB hi ho i v) + rw [← Nat.cast_mul] + exact Nat.cast_le.mpr he + +end History.Subround +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Guard.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Guard.lean new file mode 100644 index 0000000000..e89c7c6ec7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Guard.lean @@ -0,0 +1,957 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.State +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Checks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Radius +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Prefix + +/-! +# One selector per selected thin row + +At an active seat the word is a zero-based index into the fixed +gadget menu. Every unused seat must contain zero, so padding +introduces no extra multiplicity in the sum over selectors. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing Transcript Finset + +namespace Branches + +open scoped Classical in +/-- Indexes the slot by the coordinates of `(B m × B a) × B n`. -/ +abbrev Slot (m a n : ℕ) := (B m × B a) × B n + +open scoped Classical in +/-- The indexed operation `Fmt.pi (fun _ : Slot m a n => Format.addr b)`. -/ +abbrev format (m a n b : ℕ) := Fmt.pi (fun _ : Slot m a n => Format.addr b) + +variable {I J A : Type} [Fintype A] {b : ℕ} + (row : I ↪ J) (hb : Fintype.card A ≤ 2 ^ b) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def selector : Transcript.Selector (I → A) (J → B b) where + write f := Function.extend row (fun i => Fin.castLE hb (Fintype.equivFin A (f i))) (fun _ => 0) + read x := + if h : (∀ i, (x (row i)).val < Fintype.card A) ∧ (∀ j ∉ Set.range row, x j = 0) then + some (fun i => (Fintype.equivFin A).symm ⟨(x (row i)).val, h.1 i⟩) else none + valid x f := by + constructor + · split + · rename_i h + intro he + cases Option.some.inj he + funext j + by_cases hj : j ∈ Set.range row + · obtain ⟨i, rfl⟩ := hj + rw [row.injective.extend_apply, Equiv.apply_symm_apply] + rfl + · rw [Function.extend_apply' _ _ _ hj, h.2 j hj] + · simp + · rintro rfl + split + · congr 1 + funext i + apply (Fintype.equivFin A).injective + rw [Equiv.apply_symm_apply] + apply Fin.ext + simp only [row.injective.extend_apply, Fin.val_castLE] + · rename_i h + exfalso + apply h + exact ⟨fun i => by rw [row.injective.extend_apply]; exact (Fintype.equivFin A (f i)).isLt, + fun j hj => Function.extend_apply' _ _ _ hj⟩ + +open scoped Classical in +theorem write_at (f : I → A) (i : I) : + (selector row hb).write f (row i) = Fin.castLE hb (Fintype.equivFin A (f i)) := + by simp only [selector, row.injective.extend_apply] + +open scoped Classical in +theorem write_pad (f : I → A) (j : J) (hj : j ∉ Set.range row) : + (selector row hb).write f j = 0 := by simp only [selector, Function.extend_apply' _ _ _ hj] + +open scoped Classical in +/-- Returns `x.val < N` when `mark` holds, and `x = 0` otherwise. -/ +def valid (N : ℕ) (mark : Bool) (x : B b) : Prop := + if mark then x.val < N else x = 0 + +open scoped Classical in +theorem valid_iff (mask : J → Bool) (hm : ∀ j, mask j = true ↔ j ∈ Set.range row) + (x : J → B b) : + ((selector row hb).read x).isSome ↔ ∀ j, valid (Fintype.card A) (mask j) (x j) := by + unfold selector + dsimp only + split + · rename_i h + simp only [Option.isSome_some, true_iff] + intro j + unfold valid + split_ifs with hj + · obtain ⟨i, rfl⟩ := (hm j).mp hj + exact h.1 i + · exact h.2 j (mt (hm j).mpr hj) + · rename_i h + simp only [Option.isSome_none, Bool.false_eq_true, false_iff] + intro hx + apply h + constructor + · intro i + simpa only [valid, ite_eq_left ((hm _).mpr ⟨i, rfl⟩)] using hx (row i) + · intro j hj + simpa only [valid, ite_eq_right (mt (hm j).mp hj)] using hx j + +open scoped Classical in +/-- Returns `1` when `valid N mark x` holds, and `0` otherwise. -/ +def test (F : Type) [Field F] (N : ℕ) (mark : Bool) (x : B b) : F := + if valid N mark x then 1 else 0 + +open scoped Classical in +theorem guard [Fintype J] (F : Type) [Field F] (mask : J → Bool) + (hm : ∀ j, mask j = true ↔ j ∈ Set.range row) (x : J → B b) : + (∏ j, test F (Fintype.card A) (mask j) (x j)) = ((selector row hb).read x).elim 0 (fun _ => 1) + := by + have hv := valid_iff row hb mask hm x + cases hr : (selector row hb).read x with + | some f => + have ht := hv.mp (by simp [hr]) + simp [test, ht] + | none => + have ht := mt hv.mpr (show ¬((selector row hb).read x).isSome by simp [hr]) + push Not at ht + obtain ⟨j, hj⟩ := ht + exact prod_eq_zero (mem_univ j) (ite_eq_right hj) + +variable {F : Type} [Field F] (P : Gadget F) + +open scoped Classical in +/-- Indexes the tag by the coordinates of `Fin P.copies × ↥P.shapes`. -/ +abbrev Tag := Fin P.copies × ↥P.shapes + +open scoped Classical in +/-- Returns `some ((Fintype.equivFin (Tag P)).symm ⟨x.val, h⟩)` when `h : x.val < Fintype.card +(Tag P)` holds, and `none` otherwise. -/ +def read (x : B b) : ChoiceTag P := + if h : x.val < Fintype.card (Tag P) then some ((Fintype.equivFin (Tag P)).symm ⟨x.val, + h⟩) else none + +open scoped Classical in +theorem read_write (hb : Fintype.card (Tag P) ≤ 2 ^ b) (f : I → Tag P) (i : I) : + read P ((selector row hb).write f (row i)) = some (f i) := by + rw [write_at] + unfold read + simp only [Fin.val_castLE, Fin.is_lt, dite_eq_left, Fin.eta, Equiv.symm_apply_apply] + +end Branches + +namespace Scheme.Posting +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u h : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h u} + (p : S.Posting r G) (hu : 0 < u) (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' (G.regroup a ha).load) + (m : Matchings a ha g) (ctl : p.Controls hu a ha g m) + +open scoped Classical in +/-- Computes the place group by the application `p.host.prodMap (cellIndex a).toEmbedding`. -/ +def placeGroup : G.V × Cell a ↪ B S.m × B a := p.host.prodMap (cellIndex a).toEmbedding + +open scoped Classical in +/-- Embeds `m.items` into `Branches.Slot S.m a (h - a + S.e)`. -/ +def seats : m.items ↪ Branches.Slot S.m a (h - a + S.e) := + (p.chart hu a ha g m ctl).marked.trans ((p.placeGroup a).prodMap (.refl _)) + +open scoped Classical in +theorem seats_iff (mask : Branches.Slot S.m a (h - a + S.e) → Bool) + (live : ∀ v j, mask (p.placeGroup a v, j) = (Match.rows (p.records a ha g m.color v)).control.1 + j) + (pad : ∀ v ∉ Set.range (p.placeGroup a), ∀ j, mask (v, j) = false) + (j : Branches.Slot S.m a (h - a + S.e)) : + mask j = true ↔ j ∈ Set.range (p.seats hu a ha g m ctl) := by + let c := p.chart hu a ha g m ctl + rcases j with ⟨v, j⟩ + constructor + · intro hm + have hv : v ∈ Set.range (p.placeGroup a) := by + by_contra hn + rw [pad v hn j] at hm + cases hm + obtain ⟨w, rfl⟩ := hv + rw [live] at hm + obtain ⟨i, hi⟩ := (c.marks (w, j)).mp hm + exact ⟨i, congrArg (fun t => (p.placeGroup a t.1, t.2)) hi⟩ + · rintro ⟨i, hi⟩ + rw [← hi] + change mask (p.placeGroup a (c.marked i).1, (c.marked i).2) = true + rw [live] + exact (c.marks _).mpr ⟨i, rfl⟩ + +variable (P : Gadget F) {b : ℕ} (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) + +open scoped Classical in +/-- Computes the branches by the application `Branches.selector (p.seats hu a ha g m ctl) hb`. -/ +def branches : Transcript.Selector (g.Choice m P) (Branches.format S.m a (h - a + S.e) b).obj := + Branches.selector (p.seats hu a ha g m ctl) hb + +open scoped Classical in +theorem read_branch (i : g.Choice m P) (j : m.items) : + Branches.read P ((p.branches hu a ha g m ctl P hb).write i (p.seats hu a ha g m ctl j)) = + some (i j) := + Branches.read_write _ P hb i j + +open scoped Classical in +theorem guard_branch (mask : Branches.Slot S.m a (h - a + S.e) → Bool) + (hm : ∀ j, mask j = true ↔ j ∈ Set.range (p.seats hu a ha g m ctl)) + (word : (Branches.format S.m a (h - a + S.e) b).obj) : + (∏ j, Branches.test F (Fintype.card (Branches.Tag P)) (mask j) (word j)) = + ((p.branches hu a ha g m ctl P hb).read word).elim 0 (fun _ => 1) := + Branches.guard _ hb F mask hm word + +end Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Ordering the incidences of an untouched-wire checker + +Order by side and local stub number. No global host or edge identifier +occurs in this order. Both ends of a loop use its source's hidden key. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing Navigation.Emission Finset + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} + {a h z Δ D k : ℕ} {B' : ℝ} (u : State S P a h z Δ D k B') + +open scoped Classical in +/-- Indexes the occurrence by the coordinates of `u.H.V × Cell (h - a)`. -/ +abbrev Occurrence := u.H.V × Cell (h - a) +open scoped Classical in +/-- Uses `History.Subround.CheckRow u.g u.m o` as the representation. -/ +abbrev CheckRow (o : u.Occurrence) := History.Subround.CheckRow u.g u.m o + +open scoped Classical in +/-- Embeds `u.CheckRow o` into `Lex (Bool × B S.e) where toFun j`. -/ +def checkName (o : u.Occurrence) : u.CheckRow o ↪ Lex (Bool × B S.e) where + toFun j := toLex (j.val.2, u.q.stub j.val.1.val j.val.2) + inj' := by + rintro ⟨⟨e, s⟩, he⟩ ⟨⟨f, t⟩, hf⟩ h + obtain ⟨rfl, hk⟩ := Prod.mk.inj (toLex.injective h) + have hv := Prod.mk.inj (he.trans hf.symm) + exact Subtype.ext (Prod.ext (Subtype.ext (u.q.separate _ _ _ hv.1 hv.2 hk)) rfl) + +open scoped Classical in +theorem check_size (o : u.Occurrence) : Fintype.card (u.CheckRow o) ≤ 2 ^ (S.e + 1) := by + let f := (u.checkName o).trans ofLex.toEmbedding + simpa only [Fintype.card_prod, Fintype.card_fin, Fintype.card_bool, pow_succ'] using + Fintype.card_le_of_injective f f.injective + +open scoped Classical in +/-- Reindexes `Fin (Fintype.card (u.CheckRow o))` and `u.CheckRow o` by an equivalence. -/ +def checkOrder (o : u.Occurrence) : Fin (Fintype.card (u.CheckRow o)) ≃ u.CheckRow o := + let s := univ.map (u.checkName o) + let f : u.CheckRow o ≃ ↥s := Equiv.ofBijective + (fun i => ⟨u.checkName o i, mem_map_of_mem _ (mem_univ i)⟩) + ⟨fun _ _ h => (u.checkName o).injective (congrArg Subtype.val h), fun j => by + obtain ⟨i, _, hi⟩ := mem_map.mp j.property + exact ⟨i, Subtype.ext hi⟩⟩ + (s.orderIsoOfFin (by simp [s])).toEquiv.trans f.symm + +open scoped Classical in +theorem check_index (o : u.Occurrence) (i : u.CheckRow o) : + ((u.checkOrder o).symm i).val = + @List.idxOf _ instBEqOfDecidableEq (u.checkName o i) (univ.map (u.checkName o)).sort := by + let s := univ.map (u.checkName o) + have hc : s.card = Fintype.card (u.CheckRow o) := by simp [s] + exact orderIsoOfFin_symm_apply s hc ⟨u.checkName o i, mem_map_of_mem _ (mem_univ i)⟩ + +open scoped Classical in +/-- The value specified by `decide (u.g.route u.m u.col (u.H.src e) (u.H.ix e) = u.g.route u.m +u.col (u.H.dst e) (u.H.ix e))`. -/ +def loop (e : u.H.E) : Bool := + decide (u.g.route u.m u.col (u.H.src e) (u.H.ix e) = u.g.route u.m u.col (u.H.dst e) (u.H.ix e)) + +open scoped Classical in +/-- Computes the check tips by the application `u.q.tip u.g u.m u.col i.val.1.val`. -/ +def checkTips {o : u.Occurrence} (i : u.CheckRow o) := u.q.tip u.g u.m u.col i.val.1.val + +open scoped Classical in +/-- The value specified by `check (b := P.b) (u.checkTips i) (u.loop i.val.1.val) i.val.2`. -/ +def checkPtr {o : u.Occurrence} (i : u.CheckRow o) := + check (b := P.b) (u.checkTips i) (u.loop i.val.1.val) i.val.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Checker ordering and pointers are determined by the receiving window -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing Navigation.Emission Finset + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} + {a h z Δ D k n : ℕ} {B' : ℝ} {u v : State S P a h z Δ D k B'} + (same : u.Same v n) (hn : 4 ≤ n) + {x : u.Occurrence} {y : v.Occurrence} + (hx : u.g.route u.m u.col x.1 x.2 = u.v) (hy : v.g.route v.m v.col y.1 y.2 = v.v) + (hs : u.q.stamp u.g u.m u.col x = v.q.stamp v.g v.m v.col y) + +include same hn hx hy hs + +open scoped Classical in +private theorem check_match (i : u.CheckRow x) : + ∃ j : v.CheckRow y, u.checkName x i = v.checkName y j ∧ + i.val.2 = j.val.2 ∧ u.checkTips i = v.checkTips j ∧ + u.loop i.val.1.val = v.loop j.val.1.val := by + obtain ⟨⟨e, b⟩, hi⟩ := i + let r := u.c.row e.val + let w := same.agree.restrict hn + have he : u.g.route u.m u.col (Scheme.side u.H e.val b) (u.H.ix e.val) = u.v := + (congrArg (fun t : u.Occurrence => u.g.route u.m u.col t.1 t.2) hi).trans hx + have win : r.1 ∈ u.env.issuers := by + have h := u.q.window_end u.g u.m u.col e.val b + have ht : (u.g.route u.m u.col (Scheme.side u.H e.val b) (u.H.ix e.val)).1 = u.v.1 := + congrArg Prod.fst he + exact (congrArg (fun v => u.H.src e.val ∈ u.q.neighborhood v) ht).mp h + obtain ⟨p, _, rel⟩ := Window.Related.issuers (β := v.env) win + have unt : Match.untouched v.env.data (p, r.2) = true := + (w.untouched rel r.2).symm.trans ((u.c.untouched_iff r).mpr ⟨e, rfl⟩) + obtain ⟨f, hf⟩ := (v.c.untouched_iff (p, r.2)).mp unt + have tip (s : Bool) : u.q.tip u.g u.m u.col e.val s = v.q.tip v.g v.m v.col f.val s := by + have h := w.tip rel (by decide) u.col r.2 s + have h' : u.env.tip u.col r.1 r.2 s = v.env.tip v.col (v.c.row f.val).1 (v.c.row f.val).2 s + := by + rw [hf, ← same.layout] + exact h + exact (u.p.tip_eq u.hu a u.ha u.g u.m u.ctl u.col e.val s).trans + (h'.trans (v.p.tip_eq v.hu a v.ha v.g v.m v.ctl v.col f.val s).symm) + have loc (s : Bool) : Window.Names u.env v.env + (u.c.site (u.g.route u.m u.col (Scheme.side u.H e.val s) (u.H.ix e.val))) + (v.c.site (v.g.route v.m v.col (Scheme.side v.H f.val s) (v.H.ix f.val))) := by + have h' : Window.Names u.env v.env (oldAt u.env.nav u.env.data u.col r s) + (oldAt v.env.nav v.env.data v.col (v.c.row f.val) s) := by + rw [hf, ← same.layout] + exact w.oldAt rel u.col r.2 s + exact (u.p.oldAt_eq u.hu a u.ha u.g u.m u.ctl u.i e.val s) ▸ + (v.p.oldAt_eq v.hu a v.ha v.g v.m v.ctl v.i f.val s) ▸ h' + have center : Window.Names u.env v.env (u.c.site u.v) (v.c.site v.v) := + ⟨Window.related_root.widen (by decide), same.key⟩ + have hf' := v.c.site.injective ((w.identical (loc b) center).mp (congrArg u.c.site he)) + have hh : (Scheme.side v.H f.val b, v.H.ix f.val) = y := by + have hstamp := (congrArg Prod.fst (tip b)).symm.trans + ((congrArg (u.q.stamp u.g u.m u.col) hi).trans hs) + have ha : v.H.anchor v.g v.m v.col (Navigation.stubAtom v.g v.m f.val b) = + v.H.anchor v.g v.m v.col (.inr (.inr y)) := hf'.trans hy.symm + have ha' := v.q.atom_unique v.g v.m v.col ha (congrArg (checker (w := S.e)) hstamp) + exact Sum.inr.inj (Sum.inr.inj ha') + refine ⟨⟨(f, b), hh⟩, ?_, rfl, funext tip, ?_⟩ + · exact congrArg (fun t : Tip S.d S.e (h - a) => toLex (b, t.2)) (tip b) + · have heq := w.identical (loc false) (loc true) + erw [u.c.site.injective.eq_iff, v.c.site.injective.eq_iff] at heq + exact decide_eq_decide.mpr heq + +open scoped Classical in +private theorem check_names : univ.map (u.checkName x) = univ.map (v.checkName y) := by + ext t + constructor + · intro ht + obtain ⟨i, _, rfl⟩ := mem_map.mp ht + obtain ⟨j, hj, _⟩ := check_match same hn hx hy hs i + exact mem_map.mpr ⟨j, mem_univ _, hj.symm⟩ + · intro ht + obtain ⟨j, _, rfl⟩ := mem_map.mp ht + obtain ⟨i, hi, _⟩ := check_match same.symm hn hy hx hs.symm j + exact mem_map.mpr ⟨i, mem_univ _, hi.symm⟩ + +open scoped Classical in +theorem Same.checkCount : Fintype.card (u.CheckRow x) = Fintype.card (v.CheckRow y) := by + simpa only [card_map, card_univ] using congrArg Finset.card (check_names same hn hx hy hs) + +open scoped Classical in +theorem Same.check_eq (i : Fin (Fintype.card (u.CheckRow x))) (j : Fin (Fintype.card (v.CheckRow + y))) + (he : i.val = j.val) : + let t := u.checkOrder x i + let t' := v.checkOrder y j + t.val.2 = t'.val.2 ∧ u.checkTips t = v.checkTips t' ∧ u.loop t.val.1.val = v.loop t'.val.1.val + := by + obtain ⟨t, ht, hh⟩ := check_match same hn hx hy hs (u.checkOrder x i) + have hij : (v.checkOrder y).symm t = j := by + apply Fin.ext + rw [v.check_index, ← check_names same hn hx hy hs, ← ht, ← u.check_index, + Equiv.symm_apply_apply, he] + rwa [(v.checkOrder y).symm_apply_eq.mp hij] at hh + +open scoped Classical in +theorem Same.checkPtr_eq (i : Fin (Fintype.card (u.CheckRow x))) (j : Fin (Fintype.card (v.CheckRow + y))) + (he : i.val = j.val) : + u.checkPtr (u.checkOrder x i) = v.checkPtr (v.checkOrder y j) := by + obtain ⟨a, b, c⟩ := same.check_eq hn hx hy hs i j he + simp only [checkPtr, a, b, c] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Recovering a gadget selector and its endpoint designations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing Match Window Navigation.Emission + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k n : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') + +open scoped Classical in +private theorem locate_party (i : u.m.items) (j : Fin 6) : + let r := u.c.marked i + readPath u.env.nav r.1 (localParties u.env.nav u.env.data u.col r.1 r.2 j) = + u.c.site (u.g.party u.m u.col i j) := u.c.gadget u.col i j + +open scoped Classical in +private theorem local_tips (i : u.m.items) : + u.q.tips u.g u.m u.col i = u.env.tips u.col (u.c.marked i).1 (u.c.marked i).2 := + u.p.tips_eq u.hu a u.ha u.g u.m u.ctl u.col i + +variable {u} {v : State S P a h z Δ D k B'} + +open scoped Classical in +private theorem Same.center (e : u.Same v n) : Names u.env v.env (u.c.site u.v) (v.c.site v.v) := + ⟨related_root.widen (by decide), e.key⟩ + +open scoped Classical in +/-- An aligned selected row has the same selector, tips and contact +pattern, even if the two instances use different global host numbers. -/ +theorem Same.gadget (e : u.Same v n) (hn : 4 ≤ n) {i : u.m.items} {j : v.m.items} {r t : Fin 6} + (hu : u.g.party u.m u.col i r = u.v) (hv : v.g.party v.m v.col j t = v.v) + (hk : u.q.atomKey u.g u.m u.col (.inr (.inl ⟨i, r⟩)) = + v.q.atomKey v.g v.m v.col (.inr (.inl ⟨j, t⟩))) : + u.i i = v.i j ∧ r = t ∧ u.q.tips u.g u.m u.col i = v.q.tips v.g v.m v.col j ∧ + ∀ t, Names u.env v.env (u.c.site (u.g.party u.m u.col i t)) + (v.c.site (v.g.party v.m v.col j t)) := by + have he : r = t := (Prod.mk.inj (Sum.inl.inj (Sum.inr.inj (Prod.mk.inj hk).2))).2 + subst t + let row := u.c.marked i + have hr : row.1 ∈ u.env.issuers := by + change u.H.src i.val ∈ u.q.neighborhood u.v.1 + have ht : u.H.src i.val ∈ u.q.neighborhood (u.g.party u.m u.col i r).1 := + u.q.window_party u.g u.m u.col i r + rwa [hu] at ht + obtain ⟨w, _, hw⟩ := Related.issuers (β := v.env) hr + have a := e.agree.restrict hn + obtain ⟨hd, _, hs⟩ := a.records hw (by decide) + have hm : (rows (u.env.data row.1)).control.1 row.2 = true := (u.c.marks row).mpr ⟨i, rfl⟩ + rw [hd] at hm + obtain ⟨f, hf⟩ := (v.c.marks (w, row.2)).mp hm + have selector : u.i i = v.i f := by + have he := congrArg (fun t => t.2 row.2) hs + change u.selector row = v.selector (w, row.2) at he + rw [← hf] at he + exact Option.some.inj ((u.selected i).symm.trans (he.trans (v.selected f))) + have tips : u.q.tips u.g u.m u.col i = v.q.tips v.g v.m v.col f := by + rw [local_tips, local_tips, hf, e.layout] + exact a.tips hw (by decide) _ _ + have dest (t : Fin 6) : Names u.env v.env (u.c.site (u.g.party u.m u.col i t)) + (v.c.site (v.g.party v.m v.col f t)) := by + rw [← u.locate_party, ← v.locate_party, hf, e.layout] + exact a.gadget hw _ _ _ + have hl : v.g.party v.m v.col f r = v.v := + v.c.site.injective ((a.identical (dest r) e.center).mp (congrArg u.c.site hu)) + have hkey : v.q.atomKey v.g v.m v.col (.inr (.inl ⟨f, r⟩)) = + v.q.atomKey v.g v.m v.col (.inr (.inl ⟨j, r⟩)) := by + refine (v.q.atom_party v.g v.m v.col f r).trans (Eq.trans ?_ + ((u.q.atom_party u.g u.m u.col i r).symm.trans hk)) + exact congrArg₂ (fun c t => Navigation.Emission.party c t r) e.layout.symm tips.symm + have eq : f = j := by + have he := v.q.atom_unique v.g v.m v.col (i := .inr (.inl ⟨f, r⟩)) (j := .inr (.inl ⟨j, r⟩)) + (hl.trans hv.symm) hkey + exact congrArg Sigma.fst (Sum.inl.inj (Sum.inr.inj he)) + subst j + exact ⟨selector, rfl, tips, dest⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Checking all selector seats without changing the records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Branches + +open Coloring Finset + +variable {F : Type} [Field F] {u b : ℕ} {L : Set (Table F)} + +open scoped Classical in +/-- The indexed operation `Fmt.pi (fun _ : J => Side.Entry b)`. -/ +abbrev Marked (J : Type) [Fintype J] (b : ℕ) := Fmt.pi (fun _ : J => Side.Entry b) + +open scoped Classical in +/-- The quantity computed by `32 * 2 ^ (2 * b + 2)`. -/ +def charge (b : ℕ) := 32 * 2 ^ (2 * b + 2) + +open scoped Classical in +private theorem one (hu : 3 ≤ u) (N : ℕ) : + Action F u L (Side.Entry b) (Side.Entry b) id (fun q => test F N q.1 q.2) (charge b) := by + intro a c i j + let : DecidableEq (Side.Entry b).obj := Classical.typeDecidableEq _ + let k (x : Val a) (y : Val c) := + let q := view (Side.Entry b) i x + if q = view (Side.Entry b) j y then test F N q.1 q.2 else 0 + obtain ⟨s, hs, hb⟩ := Net.dense a c k + obtain ⟨t, ht, hw⟩ := hs.includeWide (L := L) hu + refine ⟨t, ht.trans ?_, hw⟩ + have hi := Fintype.card_congr i + have hj := Fintype.card_congr j + rw [card_slots] at hi hj + have he : (Side.Entry b).width = 1 + b := by simp [Side.Entry] + change Fintype.card (Side.Entry b).pins = _ at he + rw [show wd a + wd c = 2 * b + 2 by omega] at hb + unfold charge + omega + +open scoped Classical in +theorem check {J : Type} [Fintype J] (hu : 3 ≤ u) (N : ℕ) : + Action F u L (Marked J b) (Marked J b) id (fun x => ∏ j, test F N (x j).1 (x j).2) + (Fintype.card J * charge b) := by + have hw := Kernel.family (fun _ : J => one (L := L) (b := b) hu N) + rw [sum_const, card_univ, Nat.nsmul_eq_mul] at hw + unfold Action + convert hw using 1 + funext x y + by_cases h : x = y + · subst y; simp + · obtain ⟨j, hj⟩ := Function.ne_iff.mp h + rw [id_eq, ite_eq_right h] + exact (prod_eq_zero (mem_univ j) (ite_eq_right hj)).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Branches +end + +/- # Recovering gadget and checker links from a local window -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Packing History.Subround Navigation.Emission Spectral.Tensor + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} + {a h z Δ D k n : ℕ} {B' : ℝ} (u : State S P a h z Δ D k B') + +open scoped Classical in +private def rolePtr {d w l : ℕ} (col : Bool) (tips : Fin 2 → Bool → Tip d w l) + (loop : Fin 8 → Bool) (r : History.Role P) : r.Port → Bool × Navigation.SpanKey d w l P.b + | .inl p => (true, demand (tips p.val.1 p.val.2) p.val.2) + | .inr p => pointer col tips (.inl (p.val.1, p.val.2.castLE (by + exact (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ p.val.1)).trans + (P.cost _ r.1.2.property).le))) (loop p.val.1) (r.side p) + +open scoped Classical in +private def roleLoop (i : u.m.items) (q : Fin 8) := + decide (u.g.party u.m u.col i (sixPair q).1 = u.g.party u.m u.col i (sixPair q).2) + +open scoped Classical in +private theorem role_key (i : u.m.items) (j : Fin 6) + (hv : u.g.party u.m u.col i j = u.v) (q : (role u.g u.m P u.i i j).Port) : + u.q.portKey P u.g u.m u.i u.p.toPresentation u.v + (matchLinks u.g u.m P u.H.units u.i u.p.toPresentation u.v i j hv q) = + rolePtr u.col (u.q.tips u.g u.m u.col i) (u.roleLoop i) (u.i i, j) q := by + cases q with + | inl q => + exact u.q.portKey_demand P u.g u.m u.i u.p.toPresentation u.v _ _ + ((match_demand u.g u.m P u.i i j q).trans hv) + | inr q => + refine (u.q.portKey_supply P u.g u.m u.i u.p.toPresentation u.v _ _ + (match_site u.g u.m P u.i u.v i j hv q)).trans ?_ + simp only [rolePtr, roleLoop, roleEdge, Navigation.eventTips, Navigation.eventKind, + Grouping.contact] + congr 1 + +open scoped Classical in +private theorem checker_key (o : u.Occurrence) (hv : u.g.route u.m u.col o.1 o.2 = u.v) + (i : Fin (Fintype.card (u.CheckRow o))) (t : Option (Fin P.b)) : + u.q.portKey P u.g u.m u.i u.p.toPresentation u.v + (checkLinks u.g u.m P u.H.units u.i u.p.toPresentation u.v o hv (u.checkOrder o) (i, t)) = + u.checkPtr (u.checkOrder o i) t := by + cases t with + | none => + exact u.q.portKey_demand P u.g u.m u.i u.p.toPresentation u.v _ _ + (check_demand u.g u.m P u.i u.v o hv (u.checkOrder o i)) + | some t => + refine (u.q.portKey_supply P u.g u.m u.i u.p.toPresentation u.v _ _ + (check_site u.g u.m P u.i u.v o hv (u.checkOrder o i) t)).trans ?_ + simp only [checkPtr, check, checkTips, loop, checkEdge, Navigation.eventTips, + Navigation.eventKind, Grouping.contact] + apply congrArg (fun d => pointer false (fun _ => u.checkTips (u.checkOrder o i)) + (.inr t) d (u.checkOrder o i).val.2) + exact decide_eq_decide.mpr Iff.rfl + +variable {u} {v : State S P a h z Δ D k B'} + +open scoped Classical in +theorem Same.check_key (same : u.Same v n) (hn : 4 ≤ n) {x : u.Occurrence} {y : v.Occurrence} + (hx : u.g.route u.m u.col x.1 x.2 = u.v) (hy : v.g.route v.m v.col y.1 y.2 = v.v) + (hs : u.q.stamp u.g u.m u.col x = v.q.stamp v.g v.m v.col y) + (i : Fin (Fintype.card (u.CheckRow x))) (j : Fin (Fintype.card (v.CheckRow y))) + (he : i.val = j.val) (t : Option (Fin P.b)) : + u.q.portKey P u.g u.m u.i u.p.toPresentation u.v + (checkLinks u.g u.m P u.H.units u.i u.p.toPresentation u.v x hx (u.checkOrder x) (i, t)) = + v.q.portKey P v.g v.m v.i v.p.toPresentation v.v + (checkLinks v.g v.m P v.H.units v.i v.p.toPresentation v.v y hy (v.checkOrder y) (j, t)) + := by + rw [checker_key, checker_key, same.checkPtr_eq hn hx hy hs i j he] + +open scoped Classical in +private theorem rolePtr_eq {d w l : ℕ} (col : Bool) (tips : Fin 2 → Bool → Tip d w l) + (loop : Fin 8 → Bool) {r s : History.Role P} (h : r = s) + {q : r.Port} {t : s.Port} (he : HEq q t) : + rolePtr col tips loop r q = rolePtr col tips loop s t := by + subst s + rw [eq_of_heq he] + +open scoped Classical in +theorem Same.match_key (same : u.Same v n) (hn : 4 + ≤ n) {i : u.m.items} {j : v.m.items} {r t : Fin 6} + (hu : u.g.party u.m u.col i r = u.v) (hv : v.g.party v.m v.col j t = v.v) + (hk : u.q.atomKey u.g u.m u.col (.inr (.inl ⟨i, r⟩)) = + v.q.atomKey v.g v.m v.col (.inr (.inl ⟨j, t⟩))) + (q : (role u.g u.m P u.i i r).Port) (w : (role v.g v.m P v.i j t).Port) (he : HEq q w) : + u.q.portKey P u.g u.m u.i u.p.toPresentation u.v + (matchLinks u.g u.m P u.H.units u.i u.p.toPresentation u.v i r hu q) = + v.q.portKey P v.g v.m v.i v.p.toPresentation v.v + (matchLinks v.g v.m P v.H.units v.i v.p.toPresentation v.v j t hv w) := by + obtain ⟨hi, hj, ht, hl⟩ := same.gadget hn hu hv hk + have loop : u.roleLoop i = v.roleLoop j := by + funext a + have h := (same.agree.restrict hn).identical (hl (sixPair a).1) (hl (sixPair a).2) + erw [u.c.site.injective.eq_iff, v.c.site.injective.eq_iff] at h + exact decide_eq_decide.mpr h + rw [role_key, role_key, loop, ht, same.layout] + exact rolePtr_eq _ _ _ (Prod.ext hi hj) he + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Recovering the original local pattern by a reverse hop -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k n : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') + +open scoped Classical in +/-- The value specified by `((u.r (u.p.vertex w).1).2 (u.p.vertex w).2.1, (u.p.vertex w).2.2)`. -/ +def oldTag (w : u.G.diagram.V) := + ((u.r (u.p.vertex w).1).2 (u.p.vertex w).2.1, (u.p.vertex w).2.2) + +open scoped Classical in +private theorem tag_value (w : u.G.diagram.V) : + let t := u.H.units.place w + u.oldTag w = ((u.env.extra t.1).1 (cellIndex _ t.2), 0) := by + let r := u.G.units.place w + rw [oldTag, u.p.vertex_eq] + change ((u.r (u.p.host r.1)).2 (u.p.block r.2), 0) = + ((u.r (u.p.host r.1)).2 (u.p.block ((splitCell a u.ha).symm + (ancestor u.ha r.2, (cellIndex _).symm (cellIndex _ (suffix a r.2))))), 0) + rw [Equiv.symm_apply_apply, show (ancestor u.ha r.2, suffix a r.2) + = splitCell a u.ha r.2 from rfl, + Equiv.symm_apply_apply] + +variable {u} {v : State S P a h z Δ D k B'} + +open scoped Classical in +theorem related_occurrence {l : u.H.V × Cell (h - a)} {r : v.H.V × Cell (h - a)} + (hu : u.g.route u.m u.col l.1 l.2 = u.v) (hv : v.g.route v.m v.col r.1 r.2 = v.v) + (he : u.q.stamp u.g u.m u.col l = v.q.stamp v.g v.m v.col r) : + Window.Related u.env v.env 1 l.1 r.1 ∧ l.2 = r.2 := by + refine ⟨?_, (cellIndex _).injective (Prod.mk.inj he).2⟩ + have he₁ := u.q.recover_reverse u.g u.m u.col l.1 l.2 + have he₂ := v.q.recover_reverse v.g v.m v.col r.1 r.2 + let j := (u.q.stamp u.g u.m u.col l).1 + have h₁ : j.elim u.env.root (u.env.nav u.env.root) = l.1 := by + exact (congrArg (fun v => u.q.recover v.1 j) hu.symm).trans he₁ + have h₂ : j.elim v.env.root (v.env.nav v.env.root) = r.1 := by + change v.q.recover v.v.1 ((u.q.stamp u.g u.m u.col l).1) = _ + rw [he] + exact (congrArg (fun w => v.q.recover w.1 (v.q.stamp v.g v.m v.col r).1) hv.symm).trans he₂ + rw [←h₁, ←h₂] + cases j + · exact Window.related_root.widen (by decide) + · exact Window.related_root.next _ + +open scoped Classical in +theorem Same.oldTag (e : u.Same v n) (hn : 4 ≤ n) {i : u.G.diagram.V} {j : v.G.diagram.V} + (hu : u.H.anchor u.g u.m u.col (.inl i) = u.v) + (hv : v.H.anchor v.g v.m v.col (.inl j) = v.v) + (hk : u.q.atomKey u.g u.m u.col (.inl i) = v.q.atomKey v.g v.m v.col (.inl j)) : + u.oldTag i = v.oldTag j := by + obtain ⟨hr, hb⟩ := related_occurrence (l := u.H.units.place i) (r := v.H.units.place j) + hu hv (congrArg Prod.fst hk) + have h := (e.agree.records hr (by omega)).2.2 + rw [tag_value, tag_value, h, hb] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # The dictionary tag of an individual atom in a wire-saving contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') + +open scoped Classical in +/-- The value specified by `⟨Fintype.card (u.CheckRow o), (u.check_size o).trans_lt +(Nat.pow_lt_pow_right (by decide) (by omega))⟩`. -/ +def checkTag (o : u.Occurrence) : B (S.e + 2) := + ⟨Fintype.card (u.CheckRow o), (u.check_size o).trans_lt + (Nat.pow_lt_pow_right (by decide) (by omega))⟩ + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `.inl (u.oldTag v)`. -/ +def kind : u.H.Atom u.g u.m → History.Kind S P (S.e + 2) + | .inl v => .inl (u.oldTag v) + | .inr (.inl ⟨i, j⟩) => .inr (.inl (u.i i, j)) + | .inr (.inr v) => .inr (.inr (u.checkTag v)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- +# The bit length inherited by a contracted occurrence +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring History History.Subround Packing + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} + {a h z Δ D k : ℕ} {B' : ℝ} (u : State S P a h z Δ D k B') (o : B S.ℓ ≃ B S.ℓ) + +local notation "c" => (S.e + 2) +local notation "J" => Receipt P u.H u.g u.m u.i u.v + +open scoped Classical in +/-- The sum of `Kind.carried S P c o (u.kind i.val)` indexed by `i : J`. -/ +def inherited := ∑ i : J, Kind.carried S P c o (u.kind i.val) + +open scoped Classical in +theorem inherited_le (mass : u.H.V × Cell (h - a) → ℝ) (hm : ∀ p, 0 ≤ mass p) + (hc : ∀ v, 0 < u.G.diagram.arity v → + (Dense.used (o (u.oldTag v).1).val : ℝ) ≤ mass (u.H.units.place v)) : + (u.inherited o : ℝ) ≤ push (fun t => u.g.route u.m u.col t.1 t.2) mass u.v := by + apply u.H.carried_size u.g u.m u.col u.v u.q.one mass hm + rintro ⟨v | (j | q), hv⟩ + · exact hc v (u.H.receipts_live _ _ _ _ _ hv) + · simp [kind, HostNet.previous] + · simp [kind, HostNet.previous] + +local notation "U" => Hidden u.g u.m P u.i u.v + +open scoped Classical in +/-- The decoded value is unchanged. Only the effective lengths of +live old tags are added to the local bookkeeping cost. -/ +theorem stored {m e d s n l : ℕ} (p : Packed J U e (S.ℓ + Kind.width S P c) s n) + (ha : ∀ i, p.tag i = Kind.names S P c o (u.kind i.val)) (ix : J ↪ B m) (f : U ↪ B e) + (hl : Post.bookkeeping m e s n S.ℓ (Kind.width S P c) + u.inherited o ≤ l) + (v : (Post.record d e n (.addr l)).obj) (hv : v.2.2 = Dense.encode l (p.encode ix f)) : + Dense.unpack l v.2.2 = p.encode ix f ∧ + Dense.used (Post.order d e n l ((Post.record d e n (.addr l)).serial v)).val ≤ + (Post.headerFmt d e n).width + Post.bookkeeping m e s n S.ℓ (Kind.width S P c) + + u.inherited o := + Post.stored_length S P o p ix f _ (funext ha) le_rfl hl v hv + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Atom tags are invariant under local renaming of hosts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k n : ℕ} {B' : ℝ} + {u v : State S P a h z Δ D k B'} + +theorem Same.kind (e : u.Same v n) (hn : 4 ≤ n) + {i : u.H.Atom u.g u.m} {j : v.H.Atom v.g v.m} + (hu : u.H.anchor u.g u.m u.col i = u.v) (hv : v.H.anchor v.g v.m v.col j = v.v) + (hk : u.q.atomKey u.g u.m u.col i = v.q.atomKey v.g v.m v.col j) : + u.kind i = v.kind j := by + have hr := (Prod.mk.inj hk).2 + rcases i with i|⟨i, r⟩|i <;> rcases j with j|⟨j, t⟩|j <;> + simp only [Navigation.role, Sum.inl.injEq, Sum.inr.injEq, reduceCtorEq, Prod.mk.injEq] at hr + · exact congrArg Sum.inl (e.oldTag hn hu hv hk) + · obtain ⟨h₁, h₂, _⟩ := e.gadget hn hu hv hk + exact congrArg (fun p => Sum.inr (Sum.inl p)) (Prod.ext h₁ h₂) + · have he := e.checkCount hn hu hv (congrArg Prod.fst hk) + exact congrArg (fun p => Sum.inr (Sum.inr p)) (show u.checkTag i = v.checkTag j from Fin.ext he) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Recovering old station links from their tag and stamp -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing History.Subround Navigation.Emission + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} + +open scoped Classical in +/-- The old pointer of type `Bool × Navigation.SpanKey S.d S.e h b`, constructed using `S.decode +label.1`. -/ +def Navigation.Emission.oldPointer {h b : ℕ} (S : Scheme F) (label : B S.ℓ × B S.k) + (t : Stamp S.d h) (j : B S.e) : Bool × Navigation.SpanKey S.d S.e h b := + let A := S.decode label.1 + if A.peer label.2 j = none then (false, exterior t j) + else (true, demand (t, j) (A.direction label.2 j)) + +namespace State + +variable {a h z Δ D k n : ℕ} {B' : ℝ} (u : State S P a h z Δ D k B') + +open scoped Classical in +private theorem origin_key (w : u.G.diagram.V) (j : B S.e) + {t : PortMap.Port u.g u.m P u.H.units u.i u.p.toPresentation u.v} + (ht : u.p.Origin a u.ha u.g u.m u.i u.v w j t) : + u.q.portKey P u.g u.m u.i u.p.toPresentation u.v t = + oldPointer S (u.oldTag w) (u.q.stamp u.g u.m u.col (u.H.units.place w)) j := by + have peer : (S.decode (u.oldTag w).1).peer (u.oldTag w).2 j = none ↔ + S.peer u.r (u.p.vertex w, j) = none := by simp [oldTag, Scheme.peer, Scheme.pattern] + unfold oldPointer + cases ht with + | outside q hq he => + have h := q.property.2 + rw [hq] at h + rw [ite_eq_left (peer.mpr h)] + erw [u.q.portKey_exterior P u.g u.m u.i u.p.toPresentation u.v q he, hq] + | inside e t he hs => + have h : S.peer u.r (u.p.vertex w, j) ≠ none := by + rw [← he] + unfold Scheme.Posting.span Scheme.peer + rw [u.p.link] + simp + have d : (S.decode (u.oldTag w).1).direction (u.oldTag w).2 j = t := by + change S.direction u.r (u.p.vertex w, j) = t + rw [← he] + exact u.p.dir e t + have entry : u.q.stub e t = j := congrArg Prod.snd he + rw [ite_eq_right (mt peer.mp h), d] + erw [u.q.portKey_demand P u.g u.m u.i u.p.toPresentation u.v e t hs] + change (true, demand (u.q.stamp u.g u.m u.col (Scheme.side u.H e t, u.H.ix e), u.q.stub e t) t) + = _ + erw [entry, u.p.station_place a u.ha w he] + +open scoped Classical in +theorem oldMap_key (w : u.G.diagram.V) + (hw : u.H.anchor u.g u.m u.col (.inl w) = u.v) (j : B S.e) + (hj : 0 < S.width u.r (u.p.vertex w, j)) : + u.q.portKey P u.g u.m u.i u.p.toPresentation u.v + ((u.p.oldMap a u.ha u.g u.m u.i u.v w hw u.hz).slot j hj) = + oldPointer S (u.oldTag w) (u.q.stamp u.g u.m u.col (u.H.units.place w)) j := + u.origin_key w j (u.p.station_origin a u.ha u.g u.m u.i u.v w hw j hj) + +variable {u} {v : State S P a h z Δ D k B'} + +open scoped Classical in +theorem Same.oldMap_key (e : u.Same v n) (hn : 4 ≤ n) {i : u.G.diagram.V} {j : v.G.diagram.V} + (hu : u.H.anchor u.g u.m u.col (.inl i) = u.v) + (hv : v.H.anchor v.g v.m v.col (.inl j) = v.v) + (hk : u.q.atomKey u.g u.m u.col (.inl i) = v.q.atomKey v.g v.m v.col (.inl j)) + (s : B S.e) (hi : 0 < S.width u.r (u.p.vertex i, s)) (hj : 0 < S.width v.r (v.p.vertex j, s)) : + u.q.portKey P u.g u.m u.i u.p.toPresentation u.v + ((u.p.oldMap a u.ha u.g u.m u.i u.v i hu u.hz).slot s hi) = + v.q.portKey P v.g v.m v.i v.p.toPresentation v.v + ((v.p.oldMap a v.ha v.g v.m v.i v.v j hv v.hz).slot s hj) := by + have hs : u.q.stamp u.g u.m u.col (u.H.units.place i) = + v.q.stamp v.g v.m v.col (v.H.units.place j) := congrArg Prod.fst hk + rw [u.oldMap_key, v.oldMap_key, e.oldTag hn hu hv hk, hs] + +end State +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Identifying the predecessor of an exterior span -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing Window + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') + +/-- Computes the border key by the application `Navigation.faceKey P u.H u.g u.m u.i +u.p.toPresentation u.q (.inl i)`. -/ +abbrev borderKey (i : u.p.toPresentation.BorderSpan) := + Navigation.faceKey P u.H u.g u.m u.i u.p.toPresentation u.q (.inl i) + +/-- The value specified by `(u.q.stamp u.g u.m u.col (u.H.units.place i.val.1), i.val.2)`. -/ +abbrev relativePointer (i : u.p.toPresentation.BorderSpan) := + (u.q.stamp u.g u.m u.col (u.H.units.place i.val.1), i.val.2) + +/-- The value specified by `((u.relativePointer i).1.1, (u.p.vertex i.val.1).2.1, i.val.2)`. -/ +abbrev predecessor (i : u.p.toPresentation.BorderSpan) := + ((u.relativePointer i).1.1, (u.p.vertex i.val.1).2.1, i.val.2) + +private theorem group_node (p : List (B S.d)) : (u.env.node p).2 = u.v.1.2 := by + induction p with + | nil => rfl + | cons _ _ ih => exact ih + +variable {u} {v : State S P a h z Δ D k B'} {n : ℕ} + {i : u.p.toPresentation.BorderSpan} {j : v.p.toPresentation.BorderSpan} + +theorem relativePointer_eq (he : u.borderKey i = v.borderKey j) : + u.relativePointer i = v.relativePointer j := by + obtain ⟨hk, hs⟩ := Prod.mk.inj (Sum.inl.inj he) + exact Prod.ext (congrArg (fun x => x.1.1) hk) hs + +theorem Same.exterior (e : u.Same v n) (hn : 4 ≤ n) + (hu : u.H.anchor u.g u.m u.col (.inl i.val.1) = u.v) + (hv : v.H.anchor v.g v.m v.col (.inl j.val.1) = v.v) (he : u.borderKey i = v.borderKey j) : + u.p.toPresentation.borderWidth i = v.p.toPresentation.borderWidth j ∧ + S.direction u.r (u.p.vertex i.val.1, i.val.2) = S.direction v.r (v.p.vertex j.val.1, j.val.2) + := by + obtain ⟨hk, hs⟩ := Prod.mk.inj (Sum.inl.inj he) + have ht := e.oldTag hn hu hv (congrArg Prod.fst hk) + exact ⟨congrArg₂ (fun (t : B S.ℓ × B S.k) s => (S.decode t.1).width t.2 s) ht hs, + congrArg₂ (fun (t : B S.ℓ × B S.k) s => (S.decode t.1).direction t.2 s) ht hs⟩ + +variable (hu : u.H.anchor u.g u.m u.col (.inl i.val.1) = u.v) + (hv : v.H.anchor v.g v.m v.col (.inl j.val.1) = v.v) (he : u.borderKey i = v.borderKey j) +include hu hv he + +/-- Equal relative pointers translate to equal absolute pointers when +the group and the block numbering agree. -/ +theorem predecessor_eq (hg : u.v.1.2 = v.v.1.2) (hb : u.p.block = v.p.block) : + u.predecessor i = v.predecessor j := by + obtain ⟨hk, hs⟩ := Prod.mk.inj (relativePointer_eq he) + obtain ⟨⟨p, _, hp, hp'⟩, ht⟩ := related_occurrence hu hv hk + have ha : (u.H.units.place i.val.1).1.2 = (v.H.units.place j.val.1).1.2 := + (congrArg Prod.snd hp).symm.trans ((u.group_node p).trans + (hg.trans ((v.group_node p).symm.trans (congrArg Prod.snd hp')))) + have hc : (u.G.units.place i.val.1).2 = (v.G.units.place j.val.1).2 := + (splitCell a u.ha).injective (Prod.ext ha ht) + have hh := congrArg Prod.fst hk + refine Prod.ext hh (Prod.ext ?_ hs) + change (u.p.vertex i.val.1).2.1 = (v.p.vertex j.val.1).2.1 + rw [u.p.vertex_eq, v.p.vertex_eq, hb, hc] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Length.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Length.lean new file mode 100644 index 0000000000..05896cc688 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Length.lean @@ -0,0 +1,1064 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.State +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Prefix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Radius +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Checks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep + +/-! +# The opposite end of an emitted wire + +A visible supply was issued within two hops, and both endpoints are +within two hops of that issuer. Four more hops recover the compact +dictionary at the opposite end. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring Packing + +namespace Window + +open scoped Classical in +private theorem node_append {V X : Type} {d h e ℓ : ℕ} (α : Env V X d h e ℓ) (p q : List (B d)) : + α.node (q ++ p) = ({ α with root := α.node p } : Env V X d h e ℓ).node q := by + simp only [Env.node, visit, List.foldr_append] + +open scoped Classical in +theorem Agree.reroot {V W X : Type} {d h e ℓ n m : ℕ} {α : Env V X d h e ℓ} {β : Env W X d h e ℓ} + {v : V} {w : W} (h : Agree α β (m + n)) (hr : Related α β n v w) : + Agree { α with root := v } { β with root := w } m := by + obtain ⟨p, hp, rfl, rfl⟩ := hr + have bound (q : List (B d)) (hq : q.length ≤ m) : (q ++ p).length ≤ m + n := by + rw [List.length_append]; exact Nat.add_le_add hq hp + constructor + · intro q r hq hr + simpa only [node_append] using h.same _ _ (bound q hq) (bound r hr) + · intro q hq + simpa only [node_append] using h.data _ (bound q hq) + · intro q hq + simpa only [node_append] using h.recv _ (bound q hq) + · intro q hq + simpa only [node_append] using h.extra _ (bound q hq) + +end Window + +namespace State +open Window Navigation.Emission + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') + +open scoped Classical in +/-- Computes the end at by the application `cond s (u.g.contact u.m u.col t).2 (u.g.contact u.m +u.col t).1`. -/ +abbrev endAt (t : u.g.Supply u.m P u.i) (s : Bool) := + cond s (u.g.contact u.m u.col t).2 (u.g.contact u.m u.col t).1 + +open scoped Classical in +/-- Computes the name at by the application `u.q.supplyKey u.g u.m u.col P u.i t s`. -/ +abbrev nameAt (t : u.g.Supply u.m P u.i) (s : Bool) := u.q.supplyKey u.g u.m u.col P u.i t s + +open scoped Classical in +private theorem in_window (t : u.g.Supply u.m P u.i) (s : Bool) (he : u.endAt t s = u.v) : + (u.c.event P u.i t).1.1 ∈ u.env.issuers := by + have hw := u.q.window_supply u.g u.m u.col P u.i t s + change _ ∈ u.q.neighborhood (u.endAt t s).1 at hw + rw [he] at hw + rcases t with ⟨t, j, i⟩ | ⟨t, i⟩ <;> exact hw + +variable {u} {v : State S P a h z Δ D k B'} {n : ℕ} + +open scoped Classical in +private theorem Same.matched (e : u.Same v n) (hn : 4 ≤ n) + (s : u.g.Supply u.m P u.i) (b : Bool) (hs : u.endAt s b = u.v) : + ∃ t : v.g.Supply v.m P v.i, v.endAt t b = v.v ∧ ∀ c, + u.nameAt s c = v.nameAt t c ∧ Names u.env v.env (u.c.site (u.endAt s c)) (v.c.site (v.endAt t + c)) := by + let A := e.agree.restrict hn + let j := u.c.event P u.i s + obtain ⟨w, _, hw⟩ := Related.issuers (β := v.env) (u.in_window s b hs) + let j' := ((w, j.1.2), j.2) + have enable := A.enabled hw (fun x i => profileOf P (x.2 i)) j.1.2 j.2 + have ok := (u.c.enabled_iff P u.i (profileOf P ∘ u.selector) u.code j).mpr ⟨s, rfl⟩ + obtain ⟨t, ht⟩ := (v.c.enabled_iff P v.i (profileOf P ∘ v.selector) v.code j').mp + (enable.symm.trans ok) + have keys (c) : u.nameAt s c = v.nameAt t c := by + have H := A.supplies hw (by decide) u.col j.1.2 j.2 + change u.env.supplies u.col j = v.env.supplies u.col j' at H + refine (u.p.supply_key u.hu a u.ha u.g u.m u.ctl u.i s c).trans ?_ + refine Eq.trans ?_ (v.p.supply_key v.hu a v.ha v.g v.m v.ctl v.i t c).symm + change supply u.col (u.env.supplies u.col j) j.2 c = + supply v.col (v.env.supplies v.col (v.c.event P v.i t)) (v.c.event P v.i t).2 c + rw [ht, H, e.layout] + have sites (c) : Names u.env v.env (u.c.site (u.endAt s c)) (v.c.site (v.endAt t c)) := by + have hu := u.p.newAt_eq u.hu a u.ha u.g u.m u.ctl u.i s c + have hv := v.p.newAt_eq v.hu a v.ha v.g v.m v.ctl v.i t c + change newAt u.env.nav u.env.data u.col j c = u.c.site (u.endAt s c) at hu + change newAt v.env.nav v.env.data v.col (v.c.event P v.i t) c = v.c.site (v.endAt t c) at hv + rw [← hu, ← hv, ht, ← e.layout] + exact A.newAt hw u.col j.1.2 j.2 c + have root : Names u.env v.env (u.c.site u.v) (v.c.site v.v) := + ⟨related_root.widen (by decide), e.key⟩ + exact ⟨t, v.c.site.injective ((A.identical (sites b) root).mp (congrArg u.c.site hs)), + fun c => ⟨keys c, sites c⟩⟩ + +open scoped Classical in +/-- Keep the diagram and its choices fixed, changing only the queried site. -/ +abbrev recenter (u : State S P a h z Δ D k B') (x : Site (u.G.V × Cell a) (h - a)) := + { u with v := x } + +open scoped Classical in +theorem Same.supply_remote (e : u.Same v n) (hn : 8 ≤ n) + {s : u.g.Supply u.m P u.i} {t : v.g.Supply v.m P v.i} {b : Bool} + (hs : u.endAt s b = u.v) (ht : v.endAt t b = v.v) (he : u.nameAt s b = v.nameAt t b) : + u.nameAt s (!b) = v.nameAt t (!b) ∧ + Related u.env v.env 4 (u.endAt s (!b)).1 (v.endAt t (!b)).1 ∧ + (u.recenter (u.endAt s (!b))).Same (v.recenter (v.endAt t (!b))) 4 := by + obtain ⟨q, hq, h⟩ := e.matched (by omega) s b hs + have ha : v.H.anchor v.g v.m v.col (Navigation.supplyAtom (G := v.H) v.g v.m P v.i q b) = + v.H.anchor v.g v.m v.col (Navigation.supplyAtom (G := v.H) v.g v.m P v.i t b) := by + have eq := Navigation.supply_anchor (G := v.H) v.g v.m v.col P v.i + exact (eq q b).trans ((hq.trans ht.symm).trans (eq t b).symm) + have hqt := v.q.supply_unique v.g v.m v.col P v.i ha ((h b).1.symm.trans he) + have : q = t := congrArg Prod.fst hqt + subst q + obtain ⟨hk, hr, hi⟩ := h (!b) + exact ⟨hk, hr, (e.agree.restrict hn).reroot (m := 4) hr, e.layout, hi⟩ + +end State +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Local determination of emitted headers and peer seats -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State + +open Coloring Packing History History.Subround + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') + +open scoped Classical in +/-- Computes the faces by the application `Face u.g u.m P u.i u.p.toPresentation`. -/ +abbrev Faces := Face u.g u.m P u.i u.p.toPresentation +open scoped Classical in +/-- Computes the face name by the application `Navigation.faceKey P u.H u.g u.m u.i +u.p.toPresentation u.q`. -/ +abbrev faceName := Navigation.faceKey P u.H u.g u.m u.i u.p.toPresentation u.q +open scoped Classical in +/-- Computes the face width by the application `visibleWidth u.g u.m P u.i u.p.toPresentation +z`. -/ +abbrev faceWidth := visibleWidth u.g u.m P u.i u.p.toPresentation z +open scoped Classical in +/-- Computes the local faces by the application `Visible u.g u.m P u.H.units u.i +u.p.toPresentation u.v`. -/ +abbrev localFaces := Visible u.g u.m P u.H.units u.i u.p.toPresentation u.v + +variable {m' d' a' e' ℓ n' l s : ℕ} {Y : Format} {M : Menu F l s ℓ} + {unpack : Y.obj → (History.code n' e' l s ℓ).obj} + +open scoped Classical in +/-- The value specified by `Allocation P u.H u.g u.m u.i u.p.toPresentation (u.G.project a u.ha +Δ D hle) Z`. -/ +abbrev Assignment (hle : Δ ≤ D) (Z : Scheme F) := + Allocation P u.H u.g u.m u.i u.p.toPresentation (u.G.project a u.ha Δ D hle) Z + +variable {hle : Δ ≤ D} + +open scoped Classical in +/-- A compact seat is the rank of the face key in the local list. -/ +def Ranked {Z : Scheme F} (A : u.Assignment hle Z) : Prop := + ∀ w t, (A.seat w t).val = Navigation.index (u.recenter w).lists.2.2 (u.faceName t.val) + +variable {u} {v : State S P a h z Δ D k B'} {n : ℕ} + (e : u.Same v n) (hn : 8 ≤ n) (α : u.Assignment hle (Post.scheme m' d' a' e' Y M unpack)) + (β : v.Assignment hle (Post.scheme m' d' a' e' Y M unpack)) + (sizeA : u.Faces → B ℓ) (sizeB : v.Faces → B ℓ) + (hsize : ∀ i j, u.faceWidth i = v.faceWidth j → sizeA i = sizeB j) + (hindex : ∀ (x : Site (u.G.V × Cell a) (h - a)) (y : Site (v.G.V × Cell a) (h - a)), + Window.Related u.env v.env 4 x.1 y.1 → intervalCode _ x.2 = intervalCode _ y.2 → + α.index (u.v.1.1, u.v.2) (x.1.1, x.2) = β.index (v.v.1.1, v.v.2) (y.1.1, y.2)) + (ha : u.Ranked α) (hb : v.Ranked β) + +include ha hb in +open scoped Classical in +private theorem seats {x : Site (u.G.V × Cell a) (h - a)} {y : Site (v.G.V × Cell a) (h - a)} + (hlist : (u.recenter x).lists = (v.recenter y).lists) + (i : (u.recenter x).localFaces) (j : (v.recenter y).localFaces) + (hij : u.faceName i.val = v.faceName j.val) : α.seat x i = β.seat y j := by + apply Fin.ext + have hl := congrArg (fun t : Window.Lists S.d S.e (h - a) P.b => t.2.2) hlist + have hi := ha x i + have hj := hb y j + exact hi.trans ((congrArg₂ Navigation.index hl hij).trans hj.symm) + +open scoped Classical in +private theorem face_mem (u : State S P a h z Δ D k B') (t : Navigation.SpanKey S.d S.e (h - a) + P.b) : + t ∈ u.lists.2.2 ↔ ∃ i : u.localFaces, u.faceName i.val = t := by + change t ∈ Finset.univ.map (Navigation.visibleNames P u.H u.g u.m u.i u.p.toPresentation u.v u.q) + ↔ _ + simp only [Finset.mem_map, Finset.mem_univ, true_and] + rfl + +include e hn ha hb in +open scoped Classical in +theorem match_seat (i : u.localFaces) : + ∃ j : v.localFaces, u.faceName i.val = v.faceName j.val ∧ α.seat u.v i = β.seat v.v j := by + have hl := e.lists (by omega) + have hm := (face_mem u _).mpr ⟨i, rfl⟩ + rw [hl] at hm + obtain ⟨j, hj⟩ := (face_mem v _).mp hm + exact ⟨j, hj.symm, seats α β ha hb (x := u.v) (y := v.v) hl i j hj.symm⟩ + +include e hn hsize hindex ha hb + +open scoped Classical in +theorem Same.header {i : u.localFaces} {j : v.localFaces} + (he : u.faceName i.val = v.faceName j.val) : α.header sizeA i.val = β.header sizeB j.val := by + rcases i with ⟨i | ⟨i, b⟩, hi⟩ <;> rcases j with ⟨j | ⟨j, c⟩, hj⟩ + · obtain ⟨hw, hd⟩ := e.exterior (by omega) hi hj he + exact Prod.ext (hsize (.inl i) (.inl j) hw) (Prod.ext hd rfl) + · cases he + · cases he + · have key : u.nameAt i.val b = v.nameAt j.val c := Sum.inr.inj he + have dir := congrArg Prod.fst key + change b = c at dir + subst c + obtain ⟨hk, hr, h⟩ := e.supply_remote hn hi hj key + have hs := h.lists le_rfl + let x := u.endAt i.val (!b) + let y := v.endAt j.val (!b) + have seat : α.unitSeat i (!b) = β.unitSeat j (!b) := by + have he : u.faceName (.inr (i, !b)) = v.faceName (.inr (j, !b)) := congrArg Sum.inr hk + exact seats α β ha hb (x := x) (y := y) hs ⟨.inr (i, !b), rfl⟩ ⟨.inr (j, !b), rfl⟩ he + have idx := hindex x y hr h.key + change u.endAt i.val b = u.v at hi + change v.endAt j.val b = v.v at hj + have heq : α.index ((u.endAt i.val b).1.1, (u.endAt i.val b).2) (x.1.1, x.2) = + β.index ((v.endAt j.val b).1.1, (v.endAt j.val b).2) (y.1.1, y.2) := by + rw [hi, hj] + exact idx + exact Prod.ext (hsize (.inr (i, b)) (.inr (j, + b)) rfl) (Prod.ext rfl (Prod.ext rfl (Prod.ext heq seat))) + +open scoped Classical in +/-- Equal keys occupy equal seats, with the same unused-seat default. -/ +theorem Same.fields : α.fields sizeA u.v = β.fields sizeB v.v := by + funext r + unfold Allocation.fields + by_cases hr : r ∈ Set.range (α.seat u.v) + · obtain ⟨i, rfl⟩ := hr + obtain ⟨j, hj, he⟩ := match_seat e hn α β ha hb i + rw [(α.seat u.v).injective.extend_apply, he] + refine (e.header hn α β sizeA sizeB hsize hindex ha hb hj).trans ?_ + exact ((β.seat v.v).injective.extend_apply (fun t => β.header sizeB t.val) (fun _ + => Post.unused) j).symm + · have hr' : r ∉ Set.range (β.seat v.v) := by + rintro ⟨j, hj⟩ + obtain ⟨i, _, he⟩ := match_seat e.symm hn β α hb ha j + exact hr ⟨i, he.symm.trans hj⟩ + rw [Function.extend_apply' _ _ _ hr, Function.extend_apply' _ _ _ hr'] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # The actual atomic factors in a wire-saving step -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing History.Subround + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') + +open scoped Classical in +/-- In the case `.inl w, hw`, this construction gives `u.p.oldMap a u.ha u.g u.m u.i u.v w hw +u.hz`. -/ +def atomMap (j : u.H.Atom u.g u.m) (hj : u.H.anchor u.g u.m u.col j = u.v) : + AtomMap u.g u.m P u.H.units u.hz u.i u.p.toPresentation u.v (History.kind S P z u.hz (u.kind + j)) j := + match j, hj with + | .inl w, hw => u.p.oldMap a u.ha u.g u.m u.i u.v w hw u.hz + | .inr (.inl ⟨t, i⟩), ht => matchMap u.g u.m P u.H.units u.i u.p.toPresentation u.v t i ht u.hz + | .inr (.inr w), hw => checkMap u.g u.m P u.H.units u.i u.p.toPresentation u.v w hw (u.checkOrder + w) u.hz + +open scoped Classical in +/-- Builds `Bundle P u.H u.g u.m u.i u.p.toPresentation u.hz u.v (S.e + 2) where label t` with +the specified `label`, `arg`. -/ +def bundle : Bundle P u.H u.g u.m u.i u.p.toPresentation u.hz u.v (S.e + 2) where + label t := u.kind t.val + arg t := u.atomMap t.val ((anchor_eq _).trans (includeAtom u.hz t).property) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # The packed code of a contracted occurrence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing History.Subround + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} + {a h z Δ D k e l s d : ℕ} {B' : ℝ} (u : State S P a h z Δ D k B') + +open scoped Classical in +/-- The data for the room construction, including `budget`, `contacts`, `floor`. -/ +structure Room (e : ℕ) : Prop where + budget : Navigation.Budget P u.H Δ k B' e + contacts : ∀ t, P.b * z ≤ u.H.tetherLoad (u.H.far t) + floor : ∀ t, z ≤ u.p.toPresentation.borderWidth t + +open scoped Classical in +/-- Returns `new` when `(u.q.hiddenKey u.g u.m P u.i q.val).isRight` holds, and `old` otherwise. -/ +def hiddenSize (old new : B d) (q : Hidden u.g u.m P u.i u.v) : B d := + if (u.q.hiddenKey u.g u.m P u.i q.val).isRight then new else old + +open scoped Classical in +theorem hiddenSize_spec (old new : B d) (len : B d → ℕ) + (ho : len old = P.b * z) (hn : len new = z) (q : Hidden u.g u.m P u.i u.v) : + len (u.hiddenSize old new q) = segmentWidth u.g u.m P u.i z q.val := by + rcases q with ⟨q|q|q, _⟩ + · exact ho + · exact ho + · exact hn + +namespace Room +variable {u} (R : u.Room e) + +include R in +open scoped Classical in +theorem recenter (x : Site (u.G.V × Cell a) (h - a)) : (u.recenter x).Room e := + ⟨R.budget, R.contacts, R.floor⟩ + +open scoped Classical in +/-- Uses `u.q.atoms u.g u.m u.i R.budget R.contacts u.v` as the representation. -/ +abbrev atoms := u.q.atoms u.g u.m u.i R.budget R.contacts u.v +open scoped Classical in +/-- Uses `u.q.hidden u.g u.m u.i R.budget u.v` as the representation. -/ +abbrev hidden := u.q.hidden u.g u.m u.i R.budget u.v +open scoped Classical in +/-- Uses `u.q.visible u.g u.m u.i u.p.toPresentation R.budget R.floor u.v` as the +representation. -/ +abbrev visible := u.q.visible u.g u.m u.i u.p.toPresentation R.budget R.floor u.v +end Room + +open scoped Classical in +/-- The value specified by `(u.bundle.packed names index R.visible (u.hiddenSize old +new)).encode R.atoms R.hidden`. -/ +def packedCode (R : u.Room e) (names : History.Kind S P (S.e + 2) ↪ B l) + (index : ∀ j : History.Kind S P (S.e + 2), (History.kind S P z u.hz j).Span ↪ B s) + (old new : B d) : (History.code e e l s d).obj := + (u.bundle.packed names index R.visible (u.hiddenSize old new)).encode R.atoms R.hidden + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- +# The common dictionary and record of a contracted occurrence + +Indices and length codes are chosen once, independently of the +number of hosts, the occurrence, and the local packet choices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing History History.Subround + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {z : ℕ} {hz : 0 < z} + +namespace History + +open scoped Classical in +/-- The data for the book construction, including `ord`, `s`, `index`, `d`, `len`. -/ +structure Book (S : Scheme F) (P : Gadget F) (z : ℕ) (hz : 0 < z) where + /-- Reindexes the data using `B S.ℓ ≃ B S.ℓ`. -/ + ord : B S.ℓ ≃ B S.ℓ + /-- The `Book` field of type `ℕ`. -/ + s : ℕ + /-- The identification of the indices of type `∀ j : Kind S P (S.e + 2), (kind S P z hz + j).Span ↪ B s`. -/ + index : ∀ j : Kind S P (S.e + 2), (kind S P z hz j).Span ↪ B s + /-- The `Book` field of type `ℕ`. -/ + d : ℕ + /-- The `Book` component of type `B d → ℕ`. -/ + len : B d → ℕ + /-- The `Book` component of type `ℕ → B d`. -/ + put : ℕ → B d + zero : len 0 = 0 + old : len (put (P.b * z)) = P.b * z + unit : len (put z) = z + +namespace Book +variable (b : Book S P z hz) + +open scoped Classical in +/-- The quantity computed by `Kind.names S P (S.e + 2) b.ord`. -/ +abbrev names := Kind.names S P (S.e + 2) b.ord +open scoped Classical in +/-- The value specified by `History.menu (kind S P z hz) b.names b.index b.len`. -/ +abbrev menu := History.menu (kind S P z hz) b.names b.index b.len +open scoped Classical in +/-- The value specified by `Post.scheme m d h e (.addr cap) b.menu (Dense.unpack (m := e) cap)`. -/ +abbrev scheme (m d h e cap : ℕ) := Post.scheme m d h e (.addr cap) b.menu (Dense.unpack (m + := e) cap) +open scoped Classical in +/-- The quantity computed by `Post.bookkeeping e e b.s b.d S.ℓ (Kind.width S P (S.e + 2))`. -/ +abbrev overhead (e : ℕ) := Post.bookkeeping e e b.s b.d S.ℓ (Kind.width S P (S.e + 2)) + +end Book +end History + +namespace State +variable {a h Δ D k e m' d' h' : ℕ} {B' : ℝ} {hle : Δ ≤ D} + (u : State S P a h z Δ D k B') (b : Book S P z hz) (r : u.Room e) + +open scoped Classical in +/-- The quantity computed by `u.packedCode r b.names b.index (b.put (P.b * z)) (b.put z)`. -/ +abbrev codeAt := u.packedCode r b.names b.index (b.put (P.b * z)) (b.put z) + +open scoped Classical in +/-- Computes the data by the application `Dense.encode cap (u.codeAt b r)`. -/ +def data (cap : ℕ) : B cap := Dense.encode cap (u.codeAt b r) + +open scoped Classical in +theorem unpack_data (cap : ℕ) (h : b.overhead e + u.inherited b.ord ≤ cap) : + Dense.unpack cap (u.data b r cap) = u.codeAt b r := by + apply Dense.unpack_encode + exact (Post.packed_length S P b.ord _ _ _ _ rfl).trans h + +open scoped Classical in +/-- Computes the sizes by the application `b.put (visibleWidth u.g u.m P u.i u.p.toPresentation +z j)`. -/ +abbrev sizes (j : Face u.g u.m P u.i u.p.toPresentation) := + b.put (visibleWidth u.g u.m P u.i u.p.toPresentation z j) + +open scoped Classical in +/-- The value specified by `(u.recenter v).data b (r.recenter v) cap`. -/ +def payload (cap : ℕ) (v : Site u.H.V (h - a)) : B cap := + (u.recenter v).data b (r.recenter v) cap + +variable (cap : ℕ) + (A : Allocation P u.H u.g u.m u.i u.p.toPresentation (u.G.project a u.ha Δ D hle) + (b.scheme m' d' h' e cap)) + +open scoped Classical in +/-- The value specified by `(true, A.fields (u.sizes b) u.v, u.data b r cap)`. -/ +def localRecord : (Post.record d' e b.d (.addr cap)).obj := + (true, A.fields (u.sizes b) u.v, u.data b r cap) + +open scoped Classical in +/-- The value specified by `A.records (u.sizes b) (u.payload b r cap)`. -/ +abbrev records := A.records (u.sizes b) (u.payload b r cap) + +open scoped Classical in +theorem record_at (v : Site u.H.V (h - a)) : + u.records b r cap A (A.vertex v).1 (A.vertex v).2.1 = + (u.recenter v).localRecord b (r.recenter v) cap A := A.record_at _ _ _ + +end State +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Common dictionaries of factor spans and lengths + +Exterior widths use a fixed palette. The two interior lengths and the +idle length cost at most three further entries. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Book +open Coloring Packing + +variable {F : Type} [Field F] (S : Scheme F) (P : Gadget F) (z : ℕ) (hz : 0 < z) + +open scoped Classical in +/-- The quantity computed by `S.e + 2 + Nat.clog 2 (P.b + 1)`. -/ +abbrev spanBits := S.e + 2 + Nat.clog 2 (P.b + 1) + +open scoped Classical in +private theorem role_card (t : Role P) : Fintype.card t.Port ≤ 4 * (P.b + 1) := by + have hd : Fintype.card t.Demand ≤ 4 := + (Fintype.card_subtype_le _).trans_eq (by simp) + have hs : Fintype.card t.Supply ≤ ∑ j, t.1.2.val j := + (Fintype.card_subtype_le _).trans_eq (by simp) + have hb := P.cost t.1.2.val t.1.2.property + change Fintype.card (t.Demand ⊕ t.Supply) ≤ _ + rw [Fintype.card_sum] + omega + +open scoped Classical in +theorem exists_index (j : Kind S P (S.e + 2)) : + Nonempty ((kind S P z hz j).Span ↪ B (spanBits S P)) := by + have h : 2 ^ (S.e + 2) * (P.b + 1) ≤ 2 ^ spanBits S P := by + rw [spanBits, pow_add 2 (S.e + 2)] + exact Nat.mul_le_mul_left _ (Nat.le_pow_clog (by decide) _) + have hf : 4 ≤ 2 ^ (S.e + 2) := by + rw [pow_add] + have hpos : 0 < 2 ^ S.e := by positivity + omega + rcases j with t|t|q + · exact ⟨Fin.castLEEmb (Nat.pow_le_pow_right (by decide) (by unfold spanBits; omega))⟩ + · change Nonempty (t.Port ↪ B (spanBits S P)) + apply Function.Embedding.nonempty_of_card_le + rw [Fintype.card_fin] + exact (role_card P t).trans ((Nat.mul_le_mul_right _ hf).trans h) + · change Nonempty (Fin q.val × Option (Fin P.b) ↪ B (spanBits S P)) + apply Function.Embedding.nonempty_of_card_le + simp only [Fintype.card_prod, Fintype.card_option, Fintype.card_fin] + exact (Nat.mul_le_mul_right _ q.isLt.le).trans h + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev lenBits (W : Finset ℕ) := History.lengthBits W + +open scoped Classical in +theorem exists_lengths (W : Finset ℕ) : + ∃ f : (ℕ → B (lenBits W)) × (B (lenBits W) → ℕ), f.2 0 = 0 ∧ + f.2 (f.1 (P.b * z)) = P.b * z ∧ f.2 (f.1 z) = z ∧ ∀ j ∈ W, f.2 (f.1 j) = j := by + let U := insert 0 (insert z (insert (P.b * z) W)) + have hc : U.card ≤ W.card + 3 := + (Finset.card_insert_le _ _).trans (Nat.succ_le_succ + ((Finset.card_insert_le _ _).trans (Nat.succ_le_succ (Finset.card_insert_le _ _)))) + obtain ⟨table, zero, decode⟩ := History.length_dictionary U (by simp [U]) + (hc.trans (Nat.le_pow_clog (by decide) _)) + exact ⟨table, zero, decode _ (by simp [U]), decode _ (by simp [U]), + fun j hj => decode j (by simp [U, hj])⟩ + +variable (ord : B S.ℓ ≃ B S.ℓ) (W : Finset ℕ) + +open scoped Classical in +/-- Builds `Book S P z hz where ord` with the specified `ord`, `index`, `len`, `put`. -/ +def make : Book S P z hz where + ord := ord + s := spanBits S P + index j := Classical.choice (exists_index S P z hz j) + d := lenBits W + len := (exists_lengths P z W).choose.2 + put := (exists_lengths P z W).choose.1 + zero := (exists_lengths P z W).choose_spec.1 + old := (exists_lengths P z W).choose_spec.2.1 + unit := (exists_lengths P z W).choose_spec.2.2.1 + +open scoped Classical in +theorem represent {j : ℕ} (hj : j ∈ W) : + let b := make S P z hz ord W + b.len (b.put j) = j := + (exists_lengths P z W).choose_spec.2.2.2 _ hj + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Book +end + +/- # Locality of every nonempty atom argument in the packed history -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing + +open scoped Classical in +private theorem pair_eq {m n : ℕ} {A : Type} (h : m = n) + (i : Fin m × A) (j : Fin n × A) (e : HEq i j) : i.1.val = j.1.val ∧ i.2 = j.2 := by + subst n + rw [eq_of_heq e] + exact ⟨rfl, rfl⟩ + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k n : ℕ} {B' : ℝ} + {u v : State S P a h z Δ D k B'} + +open scoped Classical in +theorem Same.atom_slot (e : u.Same v n) (hn : 4 ≤ n) + {i : u.H.Atom u.g u.m} {j : v.H.Atom v.g v.m} + (hu : u.H.anchor u.g u.m u.col i = u.v) (hv : v.H.anchor v.g v.m v.col j = v.v) + (hk : u.q.atomKey u.g u.m u.col i = v.q.atomKey v.g v.m v.col j) + (x : (History.kind S P z u.hz (u.kind i)).Span) + (y : (History.kind S P z v.hz (v.kind j)).Span) + (he : HEq x y) (hx : 0 < (History.kind S P z u.hz (u.kind i)).width x) + (hy : 0 < (History.kind S P z v.hz (v.kind j)).width y) : + u.q.portKey P u.g u.m u.i u.p.toPresentation u.v ((u.atomMap i hu).slot x hx) = + v.q.portKey P v.g v.m v.i v.p.toPresentation v.v ((v.atomMap j hv).slot y hy) := by + have hr := (Prod.mk.inj hk).2 + rcases i with i|⟨i, r⟩|i <;> rcases j with j|⟨j, t⟩|j <;> + simp only [Navigation.role, Sum.inl.injEq, Sum.inr.injEq, reduceCtorEq, Prod.mk.injEq] at hr + · change B S.e at x y + have eq : x = y := eq_of_heq he + subst y + exact e.oldMap_key hn hu hv hk x hx hy + · exact e.match_key hn hu hv hk x y he + · have hs := congrArg Prod.fst hk + have hc := e.checkCount hn hu hv hs + change Fin (Fintype.card (u.CheckRow i)) × Option (Fin P.b) at x + change Fin (Fintype.card (v.CheckRow j)) × Option (Fin P.b) at y + obtain ⟨b, l⟩ := x + obtain ⟨c, r⟩ := y + obtain ⟨h₁, h₂⟩ := pair_eq hc (b, l) (c, r) he + change l = r at h₂ + subst r + exact e.check_key hn hu hv hs b c h₁ l + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- +# Equal local windows emit identical packed histories + +Compact each of the three name dictionaries in its fixed order. +Raw key equality then gives equality of numerical labels and links. +The padding conventions agree also on unused keys and empty spans. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing History.Subround Navigation Finset + +open scoped Classical in +private theorem compact_extend {A T K Z : Type} [Fintype A] [Fintype T] [Encodable K] {e : ℕ} + {f : A ↪ K} {g : T ↪ K} {hf : Fintype.card A ≤ 2 ^ e} {hg : Fintype.card T ≤ 2 ^ e} + (h : univ.map f = univ.map g) (a : A → Z) (t : T → Z) (base : B e → Z) + (he : ∀ i j, f i = g j → a i = t j) : + Function.extend (compact f hf) a base = Function.extend (compact g hg) t base := by + funext x + by_cases hx : x ∈ Set.range (compact f hf) + · obtain ⟨i, rfl⟩ := hx + obtain ⟨j, _, hj⟩ := mem_map.mp (h ▸ mem_map_of_mem f (mem_univ i)) + rw [(compact f hf).injective.extend_apply, compact_eq (hg := hg) h hj.symm, + (compact g hg).injective.extend_apply] + exact he i j hj.symm + have hy : x ∉ Set.range (compact g hg) := by + rintro ⟨j, rfl⟩ + obtain ⟨i, _, hi⟩ := mem_map.mp (h.symm ▸ mem_map_of_mem g (mem_univ j)) + exact hx ⟨i, compact_eq h hi⟩ + rw [Function.extend_apply' _ _ _ hx, Function.extend_apply' _ _ _ hy] + +open scoped Classical in +private theorem extend_slot {F L X Y Z : Type} {s : ℕ} (a : L → History.Atom F) + (index : ∀ i, (a i).Span ↪ B s) {i j : L} (e : i = j) + (f : ∀ x, 0 < (a i).width x → X) (g : ∀ y, 0 < (a j).width y → Y) + (p : X → Z) (q : Y → Z) (x : X) (y : Y) (he : p x = q y) + (hs : ∀ b c, HEq b c → ∀ h h', p (f b h) = q (g c h')) (t : B s) : + p (Function.extend (index i) (fun b => if h : 0 < (a i).width b then f b h else x) (fun _ + => x) t) = + q (Function.extend (index j) (fun c => if h : 0 < (a j).width c then g c h else y) (fun _ + => y) t) := by + subst j + by_cases h : t ∈ Set.range (index i) + · obtain ⟨b, rfl⟩ := h + simp only [(index i).injective.extend_apply] + by_cases hb : 0 < (a i).width b + · rw [dite_eq_left hb, dite_eq_left hb] + exact hs _ _ HEq.rfl _ _ + · simpa only [dite_eq_right hb] using he + simpa only [Function.extend_apply' _ _ _ h] using he + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} + {a h z Δ D k n e l s d : ℕ} {B' : ℝ} {u v : State S P a h z Δ D k B'} + +open scoped Classical in +private theorem compact_val {A K : Type} [Fintype A] [Encodable K] + (f : A ↪ K) (h : Fintype.card A ≤ 2 ^ e) (x : A) : + (compact f h x).val = Navigation.index (univ.map f) (f x) := rfl + +open scoped Classical in +theorem visible_index (R : u.Room e) (x : Visible u.g u.m P u.H.units u.i u.p.toPresentation u.v) : + (R.visible x).val = Navigation.index u.lists.2.2 (u.q.faceKey P u.H u.g u.m u.i + u.p.toPresentation x.val) := by + unfold Room.visible Navigation.visible lists Scheme.Posting.dictionaries + erw [@compact_val] + congr 3 + exact Subsingleton.elim _ _ + +open scoped Classical in +private theorem Same.link (same : u.Same v n) (hn : 4 ≤ n) (R : u.Room e) (T : v.Room e) + {x : PortMap.Port u.g u.m P u.H.units u.i u.p.toPresentation u.v} + {y : PortMap.Port v.g v.m P v.H.units v.i v.p.toPresentation v.v} + (he : u.q.portKey P u.g u.m u.i u.p.toPresentation u.v x = + v.q.portKey P v.g v.m v.i v.p.toPresentation v.v y) : + History.Packed.link R.hidden (x.map R.visible id, (0 : B d)) = + History.Packed.link T.hidden (y.map T.visible id, (0 : B d)) := by + have hs := same.lists hn + rcases x with x|x <;> rcases y with y|y + · have hv : R.visible x = T.visible y := by + apply Fin.ext + rw [visible_index, visible_index] + exact congrArg₂ Navigation.index (congrArg (fun p => p.2.2) hs) (congrArg Prod.snd he) + exact congrArg (fun i => (false, i, (0 : B d))) hv + · exact (Bool.false_ne_true (congrArg Prod.fst he)).elim + · exact (Bool.false_ne_true (congrArg Prod.fst he.symm)).elim + · have hv : R.hidden x = T.hidden y := + compact_eq (congrArg (fun p => p.2.1) hs) (congrArg Prod.snd he) + exact congrArg (fun i => (true, i, (0 : B d))) hv + +open scoped Classical in +theorem Same.packedCode (same : u.Same v n) (hn : 4 ≤ n) (R : u.Room e) (T : v.Room e) + (names : History.Kind S P (S.e + 2) ↪ B l) + (index : ∀ j : History.Kind S P (S.e + 2), (History.kind S P z u.hz j).Span ↪ B s) + (old new : B d) : + u.packedCode R names index old new = v.packedCode T names index old new := by + have keys := same.lists hn + apply Prod.ext + · apply compact_extend (congrArg (fun p => p.2.1) keys) + intro i j hij + exact congrArg (fun x => if x.isRight then new else old) hij + · unfold State.packedCode History.Packed.encode Room.atoms Navigation.atoms + dsimp only + refine compact_extend (congrArg Prod.fst keys) _ _ _ ?_ + intro i j hij + have hu : u.H.anchor u.g u.m u.col i.val = u.v := + (anchor_eq _).trans (includeAtom u.hz i).property + have hv : v.H.anchor v.g v.m v.col j.val = v.v := + (anchor_eq _).trans (includeAtom v.hz j).property + have he := same.kind hn hu hv hij + refine Prod.ext rfl (Prod.ext (congrArg names he) (funext fun q => ?_)) + refine extend_slot (History.kind S P z u.hz) index he + (fun x h => ((u.atomMap i.val hu).slot x h).map R.visible id) + (fun x h => ((v.atomMap j.val hv).slot x h).map T.visible id) + (fun x => History.Packed.link R.hidden (x, (0 : B d))) + (fun x => History.Packed.link T.hidden (x, (0 : B d))) + (.inl 0) (.inl 0) rfl ?_ q + intro x y hxy hx hy + exact same.link hn R T (same.atom_slot hn hu hv hij x y hxy hx hy) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Local determination of a complete contraction record -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing History + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + {u v : State S P a h z Δ D k B'} {m' d' h' e n : ℕ} {hz : 0 < z} {hle : Δ ≤ D} + +theorem Same.localRecord (same : u.Same v n) (hn : 8 ≤ n) (b : Book S P z hz) + (ru : u.Room e) (rv : v.Room e) (cap : ℕ) + (α : u.Assignment hle (b.scheme m' d' h' e cap)) (β : v.Assignment hle (b.scheme m' d' h' e + cap)) + (hindex : ∀ (x : Site (u.G.V × Cell a) (h - a)) (y : Site (v.G.V × Cell a) (h - a)), + Window.Related u.env v.env 4 x.1 y.1 → intervalCode _ x.2 = intervalCode _ y.2 → + α.index (u.v.1.1, u.v.2) (x.1.1, x.2) = β.index (v.v.1.1, v.v.2) (y.1.1, y.2)) + (ha : u.Ranked α) (hb : v.Ranked β) : + u.localRecord b ru cap α = v.localRecord b rv cap β := by + have hp := same.packedCode (by omega) ru rv b.names b.index (b.put (P.b * z)) (b.put z) + have hf := same.fields hn α β (u.sizes b) (v.sizes b) (fun _ _ he + => congrArg b.put he) hindex ha hb + exact Prod.ext rfl (Prod.ext hf (congrArg (Dense.encode cap) hp)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Posting a contracted host from its local histories -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing History History.Subround + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + {hz : 0 < z} {e m' d' h' : ℕ} + (u : State S P a h z Δ D k B') (b : Book S P z hz) (r : u.Room e) (cap : ℕ) + (hle : Δ ≤ D) + +open scoped Classical in +/-- Uses `⟨host, block, slot, fun v => (r.recenter v).visible⟩` as the representation. -/ +abbrev allocate (host : Site u.G.V (h - a) ↪ B m') (block : Cell a ↪ B h') + (slot : Site u.G.V (h - a) → Site u.G.V (h - a) → B d') : + u.Assignment hle (b.scheme m' d' h' e cap) := + ⟨host, block, slot, fun v => (r.recenter v).visible⟩ + +variable {hle} (A : u.Assignment hle (b.scheme m' d' h' e cap)) (nav : B m' → B d' → B m') + +open scoped Classical in +/-- The value specified by `Post.write b.menu (Dense.unpack (m := e) cap) nav (u.records b r cap +A)`. -/ +abbrev output := Post.write b.menu (Dense.unpack (m := e) cap) nav (u.records b r cap A) + +open scoped Classical in +/-- The bounds necessary to store this family of local histories. -/ +structure Ready : Prop where + seat : ∀ v, A.seat v = (r.recenter v).visible + sizes : ∀ j, b.len (b.put (u.p.toPresentation.borderWidth j)) = u.p.toPresentation.borderWidth j + hop : ∀ v w, w ∈ (u.G.project a u.ha Δ D hle).C v → nav (A.host v) (A.index v w) = A.host w + neutral : ∀ v, u.G.diagram.arity v = 0 → ∀ x, Transcript.sample (u.G.diagram.table v) x = 1 + budget : ∀ v, b.overhead e + (u.recenter v).inherited b.ord ≤ cap + +open scoped Classical in +private theorem offsets {e : ℕ} (w : B e → ℕ) {x y : B e} (he : x = y) + {n : ℕ} (i : Fin n) (hx : n = w x) (hy : n = w y) : + (⟨x, i.cast hx⟩ : Σ j, Fin (w j)) = ⟨y, i.cast hy⟩ := by subst y; rfl + +namespace Ready + +variable {u b r cap A nav} (H : Ready u b r cap A nav) + +include H in +open scoped Classical in +theorem emitted : A.Emitted (u.sizes b) nav (u.records b r cap A) := by + refine A.emitted _ _ _ b.zero ?_ (A.end_nav nav H.hop) + rintro (j|j) + · exact H.sizes j + · exact b.unit + +include H in +open scoped Classical in +theorem ranked : u.Ranked A := by + intro v j + rw [H.seat v] + exact visible_index (r.recenter v) j + +local notation "Z" => b.scheme m' d' h' e cap +local notation "out" => u.output b r cap A nav +local notation "len" => H.emitted.lengths + +open scoped Classical in +/-- The widths of the fields in the posted record for a site. -/ +abbrev readyWidths (v : Site u.H.V (h - a)) (j : B e) := + (Z).width out (A.vertex v, j) + +local notation "readyW" => readyWidths (u := u) (b := b) (r := r) (cap := cap) (A := A) (nav := nav) +local notation "VisibleAt" => Visible u.g u.m P u.H.units u.i u.p.toPresentation +local notation "Width" => (fun q => visibleWidth u.g u.m P u.i u.p.toPresentation z q) + +include H in +open scoped Classical in +theorem visible_width (v : Site u.H.V (h - a)) (j : VisibleAt v) : + readyW v ((r.recenter v).visible j) = Width j.val := by + rw [show (r.recenter v).visible = A.seat v from (H.seat v).symm] + exact A.length_at len v j + +include H in +open scoped Classical in +theorem visible_pin (v : Site u.H.V (h - a)) (j : VisibleAt v) (k : Fin (Width j.val)) : + A.pin len u.hz v (visibleBits u.g u.m P u.H.units u.hz u.i u.p.toPresentation v ⟨j, k⟩) = + ⟨(r.recenter v).visible j, k.cast (H.visible_width v j).symm⟩ := by + erw [A.pin_at len u.hz v j k] + have seat : A.seat v j = (r.recenter v).visible j := + congrArg (fun seat : VisibleAt v ↪ B e => seat j) (H.seat v) + exact offsets (readyW v) seat k (A.length_at len v j).symm (H.visible_width v j).symm + +open scoped Classical in +private def DecodesAt (b : Book S P z hz) (v : Site u.H.V (h - a)) + (room : (u.recenter v).Room e) (width : B e → ℕ) : Prop := + let size := (u.recenter v).hiddenSize (b.put (P.b * z)) (b.put z) + ∀ (hw : ∀ j : VisibleAt v, width (room.visible j) = Width j.val) + (pin : (u.g.contract u.m P u.H.units u.hz u.i).Port v ≃ Positions width), + (∀ (j : VisibleAt v) (k : Fin (Width j.val)), + pin (visibleBits u.g u.m P u.H.units u.hz u.i u.p.toPresentation v ⟨j, k⟩) = + ⟨room.visible j, k.cast (hw j).symm⟩) → + (∀ j, u.H.diagram.arity j = 0 → ∀ x, Transcript.sample (u.H.diagram.table j) x = 1) → + ∀ {count : ℕ} (atoms : Receipt P u.H u.g u.m u.i v ↪ B count) + (hidden : Hidden u.g u.m P u.i v ↪ B e) (t : Positions width → Bool), + (History.menu (History.kind S P z u.hz) b.names b.index b.len).decode width + (((u.recenter v).bundle.packed b.names b.index room.visible size).encode atoms hidden) t = + Transcript.sample ((u.g.contract u.m P u.H.units u.hz u.i).table v) (t ∘ pin) + +open scoped Classical in +private theorem decode_code_at (v : Site u.H.V (h - a)) (room : (u.recenter v).Room e) + (width : B e → ℕ) : DecodesAt b v room width := by + unfold DecodesAt + intro size hw pin hp neutral count atoms hidden t + let state := u.recenter v + let old := b.put (P.b * z) + let fresh := b.put z + have size_width := state.hiddenSize_spec old fresh b.len b.old b.unit + have correct := @Bundle.decode u.T F inferInstance u.finite u.x u.y u.L (h - a) z P u.H + Δ D k B' u.g u.m u.i S u.r u.p.toPresentation u.hz v (S.e + 2) e + (S.ℓ + Kind.width S P (S.e + 2)) b.s b.d state.bundle b.names b.index room.visible + size b.len width b.zero size_width hw pin hp neutral count atoms hidden t + with_reducible exact correct + +include H in +open scoped Classical in +private theorem agrees_at (v : Site u.H.V (h - a)) (t : Positions (readyW v) → Bool) : + b.menu.decode (readyW v) ((u.recenter v).codeAt b (r.recenter v)) t = + Transcript.sample ((u.g.contract u.m P u.H.units u.hz u.i).table v) + (t ∘ A.pin len u.hz v) := + decode_code_at (b := b) v (r.recenter v) (readyW v) (H.visible_width v) + (A.pin len u.hz v) (H.visible_pin v) H.neutral (r.recenter v).atoms (r.recenter v).hidden t + +include H in +open scoped Classical in +theorem agrees : A.Agrees len u.hz := + H.emitted.agrees u.hz fun v t => by + rw [u.record_at b r cap A v] + change b.menu.decode _ (Dense.unpack (m := e) cap ((u.recenter v).data b (r.recenter v) cap)) + t = _ + rw [(u.recenter v).unpack_data b (r.recenter v) cap (H.budget v)] + exact H.agrees_at v t + +include H in +open scoped Classical in +/-- Uses `A.posting len u.hz H.agrees hle` as the representation. -/ +def posting : (Z).Posting out (HostNet.contracted (u.G.project a u.ha Δ D hle) u.g u.m u.hz hle + u.i) := + A.posting len u.hz H.agrees hle + +open scoped Classical in +theorem floor {w : ℕ} (hw : ∀ j, w ≤ u.p.toPresentation.borderWidth j) : + ∀ j, w ≤ H.posting.toPresentation.borderWidth j := + H.emitted.floor u.hz H.agrees hw + +open scoped Classical in +theorem palette (W : Finset ℕ) (hw : ∀ j, u.p.toPresentation.borderWidth j ∈ W) : + ∀ j, H.posting.toPresentation.borderWidth j ∈ W := by + let p' := A.presentation len u.hz H.agrees + intro j + let x : p'.BorderBit := ⟨j, ⟨0, j.property.1⟩⟩ + obtain ⟨t, ht⟩ := u.p.toPresentation.exteriorBits.surjective (p'.exteriorBits x) + have h := (H.emitted.boundary u.hz H.agrees (p'.exteriorBits x)).1 + rw [p'.border_pin, ← ht] at h + have h := h.trans (congrArg (fun q : S.Pin u.r => S.width u.r q.1) (u.p.toPresentation.border_pin + t)) + exact Eq.mp (congrArg (· ∈ W) h.symm) (hw t.1) + +include H in +open scoped Classical in +theorem stored (v : Site u.H.V (h - a)) : + Dense.used (Post.order d' e b.d cap ((out (A.vertex v).1).2 (A.vertex v).2.1)).val ≤ + (Post.headerFmt d' e b.d).width + b.overhead e + (u.recenter v).inherited b.ord := by + let u' := u.recenter v + let r' := r.recenter v + let p := u'.bundle.packed b.names b.index r'.visible (u'.hiddenSize (b.put (P.b * z)) (b.put z)) + let q := u'.localRecord b r' cap A + have h := u'.stored b.ord p (fun _ => rfl) r'.atoms r'.hidden (H.budget v) q rfl + change Dense.used (Post.order d' e b.d cap ((Post.record _ _ _ _).serial + (u.records b r cap A (A.vertex v).1 (A.vertex v).2.1))).val ≤ _ + rw [u.record_at] + exact h.2 + +end Ready +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- +# Amortizing the length of a contraction history + +Charge an old table name just once against its occurrence's current +and retired ports. In particular, the previous maximum name length +is not multiplied by the number of contributing stations. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Packing + +namespace Packing.HostNet + +variable {F T : Type} {x y : Wire} {L : Fringe x y T} {h u : ℕ} (G : HostNet F L h u) + +open scoped Classical in +theorem active_floor (he : ∀ t, u ≤ G.tetherLoad (G.far t)) (w : G.V × Cell h) + (hp : 0 < G.tetherLoad w + degree G.pair w * u) : u ≤ G.footprint w := by + by_cases hx : G.tetherLoad w = 0 + · have hh : 0 < degree G.pair w := by + by_contra! hz + simp [hx, Nat.eq_zero_of_le_zero hz] at hp + have := Nat.le_mul_of_pos_left u hh + unfold footprint + omega + · have hf : ∃ t, G.far t = w := by + by_contra! hn + have hv : (G.tetherLoad w : ℝ) = 0 := by + rw [tetherLoad, port_load] + change push G.far (fun _ => 1) w = 0 + simp [push, hn] + exact hx (Nat.cast_eq_zero.mp hv) + obtain ⟨t, rfl⟩ := hf + have := he t + unfold footprint + omega + +open scoped Classical in +theorem arity_active [Finite T] (v : G.diagram.V) (hv : 0 < G.diagram.arity v) : + 0 < G.tetherLoad (G.units.place v) + degree G.pair (G.units.place v) * u := by + let : Fintype T := Fintype.ofFinite T + let w := G.units.place v + have ht : (G.diagram.arity v : ℝ) ≤ push G.units.place (fun i => (G.diagram.arity i : ℝ)) w := by + unfold push + refine le_trans ?_ (Finset.single_le_sum (fun i _ + => by split_ifs <;> positivity) (Finset.mem_univ v)) + simp [w] + have he := G.load_eq w + simp only [load, Prod.mk.eta] at he + have hp : (0 : ℝ) < (G.diagram.arity v : ℝ) := Nat.cast_pos.mpr hv + have h : 0 < (G.tetherLoad w : ℝ) + degree G.pair w * (u : ℝ) := by linarith only [ht, he, hp] + exact_mod_cast h + +end Packing.HostNet + +namespace Assembly.State +open Coloring History + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') (o : B S.ℓ ≃ B S.ℓ) (unit cost : ℕ) + +open scoped Classical in +/-- The charged used in the `State` construction. -/ +def Charged := ∀ w : u.G.V × Cell h, 0 < u.G.tetherLoad w + degree u.G.pair w * (P.b * z) → + Dense.used (o ((u.r (u.p.host w.1)).2 (u.p.block w.2))).val * unit ≤ cost * u.G.footprint w + +variable {o unit cost} (hc : Δ ≤ D) + +local notation "pr" => u.G.project a u.ha Δ D hc +local notation "Q" => HostNet.contracted pr u.g u.m u.hz hc u.i + +open scoped Classical in +theorem inherited_charge (tag : u.Charged o unit cost) (hu : 0 < unit) : + u.inherited o * unit ≤ cost * (Q).footprint ((pr).place u.v) := by + let c : ℝ := (cost : ℝ) / unit + have hc' : 0 ≤ c := by unfold c; positivity + have hu' : (0 : ℝ) < unit := Nat.cast_pos.mpr hu + let mass (p : u.H.V × Cell (h - a)) := c * (u.H.footprint p : ℝ) + have hh := u.inherited_le o mass (fun t => mul_nonneg hc' (Nat.cast_nonneg _)) (by + intro v hv + let w := u.G.units.place v + have ht := tag w (u.G.arity_active v hv) + rw [oldTag, u.p.vertex_eq] + change (Dense.used (o ((u.r (u.p.host w.1)).2 (u.p.block w.2))).val : ℝ) ≤ + (cost : ℝ) / unit * (u.G.regroup a u.ha).footprint (splitAddr u.G.V a u.ha w) + rw [u.G.regroup_footprint, div_mul_eq_mul_div, le_div_iff₀ hu'] + exact_mod_cast ht) + have hf := HostNet.footprint_route pr u.g u.m u.hz hc u.i u.v + have hm : push (fun t => u.g.route u.m u.col t.1 t.2) mass u.v + ≤ c * (Q).footprint ((pr).place u.v) := by + refine le_trans ?_ (mul_le_mul_of_nonneg_left hf hc') + have ee := push_div (Function.uncurry (u.g.route u.m u.col)) + (fun t => (u.H.footprint t : ℝ)) c⁻¹ u.v + simp only [div_inv_eq_mul, mul_comm _ c] at ee + exact ee.le + have hh := hh.trans hm + rw [show c = (cost : ℝ) / unit from rfl, div_mul_eq_mul_div, le_div_iff₀ hu'] at hh + exact_mod_cast hh + +open scoped Classical in +theorem inherited_bound (tag : u.Charged o unit cost) (hu : 0 < unit) (B : ℕ) + (hm : (Q).mass ≤ u.L.cap) (hl : ∀ v i, (Q).load v i ≤ (B : ℝ) * unit) : + u.inherited o ≤ cost * (2 ^ u.L.discount * B) := by + let w := (pr).place u.v + have hp : (Q).footprint w ≤ 2 ^ u.L.discount * B * unit := by + have he := ((Q).footprint_le hm w).trans (mul_le_mul_of_nonneg_left (hl w.1 w.2) (by + positivity)) + rw [← mul_assoc] at he + exact_mod_cast he + apply Nat.le_of_mul_le_mul_right _ hu + rw [mul_assoc] + exact (u.inherited_charge hc tag hu).trans (Nat.mul_le_mul_left _ hp) + +end Assembly.State +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Prefix.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Prefix.lean new file mode 100644 index 0000000000..61725ec863 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Prefix.lean @@ -0,0 +1,956 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rule +public import Mathlib.Data.Nat.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Entry +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Checks + +/-! # Eliminating the private join variables of a routed wire -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule + +variable {K S E X Y : Type} [Field K] [Fintype S] [Fintype E] [Fintype X] [Fintype Y] + +open Classical in +/-- If nonzero contributions force a single setting of every local +joining bit, the serial sum is the product at that setting. -/ +theorem series_eval {a b c : E → S} {W : X → S × S} {U : Y → S × S} + (hf : Rule K (fun e => (a e, b e)) (fun _ : Unit => W)) + (hg : Rule K (fun e => (b e, c e)) (fun _ : Unit => U)) + (v : S) (x y : E → Bool) (u : X ⊕ Y → Bool) (k : E → Bool) + (hp : ∀ t, hf.entry () v x t (u ∘ Sum.inl) ≠ 0 → hg.entry () v t y (u ∘ Sum.inr) ≠ 0 → + ∀ e, b e = v → t e = k e) : + (hf.series hg).entry () v x y u = + hf.entry () v x k (u ∘ Sum.inl) * hg.entry () v k y (u ∘ Sum.inr) := by + let T := {e // b e = v} + let fill (t : T → Bool) (e : E) := if h : b e = v then t ⟨e, h⟩ else false + let z (e : T) := k e.1 + change (∑ t, hf.entry () v x (fill t) (u ∘ Sum.inl) * hg.entry () v (fill t) y (u ∘ Sum.inr)) = _ + rw [Fintype.sum_eq_single z] + · have he (e) (h : b e = v) : fill z e = k e := by simp [fill, h, z] + apply congrArg₂ (· * ·) + · exact hf.local' _ _ _ _ _ _ _ _ (fun _ _ => rfl) he (fun _ _ => rfl) + · exact hg.local' _ _ _ _ _ _ _ _ he (fun _ _ => rfl) (fun _ _ => rfl) + · intro t ht + by_contra hn + apply ht + funext e + have hh := hp (fill t) (left_ne_zero_of_mul hn) (right_ne_zero_of_mul hn) e.val e.property + simpa only [fill, dite_eq_left e.property] using hh + +open Classical in +theorem path_entry (D : ℕ → E → S) (n : ℕ) (v : S) (x y : E → Bool) (z : Fin n × E → Bool) : + (Rule.path K D n).entry () v x y z = + if ∀ (i : Fin (n + 1)) e, D i.val e = v → + Fin.cons (α := fun _ => E → Bool) x (Function.curry z) i e = + Fin.snoc (α := fun _ => E → Bool) (Function.curry z) y i e then 1 else 0 := rfl + +open Classical in +theorem path_head (D : ℕ → E → S) {n : ℕ} (v : S) (x y : E → Bool) (z : Fin (n + 1) × E → Bool) + (hn : (Rule.path K D (n + 1)).entry () v x y z ≠ 0) (e : E) (he : D 0 e = v) : + x e = z (0, e) := by + rw [path_entry] at hn + split at hn + · rename_i h + simpa [Fin.snoc] using h 0 e he + · contradiction + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule +end + +/- +# Products of trivalent tables on named bits + +Collect all factors with the same ordered triple of inputs by +pointwise multiplication. Over a finite field the resulting table +of coefficients has a cubic description length. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Finset +variable (F J : Type) [Field F] [Fintype J] + +open Classical in +/-- The indexing data represented by `Fin 3 → Option J`. -/ +abbrev Triple := Fin 3 → Option J +open Classical in +/-- The indexing data represented by `Triple J → (Fin 3 → Bool) → F`. -/ +abbrev Tables := Triple J → (Fin 3 → Bool) → F +open Classical in +/-- Computes the read bit by the application `s.elim false x`. -/ +def readBit (x : J → Bool) (s : Option J) : Bool := s.elim false x + +open Classical in +/-- The product of `c j (readBit J x ∘ j)` indexed by `j`. -/ +def evaluate (c : Tables F J) (x : J → Bool) := ∏ j, c j (readBit J x ∘ j) + +open Classical in +/-- Builds `Submonoid ((J → Bool) → F) where carrier` with the specified `carrier`, `one_mem'`, +`mul_mem'`. -/ +def simple : Submonoid ((J → Bool) → F) where + carrier := Set.range (evaluate F J) + one_mem' := ⟨1, by ext; simp [evaluate]⟩ + mul_mem' := by + rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩ + exact ⟨a * b, by ext; simp [evaluate, prod_mul_distrib]⟩ + +open Classical in +/-- The quantity computed by `(Fintype.card J + 1) ^ 3 * 8 * Nat.clog 2 (Fintype.card F)`. -/ +def tripleCost [Fintype F] := (Fintype.card J + 1) ^ 3 * 8 * Nat.clog 2 (Fintype.card F) + +omit [Field F] in +open Classical in +theorem triple_bound [Fintype F] : Fintype.card (Tables F J) ≤ 2 ^ tripleCost F J := by + simp only [Tables, Triple, Fintype.card_fun, Fintype.card_option, Fintype.card_fin, + Fintype.card_bool] + unfold tripleCost + rw [mul_comm _ (Nat.clog _ _), pow_mul (2 : ℕ), ← pow_mul] + rw [mul_comm (2 ^ 3)] + exact Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) _ + +variable {F J} + +open Classical in +theorem one_table (j : Triple J) (g : (Fin 3 → Bool) → F) : + (fun x => g (readBit J x ∘ j)) ∈ simple F J := by + refine ⟨fun k z => if k = j then g z else 1, ?_⟩ + ext x + simp [evaluate] + +open Classical in +theorem local_table {I : Type} [Fintype I] (f : (J → Bool) → F) (a : I → Option J) + (hb : Fintype.card I ≤ 3) + (hf : ∀ x y, (∀ j, readBit J x (a j) = readBit J y (a j)) → f x = f y) : + f ∈ simple F J := by + obtain ⟨e⟩ : Nonempty (I ↪ Fin 3) := Function.Embedding.nonempty_of_card_le (by simpa using hb) + let addr := Function.extend e a (fun _ => none) + let pull (x : J → Bool) := readBit J x ∘ addr + have he (x y : J → Bool) (h : pull x = pull y) : f x = f y := by + apply hf + intro i + simpa only [pull, Function.comp_apply, addr, e.injective.extend_apply] using congrFun h (e i) + let k (t : Fin 3 → Bool) := f (Function.invFun pull t) + have h := one_table addr k + convert h using 1 + funext x + exact he _ _ (Function.invFun_eq ⟨x, rfl⟩).symm + +open Classical in +theorem prod_simple {I : Type} (S : Finset I) (f : I → (J → Bool) → F) + (hf : ∀ i ∈ S, f i ∈ simple F J) : + (fun x => ∏ i ∈ S, f i x) ∈ simple F J := by + convert (simple F J).prod_mem hf using 1 + ext + exact (Finset.prod_apply ..).symm + +open Classical in +theorem check_simple (a b : Option J) : + (fun x => if readBit J x a = readBit J x b then (1 : F) else 0) ∈ simple F J := + one_table ![a, b, none] (fun t => if t 0 = t 1 then 1 else 0) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # A local description of a reset station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Coloring +variable {F : Type} [Field F] + +open scoped Classical in +/-- Indexes the addr by the coordinates of `B e ⊕ B e`. -/ +abbrev Addr (e : ℕ) := B e ⊕ B e +open scoped Classical in +/-- Indexes the control by the coordinates of `Bool × B S.k × (B S.e → Addr e)`. -/ +abbrev Control (S : Scheme F) (e : ℕ) := Bool × B S.k × (B S.e → Addr e) +open scoped Classical in +/-- Indexes the shape by the coordinates of `Fin (2 ^ e + 1) × (B e → Control S e) × Tables F +(Addr e)`. -/ +abbrev Shape (S : Scheme F) (e : ℕ) := Fin (2 ^ e + 1) × (B e → Control S e) × Tables F (Addr e) +open scoped Classical in +/-- Indexes the recipe by the coordinates of `Shape S e × (B e → B S.ℓ)`. -/ +abbrev Recipe (S : Scheme F) (e : ℕ) := Shape S e × (B e → B S.ℓ) + +variable {S : Scheme F} {e : ℕ} + +open scoped Classical in +/-- In the case `.inl i, j`, this construction gives `x i j`. -/ +def fetch {n u : ℕ} (x : B e → ℕ → Bool) (y : Fin n × Fin u → Bool) : Addr e → ℕ → Bool + | .inl i, j => x i j + | .inr i, j => if h : i.val < n ∧ j < u then y (⟨i, h.1⟩, ⟨j, h.2⟩) else false + +open scoped Classical in +/-- Returns `(S.decode (o.symm t)).value c.2.1 (fun i j => f (c.2.2 i) j.val)` when `c.1` holds, +and `1` otherwise. -/ +def prior (o : B S.ℓ ≃ B S.ℓ) (c : Control S e) (t : B S.ℓ) (f : Addr e → ℕ → Bool) : F := + if c.1 then (S.decode (o.symm t)).value c.2.1 (fun i j => f (c.2.2 i) j.val) else 1 + +open scoped Classical in +/-- The run of type `F` for the given inputs. -/ +def run (o : B S.ℓ ≃ B S.ℓ) (u : ℕ) (r : Recipe S e) (x : B e → ℕ → Bool) : F := + ∑ y : Fin r.1.1.val × Fin u → Bool, + (∏ i : B e, prior o (r.1.2.1 i) (r.2 i) (fetch x y)) * + ∏ j : Fin u, evaluate F (Addr e) r.1.2.2 (fun i => fetch x y i j.val) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- +# Canonical labels for reset tables + +A recipe stores fixed-size controls and the old labels at their actual +bit lengths. Choosing the least label for a function makes the emitted +record independent of the recipe witnessing its length bound. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Coloring + +variable {F : Type} [Fintype F] (S : Scheme F) (e : ℕ) + +open scoped Classical in +/-- The quantity computed by `e + 1 + 2 ^ e * (1 + S.k + 2 ^ S.e * (e + 1)) + tripleCost F (Addr +e)`. -/ +def shapeWidth := e + 1 + 2 ^ e * (1 + S.k + 2 ^ S.e * (e + 1)) + tripleCost F (Addr e) +open scoped Classical in +/-- The quantity computed by `shapeWidth S e + 2 ^ e * Dense.used S.ℓ`. -/ +def overhead := shapeWidth S e + 2 ^ e * Dense.used S.ℓ + +open scoped Classical in +private theorem card_addr : Fintype.card (Addr e) = 2 ^ (e + 1) := by + simp only [Addr, B, Fintype.card_sum, Fintype.card_fin, pow_succ, mul_two] + +omit [Fintype F] in +open scoped Classical in +private theorem card_control : Fintype.card (Control S e) = 2 ^ (1 + S.k + 2 ^ S.e * (e + 1)) := by + simp only [Control, Fintype.card_prod, Fintype.card_bool, Fintype.card_fun, card_addr, B, + Fintype.card_fin] + rw [← pow_mul, mul_comm (e + 1), pow_add, pow_add, pow_one, mul_assoc] + +omit [Fintype F] in +open scoped Classical in +private theorem card_controls : Fintype.card (B e → Control S e) = 2 ^ (2 ^ e * (1 + S.k + + 2 ^ S.e * (e + 1))) := by + rw [Fintype.card_fun, card_control, ← pow_mul, mul_comm] + simp only [B, Fintype.card_fin] + +open scoped Classical in +private theorem prod_bound (A B C : Type) [Fintype A] [Fintype B] [Fintype C] (a b c : ℕ) + (ha : Fintype.card A ≤ 2 ^ a) (hb : Fintype.card B ≤ 2 ^ b) (hc : Fintype.card C ≤ 2 ^ c) : + Fintype.card (A × B × C) ≤ 2 ^ (a + b + c) := by + rw [Fintype.card_prod, Fintype.card_prod, pow_add, pow_add, mul_assoc] + exact Nat.mul_le_mul ha (Nat.mul_le_mul hb hc) + +open scoped Classical in +private theorem tables_bound (J : Type) [Fintype J] (I : Fintype (Tables F J)) : + @Fintype.card _ I ≤ 2 ^ tripleCost F J := by + convert! triple_bound F J using 2 + +open scoped Classical in +theorem shape_bound : Fintype.card (Shape S e) ≤ 2 ^ shapeWidth S e := by + have hn : Fintype.card (Fin (2 ^ e + 1)) ≤ 2 ^ (e + 1) := by + rw [Fintype.card_fin, pow_succ, mul_two] + exact Nat.add_le_add_left (Nat.two_pow_pos _) _ + exact prod_bound _ _ _ _ _ _ hn (card_controls S e).le (tables_bound (Addr e) inferInstance) + +open scoped Classical in +/-- Embeds `Shape S e` into `B (shapeWidth S e)`. -/ +def shapeCode : Shape S e ↪ B (shapeWidth S e) := + (Fintype.equivFin _).toEmbedding.trans (Fin.castLEEmb (shape_bound S e)) + +variable {S e} + +open scoped Classical in +/-- The value specified by `Dense.pack (shapeCode S e r.1, r.2)`. -/ +def recipeCode (r : Recipe S e) := Dense.pack (shapeCode S e r.1, r.2) + +open scoped Classical in +private theorem recipeCode_inj : Function.Injective (recipeCode (S := S) (e := e)) := by + intro r s h + obtain ⟨ha, hb⟩ := Prod.mk.inj (Dense.injective h) + exact Prod.ext ((shapeCode S e).injective ha) hb + +open scoped Classical in +theorem recipe_length (r : Recipe S e) : + Dense.used (recipeCode r) ≤ overhead S e + Dense.cost r.2 := by + simpa only [recipeCode, overhead, Dense.header, B, Fintype.card_fin] using + Dense.length (shapeCode S e r.1, r.2) + +variable [Field F] (o : B S.ℓ ≃ B S.ℓ) (u cap : ℕ) + +open scoped Classical in +/-- The value specified by `run o u (Function.invFun (recipeCode (S := S) (e := e)) c.val)`. -/ +def decoder (c : B cap) : (B e → ℕ → Bool) → F := + run o u (Function.invFun (recipeCode (S := S) (e := e)) c.val) + +variable (target : (B e → ℕ → Bool) → F) + +open scoped Classical in +/-- The subset of all indices on which the defining predicate holds. -/ +def candidates := Finset.univ.filter (fun c : B cap => decoder o u cap c = target) + +open scoped Classical in +/-- Returns `(candidates o u cap target).min' h` when `h : (candidates o u cap target).Nonempty` +holds, and `0` otherwise. -/ +def canonical : B cap := + if h : (candidates o u cap target).Nonempty then (candidates o u cap target).min' h else 0 + +variable {o u cap target} + +open scoped Classical in +theorem canonical_spec (r : Recipe S e) (hr : run o u r = target) + (hc : overhead S e + Dense.cost r.2 ≤ cap) : + decoder o u cap (canonical o u cap target) = target ∧ + Dense.used (canonical o u cap target).val ≤ overhead S e + Dense.cost r.2 := by + let c : B cap := ⟨recipeCode r, Dense.used_le.mp ((recipe_length r).trans hc)⟩ + let t := candidates o u cap target + have ht : c ∈ t := by + refine Finset.mem_filter.mpr ⟨Finset.mem_univ _, ?_⟩ + change run o u (Function.invFun recipeCode (recipeCode r)) = target + rw [Function.leftInverse_invFun recipeCode_inj r] + exact hr + have hn : t.Nonempty := ⟨c, ht⟩ + have he : canonical o u cap target = t.min' hn := dite_eq_left hn + rw [he] + refine ⟨(Finset.mem_filter.mp (t.min'_mem hn)).2, Dense.used_le.mpr ?_⟩ + exact lt_of_le_of_lt (t.min'_le c ht) (Dense.used_le.mp (recipe_length r)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- +# Short tags for a contracted table + +Keep the short pointer rows intact. Only the recursively generated +labels need variable-length packing. Unoccupied slots use the zero +tag and so consume no tag bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +open Coloring +variable {F A T : Type} {m e l s d : ℕ} + +namespace Dense + +open scoped Classical in +/-- The indexed operation `((code m e 0 s d).serial (c.1, fun i => ((c.2 i).1, 0, (c.2 i).2.2)), +fun i => (c.2 i).2.1)`. -/ +def split (c : (code m e l s d).obj) : B (code m e 0 s d).width × (B m → B l) := + ((code m e 0 s d).serial (c.1, fun i => ((c.2 i).1, 0, (c.2 i).2.2)), fun i => (c.2 i).2.1) + +open scoped Classical in +private theorem split_inj : Function.Injective (split (m := m) (e := e) (l := l) (s := s) (d := d)) + := by + intro x y h + obtain ⟨a, b⟩ := Prod.mk.inj h + obtain ⟨u, v⟩ := Prod.mk.inj ((code m e 0 s d).serial.injective a) + refine Prod.ext u (funext fun i => ?_) + have he := congrFun v i + exact Prod.ext (Prod.mk.inj he).1 (Prod.ext (congrFun b i) (Prod.mk.inj (Prod.mk.inj he).2).2) + +open scoped Classical in +/-- Computes the index by the application `pack (split c)`. -/ +def index (c : (code m e l s d).obj) := pack (split c) + +open scoped Classical in +theorem index_inj : Function.Injective (index (m := m) (e := e) (l := l) (s := s) (d := d)) := + injective.comp split_inj + +open scoped Classical in +/-- The quantity computed by `(code m e 0 s d).width + 2 ^ m * used l`. -/ +def overhead (m e l s d : ℕ) := (code m e 0 s d).width + 2 ^ m * used l + +open scoped Classical in +theorem index_length (c : (code m e l s d).obj) : + used (index c) ≤ overhead m e l s d + ∑ i, used ((c.2 i).2.1).val := by + simpa only [index, overhead, header, cost, split, B, Fintype.card_fin] using length (split c) + +open scoped Classical in +/-- Only tags below the chosen limit are requested. On other inputs +the computation may return a dummy value. -/ +def encode (q : ℕ) (c : (code m e l s d).obj) : B q := + if h : index c < 2 ^ q then ⟨index c, h⟩ else 0 + +open scoped Classical in +/-- Computes the unpack by the application `Function.invFun index v.val`. -/ +def unpack (q : ℕ) (v : B q) : (code m e l s d).obj := + Function.invFun index v.val + +open scoped Classical in +theorem encode_val {q : ℕ} {c : (code m e l s d).obj} (h : used (index c) ≤ q) : + (encode q c).val = index c := by simp [encode, used_le.mp h] + +open scoped Classical in +theorem unpack_encode {q : ℕ} {c : (code m e l s d).obj} (h : used (index c) ≤ q) : + unpack q (encode q c) = c := by + rw [unpack, encode_val h] + exact Function.leftInverse_invFun index_inj c + +end Dense + +namespace Packed +variable [Fintype A] (p : Packed A T e l s d) (g : A ↪ B m) (f : T ↪ B e) + +open scoped Classical in +theorem index_length : + Dense.used (Dense.index (p.encode g f)) ≤ + Dense.overhead m e l s d + ∑ i, Dense.used (p.tag i).val := by + refine (Dense.index_length _).trans_eq (congrArg _ ?_) + symm + refine Fintype.sum_of_injective g g.injective _ _ ?_ ?_ + · intro j hj + simp only [encode, Function.extend_apply' _ _ _ hj] + exact Dense.used_zero + · intro i + rw [store] + +open scoped Classical in +theorem unpack_encode {q : ℕ} (h : Dense.overhead m e l s d + (∑ i, Dense.used (p.tag i).val) ≤ q) : + Dense.unpack q (Dense.encode q (p.encode g f)) = p.encode g f := + Dense.unpack_encode ((p.index_length g f).trans h) + +end Packed +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +end + +/- +# Local records for a wire-saving step + +The decoder reads only the block record. Global names appear in the +host's common neighbor array. The vacant record has no arguments +and weight one, including in positive characteristic. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Post +open Coloring + +open scoped Classical in +/-- Extend a record to a padded position, using its vacant value outside the original range. -/ +def extendRecord {A X Y T : Type*} (vertex : A → X × Y × B 0) + (localRecord : A → T) (vacant : T) (x : X) (y : Y) : T := + Function.extend vertex localRecord (fun _ => vacant) (x, y, 0) + +private theorem paddedVertex {X Y : Type*} (v : X × Y × B 0) : + (v.1, v.2.1, (0 : B 0)) = v := + Prod.ext rfl (Prod.ext rfl (Fin.eq_zero _).symm) + +theorem extendRecord_at {A X Y T : Type*} (vertex : A ↪ X × Y × B 0) + (localRecord : A → T) (vacant : T) (v : A) : + extendRecord vertex localRecord vacant (vertex v).1 (vertex v).2.1 = localRecord v := by + classical + unfold extendRecord + rw [paddedVertex] + exact vertex.injective.extend_apply _ _ v + +theorem extendRecord_vacant {A X Y T : Type*} (vertex : A → X × Y × B 0) + (localRecord : A → T) (vacant : T) (v : X × Y × B 0) (outside : v ∉ Set.range vertex) : + extendRecord vertex localRecord vacant v.1 v.2.1 = vacant := by + classical + unfold extendRecord + rw [paddedVertex] + exact Function.extend_apply' _ _ _ outside + +/-- Length index, direction, attached flag, neighbor slot, peer slot. -/ +abbrev field (d e ℓ : ℕ) : Format := + .pair (.addr ℓ) (.pair .bit (.pair .bit (.pair (.addr d) (.addr e)))) + +/-- The value specified by `.pair .bit (.pair (.vec e (field d e ℓ)) Y)`. -/ +abbrev record (d e ℓ : ℕ) (Y : Format) : Format := + .pair .bit (.pair (.vec e (field d e ℓ)) Y) + +theorem width_record (d e ℓ : ℕ) (Y : Format) : + (record d e ℓ Y).width = 1 + (2 ^ e * (ℓ + (1 + (1 + (d + e)))) + Y.width) := by + simp [record, field] + +variable {F : Type} [Field F] {m d h e l s ℓ a : ℕ} {Y : Format} + +/-- The value specified by `(0, false, false, 0, 0)`. -/ +abbrev unused : (field d e ℓ).obj := (0, false, false, 0, 0) + +/-- The indexed operation `(false, fun _ => unused, Y.serial.symm 0)`. -/ +def vacant : (record d e ℓ Y).obj := (false, fun _ => unused, Y.serial.symm 0) + +/-- Builds `Pattern F d 0 e where width _ t` with the specified `width`, `direction`, `peer`, +`value`. -/ +def pattern (M : Menu F l s ℓ) (unpack : Y.obj → (code a e l s ℓ).obj) + (r : (record d e ℓ Y).obj) : Pattern F d 0 e where + width _ t := M.length (r.2.1 t).1 + direction _ t := (r.2.1 t).2.1 + peer _ t := if (r.2.1 t).2.2.1 then some ((r.2.1 t).2.2.2.1, 0, (r.2.1 t).2.2.2.2) else none + value _ x := if r.1 then M.decode (fun t => M.length (r.2.1 t).1) (unpack r.2.2) (fun i + => x i.1 i.2) else 1 + +/-- Uses `⟨m, d, h, 0, e, (record d e ℓ Y).width, pattern M unpack ∘ (record d e ℓ +Y).serial.symm⟩` as the representation. -/ +abbrev scheme (m d h e : ℕ) (Y : Format) (M : Menu F l s ℓ) + (unpack : Y.obj → (code a e l s ℓ).obj) : Scheme F := + ⟨m, d, h, 0, e, (record d e ℓ Y).width, pattern M unpack ∘ (record d e ℓ Y).serial.symm⟩ + +/-- Evaluates `(nav v, (record d e ℓ Y).serial ∘ R v)` at the input `v`. -/ +def write (M : Menu F l s ℓ) (unpack : Y.obj → (code a e l s ℓ).obj) + (nav : B m → B d → B m) (R : B m → B h → (record d e ℓ Y).obj) : + (scheme m d h e Y M unpack).format.obj := + fun v => (nav v, (record d e ℓ Y).serial ∘ R v) + +theorem read_write (M : Menu F l s ℓ) (unpack : Y.obj → (code a e l s ℓ).obj) + (nav : B m → B d → B m) (R : B m → B h → (record d e ℓ Y).obj) + (v : (scheme m d h e Y M unpack).Vtx) : + (scheme m d h e Y M unpack).pattern (write M unpack nav R) v = pattern M unpack (R v.1 v.2.1) := + congrArg (pattern M unpack) ((record d e ℓ Y).serial.symm_apply_apply (R v.1 v.2.1)) + +theorem table_eq (M : Menu F l s ℓ) (unpack : Y.obj → (code a e l s ℓ).obj) + (out : (scheme m d h e Y M unpack).format.obj) + (v : (scheme m d h e Y M unpack).Vtx) (r : (record d e ℓ Y).obj) + (hr : (scheme m d h e Y M unpack).pattern out v = pattern M unpack r) + (x : (scheme m d h e Y M unpack).LocalPin out v → Bool) : + (scheme m d h e Y M unpack).table out v x = if r.1 then + M.decode (fun t => (scheme m d h e Y M unpack).width out (v, t)) (unpack r.2.2) x else 1 := by + have eq (P : Pattern F d 0 e) (he : P = pattern M unpack r) (j : B 0) + (x : Positions (P.width j) → Bool) : + P.value j (fun s i => x ⟨s, i⟩) = + if r.1 then M.decode (P.width j) (unpack r.2.2) x else 1 := by + subst P + rfl + exact eq _ hr _ x + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Post +end + +/- +# Putting the long part of an occurrence label at the high end + +A fixed bijection translates between the physical serialization and +the ordering used to measure label lengths. The same ordering is +used when an old station becomes an atom at the next stage. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +open Coloring + +namespace Dense + +open scoped Classical in +/-- Computes the concat by the application `finProdFinEquiv.trans (finCongr (pow_add 2 h +l).symm)`. -/ +def concat (h l : ℕ) : B h × B l ≃ B (h + l) := + finProdFinEquiv.trans (finCongr (pow_add 2 h l).symm) + +open scoped Classical in +theorem concat_length {h l : ℕ} (a : B h) (b : B l) : + used (concat h l (a, b)).val ≤ used a.val + l := by + rw [used_le, pow_add 2 (used a.val) l] + change b.val + 2 ^ l * a.val < _ + calc + _ < 2 ^ l + 2 ^ l * a.val := Nat.add_lt_add_right b.isLt _ + _ = (a.val + 1) * 2 ^ l := by rw [add_mul, one_mul, mul_comm a.val, add_comm] + _ ≤ _ := Nat.mul_le_mul_right _ (used_le.mp le_rfl) + +end Dense + +namespace Post + +open scoped Classical in +/-- Computes the header fmt by the application `Format.pair .bit (.vec e (field d e n))`. -/ +abbrev headerFmt (d e n : ℕ) := Format.pair .bit (.vec e (field d e n)) +open scoped Classical in +/-- The value specified by `(record d e n (.addr l)).width`. -/ +abbrev width (d e n l : ℕ) := (record d e n (.addr l)).width + +open scoped Classical in +theorem width_eq (d e n l : ℕ) : l + (headerFmt d e n).width = width d e n l := by + simp only [width, headerFmt, record, Format.width_pair, Format.width_addr] + omega + +open scoped Classical in +/-- Reindexes `B (width d e n l)` and `B (width d e n l)` by an equivalence. -/ +def order (d e n l : ℕ) : B (width d e n l) ≃ B (width d e n l) := + (record d e n (.addr l)).serial.symm |>.trans ((Equiv.prodAssoc _ _ _).symm.trans + ((Equiv.prodComm _ _).trans (((Equiv.refl _).prodCongr (headerFmt d e n).serial).trans + ((Dense.concat _ _).trans (finCongr (congrArg (2^·) (width_eq d e n l))))))) + +open scoped Classical in +theorem order_length {d e n l : ℕ} (c : (record d e n (.addr l)).obj) : + Dense.used (order d e n l ((record d e n (.addr l)).serial c)).val ≤ + Dense.used c.2.2.val + (headerFmt d e n).width := by + simp only [order, Equiv.trans_apply, Equiv.symm_apply_apply] + exact Dense.concat_length c.2.2 ((headerFmt d e n).serial (c.1, c.2.1)) + +end Post + +namespace Kind +variable {F : Type} [Field F] (S : Scheme F) (P : Packing.Gadget F) (c : ℕ) + +open scoped Classical in +/-- Indexes the small by the coordinates of `B S.k ⊕ Role P ⊕ B c`. -/ +abbrev Small := B S.k ⊕ Role P ⊕ B c + +open scoped Classical in +/-- Computes the width by the application `Dense.used (Fintype.card (Small S P c))`. -/ +def width := Dense.used (Fintype.card (Small S P c)) + +open scoped Classical in +/-- Embeds `Small S P c` into `B (width S P c)`. -/ +def tags : Small S P c ↪ B (width S P c) := + (Fintype.equivFin _).toEmbedding.trans (Fin.castLEEmb (le_of_lt (Dense.used_le.mp le_rfl))) + +variable (o : B S.ℓ ≃ B S.ℓ) + +open scoped Classical in +/-- In the case `.inl x`, this construction gives `(o x.1, .inl x.2)`. -/ +def parts : Kind S P c → B S.ℓ × Small S P c + | .inl x => (o x.1, .inl x.2) + | .inr x => (0, .inr x) + +open scoped Classical in +theorem parts_inj : Function.Injective (parts S P c o) := by + rintro (⟨x, i⟩ | x) (⟨y, j⟩ | y) h <;> + simp only [parts, Prod.mk.injEq, Sum.inl.injEq, Sum.inr.injEq, Equiv.apply_eq_iff_eq, + reduceCtorEq, + true_and, and_false] at h ⊢ <;> exact h + +open scoped Classical in +/-- Embeds `Kind S P c` into `B (S.ℓ + width S P c)`. -/ +def names : Kind S P c ↪ B (S.ℓ + width S P c) := + (⟨parts S P c o, parts_inj S P c o⟩ : Kind S P c ↪ _).trans + (((Function.Embedding.refl _).prodMap (tags S P c)).trans (Dense.concat _ _).toEmbedding) + +open scoped Classical in +/-- Computes the carried by the application `Dense.used (parts S P c o j).1.val`. -/ +def carried (j : Kind S P c) := Dense.used (parts S P c o j).1.val + +open scoped Classical in +theorem names_length (j : Kind S P c) : + Dense.used (names S P c o j).val ≤ carried S P c o j + width S P c := + Dense.concat_length _ _ + +open scoped Classical in +@[simp] theorem carried_old (x : B S.ℓ) (i : B S.k) : + carried S P c o (.inl (x, i)) = Dense.used (o x).val := rfl + +open scoped Classical in +@[simp] theorem carried_new (i : Role P ⊕ B c) : carried S P c o (.inr i) = 0 := + Dense.used_zero + +end Kind + +namespace Post + +variable {F A T : Type} [Field F] [Fintype A] + {m e d s n c : ℕ} (S : Scheme F) (P : Packing.Gadget F) (o : B S.ℓ ≃ B S.ℓ) + (p : Packed A T e (S.ℓ + Kind.width S P c) s n) + (g : A ↪ B m) (f : T ↪ B e) + +open scoped Classical in +/-- Header cost includes role names, widths and pointers. It depends +on the previous label bound only through its logarithm. -/ +def bookkeeping (m e s n old role : ℕ) := + Dense.overhead m e (old + role) s n + 2 ^ m * role + +open scoped Classical in +theorem packed_length (t : A → Kind S P c) (ht : p.tag = Kind.names S P c o ∘ t) : + Dense.used (Dense.index (p.encode g f)) ≤ + bookkeeping m e s n S.ℓ (Kind.width S P c) + ∑ i, Kind.carried S P c o (t i) := by + refine (p.index_length g f).trans ?_ + have ha : Fintype.card A ≤ 2 ^ m := by simpa using Fintype.card_le_of_injective g g.injective + have h : (∑ i, Dense.used (p.tag i).val) ≤ ∑ i, (Kind.carried S P c o (t i) + Kind.width S P c) + := by + rw [ht] + exact Finset.sum_le_sum fun i _ => Kind.names_length S P c o (t i) + simp only [Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, Nat.nsmul_eq_mul] at h + have h' := Nat.mul_le_mul_right (Kind.width S P c) ha + unfold bookkeeping + omega + +open scoped Classical in +/-- The receipt need only retain the effective lengths of its +ancestors. In particular the maximum old length is not multiplied +by the number of candidate ports or atoms. -/ +theorem stored_length {l bound : ℕ} (t : A → Kind S P c) + (ht : p.tag = Kind.names S P c o ∘ t) + (hb : (∑ i, Kind.carried S P c o (t i)) ≤ bound) + (hl : bookkeeping m e s n S.ℓ (Kind.width S P c) + bound ≤ l) + (v : (record d e n (.addr l)).obj) (hv : v.2.2 = Dense.encode l (p.encode g f)) : + Dense.unpack l v.2.2 = p.encode g f ∧ + Dense.used (order d e n l ((record d e n (.addr l)).serial v)).val ≤ + (headerFmt d e n).width + bookkeeping m e s n S.ℓ (Kind.width S P c) + bound := by + have h := (packed_length S P o p g f t ht).trans (Nat.add_le_add_left hb _) + refine ⟨by rw [hv]; exact Dense.unpack_encode (h.trans hl), ?_⟩ + have he := order_length v + rw [hv, Dense.encode_val (h.trans hl)] at he + omega + +end Post +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +end + +/- # Decoding the emitted span records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Allocation +open Coloring Packing + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z a : ℕ} + {P : Gadget F} {G : HostNet F L h (P.b * z)} + {Δ D k : ℕ} {B' : ℝ} {g : Grouping G.N G.C Δ D k B' G.load} + {m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix} {i : g.Choice m P} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r G.diagram} + {q : G.Projection Δ D a} + {m' d h' e ℓ n l s : ℕ} {Y : Format} {M : Menu F l s ℓ} + {u : Y.obj → (code n e l s ℓ).obj} + +local notation "U" => Post.scheme m' d h' e Y M u +local notation "Face'" => Face g m P i p +local notation "Host" => endHost (p := p) (q := q) + +variable (A : Allocation P G g m i p q (Post.scheme m' d h' e Y M u)) + +open scoped Classical in +/-- The header used in the `Allocation` construction. -/ +def header (A : Allocation P G g m i p q U) (size : Face' → B ℓ) : Face' → (Post.field d e ℓ).obj + | .inl j => (size (.inl j), S.direction r (p.vertex j.val.1, j.val.2), false, 0, 0) + | .inr (b, t) => + (size (.inr (b, t)), t, true, A.index (Host b t) (Host b (!t)), A.unitSeat b (!t)) + +variable {nav : B m' → B d → B m'} {R : B m' → B h' → (Post.record d e ℓ Y).obj} + {size : Face g m P i p → B ℓ} + +local notation "out" => Post.write M u nav R + +open scoped Classical in +/-- The active record fields are indexed only by the local seats. +Unused argument seats have zero length and no peer. -/ +structure Emitted (A : Allocation P G g m i p q U) (size : Face' → B ℓ) (nav : B m' → B d → B m') + (R : B m' → B h' → (Post.record d e ℓ Y).obj) : Prop where + zero : M.length 0 = 0 + length : ∀ j, M.length (size j) = visibleWidth g m P i p z j + active : ∀ v, (R (A.vertex v).1 (A.vertex v).2.1).1 = true + vacant : ∀ v : (U).Vtx, v ∉ Set.range A.vertex → (R v.1 v.2.1).1 = false + used : ∀ j : Face', let t : (U).Span := A.span j + (R t.1.1 t.1.2.1).2.1 t.2 = A.header size j + idle : ∀ t : (U).Span, t ∉ Set.range A.span → (R t.1.1 t.1.2.1).2.1 t.2 = Post.unused + hop : ∀ (b : g.Survivors m P i) t, let v := Host b t + let w := Host b (!t) + nav (A.host v) (A.index v w) = A.host w + +namespace Emitted +variable {A} (H : A.Emitted size nav R) + +include H in +open scoped Classical in +theorem lengths : A.Lengths out where + used j := by + rw [Scheme.width, Post.read_write] + change M.length ((R _ _).2.1 _).1 = _ + rw [H.used j] + rcases j with j|⟨b, t⟩ <;> exact H.length _ + idle t ht := by + rw [Scheme.width, Post.read_write] + change M.length ((R _ _).2.1 _).1 = _ + rw [H.idle t ht] + exact H.zero + +include H in +open scoped Classical in +theorem exposed_direction (j : p.BorderSpan) : + (U).direction out (A.span (.inl j)) = S.direction r (p.vertex j.val.1, j.val.2) := by + rw [Scheme.direction, Post.read_write] + change ((R _ _).2.1 _).2.1 = _ + rw [H.used] + rfl + +open scoped Classical in +theorem agrees (hz : 0 < z) + (hs : ∀ v t, M.decode (fun a => (U).width out (A.vertex v, a)) + (u (R (A.vertex v).1 (A.vertex v).2.1).2.2) t = + Transcript.sample ((g.contract m P G.units hz i).table v) (t ∘ A.pin H.lengths hz v)) : + A.Agrees H.lengths hz where + sample v t := by + rw [Post.table_eq M u out _ _ (Post.read_write _ _ _ _ _), H.active] + exact hs v t + vacant v hv t := by + rw [Post.table_eq M u out _ _ (Post.read_write _ _ _ _ _), H.vacant v hv] + rfl + outside j := by + rw [Scheme.peer, Post.read_write] + simp only [Post.pattern, H.used, header, Bool.false_eq_true, ↓reduceIte, Option.map_none] + idle t ht := by + rw [Scheme.peer, Post.read_write] + simp only [Post.pattern, H.idle t ht, Post.unused, Bool.false_eq_true, ↓reduceIte, + Option.map_none] + dir b t := by + rw [Scheme.direction, Post.read_write] + simp only [Post.pattern, H.used, header] + link b t := by + dsimp only + rw [Post.read_write] + simp only [Post.pattern, H.used, header, ↓reduceIte] + nav b t := H.hop b t + +open scoped Classical in +/-- Every original exterior offset retains its span length and orientation. -/ +theorem boundary (hz : 0 < z) (hA : A.Agrees H.lengths hz) (t : slots x ⊕ slots y) : + let p' := A.presentation H.lengths hz hA + let b := p.toSeating.ends (boundaryEnd _ t) + let b' := p'.toSeating.ends (boundaryEnd _ t) + (U).width out b'.1 = S.width r b.1 ∧ (U).direction out b'.1 = S.direction r b.1 ∧ + b'.2.val = b.2.val := by + obtain ⟨j, rfl⟩ := p.exteriorBits.surjective t + dsimp only [presentation] + rw [p.border_pin, A.exposed_pin] + exact ⟨H.lengths.used (.inl j.1), H.exposed_direction j.1, rfl⟩ + +open scoped Classical in +theorem floor (hz : 0 < z) (hA : A.Agrees H.lengths hz) {w : ℕ} + (hw : ∀ b, w ≤ p.borderWidth b) : + ∀ b, w ≤ (A.presentation H.lengths hz hA).borderWidth b := by + let p' := A.presentation H.lengths hz hA + intro b + let j : p'.BorderBit := ⟨b, ⟨0, b.property.1⟩⟩ + obtain ⟨t, ht⟩ := p.exteriorBits.surjective (p'.exteriorBits j) + have h := (H.boundary hz hA (p'.exteriorBits j)).1 + rw [p'.border_pin, ← ht, p.border_pin] at h + exact (hw _).trans_eq h.symm + +end Emitted +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Allocation +end + +/- # Constructing the visible span records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Allocation +open Coloring Packing + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z a : ℕ} + {P : Gadget F} {G : HostNet F L h (P.b * z)} + {Δ D k : ℕ} {B' : ℝ} {g : Grouping G.N G.C Δ D k B' G.load} + {m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix} {i : g.Choice m P} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r G.diagram} + {q : G.Projection Δ D a} + {m' d h' e ℓ n l s : ℕ} {Y : Format} {M : Menu F l s ℓ} + {u : Y.obj → (code n e l s ℓ).obj} + +local notation "U" => Post.scheme m' d h' e Y M u +local notation "Face'" => Face g m P i p +local notation "Host" => endHost (p := p) (q := q) + +variable (A : Allocation P G g m i p q (Post.scheme m' d h' e Y M u)) + +variable (size : Face g m P i p → B ℓ) (data : Site G.V h → Y.obj) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def fields (v : Site G.V h) : B e → (Post.field d e ℓ).obj := + Function.extend (A.seat v) (fun j => A.header size j.val) (fun _ => Post.unused) + +open scoped Classical in +/-- The value specified by `(true, A.fields size v, data v)`. -/ +def localRecord (v : Site G.V h) : (Post.record d e ℓ Y).obj := + (true, A.fields size v, data v) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def records (x : B m') (y : B h') : (Post.record d e ℓ Y).obj := + Post.extendRecord A.vertex (A.localRecord size data) Post.vacant x y + +open scoped Classical in +theorem record_at (v : Site G.V h) : + A.records size data (A.vertex v).1 (A.vertex v).2.1 = A.localRecord size data v := + Post.extendRecord_at A.vertex (A.localRecord size data) _ v + +open scoped Classical in +theorem record_vacant (v : (U).Vtx) (hv : v ∉ Set.range A.vertex) : + A.records size data v.1 v.2.1 = Post.vacant := + Post.extendRecord_vacant A.vertex (A.localRecord size data) _ v hv + +variable (nav : B m' → B d → B m') + +open scoped Classical in +theorem emitted (h₀ : M.length 0 = 0) (hsize : ∀ j, M.length (size j) = visibleWidth g m P i p z j) + (hop : ∀ (b : g.Survivors m P i) t, nav (A.host (Host b t)) + (A.index (Host b t) (Host b (!t))) = A.host (Host b (!t))) : + A.Emitted size nav (A.records size data) where + zero := h₀ + length := hsize + active v := by rw [record_at]; rfl + vacant v hv := by rw [record_vacant _ _ _ _ hv]; rfl + used j := by + let v := whereAt g m P G.units i p j + change (A.records size data (A.vertex v).1 (A.vertex v).2.1).2.1 (A.slot j) = _ + rw [record_at] + let e : Visible g m P G.units i p v := ⟨j, rfl⟩ + change A.fields size v (A.seat v e) = A.header size e.val + rw [fields, (A.seat v).injective.extend_apply] + idle t ht := by + rcases t with ⟨v, j⟩ + by_cases hv : v ∈ Set.range A.vertex + · obtain ⟨w, rfl⟩ := hv + rw [record_at] + have hn : j ∉ Set.range (A.seat w) := by + rintro ⟨e, rfl⟩ + exact ht ⟨e.val, Prod.ext (congrArg A.vertex e.property) (A.slot_eq w e)⟩ + change A.fields size w j = _ + rw [fields, Function.extend_apply' _ _ _ hn] + · rw [record_vacant _ _ _ _ hv] + rfl + hop := hop + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Allocation +end + +/- # A finite length table with zero at the reserved address -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History + +open Coloring + +/-- The address width for a set with space for three additional lengths. -/ +abbrev lengthBits (lengths : Finset ℕ) := Nat.clog 2 (lengths.card + 3) + +open scoped Classical in +/-- Encode a bounded finite set of lengths with a decoder that sends the reserved +address to zero and recovers every length in the set. -/ +theorem length_dictionary (lengths : Finset ℕ) {d : ℕ} + (zero_mem : 0 ∈ lengths) (capacity : lengths.card ≤ 2 ^ d) : + ∃ table : (ℕ → B d) × (B d → ℕ), + table.2 0 = 0 ∧ ∀ n ∈ lengths, table.2 (table.1 n) = n := by + obtain ⟨embed⟩ : Nonempty (↥lengths ↪ B d) := + Function.Embedding.nonempty_of_card_le (by + simpa only [Fintype.card_coe, Fintype.card_fin] using capacity) + let zero : ↥lengths := ⟨0, zero_mem⟩ + let address := embed.trans (Equiv.swap (embed zero) 0).toEmbedding + have reserved : address zero = 0 := Equiv.swap_apply_left _ _ + let decode := Function.extend address Subtype.val (fun _ => 0) + let encode (n : ℕ) := if h : n ∈ lengths then address ⟨n, h⟩ else 0 + refine ⟨(encode, decode), ?_, fun n hn => ?_⟩ + · change decode 0 = 0 + rw [← reserved] + exact address.injective.extend_apply Subtype.val (fun _ => 0) zero + · simp only [encode, dite_eq_left hn, decode, address.injective.extend_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Radius.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Radius.lean new file mode 100644 index 0000000000..7a8a500eb4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Radius.lean @@ -0,0 +1,739 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Checks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix + +/-! # Bounding the number of hidden spans by earlier incidences -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +open Finset Packing + +open scoped Classical in +private theorem loops {E V : Type} [Fintype E] (f : E → V × V) (v : V) : + Fintype.card {e // f e = (v, v)} ≤ degree f v := by + rw [Fintype.card_subtype, card_eq_sum_ones, sum_filter, degree_sum] + apply sum_le_sum + intro e _ + by_cases he : f e = (v, v) <;> simp [he, arityCost] + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z : ℕ} + (P : Gadget F) (G : HostNet F L h (P.b * z)) + {Δ D k : ℕ} {B : ℝ} (g : Grouping G.N G.C Δ D k B G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (i : g.Choice m P) + (v : Site G.V h) + +open scoped Classical in +private theorem degree_ends : + degree (ends g m P i) v = 2 * degree (g.oldContact m (g.layout m P i)) v + + degree (g.contact (b := P.b) (f := g.profile m i) m (g.layout m P i)) v := by + let f := g.oldContact m (g.layout m P i) + rw [degree_sum, degree_sum, degree_sum, Fintype.sum_sum_type, Fintype.sum_sum_type, + ← add_assoc, ← sum_add_distrib, mul_sum] + congr 1 + apply sum_congr rfl + intro j _ + change arityCost v ((f j).1, (f j).1) + arityCost v ((f j).2, (f j).2) = 2 * arityCost v (f j) + simp only [arityCost] + omega + +open scoped Classical in +theorem hidden_bound (hB : 0 ≤ B) : + Fintype.card (Hidden g m P i v) * (z : ℝ) ≤ 10 * (near G.C Δ v).card * ((2 : ℝ) ^ k * B) := by + let col := g.layout m P i + let n := degree (g.oldContact m col) v + have hi : Fintype.card (Hidden g m P i v) ≤ 10 * P.b * n := calc + _ ≤ degree (ends g m P i) v := by convert! loops (ends g m P i) v using 2 + _ = _ := degree_ends P G g m i v + _ ≤ 2 * n + 8 * P.b * n := Nat.add_le_add_left + (g.contact_degree m P.b (g.profile m i) (fun e => P.cost _ (i e).2.property) col v) _ + _ ≤ _ := by + have ht := Nat.le_mul_of_pos_left n P.pos + rw [mul_assoc 8, mul_assoc 10] + omega + let f (p : G.V × Cell h) := g.route m col p.1 p.2 + have hn : (n : ℝ) * (P.b * z : ℕ) ≤ (near G.C Δ v).card * ((2 : ℝ) ^ k * B) := by + refine le_trans ?_ (g.route_load m G.cs G.sub G.edge G.load_nonneg hB col v) + change degree (fun e => Prod.map f f (G.pair e)) v * ((P.b * z : ℕ) : ℝ) ≤ _ + rw [degree_map, Nat.cast_sum, sum_mul] + apply sum_le_sum + intro p _ + by_cases he : g.route m col p.1 p.2 = v + · simp only [f, ite_eq_left he] + exact (le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load _ _) + · simp [f, he] + calc + _ ≤ ((10 * P.b * n : ℕ) : ℝ) * z := + mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hi) (Nat.cast_nonneg _) + _ = 10 * ((n : ℝ) * (P.b * z : ℕ)) := by push_cast; ring + _ ≤ _ := by rw [mul_assoc]; exact mul_le_mul_of_nonneg_left hn (by norm_num) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround +end + +/- +# Packing the active factors of a contracted station + +Each argument names a whole visible or hidden span. Empty and +unused arguments need no pointer. The arbitrary enumerations of +atoms and hidden spans do not affect the decoded value. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +open Coloring Packing + +open scoped Classical in +theorem menu_read {F L : Type} [Field F] {s l d : ℕ} (a : L → Atom F) + (names : L ↪ B l) (index : ∀ i, (a i).Span ↪ B s) (len : B d → ℕ) + (i : L) (x : Positions ((menu a names index len).width (names i)) → Bool) : + (menu a names index len).value (names i) x = (a i).weight + (fun j t => x ⟨index i j, t.cast (menu_width a names index len i j).symm⟩) := by + let u j k := if h : k < (menu a names index len).width (names i) j then x ⟨j, ⟨k, h⟩⟩ else false + have h := menu_value a names index len i u + have he : (fun j => u j.1 j.2.val) = x := by + funext j + simp [u, j.2.isLt] + rw [he] at h + refine h.trans (congrArg _ (funext fun j => funext fun t => ?_)) + have hu : t.val < (menu a names index len).width (names i) (index i j) := by + rw [menu_width] + exact t.isLt + exact dite_eq_left hu + +namespace Subround + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z : ℕ} + (P : Gadget F) (G : HostNet F L h (P.b * z)) + {Δ D k : ℕ} {B' : ℝ} (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (i : g.Choice m P) + {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G.diagram) (hz : 0 < z) + (v : Site G.V h) + +open scoped Classical in +/-- The value specified by `↥(G.receipts g m (g.layout m P i) v)`. -/ +abbrev Receipt := ↥(G.receipts g m (g.layout m P i) v) + +open scoped Classical in +/-- The data for the bundle construction, including `label`, `arg`. -/ +structure Bundle (c : ℕ) where + /-- The label at each coordinate of type `Receipt P G g m i v → Kind S P c`. -/ + label : Receipt P G g m i v → Kind S P c + /-- The `Bundle` component of type `AtomMap g m P G.units hz i p v (kind S P z hz (label t)) + t.val`. -/ + arg (t : Receipt P G g m i v) : + AtomMap g m P G.units hz i p v (kind S P z hz (label t)) t.val + +variable {P G g m i p hz v} +local notation "J" => Receipt P G g m i v +local notation "H" => Hidden g m P i v +local notation "V" => Visible g m P G.units i p v +local notation "W" => PortMap.Port g m P G.units i p v +local notation "Q" => cluster g m P G.units hz i + +open scoped Classical in +theorem anchor_eq (t : G.Atom g m) : G.anchor g m (g.layout m P i) t = (Q).owner t := by + rcases t with a | (b | c) <;> rfl + +open scoped Classical in +/-- Embeds `J` into `{u // (cluster g m P G.units hz i).owner u = v} where toFun t`. -/ +def includeAtom (hz : 0 < z) : J ↪ {u // (cluster g m P G.units hz i).owner u = v} where + toFun t := ⟨t.val, (anchor_eq _).symm.trans (Finset.mem_filter.mp t.2).2.2⟩ + inj' _ _ h := Subtype.ext (Subtype.mk.inj h) + +open scoped Classical in +theorem idle_atoms + (neutral : ∀ u, G.diagram.arity u = 0 → ∀ x, Transcript.sample (G.diagram.table u) x = 1) + (t : {u // (Q).owner u = v}) (ht : t ∉ Set.range (includeAtom hz)) (w : Bit Q → Bool) : + factor Q t.val w = 1 := by + have hn : ¬ G.live g m t.val := by + intro h + have he : t.val ∈ G.receipts g m (g.layout m P i) v := + Finset.mem_filter.mpr ⟨Finset.mem_univ _, h, (anchor_eq _).trans t.property⟩ + exact ht ⟨⟨_, he⟩, rfl⟩ + rcases t with ⟨u | (e | r), _⟩ + · rw [old_factor] + exact neutral u (Nat.eq_zero_of_not_pos hn) _ + · exact (hn trivial).elim + · exact unpaired_idle g m P G.units hz i w r (fun e h => hn ⟨e, .inl h⟩) (fun e h => hn ⟨e, + .inr h⟩) + +namespace Bundle +variable {c e l s d : ℕ} (b : Bundle P G g m i p hz v c) + (names : Kind S P c ↪ B l) (index : ∀ a : Kind S P c, (kind S P z hz a).Span ↪ B s) + (seat : Visible g m P G.units i p v ↪ B e) (size : Hidden g m P i v → B d) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def ptr (t : J) : B s → B e ⊕ H := + Function.extend (index (b.label t)) + (fun j => if h : 0 < (kind S P z hz (b.label t)).width j then + ((b.arg t).slot j h).map seat id else .inl 0) (fun _ => .inl 0) + +open scoped Classical in +/-- Builds `Packed J H e l s d where tag t` with the specified `tag`, `width`, `ptr`. -/ +def packed : Packed J H e l s d where + tag t := names (b.label t) + width := size + ptr t j := (b.ptr index seat t j, 0) + +open scoped Classical in +theorem ptr_at (t : J) (j : (kind S P z hz (b.label t)).Span) (h : 0 + < (kind S P z hz (b.label t)).width j) : + b.ptr index seat t (index (b.label t) j) = ((b.arg t).slot j h).map seat id := by + rw [ptr, (index _).injective.extend_apply, dite_eq_left h] + +variable (len : B d → ℕ) (w : B e → ℕ) (h₀ : len 0 = 0) + (hi : ∀ q : Hidden g m P i v, len (size q) = segmentWidth g m P i z q.val) + (ho : ∀ q : Visible g m P G.units i p v, w (seat q) = visibleWidth g m P i p z q.val) +local notation "pack" => b.packed names index seat size +local notation "M" => menu (kind S P z hz) names index len + +include hi ho in +open scoped Classical in +theorem capacity (q : W) : + (pack).cap M w (q.map seat id, 0) = PortMap.width g m P G.units i p v q := by + cases q with + | inl q => exact ho q + | inr q => exact hi q + +include h₀ hi ho in +open scoped Classical in +theorem fits : (pack).Fits M w := by + intro t j a + have ha := a.isLt + change a.val < (M).width (names (b.label t)) j at ha + have hj : j ∈ Set.range (index (b.label t)) := by + by_contra h + have h' := menu_empty (kind S P z hz) names index len (b.label t) j h + omega + obtain ⟨q, rfl⟩ := hj + have hq := menu_width (kind S P z hz) names index len (b.label t) q + have hp : 0 < (kind S P z hz (b.label t)).width q := by omega + change len 0 + a.val < (pack).cap M w (b.ptr index seat t _, 0) + rw [h₀, zero_add, ptr_at _ _ _ _ _ hp, capacity _ _ _ _ _ _ _ hi ho, (b.arg t).size] + exact ha.trans_eq hq + +end Bundle +end Subround +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History +end + +/- +# Accounting for old histories + +There is at most one old station at an occurrence. Each next +contraction receives a disjoint set of the old labels, even if +many of its local pointers refer to the same label. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +open Finset + +variable {T F : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} {h u : ℕ} + (G : HostNet F L h u) {Δ D k : ℕ} {B : ℝ} (g : Grouping G.N G.C Δ D k B G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) + (col : Bool) (w : Site G.V h) + +open scoped Classical in +theorem receipts_live (a : G.Atom g m) (h : a ∈ G.receipts g m col w) : G.live g m a := + (mem_filter.mp h).2.1 + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def previous (cost : G.V × Cell h → ℝ) : G.Atom g m → ℝ := + Sum.elim (cost ∘ G.units.place) (fun _ => 0) + +open scoped Classical in +theorem carried_size (one : Function.Injective G.units.place) + (cost : G.V × Cell h → ℝ) (hc : ∀ t, 0 ≤ cost t) + (sizes : ↥(G.receipts g m col w) → ℕ) + (hsizes : ∀ i : ↥(G.receipts g m col w), (sizes i : ℝ) ≤ G.previous g m cost i) : + (∑ i, sizes i : ℕ) ≤ push (fun t => g.route m col t.1 t.2) cost w := by + let f (t : G.V × Cell h) := if g.route m col t.1 t.2 = w then cost t else 0 + have hf (t) : 0 ≤ f t := by unfold f; split <;> first | exact hc t | exact le_rfl + have he (i : ↥(G.receipts g m col w)) : G.previous g m cost i = G.previous g m f i := by + obtain ⟨a, h⟩ := i + have hw := (mem_filter.mp h).2.2 + cases a with + | inl v => + change cost _ = if _ then cost _ else 0 + exact (ite_eq_left hw).symm + | inr q => rfl + rw [Nat.cast_sum] + calc + _ ≤ ∑ i : ↥(G.receipts g m col w), G.previous g m f i := + sum_le_sum fun i _ => (hsizes i).trans_eq (he i) + _ ≤ ∑ i, G.previous g m f i := by + rw [sum_coe_sort] + apply sum_le_sum_of_subset_of_nonneg (subset_univ _) + rintro (v|j) _ _ + · exact hf _ + · exact le_rfl + _ = ∑ i, f (G.units.place i) := by + rw [Fintype.sum_sum_type] + simp only [previous, Sum.elim_inl, Sum.elim_inr, Function.comp_apply, sum_const_zero, + add_zero] + _ ≤ _ := by + let e : G.diagram.V ↪ G.V × Cell h := ⟨_, one⟩ + have hh : push (fun t => g.route m col t.1 t.2) cost w = ∑ t, f t := by + apply sum_congr rfl + intro i _ + unfold f; congr + rw [hh] + change (∑ i, f (e i)) ≤ ∑ t, f t + rw [← sum_map univ e] + exact sum_le_sum_of_subset_of_nonneg (subset_univ _) (fun i _ _ => hf i) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- # Correctness of the packed local history -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Bundle +open Coloring Packing + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z : ℕ} + {P : Gadget F} {G : HostNet F L h (P.b * z)} + {Δ D k : ℕ} {B' : ℝ} {g : Grouping G.N G.C Δ D k B' G.load} + {m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix} {i : g.Choice m P} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r G.diagram} {hz : 0 < z} + {v : Site G.V h} + {c e l s d : ℕ} (b : Bundle P G g m i p hz v c) + (names : Kind S P c ↪ B l) (index : ∀ a : Kind S P c, (kind S P z hz a).Span ↪ B s) + (seat : Visible g m P G.units i p v ↪ B e) (size : Hidden g m P i v → B d) + (len : B d → ℕ) (w : B e → ℕ) (h₀ : len 0 = 0) + (hi : ∀ q : Hidden g m P i v, len (size q) = segmentWidth g m P i z q.val) + (ho : ∀ q : Visible g m P G.units i p v, w (seat q) = visibleWidth g m P i p z q.val) + (p' : (g.contract m P G.units hz i).Port v ≃ Positions w) + (hp : ∀ j : Visible g m P G.units i p v, ∀ t : Fin (visibleWidth g m P i p z j.val), + p' (visibleBits g m P G.units hz i p v ⟨j, t⟩) = ⟨seat j, t.cast (ho j).symm⟩) + +local notation "pack" => b.packed names index seat size +local notation "M" => menu (kind S P z hz) names index len +local notation "Q" => cluster g m P G.units hz i + +local notation "N" => g.contract m P G.units hz i + +open scoped Classical in +private def inner : (pack).Inner M ≃ (Q).hidden v := + (Equiv.sigmaCongrRight (fun j => finCongr (hi j))).trans (hiddenBits g m P G.units hz i v) + +include hp in +open scoped Classical in +private theorem resolve (q : PortMap.Port g m P G.units i p v) + (t : Fin (PortMap.width g m P G.units i p v q)) + (r : (B e ⊕ Hidden g m P i v) × B d) (he : r = (q.map seat id, 0)) + (a : Fin ((pack).cap M w r)) (ha : a.val = t.val) : + Sum.map (fun u => named N v (p'.symm u)) + (fun j => (⟨v, b.inner names index seat size len hi j⟩ : Σ u, + (Q).hidden u)) ((pack).resolve M w r a) = + PortMap.bit g m P G.units i p v hz q t := by + subst r + cases q with + | inl q => + have e : p' (visibleBits g m P G.units hz i p v ⟨q, t⟩) = ⟨seat q, a⟩ := + (hp q t).trans (congrArg (fun s : Fin (w (seat q)) => (⟨seat q, s⟩ + : Positions w)) (Fin.ext ha.symm)) + change Sum.inl (named _ _ (p'.symm ⟨seat q, a⟩)) = _ + rw [← e, Equiv.symm_apply_apply, visible_pin] + rfl + | inr q => + have eq : (finCongr (hi q)) a = t := Fin.ext ha + change Sum.inr (⟨v, hiddenBits g m P G.units hz i v ⟨q, (finCongr (hi q)) a⟩⟩ : Σ u, + (Q).hidden u) = _ + rw [eq] + rfl + +variable (neutral : ∀ u, G.diagram.arity u = 0 → ∀ x, Transcript.sample (G.diagram.table u) x = 1) + +include hp h₀ hi ho neutral in +open scoped Classical in +theorem decode {t : ℕ} (atoms : Receipt P G g m i v ↪ B t) (hidden : Hidden g m P i v ↪ B e) + (x : Positions w → Bool) : + (M).decode w ((pack).encode atoms hidden) x = + Transcript.sample ((g.contract m P G.units hz i).table v) (x ∘ p') := by + have ht := b.fits names index seat size len w h₀ hi ho + rw [Packed.decode _ _ _ _ _ h₀ ht] + let _ : Fintype ((before g m P G.units hz i).Between (Sum.elim (g.assign m P G.units i) (g.locate + m (g.layout m P i)))) := (N).fe + refine Traces.correct (C := Q) (out := p') ?_ x + refine ⟨includeAtom hz, b.inner names index seat size len hi, ?_, fun t ht w + => idle_atoms neutral t ht w⟩ + intro j y + let Y := (pack).history M w ht + let e := b.inner names index seat size len hi + let k := y ∘ embed Q Y v p' e ∘ Y.read j + change (M).value (names (b.label j)) k = _ + refine (menu_read (kind S P z hz) names index len (b.label j) k).trans ?_ + refine Eq.trans ?_ ((b.arg j).value y) + refine congrArg _ (funext fun u => funext fun t => ?_) + let q := (b.arg j).slot u (Nat.zero_lt_of_lt t.isLt) + let a := index (b.label j) u + let r := (pack).ptr j a + have hr : r = (q.map seat id, 0) := by + change (b.ptr index seat j a, 0) = _ + rw [show a = index (b.label j) u from rfl, b.ptr_at index seat j u (Nat.zero_lt_of_lt t.isLt)] + let t' : Fin ((M).width (names (b.label j)) a) := + t.cast (menu_width _ names index len _ u).symm + let n : Fin ((pack).cap M w r) := ⟨_, ht j a t'⟩ + have hn : n.val = t.val := by change len 0 + t.val = _; rw [h₀, zero_add] + exact congrArg y (b.resolve names index seat size len w hi ho p' hp q + (t.cast ((b.arg j).size u _).symm) r hr n hn) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Subround.Bundle +end + +/- +# Compact local numbering for contraction histories + +Rank each key within the finite set of keys actually present, using the +fixed order of their encodings. Only the resulting rank is stored. Neither +the enumeration of the objects nor the proof of the size bound affects it. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +open Coloring Packing HostNet History.Subround Finset + +variable {A A' K : Type} [Fintype A] [Fintype A'] [Encodable K] {H : ℕ} + +open scoped Classical in +/-- The indexed operation `(s.filter fun y => Encodable.encode y < Encodable.encode x).card`. -/ +def index (s : Finset K) (x : K) : ℕ := + (s.filter fun y => Encodable.encode y < Encodable.encode x).card + +open scoped Classical in +theorem index_lt (s : Finset K) (x : K) (hx : x ∈ s) : index s x < s.card := by + apply card_lt_card + exact Finset.ssubset_iff_subset_ne.mpr ⟨filter_subset _ _, fun he => by + have := congrArg (x ∈ ·) he + simp [hx] at this⟩ + +open scoped Classical in +theorem index_strict (s : Finset K) (x y : K) (hx : x ∈ s) + (he : Encodable.encode x < Encodable.encode y) : index s x < index s y := by + apply card_lt_card + apply Finset.ssubset_iff_subset_ne.mpr + constructor + · intro i hi + obtain ⟨hi, h⟩ := mem_filter.mp hi + exact mem_filter.mpr ⟨hi, h.trans he⟩ + · intro h + have hh := congrArg (x ∈ ·) h + simp [hx, he] at hh + +open scoped Classical in +/-- Embeds `A` into `B H where toFun x`. -/ +def compact (key : A ↪ K) (bound : Fintype.card A ≤ 2 ^ H) : A ↪ B H where + toFun x := ⟨index (univ.map key) (key x), + (index_lt _ _ (mem_map_of_mem key (mem_univ x))).trans_le (by simpa using bound)⟩ + inj' x y he := by + have h := congrArg Fin.val he + rcases lt_trichotomy (Encodable.encode (key x)) (Encodable.encode (key y)) with hr | hr | hr + · exact ((index_strict _ _ _ (mem_map_of_mem key (mem_univ x)) hr).ne h).elim + · exact key.injective (Encodable.encode_injective hr) + · exact ((index_strict _ _ _ (mem_map_of_mem key (mem_univ y)) hr).ne h.symm).elim + +open scoped Classical in +theorem compact_eq {f : A ↪ K} {g : A' ↪ K} + {hf : Fintype.card A ≤ 2 ^ H} {hg : Fintype.card A' ≤ 2 ^ H} + (hs : univ.map f = univ.map g) {x : A} {y : A'} (he : f x = g y) : + compact f hf x = compact g hg y := by + apply Fin.ext + exact congrArg₂ index hs he + +open scoped Classical in +theorem compact_relabel (e : A ≃ A') {f : A ↪ K} {g : A' ↪ K} + {hf : Fintype.card A ≤ 2 ^ H} {hg : Fintype.card A' ≤ 2 ^ H} + (he : ∀ x, f x = g (e x)) (x : A) : + compact f hf x = compact g hg (e x) := by + refine compact_eq ?_ (he x) + ext q + simp only [mem_map, mem_univ, true_and] + exact ⟨fun ⟨i, hi⟩ => ⟨e i, (he i).symm.trans hi⟩, + fun ⟨i, hi⟩ => ⟨e.symm i, by rw [he, e.apply_symm_apply, hi]⟩⟩ + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z d w : ℕ} + +open scoped Classical in +/-- The data for the budget construction, including `pos`, `nonneg`, `core`, `deg`, `bound`. -/ +structure Budget (P : Gadget F) (G : HostNet F L h (P.b * z)) (Δ k : ℕ) (B' : ℝ) (H : ℕ) : Prop + where + pos : 0 < z + nonneg : 0 ≤ B' + core : 0 < Δ + deg : ∀ v, (G.C v).card ≤ Δ + bound : (10 : ℝ) * (4 * Δ) ^ 300 * 2 ^ k * B' ≤ 2 ^ H * z + +variable {P : Gadget F} {G : HostNet F L h (P.b * z)} {Δ D k : ℕ} {B' : ℝ} + +omit [Fintype T] in +open scoped Classical in +theorem Budget.fit (b : Budget P G Δ k B' H) (v : Site G.V h) (n : ℕ) {c : ℝ} + (hc : c ≤ 10) (hn : n * (z : ℝ) ≤ c * (near G.C Δ v).card * ((2 : ℝ) ^ k * B')) : n ≤ 2 ^ H + := by + have ha : ((near G.C Δ v).card : ℝ) ≤ (4 * Δ) ^ 300 := by + exact_mod_cast near_card G.C Δ b.core b.deg v + have hs : n * (z : ℝ) ≤ 2 ^ H * z := calc + _ ≤ _ := hn + _ ≤ 10 * (4 * Δ) ^ 300 * ((2 : ℝ) ^ k * B') := mul_le_mul_of_nonneg_right + (mul_le_mul hc ha (Nat.cast_nonneg _) (by norm_num)) (mul_nonneg (by positivity) b.nonneg) + _ ≤ _ := by simpa only [mul_assoc] using b.bound + exact_mod_cast le_of_mul_le_mul_right hs (Nat.cast_pos.mpr b.pos) + +variable (q : Navigation G d w) (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (i : g.Choice m P) + +open scoped Classical in +/-- Embeds `↥(G.receipts g m (g.layout m P i) v)` into `B H`. -/ +def atoms (b : Budget P G Δ k B' H) (contacts : ∀ t, P.b * z ≤ G.tetherLoad (G.far t)) + (v : Site G.V h) : ↥(G.receipts g m (g.layout m P i) v) ↪ B H := + compact (q.atomNames g m (g.layout m P i) v) (by + rw [Fintype.card_coe] + refine b.fit v _ (by norm_num : (8 : ℝ) ≤ 10) (le_trans ?_ + (G.receipts_bound g m contacts q.one b.nonneg (g.layout m P i) v)) + exact mul_le_mul_of_nonneg_left (Nat.cast_le.mpr (Nat.le_mul_of_pos_left _ P.pos)) + (Nat.cast_nonneg _)) + +open scoped Classical in +/-- Computes the hidden by the application `compact (q.hiddenNames g m P i v) (b.fit v _ le_rfl +(hidden_bound P G g m i v b.nonneg))`. -/ +def hidden (b : Budget P G Δ k B' H) (v : Site G.V h) : Hidden g m P i v ↪ B H := + compact (q.hiddenNames g m P i v) (b.fit v _ le_rfl (hidden_bound P G g m i v b.nonneg)) + +variable {S : Scheme F} {r : S.format.obj} + +open scoped Classical in +/-- Embeds `Visible g m P G.units i p v` into `B H`. -/ +def visible (q : Navigation G d S.e) (p : S.Presentation r G.diagram) + (b : Budget P G Δ k B' H) (floor : ∀ t, z ≤ p.borderWidth t) + (v : Site G.V h) : Visible g m P G.units i p v ↪ B H := + compact (visibleNames P G g m i p v q) + (b.fit v _ (by norm_num : (9 : ℝ) ≤ 10) (visible_bound P G g m i p v b.pos b.nonneg floor)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +end + +/- # Span links at a live station of the previous presentation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +open Coloring Packing History History.Subround + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} + {h z : ℕ} {P : Gadget F} {S : Scheme F} {r : S.format.obj} + {G : HostNet F L h (P.b * z)} (p : S.Posting r G) + (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' (G.regroup a ha).load) + (m : Matching (g.ends (G.regroup a ha).src (G.regroup a ha).ix) + (g.ends (G.regroup a ha).dst (G.regroup a ha).ix) (G.regroup a ha).ix) + (i : g.Choice m P) (v : Site (G.V × Cell a) (h - a)) (w : G.diagram.V) + (hw : g.assign m P (G.regroup a ha).units i w = v) + +local notation "H" => G.regroup a ha +local notation "V" => PortMap.Port g m P (HostNet.units H) i p.toPresentation v +local notation "W" => PortMap.width g m P (HostNet.units H) i p.toPresentation v + +omit [Fintype T] in +open scoped Classical in +theorem station_place {j : B S.e} {e : G.E} {t : Bool} (he : p.span e t = (p.vertex w, j)) : + (H).units.place w = (side H e t, (H).ix e) := by + change splitAddr G.V a ha (G.units.place w) = _ + rw [p.place_of_span he] + cases t <;> rfl + +include hw in +open scoped Classical in +private theorem station_location {j : B S.e} {e : G.E} {t : Bool} (he : p.span e t = (p.vertex w, + j)) : + g.route m (g.layout m P i) (side H e t) ((H).ix e) = v := by + unfold Grouping.assign at hw + rw [p.station_place a ha w he] at hw + exact hw + +variable (j : B S.e) (hj : 0 < S.width r (p.vertex w, j)) + +open scoped Classical in +/-- The origin used in the `Posting` construction. -/ +inductive Origin : V → Prop + | outside (q : p.toPresentation.BorderSpan) (hq : q.val = (w, j)) (he) : + Origin (PortMap.exterior g m P (H).units i p.toPresentation v q he) + | inside (e : G.E) (t : Bool) (he : p.span e t = (p.vertex w, j)) (hs) : + Origin (PortMap.demand g m P (H).units i p.toPresentation v e t hs) + +include hw hj in +open scoped Classical in +theorem exists_origin : ∃ q, p.Origin a ha g m i v w j q := by + by_cases h : S.peer r (p.vertex w, j) = none + · exact ⟨_, .outside ⟨(w, j), hj, h⟩ rfl hw⟩ + · obtain ⟨e, t, he⟩ := p.span_end _ hj h + exact ⟨_, .inside e t he (p.station_location a ha g m i v w hw he)⟩ + +open scoped Classical in +/-- The value specified by `(p.exists_origin a ha g m i v w hw j hj).choose`. -/ +def stationPort : V := (p.exists_origin a ha g m i v w hw j hj).choose + +open scoped Classical in +theorem station_origin : p.Origin a ha g m i v w j (p.stationPort a ha g m i v w hw j hj) := + (p.exists_origin a ha g m i v w hw j hj).choose_spec + +open scoped Classical in +theorem origin_width {s : V} (hs : p.Origin a ha g m i v w j s) : + W s = S.width r (p.vertex w, j) := by + cases hs with + | outside q hq he => + erw [PortMap.width_exterior g m P (H).units i p.toPresentation v q he, + Presentation.borderWidth, hq] + rfl + | inside e t he hs => + erw [PortMap.width_demand g m P (H).units i p.toPresentation v e t hs, ← he] + exact (p.length e t).symm + +variable (hz : 0 < z) + +open scoped Classical in +theorem origin_address {s : V} (hs : p.Origin a ha g m i v w j s) + (b : Fin (S.width r (p.vertex w, j))) : + address (cluster g m P (H).units hz i) (old g m P (H).units hz i + (p.toSeating.ends.symm ⟨(p.vertex w, j), b⟩)) = + PortMap.bit g m P (H).units i p.toPresentation v hz s + (b.cast (p.origin_width a ha g m i v w j hs).symm) := by + cases hs with + | outside q hq he => + rcases q with ⟨⟨u, l⟩, h⟩ + obtain ⟨rfl, rfl⟩ := Prod.mk.inj hq + let q : p.toPresentation.BorderSpan := ⟨(u, l), h⟩ + have hh : p.toSeating.ends.symm ⟨(p.vertex u, l), b⟩ = + boundaryEnd _ (p.toPresentation.exteriorBits ⟨q, b⟩) := + p.toPresentation.ends_symm_borderPin ⟨q, b⟩ + rw [hh] + exact PortMap.address_exterior g m P (H).units i p.toPresentation v hz q he b + | inside e t he hm => + let c := b.cast ((congrArg (S.width r) he.symm).trans (p.length e t)) + rw [p.ends_symm_span he b] + exact PortMap.address_demand_old g m P (H).units i p.toPresentation v hz e t hm c + +open scoped Classical in +/-- The value specified by `((r (p.vertex w).1).2 (p.vertex w).2.1, (p.vertex w).2.2)`. -/ +abbrev oldLabel := ((r (p.vertex w).1).2 (p.vertex w).2.1, (p.vertex w).2.2) + +open scoped Classical in +/-- The old map of type `AtomMap g m P (H).units hz i p.toPresentation v (History.original S +(p.oldLabel w)) (.inl w) where slot j h`, constructed using `p.pin w k`. -/ +def oldMap : AtomMap g m P (H).units hz i p.toPresentation v (History.original S (p.oldLabel w)) + (.inl w) where + slot j h := p.stationPort a ha g m i v w hw j h + size j h := p.origin_width a ha g m i v w j (p.station_origin a ha g m i v w hw j h) + value b := by + erw [old_factor g m P (H).units hz i b w] + change S.table r (p.vertex w) (fun u => b (PortMap.bit g m P (H).units i p.toPresentation v hz + (p.stationPort a ha g m i v w hw u.1 u.2.pos) (u.2.cast + (p.origin_width a ha g m i v w u.1 (p.station_origin a ha g m i v w hw u.1 + u.2.pos)).symm))) = _ + rw [p.sample] + apply congrArg + funext k + let u := p.pin w k + have ht := p.origin_address a ha g m i v w u.1 hz (p.station_origin a ha g m i v w hw u.1 + u.2.pos) u.2 + have he : p.toSeating.ends.symm ⟨(p.vertex w, u.1), u.2⟩ = named G.diagram w k := + p.toSeating.ends.symm_apply_eq.mpr (p.toSeating.ends_at w k).symm + rw [he] at ht + exact congrArg b ht.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +end + +/- # A two-hop bound on the sources of all receipts at a site -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +open Coloring Packing Finset + +variable {T F : Type} {x y : Wire} {L : Fringe x y T} {h u d w : ℕ} + {G : HostNet F L h u} (p : Navigation G d w) + +open scoped Classical in +/-- Indexes the neighborhood by the coordinates of `univ.image fun i : Option (B d) × Option (B +d) => p.recover (p.recover root i.1) i.2`. -/ +def neighborhood (root : G.V) := + univ.image fun i : Option (B d) × Option (B d) => p.recover (p.recover root i.1) i.2 + +open scoped Classical in +theorem neighborhood_card (v : G.V) : (p.neighborhood v).card ≤ (2 ^ d + 1) ^ 2 := by + unfold neighborhood + exact card_image_le.trans_eq (by simp [pow_two]) + +variable [Fintype T] {Δ D k : ℕ} {B' : ℝ} (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (col : Bool) + +open scoped Classical in +private theorem reachable (v : G.V) (b : Cell h) (j : Option (B d)) : + p.recover v j ∈ p.neighborhood (g.route m col v b).1 := by + let z := (g.route m col v b).1 + refine mem_image.mpr ⟨(p.reverse z v, j), mem_univ _, ?_⟩ + exact congrArg (fun u => p.recover u j) (p.recover_reverse g m col v b) + +open scoped Classical in +theorem window_move (v : G.V) (b : Cell h) : + v ∈ p.neighborhood (g.route m col v b).1 := + p.reachable g m col v b none + +open scoped Classical in +theorem window_end (i : G.E) (b : Bool) : + G.src i ∈ p.neighborhood (g.route m col (Scheme.side G i b) (G.ix i)).1 := by + cases b + · exact p.window_move g m col _ _ + · rw [← p.back i] + exact p.reachable g m col (G.dst i) (G.ix i) (some _) + +open scoped Classical in +theorem window_party (i : m.items) (j : Fin 6) : + G.src i.val ∈ p.neighborhood (g.party m col i j).1 := by + let e := G.via g m col j i + let b := (HostNet.roleCode col j).2 + have hs : G.src e = G.src i.val := by + have he : G.src (m.mate i) = G.src i.val := congrArg Sigma.fst (m.spec i).2.1 + unfold e HostNet.via Matching.pairEdge + change G.src (if (HostNet.roleCode col j).1 = 0 then m.mate i else i.val) = _ + split_ifs <;> first | exact he | rfl + have he : g.rep m col i j = (Scheme.side G e b, G.ix e) := by + rw [G.role] + dsimp only [b, e] + cases (HostNet.roleCode col j).2 <;> rfl + rw [Grouping.party, he, ←hs] + exact p.window_end g m col e b + +variable [Field F] (P : Gadget F) (i : g.Choice m P) + +open scoped Classical in +/-- In the case `.inl e`, this construction gives `G.src e.1.val`. -/ +def issuer : g.Supply m P i → G.V + | .inl e => G.src e.1.val + | .inr e => G.src e.1.val + +open scoped Classical in +theorem window_supply (e : g.Supply m P i) (b : Bool) : + issuer g m P i e ∈ p.neighborhood + (cond b (g.contact m col e).2 (g.contact m col e).1).1 := by + rcases e with ⟨e, j, t⟩|⟨e, t⟩ + · cases b <;> exact p.window_party g m col e _ + · cases b + · exact p.window_end g m col e.val false + · exact p.window_end g m col e.val true + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Reads.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Reads.lean new file mode 100644 index 0000000000..303c657e9f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/Reads.lean @@ -0,0 +1,781 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood + +/-! +# Emitting raw history keys + +A stamp contains the block and the optional return hop to the original +host. One stub number completes the record for an old wire end. For a +matched pair the two rows are in thick, thin order. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +open Coloring Packing HostNet History.Subround Spectral.Tensor + +namespace Emission + +open scoped Classical in +/-- Indexes the stamp by the coordinates of `Option (B d) × B h`. -/ +abbrev Stamp (d h : ℕ) := Option (B d) × B h +open scoped Classical in +/-- Indexes the tip by the coordinates of `Stamp d h × B w`. -/ +abbrev Tip (d w h : ℕ) := Stamp d h × B w + +variable {d w h b : ℕ} + +open scoped Classical in +/-- The value specified by `(x, .inl ())`. -/ +def station (x : Stamp d h) : AtomKey d w h := (x, .inl ()) +open scoped Classical in +/-- The value specified by `(x, .inr (.inr ()))`. -/ +def checker (x : Stamp d h) : AtomKey d w h := (x, .inr (.inr ())) + +open scoped Classical in +/-- The party of type `AtomKey d w h`, constructed using `roleCode col j`. -/ +def party (col : Bool) (tips : Fin 2 → Bool → Tip d w h) (j : Fin 6) : AtomKey d w h := + let c := roleCode col j + let x := tips c.1 c.2 + (x.1, .inr (.inl (x.2, j))) + +open scoped Classical in +/-- The value specified by `((checker x.1, side), x.2)`. -/ +def stub (x : Tip d w h) (side : Bool) : StubKey d w h := ((checker x.1, side), x.2) + +open scoped Classical in +/-- The value specified by `.inl ((station x, false), j)`. -/ +def exterior (x : Stamp d h) (j : B w) : SpanKey d w h b := .inl ((station x, false), j) + +open scoped Classical in +/-- The value specified by `.inl (stub x side)`. -/ +def demand (x : Tip d w h) (side : Bool) : SpanKey d w h b := .inl (stub x side) + +open scoped Classical in +/-- In the case `.inl (j, k)`, this construction gives `.inl (party col tips (cond side (sixPair +j).2 (sixPair j).1), j, k)`. -/ +def supply (col : Bool) (tips : Fin 2 → Bool → Tip d w h) (kind : Match.Kind b) (side : Bool) : + SupplyKey d w h b := + (side, match kind with + | .inl (j, k) => .inl (party col tips (cond side (sixPair j).2 (sixPair j).1), j, k) + | .inr k => .inr (stub (tips 1 side) side, k)) + +open scoped Classical in +/-- A loop has one hidden name. Both of its ends refer to its source. -/ +def pointer (col : Bool) (tips : Fin 2 → Bool → Tip d w h) + (kind : Match.Kind b) (loop side : Bool) : Bool × SpanKey d w h b := + (loop, .inr (supply col tips kind (if loop then false else side))) + +open scoped Classical in +/-- An equality constraint reads its old full-width end and one +separate span per replacement bundle. All reads start at offset zero. -/ +def check (tips : Bool → Tip d w h) (loop side : Bool) : + Option (Fin b) → Bool × SpanKey d w h b + | none => (true, demand (tips side) side) + | some k => pointer false (fun _ => tips) (.inr k) loop side + +end Emission + +variable {T F : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} {h u d w : ℕ} + {G : HostNet F L h u} (q : Navigation G d w) + {Δ D k : ℕ} {B' : ℝ} (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (col : Bool) + +open scoped Classical in +/-- The value specified by `(q.reverse (g.route m col v.1 v.2).1 v.1, cellIndex h v.2)`. -/ +def stamp (v : G.V × Cell h) : Emission.Stamp d h := + (q.reverse (g.route m col v.1 v.2).1 v.1, cellIndex h v.2) + +open scoped Classical in +/-- The value specified by `(q.stamp g m col (Scheme.side G e side, G.ix e), q.stub e side)`. -/ +def tip (e : G.E) (side : Bool) : Emission.Tip d w h := + (q.stamp g m col (Scheme.side G e side, G.ix e), q.stub e side) + +open scoped Classical in +/-- The value specified by `q.tip g m col (m.pairEdge (t, j))`. -/ +def tips (t : m.items) (j : Fin 2) := q.tip g m col (m.pairEdge (t, j)) + +open scoped Classical in +theorem atom_station (v : G.diagram.V) : + q.atomKey g m col (.inl v) = Emission.station (q.stamp g m col (G.units.place v)) := rfl + +open scoped Classical in +theorem atom_checker (v : G.V × Cell h) : + q.atomKey g m col (.inr (.inr v)) = Emission.checker (q.stamp g m col v) := rfl + +open scoped Classical in +theorem atom_party (t : m.items) (j : Fin 6) : + q.atomKey g m col (.inr (.inl ⟨t, j⟩)) = Emission.party col (q.tips g m col t) j := by + have he : g.rep m col t j = (Scheme.side G (G.via g m col j t) (roleCode col j).2, + G.ix (G.via g m col j t)) := by rw [G.role]; cases (roleCode col j).2 <;> rfl + change (q.stamp g m col (g.rep m col t j), _) = _ + rw [he] + rfl + +open scoped Classical in +theorem stub_eq (e : G.E) (s : Bool) : + q.stubKey g m col e s = Emission.stub (q.tip g m col e s) s := rfl + +variable [Field F] (P : Gadget F) (i : g.Choice m P) + +open scoped Classical in +/-- In the case `.inl ⟨t, _, _⟩`, this construction gives `q.tips g m col t`. -/ +def eventTips : g.Supply m P i → Fin 2 → Bool → Emission.Tip d w h + | .inl ⟨t, _, _⟩ => q.tips g m col t + | .inr (e, _) => fun _ => q.tip g m col e.val + +open scoped Classical in +/-- The event kind used in the `Navigation` construction. -/ +def eventKind : g.Supply m P i → Match.Kind P.b + | .inl ⟨t, j, k⟩ => .inl (j, k.castLE (by + exact (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ j)).trans + (P.cost _ (i t).2.property).le)) + | .inr (_, j) => .inr j + +open scoped Classical in +theorem supply_eq (e : g.Supply m P i) (s : Bool) : + q.supplyKey g m col P i e s = + Emission.supply col (q.eventTips g m col P i e) (eventKind g m P i e) s := by + rcases e with ⟨t, j, a⟩ | ⟨t, a⟩ + · cases s <;> simp only [supplyKey, supplyAtom, Grouping.supplies, eventKind, eventTips, + Emission.supply, Bool.cond_false, Bool.cond_true, atom_party] + · rfl + +open scoped Classical in +theorem hidden_old (e : G.E) (s : Bool) : + q.hiddenKey g m P i (cond s (.inr (.inl e)) (.inl e)) = + Emission.demand (q.tip g m (g.layout m P i) e s) s := by cases s <;> rfl + +open scoped Classical in +theorem hidden_new (e : g.Supply m P i) (s : Bool) : + let c := g.layout m P i + (true, q.hiddenKey g m P i (.inr (.inr e))) = + Emission.pointer c (q.eventTips g m c P i e) (eventKind g m P i e) true s := by + simp only [hiddenKey, Emission.pointer, ite_true, supply_eq] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +open Coloring Packing History.Subround + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z d : ℕ} + (P : Gadget F) (G : HostNet F L h (P.b * z)) + {Δ D k : ℕ} {B' : ℝ} (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (i : g.Choice m P) + {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G.diagram) + (q : Navigation G d S.e) + +open scoped Classical in +theorem visible_old (e : p.BorderSpan) : + q.faceKey P G g m i p (.inl e) = + Emission.exterior (q.stamp g m (g.layout m P i) (G.units.place e.val.1)) e.val.2 := rfl + +open scoped Classical in +theorem visible_new (e : g.Survivors m P i) (s : Bool) : + let c := g.layout m P i + (false, q.faceKey P G g m i p (.inr (e, s))) = + Emission.pointer c (q.eventTips g m c P i e.val) (eventKind g m P i e.val) false s := by + simp only [faceKey, Emission.pointer, Bool.false_eq_true, ite_false, supply_eq] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +end + +/- # Reading the stub and reverse hop of an emitted contact -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +open Coloring Packing + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u h : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h u} + (p : S.Posting r G) (hu : 0 < u) (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' (G.regroup a ha).load) + +local notation "H" => G.regroup a ha +local notation "q" => p.navigation hu a ha + +open scoped Classical in +theorem record_stub (c : Color (h - a)) (e : (H).E) : + (((p.records a ha g c ((H).src e)).2.1 (cellIndex _ ((H).ix e))).2 ((q).stub e false)).2 = + ((q).slot ((H).src e) ((H).dst e), (q).stub e true) := by + change G.E at e + change (p.localStub (G.src e) ((splitCell a ha).symm + (ancestor ha (G.ix e), (cellIndex _).symm (cellIndex _ (suffix a (G.ix e))))) + (p.stub e false)).2 = _ + rw [Equiv.symm_apply_apply, show (ancestor ha _, suffix a _) = splitCell a ha (G.ix e) from rfl, + Equiv.symm_apply_apply] + exact p.local_slot e + +open scoped Classical in +/-- Read the opposite stub at a given grouped occurrence. -/ +def receiving (v : G.V × Cell a) (b : B (h - a)) (s : B S.e) := + (S.decode ((r (p.host v.1)).2 (p.block ((splitCell a ha).symm + (v.2, (cellIndex _).symm b))))).peer 0 s + +omit [Fintype T] in +open scoped Classical in +theorem receiving_eq (e : (H).E) : + p.receiving a ha ((H).dst e) (cellIndex _ ((H).ix e)) ((q).stub e true) = + some ((q).slot ((H).dst e) ((H).src e), 0, (q).stub e false) := by + change G.E at e + unfold receiving + rw [Equiv.symm_apply_apply] + change (S.decode ((r (p.host (G.dst e))).2 + (p.block ((splitCell a ha).symm (splitCell a ha (G.ix e)))))).peer 0 (p.stub e true) = _ + rw [Equiv.symm_apply_apply] + exact p.link e true + +omit [Fintype T] in +open scoped Classical in +theorem reverse_eq (e : (H).E) : + (q).reverse ((H).dst e) ((H).src e) = + if (H).dst e = (H).src e then none else + (p.receiving a ha ((H).dst e) (cellIndex _ ((H).ix e)) ((q).stub e true)).map Prod.fst := by + rw [receiving_eq] + rfl + +variable (m : Matchings a ha g) (ctl : p.Controls hu a ha g m) + +local notation "data" => p.records a ha g m.color + +open scoped Classical in +/-- Locate the receiving stub of the thick mate of a sampled thin row. -/ +def mateAddress {d n e l : ℕ} (x : (Match.Input d n e e l).obj) (b : B n) : B n × B e := + let ctrl := (Match.rows x).control + let i := Match.rowIndex n e (ctrl.2 (Match.sampleRow ctrl.1 b)) + (i.1, ((x.2.1 i.1).2 i.2).2.2) + +include ctl in +open scoped Classical in +theorem mateAddress_eq (col : Bool) (v : (H).V) (b : Cell (h - a)) + (hm : (g.route m col v b).1 ≠ v) : + ∃ e : (H).E, (H).src e = v ∧ (H).dst e = (g.route m col v b).1 ∧ + mateAddress (data v) (cellIndex _ b) = (cellIndex _ ((H).ix e), (q).stub e true) := by + cases col + · exact (hm rfl).elim + let chart := p.chart hu a ha g m ctl + let row := Match.rows (data v) + let i := Match.sampleRow row.control.1 (cellIndex _ b) + have hs : row.control.1 i = true := by + have hh := (chart.stubs.motion_spec _ _ chart.records chart.controls + (g.loc v b) b (chart.labels v b)).1 + change row.control.1 i = _ at hh + rw [hh] + cases he : m.plan (g.loc v b) b with + | none => + exfalso + apply hm + change ((m.plan (g.loc v b) b).getD (g.loc v b)).1 = v + rw [he] + rfl + | some _ => rfl + obtain ⟨j, hj⟩ := (chart.marks (v, i)).mp hs + have hjv : (H).src j.val = v := congrArg Prod.fst hj + have hji : chart.stubs.pos j.val = i := congrArg Prod.snd hj + have hjb : (H).ix j.val = b := by + apply (cellIndex _).injective + have hb := Match.sampleRow_block row.control.1 (cellIndex _ b) + change (Match.rowIndex _ _ i).1 = _ at hb + rw [← hji, Match.Stubs.pos, Equiv.apply_symm_apply] at hb + exact hb + let e := m.mate j + have he : (H).src e = v := (congrArg Sigma.fst (m.spec j).2.1).trans hjv + have hd : (H).dst e = (g.route m true v b).1 := by + rw [← hjv, ← hjb, g.route_thin m true j] + rfl + refine ⟨e, he, hd, ?_⟩ + have hp := chart.controls.mate j + change chart.stubs.pos e = (Match.rows (data ((H).src j.val))).control.2 (chart.stubs.pos j.val) + at hp + rw [hjv, hji] at hp + unfold mateAddress + dsimp only + rw [← hp, Match.Stubs.pos, Equiv.apply_symm_apply, ← he] + have hr := congrArg Prod.snd (p.record_stub hu a ha g m.color e) + exact Prod.ext rfl hr + +include ctl in +open scoped Classical in +theorem reverse_move (col : Bool) (v : (H).V) (b : Cell (h - a)) : + let t := (g.route m col v b).1 + let addr := mateAddress (data v) (cellIndex _ b) + (q).reverse t v = if t = v then none else (p.receiving a ha t addr.1 addr.2).map Prod.fst := by + dsimp only + by_cases hm : (g.route m col v b).1 = v + · rw [ite_eq_left hm] + exact ite_eq_left hm + obtain ⟨e, hs, hd, he⟩ := p.mateAddress_eq hu a ha g m ctl col v b hm + rw [he, ← hd, ← hs] + exact p.reverse_eq hu a ha e + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +end + +/- +# Reading the raw history keys from row and movement records + +A moved occurrence needs the return stub of the sampled row's mate. +The other three fields are the block, orientation and stub in an old +edge record. The computation uses no global edge identifier. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing + +namespace Navigation.Emission + +variable {V : Type} {d h w ℓ : ℕ} + (nav : V → B d → V) (data : V → (Match.Input d h w w ℓ).obj) + (recv : V → B h → B w → Option (B d)) (col : Bool) + +open scoped Classical in +/-- The stamp at of type `Stamp d h`, constructed using `(Match.follow nav v (Match.action col +(data v) t)).1`. -/ +def stampAt (v : V) (t : B h) : Stamp d h := + let dst := (Match.follow nav v (Match.action col (data v) t)).1 + let addr := Scheme.Posting.mateAddress (data v) t + (if dst = v then none else recv dst addr.1 addr.2, t) + +open scoped Classical in +/-- The tip at of type `Tip d w h`, constructed using `Match.rowIndex h w i`. -/ +def tipAt (v : V) (i : B (h + w)) (side : Bool) : Tip d w h := + let (b, j) := Match.rowIndex h w i + let dst := (((data v).2.1 b).2 j).2 + let host := cond side (nav v dst.1) v + (stampAt nav data recv col host b, cond side dst.2 j) + +open scoped Classical in +/-- The value specified by `tipAt nav data recv col v (if j = 0 then (Match.rows (data +v)).control.2 i else i)`. -/ +def partyTips (v : V) (i : B (h + w)) (j : Fin 2) := + tipAt nav data recv col v (if j = 0 then (Match.rows (data v)).control.2 i else i) + +open scoped Classical in +/-- In the case `.inl _`, this construction gives `partyTips nav data recv col e.1.1 e.1.2`. -/ +def supplyTips {b : ℕ} (e : Match.Candidate V (h + w) b) : Fin 2 → Bool → Tip d w h := + match e.2 with + | .inl _ => partyTips nav data recv col e.1.1 e.1.2 + | .inr _ => fun _ => tipAt nav data recv col e.1.1 e.1.2 + +end Navigation.Emission + +namespace Scheme.Posting +open Navigation.Emission + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u h : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h u} + (p : S.Posting r G) (hu : 0 < u) (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' (G.regroup a ha).load) + (m : Matchings a ha g) (ctl : p.Controls hu a ha g m) (col : Bool) + +local notation "H" => G.regroup a ha +local notation "q" => p.navigation hu a ha +local notation "c" => p.chart hu a ha g m ctl +local notation "data" => p.records a ha g m.color + +open scoped Classical in +/-- Transforms the indexed data by `(p.receiving a ha v t i).map Prod.fst`. -/ +def recv (v : (H).V) (t : B (h - a)) (i : B S.e) : Option (B S.d) := + (p.receiving a ha v t i).map Prod.fst + +include ctl in +open scoped Classical in +theorem stamp_eq (v : (H).V) (t : Cell (h - a)) : + (q).stamp g m col (v, t) = + stampAt (p.groupNav a) data (p.recv a ha) col v (cellIndex _ t) := by + have he := congrArg Prod.fst ((c).moved col v t) + change (Match.follow _ v (Match.action col (data v) (cellIndex _ t))).1 + = (g.route m col v t).1 at he + let addr := mateAddress (data v) (cellIndex _ t) + let f (w : (H).V) := if w = v then none else p.recv a ha w addr.1 addr.2 + have hr : (q).reverse (g.route m col v t).1 v = f (g.route m col v t).1 := + p.reverse_move hu a ha g m ctl col v t + exact Prod.ext (hr.trans (congrArg f he.symm)) rfl + +open scoped Classical in +theorem tip_eq (e : (H).E) (b : Bool) : + (q).tip g m col e b = + tipAt (p.groupNav a) data (p.recv a ha) col ((H).src e) ((c).stubs.pos e) b := by + have hpos : Match.rowIndex _ _ ((c).stubs.pos e) = + (cellIndex _ ((H).ix e), (q).stub e false) := Equiv.apply_symm_apply _ _ + have hdst : p.groupNav a ((H).src e) ((q).slot ((H).src e) ((H).dst e)) = (H).dst e := + (c).contacts e + unfold tipAt + rw [hpos] + simp only [p.record_stub hu a ha g m.color e, hdst] + cases b <;> simp only [Navigation.tip, Scheme.side, Bool.cond_false, Bool.cond_true, + p.stamp_eq hu a ha g m ctl] <;> rfl + +open scoped Classical in +theorem tips_eq (t : m.items) : + (q).tips g m col t = + partyTips (p.groupNav a) data (p.recv a ha) col ((H).src t.val) ((c).stubs.pos t.val) := by + have hp : (Match.rows (data ((H).src t.val))).control.2 ((c).stubs.pos t.val) = + (c).stubs.pos (m.mate t) := ((c).controls.mate t).symm + have hs : (H).src (m.mate t) = (H).src t.val := congrArg Sigma.fst (m.spec t).2.1 + funext j b + fin_cases j + · change (q).tip g m col (m.mate t) b = tipAt _ _ _ _ _ _ _ + rw [p.tip_eq hu a ha g m ctl, hs, ← hp] + rfl + · exact p.tip_eq hu a ha g m ctl col t.val b + +variable (P : Gadget F) (i : g.Choice m P) + +open scoped Classical in +theorem eventTips_eq (e : g.Supply m P i) : + (q).eventTips g m col P i e = + supplyTips (p.groupNav a) data (p.recv a ha) col ((c).event P i e) := by + rcases e with ⟨t, j, s⟩ | ⟨t, s⟩ + · exact p.tips_eq hu a ha g m ctl col t + · funext j b + exact p.tip_eq hu a ha g m ctl col t.val b + +open scoped Classical in +theorem eventKind_eq (e : g.Supply m P i) : + Navigation.eventKind (G := H) g m P i e = ((c).event P i e).2 := by + rcases e with ⟨t, j, s⟩ | ⟨t, s⟩ <;> rfl + +open scoped Classical in +/-- Both endpoints use their old offset, even if the occurrence moves. -/ +theorem old_offset (e : (H).E) (s : Bool) (t : Fin u) : + let name := tipAt (p.groupNav a) data (p.recv a ha) col ((H).src e) ((c).stubs.pos e) s + let j := p.toSeating.ends (endBit G e s t) + j.1.2 = name.2 ∧ j.2.val = t.val := by + dsimp only + rw [← p.tip_eq hu a ha g m ctl] + obtain ⟨he, ht⟩ := p.ordered e s t + exact ⟨congrArg Prod.snd he, ht⟩ + +open scoped Classical in +/-- Reading either address gives the anchor of the corresponding factor, +so the opposite endpoint can be located from this same event. -/ +theorem event_anchor (e : g.Supply m P i) (s : Bool) : + let j := (c).event P i e + let path := Match.paths (p.groupNav a) data col j + (c).site ((H).anchor g m col (Navigation.supplyAtom (G := H) g m P i e s)) = + Match.readPath (p.groupNav a) j.1.1 (cond s path.2 path.1) := by + have he := (c).read_event P i col e + dsimp only + rw [Navigation.supply_anchor (G := H) g m col P i e s] + cases s + · exact (congrArg Prod.fst he).symm + · exact (congrArg Prod.snd he).symm + +end Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Comparing rooted neighborhoods by short addresses + +A walk is recorded last hop first. Equality of two neighborhoods +requires the same local records along every bounded walk and the +same coincidence pattern of visited hosts. Absolute names may differ. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +open Coloring Match Navigation.Emission + +variable {V W X : Type} {d h e ℓ : ℕ} + +open scoped Classical in +/-- The indexed operation `path.foldr (fun i v => nav v i) root`. -/ +def visit (nav : V → B d → V) (root : V) (path : List (B d)) := + path.foldr (fun i v => nav v i) root + +open scoped Classical in +/-- The data for the env construction, including `nav`, `data`, `recv`, `extra`, `root`. -/ +structure Env (V X : Type) (d h e ℓ : ℕ) where + /-- The `Env` component of type `V → B d → V`. -/ + nav : V → B d → V + /-- The carried data of type `V → (Input d h e e ℓ).obj`. -/ + data : V → (Input d h e e ℓ).obj + /-- The `Env` component of type `V → B h → B e → Option (B d)`. -/ + recv : V → B h → B e → Option (B d) + /-- The `Env` component of type `V → X`. -/ + extra : V → X + /-- The root of type `V`. -/ + root : V + +namespace Env +variable (α : Env V X d h e ℓ) +open scoped Classical in +/-- Uses `visit α.nav α.root` as the representation. -/ +def node := visit α.nav α.root +open scoped Classical in +/-- Uses `stampAt α.nav α.data α.recv` as the representation. -/ +abbrev stamp := stampAt α.nav α.data α.recv +open scoped Classical in +/-- Uses `tipAt α.nav α.data α.recv` as the representation. -/ +abbrev tip := tipAt α.nav α.data α.recv +open scoped Classical in +/-- Uses `partyTips α.nav α.data α.recv` as the representation. -/ +abbrev tips := partyTips α.nav α.data α.recv +open scoped Classical in +/-- The value specified by `supplyTips (b := b) α.nav α.data α.recv`. -/ +abbrev supplies {b : ℕ} := supplyTips (b := b) α.nav α.data α.recv +end Env + +variable (α : Env V X d h e ℓ) (β : Env W X d h e ℓ) + +open scoped Classical in +/-- The condition `∃ path, path.length ≤ n ∧ α.node path = v ∧ β.node path = w` on the specified +data. -/ +def Related (n : ℕ) (v : V) (w : W) : Prop := + ∃ path, path.length ≤ n ∧ α.node path = v ∧ β.node path = w + +open scoped Classical in +/-- The data for the agree construction, including `same`, `data`, `recv`, `extra`. -/ +structure Agree (n : ℕ) : Prop where + same : ∀ p q, p.length ≤ n → q.length ≤ n → + (α.node p = α.node q ↔ β.node p = β.node q) + data : ∀ p, p.length ≤ n → α.data (α.node p) = β.data (β.node p) + recv : ∀ p, p.length ≤ n → α.recv (α.node p) = β.recv (β.node p) + extra : ∀ p, p.length ≤ n → α.extra (α.node p) = β.extra (β.node p) + +variable {α β} {v v' : V} {w w' : W} {n k : ℕ} + +open scoped Classical in +theorem Agree.symm (a : Agree α β n) : Agree β α n := + ⟨fun p q h h' => (a.same p q h h').symm, fun p h => (a.data p h).symm, + fun p h => (a.recv p h).symm, fun p h => (a.extra p h).symm⟩ + +open scoped Classical in +theorem related_root : Related α β 0 α.root β.root := ⟨[], le_rfl, rfl, rfl⟩ + +variable (a : Agree α β n) (r : Related α β k v w) + +open scoped Classical in +theorem Related.widen (h : k ≤ n) (r : Related α β k v w) : Related α β n v w := by + obtain ⟨p, hp, hv, hw⟩ := r + exact ⟨p, hp.trans h, hv, hw⟩ + +include r in +open scoped Classical in +theorem Related.next (j : B d) : Related α β (k + 1) (α.nav v j) (β.nav w j) := by + obtain ⟨p, hp, rfl, rfl⟩ := r + exact ⟨j::p, Nat.succ_le_succ hp, rfl, rfl⟩ + +include a in +open scoped Classical in +theorem Agree.equal (r : Related α β n v w) (s : Related α β n v' w') : + v = v' ↔ w = w' := by + obtain ⟨p, hp, rfl, rfl⟩ := r + obtain ⟨q, hq, rfl, rfl⟩ := s + exact a.same p q hp hq + +include a r + +open scoped Classical in +theorem Agree.records (hk : k ≤ n) : + α.data v = β.data w ∧ α.recv v = β.recv w ∧ α.extra v = β.extra w := by + obtain ⟨p, hp, rfl, rfl⟩ := r + exact ⟨a.data p (hp.trans hk), a.recv p (hp.trans hk), a.extra p (hp.trans hk)⟩ + +omit a in +open scoped Classical in +theorem Related.follow (x : (Move d ℓ).obj) : + Related α β (k + 1) (follow α.nav v x).1 (follow β.nav w x).1 := by + unfold Match.follow + split_ifs + · exact r.next _ + · exact r.widen (by omega) + +omit a in +open scoped Classical in +theorem Related.path (x : (Match.Path d ℓ).obj) : + Related α β (k + 2) (readPath α.nav v x).1 (readPath β.nav w x).1 := by + unfold readPath + split_ifs + · exact (r.next _).follow _ + · exact (r.follow _).widen (by omega) + +open scoped Classical in +theorem Agree.ends (hk : k + 1 ≤ n) (c : Bool) : + localEnds α.nav α.data c v = localEnds β.nav β.data c w := by + have remote : (fun i => action c (α.data (α.nav v i))) = + (fun i => action c (β.data (β.nav w i))) := by + funext i + rw [(a.records (r.next i) hk).1] + unfold localEnds + rw [remote, (a.records r (by omega)).1] + +open scoped Classical in +theorem Agree.parties (hk : k + 1 ≤ n) (c : Bool) : + localParties α.nav α.data c v = localParties β.nav β.data c w := by + funext i + unfold localParties + rw [a.ends r hk c, (a.records r (by omega)).1] + +open scoped Classical in +theorem Agree.paths (hk : k + 1 ≤ n) (c : Bool) (i : B (h + e)) {b : ℕ} (j : Kind b) : + Match.paths α.nav α.data c ((v, i), j) = Match.paths β.nav β.data c ((w, i), j) := by + rcases j with ⟨j, t⟩|t + · simp only [Match.paths, a.parties r hk c] + · exact congrFun (a.ends r hk c) i + +open scoped Classical in +theorem Agree.stamp (hk : k + 1 ≤ n) (c : Bool) (i : B h) : + α.stamp c v i = β.stamp c w i := by + have hd := (a.records r (by omega)).1 + let x := action c (β.data w) i + have t := r.follow x + unfold Env.stamp stampAt + rw [hd] + change (if (follow α.nav v x).1 = v then none else _, i) = + (if (follow β.nav w x).1 = w then none else _, i) + have hr := (a.records t hk).2.1 + have he := a.equal (t.widen hk) (r.widen (by omega)) + dsimp only [x] at * + simp only [he, hr] + +open scoped Classical in +theorem Agree.tip (hk : k + 2 ≤ n) (c : Bool) (i : B (h + e)) (s : Bool) : + α.tip c v i s = β.tip c w i s := by + have hd := (a.records r (by omega)).1 + unfold Env.tip tipAt + rw [hd] + cases s + · exact Prod.ext (a.stamp r (by omega) c _) rfl + · exact Prod.ext (a.stamp (r.next _) hk c _) rfl + +open scoped Classical in +theorem Agree.tips (hk : k + 2 ≤ n) (c : Bool) (i : B (h + e)) : + α.tips c v i = β.tips c w i := by + funext j s + unfold Env.tips partyTips + rw [(a.records r (by omega)).1] + exact a.tip r hk c _ s + +open scoped Classical in +theorem Agree.supplies (hk : k + 2 ≤ n) (c : Bool) (i : B (h + e)) {b : ℕ} (j : Kind b) : + α.supplies c ((v, i), j) = β.supplies c ((w, i), j) := by + cases j + · exact a.tips r hk c _ + · exact funext fun _ => funext fun s => a.tip r hk c _ s + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +end + +/- +# Gathering histories along bounded walks + +Each announcement exchanges all groups in a single payload. Paths +are indexed independently of their endpoints, including when many +paths end at the same host. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +open Coloring Neighborhood + +variable {m d a r : ℕ} {A : Format} + +/-- The quantity computed by `Format.vec ((d + 1) * r) A`. -/ +abbrev Walks (r d : ℕ) (A : Format) := Format.vec ((d + 1) * r) A + +/-- Maps the coordinate `i` to `((X i).1, fun j k => (X (walks r (fun x => (X x).1) i k)).2 j)`. -/ +def reads (r : ℕ) (X : (Fmt.groups m d a A).obj) : (Fmt.groups m d a (Walks r d A)).obj := + fun i => ((X i).1, fun j k => (X (walks r (fun x => (X x).1) i k)).2 j) + +private def previous (k : B ((d + 1) * (r + 1))) : B ((d + 1) * r) := + (path_surjective d r (path d (r + 1) k).2).choose + +private def advance (d r : ℕ) (A : Format) (x : (Walks r d A).obj × (B d → (Walks r d A).obj)) : + (Walks (r + 1) d A).obj := + fun k => ((path d (r + 1) k).1.elim x.1 x.2) (previous k) + +private theorem continuation (X : (Fmt.groups m d a A).obj) : + announce (A := Walks r d A) (H := Walks r d A) (O := Walks (r + 1) d A) + id (advance d r A) (reads r X) = reads (r + 1) X := by + funext i + refine Prod.ext (show _ = _ from rfl) ?_ + funext j k + have hk : path d r (previous k) = (path d (r + 1) k).2 := + (path_surjective d r (path d (r + 1) k).2).choose_spec + simp only [announce, advance, id_eq, reads, walks, run] + cases (path d (r + 1) k).1 <;> simp only [Option.elim_none, Option.elim_some, hk] + +variable {F : Type} [Field F] {u v n : ℕ} {L : Set (Table F)} + +private theorem advance_net : + let Z := Walks r d A + let W := Walks (r + 1) d A + Circuit F (.pair Z (.vec d Z)) W (advance d r A) + ((Format.pair Z (.vec d Z)).width + 2 * W.width) := by + intro Z W + let pin (q : W.pins) : (Format.pair Z (.vec d Z)).pins := + (path d (r + 1) q.1).1.elim (.inl (previous q.1, q.2)) (fun z => .inr (z, previous q.1, q.2)) + apply Circuit.project pin + rintro x ⟨i, j⟩ + change A.code (advance d r A x i) j = _ + simp only [advance, pin] + cases (path d (r + 1) i).1 <;> rfl + +/-- The quantity computed by `gatherCost m d v n + 1000 * (2 ^ m * (2 ^ d * (m + v) + v))`. -/ +def readCost (m d v n : ℕ) := gatherCost m d v n + 1000 * (2 ^ m * (2 ^ d * (m + v) + v)) + +private theorem cost_bound (Z W : Format) (hz : 2 ^ a * Z.width ≤ v) (hw : 2 ^ a * W.width ≤ v) : + announceCost m d a v n Z Z (4 * Z.width) + (4 * ((Format.pair Z (.vec d Z)).width + 2 * W.width)) ≤ readCost m d v n := by + have h₁ := Nat.mul_le_mul_left (2 ^ m) hz + have h₂ := Nat.mul_le_mul_left (2 ^ m * 2 ^ d) hz + have h₃ := Nat.mul_le_mul_left (2 ^ m) hw + simp only [announceCost, readCost, Fmt.groups, Fmt.bank, Format.width_vec, Format.width_pair, + Format.width_addr] + ring_nf at h₁ h₂ h₃ ⊢ + omega + +theorem reads_net {I : Type*} (hu : 3 ≤ u) (ht : Access F u L (m + d) v n) + (X : I → (Fmt.groups m d a A).obj) (hx : ∀ i, Fmt.Reciprocal (.vec a A) (X i)) + (hr : 2 ^ a * (Walks r d A).width ≤ v) : + Computes F u L (Fmt.groups m d a A) (Fmt.groups m d a (Walks r d A)) + X (fun i => reads r (X i)) (fun _ => 1) ((r + 1) * readCost m d v n) := by + induction r with + | zero => + let E := Fmt.groups m d a A + let O := Fmt.groups m d a (Walks 0 d A) + have c : Circuit F E O (reads 0) (E.width + 2 * O.width) := by + let pin : O.pins → E.pins + | (i, .inl j) => (i, .inl j) + | (i, .inr (j, _, k)) => (i, .inr (j, k)) + apply Circuit.project pin + rintro x ⟨i, j|⟨j, k, l⟩⟩ <;> rfl + refine (Computes.of_map (Map.circuit hu c) (fun _ => rfl)).mono ?_ + simp only [E, O, Fmt.groups, Fmt.bank, Walks, Format.width_vec, Format.width_pair, + Format.width_addr, + mul_zero, pow_zero, one_mul, readCost, zero_add] at hr ⊢ + have hh := Nat.mul_le_mul_left (2 ^ m) hr + ring_nf at hh ⊢ + omega + | succ r ih => + let Z := Walks r d A + let W := Walks (r + 1) d A + have hz : 2 ^ a * Z.width ≤ v := le_trans (Nat.mul_le_mul_left _ (by + unfold Z Walks + simp only [Format.width_vec] + gcongr; omega)) hr + have h := computes_announce (L := L) hu ht (show (Format.vec a Z).width ≤ v by simpa using hz) + (fun i => reads r (X i)) hx (Map.circuit hu (Circuit.id F Z)) + (Map.circuit hu (advance_net (r := r) (d := d) (A := A))) + have hk := (ih hz).comp (h.mono (cost_bound Z W hz hr)) + rw [show (fun i => announce id (advance d r A) (reads r (X i))) = (fun i => reads (r + + 1) (X i)) from funext (fun i => continuation (X i))] at hk + simpa only [one_mul, Nat.succ_mul] using hk + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/State.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/State.lean new file mode 100644 index 0000000000..72ef5dd642 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/History/State.lean @@ -0,0 +1,918 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Reads +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Radius +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Checks + +/-! # Recognizing exterior spans by their local pattern -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +open Coloring Packing + +variable {F T : Type} [Field F] {x y : Wire} {L : Fringe x y T} + {h u : ℕ} {S : Scheme F} {r : S.format.obj} + {G : HostNet F L h u} (p : S.Posting r G) (a : ℕ) (ha : a ≤ h) + +local notation "H" => G.regroup a ha + +open scoped Classical in +/-- The value specified by `S.decode ((r (p.host v.1)).2 (p.block ((splitCell a ha).symm (v.2, +(cellIndex _).symm b))))`. -/ +def patternAt (v : G.V × Cell a) (b : B (h - a)) : Pattern F S.d S.k S.e := + S.decode ((r (p.host v.1)).2 (p.block ((splitCell a ha).symm (v.2, (cellIndex _).symm b)))) + +open scoped Classical in +private def addressAt (v : G.V × Cell a) (b : B (h - a)) : S.Vtx := + (p.host v.1, p.block ((splitCell a ha).symm (v.2, (cellIndex _).symm b)), 0) + +open scoped Classical in +private theorem addressAt_eq (v : G.V × Cell a) (b : B (h - a)) (w : G.diagram.V) : + p.vertex w = p.addressAt a ha v b ↔ (H).units.place w = (v, (cellIndex _).symm b) := by + rw [p.vertex_eq] + change _ ↔ splitAddr G.V a ha (G.units.place w) = (v, (cellIndex _).symm b) + rw [← Equiv.eq_symm_apply] + simp only [addressAt, Prod.mk.injEq, p.host.injective.eq_iff, p.block.injective.eq_iff, and_true] + rw [Prod.ext_iff] + rfl + +open scoped Classical in +theorem occupied_iff (v : G.V × Cell a) (b : B (h - a)) : + (∃ j, 0 < (p.patternAt a ha v b).width 0 j) ↔ + ∃ w : G.diagram.V, 0 < G.diagram.arity w ∧ (H).units.place w = (v, (cellIndex _).symm b) := by + let q := p.addressAt a ha v b + have size w : 0 < G.diagram.arity w ↔ Nonempty (S.LocalPin r (p.vertex w)) := by + rw [← Fintype.card_pos_iff, ← Fintype.card_congr (p.pin w)] + simp only [Diagram.Port, Fintype.card_sum, card_slots, Diagram.arity] + change (∃ j, 0 < S.width r (q, j)) ↔ _ + constructor + · rintro ⟨j, hj⟩ + obtain ⟨w, hw⟩ := p.cover ⟨(q, j), ⟨0, hj⟩⟩ + change p.vertex w = q at hw + refine ⟨w, (size w).mpr ?_, (p.addressAt_eq _ _ _ _ _).mp hw⟩ + rw [hw] + exact ⟨⟨j, ⟨0, hj⟩⟩⟩ + · rintro ⟨w, hw, ht⟩ + have h := (size w).mp hw + rw [(p.addressAt_eq _ _ _ _ _).mpr ht] at h + obtain ⟨⟨j, i⟩⟩ := h + exact ⟨j, i.pos⟩ + +open scoped Classical in +theorem border_iff (v : G.V × Cell a) (b : B (h - a)) (j : B S.e) : + let t := (cellIndex _).symm b + let M := p.patternAt a ha v b + 0 < M.width 0 j ∧ M.peer 0 j = none ↔ + ∃ e : p.toPresentation.BorderSpan, (H).units.place e.val.1 = (v, t) ∧ e.val.2 = j := by + intro t M + let y : S.Vtx := (p.host v.1, p.block ((splitCell a ha).symm (v.2, t)), 0) + have hv (w : G.diagram.V) : p.vertex w = y ↔ (H).units.place w = (v, t) := + p.addressAt_eq a ha v b w + have peer : M.peer 0 j = none ↔ S.peer r (y, j) = none := by + simp [M, patternAt, t, Scheme.peer, Scheme.pattern, y] + rw [peer] + change 0 < S.width r (y, j) ∧ _ ↔ _ + constructor + · rintro ⟨hw, hp⟩ + obtain ⟨w, he⟩ := p.cover ⟨(y, j), ⟨0, hw⟩⟩ + change p.vertex w = y at he + exact ⟨⟨(w, j), by rw [he]; exact ⟨hw, hp⟩⟩, (hv w).mp he, rfl⟩ + · rintro ⟨⟨⟨w, s⟩, hs⟩, hw, rfl⟩ + rwa [← (hv w).mpr hw] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +end + +/- +# Identifying the active atoms of a contraction locally + +Search only the two-hop neighborhood of the receiving position. +Checkers are counted once by their stamp even if many untouched rows +name the same occurrence. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting + +open Coloring Packing Navigation.Emission Finset + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} + {u h : ℕ} {S : Scheme F} {r : S.format.obj} + {G : HostNet F L h u} (p : S.Posting r G) (hu : 0 < u) + (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' (G.regroup a ha).load) + (m : Matchings a ha g) (ctl : p.Controls hu a ha g m) (col : Bool) + (v : Site (G.V × Cell a) (h - a)) + +local notation "H" => G.regroup a ha +local notation "q" => p.navigation hu a ha +local notation "c" => p.chart hu a ha g m ctl +local notation "nav" => p.groupNav a +local notation "data" => p.records a ha g m.color +local notation "recv" => p.recv a ha +local notation "key" => Navigation.AtomKey S.d S.e (h - a) +local notation "row" => (G.V × Cell a) × B (h - a + S.e) + +open scoped Classical in +private theorem checker_at (e : (H).E) (s : Bool) : + let j := (c).row e + let ends := Match.localEnds nav data col j.1 j.2 + Match.readPath nav j.1 (cond s ends.2 ends.1) = + (c).site (g.route m col (Scheme.side H e s) ((H).ix e)) := by + have he := (c).endpoints col e + cases s + · exact congrArg Prod.fst he + · exact congrArg Prod.snd he + +open scoped Classical in +private theorem checker_key (e : (H).E) (s : Bool) : + let j := (c).row e + (q).atomKey g m col (Navigation.stubAtom g m e s) = + checker (tipAt nav data recv col j.1 j.2 s).1 := + congrArg (fun t : Tip S.d S.e (h - a) => checker (w + := S.e) t.1) (p.tip_eq hu a ha g m ctl col e s) + +open scoped Classical in +/-- The reported of type `Prop` for the given inputs. -/ +def Reported (j : key) : Prop := + (∃ w ∈ (q).neighborhood v.1, ∃ b, + (∃ i, 0 < (p.patternAt a ha w b).width 0 i) ∧ + Match.follow nav w (Match.action col (data w) b) = (c).site v ∧ + station (stampAt nav data recv col w b) = j) ∨ + (∃ t : row, t.1 ∈ (q).neighborhood v.1 ∧ ∃ i, + (Match.rows (data t.1)).control.1 t.2 = true ∧ + Match.readPath nav t.1 (Match.localParties nav data col t.1 t.2 i) = (c).site v ∧ + party col (partyTips nav data recv col t.1 t.2) i = j) ∨ + (∃ t : row, t.1 ∈ (q).neighborhood v.1 ∧ ∃ s : Bool, + Match.untouched data t = true ∧ + (let ends := Match.localEnds nav data col t.1 t.2 + Match.readPath nav t.1 (cond s ends.2 ends.1) = (c).site v) ∧ + checker (tipAt nav data recv col t.1 t.2 s).1 = j) + +open scoped Classical in +theorem atom_image (j : key) : + j ∈ univ.map ((q).atomNames g m col v) ↔ p.Reported hu a ha g m ctl col v j := by + have mark (w : (H).V) (b : Cell (h - a)) := p.stamp_eq hu a ha g m ctl col w b + have role (t : m.items) (i : Fin 6) : + (q).atomKey g m col (.inr (.inl ⟨t, i⟩)) = + party col (partyTips nav data recv col ((c).marked t).1 ((c).marked t).2) i := + ((q).atom_party g m col t i).trans + (congrArg (fun y => party col y i) (p.tips_eq hu a ha g m ctl col t)) + constructor + · intro he + obtain ⟨⟨t, hv⟩, _, hj⟩ := mem_map.mp he + simp only [HostNet.receipts, mem_filter, mem_univ, true_and] at hv + obtain ⟨ht, hw⟩ := hv + change (q).atomKey g m col t = j at hj + rcases t with t|⟨t, i⟩|t + · let y := (H).units.place t + change g.route m col y.1 y.2 = v at hw + refine .inl ⟨y.1, hw ▸ (q).window_move g m col y.1 y.2, cellIndex _ y.2, ?_, ?_, ?_⟩ + · exact (p.occupied_iff a ha _ _).mpr ⟨t, ht, by rw [Equiv.symm_apply_apply]; rfl⟩ + · exact ((c).moved col _ _).trans (congrArg (c).site hw) + · exact (congrArg station (mark _ _)).symm.trans hj + · change g.party m col t i = v at hw + exact .inr (.inl ⟨(c).marked t, hw ▸ (q).window_party g m col t i, i, + ((c).marks _).mpr ⟨t, rfl⟩, ((c).gadget col t i).trans (congrArg _ hw), + (role _ _).symm.trans hj⟩) + · obtain ⟨e, he⟩ := ht + obtain ⟨s, rfl⟩ : ∃ s, (Scheme.side H e.val s, (H).ix e.val) = t := by + rcases he with he|he + · exact ⟨false, he⟩ + · exact ⟨true, he⟩ + change g.route m col (Scheme.side H e.val s) ((H).ix e.val) = v at hw + exact .inr (.inr ⟨(c).row e.val, hw ▸ (q).window_end g m col e.val s, s, + ((c).untouched_iff _).mpr ⟨e, rfl⟩, + (p.checker_at hu a ha g m ctl col e.val s).trans (congrArg _ hw), + (p.checker_key hu a ha g m ctl col e.val s).symm.trans hj⟩) + · have put (i : (H).Atom g m) (hi : (H).live g m i) + (hv : (H).anchor g m col i = v) (hk : (q).atomKey g m col i = j) : + j ∈ univ.map ((q).atomNames g m col v) := + mem_map.mpr ⟨⟨i, by + simp only [HostNet.receipts, mem_filter, mem_univ, true_and] + exact ⟨hi, hv⟩⟩, mem_univ _, hk⟩ + rintro (⟨w, _, b, ht, hs, hk⟩|⟨t, _, i, ht, hs, hk⟩|⟨t, _, i, ht, hs, hk⟩) + · obtain ⟨b, rfl⟩ := (cellIndex _).surjective b + obtain ⟨u, hu', he⟩ := (p.occupied_iff _ _ _ _).mp ht + rw [Equiv.symm_apply_apply] at he + refine put (.inl u) hu' ?_ ?_ + · change g.route m col ((H).units.place u).1 ((H).units.place u).2 = v + rw [he] + exact (c).site.injective (((c).moved col w b).symm.trans hs) + · exact ((q).atom_station g m col u).trans ((congrArg + (fun t => station ((q).stamp g m col t)) he).trans ((congrArg station (mark w b)).trans + hk)) + · obtain ⟨t, rfl⟩ := ((c).marks _).mp ht + exact put (.inr (.inl ⟨t, i⟩)) trivial + ((c).site.injective (((c).gadget col t i).symm.trans hs)) ((role _ _).trans hk) + · obtain ⟨e, rfl⟩ := ((c).untouched_iff _).mp ht + refine put (Navigation.stubAtom (G := H) g m e.val i) ?_ + ((c).site.injective ((p.checker_at hu a ha g m ctl col e.val i).symm.trans hs)) + ((p.checker_key hu a ha g m ctl col e.val i).trans hk) + refine ⟨e, ?_⟩ + cases i + · exact .inl rfl + · exact .inr rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +end + +/- # Compact keys of incident spans before local numbering -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +open Coloring Packing History.Subround + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h z d : ℕ} + (P : Gadget F) {G : HostNet F L h (P.b * z)} {S : Scheme F} {r : S.format.obj} + (q : Navigation G d S.e) + {Δ D k : ℕ} {B' : ℝ} (g : Grouping G.N G.C Δ D k B' G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) (i : g.Choice m P) + (p : S.Presentation r G.diagram) (v : Site G.V h) + +open scoped Classical in +/-- In the case `.inl u`, this construction gives `(false, q.faceKey P G g m i p u.val)`. -/ +def portKey : PortMap.Port g m P G.units i p v → Bool × SpanKey d S.e h P.b + | .inl u => (false, q.faceKey P G g m i p u.val) + | .inr u => (true, q.hiddenKey g m P i u.val) + +local notation "col" => g.layout m P i + +open scoped Classical in +theorem portKey_exterior (e : p.BorderSpan) (he : g.assign m P G.units i e.val.1 = v) : + q.portKey P g m i p v (PortMap.exterior g m P G.units i p v e he) = + (false, Emission.exterior (q.stamp g m col (G.units.place e.val.1)) e.val.2) := rfl + +open scoped Classical in +theorem portKey_demand (e : G.E) (t : Bool) + (he : g.route m col (cond t (G.dst e) (G.src e)) (G.ix e) = v) : + q.portKey P g m i p v (PortMap.demand g m P G.units i p v e t he) = + (true, Emission.demand (q.tip g m col e t) t) := by cases t <;> rfl + +open scoped Classical in +theorem portKey_supply (e : g.Supply m P i) (t : Bool) + (he : PortMap.supplySite g m P i e t = v) : + q.portKey P g m i p v (PortMap.supply g m P G.units i p v e t he) = + Emission.pointer col (q.eventTips g m col P i e) (eventKind g m P i e) + (decide ((g.contact m col e).1 = (g.contact m col e).2)) t := by + by_cases h : (g.contact m col e).1 = (g.contact m col e).2 + · rw [PortMap.supply, dite_eq_left h, decide_eq_true h] + exact q.hidden_new g m P i e t + · rw [PortMap.supply, dite_eq_right h, decide_eq_false h] + exact q.visible_new P G g m i p ⟨e, h⟩ t + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation +end + +/- # Recovering all hidden and visible keys from active records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation.Emission +open Coloring + +variable {V : Type} {d h w ℓ b : ℕ} (nav : V → B d → V) + (data : V → (Match.Input d h w w ℓ).obj) (col : Bool) + +/-- The old at of type `V × B ℓ`, constructed using `Match.localEnds nav data col j.1 j.2`. -/ +def oldAt (j : V × B (h + w)) (s : Bool) : V × B ℓ := + let ends := Match.localEnds nav data col j.1 j.2 + Match.readPath nav j.1 (cond s ends.2 ends.1) + +/-- The new at of type `V × B ℓ`, constructed using `Match.paths nav data col j`. -/ +def newAt (j : Match.Candidate V (h + w) b) (s : Bool) : V × B ℓ := + let ends := Match.paths nav data col j + Match.readPath nav j.1.1 (cond s ends.2 ends.1) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Navigation.Emission + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +open Coloring Packing Navigation.Emission Finset + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} + {h z : ℕ} {P : Gadget F} {S : Scheme F} {r : S.format.obj} + {G : HostNet F L h (P.b * z)} (p : S.Posting r G) + (hu : 0 < P.b * z) (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' (G.regroup a ha).load) + (m : Matchings a ha g) (ctl : p.Controls hu a ha g m) (i : g.Choice m P) + +local notation "H" => G.regroup a ha +local notation "q" => p.navigation hu a ha +local notation "c" => p.chart hu a ha g m ctl +local notation "col" => g.layout m P i +local notation "data" => p.records a ha g m.color + +local notation "nav" => p.groupNav a +local notation "candidate" => Match.Candidate (G.V × Cell a) (h - a + S.e) P.b + +open scoped Classical in +theorem oldAt_eq (t : (H).E) (s : Bool) : + oldAt nav data col ((c).row t) s = + (c).site (g.route m col (Scheme.side H t s) ((H).ix t)) := by + have he := (c).endpoints col t + cases s + · exact congrArg Prod.fst he + · exact congrArg Prod.snd he + +open scoped Classical in +theorem newAt_eq (t : g.Supply m P i) (s : Bool) : + newAt nav data col ((c).event P i t) s = + (c).site (cond s (g.contact m col t).2 (g.contact m col t).1) := by + have he := (c).read_event P i col t + cases s + · exact congrArg Prod.fst he + · exact congrArg Prod.snd he + +open scoped Classical in +theorem old_key (t : (H).E) (s : Bool) : + let j := (c).row t + (q).hiddenKey g m P i (cond s (.inr (.inl t)) (.inl t)) = + demand (tipAt nav data (p.recv a ha) col j.1 j.2 s) s := + ((q).hidden_old g m P i t s).trans + (congrArg (fun x => demand x s) (p.tip_eq hu a ha g m ctl col t s)) + +open scoped Classical in +theorem supply_key (t : g.Supply m P i) (s : Bool) : + let j := (c).event P i t + (q).supplyKey g m col P i t s = + supply col (supplyTips nav data (p.recv a ha) col j) j.2 s := + ((q).supply_eq g m col P i t s).trans (congrArg₂ (fun x y => supply col x y s) + (p.eventTips_eq hu a ha g m ctl col P i t) (p.eventKind_eq hu a ha g m ctl P i t)) + +variable (shape : (G.V × Cell a) × B (h - a + S.e) → Fin 8 → ℕ) + (code : ∀ t, shape ((p.chart hu a ha g m ctl).marked t) = g.profile m i t) + (v : Site (G.V × Cell a) (h - a)) (j : Navigation.SpanKey S.d S.e (h - a) P.b) + +open scoped Classical in +private theorem in_window (t : g.Supply m P i) (s : Bool) + (he : cond s (g.contact m col t).2 (g.contact m col t).1 = v) : + ((c).event P i t).1.1 ∈ (q).neighborhood v.1 := by + have hs := (q).window_supply g m col P i t s + subst v + rcases t with ⟨t, j, l⟩ | ⟨t, l⟩ <;> exact hs + +include code in +open scoped Classical in +theorem hidden_image : + j ∈ univ.map ((q).hiddenNames g m P i v) ↔ + (∃ (t : (G.V × Cell a) × B (h - a + S.e)) (s : Bool), + t.1 ∈ (q).neighborhood v.1 ∧ (Match.rows (data t.1)).active t.2 = true + ∧ oldAt nav data col t s = (c).site v ∧ + demand (tipAt nav data (p.recv a ha) col t.1 t.2 s) s = j) ∨ + (∃ t : candidate, t.1.1 ∈ (q).neighborhood v.1 ∧ Match.enabled data shape t = true ∧ + newAt nav data col t false = (c).site v ∧ newAt nav data col t true = (c).site v ∧ + .inr (supply col (supplyTips nav data (p.recv a ha) col t) t.2 false) = j) := by + have old := p.oldAt_eq hu a ha g m ctl i + have new := p.newAt_eq hu a ha g m ctl i + have first := p.old_key hu a ha g m ctl i + have second := p.supply_key hu a ha g m ctl i + have win (t : (H).E) (s : Bool) (he : g.route m col (Scheme.side H t s) ((H).ix t) = v) : + ((c).row t).1 ∈ (q).neighborhood v.1 := by + rw [← he] + exact (q).window_end g m col t s + constructor + · intro hj + obtain ⟨⟨t|t|t, ht⟩, _, he⟩ := mem_map.mp hj + · exact .inl ⟨(c).row t, false, win t false (congrArg Prod.fst ht), ((c).active _).mpr ⟨t, rfl⟩, + (old t false).trans (congrArg (c).site (congrArg Prod.fst ht)), + (first t false).symm.trans he⟩ + · exact .inl ⟨(c).row t, true, win t true (congrArg Prod.fst ht), ((c).active _).mpr ⟨t, rfl⟩, + (old t true).trans (congrArg (c).site (congrArg Prod.fst ht)), (first t true).symm.trans he⟩ + · exact .inr ⟨(c).event P i t, p.in_window hu a ha g m ctl i v t false (congrArg Prod.fst ht), + ((c).enabled_iff P i shape code _).mpr ⟨t, rfl⟩, + (new t false).trans (congrArg (c).site (congrArg Prod.fst ht)), + (new t true).trans (congrArg (c).site (congrArg Prod.snd ht)), + (congrArg Sum.inr (second t false).symm).trans he⟩ + · rintro (⟨j, s, _, hj, hv, he⟩|⟨j, _, hj, hv, hw, he⟩) + · obtain ⟨t, rfl⟩ := ((c).active j).mp hj + have hm := (c).site.injective ((old t s).symm.trans hv) + have hloc : History.Subround.ends g m P i (cond s (.inr (.inl t)) (.inl t)) = (v, v) := by + cases s <;> exact Prod.ext hm hm + exact mem_map.mpr ⟨⟨_, hloc⟩, mem_univ _, (first t s).trans he⟩ + · obtain ⟨t, rfl⟩ := ((c).enabled_iff P i shape code j).mp hj + have hloc : g.contact m col t = (v, v) := Prod.ext + ((c).site.injective ((new t false).symm.trans hv)) + ((c).site.injective ((new t true).symm.trans hw)) + exact mem_map.mpr ⟨⟨.inr (.inr t), hloc⟩, mem_univ _, + (congrArg Sum.inr (second t false)).trans he⟩ + +include code in +open scoped Classical in +theorem visible_image : + j ∈ univ.map ((q).visibleNames P H g m i p.toPresentation v) ↔ + (∃ (w : G.V × Cell a) (b : B (h - a)) (s : B S.e), w ∈ (q).neighborhood v.1 ∧ + (0 < (p.patternAt a ha w b).width 0 s ∧ (p.patternAt a ha w b).peer 0 s = none) ∧ + Match.follow nav w (Match.action col (data w) b) = (c).site v ∧ + exterior (stampAt nav data (p.recv a ha) col w b) s = j) ∨ + (∃ (t : candidate) (s : Bool), t.1.1 ∈ (q).neighborhood v.1 ∧ + Match.enabled data shape t = true ∧ newAt nav data col t s = (c).site v ∧ + newAt nav data col t false ≠ newAt nav data col t true ∧ + .inr (supply col (supplyTips nav data (p.recv a ha) col t) t.2 s) = j) := by + have new := p.newAt_eq hu a ha g m ctl i + have key := p.supply_key hu a ha g m ctl i + have border (t : p.toPresentation.BorderSpan) := (q).visible_old P H g m i p.toPresentation t + have loc (w : G.V × Cell a) (b : Cell (h - a)) : + Match.follow nav w (Match.action col (data w) (cellIndex _ b)) = (c).site (g.route m col w b) + := + (c).moved col w b + constructor + · intro hj + obtain ⟨⟨t|⟨t, s⟩, ht⟩, _, he⟩ := mem_map.mp hj + · let w := (H).units.place t.val.1 + change g.route m col w.1 w.2 = v at ht + have win := (q).window_move g m col w.1 w.2 + refine .inl ⟨w.1, cellIndex _ w.2, t.val.2, ?_, ?_, (loc _ _).trans (congrArg (c).site ht), + ?_⟩ + · rw [← ht] + exact win + · apply (p.border_iff a ha _ _ _).mpr + exact ⟨t, by rw [Equiv.symm_apply_apply]; rfl, rfl⟩ + · exact (congrArg (fun z => exterior z t.val.2) + (p.stamp_eq hu a ha g m ctl col w.1 w.2).symm).trans ((border t).symm.trans he) + · refine .inr ⟨(c).event P i t.val, s, p.in_window hu a ha g m ctl i v t.val s ht, + ((c).enabled_iff P i shape code _).mpr ⟨t.val, rfl⟩, + (new t.val s).trans (congrArg (c).site ht), + ?_, (congrArg Sum.inr (key t.val s).symm).trans he⟩ + exact fun e => t.property ((c).site.injective ((new t.val false).symm.trans (e.trans (new + t.val true)))) + · rintro (⟨w, b, s, _, hb, hv, he⟩|⟨t, s, _, ht, hv, hw, he⟩) + · obtain ⟨b, rfl⟩ := (cellIndex (h - a)).surjective b + obtain ⟨j, hj, rfl⟩ := (p.border_iff a ha w _ s).mp hb + rw [Equiv.symm_apply_apply] at hj + have hroute := (c).site.injective ((loc w b).symm.trans hv) + have hwhere : History.Subround.whereAt g m P (H).units i p.toPresentation (.inl j) = v := by + change g.route m col ((H).units.place j.val.1).1 ((H).units.place j.val.1).2 = v + rw [hj] + exact hroute + refine mem_map.mpr ⟨⟨.inl j, hwhere⟩, mem_univ _, (border j).trans ?_⟩ + rw [hj] + exact (congrArg (fun z => exterior z j.val.2) (p.stamp_eq hu a ha g m ctl col w b)).trans he + · obtain ⟨t, rfl⟩ := ((c).enabled_iff P i shape code t).mp ht + have hne : (g.contact m col t).1 ≠ (g.contact m col t).2 := fun e => + hw ((new t false).trans ((congrArg (c).site e).trans (new t true).symm)) + have hwhere := (c).site.injective ((new t s).symm.trans hv) + exact mem_map.mpr ⟨⟨.inr (⟨t, hne⟩, s), hwhere⟩, mem_univ _, + (congrArg Sum.inr (key t s)).trans he⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +end + +/- # Comparing destination names in two local coordinate systems -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +open Coloring Match Navigation.Emission + +variable {V W X : Type} {d h e ℓ n : ℕ} {α : Env V X d h e ℓ} {β : Env W X d h e ℓ} + +open scoped Classical in +/-- Indexes the issuers by the coordinates of `Finset.univ.image fun i : Option (B d) × Option +(B d) => let v := i.1.elim α.root (α.nav α.root) i.2.elim v (α.nav v)`. -/ +def Env.issuers (α : Env V X d h e ℓ) := + Finset.univ.image fun i : Option (B d) × Option (B d) => + let v := i.1.elim α.root (α.nav α.root) + i.2.elim v (α.nav v) + +open scoped Classical in +theorem Related.issuers {v : V} (hv : v ∈ α.issuers) : + ∃ w ∈ β.issuers, Related α β 2 v w := by + obtain ⟨⟨i, j⟩, _, rfl⟩ := Finset.mem_image.mp hv + refine ⟨_, Finset.mem_image_of_mem _ (Finset.mem_univ (i, j)), ?_⟩ + have r : Related α β 0 α.root β.root := related_root + cases i <;> cases j + · exact r.widen (by decide) + · exact (r.next _).widen (by decide) + · exact (r.next _).widen (by decide) + · exact (r.next _).next _ + +open scoped Classical in +/-- The value specified by `Related α β 4 x.1 y.1 ∧ x.2 = y.2`. -/ +def Names (α : Env V X d h e ℓ) (β : Env W X d h e ℓ) (x : V × B ℓ) (y : W × B ℓ) := + Related α β 4 x.1 y.1 ∧ x.2 = y.2 + +open scoped Classical in +theorem names_root (i : B ℓ) : Names α β (α.root, i) (β.root, i) := + ⟨related_root.widen (by decide), rfl⟩ + +variable (a : Agree α β 4) {v : V} {w : W} (r : Related α β 2 v w) + +include a in +open scoped Classical in +theorem Agree.identical {x x' : V × B ℓ} {y y' : W × B ℓ} + (h₁ : Names α β x y) (h₂ : Names α β x' y') : + x = x' ↔ y = y' := by + rw [Prod.ext_iff, Prod.ext_iff, a.equal h₁.1 h₂.1, h₁.2, h₂.2] + +include a r + +open scoped Classical in +theorem Agree.motion (c : Bool) (b : B h) : + Names α β (follow α.nav v (action c (α.data v) b)) (follow β.nav w (action c (β.data w) b)) + := by + rw [(a.records r (by decide)).1] + exact ⟨(r.follow _).widen (by decide), rfl⟩ + +omit a in +open scoped Classical in +private theorem related_path (p : (Match.Path d ℓ).obj) : + Names α β (readPath α.nav v p) (readPath β.nav w p) := + ⟨r.path p, rfl⟩ + +open scoped Classical in +theorem Agree.gadget (c : Bool) (i : B (h + e)) (j : Fin 6) : + Names α β (readPath α.nav v (localParties α.nav α.data c v i j)) + (readPath β.nav w (localParties β.nav β.data c w i j)) := by + rw [a.parties r (by decide)] + exact related_path r _ + +open scoped Classical in +theorem Agree.oldAt (c : Bool) (i : B (h + e)) (s : Bool) : + Names α β (oldAt α.nav α.data c (v, i) s) (oldAt β.nav β.data c (w, i) s) := by + unfold Navigation.Emission.oldAt + rw [a.ends r (by decide)] + exact related_path r _ + +open scoped Classical in +theorem Agree.newAt (c : Bool) (i : B (h + e)) {b : ℕ} (j : Kind b) (s : Bool) : + Names α β (newAt α.nav α.data c ((v, i), j) s) (newAt β.nav β.data c ((w, i), j) s) := by + unfold Navigation.Emission.newAt + rw [a.paths r (by decide)] + exact related_path r _ + +open scoped Classical in +theorem Agree.untouched (i : B (h + e)) : + Match.untouched α.data (v, i) = Match.untouched β.data (w, i) := by + simp only [Match.untouched, (a.records r (by decide)).1] + +open scoped Classical in +theorem Agree.enabled (f : X → B (h + e) → Fin 8 → ℕ) (i : B (h + e)) {b : ℕ} (j : Kind b) : + Match.enabled α.data (fun t => f (α.extra t.1) t.2) ((v, i), j) = + Match.enabled β.data (fun t => f (β.extra t.1) t.2) ((w, i), j) := by + rcases j with ⟨j, k⟩|k + · simp only [Match.enabled, (a.records r (by decide)).1, (a.records r (by decide)).2.2] + · exact a.untouched r i + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +end + +/- +# Receipt lists depend only on the rooted window + +The candidate issuer is at distance at most two; reading either of +its endpoints needs at most two more hops. Raw names are compared +locally, without storing absolute host addresses. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +open Coloring Navigation Navigation.Emission Match + +variable {V W X F : Type} {d h e ℓ k b : ℕ} {α : Env V X d h e ℓ} {β : Env W X d h e ℓ} + +open scoped Classical in +private theorem issuer_exists {f : V → Prop} {g : W → Prop} + (hh : ∀ v w, Related α β 2 v w → (f v ↔ g w)) : + (∃ v ∈ α.issuers, f v) ↔ ∃ w ∈ β.issuers, g w := by + constructor + · rintro ⟨v, hv, hf⟩ + obtain ⟨w, hw, r⟩ := Related.issuers (β := β) hv + exact ⟨w, hw, (hh v w r).mp hf⟩ + · rintro ⟨w, hw, hg⟩ + obtain ⟨v, hv, p, hp, e, f⟩ := Related.issuers (β := α) hw + exact ⟨v, hv, (hh v w ⟨p, hp, f, e⟩).mpr hg⟩ + +open scoped Classical in +private theorem row_exists {A : Type} {f : V × A → Prop} {g : W × A → Prop} + (hh : ∀ v w, Related α β 2 v w → ∀ i, f (v, i) ↔ g (w, i)) : + (∃ v, v.1 ∈ α.issuers ∧ f v) ↔ ∃ w, w.1 ∈ β.issuers ∧ g w := by + simp only [Prod.exists, exists_and_left] + exact issuer_exists fun v w r => exists_congr (hh v w r) + +open scoped Classical in +private theorem event_exists {A Z : Type} {f : (V × A) × Z → Prop} {g : (W × A) × Z → Prop} + (hh : ∀ v w, Related α β 2 v w → ∀ i j, f ((v, i), j) ↔ g ((w, i), j)) : + (∃ v, v.1.1 ∈ α.issuers ∧ f v) ↔ ∃ w, w.1.1 ∈ β.issuers ∧ g w := by + simp only [Prod.exists, exists_and_left] + exact issuer_exists fun v w r => exists_congr fun i => exists_congr (hh v w r i) + +variable (pattern : X → B h → Pattern F d k e) (shape : X → B (h + e) → Fin 8 → ℕ) + +namespace Env +variable (α : Env V X d h e ℓ) (col : Bool) (u : B ℓ) + +open scoped Classical in +/-- The atoms of type `Prop` for the given inputs. -/ +def atoms (j : AtomKey d e h) : Prop := + (∃ w ∈ α.issuers, ∃ i, + (∃ k, 0 < (pattern (α.extra w) i).width 0 k) ∧ + follow α.nav w (action col (α.data w) i) = (α.root, u) ∧ + station (α.stamp col w i) = j) ∨ + (∃ t : V × B (h + e), t.1 ∈ α.issuers ∧ ∃ i, + (rows (α.data t.1)).control.1 t.2 = true ∧ + readPath α.nav t.1 (localParties α.nav α.data col t.1 t.2 i) = (α.root, u) ∧ + party col (α.tips col t.1 t.2) i = j) ∨ + (∃ t : V × B (h + e), t.1 ∈ α.issuers ∧ ∃ s : Bool, untouched α.data t = true ∧ + oldAt α.nav α.data col t s = (α.root, u) ∧ checker (α.tip col t.1 t.2 s).1 = j) + +open scoped Classical in +/-- The hidden of type `Prop` for the given inputs. -/ +def hidden (j : SpanKey d e h b) : Prop := + (∃ (t : V × B (h + e)) (s : Bool), t.1 ∈ α.issuers ∧ (rows (α.data t.1)).active t.2 = true ∧ + oldAt α.nav α.data col t s = (α.root, u) ∧ demand (α.tip col t.1 t.2 s) s = j) ∨ + (∃ t : Candidate V (h + e) b, t.1.1 ∈ α.issuers ∧ + enabled α.data (fun t => shape (α.extra t.1) t.2) t = true ∧ + newAt α.nav α.data col t false = (α.root, u) ∧ newAt α.nav α.data col t true = (α.root, u) ∧ + .inr (supply col (α.supplies col t) t.2 false) = j) + +open scoped Classical in +/-- The visible of type `Prop` for the given inputs. -/ +def visible (j : SpanKey d e h b) : Prop := + (∃ (w : V) (i : B h) (t : B e), w ∈ α.issuers ∧ + (0 < (pattern (α.extra w) i).width 0 t ∧ (pattern (α.extra w) i).peer 0 t = none) ∧ + follow α.nav w (action col (α.data w) i) = (α.root, u) ∧ + exterior (α.stamp col w i) t = j) ∨ + (∃ (t : Candidate V (h + e) b) (s : Bool), t.1.1 ∈ α.issuers ∧ + enabled α.data (fun t => shape (α.extra t.1) t.2) t = true ∧ + newAt α.nav α.data col t s = (α.root, u) ∧ + newAt α.nav α.data col t false ≠ newAt α.nav α.data col t true ∧ + .inr (supply col (α.supplies col t) t.2 s) = j) +end Env + +variable (a : Agree α β 4) (col : Bool) (u : B ℓ) +include a + +open scoped Classical in +theorem Agree.atoms (j : AtomKey d e h) : + α.atoms pattern col u j ↔ β.atoms pattern col u j := by + unfold Env.atoms + refine or_congr ?_ (or_congr ?_ ?_) + · refine issuer_exists fun v w r => exists_congr fun i => ?_ + rw [a.identical (a.motion r col i) (names_root u), a.stamp r (by decide), + (a.records r (by decide)).2.2] + · refine row_exists fun v w r i => exists_congr fun t => ?_ + rw [a.identical (a.gadget r col i t) (names_root u), a.tips r (by decide), + (a.records r (by decide)).1] + · refine row_exists fun v w r i => exists_congr fun t => ?_ + rw [a.identical (a.oldAt r col i t) (names_root u), a.tip r (by decide), a.untouched r] + +open scoped Classical in +theorem Agree.hidden (j : SpanKey d e h b) : + α.hidden shape col u j ↔ β.hidden shape col u j := by + unfold Env.hidden + refine or_congr ?_ ?_ + · simp only [exists_and_left] + refine row_exists fun v w r i => and_congr (by rw [(a.records r (by decide)).1]) + (exists_congr fun t => ?_) + rw [a.identical (a.oldAt r col i t) (names_root u), a.tip r (by decide)] + · refine event_exists fun v w r i t => ?_ + rw [a.identical (a.newAt r col i t false) (names_root u), + a.identical (a.newAt r col i t true) (names_root u), a.enabled r, a.supplies r (by decide)] + +open scoped Classical in +theorem Agree.visible (j : SpanKey d e h b) : + α.visible pattern shape col u j ↔ β.visible pattern shape col u j := by + unfold Env.visible + refine or_congr ?_ ?_ + · simp only [exists_and_left] + refine issuer_exists fun v w r => exists_congr fun i => exists_congr fun t => ?_ + rw [a.identical (a.motion r col i) (names_root u), a.stamp r (by decide), + (a.records r (by decide)).2.2] + · simp only [exists_and_left] + refine event_exists fun v w r i t => and_congr (by rw [a.enabled r]) (exists_congr fun s => ?_) + simp only [ne_eq] + rw [a.identical (a.newAt r col i t s) (names_root u), + not_congr (a.identical (a.newAt r col i t false) (a.newAt r col i t true)), + a.supplies r (by decide)] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Window +end + +/- # Recovering the three compact-name dictionaries from a local window -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing Finset + +namespace Window + +open scoped Classical in +/-- Indexes the lists by the coordinates of `Finset (Navigation.AtomKey d w h) × Finset +(Navigation.SpanKey d w h b) × Finset (Navigation.SpanKey d w h b)`. -/ +abbrev Lists (d w h b : ℕ) := Finset (Navigation.AtomKey d w h) × + Finset (Navigation.SpanKey d w h b) × Finset (Navigation.SpanKey d w h b) + +variable {V W X F : Type} {d h e ℓ k b : ℕ} + (pattern : X → B h → Pattern F d k e) (shape : X → B (h + e) → Fin 8 → ℕ) + +open scoped Classical in +/-- The selected finite family `(univ.filter (α.atoms pattern col key), univ.filter (α.hidden +shape col key), univ.filter (α.visible pattern shape col key))`. -/ +def Env.lists (α : Env V X d h e ℓ) (col : Bool) (key : B ℓ) : Lists d e h b := + (univ.filter (α.atoms pattern col key), univ.filter (α.hidden shape col key), + univ.filter (α.visible pattern shape col key)) + +open scoped Classical in +theorem Agree.lists {α : Env V X d h e ℓ} {β : Env W X d h e ℓ} (ha : Agree α β 4) + (col : Bool) (key : B ℓ) : + α.lists (b := b) pattern shape col key = β.lists pattern shape col key := by + refine Prod.ext ?_ (Prod.ext ?_ ?_) + · ext i + simp only [Env.lists, mem_filter, mem_univ, true_and] + exact ha.atoms pattern _ _ _ + · ext i + simp only [Env.lists, mem_filter, mem_univ, true_and] + exact ha.hidden shape _ _ _ + · ext i + simp only [Env.lists, mem_filter, mem_univ, true_and] + exact ha.visible pattern shape _ _ _ + +end Window + +namespace Scheme.Posting + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} + {h z : ℕ} {P : Gadget F} {S : Scheme F} {r : S.format.obj} + {G : HostNet F L h (P.b * z)} (p : S.Posting r G) + (hu : 0 < P.b * z) (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' (G.regroup a ha).load) + (m : Matchings a ha g) (ctl : p.Controls hu a ha g m) (i : g.Choice m P) + +local notation "H" => G.regroup a ha +local notation "q" => p.navigation hu a ha +local notation "c" => p.chart hu a ha g m ctl +local notation "col" => g.layout m P i + +open scoped Classical in +/-- Indexes the detail by the coordinates of `(B n → B S.ℓ) × (B (n + S.e) → J)`. -/ +abbrev Detail (S : Scheme F) (J : Type) (n : ℕ) := + (B n → B S.ℓ) × (B (n + S.e) → J) + +variable {J : Type} (selector : (G.V × Cell a) × B (h - a + S.e) → J) + (profile : J → Fin 8 → ℕ) (v : Site (G.V × Cell a) (h - a)) + +open scoped Classical in +/-- Builds `Window.Env (G.V × Cell a) (Detail S J (h - a)) S.d (h - a) S.e (h - a + 1) where +root` with the specified `root`, `nav`, `data`, `recv`. -/ +def environment : Window.Env (G.V × Cell a) (Detail S J (h - a)) S.d (h - a) S.e (h - a + 1) where + root := v.1 + nav := p.groupNav a + data := p.records a ha g m.color + recv := p.recv a ha + extra w := (fun b => (r (p.host w.1)).2 (p.block ((splitCell a ha).symm (w.2, + (cellIndex _).symm b))), + fun j => selector (w, j)) + +open scoped Classical in +/-- The dictionaries of type `Window.Lists S.d S.e (h - a) P.b` for the given inputs. -/ +def dictionaries : Window.Lists S.d S.e (h - a) P.b := + (univ.map ((q).atomNames g m col v), univ.map ((q).hiddenNames g m P i v), + univ.map ((q).visibleNames P H g m i p.toPresentation v)) + +open scoped Classical in +theorem dictionaries_eq (code : ∀ t, profile (selector ((c).marked t)) = g.profile m i t) : + p.dictionaries hu a ha g m i v = + (p.environment a ha g m selector v).lists + (fun t b => S.decode (t.1 b)) (fun t j => profile (t.2 j)) col (intervalCode _ v.2) := by + refine Prod.ext ?_ (Prod.ext ?_ ?_) + · ext j + simp only [dictionaries, Window.Env.lists, mem_filter, mem_univ, true_and] + exact p.atom_image hu a ha g m ctl col v j + · ext j + simp only [dictionaries, Window.Env.lists, mem_filter, mem_univ, true_and] + exact p.hidden_image hu a ha g m ctl i (profile ∘ selector) code v j + · ext j + simp only [dictionaries, Window.Env.lists, mem_filter, mem_univ, true_and] + exact p.visible_image hu a ha g m ctl i (profile ∘ selector) code v j + +end Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Comparing two contracted occurrences + +Each occurrence may come from a different original diagram and group. +Only the common pattern menu, gadget and scales are shared. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing + +variable {F : Type} [Field F] + +open scoped Classical in +/-- Indexes the choice tag by the coordinates of `Option (Fin P.copies × ↥P.shapes)`. -/ +abbrev ChoiceTag (P : Gadget F) := Option (Fin P.copies × ↥P.shapes) + +open scoped Classical in +/-- Evaluates `q.elim (fun _ => 0) (fun i => i.2.val)` at the input `q`. -/ +def profileOf (P : Gadget F) : ChoiceTag P → Fin 8 → ℕ := + fun q => q.elim (fun _ => 0) (fun i => i.2.val) + +open scoped Classical in +/-- The data for the state construction, including `T`, `[finite`, `x`, `y`, `L`. -/ +structure State (S : Scheme F) (P : Gadget F) (a h z Δ D k : ℕ) (B' : ℝ) where + /-- The `State` component of type `Type`. -/ + T : Type + [finite : Fintype T] + /-- The `State` component of type `Wire`. -/ + x : Wire + /-- The `State` component of type `Wire`. -/ + y : Wire + /-- The `State` component of type `Fringe x y T`. -/ + L : Fringe x y T + /-- The `State` component of type `HostNet F L h (P.b * z)`. -/ + G : HostNet F L h (P.b * z) + /-- The `State` component of type `S.format.obj`. -/ + r : S.format.obj + /-- The `State` component of type `S.Posting r G`. -/ + p : S.Posting r G + ha : a ≤ h + hz : 0 < z + /-- The `State` component of type `Grouping (G.regroup a ha).N (G.regroup a ha).C Δ D k B' + (G.regroup a ha).load`. -/ + g : Grouping (G.regroup a ha).N (G.regroup a ha).C Δ D k B' (G.regroup a ha).load + /-- The `State` component of type `Scheme.Posting.Matchings a ha g`. -/ + m : Scheme.Posting.Matchings a ha g + ctl : p.Controls (Nat.mul_pos P.pos hz) a ha g m + /-- The `State` component of type `g.Choice m P`. -/ + i : g.Choice m P + /-- The `State` component of type `(G.V × Cell a) × B (h - a + S.e) → ChoiceTag P`. -/ + selector : (G.V × Cell a) × B (h - a + S.e) → ChoiceTag P + selected : ∀ t, selector ((p.chart (Nat.mul_pos P.pos hz) a ha g m ctl).marked t) = some (i t) + /-- The `State` component of type `Site (G.V × Cell a) (h - a)`. -/ + v : Site (G.V × Cell a) (h - a) + +attribute [instance] State.finite + +open scoped Classical in +theorem Window.Agree.restrict {V W X : Type} {d h e ℓ m n : ℕ} + {α : Window.Env V X d h e ℓ} {β : Window.Env W X d h e ℓ} (h : Window.Agree α β n) + (hm : m ≤ n) : Window.Agree α β m := + ⟨fun _ _ hp hq => h.same _ _ (hp.trans hm) (hq.trans hm), + fun _ hp => h.data _ (hp.trans hm), fun _ hp => h.recv _ (hp.trans hm), + fun _ hp => h.extra _ (hp.trans hm)⟩ + +namespace State +variable {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + (u v : State S P a h z Δ D k B') + +include u in +open scoped Classical in +theorem hu : 0 < P.b * z := Nat.mul_pos P.pos u.hz + +open scoped Classical in +/-- Computes the h by the application `u.G.regroup a u.ha`. -/ +abbrev H := u.G.regroup a u.ha +open scoped Classical in +/-- Computes the q by the application `u.p.navigation u.hu a u.ha`. -/ +abbrev q := u.p.navigation u.hu a u.ha +open scoped Classical in +/-- Computes the c by the application `u.p.chart u.hu a u.ha u.g u.m u.ctl`. -/ +abbrev c := u.p.chart u.hu a u.ha u.g u.m u.ctl +open scoped Classical in +/-- Computes the col by the application `u.g.layout u.m P u.i`. -/ +abbrev col := u.g.layout u.m P u.i +open scoped Classical in +/-- Computes the env by the application `u.p.environment a u.ha u.g u.m u.selector u.v`. -/ +abbrev env := u.p.environment a u.ha u.g u.m u.selector u.v +open scoped Classical in +/-- Computes the lists by the application `u.p.dictionaries u.hu a u.ha u.g u.m u.i u.v`. -/ +abbrev lists := u.p.dictionaries u.hu a u.ha u.g u.m u.i u.v + +open scoped Classical in +theorem code (t : u.m.items) : profileOf P (u.selector (u.c.marked t)) = u.g.profile u.m u.i t := by + rw [show u.selector (u.c.marked t) = some (u.i t) from u.selected t] + rfl + +open scoped Classical in +/-- The data for the same construction, including `agree`, `layout`, `key`. -/ +structure Same (n : ℕ) : Prop where + agree : Window.Agree u.env v.env n + layout : u.col = v.col + key : intervalCode _ u.v.2 = intervalCode _ v.v.2 + +variable {u v} {n : ℕ} + +open scoped Classical in +theorem Same.symm (h : u.Same v n) : v.Same u n := ⟨h.agree.symm, h.layout.symm, h.key.symm⟩ + +open scoped Classical in +theorem Same.lists (e : u.Same v n) (hn : 4 ≤ n) : u.lists = v.lists := by + have hu := u.p.dictionaries_eq u.hu a u.ha u.g u.m u.ctl u.i u.selector (profileOf P) u.v u.code + have hv := v.p.dictionaries_eq v.hu a v.ha v.g v.m v.ctl v.i v.selector (profileOf P) v.v v.code + refine hu.trans (Eq.trans ?_ hv.symm) + erw [show u.g.layout u.m P u.i = v.g.layout v.m P v.i from e.layout, e.key] + exact (e.agree.restrict hn).lists _ _ _ _ + +end State +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Hold.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Hold.lean new file mode 100644 index 0000000000..935a46efb8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Hold.lean @@ -0,0 +1,972 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Add +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute + +/-! +# Gathering pointers for packed intervals + +Each record gives an inclusive start, exclusive end, and translation +modulo the address space. Empty or reversed intervals are inactive. +After sorting the starts, all queries run a parallel binary search. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +open Coloring +noncomputable section +variable {h j k : ℕ} + +/-- Computes the span by the application `Format.pair (.addr k) (.pair (.addr k) (.addr k))`. -/ +abbrev span (k : ℕ) := Format.pair (.addr k) (.pair (.addr k) (.addr k)) + +/-- Requires `v.1 ≤ b ∧ b < v.2.1`. -/ +def contains (v : (span k).obj) (b : B k) : Prop := v.1 ≤ b ∧ b < v.2.1 + +/-- Returns `v.1` when `v.1 < v.2.1` holds, and `⊤` otherwise. -/ +def key (v : (span k).obj) : B k := if v.1 < v.2.1 then v.1 else ⊤ + +/-- The quantity computed by `if q < v.1 then pad else if q < v.2.1 then q + v.2.2 else pad`. -/ +def get (q pad : B k) (v : (span k).obj) : B k := + if q < v.1 then pad else if q < v.2.1 then q + v.2.2 else pad + +/-- Returns `⟨i.val + 2 ^ d, e⟩` when `e : i.val + 2 ^ d < 2 ^ h` holds, and `i` otherwise. -/ +def jump (d : ℕ) (i : B h) : B h := + if e : i.val + 2 ^ d < 2 ^ h then ⟨i.val + 2 ^ d, e⟩ else i + +/-- In the case `0, i`, this construction gives `i`. -/ +def seek (a : B h → B k) (q : B k) : ℕ → B h → B h + | 0, i => i + | d + 1, i => seek a q d (if q < a (jump d i) then i else jump d i) + +private theorem seek_ok (a : B h → B k) (ha : Monotone a) (q : B k) (i : B h) (hi : a i ≤ q) + (hb : ∀ t, a t ≤ q → t ≤ i) (d : ℕ) (l : B h) (hl : l ≤ i) (hu : i.val < l.val + 2 ^ d) : + seek a q d l = i := by + induction d generalizing l with + | zero => + change l.val ≤ i.val at hl + change l = i + exact Fin.ext (by rw [pow_zero] at hu; omega) + | succ d ih => + rw [seek] + by_cases hlow : i.val < l.val + 2 ^ d + · by_cases hj : l.val + 2 ^ d < 2 ^ h + · have e : q < a (jump d l) := lt_of_not_ge fun h => by + have := hb _ h + simp only [jump, dite_eq_left hj, Fin.le_def] at this + omega + rw [ite_eq_left e] + exact ih l hl hlow + · simpa [jump, hj] using ih l hl hlow + · have hj : l.val + 2 ^ d < 2 ^ h := (le_of_not_gt hlow).trans_lt i.isLt + have hj' : jump d l ≤ i := by simpa [jump, hj, Fin.le_def] using le_of_not_gt hlow + rw [ite_eq_right ((ha hj').trans hi).not_gt] + refine ih _ hj' ?_ + rw [pow_succ] at hu + simp only [jump, dite_eq_left hj] + omega + +/-- The indexed operation `permutation (key ∘ x) (fun _ => true)`. -/ +def order (x : B h → (span k).obj) : Equiv.Perm (B h) := + permutation (key ∘ x) (fun _ => true) + +/-- The packed of type `B h → B k`, constructed using `x ∘ order x`. -/ +def packed (q : B h → B k) (pad : B k) (x : B h → (span k).obj) : B h → B k := + let y := x ∘ order x + fun b => get (q b) pad (y (seek (key ∘ y) (q b) h 0)) + +private theorem packed_at (q : B h → B k) (pad : B k) (x : B h → (span k).obj) + (b i : B h) (hc : contains (x i) (q b)) + (unique : ∀ u, (x i).1 ≤ (x u).1 → (x u).1 ≤ q b → (x u).1 < (x u).2.1 → x u = x i) : + packed q pad x b = q b + (x i).2.2 := by + let y := x ∘ order x + let a := key ∘ y + have ha : Monotone a := fun _ _ h => rankAt_le (key ∘ x) _ _ h + let s := Finset.univ.filter fun t => a t ≤ q b + let i' := (order x).symm i + have hei : a i' = (x i).1 := by simp [a, y, key, i', lt_of_le_of_lt hc.1 hc.2] + have hi : i' ∈ s := Finset.mem_filter.mpr ⟨Finset.mem_univ _, hei.le.trans hc.1⟩ + let m := s.max' ⟨_, hi⟩ + have hm : a m ≤ q b := (Finset.mem_filter.mp (s.max'_mem _)).2 + have hmax (t : B h) (h : a t ≤ q b) : t ≤ m := + s.le_max' _ (Finset.mem_filter.mpr ⟨Finset.mem_univ _, h⟩) + have he : seek a (q b) h 0 = m := seek_ok a ha _ m hm hmax h 0 (Fin.zero_le _) (by simp) + have hvalid : (y m).1 < (y m).2.1 := by + by_contra h + have e : a m = ⊤ := ite_eq_right h + exact (hc.2.trans_le le_top).not_ge (e ▸ hm) + have e : a m = (y m).1 := ite_eq_left hvalid + have eq : y m = x i := + unique _ (hei.ge.trans ((ha (s.le_max' _ hi)).trans_eq e)) (e.ge.trans hm) hvalid + change get (q b) pad (y (seek a (q b) h 0)) = _ + rw [he, eq, get, ite_eq_right hc.1.not_gt, ite_eq_left hc.2] + +/-- Computes the extend by the application `Fin.castLE (Nat.pow_le_pow_right (by decide) h)`. -/ +def extend {j t : ℕ} (h : j ≤ t) : B j → B t := Fin.castLE (Nat.pow_le_pow_right (by decide) h) + +/-- The quantity computed by `⟨i.val % 2 ^ j, Nat.mod_lt _ (by positivity)⟩`. -/ +def shrink (j : ℕ) (i : B h) : B j := ⟨i.val % 2 ^ j, Nat.mod_lt _ (by positivity)⟩ + +@[simp] theorem shrink_extend {t : ℕ} (h : j ≤ t) (a : B j) : shrink j (extend h a) = a := + Fin.ext (Nat.mod_eq_of_lt a.isLt) + +/-- The value specified by `packed (query ∘ shrink h) pad (x ∘ shrink j) (extend (le_max_right j +h) b)`. -/ +def eval (query : B h → B k) (pad : B k) (x : B j → (span k).obj) (b : B h) : B k := + packed (query ∘ shrink h) pad (x ∘ shrink j) (extend (le_max_right j h) b) + +theorem eval_at (query : B h → B k) (pad : B k) (x : B j → (span k).obj) (b : B h) (i : B j) + (hc : contains (x i) (query b)) + (hu : ∀ u v, contains (x i) v → contains (x u) v → x u = x i) : + eval query pad x b = query b + (x i).2.2 := by + have he := packed_at (query ∘ shrink h) pad (x ∘ shrink j) + (extend (le_max_right j h) b) (extend (le_max_left j h) i) + simp only [Function.comp_apply, shrink_extend] at he + exact he hc (fun u h₁ h₂ h₃ => hu _ _ ⟨h₁, h₂.trans_lt hc.2⟩ ⟨le_rfl, h₃⟩) + +theorem eval_pad (query : B h → B k) (pad : B k) (x : B j → (span k).obj) (b : B h) + (hc : ∀ i, ¬ contains (x i) (query b)) : eval query pad x b = pad := by + have hg (i) : get (query b) pad (x i) = pad := by + by_cases hi : query b < (x i).1 + · exact ite_eq_left hi + · rw [get, ite_eq_right hi, ite_eq_right (fun h => hc i ⟨le_of_not_gt hi, h⟩)] + simp only [eval, packed, Function.comp_apply, shrink_extend, hg] + +end +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +end + +/- +# Carrying a public tape across the entire computation + +Some protocols transport the physical payload only at termination. +Compose the control kernels first, and add a *single* identity on +the public tape. Its cost is independent of the number of stages. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +universe v +variable {F : Type} [Field F] {x y : Wire} + {X Y : Snapshot.{v} F x y} {u s : ℕ} {L : Set (Table F)} + +open scoped Classical in +/-- Builds `Snapshot.{v} F x y where state` with the specified `state`, `eval`, `port`, +`encode`. -/ +def Snapshot.hold (X : Snapshot.{v} F x y) (D : Format) (f : Val x → Val y → D.obj) : + Snapshot.{v} F x y where + state := X.state + eval := X.eval + port := X.port.pair D + encode i a b := (X.encode i a b, f a b) + +open scoped Classical in +/-- The indexed operation `X.hold (.wire (.pair x y)) (fun a b => (a, b))`. -/ +abbrev Snapshot.public (X : Snapshot.{v} F x y) : Snapshot.{v} F x y := + X.hold (.wire (.pair x y)) (fun a b => (a, b)) + +open scoped Classical in +theorem Transforms.hold (h : Transforms F u L X Y s) (hu : 3 ≤ u) (D : Format) + (f : Val x → Val y → D.obj) : + Transforms F u L (X.hold D f) (Y.hold D f) (s + 4 * D.width) := by + obtain ⟨k, hk, he⟩ := h + have hid := Map.circuit (L := L) hu (Circuit.id F D) + refine ⟨_, hk.par hid, fun i => ?_⟩ + change X.state at i + obtain ⟨I, _, q, c, hq, hs⟩ := he i + refine ⟨I, inferInstance, q, c, hq, ?_⟩ + rintro a b ⟨t, v⟩ + change k (X.encode i a b) t * (if f a b = v then 1 else 0) = + ∑ j, @ite F ((Y.encode (q j) a b, f a b) = (t, v)) (Classical.propDecidable _) (c j) 0 + rw [hs] + by_cases h : f a b = v <;> simp [h, Prod.mk.injEq] + +open scoped Classical in +/-- There is no extra identity charge at each step of the iteration. -/ +theorem Transforms.stages (X : ℕ → Snapshot.{v} F x y) (cost : ℕ → ℕ) + (j : ℕ) (hj : 0 < j) + (steps : ∀ i < j, Transforms F u L (X i) (X (i + 1)) (cost i)) : + Transforms F u L (X 0) (X j) (∑ i ∈ Finset.range j, cost i) := by + induction j, hj using Nat.le_induction with + | base => simpa using steps 0 (by decide) + | succ j hj ih => + rw [Finset.sum_range_succ] + exact (ih fun i hi => steps i (Nat.lt_succ_of_lt hi)).comp (steps j (by omega)) + +open scoped Classical in +theorem Finishes.widen (h : Finishes F u L X s) {v : ℕ} {T : Set (Table F)} + (hu : u ≤ v) (hL : L ⊆ T) : Finishes F v T X s := + let ⟨f, hf, he⟩ := h + ⟨f, hf.widen hu hL, he⟩ + +open scoped Classical in +theorem Snapshot.public_start (X : Snapshot.{v} F x y) (i : X.state) + (c : X.port.obj) (hc : ∀ a b, X.encode i a b = c) (hu : 3 ≤ u) : + Map F u L (.wire (.pair x y)) X.public.port (fun z => X.public.encode i z.1 z.2) + (4 * (wd x + wd y + 34 * X.public.port.width)) := by + have h : Install.Depends (X.public.port.code ∘ (fun z => X.public.encode i z.1 z.2) ∘ + (bits (.pair x y)).symm) 1 := by + rintro (j|j) + · refine ⟨∅, by simp, fun a b _ => ?_⟩ + change X.port.code (X.encode i _ _) j = X.port.code (X.encode i _ _) j + rw [hc, hc] + · refine ⟨{j}, by simp, fun a b he => ?_⟩ + change bits (.pair x y) ((bits (.pair x y)).symm a) j + = bits (.pair x y) ((bits (.pair x y)).symm b) j + rw [Equiv.apply_symm_apply, Equiv.apply_symm_apply] + exact he _ (by simp) + apply Map.circuit hu + have hk := h.bnet F + rw [card_slots] at hk + exact hk + +open scoped Classical in +theorem Transforms.public_end (h : Transforms F u L X Y s) {m : ℕ} (hu : 3 ≤ u) + (stop : Finishes F u L Y.public m) (i : X.state) (c : X.port.obj) + (hc : ∀ a b, X.encode i a b = c) : + ∃ n ≤ 150 * (X.port.width + wd x + wd y) + s + m, Wide F u L x y (X.eval i) n := by + have held := h.hold hu (.wire (.pair x y)) fun a b => (a, b) + obtain ⟨n, hn, hnet⟩ := Finishes.start (X := X.public) hu i (X.public_start i c hc hu) + (held.finish stop) + refine ⟨n, hn.trans ?_, hnet⟩ + change 4 * (wd x + wd y + 34 * (X.port.pair (.wire (.pair x y))).width) + + (s + 4 * (Format.wire (.pair x y)).width + m) + 4 * wd y ≤ _ + rw [Format.width_pair] + rw [show (Format.wire (.pair x y)).width = wd x + wd y from card_slots (.pair x y)] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +section +/- Parallel binary search on a vector of sorted addresses. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +open Coloring +noncomputable section +variable (F : Type) [Field F] {h k t : ℕ} + +theorem cheap_compare (hk : k ≤ t) : + Cheap F 0 t (.pair (.addr k) (.addr k)) .bit (fun z => decide (z.1 < z.2)) 3 := by + refine ⟨_, numeric_lt F k, ?_⟩ + simp only [Format.width_pair, Format.width_addr] + rw [Format.width_bit] + ring_nf + omega + +/-- Computes the col by the application `Format.vec h (.addr k)`. -/ +abbrev Col (h k : ℕ) := Format.vec h (.addr k) + +theorem vec_bound (h : ℕ) {A : Format} (hw : A.width ≤ 100 + t) : + (Format.vec h A).width ≤ 2 ^ h * (100 + t) ^ 1 := by + rw [Format.width_vec, pow_one] + exact Nat.mul_le_mul_left _ hw + +private theorem col_bound (h : ℕ) (hk : k ≤ t) : (Col h k).width ≤ 2 ^ h * (100 + t) ^ 1 := + vec_bound _ (by rw [Format.width_addr]; omega) + +private abbrev State (h k : ℕ) := Format.pair (Col h k) (Col h h) + +private def step (q : B h → B k) (d : ℕ) (x : (State h k).obj) : (State h k).obj := + (x.1, fun i => if q i < x.1 (jump d (x.2 i)) then x.2 i else jump d (x.2 i)) + +private def steps (q : B h → B k) (d : ℕ) (x : (State h k).obj) : (State h k).obj := + (x.1, fun i => seek x.1 (q i) d (x.2 i)) + +private theorem cheap_step (q : B h → B k) (d : ℕ) (hk : h + k ≤ t) : + Cheap F h t (State h k) (State h k) (step q d) 20 := by + have hl : (State h k).width ≤ 2 ^ h * (100 + t) ^ 1 := by + simp only [State, Col, Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add, + pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have ha : k ≤ t := by omega + have hb : h ≤ t := by omega + have x := Cheap.id F hl + have trial := ((Cheap.const F hl (col_bound h hb) (jump d)).pair x.snd).comp + (Cheap.lookup F h t (.addr h) hb (by simp [hb])) + have val := (x.fst.pair trial).comp (Cheap.lookup F h t (.addr k) hb (by simp [ha])) + have query := Cheap.const F hl (col_bound h ha) q + have lt := (query.pair val).zip.comp (Cheap.map _ fun _ : B h => cheap_compare F ha) + have sel := ((x.snd.pair trial).zip.pair lt).zip.comp + (Cheap.map _ fun _ : B h => (cheap_select F h).widen hb) + convert (x.fst.pair sel).mono (d := 20) (by decide) using 1 + funext x + apply Prod.ext + · rfl + · funext i + by_cases he : q i < x.1 (jump d (x.2 i)) <;> simp [step, he] + +private theorem cheap_steps (q : B h → B k) (hk : h + k ≤ t) : + Cheap F h t (State h k) (State h k) (steps q h) 21 := by + let A := State h k + let C := 2 ^ h * (100 + t) ^ 20 + have run (d) : Circuit F A A (steps q d) (A.width + d * C) := by + induction d with + | zero => + rw [Nat.zero_mul, Nat.add_zero] + exact Circuit.id F A + | succ d ih => + obtain ⟨m, h₁, h₂⟩ := cheap_step F q d hk + have he : steps q (d + 1) = steps q d ∘ step q d := rfl + rw [he, Nat.succ_mul] + exact (h₁.comp ih).mono (by omega) + obtain ⟨m, _, hm⟩ := cheap_step F q 0 hk + refine ⟨_, run h, ?_⟩ + rw [pow_succ, ← mul_assoc (2 ^ h)] + have ht := Nat.mul_le_mul_right C (show h ≤ t by omega) + change A.width + A.width + (A.width + h * C) ≤ C * (100 + t) + rw [mul_add, mul_comm C 100, mul_comm C t] + change A.width + A.width + m ≤ C at hm + omega + +theorem cheap_seek (q : B h → B k) (hk : h + k ≤ t) : + Cheap F h t (Col h k) (Perm h) (fun a b => seek a (q b) h 0) 23 := by + have hb := col_bound h (show k ≤ t by omega) + have hz := Cheap.const F hb (col_bound h (show h ≤ t by omega)) (fun _ => 0) + exact (((Cheap.id F hb).pair hz).comp (cheap_steps F q hk)).snd + +end +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +end + +/- +# Computing the status masks for a frozen core + +Read the status of each neighbor once, then duplicate the short +mask at each block. The label serialization only permutes bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +open Coloring + +variable {F : Type} [Field F] (S : Scheme F) + +private theorem serial_bits (A : Format) : + ∃ e : (Format.addr A.width).pins → A.pins, + ∀ x i, (Format.addr A.width).code (A.serial x) i = A.code x (e i) := by + have h (k : slots (word A.width) ≃ A.pins) : + ∃ e : (Format.addr A.width).pins → A.pins, + ∀ x i, (Format.addr A.width).code + (((A.code.trans (k.symm.arrowCongr (.refl _))).trans (Format.addr A.width).code.symm) x) + i = + A.code x (e i) := by + refine ⟨k, fun x i => ?_⟩ + rw [Equiv.trans_apply, Equiv.apply_symm_apply] + rfl + exact h _ + +/-- Computes the cut input by the application `S.format.pair (.vec S.m .bit)`. -/ +abbrev cutInput := S.format.pair (.vec S.m .bit) +private abbrev query := Format.pair (.vec S.m .bit) (.vec S.d (Perm S.m)) +private abbrev statuses := Format.vec S.m (.vec S.d .bit) + +private def labels (x : S.cutInput.obj) : (query S).obj := + (x.2, fun j i => (x.1 i).1 j) + +private def emit (x : (S.cutInput.pair (statuses S)).obj) : S.cut.format.obj := + fun v => ((x.1.1 v).1, fun i => S.cutCode.serial ((x.1.1 v).2 i, x.1.2 v, x.2 v)) + +private theorem emit_net : + Circuit F (S.cutInput.pair (statuses S)) S.cut.format (emit S) + ((S.cutInput.pair (statuses S)).width + 2 * S.cut.format.width) := by + obtain ⟨k, hk⟩ := serial_bits S.cutCode + let pins (i : B S.m) (j : B S.h) : S.cutCode.pins → (S.cutInput.pair (statuses S)).pins + | .inl a => .inl (.inl (i, .inr (j, a))) + | .inr (.inl a) => .inl (.inr (i, a)) + | .inr (.inr a) => .inr (i, a) + let read : S.cut.format.pins → (S.cutInput.pair (statuses S)).pins + | (i, .inl j) => .inl (.inl (i, .inl j)) + | (i, .inr (j, a)) => pins i j (k a) + refine Circuit.project read ?_ + rintro x ⟨i, j|⟨j, a⟩⟩ + · rfl + · refine (hk ((x.1.1 i).2 j, x.1.2 i, x.2 i) a).trans ?_ + change _ = (S.cutInput.pair (statuses S)).code x (pins i j (k a)) + rcases k a with a | (a|a) <;> rfl + +/-- The quantity computed by `4 * (10 * S.cutInput.width + 2 * S.cut.format.width + 3 * 2 ^ S.m +* (100 + (S.m + 2 ^ S.d)) ^ 12)`. -/ +def cutCost := 4 * (10 * S.cutInput.width + 2 * S.cut.format.width + 3 * 2 ^ S.m * (100 + (S.m + + 2 ^ S.d)) ^ 12) + +theorem map_remove {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) : + Map F u L S.cutInput S.cut.format (fun x => S.remove x.1 x.2) S.cutCost := by + have a : Circuit F S.cutInput (query S) (labels S) (S.cutInput.width + 2 * (query S).width) := + Circuit.project (Sum.elim Sum.inr (fun z => Sum.inl (z.2.1, .inl (z.1, z.2.2)))) + (by rintro _ (i|j) <;> rfl) + obtain ⟨m, h, hb⟩ := Cheap.neighbors F .bit S.m (S.m + 2 ^ S.d) S.d (Nat.le_add_right _ _) + (Format.width_bit.le.trans ((Nat.two_pow_pos S.d).trans_le (Nat.le_add_left _ _))) + (Nat.le_add_left _ _) + let x := Circuit.id F S.cutInput + have out := (x.pair (a.comp h)).comp (S.emit_net) + simp only [Function.comp_def, id_eq] at out + refine (Map.circuit hu out).mono ?_ + change (query S).width + (statuses S).width + m ≤ _ at hb + rw [Format.width_pair S.cutInput (statuses S)] + unfold cutCost + rw [mul_assoc 3] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- +# Deterministic grouping and coloring + +The chosen mixer minimizes the number of splits. The affine coloring +maximizes the number of matched units for this grouping. Unused +host positions have score zero. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Packing Coloring Finset + +variable {X : Type} [Fintype X] {b k d : ℕ} + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def ballots (f : X ↪ B b) (s : B k → X → B d) (i : B k) (j : B b) := + Function.extend f (s i) (fun _ => 0) j + +open scoped Classical in +theorem ballots_total (f : X ↪ B b) (s : B k → X → B d) (i : B k) : + (∑ j, (ballots f s i j).val) = ∑ x, (s i x).val := by + rw [← sum_subset (subset_univ (univ.map f)), sum_map] + · simp [ballots, f.injective.extend_apply] + · intro z _ hz + have h : z ∉ Set.range f := by simpa using hz + simp only [ballots, Function.extend_apply' _ _ _ h, Fin.val_zero] + +open scoped Classical in +/-- Uses `⟨splits N delay l i x, splits_le _ _ _ _ _⟩` as the representation. -/ +def splitScore (N : X → Finset X) (delay : X → X → ℕ) (l : X → Cell k → ℝ) + (i : B k) (x : X) : B k := ⟨splits N delay l i x, splits_le _ _ _ _ _⟩ + +open scoped Classical in +theorem elected_best (N : X → Finset X) (delay : X → X → ℕ) (l : X → Cell k → ℝ) + (f : X ↪ B b) : + best N delay l (elect ⊥ (ballots f (splitScore N delay l))) := by + intro q + simpa only [ballots_total, splitScore] using elect_min (ballots f (splitScore N delay l)) q + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def colorIndex (k : ℕ) : B (k + 1) ≃ Color k := + Fintype.equivOfCardEq (by simp [Color, Cell, pow_succ]) + +namespace Scheme.Posting + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u h : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h u} + (p : S.Posting r G) (hu : 0 < u) (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' (G.regroup a ha).load) + +open scoped Classical in +/-- The color score of type `B (h - a + S.e + 1)`, constructed using `Match.rows (p.records a ha +g (colorIndex _ c) v)`. -/ +def colorScore (c : B (h - a + 1)) (v : G.V × Cell a) : B (h - a + S.e + 1) := + let row := Match.rows (p.records a ha g (colorIndex _ c) v) + ⟨(univ.filter fun i => row.control.1 i).card, by + refine (card_filter_le _ _).trans_lt ?_ + rw [card_univ, Fintype.card_fin, pow_succ] + have : 0 < (2 : ℕ) ^ (h - a + S.e) := by positivity + omega⟩ + +open scoped Classical in +/-- The quantity computed by `colorIndex (h - a) (elect ⊤ (ballots f (p.colorScore a ha g)))`. -/ +def color (f : G.V × Cell a ↪ B b) := + colorIndex (h - a) (elect ⊤ (ballots f (p.colorScore a ha g))) + +open scoped Classical in +theorem score_optimal (f : G.V × Cell a ↪ B b) (c : Color (h - a)) : + p.score a ha g c ≤ p.score a ha g (p.color a ha g f) := by + have he := elect_max (ballots f (p.colorScore a ha g)) ((colorIndex (h - a)).symm c) + rw [ballots_total, ballots_total] at he + change p.score a ha g ((colorIndex (h - a)) ((colorIndex (h - a)).symm c)) ≤ _ at he + rw [Equiv.apply_symm_apply] at he + exact he + +open scoped Classical in +theorem elected_matching (f : G.V × Cell a ↪ B b) (σ : ℝ) (hB : 0 < B') + (bounds : G.Bounded Δ D B') (hbins : 256 * (coreBins Δ + 1) ≤ 2 ^ k) + (slack : (2 : ℝ) ^ k * B' * (Fintype.card G.V * 2 ^ a : ℕ) ≤ σ) : + ∃ m : Matchings a ha g, m.color = p.color a ha g f ∧ p.Controls hu a ha g m ∧ + (G.X : ℝ) / 4 - (L.Z + σ) ≤ u * (m.count : ℝ) := by + obtain ⟨m, hm, hc⟩ := p.matching hu a ha g σ hB bounds hbins slack + obtain ⟨t, ht, ctl⟩ := p.all_colors hu a ha g (p.color a ha g f) + refine ⟨t, ht, ctl, hc.trans (mul_le_mul_of_nonneg_left ?_ (Nat.cast_nonneg _))⟩ + rw [Nat.cast_le, ← p.match_score hu a ha g m hm, ← p.match_score hu a ha g t ctl, ht] + exact p.score_optimal a ha g f _ + +end Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- The bucket ordinal is the occurrence rank in the vector of dyadic levels. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.PackRank + +open Coloring +variable {h k V l : ℕ} + +/-- Uses `⟨Nat.clog 2 x.val, (Nat.clog_le_of_le_pow x.isLt.le).trans_lt Nat.lt_two_pow_self⟩` as +the representation. -/ +def code (x : B k) : B k := + ⟨Nat.clog 2 x.val, (Nat.clog_le_of_le_pow x.isLt.le).trans_lt Nat.lt_two_pow_self⟩ + +/-- The value specified by `(code (x i), groupRank (code ∘ x) i)`. -/ +def assign (x : B h → B k) (i : B h) := (code (x i), groupRank (code ∘ x) i) + +private theorem ranked {n : ℕ} (z : B h → Fin n) (i : B h) : + ((Fintype.orderIsoFinOfCardEq {u // z u = z i} rfl).symm ⟨i, rfl⟩).val = + Control.rank z i := by + let S := {u // z u = z i} + let f (x : S) : Fin (Fintype.card S) := ⟨Control.rank z x.val, by + rw [show Fintype.card S = Control.histogram z (z i) none by + unfold S; rw [Fintype.card_subtype, Control.histogram_none]] + exact (Control.rank_lt z x.val).trans_eq (congrArg (fun w => Control.histogram z w none) x.2)⟩ + have hf : StrictMono f := fun u v h => Control.rank_mono z (u.2.trans v.2.symm) h + let e := Fintype.orderIsoFinOfCardEq S rfl + have he := congrFun (hf.comp e.strictMono).eq_id (e.symm ⟨i, rfl⟩) + simp only [Function.comp_apply, OrderIso.apply_symm_apply, id_eq] at he + exact (congrArg Fin.val he).symm + +theorem correct (p : Payload h V l) (x : B h → B k) (hx : ∀ i, (x i).val = p.length i) + (i : B h) : + (assign x i).1.val = (p.seat.write i).1.val ∧ + (assign x i).2.val = (p.seat.write i).2.val := by + let z (j : B h) := (p.seat.write j).1 + have hz (j : B h) : (code (x j)).val = (z j).val := by + change Nat.clog 2 (x j).val = Nat.clog 2 (max 1 (p.length j)) + rw [hx] + rcases le_total 1 (p.length j) with h | h + · rw [max_eq_right h] + · rw [max_eq_left h, Nat.clog_of_right_le_one h, Nat.clog_of_right_le_one le_rfl] + refine ⟨hz i, ?_⟩ + change (groupRank (code ∘ x) i).val = + ((Fintype.orderIsoFinOfCardEq {u // z u = z i} rfl).symm ⟨i, rfl⟩).val + rw [ranked, groupRank_val, Control.rank, Control.rank, Control.histogram_some, + Control.histogram_some] + congr 1 + ext j + simp [Fin.ext_iff, hz] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.PackRank +end + +/- Near-linear circuit for assigning the ordered slots of a payload bank. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.PackRank +open Coloring + +variable {k : ℕ} + +private def scan (x : B k) : ℕ → B k + | 0 => 0 + | m + 1 => if h : m < k then + if 2 ^ m < x.val then ⟨m + 1, (Nat.succ_le_of_lt h).trans_lt Nat.lt_two_pow_self⟩ + else scan x m + else scan x m + +private theorem scan_eq (x : B k) (n : ℕ) (hn : n ≤ k) (hx : x.val ≤ 2 ^ n) : + (scan x n).val = Nat.clog 2 x.val := by + have h := Nat.clog_le_of_le_pow hx + induction n with + | zero => simp only [scan, Fin.val_zero]; omega + | succ m ih => + rw [scan, dite_eq_left (by omega)] + by_cases hm : 2 ^ m < x.val + · rw [ite_eq_left hm] + have := (Nat.lt_clog_iff_pow_lt (by decide : 1 < 2)).mpr hm + change m + 1 = _ + omega + · rw [ite_eq_right hm] + exact ih (by omega) (le_of_not_gt hm) (Nat.clog_le_of_le_pow (le_of_not_gt hm)) + +variable (F : Type) [Field F] + +private abbrev Cell (k : ℕ) := Format.pair (.addr k) (.addr k) + +private theorem step (key level : B k) : Cheap F 0 k (Cell k) (Cell k) + (fun y => (y.1, if key < y.1 then level else y.2)) 12 := by + have hi : (Cell k).width ≤ 2 ^ 0 * (100 + k) ^ 2 := by simp [Cell]; ring_nf; omega + have hw : (Format.addr k).width ≤ 2 ^ 0 * (100 + k) ^ 2 := by simp; ring_nf; omega + have x := Cheap.id F hi + have lt := ((Cheap.const F hi hw key).pair x.fst).comp (Intervals.cheap_compare F le_rfl) + have sel := (((Cheap.const F hi hw level).pair x.snd).pair lt).comp (cheap_select F k) + convert (x.fst.pair sel).mono (d := 12) (by decide) using 1 + funext y + by_cases h : key < y.1 <;> simp [h] + +theorem cheap_code (k : ℕ) : Cheap F 0 k (.addr k) (.addr k) code 16 := by + let C := 2 ^ 0 * (100 + k) ^ 12 + have hw : (Format.addr k).width ≤ 2 ^ 0 * (100 + k) ^ 1 := by simp + have net (n : ℕ) (hn : n ≤ k) : + Circuit F (.addr k) (Cell k) (fun x => (x, scan x n)) ((n + 1) * C) := by + induction n with + | zero => + obtain ⟨m, hm, hb⟩ := ((Cheap.id F hw).pair (Cheap.const F hw hw 0)).mono (d + := 12) (by decide) + change Circuit F (.addr k) (Cell k) (fun x => (x, 0)) (1 * C) + exact hm.mono (by unfold C; omega) + | succ n ih => + have hh : n < k := hn + let a : B k := ⟨2 ^ n, Nat.pow_lt_pow_right (by decide) hh⟩ + let b : B k := ⟨n + 1, hn.trans_lt Nat.lt_two_pow_self⟩ + obtain ⟨m, hm, hb⟩ := step F a b + have he : (fun x : B k => (x, scan x (n + 1))) = + (fun y : (Cell k).obj => (y.1, if a < y.1 then b else y.2)) ∘ (fun x => (x, scan x n)) + := by + funext x + rw [scan, dite_eq_left hh] + rfl + rw [he, Nat.succ_mul] + exact ((ih hh.le).comp hm).mono (Nat.add_le_add_left (by unfold C; omega) _) + have he : (fun x : B k => (x, scan x k)) = fun x => (x, code x) := + funext fun x => Prod.ext rfl (Fin.ext (scan_eq x k le_rfl x.isLt.le)) + have hn := net k le_rfl + rw [he] at hn + have hc : Cheap F 0 k (.addr k) (Cell k) (fun x => (x, code x)) 13 := by + refine ⟨_, hn, ?_⟩ + simp only [Cell, Format.width_pair, Format.width_addr] + have hk : k ≤ C := by + unfold C + simpa using (show k ≤ 100 + k by omega).trans (Nat.le_pow (by decide : 0 < 12)) + rw [pow_succ, ← mul_assoc (2 ^ 0)] + change k + (k + k) + (k + 1) * C ≤ C * (100 + k) + nlinarith + exact hc.snd.mono (by decide) + +theorem cheap (h k : ℕ) : + Cheap F h (h + k) (.vec h (.addr k)) (.vec h (.pair (.addr k) (.addr h))) assign 110 := by + have levels := Cheap.map _ (fun _ : B h => (cheap_code F k).widen (show k ≤ h + k by omega)) + have rank := levels.comp (cheap_groupRank F h k) + exact (levels.pair rank).zip.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.PackRank +end + +/- +# Distributing host records to dyadic slots + +At each level, sort a one-bit key stably. The hosts of that level +come first, in increasing input order. Replace all inactive rows +by the padding value and retain the physical bucket's prefix. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Redistribute + +open Coloring Transcript + +variable {m w V k : ℕ} + +/-- Computes the input by the application `Format.pair (.vec m (.addr w)) (.vec m A)`. -/ +abbrev input (m w : ℕ) (A : Format) := Format.pair (.vec m (.addr w)) (.vec m A) +/-- The quantity computed by `Fmt.pi (fun _ : Slot (2 ^ m) V k => A)`. -/ +abbrev output (m V k : ℕ) (A : Format) := Fmt.pi (fun _ : Slot (2 ^ m) V k => A) + +/-- Returns `0` when `(PackRank.code x).val = l` holds, and `1` otherwise. -/ +def flag (l : ℕ) (x : B w) : B 1 := if (PackRank.code x).val = l then 0 else 1 + +/-- Computes the index by the application `s.2.castLE (min_le_left _ _)`. -/ +def index (s : Slot (2 ^ m) V k) : B m := s.2.castLE (min_le_left _ _) + +/-- Returns `x.2 i` when `x.1 i = 0` holds, and `pad` otherwise. -/ +def mask (A : Format) (pad : A.obj) (x : (input m 1 A).obj) (i : B m) : A.obj := + if x.1 i = 0 then x.2 i else pad + +/-- The construction uses `flag l ∘ x.1` for its intermediate `f`. -/ +def bucket (l : ℕ) (A : Format) (pad : A.obj) (x : (input m w A).obj) := + let f := flag l ∘ x.1 + mask A pad (f, x.2) ∘ Coloring.order f + +/-- Evaluates `bucket s.1.val A pad x (index s)` at the input `s`. -/ +def eval (A : Format) (pad : A.obj) (x : (input m w A).obj) : (output m V k A).obj := + fun s => bucket s.1.val A pad x (index s) + +private theorem zero_rank (f : B m → B 1) (i : B m) (h : f i = 0) : + ((Coloring.order f).symm i).val = Control.rank f i := by + let a := f ∘ Coloring.order f + let j := (Coloring.order f).symm i + have hj : a j = 0 := by simp [a, j, h] + have hz : a 0 = a j := by + refine le_antisymm (order_mono f (Fin.zero_le j)) ?_ + change a j ≤ a 0 + rw [hj] + exact Fin.zero_le _ + have hl : leader a j = 0 := + le_antisymm ((leader_spec a (order_mono f) j).2 0 hz) (Fin.zero_le _) + rw [← groupRank_val] + change j.val = (j - leader a j).val + rw [hl, sub_zero] + +private theorem position (p : Payload m V k) (x : B m → B w) (hx : ∀ i, (x i).val = p.length i) + (s : Slot (2 ^ m) V k) (i : B m) : + p.seat.write i = s ↔ (flag s.1.val ∘ x) i = 0 ∧ Coloring.order (flag s.1.val ∘ x) (index s) = i + := by + let f := flag s.1.val ∘ x + have hk (j : B m) : f j = 0 ↔ (PackRank.code (x j)).val = s.1.val := by + simp [f, flag] + obtain ⟨hl, hr⟩ := PackRank.correct p x hx i + change (PackRank.code (x i)).val = _ at hl + have he : f i = 0 ↔ (p.seat.write i).1 = s.1 := by rw [hk, hl, Fin.ext_iff] + have hpos (h : f i = 0) : ((Coloring.order f).symm i).val = (p.seat.write i).2.val := by + rw [zero_rank f i h, ← hr] + change _ = (groupRank (PackRank.code ∘ x) i).val + rw [groupRank_val, Control.rank, Control.rank, Control.histogram_some, Control.histogram_some] + congr 1 + ext j + simp only [Finset.mem_filter, Finset.mem_univ, true_and, Function.comp_apply, h, hk, + Fin.ext_iff, + (hk i).mp h] + change p.seat.write i = s ↔ f i = 0 ∧ Coloring.order f (index s) = i + constructor + · intro h + have hf := he.mpr (congrArg Sigma.fst h) + refine ⟨hf, (Coloring.order f).eq_symm_apply.mp (Fin.ext ?_)⟩ + rw [hpos hf, h] + rfl + · rintro ⟨hf, hi⟩ + have hr' := (hpos hf).symm.trans (congrArg Fin.val ((Coloring.order f).eq_symm_apply.mpr + hi).symm) + have he' := he.mp hf + change (p.seat.write i).2.val = s.2.val at hr' + generalize p.seat.write i = u at * + obtain ⟨l, a⟩ := u + obtain ⟨r, b⟩ := s + change l = r at he' + subst r + exact congrArg (Sigma.mk l) (Fin.ext hr') + +theorem correct (p : Payload m V k) (A : Format) (pad : A.obj) (x : (input m w A).obj) + (hx : ∀ i, (x.1 i).val = p.length i) : + eval A pad x = fun s => (p.seat.read s).elim pad x.2 := by + funext s + let f := flag s.1.val ∘ x.1 + let i := Coloring.order f (index s) + change (if f i = 0 then x.2 i else pad) = _ + cases hr : p.seat.read s with + | none => + have hf : f i ≠ 0 := by + intro h + have he := (p.seat.valid s i).mpr ((position p x.1 hx s i).mpr ⟨h, rfl⟩).symm + rw [hr] at he + contradiction + simp [hf] + | some j => + obtain ⟨hj, hi⟩ := (position p x.1 hx s j).mp ((p.seat.valid s j).mp hr).symm + change i = j at hi + rw [hi, ite_eq_left hj] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Redistribute +end + +/- Only the address metadata passes through comparison sorting. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Redistribute +open Coloring + +variable (F : Type) [Field F] {m w : ℕ} + +open scoped Classical in +private theorem cheap_flag (l w : ℕ) : Cheap F 0 (w + 1) (.addr w) (.addr 1) (flag l) 24 := by + have hw : (Format.addr w).width ≤ 2 ^ 0 * (100 + (w + 1)) ^ 1 := by simp; omega + have hb : (Format.addr 1).width ≤ 2 ^ 0 * (100 + (w + 1)) ^ 1 + := by rw [Format.width_addr]; simp; omega + by_cases h : l < 2 ^ w + · let y : B w := ⟨l, h⟩ + have lev := (PackRank.cheap_code F w).widen (show w ≤ w + 1 by omega) + have eq := (lev.pair (Cheap.const F hw hw y)).comp (cheap_eq F (show w ≤ w + 1 by omega)) + have choices := (Cheap.const F hw hb 0).pair (Cheap.const F hw hb 1) + have send := (choices.pair eq).comp ((cheap_select F 1).widen (show 1 ≤ w + 1 by omega)) + convert send.mono (d := 24) (by decide) using 1 + funext x + by_cases h : (PackRank.code x).val = l <;> simp [flag, Fin.ext_iff, y, h] + · convert (Cheap.const F hw hb 1).mono (d := 24) (by decide) using 1 + funext x + exact ite_eq_right (ne_of_lt ((PackRank.code x).isLt.trans_le (le_of_not_gt h))) + +open scoped Classical in +private theorem mask_cost (A : Format) (pad : A.obj) (m : ℕ) : + Circuit F (input m 1 A) (.vec m A) (mask A pad) (2 ^ m * (1 + 69 * A.width)) := by + let R := input m 1 A + let D := Format.vec m A + have h : Install.Depends (D.code ∘ mask A pad ∘ R.code.symm) 2 := by + rintro ⟨i, j⟩ + let fromKey (k : (Format.addr 1).pins) : R.pins := .inl (i, k) + let out : R.pins := .inr (i, j) + let S := Finset.univ.image fromKey + have hS : S.card ≤ 1 := Finset.card_image_le.trans_eq (Format.width_addr 1) + refine ⟨insert out S, (Finset.card_insert_le _ _).trans (by omega), fun x y he => ?_⟩ + let a := R.code.symm x + let b := R.code.symm y + have hk : a.1 i = b.1 i := by + apply (Format.addr 1).code.injective + funext k + change R.code a (fromKey k) = R.code b (fromKey k) + simpa only [a, b, Equiv.apply_symm_apply] using he (fromKey k) + (Finset.mem_insert_of_mem (Finset.mem_image_of_mem fromKey (Finset.mem_univ _))) + have hb : A.code (a.2 i) j = A.code (b.2 i) j := by + change R.code a out = R.code b out + simpa only [a, b, Equiv.apply_symm_apply] using he out (Finset.mem_insert_self _ _) + change A.code (mask A pad a i) j = A.code (mask A pad b i) j + unfold mask + rw [hk] + split <;> first | exact hb | rfl + refine (h.bnet F).mono ?_ + change R.width + 68 * D.width ≤ _ + simp only [R, D, input, Format.width_pair, Format.width_vec] + rw [Format.width_addr] + exact le_of_eq (by ring) + +open scoped Classical in +/-- The quantity computed by `2 ^ m * (v + (101 + m + w) ^ 60)`. -/ +def budget (m w v : ℕ) := 2 ^ m * (v + (101 + m + w) ^ 60) + +open scoped Classical in +theorem bound_width {v : ℕ} (A : Format) (ha : A.width ≤ v) (m w : ℕ) : + (input m w A).width ≤ budget m w v := by + simp only [input, Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add, budget] + have h := Nat.le_pow (a := 101 + m + w) (by decide : 0 < 60) + exact Nat.mul_le_mul_left _ (by omega) + +open scoped Classical in +/-- The value specified by `(Coloring.order (flag l ∘ x.1), mask A pad (flag l ∘ x.1, x.2))`. -/ +def prepare (A : Format) (l : ℕ) (pad : A.obj) (x : (input m w A).obj) : (exchangeIn A m).obj := + (Coloring.order (flag l ∘ x.1), mask A pad (flag l ∘ x.1, x.2)) + +open scoped Classical in +theorem prepare_cost {v : ℕ} (A : Format) (ha : A.width ≤ v) (l : ℕ) (pad : A.obj) : + Circuit F (input m w A) (exchangeIn A m) (prepare A l pad) (100 * budget m w v) := by + let B := budget m w v + have hC := Nat.le_pow (a := 101 + m + w) (by decide : 0 < 60) + have hb (k c) (hk : k ≤ m + w + 1) (hc : c ≤ 60) : 2 ^ m * (100 + k) ^ c ≤ B := by + unfold B budget + exact Nat.mul_le_mul_left _ (((Nat.pow_le_pow_left (by omega : 100 + k ≤ 101 + m + w) _).trans + (Nat.pow_le_pow_right (by omega) hc)).trans (Nat.le_add_left _ _)) + have h₀ : (input m 1 A).width ≤ B := by + simp only [input, Format.width_pair, Format.width_vec, ← mul_add] + exact Nat.mul_le_mul_left _ (by omega : 1 + A.width ≤ v + (101 + m + w) ^ 60) + have h₁ : (Format.vec m A).width ≤ B := (by rw [Format.width_pair] at h₀; omega) + have h₂ : (Column m 1).width ≤ B := by + rw [Format.width_pair] at h₀ + exact (Nat.le_add_right _ _).trans h₀ + obtain ⟨r, hr, hr'⟩ := Cheap.map _ (fun _ : Coloring.B m => cheap_flag F l w) + obtain ⟨s, hs, hs'⟩ := cheap_order F m 1 + have pre := hr.par (Circuit.id F (.vec m A)) + have take := Circuit.project (F := F) (A := input m 1 A) (D := Column m 1) (f := Prod.fst) + Sum.inl (fun _ _ => rfl) + have ord := take.comp hs + have hmask : 2 ^ m * (1 + 69 * A.width) ≤ 69 * B := by + unfold B budget + rw [mul_left_comm 69] + exact Nat.mul_le_mul_left _ (by omega) + have h := pre.comp (ord.pair (mask_cost F A pad m)) + have hr'' := hr'.trans (hb _ _ (by omega) (by decide)) + have hs'' := hs'.trans (hb _ _ (by omega) (by decide)) + exact h.mono (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Redistribute +end + +/- Each level uses a single controlled exchange of whole records. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Redistribute +open Coloring Transcript + +variable {F : Type} [Field F] {m w V k u v c : ℕ} {L : Set (Table F)} + +open scoped Classical in +/-- The quantity computed by `10000 * (k + 1) * (c + budget m w v)`. -/ +def cost (m k w v c : ℕ) := 10000 * (k + 1) * (c + budget m w v) + +open scoped Classical in +private theorem one (hu : 3 ≤ u) (ht : Radix.Tag F m v c) (A : Format) (ha : A.width ≤ v) + (pad : A.obj) (l : ℕ) : + Map F u L (input m w A) (.vec m A) (bucket l A pad) (4 * c + 1400 * budget m w v) := by + have p := Map.circuit (L := L) hu (prepare_cost F A ha l pad (m := m) (w := w)) + have h := p.then_kernel (permutation_kernel A hu ht ha) + have he (x : (input m w A).obj) (y : (Format.vec m A).obj) : + exchange A F (prepare A l pad x) y = if bucket l A pad x = y then 1 else 0 := by + change (if Function.Bijective (Coloring.order (flag l ∘ x.1)) ∧ y = bucket l A pad x + then (1 : F) else 0) = _ + simp [eq_comm] + simp only [he] at h + have hb : 2 ^ m * (m + v + 1) ≤ budget m w v := by + have := Nat.le_pow (a := 101 + m + w) (by decide : 0 < 60) + exact Nat.mul_le_mul_left _ (by omega) + have hg := h.mono (n := 4 * c + 1400 * budget m w v) (by linarith only [hb]) + unfold Map + convert hg using 1 + funext x y + split_ifs <;> rfl + +open scoped Classical in +private theorem output_width (A : Format) : + (output m V k A).width ≤ (k + 1) * (2 ^ m * A.width) := by + have hc : Fintype.card (Slot (2 ^ m) V k) ≤ (k + 1) * 2 ^ m := by + rw [Fintype.card_sigma] + calc + _ ≤ ∑ _i : Fin (k + 1), 2 ^ m := Finset.sum_le_sum fun i _ => by + rw [Fintype.card_fin]; exact min_le_left _ _ + _ = _ := by simp + simp only [output, Fmt.width_pi, Finset.sum_const, Finset.card_univ, smul_eq_mul, ← mul_assoc] + exact Nat.mul_le_mul_right _ hc + +open scoped Classical in +/-- Total redistribution, including when a bucket has too many entries. +In that case only the entries in its physical seats are retained. -/ +theorem realize (hu : 3 ≤ u) (ht : Radix.Tag F m v c) (A : Format) (ha : A.width ≤ v) + (pad : A.obj) : + Map F u L (input m w A) (output m V k A) (eval A pad) (cost m k w v c) := by + let I := input m w A + let J := Fmt.pi (fun _ : Fin (k + 1) => I) + let K := Fmt.pi (fun _ : Fin (k + 1) => Format.vec m A) + let D := output m V k A + have copy : Circuit F I J (fun x _ => x) (I.width + 2 * J.width) := + Circuit.project (fun a => a.2) (fun _ _ => rfl) + have p := Map.family (fun i : Fin (k + 1) => one (L := L) (w := w) hu ht A ha pad i.val) + have cut : Circuit F K D (fun x s => x s.1 (index s)) (K.width + 2 * D.width) := + Circuit.project (fun j => ⟨j.1.1, index j.1, j.2⟩) (fun _ _ => rfl) + have h := ((Map.circuit hu copy).comp p).comp (Map.circuit hu cut) + let b := budget m w v + have hi : I.width ≤ b := bound_width A ha m w + have hv : 2 ^ m * A.width ≤ b := Nat.mul_le_mul_left _ (ha.trans (Nat.le_add_right _ _)) + have hj : J.width ≤ (k + 1) * b := by simpa [J] using Nat.mul_le_mul_left (k + 1) hi + have hk : K.width ≤ (k + 1) * b := by simpa [K] using Nat.mul_le_mul_left (k + 1) hv + have hd : D.width ≤ (k + 1) * b := (output_width A).trans (Nat.mul_le_mul_left _ hv) + refine h.mono ?_ + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] + change 4 * (I.width + 2 * J.width) + (k + 1) * (4 * c + 1400 * b) + 4 * (K.width + 2 * D.width) ≤ + 10000 * (k + 1) * (c + b) + linarith only [hi, hj, hk, hd, Nat.zero_le b, Nat.zero_le c, Nat.zero_le (k * b), + Nat.zero_le (k * c)] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Redistribute +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Matching.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Matching.lean new file mode 100644 index 0000000000..f40822eaed --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Matching.lean @@ -0,0 +1,1000 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.FieldLift + +/-! +# Local movement of thin occurrences + +The column contraction moves a whole occurrence to its matched +destination if any of its outgoing rows is selected. Select one +such row from the padded array and recover the destination from +the thick mate. The row contraction leaves all occurrences in place. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match + +open Coloring Packing + +variable {d h e k ℓ : ℕ} (x : (Input d h e k ℓ).obj) + +/-- The motion of type `Bool × B (Labels h ℓ d).width`, constructed using `rows x`. -/ +def motion (b : B h) : Bool × B (Labels h ℓ d).width := + let y := rows x + let i := sampleRow y.control.1 b + (y.control.1 i, y.dest (y.control.2 i)) + +theorem cheap_motion (F : Type) [Field F] (d h e k ℓ t : ℕ) + (ht : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) (hw : k ≤ t) (hd : 2 ^ d ≤ t) : + Cheap F (h + e) t (Input d h e k ℓ) + (.vec h (.pair .bit (.addr (Labels h ℓ d).width))) motion 160 := by + have hi := ht + unfold Rows.overhead at hi + let A := Format.addr (Labels h ℓ d).width + have ha : (Format.pair .bit A).width ≤ t := by + unfold A; rw [Format.width_pair, Format.width_bit, Format.width_addr]; omega + have ctl := cheap_match F d h e k ℓ t ht hw hd + have remote := (cheap_rows F d h e k ℓ t ht hw hd).snd.snd.snd.snd + have get := Cheap.lookup F (h + e) t A (by omega) (by rw [Format.width_pair] at ha; omega) + have addr := (remote.pair ctl.snd).comp get + have sample := cheap_sample (h := h) (e := e) F (by omega) (.pair .bit A) ha + exact ((ctl.fst.pair (ctl.fst.pair addr).zip).comp sample).mono (by decide) + +private theorem mask_active {h k : ℕ} (x : Rows h k) {i : B h} (hi : x.control.1 i = true) : + x.active i = true := by + have := ((x.gather x.perm).mask_iff (x.perm.symm i)).mp hi + simpa only [Rows.gather, Rows.active, Function.comp_apply, Equiv.apply_symm_apply] using this.1.1 + +namespace Stubs +variable {P V E : Type} {r : ℕ} {src dst : E → P} {ix : E → Cell r} {owner : P → V} + (f : Stubs src dst ix owner d h e ℓ) + (data : V → (Input d h e k ℓ).obj) (m : Matching src dst ix) + (enc : f.Records data m.color) + (ctl : Rows.Controls (fun p => rows (data (owner p))) f.pos m) + +include enc ctl + +/-- The read address is the neighbor slot and colony key of the +specific thick mate. Inactive rows need no dummy destination. -/ +theorem motion_spec (p : P) (b : Cell r) (key : ((data (owner p)).2.1 (f.block b)).1 = f.tag p) : + let y := motion (data (owner p)) (f.block b) + y.1 = (m.plan p b).isSome ∧ + (y.1 = true → ∃ i, src i = p ∧ m.plan p b = some (dst i) ∧ + y.2 = (Labels h ℓ d).serial (0, f.tag (dst i), f.near i)) := by + let X := rows (data (owner p)) + let i := sampleRow X.control.1 (f.block b) + let y := motion (data (owner p)) (f.block b) + have hr : (rowIndex h e i).1 = f.block b := sampleRow_block _ _ + have hc : X.src i = f.key p := by simp only [X, Rows.src, rows, hr, key, Stubs.key] + have ok := f.represents data m.color enc p + have spec (hi : y.1 = true) : + ∃ j, src j = p ∧ m.plan p b = some (dst j) ∧ + y.2 = (Labels h ℓ d).serial (0, f.tag (dst j), f.near j) := by + change X.control.1 i = true at hi + obtain ⟨j, hj, hp⟩ := ok.onto i (mask_active X hi) hc + have hb : ix j = b := by + apply f.block.injective + simpa [← hp, pos] using hr + have hh : (m.plan (src j) (ix j)).isSome := by rw [ctl.mask, hj, hp]; exact hi + let t := m.mate ⟨j, hh⟩ + obtain ⟨_, ht, hd⟩ := m.spec ⟨j, hh⟩ + have hs : src t = p := ht.trans hj + have ha : f.pos t = X.control.2 i := by simpa only [hj, hp] using ctl.mate ⟨j, hh⟩ + refine ⟨t, hs, by simpa only [hj, hb] using hd, ?_⟩ + change X.dest (X.control.2 i) = _ + rw [← ha] + simp only [X, Rows.dest, rows, pos, Equiv.apply_symm_apply, ← hs, enc.slot, enc.remote] + refine ⟨Bool.eq_iff_iff.mpr ⟨?_, ?_⟩, spec⟩ + · intro hi + obtain ⟨_, _, ht, _⟩ := spec hi + simp [ht] + · intro hp + obtain ⟨j, hj, hb⟩ := m.used p b hp + have hh : X.control.1 (f.pos j) = true := by + have := ctl.mask j + rw [hj, hb] at this + exact this.symm.trans hp + change X.control.1 i = true + simpa [i, pos, hb] using sampleRow_marked _ hh + +end Stubs +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +/- +# Short addresses for contracted sites + +A moved station specifies a neighbor index and a colony label. From the +source of an original edge, both of its new endpoint addresses are at +most two local hops away. All six gadget parties use these same addresses. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +open Coloring Packing +variable {d h e k ℓ : ℕ} + +/-- The value specified by `Format.pair .bit (.pair (.addr ℓ) (.addr d))`. -/ +abbrev Move (d ℓ : ℕ) := Format.pair .bit (.pair (.addr ℓ) (.addr d)) + +/-- After the motion query, only the local label and one decision bit +are needed to determine the destination of the occurrence. -/ +def step (col : Bool) (own : B ℓ) (q : Bool × B (Labels h ℓ d).width) : (Move d ℓ).obj := + if col && q.1 then (true, ((Labels h ℓ d).serial.symm q.2).2) else (false, own, 0) + +/-- The value specified by `step (h := h) col (x.2.1 b).1 (motion x b)`. -/ +def action (col : Bool) (x : (Input d h e k ℓ).obj) (b : B h) := + step (h := h) col (x.2.1 b).1 (motion x b) + +variable {V : Type} (nav : V → B d → V) + +/-- The value specified by `(if a.1 then nav v a.2.2 else v, a.2.1)`. -/ +def follow (v : V) (a : (Move d ℓ).obj) : V × B ℓ := + (if a.1 then nav v a.2.2 else v, a.2.1) + +namespace Stubs +variable {P E : Type} {r : ℕ} {src dst : E → P} {ix : E → Cell r} {owner : P → V} + (f : Stubs src dst ix owner d h e ℓ) + (data : V → (Input d h e k ℓ).obj) (m : Matching src dst ix) + (enc : f.Records data m.color) + (ctl : Rows.Controls (fun p => rows (data (owner p))) f.pos m) + (contacts : ∀ i, nav (owner (src i)) (f.near i) = owner (dst i)) + +include enc ctl contacts + +theorem action_spec (p : P) (b : Cell r) (col : Bool) + (own : ((data (owner p)).2.1 (f.block b)).1 = f.tag p) : + let q := if col then (m.plan p b).getD p else p + follow nav (owner p) (action col (data (owner p)) (f.block b)) = (owner q, f.tag q) := by + obtain ⟨hm, he⟩ := f.motion_spec data m enc ctl p b own + cases col + · simp [action, step, follow, own] + cases h : m.plan p b with + | none => simp [action, step, follow, own, hm, h] + | some q => + have ha : (motion (data (owner p)) (f.block b)).1 = true := by rw [hm, h]; rfl + obtain ⟨i, hs, ht, hp⟩ := he ha + have eq : dst i = q := Option.some.inj (ht.symm.trans h) + have hv : nav (owner p) (f.near i) = owner q := by rw [← hs, contacts, eq] + simp [action, step, follow, ha, hp, hv, eq] +end Stubs + +/-- The first hop is optional. It precedes the movement of the endpoint. -/ +abbrev Path (d ℓ : ℕ) := Format.pair (.pair .bit (.addr d)) (Move d ℓ) + +/-- Computes the read path by the application `follow nav (if q.1.1 then nav v q.1.2 else v) +q.2`. -/ +def readPath (v : V) (q : (Path d ℓ).obj) := + follow nav (if q.1.1 then nav v q.1.2 else v) q.2 + +/-- The ends of type `(Path d ℓ).obj × (Path d ℓ).obj`, constructed using `(rowIndex h e i).1`. -/ +def ends (x : (Input d h e k ℓ).obj) (localMove : B h → (Move d ℓ).obj) + (remote : B d → B h → (Move d ℓ).obj) (i : B (h + e)) : (Path d ℓ).obj × (Path d ℓ).obj := + let b := (rowIndex h e i).1 + let j := (rowIndex h e i).2 + let w := ((x.2.1 b).2 j).2.1 + (((false, 0), localMove b), ((true, w), remote w b)) + +/-- The value specified by `![a.1, a.2, b.1, b.2, if col then b.2 else a.1, if col then a.2 else +b.2]`. -/ +def parties (col : Bool) {A : Type} (a b : A × A) : Fin 6 → A := + ![a.1, a.2, b.1, b.2, if col then b.2 else a.1, if col then a.2 else b.2] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +/- # Computing the local movement record without long addresses -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +open Coloring + +variable (F : Type) [Field F] {d h e k ℓ t : ℕ} + +private theorem unpack (A : Format) (ha : A.width ≤ t) : + Cheap F 0 t (.addr A.width) A A.serial.symm 2 := by + have aux (f : slots (word A.width) ≃ A.pins) : + Cheap F 0 t (.addr A.width) A + ((A.code.trans (f.symm.arrowCongr (.refl _))).trans (Format.addr _).code.symm).symm 2 := by + have hw : A.width ≤ 2 ^ 0 * (100 + t) ^ 1 := by simp; omega + have hd : (Format.addr A.width).width ≤ 2 ^ 0 * (100 + t) ^ 1 := by rwa [Format.width_addr] + apply Cheap.project F hd hw f.symm + intro x i + rw [Equiv.symm_trans_apply, Equiv.symm_trans_apply, Equiv.apply_symm_apply] + rfl + exact aux _ + +private abbrev Step (d h ℓ : ℕ) := + Format.pair .bit (.pair (.addr ℓ) (.pair .bit (.addr (Labels h ℓ d).width))) + +private theorem cheap_step (ht : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) : + Cheap F 0 t (Step d h ℓ) (Move d ℓ) (fun x => step x.1 x.2.1 x.2.2) 20 := by + have hw : (Step d h ℓ).width ≤ 2 ^ 0 * (100 + t) ^ 1 := by + simp only [Step, Format.width_pair, Format.width_addr, pow_zero, one_mul, pow_one] + rw [Format.width_bit] + rw [Rows.overhead, width_labels] at ht + omega + have hi := ht + rw [Rows.overhead, width_labels] at hi + have key := unpack F (Labels h ℓ d) (t := t) (by rw [width_labels]; omega) + have gate : Cheap F 0 t (.pair .bit .bit) .bit (fun x => x.1 && x.2) 2 := by + refine ⟨_, Coloring.small (A := .pair .bit .bit) (by simp) _, ?_⟩ + change 2 + 1 + 200 ≤ _ + ring_nf; omega + have x := Cheap.id F hw + have take := (x.fst.pair x.snd.snd.fst).comp gate + have data := (x.snd.snd.snd.comp key).snd + have zero := Cheap.const F hw (D := .addr d) (by simp; omega) (0 : B d) + have own := ((data.fst.pair x.snd.fst).pair take).comp ((cheap_select F ℓ).widen (l + := t) (by omega)) + have idx := ((data.snd.pair zero).pair take).comp ((cheap_select F d).widen (l := t) (by omega)) + convert (take.pair (own.pair idx)).mono (d := 20) (by decide) using 1 + funext x + simp only [step, Function.comp_apply, id_eq] + cases x.1 && x.2.2.1 <;> simp + +theorem cheap_lift {n p t c : ℕ} {A D : Format} {f : A.obj → D.obj} + (hf : Cheap F n t A D f c) (hn : n ≤ p) : Cheap F p t A D f c := by + obtain ⟨m, hf, hb⟩ := hf + exact ⟨m, hf, hb.trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) hn))⟩ + +private theorem zip {n c : ℕ} {A D E : Format} + {f : A.obj → (B h → D.obj) × (B h → E.obj)} + (hf : Cheap F n t A (.pair (.vec h D) (.vec h E)) f c) : + Cheap F n t A (.vec h (.pair D E)) (fun x i => ((f x).1 i, (f x).2 i)) (c + 1) := by + let x := Format.pair (.vec h D) (.vec h E) + let y := Format.vec h (.pair D E) + have hz : Circuit F x y (fun p i => (p.1 i, p.2 i)) (x.width + 2 * y.width) := + Circuit.project (Equiv.prodSumDistrib _ _ _) (by rintro p ⟨i, j | j⟩ <;> rfl) + obtain ⟨m, hm, hb⟩ := hf + refine ⟨_, hm.comp hz, ?_⟩ + have he : x.width = y.width := by simp [x, y, mul_add] + have hg : 5 * (2 ^ n * (100 + t) ^ c) ≤ 2 ^ n * (100 + t) ^ (c + 1) := by + rw [mul_comm 5, pow_succ, ← mul_assoc] + exact Nat.mul_le_mul_left _ (by omega) + change A.width + x.width + m ≤ _ at hb + change A.width + y.width + (m + (x.width + 2 * y.width)) ≤ _ + omega + +/-- The value specified by `Format.pair .bit (Input d h e k ℓ)`. -/ +abbrev Directed (d h e k ℓ : ℕ) := Format.pair .bit (Input d h e k ℓ) + +theorem cheap_action (d h e k ℓ t : ℕ) + (ht : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) (hw : k ≤ t) (hd : 2 ^ d ≤ t) : + Cheap F (h + e) t (Directed d h e k ℓ) (.vec h (Move d ℓ)) (fun x => action x.1 x.2) 180 := by + have hi := ht + rw [Rows.overhead, width_labels] at hi + let A := Directed d h e k ℓ + have ha : A.width ≤ 2 ^ (h + e) * (100 + t) ^ 31 := by + obtain ⟨m, _, hm⟩ := cheap_rows F d h e k ℓ t ht hw hd + rw [Format.width_pair, Format.width_bit, pow_succ (100 + t) 30, ← mul_assoc] + have := lt_mul_of_one_lt_right (by positivity : 0 < 2 ^ (h + e) * (100 + t) ^ 30) + (by omega : 1 < 100 + t) + omega + have small (U : Format) (hs : U.width ≤ t) : + (Format.vec h U).width ≤ 2 ^ (h + e) * (100 + t) ^ 31 := by + rw [Format.width_vec] + apply Nat.mul_le_mul (Nat.pow_le_pow_right (by decide) (by omega)) + have hwidth : U.width ≤ (100 + t) ^ 1 := by + simp + omega + exact hwidth.trans (Nat.pow_le_pow_right (by omega) (by decide)) + have col : Cheap F (h + e) t A (.vec h .bit) (fun x _ => x.1) 32 := + Cheap.project F ha (small .bit (by simp; omega)) (fun i => .inl i.2) (fun _ _ => rfl) + have label : Cheap F (h + e) t A (.vec h (.addr ℓ)) (fun x i => (x.2.2.1 i).1) 32 := + Cheap.project F ha (small (.addr ℓ) (by simp; omega)) + (fun i => .inr (.inr (.inl (i.1, .inl i.2)))) (fun _ _ => rfl) + have moved := (Cheap.id F ha).snd.comp (cheap_motion F d h e k ℓ t ht hw hd) + have send := cheap_lift F (Cheap.map (A := Step d h ℓ) (D := Move d ℓ) (fun _ => _) (fun _ : B h + => cheap_step F ht)) (Nat.le_add_right h e) + have inp := zip F (col.pair (zip F (label.pair moved))) + exact (inp.comp send).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +/- # Recovering the physical replacement endpoints from local records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +open Coloring Packing +variable {d h e k ℓ : ℕ} {V : Type} + (nav : V → B d → V) (data : V → (Input d h e k ℓ).obj) + +/-- The indexed operation `ends (data v) (action col (data v)) (fun j => action col (data (nav v +j)))`. -/ +def localEnds (col : Bool) (v : V) := + ends (data v) (action col (data v)) (fun j => action col (data (nav v j))) + +/-- The construction uses `localEnds nav data col v` for its intermediate `f`. -/ +def localParties (col : Bool) (v : V) (i : B (h + e)) := + let f := localEnds nav data col v + parties col (f ((rows (data v)).control.2 i)) (f i) + +variable [Fintype V] {E : Type} {N C : V → Finset V} {Δ D u r : ℕ} + {L : ℝ} {l : V → Cell r → ℝ} (g : Grouping N C Δ D u L l) + {src dst : E → V} {ix : E → Cell r} + +/-- The encoded site name stores a host position and a local interval key. -/ +structure Chart (m : Matching (g.ends src ix) (g.ends dst ix) ix) where + /-- The `Chart` component of type `Stubs (g.ends src ix) (g.ends dst ix) ix (fun p => p.1) d h + e ℓ`. -/ + stubs : Stubs (g.ends src ix) (g.ends dst ix) ix (fun p => p.1) d h e ℓ + records : stubs.Records data m.color + controls : Rows.Controls (fun p => rows (data p.1)) stubs.pos m + contacts : ∀ i, nav (src i) (stubs.near i) = dst i + labels : ∀ v j, ((data v).2.1 (stubs.block j)).1 = stubs.tag (g.loc v j) + /-- Embeds the coordinates as `Site V r ↪ V × B ℓ`. -/ + site : Site V r ↪ V × B ℓ + key : ∀ p, site (g.site p) = (p.1, stubs.tag p) + +namespace Chart + +variable {g nav data} {m : Matching (g.ends src ix) (g.ends dst ix) ix} + (p : Chart nav data g m) + +theorem moved (col : Bool) (v : V) (j : Cell r) : + follow nav v (action col (data v) (p.stubs.block j)) = p.site (g.route m col v j) := by + have h := p.stubs.action_spec nav data m p.records p.controls p.contacts (g.loc v j) j col + (p.labels v j) + cases col <;> exact h.trans (p.key _).symm + +theorem endpoints (col : Bool) (i : E) : + let f := readPath nav (src i) + Prod.map f f (localEnds nav data col (src i) (p.stubs.pos i)) = + (p.site (g.route m col (src i) (ix i)), p.site (g.route m col (dst i) (ix i))) := by + have hs : (((data (src i)).2.1 (p.stubs.block (ix i))).2 (p.stubs.stub i)).2.1 = + p.stubs.near i := p.records.slot i + simp only [localEnds, ends, Stubs.pos, Equiv.apply_symm_apply, Prod.map, readPath, + Bool.false_eq_true, ite_false, ite_true, hs, p.contacts] + exact Prod.ext (p.moved col _ _) (p.moved col _ _) + +theorem gadget (col : Bool) (i : m.items) (j : Fin 6) : + readPath nav (src i.val) (localParties nav data col (src i.val) (p.stubs.pos i.val) j) = + p.site (g.party m col i j) := by + have ptr : (rows (data (src i.val))).control.2 (p.stubs.pos i.val) = p.stubs.pos (m.mate i) := + (p.controls.mate i).symm + have origin : src (m.mate i) = src i.val := congrArg Sigma.fst (m.spec i).2.1 + let a := localEnds nav data col (src i.val) (p.stubs.pos (m.mate i)) + let b := localEnds nav data col (src i.val) (p.stubs.pos i.val) + let f := readPath (ℓ := ℓ) nav (src i.val) + have ha : Prod.map f f a = + (p.site (g.party m col i 0), p.site (g.party m col i 1)) := by + unfold f a + rw [← origin] + exact p.endpoints col _ + have hb : Prod.map f f b = + (p.site (g.party m col i 2), p.site (g.party m col i 3)) := p.endpoints col _ + unfold localParties + rw [ptr] + change f (parties col a b j) = _ + have h₀ := congrArg Prod.fst ha + have h₁ := congrArg Prod.snd ha + have h₂ := congrArg Prod.fst hb + have h₃ := congrArg Prod.snd hb + fin_cases j + · exact h₀ + · exact h₁ + · exact h₂ + · exact h₃ + · cases col + · exact h₀ + · exact h₃ + · cases col + · exact h₃ + · exact h₁ + +end Chart +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +/- # Stub and colony numbering for grouped host positions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing + +variable {V : Type} {h : ℕ} + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def cellIndex (h : ℕ) : Cell h ≃ B h := Fintype.equivOfCardEq (by simp [Cell]) + +open scoped Classical in +/-- Embeds `(Σ d : Fin (h + 1), Cell d.val)` into `B (h + 1)`. -/ +def intervalCode (h : ℕ) : (Σ d : Fin (h + 1), Cell d.val) ↪ B (h + 1) := + Classical.choice (Function.Embedding.nonempty_of_card_le (by + have ht := Site.card Unit h + simpa only [Site, Fintype.card_prod, Fintype.card_unit, one_mul, mul_one, B, + Fintype.card_fin, pow_succ'] using ht)) + +open scoped Classical in +/-- Embeds `Site V h` into `V × B (h + 1)`. -/ +def siteCode (V : Type) (h : ℕ) : Site V h ↪ V × B (h + 1) := + (Function.Embedding.refl V).prodMap (intervalCode h) + +namespace Scheme.Posting + +variable {F T : Type} [Field F] {x y : Wire} {L : Fringe x y T} {u : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h u} + (p : S.Posting r G) (hu : 0 < u) + +open scoped Classical in +/-- Follow a short neighbor index, defaulting to home for an empty seat. -/ +def nav (v : G.V) (i : B S.d) : G.V := + if h : ∃ w, p.host w = (r (p.host v)).1 i then h.choose else v + +include hu in +open scoped Classical in +theorem nav_target (i : G.E) : p.nav (G.src i) (p.index (G.src i) (G.dst i)) = G.dst i := by + have h : ∃ w, p.host w = (r (p.host (G.src i))).1 (p.index (G.src i) (G.dst i)) := + ⟨G.dst i, (p.target hu i).symm⟩ + rw [nav, dite_eq_left h] + exact p.host.injective (h.choose_spec.trans (p.target hu i)) + +variable (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + {l : G.V × Cell a → Cell (h - a) → ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' l) + +open scoped Classical in +/-- Computes the g src by the application `g.ends (G.regroup a ha).src (G.regroup a ha).ix`. -/ +abbrev gSrc := g.ends (G.regroup a ha).src (G.regroup a ha).ix +open scoped Classical in +/-- Computes the g dst by the application `g.ends (G.regroup a ha).dst (G.regroup a ha).ix`. -/ +abbrev gDst := g.ends (G.regroup a ha).dst (G.regroup a ha).ix + +open scoped Classical in +/-- The value specified by `(p.nav v.1 i, v.2)`. -/ +def groupNav (v : G.V × Cell a) (i : B S.d) := (p.nav v.1 i, v.2) + +open scoped Classical in +/-- The stubs of type `Match.Stubs (gSrc a ha g) (gDst a ha g) (G.regroup a ha).ix (fun v => +v.1) S.d (h - a) S.e (h - a + 1) where block` for the given inputs. -/ +def stubs : Match.Stubs (gSrc a ha g) (gDst a ha g) (G.regroup a ha).ix + (fun v => v.1) S.d (h - a) S.e (h - a + 1) where + block := (cellIndex _).toEmbedding + tag q := intervalCode _ (g.site q).2 + separate _ _ hv hi := g.site_injective (Prod.ext hv ((intervalCode _).injective hi)) + stub i := p.stub i false + unique i j he hb hi := by + have hs : (G.src i, ancestor ha (G.ix i)) = (G.src j, ancestor ha (G.ix j)) := + congrArg Sigma.fst he + obtain ⟨hv, hx⟩ := Prod.mk.inj hs + have hl : G.ix i = G.ix j := (splitCell a ha).injective (Prod.ext hx hb) + apply p.distinct hu + change ((p.host (G.src i), p.block (G.ix i), 0), p.stub i false) = + ((p.host (G.src j), p.block (G.ix j), 0), p.stub j false) + rw [hv, hl, hi] + near i := p.index (G.src i) (G.dst i) + neighbor i j he := by + have hs : (G.src i, ancestor ha (G.ix i)) = (G.src j, ancestor ha (G.ix j)) := + congrArg Sigma.fst he + obtain ⟨hv, hx⟩ := Prod.mk.inj hs + change _ ↔ (G.dst i, ancestor ha (G.ix i)) = (G.dst j, ancestor ha (G.ix j)) + constructor + · intro hi + have ht : G.dst i = G.dst j := by rw [← p.nav_target hu i, hi, hv, p.nav_target hu j] + exact Prod.ext ht hx + · intro ht + rw [hv, (Prod.mk.inj ht).1] + +end Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Extracting the outgoing records from local station patterns -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring Packing + +variable {F : Type} {d k e : ℕ} + +open scoped Classical in +/-- The outgoing of type `Bool × B d × B e`, constructed using `P.peer 0 j`. -/ +def Pattern.outgoing (P : Pattern F d k e) (j : B e) : Bool × B d × B e := + let q := P.peer 0 j + let active := decide (0 < P.width 0 j ∧ P.direction 0 j = false ∧ q.isSome) + (active, (q.getD (0, 0, 0)).1, (q.getD (0, 0, 0)).2.2) + +namespace Scheme.Posting + +variable [Field F] {T : Type} {x y : Wire} {L : Fringe x y T} {u h : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h u} + (p : S.Posting r G) (hu : 0 < u) + +open scoped Classical in +/-- The value specified by `(S.decode ((r (p.host v)).2 (p.block t))).outgoing`. -/ +def localStub (v : G.V) (t : Cell h) := + (S.decode ((r (p.host v)).2 (p.block t))).outgoing + +include hu in +open scoped Classical in +theorem active (v : G.V) (t : Cell h) (i : B S.e) : + (p.localStub v t i).1 = true ↔ ∃ q, G.src q = v ∧ G.ix q = t ∧ p.stub q false = i := by + trans S.outgoing r ((p.host v, p.block t, 0), i) + · simp [localStub, Pattern.outgoing, outgoing, width, direction, peer, pattern] + rw [p.enumerates hu] + simp [span, spanAt, side, p.host.injective.eq_iff, p.block.injective.eq_iff, and_assoc] + +open scoped Classical in +theorem local_slot (i : G.E) : + (p.localStub (G.src i) (G.ix i) (p.stub i false)).2 = + (p.index (G.src i) (G.dst i), p.stub i true) := by + have ht := p.link i false + change (S.decode ((r (p.host (G.src i))).2 (p.block (G.ix i)))).peer 0 (p.stub i false) = + some (p.index (G.src i) (G.dst i), 0, p.stub i true) at ht + simp [localStub, Pattern.outgoing, ht] + +variable (a : ℕ) (ha : a ≤ h) {Δ D j : ℕ} {B' : ℝ} + {l : G.V × Cell a → Cell (h - a) → ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D j B' l) + +open scoped Classical in +/-- Computes the label by the application `intervalCode _ (g.here v i).2`. -/ +def label (v : G.V × Cell a) (i : Cell (h - a)) := intervalCode _ (g.here v i).2 + +open scoped Classical in +/-- The records of type `(Match.Input S.d (h - a) S.e S.e (h - a + 1)).obj`, constructed using +`(cellIndex (h - a)).symm i`. -/ +def records (c : Color (h - a)) (v : G.V × Cell a) : + (Match.Input S.d (h - a) S.e S.e (h - a + 1)).obj := + let old i := (cellIndex (h - a)).symm i + (fun i => decide (thick c (old i)), + fun i => (label a g v (old i), p.localStub v.1 ((splitCell a ha).symm (v.2, old i))), + fun i t => label a g (p.groupNav a v t) (old i)) + +open scoped Classical in +theorem record_label (c : Color (h - a)) (v : G.V × Cell a) (i : Cell (h - a)) : + ((p.records a ha g c v).2.1 ((p.stubs hu a ha g).block i)).1 = + (p.stubs hu a ha g).tag (g.loc v i) := by + change label a g v ((cellIndex _).symm (cellIndex _ i)) = _ + rw [Equiv.symm_apply_apply] + rfl + +open scoped Classical in +theorem records_correct (c : Color (h - a)) : + (p.stubs hu a ha g).Records (p.records a ha g c) c := by + constructor + · intro v i j + change (p.localStub v.1 ((splitCell a ha).symm (v.2, (cellIndex _).symm i)) j).1 = true ↔ + ∃ q : G.E, (G.src q, ancestor ha (G.ix q)) = v ∧ cellIndex _ (suffix a (G.ix q)) = i ∧ + p.stub q false = j + rw [p.active hu] + apply exists_congr + intro q + rw [Equiv.eq_symm_apply, Prod.ext_iff] + change (G.src q = v.1 ∧ (ancestor ha (G.ix q) = v.2 ∧ + suffix a (G.ix q) = (cellIndex _).symm i) ∧ _) ↔ _ + rw [Equiv.eq_symm_apply, Prod.ext_iff] + tauto + · intro i + change G.E at i + change decide (thick c ((cellIndex _).symm (cellIndex _ (suffix a (G.ix i))))) = true ↔ _ + rw [decide_eq_true_eq, Equiv.symm_apply_apply] + rfl + · intro i + change G.E at i + exact p.record_label hu a ha g c _ _ + · intro i + change G.E at i + let q := G.ix i + change (p.localStub (G.src i) ((splitCell a ha).symm + (ancestor ha q, (cellIndex _).symm (cellIndex _ (suffix a q)))) (p.stub i false)).2.1 = _ + rw [Equiv.symm_apply_apply, show (ancestor ha q, suffix a q) = splitCell a ha q from rfl, + Equiv.symm_apply_apply] + exact congrArg Prod.fst (p.local_slot i) + · intro i + change G.E at i + change label a g (p.nav (G.src i) (p.index (G.src i) (G.dst i)), ancestor ha (G.ix i)) + ((cellIndex _).symm (cellIndex _ (suffix a (G.ix i)))) = _ + rw [Equiv.symm_apply_apply, p.nav_target hu] + rfl + +end Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Counting selector seats by the local mask bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match.Chart +open Coloring Packing + +variable {d h e k ℓ : ℕ} {V E : Type} [Fintype V] + {nav : V → B d → V} {data : V → (Input d h e k ℓ).obj} + {N C : V → Finset V} {Δ D u r : ℕ} + {L : ℝ} {l : V → Cell r → ℝ} {g : Grouping N C Δ D u L l} + {src dst : E → V} {ix : E → Cell r} + {m : Matching (g.ends src ix) (g.ends dst ix) ix} + (p : Chart nav data g m) + +open scoped Classical in +/-- Embeds `E` into `V × B (h + e) where toFun i`. -/ +def row : E ↪ V × B (h + e) where + toFun i := (src i, p.stubs.pos i) + inj' := by + intro i j he + obtain ⟨ha, hb⟩ := Prod.mk.inj he + have he := (rowIndex h e).symm.injective hb + have hi := p.stubs.block.injective (Prod.mk.inj he).1 + exact p.stubs.unique i j (by unfold Grouping.ends; rw [ha, hi]) hi (Prod.mk.inj he).2 + +open scoped Classical in +/-- Embeds `m.items` into `V × B (h + e)`. -/ +def marked : m.items ↪ V × B (h + e) := + (Function.Embedding.subtype _).trans p.row + +open scoped Classical in +theorem active (j : V × B (h + e)) : + (rows (data j.1)).active j.2 = true ↔ j ∈ Set.range p.row := by + constructor + · intro hj + obtain ⟨i, hs, hb, he⟩ := (p.records.active _ _ _).mp hj + exact ⟨i, Prod.ext hs ((rowIndex h e).symm_apply_eq.mpr (Prod.ext hb he))⟩ + · rintro ⟨i, rfl⟩ + exact (p.stubs.represents data _ p.records _).active i rfl + +open scoped Classical in +theorem marks (j : V × B (h + e)) : + (rows (data j.1)).control.1 j.2 = true ↔ j ∈ Set.range p.marked := by + constructor + · intro hj + let x := rows (data j.1) + have hh := ((x.gather x.perm).mask_iff (x.perm.symm j.2)).mp hj + have he : x.active j.2 = true := by + simpa only [Rows.gather, Rows.active, Function.comp_apply, Equiv.apply_symm_apply] + using hh.1.1 + obtain ⟨i, rfl⟩ := (p.active j).mp he + exact ⟨⟨i, (p.controls.mask i).trans hj⟩, rfl⟩ + · rintro ⟨i, rfl⟩ + exact (p.controls.mask i.val).symm.trans i.property + +include p in +open scoped Classical in +theorem mark_count [Fintype E] : + (∑ v, (Finset.univ.filter fun i => (rows (data v)).control.1 i).card) = m.count := by + let s := Finset.univ.filter fun j : V × B (h + e) => (rows (data j.1)).control.1 j.2 + have hs : s = Finset.univ.map p.marked := by + ext j + simp only [s, Finset.mem_filter, Finset.mem_univ, true_and, p.marks, Finset.mem_map, + Set.mem_range] + have he : s.card = m.count := by rw [hs, Finset.card_map, Finset.card_univ, m.card_items] + rw [← he] + simp only [s, Finset.card_eq_sum_ones, Finset.sum_filter, Fintype.sum_prod_type] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match.Chart +end + +/- +# Candidate wires for an entire subround + +A fixed bank of slots accompanies each possible old row. The forward +and reciprocal mask bits distinguish the two members of a matched +pair from an untouched unit. Test for loops after reading the addresses. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +open Coloring Packing Spectral.Tensor + +open scoped Classical in +/-- Indexes the kind by the coordinates of `(Fin 8 × Fin (4 * b)) ⊕ Fin b`. -/ +abbrev Kind (b : ℕ) := (Fin 8 × Fin (4 * b)) ⊕ Fin b +open scoped Classical in +/-- Indexes the candidate by the coordinates of `(V × B n) × Kind b`. -/ +abbrev Candidate (V : Type) (n b : ℕ) := (V × B n) × Kind b + +variable {V : Type} {d h e k ℓ b : ℕ} + (nav : V → B d → V) (data : V → (Input d h e k ℓ).obj) + +open scoped Classical in +/-- The construction uses `rows (data j.1)` for its intermediate `x`. -/ +def untouched (j : V × B (h + e)) := + let x := rows (data j.1) + x.active j.2 && !(x.control.1 j.2) && !(x.control.1 (x.control.2 j.2)) + +open scoped Classical in +/-- In the case `.inl (j, t)`, this construction gives `(rows (data q.1.1)).control.1 q.1.2 && +decide (t.val < shape q.1 j)`. -/ +def enabled (shape : V × B (h + e) → Fin 8 → ℕ) (q : Candidate V (h + e) b) : Bool := + match q.2 with + | .inl (j, t) => (rows (data q.1.1)).control.1 q.1.2 && decide (t.val < shape q.1 j) + | .inr _ => untouched data q.1 + +open scoped Classical in +/-- The paths of type `(Path d ℓ).obj × (Path d ℓ).obj`, constructed using `q.1`. -/ +def paths (col : Bool) (q : Candidate V (h + e) b) : (Path d ℓ).obj × (Path d ℓ).obj := + let (v, i) := q.1 + match q.2 with + | .inl (j, _) => Prod.map (localParties nav data col v i) (localParties nav data col v i) + (sixPair j) + | .inr _ => localEnds nav data col v i + +namespace Chart +variable {nav data} {E F : Type} [Field F] [Fintype V] {N C : V → Finset V} {Δ D u r : ℕ} + {L : ℝ} {l : V → Cell r → ℝ} {g : Grouping N C Δ D u L l} + {src dst : E → V} {ix : E → Cell r} + {m : Matching (g.ends src ix) (g.ends dst ix) ix} + (p : Chart nav data g m) + +open scoped Classical in +private theorem paired (i : E) : i ∈ Set.range m.pairEdge ↔ + (m.plan (g.ends src ix i) (ix i)).isSome ∨ ∃ t, m.mate t = i := by + constructor + · rintro ⟨⟨t, j⟩, rfl⟩ + fin_cases j + · exact .inr ⟨t, rfl⟩ + · exact .inl t.property + · rintro (hi | ⟨t, rfl⟩) + · exact ⟨(⟨i, hi⟩, 1), rfl⟩ + · exact ⟨(t, 0), rfl⟩ + +open scoped Classical in +theorem untouched_iff (j : V × B (h + e)) : + untouched data j = true ↔ ∃ i : m.unpaired, p.row i.val = j := by + have onRow (i : E) : untouched data (p.row i) = true ↔ i ∉ Set.range m.pairEdge := by + have ha := (p.active (p.row i)).mpr ⟨i, rfl⟩ + have hm := p.controls.mask i + have ht := p.controls.used_iff (p.stubs.represents data _ p.records) i + change (m.plan _ _).isSome = (rows (data (p.row i).1)).control.1 (p.row i).2 at hm + change (rows (data (p.row i).1)).control.1 + ((rows (data (p.row i).1)).control.2 (p.row i).2) = true ↔ _ at ht + simp only [untouched, Bool.and_eq_true, Bool.not_eq_true', ha, true_and, ← hm, + paired, not_or, ← ht, Bool.not_eq_true] + constructor + · intro hj + have ha := hj + simp only [untouched, Bool.and_eq_true] at ha + obtain ⟨i, rfl⟩ := (p.active j).mp ha.1.1 + exact ⟨⟨i, (onRow i).mp hj⟩, rfl⟩ + · rintro ⟨i, rfl⟩ + exact (onRow _).mpr i.property + +variable (P : Gadget F) (i : g.Choice m P) + +open scoped Classical in +theorem profile_le (t : m.items) (j : Fin 8) : g.profile m i t j ≤ 4 * P.b := + (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ j)).trans (P.cost _ (i + t).2.property).le + +open scoped Classical in +/-- In the case `.inl ⟨t, j, k⟩`, this construction gives `(p.marked t, .inl (j, Fin.castLE +(profile_le P i t j) k))`. -/ +def event : g.Supply m P i ↪ Candidate V (h + e) P.b where + toFun + | .inl ⟨t, j, k⟩ => (p.marked t, .inl (j, Fin.castLE (profile_le P i t j) k)) + | .inr (t, k) => (p.row t.val, .inr k) + inj' := by + rintro (⟨t, j, k⟩ | ⟨t, k⟩) (⟨a, z, w⟩ | ⟨a, w⟩) he + · obtain ⟨hr, hj⟩ := Prod.mk.inj he + cases p.marked.injective hr + obtain ⟨rfl, hk⟩ := Prod.mk.inj (Sum.inl.inj hj) + have hk' : k = w := Fin.castLE_injective _ hk + rw [hk'] + · cases (Prod.mk.inj he).2 + · cases (Prod.mk.inj he).2 + · obtain ⟨hr, hw⟩ := Prod.mk.inj he + exact congrArg Sum.inr (Prod.ext (Subtype.ext (p.row.injective hr)) (Sum.inr.inj hw)) + +variable (shape : V × B (h + e) → Fin 8 → ℕ) + (code : ∀ t, shape (p.marked t) = g.profile m i t) + +include code in +open scoped Classical in +theorem enabled_iff (q : Candidate V (h + e) P.b) : + enabled data shape q = true ↔ q ∈ Set.range (p.event P i) := by + constructor + · rcases q with ⟨x, ⟨j, k⟩ | k⟩ + · simp only [enabled, Bool.and_eq_true, decide_eq_true_eq] + rintro ⟨hx, hk⟩ + obtain ⟨t, rfl⟩ := (p.marks x).mp hx + rw [code] at hk + exact ⟨.inl ⟨t, j, ⟨k.val, hk⟩⟩, rfl⟩ + · intro h + obtain ⟨t, rfl⟩ := (p.untouched_iff x).mp h + exact ⟨.inr (t, k), rfl⟩ + · rintro ⟨⟨t, j, k⟩ | ⟨t, k⟩, rfl⟩ + · change ((rows (data (p.marked t).1)).control.1 (p.marked t).2 && + decide (k.val < shape (p.marked t) j)) = true + simp only [Bool.and_eq_true, decide_eq_true_eq, code] + exact ⟨(p.marks _).mpr ⟨t, rfl⟩, k.isLt⟩ + · exact (p.untouched_iff _).mpr ⟨t, rfl⟩ + +open scoped Classical in +theorem read_event (col : Bool) (s : g.Supply m P i) : + let q := p.event P i s + let f := readPath nav q.1.1 + Prod.map f f (paths nav data col q) = Prod.map p.site p.site (g.contact m col s) := by + rcases s with ⟨t, j, k⟩ | ⟨t, k⟩ + · exact Prod.ext (p.gadget col t (sixPair j).1) (p.gadget col t (sixPair j).2) + · exact p.endpoints col t.val + +variable [Fintype E] + +open scoped Classical in +/-- Embeds `g.Survivors m P i` into `Candidate V (h + e) P.b`. -/ +def survivor : g.Survivors m P i ↪ Candidate V (h + e) P.b := + (Function.Embedding.subtype _).trans (p.event P i) + +include code in +open scoped Classical in +theorem survives_iff (collision : V → (Path d ℓ).obj → (Path d ℓ).obj → Bool) + (test : ∀ v a b, collision v a b = true ↔ readPath nav v a = readPath nav v b) + (q : Candidate V (h + e) P.b) : + let z := paths nav data (g.layout m P i) q + (enabled data shape q && !(collision q.1.1 z.1 z.2)) = true ↔ + q ∈ Set.range (p.survivor P i) := by + have cross (s : g.Supply m P i) : + let q := p.event P i s + let z := paths nav data (g.layout m P i) q + collision q.1.1 z.1 z.2 = false ↔ + (g.contact m (g.layout m P i) s).1 ≠ (g.contact m (g.layout m P i) s).2 := by + have he := p.read_event P i (g.layout m P i) s + have h₁ := congrArg Prod.fst he + have h₂ := congrArg Prod.snd he + simp only [Prod.map_fst, Prod.map_snd] at h₁ h₂ + simp only [← Bool.not_eq_true, test, h₁, h₂, p.site.injective.eq_iff] + simp only [Bool.and_eq_true, Bool.not_eq_true', p.enabled_iff P i shape code] + constructor + · rintro ⟨⟨s, rfl⟩, hs⟩ + exact ⟨⟨s, (cross s).mp hs⟩, rfl⟩ + · rintro ⟨s, rfl⟩ + exact ⟨⟨s.val, rfl⟩, (cross s.val).mpr s.property⟩ + +open scoped Classical in +theorem pick_layout {n a : ℕ} (index : B n ≃ V × B (h + e)) + (profile : B a → Fin 8 → ℕ) (x : (Side.Input n a).obj) + (active : ∀ j, (x j).1 = (rows (data (index j).1)).control.1 (index j).2) + (value : ∀ t, profile (x (index.symm (p.marked t))).2 = g.profile m i t) : + Side.pick profile x = g.layout m P i := by + apply Side.pick_eq_side profile (g.profile m i) x (p.marked.trans index.symm.toEmbedding) _ value + intro j + rw [active, p.marks] + exact exists_congr fun t => index.symm_apply_eq.symm + +open scoped Classical in +/-- This version allows the host index set itself to be padded. -/ +theorem extract_layout {n a : ℕ} (host : V ↪ B n) (profile : B a → Fin 8 → ℕ) + (x : B n → (Side.Tagged d h e k ℓ a).obj) + (read : ∀ v, (x (host v)).1 = data v) + (pad : ∀ v, v ∉ Set.range host → ∀ j, (rows (x v).1).control.1 j = false) + (value : ∀ t, profile ((x (host (p.marked t).1)).2 (p.marked t).2) = g.profile m i t) : + Side.pick profile (Side.extract x) = g.layout m P i := by + let places := rowIndex n (h + e) + let addr := (host.prodMap (.refl (B (h + e)))).trans places.symm.toEmbedding + have hread (j : V × B (h + e)) : Side.extract x (addr j) = + Side.clean ((rows (data j.1)).control.1 j.2, (x (host j.1)).2 j.2) := by + change Side.collect (x (places (places.symm (host j.1, j.2))).1) + (places (places.symm (host j.1, j.2))).2 = _ + simp only [Equiv.apply_symm_apply, Side.collect, read] + apply Side.pick_eq_side profile (g.profile m i) _ (p.marked.trans addr) + · intro j + constructor + · intro hj + have hv : (places j).1 ∈ Set.range host := by + by_contra hn + exact Bool.noConfusion ((pad _ hn (places j).2).symm.trans hj) + obtain ⟨v, hv⟩ := hv + have he : addr (v, (places j).2) = j := places.symm_apply_eq.mpr (Prod.ext hv rfl) + rw [← he, hread] at hj + obtain ⟨t, ht⟩ := (p.marks _).mp hj + exact ⟨t, (congrArg addr ht).trans he⟩ + · rintro ⟨t, rfl⟩ + rw [Function.Embedding.trans_apply, hread] + exact (p.marks _).mpr ⟨t, rfl⟩ + · intro t + rw [Function.Embedding.trans_apply, hread] + simp only [Side.clean, (p.marks _).mpr ⟨t, rfl⟩, ite_true, value] + +end Chart +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +/- # A subround matching determined by fixed-width arrays -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +open Finset Coloring Packing + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u h : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h u} + (p : S.Posting r G) (hu : 0 < u) (a : ℕ) (ha : a ≤ h) {Δ D k : ℕ} {B' : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B' (G.regroup a ha).load) + +open scoped Classical in +/-- Computes the row data by the application `Match.rows (p.records a ha g c q.1)`. -/ +abbrev rowData (c : Color (h - a)) (q : g.Colony) := Match.rows (p.records a ha g c q.1) + +open scoped Classical in +/-- Computes the matchings by the application `Matching (gSrc a ha g) (gDst a ha g) (G.regroup a +ha).ix`. -/ +abbrev Matchings := Matching (gSrc a ha g) (gDst a ha g) (G.regroup a ha).ix + +open scoped Classical in +/-- The value specified by `Rows.Controls (p.rowData a ha g m.color) (p.stubs hu a ha g).pos m`. -/ +def Controls (m : Matchings a ha g) := + Rows.Controls (p.rowData a ha g m.color) (p.stubs hu a ha g).pos m + +open scoped Classical in +/-- Builds `Match.Chart (p.groupNav a) (p.records a ha g m.color) g m where stubs` with the +specified `stubs`, `records`, `controls`, `contacts`. -/ +def chart (m : Matchings a ha g) (ctl : p.Controls hu a ha g m) : + Match.Chart (p.groupNav a) (p.records a ha g m.color) g m where + stubs := p.stubs hu a ha g + records := p.records_correct hu a ha g m.color + controls := ctl + contacts e := Prod.ext (p.nav_target hu e) rfl + labels := p.record_label hu a ha g m.color + site := siteCode _ _ + key _ := rfl + +open scoped Classical in +theorem all_colors (c : Color (h - a)) : + ∃ m : Matchings a ha g, m.color = c ∧ p.Controls hu a ha g m := by + let r := p.rowData a ha g c + let b := p.stubs hu a ha g + obtain ⟨m, hc, hh, _⟩ := Rows.controlled_matching r b.pos + (b.represents _ _ (p.records_correct hu a ha g c)) (Fintype.card G.E) (coreBins Δ) + (fun _ _ => card_le_univ _) (g.destinations _ _ _ (G.regroup a ha).edge) + exact ⟨m, hc, by unfold Controls; rw [hc]; exact hh⟩ + +open scoped Classical in +theorem matching (σ : ℝ) (hB : 0 < B') (bounds : G.Bounded Δ D B') + (hbins : 256 * (coreBins Δ + 1) ≤ 2 ^ k) + (slack : (2 : ℝ) ^ k * B' * (Fintype.card G.V * 2 ^ a : ℕ) ≤ σ) : + ∃ m : Matchings a ha g, p.Controls hu a ha g m ∧ + (G.X : ℝ) / 4 - (L.Z + σ) ≤ u * (m.count : ℝ) := by + let H := G.regroup a ha + let b := p.stubs hu a ha g + have hb := G.regroup_bounded a ha bounds + obtain ⟨m, hc, hm⟩ := Rows.controlled_subround (gSrc a ha g) (gDst a ha g) H.ix + (p.rowData a ha g) (fun _ => b.pos) (fun _ => b.key) + (fun c => b.represents _ _ (p.records_correct hu a ha g c)) u B' (coreBins Δ) + (Nat.cast_pos.mpr hu) hB.le + (fun q t => (g.outgoing H.src H.ix u (Nat.cast_nonneg _) H.outgoing q t).trans (hb.2.2 _ _)) + (g.destinations _ _ _ H.edge) + have hs : (2 : ℝ) ^ k * B' * Fintype.card (G.V × Cell a) ≤ σ := by + rwa [Fintype.card_prod, card_cell] + have hl : (∑ v, ∑ i, H.load v i) ≤ 2 * ((G.X : ℝ) + L.Z) := by + rw [mul_add]; exact H.sum_load + have hk : (256 : ℝ) * (coreBins Δ + 1) ≤ 2 ^ k := by exact_mod_cast hbins + have hσ : 0 ≤ σ := (show 0 ≤ (2 : ℝ) ^ k * B' * Fintype.card (G.V × Cell a) by + positivity).trans hs + have h := bin_charge hB (by positivity) (Nat.cast_nonneg _) L.total_nonneg hσ hk hs hl + g.card_bound + have he : (u : ℝ) * Fintype.card H.E = G.X := by + change (u : ℝ) * Fintype.card G.E = ↑(Fintype.card G.E * u) + rw [Nat.cast_mul, mul_comm] + refine ⟨m, hc, ?_⟩ + rw [he] at hm + linarith only [h, hm] + +open scoped Classical in +/-- Indexes the score by the coordinates of `∑ v : G.V × Cell a, (univ.filter fun i => +(Match.rows (p.records a ha g c v)).control.1 i).card`. -/ +def score (c : Color (h - a)) := + ∑ v : G.V × Cell a, (univ.filter fun i => (Match.rows (p.records a ha g c v)).control.1 i).card + +open scoped Classical in +theorem match_score (m : Matchings a ha g) (ctl : p.Controls hu a ha g m) : + p.score a ha g m.color = m.count := + (p.chart hu a ha g m ctl).mark_count + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Merge/Program.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Merge/Program.lean new file mode 100644 index 0000000000..2ee17ff924 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Merge/Program.lean @@ -0,0 +1,861 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanSupplies +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial + +/-! +# Concatenating spans at one station + +The channel and direction identify the new lane. The two ends of +each contact order old spans by the lane at the source. Exposed spans +retain their old relative order on each side. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring Finset + +variable {F : Type} {d k e : ℕ} + +open scoped Classical in +/-- Indexes the key by the coordinates of `Option (B d) × Bool`. -/ +abbrev Key (d : ℕ) := Option (B d) × Bool + +open scoped Classical in +/-- Embeds `Key d` into `B (d + 2)`. -/ +def code (d : ℕ) : Key d ↪ B (d + 2) := + Classical.choice (Function.Embedding.nonempty_of_card_le (by + simp only [Key, Fintype.card_prod, Fintype.card_option, Fintype.card_bool, Fintype.card_fin, + pow_add] + have := Nat.one_le_pow d 2 (by decide) + omega)) + +open scoped Classical in +/-- Computes the parse by the application `Function.invFun (code d) i`. -/ +def parse (i : B (d + 2)) : Key d := Function.invFun (code d) i + +open scoped Classical in +@[simp] theorem parse_code (p : Key d) : parse (code d p) = p := + Function.leftInverse_invFun (code d).injective _ + +variable (P : Pattern F d k e) (v : B k) + +open scoped Classical in +/-- Transforms the indexed data by `code d ((P.peer v i).map Prod.fst, P.direction v i)`. -/ +def lane (i : B e) := code d ((P.peer v i).map Prod.fst, P.direction v i) + +open scoped Classical in +/-- Transforms the indexed data by `((P.peer v i).map fun z => z.2.2).getD i`. -/ +def mate (i : B e) := ((P.peer v i).map fun z => z.2.2).getD i + +open scoped Classical in +/-- Returns `mate P v i` when `P.direction v i` holds, and `i` otherwise. -/ +def order (i : B e) := if P.direction v i then mate P v i else i + +open scoped Classical in +/-- The sum of `P.width v i` indexed by `i with lane P v i = s`. -/ +def length (s : B (d + 2)) := ∑ i with lane P v i = s, P.width v i + +open scoped Classical in +/-- The sum of `P.width v j` indexed by `j with lane P v j = lane P v i ∧ order P v j < order P +v i`. -/ +def offset (i : B e) := + ∑ j with lane P v j = lane P v i ∧ order P v j < order P v i, P.width v j + +open scoped Classical in +private theorem prefix_le (i : B e) (a : Finset (B e)) (ha : i ∈ a) + (hall : ∀ j, lane P v j = lane P v i → order P v j < order P v i → j ∈ a) : + offset P v i + P.width v i ≤ ∑ j ∈ a, P.width v j := by + unfold offset + rw [add_comm, ← sum_insert (by simp)] + refine sum_le_sum_of_subset (insert_subset ha ?_) + intro j hj + exact hall j (mem_filter.mp hj).2.1 (mem_filter.mp hj).2.2 + +open scoped Classical in +theorem inside (i : B e) : offset P v i + P.width v i ≤ length P v (lane P v i) := + prefix_le P v i _ (by simp) (fun _ h _ => mem_filter.mpr ⟨mem_univ _, h⟩) + +open scoped Classical in +theorem before {i j : B e} (h : lane P v i = lane P v j) (h' : order P v i < order P v j) : + offset P v i + P.width v i ≤ offset P v j := + prefix_le P v i _ (mem_filter.mpr ⟨mem_univ _, h, h'⟩) + (fun _ a b => mem_filter.mpr ⟨mem_univ _, a.trans h, b.trans h'⟩) + +open scoped Classical in +/-- The quantity computed by `⟨lane P v p.1, offset P v p.1 + p.2.val, (Nat.add_lt_add_left +p.2.isLt _).trans_le (inside P v p.1)⟩`. -/ +def index (p : P.Pin v) : Σ s, Fin (length P v s) := + ⟨lane P v p.1, offset P v p.1 + p.2.val, + (Nat.add_lt_add_left p.2.isLt _).trans_le (inside P v p.1)⟩ + +open scoped Classical in +theorem bijective (uniq : ∀ i j, 0 < P.width v i → 0 < P.width v j → + lane P v i = lane P v j → order P v i = order P v j → i = j) : + Function.Bijective (index P v) := by + apply (Fintype.bijective_iff_injective_and_card _).mpr + constructor + · rintro ⟨i, x⟩ ⟨j, y⟩ he + have hc : lane P v i = lane P v j := congrArg Sigma.fst he + have hw : offset P v i + x.val = offset P v j + y.val := + congrArg (fun p => p.2.val) he + have hi := x.isLt + have hj := y.isLt + rcases lt_trichotomy (order P v i) (order P v j) with h|h|h + · have := before P v hc h; omega + · have h' := uniq _ _ (by omega) (by omega) hc h + subst j + rw [show x = y from Fin.ext (by omega)] + · have := before P v hc.symm h; omega + · simp only [Pattern.Pin, Fintype.card_sigma, Fintype.card_fin, length, sum_filter] + rw [sum_comm]; simp + +variable (back : B d → B d) + +open scoped Classical in +/-- Builds `Pattern F d k (d + 2) where width` with the specified `width`, `direction`, `peer`, +`value`. -/ +def pattern : Pattern F d k (d + 2) where + width := length P + direction _ s := (parse s).2 + peer v s := if length P v s = 0 then none else (parse s).1.map fun c => + (c, 0, code d (some (back c), !(parse s).2)) + value v x := P.value v fun i j => x (index P v ⟨i, j⟩).1 (index P v ⟨i, j⟩).2 + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- # Short labels for merging spans. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring Finset + +variable {F : Type} (S : Scheme F) + +open scoped Classical in +/-- The value specified by `Format.pair (.addr S.ℓ) (.vec S.d (.addr S.d))`. -/ +abbrev key := Format.pair (.addr S.ℓ) (.vec S.d (.addr S.d)) + +open scoped Classical in +/-- The indexed operation `{ S with e := S.d + 2, ℓ := (key S).width, decode := fun c => let a +:= (key S).serial.symm c pattern (S.decode a.1) a.2 }`. -/ +abbrev scheme : Scheme F := + { S with e := S.d + 2, ℓ := (key S).width, + decode := fun c => let a := (key S).serial.symm c + pattern (S.decode a.1) a.2 } + +open scoped Classical in +theorem label_width : (scheme S).ℓ = S.ℓ + 2 ^ S.d * S.d := by simp [key] + +open scoped Classical in +/-- The sum of `if (r ((r i).1 j)).1 k = i then k else 0` indexed by `k`. -/ +def back (r : S.format.obj) (i : B S.m) (j : B S.d) : B S.d := + ∑ k, if (r ((r i).1 j)).1 k = i then k else 0 + +open scoped Classical in +/-- Evaluates `((r i).1, fun z => (key S).serial ((r i).2 z, back S r i))` at the input `i`. -/ +def rows (r : S.format.obj) : (scheme S).format.obj := + fun i => ((r i).1, fun z => (key S).serial ((r i).2 z, back S r i)) + +open scoped Classical in +/-- Uses `{ D with scheme := scheme D.scheme, order := Equiv.refl _ }` as the representation. -/ +abbrev template (D : Template F) : Template F := + { D with scheme := scheme D.scheme, order := Equiv.refl _ } + +open scoped Classical in +/-- The value specified by `(rows D.scheme r.1, r.2)`. -/ +def record (D : Template F) (r : D.format.obj) : (template D).format.obj := + (rows D.scheme r.1, r.2) + +variable (r : S.format.obj) + +open scoped Classical in +theorem at_row (v : S.Vtx) : + (scheme S).pattern (rows S r) v = pattern (S.pattern r v) (back S r v.1) := by + simp only [Scheme.pattern, rows, scheme, Equiv.symm_apply_apply] + +open scoped Classical in +theorem width (v : S.Vtx) (c : B (S.d + 2)) : + (scheme S).width (rows S r) (v, c) = length (S.pattern r v) v.2.2 c := by + rw [Scheme.width, at_row]; rfl + +open scoped Classical in +theorem direction (v : S.Vtx) (c : B (S.d + 2)) : + (scheme S).direction (rows S r) (v, c) = (parse c).2 := by + rw [Scheme.direction, at_row]; rfl + +open scoped Classical in +theorem peer (v : S.Vtx) (c : B (S.d + 2)) : + (scheme S).peer (rows S r) (v, c) = + if length (S.pattern r v) v.2.2 c = 0 then none else + (parse c).1.map fun j => (((r v.1).1 j, v.2.1, 0), + code S.d (some (back S r v.1 j), !(parse c).2)) := by + rw [Scheme.peer, at_row] + simp only [pattern] + split + · rfl + · cases (parse c).1 <;> rfl + +open scoped Classical in +/-- The value specified by `Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) r`. -/ +abbrev Recip := Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) r + +open scoped Classical in +theorem back_eq (hr : Recip S r) {i l : B S.m} {j k : B S.d} + (hj : (r i).1 j = l) (hk : (r l).1 k = i) (hne : i ≠ l) : back S r i j = k := by + have hu := hr i j (by rw [hj]; exact hne.symm) + rw [hj] at hu + have eq a : (r l).1 a = i ↔ a = k := ⟨fun h => hu.unique h hk, fun h => h ▸ hk⟩ + simp only [back, hj, eq, sum_ite_eq', mem_univ, ite_true] + +open scoped Classical in +/-- Computes the band by the application `lane (S.pattern r v) v.2.2 i`. -/ +abbrev band (v : S.Vtx) (i : B S.e) := lane (S.pattern r v) v.2.2 i +open scoped Classical in +/-- Computes the priority by the application `order (S.pattern r v) v.2.2 i`. -/ +abbrev priority (v : S.Vtx) (i : B S.e) := order (S.pattern r v) v.2.2 i +open scoped Classical in +/-- Computes the start by the application `offset (S.pattern r v) v.2.2 i`. -/ +abbrev start (v : S.Vtx) (i : B S.e) := offset (S.pattern r v) v.2.2 i + +open scoped Classical in +/-- On the destination side the source lane is unique by reciprocity. -/ +theorem distinct (h : S.Proper r) (v : S.Vtx) (i j : B S.e) + (hc : band S r v i = band S r v j) (hp : priority S r v i = priority S r v j) + (hk : S.k = 0) : i = j := by + have : Subsingleton (B S.k) := by rw [hk]; exact inferInstanceAs (Subsingleton (Fin 1)) + obtain ⟨he, hd⟩ := Prod.mk.inj ((code S.d).injective hc) + unfold priority order at hp + rw [hd] at hp + split at hp + · unfold mate at hp + cases hi : (S.pattern r v).peer v.2.2 i with + | none => + have hj : (S.pattern r v).peer v.2.2 j = none := by simpa [hi] using he.symm + simpa [hi, hj] using hp + | some a => + cases hj : (S.pattern r v).peer v.2.2 j with + | none => simp [hi, hj] at he + | some b => + have hab : a = b := Prod.ext (by simpa [hi, hj] using he) + (Prod.ext (Subsingleton.elim ..) (by simpa [hi, hj] using hp)) + subst b + have hi' : S.peer r (v, i) = some (((r v.1).1 a.1, v.2.1, a.2.1), a.2.2) + := by simp [Scheme.peer, hi] + have hj' : S.peer r (v, j) = some (((r v.1).1 a.1, v.2.1, a.2.1), a.2.2) + := by simp [Scheme.peer, hj] + exact congrArg Prod.snd (Option.some.inj ((h _ _ hi').1.symm.trans (h _ _ hj').1)) + · exact hp + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- # Matching the two ordered lists of spans on a contact -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring Finset + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {v w : S.Vtx} {c d : B S.d} + +open scoped Classical in +/-- Computes the other by the application `mate (S.pattern r v) v.2.2`. -/ +abbrev other (S : Scheme F) (r : S.format.obj) (v : S.Vtx) := mate (S.pattern r v) v.2.2 + +open scoped Classical in +/-- The data for the contact construction, including `left`, `right`, `block`, `ne`. -/ +structure Contact (S : Scheme F) (r : S.format.obj) (v w : S.Vtx) (c d : B S.d) : Prop where + left : (r v.1).1 c = w.1 + right : (r w.1).1 d = v.1 + block : v.2.1 = w.2.1 + ne : v.1 ≠ w.1 + +open scoped Classical in +theorem Contact.symm (h : Contact S r v w c d) : Contact S r w v d c := + ⟨h.right, h.left, h.block.symm, h.ne.symm⟩ + +variable {i j : B S.e} + +open scoped Classical in +theorem contact (pr : S.Proper r) (h : S.peer r (v, i) = some (w, j)) (ne : v.1 ≠ w.1) : + ∃ c d, Contact S r v w c d := by + have hw := (pr _ _ h).1 + unfold Scheme.peer at h hw + obtain ⟨q, _, hq⟩ := Option.map_eq_some_iff.mp h + obtain ⟨z, _, hz⟩ := Option.map_eq_some_iff.mp hw + exact ⟨q.1, z.1, congrArg (fun x => x.1.1) hq, congrArg (fun x => x.1.1) hz, + congrArg (fun x => x.1.2.1) hq, ne⟩ + +namespace Contact +variable (h : Contact S r v w c d) (pr : S.Proper r) (hr : Recip S r) (hk : S.k = 0) +include h + +include hr in +open scoped Classical in +theorem band_of (he : S.peer r (v, i) = some (w, j)) : + band S r v i = code S.d (some c, S.direction r (v, i)) ∧ Merge.other S r v i = j := by + obtain ⟨q, hq, ep⟩ := Option.map_eq_some_iff.mp he + have ea : (r v.1).1 q.1 = w.1 := congrArg (fun x => x.1.1) ep + have ej : q.2.2 = j := congrArg Prod.snd ep + have ec : q.1 = c := (back_eq S r hr h.right ea h.ne.symm).symm.trans + (back_eq S r hr h.right h.left h.ne.symm) + simp [band, lane, Merge.other, mate, Scheme.direction, hq, ec, ej] + +include hk in +open scoped Classical in +private theorem peer_of {b : Bool} (hi : band S r v i = code S.d (some c, b)) : + S.peer r (v, i) = some (w, Merge.other S r v i) ∧ S.direction r (v, i) = b := by + have : Subsingleton (B S.k) := by rw [hk]; exact inferInstanceAs (Subsingleton (Fin 1)) + obtain ⟨hp, hd⟩ := Prod.mk.inj ((code S.d).injective hi) + obtain ⟨q, hq, hc⟩ := Option.map_eq_some_iff.mp hp + refine ⟨?_, hd⟩ + simp only [Scheme.peer, other, mate, hq, Option.map_some, Option.getD_some, hc, h.left, h.block, + Subsingleton.elim q.2.1 w.2.2] + +include pr hr hk in +open scoped Classical in +theorem pair {b : Bool} (hi : band S r v i = code S.d (some c, b)) : + let j := Merge.other S r v i + band S r w j = code S.d (some d, !b) ∧ Merge.other S r w j = i ∧ + priority S r v i = priority S r w j ∧ S.width r (v, i) = S.width r (w, j) := by + intro j + obtain ⟨hv, hd⟩ := h.peer_of hk hi + obtain ⟨hw, he, hne⟩ := pr _ _ hv + obtain ⟨hb, hm⟩ := h.symm.band_of hr hw + have hs : S.direction r (w, j) = !b := by + rw [hd] at hne + change b ≠ S.direction r (w, j) at hne + cases b <;> simpa using hne.symm + refine ⟨hb.trans (by rw [hs]), hm, ?_, he⟩ + change (if S.direction r (v, i) then j else i) = (if S.direction r (w, + j) then Merge.other S r w j else j) + rw [hd, hs, hm] + cases b <;> rfl + +include pr hr hk in +open scoped Classical in +private theorem sums (b : Bool) (f : B S.e → Prop) [DecidablePred f] : + (∑ i with band S r v i = code S.d (some c, b) ∧ f (priority S r v i), S.width r (v, i)) = + (∑ j with band S r w j = code S.d (some d, !b) ∧ f (priority S r w j), S.width r (w, j)) := by + apply sum_bij' (fun i _ => Merge.other S r v i) (fun j _ => Merge.other S r w j) + · intro i hi + obtain ⟨hc, hf⟩ := (mem_filter.mp hi).2 + obtain ⟨ha, _, he, _⟩ := h.pair pr hr hk hc + exact mem_filter.mpr ⟨mem_univ _, ha, he ▸ hf⟩ + · intro j hj + obtain ⟨hd, hf⟩ := (mem_filter.mp hj).2 + obtain ⟨ha, _, he, _⟩ := h.symm.pair pr hr hk hd + rw [Bool.not_not] at ha + exact mem_filter.mpr ⟨mem_univ _, ha, he ▸ hf⟩ + · intro i hi; exact (h.pair pr hr hk (mem_filter.mp hi).2.1).2.1 + · intro j hj; exact (h.symm.pair pr hr hk (mem_filter.mp hj).2.1).2.1 + · intro i hi; exact (h.pair pr hr hk (mem_filter.mp hi).2.1).2.2.2 + +include pr hr hk in +open scoped Classical in +theorem agree (hi : S.peer r (v, i) = some (w, j)) : + band S r w j = code S.d (some d, !(S.direction r (v, i))) ∧ + length (S.pattern r v) v.2.2 (band S r v i) = length (S.pattern r w) w.2.2 (band S r w j) ∧ + start S r v i = start S r w j := by + obtain ⟨hc, hj⟩ := h.band_of hr hi + obtain ⟨hd, _, he, _⟩ := h.pair pr hr hk hc + rw [hj] at hd he + refine ⟨hd, ?_, ?_⟩ + · rw [hc, hd] + have eq := h.sums pr hr hk (S.direction r (v, i)) (fun _ => True) + simp only [and_true] at eq + exact eq + · have eq := h.sums pr hr hk (S.direction r (v, i)) (fun k => k < priority S r v i) + rw [←hc, ←hd] at eq + conv at eq => rhs; rw [he] + exact eq + +end Contact +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- # Reciprocal contacts and payload offsets after merging -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring Finset + +variable {F : Type} (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +/-- Every nonempty internal span crosses to a different host. -/ +def Across := ∀ v w i j, 0 < S.width r (v, i) → S.peer r (v, i) = some (w, j) → v.1 ≠ w.1 + +open scoped Classical in +/-- The value specified by `(q.1, band S r q.1 q.2)`. -/ +def span (q : S.Span) : (scheme S).Span := (q.1, band S r q.1 q.2) + +local notation "M" => scheme S +local notation "R" => rows S r + +open scoped Classical in +theorem side (q : S.Span) : (M).direction R (span S r q) = S.direction r q := by + rw [span, direction, band, lane, parse_code]; rfl + +open scoped Classical in +theorem exterior {q : S.Span} (he : S.peer r q = none) : (M).peer R (span S r q) = none := by + have h := Option.map_eq_none_iff.mp he + rw [span, peer] + simp [band, lane, h] + +variable (pr : S.Proper r) (hr : Recip S r) (hk : S.k = 0) (ne : Across S r) +include pr hr hk ne + +open scoped Classical in +theorem linked {p q : S.Span} (hp : 0 < S.width r p) (he : S.peer r p = some q) : + (M).peer R (span S r p) = some (span S r q) ∧ + (M).width R (span S r p) = (M).width R (span S r q) ∧ + start S r p.1 p.2 = start S r q.1 q.2 := by + obtain ⟨v, i⟩ := p + obtain ⟨w, j⟩ := q + obtain ⟨c, d, h⟩ := contact pr he (ne v w i j hp he) + obtain ⟨hb, hsize, hoff⟩ := h.agree pr hr hk he + have ha := (h.band_of hr he).1 + refine ⟨?_, ?_, hoff⟩ + · have hn : length (S.pattern r v) v.2.2 (band S r v i) ≠ 0 := by + have ht := inside (S.pattern r v) v.2.2 i + change start S r v i + S.width r (v, i) ≤ length (S.pattern r v) v.2.2 (band S r v i) at ht + omega + have : Subsingleton (B S.k) := by rw [hk]; exact inferInstanceAs (Subsingleton (Fin 1)) + rw [span, peer, ite_eq_right hn, ha, parse_code] + simp only [span, Option.map_some, h.left, h.block, back_eq S r hr h.left h.right h.ne, hb, + Subsingleton.elim (0 : B S.k) w.2.2] + · exact (width S r _ _).trans (hsize.trans (width S r _ _).symm) + +open scoped Classical in +theorem proper : (M).Proper R := by + rintro ⟨v, c⟩ y hy + have hp : length (S.pattern r v) v.2.2 c ≠ 0 := by + intro h + have hh := (peer S r v c).symm.trans hy + rw [ite_eq_left h] at hh; cases hh + obtain ⟨i, hi, hpos⟩ := Finset.exists_ne_zero_of_sum_ne_zero hp + have hl : band S r v i = c := (mem_filter.mp hi).2 + have hw : 0 < S.width r (v, i) := Nat.pos_of_ne_zero hpos + have hx : (v, c) = span S r (v, i) := by simp only [span, hl] + rw [hx] at hy ⊢ + cases he : S.peer r (v, i) with + | none => rw [exterior S r he] at hy; cases hy + | some q => + obtain ⟨hq, hl, _⟩ := linked S r pr hr hk ne hw he + have hb := pr _ _ he + have heq := Option.some.inj (hy.symm.trans hq) + rw [heq] + refine ⟨(linked S r pr hr hk ne (hw.trans_eq hb.2.1) hb.1).1, hl, ?_⟩ + simpa only [side] using hb.2.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- # Local pin bijections and table values after merging -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring + +variable {F : Type} {d k e : ℕ} (P : Pattern F d k e) (Q : Pattern F d k (d + 2)) + (b : B d → B d) (h : Q = pattern P b) + +open scoped Classical in +/-- The quantity computed by `⟨lane P j p.1, offset P j p.1 + p.2.val, by rw [h]; exact (index P +j p).2.isLt⟩`. -/ +def rename (j : B k) (p : P.Pin j) : Q.Pin j := + ⟨lane P j p.1, offset P j p.1 + p.2.val, by + rw [h]; exact (index P j p).2.isLt⟩ + +open scoped Classical in +theorem rename_bijective (j : B k) (hu : Function.Bijective (index P j)) : + Function.Bijective (rename P Q b h j) := by subst Q; exact hu + +open scoped Classical in +private theorem rename_table (j : B k) (t : Q.Pin j → Bool) : + Q.value j (fun q i => t ⟨q, i⟩) = + P.value j (fun q i => t (rename P Q b h j ⟨q, i⟩)) := by subst Q; rfl + +variable (S : Scheme F) (r : S.format.obj) (pr : S.Proper r) (hk : S.k = 0) +local notation "M" => scheme S +local notation "R" => rows S r + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def pins (v : S.Vtx) : S.LocalPin r v ≃ (M).LocalPin R v := + Equiv.ofBijective (rename _ _ _ (at_row S r v) v.2.2) + (rename_bijective _ _ _ (at_row S r v) v.2.2 + (bijective _ _ (fun i j _ _ hl ho => distinct S r pr v i j hl ho hk))) + +open scoped Classical in +theorem table (v : S.Vtx) (t : (M).LocalPin R v → Bool) : + (M).table R v t = S.table r v (t ∘ pins S r pr hk v) := + rename_table _ _ _ (at_row S r v) v.2.2 t + +variable [Field F] {x y : Wire} {G : Diagram F x y} + (a : S.Seating r G) + +open scoped Classical in +/-- Builds `(M).Seating R G where vertex` with the specified `vertex`, `pin`, `cover`, `sample`. -/ +def seat : (M).Seating R G where + vertex := a.vertex + pin v := (a.pin v).trans (pins S r pr hk (a.vertex v)) + cover p := a.cover (S.port r p.1.1 ((pins S r pr hk p.1.1).symm ⟨p.1.2, p.2⟩)) + sample v t := (table S r pr hk _ t).trans (a.sample v _) + vacant v hv t := (table S r pr hk _ t).trans (a.vacant v hv _) + +open scoped Classical in +/-- All offsets refer to the original source lane, including at a +destination with a different local lane enumeration. -/ +theorem seat_ends (t : G.End) : + let p := a.ends t + let q := (seat S r pr hk a).ends t + q.1 = span S r p.1 ∧ q.2.val = start S r p.1.1 p.1.2 + p.2.val := by + obtain ⟨⟨v, i⟩, rfl⟩ := G.portEquiv.surjective t + dsimp only + rw [Scheme.Seating.ends_at, Scheme.Seating.ends_at] + exact ⟨rfl, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- # Merging the bundles of a loopless board -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} {r : D.format.obj} + {P : Rounds.Board F x y D.scheme.h} (p : D.Presents r P) + (hl : ∀ e, P.diagram.source e ≠ P.diagram.target e) + +local notation "S" => D.scheme +local notation "M" => scheme D.scheme +local notation "R" => rows D.scheme (Prod.fst r) + +open scoped Classical in +private theorem ends_host (t : P.diagram.End) : + (p.pres.toSeating.ends t).1.1.1 = p.host (P.place (P.diagram.station t)).1 := by + obtain ⟨⟨v, i⟩, rfl⟩ := P.diagram.portEquiv.surjective t + rw [p.pres.toSeating.ends_at, Diagram.station_port] + exact congrArg Prod.fst (p.vertex v) + +include p hl in +open scoped Classical in +theorem across : Across (S) r.1 := by + have sep (e : P.diagram.E) : + (p.pres.toSeating.ends (.inl (.inr e))).1.1.1 ≠ + (p.pres.toSeating.ends (.inr (.inr e))).1.1.1 := by + rw [ends_host, ends_host] + exact fun he => hl e (P.one (Prod.ext (p.host.injective he) (P.edge e).1.symm)) + intro v w i j hp he + obtain ⟨t, ht⟩ := p.pres.toSeating.ends.surjective ⟨(v, i), 0, hp⟩ + have h : (p.pres.toSeating.ends t).1 = (v, i) := congrArg Sigma.fst ht + rw [← h] at he + rcases t with (q|q)|(q|q) + · rw [p.pres.input] at he; cases he + · have hw := Option.some.inj ((p.pres.internal q).1.symm.trans he) + simpa only [h, hw] using sep q + · rw [p.pres.output] at he; cases he + · have hw := Option.some.inj (((p.pres.internal q).symm p.pres.proper).1.symm.trans he) + simpa only [h, hw] using (sep q).symm + +variable (hk : D.scheme.k = 0) + +open scoped Classical in +/-- Builds `(M).Presentation R P.diagram where toSeating` with the specified `toSeating`, +`proper`, `internal`, `obtain`. -/ +def presentation : (M).Presentation R P.diagram where + toSeating := seat (S) r.1 p.pres.proper hk p.pres.toSeating + proper := proper (S) r.1 p.pres.proper p.reciprocal hk (across p hl) + internal e := by + obtain ⟨h, h'⟩ := p.pres.internal e + obtain ⟨he, _, ho⟩ := linked (S) r.1 p.pres.proper p.reciprocal hk (across p hl) + (Nat.zero_lt_of_lt (p.pres.toSeating.ends (.inl (.inr e))).2.isLt) h + have a := seat_ends (S) r.1 p.pres.proper hk p.pres.toSeating (.inl (.inr e)) + have b := seat_ends (S) r.1 p.pres.proper hk p.pres.toSeating (.inr (.inr e)) + exact ⟨by rw [a.1, b.1, he], by rw [a.2, b.2, ho, h']⟩ + input i := by + rw [(seat_ends (S) r.1 p.pres.proper hk p.pres.toSeating _).1] + exact exterior (S) r.1 (p.pres.input i) + output i := by + rw [(seat_ends (S) r.1 p.pres.proper hk p.pres.toSeating _).1] + exact exterior (S) r.1 (p.pres.output i) + +open scoped Classical in +/-- Builds `(template D).Presents (record D r) P where pres` with the specified `pres`, `host`, +`vertex`, `directed`. -/ +def present : (template D).Presents (record D r) P where + pres := presentation p hl hk + host := p.host + vertex := p.vertex + directed t := by + have he := (seat_ends (S) r.1 p.pres.proper hk p.pres.toSeating t).1 + exact (congrArg ((M).direction R) he).trans ((side (S) r.1 _).trans (p.directed t)) + live := p.live + closed := p.closed + reciprocal := p.reciprocal + edge := p.edge + core := p.core + load := p.load + +open scoped Classical in +theorem ends (t : P.diagram.End) : + let x := p.pres.toSeating.ends t + let y := (present p hl hk).pres.toSeating.ends t + y.1 = span (S) r.1 x.1 ∧ y.2.val = start (S) r.1 x.1.1 x.1.2 + x.2.val := + seat_ends (S) r.1 p.pres.proper hk p.pres.toSeating t + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- # Preparing the reciprocal channel array once per host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring Finset + +variable (F : Type) [Field F] {m d t : ℕ} (hm : m ≤ t) (hd : 2 ^ d ≤ t) +include hm hd + +private theorem check_code (k : B d) : + Cheap F 0 t (.pair (.addr m) (.addr m)) (.addr d) + (fun x => if x.1 = x.2 then k else 0) 7 := by + have hw : d ≤ t := Nat.lt_two_pow_self.le.trans hd + have ha : (Format.pair (.addr m) (.addr m)).width ≤ 2 ^ 0 * (100 + t) ^ 2 + := by simp; ring_nf; omega + have hb : (Format.pair (.addr d) (.addr d)).width ≤ 2 ^ 0 * (100 + t) ^ 2 + := by simp; ring_nf; omega + have kk := Cheap.const F ha hb (k, 0) + have h := (kk.pair (cheap_eq F hm)).comp ((cheap_select F d).widen hw) + convert h.mono (d := 7) (by decide) using 1 + funext x + simp + +/-- Computes the masks by the application `Format.vec m (.vec d (.addr d))`. -/ +abbrev Masks (m d : ℕ) := Format.vec m (.vec d (.addr d)) + +/-- Evaluates `∑ k, if x (x i j) k = i then k else 0` at the input `i j`. -/ +def reverse (x : (Neighborhood.Rows m d).obj) : (Masks m d).obj := + fun i j => ∑ k, if x (x i j) k = i then k else 0 + +theorem cheap_reverse : Cheap F m t (Neighborhood.Rows m d) (Masks m d) reverse 24 := by + have hw : d ≤ t := Nat.lt_two_pow_self.le.trans hd + have hp : (Perm m).width ≤ 2 ^ m * (100 + t) ^ 2 := + (column_width m hm).trans (by gcongr; omega) + have pos := Cheap.const F (Neighborhood.width hm hd) hp id + have get := Cheap.lookup F m t (.addr m) hm (by simpa) + have pair (j k : B d) : Cheap F m t (Neighborhood.Rows m d) (Column m d) + (fun x i => if x (x i j) k = i then k else 0) 14 := by + have col := ((Neighborhood.column F hm hd k).pair (Neighborhood.column F hm hd j)).comp get + exact ((col.pair pos).zip.comp (Cheap.map _ fun _ => check_code F hm hd k)).mono (by decide) + let D := Format.vec d (.vec d (.vec m (.addr d))) + let A := Format.vec m (.vec d (.vec d (.addr d))) + have ha : A.width ≤ 2 ^ m * (100 + t) ^ 3 := by + simp only [A, Format.width_vec, Format.width_addr] + apply Nat.mul_le_mul_left + calc + _ ≤ t * (t * t) := by gcongr + _ ≤ _ := by ring_nf; omega + have eq : D.width = A.width := by simp only [D, A, Format.width_vec]; ring + have all := Cheap.share _ (fun j => Cheap.share _ (pair j) hd) hd + have swap : Cheap F m t D A (fun x i j k => x j k i) 4 := + Cheap.project F (eq.le.trans ha) ha (fun i => (i.2.1, i.2.2.1, i.1, i.2.2.2)) (fun _ _ => rfl) + have sums : Cheap F 0 t (.vec d (Column d d)) (Column d d) (fun x j => ∑ k, x j k) 12 := by + have lift {A D : Format} {f : A.obj → D.obj} {c} (h : Cheap F d t A D f c) : + Cheap F 0 t A D f (c + 1) := by + obtain ⟨n, hn, hc⟩ := h + refine ⟨n, hn, hc.trans ?_⟩ + rw [pow_zero, one_mul, pow_succ'] + exact Nat.mul_le_mul_right _ (by omega) + exact lift (Cheap.map _ fun _ => lift (SpanPlan.cheap_sum F hw)) + exact ((all.comp swap).comp (Cheap.map _ fun _ => sums)).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- # Local relabeling after reciprocal channels have been computed -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring + +variable {F : Type} [Field F] (D : Template F) + +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "Q" => Masks m d +local notation "A" => D.format.pair Q + +private def nav (r : D.format.obj) : (Neighborhood.Rows m d).obj := D.nav r + +private def emit (x : (A).obj) : (template D).format.obj := + (fun i => ((x.1.1 i).1, fun z => (key D.scheme).serial ((x.1.1 i).2 z, x.2 i)), x.1.2) + +private theorem emit_net : Circuit F (A) (template D).format (emit D) + ((A).width + 2 * (template D).format.width) := by + let K := key D.scheme + let e : slots (word K.width) ≃ K.pins := + @Fintype.equivOfCardEq _ _ (slotsFintype _) K.finite ((card_slots _).trans (wd_word _)) + have he (x : K.obj) (i) : (Format.addr K.width).code (K.serial x) i = K.code x (e i) := by + rw [Format.serial, Equiv.trans_apply, Equiv.apply_symm_apply] + rfl + let pick (i : B m) (j : B D.scheme.h) : K.pins → (A).pins + | .inl a => .inl (.inl (i, .inr (j, a))) + | .inr a => .inr (i, a) + let read : (template D).format.pins → (A).pins + | .inl (i, .inl a) => .inl (.inl (i, .inl a)) + | .inl (i, .inr (j, a)) => pick i j (e a) + | .inr a => .inl (.inr a) + refine Circuit.project read ?_ + rintro x (⟨i, j | ⟨j, a⟩⟩ | z) + · rfl + · refine (he ((x.1.1 i).2 j, x.2 i) a).trans ?_ + change _ = (A).code x (pick i j (e a)) + cases e a <;> rfl + · rfl + +/-- The quantity computed by `8 * D.format.width + 2 * (template D).format.width + 2 * (2 ^ m * +(100 + m + 2 ^ d) ^ 24)`. -/ +def cost := 8 * D.format.width + 2 * (template D).format.width + 2 * (2 ^ m * (100 + m + + 2 ^ d) ^ 24) + +/-- Long-address comparisons are shared by all blocks. Per occurrence +only the old label and the short reciprocal array are copied. -/ +theorem record_net : Circuit F D.format (template D).format (record D) (cost D) := by + have get : Circuit F D.format (Neighborhood.Rows m d) (nav D) + (D.format.width + 2 * (Neighborhood.Rows m d).width) := + Circuit.project (fun q => .inl (q.1, .inl q.2)) (fun _ _ => rfl) + obtain ⟨n, hn, hc⟩ := cheap_reverse F (Nat.le_add_right m (2 ^ d)) (Nat.le_add_left (2 ^ d) m) + have c := ((Circuit.id F D.format).pair (get.comp hn)).comp (emit_net D) + refine c.mono ?_ + unfold cost + rw [show (A).width = D.format.width + (Q).width from Format.width_pair .., add_assoc 100] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end + +/- +# Merged exterior payloads + +Each old span is one fragment. At the sending end use the old order. +At the receiving end group by destination lane, then old lane. Both +lists name each fragment by its sending index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +open Coloring + +variable {F : Type} (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +theorem ordered {v : S.Vtx} {i j : B S.e} + (hi : S.peer r (v, i) = none) (hj : S.peer r (v, j) = none) + (hc : band S r v i = band S r v j) (ho : i < j) : + start S r v i + S.width r (v, i) ≤ start S r v j := by + apply before _ _ hc + have hi' := Option.map_eq_none_iff.mp hi + have hj' := Option.map_eq_none_iff.mp hj + simpa [order, mate, hi', hj'] using ho + +open scoped Classical in +/-- The quantity computed by `S.k + (S.d + 2 + S.e)`. -/ +abbrev dim := S.k + (S.d + 2 + S.e) + +open scoped Classical in +/-- The value specified by `(Match.rowIndex i j).symm (a, b)`. -/ +abbrev cat {i j : ℕ} (a : B i) (b : B j) : B (i + j) := (Match.rowIndex i j).symm (a, b) + +open scoped Classical in +/-- Computes the slot by the application `cat v (cat (if b then lane P v i else 0) i)`. -/ +def slot (b : Bool) (P : Pattern F S.d S.k S.e) (v : B S.k) (i : B S.e) := + cat v (cat (if b then lane P v i else 0) i) + +open scoped Classical in +/-- Computes the pos by the application `cat t.1.2.1 (slot S b (S.pattern r t.1) t.1.2.2 t.2)`. -/ +def pos (b : Bool) (t : S.Span) : B (S.h + dim S) := + cat t.1.2.1 (slot S b (S.pattern r t.1) t.1.2.2 t.2) + +open scoped Classical in +/-- The fragment of type `(SpanPlan.header w 0 (S.h + dim S)).obj`, constructed using +`(Match.rowIndex S.k (S.d + 2 + S.e) j).1`. -/ +def fragment (w : ℕ) (b : Bool) (P : Pattern F S.d S.k S.e) + (z : B S.h) (j : B (dim S)) : (SpanPlan.header w 0 (S.h + dim S)).obj := + let v := (Match.rowIndex S.k (S.d + 2 + S.e) j).1 + let i := (Match.rowIndex (S.d + 2) S.e (Match.rowIndex S.k (S.d + 2 + S.e) j).2).2 + let n := if P.peer v i = none ∧ j = slot S b P v i then P.width v i else 0 + (0, Fin.ofNat (2 ^ w) n, cat z (slot S false P v i)) + +open scoped Classical in +/-- Evaluates `(fragment S w false (S.decode l) z, fun _ => fragment S w true (S.decode l) z)` +at the input `l z`. -/ +def program (w : ℕ) : SpanProgram S 0 w (dim S) := + fun l z => (fragment S w false (S.decode l) z, fun _ => fragment S w true (S.decode l) z) + +open scoped Classical in +/-- The construction uses `Match.rowIndex S.h (dim S) j` for its intermediate `z`. -/ +def list (w : ℕ) (b : Bool) (i : B S.m) (j : B (S.h + dim S)) := + let z := Match.rowIndex S.h (dim S) j + fragment S w b (S.decode ((r i).2 z.1)) z.1 z.2 + +open scoped Classical in +theorem send (w : ℕ) : (program S w).send r = list S r w false := rfl + +open scoped Classical in +theorem no_suffix {m : ℕ} (v : B m) : Match.rowIndex m 0 v = (v, 0) := by + apply (Match.rowIndex m 0).symm.injective + rw [Equiv.symm_apply_apply] + apply Fin.ext + change v.val = 0 + 1 * v.val + omega + +open scoped Classical in +theorem take (w : ℕ) : (program S w).take r = list S r w true := by + funext i j + simp only [SpanProgram.take, SpanProgram.plan, SpanProgram.reorder, no_suffix, program, list] + +open scoped Classical in +theorem row_entry (w : ℕ) (b : Bool) (q : S.Span) : + list S r w b q.1.1 (pos S r b q) = + (0, Fin.ofNat (2 ^ w) (S.borderLen r q), pos S r false q) := by + simp only [list, fragment, pos, slot, cat, Equiv.apply_symm_apply, Scheme.pattern, and_true] + simp only [Scheme.borderLen, Scheme.peer, Scheme.pattern, Scheme.width, Option.map_eq_none_iff] + +open scoped Classical in +theorem row_cover (w : ℕ) (b : Bool) (i : B S.m) (j : B (S.h + dim S)) + (hj : 0 < (list S r w b i j).2.1.val) : + ∃ q, 0 < S.borderLen r q ∧ q.1.1 = i ∧ pos S r b q = j := by + obtain ⟨⟨z, a⟩, rfl⟩ := (Match.rowIndex S.h (dim S)).symm.surjective j + let p := S.decode ((r i).2 z) + let v := (Match.rowIndex S.k (S.d + 2 + S.e) a).1 + let n := (Match.rowIndex (S.d + 2) S.e (Match.rowIndex S.k (S.d + 2 + S.e) a).2).2 + simp only [list, Equiv.apply_symm_apply, fragment] at hj + change 0 < (Fin.ofNat (2 ^ w) (if p.peer v n = none ∧ a + = slot S b p v n then p.width v n else 0)).val at hj + split at hj + · rename_i he + refine ⟨((i, z, v), n), ?_, rfl, ?_⟩ + · have hw := lt_of_lt_of_le hj (Nat.mod_le _ _) + simp only [Scheme.borderLen, Scheme.peer, Option.map_eq_none_iff, Scheme.width] + change 0 < if p.peer v n = none then p.width v n else 0 + rwa [ite_eq_left he.1] + · exact congrArg (cat z) he.2.symm + · simp at hj + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Merge +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Mixer/Apply.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Mixer/Apply.lean new file mode 100644 index 0000000000..cb38b5a414 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Mixer/Apply.lean @@ -0,0 +1,956 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.BadBases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Mixer.Score +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Budget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.ResetLocation + +/-! +# Applying a single linear mixer in every host row + +Decode the permutation once and broadcast it. Each row then uses +a Batcher gather on its own short records. The output separates +the group index from the within-group address. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +open Coloring Packing + +variable (h a : ℕ) (ha : a ≤ h) + +open scoped Classical in +/-- The value specified by `(splitCell a ha).symm ((cellIndex _).symm b, (cellIndex _).symm z)`. -/ +def merge (b : B a) (z : B (h - a)) : Cell h := + (splitCell a ha).symm ((cellIndex _).symm b, (cellIndex _).symm z) + +open scoped Classical in +/-- The value specified by `(menu h i).symm (merge h a ha b z)`. -/ +def original (i : B h) (b : B a) (z : B (h - a)) := + (menu h i).symm (merge h a ha b z) + +variable (A : Format) (m : ℕ) + +open scoped Classical in +/-- Computes the data by the application `Format.vec m (.vec h A)`. -/ +abbrev Data := Format.vec m (.vec h A) +open scoped Classical in +/-- The quantity computed by `Format.vec m (.vec a (.vec (h - a) A))`. -/ +abbrev Groups := Format.vec m (.vec a (.vec (h - a) A)) + +open scoped Classical in +/-- Evaluates `x.2 j (cellIndex h (original h a ha x.1 b z))` at the input `j b z`. -/ +def regroup (x : (Format.pair (.addr h) (Data h A m)).obj) : (Groups h a A m).obj := + fun j b z => x.2 j (cellIndex h (original h a ha x.1 b z)) + +open scoped Classical in +private def perm (i : B h) (z : B h) := + cellIndex h ((menu h i).symm ((cellIndex h).symm z)) + +open scoped Classical in +/-- The quantity computed by `h + Install.localCost h * (2 ^ h * h)`. -/ +def permCost := h + Install.localCost h * (2 ^ h * h) + +variable {F : Type} [Field F] + +open scoped Classical in +private theorem perm_net : Circuit F (.addr h) (Coloring.Perm h) (perm h) (permCost h) := by + let A := Format.addr h + let D := Coloring.Perm h + have he : Install.Depends (D.code ∘ perm h ∘ A.code.symm) h := + fun i => ⟨Finset.univ, by simp [A], fun x y e => by + rw [funext (fun j => e j (Finset.mem_univ _))]⟩ + have hc : Circuit F A D (perm h) (A.width + Install.localCost h * D.width) := he.bnet F + simpa only [A, D, Coloring.Perm, permCost, Format.width_addr, Format.width_vec] using hc + +open scoped Classical in +/-- Computes the local row by the application `Format.pair (.vec h A) (Coloring.Perm h)`. -/ +abbrev LocalRow := Format.pair (.vec h A) (Coloring.Perm h) + +open scoped Classical in +/-- The construction uses `(Data h A m).width` for its intermediate `w`. -/ +def applyCost := + let w := (Data h A m).width + permCost h + w + (Coloring.Perm h).width + w + 2 * (Format.vec m (LocalRow h A)).width + + 2 ^ m * (2 ^ h * (100 + (h + A.width)) ^ 8) + 3 * w + +open scoped Classical in +theorem apply_mixer : + Circuit F (.pair (.addr h) (Data h A m)) (Groups h a A m) + (regroup h a ha A m) (applyCost h A m) := by + let C := Format.pair (Coloring.Perm h) (Data h A m) + let D := Format.vec m (LocalRow h A) + have broadcast : Circuit F C D (fun x j => (x.2 j, x.1)) (C.width + 2 * D.width) := + Circuit.project (fun p => p.2.elim (fun q => .inr (p.1, q)) .inl) + (by rintro x ⟨i, q|q⟩ <;> rfl) + have copy : Circuit F (Data h A m) (Groups h a A m) + (fun x j b z => x j (cellIndex h (merge h a ha b z))) + ((Data h A m).width + 2 * (Groups h a A m).width) := + Circuit.project (fun p => (p.1, cellIndex h (merge h a ha p.2.1 p.2.2.1), p.2.2.2)) + (fun _ _ => rfl) + obtain ⟨s, hs, hb⟩ := Cheap.lookup F h (h + A.width) A (by omega) (by omega) + have row := Circuit.map (A := LocalRow h A) (D := .vec h A) _ (fun _ : B m => hs) + have start := (perm_net (F := F) h).par (Circuit.id F (Data h A m)) + have all := ((start.comp broadcast).comp row).comp copy + have he : (Groups h a A m).width = (Data h A m).width := by + simp only [Groups, Data, Format.width_vec] + rw [← mul_assoc (2 ^ a), ← pow_add, Nat.add_sub_of_le ha] + have limit : 2 ^ m * s ≤ 2 ^ m * (2 ^ h * (100 + (h + A.width)) ^ 8) + := Nat.mul_le_mul_left _ (by omega) + rw [show C.width = (Coloring.Perm h).width + (Data h A m).width from Format.width_pair _ _, + he] at all + convert all.mono (n := applyCost h A m) (by dsimp only [applyCost, D]; omega) using 1 + funext x j b z + simp only [regroup, original, Function.comp_apply, perm, Prod.map_fst, Prod.map_snd, id_eq, + Equiv.symm_apply_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end + +/- # Reading a butterfly in an indexed record format -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +open Coloring Packing Mixer + +variable {a : Wire} + +private def slot : (h : ℕ) → Cell h → slots a → slots (tree h a) + | 0, _, i => i + | h + 1, z, i => + if z 0 = 0 then .inl (slot h (Fin.tail z) i) else .inr (slot h (Fin.tail z) i) + +private theorem read_bit (h : ℕ) (z : Cell h) (x : Val (tree h a)) (i : slots a) : + bits a (Mixer.read h x z) i = bits (tree h a) x (slot h z i) := by + induction h with + | zero => rfl + | succ h ih => + simp only [Mixer.read, slot] + split_ifs + · exact ih _ x.1 + · exact ih _ x.2 + +private def coords (a : Wire) (h : ℕ) : Cell h × slots a ≃ slots (tree h a) := + Equiv.ofBijective (Function.uncurry (slot h)) (by + apply (Fintype.bijective_iff_injective_and_card _).mpr + refine ⟨?_, by simp [Fintype.card_prod, wd_tree]⟩ + intro p q eq + let r z := (bits a).symm (fun j => decide (p = (z, j))) + have test := congrArg (bits (tree h a) (write h r)) eq + change bits (tree h a) _ (slot h p.1 p.2) = bits (tree h a) _ (slot h q.1 q.2) at test + simpa only [← read_bit, read_write, r, Equiv.apply_symm_apply, Prod.mk.eta, decide_true, + eq_comm (a := true), decide_eq_true_eq] using test) + +private def layout (a : Wire) (h : ℕ) : (Format.vec h (.wire a)).pins ≃ slots (tree h a) := + ((cellIndex h).symm.prodCongr (.refl _)).trans (coords a h) + +private theorem layout_read (h : ℕ) (x : Val (tree h a)) : + Assembly.view _ (layout a h) x = Mixer.read h x ∘ (cellIndex h).symm := by + apply (Format.vec h (.wire a)).code.injective + rw [view_apply, Equiv.apply_symm_apply] + funext ⟨i, j⟩ + exact (read_bit _ _ _ _).symm + +/-- The value specified by `Mixer.read h (f (write h (x ∘ cellIndex h))) ∘ (cellIndex h).symm`. -/ +def packed (h : ℕ) (f : Val (tree h a) → Val (tree h a)) (x : B h → Val a) := + Mixer.read h (f (write h (x ∘ cellIndex h))) ∘ (cellIndex h).symm + +theorem packed_map {F : Type} [Field F] {u m h : ℕ} {L : Set (Table F)} + {f : Val (tree h a) → Val (tree h a)} + (hf : DWide F u L (tree h a) (tree h a) f m) : + Map F u L (.vec h (.wire a)) (.vec h (.wire a)) (packed h f) m := by + apply Map.of_layout (layout a h) (layout a h) hf + intro x + have he : write h (Assembly.view _ (layout a h) x ∘ cellIndex h) = x := by + apply (Assembly.view _ (layout a h)).injective + rw [layout_read, read_write] + funext j + simp only [Function.comp_apply, Equiv.apply_symm_apply] + exact (layout_read h _).trans (by unfold packed; rw [he]) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end + +/- # Autocorrelations of binary load words -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +open Coloring Packing Mixer Finset + +open scoped Classical in +/-- The value specified by `lookup F A B (fun x y => if f x = y then 1 else 0)`. -/ +def graph (F : Type) [Field F] (A B : Format) (f : A.obj → B.obj) : Table F := + lookup F A B (fun x y => if f x = y then 1 else 0) + +variable {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} + +open scoped Classical in +theorem gate {A B : Format} {f : A.obj → B.obj} (hu : A.width + B.width ≤ u) + (h : graph F A B f ∈ L) : Map F u L A B f (1 + A.width + B.width) := + Kernel.lookup hu h + +open scoped Classical in +/-- The quantity computed by `2 * (h + d) + 1`. -/ +def precision (h d : ℕ) := 2 * (h + d) + 1 + +open scoped Classical in +/-- The quantity computed by `(wordCode n).symm (q.val : ZMod (2 ^ n))`. -/ +def start (d n : ℕ) (q : B d) : Val (word n) := (wordCode n).symm (q.val : ZMod (2 ^ n)) + +open scoped Classical in +/-- The quantity computed by `⟨(wordCode n x).val / 2 ^ h, (Nat.div_le_self _ _).trans_lt +(ZMod.val_lt _)⟩`. -/ +def finish (h n : ℕ) (x : Val (word n)) : B n := + ⟨(wordCode n x).val / 2 ^ h, (Nat.div_le_self _ _).trans_lt (ZMod.val_lt _)⟩ + +open scoped Classical in +/-- The correlate of type `B h → B (precision h d)`, constructed using `precision h d`. -/ +def correlate (h d : ℕ) (x : B h → B d) : B h → B (precision h d) := + let n := precision h d + finish h n ∘ packed h (correlation (wordCode n) h) (start d n ∘ x) + +open scoped Classical in +theorem correlate_eq (h d : ℕ) (x : B h → B d) (z : Cell h) : + (correlate h d x (cellIndex h z)).val = + ∑ i, (x (cellIndex h i)).val * (x (cellIndex h (i + z))).val := by + let f := fun i => (x (cellIndex h i)).val + have hb := exact_correlation h d f (fun i => (x _).isLt.le) z + unfold correlate finish packed + simp only [Function.comp_apply, Equiv.symm_apply_apply] + change (Mixer.view (wordCode (2 * (h + d) + 1)) h (correlation (wordCode (2 * (h + d) + + 1)) h (encode h (2 * (h + d) + 1) f)) z).val / 2 ^ h = _ + rw [hb] + exact Nat.mul_div_cancel_left _ (by positivity) + +open scoped Classical in +/-- The corr keys of type `Finset (Table F)`, constructed using `precision h d`. -/ +def corrKeys (F : Type) [Field F] (h d : ℕ) : Finset (Table F) := + let n := precision h d + insert (graph F (.addr d) (.wire (word n)) (start d n)) <| + insert (graph F (.wire (word n)) (.addr n) (finish h n)) (dictionary (wordCode n) F) + +open scoped Classical in +theorem size_keys (h d : ℕ) : (corrKeys F h d).card ≤ 4 := + (card_insert_le _ _).trans (Nat.add_le_add_right + ((card_insert_le _ _).trans (Nat.add_le_add_right (dictionary_size _) 1)) 1) + +open scoped Classical in +/-- The bound obtained by adding the component charges `let n := precision h d 2 ^ h * ((1 + d + +n) + (2 * h + 3) * (1 + 4 * n) + (1 + n + n))`. -/ +def corrCost (h d : ℕ) := + let n := precision h d + 2 ^ h * ((1 + d + n) + (2 * h + 3) * (1 + 4 * n) + (1 + n + n)) + +open scoped Classical in +theorem corr_map (h d : ℕ) (hu : 4 * precision h d ≤ u) (hl : (corrKeys F h d : Set _) ⊆ L) : + Map F u L (.vec h (.addr d)) (.vec h (.addr (precision h d))) (correlate h d) (corrCost h d) + := by + let n := precision h d + change 4 * n ≤ u at hu + have hn : 1 ≤ n ∧ d ≤ n := by unfold n precision; omega + have hw : (Format.wire (word n)).width = n := by simp [Format.width] + have lead : Map F u L (.addr d) (.wire (word n)) (start d n) (1 + d + n) := by + apply Kernel.mono (gate (by rw [Format.width_addr, hw]; omega) + (hl (by simp [corrKeys, n]))) + rw [Format.width_addr, hw] + have last : Map F u L (.wire (word n)) (.addr n) (finish h n) (1 + n + n) := by + apply Kernel.mono (gate (by rw [Format.width_addr]; omega) + (hl (by simp [corrKeys, n]))) + rw [Format.width_addr] + have net := correlation_net (wordCode n) h (F := F) (u := u) (by omega) (by rwa [wd_word]) + have hh : (dictionary (wordCode n) F : Set _) ⊆ L := + fun k hk => hl (mem_insert_of_mem (mem_insert_of_mem hk)) + have mid := Kernel.widen (packed_map net) le_rfl hh + rw [wd_word] at mid + have before := Map.vec (t := h) _ (fun _ => lead) + have after := Map.vec (t := h) _ (fun _ => last) + exact ((before.comp mid).comp after).mono (by unfold corrCost; exact le_of_eq (by ring)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end + +/- # Weighted autocorrelation tables for one processor -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +open Coloring Finset + +open scoped Classical in +/-- Computes the num by the application `Format.vec h (.addr d)`. -/ +abbrev Num (h d : ℕ) := Format.vec h (.addr d) +open scoped Classical in +/-- Computes the input by the application `Format.pair (Num h d) (Num k d)`. -/ +abbrev Input (h k d : ℕ) := Format.pair (Num h d) (Num k d) +open scoped Classical in +/-- Computes the both by the application `Format.pair (.addr n) (.addr d)`. -/ +abbrev Both (n d : ℕ) := Format.pair (.addr n) (.addr d) +open scoped Classical in +/-- The quantity computed by `precision h d + d`. -/ +abbrev wordLength (h d : ℕ) := precision h d + d + +open scoped Classical in +/-- The quantity computed by `⟨v.1.val * v.2.val, by rw [pow_add]; exact +Nat.mul_lt_mul_of_lt_of_lt v.1.isLt v.2.isLt⟩`. -/ +def times (n d : ℕ) (v : (Both n d).obj) : B (n + d) := + ⟨v.1.val * v.2.val, by rw [pow_add]; exact Nat.mul_lt_mul_of_lt_of_lt v.1.isLt v.2.isLt⟩ + +open scoped Classical in +/-- The value specified by `(v.1 (Match.rowIndex k h i).2, v.2 (Match.rowIndex k h i).1)`. -/ +def pairs (h k n d : ℕ) (v : ((Num h n).pair (Num k d)).obj) + (i : B (k + h)) : (Both n d).obj := + (v.1 (Match.rowIndex k h i).2, v.2 (Match.rowIndex k h i).1) + +open scoped Classical in +/-- The value specified by `times (precision h d) d (pairs h k _ _ (correlate h d x.1, x.2) i)`. -/ +def products (h k d : ℕ) (x : (Input h k d).obj) (i : B (k + h)) := + times (precision h d) d (pairs h k _ _ (correlate h d x.1, x.2) i) + +variable {F : Type} [Field F] {L : Set (Table F)} {u : ℕ} + +open scoped Classical in +/-- Computes the keys by the application `insert (graph F (Both (precision h d) d) (.addr +(wordLength h d)) (times _ _)) (corrKeys F h d)`. -/ +def keys (F : Type) [Field F] (h d : ℕ) := + insert (graph F (Both (precision h d) d) (.addr (wordLength h d)) (times _ _)) (corrKeys F h d) + +open scoped Classical in +theorem card_keys (h d : ℕ) : (keys F h d).card ≤ 5 := + (card_insert_le _ _).trans (Nat.add_le_add_right (size_keys h d) 1) + +open scoped Classical in +theorem arity_keys {h d : ℕ} {t : Table F} (ht : t ∈ keys F h d) : + wd t.1 + wd t.2.1 ≤ 4 * precision h d := by + have hw : (Format.wire (word (precision h d))).width = precision h d := by + exact (card_slots _).trans (wd_word _) + simp only [keys, corrKeys, mem_insert] at ht + rcases ht with rfl | rfl | rfl | hd + · simp only [graph, lookup, wd_word, Both, Format.width_pair, Format.width_addr, wordLength] + unfold precision + omega + · simp only [graph, lookup, wd_word, Format.width_addr, hw] + unfold precision + omega + · simp only [graph, lookup, wd_word, hw] + unfold precision + omega + · simpa only [wd_word] using Mixer.dictionary_arity _ hd + +open scoped Classical in +/-- The quantity computed by `2 ^ h * n + 2 ^ k * d + 2 * (2 ^ (k + h) * (n + d))`. -/ +def pairCost (h k n d : ℕ) := 2 ^ h * n + 2 ^ k * d + 2 * (2 ^ (k + h) * (n + d)) + +open scoped Classical in +private theorem pairs_net (h k n d : ℕ) : + Circuit F ((Num h n).pair (Num k d)) (.vec (k + h) (Both n d)) (pairs h k n d) + (pairCost h k n d) := by + let A := (Num h n).pair (Num k d) + let C := Format.vec (k + h) (Both n d) + have hp : Circuit F A C (pairs h k n d) (A.width + 2 * C.width) := + Circuit.project (fun p => Sum.elim + (fun j => .inl ((Match.rowIndex k h p.1).2, j)) + (fun j => .inr ((Match.rowIndex k h p.1).1, j)) p.2) (by rintro x ⟨i, j|j⟩ <;> rfl) + simpa only [A, C, pairCost, Num, Both, Format.width_vec, Format.width_pair, Format.width_addr] + using hp + +open scoped Classical in +/-- The bound obtained by adding the component charges `corrCost h d + 4 * (2 ^ k * d) + 4 * +pairCost h k (precision h d) d + 2 ^ (k + h) * (1 + wordLength h d + wordLength h d)`. -/ +def rowCost (h k d : ℕ) := corrCost h d + 4 * (2 ^ k * d) + 4 * pairCost h k (precision h d) d + + 2 ^ (k + h) * (1 + wordLength h d + wordLength h d) + +open scoped Classical in +theorem products_map (h k d : ℕ) (hu : 4 * precision h d ≤ u) (hl : (keys F h d : Set _) ⊆ L) : + Map F u L (Input h k d) (Num (k + h) (wordLength h d)) (products h k d) (rowCost h k d) := by + have h₃ : 3 ≤ u := by unfold precision at hu; omega + have ht : Map F u L (Both (precision h d) d) (.addr (wordLength h d)) (times _ _) + (1 + wordLength h d + wordLength h d) := by + apply Kernel.mono (gate ?_ (hl (mem_insert_self _ _))) + · simp [Both] + · simp only [Both, Format.width_pair, Format.width_addr, wordLength] + unfold precision at * + omega + have hp := Map.circuit (L := L) h₃ (pairs_net (F := F) h k (precision h d) d) + have hi := Map.circuit (L := L) h₃ (Circuit.id F (Num k d)) + have hc := corr_map h d hu (fun _ hi => hl (mem_insert_of_mem hi)) + have mult := Map.vec (t := k + h) _ (fun _ => ht) + refine (((hc.par hi).comp hp).comp mult).mono ?_ + simp only [rowCost, Num, Format.width_vec, Format.width_addr, le_refl] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end + +/- +# Accumulating coefficients before testing mixers + +Sum each column over hosts first. The quadratic-size candidate test +on the resulting single table is paid just once. Only the column +sums and the comparisons use long words. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing + +open Coloring Finset + +variable {m k d z : ℕ} (F : Type) [Field F] + +open scoped Classical in +/-- Computes the matrix by the application `Format.vec m (Num k d)`. -/ +abbrev Matrix (m k d : ℕ) := Format.vec m (Num k d) + +open scoped Classical in +/-- The indexed operation `total m d (fun j => x j i)`. -/ +def collect (x : B m → B k → B d) (i : B k) := total m d (fun j => x j i) + +open scoped Classical in +/-- The quantity computed by `2 ^ k * 2 ^ m * (3 * d + (100 + d) ^ 5)`. -/ +def collectCost (m k d : ℕ) := 2 ^ k * 2 ^ m * (3 * d + (100 + d) ^ 5) + +open scoped Classical in +theorem collect_net (m k d : ℕ) : + Circuit F (Matrix m k d) (Num k (d + m)) collect (collectCost m k d) := by + let A := Matrix m k d + let D := Matrix k m d + have hp : Circuit F A D (fun x i j => x j i) (A.width + 2 * D.width) := + Circuit.project (fun t => (t.2.1, t.1, t.2.2)) (fun _ _ => rfl) + obtain ⟨c, hc, hh⟩ := cheap_total F m d + have hs := Circuit.map (A := Num m d) (D := .addr (d + m)) (fun _ : B k => total m d) + (fun _ => hc) + refine (hp.comp hs).mono ?_ + have ho : c ≤ 2 ^ m * (100 + d) ^ 5 := by omega + simp only [A, D, Matrix, Num, Format.width_vec, Format.width_addr, collectCost] + refine (Nat.add_le_add_left (Nat.mul_le_mul_left _ ho) _).trans_eq (by ring) + +variable (p : B z → B k → Prop) + +open scoped Classical in +/-- Returns `x j` when `p i j` holds, and `0` otherwise. -/ +def mask (x : B k → B d) (i : B z) (j : B k) : B d := if p i j then x j else 0 + +open scoped Classical in +/-- The quantity computed by `2 ^ k * d + Install.localCost 1 * (2 ^ z * (2 ^ k * d))`. -/ +def maskCost (k z d : ℕ) := 2 ^ k * d + Install.localCost 1 * (2 ^ z * (2 ^ k * d)) + +open scoped Classical in +private theorem mask_net (d : ℕ) : + Circuit F (Num k d) (Matrix z k d) (mask p) (maskCost k z d) := by + let A := Num k d + let D := Matrix z k d + have hm : Install.Depends (D.code ∘ mask p ∘ A.code.symm) 1 := by + rintro ⟨i, j, t⟩ + refine ⟨{(j, t)}, by simp, fun x y he => ?_⟩ + change (Format.addr d).code (mask p (A.code.symm x) i j) t = + (Format.addr d).code (mask p (A.code.symm y) i j) t + unfold mask + split_ifs + · change A.code (A.code.symm x) (j, t) = A.code (A.code.symm y) (j, t) + simpa using he (j, t) (mem_singleton_self _) + · rfl + have h : Circuit F A D (mask p) (A.width + Install.localCost 1 * D.width) := hm.bnet F + simpa only [A, D, Num, Matrix, Format.width_vec, Format.width_addr, maskCost] using h + +open scoped Classical in +/-- The value specified by `elect ⊥ (mask p (collect x))`. -/ +def minimize (x : B m → B k → B d) := elect ⊥ (mask p (collect x)) + +open scoped Classical in +/-- The value specified by `∑ j, if p i j then ∑ v, (x v j).val else 0`. -/ +def test (x : B m → B k → B d) (i : B z) := + ∑ j, if p i j then ∑ v, (x v j).val else 0 + +open scoped Classical in +theorem minimize_spec (x : B m → B k → B d) (i : B z) : + test p x (minimize p x) ≤ test p x i := by + have he q j : (mask p (collect x) q j).val = if p q j then ∑ v, (x v j).val else 0 := by + unfold mask + split_ifs <;> rfl + have hp q : (∑ j, (mask p (collect x) q j).val) = test p x q := sum_congr rfl (fun j _ => he q j) + rw [← hp, ← hp] + exact elect_min (mask p (collect x)) i + +open scoped Classical in +/-- The bound obtained by adding the component charges `collectCost m k d + maskCost k z (d + m) ++ 2 ^ z * (2 ^ k * (100 + (d + m)) ^ 5 + (100 + (z + (d + m + k))) ^ 42)`. -/ +def testCost (m k d z : ℕ) := collectCost m k d + maskCost k z (d + m) + + 2 ^ z * (2 ^ k * (100 + (d + m)) ^ 5 + (100 + (z + (d + m + k))) ^ 42) + +open scoped Classical in +theorem minimize_net (m d : ℕ) : + Circuit F (Matrix m k d) (.addr z) (minimize p) (testCost m k d z) := + ((collect_net F m k d).comp (mask_net F p _)).comp (election F k z (d + m) ⊥) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end + +/- +# Computing the least-cost mixer + +Each row carries a nonnegative integer load at each block and an +integer weight for each depth. Zero weights disable unused depths. +The circuit returns a single common choice, breaking ties by index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing + +open Coloring Finset Packing + +variable {m h k d : ℕ} + +open scoped Classical in +/-- Embeds `Fin (h + 1) × Cell h` into `B (k + h)`. -/ +def location (hk : h < 2 ^ k) : Fin (h + 1) × Cell h ↪ B (k + h) := + ((Fin.castLEEmb hk).prodMap (cellIndex h).toEmbedding).trans (Match.rowIndex k h).symm.toEmbedding + +open scoped Classical in +/-- The condition `∃ z, location hk z = u ∧ ancestor z.1.is_le (menu h i z.2) = 0` on the +specified data. -/ +def keep (hk : h < 2 ^ k) (i : B h) (u : B (k + h)) : Prop := + ∃ z, location hk z = u ∧ ancestor z.1.is_le (menu h i z.2) = 0 + +open scoped Classical in +/-- Computes the rows by the application `Format.vec m (Input h k d)`. -/ +abbrev Rows (m h k d : ℕ) := Format.vec m (Input h k d) + +open scoped Classical in +/-- The indexed operation `minimize (keep hk) (fun j => products h k d (x j))`. -/ +def choose (hk : h < 2 ^ k) (x : (Rows m h k d).obj) := + minimize (keep hk) (fun j => products h k d (x j)) + +open scoped Classical in +/-- Evaluates `∑ j, ((products h k d (x j) (location hk (i, z))).val : ℝ)` at the input `i z`. -/ +def coefficients (hk : h < 2 ^ k) (x : (Rows m h k d).obj) : Mixer.Coeff h := + fun i z => ∑ j, ((products h k d (x j) (location hk (i, z))).val : ℝ) + +open scoped Classical in +theorem product_eq (hk : h < 2 ^ k) (x : (Input h k d).obj) (i : Fin (h + 1)) (z : Cell h) : + (products h k d x (location hk (i, z))).val = (x.2 (Fin.castLE hk i)).val * + ∑ j, (x.1 (cellIndex h j)).val * (x.1 (cellIndex h (j + z))).val := by + have hl : Match.rowIndex k h (location hk (i, z)) = (Fin.castLE hk i, cellIndex h z) := + (Match.rowIndex k h).apply_symm_apply _ + simp only [products, pairs, hl, times, correlate_eq, mul_comm] + +open scoped Classical in +theorem test_eq (hk : h < 2 ^ k) (x : (Rows m h k d).obj) (i : B h) : + (test (keep hk) (fun j => products h k d (x j)) i : ℝ) = + Mixer.eval (menu h i) (coefficients hk x) := by + unfold test + rw [← sum_subset (subset_univ (univ.map (location hk))), sum_map, Fintype.sum_prod_type] + · have eq (u : Fin (h + 1)) z : + keep hk i (location hk (u, z)) ↔ ancestor u.is_le (menu h i z) = 0 := by + simp [keep] + push_cast + simp only [eq] + rfl + · intro v _ hv + apply ite_eq_right + rintro ⟨z, he, _⟩ + exact hv (mem_map.mpr ⟨z, mem_univ _, he⟩) + +open scoped Classical in +theorem choose_le (hk : h < 2 ^ k) (x : (Rows m h k d).obj) (i : B h) : + Mixer.eval (menu h (choose hk x)) (coefficients hk x) ≤ + Mixer.eval (menu h i) (coefficients hk x) := by + rw [← test_eq, ← test_eq, Nat.cast_le] + exact minimize_spec _ _ _ + +open scoped Classical in +/-- The quantity computed by `2 ^ m * rowCost h k d + 4 * testCost m (k + h) (wordLength h d) +h`. -/ +def cost (m h k d : ℕ) := + 2 ^ m * rowCost h k d + 4 * testCost m (k + h) (wordLength h d) h + +open scoped Classical in +/-- The input-scale work is linear in the number of hosts; the exhaustive +search on the block addresses is done only on the aggregated table. -/ +theorem compute {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} + (hk : h < 2 ^ k) (hu : 4 * precision h d ≤ u) (hl : (keys F h d : Set _) ⊆ L) : + Map F u L (Rows m h k d) (.addr h) (choose hk) (cost m h k d) := by + have h₃ : 3 ≤ u := by unfold precision at hu; omega + have r := Map.vec (t := m) _ (fun _ => products_map h k d hu hl) + exact r.comp (Map.circuit h₃ (minimize_net F (keep hk) m (wordLength h d))) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end + +/- +# Recovering the reset estimate from integer records + +All loads may carry a common positive scale. Each position or +contact contributes one record, and unused records carry zero weight. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing + +open Coloring Finset Packing + +variable {m h k d : ℕ} {V A : Type} [Fintype V] [Fintype A] + (base : V → ℕ) (q : A → ℕ) (l : V → Cell h → ℝ) (y : A → Cell h → ℝ) (g : ℝ) + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `if base v ≤ i.val then 6 * resetWeight (i.val +- base v) else 0`. -/ +def weight (i : Fin (h + 1)) : V ⊕ A → ℝ + | .inl v => if base v ≤ i.val then 6 * resetWeight (i.val - base v) else 0 + | .inr c => if i.val = q c then 4 * g ^ 2 else 0 + +open scoped Classical in +/-- Computes the signal by the application `Sum.elim l y`. -/ +def signal := Sum.elim l y + +open scoped Classical in +private theorem contribution (i : Fin (h + 1)) (z : Cell h) : + Mixer.coefficients base q l y g i z = + ∑ t, weight base q g i t * Mixer.conv (signal l y t) (signal l y t) z := by + rw [Fintype.sum_sum_type] + simp only [Mixer.coefficients, Pi.add_apply, Pi.smul_apply, Finset.sum_apply, nsmul_eq_mul, + Pi.mul_apply, Pi.ofNat_apply, + Nat.cast_ofNat, smul_eq_mul, mul_sum, Mixer.atDepth, weight, signal, Sum.elim_inl, Sum.elim_inr] + congr 1 + · apply sum_congr rfl + intro v _ + by_cases hi : base v ≤ i.val + · rw [ite_eq_left hi, sum_eq_single (i.val - base v)] + · rw [ite_eq_left (by omega)] + ring + · intro j _ hj + rw [ite_eq_right (by omega), mul_zero, mul_zero] + · have := i.isLt + simp only [mem_range] + omega + · rw [ite_eq_right hi, zero_mul] + exact sum_eq_zero (fun j _ => by rw [ite_eq_right (by omega), mul_zero, mul_zero]) + · apply sum_congr rfl + intro c _ + split_ifs <;> ring + +open scoped Classical in +/-- The data for the encodes construction, including `loads`, `weights`, `vacant`. -/ +structure Encodes (hk : h < 2 ^ k) (x : (Rows m h k d).obj) + (pos : V ⊕ A ↪ B m) (scale : ℝ) : Prop where + loads : ∀ t z, signal l y t z = scale * ((x (pos t)).1 (cellIndex h z)).val + weights : ∀ (i : Fin (h + 1)) t, + weight base q g i t = ((x (pos t)).2 (Fin.castLE hk i)).val + vacant : ∀ (i : Fin (h + 1)) j, j ∉ Set.range pos → ((x j).2 (Fin.castLE hk i)).val = 0 ∨ + ∀ z, ((x j).1 (cellIndex h z)).val = 0 + +variable {base q l y g} {hk : h < 2 ^ k} {x : (Rows m h k d).obj} + {pos : V ⊕ A ↪ B m} {scale : ℝ} + +open scoped Classical in +theorem Encodes.coefficients_eq (e : Encodes base q l y g hk x pos scale) : + Mixer.coefficients base q l y g = scale ^ 2 • coefficients hk x := by + funext i z + rw [contribution] + simp only [coefficients, Pi.smul_apply, smul_eq_mul] + rw [← sum_subset (subset_univ (univ.map pos)), sum_map, mul_sum] + · refine sum_congr rfl (fun t _ => ?_) + rw [product_eq, e.weights] + simp only [Mixer.conv, e.loads, Nat.cast_mul, Nat.cast_sum, mul_sum] + exact sum_congr rfl (fun _ _ => by ring) + · intro j _ hj + rw [product_eq] + rcases e.vacant i j (by simpa using hj) with h | h <;> simp [h] + +open scoped Classical in +theorem Encodes.optimal (e : Encodes base q l y g hk x pos scale) + (hq : ∀ c, q c ≤ h) (t : ℕ) (i : B h) : + score base q l y g (menu h (choose hk x)).toEquiv t ≤ + score base q l y g (menu h i).toEquiv t := by + apply sub_nonpos.mp + rw [Mixer.score_diff _ _ _ _ _ _ _ hq, e.coefficients_eq, + map_smul, smul_eq_mul, LinearMap.sub_apply] + exact mul_nonpos_of_nonneg_of_nonpos (sq_nonneg scale) (sub_nonpos.mpr (choose_le hk x i)) + +open scoped Classical in +/-- Computing the winner from short control words gives the same bound +as averaging over nonzero field multipliers. -/ +theorem Encodes.bad (e : Encodes base q l y g hk x pos scale) + (E : V → Finset V) (delay : V → V → ℕ) + (ends : (Σ c, Cell (q c)) → Bool → Σ v, Cell (base v)) (t : ℕ) + (drop : ∀ v u, u ∈ E v → base u ≤ base v + 8 * delay v u) + (budget : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (delay v u) else 0) ≤ 1 / 2) + (hl : ∀ v z, 0 ≤ l v z ∧ l v z ≤ 1 / (2 : ℝ) ^ t) + (hy : ∀ c z, 0 ≤ y c z ∧ y c z ≤ 1 / (2 : ℝ) ^ t) + (hb : ∀ v, ∑ z, l v z ≤ (2 : ℝ) ^ (base v)) + (hq : ∀ c, q c ≤ h) (hg : 0 < g) : + badLoad E delay base q ends l y g (menu h (choose hk x)).toEquiv ≤ + 144 * resetWeight t / (2 : ℝ) ^ t * (∑ v, ∑ z, l v z) + + 4 * g ^ 2 / (2 : ℝ) ^ t * (∑ c, ∑ z, y c z) := by + obtain ⟨i, hi⟩ := exists_score base q l y g hl hy hb hq + exact (bad_le_score E delay base q ends l y g _ drop budget hl hb hg).trans + ((e.optimal hq t i).trans hi) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end + +/- +# From short records to the reset election + +A host row carries one header per possible contact and one for its +own load. A header contains a live bit, a contact bit and a depth. +One local record per block suffices to recover all of the loads at +that position. Global host names do not enter the two lookup tables. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing + +open Coloring Finset Packing + +open scoped Classical in +/-- Computes the header by the application `Format.pair .bit (.pair .bit (.addr k))`. -/ +abbrev Header (k : ℕ) := Format.pair .bit (.pair .bit (.addr k)) +open scoped Classical in +/-- Computes the local by the application `Format.pair (.vec e (Header k)) (Num h s)`. -/ +abbrev Local (e h k s : ℕ) := Format.pair (.vec e (Header k)) (Num h s) +open scoped Classical in +/-- Computes the records by the application `Format.vec m (Local e h k s)`. -/ +abbrev Records (m e h k s : ℕ) := Format.vec m (Local e h k s) + +variable {m e h k s d : ℕ} + +open scoped Classical in +/-- The multiplier of type `B d`, constructed using `r.2.2.val`. -/ +def multiplier (g d : ℕ) (r : (Header k).obj) (j : B k) : B d := + let i := r.2.2.val + Fin.ofNat _ (if r.1 then + if r.2.1 then if j.val = i then 4 * g ^ 2 else 0 + else if i ≤ j.val then 6 * 2 ^ ((j.val - i + 7) / 8) else 0 + else 0) + +open scoped Classical in +/-- The value specified by `(x (Match.rowIndex m e t).1).1 (Match.rowIndex m e t).2`. -/ +def header (x : (Records m e h k s).obj) (t : B (m + e)) := + (x (Match.rowIndex m e t).1).1 (Match.rowIndex m e t).2 + +open scoped Classical in +/-- Computes the digit by the application `get ((x (Match.rowIndex m e t).1).2 z) +(Match.rowIndex m e t).2`. -/ +def digit (get : B s → B e → B d) (x : (Records m e h k s).obj) (t : B (m + e)) (z : B h) := + get ((x (Match.rowIndex m e t).1).2 z) (Match.rowIndex m e t).2 + +open scoped Classical in +/-- Evaluates `(digit get x t, multiplier g d (header x t))` at the input `t`. -/ +def rows (g : ℕ) (get : B s → B e → B d) (x : (Records m e h k s).obj) : (Rows (m + e) h k d).obj := + fun t => (digit get x t, multiplier g d (header x t)) + +variable {V A : Type} [Fintype V] [Fintype A] (base : V → ℕ) (q : A → ℕ) + (l : V → Cell h → ℝ) (y : A → Cell h → ℝ) (g : ℕ) (hk : h < 2 ^ k) + (get : B s → B e → B d) (x : (Records m e h k s).obj) (pos : V ⊕ A ↪ B (m + e)) (scale : ℝ) + +omit [Fintype V] [Fintype A] in +open scoped Classical in +theorem encodes (hb : ∀ v, base v ≤ h) (hq : ∀ c, q c ≤ h) + (hg : 4 * g ^ 2 < 2 ^ d) (hw : 6 * 2 ^ h < 2 ^ d) + (heads : ∀ v, header x (pos (.inl v)) = (true, false, ⟨base v, (hb v).trans_lt hk⟩)) + (edges : ∀ c, header x (pos (.inr c)) = (true, true, ⟨q c, (hq c).trans_lt hk⟩)) + (idle : ∀ j, j ∉ Set.range pos → (header x j).1 = false ∨ + ∀ z, (digit get x j (cellIndex h z)).val = 0) + (loads : ∀ t z, signal l y t z = scale * (digit get x (pos t) (cellIndex h z)).val) : + Encodes base q l y g hk (rows g get x) pos scale := by + refine ⟨loads, ?_, ?_⟩ + · intro i t + rcases t with v | c + · have ht : 6 * 2 ^ ((i.val - base v + 7) / 8) < 2 ^ d := + (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide) + (show (i.val - base v + 7) / 8 ≤ h by have := i.isLt; omega))).trans_lt hw + by_cases hi : base v ≤ i.val <;> simp [rows, multiplier, heads, weight, hi, resetWeight, + Nat.mod_eq_of_lt ht] + · by_cases hi : i.val = q c <;> simp [rows, multiplier, edges, weight, hi, Nat.mod_eq_of_lt hg] + · intro i j hj + rcases idle j hj with h | h + · left; simp [rows, multiplier, h] + · exact .inr h + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end + +/- # The load- and weight-extraction network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing + +open Coloring Finset + +variable {m e h k s d : ℕ} (g : ℕ) (get : B s → B e → B d) + +open scoped Classical in +/-- Computes the temp by the application `Format.pair (Matrix e k d) (Matrix h e d)`. -/ +abbrev Temp (e h k d : ℕ) := Format.pair (Matrix e k d) (Matrix h e d) + +open scoped Classical in +private def transpose (x : (Format.vec m (Temp e h k d)).obj) : (Rows (m + e) h k d).obj := + fun i => let z := Match.rowIndex m e i + (fun u => (x z.1).2 u z.2, (x z.1).1 z.2) + +open scoped Classical in +/-- Computes the row keys by the application `insert (graph F (.addr s) (Num e d) get) (insert +(graph F (Header k) (Num k d) (multiplier g d)) (keys F h d))`. -/ +def rowKeys (F : Type) [Field F] (h k : ℕ) := + insert (graph F (.addr s) (Num e d) get) + (insert (graph F (Header k) (Num k d) (multiplier g d)) (keys F h d)) + +open scoped Classical in +theorem rowKeys_size (F : Type) [Field F] (h k : ℕ) : (rowKeys g get F h k).card ≤ 7 := + (card_insert_le _ _).trans (Nat.add_le_add_right + ((card_insert_le _ _).trans (Nat.add_le_add_right (card_keys h d) 1)) 1) + +open scoped Classical in +/-- The maximum of the quantities in `(4 * precision h d) (max (s + 2 ^ e * d) (2 + k + 2 ^ k * +d))`. -/ +def arity (e h k s d : ℕ) := max (4 * precision h d) (max (s + 2 ^ e * d) (2 + k + 2 ^ k * d)) + +open scoped Classical in +/-- The bound obtained by adding the component charges `2 ^ m * ((2 ^ e + 2 ^ h) * (1 + arity e +h k s d)) + 4 * ((Format.vec m (Temp e h k d)).width + 2 * (Rows (m + e) h k d).width)`. -/ +def extractionCost (m e h k s d : ℕ) := + 2 ^ m * ((2 ^ e + 2 ^ h) * (1 + arity e h k s d)) + + 4 * ((Format.vec m (Temp e h k d)).width + 2 * (Rows (m + e) h k d).width) + +variable {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} + +open scoped Classical in +theorem rowKeys_arity {T : Table F} (ht : T ∈ rowKeys g get F h k) : + wd T.1 + wd T.2.1 ≤ arity e h k s d := by + unfold arity + simp only [rowKeys, mem_insert] at ht + rcases ht with rfl | rfl | ht + · simp only [graph, lookup, wd_word, Num, Format.width_vec, Format.width_addr] + omega + · simp only [graph, lookup, wd_word, Num, Format.width_vec, Format.width_addr, Header, + Format.width_pair] + rw [Format.width_bit] + omega + · exact (arity_keys ht).trans (le_max_left _ _) + +open scoped Classical in +private theorem transpose_net : + Circuit F (.vec m (Temp e h k d)) (Rows (m + e) h k d) transpose + ((Format.vec m (Temp e h k d)).width + 2 * (Rows (m + e) h k d).width) := by + refine Circuit.project (fun p => + ((Match.rowIndex m e p.1).1, p.2.elim + (fun t => .inr (t.1, (Match.rowIndex m e p.1).2, t.2)) + (fun t => .inl ((Match.rowIndex m e p.1).2, t)))) ?_ + rintro x ⟨i, t|t⟩ <;> rfl + +open scoped Classical in +theorem extract (ha : arity e h k s d ≤ u) (hl : (rowKeys g get F h k : Set _) ⊆ L) : + Map F u L (Records m e h k s) (Rows (m + e) h k d) (rows g get) (extractionCost m e h k s d) + := by + let a := arity e h k s d + have hu : 3 ≤ u := by unfold arity precision at ha; omega + have ht (A D : Format) (f : A.obj → D.obj) (hf : graph F A D f ∈ rowKeys g get F h k) : + Map F u L A D f (1 + a) := by + have hb : A.width + D.width ≤ a := by + simpa only [graph, lookup, wd_word] using rowKeys_arity g get hf + exact (gate (hb.trans ha) (hl hf)).mono (by omega) + have hd := Map.vec (t := h) _ + (fun _ => ht (.addr s) (Num e d) get (by simp [rowKeys])) + have hw := Map.vec (t := e) _ + (fun _ => ht (Header k) (Num k d) (multiplier g d) (by simp [rowKeys])) + have ht' := Map.vec (t := m) _ (fun _ => hw.par hd) + exact (ht'.comp (Map.circuit hu transpose_net)).mono (by unfold extractionCost; rw [add_mul]) + +open scoped Classical in +/-- Only the scalar decoder and width parameters enter the seven labels. -/ +theorem elect_records (hk : h < 2 ^ k) (ha : arity e h k s d ≤ u) + (hl : (rowKeys g get F h k : Set _) ⊆ L) : + Map F u L (Records m e h k s) (.addr h) (choose hk ∘ rows g get) + (extractionCost m e h k s d + cost (m + e) h k d) := + (extract g get ha hl).comp (compute hk ((le_max_left _ _).trans ha) + (fun _ ht => hl (mem_insert_of_mem (mem_insert_of_mem ht)))) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end + +/- +# Constructing the reset schedule from finite control words + +The linear permutation and all base depths are determined from +loads, contact totals and the fixed parameters. No minimization over +completed diagrams is required. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +open Coloring Packing Finset + +variable {V A U : Type} [Fintype V] [Fintype A] [Fintype U] {h : ℕ} + +open scoped Classical in +/-- The quantity computed by `baseDepths E delay a (h - k) (fun v => ∑ x, l v x)`. -/ +def depths (E : V → Finset V) (delay : V → V → ℕ) (a k : ℕ) (l : V → Cell h → ℝ) := + baseDepths E delay a (h - k) (fun v => ∑ x, l v x) + +open scoped Classical in +theorem depths_spec {E : V → Finset V} {delay : V → V → ℕ} {a t : ℕ} + (budget : ∀ w, ∑ v, (if w ∈ E v then 1 / (2 : ℝ) ^ (delay v w) else 0) ≤ 1 / 2) + (gap : a + t ≤ h) (l : V → Cell h → ℝ) (hl : ∀ v z, 0 ≤ l v z ∧ l v z ≤ 1 / (2 : ℝ) ^ t) : + let base := depths E delay a t l + (∀ v, a ≤ base v ∧ base v ≤ h - t ∧ (∑ x, l v x) ≤ (2 : ℝ) ^ (base v)) ∧ + (∀ v u, u ∈ E v → base u ≤ base v + 8 * delay v u) ∧ + (∑ v, (2 : ℝ) ^ (base v)) ≤ 2 * Fintype.card V * (2 : ℝ) ^ a + 4 * (∑ v, ∑ x, l v x) := by + apply baseDepths_spec E delay budget a (h - t) (by omega) + intro v + refine ⟨sum_nonneg (fun x _ => (hl v x).1), ?_⟩ + calc + _ ≤ ∑ _x : Cell h, 1 / (2 : ℝ) ^ t := sum_le_sum (fun x _ => (hl v x).2) + _ = _ := by + simp only [sum_const, card_univ, card_cell, nsmul_eq_mul, Nat.cast_pow, Nat.cast_ofNat, + mul_one_div, div_eq_iff (by positivity : (2 : ℝ) ^ t ≠ 0), ← pow_add, + Nat.sub_add_cancel (by omega : t ≤ h)] + +open scoped Classical in +/-- Any sufficiently large dyadic parameter with the given error margin +works. Both data fields are explicit. The remaining fields certify them. -/ +def schedule (T : Demands V A U h) (E : V → Finset V) (delay : V → V → ℕ) + (a t : ℕ) (l : V → Cell h → ℝ) (u g ε : ℝ) + {m k d : ℕ} (hk : h < 2 ^ k) (x : (Rows m h k d).obj) + {pos : V ⊕ A ↪ B m} {scale : ℝ} + (correct : Encodes (depths E delay a t l) (contactDepth (depths E delay a t l) T.ends) + l (T.amounts u) g hk x pos scale) + (budget : ∀ w, ∑ v, (if w ∈ E v then 1 / (2 : ℝ) ^ (delay v w) else 0) ≤ 1 / 2) + (gap : a + t ≤ h) (hl : ∀ v z, 0 ≤ l v z ∧ l v z ≤ 1 / (2 : ℝ) ^ t) + (inc : ∀ v z, T.incident u v z ≤ l v z) (hu : 0 < u) (hg : 0 < g) + (small : 144 * resetWeight t / (2 : ℝ) ^ t + 4 * g ^ 2 / (2 : ℝ) ^ t ≤ ε) : + Schedule T E delay a t l u g ε := by + let base := depths E delay a t l + have props := depths_spec budget gap l hl + refine ⟨base, menu h (choose hk x), fun v => (props.1 v).1, fun v => (props.1 v).2.1, + fun v => (props.1 v).2.2, props.2.1, props.2.2, ?_, hl, inc, gap, hu, hg⟩ + have hy c z : 0 ≤ T.amounts u c z ∧ T.amounts u c z ≤ 1 / (2 : ℝ) ^ t := + ⟨push_nonneg _ _ (fun _ => hu.le) _, + ((T.amount_le u hu.le c false z).trans (inc _ z)).trans (hl _ z).2⟩ + have hq := T.contact_le base (fun v => ((props.1 v).2.1).trans (Nat.sub_le _ _)) + refine (correct.bad E delay (contactEnd base T.ends) t props.2.1 budget hl hy + (fun v => (props.1 v).2.2) hq hg).trans ?_ + have mass : 0 ≤ ∑ v, ∑ z, l v z := sum_nonneg (fun v _ => sum_nonneg fun z _ => (hl v z).1) + have hs : (∑ c, ∑ z, T.amounts u c z) ≤ ∑ v, ∑ z, l v z := by + refine le_trans ?_ (sum_le_sum fun v _ => sum_le_sum fun z _ => inc v z) + unfold Demands.amounts Demands.incident + rw [← Fintype.sum_prod_type (push T.edge _), ← Fintype.sum_prod_type (push _ _), + sum_push, sum_push] + simp only [sum_const, card_univ, Fintype.card_prod, Fintype.card_bool, nsmul_eq_mul] + gcongr + omega + refine le_trans ?_ (mul_le_mul_of_nonneg_right small mass) + rw [add_mul] + exact add_le_add_right (mul_le_mul_of_nonneg_left hs (by positivity)) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Mixer/Choice.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Mixer/Choice.lean new file mode 100644 index 0000000000..6dd8941d6c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Mixer/Choice.lean @@ -0,0 +1,705 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.ResetLocation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Mixer.Apply + +/-! +# Reading contact loads from local patterns + +The neighbor list may repeat the host itself. Choose one column per +oriented core contact, using the occupied column whenever there are +demands. All other columns contribute zero to the mixer score. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Finset Coloring Packing + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun s => (P.outgoing s).1 = true ∧ +(P.outgoing s).2.1 = j`. -/ +def Pattern.uses {F : Type} {d k e : ℕ} (P : Pattern F d k e) (j : B d) : + Finset (B e) := univ.filter fun s => (P.outgoing s).1 = true ∧ (P.outgoing s).2.1 = j + +namespace Template.Encodes + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} + {D : Template F} {G : HostNet F L D.scheme.h u} {r : D.format.obj} (p : D.Encodes r G) + (hu : 0 < u) + +open scoped Classical in +/-- The contact col of type `B D.scheme.d`, constructed using `p.post.index c.val.1 c.val.2`. -/ +def contactCol (c : CoreContact G.C) : B D.scheme.d := + let j := p.post.index c.val.1 c.val.2 + if D.nav r (p.post.host c.val.1) j = p.post.host c.val.2 then j + else ((p.core _ _).mp c.property).choose + +open scoped Classical in +theorem nav_contact (c : CoreContact G.C) : + D.nav r (p.post.host c.val.1) (p.contactCol c) = p.post.host c.val.2 := by + unfold contactCol + dsimp only + split_ifs with he + · exact he + · exact ((p.core _ _).mp c.property).choose_spec.1 + +open scoped Classical in +/-- The value specified by `(p.post.host c.val.1, p.contactCol c)`. -/ +def contactLoc (c : CoreContact G.C) := (p.post.host c.val.1, p.contactCol c) + +open scoped Classical in +theorem contact_inj : Function.Injective p.contactLoc := by + intro c z he + obtain ⟨hs, ht⟩ := Prod.mk.inj he + have hp := p.nav_contact c + rw [hs, ht, p.nav_contact] at hp + exact Subtype.ext (Prod.ext (p.post.host.injective hs) (p.post.host.injective hp.symm)) + +include hu in +open scoped Classical in +theorem col_unit (i : G.E) : p.contactCol ((coreDemands G.ix G.edge).contact i) = + p.post.index (G.src i) (G.dst i) := ite_eq_left (p.post.target hu i) + +open scoped Classical in +/-- The value specified by `(D.scheme.decode ((r.1 (p.post.host v)).2 (cellIndex _ b))).uses j`. -/ +def usedCol (v : G.V) (b : Cell D.scheme.h) (j : B D.scheme.d) := + (D.scheme.decode ((r.1 (p.post.host v)).2 (cellIndex _ b))).uses j + +include hu in +open scoped Classical in +theorem used_iff (v : G.V) (b : Cell D.scheme.h) (j : B D.scheme.d) (s : B D.scheme.e) : + s ∈ p.usedCol v b j ↔ ∃ i, G.src i = v ∧ G.ix i = b ∧ p.post.stub i false = s ∧ + p.contactCol ((coreDemands G.ix G.edge).contact i) = j := by + unfold usedCol Pattern.uses + rw [mem_filter, ← p.block] + simp only [mem_univ, true_and] + change (p.post.localStub v b s).1 = true ∧ (p.post.localStub v b s).2.1 = j ↔ _ + rw [p.post.active hu] + constructor + · rintro ⟨⟨i, rfl, rfl, rfl⟩, hh⟩ + rw [p.post.local_slot] at hh + exact ⟨i, rfl, rfl, rfl, (p.col_unit hu i).trans hh⟩ + · rintro ⟨i, rfl, rfl, rfl, hc⟩ + exact ⟨⟨i, rfl, rfl, rfl⟩, (congrArg Prod.fst (p.post.local_slot i)).trans + ((p.col_unit hu i).symm.trans hc)⟩ + +include hu in +open scoped Classical in +theorem unused (v : G.V) (b : Cell D.scheme.h) (j : B D.scheme.d) + (idle : (p.post.host v, j) ∉ Set.range p.contactLoc) : p.usedCol v b j = ∅ := by + apply eq_empty_of_forall_notMem + intro s hs + obtain ⟨i, hv, _, _, hj⟩ := (p.used_iff hu _ _ _ _).mp hs + exact idle ⟨(coreDemands G.ix G.edge).contact i, Prod.ext (congrArg p.post.host hv) hj⟩ + +include hu in +open scoped Classical in +theorem contact_load (c : CoreContact G.C) (b : Cell D.scheme.h) (w : ℝ) : + (coreDemands G.ix G.edge).amounts w c b = (p.usedCol c.val.1 b (p.contactCol c)).card * w := by + let J := coreDemands G.ix G.edge + let A := univ.filter fun i => J.edge i = (c, b) + have hi (i : G.E) (he : i ∈ A) : G.src i = c.val.1 ∧ G.ix i = b := by + obtain ⟨hc, hb⟩ := Prod.mk.inj (mem_filter.mp he).2 + exact ⟨congrArg (fun t => t.val.1) hc, hb⟩ + have hs : A.card = (p.usedCol c.val.1 b (p.contactCol c)).card := by + apply card_bij (fun i _ => p.post.stub i false) + · intro i he + apply (p.used_iff hu _ _ _ _).mpr + exact ⟨i, (hi i he).1, (hi i he).2, rfl, congrArg p.contactCol (Prod.mk.inj (mem_filter.mp + he).2).1⟩ + · intro i h₁ j h₂ he + apply p.post.distinct hu + simp only [Scheme.Posting.span, Scheme.spanAt, Scheme.side, Bool.cond_false, + (hi i h₁).1, (hi i h₁).2, (hi j h₂).1, (hi j h₂).2, he] + · intro s hs + obtain ⟨i, hv, hb, he, hc⟩ := (p.used_iff hu _ _ _ _).mp hs + refine ⟨i, mem_filter.mpr ⟨mem_univ _, Prod.ext ?_ hb⟩, he⟩ + exact p.contact_inj (Prod.ext (congrArg p.post.host hv) hc) + unfold Demands.amounts push + rw [← hs, ← nsmul_eq_mul, ← sum_const] + unfold A J + rw [sum_filter] + exact sum_congr rfl (fun i _ => by split_ifs <;> rfl) + +end Template.Encodes +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Position and contact rows for the reset + +Flatten a host and a short column index. Reserve one column for +the load of the position and one per neighboring host for outgoing +demands. All duplicate and unused contact columns have zero load. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing Finset + +variable {F : Type} (D : Template F) + +open scoped Classical in +/-- The quantity computed by `D.scheme.d + 1`. -/ +abbrev widthCols := D.scheme.d + 1 +open scoped Classical in +/-- The quantity computed by `D.scheme.ℓ + D.count`. -/ +abbrev profileBits := D.scheme.ℓ + D.count +open scoped Classical in +/-- Computes the profile shape by the application `Mixing.Records D.scheme.m D.widthCols +D.scheme.h k D.profileBits`. -/ +abbrev profileShape (k : ℕ) := Mixing.Records D.scheme.m D.widthCols D.scheme.h k D.profileBits + +open scoped Classical in +/-- The indexed operation `((halves D.scheme.d).symm i).elim (fun j => (on && decide (j = 0), +false, a)) (fun j => (on, true, max a (near j)))`. -/ +def heads {k : ℕ} (on : Bool) (a : B k) (near : B D.scheme.d → B k) + (i : B D.widthCols) : (Mixing.Header k).obj := + ((halves D.scheme.d).symm i).elim (fun j => (on && decide (j = 0), false, a)) + (fun j => (on, true, max a (near j))) + +open scoped Classical in +/-- The profile of type `(D.profileShape k).obj` for the given inputs. -/ +def profile {k : ℕ} (r : D.format.obj) (base : B D.scheme.m → B k) : (D.profileShape k).obj := + fun v => (D.heads (D.live r v) (base v) (base ∘ D.nav r v), + fun i => (Match.rowIndex D.scheme.ℓ D.count).symm ((r.1 v).2 i, D.counter r v i)) + +open scoped Classical in +/-- The get load of type `B d`, constructed using `Match.rowIndex D.scheme.ℓ D.count x`. -/ +def getLoad (u Z d : ℕ) (x : B D.profileBits) (i : B D.widthCols) : B d := + let p := Match.rowIndex D.scheme.ℓ D.count x + Fin.ofNat _ <| ((halves D.scheme.d).symm i).elim + (fun _ => ⌊D.load p.2 * Z⌋₊) + (fun j => ((D.scheme.decode p.1).uses j).card * u * Z) + +open scoped Classical in +/-- The value specified by `(Match.rowIndex D.scheme.m D.widthCols).symm (v, halves D.scheme.d +j)`. -/ +def col (v : B D.scheme.m) (j : B D.scheme.d ⊕ B D.scheme.d) := + (Match.rowIndex D.scheme.m D.widthCols).symm (v, halves D.scheme.d j) + +open scoped Classical in +theorem header_col {k : ℕ} (r : D.format.obj) (base : B D.scheme.m → B k) v j : + Mixing.header (D.profile r base) (D.col v j) = + j.elim (fun i => (D.live r v && decide (i = 0), false, base v)) + (fun i => (D.live r v, true, max (base v) (base (D.nav r v i)))) := by + simp [Mixing.header, profile, col, heads] + +open scoped Classical in +theorem digit_col {k : ℕ} (r : D.format.obj) (base : B D.scheme.m → B k) u Z d v j b : + (Mixing.digit (D.getLoad u Z d) (D.profile r base) (D.col v j) b).val = + (j.elim (fun _ => ⌊D.load (D.counter r v b) * Z⌋₊) + (fun i => ((D.scheme.decode ((r.1 v).2 b)).uses i).card * u * Z)) % 2 ^ d := by + simp [Mixing.digit, profile, col, getLoad] + +namespace Encodes + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u k : ℕ} + {D : Template F} {G : HostNet F L D.scheme.h u} {r : D.format.obj} (p : D.Encodes r G) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def rowId : G.V ⊕ CoreContact G.C ↪ B (D.scheme.m + D.widthCols) where + toFun := Sum.elim (fun v => D.col (p.post.host v) (.inl 0)) + (fun c => D.col (p.contactLoc c).1 (.inr (p.contactLoc c).2)) + inj' := by + rintro (v|c) (w|e) he <;> + simp only [Sum.elim_inl, Sum.elim_inr, col, Equiv.symm_apply_eq, Equiv.apply_symm_apply, + Prod.mk.injEq, (halves D.scheme.d).injective.eq_iff, reduceCtorEq, and_false] at he + · exact congrArg Sum.inl (p.post.host.injective he.1) + · exact congrArg Sum.inr (p.contact_inj (Prod.ext he.1 (Sum.inr.inj he.2))) + +open scoped Classical in +/-- The value specified by `(b (p.post.host v)).val`. -/ +def depth (b : B D.scheme.m → B k) (v : G.V) := (b (p.post.host v)).val + +open scoped Classical in +theorem header_node (b : B D.scheme.m → B k) (v : G.V) : + Mixing.header (D.profile r b) (p.rowId (.inl v)) = (true, false, b (p.post.host v)) := by + change Mixing.header _ (D.col (p.post.host v) (.inl 0)) = _ + simp [D.header_col, (p.live _).mpr ⟨v, rfl⟩] + +open scoped Classical in +theorem header_link (b : B D.scheme.m → B k) (c : CoreContact G.C) : + Mixing.header (D.profile r b) (p.rowId (.inr c)) = + (true, true, max (b (p.post.host c.val.1)) (b (p.post.host c.val.2))) := by + change Mixing.header _ (D.col (p.post.host c.val.1) (.inr (p.contactCol c))) = _ + simp [D.header_col, (p.live _).mpr ⟨c.val.1, rfl⟩, p.nav_contact] + +open scoped Classical in +theorem idle_col (hu : 0 < u) (b : B D.scheme.m → B k) (Z d : ℕ) (i : B (D.scheme.m + D.widthCols)) + (hi : i ∉ Set.range p.rowId) : + (Mixing.header (D.profile r b) i).1 = false ∨ + ∀ z, (Mixing.digit (D.getLoad u Z d) (D.profile r b) i (cellIndex _ z)).val = 0 := by + obtain ⟨⟨v, j⟩, rfl⟩ := (Match.rowIndex _ _).symm.surjective i + obtain ⟨q, rfl⟩ := (halves _).surjective j + change D.col v q ∉ Set.range p.rowId at hi + change (Mixing.header _ (D.col v q)).1 = false ∨ _ + rw [D.header_col] + by_cases hl : D.live r v = true + swap + · left + cases q <;> simp [Bool.eq_false_iff.mpr hl] + obtain ⟨w, rfl⟩ := (p.live _).mp hl + cases q with + | inl j => + have hn : j ≠ 0 := by rintro rfl; exact hi ⟨.inl w, rfl⟩ + left; simp [hn] + | inr j => + right + intro z + have hn : (p.post.host w, j) ∉ Set.range p.contactLoc := by + rintro ⟨c, hc⟩ + exact hi ⟨.inr c, congrArg (fun t : B D.scheme.m × B D.scheme.d => D.col t.1 (.inr t.2)) hc⟩ + change (Mixing.digit _ _ (D.col _ (.inr j)) _).val = _ + rw [D.digit_col] + change ((p.usedCol w z j).card * u * Z) % 2 ^ d = 0 + simp [p.unused hu _ _ _ hn] + +end Encodes +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Correctness of load extraction from a posting -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +open Coloring Packing Finset + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u k d Z : ℕ} + {D : Template F} {G : HostNet F L D.scheme.h u} {r : D.format.obj} (p : D.Encodes r G) + (hu : 0 < u) (b : B D.scheme.m → B k) + +omit [Field F] in +include hu in +open scoped Classical in +theorem amounts_le (c : CoreContact G.C) (z : Cell D.scheme.h) : + (coreDemands G.ix G.edge).amounts u c z ≤ G.load c.val.1 z := by + refine ((coreDemands G.ix G.edge).amount_le u (by positivity) c false z).trans ?_ + unfold Demands.incident + rw [← degree_push] + exact (le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load _ _) + +open scoped Classical in +theorem digit_self (v : G.V) (z : Cell D.scheme.h) + (bound : ∃ n : B d, G.load v z * Z = n.val) : + (Mixing.digit (D.getLoad u Z d) (D.profile r b) (p.rowId (.inl v)) (cellIndex _ z)).val = + G.load v z * Z := by + obtain ⟨n, hn⟩ := bound + change ((Mixing.digit _ _ (D.col _ (.inl 0)) _).val : ℝ) = _ + rw [D.digit_col, Sum.elim_inl, ← p.block, p.load, hn, Nat.floor_natCast, Nat.mod_eq_of_lt n.isLt] + +include hu in +open scoped Classical in +theorem digit_link (c : CoreContact G.C) (z : Cell D.scheme.h) + (bound : ∃ n : B d, G.load c.val.1 z * Z = n.val) : + (Mixing.digit (D.getLoad u Z d) (D.profile r b) (p.rowId (.inr c)) (cellIndex _ z)).val = + (coreDemands G.ix G.edge).amounts u c z * Z := by + obtain ⟨n, hn⟩ := bound + let j := (p.usedCol c.val.1 z (p.contactCol c)).card + have hc : (coreDemands G.ix G.edge).amounts u c z = j * (u : ℝ) := p.contact_load hu c z u + have hj : j * u * Z < 2 ^ d := by + have h' := mul_le_mul_of_nonneg_right (amounts_le hu c z) (Nat.cast_nonneg (α := ℝ) Z) + rw [hc, hn] at h' + have : j * u * Z ≤ n.val := by exact_mod_cast h' + exact this.trans_lt n.isLt + change ((Mixing.digit _ _ (D.col _ (.inr (p.contactCol c))) _).val : ℝ) = _ + rw [D.digit_col, Sum.elim_inr, hc] + change ((j * u * Z % 2 ^ d : ℕ) : ℝ) = _ + simp only [Nat.mod_eq_of_lt hj, Nat.cast_mul] + +include hu in +open scoped Classical in +theorem profiled (hk : D.scheme.h < 2 ^ k) (depths : ∀ v, p.depth b v ≤ D.scheme.h) + (g : ℕ) (hg : 4 * g ^ 2 < 2 ^ d) (hw : 6 * 2 ^ D.scheme.h < 2 ^ d) (hZ : 0 < Z) + (bound : ∀ v z, ∃ n : B d, G.load v z * Z = n.val) (W : ℝ) (hW : 0 < W) : + let E := coreDemands G.ix G.edge + Mixing.Encodes (p.depth b) (contactDepth (p.depth b) E.ends) (fun v z => G.load v z / W) + (E.amounts (u / W)) g hk (Mixing.rows g (D.getLoad u Z d) (D.profile r b)) p.rowId (1 / (Z * + W)) := by + intro E + have hq c : contactDepth (p.depth b) E.ends c ≤ D.scheme.h := max_le (depths _) (depths _) + apply Mixing.encodes _ _ _ _ _ _ _ _ _ _ depths hq hg hw + · intro v + exact p.header_node b v + · intro c + exact p.header_link b c + · exact p.idle_col hu b Z d + · intro i z + have ht : (Z : ℝ) ≠ 0 := by positivity + cases i with + | inl v => + rw [p.digit_self b v z (bound v z)] + change G.load v z / W = _ + field_simp + | inr c => + rw [p.digit_link hu b c z (bound c.val.1 z)] + change E.amounts (u / W) c z = _ + unfold Demands.amounts + rw [push_div] + dsimp only [E] + field_simp + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +end + +/- +# Computing base depths from the navigation masks + +A port may repeat its own host address. Take the maximum of all +reported lower bounds. Missing tethers are harmless when their +delay exceeds the entire range of possible base depths. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing +open Coloring Packing Finset + +variable {m d k : ℕ} + +open scoped Classical in +/-- The update used in the `Mixing` construction. -/ +def update (Δ D : ℕ) (marks : (Group.Flags d).obj) (start : ℕ) (neighbor : B d → ℕ) := + max start (univ.sup fun j => if (marks j).2 then neighbor j - 32 * Nat.clog 2 (2 * Δ) + else if (marks j).1 then neighbor j - 32 * Nat.clog 2 (2 * D) else 0) + +open scoped Classical in +/-- In the case `0`, this construction gives `start`. -/ +def wave (Δ D : ℕ) (nav : B m → B d → B m) (flags : B m → (Group.Flags d).obj) + (start : B m → B k) : ℕ → B m → B k + | 0 => start + | n + 1 => fun v => Fin.ofNat _ (update Δ D (flags v) (start v).val + (fun j => (wave Δ D nav flags start n (nav v j)).val)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Mixing + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +open Coloring Packing Finset + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u k : ℕ} + {A : Template F} {G : HostNet F L A.scheme.h u} {r : A.format.obj} (p : A.Encodes r G) + {a Δ D : ℕ} + +open scoped Classical in +private theorem update_eq (hle : Δ ≤ D) (late : A.full = false → A.scheme.h - a + ≤ 32 * Nat.clog 2 (2 * D)) + (v : G.V) (l : ℕ) (lo : a ≤ l) (f : B A.scheme.m → ℕ) (high : ∀ w, f (p.post.host w) + ≤ A.scheme.h) : + Mixing.update Δ D (A.flags r (p.post.host v)) l (f ∘ A.nav r (p.post.host v)) = + max l ((G.N v).sup fun z => f (p.post.host z) - 8 * resetDelay G.C Δ D v z) := by + let M := A.flags r (p.post.host v) + let N := A.nav r (p.post.host v) + let cost j := if (M j).2 then f (N j) - 32 * Nat.clog 2 (2 * Δ) + else if (M j).1 then f (N j) - 32 * Nat.clog 2 (2 * D) else 0 + let due z := f (p.post.host z) - 8 * resetDelay G.C Δ D v z + change max l (univ.sup cost) = max l ((G.N v).sup due) + have edge i z (hz : N i = p.post.host z) (hi : (M i).1 = true) : z ∈ G.N v := by + have he := (p.edge v z).mpr ⟨i, hz, hi⟩ + unfold Template.adj at he + split_ifs at he + · exact he + · exact G.sub _ he + have core i z (hz : N i = p.post.host z) (hi : (M i).2 = true) : z ∈ G.C v := + (p.core v z).mpr ⟨i, hz, hi⟩ + have low := Nat.clog_mono_right 2 (Nat.mul_le_mul_left 2 hle) + apply le_antisymm + · refine max_le_max_left l (Finset.sup_le fun i _ => ?_) + obtain ⟨z, hz⟩ := p.closed v i + have eq : N i = p.post.host z := hz.symm + unfold cost + rw [eq] + split_ifs with hc he + · have hh := core i z eq hc + apply le_trans _ (le_sup (f := due) (G.sub _ hh)) + simp only [due, resetDelay, ite_eq_left hh] + omega + · apply le_trans _ (le_sup (f := due) (edge i z eq he)) + unfold due resetDelay + split_ifs <;> omega + · exact Nat.zero_le _ + refine max_le (le_max_left _ _) (Finset.sup_le fun z hz => ?_) + by_cases hc : z ∈ G.C v + · obtain ⟨i, hi, hm⟩ := (p.core v z).mp hc + refine le_trans ?_ ((le_sup (f := cost) (mem_univ i)).trans (le_max_right _ _)) + change N i = _ at hi + change (M i).2 = true at hm + simp only [due, resetDelay, ite_eq_left hc, cost, hm, ite_true, hi] + omega + by_cases full : A.full = true + · obtain ⟨i, hi, hm⟩ := (p.edge v z).mp (by simpa [Template.adj, full] using hz) + refine le_trans ?_ ((le_sup (f := cost) (mem_univ i)).trans (le_max_right _ _)) + change N i = _ at hi + change (M i).1 = true at hm + simp only [due, resetDelay, ite_eq_right hc, cost, hm, ite_true, hi] + split_ifs <;> omega + · apply le_max_of_le_left + have ht := late (Bool.eq_false_iff.mpr full) + have := high z + simp only [due, resetDelay, ite_eq_right hc] + omega + +open scoped Classical in +theorem wave_eq (hle : Δ ≤ D) (late : A.full = false → A.scheme.h - a ≤ 32 * Nat.clog 2 (2 * D)) + (hk : A.scheme.h < 2 ^ k) (l : G.V → ℕ) (s : B A.scheme.m → B k) + (bounds : ∀ v, a ≤ l v ∧ l v ≤ A.scheme.h) (init : ∀ v, (s (p.post.host v)).val = l v) + (n : ℕ) (v : G.V) : + (Mixing.wave Δ D (A.nav r) (A.flags r) s n (p.post.host v)).val = + iterateDepth G.N (resetDelay G.C Δ D) l n v := by + let iter := iterateDepth G.N (resetDelay G.C Δ D) l + have bound n v : iter n v ≤ A.scheme.h := + depth_bounded _ _ _ (fun _ => A.scheme.h) (fun v => (bounds v).2) + (fun _ _ _ => Nat.le_add_right _ _) n v + induction n generalizing v with + | zero => exact init v + | succ n ih => + let f j := (Mixing.wave Δ D (A.nav r) (A.flags r) s n j).val + have hm := p.update_eq hle late v (l v) (bounds v).1 f (fun w => (ih w).trans_le (bound n w)) + change Mixing.update Δ D _ _ (f ∘ _) % 2 ^ k = _ + rw [init, hm] + simp only [f, ih] + exact Nat.mod_eq_of_lt ((bound (n + 1) v).trans_lt hk) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +end + +/- +# Exact summaries of a posted network + +The counter and the pattern of a single occurrence determine its +scaled load and its unit counts by outgoing contact. The initial +base depth is read from the sum of these short load words. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template + +open Coloring Packing Finset + +variable {F : Type} (A : Template F) + +open scoped Classical in +/-- The quantity computed by `A.scheme.e + 1`. -/ +abbrev CounterBits := A.scheme.e + 1 +open scoped Classical in +/-- The quantity computed by `A.CounterBits + A.scheme.h`. -/ +abbrev CountBits := A.CounterBits + A.scheme.h +open scoped Classical in +/-- The value specified by `Format.pair (.addr A.scheme.ℓ) (.addr A.count)`. -/ +abbrev MixSource := Format.pair (.addr A.scheme.ℓ) (.addr A.count) +open scoped Classical in +/-- Computes the summand by the application `Format.pair (.addr d) (Mixing.Num A.scheme.d +A.CounterBits)`. -/ +abbrev Summand (d : ℕ) := Format.pair (.addr d) (Mixing.Num A.scheme.d A.CounterBits) +open scoped Classical in +/-- Computes the statistics by the application `Format.pair (.addr k) (Mixing.Num A.scheme.d +A.CountBits)`. -/ +abbrev Statistics (k : ℕ) := Format.pair (.addr k) (Mixing.Num A.scheme.d A.CountBits) + +open scoped Classical in +/-- The value specified by `((r.1 v).2 i, A.counter r v i)`. -/ +def source (r : A.format.obj) (v : B A.scheme.m) (i : B A.scheme.h) : A.MixSource.obj := + ((r.1 v).2 i, A.counter r v i) + +open scoped Classical in +/-- The summand of type `(A.Summand d).obj` for the given inputs. -/ +def summand (Z d : ℕ) (t : A.MixSource.obj) : (A.Summand d).obj := + (Fin.ofNat _ ⌊A.load t.2 * Z⌋₊, fun j => ⟨((A.scheme.decode t.1).uses j).card, by + refine (card_le_univ _).trans_lt ?_ + rw [Fintype.card_fin, CounterBits, pow_succ] + have : 0 < (2 : ℕ) ^ A.scheme.e := by positivity + omega⟩) + +open scoped Classical in +/-- The quantity computed by `Fin.ofNat _ (requested a (t.val / ((Z : ℝ) * W)))`. -/ +def request (a Z k : ℕ) (W : ℝ) {d : ℕ} (t : B d) : B k := + Fin.ofNat _ (requested a (t.val / ((Z : ℝ) * W))) + +open scoped Classical in +/-- The indexed operation `(request a Z k W (total A.scheme.h d (fun i => (A.summand Z d (x +i)).1)), Mixing.collect fun i => (A.summand Z d (x i)).2)`. -/ +def summary (a Z k d : ℕ) (W : ℝ) (x : B A.scheme.h → A.MixSource.obj) : (A.Statistics k).obj := + (request a Z k W (total A.scheme.h d (fun i => (A.summand Z d (x i)).1)), + Mixing.collect fun i => (A.summand Z d (x i)).2) + +open scoped Classical in +/-- The value specified by `(A.summary 0 0 0 0 0 (A.source r v)).2 j`. -/ +def unitCount (r : A.format.obj) (v : B A.scheme.m) (j : B A.scheme.d) : B A.CountBits := + (A.summary 0 0 0 0 0 (A.source r v)).2 j + +open scoped Classical in +/-- The value specified by `(A.summary a Z k d W (A.source r v)).1`. -/ +def startDepth (a Z k d : ℕ) (W : ℝ) (r : A.format.obj) (v : B A.scheme.m) := + (A.summary a Z k d W (A.source r v)).1 + +open scoped Classical in +/-- The quantity computed by `Mixing.wave Δ D (A.nav r) (A.flags r) (A.startDepth a Z k d W r) +(A.scheme.h - t - a)`. -/ +def baseDepth (a t Δ D Z k d : ℕ) (W : ℝ) (r : A.format.obj) := + Mixing.wave Δ D (A.nav r) (A.flags r) (A.startDepth a Z k d W r) (A.scheme.h - t - a) + +namespace Encodes +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u k d Z : ℕ} + {A : Template F} {G : HostNet F L A.scheme.h u} {r : A.format.obj} (p : A.Encodes r G) + +open scoped Classical in +theorem unit_count (v : G.V) (j : B A.scheme.d) : + (A.unitCount r (p.post.host v) j).val = ∑ b, (p.usedCol v b j).card := by + change (∑ b, ((A.scheme.decode ((r.1 (p.post.host v)).2 b)).uses j).card) = _ + rw [← (cellIndex _).sum_comp] + rfl + +open scoped Classical in +theorem amount_total (hu : 0 < u) (c : CoreContact G.C) (w : ℝ) : + (∑ z, (coreDemands G.ix G.edge).amounts w c z) = + (A.unitCount r (p.post.host c.val.1) (p.contactCol c)).val * w := by + rw [p.unit_count, Nat.cast_sum, sum_mul] + exact sum_congr rfl (fun z _ => p.contact_load hu c z w) + +open scoped Classical in +theorem requested_eq (a : ℕ) (hk : A.scheme.h < 2 ^ k) (hZ : 0 < Z) (W : ℝ) (hW : 0 < W) + (bound : ∀ v z, ∃ n : B d, G.load v z * Z = n.val) + (req : ∀ v, requested a (∑ z, G.load v z / W) ≤ A.scheme.h) (v : G.V) : + (A.startDepth a Z k d W r (p.post.host v)).val = requested a (∑ z, G.load v z / W) := by + let s b := (A.summand Z d (A.source r (p.post.host v) b)).1 + have eq z : ((s (cellIndex _ z)).val : ℝ) = G.load v z * Z := by + obtain ⟨n, hn⟩ := bound v z + change ((⌊A.load (A.counter r _ (cellIndex _ z)) * Z⌋₊ % 2 ^ d : ℕ) : ℝ) = _ + rw [← p.block, p.load, hn, Nat.floor_natCast, Nat.mod_eq_of_lt n.isLt] + have he : (total _ d s).val / ((Z : ℝ) * W) = ∑ z, G.load v z / W := by + change (↑(∑ i, (s i).val) : ℝ) / _ = _ + rw [Nat.cast_sum, ← (cellIndex _).sum_comp, sum_div] + apply sum_congr rfl + intro z _ + rw [eq] + field_simp + change requested a ((total _ d s).val / ((Z : ℝ) * W)) % 2 ^ k = _ + rw [he, Nat.mod_eq_of_lt ((req _).trans_lt hk)] + +open scoped Classical in +theorem depths_eq {a t Δ D : ℕ} (hΔ : 0 < Δ) (hle : Δ ≤ D) + (late : A.full = false → A.scheme.h - a ≤ 32 * Nat.clog 2 (2 * D)) + (hk : A.scheme.h < 2 ^ k) (gap : a + t ≤ A.scheme.h) (hZ : 0 < Z) (W : ℝ) (hW : 0 < W) + (bound : ∀ v z, ∃ n : B d, G.load v z * Z = n.val) + (caps : ∀ v z, G.load v z / W ≤ 1 / (2 : ℝ) ^ t) + (hc : ∀ v, (G.C v).card ≤ Δ) (hd : ∀ v, (G.N v).card ≤ D) : + p.depth (A.baseDepth a t Δ D Z k d W r) = + Mixing.depths G.N (resetDelay G.C Δ D) a t (fun v z => G.load v z / W) := by + let l := fun v z => G.load v z / W + have hb := (Mixing.depths_spec (delay := resetDelay G.C Δ D) + (edge_weight_sum G.N G.C Δ D 4 hΔ (hΔ.trans_le hle) G.ns G.cs hd hc (by decide)) + gap l (fun v z => ⟨div_nonneg (G.load_nonneg v z) hW.le, caps v z⟩)).1 + have up v : requested a (∑ z, l v z) ≤ A.scheme.h := + ((requested_le _ _ _).mpr ⟨(hb v).1, (hb v).2.2⟩).trans ((hb v).2.1.trans (Nat.sub_le _ _)) + funext v + exact p.wave_eq hle late hk _ _ (fun v => ⟨le_max_left _ _, up v⟩) + (p.requested_eq a hk hZ W hW bound up) _ _ + +end Encodes +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Selecting a valid reset schedule from a template -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template + +open Packing Coloring Finset + +variable {F : Type} (A : Template F) + +open scoped Classical in +/-- The value specified by `Mixing.choose hk (Mixing.rows g (A.getLoad u Z d) (A.profile r +(A.baseDepth a t Δ D Z k d W r)))`. -/ +def mixerChoice (a t Δ D u g Z k d : ℕ) (hk : A.scheme.h < 2 ^ k) (W : ℝ) (r : A.format.obj) := + Mixing.choose hk (Mixing.rows g (A.getLoad u Z d) (A.profile r (A.baseDepth a t Δ D Z k d W r))) + +namespace Encodes + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} + {A : Template F} {G : HostNet F L A.scheme.h u} {r : A.format.obj} (p : A.Encodes r G) + +open scoped Classical in +/-- Number-format and graph bounds required by the reset controller. -/ +structure Fits (a t Δ D g Z k d : ℕ) (W ε : ℝ) : Prop where + corePos : 0 < Δ + full : Δ ≤ D + late : A.full = false → A.scheme.h - a ≤ 32 * Nat.clog 2 (2 * D) + gap : a + t ≤ A.scheme.h + depth : A.scheme.h < 2 ^ k + integer : ∀ v z, ∃ n : B d, G.load v z * Z = n.val + denominator : 0 < Z + width : 0 < u + margin : 0 < g + widthLimit : 4 * g ^ 2 < 2 ^ d + weightLimit : 6 * 2 ^ A.scheme.h < 2 ^ d + capacity : 0 < W + bound : ∀ v z, G.load v z / W ≤ 1 / (2 : ℝ) ^ t + cdeg : ∀ v, (G.C v).card ≤ Δ + ndeg : ∀ v, (G.N v).card ≤ D + small : 144 * resetWeight t / (2 : ℝ) ^ t + 4 * (g : ℝ) ^ 2 / (2 : ℝ) ^ t ≤ ε + +variable {a t Δ D g Z k d : ℕ} {W ε : ℝ} + (ok : Fits (G := G) a t Δ D g Z k d W ε) + +open scoped Classical in +/-- The reset schedule of type `Schedule (coreDemands G.ix G.edge) G.N (resetDelay G.C Δ D) a t +(fun v z => G.load v z / W) ((u : ℝ) / W) g ε`, constructed using `A.baseDepth a t Δ D Z k d +W r`. -/ +def resetSchedule : Schedule (coreDemands G.ix G.edge) G.N (resetDelay G.C Δ D) a t + (fun v z => G.load v z / W) ((u : ℝ) / W) g ε := by + let b := A.baseDepth a t Δ D Z k d W r + let l := fun v z => G.load v z / W + let delay := resetDelay G.C Δ D + have budget := edge_weight_sum G.N G.C Δ D 4 ok.corePos (ok.corePos.trans_le ok.full) + G.ns G.cs ok.ndeg ok.cdeg (by decide) + have hl v z : 0 ≤ l v z ∧ l v z ≤ 1 / (2 : ℝ) ^ t := + ⟨div_nonneg (G.load_nonneg v z) ok.capacity.le, ok.bound v z⟩ + have hb := (Mixing.depths_spec (delay := delay) budget ok.gap l hl).1 + have eq := p.depths_eq ok.corePos ok.full ok.late ok.depth ok.gap ok.denominator W ok.capacity + ok.integer ok.bound ok.cdeg ok.ndeg + have depth v : p.depth b v ≤ A.scheme.h := + (congrFun eq v).trans_le ((hb v).2.1.trans (Nat.sub_le _ _)) + have enc := p.profiled ok.width b ok.depth depth g ok.widthLimit ok.weightLimit + ok.denominator ok.integer W ok.capacity + rw [show p.depth b = _ from eq] at enc + refine Mixing.schedule _ G.N delay a t l _ _ ε ok.depth _ enc budget ok.gap hl + ?_ (div_pos (Nat.cast_pos.mpr ok.width) ok.capacity) (Nat.cast_pos.mpr ok.margin) ok.small + intro v z + unfold Demands.incident + rw [push_div, ← degree_push] + exact div_le_div_of_nonneg_right + ((le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load v z)) ok.capacity.le + +open scoped Classical in +theorem reset_mixer : (p.resetSchedule ok).π = menu _ (A.mixerChoice a t Δ D u g Z k d ok.depth W + r) := + rfl + +open scoped Classical in +theorem reset_depth (v : G.V) : + (p.resetSchedule ok).base v = (A.baseDepth a t Δ D Z k d W r (p.post.host v)).val := + congrFun (p.depths_eq ok.corePos ok.full ok.late ok.depth ok.gap ok.denominator W ok.capacity + ok.integer ok.bound ok.cdeg ok.ndeg).symm v + +open scoped Classical in +theorem reset_capacity (c : CoreContact G.C) : + (p.resetSchedule ok).capacity c = + (A.unitCount r (p.post.host c.val.1) (p.contactCol c)).val * (u / W) / + (2 : ℝ) ^ (contactDepth (p.resetSchedule ok).base unitEnds c) + 1 / g := by + unfold Schedule.capacity mean + rw [p.amount_total ok.width] + rfl + +end Encodes +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Neighborhood.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Neighborhood.lean new file mode 100644 index 0000000000..c4531bd4f9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Neighborhood.lean @@ -0,0 +1,1139 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Restore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal +public import Mathlib.Algebra.BigOperators.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute + +/-! +# The exterior payload bank of a stage + +Only the occupied prefix of each assigned slot stores data. +All other positions are pinned to zero. The physical width +depends on the total length allowance, up to a factor for the +number of dyadic levels. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring Transcript + +namespace Fmt + +open scoped Classical in +/-- Indexes the port by the coordinates of `Σ s : Slot (2 ^ m) V k, Fin (capacity s)`. -/ +abbrev Port (m V k : ℕ) := Σ s : Slot (2 ^ m) V k, Fin (capacity s) + +open scoped Classical in +/-- The indexing data represented by `⟨Port m V k → Bool, Port m V k, Equiv.refl _⟩`. -/ +abbrev payload (m V k : ℕ) : Format := ⟨Port m V k → Bool, Port m V k, Equiv.refl _⟩ + +open scoped Classical in +theorem width_payload (m V k : ℕ) : (payload m V k).width ≤ (k + 1) * (2 * V) := by + simpa only [Format.width, payload, Fintype.card_sigma, Fintype.card_fin] using + sum_capacity (2 ^ m) V k + +end Fmt + +variable {m V k : ℕ} + +open scoped Classical in +/-- An empty host takes one unit, so the usual dyadic capacity +bounds apply without an exception at zero. -/ +structure Payload (m V k : ℕ) where + /-- The length of the indexed record carried by `Payload`, with type `B m → ℕ`. -/ + length : B m → ℕ + total : ∑ i, max 1 (length i) ≤ V + longest : ∀ i, length i ≤ 2 ^ k + +namespace Payload +variable (p : Payload m V k) + +open scoped Classical in +/-- Indexes the bit by the coordinates of `Σ i, Fin (p.length i)`. -/ +abbrev Bit := Σ i, Fin (p.length i) + +open scoped Classical in +/-- The seat of type `Selector (B m) (Slot (2 ^ m) V k)` for the given inputs. -/ +def seat : Selector (B m) (Slot (2 ^ m) V k) := + Selector.packed (fun i => max 1 (p.length i)) (fun _ + => lt_of_lt_of_le zero_lt_one (le_max_left 1 _)) (by simp) + p.total (fun i => max_le (Nat.two_pow_pos k) (p.longest i)) + +open scoped Classical in +theorem fits (i : B m) : p.length i ≤ capacity (p.seat.write i) := + (le_max_right 1 _).trans (Selector.packed_size (fun t => max 1 (p.length t)) _ _ _ _ i) + +open scoped Classical in +/-- Number each channel's bits in their original order. -/ +def wire : p.Bit ↪ Fmt.Port m V k := + Function.Embedding.sigmaMap ⟨p.seat.write, p.seat.injective⟩ (fun i => Fin.castLEEmb (p.fits i)) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def store (f : p.Bit → Bool) : (Fmt.payload m V k).obj := + Function.extend p.wire f (fun _ => false) + +open scoped Classical in +@[simp] theorem read_store (f : p.Bit → Bool) (i : p.Bit) : p.store f (p.wire i) = f i := + p.wire.injective.extend_apply _ _ _ + +open scoped Classical in +theorem padding (f : p.Bit → Bool) (i : Fmt.Port m V k) (hi : i ∉ Set.range p.wire) : + p.store f i = false := Function.extend_apply' _ _ _ hi + +open scoped Classical in +theorem store_unique (f : p.Bit → Bool) (x : (Fmt.payload m V k).obj) + (hr : ∀ i, x (p.wire i) = f i) (hz : ∀ i ∉ Set.range p.wire, x i = false) : + x = p.store f := by + funext i + by_cases hi : i ∈ Set.range p.wire + · obtain ⟨j, rfl⟩ := hi + rw [hr, read_store] + · rw [hz _ hi, padding _ _ _ hi] + +open scoped Classical in +theorem store_injective : Function.Injective p.store := by + intro x y he + funext i + simpa using congrFun he (p.wire i) + +end Payload +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Ordered bundles on a common host + +Patterns use short neighbor indices at every occurrence. The decoding +table is independent of the global host names and the block number. +Port order inside each span is the same at its two ends. Width zero +permits unused seats, including a scalar with no arguments. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +open scoped Classical in +/-- The data for the pattern construction, including `width`, `direction`, `peer`, `value`. -/ +structure Pattern (F : Type) (d k e : ℕ) where + /-- The width parameter carried by `Pattern`, with type `B k → B e → ℕ`. -/ + width : B k → B e → ℕ + /-- The `Pattern` component of type `B k → B e → Bool`. -/ + direction : B k → B e → Bool + /-- The `Pattern` component of type `B k → B e → Option (B d × B k × B e)`. -/ + peer : B k → B e → Option (B d × B k × B e) + /-- The evaluation map carried by `Pattern`, with type `(j : B k) → (∀ s : B e, Fin (width j + s) → Bool) → F`. -/ + value : (j : B k) → (∀ s : B e, Fin (width j s) → Bool) → F + +open scoped Classical in +/-- The data for the scheme construction, including `m`, `d`, `h`, `k`, `e`. -/ +structure Scheme (F : Type) where + /-- The `Scheme` field of type `ℕ`. -/ + m : ℕ + /-- The `Scheme` field of type `ℕ`. -/ + d : ℕ + /-- The `Scheme` field of type `ℕ`. -/ + h : ℕ + /-- The `Scheme` field of type `ℕ`. -/ + k : ℕ + /-- The `Scheme` field of type `ℕ`. -/ + e : ℕ + /-- The `Scheme` field of type `ℕ`. -/ + ℓ : ℕ + /-- The `Scheme` component of type `B ℓ → Pattern F d k e`. -/ + decode : B ℓ → Pattern F d k e + +namespace Scheme +variable {F : Type} (S : Scheme F) + +open scoped Classical in +/-- The value specified by `Fmt.rows S.m S.d S.h (.addr S.ℓ)`. -/ +abbrev format := Fmt.rows S.m S.d S.h (.addr S.ℓ) +open scoped Classical in +/-- Indexes the vtx by the coordinates of `B S.m × B S.h × B S.k`. -/ +abbrev Vtx := B S.m × B S.h × B S.k +open scoped Classical in +/-- Indexes the span by the coordinates of `S.Vtx × B S.e`. -/ +abbrev Span := S.Vtx × B S.e + +variable (r : S.format.obj) + +open scoped Classical in +/-- Computes the pattern by the application `S.decode ((r v.1).2 v.2.1)`. -/ +def pattern (v : S.Vtx) := S.decode ((r v.1).2 v.2.1) + +open scoped Classical in +/-- The value specified by `(S.pattern r p.1).width p.1.2.2 p.2`. -/ +def width (p : S.Span) := (S.pattern r p.1).width p.1.2.2 p.2 + +open scoped Classical in +/-- The value specified by `(S.pattern r p.1).direction p.1.2.2 p.2`. -/ +def direction (p : S.Span) := (S.pattern r p.1).direction p.1.2.2 p.2 + +open scoped Classical in +/-- Transforms the indexed data by `((S.pattern r p.1).peer p.1.2.2 p.2).map fun t => (((r +p.1.1).1 t.1, p.1.2.1, t.2.1), t.2.2)`. -/ +def peer (p : S.Span) : Option S.Span := + ((S.pattern r p.1).peer p.1.2.2 p.2).map + fun t => (((r p.1.1).1 t.1, p.1.2.1, t.2.1), t.2.2) + +open scoped Classical in +/-- The condition `∀ p q, S.peer r p = some q → S.peer r q = some p ∧ S.width r p = S.width r q +∧ S.direction r p ≠ S.direction r q` on the specified data. -/ +def Proper : Prop := ∀ p q, S.peer r p = some q → + S.peer r q = some p ∧ S.width r p = S.width r q ∧ S.direction r p ≠ S.direction r q + +open scoped Classical in +theorem span_mem_of_pos {A : Type*} (span : A → S.Span) + (idle : ∀ s ∉ Set.range span, S.width r s = 0) {s : S.Span} (positive : 0 < S.width r s) : + s ∈ Set.range span := by + by_contra h + rw [idle s h] at positive + exact (Nat.lt_irrefl _) positive + +open scoped Classical in +theorem peer_of_link {p q : S.Span} {src dst : B S.m} {block : B S.h} {layer : B S.k} + {index : B S.d} (source : p.1 = (src, block, layer)) (target : q.1 = (dst, block, layer)) + (link : (S.pattern r p.1).peer p.1.2.2 p.2 = some (index, layer, q.2)) + (nav : (r src).1 index = dst) : S.peer r p = some q := by + rw [peer, link, Option.map_some, source] + dsimp only + rw [nav] + exact congrArg some (Prod.ext target.symm rfl) + +open scoped Classical in +theorem proper_of_span {J E : Type*} (span : J ⊕ (E × Bool) → S.Span) (edgeWidth : ℕ) + (idle : ∀ s ∉ Set.range span, S.peer r s = none) + (outside : ∀ j, S.peer r (span (.inl j)) = none) + (peerEnd : ∀ e t, S.peer r (span (.inr (e, t))) = some (span (.inr (e, !t)))) + (widthEnd : ∀ e t, S.width r (span (.inr (e, t))) = edgeWidth) + (direction : ∀ e t, S.direction r (span (.inr (e, t))) = t) : S.Proper r := by + intro a b h + by_cases he : a ∈ Set.range span + swap + · rw [idle _ he] at h + cases h + obtain ⟨j|⟨e, t⟩, rfl⟩ := he + · rw [outside] at h + cases h + rw [peerEnd, Option.some.injEq] at h + subst b + rw [peerEnd, Bool.not_not, widthEnd, widthEnd, direction, direction] + exact ⟨rfl, rfl, by cases t <;> decide⟩ + +open scoped Classical in +/-- Indexes the pin by the coordinates of `Σ p : S.Span, Fin (S.width r p)`. -/ +abbrev Pin := Σ p : S.Span, Fin (S.width r p) + +open scoped Classical in +/-- A pin lies at the vertex of a positive-width span in the allocation. -/ +theorem cover_of_span {A V : Type*} (span : A → S.Span) (vertex : V → S.Vtx) + (site : A → V) (placed : ∀ j, vertex (site j) = (span j).1) + (idle : ∀ s ∉ Set.range span, S.width r s = 0) (pin : S.Pin r) : + ∃ v, vertex v = pin.1.1 := by + obtain ⟨j, equal⟩ := S.span_mem_of_pos r span idle (s := pin.1) + ((Nat.zero_le pin.2.val).trans_lt pin.2.isLt) + exact ⟨site j, (placed j).trans (congrArg Prod.fst equal)⟩ + +open scoped Classical in +/-- Indexes the local pin by the coordinates of `Σ s : B S.e, Fin (S.width r (v, s))`. -/ +abbrev LocalPin (v : S.Vtx) := Σ s : B S.e, Fin (S.width r (v, s)) +open scoped Classical in +/-- The subtype of `p : S.Pin r` satisfying `S.peer r p.1 = none`. -/ +abbrev exposed := {p : S.Pin r // S.peer r p.1 = none} + +/-- Embedding the site and the seats above each site gives an injective span address. -/ +theorem span_injective {Site Face : Type*} (atSite : Face → Site) + (vertex : Site ↪ S.Vtx) (seat : ∀ v, {j // atSite j = v} ↪ B S.e) + (slot : Face → B S.e) (slot_eq : ∀ v j, slot j.val = seat v j) : + Function.Injective (fun j => (vertex (atSite j), slot j)) := by + intro j k he + have hk := vertex.injective (Prod.mk.inj he).1 + let t : {j // atSite j = atSite k} := ⟨j, hk⟩ + have h : seat _ t = seat _ ⟨k, rfl⟩ := + (slot_eq _ t).symm.trans ((Prod.mk.inj he).2.trans (slot_eq _ ⟨k, rfl⟩)) + exact congrArg Subtype.val ((seat _).injective h) + +/-- Order the pins at a site by its visible faces and then by the offset within each face. -/ +def orderPins {Site Face : Type*} (atSite : Face → Site) + (vertex : Site ↪ S.Vtx) (seat : ∀ v, {j // atSite j = v} ↪ B S.e) + (slot : Face → B S.e) (slot_eq : ∀ v j, slot j.val = seat v j) + (width : Face → ℕ) (v : Site) + (length_at : ∀ j, S.width r (vertex v, seat v j) = width j.val) + (idle : ∀ t ∉ Set.range (fun j => (vertex (atSite j), slot j)), S.width r t = 0) : + (Σ j : {j // atSite j = v}, Fin (width j.val)) ≃ S.LocalPin r (vertex v) := + Equiv.ofBijective (fun t => ⟨seat v t.1, t.2.cast (length_at t.1).symm⟩) ⟨by + rintro ⟨j, b⟩ ⟨k, c⟩ he + have hj : j = k := (seat v).injective (congrArg Sigma.fst he) + subst k + have hi : b.val = c.val := congrArg (fun p => p.2.val) he + rw [Fin.ext hi], by + rintro ⟨j, b⟩ + obtain ⟨k, hk⟩ := S.span_mem_of_pos r _ idle (Nat.zero_le b.val |>.trans_lt b.isLt) + let t : {j // atSite j = v} := ⟨k, vertex.injective (Prod.mk.inj hk).1⟩ + have he : seat v t = j := (slot_eq v t).symm.trans (Prod.mk.inj hk).2 + have hl : b.val < width t.val := by rw [← length_at, he]; exact b.isLt + refine ⟨⟨t, ⟨b.val, hl⟩⟩, Sigma.ext he ?_⟩ + exact (Fin.heq_ext_iff (congrArg (fun j => S.width r (vertex v, j)) he)).mpr rfl⟩ + +open scoped Classical in +/-- Uses `⟨(v, p.1), p.2⟩` as the representation. -/ +def port (v : S.Vtx) (p : S.LocalPin r v) : S.Pin r := ⟨(v, p.1), p.2⟩ + +open scoped Classical in +/-- The indexed operation `(S.pattern r v).value v.2.2 fun s i => x ⟨s, i⟩`. -/ +def table (v : S.Vtx) (x : S.LocalPin r v → Bool) := + (S.pattern r v).value v.2.2 fun s i => x ⟨s, i⟩ + +open scoped Classical in +/-- Requires `S.peer r p.1 = some q.1 ∧ p.2.val = q.2.val`. -/ +def Joins (p q : S.Pin r) : Prop := S.peer r p.1 = some q.1 ∧ p.2.val = q.2.val + +open scoped Classical in +/-- Requires `(∀ p, y p.val = x p) ∧ ∀ p q, S.Joins r p q → y p = y q`. -/ +def Agrees (x : S.exposed r → Bool) (y : S.Pin r → Bool) : Prop := + (∀ p, y p.val = x p) ∧ ∀ p q, S.Joins r p q → y p = y q + +open scoped Classical in +/-- The indexing data represented by `∑ y : S.Pin r → Bool, if S.Agrees r x y then ∏ v, S.table +r v (y ∘ S.port r v) else 0`. -/ +def eval [Field F] (x : S.exposed r → Bool) := + ∑ y : S.Pin r → Bool, if S.Agrees r x y then ∏ v, S.table r v (y ∘ S.port r v) else 0 + +end Scheme +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Station tables in span order + +Each side lists the spans in increasing order and the bits of each +span in increasing offset. Only the pattern and local station label +are needed to construct the table. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Pattern +open Coloring Transcript + +variable {F : Type} {d k e : ℕ} (P : Pattern F d k e) (j : B k) + +/-- Indexes the pin by the coordinates of `Σ s, Fin (P.width j s)`. -/ +abbrev Pin := Σ s, Fin (P.width j s) +/-- The subtype of `s` satisfying `P.direction j s = b`. -/ +abbrev Side (b : Bool) := {s // P.direction j s = b} +/-- Computes the lengths by the application `P.width j s.1`. -/ +abbrev lengths (b : Bool) (s : P.Side j b) := P.width j s.1 +/-- Indexes the group by the coordinates of `Σ s, Fin (P.lengths j b s)`. -/ +abbrev Group (b : Bool) := Σ s, Fin (P.lengths j b s) + +/-- Computes the wire by the application `word (Fintype.card (Lex (P.Group j b)))`. -/ +def wire (b : Bool) := word (Fintype.card (Lex (P.Group j b))) + +/-- Reindexes `slots (P.wire j b)` and `P.Group j b` by an equivalence. -/ +def serial (b : Bool) : slots (P.wire j b) ≃ P.Group j b := + ((positions (P.wire j b)).trans (finCongr (wd_word _))).trans + ((Fintype.orderIsoFinOfCardEq (Lex (P.Group j b)) rfl).toEquiv.trans ofLex) + +/-- Uses `⟨q.1.1, q.2⟩` as the representation. -/ +def flat (b : Bool) (q : P.Group j b) : P.Pin j := ⟨q.1.1, q.2⟩ + +theorem flat_inj (b : Bool) : Function.Injective (P.flat j b) := by + rintro ⟨⟨s, h⟩, i⟩ ⟨⟨t, h'⟩, l⟩ he + have eq : s = t := congrArg Sigma.fst he + subst t + have : i = l := Fin.ext (congrArg (fun x => x.2.val) he) + rw [this] + +/-- Bundles the indexing function as an equivalence. -/ +def sides : P.Group j false ⊕ P.Group j true ≃ P.Pin j := + Equiv.ofBijective (Sum.elim (P.flat j false) (P.flat j true)) (by + constructor + · rintro (i|i) (l|l) h + · exact congrArg Sum.inl (P.flat_inj j _ h) + · have he : i.1.1 = l.1.1 := congrArg Sigma.fst h + have := i.1.2 + rw [he, l.1.2] at this + cases this + · have he : i.1.1 = l.1.1 := congrArg Sigma.fst h + have := i.1.2 + rw [he, l.1.2] at this + cases this + · exact congrArg Sum.inr (P.flat_inj j _ h) + · rintro ⟨s, i⟩ + cases h : P.direction j s + · exact ⟨.inl ⟨⟨s, h⟩, i⟩, rfl⟩ + · exact ⟨.inr ⟨⟨s, h⟩, i⟩, rfl⟩) + +/-- Reindexes `slots (P.wire j false) ⊕ slots (P.wire j true)` and `P.Pin j` by an equivalence. -/ +def orderedPin : slots (P.wire j false) ⊕ slots (P.wire j true) ≃ P.Pin j := + ((P.serial j false).sumCongr (P.serial j true)).trans (P.sides j) + +theorem pin_side (i : slots (P.wire j false) ⊕ slots (P.wire j true)) : + P.direction j (P.orderedPin j i).1 = i.isRight := by + cases i with + | inl i => exact (P.serial j false i).1.2 + | inr i => exact (P.serial j true i).1.2 + +/-- The ordered table of type `Table F` for the given inputs. -/ +def orderedTable : Table F := + ⟨P.wire j false, P.wire j true, fun x y => P.value j fun s i => + Sum.elim (bits (P.wire j false) x) (bits (P.wire j true) y) ((P.orderedPin j).symm ⟨s, i⟩)⟩ + +theorem sample_ordered (t : P.Pin j → Bool) : + sample (P.orderedTable j) (t ∘ P.orderedPin j) = P.value j (fun s i => t ⟨s, i⟩) := by + unfold sample orderedTable + apply congrArg (P.value j) + funext s i + simp only [Equiv.apply_symm_apply] + have h (x : slots (P.wire j false) ⊕ slots (P.wire j true)) : + Sum.elim (t ∘ P.orderedPin j ∘ Sum.inl) (t ∘ P.orderedPin j ∘ Sum.inr) x = + t (P.orderedPin j x) := by cases x <;> rfl + rw [← Function.comp_assoc, ← Function.comp_assoc] at h + rw [h, Equiv.apply_symm_apply] + +/-- The value specified by `Processor.start (P.lengths j (P.direction j s)) ⟨s, rfl⟩`. -/ +def start (s : B e) := + Processor.start (P.lengths j (P.direction j s)) ⟨s, rfl⟩ + +private theorem start_eq (b : Bool) (s : P.Side j b) : + P.start j s.1 = Processor.start (P.lengths j b) s := by + obtain ⟨s, h⟩ := s + subst b + rfl + +theorem start_left {s t : B e} (h : P.direction j s = P.direction j t) (ht : s < t) : + P.start j s + P.width j s ≤ P.start j t := by + rw [P.start_eq j _ ⟨s, h⟩] + exact Processor.start_left (P.lengths j _) ⟨s, h⟩ ⟨t, rfl⟩ ht + +private theorem serial_position (b : Bool) (i : slots (P.wire j b)) : + (positions (P.wire j b) i).val = P.start j (P.serial j b i).1.1 + (P.serial j b i).2.val := by + rw [P.start_eq] + let g := Fintype.orderIsoFinOfCardEq (Lex (P.Group j b)) rfl + let x := (finCongr (wd_word (Fintype.card (Lex (P.Group j b))))) (positions (P.wire j b) i) + calc + _ = (g.symm (g x)).val := by rw [OrderIso.symm_apply_apply]; rfl + _ = _ := Processor.serial_rank (P.lengths j b) rfl (g x) + +theorem position_left (i : slots (P.wire j false)) : + (positions (P.wire j false) i).val = P.start j (P.orderedPin j (.inl i)).1 + + (P.orderedPin j (.inl i)).2.val := P.serial_position j false i + +theorem position_right (i : slots (P.wire j true)) : + (positions (P.wire j true) i).val = P.start j (P.orderedPin j (.inr i)).1 + + (P.orderedPin j (.inr i)).2.val := P.serial_position j true i + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Pattern +end + +/- +# Computing the matching at one host position + +The neighbor list is common to all blocks of the position. Only a +short index into that list and the neighbor's colony key enter a row. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +open Coloring + +/-- The value specified by `Format.pair (.vec h .bit) (.pair (.vec h (Fmt.occ d h e k ℓ)) (.vec +h (.vec d (.addr ℓ))))`. -/ +abbrev Input (d h e k ℓ : ℕ) := + Format.pair (.vec h .bit) (.pair (.vec h (Fmt.occ d h e k ℓ)) (.vec h (.vec d (.addr ℓ)))) + +/-- The value specified by `Format.pair (.addr h) (.pair (.addr ℓ) (.addr d))`. -/ +abbrev Labels (h ℓ d : ℕ) := Format.pair (.addr h) (.pair (.addr ℓ) (.addr d)) + +/-- Reindexes `B (h + e)` and `B h × B e` by an equivalence. -/ +def rowIndex (h e : ℕ) : B (h + e) ≃ B h × B e := + (finCongr (pow_add 2 h e)).trans finProdFinEquiv.symm + +variable {d h e k ℓ : ℕ} + +/-- The rows of type `Rows (h + e) (Labels h ℓ d).width`, constructed using `(rowIndex h e +i).1`. -/ +def rows (x : (Input d h e k ℓ).obj) : Rows (h + e) (Labels h ℓ d).width := + let block i := (rowIndex h e i).1 + let stub i := (x.2.1 (block i)).2 (rowIndex h e i).2 + let code := (Labels h ℓ d).serial + (fun i => (stub i).1, fun i => x.1 (block i), + fun i => code (0, (x.2.1 (block i)).1, 0), fun i => code (block i, 0, 0), + fun i => code (0, x.2.2 (block i) (stub i).2.1, (stub i).2.1)) + +theorem width_labels (h ℓ d : ℕ) : (Labels h ℓ d).width = h + (ℓ + d) := by simp [Labels] + +variable (F : Type) [Field F] + +theorem read_one (U : Format) {t : ℕ} (hh : d ≤ t) (hl : U.width ≤ t) (hd : 2 ^ d ≤ t) : + Cheap F 0 t (.pair (.addr d) (.vec d U)) U (fun x => x.2 x.1) 12 := by + let A := Format.pair (.addr d) (.vec d U) + have ha : A.width ≤ 2 ^ d * (100 + t) ^ 2 := by + simp only [A, Format.width_pair, Format.width_vec, Format.width_addr] + calc + _ ≤ 2 ^ d * d + 2 ^ d * U.width := Nat.add_le_add_right (Nat.le_mul_of_pos_left _ (by + positivity)) _ + _ ≤ _ := by rw [← mul_add]; gcongr; ring_nf; omega + have hi : (Perm d).width ≤ 2 ^ d * (100 + t) ^ 2 := + (column_width _ hh).trans (by gcongr; omega) + have hv : Cheap F d t A (Perm d) (fun x _ => x.1) 3 := + Cheap.project F ha hi (fun j => Sum.inl j.2) (fun _ _ => rfl) + have hs := ((Cheap.id F ha).snd.pair hv).comp (Cheap.lookup F d t U hh hl) + have hk : U.width ≤ 2 ^ d * (100 + t) ^ 1 := by + rw [pow_one] + exact (Nat.le_mul_of_pos_left _ (by positivity)).trans (Nat.mul_le_mul_left _ (by omega)) + have hm : (Format.vec d U).width ≤ 2 ^ d * (100 + t) ^ 1 := by + rw [Format.width_vec, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have out : Cheap F d t (.vec d U) U (fun x => x 0) 2 := + Cheap.project F hm hk (fun j => (0, j)) (fun _ _ => rfl) + obtain ⟨m, hm, hc⟩ := (hs.comp out).mono (d := 11) (by decide) + refine ⟨m, hm, hc.trans ?_⟩ + rw [pow_zero, one_mul, show 12 = 11 + 1 from rfl, pow_succ' (100 + t) 11] + exact Nat.mul_le_mul_right _ (by omega) + +theorem input_bound (t : ℕ) (h₁ : d ≤ t) (h₂ : k ≤ t) (h₃ : ℓ ≤ t) (hd : 2 ^ d ≤ t) : + (Input d h e k ℓ).width ≤ 2 ^ (h + e) * (100 + t) ^ 2 := by + unfold Input + rw [Format.width_pair, Format.width_pair, Format.width_vec, Format.width_bit, Format.width_vec, + Fmt.width_occ, Format.width_vec, Format.width_vec, Format.width_addr, ← mul_add, ← mul_add, + pow_add, mul_assoc] + apply Nat.mul_le_mul_left + have he : 0 < 2 ^ e := by positivity + calc + _ ≤ 2 ^ e * (1 + (ℓ + (1 + (d + k)) + 2 ^ d * ℓ)) := by + simp only [mul_add] + have := Nat.le_mul_of_pos_left ℓ he + have := Nat.le_mul_of_pos_left (2 ^ d * ℓ) he + omega + _ ≤ _ := by gcongr; nlinarith only [h₁, h₂, h₃, Nat.mul_le_mul hd h₃] + +theorem cheap_rows (d h e k ℓ t : ℕ) (ht : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) + (hw : k ≤ t) (hd : 2 ^ d ≤ t) : + Cheap F (h + e) t (Input d h e k ℓ) (RowFmt (h + e) (Labels h ℓ d).width) rows 30 := by + let A := Input d h e k ℓ + let b i := (rowIndex h e i).1 + let j i := (rowIndex h e i).2 + let stub (x : A.obj) i := (x.2.1 (b i)).2 (j i) + have wt := ht + rw [Rows.overhead, width_labels] at wt + have ha := input_bound (h := h) (e := e) t (show d ≤ t by omega) hw (show ℓ ≤ t by omega) hd + have hc (i : ℕ) (hi : i ≤ t) : (Column (h + e) i).width ≤ 2 ^ (h + e) * (100 + t) ^ 2 := + (column_width _ hi).trans (by gcongr; omega) + have hb : (Format.vec (h + e) .bit).width ≤ 2 ^ (h + e) * (100 + t) ^ 2 := by + rw [Format.width_vec, Format.width_bit] + exact Nat.mul_le_mul_left _ (Nat.one_le_pow _ _ (by omega)) + have hn : (Format.vec (h + e) (.vec d (.addr ℓ))).width ≤ 2 ^ (h + e) * (100 + t) ^ 2 := by + rw [Format.width_vec, Format.width_vec, Format.width_addr, pow_two] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul (by omega) (by omega)) + have active : Cheap F (h + e) t A (.vec (h + e) .bit) (fun x i => (stub x i).1) 3 := + Cheap.project F ha hb (fun z => .inr (.inl (b z.1, .inr (j z.1, .inl z.2)))) (fun _ _ => rfl) + have thick : Cheap F (h + e) t A (.vec (h + e) .bit) (fun x i => x.1 (b i)) 3 := + Cheap.project F ha hb (fun z => .inl (b z.1, z.2)) (fun _ _ => rfl) + have label : Cheap F (h + e) t A (Column (h + e) ℓ) (fun x i => (x.2.1 (b i)).1) 3 := + Cheap.project F ha (hc ℓ (by omega)) (fun z => .inr (.inl (b z.1, .inl z.2))) (fun _ _ => rfl) + have near : Cheap F (h + e) t A (Column (h + e) d) (fun x i => (stub x i).2.1) 3 := + Cheap.project F ha (hc d (by omega)) + (fun z => .inr (.inl (b z.1, .inr (j z.1, .inr (.inl z.2))))) (fun _ _ => rfl) + have remote : Cheap F (h + e) t A (.vec (h + e) (.vec d (.addr ℓ))) (fun x i => x.2.2 (b i)) 3 := + Cheap.project F ha hn (fun z => .inr (.inr (b z.1, z.2))) (fun _ _ => rfl) + have addr := (near.pair remote).zip.comp + (Cheap.map (fun _ => _) (fun _ => read_one (d := d) F (.addr ℓ) (by omega) (by simp; omega) hd)) + have zero (i : ℕ) (hi : i ≤ t) : Cheap F (h + e) t A (Column (h + e) i) (fun _ _ => 0) 3 := + Cheap.const F ha (hc i hi) (fun _ => 0) + have keys := cheap_keys (Labels h ℓ d) F (h + e) (show (Labels h ℓ d).width + ≤ t by rw [width_labels]; omega) + have block := Cheap.const F ha (hc h (by omega)) b + have src := ((zero h (by omega)).pair (label.pair (zero d (by omega))).zip).zip.comp keys + have item := (block.pair ((zero ℓ (by omega)).pair (zero d (by omega))).zip).zip.comp keys + have dest := ((zero h (by omega)).pair (addr.pair near).zip).zip.comp keys + exact (active.pair (thick.pair (src.pair (item.pair dest)))).mono (by decide) + +theorem cheap_match (d h e k ℓ t : ℕ) (ht : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) + (hw : k ≤ t) (hd : 2 ^ d ≤ t) : + Cheap F (h + e) t (Input d h e k ℓ) (.pair (.vec (h + e) .bit) (Perm (h + e))) + (fun x => (rows x).control) 151 := + ((cheap_rows F d h e k ℓ t ht hw hd).comp ((Rows.cheap_control F _ _).widen ht)).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +/- # Packing the exterior bits of a scheme by host and occurrence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme + +open Coloring +variable {F : Type} (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +/-- Uses `i.val.1.1.1` as the representation. -/ +def owner (i : S.exposed r) : B S.m := i.val.1.1.1 + +open scoped Classical in +/-- The subtype of `a : S.exposed r` satisfying `S.owner r a = i`. -/ +abbrev fiber (i : B S.m) := {a : S.exposed r // S.owner r a = i} + +open scoped Classical in +/-- Counts the elements of `(S.fiber r i)`. -/ +def load (i : B S.m) := Fintype.card (S.fiber r i) + +open scoped Classical in +/-- Requires `(∑ i, max 1 (S.load r i)) ≤ V ∧ ∀ i, S.load r i ≤ 2 ^ k`. -/ +def Fits (V k : ℕ) : Prop := + (∑ i, max 1 (S.load r i)) ≤ V ∧ ∀ i, S.load r i ≤ 2 ^ k + +open scoped Classical in +/-- The quantity computed by `S.h + S.k + S.e`. -/ +def spanRows := S.h + S.k + S.e + +open scoped Classical in +/-- Reindexes `B S.m × B S.spanRows` and `S.Span` by an equivalence. -/ +def hostSpan : B S.m × B S.spanRows ≃ S.Span := + ((Equiv.refl _).prodCongr + ((Match.rowIndex (S.h + S.k) S.e).trans + ((Match.rowIndex S.h S.k).prodCongr (.refl _)))).trans (Equiv.prodAssoc _ _ _).symm + +open scoped Classical in +/-- The value specified by `(S.hostSpan.symm p).2`. -/ +def spanIndex (p : S.Span) := (S.hostSpan.symm p).2 + +open scoped Classical in +@[simp] theorem hostSpan_owner (i : B S.m) (t : B S.spanRows) : (S.hostSpan (i, t)).1.1 = i := rfl + +open scoped Classical in +@[simp] theorem spanIndex_hostSpan (i : B S.m) (t : B S.spanRows) : + S.spanIndex (S.hostSpan (i, t)) = t := by rw [spanIndex, Equiv.symm_apply_apply] + +open scoped Classical in +@[simp] theorem hostSpan_spanIndex (p : S.Span) : S.hostSpan (p.1.1, S.spanIndex p) = p := + S.hostSpan.apply_symm_apply p + +open scoped Classical in +/-- The construction uses `S.hostSpan (i, t)` for its intermediate `p`. -/ +def extent (i : B S.m) (t : B S.spanRows) := + let p := S.hostSpan (i, t) + if S.peer r p = none then S.width r p else 0 + +open scoped Classical in +/-- Reindexes `S.fiber r i` and `Σ t, Fin (S.extent r i t)` by an equivalence. -/ +def localBits (i : B S.m) : S.fiber r i ≃ Σ t, Fin (S.extent r i t) := by + have he (a : S.fiber r i) : S.hostSpan (i, S.spanIndex a.val.val.1) = a.val.val.1 := + (congrArg (fun z => S.hostSpan (z, S.spanIndex a.val.val.1)) a.2.symm).trans + (S.hostSpan_spanIndex _) + let f : S.fiber r i → Σ t, Fin (S.extent r i t) := fun a => + ⟨S.spanIndex a.val.val.1, a.val.val.2.val, by + unfold extent + rw [he] + simp only [a.val.property, ite_true] + exact a.val.val.2.isLt⟩ + refine Equiv.ofBijective f ⟨?_, ?_⟩ + · intro a b heq + have h₁ : S.spanIndex a.val.val.1 = S.spanIndex b.val.val.1 := congrArg Sigma.fst heq + have h₂ : a.val.val.2.val = b.val.val.2.val := congrArg (fun i => i.2.val) heq + have h₃ : a.val.val.1 = b.val.val.1 := by rw [← he a, ← he b, h₁] + exact Subtype.ext (Subtype.ext (Sigma.ext h₃ ((Fin.heq_ext_iff (congrArg _ h₃)).mpr h₂))) + · rintro ⟨t, b⟩ + let u := S.hostSpan (i, t) + have hb : b.val < if S.peer r u = none then S.width r u else 0 := b.isLt + split at hb + swap + · omega + rename_i hu + let p : S.fiber r i := ⟨⟨⟨u, ⟨b.val, hb⟩⟩, hu⟩, rfl⟩ + have hp : (f p).1 = t := S.spanIndex_hostSpan _ _ + exact ⟨p, Sigma.ext hp ((Fin.heq_ext_iff (congrArg _ hp)).mpr rfl)⟩ + +open scoped Classical in +theorem load_eq (i : B S.m) : S.load r i = ∑ j, S.extent r i j := by + unfold load + rw [Fintype.card_congr (S.localBits r i), Fintype.card_sigma] + simp + +open scoped Classical in +/-- Order within one host is lexicographic by block, station, span +and offset within the span. -/ +def serial (i : B S.m) : S.fiber r i ≃ Fin (S.load r i) := + (S.localBits r i).trans (finSigmaFinEquiv.trans (finCongr (S.load_eq r i).symm)) + +variable {V k : ℕ} (h : S.Fits r V k) + +open scoped Classical in +/-- Uses `⟨S.load r, h.1, h.2⟩` as the representation. -/ +def payload : Payload S.m V k := ⟨S.load r, h.1, h.2⟩ + +open scoped Classical in +/-- Reindexes `S.exposed r` and `(S.payload r h).Bit` by an equivalence. -/ +def index : S.exposed r ≃ (S.payload r h).Bit := + (Equiv.sigmaFiberEquiv (S.owner r)).symm.trans (Equiv.sigmaCongrRight (S.serial r)) + +open scoped Classical in +/-- The sum of `S.extent r i j` indexed by `j with j < t`. -/ +def start (i : B S.m) (t : B S.spanRows) := ∑ j with j < t, S.extent r i j + +open scoped Classical in +private theorem strict_sum {n : ℕ} (f : Fin n → ℕ) (b : Fin n) : + (∑ i : Fin b.val, f (i.castLE b.isLt.le)) = ∑ i with i < b, f i := by + let e : Fin b.val ≃ {i // i < b} := + { toFun := fun i => ⟨i.castLE b.isLt.le, i.isLt⟩ + invFun := fun i => ⟨i.val.val, i.property⟩ + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + rw [Finset.sum_subtype (p := (· < b)) _ Finset.mem_filter_univ] + exact Fintype.sum_equiv e _ _ (fun _ => rfl) + +open scoped Classical in +theorem index_val (a : S.exposed r) : + (S.index r h a).2.val = S.start r (S.owner r a) (S.spanIndex a.val.1) + a.val.2.val := by + let i := S.owner r a + let q := S.localBits r i ⟨a, rfl⟩ + change (finSigmaFinEquiv q).val = _ + rw [finSigmaFinEquiv_apply, strict_sum] + rfl + +open scoped Classical in +/-- Embeds `S.exposed r` into `Fmt.Port S.m V k`. -/ +def wire : S.exposed r ↪ Fmt.Port S.m V k := + (S.index r h).toEmbedding.trans (S.payload r h).wire + +open scoped Classical in +/-- The value specified by `(S.payload r h).store (x ∘ (S.index r h).symm)`. -/ +def store (x : S.exposed r → Bool) : (Fmt.payload S.m V k).obj := + (S.payload r h).store (x ∘ (S.index r h).symm) + +open scoped Classical in +@[simp] theorem read_store (x : S.exposed r → Bool) (i : S.exposed r) : + S.store r h x (S.wire r h i) = x i := by + simp [store, wire] + +open scoped Classical in +theorem store_unique (x : S.exposed r → Bool) (y : (Fmt.payload S.m V k).obj) + (hx : ∀ i, y (S.wire r h i) = x i) (hy : ∀ i ∉ Set.range (S.wire r h), y i = false) : + y = S.store r h x := by + apply Payload.store_unique + · intro i + simpa [wire] using hx ((S.index r h).symm i) + · intro i hi + exact hy i fun ⟨j, hj⟩ => hi ⟨S.index r h j, hj⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- +# Matching reciprocal neighbor names + +Sort by the unordered pair of names and return the other row with +that key. A row naming its own host stays fixed, so self-contacts +may have arbitrary multiplicity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +private abbrev Names (m : ℕ) := Format.pair (.addr m) (.addr m) + +private def sorted {m : ℕ} (z : B m × B m) := if z.1 < z.2 then z else z.swap + +private theorem sorted_swap {m : ℕ} (a b : B m) : sorted (a, b) = sorted (b, a) := by + rcases lt_trichotomy a b with h | rfl | h + · simp [sorted, h, not_lt.mpr h.le] + · rfl + · simp [sorted, h, not_lt.mpr h.le] + +private theorem cheap_sorted (F : Type) [Field F] {m t : ℕ} (hm : m ≤ t) : + Cheap F 0 t (Names m) (Names m) sorted 12 := by + have lt : Cheap F 0 t (Names m) .bit (fun z => decide (z.1 < z.2)) 3 := by + refine ⟨_, numeric_lt F m, ?_⟩ + simp only [Format.width_pair, Format.width_addr] + rw [Format.width_bit] + ring_nf + omega + have hw : (Names m).width ≤ 2 ^ 0 * (100 + t) ^ 2 := by simp [Names]; ring_nf; omega + have a := Cheap.id F hw + have l := (a.pair lt).comp ((cheap_select F m).widen hm) + have r := ((a.snd.pair a.fst).pair lt).comp ((cheap_select F m).widen hm) + convert (l.pair r).mono (d := 12) (by decide) using 1 + funext z + obtain ⟨x, y⟩ := z + by_cases he : x < y <;> simp [sorted, he] + +variable {j m : ℕ} (host p : B j → B m) + +private def keys := (Names m).keys (fun i => sorted (host i, p i)) + +private def neighbor (i : B j) := + if host i = p i then i else other (keys host p) i + +private theorem reverse_eq + (h : ∀ i, p i ≠ host i → ∃! l, p i = host l ∧ p l = host i) + (i l : B j) (hi : p i ≠ host i) (hl : p i = host l ∧ p l = host i) : + neighbor host p i = l := by + have hn : l ≠ i := fun he => hi (he ▸ hl.1) + have he : keys host p l = keys host p i := by + unfold keys Format.keys + simp only [Function.comp_apply, ← hl.1, hl.2, sorted_swap] + rw [neighbor, ite_eq_right hi.symm] + let t := other (keys host p) i + obtain ⟨ht, hne⟩ := other_spec (keys host p) i + have hti : t ≠ i := hne l he hn + have hh : sorted (host t, p t) = sorted (host i, p i) := (Names m).serial.injective ht + have hk : (host t = host i ∧ p t = p i) ∨ (p i = host t ∧ p t = host i) := by + unfold sorted at hh + split_ifs at hh <;> simp only [Prod.swap_prod_mk, Prod.mk.injEq] at hh <;> tauto + rcases hk with hk | hk + · have hn' : p l ≠ host l := by rw [hl.2, ← hl.1]; exact hi.symm + exact (hti ((h l hn').unique ⟨hl.2.trans hk.1.symm, hk.2.trans hl.1⟩ ⟨hl.2, hl.1⟩)).elim + · exact (h i hi).unique hk hl + +theorem contacts (F : Type) [Field F] (j m : ℕ) (host : B j → B m) : + ∃ f : (B j → B m) → B j → B j, + Cheap F j (j + 3 * m + 1) (.vec j (.addr m)) (Perm j) f 200 ∧ + ∀ p, (∀ i, p i ≠ host i → ∃! l, p i = host l ∧ p l = host i) → + Function.Bijective (f p) ∧ ∀ i, host (f p i) = p i := by + refine ⟨neighbor host, ?_, fun p h => ?_⟩ + · let t := j + 3 * m + 1 + have hm : m ≤ t := by omega + have hj : j ≤ t := by omega + have hw : j + (Names m).width ≤ t := by simp [Names]; omega + have a := column_width j hm + have pair := ((Cheap.const F a a host).pair (Cheap.id F a)).zip + have sort := pair.comp (Cheap.map _ (fun _ => cheap_sorted F hm)) + have key := sort.comp (cheap_keys (Names m) F j (k := t) (by omega)) + have peer := key.comp ((cheap_other F j _).widen hw) + have eq := pair.comp (Cheap.map _ (fun _ => cheap_eq F hm)) + have self := Cheap.const F a (column_width j hj) id + have pick := (((self.pair peer).zip.pair eq).zip.comp (Cheap.map _ (fun _ + => (cheap_select F j).widen hj))) + convert pick.mono (d := 200) (by decide) using 1 + funext p i + simp [neighbor, keys] + · have both (i : B j) : neighbor host p (neighbor host p i) = i ∧ + host (neighbor host p i) = p i := by + by_cases he : p i = host i + · have hi : neighbor host p i = i := ite_eq_left he.symm + rw [hi, hi] + exact ⟨rfl, he.symm⟩ + · obtain ⟨l, hl, _⟩ := h i he + have hn : p l ≠ host l := by rw [hl.2, ← hl.1]; exact Ne.symm he + rw [reverse_eq host p h i l he hl] + exact ⟨reverse_eq host p h l i hn ⟨hl.2, hl.1⟩, hl.1.symm⟩ + exact ⟨Function.Involutive.bijective (fun i => (both i).1), fun i => (both i).2⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Exchanging full block records across a variable host + +Long names are routed only once per incident neighbor, independently +of the number of blocks carried by a record. Empty neighbor entries +name their own host. They need not be distinct. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] {u v n m d : ℕ} {L : Set (Table F)} + {I : Type*} (A : Format) + +open scoped Classical in +/-- Computes the bank by the application `Format.vec m (.pair (.vec d (.addr m)) A)`. -/ +abbrev Fmt.bank (m d : ℕ) (A : Format) := Format.vec m (.pair (.vec d (.addr m)) A) + +namespace Fmt + +open scoped Classical in +/-- The condition `∀ i j, (x i).1 j ≠ i → ∃! l, (x ((x i).1 j)).1 l = i` on the specified data. -/ +def Reciprocal (x : (bank m d A).obj) := ∀ i j, (x i).1 j ≠ i → + ∃! l, (x ((x i).1 j)).1 l = i + +open scoped Classical in +/-- The value specified by `(x ((x i).1 j)).2`. -/ +def gather (x : (bank m d A).obj) (i : B m) (j : B d) := (x ((x i).1 j)).2 + +end Fmt + +open scoped Classical in +private abbrev Col (m d : ℕ) := Format.vec (m + d) (.addr m) +open scoped Classical in +private abbrev Vec (m d : ℕ) (A : Format) := Format.vec (m + d) A + +open scoped Classical in +private def targets (x : (Fmt.bank m d A).obj) (j : B (m + d)) := + (x (Match.rowIndex m d j).1).1 (Match.rowIndex m d j).2 + +open scoped Classical in +private def hosts (m d : ℕ) (j : B (m + d)) := (Match.rowIndex m d j).1 + +open scoped Classical in +private theorem reciprocal_edges (x : (Fmt.bank m d A).obj) (h : Fmt.Reciprocal A x) + (i : B (m + d)) (hi : targets A x i ≠ hosts m d i) : + ∃! l, targets A x i = hosts m d l ∧ targets A x l = hosts m d i := by + let e := Match.rowIndex m d + obtain ⟨t, ht, hu⟩ := h (e i).1 (e i).2 hi + refine ⟨e.symm (targets A x i, t), ?_, fun j hj => ?_⟩ + · simpa only [targets, hosts, e, Equiv.apply_symm_apply, true_and] using ht + · apply e.injective + rw [e.apply_symm_apply] + refine Prod.ext hj.1.symm (hu _ ?_) + change (x (targets A x i)).1 (e j).2 = (e i).1 + rw [hj.1] + exact hj.2 + +open scoped Classical in +private theorem packets (hu : 3 ≤ u) (f : (Col m d).obj → (Perm (m + d)).obj) + (hf : Circuit F (Col m d) (Perm (m + d)) f n) : + Map F u L (Fmt.bank m d A) (exchangeIn A (m + d)) + (fun x => (f (targets A x), fun j => (x (hosts m d j)).2)) + (4 * (7 * (Fmt.bank m d A).width + 2 * ((Col m d).width + (Vec m d A).width) + n)) := by + let X := Fmt.bank m d A + have select : Circuit F X (Col m d) (targets A) (X.width + 2 * (Col m d).width) := + Circuit.project (fun p => let q := Match.rowIndex m d p.1; (q.1, .inl (q.2, p.2))) (fun _ _ + => rfl) + have data : Circuit F X (Vec m d A) (fun x j => (x (hosts m d j)).2) + (X.width + 2 * (Vec m d A).width) := + Circuit.project (fun p => (hosts m d p.1, .inr p.2)) (fun _ _ => rfl) + exact (Map.circuit hu ((select.comp hf).pair data)).mono (by unfold X; omega) + +open scoped Classical in +/-- The quantity computed by `4 * n + 4 * (2 ^ (m + d) * (100 + (m + d + 3 * m + 1)) ^ 200) + +1100 * 2 ^ (m + d) * (m + d + v + 1)`. -/ +def gatherCost (m d v n : ℕ) := + 4 * n + 4 * (2 ^ (m + d) * (100 + (m + d + 3 * m + 1)) ^ 200) + 1100 * 2 ^ (m + d) * (m + d + v + + 1) + +open scoped Classical in +theorem gather_neighbors (hu : 3 ≤ u) (ht : Access F u L (m + d) v n) (ha : A.width ≤ v) + (X : I → (Fmt.bank m d A).obj) (hx : ∀ i, Fmt.Reciprocal A (X i)) : + Computes F u L (Fmt.bank m d A) (.vec m (.vec d A)) X (fun i => Fmt.gather A (X i)) + (fun _ => 1) (gatherCost m d v n) := by + obtain ⟨f, ⟨c, hf, hc⟩, he⟩ := contacts F (m + d) m (hosts m d) + let out := Format.vec m (.vec d A) + have post : Map F u L (exchangeOut A (m + d)) out + (fun x i j => x ((Match.rowIndex m d).symm (i, j))) + (4 * ((Vec m d A).width + 2 * out.width)) := + Map.circuit hu (Circuit.project (fun z => ((Match.rowIndex m d).symm (z.1, z.2.1), z.2.2)) + fun _ _ => rfl) + have pre := packets (L := L) A hu f hf + have k := pre.then_kernel (ht A ha) + let y i j := (X i (targets A (X i) j)).2 + have relay : Computes F u L (Fmt.bank m d A) (exchangeOut A (m + d)) + X y (fun _ => 1) _ := ⟨_, k, fun i z => by + obtain ⟨hh, hh'⟩ := he _ (reciprocal_edges A (X i) (hx i)) + have hy : (fun j => (X i (hosts m d j)).2) ∘ f (targets A (X i)) = y i := + funext fun j => congrArg (fun l => (X i l).2) (hh' j) + simp only [exchange, hh, true_and, hy, eq_comm]⟩ + have h := relay.comp (Computes.of_map (x := y) post (y := fun i => Fmt.gather A (X i)) (by + intro i; funext j l + simp only [y, targets, Fmt.gather, Equiv.apply_symm_apply])) + simp only [mul_one] at h + refine h.mono ?_ + have hc' : c ≤ 2 ^ (m + d) * (100 + (m + d + 3 * m + 1)) ^ 200 := + (Nat.le_add_left _ _).trans hc + have hv : 2 ^ m * A.width ≤ 2 ^ (m + d) * v := + Nat.mul_le_mul (Nat.pow_le_pow_right (by decide) (Nat.le_add_right _ _)) ha + have ha' := Nat.mul_le_mul_left (2 ^ (m + d)) ha + simp only [out, Fmt.bank, Col, Vec, Format.width_vec, Format.width_pair, Format.width_addr, + gatherCost, mul_add, ← mul_assoc, ← pow_add] + simp only [mul_assoc] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Closed neighborhoods of a reciprocal host graph + +A walk may stay put at any step. A fixed dictionary enumerates all +walk instructions. At each center keep the first occurrence of each +destination and replace every repeated occurrence by the center. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +open Coloring + +/-- Computes the rows by the application `Format.vec m (.vec d (.addr m))`. -/ +abbrev Rows (m d : ℕ) := Format.vec m (.vec d (.addr m)) + +variable {m d : ℕ} (g : B m → B d → B m) + +/-- The two cases impose `x = y` and `∃ z, (z = x ∨ ∃ i, g x i = z) ∧ Reach r z y`, +respectively. -/ +def Reach : ℕ → B m → B m → Prop + | 0, x, y => x = y + | r + 1, x, y => ∃ z, (z = x ∨ ∃ i, g x i = z) ∧ Reach r z y + +theorem Reach.refl (r : ℕ) (x : B m) : Reach g r x x := by + induction r with + | zero => rfl + | succ r ih => exact ⟨x, Or.inl rfl, ih⟩ + +variable {g} {r : ℕ} {x y z : B m} + +theorem Reach.tail (h : Reach g r x y) (he : z = y ∨ ∃ i, g y i = z) : + Reach g (r + 1) x z := by + induction r generalizing x with + | zero => + change x = y at h + subst x + exact ⟨z, he, rfl⟩ + | succ r ih => + obtain ⟨a, ha, h⟩ := h + exact ⟨a, ha, ih h⟩ + +theorem Reach.symm (h : Reach g r x y) (hg : ∀ i j, g i j ≠ i → ∃ l, g (g i j) l = i) : + Reach g r y x := by + induction r generalizing x with + | zero => exact Eq.symm h + | succ r ih => + obtain ⟨a, ha, h⟩ := h + apply (ih h).tail + by_cases he : a = x + · exact .inl he.symm + · obtain ⟨i, rfl⟩ := ha.resolve_left he + exact .inr (hg _ _ he) + +/-- In the case `0`, this construction gives `Unit`. -/ +def Walk (d : ℕ) : ℕ → Type + | 0 => Unit + | r + 1 => Option (B d) × Walk d r + +instance walkFinite (d : ℕ) : (r : ℕ) → Fintype (Walk d r) + | 0 => inferInstanceAs (Fintype Unit) + | r + 1 => + let _ := walkFinite d r + inferInstanceAs (Fintype (Option (B d) × Walk d r)) + +/-- In the case `0`, this construction gives `()`. -/ +def stay (d : ℕ) : (r : ℕ) → Walk d r + | 0 => () + | r + 1 => (none, stay d r) + +instance (d r : ℕ) : Nonempty (Walk d r) := ⟨stay d r⟩ + +theorem walk_card (d r : ℕ) : Fintype.card (Walk d r) ≤ 2 ^ ((d + 1) * r) := by + induction r with + | zero => exact (Fintype.card_unit).le + | succ r ih => + change Fintype.card (Option (B d) × Walk d r) ≤ _ + rw [Fintype.card_prod, Fintype.card_option, Fintype.card_fin, Nat.mul_succ, pow_add, + Nat.mul_comm (2 ^ ((d + 1) * r))] + apply Nat.mul_le_mul _ ih + rw [pow_succ] + have := Nat.two_pow_pos d + omega + +/-- Embeds `Walk d r` into `B ((d + 1) * r)`. -/ +def code (d r : ℕ) : Walk d r ↪ B ((d + 1) * r) := + let e := (Fintype.equivFin _).toEmbedding.trans (Fin.castLEEmb (walk_card d r)) + e.trans (Equiv.swap (e (stay d r)) 0).toEmbedding + +/-- Computes the path by the application `Function.invFun (code d r)`. -/ +def path (d r : ℕ) := Function.invFun (code d r) + +/-- In the case `0, _, x`, this construction gives `x`. -/ +def run (g : B m → B d → B m) : (r : ℕ) → Walk d r → B m → B m + | 0, _, x => x + | r + 1, w, x => run g r w.2 (w.1.elim x (g x)) + +theorem path_surjective (d r : ℕ) : Function.Surjective (path d r) := + fun w => ⟨code d r w, Function.leftInverse_invFun (code d r).injective w⟩ + +/-- Computes the walks by the application `run g r (path d r i) x`. -/ +def walks (r : ℕ) (g : B m → B d → B m) (x : B m) (i : B ((d + 1) * r)) := + run g r (path d r i) x + +private theorem reach_iff : Reach g r x y ↔ ∃ w, run g r w x = y := by + induction r generalizing x with + | zero => exact ⟨fun h => ⟨(), h⟩, fun ⟨_, h⟩ => h⟩ + | succ r ih => + constructor + · rintro ⟨a, ha, h⟩ + obtain ⟨w, hw⟩ := ih.mp h + rcases ha with rfl | ⟨i, rfl⟩ + · exact ⟨(none, w), hw⟩ + · exact ⟨(some i, w), hw⟩ + · rintro ⟨⟨_|i, w⟩, hw⟩ + · exact ⟨x, Or.inl rfl, ih.mpr ⟨w, hw⟩⟩ + · exact ⟨g x i, Or.inr ⟨i, rfl⟩, ih.mpr ⟨w, hw⟩⟩ + +/-- Returns `a i` when `groupFirst a i = i` holds, and `x` otherwise. -/ +def dedup {q : ℕ} (x : B m) (a : B q → B m) (i : B q) := + if groupFirst a i = i then a i else x + +/-- The indexed operation `dedup x (fun i => run g r (path d r i) x)`. -/ +def expand (r : ℕ) (g : B m → B d → B m) (x : B m) : B ((d + 1) * r) → B m := + dedup x (fun i => run g r (path d r i) x) + +theorem origin : expand r g x 0 = x := by + have hc : code d r (stay d r) = 0 := Equiv.swap_apply_left _ _ + have he : path d r 0 = stay d r := by + rw [← hc] + exact Function.leftInverse_invFun (code d r).injective _ + have hx (n : ℕ) : run g n (stay d n) x = x := by + induction n with + | zero => rfl + | succ _ ih => exact ih + simp only [expand, dedup, he, hx, ite_self] + +theorem mem : (∃ i, expand r g x i = y) ↔ Reach g r x y := by + let a i := run g r (path d r i) x + constructor + · rintro ⟨i, rfl⟩ + unfold expand dedup + split + · exact reach_iff.mpr ⟨_, rfl⟩ + · exact Reach.refl _ _ _ + · intro h + obtain ⟨w, hw⟩ := reach_iff.mp h + let i := code d r w + have hi : a i = y := by + unfold a path i + rw [Function.leftInverse_invFun (code d r).injective] + exact hw + let j := groupFirst a i + have hj : a j = a i := (first_spec a i).1 + have hfix : groupFirst a j = j := le_antisymm ((first_spec a j).2 j rfl) + ((first_spec a i).2 _ ((first_spec a j).1.trans hj)) + exact ⟨j, (ite_eq_left hfix).trans (hj.trans hi)⟩ + +theorem unique {i j : B ((d + 1) * r)} (hi : expand r g x i = y) (hj : expand r g x j = y) + (hy : y ≠ x) : i = j := by + let a i := run g r (path d r i) x + have least (t : B ((d + 1) * r)) (ht : expand r g x t = y) : + a t = y ∧ ∀ v, a v = y → t ≤ v := by + change (if groupFirst a t = t then a t else x) = y at ht + split at ht + next h => exact ⟨ht, fun v hv => h ▸ (first_spec a t).2 v (hv.trans ht.symm)⟩ + next => exact (hy ht.symm).elim + exact le_antisymm ((least i hi).2 j (least j hj).1) ((least j hj).2 i (least i hi).1) + +theorem reciprocal {A D : Format} {a : (Fmt.bank m d A).obj} (ha : Fmt.Reciprocal A a) + (r : ℕ) (b : B m → D.obj) : + Fmt.Reciprocal D (fun i => (expand r (fun j => (a j).1) i, b i)) := by + intro i j h + let g k := (a k).1 + have he : Reach g r i (expand r g i j) := mem.mp ⟨j, rfl⟩ + obtain ⟨l, hl⟩ := mem.mpr (he.symm fun i j h => (ha i j h).exists) + exact ⟨l, hl, fun k hk => unique hk hl (Ne.symm h)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/PayloadProgram.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/PayloadProgram.lean new file mode 100644 index 0000000000..fb880aeec1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/PayloadProgram.lean @@ -0,0 +1,930 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Fragments +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.RetagStore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes + +/-! # Logical fragments at a slot and their packed coordinates -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank + +open Coloring + +variable {A D : Format} (P : Bank A D) {k d p w n : ℕ} + +open scoped Classical in +/-- The indexed operation `Fmt.pi (fun _ : P.Slot => Fragments.Input w p n)`. -/ +abbrev records (w p n : ℕ) := Fmt.pi (fun _ : P.Slot => Fragments.Input w p n) + +open scoped Classical in +/-- Evaluates `Fragments.runs i.1.1.val (P.localWidth k d i) (x i.2.val)` at the input `i`. -/ +def distribute (x : (P.records w p n).obj) : (P.intervals k d (fun _ => n)).obj := + fun i => Fragments.runs i.1.1.val (P.localWidth k d i) (x i.2.val) + +namespace Links +variable {P} (L : P.Links k d) (hd : d ≤ 2 ^ p) (x : (P.records w p n).obj) + +open scoped Classical in +/-- The value specified by `(L.place e).2.castLE hd`. -/ +def portName (e : L.E × Bool) : B p := (L.place e).2.castLE hd + +open scoped Classical in +/-- All lengths and offsets are local to a host. The disjointness +and coverage conditions concern logical packet offsets. -/ +structure Pieces : Prop where + lengths : ∀ s, L.FitsLengths s hd (x s).1 + inside : ∀ s i, let a := (x s).2 i + a.2.1.val + a.2.2.1.val ≤ ((x s).1 a.1).val + apart : ∀ s i j t, ((x s).2 i).1 = ((x s).2 j).1 → + Intervals.covers ((x s).2 i).2 t → Intervals.covers ((x s).2 j).2 t → j = i + live : ∀ (e : L.E × Bool) (t : Fin (L.length e.1)), let s := (L.place e).1 + ∃ i, ((x s).2 i).1 = L.portName hd e ∧ Intervals.covers ((x s).2 i).2 t.val ∧ + ((x s).2 i).2.2.2.val + (t.val - ((x s).2 i).2.1.val) = (L.pointer e.1 e.2 t).val + +open scoped Classical in +/-- The quantity computed by `2 ^ i.1.val * (L.location i e).2.val`. -/ +def base (i : P.Level k d) (e : L.At i × Bool) := 2 ^ i.1.val * (L.location i e).2.val + +open scoped Classical in +/-- The value specified by `(e.1.val, e.2)`. -/ +abbrev pair {i : P.Level k d} (e : L.At i × Bool) : L.E × Bool := (e.1.val, e.2) + +open scoped Classical in +/-- Requires `L.site i.1 e = i.2 ∧ ((x i.2.val).2 a).1 = L.portName hd (L.pair e)`. -/ +def assigned (i : P.Endpoint k d) (a : B n) (e : L.At i.1 × Bool) : Prop := + L.site i.1 e = i.2 ∧ ((x i.2.val).2 a).1 = L.portName hd (L.pair e) + +variable {L hd x} (h : L.Pieces hd x) + +open scoped Classical in +theorem end_lt (L : P.Links k d) (i : P.Level k d) (e : L.At i × Bool) : + L.base i e + L.length e.1.val < 2 ^ (P.depth (L.site i e).val + 1) := by + have hb := L.lane_end i e + have he : L.depth e.1.val = i.1.val := congrArg (fun i : P.Level k d => i.1.val) e.1.2.1 + have hf := L.fits e.1.val + rw [he] at hf + simp only [mul_add, mul_one] at hb + exact lt_of_le_of_lt (Nat.add_le_add_left hf _) hb + +include h in +open scoped Classical in +theorem Pieces.bound {i : P.Endpoint k d} {a : B n} {e : L.At i.1 × Bool} + (he : L.assigned hd x i a e) : + ((x i.2.val).2 a).2.1.val + ((x i.2.val).2 a).2.2.1.val ≤ L.length e.1.val := by + have hu : (L.place (L.pair e)).1 = i.2.val := congrArg Subtype.val he.1 + have hv := (h.lengths _).1 _ hu + have hb := h.inside i.2.val a + change _ ≤ ((x i.2.val).1 ((x i.2.val).2 a).1).val at hb + rw [he.2] at hb + exact hb.trans_eq hv + +include h in +open scoped Classical in +theorem Pieces.shifted {i : P.Endpoint k d} {a : B n} {e : L.At i.1 × Bool} + (he : L.assigned hd x i a e) : + let v := P.distribute x i a + let u := ((x i.2.val).2 a).2 + v.1.val = u.1.val + L.base i.1 e ∧ v.2.1.val = u.2.1.val ∧ + v.2.2.val = u.2.2.val % 2 ^ P.localWidth k d i := by + have hr := L.lanes_correct i.1 e (he.1.symm ▸ h.lengths i.2.val) + rw [he.1] at hr + have hend := L.end_lt i.1 e + rw [he.1] at hend + have hb := h.bound he + change _ < 2 ^ P.localWidth k d i at hend + have h₁ : ((x i.2.val).2 a).2.1.val + L.base i.1 e < 2 ^ P.localWidth k d i := by omega + have h₂ : ((x i.2.val).2 a).2.2.1.val < 2 ^ P.localWidth k d i := by omega + have hv := Fragments.adjust_val i.1.1.val (P.localWidth k d i) (Fragments.items (x i.2.val) a) + have eq : (Fragments.items (x i.2.val) a).1 = PackRank.lanes (x i.2.val).1 (L.portName hd (L.pair + e)) := + congrArg (PackRank.lanes (x i.2.val).1) he.2 + rw [eq] at hv + simp only [portName, pair, hr.1, hr.2, ite_true] at hv + exact ⟨hv.1.trans (Nat.mod_eq_of_lt h₁), hv.2.1.trans (Nat.mod_eq_of_lt h₂), hv.2.2⟩ + +include h in +open scoped Classical in +theorem Pieces.active (i : P.Endpoint k d) (a : B n) (hu : 0 < (P.distribute x i a).2.1.val) : + ∃ e, L.assigned hd x i a e := by + let u := (x i.2.val).2 a + have hv := (Fragments.adjust_val i.1.1.val (P.localWidth k d i) (Fragments.items (x i.2.val) + a)).2.1 + change (P.distribute x i a).2.1.val = + if Nat.clog 2 ((x i.2.val).1 u.1).val = i.1.1.val then u.2.2.1.val % _ else 0 at hv + split at hv + swap + · omega + rename_i hl + have hp : 0 < ((x i.2.val).1 u.1).val := by + have he : u.2.1.val + u.2.2.1.val ≤ ((x i.2.val).1 u.1).val := h.inside _ _ + have hm := Nat.mod_le u.2.2.1.val (2 ^ P.localWidth k d i) + omega + obtain ⟨⟨e, b⟩, hs, ha⟩ := (h.lengths _).2 u.1 hp + have hi := (h.lengths _).1 (e, b) hs + rw [ha] at hi + have he : L.level e = i.1 := by + apply Subtype.ext + apply Fin.ext + change Nat.clog 2 (L.length e) = _ + rwa [hi] at hl + exact ⟨(⟨e, he, hi ▸ hp⟩, b), Subtype.ext hs, ha.symm⟩ + +end Links +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank +end + +/- # The local gather checks from logical packet fragments -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank.Links + +open Coloring + +variable {A D : Format} {P : Bank A D} {k d p w n : ℕ} + {L : P.Links k d} {hd : d ≤ 2 ^ p} {x : (P.records w p n).obj} (h : L.Pieces hd x) + +open scoped Classical in +private def interval (L : P.Links k d) {i : P.Level k d} (e : L.At i × Bool) (t : ℕ) := + L.base i e ≤ t ∧ t < L.base i e + 2 ^ i.1.val + +open scoped Classical in +private theorem lane_eq {q : ℕ} {i : P.Level k d} {a b : L.At i × Bool} + (hs : L.site i a = L.site i b) (ha : L.interval a q) (hb : L.interval b q) : a = b := by + have hf : (L.location i a).1 = (L.location i b).1 := hs + have ht : (L.location i a).2.val = (L.location i b).2.val := by + unfold interval base at ha hb + rcases lt_trichotomy (L.location i a).2.val (L.location i b).2.val with h | h | h + · have := Nat.mul_le_mul_left (2 ^ i.1.val) (Nat.succ_le_of_lt h) + rw [Nat.mul_succ] at this + omega + · exact h + · have := Nat.mul_le_mul_left (2 ^ i.1.val) (Nat.succ_le_of_lt h) + rw [Nat.mul_succ] at this + omega + exact (L.location i).injective (Sigma.ext hf ((Fin.heq_ext_iff (congrArg (P.lanes d _) hf)).mpr + ht)) + +include h in +open scoped Classical in +private theorem Pieces.logical (i : P.Endpoint k d) (a : B n) (t : ℕ) + (hc : Intervals.covers (P.distribute x i a) t) : + ∃ e : L.At i.1 × Bool, L.assigned hd x i a e ∧ L.interval e t ∧ + Intervals.covers ((x i.2.val).2 a).2 (t - L.base i.1 e) := by + unfold Intervals.covers at hc + obtain ⟨e, he⟩ := h.active i a (by omega) + obtain ⟨h₁, h₂, _⟩ := h.shifted he + rw [h₁, h₂] at hc + have hlen : L.length e.1.val ≤ 2 ^ i.1.1.val := by + have he : L.depth e.1.val = i.1.1.val := congrArg (fun j : P.Level k d => j.1.val) e.1.2.1 + rw [← he] + exact L.fits _ + have hb := h.bound he + refine ⟨e, he, ?_, ?_⟩ + · unfold interval; omega + · unfold Intervals.covers; omega + +include h in +open scoped Classical in +theorem Pieces.runs : L.Runs (fun _ => n) (P.distribute x) := by + refine ⟨?_, ?_, ?_, ?_⟩ + · intro i a + cases (Nat.zero_le (P.distribute x i a).2.1.val).eq_or_lt with + | inl hz => rw [← hz, add_zero]; exact (P.distribute x i a).1.isLt + | inr hp => + obtain ⟨e, he⟩ := h.active _ _ hp + obtain ⟨h₁, h₂, _⟩ := h.shifted he + rw [h₁, h₂] + have hlen := L.end_lt i.1 e + rw [he.1] at hlen + have hb := h.bound he + change _ < 2 ^ (P.depth i.2.val + 1) + omega + · intro i a b t ha hb + obtain ⟨e, h₁, h₂, h₃⟩ := h.logical _ _ _ ha + obtain ⟨f, h₄, h₅, h₆⟩ := h.logical _ _ _ hb + have := lane_eq (h₁.1.trans h₄.1.symm) h₂ h₅ + subst f + exact h.apart _ _ _ _ (h₁.2.trans h₄.2.symm) h₃ h₆ + · intro i e b hb + let t := L.vector i e + have he : (L.place (L.pair e)).1 = t.2.val := rfl + obtain ⟨a, h₁, h₂, h₃⟩ := h.live (L.pair e) ⟨b.val, hb⟩ + have ha : L.assigned hd x t a e := ⟨rfl, h₁⟩ + obtain ⟨hs, hl, hpos⟩ := h.shifted ha + have ht : (L.offset i e b).val = b.val + L.base i e := L.offset_val _ _ _ + change Intervals.covers ((x t.2.val).2 a).2 b.val at h₂ + change ((x t.2.val).2 a).2.2.2.val + (b.val - ((x t.2.val).2 a).2.1.val) = + (L.pointer e.1.val e.2 ⟨b.val, hb⟩).val at h₃ + change _ = _ + L.base i e at hs + have hbnd : (L.pointer e.1.val e.2 ⟨b.val, hb⟩).val < 2 ^ P.localWidth k d t := + (L.pointer _ _ _).isLt.trans_le (Nat.pow_le_pow_right (by decide) (Nat.le_succ _)) + rw [Nat.mod_eq_of_lt (show ((x t.2.val).2 a).2.2.2.val + < 2 ^ P.localWidth k d t by omega)] at hpos + refine ⟨a, ?_, ?_⟩ + · change Intervals.covers (P.distribute x t a) _ + unfold Intervals.covers at h₂ ⊢ + rw [hs, hl, ht] + omega + · change (P.distribute x t a).2.2.val + (_ - (P.distribute x t a).1.val) = _ + rw [hpos, ht, hs, Nat.add_sub_add_right] + exact h₃ + · intro i e b hb v hcov + obtain ⟨a, h₁, h₂, h₃⟩ := h.logical _ _ _ hcov + have ht : (L.offset i e b).val = b.val + L.base i e := L.offset_val _ _ _ + have he : L.interval e (L.offset i e b).val := by + unfold interval + have := b.isLt + omega + have eq : a = e := lane_eq h₁.1 h₂ he + subst a + have hu := h.bound h₁ + unfold Intervals.covers at h₃ + change _ ∧ (L.offset i e b).val - L.base i e < _ at h₃ + change _ ≤ L.length e.1.val at hu + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank.Links +end + +/- # Forming short interval descriptions at every eligible level -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank + +open Coloring +variable {A D : Format} (P : Bank A D) (k d w p n : ℕ) + +open scoped Classical in +/-- The indexed operation `Fmt.pi (fun _ : P.Endpoint k d => Fragments.Input w p n)`. -/ +abbrev copies := Fmt.pi (fun _ : P.Endpoint k d => Fragments.Input w p n) +open scoped Classical in +/-- The distribution cost used in the `Bank` construction. -/ +def distributionCost := + 4 * ((P.records w p n).width + 2 * (P.copies k d w p n).width) + + Fintype.card (P.Endpoint k d) * (4 * (2 ^ max p n * (100 + (n + 4 * w + 2 * p + k + 2)) ^ 118)) + +open scoped Classical in +theorem distribute_net {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} + (hu : 3 ≤ u) (hk : ∀ i, P.depth i ≤ k) : + Map F u L (P.records w p n) (P.intervals k d (fun _ => n)) + P.distribute (P.distributionCost k d w p n) := by + let X := P.records w p n + let Y := P.copies k d w p n + let f := fun (x : X.obj) (i : P.Endpoint k d) => x i.2.val + have hc : Circuit F X Y f (X.width + 2 * Y.width) := + Circuit.project (fun v => ⟨v.1.2.val, v.2⟩) fun _ _ => rfl + let b := n + 4 * w + 2 * p + k + 2 + have hd (i : P.Endpoint k d) : Map F u L (Fragments.Input w p n) (.vec n (Intervals.span + (P.localWidth k d i))) + (Fragments.runs i.1.1.val (P.localWidth k d i)) (4 * (2 ^ max p n * (100 + b) ^ 118)) := by + obtain ⟨s, hs, ht⟩ := Fragments.cheap F (p := p) (n := n) (w := w) (b := b) i.1.1.val + (P.localWidth k d i) (by unfold b; have := i.1.1.isLt; omega) + (by unfold b localWidth; have := hk i.2.val; omega) + exact (Map.circuit hu hs).mono (by omega) + have he := ((Map.circuit (L := L) hu hc).comp (Map.family hd)) + simp only [Finset.sum_const, Finset.card_univ, Nat.nsmul_eq_mul] at he + exact he + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank +end + +/- The commands generated by the logical host layout agree with the physical plan. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout +open Coloring + +variable {m m' V V' k k' d p w : ℕ} {x : Payload m V k} {y : Payload m' V' k'} + {L : Payload.Traffic x y d} {hd : d ≤ 2 ^ p} {v : (input m m' p w).obj} + +local notation "bank" => P m V k m' V' k' +local notation "H" => host m V k m' V' k' +local notation "n" => max m m' +local notation "b" => bits k k' + +open scoped Classical in +theorem Fits.left (h : Fits L hd v) (a : B m) : + L.links.FitsLengths (.inl (x.seat.write a)) hd (v.1.1.2 a) := by + constructor + · rintro ⟨e, _ | _⟩ he + · have ha := x.seat.injective (Sum.inl.inj he) + change (L.src e).1 = a at ha + subst a + exact h.send e + · exact (Sum.inr_ne_inl he).elim + · intro j hj + obtain ⟨e, he, he'⟩ := h.all_send a j hj + exact ⟨(e, false), congrArg (fun a => Sum.inl (x.seat.write a)) he, he'⟩ + +open scoped Classical in +theorem Fits.right (h : Fits L hd v) (a : B m') : + L.links.FitsLengths (.inr (y.seat.write a)) hd (v.1.2.2 a) := by + constructor + · rintro ⟨e, _ | _⟩ he + · exact (Sum.inl_ne_inr he).elim + · have ha := y.seat.injective (Sum.inr.inj he) + change (L.dst e).1 = a at ha + subst a + exact h.receive e + · intro j hj + obtain ⟨e, he, he'⟩ := h.all_receive a j hj + exact ⟨(e, true), congrArg (fun a => Sum.inr (y.seat.write a)) he, he'⟩ + +variable (i : (P m V k m' V' k').Level (max k k') d) + +open scoped Classical in +theorem Fits.source (h : Fits L hd v) (e : L.links.At i) : + address n b false v.1.1 (post hd (L.src e.val)) = + (bank).codePort i H hd (L.links.location i (e, false)) := by + rw [L.links.codePort_of_fits i H hd (e, false) _ (h.left (L.src e.val).1)] + simp only [address, post, Equiv.apply_symm_apply, assigned_slot _ _ _ _ _ h.from_size] + rfl + +open scoped Classical in +theorem Fits.destination (h : Fits L hd v) (e : L.links.At i) : + address n b true v.1.2 (post hd (L.dst e.val)) = + (bank).codePort i H hd (L.links.location i (e, true)) := by + rw [L.links.codePort_of_fits i H hd (e, true) _ (h.right (L.dst e.val).1)] + simp only [address, post, Equiv.apply_symm_apply, assigned_slot _ _ _ _ _ h.to_size] + rfl + +open scoped Classical in +theorem Fits.active (h : Fits L hd v) (a : B (m + p)) : + PeerLayout.active i.1.val v.1.1 a = true ↔ ∃ e : L.links.At i, post hd (L.src e.val) = a := by + simp only [PeerLayout.active, enabled, decide_eq_true_eq] + constructor + · rintro ⟨hp, he⟩ + obtain ⟨e, he₁, he₂⟩ := h.all_send _ _ hp + have eq : post hd (L.src e) = a := (Match.rowIndex m p).symm_apply_eq.mpr (Prod.ext he₁ he₂) + rw [← he₁, ← he₂, h.send] at hp he + exact ⟨⟨e, Subtype.ext (Fin.ext he), hp⟩, eq⟩ + · rintro ⟨e, rfl⟩ + simp only [post, Equiv.apply_symm_apply] + rw [h.send e.val] + exact ⟨e.2.2, congrArg (fun i : (bank).Level (max k k') d => i.1.val) e.2.1⟩ + +open scoped Classical in +private theorem Fits.rows_at (h : Fits L hd v) (e : L.links.At i) (z : B 1) : + rows n b i.1.val v ((Match.rowIndex (m + p) 1).symm (post hd (L.src e.val), z)) = + L.links.descriptor i H hd (e, decide (z ≠ 0)) := by + have ha := (h.active i _).mpr ⟨e, rfl⟩ + simp only [rows, Equiv.apply_symm_apply, ha, h.peer e.val e.2.2, h.source i e, h.destination i e] + by_cases hz : z = 0 <;> simp [hz, Bank.Links.descriptor, Bank.Links.opposite] + +open scoped Classical in +theorem Fits.correct (h : Fits L hd v) : control hd v = L.links.plan.control.2.1 := by + funext i + apply L.links.decoded + · intro j hj + let u := Match.rowIndex (m + p) 1 j + obtain ⟨e, he⟩ := (h.active i u.1).mp hj + have eq : (Match.rowIndex (m + p) 1).symm (post hd (L.src e.val), u.2) = j := + (Match.rowIndex (m + p) 1).symm_apply_eq.mpr (Prod.ext he rfl) + exact ⟨(e, decide (u.2 ≠ 0)), eq ▸ h.rows_at i e u.2⟩ + · rintro ⟨e, _|_⟩ + · exact ⟨_, h.rows_at i e 0⟩ + · exact ⟨_, h.rows_at i e 1⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout +end + +/- +# Packing transfer metadata from logical hosts + +Each record travels with its host's extent. Empty physical slots +receive zero lengths and empty fragments. The original peer grid +is available unchanged after packing. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload +open Coloring Transcript + +/-- The script used in the `Payload` construction. -/ +abbrev Script (m m' p w n : ℕ) := + Format.pair (PeerLayout.input m m' p w) + (.pair (.vec m (.vec n (Fragments.Entry w p))) (.vec m' (.vec n (Fragments.Entry w p)))) + +namespace Script +variable {m V k m' V' k' d p w n : ℕ} + +/-- Computes the item by the application `Format.pair (Fragments.Input w p n) (.addr w)`. -/ +abbrev item (w p n : ℕ) := Format.pair (Fragments.Input w p n) (.addr w) +/-- Computes the out by the application `Format.pair ((payloadBank m V k m' V' k').records w p +n) (.pair (PeerLayout.input m m' p w) (Lengths m' V' k'))`. -/ +abbrev Out (m V k m' V' k' p w n : ℕ) := + Format.pair ((payloadBank m V k m' V' k').records w p n) + (.pair (PeerLayout.input m m' p w) (Lengths m' V' k')) + +/-- The indexed operation `(fun _ => 0, fun _ => (0, 0, 0, 0))`. -/ +def empty (w p n : ℕ) : (Fragments.Input w p n).obj := + (fun _ => 0, fun _ => (0, 0, 0, 0)) + +/-- The value specified by `(empty w p n, 0)`. -/ +def pad (w p n : ℕ) : (item w p n).obj := (empty w p n, 0) + +/-- The indexed operation `(v.1.1.1.1, fun i => ((v.1.1.1.2 i, v.2.1 i), v.1.1.1.1 i))`. -/ +def left (v : (Script m m' p w n).obj) : (Redistribute.input m w (item w p n)).obj := + (v.1.1.1.1, fun i => ((v.1.1.1.2 i, v.2.1 i), v.1.1.1.1 i)) + +/-- The indexed operation `(v.1.1.2.1, fun i => ((v.1.1.2.2 i, v.2.2 i), v.1.1.2.1 i))`. -/ +def right (v : (Script m m' p w n).obj) : (Redistribute.input m' w (item w p n)).obj := + (v.1.1.2.1, fun i => ((v.1.1.2.2 i, v.2.2 i), v.1.1.2.1 i)) + +/-- The pack of type `(Out m V k m' V' k' p w n).obj`, constructed using `Redistribute.eval (V +:= V) (k := k) _ (pad w p n) (left v)`. -/ +def pack (v : (Script m m' p w n).obj) : (Out m V k m' V' k' p w n).obj := + let l := Redistribute.eval (V := V) (k := k) _ (pad w p n) (left v) + let r := Redistribute.eval (V := V') (k := k') _ (pad w p n) (right v) + (Sum.elim (fun i => (l i).1) (fun i => (r i).1), v.1, fun i => Intervals.shrink (k' + 1) (r i).2) + +variable {x : Payload m V k} {y : Payload m' V' k'} {M : Traffic x y d} + {hd : d ≤ 2 ^ p} {v : (Script m m' p w n).obj} (h : PeerLayout.Fits M hd v.1) + +local notation "packed" => pack (V := V) (k := k) (V' := V') (k' := k') v + +include h + +theorem source (i : B m) : (packed).1 (.inl (x.seat.write i)) = (v.1.1.1.2 i, v.2.1 i) := by + have he := congrFun (Redistribute.correct x _ (pad w p n) (left v) h.from_size) (x.seat.write i) + rw [(x.seat.valid _ _).mpr rfl] at he + exact congrArg Prod.fst he + +theorem destination (i : B m') : (packed).1 (.inr (y.seat.write i)) = (v.1.1.2.2 i, v.2.2 i) := by + have he := congrFun (Redistribute.correct y _ (pad w p n) (right v) h.to_size) (y.seat.write i) + rw [(y.seat.valid _ _).mpr rfl] at he + exact congrArg Prod.fst he + +theorem empty_source (s : Slot (2 ^ m) V k) (hs : x.seat.read s = none) : + (packed).1 (.inl s) = empty w p n := by + have he := congrFun (Redistribute.correct x _ (pad w p n) (left v) h.from_size) s + rw [hs] at he + exact congrArg Prod.fst he + +theorem empty_destination (s : Slot (2 ^ m') V' k') (hs : y.seat.read s = none) : + (packed).1 (.inr s) = empty w p n := by + have he := congrFun (Redistribute.correct y _ (pad w p n) (right v) h.to_size) s + rw [hs] at he + exact congrArg Prod.fst he + +theorem lengths : (packed).2.2 = y.lengths := by + funext s + have he := congrFun (Redistribute.correct y _ (pad w p n) (right v) h.to_size) s + apply Fin.ext + change (Redistribute.eval _ (pad w p n) (right v) s).2.val % 2 ^ (k' + 1) = y.used s + rw [he, used] + cases hr : y.seat.read s with + | none => simp [pad] + | some i => + change (v.1.1.2.1 i).val % 2 ^ (k' + 1) = y.length i + rw [h.to_size, Nat.mod_eq_of_lt ((y.longest i).trans_lt (Nat.pow_lt_pow_right (by decide) (by + omega)))] + +theorem fits (s : (payloadBank m V k m' V' k').Slot) : + M.links.FitsLengths s hd ((packed).1 s).1 := by + have absent (s : (payloadBank m V k m' V' k').Slot) + (ha : ∀ a, (M.links.place a).1 ≠ s) : M.links.FitsLengths s hd (empty w p n).1 := + ⟨fun a h => (ha a h).elim, fun _ h => (Nat.lt_irrefl _ h).elim⟩ + rcases s with s|s + · cases he : x.seat.read s with + | some i => rw [(x.seat.valid _ _).mp he, source h i]; exact h.left i + | none => + rw [empty_source h s he] + apply absent + rintro ⟨e, _|_⟩ he' + · have hh := (x.seat.valid s (M.src e).1).mpr (Sum.inl.inj he').symm + rw [he] at hh + contradiction + · exact Sum.inr_ne_inl he' + · cases he : y.seat.read s with + | some i => rw [(y.seat.valid _ _).mp he, destination h i]; exact h.right i + | none => + rw [empty_destination h s he] + apply absent + rintro ⟨e, _|_⟩ he' + · exact Sum.inl_ne_inr he' + · have hh := (y.seat.valid s (M.dst e).1).mpr (Sum.inr.inj he').symm + rw [he] at hh + contradiction + +end Script +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload +end + +/- Form both directions of each active peer descriptor. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout +open Coloring +variable (F : Type) [Field F] {m m' a b p w n t : ℕ} + +theorem input_bound (hm : m + p ≤ n) (hm' : m' + p ≤ n) (hw : w ≤ t) (hn : n ≤ t) : + (input m m' p w).width ≤ 2 ^ n * (100 + t) ^ 3 := by + let C := 2 ^ n * (100 + t) ^ 2 + have h (k : ℕ) (hk : k + p ≤ n) : (lengths k p w).width ≤ C := + (lengths_bound hw).trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) hk)) + have h₁ : (Column (m + p) (m' + p)).width ≤ C := + (Peers.bound_vec _ (by simpa using hm'.trans hn) hm).trans (Nat.mul_le_mul_left _ + (Nat.pow_le_pow_right (by omega) (by decide))) + have h₂ : C * 3 ≤ 2 ^ n * (100 + t) ^ 3 := calc + _ ≤ C * (100 + t) := Nat.mul_le_mul_left _ (by omega) + _ = _ := by unfold C; rw [mul_assoc, ← pow_succ] + unfold input + rw [Format.width_pair, Format.width_pair] + exact (Nat.add_le_add (Nat.add_le_add (h m hm) (h m' hm')) h₁).trans (by omega) + +private def turn {R : Format} (side : B 1) (x : (Peers.desc R).obj) : (Peers.desc R).obj := + (x.1, if side = 0 then x.2 else (x.2.2, x.2.1)) + +private theorem cheap_turn (R : Format) (side : B 1) (hr : (Peers.desc R).width ≤ t) : + Cheap F 0 t (Peers.desc R) (Peers.desc R) (turn side) 6 := by + have x := Cheap.id F (show (Peers.desc R).width ≤ 2 ^ 0 * (100 + + t) ^ 1 by simp only [pow_zero, pow_one, one_mul]; omega) + by_cases h : side = 0 + · rw [show turn (R := R) side = id by funext x; simp [turn, h]] + exact x.mono (by decide) + · rw [show turn (R := R) side = fun x => (x.1, (x.2.2, x.2.1)) by funext x; simp [turn, h]] + exact x.fst.pair (x.snd.snd.pair x.snd.fst) + +private def straight (a b l : ℕ) (x : (input m m' p w).obj) (i : B (m + p)) : + (Peers.desc (keyFmt a b p)).obj := + (active l x.1.1 i, address a b false x.1.1 i, address a b true x.1.2 (x.2 i)) + +private theorem cheap_straight (hm : m + p ≤ n) (hm' : m' + p ≤ n) + (h : n + w + a + b + 1 ≤ t) (ht : (Peers.desc (keyFmt a b p)).width ≤ t) (l : ℕ) : + Cheap F n t (input m m' p w) (.vec (m + p) (Peers.desc (keyFmt a b p))) (straight a b l) 130 + := by + have hw : w ≤ t := by omega + have hn : n ≤ t := by omega + let K := keyFmt a b p + have hK : K.width ≤ t := by + change (Peers.desc K).width ≤ t at ht + simp only [Peers.desc, Format.width_pair] at ht + omega + have x := Cheap.id F (input_bound hm hm' hw hn) + have old := x.fst.fst + have flag := old.comp (Peers.lift F (cheap_active F l hw (m := m) (p := p)) hm) + have a₁ := cheap_address F false (show m + p + w + a + b + 1 ≤ t by omega) + have a₂ := cheap_address F true (show m' + p + w + a + b + 1 ≤ t by omega) + have src := old.comp (Peers.lift F a₁ hm) + have dst := x.fst.snd.comp (Peers.lift F a₂ hm') + have remote := (dst.pair x.snd).comp (Peers.read F K hK hm' hm hn) + have hay : Format.bit.width + (Format.pair K K).width ≤ (100 + t) ^ 2 := + (by rw [← Format.width_pair]; exact ht.trans (by ring_nf; omega)) + have hk' : K.width + K.width ≤ (100 + t) ^ 2 := by rw [Format.width_pair] at hay; omega + have pair := (src.pair remote).comp (Peers.zipper F _ hm K K hk') + have res := (flag.pair pair).comp (Peers.zipper F _ hm .bit (.pair K K) hay) + exact res.mono (by decide) + +theorem cheap_rows (hm : m + p + 1 ≤ n) (hm' : m' + p ≤ n) + (h : n + w + a + b + 1 ≤ t) (ht : (Peers.desc (keyFmt a b p)).width ≤ t) (l : ℕ) : + Cheap F n t (input m m' p w) (.vec (m + p + 1) (Peers.desc (keyFmt a b p))) (rows a b l) 132 + := by + have hh : m + p ≤ n := by omega + have prep := cheap_straight F hh hm' h ht l + let z := Match.rowIndex (m + p) 1 + have spread := Peers.reindex F (Peers.desc (keyFmt a b p)) ht hh hm (fun i => (z i).1) + have tw := Cheap.map _ (fun i : B (m + p + 1) => cheap_turn F (keyFmt a b p) (z i).2 ht) + have finish := Peers.lift F tw hm + have done := (prep.comp spread).comp finish + exact done.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout +end + +/- +# Global peer commands from host extents and contact lengths + +The two host banks can have different sizes. The table height uses +only the logarithm of the number of dyadic levels. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout + +open Coloring +variable {m V k m' V' k' d p w : ℕ} + +open scoped Classical in +/-- The maximum of the quantities in `m m' + bits k k' + p + 2`. -/ +def height (m k m' k' p : ℕ) := max m m' + bits k k' + p + 2 +open scoped Classical in +/-- The construction uses `height m k m' k' p` for its intermediate `n`. -/ +def size (m k m' k' p w : ℕ) := + let n := height m k m' k' p + 16 * (max k k' + 2) * (2 ^ n * (101 + 5 * n + w) ^ 134) + +open scoped Classical in +theorem count_bound (hd : d ≤ 2 ^ p) (i : (P m V k m' V' k').Level (max k k') d) : + (P m V k m' V' k').count _ d i ≤ height m k m' k' p := by + let K := keyFmt (max m m') (bits k k') p + let e := ((P m V k m' V' k').codePort i (host _ _ _ _ _ _) hd).trans K.serial.toEmbedding + have h := Fintype.card_le_of_injective e e.injective + rw [Fintype.card_fin] at h + have he : height m k m' k' p = K.width + 1 := by + simp [K, height, keyFmt, Bank.pairCode, hostFmt]; omega + unfold Bank.count + apply Nat.clog_le_of_le_pow + rw [he, pow_succ] + have := Nat.two_pow_pos K.width + omega + +open scoped Classical in +private theorem level_cost (F : Type) [Field F] (hd : d ≤ 2 ^ p) + (i : (P m V k m' V' k').Level (max k k') d) : + let n := height m k m' k' p + Cheap F n (1 + 5 * n + w) (input m m' p w) (Perm ((P m V k m' V' k').count _ d i)) + (fun x => control (V := V) (k := k) (V' := V') (k' := k') hd x i) 134 := by + intro n + let t := 1 + 5 * n + w + let K := keyFmt (max m m') (bits k k') p + let q := (P m V k m' V' k').count _ d i + have hK : K.width ≤ n := by simp [K, keyFmt, Bank.pairCode, hostFmt, n, height]; omega + have hq : q ≤ n := count_bound hd i + have h₁ : m + p + 1 ≤ n := by unfold n height; omega + have h₂ : m' + p ≤ n := by unfold n height; omega + have h₃ : n + w + max m m' + bits k k' + 1 ≤ t := by unfold t n height; omega + have h₄ : (Peers.desc K).width ≤ t := by + simp only [Peers.desc, Format.width_pair] + change 1 + (K.width + K.width) ≤ _ + omega + have gen := cheap_rows F h₁ h₂ h₃ h₄ i.1.val + have hn : Peers.height (m + p + 1) q K ≤ n := max_le h₁ (max_le hq hK) + have ht : Peers.width (m + p + 1) q K ≤ t := by unfold Peers.width; omega + let tab := (P m V k m' V' k').portTable i (host _ _ _ _ _ _) hd + have dec := (Peers.lift F (Peers.cheap_decode F (m + p + 1) K tab) hn).widen ht + exact (gen.comp dec).mono (by decide) + +open scoped Classical in +private theorem broadcast {F I : Type} [Field F] [Fintype I] {u : ℕ} {L : Set (Table F)} + (hu : 3 ≤ u) (A : Format) (X : I → Format) (f : A.obj → (Fmt.pi X).obj) (J C : ℕ) + (hI : Fintype.card I ≤ J + 1) (hA : A.width ≤ C) + (hslot : ∀ i : I, Map F u L A (X i) (fun x => f x i) (4 * C)) : + Map F u L A (Fmt.pi X) f (16 * (J + 2) * C) := by + let R := Fmt.pi (fun _ : I => A) + have hc := Map.family hslot + have copy : Circuit F A R (fun x _ => x) (A.width + 2 * R.width) := + Circuit.project (A := A) (D := R) (fun v => v.2) (fun _ _ => rfl) + have h := ((Map.circuit (L := L) hu copy).comp hc) + have hR : R.width ≤ (J + 1) * C := by + simp only [R, Fmt.width_pi, Finset.sum_const, Finset.card_univ, smul_eq_mul] + exact Nat.mul_le_mul hI hA + refine h.mono ?_ + simp only [Finset.sum_const, Finset.card_univ, smul_eq_mul] + linarith only [hR, hA, Nat.mul_le_mul_right C hI, Nat.zero_le (J * C), Nat.zero_le C] + +open scoped Classical in +theorem realize {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) (hd : d ≤ 2 ^ p) : + Map F u L (input m m' p w) (S m V k m' V' k' d).peers (control hd) (size m k m' k' p w) := by + let n := height m k m' k' p + let t := 1 + 5 * n + w + let C := 2 ^ n * (100 + t) ^ 134 + let A := input m m' p w + let Z := S m V k m' V' k' d + let I := Z.Levels + have hslot (i : I) : Map F u L A (Perm (Z.count i)) + (fun x => control (V := V) (k := k) (V' := V') (k' := k') hd x i) (4 * C) := by + obtain ⟨r, hr, hb⟩ := level_cost F hd i (w := w) + change _ + _ + r ≤ C at hb + have H := Map.circuit (L := L) hu hr + have ht : r ≤ C := (Nat.le_add_left _ _).trans hb + exact H.mono (Nat.mul_le_mul_left 4 ht) + have hI : Fintype.card I ≤ max k k' + 1 := by + let f : Z.Levels → Fin (max k k' + 1) := fun i => i.1 + have hf : Function.Injective f := Subtype.val_injective + simpa only [Fintype.card_fin] using Fintype.card_le_of_injective f hf + have hA : A.width ≤ C := by + unfold A C + refine (input_bound (n := n) (t := t) (by unfold n height; omega) + (by unfold n height; omega) (by unfold t; omega) (by unfold t; omega)).trans ?_ + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) (by decide)) + have he : size m k m' k' p w = 16 * (max k k' + 2) * C := by + unfold size + dsimp only + rw [show 101 + 5 * height m k m' k' p + w = 100 + t by unfold t n; omega] + rw [he] + have done := broadcast (F := F) (L := L) hu A (fun i : I => Perm (Z.count i)) + (control (m := m) (m' := m') (V := V) (k := k) (V' := V') (k' := k') (w + := w) hd) (max k k') C hI hA hslot + dsimp only [I, Z, A] at done + unfold Channels.peers + exact done + +open scoped Classical in +/-- Polynomial overhead above the number of padded contacts. -/ +theorem size_le {t : ℕ} (hm : max m m' ≤ t) (hk : max k k' ≤ t) + (hp : p ≤ t) (hw : w ≤ t) : + size m k m' k' p w ≤ 2 ^ (max m m' + p) * (100 + t) ^ 274 := by + let n := height m k m' k' p + let a := 100 + t + have hb : 2 ^ bits k k' ≤ 2 * (max k k' + 1) := Transcript.pow_clog_le_twice (by omega) + have hc := Nat.lt_two_pow_self (n := bits k k') + have hn : n ≤ 4 * t + 4 := by unfold n height; omega + have hu : 101 + 5 * n + w ≤ a ^ 2 := by unfold a; ring_nf; omega + have hv : 16 * (max k k' + 2) ≤ a ^ 2 := by unfold a; ring_nf; omega + have ha : 2 ^ (bits k k' + 2) ≤ a ^ 4 := by + have hh : 2 ^ bits k k' * 4 ≤ a ^ 2 := by unfold a; ring_nf; omega + rw [pow_add] + exact hh.trans (Nat.pow_le_pow_right (by omega) (by decide)) + have he : 2 ^ n = 2 ^ (max m m' + p) * 2 ^ (bits k k' + 2) := by + rw [← pow_add]; congr 1; unfold n height; omega + change 16 * (max k k' + 2) * (2 ^ n * (101 + 5 * n + w) ^ 134) ≤ _ + rw [he] + calc + _ ≤ a ^ 2 * ((2 ^ (max m m' + p) * a ^ 4) * (a ^ 2) ^ 134) := + Nat.mul_le_mul hv (Nat.mul_le_mul (Nat.mul_le_mul_left _ ha) (Nat.pow_le_pow_left hu 134)) + _ = _ := by rw [← pow_mul, mul_assoc _ (a ^ 4), mul_left_comm, ← pow_add, ← pow_add] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.PeerLayout +end + +/- +# Compiling a payload transfer + +The global list has one entry per contact. Locally the address +stream is supplied as disjoint intervals, without a global +address for each transmitted bit. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload.Script + +open Coloring PeerLayout +variable {m V k m' V' k' d p w n : ℕ} (hd : d ≤ 2 ^ p) + +open scoped Classical in +/-- Computes the prepare by the application `Prod.map (P m V k m' V' k').distribute (Prod.map +(PeerLayout.control hd) mask)`. -/ +def prepare : (Out m V k m' V' k' p w n).obj → + ((S m V k m' V' k' d).shortControl (fun _ => n)).obj := + Prod.map (P m V k m' V' k').distribute (Prod.map (PeerLayout.control hd) mask) + +open scoped Classical in +/-- The indexed operation `(S m V k m' V' k' d).expandControl (fun _ => n) (fun _ => id) ((P m V +k m' V' k').sentinel (max k k') d) ∘ prepare hd`. -/ +def command : (Out m V k m' V' k' p w n).obj → (S m V k m' V' k' d).control.obj := + (S m V k m' V' k' d).expandControl (fun _ => n) (fun _ => id) + ((P m V k m' V' k').sentinel (max k k') d) ∘ prepare hd + +open scoped Classical in +/-- The bound obtained by adding the component charges `(P m V k m' V' k').distributionCost (max +k k') d w p n + (PeerLayout.size m k m' k' p w + 8000 * (k' + 2) * (Fmt.payload m' V' +k').width)`. -/ +def setupCost (m V k m' V' k' d p w n : ℕ) := + (P m V k m' V' k').distributionCost (max k k') d w p n + + (PeerLayout.size m k m' k' p w + 8000 * (k' + 2) * (Fmt.payload m' V' k').width) + +open scoped Classical in +/-- The quantity computed by `setupCost m V k m' V' k' d p w n + (S m V k m' V' k' d).expandCost +(fun _ => n)`. -/ +def commandCost (m V k m' V' k' d p w n : ℕ) := + setupCost m V k m' V' k' d p w n + (S m V k m' V' k' d).expandCost (fun _ => n) + +open scoped Classical in +private theorem setup_net {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) : + Map F u L (Out m V k m' V' k' p w n) ((S m V k m' V' k' d).shortControl (fun _ => n)) + (prepare hd) (setupCost m V k m' V' k' d p w n) := by + let b := P m V k m' V' k' + have hk (i : b.Slot) : b.depth i ≤ max k k' := by + rcases i with i | i + · exact (Nat.lt_succ_iff.mp i.1.isLt).trans (le_max_left _ _) + · exact (Nat.lt_succ_iff.mp i.1.isLt).trans (le_max_right _ _) + have ha := b.distribute_net (max k k') d w p n (F := F) (L := L) hu hk + have hp := PeerLayout.realize (F := F) (L := L) (m := m) (m' := m') (V := V) (V' := V') + (k := k) (k' := k') (w := w) hu hd + have hm := mask_net (F := F) (L := L) (m := m') (V := V') (k := k') hu + have h := ha.par (hp.par hm) + intro a b i j + exact h a b i j + +open scoped Classical in +theorem command_net {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) : + Map F u L (Out m V k m' V' k' p w n) (S m V k m' V' k' d).control + (command hd) (commandCost m V k m' V' k' d p w n) := by + have h := setup_net (m := m) (m' := m') (V := V) (V' := V') (k := k) (k' := k') + (w := w) (n := n) hd (F := F) (L := L) hu + have he := (S m V k m' V' k' d).expand_control (fun _ => n) (F := F) (L := L) hu + (fun _ => id) ((P m V k m' V' k').sentinel (max k k') d) + exact h.comp he + +variable {x : Payload m V k} {y : Payload m' V' k'} (M : Traffic x y d) + +open scoped Classical in +theorem represents {q : (Script m m' p w n).obj} (hq : PeerLayout.Fits M hd q.1) + (h : M.links.Pieces hd (pack q).1) : M.links.Represents (command hd (pack q)) := by + have hm : mask (pack (V := V) (k := k) (V' := V') (k' := k') q).2.2 = M.links.pad := by + rw [Script.lengths hq] + exact funext y.mask_eq + have he : prepare hd (pack q) = ((P m V k m' V' k').distribute (pack q).1, + M.links.plan.control.2) := + Prod.ext rfl (Prod.ext hq.correct hm) + rw [command, Function.comp_apply, he] + exact Bank.Links.Runs.represents (fun _ => n) M.links _ h.runs + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload.Script +end + +/- Two independent host redistributions and fixed reindexings of the metadata. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload.Script +open Coloring Transcript + +/-- Computes the first by the application `Format.pair (.pair (Redistribute.input m w (item w p +n)) (Redistribute.input m' w (item w p n))) (PeerLayout.input m m' p w)`. -/ +abbrev first (m m' p w n : ℕ) := + Format.pair (.pair (Redistribute.input m w (item w p n)) (Redistribute.input m' w (item w p n))) + (PeerLayout.input m m' p w) + +/-- The moved used in the `Script` construction. -/ +abbrev moved (m V k m' V' k' p w n : ℕ) := + Format.pair (.pair (Redistribute.output m V k (item w p n)) (Redistribute.output m' V' k' (item w + p n))) + (PeerLayout.input m m' p w) + +/-- The staged used in the `Script` construction. -/ +abbrev staged (m V k m' V' k' p w n : ℕ) := + Format.pair ((payloadBank m V k m' V' k').records w p n) + (.pair (PeerLayout.input m m' p w) (Fmt.pi (fun _ : Slot (2 ^ m') V' k' => .addr w))) + +variable {F : Type} [Field F] {m V k m' V' k' p w n : ℕ} + +private def firstPin : (first m m' p w n).pins → (Script m m' p w n).pins + | .inr j => .inl j + | .inl (.inl (.inl j)) => .inl (.inl (.inl (.inl j))) + | .inl (.inl (.inr (i, .inl (.inl j)))) => .inl (.inl (.inl (.inr (i, j)))) + | .inl (.inl (.inr (i, .inl (.inr j)))) => .inr (.inl (i, j)) + | .inl (.inl (.inr (i, .inr j))) => .inl (.inl (.inl (.inl (i, j)))) + | .inl (.inr (.inl j)) => .inl (.inl (.inr (.inl j))) + | .inl (.inr (.inr (i, .inl (.inl j)))) => .inl (.inl (.inr (.inr (i, j)))) + | .inl (.inr (.inr (i, .inl (.inr j)))) => .inr (.inr (i, j)) + | .inl (.inr (.inr (i, .inr j))) => .inl (.inl (.inr (.inl (i, j)))) + +private theorem first_net : + Circuit F (Script m m' p w n) (first m m' p w n) (fun x => ((left x, right x), x.1)) + ((Script m m' p w n).width + 2 * (first m m' p w n).width) := by + apply Circuit.project firstPin + rintro x (((j | ⟨i, (t|t)|t⟩) | (j | ⟨i, (t|t)|t⟩)) | j) <;> rfl + +private def stage (x : (moved m V k m' V' k' p w n).obj) : + (staged m V k m' V' k' p w n).obj := + (Sum.elim (fun i => (x.1.1 i).1) (fun i => (x.1.2 i).1), x.2, fun i => (x.1.2 i).2) + +private def stagePin : (staged m V k m' V' k' p w n).pins → (moved m V k m' V' k' p w n).pins + | .inl ⟨.inl s, j⟩ => .inl (.inl ⟨s, .inl j⟩) + | .inl ⟨.inr s, j⟩ => .inl (.inr ⟨s, .inl j⟩) + | .inr (.inl j) => .inr j + | .inr (.inr ⟨s, j⟩) => .inl (.inr ⟨s, .inr j⟩) + +private theorem stage_net : + Circuit F (moved m V k m' V' k' p w n) (staged m V k m' V' k' p w n) stage + ((moved m V k m' V' k' p w n).width + 2 * (staged m V k m' V' k' p w n).width) := by + apply Circuit.project stagePin + rintro x (⟨s|s, j⟩|j|⟨s, j⟩) <;> rfl + +variable {u v c c' : ℕ} {L : Set (Table F)} + +/-- The raw cost used in the `Script` construction. -/ +def rawCost (m V k m' V' k' p w n v c c' : ℕ) := + 4 * ((Script m m' p w n).width + 2 * (first m m' p w n).width) + + (Redistribute.cost m k w v c + Redistribute.cost m' k' w v c' + + 4 * (PeerLayout.input m m' p w).width) + + 4 * ((moved m V k m' V' k' p w n).width + 2 * (staged m V k m' V' k' p w n).width) + + (4 * ((payloadBank m V k m' V' k').records w p n).width + + (4 * (PeerLayout.input m m' p w).width + Fintype.card (Slot (2 ^ m') V' k') * (4 * (100 + (w + + k' + 1)) ^ 2))) + +theorem build (hu : 3 ≤ u) (ht : Radix.Tag F m v c) (ht' : Radix.Tag F m' v c') + (ha : (item w p n).width ≤ v) : + Map F u L (Script m m' p w n) (Out m V k m' V' k' p w n) pack (rawCost m V k m' V' k' p w n v c + c') := by + let mid := PeerLayout.input m m' p w + have peer := Map.circuit (L := L) hu (Circuit.id F mid) + have entries := Map.circuit (L := L) hu (Circuit.id F ((payloadBank m V k m' V' k').records w p + n)) + obtain ⟨r, hr, hb⟩ := Intervals.cheap_shrink F (show w ≤ w + k' + + 1 by omega) (show k' + 1 ≤ w + k' + 1 by omega) + have hs := (Map.circuit (L := L) hu hr).mono (n := 4 * (100 + (w + k' + 1)) ^ 2) (by omega) + have hall := Map.family (fun _ : Slot (2 ^ m') V' k' => hs) + simp only [Finset.sum_const, Finset.card_univ, smul_eq_mul] at hall + have r₁ := Redistribute.realize (L := L) (V := V) (k := k) (w := w) hu ht _ ha (pad w p n) + have r₂ := Redistribute.realize (L := L) (V := V') (k := k') (w := w) hu ht' _ ha (pad w p n) + have pre := Map.circuit (L := L) hu (first_net (F := F) (m := m) (m' := m') (p := p) (w := w) (n + := n)) + have rows := pre.comp ((r₁.par r₂).par peer) + have after := rows.comp (Map.circuit hu stage_net) + have result := after.comp (entries.par (peer.par hall)) + exact result + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload.Script +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare.lean new file mode 100644 index 0000000000..dd3a97f8d8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare.lean @@ -0,0 +1,963 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Rate.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanTiles +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanSupplies +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Shipment.Bound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Status +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access + +/-! +# Payload orders for a child host + +Within a contact the old block and span number give a common +pairing key. Each side also displays its own spans in the physical +order of that side's payload bank. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring Packing BatchDescent + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) +local notation "S" => D.scheme +local notation "U" => b.target + +open scoped Classical in +/-- The quantity computed by `(D.scheme.h - a) + 1`. -/ +abbrev suffixBits (_ : D.Binning a H T R θ) := (D.scheme.h - a) + 1 +open scoped Classical in +/-- The quantity computed by `V.h + (V.k + V.e)`. -/ +abbrev rowBits (V : Scheme F) := V.h + (V.k + V.e) +open scoped Classical in +/-- The maximum of the quantities in `(rowBits S) (rowBits U)`. -/ +abbrev width := max (rowBits S) (rowBits U) + +variable (w : ℕ) +local notation "z" => b.suffixBits +local notation "n" => b.width +open scoped Classical in +/-- Computes the ticket by the application `SpanPlan.header w z n`. -/ +abbrev Ticket := SpanPlan.header w z n +open scoped Classical in +/-- Computes the reply by the application `Format.vec V.k (.vec V.e (b.Ticket w))`. -/ +abbrev Reply (V : Scheme F) := Format.vec V.k (.vec V.e (b.Ticket w)) +open scoped Classical in +/-- Computes the grid by the application `Format.vec V.m (.vec V.h A)`. -/ +abbrev Grid (V : Scheme F) (A : Format) := Format.vec V.m (.vec V.h A) +open scoped Classical in +/-- Computes the replies by the application `Grid V (b.Reply w V)`. -/ +abbrev Replies (V : Scheme F) := Grid V (b.Reply w V) +open scoped Classical in +/-- The value specified by `Format.pair (.addr D.scheme.ℓ) (.pair (.addr D.scheme.h) (.addr +z))`. -/ +abbrev Question := Format.pair (.addr D.scheme.ℓ) (.pair (.addr D.scheme.h) (.addr z)) + +open scoped Classical in +/-- The value specified by `(V.spanOrd s).castLE (Nat.pow_le_pow_right (by decide) hv)`. -/ +def ordinal {N : ℕ} (V : Scheme F) (hv : rowBits V ≤ N) (s : V.Span) : B N := + (V.spanOrd s).castLE (Nat.pow_le_pow_right (by decide) hv) + +open scoped Classical in +/-- Computes the left by the application `ordinal S (le_max_left (rowBits S) (rowBits U))`. -/ +abbrev left := ordinal S (le_max_left (rowBits S) (rowBits U)) +open scoped Classical in +/-- Computes the right by the application `ordinal U (le_max_right (rowBits S) (rowBits U))`. -/ +abbrev right := ordinal U (le_max_right (rowBits S) (rowBits U)) + +open scoped Classical in +/-- Returns `(V.decode l).width t q` when `(V.decode l).peer t q = none` holds, and `0` +otherwise. -/ +def border (V : Scheme F) (l : B V.ℓ) (t : B V.k) (q : B V.e) := + if (V.decode l).peer t q = none then (V.decode l).width t q else 0 + +open scoped Classical in +/-- Returns `⟨j, h⟩` when `h : j < 2 ^ w` holds, and `0` otherwise. -/ +def putLen (w j : ℕ) : B w := if h : j < 2 ^ w then ⟨j, h⟩ else 0 + +open scoped Classical in +/-- Evaluates `(v.2.2, putLen w (border S v.1 t q), b.left ((0, v.2.1, t), q))` at the input `t +q`. -/ +def send (v : b.Question.obj) : (b.Reply w S).obj := fun t q => + (v.2.2, putLen w (border S v.1 t q), b.left ((0, v.2.1, t), q)) + +open scoped Classical in +/-- Evaluates `let s := (v.2 t q).2.2 (0, putLen w (border U v.1 t q), b.left (Trail.locate 0 +s))` at the input `t q`. -/ +def take (v : b.Fields.obj) : (b.Reply w U).obj := fun t q => + let s := (v.2 t q).2.2 + (0, putLen w (border U v.1 t q), b.left (Trail.locate 0 s)) + +open scoped Classical in +/-- The split of type `B a × B (D.scheme.h - a)`, constructed using `splitCell a b.ha.le +((cellIndex _).symm t)`. -/ +def split (t : B D.scheme.h) : B a × B (D.scheme.h - a) := + let j := splitCell a b.ha.le ((cellIndex _).symm t) + (cellIndex _ j.1, cellIndex _ j.2) + +omit [Field F] in +open scoped Classical in +theorem position_split (t : B D.scheme.h) : D.position a b.ha.le (b.split t).1 (b.split t).2 = t + := by + simp [split, position] + +omit [Field F] in +open scoped Classical in +theorem split_position (i : B a) (j : B (D.scheme.h - a)) : b.split (D.position a b.ha.le i j) + = (i, j) := by + simp [split, position] + +open scoped Classical in +/-- Evaluates `let j := b.split l let c := (x v).2 j.1 j.2 (c.1, l, c.2.2)` at the input `v l`. -/ +def ask (x : b.Bank.obj) : (Grid S b.Question).obj := fun v l => + let j := b.split l + let c := (x v).2 j.1 j.2 + (c.1, l, c.2.2) + +open scoped Classical in +/-- Evaluates `((x.1 v).2 l, x.2 v l)` at the input `v l`. -/ +def respond (x : b.Output.obj) : (Grid U b.Fields).obj := fun v l => ((x.1 v).2 l, x.2 v l) + +open scoped Classical in +/-- The line of type `SpanPlan.Entries V.m w z n`, constructed using `V.spanItem v ⟨j.val, h⟩`. -/ +def line (V : Scheme F) (s : (b.Replies w V).obj) : SpanPlan.Entries V.m w z n := fun v j => + if h : j.val < 2 ^ rowBits V then + let i := V.spanItem v ⟨j.val, h⟩ + s v i.1.2.1 i.1.2.2 i.2 + else (0, 0, 0) + +open scoped Classical in +/-- The indexed operation `b.line w S (fun v l => b.send w (b.ask (b.bank r) v l))`. -/ +abbrev sources (r : D.format.obj) := b.line w S (fun v l => b.send w (b.ask (b.bank r) v l)) +open scoped Classical in +/-- The indexed operation `b.line w U (fun v l => b.take w (b.respond (b.result r) v l))`. -/ +abbrev targets (r : D.format.obj) := b.line w U (fun v l => b.take w (b.respond (b.result r) v l)) +open scoped Classical in +/-- Computes the child by the application `Match.rowIndex D.scheme.m z`. -/ +abbrev child := Match.rowIndex D.scheme.m z +open scoped Classical in +/-- The value specified by `(Match.rowIndex b.target.m z).symm (i, 0)`. -/ +def peer (i : B (D.scheme.m + z)) := (Match.rowIndex b.target.m z).symm (i, 0) +open scoped Classical in +/-- Uses `Payload.Script D.scheme.m b.target.m z w n` as the representation. -/ +abbrev Script := Payload.Script D.scheme.m b.target.m z w n +open scoped Classical in +/-- The value specified by `SpanPlan.emit b.peer (b.sources w r, b.targets w r)`. -/ +def script (r : D.format.obj) : (b.Script w).obj := SpanPlan.emit b.peer (b.sources w r, + b.targets w r) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- # Computing both sides of a span transfer with two local tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring Packing BatchDescent + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) +local notation "S" => D.scheme +local notation "U" => b.target + +variable (w : ℕ) +local notation "z" => b.suffixBits +local notation "n" => b.width + +open scoped Classical in +/-- The value specified by `(b.Bank.pair b.Remote).pair b.Output`. -/ +abbrev Input := (b.Bank.pair b.Remote).pair b.Output +open scoped Classical in +/-- The value specified by `(Grid S b.Question).pair (Grid U b.Fields)`. -/ +abbrev Jobs := (Grid S b.Question).pair (Grid U b.Fields) +open scoped Classical in +/-- The value specified by `(b.Replies w S).pair (b.Replies w U)`. -/ +abbrev Posted := (b.Replies w S).pair (b.Replies w U) +open scoped Classical in +/-- Computes the lines by the application `Format.vec V.m (SpanPlan.entries w z n)`. -/ +abbrev Lines (V : Scheme F) := Format.vec V.m (SpanPlan.entries w z n) +open scoped Classical in +/-- The value specified by `(b.Lines w S).pair (b.Lines w U)`. -/ +abbrev Both := (b.Lines w S).pair (b.Lines w U) + +open scoped Classical in +/-- The value specified by `(b.ask s.1.1, b.respond s.2)`. -/ +def jobs (s : b.Input.obj) : b.Jobs.obj := (b.ask s.1.1, b.respond s.2) + +open scoped Classical in +private theorem jobs_net : Circuit F b.Input b.Jobs b.jobs (b.Input.width + 34 * b.Jobs.width) := by + apply Window.Tile.project_const + rintro (⟨i, j, h|h|h⟩ | ⟨i, j, h|h⟩) + · exact .inl ⟨.inl (.inl (i, .inr ((b.split j).1, (b.split j).2, .inl h))), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr D.scheme.h).code j h, fun _ => rfl⟩ + · exact .inl ⟨.inl (.inl (i, .inr ((b.split j).1, (b.split j).2, .inr (.inr h)))), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inl (i, .inr (j, h))), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inr (i, j, h)), fun _ => rfl⟩ + +open scoped Classical in +private theorem line_net (V : Scheme F) : + Circuit F (b.Replies w V) (b.Lines w V) (b.line w V) + ((b.Replies w V).width + 34 * (b.Lines w V).width) := by + apply Window.Tile.project_const + rintro ⟨i, j, h⟩ + by_cases hj : j.val < 2 ^ rowBits V + · let q := V.spanItem i ⟨j.val, hj⟩ + refine .inl ⟨(i, q.1.2.1, q.1.2.2, q.2, h), fun x => ?_⟩ + change (b.Ticket w).code (b.line w V x i j) h = _ + rw [line, dite_eq_left hj] + rfl + · refine .inr ⟨(b.Ticket w).code (0, 0, 0) h, fun x => ?_⟩ + change (b.Ticket w).code (b.line w V x i j) h = _ + rw [line, dite_eq_right hj] + +open scoped Classical in +/-- The indexed operation `weightTable (b.send w) (fun _ => 1)`. -/ +def sendGate : Table F := weightTable (b.send w) (fun _ => 1) +open scoped Classical in +/-- The indexed operation `weightTable (b.take w) (fun _ => 1)`. -/ +def takeGate : Table F := weightTable (b.take w) (fun _ => 1) +open scoped Classical in +/-- Computes the program keys by the application `insert (b.sendGate w) (insert (b.takeGate w) +b.keys)`. -/ +def programKeys := insert (b.sendGate w) (insert (b.takeGate w) b.keys) + +open scoped Classical in +theorem few : (b.programKeys w).card ≤ 5 := + (Finset.card_insert_le _ _).trans (Nat.succ_le_succ + ((Finset.card_insert_le _ _).trans (Nat.succ_le_succ b.card_keys))) + +open scoped Classical in +/-- The quantity computed by `b.Question.width + (b.Reply w S).width`. -/ +def sendArity := b.Question.width + (b.Reply w S).width +open scoped Classical in +/-- The quantity computed by `b.Fields.width + (b.Reply w U).width`. -/ +def takeArity := b.Fields.width + (b.Reply w U).width +open scoped Classical in +/-- The quantity computed by `3 + b.arity + b.sendArity w + b.takeArity w`. -/ +def programArity := 3 + b.arity + b.sendArity w + b.takeArity w + +open scoped Classical in +/-- The indexed operation `(fun i j => b.send w (x.1 i j), fun i j => b.take w (x.2 i j))`. -/ +def answer (x : b.Jobs.obj) : (b.Posted w).obj := + (fun i j => b.send w (x.1 i j), fun i j => b.take w (x.2 i j)) + +open scoped Classical in +/-- The value specified by `2 ^ D.scheme.m * (2 ^ D.scheme.h * (1 + b.sendArity w)) + 2 ^ +b.target.m * (2 ^ b.target.h * (1 + b.takeArity w))`. -/ +def work := 2 ^ D.scheme.m * (2 ^ D.scheme.h * (1 + b.sendArity w)) + + 2 ^ b.target.m * (2 ^ b.target.h * (1 + b.takeArity w)) + +variable {u p t : ℕ} {L : Set (Table F)} + (ha : b.programArity w ≤ u) (hk : (b.programKeys w : Set _) ⊆ L) + +include ha hk in +open scoped Classical in +private theorem answers : Map F u L b.Jobs (b.Posted w) (b.answer w) (b.work w) := by + have hs : Map F u L b.Question (b.Reply w S) (b.send w) (1 + b.sendArity w) := by + rw [sendArity, ← add_assoc] + refine Kernel.lookup ?_ (hk (Finset.mem_insert_self _ _)) + unfold programArity sendArity at ha + omega + have ht : Map F u L b.Fields (b.Reply w U) (b.take w) (1 + b.takeArity w) := by + rw [takeArity, ← add_assoc] + exact Kernel.lookup (by unfold programArity takeArity at ha; omega) + (hk (Finset.mem_insert_of_mem (Finset.mem_insert_self _ _))) + exact (Map.vec _ fun _ : B D.scheme.m => Map.vec _ fun _ : B D.scheme.h => hs).par + (Map.vec _ fun _ : B b.target.m => Map.vec _ fun _ : B b.target.h => ht) + +open scoped Classical in +/-- The issue cost used in the `Binning` construction. -/ +def issueCost := + 4 * (b.Input.width + 34 * b.Jobs.width) + b.work w + + 4 * ((b.Posted w).width + 34 * (b.Both w).width) + + 4 * SpanPlan.emitCost D.scheme.m b.target.m w z n + +open scoped Classical in +/-- The bound obtained by adding the component charges `20 * D.format.width + b.bankCost p t + +b.cost p t + 24 * b.Input.width + 8 * b.target.format.width + b.issueCost w`. -/ +def programCost (p t : ℕ) := + 20 * D.format.width + b.bankCost p t + b.cost p t + + 24 * b.Input.width + 8 * b.target.format.width + b.issueCost w + +open scoped Classical in +private def compile : b.Input.obj → (b.Script w).obj := + SpanPlan.emit b.peer ∘ (Prod.map (b.line w S) (b.line w U) ∘ (b.answer w ∘ b.jobs)) + +open scoped Classical in +private theorem compile_eq (r : D.format.obj) : + b.compile w (b.banks r, b.result r) = b.script w r := by + simp only [compile, Function.comp_apply, answer, jobs, banks, Prod.map, script, sources, targets] + +include ha hk in +open scoped Classical in +private theorem compile_net (hu : 3 ≤ u) : + Map F u L b.Input (b.Script w) (b.compile w) (b.issueCost w) := by + have both : Circuit F (b.Posted w) (b.Both w) (Prod.map (b.line w S) (b.line w U)) + ((b.Posted w).width + 34 * (b.Both w).width) := by + refine ((b.line_net w S).par (b.line_net w U)).mono ?_ + unfold Posted Both + simp only [Format.width_pair] + omega + exact (((Map.circuit hu b.jobs_net).comp (b.answers w ha hk)).comp (Map.circuit hu both)).comp + (Map.circuit hu (SpanPlan.emit_net (w := w) («n» := n) b.peer F)) + +open scoped Classical in +private theorem pair_keep {I : Type*} {X Y Z C Q : Format} + {x : I → X.obj} {y : I → Y.obj} {z' : I → Z.obj} {c : I → C.obj} {q : I → Q.obj} + {f : (Y.pair (Z.pair C)).obj → Q.obj} {j k l : ℕ} + (hu : 3 ≤ u) (hy : Computes F u L X Y x y (fun _ => 1) j) + (hz : Computes F u L X (Z.pair C) x (fun i => (z' i, c i)) (fun _ => 1) k) + (hf : Map F u L (Y.pair (Z.pair C)) Q f l) (he : ∀ i, f (y i, z' i, c i) = q i) : + Computes F u L X (Z.pair Q) x (fun i => (z' i, q i)) (fun _ => 1) + (20 * X.width + j + k + 24 * (Y.pair (Z.pair C)).width + 8 * Z.width + l) := by + let A := Y.pair (Z.pair C) + let s i := (y i, z' i, c i) + have pr : Circuit F A Z (fun x => x.2.1) (A.width + 2 * Z.width) := + Circuit.project (fun i => .inr (.inl i)) (fun _ _ => rfl) + have keep := Computes.of_map (L := L) (x := s) (y := z') (Map.circuit hu pr) (fun _ => rfl) + have send := Computes.of_map (x := s) (y := q) hf he + have hh := (hy.pair hu hz).comp (keep.pair hu send) + simp only [one_mul] at hh + refine hh.mono ?_ + unfold A + omega + +include ha hk in +open scoped Classical in +theorem programs {I : Type*} (hg : Access F u L b.tagDepth b.tagCap p) + (hs : Access F u L b.sheetDepth b.stack.width t) + (X : I → D.format.obj) (hr : ∀ i, Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) (X i).1) : + Computes F u L D.format (b.target.format.pair (b.Script w)) X + (fun i => (b.data (X i), b.script w (X i))) (fun _ => 1) (b.programCost w p t) := by + have hu : 3 ≤ u := by unfold programArity at ha; omega + have hw : b.arity ≤ u := by unfold programArity at ha; omega + have hl : (b.keys : Set _) ⊆ L := fun _ h => hk (Finset.mem_insert_of_mem + (Finset.mem_insert_of_mem h)) + have hb := b.banks_net hu hg hs (by unfold arity at hw; omega) (fun _ h + => hl (Finset.mem_insert_of_mem h)) X hr + have hc := b.computes hu hg hs hw hl X hr + exact pair_keep (Z := b.target.format) (C := Trail.controls D.scheme b.target 0) + (z' := b.data ∘ X) (c := fun i => (b.move (X i)).commands) + hu hb hc (b.compile_net w ha hk hu) (fun i => b.compile_eq w (X i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- # Widths for transfer commands at the source and destination -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +open Coloring +/-- The quantity computed by `i.t + 1`. -/ +abbrev Case.w (i : Case) := i.t + 1 + +theorem length : Short Case.w := payload.add (short_const 1) + +theorem oldCount : Short (fun i => 2 ^ (i.D.scheme.k + i.D.scheme.e)) := stations.exp_add spans + +theorem newCount : Short (fun i => 2 ^ (i.b.target.k + i.b.target.e)) + := childStations.exp_add childSpans + +theorem width : Short (fun i => i.b.width) := by + refine ((height.add oldCount.of_exp).add (groupHeight.add newCount.of_exp)).mono fun i => ?_ + exact max_le (Nat.le_add_right ..) (Nat.le_add_left ..) + +theorem widthPow : Row (fun i => 2 ^ i.b.width) := by + refine (oldCount.blocks.add newCount.groups).mono fun i => ?_ + change 2 ^ max (i.h + _) (i.a + _) ≤ _ + rw [← pow_add, ← pow_add] + rcases le_total (rowBits i.D.scheme) (rowBits i.b.target) with h | h + · exact (congrArg (2^·) (max_eq_right h)).le.trans (Nat.le_add_left ..) + · exact (congrArg (2^·) (max_eq_left h)).le.trans (Nat.le_add_right ..) + +theorem ticket : Short (fun i => (i.b.Ticket i.w).width) := by + refine (suffix.of_exp.add (length.add width)).mono fun i => ?_ + rw [Ticket, SpanPlan.header, Format.width_pair, Format.width_pair, + Format.width_addr, Format.width_addr, Format.width_addr] + +theorem question : Short (fun i => i.b.Question.width) := by + refine (labels.add (height.add suffix.of_exp)).mono fun i => ?_ + rw [Question, Format.width_pair, Format.width_pair, Format.width_addr, Format.width_addr, + Format.width_addr] + +variable {V : (i : Case) → Scheme i.F} + +private theorem reply (h : Short (fun i => 2 ^ ((V i).k + (V i).e))) : + Short (fun i => (i.b.Reply i.w (V i)).width) := by + refine (h.mul ticket).mono fun i => ?_ + rw [Reply, Format.width_vec, Format.width_vec, pow_add, mul_assoc] + +theorem sendArity : Short (fun i => i.b.sendArity i.w) := question.add (reply oldCount) +theorem takeArity : Short (fun i => i.b.takeArity i.w) := fields.add (reply newCount) + +theorem programArity : Short (fun i => i.b.programArity i.w) := + (((short_const 3).add arity).add sendArity).add takeArity + +theorem input : Cost (fun i => i.b.Input.width) := pair_cost (pair_cost bank remote) output + +variable {A : Case → Format} + +private theorem source (h : Short (fun i => (A i).width)) : + Cost (fun i => (Grid i.D.scheme (A i)).width) := + h.blocks.hosts.mono fun i => by rw [Grid, Format.width_vec, Format.width_vec] + +private theorem dest (h : Short (fun i => (A i).width)) : + Cost (fun i => (Grid i.b.target (A i)).width) := + h.groups.children.mono fun i => by rw [Grid, Format.width_vec, Format.width_vec] + +theorem jobs : Cost (fun i => i.b.Jobs.width) := pair_cost (source question) (dest fields) + +theorem posted : Cost (fun i => (i.b.Posted i.w).width) := + pair_cost (source (reply oldCount)) (dest (reply newCount)) + +theorem both : Cost (fun i => (i.b.Both i.w).width) := by + have h : Row (fun i => (SpanPlan.entries i.w i.b.suffixBits i.b.width).width) := + (widthPow.mul ticket).mono fun i => by rw [SpanPlan.entries, Format.width_vec] + exact pair_cost (h.hosts.mono fun i => by rw [Lines, Format.width_vec]) + (h.children.mono fun i => by rw [Lines, Format.width_vec]) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +end + +/- # Total cost of the controller for a grouped span transfer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate + +theorem work : Cost (fun i => i.b.work i.w) := + (Short.blocks ((short_const 1).add sendArity)).hosts.add + (Short.groups ((short_const 1).add takeArity)).children + +theorem emitCost : Cost (fun i => SpanPlan.emitCost i.m i.b.target.m i.w i.b.suffixBits i.b.width) + := by + have hp : Short (fun i => i.b.suffixBits) := suffix.of_exp + have he : Row (fun i => 2 ^ (i.b.width + i.b.suffixBits)) := + (widthPow.mul suffix).mono fun i => (pow_add ..).le + have hc := ((short_const 100).add ((((short_const 2).mul width).add hp).add length)).pow 140 + have hrow := ((he.mul hc).add (((Long.row (Short.long (length.add (suffix.mul length)))).add + (widthPow.mul (hp.add ((short_const 3).mul length)))).scale 35)) + have haddr := (Long.row (childHosts.add hp.long)).expand suffix + refine (((Row.hosts hrow).add (Row.children hrow)).add (haddr.scale 34)).mono fun i => ?_ + rw [SpanPlan.emit_price, add_mul, mul_assoc 34] + +theorem issueCost : Cost (fun i => i.b.issueCost i.w) := + (((((input.add (jobs.scale 34)).scale 4).add work).add + ((posted.add (both.scale 34)).scale 4)).add (emitCost.scale 4)) + +theorem programCost : Cost (fun i => i.b.programCost i.w i.tagFee i.sheetFee) := + (((((format.scale 20).add bankCost).add charge).add (input.scale 24)).add + (targetFormat.scale 8)).add issueCost + +/-- One exponent works simultaneously for both bounds and all fields. -/ +theorem uniform : ∃ k : ℕ, ∀ i : Case, + i.b.programArity i.w ≤ i.short ^ k ∧ + i.b.programCost i.w i.tagFee i.sheetFee ≤ 2 ^ i.m * i.long ^ k + 2 ^ (i.m + i.h) * i.short ^ k + := by + obtain ⟨j, hj⟩ := programArity.bound + obtain ⟨k, hk⟩ := programCost + refine ⟨max j k, fun i => ?_⟩ + have hs : 0 < i.short := lt_of_lt_of_le (by decide) i.short_two + have hl := hs.trans_le i.short_long + exact ⟨(hj i).trans (Nat.pow_le_pow_right hs (le_max_left ..)), (hk i).trans + (Nat.add_le_add (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right hl (le_max_right ..))) + (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right hs (le_max_right ..))))⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +end + +/- +# Preparation including shipment + +The coefficient of the exterior-bit count involves only the routing +price and the payload depths. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate + +namespace Case +variable (i : Case) + +/-- The quantity computed by `1000 + i.p.W + i.t + i.t`. -/ +abbrev bitBase := 1000 + i.p.W + i.t + i.t +private def lengths := i.bitBase + i.b.suffixBits + (i.t + 1) + i.b.width +private def address := i.lengths + i.m + i.b.target.m + i.p.w + i.p.w ^ i.p.power + +private def setup (K : ℕ) := + i.b.programCost i.w i.tagFee i.sheetFee + 4 * i.b.target.format.width + + (2 ^ i.m + 2 ^ i.b.target.m) * (2 ^ i.b.suffixBits * (i.address ^ K + + 2 ^ i.b.width * i.lengths ^ K) + i.bitBase ^ K) + +theorem bitBase_two : 2 ≤ i.bitBase := by unfold bitBase; omega +end Case + +theorem bitBase : Short Case.bitBase := + (((short_const 1000).add weights).add payload).add payload + +private theorem lengths : Short Case.lengths := ((bitBase.add suffix.of_exp).add length).add width + +private theorem address : Long Case.address := by + have w : Long (fun i => i.p.w) := + BatchDescent.Phase.Poly.of_le Case.long_two fun i => by unfold Case.long; omega + exact (((lengths.long.add hosts).add childHosts).add w).add threshold + +private theorem setup (K : ℕ) : Cost (fun i => i.setup K) := by + have hrow := (((Long.row (address.pow K)).add (widthPow.mul (lengths.pow K))).left suffix).add + (Long.row (bitBase.long.pow K)) + refine ((programCost.add (targetFormat.scale 4)).add + ((Row.hosts hrow).add (Row.children hrow))).mono fun i => ?_ + rw [Case.setup, add_mul] + +theorem total : ∃ k : ℕ, ∀ (i : Case) (N : ℕ), + i.b.programArity i.w ≤ i.short ^ k ∧ + i.b.programCost i.w i.tagFee i.sheetFee + i.p.shipment i.b.target.format.width + i.m (2 ^ i.m + N) i.t i.b.target.m (2 ^ i.b.target.m + N) i.t i.b.suffixBits i.w i.b.width ≤ + 2 ^ i.m * i.long ^ k + 2 ^ (i.m + i.h) * i.short ^ k + N * i.bitBase ^ k := by + obtain ⟨K, hK⟩ := Rounds.Contraction.Prices.shipment_le + obtain ⟨s, hs⟩ := setup K + obtain ⟨a, ha⟩ := programArity.bound + let k := max a (max s (K + 1)) + refine ⟨k, fun i N => ?_⟩ + have hpos : 0 < i.short := lt_of_lt_of_le (by decide) i.short_two + have hl := hpos.trans_le i.short_long + have hb : 0 < i.bitBase := lt_of_lt_of_le (by decide) i.bitBase_two + refine ⟨(ha i).trans (Nat.pow_le_pow_right hpos (le_max_left ..)), ?_⟩ + have h := hK i.F i.p i.b.target.format.width + i.m (2 ^ i.m + N) i.t i.b.target.m (2 ^ i.b.target.m + N) i.t i.b.suffixBits i.w i.b.width + have hmix : i.setup K ≤ 2 ^ i.m * i.long ^ k + 2 ^ (i.m + i.h) * i.short ^ k := by + have he : s ≤ k := (le_max_left ..).trans (le_max_right ..) + exact (hs i).trans (Nat.add_le_add (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right hl he)) + (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right hpos he))) + have hbit : i.bitBase ^ K * 2 ≤ i.bitBase ^ k := calc + _ ≤ i.bitBase ^ K * i.bitBase := Nat.mul_le_mul_left _ i.bitBase_two + _ = i.bitBase ^ (K + 1) := (pow_succ ..).symm + _ ≤ _ := Nat.pow_le_pow_right hb ((le_max_right ..).trans (le_max_right ..)) + calc + _ ≤ i.b.programCost i.w i.tagFee i.sheetFee + (4 * i.b.target.format.width + + (2 ^ i.m + 2 ^ i.b.target.m) * 2 ^ i.b.suffixBits * (i.address ^ K + + 2 ^ i.b.width * i.lengths ^ K) + + ((2 ^ i.m + N) + (2 ^ i.b.target.m + N)) * i.bitBase ^ K) := Nat.add_le_add_left h _ + _ = i.setup K + N * (i.bitBase ^ K * 2) := by unfold Case.setup; ring + _ ≤ _ := Nat.add_le_add hmix (Nat.mul_le_mul_left N hbit) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +end + +/- # Checking the two orders on active exterior spans -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring Packing BatchDescent + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) +local notation "S" => D.scheme +local notation "U" => b.target +variable {w : ℕ} (V : Scheme F) + +open scoped Classical in +theorem line_at (h : rowBits V ≤ b.width) (t : (b.Replies w V).obj) (s : V.Span) : + b.line w V t s.1.1 (ordinal V h s) = t s.1.1 s.1.2.1 s.1.2.2 s.2 := by + have e : (ordinal V h s).val < 2 ^ rowBits V := (V.spanOrd s).isLt + rw [line, dite_eq_left e, show (⟨(ordinal V h s).val, e⟩ : B (rowBits V)) = V.spanOrd s from rfl, + V.spanItem_spanOrd] + +open scoped Classical in +theorem line_cover (h : rowBits V ≤ b.width) (t : (b.Replies w V).obj) (v : B V.m) (j : B b.width) + (hj : 0 < (b.line w V t v j).2.1.val) : ∃ s, s.1.1 = v ∧ ordinal V h s = j := by + unfold line at hj + split at hj + · rename_i hi + refine ⟨V.spanItem v ⟨j.val, hi⟩, rfl, ?_⟩ + unfold ordinal + rw [V.spanOrd_spanItem] + rfl + · exact (lt_irrefl _ hj).elim + +omit [Field F] in +open scoped Classical in +theorem border_eq (r : V.format.obj) (s : V.Span) : + border V ((r s.1.1).2 s.1.2.1) s.1.2.2 s.2 = V.borderLen r s := by + simp only [border, Scheme.borderLen, Scheme.width, Scheme.pattern, Scheme.peer, + Option.map_eq_none_iff] + +omit [Field F] in +open scoped Classical in +private theorem put_at {r : V.format.obj} {k l : ℕ} (hf : V.Fits r l k) (h : k < w) (s : V.Span) : + (putLen w (V.borderLen r s)).val = V.borderLen r s := by + have ht := ((V.border_le r s).trans (hf.2 _)).trans_lt (Nat.pow_lt_pow_right (by decide : 1 + < 2) h) + rw [putLen, dite_eq_left ht] + +variable (r : D.format.obj) + +open scoped Classical in +/-- The value specified by `(b.ask (b.bank r) s.1.1 s.1.2.1).2.2`. -/ +def channel (s : (S).Span) := (b.ask (b.bank r) s.1.1 s.1.2.1).2.2 + +open scoped Classical in +theorem source_at (s : (S).Span) : + b.sources w r s.1.1 (b.left s) = (b.channel r s, putLen w ((S).borderLen r.1 s), b.left s) := by + rw [sources, left, b.line_at] + unfold send channel + have hx : (b.ask (b.bank r) s.1.1 s.1.2.1).1 = (r.1 s.1.1).2 s.1.2.1 := by + simp only [ask, bank, sheet, b.position_split] + rw [hx, border_eq] + rfl + +open scoped Classical in +theorem target_at (s : (U).Span) : + b.targets w r s.1.1 (b.right s) = (0, putLen w ((U).borderLen (b.data r) s), + b.left (Trail.locate 0 (Trail.point D.scheme ((b.move r).read s)).2.2)) := by + rw [targets, right, b.line_at] + change (0, putLen _ (border _ _ _ _), _) = _ + rw [← border_eq] + rfl + +namespace Trial +variable {b r} {x y : Wire} {P : Rounds.Board F x y D.scheme.h} {p : D.Presents r P} + {L : ℝ} (t : b.Trial p L) +local notation "old" => p.pres.boundary +local notation "new" => t.order.boundary + +open scoped Classical in +/-- Returns `(new h.choose).val.1` when `h : ∃ i, (old i).val.1 = s` holds, and `((0, 0, 0), 0)` +otherwise. -/ +def shift (s : (S).Span) : (U).Span := + if h : ∃ i, (old i).val.1 = s then (new h.choose).val.1 else ((0, 0, 0), 0) + +open scoped Classical in +theorem shifted (i : slots x ⊕ slots y) : t.shift (old i).val.1 = (new i).val.1 := by + have h : ∃ j, (old j).val.1 = (old i).val.1 := ⟨i, rfl⟩ + rw [shift, dite_eq_left h] + exact t.follows.same h.choose_spec + +open scoped Classical in +theorem channel_eq (i : slots x ⊕ slots y) : b.channel r (old i).val.1 + = (b.child (new i).val.1.1.1).2 := by + have hv : (old i).val.1.1 = p.pres.vertex (portEnd P.diagram i) := by + cases i + · exact p.pres.end_station _ + · exact p.pres.end_station _ + rw [t.outer_span] + change (b.ask (b.bank r) _ _).2.2 = (b.child (t.plan.addr (portEnd P.diagram i)).1).2 + rw [hv, Presents.Plan.given (ha := b.ha)] + simp only [ask, bank, b.split_position, child, Presents.Plan.addr, Presents.Plan.cell_parts, + Equiv.apply_symm_apply] + exact t.plan.row_interval _ + +open scoped Classical in +theorem return_order (i : slots x ⊕ slots y) : + b.left (Trail.locate 0 (Trail.point D.scheme ((b.move r).read (new i).val.1)).2.2) = + b.left (old i).val.1 := by + obtain ⟨s, he, hp⟩ := Option.map_eq_some_iff.mp (t.follows.mapped i).1 + rw [he, ← hp] + rfl + +open scoped Classical in +theorem spec {V k V' k' : ℕ} (hx : D.scheme.Fits r.1 V k) (hy : b.target.Fits (b.data r) V' k') + (hw : k < w) (hw' : k' < w) : + SpanPlan.Spec p.pres t.order b.child t.shift (fun _ => 0) b.left (b.right ∘ t.shift) + (b.sources w r) (b.targets w r) where + parent s hs := by + obtain ⟨i, rfl⟩ := (p.pres.border_pos _).mp hs + rw [t.shifted] + exact t.ancestor_owner i + bits i := ⟨(t.shifted i).symm, (t.follows.mapped i).2.2.trans (Nat.zero_add _).symm⟩ + ordered _ _ _ _ _ h := h + merged _ _ _ _ _ h := Or.inl h + source s hs := by + obtain ⟨i, rfl⟩ := (p.pres.border_pos _).mp hs + rw [source_at, t.shifted] + exact ⟨t.channel_eq i, put_at _ hx hw _, rfl⟩ + target s hs := by + obtain ⟨i, rfl⟩ := (p.pres.border_pos _).mp hs + rw [Function.comp_apply, t.shifted, target_at] + refine ⟨rfl, (put_at _ hy hw' _).trans ?_, t.return_order i⟩ + rw [Scheme.len_at, Scheme.len_at] + exact (t.follows.mapped i).2.1 + sourceCover v j hj := by + obtain ⟨s, rfl, rfl⟩ := b.line_cover S (le_max_left ..) _ v j hj + refine ⟨s, ?_, rfl, rfl⟩ + change 0 < (b.sources _ _ _ (b.left _)).2.1.val at hj + rw [source_at] at hj + exact hj.trans_eq (put_at _ hx hw s) + targetCover v j hj := by + obtain ⟨s, rfl, rfl⟩ := b.line_cover U (le_max_right ..) _ v j hj + change 0 < (b.targets _ _ _ (b.right _)).2.1.val at hj + rw [target_at] at hj + obtain ⟨i, rfl⟩ := (t.order.border_pos s).mp (hj.trans_eq (put_at _ hy hw' s)) + refine ⟨(old i).val.1, (p.pres.border_pos _).mpr ⟨i, rfl⟩, ?_, ?_⟩ + · rw [t.shifted] + · rw [Function.comp_apply, t.shifted] + +end Trial +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- # Carrying the payload while grouping a layer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Packing + +variable {F : Type} [Field F] {x y : Wire} {a H T R : ℕ} {θ L : ℝ} + (P : Layer F x y) (b : P.template.Binning a H T R θ) + (t : ∀ i, b.Trial (P.presents i) L) (W : Contraction.Prices F) + +local notation "m" => P.template.scheme.m +local notation "m'" => b.target.m +local notation "w" => (P.height + 1) +local notation "r" => (P.template.scheme.h - a) + +/-- The group cost used in the `Layer` construction. -/ +def groupCost := + b.programCost w (W.fee b.tagDepth b.tagCap) (W.fee b.sheetDepth b.stack.width) + + W.shipment b.target.format.width m P.volume P.height m' (P.groupedVolume b) P.height + b.suffixBits w b.width + +private theorem room (size : m + 5 * r + P.height + 4 ≤ W.w) : + 2 ^ b.suffixBits * ((max P.height P.height + 1) * (2 ^ m + 2 ^ m')) < 2 ^ W.w := by + have hm : m ≤ m' := Nat.le_add_right .. + have hq : P.height + 1 ≤ 2 ^ P.height := Nat.lt_two_pow_self + rw [max_self] + calc + _ ≤ 2 ^ b.suffixBits * (2 ^ P.height * (2 ^ m' + 2 ^ m')) := by gcongr + _ = 2 ^ (b.suffixBits + P.height + (m' + 1)) := by rw [pow_add, pow_add, pow_succ]; ring + _ < _ := Nat.pow_lt_pow_right (by decide) (by + change r + 1 + P.height + (m + (r + 1) + 1) < _; omega) + +theorem grouped_compute (q : ℕ) (hd : P.template.scheme.d ≤ 4) (hm : 1 ≤ m) + (size : m + 5 * r + P.height + 4 ≤ W.w) : + Computes F (b.programArity w) (b.programKeys w) P.snapshot.port (P.grouped b t q).port + (fun i : P.State × Val x × Val y => P.snapshot.encode i.1 i.2.1 i.2.2) + (fun i => (P.grouped b t q).encode i.1 i.2.1 i.2.2) (fun _ => 1) (P.groupCost b W) := by + have ok (i : P.State) : (P.presents i).pres.Supplies (t i).order (P.fits i) ((t i).fits (P.fits + i)) + (b.script w (P.data i)) := by + have hx := P.fits i + have hy := (t i).fits hx + have hl := Nat.lt_succ_self P.height + have h := ((t i).spec hx hy hl hl).supplies hx hy hl hl + simp only [Template.Binning.child, Equiv.symm_apply_apply] at h + exact h + let u := b.programArity w + let L : Set (Table F) := b.programKeys w + have hu : 3 ≤ u := by unfold u Template.Binning.programArity; omega + have hs : b.tagDepth ≤ W.w := by + have hj := Nat.mul_le_mul_right r (show P.template.scheme.d + 1 ≤ 5 by omega) + unfold Template.Binning.tagDepth + omega + have hc : b.sheetDepth ≤ W.w := by unfold Template.Binning.sheetDepth; omega + have send := W.access (L := L) hu (hm.trans (Nat.le_add_right ..)) hs b.tagCap + have take := W.access (L := L) hu (hm.trans (Nat.le_add_right ..)) hc b.stack.width + have h := b.programs w le_rfl (Set.Subset.rfl : L ⊆ L) send take P.data (fun i + => (P.presents i).reciprocal) + let X := P.State × Val x × Val y + let src (i : X) := (P.snapshot.encode i.1 i.2.1 i.2.2).2 + let dst (i : X) := ((P.grouped b t q).encode i.1 i.2.1 i.2.2).2 + have move := W.ship (f := src) (g := dst) hu hm (hm.trans (Nat.le_add_right ..)) + (P.room b W size) (h.restrict (fun i : X => i.1)) (fun i v => (ok i.1).carries _ _ v) + exact move + +theorem grouped_transfer (q : ℕ) (hd : P.template.scheme.d ≤ 4) (hm : 1 ≤ m) + (size : m + 5 * r + P.height + 4 ≤ W.w) : + Transforms F (b.programArity w) (b.programKeys w) P.snapshot (P.grouped b t q) (P.groupCost b + W) := by + exact Transforms.deterministic (fun i => i) (fun i => ((t i).eval q).symm) + (P.grouped_compute b t W q hd hm size) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # The transfer budget also covers carrying direct adjacency flags -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Packing +open Template.Binning + +variable {F : Type} [Field F] {x y : Wire} {a H T R : ℕ} {θ : ℝ} + (P : Layer F x y) (b : P.template.Binning a H T R θ) (W : Contraction.Prices F) + +private theorem core_budget {D : Template F} (b : D.Binning a H T R θ) (w p t : ℕ) : + D.format.width + b.target.format.width + b.Flags.width + D.navCost a b.target.d + ≤ b.programCost w p t := by + have he := b.flags_bound + change D.format.width + b.target.format.width + b.Flags.width + D.navCost a (D.childD a 5) ≤ _ + change b.Flags.width ≤ D.navCost a (D.childD a 5) at he + unfold programCost Template.Binning.cost linkCost + omega + +private theorem payload_budget (size m V k m' V' p l n : ℕ) : + (Fmt.payload m V k).width + (Fmt.payload m' V' k).width ≤ W.shipment size m V k m' V' k p l n + := by + refine le_trans ?_ (Nat.le_add_left (W.transferCost m V k m' V' k p) _) + have h : 2 ≤ 500000 * ((102 + k) ^ 8 + W.W) := + (by decide : 2 ≤ 500000).trans (Nat.le_mul_of_pos_right _ (by positivity)) + unfold Contraction.Prices.transferCost + rw [max_self] + dsimp only + calc + _ ≤ (k + 1) * (2 * V) + (k + 1) * (2 * V') := Nat.add_le_add (Fmt.width_payload ..) + (Fmt.width_payload ..) + _ = 2 * (k + 1) * (V + V') := by ring + _ ≤ _ := Nat.mul_le_mul (Nat.mul_le_mul h (Nat.le_self_pow (by decide) _)) + ((Nat.le_add_left _ _).trans (Nat.le_add_right ..)) + +theorem group_budget : P.template.format.width + b.target.format.width + b.Flags.width + + P.template.navCost a b.target.d + (Fmt.payload P.template.scheme.m P.volume P.height).width + + (Fmt.payload b.target.m (P.groupedVolume b) P.height).width ≤ P.groupCost b W := by + rw [add_assoc] + exact Nat.add_le_add (core_budget b _ _ _) (payload_budget W _ _ _ _ _ _ _ _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # Retaining direct adjacency with the regrouped inputs -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Packing + +variable {F : Type} [Field F] + +private theorem with_status {I : Type*} {X Y C D E : Format} + {x : I → X.obj} {y : I → Y.obj} {c : I → C.obj} {d : I → D.obj} {f : X.obj → E.obj} + {w k u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + (h : Computes F u L (X.pair Y) (C.pair D) (fun i => (x i, y i)) (fun i => (c i, d i)) (fun _ + => 1) w) + (g : Circuit F X E f (200 * k)) + (hw : X.width + C.width + E.width + k + Y.width + D.width ≤ w) : + Computes F u L (X.pair Y) (C.pair (E.pair D)) (fun i => (x i, y i)) + (fun i => (c i, f (x i), d i)) (fun _ => 1) (1000 * w) := by + have pr : Circuit F (X.pair Y) X Prod.fst ((X.pair Y).width + 2 * X.width) := + Circuit.project Sum.inl (fun _ _ => rfl) + let A := (C.pair D).pair E + let B := C.pair (E.pair D) + have post : Circuit F A B (fun i => (i.1.1, i.2, i.1.2)) (A.width + 2 * B.width) := by + let q : B.pins → A.pins + | .inl i => .inl (.inl i) + | .inr (.inl i) => .inr i + | .inr (.inr i) => .inl (.inr i) + refine Circuit.project q ?_ + rintro v (i|j|l) <;> rfl + have status := Computes.of_map (L := L) (x := fun i => (x i, y i)) (y := f ∘ x) + (Map.circuit hu (pr.comp g)) (fun _ => rfl) + have h' := (h.pair hu status).comp + (Computes.of_map (y := fun i => (c i, f (x i), d i)) (Map.circuit hu post) (fun _ => rfl)) + simp only [one_mul] at h' + refine h'.mono ?_ + simp only [A, B, Format.width_pair] + omega + +variable {x y : Wire} {a H T R : ℕ} {θ L : ℝ} + (P : Layer F x y) (b : P.template.Binning a H T R θ) + (t : ∀ i, b.Trial (P.presents i) L) (W : Contraction.Prices F) + +/-- The quantity computed by `1000 * P.groupCost b W`. -/ +abbrev maskedCost := 1000 * P.groupCost b W + +theorem masked_transfer (q : ℕ) (hd : P.template.scheme.d ≤ 4) (hm : 1 ≤ P.template.scheme.m) + (size : P.template.scheme.m + 5 * (P.template.scheme.h - a) + P.height + 4 ≤ W.w) : + Transforms F (b.programArity (P.height + 1)) (b.programKeys (P.height + 1)) + P.snapshot (P.masked b t q) (P.maskedCost b W) := by + have hu : 3 ≤ b.programArity (P.height + 1) := by unfold Template.Binning.programArity; omega + let I := P.State × Val x × Val y + have h := with_status (I := I) (x := fun i => P.data i.1) + (y := fun i => (P.snapshot.encode i.1 i.2.1 i.2.2).2) + (c := fun i => b.data (P.data i.1)) + (d := fun i => ((P.grouped b t q).encode i.1 i.2.1 i.2.2).2) + hu (P.grouped_compute b t W q hd hm size) b.status_net (P.group_budget b W) + exact Transforms.deterministic (fun i => i) (fun i => ((t i).eval q).symm) h + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # Uniform arity and size of the complete initial grouping step -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Assembly.Template + +variable {F : Type} [Field F] {x y : Wire} {a H T R : ℕ} {θ : ℝ} + +open scoped Classical in +theorem Assembly.Template.Binning.key_arity {D : Template F} (b : D.Binning a H T R θ) (w : ℕ) + {t : Table F} (ht : t ∈ b.programKeys w) : Processor.arity t ≤ b.programArity w := by + simp only [programKeys, keys, Finset.mem_insert] at ht + rcases ht with rfl|rfl|rfl|ht + · simp only [Processor.arity, sendGate, weightTable, lookup, wd_word, programArity, sendArity]; + omega + · simp only [Processor.arity, takeGate, weightTable, lookup, wd_word, programArity, takeArity]; + omega + · simp only [Processor.arity, gate, weightTable, lookup, wd_word, programArity, arity]; omega + · have h : Processor.arity t ≤ b.tagArity := Group.arity_keys F ht + unfold programArity arity; omega + +namespace Rounds.Layer + +open scoped Classical in +/-- Uses `⟨F, P.template, a, H, T, R, θ, b, W, P.height, hd, hk⟩` as the representation. -/ +abbrev grouping (P : Layer F x y) (b : P.template.Binning a H T R θ) (W : Contraction.Prices F) + (hd : P.template.scheme.d ≤ 4) (hk : P.template.scheme.k = 0) : Binning.Rate.Case := + ⟨F, P.template, a, H, T, R, θ, b, W, P.height, hd, hk⟩ + +open scoped Classical in +theorem grouped_bound : ∃ k : ℕ, ∀ (F : Type) [Field F] (x y : Wire) (a H T R : ℕ) (θ : ℝ) + (P : Layer F x y) (b : P.template.Binning a H T R θ) (W : Contraction.Prices F) + (hd : P.template.scheme.d ≤ 4) (hk : P.template.scheme.k = 0), + P.volume = 2 ^ P.template.scheme.m + wd x + wd y → + let i := P.grouping b W hd hk + b.programArity (P.height + 1) ≤ i.short ^ k ∧ + P.groupCost b W ≤ 2 ^ i.m * i.long ^ k + 2 ^ (i.m + i.h) * i.short ^ k + (wd x + + wd y) * i.bitBase ^ k := by + obtain ⟨k, h⟩ := Binning.Rate.total + refine ⟨k, ?_⟩ + intro F _ x y a H T R θ P b W hd hk hv i + unfold groupCost groupedVolume + rw [hv, add_assoc (2 ^ P.template.scheme.m), add_assoc (2 ^ b.target.m)] + have hj := h i (wd x + wd y) + simp only [i, grouping] at hj + exact hj + +open scoped Classical in +private theorem enlarge (n k : ℕ) (h : 2 ≤ n) : 1000 * n ^ k ≤ n ^ (k + 10) := by + rw [pow_add, mul_comm (n ^ k)] + exact Nat.mul_le_mul_right _ ((by decide : 1000 ≤ 2 ^ 10).trans (Nat.pow_le_pow_left h 10)) + +open scoped Classical in +theorem masked_bound : ∃ k : ℕ, ∀ (F : Type) [Field F] (x y : Wire) (a H T R : ℕ) (θ : ℝ) + (P : Layer F x y) (b : P.template.Binning a H T R θ) (W : Contraction.Prices F) + (hd : P.template.scheme.d ≤ 4) (hk : P.template.scheme.k = 0), + P.volume = 2 ^ P.template.scheme.m + wd x + wd y → + let i := P.grouping b W hd hk + b.programArity (P.height + 1) ≤ i.short ^ k ∧ + P.maskedCost b W ≤ 2 ^ i.m * i.long ^ k + 2 ^ (i.m + i.h) * i.short ^ k + (wd x + + wd y) * i.bitBase ^ k := by + obtain ⟨k, h⟩ := grouped_bound + refine ⟨k + 10, ?_⟩ + intro F _ x y a H T R θ P b W hd hk hv i + obtain ⟨ha, hc⟩ := h F x y a H T R θ P b W hd hk hv + refine ⟨ha.trans (Nat.pow_le_pow_right (lt_of_lt_of_le (by decide) i.short_two) (Nat.le_add_right + ..)), ?_⟩ + calc + _ ≤ 1000 * (2 ^ i.m * i.long ^ k + 2 ^ (i.m + i.h) * i.short ^ k + (wd x + + wd y) * i.bitBase ^ k) := + Nat.mul_le_mul_left _ hc + _ = 2 ^ i.m * (1000 * i.long ^ k) + 2 ^ (i.m + i.h) * (1000 * i.short ^ k) + (wd x + + wd y) * (1000 * i.bitBase ^ k) := by ring + _ ≤ _ := Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ (enlarge _ k i.long_two)) + (Nat.mul_le_mul_left _ (enlarge _ k i.short_two))) (Nat.mul_le_mul_left _ (enlarge _ k + i.bitBase_two)) + +end Rounds.Layer +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Contacts.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Contacts.lean new file mode 100644 index 0000000000..51d57dca21 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Contacts.lean @@ -0,0 +1,799 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Sheet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Parcel + +/-! # Recovering occupied rows and their ranks -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents.Plan +open Coloring Packing Rounds Finset + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} + {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} {p : D.Presents r P} + {g H T a u : ℕ} {L θ : ℝ} {ha : a < D.scheme.h} (G : p.Plan ha g H T) + +local notation "n" => D.scheme.h - a +local notation "old" => P.diagram +local notation "suffixOf" => (row (P := P) (ha := ha)) +local notation "colony" => G.group.Colony +local notation "page" => D.sheet a ha g H T r + +open scoped Classical in +/-- Computes the parent by the application `p.host (P.place i).1`. -/ +abbrev parent (i : (old).V) := p.host (P.place i).1 +open scoped Classical in +/-- Computes the prefix of by the application `cellIndex _ (ancestor ha.le (P.place i).2)`. -/ +abbrev prefixOf (i : (old).V) := cellIndex _ (ancestor ha.le (P.place i).2) +open scoped Classical in +/-- The value specified by `page (parent (p := p) i) (prefixOf (ha := ha) i)`. -/ +abbrev sheetAt (i : (old).V) := page (parent (p := p) i) (prefixOf (ha := ha) i) +open scoped Classical in +/-- Computes the rank by the application `Sheet.list u (G.weight (G.col i)) (suffixOf i)`. -/ +abbrev rank (u : ℕ) (i : (old).V) := Sheet.list u (G.weight (G.col i)) (suffixOf i) + +open scoped Classical in +/-- Embeds `colony` into `B (D.childM a) × B a`. -/ +def cellAddr : colony ↪ B (D.childM a) × B a := + ((⟨G.group.site, G.group.site_injective⟩ : colony ↪ _).trans splitSite.toEmbedding).trans + ((Child.host p.host n).prodMap (cellIndex _).toEmbedding) + +local notation "base" => (parent (p := p)) +local notation "top" => (prefixOf (P := P) (ha := ha)) +local notation "atSheet" => (sheetAt (p := p) (ha := ha) (g := g) (H := H) (T := T)) + +open scoped Classical in +theorem cell_parts (i : (old).V) : + G.cellAddr (G.col i) = ((Match.rowIndex D.scheme.m (n + 1)).symm (base i, + G.interval (G.col i)), top i) := rfl + +omit [Field F] in +open scoped Classical in +private theorem position_inj : Function.Injective + (fun t : B a × B n => D.position a ha.le t.1 t.2) := + ((cellIndex _).injective.comp (splitCell a ha.le).symm.injective).comp + (((cellIndex a).symm.prodCongr (cellIndex n).symm).injective) + +open scoped Classical in +theorem given (i : (old).V) : p.pres.vertex i = (base i, D.position a ha.le (top i) (suffixOf i), + 0) := by + rw [p.vertex] + have ht : D.position a ha.le (top i) (suffixOf i) = cellIndex _ (P.place i).2 := by + unfold position prefixOf row + simp only [Equiv.symm_apply_apply] + exact congrArg (cellIndex _) ((splitCell a ha.le).symm_apply_apply (P.place i).2) + rw [ht] + +open scoped Classical in +theorem row_label (i : (old).V) : D.scheme.decode (atSheet i (suffixOf i)).1 = + D.scheme.pattern r.1 (p.pres.vertex i) := by rw [given (ha := ha)]; rfl + +open scoped Classical in +theorem row_interval (i : (old).V) : + (atSheet i (suffixOf i)).2.2 = G.interval (G.col i) := + G.tag (occurrence (ha := ha) i).1 (occurrence (ha := ha) i).2 + +open scoped Classical in +theorem row_weights (i : (old).V) : + Sheet.weights D (atSheet i) (suffixOf i) = G.weight (G.col i) := by + rw [← G.profile_eq] + funext j + unfold Sheet.weights + rw [G.row_interval] + rfl + +open scoped Classical in +theorem row_rank (i : (old).V) : + Sheet.rank D (atSheet i) u (suffixOf i) = G.rank u i := congrArg (fun l + => Sheet.list _ l _) (G.row_weights i) + +open scoped Classical in +theorem row_live (i : (old).V) (hi : 0 < (old).arity i) : Sheet.live D (atSheet i) (suffixOf i) + := by + have h : Nonempty ((old).Port i) := Fintype.card_pos_iff.mp (by simpa [Diagram.Port, + Diagram.arity] using hi) + have h' : Nonempty (D.scheme.LocalPin r.1 (p.pres.vertex i)) := h.map (p.pres.pin i) + rw [given (ha := ha)] at h' + exact h' + +open scoped Classical in +theorem live_row (v : B D.scheme.m) (l : B a) (j : B n) (hw : Sheet.live D (page v l) j) : + ∃ i, 0 < (old).arity i ∧ base i = v ∧ top i = l ∧ suffixOf i = j := by + let v' : D.scheme.Vtx := (v, D.position a ha.le l j, 0) + have hv : Nonempty (D.scheme.LocalPin r.1 v') := hw + obtain ⟨z⟩ := hv + obtain ⟨i, hi⟩ := p.pres.cover (D.scheme.port r.1 v' z) + change p.pres.vertex i = v' at hi + have h₁ : 0 < (old).arity i := Parcel.Manifest.positive (s := z.1) (by rw [hi]; exact z.2.pos) + rw [given (ha := ha)] at hi + have he := Prod.mk.inj hi + have h₂ : (top i, suffixOf i) = (l, j) := position_inj (ha := ha) (Prod.mk.inj he.2).1 + exact ⟨i, h₁, he.1, Prod.mk.inj h₂⟩ + +variable (hg : 0 < g) (hH : 0 < H) (hT : 0 < T) (ok : P.Ready g H T L θ) + (hs : (P.seats : ℝ) * H * T ≤ L * (2 : ℝ) ^ (D.scheme.h - a)) + +open scoped Classical in +theorem row_bin (i : (old).V) : + Sheet.bins D (atSheet i) H T hH (suffixOf i) = G.bin hg hH hT ok hs i := + congrArg (fun l => Cells.chooseBin H T hH l (suffixOf i)) (G.row_weights i) + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev depth (H : ℕ) (θ : ℝ) := Nat.clog 2 ⌈(H : ℝ) / θ⌉₊ + +open scoped Classical in +/-- The condition `∀ c, (active (G.weight c)).card ≤ 2 ^ u` on the specified data. -/ +def Room (u : ℕ) : Prop := ∀ c, (active (G.weight c)).card ≤ 2 ^ u + +include hg hH hT ok hs in +open scoped Classical in +theorem room (hθ : 0 < θ) : G.Room (depth H θ) := fun c => + (G.active_card hg hH hT ok hs hθ c).trans (Nat.le_pow_clog (by decide) _) + +open scoped Classical in +theorem unique_rank (hw : G.Room u) (i j : (old).V) (hi : 0 < (old).arity i) (hj : 0 + < (old).arity j) + (he : G.col i = G.col j) (hr : G.rank u i = G.rank u j) : i = j := by + have mem i (h : 0 < (old).arity i) : suffixOf i ∈ active (G.weight (G.col i)) := + mem_filter.mpr ⟨mem_univ _, (G.weight_at i).symm ▸ (Nat.cast_pos.mpr h).trans_le (P.cover i)⟩ + unfold rank at hr + rw [he] at hr + exact G.one (Prod.ext he (Sheet.list_inj u _ (hw _) (he ▸ mem i hi) (mem j hj) hr)) + +open scoped Classical in +theorem eligible (v : B D.scheme.m) (l : B a) (z : B (n + 1)) (b : B u) (j : B n) : + Sheet.eligible D (page v l) u z b j ↔ + ∃ i, 0 < (old).arity i ∧ G.cellAddr (G.col i) = ((Match.rowIndex _ _).symm (v, z), l) ∧ + G.rank u i = b ∧ suffixOf i = j := by + constructor + · rintro ⟨hl, hz, hr⟩ + obtain ⟨i, hi, rfl, rfl, rfl⟩ := live_row (p := p) _ _ _ hl + refine ⟨i, hi, ?_, (G.row_rank i).symm.trans hr, rfl⟩ + rw [G.cell_parts, ← G.row_interval] + exact congrArg (fun z => ((Match.rowIndex _ _).symm (base i, z), top i)) hz + · rintro ⟨i, hi, he, rfl, rfl⟩ + rw [G.cell_parts] at he + obtain ⟨hp, rfl⟩ := Prod.mk.inj he + obtain ⟨rfl, rfl⟩ := Prod.mk.inj ((Match.rowIndex _ _).symm.injective hp) + exact ⟨row_live i hi, G.row_interval i, G.row_rank i⟩ + +open scoped Classical in +theorem found (hw : G.Room u) (i : (old).V) (hi : 0 < (old).arity i) : + Sheet.find D (atSheet i) u (G.interval (G.col i)) (G.rank u i) = some (suffixOf i) := by + have ht := G.eligible (base i) (top i) (G.interval (G.col i)) (G.rank u i) + have ex : ∃ j, Sheet.eligible D (atSheet i) u (G.interval (G.col i)) (G.rank u i) j := + ⟨suffixOf i, (ht _).mpr ⟨i, hi, rfl, rfl, rfl⟩⟩ + rw [Sheet.find, dite_eq_left ex] + obtain ⟨v, hv, he, hr, hl⟩ := (ht _).mp ex.choose_spec + have hh := G.unique_rank hw v i hv hi (G.cellAddr.injective he) hr + subst v + exact congrArg some hl.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents.Plan +end + +/- # Reading old and copied bits from the merged tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +open Rounds Packing Coloring + +variable {F : Type} [Field F] {x y : Wire} {h a g H T : ℕ} {L : ℝ} + {P : Rounds.Board F x y h} {C : Cells P a g H T L} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r P.diagram} + {m d k u : ℕ} {bin : P.diagram.V → Fin H} {w : (Frame S m d a k u).obj} (A : Manifest C p bin w) + +local notation "G" => P.diagram +local notation "E" => Cells.before P +local notation "N" => scheme S m d a k u +local notation "out" => encode S w + +open scoped Classical in +/-- Returns `t ⟨p, ⟨i, h⟩⟩` when `h : i < S.width s p` holds, and `false` otherwise. -/ +def bit {F : Type} (S : Scheme F) (s : S.format.obj) (t : S.Pin s → Bool) (p : S.Span) (i : ℕ) := + if h : i < S.width s p then t ⟨p, ⟨i, h⟩⟩ else false + +open scoped Classical in +theorem bit_at {F : Type} (S : Scheme F) (s : S.format.obj) (t : S.Pin s → Bool) (p : S.Pin s) : + bit S s t p.1 p.2.val = t p := by rw [bit, dite_eq_left p.2.isLt] + +open scoped Classical in +/-- The indexed operation `A.value j (fun s l => w s l.val)`. -/ +def value {d k e : ℕ} (A : Pattern F d k e) (j : B k) (w : B e → ℕ → Bool) := + A.value j (fun s l => w s l.val) + +omit [Field F] in +open scoped Classical in +private theorem table_bit {S : Scheme F} (r : S.format.obj) (t : S.Pin r → Bool) (v : S.Vtx) : + S.table r v (t ∘ S.port r v) = value (S.pattern r v) v.2.2 (fun s => bit S r t (v, s)) := by + apply congrArg ((S.pattern r v).value v.2.2) + funext j i + exact (bit_at S r t ⟨(v, j), i⟩).symm + +open scoped Classical in +/-- The value specified by `rowAt w (v.1, v.2.1)`. -/ +abbrev atRow (v : (N).Vtx) := rowAt w (v.1, v.2.1) +open scoped Classical in +/-- The value specified by `bit (N) out t (v, Parcel.index _ _ (b, i, s))`. -/ +def bitsAt (v : (N).Vtx) (t : (N).Pin out → Bool) (b : Bool) (i : B u) (s : B S.e) := + bit (N) out t (v, Parcel.index _ _ (b, i, s)) + +open scoped Classical in +theorem table_factor (v : (N).Vtx) (t : (N).Pin out → Bool) : + (N).table out v (t ∘ (N).port out v) = + ∏ i, factor S (atRow (w := w) v) v.2.2 (bitsAt v t) i := by + rw [table_bit, pattern_encode] + let R := atRow (w := w) v + let f := fun s (i : Fin (size S R v.2.2 s)) => bit (N) out t (v, s) i.val + change (∏ i, factor S R v.2.2 (read S R v.2.2 f) i) = _ + have h : read S R v.2.2 f = bitsAt v t := by + funext b i s j + let q := Parcel.index _ _ (b, i, s) + have he : (N).width out (v, q) = size S R v.2.2 q := by rw [Scheme.width, pattern_encode]; rfl + change (if h : j < size S R v.2.2 q then f q ⟨j, h⟩ else false) = bit (N) out t (v, q) j + split + · rfl + · rename_i hh + unfold bit + rw [dite_eq_right (fun hj => hh (hj.trans_eq he))] + rw [h] + +variable (t : (scheme S m d a k u).Pin (encode S w) → Bool) + +open scoped Classical in +theorem real_at (q : (G).End) : + bitsAt (A.place none ((G).station q)) t false (A.rank ((G).station q)) (stub p q) + (p.toSeating.ends q).2.val = + t (A.route (real G q)) := by + have h := bit_at (N) out t (A.route (real G q)) + rw [offset, axis_real, real_span] at h + exact h + +open scoped Classical in +theorem copy_at (q : slots x ⊕ slots y) (b : Bool) : + bitsAt (A.place (some false) (portEnd G q)) t b (A.rank (portEnd G q)) + (stub p (boundaryEnd G q)) (p.toSeating.ends (boundaryEnd G q)).2.val = + t (A.route (copy G b q)) := by + have h := bit_at (N) out t (A.route (copy G b q)) + rw [offset, axis_copy, copy_span] at h + exact h + +open scoped Classical in +/-- The value specified by `(E).weight i (t ∘ A.route ∘ .inl) (t ∘ A.route ∘ .inr)`. -/ +def contribution (i : (E).V) := (E).weight i (t ∘ A.route ∘ .inl) (t ∘ A.route ∘ .inr) + +open scoped Classical in +theorem row_value (i : (G).V) (hi : 0 < (G).arity i) : + factor S (A.row i) (A.mobile i) (bitsAt (A.place none i) t) (A.rank i) = + A.contribution t (.inl i) := by + have hn : slot S (A.row i) (A.rank i) = A.mobile i := A.slot_eq i hi + rw [factor, hn, ite_eq_right (A.mobile_ne i), ite_eq_right (A.mobile_ne i), ite_eq_left rfl] + change value (label S (A.row i) (A.rank i)) 0 (bitsAt (A.place none i) t false (A.rank i)) = + (E).weight (.inl i) ((t ∘ A.route) ∘ .inl) ((t ∘ A.route) ∘ .inr) + rw [A.pattern_eq _ hi, ← A.first i, factor_real] + let w' := t ∘ A.route ∘ real G ∘ p.toSeating.ends.symm + have eq : w' ∘ p.toSeating.ends = t ∘ A.route ∘ real G := + funext fun j => congrArg (t ∘ A.route ∘ real G) (p.toSeating.ends.symm_apply_apply j) + have he := p.weight_at w' i + rw [← Function.comp_assoc w', ← Function.comp_assoc w', eq] at he + refine Eq.trans ?_ he + apply congrArg ((S.pattern r (p.vertex i)).value (p.vertex i).2.2) + funext s l + let q := p.toSeating.ends.symm ⟨(p.vertex i, s), l⟩ + have hp : p.toSeating.ends q = ⟨(p.vertex i, s), l⟩ := p.toSeating.ends.apply_symm_apply _ + have hs : (G).station q = i := p.vertex.injective ((p.end_station q).symm.trans + (congrArg (fun z : S.Pin r => z.1.1) hp)) + have h := A.real_at t q + rw [hs, stub, hp] at h + exact h + +open scoped Classical in +/-- Requires `t (A.route (copy G false i)) = t (A.route (copy G true i))`. -/ +def equal (i : slots x ⊕ slots y) : Prop := t (A.route (copy G false i)) + = t (A.route (copy G true i)) + +open scoped Classical in +theorem copy_value (q : slots x ⊕ slots y) : + A.contribution t (.inr q) = if A.equal t q then 1 else 0 := by + have he := factor_copy G q (t ∘ A.route) + change A.contribution t (.inr q) = _ at he + rw [he] + by_cases h : A.equal t q + · exact (ite_eq_left h).trans (ite_eq_left h).symm + · exact (ite_eq_right h).trans (ite_eq_right h).symm + +open scoped Classical in +theorem check_value (i : (G).V) (hi : 0 < (G).arity i) : + factor S (A.row i) 0 (bitsAt (A.place (some false) i) t) (A.rank i) = + if ∀ q, portEnd G q = i → A.equal t q then 1 else 0 := by + let w' := bitsAt (A.place (some false) i) t + have h : (∀ s, external S (A.row i) (A.rank i) s → + ∀ l : Fin ((label S (A.row i) (A.rank i)).width 0 s), w' false (A.rank i) s l + = w' true (A.rank i) s l) ↔ + ∀ q, portEnd G q = i → A.equal t q := by + have read' (q : slots x ⊕ slots y) (hq : portEnd G q = i) (b : Bool) : + w' b (A.rank i) (stub p (boundaryEnd G q)) (p.toSeating.ends (boundaryEnd G q)).2.val = + t (A.route (copy G b q)) := by + unfold w' + rw [← hq] + exact A.copy_at t q b + constructor + · intro hc q hq + let s := stub p (boundaryEnd G q) + have hs : (p.toSeating.ends (boundaryEnd G q)).1 = (p.vertex i, s) := by + rw [old, station_boundary, hq] + have hn : external S (A.row i) (A.rank i) s := (A.raw_external hi s).mpr (by + rw [← hs]; exact (p.no_peer _).mpr ⟨q, rfl⟩) + let j := (p.toSeating.ends (boundaryEnd G q)).2.cast + ((congrArg (S.width r) hs).trans (A.raw_length hi s).symm) + exact (read' q hq false).symm.trans ((hc s hn j).trans (read' q hq true)) + · intro hc s hs j + let z : S.Pin r := ⟨(p.vertex i, s), j.cast (A.raw_length hi s)⟩ + obtain ⟨q, hq⟩ := (p.no_peer (p.toSeating.ends.symm z)).mp (by + rw [Equiv.apply_symm_apply]; exact (A.raw_external hi s).mp hs) + have he := p.toSeating.ends.eq_symm_apply.mp hq + have hiq : portEnd G q = i := by + apply p.vertex.injective + rw [← station_boundary, ← p.end_station, he] + have eq := (read' q hiq false).trans ((hc q hiq).trans (read' q hiq true).symm) + rw [stub, he] at eq + exact eq + have hn : slot S (A.row i) (A.rank i) ≠ 0 := (A.slot_eq i hi).trans_ne (A.mobile_ne i) + unfold factor + simp only [ite_eq_right hn, ite_true] + exact if_congr h rfl rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +end + +/- # Evaluating all the rows of a group -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +open Rounds Packing Coloring + +variable {F : Type} [Field F] {x y : Wire} {h a g H T : ℕ} {L : ℝ} + {P : Rounds.Board F x y h} {C : Cells P a g H T L} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r P.diagram} + {m d k u : ℕ} {bin : P.diagram.V → Fin H} {w : (Frame S m d a k u).obj} (A : Manifest C p bin w) + +local notation "G" => P.diagram +local notation "E" => Cells.before P +local notation "N" => scheme S m d a k u +local notation "out" => encode S w +open Finset + +variable (t : (scheme S m d a k u).Pin (encode S w) → Bool) + (hn : ∀ v, P.diagram.arity v = 0 → ∀ z, Transcript.sample (P.diagram.table v) z = 1) + +open scoped Classical in +private theorem copy_prod (i : (G).V) : + (∏ q : {q // portEnd G q = i}, A.contribution t (.inr q.val)) = + if ∀ q, portEnd G q = i → A.equal t q then 1 else 0 := by + split + · rename_i h + exact prod_eq_one fun q _ => (A.copy_value t _).trans (ite_eq_left (h _ q.2)) + · rename_i h + push Not at h + obtain ⟨q, hq, he⟩ := h + refine prod_eq_zero (mem_univ (⟨q, hq⟩ : {q // portEnd G q = i})) ?_ + exact (A.copy_value t q).trans (ite_eq_right he) + +open scoped Classical in +/-- Computes the position by the application `A.seat (C.seat bin q)`. -/ +abbrev position (q : (E).V) := A.seat (C.seat bin q) + +open scoped Classical in +theorem pos_real (i : (G).V) : A.position (.inl i) = A.place none i := rfl +open scoped Classical in +theorem pos_copy (q : slots x ⊕ slots y) : A.position (.inr q) = A.place (some false) (portEnd G q) + := + congrArg (fun k => ((A.address (portEnd G q)).1, (A.address (portEnd G q)).2, k)) A.zero + +open scoped Classical in +/-- Returns `A.contribution t q` when `A.position q = v` holds, and `1` otherwise. -/ +def piece (v : (N).Vtx) (q : (E).V) : F := if A.position q = v then A.contribution t q else 1 +open scoped Classical in +/-- The quantity computed by `A.piece t v (.inl i) * ∏ q : {q // portEnd G q = i}, A.piece t v +(.inr q.val)`. -/ +def block (v : (N).Vtx) (i : (G).V) : F := + A.piece t v (.inl i) * ∏ q : {q // portEnd G q = i}, A.piece t v (.inr q.val) + +open scoped Classical in +private theorem pieces (v : (N).Vtx) : + (∏ i, A.block t v i) = ∏ q, A.piece t v q := by + unfold block + rw [prod_mul_distrib, Fintype.prod_fiberwise (portEnd G) (fun q => A.piece t v (.inr q))] + exact (Fintype.prod_sum_type (A.piece t v)).symm + +open scoped Classical in +private theorem block_eq (v : (N).Vtx) (i : (G).V) : A.block t v i = + (if A.place none i = v then A.contribution t (.inl i) else 1) * + (if A.place (some false) i = v then if ∀ q, portEnd G q = i → A.equal t q then 1 else 0 else 1) + := by + unfold block piece + rw [pos_real] + congr 1 + have he (q : {q // portEnd G q = i}) : A.position (.inr q.val) = A.place (some false) i := by + rw [pos_copy, q.property] + simp only [he, prod_ite_irrel, prod_const_one, A.copy_prod] + +include hn in +open scoped Classical in +theorem neutral {q : (E).V} (h : (E).arity q = 0) : A.contribution t q = 1 := by + rcases q with i|q + · unfold contribution + rw [← Function.comp_assoc t, ← Function.comp_assoc t, factor_real] + exact hn i h (fun u => t (A.route (real G ((G).portEquiv ⟨i, u⟩)))) + · exact ((by decide : 2 ≠ 0) h).elim + +open scoped Classical in +private theorem eq_place {v : (N).Vtx} {i : (G).V} {b : Option Bool} + (ha : A.address i = (v.1, v.2.1)) : A.place b i = v ↔ A.idSlot b i = v.2.2 := + ⟨fun h => congrArg (fun q : (N).Vtx => q.2.2) h, fun h => + Prod.ext (Prod.mk.inj ha).1 (Prod.ext (Prod.mk.inj ha).2 h)⟩ + +include hn in +open scoped Classical in +theorem active {v : (N).Vtx} {i : (G).V} (hi : A.block t v i ≠ 1) : + 0 < (G).arity i ∧ A.address i = (v.1, v.2.1) := by + constructor + · by_contra! h + have hz : (G).arity i = 0 := Nat.eq_zero_of_le_zero h + have he : ∀ q, portEnd G q = i → A.equal t q := by + intro q hq + have hpos := live p (boundaryEnd G q) + rw [station_boundary, hq, hz] at hpos + exact (lt_irrefl _ hpos).elim + rw [A.block_eq, A.neutral t hn (q := .inl i) hz, ite_eq_left he, ite_self, ite_self, one_mul] + at hi + exact hi rfl + · by_contra h + have hv b : A.place b i ≠ v := fun e => h (congrArg (fun q : (N).Vtx => (q.1, q.2.1)) e) + exact hi (by rw [A.block_eq, ite_eq_right (hv _), ite_eq_right (hv _), one_mul]) + +open scoped Classical in +private theorem block_factor {v : (N).Vtx} {i : (G).V} (hi : 0 < (G).arity i) + (ha : A.address i = (v.1, v.2.1)) : + A.block t v i = factor S (atRow (w := w) v) v.2.2 (bitsAt v t) (A.rank i) := by + rw [block_eq] + have h : A.place none i ≠ A.place (some false) i := fun h => + A.mobile_ne i (congrArg (fun v : (N).Vtx => v.2.2) h) + by_cases hf : A.place (some false) i = v + · subst v + rw [ite_eq_right h, ite_eq_left rfl, one_mul] + exact (A.check_value t i hi).symm + rw [ite_eq_right hf, mul_one] + by_cases he : A.place none i = v + · subst v + rw [ite_eq_left rfl] + exact (A.row_value t i hi).symm + rw [ite_eq_right he] + have h₁ : v.2.2 ≠ 0 := fun e => hf ((A.eq_place ha).mpr e.symm) + have h₂ : v.2.2 ≠ A.mobile i := fun e => he ((A.eq_place ha).mpr e.symm) + have h₃ : slot S (atRow (w := w) v) (A.rank i) = A.mobile i := by + unfold atRow + rw [← ha] + exact A.slot_eq i hi + simp only [factor, h₃, ite_eq_right (A.mobile_ne i), ite_eq_right h₁, ite_eq_right h₂] + +include hn in +open scoped Classical in +theorem product (v : (N).Vtx) : (N).table out v (t ∘ (N).port out v) = ∏ q, A.piece t v q := by + rw [table_factor, ← pieces] + symm + refine prod_bij_ne_one (fun i _ _ => A.rank i) (fun _ _ _ => mem_univ _) ?_ ?_ ?_ + · intro i _ hi j _ hj he + obtain ⟨h₁, h₂⟩ := A.active t hn hi + obtain ⟨k₁, k₂⟩ := A.active t hn hj + exact A.one i j h₁ k₁ (A.cell.injective (h₂.trans k₂.symm)) he + · intro j _ hj + have h : slot S (atRow (w := w) v) j ≠ 0 := fun h => hj (ite_eq_left h) + obtain ⟨i, hi, hv, rfl⟩ := A.appears _ _ h + exact ⟨i, mem_univ _, (A.block_factor t hi hv).trans_ne hj, rfl⟩ + · intro i _ hi + obtain ⟨h₁, h₂⟩ := A.active t hn hi + exact A.block_factor t h₁ h₂ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +end + +/- # Presenting the merged diagram -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +open Rounds Packing Coloring + +variable {F : Type} [Field F] {x y : Wire} {h a g H T : ℕ} {L : ℝ} + {P : Rounds.Board F x y h} {C : Cells P a g H T L} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r P.diagram} + {m d k u : ℕ} {bin : P.diagram.V → Fin H} {w : (Frame S m d a k u).obj} (A : Manifest C p bin w) + +local notation "G" => P.diagram +local notation "E" => Cells.before P +local notation "N" => scheme S m d a k u +local notation "out" => encode S w + +open Finset + +variable (sep : (Cells.before P).Separated (C.seat bin)) + (hn : ∀ v, P.diagram.arity v = 0 → ∀ z, Transcript.sample (P.diagram.table v) z = 1) + +include hn in +open scoped Classical in +theorem occupied (v : (C.stations bin).V) (t : (N).Pin out → Bool) : + (N).table out (A.vertex v) (t ∘ (N).port out (A.vertex v)) = + (C.stations bin).weight v (t ∘ A.ends sep ∘ .inl) (t ∘ A.ends sep ∘ .inr) := by + rw [A.product t hn] + let l : (C.grouped bin).End → Bool := t ∘ A.ends sep + have he : l ∘ sep.ends = t ∘ A.route := funext fun q => congrArg t (A.ends_at sep q) + have h := sep.weight v.val l + simp only [← Function.comp_assoc l, he] at h + refine Eq.trans ?_ h.symm + unfold piece + rw [← prod_filter] + refine prod_subtype _ (fun q => ?_) (A.contribution t) + simp only [mem_filter, mem_univ, true_and] + exact A.seat.injective.eq_iff + +include hn sep in +open scoped Classical in +theorem vacant (v : (N).Vtx) (hv : v ∉ Set.range A.vertex) (t : (N).LocalPin out v → Bool) : + (N).table out v t = 1 := by + let z : (N).Pin out → Bool := fun _ => false + have ht : t = z ∘ (N).port out v := by + funext i + obtain ⟨j, hj⟩ := (A.ends sep).surjective ((N).port out v i) + exact (hv ⟨_, (A.station sep j).symm.trans (congrArg (fun q : (N).Pin out => q.1.1) hj)⟩).elim + rw [ht, A.product z hn] + refine prod_eq_one fun q _ => ?_ + unfold piece + split + · rename_i he + apply A.neutral z hn + apply sep.zero + by_contra! hc + exact hv ⟨⟨_, Nat.pos_of_ne_zero hc⟩, he⟩ + · rfl + +open scoped Classical in +/-- Builds `Sphere.Print.Seating (N) out (C.stations bin) where vertex` with the specified +`vertex`, `ends`, `station`, `value`. -/ +def seating : Sphere.Print.Seating (N) out (C.stations bin) where + vertex := A.vertex + ends := A.ends sep + station := A.station sep + value t v := A.occupied sep hn v t + empty v hv t := A.vacant sep hn v hv t + +variable (hd : p.Directed) + +open scoped Classical in +theorem at_ends (q : (E).End) : + (A.seating sep hn).seat.ends (sep.ends q) = A.route q := by + rw [Sphere.Print.Seating.ends_eq] + exact A.ends_at sep q + +open scoped Classical in +/-- Builds `(N).Presentation out (C.stations bin) where toSeating` with the specified +`toSeating`, `proper`, `input`, `change`. -/ +def present : (N).Presentation out (C.stations bin) where + toSeating := (A.seating sep hn).seat + proper := A.proper hd + input i := by + change (N).peer out ((A.seating sep hn).seat.ends (sep.ends (boundaryEnd E (.inl i)))).1 = none + rw [at_ends] + exact A.outside (.inl i) + output i := by + change (N).peer out ((A.seating sep hn).seat.ends (sep.ends (boundaryEnd E (.inr i)))).1 = none + rw [at_ends] + exact A.outside (.inr i) + internal i := by + obtain ⟨e, rfl⟩ := sep.edges.surjective i + change (N).Joins out ((A.seating sep hn).seat.ends (sep.ends (.inl (.inr e)))) + ((A.seating sep hn).seat.ends (sep.ends (.inr (.inr e)))) + rw [at_ends, at_ends] + exact ⟨(A.internal e).1.1, (A.internal e).2.2.2⟩ + +open scoped Classical in +theorem directed : (A.present sep hn hd).Directed := by + intro i + obtain ⟨q, rfl⟩ := sep.ends.surjective i + rw [show (A.present sep hn hd).toSeating.ends (sep.ends q) = A.route q from A.at_ends sep hn q, + A.direction hd] + cases q <;> rfl + +variable (R : ℕ) +open scoped Classical in +/-- The value specified by `(A.present sep hn hd).pad (A.directed sep hn hd) A.resolved R +(C.loopless bin)`. -/ +def padded := (A.present sep hn hd).pad (A.directed sep hn hd) A.resolved R (C.loopless bin) + +open scoped Classical in +theorem padded_directed : (A.padded sep hn hd R).Directed := + (A.present sep hn hd).pad_directed (A.directed sep hn hd) A.resolved R (C.loopless bin) + +open scoped Classical in +theorem padded_end (i : slots x ⊕ slots y) : + (A.padded sep hn hd R).toSeating.ends (boundaryEnd _ i) + = (N).liftPad out R false (A.route (copy G false i)) := by + have he : boundaryEnd ((C.stations bin).pad R) i + = (C.stations bin).insertEnds R (sep.ends (copy G false i)) := by + cases i <;> rfl + rw [he, padded, Scheme.Presentation.pad_ends, Scheme.Presentation.pad_old] + exact congrArg _ (A.at_ends sep hn (copy G false i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +end + +/- # Resolving original contacts on the child host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents.Plan +open Coloring Packing Rounds Finset + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} + {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} {p : D.Presents r P} + {g H T a u : ℕ} {L θ : ℝ} {ha : a < D.scheme.h} (G : p.Plan ha g H T) + +local notation "n" => D.scheme.h - a +local notation "old" => P.diagram +local notation "suffixOf" => (row (P := P) (ha := ha)) +local notation "colony" => G.group.Colony +local notation "page" => D.sheet a ha g H T r +local notation "base" => (parent (p := p)) +local notation "top" => (prefixOf (P := P) (ha := ha)) +local notation "atSheet" => (sheetAt (p := p) (ha := ha) (g := g) (H := H) (T := T)) + +open scoped Classical in +theorem childPresent (p : D.Presents r P) (ha : a < D.scheme.h) : + Child.Presents P.adj p.host (D.childInput a ha r) := by + have h : Group.Presents (D.groups a ha.le r) p.host P.adj P.adj (P.groupLoad a ha.le) D.load := + ⟨p.live, p.closed, p.edge, p.core, p.group_load ha⟩ + exact Child.presents h false + +local notation "nav" => D.binNav a ha g r +local notation "host" => Child.host p.host n + +open scoped Classical in +theorem reach (hg : 0 < g) {v w : Site P.V n} (hw : w ∈ near P.adj g v) : + nav (host v) (Child.index nav (host v) (host w)) = host w := + (childPresent p ha).nav hg v w ((mem_cube ..).mpr ⟨v, near_self .., v, near_self .., hw⟩) + +variable (hH : 0 < H) +local notation "frame" => D.childFrame a ha g H T r hH u +local notation "back" => Equiv.symm (Match.rowIndex D.scheme.m (n + 1)) + +open scoped Classical in +/-- Computes the addr by the application `G.cellAddr (G.col v)`. -/ +abbrev addr (v : (old).V) := G.cellAddr (G.col v) + +open scoped Classical in +/-- The rewrite target of type `B D.scheme.e → (Parcel.destination (D.childD a g) (Sheet.slots +H) u).obj` for the given inputs. -/ +abbrev rewriteTarget (v : (old).V) : B D.scheme.e → (Parcel.destination (D.childD a g) (Sheet.slots + H) u).obj := + Sheet.target D (atSheet v) H T hH u _ (fun s => page (D.nav r (base v) s) (top v)) + (fun l s l' => Child.index nav (back (base v, l)) (back (D.nav r (base v) s, l'))) (suffixOf v) + +open scoped Classical in +theorem entry (hroom : G.Room u) (i : (old).V) (hi : 0 < (old).arity i) : + Parcel.rowAt frame (G.addr i) (G.rank u i) = + (Sheet.number H (some (Sheet.bins D (atSheet i) H T hH (suffixOf i))), + (atSheet i (suffixOf i)).1, rewriteTarget (p := p) (ha := ha) (g := g) (T := T) hH i) := by + simp only [addr, cell_parts, Parcel.rowAt, childFrame, Equiv.apply_symm_apply, Sheet.record] + rw [G.found hroom i hi] + +open scoped Classical in +theorem appears (v : B (D.childM a) × B a) (b : B u) + (hb : Parcel.slot D.scheme (Parcel.rowAt frame v) b ≠ 0) : + ∃ i, 0 < (old).arity i ∧ G.addr i = v ∧ G.rank u i = b := by + obtain ⟨v, l⟩ := v + obtain ⟨⟨v, z⟩, rfl⟩ := (back).surjective v + simp only [Parcel.slot, Parcel.rowAt, childFrame, Equiv.apply_symm_apply, Sheet.record] at hb + cases h : Sheet.find D (page v l) u z b with + | none => rw [h] at hb; exact (hb rfl).elim + | some j => + obtain ⟨i, hi, he, hr, _⟩ := (G.eligible v l z b j).mp (Sheet.find_spec _ _ _ _ _ _ h) + exact ⟨i, hi, he, hr⟩ + +variable {i j : P.diagram.V} {s t : B D.scheme.e} + +open scoped Classical in +theorem adjacency (hp : 0 < D.scheme.width r.1 (p.pres.vertex i, s)) + (he : D.scheme.peer r.1 (p.pres.vertex i, s) = some (p.pres.vertex j, t)) : + (∃ e, (old).source e = i ∧ (old).target e = j) ∨ (∃ e, (old).source e = j ∧ (old).target e = i) + := by + obtain ⟨e, b, hb⟩ := p.pres.linked (q := ⟨(p.pres.vertex i, s), ⟨0, hp⟩⟩) (by simp [he]) + have h : (p.pres.tip e b).1 = (p.pres.vertex i, s) := congrArg Sigma.fst hb + have h' : (p.pres.tip e (!b)).1 = (p.pres.vertex j, t) := + Option.some.inj ((p.pres.link_tip e b).1.symm.trans (h ▸ he)) + have h₁ := p.pres.vertex.injective ((p.pres.at_tip e b).symm.trans (congrArg Prod.fst h)) + have h₂ := p.pres.vertex.injective ((p.pres.at_tip e (!b)).symm.trans (congrArg Prod.fst h')) + cases b + · exact .inl ⟨e, h₁, h₂⟩ + · exact .inr ⟨e, h₂, h₁⟩ + +open scoped Classical in +private theorem old_target (he : D.scheme.peer r.1 (p.pres.vertex i, s) = some (p.pres.vertex j, + t)) : + ∃ b, (D.scheme.decode (atSheet i (suffixOf i)).1).peer 0 s = some (b, 0, t) ∧ + D.nav r (base i) b = base j ∧ top i = top j ∧ suffixOf i = suffixOf j := by + rw [p.vertex i, p.vertex j] at he + obtain ⟨⟨b, c, l⟩, h₁, h₂⟩ := Option.map_eq_some_iff.mp he + obtain ⟨hv, hl⟩ := Prod.mk.inj h₂ + have hc := (Prod.mk.inj (Prod.mk.inj hv).2).2 + have hp := (cellIndex D.scheme.h).injective ((Prod.mk.inj (Prod.mk.inj hv).2).1) + change c = 0 at hc + change l = t at hl + subst c; subst l + refine ⟨b, ?_, (Prod.mk.inj hv).1, congrArg (fun j => cellIndex _ (ancestor ha.le j)) hp, + congrArg (fun j => cellIndex _ (suffix a j)) hp⟩ + rw [row_label, p.vertex i] + exact h₁ + +variable (hg : 0 < g) (hT : 0 < T) (ok : P.Ready g H T L θ) + (hs : (P.seats : ℝ) * H * T ≤ L * (2 : ℝ) ^ (D.scheme.h - a)) +local notation "C" => G.cells hg hH hT ok hs +local notation "bin" => G.bin hg hH hT ok hs + +open scoped Classical in +theorem target_eq (he : D.scheme.peer r.1 (p.pres.vertex i, s) = some (p.pres.vertex j, t)) : + rewriteTarget (p := p) (ha := ha) (g := g) (T := T) hH i s = + (Child.index nav (G.addr i).1 (G.addr j).1, Sheet.number H (some (bin j)), G.rank u j) := by + obtain ⟨b, h₁, h₂, h₃, h₄⟩ := old_target (ha := ha) (g := g) (H := H) (T := T) he + unfold rewriteTarget Sheet.target + rw [h₁] + dsimp only + rw [G.row_interval i, h₂, h₃, h₄] + change (Child.index nav (G.addr i).1 (back (base j, (atSheet j (suffixOf j)).2.2)), + Sheet.number H (some (Sheet.bins D (atSheet j) H T hH (suffixOf j))), + Sheet.rank D (atSheet j) u (suffixOf j)) = _ + rw [G.row_interval j, G.row_rank j, G.row_bin hg hH hT ok hs j] + rfl + +open scoped Classical in +/-- Builds `Parcel.Manifest (C) p.pres bin frame where cell` with the specified `cell`, +`number`, `zero`, `rank`. -/ +def manifest (hroom : G.Room u) : Parcel.Manifest (C) p.pres bin frame where + cell := G.cellAddr + number := Sheet.number H + zero := Sheet.number_none H + rank := G.rank u + one := G.unique_rank hroom + first i := by rw [p.vertex] + slot_eq i hi := by + change (Parcel.rowAt frame (G.addr i) (G.rank u i)).1 = _ + rw [G.entry hH hroom i hi, G.row_bin hg hH hT ok hs] + pattern_eq i hi := by + change D.scheme.decode (Parcel.rowAt frame (G.addr i) (G.rank u i)).2.1 = _ + rw [G.entry hH hroom i hi] + exact row_label (g := g) (H := H) (T := T) i + appears := G.appears hH + index := Child.index nav + stay i := by + have h : nav i 0 = i := Neighborhood.origin + simp only [Child.index, Child.select, h, decide_true, ite_true] + self _ := Neighborhood.origin + peer i s j t hp he := by + change (Parcel.rowAt frame (G.addr i) (G.rank u i)).2.2 s = _ ∧ _ + rw [G.entry hH hroom i (Parcel.Manifest.positive hp)] + refine ⟨G.target_eq hH hg hT ok hs he, ?_⟩ + have hloc : ((C).site ((C).cell j)).1 ∈ near P.adj g ((C).site ((C).cell i)).1 ∧ + ((C).site ((C).cell i)).2 = ((C).site ((C).cell j)).2 := by + rcases adjacency hp he with ⟨e, rfl, rfl⟩|⟨e, rfl, rfl⟩ + · exact ⟨((C).edge e).2, ((C).edge e).1.symm⟩ + · exact ⟨(C).sym _ _ ((C).edge e).2, ((C).edge e).1⟩ + exact ⟨reach (p := p) (ha := ha) hg hloc.1, congrArg (cellIndex a) hloc.2⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents.Plan +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Parcel.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Parcel.lean new file mode 100644 index 0000000000..65ddbe08c9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Parcel.lean @@ -0,0 +1,1077 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Seating +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal + +/-! +# Real and padding bits of a directed bundle + +Additional bits are fixed to zero at both ends. They form at most +one extra span for each ordered pair of stations. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram +open Finset Sphere.Layout + +variable {F : Type} {x y : Wire} (G : Diagram F x y) (R : ℕ) + +open scoped Classical in +/-- The quantity computed by `padWidth R (G.width p.1 p.2) - G.width p.1 p.2`. -/ +abbrev padSize (p : G.V × G.V) := padWidth R (G.width p.1 p.2) - G.width p.1 p.2 +open scoped Classical in +/-- Indexes the pad extra by the coordinates of `Σ p : G.V × G.V, Fin (G.padSize R p)`. -/ +abbrev PadExtra := Σ p : G.V × G.V, Fin (G.padSize R p) + +open scoped Classical in +/-- The subtype of `e` satisfying `G.source e = p.1 ∧ G.target e = p.2`. -/ +abbrev wires (p : G.V × G.V) := {e // G.source e = p.1 ∧ G.target e = p.2} + +open scoped Classical in +/-- Reindexes `G.E` and `Σ p : G.V × G.V, G.wires p where toFun e` by an equivalence. -/ +def splitPairs : G.E ≃ Σ p : G.V × G.V, G.wires p where + toFun e := ⟨(G.source e, G.target e), e, rfl, rfl⟩ + invFun q := q.2.val + left_inv _ := rfl + right_inv := by rintro ⟨⟨v, w⟩, e, hv, hw⟩; cases hv; cases hw; rfl + +open scoped Classical in +/-- Reindexes `G.wires p ⊕ Fin (G.padSize R p)` and `Fin (padWidth R (G.width p.1 p.2))` by an +equivalence. -/ +def ranges (p : G.V × G.V) : G.wires p ⊕ Fin (G.padSize R p) ≃ Fin (padWidth R (G.width p.1 + p.2)) := + ((Fintype.equivFin _).sumCongr (Equiv.refl _)).trans + (finSumFinEquiv.trans (finCongr (Nat.add_sub_of_le (le_padWidth R _)))) + +variable [Field F] + +open scoped Classical in +/-- Reindexes `G.E ⊕ G.PadExtra R` and `(G.pad R).E` by an equivalence. -/ +def padBits : G.E ⊕ G.PadExtra R ≃ (G.pad R).E := + (G.splitPairs.sumCongr (Equiv.refl _)).trans + ((Equiv.sigmaSumDistrib _ _).symm.trans (Equiv.sigmaCongrRight (G.ranges R))) + +open scoped Classical in +theorem padBits_old (e : G.E) : (G.padBits R (.inl e)).1 = (G.source e, G.target e) := rfl +open scoped Classical in +theorem padBits_extra (i : G.PadExtra R) : (G.padBits R (.inr i)).1 = i.1 := rfl + +variable (v : G.V) (t : (G.pad R).End → Bool) + +open scoped Classical in +/-- Transforms the indexed data by `Sum.map (Sum.map id (fun e => G.padBits R (.inl e))) +(Sum.map id (fun e => G.padBits R (.inl e)))`. -/ +def insertEnds : G.End → (G.pad R).End := + Sum.map (Sum.map id (fun e => G.padBits R (.inl e))) (Sum.map id (fun e => G.padBits R (.inl e))) + +open scoped Classical in +/-- The legal of type `Prop` for the given inputs. -/ +def legal : Prop := + (∀ i : G.PadExtra R, i.1.1 = v → t (.inl (.inr (G.padBits R (.inr i)))) = false) ∧ + (∀ i : G.PadExtra R, i.1.2 = v → t (.inr (.inr (G.padBits R (.inr i)))) = false) + +open scoped Classical in +private abbrev State := ∀ p, G.wires p → Bool + +open scoped Classical in +private def pack (s : G.State) (i : (G.pad R).E) := + if h : i.2.val < G.width i.1.1 i.1.2 then + s i.1 ((Fintype.equivFin (G.wires i.1)).symm ⟨i.2.val, h⟩) else false + +open scoped Classical in +private theorem pack_old (s : G.State) (e : G.E) : + G.pack R s (G.padBits R (.inl e)) = s (G.source e, G.target e) ⟨e, rfl, rfl⟩ := by + let p := (G.source e, G.target e) + let q : G.wires p := ⟨e, rfl, rfl⟩ + let i := Fintype.equivFin (G.wires p) q + change (if h : i.val < G.width p.1 p.2 then + s p ((Fintype.equivFin _).symm ⟨i.val, h⟩) else false) = s p q + rw [dite_eq_left (show i.val < G.width p.1 p.2 from i.isLt)] + exact congrArg _ ((Fintype.equivFin (G.wires p)).symm_apply_apply q) + +open scoped Classical in +private theorem pack_new (s : G.State) (i : G.PadExtra R) : + G.pack R s (G.padBits R (.inr i)) = false := by + unfold pack + apply dite_eq_right + exact Nat.not_lt_of_ge (Nat.le_add_right _ _) + +open scoped Classical in +private def valid (s : G.State) := + (∀ i : (G.pad R).E, i.1.1 = v → G.pack R s i = t (.inl (.inr i))) ∧ + (∀ i : (G.pad R).E, i.1.2 = v → G.pack R s i = t (.inr (.inr i))) + +open scoped Classical in +private theorem admissible (hn : ∀ e, G.source e ≠ G.target e) : + (∃ s, G.valid R v t s) ↔ G.legal R v t := by + constructor + · rintro ⟨s, h₁, h₂⟩ + exact ⟨fun i h => (h₁ _ h).symm.trans (G.pack_new R s i), + fun i h => (h₂ _ h).symm.trans (G.pack_new R s i)⟩ + intro h + let s : G.State := fun p e => if p.1 = v then t (.inl (.inr (G.padBits R (.inl e.val)))) + else t (.inr (.inr (G.padBits R (.inl e.val)))) + refine ⟨s, ?_, ?_⟩ + · intro i hi + obtain ⟨e|j, rfl⟩ := (G.padBits R).surjective i + · rw [pack_old] + exact ite_eq_left hi + · exact (G.pack_new R s j).trans (h.1 j hi).symm + · intro i hi + obtain ⟨e|j, rfl⟩ := (G.padBits R).surjective i + · rw [pack_old] + exact ite_eq_right (fun h => hn e (h.trans hi.symm)) + · exact (G.pack_new R s j).trans (h.2 j hi).symm + +open scoped Classical in +private theorem weight_bundled (B : Bundled F x y) (v : B.V) (x y) : + B.diagram.weight v x y = B.weight v x y := + weight_ofLocal _ _ _ B.local_weight _ _ _ + +open scoped Classical in +private theorem pad_value : + (G.pad R).weight v (t ∘ .inl) (t ∘ .inr) = + if h : ∃ s, G.valid R v t s then + G.vertex ((bits x).symm (t ∘ .inl ∘ .inl)) ((bits y).symm (t ∘ .inr ∘ .inl)) + (fun e => h.choose (G.source e, G.target e) ⟨e, rfl, rfl⟩) v + else 0 := by + unfold pad + rw [weight_bundled] + unfold Bundled.weight + split + · rename_i hs + have h : ∃ s, G.valid R v t s := hs + rw [dite_eq_left h] + rfl + · rename_i hs + have h : ¬∃ s, G.valid R v t s := hs + rw [dite_eq_right h] + +open scoped Classical in +theorem pad_weight (hn : ∀ e, G.source e ≠ G.target e) : + (G.pad R).weight v (t ∘ .inl) (t ∘ .inr) = + if G.legal R v t then G.weight v (t ∘ G.insertEnds R ∘ .inl) (t ∘ G.insertEnds R ∘ .inr) else + 0 := by + rw [pad_value] + by_cases h : G.legal R v t + · have hs := (G.admissible R v t hn).mpr h + rw [dite_eq_left hs, ite_eq_left h] + apply G.local_weight + · rintro (i|e) he + · simp only [Sum.elim_inl, Equiv.apply_symm_apply]; rfl + · exact (G.pack_old R hs.choose e).symm.trans (hs.choose_spec.1 _ he) + · rintro (i|e) he + · simp only [Sum.elim_inl, Equiv.apply_symm_apply]; rfl + · exact (G.pack_old R hs.choose e).symm.trans (hs.choose_spec.2 _ he) + · rw [dite_eq_right ((G.admissible R v t hn).not.mpr h), ite_eq_right h] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- +# Recognizing a parallel bundle at either endpoint + +Both local patterns see the same set of ordered pairs of span +indices, counted once per wire. They can agree on one pair to carry +an extra padding span without inspecting any long host names. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Finset Coloring + +variable {F : Type} {d k e : ℕ} + +namespace Pattern +variable (A : Pattern F d k e) (j : B k) (s : B e) + +open scoped Classical in +/-- Transforms the indexed data by `(A.peer j s).map fun u => (u.1, u.2.1)`. -/ +def target := (A.peer j s).map fun u => (u.1, u.2.1) +open scoped Classical in +/-- Transforms the indexed data by `((A.peer j s).map fun u => u.2.2).getD 0`. -/ +def opposite := ((A.peer j s).map fun u => u.2.2).getD 0 +open scoped Classical in +/-- Returns `(A.opposite j s, s)` when `A.direction j s` holds, and `(s, A.opposite j s)` +otherwise. -/ +def mark := if A.direction j s then (A.opposite j s, s) else (s, A.opposite j s) + +open scoped Classical in +/-- The subtype of `t : A.Pin j` satisfying `A.target j t.1 = A.target j s ∧ A.direction j t.1 = +A.direction j s`. -/ +abbrev Slice := {t : A.Pin j // A.target j t.1 = A.target j s ∧ A.direction j t.1 = A.direction j s} +open scoped Classical in +/-- The indexed operation `univ.image (fun t : A.Slice j s => A.mark j t.val.1)`. -/ +def marks := univ.image (fun t : A.Slice j s => A.mark j t.val.1) + +open scoped Classical in +/-- Returns `h.choose` when `h : q.Nonempty` holds, and `(0, 0)` otherwise. -/ +def pick (q : Finset (B e × B e)) := if h : q.Nonempty then h.choose else (0, 0) + +open scoped Classical in +/-- Counts the elements of `(A.Slice j s); Diagram.padWidth R n - n else 0`. -/ +def extra (R : ℕ) : ℕ := + if 0 < A.width j s ∧ (A.target j s).isSome ∧ A.mark j s = pick (A.marks j s) + then let n := Fintype.card (A.Slice j s); Diagram.padWidth R n - n else 0 + +end Pattern + +namespace Scheme +variable {S : Scheme F} {r : S.format.obj} +open scoped Classical in +/-- The value specified by `(S.pattern r a.1).target a.1.2.2 a.2`. -/ +abbrev arc (S : Scheme F) (r : S.format.obj) (a : S.Span) := (S.pattern r a.1).target a.1.2.2 a.2 +open scoped Classical in +/-- The value specified by `(S.pattern r a.1).mark a.1.2.2 a.2`. -/ +abbrev mark (S : Scheme F) (r : S.format.obj) (a : S.Span) := (S.pattern r a.1).mark a.1.2.2 a.2 +open scoped Classical in +/-- The value specified by `(S.pattern r a.1).extra a.1.2.2 a.2 R`. -/ +abbrev extra (S : Scheme F) (r : S.format.obj) (R : ℕ) (a : S.Span) := + (S.pattern r a.1).extra a.1.2.2 a.2 R + +open scoped Classical in +/-- The resolved of type `Prop` for the given inputs. -/ +def Resolved (S : Scheme F) (r : S.format.obj) : Prop := + ∀ u s t, 0 < S.width r (u, s) → 0 < S.width r (u, t) → + (S.peer r (u, s)).map Prod.fst = (S.peer r (u, t)).map Prod.fst → S.arc r (u, s) = S.arc r (u, + t) + +open scoped Classical in +theorem destination (a : S.Span) : (S.peer r a).map Prod.fst = + (S.arc r a).map (fun v => ((r a.1.1).1 v.1, a.1.2.1, v.2)) := by + unfold peer arc Pattern.target + cases (S.pattern r a.1).peer a.1.2.2 a.2 <;> rfl + +open scoped Classical in +theorem mark_eq {a b : S.Span} (h : S.peer r a = some b) : + S.mark r a = if S.direction r a then (b.2, a.2) else (a.2, b.2) := by + have ht : (S.pattern r a.1).opposite a.1.2.2 a.2 = b.2 := by + unfold peer at h + unfold Pattern.opposite + cases he : (S.pattern r a.1).peer a.1.2.2 a.2 + · simp [he] at h + · simp only [he, Option.map_some, Option.getD_some, Option.some.injEq] at h ⊢ + exact congrArg Prod.snd h + simp only [mark, Pattern.mark, ht, direction] + congr! 2 + +namespace Presentation +variable [Field F] {x y : Wire} {G : Diagram F x y} (p : S.Presentation r G) + (hd : p.Directed) (hr : S.Resolved r) + +open scoped Classical in +theorem end_station (i : G.End) : (p.toSeating.ends i).1.1 = p.vertex (G.station i) := by + obtain ⟨⟨v, j⟩, rfl⟩ := G.portEquiv.surjective i + rw [G.station_port, p.toSeating.ends_at] + rfl + +open scoped Classical in +/-- In the case `false`, this construction gives `.inl (.inr z)`. -/ +def endOf (G : Diagram F x y) (z : G.E) : Bool → G.End + | false => .inl (.inr z) + | true => .inr (.inr z) + +open scoped Classical in +/-- Computes the node by the application `cond t a.2 a.1`. -/ +def node (a : G.V × G.V) (t : Bool) := cond t a.2 a.1 +open scoped Classical in +/-- The value specified by `(G.source z, G.target z)`. -/ +abbrev pair (G : Diagram F x y) (z : G.E) := (G.source z, G.target z) +open scoped Classical in +/-- Computes the tip by the application `p.toSeating.ends (endOf G z t)`. -/ +def tip (z : G.E) (t : Bool) := p.toSeating.ends (endOf G z t) + +open scoped Classical in +theorem at_tip (z : G.E) (t : Bool) : (p.tip z t).1.1 = p.vertex (node (pair G z) t) := by + unfold tip + rw [p.end_station] + cases t <;> rfl + +open scoped Classical in +theorem link_tip (z : G.E) (t : Bool) : S.Joins r (p.tip z t) (p.tip z (!t)) := by + cases t + · exact p.internal z + · exact (p.internal z).symm p.proper + +include hd in +open scoped Classical in +theorem dir_tip (z : G.E) (t : Bool) : S.direction r (p.tip z t).1 = t := by + unfold tip + rw [hd] + cases t <;> rfl + +open scoped Classical in +/-- The value specified by `((p.tip z false).1.2, (p.tip z true).1.2)`. -/ +abbrev stamp (z : G.E) := ((p.tip z false).1.2, (p.tip z true).1.2) +open scoped Classical in +/-- The subtype of `z` satisfying `G.source z = a.1 ∧ G.target z = a.2`. -/ +abbrev PairEdges (G : Diagram F x y) (a : G.V × G.V) := {z // G.source z = a.1 ∧ G.target z = a.2} +open scoped Classical in +/-- The indexed operation `univ.image (fun z : PairEdges G a => p.stamp z.val)`. -/ +def marks (a : G.V × G.V) := univ.image (fun z : PairEdges G a => p.stamp z.val) + +include hd in +open scoped Classical in +theorem stamp_tip (z : G.E) (t : Bool) : S.mark r (p.tip z t).1 = p.stamp z := by + rw [mark_eq (p.link_tip z t).1, p.dir_tip hd] + cases t <;> rfl + +open scoped Classical in +theorem linked {q : S.Pin r} (h : (S.peer r q.1).isSome) : ∃ z t, p.tip z t = q := by + obtain ⟨(i|z)|(i|z), rfl⟩ := p.toSeating.ends.surjective q + · simp [p.input] at h + · exact ⟨z, false, rfl⟩ + · simp [p.output] at h + · exact ⟨z, true, rfl⟩ + +include hd hr in +open scoped Classical in +theorem same_pair (z : G.E) (t : Bool) (q : S.Pin r) : + (q.1.1 = (p.tip z t).1.1 ∧ S.arc r q.1 = S.arc r (p.tip z t).1 ∧ S.direction r q.1 = t) ↔ + ∃ w, pair G w = pair G z ∧ p.tip w t = q := by + constructor + · rintro ⟨hv, ha, hd'⟩ + have he : (S.peer r q.1).map Prod.fst = some (p.tip z (!t)).1.1 := by + rw [destination, ha, hv, ← destination, (p.link_tip z t).1] + rfl + have hq : (S.peer r q.1).isSome := by + cases h : S.peer r q.1 <;> simp [h] at he ⊢ + obtain ⟨w, s, rfl⟩ := p.linked hq + rw [p.dir_tip hd] at hd' + subst s + rw [(p.link_tip w t).1, Option.map_some, Option.some.injEq, p.at_tip, p.at_tip] at he + rw [p.at_tip, p.at_tip] at hv + have h₁ := p.vertex.injective hv + have h₂ := p.vertex.injective he + refine ⟨w, ?_, rfl⟩ + cases t + · exact Prod.ext h₁ h₂ + · exact Prod.ext h₂ h₁ + · rintro ⟨w, hw, rfl⟩ + have he (s : Bool) : (p.tip w s).1.1 = (p.tip z s).1.1 := by rw [p.at_tip, p.at_tip, hw] + refine ⟨he t, ?_, p.dir_tip hd w t⟩ + have hh : (S.peer r (p.tip w t).1).map Prod.fst = (S.peer r (p.tip z t).1).map Prod.fst := by + rw [(p.link_tip w t).1, (p.link_tip z t).1, Option.map_some, Option.map_some, he] + generalize hx : p.tip w t = i at * + generalize hy : p.tip z t = j at * + obtain ⟨⟨v, x⟩, l⟩ := i + obtain ⟨⟨u, y⟩, k⟩ := j + have hv : v = u := by simpa [hx, hy] using he t + subst v + exact hr _ _ _ l.pos k.pos hh + +open scoped Classical in +/-- The value specified by `(S.pattern r s.1).Slice s.1.2.2 s.2`. -/ +abbrev Slice (s : S.Span) := (S.pattern r s.1).Slice s.1.2.2 s.2 + +omit [Field F] in +open scoped Classical in +private theorem local_bit (q : S.Pin r) (v : S.Vtx) (h : q.1.1 = v) : + ∃ i, S.port r v i = q := by + rcases q with ⟨⟨u, s⟩, i⟩ + subst v + exact ⟨⟨s, i⟩, rfl⟩ + +include hd hr in +open scoped Classical in +private theorem slice (z : G.E) (t : Bool) : + let s := (p.tip z t).1 + ∃ e : Slice (r := r) s ≃ PairEdges G (pair G z), ∀ i, + p.tip (e i).val t = S.port r s.1 i.val := by + intro s + have exists' (i : Slice (r := r) s) : + ∃ w : PairEdges G (pair G z), p.tip w.val t = S.port r s.1 i.val := by + obtain ⟨w, hw, he⟩ := (p.same_pair hd hr z t (S.port r s.1 i.val)).mp + ⟨rfl, i.property.1, i.property.2.trans (p.dir_tip hd z t)⟩ + exact ⟨⟨w, Prod.mk.inj hw⟩, he⟩ + choose f hf using exists' + have inj : Function.Injective f := by + intro i j he + apply Subtype.ext + have h := (hf i).symm.trans (he ▸ hf j) + have h₁ : i.val.1 = j.val.1 := congrArg (fun t : S.Pin r => t.1.2) h + exact Sigma.ext h₁ ((Fin.heq_ext_iff (congrArg (fun z => S.width r (s.1, z)) h₁)).mpr + (congrArg (fun t : S.Pin r => t.2.val) h)) + have surj : Function.Surjective f := by + intro w + obtain ⟨h₁, h₂, h₃⟩ := (p.same_pair hd hr z t _).mpr ⟨w.val, Prod.ext w.2.1 w.2.2, rfl⟩ + obtain ⟨i, hi⟩ := local_bit (p.tip w.val t) s.1 h₁ + rw [← hi] at h₂ h₃ + let k : Slice (r := r) s := ⟨i, h₂, h₃.trans (p.dir_tip hd z t).symm⟩ + have he := p.toSeating.ends.injective ((hf k).trans hi) + refine ⟨k, Subtype.ext ?_⟩ + cases t + · exact Sum.inr.inj (Sum.inl.inj he) + · exact Sum.inr.inj (Sum.inr.inj he) + exact ⟨Equiv.ofBijective f ⟨inj, surj⟩, hf⟩ + +include hd hr in +open scoped Classical in +theorem extra_tip (R : ℕ) (z : G.E) (t : Bool) : + S.extra r R (p.tip z t).1 = + if p.stamp z = Pattern.pick (p.marks (pair G z)) then G.padSize R (pair G z) else 0 := by + let s := (p.tip z t).1 + let A := S.pattern r s.1 + let j := s.1.2.2 + obtain ⟨e, he⟩ := p.slice hd hr z t + have hc : Fintype.card (A.Slice j s.2) = G.width (G.source z) (G.target z) := + Fintype.card_congr e + have hv (i : A.Slice j s.2) : A.mark j i.val.1 = p.stamp (e i).val := + (congrArg (fun b : S.Pin r => S.mark r b.1) (he i).symm).trans (p.stamp_tip hd _ t) + have hm : A.marks j s.2 = p.marks (pair G z) := by + ext q + simp only [Pattern.marks, marks, mem_image, mem_univ, true_and] + constructor + · rintro ⟨i, rfl⟩ + exact ⟨e i, (hv i).symm⟩ + · rintro ⟨w, rfl⟩ + obtain ⟨i, rfl⟩ := e.surjective w + exact ⟨i, hv i⟩ + have ha : (A.target j s.2).isSome := by + have he := destination (r := r) s + rw [(p.link_tip z t).1] at he + cases hh : A.target j s.2 + · change S.arc r s = none at hh + simp [hh] at he + · rfl + have hp : 0 < A.width j s.2 := (p.tip z t).2.pos + have hs : A.mark j s.2 = p.stamp z := p.stamp_tip hd z t + change A.extra j s.2 R = _ + simp only [Pattern.extra, hp, ha, hs, hm, hc, true_and] + +end Presentation +end Scheme +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # A bijection between padding ends and their local span addresses -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +open Coloring Finset + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {R : ℕ} + +open scoped Classical in +/-- Indexes the extra by the coordinates of `Σ a : S.Span, Fin (S.extra r R a)`. -/ +abbrev Extra (S : Scheme F) (r : S.format.obj) (R : ℕ) := Σ a : S.Span, Fin (S.extra r R a) + +open scoped Classical in +theorem extra_pos {a : S.Span} (h : 0 < S.extra r R a) : + 0 < S.width r a ∧ (S.peer r a).isSome := by + unfold extra Pattern.extra at h + split at h + · rename_i hh + refine ⟨hh.1, ?_⟩ + have he := congrArg Option.isSome (destination (r := r) a) + simpa only [Option.isSome_map] using he.trans (by simpa only [Option.isSome_map] using hh.2.1) + · exact (lt_irrefl _ h).elim + +namespace Presentation +variable [Field F] {x y : Wire} {G : Diagram F x y} (p : S.Presentation r G) + (hd : p.Directed) (hr : S.Resolved r) + +open scoped Classical in +theorem pick_exists (a : G.V × G.V) (ha : 0 < G.padSize R a) : + ∃ z, pair G z = a ∧ p.stamp z = Pattern.pick (p.marks a) := by + have h : 0 < G.width a.1 a.2 := by + by_contra! hn + simp [Diagram.padSize, Nat.eq_zero_of_le_zero hn] at ha + have : Nonempty (PairEdges G a) := Fintype.card_pos_iff.mp h + have hn : (p.marks a).Nonempty := univ_nonempty.image _ + have hp : Pattern.pick (p.marks a) ∈ p.marks a := by + rw [Pattern.pick, dite_eq_left hn]; exact hn.choose_spec + obtain ⟨z, _, hz⟩ := mem_image.mp hp + exact ⟨z.val, Prod.ext z.property.1 z.property.2, hz⟩ + +open scoped Classical in +/-- The value specified by `(p.pick_exists i.1 i.2.pos).choose`. -/ +def chosen (i : G.PadExtra R) := (p.pick_exists i.1 i.2.pos).choose + +open scoped Classical in +theorem chosen_spec (i : G.PadExtra R) : pair G (p.chosen i) = i.1 ∧ + p.stamp (p.chosen i) = Pattern.pick (p.marks i.1) := (p.pick_exists i.1 i.2.pos).choose_spec + +open scoped Classical in +/-- The value specified by `(p.tip (p.chosen i) t).1`. -/ +abbrev dock (i : G.PadExtra R) (t : Bool) := (p.tip (p.chosen i) t).1 + +include hd hr in +open scoped Classical in +theorem dock_size (i : G.PadExtra R) (t : Bool) : S.extra r R (p.dock i t) = G.padSize R i.1 := by + rw [dock, p.extra_tip hd hr, (p.chosen_spec i).1, ite_eq_left (p.chosen_spec i).2] + +open scoped Classical in +theorem dock_at (i : G.PadExtra R) (t : Bool) : (p.dock i t).1 = p.vertex (node i.1 t) := by + rw [dock, p.at_tip, (p.chosen_spec i).1] + +open scoped Classical in +/-- Uses `⟨p.dock q.1 q.2, q.1.2.cast (p.dock_size hd hr _ _).symm⟩` as the representation. -/ +def inserted (q : G.PadExtra R × Bool) : S.Extra r R := + ⟨p.dock q.1 q.2, q.1.2.cast (p.dock_size hd hr _ _).symm⟩ + +open scoped Classical in +theorem inserted_inj : Function.Injective (p.inserted (R := R) hd hr) := by + rintro ⟨i, t⟩ ⟨j, u⟩ h + have e : p.dock i t = p.dock j u := congrArg (fun q : S.Extra r R => q.1) h + have et : t = u := (p.dir_tip hd _ _).symm.trans ((congrArg (S.direction r) e).trans (p.dir_tip + hd _ _)) + subst u + have ho : p.dock i (!t) = p.dock j (!t) := Option.some.inj + ((p.link_tip _ t).1.symm.trans ((congrArg (S.peer r) e).trans (p.link_tip _ t).1)) + have eq s (he : p.dock i s = p.dock j s) : node i.1 s = node j.1 s := + p.vertex.injective ((p.dock_at _ s).symm.trans ((congrArg Prod.fst he).trans (p.dock_at _ s))) + have ha : i.1 = j.1 := by + cases t + · exact Prod.ext (eq _ e) (eq _ ho) + · exact Prod.ext (eq _ ho) (eq _ e) + have hb : i.2.val = j.2.val := congrArg (fun k => k.2.val) h + exact Prod.ext (Sigma.ext ha ((Fin.heq_ext_iff (congrArg (G.padSize R) ha)).mpr hb)) rfl + +open scoped Classical in +theorem inserted_surj : Function.Surjective (p.inserted (R := R) hd hr) := by + rintro ⟨a, j⟩ + obtain ⟨hw, hp⟩ := extra_pos j.pos + obtain ⟨z, t, ht⟩ := p.linked (q := ⟨a, ⟨0, hw⟩⟩) hp + have ha : (p.tip z t).1 = a := congrArg Sigma.fst ht + have h := p.extra_tip hd hr R z t + rw [ha] at h + have hs : p.stamp z = Pattern.pick (p.marks (pair G z)) := by + by_contra hn + rw [ite_eq_right hn] at h + exact Nat.ne_of_gt j.pos h + rw [ite_eq_left hs] at h + let i : G.PadExtra R := ⟨pair G z, j.cast h⟩ + have he : p.stamp (p.chosen i) = p.stamp z := (p.chosen_spec i).2.trans hs.symm + have hc : p.dock i t = a := by + refine (Prod.ext ((p.dock_at i t).trans (p.at_tip z t).symm) ?_).trans ha + cases t + · exact congrArg Prod.fst he + · exact (Prod.mk.inj he).2 + refine ⟨(i, t), Sigma.ext hc ?_⟩ + exact (Fin.heq_ext_iff (congrArg (S.extra r R) hc)).mpr rfl + +open scoped Classical in +/-- The equivalence obtained by `Equiv.ofBijective (p.inserted hd hr) ⟨p.inserted_inj hd hr, +p.inserted_surj hd hr⟩`. -/ +def adds (R : ℕ) : G.PadExtra R × Bool ≃ S.Extra r R := + Equiv.ofBijective (p.inserted hd hr) ⟨p.inserted_inj hd hr, p.inserted_surj hd hr⟩ + +include hd hr in +open scoped Classical in +theorem extra_peer {a b : S.Span} (h : S.peer r a = some b) : S.extra r R a = S.extra r R b := by + by_cases ha : 0 < S.width r a + · obtain ⟨z, t, ht⟩ := p.linked (q := ⟨a, ⟨0, ha⟩⟩) (by simp [h]) + have he : (p.tip z t).1 = a := congrArg Sigma.fst ht + have hb : (p.tip z (!t)).1 = b := Option.some.inj ((p.link_tip z t).1.symm.trans (he ▸ h)) + rw [← he, ← hb, p.extra_tip hd hr, p.extra_tip hd hr] + have hb : ¬0 < S.width r b := by rwa [← (p.proper _ _ h).2.1] + exact (Nat.eq_zero_of_not_pos (fun e => ha (extra_pos e).1)).trans + (Nat.eq_zero_of_not_pos (fun e => hb (extra_pos e).1)).symm + +end Presentation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- +# Padding a local pattern + +A second copy of the span indices holds the extra bits. The label +and navigation records do not change, only the decoder. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} {d k e : ℕ} + +namespace Pattern +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def tag (e : ℕ) : Bool × B e ≃ B (e + 1) := Fintype.equivOfCardEq (by simp [pow_succ']) + +variable (A : Pattern F d k e) (R : ℕ) + +open scoped Classical in +/-- The construction uses `(tag e).symm s` for its intermediate `u`. -/ +def length (j : B k) (s : B (e + 1)) := + let u := (tag e).symm s + cond u.1 (A.extra j u.2 R) (A.width j u.2) + +open scoped Classical in +theorem length_at (j : B k) (b : Bool) (s : B e) : + A.length R j (tag e (b, s)) = cond b (A.extra j s R) (A.width j s) := by + simp only [length, Equiv.symm_apply_apply] + +open scoped Classical in +/-- Builds `Pattern F d k (e + 1) where width` with the specified `width`, `direction`, `peer`, +`value`. -/ +def padded [Zero F] : Pattern F d k (e + 1) where + width := A.length R + direction j t := A.direction j ((tag e).symm t).2 + peer j t := (A.peer j ((tag e).symm t).2).map (fun u => (u.1, u.2.1, tag e (((tag e).symm t).1, + u.2.2))) + value j f := + if ∀ s (i : Fin (A.extra j s R)), f (tag e (true, s)) (i.cast (A.length_at R j true s).symm) + = false + then A.value j (fun s i => f (tag e (false, s)) (i.cast (A.length_at R j false s).symm)) + else 0 + +end Pattern +namespace Scheme +variable [Field F] (S : Scheme F) (r : S.format.obj) (R : ℕ) + +open scoped Classical in +/-- The quantity computed by `{ S with e := S.e + 1, decode := fun i => (S.decode i).padded R +}`. -/ +abbrev padded : Scheme F := { S with e := S.e + 1, decode := fun i => (S.decode i).padded R } + +open scoped Classical in +/-- The value specified by `(a.1, Pattern.tag _ (b, a.2))`. -/ +def seatPad (b : Bool) (a : S.Span) : (S.padded R).Span := (a.1, Pattern.tag _ (b, a.2)) + +open scoped Classical in +theorem width_pad (b : Bool) (a : S.Span) : + (S.padded R).width r (S.seatPad R b a) = cond b (S.extra r R a) (S.width r a) := + (S.pattern r a.1).length_at R _ _ _ + +open scoped Classical in +theorem direction_pad (b : Bool) (a : S.Span) : + (S.padded R).direction r (S.seatPad R b a) = S.direction r a := by + simp only [direction, pattern, padded, Pattern.padded, seatPad, Equiv.symm_apply_apply] + +open scoped Classical in +theorem peer_pad (b : Bool) (a : S.Span) : + (S.padded R).peer r (S.seatPad R b a) = (S.peer r a).map (S.seatPad R b) := by + simp only [peer, pattern, padded, Pattern.padded, seatPad, Equiv.symm_apply_apply, Option.map_map] + rfl + +open scoped Classical in +theorem seatPad_surj (s : (S.padded R).Span) : ∃ b a, S.seatPad R b a = s := by + obtain ⟨v, t⟩ := s + obtain ⟨⟨b, u⟩, rfl⟩ := (Pattern.tag S.e).surjective t + exact ⟨b, (v, u), rfl⟩ + +open scoped Classical in +theorem seatPad_inj {b c : Bool} {a t : S.Span} (h : S.seatPad R b a = S.seatPad R c t) : + b = c ∧ a = t := by + obtain ⟨h₁, h₂⟩ := Prod.mk.inj h + obtain ⟨he, hs⟩ := Prod.mk.inj ((Pattern.tag S.e).injective h₂) + exact ⟨he, Prod.ext h₁ hs⟩ + +open scoped Classical in +theorem proper_pad {x y : Wire} {G : Diagram F x y} (p : S.Presentation r G) + (hd : p.Directed) (hr : S.Resolved r) : (S.padded R).Proper r := by + intro s t h + obtain ⟨b, a, rfl⟩ := S.seatPad_surj R s + rw [peer_pad] at h + obtain ⟨u, hu, rfl⟩ := Option.map_eq_some_iff.mp h + obtain ⟨h₁, h₂, h₃⟩ := p.proper _ _ hu + rw [peer_pad, h₁, Option.map_some, width_pad, width_pad, h₂, p.extra_peer hd hr hu, + direction_pad, direction_pad] + exact ⟨rfl, rfl, h₃⟩ + +open scoped Classical in +/-- Indexes the pad pin by the coordinates of `Σ a : S.Span, Fin (cond b (S.extra r R a) +(S.width r a))`. -/ +abbrev padPin (b : Bool) := Σ a : S.Span, Fin (cond b (S.extra r R a) (S.width r a)) + +open scoped Classical in +/-- Uses `⟨S.seatPad R b i.1, i.2.cast (S.width_pad r R b i.1).symm⟩` as the representation. -/ +def liftPad (b : Bool) (i : S.padPin r R b) : (S.padded R).Pin r := + ⟨S.seatPad R b i.1, i.2.cast (S.width_pad r R b i.1).symm⟩ + +open scoped Classical in +theorem liftPad_inj (b : Bool) : Function.Injective (S.liftPad r R b) := by + rintro ⟨a, i⟩ ⟨t, j⟩ h + have ht : a = t := (S.seatPad_inj R (congrArg Sigma.fst h)).2 + subst t + have he : i = j := Fin.ext (congrArg (fun t => t.2.val) h) + rw [he] + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def padPins : S.Pin r ⊕ S.Extra r R ≃ (S.padded R).Pin r := + Equiv.ofBijective (Sum.elim (S.liftPad r R false) (S.liftPad r R true)) (by + constructor + · rintro (i|i) (j|j) h + · exact congrArg Sum.inl (S.liftPad_inj r R false h) + · exact Bool.false_ne_true (S.seatPad_inj R (congrArg Sigma.fst h)).1 |>.elim + · exact Bool.false_ne_true (S.seatPad_inj R (congrArg Sigma.fst h.symm)).1 |>.elim + · exact congrArg Sum.inr (S.liftPad_inj r R true h) + · rintro ⟨s, i⟩ + obtain ⟨b, a, rfl⟩ := S.seatPad_surj R s + let q : S.padPin r R b := ⟨a, i.cast (S.width_pad r R b a)⟩ + cases b + · exact ⟨.inl q, rfl⟩ + · exact ⟨.inr q, rfl⟩) + +open scoped Classical in +/-- The condition `∀ j : S.Extra r R, j.1.1 = v → t (S.liftPad r R true j) = false` on the +specified data. -/ +def clear (v : S.Vtx) (t : (S.padded R).Pin r → Bool) := + ∀ j : S.Extra r R, j.1.1 = v → t (S.liftPad r R true j) = false + +open scoped Classical in +theorem table_pad (v : S.Vtx) (t : (S.padded R).Pin r → Bool) : + (S.padded R).table r v (t ∘ (S.padded R).port r v) = + if S.clear r R v t then S.table r v (t ∘ S.liftPad r R false ∘ S.port r v) else 0 := by + have h : S.clear r R v t ↔ ∀ s (i : Fin (S.extra r R (v, s))), + t (S.liftPad r R true ⟨(v, s), i⟩) = false := by + refine ⟨fun h s i => h ⟨(v, s), i⟩ rfl, ?_⟩ + rintro h ⟨⟨w, s⟩, i⟩ rfl + exact h s i + simp only [h] + rfl + +end Scheme +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Presenting the padded diagram on the original navigation network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Coloring + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {r : S.format.obj} {G : Diagram F x y} + (p : S.Presentation r G) (hd : p.Directed) (hr : S.Resolved r) (R : ℕ) + +open scoped Classical in +theorem weight_at (t : S.Pin r → Bool) (v : G.V) : + S.table r (p.vertex v) (t ∘ S.port r (p.vertex v)) = + G.weight v (t ∘ p.toSeating.ends ∘ .inl) (t ∘ p.toSeating.ends ∘ .inr) := by + rw [p.sample] + change Transcript.sample _ _ = Transcript.sample _ (fun j => t (p.toSeating.ends (G.portEquiv ⟨v, + j⟩))) + apply congrArg (Transcript.sample _) + funext i + exact congrArg t (p.toSeating.ends_at v i).symm + +open scoped Classical in +/-- In the case `.inl (.inl i)`, this construction gives `.inl (i.map id .inl)`. -/ +def reorder (X Y E U : Type) : + ((X ⊕ E) ⊕ (Y ⊕ E)) ⊕ (U × Bool) ≃ (X ⊕ E ⊕ U) ⊕ (Y ⊕ E ⊕ U) where + toFun + | .inl (.inl i) => .inl (i.map id .inl) + | .inl (.inr i) => .inr (i.map id .inl) + | .inr (i, false) => .inl (.inr (.inr i)) + | .inr (i, true) => .inr (.inr (.inr i)) + invFun + | .inl (.inl i) => .inl (.inl (.inl i)) + | .inl (.inr (.inl i)) => .inl (.inl (.inr i)) + | .inl (.inr (.inr i)) => .inr (i, false) + | .inr (.inl i) => .inl (.inr (.inl i)) + | .inr (.inr (.inl i)) => .inl (.inr (.inr i)) + | .inr (.inr (.inr i)) => .inr (i, true) + left_inv := by rintro (((_|_)|(_|_))|⟨_, _|_⟩) <;> rfl + right_inv := by rintro ((_|_|_)|(_|_|_)) <;> rfl + +open scoped Classical in +/-- Reindexes `G.End ⊕ (G.PadExtra R × Bool)` and `(G.pad R).End` by an equivalence. -/ +def combine : G.End ⊕ (G.PadExtra R × Bool) ≃ (G.pad R).End := + (reorder _ _ _ _).trans (((Equiv.refl _).sumCongr (G.padBits R)).sumCongr + ((Equiv.refl _).sumCongr (G.padBits R))) + +open scoped Classical in +/-- Reindexes `(G.pad R).End` and `(S.padded R).Pin r` by an equivalence. -/ +def padEnds : (G.pad R).End ≃ (S.padded R).Pin r := + (combine R).symm.trans ((p.toSeating.ends.sumCongr (p.adds hd hr R)).trans (S.padPins r R)) + +open scoped Classical in +theorem pad_old (i : G.End) : + p.padEnds hd hr R (G.insertEnds R i) = S.liftPad r R false (p.toSeating.ends i) := by + have h : G.insertEnds R i = combine R (.inl i) := by rcases i with (_|_)|(_|_) <;> rfl + simp only [padEnds, h, Equiv.trans_apply, Equiv.symm_apply_apply] + rfl + +open scoped Classical in +theorem pad_extra (i : G.PadExtra R) (t : Bool) : + p.padEnds hd hr R (endOf (G.pad R) (G.padBits R (.inr i)) t) = + S.liftPad r R true (p.adds hd hr R (i, t)) := by + have h : endOf (G.pad R) (G.padBits R (.inr i)) t = combine R (.inr (i, t)) := by cases t <;> rfl + simp only [padEnds, h, Equiv.trans_apply, Equiv.symm_apply_apply] + rfl + +open scoped Classical in +private theorem pad_cases (q : (G.pad R).End) : + (∃ i, G.insertEnds R i = q) ∨ (∃ i t, endOf (G.pad R) (G.padBits R (.inr i)) t = q) := by + obtain ⟨i|⟨i, t⟩, rfl⟩ := (combine R).surjective q + · exact .inl ⟨i, by rcases i with (_|_)|(_|_) <;> rfl⟩ + · exact .inr ⟨i, t, by cases t <;> rfl⟩ + +open scoped Classical in +theorem pad_station (i : (G.pad R).End) : (p.padEnds hd hr R i).1.1 + = p.vertex ((G.pad R).station i) := by + rcases pad_cases R i with ⟨q, rfl⟩|⟨q, t, rfl⟩ + · rw [pad_old] + have he : (G.pad R).station (G.insertEnds R q) = G.station q := by + rcases q with (_|_)|(_|_) <;> rfl + rw [he]; exact p.end_station q + · rw [pad_extra] + have he : (G.pad R).station (endOf (G.pad R) (G.padBits R (.inr q)) t) = node q.1 t := by + cases t <;> rfl + rw [he]; exact p.dock_at q t + +open scoped Classical in +theorem pad_direction (i : (G.pad R).End) : (S.padded R).direction r (p.padEnds hd hr R i).1 + = i.isRight := by + rcases pad_cases R i with ⟨q, rfl⟩|⟨q, t, rfl⟩ + · rw [pad_old, liftPad, direction_pad, hd] + cases q <;> rfl + · rw [pad_extra, liftPad, direction_pad] + change S.direction r (p.dock q t) = _ + rw [dock, p.dir_tip hd] + cases t <;> rfl + +open scoped Classical in +theorem clear_iff (v : G.V) (t : (S.padded R).Pin r → Bool) : + S.clear r R (p.vertex v) t ↔ G.legal R v (t ∘ p.padEnds hd hr R) := by + have eq (i : G.PadExtra R) (b : Bool) : + (t ∘ p.padEnds hd hr R) (endOf (G.pad R) (G.padBits R (.inr i)) b) = + t (S.liftPad r R true (p.adds hd hr R (i, b))) := congrArg t (p.pad_extra hd hr R i b) + constructor + · intro h + have hu (i : G.PadExtra R) (b : Bool) (hi : node i.1 b = v) := + (eq i b).trans (h _ ((p.dock_at i b).trans (congrArg p.vertex hi))) + exact ⟨fun i => hu i false, fun i => hu i true⟩ + · intro h j hj + obtain ⟨⟨i, b⟩, rfl⟩ := (p.adds hd hr R).surjective j + have he := p.vertex.injective ((p.dock_at i b).symm.trans hj) + rw [← eq] + cases b + · exact h.1 i he + · exact h.2 i he + +variable (hn : ∀ i, G.source i ≠ G.target i) + +open scoped Classical in +/-- Builds `Sphere.Print.Seating (S.padded R) r (G.pad R) where vertex` with the specified +`vertex`, `ends`, `station`, `value`. -/ +def padSeat : Sphere.Print.Seating (S.padded R) r (G.pad R) where + vertex := p.vertex + ends := p.padEnds hd hr R + station := p.pad_station hd hr R + value t v := by + rw [S.table_pad] + change _ = (G.pad R).weight v ((t ∘ p.padEnds hd hr R) ∘ .inl) ((t ∘ p.padEnds hd hr R) ∘ .inr) + rw [G.pad_weight R v _ hn, ← p.clear_iff hd hr R] + split + · have he : p.padEnds hd hr R ∘ G.insertEnds R = S.liftPad r R false ∘ p.toSeating.ends := + funext (p.pad_old hd hr R) + simpa only [Function.comp_assoc, ← Function.comp_assoc (p.padEnds hd hr R), he] using + p.weight_at (t ∘ S.liftPad r R false) v + · rfl + empty v hv t := by + have hz (s : B S.e) : ¬0 < S.width r (v, s) := fun h => hv (p.cover ⟨(v, s), ⟨0, h⟩⟩) + unfold table pattern padded Pattern.padded + dsimp only + split + · exact p.vacant v hv (fun i => t ⟨Pattern.tag S.e (false, i.1), + i.2.cast (S.width_pad r R false (v, i.1)).symm⟩) + · rename_i h + exact (h (fun s i => (hz s (extra_pos (S := S) (r := r) (R := R) (a := (v, + s)) i.pos).1).elim)).elim + +open scoped Classical in +theorem padded_outside (q : slots x ⊕ slots y) : + (S.padded R).peer r (p.padEnds hd hr R (boundaryEnd (G.pad R) q)).1 = none := by + have he : boundaryEnd (G.pad R) q = G.insertEnds R (boundaryEnd G q) := by cases q <;> rfl + rw [he, pad_old, liftPad, peer_pad, (p.no_peer _).mpr ⟨q, rfl⟩] + rfl + +open scoped Classical in +/-- Builds `(S.padded R).Presentation r (G.pad R) where toSeating` with the specified +`toSeating`, `proper`, `input`, `output`. -/ +def pad : (S.padded R).Presentation r (G.pad R) where + toSeating := (p.padSeat hd hr R hn).seat + proper := S.proper_pad r R p hd hr + input i := by rw [Sphere.Print.Seating.ends_eq]; exact p.padded_outside hd hr R (.inl i) + output i := by rw [Sphere.Print.Seating.ends_eq]; exact p.padded_outside hd hr R (.inr i) + internal i := by + rw [Sphere.Print.Seating.ends_eq] + obtain ⟨z|j, rfl⟩ := (G.padBits R).surjective i + · change (S.padded R).Joins r (p.padEnds hd hr R (G.insertEnds R (.inl (.inr z)))) + (p.padEnds hd hr R (G.insertEnds R (.inr (.inr z)))) + rw [pad_old, pad_old] + refine ⟨?_, (p.internal z).2⟩ + rw [liftPad, peer_pad, (p.internal z).1] + rfl + · change (S.padded R).Joins r (p.padEnds hd hr R (endOf _ (G.padBits R (.inr j)) false)) + (p.padEnds hd hr R (endOf _ (G.padBits R (.inr j)) true)) + rw [pad_extra, pad_extra] + refine ⟨?_, rfl⟩ + change (S.padded R).peer r (S.seatPad R true (p.dock j false)) + = some (S.seatPad R true (p.dock j true)) + rw [peer_pad, dock, (p.link_tip _ false).1] + rfl + +open scoped Classical in +theorem pad_ends : (p.pad hd hr R hn).toSeating.ends = p.padEnds hd hr R := + (p.padSeat hd hr R hn).ends_eq + +open scoped Classical in +theorem pad_directed : (p.pad hd hr R hn).Directed := by + intro t + rw [p.pad_ends] + exact p.pad_direction hd hr R t + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- +# Short records for a group of stations + +A record contains the old labels, the bin numbers, and remote +addresses expressed relative to the child host. Bin zero holds the +exterior identities. A row with bin number zero is inactive. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel +open Coloring + +variable {F : Type} {m d h k e u : ℕ} + +open scoped Classical in +/-- Computes the destination by the application `Format.pair (.addr d) (.pair (.addr k) (.addr +u))`. -/ +abbrev destination (d k u : ℕ) := Format.pair (.addr d) (.pair (.addr k) (.addr u)) + +open scoped Classical in +/-- The value specified by `Format.pair (.addr k) (.pair (.addr S.ℓ) (.vec S.e (destination d k +u)))`. -/ +abbrev entry (S : Scheme F) (d k u : ℕ) := + Format.pair (.addr k) (.pair (.addr S.ℓ) (.vec S.e (destination d k u))) + +open scoped Classical in +/-- Computes the record by the application `Format.vec u (entry S d k u)`. -/ +abbrev record (S : Scheme F) (d k u : ℕ) := Format.vec u (entry S d k u) + +open scoped Classical in +theorem width (S : Scheme F) (d k u : ℕ) : + (record S d k u).width = 2 ^ u * (k + (S.ℓ + 2 ^ S.e * (d + (k + u)))) := by + simp [record, entry, destination] + +open scoped Classical in +/-- Indexes the index by the coordinates of `Bool × B u × B e`. -/ +abbrev Index (u e : ℕ) := Bool × B u × B e + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def index (u e : ℕ) : Index u e ≃ B (u + e + 1) := Fintype.equivOfCardEq (by simp [Index, + pow_succ', pow_add]) + +variable (S : Scheme F) (w : (record S d k u).obj) + +open scoped Classical in +/-- The value specified by `(w i).1`. -/ +abbrev slot (i : B u) := (w i).1 +open scoped Classical in +/-- Computes the label by the application `S.decode (w i).2.1`. -/ +abbrev label (i : B u) := S.decode (w i).2.1 +open scoped Classical in +/-- The value specified by `(label S w i).peer 0 s = none`. -/ +abbrev external (i : B u) (s : B S.e) := (label S w i).peer 0 s = none + +open scoped Classical in +/-- Requires `slot S w i ≠ 0 ∧ ((j = 0 ∧ external S w i s) ∨ (j = slot S w i ∧ b = false))`. -/ +def accepts (j : B k) (b : Bool) (i : B u) (s : B S.e) : Prop := + slot S w i ≠ 0 ∧ ((j = 0 ∧ external S w i s) ∨ (j = slot S w i ∧ b = false)) + +open scoped Classical in +/-- Returns `(label S w p.2.1).width 0 p.2.2` when `accepts S w j p.1 p.2.1 p.2.2` holds, and +`0` otherwise. -/ +def length (j : B k) (p : Index u S.e) := + if accepts S w j p.1 p.2.1 p.2.2 then (label S w p.2.1).width 0 p.2.2 else 0 + +open scoped Classical in +/-- In the case `none`, this construction gives `some (0, 0, index _ _ (true, i, s))`. -/ +def link (j : B k) (p : Index u S.e) : Option (B d × B k × B (u + S.e + 1)) := + if 0 < length S w j p then + let i := p.2.1 + let s := p.2.2 + if j = 0 then + if p.1 then some (0, slot S w i, index _ _ (false, i, s)) else none + else match (label S w i).peer 0 s with + | none => some (0, 0, index _ _ (true, i, s)) + | some t => + let v := (w i).2.2 s + some (v.1, v.2.1, index _ _ (false, v.2.2, t.2.2)) + else none + +open scoped Classical in +/-- The construction uses `(label S w p.2.1).direction 0 p.2.2` for its intermediate `b`. -/ +def side (p : Index u S.e) := + let b := (label S w p.2.1).direction 0 p.2.2 + cond p.1 (!b) b + +open scoped Classical in +/-- Computes the size by the application `length S w j ((index _ _).symm s)`. -/ +abbrev size (j : B k) (s : B (u + S.e + 1)) := length S w j ((index _ _).symm s) + +open scoped Classical in +/-- The construction uses `index _ _ (b, i, s)` for its intermediate `a`. -/ +def read (j : B k) (t : ∀ s, Fin (size S w j s) → Bool) (b : Bool) (i : B u) (s : B S.e) (l : ℕ) := + let a := index _ _ (b, i, s) + if h : l < size S w j a then t a ⟨l, h⟩ else false + +variable [Field F] + +open scoped Classical in +/-- The factor of type `F` for the given inputs. -/ +def factor (j : B k) (t : Bool → B u → B S.e → ℕ → Bool) (i : B u) : F := + if slot S w i = 0 then 1 else + if j = 0 then + if ∀ s, external S w i s → ∀ l : Fin ((label S w i).width 0 s), t false i s l = t true i s l + then 1 else 0 + else if j = slot S w i then (label S w i).value 0 (fun s l => t false i s l) else 1 + +open scoped Classical in +/-- Builds `Pattern F d k (u + S.e + 1) where width` with the specified `width`, `direction`, +`peer`, `value`. -/ +def pattern : Pattern F d k (u + S.e + 1) where + width := size S w + direction _ s := side S w ((index _ _).symm s) + peer j s := link S w j ((index _ _).symm s) + value j t := ∏ i, factor S w j (read S w j t) i + +open scoped Classical in +/-- The quantity computed by `m d := d h := h k := k e := u + S.e + 1`. -/ +abbrev scheme (m d h k u : ℕ) : Scheme F where + m := m + d := d + h := h + k := k + e := u + S.e + 1 + ℓ := (record S d k u).width + decode i := pattern S ((record S d k u).serial.symm i) + +open scoped Classical in +/-- Computes the frame by the application `Fmt.rows m d h (record S d k u)`. -/ +abbrev Frame (S : Scheme F) (m d h k u : ℕ) := Fmt.rows m d h (record S d k u) + +open scoped Classical in +/-- Maps the coordinate `i` to `((r i).1, fun j => (record S d k u).serial ((r i).2 j))`. -/ +def encode (r : (Frame S m d h k u).obj) : (scheme S m d h k u).format.obj := + fun i => ((r i).1, fun j => (record S d k u).serial ((r i).2 j)) + +open scoped Classical in +theorem pattern_encode (r : (Frame S m d h k u).obj) (v : (scheme S m d h k u).Vtx) : + (scheme S m d h k u).pattern (encode S r) v = pattern S ((r v.1).2 v.2.1) := by + simp only [Scheme.pattern, scheme, encode, Equiv.symm_apply_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Rate/Network.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Rate/Network.lean new file mode 100644 index 0000000000..7547e5e3fe --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Rate/Network.lean @@ -0,0 +1,984 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Status +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.ChildPaths +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access + +/-! +# Transmitting the grouped sheets + +The election reads short counters. One additional exchange carries +all block sheets as a single record per host. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) +local notation "n" => D.scheme.h - a +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "q" => ((d + 1) * n) +local notation "Bin" => D.Binning a H T R θ + +open scoped Classical in +/-- The quantity computed by `Format.vec (m + a) (Group.Labels n)`. -/ +abbrev Elected (_ : Bin) := Format.vec (m + a) (Group.Labels n) +open scoped Classical in +/-- Computes the stack by the application `Format.vec a (D.Sheet n)`. -/ +abbrev stack (_ : Bin) := Format.vec a (D.Sheet n) +open scoped Classical in +/-- Computes the bank by the application `Fmt.bank m d b.stack`. -/ +abbrev Bank := Fmt.bank m d b.stack +open scoped Classical in +/-- Computes the remote by the application `Format.vec m (.vec d b.stack)`. -/ +abbrev Remote := Format.vec m (.vec d b.stack) +open scoped Classical in +/-- The quantity computed by `(H : ℝ) * T / 2`. -/ +abbrev cutoff (_ : Bin) := (H : ℝ) * T / 2 + +open scoped Classical in +/-- Computes the tag keys by the application `Group.keys F q n D.count 5 5 (D.relative 1 +b.cutoff)`. -/ +def tagKeys := Group.keys F q n D.count 5 5 (D.relative 1 b.cutoff) +open scoped Classical in +/-- Computes the tag arity by the application `Group.arity q n D.count`. -/ +abbrev tagArity (_ : Bin) := Group.arity q n D.count +open scoped Classical in +/-- The value specified by `(Group.Parcel d a n D.count).width`. -/ +abbrev tagCap (_ : Bin) := (Group.Parcel d a n D.count).width +open scoped Classical in +/-- The quantity computed by `m + q`. -/ +abbrev tagDepth (_ : Bin) := m + q +open scoped Classical in +/-- The quantity computed by `m + d`. -/ +abbrev sheetDepth (_ : Bin) := m + d + +open scoped Classical in +/-- The pre bank of type `b.Bank.obj`, constructed using `D.position a b.ha.le l j`. -/ +def preBank (s : (D.format.pair b.Elected).obj) : b.Bank.obj := fun i => + (D.nav s.1 i, fun l j => + let t := D.position a b.ha.le l j + ((s.1.1 i).2 t, D.counter s.1 i t, s.2 ((Match.rowIndex m a).symm (i, l)) j)) + +open scoped Classical in +private theorem preBank_net : + Circuit F (D.format.pair b.Elected) b.Bank b.preBank ((D.format.pair b.Elected).width + + 2 * b.Bank.width) := by + let f : b.Bank.pins → (D.format.pair b.Elected).pins + | (i, .inl h) => .inl (.inl (i, .inl h)) + | (i, .inr (l, j, .inl h)) => .inl (.inl (i, .inr (D.position a b.ha.le l j, h))) + | (i, .inr (l, j, .inr (.inl h))) => .inl (.inr (i, .inr (.inr (D.position a b.ha.le l j, h)))) + | (i, .inr (l, j, .inr (.inr h))) => .inr ((Match.rowIndex m a).symm (i, l), j, h) + apply Circuit.project f + rintro x ⟨i, h|⟨l, j, h|h|h⟩⟩ <;> rfl + +open scoped Classical in +/-- Evaluates `(D.nav s i, D.sheet a b.ha 5 H T s i)` at the input `i`. -/ +def bank (s : D.format.obj) : b.Bank.obj := fun i => (D.nav s i, D.sheet a b.ha 5 H T s i) +open scoped Classical in +/-- The value specified by `(b.bank s, Fmt.gather b.stack (b.bank s))`. -/ +def banks (s : D.format.obj) : (b.Bank.pair b.Remote).obj := (b.bank s, + Fmt.gather b.stack (b.bank s)) + +open scoped Classical in +/-- The bank cost used in the `Binning` construction. -/ +def bankCost (p t : ℕ) := + 100 * (D.format.width + (D.groupInput a).width + b.Elected.width + b.Bank.width) + + Group.patchCost m d a n D.count b.tagCap p + Group.cost (m + a) q n D.count + + gatherCost m d b.stack.width t + +variable {u p t : ℕ} {L : Set (Table F)} {I : Type*} + +open scoped Classical in +theorem banks_net (hu : 3 ≤ u) (hg : Access F u L b.tagDepth b.tagCap p) + (hs : Access F u L b.sheetDepth b.stack.width t) + (ha : b.tagArity ≤ u) (hk : (b.tagKeys : Set _) ⊆ L) (X : I → D.format.obj) + (recip : ∀ i, Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) (X i).1) : + Computes F u L D.format (b.Bank.pair b.Remote) X (b.banks ∘ X) (fun _ => 1) (b.bankCost p t) + := by + let Y := D.groups a b.ha.le ∘ X + have prep := Computes.of_map (x := X) (y := Y) (Map.circuit (L + := L) hu (D.groups_circuit a b.ha.le)) + (fun _ => rfl) + have elect := prep.comp (Group.labels_net hu (Nat.sub_pos_of_lt b.ha) hg le_rfl Y recip ha hk) + let Z := b.bank ∘ X + have keep := Computes.of_map (x := X) (y := X) (Map.circuit (L + := L) hu (Circuit.id F D.format)) (fun _ => rfl) + have get := (keep.pair hu elect).comp + (Computes.of_map (y := Z) (Map.circuit hu b.preBank_net) (fun _ => rfl)) + have back := Computes.of_map (x := Z) (y := Z) (Map.circuit (L + := L) hu (Circuit.id F b.Bank)) (fun _ => rfl) + have all := get.comp (back.pair hu (gather_neighbors b.stack hu hs le_rfl Z recip)) + simp only [one_mul] at all + refine all.mono ?_ + unfold bankCost + rw [Format.width_pair D.format b.Elected] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- # Preparing common navigation data for short lookups -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) +local notation "n" => D.scheme.h - a +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "M" => D.childM a +local notation "e" => D.childD a 5 +local notation "Bin" => D.Binning a H T R θ + +open scoped Classical in +/-- Computes the nav by the application `Neighborhood.Rows M e`. -/ +abbrev Nav (_ : Bin) := Neighborhood.Rows M e +open scoped Classical in +/-- The quantity computed by `Neighborhood.Rows m (d + 1)`. -/ +abbrev Prior (_ : Bin) := Neighborhood.Rows m (d + 1) +open scoped Classical in +/-- The quantity computed by `Neighborhood.Mask m ((d + 1) + (n + 1)) e`. -/ +abbrev Mask (_ : Bin) := Neighborhood.Mask m ((d + 1) + (n + 1)) e + +open scoped Classical in +/-- Evaluates `let q := (Pattern.tag d).symm j if q.1 then v else D.nav s v q.2` at the input `v +j`. -/ +def prior (s : D.format.obj) : b.Prior.obj := fun v j => + let q := (Pattern.tag d).symm j + if q.1 then v else D.nav s v q.2 + +omit [Field F] in +open scoped Classical in +theorem prior_self (s : D.format.obj) (v : B m) : b.prior s v (Pattern.tag d (true, 0)) = v := by + simp [prior] + +omit [Field F] in +open scoped Classical in +theorem prior_peer (s : D.format.obj) (v : B m) (j : B d) : + b.prior s v (Pattern.tag d (false, j)) = D.nav s v j := by simp [prior] + +open scoped Classical in +/-- The value specified by `Child.mask (b.prior s) (D.binNav a b.ha 5 s)`. -/ +def mask (s : D.format.obj) : b.Mask.obj := Child.mask (b.prior s) (D.binNav a b.ha 5 s) +open scoped Classical in +/-- The value specified by `(D.binNav a b.ha 5 s, b.mask s)`. -/ +def links (s : D.format.obj) : (b.Nav.pair b.Mask).obj := (D.binNav a b.ha 5 s, b.mask s) + +open scoped Classical in +private theorem prior_net : Circuit F D.format b.Prior b.prior (D.format.width + + 34 * b.Prior.width) := by + have hd : Install.Depends (b.Prior.code ∘ b.prior ∘ D.format.code.symm) 1 := by + rintro ⟨v, j, i⟩ + obtain ⟨⟨f, k⟩, rfl⟩ := (Pattern.tag d).surjective j + cases f + · let t : D.format.pins := .inl (v, .inl (k, i)) + refine ⟨{t}, by simp, fun x y he => ?_⟩ + change (Format.addr m).code (b.prior (D.format.code.symm x) v (Pattern.tag d (false, k))) i = + (Format.addr m).code (b.prior (D.format.code.symm y) v (Pattern.tag d (false, k))) i + rw [prior_peer, prior_peer] + exact (congrFun (D.format.code.apply_symm_apply x) t).trans + ((he t (by simp)).trans (congrFun (D.format.code.apply_symm_apply y) t).symm) + · refine ⟨∅, by simp, fun x y _ => ?_⟩ + change (Format.addr m).code (b.prior (D.format.code.symm x) v (Pattern.tag d (true, k))) i = + (Format.addr m).code (b.prior (D.format.code.symm y) v (Pattern.tag d (true, k))) i + simp only [prior, Equiv.symm_apply_apply, ite_true] + exact hd.bnet F + +open scoped Classical in +/-- The quantity computed by `M + 2 ^ ((d + 1) + (n + 1)) + 2 ^ e`. -/ +abbrev precision (_ : Bin) := M + 2 ^ ((d + 1) + (n + 1)) + 2 ^ e +open scoped Classical in +/-- The quantity computed by `12 * D.format.width + 34 * b.Prior.width + 2 * (D.navCost a e) + 2 +^ M * (100 + b.precision) ^ 40`. -/ +def linkCost := 12 * D.format.width + 34 * b.Prior.width + 2 * (D.navCost a e) + 2 ^ M * (100 + + b.precision) ^ 40 + +open scoped Classical in +theorem links_net : Circuit F D.format (b.Nav.pair b.Mask) b.links b.linkCost := by + have nav : Circuit F D.format b.Nav (D.binNav a b.ha 5) (D.navCost a e) + := D.nav_net a b.ha.le false 5 + have hm : M ≤ b.precision := (Nat.le_add_right _ _).trans (Nat.le_add_right _ _) + have hp : 2 ^ ((d + 1) + (n + 1)) ≤ b.precision + := (Nat.le_add_left _ _).trans (Nat.le_add_right _ _) + have hq : 2 ^ e ≤ b.precision := Nat.le_add_left _ _ + obtain ⟨k, hk, hc⟩ := Child.cheap_mask F («m» := m) («e» := n + 1) hm hp hq + have h : k ≤ 2 ^ M * (100 + b.precision) ^ 40 := (Nat.le_add_left _ _).trans hc + refine (nav.pair ((b.prior_net.pair nav).comp hk)).mono ?_ + unfold linkCost + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- # Cost of writing host status and direct adjacency flags -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) +local notation "n" => D.scheme.h - a +local notation "m" => b.target.m +local notation "d" => b.target.d +local notation "N" => D.scheme.d + Child.width n 5 +local notation "t" => (m + 2 ^ d) +local notation "cost" => D.navCost a d + +open scoped Classical in +private theorem small : 2 ^ N ≤ 2 ^ d := + Nat.pow_le_pow_right (by decide) (by change N ≤ (N + 1) * 3; omega) + +open scoped Classical in +private theorem charge (x : ℕ) (hx : x ≤ (100 + t) ^ 201) : 2 ^ m * x ≤ cost := + (Nat.mul_le_mul_left _ hx).trans (Nat.le_add_left _ _) + +open scoped Classical in +theorem flags_bound : b.Flags.width ≤ cost := by + rw [Flags, Format.width_vec, Format.width_pair, Format.width_vec, Format.width_bit, mul_one] + refine b.charge _ ((show 1 + 2 ^ d ≤ 100 + t by omega).trans ?_) + exact Nat.le_self_pow (by decide) _ + +open scoped Classical in +private theorem step_bound : (Neighborhood.Rows m N).width ≤ cost := by + rw [Neighborhood.Rows, Format.width_vec, Format.width_vec, Format.width_addr] + have hp := Nat.zero_le (2 ^ d) + refine b.charge _ (le_trans ?_ (Nat.pow_le_pow_right (by omega) (by decide : 2 ≤ 201))) + rw [pow_two] + exact Nat.mul_le_mul (b.small.trans (by omega)) (by omega) + +open scoped Classical in +private theorem step_net : Circuit F D.format (Neighborhood.Rows m N) b.step (100 * cost) := by + have start := (D.groups_circuit a b.ha.le).comp (Child.fromGroup_circuit F false) + have walk : Circuit F (Child.Input D.scheme.m D.scheme.d) (Neighborhood.Rows m N) (Child.step n 5) + ((Child.Input D.scheme.m D.scheme.d).width + 68 * (Neighborhood.Rows m N).width) := + Child.step_depends.bnet F + refine (start.comp walk).mono ?_ + have h := b.step_bound + unfold Template.navCost Template.groupInput at h ⊢ + omega + +open scoped Classical in +private abbrev Adj := Format.vec m (.vec d .bit) +open scoped Classical in +private abbrev Raw := (D.Status a).pair b.Adj +open scoped Classical in +private def pair (x : b.Raw.obj) : b.Flags.obj := fun v => (x.1 v, x.2 v) + +open scoped Classical in +private theorem pair_net : Circuit F b.Raw b.Flags b.pair (3 * b.Flags.width) := by + have h : Circuit F b.Raw b.Flags b.pair (b.Raw.width + 2 * b.Flags.width) := by + apply Circuit.project (fun (j : b.Flags.pins) => Sum.map (fun i => (j.1, i)) (fun i => (j.1, + i)) j.2) + rintro x ⟨i, j|j⟩ <;> rfl + have he : b.Raw.width = b.Flags.width := by + change (Format.pair (.vec m .bit) (.vec m (.vec d .bit))).width = _ + simp only [Flags, Format.width_pair, Format.width_vec, mul_add] + exact h.mono (by omega) + +open scoped Classical in +theorem status_net : Circuit F D.format b.Flags b.status (200 * cost) := by + have hnav : Circuit F D.format (Neighborhood.Rows m d) (D.binNav a b.ha 5) cost := + D.nav_net a b.ha.le false 5 + obtain ⟨s, g, hg⟩ := Child.cheap_coreFlags F (Nat.le_add_right m (2 ^ d)) (Nat.le_add_left (2 ^ + d) m) + (b.small.trans (Nat.le_add_left _ _)) + have hb : s ≤ cost := (le_trans (Nat.le_add_left _ _) hg).trans + (b.charge _ (Nat.pow_le_pow_right (by positivity) (by decide))) + have ha := (hnav.pair b.step_net).comp (g.mono hb) + have hh := ((D.status_net a).pair ha).comp b.pair_net + have h₁ : (D.Status a).width ≤ b.Flags.width := by + change (Format.vec m .bit).width ≤ _ + simp only [Flags, Format.width_pair, Format.width_vec] + exact Nat.mul_le_mul_left _ (Nat.le_add_right ..) + have h₂ := b.flags_bound + have h₃ : D.format.width ≤ cost := by unfold navCost; omega + have eq : b.pair ∘ (fun i => (D.childLive a i, + Child.coreFlags (D.binNav a b.ha 5 i) (b.step i))) = b.status := by + funext i v; simp only [Function.comp_apply, pair, status] + rw [← eq] + simp only [Function.comp_def] at hh ⊢ + refine hh.mono ?_ + unfold Template.statusCost + have same : cost = D.navCost a (D.childD a 5) := rfl + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- # One standardized local lookup per child occurrence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring BatchDescent + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) +local notation "n" => D.scheme.h - a +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "M" => D.childM a +local notation "e" => D.childD a 5 +local notation "Bin" => D.Binning a H T R θ +local notation "orig" => Match.rowIndex m (n + 1) +local notation "pre" => Equiv.symm (Match.rowIndex (d + 1) (n + 1)) + +open scoped Classical in +/-- The value specified by `(b.Bank.pair b.Remote).pair (b.Nav.pair b.Mask)`. -/ +abbrev View := (b.Bank.pair b.Remote).pair (b.Nav.pair b.Mask) +open scoped Classical in +/-- The tile used in the `Binning` construction. -/ +abbrev Tile (_ : Bin) := + Format.pair (.addr (n + 1)) (.pair (.addr a) (.pair (D.Sheet n) + (.pair (.vec d (D.Sheet n)) (.vec d (.vec (n + 1) (.vec e .bit)))))) +open scoped Classical in +/-- The value specified by `Format.pair (.addr b.target.ℓ) (.vec b.target.k (.vec b.target.e +(Trail.pointer D.scheme 0)))`. -/ +abbrev Fields := Format.pair (.addr b.target.ℓ) (.vec b.target.k (.vec b.target.e (Trail.pointer + D.scheme 0))) +open scoped Classical in +/-- Computes the rows by the application `Fmt.rows M e a`. -/ +abbrev Rows (_ : Bin) := Fmt.rows M e a +open scoped Classical in +/-- Computes the output by the application `b.target.format.pair (Trail.controls D.scheme +b.target 0)`. -/ +abbrev Output := b.target.format.pair (Trail.controls D.scheme b.target 0) + +open scoped Classical in +/-- The value specified by `(b.banks r, b.links r)`. -/ +def view (r : D.format.obj) : b.View.obj := (b.banks r, b.links r) + +open scoped Classical in +/-- The tiles of type `(b.Rows b.Tile).obj`, constructed using `(orig i).1`. -/ +def tiles (v : b.View.obj) : (b.Rows b.Tile).obj := fun i => + (v.2.1 i, fun l => + let j := (orig i).1 + let z := (orig i).2 + (z, l, (v.1.1 j).2 l, fun s => v.1.2 j s l, + fun s t k => v.2.2 j (pre (Pattern.tag d (true, 0), z)) k (pre (Pattern.tag d (false, s), + t)))) + +open scoped Classical in +/-- The label of type `B b.target.ℓ` for the given inputs. -/ +def label (v : b.Tile.obj) : B b.target.ℓ := + (Parcel.record D.scheme e (Sheet.slots H) b.depth).serial + (Sheet.record D v.2.2.1 H T b.pos b.depth e v.2.2.2.1 + (fun _ s t => Child.select (v.2.2.2.2 s t)) v.1) + +open scoped Classical in +/-- The indexed operation `(b.label v, fun i j => Trail.point D.scheme (b.marked v.2.2.1 v.1 +v.2.1 (b.label v) i j))`. -/ +def issue (v : b.Tile.obj) : b.Fields.obj := + (b.label v, fun i j => Trail.point D.scheme (b.marked v.2.2.1 v.1 v.2.1 (b.label v) i j)) + +open scoped Classical in +/-- The indexed operation `(fun i => ((s i).1, fun l => ((s i).2 l).1), fun i l => ((s i).2 +l).2)`. -/ +def deliver (s : (b.Rows b.Fields).obj) : b.Output.obj := + (fun i => ((s i).1, fun l => ((s i).2 l).1), fun i l => ((s i).2 l).2) + +open scoped Classical in +/-- The value specified by `(b.data s, (b.move s).commands)`. -/ +def result (s : D.format.obj) : b.Output.obj := (b.data s, (b.move s).commands) + +omit [Field F] in +open scoped Classical in +private theorem record_congr {v k : ℕ} (sheet : (D.Sheet v).obj) (u : ℕ) (hH : 0 < H) + (near : B D.scheme.d → (D.Sheet v).obj) (x y : B (v + 1) → B D.scheme.d → B (v + 1) → B k) + (z : B (v + 1)) (he : ∀ s t, x z s t = y z s t) : + Sheet.record D sheet H T hH u k near x z = Sheet.record D sheet H T hH u k near y z := by + funext i + unfold Sheet.record + cases h : Sheet.find D sheet u z i with + | none => rfl + | some j => + have ht := (Sheet.find_spec _ _ _ _ _ _ h).2.1 + refine Prod.ext rfl (Prod.ext rfl ?_) + change Sheet.target D sheet H T hH u k near x j = Sheet.target D sheet H T hH u k near y j + funext s + unfold Sheet.target + cases (D.scheme.decode (sheet j).1).peer 0 s with + | none => rfl + | some t => simp only [ht, he] + +open scoped Classical in +private theorem label_eq (r : D.format.obj) (i : B M) (l : B a) : + b.label ((b.tiles (b.view r) i).2 l) = (b.data r i).2 l := by + let y := orig i + let page := D.sheet a b.ha 5 H T r + let near := fun s => page (D.nav r y.1 s) l + let nav := D.binNav a b.ha 5 r + let raw := fun z s t => Child.index nav ((orig).symm (y.1, z)) ((orig).symm (D.nav r y.1 s, t)) + let short := fun (_ : B (n + 1)) s t => Child.select + (fun k => b.mask r y.1 (pre (Pattern.tag d (true, 0), y.2)) k (pre (Pattern.tag d (false, s), + t))) + have he (s : B d) (t : B (n + 1)) : short y.2 s t = raw y.2 s t := by + have h := Child.index_eq (b.prior r) nav y.1 (Pattern.tag d (true, 0)) (Pattern.tag d (false, + s)) y.2 t + rw [b.prior_self, b.prior_peer] at h + exact h.symm + let code := (Parcel.record D.scheme e (Sheet.slots H) b.depth).serial + simp only [label, tiles, view, banks, links, bank, Fmt.gather, data, frame, Parcel.encode, + childFrame] + change code (Sheet.record D (page y.1 l) H T b.pos b.depth e near short y.2) = + code (Sheet.record D (page y.1 l) H T b.pos b.depth e near raw y.2) + exact congrArg code (record_congr _ _ b.pos _ _ _ _ he) + +open scoped Classical in +theorem issued (r : D.format.obj) : + b.deliver (Fmt.update b.issue (b.tiles (b.view r))) = b.result r := by + simp only [deliver, Fmt.update, issue, result] + apply Prod.ext + · funext i + exact Prod.ext rfl (funext fun j => b.label_eq r i j) + · funext i l j s + let t := (b.tiles (b.view r) i).2 l + change Trail.point _ (b.marked t.2.2.1 t.1 t.2.1 (b.label t) j s) = _ + rw [show b.label t = _ from b.label_eq r i l] + simp only [move, Trail.Move.commands, t, tiles, view, banks, bank] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- # The network computing grouped labels and exterior predecessors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring BatchDescent + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) +local notation "n" => D.scheme.h - a +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "M" => D.childM a +local notation "e" => D.childD a 5 +local notation "Bin" => D.Binning a H T R θ +local notation "orig" => Match.rowIndex m (n + 1) +local notation "pre" => Equiv.symm (Match.rowIndex (d + 1) (n + 1)) + +open scoped Classical in +private theorem tiles_net : + Circuit F b.View (b.Rows b.Tile) b.tiles (b.View.width + 34 * (b.Rows b.Tile).width) := by + let X := b.View + let Y := b.Rows b.Tile + have h : Install.Depends (Y.code ∘ b.tiles ∘ X.code.symm) 1 := by + have pin (i : Y.pins) (j : X.pins) (he : ∀ t, Y.code (b.tiles t) i = X.code t j) : + ∃ s : Finset X.pins, s.card ≤ 1 ∧ ∀ x y, (∀ l ∈ s, x l = y l) → + (Y.code ∘ b.tiles ∘ X.code.symm) x i = (Y.code ∘ b.tiles ∘ X.code.symm) y i := by + refine ⟨{j}, by simp, fun x y h => ?_⟩ + simp only [Function.comp_apply, he, Equiv.apply_symm_apply] + exact h j (by simp) + rintro ⟨v, h|⟨l, i|j|k|⟨s, t⟩|⟨s, r, k, t⟩⟩⟩ + · exact pin _ (.inr (.inl (v, h))) fun _ => rfl + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + · exact pin _ (.inl (.inl ((orig v).1, .inr (l, k)))) fun _ => rfl + · exact pin _ (.inl (.inr ((orig v).1, s, l, t))) fun _ => rfl + · exact pin _ (.inr (.inr ((orig v).1, pre (Pattern.tag d (true, 0), (orig v).2), + k, pre (Pattern.tag d (false, s), r), t))) fun _ => rfl + exact h.bnet F + +open scoped Classical in +private theorem deliver_net : Circuit F (b.Rows b.Fields) b.Output b.deliver + ((b.Rows b.Fields).width + 2 * b.Output.width) := by + let f : b.Output.pins → (b.Rows b.Fields).pins + | .inl (v, .inl i) => (v, .inl i) + | .inl (v, .inr (l, j)) => (v, .inr (l, .inl j)) + | .inr (v, l, j) => (v, .inr (l, .inr j)) + apply Circuit.project f + rintro x (⟨_, _|_⟩|_) <;> rfl + +open scoped Classical in +/-- The indexed operation `weightTable b.issue (fun _ => 1)`. -/ +def gate : Table F := weightTable b.issue (fun _ => 1) +open scoped Classical in +/-- Computes the keys by the application `insert b.gate b.tagKeys`. -/ +def keys := insert b.gate b.tagKeys +open scoped Classical in +/-- The quantity computed by `b.tagArity + b.Tile.width + b.Fields.width`. -/ +def arity := b.tagArity + b.Tile.width + b.Fields.width + +open scoped Classical in +theorem card_keys : b.keys.card ≤ 3 := + (Finset.card_insert_le _ _).trans (Nat.succ_le_succ (Group.card_keys F)) + +open scoped Classical in +/-- The cost used in the `Binning` construction. -/ +def cost (p t : ℕ) := + 20 * D.format.width + b.bankCost p t + 4 * b.linkCost + 4 * (b.View.width + + 34 * (b.Rows b.Tile).width) + + updateCost M e a b.Tile b.Fields + 4 * ((b.Rows b.Fields).width + 2 * b.Output.width) + +variable {u p t : ℕ} {L : Set (Table F)} {I : Type*} + +open scoped Classical in +theorem computes (hu : 3 ≤ u) (hg : Access F u L b.tagDepth b.tagCap p) + (hs : Access F u L b.sheetDepth b.stack.width t) + (ha : b.arity ≤ u) (hk : (b.keys : Set _) ⊆ L) (X : I → D.format.obj) + (recip : ∀ i, Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) (X i).1) : + Computes F u L D.format b.Output X (b.result ∘ X) (fun _ => 1) (b.cost p t) := by + unfold arity at ha + have hb := b.banks_net hu hg hs (by omega) (fun _ h => hk (Finset.mem_insert_of_mem h)) X recip + have ht := Computes.of_map (L := L) (x := X) (y + := b.links ∘ X) (Map.circuit hu b.links_net) (fun _ => rfl) + let Y := b.tiles ∘ b.view ∘ X + have hi := (hb.pair hu ht).comp + (Computes.of_map (y := Y) (Map.circuit hu b.tiles_net) (fun _ => rfl)) + have update := computes_update b.issue (fun _ => (1 : F)) hu (by omega) + (hk (Finset.mem_insert_self _ _)) Y + have h := (hi.comp update).comp (Computes.of_map (y + := b.result ∘ X) (Map.circuit hu b.deliver_net) + (fun i => b.issued (X i))) + simp only [Fmt.weight, Function.comp_apply, Finset.prod_const_one, one_mul] at h + refine h.mono ?_ + unfold cost + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- +# Uniform bounds for preparing a contraction + +The index includes the coefficient field. Charges repeated in each +cell only use the short base. Host addresses and the minimum payload +charged by a routing price are included in the long base. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +open BatchDescent.Phase + +/-- The data for the case construction, including `F`, `[field`, `D`, `a`, `H`. -/ +structure Case where + /-- The `Case` component of type `Type`. -/ + F : Type + [field : Field F] + /-- The `Case` component of type `Template F`. -/ + D : Template F + /-- The left component. -/ + a : ℕ + /-- The `Case` field of type `ℕ`. -/ + H : ℕ + /-- The `Case` field of type `ℕ`. -/ + T : ℕ + /-- The `Case` field of type `ℕ`. -/ + R : ℕ + /-- The `Case` field of type `ℝ`. -/ + θ : ℝ + b : D.Binning a H T R θ + /-- The `Case` component of type `Rounds.Contraction.Prices F`. -/ + p : Rounds.Contraction.Prices F + /-- The `Case` field of type `ℕ`. -/ + t : ℕ + hd : D.scheme.d ≤ 4 + hk : D.scheme.k = 0 + +attribute [instance] Case.field + +namespace Case +variable (i : Case) +/-- Uses `i.D.scheme.m` as the representation. -/ +abbrev m := i.D.scheme.m +/-- Uses `i.D.scheme.h` as the representation. -/ +abbrev h := i.D.scheme.h +/-- The quantity computed by `i.h - i.a`. -/ +abbrev n := i.h - i.a +/-- Uses `i.D.scheme.d` as the representation. -/ +abbrev d := i.D.scheme.d +/-- The quantity computed by `(i.d + 1) * i.n`. -/ +abbrev q := (i.d + 1) * i.n +/-- The value specified by `1000000 + i.H + 2 ^ i.b.depth + i.D.scheme.ℓ + i.D.count + 2 ^ +i.D.scheme.e + i.h + 2 ^ i.n + i.p.W + i.t`. -/ +abbrev short := 1000000 + i.H + 2 ^ i.b.depth + i.D.scheme.ℓ + i.D.count + + 2 ^ i.D.scheme.e + i.h + 2 ^ i.n + i.p.W + i.t +/-- The quantity computed by `i.short + i.m + i.p.w + i.p.w ^ i.p.power`. -/ +abbrev long := i.short + i.m + i.p.w + i.p.w ^ i.p.power + +theorem parts : 2 ≤ i.short ∧ i.H ≤ i.short ∧ 2 ^ i.b.depth ≤ i.short ∧ + i.D.scheme.ℓ ≤ i.short ∧ i.D.count ≤ i.short ∧ 2 ^ i.D.scheme.e ≤ i.short ∧ + i.h ≤ i.short ∧ 2 ^ i.n ≤ i.short ∧ i.p.W ≤ i.short ∧ i.t ≤ i.short := by + unfold short + generalize 2 ^ i.b.depth = x, 2 ^ i.D.scheme.e = y, 2 ^ i.n = z + omega + +theorem short_two : 2 ≤ i.short := i.parts.1 +theorem short_long : i.short ≤ i.long := by unfold long; omega +theorem long_two : 2 ≤ i.long := i.short_two.trans i.short_long +end Case + +/-- Computes the short by the application `Poly Case.short`. -/ +abbrev Short := Poly Case.short +/-- Computes the long by the application `Poly Case.long`. -/ +abbrev Long := Poly Case.long + +/-- The condition `∃ k : ℕ, ∀ i, f i ≤ 2 ^ (j i) * i.long ^ k + 2 ^ (j i + i.h) * i.short ^ k` +on the specified data. -/ +abbrev Mixed (j f : Case → ℕ) : Prop := + MixedCost (fun i => i.long) (fun i => i.short) (fun i => i.h) j f + +/-- Computes the cost by the application `Mixed Case.m`. -/ +abbrev Cost := Mixed Case.m +/-- The indexed operation `Mixed (fun _ => 0)`. -/ +abbrev Row := Mixed (fun _ => 0) + +variable {j f g n : Case → ℕ} + +theorem Short.long (h : Short f) : Long f := h.grow Case.short_long +theorem short_const (k : ℕ) : Short (fun _ => k) := Poly.const Case.short_two k +theorem long_const (k : ℕ) : Long (fun _ => k) := Poly.const Case.long_two k + +namespace Mixed + +theorem mono (h : Mixed j f) (hg : ∀ i, g i ≤ f i) : Mixed j g := + MixedCost.mono h hg + +theorem add (h : Mixed j f) (h' : Mixed j g) : Mixed j (fun i => f i + g i) := + MixedCost.add h h' (fun i => i.long_two) (fun i => i.short_two) + +theorem mul (h : Mixed j f) (h' : Short g) : Mixed j (fun i => f i * g i) := + MixedCost.mul h h' (fun i => i.short_long) + +theorem left (h : Mixed j f) (h' : Short g) : Mixed j (fun i => g i * f i) := + (h.mul h').mono fun _ => le_of_eq (mul_comm ..) + +theorem scale (h : Mixed j f) (k : ℕ) : Mixed j (fun i => k * f i) := h.left (short_const k) + +theorem long (j : Case → ℕ) (h : Long f) : Mixed j (fun i => 2 ^ (j i) * f i) := + MixedCost.long j h + +theorem short (j : Case → ℕ) (h : Short f) : Mixed j (fun i => 2 ^ (j i + i.h) * f i) := + MixedCost.short j h + +end Mixed + +theorem Long.row (h : Long f) : Row f := by + simpa only [pow_zero, one_mul] using Mixed.long (fun _ => 0) h + +theorem Short.blocks (h : Short f) : Row (fun i => 2 ^ i.h * f i) := by + simpa only [zero_add] using Mixed.short (fun _ => 0) h + +theorem Short.groups (h : Short f) : Row (fun i => 2 ^ i.a * f i) := + h.blocks.mono (fun i => Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) i.b.ha.le)) + +theorem Row.hosts (h : Row f) : Cost (fun i => 2 ^ i.m * f i) := + MixedCost.hosts (fun i => i.m) h + +theorem Row.expand (h : Row f) (h' : Short (fun i => 2 ^ n i)) : + Cost (fun i => 2 ^ (i.m + n i) * f i) := by + simpa only [pow_add, mul_assoc] using Row.hosts (h.left h') + +theorem Row.cost (h : Row f) : Cost f := + h.hosts.mono fun _ => Nat.le_mul_of_pos_left _ (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +end + +/- # The short numerical parameters of a grouped step -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +open BatchDescent.Phase + +theorem bins : Short (fun i => i.H) := + Poly.of_le Case.short_two fun i => i.parts.2.1 + +theorem depths : Short (fun i => 2 ^ i.b.depth) := + Poly.of_le Case.short_two fun i => i.parts.2.2.1 + +theorem labels : Short (fun i => i.D.scheme.ℓ) := + Poly.of_le Case.short_two fun i => i.parts.2.2.2.1 + +theorem counters : Short (fun i => i.D.count) := + Poly.of_le Case.short_two fun i => i.parts.2.2.2.2.1 + +theorem spans : Short (fun i => 2 ^ i.D.scheme.e) := + Poly.of_le Case.short_two fun i => i.parts.2.2.2.2.2.1 + +theorem height : Short (fun i => i.h) := + Poly.of_le Case.short_two fun i => i.parts.2.2.2.2.2.2.1 + +theorem tiles : Short (fun i => 2 ^ i.n) := + Poly.of_le Case.short_two fun i => i.parts.2.2.2.2.2.2.2.1 + +theorem weights : Short (fun i => i.p.W) := + Poly.of_le Case.short_two fun i => i.parts.2.2.2.2.2.2.2.2.1 + +theorem payload : Short (fun i => i.t) := + Poly.of_le Case.short_two fun i => i.parts.2.2.2.2.2.2.2.2.2 + +theorem hosts : Long Case.m := Poly.of_le Case.long_two fun i => by unfold Case.long; omega + +theorem threshold : Long (fun i => i.p.w ^ i.p.power) := + Poly.of_le Case.long_two fun _ => Nat.le_add_left .. + +theorem groupHeight : Short Case.a := height.mono fun i => i.b.ha.le + +theorem slots : Short (fun i => 2 ^ i.d) := + (short_const (2 ^ 4)).mono fun i => Nat.pow_le_pow_right (by decide) i.hd + +theorem stations : Short (fun i => 2 ^ i.D.scheme.k) := by + refine (short_const 1).mono fun i => ?_ + simp only [i.hk, pow_zero, le_refl] + +theorem suffix : Short (fun i => 2 ^ (i.n + 1)) := + Poly.exp_add tiles (short_const 2) + +theorem path : Short (fun i => 2 ^ i.q) := by + refine (tiles.pow 5).mono fun i => ?_ + rw [← pow_mul, mul_comm i.n] + exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ (Nat.succ_le_succ i.hd)) + +theorem childSlots : Short (fun i => 2 ^ i.b.target.d) := by + have hw : Short (fun i => 2 ^ Child.width i.n 5) := + suffix.mono (fun i => Nat.pow_le_pow_right (by decide) (min_le_left ..)) + refine (((slots.exp_add hw).exp_add (g := fun _ => 1) (short_const 2)).pow 3).mono fun i => ?_ + rw [← pow_mul] + +theorem childHosts : Long (fun i => i.b.target.m) := hosts.add (Short.long suffix.of_exp) + +theorem childStations : Short (fun i => 2 ^ i.b.target.k) := + (bins.add (short_const 1)).exp_clog + +theorem childSpans : Short (fun i => 2 ^ i.b.target.e) := + ((depths.exp_add spans).exp_add (short_const 2)).exp_add (short_const 2) + +theorem childLabels : Short (fun i => i.b.target.ℓ) := by + have hk := childStations.of_exp + have hd := childSlots.of_exp + have hu := depths.of_exp + refine (depths.mul (hk.add (labels.add (spans.mul (hd.add (hk.add hu)))))).mono fun i => ?_ + change (Parcel.record i.D.scheme (i.D.childD i.a 5) (Sheet.slots i.H) i.b.depth).width ≤ _ + rw [Parcel.width] + +variable {f : Case → ℕ} +theorem Row.children (h : Row f) : Cost (fun i => 2 ^ i.b.target.m * f i) := + h.expand suffix + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +end + +/- # Local arities and replicated row widths -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +open BatchDescent Coloring + +theorem sheet : Short (fun i => (i.D.Sheet i.n).width) := by + refine (tiles.mul (labels.add (counters.add suffix.of_exp))).mono fun i => ?_ + rw [Template.sheet_width] + +theorem stack : Row (fun i => i.b.stack.width) := + sheet.groups.mono fun i => by rw [Binning.stack, Format.width_vec] + +theorem parcel : Row (fun i => i.b.tagCap) := by + have h := Short.groups (tiles.mul counters) + refine ((long_const 1).row.add ((Long.row (slots.long.mul (long_const 2))).add h)).mono fun i + => ?_ + simp only [Binning.tagCap, Group.Parcel, Group.Flags, Format.width_pair, Format.width_vec, + Format.width_addr] + rw [Format.width_bit] + +theorem patch : Short (fun i => (Group.Patch i.q i.n i.D.count).width) := by + refine ((short_const 1).add (path.mul ((path.mul (short_const 2)).add (tiles.mul + counters)))).mono fun i => ?_ + rw [Group.width_patch] + +theorem groupLabels : Short (fun i => (Group.Labels i.n).width) := by + refine (tiles.mul suffix.of_exp).mono fun i => ?_ + rw [Group.Labels, Format.width_vec, Format.width_addr] + +theorem tagArity : Short (fun i => i.b.tagArity) := by + have hs : Short (fun i => (Group.Summary i.n).width) := + (tiles.mul (tiles.of_exp.add (tiles.mul suffix.of_exp))).mono fun i + => by rw [Group.width_summary] + exact ((patch.add hs).add tiles.of_exp).add groupLabels + +theorem pointer : Short (fun i => (Trail.pointer i.D.scheme 0).width) := by + refine ((short_const 1).add ((short_const 0).add (height.add + (stations.of_exp.add spans.of_exp)))).mono fun i => ?_ + simp only [Trail.pointer, Format.width_pair, Format.width_addr] + rfl + +theorem fields : Short (fun i => i.b.Fields.width) := by + refine (childLabels.add (childStations.mul (childSpans.mul pointer))).mono fun i => ?_ + rw [Fields, Format.width_pair, Format.width_addr, Format.width_vec, Format.width_vec] + +theorem tile : Short (fun i => i.b.Tile.width) := by + have hf := slots.mul (suffix.mul (childSlots.mul (short_const 1))) + refine (suffix.of_exp.add (groupHeight.add (sheet.add ((slots.mul sheet).add hf)))).mono fun i + => ?_ + simp only [Tile, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_addr (i.D.scheme.h - i.a + 1), Format.width_bit] + +theorem arity : Short (fun i => i.b.arity) := (tagArity.add tile).add fields + +variable {A B : Case → Format} {f : Case → ℕ} + +theorem pair_cost (h : Cost (fun i => (A i).width)) (h' : Cost (fun i => (B i).width)) : + Cost (fun i => ((A i).pair (B i)).width) := + (h.add h').mono fun _ => (Format.width_pair _ _).le + +theorem rows (h : Short (fun i => (A i).width)) : Cost (fun i => (i.b.Rows (A i)).width) := + (Row.children ((Long.row (childSlots.long.mul childHosts)).add h.groups)).mono + fun _ => (Fmt.width_rows ..).le + +theorem targetFormat : Cost (fun i => i.b.target.format.width) := + rows (A := fun i => .addr i.b.target.ℓ) (childLabels.mono fun _ => (Format.width_addr _).le) + +theorem format : Cost (fun i => i.D.format.width) := by + have h : Cost (fun i => i.D.scheme.format.width) := by + refine (Row.hosts ((Long.row (slots.long.mul hosts)).add labels.blocks)).mono fun i => ?_ + rw [Scheme.format, Fmt.width_rows, Format.width_addr] + apply pair_cost h + have flags := Long.row (slots.long.mul (long_const 2)) + refine (Row.hosts ((long_const 2).row.add (flags.add counters.blocks))).mono fun i => ?_ + simp only [Template.header, Group.Flags, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit] + +theorem bankFmt (h : Row (fun i => (A i).width)) : + Cost (fun i => (Fmt.bank i.m i.d (A i)).width) := by + refine (Row.hosts ((Long.row (slots.long.mul hosts)).add h)).mono fun i => ?_ + rw [Fmt.bank, Format.width_vec, Format.width_pair, Format.width_vec, Format.width_addr] + +theorem bank : Cost (fun i => i.b.Bank.width) := bankFmt stack + +theorem groupInput : Cost (fun i => (i.D.groupInput i.a).width) := bankFmt parcel + +theorem remote : Cost (fun i => i.b.Remote.width) := + (Row.hosts (stack.left slots)).mono fun i => by rw [Remote, Format.width_vec, Format.width_vec] + +theorem output : Cost (fun i => i.b.Output.width) := by + apply pair_cost targetFormat + refine (Short.groups (childStations.mul (childSpans.mul pointer))).children.mono fun i => ?_ + rw [Trail.controls, Format.width_vec, Trail.localCommands, Format.width_vec, Format.width_vec, + Format.width_vec] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +end + +/- # Access, patch, and election costs -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +open Coloring + +/-- Computes the tag fee by the application `i.p.fee i.b.tagDepth i.b.tagCap`. -/ +abbrev Case.tagFee (i : Case) := i.p.fee i.b.tagDepth i.b.tagCap +/-- Computes the sheet fee by the application `i.p.fee i.b.sheetDepth i.b.stack.width`. -/ +abbrev Case.sheetFee (i : Case) := i.p.fee i.b.sheetDepth i.b.stack.width + +variable {j v : Case → ℕ} + +theorem fee (hj : Short (fun i => 2 ^ j i)) (hv : Row v) : + Cost (fun i => i.p.fee (i.m + j i) (v i)) := by + have h := (Row.expand ((hv.add (long_const 1).row).add threshold.row) hj).left + ((short_const 1000).mul ((short_const 1).add weights)) + exact h.mono fun i => by rw [Rounds.Contraction.Prices.fee, mul_assoc] + +theorem gather (hj : Short (fun i => 2 ^ j i)) (hv : Row v) : + Cost (fun i => gatherCost i.m (j i) (v i) (i.p.fee (i.m + j i) (v i))) := by + have hm : Long (fun i => i.m + j i) := hosts.add (Short.long hj.of_exp) + have hc := ((long_const 100).add ((hm.add ((long_const 3).mul hosts)).add (long_const 1))).pow 200 + have hw := Row.expand ((hm.row.add hv).add (long_const 1).row) hj + refine ((((fee hj hv).scale 4).add ((Long.row hc).expand hj |>.scale 4)).add + (hw.scale 1100)).mono fun i => ?_ + rw [gatherCost, mul_assoc 1100] + +theorem Short.hostGroups {f : Case → ℕ} (h : Short f) : Cost (fun i => 2 ^ (i.m + i.a) * f i) := + h.groups.hosts.mono fun i => by rw [pow_add, mul_assoc] + +private theorem patchCost : + Cost (fun i => Group.patchCost i.m i.d i.a i.n i.D.count i.b.tagCap i.tagFee) := by + have patches : Cost (fun i => (Group.Patches i.m i.d i.a i.n i.D.count).width) := + patch.hostGroups.mono fun i => by rw [Group.Patches, Format.width_vec] + have loads : Cost (fun i => (Format.vec i.m (.vec i.q (Group.Parcel i.d i.a i.n + i.D.count))).width) := + (Row.hosts (parcel.left path)).mono fun i => by rw [Format.width_vec, Format.width_vec] + have cost := Mixed.long Case.m (((long_const 100).add (hosts.add path.long)).pow 220) + exact (((((groupInput.add patches).add loads).add cost).scale 1000).add (gather path parcel)) + +private theorem election : Cost (fun i => Group.electionCost (i.m + i.a) i.n) := by + have hr := Short.hostGroups (((short_const 100).add tiles.of_exp).pow 5) + have hl : Long Case.n := Short.long tiles.of_exp + have hc := ((long_const 100).add (hl.add (hl.add (hosts.add groupHeight.long)))).pow 42 + exact (hr.add (Long.row hc).cost).left tiles + +private theorem groupCost : Cost (fun i => Group.cost (i.m + i.a) i.q i.n i.D.count) := + ((Short.hostGroups ((short_const 1).add tagArity)).scale 100).add (election.scale 4) + +theorem bankCost : Cost (fun i => i.b.bankCost i.tagFee i.sheetFee) := by + have he : Cost (fun i => i.b.Elected.width) := + groupLabels.hostGroups.mono fun i => by rw [Elected, Format.width_vec] + exact ((((((format.add groupInput).add he).add bank).scale 100).add patchCost).add + groupCost).add (gather slots stack) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +end + +/- # Host navigation and the grouped-label network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +open Coloring + +private theorem priorSlots : Short (fun i => 2 ^ (i.d + 1)) := slots.exp_add (short_const 2) + +private theorem maskSlots : Short (fun i => 2 ^ ((i.d + 1) + (i.n + 1))) + := priorSlots.exp_add suffix + +theorem prior : Cost (fun i => i.b.Prior.width) := + (Mixed.long Case.m (priorSlots.long.mul hosts)).mono (fun i => by + rw [Prior, Neighborhood.Rows, Format.width_vec, Format.width_vec, Format.width_addr]) + +theorem nav : Cost (fun i => i.b.Nav.width) := + (Long.row (childSlots.long.mul childHosts)).children.mono (fun i => by + rw [Nav, Neighborhood.Rows, Format.width_vec, Format.width_vec, Format.width_addr]) + +theorem mask : Cost (fun i => i.b.Mask.width) := by + have h := maskSlots.mul (childSlots.mul (maskSlots.mul (short_const 1))) + refine (Mixed.long Case.m (Short.long h)).mono fun i => ?_ + rw [Mask, Neighborhood.Mask, Format.width_vec, Format.width_vec, Format.width_vec, + Format.width_vec, Format.width_bit] + +theorem view : Cost (fun i => i.b.View.width) := + pair_cost (pair_cost bank remote) (pair_cost nav mask) + +private theorem childInput : Cost (fun i => (Child.Input i.m i.d).width) := by + refine (Mixed.long Case.m (slots.long.mul ((long_const 1).add hosts))).mono fun i => ?_ + rw [Child.Input, Format.width_vec, Format.width_vec, Format.width_pair, Format.width_bit, + Format.width_addr] + +private theorem navCost : Cost (fun i => i.D.navCost i.a i.b.target.d) := by + have h := ((long_const 100).add (childHosts.add childSlots.long)).pow 201 + exact ((format.add (groupInput.scale 3)).add (childInput.scale 68)).add (Long.row h).children + +theorem linkCost : Cost (fun i => i.b.linkCost) := by + have h := ((long_const 100).add ((childHosts.add maskSlots.long).add childSlots.long)).pow 40 + exact (((format.scale 12).add (prior.scale 34)).add (navCost.scale 2)).add (Long.row h).children + +private theorem update : Cost (fun i => updateCost i.b.target.m i.b.target.d i.a i.b.Tile + i.b.Fields) := + Row.children (((Long.row (childSlots.long.mul childHosts)).scale 4).add + (Short.groups (((short_const 1).add tile).add fields))) + +theorem charge : Cost (fun i => i.b.cost i.tagFee i.sheetFee) := by + have send := (view.add ((rows tile).scale 34)).scale 4 + have recv := ((rows fields).add (output.scale 2)).scale 4 + exact (((((format.scale 20).add bankCost).add (linkCost.scale 4)).add send).add update).add recv + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Rate +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Sheet.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Sheet.lean new file mode 100644 index 0000000000..d4f50400bf --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Sheet.lean @@ -0,0 +1,1086 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Spans +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Parcel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.ChildPaths + +/-! # Grouping a board using only the transmitted loads -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents +open Coloring Packing Rounds + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} + {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} (p : D.Presents r P) + {g H T a : ℕ} {L θ : ℝ} (ha : a < D.scheme.h) + +local notation "n" => D.scheme.h - a +local notation "cost" => ((H : ℝ) * T / 2) + +open scoped Classical in +theorem group_load (v : P.V) (i : Cell a) (j : Cell n) : + D.load (D.counter r (p.host v) (D.position a ha.le (cellIndex a i) (cellIndex n j))) = + P.groupLoad a ha.le (v, i) j := by + let q := (splitCell a ha.le).symm (i, j) + have he : splitAddr P.V a ha.le (v, q) = ((v, i), j) := by simp [splitAddr, q] + rw [show D.position a ha.le _ _ = cellIndex _ q by simp [position, q], p.load] + unfold Rounds.Board.groupLoad push + simp only [Function.comp_apply, ← he, (splitAddr P.V a ha.le).injective.eq_iff] + congr! 3 + +open scoped Classical in +/-- The data for the plan construction, including `group`, `tag`. -/ +structure Plan (g H T : ℕ) where + /-- The `Plan` component of type `P.Plan a ha.le g H T`. -/ + group : P.Plan a ha.le g H T + tag : ∀ v i, D.intervals a ha.le 1 ((H : ℝ) * T / 2) g g r (Group.embed p.host a v) (cellIndex n + i) = + intervalCode n (group.here v i).2 + +open scoped Classical in +theorem plan (hg : 0 < g) (hH : 0 < H) (hT : 0 < T) (ok : P.Ready g H T L θ) : + Nonempty (p.Plan ha g H T) := by + have h : Group.Presents (D.groups a ha.le r) p.host P.adj P.adj + (Packing.relative 1 cost (P.groupLoad a ha.le)) (D.relative 1 cost) := + ⟨p.live, p.closed, p.edge, p.core, fun v i j => + congrArg (· / ((2 : ℝ) ^ 1 * cost)) (p.group_load ha v i j)⟩ + obtain ⟨G, hG⟩ := h.grouping hg hg le_rfl (by omega) (by positivity) + P.sym P.sym (fun _ => Finset.Subset.rfl) ok.1 ok.1 (P.groupBound ha.le ok) + exact ⟨⟨G, hG⟩⟩ + +namespace Plan +variable {p ha} (G : p.Plan ha g H T) + +open scoped Classical in +/-- Computes the occurrence by the application `splitAddr P.V a ha.le (P.place i)`. -/ +def occurrence (i : P.diagram.V) := splitAddr P.V a ha.le (P.place i) +open scoped Classical in +/-- The value specified by `G.group.loc (occurrence (ha := ha) i).1 (occurrence (ha := ha) +i).2`. -/ +def col (i : P.diagram.V) := G.group.loc (occurrence (ha := ha) i).1 (occurrence (ha := ha) i).2 +open scoped Classical in +/-- The value specified by `cellIndex n (occurrence (ha := ha) i).2`. -/ +def row (i : P.diagram.V) := cellIndex n (occurrence (ha := ha) i).2 + +local notation "suffixOf" => (row (P := P) (ha := ha)) + +open scoped Classical in +theorem one : Function.Injective (fun i => (G.col i, suffixOf i)) := by + intro i j he + apply P.one + apply (splitAddr P.V a ha.le).injective + exact Prod.ext (congrArg (fun x => x.1.1) he) ((cellIndex n).injective (congrArg Prod.snd he)) + +variable (hg : 0 < g) (hH : 0 < H) (hT : 0 < T) (ok : P.Ready g H T L θ) + (hs : (P.seats : ℝ) * H * T ≤ L * (2 : ℝ) ^ (D.scheme.h - a)) + +open scoped Classical in +/-- Computes the cells by the application `P.withCells hg hH hT ha ok hs G.group`. -/ +abbrev cells := P.withCells hg hH hT ha ok hs G.group +open scoped Classical in +/-- The value specified by `(G.cells hg hH hT ok hs).bin suffixOf hH`. -/ +abbrev bin := (G.cells hg hH hT ok hs).bin suffixOf hH + +variable {R : ℕ} (hd : (4 * g) ^ 300 < H) (hR : 0 < R) (hRT : R * H ^ 2 ≤ T) + (hx : ((wd x + wd y : ℕ) : ℝ) * H ≤ L) + +open scoped Classical in +/-- The input used in the `Plan` construction. -/ +abbrev input := (G.cells hg hH hT ok hs).input hd hR hRT + ((Finset.sum_nonneg fun v _ => P.charge_nonneg v).trans ok.2.1) hx (G.bin hg hH hT ok hs) + ((G.cells hg hH hT ok hs).bin_sq suffixOf hH G.one ok.2.1 ok.2.2.1) + +end Plan +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents +end + +/- # Suffix rows as read from the grouping controller -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents.Plan +open Coloring Packing Rounds Finset + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} + {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} {p : D.Presents r P} + {g H T a : ℕ} {L θ : ℝ} {ha : a < D.scheme.h} (G : p.Plan ha g H T) + +local notation "n" => D.scheme.h - a +local notation "suffixOf" => (row (P := P) (ha := ha)) +local notation "Col" => G.group.Colony + +open scoped Classical in +/-- The indexed operation `push (fun v => (G.col v, suffixOf v)) P.charge (c, j)`. -/ +abbrev weight (c : Col) (j : B n) := push (fun v => (G.col v, suffixOf v)) P.charge (c, j) + +open scoped Classical in +theorem weight_at (v : P.diagram.V) : G.weight (G.col v) (suffixOf v) = P.charge v := by + simp only [weight, push, G.one.eq_iff, sum_ite_eq', mem_univ, ite_true] + +open scoped Classical in +theorem weight_pos {c : Col} {j : B n} (h : 0 < G.weight c j) : + ∃ i : P.diagram.V, G.col i = c ∧ suffixOf i = j ∧ 0 < P.charge i := by + by_contra! hn + refine h.not_ge (sum_nonpos fun i _ => ?_) + split_ifs with hi + · exact hn i (Prod.mk.inj hi).1 (Prod.mk.inj hi).2 + · rfl + +open scoped Classical in +theorem weight_eq (c : Col) (j : Cell n) : + G.weight c (cellIndex n j) = if G.group.loc c.1 j = c then P.groupLoad a ha.le c.1 j else 0 + := by + have test (i : P.diagram.V) : (G.col i, suffixOf i) = (c, cellIndex n j) ↔ + G.group.loc c.1 j = c ∧ occurrence (ha := ha) i = (c.1, j) := by + constructor + · intro h + have he := Prod.mk.inj h + have eq : occurrence (ha := ha) i = (c.1, j) := + Prod.ext (congrArg Sigma.fst he.1) ((cellIndex n).injective he.2) + exact ⟨by simpa only [col, eq] using he.1, eq⟩ + · rintro ⟨h, he⟩ + simp only [col, row, he, h] + unfold weight push + simp only [test, ite_and, sum_ite_irrel, sum_const_zero] + split_ifs + · apply sum_congr rfl + intro i _ + unfold occurrence + by_cases h : splitAddr P.V a ha.le (P.place i) = (c.1, j) + · exact (ite_eq_left h).trans (ite_eq_left h).symm + · exact (ite_eq_right h).trans (ite_eq_right h).symm + · rfl + +open scoped Classical in +/-- Computes the interval by the application `intervalCode n (G.group.site c).2`. -/ +def interval (c : Col) := intervalCode n (G.group.site c).2 +open scoped Classical in +/-- The quantity computed by `D.intervals a ha.le 1 ((H : ℝ) * T / 2) g g r ((Match.rowIndex _ +_).symm (v, i))`. -/ +def labels (v : B D.scheme.m) (i : B a) := + D.intervals a ha.le 1 ((H : ℝ) * T / 2) g g r ((Match.rowIndex _ _).symm (v, i)) + +open scoped Classical in +/-- Selects the appropriate branch of `if labels (D := D) (r := r) (ha := ha) (H := H) (T := T) +(g := g) v i j = k then D.load (D.counter r v (D.position a ha.le i j)) else 0`. -/ +def profile (v : B D.scheme.m) (i : B a) (k : B (n + 1)) (j : B n) := + if labels (D := D) (r := r) (ha := ha) (H := H) (T := T) (g := g) v i j = k + then D.load (D.counter r v (D.position a ha.le i j)) else 0 + +open scoped Classical in +theorem profile_eq (c : Col) : + profile (D := D) (r := r) (ha := ha) (H := H) (T := T) (g := g) + (p.host c.1.1) (cellIndex _ c.1.2) (G.interval c) = G.weight c := by + funext j + obtain ⟨j, rfl⟩ := (cellIndex n).surjective j + rw [weight_eq, profile, p.group_load ha] + have ht := G.tag c.1 j + change labels (D := D) (r := r) (ha := ha) (H := H) (T := T) (g := g) + (p.host c.1.1) (cellIndex _ c.1.2) (cellIndex n j) = _ at ht + rw [ht] + have eq : intervalCode n (G.group.here c.1 j).2 = G.interval c ↔ G.group.loc c.1 j = c := + ⟨fun h => G.group.site_injective (Prod.ext rfl ((intervalCode n).injective h)), + fun h => congrArg G.interval h⟩ + simp only [eq] + +open scoped Classical in +/-- Selects the elements of all indices satisfying `(fun j => 0 < f j)`. -/ +def active {q : ℕ} (f : B q → ℝ) := univ.filter (fun j => 0 < f j) + +open scoped Classical in +theorem active_card (hg : 0 < g) (hH : 0 < H) (hT : 0 < T) (ok : P.Ready g H T L θ) + (hs : (P.seats : ℝ) * H * T ≤ L * (2 : ℝ) ^ n) (hθ : 0 < θ) (c : Col) : + (active (G.weight c)).card ≤ ⌈(H : ℝ) / θ⌉₊ := by + let s := active (G.weight c) + have low j (hj : j ∈ s) : θ * T ≤ G.weight c j := by + obtain ⟨v, rfl, rfl, hv⟩ := G.weight_pos (mem_filter.mp hj).2 + rw [G.weight_at] + exact (ok.2.2.2 v).2.resolve_left hv.ne' + have h : (s.card : ℝ) * θ * T ≤ (H : ℝ) * T := calc + _ = ∑ _ ∈ s, θ * T := by simp [mul_assoc] + _ ≤ ∑ j ∈ s, G.weight c j := sum_le_sum low + _ ≤ ∑ j, G.weight c j := sum_le_sum_of_subset_of_nonneg (subset_univ _) fun _ _ _ => + push_nonneg _ _ P.charge_nonneg _ + _ ≤ _ := by + unfold weight + rw [← push_fst, push_comp] + exact (G.cells hg hH hT ok hs).mass c + exact Nat.cast_le.mp (((le_div_iff₀ hθ).mpr + (le_of_mul_le_mul_right h (Nat.cast_pos.mpr hT))).trans (Nat.le_ceil _)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents.Plan +end + +/- # Merging on a loopless board preserves the full kernel -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents.Plan +open Coloring Packing Rounds + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} + {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} {p : D.Presents r P} + {g H T a R : ℕ} {L θ : ℝ} {ha : a < D.scheme.h} (G : p.Plan ha g H T) + (hg : 0 < g) (hH : 0 < H) (hT : 0 < T) (ok : P.Ready g H T L θ) + (hs : (P.seats : ℝ) * H * T ≤ L * (2 : ℝ) ^ (D.scheme.h - a)) + (hn : ∀ i, P.diagram.source i ≠ P.diagram.target i) + +local notation "C" => G.cells hg hH hT ok hs +local notation "f" => G.bin hg hH hT ok hs +local notation "A" => Cells.before P + +include hn in +open scoped Classical in +theorem separated : (A).Separated ((C).seat f) := by + rintro (i|j|k) e + · have hc : G.col (P.diagram.source i) = G.col (P.diagram.target i) := congrArg Prod.fst e + have hr : row (ha := ha) (P.diagram.source i) = row (ha := ha) (P.diagram.target i) := + congrArg (fun t => cellIndex _ (suffix a t)) (P.edge i).1.symm + exact hn i (G.one (Prod.ext hc hr)) + · exact Option.some_ne_none _ (congrArg Prod.snd e) + · exact Option.some_ne_none _ (congrArg Prod.snd e.symm) + +variable (hd : (4 * g) ^ 300 < H) (hR : 0 < R) (hRT : R * H ^ 2 ≤ T) (hx : ((wd x + + wd y : ℕ) : ℝ) * H ≤ L) + +include hn in +open scoped Classical in +theorem input_eval (neutral : ∀ v, P.diagram.arity v = 0 → ∀ t, + Transcript.sample (P.diagram.table v) t = 1) : + (G.input hg hH hT ok hs hd hR hRT hx).diagram.eval = P.diagram.eval := by + have ne (v : (A).V) (h : (A).arity v = 0) (t : Transcript.Ports ((A).table v) → Bool) : + Transcript.sample ((A).table v) t = 1 := by + rcases v with i|j + · exact neutral i h t + · exact ((by decide : 2 ≠ 0) h).elim + exact (Diagram.eval_pad ((C).stations f) R).trans + (((G.separated hg hH hT ok hs hn).prune_eval ne).trans (eval_ident P.diagram)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents.Plan +end + +/- +# Tracking an exterior bit through its equality station + +Each old bit keeps its original station. For a boundary bit there +are two more ends, on opposite sides of the attached identity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel +open Packing Rounds + +variable {F : Type} [Field F] {x y : Wire} (G : Diagram F x y) +local notation "E" => (Border.attach (ident F x y) G) + +open scoped Classical in +/-- In the case `.inl (.inl i)`, this construction gives `(some false, .inl (.inl i))`. -/ +def axis : (E).End → Option Bool × G.End + | .inl (.inl i) => (some false, .inl (.inl i)) + | .inl (.inr (.inl e)) => (none, .inl (.inr e)) + | .inl (.inr (.inr (.inl i))) => (none, .inl (.inl i)) + | .inl (.inr (.inr (.inr j))) => (some true, .inr (.inl j)) + | .inr (.inl j) => (some false, .inr (.inl j)) + | .inr (.inr (.inl e)) => (none, .inr (.inr e)) + | .inr (.inr (.inr (.inl i))) => (some true, .inl (.inl i)) + | .inr (.inr (.inr (.inr j))) => (none, .inr (.inl j)) + +open scoped Classical in +/-- In the case `.inl (.inl i)`, this construction gives `.inl (.inr (.inr (.inl i)))`. -/ +def real : G.End → (E).End + | .inl (.inl i) => .inl (.inr (.inr (.inl i))) + | .inl (.inr e) => .inl (.inr (.inl e)) + | .inr (.inl i) => .inr (.inr (.inr (.inr i))) + | .inr (.inr e) => .inr (.inr (.inl e)) + +open scoped Classical in +/-- In the case `false, i`, this construction gives `boundaryEnd E i`. -/ +def copy : Bool → slots x ⊕ slots y → (E).End + | false, i => boundaryEnd E i + | true, .inl i => .inr (.inr (.inr (.inl i))) + | true, .inr j => .inl (.inr (.inr (.inr j))) + +open scoped Classical in +theorem axis_real (q : G.End) : axis G (real G q) = (none, q) + := by rcases q with (_|_)|(_|_) <;> rfl +open scoped Classical in +theorem axis_copy (b : Bool) (i : slots x ⊕ slots y) : + axis G (copy G b i) = (some b, boundaryEnd G i) := by cases b <;> cases i <;> rfl + +open scoped Classical in +theorem covered (t : (E).End) : (∃ q, t = real G q) ∨ (∃ b i, t = copy G b i) := by + rcases t with (i|e|i|j)|(j|e|i|j) + · exact .inr ⟨false, .inl i, rfl⟩ + · exact .inl ⟨.inl (.inr e), rfl⟩ + · exact .inl ⟨.inl (.inl i), rfl⟩ + · exact .inr ⟨true, .inr j, rfl⟩ + · exact .inr ⟨false, .inr j, rfl⟩ + · exact .inl ⟨.inr (.inr e), rfl⟩ + · exact .inr ⟨true, .inl i, rfl⟩ + · exact .inl ⟨.inr (.inl j), rfl⟩ + +open scoped Classical in +theorem axis_inj : Function.Injective (axis G) := by + intro i j h + rcases covered G i with ⟨_, rfl⟩|⟨_, _, rfl⟩ <;> rcases covered G j with ⟨_, rfl⟩|⟨_, _, rfl⟩ <;> + simp only [axis_real, axis_copy, Prod.mk.injEq, reduceCtorEq, Option.some.injEq, + (boundaryEnd G).injective.eq_iff, true_and, false_and] at h + · rw [h] + · rw [h.1, h.2] + +open scoped Classical in +theorem station_real (q : G.End) : (E).station (real G q) = Sum.inl (G.station q) := by + rcases q with (_|_)|(_|_) <;> rfl + +open scoped Classical in +theorem station_copy (b : Bool) (i : slots x ⊕ slots y) : (E).station (copy G b i) = Sum.inr i := by + cases b <;> cases i <;> rfl + +open scoped Classical in +theorem factor_real (v : G.V) (w : (E).End → Bool) : + (E).weight (.inl v) (w ∘ .inl) (w ∘ .inr) = + G.weight v (w ∘ real G ∘ .inl) (w ∘ real G ∘ .inr) := by + unfold Diagram.weight + apply congrArg₂ (G.table v).2.2 <;> apply congrArg <;> funext i + · change w (.inl (Border.merge _ _ _ _ (.inl (G.src ⟨v, i⟩)))) = w (real G (.inl (G.src ⟨v, i⟩))) + cases G.src ⟨v, i⟩ <;> rfl + · change w (.inr (((Equiv.refl _).sumCongr ((Equiv.refl _).sumCongr (Equiv.sumComm _ _))) + (Border.merge _ _ _ _ (.inl (G.dst ⟨v, i⟩))))) = w (real G (.inr (G.dst ⟨v, i⟩))) + cases G.dst ⟨v, i⟩ <;> rfl + +open scoped Classical in +theorem factor_copy (i : slots x ⊕ slots y) (w : (E).End → Bool) : + (E).weight (.inr i) (w ∘ .inl) (w ∘ .inr) = + if w (copy G false i) = w (copy G true i) then 1 else 0 := by + cases i + · rfl + · simp only [eq_comm (a := w (copy G false _))] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel +end + +/- # Local labels and peer addresses of active rows -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel +open Rounds Packing Coloring + +variable {F : Type} [Field F] {x y : Wire} {h a g H T : ℕ} {L : ℝ} + {P : Rounds.Board F x y h} (C : Cells P a g H T L) + {S : Scheme F} {r : S.format.obj} (p : S.Presentation r P.diagram) + {m d k u : ℕ} (bin : P.diagram.V → Fin H) (w : (Frame S m d a k u).obj) + +local notation "N" => scheme S m d a k u +local notation "out" => encode S w + +open scoped Classical in +/-- The value specified by `(w t.1).2 t.2`. -/ +abbrev rowAt (w : (Frame S m d a k u).obj) (t : B m × B a) := (w t.1).2 t.2 + +open scoped Classical in +/-- Agreement of the transmitted rows with the original incidence +data, expressed entirely in short addresses. -/ +structure Manifest where + /-- Embeds the coordinates as `C.A ↪ B m × B a`. -/ + cell : C.A ↪ B m × B a + /-- Embeds the coordinates as `Option (Fin H) ↪ B k`. -/ + number : Option (Fin H) ↪ B k + zero : number none = 0 + /-- The rank of type `P.diagram.V → B u`. -/ + rank : P.diagram.V → B u + one : ∀ i j, 0 < P.diagram.arity i → 0 < P.diagram.arity j → C.cell i = C.cell j → rank i + = rank j → i = j + first : ∀ i, (p.vertex i).2.2 = 0 + slot_eq : ∀ i, 0 < P.diagram.arity i → slot S (rowAt w (cell (C.cell i))) (rank i) + = number (some (bin i)) + pattern_eq : ∀ i, 0 < P.diagram.arity i → + label S (rowAt w (cell (C.cell i))) (rank i) = S.pattern r (p.vertex i) + appears : ∀ t j, slot S (rowAt w t) j ≠ 0 → ∃ i, 0 < P.diagram.arity i ∧ cell (C.cell i) = t + ∧ rank i = j + /-- The identification of the indices of type `B m → B m → B d`. -/ + index : B m → B m → B d + stay : ∀ v, index v v = 0 + self : ∀ v, (w v).1 0 = v + peer : ∀ i s j t, 0 < S.width r (p.vertex i, s) → S.peer r (p.vertex i, s) = some (p.vertex j, + t) → + let v := cell (C.cell i) + let v' := cell (C.cell j) + ((rowAt w v (rank i)).2.2 s = (index v.1 v'.1, number (some (bin j)), rank j)) ∧ + (w v.1).1 (index v.1 v'.1) = v'.1 ∧ v.2 = v'.2 + +namespace Manifest +variable {C p bin w} (A : Manifest C p bin w) + +open scoped Classical in +/-- Computes the address by the application `A.cell (C.cell v)`. -/ +abbrev address (v : P.diagram.V) := A.cell (C.cell v) +open scoped Classical in +/-- Computes the row by the application `rowAt w (A.address v)`. -/ +abbrev row (v : P.diagram.V) := rowAt w (A.address v) +open scoped Classical in +/-- Computes the mobile by the application `A.number (some (bin v))`. -/ +abbrev mobile (v : P.diagram.V) := A.number (some (bin v)) + +open scoped Classical in +theorem mobile_ne (v : P.diagram.V) : A.mobile v ≠ 0 := + fun h => Option.some_ne_none _ (A.number.injective (h.trans A.zero.symm)) + +open scoped Classical in +/-- Embeds `C.Slot` into `(N).Vtx`. -/ +def seat : C.Slot ↪ (N).Vtx := + (A.cell.prodMap A.number).trans (Equiv.prodAssoc _ _ _).toEmbedding + +open scoped Classical in +/-- Embeds `(C.stations bin).V` into `(N).Vtx`. -/ +abbrev vertex : (C.stations bin).V ↪ (N).Vtx := (Function.Embedding.subtype _).trans A.seat +open scoped Classical in +/-- The indexed operation `f.elim (A.mobile v) (fun _ => 0)`. -/ +abbrev idSlot (f : Option Bool) (v : P.diagram.V) := f.elim (A.mobile v) (fun _ => 0) +open scoped Classical in +/-- The value specified by `((A.address v).1, (A.address v).2, A.idSlot f v)`. -/ +def place (f : Option Bool) (v : P.diagram.V) : (N).Vtx := ((A.address v).1, (A.address v).2, + A.idSlot f v) +open scoped Classical in +/-- The value specified by `(A.place f v, Parcel.index _ _ (f.getD false, A.rank v, s))`. -/ +def span (f : Option Bool) (v : P.diagram.V) (s : B S.e) : (N).Span := + (A.place f v, Parcel.index _ _ (f.getD false, A.rank v, s)) + +open scoped Classical in +theorem positive {v : P.diagram.V} {s : B S.e} (hw : 0 < S.width r (p.vertex v, s)) : + 0 < P.diagram.arity v := by + have ht : Nonempty (P.diagram.Port v) := ⟨(p.pin v).symm ⟨s, ⟨0, hw⟩⟩⟩ + simpa [Diagram.Port, Diagram.arity] using Fintype.card_pos_iff.mpr ht + +open scoped Classical in +theorem raw_length {v : P.diagram.V} (hv : 0 < P.diagram.arity v) (s : B S.e) : + (label S (A.row v) (A.rank v)).width 0 s = S.width r (p.vertex v, s) := by + rw [A.pattern_eq v hv, Scheme.width, A.first] + +open scoped Classical in +theorem raw_external {v : P.diagram.V} (hv : 0 < P.diagram.arity v) (s : B S.e) : + external S (A.row v) (A.rank v) s ↔ S.peer r (p.vertex v, s) = none := by + unfold external Scheme.peer + rw [A.pattern_eq v hv, A.first] + exact Option.map_eq_none_iff.symm + +open scoped Classical in +theorem accept {v : P.diagram.V} (hv : 0 < P.diagram.arity v) (s : B S.e) (f : Option Bool) + (hf : f ≠ none → S.peer r (p.vertex v, s) = none) : + accepts S (A.row v) (A.idSlot f v) (f.getD false) (A.rank v) s := by + unfold accepts + rw [A.slot_eq v hv] + refine ⟨A.mobile_ne v, ?_⟩ + cases f with + | none => exact .inr ⟨rfl, rfl⟩ + | some b => exact .inl ⟨rfl, (A.raw_external hv s).mpr (hf (Option.some_ne_none _))⟩ + +open scoped Classical in +theorem length_eq {v : P.diagram.V} (hv : 0 < P.diagram.arity v) (s : B S.e) (f : Option Bool) + (hf : f ≠ none → S.peer r (p.vertex v, s) = none) : + length S (A.row v) (A.idSlot f v) (f.getD false, A.rank v, s) = S.width r (p.vertex v, s) := by + rw [length, ite_eq_left (A.accept hv s f hf), A.raw_length hv s] + +open scoped Classical in +theorem width_eq {v : P.diagram.V} (hv : 0 < P.diagram.arity v) (s : B S.e) (f : Option Bool) + (hf : f ≠ none → S.peer r (p.vertex v, s) = none) : + (N).width out (A.span f v s) = S.width r (p.vertex v, s) := by + rw [Scheme.width, pattern_encode] + simpa only [span, place, pattern, size, Equiv.symm_apply_apply] using A.length_eq hv s f hf + +open scoped Classical in +theorem dir_eq {v : P.diagram.V} (hv : 0 < P.diagram.arity v) (s : B S.e) (f : Option Bool) : + (N).direction out (A.span f v s) = + cond (f.getD false) (!(S.direction r (p.vertex v, s))) (S.direction r (p.vertex v, s)) := by + rw [Scheme.direction, pattern_encode] + simp only [span, place, pattern, Equiv.symm_apply_apply, side] + rw [Scheme.direction, A.first] + exact congrArg (fun l : Pattern F _ _ _ => cond (f.getD false) (!(l.direction 0 s)) (l.direction + 0 s)) + (A.pattern_eq v hv) + +open scoped Classical in +theorem span_inj {v v' : P.diagram.V} {s s' : B S.e} {f f' : Option Bool} + (hv : 0 < P.diagram.arity v) (hv' : 0 < P.diagram.arity v') + (he : A.span f v s = A.span f' v' s') : f = f' ∧ v = v' ∧ s = s' := by + have hl : A.address v = A.address v' := congrArg (fun t : (N).Span => (t.1.1, t.1.2.1)) he + have ht : A.idSlot f v = A.idSlot f' v' := congrArg (fun t : (N).Span => t.1.2.2) he + obtain ⟨hb, hr⟩ := Prod.mk.inj ((Parcel.index u S.e).injective (congrArg Prod.snd he)) + have hvv := A.one _ _ hv hv' (A.cell.injective hl) (Prod.mk.inj hr).1 + refine ⟨?_, hvv, (Prod.mk.inj hr).2⟩ + cases f <;> cases f' + · rfl + · exact ((A.mobile_ne v) ht).elim + · exact ((A.mobile_ne v') ht.symm).elim + · exact congrArg some hb + +open scoped Classical in +private theorem split_span (i : B m) (l : B a) (j : B k) (b : Bool) (x : B u) (s : B S.e) + (ht : 0 < (N).width out ((i, l, j), Parcel.index _ _ (b, x, s))) : + accepts S (rowAt w (i, l)) j b x s ∧ 0 < (label S (rowAt w (i, l)) x).width 0 s := by + have e : (N).width out ((i, l, j), Parcel.index _ _ (b, x, s)) = length S (rowAt w (i, l)) j (b, + x, s) := by + rw [Scheme.width, pattern_encode] + simp only [pattern, size, Equiv.symm_apply_apply, rowAt] + have h := ht.trans_eq e + unfold length at h + split at h + · exact ⟨by assumption, h⟩ + · exact (lt_irrefl _ h).elim + +open scoped Classical in +theorem used (t : (N).Span) (ht : 0 < (N).width out t) : + ∃ f v s, A.span f v s = t ∧ 0 < S.width r (p.vertex v, s) ∧ + (f ≠ none → S.peer r (p.vertex v, s) = none) := by + obtain ⟨⟨i, l, j⟩, q⟩ := t + obtain ⟨⟨b, x, s⟩, rfl⟩ := (Parcel.index u S.e).surjective q + obtain ⟨ha, ht'⟩ := split_span i l j b x s ht + clear ht + obtain ⟨v, hv, he, hr⟩ := A.appears (i, l) x ha.1 + have hw : 0 < S.width r (p.vertex v, s) := by + rw [← A.raw_length hv, hr] + unfold row address + rw [he]; exact ht' + have e : A.row v = rowAt w (i, l) := congrArg (rowAt w) he + obtain ⟨rfl, hp⟩|⟨hj, rfl⟩ := ha.2 + · refine ⟨some b, v, s, ?_, hw, fun _ => (A.raw_external hv s).mp ?_⟩ + · simp only [span, place, address, he, hr]; rfl + · rw [e, hr]; exact hp + · have hm : A.mobile v = j := by + rw [show A.mobile v = slot S (A.row v) (A.rank v) from (A.slot_eq v hv).symm, e, hr] + exact hj.symm + refine ⟨none, v, s, ?_, hw, by simp⟩ + simp only [span, place, address, he, hr, idSlot, Option.elim_none, hm]; rfl + +end Manifest +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel +end + +/- # The address of each physical wire end after merging -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +open Rounds Packing Coloring + +variable {F : Type} [Field F] {x y : Wire} {h a g H T : ℕ} {L : ℝ} + {P : Rounds.Board F x y h} {C : Cells P a g H T L} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r P.diagram} + {m d k u : ℕ} {bin : P.diagram.V → Fin H} {w : (Frame S m d a k u).obj} (A : Manifest C p bin w) + +local notation "G" => P.diagram +local notation "E" => Cells.before P +local notation "N" => scheme S m d a k u +local notation "out" => encode S w + +open scoped Classical in +/-- The value specified by `(p.toSeating.ends q).1.2`. -/ +abbrev stub (p : S.Presentation r P.diagram) (q : (G).End) := (p.toSeating.ends q).1.2 + +open scoped Classical in +theorem old (p : S.Presentation r P.diagram) (q : (G).End) : + (p.toSeating.ends q).1 = (p.vertex ((G).station q), stub p q) := Prod.ext (p.end_station q) rfl + +open scoped Classical in +theorem live (p : S.Presentation r P.diagram) (q : (G).End) : 0 < (G).arity ((G).station q) := + positive ((old p q) ▸ (p.toSeating.ends q).2.pos) + +open scoped Classical in +/-- The destination of type `(N).Span`, constructed using `axis G t`. -/ +def destination (t : (E).End) : (N).Span := + let z := axis G t + A.span z.1 ((G).station z.2) (stub p z.2) + +open scoped Classical in +theorem is_exposed (p : S.Presentation r P.diagram) (t : (E).End) : + (axis G t).1 ≠ none → S.peer r (p.toSeating.ends (axis G t).2).1 = none := by + rcases covered G t with ⟨q, rfl⟩|⟨b, i, rfl⟩ + · simp only [axis_real]; exact fun he => (he rfl).elim + · rw [axis_copy]; exact fun _ => (p.no_peer _).mpr ⟨i, rfl⟩ + +open scoped Classical in +theorem destination_size (t : (E).End) : + (N).width out (A.destination t) = S.width r (p.toSeating.ends (axis G t).2).1 := by + have h := is_exposed p t + rw [old p] at h ⊢ + exact A.width_eq (live p _) _ _ h + +open scoped Classical in +/-- Uses `⟨A.destination t, (p.toSeating.ends (axis G t).2).2.cast (A.destination_size t).symm⟩` +as the representation. -/ +def route (t : (E).End) : (N).Pin out := + ⟨A.destination t, (p.toSeating.ends (axis G t).2).2.cast (A.destination_size t).symm⟩ + +open scoped Classical in +theorem route_inj : Function.Injective A.route := by + intro i j h + have he : A.destination i = A.destination j := congrArg Sigma.fst h + have hi := live p (axis G i).2 + have hj := live p (axis G j).2 + obtain ⟨hd, hv, hs⟩ := A.span_inj hi hj he + apply axis_inj G + refine Prod.ext hd (p.toSeating.ends.injective ?_) + have ht : (p.toSeating.ends (axis G i).2).1 = (p.toSeating.ends (axis G j).2).1 := + by rw [old p (axis G i).2, old p (axis G j).2, hv, hs] + exact Sigma.ext ht ((Fin.heq_ext_iff (congrArg (S.width r) ht)).mpr + (congrArg (fun t : (N).Pin out => t.2.val) h)) + +open scoped Classical in +theorem route_surj : Function.Surjective A.route := by + rintro ⟨s, j⟩ + obtain ⟨f, v, b, rfl, hw, hb⟩ := A.used s j.pos + let q : S.Pin r := ⟨(p.vertex v, b), j.cast (A.width_eq (positive hw) b f hb)⟩ + let i := p.toSeating.ends.symm q + have hi : p.toSeating.ends i = q := p.toSeating.ends.apply_symm_apply q + have hv : (G).station i = v := + p.vertex.injective ((p.end_station i).symm.trans (congrArg (fun z : S.Pin r => z.1.1) hi)) + have hq : ∃ t, axis G t = (f, i) := by + cases f with + | none => exact ⟨real G i, axis_real G _⟩ + | some c => + obtain ⟨l, hl⟩ := (p.no_peer i).mp (by rw [hi]; exact hb (Option.some_ne_none _)) + exact ⟨copy G c l, (axis_copy G _ _).trans (Prod.ext rfl hl)⟩ + obtain ⟨t, ht⟩ := hq + have hd : A.destination t = A.span f v b := by + unfold destination + rw [ht] + dsimp only + rw [hv, show stub p i = b from congrArg (fun z : S.Pin r => z.1.2) hi] + refine ⟨t, Sigma.ext hd ((Fin.heq_ext_iff (congrArg ((N).width out) hd)).mpr ?_)⟩ + change (p.toSeating.ends (axis G t).2).2.val = j.val + rw [ht, hi]; rfl + +open scoped Classical in +theorem location (t : (E).End) : (A.route t).1.1 = A.seat (C.seat bin ((E).station t)) := by + change A.place _ _ = _ + rcases covered G t with ⟨i, rfl⟩|⟨b, j, rfl⟩ + · rw [axis_real, station_real] + rfl + · rw [axis_copy, station_copy, station_boundary] + exact congrArg (fun k => ((A.address (portEnd G j)).1, (A.address (portEnd G j)).2, + k)) A.zero.symm + +open scoped Classical in +theorem direction (hd : p.Directed) (t : (E).End) : (N).direction out (A.route t).1 = t.isRight + := by + rw [show (A.route t).1 = A.destination t from rfl, destination, A.dir_eq (live p _), ← old, hd] + rcases t with (_|_|_|_)|(_|_|_|_) <;> rfl + +variable (sep : (Cells.before P).Separated (C.seat bin)) + +open scoped Classical in +/-- Reindexes `(C.stations bin).End` and `(N).Pin out` by an equivalence. -/ +def ends : (C.stations bin).End ≃ (N).Pin out := + sep.ends.symm.trans (Equiv.ofBijective A.route ⟨A.route_inj, A.route_surj⟩) + +open scoped Classical in +theorem ends_at (t : (E).End) : A.ends sep (sep.ends t) = A.route t := + congrArg A.route (sep.ends.symm_apply_apply t) + +open scoped Classical in +theorem station (t : (C.stations bin).End) : + (A.ends sep t).1.1 = A.vertex ((C.stations bin).station t) := by + obtain ⟨q, rfl⟩ := sep.ends.surjective t + rw [ends_at, location, ← sep.station] + rcases q with (_|_)|(_|_) <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +end + +/- # Linking spans at a merged station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +open Rounds Packing Coloring + +variable {F : Type} [Field F] {x y : Wire} {h a g H T : ℕ} {L : ℝ} + {P : Rounds.Board F x y h} {C : Cells P a g H T L} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r P.diagram} + {m d k u : ℕ} {bin : P.diagram.V → Fin H} {w : (Frame S m d a k u).obj} (A : Manifest C p bin w) + +local notation "G" => P.diagram +local notation "E" => Cells.before P +local notation "N" => scheme S m d a k u +local notation "out" => encode S w + +open scoped Classical in +/-- Requires `(N).peer out q = some t ∧ (N).arc out q = some (A.index q.1.1 t.1.1, t.1.2.2)`. -/ +def Leads (q t : (N).Span) : Prop := + (N).peer out q = some t ∧ (N).arc out q = some (A.index q.1.1 t.1.1, t.1.2.2) + +open scoped Classical in +/-- The value specified by `((N).pattern out q.1).peer q.1.2.2 q.2`. -/ +abbrev localLink (q : (N).Span) := ((N).pattern out q.1).peer q.1.2.2 q.2 + +open scoped Classical in +private theorem leads_of {q t : (N).Span} + (h : localLink (w := w) q = some (A.index q.1.1 t.1.1, t.1.2.2, t.2)) + (hn : (w q.1.1).1 (A.index q.1.1 t.1.1) = t.1.1) (hb : q.1.2.1 = t.1.2.1) : + A.Leads q t := by + unfold localLink at h + unfold Leads Scheme.peer Scheme.arc Pattern.target + rw [h] + simp only [Option.map_some, Parcel.encode, hn, hb, and_self] + +open scoped Classical in +theorem local_link (f : Option Bool) (v : (G).V) (s : B S.e) : + localLink (w := w) (A.span f v s) = + Parcel.link S (A.row v) (A.idSlot f v) (f.getD false, A.rank v, s) := by + unfold localLink + rw [pattern_encode] + simp only [span, place, pattern, Equiv.symm_apply_apply, row, rowAt] + +variable {i j : P.diagram.V} {s t : B S.e} + +open scoped Classical in +theorem joined (hw : 0 < S.width r (p.vertex i, s)) (he : S.peer r (p.vertex i, s) + = some (p.vertex j, t)) : + A.Leads (A.span none i s) (A.span none j t) := by + obtain ⟨hp, hn, hb⟩ := A.peer i s j t hw he + apply A.leads_of _ hn hb + have hi := positive hw + have ht : ∃ d k, (label S (A.row i) (A.rank i)).peer 0 s = some (d, k, t) := by + rw [A.pattern_eq _ hi, ← A.first i] + obtain ⟨⟨d, k, e⟩, h₁, h₂⟩ := Option.map_eq_some_iff.mp he + have : e = t := congrArg Prod.snd h₂ + subst e + exact ⟨_, _, h₁⟩ + obtain ⟨l, k, hk⟩ := ht + rw [A.local_link, Parcel.link, A.length_eq hi s none (by simp), ite_eq_left hw] + change (if A.mobile i = 0 then _ else _) = _ + rw [ite_eq_right (A.mobile_ne i), hk] + dsimp only + rw [show (A.row i (A.rank i)).2.2 s = _ from hp] + rfl + +open scoped Classical in +theorem exposed (hw : 0 < S.width r (p.vertex i, s)) (he : S.peer r (p.vertex i, s) = none) : + (N).peer out (A.span (some false) i s) = none ∧ + A.Leads (A.span none i s) (A.span (some true) i s) ∧ + A.Leads (A.span (some true) i s) (A.span none i s) := by + have hi := positive hw + have hg := (A.raw_external hi s).mpr he + have hn : (w (A.address i).1).1 (A.index (A.address i).1 (A.address i).1) = (A.address i).1 := by + rw [A.stay, A.self] + have hl (b : Option Bool) := A.length_eq hi s b (fun _ => he) + constructor + · change (localLink (w := w) _).map _ = _ + rw [A.local_link, Parcel.link, hl, ite_eq_left hw] + simp [idSlot] + constructor + · refine A.leads_of ?_ hn rfl + rw [A.local_link, Parcel.link, hl, ite_eq_left hw] + change (if A.mobile i = 0 then _ else _) = _ + rw [ite_eq_right (A.mobile_ne i), hg] + simp only [span, place, A.stay] + rfl + · refine A.leads_of ?_ hn rfl + rw [A.local_link, Parcel.link, hl, ite_eq_left hw] + simp only [idSlot, Option.elim_some, ite_true, Option.getD_some, span, place, A.stay] + rw [show slot S (A.row i) (A.rank i) = A.mobile i from A.slot_eq i hi] + rfl + +open scoped Classical in +theorem unused {q : (N).Span} (h : ¬0 < (N).width out q) : (N).peer out q = none := by + rw [Scheme.width, pattern_encode] at h + simp only [pattern, size] at h + rw [Scheme.peer, pattern_encode] + change (Parcel.link _ _ _ _).map _ = none + unfold Parcel.link + rw [ite_eq_right h] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +end + +/- # Peer alignment in the merged network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +open Rounds Packing Coloring + +variable {F : Type} [Field F] {x y : Wire} {h a g H T : ℕ} {L : ℝ} + {P : Rounds.Board F x y h} {C : Cells P a g H T L} + {S : Scheme F} {r : S.format.obj} {p : S.Presentation r P.diagram} + {m d k u : ℕ} {bin : P.diagram.V → Fin H} {w : (Frame S m d a k u).obj} (A : Manifest C p bin w) + +local notation "G" => P.diagram +local notation "E" => Cells.before P +local notation "N" => scheme S m d a k u +local notation "out" => encode S w + +open scoped Classical in +/-- The bond of type `Prop` for the given inputs. -/ +def Bond (i j : (E).End) : Prop := + A.Leads (A.route i).1 (A.route j).1 ∧ A.Leads (A.route j).1 (A.route i).1 ∧ + (N).width out (A.route i).1 = (N).width out (A.route j).1 ∧ + (A.route i).2.val = (A.route j).2.val + +open scoped Classical in +theorem Bond.swap {i j : (E).End} (e : A.Bond i j) : A.Bond j i := + ⟨e.2.1, e.1, e.2.2.1.symm, e.2.2.2.symm⟩ + +open scoped Classical in +theorem real_span (i : (G).End) : + (A.route (real G i)).1 = A.span none ((G).station i) (stub p i) := by + simp only [route, destination, axis_real] + +open scoped Classical in +theorem copy_span (b : Bool) (i : slots x ⊕ slots y) : + (A.route (copy G b i)).1 = A.span (some b) (portEnd G i) (stub p (boundaryEnd G i)) := by + simp only [route, destination, axis_copy, station_boundary] + +open scoped Classical in +theorem routed_width (i : (E).End) : + (N).width out (A.route i).1 = S.width r (p.toSeating.ends (axis G i).2).1 := + A.destination_size i + +open scoped Classical in +theorem offset (i : (E).End) : (A.route i).2.val = (p.toSeating.ends (axis G i).2).2.val := rfl + +open scoped Classical in +private theorem bond_old (z : (G).E) : + A.Bond (real G (.inl (.inr z))) (real G (.inr (.inr z))) := by + have h := p.internal z + have b := p.proper _ _ h.1 + have go {i j : (G).End} (he : S.peer r (p.toSeating.ends i).1 = some (p.toSeating.ends j).1) : + A.Leads (A.route (real G i)).1 (A.route (real G j)).1 := by + rw [old p i, old p j] at he + rw [real_span, real_span] + exact A.joined ((old p i) ▸ (p.toSeating.ends i).2.pos) he + refine ⟨go h.1, go b.1, ?_, ?_⟩ + · rw [routed_width, routed_width, axis_real, axis_real]; exact b.2.1 + · rw [offset, offset, axis_real, axis_real]; exact h.2 + +open scoped Classical in +private theorem bond_copy (i : slots x ⊕ slots y) : + (N).peer out (A.route (copy G false i)).1 = none ∧ + A.Bond (real G (boundaryEnd G i)) (copy G true i) := by + let q := boundaryEnd G i + have he := (p.no_peer q).mpr ⟨i, rfl⟩ + have hw := (p.toSeating.ends q).2.pos + rw [old p q] at he hw + obtain ⟨h₁, h₂, h₃⟩ := A.exposed hw he + refine ⟨?_, ?_, ?_, ?_, ?_⟩ + · rw [copy_span, ← station_boundary]; exact h₁ + · rw [real_span, copy_span, ← station_boundary]; exact h₂ + · rw [real_span, copy_span, ← station_boundary]; exact h₃ + · rw [routed_width, routed_width, axis_real, axis_copy] + · rw [offset, offset, axis_real, axis_copy] + +open scoped Classical in +theorem internal (i : (E).E) : A.Bond (.inl (.inr i)) (.inr (.inr i)) := by + rcases i with z|i|j + · exact A.bond_old z + · exact (A.bond_copy (.inl i)).2 + · exact ((A.bond_copy (.inr j)).2.swap A) + +open scoped Classical in +theorem outside (i : slots x ⊕ slots y) : + (N).peer out (A.route (boundaryEnd E i)).1 = none := (A.bond_copy i).1 + +open scoped Classical in +private theorem reciprocal {q t : (N).Span} (he : (N).peer out q = some t) : + ∃ i j : (E).End, (A.route i).1 = q ∧ (A.route j).1 = t ∧ A.Bond i j ∧ i.isRight ≠ j.isRight + := by + have hq : 0 < (N).width out q := by + by_contra hn + rw [unused hn] at he + contradiction + obtain ⟨i, hi⟩ := A.route_surj ⟨q, ⟨0, hq⟩⟩ + have hw : (A.route i).1 = q := congrArg Sigma.fst hi + rw [← hw] at he + rcases i with (i|i)|(i|i) + · exact (Option.some_ne_none t (he.symm.trans (A.outside (.inl i)))).elim + · have e := A.internal i + exact ⟨_, _, hw, Option.some.inj (e.1.1.symm.trans he), e, Bool.false_ne_true⟩ + · exact (Option.some_ne_none t (he.symm.trans (A.outside (.inr i)))).elim + · have e := (A.internal i).swap A + exact ⟨_, _, hw, Option.some.inj (e.1.1.symm.trans he), e, Ne.symm Bool.false_ne_true⟩ + +include A in +open scoped Classical in +theorem proper (hd : p.Directed) : (N).Proper out := by + intro i j he + obtain ⟨s, t, rfl, rfl, b, hn⟩ := A.reciprocal he + exact ⟨b.2.1.1, b.2.2.1, by rwa [A.direction hd, A.direction hd]⟩ + +open scoped Classical in +theorem arc_eq (i : (N).Span) : + (N).arc out i = ((N).peer out i).map (fun q => (A.index i.1.1 q.1.1, q.1.2.2)) := by + cases h : (N).peer out i with + | none => + have he := Scheme.destination (r := out) i + rw [h, Option.map_none] at he + exact Option.map_eq_none_iff.mp he.symm + | some t => + obtain ⟨s, u, rfl, rfl, b, _⟩ := A.reciprocal h + exact b.1.2 + +include A in +open scoped Classical in +theorem resolved : (N).Resolved out := by + intro v i j _ _ h + rw [A.arc_eq, A.arc_eq] + simpa only [Option.map_map, Function.comp_def] using + congrArg (Option.map (fun y : (N).Vtx => (A.index v.1 y.1, y.2.2))) h + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Parcel.Manifest +end + +/- +# Enumerating active rows in one colony + +The temporary sheet contains the label, counter and elected interval +of every suffix. The record sent to the next stage keeps only active +rows and replaces remote host names by indices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing Rounds + +variable {F : Type} (D : Template F) (n : ℕ) + +open scoped Classical in +/-- The quantity computed by `Format.vec n (.pair (.addr D.scheme.ℓ) (.pair (.addr D.count) +(.addr (n + 1))))`. -/ +abbrev Sheet := Format.vec n (.pair (.addr D.scheme.ℓ) (.pair (.addr D.count) (.addr (n + 1)))) + +open scoped Classical in +theorem sheet_width : (D.Sheet n).width = 2 ^ n * (D.scheme.ℓ + (D.count + (n + 1))) := by + simp only [Sheet, Format.width_vec, Format.width_pair, Format.width_addr] + exact congrArg (fun x => 2 ^ n * (D.scheme.ℓ + (D.count + x))) (Format.width_addr (n + 1)) + +namespace Sheet + +variable {n} (c : (D.Sheet n).obj) + +open scoped Classical in +/-- Returns `D.load (c i).2.1` when `(c i).2.2 = (c j).2.2` holds, and `0` otherwise. -/ +def weights (j : B n) (i : B n) := if (c i).2.2 = (c j).2.2 then D.load (c i).2.1 else 0 + +open scoped Classical in +/-- The list of type `B u`, constructed using `Presents.Plan.active l`. -/ +def list (u : ℕ) (l : B n → ℝ) (i : B n) : B u := + let s := Presents.Plan.active l + if h : i ∈ s ∧ s.card ≤ 2 ^ u then Fin.castLE h.2 (s.equivFin ⟨i, h.1⟩) else 0 + +open scoped Classical in +theorem list_inj (u : ℕ) (l : B n → ℝ) (hl : (Presents.Plan.active l).card ≤ 2 ^ u) : + Set.InjOn (list u l) (Presents.Plan.active l) := by + intro i hi j hj h + let s := Presents.Plan.active l + have he (x : B n) (hx : x ∈ s) : list u l x = Fin.castLE hl (s.equivFin ⟨x, hx⟩) := + dite_eq_left (show x ∈ s ∧ s.card ≤ 2 ^ u from ⟨hx, hl⟩) + rw [he i hi, he j hj] at h + exact congrArg Subtype.val (s.equivFin.injective ((Fin.castLE_injective hl) h)) + +open scoped Classical in +/-- Computes the rank by the application `list u (weights D c j) j`. -/ +abbrev rank (u : ℕ) (j : B n) := list u (weights D c j) j +open scoped Classical in +/-- Computes the bins by the application `Cells.chooseBin H T hH (weights D c j) j`. -/ +abbrev bins (H T : ℕ) (hH : 0 < H) (j : B n) := Cells.chooseBin H T hH (weights D c j) j +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev slots (H : ℕ) := Nat.clog 2 (H + 1) + +open scoped Classical in +/-- Embeds `Option (Fin H)` into `B (slots H)`. -/ +def number (H : ℕ) : Option (Fin H) ↪ B (slots H) := + ((finSuccEquiv H).symm.toEmbedding).trans (Fin.castLEEmb (Nat.le_pow_clog (by decide) _)) + +open scoped Classical in +theorem number_none (H : ℕ) : number H none = 0 := by apply Fin.ext; rfl + +open scoped Classical in +/-- Computes the live by the application `Nonempty ((D.scheme.decode (c j).1).Pin 0)`. -/ +def live (j : B n) := Nonempty ((D.scheme.decode (c j).1).Pin 0) + +open scoped Classical in +/-- Requires `live D c j ∧ (c j).2.2 = z ∧ rank D c u j = b`. -/ +def eligible (u : ℕ) (z : B (n + 1)) (b : B u) (j : B n) : Prop := + live D c j ∧ (c j).2.2 = z ∧ rank D c u j = b + +open scoped Classical in +/-- Returns `some h.choose` when `h : ∃ j, eligible D c u z b j` holds, and `none` otherwise. -/ +def find (u : ℕ) (z : B (n + 1)) (b : B u) : Option (B n) := + if h : ∃ j, eligible D c u z b j then some h.choose else none + +open scoped Classical in +theorem find_spec (u : ℕ) (z : B (n + 1)) (b : B u) (j : B n) (he : find D c u z b = some j) : + eligible D c u z b j := by + unfold find at he + split at he + · rename_i h + rw [← Option.some.inj he] + exact h.choose_spec + · contradiction + +variable (H T : ℕ) (hH : 0 < H) (u d : ℕ) + (neigh : B D.scheme.d → (D.Sheet n).obj) + (nav : B (n + 1) → B D.scheme.d → B (n + 1) → B d) + +open scoped Classical in +/-- In the case `none`, this construction gives `(0, 0, 0)`. -/ +def target (j : B n) (s : B D.scheme.e) : (Parcel.destination d (slots H) u).obj := + match (D.scheme.decode (c j).1).peer 0 s with + | none => (0, 0, 0) + | some t => + let w := neigh t.1 + (nav (c j).2.2 t.1 (w j).2.2, number H (some (bins D w H T hH j)), rank D w u j) + +open scoped Classical in +/-- The record of type `(Parcel.record D.scheme d (slots H) u).obj` for the given inputs. -/ +def record (z : B (n + 1)) : (Parcel.record D.scheme d (slots H) u).obj := fun i => + match find D c u z i with + | none => (0, 0, fun _ => (0, 0, 0)) + | some j => (number H (some (bins D c H T hH j)), (c j).1, target D c H T hH u d neigh nav j) + +end Sheet + +variable [Field F] (a : ℕ) (ha : a < D.scheme.h) (g H T : ℕ) (r : D.format.obj) +local notation "q" => D.scheme.h - a + +open scoped Classical in +/-- The sheet of type `(D.Sheet q).obj`, constructed using `D.position a ha.le x j`. -/ +def sheet (v : B D.scheme.m) (x : B a) : (D.Sheet q).obj := fun j => + let i := D.position a ha.le x j + ((r.1 v).2 i, D.counter r v i, Presents.Plan.labels (D := D) (r := r) (ha := ha) + (g := g) (H := H) (T := T) v x j) + +open scoped Classical in +/-- Computes the child input by the application `Child.fromGroup (D.groups a ha.le r) false`. -/ +abbrev childInput := Child.fromGroup (D.groups a ha.le r) false +open scoped Classical in +/-- Computes the bin nav by the application `Child.neighbors q g (D.childInput a ha r)`. -/ +abbrev binNav := Child.neighbors q g (D.childInput a ha r) +open scoped Classical in +/-- The quantity computed by `D.scheme.m + ((D.scheme.h - a) + 1)`. -/ +abbrev childM := D.scheme.m + ((D.scheme.h - a) + 1) +open scoped Classical in +/-- The quantity computed by `Child.nextWidth (D.scheme.h - a) g D.scheme.d`. -/ +abbrev childD := Child.nextWidth (D.scheme.h - a) g D.scheme.d + +open scoped Classical in +/-- The child frame of type `(Parcel.Frame D.scheme (D.childM a) (D.childD a g) a (Sheet.slots +H) u).obj`, constructed using `D.binNav a ha g r`. -/ +def childFrame (hH : 0 < H) (u : ℕ) : (Parcel.Frame D.scheme (D.childM a) (D.childD a g) a + (Sheet.slots H) u).obj := + let Z := D.binNav a ha g r + let y := Match.rowIndex D.scheme.m (q + 1) + let f := D.sheet a ha g H T r + fun i => (Z i, fun j => Sheet.record D (f (y i).1 j) H T hH u _ + (fun s => f (D.nav r (y i).1 s) j) + (fun l s l' => Child.index Z (y.symm ((y i).1, l)) (y.symm (D.nav r (y i).1 s, l'))) + (y i).2) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Status.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Status.lean new file mode 100644 index 0000000000..6f30c3b29c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Prepare/Status.lean @@ -0,0 +1,500 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Contacts +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Hop +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.One +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents + +/-! # Preparing the common pattern and host chart for local concentration -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing Rounds + +variable {F : Type} [Field F] {x y : Wire} (D : Template F) + +open scoped Classical in +/-- The data for the binning construction, including `ha`, `hH`, `hT`, `hR`, `hRT`. -/ +structure Binning (a H T R : ℕ) (θ : ℝ) : Prop where + ha : a < D.scheme.h + hH : (4 * 5) ^ 300 < H + hT : 0 < T + hR : 0 < R + hRT : R * H ^ 2 ≤ T + floor : 0 < θ + +namespace Binning +variable {D} {a H T R : ℕ} {θ L : ℝ} (B : D.Binning a H T R θ) + +omit [Field F] in +open scoped Classical in +theorem pos (B : D.Binning a H T R θ) : 0 < H := (Nat.zero_le _).trans_lt B.hH + +open scoped Classical in +/-- Uses `Presents.Plan.depth H θ` as the representation. -/ +abbrev depth (_ : D.Binning a H T R θ) := Presents.Plan.depth H θ +open scoped Classical in +/-- Computes the raw by the application `Parcel.scheme D.scheme (D.childM a) (D.childD a 5) a +(Sheet.slots H) B.depth`. -/ +abbrev raw := Parcel.scheme D.scheme (D.childM a) (D.childD a 5) a (Sheet.slots H) B.depth +open scoped Classical in +/-- Computes the target by the application `B.raw.padded R`. -/ +abbrev target := B.raw.padded R +open scoped Classical in +/-- Computes the frame by the application `D.childFrame a B.ha 5 H T r B.pos B.depth`. -/ +abbrev frame (r : D.format.obj) := D.childFrame a B.ha 5 H T r B.pos B.depth +open scoped Classical in +/-- Computes the data by the application `Parcel.encode D.scheme (B.frame r)`. -/ +abbrev data (r : D.format.obj) : B.target.format.obj := Parcel.encode D.scheme (B.frame r) + +variable {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} (p : D.Presents r P) + +open scoped Classical in +/-- A branch of the input family with a grouping elected by the controller. -/ +structure Trial (L : ℝ) where + ready : P.Ready 5 H T L θ + slack : (P.seats : ℝ) * H * T ≤ L * (2 : ℝ) ^ (D.scheme.h - a) + ext : ((wd x + wd y : ℕ) : ℝ) * H ≤ L + neutral : ∀ v, P.diagram.arity v = 0 → ∀ t, Transcript.sample (P.diagram.table v) t = 1 + loopless : ∀ i, P.diagram.source i ≠ P.diagram.target i + /-- The `Trial` component of type `p.Plan B.ha 5 H T`. -/ + plan : p.Plan B.ha 5 H T + +namespace Trial +variable {B p} (t : B.Trial p L) + +open scoped Classical in +theorem five : 0 < 5 := by decide +open scoped Classical in +/-- Uses `t.plan.cells five B.pos B.hT t.ready t.slack` as the representation. -/ +abbrev cells := t.plan.cells five B.pos B.hT t.ready t.slack +open scoped Classical in +/-- Uses `t.plan.bin five B.pos B.hT t.ready t.slack` as the representation. -/ +abbrev bin := t.plan.bin five B.pos B.hT t.ready t.slack + +open scoped Classical in +theorem sep : (Cells.before P).Separated (t.cells.seat t.bin) := + t.plan.separated five B.pos B.hT t.ready t.slack t.loopless +open scoped Classical in +theorem room : t.plan.Room B.depth := t.plan.room five B.pos B.hT t.ready t.slack B.floor + +open scoped Classical in +/-- Computes the layout by the application `t.plan.manifest B.pos five B.hT t.ready t.slack +t.room`. -/ +abbrev layout := t.plan.manifest B.pos five B.hT t.ready t.slack t.room +open scoped Classical in +/-- Uses `t.plan.input five B.pos B.hT t.ready t.slack B.hH B.hR B.hRT t.ext` as the +representation. -/ +abbrev input := t.plan.input five B.pos B.hT t.ready t.slack B.hH B.hR B.hRT t.ext +open scoped Classical in +/-- Computes the post by the application `t.layout.padded t.sep t.neutral p.directed R`. -/ +abbrev post : B.target.Presentation (B.data r) t.input.diagram := + t.layout.padded t.sep t.neutral p.directed R + +open scoped Classical in +theorem directed : t.post.Directed := t.layout.padded_directed t.sep t.neutral p.directed R + +open scoped Classical in +/-- Builds `t.input.HostChart B.target (B.data r) where host` with the specified `host`, +`block`, `adjacent`, `reciprocal`. -/ +def chart : t.input.HostChart B.target (B.data r) where + host := Child.host p.host (D.scheme.h - a) + block := (cellIndex a).toEmbedding + adjacent _ _ hij _ := ⟨_, Presents.Plan.reach (p := p) (ha := B.ha) five hij⟩ + reciprocal := (Presents.Plan.childPresent p B.ha).reciprocal five P.sym _ _ + +open scoped Classical in +/-- Tests whether `v.2.2 ≠ 0` holds. -/ +def mobile (B : D.Binning a H T R θ) (v : B.target.Vtx) := decide (v.2.2 ≠ 0) + +open scoped Classical in +theorem location (v : t.input.diagram.V) : + ((t.post.vertex v).1, (t.post.vertex v).2.1) = t.chart.coord (t.input.grid.cell v) := rfl + +open scoped Classical in +theorem flag (v : t.input.diagram.V) : decide (t.input.mobile v) = mobile B (t.post.vertex v) := by + unfold mobile + apply decide_eq_decide.mpr + change v.val.2 ≠ none ↔ Sheet.number H v.val.2 ≠ 0 + rw [← Sheet.number_none H, (Sheet.number H).injective.ne_iff] + +open scoped Classical in +/-- Computes the normal by the application `t.chart.normalized t.post t.directed q`. -/ +abbrev normal (q : ℕ) := t.chart.normalized t.post t.directed q +open scoped Classical in +/-- Computes the order by the application `t.post.toOrdered t.directed`. -/ +abbrev order := t.post.toOrdered t.directed +open scoped Classical in +/-- Computes the atlas by the application `t.chart.next t.post t.directed q`. -/ +abbrev atlas (q : ℕ) := t.chart.next t.post t.directed q + +open scoped Classical in +theorem placed (q : ℕ) : (t.normal q).Placed t.order (t.atlas q).coord + (fun i => ((t.atlas q).tone q i).val) (mobile B) := + t.chart.normalized_placed t.post t.directed q (mobile B) t.location t.flag + +open scoped Classical in +theorem ranks (q : ℕ) (h : 2 ≤ q) : (t.normal q).LocalRanks := + t.chart.normalized_ranks t.post t.directed q h (mobile B) t.location t.flag + +open scoped Classical in +theorem eval (q : ℕ) : (t.normal q).diagram.eval = P.diagram.eval := + (t.input.normalize_eval _ _ _).trans + (t.plan.input_eval five B.pos B.hT t.ready t.slack t.loopless B.hH B.hR B.hRT + t.ext t.neutral) + +open scoped Classical in +theorem seats (q : ℕ) : Fintype.card (t.normal q).V * 2 ^ a ≤ 2 * P.seats := t.cells.seats + +end Trial +end Binning +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Size of the grouped station records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) + +theorem fields : + b.target.ℓ = 2 ^ b.depth * (Sheet.slots H + (D.scheme.ℓ + 2 ^ D.scheme.e * (b.target.d + + (Sheet.slots H + b.depth)))) := + Parcel.width D.scheme _ _ _ + +theorem shape : b.target.m = D.scheme.m + (D.scheme.h - a + 1) ∧ b.target.h = a ∧ + b.target.d = D.childD a 5 ∧ b.target.k = Sheet.slots H ∧ b.target.e = b.depth + D.scheme.e + 2 + := + ⟨rfl, rfl, rfl, rfl, rfl⟩ + +theorem capacity : 2 ^ b.target.m * 2 ^ b.target.h = 2 * (2 ^ D.scheme.m * 2 ^ D.scheme.h) := by + rw [b.shape.1, b.shape.2.1, ← pow_add, ← pow_add, ← pow_succ'] + have := b.ha + congr 1; omega + +private theorem clog_bound (n : ℕ) : 2 ^ Nat.clog 2 n ≤ 2 * (n + 1) := by + cases h : Nat.clog 2 n with + | zero => rw [pow_zero]; omega + | succ i => + have he : ¬ n ≤ 2 ^ i := by + intro hn + have := (Nat.clog_le_iff_le_pow (by decide : 1 < 2)).mpr hn + omega + rw [pow_succ'] + exact Nat.mul_le_mul_left _ (by omega) + +private theorem large (n : ℕ) (h : 2 ≤ n) : 64 ≤ (4 * 5 : ℕ) ^ n := + (by decide : 64 ≤ (4 * 5 : ℕ) ^ 2).trans (Nat.pow_le_pow_right (by decide) h) + +private theorem bounded_slots {N K : ℕ} (n : ℕ) (h : N < K) : + 2 ^ min n (Nat.clog 2 N) ≤ 2 * K := + (Nat.pow_le_pow_right (by decide) (min_le_right ..)).trans + ((clog_bound N).trans (Nat.mul_le_mul_left 2 h)) + +theorem nav_bound (hd : D.scheme.d ≤ 4) : 2 ^ (b.target.d + 1) ≤ H ^ 10 := by + have hH : 64 ≤ H := (large 300 (by decide)).trans b.hH.le + have hw : 2 ^ Child.width (D.scheme.h - a) 5 ≤ 2 * H := bounded_slots _ b.hH + have hs : 2 ^ (D.scheme.d + Child.width (D.scheme.h - a) 5 + 1) ≤ H ^ 2 := calc + _ = (2 ^ D.scheme.d * 2 ^ Child.width (D.scheme.h - a) 5) * 2 := by rw [pow_succ, pow_add] + _ ≤ (2 ^ 4 * (2 * H)) * 2 := Nat.mul_le_mul_right _ (Nat.mul_le_mul (Nat.pow_le_pow_right (by + decide) hd) hw) + _ = 64 * H := by ring + _ ≤ H ^ 2 := by rw [pow_two]; exact Nat.mul_le_mul_right H hH + change 2 ^ ((D.scheme.d + Child.width (D.scheme.h - a) 5 + 1) * 3 + 1) ≤ _ + rw [pow_succ, pow_mul] + calc + _ ≤ (H ^ 2) ^ 3 * H := Nat.mul_le_mul (Nat.pow_le_pow_left hs _) (by omega) + _ = H ^ 7 := by rw [← pow_mul, ← pow_succ] + _ ≤ _ := Nat.pow_le_pow_right b.pos (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- +# Recovering the predecessor of an exterior span + +The new host address includes the old host as a prefix. Within +that host the active-row rank determines the old suffix and the +span number retains the old stub. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring Packing Rounds BatchDescent + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} {a H T R : ℕ} {θ L : ℝ} + (b : D.Binning a H T R θ) + +local notation "n" => D.scheme.h - a +local notation "parent" => Match.rowIndex D.scheme.m (n + 1) + +open scoped Classical in +/-- The pointer of type `Option (B 0 × Trail.Stub D.scheme)` for the given inputs. -/ +def pointer (q : (D.Sheet n).obj) (z : B (n + 1)) (l : B a) (e : B b.target.e) : Option (B 0 × + Trail.Stub D.scheme) := + let u := (Parcel.index b.depth D.scheme.e).symm ((Pattern.tag b.raw.e).symm e).2 + (Sheet.find D q b.depth z u.2.1).map (fun j => (0, D.position a b.ha.le l j, 0, u.2.2)) + +open scoped Classical in +/-- Selects the appropriate branch of `if 0 < (b.target.decode s).width v e ∧ (b.target.decode +s).peer v e = none then b.pointer q z l e else none`. -/ +def marked (q : (D.Sheet n).obj) (z : B (n + 1)) (l : B a) (s : B b.target.ℓ) + (v : B b.target.k) (e : B b.target.e) := + if 0 < (b.target.decode s).width v e ∧ (b.target.decode s).peer v e = none + then b.pointer q z l e else none + +open scoped Classical in +/-- Builds `Trail.Move D.scheme b.target 0 where nav i _` with the specified `nav`, `read`, +`let`. -/ +def move (r : D.format.obj) : Trail.Move D.scheme b.target 0 where + nav i _ := (parent i).1 + read q := + let i := parent q.1.1 + b.marked (D.sheet a b.ha 5 H T r i.1 q.1.2.1) i.2 q.1.2.1 ((b.data r q.1.1).2 q.1.2.1) + q.1.2.2 q.2 + +open scoped Classical in +theorem read_eq (r : D.format.obj) (q : b.target.Span) : + (b.move r).read q = + if 0 < b.target.width (b.data r) q ∧ b.target.peer (b.data r) q = none then + b.pointer (D.sheet a b.ha 5 H T r (parent q.1.1).1 q.1.2.1) (parent q.1.1).2 q.1.2.1 q.2 + else none := by + simp only [move, marked, Scheme.width, Scheme.peer, Scheme.pattern, Option.map_eq_none_iff] + +namespace Trial +variable {b} {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} {p : D.Presents r P} + (t : b.Trial p L) + +open scoped Classical in +private theorem outer_eq {S : Scheme F} {r : S.format.obj} {G : Diagram F x y} (p : S.Presentation + r G) + (i : slots x ⊕ slots y) : (p.boundary i).val = p.toSeating.ends (boundaryEnd G i) + := by cases i <;> rfl + +open scoped Classical in +theorem outer (i : slots x ⊕ slots y) : + (t.order.boundary i).val = b.raw.liftPad (b.data r) R false (t.layout.route (Parcel.copy + P.diagram false i)) := by + have sameEnds : t.order.toSeating.ends = t.post.toSeating.ends := + t.post.ordered_ends t.directed + rw [outer_eq, sameEnds] + exact t.layout.padded_end t.sep t.neutral p.directed R i + +open scoped Classical in +/-- Computes the dest by the application `b.raw.seatPad R false (t.layout.span (some false) v +s)`. -/ +def dest (v : P.diagram.V) (s : B D.scheme.e) := + b.raw.seatPad R false (t.layout.span (some false) v s) + +open scoped Classical in +theorem outer_span (i : slots x ⊕ slots y) : + (t.order.boundary i).val.1 = t.dest (portEnd P.diagram i) (p.pres.boundary i).val.1.2 := by + rw [t.outer, outer_eq] + exact congrArg (b.raw.seatPad R false) (t.layout.copy_span false i) + +open scoped Classical in +private theorem dest_eq (v : P.diagram.V) (s : B D.scheme.e) : + t.dest v s = (((t.plan.addr v).1, (t.plan.addr v).2, 0), + Pattern.tag b.raw.e (false, Parcel.index b.depth D.scheme.e (false, t.plan.rank b.depth v, + s))) := rfl + +open scoped Classical in +private theorem pointer_eq (v : P.diagram.V) (hv : 0 < P.diagram.arity v) (s : B D.scheme.e) : + let q := t.dest v s + b.pointer (D.sheet a b.ha 5 H T r (parent q.1.1).1 q.1.2.1) (parent q.1.1).2 q.1.2.1 q.2 = + some (0, (p.pres.vertex v).2.1, 0, s) := by + simp only [dest_eq, Presents.Plan.addr, Presents.Plan.cell_parts, Equiv.apply_symm_apply, + pointer, Equiv.symm_apply_apply] + rw [t.plan.found t.room v hv, Option.map_some, Presents.Plan.given (ha := b.ha)] + +open scoped Classical in +theorem follows : (b.move r).Agrees p.pres t.order where + mapped i := by + let v := portEnd P.diagram i + let s := (p.pres.boundary i).val.1.2 + have he : (p.pres.boundary i).val.1 = (p.pres.vertex v, s) := by + refine Prod.ext ?_ rfl + rw [outer_eq, p.pres.end_station, station_boundary] + have hp : 0 < P.diagram.arity v := Parcel.Manifest.positive (he ▸ (p.pres.boundary i).val.2.pos) + have hz := (t.order.boundary i).property + have hw := (t.order.boundary i).val.2.pos + refine ⟨?_, ?_, ?_⟩ + · rw [Trail.Move.previous, read_eq, ite_eq_left ⟨hw, hz⟩, t.outer_span, t.pointer_eq v hp, + Option.map_some, he] + simp only [move, dest_eq, Presents.Plan.addr, Presents.Plan.cell_parts, + Equiv.apply_symm_apply, Trail.locate] + rw [p.vertex] + · rw [t.outer_span, dest, Scheme.width_pad, he] + exact t.layout.width_eq hp s (some false) (fun _ => he ▸ (p.pres.boundary i).property) + · rw [t.outer, outer_eq] + exact (t.layout.offset _).trans (by rw [Parcel.axis_copy]) + active s hs := by + rw [read_eq] at hs + split at hs + · rename_i ht + obtain ⟨q, hq⟩ := t.order.boundary.surjective ⟨⟨s, ⟨0, ht.1⟩⟩, ht.2⟩ + exact ⟨q, congrArg (fun x => x.val.1) hq⟩ + · contradiction + +end Trial +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- # Grouping and padding do not increase the set of origins at a host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring Packing Rounds BatchDescent + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} {a H T R : ℕ} {θ L : ℝ} + (b : D.Binning a H T R θ) + +open scoped Classical in +/-- The quantity computed by `(Match.rowIndex D.scheme.m (D.scheme.h - a + 1) i).1`. -/ +abbrev parent (i : B b.target.m) := (Match.rowIndex D.scheme.m (D.scheme.h - a + 1) i).1 + +namespace Trial +variable {b} {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} {p : D.Presents r P} + (t : b.Trial p L) + +open scoped Classical in +theorem ancestor_owner (i : slots x ⊕ slots y) : + b.parent (t.order.boundary i).val.1.1.1 = (p.pres.boundary i).val.1.1.1 := by + have h := (t.follows.mapped i).1 + obtain ⟨s, _, he⟩ := Option.map_eq_some_iff.mp h + exact congrArg (fun v : D.scheme.Span => v.1.1) he + +include t in +open scoped Classical in +theorem load_le (i : B b.target.m) : + b.target.load (b.data r) i ≤ D.scheme.load r.1 (b.parent i) := by + let f := t.order.boundary.symm.trans p.pres.boundary + have he (j : b.target.exposed (b.data r)) : + D.scheme.owner r.1 (f j) = b.parent (b.target.owner (b.data r) j) := by + obtain ⟨s, rfl⟩ := t.order.boundary.surjective j + rw [show f (t.order.boundary s) = p.pres.boundary s by + simp only [f, Equiv.trans_apply, Equiv.symm_apply_apply]] + exact (t.ancestor_owner s).symm + let g (x : b.target.fiber (b.data r) i) : D.scheme.fiber r.1 (b.parent i) := + ⟨f x.val, by rw [he, x.property]⟩ + exact Fintype.card_le_of_injective g fun _ _ h => Subtype.ext (f.injective (congrArg Subtype.val + h)) + +include t in +open scoped Classical in +theorem fits {k v : ℕ} (h : D.scheme.Fits r.1 v k) : + b.target.Fits (b.data r) (2 ^ b.target.m + wd x + wd y) k := + t.order.fits le_rfl (fun i => (t.load_le i).trans (h.2 _)) + +variable {h u : ℕ} {Q : Rounds.Board F (copies x (2 ^ h * u)) (copies y (2 ^ h * u)) D.scheme.h} + {q : D.Presents r Q} (s : b.Trial q L) + +open scoped Classical in +theorem origins_le (i : B b.target.m) : + Trail.origins s.order i ⊆ Trail.origins q.pres (b.parent i) := by + intro j hj + obtain ⟨_, u, v, he⟩ := Finset.mem_filter.mp hj + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, u, v, + (s.ancestor_owner _).symm.trans (congrArg b.parent he)⟩ + +open scoped Classical in +theorem tracks {d e : ℕ} {name : Stack.Outer x y ↪ (Fin e → Bool)} + {z : Trail.Record D.scheme h d e} (hu : 0 < u) (hd : 0 < d) + (cap : ∀ i, (Trail.origins q.pres i).card ≤ d) (hT : Trail.Tracks q.pres name z) : + Trail.Tracks s.order name ((b.move r).update d z) := + hT.update s.follows hu hd fun i => (Finset.card_le_card (s.origins_le i)).trans (cap _) + +end Trial +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end + +/- +# Host status and the exact one-step graph + +Routing uses the third neighborhood. The shorter list of actual +neighbors is marked in this list by a Boolean column per host. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +open Coloring Packing Rounds + +variable {F : Type} [Field F] {D : Template F} {a H T R : ℕ} {θ : ℝ} (b : D.Binning a H T R θ) +local notation "n" => D.scheme.h - a +local notation "m" => b.target.m +local notation "d" => b.target.d + +open scoped Classical in +/-- Computes the flags by the application `Format.vec m (.pair .bit (.vec d .bit))`. -/ +abbrev Flags := Format.vec m (.pair .bit (.vec d .bit)) + +open scoped Classical in +/-- The value specified by `Child.step n 5 (D.childInput a b.ha r)`. -/ +abbrev step (r : D.format.obj) := Child.step n 5 (D.childInput a b.ha r) +open scoped Classical in +/-- Evaluates `(D.childLive a r v, Child.coreFlags (D.binNav a b.ha 5 r) (b.step r) v)` at the +input `v`. -/ +def status (r : D.format.obj) : b.Flags.obj := fun v => + (D.childLive a r v, Child.coreFlags (D.binNav a b.ha 5 r) (b.step r) v) + +namespace Trial +variable {b} {x y : Wire} {L : ℝ} {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} + {p : D.Presents r P} (t : b.Trial p L) (q : ℕ) + +local notation "host" => (Input.HostChart.host (t.atlas q)) +local notation "nav" => (Input.HostChart.graph (t.atlas q)) + +open scoped Classical in +theorem nonempty (h : Nonempty P.V) : Nonempty (t.normal q).V := + ⟨(h.some, ⟨0, 0⟩)⟩ + +open scoped Classical in +theorem live_status (i : B m) : (b.status r i).1 = true ↔ i ∈ Set.range host := by + change D.childLive a r i = true ↔ i ∈ Set.range (Child.host p.host n) + simp only [childLive, Bool.and_eq_true, decide_eq_true_eq, p.live] + constructor + · rintro ⟨⟨v, hv⟩, ⟨s, hs⟩⟩ + refine ⟨(v, s), (Match.rowIndex D.scheme.m (n + 1)).injective ?_⟩ + rw [Child.host_parts] + exact Prod.ext hv hs + · rintro ⟨v, rfl⟩ + rw [Child.host_parts] + exact ⟨⟨_, rfl⟩, ⟨_, rfl⟩⟩ + +open scoped Classical in +theorem closed (v : (t.normal q).V) (k : B d) : nav (host v) k ∈ Set.range host := by + obtain ⟨u, _, hu⟩ := ((Presents.Plan.childPresent p b.ha).mem (by decide : 0 < 5) v _).mp ⟨k, rfl⟩ + exact ⟨u, hu⟩ + +open scoped Classical in +theorem edge_status (v w : (t.normal q).V) (hne : v ≠ w) : + w ∈ (t.normal q).adj v ↔ ∃ k, nav (host v) k = host w ∧ (b.status r (host v)).2 k = true := by + have h := (Presents.Plan.childPresent p b.ha).step_mem (by decide : 0 < 5) v (host w) + constructor + · intro hw + obtain ⟨k, hk⟩ := (t.atlas q).adjacent v w hw hne + refine ⟨k, hk, ?_⟩ + unfold status Child.coreFlags; dsimp only + apply decide_eq_true + obtain ⟨j, hj⟩ := (h.mpr ⟨w, hw, rfl⟩).resolve_left ((host).injective.ne hne.symm) + exact ⟨j, hj.trans hk.symm⟩ + · rintro ⟨k, hk, hf⟩ + unfold status Child.coreFlags at hf; dsimp only at hf + obtain ⟨j, hj⟩ := of_decide_eq_true hf + obtain ⟨u, hu, he⟩ := h.mp (.inr ⟨j, hj.trans hk⟩) + exact (host).injective he ▸ hu + +end Trial +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Attachment/WriteNet.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Attachment/WriteNet.lean new file mode 100644 index 0000000000..afde8bc171 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Attachment/WriteNet.lean @@ -0,0 +1,887 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Move +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Length +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Ports.Correspondence +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Checks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Headers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.BoardPush +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Apply +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Described +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Ports.Eval + +/-! # Passing the budget for old labels through a reset -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Coloring Packing Finset + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + (v : Cell a × q.vertex) + +local notation "Q" => G.afterReset q + +open scoped Classical in +theorem footprint_reset : + push q.owner (fun t => (G.footprint t : ℝ)) v ≤ (Q).footprint v.swap := by + let f := Prod.swap ∘ q.owner + have he : push q.owner (fun t => (G.footprint t : ℝ)) v = + push f (fun t => (G.footprint t : ℝ)) v.swap := by + apply sum_congr rfl + intro i _ + simp [f] + have ext : push f (fun t => (G.tetherLoad t : ℝ)) v.swap = (Q).tetherLoad v.swap := by + unfold HostNet.tetherLoad + erw [← exterior_comp, port_load] + have past : push f (fun t => (G.past t + degree G.pair t * u : ℕ)) v.swap = + (Q).past v.swap := by + change _ = (G.carried f v.swap : ℝ) + simp only [HostNet.carried, Nat.cast_sum, Nat.cast_ite, Nat.cast_zero, push] + have add : push f (fun t => (G.footprint t : ℝ)) v.swap = + push f (fun t => (G.past t + degree G.pair t * u : ℕ)) v.swap + + push f (fun t => (G.tetherLoad t : ℝ)) v.swap := by + unfold push + rw [← sum_add_distrib] + refine sum_congr rfl fun t _ => ?_ + split_ifs + · simp only [HostNet.footprint, Nat.cast_add]; exact add_right_comm _ _ _ + · exact (add_zero _).symm + rw [he, add, ext, past] + simp only [HostNet.footprint, Nat.cast_add] + exact le_add_of_nonneg_right (Nat.cast_nonneg (α := ℝ) _) + +open scoped Classical in +/-- The charged used in the `Reset` construction. -/ +def Charged (o : B S.ℓ ≃ B S.ℓ) (unit cost : ℕ) := + ∀ t : G.V × Cell h, 0 < G.tetherLoad t + degree G.pair t * u → + Dense.used (o ((r (p.host t.1)).2 (p.block t.2))).val * unit ≤ cost * G.footprint t + +variable {o : B S.ℓ ≃ B S.ℓ} {unit cost : ℕ} + +open scoped Classical in +theorem inherited_charge (tag : Charged p o unit cost) (hu : 0 < unit) : + inherited p q v o * unit ≤ cost * (Q).footprint v.swap := by + let c : ℝ := (cost : ℝ) / unit + have hc : 0 ≤ c := by unfold c; positivity + have hu' : (0 : ℝ) < unit := Nat.cast_pos.mpr hu + let mass (t : G.V × Cell h) := c * (G.footprint t : ℝ) + have hh := inherited_le p q v o mass (fun t => mul_nonneg hc (Nat.cast_nonneg _)) (by + intro w hw + let t := G.units.place w + have ht := tag t (G.arity_active w hw) + rw [oldLabel, p.vertex_eq] + change (Dense.used (o ((r (p.host t.1)).2 (p.block t.2))).val : ℝ) ≤ + (cost : ℝ) / unit * G.footprint t + rw [div_mul_eq_mul_div, le_div_iff₀ hu'] + exact_mod_cast ht) + have hm : push q.owner mass v ≤ c * (Q).footprint v.swap := by + refine le_trans ?_ (mul_le_mul_of_nonneg_left (footprint_reset q v) hc) + have ee := push_div q.owner (fun t => (G.footprint t : ℝ)) c⁻¹ v + simp only [div_inv_eq_mul, mul_comm _ c] at ee + exact ee.le + have hh := hh.trans hm + rw [show c = (cost : ℝ) / unit from rfl, div_mul_eq_mul_div, le_div_iff₀ hu'] at hh + exact_mod_cast hh + +open scoped Classical in +theorem inherited_bound (tag : Charged p o unit cost) (hu : 0 < unit) (b : ℕ) + (hm : (Q).mass ≤ L.cap) (hl : 89 * B' ≤ (b : ℝ) * unit) : + inherited p q v o ≤ cost * (2 ^ L.discount * b) := by + have hp : (Q).footprint v.swap ≤ 2 ^ L.discount * b * unit := by + have hload := (G.reset_load q v.2 v.1).trans hl + have he := ((Q).footprint_le hm v.swap).trans (mul_le_mul_of_nonneg_left hload (by positivity)) + rw [← mul_assoc] at he + exact_mod_cast he + apply Nat.le_of_mul_le_mul_right _ hu + rw [mul_assoc] + exact (inherited_charge p q v tag hu).trans (Nat.mul_le_mul_left _ hp) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Charging an emitted reset label to the next occurrence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Book.Ready +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} {p : S.Posting r G} + {B' W' : ℝ} {Hcap D : ℕ} + {q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W' Hcap D} + {m d h' e cap : ℕ} {b : Book S u e cap} + {A : Allocation p q (b.scheme m d h')} {nav : B m → B d → B m} (H : b.Ready A nav) + {unit cost : ℕ} + +open scoped Classical in +theorem charged (tag : Charged p b.ord unit cost) (hu : 0 < unit) (hle : unit ≤ u) + (hw : ∀ j, u ≤ p.toPresentation.borderWidth j) : + Charged H.posting (Post.order d e b.d cap) unit (cost + (Post.headerFmt d e b.d).width + + overhead S e) := by + intro w active + let Q := G.afterReset q + let W := (Post.headerFmt d e b.d).width + overhead S e + have hf := Q.active_floor (H.posting.toPresentation.contacts (H.floor hw)) w active + have hl := H.stored w.swap + have hi := inherited_charge p q w.swap tag hu + have hh : W * unit ≤ W * Q.footprint w := Nat.mul_le_mul_left W (hle.trans hf) + calc + _ ≤ (W + inherited p q w.swap b.ord) * unit := Nat.mul_le_mul_right _ hl + _ ≤ W * Q.footprint w + cost * Q.footprint w := by rw [Nat.add_mul]; exact Nat.add_le_add hh hi + _ = _ := by rw [← Nat.add_mul, Nat.add_comm W, Nat.add_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Book.Ready +end + +/- # Sufficient load and label budgets for a host reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing Coloring +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + {unit cost b : ℕ} + +open scoped Classical in +theorem seats_fit (v : Cell a × q.vertex) (hu : 0 < unit) (hle : unit ≤ u) + (hw : ∀ j, u ≤ p.toPresentation.borderWidth j) (hb : 89 * B' ≤ (b : ℝ) * unit) : + Fintype.card (Hidden q v) ≤ b ∧ Fintype.card (Live q v) ≤ b ∧ Fintype.card (Visible p q v) ≤ b + := by + have fit (n : ℕ) (hn : (n : ℝ) * u ≤ 89 * B') : n ≤ b := by + apply Nat.le_of_mul_le_mul_right _ hu + have hh : (n : ℝ) * unit ≤ (b : ℝ) * unit := + (mul_le_mul_of_nonneg_left (Nat.cast_le.mpr hle) (Nat.cast_nonneg _)).trans (hn.trans hb) + exact_mod_cast hh + exact ⟨fit _ (hidden_bound q v), fit _ (live_bound p q v hw), fit _ (visible_bound p q v hw)⟩ + +variable {p q} [Fintype F] {m d h' e cap : ℕ} (t : Book S u e cap) + (A : Allocation p q (t.scheme m d h')) (nav : B m → B d → B m) + +local notation "Host" => Allocation.endHost (q := q) + +open scoped Classical in +theorem Book.ready + (sizes : ∀ j, t.len (t.put (p.toPresentation.borderWidth j)) = p.toPresentation.borderWidth j) + (hop : ∀ (i : q.Survivors) z, + nav (A.host (Host i z)) (A.index (Host i z) (Host i (!z))) = A.host (Host i (!z))) + (hs : q.rule.Simple) + (hn : ∀ w, G.diagram.arity w = 0 → ∀ z, Transcript.sample (G.diagram.table w) z = 1) + (tag : Charged p t.ord unit cost) (hu : 0 < unit) (hle : unit ≤ u) + (hw : ∀ j, u ≤ p.toPresentation.borderWidth j) (hm : (G.afterReset q).mass ≤ L.cap) + (hb : 89 * B' ≤ (b : ℝ) * unit) (he : b ≤ 2 ^ e) + (hc : overhead S e + cost * (2 ^ L.discount * b) ≤ cap) : t.Ready A nav where + sizes := sizes + hop := hop + describe v := by + obtain ⟨hi, hl, _⟩ := seats_fit p q v hu hle hw hb + exact describe p q v (A.seat v) t.ord hs hn (hi.trans he) (hl.trans he) + budget v := (Nat.add_le_add_left (inherited_bound p q v tag hu b hm hb) _).trans hc + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Comparing the long addresses once at every host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +open Coloring Neighborhood +variable {F : Type} [Field F] (A : Template F) (n : ℕ) +local notation "m" => A.scheme.m +local notation "d" => A.scheme.d + +/-- The quantity computed by `A.format.width + 2 ^ m * (100 + (m + 2 ^ ((d + 1) * n))) ^ 50`. -/ +def maskCost := A.format.width + 2 ^ m * (100 + (m + 2 ^ ((d + 1) * n))) ^ 50 + +theorem mask_net (hn : 0 < n) : Circuit F A.format (.vec m (coincides d n)) (mask A n) (maskCost A + n) := by + have nav : Circuit F A.format (Neighborhood.Rows m d) A.nav (A.format.width + + 2 * (Neighborhood.Rows m d).width) := + Circuit.project (A := A.format) (D := Neighborhood.Rows m d) (fun z => .inl (z.1, + .inl z.2)) (fun _ _ => rfl) + let t := m + 2 ^ ((d + 1) * n) + obtain ⟨s, net, hs⟩ := (cheap_walks F m d n hn).comp (cheap_equal F (Nat.le_add_right ..) + (Nat.le_add_left ..)) + refine (nav.comp net).mono ?_ + have hq := Nat.two_pow_pos ((d + 1) * n) + have hc : 2 * (2 ^ m * (100 + t) ^ 26) ≤ 2 ^ m * (100 + t) ^ 50 := calc + _ = 2 ^ m * (2 * (100 + t) ^ 26) := mul_left_comm .. + _ ≤ 2 ^ m * (100 + t) ^ 27 := by rw [pow_succ' (100 + t) 26]; gcongr; omega + _ ≤ _ := Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) (by decide)) + change (Neighborhood.Rows m d).width + _ + s ≤ 2 ^ m * (100 + t) ^ 26 at hs + change _ ≤ A.format.width + 2 ^ m * (100 + t) ^ 50 + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end + +/- # Sending a short window to every child and group -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +open Coloring +variable {F : Type} (A D : Template F) (k n t : ℕ) + (ha : D.scheme.h ≤ A.scheme.h) (hm : D.scheme.m = A.scheme.m + t) + +local notation "a" => D.scheme.h +local notation "m" => A.scheme.m +local notation "d" => A.scheme.d +local notation "W" => Window.Walks n A.scheme.d (row A D.scheme.h k) +local notation "src" => pair A k + +/-- The value specified by `(src).pair ((Format.vec m (coincides d n)).pair (Fmt.groups m d a +W))`. -/ +abbrev gathered := (src).pair ((Format.vec m (coincides d n)).pair (Fmt.groups m d a W)) +/-- Computes the queries by the application `Format.vec D.scheme.m (.vec a (sample A a k n t))`. -/ +abbrev queries := Format.vec D.scheme.m (.vec a (sample A a k n t)) +/-- The quantity computed by `2 ^ a * (W).width`. -/ +def volume := 2 ^ a * (W).width + +/-- The value specified by `(r, mask A n r.1, Window.reads n (packet A a k ha r))`. -/ +def collect (r : (src).obj) : (gathered A D k n).obj := + (r, mask A n r.1, Window.reads n (packet A a k ha r)) + +/-- The distribute of type `(queries A D k n t).obj`, constructed using `Match.rowIndex m t +(Fin.cast (congrArg (2^·) hm) v)`. -/ +def distribute (r : (gathered A D k n).obj) : (queries A D k n t).obj := + fun v i => + let p := Match.rowIndex m t (Fin.cast (congrArg (2^·) hm) v) + ((A.live r.1.1 p.1, p.2), (r.1.2.1, i), r.2.1 p.1, (r.2.2 p.1).2 i) + +/-- Evaluates `look A a k ha n t r (Fin.cast (congrArg (2^·) hm) v) i` at the input `v i`. -/ +def lookupKey (r : (src).obj) : (queries A D k n t).obj := + fun v i => look A a k ha n t r (Fin.cast (congrArg (2^·) hm) v) i + +/-- The window cost used in the `Tile` construction. -/ +def windowCost (N : ℕ) := + 100 * ((src).width + packetCost A a k + maskCost A n + (gathered A D k n).width) + + 136 * (queries A D k n t).width + (n + 1) * Window.readCost m d (volume A D k n) N + +variable [Field F] + +private theorem distribute_net : + Circuit F (gathered A D k n) (queries A D k n t) (distribute A D k n t hm) + ((gathered A D k n).width + 34 * (queries A D k n t).width) := by + apply Window.Tile.project_const + rintro ⟨v, i, j⟩ + let p := Match.rowIndex m t (Fin.cast (congrArg (2^·) hm) v) + rcases j with (j|j)|(j|j)|j|j + · exact .inl ⟨.inl (.inl (.inr (p.1, .inl (.inl j)))), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr t).code p.2 j, fun _ => rfl⟩ + · exact .inl ⟨.inl (.inr (.inl j)), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr a).code i j, fun _ => rfl⟩ + · exact .inl ⟨.inr (.inl (p.1, j)), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inr (p.1, .inr (i, j))), fun _ => rfl⟩ + +theorem window_net {I : Type*} {u N : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + (hn : 0 < n) (access : Access F u L (m + d) (volume A D k n) N) + (x : I → (src).obj) + (hr : ∀ i, Fmt.Reciprocal (.vec A.scheme.h (.addr A.scheme.ℓ)) (x i).1.1) : + Computes F u L src (queries A D k n t) x (lookupKey A D k n t ha hm ∘ x) + (fun _ => 1) (windowCost A D k n t N) := by + have send := Computes.of_map (L := L) (x := x) (Map.circuit hu (packet_net A a k ha)) (fun _ + => rfl) + have read := Window.reads_net (r := n) hu access (fun i => packet A a k ha (x i)) hr le_rfl + have first : Circuit F src A.format Prod.fst ((src).width + 2 * A.format.width) := + Circuit.project Sum.inl (fun _ _ => rfl) + have eqs := Computes.of_map (L := L) (x := x) (Map.circuit hu (first.comp (mask_net A n hn))) + (fun _ => rfl) + have copy := Computes.of_map (L := L) (x := x) (Map.circuit hu (Circuit.id F src)) (fun _ => rfl) + have all := Computes.pair hu copy (Computes.pair hu eqs (send.comp read)) + have output := Computes.of_map (x := collect A D k n ha ∘ x) (L := L) + (Map.circuit hu (distribute_net A D k n t hm)) (fun _ => rfl) + have net := all.comp output + simp only [one_mul] at net + refine net.mono ?_ + have hv : A.format.width ≤ (src).width := by rw [Format.width_pair A.format]; omega + unfold windowCost + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end + +/- +# Selecting a relative header from a short observation + +Only one group is needed for each child. The frozen flag is +available separately at the parent. Global addresses never +enter the dictionary gate. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +open Coloring + +variable {F : Type} (A D : Template F) (k n t : ℕ) + (ha : D.scheme.h ≤ A.scheme.h) (hm : D.scheme.m = A.scheme.m + t) +local notation "m" => A.scheme.m +local notation "d" => A.scheme.d +local notation "l" => D.scheme.d +local notation "src" => pair A k +local notation "Q" => queries A D k n t + +open scoped Classical in +/-- Computes the vertex format by the application `Format.pair .bit (sample A D.scheme.h k n +t)`. -/ +abbrev vertexFormat := Format.pair .bit (sample A D.scheme.h k n t) + +open scoped Classical in +/-- The value specified by `(A.frozen x.1 (Match.rowIndex m t v).1, look A D.scheme.h k ha n t x +v 0)`. -/ +def vertexKey (x : (src).obj) (v : B (m + t)) : (vertexFormat A D k n t).obj := + (A.frozen x.1 (Match.rowIndex m t v).1, look A D.scheme.h k ha n t x v 0) + +open scoped Classical in +/-- The quantity computed by `Format.vec (m + t) (Child.Suffix d t l)`. -/ +abbrev headers := Format.vec (m + t) (Child.Suffix d t l) + +open scoped Classical in +/-- The condition `∀ q q' v v', vertexKey A D k n t ha (x q) v = vertexKey A D k n t ha (x q') +v' → z q v = z q' v'` on the specified data. -/ +def HeaderLocal {I : Type*} (x : I → (src).obj) (z : I → (headers A D t).obj) : Prop := + ∀ q q' v v', vertexKey A D k n t ha (x q) v = vertexKey A D k n t ha (x q') v' → z q v = z q' v' + +open scoped Classical in +/-- The quantity computed by `Format.pair (Neighborhood.Rows m d) (.vec (m + t) (vertexFormat A +D k n t))`. -/ +abbrev request := Format.pair (Neighborhood.Rows m d) (.vec (m + t) (vertexFormat A D k n t)) + +open scoped Classical in +private def take (r : (Format.pair src Q).obj) : (request A D k n t).obj := + (A.nav r.1.1, fun v => + (A.frozen r.1.1 (Match.rowIndex m t v).1, r.2 (Fin.cast (congrArg (2^·) hm.symm) v) 0)) + +open scoped Classical in +/-- The quantity computed by `(vertexFormat A D k n t).width + (Child.Suffix d t l).width`. -/ +def headerWidth := (vertexFormat A D k n t).width + (Child.Suffix d t l).width + +open scoped Classical in +/-- The bound obtained by adding the component charges `100 * ((src).width + (Q).width + +(request A D k n t).width) + windowCost A D k n t N + 2 ^ (m + t) * (1 + headerWidth A D k n +t)`. -/ +def headerCost (N : ℕ) := 100 * ((src).width + (Q).width + (request A D k n t).width) + + windowCost A D k n t N + 2 ^ (m + t) * (1 + headerWidth A D k n t) + +variable [Field F] + +open scoped Classical in +private theorem take_net : + Circuit F (.pair src Q) (request A D k n t) (take A D k n t hm) + ((Format.pair src Q).width + 2 * (request A D k n t).width) := by + let idx : (request A D k n t).pins → (Format.pair src Q).pins + | .inl (v, j) => .inl (.inl (.inl (v, .inl j))) + | .inr (v, .inl j) => .inl (.inl (.inr ((Match.rowIndex m t v).1, .inl (.inr j)))) + | .inr (v, .inr j) => .inr (Fin.cast (congrArg (2^·) hm.symm) v, 0, j) + exact Circuit.project idx (by rintro x (⟨v, j⟩|⟨v, j|j⟩) <;> rfl) + +include hm in +open scoped Classical in +theorem header_net {I : Type*} (x : I → (pair A k).obj) (z : I → (headers A D t).obj) + (h : HeaderLocal A D k n t ha x z) + (hr : ∀ i, Fmt.Reciprocal (.vec A.scheme.h (.addr A.scheme.ℓ)) (x i).1.1) (hn : 0 < n) : + ∃ gate : Table F, Processor.arity gate = headerWidth A D k n t ∧ + ∀ {u N : ℕ} {L : Set (Table F)}, 3 ≤ u → headerWidth A D k n t ≤ u → gate ∈ L → + Access F u L (m + d) (volume A D k n) N → + Computes F u L src (Child.Input m d t l) x (fun i => (A.nav (x i).1, z i)) + (fun _ => 1) (headerCost A D k n t N) := by + let U := vertexFormat A D k n t + let V := Child.Suffix d t l + let gateKey (p : I × B (m + t)) := vertexKey A D k n t ha (x p.1) p.2 + let val (p : I × B (m + t)) := z p.1 p.2 + have hf : Function.FactorsThrough val gateKey := fun _ _ => h _ _ _ _ + let default' : U.obj → V.obj := fun _ => V.code.symm (fun _ => false) + let f := Function.extend gateKey val default' + refine ⟨lookup F U V (fun x y => @ite F (f x = y) (Classical.propDecidable _) 1 0), ?_, ?_⟩ + · simp only [Processor.arity, lookup, wd_word, headerWidth, U, V] + intro u N L hu hw hg access + have one : Map F u L U V f (1 + headerWidth A D k n t) := by + rw [headerWidth, ← add_assoc] + exact Kernel.lookup hw hg + have first := window_net A D k n t ha hm hu hn access x hr + have cp := Computes.of_map (x := x) (L := L) (Map.circuit hu (Circuit.id F src)) (fun _ => rfl) + let y (i : I) : (request A D k n t).obj := (A.nav (x i).1, vertexKey A D k n t ha (x i)) + have prep := (Computes.pair hu cp first).comp (Computes.of_map (y := y) + (Map.circuit hu (take_net A D k n t hm)) (fun _ => rfl)) + have gate := (Map.circuit hu (Circuit.id F (Neighborhood.Rows m d))).par + (Map.vec _ (fun _ : B (m + t) => one)) + have fields (i : I) : Prod.map id (fun x v => f (x v)) (y i) = (A.nav (x i).1, z i) := + Prod.ext rfl (funext fun v => hf.extend_apply default' (i, v)) + have end' := Computes.of_map (x := y) gate fields + have net := prep.comp end' + simp only [one_mul] at net + refine net.mono ?_ + have hv : (Neighborhood.Rows m d).width ≤ (request A D k n t).width := by + rw [Format.width_pair]; exact Nat.le_add_right .. + rw [Format.width_pair src Q, headerCost] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end + +/- # One dictionary gate shared by all reset decisions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +open Coloring +variable {F : Type} (A D : Template F) (k n t : ℕ) + (ha : D.scheme.h ≤ A.scheme.h) (hm : D.scheme.m = A.scheme.m + t) +local notation "a" => D.scheme.h +local notation "m" => D.scheme.m +local notation "U" => sample A D.scheme.h k n t +local notation "V" => output A D +local notation "src" => pair A k +variable {I : Type*} (x : I → (pair A k).obj) (y : I → (whole A D).obj) + +open scoped Classical in +/-- The defining condition `∀ q q' v v' i i', lookupKey A D k n t ha hm (x q) v i = lookupKey A +D k n t ha hm (x q') v' i' → part A D (y q) v i = part A D (y q') v' i'`. -/ +def Local : Prop := + ∀ q q' v v' i i', + lookupKey A D k n t ha hm (x q) v i = lookupKey A D k n t ha hm (x q') v' i' → + part A D (y q) v i = part A D (y q') v' i' + +open scoped Classical in +/-- The quantity computed by `(U).width + (V).width`. -/ +def printWidth := (U).width + (V).width +open scoped Classical in +/-- The bound obtained by adding the component charges `20 * (src).width + H + windowCost A D k +n t N + 2 ^ m * (2 ^ a * (1 + printWidth A D k n t)) + 4 * assembleCost A D`. -/ +def printCost (N H : ℕ) := 20 * (src).width + H + windowCost A D k n t N + + 2 ^ m * (2 ^ a * (1 + printWidth A D k n t)) + 4 * assembleCost A D + +open scoped Classical in +private theorem depends (h : Local A D k n t ha hm x y) : + ∃ f : (U).obj → (V).obj, ∀ q v i, f (lookupKey A D k n t ha hm (x q) v i) = part A D (y q) v i + := by + have hx (z : (U).obj) : ∃ o : (V).obj, + ∀ q v i, lookupKey A D k n t ha hm (x q) v i = z → o = part A D (y q) v i := by + by_cases hs : ∃ q v i, lookupKey A D k n t ha hm (x q) v i = z + · obtain ⟨q, v, i, hq⟩ := hs + exact ⟨part A D (y q) v i, fun q' v' i' ht => h _ _ _ _ _ _ (hq.trans ht.symm)⟩ + · exact ⟨(V).code.symm (fun _ => false), fun q v i he => (hs ⟨q, v, i, he⟩).elim⟩ + choose f hf using hx + exact ⟨f, fun q v i => hf _ _ _ _ rfl⟩ + +open scoped Classical in +theorem print_net [Field F] (h : Local A D k n t ha hm x y) + (hr : ∀ i, Fmt.Reciprocal (.vec A.scheme.h (.addr A.scheme.ℓ)) (x i).1.1) (hn : 0 < n) : + ∃ gate : Table F, Processor.arity gate = printWidth A D k n t ∧ + ∀ {u N H : ℕ} {L : Set (Table F)}, 3 ≤ u → printWidth A D k n t ≤ u → gate ∈ L → + Access F u L (A.scheme.m + A.scheme.d) (volume A D k n) N → + Computes F u L src (graph D) x (fun i => header D (y i).1) (fun _ => 1) H → + Computes F u L src (whole A D) x y (fun _ => 1) (printCost A D k n t N H) := by + obtain ⟨f, hf⟩ := depends A D k n t ha hm x y h + refine ⟨lookup F U V (fun x y => @ite F (f x = y) (Classical.propDecidable _) 1 0), ?_, ?_⟩ + · simp only [Processor.arity, lookup, wd_word, printWidth] + intro u N H L hu hw hg access heads + have one : Map F u L U V f (1 + printWidth A D k n t) := + by rw [printWidth, ← add_assoc]; exact Kernel.lookup hw hg + have rows := Map.vec _ (fun _ : B m => Map.vec _ (fun _ : B a => one)) + have fields : Computes F u L (queries A D k n t) (body A D) (lookupKey A D k n t ha hm ∘ x) + (fun i => part A D (y i)) (fun _ => 1) (2 ^ m * (2 ^ a * (1 + printWidth A D k n t))) := by + refine Computes.of_map rows ?_ + intro q; funext v i; exact hf q v i + have area := window_net A D k n t ha hm hu hn access x hr + have all := Computes.pair hu heads (area.comp fields) + have net := all.comp (Computes.of_map (y := y) (Map.circuit hu (assemble_net A D)) + (fun i => assemble_part A D (y i))) + simp only [one_mul] at net + exact net.mono (by unfold printCost; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end + +/- # Issuing attachment requests from the reset windows -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile + +open Coloring +variable {F : Type} (A D : Template F) (T : Attachment A) (k n t slots : ℕ) + (ha : D.scheme.h ≤ A.scheme.h) (hm : D.scheme.m = A.scheme.m + t) +local notation "U" => sample A D.scheme.h k n t +local notation "V" => Format.pair Format.bit (T.orders D slots 0) +local notation "src" => pair A k +variable {I : Type*} (x : I → (pair A k).obj) (qs : I → Attachment.Query T D slots 0) + +open scoped Classical in +/-- The defining condition `∀ q q' v v' i i', lookupKey A D k n t ha hm (x q) v i = lookupKey A +D k n t ha hm (x q') v' i' → ((qs q).ticketAt v i).2 = ((qs q').ticketAt v' i').2`. -/ +def QueryLocal : Prop := + ∀ q q' v v' i i', + lookupKey A D k n t ha hm (x q) v i = lookupKey A D k n t ha hm (x q') v' i' → + ((qs q).ticketAt v i).2 = ((qs q').ticketAt v' i').2 + +open scoped Classical in +/-- The quantity computed by `(U).width + (V).width`. -/ +def queryWidth := (U).width + (V).width +open scoped Classical in +/-- The bound obtained by adding the component charges `4 * T.format.width + 20 * (src).width + +H + windowCost A D k n t N + 2 ^ D.scheme.m * (2 ^ D.scheme.h * (1 + queryWidth A D T k n t +slots))`. -/ +def queryCost (N H : ℕ) := + 4 * T.format.width + 20 * (src).width + H + windowCost A D k n t N + + 2 ^ D.scheme.m * (2 ^ D.scheme.h * (1 + queryWidth A D T k n t slots)) + +open scoped Classical in +private theorem ticket (h : QueryLocal A D T k n t slots ha hm x qs) : + ∃ f : (U).obj → (V).obj, + ∀ q v i, f (lookupKey A D k n t ha hm (x q) v i) = ((qs q).ticketAt v i).2 := by + have hx (z : (U).obj) : ∃ o : (V).obj, + ∀ q v i, lookupKey A D k n t ha hm (x q) v i = z → o = ((qs q).ticketAt v i).2 := by + by_cases hs : ∃ q v i, lookupKey A D k n t ha hm (x q) v i = z + · obtain ⟨q, v, i, hq⟩ := hs + exact ⟨_, fun q' v' i' ht => h q q' v v' i i' (hq.trans ht.symm)⟩ + · exact ⟨(V).code.symm (fun _ => false), fun q v i he => (hs ⟨q, v, i, he⟩).elim⟩ + choose f hf using hx + exact ⟨f, fun q v i => hf _ _ _ _ rfl⟩ + +open scoped Classical in +/-- The separate dictionary gate emits all local controls. Its input +window and the fresh core use the same reset data. -/ +theorem query_net [Field F] (h : QueryLocal A D T k n t slots ha hm x qs) + (hr : ∀ i, Fmt.Reciprocal (.vec A.scheme.h (.addr A.scheme.ℓ)) (x i).1.1) (hn : 0 < n) : + ∃ gate : Table F, Processor.arity gate = queryWidth A D T k n t slots ∧ + ∀ {u N H : ℕ} {L : Set (Table F)}, 3 ≤ u → queryWidth A D T k n t slots ≤ u → gate ∈ L → + Access F u L (A.scheme.m + A.scheme.d) (volume A D k n) N → + Computes F u L src D.format x (fun i => (qs i).fresh) (fun _ => 1) H → + Computes F u L (T.format.pair src) (T.Requests D slots 0) + (fun i => ((qs i).old, x i)) (fun i => (qs i).requests) (fun _ => 1) + (queryCost A D T k n t slots N H) := by + obtain ⟨f, hf⟩ := ticket A D T k n t slots ha hm x qs h + refine ⟨lookup F U V (fun x y => @ite F (f x = y) (Classical.propDecidable _) 1 0), ?_, ?_⟩ + · simp only [Processor.arity, lookup, wd_word, queryWidth] + intro u N H L hu hw hg access fresh + have one : Map F u L U V f (1 + queryWidth A D T k n t slots) := + by rw [queryWidth, ← add_assoc]; exact Kernel.lookup hw hg + have rows := Map.vec _ (fun _ : B D.scheme.m => Map.vec _ (fun _ : B D.scheme.h => one)) + have data : Computes F u L (queries A D k n t) (.vec D.scheme.m (.vec D.scheme.h V)) + (lookupKey A D k n t ha hm ∘ x) (fun i v j => ((qs i).ticketAt v j).2) (fun _ => 1) + (2 ^ D.scheme.m * (2 ^ D.scheme.h * (1 + queryWidth A D T k n t slots))) := by + refine Computes.of_map rows ?_ + intro i; funext v j; exact hf i v j + have area := window_net A D k n t ha hm hu hn access x hr + have keep := Computes.of_map (x := fun i => (qs i).old) (L + := L) (Map.circuit hu (Circuit.id F T.format)) + (fun _ => rfl) + have all := keep.par (Computes.pair hu fresh (area.comp data)) + simp only [one_mul] at all + exact all.mono (by unfold queryCost; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end + +/- # One short lookup table computes all reset records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +open Packing Coloring Setup +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w k n : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] {U V : Setup A.scheme A.scheme.h u a Δ D Y w W} + {b : Board A U k} {c : Board A V k} + {R : Rotor F Y w} {fit : U.Fits R cost} {fit' : V.Fits R cost} + {e cap t d : ℕ} {B' : Book A.scheme u e cap} + {L : U.Layout R fit B' (A.scheme.m + t) d} {L' : V.Layout R fit' B' (A.scheme.m + t) d} + {g g' : (Child.Graph (A.scheme.m + t) d).obj} + {locate : Coord R A.scheme.h a Δ ↪ B t} + (M : Template.Meter) +local notation "E" => A.resetTarget B' M (A.scheme.m + t) d a + +open scoped Classical in +theorem part_eq (hn : A.scheme.h - a + 8 ≤ n) (hD : 0 < D) + (delayed : A.full = false → A.scheme.h - a ≤ 32 * Nat.clog 2 (2 * D)) + (hp : Placed A L locate) (hq : Placed A L' locate) (ha : Ranked L) (hb : Ranked L') + (hi : ∀ v z σ, Sample b c v z σ n → IndexAgrees L L' (path v z) σ v z) + (hu : ∀ t, U.G.diagram.arity t = 0 → ∀ x, Transcript.sample (U.G.diagram.table t) x = 1) + (hv : ∀ t, V.G.diagram.arity t = 0 → ∀ x, Transcript.sample (V.G.diagram.table t) x = 1) + (hs : B'.Ready L g.1) (ht : B'.Ready L' g'.1) + {i j : B (A.scheme.m + t)} {x y : B a} + (he : Tile.look A a k U.groups n t b.tape i x = Tile.look A a k V.groups n t c.tape j y) : + Tile.part A E (emitted M L g (parent A t)) i x = + Tile.part A E (emitted M L' g' (parent A t)) j y := by + rcases matched hp hq he with ⟨hl, hr⟩|⟨σ, v, z, loc, rfl, rfl, rfl, rfl, h⟩ + · exact (emitted_vacant M L g (parent A t) hl x).trans (emitted_vacant M L' g' (parent A t) hr + y).symm + · exact h.cell hn hD delayed ha hb (hi v z σ h) hu hv loc M hs ht hp.block hq.block (parent A t) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +end + +/- # Locality of the graph header from a single group's sample -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +open Packing Coloring Setup +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w k n : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] {U V : Setup A.scheme A.scheme.h u a Δ D Y w W} + {b : Board A U k} {c : Board A V k} + {R : Rotor F Y w} {fit : U.Fits R cost} {fit' : V.Fits R cost} + {e cap t d : ℕ} {B' : Book A.scheme u e cap} + {L : U.Layout R fit B' (A.scheme.m + t) d} {L' : V.Layout R fit' B' (A.scheme.m + t) d} + {locate : Coord R A.scheme.h a Δ ↪ B t} + (M : Template.Meter) +local notation "E" => A.resetTarget B' M (A.scheme.m + t) d a + +open scoped Classical in +theorem vertex_eq (hp : Placed A L locate) (hq : Placed A L' locate) + (f g : B (A.scheme.m + t) → (Child.Suffix A.scheme.d t d).obj) + (idle : ∀ i j, i ∉ Set.range L.host → j ∉ Set.range L'.host → + (Match.rowIndex _ t i).2 = (Match.rowIndex _ t j).2 → f i = g j) + (active : ∀ v z σ loc, Preview b.read c.read (path v z) n → (U.G.frozen v ↔ V.G.frozen z) → + f (L.host (U.station R fit σ v loc).2) = g (L'.host (V.station R fit' σ z loc).2)) + {i j : B (A.scheme.m + t)} + (he : Tile.vertexKey A E k n t U.groups b.tape i = Tile.vertexKey A E k n t V.groups c.tape j) : + f i = g j := by + obtain ⟨hf, hl⟩ := Prod.mk.inj he + change Tile.look A a k U.groups n t b.tape i 0 = Tile.look A a k V.groups n t c.tape j 0 at hl + rcases matched hp hq hl with ⟨hs, ht⟩ | ⟨σ, v, z, loc, _, _, rfl, rfl, h⟩ + · exact idle _ _ hs ht (congrArg (fun x => x.1.2) hl) + apply active v z σ loc h.look.preview + rw [← b.frozen, ← c.frozen] + simp only [hp.host, hq.host, Equiv.apply_symm_apply] at hf + rw [hf] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +end + +/- # Choosing a layout and common header for each input branch -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w k : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] {I : Type*} (U : I → Setup A.scheme A.scheme.h u a Δ D Y w W) + (R : Rotor F Y w) (fit : ∀ i, (U i).Fits R cost) (boards : ∀ i, Board A (U i) k) + {e cap : ℕ} (b : Book A.scheme u e cap) (M : Template.Meter) (ha : a ≤ A.scheme.h) +local notation "E" => (A.reset R Δ D a b M) +local notation "t" => (Child.extra R Δ (A.scheme.h - a)) +local notation "mx" => (A.scheme.m + t) +local notation "dx" => (Child.width D Y A.full) +local notation "n" => (A.scheme.h - a + 8) + +open scoped Classical in +/-- The data for the selection construction, including `layout`, `graph`, `address`, `placed`, +`ranked`. -/ +structure Selection where + /-- The `Selection` component of type `∀ i, (U i).Layout R (fit i) b mx dx`. -/ + layout : ∀ i, (U i).Layout R (fit i) b mx dx + /-- The `Selection` component of type `I → (Child.Graph mx dx).obj`. -/ + graph : I → (Child.Graph mx dx).obj + /-- The address of each position carried by `Selection`, with type `Coord R A.scheme.h a Δ ↪ B + t`. -/ + address : Coord R A.scheme.h a Δ ↪ B t + placed : ∀ i, Placed A (layout i) address + ranked : ∀ i, Ranked (layout i) + agree : ∀ i j v z σ, Board.Sample (boards i) (boards j) v z σ n → + IndexAgrees (layout i) (layout j) (Board.path v z) σ v z + describes : ∀ i, Child.Describes (m := mx) (d := dx) A.full + ((U i).graph R (fit i)) (layout i).host (layout i).index (graph i) + /-- The `Selection` component of type `I → (Tile.headers A E t).obj`. -/ + headers : I → (Tile.headers A E t).obj + control : Tile.HeaderLocal A E k n t ha (fun i => (boards i).tape) headers + build : ∀ i, Child.build A.scheme.m A.scheme.d t dx (A.nav (boards i).tape.1, headers i) = graph i + +namespace Selection +variable {U R fit boards b M ha} (s : Selection U R fit boards b M ha) + +open scoped Classical in +/-- Computes the output by the application `emitted M (s.layout i) (s.graph i) (parent A t)`. -/ +abbrev output (i : I) : (Tile.whole A E).obj := + emitted M (s.layout i) (s.graph i) (parent A t) + +open scoped Classical in +theorem fields (hD : 0 < D) (delayed : A.full = false → A.scheme.h - a ≤ 32 * Nat.clog 2 (2 * D)) + (neutral : ∀ i v, (U i).G.diagram.arity v = 0 → ∀ x, + Transcript.sample ((U i).G.diagram.table v) x = 1) + (ready : ∀ i, b.Ready (s.layout i) (s.graph i).1) : + Tile.Local A E k n t ha rfl (fun i => (boards i).tape) s.output := by + intro i j _ _ _ _ eq + exact Board.part_eq M le_rfl hD delayed (s.placed i) (s.placed j) (s.ranked i) (s.ranked j) + (s.agree i j) (neutral i) (neutral j) (ready i) (ready j) eq + +end Selection +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # A single controlled layout across all branches of a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w k : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] {I : Type*} (U : I → Setup A.scheme A.scheme.h u a Δ D Y w W) + (R : Rotor F Y w) (fit : ∀ i, (U i).Fits R cost) (boards : ∀ i, Board A (U i) k) + {e cap : ℕ} (b : Book A.scheme u e cap) (M : Template.Meter) (ha : a ≤ A.scheme.h) +local notation "E" => (A.reset R Δ D a b M) +local notation "ex" => (Child.extra R Δ (A.scheme.h - a)) +local notation "mx" => (A.scheme.m + ex) +local notation "dx" => (Child.width D Y A.full) +local notation "n" => (A.scheme.h - a + 8) + +open scoped Classical in +/-- The select of type `Selection U R fit boards b M ha`, constructed using `(U i).index R (fit +i) A.full`. -/ +def select (room : ∀ i, (U i).Room R (fit i) (E).scheme) : + Selection U R fit boards b M ha := by + let idx i := (U i).index R (fit i) A.full + let hd i := (U i).desc R (fit i) A.full + let L i := (U i).arrange R (fit i) b (idx i) (room i) + have place i := (U i).arrange_placed R (fit i) b (idx i) (room i) + refine ⟨L, fun i => Child.build _ _ _ _ (A.nav (boards i).tape.1, hd i), + Child.code R Δ (A.scheme.h - a), place, fun i + => (U i).arrange_ranked R (fit i) b (idx i) (room i), + ?_, fun i => (U i).describes R (fit i) (boards i), hd, ?_, fun _ => rfl⟩ + · intro i j v z σ h v' z' hr loc loc' + apply h.look.preview.idx_match R (fit i) (fit j) (k := 0) (by omega) + · rw [station_parts, station_parts] + exact Board.start v z + · rw [station_parts, station_parts] + · rw [station_parts, station_parts] + exact h.look.widen (by omega) hr + · rw [station_parts, station_parts] + · intro i j x y h + apply Board.vertex_eq M (place i) (place j) (hd i) (hd j) _ _ h + · intro v z hv hz he + unfold hd + rw [desc_vacant _ _ _ _ _ hv, desc_vacant _ _ _ _ _ hz, he] + · intro v z σ loc p frozen + change hd i ((U i).host R (fit i) _) = hd j ((U j).host R (fit j) _) + unfold hd + refine ((U i).desc_live R (fit i) A.full _).trans (Eq.trans ?_ ((U j).desc_live R (fit j) + A.full _).symm) + apply p.suffix_eq R (fit i) (fit j) (k := 0) (by omega) + · rw [station_parts, station_parts] + exact Board.start v z + · rw [station_parts, station_parts] + · change (U i).G.frozen (((U i).result R (fit i)).origin _) ↔ + (U j).G.frozen (((U j).result R (fit j)).origin _) + rw [station_owner, station_owner] + exact frozen + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The two local gates that write a reset from summarized inputs -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +open Coloring + +variable {F : Type} [Field F] + +open scoped Classical in +private theorem build_net {m d t l j u : ℕ} {L : Set (Table F)} (hm : j = m + t) (hu : 3 ≤ u) : + Map F u L (Child.Input m d t l) (Child.Graph j l) + (fun x => cast (congrArg (fun i => (Child.Graph i l).obj) hm.symm) (Child.build m d t l x)) + (4 * Child.buildCost m d t l) := by + subst j + exact Map.circuit hu (Child.build_net F m d t l) + +variable (A D : Template F) (k n t : ℕ) (ha : D.scheme.h ≤ A.scheme.h) (hm : D.scheme.m + = A.scheme.m + t) +local notation "m" => A.scheme.m +local notation "d" => A.scheme.d +local notation "l" => D.scheme.d + +open scoped Classical in +theorem writer_net {I : Type*} (x : I → (pair A k).obj) (y : I → (whole A D).obj) + (z : I → (headers A D t).obj) (fields : Local A D k n t ha hm x y) + (control : HeaderLocal A D k n t ha x z) + (build : ∀ i, cast (congrArg (fun v => (Child.Graph v l).obj) hm.symm) + (Child.build m d t l (A.nav (x i).1, z i)) = header D (y i).1) + (hr : ∀ i, Fmt.Reciprocal (.vec A.scheme.h (.addr A.scheme.ℓ)) (x i).1.1) (hn : 0 < n) : + ∃ f g : Table F, Processor.arity f = printWidth A D k n t ∧ Processor.arity g + = headerWidth A D k n t ∧ + ∀ {u N : ℕ} {L : Set (Table F)}, 3 ≤ u → printWidth A D k n t ≤ u → headerWidth A D k n t + ≤ u → + f ∈ L → g ∈ L → Access F u L (m + d) (volume A D k n) N → + Computes F u L (pair A k) (whole A D) x y (fun _ => 1) + (printCost A D k n t N (headerCost A D k n t N + 4 * Child.buildCost m d t l)) := by + obtain ⟨f, hf, body⟩ := print_net A D k n t ha hm x y fields hr hn + obtain ⟨g, hg, head⟩ := header_net A D k n t ha hm x z control hr hn + refine ⟨f, g, hf, hg, ?_⟩ + intro u N L hu hp hq h₁ h₂ access + have next := (head hu hq h₂ access).comp (Computes.of_map + (y := fun i => header D (y i).1) (build_net (L:=L) hm hu) build) + simp only [one_mul] at next + exact body hu hp h₁ access next + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end + +/- # Writing the reset network and its frozen-station controls -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +open Coloring + +variable {F : Type} (A D : Template F) (T : Attachment A) (k n t slots : ℕ) + (ha : D.scheme.h ≤ A.scheme.h) (hm : D.scheme.m = A.scheme.m + t) + +open scoped Classical in +/-- The maximum of the quantities in `(max (printWidth A D k n t) (headerWidth A D k n t)) +(queryWidth A D T k n t slots)`. -/ +def attachedWidth := + max (max (printWidth A D k n t) (headerWidth A D k n t)) (queryWidth A D T k n t slots) + +open scoped Classical in +/-- The attached cost used in the `Tile` construction. -/ +def attachedCost (N : ℕ) := + queryCost A D T k n t slots N + (printCost A D k n t N (headerCost A D k n t N + + 4 * Child.buildCost A.scheme.m A.scheme.d t D.scheme.d) + + 4 * ((whole A D).width + 2 * D.format.width)) + +open scoped Classical in +/-- The dictionary contains at most three local tables, independent +of the state, host, group and old attachment labels. -/ +theorem attached_net [Field F] {I : Type*} (x : I → (pair A k).obj) + (qs : I → Attachment.Query T D slots 0) (z : I → (headers A D t).obj) + (hloc : Local A D k n t ha hm x (fun i => ((qs i).fresh, (qs i).M.commands))) + (hheader : HeaderLocal A D k n t ha x z) + (hbuild : ∀ i, cast (congrArg (fun v => (Child.Graph v D.scheme.d).obj) hm.symm) + (Child.build A.scheme.m A.scheme.d t D.scheme.d (A.nav (x i).1, z i)) = header D (qs i).fresh) + (hquery : QueryLocal A D T k n t slots ha hm x qs) + (hr : ∀ i, Fmt.Reciprocal (.vec A.scheme.h (.addr A.scheme.ℓ)) (x i).1.1) (hn : 0 < n) : + ∃ gates : Finset (Table F), gates.card ≤ 3 ∧ + (∀ f ∈ gates, Processor.arity f ≤ attachedWidth A D T k n t slots) ∧ + ∀ {u N : ℕ} {L : Set (Table F)}, 3 ≤ u → attachedWidth A D T k n t slots ≤ u → + (∀ f ∈ gates, f ∈ L) → Access F u L (A.scheme.m + A.scheme.d) (volume A D k n) N → + Computes F u L (T.format.pair (pair A k)) (T.Requests D slots 0) + (fun i => ((qs i).old, x i)) (fun i => (qs i).requests) (fun _ => 1) + (attachedCost A D T k n t slots N) := by + let y (i : I) : (whole A D).obj := ((qs i).fresh, (qs i).M.commands) + obtain ⟨f, g, hf, hg, write⟩ := writer_net A D k n t ha hm x y z hloc hheader hbuild hr hn + obtain ⟨e, he, run⟩ := query_net A D T k n t slots ha hm x qs hquery hr hn + refine ⟨{f, g, e}, Finset.card_le_three, ?_, ?_⟩ + · simp only [Finset.mem_insert, Finset.mem_singleton] + rintro _ (rfl|rfl|rfl) <;> unfold attachedWidth <;> omega + intro u N L hu hw hl access + unfold attachedWidth at hw + have h := write hu (by omega) (by omega) (hl f (by simp)) (hl g (by simp)) access + have proj : Circuit F (whole A D) D.format Prod.fst ((whole A D).width + 2 * D.format.width) := + Circuit.project Sum.inl (fun _ _ => rfl) + have fresh := h.comp (Computes.of_map (y := fun i => (qs i).fresh) (Map.circuit hu proj) + (fun _ => rfl)) + simp only [one_mul] at fresh + exact run hu (by omega) (hl e (by simp)) access fresh + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Described.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Described.lean new file mode 100644 index 0000000000..826985fe03 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Described.lean @@ -0,0 +1,827 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Ports.Eval +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Factor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Apply +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Headers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep + +/-! +# Relocating frozen stations after a reset + +Retain the old seat and the suffix of the mixed block. The child block +supplies the prefix, so the inverse mixer recovers the original block. +The ownership test suppresses duplicates at all other children. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing Coloring +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w : ℕ} {W c : ℝ} + [NeZero Y] [NeZero w] (T : Attachment A) (U : Setup A.scheme A.scheme.h u a Δ D Y w W) + {R : Rotor F Y w} {fit : U.Fits R c} {e cap t d : ℕ} {b : Book A.scheme u e cap} + +local notation "n" => A.scheme.h - a +local notation "k" => A.scheme.h - a + T.k + +open scoped Classical in +/-- The value specified by `U.Z.π.symm ((splitCell a U.groups).symm ((cellIndex a).symm i, +(cellIndex _).symm j))`. -/ +def recover (i : B a) (j : B n) : Cell A.scheme.h := + U.Z.π.symm ((splitCell a U.groups).symm ((cellIndex a).symm i, (cellIndex _).symm j)) + +omit [Fintype F] [NeZero Y] [NeZero w] in +open scoped Classical in +theorem recover_eq (i : B a) (j : B n) (s : Cell A.scheme.h) : + U.recover i j = s ↔ i = cellIndex a (U.Z.group s) ∧ + j = cellIndex _ (suffix a (U.Z.π s)) := by + unfold recover + rw [LinearEquiv.symm_apply_eq, Equiv.symm_apply_eq] + change (_, _) = (U.Z.group s, suffix a (U.Z.π s)) ↔ _ + rw [Prod.mk.injEq, Equiv.symm_apply_eq, Equiv.symm_apply_eq] + +open scoped Classical in +/-- The value specified by `(Match.rowIndex n T.k).symm (cellIndex _ (suffix a (U.Z.π (U.G.park +i).2)), slot i)`. -/ +def resetSlot (slot : U.T → B T.k) (i : U.T) : B k := + (Match.rowIndex n T.k).symm (cellIndex _ (suffix a (U.Z.π (U.G.park i).2)), slot i) + +omit [Fintype F] [NeZero Y] [NeZero w] in +open scoped Classical in +theorem resetSlot_pos (slot : U.T → B T.k) (hs : ∀ i, slot i ≠ 0) (i : U.T) : + resetSlot T U slot i ≠ 0 := by + intro h + have hz : (Match.rowIndex n T.k 0).2 = 0 := by apply Fin.ext; simp [Match.rowIndex] + have h' := congrArg (fun z => (Match.rowIndex n T.k z).2) h + rw [resetSlot, Equiv.apply_symm_apply, hz] at h' + exact hs i h' + +variable {U} (M : Template.Meter) (L : U.Layout R fit b (A.scheme.m + t) d) +local notation "Out" => A.resetTarget b M (A.scheme.m + t) d a +local notation "P" => U.result R fit + +open scoped Classical in +/-- The condition `∃ v, L.host ((P).owner (v, s)).2 = j` on the specified data. -/ +def hosts (j : B (A.scheme.m + t)) (s : Cell A.scheme.h) := + ∃ v, L.host ((P).owner (v, s)).2 = j + +open scoped Classical in +/-- Builds `T.Relocation Out k where parent` with the specified `parent`, `prev`, `let`, `let`. -/ +def relocation : T.Relocation Out k where + parent := Setup.parent A t + prev v i j := + let y := Match.rowIndex n T.k j + let s := U.recover i y.1 + if hosts L v s then some (cellIndex _ s, y.2) else none + +variable {L} {locate : Coord R A.scheme.h a Δ ↪ B t} (pl : Placed A L locate) + +include pl in +open scoped Classical in +theorem Placed.owner_parent (v : U.G.V) (j : Cell A.scheme.h) : + Setup.parent A t (L.host ((P).owner (v, j)).2) = U.post.host v := by + rw [pl.parent, (P).origin_owner] + +include pl in +open scoped Classical in +theorem Placed.back (slot : U.T → B T.k) (i : U.T) (v : B (A.scheme.m + t)) (j : B a) (s : B k) : + (relocation T M L).back (v, j, s) = + some (U.post.host (U.G.park i).1, cellIndex _ (U.G.park i).2, slot i) ↔ + (v, j, s) = (L.host ((U.graph R fit).park i).1, cellIndex a ((U.graph R fit).park i).2, + resetSlot T U slot i) := by + let p := U.G.park i + let q := Match.rowIndex n T.k + let block := U.recover j (q s).1 + let grp := cellIndex a (U.Z.group p.2) + let suffixIdx := cellIndex _ (suffix a (U.Z.π p.2)) + let dest := L.host ((P).owner p).2 + change Option.map (Prod.mk (Setup.parent A t v)) + (if hosts L v block then some (cellIndex _ block, (q s).2) else none) = + some (U.post.host p.1, cellIndex _ p.2, slot i) ↔ (v, j, s) = (dest, grp, q.symm (suffixIdx, + slot i)) + constructor + · intro he + split at he <;> try contradiction + rename_i h + simp only [Option.map_some, Option.some.injEq, Prod.mk.injEq, (cellIndex _).injective.eq_iff] + at he + obtain ⟨hv, hb, hs⟩ := he + obtain ⟨hj, hq⟩ := (U.recover_eq ..).mp hb + obtain ⟨u, hu⟩ := h + have hu' : u = p.1 := U.post.host.injective ((pl.owner_parent u block).symm.trans (hu ▸ hv)) + rw [hu', hb] at hu + exact Prod.ext hu.symm (Prod.ext hj (q.eq_symm_apply.mpr (Prod.ext hq hs))) + · intro he + obtain ⟨hv, hj, hs⟩ := (by simpa only [Prod.mk.injEq] using he) + have eqn := q.eq_symm_apply.mp hs + have hb : block = p.2 := (U.recover_eq ..).mpr ⟨hj, congrArg Prod.fst eqn⟩ + have ok : hosts L v block := ⟨p.1, by rw [hb]; exact hv.symm⟩ + rw [ite_eq_left ok, Option.map_some, hb, eqn, hv, show Setup.parent A t dest + = U.post.host p.1 from pl.owner_parent ..] + +include pl in +open scoped Classical in +theorem Placed.moves {x y : Wire} {Z : Border F U.T x y U.x U.y} {s : (Out).format.obj} + {r : T.format.obj} (q : T.Encloses r U.G Z) (p : (Out).Encodes s (U.graph R fit)) + (h : q.core.post.host = U.post.host) (h' : p.post.host = L.host) : + (relocation T M L).Moves q p (resetSlot T U q.slot) where + positive := resetSlot_pos T U q.slot q.positive + iff := by + rintro ⟨v, j, s⟩ i + rw [q.frozen, q.core.block, p.block, h, h'] + exact pl.back T M q.slot i v j s + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Active and vacant output records of a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring BatchDescent.Trail + +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] {U V : Setup A.scheme A.scheme.h u a Δ D Y w B'} {R : Rotor F Y w} + {fit : U.Fits R c} {fit' : V.Fits R c} {e cap mx dx : ℕ} {b : Book A.scheme u e cap} + (M : Template.Meter) (L : U.Layout R fit b mx dx) (g : (Child.Graph mx dx).obj) + (parent : B mx → B A.scheme.m) +local notation "E" => (A.resetTarget b M mx dx a) + +open scoped Classical in +/-- The value specified by `(printed M L g, (L.move parent).commands)`. -/ +def emitted : (Tile.whole A E).obj := (printed M L g, (L.move parent).commands) + +open scoped Classical in +/-- The indexed operation `(((Post.record dx e b.d (.addr cap)).serial Post.vacant, 0), fun _ _ +=> point A.scheme none)`. -/ +def vacant : (Tile.output A E).obj := + (((Post.record dx e b.d (.addr cap)).serial Post.vacant, 0), fun _ _ => point A.scheme none) + +open scoped Classical in +theorem emitted_vacant {v : B mx} (hv : v ∉ Set.range L.host) (i : B a) : + Tile.part A E (emitted M L g parent) v i = vacant M := by + have he : (v, i, 0) ∉ Set.range L.vertex := by + rintro ⟨t, ht⟩ + exact hv ⟨t.2, congrArg Prod.fst ht⟩ + have hp (j : B 0) (t : B e) : ((v, i, j), t) ∉ Set.range L.span := by + rintro ⟨x, hx⟩ + exact hv ⟨(whereAt _ _ x).2, congrArg (fun p => p.1.1) hx⟩ + apply Prod.ext + · apply Prod.ext + · exact congrArg (Post.record dx e b.d (.addr cap)).serial + (L.record_vacant (b.size _ _) (b.data L) _ he) + · change counters M L v i = 0 + unfold counters + exact Function.extend_apply' _ _ _ hv + · funext j t + exact congrArg (point A.scheme) (L.read_idle parent _ (hp j t)) + +open scoped Classical in +theorem emitted_at (blk : L.block = (cellIndex a).toEmbedding) (v : U.At R fit) : + Tile.part A E (emitted M L g parent) (L.host v.2) (L.block v.1) = + (((b.output L g.1 (L.host v.2)).2 (L.block v.1), M.read (U.graph R fit) v.swap), + localPointers L parent v) := by + refine Prod.ext (Prod.ext rfl ?_) rfl + change (E).counter (printed M L g) (L.host v.2) (L.block v.1) = _ + rw [blk] + exact counter_at M L g v.2 v.1 + +variable (L' : V.Layout R fit' b mx dx) (g' : (Child.Graph mx dx).obj) + +open scoped Classical in +theorem volume_eq (H : b.Ready L g.1) (H' : b.Ready L' g'.1) + (v : U.At R fit) (z : V.At R fit') + (eq : (b.output L g.1 (L.host v.2)).2 (L.block v.1) + = (b.output L' g'.1 (L'.host z.2)).2 (L'.block z.1)) : + (U.graph R fit).tetherLoad v.swap + degree (U.graph R fit).pair v.swap * u = + (V.graph R fit').tetherLoad z.swap + degree (V.graph R fit').pair z.swap * u := by + have he : H.posting.atBlock v.swap = H'.posting.atBlock z.swap + := congrArg (b.scheme mx dx a).decode eq + exact congrArg₂ (·+·) + ((H.posting.exterior_volume v.swap).symm.trans + ((congrArg (fun r => r.volume false) he).trans (H'.posting.exterior_volume z.swap))) + ((H.posting.internal_volume v.swap).symm.trans + ((congrArg (fun r => r.volume true) he).trans (H'.posting.internal_volume z.swap))) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The attachment query issued by a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing Coloring +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w : ℕ} {W c : ℝ} + [NeZero Y] [NeZero w] (T : Attachment A) {U : Setup A.scheme A.scheme.h u a Δ D Y w W} + {R : Rotor F Y w} {fit : U.Fits R c} {e cap t d : ℕ} {b : Book A.scheme u e cap} + (M : Template.Meter) (L : U.Layout R fit b (A.scheme.m + t) d) + (g : (Child.Graph (A.scheme.m + t) d).obj) (old : T.format.obj) + +local notation "Out" => A.resetTarget b M (A.scheme.m + t) d a + +open scoped Classical in +/-- Builds `Attachment.Query T Out (A.scheme.h - a + T.k) 0 where R` with the specified `old`, +`fresh`, `active`. -/ +def query : Attachment.Query T Out (A.scheme.h - a + T.k) 0 where + R := relocation T M L + M := L.move (parent A t) + old := old + fresh := printed M L g + active j _ := decide (j ∈ Set.range L.host) + +open scoped Classical in +theorem query_active (p : (Out).Encodes (printed M L g) (U.graph R fit)) + (hp : p.post.host = L.host) : Attachment.Relocation.WriteActive p (query T M L g old).active + := by + intro i j + change decide (i ∈ Set.range L.host) = true ↔ _ + rw [decide_eq_true_eq] + constructor + · rintro ⟨v, rfl⟩ + let q : (U.graph R fit).diagram.V := ((cellIndex a).symm j, v) + refine ⟨q, ?_⟩ + rw [p.post.vertex_eq, hp, p.block] + change (L.host v, cellIndex a ((cellIndex a).symm j), _) = _ + rw [Equiv.apply_symm_apply] + · rintro ⟨q, hq⟩ + rw [p.post.vertex_eq, hp] at hq + exact ⟨_, congrArg Prod.fst hq⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- +# Relative neighbor addresses of a reset host + +Each occupied column names the adjacent host by a parent hop and +a hardware suffix. Unused columns return to the current host. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Coloring Packing Finset + +variable {F : Type} [Field F] {S : Scheme F} {u h a Δ D Y w : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w W) (R : Rotor F Y w) + (fit : U.Fits R cost) (full : Bool) +local notation "t" => (Child.extra R Δ (h - a)) +local notation "d" => (Child.width D Y full) +local notation "V" => HostNet.V (U.graph R fit) +local notation "col" => (Child.Suffix S.d t d) +local notation "adj" => (U.neighbors R fit full) +local notation "code" => (Child.code R Δ (h - a)) +local notation "split" => (U.parts R fit) +local notation "hop" => (BatchDescent.Trail.hop S.d) +local notation "idx" => (U.index R fit full) + +open scoped Classical in +/-- The indexed operation `((false, false), fun _ => ((false, false), hop none, z))`. -/ +def vacantSuffix (z : B t) : (col).obj := ((false, false), fun _ => ((false, false), hop none, z)) + +open scoped Classical in +/-- The live suffix of type `(col).obj`, constructed using `hj.choose`. -/ +def liveSuffix (v : V) : (col).obj := + ((true, decide ((U.graph R fit).frozen v)), fun j => + if hj : ∃ x ∈ adj v, idx v x = j then + let x := hj.choose + ((true, decide (x ∈ (U.graph R fit).C v)), hop (U.chart.label (split v).1 (split x).1), + code (split x).2) + else ((false, false), hop none, code (split v).2)) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def desc : B (S.m + t) → (col).obj := + Function.extend (U.host R fit) (U.liveSuffix R fit full) + (fun i => vacantSuffix (S := S) (D := D) R full (Match.rowIndex _ _ i).2) + +open scoped Classical in +theorem desc_live (v : V) : U.desc R fit full (U.host R fit v) = U.liveSuffix R fit full v := + (U.host R fit).injective.extend_apply _ _ v + +open scoped Classical in +theorem desc_vacant (i : B (S.m + t)) (hi : i ∉ Set.range (U.host R fit)) : + U.desc R fit full i = vacantSuffix (S := S) (D := D) R full (Match.rowIndex _ _ i).2 := + Function.extend_apply' _ _ _ hi + +open scoped Classical in +theorem suffix_used (P : U.Reading full) (v z : V) (he : z ∈ adj v) : + (U.liveSuffix R fit full v).2 (idx v z) = + ((true, decide (z ∈ (U.graph R fit).C v)), hop (U.chart.label (split v).1 (split z).1), + code (split z).2) := by + have h : ∃ x ∈ adj v, idx v x = idx v z := ⟨z, he, rfl⟩ + have eq : h.choose = z := U.index_inj R fit full P v + (mem_insert_of_mem h.choose_spec.1) (mem_insert_of_mem he) h.choose_spec.2 + simp only [liveSuffix, dite_eq_left h, eq] + +open scoped Classical in +theorem suffix_spare (v : V) (j : B d) (he : ∀ z ∈ adj v, idx v z ≠ j) : + (U.liveSuffix R fit full v).2 j = ((false, false), hop none, code (split v).2) := by + have hn : ¬∃ x ∈ adj v, idx v x = j := by rintro ⟨x, hx, hh⟩; exact he x hx hh + simp only [liveSuffix, dite_eq_right hn] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The emitted child header describes the reset graph exactly -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring Finset + +variable {F : Type} [Field F] {A : Template F} {u a Δ D Y w k : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] (U : Setup A.scheme A.scheme.h u a Δ D Y w W) + (R : Rotor F Y w) (fit : U.Fits R cost) (b : Board A U k) + +local notation "t" => (Child.extra R Δ (A.scheme.h - a)) +local notation "d" => (Child.width D Y A.full) +local notation "host" => (U.host R fit) +local notation "parts" => (U.parts R fit) + +local notation "idx" => (U.index R fit A.full) +local notation "profile" => (U.desc R fit A.full) + +open scoped Classical in +theorem describes : Child.Describes A.full (U.graph R fit) host idx + (Child.build _ _ _ _ (A.nav b.tape.1, profile)) := by + let src : (Child.Input A.scheme.m A.scheme.d t d).obj := (A.nav b.tape.1, profile) + apply Child.describes_of_columns + · intro i + change (profile i).1.1 = true ↔ _ + by_cases hi : i ∈ Set.range host + · obtain ⟨j, rfl⟩ := hi + rw [desc_live] + exact ⟨fun _ => ⟨j, rfl⟩, fun _ => rfl⟩ + · rw [desc_vacant _ _ _ _ _ hi] + exact ⟨fun e => Bool.noConfusion e, fun he => (hi he).elim⟩ + · intro i + change (profile (host i)).1.2 = true ↔ _ + rw [desc_live] + exact decide_eq_true_iff + · intro i hi j + apply Child.build_stay src i j + change ((profile i).2 j).2 = _ + rw [desc_vacant _ _ _ _ _ hi] + rfl + · intro i j he + have hd := U.suffix_used R fit A.full b.read i j he + rw [← desc_live] at hd + refine ⟨?_, congrArg Prod.fst hd⟩ + have hx := Child.build_hop src (host i) (idx i j) _ _ (congrArg Prod.snd hd) + rw [host_parts] at hx + have hn := b.parent_hop _ _ (U.parent_mem R fit A.full he) + refine hx.trans ?_ + change (Match.rowIndex _ t).symm ((U.chart.label (parts i).1 (parts j).1).elim _ (A.nav + b.tape.1 _), _) = _ + rw [hn] + rfl + · intro i j he + have hd := U.suffix_spare R fit A.full i j he + rw [← desc_live] at hd + refine ⟨Child.build_stay src (host i) j ?_, congrArg Prod.fst hd⟩ + rw [host_parts] + exact congrArg Prod.snd hd + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Matching the relative addresses in two reset headers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup.Preview +open Coloring Packing Finset +variable {F : Type} [Field F] {S : Scheme F} {u h a Δ D Y w : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] {U V : Setup S h u a Δ D Y w W} {full : Bool} {n k : ℕ} + {P : U.Reading full} {Q : V.Reading full} {T : Relation U V} + (p : Preview P Q T n) (R : Rotor F Y w) (fu : U.Fits R cost) (fv : V.Fits R cost) + {x x' : (U.graph R fu).V} {y y' : (V.graph R fv).V} (hk : k + 4 ≤ n) + (hr : T k (U.parts R fu x).1 (V.parts R fv y).1) + (he : (U.parts R fu x).2 = (V.parts R fv y).2) + +include p hk hr he +open scoped Classical in +private theorem used_eq (i : B (Child.width D Y full)) + (hx : ∃ v ∈ U.neighbors R fu full x, U.index R fu full x v = i) : + (U.liveSuffix R fu full x).2 i = (V.liveSuffix R fv full y).2 i := by + obtain ⟨v, hv, rfl⟩ := hx + obtain ⟨z, hz, ht, hv'⟩ := p.adjacent R fu fv full id hk hr he hv + have hw := p.widen (by omega : k + 1 ≤ n) ht + have hi := p.idx_match R fu fv hk hr he hw hv' + have hc : v ∈ (U.graph R fu).C x ↔ z ∈ (V.graph R fv).C y := + p.neighbors_iff R fu fv hk hr he hw hv' false (by simp) + rw [U.suffix_used R fu full P x v hv, hi, V.suffix_used R fv full Q y z hz] + simp only [hc, p.labels (by omega : k < n) hr hw, hv'] + +open scoped Classical in +theorem suffix_eq (hf : (U.graph R fu).frozen x ↔ (V.graph R fv).frozen y) : + U.liveSuffix R fu full x = V.liveSuffix R fv full y := by + apply Prod.ext + · simp only [liveSuffix, hf] + funext i + by_cases hx : ∃ v ∈ U.neighbors R fu full x, U.index R fu full x v = i + · exact p.used_eq R fu fv hk hr he i hx + by_cases hy : ∃ v ∈ V.neighbors R fv full y, V.index R fv full y v = i + · exact (p.symm.used_eq R fv fu hk hr he.symm i hy).symm + push Not at hx hy + rw [U.suffix_spare R fu full x i hx, V.suffix_spare R fv full y i hy, he] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup.Preview +end + +/- # Equal samples determine the same local reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +open Coloring Packing +variable {F : Type} [Field F] {A : Template F} {u a Δ D Y w k n : ℕ} {W : ℝ} + {U V : Setup A.scheme A.scheme.h u a Δ D Y w W} + (b : Board A U k) (c : Board A V k) (v : U.G.V) (z : V.G.V) (σ : Cell a) + +open scoped Classical in +/-- Evaluates `∃ p : List (B A.scheme.d), p.length ≤ n ∧ node v p = i ∧ node z p = j` at the +input `n i j`. -/ +def path : U.Relation V := fun n i j => + ∃ p : List (B A.scheme.d), p.length ≤ n ∧ node v p = i ∧ node z p = j + +open scoped Classical in +theorem start : path v z 0 v z := ⟨[], le_rfl, rfl, rfl⟩ + +open scoped Classical in +/-- The data for the sample construction, including `mixer`, `mask`, `rows`. -/ +structure Sample (n : ℕ) : Prop where + mixer : b.tape.2.1 = c.tape.2.1 + mask : Tile.mask A n b.tape.1 (U.post.host v) = Tile.mask A n c.tape.1 (V.post.host z) + rows : (Window.reads n (Tile.packet A a k U.groups b.tape) (U.post.host v)).2 (cellIndex a σ) = + (Window.reads n (Tile.packet A a k V.groups c.tape) (V.post.host z)).2 (cellIndex a σ) + +variable {b c v z σ} + +open scoped Classical in +theorem sample {t : ℕ} (i j : B t) + (he : Tile.look A a k U.groups n t b.tape ((Match.rowIndex _ t).symm (U.post.host v, + i)) (cellIndex a σ) = + Tile.look A a k V.groups n t c.tape ((Match.rowIndex _ t).symm (V.post.host z, + j)) (cellIndex a σ)) : + Sample b c v z σ n := by + simp only [Tile.look, Equiv.apply_symm_apply, Prod.mk.injEq] at he + exact ⟨he.2.1.1, he.2.2.1, he.2.2.2⟩ + +namespace Sample +variable (e : Sample b c v z σ n) {i i' : U.G.V} {j j' : V.G.V} +include e + +open scoped Classical in +theorem mix : U.Z.π = V.Z.π := by rw [b.mix, c.mix, e.mixer] + +open scoped Classical in +theorem same (h : path v z n i j) (h' : path v z n i' j') : i = i' ↔ j = j' := by + obtain ⟨p, hp, rfl, rfl⟩ := h + obtain ⟨q, hq, rfl, rfl⟩ := h' + obtain ⟨r, hr⟩ := Assembly.Child.visit_slot p hp + obtain ⟨s, hs⟩ := Assembly.Child.visit_slot q hq + have eq := congrFun (congrFun e.mask r) s + simp only [Tile.mask, hr, hs, ← b.at_node, ← c.at_node, U.post.host.injective.eq_iff, + V.post.host.injective.eq_iff, decide_eq_decide] at eq + exact eq + +open scoped Classical in +theorem row (h : path v z n i j) : b.localRow i σ = c.localRow j σ := by + obtain ⟨p, hp, rfl, rfl⟩ := h + obtain ⟨r, hr⟩ := Assembly.Child.visit_slot p hp + have eq := congrFun e.rows r + change ((Tile.packet A a k U.groups b.tape) (Neighborhood.walks n (A.nav b.tape.1) _ r)).2 _ = + ((Tile.packet A a k V.groups c.tape) (Neighborhood.walks n (A.nav c.tape.1) _ r)).2 _ at eq + rw [hr, hr, ← b.at_node, ← c.at_node] at eq + exact eq + +open scoped Classical in +theorem record (h : path v z n i j) (x : Cell A.scheme.h) (hx : U.Z.group x = σ) : + U.tag i x = V.tag j x ∧ A.counter b.tape.1 (U.post.host i) (cellIndex _ x) = + A.counter c.tape.1 (V.post.host j) (cellIndex _ x) := by + let r := cellIndex _ (splitCell a U.groups (U.Z.π x)).2 + have hp : Mixing.original A.scheme.h a U.groups b.tape.2.1 (cellIndex a σ) r = x := + hx ▸ b.original x + have hq : Mixing.original A.scheme.h a V.groups c.tape.2.1 (cellIndex a σ) r = x := by + rw [← e.mixer]; exact hp + have he := congrFun (congrArg (fun w => w.2.2) (e.row h)) r + simp only [localRow, Tile.packet, hp, hq, Prod.mk.injEq] at he + rw [b.tag, c.tag] + exact he + +open scoped Classical in +theorem look : Setup.Look b.read c.read σ (path v z) n := by + refine ⟨⟨?_, e.same, ?_, b.margin.trans c.margin.symm, ?_, ?_, ?_⟩, e.mix, ?_, ?_⟩ + · rintro l m i j hm ⟨p, hp, rfl, rfl⟩ + exact ⟨p, hp.trans hm, rfl, rfl⟩ + · rintro l i j ⟨p, hp, rfl, rfl⟩ q + exact ⟨q::p, Nat.succ_le_succ hp, rfl, rfl⟩ + · intro i j h + rw [b.flags, c.flags] + exact congrArg (fun w => w.2.1) (e.row h) + · intro i j h; funext s + rw [b.counts, c.counts] + exact congrArg (fun w => (w.1.2 s).val) (e.row h) + · intro i j h + rw [b.depth, c.depth] + exact congrArg (fun w => w.1.1.val) (e.row h) + · exact fun h x hx => (e.record h x hx).1 + · intro i j h x hx + rw [b.load, c.load, (e.record h x hx).2] + +end Sample +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +end + +/- # Deciding occupancy and the relative address of a child -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +open Packing Coloring Setup +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w k n : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] {U V : Setup A.scheme A.scheme.h u a Δ D Y w W} + {b : Board A U k} {c : Board A V k} + {R : Rotor F Y w} {fit : U.Fits R cost} {fit' : V.Fits R cost} + {e cap t d : ℕ} {B' : Book A.scheme u e cap} + {L : U.Layout R fit B' (A.scheme.m + t) d} {L' : V.Layout R fit' B' (A.scheme.m + t) d} + {locate : Coord R A.scheme.h a Δ ↪ B t} + +open scoped Classical in +theorem matched (hL : Placed A L locate) (hL' : Placed A L' locate) + {v z : B (A.scheme.m + t)} {i j : B a} + (he : Tile.look A a k U.groups n t b.tape v i = Tile.look A a k V.groups n t c.tape z j) : + (v ∉ Set.range L.host ∧ z ∉ Set.range L'.host) ∨ + ∃ σ s q loc, i = cellIndex _ σ ∧ j = cellIndex _ σ ∧ + v = L.host (U.station R fit σ s loc).2 ∧ z = L'.host (V.station R fit' σ q loc).2 ∧ + Sample b c s q σ n := by + obtain ⟨⟨v, r⟩, rfl⟩ := (Match.rowIndex A.scheme.m t).symm.surjective v + obtain ⟨⟨z, r'⟩, rfl⟩ := (Match.rowIndex A.scheme.m t).symm.surjective z + have h := he + simp only [Tile.look, Equiv.apply_symm_apply, Prod.mk.injEq] at h + obtain ⟨⟨live, rfl⟩, ⟨_, rfl⟩, _⟩ := h + have eqv : v ∈ Set.range U.post.host ↔ z ∈ Set.range V.post.host + := by rw [← b.live, ← c.live, live] + by_cases hv : v ∈ Set.range U.post.host ∧ r ∈ Set.range locate + · obtain ⟨q, rfl⟩ := eqv.mp hv.1 + obtain ⟨⟨s, rfl⟩, ⟨loc, rfl⟩⟩ := hv + obtain ⟨σ, rfl⟩ := (cellIndex a).surjective i + exact .inr ⟨σ, s, q, loc, rfl, rfl, (hL.host ..).symm, (hL'.host ..).symm, sample _ _ he⟩ + · left + rw [hL.live, hL'.live, ← eqv] + exact ⟨hv, hv⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +end + +/- # The frozen-seat pointers depend only on the local sample -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Setup Coloring Packing +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w k n : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] {U V : Setup A.scheme A.scheme.h u a Δ D Y w W} + {b : Board A U k} {c : Board A V k} + {R : Rotor F Y w} {fit : U.Fits R cost} {fit' : V.Fits R cost} + {e cap t d : ℕ} {B' : Book A.scheme u e cap} + {L : U.Layout R fit B' (A.scheme.m + t) d} {L' : V.Layout R fit' B' (A.scheme.m + t) d} + {locate : Coord R A.scheme.h a Δ ↪ B t} + +open scoped Classical in +private theorem hosts_at (σ : Cell a) (v : U.G.V) (loc : Coord R A.scheme.h a Δ) + (x : Cell A.scheme.h) (hx : U.Z.group x = σ) : + hosts L (L.host (U.station R fit σ v loc).2) x ↔ + (U.result R fit).owner (v, x) = U.station R fit σ v loc := by + constructor + · rintro ⟨w, hw⟩ + have he := L.host.injective hw + have hv := congrArg (U.result R fit).origin he + rw [(U.result R fit).origin_owner, station_owner] at hv + change w = v at hv + subst w + exact Prod.ext hx he + · exact fun h => ⟨v, congrArg (fun p => L.host p.2) h⟩ + +open scoped Classical in +private theorem no_host {v : B (A.scheme.m + t)} (hv : v ∉ Set.range L.host) (x : Cell A.scheme.h) : + ¬ hosts L v x := fun ⟨_, h⟩ => hv ⟨_, h⟩ + +variable (T : Attachment A) (M : Template.Meter) (hL : Placed A L locate) (hL' : Placed A L' locate) + (hn : A.scheme.h - a + 2 < n) (hD : 0 < D) (delayed : A.full = false → A.scheme.h - a + ≤ 32 * Nat.clog 2 (2 * D)) + {v z : B (A.scheme.m + t)} {i j : B a} + (he : Tile.look A a k U.groups n t b.tape v i = Tile.look A a k V.groups n t c.tape z j) + +include hL hL' hn hD delayed he in +open scoped Classical in +theorem Board.relocate_eq : + (relocation T M L).prev v i = (relocation T M L').prev z j := by + rcases Board.matched hL hL' he with ⟨hv, hz⟩ | ⟨σ, s, q, loc, rfl, rfl, rfl, rfl, e⟩ + · funext k + simp only [relocation, no_host hv, no_host hz, ite_false] + · have ha := (e.look.region hn hD delayed).toSurvey.agree (k := 0) (by omega) (Board.start s q) + have hx (y : B (A.scheme.h - a)) : U.recover (cellIndex a σ) y = V.recover (cellIndex a σ) y + := by + unfold recover + rw [e.mix] + funext k + let y := (Match.rowIndex (A.scheme.h - a) T.k k).1 + let x := U.recover (cellIndex a σ) y + have hu : U.Z.group x = σ := + (cellIndex a).injective ((U.recover_eq (cellIndex a σ) y x).mp rfl).1.symm + have hv : V.Z.group x = σ := (ha.group x).symm.trans hu + have eqn : hosts L (L.host (U.station R fit σ s loc).2) x ↔ + hosts L' (L'.host (V.station R fit' σ q loc).2) x := by + rw [hosts_at _ _ _ _ hu, hosts_at _ _ _ _ hv] + exact ⟨fun h => ha.owner_here h, fun h => ha.symm.owner_here h⟩ + simp only [relocation, ← hx] + exact if_congr eqn rfl rfl + +include hL hL' hn hD delayed he in +open scoped Classical in +theorem Board.query_eq {g g' : (Child.Graph (A.scheme.m + t) d).obj} (old old' : T.format.obj) + (hm : Tile.part A (A.resetTarget B' M _ d a) (emitted M L g (parent A t)) v i = + Tile.part A (A.resetTarget B' M _ d a) (emitted M L' g' (parent A t)) z j) : + ((query T M L g old).ticketAt v i).2 = ((query T M L' g' old').ticketAt z j).2 := by + have hl : v ∈ Set.range L.host ↔ z ∈ Set.range L'.host := by + rcases Board.matched hL hL' he with ⟨hv, hz⟩ | ⟨σ, s, q, loc, _, _, rfl, rfl, _⟩ + · exact iff_of_false hv hz + · exact iff_of_true ⟨_, rfl⟩ ⟨_, rfl⟩ + have hprev := Board.relocate_eq T M hL hL' hn hD delayed he + refine Prod.ext ?_ (Prod.ext ?_ ?_) + · exact decide_eq_decide.mpr hl + · exact congrFun (congrArg Prod.snd hm) 0 + · exact funext fun k => congrArg T.tag (congrFun hprev k) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Local determination of the charge and history carried through a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +open Packing + +variable {F : Type} [Field F] {u a Δ D Y w : ℕ} {W cost : ℝ} [NeZero Y] [NeZero w] + +namespace Setup + +variable {S : Scheme F} {h : ℕ} {U V : Setup S h u a Δ D Y w W} {R : Rotor F Y w} + {fit : U.Fits R cost} {fit' : V.Fits R cost} {v : U.G.V} {z : V.G.V} + {σ : Cell a} {loc : Coord R h a Δ} + +open scoped Classical in +private theorem local_sum (x : U.G.V × Cell h → ℝ) : + push (Prod.swap ∘ (U.result R fit).owner) x (U.station R fit σ v loc).swap = + ∑ j, if (U.result R fit).owner (v, j) = U.station R fit σ v loc then x (v, j) else 0 := by + unfold push + rw [Fintype.sum_prod_type, Fintype.sum_eq_single v] + · simp + · intro t ht + refine Finset.sum_eq_zero fun j _ => ite_eq_right ?_ + intro he + exact ht (owner_here (Prod.swap_injective he)).2 + +open scoped Classical in +private theorem Agree.push_eq (g : Agree U V σ v z) (x : U.G.V × Cell h → ℝ) + (y : V.G.V × Cell h → ℝ) (eq : ∀ j, U.Z.group j = σ → x (v, j) = y (z, j)) : + push (Prod.swap ∘ (U.result R fit).owner) x (U.station R fit σ v loc).swap = + push (Prod.swap ∘ (V.result R fit').owner) y (V.station R fit' σ z loc).swap := by + rw [local_sum, local_sum] + apply Finset.sum_congr rfl + intro j _ + by_cases hj : (U.result R fit).owner (v, j) = U.station R fit σ v loc + · rw [ite_eq_left hj, ite_eq_left (g.owner_here hj)] + exact eq j (Setup.owner_here hj).1 + · exact (ite_eq_right hj).trans (ite_eq_right (fun h => hj (g.symm.owner_here h))).symm + +open scoped Classical in +private theorem after_past : + ((U.graph R fit).past (U.station R fit σ v loc).swap : ℝ) = + push (Prod.swap ∘ (U.result R fit).owner) + (fun x => (U.G.past x + degree U.G.pair x * u : ℕ)) (U.station R fit σ v loc).swap := by + change (U.G.carried _ _ : ℝ) = _ + simp only [HostNet.carried, push, Nat.cast_sum, Nat.cast_ite, Nat.cast_zero] + +open scoped Classical in +private theorem after_park : + push (U.graph R fit).park U.L.charge (U.station R fit σ v loc).swap = + push (Prod.swap ∘ (U.result R fit).owner) (push U.G.park U.L.charge) (U.station R fit σ v + loc).swap := + (push_comp U.G.park (Prod.swap ∘ (U.result R fit).owner) U.L.charge _).symm + +end Setup + +namespace Board + +variable {A : Template F} {U V : Setup A.scheme A.scheme.h u a Δ D Y w W} + {k n : ℕ} {b : Board A U k} {c : Board A V k} {v : U.G.V} {z : V.G.V} {σ : Cell a} + +open scoped Classical in +/-- Equal records give the same past, parked charge and internal volume. +Once the new arities match, all three arguments of the meter agree. -/ +theorem Sample.meter (e : Sample b c v z σ n) (hn : A.scheme.h - a + 8 ≤ n) + (hD : 0 < D) (delayed : A.full = false → A.scheme.h - a ≤ 32 * Nat.clog 2 (2 * D)) + (M : Template.Meter) (R : Rotor F Y w) (fit : U.Fits R cost) (fit' : V.Fits R cost) + (loc : Setup.Coord R A.scheme.h a Δ) + (har : let p := (U.station R fit σ v loc).swap + let q := (V.station R fit' σ z loc).swap + (U.graph R fit).tetherLoad p + degree (U.graph R fit).pair p * u = + (V.graph R fit').tetherLoad q + degree (V.graph R fit').pair q * u) : + M.read (U.graph R fit) (U.station R fit σ v loc).swap = + M.read (V.graph R fit') (V.station R fit' σ z loc).swap := by + have region := e.look.region (show A.scheme.h - a + 2 < n by omega) hD delayed + have g := region.toSurvey.agree (by omega) (start v z) + have records := e.record (e.look.widen (Nat.zero_le n) (start v z)) + unfold Template.Meter.read + dsimp only at har + rw [har] + refine congrArg₂ (M.encode _) ?_ ?_ + · rw [Setup.after_park, Setup.after_park] + apply g.push_eq + intro j hj + rw [b.park, c.park, (records j hj).2] + · apply Nat.cast_injective (R := ℝ) + rw [Setup.after_past, Setup.after_past] + apply g.push_eq + intro j hj + have hc := records j hj + have htag : U.post.atBlock (v, j) = V.post.atBlock (z, j) := congrArg A.scheme.decode hc.1 + simp only [← U.post.internal_volume, ← V.post.internal_volume, htag, b.past, c.past, hc.2] + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # The full record at an occupied child is locally determined -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +open Packing Coloring Setup +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w k n : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] {U V : Setup A.scheme A.scheme.h u a Δ D Y w W} + {b : Board A U k} {c : Board A V k} {v : U.G.V} {z : V.G.V} {σ : Cell a} + (p : Sample b c v z σ n) (hn : A.scheme.h - a + 8 ≤ n) + (hD : 0 < D) (delayed : A.full = false → A.scheme.h - a ≤ 32 * Nat.clog 2 (2 * D)) + {R : Rotor F Y w} {fit : U.Fits R cost} {fit' : V.Fits R cost} + {e cap m d : ℕ} {B' : Book A.scheme u e cap} + {L : U.Layout R fit B' m d} {L' : V.Layout R fit' B' m d} + (ha : Ranked L) (hb : Ranked L') (hi : IndexAgrees L L' (path v z) σ v z) +include p hn hD delayed ha hb hi + +open scoped Classical in +theorem Sample.corresponds : Corresponds L L' (path v z) σ v z (n - 1) := by + refine ⟨p.look.region (by omega) hD delayed, by omega, start _ _, ?_, ?_, ha, hb, hi⟩ + · exact fun _ _ hr => p.look.tag (p.look.widen (by omega) hr) + · ext x + rw [b.block, c.block] + +variable (hu : ∀ t, U.G.diagram.arity t = 0 → ∀ x, Transcript.sample (U.G.diagram.table t) x = 1) + (hv : ∀ t, V.G.diagram.arity t = 0 → ∀ x, Transcript.sample (V.G.diagram.table t) x = 1) + (loc : Coord R A.scheme.h a Δ) +local notation "x" => U.station R fit σ v loc +local notation "y" => V.station R fit' σ z loc +include hu hv + +open scoped Classical in +theorem Sample.payload : B'.data L x = B'.data L' y := by + have h := p.corresponds hn hD delayed ha hb hi + apply congrArg (canonical B'.ord u cap) + funext w + exact h.region.eval (k := 0) (by omega) h.root h.at_root hu hv (L.seat x) (L'.seat y) w w + (fun i j he t => congrArg (fun s => w s t) (h.seat he)) + +variable (M : Template.Meter) {g g' : (Child.Graph m d).obj} + (hs : B'.Ready L g.1) (ht : B'.Ready L' g'.1) + (blk : L.block = (cellIndex a).toEmbedding) (blk' : L'.block = (cellIndex a).toEmbedding) + (parent : B m → B A.scheme.m) +local notation "E" => A.resetTarget B' M m d a +include hs ht blk blk' + +open scoped Classical in +theorem Sample.cell : + Tile.part A E (emitted M L g parent) (L.host (x).2) (cellIndex a σ) = + Tile.part A E (emitted M L' g' parent) (L'.host (y).2) (cellIndex a σ) := by + have h := p.corresponds hn hD delayed ha hb hi + have payload := p.payload hn hD delayed ha hb hi hu hv loc + have tag := h.tag loc g.1 g'.1 payload + have arity := volume_eq L g L' g' hs ht x y tag + have meter := p.meter hn hD delayed M R fit fit' loc arity + have left := emitted_at M L g parent blk x + have right := emitted_at M L' g' parent blk' y + have he := left.trans ((Prod.ext (Prod.ext tag meter) (h.pointers parent loc)).trans right.symm) + rw [blk, blk'] at he + exact he + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Board +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Follow.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Follow.lean new file mode 100644 index 0000000000..c5c037db88 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Follow.lean @@ -0,0 +1,984 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Width +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Routes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Mixer.Choice +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Mixer.Apply +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Reads +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Hop +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.ChildPaths + +/-! # Addressing the hardware attached to each parent host -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +open Coloring Packing + +/-- The quantity computed by `Format.pair (.pair .bit .bit) (.vec l (.pair (.pair .bit .bit) +(.pair (.addr (d + 1)) (.addr k))))`. -/ +abbrev Suffix (d k l : ℕ) := + Format.pair (.pair .bit .bit) (.vec l (.pair (.pair .bit .bit) (.pair (.addr (d + 1)) (.addr k)))) + +/-- The quantity computed by `Format.pair (Neighborhood.Rows m d) (.vec (m + k) (Suffix d k +l))`. -/ +abbrev Input (m d k l : ℕ) := Format.pair (Neighborhood.Rows m d) (.vec (m + k) (Suffix d k l)) +/-- Computes the graph by the application `Format.pair (Neighborhood.Rows m l) (.vec m (.pair +(.pair .bit .bit) (Group.Flags l)))`. -/ +abbrev Graph (m l : ℕ) := + Format.pair (Neighborhood.Rows m l) (.vec m (.pair (.pair .bit .bit) (Group.Flags l))) + +/-- Returns `nav parent ⟨hop.val, h⟩` when `h : hop.val < 2 ^ d` holds, and `parent` otherwise. -/ +def follow {m d : ℕ} (nav : (Neighborhood.Rows m d).obj) (parent : B m) (hop : B (d + 1)) := + if h : hop.val < 2 ^ d then nav parent ⟨hop.val, h⟩ else parent + +/-- The build of type `(Graph (m + k) l).obj`, constructed using `(Match.rowIndex m k i).1`. -/ +def build (m d k l : ℕ) (r : (Input m d k l).obj) : (Graph (m + k) l).obj := + (fun i j => + let parent := (Match.rowIndex m k i).1 + let q := ((r.2 i).2 j).2 + (Match.rowIndex m k).symm (follow r.1 parent q.1, q.2), + fun i => ((r.2 i).1, fun j => ((r.2 i).2 j).1)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +end + +section +/- # Information represented by the graph header after a reset -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +open Packing Coloring + +variable {F T : Type} {x y : Wire} {L : Fringe x y T} {a u m d : ℕ} + +/-- The data for the describes construction, including `live`, `frozen`, `closed`, `reciprocal`, +`edge`. -/ +structure Describes (full : Bool) (G : HostNet F L a u) (host : G.V ↪ B m) + (index : G.V → G.V → B d) (g : (Graph m d).obj) : Prop where + live : ∀ i, (g.2 i).1.1 = true ↔ i ∈ Set.range host + frozen : ∀ v, (g.2 (host v)).1.2 = true ↔ G.frozen v + closed : ∀ v j, g.1 (host v) j ∈ Set.range host + reciprocal : ∀ i j, g.1 i j ≠ i → ∃! l, g.1 (g.1 i j) l = i + edge : ∀ v z, z ∈ (if full then G.N else G.C) v ↔ + ∃ j, g.1 (host v) j = host z ∧ ((g.2 (host v)).2 j).1 = true + core : ∀ v z, z ∈ G.C v ↔ ∃ j, g.1 (host v) j = host z ∧ ((g.2 (host v)).2 j).2 = true + hop : ∀ v z, z ∈ G.C v → g.1 (host v) (index v z) = host z + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +end + +/- # Certifying the graph header from the active and vacant columns -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +open Packing Coloring + +variable {F T : Type} {x y : Wire} {L : Fringe x y T} {a u m d : ℕ} + (full : Bool) (G : HostNet F L a u) (host : G.V ↪ B m) + (index : G.V → G.V → B d) (g : (Graph m d).obj) +local notation "adj" => (ite (full = true) G.N G.C) + +open scoped Classical in +theorem describes_of_columns + (live : ∀ i, (g.2 i).1.1 = true ↔ i ∈ Set.range host) + (frozen : ∀ v, (g.2 (host v)).1.2 = true ↔ G.frozen v) + (idle : ∀ i ∉ Set.range host, ∀ j, g.1 i j = i) + (used : ∀ v w, w ∈ adj v → g.1 (host v) (index v w) = host w ∧ + (g.2 (host v)).2 (index v w) = (true, decide (w ∈ G.C v))) + (spare : ∀ v j, (∀ w ∈ adj v, index v w ≠ j) → + g.1 (host v) j = host v ∧ (g.2 (host v)).2 j = (false, false)) : + Describes full G host index g := by + have sym : ∀ v w, w ∈ adj v → v ∈ adj w := by + cases full + · exact G.cs + · exact G.ns + have sub : ∀ v, G.C v ⊆ adj v := by + cases full + · exact fun _ _ h => h + · exact G.sub + have split (v j) : + (∃ w ∈ adj v, index v w = j) ∨ (g.1 (host v) j = host v ∧ (g.2 (host v)).2 j = (false, + false)) := by + by_cases h : ∃ w ∈ adj v, index v w = j + · exact .inl h + exact .inr (spare v j (fun w hw he => h ⟨w, hw, he⟩)) + refine ⟨live, frozen, ?_, ?_, ?_, ?_, fun v w hw => (used v w (sub v hw)).1⟩ + · intro v j + rcases split v j with ⟨w, hw, rfl⟩|⟨he, _⟩ + · exact ⟨w, (used _ _ hw).1.symm⟩ + · exact ⟨v, he.symm⟩ + · intro i j hn + by_cases hi : i ∈ Set.range host + swap + · exact (hn (idle i hi j)).elim + obtain ⟨v, rfl⟩ := hi + rcases split v j with ⟨w, hw, rfl⟩|⟨he, _⟩ + swap + · exact (hn he).elim + rw [(used v w hw).1] at hn ⊢ + refine ⟨index w v, (used _ _ (sym _ _ hw)).1, fun l hl => ?_⟩ + rcases split w l with ⟨z, hz, rfl⟩|⟨he, _⟩ + · exact congrArg (index w) (host.injective ((used w z hz).1.symm.trans hl)) + · exact (hn (he.symm.trans hl)).elim + · intro v w + constructor + · intro h + exact ⟨index v w, (used v w h).1, congrArg Prod.fst (used v w h).2⟩ + rintro ⟨j, hj, h⟩ + rcases split v j with ⟨z, hz, rfl⟩|⟨_, he⟩ + · exact host.injective ((used v z hz).1.symm.trans hj) ▸ hz + · rw [he] at h; cases h + · intro v w + constructor + · intro h + obtain ⟨he, hf⟩ := used v w (sub v h) + exact ⟨index v w, he, by simp [hf, h]⟩ + rintro ⟨j, hj, h⟩ + rcases split v j with ⟨z, hz, rfl⟩|⟨_, he⟩ + · have : z = w := host.injective ((used v z hz).1.symm.trans hj) + subst z + simpa only [(used _ _ hz).2, decide_eq_true_eq] using h + · rw [he] at h; cases h + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +end + +/- # Encoding the hardware at each reset host by a common suffix -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +open Coloring Packing + +variable {F : Type} [Field F] {Y w : ℕ} + +namespace Child + +open scoped Classical in +/-- The value specified by `R.Host (Schedule.Address n) (terminalWidth Δ Y)`. -/ +abbrev Part (R : Rotor F Y w) (Δ n : ℕ) := R.Host (Schedule.Address n) (terminalWidth Δ Y) + +open scoped Classical in +/-- Embeds `Part R Δ n` into `B (extra R Δ n)`. -/ +def code (R : Rotor F Y w) (Δ n : ℕ) : Part R Δ n ↪ B (extra R Δ n) := by + apply Classical.choice + apply Function.Embedding.nonempty_of_card_le + have h := Fintype.card_le_of_embedding (intervalCode n) + rw [Fintype.card_fin, pow_succ] at h + have ht := Nat.le_pow_clog (by decide : 1 < 2) (resetPositions R Δ) + rw [Fintype.card_fin, extra, pow_add 2 n] + refine le_trans ?_ (Nat.mul_le_mul_left _ ht) + unfold Part Rotor.Host resetPositions + rw [Fintype.card_sum, Fintype.card_prod, Fintype.card_prod, Fintype.card_prod, Fintype.card_fin] + rw [mul_assoc, ← mul_add, ← mul_assoc] + exact Nat.mul_le_mul_right _ h + +end Child +namespace Setup + +variable {S : Scheme F} {h u a Δ D : ℕ} {B' c : ℝ} [NeZero Y] [NeZero w] + (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) (fits : U.Fits R c) + +open scoped Classical in +/-- Reindexes `(U.graph R fits).V` and `U.G.V × Child.Part R Δ (h - a)` by an equivalence. -/ +abbrev parts : (U.graph R fits).V ≃ U.G.V × Child.Part R Δ (h - a) := + Schedule.splitHost R a h (terminalWidth Δ Y) + +open scoped Classical in +/-- Returns `(U.graph R fits).N` when `full` holds, and `(U.graph R fits).C` otherwise. -/ +abbrev neighbors (full : Bool) := if full then (U.graph R fits).N else (U.graph R fits).C + +open scoped Classical in +/-- Embeds `(U.graph R fits).V` into `B (S.m + Child.extra R Δ (h - a))`. -/ +def host : (U.graph R fits).V ↪ B (S.m + Child.extra R Δ (h - a)) := + (U.parts R fits).toEmbedding.trans ((U.post.host.prodMap (Child.code R Δ (h - a))).trans + (Match.rowIndex S.m (Child.extra R Δ (h - a))).symm.toEmbedding) + +open scoped Classical in +@[simp] theorem host_parts (i : (U.graph R fits).V) : + Match.rowIndex S.m (Child.extra R Δ (h - a)) (U.host R fits i) = + (U.post.host (U.parts R fits i).1, Child.code R Δ (h - a) (U.parts R fits i).2) := + (Match.rowIndex _ _).apply_symm_apply _ + +open scoped Classical in +theorem frozen_parts (i : (U.graph R fits).V) : + (U.graph R fits).frozen i = U.G.frozen (U.parts R fits i).1 := by + rcases i with a|b <;> rfl + +end Setup +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Numbering reset neighbors from the previous header -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +open Packing Coloring Finset + +variable {V W : Type} {C : V → Finset V} {d : ℕ} + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun i => nav v i = w`. -/ +def hops (nav : V → B d → V) (v w : V) : Finset (B d) := + univ.filter fun i => nav v i = w + +open scoped Classical in +/-- Selects the appropriate branch of `if v = w then none else if h : (hops nav v w).Nonempty +then some h.choose else none`. -/ +def label (nav : V → B d → V) (v w : V) : Option (B d) := + if v = w then none else if h : (hops nav v w).Nonempty then some h.choose else none + +open scoped Classical in +theorem label_spec (nav : V → B d → V) {v w : V} (h : w = v ∨ ∃ i, nav v i = w) : + (label nav v w).elim v (nav v) = w := by + unfold label + by_cases he : v = w + · simp [he] + obtain ⟨i, hi⟩ := h.resolve_left (Ne.symm he) + have hh : (hops nav v w).Nonempty := ⟨i, mem_filter.mpr ⟨mem_univ _, hi⟩⟩ + rw [ite_eq_right he, dite_eq_left hh] + exact (mem_filter.mp hh.choose_spec).2 + +open scoped Classical in +theorem label_eq {nav : V → B d → V} {nav' : W → B d → W} {v t : V} {w z : W} + (he : v = t ↔ w = z) (ht : ∀ j, nav v j = t ↔ nav' w j = z) : + label nav v t = label nav' w z := by + have hh : hops nav v t = hops nav' w z := by ext i; simp [hops, ht] + simp only [label, he, hh] + +open scoped Classical in +/-- Builds `Chart C d where label` with the specified `label`, `self`, `inj`. -/ +def chart (nav : V → B d → V) (ok : ∀ v w, w ∈ C v → ∃ i, nav v i = w) : Chart C d where + label := label nav + self v := by simp [label] + inj v i hi j hj he := by + have decode (i : V) (h : i ∈ insert v (C v)) : (label nav v i).elim v (nav v) = i := + label_spec nav ((mem_insert.mp h).imp_right (ok v i)) + rw [← decode i hi, he, decode j hj] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +open Packing Coloring + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} + {D : Template F} {G : HostNet F L D.scheme.h u} {r : D.format.obj} (p : D.Encodes r G) + +open scoped Classical in +theorem host_nav (v : G.V) (j : B D.scheme.d) : + p.post.host (p.post.nav v j) = D.nav r (p.post.host v) j := by + have hh : ∃ w, p.post.host w = (r.1 (p.post.host v)).1 j := p.closed v j + rw [Scheme.Posting.nav, dite_eq_left hh] + exact hh.choose_spec + +open scoped Classical in +/-- The reset chart of type `History.Reset.Chart G.C D.scheme.d` for the given inputs. -/ +def resetChart : History.Reset.Chart G.C D.scheme.d := + History.Reset.chart p.post.nav fun v w he => by + obtain ⟨i, hi, _⟩ := (p.core v w).mp he + exact ⟨i, p.post.host.injective ((p.host_nav v i).trans hi)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +end + +/- +# Summing over repeated neighbor columns + +All padding columns have zero demand. Their presence makes a sum +over the whole neighbor fiber independent of which column was chosen +for an unused contact. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +open Packing Coloring History.Reset Finset + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} + {D : Template F} {G : HostNet F L D.scheme.h u} {r : D.format.obj} (p : D.Encodes r G) + (hu : 0 < u) (c : CoreContact G.C) + +open scoped Classical in +/-- Computes the columns by the application `hops p.post.nav c.val.1 c.val.2`. -/ +abbrev columns := hops p.post.nav c.val.1 c.val.2 + +open scoped Classical in +theorem contact_mem : p.contactCol c ∈ p.columns c := by + exact mem_filter.mpr ⟨mem_univ _, p.post.host.injective ((p.host_nav _ _).trans (p.nav_contact + c))⟩ + +include hu in +open scoped Classical in +private theorem no_units (j : B D.scheme.d) (hj : j ∈ p.columns c) (hn : j ≠ p.contactCol c) + (b : Cell D.scheme.h) : p.usedCol c.val.1 b j = ∅ := by + apply p.unused hu + rintro ⟨c', he⟩ + obtain ⟨hv, hj'⟩ := Prod.mk.inj he + have hs : c'.val.1 = c.val.1 := p.post.host.injective hv + have ht : p.post.nav c'.val.1 (p.contactCol c') = c'.val.2 := (mem_filter.mp (p.contact_mem c')).2 + rw [hs, hj'] at ht + have eq : c' = c := Subtype.ext (Prod.ext hs (ht.symm.trans (mem_filter.mp hj).2)) + exact hn (hj'.symm.trans (congrArg p.contactCol eq)) + +include hu in +open scoped Classical in +theorem column_load (b : Cell D.scheme.h) (w : ℝ) : + (coreDemands G.ix G.edge).amounts w c b = + (∑ j ∈ p.columns c, (p.usedCol c.val.1 b j).card : ℕ) * w := by + rw [p.contact_load hu, sum_eq_single_of_mem _ (p.contact_mem c)] + exact fun j hj hn => by rw [p.no_units hu c j hj hn, card_empty] + +include hu in +open scoped Classical in +theorem column_total (w : ℝ) : + (∑ b, (coreDemands G.ix G.edge).amounts w c b) = + (∑ j ∈ p.columns c, (D.unitCount r (p.post.host c.val.1) j).val : ℕ) * w := by + rw [p.amount_total hu, sum_eq_single_of_mem _ (p.contact_mem c)] + intro j hj hn + simp only [p.unit_count, p.no_units hu c j hj hn, card_empty, sum_const_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +end + +/- # Recovering both stubs of a unit from a local posting -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + (U V : Setup S h u a Δ D Y w B') + +open scoped Classical in +/-- The value specified by `(U.r (U.post.host v)).2 (U.post.block x)`. -/ +abbrev tag (v : U.G.V) (x : Cell h) := (U.r (U.post.host v)).2 (U.post.block x) +open scoped Classical in +/-- Computes the pat by the application `S.decode (U.tag v x)`. -/ +abbrev pat (v : U.G.V) (x : Cell h) := S.decode (U.tag v x) + +open scoped Classical in +theorem stub_link (i : U.G.E) (t : Bool) : + let v := Scheme.side U.G i t + let q := Scheme.side U.G i (!t) + (U.pat v (U.G.ix i)).peer 0 (U.post.stub i t) = some (U.post.index v q, 0, U.post.stub i (!t)) + := + U.post.link i t + +open scoped Classical in +theorem endpoint (v : U.G.V) (x : Cell h) (t : Bool) (i : B S.e) + (hp : 0 < (U.pat v x).width 0 i) (hd : (U.pat v x).direction 0 i = t) + (he : ((U.pat v x).peer 0 i).isSome) : + ∃ f, Scheme.side U.G f t = v ∧ U.G.ix f = x ∧ U.post.stub f t = i := by + let p := U.post + let z : S.Span := ((p.host v, p.block x, 0), i) + have used : (S.peer U.r z).isSome := by + simpa [Scheme.peer, Scheme.pattern, z, p, pat, tag] using he + obtain ⟨q, hq⟩ := p.toSeating.ends.surjective ⟨z, ⟨0, hp⟩⟩ + have hit := congrArg Sigma.fst hq + have key (i' : U.G.E) (b : Bool) (j : Fin u) + (hs : (p.toSeating.ends (Scheme.endBit U.G i' b j)).1 = z) : + ∃ f, Scheme.side U.G f t = v ∧ U.G.ix f = x ∧ U.post.stub f t = i := by + have hspan := (p.ordered i' b j).1.symm.trans hs + have hb : b = t := (p.dir i' b).symm.trans ((congrArg (S.direction U.r) hspan).trans hd) + subst b + obtain ⟨ha, hi⟩ := Prod.mk.inj hspan + exact ⟨i', p.host.injective (Prod.mk.inj ha).1, + p.block.injective (Prod.mk.inj (Prod.mk.inj ha).2).1, hi⟩ + change (p.toSeating.ends q).1 = z at hit + rcases q with (i|e)|(i|e) + · rw [← hit, p.input] at used + cases used + · obtain ⟨⟨f, j⟩, rfl⟩ := U.G.units.bits.symm.surjective e + exact key f false j hit + · rw [← hit, p.output] at used + cases used + · obtain ⟨⟨f, j⟩, rfl⟩ := U.G.units.bits.symm.surjective e + exact key f true j hit + +open scoped Classical in +theorem stub_nav (e : U.G.E) (t : Bool) : + let x := Scheme.side U.G e t + let y := Scheme.side U.G e (!t) + U.post.nav x (U.post.index x y) = y := by + cases t + · exact U.post.nav_target U.hu e + · exact U.post.return_nav U.hu e + +open scoped Classical in +theorem transfer {e : U.G.E} {t : Bool} {v : U.G.V} {z : V.G.V} + (hv : Scheme.side U.G e t = v) (ht : U.tag v (U.G.ix e) = V.tag z (U.G.ix e)) : + ∃ f : V.G.E, Scheme.side V.G f t = z ∧ U.G.ix e = V.G.ix f ∧ + (∀ b, U.post.stub e b = V.post.stub f b) ∧ + U.post.index v (Scheme.side U.G e (!t)) = V.post.index z (Scheme.side V.G f (!t)) := by + subst v + let i := U.post.stub e t + let x := U.G.ix e + let v := Scheme.side U.G e t + have pat : U.pat v x = V.pat z x := congrArg S.decode ht + have eq := U.stub_link e t + change (U.pat v x).peer 0 i = some _ at eq + obtain ⟨f, hf, hx, hi⟩ := V.endpoint z x t i + (by rw [← pat]; exact U.hu.trans_eq (U.post.length e t).symm) + (by rw [← pat]; exact U.post.dir e t) + (by rw [← pat, eq]; rfl) + have other := V.stub_link f t + dsimp only at other + rw [hf, hx, hi, ← pat, eq, Option.some.injEq] at other + refine ⟨f, hf, hx.symm, ?_, (Prod.mk.inj other).1⟩ + intro b + by_cases hb : b = t + · rw [hb]; exact hi.symm + have : b = !t := by cases b <;> cases t <;> first | rfl | contradiction + rw [this] + exact (Prod.mk.inj (Prod.mk.inj other).2).2 + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- +# Common information read from a template header + +A graph with very large full degree can omit its noncore edges +when they cannot affect a split at the present height. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring Finset + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + (U V : Setup S h u a Δ D Y w B') (full : Bool) + +open scoped Classical in +/-- Returns `U.G.N` when `full` holds, and `U.G.C` otherwise. -/ +abbrev adj := if full then U.G.N else U.G.C + +open scoped Classical in +/-- The data for the reading construction, including `flags`, `counts`, `chart`, `links`, +`core`. -/ +structure Reading where + /-- The `Reading` component of type `U.G.V → (Group.Flags S.d).obj`. -/ + flags : U.G.V → (Group.Flags S.d).obj + /-- The `Reading` component of type `U.G.V → B S.d → ℕ`. -/ + counts : U.G.V → B S.d → ℕ + chart : U.chart.label = label U.post.nav + links : ∀ v z, z ∈ U.adj full v ↔ ∃ j, U.post.nav v j = z ∧ (flags v j).1 = true + core : ∀ v z, z ∈ U.G.C v ↔ ∃ j, U.post.nav v j = z ∧ (flags v j).2 = true + weight : ∀ (c : CoreContact U.G.C) x, + U.amount c x = (∑ j ∈ hops U.post.nav c.val.1 c.val.2, + ((U.pat c.val.1 x).uses j).card : ℕ) * ((u : ℝ) / B') + total : ∀ c : CoreContact U.G.C, + (∑ x, U.amount c x) = (∑ j ∈ hops U.post.nav c.val.1 c.val.2, + counts c.val.1 j : ℕ) * ((u : ℝ) / B') + +open scoped Classical in +/-- Builds `U.Reading T.full where flags v` with the specified `flags`, `counts`, `chart`, +`links`. -/ +def reading {T : Template F} (U : Setup T.scheme T.scheme.h u a Δ D Y w B') + (b : (Format.vec T.scheme.m T.header).obj) (p : T.Encodes (U.r, b) U.G) + (he : p.post = U.post) (hc : U.chart = p.resetChart) : U.Reading T.full where + flags v := T.flags (U.r, b) (U.post.host v) + counts v j := (T.unitCount (U.r, b) (U.post.host v) j).val + chart := by rw [hc, ← he]; rfl + links v z := by + change z ∈ T.adj U.G v ↔ _ + rw [p.edge, ← he] + apply exists_congr + intro j + rw [← p.host_nav, p.post.host.injective.eq_iff] + core v z := by + rw [p.core, ← he] + apply exists_congr + intro j + rw [← p.host_nav, p.post.host.injective.eq_iff] + weight c x := by + simp only [pat, tag, ← he, p.block] + exact p.column_load U.hu c x _ + total c := by + rw [← he] + exact p.column_total U.hu c _ + +section + +variable {U V full} (P : U.Reading full) (Q : V.Reading full) + (R : Relation U V) (n : ℕ) + +open scoped Classical in +/-- Agreements on the reset graph, counts and contact depths. -/ +structure Preview : Prop where + widen : ∀ {k j v z}, k ≤ j → R k v z → R j v z + same : ∀ {v z v' z'}, R n v z → R n v' z' → (v = v' ↔ z = z') + next : ∀ {k v z}, R k v z → ∀ j, R (k + 1) (U.post.nav v j) (V.post.nav z j) + margin : U.g = V.g + flags : ∀ {v z}, R n v z → P.flags v = Q.flags z + counts : ∀ {v z}, R n v z → P.counts v = Q.counts z + base : ∀ {v z}, R n v z → U.Z.base v = V.Z.base z + +variable {P Q R n} + +namespace Preview + +variable (p : Preview P Q R n) {v v' : U.G.V} {z z' : V.G.V} {k : ℕ} +include p + +open scoped Classical in +theorem symm : Preview Q P (flip R) n := + ⟨fun h r => p.widen h r, fun r s => (p.same r s).symm, fun r j => p.next r j, + p.margin.symm, fun r => (p.flags r).symm, fun r => (p.counts r).symm, fun r => (p.base r).symm⟩ + +section +variable (hk : k < n) (hr : R k v z) (ht : R n v' z') +include hk hr ht + +open scoped Classical in +theorem reach (j : B S.d) : U.post.nav v j = v' ↔ V.post.nav z j = z' := + p.same (p.widen hk (p.next hr j)) ht + +open scoped Classical in +theorem labels : U.chart.label v v' = V.chart.label z z' := by + rw [P.chart, Q.chart] + exact label_eq (p.same (p.widen hk.le hr) ht) (p.reach hk hr ht) + +open scoped Classical in +theorem columns : hops U.post.nav v v' = hops V.post.nav z z' := by + ext j + simp only [hops, mem_filter, mem_univ, true_and, p.reach hk hr ht] + +open scoped Classical in +theorem links : v' ∈ U.adj full v ↔ z' ∈ V.adj full z := by + simp only [P.links, Q.links, p.reach hk hr ht, p.flags (p.widen hk.le hr)] + +open scoped Classical in +theorem core : v' ∈ U.G.C v ↔ z' ∈ V.G.C z := by + simp only [P.core, Q.core, p.reach hk hr ht, p.flags (p.widen hk.le hr)] + +end + +open scoped Classical in +theorem capacity {c : CoreContact U.G.C} {c' : CoreContact V.G.C} + (hk : k < n) (hr : R k c.val.1 c'.val.1) (ht : R k c.val.2 c'.val.2) : + U.Z.capacity c = V.Z.capacity c' := by + have ha := p.widen hk.le hr + have hb := p.widen hk.le ht + have hc : (∑ j, U.amount c j) = (∑ j, V.amount c' j) := by + rw [P.total, Q.total, p.columns hk hr hb, p.counts ha] + have hd : contactDepth U.Z.base unitEnds c = contactDepth V.Z.base unitEnds c' := + congrArg₂ max (p.base ha) (p.base hb) + change (∑ j, U.amount c j) / 2 ^ (contactDepth U.Z.base unitEnds c) + 1 / U.g = + (∑ j, V.amount c' j) / 2 ^ (contactDepth V.Z.base unitEnds c') + 1 / V.g + rw [hc, hd, p.margin] + +end Preview + +end + +variable {U V full} (P : U.Reading full) (Q : V.Reading full) + (σ : Cell a) (R : Relation U V) (n : ℕ) + +open scoped Classical in +/-- The reset graph agreements together with the chosen blocks and their records. -/ +structure Look : Prop extends preview : Preview P Q R n where + mix : U.Z.π = V.Z.π + tag : ∀ {v z}, R n v z → ∀ j, U.Z.group j = σ → U.tag v j = V.tag z j + load : ∀ {v z}, R n v z → ∀ j, U.Z.group j = σ → U.G.load v j = V.G.load z j + +namespace Look +variable {P Q σ R n} (p : Look P Q σ R n) +include p + +open scoped Classical in +theorem group (x : Cell h) : U.Z.group x = V.Z.group x := by unfold Schedule.group; rw [p.mix] + +open scoped Classical in +theorem symm : Look Q P σ (flip R) n := + ⟨p.preview.symm, p.mix.symm, fun r x h => (p.tag r x ((p.group x).trans h)).symm, + fun r x h => (p.load r x ((p.group x).trans h)).symm⟩ + +end Look +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # From matching records to a matching reset region -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup.Look +open Packing Coloring Finset + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w k n : ℕ} {B' : ℝ} + {U V : Setup S h u a Δ D Y w B'} {full : Bool} {P : U.Reading full} {Q : V.Reading full} + {σ : Cell a} {R : Relation U V} (p : Look P Q σ R n) + {v v' : U.G.V} {z z' : V.G.V} {c : CoreContact U.G.C} {c' : CoreContact V.G.C} + +include p in +open scoped Classical in +theorem amounts (hk : k < n) (hr : R k c.val.1 c'.val.1) (ht : R k c.val.2 c'.val.2) : + U.Z.capacity c = V.Z.capacity c' ∧ ∀ j, U.Z.group j = σ → U.amount c j = V.amount c' j := by + have ha := p.widen hk.le hr + have hb := p.widen hk.le ht + have hs := p.preview.columns hk hr hb + refine ⟨p.preview.capacity hk hr ht, ?_⟩ + intro j hj + rw [P.weight, Q.weight, hs] + simp only [pat, p.tag ha j hj] + +include p in +open scoped Classical in +theorem siblings (hk : k + 1 < n) (hr : R k v z) : Siblings U V σ R k v z := by + intro c t he + have hm : unitEnds c (!t) ∈ U.G.C v := he ▸ Chart.partner_mem U.G.cs c t + obtain ⟨j, hj, _⟩ := (P.core _ _).mp hm + let w := V.post.nav z j + have ht : R (k + 1) (unitEnds c (!t)) w := hj ▸ p.next hr j + have hm' := (p.preview.core (by omega) hr (p.widen hk.le ht)).mp hm + have hl := p.preview.labels (by omega) hr (p.widen hk.le ht) + have hv : R (k + 1) (unitEnds c t) z := he.symm ▸ p.widen (by omega) hr + cases t + · let c' : CoreContact V.G.C := ⟨(z, w), hm'⟩ + exact ⟨c', rfl, ht, hl, p.amounts (c' := c') hk hv ht⟩ + · let c' : CoreContact V.G.C := ⟨(w, z), V.G.cs _ _ hm'⟩ + exact ⟨c', rfl, ht, hl, p.amounts (c' := c') hk ht hv⟩ + +include p in +open scoped Classical in +theorem side (hn : k < n) (hD : 0 < D) (delayed : full = false → h - a ≤ 32 * Nat.clog 2 (2 * D)) : + SurveySide U V σ R k := by + refine ⟨p.mix, fun _ _ _ hr hi => p.base (p.widen (hi.trans hn.le) hr), + fun _ _ _ hr hi => p.load (p.widen (hi.trans hn.le) hr), ?_, ?_, ?_⟩ + · intro i v z hr hi t ht hd + have hm : t ∈ U.adj full v := by + by_cases he : full = true + · simpa [adj, he] using ht + have h' := delayed (by simpa using he) + have hc : t ∈ U.G.C v := by + by_contra hbad + simp only [delay, resetDelay, hbad, ite_false] at hd + omega + simpa [adj, he] using hc + obtain ⟨j, hj, _⟩ := (P.links _ _).mp hm + let t' := V.post.nav z j + have ht' : R (i + 1) t t' := hj ▸ p.next hr j + have hh := p.widen (by omega : i + 1 ≤ n) ht' + have he := (p.preview.links (by omega) hr hh).mp hm + have hc := p.preview.core (by omega) hr hh + refine ⟨?_, t', ?_, ?_, ht'⟩ + · unfold delay resetDelay + apply Nat.mul_pos (by decide) + apply Nat.clog_pos (by decide) + have := U.hΔ + split_ifs <;> omega + · unfold adj at he + split at he <;> first | exact he | exact V.G.sub _ he + · simp only [delay, resetDelay, hc] + · intro i v z hr hi + exact p.siblings (by omega) hr + · intro i v z hr hi e t hx hv + obtain ⟨f, hz, hb, hs, he⟩ := U.transfer V hv (p.tag (p.widen (by omega) hr) _ hx) + have ht := p.next hr (U.post.index v (Scheme.side U.G e (!t))) + have eh := U.stub_nav e t + have fh := V.stub_nav f t + dsimp only at eh fh + rw [hv] at eh + rw [hz] at fh + rw [eh, he, fh] at ht + exact ⟨f, hz, ⟨hb, hs, p.preview.labels (by omega) hr (p.widen (by omega) ht)⟩, ht⟩ + +include p in +open scoped Classical in +theorem region (hn : k < n) (hD : 0 < D) (delayed : full = false → h - a + ≤ 32 * Nat.clog 2 (2 * D)) : + Region U V σ R k := + ⟨⟨p.side hn hD delayed, p.symm.side hn hD delayed⟩, p.widen, + fun r s => p.same (p.widen hn.le r) (p.widen hn.le s), + fun h r s => p.preview.labels (h.trans hn) r (p.widen hn.le s)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup.Look +end + +/- # The explicit reset selected by a template's controller -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +open Packing History.Reset + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} + {A : Template F} {G : HostNet F L A.scheme.h u} {r : A.format.obj} + (p : A.Encodes r G) {a t Δ D Y w Z k d : ℕ} {W ε : ℝ} + +open scoped Classical in +/-- The quantity computed by `2 * Δ * 2 ^ (32 * Nat.clog 2 (2 * Δ))`. -/ +def margin (Δ : ℕ) := 2 * Δ * 2 ^ (32 * Nat.clog 2 (2 * Δ)) + +open scoped Classical in +theorem margin_eq (Δ : ℕ) : (margin Δ : ℝ) = reserveCount Δ := by simp [margin, reserveCount] + +variable (ok : Fits (G := G) a t Δ D (margin Δ) Z k d W ε) (enough : 4 * coreBins Δ ≤ Y) + (space : Y ^ 2 * w ≤ 2 ^ t) (unit : (u : ℝ) / W ≤ 1 / (2 : ℝ) ^ t) + +open scoped Classical in +/-- Builds `Setup A.scheme A.scheme.h u a Δ D Y w W where T` with the specified `post`, `chart`, +`bound`, `hu`. -/ +def elected : Setup A.scheme A.scheme.h u a Δ D Y w W where + T := T + x := x + y := y + L := L + G := G + r := r.1 + post := p.post + chart := p.resetChart + k := t + g := margin Δ + ε := ε + Z := p.resetSchedule ok + bound := (p.resetSchedule ok).reserve G.cs G.sub ok.corePos ok.cdeg enough (margin_eq _) + hu := ok.width + hB := ok.capacity + hΔ := ok.corePos + deg := ok.cdeg + space := space + unit := unit + +open scoped Classical in +/-- Uses `Setup.reading _ r.2 p rfl rfl` as the representation. -/ +def reading : (p.elected ok enough space unit).Reading A.full := + Setup.reading _ r.2 p rfl rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Encodes +end + +/- +# Short records for the reset controller + +The mixer and full contact totals are selected once. A subsequent +lookup uses one group of blocks at every host reached by a short +walk, with a Boolean mask for coincidences of host names. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +open Coloring +variable {F : Type} (A : Template F) (a k : ℕ) (ha : a ≤ A.scheme.h) +local notation "S" => A.scheme + +open scoped Classical in +/-- Computes the summary by the application `Format.pair (.addr A.scheme.h) (.vec A.scheme.m +(A.Statistics k))`. -/ +abbrev summary := Format.pair (.addr A.scheme.h) (.vec A.scheme.m (A.Statistics k)) +open scoped Classical in +/-- The value specified by `A.format.pair (summary A k)`. -/ +abbrev pair := A.format.pair (summary A k) +open scoped Classical in +/-- The value specified by `Format.pair (.addr A.scheme.ℓ) (.addr A.count)`. -/ +abbrev data := Format.pair (.addr A.scheme.ℓ) (.addr A.count) +open scoped Classical in +/-- The quantity computed by `(A.Statistics k).pair ((Group.Flags A.scheme.d).pair (.vec +(A.scheme.h - a) (data A)))`. -/ +abbrev row := (A.Statistics k).pair ((Group.Flags A.scheme.d).pair (.vec (A.scheme.h - a) (data A))) +open scoped Classical in +/-- Computes the bank by the application `Fmt.groups A.scheme.m A.scheme.d a (row A a k)`. -/ +abbrev bank := Fmt.groups A.scheme.m A.scheme.d a (row A a k) + +open scoped Classical in +/-- The packet of type `(bank A a k).obj`, constructed using `cellIndex _ (Mixing.original +A.scheme.h a ha x.2.1 i j)`. -/ +def packet (x : (pair A k).obj) : (bank A a k).obj := + fun v => (A.nav x.1 v, fun i => (x.2.2 v, A.flags x.1 v, fun j => + let b := cellIndex _ (Mixing.original A.scheme.h a ha x.2.1 i j) + ((x.1.1 v).2 b, A.counter x.1 v b))) + +open scoped Classical in +/-- The quantity computed by `Format.vec ((d + 1) * n) (.vec ((d + 1) * n) .bit)`. -/ +abbrev coincides (d n : ℕ) := Format.vec ((d + 1) * n) (.vec ((d + 1) * n) .bit) + +open scoped Classical in +/-- Evaluates `decide (Neighborhood.walks n (A.nav r) v i = Neighborhood.walks n (A.nav r) v j)` +at the input `i j`. -/ +def mask (n : ℕ) (r : A.format.obj) (v : B A.scheme.m) : (coincides A.scheme.d n).obj := + fun i j => decide (Neighborhood.walks n (A.nav r) v i = Neighborhood.walks n (A.nav r) v j) + +open scoped Classical in +/-- The sample used in the `Tile` construction. -/ +abbrev sample (n t : ℕ) := + Format.pair (.pair .bit (.addr t)) (.pair (.pair (.addr A.scheme.h) (.addr a)) + (.pair (coincides A.scheme.d n) (Window.Walks n A.scheme.d (row A a k)))) + +open scoped Classical in +/-- The look of type `(sample A a k n t).obj`, constructed using `Match.rowIndex A.scheme.m t +v`. -/ +def look (n t : ℕ) (x : (pair A k).obj) (v : B (A.scheme.m + t)) (i : B a) : + (sample A a k n t).obj := + let p := Match.rowIndex A.scheme.m t v + ((A.live x.1 p.1, p.2), (x.2.1, i), mask A n x.1 p.1, + (Window.reads n (packet A a k ha x) p.1).2 i) + +open scoped Classical in +/-- The value specified by `(data D).pair (.vec D.scheme.k (.vec D.scheme.e +(BatchDescent.Trail.pointer S 0)))`. -/ +abbrev output (D : Template F) := + (data D).pair (.vec D.scheme.k (.vec D.scheme.e (BatchDescent.Trail.pointer S 0))) + +open scoped Classical in +/-- Computes the whole by the application `D.format.pair (BatchDescent.Trail.controls S D.scheme +0)`. -/ +abbrev whole (D : Template F) := D.format.pair (BatchDescent.Trail.controls S D.scheme 0) + +open scoped Classical in +/-- The value specified by `(((x.1.1 v).2 i, D.counter x.1 v i), x.2 v i)`. -/ +def part (D : Template F) (x : (whole A D).obj) (v : B D.scheme.m) (i : B D.scheme.h) : + (output A D).obj := + (((x.1.1 v).2 i, D.counter x.1 v i), x.2 v i) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end + +/- # Representation of an elected reset by its short and long records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +open Coloring Packing +variable {F : Type} [Field F] (A : Template F) {u a Δ D Y w : ℕ} {W : ℝ} + (U : Setup A.scheme A.scheme.h u a Δ D Y w W) + +open scoped Classical in +/-- The data for the board construction, including `read`, `tape`, `nav`, `live`, `frozen`. -/ +structure Board (k : ℕ) where + /-- The read operation of type `U.Reading A.full`. -/ + read : U.Reading A.full + /-- The `Board` component of type `(Tile.pair A k).obj`. -/ + tape : (Tile.pair A k).obj + nav : ∀ v i, U.post.host (U.post.nav v i) = A.nav tape.1 (U.post.host v) i + live : ∀ i, A.live tape.1 i = true ↔ i ∈ Set.range U.post.host + frozen : ∀ v, A.frozen tape.1 (U.post.host v) = true ↔ U.G.frozen v + flags : ∀ v, read.flags v = A.flags tape.1 (U.post.host v) + counts : ∀ v j, read.counts v j = ((tape.2.2 (U.post.host v)).2 j).val + depth : ∀ v, U.Z.base v = (tape.2.2 (U.post.host v)).1.val + mix : U.Z.π = menu A.scheme.h tape.2.1 + margin : U.g = reserveCount Δ + block : ∀ x, U.post.block x = cellIndex _ x + tag : ∀ v x, U.tag v x = (tape.1.1 (U.post.host v)).2 (cellIndex _ x) + load : ∀ v x, U.G.load v x = A.load (A.counter tape.1 (U.post.host v) (cellIndex _ x)) + park : ∀ v x, push U.G.park U.L.charge (v, x) = A.park (A.counter tape.1 (U.post.host v) + (cellIndex _ x)) + past : ∀ v x, U.G.past (v, x) = A.past (A.counter tape.1 (U.post.host v) (cellIndex _ x)) + +variable {A} {T : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} {G : HostNet F L A.scheme.h u} + {r : A.format.obj} (p : A.Encodes r G) {t Z k d : ℕ} {ε : ℝ} + (ok : Template.Encodes.Fits (G := G) a t Δ D (Template.Encodes.margin Δ) Z k d W ε) + (enough : 4 * coreBins Δ ≤ Y) (space : Y ^ 2 * w ≤ 2 ^ t) (unit : (u : ℝ) / W ≤ 1 / (2 : ℝ) ^ t) + +open scoped Classical in +/-- Builds `Board A (p.elected ok enough space unit) k where read` with the specified `read`, +`tape`, `fun`, `live`. -/ +def electedBoard : Board A (p.elected ok enough space unit) k where + read := p.reading ok enough space unit + tape := (r, A.mixerChoice a t Δ D u _ Z k d ok.depth W r, + fun v => (A.baseDepth a t Δ D Z k d W r v, A.unitCount r v)) + nav := p.host_nav + live := p.live + frozen := p.frozen + flags _ := rfl + counts _ _ := rfl + depth := p.reset_depth ok + mix := p.reset_mixer ok + margin := Template.Encodes.margin_eq Δ + block := p.block + tag v x := congrArg (r.1 (p.post.host v)).2 (p.block x) + load v x := (p.load v x).symm.trans (by rw [p.block]; rfl) + park v x := (p.park v x).symm.trans (by rw [p.block]; rfl) + past v x := (p.past v x).symm.trans (by rw [p.block]; rfl) + +namespace Board +variable {U} (b : Board A U k) (v : U.G.V) + +open scoped Classical in +/-- Computes the node by the application `Window.visit U.post.nav v p`. -/ +def node (p : List (B A.scheme.d)) := Window.visit U.post.nav v p + +include b in +open scoped Classical in +theorem at_node (p : List (B A.scheme.d)) : + U.post.host (node v p) = Window.visit (A.nav b.tape.1) (U.post.host v) p := by + induction p with + | nil => rfl + | cons j p ih => + rw [show node v (j::p) = U.post.nav (node v p) j from rfl, b.nav, ih] + rfl + +open scoped Classical in +/-- The value specified by `((Tile.packet A a k U.groups b.tape) (U.post.host v)).2 (cellIndex a +σ)`. -/ +def localRow (σ : Cell a) := + ((Tile.packet A a k U.groups b.tape) (U.post.host v)).2 (cellIndex a σ) + +open scoped Classical in +theorem original (x : Cell A.scheme.h) : + Mixing.original A.scheme.h a U.groups b.tape.2.1 (cellIndex _ (U.Z.group x)) + (cellIndex _ (splitCell a U.groups (U.Z.π x)).2) = x := by + simp only [Mixing.original, Mixing.merge, Equiv.symm_apply_apply, ← b.mix] + change U.Z.π.symm ((splitCell a U.groups).symm (splitCell a U.groups (U.Z.π x))) = x + simp + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Decoding a short parent hop and appending a hardware address -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +open Coloring Packing Finset + +namespace Child +variable {m d k l : ℕ} (r : (Input m d k l).obj) + +open scoped Classical in +theorem follow_hop (x : B m) (p : Option (B d)) : + follow r.1 x (BatchDescent.Trail.hop d p) = p.elim x (r.1 x) := by + cases p <;> simp [follow, BatchDescent.Trail.hop] + +open scoped Classical in +theorem build_hop (x : B (m + k)) (j : B l) (p : Option (B d)) (z : B k) + (he : ((r.2 x).2 j).2 = (BatchDescent.Trail.hop d p, z)) : + let v := (Match.rowIndex m k x).1 + (build m d k l r).1 x j = (Match.rowIndex m k).symm (p.elim v (r.1 v), z) := by + simp only [build, he, follow_hop] + +open scoped Classical in +theorem build_stay (x : B (m + k)) (j : B l) + (he : ((r.2 x).2 j).2 = (BatchDescent.Trail.hop d none, (Match.rowIndex m k x).2)) : + (build m d k l r).1 x j = x := + (build_hop r x j none _ he).trans ((Match.rowIndex m k).symm_apply_apply _) + +end Child + +namespace Board +variable {F : Type} [Field F] {A : Template F} {u a Δ D Y w k : ℕ} {W : ℝ} + {U : Setup A.scheme A.scheme.h u a Δ D Y w W} (b : Board A U k) + +open scoped Classical in +theorem parent_hop (v z : U.G.V) (h : z ∈ insert v (U.adj A.full v)) : + (U.chart.label v z).elim (U.post.host v) (A.nav b.tape.1 (U.post.host v)) = U.post.host z := by + have ht : z = v ∨ ∃ i, U.post.nav v i = z := by + rcases mem_insert.mp h with he|he + · exact .inl he + obtain ⟨i, hi, _⟩ := (b.read.links _ _).mp he + exact .inr ⟨i, hi⟩ + have he := label_spec U.post.nav ht + rw [← b.read.chart] at he + cases hm : U.chart.label v z with + | none => simp only [hm, Option.elim_none] at he; exact congrArg U.post.host he + | some i => + simp only [hm, Option.elim_some] at he + exact (b.nav _ i).symm.trans (congrArg U.post.host he) + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Headers.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Headers.lean new file mode 100644 index 0000000000..a2d3ec31eb --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Headers.lean @@ -0,0 +1,904 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Raw.Local + +/-! +# Expanding relative reset headers + +An address bit is either copied from the local suffix or selected +from the parent and its neighbors. Test each possible hop in +parallel. The cost per child is linear in the parent address width. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +open Coloring Install + +open scoped Classical in +/-- Test a disjunction of conjunctions, each test depending on at +most one input bit. -/ +private theorem any_all (F I J U V : Type) [Field F] [Fintype I] [Fintype J] + [Fintype U] [Fintype V] (bad : (I → Bool) → (J × U) × V → Bool) + (h : Depends bad 1) : + BNet F (fun x j => decide (∃ u, ∀ v, bad x ((j, u), v) = false)) + (Fintype.card I + Fintype.card J * (1 + 40 * Fintype.card U * (Fintype.card V + 1))) := by + have reject := (h.bnet F).comp ((BNet.any F V).copies (J × U)) + have neg : Depends (fun (x : (J × U) × Unit → Bool) (p : J × U) => !(x (p, ()))) 1 := by + intro p + exact ⟨{(p, ())}, by simp, fun _ _ e => congrArg Bool.not (e _ (by simp))⟩ + have accept := (reject.comp (neg.bnet F)).comp ((BNet.any F U).copies J) + have net := accept.rename (.refl I) (Equiv.prodUnique J Unit) + convert net.mono (n := Fintype.card I + + Fintype.card J * (1 + 40 * Fintype.card U * (Fintype.card V + 1))) ?_ using 1 + · funext x j + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq, Equiv.coe_refl, CompTriple.comp_eq, Function.comp_apply, + Bool.not_eq_eq_eq_not, Bool.not_true, decide_eq_false_iff_not, not_exists, Bool.not_eq_true, + Equiv.prodUnique_symm_apply, PUnit.default_eq_unit] + exact decide_eq_true_iff.symm + · simp only [localCost, Fintype.card_prod, Fintype.card_unit] + ring_nf + omega + +open scoped Classical in +/-- The key bits are projections and each candidate value is a projection +or a constant. -/ +private def Selects (A : Format) (n : ℕ) (f : A.obj → Bool) : Prop := + ∃ (key : A.obj → B n) (kn : slots (word n) → A.pins) + (val : B n → A.pins ⊕ Bool), + (∀ x i, (Format.addr n).code (key x) i = A.code x (kn i)) ∧ + ∀ x, f x = Sum.elim (A.code x) id (val (key x)) + +open scoped Classical in +private theorem select_net (F : Type) [Field F] {A D : Format} {n : ℕ} + {f : A.obj → D.obj} (H : ∀ j, Selects A n (fun x => D.code (f x) j)) : + Circuit F A D f (A.width + D.width * (1 + 40 * 2 ^ n * (n + 2))) := by + choose key kn val hk hv using H + let bad (x : A.pins → Bool) (p : (D.pins × B n) × Option (slots (word n))) := + let j := p.1.1 + let u := p.1.2 + match p.2 with + | none => !(Sum.elim x id (val j u)) + | some i => decide (x (kn j i) ≠ (Format.addr n).code u i) + have hd : Depends bad 1 := by + rintro ⟨⟨j, u⟩, _|i⟩ + · cases he : val j u with + | inl v => exact ⟨{v}, by simp, fun x y h => by simp [bad, he, h v (by simp)]⟩ + | inr b => exact ⟨∅, by simp, fun _ _ _ => by simp [bad, he]⟩ + · exact ⟨{kn j i}, by simp, fun x y h => by simp [bad, h (kn j i) (by simp)]⟩ + have net := any_all F _ _ _ _ bad hd + have valid (x : A.obj) (j) (u) : + (∀ i, bad (A.code x) ((j, u), i) = false) ↔ + key j x = u ∧ Sum.elim (A.code x) id (val j u) = true := by + constructor + · intro ht + refine ⟨(Format.addr n).code.injective (funext fun i => ?_), by simpa [bad] using ht none⟩ + simpa [bad, hk] using ht (some i) + · rintro ⟨rfl, ht⟩ (_ | i) + · simp [bad, ht] + · simp [bad, hk] + unfold Circuit + convert net using 1 + · funext x j + obtain ⟨v, rfl⟩ := A.code.surjective x + apply Bool.eq_iff_iff.mpr + simp [Function.comp_def, valid, hv] + · simp [Format.width, B, Nat.add_assoc] + +open scoped Classical in +private theorem build_selects (m d k l : ℕ) (t : (Graph (m + k) l).pins) : + Selects (Input m d k l) (d + 1) (fun x => (Graph (m + k) l).code (build m d k l x) t) := by + let I := Input m d k l + let hop (i : B (m + k)) (j : B l) (x : I.obj) := ((x.2 i).2 j).2.1 + have useHop {g : I.obj → Bool} (i : B (m + k)) (j : B l) + (v : B (d + 1) → I.pins ⊕ Bool) (he : ∀ x, g x = Sum.elim (I.code x) id (v (hop i j x))) : + Selects I (d + 1) g := + ⟨hop i j, fun t => .inr (i, .inr (j, .inr (.inl t))), v, fun _ _ => rfl, he⟩ + rcases t with ⟨i, j, z⟩ | ⟨i, z|⟨j, z⟩⟩ + · let parent := (Match.rowIndex m k i).1 + obtain ⟨q, hq⟩ := Match.append_pin m k z + rcases q with q | q + · let v (a : B (d + 1)) : I.pins ⊕ Bool := + if he : a.val < 2 ^ d then .inl (.inl (parent, ⟨a.val, he⟩, q)) + else .inr ((Format.addr m).code parent q) + refine useHop i j v fun x => ?_ + refine (hq (follow x.1 parent (hop i j x)) ((x.2 i).2 j).2.2).trans ?_ + simp only [Sum.elim_inl, follow, v] + split <;> rfl + · refine useHop i j (fun _ => .inl (.inr (i, .inr (j, .inr (.inr q))))) fun x => ?_ + exact hq (follow x.1 parent (hop i j x)) ((x.2 i).2 j).2.2 + · exact useHop i 0 (fun _ => .inl (.inr (i, .inl z))) fun _ => rfl + · exact useHop i j (fun _ => .inl (.inr (i, .inr (j, .inl z)))) fun _ => rfl + +open scoped Classical in +/-- The quantity computed by `1000 * 2 ^ (m + k + l + d) * (2 + d) * (4 + k + m)`. -/ +def buildCost (m d k l : ℕ) := 1000 * 2 ^ (m + k + l + d) * (2 + d) * (4 + k + m) + +open scoped Classical in +theorem build_net (F : Type) [Field F] (m d k l : ℕ) : + Circuit F (Input m d k l) (Graph (m + k) l) (build m d k l) (buildCost m d k l) := by + apply (select_net F (build_selects m d k l)).mono + have h₀ := Nat.pow_le_pow_right (by decide : 0 < 2) (show m + d ≤ m + k + l + d by omega) + have h₁ := Nat.pow_le_pow_right (by decide : 0 < 2) (show m + k ≤ m + k + l by omega) + have h₂ := Nat.pow_le_pow_right (by decide : 0 < 2) (show m + k + l ≤ m + k + l + d by omega) + have hi : (Input m d k l).width ≤ 2 ^ (m + k + l + d) * (m + 5 + d + k) := by + have hu := Nat.mul_le_mul_right m h₀ + have hv := Nat.mul_le_mul_right (5 + d + k) h₂ + simp only [Input, Suffix, Neighborhood.Rows, Format.width_vec, Format.width_pair, + Format.width_addr] + rw [Format.width_bit, Format.width_addr (d + 1)] + simp only [pow_add] at hu hv h₁ ⊢ + ring_nf at hu hv h₁ ⊢ + omega + have ho : (Graph (m + k) l).width ≤ 2 ^ (m + k + l) * (4 + m + k) := by + simp only [Graph, Group.Flags, Neighborhood.Rows, Format.width_vec, Format.width_pair, + Format.width_addr] + rw [Format.width_bit] + simp only [pow_add] at h₁ ⊢ + ring_nf at h₁ ⊢ + omega + have hcost : 1 + 40 * 2 ^ (d + 1) * (d + 1 + 2) ≤ 200 * 2 ^ d * (2 + d) := by + have := Nat.two_pow_pos d + rw [pow_succ] + ring_nf + omega + refine (Nat.add_le_add hi (Nat.mul_le_mul ho hcost)).trans ?_ + unfold buildCost + rw [pow_add 2 (m + k + l) d] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +end + +/- +# Comparing reset headers without block data + +The common child graph only needs the graph masks, base depths +and contact totals. Neither the chosen mixer nor the block records +enter this comparison. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring Finset + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + {U V : Setup S h u a Δ D Y w B'} {full : Bool} + (P : U.Reading full) (Q : V.Reading full) (R : Relation U V) (n : ℕ) + +namespace Preview + +variable {P Q R n} (p : Preview P Q R n) {v v' : U.G.V} {z z' : V.G.V} {k : ℕ} +include p + +open scoped Classical in +theorem neighbor (hk : k < n) (hr : R k v z) (he : v' ∈ U.G.C v) : + ∃ z' ∈ V.G.C z, R (k + 1) v' z' := by + obtain ⟨j, hj, _⟩ := (P.core _ _).mp he + have ht := hj ▸ p.next hr j + exact ⟨_, (p.core hk hr (p.widen hk ht)).mp he, ht⟩ + +open scoped Classical in +theorem maps (hk : k < n) (hr : R k v z) : U.chart.Maps V.chart v z := by + intro i hi + obtain ⟨j, hj, he⟩ := p.neighbor hk hr hi + exact ⟨j, hj, p.labels hk hr (p.widen hk he)⟩ + +open scoped Classical in +theorem opposite (hk : k + 1 < n) (hr : R k v z) (c : CoreContact U.G.C) + (t : Bool) (he : unitEnds c t = v) : + ∃ c' : CoreContact V.G.C, unitEnds c' t = z ∧ + R (k + 1) (unitEnds c (!t)) (unitEnds c' (!t)) ∧ + Chart.Matches (relBase a U.Z.base) (relBase a V.Z.base) c c' ∧ + U.Z.capacity c = V.Z.capacity c' := by + have hm : unitEnds c (!t) ∈ U.G.C v := he ▸ Chart.partner_mem U.G.cs c t + obtain ⟨w, hw, ht⟩ := p.neighbor (by omega) hr hm + have hv : R (k + 1) (unitEnds c t) z := he.symm ▸ p.widen (by omega) hr + have base {i j} (r : R (k + 1) i j) : relBase a U.Z.base i = relBase a V.Z.base j := + congrArg (· - a) (p.base (p.widen hk.le r)) + cases t + · let c' : CoreContact V.G.C := ⟨(z, w), hw⟩ + exact ⟨c', rfl, ht, fun b => by cases b <;> first | exact base hv | exact base ht, + p.capacity (c' := c') hk hv ht⟩ + · let c' : CoreContact V.G.C := ⟨(w, z), V.G.cs _ _ hw⟩ + exact ⟨c', rfl, ht, fun b => by cases b <;> first | exact base ht | exact base hv, + p.capacity (c' := c') hk ht hv⟩ + +open scoped Classical in +theorem relative (hk : k + 1 < n) (hr : R k v z) : + U.chart.Reserves U.Z.capacity V.chart V.Z.capacity (relBase a U.Z.base) (relBase a V.Z.base) v + z := by + intro c t ht + obtain ⟨c', ht', he, hd, hc⟩ := p.opposite hk hr c t ht + exact ⟨c', ht', p.labels (by omega) hr (p.widen hk.le he), hd, hc⟩ + +end Preview +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Agreement of both ends of the reserved output links -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + (U : Setup S h u a Δ D Y w B') + +open scoped Classical in +private abbrev Contact := Link (relBase a U.Z.base) (unitEnds (C := U.G.C)) +open scoped Classical in +private abbrev Place (e : U.Contact) := Fin ⌈U.Z.capacity e.1 * Y / 8⌉₊ +open scoped Classical in +private abbrev anchor := outLeaf (relBase a U.Z.base) (unitEnds (C := U.G.C)) (relHi a U.Z.depth) + +open scoped Classical in +private def reserved (e : U.Contact) (t : Bool) (i : U.Place e) : Site U.G.V (h - a) × Fin Y := + (U.anchor e t, U.plugs _ ⟨⟨(e, t), rfl⟩, i⟩) + +open scoped Classical in +private theorem reserved_slot (e : U.Contact) (t : Bool) (i : U.Place e) + (x : Site U.G.V (h - a)) (hx : U.anchor e t = x) : + (U.reserved e t i).2 = U.plugs x ⟨⟨(e, t), hx⟩, i⟩ := by subst x; rfl + +open scoped Classical in +private theorem peer_unused (x : Site U.G.V (h - a) × Fin Y) + (hn : ¬∃ e t i, U.reserved e t i = x) : Packing.peer U.plugs x = x := by + unfold Packing.peer + exact dite_eq_right (by rintro ⟨⟨⟨e, i⟩, t⟩, he⟩; exact hn ⟨e, t, i, he⟩) + +open scoped Classical in +private theorem peer_at (e : U.Contact) (t : Bool) (i : U.Place e) : + Packing.peer U.plugs (U.reserved e t i) = U.reserved e (!t) i := by + unfold Packing.peer + split + · rename_i he + have hh := he.choose_spec + generalize he.choose = p at * + rcases p with ⟨⟨q, j⟩, b⟩ + change U.reserved q b j = U.reserved e t i at hh + have hz : U.anchor q b = U.anchor e t := congrArg Prod.fst hh + have hn : U.plugs _ ⟨⟨(q, b), hz⟩, j⟩ = U.plugs (U.anchor e t) ⟨⟨(e, t), rfl⟩, i⟩ := + (U.reserved_slot q b j _ hz).symm.trans (congrArg Prod.snd hh) + obtain ⟨hk, hi⟩ := Sigma.mk.inj ((U.plugs _).injective hn) + have hp : (q, b) = (e, t) := congrArg Subtype.val hk + obtain ⟨rfl, rfl⟩ := Prod.mk.inj hp + cases eq_of_heq hi + rfl + · rename_i hn + exact (hn ⟨(⟨e, i⟩, t), rfl⟩).elim + +open scoped Classical in +/-- Unused terminals stay at home. Used terminals reach core neighbors. -/ +theorem peer_host (v : U.G.V) (d : Schedule.Address (h - a)) (i : Fin Y) : + (Packing.peer U.plugs ((v, d), i)).1.1 ∈ insert v (U.G.C v) := by + by_cases he : ∃ e t k, U.reserved e t k = ((v, d), i) + · obtain ⟨e, t, k, hk⟩ := he + rw [← hk, peer_at] + have hv : unitEnds e.1 t = v := congrArg (·.1.1) hk + exact Finset.mem_insert_of_mem (hv ▸ Chart.partner_mem U.G.cs e.1 t) + · rw [peer_unused U _ he] + exact Finset.mem_insert_self _ _ + +variable {U} {V : Setup S h u a Δ D Y w B'} {full : Bool} {P : U.Reading full} {Q : V.Reading full} + {R : Relation U V} {n k : ℕ} (p : Preview P Q R n) {v : U.G.V} {z : V.G.V} + +include p in +open scoped Classical in +private theorem Preview.slot_eq (hk : k + 1 < n) {e : U.Contact} {f : V.Contact} + (t : Bool) (hr : R k (unitEnds e.1 t) (unitEnds f.1 t)) + (hs : R n (unitEnds e.1 (!t)) (unitEnds f.1 (!t))) + (hd : (U.anchor e t).2 = (V.anchor f t).2) (ha : Chart.address e = Chart.address f) + {i : U.Place e} {j : V.Place f} (hi : i.val = j.val) : + (U.reserved e t i).2 = (V.reserved f t j).2 := by + let x := (U.anchor e t).2 + have hu : U.anchor e t = (unitEnds e.1 t, x) := rfl + have hv : V.anchor f t = (unitEnds f.1 t, x) := Prod.ext rfl hd.symm + rw [U.reserved_slot _ _ _ _ hu, V.reserved_slot _ _ _ _ hv] + apply Chart.plugs_eq U.chart U.G.cs _ _ V.chart V.G.cs _ _ + (p.relative hk hr) (p.symm.relative hk hr) + exact Prod.ext rfl (Prod.ext (p.labels (by omega) hr hs) (Prod.ext ha hi)) + +include p in +open scoped Classical in +private theorem Preview.peer_on (hk : k + 3 ≤ n) (hr : R k v z) {d : Schedule.Address (h - a)} {i : + Fin Y} + (e : U.Contact) (t : Bool) (j : U.Place e) (he : U.reserved e t j = ((v, d), i)) : + let x := Packing.peer U.plugs ((v, d), i) + let y := Packing.peer V.plugs ((z, d), i) + R (k + 1) x.1.1 y.1.1 ∧ x.1.2 = y.1.2 ∧ x.2 = y.2 := by + have hv : unitEnds e.1 t = v := congrArg (·.1.1) he + obtain ⟨c, hz, hp, hm, hc⟩ := p.opposite (by omega) hr e.1 t hv + obtain ⟨f, rfl, ha⟩ := Chart.link_exists e c hm + let l : V.Place f := ⟨j.val, hc ▸ j.isLt⟩ + have hs (b) : (U.anchor e b).2 = (V.anchor f b).2 := + Chart.Matches.site _ _ hm ha b + have hr' : R k (unitEnds e.1 t) (unitEnds f.1 t) := by rw [hv, hz]; exact hr + have hf : V.reserved f t l = ((z, d), i) := by + have eq := p.slot_eq (by omega) t hr' (p.widen (by omega) hp) (hs t) ha (i := j) (j := l) rfl + exact Prod.ext (Prod.ext hz ((hs t).symm.trans (congrArg (·.1.2) he))) + (eq.symm.trans (congrArg Prod.snd he)) + rw [← he, ← hf, U.peer_at, V.peer_at] + refine ⟨hp, hs (!t), p.slot_eq (by omega) (!t) hp ?_ (hs (!t)) ha rfl⟩ + rw [Bool.not_not] + exact p.widen (by omega) hr' + +include p in +open scoped Classical in +/-- The extra radius compares both the near and far reservations. -/ +theorem Preview.peer (hk : k + 3 ≤ n) (hr : R k v z) (d : Schedule.Address (h - a)) (i : Fin Y) : + let x := Packing.peer U.plugs ((v, d), i) + let y := Packing.peer V.plugs ((z, d), i) + R (k + 1) x.1.1 y.1.1 ∧ x.1.2 = y.1.2 ∧ x.2 = y.2 := by + by_cases hu : ∃ e t j, U.reserved e t j = ((v, d), i) + · obtain ⟨e, t, j, he⟩ := hu + exact p.peer_on hk hr e t j he + by_cases hv : ∃ f t j, V.reserved f t j = ((z, d), i) + · obtain ⟨f, t, j, hf⟩ := hv + obtain ⟨he, hd, hi⟩ := p.symm.peer_on hk hr f t j hf + exact ⟨he, hd.symm, hi.symm⟩ + rw [U.peer_unused _ hu, V.peer_unused _ hv] + exact ⟨p.widen (by omega) hr, rfl, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The forms of links in a reset graph -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring Finset + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} + {B' c : ℝ} [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + +local notation "L" => terminalWidth Δ Y +local notation "SiteAddr" => Schedule.Address (h - a) +local notation "Part" => Child.Part R Δ (h - a) + +open scoped Classical in +/-- The part link used in the `Setup` construction. -/ +inductive PartLink (mode : Bool) : U.G.V → Part → U.G.V → Part → Prop where + | rotor (v s r t) (he : t ∈ R.support r) : PartLink mode v (.inl (s, r)) v (.inl (s, t)) + | peer (v s i z t j) (he : Packing.peer U.plugs ((v, s), i) = ((z, t), j)) : + PartLink mode v (.inl (s, R.root true i)) z (.inl (t, R.root true j)) + | enter (v s i) : PartLink mode v (.inl (s, R.root false i)) v (.inr ((s, i), Tree.root L)) + | leave (v s i) : PartLink mode v (.inr ((s, i), Tree.root L)) v (.inl (s, R.root false i)) + | tree (v s i p q) (he : q ∈ Tree.adj p) : PartLink mode v (.inr ((s, i), p)) v (.inr ((s, i), q)) + | bridge (v s i z t j) (he : ((z, t), j) ∈ U.switch.near ((v, s), i)) : + PartLink mode v (.inr ((s, i), Tree.tip (U.pins _ ⟨_, he⟩))) + z (.inr ((t, j), Tree.tip (U.pins _ ⟨_, U.switch.sym _ _ he⟩))) + | tether (v s i z t j) (hm : mode = true) (he : ((z, t), j) ∈ terminalNear U.G.N D Y ((v, s), + i)) : + PartLink mode v (.inl (s, R.root false i)) z (.inl (t, R.root false j)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Translating between hardware links and numbered parts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring Finset + +open scoped Classical in +private theorem detour_cases {X : Type} [Fintype X] {l : ℕ} (sw : Detour.Switch X l) + (x : X) (p : Tree.Node l) {q : Detour.Hub X l} (hq : q ∈ sw.adj (.inr (x, p))) : + (∃ t ∈ Tree.adj p, q = .inr (x, t)) ∨ (p = Tree.root l ∧ q = .inl x) ∨ + (∃ y, ∃ h : y ∈ sw.near x, p = Tree.tip (sw.pin x ⟨y, h⟩) ∧ + q = .inr (y, Tree.tip (sw.pin y ⟨x, sw.sym _ _ h⟩))) := by + rcases mem_union.mp hq with hq|hq + · rcases mem_union.mp hq with hq|hq + · obtain ⟨t, ht, rfl⟩ := mem_image.mp hq + exact .inl ⟨t, ht, rfl⟩ + · split_ifs at hq with hp + · exact .inr (.inl ⟨hp, mem_singleton.mp hq⟩) + · exact (Finset.notMem_empty _ hq).elim + · obtain ⟨⟨y, t⟩, ht, rfl⟩ := mem_image.mp hq + obtain ⟨he, hp, ht⟩ := (mem_filter.mp ht).2 + exact .inr (.inr ⟨y, he, hp.symm, congrArg (fun i => Sum.inr (y, i)) ht.symm⟩) + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} + {B' c : ℝ} [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + +local notation "L" => terminalWidth Δ Y +local notation "SiteAddr" => Schedule.Address (h - a) +local notation "Part" => Child.Part R Δ (h - a) + +variable (fits : U.Fits R c) (mode : Bool) +local notation "parts" => (Setup.parts U R fits) +local notation "links" => (Rotor.links R (switch U) (Packing.peer (plugs U))) + +open scoped Classical in +private theorem core_link {x y : (U.graph R fits).V} (he : y ∈ links x) : + PartLink U R mode (parts x).1 (parts x).2 (parts y).1 (parts y).2 := by + rcases x with ⟨⟨v, s⟩, r⟩|⟨⟨⟨v, s⟩, i⟩, p⟩ + · rcases mem_union.mp he with he|he + · obtain ⟨⟨⟨z, t⟩, q⟩, hq, rfl⟩ := mem_image.mp he + rcases (R.mem_net ..).mp hq with ⟨hx, hq⟩|⟨i, hi, hq⟩ + · obtain ⟨rfl, rfl⟩ := Prod.mk.inj hx + exact .rotor _ _ _ _ hq + · change r = R.root true i at hi + subst r + generalize hh : Packing.peer U.plugs ((v, s), i) = j at hq + obtain ⟨⟨z', t'⟩, j⟩ := j + obtain ⟨⟨rfl, rfl⟩, rfl⟩ := hq + exact .peer _ _ _ _ _ _ hh + · obtain ⟨i, hi, rfl⟩ := mem_image.mp he + have hr : r = R.root false i := (mem_filter.mp hi).2 + subst r + exact .enter _ _ _ + · obtain ⟨q, hq, rfl⟩ := mem_image.mp he + rcases detour_cases U.switch _ _ hq with ⟨t, ht, rfl⟩|⟨rfl, rfl⟩|⟨⟨⟨z, t⟩, j⟩, hn, rfl, rfl⟩ + · exact .tree _ _ _ _ _ ht + · exact .leave _ _ _ + · exact .bridge _ _ _ _ _ _ hn + +open scoped Classical in +theorem part_link {x y : (U.graph R fits).V} (he : y ∈ U.neighbors R fits mode x) : + PartLink U R mode (parts x).1 (parts x).2 (parts y).1 (parts y).2 := by + cases mode + · exact core_link U R fits false he + rcases mem_union.mp he with he|he + · exact core_link U R fits true he + · split_ifs at he with hx + · obtain ⟨⟨⟨z, t⟩, j⟩, hz, rfl⟩ := mem_image.mp he + have hv := hx.choose_spec + generalize hx.choose = i at hv hz + obtain ⟨⟨v, s⟩, i⟩ := i + rw [← hv] + exact .tether _ _ _ _ _ _ rfl hz + · exact (Finset.notMem_empty _ he).elim + +open scoped Classical in +private theorem from_core (x y : (U.graph R fits).V) (hy : y ∈ links x) : + y ∈ U.neighbors R fits mode x := by + cases mode + · exact hy + · exact (U.graph R fits).sub _ hy + +open scoped Classical in +theorem link_part {x y : U.G.V} {s t : Part} (he : PartLink U R mode x s y t) : + (parts).symm (y, t) ∈ U.neighbors R fits mode ((parts).symm (x, s)) := by + cases he with + | rotor j p q he => + apply from_core U R fits mode + exact R.links_net U.switch _ ((R.mem_net ..).mpr (.inl ⟨rfl, he⟩)) + | peer i p z j q he => + apply from_core U R fits mode + apply R.links_net + apply (R.mem_net ..).mpr + exact .inr ⟨p, rfl, by rw [he]⟩ + | enter j i => + apply from_core U R fits mode + exact R.links_detour U.switch (Packing.peer U.plugs) (v:=.inl ((x, j), + i)) (mem_singleton_self _) + | leave j i => + apply from_core U R fits mode + exact R.links_detour U.switch (Packing.peer U.plugs) (U.switch.adj_symm (.inl ((x, j), + i)) _ (mem_singleton_self _)) + | tree j i p q he => + apply from_core U R fits mode + exact R.links_detour U.switch (Packing.peer U.plugs) (U.switch.adj_inner ((x, j), i) he) + | bridge j i z q l he => + apply from_core U R fits mode + have ht := U.switch.adj_bridge _ _ he + have heq : U.switch.pin = U.pins := rfl + rw [heq] at ht + have link := R.links_detour U.switch (Packing.peer U.plugs) ht + exact link + | tether i p z j q hm he => + subst mode + have hh := R.input_full U.switch (Packing.peer U.plugs) (terminalNear U.G.N D Y) he + exact hh + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Transporting a child link between matching parent neighborhoods -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring Finset + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} + {B' : ℝ} {U V : Setup S h u a Δ D Y w B'} {full : Bool} + {P : U.Reading full} {Q : V.Reading full} {T : Relation U V} {k n : ℕ} + +namespace Preview +variable (p : Preview P Q T n) {x x' : U.G.V} {y y' : V.G.V} + {s t : Schedule.Address (h - a)} {i j : Fin Y} +include p + +open scoped Classical in +private theorem move_terminal {C : U.G.V → Finset U.G.V} {C' : V.G.V → Finset V.G.V} + {L : ℕ} (hr : T k x y) (hc : ∀ v ∈ C x, ∃ z ∈ C' y, T (k + 1) v z) + (he : ((x', t), j) ∈ terminalNear C L Y ((x, s), i)) : + ∃ z, ((z, t), j) ∈ terminalNear C' L Y ((y, s), i) ∧ T (k + 1) x' z := by + rcases (mem_near ..).mp (mem_product.mp he).1 with eq | ⟨hv, ht⟩ + · obtain ⟨rfl, rfl⟩ := Prod.mk.inj eq + exact ⟨y, mem_product.mpr ⟨near_self _ _ _, mem_univ _⟩, p.widen (by omega) hr⟩ + obtain ⟨z, hz, r⟩ := hc _ hv + exact ⟨z, mem_product.mpr ⟨(mem_near ..).mpr (.inr ⟨hz, ht⟩), mem_univ _⟩, r⟩ + +open scoped Classical in +private theorem pin_eq (hn : k < n) (hr : T k x y) (ht : T n x' y') + (he : ((x', t), j) ∈ terminalNear U.G.C Δ Y ((x, s), i)) + (hf : ((y', t), j) ∈ terminalNear V.G.C Δ Y ((y, s), i)) : + U.pins _ ⟨_, he⟩ = V.pins _ ⟨_, hf⟩ := + U.chart.treePin_eq V.chart (p.maps hn hr) (p.symm.maps hn hr) + U.hΔ U.deg V.deg s i _ _ (Prod.ext (p.labels hn hr ht) rfl) + +open scoped Classical in +/-- Both parts of a link are unchanged when its parent hosts are relabeled. -/ +theorem move_link (R : Rotor F Y w) (mode : Bool) (hm : mode = true → full = true) + {i j : Child.Part R Δ (h - a)} (hn : k + 4 ≤ n) (hr : T k x y) + (hx : PartLink U R mode x i x' j) : + ∃ y', PartLink V R mode y i y' j ∧ T (k + 1) x' y' := by + have hk : k < n := by omega + have hw : T (k + 1) x y := p.widen (by omega) hr + cases hx with + | rotor s r t he => exact ⟨y, .rotor _ _ _ _ he, hw⟩ + | enter s i => exact ⟨y, .enter _ _ _, hw⟩ + | leave s i => exact ⟨y, .leave _ _ _, hw⟩ + | tree s i b c he => exact ⟨y, .tree _ _ _ _ _ he, hw⟩ + | peer s i z t j he => + have hp := p.peer (by omega) hr s i + rw [he] at hp + exact ⟨_, .peer _ _ _ _ _ _ (Prod.ext (Prod.ext rfl hp.2.1.symm) hp.2.2.symm), hp.1⟩ + | bridge s i z t j he => + obtain ⟨b, hb, hz⟩ := p.move_terminal hr (fun _ h => p.neighbor hk hr h) he + have hf := p.pin_eq hk hr (p.widen hk hz) he hb + have hg := p.pin_eq (by omega) hz (p.widen hk.le hr) + (U.switch.sym _ _ he) (V.switch.sym _ _ hb) + rw [hf, hg] + exact ⟨b, .bridge _ _ _ _ _ _ hb, hz⟩ + | tether s i z t j ha he => + have hh := hm ha + subst full + have hc (v) (hv : v ∈ U.G.N x) : ∃ b ∈ V.G.N y, T (k + 1) v b := by + obtain ⟨q, hq, _⟩ := (P.links _ _).mp hv + have hb := hq ▸ p.next hr q + exact ⟨_, (p.links hk hr (p.widen hk hb)).mp hv, hb⟩ + obtain ⟨b, hb, hz⟩ := p.move_terminal hr hc he + exact ⟨b, .tether _ _ _ _ _ _ ha hb, hz⟩ + +end Preview +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Reconstructing child adjacency from the parent computation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring Finset + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} + {B' c : ℝ} [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + +local notation "Part" => Child.Part R Δ (h - a) + +omit [NeZero Y] [NeZero w] in +open scoped Classical in +private theorem part_parent (full : Bool) {v z : U.G.V} {i j : Part} + (e : PartLink U R full v i z j) : z ∈ insert v (U.adj full v) := by + have sub (v : U.G.V) : insert v (U.G.C v) ⊆ insert v (U.adj full v) := by + cases full + · exact subset_rfl + · exact insert_subset_insert _ (U.G.sub v) + cases e with + | rotor | enter | leave | tree => exact mem_insert_self .. + | peer s i z t j he => + have ht := U.peer_host v s i + rw [he] at ht + exact sub _ ht + | bridge s i z t j he => + exact sub _ (Chart.near_host (mem_product.mp he).1) + | tether s i z t j hm he => + subst full + exact Chart.near_host (mem_product.mp he).1 + +open scoped Classical in +theorem parent_mem (fits : U.Fits R c) (full : Bool) {x y : (U.graph R fits).V} + (he : y ∈ U.neighbors R fits full x) : + (U.parts R fits y).1 ∈ insert (U.parts R fits x).1 (U.adj full (U.parts R fits x).1) := + part_parent U R full (part_link U R fits full he) + +variable {U} {V : Setup S h u a Δ D Y w B'} {full : Bool} {k n : ℕ} + {P : U.Reading full} {Q : V.Reading full} {T : Relation U V} + +open scoped Classical in +theorem Preview.adjacent (p : Preview P Q T n) (R : Rotor F Y w) (fu : U.Fits R c) (fv : V.Fits R c) + (mode : Bool) (hm : mode = true → full = true) {x x' : (U.graph R fu).V} {y : (V.graph R fv).V} + (hn : k + 4 ≤ n) (hr : T k (U.parts R fu x).1 (V.parts R fv y).1) + (he : (U.parts R fu x).2 = (V.parts R fv y).2) (hx : x' ∈ U.neighbors R fu mode x) : + ∃ y' ∈ V.neighbors R fv mode y, T (k + 1) (U.parts R fu x').1 (V.parts R fv y').1 ∧ + (U.parts R fu x').2 = (V.parts R fv y').2 := by + obtain ⟨z, ha, hz⟩ := p.move_link R mode hm hn hr (part_link U R fu mode hx) + rw [he] at ha + have hh := link_part V R fv mode ha + rw [Prod.mk.eta, Equiv.symm_apply_apply] at hh + refine ⟨_, hh, ?_⟩ + rw [Equiv.apply_symm_apply] + exact ⟨hz, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- +# Numbering child neighbors by relative names + +Slot zero is reserved for the child itself. Number its strict +neighbors by the return hop at the parent and the hardware suffix. +The resulting order needs no ambient host names. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Coloring Packing Finset + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) (fits : U.Fits R c) + +open scoped Classical in +/-- The value specified by `(U.chart.label (U.parts R fits x).1 (U.parts R fits y).1, (U.parts R +fits y).2)`. -/ +def coord (x y : (U.graph R fits).V) := + (U.chart.label (U.parts R fits x).1 (U.parts R fits y).1, (U.parts R fits y).2) + +open scoped Classical in +/-- The selected finite family `((U.neighbors R fits mode x).image (U.coord R fits x)).erase +(U.coord R fits x x)`. -/ +def candidates (mode : Bool) (x : (U.graph R fits).V) := + ((U.neighbors R fits mode x).image (U.coord R fits x)).erase (U.coord R fits x x) + +open scoped Classical in +theorem card_candidates (mode : Bool) (x : (U.graph R fits).V) : + (U.candidates R fits mode x).card < 2 ^ (Child.width D Y mode) := by + refine lt_of_le_of_lt (card_erase_le.trans card_image_le) ?_ + cases mode + · exact Nat.lt_succ_of_le ((U.result R fits).core_degree x) + · have hd := (U.result R fits).full_degree x + have ht := Nat.le_pow_clog (by decide : 1 < 2) (4 + terminalWidth D Y) + change ((U.result R fits).full x).card < 2 ^ Nat.clog 2 (4 + terminalWidth D Y) + omega + +open scoped Classical in +/-- Returns `(s.equivFin ⟨x, hp⟩).val + 1` when `hp : x ∈ s` holds, and `0` otherwise. -/ +def number {A : Type} (s : Finset A) (x : A) : ℕ := + if hp : x ∈ s then (s.equivFin ⟨x, hp⟩).val + 1 else 0 + +open scoped Classical in +theorem number_le {A : Type} (s : Finset A) (x : A) : number s x ≤ s.card := by + unfold number + split + · exact (s.equivFin _).isLt + · exact Nat.zero_le _ + +open scoped Classical in +private theorem number_inj {A : Type} (s : Finset A) (x : A) : + Set.InjOn (number s) (insert x (s : Set A)) := by + intro i hi j hj he + unfold number at he + split at he <;> split at he + · exact congrArg Subtype.val (s.equivFin.injective (Fin.ext (Nat.add_right_cancel he))) + · omega + · omega + · rename_i h₁ h₂ + exact (hi.resolve_right h₁).trans (hj.resolve_right h₂).symm + +open scoped Classical in +/-- The value specified by `⟨number (U.candidates R fits full x) (U.coord R fits x y), +(number_le ..).trans_lt (U.card_candidates R fits full x)⟩`. -/ +def index (full : Bool) (x y : (U.graph R fits).V) : B (Child.width D Y full) := + ⟨number (U.candidates R fits full x) (U.coord R fits x y), + (number_le ..).trans_lt (U.card_candidates R fits full x)⟩ + +open scoped Classical in +theorem index_self (full : Bool) (x : (U.graph R fits).V) : U.index R fits full x x = 0 := by + apply Fin.ext + simp [index, number, candidates] + +open scoped Classical in +theorem index_inj (full : Bool) (P : U.Reading full) (x : (U.graph R fits).V) : + Set.InjOn (U.index R fits full x) (↑(insert x (U.neighbors R fits full x))) := by + let f := U.coord R fits x + let A := U.candidates R fits full x + let base := (U.parts R fits x).1 + have info (i : (U.graph R fits).V) (hi : i ∈ insert x (U.neighbors R fits full x)) : + f i ∈ insert (f x) (A : Set _) ∧ + (f i).1.elim base (U.post.nav base) = (U.parts R fits i).1 := by + have hm : (U.parts R fits i).1 ∈ insert base (U.adj full base) := by + rcases mem_insert.mp hi with rfl | hi + · exact mem_insert_self .. + · exact U.parent_mem R fits full hi + refine ⟨?_, ?_⟩ + · by_cases he : f i = f x + · exact .inl he + · have hi' := (mem_insert.mp hi).resolve_left (mt (congrArg f) he) + exact .inr (mem_erase.mpr ⟨he, mem_image_of_mem _ hi'⟩) + · change (U.chart.label base _).elim base _ = _ + rw [P.chart] + refine label_spec _ ((mem_insert.mp hm).imp_right (fun h => ?_)) + obtain ⟨j, hj, _⟩ := (P.links _ _).mp h + exact ⟨j, hj⟩ + intro i hi j hj he + obtain ⟨hi, di⟩ := info i hi + obtain ⟨hj, dj⟩ := info j hj + have hh : f i = f j := number_inj A (f x) hi hj (congrArg Fin.val he) + apply (U.parts R fits).injective + exact Prod.ext (di.symm.trans (hh ▸ dj)) (congrArg (fun t => t.2) hh) + +namespace Preview + +variable {U} {V : Setup S h u a Δ D Y w B'} {full : Bool} {n k : ℕ} + {P : U.Reading full} {Q : V.Reading full} {T : Relation U V} (p : Preview P Q T n) + (R : Rotor F Y w) (fu : U.Fits R c) (fv : V.Fits R c) + {x x' : (U.graph R fu).V} {y y' : (V.graph R fv).V} + (hk : k + 4 ≤ n) (hr : T k (U.parts R fu x).1 (V.parts R fv y).1) + (he : (U.parts R fu x).2 = (V.parts R fv y).2) + (hr' : T n (U.parts R fu x').1 (V.parts R fv y').1) + (he' : (U.parts R fu x').2 = (V.parts R fv y').2) + +include p hk hr he hr' he' + +open scoped Classical in +private theorem neighbor_forward (mode : Bool) (hm : mode = true → full = true) + (hx : x' ∈ U.neighbors R fu mode x) : y' ∈ V.neighbors R fv mode y := by + obtain ⟨z, hz, ht, heq⟩ := p.adjacent R fu fv mode hm hk hr he hx + have same : z = y' := (V.parts R fv).injective (Prod.ext + ((p.same (p.widen (by omega) ht) hr').mp rfl) (heq.symm.trans he')) + rwa [same] at hz + +open scoped Classical in +theorem neighbors_iff (mode : Bool) (hm : mode = true → full = true) : + x' ∈ U.neighbors R fu mode x ↔ y' ∈ V.neighbors R fv mode y := + ⟨p.neighbor_forward R fu fv hk hr he hr' he' mode hm, + p.symm.neighbor_forward R fv fu hk hr he.symm hr' he'.symm mode hm⟩ + +omit he in +open scoped Classical in +private theorem same_coord : U.coord R fu x x' = V.coord R fv y y' := + Prod.ext (p.labels (by omega) hr hr') he' + +omit hr' he' in +open scoped Classical in +private theorem image_sub : + (U.neighbors R fu full x).image (U.coord R fu x) ⊆ + (V.neighbors R fv full y).image (V.coord R fv y) := by + intro a ha + obtain ⟨z, hz, rfl⟩ := mem_image.mp ha + obtain ⟨b, hb, ht, heq⟩ := p.adjacent R fu fv full id hk hr he hz + exact mem_image.mpr ⟨b, hb, (p.same_coord R fu fv hk hr (p.widen (by omega) ht) heq).symm⟩ + +open scoped Classical in +theorem idx_match : U.index R fu full x x' = V.index R fv full y y' := by + have hset := subset_antisymm (p.image_sub R fu fv hk hr he) + (p.symm.image_sub R fv fu hk hr he.symm) + have self := p.same_coord R fu fv hk hr (p.widen (by omega) hr) he + have eq := p.same_coord R fu fv hk hr hr' he' + apply Fin.ext + change number (U.candidates R fu full x) _ = number (V.candidates R fv full y) _ + unfold candidates + rw [self, hset, eq] + +end Preview +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Reassembling a reset from graph headers and block decisions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +open Coloring +variable {F : Type} (A D : Template F) + +/-- Computes the graph by the application `Format.pair (Neighborhood.Rows D.scheme.m D.scheme.d) +(.vec D.scheme.m (.pair (.pair .bit .bit) (Group.Flags D.scheme.d)))`. -/ +abbrev graph := Format.pair (Neighborhood.Rows D.scheme.m D.scheme.d) + (.vec D.scheme.m (.pair (.pair .bit .bit) (Group.Flags D.scheme.d))) + +theorem graph_width_le : (graph D).width ≤ D.format.width := by + rw [Template.width] + simp only [graph, Neighborhood.Rows, Group.Flags, Format.width_pair, Format.width_vec, + Format.width_addr] + rw [Format.width_bit, ← mul_add] + apply Nat.mul_le_mul_left + ring_nf + omega + +/-- The indexed operation `(D.nav r, fun v => ((D.live r v, D.frozen r v), D.flags r v))`. -/ +def header (r : D.format.obj) : (graph D).obj := + (D.nav r, fun v => ((D.live r v, D.frozen r v), D.flags r v)) + +/-- Computes the body by the application `Format.vec D.scheme.m (.vec D.scheme.h (output A D))`. -/ +abbrev body := Format.vec D.scheme.m (.vec D.scheme.h (output A D)) + +/-- The indexed operation `((fun v => (r.1.1 v, fun j => (r.2 v j).1.1), fun v => ((r.1.2 v).1, +(r.1.2 v).2, fun j => (r.2 v j).1.2)), fun v j => (r.2 v j).2)`. -/ +def assemble (r : (Format.pair (graph D) (body A D)).obj) : (whole A D).obj := + ((fun v => (r.1.1 v, fun j => (r.2 v j).1.1), + fun v => ((r.1.2 v).1, (r.1.2 v).2, fun j => (r.2 v j).1.2)), + fun v j => (r.2 v j).2) + +theorem assemble_part (x : (whole A D).obj) : + assemble A D (header D x.1, part A D x) = x := rfl + +/-- The quantity computed by `(Format.pair (graph D) (body A D)).width + 2 * (whole A D).width`. -/ +def assembleCost := (Format.pair (graph D) (body A D)).width + 2 * (whole A D).width + +theorem assemble_net [Field F] : + Circuit F (.pair (graph D) (body A D)) (whole A D) (assemble A D) (assembleCost A D) := by + let idx : (whole A D).pins → (Format.pair (graph D) (body A D)).pins + | .inl (.inl (v, .inl j)) => .inl (.inl (v, j)) + | .inl (.inl (v, .inr (b, j))) => .inr (v, b, .inl (.inl j)) + | .inl (.inr (v, .inl j)) => .inl (.inr (v, .inl j)) + | .inl (.inr (v, .inr (.inl j))) => .inl (.inr (v, .inr j)) + | .inl (.inr (v, .inr (.inr (b, j)))) => .inr (v, b, .inl (.inr j)) + | .inr (v, b, j) => .inr (v, b, .inr j) + apply Circuit.project idx + rintro _ ((⟨v, j|⟨b, j⟩⟩|⟨v, j|j|⟨b, j⟩⟩)|⟨v, b, j⟩) <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end + +/- # Applying a selected mixer to the short fields of every host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +open Coloring +variable {F : Type} (A : Template F) (a k : ℕ) (ha : a ≤ A.scheme.h) +local notation "G" => Mixing.Groups A.scheme.h a (data A) A.scheme.m +local notation "D" => + Format.pair (Format.addr A.scheme.h) (Mixing.Data A.scheme.h (data A) A.scheme.m) +local notation "R" => pair A k +local notation "B" => bank A a k + +private def split (x : (R).obj) : (D).obj := + (x.2.1, fun v i => ((x.1.1 v).2 i, A.counter x.1 v i)) + +private def join (x : (Format.pair R G).obj) : (B).obj := + fun v => (A.nav x.1.1 v, fun i => (x.1.2.2 v, A.flags x.1.1 v, x.2 v i)) + +/-- The bound obtained by adding the component charges `10 * (R).width + 2 * (D).width + +(G).width + 2 * (B).width + Mixing.applyCost A.scheme.h (data A) A.scheme.m`. -/ +def packetCost := 10 * (R).width + 2 * (D).width + (G).width + 2 * (B).width + + Mixing.applyCost A.scheme.h (data A) A.scheme.m + +variable [Field F] + +private theorem split_net : Circuit F R D (split A k) ((R).width + 2 * (D).width) := by + let idx : (D).pins → (R).pins + | .inl j => .inr (.inl j) + | .inr (v, i, .inl j) => .inl (.inl (v, .inr (i, j))) + | .inr (v, i, .inr j) => .inl (.inr (v, .inr (.inr (i, j)))) + exact Circuit.project idx (by rintro _ (j|⟨v, i, j|j⟩) <;> rfl) + +private theorem join_net : Circuit F (.pair R G) B (join A a k) ((Format.pair R G).width + + 2 * (B).width) := by + let idx : (B).pins → (Format.pair R G).pins + | (v, .inl j) => .inl (.inl (.inl (v, .inl j))) + | (v, .inr (_, .inl j)) => .inl (.inr (.inr (v, j))) + | (v, .inr (_, .inr (.inl j))) => .inl (.inl (.inr (v, .inr (.inl j)))) + | (v, .inr (i, .inr (.inr j))) => .inr (v, i, j) + exact Circuit.project idx (by rintro _ ⟨v, j|⟨i, j|j|j⟩⟩ <;> rfl) + +theorem packet_net : Circuit F R B (packet A a k ha) (packetCost A a k) := by + have mix := (split_net A k).comp (Mixing.apply_mixer A.scheme.h a ha (data A) A.scheme.m) + have net := ((Circuit.id F R).pair mix).comp (join_net A a k) + exact net.mono (by rw [packetCost, Format.width_pair R G]; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Tile +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Width.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Width.lean new file mode 100644 index 0000000000..9d372e5ca6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Child/Width.lean @@ -0,0 +1,513 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.ResetLocation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.HostReset + +/-! +# Reset splits depend on one group and a bounded neighborhood + +Each propagation increases the depth by a positive amount. It never +leaves the current group. An edge with a delay at least the remaining +height can be omitted even when other neighbors can cause splits. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +open Packing Finset + +variable {h a : ℕ} (ha : a ≤ h) (π : Equiv.Perm (Cell h)) (s : Cell a) + +open scoped Classical in +/-- Requires `ancestor ha (π x) = s`. -/ +def InGroup (x : Cell h) : Prop := ancestor ha (π x) = s + +open scoped Classical in +theorem load_eq {l m : Cell h → ℝ} (hl : ∀ x, InGroup ha π s x → l x = m x) + {i : ℕ} (hi : a ≤ i) {z : Cell i} (hz : ancestor hi z = s) : + load l π i z = load m π i z := by + unfold load + split + · refine sum_congr rfl fun x _ => ?_ + split + · rename_i he + exact hl x ((congrArg (ancestor hi) he).trans hz) + · rfl + · rfl + +variable {V W : Type} {N : V → Finset V} {N' : W → Finset W} + {d : V → V → ℕ} {d' : W → W → ℕ} {l : V → Cell h → ℝ} {l' : W → Cell h → ℝ} + +open scoped Classical in +/-- The value specified by `2 < load (l v) π i z`. -/ +abbrev High (l : V → Cell h → ℝ) (π : Equiv.Perm (Cell h)) (v : V) (i : ℕ) (z : Cell i) := + 2 < load (l v) π i z + +open scoped Classical in +theorem high_lt (hl : ∀ v x, l v x ≤ 1) {v : V} {i : ℕ} {z : Cell i} + (hq : High l π v i z) : i < h := by + unfold High load at hq + split at hq + · rename_i hi + exact heavy.lt (hl v) ⟨hi, lt_trans (by norm_num) hq⟩ + · norm_num at hq + +open scoped Classical in +/-- Matching local rows along walks of length strictly less than the +number of remaining bits suffices. -/ +structure Forward (R : ℕ → V → W → Prop) (N : V → Finset V) (N' : W → Finset W) + (d : V → V → ℕ) (d' : W → W → ℕ) (l : V → Cell h → ℝ) (l' : W → Cell h → ℝ) : Prop where + item : ∀ v x, l v x ≤ 1 + values : ∀ k v w, R k v w → k < h - a → ∀ x, InGroup ha π s x → l v x = l' w x + edges : ∀ k v w, R k v w → k < h - a → ∀ t ∈ N v, 2 * d v t < h - a → + 0 < d v t ∧ ∃ t' ∈ N' w, d v t = d' w t' ∧ R (k + 1) t t' + +variable {π s ha} {R : ℕ → V → W → Prop} + +open scoped Classical in +private theorem move {v w : W} {i k : ℕ} (he : w ∈ N' v) (hk : k = d' v w) + (j : Cell (i + 2 * k)) (hg : Spread N' d' (High l' π) w _ j) : + Spread N' d' (High l' π) v i (ancestor (Nat.le_add_right ..) j) := by + subst k + exact .move he j hg + +open scoped Classical in +theorem Forward.spread (hf : Forward ha π s R N N' d d' l l') {v : V} {i : ℕ} {z : Cell i} + (hm : Spread N d (High l π) v i z) : + ∀ {k w}, R k v w → (hi : a + k ≤ i) → ancestor (by omega : a ≤ i) z = s → + Spread N' d' (High l' π) w i z := by + have bound : ∀ v i z, High l π v i z → i < h := fun _ _ _ => high_lt π hf.item + induction hm with + | @start v i z hm => + intro k w hr hi hz + have ht := bound v i z hm + exact .start (show 2 < load (l' w) π i z by + rw [← load_eq ha π s (hf.values k v w hr (by omega)) (by omega) hz] + exact hm) + | @move v t i he z hm ih => + intro k w hr hi hz + have ht := hm.depth bound + obtain ⟨hd, u, hu, heq, hR⟩ := hf.edges k v w hr (by omega) t he (by omega) + exact move hu heq z (ih hR (by omega) hz) + +variable {v : V} {w : W} {base : V → ℕ} {base' : W → ℕ} + +open scoped Classical in +theorem split_eq {R' : ℕ → W → V → Prop} + (hf : Forward ha π s R N N' (fun x y => 8 * d x y) (fun x y => 8 * d' x y) l l') + (hg : Forward ha π s R' N' N (fun x y => 8 * d' x y) (fun x y => 8 * d x y) l' l) + (hr : R 0 v w) (hr' : R' 0 w v) (hb : a ≤ base v) (he : base v = base' w) + (x : Cell h) (hx : InGroup ha π s x) (i : ℕ) (hi : i ≤ h) : + ResetSplit N d base l π v i (ancestor hi (π x)) ↔ + ResetSplit N' d' base' l' π w i (ancestor hi (π x)) := by + unfold ResetSplit + rw [← he] + by_cases ht : i < base v + · exact ⟨fun _ => .inl ht, fun _ => .inl ht⟩ + simp only [ht, false_or] + exact ⟨fun hm => hf.spread hm hr (by omega) hx, fun hm => hg.spread hm hr' (by omega) hx⟩ + +open scoped Classical in +theorem depth_eq {M M' : (i : ℕ) → Cell i → Prop} (x : Cell h) + (he : ∀ i (hi : i ≤ h), M i (ancestor hi x) ↔ M' i (ancestor hi x)) : + leafDepth M x = leafDepth M' x := by + unfold leafDepth + congr! 2 with i + exact forall_congr' (fun hi => not_congr (he i hi.le)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- +# Comparing reset neighborhoods + +At a host the only names needed for switch pins and reserved links +are the positions of its neighbors. The host itself also has a +position, whether or not it is a neighbor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Finset Packing + +variable {V W A A' K : Type} {b d h Y : ℕ} + +open scoped Classical in +/-- Returns `(Fintype.equivFin ↥s ⟨x, hx⟩).val` when `hx : x ∈ s` holds, and `0` otherwise. -/ +def numbering (s : Finset K) (x : K) : ℕ := + if hx : x ∈ s then (Fintype.equivFin ↥s ⟨x, hx⟩).val else 0 + +open scoped Classical in +/-- Embeds `A` into `Fin b where toFun x`. -/ +def rank [Fintype A] (key : A ↪ K) (bound : Fintype.card A ≤ b) : A ↪ Fin b where + toFun x := ⟨numbering (univ.map key) (key x), by + rw [numbering, dite_eq_left (mem_map_of_mem key (mem_univ x))] + exact (Fin.isLt _).trans_le (by simpa using bound)⟩ + inj' x y h := by + have eq := congrArg Fin.val h + dsimp only at eq + rw [numbering, numbering, dite_eq_left (mem_map_of_mem key (mem_univ x)), + dite_eq_left (mem_map_of_mem key (mem_univ y))] at eq + exact key.injective (congrArg Subtype.val ((Fintype.equivFin _).injective (Fin.ext eq))) + +open scoped Classical in +theorem rank_eq [Fintype A] [Fintype A'] {key : A ↪ K} {key' : A' ↪ K} + {bound : Fintype.card A ≤ b} {bound' : Fintype.card A' ≤ b} {x : A} {y : A'} + (sur : ∀ a, ∃ a', key a = key' a') (inv : ∀ a', ∃ a, key' a' = key a) + (he : key x = key' y) : + rank key bound x = rank key' bound' y := by + have hs : univ.map key = univ.map key' := by + ext t + simp only [mem_map, mem_univ, true_and] + constructor + · rintro ⟨a, rfl⟩ + obtain ⟨a', he⟩ := sur a + exact ⟨a', he.symm⟩ + · rintro ⟨a', rfl⟩ + obtain ⟨a, he⟩ := inv a' + exact ⟨a, he.symm⟩ + exact Fin.ext (congrArg₂ numbering hs he) + +open scoped Classical in +/-- The data for the chart construction, including `label`, `self`, `inj`. -/ +structure Chart (C : V → Finset V) (d : ℕ) where + /-- Colors edges joining the base classes before and after the input permutation. -/ + label : V → V → Option (Fin (2 ^ d)) + self : ∀ v, label v v = none + inj : ∀ v, Set.InjOn (label v) (↑(insert v (C v))) + +namespace Chart +variable {C : V → Finset V} {D : W → Finset W} (s : Chart C d) (t : Chart D d) + +open scoped Classical in +/-- The condition `∀ x ∈ C v, ∃ y ∈ D w, s.label v x = t.label w y` on the specified data. -/ +def Maps (v : V) (w : W) : Prop := + ∀ x ∈ C v, ∃ y ∈ D w, s.label v x = t.label w y + +open scoped Classical in +theorem same_root {v x : V} {w y : W} (hx : x ∈ insert v (C v)) (hy : y ∈ insert w (D w)) + (he : s.label v x = t.label w y) : x = v ↔ y = w := by + constructor + · intro h; apply t.inj w hy (mem_insert_self _ _); rw [← he, h, s.self, t.self] + · intro h; apply s.inj v hx (mem_insert_self _ _); rw [he, h, s.self, t.self] + +variable [Fintype V] [Fintype W] {Δ : ℕ} + +open scoped Classical in +theorem near_host {x y : Site V h} (he : y ∈ near C Δ x) : y.1 ∈ insert x.1 (C x.1) := by + rcases (mem_near ..).mp he with rfl | he + · exact mem_insert_self _ _ + · exact mem_insert_of_mem he.1 + +open scoped Classical in +theorem Maps.near {v : V} {w : W} (hs : s.Maps t v w) (x : Schedule.Address h) + (y : Site V h) (hy : y ∈ near C Δ (v, x)) : + ∃ z, (z, y.2) ∈ near D Δ (w, x) ∧ s.label v y.1 = t.label w z := by + rcases (mem_near ..).mp hy with rfl | ⟨hy, h⟩ + · exact ⟨w, near_self _ _ _, (s.self v).trans (t.self w).symm⟩ + obtain ⟨z, hz, he⟩ := hs _ hy + exact ⟨z, (mem_near ..).mpr (.inr ⟨hz, h⟩), he⟩ + +open scoped Classical in +/-- Embeds `↥(terminalNear C Δ Y x)` into `Option (Fin (2 ^ d)) × Schedule.Address h × Fin Y +where toFun y`. -/ +def treeKey (x : Site V h × Fin Y) : + ↥(terminalNear C Δ Y x) ↪ Option (Fin (2 ^ d)) × Schedule.Address h × Fin Y where + toFun y := (s.label x.1.1 y.val.1.1, y.val.1.2, y.val.2) + inj' a b h := by + obtain ⟨hq, ht⟩ := Prod.mk.inj h + have hu := s.inj _ (near_host (mem_product.mp a.property).1) + (near_host (mem_product.mp b.property).1) hq + exact Subtype.ext (Prod.ext (Prod.ext hu (Prod.mk.inj ht).1) (Prod.mk.inj ht).2) + +open scoped Classical in +/-- Embeds `↥(terminalNear C Δ Y x)` into `Fin (terminalWidth Δ Y)`. -/ +def treePin (hΔ : 0 < Δ) (hc : ∀ v, (C v).card ≤ Δ) (x : Site V h × Fin Y) : + ↥(terminalNear C Δ Y x) ↪ Fin (terminalWidth Δ Y) := + rank (s.treeKey x) (by simpa using terminal_card C Δ Y hΔ hc x) + +open scoped Classical in +private theorem treeKey_maps {v : V} {w : W} (hs : s.Maps t v w) + (x : Schedule.Address h) (i : Fin Y) (q : ↥(terminalNear C Δ Y ((v, x), i))) : + ∃ r : ↥(terminalNear D Δ Y ((w, x), i)), s.treeKey ((v, x), i) q = t.treeKey ((w, x), i) r := by + obtain ⟨z, hz, he⟩ := Maps.near s t hs x _ (mem_product.mp q.property).1 + exact ⟨⟨((z, q.val.1.2), q.val.2), mem_product.mpr ⟨hz, mem_univ _⟩⟩, Prod.ext he rfl⟩ + +open scoped Classical in +theorem treePin_eq {v : V} {w : W} (hs : s.Maps t v w) (ht : t.Maps s w v) + (hΔ : 0 < Δ) (hc : ∀ v, (C v).card ≤ Δ) (hd : ∀ w, (D w).card ≤ Δ) + (x : Schedule.Address h) (i : Fin Y) (q : ↥(terminalNear C Δ Y ((v, x), i))) + (r : ↥(terminalNear D Δ Y ((w, x), i))) (he : s.treeKey ((v, x), i) q = t.treeKey ((w, x), + i) r) : + s.treePin hΔ hc _ q = t.treePin hΔ hd _ r := + rank_eq (s.treeKey_maps t hs x i) (t.treeKey_maps s ht x i) he + +end Chart +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +section +/- # Number of child host and neighbor address bits -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +open Packing +variable {F : Type} [Field F] {Y l : ℕ} + +/-- The quantity computed by `n + Nat.clog 2 (resetPositions P Δ)`. -/ +noncomputable def extra (P : Rotor F Y l) (Δ n : ℕ) := n + Nat.clog 2 (resetPositions P Δ) + +/-- Returns `Nat.clog 2 (4 + terminalWidth D Y)` when `full` holds, and `2` otherwise. -/ +noncomputable def width (D Y : ℕ) (full : Bool) := if full then Nat.clog 2 (4 + + terminalWidth D Y) else 2 + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +end + +/- # Common numbering of the output terminals for all reset groups -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Chart +open Packing Finset + +variable {V W : Type} {C : V → Finset V} {D : W → Finset W} {h Y d : ℕ} + +open scoped Classical in +theorem partner_mem (sym : ∀ v w, w ∈ C v → v ∈ C w) (q : CoreContact C) (t : Bool) : + unitEnds q (!t) ∈ C (unitEnds q t) := by + cases t + · exact q.property + · exact sym _ _ q.property + +open scoped Classical in +theorem contact_ext (q r : CoreContact C) (t : Bool) + (hq : unitEnds q t = unitEnds r t) (hr : unitEnds q (!t) = unitEnds r (!t)) : q = r := by + cases t + · exact Subtype.ext (Prod.ext hq hr) + · exact Subtype.ext (Prod.ext hr hq) + +open scoped Classical in +/-- Indexes the address by the coordinates of `Σ i : ℕ, Cell i`. -/ +abbrev Address := Σ i : ℕ, Cell i +open scoped Classical in +/-- Indexes the plug key by the coordinates of `Bool × Option (Fin (2 ^ d)) × Address × ℕ`. -/ +abbrev PlugKey (d : ℕ) := Bool × Option (Fin (2 ^ d)) × Address × ℕ + +open scoped Classical in +/-- Uses `⟨_, z.2⟩` as the representation. -/ +def address {base : V → ℕ} (z : Link base (unitEnds (C := C))) : Address := ⟨_, z.2⟩ + +open scoped Classical in +theorem address_inj {base : V → ℕ} {p q : Link base (unitEnds (C := C))} + (he : p.1 = q.1) (hz : address p = address q) : p = q := Sigma.ext he (Sigma.mk.inj hz).2 + +variable (s : Chart C d) (sym : ∀ v w, w ∈ C v → v ∈ C w) {base : V → ℕ} + (hb : ∀ v, base v ≤ h) (cap : CoreContact C → ℝ) + +open scoped Classical in +/-- Computes the ports by the application `Slots base unitEnds hb cap Y x`. -/ +abbrev Ports (Y : ℕ) (x : Site V h) := Slots base unitEnds hb cap Y x + +open scoped Classical in +/-- Embeds `Ports hb cap Y x` into `PlugKey d where toFun p`. -/ +def plugKey (x : Site V h) : Ports hb cap Y x ↪ PlugKey d where + toFun p := (p.1.val.2, s.label x.1 (unitEnds p.1.val.1.1 (!p.1.val.2)), address p.1.val.1, + p.2.val) + inj' := by + rintro ⟨⟨⟨i, t⟩, hi⟩, a⟩ ⟨⟨⟨j, t'⟩, hj⟩, b⟩ he + change (t, _, _, _) = (t', _, _, _) at he + obtain ⟨rfl, he⟩ := Prod.mk.inj he + obtain ⟨he, h⟩ := Prod.mk.inj he + obtain ⟨h, h'⟩ := Prod.mk.inj h + have hv : unitEnds i.1 t = x.1 := congrArg (fun z : Site V _ => z.1) hi + have hw : unitEnds j.1 t = x.1 := congrArg (fun z : Site V _ => z.1) hj + have hm : unitEnds i.1 (!t) = unitEnds j.1 (!t) := s.inj _ + (mem_insert_of_mem (hv ▸ partner_mem sym i.1 t)) (mem_insert_of_mem (hw ▸ partner_mem sym j.1 + t)) he + have := address_inj (contact_ext _ _ t (hv.trans hw.symm) hm) h + subst j + cases Fin.ext h' + rfl + +open scoped Classical in +/-- Computes the plugs by the application `rank (s.plugKey sym hb cap x) (by simpa using +Fintype.card_le_of_embedding (bound x).some)`. -/ +def plugs [Fintype V] (bound : ∀ x, Nonempty (Ports hb cap Y x ↪ Fin Y)) (x : Site V h) : + Ports hb cap Y x ↪ Fin Y := + rank (s.plugKey sym hb cap x) (by simpa using Fintype.card_le_of_embedding (bound x).some) + +variable (s' : Chart D d) (sym' : ∀ v w, w ∈ D v → v ∈ D w) {base' : W → ℕ} + (hb' : ∀ v, base' v ≤ h) (cap' : CoreContact D → ℝ) + +open scoped Classical in +/-- The condition `∀ b, base (unitEnds q b) = base' (unitEnds r b)` on the specified data. -/ +def Matches (base : V → ℕ) (base' : W → ℕ) (q : CoreContact C) (r : CoreContact D) := + ∀ b, base (unitEnds q b) = base' (unitEnds r b) + +open scoped Classical in +theorem Matches.depth {q : CoreContact C} {r : CoreContact D} (hm : Matches base base' q r) : + contactDepth base unitEnds q = contactDepth base' unitEnds r := + congrArg₂ max (hm false) (hm true) + +open scoped Classical in +private theorem prefix_eq {i j k l : ℕ} (a : Cell k) (b : Cell l) + (hi : i ≤ k) (hj : j ≤ l) (hk : i ≤ h) (hl : j ≤ h) + (e : i = j) (f : (⟨k, a⟩ : Address) = ⟨l, b⟩) : + (⟨⟨i, Nat.lt_succ_of_le hk⟩, ancestor hi a⟩ : Schedule.Address h) = + ⟨⟨j, Nat.lt_succ_of_le hl⟩, ancestor hj b⟩ := by cases e; cases f; rfl + +open scoped Classical in +theorem Matches.site {z : Link base (unitEnds (C := C))} {z' : Link base' (unitEnds (C := D))} + (hm : Matches base base' z.1 z'.1) (ha : address z = address z') (t : Bool) : + (outLeaf base unitEnds hb z t).2 = (outLeaf base' unitEnds hb' z' t).2 := + prefix_eq z.2 z'.2 (le_contactDepth _ _ _ _) (le_contactDepth _ _ _ _) (hb _) (hb' _) (hm t) ha + +open scoped Classical in +/-- The reserves of type `Prop` for the given inputs. -/ +def Reserves (base : V → ℕ) (base' : W → ℕ) (v : V) (w : W) : Prop := + ∀ (q : CoreContact C) t, unitEnds q t = v → ∃ r : CoreContact D, + unitEnds r t = w ∧ s.label v (unitEnds q (!t)) = s'.label w (unitEnds r (!t)) ∧ + Matches base base' q r ∧ cap q = cap' r + +open scoped Classical in +theorem link_exists (z : Link base (unitEnds (C := C))) (c : CoreContact D) + (hm : Matches base base' z.1 c) : + ∃ z' : Link base' unitEnds, z'.1 = c ∧ address z = address z' := by + exact ⟨⟨c, cast (congrArg Cell hm.depth) z.2⟩, rfl, + Sigma.ext hm.depth (cast_heq _ _).symm⟩ + +open scoped Classical in +theorem key_maps {v : V} {w : W} (hs : s.Reserves cap s' cap' base base' v w) + (x : Schedule.Address h) (p : Ports hb cap Y (v, x)) : + ∃ q : Ports hb' cap' Y (w, x), s.plugKey sym hb cap _ p = s'.plugKey sym' hb' cap' _ q := by + obtain ⟨⟨⟨z, t⟩, hz⟩, i⟩ := p + obtain ⟨c, hc, he, hm, hy⟩ := hs z.1 t (congrArg (fun z : Site V h => z.1) hz) + obtain ⟨u, rfl, ha⟩ := link_exists z c hm + have hloc : outLeaf base' unitEnds hb' u t = (w, x) := + Prod.ext hc ((Matches.site hb hb' hm ha t).symm.trans (congrArg Prod.snd hz)) + have hi : i.val < ⌈cap' u.1 * Y / 8⌉₊ := hy ▸ i.isLt + exact ⟨⟨⟨(u, t), hloc⟩, ⟨i.val, hi⟩⟩, Prod.ext rfl (Prod.ext he (Prod.ext ha rfl))⟩ + +open scoped Classical in +theorem plugs_eq [Fintype V] [Fintype W] {v : V} {w : W} + (hs : s.Reserves cap s' cap' base base' v w) (ht : s'.Reserves cap' s cap base' base w v) + (bound : ∀ x, Nonempty (Ports hb cap Y x ↪ Fin Y)) + (bound' : ∀ x, Nonempty (Ports hb' cap' Y x ↪ Fin Y)) + (x : Schedule.Address h) (p : Ports hb cap Y (v, x)) (q : Ports hb' cap' Y (w, x)) + (he : s.plugKey sym hb cap _ p = s'.plugKey sym' hb' cap' _ q) : + s.plugs sym hb cap bound _ p = s'.plugs sym' hb' cap' bound' _ q := + rank_eq (s.key_maps sym hb cap s' sym' hb' cap' hs x) + (s'.key_maps sym' hb' cap' s sym hb cap ht x) he + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Chart +end + +/- +# Testing exceptional contacts with local data + +Capacity depends on one total over all blocks. Given that scalar, +testing a particular base reads only the loads in its own group. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +open Packing + +variable {h a : ℕ} {ha : a ≤ h} {s : Cell a} {π : Equiv.Perm (Cell h)} + +open scoped Classical in +private def overfull (π : Equiv.Perm (Cell h)) (x : Cell h) {i k : ℕ} (hi : i ≤ h) + (hk : i ≤ k) (cap : ℝ) (m : Cell h → ℝ) : Prop := + ∃ z : Cell k, ancestor hk z = ancestor hi (π x) ∧ cap < load m π k z + +open scoped Classical in +private theorem overfull_eq {x : Cell h} (hx : InGroup ha π s x) + {i i' k k' : ℕ} (hi : i ≤ h) (hk : i ≤ k) (hi' : i' ≤ h) (hk' : i' ≤ k') + (hm : a ≤ i) (e : i = i') (f : k = k') + {c c' : ℝ} (hc : c = c') {m m' : Cell h → ℝ} + (hw : ∀ y, InGroup ha π s y → m y = m' y) : + overfull π x hi hk c m ↔ overfull π x hi' hk' c' m' := by + subst i'; subst k'; subst c' + unfold overfull + apply exists_congr + intro z + by_cases hz : ancestor hk z = ancestor hi (π x) + · have hs : ancestor (hm.trans hk) z = s := (congrArg (ancestor hm) hz).trans hx + rw [load_eq ha π s hw (hm.trans hk) hs] + · simp [hz] + +variable {V W A A' : Type} {N : V → Finset V} {N' : W → Finset W} + {d : V → V → ℕ} {d' : W → W → ℕ} {l : V → Cell h → ℝ} {l' : W → Cell h → ℝ} + {v : V} {w : W} {base : V → ℕ} {base' : W → ℕ} + {ends : A → Bool → V} {ends' : A' → Bool → W} + {y : A → Cell h → ℝ} {y' : A' → Cell h → ℝ} {g g' : ℝ} + +open scoped Classical in +private def pressure (N : V → Finset V) (d : V → V → ℕ) (l : V → Cell h → ℝ) + (π : Equiv.Perm (Cell h)) (v : V) {i : ℕ} (hi : i ≤ h) (x : Cell h) : Prop := + Spread N (fun p q => 8 * d p q) (High l π) v i (ancestor hi (π x)) + +open scoped Classical in +private theorem failed_iff (hb : ∀ v, base v ≤ h) (x : Cell h) : + BadBase N d base (contactDepth base ends) (contactEnd base ends) l y g π (prefixSite base hb π + (v, x)) ↔ + pressure N d l π v (hb v) x ∨ ∃ c t, ends c t = v ∧ + overfull π x (hb (ends c t)) (le_contactDepth base ends c t) + (mean (y c) (contactDepth base ends c) + 1 / g) (y c) := by + unfold BadBase prefixSite pressure + apply or_congr_right + constructor + · rintro ⟨⟨c, z⟩, t, hc, he⟩ + have hv : ends c t = v := congrArg Sigma.fst he + subst v + exact ⟨c, t, rfl, z, eq_of_heq (Sigma.mk.inj he).2, hc⟩ + · rintro ⟨c, t, rfl, z, he, hc⟩ + exact ⟨⟨c, z⟩, t, hc, congrArg (Sigma.mk (ends c t)) he⟩ + +open scoped Classical in +/-- Match the incident contacts and their multiplicities at every block +in the group, as well as their aggregate capacities. -/ +def Contacts (ha : a ≤ h) (π : Equiv.Perm (Cell h)) (s : Cell a) + (base : V → ℕ) (ends : A → Bool → V) (y : A → Cell h → ℝ) (cap : A → ℝ) + (base' : W → ℕ) (ends' : A' → Bool → W) (y' : A' → Cell h → ℝ) (cap' : A' → ℝ) + (v : V) (w : W) : Prop := + ∀ c t, ends c t = v → ∃ c', ends' c' t = w ∧ + contactDepth base ends c = contactDepth base' ends' c' ∧ cap c = cap' c' ∧ + ∀ x, InGroup ha π s x → y c x = y' c' x + +open scoped Classical in +private theorem pressure_mono {R : ℕ → V → W → Prop} + (hf : Forward ha π s R N N' (fun v w => 8 * d v w) (fun v w => 8 * d' v w) l l') + (hr : R 0 v w) {i i' : ℕ} (hi : i ≤ h) (hi' : i' ≤ h) (ho : a ≤ i) (he : i = i') + {x : Cell h} (hx : InGroup ha π s x) (p : pressure N d l π v hi x) : + pressure N' d' l' π w hi' x := by + subst i' + exact hf.spread p hr ho hx + +open scoped Classical in +theorem Forward.failed {R : ℕ → V → W → Prop} + (hf : Forward ha π s R N N' (fun v w => 8 * d v w) (fun v w => 8 * d' v w) l l') + (hr : R 0 v w) (ho : a ≤ base v) (he : base v = base' w) (hb : ∀ v, base v ≤ h) + (hb' : ∀ w, base' w ≤ h) (hc : Contacts ha π s base ends y + (fun c => mean (y c) (contactDepth base ends c) + 1 / g) base' ends' y' + (fun c' => mean (y' c') (contactDepth base' ends' c') + 1 / g') v w) + {x : Cell h} (hx : InGroup ha π s x) : + BadBase N d base (contactDepth base ends) (contactEnd base ends) l y g π (prefixSite base hb π + (v, x)) → + BadBase N' d' base' (contactDepth base' ends') (contactEnd base' ends') l' y' g' π + (prefixSite base' hb' π (w, x)) := by + rw [failed_iff, failed_iff] + rintro (hp|⟨c, t, rfl, hc'⟩) + · exact .inl (pressure_mono hf hr _ _ ho he hx hp) + · obtain ⟨c', rfl, he', hcap, hy⟩ := hc c t rfl + exact .inr ⟨c', t, rfl, (overfull_eq hx _ _ _ _ ho he he' hcap hy).mp hc'⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Move.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Move.lean new file mode 100644 index 0000000000..3f011bf821 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Move.lean @@ -0,0 +1,779 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Prefix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.TetherHost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Repost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Hop + +/-! # The local product at a rotor and its gathering trees -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +open Spectral.Packet + +variable {F A : Type} [Field F] [Fintype A] {Y w n : ℕ} + (R : Rotor F Y w) (p q : A → Fin Y) (σ : Fin n → Equiv.Perm (Fin Y)) + (lane : A → Fin n × Fin w) (inj : Function.Injective (fun a => (p a, lane a))) + (route : ∀ a, σ (lane a).1 (p a) = q a) + +theorem treeRule_entry (b : Bool) (v : R.Hardware) (x y : A → Bool) (u : PathEdge w A → Bool) : + (R.treeRule p lane b).entry () v x y u = + (Rule.path F (fun k a => R.walk b (p a) (lane a).2 k) (Nat.clog 2 w + 1)).entry () v x y u := + rfl + +/-- At a hardware port the path variable on the first edge gives +the unique allowed value of the intermediate bit. -/ +theorem deployRule_entry (v : R.Hardware) (x y : A → Bool) (u : R.Supply A n → Bool) : + let s := fun e => u (.inl (0, e)) + let t := fun e => u (.inr (.inr (0, e))) + (R.deployRule p q σ lane inj route).entry () v x y u = + (R.treeRule p lane false).entry () v s x (u ∘ Sum.inl) * + ((R.layerRule p q σ lane inj route).entry () v s t (u ∘ Sum.inr ∘ Sum.inl) * + (R.treeRule q lane true).entry () v t y (u ∘ Sum.inr ∘ Sum.inr)) := by + intro s t + let f := R.treeRule p lane false + let g := R.layerRule p q σ lane inj route + let h := R.treeRule q lane true + have hs := Rule.series_eval f.reverse (g.series h) v x y u s (by + intro a ha _ e he + exact Rule.path_head (K := F) (fun j e => R.walk false (p e) (lane e).2 j) v a x _ ha e he) + have ht := Rule.series_eval g h v s y (u ∘ Sum.inr) t (by + intro a _ ha e he + exact Rule.path_head (K := F) (fun j e => R.walk true (q e) (lane e).2 j) v a y _ ha e he) + rw [ht] at hs + exact hs + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +end + +/- # Reindexing a layer of a programmed rotor -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule +variable {F S A B E : Type} [Field F] [Fintype S] [Fintype A] [Fintype B] + +open scoped Classical in +/-- Returns `x ha.choose` when `ha : ∃ b, i b = a` holds, and `false` otherwise. -/ +def fill (i : A → E) (x : A → Bool) (a : E) := + if ha : ∃ b, i b = a then x ha.choose else false + +open scoped Classical in +theorem fill_eval (i : A → E) (x : A → Bool) (hi : Function.Injective i) (a : A) : + fill i x (i a) = x a := by + have ht := show ∃ b, i b = i a from ⟨a, rfl⟩ + simp only [fill, dite_eq_left ht, hi ht.choose_spec] + +open scoped Classical in +theorem fill_map (i : A → E) (j : B → E) (hi : Function.Injective i) + (e : A ≃ B) (he : ∀ a, i a = j (e a)) (x : A → Bool) (y : B → Bool) + (hx : ∀ a, x a = y (e a)) : fill i x = fill j y := by + have hj : Function.Injective j := by + intro b c hh + obtain ⟨a, rfl⟩ := e.surjective b + obtain ⟨d, rfl⟩ := e.surjective c + rw [← he, ← he, hi.eq_iff] at hh + rw [hh] + funext v + by_cases ht : ∃ a, i a = v + · obtain ⟨a, rfl⟩ := ht + rw [fill_eval i x hi, he, fill_eval j y hj, hx] + have ht' : ¬∃ b, j b = v := by + rintro ⟨b, h⟩ + exact ht ⟨e.symm b, by rw [he, e.apply_symm_apply, h]⟩ + simp only [fill, ht, ht', dite_false] + +open scoped Classical in +theorem path_map (n : ℕ) (P : ℕ → A → S) (Q : ℕ → B → S) (e : A ≃ B) + (hp : ∀ k a, P k a = Q k (e a)) (v : S) (x y : A → Bool) (z : Fin n × A → Bool) + (x' y' : B → Bool) (z' : Fin n × B → Bool) + (hx : ∀ a, x a = x' (e a)) (hy : ∀ a, y a = y' (e a)) (hz : ∀ i a, z (i, a) = z' (i, e a)) : + (Rule.path F P n).entry () v x y z = (Rule.path F Q n).entry () v x' y' z' := by + have left (i : Fin (n + 1)) a : + Fin.cons (α := fun _ => A → Bool) x (Function.curry z) i a = + Fin.cons (α := fun _ => B → Bool) x' (Function.curry z') i (e a) := by + induction i using Fin.cases <;> simp [hx, hz] + have right (i : Fin (n + 1)) a : + Fin.snoc (α := fun _ => A → Bool) (Function.curry z) y i a = + Fin.snoc (α := fun _ => B → Bool) (Function.curry z') y' i (e a) := by + induction i using Fin.lastCases <;> simp [hy, hz] + simp only [path_entry, left, right, hp] + congr! 2 with i + constructor + · intro h b; obtain ⟨a, rfl⟩ := e.surjective b; exact h a + · exact fun h a => h _ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +open Spectral.Packet +variable {F A B : Type} [Field F] [Fintype A] [Fintype B] {Y w n : ℕ} (R : Rotor F Y w) + +open scoped Classical in +private def plug (p : A → Fin Y) (lane : A → Fin n × Fin w) (a : A) : Σ _ : Fin n, Fin Y × Fin w := + ⟨(lane a).1, p a, (lane a).2⟩ + +variable (p q : A → Fin Y) (p' q' : B → Fin Y) (σ : Fin n → Equiv.Perm (Fin Y)) + (l : A → Fin n × Fin w) (l' : B → Fin n × Fin w) + (hi : Function.Injective (fun a => (p a, l a))) (hr : ∀ a, σ (l a).1 (p a) = q a) + (hi' : Function.Injective (fun a => (p' a, l' a))) (hr' : ∀ a, σ (l' a).1 (p' a) = q' a) + +open scoped Classical in +theorem layer_map (e : A ≃ B) (hp : ∀ a, p a = p' (e a)) (hl : ∀ a, l a = l' (e a)) + (v : R.Hardware) (x y : A → Bool) (x' y' : B → Bool) (z : R.LayerEdge n → Bool) + (hx : ∀ a, x a = x' (e a)) (hy : ∀ a, y a = y' (e a)) : + (R.layerRule p q σ l hi hr).entry () v x y z = + (R.layerRule p' q' σ l' hi' hr').entry () v x' y' z := by + have he : Function.Injective (plug p l) := by + intro a b hab + simp only [plug, Sigma.mk.inj_iff, heq_eq_eq, Prod.mk.injEq] at hab + exact hi (Prod.ext hab.2.1 (Prod.ext hab.1 hab.2.2)) + have ht : ∀ a, plug p l a = plug p' l' (e a) := by intro a; simp only [plug, hp, hl] + have hx' := Rule.fill_map _ _ he e ht x x' hx + have hy' := Rule.fill_map _ _ he e ht y y' hy + let f := Rule.parallelOne (fun t : Fin n => (R.packet (σ t)).rule) + let g := f.place (fun t => (Sum.inl t.2 : R.Hardware)) + change g.entry () v (Rule.fill (plug p l) x) (Rule.fill (plug p l) y) z = + g.entry () v (Rule.fill (plug p' l') x') (Rule.fill (plug p' l') y') z + rw [hx', hy'] + +open scoped Classical in +/-- In the case `.inl (j, a)`, this construction gives `.inl (j, e a)`. -/ +def supplyMap {m : ℕ} (e : A ≃ B) (hn : n = m) : R.Supply A n → R.Supply B m + | .inl (j, a) => .inl (j, e a) + | .inr (.inl ⟨i, b⟩) => .inr (.inl ⟨i.cast hn, b⟩) + | .inr (.inr (j, a)) => .inr (.inr (j, e a)) + +open scoped Classical in +theorem deploy_map {m : ℕ} (σ' : Fin m → Equiv.Perm (Fin Y)) (l' : B → Fin m × Fin w) + (hi' : Function.Injective (fun a => (p' a, l' a))) (hr' : ∀ a, σ' (l' a).1 (p' a) = q' a) + (e : A ≃ B) (hn : n = m) (hp : ∀ a, p a = p' (e a)) (hq : ∀ a, q a = q' (e a)) + (hl : ∀ a, ((l a).1.cast hn, (l a).2) = l' (e a)) (hc : ∀ i, σ i = σ' (i.cast hn)) + (v : R.Hardware) (x y : A → Bool) (z : R.Supply A n → Bool) (x' y' : B → Bool) + (z' : R.Supply B m → Bool) + (hx : ∀ a, R.root false (p a) = v → x a = x' (e a)) + (hy : ∀ a, R.root true (q a) = v → y a = y' (e a)) + (hz : ∀ i, (R.supply p q l i).1 = v ∨ (R.supply p q l i).2 = v → + z i = z' (R.supplyMap e hn i)) : + (R.deployRule p q σ l hi hr).entry () v x y z = + (R.deployRule p' q' σ' l' hi' hr').entry () v x' y' z' := by + subst m + have hσ : σ = σ' := funext hc + subst σ' + have hl' : ∀ a, l a = l' (e a) := hl + have hh := (R.deployRule p q σ l hi hr).local' () v x y z (x' ∘ e) (y' ∘ e) + (z' ∘ R.supplyMap e rfl) hx hy hz + rw [hh, deployRule_entry, deployRule_entry] + apply congrArg₂ (·*·) + · rw [treeRule_entry, treeRule_entry] + apply Rule.path_map _ _ _ e + · intro k a; simp only [hp, hl'] + · intro; rfl + · intro; rfl + · intro _ _; rfl + apply congrArg₂ (·*·) + · exact R.layer_map p q p' q' σ l l' hi hr hi' hr' e hp hl' v _ _ _ _ _ (fun _ => rfl) (fun _ + => rfl) + rw [treeRule_entry, treeRule_entry] + apply Rule.path_map _ _ _ e + · intro k a; simp only [hq, hl'] + · intro; rfl + · intro; rfl + · intro _ _; rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +end + +/- # Evaluating one site's contribution in a parallel delivery -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule + +open scoped Classical in +theorem select_entry_equiv {K S A B E : Type} [Field K] [Fintype S] [Fintype A] [Fintype B] + [Fintype E] {D : B → S × S} {W : E → S × S} (h : Rule K D (fun _ : Unit => W)) + (i : A ≃ B) (v : S) (x y : A → Bool) (z : E → Bool) : + (h.select i.toEmbedding).entry () v x y z = h.entry () v (x ∘ i.symm) (y ∘ i.symm) z := by + have he (x : A → Bool) : fill i x = x ∘ i.symm := by + funext b + obtain ⟨a, rfl⟩ := i.surjective b + simp only [fill_eval i x i.injective, Function.comp_apply, Equiv.symm_apply_apply] + rw [← he, ← he] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Delivery +open Spectral.Packet Finset + +variable {P U X W F : Type} [Fintype P] [Field F] [Fintype X] [Fintype U] + {leaf : P → X} {point : U → Bool → P} {good : U → Prop} + {edge : U → W} {outLeaf : W → Bool → X} {cap : W → ℝ} {Y w : ℕ} + {out : ∀ x, Port outLeaf cap Y x ↪ Fin Y} {l : P → ℝ} {u : ℝ} + (d : Delivery leaf point good edge outLeaf cap Y w out l u) (R : Rotor F Y w) + +open scoped Classical in +theorem deploy_entry (v : X) (t : R.Hardware) (x y : {e // good e} → Bool) (z : d.Wires R → Bool) : + (d.deployRule R).entry () (v, t) x y z = + (R.deployRule (d.inputAt v) (d.outputAt v) (d.config v) (d.lane v) (d.input v) + (d.routes v)).entry () t (fun e => if e.val.2 then y e.val.1 else x e.val.1) + (fun e => z (.inr e.val.1)) (fun b => z (.inl ⟨v, b⟩)) := by + let s : Finset (Σ _ : X, R.Hardware) := univ.filter fun b => (b.1, b.2) = (v, t) + have hs : s = {⟨v, t⟩} := by ext ⟨i, j⟩; simp [s] + dsimp only [s] at hs + simp only [deployRule, Rule.joinOutputs, Rule.select_entry_equiv, Rule.place, hs, prod_singleton] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Delivery +end + +/- # Closure rules for compressed reset factors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule +open Assembly.History.Reset + +variable {F S E U : Type} [Field F] [Fintype S] [Fintype E] [Fintype U] + {D : E → S × S} {W : U → S × S} + +open Classical in +/-- Every way of plugging named bits or zero into this site gives +a product of trivalent factors. -/ +def Simple (h : Rule F D (fun _ : Unit => W)) : Prop := + ∀ (J : Type) [Fintype J] (v : S) (x y : E → Option J) (z : U → Option J), + (fun a => h.entry () v (readBit J a ∘ x) (readBit J a ∘ y) (readBit J a ∘ z)) ∈ simple F J + +namespace Simple +variable {h : Rule F D (fun _ : Unit => W)} + +open Classical in +theorem congr {D' W'} (hh : Simple h) (hd : D = D') (hw : W = W') : + Simple (h.congr hd (congrArg (fun t _ => t) hw)) := by + subst D' W' + exact hh + +open Classical in +theorem place {T : Type} [Fintype T] (hh : Simple h) (g : S → T) : Simple (h.place g) := by + intro J _ v x y z + exact prod_simple (Finset.univ.filter (fun w => g w = v)) _ (fun w _ => hh J w x y z) + +open Classical in +theorem select {B : Type} [Fintype B] (hh : Simple h) (e : B ↪ E) : Simple (h.select e) := by + intro J _ v x y z + let fill (p : B → Option J) (i : E) := if hi : ∃ b, e b = i then p hi.choose else none + have ext (a : J → Bool) (p : B → Option J) : + (fun i => if hi : ∃ b, e b = i then readBit J a (p hi.choose) else false) = + readBit J a ∘ fill p := by + funext i + unfold Function.comp fill + split_ifs <;> rfl + convert hh J v (fill x) (fill y) z using 1 + funext a + rw [← ext, ← ext] + rfl + +open Classical in +theorem partition (G : E → Prop) [DecidablePred G] {Z : Type} [Fintype Z] {V : Z → S × S} + {hf : Rule F (fun e : {i // G i} => D e.val) (fun _ : Unit => W)} + {hg : Rule F (fun e : {i // ¬G i} => D e.val) (fun _ : Unit => V)} + (f : Simple hf) (g : Simple hg) : Simple (Rule.partition G D hf hg) := by + intro J _ v x y z + exact (simple F J).mul_mem (f J v (x ∘ Subtype.val) (y ∘ Subtype.val) (z ∘ Sum.inl)) + (g J v (x ∘ Subtype.val) (y ∘ Subtype.val) (z ∘ Sum.inr)) + +open Classical in +theorem parallel {K : Type} [Fintype K] {S E U : K → Type} + [∀ k, Fintype (S k)] [∀ k, Fintype (E k)] [∀ k, Fintype (U k)] + {D : (k : K) → E k → S k × S k} {W : (k : K) → U k → S k × S k} + {h : ∀ k, Rule F (D k) (fun _ : Unit => W k)} (hs : ∀ k, Simple (h k)) : + Simple (Rule.parallelOne h) := by + rintro J _ ⟨k, v⟩ x y z + exact hs k J v (x ∘ Sigma.mk k) (y ∘ Sigma.mk k) (z ∘ Sigma.mk k) + +open Classical in +theorem joinOutputs {a b : E × Bool → S} + {h : Rule F (fun e => (a e, b e)) (fun _ : Unit => W)} (hh : Simple h) : + Simple h.joinOutputs := by + intro J _ v x y z + let p (e : E × Bool) := if e.2 then y e.1 else x e.1 + convert hh J v p (fun e => z (.inr e.1)) (z ∘ Sum.inl) using 1 + funext a + have he : readBit J a ∘ p = fun e => if e.2 then readBit J a (y e.1) else readBit J a (x e.1) + := by + funext e + simp only [Function.comp_apply, p] + split_ifs <;> rfl + rw [he] + rfl + +end Simple + +open Classical in +theorem path_simple (D : ℕ → E → S) (n : ℕ) : (Rule.path F D n).Simple := by + intro J _ v x y z + let a : Fin (n + 1) → E → Option J := Fin.cons x (Function.curry z) + let b : Fin (n + 1) → E → Option J := Fin.snoc (Function.curry z) y + let t := Finset.univ.filter (fun p : Fin (n + 1) × E => D p.1.val p.2 = v) + have h := prod_simple t _ (fun p _ => check_simple (F := F) (a p.1 p.2) (b p.1 p.2)) + convert h using 1 + funext g + rw [path_entry, Finset.prod_ite_zero, Finset.prod_const_one] + have ha (i : Fin (n + 1)) e : + Fin.cons (α := fun _ => E → Bool) (readBit J g ∘ x) (Function.curry (readBit J g ∘ z)) i e = + readBit J g (a i e) := by induction i using Fin.cases <;> simp [a] + have hb (i : Fin (n + 1)) e : + Fin.snoc (α := fun _ => E → Bool) (Function.curry (readBit J g ∘ z)) (readBit J g ∘ y) i e = + readBit J g (b i e) := by induction i using Fin.lastCases <;> simp [b] + simp only [ha, hb, t, Finset.mem_filter, Finset.mem_univ, true_and, Prod.forall] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule +end + +/- # Trivalent factors of a deployed rotor -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +open Assembly.History.Reset Spectral.Packet +variable {F A : Type} [Field F] [Fintype A] {Y w n : ℕ} + (R : Rotor F Y w) + +open Classical in +theorem packet_simple (σ : Equiv.Perm (Fin Y)) : (R.packet σ).rule.Simple := by + intro J _ v x y z + let f : RotorEnd Y w R.E → Option J + | .inl (false, i, j) => x (i, j) + | .inl (true, i, j) => y (σ.symm i, j) + | .inr (.inl i) => z i + | .inr (.inr i) => z i + apply local_table _ (fun i : {q // R.pos q = v} => f i.val) (R.degree v) + intro a b he + apply (R.packet σ).rule.local' + · rintro ⟨i, j⟩ h + exact he ⟨.inl (false, i, j), h⟩ + · rintro ⟨i, j⟩ h + simpa only [f, Function.comp_apply, Equiv.symm_apply_apply] using he ⟨.inl (true, σ i, j), h⟩ + · rintro e (h|h) + · exact he ⟨.inr (.inl e), h⟩ + · exact he ⟨.inr (.inr e), h⟩ + +variable (p q : A → Fin Y) (σ : Fin n → Equiv.Perm (Fin Y)) + (lane : A → Fin n × Fin w) (inj : Function.Injective (fun a => (p a, lane a))) + (route : ∀ a, σ (lane a).1 (p a) = q a) + +open Classical in +theorem layer_simple : (R.layerRule p q σ lane inj route).Simple := by + unfold layerRule + apply Rule.Simple.congr + · apply Rule.Simple.place + apply Rule.Simple.select + exact Rule.Simple.parallel (fun t => R.packet_simple (σ t)) + · rfl + +open Classical in +theorem tree_simple (b : Bool) : (R.treeRule p lane b).Simple := by + intro J _ v x y z + simp only [treeRule_entry] + exact Rule.path_simple _ _ J v x y z + +open Classical in +theorem deploy_simple : (R.deployRule p q σ lane inj route).Simple := by + intro J _ v x y z + let s := fun e => z (.inl (0, e)) + let t := fun e => z (.inr (.inr (0, e))) + have h₁ := R.tree_simple p lane false J v s x (z ∘ Sum.inl) + have h₂ := R.layer_simple p q σ lane inj route J v s t (z ∘ Sum.inr ∘ Sum.inl) + have h₃ := R.tree_simple q lane true J v t y (z ∘ Sum.inr ∘ Sum.inr) + convert (simple F J).mul_mem h₁ ((simple F J).mul_mem h₂ h₃) using 1 + funext a + exact R.deployRule_entry p q σ lane inj route v _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +end + +/- # The load pays for visible spans, hidden bundles and inherited histories -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Coloring Packing Finset + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + (v : Cell a × q.vertex) + +open scoped Classical in +theorem loaded_bound : push q.owner (Function.uncurry G.load) v ≤ 89 * B' := + (le_add_of_nonneg_right (by positivity)).trans (q.load v) + +open scoped Classical in +theorem hidden_bound : (Fintype.card (Hidden q v) : ℝ) * u ≤ 89 * B' := by + let f := fun e => Prod.map q.owner q.owner (G.pair e) + have hk : Fintype.card (Hidden q v) ≤ degree f v + degree q.supply v := by + rw [Fintype.card_subtype, card_eq_sum_ones, sum_filter, degree_sum, degree_sum, + Fintype.sum_sum_type, Fintype.sum_sum_type, ← add_assoc, ← sum_add_distrib] + apply Nat.add_le_add + · apply sum_le_sum + intro e _ + apply le_of_eq + simp only [ends, arityCost, f, HostNet.pair, Prod.map, Prod.mk.injEq, and_self] + congr + · apply sum_le_sum + intro e _ + by_cases he : q.supply e = (v, v) <;> simp [ends, he, arityCost] + have hold : (degree f v : ℝ) * u ≤ push q.owner (Function.uncurry G.load) v := by + unfold f + rw [degree_map, Nat.cast_sum, sum_mul] + apply sum_le_sum + intro j _ + by_cases hj : q.owner j = v + · simp only [ite_eq_left hj] + exact (le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load _ _) + · simp [hj] + refine (mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hk) (Nat.cast_nonneg _)).trans ?_ + rw [Nat.cast_add, add_mul] + exact (add_le_add_left hold _).trans (q.load v) + +variable (hu : ∀ j, u ≤ p.toPresentation.borderWidth j) + +include hu in +open scoped Classical in +theorem width_floor (j : Port p q v) : u ≤ width p q v j := by + rcases j with ⟨j|j, _⟩|j + · exact hu j + · exact le_rfl + · exact le_rfl + +include hu in +open scoped Classical in +theorem visible_bound : (Fintype.card (Visible p q v) : ℝ) * u ≤ 89 * B' := by + have hk : Fintype.card (Visible p q v) * u ≤ (q.contract G.units).arity v := by + have eq := Fintype.card_congr (visibleBits p q v) + simp only [Fintype.card_sigma, Fintype.card_fin, Diagram.Port, Fintype.card_sum, card_slots] + at eq + have hl (j : Visible p q v) : u ≤ visibleWidth p q j.val := + width_floor p q v hu (.inl j) + have hh := sum_le_sum (s := univ) (fun j _ => hl j) + rw [sum_const, card_univ, Nat.nsmul_eq_mul] at hh + exact hh.trans_eq eq + rw [← Nat.cast_mul] + apply (Nat.cast_le.mpr hk).trans (q.arity_contract G.units ?_ v) + intro i + exact (le_add_of_nonneg_right (by positivity)).trans (G.core_le_load _ _) + +include p in +open scoped Classical in +private theorem live_cost (c : Live q v → ℝ) (mass : G.V × Cell h → ℝ) + (hm : ∀ i, 0 ≤ mass i) (hc : ∀ w, c w ≤ mass (G.units.place w.val)) : + (∑ w, c w) ≤ push q.owner mass v := by + let f (t : G.V × Cell h) := if q.owner t = v then mass t else 0 + let e : Live q v ↪ G.V × Cell h := ⟨fun i => G.units.place i.val, by + intro i j hij + change G.units.place i.val = G.units.place j.val at hij + apply Subtype.ext + apply p.vertex.injective + rw [p.vertex_eq, p.vertex_eq, hij]⟩ + have hh : push q.owner mass v = ∑ i, f i := by + apply sum_congr rfl + intro i _ + unfold f; congr + rw [hh] + calc + _ ≤ ∑ w, f (e w) := sum_le_sum fun w _ => (hc w).trans_eq (ite_eq_left w.property.2).symm + _ ≤ _ := by + rw [← sum_map univ e] + apply sum_le_sum_of_subset_of_nonneg (subset_univ _) + intro i _ _ + unfold f + split <;> first | exact hm i | exact le_rfl + +open scoped Classical in +/-- The sum of `Dense.used (o (oldLabel p w.val).1).val` indexed by `w : Live q v`. -/ +def inherited (o : B S.ℓ ≃ B S.ℓ) := ∑ w : Live q v, Dense.used (o (oldLabel p w.val).1).val + +open scoped Classical in +theorem inherited_le (o : B S.ℓ ≃ B S.ℓ) (mass : G.V × Cell h → ℝ) (hm : ∀ i, 0 ≤ mass i) + (hc : ∀ w, 0 < G.diagram.arity w → (Dense.used (o (oldLabel p w).1).val : ℝ) + ≤ mass (G.units.place w)) : + (inherited p q v o : ℝ) ≤ push q.owner mass v := by + rw [inherited, Nat.cast_sum] + exact live_cost p q v _ mass hm fun w => hc w.val w.property.1 + +include hu in +open scoped Classical in +private theorem live_floor (w : Live q v) : u ≤ G.diagram.arity w.val := by + have eq := Fintype.card_congr (p.pin w.val) + simp only [Diagram.Port, Fintype.card_sum, card_slots] at eq + change G.diagram.arity w.val = Fintype.card (S.LocalPin r (p.vertex w.val)) at eq + obtain ⟨⟨j, t⟩⟩ := Fintype.card_pos_iff.mp (w.property.1.trans_eq eq) + let m := oldMap p q v w.val w.property.2 + have hl : u ≤ S.width r (p.vertex w.val, j) := + (width_floor p q v hu _).trans_eq (m.size j t.pos) + rw [eq] + simp only [Scheme.LocalPin, Fintype.card_sigma] + simp only [Fintype.card_fin] + exact hl.trans (single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ j)) + +include hu in +open scoped Classical in +theorem live_bound : (Fintype.card (Live q v) : ℝ) * u ≤ 89 * B' := by + have hload (w : Live q v) : (u : ℝ) ≤ Function.uncurry G.load (G.units.place w.val) := by + let t := G.units.place w.val + have hv : (G.diagram.arity w.val : ℝ) ≤ push G.units.place (fun i => (G.diagram.arity i : ℝ)) t + := by + unfold push + refine le_trans ?_ (single_le_sum (fun i _ => by split_ifs <;> positivity) (mem_univ w.val)) + simp [t] + change _ ≤ G.load t.1 t.2 + rw [G.load_eq t] + exact ((Nat.cast_le.mpr (live_floor p q v hu w)).trans hv).trans + ((le_add_of_nonneg_right (mul_nonneg L.pos.le (push_nonneg _ _ L.nonneg _))).trans + (le_add_of_nonneg_right (mul_nonneg G.rate_nonneg (Nat.cast_nonneg _)))) + have hc := live_cost p q v (fun _ => (u : ℝ)) (Function.uncurry G.load) + (fun t => G.load_nonneg t.1 t.2) hload + rw [sum_const, card_univ, nsmul_eq_mul] at hc + exact hc.trans (loaded_bound q v) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Encoding station references and collecting the new factors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + (v : Cell a × q.vertex) {e : ℕ} + (slot : Port p q v → Addr e) (o : B S.ℓ ≃ B S.ℓ) + +open scoped Classical in +/-- Evaluates `g (slot i) j.val` at the input `i j`. -/ +def access (g : Addr e → ℕ → Bool) : Tape p q v := fun i j => g (slot i) j.val + +open scoped Classical in +private def instruction (i : Live q v) : Control S e := + (true, (oldLabel p i.val).2, fun j => + if hj : 0 < (original S (oldLabel p i.val)).width j then + slot ((oldMap p q v i.val i.property.2).slot j hj) + else .inl 0) + +open scoped Classical in +private theorem instruction_eq (i : Live q v) (g : Addr e → ℕ → Bool) : + prior o (instruction p q v slot i) (o (oldLabel p i.val).1) g = + previous p q v (access p q v slot g) i := by + unfold prior + rw [Equiv.symm_apply_apply] + unfold instruction previous + dsimp only [original, access] + rw [ite_eq_left rfl] + apply congrArg + funext j t + erw [dite_eq_left t.pos] + rfl + +open scoped Classical in +theorem previous_code (n : Live q v ↪ B e) : + ∃ c : B e → Control S e, ∃ t : B e → B S.ℓ, Dense.cost t = inherited p q v o ∧ + ∀ g : Addr e → ℕ → Bool, + (∏ j, prior o (c j) (t j) g) = ∏ i, previous p q v (access p q v slot g) i := by + let c := Function.extend n (instruction p q v slot) (fun _ => (false, 0, fun _ => Sum.inl 0)) + let t := Function.extend n (fun i => o (oldLabel p i.val).1) (fun _ => 0) + refine ⟨c, t, ?_, ?_⟩ + · symm + refine Fintype.sum_of_injective n n.injective _ _ ?_ ?_ + · intro j hj + simp only [t, Function.extend_apply' _ _ _ hj] + exact Dense.used_zero + · intro j + simp only [t, n.injective.extend_apply] + · intro g + symm + refine Fintype.prod_of_injective n n.injective _ _ ?_ ?_ + · intro j hj + simp only [c, Function.extend_apply' _ _ _ hj] + rfl + · intro j + simp only [c, t, n.injective.extend_apply] + exact (instruction_eq p q v slot o j g).symm + +open scoped Classical in +private def sourceRef (t : Bool) (i : G.E) : Option (Addr e) := + if h : demandSite q i t = v then some (slot (demand p q v i t h)) else none + +open scoped Classical in +private def wireRef (i : q.wire) : Option (Addr e) := + if h : supplySite q i false = v then some (slot (supply p q v i false h)) + else if h : supplySite q i true = v then some (slot (supply p q v i true h)) else none + +open scoped Classical in +theorem created_code (hs : q.rule.Simple) : ∃ c : Tables F (Addr e), + ∀ g : Addr e → ℕ → Bool, + (∏ j : Fin u, evaluate F (Addr e) c (fun i => g i j.val)) = + created p q v (access p q v slot g) := by + obtain ⟨c, hc⟩ := hs (Addr e) v (sourceRef p q v slot false) + (sourceRef p q v slot true) (wireRef p q v slot) + refine ⟨c, fun g => Finset.prod_congr rfl ?_⟩ + intro j _ + let y (i : Addr e) := g i j.val + have src (t : Bool) : readBit _ y ∘ sourceRef p q v slot t = + inBits p q v (access p q v slot g) t j := by + funext i + unfold Function.comp sourceRef inBits + split_ifs <;> rfl + have dest : readBit _ y ∘ wireRef p q v slot = + outBits p q v (access p q v slot g) j := by + funext i + unfold Function.comp wireRef outBits + split_ifs <;> rfl + exact (congrFun hc y).trans (by rw [src, src, dest]) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- +# Existence of a short recipe + +The order of the hidden wires and of the previous stations is arbitrary. +Only the lengths of the occupied old labels contribute to the variable +part of a recipe. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + (v : Cell a × q.vertex) {e : ℕ} + (seat : Visible p q v ↪ B e) (o : B S.ℓ ≃ B S.ℓ) + +open scoped Classical in +theorem describe (hs : q.rule.Simple) + (hn : ∀ w, G.diagram.arity w = 0 → ∀ z, Transcript.sample (G.diagram.table w) z = 1) + (hi : Fintype.card (Hidden q v) ≤ 2 ^ e) (hl : Fintype.card (Live q v) ≤ 2 ^ e) : + ∃ a : Recipe S e, run o u a = localEval p q v seat ∧ Dense.cost a.2 = inherited p q v o := by + let J := Fintype.equivFin (Hidden q v) + let slot : Port p q v → Addr e := Sum.map seat (fun i => (J i).castLE hi) + let b := J.prodCongr (Equiv.refl (Fin u)) + have hread (x : B e → ℕ → Bool) (z : Fin (Fintype.card (Hidden q v)) × Fin u → Bool) : + access p q v slot (fetch x z) = tape p q v seat x (z ∘ b) := by + funext j t + cases j with + | inl j => rfl + | inr j => + change fetch x z (.inr ((J j).castLE hi)) t.val = z (J j, t) + have ht : (J j).val < Fintype.card (Hidden q v) ∧ t.val < u := ⟨(J j).isLt, t.isLt⟩ + simp only [fetch, Fin.val_castLE, dite_eq_left ht] + rfl + let n := (Fintype.equivFin (Live q v)).toEmbedding.trans (Fin.castLEEmb hl) + obtain ⟨c, t, ht, hc⟩ := previous_code p q v slot o n + obtain ⟨d, hd⟩ := created_code p q v slot hs + refine ⟨((⟨_, Nat.lt_succ_of_le hi⟩, c, d), t), ?_, ht⟩ + funext x + rw [eval_formula p q v hn] + unfold run + refine Fintype.sum_equiv (b.symm.arrowCongr (Equiv.refl Bool)) _ _ ?_ + intro z + change (∏ j, prior o (c j) (t j) (fetch x z)) * + (∏ j : Fin u, evaluate F (Addr e) d (fun i => fetch x z i j.val)) = _ + rw [hc, hd, hread] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Recovering the predecessor of each exterior span after a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + +open BatchDescent.Trail + +open scoped Classical in +/-- In the case `.inl j`, this construction gives `some (0, stub (p.vertex j.val.1, j.val.2))`. -/ +def facePointer : Face p q → Option (B 0 × Stub S) + | .inl j => some (0, stub (p.vertex j.val.1, j.val.2)) + | .inr _ => none + +namespace Allocation +variable {p q} {U : Scheme F} (A : Allocation p q U) (parent : B U.m → B S.m) + +open scoped Classical in +/-- A reset never imports an exterior span from a neighbor of the +parent host. All the predecessor pointers therefore have hop zero. -/ +def move : Move S U 0 where + nav i _ := parent i + read := Function.extend A.span (facePointer p q) (fun _ => none) + +open scoped Classical in +@[simp] theorem read_span (j : Face p q) : + (A.move parent).read (A.span j) = facePointer p q j := + A.span_injective.extend_apply (facePointer p q) (fun _ => none) j + +open scoped Classical in +theorem read_idle (s : U.Span) (hs : s ∉ Set.range A.span) : (A.move parent).read s = none := + Function.extend_apply' (facePointer p q) (fun _ => none) s hs + +open scoped Classical in +private theorem previous_span (hp : ∀ w, parent (A.host w) = p.host (q.origin w)) + (j : p.toPresentation.BorderSpan) : + (A.move parent).previous (A.span (.inl j)) = some (p.vertex j.val.1, j.val.2) := by + rw [Move.previous, read_span] + change some ((parent (A.host (q.owner (G.units.place j.val.1)).2), + (p.vertex j.val.1).2), j.val.2) = _ + rw [hp, q.origin_owner, p.vertex_eq] + +open scoped Classical in +theorem move_agrees {out : U.format.obj} (l : A.Lengths out) (H : A.Agrees l) + (parent : B U.m → B S.m) (hp : ∀ w, parent (A.host w) = p.host (q.origin w)) : + (A.move parent).Agrees p.toPresentation (A.posting l H).toPresentation := by + have he (j : p.toPresentation.BorderBit) : + ((A.posting l H).toPresentation.boundary (p.toPresentation.exteriorBits j)).val = + ⟨A.span (.inl j.1), j.2.cast (l.used (.inl j.1)).symm⟩ := by + rw [Scheme.Presentation.boundary_val] + exact A.exposed_pin l H j + constructor + · intro i + obtain ⟨j, rfl⟩ := p.toPresentation.exteriorBits.surjective i + rw [he, Scheme.Presentation.boundary_val, p.toPresentation.border_pin] + exact ⟨A.previous_span parent hp _, l.used (.inl j.1), rfl⟩ + · intro s hs + by_cases h : s ∈ Set.range A.span + · obtain ⟨j|j, rfl⟩ := h + · let t : p.toPresentation.BorderBit := ⟨j, ⟨0, j.property.1⟩⟩ + exact ⟨p.toPresentation.exteriorBits t, congrArg Sigma.fst (he t)⟩ + · rw [read_span] at hs + cases hs + · rw [A.read_idle parent s h] at hs + cases hs + +end Allocation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Ports/Correspondence.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Ports/Correspondence.lean new file mode 100644 index 0000000000..50fc0b8d1d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Ports/Correspondence.lean @@ -0,0 +1,940 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Raw.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Repost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Move +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Routes + +/-! # Transporting the equality checks of exceptional paths -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Spectral.Packet + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U V : Setup S h u a Δ D Y w B') (R : Rotor F Y w) (fit : U.Fits R c) +local notation "L" => terminalWidth Δ Y +local notation "m" => Detour.steps L + +open scoped Classical in +theorem old_start (e : U.G.E) : + U.oldPlace R fit e false = (U.Z.group (U.G.ix e), U.stop R e 0) := by + unfold stop + rw [Detour.Switch.path_zero] + rfl + +open scoped Classical in +theorem old_end (e : U.G.E) : + U.oldPlace R fit e true = (U.Z.group (U.G.ix e), U.stop R e m) := by + unfold stop + rw [Detour.Switch.path_last] + rfl + +variable {U V R fit} {fit' : V.Fits R c} {σ : Cell a} {v : U.G.V} {z : V.G.V} + {loc : Coord R h a Δ} {x : U.Value R} {y : V.Value R} + (al : Alignment R fit fit' σ v z loc x y) {e : U.Z.Exceptional} {f : V.Z.Exceptional} + +include al in +open scoped Classical in +theorem Alignment.joins (i : Fin (m + 1)) + (he : (U.Z.group (U.G.ix e.val), U.stop R e.val i.val) = (σ, v, loc)) + (hf : (V.Z.group (V.G.ix f.val), V.stop R f.val i.val) = (σ, z, loc)) + (hn : ∀ b, endName U.post e.val b = endName V.post f.val b) : + U.joins R x i e ↔ V.joins R y i f := by + have wire (j : Fin m) (b : Bool) (hj : step j.val b = i.val) : + x (.inr (.inr (j, e))) = y (.inr (.inr (j, f))) := by + apply al.wire _ _ b + · rw [detour_place, hj]; exact he + · rw [detour_place, hj]; exact hf + · simp only [rawKey, hn] + unfold Setup.joins Rule.through + apply Iff.of_eq + apply congrArg₂ Eq + · induction i using Fin.cases with + | zero => + simp only [Fin.cons_zero] + exact al.old _ _ false ((U.old_start R fit e.val).trans he) ((V.old_start R fit' f.val).trans + hf) (hn false) + | succ j => + simp only [Fin.cons_succ] + exact wire j true rfl + · induction i using Fin.lastCases with + | last => + simp only [Fin.snoc_last] + exact al.old _ _ true ((U.old_end R fit e.val).trans he) ((V.old_end R fit' f.val).trans hf) + (hn true) + | cast j => + simp only [Fin.snoc_castSucc] + exact wire j false rfl + +variable {Q : Relation U V} {k n : ℕ} (p : Region U V σ Q n) (hk : k + (h - a) + 3 + ≤ n) (hr : Q k v z) +include al p hk hr + +open scoped Classical in +private theorem pull_detours (hy : V.detours R σ z loc y) : U.detours R σ v loc x := by + intro i e he + let t := Detour.Switch.side L i.val + have hv : Scheme.side U.G e.val t = v := (U.stop_side R e.val i).symm.trans (Prod.mk.inj + (Prod.mk.inj he).2).1 + obtain ⟨g, hg, r⟩ := p.unit_pair (k := k) (by omega) e.val t z (Prod.mk.inj he).1 (hv ▸ hr) + let f : V.Z.Exceptional := ⟨g, mt r.good.mpr e.property⟩ + have hf : (V.Z.group (V.G.ix f.val), V.stop R f.val i.val) = (σ, z, loc) := + Prod.ext (r.group' p) (Prod.ext ((V.stop_side R g i).trans hg) + ((r.stop p (by omega) R i).symm.trans (Prod.mk.inj (Prod.mk.inj he).2).2)) + exact (al.joins i he hf r.name).mpr (hy i f hf) + +open scoped Classical in +theorem Alignment.detours : U.detours R σ v loc x ↔ V.detours R σ z loc y := + ⟨pull_detours al.symm p.symm hk hr, pull_detours al p hk hr⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Corresponding ports of two programmed rotor copies -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Spectral.Packet + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U V : Setup S h u a Δ D Y w B') (R : Rotor F Y w) (fit : U.Fits R c) + {σ : Cell a} {v : U.G.V} {z : V.G.V} {loc : Coord R h a Δ} + {q : Schedule.Address h} {t : R.Hardware} + +open scoped Classical in +theorem old_selected (e : U.End v q) (hs : selected R σ loc q t) + (he : R.root false (U.delivery.inputAt (v, q) e) = t) : + U.oldPlace R fit e.val.1.val e.val.2 = (σ, v, loc) := by + rw [old_place, e.property, U.end_root] + exact Prod.ext ((U.end_group v q e).trans hs.1) (Prod.ext rfl (he ▸ hs.2)) + +open scoped Classical in +theorem direct_selected (e : U.End v q) (hs : selected R σ loc q t) + (he : R.root true (U.delivery.outputAt (v, q) e) = t) : + U.rawPlace R fit (.inl (.inr e.val.1)) e.val.2 = (σ, v, loc) := by + have aux {x : Site U.G.V h} (p : GoodEnd U.Z.leaf (demands U.G).point U.Z.good x) : + U.delivery.outputAt x p = (U.delivery.plug p.val.1 p.val.2).2 := by + obtain ⟨⟨j, b⟩, rfl⟩ := p + rfl + rw [direct_place, e.property, U.end_root, ← aux e, he] + exact Prod.ext ((U.end_group v q e).trans hs.1) (Prod.ext rfl hs.2) + +open scoped Classical in +theorem inside_selected (e : U.delivery.LocalWires R (v, q)) (b : Bool) (hs : selected R σ loc q t) + (he : cond b (U.localSupply R (v, q) e).2 (U.localSupply R (v, q) e).1 = t) : + U.rawPlace R fit (.inl (.inl ⟨(v, q), e⟩)) b = (σ, v, loc) := by + rw [local_place] + unfold localSupply at he + rw [he] + exact Prod.ext hs.1 (Prod.ext rfl hs.2) + +variable {U V R} + +open scoped Classical in +/-- The data for the program construction, including `side`, `name`, `input`, `output`, +`layers`. -/ +structure Program (v : U.G.V) (z : V.G.V) (q : Schedule.Address h) + (e : U.End v q ≃ V.End z q) : Prop where + side : ∀ i, i.val.2 = (e i).val.2 + name : ∀ i, endName U.post i.val.1.val i.val.2 = endName V.post (e i).val.1.val (e i).val.2 + input : ∀ i, U.delivery.inputAt (v, q) i = V.delivery.inputAt (z, q) (e i) + output : ∀ i, U.delivery.outputAt (v, q) i = V.delivery.outputAt (z, q) (e i) + layers : U.delivery.layers (v, q) = V.delivery.layers (z, q) + lane : ∀ i, ((U.delivery.lane (v, q) i).1.cast layers, (U.delivery.lane (v, q) i).2) = + V.delivery.lane (z, q) (e i) + config : ∀ j, U.delivery.config (v, q) j = V.delivery.config (z, q) (j.cast layers) + +open scoped Classical in +theorem Agree.program (p : Agree U V σ v z) (hq : Site.group a (v, q) = σ) : + ∃ e, Program (U := U) (V := V) v z q e := by + obtain ⟨m, e, hm⟩ := p.matching hq + have name (i : U.End v q) : + endName U.post i.val.1.val i.val.2 = endName V.post (e i).val.1.val (e i).val.2 + := (hm.contact i).symm + have he (i : U.End v q) : i.val.2 = (e i).val.2 ∧ + Related U V v z i.val.2 i.val.1.val (e i).val.1.val := by + obtain ⟨j, hj, hr⟩ := p.end_map hq i + have eq : j = e i := endName_inj V.post V.hu V.Z (z, q) (by + change endName V.post j.val.1.val j.val.2 = _ + rw [← hj, ← hr.name] + exact name i) + subst j + exact ⟨hj, hr⟩ + refine ⟨e, fun i => (he i).1, name, fun i => p.input hq (he i).2.ix, fun i => (hm.output i).symm, + p.layers hq, ?_, + fun j => p.config hq _ _ rfl⟩ + intro i + obtain ⟨hl, ht⟩ := Prod.mk.inj (p.lane hq (he i).1 (he i).2) + exact Prod.ext (Fin.ext hl) ht + +open scoped Classical in +theorem Program.wire {e : U.End v q ≃ V.End z q} (p : Program v z q e) (R : Rotor F Y w) + (i : U.delivery.LocalWires R (v, q)) : + U.localKey R (v, q) i = V.localKey R (z, q) (R.supplyMap e p.layers i) ∧ + U.localSupply R (v, q) i = V.localSupply R (z, q) (R.supplyMap e p.layers i) := by + have hl (i : U.End v q) := (Prod.mk.inj (p.lane i)).2 + rcases i with ⟨j, b⟩|⟨j, b⟩|⟨j, b⟩ + · simp only [Rotor.supplyMap, localKey, p.name, localSupply, Rotor.supply, Sum.elim_inl, + Rotor.pathEdge, p.input, hl, and_self] + · exact ⟨rfl, rfl⟩ + · simp only [Rotor.supplyMap, localKey, p.name, localSupply, Rotor.supply, Sum.elim_inr, + Rotor.pathEdge, p.output, hl, and_self] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Corresponding stations implement the same reset packet -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Finset +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] {U V : Setup S h u a Δ D Y w B'} {R : Rotor F Y w} + {fit : U.Fits R c} {fit' : V.Fits R c} {σ : Cell a} {v : U.G.V} {z : V.G.V} + {loc : Coord R h a Δ} {x : U.Value R} {y : V.Value R} + (al : Alignment R fit fit' σ v z loc x y) + +open scoped Classical in +private theorem pair_read {T : Type} (f : T × Bool → Bool) (i : T) (b : Bool) : + (if b then f (i, true) else f (i, false)) = f (i, b) := by cases b <;> rfl + +variable (U R) (q : Schedule.Address h) + +open scoped Classical in +private def rotorIn (v : U.G.V) (x : U.Value R) (i : U.End v q) := + if i.val.2 then x (.inl (i.val.1.val, true)) else x (.inl (i.val.1.val, false)) + +open scoped Classical in +private def rotorOut (v : U.G.V) (x : U.Value R) (i : U.End v q) := + x (.inr (.inl (.inr i.val.1))) + +open scoped Classical in +private def rotorRead (v : U.G.V) (x : U.Value R) (i : U.delivery.LocalWires R (v, q)) := + x (.inr (.inl (.inl ⟨(v, q), i⟩))) + +-- Use the same enumeration of incident ends as the abstract delivery. +open scoped Classical in +/-- Decidable equality on sites for the finite correspondence calculations. -/ +local instance {V : Type} {h : ℕ} : DecidableEq (Site V h) := Classical.decEq _ + +open scoped Classical in +private theorem rotor_eval (v : U.G.V) (x : U.Value R) (t : R.Hardware) : + U.rotorWeight R x ((v, q), t) = + (R.deployRule (U.delivery.inputAt (v, q)) (U.delivery.outputAt (v, q)) + (U.delivery.config (v, q)) (U.delivery.lane (v, q)) (U.delivery.input (v, + q)) (U.delivery.routes (v, q))).entry () t + (U.rotorIn R q v x) (U.rotorOut R q v x) (U.rotorRead R q v x) := by + unfold rotorWeight rotorIn rotorOut rotorRead + rw [Delivery.deploy_entry] + +variable {U R q} {t : R.Hardware} {e : U.End v q ≃ V.End z q} + (prog : Program v z q e) (hs : selected R σ loc q t) + +include al prog hs in +open scoped Classical in +private theorem input_eq (i : U.End v q) (hi : R.root false (U.delivery.inputAt (v, q) i) = t) : + U.rotorIn R q v x i = V.rotorIn R q z y (e i) := by + unfold rotorIn + have h := U.old_selected R fit i hs hi + have h' := V.old_selected R fit' (e i) hs ((congrArg (R.root false) (prog.input i)).symm.trans hi) + have hn := prog.name i + rw [← prog.side i] at h' hn + have eq := al.old _ _ _ h h' hn + have a := pair_read (x ∘ Sum.inl) i.val.1.val i.val.2 + have b := pair_read (y ∘ Sum.inl) (e i).val.1.val (e i).val.2 + rw [prog.side i] at eq + rw [prog.side i] at a + simp only [prog.side i] + exact a.trans (eq.trans b.symm) + +include al prog hs in +open scoped Classical in +private theorem output_eq (i : U.End v q) (hi : R.root true (U.delivery.outputAt (v, q) i) = t) : + U.rotorOut R q v x i = V.rotorOut R q z y (e i) := by + have h := U.direct_selected R fit i hs hi + have h' := V.direct_selected R fit' (e i) hs ((congrArg (R.root true) (prog.output i)).symm.trans + hi) + have hn := prog.name i + rw [← prog.side i] at h' hn + exact al.wire _ _ _ h h' (congrArg RawId.direct hn) + +include al prog hs in +open scoped Classical in +private theorem inside_eq (i : U.delivery.LocalWires R (v, q)) + (hi : (U.localSupply R (v, q) i).1 = t ∨ (U.localSupply R (v, q) i).2 = t) : + U.rotorRead R q v x i = V.rotorRead R q z y (R.supplyMap e prog.layers i) := by + obtain ⟨hkey, heq⟩ := prog.wire R i + have hs' : ∃ b : Bool, cond b (U.localSupply R (v, q) i).2 (U.localSupply R (v, q) i).1 = t := + hi.elim (fun h => ⟨false, h⟩) (fun h => ⟨true, h⟩) + obtain ⟨b, hb⟩ := hs' + exact al.wire _ _ _ (U.inside_selected R fit i b hs hb) + (V.inside_selected R fit' (R.supplyMap e prog.layers i) b hs (heq ▸ hb)) hkey + +include al in +open scoped Classical in +theorem Alignment.rotor (p : Agree U V σ v z) {q : Schedule.Address h} {t : R.Hardware} + (hs : selected R σ loc q t) : + U.rotorWeight R x ((v, q), t) = V.rotorWeight R y ((z, q), t) := by + obtain ⟨e, prog⟩ := p.program (q := q) hs.1 + rw [rotor_eval, rotor_eval] + exact R.deploy_map _ _ _ _ _ _ _ _ _ _ _ _ e prog.layers prog.input prog.output + prog.lane prog.config t _ _ _ _ _ _ + (input_eq al prog hs) (output_eq al prog hs) (inside_eq al prog hs) + +include al in +open scoped Classical in +theorem Alignment.main (p : Agree U V σ v z) : + U.mainValue R σ v loc x = V.mainValue R σ z loc y := by + unfold mainValue + refine prod_congr rfl fun q _ => prod_congr rfl fun t _ => ?_ + split + · exact al.rotor p ‹_› + · rfl + +include al in +open scoped Classical in +theorem Alignment.value {Q : Relation U V} {k n : ℕ} (p : Region U V σ Q n) + (hk : k + (h - a) + 3 ≤ n) (hr : Q k v z) : + U.valueAt R fit σ v loc x = V.valueAt R fit' σ z loc y := by + simp only [value_eq, al.main (p.toSurvey.agree (by omega) hr), al.detours p hk hr] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Correspondence of both endpoints of each reset supply wire -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c c' : ℝ} + [NeZero Y] [NeZero w] {U V : Setup S h u a Δ D Y w B'} + (R : Rotor F Y w) (fit : U.Fits R c) (fit' : V.Fits R c') + (Q : Relation U V) (σ : Cell a) (k : ℕ) + +open scoped Classical in +/-- A matched supply uses the same kind at both endpoints. Inside wires share an address. +Direct and detoured wires carry a unit pairing, and detoured wires share the detour step. -/ +inductive RawMode : U.Raw R → V.Raw R → Prop + | inside (x : Schedule.Address h) (v z) + (e : U.delivery.LocalWires R (v, x)) (f : V.delivery.LocalWires R (z, x)) : + RawMode (.inl (.inl ⟨(v, x), e⟩)) (.inl (.inl ⟨(z, x), f⟩)) + | direct (e : {i // U.Z.good i}) (f : {j // V.Z.good j}) (r : UnitPair Q σ k e.val f.val) : + RawMode (.inl (.inr e)) (.inl (.inr f)) + | detour (j : Fin (Detour.steps (terminalWidth Δ Y))) (e : U.Z.Exceptional) (f : V.Z.Exceptional) + (r : UnitPair Q σ k e.val f.val) : RawMode (.inr (j, e)) (.inr (j, f)) + +open scoped Classical in +/-- The data for the raw pair construction, including `mode`, `key`, `group`, `group'`, `host`. -/ +structure RawPair (e : U.Raw R) (f : V.Raw R) : Prop where + mode : RawMode R Q σ k e f + key : ∀ t, U.rawKey R e t = V.rawKey R f t + group : ∀ t, (U.rawPlace R fit e t).1 = σ + group' : ∀ t, (V.rawPlace R fit' f t).1 = σ + host : ∀ t, Q k (U.rawPlace R fit e t).2.1 (V.rawPlace R fit' f t).2.1 + coord : ∀ t, (U.rawPlace R fit e t).2.2 = (V.rawPlace R fit' f t).2.2 + +variable {Q σ k} {n : ℕ} (p : Region U V σ Q n) + +include p in +open scoped Classical in +theorem RawPair.direct (hk : k + (h - a) + 2 ≤ n) + (e : {i // U.Z.good i}) (f : {j // V.Z.good j}) (r : UnitPair Q σ k e.val f.val) : + RawPair R fit fit' Q σ k (.inl (.inr e)) (.inl (.inr f)) := by + refine ⟨.direct _ _ r, fun t => congrArg RawId.direct (r.name t), ?_, ?_, ?_, ?_⟩ + · intro t; rw [direct_place]; exact r.group + · intro t; rw [direct_place]; exact r.group' p + · intro t; rw [direct_place, direct_place]; exact r.hosts t + · intro t + rw [direct_place, direct_place] + exact congrArg Sum.inl (Prod.ext (r.drop p hk t) + (congrArg (R.root true) (r.plug p hk e.property f.property t))) + +include p in +open scoped Classical in +theorem RawPair.detour (hk : k + (h - a) + 2 ≤ n) + (j : Fin (Detour.steps (terminalWidth Δ Y))) (e : U.Z.Exceptional) (f : V.Z.Exceptional) + (r : UnitPair Q σ k e.val f.val) : + RawPair R fit fit' Q σ k (.inr (j, e)) (.inr (j, f)) := by + refine ⟨.detour _ _ _ r, fun t => congrArg (RawId.detour j.val) (r.name _), ?_, ?_, ?_, ?_⟩ + · intro t; rw [detour_place]; exact r.group + · intro t; rw [detour_place]; exact r.group' p + · intro t; simp only [detour_place, stop_side]; exact r.hosts _ + · intro t; rw [detour_place, detour_place]; exact r.stop p hk R _ + +include p in +open scoped Classical in +/-- A hit at one endpoint identifies a supply at both endpoints. +The peer can use one extra step in the neighborhood relation. -/ +theorem Region.raw (hk : k + (h - a) + 3 ≤ n) (e : U.Raw R) (t : Bool) (z : V.G.V) + (hg : (U.rawPlace R fit e t).1 = σ) (hv : Q k (U.rawPlace R fit e t).2.1 z) : + ∃ f, (V.rawPlace R fit' f t).2.1 = z ∧ RawPair R fit fit' Q σ (k + 1) e f := by + rcases e with (⟨⟨v, x⟩, b⟩|j)|⟨i, j⟩ + · simp only [local_place] at hg hv + obtain ⟨d, hd, hl⟩ := (p.toSurvey.agree (by omega) hv).local_wire hg R b + refine ⟨.inl (.inl ⟨(z, x), d⟩), by rw [local_place], .inside .., fun _ => hd, ?_, ?_, ?_, ?_⟩ + · intro t; rw [local_place]; exact hg + · intro t; rw [local_place]; exact hg + · intro t; rw [local_place, local_place]; exact p.widen (by omega) hv + · intro t + simp only [local_place] + unfold localSupply at hl + rw [hl] + rfl + · simp only [direct_place] at hg hv + obtain ⟨f, hf, hr⟩ := p.unit_pair (by omega) j.val t z hg hv + let g := Subtype.mk f (hr.good.mp j.2) + exact ⟨.inl (.inr g), by rw [direct_place]; exact hf, + RawPair.direct R fit fit' p (by omega) j g hr⟩ + · simp only [detour_place, stop_side] at hg hv + obtain ⟨f, hf, hr⟩ := p.unit_pair (by omega) j.val _ z hg hv + let g : V.Z.Exceptional := ⟨f, mt hr.good.mpr j.2⟩ + exact ⟨.inr (i, g), by simp only [detour_place, stop_side]; exact hf, + RawPair.detour R fit fit' p (by omega) i j g hr⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Visible and hidden span names at a reset station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + (fit : U.Fits R c) + +open scoped Classical in +/-- Indexes the at by the coordinates of `Cell a × (U.result R fit).vertex`. -/ +abbrev At := Cell a × (U.result R fit).vertex +open scoped Classical in +/-- The value specified by `(U.place R fit).symm (σ, v, loc)`. -/ +abbrev station (σ : Cell a) (v : U.G.V) (loc : Coord R h a Δ) := + (U.place R fit).symm (σ, v, loc) + +open scoped Classical in +/-- The port id used in the `Setup` construction. -/ +inductive PortId (R : Rotor F Y w) (h : ℕ) where + | border (b : Cell h) (j : ℕ) + | demand (t : Bool) (name : ℕ) + | line (visible t : Bool) (id : RawId R h) + +variable (v : U.At R fit) +local notation "Dlv" => U.result R fit + +open scoped Classical in +/-- In the case `.inl ⟨.inl q, _⟩`, this construction gives `.border (U.G.units.place q.val.1).2 +q.val.2.val`. -/ +def portKey : Reset.Port U.post Dlv v → PortId R h + | .inl ⟨.inl q, _⟩ => .border (U.G.units.place q.val.1).2 q.val.2.val + | .inl ⟨.inr (e, t), _⟩ => .line true t (U.rawKey R e.val t) + | .inr ⟨.inl e, _⟩ => .demand false (endName U.post e false) + | .inr ⟨.inr (.inl e), _⟩ => .demand true (endName U.post e true) + | .inr ⟨.inr (.inr e), _⟩ => .line false false (U.rawKey R e false) + +open scoped Classical in +theorem exterior_key (j : U.post.toPresentation.BorderSpan) (hj) : + U.portKey R fit v (exterior U.post Dlv v j hj) = + .border (U.G.units.place j.val.1).2 j.val.2.val := rfl + +open scoped Classical in +theorem demand_key (e : U.G.E) (t : Bool) (he) : + U.portKey R fit v (demand U.post Dlv v e t he) = .demand t (endName U.post e t) := by + cases t <;> rfl + +open scoped Classical in +theorem supply_key (e : U.Raw R) (t : Bool) (he) : + U.portKey R fit v (supply U.post Dlv v e t he) = + if ((Dlv).supply e).1 = ((Dlv).supply e).2 then .line false false (U.rawKey R e false) + else .line true t (U.rawKey R e t) := by + unfold supply + split <;> rfl + +open scoped Classical in +theorem supply_place (e : U.Raw R) (t : Bool) : + U.place R fit (supplySite Dlv e t) = U.rawPlace R fit e t := rfl + +open scoped Classical in +theorem demand_place (e : U.G.E) (t : Bool) : + U.place R fit (demandSite Dlv e t) = U.oldPlace R fit e t := by rw [oldPlace, point_eq] + +open scoped Classical in +theorem owner_place (p : U.G.V × Cell h) : + U.place R fit ((Dlv).owner p) = (U.Z.group p.2, p.1, + .inl (((U.Z.leaf p).drop a).2, R.root false (U.delivery.terminal p))) := rfl + +open scoped Classical in +private theorem unique_border {j k : U.post.toPresentation.BorderSpan} + (he : (Dlv).owner (U.G.units.place j.val.1) = (Dlv).owner (U.G.units.place k.val.1)) + (hb : (U.G.units.place j.val.1).2 = (U.G.units.place k.val.1).2) (hs : j.val.2.val + = k.val.2.val) : + j = k := by + have hp := congrArg (U.place R fit) he + rw [owner_place, owner_place] at hp + have hplace : U.G.units.place j.val.1 = U.G.units.place k.val.1 := + Prod.ext (congrArg (fun p => p.2.1) hp) hb + apply Subtype.ext + refine Prod.ext ?_ (Fin.ext hs) + apply U.post.vertex.injective + rw [U.post.vertex_eq, U.post.vertex_eq, hplace] + +open scoped Classical in +private theorem unique_demand {e f : U.G.E} (t : Bool) + (he : demandSite Dlv e t = demandSite Dlv f t) (hh : endName U.post e t + = endName U.post f t) : e = f := by + apply U.end_inj_at _ hh + have hp := congrArg (U.place R fit) he + simp only [demand_place, old_place] at hp + exact congrArg (fun p => p.2.1) hp + +open scoped Classical in +theorem portKey_injective : Function.Injective (U.portKey R fit v) := by + rintro (⟨j|⟨e, t⟩, he⟩ | ⟨e|e|e, he⟩) (⟨k|⟨f, b⟩, hf⟩ | ⟨f|f|f, hf⟩) hh <;> + simp only [portKey, PortId.border.injEq, PortId.demand.injEq, PortId.line.injEq, + reduceCtorEq, eq_self, true_and, false_and] at hh + · have : j = k := unique_border U R fit (he.trans hf.symm) hh.1 hh.2 + subst k; rfl + · obtain ⟨rfl, hk⟩ := hh + have hp : U.rawPlace R fit e.val t = U.rawPlace R fit f.val t := + congrArg (U.place R fit) (he.trans hf.symm) + have : e = f := Subtype.ext (U.raw_inj R fit (congrArg (fun p => p.2.1) hp) hk) + subst f; rfl + · have : e = f := unique_demand U R fit false (congrArg Prod.fst (he.trans hf.symm)) hh + subst f; rfl + · have : e = f := unique_demand U R fit true (congrArg Prod.fst (he.trans hf.symm)) hh + subst f; rfl + · have hp : U.rawPlace R fit e false = U.rawPlace R fit f false := + congrArg (fun p => U.place R fit p.1) (he.trans hf.symm) + have : e = f := U.raw_inj R fit (congrArg (fun p => p.2.1) hp) hh + subst f; rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Resident wires and their peer endpoints -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] {U V : Setup S h u a Δ D Y w B'} {R : Rotor F Y w} + {fit : U.Fits R c} {fit' : V.Fits R c} {σ : Cell a} {v : U.G.V} {z : V.G.V} + {loc : Coord R h a Δ} {Q : Relation U V} {k n : ℕ} {t : Bool} + +open scoped Classical in +theorem RawPair.loop {e : U.Raw R} {f : V.Raw R} (r : RawPair R fit fit' Q σ k e f) + (p : Region U V σ Q n) (hk : k ≤ n) : + ((U.result R fit).supply e).1 = ((U.result R fit).supply e).2 ↔ + ((V.result R fit').supply f).1 = ((V.result R fit').supply f).2 := by + have eqn : U.rawPlace R fit e false = U.rawPlace R fit e true ↔ + V.rawPlace R fit' f false = V.rawPlace R fit' f true := by + have ha := p.same (p.widen hk (r.host false)) (p.widen hk (r.host true)) + simp only [Prod.ext_iff, r.group, r.group', r.coord, ha] + simpa only [rawPlace, Bool.cond_false, Bool.cond_true, Equiv.apply_eq_iff_eq] using eqn + +open scoped Classical in +theorem old_at {e : U.G.E} : demandSite (U.result R fit) e t = U.station R fit σ v loc ↔ + U.oldPlace R fit e t = (σ, v, loc) := by + rw [station, Equiv.eq_symm_apply, demand_place] + +open scoped Classical in +theorem raw_at {e : U.Raw R} : supplySite (U.result R fit) e t = U.station R fit σ v loc ↔ + U.rawPlace R fit e t = (σ, v, loc) := (U.place R fit).eq_symm_apply + +variable (p : Region U V σ Q n) (hk : k + (h - a) + 3 ≤ n) (hr : Q k v z) +include p hk hr + +open scoped Classical in +theorem Region.old_here {e : U.G.E} (he : U.oldPlace R fit e t = (σ, v, loc)) : + ∃ f, V.oldPlace R fit' f t = (σ, z, loc) ∧ UnitPair Q σ (k + 1) e f := by + simp only [old_place, Prod.mk.injEq] at he + obtain ⟨f, hf, r⟩ := p.unit_pair (by omega) e t z he.1 (he.2.1 ▸ hr) + refine ⟨f, ?_, r⟩ + simp only [old_place, Prod.mk.injEq] + refine ⟨r.group' p, hf, ?_⟩ + rw [← he.2.2] + exact congrArg Sum.inl (Prod.ext (r.drop p (by omega) t).symm + (congrArg (R.root false) (r.terminal p (by omega) t).symm)) + +open scoped Classical in +theorem Region.raw_here {e : U.Raw R} (he : U.rawPlace R fit e t = (σ, v, loc)) : + ∃ f, V.rawPlace R fit' f t = (σ, z, loc) ∧ RawPair R fit fit' Q σ (k + 1) e f := by + obtain ⟨f, hf, r⟩ := p.raw R fit fit' hk e t z (by rw [he]) (by rwa [he]) + exact ⟨f, Prod.ext (r.group' t) (Prod.ext hf ((r.coord t).symm.trans (by rw [he]))), r⟩ + +open scoped Classical in +theorem Region.raw_pair {e : U.Raw R} {f : V.Raw R} + (he : U.rawPlace R fit e t = (σ, v, loc)) (hf : V.rawPlace R fit' f t = (σ, z, loc)) + (hn : U.rawKey R e t = V.rawKey R f t) : RawPair R fit fit' Q σ (k + 1) e f := by + obtain ⟨j, hj, r⟩ := p.raw_here (fit' := fit') hk hr he + have : j = f := V.raw_inj R fit' (by rw [hj, hf]) ((r.key t).symm.trans hn) + rwa [this] at r + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The scheduled reset has a short local factorization -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Spectral.Packet + +namespace Delivery +variable {P U X W F : Type} [Fintype P] [Field F] [Fintype X] [Fintype U] + {leaf : P → X} {point : U → Bool → P} {good : U → Prop} + {edge : U → W} {outLeaf : W → Bool → X} {cap : W → ℝ} {Y w : ℕ} + {out : ∀ x, Port outLeaf cap Y x ↪ Fin Y} {l : P → ℝ} {u : ℝ} + (d : Delivery leaf point good edge outLeaf cap Y w out l u) (R : Rotor F Y w) + +open Classical in +theorem deploy_simple : (d.deployRule R).Simple := by + unfold deployRule + apply Rule.Simple.joinOutputs + apply Rule.Simple.select + apply Rule.Simple.place + apply Rule.Simple.parallel + intro x + exact R.deploy_simple _ _ _ _ _ _ + +end Delivery + +namespace Schedule +variable {V A U F : Type} [Fintype V] [Fintype U] [Field F] {h a k Y w L : ℕ} + {T : Demands V A U h} {N : V → Finset V} {d : V → V → ℕ} + {l : V → Cell h → ℝ} {u g ε : ℝ} + (Z : Schedule T N d a k l u g ε) {o : Z.Plugs Y} + (D : Z.Dispatch o w) (R : Rotor F Y w) + (sw : Detour.Switch (Site V (h - a) × Fin Y) L) + (ok : ∀ i : U, Z.terminal D (T.point i true) ∈ sw.near (Z.terminal D (T.point i false))) + +open Classical in +theorem rule_simple : (Z.rule D R sw ok).Simple := by + unfold rule + apply Rule.Simple.partition + · apply Rule.Simple.congr + · exact (D.deploy_simple R).place _ + · rfl + · apply Rule.Simple.place + unfold Detour.Switch.rule + apply Rule.Simple.congr + · exact Rule.path_simple _ _ + · rfl + +end Schedule +end MatrixMultiplicationAllFields.MatrixExponent.Packing + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + +theorem result_simple (fits : U.Fits R c) : (U.result R fits).rule.Simple := + U.Z.rule_simple U.delivery R _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Serializing the outgoing spans and local tensor after a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Allocation + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} {p : S.Posting r G} + {B' W : ℝ} {Hcap D : ℕ} + {q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D} + {m d h' e ℓ cap : ℕ} {len : B ℓ → ℕ} {decode : B cap → (B e → ℕ → Bool) → F} + +local notation "U" => scheme m d h' e ℓ cap len decode +local notation "Host" => endHost (q := q) +local notation "R" => Post.record d e ℓ (Format.addr cap) + +variable (A : Allocation p q (scheme m d h' e ℓ cap len decode)) (size : Face p q → B ℓ) + (payload : Cell a × q.vertex → B cap) (nav : B m → B d → B m) + +open scoped Classical in +/-- The header used in the `Allocation` construction. -/ +def header : Face p q → (Post.field d e ℓ).obj + | .inl j => (size (.inl j), S.direction r (p.vertex j.val.1, j.val.2), false, 0, 0) + | .inr (b, t) => (size (.inr (b, t)), t, true, A.index (Host b t) (Host b (!t)), + A.unitSeat b (!t)) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def fields (v : Cell a × q.vertex) : B e → (Post.field d e ℓ).obj := + Function.extend (A.seat v) (fun j => A.header size j.val) (fun _ => Post.unused) + +open scoped Classical in +/-- The value specified by `(true, A.fields size v, payload v)`. -/ +def localRecord (v : Cell a × q.vertex) : (R).obj := + (true, A.fields size v, payload v) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def records (x : B m) (y : B h') : (R).obj := + Post.extendRecord A.vertex (A.localRecord size payload) Post.vacant x y + +open scoped Classical in +/-- Evaluates `(nav v, (R).serial ∘ A.records size payload v)` at the input `v`. -/ +def output : (U).format.obj := fun v => (nav v, (R).serial ∘ A.records size payload v) + +local notation "out" => A.output size payload nav + +open scoped Classical in +theorem read_output (v : (U).Vtx) : + (U).pattern out v = pattern len decode (A.records size payload v.1 v.2.1) := + congrArg (pattern len decode) ((R).serial.symm_apply_apply _) + +open scoped Classical in +theorem record_at (v : Cell a × q.vertex) : + A.records size payload (A.vertex v).1 (A.vertex v).2.1 = A.localRecord size payload v := + Post.extendRecord_at A.vertex (A.localRecord size payload) _ v + +open scoped Classical in +theorem record_vacant (v : (U).Vtx) (hv : v ∉ Set.range A.vertex) : + A.records size payload v.1 v.2.1 = Post.vacant := + Post.extendRecord_vacant A.vertex (A.localRecord size payload) _ v hv + +open scoped Classical in +theorem stored (v : Cell a × q.vertex) : + Dense.used (Post.order d e ℓ cap ((out (A.host v.2)).2 (A.block v.1))).val ≤ + Dense.used (payload v).val + (Post.headerFmt d e ℓ).width := by + change Dense.used (Post.order d e ℓ cap + ((R).serial (A.records size payload (A.vertex v).1 (A.vertex v).2.1))).val ≤ _ + rw [record_at] + exact Post.order_length (A.localRecord size payload v) + +open scoped Classical in +theorem used (j : Face p q) : + (A.records size payload (A.span j).1.1 (A.span j).1.2.1).2.1 (A.span j).2 = A.header size j + := by + let v := whereAt p q j + change (A.records size payload (A.vertex v).1 (A.vertex v).2.1).2.1 (A.slot j) = _ + rw [record_at] + let t : Visible p q v := ⟨j, rfl⟩ + change A.fields size v (A.seat v t) = A.header size t.val + rw [fields, (A.seat v).injective.extend_apply] + +open scoped Classical in +theorem idle (t : (U).Span) (ht : t ∉ Set.range A.span) : + (A.records size payload t.1.1 t.1.2.1).2.1 t.2 = Post.unused := by + rcases t with ⟨v, j⟩ + by_cases hv : v ∈ Set.range A.vertex + · obtain ⟨w, rfl⟩ := hv + rw [record_at] + have hn : j ∉ Set.range (A.seat w) := by + rintro ⟨t, rfl⟩ + exact ht ⟨t.val, Prod.ext (congrArg A.vertex t.property) (A.slot_eq w t)⟩ + change A.fields size w j = _ + rw [fields, Function.extend_apply' _ _ _ hn] + · rw [record_vacant _ _ _ _ hv] + rfl + +open scoped Classical in +theorem exposed_direction (j : p.toPresentation.BorderSpan) : + (U).direction out (A.span (.inl j)) = S.direction r (p.vertex j.val.1, j.val.2) := by + rw [Scheme.direction, read_output] + simp only [pattern, used, header] + +variable (h₀ : len 0 = 0) (hlen : ∀ j, len (size j) = visibleWidth p q j) + +include h₀ hlen in +open scoped Classical in +theorem lengths : A.Lengths out where + used j := by + rw [Scheme.width, read_output] + change len ((A.records _ _ _ _).2.1 _).1 = _ + rw [A.used] + rcases j with j|⟨b, t⟩ <;> exact hlen _ + idle t ht := by + rw [Scheme.width, read_output] + change len ((A.records _ _ _ _).2.1 _).1 = _ + rw [A.idle _ _ _ ht] + exact h₀ + +local notation "l" => A.lengths size payload nav h₀ hlen + +open scoped Classical in +theorem agrees + (hop : ∀ (b : q.Survivors) t, + nav (A.host (Host b t)) (A.index (Host b t) (Host b (!t))) = A.host (Host b (!t))) + (H : ∀ v (x : B e → ℕ → Bool), decode (payload v) x = + Transcript.sample ((q.contract G.units).table v) + (fun j => let y := (visibleBits p q v).symm j; x (A.seat v y.1) y.2.val)) : + A.Agrees l where + sample v t := by + rw [table_eq len decode out _ _ (A.read_output size payload nav _), record_at] + change decode (payload v) _ = _ + rw [H] + apply congrArg + funext i + obtain ⟨⟨j, b⟩, rfl⟩ := (visibleBits p q v).surjective i + dsimp only [Function.comp_apply] + rw [Equiv.symm_apply_apply, A.pin_at] + have ht : b.val < (U).width out (A.vertex v, A.seat v j) := by + rw [A.length_at l] + exact b.isLt + exact dite_eq_left ht + vacant v hv t := by + rw [table_eq len decode out _ _ (A.read_output size payload nav _), record_vacant _ _ _ _ hv] + rfl + outside j := by + rw [Scheme.peer, read_output] + simp only [pattern, used, header, Bool.false_eq_true, ↓reduceIte, Option.map_none] + idle t ht := by + rw [Scheme.peer, read_output] + simp only [pattern, A.idle _ _ t ht, Post.unused, Bool.false_eq_true, ↓reduceIte, + Option.map_none] + dir b t := by + rw [Scheme.direction, read_output] + simp only [pattern, used, header] + link b t := by + dsimp only + rw [read_output] + simp only [pattern, used, header, ↓reduceIte] + nav b t := hop b t + +open scoped Classical in +theorem boundary (H : A.Agrees l) (t : slots x ⊕ slots y) : + let b := p.toSeating.ends (boundaryEnd _ t) + let b' := (A.presentation l H).toSeating.ends (boundaryEnd _ t) + (U).width out b'.1 = S.width r b.1 ∧ (U).direction out b'.1 = S.direction r b.1 ∧ + b'.2.val = b.2.val := by + obtain ⟨j, rfl⟩ := p.toPresentation.exteriorBits.surjective t + dsimp only [presentation] + rw [p.toPresentation.border_pin, A.exposed_pin] + exact ⟨(l).used (.inl j.1), A.exposed_direction size payload nav j.1, rfl⟩ + +open scoped Classical in +theorem floor (H : A.Agrees l) {w : ℕ} (hw : ∀ b, w ≤ p.toPresentation.borderWidth b) : + ∀ b, w ≤ (A.presentation l H).borderWidth b := by + let p' := A.presentation l H + intro b + let j : p'.BorderBit := ⟨b, ⟨0, b.property.1⟩⟩ + obtain ⟨t, ht⟩ := p.toPresentation.exteriorBits.surjective (p'.exteriorBits j) + have h := (A.boundary size payload nav h₀ hlen H (p'.exteriorBits j)).1 + rw [p'.border_pin, ← ht, p.toPresentation.border_pin] at h + exact (hw _).trans_eq h.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Allocation +end + +/- # Posting a reset network from descriptions of the local tensors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Book + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} {p : S.Posting r G} + {B' W' : ℝ} {Hcap D : ℕ} + {q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W' Hcap D} + {m d h' e cap : ℕ} (b : Book S u e cap) + (A : Allocation p q (b.scheme m d h')) (nav : B m → B d → B m) + +open scoped Classical in +/-- Computes the data by the application `b.payload p q v (A.seat v)`. -/ +abbrev data (v : Cell a × q.vertex) := b.payload p q v (A.seat v) + +open scoped Classical in +/-- The value specified by `A.output (b.size p q) (b.data A) nav`. -/ +abbrev output := A.output (b.size p q) (b.data A) nav + +local notation "Host" => Allocation.endHost (q := q) + +open scoped Classical in +/-- A recipe witnesses the length bound. Only its decoded function +determines the emitted label. -/ +structure Ready : Prop where + sizes : ∀ j, b.len (b.put (p.toPresentation.borderWidth j)) = p.toPresentation.borderWidth j + hop : ∀ (t : q.Survivors) i, + nav (A.host (Host t i)) (A.index (Host t i) (Host t (!i))) = A.host (Host t (!i)) + describe : ∀ v, ∃ c : Recipe S e, + run b.ord u c = localEval p q v (A.seat v) ∧ Dense.cost c.2 = inherited p q v b.ord + budget : ∀ v, overhead S e + inherited p q v b.ord ≤ cap + +namespace Ready + +variable {b A nav} (H : b.Ready A nav) +local notation "out" => b.output A nav +local notation "U" => b.scheme m d h' + +include H in +open scoped Classical in +theorem length (j : Face p q) : b.len (b.size p q j) = visibleWidth p q j := by + cases j with + | inl j => exact H.sizes j + | inr _ => exact b.unit + +include H in +open scoped Classical in +theorem lengths : A.Lengths out := A.lengths (b.size p q) (b.data A) nav b.zero H.length + +include H in +open scoped Classical in +theorem data_spec (v : Cell a × q.vertex) : + decoder b.ord u cap (b.data A v) = localEval p q v (A.seat v) ∧ + Dense.used (b.data A v).val ≤ overhead S e + inherited p q v b.ord := by + obtain ⟨c, hc, hl⟩ := H.describe v + rw [← hl] + exact canonical_spec c hc (by rw [hl]; exact H.budget v) + +open scoped Classical in +theorem agrees : A.Agrees H.lengths := + A.agrees (b.size p q) (b.data A) nav b.zero H.length H.hop (fun v t + => congrFun (H.data_spec v).1 t) + +open scoped Classical in +/-- Uses `A.posting H.lengths H.agrees` as the representation. -/ +def posting : (U).Posting out (G.afterReset q) := A.posting H.lengths H.agrees + +open scoped Classical in +theorem boundary (t : slots x ⊕ slots y) : + let i := p.toSeating.ends (boundaryEnd _ t) + let j := H.posting.toSeating.ends (boundaryEnd _ t) + (U).width out j.1 = S.width r i.1 ∧ (U).direction out j.1 = S.direction r i.1 ∧ + j.2.val = i.2.val := + A.boundary (b.size p q) (b.data A) nav b.zero H.length H.agrees t + +open scoped Classical in +theorem floor {w : ℕ} (hw : ∀ j, w ≤ p.toPresentation.borderWidth j) : + ∀ j, w ≤ H.posting.toPresentation.borderWidth j := + A.floor (b.size p q) (b.data A) nav b.zero H.length H.agrees hw + +open scoped Classical in +theorem palette (W : Finset ℕ) (hw : ∀ j, p.toPresentation.borderWidth j ∈ W) : + ∀ j, H.posting.toPresentation.borderWidth j ∈ W := by + let p' := H.posting.toPresentation + intro j + let x : p'.BorderBit := ⟨j, ⟨0, j.property.1⟩⟩ + obtain ⟨t, ht⟩ := p.toPresentation.exteriorBits.surjective (p'.exteriorBits x) + have hh := (H.boundary (p'.exteriorBits x)).1 + rw [p'.border_pin, ← ht, p.toPresentation.border_pin] at hh + exact Eq.mp (congrArg (· ∈ W) hh.symm) (hw t.1) + +include H in +open scoped Classical in +theorem stored (v : Cell a × q.vertex) : + Dense.used (Post.order d e b.d cap ((out (A.host v.2)).2 (A.block v.1))).val ≤ + (Post.headerFmt d e b.d).width + overhead S e + inherited p q v b.ord := by + refine (A.stored (b.size p q) (b.data A) nav v).trans ?_ + have := (H.data_spec v).2 + omega + +end Ready +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Book +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Ports/Eval.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Ports/Eval.lean new file mode 100644 index 0000000000..d1c06be32a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Ports/Eval.lean @@ -0,0 +1,1012 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Ports.Correspondence +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Repost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Move +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Width +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Raw.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Headers + +/-! # Old vertices and exterior spans resident at a reset station -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing Coloring +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + (U V : Setup S h u a Δ D Y w B') {R : Rotor F Y w} + {σ : Cell a} {v : U.G.V} {z : V.G.V} {loc : Coord R h a Δ} + +open scoped Classical in +/-- The condition `∀ j, U.Z.group j = σ → U.tag v j = V.tag z j` on the specified data. -/ +def Tags (σ : Cell a) (v : U.G.V) (z : V.G.V) := + ∀ j, U.Z.group j = σ → U.tag v j = V.tag z j + +open scoped Classical in +private theorem positive_arity (t : U.G.diagram.V) : + 0 < U.G.diagram.arity t ↔ ∃ j, 0 < S.width U.r (U.post.vertex t, j) := by + have he : 0 < U.G.diagram.arity t ↔ Nonempty (S.LocalPin U.r (U.post.vertex t)) := by + rw [← Fintype.card_pos_iff, ← Fintype.card_congr (U.post.pin t)] + simp only [Diagram.Port, Fintype.card_sum, card_slots, Diagram.arity] + rw [he] + exact ⟨fun ⟨⟨j, i⟩⟩ => ⟨j, i.pos⟩, fun ⟨j, hj⟩ => ⟨⟨j, ⟨0, hj⟩⟩⟩⟩ + +open scoped Classical in +private theorem exists_vertex (v : U.G.V) (j : Cell h) (t : B S.e) (ht : 0 + < (U.pat v j).width 0 t) : + ∃ x, 0 < U.G.diagram.arity x ∧ U.G.units.place x = (v, j) := by + let b : S.Vtx := (U.post.host v, U.post.block j, 0) + obtain ⟨x, hx⟩ := U.post.cover ⟨(b, t), ⟨0, ht⟩⟩ + change U.post.vertex x = b at hx + refine ⟨x, (U.positive_arity x).mpr ⟨t, by rw [hx]; exact ht⟩, ?_⟩ + rw [U.post.vertex_eq] at hx + exact Prod.ext (U.post.host.injective (Prod.mk.inj hx).1) + (U.post.block.injective (Prod.mk.inj (Prod.mk.inj hx).2).1) + +variable {U V} [NeZero Y] [NeZero w] {fit : U.Fits R c} {fit' : V.Fits R c} + (p : Agree U V σ v z) (ht : U.Tags V σ v z) + +include p ht in +omit [NeZero Y] [NeZero w] in +open scoped Classical in +theorem Tags.symm : V.Tags U σ z v := fun j hj => (ht j ((p.group j).trans hj)).symm + +open scoped Classical in +theorem owner_here {s : U.G.V × Cell h} (he : (U.result R fit).owner s = U.station R fit σ v loc) : + U.Z.group s.2 = σ ∧ s.1 = v := by + have := (U.place R fit).eq_symm_apply.mp he + simp only [owner_place, Prod.mk.injEq] at this + exact ⟨this.1, this.2.1⟩ + +include p in +open scoped Classical in +theorem Agree.owner_here {s : U.G.V × Cell h} + (he : (U.result R fit).owner s = U.station R fit σ v loc) : + (V.result R fit').owner (z, s.2) = V.station R fit' σ z loc := by + obtain ⟨v', j⟩ := s + obtain ⟨hg, hv⟩ := Setup.owner_here he + change v' = v at hv + subst v' + have hdrop := congrArg (fun b => (Site.drop a ((), b)).2) (p.leaf j hg) + change ((U.Z.leaf (v, j)).drop a).2 = ((V.Z.leaf (z, j)).drop a).2 at hdrop + simp only [station, Equiv.eq_symm_apply, owner_place, Prod.mk.injEq, true_and] at he ⊢ + rwa [← p.group, ← hdrop, ← p.terminal j hg] + +open scoped Classical in +/-- The value specified by `Live (U.result R fit) (U.station R fit σ v loc)`. -/ +abbrev Actors (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) (fit : U.Fits R c) + (σ : Cell a) (v : U.G.V) (loc : Coord R h a Δ) := + Live (U.result R fit) (U.station R fit σ v loc) + +open scoped Classical in +/-- The value specified by `(U.G.units.place t.val).2`. -/ +def blockOf (t : U.Actors R fit σ v loc) : Cell h := (U.G.units.place t.val).2 + +open scoped Classical in +theorem actor_label (t : U.Actors R fit σ v loc) : + oldLabel U.post t.val = (U.tag v (blockOf t), 0) := by + unfold oldLabel + rw [U.post.vertex_eq, (Setup.owner_here t.2.2).2] + rfl + +open scoped Classical in +private theorem block_inj : Function.Injective (blockOf (U := U) (fit := fit) (σ := σ) (v + := v) (loc := loc)) := by + intro i j he + apply Subtype.ext + apply U.post.vertex.injective + rw [U.post.vertex_eq, U.post.vertex_eq, (owner_here i.2.2).2, (owner_here j.2.2).2] + unfold blockOf at he + rw [he] + +include p ht in +open scoped Classical in +private theorem Agree.actor_map (t : U.Actors R fit σ v loc) : + ∃ t' : V.Actors R fit' σ z loc, blockOf t = blockOf t' := by + obtain ⟨j, hj⟩ := (U.positive_arity t.val).mp t.2.1 + have htag := ht (blockOf t) (Setup.owner_here t.2.2).1 + rw [U.post.vertex_eq, (Setup.owner_here t.2.2).2] at hj + change 0 < (S.decode (U.tag v (blockOf t))).width 0 j at hj + rw [htag] at hj + obtain ⟨x, hx, he⟩ := V.exists_vertex _ _ j hj + refine ⟨⟨x, hx, by rw [he]; exact p.owner_here t.2.2⟩, (congrArg Prod.snd he).symm⟩ + +include p ht in +open scoped Classical in +theorem Agree.actors : + ∃ e : U.Actors R fit σ v loc ≃ V.Actors R fit' σ z loc, ∀ t, blockOf (e t) = blockOf t := + Dispatch.equivalent _ _ block_inj block_inj (p.actor_map ht) (p.symm.actor_map (ht.symm p)) + +include p ht in +open scoped Classical in +theorem Agree.border_map (t : U.post.toPresentation.BorderSpan) + (he : (U.result R fit).owner (U.G.units.place t.val.1) = U.station R fit σ v loc) : + ∃ j : V.post.toPresentation.BorderSpan, + (V.result R fit').owner (V.G.units.place j.val.1) = V.station R fit' σ z loc ∧ + (V.G.units.place j.val.1).2 = (U.G.units.place t.val.1).2 ∧ j.val.2 = t.val.2 ∧ + V.post.toPresentation.borderWidth j = U.post.toPresentation.borderWidth t := by + let i := (U.G.units.place t.val.1).2 + have hl : U.pat v i = V.pat z i := congrArg S.decode (ht i (Setup.owner_here he).1) + have hv : U.post.vertex t.val.1 = (U.post.host v, U.post.block i, 0) := by + rw [U.post.vertex_eq, (Setup.owner_here he).2] + have h := t.property + rw [hv] at h + have hm : 0 < (V.pat z i).width 0 t.val.2 := by rw [← hl]; exact h.1 + obtain ⟨x, _, hx⟩ := V.exists_vertex _ _ _ hm + have hz : V.post.vertex x = (V.post.host z, V.post.block i, 0) := by rw [V.post.vertex_eq, hx] + have hh : S.peer V.r (V.post.vertex x, t.val.2) = none := by + rw [hz] + have hs : (U.pat v i).peer 0 t.val.2 = none := by + simpa [pat, tag, Scheme.peer, Scheme.pattern] using h.2 + rw [hl] at hs + simpa [pat, tag, Scheme.peer, Scheme.pattern] using hs + let j : V.post.toPresentation.BorderSpan := ⟨(x, t.val.2), by rw [hz]; exact hm, hh⟩ + refine ⟨j, ?_, congrArg Prod.snd hx, rfl, ?_⟩ + · change (V.result R fit').owner (V.G.units.place x) = _ + rw [hx]; exact p.owner_here he + · change S.width V.r (V.post.vertex x, _) = S.width U.r (U.post.vertex t.val.1, _) + rw [hz, hv] + exact congrArg (fun p : Pattern F S.d S.k S.e => p.width 0 t.val.2) hl.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The visible and hidden carriers at matching reset stations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + (fit : U.Fits R c) (σ : Cell a) (v : U.G.V) (loc : Coord R h a Δ) + +open scoped Classical in +/-- The value specified by `Visible U.post (U.result R fit) (U.station R fit σ v loc)`. -/ +abbrev Seen := Visible U.post (U.result R fit) (U.station R fit σ v loc) +open scoped Classical in +/-- The value specified by `Hidden (U.result R fit) (U.station R fit σ v loc)`. -/ +abbrev Unseen := Hidden (U.result R fit) (U.station R fit σ v loc) + +open scoped Classical in +/-- Computes the visible key by the application `U.portKey R fit _ (.inl t)`. -/ +def visibleKey (t : U.Seen R fit σ v loc) := U.portKey R fit _ (.inl t) +open scoped Classical in +/-- Computes the hidden key by the application `U.portKey R fit _ (.inr t)`. -/ +def hiddenKey (t : U.Unseen R fit σ v loc) := U.portKey R fit _ (.inr t) + +open scoped Classical in +theorem visible_inj : Function.Injective (U.visibleKey R fit σ v loc) := + fun _ _ he => Sum.inl.inj (U.portKey_injective R fit _ he) + +open scoped Classical in +theorem hidden_inj : Function.Injective (U.hiddenKey R fit σ v loc) := + fun _ _ he => Sum.inr.inj (U.portKey_injective R fit _ he) + +variable {U R fit σ v loc} {V : Setup S h u a Δ D Y w B'} {fit' : V.Fits R c} + {z : V.G.V} {Q : Relation U V} {k n : ℕ} + +open scoped Classical in +theorem distinct_keys (j : U.Seen R fit σ v loc) (t : V.Unseen R fit' σ z loc) : + U.visibleKey R fit σ v loc j ≠ V.hiddenKey R fit' σ z loc t := by + rcases j with ⟨j | ⟨q, b⟩, hj⟩ <;> rcases t with ⟨e|e|e, he⟩ <;> + simp [visibleKey, hiddenKey, portKey] + +variable (p : Region U V σ Q n) (hk : k + (h - a) + 3 ≤ n) (hr : Q k v z) + (ht : U.Tags V σ v z) + +include p hk hr ht in +open scoped Classical in +theorem Region.visible_map (t : U.Seen R fit σ v loc) : + ∃ j : V.Seen R fit' σ z loc, U.visibleKey R fit σ v loc t = V.visibleKey R fit' σ z loc j ∧ + visibleWidth U.post (U.result R fit) t.val = visibleWidth V.post (V.result R fit') j.val := by + rcases t with ⟨q | ⟨e, b⟩, he⟩ + · obtain ⟨j, hj, hb, hs, hw⟩ := (p.toSurvey.agree (by omega) hr).border_map (fit' := fit') ht q he + refine ⟨⟨.inl j, hj⟩, ?_, hw.symm⟩ + exact congrArg₂ PortId.border hb.symm (congrArg Fin.val hs.symm) + · obtain ⟨f, hf, r⟩ := p.raw_here (fit' := fit') hk hr (raw_at.mp he) + let g : (V.result R fit').Survivors := ⟨f, mt (r.loop p (by omega)).mpr e.property⟩ + exact ⟨⟨.inr (g, b), raw_at.mpr hf⟩, congrArg (PortId.line true b) (r.key b), rfl⟩ + +include p hk hr ht in +open scoped Classical in +theorem Region.visible : + ∃ e : U.Seen R fit σ v loc ≃ V.Seen R fit' σ z loc, ∀ t, + V.visibleKey R fit' σ z loc (e t) = U.visibleKey R fit σ v loc t ∧ + visibleWidth V.post (V.result R fit') (e t).val = visibleWidth U.post (U.result R fit) t.val + := by + have a := p.visible_map (fit := fit) (fit' := fit') (loc := loc) hk hr ht + have b := p.symm.visible_map (fit := fit') (fit' := fit) (loc := loc) hk hr + (ht.symm (p.toSurvey.agree (by omega) hr)) + obtain ⟨e, he⟩ := Dispatch.equivalent _ _ (U.visible_inj R fit σ v loc) (V.visible_inj R fit' σ z + loc) + (fun x => (a x).imp (fun _ h => h.1)) (fun x => (b x).imp (fun _ h => h.1)) + refine ⟨e, fun t => ⟨he t, ?_⟩⟩ + obtain ⟨q, hq, hw⟩ := b (e t) + rw [U.visible_inj R fit σ v loc (hq.symm.trans (he t))] at hw + exact hw + +include p hk hr in +open scoped Classical in +private theorem Region.hidden_map (t : U.Unseen R fit σ v loc) : + ∃ j : V.Unseen R fit' σ z loc, U.hiddenKey R fit σ v loc t = V.hiddenKey R fit' σ z loc j := by + rcases t with ⟨e|e|e, he⟩ + · have h : demandSite (U.result R fit) e false = U.station R fit σ v loc := congrArg Prod.fst he + obtain ⟨f, hf, r⟩ := p.old_here (fit' := fit') hk hr (old_at.mp h) + exact ⟨⟨.inl f, Prod.ext (old_at.mpr hf) (old_at.mpr hf)⟩, + congrArg (PortId.demand false) (r.name false)⟩ + · have h : demandSite (U.result R fit) e true = U.station R fit σ v loc := congrArg Prod.fst he + obtain ⟨f, hf, r⟩ := p.old_here (fit' := fit') hk hr (old_at.mp h) + exact ⟨⟨.inr (.inl f), Prod.ext (old_at.mpr hf) (old_at.mpr hf)⟩, + congrArg (PortId.demand true) (r.name true)⟩ + · have h : supplySite (U.result R fit) e false = U.station R fit σ v loc := congrArg Prod.fst he + obtain ⟨f, hf, r⟩ := p.raw_here (fit' := fit') hk hr (raw_at.mp h) + have hh := (r.loop p (by omega)).mp ((congrArg Prod.fst he).trans (congrArg Prod.snd he).symm) + exact ⟨⟨.inr (.inr f), Prod.ext (raw_at.mpr hf) (hh.symm.trans (raw_at.mpr hf))⟩, + congrArg (PortId.line false false) (r.key false)⟩ + +include p hk hr in +open scoped Classical in +theorem Region.hidden : + ∃ e : U.Unseen R fit σ v loc ≃ V.Unseen R fit' σ z loc, ∀ t, + V.hiddenKey R fit' σ z loc (e t) = U.hiddenKey R fit σ v loc t := + Dispatch.equivalent _ _ (U.hidden_inj ..) (V.hidden_inj ..) + (p.hidden_map hk hr) (p.symm.hidden_map hk hr) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Reading the same reset rule on matching port tapes -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + (fit : U.Fits R c) (σ : Cell a) (v : U.G.V) (loc : Coord R h a Δ) + +open scoped Classical in +/-- The value specified by `Port U.post (U.result R fit) (U.station R fit σ v loc)`. -/ +abbrev Pins := Port U.post (U.result R fit) (U.station R fit σ v loc) +open scoped Classical in +/-- The value specified by `Tape U.post (U.result R fit) (U.station R fit σ v loc)`. -/ +abbrev Readings := Tape U.post (U.result R fit) (U.station R fit σ v loc) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def values (x : U.Readings R fit σ v loc) (j : Fin u) : U.Value R := + Sum.elim (fun i => inBits U.post _ _ x i.2 j i.1) (outBits U.post _ _ x j) + +open scoped Classical in +private theorem loop_port (e : U.Raw R) (h₁ : supplySite (U.result R fit) e false + = U.station R fit σ v loc) + (h₂ : supplySite (U.result R fit) e true = U.station R fit σ v loc) : + supply U.post (U.result R fit) (U.station R fit σ v loc) e false h₁ + = supply U.post (U.result R fit) (U.station R fit σ v loc) e true h₂ := by + have he : ((U.result R fit).supply e).1 = ((U.result R fit).supply e).2 := h₁.trans h₂.symm + simp only [supply, dite_eq_left he] + +open scoped Classical in +private theorem read_line (x : U.Readings R fit σ v loc) (j : Fin u) (e : U.Raw R) (t : Bool) + (he : supplySite (U.result R fit) e t = U.station R fit σ v loc) : + U.values R fit σ v loc x j (.inr e) = x (supply U.post (U.result R fit) (U.station R fit σ v + loc) e t he) + (j.cast (width_supply U.post (U.result R fit) (U.station R fit σ v loc) e t he).symm) := by + change outBits U.post (U.result R fit) (U.station R fit σ v loc) x j e = _ + unfold outBits + cases t + · rw [dite_eq_left he] + · by_cases hf : supplySite (U.result R fit) e false = U.station R fit σ v loc + · rw [dite_eq_left hf] + congr 1 + · exact U.loop_port R fit σ v loc e hf he + · apply (Fin.heq_ext_iff ((width_supply ..).trans (width_supply ..).symm)).mpr + rfl + · rw [dite_eq_right hf, dite_eq_left he] + +variable {U R fit σ v loc} {V : Setup S h u a Δ D Y w B'} {fit' : V.Fits R c} + {z : V.G.V} {Q : Relation U V} {k n : ℕ} + +open scoped Classical in +/-- The condition `∀ i j, U.portKey R fit _ i = V.portKey R fit' _ j → ∀ t t', t.val = t'.val → +x i t = y j t'` on the specified data. -/ +def Reads (x : U.Readings R fit σ v loc) (y : V.Readings R fit' σ z loc) : Prop := + ∀ i j, U.portKey R fit _ i = V.portKey R fit' _ j → + ∀ t t', t.val = t'.val → x i t = y j t' + +variable (p : Region U V σ Q n) (hk : k + (h - a) + 3 ≤ n) (hr : Q k v z) + {x : U.Readings R fit σ v loc} {y : V.Readings R fit' σ z loc} (hread : Reads x y) + +include p hk hr hread in +open scoped Classical in +theorem Region.alignment (j : Fin u) : Alignment R fit fit' σ v z loc + (U.values R fit σ v loc x j) (V.values R fit' σ z loc y j) := by + constructor + · intro e f t he hf hn + have he' := old_at.mpr he + have hf' := old_at.mpr hf + change inBits U.post _ _ x t j e = inBits V.post _ _ y t j f + simp only [inBits, dite_eq_left he', dite_eq_left hf'] + refine hread _ _ ?_ _ _ rfl + rw [demand_key, demand_key, hn] + · intro e f t he hf hn + have he' := raw_at.mpr he + have hf' := raw_at.mpr hf + have r := p.raw_pair hk hr he hf hn + rw [U.read_line R fit σ v loc x j e t he', V.read_line R fit' σ z loc y j f t hf'] + refine hread _ _ ?_ _ _ rfl + simp only [supply_key, r.loop p (by omega), r.key] + +include p hk hr hread in +open scoped Classical in +theorem Region.created : created U.post _ _ x = created V.post _ _ y := by + apply Finset.prod_congr rfl + intro j _ + exact (p.alignment hk hr hread j).value p hk hr + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Recovering old argument names from a posted local table -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + (fit : U.Fits R c) (σ : Cell a) (v : U.G.V) (loc : Coord R h a Δ) + +open scoped Classical in +/-- The old key of type `PortId R h`, constructed using `S.decode k.1`. -/ +def oldKey (S : Scheme F) (b : Cell h) (k : B S.ℓ × B S.k) (j : B S.e) : PortId R h := + let pat := S.decode k.1 + if pat.peer k.2 j = none then .border b j.val + else .demand (pat.direction k.2 j) (Encodable.encode (cellIndex h b, j, pat.direction k.2 j)) + +open scoped Classical in +theorem origin_key (x : U.Actors R fit σ v loc) (j : B S.e) + {p : Port U.post (U.result R fit) (U.station R fit σ v loc)} + (hp : Origin U.post (U.result R fit) (U.station R fit σ v loc) x.val j p) : + U.portKey R fit _ p = oldKey R S (blockOf x) (oldLabel U.post x.val) j := by + unfold oldKey + dsimp only + let t := U.post.vertex x.val + change _ = if (S.pattern U.r t).peer t.2.2 j = none then PortId.border _ _ else _ + cases hp with + | outside q hq he => + have h : (S.pattern U.r t).peer t.2.2 j = none := by + have h := q.property.2 + rw [hq] at h + simpa [t, Scheme.peer] using h + rw [ite_eq_left h, exterior_key, hq] + rfl + | inside e b he hs => + have ht : (U.post.span e b).1 = t := congrArg Prod.fst he + have hj : U.post.stub e b = j := congrArg Prod.snd he + have hb : U.G.ix e = blockOf x := by + unfold blockOf + apply U.post.block.injective + rw [U.post.vertex_eq] at he + exact congrArg (fun p : S.Span => p.1.2.1) he + have hi : (S.pattern U.r t).peer t.2.2 j ≠ none := by + rw [← ht, ← hj] + exact (U.post.link e b).trans_ne (by simp) + rw [ite_eq_right hi, demand_key] + change PortId.demand b (endName U.post e b) = + .demand (S.direction U.r (t, j)) (Encodable.encode (cellIndex h (blockOf x), j, + S.direction U.r (t, j))) + have hd : S.direction U.r (t, j) = b := (congrArg (S.direction U.r) he).symm.trans (U.post.dir + e b) + rw [hd, endName, hb, hj] + +variable {U R fit σ v loc} {V : Setup S h u a Δ D Y w B'} {fit' : V.Fits R c} + {z : V.G.V} + +omit [Field F] in +open scoped Classical in +private theorem original_congr {m n : B S.ℓ × B S.k} (h : m = n) + (x : ∀ j : B S.e, Fin ((History.original S m).width j) → Bool) + (y : ∀ j : B S.e, Fin ((History.original S n).width j) → Bool) + (he : ∀ j t t', t.val = t'.val → x j t = y j t') : + (History.original S m).weight x = (History.original S n).weight y := by + subst n + exact congrArg _ (funext fun j => funext fun t => he j t t rfl) + +open scoped Classical in +theorem Reads.previous {x : U.Readings R fit σ v loc} {y : V.Readings R fit' σ z loc} + (r : Reads x y) (ht : U.Tags V σ v z) + (i : U.Actors R fit σ v loc) (j : V.Actors R fit' σ z loc) (hb : blockOf i = blockOf j) : + previous U.post _ _ x i = previous V.post _ _ y j := by + have hl : oldLabel U.post i.val = oldLabel V.post j.val := by + rw [actor_label, actor_label, ← hb, ht (blockOf i) (owner_here i.2.2).1] + unfold Reset.previous + apply original_congr hl + intro t a b he + apply r _ _ _ _ _ he + have h₁ := U.origin_key R fit σ v loc i t (station_origin U.post _ _ i.val i.property.2 t a.pos) + have h₂ := V.origin_key R fit' σ z loc j t (station_origin V.post _ _ j.val j.property.2 t b.pos) + exact h₁.trans ((congrArg₂ (fun q l => oldKey R S q l t) hb hl).trans h₂.symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Local equality of contracted reset tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] {U V : Setup S h u a Δ D Y w B'} {R : Rotor F Y w} + {fit : U.Fits R c} {fit' : V.Fits R c} {σ : Cell a} {v : U.G.V} {z : V.G.V} + {loc : Coord R h a Δ} {Q : Relation U V} {k n e e' : ℕ} + +local notation "d" => U.result R fit +local notation "d'" => V.result R fit' +local notation "b" => U.station R fit σ v loc +local notation "b'" => V.station R fit' σ z loc + +open scoped Classical in +private def renameBits (f : U.Unseen R fit σ v loc ≃ V.Unseen R fit' σ z loc) : + (Inner d b → Bool) ≃ (Inner d' b' → Bool) := + (f.prodCongr (.refl _)).arrowCongr (.refl _) + +open scoped Classical in +private theorem tape_eq (f : U.Unseen R fit σ v loc ≃ V.Unseen R fit' σ z loc) + (hf : ∀ t, V.hiddenKey R fit' σ z loc (f t) = U.hiddenKey R fit σ v loc t) + (s : U.Seen R fit σ v loc ↪ B e) (s' : V.Seen R fit' σ z loc ↪ B e') + (x : B e → ℕ → Bool) (y : B e' → ℕ → Bool) + (he : ∀ i j, U.visibleKey R fit σ v loc i = V.visibleKey R fit' σ z loc j → ∀ l, x (s i) l + = y (s' j) l) + (t : Inner d b → Bool) : + Reads (tape U.post d b s x t) (tape V.post d' b' s' y (renameBits f t)) := by + rintro (i|i) (j|j) h a a' ha + · exact (he i j h a.val).trans (congrArg (y (s' j)) ha) + · exact (distinct_keys i j h).elim + · exact (distinct_keys j i h.symm).elim + · have hj := V.hidden_inj R fit' σ z loc ((hf i).trans h) + change t (i, a) = t (f.symm j, a') + rw [← hj, Equiv.symm_apply_apply, Fin.ext ha] + +open scoped Classical in +/-- Matched input patches yield exactly the same table for all +assignments agreeing at their named exterior ports. -/ +theorem Region.eval (p : Region U V σ Q n) (hk : k + (h - a) + 3 ≤ n) (hr : Q k v z) + (ht : U.Tags V σ v z) + (hu : ∀ t, U.G.diagram.arity t = 0 → ∀ x, Transcript.sample (U.G.diagram.table t) x = 1) + (hv : ∀ t, V.G.diagram.arity t = 0 → ∀ x, Transcript.sample (V.G.diagram.table t) x = 1) + (s : U.Seen R fit σ v loc ↪ B e) (s' : V.Seen R fit' σ z loc ↪ B e') + (x : B e → ℕ → Bool) (y : B e' → ℕ → Bool) + (he : ∀ i j, U.visibleKey R fit σ v loc i = V.visibleKey R fit' σ z loc j → ∀ l, x (s i) l + = y (s' j) l) : + localEval U.post d b s x = localEval V.post d' b' s' y := by + obtain ⟨f, hf⟩ := p.hidden (fit := fit) (fit' := fit') (loc := loc) hk hr + obtain ⟨g, hg⟩ := (p.toSurvey.agree (by omega) hr).actors (fit := fit) (fit' := fit') (loc + := loc) ht + rw [eval_formula _ _ _ hu, eval_formula _ _ _ hv] + apply Fintype.sum_equiv (renameBits f) + intro t + have H := tape_eq f hf s s' x y he t + apply congrArg₂ (· * ·) _ (p.created hk hr H) + exact Fintype.prod_equiv g _ _ (fun i => H.previous ht i (g i) (hg i).symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # A common numbering of all visible spans at a reset station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U V : Setup S h u a Δ D Y w B') (R : Rotor F Y w) (fit : U.Fits R c) + (Z : Scheme F) + +open scoped Classical in +/-- Embeds `Visible U.post (U.result R fit) v` into `PortId R h`. -/ +def visibleName (v : U.At R fit) : Visible U.post (U.result R fit) v ↪ PortId R h := + ⟨fun j => U.portKey R fit v (.inl j), (U.portKey_injective R fit v).comp Sum.inl_injective⟩ + +open scoped Classical in +/-- The condition `∀ v, Fintype.card (Visible U.post (U.result R fit) v) ≤ 2 ^ Z.e` on the +specified data. -/ +def Room := ∀ v, Fintype.card (Visible U.post (U.result R fit) v) ≤ 2 ^ Z.e + +open scoped Classical in +/-- Builds `Allocation U.post (U.result R fit) Z where host` with the specified `host`, `block`, +`index`, `seat`. -/ +def allocate (host : (U.result R fit).vertex ↪ B Z.m) (block : Cell a ↪ B Z.h) + (index : (U.result R fit).vertex → (U.result R fit).vertex → B Z.d) + (room : U.Room R fit Z) : Allocation U.post (U.result R fit) Z where + host := host + block := block + index := index + seat v := rank (U.visibleName R fit v) (room v) + +variable {U V R fit Z} + +open scoped Classical in +/-- The condition `∀ v, A.seat v = rank (U.visibleName R fit v) (by simpa using +Fintype.card_le_of_embedding (A.seat v))` on the specified data. -/ +def Ranked (A : Allocation U.post (U.result R fit) Z) := + ∀ v, A.seat v = rank (U.visibleName R fit v) (by simpa using Fintype.card_le_of_embedding (A.seat + v)) + +variable {fit' : V.Fits R c} {Q : Relation U V} {σ : Cell a} {k n : ℕ} + {v : U.G.V} {z : V.G.V} {loc : Coord R h a Δ} + {A : Allocation U.post (U.result R fit) Z} {A' : Allocation V.post (V.result R fit') Z} + (p : Region U V σ Q n) (hk : k + (h - a) + 3 ≤ n) (hr : Q k v z) + (ht : U.Tags V σ v z) (ha : Ranked A) (hb : Ranked A') + +include p hk hr ht ha hb in +open scoped Classical in +theorem Region.seat {i : U.Seen R fit σ v loc} {j : V.Seen R fit' σ z loc} + (he : U.visibleKey R fit σ v loc i = V.visibleKey R fit' σ z loc j) : + A.seat _ i = A'.seat _ j := by + obtain ⟨e, he'⟩ := p.visible (fit := fit) (fit' := fit') (loc := loc) hk hr ht + rw [ha, hb] + apply rank_eq _ _ he + · exact fun i => ⟨e i, (he' i).1.symm⟩ + · intro j + obtain ⟨i, rfl⟩ := e.surjective j + exact ⟨i, (he' i).1⟩ + +variable {s : (U.result R fit).Survivors} {r : (V.result R fit').Survivors} {b : Bool} + +open scoped Classical in +theorem end_site (s : (U.result R fit).Survivors) (b : Bool) : + (U.place R fit).symm (U.rawPlace R fit s.val b) = whereAt U.post (U.result R fit) (.inr (s, b)) + := + (U.place R fit).symm_apply_apply _ + +include p hk hr ht ha hb in +open scoped Classical in +theorem Region.unit_seat + (hs : U.rawPlace R fit s.val b = (σ, v, loc)) (hr' : V.rawPlace R fit' r.val b = (σ, z, loc)) + (he : U.rawKey R s.val b = V.rawKey R r.val b) : A.unitSeat s b = A'.unitSeat r b := by + let i : U.Seen R fit σ v loc := ⟨.inr (s, b), raw_at.mpr hs⟩ + let j : V.Seen R fit' σ z loc := ⟨.inr (r, b), raw_at.mpr hr'⟩ + have eq : U.visibleKey R fit σ v loc i = V.visibleKey R fit' σ z loc j := + congrArg (PortId.line true b) he + exact (A.slot_eq _ i).trans ((p.seat hk hr ht ha hb eq).trans (A'.slot_eq _ j).symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The peer address of a surviving span after a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring + +variable {F : Type} [Field F] {S Z : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] {U V : Setup S h u a Δ D Y w B'} {R : Rotor F Y w} + {fit : U.Fits R c} {fit' : V.Fits R c} (A : Allocation U.post (U.result R fit) Z) + (A' : Allocation V.post (V.result R fit') Z) + (Q : Relation U V) (σ : Cell a) (v : U.G.V) (z : V.G.V) + +open scoped Classical in +/-- The index agrees of type `Prop` for the given inputs. -/ +def IndexAgrees : Prop := + ∀ v' z', Q 1 v' z' → ∀ loc loc', + A.index (U.station R fit σ v loc).2 (U.station R fit σ v' loc').2 = + A'.index (V.station R fit' σ z loc).2 (V.station R fit' σ z' loc').2 + +variable {A A' Q σ v z} {loc : Coord R h a Δ} {n : ℕ} + (p : Region U V σ Q n) (hk : (h - a) + 4 ≤ n) (hr : Q 0 v z) + (ht : ∀ i j, Q 1 i j → U.Tags V σ i j) (ha : Ranked A) (hb : Ranked A') + (hi : IndexAgrees A A' Q σ v z) + {s : (U.result R fit).Survivors} {r : (V.result R fit').Survivors} {b : Bool} + +open scoped Classical in +theorem station_end (hs : U.rawPlace R fit s.val b = (σ, v, loc)) : + (U.station R fit σ v loc).2 = Allocation.endHost (q := U.result R fit) s b := by + rw [station, ← hs, end_site] + rfl + +include p hk hr ht ha hb hi in +open scoped Classical in +theorem Region.link + (hs : U.rawPlace R fit s.val b = (σ, v, loc)) (hr' : V.rawPlace R fit' r.val b = (σ, z, loc)) + (he : U.rawKey R s.val b = V.rawKey R r.val b) : + A.unitSeat s (!b) = A'.unitSeat r (!b) ∧ + A.index (Allocation.endHost (q := U.result R fit) s b) (Allocation.endHost (q + := U.result R fit) s (!b)) = + A'.index (Allocation.endHost (q := V.result R fit') r b) (Allocation.endHost (q + := V.result R fit') r (!b)) := by + have hh := p.raw_pair (k := 0) (by omega) hr hs hr' he + let x := U.rawPlace R fit s.val (!b) + let y := V.rawPlace R fit' r.val (!b) + have hx : U.rawPlace R fit s.val (!b) = (σ, x.2.1, x.2.2) := Prod.ext (hh.group _) rfl + have hy : V.rawPlace R fit' r.val (!b) = (σ, y.2.1, x.2.2) := + Prod.ext (hh.group' _) (Prod.ext rfl (hh.coord _).symm) + have heq : Q 1 x.2.1 y.2.1 := hh.host (!b) + refine ⟨p.unit_seat (by omega) heq (ht _ _ heq) ha hb hx hy (hh.key _), ?_⟩ + rw [← station_end hs, ← station_end hx, ← station_end hr', ← station_end hy] + exact hi _ _ heq loc x.2.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Both the header and the exterior return pointer are local -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring BatchDescent.Trail + +variable {F : Type} [Field F] [Fintype F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] {U V : Setup S h u a Δ D Y w B'} {R : Rotor F Y w} + {fit : U.Fits R c} {fit' : V.Fits R c} {e cap m d : ℕ} + {b : Book S u e cap} + (A : Allocation U.post (U.result R fit) (b.scheme m d a)) + (A' : Allocation V.post (V.result R fit') (b.scheme m d a)) + (Q : Relation U V) (σ : Cell a) (v : U.G.V) (z : V.G.V) (n : ℕ) + +open scoped Classical in +/-- The data for the corresponds construction, including `region`, `depth`, `root`, `tags`, +`block`. -/ +structure Corresponds : Prop where + region : Region U V σ Q n + depth : h - a + 4 ≤ n + root : Q 0 v z + tags : ∀ i j, Q 1 i j → U.Tags V σ i j + block : U.post.block = V.post.block + left : Ranked A + right : Ranked A' + index : IndexAgrees A A' Q σ v z + +namespace Corresponds +variable {A A' Q σ v z n} (p : Corresponds A A' Q σ v z n) {loc : Coord R h a Δ} + {i : U.Seen R fit σ v loc} {j : V.Seen R fit' σ z loc} +include p + +open scoped Classical in +theorem at_root : U.Tags V σ v z := p.tags _ _ (p.region.widen (by omega) p.root) + +open scoped Classical in +theorem seat (he : U.visibleKey R fit σ v loc i = V.visibleKey R fit' σ z loc j) : + A.seat _ i = A'.seat _ j := + p.region.seat (k := 0) (by have := p.depth; omega) p.root p.at_root p.left p.right he + +open scoped Classical in +theorem header (he : U.visibleKey R fit σ v loc i = V.visibleKey R fit' σ z loc j) + (hw : visibleWidth U.post (U.result R fit) i.val + = visibleWidth V.post (V.result R fit') j.val) : + A.header (b.size U.post (U.result R fit)) i.val + = A'.header (b.size V.post (V.result R fit')) j.val ∧ + facePointer U.post (U.result R fit) i.val = facePointer V.post (V.result R fit') j.val := by + have hb := congrArg b.put hw + change b.size _ _ i.val = b.size _ _ j.val at hb + rcases i with ⟨s|⟨s, t⟩, hs⟩ <;> rcases j with ⟨r|⟨r, t'⟩, hr⟩ + · obtain ⟨hx, hy⟩ := PortId.border.inj he + have hy := Fin.ext hy + obtain ⟨hg, hv⟩ := owner_here hs + obtain ⟨_, hz⟩ := owner_here hr + have hdr : S.direction U.r (U.post.vertex s.val.1, s.val.2) = + S.direction V.r (V.post.vertex r.val.1, r.val.2) := by + rw [U.post.vertex_eq, V.post.vertex_eq] + change (U.pat _ _).direction 0 _ = (V.pat _ _).direction 0 _ + rw [hv, hz, ← hx, hy] + unfold pat + rw [p.at_root _ hg] + constructor + · simp only [Allocation.header, hdr, hb] + · simp only [facePointer, stub, U.post.vertex_eq, V.post.vertex_eq, p.block, hx, hy] + · cases he + · cases he + · obtain ⟨_, rfl, hn⟩ := PortId.line.inj he + obtain ⟨hseat, hindex⟩ := p.region.link p.depth p.root p.tags p.left p.right p.index + (raw_at.mp hs) (raw_at.mp hr) hn + exact ⟨by simp only [Allocation.header, hb, hseat, hindex], rfl⟩ + +end Corresponds +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Serializing matched local fields and pointers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring BatchDescent.Trail + +variable {F : Type} [Field F] [Fintype F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] {U V : Setup S h u a Δ D Y w B'} {R : Rotor F Y w} + {fit : U.Fits R c} {fit' : V.Fits R c} {e cap m d : ℕ} + {b : Book S u e cap} + (A : Allocation U.post (U.result R fit) (b.scheme m d a)) + (A' : Allocation V.post (V.result R fit') (b.scheme m d a)) + +open scoped Classical in +private theorem span_at (x : U.At R fit) (j : Visible U.post (U.result R fit) x) : + A.span j.val = (A.vertex x, A.seat x j) := + Prod.ext (congrArg A.vertex j.property) (A.slot_eq _ j) + +open scoped Classical in +private theorem unused_at (x : U.At R fit) {s : B e} (hs : s ∉ Set.range (A.seat x)) : + (A.vertex x, s) ∉ Set.range A.span := by + rintro ⟨j, he⟩ + have hv : whereAt U.post (U.result R fit) j = x := A.vertex.injective (Prod.mk.inj he).1 + exact hs ⟨⟨j, hv⟩, (A.slot_eq x ⟨j, hv⟩).symm.trans (Prod.mk.inj he).2⟩ + +variable (parent : B m → B S.m) + +open scoped Classical in +/-- The value specified by `(A.move parent).commands (A.host x.2) (A.block x.1)`. -/ +def localPointers (x : U.At R fit) := (A.move parent).commands (A.host x.2) (A.block x.1) + +variable {A A'} {Q : Relation U V} {σ : Cell a} {v : U.G.V} {z : V.G.V} {n : ℕ} + (p : Corresponds A A' Q σ v z n) (loc : Coord R h a Δ) +local notation "src" => U.station R fit σ v loc +local notation "dst" => V.station R fit' σ z loc + +include p in +open scoped Classical in +private theorem slot_value (s : B e) : + A.fields (b.size _ _) src s = A'.fields (b.size _ _) dst s ∧ + (A.move parent).read (A.vertex src, s) = (A'.move parent).read (A'.vertex dst, s) := by + obtain ⟨f, hf⟩ := p.region.visible (k := 0) (fit := fit) (fit' := fit') (loc := loc) + (by have := p.depth; omega) p.root p.at_root + have hs (i) : A.seat src i = A'.seat dst (f i) := p.seat (hf i).1.symm + by_cases h : s ∈ Set.range (A.seat src) + · obtain ⟨i, rfl⟩ := h + obtain ⟨hh, hp⟩ := p.header (hf i).1.symm (hf i).2.symm + constructor + · rw [Allocation.fields, Allocation.fields, (A.seat _).injective.extend_apply, hs, + (A'.seat _).injective.extend_apply] + exact hh + · rw [← span_at, Allocation.read_span, hs, ← span_at, Allocation.read_span] + exact hp + have h' : s ∉ Set.range (A'.seat dst) := by + rintro ⟨j, rfl⟩ + exact h ⟨f.symm j, by rw [hs, f.apply_symm_apply]⟩ + constructor + · rw [Allocation.fields, Allocation.fields, Function.extend_apply' _ _ _ h, + Function.extend_apply' _ _ _ h'] + · rw [A.read_idle _ _ (unused_at A _ h), A'.read_idle _ _ (unused_at A' _ h')] + +include p in +open scoped Classical in +theorem Corresponds.pointers : localPointers A parent src = localPointers A' parent dst := by + funext j s + have : j = 0 := Fin.eq_zero _ + subst j + exact congrArg (point S) (slot_value parent p loc s).2 + +include p in +open scoped Classical in +theorem Corresponds.tag (nav nav' : B m → B d → B m) + (payload : b.data A src = b.data A' dst) : + (b.output A nav (A.host (src).2)).2 (A.block (src).1) = + (b.output A' nav' (A'.host (dst).2)).2 (A'.block (dst).1) := by + change (Post.record d e b.d (.addr cap)).serial + (A.records _ _ (A.vertex src).1 (A.vertex src).2.1) = + (Post.record d e b.d (.addr cap)).serial (A'.records _ _ (A'.vertex dst).1 (A'.vertex dst).2.1) + rw [Allocation.record_at, Allocation.record_at] + have hh := funext fun s => (slot_value (fun _ => 0) p loc s).1 + simp only [Allocation.localRecord, hh, payload] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The output template shared by all branches of a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Packing History + +variable {F : Type} [Field F] [Fintype F] {Y l u e cap : ℕ} + +/-- Builds `Template F where scheme` with the specified `scheme`, `count`, `load`, `park`. -/ +abbrev resetTarget (T : Template F) (b : Reset.Book T.scheme u e cap) (M : Meter) + (m d a : ℕ) : Template F where + scheme := b.scheme m d a + count := M.count + load := M.load + park := M.park + past := M.past + order := Post.order d e b.d cap + full := T.full + +/-- The value specified by `T.resetTarget b M (T.scheme.m + Reset.Child.extra P Δ (T.scheme.h - +a)) (Reset.Child.width D Y T.full) a`. -/ +abbrev reset (T : Template F) (P : Rotor F Y l) (Δ D a : ℕ) + (b : Reset.Book T.scheme u e cap) (M : Meter) : Template F := + T.resetTarget b M (T.scheme.m + Reset.Child.extra P Δ (T.scheme.h - a)) + (Reset.Child.width D Y T.full) a + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Combining local reset histories and the common graph header -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U : Setup A.scheme A.scheme.h u a Δ D Y w B') (R : Rotor F Y w) + (fit : U.Fits R c) {e cap : ℕ} (b : Book A.scheme u e cap) (M : Template.Meter) + +variable {mx dx : ℕ} +local notation "E" => (A.resetTarget b M mx dx a) + +open scoped Classical in +/-- Computes the layout by the application `Allocation U.post (U.result R fit) (b.scheme mx dx +a)`. -/ +abbrev Layout (mx dx : ℕ) := Allocation U.post (U.result R fit) (b.scheme mx dx a) + +variable {U R fit b} (L : U.Layout R fit b mx dx) (g : (Child.Graph mx dx).obj) + +open scoped Classical in +theorem hop (h : Child.Describes (m := mx) (d := dx) A.full (U.graph R fit) L.host L.index g) + (i : (U.result R fit).Survivors) (t : Bool) : + let src := Allocation.endHost (q := U.result R fit) i t + let dst := Allocation.endHost (q := U.result R fit) i (!t) + g.1 (L.host src) (L.index src dst) = L.host dst := by + apply h.hop + cases t + · exact (U.graph R fit).edge i + · exact (U.graph R fit).cs _ _ ((U.graph R fit).edge i) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def counters (i : B mx) (j : B a) : B M.count := + Function.extend L.host (fun v => M.read (U.graph R fit) (v, (cellIndex a).symm j)) (fun _ => 0) i + +open scoped Classical in +/-- The indexed operation `(b.output (m := mx) (d := dx) (h' := a) L g.1, fun i => ((g.2 i).1, +(g.2 i).2, counters M L i))`. -/ +def printed : (E).format.obj := + (b.output (m := mx) (d := dx) (h' := a) L g.1, fun i => ((g.2 i).1, (g.2 i).2, counters M L i)) + +open scoped Classical in +theorem printed_header : Tile.header E (printed M L g) = g := rfl + +open scoped Classical in +theorem counter_at (v : (U.graph R fit).V) (i : Cell a) : + (E).counter (printed M L g) (L.host v) (cellIndex a i) = M.read (U.graph R fit) (v, i) := by + change counters M L _ _ = _ + refine (L.host.injective.extend_apply _ _ _).trans ?_ + exact congrArg (fun j => M.read (U.graph R fit) (v, j)) ((cellIndex a).symm_apply_apply i) + +open scoped Classical in +/-- Uses `H.posting` as the representation. -/ +def outputEncodes (H : b.Ready (m := mx) (d := dx) (h' := a) L g.1) (blk : L.block + = (cellIndex a).toEmbedding) + (head : Child.Describes (m := mx) (d := dx) A.full (U.graph R fit) L.host L.index g) + (meter : M.Valid (U.graph R fit)) : + (E).Encodes (printed M L g) (U.graph R fit) where + post := H.posting + block i := congrArg (fun f => f i) blk + live := head.live + frozen := head.frozen + closed := head.closed + reciprocal := head.reciprocal + edge := head.edge + core := head.core + load v i := by + change M.load ((E).counter _ (L.host v) (L.block i)) = _ + rw [blk, Equiv.toEmbedding_apply, counter_at] + exact (meter (v, i)).1 + park v i := by + change M.park ((E).counter _ (L.host v) (L.block i)) = _ + rw [blk, Equiv.toEmbedding_apply, counter_at] + exact (meter (v, i)).2.1 + past v i := by + change M.past ((E).counter _ (L.host v) (L.block i)) = _ + rw [blk, Equiv.toEmbedding_apply, counter_at] + exact (meter (v, i)).2.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The static parent of each reset station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring +variable {F : Type} [Field F] [Fintype F] (A : Template F) {u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] {U : Setup A.scheme A.scheme.h u a Δ D Y w B'} {R : Rotor F Y w} + {fit : U.Fits R c} {e cap t d : ℕ} {b : Book A.scheme u e cap} + (L : U.Layout R fit b (A.scheme.m + t) d) (locate : Coord R A.scheme.h a Δ ↪ B t) + +open scoped Classical in +/-- The data for the placed construction, including `block`, `host`. -/ +structure Placed : Prop where + block : L.block = (cellIndex a).toEmbedding + host : ∀ σ v loc, L.host (U.station R fit σ v loc).2 = + (Match.rowIndex A.scheme.m t).symm (U.post.host v, locate loc) + +open scoped Classical in +/-- The value specified by `(Match.rowIndex A.scheme.m t j).1`. -/ +abbrev parent (t : ℕ) (j : B (A.scheme.m + t)) := (Match.rowIndex A.scheme.m t j).1 + +variable {A L locate} (p : Placed A L locate) + +omit [Fintype F] in +open scoped Classical in +theorem station_owner (U : Setup A.scheme A.scheme.h u a Δ D Y w B') (R : Rotor F Y w) + (fit : U.Fits R c) (σ : Cell a) (v : U.G.V) (loc : Coord R A.scheme.h a Δ) : + (U.result R fit).origin (U.station R fit σ v loc).2 = v := by + cases loc <;> rfl + +include p in +open scoped Classical in +theorem Placed.parent (w : (U.result R fit).vertex) : + parent A t (L.host w) = U.post.host ((U.result R fit).origin w) := by + obtain ⟨⟨σ, v, loc⟩, he⟩ := (U.place R fit).symm.surjective (0, w) + have hw : (U.station R fit σ v loc).2 = w := congrArg Prod.snd he + rw [← hw, p.host, station_owner] + exact congrArg Prod.fst ((Match.rowIndex _ _).apply_symm_apply _) + +include p in +open scoped Classical in +theorem Placed.live (v : B A.scheme.m) (s : B t) : + (Match.rowIndex _ _).symm (v, s) ∈ Set.range L.host ↔ + v ∈ Set.range U.post.host ∧ s ∈ Set.range locate := by + constructor + · rintro ⟨w, hw⟩ + obtain ⟨⟨σ, z, loc⟩, he⟩ := (U.place R fit).symm.surjective (0, w) + have hz : (U.station R fit σ z loc).2 = w := congrArg Prod.snd he + rw [← hz, p.host] at hw + obtain ⟨hv, hs⟩ := Prod.mk.inj ((Match.rowIndex _ _).symm.injective hw) + exact ⟨⟨z, hv⟩, ⟨loc, hs⟩⟩ + · rintro ⟨⟨i, rfl⟩, ⟨j, rfl⟩⟩ + exact ⟨(U.station R fit 0 i j).2, p.host ..⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Placing the reset hardware and successively numbering its spans -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Coloring Packing + +variable {F : Type} [Field F] [Fintype F] {A : Template F} {u a Δ D Y w k : ℕ} {W cost : ℝ} + [NeZero Y] [NeZero w] (U : Setup A.scheme A.scheme.h u a Δ D Y w W) + (R : Rotor F Y w) (fit : U.Fits R cost) + {e cap d : ℕ} (b : Book A.scheme u e cap) +local notation "t" => (Child.extra R Δ (A.scheme.h - a)) +local notation "mx" => (A.scheme.m + t) +variable (index : (U.graph R fit).V → (U.graph R fit).V → B d) + (room : U.Room R fit (b.scheme (A.scheme.m + Child.extra R Δ (A.scheme.h - a)) d a)) + +open scoped Classical in +/-- Computes the arrange by the application `U.allocate R fit (b.scheme mx d a) (U.host R fit) +(cellIndex a).toEmbedding index room`. -/ +def arrange : U.Layout R fit b mx d := + U.allocate R fit (b.scheme mx d a) (U.host R fit) (cellIndex a).toEmbedding index room + +omit [Fintype F] in +open scoped Classical in +theorem station_parts (σ : Cell a) (v : U.G.V) (loc : Coord R A.scheme.h a Δ) : + U.parts R fit (U.station R fit σ v loc).2 = (v, loc) := + (U.parts R fit).apply_symm_apply _ + +open scoped Classical in +theorem arrange_placed : Placed A (U.arrange R fit b index room) (Child.code R Δ (A.scheme.h - a)) + := by + refine ⟨rfl, fun σ v loc => ?_⟩ + change U.host R fit _ = _ + exact congrArg (fun x => (Match.rowIndex _ _).symm + (U.post.host x.1, Child.code R Δ (A.scheme.h - a) x.2)) (station_parts U R fit σ v loc) + +open scoped Classical in +theorem arrange_ranked : Ranked (U.arrange R fit b index room) := fun _ => rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Raw/Local.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Raw/Local.lean new file mode 100644 index 0000000000..174192492a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Raw/Local.lean @@ -0,0 +1,1029 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Routes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Prefix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Repost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Move + +/-! # Consistency of the reserved slot of a matched good unit -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing Coloring +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + {U V : Setup S h u a Δ D Y w B'} {σ : Cell a} {v : U.G.V} {z : V.G.V} + {t : Bool} {e : U.G.E} {f : V.G.E} + +open scoped Classical in +private theorem addr_aux {i j : ℕ} (hi : i ≤ h) (hj : j ≤ h) (p q : Cell h) (he : i = j) (hp : p + = q) : + (⟨i, ancestor hi p⟩ : Chart.Address) = ⟨j, ancestor hj q⟩ := by cases he; cases hp; rfl + +open scoped Classical in +theorem Agree.address (c : Agree U V σ v z) (r : Related U V v z t e f) + (he : Scheme.side U.G e t = v) (hf : Scheme.side V.G f t = z) : + Chart.address (U.Z.link e) = Chart.address (V.Z.link f) := by + have hd := (c.contact r he hf).1.depth + have hm : U.Z.π (U.G.ix e) = V.Z.π (V.G.ix f) := by rw [c.mix, r.ix] + exact addr_aux _ _ _ _ hd hm + +open scoped Classical in +private theorem drop_addr {k l : ℕ} (b : ℕ) (hg : l = k - b) (x : Cell k) : + (⟨l, fun i => suffix b x (Fin.cast hg i)⟩ : Chart.Address) = ⟨k - b, suffix b x⟩ := by + subst l; rfl + +open scoped Classical in +theorem Agree.drop_address (c : Agree U V σ v z) (r : Related U V v z t e f) + (he : Scheme.side U.G e t = v) (hf : Scheme.side V.G f t = z) : + Chart.address (dropContact a (U.Z.link e)) = Chart.address (dropContact a (V.Z.link f)) := by + let d (p : Chart.Address) : Chart.Address := ⟨p.1 - a, suffix a p.2⟩ + calc + _ = d (Chart.address (U.Z.link e)) := drop_addr a _ _ + _ = d (Chart.address (V.Z.link f)) := congrArg d (c.address r he hf) + _ = _ := (drop_addr a _ _).symm + +open scoped Classical in +/-- Computes the fiber by the application `Dispatch.LinkFiber U.Z.good U.Z.link (U.Z.link e)`. -/ +abbrev Fiber (U : Setup S h u a Δ D Y w B') (e : U.G.E) := + Dispatch.LinkFiber U.Z.good U.Z.link (U.Z.link e) + +open scoped Classical in +private theorem Agree.link_maps (c : Agree U V σ v z) (r : Related U V v z t e f) + (he : Scheme.side U.G e t = v) (hf : Scheme.side V.G f t = z) + (hg : U.Z.good e) (hs : U.Z.group (U.G.ix e) = σ) (p : U.Fiber e) : + ∃ q : V.Fiber f, linkName U.post p.val.val = linkName V.post q.val.val := by + obtain ⟨⟨b, hb⟩, hl⟩ := p + change U.Z.link b = U.Z.link e at hl + have hc : U.contact b = U.contact e := congrArg Sigma.fst hl + have hroot : Scheme.side U.G b t = v := by rw [← U.ends, hc, U.ends, he] + have hleaf : U.Z.leaf ((demands U.G).point b t) = U.Z.leaf ((demands U.G).point e t) := by + rw [U.Z.routes b hb, U.Z.routes e hg, hl] + have hgroup : U.Z.group (U.G.ix b) = σ := by + exact ((U.Z.group_end b t).symm.trans ((congrArg (Site.group a) hleaf).trans + (U.Z.group_end e t))).trans hs + obtain ⟨j, hj, hroot', r'⟩ := c.fwd b t hb hgroup hroot + have heq : V.Z.link j = V.Z.link f := by + apply Chart.address_inj + · change V.contact j = V.contact f + apply unique_contact ((V.ends j t).trans hroot') ((V.ends f t).trans hf) + rw [V.ends, V.ends, ← r'.label, ← r.label, ← U.ends, ← U.ends, hc] + · rw [← c.address r' hroot hroot', ← c.address r he hf, hl] + exact ⟨⟨⟨j, hj⟩, heq⟩, r'.name false⟩ + +variable [NeZero Y] [NeZero w] + +open scoped Classical in +theorem Agree.slot (c : Agree U V σ v z) (r : Related U V v z t e f) + (he : Scheme.side U.G e t = v) (hf : Scheme.side V.G f t = z) + (hg : U.Z.good e) (hg' : V.Z.good f) (hs : U.Z.group (U.G.ix e) = σ) : + (U.delivery.slot ⟨e, hg⟩).val = (V.delivery.slot ⟨f, hg'⟩).val := by + have hs' : V.Z.group (V.G.ix f) = σ := by rw [← r.ix, ← c.group, hs] + let i : U.Fiber e := ⟨⟨e, hg⟩, rfl⟩ + let j : V.Fiber f := ⟨⟨f, hg'⟩, rfl⟩ + have h₁ := linkName_inj U.post U.hu U.Z (U.Z.link e) + have h₂ := linkName_inj V.post V.hu V.Z (V.Z.link f) + obtain ⟨p, hp⟩ := Dispatch.equivalent _ _ h₁ h₂ (c.link_maps r he hf hg hs) + (c.symm.link_maps r.symm hf he hg' hs') + have hij : p i = j := h₂ ((hp i).trans (r.name false)) + have heq := U.local_delivery.slot_congr V.local_delivery p hp (c.contact r he hf).2 i + rw [hij] at heq + exact heq + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # A reset label consists of span headers and one encoded contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Coloring +variable {F : Type} [Field F] {m d h e ℓ cap : ℕ} + +/-- Outside the stated span length the decoder sees zeros. -/ +def totalize (w : B e → ℕ) (x : Positions w → Bool) (s : B e) (i : ℕ) := + if H : i < w s then x ⟨s, ⟨i, H⟩⟩ else false + +/-- Builds `Pattern F d 0 e where width _ t` with the specified `width`, `direction`, `peer`, +`value`. -/ +def pattern (len : B ℓ → ℕ) (decode : B cap → (B e → ℕ → Bool) → F) + (r : (Post.record d e ℓ (.addr cap)).obj) : Pattern F d 0 e where + width _ t := len (r.2.1 t).1 + direction _ t := (r.2.1 t).2.1 + peer _ t := if (r.2.1 t).2.2.1 then some ((r.2.1 t).2.2.2.1, 0, (r.2.1 t).2.2.2.2) else none + value _ x := if r.1 then decode r.2.2 + (totalize (fun t => len (r.2.1 t).1) (fun i => x i.1 i.2)) else 1 + +/-- The value specified by `⟨m, d, h, 0, e, Post.width d e ℓ cap, pattern len decode ∘ +(Post.record d e ℓ (.addr cap)).serial.symm⟩`. -/ +abbrev scheme (m d h e ℓ cap : ℕ) (len : B ℓ → ℕ) (decode : B cap → (B e → ℕ → Bool) → F) : Scheme + F := + ⟨m, d, h, 0, e, Post.width d e ℓ cap, pattern len decode ∘ (Post.record d e ℓ (.addr + cap)).serial.symm⟩ + +variable (len : B ℓ → ℕ) (decode : B cap → (B e → ℕ → Bool) → F) +local notation "U" => scheme m d h e ℓ cap len decode + +theorem table_eq (out : (U).format.obj) (v : (U).Vtx) (r : (Post.record d e ℓ (.addr cap)).obj) + (hr : (U).pattern out v = pattern len decode r) (x : (U).LocalPin out v → Bool) : + (U).table out v x = if r.1 then + decode r.2.2 (totalize (fun t => (U).width out (v, t)) x) else 1 := by + have eq (P : Pattern F d 0 e) (he : P = pattern len decode r) (j : B 0) + (z : Positions (P.width j) → Bool) : + P.value j (fun s i => z ⟨s, i⟩) = + if r.1 then decode r.2.2 (totalize (P.width j) z) else 1 := by + subst P + rfl + exact eq _ hr _ x + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Dictionaries shared by all occurrences in one reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +open Coloring Packing + +variable {F : Type} (S : Scheme F) (u e cap : ℕ) + +open scoped Classical in +/-- The data for the book construction, including `ord`, `d`, `len`, `put`, `zero`. -/ +structure Book (S : Scheme F) (u e cap : ℕ) where + /-- Reindexes the data using `B S.ℓ ≃ B S.ℓ`. -/ + ord : B S.ℓ ≃ B S.ℓ + /-- The `Book` field of type `ℕ`. -/ + d : ℕ + /-- The `Book` component of type `B d → ℕ`. -/ + len : B d → ℕ + /-- The `Book` component of type `ℕ → B d`. -/ + put : ℕ → B d + zero : len 0 = 0 + unit : len (put u) = u + +namespace Book + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev lenBits (W : Finset ℕ) := History.lengthBits W + +open scoped Classical in +theorem dictionary (W : Finset ℕ) : + ∃ f : (ℕ → B (lenBits W)) × (B (lenBits W) → ℕ), f.2 0 = 0 ∧ + f.2 (f.1 u) = u ∧ ∀ j ∈ W, f.2 (f.1 j) = j := by + let U := insert 0 (insert u W) + have hc : U.card ≤ W.card + 3 := + ((Finset.card_insert_le _ _).trans (Nat.succ_le_succ (Finset.card_insert_le _ _))).trans + (Nat.le_succ _) + obtain ⟨table, zero, decode⟩ := History.length_dictionary U (by simp [U]) + (hc.trans (Nat.le_pow_clog (by decide) _)) + exact ⟨table, zero, decode _ (by simp [U]), fun j hj => decode j (by simp [U, hj])⟩ + +variable (ord : B S.ℓ ≃ B S.ℓ) (W : Finset ℕ) + +open scoped Classical in +/-- Builds `Book S u e cap where ord` with the specified `ord`, `len`, `put`, `zero`. -/ +def make : Book S u e cap where + ord := ord + d := lenBits W + len := (dictionary u W).choose.2 + put := (dictionary u W).choose.1 + zero := (dictionary u W).choose_spec.1 + unit := (dictionary u W).choose_spec.2.1 + +open scoped Classical in +theorem represent {j : ℕ} (hj : j ∈ W) : + let b := make S u e cap ord W + b.len (b.put j) = j := + (dictionary u W).choose_spec.2.2 _ hj + +variable {S u e cap} [Field F] [Fintype F] (b : Book S u e cap) + +open scoped Classical in +/-- The value specified by `Reset.scheme m' d' h' e b.d cap b.len (decoder b.ord u cap)`. -/ +abbrev scheme (m' d' h' : ℕ) := + Reset.scheme m' d' h' e b.d cap b.len (decoder b.ord u cap) + +variable {T : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} {h a : ℕ} + {G : HostNet F L h u} {r : S.format.obj} (p : S.Posting r G) + {B' W' : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W' Hcap D) + +open scoped Classical in +/-- The value specified by `b.put ∘ visibleWidth p q`. -/ +def size : Face p q → B b.d := b.put ∘ visibleWidth p q + +open scoped Classical in +/-- Computes the payload by the application `canonical b.ord u cap (localEval p q v seat)`. -/ +def payload (v : Cell a × q.vertex) (seat : Visible p q v ↪ B e) : B cap := + canonical b.ord u cap (localEval p q v seat) + +end Book +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Matching reset deliveries on corresponding leaves -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing Coloring +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + (U : Setup S h u a Δ D Y w B') (v : U.G.V) (x : Schedule.Address h) + +open scoped Classical in +/-- The value specified by `Dispatch.Base U.Z.leaf (v, x)`. -/ +abbrev Occ := Dispatch.Base U.Z.leaf (v, x) +open scoped Classical in +/-- The value specified by `GoodEnd U.Z.leaf (demands U.G).point U.Z.good (v, x)`. -/ +abbrev End := GoodEnd U.Z.leaf (demands U.G).point U.Z.good (v, x) + +open scoped Classical in +theorem end_root (q : U.End v x) : Scheme.side U.G q.val.1.val q.val.2 = v := + (point_side ..).symm.trans (congrArg (fun y : Site U.G.V h => y.1) q.2) + +open scoped Classical in +theorem end_group (q : U.End v x) : + U.Z.group (U.G.ix q.val.1.val) = Site.group a (v, x) := + (U.Z.group_end ..).symm.trans (congrArg (Site.group a) q.2) + +variable [NeZero Y] [NeZero w] + +open scoped Classical in +/-- The value specified by `Dispatch.site U.delivery (occName (G := U.G)) (endName U.post) (v, +x)`. -/ +def data : Dispatch.Site (U.Occ v x) (U.End v x) Y := + Dispatch.site U.delivery (occName (G := U.G)) (endName U.post) (v, x) + +open scoped Classical in +private def port (q : U.End v x) := + dropSlot a U.Z.lo (v, x) (portOf _ _ _ _ _ _ Y U.delivery.agree U.delivery.slot q) + +open scoped Classical in +private theorem port_key (q : U.End v x) : + U.chart.plugKey U.G.cs (relHi a U.Z.depth) U.Z.capacity _ (U.port v x q) = + (q.val.2, U.chart.label v (Scheme.side U.G q.val.1.val (!q.val.2)), + Chart.address (dropContact a (U.Z.link q.val.1.val)), (U.delivery.slot q.val.1).val) := by + rw [← U.ends] + rfl + +variable {U v x} {V : Setup S h u a Δ D Y w B'} {σ : Cell a} {z : V.G.V} + (c : Agree U V σ v z) (hx : Site.group a (v, x) = σ) + +include c hx in +open scoped Classical in +theorem Agree.output {q : U.End v x} {q' : V.End z x} + (ht : q.val.2 = q'.val.2) (r : Related U V v z q.val.2 q.val.1.val q'.val.1.val) : + (U.data v x).output q = (V.data z x).output q' := by + have he := U.end_root v x q + have hf := V.end_root z x q' + rw [← ht] at hf + have haddr := c.drop_address r he hf + have hslot := c.slot r he hf q.val.1.property q'.val.1.property ((U.end_group v x q).trans hx) + have hp : U.chart.plugKey U.G.cs (relHi a U.Z.depth) U.Z.capacity _ (U.port v x q) = + V.chart.plugKey V.G.cs (relHi a V.Z.depth) V.Z.capacity _ (V.port z x q') := by + rw [port_key, port_key, ← ht, r.label, haddr, hslot] + exact U.chart.plugs_eq U.G.cs (relHi a U.Z.depth) U.Z.capacity + V.chart V.G.cs (relHi a V.Z.depth) V.Z.capacity c.relative c.symm.relative + U.bound V.bound (Site.drop a (v, x)).2 (U.port v x q) (V.port z x q') hp + +include c hx in +open scoped Classical in +private theorem Agree.occ_map (p : U.Occ v x) : + ∃ p' : V.Occ z x, (U.data v x).occurrence p = (V.data z x).occurrence p' ∧ + (U.data v x).load p = (V.data z x).load p' := by + obtain ⟨⟨t, j⟩, he⟩ := p + have ht : t = v := congrArg (fun p : Site U.G.V h => p.1) he + subst t + have hj : U.Z.group j = σ := (U.Z.leaf_group (v, j)).symm.trans + ((congrArg (Site.group a) he).trans hx) + have hy := (c.leaf j hj).symm.trans (congrArg Prod.snd he) + exact ⟨⟨(z, j), Prod.ext rfl hy⟩, rfl, congrArg (· / B') (c.load j hj)⟩ + +include c hx in +omit [NeZero Y] [NeZero w] in +open scoped Classical in +theorem Agree.end_map (p : U.End v x) : + ∃ q : V.End z x, p.val.2 = q.val.2 ∧ Related U V v z p.val.2 p.val.1.val q.val.1.val := by + have hv := U.end_root v x p + have hs := (U.end_group v x p).trans hx + obtain ⟨f, hf, hz, hr⟩ := c.fwd _ _ p.val.1.property hs hv + have he : (demands U.G).point p.val.1.val p.val.2 = (v, U.G.ix p.val.1.val) := + Prod.ext ((point_side ..).trans hv) rfl + have he' : (demands V.G).point f p.val.2 = (z, U.G.ix p.val.1.val) := + Prod.ext ((point_side ..).trans hz) hr.ix.symm + have hleaf : V.Z.leaf ((demands V.G).point f p.val.2) = (z, x) := by + rw [he'] + apply Prod.ext + · rfl + rw [← c.leaf _ hs, ← he, p.2] + exact ⟨⟨(⟨f, hf⟩, p.val.2), hleaf⟩, rfl, hr⟩ + +open scoped Classical in +private def occKey (U : Setup S h u a Δ D Y w B') (v : U.G.V) (x : Schedule.Address h) + (p : U.Occ v x) := ((U.data v x).occurrence p, (U.data v x).load p) + +open scoped Classical in +private def endKey (U : Setup S h u a Δ D Y w B') (v : U.G.V) (x : Schedule.Address h) + (p : U.End v x) := ((U.data v x).contact p, (U.data v x).input p, (U.data v x).output p) + +open scoped Classical in +private theorem occ_inj : Function.Injective (U.occKey v x) := + fun _ _ h => occName_inj U.Z (v, x) (Prod.mk.inj h).1 + +open scoped Classical in +private theorem end_inj : Function.Injective (U.endKey v x) := + fun _ _ h => endName_inj U.post U.hu U.Z (v, x) (Prod.mk.inj h).1 + +include c hx in +open scoped Classical in +private theorem Agree.endKey_map (p : U.End v x) : ∃ q : V.End z x, U.endKey v x p = V.endKey z x q + := by + obtain ⟨q, ht, hr⟩ := c.end_map hx p + refine ⟨q, Prod.ext ?_ (Prod.ext ?_ (c.output hx ht hr))⟩ + · change endName U.post _ _ = endName V.post _ _ + rw [← ht, hr.name] + · exact congrArg (fun j : Cell h => (cellIndex h j).val) hr.ix + +include c hx in +open scoped Classical in +/-- Matching sibling blocks and incident units identify all local +inputs to the deterministic routing schedule. -/ +theorem Agree.matching : + ∃ e : U.Occ v x ≃ V.Occ z x, ∃ f : U.End v x ≃ V.End z x, + Dispatch.Match (U.data v x) (V.data z x) e f := by + have hx' : Site.group a (z, x) = σ := hx + have ho := c.occ_map hx + have ho' := c.symm.occ_map hx' + obtain ⟨e, he⟩ := Dispatch.equivalent (U.occKey v x) (V.occKey z x) occ_inj occ_inj + (by simpa only [occKey, Prod.mk.injEq] using ho) (by simpa only [occKey, Prod.mk.injEq] + using ho') + obtain ⟨f, hf⟩ := Dispatch.equivalent (U.endKey v x) (V.endKey z x) end_inj end_inj + (c.endKey_map hx) (c.symm.endKey_map hx') + simp only [occKey, endKey, Prod.mk.injEq] at he hf + exact ⟨e, f, fun p => (he p).1, fun q => (hf q).1, fun p => (he p).2, + fun q => (hf q).2.1, fun q => (hf q).2.2⟩ + +include c hx in +open scoped Classical in +theorem Agree.route : Dispatch.schedule U.delivery (occName (G := U.G)) (endName U.post) (v, x) = + Dispatch.schedule V.delivery (occName (G := V.G)) (endName V.post) (z, x) := by + obtain ⟨e, f, he⟩ := c.matching hx + exact Dispatch.schedule_eq he + +include c hx in +open scoped Classical in +theorem Agree.layers : U.delivery.layers (v, x) = V.delivery.layers (z, x) := by + rw [U.local_delivery.layers_eq, V.local_delivery.layers_eq] + exact congrArg Dispatch.Route.layers (c.route hx) + +include c hx in +open scoped Classical in +theorem Agree.config (i : Fin (U.delivery.layers (v, x))) (j : Fin (V.delivery.layers (z, x))) + (hij : i.val = j.val) : U.delivery.config (v, x) i = V.delivery.config (z, x) j := by + rw [U.local_delivery.config_eq, V.local_delivery.config_eq, hij] + exact congrArg (fun r : Dispatch.Route Y w => r.config j.val) (c.route hx) + +include c hx in +open scoped Classical in +theorem Agree.lane {q : U.End v x} {q' : V.End z x} (ht : q.val.2 = q'.val.2) + (r : Related U V v z q.val.2 q.val.1.val q'.val.1.val) : + ((U.delivery.lane (v, x) q).1.val, (U.delivery.lane (v, x) q).2) = + ((V.delivery.lane (z, x) q').1.val, (V.delivery.lane (z, x) q').2) := by + rw [U.local_delivery.lane_eq, V.local_delivery.lane_eq, ← ht, r.name] + exact congrArg (fun k : Dispatch.Route Y w => k.lane (endName V.post q'.val.1.val q.val.2)) + (c.route hx) + +include c in +open scoped Classical in +theorem Agree.terminal (j : Cell h) (hj : U.Z.group j = σ) : + U.delivery.terminal (v, j) = V.delivery.terminal (z, j) := by + let x := (U.Z.leaf (v, j)).2 + let p : U.Occ v x := ⟨(v, j), rfl⟩ + let q : V.Occ z x := ⟨(z, j), Prod.ext rfl (c.leaf j hj).symm⟩ + have hx : Site.group a (v, x) = σ := (U.Z.leaf_group (v, j)).trans hj + change U.delivery.terminal p.val = V.delivery.terminal q.val + rw [U.local_delivery.terminal_eq (v, x) p, V.local_delivery.terminal_eq (z, x) q] + exact congrArg (fun k : Dispatch.Route Y w => k.terminal (cellIndex h j).val) (c.route hx) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Naming reset wires at each incident host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + (fit : U.Fits R c) + +open scoped Classical in +/-- The value specified by `U.Z.Wires (L := terminalWidth Δ Y) U.delivery R`. -/ +abbrev Raw := U.Z.Wires (L := terminalWidth Δ Y) U.delivery R +open scoped Classical in +/-- The quantity computed by `R.Host (Schedule.Address (h - a)) (terminalWidth Δ Y)`. -/ +abbrev Coord (R : Rotor F Y w) (h a Δ : ℕ) := R.Host (Schedule.Address (h - a)) (terminalWidth Δ Y) + +open scoped Classical in +/-- Reindexes `Cell a × (U.result R fit).vertex` and `Cell a × U.G.V × Coord R h a Δ` by an +equivalence. -/ +def place : Cell a × (U.result R fit).vertex ≃ Cell a × U.G.V × Coord R h a Δ := + (Equiv.refl _).prodCongr (Schedule.splitHost R a h _) + +open scoped Classical in +/-- Computes the raw place by the application `U.place R fit (cond t ((U.result R fit).supply +e).2 ((U.result R fit).supply e).1)`. -/ +def rawPlace (e : U.Raw R) (t : Bool) := + U.place R fit (cond t ((U.result R fit).supply e).2 ((U.result R fit).supply e).1) + +open scoped Classical in +/-- The raw id used in the `Setup` construction. -/ +inductive RawId (R : Rotor F Y w) (h : ℕ) where + | path (x : Schedule.Address h) (out : Bool) (step name : ℕ) + | layer (x : Schedule.Address h) (j : ℕ) (e : R.E) + | direct (name : ℕ) + | detour (step name : ℕ) + +open scoped Classical in +/-- In the case `.inl (j, q)`, this construction gives `.path x.2 false j.val (endName U.post +q.val.1.val q.val.2)`. -/ +def localKey (x : Site U.G.V h) : U.delivery.LocalWires R x → RawId R h + | .inl (j, q) => .path x.2 false j.val (endName U.post q.val.1.val q.val.2) + | .inr (.inl v) => .layer x.2 v.1.val v.2 + | .inr (.inr (j, q)) => .path x.2 true j.val (endName U.post q.val.1.val q.val.2) + +open scoped Classical in +/-- Returns `j + 1` when `t` holds, and `j` otherwise. -/ +def step (j : ℕ) (t : Bool) := if t then j + 1 else j + +open scoped Classical in +/-- In the case `.inl (.inl ⟨x, b⟩)`, this construction gives `U.localKey R x b`. -/ +def rawKey (e : U.Raw R) (t : Bool) : RawId R h := + match e with + | .inl (.inl ⟨x, b⟩) => U.localKey R x b + | .inl (.inr q) => .direct (endName U.post q.val t) + | .inr (j, q) => .detour j.val + (endName U.post q.val (Detour.Switch.side (terminalWidth Δ Y) (step j.val t))) + +open scoped Classical in +theorem local_place (x : Site U.G.V h) (b : U.delivery.LocalWires R x) (t : Bool) : + let p := R.supply (U.delivery.inputAt x) (U.delivery.outputAt x) (U.delivery.lane x) b + U.rawPlace R fit (.inl (.inl ⟨x, b⟩)) t = (x.group a, x.1, .inl ((x.drop a).2, cond t p.2 p.1)) + := by + cases t <;> rfl + +open scoped Classical in +theorem direct_place (q : {e // U.Z.good e}) (t : Bool) : + let x := U.Z.leaf ((demands U.G).point q.val t) + U.rawPlace R fit (.inl (.inr q)) t = (U.Z.group (U.G.ix q.val), Scheme.side U.G q.val t, + .inl ((x.drop a).2, R.root true (U.delivery.plug q t).2)) := by + have he : Site.group a (U.Z.leaf ((demands U.G).point q.val t)) = U.Z.group (U.G.ix q.val) := + U.Z.group_end q.val t + rw [← point_side, ← he] + cases t <;> rfl + +open scoped Classical in +/-- Uses `⟨terminalNear U.G.C Δ Y, terminal_symm U.G.cs _ _, U.pins⟩` as the representation. -/ +def switch : Detour.Switch (Site U.G.V (h - a) × Fin Y) (terminalWidth Δ Y) := + ⟨terminalNear U.G.C Δ Y, terminal_symm U.G.cs _ _, U.pins⟩ + +open scoped Classical in +/-- Computes the end term by the application `U.Z.terminal U.delivery ((demands U.G).point e +t)`. -/ +abbrev endTerm (e : U.G.E) (t : Bool) := U.Z.terminal U.delivery ((demands U.G).point e t) + +open scoped Classical in +theorem reaches (e : U.G.E) : U.endTerm e true ∈ U.switch.near (U.endTerm e false) := + Finset.mem_product.mpr ⟨U.Z.leaf_near U.G.cs U.G.sub (fun _ _ he => by simp [he]) + (U.G.edge e) (U.G.ix e), Finset.mem_univ _⟩ + +open scoped Classical in +/-- Computes the stop by the application `Schedule.splitHost R a h _ (R.hub (U.switch.path +(U.reaches e) j))`. -/ +def stop (e : U.G.E) (j : ℕ) : U.G.V × Coord R h a Δ := + Schedule.splitHost R a h _ (R.hub (U.switch.path (U.reaches e) j)) + +open scoped Classical in +theorem detour_place (j : Fin (Detour.steps (terminalWidth Δ Y))) (q : U.Z.Exceptional) (t : Bool) : + U.rawPlace R fit (.inr (j, q)) t = (U.Z.group (U.G.ix q.val), U.stop R q.val (step j.val t)) + := by + cases t <;> rfl + +open scoped Classical in +theorem stop_side (e : U.G.E) (j : ℕ) : + (U.stop R e j).1 = Scheme.side U.G e (Detour.Switch.side (terminalWidth Δ Y) j) := by + have h (x : Detour.Hub (Site U.G.V (h - a) × Fin Y) (terminalWidth Δ Y)) : + (Schedule.splitHost R a h _ (R.hub x)).1 = (Detour.owner x).1.1 := by cases x <;> rfl + unfold stop + rw [h, U.switch.path_owner] + cases Detour.Switch.side (terminalWidth Δ Y) j <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Uniqueness of raw supply names at a fixed host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing Coloring +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + +open scoped Classical in +theorem end_inj_at {e f : U.G.E} {t : Bool} (hz : Scheme.side U.G e t = Scheme.side U.G f t) + (hk : endName U.post e t = endName U.post f t) : e = f := by + obtain ⟨hi, hj⟩ := Prod.mk.inj (Encodable.encode_injective hk) + exact U.post.stub_unique U.hu _ _ t hz ((cellIndex h).injective hi) (Prod.mk.inj hj).1 + +variable [NeZero Y] [NeZero w] (fit : U.Fits R c) + +open scoped Classical in +private def category : RawId R h → Option (Schedule.Address h) ⊕ Unit + | .path x .. | .layer x .. => .inl (some x) + | .direct _ => .inl none + | .detour .. => .inr () + +open scoped Classical in +private theorem local_category (x : Site U.G.V h) (b : U.delivery.LocalWires R x) : + category R (U.localKey R x b) = .inl (some x.2) := by + rcases b with b|b|b <;> rfl + +open scoped Classical in +theorem localKey_injective (x : Site U.G.V h) : Function.Injective (U.localKey R x) := by + have he := endName_inj U.post U.hu U.Z x + rintro (⟨j, e⟩|⟨j, e⟩|⟨j, e⟩) (⟨k, f⟩|⟨k, f⟩|⟨k, f⟩) hk <;> + simp only [localKey, RawId.path.injEq, RawId.layer.injEq, eq_self, true_and, + reduceCtorEq, false_and] at hk + · rw [Fin.ext hk.1, he hk.2] + · rw [hk.2, Fin.ext hk.1] + · rw [Fin.ext hk.1, he hk.2] + +open scoped Classical in +/-- Together with the endpoint flag the local name distinguishes +all incident wires, including both ends of loops. -/ +theorem raw_inj {e f : U.Raw R} {t : Bool} + (hv : (U.rawPlace R fit e t).2.1 = (U.rawPlace R fit f t).2.1) + (he : U.rawKey R e t = U.rawKey R f t) : e = f := by + have hc := congrArg (category R) he + rcases e with (⟨x, e⟩|e)|⟨i, e⟩ <;> rcases f with (⟨y, f⟩|f)|⟨j, f⟩ <;> + simp only [rawKey, local_category] at hc <;> try {simp [category] at hc; done} + · rw [local_place, local_place] at hv + have hxy : x = y := Prod.ext hv (Option.some.inj (Sum.inl.inj hc)) + subst y + rw [U.localKey_injective R x he] + · rw [direct_place, direct_place] at hv + have : e = f := Subtype.ext (U.end_inj_at hv (RawId.direct.inj he)) + rw [this] + · obtain ⟨h, h'⟩ := RawId.detour.inj he + have heq := Fin.ext h + subst j + simp only [detour_place, stop_side] at hv + have : e = f := Subtype.ext (U.end_inj_at hv h') + rw [this] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Matching an old unit and the terminals at both ends -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + {U V : Setup S h u a Δ D Y w B'} {Q : Relation U V} {σ : Cell a} {k n : ℕ} + {e : U.G.E} {f : V.G.E} + +open scoped Classical in +/-- The data for the unit pair construction, including `ix`, `stub`, `hosts`, `group`, `good`. -/ +structure UnitPair (Q : Relation U V) (σ : Cell a) (k : ℕ) (e : U.G.E) (f : V.G.E) : Prop where + ix : U.G.ix e = V.G.ix f + stub : ∀ b, U.post.stub e b = V.post.stub f b + hosts : ∀ b, Q k (Scheme.side U.G e b) (Scheme.side V.G f b) + group : U.Z.group (U.G.ix e) = σ + good : U.Z.good e ↔ V.Z.good f + +open scoped Classical in +theorem Region.unit_pair (p : Region U V σ Q n) (hk : k + (h - a) + 2 ≤ n) + (e : U.G.E) (b : Bool) (z : V.G.V) (hg : U.Z.group (U.G.ix e) = σ) + (hr : Q k (Scheme.side U.G e b) z) : + ∃ f, Scheme.side V.G f b = z ∧ UnitPair Q σ (k + 1) e f := by + obtain ⟨f, hs, he, ho⟩ := p.fwd.hits _ _ _ hr (by omega) e b hg rfl + have ht : Q k (Scheme.side U.G e b) (Scheme.side V.G f b) := hs ▸ hr + refine ⟨f, hs, he.ix, he.stub, ?_, hg, p.toSurvey.good hk he.ix ht ho hg⟩ + intro t + by_cases h : t = b + · subst t; exact p.widen (by omega) ht + · have h' : t = !b := by cases b <;> cases t <;> first | rfl | contradiction + rwa [h'] + +open scoped Classical in +theorem point_eq (U : Setup S h u a Δ D Y w B') (e : U.G.E) (t : Bool) : + (demands U.G).point e t = (Scheme.side U.G e t, U.G.ix e) := + Prod.ext (point_side ..) rfl + +namespace UnitPair +variable (r : UnitPair Q σ k e f) (p : Region U V σ Q n) (hk : k + (h - a) + 2 ≤ n) + +include p r in +open scoped Classical in +theorem group' : V.Z.group (V.G.ix f) = σ := by rw [← r.ix, ← p.fwd.group, r.group] + +include r in +open scoped Classical in +theorem name (b : Bool) : endName U.post e b = endName V.post f b := by + rw [endName, endName, r.ix, r.stub] + +include p hk r in +open scoped Classical in +theorem related (b : Bool) : + Related U V (Scheme.side U.G e b) (Scheme.side V.G f b) b e f := + ⟨r.ix, r.stub, p.labels (by omega) (r.hosts b) (p.widen (by omega) (r.hosts (!b)))⟩ + +include p hk r in +open scoped Classical in +theorem leaf (b : Bool) : + (U.Z.leaf ((demands U.G).point e b)).2 = (V.Z.leaf ((demands V.G).point f b)).2 := by + rw [point_eq, point_eq, ← r.ix] + exact p.toSurvey.leaf (by omega) (r.hosts b) r.group + +variable [NeZero Y] [NeZero w] + +include p hk r in +open scoped Classical in +theorem terminal (b : Bool) : + U.delivery.terminal ((demands U.G).point e b) = + V.delivery.terminal ((demands V.G).point f b) := by + rw [point_eq, point_eq, ← r.ix] + exact (p.toSurvey.agree hk (r.hosts b)).terminal _ r.group + +include p hk r in +open scoped Classical in +theorem drop (b : Bool) : (U.endTerm e b).1.2 = (V.endTerm f b).1.2 := + congrArg (fun x => (Site.drop a ((), x)).2) (r.leaf p hk b) + +end UnitPair + +variable [NeZero Y] [NeZero w] + +open scoped Classical in +theorem endTerm_host (U : Setup S h u a Δ D Y w B') (e : U.G.E) (b : Bool) : + (U.endTerm e b).1.1 = Scheme.side U.G e b := point_side e b + +open scoped Classical in +private theorem output_plug {x : Site U.G.V h} + (t : GoodEnd U.Z.leaf (demands U.G).point U.Z.good x) : + U.delivery.outputAt x t = (U.delivery.plug t.val.1 t.val.2).2 := by + obtain ⟨⟨j, b⟩, rfl⟩ := t + rfl + +open scoped Classical in +theorem UnitPair.plug (r : UnitPair Q σ k e f) (p : Region U V σ Q n) (hk : k + (h - a) + 2 ≤ n) + (he : U.Z.good e) (hf : V.Z.good f) (b : Bool) : + (U.delivery.plug ⟨e, he⟩ b).2 = (V.delivery.plug ⟨f, hf⟩ b).2 := by + let v := Scheme.side U.G e b + let z := Scheme.side V.G f b + let x := (U.Z.leaf ((demands U.G).point e b)).2 + have h₁ : U.Z.leaf ((demands U.G).point e b) = (v, x) := Prod.ext (point_side ..) rfl + have h₂ : V.Z.leaf ((demands V.G).point f b) = (z, x) := + Prod.ext (point_side ..) (r.leaf p hk b).symm + let i : U.End v x := ⟨(⟨e, he⟩, b), h₁⟩ + let j : V.End z x := ⟨(⟨f, hf⟩, b), h₂⟩ + have hx : Site.group a (v, x) = σ := (U.end_group v x i).symm.trans r.group + have hh := (p.toSurvey.agree hk (r.hosts b)).output hx (q := i) (q' := j) rfl (r.related p hk b) + change U.delivery.outputAt _ i = V.delivery.outputAt _ j at hh + rwa [output_plug, output_plug] at hh + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Correspondence of rotor paths and layers within one leaf -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + [NeZero Y] [NeZero w] {U V : Setup S h u a Δ D Y w B'} {σ : Cell a} + {v : U.G.V} {z : V.G.V} {x : Schedule.Address h} + +open scoped Classical in +theorem Agree.input (c : Agree U V σ v z) (hx : Site.group a (v, x) = σ) + {q : U.End v x} {q' : V.End z x} (hi : U.G.ix q.val.1.val = V.G.ix q'.val.1.val) : + U.delivery.inputAt (v, x) q = V.delivery.inputAt (z, x) q' := by + unfold Delivery.inputAt + rw [point_eq, point_eq, U.end_root, V.end_root, ← hi] + exact c.terminal _ ((U.end_group v x q).trans hx) + +open scoped Classical in +/-- Computes the local supply by the application `R.supply (U.delivery.inputAt x) +(U.delivery.outputAt x) (U.delivery.lane x)`. -/ +def localSupply (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) (x : Site U.G.V h) := + R.supply (U.delivery.inputAt x) (U.delivery.outputAt x) (U.delivery.lane x) + +open scoped Classical in +theorem Agree.local_wire (c : Agree U V σ v z) (hx : Site.group a (v, x) = σ) + (R : Rotor F Y w) (e : U.delivery.LocalWires R (v, x)) : + ∃ f : V.delivery.LocalWires R (z, x), + U.localKey R (v, x) e = V.localKey R (z, x) f ∧ + U.localSupply R (v, x) e = V.localSupply R (z, x) f := by + have matchEnd (q : U.End v x) : ∃ q' : V.End z x, + endName U.post q.val.1.val q.val.2 = endName V.post q'.val.1.val q'.val.2 ∧ + (U.delivery.lane (v, x) q).2 = (V.delivery.lane (z, x) q').2 ∧ + U.delivery.inputAt (v, x) q = V.delivery.inputAt (z, x) q' ∧ + U.delivery.outputAt (v, x) q = V.delivery.outputAt (z, x) q' := by + obtain ⟨q', ht, hr⟩ := c.end_map hx q + refine ⟨q', ?_, (Prod.mk.inj (c.lane hx ht hr)).2, c.input hx hr.ix, c.output hx ht hr⟩ + rw [← ht, hr.name] + rcases e with ⟨i, q⟩ | ⟨i, q⟩ | ⟨i, q⟩ + · obtain ⟨p, hn, hl, hi, _⟩ := matchEnd q + refine ⟨.inl (i, p), ?_, ?_⟩ + · simp only [localKey, hn] + · simp only [localSupply, Rotor.supply, Sum.elim_inl, Rotor.pathEdge, hi, hl] + · refine ⟨.inr (.inl ⟨i.cast (c.layers hx), q⟩), rfl, rfl⟩ + · obtain ⟨p, hn, hl, _, ho⟩ := matchEnd q + refine ⟨.inr (.inr (i, p)), ?_, ?_⟩ + · simp only [localKey, hn] + · simp only [localSupply, Rotor.supply, Sum.elim_inr, Rotor.pathEdge, ho, hl] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Matching pins and stops on the two arms of a detour -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + {U V : Setup S h u a Δ D Y w B'} {Q : Relation U V} {σ : Cell a} {k n : ℕ} + {e : U.G.E} {f : V.G.E} + +open scoped Classical in +theorem Region.neighbors (p : Region U V σ Q n) (hk : k < n) + {v : U.G.V} {z : V.G.V} (hr : Q k v z) : U.chart.Maps V.chart v z := by + intro x hx + obtain ⟨c, hc, _, hl, _⟩ := p.fwd.siblings _ _ _ hr hk ⟨(v, x), hx⟩ false rfl + exact ⟨unitEnds c true, hc ▸ Chart.partner_mem V.G.cs c false, hl⟩ + +open scoped Classical in +/-- Indexes the terminal by the coordinates of `Site U.G.V (h - a) × Fin Y`. -/ +abbrev Terminal (U : Setup S h u a Δ D Y w B') := Site U.G.V (h - a) × Fin Y + +open scoped Classical in +/-- The value specified by `(x.1.2, x.2)`. -/ +def tipKey (x : U.Terminal) := (x.1.2, x.2) + +open scoped Classical in +theorem Region.pins_eq (p : Region U V σ Q n) (hk : k < n) + {x y : U.Terminal} {x' y' : V.Terminal} (hxy : y ∈ terminalNear U.G.C Δ Y x) + (hxy' : y' ∈ terminalNear V.G.C Δ Y x') + (hx : Q k x.1.1 x'.1.1) (hy : Q n y.1.1 y'.1.1) + (h₁ : tipKey x = tipKey x') (h₂ : tipKey y = tipKey y') : + U.pins x ⟨y, hxy⟩ = V.pins x' ⟨y', hxy'⟩ := by + rcases x with ⟨⟨v, a⟩, j⟩ + rcases x' with ⟨⟨v', b⟩, j'⟩ + obtain ⟨rfl, rfl⟩ := Prod.mk.inj h₁ + exact U.chart.treePin_eq V.chart (p.neighbors hk hx) (p.symm.neighbors hk hx) + U.hΔ U.deg V.deg _ _ _ _ (Prod.ext (p.labels hk hx hy) h₂) + +variable [NeZero Y] [NeZero w] (r : UnitPair Q σ k e f) (p : Region U V σ Q n) + (hk : k + (h - a) + 2 ≤ n) + +include r p hk in +open scoped Classical in +theorem UnitPair.tip (t : Bool) : tipKey (U.endTerm e t) = tipKey (V.endTerm f t) := + Prod.ext (r.drop p hk t) (r.terminal p hk t) + +open scoped Classical in +/-- The value specified by `U.pins (U.endTerm e b) ⟨U.endTerm e (!b), by cases b · exact +U.reaches e · exact U.switch.sym _ _ (U.reaches e)⟩`. -/ +def pinAt (U : Setup S h u a Δ D Y w B') (e : U.G.E) (b : Bool) := + U.pins (U.endTerm e b) ⟨U.endTerm e (!b), by + cases b + · exact U.reaches e + · exact U.switch.sym _ _ (U.reaches e)⟩ + +include r p hk in +open scoped Classical in +theorem UnitPair.pin (b : Bool) : U.pinAt e b = V.pinAt f b := by + unfold pinAt + apply p.pins_eq (k := k) (by omega) + · rw [endTerm_host, endTerm_host]; exact r.hosts b + · rw [endTerm_host, endTerm_host]; exact p.widen (by omega) (r.hosts (!b)) + · exact r.tip p hk b + · exact r.tip p hk (!b) + +variable (R : Rotor F Y w) +local notation "L" => terminalWidth Δ Y +local notation "m" => Nat.clog 2 L + +open scoped Classical in +private def arm (x : Schedule.Address (h - a) × Fin Y) (pin : Fin L) (k : ℕ) : Coord R h a Δ := + if k ≤ m then .inr (x, Tree.climb pin k) else .inl (x.1, R.root false x.2) + +open scoped Classical in +private theorem stop_coord (U : Setup S h u a Δ D Y w B') (e : U.G.E) (j : ℕ) : + (U.stop R e j).2 = + if j ≤ m + 1 then arm R (tipKey (U.endTerm e false)) (U.pinAt e false) (m + 1 - j) + else arm R (tipKey (U.endTerm e true)) (U.pinAt e true) (j - (m + 2)) := by + have aux (x : U.Terminal) (i : Fin L) (t : ℕ) : + (Schedule.splitHost R a h L (R.hub (if t ≤ m then .inr (x, Tree.climb i t) else .inl x))).2 = + arm R (tipKey x) i t := by unfold arm; split <;> rfl + unfold stop Detour.Switch.path + split + · exact aux _ _ _ + · exact aux _ _ _ + +include r p hk in +open scoped Classical in +theorem UnitPair.stop (j : ℕ) : (U.stop R e j).2 = (V.stop R f j).2 := by + simp only [stop_coord, r.tip p hk, r.pin p hk] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # Comparing bit assignments at a reset station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U V : Setup S h u a Δ D Y w B') (R : Rotor F Y w) + (fit : U.Fits R c) (fit' : V.Fits R c) + +open scoped Classical in +/-- Indexes the value by the coordinates of `(U.G.E × Bool) ⊕ U.Raw R → Bool`. -/ +abbrev Value := (U.G.E × Bool) ⊕ U.Raw R → Bool + +open scoped Classical in +/-- Computes the old place by the application `U.place R fit ((U.result R fit).owner ((demands +U.G).point e t))`. -/ +def oldPlace (e : U.G.E) (t : Bool) := + U.place R fit ((U.result R fit).owner ((demands U.G).point e t)) + +open scoped Classical in +/-- The value at used in the `Setup` construction. -/ +def valueAt (σ : Cell a) (v : U.G.V) (loc : Coord R h a Δ) (x : U.Value R) := + (U.result R fit).rule.entry () ((U.place R fit).symm (σ, v, loc)) + (fun i => x (.inl (i, false))) (fun i => x (.inl (i, true))) (x ∘ Sum.inr) + +open scoped Classical in +theorem old_place (e : U.G.E) (t : Bool) : + let x := U.Z.leaf ((demands U.G).point e t) + U.oldPlace R fit e t = (U.Z.group (U.G.ix e), Scheme.side U.G e t, + .inl ((x.drop a).2, R.root false (U.delivery.terminal ((demands U.G).point e t)))) := by + rw [← point_side] + rfl + +variable {U V} +open scoped Classical in +/-- The data for the alignment construction, including `old`, `wire`. -/ +structure Alignment (σ : Cell a) (v : U.G.V) (z : V.G.V) (loc : Coord R h a Δ) + (x : U.Value R) (y : V.Value R) : Prop where + old : ∀ i j t, U.oldPlace R fit i t = (σ, v, loc) → V.oldPlace R fit' j t = (σ, z, loc) → + endName U.post i t = endName V.post j t → x (.inl (i, t)) = y (.inl (j, t)) + wire : ∀ i j t, U.rawPlace R fit i t = (σ, v, loc) → V.rawPlace R fit' j t = (σ, z, loc) → + U.rawKey R i t = V.rawKey R j t → x (.inr i) = y (.inr j) + +variable {R fit fit'} {σ : Cell a} {v : U.G.V} {z : V.G.V} {loc : Coord R h a Δ} + {x : U.Value R} {y : V.Value R} + +open scoped Classical in +theorem Alignment.symm (e : Alignment R fit fit' σ v z loc x y) : + Alignment R fit' fit σ z v loc y x := + ⟨fun i j t h h' he => (e.old j i t h' h he.symm).symm, + fun i j t h h' he => (e.wire j i t h' h he.symm).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- +# Separating the programmed rotor from the exceptional contacts + +A site receives a product from the rotor stations mapped there. +For each exceptional path, consecutive bits must agree whenever +the path passes through this site. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule +open Finset + +variable {F S E T : Type} [Field F] [Fintype S] [Fintype E] [Fintype T] {n : ℕ} + +open scoped Classical in +/-- Requires `Fin.cons (α := fun _ => E → Bool) x (Function.curry z) i e = Fin.snoc (α := fun _ +=> E → Bool) (Function.curry z) y i e`. -/ +def through (x y : E → Bool) (z : Fin n × E → Bool) (i : Fin (n + 1)) (e : E) : Prop := + Fin.cons (α := fun _ => E → Bool) x (Function.curry z) i e = + Fin.snoc (α := fun _ => E → Bool) (Function.curry z) y i e + +open scoped Classical in +theorem path_place (D : ℕ → E → S) (g : S → T) (v : T) + (x y : E → Bool) (z : Fin n × E → Bool) : + ((Rule.path F D n).place g).entry () v x y z = + if ∀ (i : Fin (n + 1)) e, g (D i.val e) = v → through x y z i e then 1 else 0 := by + change (∏ w ∈ univ.filter (fun w => g w = v), (Rule.path F D n).entry () w x y z) = _ + simp only [path_entry, prod_ite_zero, prod_const_one, mem_filter, mem_univ, true_and] + congr! 1 + constructor + · exact fun h i e he => h _ he i e rfl + · rintro h w hw i e rfl; exact h i e hw + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet.Rule + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Spectral.Packet Finset +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' c : ℝ} + [NeZero Y] [NeZero w] (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) (fit : U.Fits R c) + (σ : Cell a) (v : U.G.V) (loc : Coord R h a Δ) (x : U.Value R) + +local notation "L" => terminalWidth Δ Y + +open scoped Classical in +/-- The indexed operation `(U.delivery.deployRule R).entry () t (fun e => x (.inl (e.val, +false))) (fun e => x (.inl (e.val, true))) (fun i => x (.inr (.inl i)))`. -/ +def rotorWeight (t : Site U.G.V h × R.Hardware) := + (U.delivery.deployRule R).entry () t (fun e => x (.inl (e.val, false))) + (fun e => x (.inl (e.val, true))) (fun i => x (.inr (.inl i))) + +open scoped Classical in +/-- The indexed operation `Rule.through (fun e => x (.inl (e.val, false))) (fun e => x (.inl +(e.val, true))) (fun j => x (.inr (.inr j))) i e`. -/ +def joins (i : Fin (Detour.steps L + 1)) (e : U.Z.Exceptional) := + Rule.through (fun e => x (.inl (e.val, false))) (fun e => x (.inl (e.val, true))) + (fun j => x (.inr (.inr j))) i e + +open scoped Classical in +/-- The defining condition `∀ (i : Fin (Detour.steps L + 1)) (e : U.Z.Exceptional), (U.Z.group +(U.G.ix e.val), U.stop R e.val i.val) = (σ, v, loc) → U.joins R x i e`. -/ +def detours : Prop := + ∀ (i : Fin (Detour.steps L + 1)) (e : U.Z.Exceptional), + (U.Z.group (U.G.ix e.val), U.stop R e.val i.val) = (σ, v, loc) → U.joins R x i e + +open scoped Classical in +/-- Requires `Site.group a ((), q) = σ ∧ Sum.inl ((Site.drop a ((), q)).2, t) = loc`. -/ +def selected (q : Schedule.Address h) (t : R.Hardware) : Prop := + Site.group a ((), q) = σ ∧ Sum.inl ((Site.drop a ((), q)).2, t) = loc + +open scoped Classical in +/-- The value specified by `∏ q : Schedule.Address h, ∏ t : R.Hardware, if selected R σ loc q t +then U.rotorWeight R x ((v, q), t) else 1`. -/ +def mainValue := + ∏ q : Schedule.Address h, ∏ t : R.Hardware, + if selected R σ loc q t then U.rotorWeight R x ((v, q), t) else 1 + +open scoped Classical in +private theorem main_eq : + (∏ t ∈ univ.filter (fun t => Schedule.mainPlace R t = (U.place R fit).symm (σ, v, loc)), + U.rotorWeight R x t) = U.mainValue R σ v loc x := by + have he (z : U.G.V) (q : Schedule.Address h) (t : R.Hardware) : + Schedule.mainPlace R ((z, q), t) = (U.place R fit).symm (σ, v, loc) ↔ + z = v ∧ selected R σ loc q t := by + refine (U.place R fit).eq_symm_apply.trans ?_ + change (Site.group a ((), q), z, Sum.inl ((Site.drop a ((), q)).2, t)) = (σ, v, loc) ↔ _ + simp only [Prod.mk.injEq, selected, and_left_comm] + rw [prod_filter, Fintype.prod_prod_type, Fintype.prod_prod_type] + simp only [he, ite_and, prod_ite_irrel, prod_const_one, prod_ite_eq', mem_univ, ite_true, + mainValue] + +open scoped Classical in +private def treeWalk (i : ℕ) (e : U.Z.Exceptional) := + (U.Z.group (U.G.ix e.val), U.switch.path (U.reaches e.val) i) + +open scoped Classical in +private theorem detour_eq : + ((Rule.path F U.treeWalk (Detour.steps L)).place (Schedule.treePlace R)).entry () + ((U.place R fit).symm (σ, v, loc)) (fun e => x (.inl (e.val, false))) + (fun e => x (.inl (e.val, true))) (fun j => x (.inr (.inr j))) = + if U.detours R σ v loc x then 1 else 0 := by + have he (i : ℕ) (e : U.Z.Exceptional) : + Schedule.treePlace R (U.treeWalk i e) = (U.place R fit).symm (σ, v, loc) ↔ + (U.Z.group (U.G.ix e.val), U.stop R e.val i) = (σ, v, loc) := + (U.place R fit).eq_symm_apply + refine (Rule.path_place U.treeWalk (Schedule.treePlace R) _ _ _ _).trans ?_ + congr! 1 + simp only [he, detours, joins] + +open scoped Classical in +theorem value_eq : + U.valueAt R fit σ v loc x = U.mainValue R σ v loc x * if U.detours R σ v loc x then 1 else 0 + := by + rw [← U.main_eq R fit, ← U.detour_eq R fit] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Repost.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Repost.lean new file mode 100644 index 0000000000..1832a543e2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Repost.lean @@ -0,0 +1,1023 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.HostReset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Checks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Rate + +/-! # Exposed spans after a host reset -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + +open scoped Classical in +/-- Indexes the face by the coordinates of `p.toPresentation.BorderSpan ⊕ (q.Survivors × Bool)`. -/ +abbrev Face := p.toPresentation.BorderSpan ⊕ (q.Survivors × Bool) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def visibleWidth : Face p q → ℕ := Sum.elim p.toPresentation.borderWidth (fun _ => u) + +open scoped Classical in +/-- In the case `.inl j`, this construction gives `q.owner (G.units.place j.val.1)`. -/ +def whereAt : Face p q → Cell a × q.vertex + | .inl j => q.owner (G.units.place j.val.1) + | .inr (e, b) => cond b (q.supply e.val).2 (q.supply e.val).1 + +open scoped Classical in +/-- Reindexes `(Σ j, Fin (visibleWidth p q j))` and `(q.contract G.units).End` by an +equivalence. -/ +def faceBits : (Σ j, Fin (visibleWidth p q j)) ≃ (q.contract G.units).End := + let swap : (q.Survivors × Bool) × Fin u ≃ (q.Survivors × Fin u) × Bool := + ⟨fun j => ((j.1.1, j.2), j.1.2), fun j => ((j.1.1, j.2), j.1.2), fun _ => rfl, fun _ => rfl⟩ + let cut := ((Equiv.sigmaEquivProd _ _).trans swap).trans + ((q.remaining G.units).prodCongr (Equiv.refl Bool)) + ((Equiv.sumSigmaDistrib _).trans (p.toPresentation.exteriorBits.sumCongr cut)).trans + (Subround.endIndex _) + +open scoped Classical in +theorem face_location (j : Σ i, Fin (visibleWidth p q i)) : + (q.contract G.units).station (faceBits p q j) = whereAt p q j.1 := by + rcases j with ⟨v|⟨e, b⟩, i⟩ + · let z : p.toPresentation.BorderBit := ⟨v, i⟩ + have he (j : slots x ⊕ slots y) : + (q.contract G.units).station (boundaryEnd _ j) + = q.owner (G.units.place (portEnd G.diagram j)) := by + cases j <;> rfl + exact (he (p.toPresentation.exteriorBits z)).trans + (congrArg (q.owner ∘ G.units.place) (p.toPresentation.border_station z)) + · cases b <;> rfl + +open scoped Classical in +/-- The subtype of `j : Face p q` satisfying `whereAt p q j = v`. -/ +abbrev Visible (v : Cell a × q.vertex) := {j : Face p q // whereAt p q j = v} + +open scoped Classical in +/-- Reindexes `(Σ j : Visible p q v, Fin (visibleWidth p q j.val))` and `(q.contract +G.units).Port v` by an equivalence. -/ +def visibleBits (v : Cell a × q.vertex) : + (Σ j : Visible p q v, Fin (visibleWidth p q j.val)) ≃ (q.contract G.units).Port v := by + let E := q.contract G.units + let e := faceBits p q + let f (j : Σ t : Visible p q v, Fin (visibleWidth p q t.val)) : + {t : E.End // E.station t = v} := + ⟨e ⟨j.1.val, j.2⟩, (face_location p q _).trans j.1.property⟩ + refine (Equiv.ofBijective f ⟨?_, ?_⟩).trans (E.incident v).symm + · rintro ⟨⟨j, hj⟩, b⟩ ⟨⟨k, hk⟩, c⟩ he + have h := e.injective (congrArg Subtype.val he) + cases h + rfl + · rintro ⟨j, hj⟩ + obtain ⟨⟨k, b⟩, rfl⟩ := e.surjective j + exact ⟨⟨⟨k, (face_location p q _).symm.trans hj⟩, b⟩, rfl⟩ + +open scoped Classical in +theorem visible_pin (v : Cell a × q.vertex) (j : Σ t : Visible p q v, + Fin (visibleWidth p q t.val)) : + named (q.contract G.units) v (visibleBits p q v j) = faceBits p q ⟨j.1.val, j.2⟩ := by + let E := q.contract G.units + change ((E.incident v) ((E.incident v).symm _)).val = _ + rw [Equiv.apply_symm_apply] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Assigning surviving and exterior spans to new host records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + (U : Scheme F) + +open scoped Classical in +/-- The data for the allocation construction, including `host`, `block`, `index`, `seat`. -/ +structure Allocation where + /-- Embeds the coordinates as `q.vertex ↪ B U.m`. -/ + host : q.vertex ↪ B U.m + /-- Embeds the coordinates as `Cell a ↪ B U.h`. -/ + block : Cell a ↪ B U.h + /-- The identification of the indices of type `q.vertex → q.vertex → B U.d`. -/ + index : q.vertex → q.vertex → B U.d + /-- Embeds the coordinates as `∀ v, Visible p q v ↪ B U.e`. -/ + seat : ∀ v, Visible p q v ↪ B U.e + +namespace Allocation +variable {p q U} (A : Allocation p q U) + +open scoped Classical in +/-- Embeds `Cell a × q.vertex` into `U.Vtx where toFun v`. -/ +def vertex : Cell a × q.vertex ↪ U.Vtx where + toFun v := (A.host v.2, A.block v.1, 0) + inj' _ _ he := Prod.ext (A.block.injective (Prod.mk.inj (Prod.mk.inj he).2).1) + (A.host.injective (Prod.mk.inj he).1) + +local notation "atSite" => whereAt p q + +open scoped Classical in +/-- The value specified by `A.seat (atSite j) ⟨j, rfl⟩`. -/ +def slot (j : Face p q) := A.seat (atSite j) ⟨j, rfl⟩ + +open scoped Classical in +theorem slot_eq (v : Cell a × q.vertex) (j : Visible p q v) : + A.slot j.val = A.seat v j := by + obtain ⟨j, rfl⟩ := j + rfl + +open scoped Classical in +/-- The value specified by `(A.vertex (atSite j), A.slot j)`. -/ +def span (j : Face p q) : U.Span := (A.vertex (atSite j), A.slot j) + +open scoped Classical in +theorem span_injective : Function.Injective A.span := + U.span_injective atSite A.vertex A.seat A.slot A.slot_eq + +open scoped Classical in +/-- The data for the lengths construction, including `used`, `idle`. -/ +structure Lengths (out : U.format.obj) : Prop where + used : ∀ j, U.width out (A.span j) = visibleWidth p q j + idle : ∀ t ∉ Set.range A.span, U.width out t = 0 + +variable {out : U.format.obj} (l : A.Lengths out) + +include l in +open scoped Classical in +theorem length_at (v : Cell a × q.vertex) (j : Visible p q v) : + U.width out (A.vertex v, A.seat v j) = visibleWidth p q j.val := by + obtain ⟨j, rfl⟩ := j + exact l.used j + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def orderPins (v : Cell a × q.vertex) : + (Σ j : Visible p q v, Fin (visibleWidth p q j.val)) ≃ + U.LocalPin out (A.vertex v) := + U.orderPins out atSite A.vertex A.seat A.slot A.slot_eq (visibleWidth p q) + v (A.length_at l v) l.idle + +open scoped Classical in +/-- Reindexes `(q.contract G.units).Port v` and `U.LocalPin out (A.vertex v)` by an equivalence. -/ +def pin (v : Cell a × q.vertex) : + (q.contract G.units).Port v ≃ U.LocalPin out (A.vertex v) := + (visibleBits p q v).symm.trans (A.orderPins l v) + +open scoped Classical in +theorem pin_at (v : Cell a × q.vertex) (j : Visible p q v) + (k : Fin (visibleWidth p q j.val)) : + A.pin l v (visibleBits p q v ⟨j, k⟩) = + ⟨A.seat v j, k.cast (A.length_at l v j).symm⟩ := by + rw [pin, Equiv.trans_apply, Equiv.symm_apply_apply] + rfl + +end Allocation +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Reposting an ordered host after a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Allocation + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} {p : S.Posting r G} + {B' W : ℝ} {Hcap D : ℕ} + {q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D} + {U : Scheme F} (A : Allocation p q U) {out : U.format.obj} (l : A.Lengths out) + +open scoped Classical in +/-- The value specified by `A.slot (.inr (e, t))`. -/ +abbrev unitSeat (e : q.Survivors) (t : Bool) := A.slot (.inr (e, t)) + +open scoped Classical in +/-- The value specified by `(cond t (q.supply e.val).2 (q.supply e.val).1).2`. -/ +abbrev endHost (e : q.Survivors) (t : Bool) := (cond t (q.supply e.val).2 (q.supply e.val).1).2 + +open scoped Classical in +theorem site_end (e : q.Survivors) (t : Bool) : + (A.span (.inr (e, t))).1 = + (A.host (endHost (q := q) e t), A.block (q.supply e.val).1.1, 0) := by + cases t + · rfl + · rw [(q.support e.val).1] + rfl + +open scoped Classical in +/-- Conditions on decoded local patterns. No names of remote hosts +are needed by a station's tensor table. -/ +structure Agrees : Prop where + sample : ∀ v t, U.table out (A.vertex v) t = + Transcript.sample ((q.contract G.units).table v) (t ∘ A.pin l v) + vacant : ∀ v ∉ Set.range A.vertex, ∀ t, U.table out v t = 1 + outside : ∀ j, U.peer out (A.span (.inl j)) = none + idle : ∀ t ∉ Set.range A.span, U.peer out t = none + dir : ∀ e t, U.direction out (A.span (.inr (e, t))) = t + link : ∀ e t, let v := A.span (.inr (e, t)) + (U.pattern out v.1).peer v.1.2.2 v.2 = + some (A.index (endHost (q := q) e t) (endHost (q := q) e (!t)), + 0, A.unitSeat e (!t)) + nav : ∀ (e : q.Survivors) t, let v := endHost (q := q) e t + let w := endHost (q := q) e (!t) + (out (A.host v)).1 (A.index v w) = A.host w + +variable (H : A.Agrees l) + +open scoped Classical in +/-- Builds `U.Seating out (q.contract G.units) where vertex` with the specified `vertex`, `pin`, +`cover`, `exact`. -/ +def seating : U.Seating out (q.contract G.units) where + vertex := A.vertex + pin := A.pin l + cover := U.cover_of_span out A.span A.vertex (whereAt p q) + (fun _ => rfl) l.idle + sample := H.sample + vacant := H.vacant + +open scoped Classical in +theorem end_pin (j : Face p q) (b : Fin (visibleWidth p q j)) : + let y := faceBits p q ⟨j, b⟩ + (A.seating l H).ends y = ⟨A.span j, b.cast (l.used j).symm⟩ := by + let v := whereAt p q j + let r : Visible p q v := ⟨j, rfl⟩ + let o := visibleBits p q v ⟨r, b⟩ + have he := visible_pin p q v ⟨r, b⟩ + change (q.contract G.units).portEquiv ⟨v, o⟩ = faceBits p q ⟨j, b⟩ at he + apply (A.seating l H).ends_eq_of_port he + change U.port out (A.vertex v) (A.pin l v o) = _ + rw [show A.pin l v o = _ from A.pin_at l v r b] + rfl + +include H in +open scoped Classical in +theorem peer_end (e : q.Survivors) (t : Bool) : + U.peer out (A.span (.inr (e, t))) = some (A.span (.inr (e, !t))) := + U.peer_of_link out (A.site_end e t) (A.site_end e (!t)) (H.link e t) (H.nav e t) + +include H in +open scoped Classical in +theorem proper : U.Proper out := + U.proper_of_span out A.span u H.idle H.outside (A.peer_end l H) + (fun e t => l.used (.inr (e, t))) H.dir + +open scoped Classical in +theorem exposed_pin (j : p.toPresentation.BorderBit) : + let G' := q.contract G.units + (A.seating l H).ends (boundaryEnd G' (p.toPresentation.exteriorBits j)) = + ⟨A.span (.inl j.1), j.2.cast (l.used (.inl j.1)).symm⟩ := + A.end_pin l H (.inl j.1) j.2 + +open scoped Classical in +theorem unit_pin (e : q.Survivors) (b : Bool) (j : Fin u) : + let e' := q.remaining G.units (e, j) + (A.seating l H).ends (cond b (.inr (.inr e')) (.inl (.inr e'))) = + ⟨A.span (.inr (e, b)), j.cast (l.used (.inr (e, b))).symm⟩ := + A.end_pin l H (.inr (e, b)) j + +open scoped Classical in +theorem exposed_none (j : slots x ⊕ slots y) : + U.peer out ((A.seating l H).ends (boundaryEnd _ j)).1 = none := by + obtain ⟨t, rfl⟩ := p.toPresentation.exteriorBits.surjective j + rw [A.exposed_pin] + exact H.outside t.1 + +open scoped Classical in +/-- Builds `U.Presentation out (q.contract G.units) where toSeating` with the specified +`toSeating`, `proper`, `input`, `output`. -/ +def presentation : U.Presentation out (q.contract G.units) where + toSeating := A.seating l H + proper := A.proper l H + input t := A.exposed_none l H (.inl t) + output t := A.exposed_none l H (.inr t) + internal e := by + obtain ⟨⟨a, j⟩, rfl⟩ := (q.remaining G.units).surjective e + have hs := A.unit_pin l H a false j + have ht := A.unit_pin l H a true j + dsimp only [cond] at hs ht + rw [hs, ht] + exact ⟨A.peer_end l H a false, rfl⟩ + +open scoped Classical in +theorem unit_span (e : q.Survivors) (b : Bool) : + U.spanAt (G.afterReset q) A.host A.block A.unitSeat e b = A.span (.inr (e, b)) := by + refine Prod.ext ?_ rfl + cases b + · exact (A.site_end e false).symm + · exact (A.site_end e true).symm + +open scoped Classical in +/-- Builds `U.Posting out (G.afterReset q) where toPresentation` with the specified +`toPresentation`, `host`, `block`, `stub`. -/ +def posting : U.Posting out (G.afterReset q) where + toPresentation := A.presentation l H + host := A.host + block := A.block + stub := A.unitSeat + index := A.index + vertex_eq _ := rfl + ordered e b j := by + change q.Survivors at e + let s := (A.seating l H).ends (Scheme.endBit (G.afterReset q) e b j) + have he : s = ⟨A.span (.inr (e, b)), j.cast (l.used (.inr (e, b))).symm⟩ := A.unit_pin l H e b j + change s.1 = _ ∧ s.2.val = j.val + rw [he] + exact ⟨(A.unit_span e b).symm, rfl⟩ + length e t := (congrArg (U.width out) (A.unit_span e t)).trans (l.used _) + dir e t := (congrArg (U.direction out) (A.unit_span e t)).trans (H.dir e t) + link e t := by + change q.Survivors at e + rw [unit_span] + cases t + · exact H.link e false + · exact H.link e true + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Allocation +end + +/- +# Internal bundles at a reset + +Each old wire contributes two hidden half-wires. Of the new supplies +only loops are hidden. All three kinds have the same unit width. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + +open scoped Classical in +/-- The value specified by `(q.rule.bundle u).reindex G.units.bits`. -/ +abbrev raw := (q.rule.bundle u).reindex G.units.bits +open scoped Classical in +/-- Computes the before by the application `G.diagram.expanded (raw q) ()`. -/ +abbrev before := G.diagram.expanded (raw q) () +open scoped Classical in +/-- The value specified by `(before q).partition (Sum.elim (q.assign G.units ()) id)`. -/ +abbrev cluster := (before q).partition (Sum.elim (q.assign G.units ()) id) +open scoped Classical in +/-- Indexes the segment by the coordinates of `G.E ⊕ G.E ⊕ q.wire`. -/ +abbrev Segment := G.E ⊕ G.E ⊕ q.wire + +open scoped Classical in +/-- In the case `.inl e`, this construction gives `let v := q.owner (G.src e, G.ix e); (v, v)`. -/ +def ends : Segment q → (Cell a × q.vertex) × (Cell a × q.vertex) + | .inl e => let v := q.owner (G.src e, G.ix e); (v, v) + | .inr (.inl e) => let v := q.owner (G.dst e, G.ix e); (v, v) + | .inr (.inr e) => q.supply e + +open scoped Classical in +/-- Reindexes `Segment q × Fin u` and `(before q).E` by an equivalence. -/ +def segmentBits : Segment q × Fin u ≃ (before q).E := + (Equiv.sumProdDistrib _ _ _).trans (G.units.bits.symm.sumCongr + ((Equiv.sumProdDistrib _ _ _).trans (G.units.bits.symm.sumCongr (.refl _)))) + +open scoped Classical in +theorem endpoints (j : Segment q × Fin u) : + let e := segmentBits q j + ((cluster q).owner ((before q).source e), (cluster q).owner ((before q).target e)) = + ends q j.1 := by + rcases j with ⟨e|e|e, j⟩ + · let i := G.units.bits.symm (e, j) + change (q.owner (G.units.place (G.diagram.source i)), + q.owner (G.src (G.units.bits i).1, G.ix (G.units.bits i).1)) = _ + simp only [G.units.left, i, Equiv.apply_symm_apply, ends] + · let i := G.units.bits.symm (e, j) + change (q.owner (G.dst (G.units.bits i).1, G.ix (G.units.bits i).1), + q.owner (G.units.place (G.diagram.target i))) = _ + simp only [G.units.right, i, Equiv.apply_symm_apply, ends] + · rfl + +open scoped Classical in +/-- The subtype of `j : Segment q` satisfying `ends q j = (v, v)`. -/ +abbrev Hidden (v : Cell a × q.vertex) := {j : Segment q // ends q j = (v, v)} + +open scoped Classical in +/-- Reindexes `Hidden q v × Fin u` and `(cluster q).hidden v` by an equivalence. -/ +def hiddenBits (v : Cell a × q.vertex) : Hidden q v × Fin u ≃ (cluster q).hidden v := by + let f (j : Hidden q v × Fin u) := segmentBits q (j.1.val, j.2) + have he (j : Hidden q v × Fin u) : + (cluster q).owner ((before q).source (f j)) = v ∧ + (cluster q).owner ((before q).target (f j)) = v := + Prod.mk.inj ((endpoints q _).trans j.1.property) + refine Equiv.ofBijective (fun j => ⟨⟨f j, (he j).1.trans (he j).2.symm⟩, (he j).1⟩) ⟨?_, ?_⟩ + · intro i j h + have hl := (segmentBits q).injective (congrArg (fun x => x.val.val) h) + exact Prod.ext (Subtype.ext (Prod.mk.inj hl).1) (Prod.mk.inj hl).2 + · rintro ⟨⟨j, hj⟩, hv⟩ + obtain ⟨⟨k, t⟩, rfl⟩ := (segmentBits q).surjective j + have ht : ends q k = (v, v) := + (endpoints q (k, t)).symm.trans (Prod.ext hv (hj.symm.trans hv)) + exact ⟨(⟨k, ht⟩, t), rfl⟩ + +open scoped Classical in +/-- In the case `.inl t`, this construction gives `.inl (t.map id Sum.inl)`. -/ +def old : G.diagram.End → (before q).End + | .inl t => .inl (t.map id Sum.inl) + | .inr t => .inr (t.map id (fun e => .inr (.inl e))) + +open scoped Classical in +/-- The value specified by `.inr (.inr (.inl e))`. -/ +def left (e : G.diagram.E) : (before q).End := .inr (.inr (.inl e)) +open scoped Classical in +/-- The value specified by `.inl (.inr (.inr (.inl e)))`. -/ +def right (e : G.diagram.E) : (before q).End := .inl (.inr (.inr (.inl e))) + +open scoped Classical in +/-- Returns `.inl (.inr (.inr (.inr j)))` when `(q.supply j.1).1 = v` holds, and `.inr (.inr +(.inr (.inr j)))` otherwise. -/ +def supplyEnd (v : Cell a × q.vertex) (j : q.wire × Fin u) : (before q).End := + if (q.supply j.1).1 = v then .inl (.inr (.inr (.inr j))) else .inr (.inr (.inr (.inr j))) + +variable (w : open scoped Classical in Bit (cluster q) → Bool) + +open scoped Classical in +/-- The value specified by `w ∘ address (cluster q)`. -/ +abbrev read := w ∘ address (cluster q) + +open scoped Classical in +theorem old_factor (v : G.diagram.V) : + factor (cluster q) (.inl v) w = + Transcript.sample (G.diagram.table v) (read q w ∘ old q ∘ named G.diagram v) := by + rw [factor, Diagram.weight_expanded] + unfold Diagram.Expansion.entry Diagram.weight Transcript.sample + apply congrArg₂ (G.diagram.table v).2.2 <;> apply congrArg <;> funext t + · change Sum.elim _ _ (G.diagram.src ⟨v, t⟩) = read q w (old q (.inl (G.diagram.src ⟨v, t⟩))) + cases G.diagram.src ⟨v, t⟩ <;> rfl + · change Sum.elim _ _ (G.diagram.dst ⟨v, t⟩) = read q w (old q (.inr (G.diagram.dst ⟨v, t⟩))) + cases G.diagram.dst ⟨v, t⟩ <;> rfl + +open scoped Classical in +theorem new_factor (v : Cell a × q.vertex) : + factor (cluster q) (.inr v) w = + ∏ j : Fin u, q.rule.entry () v + (fun e => read q w (left q (G.units.bits.symm (e, j)))) + (fun e => read q w (right q (G.units.bits.symm (e, j)))) + (fun e => read q w (supplyEnd q v (e, j))) := by + change _ = (raw q).entry () v (read q w ∘ left q) (read q w ∘ right q) + (read q w ∘ supplyEnd q v) + rw [factor, Diagram.weight_expanded] + unfold Diagram.Expansion.entry + apply congrArg ((raw q).entry () v (read q w ∘ left q) (read q w ∘ right q)) + funext j + unfold supplyEnd + simp only [Function.comp_apply] + split_ifs <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Addresses of the visible and hidden spans after a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + (v : Cell a × q.vertex) + +open scoped Classical in +/-- Indexes the port by the coordinates of `Visible p q v ⊕ Hidden q v`. -/ +abbrev Port := Visible p q v ⊕ Hidden q v + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def width : Port p q v → ℕ := Sum.elim (fun j => visibleWidth p q j.val) (fun _ => u) + +open scoped Classical in +/-- In the case `.inl j, b`, this construction gives `.inl (faceBits p q ⟨j.val, b⟩)`. -/ +def bit : (j : Port p q v) → Fin (width p q v j) → Bit (cluster q) + | .inl j, b => .inl (faceBits p q ⟨j.val, b⟩) + | .inr j, b => .inr ⟨v, hiddenBits q v (j, b)⟩ + +open scoped Classical in +/-- The value specified by `.inl ⟨.inl x, he⟩`. -/ +def exterior (x : p.toPresentation.BorderSpan) (he : q.owner (G.units.place x.val.1) = v) : + Port p q v := .inl ⟨.inl x, he⟩ + +open scoped Classical in +theorem width_exterior (x : p.toPresentation.BorderSpan) (he) : + width p q v (exterior p q v x he) = p.toPresentation.borderWidth x := rfl + +open scoped Classical in +/-- The value specified by `q.owner (Scheme.side G e t, G.ix e)`. -/ +abbrev demandSite (e : G.E) (t : Bool) := q.owner (Scheme.side G e t, G.ix e) + +open scoped Classical in +/-- The value specified by `.inr ⟨cond t (.inr (.inl e)) (.inl e), by cases t <;> exact Prod.ext +he he⟩`. -/ +def demand (e : G.E) (t : Bool) (he : demandSite q e t = v) : Port p q v := + .inr ⟨cond t (.inr (.inl e)) (.inl e), by cases t <;> exact Prod.ext he he⟩ + +open scoped Classical in +theorem width_demand (e : G.E) (t : Bool) (he) : + width p q v (demand p q v e t he) = u := rfl + +open scoped Classical in +/-- Computes the supply site by the application `cond t (q.supply e).2 (q.supply e).1`. -/ +abbrev supplySite (e : q.wire) (t : Bool) := cond t (q.supply e).2 (q.supply e).1 + +open scoped Classical in +/-- The supply of type `Port p q v` for the given inputs. -/ +def supply (e : q.wire) (t : Bool) (he : supplySite q e t = v) : Port p q v := + if h : (q.supply e).1 = (q.supply e).2 then + .inr ⟨.inr (.inr e), by + cases t + · exact Prod.ext he (h.symm.trans he) + · exact Prod.ext (h.trans he) he⟩ + else .inl ⟨.inr (⟨e, h⟩, t), he⟩ + +open scoped Classical in +theorem width_supply (e : q.wire) (t : Bool) (he) : + width p q v (supply p q v e t he) = u := by + unfold supply + split <;> rfl + +open scoped Classical in +theorem address_exterior (x : p.toPresentation.BorderSpan) (he) + (j : Fin (p.toPresentation.borderWidth x)) : + address (cluster q) (old q (boundaryEnd G.diagram (p.toPresentation.exteriorBits ⟨x, j⟩))) = + bit p q v (exterior p q v x he) j := by + change _ = (Sum.inl (boundaryEnd (q.contract G.units) (p.toPresentation.exteriorBits ⟨x, + j⟩)) : Bit (cluster q)) + cases p.toPresentation.exteriorBits ⟨x, j⟩ <;> rfl + +open scoped Classical in +private theorem address_internal (e : Hidden q v) (j : Fin u) (t : Bool) : + let b := segmentBits q (e.val, j) + address (cluster q) (cond t (.inr (.inr b)) (.inl (.inr b))) = + .inr ⟨v, hiddenBits q v (e, j)⟩ := by + have h : (cluster q).edges.symm (segmentBits q (e.val, j)) = .inr ⟨v, hiddenBits q v (e, j)⟩ := + (cluster q).edges.symm_apply_eq.mpr rfl + cases t <;> simp only [cond, address, h, Sum.map_inr, id_eq] + +open scoped Classical in +theorem address_demand_old (e : G.E) (t : Bool) (he) (j : Fin u) : + address (cluster q) (old q (Scheme.endBit G e t j)) = bit p q v (demand p q v e t he) j := by + cases t + · exact address_internal q v ⟨.inl e, Prod.ext he he⟩ j false + · exact address_internal q v ⟨.inr (.inl e), Prod.ext he he⟩ j true + +open scoped Classical in +theorem address_demand_new (e : G.E) (t : Bool) (he) (j : Fin u) : + let b := G.units.bits.symm (e, j) + address (cluster q) (cond t (right q b) (left q b)) = bit p q v (demand p q v e t he) j := by + cases t + · exact address_internal q v ⟨.inl e, Prod.ext he he⟩ j true + · exact address_internal q v ⟨.inr (.inl e), Prod.ext he he⟩ j false + +open scoped Classical in +theorem bit_congr {x y : Port p q v} (h : x = y) + {i : Fin (width p q v x)} {j : Fin (width p q v y)} (e : i.val = j.val) : + bit p q v x i = bit p q v y j := by + subst y + rw [Fin.ext e] + +open scoped Classical in +theorem address_supply (e : q.wire) (t : Bool) (he : supplySite q e t = v) (j : Fin u) : + address (cluster q) (supplyEnd q v (e, j)) = + bit p q v (supply p q v e t he) (j.cast (width_supply p q v e t he).symm) := by + by_cases h : (q.supply e).1 = (q.supply e).2 + · have hh : q.supply e = (v, v) := by + cases t + · exact Prod.ext he (h.symm.trans he) + · exact Prod.ext (h.trans he) he + let s : Hidden q v := ⟨.inr (.inr e), hh⟩ + have eq : supply p q v e t he = .inr s := dite_eq_left h + refine Eq.trans ?_ (bit_congr p q v eq.symm (i := j) rfl) + unfold supplyEnd + rw [ite_eq_left (congrArg Prod.fst hh)] + exact address_internal q v s j false + · let f : q.Survivors := ⟨e, h⟩ + let s : Visible p q v := ⟨.inr (f, t), he⟩ + have eq : supply p q v e t he = .inl s := dite_eq_right h + refine Eq.trans ?_ (bit_congr p q v eq.symm (i := j) rfl) + have hx : (cluster q).edges.symm (.inr (.inr (e, j))) = .inl (q.remaining G.units (f, j)) := + (cluster q).edges.symm_apply_eq.mpr rfl + subst v + cases t <;> simp only [cond, supplySite, supplyEnd, h, ↓reduceIte, address, hx] <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Addressing the old tensors in a reset cluster -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Coloring Packing Scheme + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + (v : Cell a × q.vertex) + +open scoped Classical in +/-- The subtype of `w : G.diagram.V` satisfying `0 < G.diagram.arity w ∧ q.owner (G.units.place +w) = v`. -/ +abbrev Live := {w : G.diagram.V // 0 < G.diagram.arity w ∧ q.owner (G.units.place w) = v} + +open scoped Classical in +/-- Each nonempty argument of a previous tensor reads one full span. -/ +structure AtomMap (m : Atom F) (w : (before q).V) where + /-- The `AtomMap` component of type `Port p q v`. -/ + slot (j : m.Span) (h : 0 < m.width j) : Port p q v + size (j) (h) : width p q v (slot j h) = m.width j + value (b : Bit (cluster q) → Bool) : + m.weight (fun j t => b (bit p q v (slot j t.pos) (t.cast (size _ _).symm))) = + factor (cluster q) w b + +variable (w : G.diagram.V) (hw : q.owner (G.units.place w) = v) + +include hw in +open scoped Classical in +private theorem station_location {j : B S.e} {e : G.E} {t : Bool} (he : p.span e t = (p.vertex w, + j)) : + demandSite q e t = v := by + rw [p.place_of_span he] at hw + exact hw + +variable (j : B S.e) (hj : 0 < S.width r (p.vertex w, j)) + +open scoped Classical in +/-- The origin used in the `Reset` construction. -/ +inductive Origin : Port p q v → Prop + | outside (f : p.toPresentation.BorderSpan) (hq : f.val = (w, j)) (he) : + Origin (exterior p q v f he) + | inside (e : G.E) (t : Bool) (he : p.span e t = (p.vertex w, j)) (hs) : + Origin (demand p q v e t hs) + +include hw hj in +open scoped Classical in +theorem exists_origin : ∃ f, Origin p q v w j f := by + by_cases h : S.peer r (p.vertex w, j) = none + · exact ⟨_, .outside ⟨(w, j), hj, h⟩ rfl hw⟩ + · obtain ⟨e, t, he⟩ := p.span_end _ hj h + exact ⟨_, .inside e t he (station_location p q v w hw he)⟩ + +open scoped Classical in +/-- The value specified by `(exists_origin p q v w hw j hj).choose`. -/ +def stationPort : Port p q v := (exists_origin p q v w hw j hj).choose + +open scoped Classical in +theorem station_origin : Origin p q v w j (stationPort p q v w hw j hj) := + (exists_origin p q v w hw j hj).choose_spec + +open scoped Classical in +theorem origin_width {s : Port p q v} (hs : Origin p q v w j s) : + width p q v s = S.width r (p.vertex w, j) := by + cases hs with + | outside f hq he => + erw [width_exterior p q v f he, Presentation.borderWidth, hq] + | inside e t he hs => + erw [width_demand p q v e t hs, ← he] + exact (p.length e t).symm + +open scoped Classical in +theorem origin_address {s : Port p q v} (hs : Origin p q v w j s) + (b : Fin (S.width r (p.vertex w, j))) : + address (cluster q) (old q + (p.toSeating.ends.symm ⟨(p.vertex w, j), b⟩)) = + bit p q v s + (b.cast (origin_width p q v w j hs).symm) := by + cases hs with + | outside f hq he => + rcases f with ⟨⟨u, l⟩, h⟩ + obtain ⟨rfl, rfl⟩ := Prod.mk.inj hq + let f : p.toPresentation.BorderSpan := ⟨(u, l), h⟩ + have hh : p.toSeating.ends.symm ⟨(p.vertex u, l), b⟩ = + boundaryEnd _ (p.toPresentation.exteriorBits ⟨f, b⟩) := + p.toPresentation.ends_symm_borderPin ⟨f, b⟩ + rw [hh] + exact address_exterior p q v f he b + | inside e t he hm => + let c := b.cast ((congrArg (S.width r) he.symm).trans (p.length e t)) + rw [p.ends_symm_span he b] + exact address_demand_old p q v e t hm c + +open scoped Classical in +/-- The value specified by `((r (p.vertex w).1).2 (p.vertex w).2.1, (p.vertex w).2.2)`. -/ +abbrev oldLabel := ((r (p.vertex w).1).2 (p.vertex w).2.1, (p.vertex w).2.2) + +open scoped Classical in +/-- Builds `AtomMap p q v (History.original S (oldLabel p w)) (.inl w) where slot j h` with the +specified `slot`, `size`, `value`, `erw`. -/ +def oldMap : AtomMap p q v (History.original S (oldLabel p w)) (.inl w) where + slot j h := stationPort p q v w hw j h + size j h := origin_width p q v w j (station_origin p q v w hw j h) + value b := by + erw [old_factor q b w] + change S.table r (p.vertex w) (fun u => b (bit p q v + (stationPort p q v w hw u.1 u.2.pos) (u.2.cast + (origin_width p q v w u.1 (station_origin p q v w hw u.1 u.2.pos)).symm))) = _ + rw [p.sample] + apply congrArg + funext k + let u := p.pin w k + have ht := origin_address p q v w u.1 (station_origin p q v w hw u.1 u.2.pos) u.2 + have he : p.toSeating.ends.symm ⟨(p.vertex w, u.1), u.2⟩ = named G.diagram w k := + p.toSeating.ends.symm_apply_eq.mpr (p.toSeating.ends_at w k).symm + rw [he] at ht + exact congrArg b ht.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # The contracted station as a local sum of products -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + (v : Cell a × q.vertex) + +open scoped Classical in +/-- Indexes the exposed by the coordinates of `Σ j : Visible p q v, Fin (visibleWidth p q +j.val)`. -/ +abbrev Exposed := Σ j : Visible p q v, Fin (visibleWidth p q j.val) +open scoped Classical in +/-- Indexes the inner by the coordinates of `Hidden q v × Fin u`. -/ +abbrev Inner := Hidden q v × Fin u +open scoped Classical in +/-- The indexing data represented by `(j : Port p q v) → Fin (width p q v j) → Bool`. -/ +abbrev Tape := (j : Port p q v) → Fin (width p q v j) → Bool + +open scoped Classical in +/-- The indexed operation `Transcript.sample ((q.contract G.units).table v) (fun j => let y := +(visibleBits p q v).symm j; x (seat y.1) y.2.val)`. -/ +def localEval {e : ℕ} (seat : Visible p q v ↪ B e) (x : B e → ℕ → Bool) : F := + Transcript.sample ((q.contract G.units).table v) + (fun j => let y := (visibleBits p q v).symm j; x (seat y.1) y.2.val) + +open scoped Classical in +/-- In the case `.inl j, b`, this construction gives `x (seat j) b.val`. -/ +def tape {e : ℕ} (seat : Visible p q v ↪ B e) (x : B e → ℕ → Bool) + (z : Inner q v → Bool) : Tape p q v + | .inl j, b => x (seat j) b.val + | .inr j, b => z (j, b) + +open scoped Classical in +/-- The previous of type `F`, constructed using `oldMap p q v i.val i.property.2`. -/ +def previous (f : Tape p q v) (i : Live q v) : F := + let m := oldMap p q v i.val i.property.2 + (History.original S (oldLabel p i.val)).weight + (fun j t => f (m.slot j t.pos) (t.cast (m.size _ _).symm)) + +open scoped Classical in +/-- Returns `f (demand p q v i t h) j` when `h : demandSite q i t = v` holds, and `false` +otherwise. -/ +def inBits (f : Tape p q v) (t : Bool) (j : Fin u) (i : G.E) : Bool := + if h : demandSite q i t = v then f (demand p q v i t h) j else false + +open scoped Classical in +/-- The out bits of type `Bool` for the given inputs. -/ +def outBits (f : Tape p q v) (j : Fin u) (i : q.wire) : Bool := + if h : supplySite q i false = v then + f (supply p q v i false h) (j.cast (width_supply p q v i false h).symm) + else if h : supplySite q i true = v then + f (supply p q v i true h) (j.cast (width_supply p q v i true h).symm) + else false + +open scoped Classical in +/-- The value specified by `∏ j : Fin u, q.rule.entry () v (inBits p q v f false j) (inBits p q +v f true j) (outBits p q v f j)`. -/ +def created (f : Tape p q v) : F := + ∏ j : Fin u, q.rule.entry () v (inBits p q v f false j) (inBits p q v f true j) (outBits p q v f + j) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # The contracted station as a local sum of products -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing Coloring + +variable {T F : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u a : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} (p : S.Posting r G) + {B' W : ℝ} {Hcap D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B' W Hcap D) + (v : Cell a × q.vertex) + +open scoped Classical in +private theorem created_eq (w : Bit (cluster q) → Bool) : + created p q v (fun i t => w (bit p q v i t)) = factor (cluster q) (.inr v) w := by + rw [new_factor] + apply Finset.prod_congr rfl + intro j _ + apply q.rule.local' + · intro i hi + change demandSite q i false = v at hi + rw [inBits, dite_eq_left hi] + exact congrArg w (address_demand_new p q v i false hi j).symm + · intro i hi + change demandSite q i true = v at hi + rw [inBits, dite_eq_left hi] + exact congrArg w (address_demand_new p q v i true hi j).symm + · intro i hi + by_cases hs : supplySite q i false = v + · rw [outBits, dite_eq_left hs] + exact congrArg w (address_supply p q v i false hs j).symm + have ht : supplySite q i true = v := hi.resolve_left hs + rw [outBits, dite_eq_right hs, dite_eq_left ht] + exact congrArg w (address_supply p q v i true ht j).symm + +open scoped Classical in +private def coord : (i : Port p q v) → Fin (width p q v i) → Exposed p q v ⊕ Inner q v + | .inl j, b => .inl ⟨j, b⟩ + | .inr j, b => .inr (j, b) + +open scoped Classical in +private def history : History F (Exposed p q v) where + A := Live q v ⊕ Unit + E := Inner q v + I _ := Exposed p q v ⊕ Inner q v + value i b := + let f := fun j t => b (coord p q v j t) + Sum.elim (previous p q v f) (fun _ => created p q v f) i + read _ := id + +open scoped Classical in +private def atom : Live q v ⊕ Unit ↪ {t // (cluster q).owner t = v} where + toFun := Sum.elim (fun i => ⟨.inl i.val, i.property.2⟩) (fun _ => ⟨.inr v, rfl⟩) + inj' := by + rintro (i|⟨⟩) (j|⟨⟩) e + · exact congrArg Sum.inl (Subtype.ext (Sum.inl.inj (congrArg Subtype.val e))) + · cases congrArg Subtype.val e + · cases congrArg Subtype.val e + · rfl + +variable (hn : ∀ w, G.diagram.arity w = 0 → ∀ z, Transcript.sample (G.diagram.table w) z = 1) + +open scoped Classical in +/-- Enumerates the edges between contracted positions using the selected contraction. -/ +local instance : Fintype ((before q).Between (Sum.elim (q.assign G.units ()) id)) := + (q.contract G.units).fe + +open scoped Classical in +private def exposed : (cluster q).collapse.Port v ≃ Exposed p q v := (visibleBits p q v).symm + +open scoped Classical in +private def traces : Traces (cluster q) (history p q v) v (exposed p q v) where + atom := atom q v + hidden := hiddenBits q v + entry i w := by + have he : (fun j t => w (embed (cluster q) (history p q v) v + (exposed p q v) (hiddenBits q v) (coord p q v j t))) = + (fun j t => w (bit p q v j t)) := by + funext j t + cases j with + | inl j => exact congrArg (w ∘ Sum.inl) (visible_pin p q v ⟨j, t⟩) + | inr j => rfl + change Sum.elim (previous p q v _) (fun _ => created p q v _) i = _ + erw [he] + cases i with + | inl i => exact (oldMap p q v i.val i.property.2).value w + | inr i => exact created_eq p q v w + idle := by + rintro ⟨i|j, h⟩ hi w + · have hz : G.diagram.arity i = 0 := Nat.eq_zero_of_not_pos + (fun hp => hi ⟨.inl ⟨i, hp, h⟩, rfl⟩) + exact (old_factor q w i).trans (hn i hz _) + · change j = v at h + subst j + exact (hi ⟨.inr (), rfl⟩).elim + +include hn in +open scoped Classical in +theorem eval_formula {e : ℕ} (seat : Visible p q v ↪ B e) (x : B e → ℕ → Bool) : + localEval p q v seat x = ∑ z : Inner q v → Bool, + (∏ i : Live q v, previous p q v (tape p q v seat x z) i) * created p q v (tape p q v seat x + z) := by + let a (j : Exposed p q v) := x (seat j.1) j.2.val + refine ((traces p q v hn).correct a).symm.trans ?_ + unfold History.eval + dsimp only [history] + refine Finset.sum_congr (congrArg (@Finset.univ _) (Subsingleton.elim _ _)) ?_ + intro z _ + have he : (fun j t => Sum.elim a z (coord p q v j t)) = tape p q v seat x z := by + funext j t + cases j <;> rfl + change (∏ i : Live q v ⊕ Unit, Sum.elim (previous p q v _) (fun _ => created p q v _) i) = _ + erw [he, Fintype.prod_sum_type] + simp only [Sum.elim_inl, Sum.elim_inr, Fintype.prod_unique] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Scalar withdrawal and composition of restoration budgets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Measure +open Coloring BatchDescent.Phase + +variable (i : Measure) (a b : Wire) + +/-- The quantity computed by `2 ^ i.m * i.long ^ j + 2 ^ (i.m + i.h) * i.short ^ j + (wd a + wd +b) * i.outer ^ j`. -/ +def budget (j : ℕ) := 2 ^ i.m * i.long ^ j + 2 ^ (i.m + i.h) * i.short ^ j + (wd a + + wd b) * i.outer ^ j + +theorem add (k l : ℕ) : i.budget a b k + i.budget a b l ≤ i.budget a b (max k l + 1) := by + unfold budget + rw [add_add_add_comm, add_add_add_comm (2 ^ i.m * i.long ^ k), ← mul_add, ← mul_add, ← mul_add] + exact Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ (Poly.pow_sum i.long_two ..)) + (Nat.mul_le_mul_left _ (Poly.pow_sum i.short_two ..))) (Nat.mul_le_mul_left _ (Poly.pow_sum + i.two ..)) + +/-- The construction uses `(script i.A.scheme).width` for its intermediate `k`. -/ +def sweep := + let k := (script i.A.scheme).width + 2 ^ (i.m + i.l) * (4 * (8 * (i.m + i.l)) + 2 ^ i.h * (1 + k + k)) + + 4 * 2 ^ (i.m + i.l) * (2 + 8 * 2 + 2 ^ i.h * k) + 4 * ((i.h + i.snd + 1) * (2 * (2 ^ (i.m + + i.l) + wd a + wd b))) + +theorem sweep_estimate (u : ℕ) (Q : Rounds.Layer i.F a b) + (hq : Q.template = result i.A i.N i.r i.s u) + (hv : Q.volume = 2 ^ (i.m + i.l) + wd a + wd b) (ht : Q.height = i.h + i.snd) : + Q.encoding.sweepCost ≤ i.sweep a b := by + have hw := Fmt.width_payload Q.template.scheme.m Q.volume Q.height + have hd (D : Template i.F) : D.header.width = 2 + 2 ^ D.scheme.d * 2 + 2 ^ D.scheme.h * D.count + := by + simp only [Template.header, Group.Flags, Format.width_vec, Format.width_pair, Format.width_addr] + rw [Format.width_bit]; ring + have own : Q.encoding.sweepCost = + 2 ^ Q.template.scheme.m * (4 * (2 ^ Q.template.scheme.d * Q.template.scheme.m)+ + 2 ^ Q.template.scheme.h * (1 + Q.template.scheme.ℓ + Q.template.scheme.ℓ)) + + 4 * 2 ^ Q.template.scheme.m * (2 + 2 ^ Q.template.scheme.d * 2 + + 2 ^ Q.template.scheme.h * Q.template.count)+ + 4 * (Fmt.payload Q.template.scheme.m Q.volume Q.height).width := by + unfold Encoding.sweepCost updateCost + rw [Format.width_addr] + have hc : Q.encoding.extra.width = 2 ^ Q.template.scheme.m * Q.template.header.width := + Format.width_vec _ _ + rw [hc, hd, mul_assoc 4] + rw [own] + refine (Nat.add_le_add_left (Nat.mul_le_mul_left 4 hw) _).trans_eq ?_ + rw [hq, hv, ht] + rfl + +theorem sweep_bound : ∃ K : ℕ, ∀ (i : Measure) a b, i.sweep a b ≤ i.budget a b K := by + have cap : Fast (fun i => i.h + i.snd + 1) := small_num fun i => by unfold outer; omega + have ha := (constantValue 8).mul cap + have hb := (constantValue 32).slow.mul (hosts.add hardware.slow) + have hc := ((hb.add (constantValue 72).slow).add (Fast.slow ha)).mul copies.slow + have hd := ((constantValue 1).add ((constantValue 6).mul script_size)).mul copies + have ho : Poly outer (fun i => 8 * (i.h + i.snd + 1)) := + (Poly.const two 8).mul (Poly.of_le two fun i => by unfold outer; omega) + obtain ⟨l, hl⟩ := hc.bound + obtain ⟨s, hs⟩ := hd.bound + obtain ⟨o, hz⟩ := ho.bound + refine ⟨l + s + o, fun i a b => ?_⟩ + have u := i.long_two + have v := i.short_two + have w := i.two + have hx := (hl i).trans (Nat.pow_le_pow_right (by omega) (show l ≤ l + s + o by omega)) + have hy := (hs i).trans (Nat.pow_le_pow_right (by omega) (show s ≤ l + s + o by omega)) + have hw := (hz i).trans (Nat.pow_le_pow_right (by omega) (show o ≤ l + s + o by omega)) + refine le_trans ?_ (Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ hx) + (Nat.mul_le_mul_left _ hy)) + (Nat.mul_le_mul_left _ hw)) + apply le_of_eq + simp only [sweep, pow_add] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Measure +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Routes.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Routes.lean new file mode 100644 index 0000000000..2f090c7e31 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Reset/Routes.lean @@ -0,0 +1,987 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Delivery +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.ResetLocation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Width +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.HostReset + +/-! +# A reset route determined by the names at one base + +The search space is independent of the ambient types of occurrences +and contacts. Relabelling those types without changing the local data +preserves the entire chosen schedule. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Dispatch + +variable {P Q A B O : Type} [Fintype P] [Fintype Q] [Fintype A] [Fintype B] + {Y w : ℕ} + +open Classical in +/-- The data for the route construction, including `terminal`, `layers`, `config`, `lane`. -/ +structure Route (Y w : ℕ) where + /-- The `Route` component of type `ℕ → Fin Y`. -/ + terminal : ℕ → Fin Y + /-- Stores the layers associated with this `Route`. -/ + layers : ℕ + /-- The `Route` component of type `ℕ → Equiv.Perm (Fin Y)`. -/ + config : ℕ → Equiv.Perm (Fin Y) + /-- The `Route` component of type `ℕ → ℕ × Fin w`. -/ + lane : ℕ → ℕ × Fin w + +open Classical in +/-- The data for the site construction, including `occurrence`, `contact`, `load`, `input`, +`output`. -/ +structure Site (P A : Type) (Y : ℕ) where + /-- The `Site` component of type `P → ℕ`. -/ + occurrence : P → ℕ + /-- The `Site` component of type `A → ℕ`. -/ + contact : A → ℕ + /-- The `Site` component of type `P → ℝ`. -/ + load : P → ℝ + /-- The input data carried by `Site`, with type `A → ℕ`. -/ + input : A → ℕ + /-- The output data carried by `Site`, with type `A → Fin Y`. -/ + output : A → Fin Y + +open Classical in +/-- The data for the route ok construction, including `load`, `cost`, `empty`, `bound`, `route`. -/ +structure RouteOK (D : Site P A Y) (u : ℝ) (s : Route Y w) : Prop where + load : ∀ i, (∑ t, if s.terminal (D.occurrence t) = i then D.load t else 0) * Y ≤ 3 + cost : (s.layers : ℝ) * Y * w * u ≤ 10 + empty : IsEmpty A → s.layers = 0 + bound : ∀ a, (s.lane (D.contact a)).1 < s.layers + route : ∀ a, s.config (s.lane (D.contact a)).1 (s.terminal (D.input a)) = D.output a + input : Function.Injective (fun a => (s.terminal (D.input a), s.lane (D.contact a))) + output : Function.Injective (fun a => (D.output a, s.lane (D.contact a))) + +variable [NeZero Y] [NeZero w] + +open Classical in +instance : Nonempty (Route Y w) := ⟨⟨fun _ => 0, 0, fun _ => .refl _, fun _ => (0, 0)⟩⟩ + +open Classical in +/-- Computes the route by the application `epsilon (RouteOK D u)`. -/ +def route (D : Site P A Y) (w : ℕ) [NeZero w] (u : ℝ) : Route Y w := + epsilon (RouteOK D u) + +open Classical in +/-- The data for the match construction, including `occurrence`, `contact`, `load`, `input`, +`output`. -/ +structure Match (D : Site P A Y) (D' : Site Q B Y) (e : P ≃ Q) (f : A ≃ B) : Prop where + occurrence : ∀ t, D'.occurrence (e t) = D.occurrence t + contact : ∀ a, D'.contact (f a) = D.contact a + load : ∀ t, D'.load (e t) = D.load t + input : ∀ a, D'.input (f a) = D.input a + output : ∀ a, D'.output (f a) = D.output a + +omit [Fintype P] [Fintype Q] [Fintype A] [Fintype B] [NeZero Y] in +open Classical in +theorem Match.symm {D : Site P A Y} {D' : Site Q B Y} {e : P ≃ Q} {f : A ≃ B} + (h : Match D D' e f) : Match D' D e.symm f.symm := by + constructor + · intro t; rw [← h.occurrence, Equiv.apply_symm_apply] + · intro t; rw [← h.contact, Equiv.apply_symm_apply] + · intro t; rw [← h.load, Equiv.apply_symm_apply] + · intro t; rw [← h.input, Equiv.apply_symm_apply] + · intro t; rw [← h.output, Equiv.apply_symm_apply] + +omit [NeZero Y] [NeZero w] [Fintype A] [Fintype B] in +open Classical in +private theorem Match.map {D : Site P A Y} {D' : Site Q B Y} {e : P ≃ Q} {f : A ≃ B} + (h : Match D D' e f) {u : ℝ} {s : Route Y w} (hs : RouteOK D' u s) : RouteOK D u s := by + refine ⟨?_, hs.cost, ?_, ?_, ?_, ?_, ?_⟩ + · intro i + have := hs.load i + rw [← e.sum_comp] at this + simpa only [h.occurrence, h.load] using this + · intro he + exact hs.empty ⟨fun b => he.false (f.symm b)⟩ + · intro a + simpa only [h.contact] using hs.bound (f a) + · intro a + simpa only [h.contact, h.input, h.output] using hs.route (f a) + · simpa only [Function.comp_def, h.contact, h.input] using hs.input.comp f.injective + · simpa only [Function.comp_def, h.contact, h.output] using hs.output.comp f.injective + +omit [Fintype A] [Fintype B] in +open Classical in +theorem route_eq {D : Site P A Y} {D' : Site Q B Y} {e : P ≃ Q} {f : A ≃ B} + (h : Match D D' e f) (u : ℝ) : route D w u = route D' w u := by + unfold route + congr 1 + exact funext fun _ => propext ⟨h.symm.map, h.map⟩ + +open Classical in +theorem route_ok (src : A → P) (dst : A → O) (out : O ↪ Fin Y) (l : P → ℝ) + (on : P → ℕ) (en : A → ℕ) (hp : Function.Injective on) (ha : Function.Injective en) + (u : ℝ) (hu : 0 < u) (ho : (Y : ℝ) ^ 2 * w * u ≤ 1) + (ht : ∑ t, l t ≤ 2) (hi : ∀ t, 0 ≤ l t ∧ l t * Y ≤ 1) + (hs : ∀ t, (∑ a, if src a = t then u else 0) ≤ l t) + (hd : ∀ o, (∑ a, if dst a = o then u else 0) * Y ≤ 9) : + let D := Site.mk on en l (on ∘ src) (out ∘ dst) + RouteOK D u (route D w u) := by + intro D + apply epsilon_spec + obtain ⟨p, k, σ, t, hp', hk, hσ, hin, hout⟩ := + route_good_base (NeZero.pos Y) (NeZero.pos w) u hu ho src dst out l ht hi hs hd + let lane (v : Fin k × Fin w) := (v.1.val, v.2) + have hlane : Function.Injective lane := fun _ _ h => + Prod.ext (Fin.ext (Prod.mk.inj h).1) (Prod.mk.inj h).2 + let z : Route Y w := { + terminal := Function.extend on p (fun _ => 0) + layers := if Nonempty A then k else 0 + config := fun j => if hj : j < k then σ ⟨j, hj⟩ else .refl _ + lane := Function.extend en (lane ∘ t) (fun _ => (0, 0)) + } + have pt v : z.terminal (on v) = p v := hp.extend_apply p (fun _ => 0) v + have lt a : z.lane (en a) = lane (t a) := ha.extend_apply (lane ∘ t) (fun _ => (0, 0)) a + refine ⟨z, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · simpa only [D, pt] using hp' + · by_cases h : Nonempty A <;> simp [z, h, hk] + · intro h; simp [z, not_nonempty_iff.mpr h] + · intro a + rw [show D.contact a = en a from rfl, lt] + simp [z, lane, show Nonempty A from ⟨a⟩] + · intro a + simp only [D, Function.comp_apply, pt, lt] + simpa [z, lane] using hσ a + · intro a b h + apply hin + simpa only [D, Function.comp_apply, pt, lt, Prod.mk.injEq, hlane.eq_iff] using h + · intro a b h + apply hout + simpa only [D, Function.comp_apply, lt, Prod.mk.injEq, hlane.eq_iff] using h + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Dispatch +end + +/- +# Assigning reserved link slots by local names + +Choose a function on natural numbers. Its feasibility predicate depends +only on the named units of one link and that link's capacity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Dispatch + +open Finset +variable {A A' U W : Type} [Fintype A] [Fintype A'] + +open Classical in +/-- Requires `(∀ a, slots (name a) < ⌈c * Y / 8⌉₊) ∧ ∀ k, (∑ a, if slots (name a) = k then u +else 0) * Y ≤ 9`. -/ +def SlotOK (name : A → ℕ) (c : ℝ) (Y : ℕ) (u : ℝ) (slots : ℕ → ℕ) : Prop := + (∀ a, slots (name a) < ⌈c * Y / 8⌉₊) ∧ + ∀ k, (∑ a, if slots (name a) = k then u else 0) * Y ≤ 9 + +open Classical in +/-- Computes the slot code by the application `epsilon (SlotOK name c Y u)`. -/ +def slotCode (name : A → ℕ) (c : ℝ) (Y : ℕ) (u : ℝ) : ℕ → ℕ := + epsilon (SlotOK name c Y u) + +open Classical in +theorem slotCode_eq (name : A → ℕ) (name' : A' → ℕ) (c c' : ℝ) (Y : ℕ) (u : ℝ) + (e : A ≃ A') (he : ∀ a, name' (e a) = name a) (hc : c' = c) : + slotCode name' c' Y u = slotCode name c Y u := by + subst c' + unfold slotCode + congr 1 + funext f + apply propext + unfold SlotOK + rw [e.surjective.forall (p := fun a => f (name' a) < ⌈c * Y / 8⌉₊)] + have hs (k : ℕ) : (∑ a, if f (name' a) = k then u else 0) = + ∑ a, if f (name a) = k then u else 0 := by + rw [← e.sum_comp] + simp only [he] + simp only [he, hs] + +open Classical in +theorem slotCode_ok (name : A → ℕ) (hinj : Function.Injective name) + {c u : ℝ} {Y : ℕ} (hY : 0 < Y) (hu : 0 < u) (he : u * Y ≤ 1) + (h : ∑ _ : A, u ≤ c) : SlotOK name c Y u (slotCode name c Y u) := by + apply epsilon_spec + obtain ⟨s, hs, ht⟩ := delivery_slots (fun _ : A => ()) (fun _ => c) Y hY u hu he + (fun _ => by simpa using h) + refine ⟨Function.extend name s (fun _ => 0), ?_⟩ + simp only [SlotOK, hinj.extend_apply] + exact ⟨hs, fun k => by simpa using ht () k⟩ + +open Classical in +/-- The subtype of `a : {a` satisfying `good a} // edge a.val = i`. -/ +abbrev LinkFiber (good : U → Prop) (edge : U → W) (i : W) := {a : {a // good a} // edge a.val = i} + +variable [Fintype U] (good : U → Prop) (edge : U → W) (cap : W → ℝ) (Y : ℕ) (u : ℝ) (ln : U → ℕ) + +open Classical in +/-- The indexed operation `slotCode (fun a : LinkFiber good edge i => ln a.val.val) (cap i) Y +u`. -/ +def slotsAt (i : W) := + slotCode (fun a : LinkFiber good edge i => ln a.val.val) (cap i) Y u + +open Classical in +theorem assign_slots (hY : 0 < Y) (hu : 0 < u) (he : u * Y ≤ 1) + (hi : ∀ i, Function.Injective (fun a : LinkFiber good edge i => ln a.val.val)) + (hd : ∀ i, push edge (fun a => if good a then u else 0) i ≤ cap i) : + ∃ slot : ∀ a : {a // good a}, Fin ⌈cap (edge a.val) * Y / 8⌉₊, + (∀ a, (slot a).val = slotsAt good edge cap Y u ln (edge a.val) (ln a.val)) ∧ + (∀ i k, (∑ a : {a // good a}, if edge a.val = i ∧ (slot a).val = k then u else 0) * Y ≤ 9) + := by + have ht (i : W) : ∑ _ : LinkFiber good edge i, u ≤ cap i := by + apply le_trans _ (hd i) + rw [sub_sum (fun a : {a // good a} => edge a.val = i) (fun _ => u), + sub_sum good (fun a => if edge a = i then u else 0)] + unfold push + apply sum_le_sum + intro a _ + dsimp only + split_ifs <;> rfl + have hs (i : W) := slotCode_ok _ (hi i) hY hu he (ht i) + let f := slotsAt good edge cap Y u ln + let s (a : {a // good a}) : Fin ⌈cap (edge a.val) * Y / 8⌉₊ := + ⟨f (edge a.val) (ln a.val), (hs (edge a.val)).1 ⟨a, rfl⟩⟩ + refine ⟨s, fun _ => rfl, fun i k => ?_⟩ + have hb := (hs i).2 k + change (∑ a : LinkFiber good edge i, if f i (ln a.val.val) = k then u else 0) * Y ≤ 9 at hb + rw [sub_sum (fun a : {a // good a} => edge a.val = i) + (fun a => if f i (ln a.val) = k then u else 0)] at hb + convert hb using 2 + apply sum_congr rfl + intro a _ + by_cases ha : edge a.val = i <;> simp [ha, s] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Dispatch +end + +/- # A reset delivery determined entirely by named local data -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Dispatch + +open Finset +variable {P U X W : Type} [Fintype P] [Fintype U] {Y w : ℕ} + {leaf : P → X} {point : U → Bool → P} {good : U → Prop} + {edge : U → W} {outLeaf : W → Bool → X} {cap : W → ℝ} + {out : ∀ x, Port outLeaf cap Y x ↪ Fin Y} {l : P → ℝ} {u : ℝ} + +open Classical in +/-- The subtype of `p` satisfying `leaf p = x`. -/ +abbrev Base (leaf : P → X) (x : X) := {p // leaf p = x} + +open Classical in +/-- The site data of type `Site (Base leaf x) (GoodEnd leaf point good x) Y` for the given +inputs. -/ +def siteData + (agree : ∀ a, good a → ∀ t, leaf (point a t) = outLeaf (edge a) t) + (slot : ∀ a : {i // good i}, Fin ⌈cap (edge a.val) * Y / 8⌉₊) + (out : ∀ x, Port outLeaf cap Y x ↪ Fin Y) (l : P → ℝ) + (on : P → ℕ) (en : U → Bool → ℕ) (x : X) : Site (Base leaf x) (GoodEnd leaf point good x) Y := + ⟨fun t => on t.val, fun q => en q.val.1.val q.val.2, fun t => l t.val, + fun q => on (point q.val.1.val q.val.2), + fun q => out x (portOf leaf point good edge outLeaf cap Y agree slot q)⟩ + +open Classical in +/-- Computes the site by the application `siteData m.agree m.slot out l on en x`. -/ +def site (m : Delivery leaf point good edge outLeaf cap Y w out l u) + (on : P → ℕ) (en : U → Bool → ℕ) (x : X) : Site (Base leaf x) (GoodEnd leaf point good x) Y := + siteData m.agree m.slot out l on en x + +variable [NeZero Y] [NeZero w] + +open Classical in +/-- Computes the schedule by the application `route (site m on en x) w u`. -/ +def schedule (m : Delivery leaf point good edge outLeaf cap Y w out l u) + (on : P → ℕ) (en : U → Bool → ℕ) (x : X) : Route Y w := + route (site m on en x) w u + +open Classical in +/-- The local used in the `Dispatch` construction. -/ +structure Local (m : Delivery leaf point good edge outLeaf cap Y w out l u) + (ln : U → ℕ) (on : P → ℕ) (en : U → Bool → ℕ) : Prop where + slot_eq : ∀ a, (m.slot a).val = slotsAt good edge cap Y u ln (edge a.val) (ln a.val) + terminal_eq : ∀ x (t : Base leaf x), m.terminal t.val = (schedule m on en x).terminal (on t.val) + layers_eq : ∀ x, m.layers x = (schedule m on en x).layers + config_eq : ∀ x i, m.config x i = (schedule m on en x).config i.val + lane_eq : ∀ x q, ((m.lane x q).1.val, (m.lane x q).2) = + (schedule m on en x).lane (en q.val.1.val q.val.2) + +open Classical in +private theorem assemble (agree : ∀ a, good a → ∀ t, leaf (point a t) = outLeaf (edge a) t) + (slot : ∀ a : {i // good i}, Fin ⌈cap (edge a.val) * Y / 8⌉₊) + (ln : U → ℕ) (on : P → ℕ) (en : U → Bool → ℕ) + (hslot : ∀ a, (slot a).val = slotsAt good edge cap Y u ln (edge a.val) (ln a.val)) + (hs : ∀ x, + let T := siteData agree slot out l on en x + RouteOK T u (route T w u)) : + ∃ m : Delivery leaf point good edge outLeaf cap Y w out l u, Local m ln on en := by + let T := siteData agree slot out l on en + let v x := route (T x) w u + have hv (x) : RouteOK (T x) u (v x) := hs x + let t (p : P) := (v (leaf p)).terminal (on p) + let E := GoodEnd leaf point good + let raw x (q : E x) := (v x).lane ((T x).contact q) + let j (x : X) (q : E x) : Fin (v x).layers × Fin w := + (⟨(raw x q).1, (hv x).bound q⟩, (raw x q).2) + have ht x (a : Base leaf x) : t a.val = (v x).terminal (on a.val) := by + unfold t; rw [a.property] + have he x (q : E x) : t (point q.val.1.val q.val.2) = (v x).terminal ((T x).input q) := + ht x ⟨_, q.property⟩ + let m : Delivery leaf point good edge outLeaf cap Y w out l u := { + agree := agree + slot := slot + terminal := t + layers := fun x => (v x).layers + config := fun x i => (v x).config i.val + lane := j + load := by + intro x i + have h := (hv x).load i + change (∑ a : Base leaf x, if (v x).terminal (on a.val) = i then l a.val else 0) * Y ≤ 3 at h + simp_rw [← ht x] at h + rw [sub_sum (fun p => leaf p = x) (fun p => if t p = i then l p else 0)] at h + simpa only [push, Prod.mk.injEq, ite_and] using h + cost := fun x => (hv x).cost + empty := fun x => (hv x).empty + routes := fun x q => by rw [he]; exact (hv x).route q + input := fun x => by + intro a b h + apply (hv x).input + simp only [he, Prod.mk.injEq] at h + exact Prod.ext h.1 (congrArg (fun p : Fin (v x).layers × Fin w => (p.1.val, p.2)) h.2) + output := fun x => by + intro a b h + apply (hv x).output + obtain ⟨ha, hb⟩ := Prod.mk.inj h + exact Prod.ext ha (congrArg (fun p : Fin (v x).layers × Fin w => (p.1.val, p.2)) hb) + } + exact ⟨m, hslot, ht, fun _ => rfl, fun _ _ => rfl, fun _ _ => rfl⟩ + +open Classical in +/-- The locations of every slot, terminal and layer are selected from +the local names and data alone. -/ +theorem deliver (leaf : P → X) (point : U → Bool → P) (good : U → Prop) + (edge : U → W) (outLeaf : W → Bool → X) (cap : W → ℝ) (Y w : ℕ) [NeZero Y] [NeZero w] + (out : ∀ x, Port outLeaf cap Y x ↪ Fin Y) (l : P → ℝ) (u : ℝ) + (hY : 0 < Y) (hw : 0 < w) (hu : 0 < u) (overhead : (Y : ℝ) ^ 2 * w * u ≤ 1) + (agree : ∀ a, good a → ∀ t, leaf (point a t) = outLeaf (edge a) t) + (total : ∀ x, push leaf l x ≤ 2) (item : ∀ p, 0 ≤ l p ∧ l p * Y ≤ 1) + (hs : ∀ p, push (Function.uncurry point) (fun _ => u) p ≤ l p) + (hd : ∀ i, push edge (fun a => if good a then u else 0) i ≤ cap i) + (ln : U → ℕ) (on : P → ℕ) (en : U → Bool → ℕ) + (hl : ∀ i, Function.Injective (fun a : LinkFiber good edge i => ln a.val.val)) + (ho : ∀ x, Function.Injective (fun t : Base leaf x => on t.val)) + (he : ∀ x, Function.Injective (fun q : GoodEnd leaf point good x => en q.val.1.val q.val.2)) : + ∃ m : Delivery leaf point good edge outLeaf cap Y w out l u, Local m ln on en := by + have hunit : u * Y ≤ 1 := by + rw [mul_comm] + refine (mul_le_mul_of_nonneg_right ?_ hu.le).trans overhead + exact_mod_cast (Nat.le_pow (by decide : 0 < 2)).trans (Nat.le_mul_of_pos_right (Y ^ 2) hw) + obtain ⟨slot, hslot, hb⟩ := assign_slots good edge cap Y u ln hY hu hunit hl hd + refine assemble agree slot ln on en hslot (fun x => ?_) + let src (q : GoodEnd leaf point good x) : Base leaf x := ⟨point q.val.1.val q.val.2, q.property⟩ + let dst := portOf leaf point good edge outLeaf cap Y agree slot (x := x) + have hbound := delivery_bound leaf point good edge outLeaf cap Y l u hu agree slot hs hb x + exact route_ok src dst (out x) (fun t => l t.val) _ _ (ho x) (he x) u hu overhead + ((sub_sum _ _).le.trans (total x)) (fun t => item t.val) hbound.1 hbound.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Dispatch +end + +/- # Comparing the chosen slots and routes of two local deliveries -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Dispatch + +variable {P U X W Q V Z K : Type} [Fintype P] [Fintype Q] [Fintype U] [Fintype V] + {Y w : ℕ} [NeZero Y] [NeZero w] {u : ℝ} + {leaf : P → X} {point : U → Bool → P} {good : U → Prop} + {edge : U → W} {outLeaf : W → Bool → X} {cap : W → ℝ} + {out : ∀ x, Port outLeaf cap Y x ↪ Fin Y} {l : P → ℝ} + {leaf' : Q → Z} {point' : V → Bool → Q} {good' : V → Prop} + {edge' : V → K} {outLeaf' : K → Bool → Z} {cap' : K → ℝ} + {out' : ∀ x, Port outLeaf' cap' Y x ↪ Fin Y} {l' : Q → ℝ} + {m : Delivery leaf point good edge outLeaf cap Y w out l u} + {m' : Delivery leaf' point' good' edge' outLeaf' cap' Y w out' l' u} + {ln : U → ℕ} {on : P → ℕ} {en : U → Bool → ℕ} + {ln' : V → ℕ} {on' : Q → ℕ} {en' : V → Bool → ℕ} + (hm : Local m ln on en) (hm' : Local m' ln' on' en') + +include hm hm' in +open Classical in +theorem Local.slot_congr {i : W} {j : K} (e : LinkFiber good edge i ≃ LinkFiber good' edge' j) + (h : ∀ a, ln' (e a).val.val = ln a.val.val) (hc : cap i = cap' j) + (a : LinkFiber good edge i) : (m.slot a.val).val = (m'.slot (e a).val).val := by + have he : slotsAt good' edge' cap' Y u ln' j = slotsAt good edge cap Y u ln i := + slotCode_eq _ _ _ _ _ _ e h hc.symm + rw [hm.slot_eq, hm'.slot_eq, a.property, (e a).property, he, h] + +variable {x : X} {y : Z} {e : Base leaf x ≃ Base leaf' y} + {f : GoodEnd leaf point good x ≃ GoodEnd leaf' point' good' y} + +omit [Fintype U] [Fintype V] in +open Classical in +theorem schedule_eq (h : Match (site m on en x) (site m' on' en' y) e f) : + schedule m on en x = schedule m' on' en' y := route_eq h u + +open Classical in +/-- Identify two sets of objects by common injective keys. -/ +theorem equivalent {I J T : Type} (k : I → T) (l : J → T) + (hk : Function.Injective k) (hl : Function.Injective l) + (fwd : ∀ i, ∃ j, k i = l j) (bwd : ∀ j, ∃ i, l j = k i) : + ∃ e : I ≃ J, ∀ i, l (e i) = k i := by + choose e he using fwd + have hi : Function.Injective e := fun i j h => hk (by rw [he, he, h]) + have hs : Function.Surjective e := by + intro j + obtain ⟨i, h⟩ := bwd j + exact ⟨i, hl ((he i).symm.trans h.symm)⟩ + exact ⟨Equiv.ofBijective e ⟨hi, hs⟩, fun i => (he i).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Dispatch +end + +/- +# Local identifiers for the reset election + +Within a single leaf the old block and stub determine the incident +unit. A reserved link can therefore use the outgoing stub to choose +the same lane at both of its endpoints. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +open Packing Coloring + +variable {T F : Type} [Field F] {x y : Wire} {L : Fringe x y T} {h u a k Δ D : ℕ} + {G : HostNet F L h u} {S : Scheme F} {r : S.format.obj} + (p : S.Posting r G) (hu : 0 < u) + {l : G.V → Cell h → ℝ} {v g ε : ℝ} + +open scoped Classical in +/-- Computes the demands by the application `coreDemands G.ix G.edge`. -/ +abbrev demands (G : HostNet F L h u) := coreDemands G.ix G.edge + +variable (Z : Schedule (demands G) G.N (resetDelay G.C Δ D) a k l v g ε) + +open scoped Classical in +/-- The value specified by `(cellIndex h p.2).val`. -/ +def occName (p : G.V × Cell h) : ℕ := (cellIndex h p.2).val + +open scoped Classical in +/-- The value specified by `Encodable.encode (cellIndex h (G.ix i), p.stub i t, t)`. -/ +def endName (i : G.E) (t : Bool) := Encodable.encode (cellIndex h (G.ix i), p.stub i t, t) + +open scoped Classical in +/-- Computes the link name by the application `endName p i false`. -/ +def linkName (i : G.E) := endName p i false + +omit [Field F] in +open scoped Classical in +theorem occName_inj (x : Site G.V h) : + Function.Injective (fun z : {q // Z.leaf q = x} => occName (G := G) z.val) := by + intro t r he + apply Subtype.ext + exact Prod.ext (congrArg (fun z : Site G.V h => z.1) (t.property.trans r.property.symm)) + ((cellIndex h).injective (Fin.ext he)) + +omit [Field F] in +open scoped Classical in +theorem point_side (i : G.E) (t : Bool) : ((demands G).point i t).1 = Scheme.side G i t := by + cases t <;> rfl + +include hu + +open scoped Classical in +theorem endName_inj (x : Site G.V h) : + Function.Injective (fun z : GoodEnd Z.leaf (demands G).point Z.good x => + endName p z.val.1.val z.val.2) := by + rintro ⟨⟨⟨i, hi⟩, t⟩, h₁⟩ ⟨⟨⟨j, hj⟩, t'⟩, h₂⟩ he + obtain ⟨hb, hs⟩ := Prod.mk.inj (Encodable.encode_injective he) + obtain ⟨hs, rfl⟩ := Prod.mk.inj hs + have hh : ((demands G).point i t).1 = ((demands G).point j t).1 := + congrArg (fun z : Site G.V h => z.1) (h₁.trans h₂.symm) + rw [point_side, point_side] at hh + have := p.stub_unique hu i j t hh ((cellIndex h).injective hb) hs + subst j + rfl + +open scoped Classical in +theorem linkName_inj (z : Link Z.base (demands G).ends) : + Function.Injective (fun i : {q : {e // Z.good e} // Z.link q.val = z} => linkName p i.val.val) + := by + intro i j he + obtain ⟨hb, hs⟩ := Prod.mk.inj (Encodable.encode_injective he) + have hh : G.src i.val.val = G.src j.val.val := + congrArg (fun q => q.1.val.1) (i.property.trans j.property.symm) + exact Subtype.ext (Subtype.ext (p.stub_unique hu _ _ false hh + ((cellIndex h).injective hb) (Prod.mk.inj hs).1)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # A normalized schedule and its deterministic reset delivery -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset + +open Packing Coloring + +open scoped Classical in +/-- The data for the setup construction, including `T`, `[finite`, `x`, `y`, `L`. -/ +structure Setup {F : Type} [Field F] (S : Scheme F) (h u a Δ D Y w : ℕ) (B' : ℝ) where + /-- The `Setup` component of type `Type`. -/ + T : Type + [finite : Fintype T] + /-- The `Setup` component of type `Wire`. -/ + x : Wire + /-- The `Setup` component of type `Wire`. -/ + y : Wire + /-- The `Setup` component of type `Fringe x y T`. -/ + L : Fringe x y T + /-- The `Setup` component of type `HostNet F L h u`. -/ + G : HostNet F L h u + /-- The `Setup` component of type `S.format.obj`. -/ + r : S.format.obj + /-- The `Setup` component of type `S.Posting r G`. -/ + post : S.Posting r G + /-- The `Setup` component of type `Chart G.C S.d`. -/ + chart : Chart G.C S.d + /-- The `Setup` field of type `ℕ`. -/ + k : ℕ + /-- The `Setup` field of type `ℝ`. -/ + g : ℝ + /-- The `Setup` field of type `ℝ`. -/ + ε : ℝ + /-- The `Setup` component of type `Schedule (demands G) G.N (resetDelay G.C Δ D) a k (fun v i + => G.load v i / B') ((u : ℝ) / B') g ε`. -/ + Z : Schedule (demands G) G.N (resetDelay G.C Δ D) a k + (fun v i => G.load v i / B') ((u : ℝ) / B') g ε + bound : ∀ x, Nonempty (Chart.Ports (relHi a Z.depth) Z.capacity Y x ↪ Fin Y) + hu : 0 < u + hB : 0 < B' + hΔ : 0 < Δ + deg : ∀ v, (G.C v).card ≤ Δ + space : Y ^ 2 * w ≤ 2 ^ k + unit : (u : ℝ) / B' ≤ 1 / (2 : ℝ) ^ k + +attribute [instance] Setup.finite + +namespace Setup +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + (U : Setup S h u a Δ D Y w B') + +open scoped Classical in +/-- The value specified by `U.chart.plugs U.G.cs (relHi a U.Z.depth) U.Z.capacity U.bound`. -/ +def plugs : U.Z.Plugs Y := U.chart.plugs U.G.cs (relHi a U.Z.depth) U.Z.capacity U.bound + +open scoped Classical in +/-- Uses `U.chart.treePin U.hΔ U.deg x` as the representation. -/ +def pins (x : Site U.G.V (h - a) × Fin Y) := U.chart.treePin U.hΔ U.deg x + +variable [NeZero Y] [NeZero w] + +open scoped Classical in +theorem exists_local : + ∃ v : U.Z.Dispatch U.plugs w, Dispatch.Local v (linkName U.post) (occName (G := U.G)) + (endName U.post) := by + have hspace : (Y : ℝ) ^ 2 * w ≤ (2 : ℝ) ^ U.k := by exact_mod_cast U.space + have hY : (Y : ℝ) ≤ (2 : ℝ) ^ U.k := hspace.trans' (by + exact_mod_cast (Nat.le_pow (by decide : 0 < 2)).trans + (Nat.le_mul_of_pos_right (Y ^ 2) (NeZero.pos w))) + have ho : (Y : ℝ) ^ 2 * w * ((u : ℝ) / B') ≤ 1 := + (mul_le_mul_of_nonneg_right hspace U.Z.width.le).trans + (by rw [mul_comm]; exact (le_div_iff₀ (by positivity)).mp U.unit) + apply Dispatch.deliver _ _ _ _ _ _ _ _ _ _ _ (NeZero.pos Y) (NeZero.pos w) U.Z.width ho + U.Z.routes U.Z.at_leaf + · rintro ⟨v, x⟩ + obtain ⟨hl, hh⟩ := U.Z.sizes v x + exact ⟨hl, (mul_le_mul_of_nonneg_left hY hl).trans ((le_div_iff₀ (by positivity)).mp hh)⟩ + · exact fun p => U.Z.mass p.1 p.2 + · exact U.Z.at_link + · exact linkName_inj U.post U.hu U.Z + · exact occName_inj U.Z + · exact endName_inj U.post U.hu U.Z + +open scoped Classical in +/-- Uses `U.exists_local.choose` as the representation. -/ +def delivery : U.Z.Dispatch U.plugs w := U.exists_local.choose + +open scoped Classical in +theorem local_delivery : Dispatch.Local U.delivery (linkName U.post) + (occName (G := U.G)) (endName U.post) := U.exists_local.choose_spec + +end Setup +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset +end + +/- # Agreement of reset inputs at two hosts within one mixer group -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup + +open Packing Coloring +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + (U V : Setup S h u a Δ D Y w B') (σ : Cell a) (v : U.G.V) (z : V.G.V) + +open scoped Classical in +/-- The value specified by `(demands U.G).contact e`. -/ +abbrev contact (e : U.G.E) : CoreContact U.G.C := (demands U.G).contact e + +open scoped Classical in +theorem ends (e : U.G.E) (t : Bool) : unitEnds (U.contact e) t = Scheme.side U.G e t := + point_side e t + +open scoped Classical in +/-- The data for the related construction, including `ix`, `stub`, `label`. -/ +structure Related (t : Bool) (e : U.G.E) (f : V.G.E) : Prop where + ix : U.G.ix e = V.G.ix f + stub : ∀ b, U.post.stub e b = V.post.stub f b + label : U.chart.label v (Scheme.side U.G e (!t)) = V.chart.label z (Scheme.side V.G f (!t)) + +open scoped Classical in +/-- The maps used in the `Setup` construction. -/ +def Maps := ∀ e t, U.Z.good e → U.Z.group (U.G.ix e) = σ → Scheme.side U.G e t = v → + ∃ f, V.Z.good f ∧ Scheme.side V.G f t = z ∧ Related U V v z t e f + +open scoped Classical in +/-- The data for the agree construction, including `mix`, `leaf`, `load`, `reserves`, +`reserves'`. -/ +structure Agree : Prop where + mix : U.Z.π = V.Z.π + leaf : ∀ j, U.Z.group j = σ → (U.Z.leaf (v, j)).2 = (V.Z.leaf (z, j)).2 + load : ∀ j, U.Z.group j = σ → U.G.load v j = V.G.load z j + reserves : U.chart.Reserves U.Z.capacity V.chart V.Z.capacity U.Z.base V.Z.base v z + reserves' : V.chart.Reserves V.Z.capacity U.chart U.Z.capacity V.Z.base U.Z.base z v + fwd : Maps U V σ v z + bwd : Maps V U σ z v + +variable {U V σ v z} {t : Bool} {e : U.G.E} {f : V.G.E} + +open scoped Classical in +theorem Related.symm (r : Related U V v z t e f) : Related V U z v t f e := + ⟨r.ix.symm, fun b => (r.stub b).symm, r.label.symm⟩ + +open scoped Classical in +theorem Related.name (r : Related U V v z t e f) (b : Bool) : + endName U.post e b = endName V.post f b := by rw [endName, endName, r.ix, r.stub] + +open scoped Classical in +theorem Agree.group (c : Agree U V σ v z) (j : Cell h) : U.Z.group j = V.Z.group j := by + unfold Schedule.group + rw [c.mix] + +open scoped Classical in +theorem Agree.symm (c : Agree U V σ v z) : Agree V U σ z v := + ⟨c.mix.symm, fun j hj => (c.leaf j ((c.group j).trans hj)).symm, + fun j hj => (c.load j ((c.group j).trans hj)).symm, c.reserves', c.reserves, c.bwd, c.fwd⟩ + +open scoped Classical in +theorem Agree.relative (c : Agree U V σ v z) : + U.chart.Reserves U.Z.capacity V.chart V.Z.capacity (relBase a U.Z.base) (relBase a V.Z.base) v + z := by + intro q t ht + obtain ⟨q', h₁, h₂, h₃, h₄⟩ := c.reserves q t ht + exact ⟨q', h₁, h₂, fun i => congrArg (· - a) (h₃ i), h₄⟩ + +open scoped Classical in +theorem unique_contact {x y : CoreContact U.G.C} (hx : unitEnds x t = v) (hy : unitEnds y t = v) + (he : U.chart.label v (unitEnds x (!t)) = U.chart.label v (unitEnds y (!t))) : x = y := by + apply Chart.contact_ext _ _ t (hx.trans hy.symm) + exact U.chart.inj _ (Finset.mem_insert_of_mem (hx ▸ Chart.partner_mem U.G.cs x t)) + (Finset.mem_insert_of_mem (hy ▸ Chart.partner_mem U.G.cs y t)) he + +open scoped Classical in +theorem Agree.contact (c : Agree U V σ v z) (r : Related U V v z t e f) + (he : Scheme.side U.G e t = v) (hf : Scheme.side V.G f t = z) : + Chart.Matches U.Z.base V.Z.base (U.contact e) (V.contact f) ∧ + U.Z.capacity (U.contact e) = V.Z.capacity (V.contact f) := by + obtain ⟨q, hq, hn, hd, hc⟩ := c.reserves (U.contact e) t ((U.ends e t).trans he) + have h : q = V.contact f := by + apply unique_contact hq ((V.ends f t).trans hf) + rw [← hn, U.ends, V.ends] + exact r.label + subst q + exact ⟨hd, hc⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # The scheduled reset uses the local pin and delivery elections -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + (U : Setup S h u a Δ D Y w B') (R : Rotor F Y w) (c : ℝ) + +/-- The data for the fits construction, including `upper`, `full`, `nonneg`, `cost`, `small`. -/ +structure Fits : Prop where + upper : Δ ≤ D + full : ∀ v, (U.G.N v).card ≤ D + nonneg : 0 ≤ c + cost : (Fintype.card R.E : ℝ) ≤ c * Y * w + small : Detour.steps (terminalWidth Δ Y) * U.ε ≤ 1 + +variable [NeZero Y] [NeZero w] {c} + +/-- The result used in the `Setup` construction. -/ +def result (fits : U.Fits R c) : + ResetResult F a U.G.N U.G.src U.G.dst U.G.ix U.G.load u B' (resetWidth c w) + (resetPositions R Δ) (3 + terminalWidth D Y) := + (U.Z.result U.delivery R (NeZero.pos Y) (NeZero.pos w) U.hΔ fits.upper U.G.ns U.G.cs U.G.sub + fits.full U.pins c fits.nonneg fits.cost fits.small).unscale U.hB + +/-- Computes the graph by the application `U.G.afterReset (U.result R fits)`. -/ +abbrev graph (fits : U.Fits R c) := U.G.afterReset (U.result R fits) + +theorem bounds (fits : U.Fits R c) {σ : ℝ} (slack : B' * (Fintype.card U.G.V * 2 ^ a : ℕ) ≤ σ) : + let Q := U.graph R fits + (∀ x y, Q.diagram.eval x y = U.G.diagram.eval x y) ∧ + Fintype.card Q.V ≤ resetPositions R Δ * 2 ^ (h - a) * Fintype.card U.G.V ∧ + Q.Bounded 3 (3 + terminalWidth D Y) (89 * B') ∧ + Q.X ≤ resetWidth c w * (σ + 2 * U.G.X + 2 * U.L.Z) ∧ U.G.Preserves Q ∧ + Q.mass = U.G.mass + 2 * U.G.X ∧ U.G.Tracks Q (resetPositions R Δ + 1) := by + let q := U.result R fits + exact ⟨q.eval_contract _, q.positions, U.G.afterReset_spec q + (by unfold resetWidth; have := fits.nonneg; positivity) slack⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- +# Agreement through a bounded reset neighborhood + +Neighbor names and capacities are shared across groups. Occurrence +labels and unit counts are needed only inside the current group. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + (U V : Setup S h u a Δ D Y w B') + +open scoped Classical in +/-- The indexing data represented by `ℕ → U.G.V → V.G.V → Prop`. -/ +abbrev Relation := ℕ → U.G.V → V.G.V → Prop + +open scoped Classical in +/-- Evaluates `R k y x` at the input `k x y`. -/ +abbrev flip {U V : Setup S h u a Δ D Y w B'} (R : Relation U V) : Relation V U := fun k x y + => R k y x + +open scoped Classical in +/-- The quantity computed by `(demands U.G).amounts ((u : ℝ) / B')`. -/ +abbrev amount := (demands U.G).amounts ((u : ℝ) / B') +open scoped Classical in +/-- The quantity computed by `U.G.load x j / B'`. -/ +abbrev score (x : U.G.V) (j : Cell h) := U.G.load x j / B' +open scoped Classical in +/-- Uses `resetDelay U.G.C Δ D` as the representation. -/ +abbrev delay := resetDelay U.G.C Δ D + +include U in +open scoped Classical in +theorem groups : a ≤ h := (Nat.le_add_right _ _).trans U.Z.block + +variable (σ : Cell a) (R : Relation U V) + +open scoped Classical in +/-- The siblings of type `Prop` for the given inputs. -/ +def Siblings (k : ℕ) (v : U.G.V) (z : V.G.V) : Prop := + ∀ (c : CoreContact U.G.C) t, unitEnds c t = v → ∃ c' : CoreContact V.G.C, + unitEnds c' t = z ∧ R (k + 1) (unitEnds c (!t)) (unitEnds c' (!t)) ∧ + U.chart.label v (unitEnds c (!t)) = V.chart.label z (unitEnds c' (!t)) ∧ + U.Z.capacity c = V.Z.capacity c' ∧ + ∀ j, U.Z.group j = σ → U.amount c j = V.amount c' j + +open scoped Classical in +/-- The data for the survey side construction, including `mix`, `base`, `data`, `edges`, +`siblings`. -/ +structure SurveySide (n : ℕ) : Prop where + mix : U.Z.π = V.Z.π + base : ∀ k v z, R k v z → k ≤ n → U.Z.base v = V.Z.base z + data : ∀ k v z, R k v z → k ≤ n → ∀ j, U.Z.group j = σ → U.G.load v j = V.G.load z j + edges : ∀ k v z, R k v z → k < n → ∀ t ∈ U.G.N v, 16 * U.delay v t < h - a → + 0 < U.delay v t ∧ ∃ t' ∈ V.G.N z, U.delay v t = V.delay z t' ∧ R (k + 1) t t' + siblings : ∀ k v z, R k v z → k < n → U.Siblings V σ R k v z + hits : ∀ k v z, R k v z → k < n → ∀ e t, U.Z.group (U.G.ix e) = σ → Scheme.side U.G e t = v → + ∃ f, Scheme.side V.G f t = z ∧ Related U V v z t e f ∧ + R (k + 1) (Scheme.side U.G e (!t)) (Scheme.side V.G f (!t)) + +open scoped Classical in +/-- The data for the survey construction, including `fwd`, `bwd`. -/ +structure Survey (n : ℕ) : Prop where + fwd : SurveySide U V σ R n + bwd : SurveySide V U σ (flip R) n + +variable {U V σ R} {n k : ℕ} {v : U.G.V} {z : V.G.V} + +open scoped Classical in +theorem Survey.symm (p : Survey U V σ R n) : Survey V U σ (flip R) n := ⟨p.bwd, p.fwd⟩ + +namespace SurveySide +variable (p : SurveySide U V σ R n) +include p + +open scoped Classical in +theorem group (j : Cell h) : U.Z.group j = V.Z.group j := by unfold Schedule.group; rw [p.mix] + +open scoped Classical in +theorem spread (hk : k + (h - a) ≤ n) : + Forward U.groups U.Z.π.toEquiv σ (fun i => R (k + i)) + U.G.N V.G.N (fun v w => 8 * U.delay v w) (fun v w => 8 * V.delay v w) U.score V.score := by + constructor + · intro v x + exact (U.Z.sizes v x).2.trans (by + apply (div_le_iff₀ (by positivity)).mpr + simp only [one_mul] + exact one_le_pow₀ (by norm_num)) + · intro i v z hR hi x hx + exact congrArg (·/B') (p.data (k + i) v z hR (by omega) x hx) + · intro i v z hR hi t ht hd + obtain ⟨hq, t', ht', he, hr⟩ := p.edges (k + i) v z hR (by omega) t ht (by omega) + exact ⟨by omega, t', ht', congrArg (8*·) he, hr⟩ + +open scoped Classical in +theorem matchBase (hk : k < n) (hR : R k v z) {c : CoreContact U.G.C} {c' : CoreContact V.G.C} + {t : Bool} (he : unitEnds c t = v) (he' : unitEnds c' t = z) + (hp : R (k + 1) (unitEnds c (!t)) (unitEnds c' (!t))) : Chart.Matches U.Z.base V.Z.base c c' + := by + intro b + by_cases hb : b = t + · rw [hb, he, he'] + exact p.base _ _ _ hR hk.le + have : b = !t := by cases b <;> cases t <;> first | rfl | contradiction + rw [this] + exact p.base _ _ _ hp hk + +open scoped Classical in +theorem reserves (hk : k < n) (hR : R k v z) : + U.chart.Reserves U.Z.capacity V.chart V.Z.capacity U.Z.base V.Z.base v z := by + intro c t hc + obtain ⟨c', hc', hp, he, hw, _⟩ := p.siblings _ _ _ hR hk c t hc + exact ⟨c', hc', he, p.matchBase hk hR hc hc' hp, hw⟩ + +open scoped Classical in +theorem contacts (hk : k < n) (hR : R k v z) : + Contacts U.groups U.Z.π.toEquiv σ U.Z.base unitEnds U.amount U.Z.capacity + V.Z.base unitEnds V.amount V.Z.capacity v z := by + intro c t hc + obtain ⟨c', hc', hp, _, hw, hs⟩ := p.siblings _ _ _ hR hk c t hc + exact ⟨c', hc', (p.matchBase hk hR hc hc' hp).depth, hw, hs⟩ + +open scoped Classical in +theorem failed (hk : k + (h - a) + 1 ≤ n) (hR : R k v z) {x : Cell h} (hx : U.Z.group x = σ) : + U.Z.failed (U.Z.baseOf (v, x)) → V.Z.failed (V.Z.baseOf (z, x)) := by + have hf := (p.spread (k := k) (by omega)).failed hR (U.Z.lo v) (p.base k v z hR (by omega)) + U.Z.depth V.Z.depth (p.contacts (by omega) hR) hx + unfold Schedule.failed Schedule.baseOf + rw [← p.mix] + exact hf + +end SurveySide + +open scoped Classical in +private theorem ancestor_pack {i j : ℕ} (hi : i ≤ h) (hj : j ≤ h) (e : i = j) (x : Cell h) : + (⟨⟨i, by omega⟩, ancestor hi x⟩ : Schedule.Address h) = ⟨⟨j, by omega⟩, ancestor hj x⟩ := by + cases e + rfl + +namespace Survey +variable (p : Survey U V σ R n) +include p + +open scoped Classical in +theorem leaf (hk : k + (h - a) ≤ n) (hR : R k v z) {x : Cell h} (hx : U.Z.group x = σ) : + (U.Z.leaf (v, x)).2 = (V.Z.leaf (z, x)).2 := by + have hf := p.fwd.spread hk + have hg := p.bwd.spread hk + rw [← p.fwd.mix] at hg + have hs := split_eq hf hg hR hR (U.Z.lo v) (p.fwd.base k v z hR (by omega)) x hx + unfold Schedule.leaf leafSite Schedule.mark + rw [← p.fwd.mix] + exact ancestor_pack _ _ (depth_eq (U.Z.π x) hs) _ + +open scoped Classical in +theorem good (hk : k + (h - a) + 2 ≤ n) {e : U.G.E} {f : V.G.E} {t : Bool} (he : U.G.ix e + = V.G.ix f) + (hR : R k (Scheme.side U.G e t) (Scheme.side V.G f t)) + (hh : R (k + 1) (Scheme.side U.G e (!t)) (Scheme.side V.G f (!t))) + (hx : U.Z.group (U.G.ix e) = σ) : U.Z.good e ↔ V.Z.good f := by + have hx' : V.Z.group (U.G.ix e) = σ := (p.fwd.group _).symm.trans hx + have eq (b : Bool) : U.Z.failed (U.Z.baseOf ((demands U.G).point e b)) ↔ + V.Z.failed (V.Z.baseOf ((demands V.G).point f b)) := by + have hm : ∃ m ≤ k + 1, R m (Scheme.side U.G e b) (Scheme.side V.G f b) := by + by_cases hb : b = t + · exact ⟨k, by omega, hb ▸ hR⟩ + have : b = !t := by cases b <;> cases t <;> first | rfl | contradiction + exact ⟨k + 1, le_rfl, this ▸ hh⟩ + obtain ⟨m, hm, hr⟩ := hm + have hh' := p.fwd.failed (k := m) (by omega) hr hx + have hh'' := p.bwd.failed (k := m) (by omega) hr hx' + have key {U : Setup S h u a Δ D Y w B'} (e : U.G.E) : + (demands U.G).point e b = (Scheme.side U.G e b, U.G.ix e) := Prod.ext (point_side e b) rfl + rw [key, key, ← he] + exact ⟨hh', hh''⟩ + exact forall_congr' fun t => not_congr (eq t) + +open scoped Classical in +theorem units (hk : k + (h - a) + 2 ≤ n) (hR : R k v z) : Maps U V σ v z := by + intro e t good hx hv + obtain ⟨f, hz, r, hr⟩ := p.fwd.hits _ _ _ hR (by omega) e t hx hv + refine ⟨f, ?_, hz, r⟩ + apply (p.good hk r.ix _ hr hx).mp good + rw [hv, hz] + exact hR + +open scoped Classical in +theorem agree (hk : k + (h - a) + 2 ≤ n) (hR : R k v z) : Agree U V σ v z := + ⟨p.fwd.mix, fun _ hx => p.leaf (by omega) hR hx, p.fwd.data _ _ _ hR (by omega), + p.fwd.reserves (by omega) hR, p.bwd.reserves (by omega) hR, p.units hk hR, p.symm.units hk hR⟩ + +end Survey +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end + +/- # A common system of local host names for two reset regions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +open Packing Coloring + +variable {F : Type} [Field F] {S : Scheme F} {h u a Δ D Y w : ℕ} {B' : ℝ} + (U V : Setup S h u a Δ D Y w B') (σ : Cell a) (R : Relation U V) (n : ℕ) + +open scoped Classical in +/-- The data for the region construction, including `widen`, `same`, `labels`. -/ +structure Region : Prop extends Survey U V σ R n where + widen : ∀ {k j v z}, k ≤ j → R k v z → R j v z + same : ∀ {v z v' z'}, R n v z → R n v' z' → (v = v' ↔ z = z') + labels : ∀ {k v z v' z'}, k < n → R k v z → R n v' z' → + U.chart.label v v' = V.chart.label z z' + +variable {U V σ R n} + +open scoped Classical in +theorem Region.symm (p : Region U V σ R n) : Region V U σ (flip R) n := + ⟨p.toSurvey.symm, fun h r => p.widen h r, fun r s => (p.same r s).symm, + fun h r s => (p.labels h r s).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Setup +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Answer.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Answer.lean new file mode 100644 index 0000000000..2a0a05d591 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Answer.lean @@ -0,0 +1,1079 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Travel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Shipment.Bound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute + +/-! +# Assigning canonical slots and outlets + +An arbitrary feasible assignment proves the two capacity bounds. +Renumber using the displayed station slots and neighbor indices. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Encloses +open Coloring Packing History.Reset + +variable {F T : Type} [Field F] [Fintype T] {a b x y : Wire} {u N r s : ℕ} + {L : Fringe x y T} {D : Template F} {A : Attachment D} {raw : A.format.obj} + {G : HostNet F L D.scheme.h u} {B' : Border F T a b x y} (q : A.Encloses raw G B') + (e : G.Restore N r s) + +open scoped Classical in +/-- The subtype of `t` satisfying `G.park t = z`. -/ +abbrev Members (z : G.V × Cell D.scheme.h) := {t // G.park t = z} + +open scoped Classical in +/-- Embeds `Members z` into `B A.k where toFun t`. -/ +def memberKey (z : G.V × Cell D.scheme.h) : Members z ↪ B A.k where + toFun t := q.slot t + inj' i j he := Subtype.ext (q.distinct (i.property.trans j.property.symm) he) + +omit [Field F] in +include e in +open scoped Classical in +theorem members_le (z : G.V × Cell D.scheme.h) : Fintype.card (Members z) ≤ r := by + let f : Members z → Fin r := fun t => e.slot t.val + have hf : Function.Injective f := fun i j h => + Subtype.ext (e.unique (Prod.ext (i.property.trans j.property.symm) h)) + simpa using Fintype.card_le_of_injective f hf + +open scoped Classical in +/-- The value specified by `rank (q.memberKey (G.park t)) (members_le e _) ⟨t, rfl⟩`. -/ +def number (t : T) : Fin r := rank (q.memberKey (G.park t)) (members_le e _) ⟨t, rfl⟩ + +open scoped Classical in +theorem number_at (t : T) (z : G.V × Cell D.scheme.h) (h : G.park t = z) : + q.number e t = rank (q.memberKey z) (members_le e z) ⟨t, h⟩ := by subst z; rfl + +open scoped Classical in +/-- The subtype of `v` satisfying `∃ i, L.tensor i = t ∧ (G.far i).1 = v`. -/ +abbrev Rack (G : HostNet F L D.scheme.h u) (t : T) := + {v // ∃ i, L.tensor i = t ∧ (G.far i).1 = v} + +omit [Field F] [Fintype T] in +open scoped Classical in +theorem rack_near {t : T} (v : Rack G t) : v.val ∈ G.N (G.park t).1 := by + obtain ⟨i, hf, he⟩ := v.property + rw [← he, ← hf] + exact G.ns _ _ (G.tether i).2.2 + +open scoped Classical in +/-- Computes the chart by the application `q.core.fullChart q.full`. -/ +abbrev chart := q.core.fullChart q.full + +open scoped Classical in +/-- Embeds `Rack G t` into `Option (B D.scheme.d) where toFun v`. -/ +def rackKey (t : T) : Rack G t ↪ Option (B D.scheme.d) where + toFun v := q.chart.label (G.park t).1 v.val + inj' i j h := Subtype.ext (q.chart.inj _ (Finset.mem_insert_of_mem (rack_near i)) + (Finset.mem_insert_of_mem (rack_near j)) h) + +omit [Field F] [Fintype T] in +include e in +open scoped Classical in +theorem rack_le (t : T) : Fintype.card (Rack G t) ≤ s := by + let f : Rack G t → Fin s := fun v => e.pin v.property.choose + have hf : Function.Injective f := by + intro v w h + have hv := v.property.choose_spec + have hw := w.property.choose_spec + have he := (e.outlet _ _ (hv.1.trans hw.1.symm)).mp h + exact Subtype.ext (hv.2.symm.trans ((congrArg Prod.fst he).trans hw.2)) + simpa using Fintype.card_le_of_injective f hf + +open scoped Classical in +/-- The value specified by `rank (q.rackKey (L.tensor i)) (rack_le e _) ⟨(G.far i).1, i, rfl, +rfl⟩`. -/ +def pin (i : slots x ⊕ slots y) : Fin s := + rank (q.rackKey (L.tensor i)) (rack_le e _) ⟨(G.far i).1, i, rfl, rfl⟩ + +open scoped Classical in +theorem pin_at (i : slots x ⊕ slots y) (t : T) (h : L.tensor i = t) : + q.pin e i = rank (q.rackKey t) (rack_le e _) ⟨(G.far i).1, i, h, rfl⟩ := by subst t; rfl + +open scoped Classical in +/-- Builds `G.Restore N r s where degree` with the specified `degree`, `slot`, `unique`, +`intro`. -/ +abbrev canonical : G.Restore N r s where + degree := e.degree + slot := q.number e + unique := by + intro i j h + obtain ⟨hv, ht⟩ := Prod.mk.inj h + rw [number_at q e _ _ hv, number_at q e j _ rfl] at ht + exact congrArg Subtype.val ((rank (q.memberKey _) _).injective ht) + pin := q.pin e + outlet := by + intro i j h + rw [pin_at q e _ _ h, pin_at q e j _ rfl, (rank (q.rackKey _) _).injective.eq_iff, + Subtype.ext_iff] + have he : (G.far i).2 = (G.far j).2 := + (G.tether i).2.1.trans ((congrArg (fun t => (G.park t).2) h).trans (G.tether j).2.1.symm) + exact ⟨fun k => Prod.ext k he, congrArg Prod.fst⟩ + pins := Restore.pins q.chart e.degree + +include q in +open scoped Classical in +theorem place_inj : Function.Injective G.units.place := by + intro i j h + apply Sum.inl.inj (β := T) + apply q.pres.vertex.injective + rw [q.internal, q.internal, h] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Encloses +end + +/- +# Template and load codes on a restored board + +At a site with ports, round the arity up to the existing positive +floor. This only lowers the charge and makes it computable from the +same record as the tensor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing Finset + +open scoped Classical in +/-- Returns `0` when `n = 0` holds, and `max (n : ℝ) u` otherwise. -/ +def amount (u n : ℕ) : ℝ := if n = 0 then 0 else max (n : ℝ) u + +open scoped Classical in +theorem amount_ge (u n : ℕ) : (n : ℝ) ≤ amount u n := by + unfold amount; split <;> simp_all + +open scoped Classical in +theorem amount_le (u n : ℕ) {c : ℝ} (hc : (n : ℝ) ≤ c) (hs : c = 0 ∨ (u : ℝ) ≤ c) : + amount u n ≤ c := by + by_cases hn : n = 0 + · simpa [amount, hn] using hc + have hp : 0 < (n : ℝ) := Nat.cast_pos.mpr (Nat.pos_of_ne_zero hn) + exact (ite_eq_right hn).le.trans (max_le hc (hs.resolve_left (ne_of_gt (hp.trans_le hc)))) + +variable {F : Type} [Field F] (S : Scheme F) + +open scoped Classical in +/-- Builds `Template F where scheme` with the specified `scheme`, `count`, `load`, `park`. -/ +abbrev template (m h u : ℕ) : Template F where + scheme := Script.scheme S m h + count := (script S).width + load j := amount u (∑ s, Script.size ((script S).serial.symm j) s) + park _ := 0 + past _ := 0 + order := .refl _ + +variable {S} {T : Type} [Fintype T] {a b x y : Wire} {u N r s m : ℕ} + {L : Fringe x y T} {D : Template F} {A : Attachment D} {raw : A.format.obj} + {G : HostNet F L D.scheme.h u} {B' : Border F T a b x y} (q : A.Encloses raw G B') + (e : G.Restore N r s) (hl : ∀ i, G.src i ≠ G.dst i) (E : Directory e.adj m) + +local notation "C" => e.route B' q.tether +local notation "f" => e.frame B' q.tether q.place_inj hl +local notation "U" => template A.scheme m D.scheme.h u + +open scoped Classical in +/-- Builds `Rounds.Board F a b D.scheme.h where V` with the specified `diagram`, `place`, `one`, +`adj`. -/ +abbrev board : Rounds.Board F a b D.scheme.h where + V := e.Space + diagram := (C).graph + place := Prod.swap + one := Prod.swap_injective + adj := e.adj + sym := Tether.adj_symm e.sw G.C G.cs + edge := e.route_support B' q.tether + charge v := amount u ((C).graph.arity v) + cover _ := amount_ge _ _ + +open scoped Classical in +/-- Embeds `Cell D.scheme.h × e.Space` into `B m × B D.scheme.h × B 0 where toFun z`. -/ +def name : Cell D.scheme.h × e.Space ↪ B m × B D.scheme.h × B 0 where + toFun z := (E.host z.2, cellIndex _ z.1, 0) + inj' _ _ he := Prod.ext ((cellIndex _).injective (congrArg (fun v => v.2.1) he)) + (E.host.injective (congrArg Prod.fst he)) + +open scoped Classical in +/-- The indexed operation `(f).encode q.pres (fun i j => E.index i.2 j.2) v`. -/ +def dataAt (v : Cell D.scheme.h × e.Space) := (f).encode q.pres (fun i j => E.index i.2 j.2) v + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def tape (i : B m) (j : B D.scheme.h) : Script A.scheme := + Function.extend (name e E) (dataAt q e hl E) (fun _ => Script.vacant A.scheme) (i, j, 0) + +open scoped Classical in +/-- The display of type `(U).format.obj`, constructed using `(script A.scheme).serial (tape q e +hl E i j)`. -/ +def display : (U).format.obj := + let label i j := (script A.scheme).serial (tape q e hl E i j) + (fun i => (E.nav i, label i), fun i => + ((decide (i ∈ Set.range E.host), false), fun j => (E.flags i j, E.flags i j), label i)) + +open scoped Classical in +theorem tape_at (v : Cell D.scheme.h × e.Space) : + tape q e hl E (E.host v.2) (cellIndex _ v.1) = dataAt q e hl E v := + (name e E).injective.extend_apply _ _ v + +open scoped Classical in +theorem show_label (v : (U).scheme.Vtx) : + (U).scheme.pattern (display q e hl E).1 v = Script.pattern (tape q e hl E v.1 v.2.1) := + congrArg (fun i => Script.pattern i) ((script A.scheme).serial.symm_apply_apply _) + +open scoped Classical in +/-- Builds `Written (f) q.pres (display q e hl E).1 where vertex` with the specified `vertex`, +`index`, `dir`, `code`. -/ +def written : Written (f) q.pres (display q e hl E).1 where + vertex := name e E + index i j := E.index i.2 j.2 + dir := q.directed + code v := by + rw [show_label] + exact congrArg (fun i => Script.pattern i) (tape_at q e hl E v) + idle v hv := by + obtain ⟨i, j, k⟩ := v + have : k = 0 := Fin.eq_zero k + subst k + rw [show_label] + exact congrArg (fun a => Script.pattern a) + (Function.extend_apply' (dataAt q e hl E) (fun _ => Script.vacant A.scheme) _ hv) + nav i b := by + have hi := e.route_support B' q.tether i + cases b + · exact Prod.ext (E.nav_link _ _ hi.2) (Prod.ext (congrArg (cellIndex _) hi.1.symm) rfl) + · exact Prod.ext (E.nav_link _ _ (Tether.adj_symm _ _ G.cs _ _ hi.2)) + (Prod.ext (congrArg (cellIndex _) hi.1) rfl) + +open scoped Classical in +/-- The presents of type `(U).Presents (display q e hl E) (board (D := D) q e) where pres`, +constructed using `written q e hl E`. -/ +def presents : (U).Presents (display q e hl E) (board (D := D) q e) where + pres := (written q e hl E).presentation + host := E.host + vertex _ := rfl + directed := (written q e hl E).directed + live _ := decide_eq_true_iff + closed := E.closed + reciprocal := E.reciprocal + edge := E.marks + core := E.marks + load v i := by + change amount u (∑ j, Script.size ((script A.scheme).serial.symm + ((script A.scheme).serial (tape q e hl E (E.host v) (cellIndex _ i)))) j) = _ + rw [Equiv.symm_apply_apply, tape_at q e hl E (i, v)] + have ht {X Y : Type} [Fintype X] (l : X → ℝ) (g : X → Y) (hg : Function.Injective g) (x : X) : + push g l (g x) = l x := by simp [push, hg.eq_iff] + have hi := ht (board (D := D) q e).charge (board (D := D) q e).place (board (D + := D) q e).one (i, v) + refine Eq.trans ?_ hi.symm + let w := written q e hl E + have hc := Fintype.card_congr (w.seating.pin (i, v)) + simp only [Diagram.Port, Scheme.LocalPin, Fintype.card_sigma, Fintype.card_sum, card_slots, + Fintype.card_fin] at hc + refine congrArg (amount u) (Eq.trans ?_ hc.symm) + exact sum_congr rfl fun j _ => (w.width _ j).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Data at the end of a wire-saving beat -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing + +variable {F : Type} [Field F] {D : Template F} + +open scoped Classical in +/-- The data for the data construction, including `T`, `[finite`, `x`, `y`, `L`. -/ +structure Data (A : Attachment D) (N r s u : ℕ) (a b : Wire) where + /-- The `Data` component of type `Type`. -/ + T : Type + [finite : Fintype T] + /-- The `Data` component of type `Wire`. -/ + x : Wire + /-- The `Data` component of type `Wire`. -/ + y : Wire + /-- The `Data` component of type `Fringe x y T`. -/ + L : Fringe x y T + /-- The `Data` component of type `HostNet F L D.scheme.h u`. -/ + G : HostNet F L D.scheme.h u + /-- The `Data` component of type `Border F T a b x y`. -/ + border : Border F T a b x y + /-- The `Data` component of type `A.format.obj`. -/ + raw : A.format.obj + /-- The `Data` component of type `A.Encloses raw G border`. -/ + q : A.Encloses raw G border + /-- The `Data` component of type `G.Restore N r s`. -/ + allocation : G.Restore N r s + core : ∀ v, (G.C v).card ≤ 3 + loopless : ∀ i, G.src i ≠ G.dst i + +attribute [instance] Data.finite + +namespace Data +variable {A : Attachment D} {N r s u : ℕ} {a b : Wire} (X Y : Data A N r s u a b) + +open scoped Classical in +/-- Computes the e by the application `X.q.canonical X.allocation`. -/ +abbrev e := X.q.canonical X.allocation +open scoped Classical in +/-- Computes the old by the application `X.border.attach X.G.diagram`. -/ +abbrev old := X.border.attach X.G.diagram +open scoped Classical in +/-- Uses `X.q.pres` as the representation. -/ +abbrev p := X.q.pres +open scoped Classical in +/-- Uses `X.q.core.post.host` as the representation. -/ +abbrev host := X.q.core.post.host +open scoped Classical in +/-- Uses `X.e.route X.border X.q.tether` as the representation. -/ +abbrev route := X.e.route X.border X.q.tether +open scoped Classical in +/-- Computes the f by the application `X.e.frame X.border X.q.tether X.q.place_inj X.loopless`. -/ +abbrev f := X.e.frame X.border X.q.tether X.q.place_inj X.loopless +open scoped Classical in +/-- Indexes the space by the coordinates of `Cell D.scheme.h × X.e.Space`. -/ +abbrev Space := Cell D.scheme.h × X.e.Space + +open scoped Classical in +/-- Computes the location by the application `Sum.elim X.G.units.place X.G.park`. -/ +def location : X.old.V → X.G.V × Cell D.scheme.h := Sum.elim X.G.units.place X.G.park +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def seat : X.old.V → B A.k := Sum.elim (fun _ => 0) X.q.slot +open scoped Classical in +/-- Computes the letter by the application `X.raw.2 (X.host v) (cellIndex _ k)`. -/ +def letter (v : X.G.V) (k : Cell D.scheme.h) := X.raw.2 (X.host v) (cellIndex _ k) + +open scoped Classical in +theorem vertex (w : X.old.V) : X.p.vertex w = + (X.host (X.location w).1, cellIndex _ (X.location w).2, X.seat w) := by + cases w + · exact (X.q.internal _).trans (Prod.ext rfl (Prod.ext (X.q.core.block _) rfl)) + · exact (X.q.frozen _).trans (Prod.ext rfl (Prod.ext (X.q.core.block _) rfl)) + +open scoped Classical in +theorem token (w : X.old.V) : + Chain.Frame.token X.p w = (X.letter (X.location w).1 (X.location w).2, X.seat w) := by + unfold Chain.Frame.token + rw [X.vertex] + rfl + +open scoped Classical in +theorem exists_iff (v : X.G.V) (k : Cell D.scheme.h) (j : B A.k) : + (∃ w, X.location w = (v, k) ∧ X.seat w = j) ↔ A.live (X.letter v k) j = true := by + have eq := X.q.occupied (X.host v, cellIndex _ k, j) + change A.live (X.letter v k) j = true ↔ _ at eq + rw [eq] + constructor + · rintro ⟨w, he, hs⟩ + exact ⟨w, by rw [X.vertex, he, hs]⟩ + · rintro ⟨w, hw⟩ + rw [X.vertex] at hw + obtain ⟨ha, hb⟩ := Prod.mk.inj hw + exact ⟨w, Prod.ext (X.host.injective ha) ((cellIndex _).injective (Prod.mk.inj hb).1), + (Prod.mk.inj hb).2⟩ + +open scoped Classical in +theorem seat_core (w : X.old.V) : X.seat w = 0 ↔ w.isLeft := by + cases w + · exact iff_of_true rfl rfl + · exact iff_of_false (X.q.positive _) Bool.false_ne_true + +open scoped Classical in +theorem map_member {v : X.G.V} {v' : Y.G.V} {k : Cell D.scheme.h} + (he : X.letter v k = Y.letter v' k) (i : Attachment.Encloses.Members (G := X.G) (v, k)) : + ∃ j : Attachment.Encloses.Members (G := Y.G) (v', k), + X.q.memberKey _ i = Y.q.memberKey _ j := by + have hi := (X.exists_iff v k (X.q.slot i.val)).mp ⟨.inr i.val, i.property, rfl⟩ + rw [he] at hi + obtain ⟨w, hw, hs⟩ := (Y.exists_iff _ _ _).mpr hi + cases w with + | inl w => exact (X.q.positive _ hs.symm).elim + | inr j => exact ⟨⟨j, hw⟩, hs.symm⟩ + +open scoped Classical in +theorem number_eq {v : X.G.V} {v' : Y.G.V} {k : Cell D.scheme.h} + (he : X.letter v k = Y.letter v' k) {i : X.T} {j : Y.T} + (hi : X.G.park i = (v, k)) (hj : Y.G.park j = (v', k)) (h : X.q.slot i = Y.q.slot j) : + X.e.slot i = Y.e.slot j := by + change X.q.number X.allocation i = Y.q.number Y.allocation j + rw [X.q.number_at X.allocation i _ hi, Y.q.number_at Y.allocation j _ hj] + exact History.Reset.rank_eq (X.map_member Y he) (Y.map_member X he.symm) h + +open scoped Classical in +theorem owner_base (w : X.old.V) : (cells (X.route.owner w).2).1 = (X.location w).1 := by + cases w <;> rfl + +open scoped Classical in +theorem owner_block (w : X.old.V) : (X.route.owner w).1 = (X.location w).2 := by cases w <;> rfl + +open scoped Classical in +theorem owner_eq {v : X.G.V} {v' : Y.G.V} {k : Cell D.scheme.h} {w : X.old.V} {w' : Y.old.V} + (he : X.letter v k = Y.letter v' k) (hw : X.location w = (v, k)) (hw' : Y.location w' = (v', k)) + (h : X.seat w = Y.seat w') : (cells (X.route.owner w).2).2 = (cells (Y.route.owner w').2).2 + := by + rcases w with w|i <;> rcases w' with w'|j + · rfl + · exact (Y.q.positive _ h.symm).elim + · exact (X.q.positive _ h).elim + · exact congrArg (fun t => (Tether.member ((), t) : Tether.Host Unit r s (Tether.width N r s))) + (X.number_eq Y he hw hw' h) + +end Data +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Matching ports and neighbors from equal short labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X Y : Data A N r s u a b) + +open scoped Classical in +/-- Computes the tag by the application `Chain.Frame.token X.p`. -/ +abbrev tag := Chain.Frame.token X.p +open scoped Classical in +/-- Computes the end at by the application `endpoint X.old`. -/ +abbrev endAt := endpoint X.old +open scoped Classical in +/-- The value specified by `(X.p.wirePin e b).1.2`. -/ +abbrev plug (e : X.old.E) (b : Bool) := (X.p.wirePin e b).1.2 +open scoped Classical in +/-- The value specified by `(X.location w).1`. -/ +abbrev base (w : X.old.V) := (X.location w).1 +open scoped Classical in +/-- The value specified by `(X.location w).2`. -/ +abbrev block (w : X.old.V) := (X.location w).2 +open scoped Classical in +/-- The value specified by `(X.p.toSeating.ends q).1.2`. -/ +abbrev port (q : X.old.End) := (X.p.toSeating.ends q).1.2 + +open scoped Classical in +theorem span_at (q : X.old.End) : + (X.p.toSeating.ends q).1 = (X.p.vertex (X.old.station q), X.port q) := by + obtain ⟨⟨w, i⟩, rfl⟩ := X.old.portEquiv.surjective q + rw [Scheme.Seating.ends_at, Diagram.station_port] + unfold port + rw [Scheme.Seating.ends_at] + rfl + +open scoped Classical in +theorem join (e : X.old.E) (t : Bool) : + ∃ j, (A.decode (X.tag (X.endAt e t)).1).peer (X.tag (X.endAt e t)).2 (X.plug e t) = + some (j, X.seat (X.endAt e (!t)), X.plug e (!t)) ∧ + X.q.core.post.nav (X.base (X.endAt e t)) j = X.base (X.endAt e (!t)) ∧ + X.block (X.endAt e t) = X.block (X.endAt e (!t)) := by + have h := X.p.wirePin_peer e t + have hs (u : Bool) : (X.p.wirePin e u).1 = (X.p.vertex (X.endAt e u), X.plug e u) := + Prod.ext (X.p.wirePin_at _ _) rfl + rw [hs, hs, Scheme.peer] at h + change ((A.decode (X.tag (X.endAt e t)).1).peer (X.tag (X.endAt e t)).2 (X.plug e t)).map _ + = _ at h + cases hv : (A.decode (X.tag (X.endAt e t)).1).peer (X.tag (X.endAt e t)).2 (X.plug e t) with + | none => rw [hv] at h; cases h + | some z => + rw [hv, Option.map_some, Option.some.injEq, X.vertex, X.vertex] at h + obtain ⟨w, he⟩ := Prod.mk.inj h + obtain ⟨hn, w⟩ := Prod.mk.inj w + obtain ⟨hb, ht⟩ := Prod.mk.inj w + refine ⟨z.1, congrArg some (Prod.ext rfl (Prod.ext ht he)), ?_, (cellIndex _).injective hb⟩ + exact X.host.injective ((X.q.core.host_nav _ _).trans hn) + +open scoped Classical in +private theorem incident (w : X.old.V) (j : B A.e) + (hw : 0 < (A.decode (X.tag w).1).width (X.tag w).2 j) : + ∃ p, X.old.station p = w ∧ X.port p = j := by + let k : A.scheme.Pin (A.rows X.raw) := ⟨(X.p.vertex w, j), ⟨0, hw⟩⟩ + obtain ⟨p, hp⟩ := X.p.toSeating.ends.surjective k + have he := congrArg Sigma.fst hp + rw [X.span_at] at he + obtain ⟨hv, hs⟩ := Prod.mk.inj he + exact ⟨p, X.p.vertex.injective hv, hs⟩ + +open scoped Classical in +theorem map_port {q : X.old.End} {w : Y.old.V} (he : X.tag (X.old.station q) = Y.tag w) : + ∃ q' : Y.old.End, Y.old.station q' = w ∧ X.port q = Y.port q' ∧ q.isRight = q'.isRight ∧ + (q ∈ Set.range (boundaryEnd X.old) ↔ q' ∈ Set.range (boundaryEnd Y.old)) := by + have hw := (X.p.toSeating.ends q).2.pos + rw [X.span_at] at hw + change + 0 < (A.decode (X.tag (X.old.station q)).1).width (X.tag (X.old.station q)).2 (X.port q) at hw + rw [he] at hw + obtain ⟨q', hv, hs⟩ := Y.incident w (X.port q) hw + subst w + refine ⟨q', rfl, hs.symm, ?_, ?_⟩ + · rw [← X.q.directed q, ← Y.q.directed q', X.span_at, Y.span_at] + exact congrArg₂ (fun t j => (A.decode t.1).direction t.2 j) he hs.symm + · rw [← X.p.no_peer, ← Y.p.no_peer, X.span_at, Y.span_at] + unfold Scheme.peer + simp only [Option.map_eq_none_iff] + exact Iff.of_eq (congrArg₂ (fun (t : B A.ℓ × B A.k) j => (A.decode t.1).peer t.2 j + = none) he hs.symm) + +open scoped Classical in +theorem map_edge (e : X.old.E) (t : Bool) {w : Y.old.V} (he : X.tag (X.endAt e t) = Y.tag w) : + ∃ (g : Y.old.E) (j : B D.scheme.d), + Y.endAt g t = w ∧ X.q.core.post.nav (X.base (X.endAt e t)) j = X.base (X.endAt e (!t)) ∧ + Y.q.core.post.nav (Y.base w) j = Y.base (Y.endAt g (!t)) ∧ + X.seat (X.endAt e (!t)) = Y.seat (Y.endAt g (!t)) ∧ ∀ b, X.plug e b = Y.plug g b := by + obtain ⟨i, hi, hp, ht, hh⟩ := X.map_port Y (q := tip X.old e t) ((congrArg X.tag (station_tip _ + _)).trans he) + rcases Chain.Frame.either i with ⟨v, hv⟩|⟨g, b, rfl⟩ + · obtain ⟨z, hz⟩ := hh.mpr ⟨v, hv.symm⟩ + cases t <;> cases z <;> cases hz + rw [side_tip, side_tip] at ht + subst b + rw [station_tip] at hi + subst w + change X.plug e t = Y.plug g t at hp + obtain ⟨j, hj, ha, _⟩ := X.join e t + obtain ⟨k, hk, hb, _⟩ := Y.join g t + rw [he, hp, hk] at hj + obtain ⟨rfl, hz⟩ := Prod.mk.inj (Option.some.inj hj) + obtain ⟨hs, hl⟩ := Prod.mk.inj hz.symm + exact ⟨g, k, rfl, ha, hb, hs, fun b => by cases t <;> cases b <;> assumption⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # Computing tether outlet numbers from displayed neighbors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X Y : Data A N r s u a b) + +open scoped Classical in +/-- Uses `X.q.core.post.nav` as the representation. -/ +abbrev nav := X.q.core.post.nav +open scoped Classical in +/-- Indexes the edge by the coordinates of `slots X.x ⊕ slots X.y`. -/ +abbrev Edge := slots X.x ⊕ slots X.y + +open scoped Classical in +theorem near_side (i : X.Edge) : + X.endAt (.inr i) i.isRight = .inl (portEnd X.G.diagram i) := by cases i <;> rfl + +open scoped Classical in +theorem far_side (i : X.Edge) : + X.endAt (.inr i) (!i.isRight) = .inr (X.L.tensor i) := by rw [X.q.tether]; cases i <;> rfl + +open scoped Classical in +theorem frozen_end (e : X.old.E) (t : Bool) (v : X.T) (h : X.endAt e t = .inr v) : + ∃ i, e = .inr i ∧ t = !i.isRight ∧ X.L.tensor i = v := by + rw [X.q.tether] + rcases e with e|i|j <;> cases t <;> + first | exact ⟨_, rfl, rfl, Sum.inr.inj h⟩ | exact (Sum.inl_ne_inr h).elim + +open scoped Classical in +/-- The condition `∀ j, X.q.chart.label v (X.nav v j) = Y.q.chart.label w (Y.nav w j)` on the +specified data. -/ +def SameLabels (v : X.G.V) (w : Y.G.V) := + ∀ j, X.q.chart.label v (X.nav v j) = Y.q.chart.label w (Y.nav w j) + +open scoped Classical in +theorem SameLabels.symm {v : X.G.V} {w : Y.G.V} (h : X.SameLabels Y v w) : + Y.SameLabels X w v := fun j => (h j).symm + +open scoped Classical in +theorem rack_map {t : X.T} {t' : Y.T} (ht : X.tag (.inr t) = Y.tag (.inr t')) + (h : X.SameLabels Y (X.G.park t).1 (Y.G.park t').1) + (v : Attachment.Encloses.Rack X.G t) : + ∃ w : Attachment.Encloses.Rack Y.G t', X.q.rackKey t v = Y.q.rackKey t' w := by + obtain ⟨i, hi, he⟩ := v.property + have hp : X.endAt (.inr i) (!i.isRight) = .inr t := (X.far_side i).trans (congrArg Sum.inr hi) + obtain ⟨g, j, hg, ha, hb, _⟩ := X.map_edge Y (.inr i) (!i.isRight) ((congrArg X.tag hp).trans ht) + obtain ⟨q, rfl, hs, hv⟩ := Y.frozen_end g _ _ hg + rw [hp, Bool.not_not, X.near_side] at ha + rw [hs, Bool.not_not, Y.near_side] at hb + refine ⟨⟨(Y.G.far q).1, q, hv, rfl⟩, ?_⟩ + change X.nav (X.G.park t).1 j = (X.G.far i).1 at ha + change Y.nav (Y.G.park t').1 j = (Y.G.far q).1 at hb + exact (congrArg _ (ha.trans he).symm).trans ((h j).trans (congrArg _ hb)) + +open scoped Classical in +theorem outlet_eq (i : X.Edge) (j : Y.Edge) + (hh : X.tag (.inr (X.L.tensor i)) = Y.tag (.inr (Y.L.tensor j))) + (hl : X.SameLabels Y (X.G.park (X.L.tensor i)).1 (Y.G.park (Y.L.tensor j)).1) + (he : X.q.chart.label (X.G.park (X.L.tensor i)).1 (X.G.far i).1 = + Y.q.chart.label (Y.G.park (Y.L.tensor j)).1 (Y.G.far j).1) : + X.e.pin i = Y.e.pin j := by + change X.q.pin X.allocation i = Y.q.pin Y.allocation j + unfold Attachment.Encloses.pin + exact History.Reset.rank_eq (X.rack_map Y hh hl) (Y.rack_map X hh.symm (SameLabels.symm _ _ hl)) + he + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # The parent of each site of a directed path -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring Chain.Frame + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X : Data A N r s u a b) +local notation "W" => Tether.width N r s +local notation "H" => X.route.graph + +open scoped Classical in +/-- The value specified by `(cells v.2).2`. -/ +abbrev part (v : X.Space) := (cells v.2).2 +open scoped Classical in +/-- The value specified by `(cells v.2).1`. -/ +abbrev home (v : X.Space) := (cells v.2).1 + +open scoped Classical in +/-- In the case `.inl _`, this construction gives `decide (k ≠ 0)`. -/ +def which (e : X.old.E) (k : ℕ) := + match e with + | .inl _ => decide (k ≠ 0) + | .inr i => + if (if i.isRight then Tether.Plan.length W s - k else k) ≤ Nat.clog 2 W + + 1 then i.isRight else !i.isRight + +open scoped Classical in +theorem node_home (e : X.old.E) (k : ℕ) : X.home (X.route.node e k) + = X.base (X.endAt e (X.which e k)) := by + rcases e with e|i + · change X.home (if k = 0 then _ else _) = X.base (X.endAt _ (decide (k ≠ 0))) + by_cases h : k = 0 + · rw [ite_eq_left h, decide_eq_false (not_not.mpr h)]; rfl + · rw [ite_eq_right h, decide_eq_true h]; rfl + · change (cells (X.e.travel i k).2).1 = _ + rw [travel_base, which] + by_cases h : (if i.isRight then Tether.Plan.length W s - k else k) ≤ Nat.clog 2 W + 1 + · rw [ite_eq_left h, ite_eq_left h, X.near_side]; rfl + · rw [ite_eq_right h, ite_eq_right h, X.far_side]; rfl + +open scoped Classical in +theorem node_block (e : X.old.E) (k : ℕ) (z : Bool) : + (X.route.node e k).1 = X.block (X.endAt e z) := by + obtain ⟨_, _, _, hg⟩ := X.join e false + have eq : X.block (X.endAt e false) = X.block (X.endAt e true) := hg + have hb (t : Bool) : X.block (X.endAt e t) = X.block (X.endAt e z) := by + cases z <;> cases t <;> first | rfl | exact eq | exact eq.symm + rcases e with e|i + · change (if k = 0 then (X.e.oldCore e).1 else (X.e.oldCore e).2).1 = _ + split <;> first | exact hb false | exact hb true + · refine Eq.trans ?_ (hb i.isRight) + rw [X.near_side] + change (X.e.travel i k).1 = (X.G.far i).2 + unfold HostNet.Restore.travel Tether.Plan.walk + split_ifs <;> rfl + +open scoped Classical in +theorem distinct (e : X.old.E) : Function.Injective (fun z => X.base (X.endAt e z)) := by + have hn : X.base (X.endAt e false) ≠ X.base (X.endAt e true) := by + rcases e with e|q + · change (X.G.units.place (X.G.diagram.source e)).1 ≠ (X.G.units.place (X.G.diagram.target e)).1 + rw [X.G.units.left, X.G.units.right] + exact X.loopless _ + · have hc : X.base (X.endAt (.inr q) q.isRight) ≠ X.base (X.endAt (.inr q) (!q.isRight)) := by + rw [X.near_side, X.far_side] + intro hh + exact (X.G.tether q).1 ((congrArg X.G.frozen hh).mpr (X.G.kept _)) + cases q <;> first | exact hc | exact hc.symm + intro t z h + cases t <;> cases z <;> first | rfl | exact (hn h).elim | exact (hn h.symm).elim + +open scoped Classical in +theorem root_home (z : X.Space) : X.home (X.f.root z) = X.home z := by + rcases z with ⟨k, (w|⟨⟨w, t⟩, p⟩)|⟨w|⟨⟨w, t⟩, p⟩, j⟩⟩ <;> rfl + +open scoped Classical in +theorem leg_eq (i : X.route.Edge) (b : Bool) : X.f.leg i b = X.which i.1 (point i b) := by + apply X.distinct i.1 + have h := congrArg X.home (X.f.anchor (tip H i b)) + rw [X.root_home, station_tip, endpoint_node, ref_tip, station_tip] at h + exact ((X.owner_base _).symm.trans h.symm).trans (X.node_home i.1 _) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # Matching a path between two local computations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X Y : Data A N r s u a b) + +open scoped Classical in +/-- The data for the link construction, including `tags`, `group`, `port`, `labels`, `paired`. -/ +structure Link (e : X.old.E) (g : Y.old.E) : Prop where + tags : ∀ z, X.tag (X.endAt e z) = Y.tag (Y.endAt g z) + group : ∀ z, X.block (X.endAt e z) = Y.block (Y.endAt g z) + port : ∀ z, X.plug e z = Y.plug g z + labels : ∀ z, X.SameLabels Y (X.base (X.endAt e z)) (Y.base (Y.endAt g z)) + paired : ∀ z, LocalPair X.q.chart Y.q.chart (X.base (X.endAt e z)) (X.base (X.endAt e (!z))) + (Y.base (Y.endAt g z)) (Y.base (Y.endAt g (!z))) + +open scoped Classical in +theorem seat_tag (w : X.old.V) : X.seat w = (X.tag w).2 := (congrArg Prod.snd (X.token w)).symm + +variable {X Y} {e : X.old.E} {g : Y.old.E} + +open scoped Classical in +theorem Link.kind (h : X.Link Y e g) (z : Bool) : (X.endAt e z).isLeft = (Y.endAt g z).isLeft := by + have ht : X.seat (X.endAt e z) = Y.seat (Y.endAt g z) := by rw [X.seat_tag, Y.seat_tag, h.tags] + have hh : (X.endAt e z).isLeft = true ↔ (Y.endAt g z).isLeft = true := by + rw [← X.seat_core, ← Y.seat_core, ht] + exact Bool.eq_iff_iff.mpr hh + +open scoped Classical in +theorem Link.cases (h : X.Link Y e g) : + (∃ i j, e = .inl i ∧ g = .inl j) ∨ (∃ i j, e = .inr i ∧ g = .inr j ∧ i.isRight = j.isRight) + := by + have ha := h.kind false + have hb := h.kind true + rcases e with e|i|j <;> rcases g with e'|i'|j' + all_goals + first + | exact .inl ⟨_, _, rfl, rfl⟩ + | exact .inr ⟨_, _, rfl, rfl, rfl⟩ + | cases ha + all_goals cases hb + +open scoped Classical in +theorem Link.turns (h : X.Link Y e g) : X.route.turns e = Y.route.turns g := by + rcases h.cases with ⟨i, j, rfl, rfl⟩ | ⟨i, j, rfl, rfl, eq⟩ <;> rfl + +open scoped Classical in +theorem Link.which (h : X.Link Y e g) (k : ℕ) : X.which e k = Y.which g k := by + rcases h.cases with ⟨i, j, rfl, rfl⟩ | ⟨i, j, rfl, rfl, eq⟩ + · rfl + · simp only [Data.which, eq] + +open scoped Classical in +theorem Link.part (h : X.Link Y e g) (k : ℕ) : X.part (X.route.node e k) + = Y.part (Y.route.node g k) := by + rcases h.cases with ⟨i, j, rfl, rfl⟩ | ⟨i, j, rfl, rfl, dir⟩ + · change X.part (if k = 0 then _ else _) = Y.part (if k = 0 then _ else _) + split_ifs <;> rfl + · have ht := h.tags (!i.isRight) + have hg := h.group (!i.isRight) + have ha := h.labels (!i.isRight) + have hf := h.paired i.isRight + have hb := h.paired (!i.isRight) + rw [Bool.not_not] at hb + rw [X.near_side, X.far_side, dir, Y.near_side, Y.far_side] at hf hb + rw [X.far_side, dir, Y.far_side] at ht hg ha + have hp := X.outlet_eq Y i j ht ha hb.label + have eq : X.e.slot (X.L.tensor i) = Y.e.slot (Y.L.tensor j) := by + simp only [Data.tag, X.token, Y.token] at ht + obtain ⟨hc, hs⟩ := Prod.mk.inj ht + change (X.G.park (X.L.tensor i)).2 = (Y.G.park (Y.L.tensor j)).2 at hg + change X.letter _ (X.G.park (X.L.tensor i)).2 = Y.letter _ (Y.G.park (Y.L.tensor j)).2 at hc + rw [← hg] at hc + exact X.number_eq Y hc rfl (Prod.ext rfl hg.symm) hs + exact travel_suffix X.e Y.e X.q.chart Y.q.chart rfl rfl i j hf hb eq hp dir k + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # A local view sufficient for restoration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X Y : Data A N r s u a b) + +open scoped Classical in +/-- The data for the view construction, including `sees`, `self`, `nav`, `letter`, `labels`. -/ +structure View (v : X.G.V) (w : Y.G.V) (k : Cell D.scheme.h) where + /-- The `View` component of type `X.G.V → Y.G.V → Prop`. -/ + sees : X.G.V → Y.G.V → Prop + self : sees v w + nav : ∀ j, sees (X.nav v j) (Y.nav w j) + letter : ∀ x y, sees x y → X.letter x k = Y.letter y k + labels : ∀ x y, sees x y → X.SameLabels Y x y + pair : ∀ x y t l, sees x y → sees t l → LocalPair X.q.chart Y.q.chart x t y l + +namespace View +variable {X Y} {v : X.G.V} {w : Y.G.V} {k : Cell D.scheme.h} (h : X.View Y v w k) + +open scoped Classical in +/-- Builds `Y.View X w v k where sees x y` with the specified `sees`, `self`, `nav`, `letter`. -/ +def symm : Y.View X w v k where + sees x y := h.sees y x + self := h.self + nav := h.nav + letter _ _ he := (h.letter _ _ he).symm + labels _ _ he := SameLabels.symm _ _ (h.labels _ _ he) + pair _ _ _ _ he ht := + let t := h.pair _ _ _ _ he ht + ⟨t.same.symm, t.full.symm, t.label.symm, t.back, t.forth⟩ + +open scoped Classical in +/-- Requires `x.1 = k ∧ y.1 = k ∧ h.sees (X.home x) (Y.home y) ∧ X.part x = Y.part y`. -/ +def sites (x : X.Space) (y : Y.Space) : Prop := + x.1 = k ∧ y.1 = k ∧ h.sees (X.home x) (Y.home y) ∧ X.part x = Y.part y + +open scoped Classical in +theorem sites_unique {x : X.Space} {y z : Y.Space} (ha : h.sites x y) (hb : h.sites x z) : y = z := + Prod.ext (ha.2.1.trans hb.2.1.symm) + (cells.injective (Prod.ext ((h.pair _ _ _ _ ha.2.2.1 hb.2.2.1).same.mp rfl) + (ha.2.2.2.symm.trans hb.2.2.2))) + +open scoped Classical in +/-- Requires `X.block x = k ∧ Y.block y = k ∧ h.sees (X.base x) (Y.base y) ∧ X.seat x = Y.seat +y`. -/ +def related (x : X.old.V) (y : Y.old.V) : Prop := + X.block x = k ∧ Y.block y = k ∧ h.sees (X.base x) (Y.base y) ∧ X.seat x = Y.seat y + +open scoped Classical in +theorem tags {x : X.old.V} {y : Y.old.V} (he : h.related x y) : X.tag x = Y.tag y := by + simp only [Data.tag, X.token, Y.token] + change (X.letter (X.base x) (X.block x), _) = (Y.letter (Y.base y) (Y.block y), _) + rw [he.1, he.2.1, h.letter _ _ he.2.2.1, he.2.2.2] + +open scoped Classical in +theorem owners {x : X.old.V} {y : Y.old.V} (he : h.related x y) : + h.sites (X.route.owner x) (Y.route.owner y) := by + refine ⟨(X.owner_block _).trans he.1, (Y.owner_block _).trans he.2.1, ?_, ?_⟩ + · change h.sees (cells _).1 (cells _).1 + rw [X.owner_base, Y.owner_base]; exact he.2.2.1 + · exact X.owner_eq Y (h.letter _ _ he.2.2.1) (Prod.ext rfl he.1) (Prod.ext rfl he.2.1) he.2.2.2 + +open scoped Classical in +theorem vertex {x : X.old.V} (hv : X.base x = v) (hk : X.block x = k) : + ∃ y : Y.old.V, Y.base y = w ∧ h.related x y := by + have hh := (X.exists_iff v k (X.seat x)).mp ⟨x, Prod.ext hv hk, rfl⟩ + rw [h.letter _ _ h.self] at hh + obtain ⟨y, hy, hs⟩ := (Y.exists_iff w k _).mpr hh + have hy₁ : Y.base y = w := congrArg Prod.fst hy + exact ⟨y, hy₁, hk, congrArg Prod.snd hy, by rw [hv, hy₁]; exact h.self, hs.symm⟩ + +open scoped Classical in +theorem link (e : X.old.E) (t : Bool) (hv : X.base (X.endAt e t) = v) (hk : X.block (X.endAt e t) + = k) : + ∃ g : Y.old.E, X.Link Y e g ∧ ∀ b, h.related (X.endAt e b) (Y.endAt g b) := by + obtain ⟨y, hy, hh⟩ := h.vertex hv hk + obtain ⟨g, j, hg, hx, hy', hs, hp⟩ := X.map_edge Y e t (h.tags hh) + subst y + have ht : h.related (X.endAt e (!t)) (Y.endAt g (!t)) := by + obtain ⟨_, _, _, hx'⟩ := X.join e t + obtain ⟨_, _, _, hz⟩ := Y.join g t + refine ⟨hx'.symm.trans hh.1, hz.symm.trans hh.2.1, ?_, hs⟩ + rw [← hx, ← hy', hv, hy] + exact h.nav j + have hr (b : Bool) : h.related (X.endAt e b) (Y.endAt g b) + := by cases t <;> cases b <;> assumption + exact ⟨g, ⟨fun z => h.tags (hr z), fun z => (hr z).1.trans (hr z).2.1.symm, hp, + fun z => h.labels _ _ (hr z).2.2.1, fun z => h.pair _ _ _ _ (hr z).2.2.1 (hr (!z)).2.2.1⟩, hr⟩ + +open scoped Classical in +theorem node {e : X.old.E} {g : Y.old.E} (l : X.Link Y e g) + (hr : ∀ b, h.related (X.endAt e b) (Y.endAt g b)) (i : ℕ) : + h.sites (X.route.node e i) (Y.route.node g i) := by + refine ⟨(X.node_block e i false).trans (hr false).1, + (Y.node_block g i false).trans (hr false).2.1, ?_, l.part _⟩ + rw [X.node_home, Y.node_home, l.which] + exact (hr _).2.2.1 + +end View +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # Comparing the original stations and visible relays of two boards -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring Chain.Frame + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} {X Y : Data A N r s u a b} + {v : X.G.V} {w : Y.G.V} {k : Cell D.scheme.h} + {x : X.Space} {y : Y.Space} +local notation "W" => Tether.width N r s + +open scoped Classical in +private def trunk (x : Tether.Host Unit r s W) : Tether.Host Unit r s W := + (Detour.owner x).elim Tether.core (fun p => Tether.member p.1) + +open scoped Classical in +private theorem root_part (x : X.Space) : X.part (X.f.root x) = trunk (X.part x) := by + rcases x with ⟨i, (v|⟨⟨v, t⟩, p⟩)|⟨v|⟨⟨v, t⟩, p⟩, j⟩⟩ <;> rfl + +namespace View +variable (h : X.View Y v w k) + +open scoped Classical in +theorem flip (hs : h.sites x y) : h.symm.sites y x := + ⟨hs.2.1, hs.1, hs.2.2.1, hs.2.2.2.symm⟩ + +open scoped Classical in +theorem homes (hs : h.sites x y) : X.home x = v ↔ Y.home y = w := + (h.pair _ _ _ _ hs.2.2.1 h.self).same + +open scoped Classical in +theorem roots (hs : h.sites x y) : h.sites (X.f.root x) (Y.f.root y) := by + refine ⟨hs.1, hs.2.1, ?_, ?_⟩ + · rw [root_home, root_home]; exact hs.2.2.1 + · rw [root_part, root_part, hs.2.2.2] + +open scoped Classical in +theorem member (hs : h.sites x y) (hv : X.home x = v) {i : X.old.V} (he : X.route.owner i = x) : + ∃ j, Y.route.owner j = y ∧ X.tag i = Y.tag j := by + have hg : X.base i = v := (X.owner_base i).symm.trans ((congrArg X.home he).trans hv) + have hk : X.block i = k := (X.owner_block i).symm.trans ((congrArg Prod.fst he).trans hs.1) + obtain ⟨j, _, hj⟩ := h.vertex hg hk + exact ⟨j, h.sites_unique (he ▸ h.owners hj) hs, h.tags hj⟩ + +open scoped Classical in +theorem occupies (hs : h.sites x y) (hv : X.home x = v) : + x ∈ Set.range X.route.owner ↔ y ∈ Set.range Y.route.owner := by + constructor + · rintro ⟨i, hi⟩ + obtain ⟨j, hj, _⟩ := h.member hs hv hi + exact ⟨j, hj⟩ + · rintro ⟨j, hj⟩ + obtain ⟨i, hi, _⟩ := h.symm.member (h.flip hs) ((h.homes hs).mp hv) hj + exact ⟨i, hi⟩ + +open scoped Classical in +theorem initial (hs : h.sites x y) (hv : X.home x = v) : + Function.extend X.route.owner X.tag (fun _ => (0, 0)) (X.f.root x) = + Function.extend Y.route.owner Y.tag (fun _ => (0, 0)) (Y.f.root y) := by + have eq := h.roots hs + have hr := (X.root_home x).trans hv + by_cases he : X.f.root x ∈ Set.range X.route.owner + · obtain ⟨i, hi⟩ := he + obtain ⟨j, hj, hp⟩ := h.member eq hr hi + rw [← hi, ← hj, X.f.one.extend_apply, Y.f.one.extend_apply, hp] + · rw [Function.extend_apply' _ _ _ he, Function.extend_apply' _ _ _ (mt (h.occupies eq hr).mpr + he)] + +open scoped Classical in +theorem segment (i : X.route.Edge) (b : Bool) (hv : X.home (endpoint X.route.graph i b) = v) + (hk : (endpoint X.route.graph i b).1 = k) : + ∃ j : Y.route.Edge, ∀ t, + h.sites (endpoint X.route.graph i t) (endpoint Y.route.graph j t) ∧ + X.f.lane X.p (tip X.route.graph i t) = Y.f.lane Y.p (tip Y.route.graph j t) := by + have ha := X.node_home i.1 (point i b) + have hb := X.node_block i.1 (point i b) (X.which i.1 (point i b)) + rw [endpoint_node] at hv hk + obtain ⟨g, hg, hr⟩ := h.link i.1 _ (ha.symm.trans hv) (hb.symm.trans hk) + let j : Y.route.Edge := ⟨g, i.2.cast (congrArg (· + 1) hg.turns)⟩ + refine ⟨j, fun t => ?_⟩ + have ht : point i t = point j t := rfl + have hl : X.f.leg i t = Y.f.leg j t := by rw [X.leg_eq, Y.leg_eq, ← ht, hg.which] + constructor + · rw [endpoint_node, endpoint_node, ← ht] + exact h.node hg hr _ + · rw [lane, lane, old_tip, old_tip, side_tip, side_tip, hl] + exact congrArg (fun q => Chain.Frame.pair A.e (t, q)) (hg.port _) + +open scoped Classical in +theorem exterior (i : slots a ⊕ slots b) (hs : h.sites x y) (hv : X.home x = v) + (hi : X.route.graph.station (boundaryEnd X.route.graph i) = x) : + ∃ j, Y.route.graph.station (boundaryEnd Y.route.graph j) = y ∧ + X.f.lane X.p (boundaryEnd X.route.graph i) = Y.f.lane Y.p (boundaryEnd Y.route.graph j) := by + have hx : X.route.owner (X.old.station (boundaryEnd X.old i)) = x := by cases i <;> exact hi + obtain ⟨z, hz, ht⟩ := h.member hs hv hx + obtain ⟨_, he, ha, hb, hm⟩ := X.map_port Y ht + obtain ⟨j, rfl⟩ := hm.mp ⟨i, rfl⟩ + refine ⟨j, ?_, ?_⟩ + · have he := (congrArg Y.route.owner he).trans hz + cases j <;> exact he + · rw [lane, lane, old_boundary, old_boundary] + apply congrArg (Chain.Frame.pair A.e) + exact Prod.ext (by cases i <;> cases j <;> exact hb) ha + +end View +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # Independence of a restored record from remote names -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data.View +open Packing Coloring Chain.Frame + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} {X Y : Data A N r s u a b} + {v : X.G.V} {w : Y.G.V} {k : Cell D.scheme.h} + {x : X.Space} {y : Y.Space} (h : X.View Y v w k) + (l : X.Space → X.Space → B 3) (t : Y.Space → Y.Space → B 3) + +open scoped Classical in +/-- The condition `∀ z z', h.sites z z' → z.2 ∈ X.e.adj x.2 → z'.2 ∈ Y.e.adj y.2 → l x z = t y +z'` on the specified data. -/ +def Aligned (x : X.Space) (y : Y.Space) : Prop := + ∀ z z', h.sites z z' → z.2 ∈ X.e.adj x.2 → z'.2 ∈ Y.e.adj y.2 → l x z = t y z' + +open scoped Classical in +theorem reverse (a : h.Aligned l t x y) : h.symm.Aligned t l y x := + fun z z' hs ha hb => (a z' z (h.symm.flip hs) hb ha).symm + +open scoped Classical in +private theorem adjacent (i : X.route.Edge) (b : Bool) : + (endpoint X.route.graph i (!b)).2 ∈ X.e.adj (endpoint X.route.graph i b).2 := by + have he := (X.e.route_support X.border X.q.tether i).2 + cases b + · exact he + · exact Tether.adj_symm _ _ X.G.cs _ _ he + +open scoped Classical in +theorem reply (hs : h.sites x y) (hv : X.home x = v) (ha : h.Aligned l t x y) + (q : X.route.graph.End) (hq : X.route.graph.station q = x) : + X.f.entry X.p l x (X.f.lane X.p q) = Y.f.entry Y.p t y (X.f.lane X.p q) := by + rcases either q with ⟨i, rfl⟩|⟨e, b, rfl⟩ + · obtain ⟨j, hj, he⟩ := h.exterior i hs hv hq + rw [← hq, X.f.entry_eq X.p l X.q.directed, he, ← hj, Y.f.entry_eq Y.p t Y.q.directed] + cases i <;> cases j <;> rfl + · have hx := (station_tip e b).symm.trans hq + obtain ⟨g, hg⟩ := h.segment e b ((congrArg X.home hx).trans hv) ((congrArg Prod.fst hx).trans + hs.1) + have hy := h.sites_unique (hx ▸ (hg b).1) hs + have ht := ha _ _ (hg (!b)).1 (hx ▸ adjacent e b) (hy ▸ adjacent g b) + rw [← hq, X.f.entry_eq X.p l X.q.directed, (hg b).2, ← (station_tip (G + := Y.route.graph) g b).trans hy, + Y.f.entry_eq Y.p t Y.q.directed, opposite_tip, opposite_tip] + change (true, true, l _ (X.route.graph.station (tip X.route.graph e (!b))), _) = + (true, true, t _ (Y.route.graph.station (tip Y.route.graph g (!b))), _) + simp only [station_tip, hx, hy, ht, (hg (!b)).2] + +open scoped Classical in +theorem answer (hs : h.sites x y) (hv : X.home x = v) (ha : h.Aligned l t x y) : + X.f.encode X.p l x = Y.f.encode Y.p t y := by + apply Prod.ext + · exact decide_eq_decide.mpr (h.occupies hs hv) + refine Prod.ext (h.initial hs hv) ?_ + funext j + change X.f.entry X.p l x j = Y.f.entry Y.p t y j + by_cases a : ∃ q, X.f.mark X.p q = (x, j) + · obtain ⟨q, hq⟩ := a + obtain ⟨hx, rfl⟩ := Prod.mk.inj hq + exact h.reply l t hs hv ha q hx + by_cases b : ∃ q, Y.f.mark Y.p q = (y, j) + · obtain ⟨q, hq⟩ := b + obtain ⟨hy, rfl⟩ := Prod.mk.inj hq + exact (h.symm.reply t l (h.flip hs) ((h.homes hs).mp hv) (h.reverse l t ha) q hy).symm + rw [entry, entry, dite_eq_right a, dite_eq_right b] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data.View +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Exterior.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Exterior.lean new file mode 100644 index 0000000000..c1da22bf1b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Exterior.lean @@ -0,0 +1,1003 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Travel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Answer +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Reads +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.BoardPush +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary + +/-! # Computing the restoration masks once per host -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Neighborhood + +/-- Computes the raw by the application `Format.pair (Rows m d) (.vec m (Group.Flags d))`. -/ +abbrev Raw (m d : ℕ) := Format.pair (Rows m d) (.vec m (Group.Flags d)) + +variable {m d t : ℕ} + +/-- The inspect of type `(Preview d).obj`, constructed using `walks 2 r.1 v`. -/ +def inspect (r : (Raw m d).obj) (v : B m) : (Preview d).obj := + let walk := walks 2 r.1 v + (fun i j => decide (walk i = walk j), fun i => r.2 (walk i)) + +private theorem flags_width : (Group.Flags d).width = 2 ^ (d + 1) := by + rw [Group.Flags, Format.width_vec, Format.width_pair, Format.width_bit, pow_succ] + +private theorem scales (h : m + 2 ^ radius d ≤ t) : m ≤ t ∧ 2 ^ d ≤ t ∧ (Group.Flags d).width ≤ t + := by + have hh : 2 ^ (d + 1) ≤ t := (Nat.pow_le_pow_right (by decide : 0 < 2) (show d + 1 + ≤ radius d by unfold radius; omega)).trans + ((Nat.le_add_left _ _).trans h) + rw [flags_width] + exact ⟨(Nat.le_add_right _ _).trans h, (Nat.pow_le_pow_right (by decide) (by omega)).trans hh, hh⟩ + +theorem rawWidth (h : m + 2 ^ radius d ≤ t) : (Raw m d).width ≤ 2 ^ m * (100 + t) ^ 3 := by + obtain ⟨hm, hd, hf⟩ := scales h + simp only [Raw, Format.width_pair, Format.width_vec, Neighborhood.Rows, Format.width_addr, + ← mul_add] + apply Nat.mul_le_mul_left + rw [Format.width_bit] + have := Nat.mul_le_mul hd hm + ring_nf at this ⊢ + omega + +variable (F : Type) [Field F] + +theorem cheap_preview (h : m + 2 ^ radius d ≤ t) : + Cheap F m t (Raw m d) (.vec m (Preview d)) inspect 60 := by + obtain ⟨hm, _, hf⟩ := scales h + let q := radius d + have hq : 2 ^ q ≤ t := (Nat.le_add_left _ _).trans h + have base := Cheap.id F (rawWidth h) + have route := base.fst.comp ((cheap_walks F m d 2 (by decide)).widen h) + have bits := route.comp (cheap_equal F hm hq) + have take := Cheap.lookup F m t (Group.Flags d) hm hf + have all := Cheap.share _ (fun i => (base.snd.pair (route.comp (column F hm hq i))).comp take) hq + let X := Format.vec q (.vec m (Group.Flags d)) + let Y := Format.vec m (.vec q (Group.Flags d)) + have hb : Y.width ≤ 2 ^ m * (100 + t) ^ 2 := by + rw [show Y.width = 2 ^ m * (2 ^ q * (Group.Flags d).width) by + unfold Y; rw [Format.width_vec, Format.width_vec]] + apply Nat.mul_le_mul_left + nlinarith only [Nat.mul_le_mul hq hf] + have hc : X.width = Y.width := by simp only [X, Y, Format.width_vec]; ring + have copy : Cheap F m t X Y (fun a x i => a i x) 3 := + Cheap.project F (hc.le.trans hb) hb (fun z => (z.2.1, z.1, z.2.2)) fun _ _ => rfl + exact (bits.pair (all.comp copy)).zip.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Extracting a matched view from the masks and nearby letters -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) +local notation "d" => D.scheme.d + +open scoped Classical in +/-- The value specified by `Window.Walks 2 d (.addr A.ℓ)`. -/ +abbrev Letters := Window.Walks 2 d (.addr A.ℓ) +open scoped Classical in +/-- Computes the question by the application `Format.pair .bit (.pair (Preview d) (Letters A))`. -/ +abbrev Question := Format.pair .bit (.pair (Preview d) (Letters A)) + +open scoped Classical in +/-- The value specified by `(D.live raw.1 v, preview D raw.1 v, (Window.reads 2 (A.rows raw) +v).2 k)`. -/ +def query (raw : A.format.obj) (v : B D.scheme.m) (k : B D.scheme.h) : (Question A).obj := + (D.live raw.1 v, preview D raw.1 v, (Window.reads 2 (A.rows raw) v).2 k) + +namespace Data +variable {A} {N r s u : ℕ} {a b : Wire} (X Y : Data A N r s u a b) + {v : X.G.V} {w : Y.G.V} {k : Cell D.scheme.h} + +open scoped Classical in +/-- Computes the word by the application `query A X.raw (X.host v) (cellIndex _ k)`. -/ +abbrev word (v : X.G.V) (k : Cell D.scheme.h) := query A X.raw (X.host v) (cellIndex _ k) + +open scoped Classical in +theorem letter_at (i : Option (B d)) : + (X.word v k).2.2 (address i none) = X.letter (hop X.q.core v i) k := by + change X.raw.2 (Neighborhood.walks 2 (D.nav X.raw.1) (X.host v) (address i none)) _ = _ + rw [follows]; rfl + +open scoped Classical in +theorem agree_at (hh : X.word v k = Y.word w k) : Agree X.q.core Y.q.core v w := + agree _ _ _ _ (congrArg (fun t => t.2.1) hh) + +open scoped Classical in +/-- Builds `X.View Y v w k where sees x y` with the specified `sees`, `self`, `nav`, `letter`. -/ +def observe (hh : X.word v k = Y.word w k) : X.View Y v w k where + sees x y := ∃ i, hop X.q.core v i = x ∧ hop Y.q.core w i = y + self := ⟨none, rfl, rfl⟩ + nav j := ⟨some j, rfl, rfl⟩ + letter := by + rintro _ _ ⟨i, rfl, rfl⟩ + rw [← X.letter_at, ← Y.letter_at, hh] + labels := by + rintro _ _ ⟨i, rfl, rfl⟩ j + exact (X.agree_at Y hh).code X.q.full i i (some j) + pair := by + rintro _ _ _ _ ⟨i, rfl, rfl⟩ ⟨j, rfl, rfl⟩ + exact (X.agree_at Y hh).pair X.q.full i j + +end Data +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- +# Canonical numbering of restored neighbors + +A neighbor is described by a parent channel, possibly stationary, +and the suffix in the other parent's hardware. Rank these pairs +inside the set of at most four actual neighbors. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring Finset + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X Y : Data A N r s u a b) +local notation "W" => Tether.width N r s +local notation "Z" => Tether.Host Unit r s W + +open scoped Classical in +/-- The value specified by `(cells v).1`. -/ +abbrev parent (v : X.e.Space) := (cells v).1 +open scoped Classical in +/-- The value specified by `(cells v).2`. -/ +abbrev seatAt (v : X.e.Space) := (cells v).2 +open scoped Classical in +/-- The value specified by `cells.symm (v, t)`. -/ +abbrev child (v : X.G.V) (t : Z) : X.e.Space := cells.symm (v, t) +open scoped Classical in +/-- Computes the shell by the application `X.e.adj v`. -/ +abbrev shell (v : X.e.Space) := X.e.adj v + +open scoped Classical in +theorem child_parent (v : X.G.V) (t : Z) : X.parent (X.child v t) = v := + congrArg Prod.fst (cells.apply_symm_apply (v, t)) + +open scoped Classical in +theorem child_seat (v : X.G.V) (t : Z) : X.seatAt (X.child v t) = t := + congrArg Prod.snd (cells.apply_symm_apply (v, t)) + +open scoped Classical in +theorem eq_child (v : X.e.Space) : X.child (X.parent v) (X.seatAt v) = v := cells.symm_apply_apply _ + +open scoped Classical in +theorem project_edge {v y : X.e.Space} (h : y ∈ X.shell v) : + X.parent y ∈ insert (X.parent v) (X.G.N (X.parent v)) := + project X.q.chart X.G.ns X.e.degree X.G.sub h + +open scoped Classical in +/-- Indexes the key by the coordinates of `Option (B d) × B t`. -/ +abbrev Key (d t : ℕ) := Option (B d) × B t + +open scoped Classical in +/-- The value specified by `(X.q.chart.label (X.parent v) (X.parent y), suffix r s W (X.seatAt +y))`. -/ +def key (v y : X.e.Space) : Key D.scheme.d (bits r s W) := + (X.q.chart.label (X.parent v) (X.parent y), suffix r s W (X.seatAt y)) + +open scoped Classical in +/-- Embeds `↥(X.shell v)` into `Key D.scheme.d (bits r s W) where toFun y`. -/ +def keys (v : X.e.Space) : ↥(X.shell v) ↪ Key D.scheme.d (bits r s W) where + toFun y := X.key v y + inj' y z he := by + obtain ⟨hh, hr⟩ := Prod.mk.inj he + have eq := X.q.chart.inj _ (X.project_edge y.property) (X.project_edge z.property) hh + exact Subtype.ext (cells.injective (Prod.ext eq ((suffix ..).injective hr))) + +open scoped Classical in +/-- Embeds `↥(X.shell v)` into `B 3`. -/ +def rank (v : X.e.Space) : ↥(X.shell v) ↪ B 3 := + History.Reset.rank (X.keys v) (by + rw [Fintype.card_coe]; exact (Tether.adj_degree X.e.sw X.G.C X.core v).trans (by decide : 4 + ≤ 2 ^ 3)) + +open scoped Classical in +/-- Returns `X.rank v ⟨w, h⟩` when `h : w ∈ X.shell v` holds, and `0` otherwise. -/ +def index (v w : X.e.Space) := if h : w ∈ X.shell v then X.rank v ⟨w, h⟩ else 0 + +open scoped Classical in +theorem decode {v w : X.e.Space} (h : w ∈ X.shell v) : + hop X.q.core (X.parent v) (X.key v w).1 = X.parent w := by + apply History.Reset.label_spec + rcases mem_insert.mp (X.project_edge h) with he|he + · exact .inl he + right + have hh : X.parent w ∈ D.adj X.G (X.parent v) := by simp [Template.adj, X.q.full, he] + obtain ⟨j, hj, _⟩ := (X.q.core.edge _ _).mp hh + exact ⟨j, X.host.injective ((X.q.core.host_nav _ _).trans hj)⟩ + +variable {X Y} {v : X.e.Space} {w : Y.e.Space} + (h : Agree X.q.core Y.q.core (X.parent v) (Y.parent w)) + (eq : X.seatAt v = Y.seatAt w) + +include h eq in +open scoped Classical in +theorem neighbors (z : ↥(X.shell v)) : ∃ t : ↥(Y.shell w), X.keys v z = Y.keys w t := by + let j := (X.key v z.val).1 + let w' := hop Y.q.core (Y.parent w) j + let t := Y.child w' (X.seatAt z.val) + have hv : hop X.q.core (X.parent v) j = X.parent z.val := X.decode z.property + have l := h.pair X.q.full none j + have l' := h.pair X.q.full j none + have c := h.core none j + rw [hv] at l l' c + have mem := links_eq X.q.chart X.G.ns X.e.degree Y.q.chart Y.G.ns Y.e.degree l l' c + (X.seatAt v) (X.seatAt z.val) + change X.child (X.parent z.val) (X.seatAt z.val) ∈ X.shell (X.child (X.parent v) (X.seatAt v)) ↔ + t ∈ Y.shell (Y.child (Y.parent w) (X.seatAt v)) at mem + rw [X.eq_child, X.eq_child, eq, Y.eq_child] at mem + refine ⟨⟨t, mem.mp z.property⟩, ?_⟩ + change X.key v z.val = Y.key w t + unfold key t + rw [Y.child_parent, Y.child_seat] + exact Prod.ext l.label rfl + +include h eq in +open scoped Classical in +theorem index_eq {z : X.e.Space} {t : Y.e.Space} (hz : z ∈ X.shell v) (ht : t ∈ Y.shell w) + (same : X.key v z = Y.key w t) : X.index v z = Y.index w t := by + simp only [index, dite_eq_left hz, dite_eq_left ht] + exact History.Reset.rank_eq (neighbors h eq) (neighbors h.symm eq.symm) same + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # Choosing a single response table for all restored records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X Y : Data A N r s u a b) +local notation "W" => Tether.width N r s +local notation "L" => bits r s W +local notation "m" => D.scheme.m +local notation "Z" => Tether.Host Unit r s W + +open scoped Classical in +/-- Computes the host out by the application `Restore.host X.host r s W`. -/ +abbrev hostOut := Restore.host X.host r s W + +open scoped Classical in +/-- Computes the directory by the application `Directory.numbered X.e.adj (Tether.adj_symm +X.e.sw X.G.C X.G.cs) X.hostOut X.rank`. -/ +def directory : Directory X.e.adj (m + L) := + Directory.numbered X.e.adj (Tether.adj_symm X.e.sw X.G.C X.G.cs) X.hostOut X.rank + +open scoped Classical in +/-- Computes the frame by the application `display X.q X.e X.loopless X.directory`. -/ +abbrev frame := display X.q X.e X.loopless X.directory +open scoped Classical in +/-- Computes the pres by the application `presents X.q X.e X.loopless X.directory`. -/ +abbrev pres := presents X.q X.e X.loopless X.directory +open scoped Classical in +/-- Computes the record by the application `tape X.q X.e X.loopless X.directory`. -/ +abbrev record := tape X.q X.e X.loopless X.directory + +open scoped Classical in +/-- The value specified by `(Match.rowIndex m L).symm (i, j)`. -/ +def combine (i : B m) (j : B L) := (Match.rowIndex m L).symm (i, j) + +open scoped Classical in +theorem child_address (v : X.G.V) (j : Z) : + X.hostOut (X.child v j) = combine (X.host v) (suffix r s W j) := by + unfold combine + apply (Match.rowIndex m L).eq_symm_apply.mpr + rw [hostOut, host_parts, cells.apply_symm_apply] + +open scoped Classical in +theorem child_active (v : B m) (j : B L) : + combine v j ∈ Set.range X.hostOut ↔ D.live X.raw.1 v = true ∧ j ∈ Set.range (suffix r s W) := by + rw [X.q.core.live] + constructor + · rintro ⟨y, hy⟩ + rw [← X.eq_child y, X.child_address] at hy + obtain ⟨hv, hj⟩ := Prod.mk.inj ((Match.rowIndex m L).symm.injective hy) + exact ⟨⟨_, hv⟩, _, hj⟩ + · rintro ⟨⟨v, rfl⟩, ⟨j, rfl⟩⟩ + exact ⟨X.child v j, X.child_address ..⟩ + +open scoped Classical in +theorem record_idle (v : B (m + L)) (k : B D.scheme.h) (hv : v ∉ Set.range X.hostOut) : + X.record v k = Script.vacant A.scheme := by + have hh : (v, k, 0) ∉ Set.range (name X.e X.directory) := by + rintro ⟨z, hz⟩; exact hv ⟨z.2, congrArg Prod.fst hz⟩ + exact Function.extend_apply' (dataAt X.q X.e X.loopless X.directory) (fun _ + => Script.vacant A.scheme) _ hh + +open scoped Classical in +theorem directory_index : X.directory.index = X.index := by + funext v w + unfold directory Directory.numbered index + dsimp only + split_ifs <;> rfl + +open scoped Classical in +theorem record_at (v : X.G.V) (j : Z) (k : Cell D.scheme.h) : + X.record (combine (X.host v) (suffix r s W j)) (cellIndex _ k) = + X.f.encode X.p (fun i j => X.index i.2 j.2) (k, X.child v j) := by + rw [← X.child_address] + rw [← X.directory_index] + exact tape_at X.q X.e X.loopless X.directory (k, X.child v j) + +open scoped Classical in +theorem agree_record {v : X.G.V} {w : Y.G.V} (k : Cell D.scheme.h) + (h : X.word v k = Y.word w k) (j : Z) : + X.record (combine (X.host v) (suffix r s W j)) (cellIndex _ k) = + Y.record (combine (Y.host w) (suffix r s W j)) (cellIndex _ k) := by + rw [X.record_at, Y.record_at] + let f := X.observe Y h + have hx : X.home (k, X.child v j) = v := X.child_parent v j + have hy : Y.home (k, Y.child w j) = w := Y.child_parent w j + have eq : X.seatAt (X.child v j) = Y.seatAt (Y.child w j) + := (X.child_seat ..).trans (Y.child_seat ..).symm + have hs : f.sites (k, X.child v j) (k, Y.child w j) := ⟨rfl, rfl, + by rw [hx, hy]; exact f.self, eq⟩ + apply f.answer _ _ hs hx + intro z t ht ha hb + have hc : Agree X.q.core Y.q.core (X.parent (X.child v j)) (Y.parent (Y.child w j)) := by + rw [X.child_parent, Y.child_parent]; exact X.agree_at Y h + exact index_eq hc eq ha hb (Prod.ext (f.pair _ _ _ _ hs.2.2.1 ht.2.2.1).label + (congrArg (suffix r s W) ht.2.2.2)) + +open scoped Classical in +theorem uniform {v w : B m} {k : B D.scheme.h} (h : query A X.raw v k + = query A Y.raw w k) (j : B L) : + X.record (combine v j) k = Y.record (combine w j) k := by + have hh : D.live X.raw.1 v = D.live Y.raw.1 w := congrArg (fun t : (Question A).obj => t.1) h + have hv : combine v j ∈ Set.range X.hostOut ↔ combine w j ∈ Set.range Y.hostOut := by + rw [X.child_active, Y.child_active, hh] + by_cases he : combine v j ∈ Set.range X.hostOut + · obtain ⟨hl, i, rfl⟩ := (X.child_active ..).mp he + obtain ⟨v, rfl⟩ := (X.q.core.live _).mp hl + obtain ⟨w, rfl⟩ := (Y.q.core.live _).mp (hh.symm.trans hl) + obtain ⟨k, rfl⟩ := (cellIndex _).surjective k + exact X.agree_record Y k h i + · rw [X.record_idle _ _ he, Y.record_idle _ _ (mt hv.mpr he)] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # A short description of the new navigation rows -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X Y : Data A N r s u a b) +local notation "W" => Tether.width N r s +local notation "L" => bits r s W +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d + +open scoped Classical in +/-- The condition `∃ w, X.hostOut w = v ∧ t ∈ X.shell w ∧ X.directory.index w t = i` on the +specified data. -/ +def Next (v : B (m + L)) (i : B 3) (t : X.e.Space) : Prop := + ∃ w, X.hostOut w = v ∧ t ∈ X.shell w ∧ X.directory.index w t = i + +open scoped Classical in +/-- Returns `some (X.key h.choose_spec.choose h.choose)` when `h : ∃ y, X.Next v i y` holds, and +`none` otherwise. -/ +def jump (v : B (m + L)) (i : B 3) : Option (Key d L) := + if h : ∃ y, X.Next v i y then some (X.key h.choose_spec.choose h.choose) else none + +open scoped Classical in +theorem next_eq {v w : X.e.Space} {i : B 3} (h : w ∈ X.shell v) (hi : X.index v w = i) : + X.jump (X.hostOut v) i = some (X.key v w) := by + have ht : ∃ y, X.Next (X.hostOut v) i y := ⟨w, v, rfl, h, by rw [X.directory_index, hi]⟩ + unfold jump + rw [dite_eq_left ht] + have hu := ht.choose_spec.choose_spec + have hv := X.hostOut.injective hu.1 + rw [hv] at hu ⊢ + have he := hu.2.2.trans hi.symm + rw [X.directory_index, index, index, dite_eq_left hu.2.1, dite_eq_left h] at he + exact congrArg (fun w => some (X.key v w)) (congrArg Subtype.val ((X.rank v).injective he)) + +open scoped Classical in +theorem jump_eq {v : X.e.Space} {w : Y.e.Space} (h : Agree X.q.core Y.q.core (X.parent v) (Y.parent + w)) + (eq : X.seatAt v = Y.seatAt w) (i : B 3) : X.jump (X.hostOut v) i = Y.jump (Y.hostOut w) i := by + have transfer (X Y : Data A N r s u a b) (v : X.e.Space) (w : Y.e.Space) + (h : Agree X.q.core Y.q.core (X.parent v) (Y.parent w)) (eq : X.seatAt v = Y.seatAt w) + (ht : ∃ t, X.Next (X.hostOut v) i t) : X.jump (X.hostOut v) i = Y.jump (Y.hostOut w) i := by + obtain ⟨z, t, he, hz, hi⟩ := ht + have := X.hostOut.injective he + subst t + rw [X.directory_index] at hi + obtain ⟨t, ht⟩ := neighbors h eq ⟨z, hz⟩ + have hm := index_eq h eq hz t.property ht + rw [X.next_eq hz hi, Y.next_eq t.property (hm.symm.trans hi)] + exact congrArg some ht + by_cases ha : ∃ t, X.Next (X.hostOut v) i t + · exact transfer _ _ _ _ h eq ha + by_cases hb : ∃ t, Y.Next (Y.hostOut w) i t + · exact (transfer _ _ _ _ h.symm eq.symm hb).symm + rw [jump, jump, dite_eq_right ha, dite_eq_right hb] + +open scoped Classical in +theorem jump_idle {v : B (m + L)} (hv : v ∉ Set.range X.hostOut) (i : B 3) : + X.jump v i = none := dite_eq_right fun ⟨_, t, h, _⟩ => hv ⟨t, h⟩ + +open scoped Classical in +theorem navigate (v : B m) (j : B L) (i : B 3) : + let w := combine v j + X.directory.nav w i = (X.jump w i).elim w (fun z => combine (step (D.nav X.raw.1) v z.1) z.2) ∧ + X.directory.flags w i = (X.jump w i).isSome := by + let w := combine v j + change X.directory.nav w i = _ ∧ _ + have flags : X.directory.flags w i = true ↔ ∃ t, X.Next w i t := by + exact @decide_eq_true_iff _ (Classical.propDecidable _) + by_cases ht : ∃ t, X.Next w i t + · obtain ⟨z, t, he, hz, hi⟩ := ht + have hj := X.next_eq hz (X.directory_index ▸ hi) + rw [he] at hj + change X.directory.nav w i = (X.jump w i).elim w _ ∧ X.directory.flags w i = (X.jump w i).isSome + rw [hj] + refine ⟨?_, flags.mpr ⟨z, t, he, hz, hi⟩⟩ + have hv := X.directory.nav_link t z hz + change X.directory.nav (X.hostOut t) (X.directory.index t z) = X.hostOut z at hv + rw [he, hi] at hv + rw [hv] + have hp : X.host (X.parent t) = v := by + rw [← X.eq_child t, X.child_address] at he + exact (Prod.mk.inj ((Match.rowIndex m L).symm.injective he)).1 + have hs : step (D.nav X.raw.1) v (X.key t z).1 = X.host (X.parent z) := by + rw [← hp, ← X.decode hz] + cases (X.key t z).1 <;> first | rfl | exact (X.q.core.host_nav ..).symm + change X.hostOut z = combine (step (D.nav X.raw.1) v (X.key t z).1) _ + rw [hs] + exact ((congrArg X.hostOut (X.eq_child z)).symm.trans (X.child_address ..)) + · have hj : X.jump w i = none := dite_eq_right ht + change X.directory.nav w i = (X.jump w i).elim w _ ∧ X.directory.flags w i = (X.jump w i).isSome + rw [hj] + refine ⟨?_, Bool.eq_false_iff.mpr (mt flags.mp ht)⟩ + exact dite_eq_right ht + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # A single local lookup for the child header and the block record -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Packing Coloring + +open scoped Classical in +/-- Computes the hint by the application `Format.pair .bit (.pair .bit (.pair (.addr d) (.addr +l)))`. -/ +abbrev Hint (d l : ℕ) := Format.pair .bit (.pair .bit (.pair (.addr d) (.addr l))) +open scoped Classical in +/-- The value specified by `Format.pair (.addr ℓ) (.pair .bit (.vec 3 (Hint d l)))`. -/ +abbrev Output (ℓ d l : ℕ) := Format.pair (.addr ℓ) (.pair .bit (.vec 3 (Hint d l))) + +open scoped Classical in +/-- In the case `none`, this construction gives `(false, false, 0, j)`. -/ +def hint {d l : ℕ} (j : B l) : Option (Data.Key d l) → (Hint d l).obj + | none => (false, false, 0, j) + | some (none, k) => (true, false, 0, k) + | some (some i, k) => (true, true, i, k) + +open scoped Classical in +/-- The value specified by `(Match.rowIndex m l).symm (if q.2.1 then g v q.2.2.1 else v, +q.2.2.2)`. -/ +def follow {m d l : ℕ} (g : B m → B d → B m) (v : B m) (q : (Hint d l).obj) := + (Match.rowIndex m l).symm (if q.2.1 then g v q.2.2.1 else v, q.2.2.2) + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (N r s : ℕ) +local notation "W" => Tether.width N r s +local notation "L" => bits r s W +local notation "m" => D.scheme.m +local notation "h" => D.scheme.h +local notation "d" => D.scheme.d + +open scoped Classical in +/-- Computes the query by the application `Format.pair (.addr h) (.pair (.addr L) (Question +A))`. -/ +abbrev Query := Format.pair (.addr h) (.pair (.addr L) (Question A)) +open scoped Classical in +/-- Computes the reply by the application `Output (script A.scheme).width d L`. -/ +abbrev Reply := Output (script A.scheme).width d L +open scoped Classical in +/-- The quantity computed by `Format.vec (m + L) (.vec h (Reply A N r s))`. -/ +abbrev Replies := Format.vec (m + L) (.vec h (Reply A N r s)) + +open scoped Classical in +/-- The value specified by `(k, (Match.rowIndex m L i).2, query A x (Match.rowIndex m L i).1 +k)`. -/ +def ask (x : A.format.obj) (i : B (m + L)) (k : B h) : (Query A N r s).obj := + (k, (Match.rowIndex m L i).2, query A x (Match.rowIndex m L i).1 k) + +namespace Data +variable {A N r s} {u : ℕ} {a b : Wire} (X Y : Data A N r s u a b) + +open scoped Classical in +/-- The respond of type `(Replies A N r s).obj` for the given inputs. -/ +def respond : (Replies A N r s).obj := fun i k => + ((script A.scheme).serial (X.record i k), decide (i ∈ Set.range X.hostOut), + fun j => hint (Match.rowIndex m L i).2 (X.jump i j)) + +open scoped Classical in +theorem same_jump {v w : B m} {k : B h} (he : query A X.raw v k + = query A Y.raw w k) (j : B L) (i : B 3) : + X.jump (combine v j) i = Y.jump (combine w j) i := by + have hh : D.live X.raw.1 v = D.live Y.raw.1 w := congrArg (fun t : (Question A).obj => t.1) he + have hv : combine v j ∈ Set.range X.hostOut ↔ combine w j ∈ Set.range Y.hostOut := by + rw [X.child_active, Y.child_active, hh] + by_cases hx : combine v j ∈ Set.range X.hostOut + · obtain ⟨hl, z, rfl⟩ := (X.child_active ..).mp hx + obtain ⟨v, rfl⟩ := (X.q.core.live _).mp hl + obtain ⟨w, rfl⟩ := (Y.q.core.live _).mp (hh.symm.trans hl) + obtain ⟨k, rfl⟩ := (cellIndex _).surjective k + rw [← X.child_address, ← Y.child_address] + apply X.jump_eq Y + · rw [X.child_parent, Y.child_parent]; exact X.agree_at Y he + · rw [X.child_seat, Y.child_seat] + · rw [X.jump_idle hx, Y.jump_idle (mt hv.mpr hx)] + +open scoped Classical in +theorem consistent {v w : B (m + L)} {j k : B h} (he : ask A N r s X.raw v j + = ask A N r s Y.raw w k) : + X.respond v j = Y.respond w k := by + obtain ⟨⟨x, i⟩, rfl⟩ := (Match.rowIndex m L).symm.surjective v + obtain ⟨⟨y, l⟩, rfl⟩ := (Match.rowIndex m L).symm.surjective w + simp only [ask, Equiv.apply_symm_apply, Prod.mk.injEq] at he + obtain ⟨rfl, rfl, he⟩ := he + have hv : combine x i ∈ Set.range X.hostOut ↔ combine y i ∈ Set.range Y.hostOut := by + have hh : D.live X.raw.1 x = D.live Y.raw.1 y := congrArg (fun t : (Question A).obj => t.1) he + rw [X.child_active, Y.child_active, hh] + simp only [respond, Equiv.apply_symm_apply] + exact Prod.ext (congrArg (script A.scheme).serial (X.uniform Y he i)) (Prod.ext + (decide_eq_decide.mpr hv) + (funext fun t => congrArg (hint i) (X.same_jump Y he i t))) + +end Data + +open scoped Classical in +/-- The render of type `(template A.scheme (m + L) h u).format.obj`, constructed using `(x i +k).1`. -/ +def render {u : ℕ} (g : B m → B d → B m) (x : (Replies A N r s).obj) : + (template A.scheme (m + L) h u).format.obj := + let lab i k := (x i k).1 + let z i j := (x i 0).2.2 j + (fun i => (fun j => follow g (Match.rowIndex m L i).1 (z i j), lab i), + fun i => (((x i 0).2.1, false), fun j => ((z i j).1, (z i j).1), lab i)) + +variable {A N r s} {u : ℕ} {a b : Wire} +open scoped Classical in +theorem Data.rendered (X : Data A N r s u a b) : render A N r s (D.nav X.raw.1) X.respond = X.frame + := by + have hr (i : B (m + L)) (j : B 3) : + follow (D.nav X.raw.1) (Match.rowIndex m L i).1 ((X.respond i 0).2.2 j) = X.directory.nav i j + ∧ + ((X.respond i 0).2.2 j).1 = X.directory.flags i j := by + obtain ⟨⟨v, l⟩, rfl⟩ := (Match.rowIndex m L).symm.surjective i + simp only [Data.respond, Equiv.apply_symm_apply] + change follow _ _ (hint l (X.jump (Data.combine v l) j)) = X.directory.nav (Data.combine v l) j + ∧ + (hint l (X.jump (Data.combine v l) j)).1 = X.directory.flags (Data.combine v l) j + rw [(X.navigate v l j).1, (X.navigate v l j).2] + rcases X.jump (Data.combine v l) j with _|⟨_|_, k⟩ <;> exact ⟨rfl, rfl⟩ + exact Prod.ext (funext fun v => Prod.ext (funext fun j => (hr v j).1) rfl) + (funext fun v => Prod.ext rfl (Prod.ext (funext fun j => Prod.ext (hr v j).2 (hr v j).2) rfl)) + +open scoped Classical in +theorem lookup_exists : + ∃ g : (Query A N r s).obj → (Reply A N r s).obj, + ∀ (X : Data A N r s u a b) v j, g (ask A N r s X.raw v j) = X.respond v j := by + let rel q z := ∃ X : Data A N r s u a b, ∃ v j, ask A N r s X.raw v j = q ∧ X.respond v j = z + let g q := if t : ∃ z, rel q z then t.choose else (Reply A N r s).serial.symm 0 + refine ⟨g, fun X v j => ?_⟩ + have e : ∃ z, rel (ask A N r s X.raw v j) z := ⟨_, X, v, j, rfl, rfl⟩ + obtain ⟨Y, w, k, hq, he⟩ := e.choose_spec + exact (dite_eq_left e).trans (he.symm.trans (Y.consistent X hq)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Gathering short labels for the restoration dictionary -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (N r s : ℕ) +local notation "W" => bits r s (Tether.width N r s) +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "h" => D.scheme.h + +/-- The quantity computed by `Format.vec (m + W) (.vec h (Query A N r s))`. -/ +abbrev Queries := Format.vec (m + W) (.vec h (Query A N r s)) +/-- Computes the ready queries by the application `Format.pair (Neighborhood.Rows m d) (Queries +A N r s)`. -/ +abbrev ReadyQueries := Format.pair (Neighborhood.Rows m d) (Queries A N r s) +/-- Computes the source by the application `Format.pair (.vec m .bit) (.pair (Raw m d) +A.scheme.format)`. -/ +abbrev Source := Format.pair (.vec m .bit) (.pair (Raw m d) A.scheme.format) +/-- Computes the gathered by the application `Format.pair (.vec m .bit) (.pair (.vec m (Preview +d)) (Fmt.groups m d h (Letters A)))`. -/ +abbrev Gathered := Format.pair (.vec m .bit) (.pair (.vec m (Preview d)) (Fmt.groups m d h (Letters + A))) + +/-- The value specified by `(D.live x.1, (D.nav x.1, D.flags x.1), A.rows x)`. -/ +def collect (x : A.format.obj) : (Source A).obj := + (D.live x.1, (D.nav x.1, D.flags x.1), A.rows x) + +/-- The value specified by `(D.live x.1, preview D x.1, Window.reads 2 (A.rows x))`. -/ +def gathered (x : A.format.obj) : (Gathered A).obj := + (D.live x.1, preview D x.1, Window.reads 2 (A.rows x)) + +/-- The indexed operation `(fun v => (x.2.2 v).1, fun v k => let w := Match.rowIndex m W v (k, +w.2, x.1 w.1, x.2.1 w.1, (x.2.2 w.1).2 k))`. -/ +def spread (x : (Gathered A).obj) : (ReadyQueries A N r s).obj := + (fun v => (x.2.2 v).1, fun v k => + let w := Match.rowIndex m W v + (k, w.2, x.1 w.1, x.2.1 w.1, (x.2.2 w.1).2 k)) + +theorem collect_net : Circuit F A.format (Source A) (collect A) (A.format.width + + 2 * (Source A).width) := by + let tap : (Source A).pins → A.format.pins + | .inl (v, i) => .inl (.inr (v, .inl (.inl i))) + | .inr (.inl (.inl (v, j))) => .inl (.inl (v, .inl j)) + | .inr (.inl (.inr (v, j))) => .inl (.inr (v, .inr (.inl j))) + | .inr (.inr (v, .inl j)) => .inl (.inl (v, .inl j)) + | .inr (.inr (v, .inr j)) => .inr (v, j) + exact Circuit.project tap (by rintro x (⟨v, i⟩|(⟨v, j⟩|⟨v, j⟩)|⟨v, j|j⟩) <;> rfl) + +theorem spread_net : Circuit F (Gathered A) (ReadyQueries A N r s) (spread A N r s) + ((Gathered A).width + 34 * (ReadyQueries A N r s).width) := by + apply Window.Tile.project_const + rintro (⟨v, i⟩|⟨v, k, i|i|i|i|i⟩) + · exact .inl ⟨.inr (.inr (v, .inl i)), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr h).code k i, fun _ => rfl⟩ + · exact .inr ⟨(Format.addr W).code (Match.rowIndex m W v).2 i, fun _ => rfl⟩ + · exact .inl ⟨.inl ((Match.rowIndex m W v).1, i), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inl ((Match.rowIndex m W v).1, i)), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inr ((Match.rowIndex m W v).1, .inr (k, i))), fun _ => rfl⟩ + +/-- The query cost used in the `Restore` construction. -/ +def queryCost (v z : ℕ) := + 4 * (A.format.width + 2 * (Source A).width)+ + (4 * (Format.vec m .bit).width + (4 * (2 ^ m * (100 + (m + 2 ^ radius d)) ^ 60) + + 3 * Window.readCost m d v z))+ + 4 * ((Gathered A).width + 34 * (ReadyQueries A N r s).width) + +variable {A N r s} {u w v z : ℕ} {a b : Wire} {P : Set (Table F)} + +theorem queries (hw : 3 ≤ w) (ht : Access F w P (m + d) v z) + (cap : 2 ^ h * (Letters A).width ≤ v) : + Computes F w P A.format (ReadyQueries A N r s) (fun X : Data A N r s u a b => X.raw) + (fun X => (D.nav X.raw.1, ask A N r s X.raw)) (fun _ => 1) (queryCost A N r s v z) := by + let I := Data A N r s u a b + let live := Format.vec m .bit + have start := Computes.of_map (L := P) (x := fun X : I => X.raw) + (Map.circuit hw (collect_net A)) (fun _ => rfl) + have keep := Computes.of_map (L := P) (x := fun X : I => D.live X.raw.1) + (Map.circuit hw (Circuit.id F live)) (fun _ => rfl) + obtain ⟨t, hg, hb⟩ := cheap_preview F («m» := m) («d» := d) le_rfl + have hc : Circuit F (Raw m d) (.vec m (Preview d)) inspect (2 ^ m * (100 + (m + + 2 ^ radius d)) ^ 60) := + hg.mono (by omega) + have scan := Computes.of_map (L := P) (x := fun X : I => (collect A X.raw).2.1) + (Map.circuit hw hc) (fun _ => rfl) + have move := Window.reads_net hw ht (fun X : I => A.rows X.raw) (fun X => X.q.core.reciprocal) cap + have stop := Computes.of_map (L := P) (x := fun X : I => gathered A X.raw) + (Map.circuit hw (spread_net A N r s)) (fun _ => rfl) + have done := (start.comp (keep.par (scan.par move))).comp stop + simp only [one_mul] at done + exact done + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Reconstructing long addresses from bounded selectors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing Finset + +variable {F : Type} [Field F] + +open scoped Classical in +theorem local_map {P Q : Format} {g : P.obj → Q.obj} {R : ℕ} + (hp : ∀ j : Q.pins, ∃ z : Finset P.pins, z.card ≤ R ∧ ∀ x y, + (∀ k ∈ z, P.code x k = P.code y k) → Q.code (g x) j = Q.code (g y) j) : + Circuit F P Q g (P.width + Install.localCost R * Q.width) := by + have h : Install.Depends (Q.code ∘ g ∘ P.code.symm) R := by + intro j + obtain ⟨z, hz, he⟩ := hp j + refine ⟨z, hz, fun x y h => he _ _ ?_⟩ + simpa only [Equiv.apply_symm_apply] using h + exact h.bnet F + +open scoped Classical in +private abbrev Before (m d h l ℓ : ℕ) := + Format.pair (Neighborhood.Rows m d) (.vec (m + l) (.vec h (Output ℓ d l))) + +open scoped Classical in +private abbrev After (m _d h l ℓ : ℕ) := + Format.pair (Fmt.rows (m + l) 3 h (.addr ℓ)) + (.vec (m + l) (.pair (.pair .bit .bit) (.pair (Group.Flags 3) (.vec h (.addr ℓ))))) + +open scoped Classical in +private def rr {m d h l ℓ : ℕ} (x : (Before m d h l ℓ).obj) : (After m d h l ℓ).obj := + let lab i k := (x.2 i k).1 + let z i j := (x.2 i 0).2.2 j + (fun i => (fun j => follow x.1 (Match.rowIndex m l i).1 (z i j), lab i), + fun i => (((x.2 i 0).2.1, false), fun j => ((z i j).1, (z i j).1), lab i)) + +open scoped Classical in +private theorem build (m d h L ℓ : ℕ) : + Circuit F (Before m d h L ℓ) (After m d h L ℓ) rr + ((Before m d h L ℓ).width + Install.localCost (2 ^ d + + (Hint d L).width) * (After m d h L ℓ).width) := by + let P := Before m d h L ℓ + let Q := After m d h L ℓ + let g : P.obj → Q.obj := rr + let R := 2 ^ d + (Hint d L).width + have hr : 1 ≤ R := (Nat.two_pow_pos d).trans_le (Nat.le_add_right _ _) + let ok (j : Q.pins) := ∃ z : Finset P.pins, z.card ≤ R ∧ ∀ x y, + (∀ k ∈ z, P.code x k = P.code y k) → Q.code (g x) j = Q.code (g y) j + have pick {j : Q.pins} (i : P.pins) (eq : ∀ x, Q.code (g x) j = P.code x i) : ok j := + ⟨{i}, by simpa using hr, fun x y he => (eq _).trans ((he i (by simp)).trans (eq _).symm)⟩ + apply local_map + change ∀ j, ok j + rintro (⟨v, ⟨j, b⟩|⟨k, b⟩⟩|⟨v, (b|b)|⟨j, b|b⟩|⟨k, b⟩⟩) + · obtain ⟨z, hz⟩ := Match.append_pin m L b + let v₀ := (Match.rowIndex m L v).1 + let tick (x : P.obj) := (x.2 v 0).2.2 j + let lift : (Hint d L).pins → P.pins := fun i => .inr (v, 0, .inr (.inr (j, i))) + have eq (x : P.obj) : Q.code (g x) (.inl (v, .inl (j, b))) = + z.elim ((Format.addr m).code (if (tick x).2.1 then x.1 v₀ (tick x).2.2.1 else v₀)) + ((Format.addr L).code (tick x).2.2.2) := by + change (Format.addr (m + L)).code (follow x.1 v₀ (tick x)) b = _ + unfold follow + rw [hz] + rcases z with k|k + · let src : B d → P.pins := fun i => .inl (v₀, i, k) + refine ⟨univ.image src ∪ univ.image lift, ?_, ?_⟩ + · exact (card_union_le _ _).trans (Nat.add_le_add (card_image_le.trans_eq (by simp)) + card_image_le) + · intro x y he + have ht : tick x = tick y := by + apply (Hint d L).code.injective + funext i + exact he _ (mem_union_right _ (mem_image_of_mem lift (mem_univ i))) + rw [eq, eq, ht] + simp only [Sum.elim_inl] + split + · exact he _ (mem_union_left _ (mem_image_of_mem src (mem_univ _))) + · rfl + · exact pick (lift (.inr (.inr (.inr k)))) (fun x => eq x) + · exact pick (.inr (v, k, .inl b)) (fun _ => rfl) + · exact pick (.inr (v, 0, .inr (.inl b))) (fun _ => rfl) + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + · exact pick (.inr (v, 0, .inr (.inr (j, .inl b)))) (fun _ => rfl) + · exact pick (.inr (v, 0, .inr (.inr (j, .inl b)))) (fun _ => rfl) + · exact pick (.inr (v, k, .inl b)) (fun _ => rfl) + +variable {D : Template F} (A : Attachment D) (N r s : ℕ) +local notation "L" => bits r s (Tether.width N r s) +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "h" => D.scheme.h + +open scoped Classical in +/-- Computes the raw reply by the application `Format.pair (Neighborhood.Rows m d) (Replies A N +r s)`. -/ +abbrev RawReply := Format.pair (Neighborhood.Rows m d) (Replies A N r s) +open scoped Classical in +/-- The quantity computed by `template A.scheme (m + L) h u`. -/ +abbrev result (u : ℕ) := template A.scheme (m + L) h u +open scoped Classical in +/-- The quantity computed by `2 ^ d + (Hint d (bits r s (Tether.width N r s))).width`. -/ +def readsBound (_ : Attachment D) (N r s : ℕ) := 2 ^ d + + (Hint d (bits r s (Tether.width N r s))).width + +open scoped Classical in +theorem render_circuit (u : ℕ) : + Circuit F (RawReply A N r s) (result A N r s u).format + (fun x => render A N r s x.1 x.2) + ((RawReply A N r s).width + Install.localCost (readsBound A N r s) * (result A N r s + u).format.width) := + build m d h L (script A.scheme).width + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Cost of writing a restored board from the attachment format -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (N r s : ℕ) +local notation "B'" => bits r s (Tether.width N r s) +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "h" => D.scheme.h + +open scoped Classical in +/-- The quantity computed by `(Query A N r s).width + (Reply A N r s).width`. -/ +def gateWidth := (Query A N r s).width + (Reply A N r s).width + +open scoped Classical in +/-- The cost used in the `Restore` construction. -/ +def cost (u v z : ℕ) := + queryCost A N r s v z + + (4 * (Neighborhood.Rows m d).width + 2 ^ (m + B') * (2 ^ h * (1 + (Query A N r s).width + + (Reply A N r s).width))) + + 4 * ((RawReply A N r s).width + Install.localCost (readsBound A N r s) * (result A N r s + u).format.width) + +variable {A N r s} {u : ℕ} {a b : Wire} + +open scoped Classical in +theorem control : + ∃ gate : Table F, ∀ {w v z : ℕ} {P : Set (Table F)}, 3 ≤ w → gate ∈ P → + gateWidth A N r s ≤ w → Access F w P (m + d) v z → 2 ^ h * (Letters A).width ≤ v → + Computes F w P A.format (result A N r s u).format + (fun X : Data A N r s u a b => X.raw) (fun X => X.frame) (fun _ => 1) (cost A N r s u v z) + := by + let I := Data A N r s u a b + obtain ⟨g, hg⟩ := lookup_exists (A := A) (N := N) (r := r) (s := s) (a := a) (b := b) (u := u) + let gate := lookup F (Query A N r s) (Reply A N r s) (fun x y => @ite F (g x + = y) (Classical.propDecidable _) 1 0) + refine ⟨gate, ?_⟩ + intro w v z P hw allowed wide ht cap + have one : Map F w P (Query A N r s) (Reply A N r s) g + (1 + (Query A N r s).width + (Reply A N r s).width) := Kernel.lookup wide allowed + have all := Map.vec _ (fun _ : B (m + B') => Map.vec _ (fun _ : B h => one)) + have keep := Map.circuit (L := P) hw (Circuit.id F (Neighborhood.Rows m d)) + have start := queries (a := a) (b := b) (u := u) (N := N) (r := r) (s := s) hw ht cap + have go := Computes.of_map (A := ReadyQueries A N r s) (B := RawReply A N r s) (x := fun X : I + => (D.nav X.raw.1, ask A N r s X.raw)) + (y := fun X : I => (D.nav X.raw.1, X.respond)) (keep.par all) + (fun X => Prod.ext rfl (funext fun i => funext fun j => hg X i j)) + have finish := Computes.of_map (A := RawReply A N r s) (B := (result A N r s u).format) (L + := P) (x := fun X : I => (D.nav X.raw.1, X.respond)) + (Map.circuit hw (render_circuit A N r s u)) (fun X => X.rendered) + have run := (start.comp go).comp finish + simp only [one_mul] at run + exact run + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- +# Locating each exposed span after restoration + +The suffix is determined by the old letter and the station index. +Every bit keeps its offset in the assigned span. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (N r s u : ℕ) +local notation "W" => Tether.width N r s + +open scoped Classical in +/-- The subtype of `i : B A.k` satisfying `A.live l i = true ∧ i ≠ 0`. -/ +abbrev Occupied (l : B A.ℓ) := {i : B A.k // A.live l i = true ∧ i ≠ 0} + +open scoped Classical in +/-- The destination of type `B (bits r s W)` for the given inputs. -/ +def destination (l : B A.ℓ) (i : B A.k) : B (bits r s W) := + if he : A.live l i = true ∧ i ≠ 0 then + if h : Fintype.card (Occupied A l) ≤ r then + suffix r s W (Tether.member ((), History.Reset.rank (Function.Embedding.subtype _) h ⟨i, he⟩)) + else 0 + else 0 + +open scoped Classical in +/-- The shift of type `(result A N r s u).scheme.Span` for the given inputs. -/ +def shift (raw : A.format.obj) (t : A.scheme.Span) : (result A N r s u).scheme.Span := + ((Data.combine t.1.1 (destination A N r s (raw.2 t.1.1 t.1.2.1) t.1.2.2), t.1.2.1, 0), + Chain.Frame.pair A.e (A.scheme.direction (A.rows raw) t, t.2)) + +namespace Data +variable {A N r s u} {a b : Wire} (X : Data A N r s u a b) + +open scoped Classical in +private def occupied (z : X.G.V × Cell D.scheme.h) : + Attachment.Encloses.Members z ≃ Occupied A (X.letter z.1 z.2) := by + let f (t : Attachment.Encloses.Members z) : Occupied A (X.letter z.1 z.2) := + ⟨X.q.slot t.val, (X.exists_iff ..).mp ⟨.inr t.val, t.property, rfl⟩, X.q.positive t.val⟩ + refine Equiv.ofBijective f ⟨fun i j he => (X.q.memberKey z).injective (congrArg Subtype.val he), + ?_⟩ + rintro ⟨j, hj, h0⟩ + obtain ⟨w, hw, he⟩ := (X.exists_iff ..).mpr hj + rcases w with w|t + · exact (h0 he.symm).elim + · exact ⟨⟨t, hw⟩, Subtype.ext he⟩ + +open scoped Classical in +theorem destination_eq (t : X.T) : + destination A N r s (X.tag (.inr t)).1 (X.tag (.inr t)).2 = + suffix r s W (Tether.member ((), X.e.slot t)) := by + let z := X.G.park t + let l := X.letter z.1 z.2 + let v := X.occupied z + have hv : ∀ i, (v i).val = X.q.memberKey z i := fun _ => rfl + have hc : Fintype.card (Occupied A l) ≤ r := by + rw [← Fintype.card_congr v] + refine LE.le.trans ?_ (Fintype.card_fin r).le + apply Fintype.card_le_of_injective (fun i => X.e.slot i.val) + exact fun i j h => Subtype.ext (X.e.unique (Prod.ext (i.property.trans j.property.symm) h)) + have hi : A.live l (X.q.slot t) = true ∧ X.q.slot t ≠ 0 := (v ⟨t, rfl⟩).property + unfold tag + rw [X.token] + change destination A N r s l (X.q.slot t) = _ + rw [destination, dite_eq_left hi, dite_eq_left hc] + apply congrArg (fun i => suffix r s W (Tether.member ((), i))) + change _ = X.q.number X.allocation t + rw [X.q.number_at X.allocation t z rfl] + exact History.Reset.rank_eq (fun i => ⟨v.symm i, + (congrArg Subtype.val (v.apply_symm_apply i)).symm.trans (hv _)⟩) + (fun i => ⟨v i, (hv i).symm⟩) rfl + +open scoped Classical in +theorem boundary_shift (i : slots a ⊕ slots b) : + let x := (X.p.boundary i).val + let y := (X.pres.pres.boundary i).val + y.1 = shift A N r s u X.raw x.1 ∧ y.2.val = x.2.val ∧ + (result A N r s u).scheme.width X.frame.1 y.1 = A.scheme.width (A.rows X.raw) x.1 := by + let g := written X.q X.e X.loopless X.directory + let t := boundaryEnd X.route.graph i + let j := boundaryEnd X.old i + have hx : (X.p.boundary i).val = X.p.toSeating.ends j := by cases i <;> rfl + have hy : (X.pres.pres.boundary i).val = g.seating.ends t := by cases i <;> rfl + have he : X.f.old X.p t = X.p.toSeating.ends j := X.f.old_boundary X.p i + have ord : (g.seating.ends t).2.val = (X.p.toSeating.ends j).2.val := + (g.ends _).2.trans (congrArg (fun q => q.2.val) he) + have sz : (result A N r s u).scheme.width X.frame.1 (g.seating.ends t).1 = + A.scheme.width (A.rows X.raw) (X.p.toSeating.ends j).1 := by rw [(g.ends _).1, g.size, he] + rw [hx, hy] + refine ⟨(g.ends _).1.trans ?_, ord, sz⟩ + have eqt : t = X.route.original j := by cases i <;> rfl + obtain ⟨u', hu⟩ : ∃ u' : X.T, X.old.station j = .inr u' := by + cases i <;> exact ⟨_, rfl⟩ + have site := (X.span_at j).trans (congrArg (fun v => (X.p.vertex v, X.port j)) hu) + have dir := X.q.directed j + unfold Written.span shift + change (g.vertex (X.route.graph.station t), X.f.lane X.p t) = _ + rw [Chain.Frame.lane, he, eqt, X.route.station_original, X.route.side_original, dir, site, hu] + change ((X.hostOut (Tether.member ((X.G.park u').1, X.e.slot u')), cellIndex _ (X.G.park u').2, + 0), _) = + ((combine (X.p.vertex (.inr u')).1 (destination A N r s (X.tag (.inr u')).1 (X.tag (.inr + u')).2), + (X.p.vertex (.inr u')).2.1, 0), _) + rw [X.destination_eq, X.vertex] + exact congrArg (fun y => ((y, cellIndex _ (X.G.park u').2, (0 : B 0)), _)) + (X.child_address (X.G.park u').1 (Tether.member ((), X.e.slot u'))) + +end Data +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Rate.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Rate.lean new file mode 100644 index 0000000000..6385394236 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Rate.lean @@ -0,0 +1,1018 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Exterior +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanSupplies +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanTiles +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Shipment.Bound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact + +/-! # Restarting a controlled round with bounded degree and load -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing Finset Rounds + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {a b : Wire} + {N r s u : ℕ} (X : Data A N r s u a b) + +open scoped Classical in +/-- The data for the feasible construction, including `allocation`, `core`, `loopless`. -/ +structure Feasible (Y : A.Data a b u) (N r s : ℕ) : Prop where + allocation : Nonempty (Y.G.Restore N r s) + core : ∀ v, (Y.G.C v).card ≤ 3 + loopless : ∀ i, Y.G.src i ≠ Y.G.dst i + +open scoped Classical in +/-- Uses `⟨Y.T, Y.a, Y.b, Y.L, Y.G, Y.Z, Y.raw, Y.q, Classical.choice ok.allocation, ok.core, +ok.loopless⟩` as the representation. -/ +abbrev Feasible.data {Y : A.Data a b u} (ok : Feasible Y N r s) : Data A N r s u a b := + ⟨Y.T, Y.a, Y.b, Y.L, Y.G, Y.Z, Y.raw, Y.q, Classical.choice ok.allocation, ok.core, ok.loopless⟩ + +open scoped Classical in +/-- Uses `Restore.board X.q X.e` as the representation. -/ +abbrev Data.board := Restore.board X.q X.e + +namespace Data + +open scoped Classical in +theorem charge_le (hB : ∀ t, (X.old.arity (.inr t) : ℝ) ≤ X.L.charge t) + (hc : ∀ i, (u : ℝ) ≤ X.G.parallelBits i) (hf : ∀ i, (u : ℝ) ≤ X.L.charge i) (z : X.Space) : + X.board.charge z ≤ X.e.charge z := + amount_le _ _ ((X.e.board X.border X.q.tether hB).cover z) (X.e.floor _ le_rfl hc hf z) + +open scoped Classical in +theorem ready {p : Rounds.Plan} (X : Data A p.full p.slots p.slots u a b) + (hp : p.Fits) {T : ℕ} {L : ℝ} (hL : 0 ≤ L) (ht : T ≤ u * p.M) + (hB : ∀ t, (X.old.arity (.inr t) : ℝ) ≤ X.L.charge t) + (hc : ∀ i, (u : ℝ) ≤ X.G.parallelBits i) (hf : ∀ i, (u : ℝ) ≤ X.L.charge i) + (bound : X.G.Bounded 3 p.full T) + (hw : (X.G.X : ℝ) ≤ (p.ρ * p.A * (1 + (p.d : ℝ)) ^ 2 + p.loss * ((p.A + + 1) / Real.sqrt p.D)) * L) + (hZ : X.L.Z ≤ p.A / Real.sqrt p.D * L) + (hsq : (∑ i, X.L.charge i ^ 2) ≤ (p.A : ℝ) * L * T) + (hmax : ∀ i, X.L.charge i ≤ (p.A : ℝ) * p.D * T) : + X.board.Ready 5 p.D (2 ^ p.p * T) (L / (2 : ℝ) ^ p.v) p.floor := by + obtain ⟨mass, sq, mx⟩ := Rounds.Plan.restored hp X.e hL bound hw hZ hsq hmax + have he := X.charge_le hB hc hf + refine ⟨fun v => (Tether.adj_degree _ _ X.core v).trans (by decide : 4 ≤ 5), ?_, ?_, ?_⟩ + · exact (sum_le_sum fun z _ => he z).trans mass + · refine le_trans ?_ sq + exact sum_le_sum fun z _ => pow_le_pow_left₀ ((Nat.cast_nonneg _).trans (X.board.cover z)) (he + z) 2 + · intro z + refine ⟨(he z).trans (mx z), ?_⟩ + change amount u _ = 0 ∨ _ ≤ amount u _ + unfold amount + split + · exact .inl rfl + · exact .inr ((p.floor_le T u ht).trans (le_max_right _ _)) + +end Data + +variable {I : Type 1} (xs : I → Data A N r s u a b) (t : ℕ) + (cap : ∀ i v, (xs i).board.diagram.arity v ≤ 2 ^ t) +local notation "P" => result A N r s u + +open scoped Classical in +/-- Builds `Layer F a b where template` with the specified `template`, `volume`, `height`, +`State`. -/ +abbrev rawLayer : Layer F a b where + template := P + volume := 2 ^ (P).scheme.m + wd a + wd b + height := D.scheme.h + t + State := I + board i := (xs i).board + data i := (xs i).frame + presents i := (xs i).pres + fits i := (xs i).pres.fits (cap i) + +open scoped Classical in +/-- The indexed operation `{ Z with template := Z.template.sweep board := fun i => (Z.board +i).sweep presents := fun i => (Z.presents i).sweep }`. -/ +abbrev swept (Z : Layer F a b) : Layer F a b := + { Z with + template := Z.template.sweep + board := fun i => (Z.board i).sweep + presents := fun i => (Z.presents i).sweep } + +open scoped Classical in +/-- Computes the layer by the application `swept (rawLayer xs t cap)`. -/ +abbrev layer := swept (rawLayer xs t cap) + +open scoped Classical in +theorem ready {g T : ℕ} {L θ : ℝ} (hr : ∀ i, (xs i).board.Ready 5 g T L θ) : + (layer xs t cap).Ready g T L θ ∧ (layer xs t cap).Loopless := by + refine ⟨⟨rfl, ?_, hr⟩, ?_⟩ + · intro i v hv z + exact (xs i).board.diagram.sweep_neutral v hv z + · intro i e + exact (xs i).e.route_loopless (xs i).border (xs i).q.tether (xs i).loopless e + +open scoped Classical in +private theorem sweep_stage (Z : Layer F a b) {w : ℕ} {K : Set (Table F)} (hw : 3 ≤ w) + (hfit : 2 * Z.template.scheme.ℓ ≤ w) (ok : Z.encoding.sweepTable ∈ K) : + Transforms F w K Z.snapshot (swept Z).snapshot Z.encoding.sweepCost := + Z.encoding.sweep_stage hw hfit ok + +open scoped Classical in +theorem withdraw {w : ℕ} {K : Set (Table F)} (hw : 3 ≤ w) (hfit : 2 * (script A.scheme).width ≤ w) + (ok : (rawLayer xs t cap).encoding.sweepTable ∈ K) : + Transforms F w K (rawLayer xs t cap).snapshot (layer xs t cap).snapshot + (rawLayer xs t cap).encoding.sweepCost := + sweep_stage (rawLayer xs t cap) hw hfit ok + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Commands for the exterior spans of a restored board -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (N r s : ℕ) +local notation "S" => A.scheme +local notation "z" => bits r s (Tether.width N r s) + +open scoped Classical in +/-- The quantity computed by `A.k + (1 + A.e)`. -/ +abbrev lineBits := A.k + (1 + A.e) +open scoped Classical in +/-- Indexes the line by the coordinates of `B A.k × B A.e`. -/ +abbrev Line := B A.k × B A.e + +open scoped Classical in +/-- Embeds `B a × B b` into `B l`. -/ +def code {a b l : ℕ} (h : a + b ≤ l) : B a × B b ↪ B l := + (Match.rowIndex a b).symm.toEmbedding.trans (Fin.castLEEmb (Nat.pow_le_pow_right (by decide) h)) + +open scoped Classical in +/-- Embeds `Line A` into `B (lineBits A)`. -/ +def fromLine : Line A ↪ B (lineBits A) := code (by unfold lineBits; omega) + +open scoped Classical in +/-- The to line of type `B z × B (lineBits A)` for the given inputs. -/ +def toLine (x : B A.ℓ) (i : Line A) : B z × B (lineBits A) := + (destination A N r s x i.1, code (a := 0) (b := 1 + A.e) (by unfold lineBits; omega) + (0, Chain.Frame.pair A.e ((A.decode x).direction i.1 i.2, i.2))) + +open scoped Classical in +/-- Returns `(A.decode x).width i.1 i.2` when `(A.decode x).peer i.1 i.2 = none` holds, and `0` +otherwise. -/ +def lineSize (x : B A.ℓ) (i : Line A) := + if (A.decode x).peer i.1 i.2 = none then (A.decode x).width i.1 i.2 else 0 + +open scoped Classical in +/-- The value specified by `(t.1.2.2, t.2)`. -/ +def line (t : (S).Span) : Line A := (t.1.2.2, t.2) + +open scoped Classical in +/-- Computes the text by the application `raw.2 t.1.1 t.1.2.1`. -/ +def text (raw : A.format.obj) (t : (S).Span) : B A.ℓ := raw.2 t.1.1 t.1.2.1 + +omit [Field F] in +open scoped Classical in +theorem size_eq (raw : A.format.obj) (t : (S).Span) : + lineSize A (text A raw t) (line A t) = (S).borderLen (A.rows raw) t := by + unfold Scheme.borderLen Scheme.peer + simp only [Option.map_eq_none_iff] + rfl + +open scoped Classical in +/-- The quantity computed by `(S).row (l := lineBits A) (show A.k + A.e ≤ A.k + (1 + A.e) by +omega)`. -/ +abbrev oldRow := (S).row (l := lineBits A) (show A.k + A.e ≤ A.k + (1 + A.e) by omega) + +open scoped Classical in +/-- The value specified by `(result A N r s u).scheme.row (l := lineBits A) (show 0 + (1 + A.e) +≤ A.k + (1 + A.e) by omega) ∘ shift A N r s u raw`. -/ +def newRow (u : ℕ) (raw : A.format.obj) := + (result A N r s u).scheme.row (l := lineBits A) (show 0 + (1 + A.e) ≤ A.k + (1 + A.e) by omega) ∘ + shift A N r s u raw + +open scoped Classical in +theorem unpack (u : ℕ) (raw : A.format.obj) (t : (S).Span) : + let tag := toLine A N r s (text A raw t) (line A t) + Match.rowIndex D.scheme.m z (shift A N r s u raw t).1.1 = (t.1.1, tag.1) ∧ + Match.rowIndex D.scheme.h (lineBits A) (oldRow A t) = (t.1.2.1, fromLine A (line A t)) ∧ + Match.rowIndex D.scheme.h (lineBits A) (newRow A N r s u raw t) = (t.1.2.1, tag.2) := + ⟨(Match.rowIndex _ _).apply_symm_apply _, (Match.rowIndex _ _).apply_symm_apply _, + (Match.rowIndex _ _).apply_symm_apply _⟩ + +open scoped Classical in +/-- The value specified by `(if t then 0 else (toLine A N r s x i).1, Fin.ofNat _ (lineSize A x +i), (Match.rowIndex _ _).symm (k, fromLine A i))`. -/ +def header (w : ℕ) (x : B A.ℓ) (k : B D.scheme.h) (t : Bool) (i : Line A) : + (SpanPlan.header w z (D.scheme.h + lineBits A)).obj := + (if t then 0 else (toLine A N r s x i).1, Fin.ofNat _ (lineSize A x i), + (Match.rowIndex _ _).symm (k, fromLine A i)) + +open scoped Classical in +/-- The program of type `SpanProgram (S) z w (lineBits A)` for the given inputs. -/ +def program (w : ℕ) : SpanProgram (S) z w (lineBits A) := fun x k => + (fun q => if h : ∃ i, 0 < lineSize A x i ∧ fromLine A i + = q then header A N r s w x k false h.choose + else (0, 0, 0), + fun p q => if h : ∃ i, 0 < lineSize A x i ∧ toLine A N r s x i = (p, + q) then header A N r s w x k true h.choose + else (0, 0, 0)) + +namespace Data +variable {A N r s} {a b : Wire} {u : ℕ} (X : Data A N r s u a b) +local notation "U" => Template.scheme (result A N r s u) +local notation "R" => A.rows X.raw + +open scoped Classical in +theorem shift_inj {t t' : (S).Span} (ht : 0 < (S).borderLen R t) (ht' : 0 < (S).borderLen R t') + (eq : shift A N r s u X.raw t = shift A N r s u X.raw t') : t = t' := by + have zero (t : (S).Span) (ht : 0 < (S).borderLen R t) : + ∃ j, (X.p.boundary j).val.1 = t ∧ (X.p.boundary j).val.2.val = 0 := by + unfold Scheme.borderLen at ht + split at ht + · rename_i ha + obtain ⟨j, hj⟩ := X.p.boundary.surjective ⟨⟨t, ⟨0, ht⟩⟩, ha⟩ + exact ⟨j, by rw [hj], by rw [hj]⟩ + · contradiction + obtain ⟨i, rfl, hi⟩ := zero t ht + obtain ⟨j, rfl, hj⟩ := zero t' ht' + have ha := X.boundary_shift i + have hb := X.boundary_shift j + have es := ha.1.trans (eq.trans hb.1.symm) + have en := ha.2.1.trans (hi.trans (hj.symm.trans hb.2.1.symm)) + have hw := (Fin.heq_ext_iff (congrArg ((U).width X.frame.1) es)).mpr en + rw [X.pres.pres.boundary.injective (Subtype.ext (Sigma.ext es hw))] + +open scoped Classical in +theorem target_inj (v : B D.scheme.m) (k : B D.scheme.h) {i j : Line A} + (hi : 0 < lineSize A (X.raw.2 v k) i) (hj : 0 < lineSize A (X.raw.2 v k) j) + (he : toLine A N r s (X.raw.2 v k) i = toLine A N r s (X.raw.2 v k) j) : i = j := by + let t (x : Line A) : (S).Span := ((v, k, x.1), x.2) + have pos (x : Line A) (h : 0 < lineSize A (X.raw.2 v k) x) : 0 < (S).borderLen R (t x) := + h.trans_eq (size_eq A X.raw (t x)) + obtain ⟨ha, hb⟩ := Prod.mk.inj he + have eq : shift A N r s u X.raw (t i) = shift A N r s u X.raw (t j) := by + have hp := (code (show 0 + (1 + A.e) ≤ lineBits A by unfold lineBits; omega)).injective hb + have hk := congrArg Prod.snd hp + exact Prod.ext (Prod.ext (congrArg (combine v) ha) rfl) hk + exact congrArg (line A) (X.shift_inj (pos i hi) (pos j hj) eq) + +end Data +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Reading the source and destination headers at every active span -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X : Data A N r s u a b) (w : ℕ) +local notation "z" => bits r s (Tether.width N r s) +local notation "S" => A.scheme +local notation "R" => A.rows X.raw +local notation "n" => lineBits A +local notation "g" => program A N r s w +local notation "f" => shift A N r s u X.raw + +open scoped Classical in +theorem outbound (t : (S).Span) (ht : 0 < (S).borderLen R t) : + (g).send R t.1.1 (oldRow A t) = header A N r s w (text A X.raw t) t.1.2.1 false (line A t) := by + have h := (unpack A N r s u X.raw t).2.1 + let q := Match.rowIndex D.scheme.h n (oldRow A t) + change (g (X.raw.2 t.1.1 q.1) q.1).1 q.2 = _ + unfold q + rw [h] + let l := text A X.raw t + let i := line A t + have he : ∃ j, 0 < lineSize A l j ∧ fromLine A j = fromLine A i := + ⟨i, by rwa [size_eq], rfl⟩ + have eq : he.choose = i := (fromLine A).injective he.choose_spec.2 + exact (dite_eq_left he).trans (congrArg (header A N r s w l t.1.2.1 false) eq) + +open scoped Classical in +theorem inbound (t : (S).Span) (ht : 0 < (S).borderLen R t) : + (g).take R (f t).1.1 (newRow A N r s u X.raw t) = + header A N r s w (text A X.raw t) t.1.2.1 true (line A t) := by + obtain ⟨hp, _, hq⟩ := unpack A N r s u X.raw t + let p := Match.rowIndex D.scheme.m z (f t).1.1 + let q := Match.rowIndex D.scheme.h n (newRow A N r s u X.raw t) + change (g (X.raw.2 p.1 q.1) q.1).2 p.2 q.2 = _ + unfold p q + rw [hp, hq] + let l := text A X.raw t + let i := line A t + have pos : 0 < lineSize A l i := ht.trans_eq (size_eq A X.raw t).symm + have he : ∃ j, 0 < lineSize A l j ∧ toLine A N r s l j = toLine A N r s l i := ⟨i, pos, rfl⟩ + have eq : he.choose = i := X.target_inj t.1.1 t.1.2.1 he.choose_spec.1 pos he.choose_spec.2 + exact (dite_eq_left he).trans (congrArg (header A N r s w l t.1.2.1 true) eq) + +open scoped Classical in +theorem out_used (v : B D.scheme.m) (i : B (D.scheme.h + n)) (h : 0 < ((g).send R v i).2.1.val) : + ∃ t, 0 < (S).borderLen R t ∧ t.1.1 = v ∧ oldRow A t = i := by + let q := Match.rowIndex D.scheme.h n i + let l := X.raw.2 v q.1 + have hp : ∃ j, 0 < lineSize A l j ∧ fromLine A j = q.2 := by + by_contra he + have hz : (g).send R v i = (0, 0, 0) := dite_eq_right he + rw [hz] at h + exact Nat.lt_irrefl 0 h + obtain ⟨j, hj, he⟩ := hp + let t : (S).Span := ((v, q.1, j.1), j.2) + refine ⟨t, hj.trans_eq (size_eq A X.raw t), rfl, (Match.rowIndex _ _).injective ?_⟩ + exact ((unpack A N r s u X.raw t).2.1).trans (Prod.ext rfl he) + +open scoped Classical in +theorem in_used (v : B (D.scheme.m + z)) (i : B (D.scheme.h + n)) (h : 0 + < ((g).take R v i).2.1.val) : + ∃ t, 0 < (S).borderLen R t ∧ (f t).1.1 = v ∧ newRow A N r s u X.raw t = i := by + let p := Match.rowIndex D.scheme.m z v + let q := Match.rowIndex D.scheme.h n i + let l := X.raw.2 p.1 q.1 + have hp : ∃ j, 0 < lineSize A l j ∧ toLine A N r s l j = (p.2, q.2) := by + by_contra he + have hz : (g).take R v i = (0, 0, 0) := dite_eq_right he + rw [hz] at h + exact Nat.lt_irrefl 0 h + obtain ⟨j, hj, he⟩ := hp + let t : (S).Span := ((p.1, q.1, j.1), j.2) + obtain ⟨ha, _, hb⟩ := unpack A N r s u X.raw t + obtain ⟨ha', hb'⟩ := Prod.mk.inj he + exact ⟨t, hj.trans_eq (size_eq A X.raw t), + (Match.rowIndex _ _).injective (ha.trans (Prod.ext rfl ha')), + (Match.rowIndex _ _).injective (hb.trans (Prod.ext rfl hb'))⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # The emitted contact rows realize the named exterior bijection -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +open Packing Coloring + +variable {F : Type} [Field F] {D : Template F} {A : Attachment D} {N r s u : ℕ} + {a b : Wire} (X : Data A N r s u a b) +local notation "z" => bits r s (Tether.width N r s) +local notation "S" => A.scheme +local notation "U" => Template.scheme (result A N r s u) +local notation "R" => A.rows X.raw + +open scoped Classical in +theorem certifies {V k w : ℕ} (fit : (S).Fits R V k) (hw : k < w) : + SpanPlan.Spec X.p X.pres.pres (Match.rowIndex D.scheme.m z) (shift A N r s u X.raw) + (fun _ => 0) (oldRow A) (newRow A N r s u X.raw) + ((program A N r s w).send R) ((program A N r s w).take R) := by + have width (t : (S).Span) (b : Bool) : + (header A N r s w (text A X.raw t) t.1.2.1 b (line A t)).2.1.val = (S).borderLen R t := by + change lineSize A (text A X.raw t) (line A t) % 2 ^ w = _ + rw [size_eq, Nat.mod_eq_of_lt] + exact ((S).border_le _ _).trans_lt ((fit.2 _).trans_lt (Nat.pow_lt_pow_right (by decide) hw)) + refine ⟨?_, ?_, ?_, ?_, ?_, ?_, X.out_used _, X.in_used _⟩ + · intro t _ + exact congrArg Prod.fst (unpack A N r s u X.raw t).1 + · intro i + obtain ⟨ht, hi, _⟩ := X.boundary_shift i + exact ⟨ht, hi.trans (zero_add _).symm⟩ + · intro t t' _ _ _ he + exact ((S).row_less _ _ _).mpr he + · intro t t' _ _ _ he + left + exact ((U).row_less (show 0 + (1 + A.e) ≤ A.k + (1 + A.e) by omega) _ _).mp he + · intro t ht + rw [X.outbound _ _ ht] + exact ⟨(congrArg Prod.snd (unpack A N r s u X.raw t).1).symm, width _ false, rfl⟩ + · intro t ht + rw [X.inbound _ _ ht] + exact ⟨rfl, width _ true, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Data +end + +/- # Joint computation of restored records and exterior commands -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (N r s w : ℕ) +local notation "p" => bits r s (Tether.width N r s) +local notation "m" => D.scheme.m +local notation "h" => D.scheme.h + +open scoped Classical in +/-- The quantity computed by `Payload.Script m (m + p) p w (h + lineBits A)`. -/ +abbrev Commands := Payload.Script m (m + p) p w (h + lineBits A) + +open scoped Classical in +/-- The value specified by `(program A N r s w).commands (A.rows raw)`. -/ +def commands (raw : A.format.obj) : (Commands A N r s w).obj := + (program A N r s w).commands (A.rows raw) + +open scoped Classical in +/-- Computes the command size by the application `SpanProgram.size A.scheme p w (lineBits A)`. -/ +def commandSize := SpanProgram.size A.scheme p w (lineBits A) + +open scoped Classical in +/-- The bound obtained by adding the component charges `20 * A.format.width + (cost A N r s u v +c + (4 * (A.format.width + 2 * A.scheme.format.width) + SpanProgram.cost A.scheme p w +(lineBits A)))`. -/ +def commandCost (u v c : ℕ) := + 20 * A.format.width + (cost A N r s u v c + + (4 * (A.format.width + 2 * A.scheme.format.width) + SpanProgram.cost A.scheme p w (lineBits A))) + +open scoped Classical in +private theorem rows_net : + Circuit F A.format A.scheme.format A.rows (A.format.width + 2 * A.scheme.format.width) := by + let tap : A.scheme.format.pins → A.format.pins + | (i, .inl j) => .inl (.inl (i, .inl j)) + | (i, .inr j) => .inr (i, j) + exact Circuit.project tap (by rintro _ ⟨i, j|j⟩ <;> rfl) + +variable {A N r s w} {u : ℕ} {a b : Wire} + +open scoped Classical in +theorem joint : + ∃ gate : Table F, ∀ {t v c : ℕ} {L : Set (Table F)}, 3 ≤ t → gate ∈ L → + (program A N r s w).gate ∈ L → gateWidth A N r s ≤ t → commandSize A N r s w ≤ t → + Access F t L (m + D.scheme.d) v c → 2 ^ h * (Letters A).width ≤ v → + Computes F t L A.format ((result A N r s u).format.pair (Commands A N r s w)) + (fun X : Data A N r s u a b => X.raw) (fun X => (X.frame, commands A N r s w X.raw)) + (fun _ => 1) (commandCost A N r s w u v c) := by + obtain ⟨gate, hg⟩ := control (A := A) (N := N) (r := r) (s := s) (a := a) (b := b) (u := u) + refine ⟨gate, ?_⟩ + intro t v c L ht ha hb hf hk hw hr + have step := hg ht ha hf hw hr + have part := (Map.circuit (L := L) ht (rows_net A)).comp + ((program A N r s w).action ht hk hb) + have cmd := Computes.of_map (x := fun X : Data A N r s u a b => X.raw) + (y := fun X => commands A N r s w X.raw) part (fun _ => rfl) + have k := Computes.pair ht step cmd + simp only [one_mul] at k + exact k + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # The separate costs of long host addresses and short block records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (N r s : ℕ) +local notation "l" => bits r s (Tether.width N r s) +local notation "m" => D.scheme.m +local notation "h" => D.scheme.h +local notation "d" => D.scheme.d +local notation "L" => (script A.scheme) +local notation "a" => A.ℓ + +/-- The quantity computed by `2 ^ radius j * (2 ^ radius j + 2 ^ j * 2)`. -/ +def maskWidth (j : ℕ) := 2 ^ radius j * (2 ^ radius j + 2 ^ j * 2) + +theorem mask_eq (j : ℕ) : (Preview j).width = maskWidth j := by + simp only [Preview, Equalities, Group.Flags, Format.width_pair, Format.width_vec] + rw [Format.width_bit, maskWidth]; ring + +theorem hint_eq (i j : ℕ) : (Hint i j).width = 2 + i + j := by + simp only [Hint, Format.width_pair, Format.width_addr] + rw [Format.width_bit]; omega + +omit [Field F] in +theorem letters_eq : (Letters A).width = 2 ^ radius d * a := by + rw [Letters, Window.Walks, Format.width_vec, Format.width_addr] + +omit [Field F] in +theorem query_eq : (Query A N r s).width = h + l + 1 + maskWidth d + 2 ^ radius d * a := by + rw [Query, Question, Format.width_pair, Format.width_pair, Format.width_pair, Format.width_pair, + Format.width_addr, Format.width_addr, Format.width_bit, mask_eq, letters_eq] + omega + +omit [Field F] in +theorem reply_eq : (Reply A N r s).width = (L).width + 1 + 8 * (2 + d + l) := by + rw [Reply, Output, Format.width_pair, Format.width_pair Format.bit (.vec 3 _), + Format.width_addr, Format.width_bit, Format.width_vec, hint_eq] + omega + +omit [Field F] in +private theorem source_eq : + (Source A).width = 2 ^ m * (1 + 2 ^ d * (2 * m + 2) + 2 ^ h * a) := by + simp only [Source, Raw, Neighborhood.Rows, Group.Flags, Scheme.format, Format.width_pair, + Format.width_vec, Format.width_addr] + rw [Format.width_bit]; ring + +omit [Field F] in +private theorem gathered_eq : + (Gathered A).width = 2 ^ m * (1 + maskWidth d + 2 ^ d * m + 2 ^ h * (Letters A).width) := by + unfold Gathered + rw [Format.width_pair, Format.width_pair, Format.width_vec, Format.width_bit, Format.width_vec, + mask_eq, + Fmt.width_rows] + ring + +omit [Field F] in +private theorem prepare_eq : + (ReadyQueries A N r s).width = 2 ^ m * (2 ^ d * m) + 2 ^ (m + + l) * 2 ^ h * (Query A N r s).width := by + rw [ReadyQueries, Queries, Neighborhood.Rows, Format.width_pair, Format.width_vec, + Format.width_vec, + Format.width_addr, Format.width_vec, Format.width_vec, mul_assoc] + +omit [Field F] in +private theorem answer_eq : + (RawReply A N r s).width = 2 ^ m * (2 ^ d * m) + 2 ^ (m + l) * 2 ^ h * (Reply A N r s).width + := by + rw [RawReply, Replies, Neighborhood.Rows, Format.width_pair, Format.width_vec, Format.width_vec, + Format.width_addr, Format.width_vec, Format.width_vec, mul_assoc] + +/-- The host work used in the `Restore` construction. -/ +def hostWork (M₀ D₀ z : ℕ) := + 28 * (2 ^ D₀ * (M₀ + 2) + 2) + 8 * (1 + 2 ^ D₀ * (2 * M₀ + 2)) + 4 + 4 * (100 + (M₀ + + 2 ^ radius D₀)) ^ 60 + + 4 * (1 + maskWidth D₀ + 39 * (2 ^ D₀ * M₀)) + 4 * Install.localCost (2 ^ D₀ + (2 + D₀ + + z)) * 2 ^ z * (8 * (M₀ + z + 2) + 2) + +/-- The block work used in the `Restore` construction. -/ +def blockWork := + 28 * (D.scheme.ℓ + D.count + a) + 16 * a + 4 * (Letters A).width + + 2 ^ l * (1 + 137 * (Query A N r s).width + 5 * (Reply A N r s).width + + 8 * Install.localCost (2 ^ d + (2 + d + l)) * (L).width) + +theorem command_price (u w v c : ℕ) : + commandCost A N r s w u v c = 2 ^ m * hostWork m d l + 2 ^ (m + h) * blockWork A N r s + + 3 * Window.readCost m d v c + SpanProgram.cost A.scheme l w (lineBits A) := by + have hu := (result A N r s u).width + change _ = 2 ^ (m + l) * (8 * (m + l + 2) + 2 + 2 ^ h * ((L).width + (L).width)) at hu + have hm : (Neighborhood.Rows m d).width = 2 ^ m * (2 ^ d * m) := by + rw [Neighborhood.Rows, Format.width_vec, Format.width_vec, Format.width_addr] + have hs : A.scheme.format.width = 2 ^ m * (2 ^ d * m + 2 ^ h * a) := by + rw [Scheme.format, Fmt.width_rows, Format.width_addr] + unfold commandCost cost queryCost hostWork blockWork + rw [source_eq, gathered_eq, prepare_eq, answer_eq, A.width, D.width, hu, hm, hs, readsBound, + hint_eq, + Format.width_vec, Format.width_bit] + generalize (100 + (m + 2 ^ radius d)) ^ 60 = M + simp only [pow_add] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- +# The three parts of the restoration cost + +Charge the long addresses per host, the label arithmetic per +occurrence, and the actual boundary transfer per exterior bit. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing Rounds.Contraction + +/-- The host rate used in the `Restore` construction. -/ +def hostRate (m d l W v : ℕ) := + hostWork m d l + 3 * (4000 * (1 + W) * 2 ^ d * (1 + v) + + 4 * 2 ^ d * (100 + (m + d + 3 * m + 1)) ^ 200 + 1100 * 2 ^ d * (m + d + 1) + 1000 * 2 ^ d * m) + + 4 * 2 ^ d * m + 136 * 2 ^ l * (m + l + l) + 4 * 2 ^ l * (8 * (m + l + 2) + 2) + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (N r s : ℕ) +local notation "l" => bits r s (Tether.width N r s) +local notation "m" => D.scheme.m +local notation "h" => D.scheme.h +local notation "d" => D.scheme.d +local notation "n" => lineBits A + +/-- The construction uses `2 ^ h * (Letters A).width` for its intermediate `v`. -/ +def stageCost (u w : ℕ) (a b : Wire) (k t : ℕ) (W : Prices F) := + let v := 2 ^ h * (Letters A).width + commandCost A N r s w u v (W.fee (m + D.scheme.d) v) + + W.shipment (result A N r s u).format.width m (Attachment.volume a b m) k (m + + l) (Attachment.volume a b (m + l)) (h + t) l w (h + lineBits A) + +/-- The block rate used in the `Restore` construction. -/ +def blockRate (w W : ℕ) := + blockWork A N r s + + 3 * ((4000 * (1 + W) + 2100) * 2 ^ d + 1000) * (Letters A).width + + (1 + 4 * A.ℓ + 137 * (A.ℓ + h) + 13 * (1 + 2 ^ l) * 2 ^ n * (l + w + (h + n))) + + 4 * (1 + 2 ^ l) * (2 ^ (n + l) * (100 + (2 * (h + n) + l + w)) ^ 140 + 35 * (w + 2 ^ l * w + + 2 ^ n * (l + 3 * w))) + + 8 * 2 ^ l * (script A.scheme).width + +theorem price (u w : ℕ) (W : Prices F) : + let v := 2 ^ h * (Letters A).width + commandCost A N r s w u v (W.fee (m + d) v) + 4 * (result A N r s u).format.width ≤ + 2 ^ m * hostRate m d l W.W (W.w ^ W.power) + 2 ^ (m + h) * blockRate A N r s w W.W := by + dsimp only + have he := (result A N r s u).width + change _ = 2 ^ (m + l) * (8 * (m + l + 2) + 2 + 2 ^ h * ((script A.scheme).width + + (script A.scheme).width)) at he + rw [command_price, SpanProgram.price, SpanPlan.emit_price, he] + unfold hostRate blockRate Window.readCost gatherCost Prices.fee + simp only [pow_add] + generalize (100 + (m + d + 3 * m + 1)) ^ 200 = C + generalize (100 + (2 * (h + n) + l + w)) ^ 140 = R + have pad : 140 * (2 ^ m + 2 ^ m * 2 ^ l) * (w + 2 ^ l * w) ≤ 2 ^ h * (140 * (2 ^ m + + 2 ^ m * 2 ^ l) * (w + 2 ^ l * w)) := + Nat.le_mul_of_pos_left _ (Nat.two_pow_pos _) + ring_nf at pad ⊢ + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Uniform parameters for the cost of restoring an attached core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Packing Rounds.Contraction + +/-- The data for the measure construction, including `F`, `[field`, `D`, `A`, `N`. -/ +structure Measure where + /-- The `Measure` component of type `Type`. -/ + F : Type + [field : Field F] + /-- The `Measure` component of type `Template F`. -/ + D : Template F + /-- The `Measure` component of type `Attachment D`. -/ + A : Attachment D + /-- The `Measure` field of type `ℕ`. -/ + N : ℕ + /-- The `Measure` field of type `ℕ`. -/ + r : ℕ + /-- The `Measure` field of type `ℕ`. -/ + s : ℕ + /-- The remaining component of type `Prices F`. -/ + c : Prices F + /-- The `Measure` field of type `ℕ`. -/ + w : ℕ + /-- Stores the fst associated with this `Measure`. -/ + fst : ℕ + /-- Stores the snd associated with this `Measure`. -/ + snd : ℕ + +attribute [instance] Measure.field + +namespace Measure +open BatchDescent.Phase + +variable (i : Measure) +/-- Uses `i.D.scheme.m` as the representation. -/ +abbrev m := i.D.scheme.m +/-- Uses `i.D.scheme.d` as the representation. -/ +abbrev d := i.D.scheme.d +/-- Uses `i.D.scheme.h` as the representation. -/ +abbrev h := i.D.scheme.h +/-- Computes the n by the application `lineBits i.A`. -/ +abbrev n := lineBits i.A +/-- Computes the l by the application `bits i.r i.s (Tether.width i.N i.r i.s)`. -/ +abbrev l := bits i.r i.s (Tether.width i.N i.r i.s) + +/-- Only the side lengths and the field-independent price multiplier +occur in the coefficient of the number of exterior bits. -/ +def outer := 1000 + i.c.W + i.fst + (i.h + i.snd) + i.l + i.w + (i.h + i.n) +/-- The value specified by `i.outer + (i.A.ℓ + i.D.scheme.ℓ + i.D.count) + 2 ^ i.d + 2 ^ i.n + 2 +^ i.l + Install.localCost (2 ^ i.d + (2 + i.d + i.l))`. -/ +def short := i.outer + (i.A.ℓ + i.D.scheme.ℓ + i.D.count) + + 2 ^ i.d + 2 ^ i.n + 2 ^ i.l + Install.localCost (2 ^ i.d + (2 + i.d + i.l)) +/-- The quantity computed by `i.short + i.m + (i.m + i.l) + i.c.w + i.c.w ^ i.c.power`. -/ +def long := i.short + i.m + (i.m + i.l) + i.c.w + i.c.w ^ i.c.power + +theorem two : 2 ≤ i.outer := by unfold outer; omega +theorem small : i.outer ≤ i.short := by + unfold short + have h₁ := Nat.zero_le (2 ^ i.d) + have h₂ := Nat.zero_le (2 ^ i.l) + have h₃ := Nat.zero_le (2 ^ i.n) + omega +theorem large : i.short ≤ i.long := by + unfold long + have := Nat.zero_le (i.c.w ^ i.c.power) + omega +theorem short_two : 2 ≤ i.short := i.two.trans i.small +theorem long_two : 2 ≤ i.long := i.short_two.trans i.large + +/-- Computes the fast by the application `Poly short f`. -/ +abbrev Fast (f : Measure → ℕ) := Poly short f +/-- Computes the slow by the application `Poly long f`. -/ +abbrev Slow (f : Measure → ℕ) := Poly long f + +variable {f : Measure → ℕ} + +theorem Fast.slow (h : Fast f) : Slow f := h.grow large +theorem constantValue (c : ℕ) : Fast (fun _ => c) := Poly.const short_two c +theorem small_num (h : ∀ i, f i ≤ i.outer) : Fast f := Poly.of_le short_two (fun i + => (h i).trans i.small) +theorem priceW : Fast (fun i => i.c.W) := small_num fun i => by unfold outer; omega +theorem codeBits : Fast w := small_num fun i => by unfold outer; omega +theorem height : Fast h := small_num fun i => by unfold outer; omega +theorem names : Fast n := small_num fun i => by unfold outer; omega +theorem seats : Fast (fun i => i.A.k) := names.mono fun i => by unfold n lineBits; omega +theorem spans : Fast (fun i => i.A.e) := names.mono fun i => by unfold n lineBits; omega +theorem hardware : Fast l := small_num fun i => by unfold outer; omega + +private theorem terms : 0 ≤ 2 ^ i.d ∧ 0 ≤ 2 ^ i.n ∧ 0 ≤ 2 ^ i.l := ⟨Nat.zero_le _, Nat.zero_le _, + Nat.zero_le _⟩ +theorem branches : Fast (fun i => 2 ^ i.d) := Poly.of_le short_two fun i + => by unfold short; have := i.terms; omega +theorem degree : Fast d := branches.of_exp +theorem lines : Fast (fun i => 2 ^ i.n) := Poly.of_le short_two fun i + => by unfold short; have := i.terms; omega +theorem copies : Fast (fun i => 2 ^ i.l) := Poly.of_le short_two fun i + => by unfold short; have := i.terms; omega +theorem control : Fast (fun i => Install.localCost (2 ^ i.d + (2 + i.d + i.l))) := + Poly.of_le short_two fun _ => Nat.le_add_left .. +theorem labels : Fast (fun i => i.A.ℓ + i.D.scheme.ℓ + i.D.count) := + Poly.of_le short_two fun i => by unfold short; have := i.terms; omega +theorem label : Fast (fun i => i.A.ℓ) := labels.mono fun i => by omega +theorem hosts : Slow m := Poly.of_le long_two fun i + => by unfold long; have := Nat.zero_le (i.c.w ^ i.c.power); omega +theorem padding : Slow (fun i => i.c.w ^ i.c.power) := Poly.of_le long_two fun _ + => Nat.le_add_left .. + +end Measure +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Uniform polynomial overhead of short records and long addresses -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Measure +open BatchDescent.Phase +open Coloring + +private theorem circle : Fast (fun i => 2 ^ radius i.d) := by + have h := (Poly.exp_add (g := fun _ => 1) branches (constantValue 2)).pow 2 + simpa only [radius, pow_mul] using h + +private theorem mask : Fast (fun i => maskWidth i.d) + := circle.mul (circle.add (branches.mul (constantValue 2))) + +theorem script_size : Fast (fun i => (script i.A.scheme).width) := by + have w : Fast (fun i => 2 ^ (1 + i.A.e)) := lines.mono fun i => + Nat.pow_le_pow_right (by decide) (Nat.le_add_left ..) + have h := (constantValue 1).add ((label.add seats).add (w.mul + ((constantValue 1).add ((constantValue 1).add + ((constantValue 3).add ((constantValue 1).add spans)))))) + exact h.mono (fun i => (script_width _).le) + +private theorem question : Fast (fun i => (Query i.A i.N i.r i.s).width) := + ((((height.add hardware).add (constantValue 1)).add mask).add (circle.mul label)).mono (fun _ + => (query_eq ..).le) + +private theorem reply : Fast (fun i => (Reply i.A i.N i.r i.s).width) := + ((script_size.add (constantValue 1)).add + ((constantValue 8).mul (((constantValue 2).add degree).add hardware))).mono + (fun _ => (reply_eq ..).le) + +private theorem letters : Fast (fun i => (Letters i.A).width) := + (circle.mul label).mono fun _ => (letters_eq ..).le + +private theorem coordinates : Fast (fun i => i.l + i.w + (i.h + i.n)) + := (hardware.add codeBits).add (height.add names) + +theorem gates : Fast (fun i => gateWidth i.A i.N i.r i.s + commandSize i.A i.N i.r i.s i.w + + 2 * (script i.A.scheme).width) := by + have q := (label.add height).add ((((constantValue 1).add copies).mul lines).mul coordinates) + have mount : Fast (fun i => commandSize i.A i.N i.r i.s i.w) := + q.mono fun _ => (SpanProgram.size_eq ..).le + exact ((question.add reply).add mount).add ((constantValue 2).mul script_size) + +private theorem work : Fast (fun i => blockWork i.A i.N i.r i.s) := by + have lp : Fast (fun i => i.D.scheme.ℓ + i.D.count + i.A.ℓ) := labels.mono fun _ => by omega + have x := (((constantValue 28).mul lp).add ((constantValue 16).mul label)).add + ((constantValue 4).mul letters) + have y := ((constantValue 1).add ((constantValue 137).mul question)).add + ((constantValue 5).mul reply) + exact x.add (copies.mul (y.add (((constantValue 8).mul control).mul script_size))) + +theorem blocks : Fast (fun i => blockRate i.A i.N i.r i.s i.w i.c.W) := by + have C := constantValue + have x := (((C 4000).mul ((C 1).add priceW)).add (C 2100)).mul branches + have x := ((C 3).mul (x.add (C 1000))).mul letters + have per := ((C 1).add ((C 4).mul label)).add ((C 137).mul (label.add height)) + have y := per.add ((((C 13).mul ((C 1).add copies)).mul lines).mul coordinates) + have pow := ((C 100).add ((((C 2).mul (height.add names)).add hardware).add codeBits)).pow 140 + have body := (codeBits.add (copies.mul codeBits)).add (lines.mul (hardware.add ((C 3).mul + codeBits))) + have t := ((C 4).mul ((C 1).add copies)).mul (((lines.exp_add copies).mul pow).add ((C 35).mul + body)) + exact (((work.add x).add y).add t).add (((C 8).mul copies).mul script_size) + +private theorem skeleton : Slow (fun i => hostWork i.m i.d i.l) := by + have C n := (constantValue n).slow + have D := branches.slow + have a := (C 28).mul ((D.mul (hosts.add (C 2))).add (C 2)) + have b := (C 8).mul ((C 1).add (D.mul (((C 2).mul hosts).add (C 2)))) + have c := (C 4).mul (((C 100).add (hosts.add circle.slow)).pow 60) + have d := (C 4).mul (((C 1).add mask.slow).add ((C 39).mul (D.mul hosts))) + have e := (((C 4).mul control.slow).mul copies.slow).mul + (((C 8).mul ((hosts.add hardware.slow).add (C 2))).add (C 2)) + exact ((((a.add b).add (C 4)).add c).add d).add e + +theorem addresses : Slow (fun i => hostRate i.m i.d i.l i.c.W (i.c.w ^ i.c.power)) := by + have C n := (constantValue n).slow + have D := branches.slow + have M := hosts.add degree.slow + have a := (((C 4000).mul ((C 1).add priceW.slow)).mul D).mul ((C 1).add padding) + have b := ((C 4).mul D).mul (((C 100).add ((M.add ((C 3).mul hosts)).add (C 1))).pow 200) + have c := ((C 1100).mul D).mul (M.add (C 1)) + have t := (C 3).mul (((a.add b).add c).add (((C 1000).mul D).mul hosts)) + have size := hosts.add hardware.slow + have s := ((C 136).mul copies.slow).mul (size.add hardware.slow) + have tail := ((C 4).mul copies.slow).mul (((C 8).mul (size.add (C 2))).add (C 2)) + exact (((skeleton.add t).add (((C 4).mul D).mul hosts)).add s).add tail + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Measure +end + +/- # Uniform gate and network bounds for degree restoration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Measure +open BatchDescent.Phase Rounds.Contraction + +variable (i : Measure) + +private def host (j : ℕ) := + hostRate i.m i.d i.l i.c.W (i.c.w ^ i.c.power) + (1 + 2 ^ i.l) * 2 ^ i.l * i.long ^ j + (1 + + 2 ^ i.l) * i.outer ^ j + +private def block (j : ℕ) := + blockRate i.A i.N i.r i.s i.w i.c.W + (1 + 2 ^ i.l) * 2 ^ i.l * 2 ^ i.n * i.outer ^ j + +private theorem certificate : ∃ j, ∀ (i : Measure) u a b, + stageCost i.A i.N i.r i.s u i.w a b i.fst i.snd i.c ≤ + 2 ^ i.m * i.host j + 2 ^ (i.m + i.h) * i.block j + (wd a + wd b) * (2 * i.outer ^ j) := by + obtain ⟨j, hj⟩ := Prices.shipment_bound + refine ⟨j, fun i u a b => ?_⟩ + let n := (result i.A i.N i.r i.s u).format.width + let B := Attachment.volume a b + let S := i.outer + let T := S + i.m + (i.m + i.l) + i.c.w + i.c.w ^ i.c.power + have he := hj i.F i.c n i.m (B i.m) i.fst (i.m + i.l) (B (i.m + i.l)) (i.h + i.snd) i.l i.w (i.h + + i.n) + let N := (2 ^ i.m + 2 ^ (i.m + i.l)) * 2 ^ i.l + have h : i.c.shipment n i.m (B i.m) i.fst (i.m + i.l) (B (i.m + i.l)) (i.h + i.snd) i.l i.w (i.h + + i.n) ≤ + 4 * n + N * (i.long ^ j + 2 ^ (i.h + i.n) * S ^ j) + (B i.m + B (i.m + i.l)) * S ^ j := by + refine he.trans ?_ + change 4 * n + N * (T ^ j + 2 ^ (i.h + i.n) * S ^ j) + (B i.m + B (i.m + i.l)) * S ^ j ≤ _ + have : T ≤ i.long := by unfold T S long; gcongr; exact i.small + exact Nat.add_le_add_right (Nat.add_le_add_left (Nat.mul_le_mul_left _ + (Nat.add_le_add_right (Nat.pow_le_pow_left this _) _)) _) _ + have cost := price i.A i.N i.r i.s u i.w i.c + unfold stageCost + dsimp only + refine (Nat.add_le_add_left h _).trans ?_ + rw [← add_assoc, ← add_assoc] + refine (Nat.add_le_add_right (Nat.add_le_add_right cost _) _).trans_eq ?_ + unfold N B S host block Attachment.volume + simp only [pow_add] + ring + +private theorem bounds (j : ℕ) : Slow (fun i => i.host j) ∧ Fast (fun i => i.block j) := by + have n := (constantValue 1).add copies + have m := n.mul copies + have f : Fast outer := Poly.of_le short_two small + have s : Slow long := Poly.of_le long_two fun _ => le_rfl + have hh : Slow (fun i => i.host j) := by + have hn : Slow _ := Fast.slow n + have hm : Slow _ := Fast.slow m + exact (addresses.add (hm.mul (s.pow j))).add (hn.mul (f.slow.pow j)) + exact ⟨hh, blocks.add ((m.mul lines).mul (f.pow j))⟩ + +theorem bound : ∃ K : ℕ, ∀ (i : Measure) (u : ℕ) (a b : Wire), + gateWidth i.A i.N i.r i.s + commandSize i.A i.N i.r i.s i.w + 2 * (script i.A.scheme).width + ≤ i.short ^ K ∧ + stageCost i.A i.N i.r i.s u i.w a b i.fst i.snd i.c ≤ + 2 ^ i.m * i.long ^ K + 2 ^ (i.m + i.h) * i.short ^ K + (wd a + wd b) * i.outer ^ K := by + obtain ⟨j, hj⟩ := certificate + obtain ⟨f, hf⟩ := gates.bound + obtain ⟨t, ht⟩ := (bounds j).1.bound + obtain ⟨s, hs⟩ := (bounds j).2.bound + refine ⟨f + t + s + j + 1, fun i u a b => ?_⟩ + have hl := i.long_two + have hb := i.short_two + have he := i.two + refine ⟨(hf i).trans (Nat.pow_le_pow_right (by omega) (by omega)), (hj i u a b).trans ?_⟩ + gcongr + · exact (ht i).trans (Nat.pow_le_pow_right (by omega) (by omega)) + · exact (hs i).trans (Nat.pow_le_pow_right (by omega) (by omega)) + · calc + _ ≤ i.outer ^ (j + 1) := by rw [pow_succ']; gcongr + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Measure +end + +/- # Composing the restoration controller and the payload network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing Rounds.Contraction + +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) + (N r s u w : ℕ) (a b : Wire) (k t : ℕ) +local notation "l" => bits r s (Tether.width N r s) +local notation "m" => D.scheme.m +local notation "h" => D.scheme.h +local notation "vol" => Attachment.volume a b +local notation "O" => result A N r s u + +/-- The construction uses `bits r s (Tether.width N r s)` for its intermediate `p`. -/ +abbrev channels (_ : Attachment D) (N r s : ℕ) (a b : Wire) (k t : ℕ) := + let p := bits r s (Tether.width N r s) + PeerLayout.S D.scheme.m (Attachment.volume a b D.scheme.m) k + (D.scheme.m + p) (Attachment.volume a b (D.scheme.m + p)) (D.scheme.h + t) (2 ^ p) + +theorem Data.moves (X : Data A N r s u a b) (hk : k < w) (ht : h + t < w) + (hx : A.scheme.Fits (A.rows X.raw) (vol m) k) + (hy : (O).scheme.Fits X.frame.1 (vol (m + l)) (h + + t)) (i : Val a) (j : Val b) (v : (Attachment.payload a b (h + t) (m + l)).obj) : + (channels A N r s a b k t).Carries (Payload.Script.decode le_rfl (commands A N r s w X.raw)) + (A.scheme.store _ hx (X.p.exterior i j)) v ↔ + (O).scheme.store _ hy (X.pres.pres.exterior i j) = v := by + have e := (X.certifies hx hk).supplies hx hy hk ht + simp only [Equiv.symm_apply_apply] at e + exact e.carries i j v + +variable {A N r s u w a b k t} +private theorem Data.fitted (X : Data A N r s u a b) (hi : ∀ z, X.board.diagram.arity z ≤ 2 ^ t) : + (O).scheme.Fits X.frame.1 (vol (m + l)) (h + t) := X.pres.fits hi + +private theorem issue {J : Type 1} (xs : J → Data A N r s u a b) + (src : J → (Attachment.payload a b k m).obj) + (dst : J → (Attachment.payload a b (h + t) (m + l)).obj) + (hok : ∀ z v, (channels A N r s a b k t).Carries + (Payload.Script.decode le_rfl (commands A N r s w (xs z).raw)) (src z) v ↔ dst z = v) + (W : Prices F) (hm : 1 ≤ m) (hd : m + D.scheme.d ≤ W.w) + (hc : 2 ^ l * ((max k (h + t) + 1) * (2 ^ m + 2 ^ (m + l))) < 2 ^ W.w) : + ∃ gate : Table F, ∀ {U : ℕ} {K : Set (Table F)}, 3 ≤ U → + gate ∈ K → (program A N r s w).gate ∈ K → gateWidth A N r s ≤ U → commandSize A N r s w ≤ U → + Computes F U K (A.format.pair (Attachment.payload a b k m)) + ((O).format.pair (Attachment.payload a b (h + t) (m + l))) (fun z => ((xs z).raw, src z)) + (fun z => ((xs z).frame, dst z)) (fun _ => 1) (stageCost A N r s u w a b k t W) := by + obtain ⟨gate, hg⟩ := joint (A := A) (N := N) (r := r) (s := s) (u := u) (w := w) (a := a) (b := b) + refine ⟨gate, ?_⟩ + intro U K hu h₁ h₂ hw hw' + have ha := W.access (L := K) hu (hm.trans (Nat.le_add_right ..)) hd (2 ^ h * (Letters A).width) + have ctrl := (hg hu h₁ h₂ hw hw' ha le_rfl).restrict xs + have done := W.ship (X := A.format) (Y := (O).format) + (y := fun i : J => (xs i).frame) (cmd := fun i : J => commands A N r s w (xs i).raw) + (f := src) (g := dst) (V := vol m) (V' := vol (m + + l)) hu hm (hm.trans (Nat.le_add_right ..)) hc ctrl hok + exact done + +variable (P : A.Data a b u → Prop) +/-- The subtype of `X : A.Data a b u` satisfying `P X ∧ X.Fits k`. -/ +abbrev Input (k : ℕ) := {X : A.Data a b u // P X ∧ X.Fits k} + +variable (R : ∀ X : Input P k, Feasible X.val N r s) + (cap : ∀ (i : Input P k) (v : (R i).data.board.diagram.V), (R i).data.board.diagram.arity v + ≤ 2 ^ t) +/-- The indexed operation `rawLayer (A := A) (u := u) (fun i : Input P k => Feasible.data (R i)) +t cap`. -/ +abbrev unmerged : Rounds.Layer F a b := rawLayer (A := A) (u := u) (fun i : Input P k + => Feasible.data (R i)) t cap +local notation "C" => channels A N r s a b k t + +theorem stage (W : Prices F) (hm : 1 ≤ m) (hd : m + D.scheme.d ≤ W.w) + (hc : 2 ^ l * ((max k (h + t) + 1) * (2 ^ m + 2 ^ (m + l))) < 2 ^ W.w) + (hk : k < w) (ht : h + t < w) : + ∃ gate : Table F, ∀ {U : ℕ} {K : Set (Table F)}, 3 ≤ U → + gate ∈ K → (program A N r s w).gate ∈ K → gateWidth A N r s ≤ U → commandSize A N r s w ≤ U → + Transforms F U K (A.frame a b u k P) (unmerged P R cap).snapshot (stageCost A N r s u w a b k + t W) := by + let J := Input P k × Val a × Val b + let X (z : J) := (R z.1).data + have hx (z : J) : A.scheme.Fits (A.rows (X z).raw) (vol m) k := z.1.property.2 + have hy (z : J) : (O).scheme.Fits (X z).frame.1 (vol (m + l)) (h + t) := (X z).fitted (cap z.1) + let src (z : J) := A.scheme.store _ (hx z) ((X z).p.exterior z.2.1 z.2.2) + let dst (z : J) := (O).scheme.store _ (hy z) ((X z).pres.pres.exterior z.2.1 z.2.2) + have hok (z : J) (v : (Attachment.payload a b (h + t) (m + l)).obj) : + (C).Carries (Payload.Script.decode le_rfl (commands A N r s w (X z).raw)) (src z) v ↔ dst z + = v := + Data.moves A N r s u w a b k t (X z) hk ht (hx z) (hy z) z.2.1 z.2.2 v + obtain ⟨gate, hg⟩ := issue X src dst hok W hm hd hc + refine ⟨gate, fun hu h₁ h₂ hw hw' => ?_⟩ + have run := hg hu h₁ h₂ hw hw' + exact Transforms.deterministic (X := A.frame a b u k P) (Y := (unmerged P R cap).snapshot) id + (fun i => (R i).data.route.eval.symm) run + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Spans.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Spans.lean new file mode 100644 index 0000000000..91e8a380db --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Spans.lean @@ -0,0 +1,881 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Costs + +/-! +# Replacing directed wires by chains of equality tests + +An old table and arbitrarily many equality tests may occupy a +station simultaneously. Testing consecutive bits on every chain +gives exactly one extension of each original assignment. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Finset + +variable {F : Type} {x y : Wire} (G : Diagram F x y) (V : Type) + +open scoped Classical in +/-- The data for the chain construction, including `owner`, `turns`, `node`, `start`, `finish`. -/ +structure Chain where + /-- The owner assigned to each element of type `G.V → V`. -/ + owner : G.V → V + /-- The `Chain` component of type `G.E → ℕ`. -/ + turns : G.E → ℕ + /-- The `Chain` component of type `G.E → ℕ → V`. -/ + node : G.E → ℕ → V + start : ∀ e, node e 0 = owner (G.source e) + finish : ∀ e, node e (turns e + 1) = owner (G.target e) + +namespace Chain +variable {G V} (C : Chain G V) + +open scoped Classical in +/-- Indexes the edge by the coordinates of `Σ e, Fin (C.turns e + 1)`. -/ +abbrev Edge := Σ e, Fin (C.turns e + 1) +open scoped Classical in +/-- Indexes the turn by the coordinates of `Σ e, Fin (C.turns e)`. -/ +abbrev Turn := Σ e, Fin (C.turns e) + +open scoped Classical in +/-- Uses `⟨t.1, t.2.castSucc⟩` as the representation. -/ +def before (t : C.Turn) : C.Edge := ⟨t.1, t.2.castSucc⟩ +open scoped Classical in +/-- Uses `⟨t.1, t.2.succ⟩` as the representation. -/ +def after (t : C.Turn) : C.Edge := ⟨t.1, t.2.succ⟩ +open scoped Classical in +/-- The quantity computed by `C.node t.1 (t.2.val + 1)`. -/ +def joint (t : C.Turn) := C.node t.1 (t.2.val + 1) +open scoped Classical in +/-- Uses `⟨e, 0⟩` as the representation. -/ +def first (e : G.E) : C.Edge := ⟨e, 0⟩ +open scoped Classical in +/-- Uses `⟨e, Fin.last _⟩` as the representation. -/ +def last (e : G.E) : C.Edge := ⟨e, Fin.last _⟩ + +open scoped Classical in +/-- In the case `.inl i`, this construction gives `C.owner (G.src.symm (.inl i)).1`. -/ +def src : slots x ⊕ C.Edge → V + | .inl i => C.owner (G.src.symm (.inl i)).1 + | .inr e => C.node e.1 e.2.val + +open scoped Classical in +/-- In the case `.inl i`, this construction gives `C.owner (G.dst.symm (.inl i)).1`. -/ +def dst : slots y ⊕ C.Edge → V + | .inl i => C.owner (G.dst.symm (.inl i)).1 + | .inr e => C.node e.1 (e.2.val + 1) + +open scoped Classical in +/-- Computes the left by the application `p.map id C.first`. -/ +def left (p : slots x ⊕ G.E) := p.map id C.first +open scoped Classical in +/-- Computes the right by the application `p.map id C.last`. -/ +def right (p : slots y ⊕ G.E) := p.map id C.last + +open scoped Classical in +theorem src_left (p : slots x ⊕ G.E) : C.src (C.left p) = C.owner (G.src.symm p).1 := by + cases p <;> first | rfl | exact C.start _ + +open scoped Classical in +theorem dst_right (p : slots y ⊕ G.E) : C.dst (C.right p) = C.owner (G.dst.symm p).1 := by + cases p <;> first | rfl | exact C.finish _ + +variable [Field F] + +open scoped Classical in +/-- The factor used in the `Chain` construction. -/ +def factor (v : V) (a : slots x ⊕ C.Edge → Bool) (b : slots y ⊕ C.Edge → Bool) := + (∏ w : {w // C.owner w = v}, G.weight w (a ∘ C.left) (b ∘ C.right)) * + (∏ t : {t // C.joint t = v}, if b (.inr (C.before t)) = a (.inr (C.after t)) then (1 : F) else 0) + +open scoped Classical in +theorem local_factor : Diagram.Local C.src C.dst C.factor := by + intro v a b a' b' ha hb + unfold factor + refine congrArg₂ (· * ·) (prod_congr rfl fun w _ => ?_) (prod_congr rfl fun t _ => ?_) + · exact G.local_weight _ _ _ _ _ + (fun p hp => ha _ ((C.src_left p).trans ((congrArg C.owner hp).trans w.property))) + (fun p hp => hb _ ((C.dst_right p).trans ((congrArg C.owner hp).trans w.property))) + · rw [hb (.inr (C.before t)) t.property, ha (.inr (C.after t)) t.property] + +variable [Fintype V] +open scoped Classical in +/-- Computes the graph by the application `Diagram.ofLocal C.src C.dst C.factor`. -/ +abbrev graph := Diagram.ofLocal C.src C.dst C.factor + +open scoped Classical in +/-- Computes the original by the application `Sum.map C.left C.right`. -/ +def original : G.End → C.graph.End := Sum.map C.left C.right + +open scoped Classical in +theorem station_original (i : G.End) : C.graph.station (C.original i) = C.owner (G.station i) := by + cases i <;> first | exact C.src_left _ | exact C.dst_right _ + +open scoped Classical in +private def consistent (z : C.Edge → Bool) := ∀ t, z (C.before t) = z (C.after t) + +omit [Fintype V] [Field F] in +open scoped Classical in +private theorem constantValue (z : C.Edge → Bool) (hz : C.consistent z) (e : C.Edge) : + z e = z (C.first e.1) := by + obtain ⟨e, k⟩ := e + induction k using Fin.induction with + | zero => rfl + | succ i hi => exact (hz ⟨e, i⟩).symm.trans hi + +open scoped Classical in +private def repeatBits : (G.E → Bool) ≃ {z : C.Edge → Bool // C.consistent z} where + toFun z := ⟨fun e => z e.1, fun _ => rfl⟩ + invFun z := z.val ∘ C.first + left_inv _ := rfl + right_inv z := Subtype.ext (funext fun e => (C.constantValue z.val z.property e).symm) + +open scoped Classical in +private theorem product (a : Val x) (b : Val y) (z : C.Edge → Bool) : + (∏ v, C.graph.vertex a b z v) = + if C.consistent z then ∏ v, G.vertex a b (z ∘ C.first) v else 0 := by + have he (v : V) : C.graph.vertex a b z v = + C.factor v (Sum.elim (bits x a) z) (Sum.elim (bits y b) z) := + Diagram.vertex_ofLocal _ _ _ C.local_factor a b z v + simp only [he, factor, prod_mul_distrib] + change (_ * ∏ v, ∏ t : {t // C.joint t = v}, if z (C.before t) + = z (C.after t) then (1 : F) else 0) = _ + rw [Fintype.prod_fiberwise C.owner (fun v => G.weight v _ _), + Fintype.prod_fiberwise C.joint (fun t => if z (C.before t) = z (C.after t) then (1 : F) else 0)] + by_cases h : C.consistent z + · rw [ite_eq_left h] + have hl : Sum.elim (bits x a) z ∘ C.left = Sum.elim (bits x a) (z ∘ C.first) := by + funext p; cases p <;> rfl + have hr : Sum.elim (bits y b) z ∘ C.right = Sum.elim (bits y b) (z ∘ C.first) := by + funext p; cases p with + | inl _ => rfl + | inr e => exact C.constantValue z h (C.last e) + simp only [show ∀ t, z (C.before t) = z (C.after t) from h, ite_true, prod_const_one, mul_one, + hl, hr] + rfl + · rw [ite_eq_right h] + obtain ⟨t, ht⟩ := not_forall.mp h + rw [prod_eq_zero (mem_univ t) (ite_eq_right ht), mul_zero] + +open scoped Classical in +theorem eval : C.graph.eval = G.eval := by + let : DecidableEq C.Edge := Classical.typeDecidableEq _ + funext a b + unfold Diagram.eval + simp only [C.product] + rw [← sum_filter] + refine (sum_subtype (p := C.consistent) (F := inferInstance) _ mem_filter_univ (fun z => ∏ v, + G.vertex a b (z ∘ C.first) v)).trans ?_ + exact (Fintype.sum_equiv C.repeatBits _ _ (fun _ => rfl)).symm + +end Chain +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Original and relay ports on a network of chains -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Finset + +variable {F : Type} [Field F] {x y : Wire} {G : Diagram F x y} {V : Type} [Fintype V] + +open scoped Classical in +/-- Computes the tip by the application `cond b (.inr (.inr e)) (.inl (.inr e))`. -/ +def tip (G : Diagram F x y) (e : G.E) (b : Bool) : G.End := + cond b (.inr (.inr e)) (.inl (.inr e)) + +open scoped Classical in +/-- Computes the endpoint by the application `cond b (G.target e) (G.source e)`. -/ +def endpoint (G : Diagram F x y) (e : G.E) (b : Bool) := cond b (G.target e) (G.source e) + +omit [Field F] in +open scoped Classical in +theorem station_tip (e : G.E) (b : Bool) : G.station (tip G e b) = endpoint G e b + := by cases b <;> rfl + +omit [Field F] in +open scoped Classical in +theorem side_tip (e : G.E) (b : Bool) : (tip G e b).isRight = b := by cases b <;> rfl + +omit [Field F] in +open scoped Classical in +theorem tip_inj {e e' : G.E} {b b' : Bool} (h : tip G e b = tip G e' b') : e = e' ∧ b = b' := by + cases b <;> cases b' <;> cases h <;> exact ⟨rfl, rfl⟩ + +namespace Chain +variable (C : Chain G V) +local notation "H" => C.graph + +open scoped Classical in +/-- Computes the relay by the application `cond b (.inr (.inr (C.before t))) (.inl (.inr +(C.after t)))`. -/ +def relay (t : C.Turn) (b : Bool) : (H).End := + cond b (.inr (.inr (C.before t))) (.inl (.inr (C.after t))) + +open scoped Classical in +theorem station_relay (t : C.Turn) (b : Bool) : (H).station (C.relay t b) = C.joint t := by + cases b <;> rfl + +open scoped Classical in +theorem side_relay (t : C.Turn) (b : Bool) : (C.relay t b).isRight = b := by cases b <;> rfl + +open scoped Classical in +theorem side_original (e : G.End) : (C.original e).isRight = e.isRight := by cases e <;> rfl + +open scoped Classical in +/-- Indexes the place by the coordinates of `G.End ⊕ C.Turn × Bool`. -/ +abbrev Place := G.End ⊕ C.Turn × Bool + +open scoped Classical in +/-- Computes the use by the application `Sum.elim C.original (Function.uncurry C.relay)`. -/ +def use : C.Place → (H).End := Sum.elim C.original (Function.uncurry C.relay) + +open scoped Classical in +/-- In the case `.inl (.inl i)`, this construction gives `.inl (.inl (.inl i))`. -/ +def parse : (H).End → C.Place + | .inl (.inl i) => .inl (.inl (.inl i)) + | .inr (.inl i) => .inl (.inr (.inl i)) + | .inl (.inr ⟨e, k⟩) => Fin.cases (.inl (tip G e false)) (fun j => .inr (⟨e, j⟩, false)) k + | .inr (.inr ⟨e, k⟩) => Fin.lastCases (.inl (tip G e true)) (fun j => .inr (⟨e, j⟩, true)) k + +open scoped Classical in +theorem parse_original (e : G.End) : C.parse (C.original e) = .inl e := by + rcases e with (i|e)|(j|e) <;> first | rfl | simp [original, right, last, parse, tip] + +open scoped Classical in +theorem parse_relay (t : C.Turn) (b : Bool) : C.parse (C.relay t b) = .inr (t, b) := by + cases b + · exact Fin.cases_succ _ + · simp [relay, before, parse] + +open scoped Classical in +/-- Reindexes `C.Place` and `(H).End where toFun` by an equivalence. -/ +def positions : C.Place ≃ (H).End where + toFun := C.use + invFun := C.parse + left_inv + | .inl e => C.parse_original e + | .inr (t, b) => C.parse_relay t b + right_inv := by + rintro ((i|⟨e, k⟩)|(j|⟨e, k⟩)) + · rfl + · induction k using Fin.cases with + | zero => rfl + | succ k => + change C.use (C.parse (C.relay ⟨e, k⟩ false)) = _ + rw [parse_relay]; rfl + · rfl + · induction k using Fin.lastCases with + | last => + change C.use (C.parse (C.original (tip G e true))) = _ + rw [parse_original]; rfl + | cast k => + change C.use (C.parse (C.relay ⟨e, k⟩ true)) = _ + rw [parse_relay]; rfl + +open scoped Classical in +theorem cases_end (e : (H).End) : + (∃ q, e = C.original q) ∨ (∃ t b, e = C.relay t b) := by + obtain ⟨q | ⟨t, b⟩, rfl⟩ := C.positions.surjective e + · exact .inl ⟨q, rfl⟩ + · exact .inr ⟨t, b, rfl⟩ + +open scoped Classical in +/-- The indexed operation `Transcript.sample (G.table v) (fun i => z (G.portEquiv ⟨v, i⟩))`. -/ +def value (G : Diagram F x y) (v : G.V) (z : G.End → Bool) := + Transcript.sample (G.table v) (fun i => z (G.portEquiv ⟨v, i⟩)) + +open scoped Classical in +theorem test (v : V) (z : (H).End → Bool) : + value H v z = (∏ w : {w // C.owner w = v}, value G w (z ∘ C.original)) * + if ∀ t, C.joint t = v → z (C.relay t true) = z (C.relay t false) then 1 else 0 := by + change (H).weight v (z ∘ Sum.inl) (z ∘ Sum.inr) = _ + rw [Diagram.weight_ofLocal _ _ _ C.local_factor] + apply congrArg₂ (· * ·) + · rfl + · change (∏ t : {t // C.joint t = v}, if z (C.relay t true) + = z (C.relay t false) then (1 : F) else 0) = _ + split + · rename_i h + exact prod_eq_one (fun t _ => ite_eq_left (h _ t.property)) + · rename_i h + push Not at h + obtain ⟨t, hv, ht⟩ := h + exact prod_eq_zero (mem_univ ⟨t, hv⟩) (ite_eq_right ht) + +end Chain +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- +# Anchors for reading labels at relay sites + +All routes joining the same ordered pair follow the same simple +path. Each intermediate site belongs to the tree of just one old +station, whose span numbers therefore identify every passing wire. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Chain + +variable {F : Type} [Field F] {x y : Wire} {G : Diagram F x y} {V : Type} [Fintype V] + (C : Chain G V) + +open scoped Classical in +/-- The data for the frame construction, including `root`, `one`, `fix`, `agrees`, `simple`. -/ +structure Frame where + /-- The root of type `V → V`. -/ + root : V → V + one : Function.Injective C.owner + fix : ∀ v, root (C.owner v) = C.owner v + agrees : ∀ e e', G.source e = G.source e' → G.target e = G.target e' → + C.turns e = C.turns e' ∧ C.node e = C.node e' + simple : ∀ e i j, i ≤ C.turns e + 1 → j ≤ C.turns e + 1 → C.node e i = C.node e j → i = j + atJoint : ∀ t, root (C.joint t) = C.owner (G.source t.1) ∨ root (C.joint t) + = C.owner (G.target t.1) + +namespace Frame +variable {C} (f : C.Frame) + +open scoped Classical in +/-- Tests whether `f.root (C.joint t) = C.owner (G.target t.1)` holds. -/ +def side (t : C.Turn) := decide (f.root (C.joint t) = C.owner (G.target t.1)) + +omit [Field F] [Fintype V] in +open scoped Classical in +theorem side_eq (t : C.Turn) : f.root (C.joint t) = C.owner (endpoint G t.1 (f.side t)) := by + unfold side endpoint + by_cases h : f.root (C.joint t) = C.owner (G.target t.1) + · simp [h] + · simp only [decide_eq_false h, Bool.cond_false] + exact (f.atJoint t).resolve_right h + +omit [Field F] [Fintype V] in +open scoped Classical in +theorem away (t : C.Turn) : f.root (C.joint t) ≠ C.joint t := by + intro e + have h := t.2.isLt + rcases f.atJoint t with hp|hp + · have := f.simple t.1 (t.2.val + 1) 0 (by omega) (by omega) (e.symm.trans (hp.trans (C.start + _).symm)) + omega + · have := f.simple t.1 (t.2.val + 1) (C.turns t.1 + 1) (by omega) le_rfl + (e.symm.trans (hp.trans (C.finish _).symm)) + omega + +omit [Field F] [Fintype V] in +include f in +open scoped Classical in +theorem joints {t t' : C.Turn} (e : t.1 = t'.1) (h : C.joint t = C.joint t') : t = t' := by + obtain ⟨i, j⟩ := t + obtain ⟨k, l⟩ := t' + change i = k at e + subst k + have eq := f.simple i (j.val + 1) (l.val + 1) (by omega) (by omega) h + rw [show j = l by apply Fin.ext; omega] + +open scoped Classical in +/-- Computes the from turn by the application `tip G t.1 (f.side t)`. -/ +def fromTurn (t : C.Turn) := tip G t.1 (f.side t) + +open scoped Classical in +/-- The indexed operation `(C.parse p).elim id (fun t => f.fromTurn t.1)`. -/ +def ref (p : C.graph.End) := (C.parse p).elim id (fun t => f.fromTurn t.1) + +open scoped Classical in +theorem orig (p : G.End) : f.ref (C.original p) = p := by rw [ref, parse_original]; rfl + +open scoped Classical in +theorem pass (t : C.Turn) (b : Bool) : f.ref (C.relay t b) = f.fromTurn t := by + rw [ref, parse_relay]; rfl + +open scoped Classical in +theorem anchor (p : C.graph.End) : f.root (C.graph.station p) = C.owner (G.station (f.ref p)) := by + rcases C.cases_end p with ⟨q, rfl⟩|⟨t, b, rfl⟩ + · rw [orig, station_original, f.fix] + · rw [pass, station_relay, fromTurn, station_tip]; exact f.side_eq t + +open scoped Classical in +theorem unique {p q : C.graph.End} (hv : C.graph.station p = C.graph.station q) + (hd : p.isRight = q.isRight) (hr : f.ref p = f.ref q) : p = q := by + rcases C.cases_end p with ⟨p, rfl⟩|⟨t, b, rfl⟩ <;> rcases C.cases_end q with ⟨q, rfl⟩|⟨t', b', + rfl⟩ + · rw [orig, orig] at hr + rw [hr] + · rw [station_original, station_relay] at hv + exact (f.away t' (hv ▸ f.fix _)).elim + · rw [station_relay, station_original] at hv + exact (f.away t (hv.symm ▸ f.fix _)).elim + · rw [station_relay, station_relay] at hv + rw [side_relay, side_relay] at hd + rw [pass, pass] at hr + rw [f.joints (tip_inj hr).1 hv, hd] + +end Frame +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Chain +end + +/- # The old port controlling a directed segment of a path -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Chain.Frame + +variable {F : Type} [Field F] {x y : Wire} {G : Diagram F x y} {V : Type} [Fintype V] + {C : Chain G V} (f : C.Frame) +local notation "H" => C.graph + +open scoped Classical in +/-- The quantity computed by `cond b (i.2.val + 1) i.2.val`. -/ +def point (i : C.Edge) (b : Bool) := cond b (i.2.val + 1) i.2.val + +omit [Field F] [Fintype V] in +open scoped Classical in +theorem point_le (i : C.Edge) (b : Bool) : point i b ≤ C.turns i.1 + 1 := by + cases b <;> first | exact i.2.isLt.le | exact i.2.isLt + +open scoped Classical in +theorem endpoint_node (i : C.Edge) (b : Bool) : endpoint H i b = C.node i.1 (point i b) := by + cases b <;> rfl + +open scoped Classical in +/-- Tests whether `f.root (C.node i.1 (point i b)) = C.owner (G.target i.1)` holds. -/ +def leg (i : C.Edge) (b : Bool) := decide (f.root (C.node i.1 (point i b)) = C.owner (G.target i.1)) + +omit [Field F] [Fintype V] in +include f in +open scoped Classical in +theorem separate (e : G.E) : C.owner (G.source e) ≠ C.owner (G.target e) := by + intro h + have := f.simple e 0 (C.turns e + 1) (by omega) le_rfl ((C.start _).trans (h.trans (C.finish + _).symm)) + omega + +open scoped Classical in +theorem ref_tip (i : C.Edge) (b : Bool) : f.ref (tip H i b) = tip G i.1 (f.leg i b) := by + obtain ⟨e, k⟩ := i + cases b + · induction k using Fin.cases with + | zero => + change f.ref (C.original (tip G e false)) = tip G e (decide (f.root (C.node e 0) + = C.owner (G.target e))) + rw [orig, C.start, f.fix, decide_eq_false (f.separate e)] + | succ k => exact f.pass ⟨e, k⟩ false + · induction k using Fin.lastCases with + | last => + change f.ref (C.original (tip G e true)) = + tip G e (decide (f.root (C.node e (C.turns e + 1)) = C.owner (G.target e))) + simp only [orig, C.finish, f.fix, decide_true] + | cast k => exact f.pass ⟨e, k⟩ true + +variable {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G) + +open scoped Classical in +/-- Computes the old by the application `p.toSeating.ends (f.ref z)`. -/ +def old (z : (H).End) := p.toSeating.ends (f.ref z) + +open scoped Classical in +theorem old_tip (i : C.Edge) (b : Bool) : f.old p (tip H i b) = p.wirePin i.1 (f.leg i b) := by + unfold old + rw [ref_tip]; rfl + +open scoped Classical in +theorem old_here {q q' : (H).End} (h : (H).station q = (H).station q') : + (f.old p q).1.1 = (f.old p q').1.1 := by + have hv (e : G.End) : (p.toSeating.ends e).1.1 = p.vertex (G.station e) := by + obtain ⟨⟨u, i⟩, rfl⟩ := G.portEquiv.surjective e + rw [Scheme.Seating.ends_at, G.station_port]; rfl + have e := f.one ((f.anchor q).symm.trans ((congrArg f.root h).trans (f.anchor q'))) + rw [old, old, hv, hv, e] + +open scoped Classical in +theorem parallel {e e' : G.E} {t t' : Bool} (hd : p.Directed) + (h : (p.wirePin e t).1 = (p.wirePin e' t').1) : + G.source e = G.source e' ∧ G.target e = G.target e' ∧ + ∀ b, (p.wirePin e b).1 = (p.wirePin e' b).1 := by + have he : t = t' := (p.wirePin_dir hd _ _).symm.trans ((congrArg (S.direction r) h).trans + (p.wirePin_dir hd _ _)) + subst t' + have ht : (p.wirePin e (!t)).1 = (p.wirePin e' (!t)).1 := + Option.some.inj ((p.wirePin_peer _ _).symm.trans ((congrArg (S.peer r) h).trans (p.wirePin_peer + _ _))) + have pair (b : Bool) : (p.wirePin e b).1 = (p.wirePin e' b).1 + := by cases t <;> cases b <;> assumption + have eq (b : Bool) := p.vertex.injective ((p.wirePin_at _ _).symm.trans + ((congrArg Prod.fst (pair b)).trans (p.wirePin_at _ _))) + exact ⟨eq false, eq true, pair⟩ + +open scoped Classical in +theorem align {i j : C.Edge} (hu : G.source i.1 = G.source j.1) (hv : G.target i.1 = G.target j.1) + (hk : i.2.val = j.2.val) (b : Bool) : + endpoint H i b = endpoint H j b ∧ f.leg i b = f.leg j b := by + have hp : point i b = point j b := by unfold point; rw [hk] + have he : C.node i.1 (point i b) = C.node j.1 (point j b) := by rw [(f.agrees _ _ hu hv).2, hp] + rw [endpoint_node, endpoint_node] + exact ⟨he, by simp only [leg, he, hv]⟩ + +open scoped Classical in +theorem other {i j : C.Edge} (b : Bool) (hd : p.Directed) + (hv : endpoint H i b = endpoint H j b) + (hs : (f.old p (tip H i b)).1 = (f.old p (tip H j b)).1) : + endpoint H i (!b) = endpoint H j (!b) ∧ + (f.old p (tip H i (!b))).1 = (f.old p (tip H j (!b))).1 := by + rw [old_tip, old_tip] at hs + obtain ⟨hc, ht, hp⟩ := parallel p hd hs + obtain ⟨hn, he⟩ := f.agrees _ _ hc ht + rw [endpoint_node, endpoint_node, he] at hv + have hh := f.simple j.1 _ _ ((point_le i b).trans_eq (congrArg (·+1) hn)) (point_le j b) hv + have hi : i.2.val = j.2.val := by cases b <;> simpa [point] using hh + obtain ⟨hz, hl⟩ := f.align hc ht hi (!b) + rw [old_tip, old_tip, hl] + exact ⟨hz, hp _⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Chain.Frame +end + +/- # Parallel bits follow a common relay span in order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Chain.Frame +open Coloring + +variable {F : Type} [Field F] {x y : Wire} {G : Diagram F x y} {V : Type} [Fintype V] + {C : Chain G V} (f : C.Frame) {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G) +local notation "H" => C.graph + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def pair (e : ℕ) : Bool × B e ≃ B (1 + e) := Fintype.equivOfCardEq (by simp [pow_add]) + +open scoped Classical in +/-- The value specified by `pair S.e (q.isRight, (f.old p q).1.2)`. -/ +def lane (q : (H).End) := pair S.e (q.isRight, (f.old p q).1.2) + +open scoped Classical in +/-- The value specified by `((H).station q, f.lane p q)`. -/ +def mark (q : (H).End) := ((H).station q, f.lane p q) + +open scoped Classical in +/-- The value specified by `(f.old p q).2.val`. -/ +def offset (q : (H).End) := (f.old p q).2.val + +open scoped Classical in +theorem equal_mark {q q' : (H).End} (h : f.mark p q = f.mark p q') : + (H).station q = (H).station q' ∧ q.isRight = q'.isRight ∧ (f.old p q).1 = (f.old p q').1 := by + obtain ⟨hv, he⟩ := Prod.mk.inj h + obtain ⟨hs, ht⟩ := Prod.mk.inj ((pair _).injective he) + exact ⟨hv, hs, Prod.ext (f.old_here p hv) ht⟩ + +open scoped Classical in +theorem mark_inj {q q' : (H).End} (h : f.mark p q = f.mark p q') + (hn : f.offset p q = f.offset p q') : q = q' := by + obtain ⟨hv, hd, hs⟩ := f.equal_mark p h + exact f.unique hv hd (p.toSeating.ends.injective (Sigma.ext hs ((Fin.heq_ext_iff (congrArg + (S.width r) hs)).mpr hn))) + +open scoped Classical in +private theorem parallel_bit (hd : p.Directed) (e : G.E) (b : Bool) + (a : Fin (S.width r (p.wirePin e b).1)) : + ∃ k, (p.wirePin k b).1 = (p.wirePin e b).1 ∧ (p.wirePin k b).2.val = a.val := by + obtain ⟨q, hq⟩ := p.toSeating.ends.surjective ⟨(p.wirePin e b).1, a⟩ + have hv : (p.toSeating.ends q).1 = (p.wirePin e b).1 := by rw [hq] + have dir : q.isRight = b := (hd q).symm.trans ((congrArg (S.direction r) hv).trans (p.wirePin_dir + hd e b)) + have inside : S.peer r (p.toSeating.ends q).1 ≠ none := by rw [hv, p.wirePin_peer]; simp + have hw := congrArg (fun t => t.2.val) hq + rcases q with (i|k)|(i|k) + · exact (inside (p.input i)).elim + · subst b; exact ⟨k, hv, hw⟩ + · exact (inside (p.output i)).elim + · subst b; exact ⟨k, hv, hw⟩ + +open scoped Classical in +theorem covers (hd : p.Directed) (q : (H).End) (k : ℕ) (hk : k < S.width r (f.old p q).1) : + ∃ z, f.mark p z = f.mark p q ∧ f.offset p z = k := by + rcases C.cases_end q with ⟨e, rfl⟩|⟨t, b, rfl⟩ + · rw [old, orig] at hk + obtain ⟨j, hj⟩ := p.toSeating.ends.surjective ⟨(p.toSeating.ends e).1, ⟨k, hk⟩⟩ + have hs : (p.toSeating.ends j).1 = (p.toSeating.ends e).1 := by rw [hj] + have hv : G.station j = G.station e := by + obtain ⟨⟨a, i⟩, rfl⟩ := G.portEquiv.surjective j + obtain ⟨⟨b, l⟩, rfl⟩ := G.portEquiv.surjective e + rw [G.station_port, G.station_port] + rw [Scheme.Seating.ends_at, Scheme.Seating.ends_at] at hs + exact p.vertex.injective (congrArg Prod.fst hs) + have hb : j.isRight = e.isRight := (hd j).symm.trans ((congrArg (S.direction r) hs).trans (hd + e)) + refine ⟨C.original j, ?_, ?_⟩ + · simp only [mark, lane, station_original, hv, C.side_original j, C.side_original e, hb, old, + orig, hs] + · rw [offset, old, orig, hj] + · rw [old, pass] at hk + obtain ⟨e, hs, hk⟩ := parallel_bit p hd t.1 (f.side t) ⟨k, hk⟩ + obtain ⟨hc, ht, hp⟩ := parallel p hd hs + obtain ⟨hn, he⟩ := f.agrees e t.1 hc ht + let u : C.Turn := ⟨e, t.2.cast hn.symm⟩ + have hv : C.joint u = C.joint t := congrFun he (t.2.val + 1) + have hb : f.side u = f.side t := by unfold side; rw [hv, show G.target u.1 = _ from ht] + have hu : f.old p (C.relay u b) = p.wirePin e (f.side t) := by rw [old, pass, fromTurn, hb]; rfl + have hq : f.old p (C.relay t b) = p.wirePin t.1 (f.side t) := by rw [old, pass]; rfl + refine ⟨C.relay u b, ?_, ?_⟩ + · simp only [mark, lane, station_relay, hv, C.side_relay u b, C.side_relay t b, hu, hq, hs] + · rw [offset, hu]; exact hk + +open scoped Classical in +/-- In the case `.inl (.inr e)`, this construction gives `some (tip G e true)`. -/ +def opposite (G : Diagram F x y) : G.End → Option G.End + | .inl (.inr e) => some (tip G e true) + | .inr (.inr e) => some (tip G e false) + | _ => none + +omit [Field F] in +open scoped Classical in +theorem opposite_tip (e : G.E) (b : Bool) : opposite G (tip G e b) = some (tip G e (!b)) + := by cases b <;> rfl + +open scoped Classical in +theorem old_boundary (i : slots x ⊕ slots y) : + f.old p (boundaryEnd H i) = p.toSeating.ends (boundaryEnd G i) := by + have hi : boundaryEnd H i = C.original (boundaryEnd G i) := by cases i <;> rfl + rw [hi, old, orig] + +omit [Field F] in +open scoped Classical in +theorem either (j : G.End) : (∃ i, j = boundaryEnd G i) ∨ (∃ e b, j = tip G e b) := by + rcases j with (i|e)|(i|e) + · exact .inl ⟨.inl i, rfl⟩ + · exact .inr ⟨e, false, rfl⟩ + · exact .inl ⟨.inr i, rfl⟩ + · exact .inr ⟨e, true, rfl⟩ + +open scoped Classical in +theorem contacts (hd : p.Directed) {q q' : (H).End} (h : f.mark p q = f.mark p q') : + (opposite H q).map (f.mark p) = (opposite H q').map (f.mark p) := by + obtain ⟨hv, hb, hs⟩ := f.equal_mark p h + have ne (i : slots x ⊕ slots y) (e : C.Edge) (b : Bool) : + (f.old p (boundaryEnd H i)).1 ≠ (f.old p (tip H e b)).1 := by + rw [old_boundary, old_tip] + intro he + have hh := (p.no_peer _).mpr ⟨i, rfl⟩ + rw [he, p.wirePin_peer] at hh + cases hh + rcases either q with ⟨i, rfl⟩ | ⟨e, b, rfl⟩ <;> rcases either q' with ⟨j, rfl⟩ | ⟨d, c, rfl⟩ + · cases i <;> cases j <;> rfl + · exact (ne _ _ _ hs).elim + · exact (ne _ _ _ hs.symm).elim + · rw [side_tip, side_tip] at hb + subst c + rw [station_tip, station_tip] at hv + obtain ⟨hx, hy⟩ := f.other p b hd hv hs + simp only [opposite_tip, Option.map_some, mark, lane, station_tip, side_tip e (!b), + side_tip d (!b), hx, hy] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Chain.Frame +end + +/- +# Merging stations in different suffix blocks + +No edge joins different blocks. When the original board has no loops +every wire therefore survives the merge, including each newly attached +boundary wire. Pruning a neutral scalar needs no correction. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram +open Finset + +variable {F X : Type} [Field F] [Fintype X] {a b : Wire} + {G : Diagram F a b} {f : G.V → X} + +open scoped Classical in +/-- The condition `∀ i, f (G.source i) ≠ f (G.target i)` on the specified data. -/ +def Separated (G : Diagram F a b) (f : G.V → X) := + ∀ i, f (G.source i) ≠ f (G.target i) + +namespace Separated +variable (h : G.Separated f) + +open scoped Classical in +/-- Reindexes `G.E` and `G.Between f where toFun i` by an equivalence. -/ +abbrev edges : G.E ≃ G.Between f where + toFun i := ⟨i, h i⟩ + invFun := Subtype.val + left_inv _ := rfl + right_inv _ := rfl + +open scoped Classical in +/-- Reindexes `G.End` and `(G.coarsen f).End` by an equivalence. -/ +abbrev ends : G.End ≃ (G.coarsen f).End := + ((Equiv.refl _).sumCongr h.edges).sumCongr ((Equiv.refl _).sumCongr h.edges) + +open scoped Classical in +theorem station (t : G.End) : (G.coarsen f).station (h.ends t) = f (G.station t) := by + rcases t with (_|_)|(_|_) <;> rfl + +omit [Field F] [Fintype X] in +open scoped Classical in +private theorem lift {Y : Type} (t : Y ⊕ G.Between f → Bool) (w : (G.partition f).Inside) : + (G.partition f).lift t w = t ∘ Sum.map id h.edges := by + funext i + rcases i with i|i + · rfl + have he : (G.partition f).edges.symm i = .inl (h.edges i) := + (G.partition f).edges.symm_apply_eq.mpr rfl + change Sum.elim (t ∘ .inr) _ ((G.partition f).edges.symm i) = _ + rw [he] + rfl + +open scoped Classical in +theorem weight (q : X) (w : (G.coarsen f).End → Bool) : + (G.coarsen f).weight q (w ∘ .inl) (w ∘ .inr) = + ∏ v : {v // f v = q}, G.weight v (w ∘ h.ends ∘ .inl) (w ∘ h.ends ∘ .inr) := by + let _ : IsEmpty ((G.partition f).hidden q) := ⟨fun i => h i.val.val i.val.property⟩ + rw [Clustering.weight_collapse, Fintype.sum_unique] + simp only [h.lift] + rfl + +include h in +open scoped Classical in +theorem zero (v : G.V) (hv : (G.coarsen f).arity (f v) = 0) : G.arity v = 0 := by + by_contra! hn + have hdeg : 0 < Fintype.card {q : G.End // G.station q = v} := by rw [G.degree v]; omega + obtain ⟨q, hq⟩ := Classical.choice (Fintype.card_pos_iff.mp hdeg) + have hc : 0 < Fintype.card {z // (G.coarsen f).station z = f v} := + Fintype.card_pos_iff.mpr ⟨⟨h.ends q, by rw [h.station, hq]⟩⟩ + rw [(G.coarsen f).degree (f v), hv] at hc + exact lt_irrefl _ hc + +include h in +open scoped Classical in +theorem prune_eval (neutral : ∀ v, G.arity v = 0 → ∀ t, Transcript.sample (G.table v) t = 1) : + (G.coarsen f).prune.eval = G.eval := by + let K := G.coarsen f + have hz (q : X) (hq : ¬ 0 < K.arity q) (u : Val a) (v : Val b) (z : K.E → Bool) : + K.vertex u v z q = 1 := by + let w : K.End → Bool := Sum.elim (Sum.elim (bits a u) z) (Sum.elim (bits b v) z) + change (G.coarsen f).weight q (w ∘ .inl) (w ∘ .inr) = 1 + rw [h.weight] + refine prod_eq_one fun i _ => ?_ + have he : G.arity i = 0 := h.zero i (i.2.symm ▸ Nat.eq_zero_of_not_pos hq) + exact neutral i he (fun j => w (h.ends (G.portEquiv ⟨i.val, j⟩))) + refine Eq.trans ?_ (G.eval_coarsen f) + funext u v + change K.prune.eval u v = K.eval u v + unfold eval + apply sum_congr rfl + intro z _ + rw [← Fintype.prod_subtype_mul_prod_subtype (fun v => 0 < K.arity v) (K.vertex u v z)] + rw [show (∏ q : {q // ¬0 < K.arity q}, K.vertex u v z q) = 1 from + prod_eq_one fun q _ => hz _ q.2 _ _ _, mul_one] + rfl + +end Separated +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- +# Local choice of bins + +Each colony uses only its own suffix-indexed charge vector. +Padding empty suffixes by zero preserves the quadratic estimate. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Cells +open Finset Packing + +variable {D T : ℕ} {U X Y : Type} [Fintype U] [Fintype X] [Fintype Y] + +open scoped Classical in +theorem per_cell (l : U → ℝ) (hD : 0 < D) (hl : ∀ u, 0 ≤ l u) + (hm : ∑ u, l u ≤ (D : ℝ) * T) : + ∃ b : U → Fin D, ∑ i, (push b l i) ^ 2 ≤ (∑ u, (l u) ^ 2) + 2 * T*∑ u, l u := by + obtain ⟨b, hb⟩ := bins (fun _ : U => ()) l D T hD hl (by simpa [push] using hm) + refine ⟨b, ?_⟩ + have eq (i : Fin D) : push (fun x => ((), b x)) l ((), i) = push b l i := by + apply sum_congr rfl + intro j _ + by_cases h : b j = i <;> simp [h] + rw [Fintype.sum_prod_type] at hb + simpa only [Fintype.sum_unique, eq] using hb + +open scoped Classical in +/-- Returns `(per_cell l hD h.1 h.2).choose` when `h : (∀ u, 0 ≤ l u) ∧ (∑ u, l u) ≤ (D : ℝ) * +T` holds, and `fun _ => ⟨0, hD⟩` otherwise. -/ +def chooseBin (D T : ℕ) (hD : 0 < D) (l : U → ℝ) : U → Fin D := + if h : (∀ u, 0 ≤ l u) ∧ (∑ u, l u) ≤ (D : ℝ) * T + then (per_cell l hD h.1 h.2).choose else fun _ => ⟨0, hD⟩ + +omit [Fintype Y] in +open scoped Classical in +private theorem push_column (b : X → U → Y) (l : X × U → ℝ) (x : X) (i : Y) : + push (fun p : X × U => (p.1, b p.1 p.2)) l (x, i) = push (b x) (fun u => l (x, u)) i := by + unfold push + rw [Fintype.sum_prod_type, sum_eq_single x] + · simp + · intro y _ hy; simp [hy] + · simp + +open scoped Classical in +private theorem squares (f : X → Y) (l : X → ℝ) (hf : Function.Injective f) : + (∑ y, (push f l y) ^ 2) = ∑ x, (l x) ^ 2 := by + rw [← sum_push f (fun x => (l x) ^ 2)] + apply sum_congr rfl + intro y _ + by_cases h : y ∈ Set.range f + · obtain ⟨x, rfl⟩ := h + simp [push, hf.eq_iff] + · have hn : ∀ x, f x ≠ y := fun x he => h ⟨x, he⟩ + simp [push, hn] + +variable {F : Type} {x y : Wire} {h a g : ℕ} {L θ : ℝ} {P : Board F x y h} + (C : Cells P a g D T L) (row : P.diagram.V → U) + +open scoped Classical in +/-- The indexed operation `push (fun i => (C.cell i, row i)) P.charge (c, u)`. -/ +def column (c : C.A) (u : U) := push (fun i => (C.cell i, row i)) P.charge (c, u) +open scoped Classical in +/-- Computes the bin by the application `chooseBin D T hD (C.column row (C.cell v)) (row v)`. -/ +def bin (hD : 0 < D) (v : P.diagram.V) := chooseBin D T hD (C.column row (C.cell v)) (row v) + +open scoped Classical in +theorem bin_sq (hD : 0 < D) (hr : Function.Injective (fun i => (C.cell i, row i))) + (h₁ : ∑ v, P.charge v ≤ L) (h₂ : ∑ v, P.charge v ^ 2 ≤ L * T) : + ∑ z, (push (C.pack (C.bin row hD)) P.charge z) ^ 2 ≤ 3 * L * T := by + let f := fun v => (C.cell v, row v) + let l := push f P.charge + let b := fun c => chooseBin D T hD (C.column row c) + have hb (c : C.A) : ∑ i, (push (b c) (C.column row c) i) ^ 2 ≤ + (∑ u, (l (c, u)) ^ 2) + 2 * T*∑ u, l (c, u) := by + have hp u := push_nonneg f P.charge P.charge_nonneg (c, u) + have hm : (∑ u, l (c, u)) ≤ (D : ℝ) * T := by + rw [← push_fst, show l = push f P.charge from rfl, push_comp] + exact C.mass c + have h : (∀ u, 0 ≤ C.column row c u) ∧ (∑ u, C.column row c u) ≤ (D : ℝ) * T := ⟨hp, hm⟩ + simp only [b, chooseBin, dite_eq_left h] + exact (per_cell _ hD h.1 h.2).choose_spec + let merge := fun p : C.A × U => (p.1, b p.1 p.2) + change (∑ z, (push (merge ∘ f) P.charge z) ^ 2) ≤ _ + simp only [← push_comp, Fintype.sum_prod_type, merge, push_column] + refine (sum_le_sum (fun c _ => hb c)).trans ?_ + simp only [sum_add_distrib, ← mul_sum] + rw [← Fintype.sum_prod_type (fun p => (l p) ^ 2), ← Fintype.sum_prod_type l] + unfold l + rw [squares f P.charge hr, sum_push] + linarith only [h₂, mul_le_mul_of_nonneg_left h₁ (Nat.cast_nonneg (α := ℝ) T)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Cells +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Travel.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Travel.lean new file mode 100644 index 0000000000..0ee6d7e891 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Restore/Travel.lean @@ -0,0 +1,935 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.RestoreCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Spans +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Bins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress + +/-! # A single path through the full and short trees of a tether -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Tether.Plan +open Finset + +variable {V G I : Type} {r s w : ℕ} {sw : Detour.Switch (End V r s) w} + (P : Plan sw G I) + +open scoped Classical in +/-- The quantity computed by `Detour.steps w + Nat.clog 2 s`. -/ +abbrev length (w s : ℕ) := Detour.steps w + Nat.clog 2 s + +open scoped Classical in +/-- Returns `(P.group i, sw.path (P.ok i) k)` when `k < Detour.steps w` holds, and `P.climb (k - +Detour.steps w) i` otherwise. -/ +def walk (i : I) (k : ℕ) := + if k < Detour.steps w then (P.group i, sw.path (P.ok i) k) + else P.climb (k - Detour.steps w) i + +open scoped Classical in +theorem low (i : I) {k : ℕ} (h : k ≤ Detour.steps w) : + P.walk i k = (P.group i, sw.path (P.ok i) k) := by + unfold walk + rcases h.eq_or_lt with rfl|hk + · simp [climb] + · exact ite_eq_left hk + +open scoped Classical in +theorem high (i : I) (k : ℕ) : P.walk i (Detour.steps w + k) = P.climb k i := by + simp [walk] + +open scoped Classical in +@[simp] theorem walk_first (i : I) : P.walk i 0 = P.terminal i := by + rw [low _ _ (Nat.zero_le _), Detour.Switch.path_zero]; rfl + +open scoped Classical in +@[simp] theorem walk_last (i : I) : P.walk i (length w s) = P.frozen i := by + unfold length + rw [high, climb, Tree.climb_top]; rfl + +open scoped Classical in +theorem walk_step (i : I) (k : Fin (length w s)) : + (P.walk i k.val, P.walk i (k.val + 1)) = + P.supply ((finSumFinEquiv.symm k).map (fun t => (t, i)) (fun t => (t, i))) := by + obtain ⟨t, rfl⟩ := finSumFinEquiv.surjective k + rw [Equiv.symm_apply_apply] + rcases t with t|t + · change (P.walk i t.val, P.walk i (t.val + 1)) = P.cold (t, i) + rw [low _ _ t.isLt.le, low _ _ t.isLt]; rfl + · change (P.walk i (Detour.steps w + t.val), P.walk i (Detour.steps w + t.val + 1)) = P.hot (t, i) + rw [Nat.add_assoc, high, high]; rfl + +open scoped Classical in +theorem walk_simple (i : I) {k l : ℕ} (hk : k ≤ length w s) (hl : l ≤ length w s) + (he : P.walk i k = P.walk i l) : k = l := by + have cold {j q : ℕ} (hj : j ≤ Detour.steps w) (hq : q ≤ Detour.steps w) + (h : P.walk i j = P.walk i q) : j = q := by + rw [low _ _ hj, low _ _ hq] at h + have e := (Prod.mk.inj h).2 + apply sw.path_inj _ hj hq _ e + have ho := congrArg Detour.owner e + rw [sw.path_owner, sw.path_owner] at ho + cases a : Detour.Switch.side w j <;> cases b : Detour.Switch.side w q <;> simp_all + have tip {j q : ℕ} (hj : j < Detour.steps w) (hq : Detour.steps w ≤ q) + (h : P.walk i j = P.walk i q) : False := by + have ho := congrArg (fun t => Detour.owner t.2) h + simp only [walk, ite_eq_left hj, ite_eq_right hq.not_gt, climb, sw.path_owner] at ho + cases e : Detour.Switch.side w j + · simp [e, Detour.owner] at ho + · have hu : P.walk i q = P.walk i (Detour.steps w) := by + rw [walk, ite_eq_right hq.not_gt, low _ _ le_rfl, sw.path_last] + unfold climb + have ht : (Sum.inr (P.src i, Tree.tip (P.pin i)) : End V r s) = + .inr (P.src i, Tree.climb (P.pin i) (q - Detour.steps w)) := by + simpa [e, Detour.owner] using ho + rw [ht] + exact hj.ne (cold hj.le le_rfl (h.trans hu)) + by_cases a : k < Detour.steps w <;> by_cases b : l < Detour.steps w + · exact cold a.le b.le he + · exact (tip a (by omega) he).elim + · exact (tip b (by omega) he.symm).elim + · simp only [walk, ite_eq_right a, ite_eq_right b, climb, Prod.mk.injEq, Sum.inl.injEq, + Sum.inr.injEq, true_and] at he + unfold length at hk hl + have eq := congrArg Fin.val (Tree.climb_injective (P.pin i) + (a₁ := ⟨k - Detour.steps w, by omega⟩) (a₂ := ⟨l - Detour.steps w, by omega⟩) he) + change k - Detour.steps w = l - Detour.steps w at eq + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Tether.Plan +end + +/- +# The directed layout of the restored network + +Input tethers run from core to border and output tethers run in +reverse. This preserves direction at every surviving port. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet.Restore +open Assembly.Restore Finset + +variable {F T : Type} [Fintype T] {a b x y : Wire} {h u D r s : ℕ} + {L : Fringe x y T} {G : HostNet F L h u} (A : G.Restore D r s) + (B : Border F T a b x y) (he : L.tensor = B.tensor) + +local notation "H" => B.attach G.diagram +local notation "n" => Tether.Plan.length (Tether.width D r s) s + +open scoped Classical in +theorem length_pos : 0 < n := by unfold Tether.Plan.length Detour.steps; omega + +open scoped Classical in +/-- The quantity computed by `A.plan.walk i (if i.isRight then n - j else j)`. -/ +def travel (i : slots x ⊕ slots y) (j : ℕ) := + A.plan.walk i (if i.isRight then n - j else j) + +open scoped Classical in +theorem travel_start (i : slots x ⊕ slots y) (he : L.tensor = B.tensor) : + A.travel i 0 = A.owner ((H).source (.inr i)) := by + cases i with + | inl i => exact A.plan.walk_first _ + | inr j => + change A.plan.walk (.inr j) n = A.toFrozen (B.tensor (.inr j)) + rw [Tether.Plan.walk_last, A.frozen_eq, he] + +open scoped Classical in +theorem travel_last (i : slots x ⊕ slots y) (he : L.tensor = B.tensor) : + A.travel i n = A.owner ((H).target (.inr i)) := by + cases i with + | inl i => + change A.plan.walk (.inl i) n = A.toFrozen (B.tensor (.inl i)) + rw [Tether.Plan.walk_last, A.frozen_eq, he] + | inr j => + change A.plan.walk (.inr j) (n - n) = A.plan.terminal (.inr j) + rw [Nat.sub_self, Tether.Plan.walk_first] + +open scoped Classical in +/-- Builds `Chain H (Cell h × A.Space) where owner` with the specified `owner`, `turns`, `node`. -/ +def route : Chain H (Cell h × A.Space) where + owner := A.owner + turns := Sum.elim (fun _ => 0) (fun _ => n - 1) + node := Sum.elim (fun e i => if i = 0 then (A.oldCore e).1 else (A.oldCore e).2) A.travel + start + | .inl _ => rfl + | .inr i => A.travel_start B i he + finish + | .inl _ => rfl + | .inr i => by + change A.travel i (n - 1 + 1) = _ + rw [Nat.sub_add_cancel length_pos] + exact A.travel_last B i he + +local notation "C" => A.route B he + +open scoped Classical in +/-- Reindexes `Fin (n - 1 + 1)` and `Fin n` by an equivalence. -/ +def index (i : slots x ⊕ slots y) : Fin (n - 1 + 1) ≃ Fin n := + (finCongr (Nat.sub_add_cancel length_pos)).trans (if i.isRight then Fin.revPerm else .refl _) + +open scoped Classical in +/-- In the case `⟨.inl e, _⟩`, this construction gives `.inr e`. -/ +def into : (C).Edge → A.Wires + | ⟨.inl e, _⟩ => .inr e + | ⟨.inr i, j⟩ => + .inl ((finSumFinEquiv.symm (index i j)).map (fun k => (k, i)) (fun k => (k, i))) + +open scoped Classical in +/-- In the case `.inr e`, this construction gives `⟨.inl e, ⟨0, Nat.zero_lt_succ _⟩⟩`. -/ +def pick : A.Wires → (C).Edge + | .inr e => ⟨.inl e, ⟨0, Nat.zero_lt_succ _⟩⟩ + | .inl (.inl (j, i)) => ⟨.inr i, (index i).symm (finSumFinEquiv (.inl j))⟩ + | .inl (.inr (j, i)) => ⟨.inr i, (index i).symm (finSumFinEquiv (.inr j))⟩ + +open scoped Classical in +/-- Reindexes `(C).Edge` and `A.Wires where toFun` by an equivalence. -/ +def arrows : (C).Edge ≃ A.Wires where + toFun := A.into B he + invFun := A.pick B he + left_inv := by + rintro ⟨e|i, j⟩ + · have hz : (j : Fin 1) = 0 := Fin.eq_zero j + cases hz; rfl + · obtain ⟨k, hk⟩ := ((index (D := D) (r := r) (s := s) i).symm).surjective j + subst j + obtain ⟨k, rfl⟩ := finSumFinEquiv.surjective k + cases k <;> simp [pick, into] + right_inv := by rintro ((⟨k, i⟩|⟨k, i⟩)|e) <;> simp [pick, into] + +open scoped Classical in +theorem links (e : (C).Edge) : + ((C).src (.inr e), (C).dst (.inr e)) = A.supply (A.arrows B he e) ∨ + ((C).src (.inr e), (C).dst (.inr e)) = (A.supply (A.arrows B he e)).swap := by + rcases e with ⟨e|i, k⟩ + · have hz : (k : Fin 1) = 0 := Fin.eq_zero k + cases hz; exact .inl rfl + · let j : Fin n := index i k + let g := A.plan.supply ((finSumFinEquiv.symm j).map (fun k => (k, i)) (fun k => (k, i))) + have eq : g = (A.plan.walk i j.val, A.plan.walk i (j.val + 1)) := (A.plan.walk_step i j).symm + change (A.travel i k.val, A.travel i (k.val + 1)) = g ∨ + (A.travel i k.val, A.travel i (k.val + 1)) = g.swap + rw [eq] + cases i with + | inl i => exact .inl rfl + | inr i => + right + have hk : k.val < n - 1 + 1 := k.isLt + have hp : 0 < n := length_pos + have eqj : j.val = n - (k.val + 1) := rfl + change (A.plan.walk _ (n - k.val), A.plan.walk _ (n - (k.val + 1))) = + (A.plan.walk _ (j.val + 1), A.plan.walk _ j.val) + rw [eqj, show n - (k.val + 1) + 1 = n - k.val by omega] + +open scoped Classical in +theorem simple (hc : ∀ e, (A.oldCore e).1 ≠ (A.oldCore e).2) + {e : (H).E} {i j : ℕ} (hi : i ≤ (C).turns e + 1) (hj : j ≤ (C).turns e + 1) + (hij : (C).node e i = (C).node e j) : i = j := by + cases e with + | inl e => + change i ≤ 1 at hi + change j ≤ 1 at hj + interval_cases i <;> interval_cases j <;> first | rfl | exact (hc e hij).elim | exact (hc e + hij.symm).elim + | inr t => + change i ≤ n - 1 + 1 at hi + change j ≤ n - 1 + 1 at hj + rw [Nat.sub_add_cancel length_pos] at hi hj + change A.travel t i = A.travel t j at hij + unfold travel at hij + split_ifs at hij + · have := A.plan.walk_simple t (Nat.sub_le _ _) (Nat.sub_le _ _) hij + omega + · exact A.plan.walk_simple t hi hj hij + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet.Restore +end + +/- # All charge estimates for the directed restoration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet.Restore +open Assembly.Restore Finset + +variable {F T : Type} [Field F] [Fintype T] {a b x y : Wire} {h u D r s : ℕ} + {L : Fringe x y T} {G : HostNet F L h u} (A : G.Restore D r s) + (B : Border F T a b x y) (he : L.tensor = B.tensor) + (cap : ∀ t, ((B.attach G.diagram).arity (.inr t) : ℝ) ≤ L.charge t) + +local notation "H" => B.attach G.diagram +local notation "C" => A.route B he + +open scoped Classical in +theorem route_support (e : (C).graph.E) : + ((C).graph.target e).1 = ((C).graph.source e).1 ∧ + ((C).graph.target e).2 ∈ A.adj ((C).graph.source e).2 := by + let P (z : (Cell h × A.Space) × (Cell h × A.Space)) := + z.2.1 = z.1.1 ∧ z.2.2 ∈ A.adj z.1.2 + change P ((C).src (.inr e), (C).dst (.inr e)) + have l := A.support (A.arrows B he e) + rcases A.links B he e with hh|hh <;> rw [hh] + · exact ⟨l.1.symm, l.2⟩ + · exact ⟨l.1, Tether.adj_symm _ _ G.cs _ _ l.2⟩ + +open scoped Classical in +theorem route_loopless (hl : ∀ e, G.src e ≠ G.dst e) (e : (C).graph.E) : + (C).graph.source e ≠ (C).graph.target e := by + have hc (e : G.diagram.E) : (A.oldCore e).1 ≠ (A.oldCore e).2 := by + intro hp + have h := A.core_injective hp + rw [G.units.left, G.units.right] at h + exact hl _ (congrArg Prod.fst h) + intro hh + exact Nat.ne_of_lt (Nat.lt_succ_self _) (A.simple B he hc e.2.isLt.le e.2.isLt hh) + +open scoped Classical in +theorem route_arity (v : Cell h × A.Space) : + (C).graph.arity v = exterior H A.owner v + Packing.degree A.supply v := by + let pair := fun e : (C).Edge => ((C).src (.inr e), (C).dst (.inr e)) + have eq : Packing.degree pair v = Packing.degree A.supply v := by + simp only [degree_sum] + apply Fintype.sum_equiv (A.arrows B he) + intro e + unfold pair + rcases A.links B he e with he|he <;> rw [he] + exact Nat.add_comm _ _ + have push_id {X : Type} [Fintype X] (l : X → ℝ) (x : X) : push id l x = l x := by simp [push] + have hh := site_arity (C).graph id v + rw [push_id] at hh + change ((C).graph.arity v : ℝ) = (exterior H A.owner v : ℝ) + Packing.degree pair v at hh + rw [eq] at hh + exact_mod_cast hh + +open scoped Classical in +/-- Builds `Rounds.Board F a b h where V` with the specified `diagram`, `place`, `one`, `adj`. -/ +abbrev board : Rounds.Board F a b h where + V := A.Space + diagram := (C).graph + place := Prod.swap + one := Prod.swap_injective + adj := A.adj + sym := Tether.adj_symm A.sw G.C G.cs + edge := A.route_support B he + charge := A.charge + cover v := by + rw [A.route_arity B he, Nat.cast_add] + exact add_le_add_left (A.exterior_covers B cap v) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet.Restore +end + +/- # Anchors of the core, contact trees and splitting trees -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet.Restore +open Assembly.Restore + +variable {F T : Type} [Fintype T] {a b x y : Wire} {h u D r s : ℕ} + {L : Fringe x y T} {G : HostNet F L h u} (A : G.Restore D r s) + (B : Border F T a b x y) (he : L.tensor = B.tensor) + +local notation "H" => B.attach G.diagram +local notation "C" => A.route B he + +open scoped Classical in +/-- The indexed operation `(v.1, (Detour.owner v.2).elim Tether.core (fun p => Tether.member +p.1))`. -/ +def root (v : Cell h × A.Space) : Cell h × A.Space := + (v.1, (Detour.owner v.2).elim Tether.core (fun p => Tether.member p.1)) + +omit [Fintype T] in +open scoped Classical in +theorem root_owner (v : G.diagram.V ⊕ T) : A.root (A.owner v) = A.owner v := by cases v <;> rfl + +omit [Fintype T] in +open scoped Classical in +theorem owner_inj (hp : Function.Injective G.units.place) : Function.Injective A.owner := by + rintro (v|t) (w|z) e + · exact congrArg Sum.inl (hp (A.core_injective e)) + · cases (congrArg Prod.snd e) + · cases (congrArg Prod.snd e) + · exact congrArg Sum.inr (A.frozen_injective e) + +omit [Fintype T] in +open scoped Classical in +theorem root_walk (i : slots x ⊕ slots y) (k : ℕ) : + A.root (A.plan.walk i k) = A.plan.terminal i ∨ A.root (A.plan.walk i k) = A.plan.frozen i := by + unfold Tether.Plan.walk + split + · unfold root + simp only [Detour.Switch.path_owner] + split <;> first | exact .inl rfl | exact .inr rfl + · exact .inr rfl + +omit [Fintype T] in +open scoped Classical in +theorem travel_eq {i j : slots x ⊕ slots y} (hi : i.isRight = j.isRight) + (hc : portEnd G.diagram i = portEnd G.diagram j) (ht : L.tensor i = L.tensor j) : + A.travel i = A.travel j := by + have hf : G.far i = G.far j := congrArg G.units.place hc + have hp := (A.outlet i j ht).mpr hf + funext k + simp only [travel, hi, Tether.Plan.walk, Tether.Plan.climb, plan, ht, hf, hp] + +open scoped Classical in +theorem agree (e e' : (H).E) (hv : (H).source e = (H).source e') + (hw : (H).target e = (H).target e') : + (C).turns e = (C).turns e' ∧ (C).node e = (C).node e' := by + rcases e with e|i|j <;> rcases e' with e'|i'|j' <;> + try first + | exact (Sum.inl_ne_inr hv).elim + | exact (Sum.inr_ne_inl hv).elim + | exact (Sum.inl_ne_inr hw).elim + | exact (Sum.inr_ne_inl hw).elim + · have es : G.diagram.source e = G.diagram.source e' := Sum.inl.inj hv + have et : G.diagram.target e = G.diagram.target e' := Sum.inl.inj hw + exact ⟨rfl, by simp [route, oldCore, es, et]⟩ + · refine ⟨rfl, A.travel_eq (i := .inl i) (j := .inl i') rfl (Sum.inl.inj hv) ?_⟩ + rw [he]; exact Sum.inr.inj hw + · refine ⟨rfl, A.travel_eq (i := .inr j) (j := .inr j') rfl (Sum.inl.inj hw) ?_⟩ + rw [he]; exact Sum.inr.inj hv + +open scoped Classical in +/-- Builds `(C).Frame where root` with the specified `root`, `one`, `fix`, `agrees`. -/ +def frame (hp : Function.Injective G.units.place) (hl : ∀ e, G.src e ≠ G.dst e) : (C).Frame where + root := A.root + one := A.owner_inj hp + fix := A.root_owner + agrees := A.agree B he + simple := by + intro e i j hi hj hij + refine A.simple B he ?_ hi hj hij + intro e he + have hh := A.core_injective he + rw [G.units.left, G.units.right] at hh + exact hl _ (congrArg Prod.fst hh) + atJoint := by + rintro ⟨e|q, j⟩ + · exact Fin.elim0 j + · let k := if q.isRight then Tether.Plan.length (Tether.width D r s) s - (j.val + 1) else j.val + + 1 + have ht := A.root_walk q k + rw [A.frozen_eq, he] at ht + cases q + · exact ht + · exact ht.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet.Restore +end + +/- +# Local names for the tether switch + +A location splits into its old host and a suffix of bounded size. +Number the switch pins using the channel leading to the remote host +and its suffix. No ordering of the long host addresses is involved. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Packing Coloring Finset +open History.Reset + +open scoped Classical in +/-- The full chart of type `Chart G.N D.scheme.d` for the given inputs. -/ +def Template.Encodes.fullChart {F T : Type} [Field F] [Fintype T] {x y : Wire} + {L : Fringe x y T} {u : ℕ} {D : Template F} {G : HostNet F L D.scheme.h u} + {r : D.format.obj} (p : D.Encodes r G) (full : D.full = true) : Chart G.N D.scheme.d := + chart p.post.nav fun v w he => by + have hm : w ∈ D.adj G v := by simpa [Template.adj, full] using he + obtain ⟨i, hi, _⟩ := (p.edge v w).mp hm + exact ⟨i, p.post.host.injective ((p.host_nav v i).trans hi)⟩ + +namespace Restore +variable {V V' : Type} {r s w d m D : ℕ} + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `(v, .inl ())`. -/ +def ends : Tether.End V r s ≃ V × Tether.End Unit r s where + toFun + | .inl v => (v, .inl ()) + | .inr ((v, i), p) => (v, .inr (((), i), p)) + invFun + | (v, .inl _) => .inl v + | (v, .inr ((_, i), p)) => .inr ((v, i), p) + left_inv := by rintro (v|⟨⟨v, i⟩, p⟩) <;> rfl + right_inv := by rintro ⟨v, _|⟨⟨_, i⟩, p⟩⟩ <;> rfl + +open scoped Classical in +/-- In the case `.inl x`, this construction gives `((ends x).1, .inl (ends x).2)`. -/ +def cells : Tether.Host V r s w ≃ V × Tether.Host Unit r s w where + toFun + | .inl x => ((ends x).1, .inl (ends x).2) + | .inr (x, i) => ((ends x).1, .inr ((ends x).2, i)) + invFun + | (v, .inl x) => .inl (ends.symm (v, x)) + | (v, .inr (x, i)) => .inr (ends.symm (v, x), i) + left_inv := by rintro (x|⟨x, i⟩) <;> simp + right_inv := by rintro ⟨v, x|⟨x, i⟩⟩ <;> simp + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def bits (r s w : ℕ) := Nat.clog 2 (Fintype.card (Tether.Host Unit r s w)) + +open scoped Classical in +/-- Embeds `Tether.Host Unit r s w` into `B (bits r s w)`. -/ +def suffix (r s w : ℕ) : Tether.Host Unit r s w ↪ B (bits r s w) := + Classical.choice (Function.Embedding.nonempty_of_card_le (by + rw [Fintype.card_fin]; exact Nat.le_pow_clog (by decide) _)) + +open scoped Classical in +/-- Computes the host by the application `cells.toEmbedding.trans ((e.prodMap (suffix r s +w)).trans (Match.rowIndex _ _).symm.toEmbedding)`. -/ +def host (e : V ↪ B m) (r s w : ℕ) : Tether.Host V r s w ↪ B (m + bits r s w) := + cells.toEmbedding.trans ((e.prodMap (suffix r s w)).trans (Match.rowIndex _ _).symm.toEmbedding) + +open scoped Classical in +theorem host_parts (e : V ↪ B m) (x : Tether.Host V r s w) : + Match.rowIndex _ _ (host e r s w x) = (e (cells x).1, suffix r s w (cells x).2) := + (Match.rowIndex _ _).apply_symm_apply _ + +open scoped Classical in +theorem near_iff (N : V → Finset V) (x y : Tether.End V r s) : + y ∈ Tether.near N r s x ↔ (ends y).1 ∈ N (ends x).1 ∧ (ends y).2.isLeft ≠ (ends x).2.isLeft + := by + rcases x with v | ⟨⟨v, i⟩, k⟩ <;> rcases y with u | ⟨⟨u, j⟩, l⟩ <;> simp [Tether.near, ends] + +variable {N : V → Finset V} (H : Chart N d) + +open scoped Classical in +/-- Embeds `↥(Tether.near N r s x)` into `Option (B d) × Tether.End Unit r s where toFun y`. -/ +def pinKey (x : Tether.End V r s) : + ↥(Tether.near N r s x) ↪ Option (B d) × Tether.End Unit r s where + toFun y := (H.label (ends x).1 (ends y.val).1, (ends y.val).2) + inj' p q eq := by + obtain ⟨hl, hp⟩ := Prod.mk.inj eq + exact Subtype.ext (ends.injective (Prod.ext (H.inj _ (mem_insert_of_mem ((near_iff ..).mp + p.property).1) + (mem_insert_of_mem ((near_iff ..).mp q.property).1) hl) hp)) + +open scoped Classical in +/-- Computes the pins by the application `rank (pinKey H x) (by simpa using Tether.near_card N D +hd x)`. -/ +def pins (hd : ∀ v, (N v).card ≤ D) (x : Tether.End V r s) : + ↥(Tether.near N r s x) ↪ Fin (Tether.width D r s) := + rank (pinKey H x) (by simpa using Tether.near_card N D hd x) + +variable {N' : V' → Finset V'} (K : Chart N' d) + {x : Tether.End V r s} {x' : Tether.End V' r s} + +open scoped Classical in +private theorem pin_maps (hs : H.Maps K (ends x).1 (ends x').1) (he : (ends x).2 = (ends x').2) + (y : ↥(Tether.near N r s x)) : + ∃ y' : ↥(Tether.near N' r s x'), pinKey H x y = pinKey K x' y' := by + obtain ⟨hy, hc⟩ := (near_iff ..).mp y.property + obtain ⟨v, hv, hk⟩ := hs _ hy + let z := ends.symm (v, (ends y.val).2) + have hz : ends z = (v, (ends y.val).2) := ends.apply_symm_apply _ + refine ⟨⟨z, (near_iff ..).mpr ?_⟩, ?_⟩ + · rw [hz, ←he]; exact ⟨hv, hc⟩ + · change (_, _) = (K.label _ (ends z).1, (ends z).2) + rw [hz, hk] + +open scoped Classical in +theorem pins_eq (hd : ∀ v, (N v).card ≤ D) (hd' : ∀ v, (N' v).card ≤ D) + (hs : H.Maps K (ends x).1 (ends x').1) (hs' : K.Maps H (ends x').1 (ends x).1) + (he : (ends x).2 = (ends x').2) + (y : ↥(Tether.near N r s x)) (y' : ↥(Tether.near N' r s x')) + (hk : pinKey H x y = pinKey K x' y') : pins H hd x y = pins K hd' x' y' := + rank_eq (pin_maps H K hs he) (pin_maps K H hs' he.symm) hk + +end Restore +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Transport of restored adjacency between matching neighborhoods -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Packing Coloring History.Reset Finset + +variable {V V' : Type} {r s d D : ℕ} {N : V → Finset V} +local notation "W" => Tether.width D r s + +open scoped Classical in +/-- Uses `⟨Tether.near N r s, Tether.near_symm N hn, pins H hd⟩` as the representation. -/ +def sw (H : Chart N d) (hn : ∀ v u, u ∈ N v → v ∈ N u) (hd : ∀ v, (N v).card ≤ D) : + Detour.Switch (Tether.End V r s) W := + ⟨Tether.near N r s, Tether.near_symm N hn, pins H hd⟩ + +open scoped Classical in +theorem sw_eq {F T : Type} {a b : Wire} {h u : ℕ} {L : Fringe a b T} + {G : HostNet F L h u} (H : Chart G.N d) (A : G.Restore D r s) (hpin : A.pins + = pins H A.degree) : + A.sw = sw H G.ns A.degree := by + unfold HostNet.Restore.sw sw + rw [hpin] + +variable [Fintype V] (C : V → Finset V) (q : Detour.Switch (Tether.End V r s) (Tether.width D r s)) + +open scoped Classical in +private def branch : Tether.End V r s → Tether.End V r s → Prop + | .inl v, .inl w => w ∈ C v + | .inr (i, p), .inr (j, t) => i = j ∧ t ∈ Tree.adj p + | _, _ => False + +open scoped Classical in +private def linked : Tether.Host V r s W → Tether.Host V r s W → Prop + | .inl x, .inl y => branch C x y + | .inl x, .inr (y, t) => x = y ∧ t = Tree.root W + | .inr (x, p), .inl y => x = y ∧ p = Tree.root W + | .inr (x, p), .inr (y, t) => (x = y ∧ t ∈ Tree.adj p) ∨ ∃ h : y ∈ q.near x, + Tree.tip (q.pin x ⟨y, h⟩) = p ∧ Tree.tip (q.pin y ⟨x, q.sym _ _ h⟩) = t + +open scoped Classical in +private theorem linked_iff (x y : Tether.Host V r s W) : + y ∈ Tether.adj q C x ↔ linked C q x y := by + rcases x with x | ⟨x, p⟩ <;> rcases y with y | ⟨y, t⟩ + · rcases x with x | ⟨x, i⟩ <;> rcases y with y | ⟨y, j⟩ <;> + simp [Tether.adj, Tether.branches, Detour.Switch.adj, linked, branch, and_comm, eq_comm] + · simp [Tether.adj, linked, eq_comm] + · by_cases hp : p = Tree.root W <;> simp [Tether.adj, Detour.Switch.adj, hp, linked, eq_comm] + · let _ : DecidableEq (Tether.End V r s) := Classical.decEq _ + have member : (y, t) ∈ q.links x p ↔ + ∃ h : y ∈ q.near x, + Tree.tip (q.pin x ⟨y, h⟩) = p ∧ Tree.tip (q.pin y ⟨x, q.sym _ _ h⟩) = t := by + simp only [Detour.Switch.links, mem_filter, mem_univ, true_and] + have inside : (Sum.inr (y, t) : Tether.Host V r s W) ∈ + (Tree.adj p).image (fun node => Sum.inr (x, node)) ↔ x = y ∧ t ∈ Tree.adj p := by + constructor + · rintro hy + rcases mem_image.mp hy with ⟨z, hz, h⟩ + obtain ⟨he, rfl⟩ := Prod.mk.inj (Sum.inr.inj h) + exact ⟨he, hz⟩ + · rintro ⟨rfl, ht⟩ + exact mem_image_of_mem _ ht + have outside : (Sum.inr (y, t) : Tether.Host V r s W) ∈ (q.links x p).image Sum.inr ↔ + (y, t) ∈ q.links x p := by + constructor + · intro hy + rcases mem_image.mp hy with ⟨z, hz, he⟩ + exact Sum.inr.inj he ▸ hz + · exact mem_image_of_mem _ + simp only [Tether.adj, Detour.Switch.adj, mem_union, Finset.notMem_empty, or_false, linked] + split_ifs + · simp only [mem_singleton, Sum.inr_ne_inl, or_false] + exact inside.or (outside.trans member) + · simp only [Finset.notMem_empty, or_false] + exact inside.or (outside.trans member) + +variable {C} (H : Chart N d) (hn : ∀ v u, u ∈ N v → v ∈ N u) (hd : ∀ v, (N v).card ≤ D) + +open scoped Classical in +/-- All restored neighbors project to the previous closed one-neighborhood. -/ +theorem project (hc : ∀ v, C v ⊆ N v) {x y : Tether.Host V r s W} + (h : y ∈ Tether.adj (sw H hn hd) C x) : + (cells y).1 ∈ insert (cells x).1 (N (cells x).1) := by + rw [linked_iff] at h + rcases x with x|⟨x, p⟩ <;> rcases y with y|⟨y, t⟩ + · rcases x with v|⟨⟨v, i⟩, p⟩ <;> rcases y with u|⟨⟨u, j⟩, t⟩ + · exact mem_insert_of_mem (hc v h) + · exact h.elim + · exact h.elim + · exact mem_insert.mpr (.inl (congrArg (fun z : V × Fin r => z.1) h.1.symm)) + · rw [h.1]; exact mem_insert_self _ _ + · rw [h.1]; exact mem_insert_self _ _ + · rcases h with ⟨rfl, _⟩|⟨hy, _⟩ + · exact mem_insert_self _ _ + · exact mem_insert_of_mem ((near_iff N x y).mp hy).1 + +variable [Fintype V'] {N' C' : V' → Finset V'} (K : Chart N' d) + (hn' : ∀ v u, u ∈ N' v → v ∈ N' u) (hd' : ∀ v, (N' v).card ≤ D) + +open scoped Classical in +/-- The data for the local pair construction, including `same`, `full`, `label`, `forth`, +`back`. -/ +structure LocalPair (v u : V) (v' u' : V') : Prop where + same : v = u ↔ v' = u' + full : u ∈ N v ↔ u' ∈ N' v' + label : H.label v u = K.label v' u' + forth : H.Maps K v v' + back : K.Maps H v' v + +omit [Fintype V] [Fintype V'] in +open scoped Classical in +theorem LocalPair.pin {v u : V} {v' u' : V'} (h : LocalPair H K v u v' u') + (x y : Tether.End Unit r s) + (e : ends.symm (u, y) ∈ Tether.near N r s (ends.symm (v, x))) + (e' : ends.symm (u', y) ∈ Tether.near N' r s (ends.symm (v', x))) : + pins H hd _ ⟨_, e⟩ = pins K hd' _ ⟨_, e'⟩ := by + apply pins_eq + · simpa using h.forth + · simpa using h.back + · simp + · change (H.label _ _, _) = (K.label _ _, _) + simp [h.label] + +open scoped Classical in +theorem links_eq {v u : V} {v' u' : V'} (h : LocalPair H K v u v' u') + (h' : LocalPair H K u v u' v') (hc : u ∈ C v ↔ u' ∈ C' v') + (x y : Tether.Host Unit r s W) : + cells.symm (u, y) ∈ Tether.adj (sw H hn hd) C (cells.symm (v, x)) ↔ + cells.symm (u', y) ∈ Tether.adj (sw K hn' hd') C' (cells.symm (v', x)) := by + have heq (i j : Tether.End Unit r s) : + ends.symm (v, i) = ends.symm (u, j) ↔ ends.symm (v', i) = ends.symm (u', j) := by + simp [h.same] + rw [linked_iff, linked_iff] + rcases x with x|⟨x, p⟩ <;> rcases y with y|⟨y, t⟩ + · rcases x with _|⟨⟨_, i⟩, p⟩ <;> rcases y with _|⟨⟨_, j⟩, t⟩ <;> + simp [cells, ends, linked, branch, h.same, hc] + · exact and_congr (heq x y) Iff.rfl + · exact and_congr (heq x y) Iff.rfl + · refine or_congr (and_congr (heq x y) Iff.rfl) ?_ + have hm : ends.symm (u, y) ∈ Tether.near N r s (ends.symm (v, x)) ↔ + ends.symm (u', y) ∈ Tether.near N' r s (ends.symm (v', x)) := by simp [near_iff, h.full] + constructor + · rintro ⟨e, l, r⟩ + refine ⟨hm.mp e, ?_, ?_⟩ + · exact (congrArg Tree.tip (h.pin H hd K hd' x y e _)).symm.trans l + · exact (congrArg Tree.tip (h'.pin H hd K hd' y x _ _)).symm.trans r + · rintro ⟨e, l, r⟩ + refine ⟨hm.mpr e, ?_, ?_⟩ + · exact (congrArg Tree.tip (h.pin H hd K hd' x y _ e)).trans l + · exact (congrArg Tree.tip (h'.pin H hd K hd' y x _ _)).trans r + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # The base and short address of a moving tether -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Packing History.Reset + +variable {V I U : Type} {r s w : ℕ} {q : Detour.Switch (Tether.End V r s) w} + (P : Tether.Plan q U I) + +private def front (i : I) := q.pin (.inl (P.dst i)) ⟨_, P.ok i⟩ +/-- The value specified by `q.pin (.inr (P.src i, Tree.tip (P.pin i))) ⟨_, q.sym _ _ (P.ok i)⟩`. -/ +def back (i : I) := q.pin (.inr (P.src i, Tree.tip (P.pin i))) ⟨_, q.sym _ _ (P.ok i)⟩ + +private def arm (x : Tether.End V r s) (p : Fin w) (k : ℕ) : Tether.Host V r s w := + if k ≤ Nat.clog 2 w then .inr (x, Tree.climb p k) else .inl x + +private theorem arm_cells (x : Tether.End V r s) (p : Fin w) (k : ℕ) : + cells (arm x p k) = ((ends x).1, arm (ends x).2 p k) := by + unfold arm + split_ifs <;> rfl + +private def position (j : Fin r) (x : Fin s) (p p' : Fin w) (k : ℕ) : + Tether.Host Unit r s w := + if k ≤ Nat.clog 2 w + 1 then arm (.inl ()) p (Nat.clog 2 w + 1 - k) + else if k < Detour.steps w then arm (.inr (((), j), Tree.tip x)) p' (k - (Nat.clog 2 w + 2)) + else .inl (.inr (((), j), Tree.climb x (k - Detour.steps w))) + +private theorem split_walk (i : I) (k : ℕ) : + cells (P.walk i k).2 = + ((if k ≤ Nat.clog 2 w + 1 then P.dst i else (P.src i).1), + position (P.src i).2 (P.pin i) (front P i) (back P i) k) := by + have hc : q.path (P.ok i) k = + if k ≤ Nat.clog 2 w + 1 then arm (.inl (P.dst i)) (front P i) (Nat.clog 2 w + 1 - k) + else arm (.inr (P.src i, Tree.tip (P.pin i))) (back P i) (k - (Nat.clog 2 w + 2)) := rfl + unfold Tether.Plan.walk position + by_cases h : k < Detour.steps w + · simp only [ite_eq_left h, hc] + split_ifs <;> rw [arm_cells] <;> rfl + · have hn : ¬k ≤ Nat.clog 2 w + 1 := by unfold Detour.steps at h; omega + simp only [ite_eq_right h, ite_eq_right hn] + rfl + +variable {F T F' T' : Type} {a b a' b' : Wire} {h u h' u' D d : ℕ} + {L : Fringe a b T} {L' : Fringe a' b' T'} + {G : HostNet F L h u} {G' : HostNet F' L' h' u'} + (A : G.Restore D r s) (A' : G'.Restore D r s) +local notation "W" => Tether.width D r s + +theorem travel_base (i : slots a ⊕ slots b) (k : ℕ) : + (cells (A.travel i k).2).1 = + if (if i.isRight then Tether.Plan.length W s - k else k) ≤ Nat.clog 2 W + 1 + then A.plan.dst i else (A.plan.src i).1 := by + unfold HostNet.Restore.travel + rw [split_walk] + +theorem travel_suffix (H : Chart G.N d) (H' : Chart G'.N d) + (pin : A.pins = pins H A.degree) (pin' : A'.pins = pins H' A'.degree) + (i : slots a ⊕ slots b) (j : slots a' ⊕ slots b') + (forward : LocalPair H H' (A.plan.dst i) (A.plan.src i).1 (A'.plan.dst j) (A'.plan.src j).1) + (reverse : LocalPair H H' (A.plan.src i).1 (A.plan.dst i) (A'.plan.src j).1 (A'.plan.dst j)) + (hs : (A.plan.src i).2 = (A'.plan.src j).2) (hp : A.pin i = A'.pin j) + (hi : i.isRight = j.isRight) (k : ℕ) : + (cells (A.travel i k).2).2 = (cells (A'.travel j k).2).2 := by + let x : Tether.End Unit r s := .inl () + let y : Tether.End Unit r s := .inr (((), (A.plan.src i).2), Tree.tip (A.pin i)) + have yh : ends.symm ((A'.plan.src j).1, y) = .inr (A'.plan.src j, Tree.tip (A'.pin j)) := by + unfold y + rw [hs, hp] + rfl + have e : ends.symm ((A.plan.src i).1, y) ∈ Tether.near G.N r s (ends.symm (A.plan.dst i, x)) + := A.plan.ok i + have e' : ends.symm ((A'.plan.src j).1, y) ∈ Tether.near G'.N r s (ends.symm (A'.plan.dst j, x)) + := by + rw [yh]; exact A'.plan.ok j + have hf := forward.pin H A.degree H' A'.degree x y e e' + have hb := reverse.pin H A.degree H' A'.degree y x (Tether.near_symm _ G.ns _ _ e) + (Tether.near_symm _ G'.ns _ _ e') + simp only [← pin, ← pin', yh] at hf hb + change front A.plan i = front A'.plan j at hf + have hb : back A.plan i = back A'.plan j := by + let z : Tether.End G'.V r s := .inl (A'.plan.dst j) + have aux (a b : Tether.End G'.V r s) (h : a = b) + (e : z ∈ Tether.near G'.N r s a) (e' : z ∈ Tether.near G'.N r s b) : + A'.pins a ⟨z, e⟩ = A'.pins b ⟨z, e'⟩ := by subst b; rfl + exact hb.trans (aux _ _ yh _ _) + have out : A.plan.pin i = A'.plan.pin j := hp + simp only [HostNet.Restore.travel, split_walk, hi, hs, hf, hb, out] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- +# Reading the full neighborhood from two-step walks + +Equality of addresses is needed only once per host. The block +records see the resulting bits and the short edge masks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Packing History.Reset + +open scoped Classical in +/-- The quantity computed by `(d + 1) * 2`. -/ +abbrev radius (d : ℕ) := (d + 1) * 2 +open scoped Classical in +/-- Computes the equalities by the application `Format.vec (radius d) (.vec (radius d) .bit)`. -/ +abbrev Equalities (d : ℕ) := Format.vec (radius d) (.vec (radius d) .bit) +open scoped Classical in +/-- Computes the preview by the application `Format.pair (Equalities d) (.vec (radius d) +(Group.Flags d))`. -/ +abbrev Preview (d : ℕ) := Format.pair (Equalities d) (.vec (radius d) (Group.Flags d)) + +variable {F : Type} {D : Template F} +local notation "d" => D.scheme.d + +open scoped Classical in +/-- The preview of type `(Preview D.scheme.d).obj`, constructed using `Neighborhood.walks 2 +(D.nav r) v`. -/ +def preview (D : Template F) (r : D.format.obj) (v : B D.scheme.m) : (Preview D.scheme.d).obj := + let walk := Neighborhood.walks 2 (D.nav r) v + (fun i j => decide (walk i = walk j), fun i => D.flags r (walk i)) + +open scoped Classical in +/-- Computes the step by the application `j.elim v (f v)`. -/ +def step {V : Type} {n : ℕ} (f : V → B n → V) (v : V) (j : Option (B n)) := j.elim v (f v) + +open scoped Classical in +/-- The value specified by `(Neighborhood.path_surjective n 2 (i, j, ())).choose`. -/ +def address {n : ℕ} (i j : Option (B n)) : B (radius n) := + (Neighborhood.path_surjective n 2 (i, j, ())).choose + +variable [Field F] {T T' : Type} [Fintype T] [Fintype T'] {x y x' y' : Wire} {u u' : ℕ} + {L : Fringe x y T} {L' : Fringe x' y' T'} {r r' : D.format.obj} + {G : HostNet F L D.scheme.h u} {G' : HostNet F L' D.scheme.h u'} + (p : D.Encodes r G) (p' : D.Encodes r' G') (v : G.V) (v' : G'.V) + +open scoped Classical in +/-- Computes the hop by the application `step p.post.nav v`. -/ +def hop := step p.post.nav v + +open scoped Classical in +theorem follows (i j : Option (B d)) : + Neighborhood.walks 2 (D.nav r) (p.post.host v) (address i j) = + p.post.host (hop p (hop p v i) j) := by + have ht : Neighborhood.path d 2 (address i j) = (i, j, ()) := + (Neighborhood.path_surjective d 2 (i, j, ())).choose_spec + unfold Neighborhood.walks + rw [ht] + cases i <;> cases j <;> simp [Neighborhood.run, hop, step, p.host_nav] + +open scoped Classical in +/-- The data for the agree construction, including `names`, `flags`. -/ +structure Agree : Prop where + names : ∀ i j k l, hop p (hop p v i) j = hop p (hop p v k) l ↔ + hop p' (hop p' v' i) j = hop p' (hop p' v' k) l + flags : ∀ i, D.flags r (p.post.host (hop p v i)) = D.flags r' (p'.post.host (hop p' v' i)) + +open scoped Classical in +theorem agree (h : preview D r (p.post.host v) = preview D r' (p'.post.host v')) : + Agree p p' v v' := by + constructor + · intro i j k l + have he := congrArg (fun t => t.1 (address i j) (address k l)) h + simpa only [preview, follows, decide_eq_decide, p.post.host.injective.eq_iff, + p'.post.host.injective.eq_iff] using he + · intro i + have he := congrArg (fun t => t.2 (address i none)) h + simp only [preview, follows] at he + exact he + +variable {p p' v v'} (h : Agree p p' v v') + +include h in +open scoped Classical in +theorem Agree.symm : Agree p' p v' v := ⟨fun i j k l => (h.names i j k l).symm, fun i + => (h.flags i).symm⟩ + +variable (full : D.full = true) + +include full in +open scoped Classical in +private theorem links (p : D.Encodes r G) (v w : G.V) : + w ∈ G.N v ↔ ∃ j, p.post.nav v j = w ∧ (D.flags r (p.post.host v) j).1 = true := by + have hh := p.edge v w + simp only [Template.adj, full, ite_true, ← p.host_nav, p.post.host.injective.eq_iff] at hh + exact hh + +include h in +open scoped Classical in +theorem Agree.code (i j l : Option (B d)) : + (p.fullChart full).label (hop p v i) (hop p (hop p v j) l) = + (p'.fullChart full).label (hop p' v' i) (hop p' (hop p' v' j) l) := + label_eq (h.names i none j l) (fun z => h.names i (some z) j l) + +include h full in +open scoped Classical in +theorem Agree.edge (i j l : Option (B d)) : + hop p (hop p v j) l ∈ G.N (hop p v i) ↔ hop p' (hop p' v' j) l ∈ G'.N (hop p' v' i) := by + rw [links full p, links full p', h.flags i] + exact exists_congr fun k => and_congr_left' (h.names i (some k) j l) + +include h in +open scoped Classical in +theorem Agree.maps (i : Option (B d)) : + (p.fullChart full).Maps (p'.fullChart full) (hop p v i) (hop p' v' i) := by + intro t ht + obtain ⟨j, rfl, _⟩ := (links full p _ _).mp ht + exact ⟨_, (h.edge full i i (some j)).mp ht, h.code full i i (some j)⟩ + +include h in +open scoped Classical in +theorem Agree.pair (i j : Option (B d)) : + LocalPair (p.fullChart full) (p'.fullChart full) (hop p v i) (hop p v j) (hop p' v' i) (hop p' + v' j) := + ⟨h.names i none j none, h.edge full i j none, h.code full i j none, h.maps full i, + h.symm.maps full i⟩ + +include h in +open scoped Classical in +theorem Agree.core (i j : Option (B d)) : + hop p v j ∈ G.C (hop p v i) ↔ hop p' v' j ∈ G'.C (hop p' v' i) := by + rw [p.core, p'.core, h.flags i] + apply exists_congr + intro k + rw [← p.host_nav, ← p'.host_nav, p.post.host.injective.eq_iff, p'.post.host.injective.eq_iff] + exact and_congr_left' (h.names i (some k) j none) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/RetagStore.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/RetagStore.lean new file mode 100644 index 0000000000..abbd88ae1f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/RetagStore.lean @@ -0,0 +1,953 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.ChannelPlan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Ranks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Add +public import Mathlib.Algebra.Group.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Keys +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal + +/-! # Pinning the unused suffix of each payload slot -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload + +open Coloring Transcript + +variable {m V k : ℕ} (p : Payload m V k) + +open scoped Classical in +/-- The quantity computed by `Fmt.pi (fun _ : Slot (2 ^ m) V k => Format.addr (k + 1))`. -/ +abbrev Lengths (m V k : ℕ) := Fmt.pi (fun _ : Slot (2 ^ m) V k => Format.addr (k + 1)) + +open scoped Classical in +/-- The value specified by `(p.seat.read s).elim 0 p.length`. -/ +def used (s : Slot (2 ^ m) V k) := (p.seat.read s).elim 0 p.length + +open scoped Classical in +/-- In the case `none`, this construction gives `exact Nat.two_pow_pos _`. -/ +def lengths : (Lengths m V k).obj := fun s => ⟨p.used s, by + unfold used + cases p.seat.read s with + | none => exact Nat.two_pow_pos _ + | some i => + change p.length i < 2 ^ (k + 1) + rw [pow_succ] + have := Nat.two_pow_pos k + have := p.longest i + omega⟩ + +open scoped Classical in +/-- Tests whether `(x i.1).val ≤ i.2.val` holds. -/ +def mask (x : (Lengths m V k).obj) (i : Fmt.Port m V k) := decide ((x i.1).val ≤ i.2.val) + +open scoped Classical in +theorem occupied (i : Fmt.Port m V k) : i ∈ Set.range p.wire ↔ i.2.val < p.used i.1 := by + constructor + · rintro ⟨⟨a, b⟩, rfl⟩ + change b.val < p.used (p.seat.write a) + rw [used, (p.seat.valid _ _).mpr rfl] + exact b.isLt + · rcases i with ⟨i, b⟩ + intro hi + change b.val < (p.seat.read i).elim 0 p.length at hi + cases h : p.seat.read i with + | none => simp [h] at hi + | some a => + have ha := (p.seat.valid _ _).mp h + subst i + rw [h] at hi + exact ⟨⟨a, b.val, hi⟩, rfl⟩ + +open scoped Classical in +theorem mask_eq (i : Fmt.Port m V k) : mask p.lengths i = decide (i ∉ Set.range p.wire) := by + apply Bool.eq_iff_iff.mpr + simp only [mask, lengths, decide_eq_true_eq, occupied, not_lt] + exact decide_eq_true_iff + +variable {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} + +open scoped Classical in +private theorem threshold (j w : ℕ) : + Circuit F (.addr w) (Fmt.raw (B j)) (fun x i => decide (x.val ≤ i.val)) (2000 * 2 ^ j * (w + + 1)) := by + have h := Install.BNet.share j _ fun i => Control.threshold_one F w i.val + apply (h.rename (.refl _) (Equiv.prodUnique _ Unit)).mono + rw [MatrixExponent.card_slots, wd_word] + ring_nf + omega + +open scoped Classical in +theorem mask_net (hu : 3 ≤ u) : Map F u L (Lengths m V k) (Fmt.payload m V k) mask + (8000 * (k + 2) * (Fmt.payload m V k).width) := by + let A := fun s : Slot (2 ^ m) V k => Fmt.raw (B s.1.val) + have h (s : Slot (2 ^ m) V k) : Map F u L (.addr (k + 1)) (A s) + (fun x i => decide (x.val ≤ i.val)) (8000 * (k + 2) * capacity s) := by + refine (Map.circuit hu (threshold s.1.val (k + 1))).mono ?_ + unfold capacity + exact le_of_eq (by ring) + have t := Map.family h + have eq : (∑ s : Slot (2 ^ m) V k, 8000 * (k + 2) * capacity s) = + 8000 * (k + 2) * (Fmt.payload m V k).width := by + simp only [Fmt.payload, Format.width, Fintype.card_sigma, Fintype.card_fin, Finset.mul_sum] + rw [eq] at t + intro a b i j + obtain ⟨v, hv, t⟩ := t a b i j + refine ⟨v, hv, ?_⟩ + convert t using 1 + funext x y + dsimp only + congr 1 + apply propext + constructor + · intro he + funext s i + exact congrFun he ⟨s, i⟩ + · intro he + funext ⟨s, i⟩ + exact congrFun (congrFun he s) i + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload +end + +section +/- Circuit for gathering a packet from span metadata. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +open Coloring +noncomputable section + +variable (F : Type) [Field F] {j h k t : ℕ} + +private theorem span_bound (hk : 3 * k ≤ t) : (span k).width ≤ 2 ^ 0 * (100 + t) ^ 1 := by + simp [span] + omega + +private theorem fixed (hk : 3 * k ≤ t) (a : B k) : + Cheap F 0 t (span k) (.addr k) (fun _ => a) 2 := + Cheap.const F (span_bound hk) (by simp; omega) _ + +private theorem cheap_key (hk : 3 * k ≤ t) : Cheap F 0 t (span k) (.addr k) key 12 := by + have h : k ≤ t := by omega + have x := Cheap.id F (span_bound hk) + have lt := (x.fst.pair x.snd.fst).comp (cheap_compare F h) + have choose := ((x.fst.pair (fixed F hk ⊤)).pair lt).comp ((cheap_select F k).widen h) + convert choose.mono (d := 12) (by decide) using 1 + funext v + by_cases he : v.1 < v.2.1 <;> simp [key, he] + +theorem cheap_add (h : k ≤ t) : Cheap F 0 t (.pair (.addr k) (.addr k)) (.addr k) (fun x => x.1 + + x.2) 4 := by + refine ⟨_, numeric_add F k, ?_⟩ + simp only [Format.width_pair, Format.width_addr] + ring_nf + omega + +private theorem cheap_get (q pad : B k) (hk : 3 * k + ≤ t) : Cheap F 0 t (span k) (.addr k) (get q pad) 16 := by + have h : k ≤ t := by omega + have hadd := cheap_add F h + have v := Cheap.id F (span_bound hk) + have query := fixed F hk q + have default := fixed F hk pad + have lower := (query.pair v.fst).comp (cheap_compare F h) + have upper := (query.pair v.snd.fst).comp (cheap_compare F h) + have index := (query.pair v.snd.snd).comp hadd + have sel := (cheap_select F k).widen h + have ptr := ((index.pair default).pair upper).comp sel + have done := ((default.pair ptr).pair lower).comp sel + convert done.mono (d := 16) (by decide) using 1 + funext v + by_cases h₁ : q < v.1 <;> by_cases h₂ : q < v.2.1 <;> simp [get, h₁, h₂] + +private theorem cheap_packed (q : B h → B k) (pad : B k) (hk : h + 3 * k ≤ t) : + Cheap F h t (.vec h (span k)) (Col h k) (packed q pad) 60 := by + have hs : 3 * k ≤ t := by omega + have hw : (span k).width ≤ t := by simp [span]; omega + have hb := vec_bound h (show (span k).width ≤ 100 + t by omega) + have keys := Cheap.map _ (fun _ : B h => cheap_key F hs) + have mask := Cheap.const F hb (vec_bound (A := .bit) (t := t) h (by simp; omega)) (fun _ => true) + have perm := (keys.pair mask).comp ((cheap_permutation F h k).widen (show h + k ≤ t by omega)) + have read := Cheap.lookup F h t (span k) (by omega) hw + have sorted := ((Cheap.id F hb).pair perm).comp read + have which := (sorted.comp keys).comp (cheap_seek F q (show h + k ≤ t by omega)) + have answer := ((sorted.pair which).comp read).comp (Cheap.map _ (fun b + => cheap_get F (q b) pad hs)) + exact answer.mono (by decide) + +/-- The two vector heights are independent of the pointer width. +Padding reads existing rows repeatedly, so it never introduces new +intervals into a query. -/ +theorem cheap (query : B h → B k) (pad : B k) : + Cheap F (max j h) (max j h + 3 * k) (.vec j (span k)) (.vec h (.addr k)) (eval query pad) 100 + := by + let n := max j h + let t := n + 3 * k + have width (A : Format) (ha : A.width ≤ t) (l : ℕ) (hl : l ≤ n) : + (Format.vec l A).width ≤ 2 ^ n * (100 + t) ^ 1 := + (vec_bound l (ha.trans (Nat.le_add_left _ _))).trans + (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) hl)) + have hs : (span k).width ≤ t := by simp [span, t]; omega + have hk : (Format.addr k).width ≤ t := by simp [t]; omega + have hj : j ≤ n := le_max_left _ _ + have hh : h ≤ n := le_max_right _ _ + have prep : Cheap F n t (.vec j (span k)) (.vec n (span k)) (fun x => x ∘ shrink j) 2 := + Cheap.project F (width _ hs _ hj) (width _ hs _ le_rfl) (fun a => (shrink j a.1, a.2)) + (fun _ _ => rfl) + have out : Cheap F n t (Col n k) (Col h k) (fun x => x ∘ extend hh) 2 := + Cheap.project F (width _ hk _ le_rfl) (width _ hk _ hh) (fun a => (extend hh a.1, a.2)) + (fun _ _ => rfl) + exact ((prep.comp (cheap_packed F (query ∘ shrink h) pad le_rfl)).comp out).mono (by decide) + +end +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +end + +section +/- Pointers from channel starts, span lengths and local bank addresses. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +open Coloring +noncomputable section +variable {j h k t : ℕ} + +/-- Metadata is (channel start, length, bank start). -/ +def encode (r : (span k).obj) : (span k).obj := (r.1, r.1 + r.2.1, r.2.2 - r.1) + +/-- The value specified by `eval query pad (encode ∘ x)`. -/ +def pointers (query : B h → B k) (pad : B k) (x : B j → (span k).obj) := + eval query pad (encode ∘ x) + +/-- The quantity computed by `v.1.val ≤ i ∧ i < v.1.val + v.2.1.val`. -/ +def covers (v : (span k).obj) (i : ℕ) := v.1.val ≤ i ∧ i < v.1.val + v.2.1.val + +theorem contains_encode (v : (span k).obj) (b : B k) (h : v.1.val + v.2.1.val < 2 ^ k) : + contains (encode v) b ↔ covers v b.val := by + simp only [contains, encode, covers, Fin.le_def, Fin.lt_def, Fin.val_add, Nat.mod_eq_of_lt h] + +theorem pointers_at (query : B h → B k) (pad : B k) (x : B j → (span k).obj) + (hx : ∀ i, (x i).1.val + (x i).2.1.val < 2 ^ k) (b : B h) (i : B j) + (hc : covers (x i) (query b).val) + (hu : ∀ u v, covers (x i) v → covers (x u) v → u = i) : + pointers query pad x b = (x i).2.2 + (query b - (x i).1) := by + unfold pointers + rw [eval_at query pad _ b i ((contains_encode _ _ (hx i)).mpr hc) (fun u v hi hj => by + rw [hu _ _ ((contains_encode _ _ (hx i)).mp hi) ((contains_encode _ _ (hx u)).mp hj)])] + change query b + ((x i).2.2 - (x i).1) = _ + abel + +theorem pointers_pad (query : B h → B k) (pad : B k) (x : B j → (span k).obj) + (hx : ∀ i, (x i).1.val + (x i).2.1.val < 2 ^ k) (b : B h) + (hc : ∀ i, ¬ covers (x i) (query b).val) : pointers query pad x b = pad := + eval_pad query pad _ b (fun i hi => hc i ((contains_encode _ _ (hx i)).mp hi)) + +variable (F : Type) [Field F] + +private abbrev Pair (k : ℕ) := Format.pair (.addr k) (.addr k) + +/-- After k doublings the coefficient 2^k vanishes modulo 2^k. -/ +theorem cheap_neg (k : ℕ) : Cheap F 0 k (.addr k) (.addr k) Neg.neg 16 := by + let step (x : (Pair k).obj) := (x.1, x.2 + x.2 + x.1) + have he (n : ℕ) (x : B k) : step^[n] (x, 0) = (x, (2 ^ n : ℕ) • x - x) := by + induction n with + | zero => simp + | succ n ih => + rw [Function.iterate_succ_apply', ih, pow_succ, mul_nsmul, two_nsmul] + unfold step + congr 1 + dsimp only + abel + have hp : (Pair k).width ≤ 2 ^ 0 * (100 + k) ^ 2 := by simp [Pair]; ring_nf; omega + have ha : (Format.addr k).width ≤ 2 ^ 0 * (100 + k) ^ 1 := by simp + have x := Cheap.id F hp + have sum := cheap_add F (k := k) le_rfl + have db := (x.snd.pair x.snd).comp sum + have it : Cheap F 0 k (Pair k) (Pair k) step 10 := + (x.fst.pair ((db.pair x.fst).comp sum)).mono (by decide) + have init := (Cheap.id F ha).pair (Cheap.const F ha ha 0) + have run := (init.comp (it.iterate le_rfl)).snd + convert run.mono (d := 16) (by decide) using 1 + funext x + have hz : (2 ^ k : ℕ) • x = 0 := by simpa using (card_nsmul_eq_zero (x := x)) + change -x = (step^[k] (x, 0)).2 + rw [he, hz, zero_sub] + +theorem cheap_encode (hk : 3 * k ≤ t) : Cheap F 0 t (span k) (span k) encode 24 := by + have hv : (span k).width ≤ 2 ^ 0 * (100 + t) ^ 1 := by simp [span]; omega + have x := Cheap.id F hv + have h : k ≤ t := by omega + have dest := (x.fst.pair x.snd.fst).comp (cheap_add F h) + have neg := x.fst.comp ((cheap_neg F k).widen h) + have bias := (x.snd.snd.pair neg).comp (cheap_add F h) + convert (x.fst.pair (dest.pair bias)).mono (d := 24) (by decide) using 1 + funext v + simp [encode, sub_eq_add_neg] + +theorem cheap_pointers (query : B h → B k) (pad : B k) : + Cheap F (max j h) (max j h + 3 * k) (.vec j (span k)) (.vec h (.addr k)) (pointers query pad) + 101 := by + let t := max j h + 3 * k + have he : Cheap F (max j h) t (.vec j (span k)) (.vec j (span k)) (fun x => encode ∘ x) 24 := by + obtain ⟨m, hm, hb⟩ := Cheap.map _ fun _ : B j => cheap_encode F (show 3 * k ≤ t by omega) + exact ⟨m, hm, hb.trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (le_max_left _ + _)))⟩ + exact he.comp (cheap F query pad) + +end +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Intervals +end + +/- A sparse edge list determines the global peer permutation. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +namespace Peers + +variable {p q : ℕ} + +/-- Computes the row by the application `Format.pair .bit (.pair (.addr q) (.addr q))`. -/ +abbrev row (q : ℕ) := Format.pair .bit (.pair (.addr q) (.addr q)) + +/-- The value specified by `(v.2.1, if v.1 then 1 else 0, v.2.2)`. -/ +def interval (v : (row q).obj) : (Intervals.span q).obj := + (v.2.1, if v.1 then 1 else 0, v.2.2) + +/-- The eval of type `B q`, constructed using `Intervals.pointers id ⊤ (interval ∘ x) i`. -/ +def eval (x : B p → (row q).obj) (i : B q) : B q := + let j := Intervals.pointers id ⊤ (interval ∘ x) i + if j < ⊤ then j else i + +private theorem one_val {v : B q} (h : v < ⊤) : (1 : B q).val = 1 := by + change (1 : ℕ) % 2 ^ q = 1 + apply Nat.mod_eq_of_lt + have h₁ := (⊤ : B q).isLt + change v.val < (⊤ : B q).val at h + omega + +theorem eval_eq (x : B p → (row q).obj) (f : B q → B q) + (h : ∀ j, (x j).1 = true → (x j).2.1 < ⊤ ∧ (x j).2.2 < ⊤ ∧ f (x j).2.1 = (x j).2.2) + (ha : ∀ i, f i ≠ i → ∃ j, (x j).1 = true ∧ (x j).2.1 = i) : eval x = f := by + let y := interval ∘ x + have fits (j : B p) : (y j).1.val + (y j).2.1.val < 2 ^ q := by + by_cases hj : (x j).1 = true + · have hlt := (h j hj).1 + simp only [y, Function.comp_apply, interval, ite_eq_left hj, one_val hlt] + exact (Nat.succ_le_of_lt hlt).trans_lt (⊤ : B q).isLt + · simp [y, interval, hj] + have hit (j : B p) (i : B q) : + Intervals.contains (Intervals.encode (y j)) i ↔ (x j).1 = true ∧ (x j).2.1 = i := by + rw [Intervals.contains_encode _ _ (fits j)] + by_cases hj : (x j).1 = true + · simp only [Intervals.covers, y, Function.comp_apply, interval, hj, ↓reduceIte, + one_val (h j hj).1, + true_and, Fin.ext_iff] + omega + · simp [Intervals.covers, y, interval, hj] + funext i + change (if Intervals.pointers id ⊤ y i < ⊤ then Intervals.pointers id ⊤ y i else i) = f i + by_cases hh : ∃ j, (x j).1 = true ∧ (x j).2.1 = i + · obtain ⟨j, hj, rfl⟩ := hh + have hv := h j hj + have he : Intervals.pointers id ⊤ y (x j).2.1 = (x j).2.2 := by + unfold Intervals.pointers + rw [Intervals.eval_at _ _ _ _ j ((hit _ _).mpr ⟨hj, rfl⟩) (fun a b h₁ h₂ => by + obtain ⟨_, he⟩ := (hit j b).mp h₁ + obtain ⟨h', he'⟩ := (hit a b).mp h₂ + have heq := he'.trans he.symm + have ho := (h a h').2.2.symm.trans ((congrArg f heq).trans hv.2.2) + have e : x a = x j := Prod.ext (h'.trans hj.symm) (Prod.ext heq ho) + simp [y, e])] + change _ + ((x j).2.2 - (x j).2.1) = _ + simp + rw [he, ite_eq_left hv.2.1, hv.2.2] + · have he : Intervals.pointers id ⊤ y i = ⊤ := + Intervals.eval_pad _ _ _ _ (fun j hj => hh ⟨j, (hit _ _).mp hj⟩) + rw [he, ite_eq_right (lt_irrefl _)] + exact (not_not.mp (mt (ha i) hh)).symm + +end Peers + +namespace Bank +variable {A D : Format} {P : Bank A D} {k d : ℕ} (i : P.Level k d) + +theorem index_lt_top (v : P.Port d i.1.val) : P.index k d i v < ⊤ := by + change (Fintype.equivFin _ v).val < 2 ^ (P.count k d i) - 1 + have h := Nat.le_pow_clog (by decide : 1 < 2) (Fintype.card (P.Port d i.1.val) + 1) + exact (Fintype.equivFin _ v).isLt.trans_le (by unfold count; omega) + +namespace Links +variable (L : P.Links k d) (i : P.Level k d) + +/-- The value specified by `(true, P.index k d i (L.location i a), P.index k d i (L.location i +(L.opposite i a)))`. -/ +def peerRow (a : L.At i × Bool) : (Peers.row (P.count k d i)).obj := + (true, P.index k d i (L.location i a), P.index k d i (L.location i (L.opposite i a))) + +theorem peers_correct {p : ℕ} (x : B p → (Peers.row (P.count k d i)).obj) + (ok : ∀ j, (x j).1 = true → ∃ a, x j = L.peerRow i a) + (cover : ∀ a, ∃ j, x j = L.peerRow i a) : Peers.eval x = L.plan.control.2.1 i := by + classical + let f := P.index k d i + let g := L.location i + let t := L.opposite i + change Peers.eval x = ⇑((t.viaEmbedding g).viaEmbedding f) + apply Peers.eval_eq + · intro j hj + obtain ⟨a, he⟩ := ok j hj + rw [he] + refine ⟨index_lt_top _ _, index_lt_top _ _, ?_⟩ + change (t.viaEmbedding g).viaEmbedding f (f (g a)) = f (g (t a)) + rw [Equiv.Perm.viaEmbedding_apply, Equiv.Perm.viaEmbedding_apply] + · intro b hb + by_cases hf : b ∈ Set.range f + · obtain ⟨a, rfl⟩ := hf + by_cases hg : a ∈ Set.range g + · obtain ⟨e, rfl⟩ := hg + obtain ⟨j, hj⟩ := cover e + exact ⟨j, by rw [hj]; rfl, by rw [hj]; rfl⟩ + · exact (hb (by rw [Equiv.Perm.viaEmbedding_apply, + Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ hg])).elim + · exact (hb (Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ hf)).elim + +end Links +end Bank +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- Expand compact interval metadata only at the local channel endpoints. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Channels +open Coloring + +variable {A D : Format} (S : Channels A D) (n : S.I → ℕ) + +open scoped Classical in +/-- The indexed operation `Format.pair (Fmt.pi (fun k => Perm (S.count k))) (Fmt.raw D.pins)`. -/ +abbrev Global := Format.pair (Fmt.pi (fun k => Perm (S.count k))) (Fmt.raw D.pins) + +open scoped Classical in +/-- The indexed operation `.pair (Fmt.pi (fun i => .vec (n i) (Intervals.span (S.localWidth +i)))) S.Global`. -/ +abbrev shortControl : Format := + .pair (Fmt.pi (fun i => .vec (n i) (Intervals.span (S.localWidth i)))) S.Global + +open scoped Classical in +/-- The indexed operation `(fun i => Intervals.pointers (query i) (pad i) (x.1 i), x.2)`. -/ +def expandControl (query : ∀ i, B (S.localWidth i) → B (S.localWidth i)) + (pad : ∀ i, B (S.localWidth i)) (x : (S.shortControl n).obj) : S.control.obj := + (fun i => Intervals.pointers (query i) (pad i) (x.1 i), x.2) + +open scoped Classical in +/-- The quantity computed by `4 * (2 ^ max j k * (100 + (max j k + 3 * k)) ^ 101)`. -/ +def pointerCost (j k : ℕ) := 4 * (2 ^ max j k * (100 + (max j k + 3 * k)) ^ 101) + +open scoped Classical in +/-- The quantity computed by `(∑ i, pointerCost (n i) (S.localWidth i)) + 4 * S.Global.width`. -/ +def expandCost := (∑ i, pointerCost (n i) (S.localWidth i)) + 4 * S.Global.width + +open scoped Classical in +theorem expand_control {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + (query : ∀ i, B (S.localWidth i) → B (S.localWidth i)) (pad : ∀ i, B (S.localWidth i)) : + Map F u L (S.shortControl n) S.control (S.expandControl n query pad) (S.expandCost n) := by + have h (i : S.I) : Map F u L (.vec (n i) (Intervals.span (S.localWidth i))) (Perm (S.localWidth + i)) + (Intervals.pointers (query i) (pad i)) (pointerCost (n i) (S.localWidth i)) := by + obtain ⟨m, hm, hb⟩ := Intervals.cheap_pointers F (j := n i) (query i) (pad i) + exact (Map.circuit hu hm).mono (Nat.mul_le_mul_left _ (by omega)) + exact (Map.family h).par (Map.circuit hu (Circuit.id F S.Global)) + +open scoped Classical in +theorem expand_bound {j k : ℕ} (hj : ∀ i, n i ≤ j) (hk : ∀ i, S.localWidth i ≤ k) : + S.expandCost n ≤ 4 * ((Fintype.card S.I * 2 ^ j + ∑ i, 2 ^ S.localWidth i) * + (100 + j + 4 * k) ^ 101 + (∑ i, 2 ^ S.count i * S.count i) + D.width) := by + have hh (i : S.I) : pointerCost (n i) (S.localWidth i) ≤ + 4 * ((2 ^ j + 2 ^ S.localWidth i) * (100 + j + 4 * k) ^ 101) := by + have hu : 2 ^ max (n i) (S.localWidth i) ≤ 2 ^ j + 2 ^ S.localWidth i := by + rw [max_def] + split + · exact Nat.le_add_left _ _ + · exact (Nat.pow_le_pow_right (by decide) (hj i)).trans (Nat.le_add_right _ _) + have hx : 100 + (max (n i) (S.localWidth i) + 3 * S.localWidth i) ≤ 100 + j + 4 * k := by + have := hj i + have := hk i + omega + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul hu (Nat.pow_le_pow_left hx _)) + have ht := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hh i) + simp only [← Finset.mul_sum, ← Finset.sum_mul, Finset.sum_add_distrib, Finset.sum_const, + Finset.card_univ, smul_eq_mul] at ht + unfold expandCost + rw [show S.Global.width = (∑ i, 2 ^ S.count i * S.count i) + D.width by simp [Global]] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Channels +end + +/- +# Encoding active gathers by disjoint runs + +A run specifies its first position in the packed lane, length and +first bank address. No condition is needed on unused ports, whose +permutation is the identity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank + +open Coloring + +variable {A D : Format} {P : Bank A D} {k d : ℕ} + +open scoped Classical in +private theorem Plan.pointer_eq (p : P.Plan k d) (i : P.Level k d) (e : P.Port d i.1.val) + (b : B i.1.val) : + p.control.1 ⟨i, e.1⟩ (P.bitIndex k d ⟨i, e.1⟩ (e.2, b)) = encode (p.pointer i e b) := by + unfold Plan.control + dsimp only + rw [(P.bitIndex k d ⟨i, e.1⟩).injective.extend_apply] + +namespace Links +variable (M : P.Links k d) + +open scoped Classical in +/-- Uses `⟨i, (M.location i e).1⟩` as the representation. -/ +def vector (i : P.Level k d) (e : M.At i × Bool) : P.Endpoint k d := ⟨i, (M.location i e).1⟩ + +open scoped Classical in +/-- The value specified by `P.bitIndex k d (M.vector i e) ((M.location i e).2, b)`. -/ +def offset (i : P.Level k d) (e : M.At i × Bool) (b : B i.1.val) := + P.bitIndex k d (M.vector i e) ((M.location i e).2, b) + +open scoped Classical in +theorem offset_val (i : P.Level k d) (e : M.At i × Bool) (b : B i.1.val) : + (M.offset i e b).val = b.val + 2 ^ i.1.val * (M.location i e).2.val := rfl + +open scoped Classical in +/-- Equality of commands where they are actually read. -/ +structure Represents (q : (P.channels k d).control.obj) : Prop where + peer : q.2.1 = M.plan.control.2.1 + mask : q.2.2 = M.pad + reads : ∀ i e b, q.1 (M.vector i e) (M.offset i e b) = + encode (M.plan.pointer i (M.location i e) b) + +open scoped Classical in +private theorem Represents.atPort {q : (P.channels k d).control.obj} (hq : M.Represents q) + (i : P.Level k d) (e : M.At i × Bool) (b : B i.1.val) : + (P.channels k d).atPort q i (P.index k d i (M.location i e)) b = + (P.channels k d).atPort M.plan.control i (P.index k d i (M.location i e)) b := by + have ht : (P.channels k d).tap i (P.index k d i (M.location i e)) b = + some ⟨M.vector i e, M.offset i e b⟩ := by + unfold channels + dsimp only + exact (P.index k d i).injective.extend_apply _ _ _ + have hr : q.1 (M.vector i e) (M.offset i e b) = + M.plan.control.1 (M.vector i e) (M.offset i e b) := + (hq.reads i e b).trans (M.plan.pointer_eq i (M.location i e) b).symm + unfold Channels.atPort + rw [ht, Option.bind_some, Option.bind_some] + exact congrArg ((P.channels k d).bank (M.vector i e)) hr + +open scoped Classical in +theorem Represents.carries {q : (P.channels k d).control.obj} (hq : M.Represents q) + (x : A.obj) (y : D.obj) : (P.channels k d).Carries q x y ↔ M.Matches x y := by + let S := P.channels k d + let a := M.plan.control + have he (i : P.Level k d) (j : B (P.count k d i)) (b : B i.1.val) : + Channels.value x y (S.atPort q i j b) = Channels.value x y (S.atPort q i (a.2.1 i j) b) ↔ + Channels.value x y (S.atPort a i j b) = Channels.value x y (S.atPort a i (a.2.1 i j) b) := by + by_cases h₁ : j ∈ Set.range (P.index k d i) + swap + · rw [show a.2.1 i j = j from Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ h₁] + simp + obtain ⟨t, rfl⟩ := h₁ + rw [show a.2.1 i (P.index k d i t) = P.index k d i (M.plan.peer i t) from + Equiv.Perm.viaEmbedding_apply _ _ _] + by_cases h₂ : t ∈ Set.range (M.location i) + swap + · rw [show M.plan.peer i t = t from Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ h₂] + simp + obtain ⟨⟨e, c⟩, rfl⟩ := h₂ + rw [M.peer_at, Represents.atPort M hq i (e, c) b, Represents.atPort M hq i (e, !c) b] + rw [← M.carries] + unfold Channels.Carries + rw [hq.peer, hq.mask] + exact and_congr Iff.rfl (forall_congr' fun i => + and_congr Iff.rfl (forall_congr' fun j => forall_congr' fun b => he i j b)) + +end Links +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank +end + +/- # Expanding a description by contiguous intervals -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank +open Coloring + +variable {A D : Format} (P : Bank A D) (k d : ℕ) (n : P.Endpoint k d → ℕ) + +open scoped Classical in +/-- The indexed operation `Fmt.pi (fun i => .vec (n i) (Intervals.span (P.localWidth k d i)))`. -/ +abbrev intervals := Fmt.pi (fun i => .vec (n i) (Intervals.span (P.localWidth k d i))) + +open scoped Classical in +/-- Computes the sentinel by the application `encode none`. -/ +def sentinel (i : P.Endpoint k d) : B (P.localWidth k d i) := encode none + +variable {P k d} (M : P.Links k d) (x : (P.intervals k d n).obj) + +namespace Links + +open scoped Classical in +/-- Span starts are measured from the start of the whole packed +buffer. The first bit of lane `i` in a level-`j` buffer is at +`i*2^j`. -/ +structure Runs : Prop where + fits : ∀ i u, (x i u).1.val + (x i u).2.1.val < 2 ^ (P.localWidth k d i) + disjoint : ∀ i a b t, Intervals.covers (x i a) t → Intervals.covers (x i b) t → b = a + live : ∀ i (e : M.At i × Bool) (b : B i.1.val) (h : b.val < M.length e.1.val), + let r := M.vector i e + let t := (M.offset i e b).val + ∃ v, Intervals.covers (x r v) t ∧ + (x r v).2.2.val + (t - (x r v).1.val) = (M.pointer e.1.val e.2 ⟨b.val, h⟩).val + gap : ∀ i (e : M.At i × Bool) (b : B i.1.val), M.length e.1.val ≤ b.val → + ∀ v, ¬Intervals.covers (x (M.vector i e) v) (M.offset i e b).val + +open scoped Classical in +theorem Runs.read (h : M.Runs n x) (i : P.Level k d) (e : M.At i × Bool) (b : B i.1.val) : + Intervals.pointers id (P.sentinel k d (M.vector i e)) (x (M.vector i e)) (M.offset i e b) + = encode (M.plan.pointer i (M.location i e) b) := by + apply Fin.ext + rw [M.pointer_at] + let r := M.vector i e + let t := M.offset i e b + split + · rename_i hb + obtain ⟨v, hv, he⟩ := h.live i e b hb + have ht := Intervals.pointers_at id (P.sentinel k d r) (x r) (h.fits r) t v hv (h.disjoint r v) + change (Intervals.pointers id (P.sentinel k d r) (x r) t).val = _ + rw [ht, id_eq, Fin.val_add, Fin.sub_val_of_le (show (x r v).1 ≤ t from hv.1)] + change (x r v).2.2.val + (t.val - (x r v).1.val) = _ at he + rw [he] + exact Nat.mod_eq_of_lt ((M.pointer _ _ _).isLt.trans_le + (Nat.pow_le_pow_right (by decide) (Nat.le_succ _))) + · rename_i hb + have ht := Intervals.pointers_pad id (P.sentinel k d r) (x r) (h.fits r) t + (h.gap i e b (Nat.le_of_not_gt hb)) + exact congrArg Fin.val ht + +open scoped Classical in +theorem Runs.represents (h : M.Runs n x) : + M.Represents ((P.channels k d).expandControl n (fun _ => id) (P.sentinel k d) + (x, M.plan.control.2)) := by + refine ⟨rfl, rfl, fun i e b => ?_⟩ + exact Runs.read n M x h i e b + +end Links +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Bank +end + +/- +# Changing the station number of the exterior + +At a host, all exterior bits use a common station number. Changing +this number preserves their order by block, span and bit offset. +Thus the same physical payload can be used before and after the cut. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Coloring + +variable {F : Type} [Field F] {S U : Scheme F} {x : S.format.obj} {y : U.format.obj} + {a b : Wire} {G H : Diagram F a b} (p : S.Presentation x G) (q : U.Presentation y H) + {V k : ℕ} + +open scoped Classical in +/-- The data for the retag construction, including `m`, `owner`, `block`, `span`, `offset`. -/ +structure Retag : Prop where + m : U.m = S.m + owner : ∀ i, (U.owner y (q.boundary i)).val = (S.owner x (p.boundary i)).val + block : ∀ i, (q.boundary i).val.1.1.2.1.val = (p.boundary i).val.1.1.2.1.val + span : ∀ i, (q.boundary i).val.1.2.val = (p.boundary i).val.1.2.val + offset : ∀ i, (q.boundary i).val.2.val = (p.boundary i).val.2.val + left : ∀ i j, (p.boundary i).val.1.1.2.2 = (p.boundary j).val.1.1.2.2 + right : ∀ i j, (q.boundary i).val.1.1.2.2 = (q.boundary j).val.1.1.2.2 + +namespace Retag +variable {p q} (t : Retag p q) + +open scoped Classical in +/-- The quantity computed by `finCongr (congrArg (fun v => 2 ^ v) t.m)`. -/ +abbrev names := finCongr (congrArg (fun v => 2 ^ v) t.m) + +open scoped Classical in +theorem load (v : B U.m) : U.load y v = S.load x (names t v) := by + let e := q.boundary.symm.trans p.boundary + have same (j : U.exposed y) : U.owner y j = v ↔ S.owner x (e j) = t.names v := by + have eq := t.owner (q.boundary.symm j) + simp only [Equiv.apply_symm_apply] at eq + simp only [Fin.ext_iff] + exact iff_of_eq (congrArg (· = v.val) eq) + exact Fintype.card_congr (e.subtypeEquiv same) + +include t in +open scoped Classical in +theorem fits (h : S.Fits x V k) : U.Fits y V k := by + refine ⟨?_, fun v => (t.load v).le.trans (h.2 _)⟩ + simpa only [t.load, (t.names).sum_comp (fun v => max 1 (S.load x v))] using h.1 + +omit [Field F] in +open scoped Classical in +private theorem precedes (f : S.Fits x V k) (i j : S.exposed x) (hs : S.owner x i = S.owner x j) + (h : S.spanIndex i.val.1 < S.spanIndex j.val.1) : + (S.index x f i).2.val < (S.index x f j).2.val := by + have small (u : S.exposed x) : u.val.2.val < S.extent x (S.owner x u) (S.spanIndex u.val.1) := by + simp [Scheme.extent, Scheme.owner, u.property] + have hi := small i + rw [hs] at hi + rw [S.index_val, S.index_val, hs] + exact Routing.offset_lt (S.extent x (S.owner x j)) Fin.val + (u := ⟨_, ⟨_, hi⟩⟩) (z := ⟨_, ⟨_, small j⟩⟩) h + +omit [Field F] in +open scoped Classical in +private theorem index_order (f : S.Fits x V k) (i j : S.exposed x) (hs : S.owner x i + = S.owner x j) : + (S.index x f i).2.val < (S.index x f j).2.val ↔ + S.spanIndex i.val.1 < S.spanIndex j.val.1 ∨ + S.spanIndex i.val.1 = S.spanIndex j.val.1 ∧ i.val.2.val < j.val.2.val := by + rcases lt_trichotomy (S.spanIndex i.val.1) (S.spanIndex j.val.1) with h | h | h + · exact iff_of_true (precedes f i j hs h) (.inl h) + · simp [S.index_val, hs, h] + · exact iff_of_false (precedes f j i hs.symm h).not_gt + (fun hh => hh.elim h.not_gt (fun h' => h.ne' h'.1)) + +omit [Field F] in +open scoped Classical in +private theorem span_order (i j : S.Span) (he : i.1.2.2 = j.1.2.2) : + S.spanIndex i < S.spanIndex j ↔ i.1.2.1.val < j.1.2.1.val ∨ + (i.1.2.1.val = j.1.2.1.val ∧ i.2.val < j.2.val) := by + change (Match.rowIndex _ _).symm ((Match.rowIndex S.h S.k).symm i.1.2, i.2) < + (Match.rowIndex _ _).symm ((Match.rowIndex S.h S.k).symm j.1.2, j.2) ↔ _ + rw [rowIndex_lt, rowIndex_lt, (Match.rowIndex S.h S.k).symm.injective.eq_iff, Prod.ext_iff, he] + simp only [lt_self_iff_false, and_false, or_false, and_true, Fin.lt_def, Fin.ext_iff] + +include t in +open scoped Classical in +theorem order (f : S.Fits x V k) (g : U.Fits y V k) (i j : slots a ⊕ slots b) + (hh : S.owner x (p.boundary i) = S.owner x (p.boundary j)) : + (U.index y g (q.boundary i)).2.val < (U.index y g (q.boundary j)).2.val ↔ + (S.index x f (p.boundary i)).2.val < (S.index x f (p.boundary j)).2.val := by + have hv : U.owner y (q.boundary i) = U.owner y (q.boundary j) := + Fin.ext (by rw [t.owner, t.owner, hh]) + have hf (u v) : U.spanIndex (q.boundary u).val.1 < U.spanIndex (q.boundary v).val.1 ↔ + S.spanIndex (p.boundary u).val.1 < S.spanIndex (p.boundary v).val.1 := by + rw [span_order _ _ (t.right ..), span_order _ _ (t.left ..), t.block, t.block, t.span, t.span] + have he : U.spanIndex (q.boundary i).val.1 = U.spanIndex (q.boundary j).val.1 ↔ + S.spanIndex (p.boundary i).val.1 = S.spanIndex (p.boundary j).val.1 := by + simp only [le_antisymm_iff, ← not_lt, hf] + rw [index_order g _ _ hv, index_order f _ _ hh, hf, he, t.offset, t.offset] + +end Retag +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- # Uniqueness of the order-preserving enumeration in a payload bank -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {m n V k : ℕ} {I : Type} + +private theorem same_order (P : Payload m V k) (f g : I ≃ P.Bit) + (host : ∀ i, (g i).1.val = (f i).1.val) + (order : ∀ i j, (f i).1 = (f j).1 → (f i).2.val < (f j).2.val → (g i).2.val < (g j).2.val) : + g = f := by + have first (i) := Fin.ext (host i) + have eq (v : B m) (i : Fin (P.length v)) : + g (f.symm ⟨v, i⟩) = ⟨v, i⟩ := by + have hv (j : Fin (P.length v)) : (g (f.symm ⟨v, j⟩)).1 = v := + (first _).trans (congrArg Sigma.fst (f.apply_symm_apply _)) + let perm (j : Fin (P.length v)) : Fin (P.length v) := + (g (f.symm ⟨v, j⟩)).2.cast (congrArg _ (hv j)) + have mono : StrictMono perm := by + intro i j hij + exact order _ _ (by rw [f.apply_symm_apply, f.apply_symm_apply]) + (by rw [f.apply_symm_apply, f.apply_symm_apply]; exact hij) + exact Sigma.ext (hv i) ((Fin.heq_ext_iff (congrArg P.length (hv i))).mpr + (congrArg Fin.val (congrFun mono.eq_id i))) + exact Equiv.ext fun i => by simpa using eq (f i).1 (f i).2 + +private theorem same_bank (P : Payload m V k) (Q : Payload n V k) (hm : n = m) + (length : ∀ v, Q.length v = P.length (finCongr (congrArg (fun t => 2 ^ t) hm) v)) + (f : I ≃ P.Bit) (g : I ≃ Q.Bit) + (host : ∀ i, (g i).1.val = (f i).1.val) + (order : ∀ i j, (f i).1 = (f j).1 → (f i).2.val < (f j).2.val → (g i).2.val < (g j).2.val) + (s : P.Bit → Bool) (t : Q.Bit → Bool) (read : ∀ i, t (g i) = s (f i)) : + HEq (Q.store t) (P.store s) := by + subst n + have he : Q.length = P.length := funext length + have h : Q = P := by cases Q; cases P; cases he; rfl + subst Q + have hf := same_order P f g host order + subst g + have ht : t = s := by + funext j + obtain ⟨i, rfl⟩ := f.surjective j + exact read i + rw [ht] + +namespace Scheme.Presentation.Retag +variable {F : Type} [Field F] {S U : Scheme F} {x : S.format.obj} {y : U.format.obj} + {a b : Wire} {G H : Diagram F a b} {p : S.Presentation x G} {q : U.Presentation y H} + (t : Retag p q) + +theorem store (h : S.Fits x V k) (i : Val a) (j : Val b) : + HEq (U.store y (t.fits h) (q.exterior i j)) (S.store x h (p.exterior i j)) := by + refine same_bank (S.payload x h) (U.payload y (t.fits h)) t.m t.load + (p.boundary.trans (S.index x h)) (q.boundary.trans (U.index y (t.fits h))) t.owner + (fun i j he => (t.order h (t.fits h) i j he).mpr) _ _ ?_ + intro u + simp only [Equiv.trans_apply, Function.comp_apply, Equiv.symm_apply_apply, exterior_boundary] + +end Scheme.Presentation.Retag +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- Expand sparse peers as singleton intervals. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Peers + +open Coloring +variable (F : Type) [Field F] {q t : ℕ} + +private theorem prepare (hq : q ≤ t) : + Cheap F 0 t (row q) (Intervals.span q) interval 12 := by + have hi : (row q).width ≤ 2 ^ 0 * (100 + t) ^ 2 := by simp [row]; ring_nf; omega + have hw : (Format.addr q).width ≤ 2 ^ 0 * (100 + t) ^ 2 := by simp; ring_nf; omega + have x := Cheap.id F hi + have u := ((Cheap.const F hi hw 1).pair (Cheap.const F hi hw 0)).pair x.fst + have len := u.comp ((cheap_select F q).widen hq) + exact (x.snd.fst.pair (len.pair x.snd.snd)).mono (by decide) + +private theorem restore (hq : q ≤ t) (i : B q) : + Cheap F 0 t (.addr q) (.addr q) (fun x => if x < ⊤ then x else i) 12 := by + have hw : (Format.addr q).width ≤ 2 ^ 0 * (100 + t) ^ 1 := by simp; omega + have x := Cheap.id F hw + have lt := (x.pair (Cheap.const F hw hw ⊤)).comp (Intervals.cheap_compare F hq) + have y := ((x.pair (Cheap.const F hw hw i)).pair lt).comp ((cheap_select F q).widen hq) + convert y.mono (d := 12) (by decide) using 1 + funext x + by_cases h : x < ⊤ <;> simp [h] + +theorem lift {A D : Format} {f : A.obj → D.obj} {h k c : ℕ} + (v : Cheap F h t A D f c) (hk : h ≤ k) : Cheap F k t A D f c := by + obtain ⟨m, hm, h⟩ := v + exact ⟨m, hm, h.trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) hk))⟩ + +theorem cheap (p q : ℕ) : + Cheap F (max p q) (max p q + 3 * q) (.vec p (row q)) (Perm q) eval 110 := by + have hq : q ≤ max p q + 3 * q := by omega + have a := lift F (Cheap.map _ (fun _ : B p => prepare F hq)) (le_max_left p q) + have b := Intervals.cheap_pointers F (j := p) (h := q) id ⊤ + have c := lift F (Cheap.map _ (restore F hq)) (le_max_right p q) + exact ((a.comp b).comp c).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Peers +end + +/- Reading physical port addresses from fixed slot-and-lane lookup tables. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +namespace Peers +variable (F : Type) [Field F] + +private theorem full_table (R : Format) {p q t : ℕ} (hr : R.width = p) (hp : p ≤ t) (hq : q ≤ t) + (v : R.obj → B q) : + Cheap F p t (.vec p R) (.vec p (.addr q)) (fun x => v ∘ x) 10 := by + subst p + have hi := Intervals.vec_bound R.width (show R.width ≤ 100 + t by omega) + have ht := Cheap.const F hi (column_width R.width hq) (v ∘ R.serial.symm) + have read := (ht.pair (cheap_keys R F R.width hp)).comp (Cheap.lookup F R.width t (.addr q) hp + (by simpa using hq)) + convert read.mono (d := 10) (by decide) using 1 + funext x j + simp [Format.keys] + +theorem cheap_table (p : ℕ) (R : Format) {q : ℕ} (v : R.obj → B q) : + Cheap F (max p R.width) (max p R.width + q + 1) (.vec p R) (.vec p (.addr q)) (fun x + => v ∘ x) 20 := by + let n := max p R.width + let t := n + q + 1 + let K := Format.pair R (.addr (n - R.width)) + have hk : K.width = n := by simp [K, n] + have hp : p ≤ n := le_max_left _ _ + have width (A : Format) (ha : A.width ≤ t) (l : ℕ) (hl : l ≤ n) : + (Format.vec l A).width ≤ 2 ^ n * (100 + t) ^ 1 := + (Intervals.vec_bound l (ha.trans (Nat.le_add_left _ _))).trans + (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) hl)) + have hr : R.width ≤ t := by omega + have hq : (Format.addr q).width ≤ t := by simp [t]; omega + have pad : Cheap F n t (.vec p R) (.vec n R) (fun x => x ∘ Intervals.shrink p) 2 := + Cheap.project F (width _ hr p hp) (width _ hr n le_rfl) (fun i => (Intervals.shrink p i.1, i.2)) + (fun _ _ => rfl) + have zeros := Cheap.const F (width _ hr p hp) + (column_width n (show n - R.width ≤ t by omega)) (fun _ => 0) + have read := full_table F K hk (show n ≤ t by omega) (show q ≤ t by omega) (fun z => v z.1) + have out : Cheap F n t (.vec n (.addr q)) (.vec p (.addr q)) + (fun x => x ∘ Intervals.extend hp) 2 := + Cheap.project F (width _ hq n le_rfl) (width _ hq p hp) (fun i => (Intervals.extend hp i.1, + i.2)) + (fun _ _ => rfl) + convert (((pad.pair zeros).zip.comp read).comp out).mono (d := 20) (by decide) using 1 + funext x i + simp only [Function.comp_apply, Intervals.shrink_extend] + +end Peers + +namespace Bank +variable {A D : Format} (P : Bank A D) {k d h q : ℕ} (i : P.Level k d) + (host : P.Slot ↪ B h) (hd : d ≤ 2 ^ q) + +/-- Computes the pair code by the application `Format.pair (.addr h) (.addr q)`. -/ +abbrev pairCode (h q : ℕ) := Format.pair (.addr h) (.addr q) + +/-- Embeds `P.Port d i.1.val` into `(pairCode h q).obj where toFun e`. -/ +def codePort : P.Port d i.1.val ↪ (pairCode h q).obj where + toFun e := (host e.1.val, e.2.castLE ((min_le_left _ _).trans hd)) + inj' := by + rintro ⟨s, v⟩ ⟨t, w⟩ he + have h : s = t := Subtype.ext (host.injective (congrArg Prod.fst he)) + subst t + have h : v = w := Fin.ext (congrArg (fun x => x.2.val) he) + rw [h] + +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def portTable : (pairCode h q).obj → B (P.count k d i) := + Function.extend (P.codePort i host hd) (P.index k d i) (fun _ => ⊤) + +theorem portTable_at (e : P.Port d i.1.val) : + P.portTable i host hd (P.codePort i host hd e) = P.index k d i e := + (P.codePort i host hd).injective.extend_apply _ _ _ + +end Bank +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Select.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Select.lean new file mode 100644 index 0000000000..19369b3c40 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Select.lean @@ -0,0 +1,474 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Choices +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats + +/-! +# Long host names and short block records + +A host's list of neighbor names is shared between blocks. An +occurrence sees only indices in this list and indices of remote +ports. This avoids charging a global address at every occurrence. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Fmt + +open Coloring + +/-- The value specified by `.vec m (.pair (.vec d (.addr m)) (.vec h A))`. -/ +abbrev rows (m d h : ℕ) (A : Format) : Format := + .vec m (.pair (.vec d (.addr m)) (.vec h A)) + +/-- Candidate outgoing stubs at one occurrence. The extra field can +carry a colony key. The block is implicit in the enclosing row. -/ +abbrev occ (d _h e k ℓ : ℕ) : Format := + .pair (.addr ℓ) (.vec e (.pair .bit (.pair (.addr d) (.addr k)))) + +theorem width_rows (m d h : ℕ) (A : Format) : + (rows m d h A).width = 2 ^ m * (2 ^ d * m + 2 ^ h * A.width) := by + simp [rows] + +theorem width_occ (d h e k ℓ : ℕ) : + (occ d h e k ℓ).width = ℓ + 2 ^ e * (1 + (d + k)) := by + simp [occ] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Fmt +end + +/- +# Networks between typed records + +Sequential composition contracts the *entire* intermediate record. +Its two layouts may differ by arbitrary renaming of bit positions. +The gate budget is additive. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring + +variable {F : Type} [Field F] {A B C D : Format} {u m n : ℕ} {L : Set (Table F)} + +open scoped Classical in +instance finiteObj (A : Format) : Finite A.obj := Finite.of_injective A.code A.code.injective + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def names (A : Format) : A.pins ≃ slots (word A.width) + := Fintype.equivOfCardEq (by simp [Format.width]) + +open scoped Classical in +/-- Reindexes `Val a` and `A.obj` by an equivalence. -/ +def view (A : Format) {a : Wire} (i : A.pins ≃ slots a) : Val a ≃ A.obj := + (bits a).trans ((i.symm.arrowCongr (.refl Bool)).trans A.code.symm) + +open scoped Classical in +theorem view_apply (A : Format) {a : Wire} (i : A.pins ≃ slots a) (x : Val a) : + view A i x = A.code.symm (bits a x ∘ i) := rfl + +open scoped Classical in +/-- The defining condition `∀ (a b : Wire) (i : A.pins ≃ slots a) (j : B.pins ≃ slots b), ∃ s ≤ +m, Wide F u L a b (fun x y => f (view A i x) (view B j y)) s`. -/ +def Kernel (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) + (A B : Format) (f : A.obj → B.obj → F) (m : ℕ) : Prop := + ∀ (a b : Wire) (i : A.pins ≃ slots a) (j : B.pins ≃ slots b), + ∃ s ≤ m, Wide F u L a b (fun x y => f (view A i x) (view B j y)) s + +open scoped Classical in +/-- Requires `Kernel F u L A B (fun x y => if f x = y then 1 else 0) m`. -/ +def Map (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) + (A B : Format) (f : A.obj → B.obj) (m : ℕ) : Prop := + Kernel F u L A B (fun x y => if f x = y then 1 else 0) m + +namespace Kernel +variable {f : A.obj → B.obj → F} + +open scoped Classical in +theorem mono (h : Kernel F u L A B f m) (hm : m ≤ n) : Kernel F u L A B f n := by + intro a b i j + obtain ⟨s, hs, h⟩ := h a b i j + exact ⟨s, hs.trans hm, h⟩ + +open scoped Classical in +theorem widen {v : ℕ} {L' : Set (Table F)} (h : Kernel F u L A B f m) + (hu : u ≤ v) (hl : L ⊆ L') : Kernel F v L' A B f m := by + intro a b i j + obtain ⟨s, hs, h⟩ := h a b i j + exact ⟨s, hs, h.mono hu hl⟩ + +open scoped Classical in +theorem of_layout {a b : Wire} (i : A.pins ≃ slots a) (j : B.pins ≃ slots b) + (h : ∃ s ≤ m, Wide F u L a b (fun x y => f (view A i x) (view B j y)) s) : + Kernel F u L A B f m := by + intro c d k l + obtain ⟨s, hs, hw⟩ := h + refine ⟨s, hs, ?_⟩ + have hp := (hw.pre (rewire_reindex (i.symm.trans k))).post (rewire_reindex (j.symm.trans l)) + simpa [view_apply, reindex, Function.comp_def] using hp + +open scoped Classical in +theorem comp [Fintype B.obj] {g : B.obj → C.obj → F} + (h : Kernel F u L A B f m) (k : Kernel F u L B C g n) : + Kernel F u L A C (fun x z => ∑ y, f x y * g y z) (m + n) := by + intro a c i l + obtain ⟨s, hs, h⟩ := h a _ i (names B) + obtain ⟨t, ht, k⟩ := k _ c (names B) l + refine ⟨s + t, Nat.add_le_add hs ht, ?_⟩ + have he (x : Val a) (z : Val c) := + (view B (names B)).sum_comp (fun y => f (view A i x) y * g y (view C l z)) + simpa only [he] using h.comp k + +open scoped Classical in +theorem par {g : C.obj → D.obj → F} (h : Kernel F u L A B f m) (k : Kernel F u L C D g n) : + Kernel F u L (.pair A C) (.pair B D) (fun x y => f x.1 y.1 * g x.2 y.2) (m + n) := by + obtain ⟨s, hs, h⟩ := h _ _ (names A) (names B) + obtain ⟨t, ht, k⟩ := k _ _ (names C) (names D) + exact of_layout (a := .pair _ _) (b := .pair _ _) + ((names A).sumCongr (names C)) ((names B).sumCongr (names D)) + ⟨_, Nat.add_le_add hs ht, h.par k⟩ + +end Kernel + +namespace Map +variable {f : A.obj → B.obj} + +open scoped Classical in +theorem mono (h : Map F u L A B f m) (hm : m ≤ n) : Map F u L A B f n := Kernel.mono h hm + +open scoped Classical in +theorem then_kernel {g : B.obj → C.obj → F} (h : Map F u L A B f m) + (k : Kernel F u L B C g n) : Kernel F u L A C (fun x y => g (f x) y) (m + n) := by + let _ := Fintype.ofFinite B.obj + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + using Kernel.comp h k + +open scoped Classical in +theorem comp {g : B.obj → C.obj} (h : Map F u L A B f m) (k : Map F u L B C g n) : + Map F u L A C (g ∘ f) (m + n) := h.then_kernel k + +open scoped Classical in +theorem par {g : C.obj → D.obj} (h : Map F u L A B f m) (k : Map F u L C D g n) : + Map F u L (.pair A C) (.pair B D) (Prod.map f g) (m + n) := by + unfold Map + simpa only [Prod.ext_iff, Prod.map_fst, Prod.map_snd, ite_and, ite_mul, one_mul, zero_mul] + using Kernel.par h k + +open scoped Classical in +theorem of_layout {a b : Wire} (i : A.pins ≃ slots a) (j : B.pins ≃ slots b) + {g : Val a → Val b} (h : DWide F u L a b g m) (he : ∀ x, view B j (g x) = f (view A i x)) : + Map F u L A B f m := by + apply Kernel.of_layout i j + obtain ⟨s, hs, hw⟩ := h + refine ⟨s, hs, ?_⟩ + simpa only [← he, Equiv.apply_eq_iff_eq] using hw + +open scoped Classical in +theorem circuit (hu : 3 ≤ u) (h : Circuit F A B f m) : Map F u L A B f (4 * m) := by + apply of_layout (names A) (names B) (DWide.of_dnet hu (h _ _ (names A) (names B))) + intro x + exact (view B (names B)).apply_symm_apply _ + +end Map +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Composing encoded expansions + +A state can carry its host, allocation and proof invariants. Only +the bit record crosses a stage boundary. It may contain payloads +in the stage's own ordering. Distinct terms with the same record +retain their field multiplicities. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring + +universe v + +open scoped Classical in +/-- The data for the snapshot construction, including `state`, `eval`, `port`, `encode`. -/ +structure Snapshot (F : Type) (x y : Wire) where + /-- The `Snapshot` component of type `Type v`. -/ + state : Type v + /-- The evaluation operation of type `state → Val x → Val y → F`. -/ + eval : state → Val x → Val y → F + /-- The `Snapshot` component of type `Format`. -/ + port : Format + /-- The `Snapshot` component of type `state → Val x → Val y → port.obj`. -/ + encode : state → Val x → Val y → port.obj + +variable {F : Type} [Field F] {x y : Wire} {u m n : ℕ} {L : Set (Table F)} + {X Y Z : Snapshot.{v} F x y} + +open scoped Classical in +/-- The expands of type `Prop` for the given inputs. -/ +def Expands (X Y : Snapshot.{v} F x y) (f : X.port.obj → Y.port.obj → F) : Prop := + ∀ s : X.state, ∃ (I : Type) (_ : Fintype I) (q : I → Y.state) (c : I → F), + (∀ a b, X.eval s a b = ∑ i, c i * Y.eval (q i) a b) ∧ + ∀ a b r, f (X.encode s a b) r = ∑ i, if Y.encode (q i) a b = r then c i else 0 + +open scoped Classical in +/-- The condition `∃ f, Kernel F u L X.port Y.port f m ∧ Expands X Y f` on the specified data. -/ +def Transforms (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) + (X Y : Snapshot.{v} F x y) (m : ℕ) : Prop := + ∃ f, Kernel F u L X.port Y.port f m ∧ Expands X Y f + +open scoped Classical in +/-- Contracting against a snapshot sums over actual branches, including +when encodings collide. -/ +private theorem contract {I R : Type} [Fintype I] [Fintype R] (q : I → R) (c : I → F) (f : R → F) : + (∑ r, (∑ i, if q i = r then c i else 0) * f r) = ∑ i, c i * f (q i) := by + simp only [Finset.sum_mul, ite_mul, zero_mul] + rw [Finset.sum_comm] + simp + +open scoped Classical in +theorem Expands.comp [Fintype Y.port.obj] {f g} (h : Expands X Y f) (k : Expands Y Z g) : + Expands X Z (fun a b => ∑ y, f a y * g y b) := by + intro s + obtain ⟨I, _, q, c, hq, he⟩ := h s + choose J fJ r d hr hd using fun i => k (q i) + let _ : ∀ i, Fintype (J i) := fJ + refine ⟨Σ i, J i, inferInstance, fun v => r v.1 v.2, fun v => c v.1 * d v.1 v.2, ?_, ?_⟩ + · intro a b + simp only [hq, hr, Finset.mul_sum, Fintype.sum_sigma, mul_assoc] + · intro a b t + simp only [he] + rw [contract, Fintype.sum_sigma] + simp only [hd, Finset.mul_sum, mul_ite, mul_zero] + +namespace Transforms + +open scoped Classical in +theorem mono (h : Transforms F u L X Y m) (hm : m ≤ n) : Transforms F u L X Y n := + let ⟨f, hf, he⟩ := h + ⟨f, hf.mono hm, he⟩ + +open scoped Classical in +theorem widen {v : ℕ} {L' : Set (Table F)} (h : Transforms F u L X Y m) (hu : u ≤ v) + (hs : L ⊆ L') : Transforms F v L' X Y m := + let ⟨f, hf, he⟩ := h + ⟨f, hf.widen hu hs, he⟩ + +open scoped Classical in +theorem comp (h : Transforms F u L X Y m) (k : Transforms F u L Y Z n) : + Transforms F u L X Z (m + n) := by + let _ := Fintype.ofFinite Y.port.obj + obtain ⟨f, hf, he⟩ := h + obtain ⟨g, hg, hg'⟩ := k + exact ⟨_, hf.comp hg, he.comp hg'⟩ + +open scoped Classical in +theorem of_map (f : X.port.obj → Y.port.obj) (q : X.state → Y.state) + (hm : Map F u L X.port Y.port f m) + (he : ∀ s, X.eval s = Y.eval (q s)) + (hc : ∀ s a b, f (X.encode s a b) = Y.encode (q s) a b) : + Transforms F u L X Y m := by + refine ⟨_, hm, fun s => ⟨Unit, inferInstance, fun _ => q s, fun _ => 1, ?_, ?_⟩⟩ + · intro a b + simp only [he, Fintype.sum_unique, one_mul] + · intro a b r + simp only [hc, Fintype.sum_unique] + +open scoped Classical in +theorem refl (hu : 3 ≤ u) (X : Snapshot.{v} F x y) : + Transforms F u L X X (4 * X.port.width) := + of_map id id (Map.circuit hu (Circuit.id F _)) (fun _ => rfl) (fun _ _ _ => rfl) + +end Transforms + +open scoped Classical in +/-- The condition `∃ k : X.port.obj → F, Kernel F u L X.port (.wire .unit) (fun a _ => k a) m ∧ +∀ s a b, k (X.encode s a b) = X.eval s a b` on the specified data. -/ +def Finishes (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) + (X : Snapshot.{v} F x y) (m : ℕ) : Prop := + ∃ k : X.port.obj → F, Kernel F u L X.port (.wire .unit) (fun a _ => k a) m ∧ + ∀ s a b, k (X.encode s a b) = X.eval s a b + +open scoped Classical in +theorem Transforms.finish (h : Transforms F u L X Y m) (k : Finishes F u L Y n) : + Finishes F u L X (m + n) := by + let _ := Fintype.ofFinite Y.port.obj + obtain ⟨f, hf, he⟩ := h + obtain ⟨g, hg, hg'⟩ := k + refine ⟨fun x => ∑ y, f x y * g y, hf.comp hg, fun s a b => ?_⟩ + obtain ⟨I, _, q, c, hq, hh⟩ := he s + simp only [hh, contract, hg', hq] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Realizing local factors on shared tapes + +Copying a tape is paid once per actual read, even if the tape is +much larger than any individual factor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Kernel + +open Coloring Transcript + +variable {F : Type} [Field F] {A B C : Format} {u m : ℕ} {L : Set (Table F)} + +open scoped Classical in +theorem of_weight (hu : 3 ≤ u) {f : ((A.pins ⊕ B.pins) → Bool) → F} + (h : WideWeight F u L f m) : + Kernel F u L A B (fun x y => f (Sum.elim (A.code x) (B.code y))) (m + 4 * B.width) := by + intro a b i j + obtain ⟨s, hs, k⟩ := h (.pair a b) (i.sumCongr j) + obtain ⟨t, ht, hc⟩ := (Net.cup F b).includeWide (L := L) hu + have hw := (((k.par hc).pre (.unit' _)).post ((Rewire.unit' _).comp (.swap _ _))).trace + have hb := (Fintype.card_congr j).trans (card_slots b) + refine ⟨s + t, Nat.add_le_add hs (by rw [Format.width, hb]; exact ht), ?_⟩ + simp only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] at hw + convert hw using 1 + funext x y + simp only [view_apply, Equiv.apply_symm_apply] + apply congrArg f + funext p + cases p <;> rfl + +open scoped Classical in +theorem factors {I Y : Type} [Fintype I] [Fintype Y] {Z : I → Type} [∀ i, Finite (Z i)] + (k : (i : I) → (Z i → Bool) → F) (r : (i : I) → Z i → (A.pins ⊕ B.pins) ⊕ Y) + (cost : I → ℕ) (hu : 3 ≤ u) (h : ∀ i, WideWeight F u L (k i) (cost i)) : + Kernel F u L A B (fun x y => weightedSum k r (Sum.elim (A.code x) (B.code y))) + (8 * (A.width + B.width + Fintype.card Y) + 9 * (∑ i, cost i) + 4 * B.width) := by + let : ∀ i, Fintype (Z i) := fun i => Fintype.ofFinite (Z i) + simpa only [Fintype.card_sum] using of_weight hu (wide_sum k r cost hu h) + +open scoped Classical in +private theorem free (a : Wire) : Net F .unit a (fun _ _ => 1) (wd a) := by + induction a with + | bit => exact .table _ _ _ (by decide) + | unit => exact .empty + | pair a b h k => simpa only [wd, one_mul] using (h.par k).pre (.unit' _) + +open scoped Classical in +theorem sum_hidden [Fintype C.obj] {f : (A.obj × C.obj) → B.obj → F} + (hu : 3 ≤ u) (h : Kernel F u L (.pair A C) B f m) : + Kernel F u L A B (fun a b => ∑ c, f (a, c) b) (m + 4 * C.width) := by + intro a b i j + let c := word C.width + obtain ⟨s, hs, hk⟩ := h (.pair a c) b (i.sumCongr (names C)) j + obtain ⟨t, ht, hf⟩ := (free (F := F) c).includeWide (L := L) hu + have hw := ((hk.par hf).pre (.unit' _)).trace + refine ⟨s + t, Nat.add_le_add hs (by simpa [c] using ht), ?_⟩ + simp only [mul_one] at hw + convert hw using 1 + funext x y + exact ((view C (names C)).sum_comp (fun z => f (view A i x, z) (view B j y))).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Kernel +end + +/- +# One selector word per branch of an exact expansion + +The menu can depend on the entire preceding state. Only the exposed +selector format must stay fixed across the possible preceding states. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Transcript + +universe v +variable {F : Type} [Field F] {x y : Wire} {u m n : ℕ} {L : Set (Table F)} + {X Y : Snapshot.{v} F x y} {C : Format} + +open scoped Classical in +/-- The data for the selected construction, including `choice`, `[finite`, `index`, `next`, +`scalar`. -/ +structure Selected (X Y : Snapshot.{v} F x y) (C : Format) where + /-- The `Selected` component of type `X.state → Type`. -/ + choice : X.state → Type + [finite : ∀ s, Fintype (choice s)] + /-- The identification of the indices of type `∀ s, Selector (choice s) C.obj`. -/ + index : ∀ s, Selector (choice s) C.obj + /-- The successor of each choice of type `∀ s, choice s → Y.state`. -/ + next : ∀ s, choice s → Y.state + /-- The scalar prefactor of type `∀ s, choice s → F`. -/ + scalar : ∀ s, choice s → F + expands : ∀ s a b, X.eval s a b = ∑ i, scalar s i * Y.eval (next s i) a b + +attribute [instance] Selected.finite + +open scoped Classical in +theorem Transforms.of_selector (hu : 3 ≤ u) (R : Selected X Y C) + {k : X.port.obj × C.obj → Y.port.obj → F} + (hk : Kernel F u L (.pair X.port C) Y.port k m) + (he : ∀ s a b c t, k (X.encode s a b, c) t = ((R.index s).read c).elim 0 + (fun i => if Y.encode (R.next s i) a b = t then R.scalar s i else 0)) : + Transforms F u L X Y (m + 4 * C.width) := by + let _ := Fintype.ofFinite C.obj + refine ⟨_, Kernel.sum_hidden hu hk, fun s => + ⟨R.choice s, inferInstance, R.next s, R.scalar s, R.expands s, fun a b t => ?_⟩⟩ + simp only [he, Selector.sum] + +open scoped Classical in +/-- The computation can reject invalid words by zero weight. -/ +theorem Transforms.of_guard (hu : 3 ≤ u) (R : Selected X Y C) + (out : X.port.obj × C.obj → Y.port.obj) (weight : X.port.obj × C.obj → F) + (hk : Kernel F u L (.pair X.port C) Y.port (fun v t => if out v = t then weight v else 0) m) + (hw : ∀ s a b c, weight (X.encode s a b, c) = ((R.index s).read c).elim 0 (R.scalar s)) + (ho : ∀ s a b i, out (X.encode s a b, (R.index s).write i) = Y.encode (R.next s i) a b) : + Transforms F u L X Y (m + 4 * C.width) := by + refine Transforms.of_selector hu R hk fun s a b c t => ?_ + rw [hw] + cases h : (R.index s).read c with + | none => simp + | some i => + rw [(R.index s).valid _ _ |>.mp h, ho] + rfl + +open scoped Classical in +theorem Finishes.start (hu : 3 ≤ u) (s : X.state) + (h : Map F u L (.wire (.pair x y)) X.port (fun p => X.encode s p.1 p.2) m) + (hf : Finishes F u L X n) : + ∃ v ≤ m + n + 4 * wd y, Wide F u L x y (X.eval s) v := by + obtain ⟨k, hk, he⟩ := hf + obtain ⟨v, hv, hv'⟩ := h.then_kernel hk (.pair x y) .unit (.refl _) (.refl _) + have viewId (z : Val (.pair x y)) : view (.wire (.pair x y)) (.refl _) z = z := + (bits _).symm_apply_apply z + simp only [viewId, he] at hv' + obtain ⟨w, hw, hcup⟩ := (Net.cup F y).includeWide (L := L) hu + have hfin := (((hv'.par hcup).pre (.unit' _)).post ((Rewire.unit' _).comp (.swap _ _))).trace + refine ⟨v + w, Nat.add_le_add hv hw, ?_⟩ + simpa only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] using hfin + +open scoped Classical in +/-- Stage budgets add even when ports, layouts and reachable states +change from round to round. -/ +theorem Finishes.stages (X : ℕ → Snapshot.{v} F x y) (cost : ℕ → ℕ) (j : ℕ) + (steps : ∀ i < j, Transforms F u L (X i) (X (i + 1)) (cost i)) + (stop : Finishes F u L (X j) m) : + Finishes F u L (X 0) ((∑ i ∈ Finset.range j, cost i) + m) := by + induction j generalizing m with + | zero => simpa using stop + | succ j ih => + rw [Finset.sum_range_succ, add_assoc] + exact ih (fun i hi => steps i (Nat.lt_succ_of_lt hi)) ((steps j (by omega)).finish stop) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Serial.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Serial.lean new file mode 100644 index 0000000000..75f3e4520c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Serial.lean @@ -0,0 +1,1000 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute + +/-! +# Freezing hosts + +A retained station keeps all its arguments in order. A span +previously paired to a removed host becomes exterior. The only +additional data per block are one status bit per neighbor and +one for the host itself. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] {d k e : ℕ} + +open scoped Classical in +/-- Returns `{ p with peer := fun v i => (p.peer v i).filter (fun j => nbr j.1) }` when `live` +holds, and `⟨fun _ _ => 0, fun _ _ => false, fun _ _ => none, fun _ _ => 1⟩` otherwise. -/ +def Pattern.cut (p : Pattern F d k e) (live : Bool) (nbr : B d → Bool) : Pattern F d k e := + if live then { p with peer := fun v i => (p.peer v i).filter (fun j => nbr j.1) } + else ⟨fun _ _ => 0, fun _ _ => false, fun _ _ => none, fun _ _ => 1⟩ + +namespace Scheme +variable (S : Scheme F) + +open scoped Classical in +/-- The value specified by `Format.pair (.addr S.ℓ) (.pair .bit (.vec S.d .bit))`. -/ +abbrev cutCode := Format.pair (.addr S.ℓ) (.pair .bit (.vec S.d .bit)) + +open scoped Classical in +/-- The indexed operation `{ S with ℓ := S.cutCode.width, decode := fun c => let v := +S.cutCode.serial.symm c (S.decode v.1).cut v.2.1 v.2.2 }`. -/ +abbrev cut : Scheme F := + { S with ℓ := S.cutCode.width, + decode := fun c => let v := S.cutCode.serial.symm c + (S.decode v.1).cut v.2.1 v.2.2 } + +open scoped Classical in +theorem cut_length : S.cut.ℓ = S.ℓ + 1 + 2 ^ S.d := by simp [cutCode, add_assoc] + +variable (r : S.format.obj) (live : B S.m → Bool) + +open scoped Classical in +/-- Evaluates `((r v).1, fun i => S.cutCode.serial ((r v).2 i, live v, live ∘ (r v).1))` at the +input `v`. -/ +def remove : S.cut.format.obj := + fun v => ((r v).1, fun i => S.cutCode.serial ((r v).2 i, live v, live ∘ (r v).1)) + +local notation "cutR" => S.remove r live + +open scoped Classical in +theorem pattern_cut (v : S.Vtx) : + S.cut.pattern cutR v = (S.pattern r v).cut (live v.1) (live ∘ (r v.1).1) := by + simp only [pattern, remove, cut, Equiv.symm_apply_apply] + +open scoped Classical in +theorem width_cut (a : S.Span) : S.cut.width cutR a = if live a.1.1 then S.width r a else 0 := by + unfold width + rw [pattern_cut] + unfold Pattern.cut + split <;> rfl + +open scoped Classical in +theorem dir_cut (a : S.Span) (h : live a.1.1 = true) : + S.cut.direction cutR a = S.direction r a := by + unfold direction + rw [pattern_cut, Pattern.cut, ite_eq_left h] + +open scoped Classical in +theorem peer_cut (a : S.Span) : + S.cut.peer cutR a = if live a.1.1 then (S.peer r a).filter (fun v => live v.1.1) else none := by + unfold peer + rw [pattern_cut, Pattern.cut] + split + · cases h : (S.pattern r a.1).peer a.1.2.2 a.2 with + | none => simp only [h]; rfl + | some z => + simp only [h, Option.map_some, Option.filter, Function.comp_apply] + split <;> rfl + · rfl + +open scoped Classical in +theorem proper_cut (h : S.Proper r) : S.cut.Proper cutR := by + intro a b he + rw [peer_cut] at he + split at he + swap + · contradiction + rename_i ha + have hb : live b.1.1 = true ∧ S.peer r a = some b := by + cases e : S.peer r a with + | none => simp [e] at he + | some t => + simp only [e, Option.filter] at he + split at he + · cases Option.some.inj he; exact ⟨by assumption, rfl⟩ + · contradiction + obtain ⟨hk, hl, hd⟩ := h _ _ hb.2 + rw [peer_cut, ite_eq_left hb.1, hk, width_cut, width_cut, ite_eq_left ha, ite_eq_left hb.1, + S.dir_cut r live a ha, S.dir_cut r live b hb.1] + exact ⟨by simp [Option.filter, ha], hl, hd⟩ + +open scoped Classical in +/-- The equivalence obtained by `Equiv.sigmaCongrRight fun i => finCongr ((S.width_cut r live +(v, i)).trans (ite_eq_left h)).symm`. -/ +def cutPin (v : S.Vtx) (h : live v.1 = true) : S.LocalPin r v ≃ S.cut.LocalPin cutR v := + Equiv.sigmaCongrRight fun i => finCongr ((S.width_cut r live (v, i)).trans (ite_eq_left h)).symm + +omit [Field F] in +open scoped Classical in +private theorem preserved (p q : Pattern F d k e) (j : B k) (links : B k → B e → Option (B d × B k + × B e)) + (h : q = { p with peer := links }) + (he : ∀ i, p.width j i = q.width j i) (x : ∀ i, Fin (q.width j i) → Bool) : + q.value j x = p.value j (fun i u => x i (u.cast (he i))) := by + subst q + rfl + +open scoped Classical in +theorem table_cut (v : S.Vtx) (h : live v.1 = true) (x : S.cut.LocalPin cutR v → Bool) : + S.cut.table cutR v x = S.table r v (x ∘ S.cutPin r live v h) := by + have he := S.pattern_cut r live v + rw [Pattern.cut, ite_eq_left h] at he + exact preserved _ _ v.2.2 _ he (fun i => ((S.width_cut r live (v, i)).trans (ite_eq_left h)).symm) + (fun j t => x ⟨j, t⟩) + +open scoped Classical in +theorem table_removed (v : S.Vtx) (h : live v.1 ≠ true) (x : S.cut.LocalPin cutR v → Bool) : + S.cut.table cutR v x = 1 := by + have he := S.pattern_cut r live v + rw [Pattern.cut, ite_eq_right h] at he + have hh (q : Pattern F S.d S.k S.e) + (hq : q = ⟨fun _ _ => 0, fun _ _ => false, fun _ _ => none, fun _ _ => 1⟩) + (x : ∀ i, Fin (q.width v.2.2 i) → Bool) : q.value v.2.2 x = 1 := by cases hq; rfl + exact hh _ he _ + +end Scheme +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Retaining all bit ordinals in the core of a frozen diagram +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Coloring Packing + +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} {x y : Wire} + {G : Diagram F x y} (p : S.Presentation r G) (Z : Freeze G) (live : B S.m → Bool) + (hl : ∀ v, live (p.vertex v).1 = true ↔ ¬Z.frozen v) + +local notation "R" => S.remove r live + +open scoped Classical in +/-- Builds `S.cut.Seating R Z.core where vertex` with the specified `vertex`, `pin`, `cover`, +`rw`. -/ +def seats : S.cut.Seating R Z.core where + vertex := (Function.Embedding.subtype _).trans p.vertex + pin v := (p.pin v.val).trans (S.cutPin r live (p.vertex v.val) ((hl _).mpr v.property)) + cover q := by + have h : 0 < S.cut.width R q.1 := Nat.zero_lt_of_lt q.2.isLt + rw [S.width_cut] at h + split at h + next hn => + obtain ⟨v, hv⟩ := p.cover ⟨q.1, ⟨0, h⟩⟩ + change p.vertex v = q.1.1 at hv + exact ⟨⟨v, (hl v).mp (by rw [hv]; exact hn)⟩, hv⟩ + next => omega + sample v t := by + exact (S.table_cut r live _ ((hl v.val).mpr v.property) t).trans (p.sample _ _) + vacant v hv t := by + by_cases h : live v.1 = true + · refine (S.table_cut r live _ h t).trans (p.vacant _ ?_ _) + rintro ⟨i, rfl⟩ + exact hv ⟨⟨i, (hl _).mp h⟩, rfl⟩ + · exact S.table_removed r live _ h t + +open scoped Classical in +/-- In the case `.inl (.inl i)`, this construction gives `.inl (.inr (Z.input i).val)`. -/ +def fullEnd : Z.core.End → G.End + | .inl (.inl i) => .inl (.inr (Z.input i).val) + | .inl (.inr e) => .inl (.inr e.val) + | .inr (.inl i) => .inr (.inr (Z.output i).val) + | .inr (.inr e) => .inr (.inr e.val) + +local notation "q" => p.seats Z live hl + +open scoped Classical in +theorem span_full (t : Z.core.End) : ((q).ends t).1 = (p.toSeating.ends (fullEnd Z t)).1 := by + rcases t with (i|e)|(i|e) <;> rfl + +open scoped Classical in +theorem ordinal_full (t : Z.core.End) : ((q).ends t).2.val = (p.toSeating.ends (fullEnd Z t)).2.val + := by + rcases t with (i|e)|(i|e) <;> rfl + +include hl in +open scoped Classical in +theorem live_wire (e : G.E) (b : Bool) : + live (p.wirePin e b).1.1.1 = true ↔ ¬Z.frozen (cond b (G.target e) (G.source e)) := by + rw [wirePin_at] + exact hl _ + +open scoped Classical in +/-- Builds `S.cut.Presentation R Z.core where toSeating` with the specified `toSeating`, +`proper`, `internal`, `change`. -/ +def freeze : S.cut.Presentation R Z.core where + toSeating := q + proper := S.proper_cut r live p.proper + internal e := by + change Z.Internal at e + have hs := (p.live_wire Z live hl e.val false).mpr e.property.1 + have ht := (p.live_wire Z live hl e.val true).mpr e.property.2 + refine ⟨?_, (p.internal e.val).2⟩ + change S.cut.peer R (p.wirePin e.val false).1 = some (p.wirePin e.val true).1 + rw [S.peer_cut, ite_eq_left hs, wirePin_peer] + simp [Option.filter, ht] + input i := by + let e := (Z.input i).val + have hs := (p.live_wire Z live hl e false).mpr (fun h => Z.separate e ⟨h, (Z.input i).property⟩) + have ht : live (p.wirePin e true).1.1.1 ≠ true := + fun h => (p.live_wire Z live hl e true).mp h (Z.input i).property + rw [span_full] + change S.cut.peer R (p.wirePin e false).1 = none + rw [S.peer_cut, ite_eq_left hs, wirePin_peer] + simp [Option.filter, ht] + output i := by + let e := (Z.output i).val + have ht := (p.live_wire Z live hl e true).mpr (fun h => Z.separate e ⟨(Z.output i).property, h⟩) + have hs : live (p.wirePin e false).1.1.1 ≠ true := + fun h => (p.live_wire Z live hl e false).mp h (Z.output i).property + rw [span_full] + change S.cut.peer R (p.wirePin e true).1 = none + rw [S.peer_cut, ite_eq_left ht, wirePin_peer] + simp [Option.filter, hs] + +open scoped Classical in +theorem freeze_span (e : Z.Internal) (t : Bool) : + ((p.freeze Z live hl).wirePin e t).1 = (p.wirePin e.val t).1 := by cases t <;> rfl + +open scoped Classical in +theorem freeze_directed (hd : p.Directed) : (p.freeze Z live hl).Directed := by + intro t + have ha : live ((q).ends t).1.1.1 = true := by + have h : 0 < S.cut.width R ((q).ends t).1 := Nat.zero_lt_of_lt ((q).ends t).2.isLt + rw [S.width_cut] at h + split at h <;> first | assumption | omega + change S.cut.direction R ((q).ends t).1 = _ + rw [S.dir_cut _ _ _ ha, span_full, hd] + rcases t with (i|e)|(i|e) <;> rfl + +open scoped Classical in +theorem freeze_uniform {u : ℕ} (h : ∀ e : Z.Internal, S.width r (p.wirePin e.val false).1 = u) : + (p.freeze Z live hl).Uniform u := by + intro e + rw [freeze_span, S.width_cut, ite_eq_left ((p.live_wire Z live hl _ false).mpr e.property.1)] + exact h e + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- +# Starting wire-saving subrounds with ordered core packets +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Coloring Packing + +variable {F V : Type} [Field F] [Fintype V] {S : Scheme F} {r : S.format.obj} {x y : Wire} + {G : Diagram F x y} (p : S.Presentation r G) (Z : Freeze G) (live : B S.m → Bool) + (hl : ∀ v, live (p.vertex v).1 = true ↔ ¬Z.frozen v) + {u h : ℕ} (hd : p.Directed) (hw : ∀ e : Z.Internal, S.width r (p.wirePin e.val false).1 = u) + (H : Z.Frame V h) (hu : 0 < u) (L : Fringe Z.x Z.y Z.Fixed) (hL : L.tensor = Z.border.tensor) + +local notation "q" => p.freeze Z live hl +local notation "dir" => p.freeze_directed Z live hl hd +local notation "size" => p.freeze_uniform Z live hl hw + +open scoped Classical in +/-- Computes the core host by the application `H.hostOf hu L hL ((q).packets dir size)`. -/ +abbrev coreHost : HostNet F L h u := H.hostOf hu L hL ((q).packets dir size) + +local notation "Q" => p.coreHost Z live hl hd hw H hu L hL +local notation "R" => S.remove r live + +open scoped Classical in +/-- The freeze posting of type `S.cut.Posting R Q`, constructed using `(q).packets dir size`. -/ +def freezePosting (host : V ↪ B S.m) (block : Cell h ↪ B S.h) (idx : V → V → B S.d) + (hv : ∀ v, p.vertex v = (host (H.place v).1, block (H.place v).2, 0)) + (hi : ∀ v w i j, S.peer r (p.vertex v, i) = some (p.vertex w, j) → + (S.pattern r (p.vertex v)).peer 0 i = some (idx (H.place v).1 (H.place w).1, 0, j)) : + S.cut.Posting R Q := by + let P := (q).packets dir size + let root : (Q).E → Z.Internal := (q).root + let v (i : (Q).E) (t : Bool) := cond t (G.target (root i).val) (G.source (root i).val) + let stub (i : (Q).E) (t : Bool) := (p.wirePin (root i).val t).1.2 + have near (i : (Q).E) (t : Bool) : Scheme.side Q i t = (H.place (v i t)).1 := by + cases t <;> rfl + have here (i : (Q).E) (t : Bool) : + S.cut.spanAt Q host block stub i t = (p.vertex (v i t), stub i t) := by + unfold spanAt + erw [near, hv] + cases t + · rfl + · rw [show (H.place (v i true)).2 = _ from (H.group (root i).val).symm] + rfl + have full (i : (Q).E) (t : Bool) : + (p.wirePin (root i).val t).1 = (p.vertex (v i t), stub i t) := + Prod.ext (p.wirePin_at _ _) rfl + have tag (i : (Q).E) (t : Bool) : + S.cut.spanAt Q host block stub i t = ((q).wirePin (root i) t).1 := + (here i t).trans ((full i t).symm.trans (p.freeze_span _ _ _ _ t).symm) + have kept (i : (Q).E) (t : Bool) : live (p.vertex (v i t)).1 = true := by + apply (hl _).mpr + cases t + · exact (root i).property.1 + · exact (root i).property.2 + refine ⟨q, host, block, stub, idx, fun v => hv v.val, ?_, ?_, ?_, ?_⟩ + · intro i t j + let e := P.bits.symm (i, j) + have he : (q).locate size e = (i, j) := P.bits.apply_symm_apply (i, j) + have hs := (q).located size e t + rw [he] at hs + rw [tag] + exact hs + · intro i t + rw [tag] + exact (q).wirePin_width size _ _ + · intro i t + rw [tag] + exact (q).wirePin_dir dir _ _ + · intro i t + have he := p.wirePin_peer (root i).val t + rw [full, full] at he + have hh := hi _ _ _ _ he + have hd' : (p.vertex (v i t)).2.2 = 0 := by rw [hv] + have hk : (r (p.vertex (v i t)).1).1 (idx (H.place (v i t)).1 (H.place (v i (!t))).1) = + (p.vertex (v i (!t))).1 := by + unfold Scheme.peer at he + simp only [hd', hh, Option.map_some, Option.some.injEq] at he + exact congrArg (fun p => p.1.1) he + rw [here, near, near] + dsimp only + rw [hd', S.pattern_cut, Pattern.cut, ite_eq_left (kept i t)] + simp [hh, Option.filter, hk, kept] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- # Looking up short movement records at the other end of each stub -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +open Coloring + +/-- The value specified by `Format.pair (Directed d h e k ℓ) (.vec d (.vec h (Move d ℓ)))`. -/ +abbrev Inbox (d h e k ℓ : ℕ) := + Format.pair (Directed d h e k ℓ) (.vec d (.vec h (Move d ℓ))) + +/-- The value specified by `Format.pair (Path d ℓ) (Path d ℓ)`. -/ +abbrev PairPath (d ℓ : ℕ) := Format.pair (Path d ℓ) (Path d ℓ) + +variable {d h e k ℓ t : ℕ} + +/-- Computes the here ends by the application `ends x.1.2 (action x.1.1 x.1.2) x.2`. -/ +def hereEnds (x : (Inbox d h e k ℓ).obj) := ends x.1.2 (action x.1.1 x.1.2) x.2 + +theorem pairPath_width (ht : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) : + (PairPath d ℓ).width ≤ t := by + rw [Rows.overhead, width_labels] at ht + simp only [PairPath, Path, Move, Format.width_pair, Format.width_addr] + rw [Format.width_bit] + omega + +theorem inbox_bound (ht : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) (hw : k ≤ t) + (hd : 2 ^ d ≤ t) : (Inbox d h e k ℓ).width ≤ 2 ^ (h + e) * (100 + t) ^ 4 := by + rw [Rows.overhead, width_labels] at ht + have ha := input_bound (h := h) (e := e) t (show d ≤ t by omega) hw (show ℓ ≤ t by omega) hd + have hm : (Move d ℓ).width ≤ t := by + rw [Format.width_pair, Format.width_bit, Format.width_pair, Format.width_addr, + Format.width_addr] + omega + have hs := Nat.mul_le_mul hd (Nat.mul_le_mul + (Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.le_add_right h e)) hm) + rw [Format.width_pair, Format.width_pair, Format.width_bit, Format.width_vec, Format.width_vec] + have hp := Nat.two_pow_pos (h + e) + ring_nf at hs ha hp ⊢ + omega + +theorem cheap_ends (F : Type) [Field F] (d h e k ℓ t : ℕ) + (ht : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) (hw : k ≤ t) (hd : 2 ^ d ≤ t) : + Cheap F (h + e) t (Inbox d h e k ℓ) (.vec (h + e) (PairPath d ℓ)) hereEnds 200 := by + let A := Inbox d h e k ℓ + let U := Move d ℓ + let b i := (rowIndex h e i).1 + let j i := (rowIndex h e i).2 + have hi := ht + rw [Rows.overhead, width_labels] at hi + have ha := inbox_bound ht hw hd + have hm : U.width ≤ t := by + rw [Format.width_pair, Format.width_bit, Format.width_pair, Format.width_addr, + Format.width_addr] + omega + have small (X : Format) (hx : X.width ≤ (100 + t) ^ 2) : + (Format.vec (h + e) X).width ≤ 2 ^ (h + e) * (100 + t) ^ 4 := by + rw [Format.width_vec] + exact Nat.mul_le_mul_left _ (hx.trans (Nat.pow_le_pow_right (by omega) (by decide))) + have hmove := small U (by nlinarith only [hm]) + have hremote := small (.vec d U) (by + rw [Format.width_vec]; nlinarith only [Nat.mul_le_mul hd hm]) + have haddr := small (.addr d) (by rw [Format.width_addr]; nlinarith only [hi]) + have hhop := small (.pair .bit (.addr d)) (by + rw [Format.width_pair, Format.width_bit, Format.width_addr]; nlinarith only [hi]) + have hbit := small .bit (by rw [Format.width_bit]; exact Nat.one_le_pow _ _ (by omega)) + have near : Cheap F (h + e) t A (.vec (h + e) (.addr d)) (fun x i + => ((x.1.2.2.1 (b i)).2 (j i)).2.1) 5 := + Cheap.project F ha haddr + (fun z => .inl (.inr (.inr (.inl (b z.1, .inr (j z.1, .inr (.inl z.2))))))) (fun _ _ => rfl) + have seats : Cheap F (h + e) t A (.vec (h + e) (.vec d U)) (fun x i w => x.2 w (b i)) 5 := + Cheap.project F ha hremote (fun z => .inr (z.2.1, b z.1, z.2.2)) (fun _ _ => rfl) + have get := (near.pair seats).zip.comp + (Cheap.map (fun _ => _) (fun _ : B (h + e) => read_one F U (by omega) hm hd)) + have act := (Cheap.id F ha).fst.comp (cheap_action F d h e k ℓ t ht hw hd) + have lift : Cheap F (h + e) t (.vec h U) (.vec (h + e) U) (fun x i => x (b i)) 5 := by + apply Cheap.project F _ hmove (fun z => (b z.1, z.2)) (fun _ _ => rfl) + apply le_trans _ hmove + rw [Format.width_vec, Format.width_vec] + gcongr; omega + have own := (Cheap.const F ha hhop (fun _ => (false, 0))).pair (act.comp lift) + have other := ((Cheap.const F ha hbit (fun _ => true)).pair near).zip.pair get + exact (own.zip.pair other.zip).zip.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +/- # Selecting six party addresses from the two paired endpoint records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +open Coloring + +open scoped Classical in +/-- Uses `⟨j.val % 6, by omega⟩` as the representation. -/ +def partyIndex (j : B 3) : Fin 6 := ⟨j.val % 6, by omega⟩ + +open scoped Classical in +/-- Computes the both by the application `Format.pair .bit (.pair (.pair A A) (.pair A A))`. -/ +abbrev Both (A : Format) := Format.pair .bit (.pair (.pair A A) (.pair A A)) + +open scoped Classical in +private def bankParties (A : Format) (p : (Both A).obj) (j : B 3) := + parties p.1 p.2.1 p.2.2 (partyIndex j) + +open scoped Classical in +private def choice (A : Format) (c : Bool) (j : Fin 6) (i : A.pins) : (Both A).pins := + Sum.inr (parties c (.inl (.inl i), .inl (.inr i)) (.inr (.inl i), .inr (.inr i)) j) + +open scoped Classical in +private theorem choice_spec (A : Format) (x : (Both A).obj) (j : Fin 6) (i : A.pins) : + A.code (parties x.1 x.2.1 x.2.2 j) i = (Both A).code x (choice A x.1 j i) := by + obtain ⟨c, a, b⟩ := x + cases c <;> fin_cases j <;> rfl + +open scoped Classical in +theorem cheap_parties (F : Type) [Field F] (A : Format) {t : ℕ} (hw : A.width ≤ t) : + Cheap F 0 t (Both A) (.vec 3 A) (fun x i => parties x.1 x.2.1 x.2.2 (partyIndex i)) 3 := by + let f := (Format.vec 3 A).code ∘ bankParties A ∘ (Both A).code.symm + have rule (x : (Both A).pins → Bool) (j : B 3) (i : A.pins) : + f x (j, i) = x (choice A (x (.inl ())) (partyIndex j) i) := by + let y := (Both A).code.symm x + change A.code (parties y.1 y.2.1 y.2.2 (partyIndex j)) i = _ + rw [choice_spec, show (Both A).code y = x from Equiv.apply_symm_apply _ _] + rfl + have H : Install.Depends f 3 := by + rintro ⟨j, i⟩ + let a c := choice A c (partyIndex j) i + refine ⟨{.inl (), a true, a false}, ?_, ?_⟩ + · exact Finset.card_le_three + · intro x y he + have b := he (.inl ()) (by simp) + rw [rule, rule, b] + apply he + cases y (.inl ()) <;> simp [a] + refine ⟨_, H.bnet F, ?_⟩ + change (Both A).width + (Format.vec 3 A).width + ((Both A).width + 134 * (Format.vec 3 A).width) + ≤ _ + simp only [Both, Format.width_pair, Format.width_vec] + rw [Format.width_bit] + ring_nf + omega + +open scoped Classical in +/-- The value specified by `Format.pair .bit (.pair .bit (.pair (PairPath d ℓ) (.vec 3 (Path d +ℓ))))`. -/ +abbrev Report (d ℓ : ℕ) := + Format.pair .bit (.pair .bit (.pair (PairPath d ℓ) (.vec 3 (Path d ℓ)))) + +variable {d h e k ℓ : ℕ} + +open scoped Classical in +/-- The report of type `(Report d ℓ).obj`, constructed using `rows x.1.2`. -/ +def report (x : (Inbox d h e k ℓ).obj) (i : B (h + e)) : (Report d ℓ).obj := + let y := rows x.1.2 + let ptr := y.control.2 i + (y.control.1 i, y.active i && !(y.control.1 i) && !(y.control.1 ptr), + hereEnds x i, fun j => parties x.1.1 (hereEnds x ptr) (hereEnds x i) (partyIndex j)) + +open scoped Classical in +private theorem cheap_free (F : Type) [Field F] (t : ℕ) : + Cheap F 0 t (.pair (.pair .bit .bit) .bit) .bit + (fun x => x.1.1 && !x.1.2 && !x.2) 2 := by + refine ⟨_, Coloring.small (A := .pair (.pair .bit .bit) .bit) (by simp) _, ?_⟩ + change 3 + 1 + 200 ≤ _ + ring_nf; omega + +open scoped Classical in +theorem cheap_report (F : Type) [Field F] (d h e k ℓ t : ℕ) + (ht : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) (hw : k ≤ t) (hd : 2 ^ d ≤ t) : + Cheap F (h + e) t (Inbox d h e k ℓ) (.vec (h + e) (Report d ℓ)) report 220 := by + let A := Inbox d h e k ℓ + have ha := inbox_bound ht hw hd + have hi := ht + unfold Rows.overhead at hi + have hp := pairPath_width ht + have hp' : (Path d ℓ).width ≤ t := (Nat.le_add_right _ _).trans + (by simpa only [PairPath, Format.width_pair] using hp) + have hbit : (Format.vec (h + e) .bit).width ≤ 2 ^ (h + e) * (100 + t) ^ 4 := by + rw [Format.width_vec, Format.width_bit] + exact Nat.mul_le_mul_left _ (Nat.one_le_pow _ _ (by omega)) + have col : Cheap F (h + e) t A (.vec (h + e) .bit) (fun x _ => x.1.1) 5 := + Cheap.project F ha hbit (fun i => .inl (.inl i.2)) (fun _ _ => rfl) + have data := (Cheap.id F ha).fst.snd + have ctl := data.comp (cheap_match F d h e k ℓ t ht hw hd) + have active := (data.comp (cheap_rows F d h e k ℓ t ht hw hd)).fst + have mask := ctl.fst + have back := ctl.comp (Cheap.lookup F (h + e) t .bit (by omega) (by simp; omega)) + have free := ((active.pair mask).zip.pair back).zip.comp + (Cheap.map _ (fun _ : B (h + e) => cheap_free F t)) + have here := cheap_ends F d h e k ℓ t ht hw hd + have there := (here.pair ctl.snd).comp (Cheap.lookup F (h + e) t (PairPath d ℓ) (by omega) hp) + have six := (col.pair (there.pair here).zip).zip.comp + (Cheap.map _ (fun _ : B (h + e) => cheap_parties F (Path d ℓ) hp')) + exact (mask.pair (free.pair (here.pair six).zip).zip).zip.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Match +end + +/- # Lexicographic rank of a span at a host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +open Coloring Finset + +variable {F : Type} (S : Scheme F) {l : ℕ} + +open scoped Classical in +/-- The row of type `B (S.h + l)` for the given inputs. -/ +def row (hl : S.k + S.e ≤ l) (t : S.Span) : B (S.h + l) := + (Match.rowIndex S.h l).symm (t.1.2.1, ((Match.rowIndex S.k S.e).symm + (t.1.2.2, t.2)).castLE (Nat.pow_le_pow_right (by decide) hl)) + +open scoped Classical in +/-- Computes the span ord by the application `S.row le_rfl`. -/ +abbrev spanOrd := S.row le_rfl + +open scoped Classical in +/-- The span item of type `S.Span`, constructed using `Match.rowIndex S.h (S.k + S.e) j`. -/ +def spanItem (v : B S.m) (j : B (S.h + (S.k + S.e))) : S.Span := + let p := Match.rowIndex S.h (S.k + S.e) j + let q := Match.rowIndex S.k S.e p.2 + ((v, p.1, q.1), q.2) + +open scoped Classical in +/-- Returns `S.width r t` when `S.peer r t = none` holds, and `0` otherwise. -/ +def borderLen (r : S.format.obj) (t : S.Span) := + if S.peer r t = none then S.width r t else 0 + +open scoped Classical in +/-- The sum of `S.borderLen r (S.spanItem t.1.1 i)` indexed by `i with i < S.spanOrd t`. -/ +def borderStart (r : S.format.obj) (t : S.Span) := + ∑ i with i < S.spanOrd t, S.borderLen r (S.spanItem t.1.1 i) + +open scoped Classical in +@[simp] theorem spanItem_spanOrd (t : S.Span) : S.spanItem t.1.1 (S.spanOrd t) = t := by + simp [spanItem, spanOrd, row] + +open scoped Classical in +@[simp] theorem spanOrd_spanItem (v : B S.m) (j : B (S.h + (S.k + S.e))) : + S.spanOrd (S.spanItem v j) = j := by + simp [spanItem, spanOrd, row] + +open scoped Classical in +theorem ext_span {t v : S.Span} (hh : t.1.1 = v.1.1) (he : S.spanOrd t = S.spanOrd v) : t = v := by + rw [← S.spanItem_spanOrd t, hh, he, S.spanItem_spanOrd] + +open scoped Classical in +theorem rowIndex_lt {h e : ℕ} (i j : B h × B e) : + (Match.rowIndex h e).symm i < (Match.rowIndex h e).symm j ↔ + i.1 < j.1 ∨ i.1 = j.1 ∧ i.2 < j.2 := by + have hlt (x y : B h × B e) (hxy : x.1 < y.1) : + (Match.rowIndex h e).symm x < (Match.rowIndex h e).symm y := by + change x.2.val + 2 ^ e * x.1.val < y.2.val + 2 ^ e * y.1.val + have := Nat.mul_le_mul_left (2 ^ e) (show x.1.val + 1 ≤ y.1.val from hxy) + rw [mul_add, mul_one] at this + have := x.2.isLt + omega + rcases lt_trichotomy i.1 j.1 with hh|hh|hh + · exact iff_of_true (hlt _ _ hh) (.inl hh) + · change i.2.val + 2 ^ e * i.1.val < j.2.val + 2 ^ e * j.1.val ↔ _ + simp [hh] + · exact iff_of_false (hlt _ _ hh).not_gt (fun h => h.elim hh.not_gt (fun e => hh.ne e.1.symm)) + +open scoped Classical in +theorem row_less (hl : S.k + S.e ≤ l) (t u : S.Span) : + S.row hl t < S.row hl u ↔ S.spanOrd t < S.spanOrd u := by + simp [spanOrd, row, rowIndex_lt] + +variable (r : S.format.obj) + +open scoped Classical in +theorem len_at (q : S.exposed r) : S.borderLen r q.val.1 = S.width r q.val.1 := + ite_eq_left q.property + +open scoped Classical in +theorem border_le (t : S.Span) : S.borderLen r t ≤ S.load r t.1.1 := by + unfold borderLen + split_ifs with ht + · let f (i : Fin (S.width r t)) : S.fiber r t.1.1 := ⟨⟨⟨t, i⟩, ht⟩, rfl⟩ + have hi : Function.Injective f := fun _ _ h => + Fin.ext (congrArg (fun q : S.fiber r t.1.1 => q.val.val.2.val) h) + simpa only [load, Fintype.card_fin] using Fintype.card_le_of_injective f hi + · exact Nat.zero_le _ + +variable {S r} [Field F] {a b : Wire} {G : Diagram F a b} + +open scoped Classical in +theorem Presentation.border_pos (p : S.Presentation r G) (t : S.Span) : + 0 < S.borderLen r t ↔ ∃ i, (p.boundary i).val.1 = t := by + constructor + · intro h + unfold borderLen at h + split_ifs at h with he + · obtain ⟨i, hi⟩ := p.boundary.surjective ⟨⟨t, ⟨0, h⟩⟩, he⟩ + exact ⟨i, congrArg (fun z : S.exposed r => z.val.1) hi⟩ + · omega + · rintro ⟨i, rfl⟩ + rw [S.len_at] + exact Nat.zero_lt_of_lt (p.boundary i).val.2.isLt + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- +# A stage boundary with exposed bits + +The data are a short record per occurrence, any auxiliary state +needed by the next step, and a dyadic bank for the actual payload. +At initialization the records are constants and each position of the +bank reads at most one exterior bit. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +universe v +variable {F : Type} [Field F] {x y : Wire} {I : Type v} + +open scoped Classical in +/-- The data for the encoding construction, including `scheme`, `volume`, `height`, `extra`, +`data`. -/ +structure Encoding (G : I → Diagram F x y) where + /-- The `Encoding` component of type `Scheme F`. -/ + scheme : Scheme F + /-- Stores the volume associated with this `Encoding`. -/ + volume : ℕ + /-- The height parameter carried by `Encoding`, with type `ℕ`. -/ + height : ℕ + /-- The `Encoding` component of type `Format`. -/ + extra : Format + /-- The carried data of type `I → extra.obj`. -/ + data : I → extra.obj + /-- The indexed rows of type `I → scheme.format.obj`. -/ + rows : I → scheme.format.obj + /-- The `Encoding` component of type `∀ i, scheme.Presentation (rows i) (G i)`. -/ + presents : ∀ i, scheme.Presentation (rows i) (G i) + fits : ∀ i, scheme.Fits (rows i) volume height + +namespace Encoding + +variable {G : I → Diagram F x y} (E : Encoding G) + +open scoped Classical in +/-- Computes the control by the application `Format.pair E.scheme.format E.extra`. -/ +abbrev control := Format.pair E.scheme.format E.extra +open scoped Classical in +/-- Uses `Fmt.payload E.scheme.m E.volume E.height` as the representation. -/ +abbrev payload := Fmt.payload E.scheme.m E.volume E.height +open scoped Classical in +/-- Computes the port by the application `E.control.pair E.payload`. -/ +abbrev port := E.control.pair E.payload + +open scoped Classical in +/-- The value specified by `((E.rows i, E.data i), E.scheme.store (E.rows i) (E.fits i) +((E.presents i).exterior a b))`. -/ +def frame (i : I) (a : Val x) (b : Val y) : E.port.obj := + ((E.rows i, E.data i), E.scheme.store (E.rows i) (E.fits i) ((E.presents i).exterior a b)) + +open scoped Classical in +/-- Uses `⟨I, fun i => (G i).eval, E.port, E.frame⟩` as the representation. -/ +def snapshot : Snapshot.{v} F x y := + ⟨I, fun i => (G i).eval, E.port, E.frame⟩ + +open scoped Classical in +theorem width : E.port.width ≤ 2 ^ E.scheme.m * (2 ^ E.scheme.d * E.scheme.m + + 2 ^ E.scheme.h * E.scheme.ℓ) + + E.extra.width + (E.height + 1) * (2 * E.volume) := by + rw [port, Format.width_pair, control, Format.width_pair, Scheme.format, Fmt.width_rows, + Format.width_addr] + exact Nat.add_le_add_left (Fmt.width_payload _ _ _) _ + +open scoped Classical in +private theorem projected (i : I) : + Install.Depends (E.port.code ∘ (fun p => E.frame i p.1 p.2) ∘ (bits (.pair x y)).symm) 1 := by + let S := E.scheme + let r := E.rows i + let h := E.fits i + let p := E.presents i + rintro (u|u) + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + by_cases he : u ∈ Set.range (S.payload r h).wire + · obtain ⟨j, rfl⟩ := he + let z := p.boundary.symm ((S.index r h).symm j) + have hz (t : slots (.pair x y) → Bool) : + E.port.code (E.frame i ((bits (.pair x y)).symm t).1 ((bits (.pair x y)).symm t).2) + (.inr ((S.payload r h).wire j)) = t z := by + change (S.payload r h).store _ ((S.payload r h).wire j) = _ + rw [Payload.read_store, Function.comp_apply, + ← p.boundary.apply_symm_apply ((S.index r h).symm j), + p.exterior_boundary] + exact congrFun ((bits (.pair x y)).apply_symm_apply t) z + exact ⟨{z}, by simp, fun a b hab => (hz a).trans ((hab z (by simp)).trans (hz b).symm)⟩ + · refine ⟨∅, by simp, fun a b _ => ?_⟩ + exact ((S.payload r h).padding _ _ he).trans ((S.payload r h).padding _ _ he).symm + +open scoped Classical in +theorem start {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) (i : I) : + Map F u L (.wire (.pair x y)) E.port (fun p => E.frame i p.1 p.2) + (4 * (wd x + wd y + 34 * E.port.width)) := by + apply Map.circuit hu + have h := (E.projected i).bnet F + rw [card_slots] at h + exact h + +open scoped Classical in +theorem finishes {u m : ℕ} {L : Set (Table F)} {k : E.port.obj → F} + (hk : Kernel F u L E.port (.wire .unit) (fun x _ => k x) m) + (he : ∀ i t, k ((E.rows i, E.data i), E.scheme.store (E.rows i) (E.fits i) t) = + E.scheme.eval (E.rows i) t) : Finishes F u L E.snapshot m := + ⟨k, hk, fun i a b => (he i _).trans ((E.presents i).eval a b)⟩ + +end Encoding + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Grouped announcements + +Groups sharing a neighbor list exchange their messages in one record. +Processing within each group uses its own map, so assembling the record +does not require a lookup table spanning the whole processor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] {u v n m d a s t : ℕ} {L : Set (Table F)} + {I : Type*} {A H O : Format} + +open scoped Classical in +/-- Computes the groups by the application `Fmt.bank m d (.vec a A)`. -/ +abbrev Fmt.groups (m d a : ℕ) (A : Format) := Fmt.bank m d (.vec a A) + +open scoped Classical in +/-- Evaluates `((x i).1, fun j => reply ((x i).2 j, fun w => msg ((x ((x i).1 w)).2 j)))` at the +input `i`. -/ +def announce (msg : A.obj → H.obj) (reply : A.obj × (B d → H.obj) → O.obj) + (x : (Fmt.groups m d a A).obj) : (Fmt.groups m d a O).obj := + fun i => ((x i).1, fun j => reply ((x i).2 j, fun w => msg ((x ((x i).1 w)).2 j))) + +open scoped Classical in +/-- The bound obtained by adding the component charges `gatherCost m d v n + 60 * (Fmt.groups m +d a A).width + 20 * (Format.vec m (.vec d (.vec a H))).width + 2 ^ m * 2 ^ a * (s + t)`. -/ +def announceCost (m d a v n : ℕ) (A H : Format) (s t : ℕ) := + gatherCost m d v n + 60 * (Fmt.groups m d a A).width + + 20 * (Format.vec m (.vec d (.vec a H))).width + 2 ^ m * 2 ^ a * (s + t) + +open scoped Classical in +private theorem process (hu : 3 ≤ u) {f : A.obj → H.obj} (hf : Map F u L A H f s) : + Map F u L (Fmt.groups m d a A) (Fmt.groups m d a H) + (fun x i => ((x i).1, fun j => f ((x i).2 j))) + (2 ^ m * (4 * (Format.vec d (.addr m)).width + 2 ^ a * s)) := by + have keep := Map.circuit (L := L) hu (Circuit.id F (.vec d (.addr m))) + exact Map.vec _ (fun _ => keep.par (Map.vec _ (fun _ : B a => hf))) + +open scoped Classical in +theorem computes_announce (hu : 3 ≤ u) (ht : Access F u L (m + d) v n) + (hh : (Format.vec a H).width ≤ v) + (X : I → (Fmt.groups m d a A).obj) (hx : ∀ i, Fmt.Reciprocal (.vec a A) (X i)) + {msg : A.obj → H.obj} {reply : A.obj × (B d → H.obj) → O.obj} + (send : Map F u L A H msg s) (recv : Map F u L (.pair A (.vec d H)) O reply t) : + Computes F u L (Fmt.groups m d a A) (Fmt.groups m d a O) X + (fun i => announce (A := A) (H := H) (O := O) msg reply (X i)) (fun _ => 1) + (announceCost m d a v n A H s t) := by + let B₀ := Fmt.groups m d a A + let R := Format.vec m (.vec d (.vec a H)) + let Z := Fmt.groups m d a (.pair A (.vec d H)) + let Y (j : I) : (Fmt.groups m d a H).obj := + fun i => ((X j i).1, fun k => msg ((X j i).2 k)) + have first := Computes.of_map (x := X) (y := Y) (process hu send) (fun _ => rfl) + have relay := gather_neighbors (L := L) (.vec a H) hu ht hh Y hx + have keep := Computes.of_map (x := X) (y := X) (Map.circuit (L := L) hu (Circuit.id F B₀)) + (fun _ => rfl) + let zip (x : (Format.pair B₀ R).obj) : Z.obj := + fun i => ((x.1 i).1, fun j => ((x.1 i).2 j, fun w => x.2 i w j)) + have stage : Circuit F (.pair B₀ R) Z zip ((Format.pair B₀ R).width + 2 * Z.width) := by + let pins : Z.pins → (Format.pair B₀ R).pins + | (i, .inl q) => .inl (i, .inl q) + | (i, .inr (j, .inl q)) => .inl (i, .inr (j, q)) + | (i, .inr (j, .inr (w, q))) => .inr (i, w, j, q) + apply Circuit.project pins + rintro x ⟨i, q | ⟨j, q | ⟨w, q⟩⟩⟩ <;> rfl + have post := (Map.circuit hu stage).comp (process (m := m) (a := a) (d := d) hu recv) + have mid := keep.pair hu (first.comp relay) + have h := mid.comp (Computes.of_map post (y := fun i => + announce (A := A) (H := H) (O := O) msg reply (X i)) (fun _ => rfl)) + simp only [one_mul] at h + refine h.mono ?_ + simp only [announceCost, B₀, R, Z, Fmt.groups, Fmt.bank, Format.width_pair, Format.width_vec] + ring_nf + omega + +namespace Match +variable {h e k ℓ : ℕ} + +open scoped Classical in +/-- The value specified by `Format.pair .bit (.pair (.vec h .bit) (.vec h (Fmt.occ d h e k +ℓ)))`. -/ +abbrev Initial (d h e k ℓ : ℕ) := + Format.pair .bit (.pair (.vec h .bit) (.vec h (Fmt.occ d h e k ℓ))) + +open scoped Classical in +/-- The value specified by `Format.vec h (.addr ℓ)`. -/ +abbrev Tags (h ℓ : ℕ) := Format.vec h (.addr ℓ) + +open scoped Classical in +/-- Evaluates `(x.2.2 i).1` at the input `i`. -/ +def tags (x : (Initial d h e k ℓ).obj) : (Tags h ℓ).obj := fun i => (x.2.2 i).1 + +open scoped Classical in +/-- The indexed operation `(x.1.1, x.1.2.1, x.1.2.2, fun i j => x.2 j i)`. -/ +def prepare (x : (Initial d h e k ℓ).obj × (B d → (Tags h ℓ).obj)) : + (Format.pair .bit (Input d h e k ℓ)).obj := + (x.1.1, x.1.2.1, x.1.2.2, fun i j => x.2 j i) + +open scoped Classical in +/-- The value specified by `announce (A := Initial d h e k ℓ) (H := Tags h ℓ) (O := .pair .bit +(Input d h e k ℓ)) tags prepare x`. -/ +def prepared (x : (Fmt.groups m d a (Initial d h e k ℓ)).obj) := + announce (A := Initial d h e k ℓ) (H := Tags h ℓ) (O := .pair .bit (Input d h e k ℓ)) + tags prepare x + +open scoped Classical in +/-- The construction uses `Initial d h e k ℓ` for its intermediate `A`. -/ +def prepareCost (m d a h e k ℓ v n : ℕ) := + let A := Initial d h e k ℓ + let H := Tags h ℓ + let O := Format.pair .bit (Input d h e k ℓ) + announceCost m d a v n A H (4 * (A.width + 2 * H.width)) + (4 * ((Format.pair A (.vec d H)).width + 2 * O.width)) + +open scoped Classical in +theorem computes_prepared (hu : 3 ≤ u) (ht : Access F u L (m + d) v n) + (hh : (Format.vec a (Tags h ℓ)).width ≤ v) + (X : I → (Fmt.groups m d a (Initial d h e k ℓ)).obj) + (hx : ∀ i, Fmt.Reciprocal (.vec a (Initial d h e k ℓ)) (X i)) : + Computes F u L (Fmt.groups m d a (Initial d h e k ℓ)) + (Fmt.groups m d a (.pair .bit (Input d h e k ℓ))) X (prepared ∘ X) (fun _ => 1) + (prepareCost m d a h e k ℓ v n) := by + let A := Initial d h e k ℓ + let H := Tags h ℓ + let D := Format.pair A (.vec d H) + let O := Format.pair .bit (Input d h e k ℓ) + have send : Circuit F A H tags (A.width + 2 * H.width) := + Circuit.project (fun i => .inr (.inr (i.1, .inl i.2))) (fun _ _ => rfl) + have recv : Circuit F D O prepare (D.width + 2 * O.width) := by + let idx : O.pins → D.pins + | .inl i => .inl (.inl i) + | .inr (.inl i) => .inl (.inr (.inl i)) + | .inr (.inr (.inl i)) => .inl (.inr (.inr i)) + | .inr (.inr (.inr (j, l, i))) => .inr (l, j, i) + apply Circuit.project idx + rintro x (i | i | i | ⟨j, l, i⟩) <;> rfl + exact computes_announce hu ht hh X hx (Map.circuit hu send) (Map.circuit hu recv) + +open scoped Classical in +/-- The value specified by `Format.vec h (Move d ℓ)`. -/ +abbrev Messages (d h ℓ : ℕ) := Format.vec h (Move d ℓ) +open scoped Classical in +/-- The quantity computed by `Format.vec (h + e) (Report d ℓ)`. -/ +abbrev Reports (d h e ℓ : ℕ) := Format.vec (h + e) (Report d ℓ) + +open scoped Classical in +/-- The indexed operation `announce (A := Directed d h e k ℓ) (H := Messages d h ℓ) (O := +Reports d h e ℓ) (fun y => action y.1 y.2) report x`. -/ +def announced (x : (Fmt.groups m d a (Directed d h e k ℓ)).obj) := + announce (A := Directed d h e k ℓ) (H := Messages d h ℓ) (O := Reports d h e ℓ) + (fun y => action y.1 y.2) report x + +open scoped Classical in +/-- The bound obtained by adding the component charges `announceCost m d a v n (Directed d h e k +ℓ) (Messages d h ℓ) (4 * (2 ^ (h + e) * (100 + t) ^ 180)) (4 * (2 ^ (h + e) * (100 + t) ^ +220))`. -/ +def reportCost (m d a h e k ℓ v n t : ℕ) := + announceCost m d a v n (Directed d h e k ℓ) (Messages d h ℓ) + (4 * (2 ^ (h + e) * (100 + t) ^ 180)) (4 * (2 ^ (h + e) * (100 + t) ^ 220)) + +open scoped Classical in +private theorem of_cheap {s t c : ℕ} {f : A.obj → H.obj} (hu : 3 ≤ u) + (hc : Cheap F s t A H f c) : Map F u L A H f (4 * (2 ^ s * (100 + t) ^ c)) := by + obtain ⟨q, hq, hb⟩ := hc + exact (Map.circuit hu hq).mono (Nat.mul_le_mul_left _ ((Nat.le_add_left _ _).trans hb)) + +open scoped Classical in +theorem computes_announced (hu : 3 ≤ u) (ht : Access F u L (m + d) v n) + (hh : (Format.vec a (Messages d h ℓ)).width ≤ v) + (ho : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) (hw : k ≤ t) (hd : 2 ^ d ≤ t) + (X : I → (Fmt.groups m d a (Directed d h e k ℓ)).obj) + (hx : ∀ i, Fmt.Reciprocal (.vec a (Directed d h e k ℓ)) (X i)) : + Computes F u L (Fmt.groups m d a (Directed d h e k ℓ)) (Fmt.groups m d a (Reports d h e ℓ)) + X (announced ∘ X) (fun _ => 1) (reportCost m d a h e k ℓ v n t) := + computes_announce hu ht hh X hx (of_cheap hu (cheap_action F d h e k ℓ t ho hw hd)) + (of_cheap hu (cheap_report F d h e k ℓ t ho hw hd)) + +open scoped Classical in +/-- Agreement on the layout bit within a group suffices. The output +contains the forward and untouched masks, both old ends and all parties. -/ +theorem announced_eq (x : (Fmt.groups m d a (Directed d h e k ℓ)).obj) (j : B a) + (col : Bool) (hc : ∀ v, ((x v).2 j).1 = col) (v : B m) (i : B (h + e)) : + let nav := fun w => (x w).1 + let data := fun w => ((x w).2 j).2 + let q := rows (data v) + (announced x v).2 j i = + (q.control.1 i, q.active i && !(q.control.1 i) && !(q.control.1 (q.control.2 i)), + localEnds nav data col v i, fun z => localParties nav data col v i (partyIndex z)) := by + simp only [announced, announce, report, hereEnds, hc, localParties, localEnds] + +open scoped Classical in +/-- Two whole-record transfers suffice for all groups at once. The +processing between transfers is trivalent. -/ +theorem computes_reports (hu : 3 ≤ u) (ht : Access F u L (m + d) v n) + (hh : (Format.vec a (Messages d h ℓ)).width ≤ v) + (ho : Rows.overhead (h + e) (Labels h ℓ d).width ≤ t) (hw : k ≤ t) (hd : 2 ^ d ≤ t) + (X : I → (Fmt.groups m d a (Initial d h e k ℓ)).obj) + (hx : ∀ i, Fmt.Reciprocal (.vec a (Initial d h e k ℓ)) (X i)) : + Computes F u L (Fmt.groups m d a (Initial d h e k ℓ)) (Fmt.groups m d a (Reports d h e ℓ)) + X (announced ∘ prepared ∘ X) (fun _ => 1) + (prepareCost m d a h e k ℓ v n + reportCost m d a h e k ℓ v n t) := by + have htags : (Format.vec a (Tags h ℓ)).width ≤ v := by + refine le_trans ?_ hh + simp only [Tags, Messages, Format.width_vec, Move, Format.width_pair, Format.width_addr] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ (by omega)) + have labels := computes_prepared (L := L) hu ht htags X hx + have result := computes_announced (L := L) hu ht hh ho hw hd (prepared ∘ X) hx + simpa only [mul_one] using labels.comp result + +end Match +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Shipment/Bound.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Shipment/Bound.lean new file mode 100644 index 0000000000..90ccea1fb8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Shipment/Bound.lean @@ -0,0 +1,1012 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Spans +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.PayloadProgram +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment + +/-! # Reuse one old label to program a station or a relay -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring Chain.Frame + +variable {F : Type} (S : Scheme F) + +open scoped Classical in +/-- The quantity computed by `Format.pair .bit (.pair .bit (.pair (.addr 3) (.addr (1 + e))))`. -/ +abbrev terminal (e : ℕ) := Format.pair .bit (.pair .bit (.pair (.addr 3) (.addr (1 + e)))) + +open scoped Classical in +/-- The quantity computed by `Format.pair .bit (.pair (.pair (.addr S.ℓ) (.addr S.k)) (.vec (1 + +S.e) (terminal S.e)))`. -/ +abbrev script := Format.pair .bit (.pair (.pair (.addr S.ℓ) (.addr S.k)) (.vec (1 + + S.e) (terminal S.e))) + +open scoped Classical in +theorem script_width : (script S).width = 1 + ((S.ℓ + S.k) + 2 ^ (1 + S.e) * (1 + (1 + (3 + (1 + + S.e))))) := by + simp only [script, terminal, Format.width_pair, Format.width_addr, Format.width_vec] + rw [Format.width_bit, Format.width_addr] + +open scoped Classical in +/-- The value specified by `(script S).obj`. -/ +abbrev Script := (script S).obj + +namespace Script +variable {S} (a : Script S) + +open scoped Classical in +/-- The indexed operation `(false, (0, 0), fun _ => (false, false, 0, 0))`. -/ +def vacant (S : Scheme F) : Script S := (false, (0, 0), fun _ => (false, false, 0, 0)) + +open scoped Classical in +/-- The value specified by `((pair e).symm j).1`. -/ +def dir {e : ℕ} (j : B (1 + e)) := ((pair e).symm j).1 + +open scoped Classical in +/-- The value specified by `((pair e).symm j).2`. -/ +def channel {e : ℕ} (j : B (1 + e)) := ((pair e).symm j).2 + +open scoped Classical in +/-- Returns `(S.decode a.2.1.1).width a.2.1.2 (channel i)` when `(a.2.2 i).1` holds, and `0` +otherwise. -/ +def size (i : B (1 + S.e)) := + if (a.2.2 i).1 then (S.decode a.2.1.1).width a.2.1.2 (channel i) else 0 + +open scoped Classical in +/-- Returns `some ((a.2.2 i).2.2.1, 0, (a.2.2 i).2.2.2)` when `(a.2.2 i).2.1` holds, and `none` +otherwise. -/ +def peer (i : B (1 + S.e)) : Option (B 3 × B 0 × B (1 + S.e)) := + if (a.2.2 i).2.1 then some ((a.2.2 i).2.2.1, 0, (a.2.2 i).2.2.2) else none + +open scoped Classical in +/-- A total reader lets the decoder use an ordinary integer offset. -/ +def read (z : ∀ i, Fin (size a i) → Bool) (j : B (1 + S.e)) (n : ℕ) := + if h : n < size a j then z j ⟨n, h⟩ else false + +variable [Field F] + +open scoped Classical in +/-- The test of type `F`, constructed using `S.decode a.2.1.1`. -/ +def test (z : B (1 + S.e) → ℕ → Bool) : F := + let p := S.decode a.2.1.1 + let k := a.2.1.2 + if a.1 then p.value k (fun j i => z (pair S.e (p.direction k j, j)) i.val) + else if ∀ j n, n < size a (pair S.e (true, j)) → + z (pair S.e (true, j)) n = z (pair S.e (false, j)) n then 1 else 0 + +open scoped Classical in +/-- Builds `Pattern F 3 0 (1 + S.e) where width _` with the specified `width`, `direction`, +`peer`, `value`. -/ +def pattern : Pattern F 3 0 (1 + S.e) where + width _ := size a + direction _ := dir + peer _ := peer a + value _ z := test a (read a z) + +open scoped Classical in +/-- The quantity computed by `⟨m, 3, h, 0, 1 + S.e, (script S).width, fun i => pattern ((script +S).serial.symm i)⟩`. -/ +abbrev scheme (S : Scheme F) (m h : ℕ) : Scheme F := + ⟨m, 3, h, 0, 1 + S.e, (script S).width, fun i => pattern ((script S).serial.symm i)⟩ + +end Script + +namespace Chain.Frame +variable [Field F] {x y : Wire} {G : Diagram F x y} {V : Type} [Fintype V] + {C : Chain G V} (f : C.Frame) {S} {r : S.format.obj} (p : S.Presentation r G) + (index : V → V → B 3) +local notation "H" => C.graph + +open scoped Classical in +/-- The token of type `B S.ℓ × B S.k`, constructed using `p.vertex v`. -/ +def token (v : G.V) : B S.ℓ × B S.k := + let t := p.vertex v + ((r t.1).2 t.2.1, t.2.2) + +open scoped Classical in +/-- In the case `some (w, i)`, this construction gives `(true, true, index v w, i)`. -/ +def entry (v : V) (j : B (1 + S.e)) : (terminal S.e).obj := + if h : ∃ q, f.mark p q = (v, j) then + match (opposite H h.choose).map (f.mark p) with + | some (w, i) => (true, true, index v w, i) + | none => (true, false, 0, 0) + else (false, false, 0, 0) + +open scoped Classical in +/-- The indexed operation `(decide (v ∈ Set.range C.owner), Function.extend C.owner (token p) +(fun _ => (0, 0)) (f.root v), f.entry p index v)`. -/ +def encode (v : V) : Script S := + (decide (v ∈ Set.range C.owner), Function.extend C.owner (token p) (fun _ => (0, 0)) (f.root v), + f.entry p index v) + +open scoped Classical in +theorem token_eq (v : V) (u : G.V) (hu : f.root v = C.owner u) : + (f.encode p index v).2.1 = token p u := by + unfold encode + rw [hu, f.one.extend_apply] + +open scoped Classical in +theorem entry_eq (hd : p.Directed) (q : (H).End) : + f.entry p index ((H).station q) (f.lane p q) = + match (opposite H q).map (f.mark p) with + | some (w, i) => (true, true, index ((H).station q) w, i) + | none => (true, false, 0, 0) := by + have h : ∃ z, f.mark p z = ((H).station q, f.lane p q) := ⟨q, rfl⟩ + rw [entry, dite_eq_left h, f.contacts p hd (q' := q) h.choose_spec] + +open scoped Classical in +theorem marked (v : V) (j : B (1 + S.e)) : + (f.entry p index v j).1 = true ↔ ∃ q, f.mark p q = (v, j) := by + unfold entry + split + · rename_i h + split <;> exact iff_of_true rfl h + · exact iff_of_false Bool.false_ne_true (by assumption) + +open scoped Classical in +theorem old_at (q : (H).End) : (f.old p q).1.1 = p.vertex (G.station (f.ref q)) := by + unfold old + obtain ⟨⟨u, i⟩, he⟩ := G.portEquiv.surjective (f.ref q) + rw [← he, Scheme.Seating.ends_at, G.station_port]; rfl + +open scoped Classical in +theorem dir_lane (q : (H).End) : Script.dir (f.lane p q) = q.isRight := + congrArg Prod.fst ((pair S.e).symm_apply_apply _) + +open scoped Classical in +theorem length (q : (H).End) : + Script.size (f.encode p index ((H).station q)) (f.lane p q) = S.width r (f.old p q).1 := by + have active := (f.marked p index _ _).mpr ⟨q, rfl⟩ + change ((f.encode p index ((H).station q)).2.2 (f.lane p q)).1 = true at active + rw [Script.size, ite_eq_left active, f.token_eq p index _ _ (f.anchor q)] + unfold Scheme.width Scheme.pattern token + rw [old_at] + simp only [Script.channel, lane, Equiv.symm_apply_apply] + +open scoped Classical in +theorem ordinal (q : (H).End) : + f.offset p q < Script.size (f.encode p index ((H).station q)) (f.lane p q) := by + rw [length]; exact (f.old p q).2.isLt + +open scoped Classical in +theorem used (hd : p.Directed) (v : V) (j : B (1 + S.e)) (n : ℕ) + (hn : n < Script.size (f.encode p index v) j) : + ∃ q, f.mark p q = (v, j) ∧ f.offset p q = n := by + have ha : (f.entry p index v j).1 = true := by + by_contra h + simp [Script.size, encode, h] at hn + obtain ⟨q, hq⟩ := (f.marked p index v j).mp ha + obtain ⟨rfl, rfl⟩ := Prod.mk.inj hq + rw [length] at hn + exact f.covers p hd q n hn + +open scoped Classical in +theorem peer_used {v : V} {j : B (1 + S.e)} + (hn : Script.peer (f.encode p index v) j ≠ none) : ∃ q, f.mark p q = (v, j) := by + by_contra h + simp [Script.peer, encode, entry, h] at hn + +end Chain.Frame +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Checking the truth table of a restored station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Chain.Frame +open Coloring Finset + +variable {F : Type} [Field F] {x y : Wire} {G : Diagram F x y} {V : Type} [Fintype V] + {C : Chain G V} (f : C.Frame) {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G) + (index : V → V → B 3) +local notation "H" => C.graph + +open scoped Classical in +theorem lane_pass (t : C.Turn) (b : Bool) : + f.lane p (C.relay t b) = pair S.e (b, (p.toSeating.ends (f.fromTurn t)).1.2) := by + rw [lane, C.side_relay t b, old, pass] + +open scoped Classical in +theorem offset_pass (t : C.Turn) (b : Bool) : + f.offset p (C.relay t b) = (p.toSeating.ends (f.fromTurn t)).2.val := by + rw [offset, old, pass] + +open scoped Classical in +/-- Computes the listener by the application `z (f.lane p q) (f.offset p q)`. -/ +def listener (z : B (1 + S.e) → ℕ → Bool) (q : (H).End) := z (f.lane p q) (f.offset p q) + +open scoped Classical in +private theorem relay_test (hd : p.Directed) (v : V) (hv : v ∉ Set.range C.owner) + (z : B (1 + S.e) → ℕ → Bool) : + (∀ j n, n < Script.size (f.encode p index v) (pair S.e (true, j)) → + z (pair S.e (true, j)) n = z (pair S.e (false, j)) n) ↔ + ∀ t, C.joint t = v → f.listener p z (C.relay t true) = f.listener p z (C.relay t false) := by + constructor + · intro hs t ht + have hn := f.ordinal p index (C.relay t true) + rw [C.station_relay, ht, lane_pass, offset_pass] at hn + simp only [listener, lane_pass, offset_pass] + exact hs _ _ hn + · intro hs j n hn + obtain ⟨q, hq, hm⟩ := f.used p index hd v _ _ hn + obtain ⟨he, hl⟩ := Prod.mk.inj hq + rcases C.cases_end q with ⟨i, rfl⟩|⟨t, b, rfl⟩ + · exact (hv ⟨_, (C.station_original i).symm.trans he⟩).elim + rw [C.station_relay] at he + rw [lane_pass] at hl + rw [offset_pass] at hm + obtain ⟨_, hj⟩ := Prod.mk.inj ((pair _).injective hl) + simpa only [listener, lane_pass, offset_pass, hj, hm] using hs t he + +open scoped Classical in +theorem eval_script (hd : p.Directed) (v : V) (z : B (1 + S.e) → ℕ → Bool) : + Script.test (f.encode p index v) z = value H v (f.listener p z) := by + rw [C.test] + by_cases hv : v ∈ Set.range C.owner + · obtain ⟨u, rfl⟩ := hv + have no (t : C.Turn) : C.joint t ≠ C.owner u := by + intro he; exact f.away t (he.symm ▸ f.fix u) + have empty (t : C.Turn) (ht : C.joint t = C.owner u) : + f.listener p z (C.relay t true) = f.listener p z (C.relay t false) := (no t ht).elim + rw [ite_eq_left empty, mul_one, prod_eq_single (⟨u, rfl⟩ : {w // C.owner w = C.owner u})] + · have yes : (f.encode p index (C.owner u)).1 = true := decide_eq_true ⟨u, rfl⟩ + rw [Script.test, ite_eq_left yes, token_eq _ _ _ _ _ (f.fix u)] + let a : S.LocalPin r (p.vertex u) → Bool := fun i => + z (pair S.e (S.direction r (p.vertex u, i.1), i.1)) i.2.val + change S.table r (p.vertex u) a = _ + rw [p.sample] + apply congrArg (Transcript.sample (G.table u)) + funext i + change a (p.pin u i) = f.listener p z (C.original (G.portEquiv ⟨u, i⟩)) + rw [listener, lane, offset, C.side_original, old, orig, ← hd, Scheme.Seating.ends_at] + rfl + · exact fun i _ hi => (hi (Subtype.ext (f.one i.property))).elim + · simp + · have no : ¬(f.encode p index v).1 = true := by simpa [encode] using hv + have eq : (∏ w : {w // C.owner w = v}, value G w (f.listener p z ∘ C.original)) = 1 := + prod_eq_one fun i _ => (hv ⟨i.val, i.property⟩).elim + rw [eq, one_mul, Script.test, ite_eq_right no] + exact if_congr (f.relay_test p index hd v hv z) rfl rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Chain.Frame +end + +/- # Reading the directed chains from their local records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +open Coloring + +variable {F : Type} [Field F] {x y : Wire} {G : Diagram F x y} {V : Type} [Fintype V] + {C : Chain G V} (f : C.Frame) {S : Scheme F} {r : S.format.obj} (p : S.Presentation r G) + {m h : ℕ} (out : (Script.scheme S m h).format.obj) +local notation "H" => C.graph +local notation "U" => Script.scheme S m h + +open scoped Classical in +/-- The data for the written construction, including `vertex`, `index`, `dir`, `code`, `idle`. -/ +structure Written where + /-- The placement of the vertices carried by `Written`, with type `V ↪ (U).Vtx`. -/ + vertex : V ↪ (U).Vtx + /-- The identification of the indices of type `V → V → B 3`. -/ + index : V → V → B 3 + dir : p.Directed + code : ∀ v, (U).pattern out (vertex v) = Script.pattern (f.encode p index v) + idle : ∀ v ∉ Set.range vertex, (U).pattern out v = Script.pattern (Script.vacant S) + nav : ∀ (i : C.Edge) (b : Bool), + let v := endpoint H i b + let w := endpoint H i (!b) + ((out (vertex v).1).1 (index v w), (vertex v).2.1, 0) = vertex w + +namespace Written +variable {f p out} (a : Written f p out) + +open scoped Classical in +/-- The value specified by `(a.vertex ((H).station q), f.lane p q)`. -/ +def span (q : (H).End) : (U).Span := (a.vertex ((H).station q), f.lane p q) + +open scoped Classical in +theorem width (v : V) (j : B (1 + S.e)) : + (U).width out (a.vertex v, j) = Script.size (f.encode p a.index v) j := by + unfold Scheme.width; rw [a.code]; rfl + +open scoped Classical in +theorem size (q : (H).End) : (U).width out (a.span q) = S.width r (f.old p q).1 := by + unfold span; rw [width, Chain.Frame.length] + +open scoped Classical in +theorem side (q : (H).End) : (U).direction out (a.span q) = q.isRight := by + unfold span Scheme.direction; rw [a.code] + exact f.dir_lane p q + +open scoped Classical in +/-- The address of type `(U).LocalPin out (a.vertex v)`, constructed using `(H).portEquiv ⟨v, +i⟩`. -/ +def address (v : V) (i : (H).Port v) : (U).LocalPin out (a.vertex v) := + let e := (H).portEquiv ⟨v, i⟩ + ⟨f.lane p e, ⟨f.offset p e, by + rw [a.width] + exact (f.ordinal p a.index e).trans_eq (congrArg (fun w + => Script.size (f.encode p a.index w) (f.lane p e)) ((H).station_port ⟨v, i⟩))⟩⟩ + +open scoped Classical in +theorem bijective (v : V) : Function.Bijective (a.address v) := by + constructor + · intro i j he + have ht : (H).portEquiv ⟨v, i⟩ = (H).portEquiv ⟨v, j⟩ := by + apply f.mark_inj p _ (congrArg (fun z => z.2.val) he) + refine Prod.ext ?_ (congrArg Sigma.fst he) + exact ((H).station_port ⟨v, i⟩).trans ((H).station_port ⟨v, j⟩).symm + exact eq_of_heq (Sigma.mk.inj ((H).portEquiv.injective ht)).2 + · rintro ⟨j, n⟩ + obtain ⟨e, he, hn⟩ := f.used p a.index a.dir v j n.val (n.isLt.trans_eq (a.width v j)) + obtain ⟨hv, hj⟩ := Prod.mk.inj he + obtain ⟨⟨u, i⟩, rfl⟩ := (H).portEquiv.surjective e + rw [Diagram.station_port] at hv + change u = v at hv + subst u + exact ⟨i, Sigma.ext hj ((Fin.heq_ext_iff (congrArg (fun j => (U).width out (a.vertex v, + j)) hj)).mpr hn)⟩ + +open scoped Classical in +private theorem eval_pattern (b : Script S) (q : Pattern F 3 0 (1 + S.e)) (hq : q + = Script.pattern b) + (j : B 0) (x : ∀ i, Fin (q.width j i) → Bool) : + q.value j x = Script.test b (fun i n => if h : n < q.width j i then x i ⟨n, h⟩ else false) := + by subst q; rfl + +open scoped Classical in +/-- Builds `(U).Seating out H where vertex` with the specified `vertex`, `pin`, `cover`, +`by_contra`. -/ +def seating : (U).Seating out H where + vertex := a.vertex + pin v := Equiv.ofBijective _ (a.bijective v) + cover q := by + by_contra hv + have hn := Nat.zero_lt_of_lt q.2.isLt + unfold Scheme.width at hn + rw [a.idle _ hv] at hn + exact Nat.not_lt_zero _ hn + sample v x := by + let z (i : B (1 + S.e)) (n : ℕ) := + if t : n < (U).width out (a.vertex v, i) then x ⟨i, ⟨n, t⟩⟩ else false + have hw : (U).table out (a.vertex v) x = Script.test (f.encode p a.index v) z := + eval_pattern _ _ (a.code v) _ (fun i j => x ⟨i, j⟩) + rw [hw, f.eval_script p a.index a.dir] + apply congrArg (Transcript.sample ((H).table v)) + funext i + change z (a.address v i).1 (a.address v i).2.val = x (a.address v i) + unfold z + rw [dite_eq_left (a.address v i).2.isLt] + vacant v hv x := by + unfold Scheme.table + rw [eval_pattern _ _ (a.idle v hv)] + simp [Script.test, Script.vacant, Script.size] + +open scoped Classical in +theorem ends (q : (H).End) : + (a.seating.ends q).1 = a.span q ∧ (a.seating.ends q).2.val = f.offset p q := by + obtain ⟨⟨v, i⟩, rfl⟩ := (H).portEquiv.surjective q + rw [Scheme.Seating.ends_at, span, Diagram.station_port] + exact ⟨rfl, rfl⟩ + +end Written +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore +end + +/- # Recovering all internal and exposed spans from the short record -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Written +open Coloring Chain.Frame + +variable {F : Type} [Field F] {x y : Wire} {G : Diagram F x y} {V : Type} [Fintype V] + {C : Chain G V} {f : C.Frame} {S : Scheme F} {r : S.format.obj} {p : S.Presentation r G} + {m h : ℕ} {out : (Script.scheme S m h).format.obj} (a : Written f p out) +local notation "H" => C.graph +local notation "U" => Script.scheme S m h + +open scoped Classical in +theorem peer (q : (H).End) : (U).peer out (a.span q) = (opposite H q).map a.span := by + unfold Scheme.peer span + rw [a.code] + change (Script.peer (f.encode p a.index ((H).station q)) (f.lane p q)).map _ = _ + let pin (v : (terminal S.e).obj) : Option (B 3 × B 0 × B (1 + S.e)) := + if v.2.1 then some (v.2.2.1, 0, v.2.2.2) else none + change (pin (f.entry p a.index ((H).station q) (f.lane p q))).map _ = _ + rw [f.entry_eq p a.index a.dir q] + rcases either q with ⟨i, rfl⟩|⟨e, b, rfl⟩ + · cases i <;> rfl + rw [opposite_tip] + change some (((out (a.vertex ((H).station (tip H e b))).1).1 + (a.index ((H).station (tip H e b)) ((H).station (tip H e (!b)))), + (a.vertex ((H).station (tip H e b))).2.1, 0), _) = + some (a.vertex ((H).station (tip H e (!b))), _) + rw [station_tip, station_tip, a.nav] + rfl + +open scoped Classical in +private theorem source {q : (U).Span} (he : (U).peer out q ≠ none) : + ∃ z, a.span z = q := by + obtain ⟨v, j⟩ := q + unfold Scheme.peer at he + by_cases hv : v ∈ Set.range a.vertex + · obtain ⟨z, rfl⟩ := hv + rw [a.code] at he + have hj : Script.peer (f.encode p a.index z) j ≠ none := by + intro ht + apply he + change (Script.peer (f.encode p a.index z) j).map _ = none + rw [ht]; rfl + obtain ⟨q, hq⟩ := f.peer_used p a.index hj + exact ⟨q, congrArg (fun t => (a.vertex t.1, t.2)) hq⟩ + · rw [a.idle _ hv] at he + exact (he rfl).elim + +open scoped Classical in +theorem internal_size (e : C.Edge) (b : Bool) : + (U).width out (a.span (tip H e b)) = S.width r (p.wirePin e.1 false).1 := by + rw [a.size, old_tip] + cases f.leg e b + · rfl + · exact (p.proper _ _ (p.internal _).1).2.1.symm + +open scoped Classical in +theorem offset_tip (e : C.Edge) (b : Bool) : + f.offset p (tip H e b) = (p.wirePin e.1 false).2.val := by + rw [offset, old_tip] + cases f.leg e b + · rfl + · exact (p.internal _).2.symm + +include a in +open scoped Classical in +theorem proper : (U).Proper out := by + intro i j he + obtain ⟨q, rfl⟩ := a.source (q := i) (by rw [he]; simp) + rw [peer] at he + rcases either q with ⟨k, rfl⟩|⟨e, b, rfl⟩ + · cases k <;> cases he + rw [opposite_tip, Option.map_some, Option.some.injEq] at he + subst j + rw [peer, opposite_tip, Bool.not_not, a.internal_size, a.internal_size, a.side, a.side, side_tip, + side_tip] + exact ⟨rfl, rfl, by cases b <;> decide⟩ + +open scoped Classical in +/-- Builds `(U).Presentation out H where toSeating` with the specified `toSeating`, `proper`, +`internal`, `change`. -/ +def presentation : (U).Presentation out H where + toSeating := a.seating + proper := a.proper + internal e := by + change (U).Joins out (a.seating.ends (tip H e false)) (a.seating.ends (tip H e true)) + constructor + · rw [(a.ends _).1, (a.ends _).1, peer, opposite_tip]; rfl + · rw [(a.ends _).2, (a.ends _).2, offset_tip, offset_tip] + input i := by rw [(a.ends _).1, peer]; rfl + output i := by rw [(a.ends _).1, peer]; rfl + +open scoped Classical in +theorem directed : a.presentation.Directed := by + intro t + exact (congrArg ((U).direction out) (a.ends t).1).trans (a.side t) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Restore.Written +end + +section +/- +# Cost scales for payload movement + +The address length occurs in the cost per host and contact. +The charges per span and per payload bit use only short widths. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Shipment +open BatchDescent.Phase + +/-- The data for the size construction, including `m`, `V`, `k`, `m'`, `V'`. -/ +structure Size where + /-- The `Size` field of type `ℕ`. -/ + m : ℕ + /-- The `Size` field of type `ℕ`. -/ + V : ℕ + /-- The `Size` field of type `ℕ`. -/ + k : ℕ + /-- The `Size` field of type `ℕ`. -/ + m' : ℕ + /-- The `Size` field of type `ℕ`. -/ + V' : ℕ + /-- The `Size` field of type `ℕ`. -/ + k' : ℕ + /-- The `Size` field of type `ℕ`. -/ + p : ℕ + /-- The `Size` field of type `ℕ`. -/ + l : ℕ + /-- The `Size` field of type `ℕ`. -/ + n : ℕ + /-- The `Size` field of type `ℕ`. -/ + W : ℕ + /-- The `Size` field of type `ℕ`. -/ + w : ℕ + /-- The `Size` field of type `ℕ`. -/ + v : ℕ + +namespace Size +variable (i : Size) +/-- The quantity computed by `1000 + i.W + i.k + i.k'`. -/ +abbrev outer := 1000 + i.W + i.k + i.k' +/-- The quantity computed by `1000 + i.W + i.k + i.k' + i.p + i.l + i.n`. -/ +abbrev short := 1000 + i.W + i.k + i.k' + i.p + i.l + i.n +/-- The quantity computed by `i.short + i.m + i.m' + i.w + i.v`. -/ +abbrev long := i.short + i.m + i.m' + i.w + i.v +/-- The quantity computed by `2 ^ i.m + 2 ^ i.m'`. -/ +abbrev hosts := 2 ^ i.m + 2 ^ i.m' +/-- The quantity computed by `i.hosts * 2 ^ i.p`. -/ +abbrev links := i.hosts * 2 ^ i.p +/-- The quantity computed by `i.links * 2 ^ i.n`. -/ +abbrev slots := i.links * 2 ^ i.n +/-- The quantity computed by `i.V + i.V'`. -/ +abbrev volume := i.V + i.V' +/-- The maximum of the quantities in `i.k i.k'`. -/ +abbrev q := max i.k i.k' +/-- The value specified by `PeerLayout.height i.m i.k i.m' i.k' i.p`. -/ +abbrev height := PeerLayout.height i.m i.k i.m' i.k' i.p +/-- The quantity computed by `i.links * i.long ^ s + i.slots * i.short ^ s`. -/ +abbrev bound (s : ℕ) := i.links * i.long ^ s + i.slots * i.short ^ s + +theorem outer_two : 2 ≤ i.outer := by unfold outer; omega +theorem outer_le : i.outer ≤ i.short := by unfold outer short; omega +theorem two : 2 ≤ i.short := by unfold short; omega +theorem le_long : i.short ≤ i.long := by unfold long; omega +theorem two_long : 2 ≤ i.long := i.two.trans i.le_long + +private def workCharges : List (ℕ × ℕ) := [(i.links, i.long), (i.slots, i.short)] + +private def heavyCharges : List (ℕ × ℕ) := i.workCharges ++ [(i.volume, i.outer)] + +private theorem workCharges_short (charge : ℕ × ℕ) (h : charge ∈ i.workCharges) : + i.short ≤ charge.2 := by + simp only [workCharges, List.mem_cons, List.not_mem_nil, or_false] at h + rcases h with rfl | rfl + · exact i.le_long + · exact le_rfl + +private theorem heavyCharges_outer (charge : ℕ × ℕ) (h : charge ∈ i.heavyCharges) : + i.outer ≤ charge.2 := by + rw [heavyCharges, List.mem_append, List.mem_singleton] at h + rcases h with h | rfl + · exact i.outer_le.trans (i.workCharges_short charge h) + · exact le_rfl + +end Size + +/-- Computes the short by the application `Poly Size.short`. -/ +abbrev Short := Poly Size.short +/-- Computes the long by the application `Poly Size.long`. -/ +abbrev Long := Poly Size.long +/-- The condition `∃ s : ℕ, ∀ i, f i ≤ i.bound s` on the specified data. -/ +def Work (f : Size → ℕ) := ∃ s : ℕ, ∀ i, f i ≤ i.bound s + +variable {f g : Size → ℕ} +theorem Short.long (h : Short f) : Long f := h.grow Size.le_long + +theorem num (s : ℕ) : Short (fun _ => s) := Poly.const Size.two s +theorem k : Short Size.k := Poly.of_le Size.two (fun i => by unfold Size.short; omega) +theorem k' : Short Size.k' := Poly.of_le Size.two (fun i => by unfold Size.short; omega) +theorem q : Short Size.q := (k.add k').mono (fun _ + => max_le (Nat.le_add_right ..) (Nat.le_add_left ..)) +theorem p : Short Size.p := Poly.of_le Size.two (fun i => by unfold Size.short; omega) +theorem l : Short Size.l := Poly.of_le Size.two (fun i => by unfold Size.short; omega) +theorem n : Short Size.n := Poly.of_le Size.two (fun i => by unfold Size.short; omega) +theorem rate : Short Size.W := Poly.of_le Size.two (fun i => by unfold Size.short; omega) +theorem m : Long Size.m := Poly.of_le Size.two_long (fun i => by unfold Size.long; omega) +theorem m' : Long Size.m' := Poly.of_le Size.two_long (fun i => by unfold Size.long; omega) +theorem w : Long Size.w := Poly.of_le Size.two_long (fun i => by unfold Size.long; omega) +theorem v : Long Size.v := Poly.of_le Size.two_long (fun i => by unfold Size.long; omega) + +namespace Work + +private theorem weighted_iff : Work f ↔ WeightedCost Size.workCharges f := by + simp only [Work, WeightedCost, Size.workCharges, Size.bound, weightedPower, List.map_cons, + List.map_nil, List.sum_cons, List.sum_nil, Nat.add_zero] + +theorem mono (hf : Work f) (h : ∀ i, g i ≤ f i) : Work g := + weighted_iff.mpr ((weighted_iff.mp hf).mono h) + +theorem add (hf : Work f) (hg : Work g) : Work (fun i => f i + g i) := + weighted_iff.mpr ((weighted_iff.mp hf).add (weighted_iff.mp hg) + fun i charge h => i.two.trans (i.workCharges_short charge h)) + +theorem mul (hf : Work f) (hg : Short g) : Work (fun i => f i * g i) := + weighted_iff.mpr ((weighted_iff.mp hf).mul hg Size.workCharges_short) + +theorem scale (hf : Work f) (hg : Short g) : Work (fun i => g i * f i) := + (hf.mul hg).mono fun _ => (mul_comm ..).le + +theorem links (hf : Long f) : Work (fun i => i.links * f i) := + let ⟨s, hs⟩ := hf.bound + ⟨s, fun i => (Nat.mul_le_mul_left _ (hs i)).trans (Nat.le_add_right ..)⟩ + +theorem slots : Work Size.slots := ⟨0, fun i => by simp only [Size.bound, pow_zero, mul_one]; omega⟩ +end Work + +/-- An exterior bit only pays for the two payload depths and the routing price. -/ +abbrev Outer := Poly Size.outer + +theorem outer_num (s : ℕ) : Outer (fun _ => s) := Poly.const Size.outer_two s +theorem outer_k : Outer Size.k := Poly.of_le Size.outer_two (fun i => by unfold Size.outer; omega) +theorem outer_k' : Outer Size.k' := Poly.of_le Size.outer_two (fun i => by unfold Size.outer; omega) +theorem outer_q : Outer Size.q := + (outer_k.add outer_k').mono fun _ => max_le (Nat.le_add_right ..) (Nat.le_add_left ..) +theorem outer_rate : Outer Size.W := Poly.of_le Size.outer_two (fun i + => by unfold Size.outer; omega) + +/-- The condition `∃ s : ℕ, ∀ i, f i ≤ i.bound s + i.volume * i.outer ^ s` on the specified +data. -/ +def Heavy (f : Size → ℕ) := ∃ s : ℕ, ∀ i, f i ≤ i.bound s + i.volume * i.outer ^ s + +theorem Work.heavy (h : Work f) : Heavy f := + let ⟨s, hs⟩ := h + ⟨s, fun i => (hs i).trans (Nat.le_add_right ..)⟩ + +namespace Heavy + +private theorem weighted_iff : Heavy f ↔ WeightedCost Size.heavyCharges f := by + simp only [Heavy, WeightedCost, Size.heavyCharges, Size.workCharges, Size.bound, weightedPower, + List.cons_append, List.nil_append, List.map_cons, List.map_nil, List.sum_cons, List.sum_nil, + Nat.add_zero, Nat.add_assoc] + +theorem mono (hf : Heavy f) (h : ∀ i, g i ≤ f i) : Heavy g := + weighted_iff.mpr ((weighted_iff.mp hf).mono h) + +theorem add (hf : Heavy f) (hg : Heavy g) : Heavy (fun i => f i + g i) := + weighted_iff.mpr ((weighted_iff.mp hf).add (weighted_iff.mp hg) + fun i charge h => i.outer_two.trans (i.heavyCharges_outer charge h)) + +theorem mul (hf : Heavy f) (hg : Outer g) : Heavy (fun i => f i * g i) := + weighted_iff.mpr ((weighted_iff.mp hf).mul hg Size.heavyCharges_outer) + +theorem scale (hf : Heavy f) (hg : Outer g) : Heavy (fun i => g i * f i) := + (hf.mul hg).mono fun _ => (mul_comm ..).le + +theorem volume : Heavy Size.volume := ⟨0, fun i => by + rw [pow_zero, mul_one]; exact Nat.le_add_left ..⟩ +end Heavy +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Shipment +end + +/- # Counting the endpoint tables and fragment records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Shipment +open Coloring Finset + +namespace Size +variable (i : Size) +open scoped Classical in +/-- Computes the bank by the application `payloadBank i.m i.V i.k i.m' i.V' i.k'`. -/ +abbrev bank := payloadBank i.m i.V i.k i.m' i.V' i.k' +open scoped Classical in +/-- The quantity computed by `i.bank.channels i.q (2 ^ i.p)`. -/ +abbrev channels := i.bank.channels i.q (2 ^ i.p) +open scoped Classical in +/-- The quantity computed by `i.bank.Endpoint i.q (2 ^ i.p)`. -/ +abbrev endpts := i.bank.Endpoint i.q (2 ^ i.p) +open scoped Classical in +/-- The quantity computed by `2 ^ i.p * 2 ^ i.n`. -/ +abbrev gates := 2 ^ i.p * 2 ^ i.n + +open scoped Classical in +theorem levels : ∀ a, i.bank.depth a ≤ i.q := by + rintro (a|a) + · exact (Nat.lt_succ_iff.mp a.1.isLt).trans (le_max_left ..) + · exact (Nat.lt_succ_iff.mp a.1.isLt).trans (le_max_right ..) + +open scoped Classical in +theorem rows : Fintype.card i.endpts ≤ (i.q + 1) ^ 2 * i.hosts := by + change Fintype.card (Σ j : i.bank.Level i.q (2 ^ i.p), i.bank.AtDepth j.1.val) ≤ _ + rw [Fintype.card_sigma] + calc + _ ≤ ∑ _ : i.bank.Level i.q (2 ^ i.p), Fintype.card i.bank.Slot := + sum_le_sum fun _ _ => Fintype.card_subtype_le _ + _ = Fintype.card (i.bank.Level i.q (2 ^ i.p)) * Fintype.card i.bank.Slot := by simp + _ ≤ (i.q + 1) * ((i.q + 1) * i.hosts) := Nat.mul_le_mul (i.bank.level_count ..) (bank_slots ..) + _ = _ := by rw [pow_two, mul_assoc] + +open scoped Classical in +theorem sends : 2 ^ i.p ≤ i.gates := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _) +open scoped Classical in +theorem receives : 2 ^ i.n ≤ i.gates := Nat.le_mul_of_pos_left _ (Nat.two_pow_pos _) +open scoped Classical in +theorem gate_pos : 0 < i.gates := (Nat.two_pow_pos _).trans_le i.sends + +open scoped Classical in +theorem fragment : (Fragments.Input i.l i.p i.n).width ≤ i.gates * (i.l + (i.p + 3 * i.l)) := by + simp only [Fragments.Input, Fragments.Entry, Intervals.span, Format.width_pair, Format.width_vec, + Format.width_addr] + rw [mul_add i.gates] + refine Nat.add_le_add (Nat.mul_le_mul_right _ i.sends) (Nat.mul_le_mul i.receives ?_) + omega + +open scoped Classical in +theorem item : (Payload.Script.item i.l i.p i.n).width ≤ i.gates * (i.l + (i.p + 3 * i.l) + i.l) + := by + rw [Payload.Script.item, Format.width_pair, Format.width_addr, mul_add i.gates] + exact Nat.add_le_add i.fragment (Nat.le_mul_of_pos_left _ i.gate_pos) +end Size + +open scoped Classical in +theorem host_gates : Work (fun i => i.hosts * i.gates) := + Work.slots.mono (fun _ => (mul_assoc ..).symm.le) + +open scoped Classical in +theorem slot_gates : Work (fun i => Fintype.card i.bank.Slot * i.gates) := + (host_gates.scale (q.add (num 1))).mono fun _ => + (Nat.mul_le_mul_right _ (bank_slots ..)).trans_eq (mul_assoc ..) + +open scoped Classical in +theorem end_gates : Work (fun i => Fintype.card i.endpts * i.gates) := + (host_gates.scale ((q.add (num 1)).pow 2)).mono fun i => + (Nat.mul_le_mul_right _ i.rows).trans_eq (mul_assoc ..) + +open scoped Classical in +private theorem fixed_width {J : Type} [Fintype J] (A : Format) : + (Fmt.pi (fun _ : J => A)).width = Fintype.card J * A.width := by simp + +open scoped Classical in +private theorem packed {f : Size → ℕ} (hf : Work (fun i => f i * i.gates)) : + Work (fun i => f i * (Fragments.Input i.l i.p i.n).width) := + (hf.mul (l.add (p.add ((num 3).mul l)))).mono fun i => + (Nat.mul_le_mul_left _ i.fragment).trans_eq (mul_assoc ..).symm + +open scoped Classical in +theorem distribution : + Work (fun i => i.bank.distributionCost i.q (2 ^ i.p) i.l i.p i.n) := by + have ha : Work (fun i => (i.bank.records i.l i.p i.n).width) := + (packed slot_gates).mono (fun _ => (fixed_width _).le) + have hb : Work (fun i => (i.bank.copies i.q (2 ^ i.p) i.l i.p i.n).width) := + (packed end_gates).mono (fun _ => (fixed_width _).le) + have hc : Short (fun i => (100 + (i.n + 4 * i.l + 2 * i.p + i.q + 2)) ^ 118) := + ((num 100).add ((((n.add ((num 4).mul l)).add ((num 2).mul p)).add q).add (num 2))).pow 118 + refine ((ha.add (hb.scale (num 2))).scale (num 4)).add ?_ + refine ((end_gates.mul hc).scale (num 4)).mono fun i => ?_ + have e : 2 ^ max i.p i.n ≤ i.gates := by + change 2 ^ max i.p i.n ≤ 2 ^ i.p * 2 ^ i.n + rw [← pow_add] + exact Nat.pow_le_pow_right (by decide) (max_le (Nat.le_add_right ..) (Nat.le_add_left ..)) + rw [mul_left_comm _ 4, mul_assoc (Fintype.card i.endpts)] + gcongr + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Shipment +end + +/- # Bounding the dyadic routing commands -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Shipment +open Coloring Finset + +open scoped Classical in +theorem height : Long Size.height := by + have hm : Long (fun i => max i.m i.m') := (m.add m').mono fun _ + => max_le (Nat.le_add_right ..) (Nat.le_add_left ..) + exact ((hm.add (Short.long (q.add (num 1)).clog)).add p.long).add (num 2).long + +open scoped Classical in +private theorem pow_height (i : Size) : 2 ^ i.height ≤ i.links * (8 * (i.q + 1)) := by + have hm : 2 ^ max i.m i.m' ≤ i.hosts := by + rcases max_choice i.m i.m' with h|h + · rw [h]; exact Nat.le_add_right .. + · rw [h]; exact Nat.le_add_left .. + calc + _ = 2 ^ max i.m i.m' * 2 ^ Nat.clog 2 (i.q + 1) * 2 ^ i.p * 4 := by + unfold Size.height PeerLayout.height PeerLayout.bits; rw [pow_add, pow_add, pow_add]; rfl + _ ≤ i.hosts * (2 * (i.q + 1)) * 2 ^ i.p * 4 := by + gcongr; exact Transcript.pow_clog_le_twice (by omega) + _ = _ := by unfold Size.links; ring + +open scoped Classical in +private theorem addresses {f : Size → ℕ} (hf : Long f) : Work (fun i => 2 ^ i.height * f i) := + (Work.links ((Short.long ((num 8).mul (q.add (num 1)))).mul hf)).mono fun i => + (Nat.mul_le_mul_right _ (pow_height i)).trans_eq (mul_assoc ..) + +open scoped Classical in +private theorem peers : Work (fun i => PeerLayout.size i.m i.k i.m' i.k' i.p i.l) := by + have h := (((num 101).long.add ((num 5).long.mul height)).add l.long).pow 134 + exact (addresses h).scale ((num 16).mul (q.add (num 2))) + +open scoped Classical in +private theorem columns : Heavy (fun i => (Fmt.payload i.m i.V i.k).width) := by + refine ((Heavy.volume.scale (outer_num 2)).scale (outer_k.add (outer_num 1))).mono fun i => ?_ + exact (Fmt.width_payload ..).trans (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ + (Nat.le_add_right ..))) + +open scoped Classical in +private theorem columns' : Heavy (fun i => (Fmt.payload i.m' i.V' i.k').width) := by + refine ((Heavy.volume.scale (outer_num 2)).scale (outer_k'.add (outer_num 1))).mono fun i => ?_ + exact (Fmt.width_payload ..).trans (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ (Nat.le_add_left + ..))) + +open scoped Classical in +private theorem cap : Heavy (fun i => i.bank.capacity) := + (columns.add columns').mono (fun _ => (bank_capacity ..).le) + +open scoped Classical in +private theorem locals : Heavy (fun i => ∑ a, 2 ^ i.channels.localWidth a) := + ((cap.scale (outer_num 2)).scale (outer_q.add (outer_num 1))).mono fun i + => i.bank.local_volume i.q (2 ^ i.p) + +open scoped Classical in +private theorem labels : Work (fun i => ∑ a, 2 ^ i.channels.count a * i.channels.count a) := by + refine ((addresses height).scale (q.add (num 1))).mono fun i => ?_ + calc + _ ≤ ∑ _a : i.bank.Level i.q (2 ^ i.p), 2 ^ i.height * i.height := by + refine sum_le_sum fun j _ => ?_ + have h := PeerLayout.count_bound le_rfl j + exact Nat.mul_le_mul (Nat.pow_le_pow_right (by decide) h) h + _ = Fintype.card (i.bank.Level i.q (2 ^ i.p)) * (2 ^ i.height * i.height) := by simp + _ ≤ _ := Nat.mul_le_mul_right _ (i.bank.level_count ..) + +open scoped Classical in +/-- Charge a pointer to the larger of the requested and local widths. +Only the latter branch can involve the exterior-bit count. -/ +private theorem split_bound {A D : Format} (S : Channels A D) (j k : ℕ) + (hk : ∀ i, S.localWidth i ≤ k) : + S.expandCost (fun _ => j) ≤ 4 * (Fintype.card S.I * 2 ^ j * (100 + 4 * j) ^ 101 + + (∑ i, 2 ^ S.localWidth i) * (100 + 4 * k) ^ 101 + (∑ i, 2 ^ S.count i * S.count i) + D.width) + := by + have step (i : S.I) : Channels.pointerCost j (S.localWidth i) ≤ + 4 * (2 ^ j * (100 + 4 * j) ^ 101 + 2 ^ S.localWidth i * (100 + 4 * k) ^ 101) := by + unfold Channels.pointerCost + apply Nat.mul_le_mul_left + rcases le_total (S.localWidth i) j with h|h + · rw [max_eq_left h] + exact (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) _)).trans (Nat.le_add_right ..) + · rw [max_eq_right h] + have := hk i + exact (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) _)).trans (Nat.le_add_left ..) + have ht := sum_le_sum (s := univ) (fun i _ => step i) + simp only [← mul_sum, sum_add_distrib, ← sum_mul, sum_const, card_univ, smul_eq_mul] at ht + rw [← mul_assoc (2 ^ j), mul_comm (2 ^ j) (Fintype.card S.I)] at ht + let U := Format.pair (Fmt.pi (fun i => Perm (S.count i))) (Fmt.raw D.pins) + change (∑ i, Channels.pointerCost j (S.localWidth i)) + 4 * U.width ≤ _ + rw [show U.width = (∑ i, 2 ^ S.count i * S.count i) + D.width by simp [U]] + omega + +open scoped Classical in +private theorem expand : Heavy (fun i => i.channels.expandCost (fun _ => i.n)) := by + have ha : Work (fun i => Fintype.card i.channels.I * 2 ^ i.n) := + end_gates.mono fun i => Nat.mul_le_mul_left _ i.receives + have hj := ha.mul (((num 100).add ((num 4).mul n)).pow 101) + have ht := ((outer_num 100).add ((outer_num 4).mul (outer_q.add (outer_num 1)))).pow 101 + refine ((((hj.heavy.add (locals.mul ht)).add labels.heavy).add columns').scale (outer_num + 4)).mono fun i => ?_ + exact split_bound i.channels _ _ (fun j => Nat.succ_le_succ (i.levels j.2.val)) + +open scoped Classical in +theorem command : Heavy (fun i => Payload.Script.commandCost i.m i.V i.k i.m' i.V' i.k' (2 ^ i.p) + i.p i.l i.n) := + (distribution.heavy.add (peers.heavy.add (columns'.scale ((outer_num 8000).mul + (outer_k'.add (outer_num 2)))))).add expand + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Shipment +end + +/- +# Uniform cost of moving exterior payloads + +The cost per payload bit is polynomial in the short widths. The +full host addresses occur only in a term charged per contact. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Shipment +open Coloring + +namespace Size +variable (i : Size) +/-- The quantity computed by `(Payload.Script.item i.l i.p i.n).width + i.v`. -/ +abbrev cap := (Payload.Script.item i.l i.p i.n).width + i.v +/-- The value specified by `Payload.Script.cost i.m i.k i.m' i.k' i.p i.l i.cap (i.W * (2 ^ i.m +* i.cap)) (i.W * (2 ^ i.m' * i.cap))`. -/ +def control := Payload.Script.cost i.m i.k i.m' i.k' i.p i.l i.cap + (i.W * (2 ^ i.m * i.cap)) (i.W * (2 ^ i.m' * i.cap)) +/-- The value specified by `500000 * ((102 + i.q) ^ 8 + i.W) * (i.q + 1) ^ 2* (1 + i.volume + 2 +^ i.p * i.hosts * (i.v + i.w + 1))`. -/ +def payload := 500000 * ((102 + i.q) ^ 8 + i.W) * (i.q + 1) ^ 2* + (1 + i.volume + 2 ^ i.p * i.hosts * (i.v + i.w + 1)) + +theorem links_pos : 0 < i.links := by unfold links hosts; positivity +theorem host_links : i.hosts ≤ i.links := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _) + +end Size + +private theorem names {f : Size → ℕ} (h : Long f) : Work (fun i => i.hosts * f i) := + (Work.links h).mono fun i => Nat.mul_le_mul_right _ i.host_links + +private theorem threshold : Work (fun i => i.hosts * i.cap) := by + have g := ((l.add (p.add ((num 3).mul l))).add l) + refine ((host_gates.mul g).add (names v)).mono fun i => ?_ + unfold Size.cap + rw [mul_add] + exact Nat.add_le_add_right ((Nat.mul_le_mul_left _ i.item).trans_eq (mul_assoc ..).symm) _ + +private theorem control : Work Size.control := by + have mail : Work (fun i => i.W * (2 ^ i.m * i.cap) + i.W * (2 ^ i.m' * i.cap)) := + (threshold.scale rate).mono fun i => by unfold Size.hosts; rw [add_mul, mul_add i.W] + have cost := (((((num 101).long.add m).add m').add l.long).add k'.long).pow 60 + have prep : Work (fun i => i.hosts * (i.cap + (101 + i.m + i.m' + i.l + i.k') ^ 60)) := + (threshold.add (names cost)).mono fun _ => by rw [mul_add] + have shift : Work (fun i => 2 ^ (i.m + i.p) * (i.m' + i.p)) := by + refine (Work.links (m'.add p.long)).mono fun i => ?_ + rw [pow_add] + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (Nat.le_add_right ..)) + exact ((mail.add prep).add shift).scale ((num 50000).mul ((k.add k').add (num 2))) + +private theorem payload : Heavy Size.payload := by + have one : Work (fun _ => 1) := (Work.links (num 1).long).mono (fun i + => by rw [mul_one]; exact i.links_pos) + have long : Work (fun i => 2 ^ i.p * i.hosts * (i.v + i.w + 1)) := by + refine (Work.links ((v.add w).add (num 1).long)).mono fun i => ?_ + rw [mul_comm (2 ^ i.p) i.hosts] + exact ((one.heavy.add Heavy.volume).add long.heavy).scale + (((outer_num 500000).mul ((((outer_num 102).add outer_q).pow 8).add outer_rate)).mul + ((outer_q.add (outer_num 1)).pow 2)) + +theorem total : Heavy (fun i => i.control + + Payload.Script.commandCost i.m i.V i.k i.m' i.V' i.k' (2 ^ i.p) i.p i.l i.n + i.payload) := + (control.heavy.add command).add payload + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Shipment + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Prices +open Assembly + +theorem shipment_le : ∃ K : ℕ, ∀ (F : Type) [Field F] (W : Prices F) + (size m V k m' V' k' p l n : ℕ), + let s := 1000 + W.W + k + k' + p + l + n + let t := s + m + m' + W.w + W.w ^ W.power + W.shipment size m V k m' V' k' p l n ≤ + 4 * size + (2 ^ m + 2 ^ m') * 2 ^ p * (t ^ K + 2 ^ n * s ^ K) + (V + V') * (1000 + W.W + k + + k') ^ K := by + obtain ⟨j, h⟩ := Shipment.total + refine ⟨j, ?_⟩ + intro F _ W size m V k m' V' k' p l n s t + let i : Shipment.Size := ⟨m, V, k, m', V', k', p, l, n, W.W, W.w, W.w ^ W.power⟩ + change 4 * size + (i.control + Payload.Script.commandCost m V k m' V' k' (2 ^ p) p l n) + + i.payload ≤ _ + rw [add_assoc] + refine (Nat.add_le_add_left (h i) _).trans_eq ?_ + change 4 * size + (i.links * t ^ j + i.links * 2 ^ n * s ^ j + (V + V') * i.outer ^ j) = 4 * size + + i.links * (t ^ j + 2 ^ n * s ^ j) + (V + V') * i.outer ^ j + ring + +theorem shipment_bound : ∃ K : ℕ, ∀ (F : Type) [Field F] (W : Prices F) + (size m V k m' V' k' p l n : ℕ), + let s := 1000 + W.W + k + k' + p + l + n + let t := s + m + m' + W.w + W.w ^ W.power + W.shipment size m V k m' V' k' p l n ≤ + 4 * size + (2 ^ m + 2 ^ m') * 2 ^ p * (t ^ K + 2 ^ n * s ^ K) + (V + V') * s ^ K := by + obtain ⟨K, h⟩ := shipment_le + refine ⟨K, ?_⟩ + intro F _ W size m V k m' V' k' p l n s t + have he : 1000 + W.W + k + k' ≤ s := by unfold s; omega + exact (h F W size m V k m' V' k' p l n).trans + (Nat.add_le_add_left (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left he K)) _) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Prices +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/SpanSupplies.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/SpanSupplies.lean new file mode 100644 index 0000000000..b3fa2da3df --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/SpanSupplies.lean @@ -0,0 +1,759 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanTiles +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes + +/-! +# Selector validation before a partial computation + +Only the first part of the network is specified on invalid selector +words. Subsequent stages need satisfy their contracts only on the +codes written by the branch selector. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +universe v +variable {F : Type} [Field F] {x y : Wire} {u m n : ℕ} {L : Set (Table F)} + {X Y : Snapshot.{v} F x y} {C D : Format} + +open scoped Classical in +theorem Transforms.checked (hu : 3 ≤ u) (R : Selected X Y C) + (head : X.state → C.obj → Val x → Val y → D.obj) + (first : Computes F u L (X.port.pair C) D + (fun p : (X.state × C.obj) × Val x × Val y => (X.encode p.1.1 p.2.1 p.2.2, p.1.2)) + (fun p => head p.1.1 p.1.2 p.2.1 p.2.2) (fun p + => if ((R.index p.1.1).read p.1.2).isSome then 1 else 0) m) + (second : Computes F u L D Y.port + (fun p : (Σ s, R.choice s) × Val x × Val y => head p.1.1 ((R.index p.1.1).write p.1.2) p.2.1 + p.2.2) + (fun p => Y.encode (R.next p.1.1 p.1.2) p.2.1 p.2.2) + (fun p => R.scalar p.1.1 p.1.2) n) : + Transforms F u L X Y (m + n + 4 * C.width) := by + let _ := Fintype.ofFinite D.obj + obtain ⟨f, hf, ef⟩ := first + obtain ⟨g, hg, eg⟩ := second + refine Transforms.of_selector hu R (hf.comp hg) fun s a b c t => ?_ + have hc := ef ((s, c), a, b) + dsimp only at hc + simp only [hc, ite_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + cases h : (R.index s).read c with + | none => simp + | some i => + rw [(R.index s).valid _ _ |>.mp h] + simp only [Option.isSome_some, ite_true, Option.elim_some, one_mul] + exact eg (⟨s, i⟩, a, b) t + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Running a command generator and moving the named exterior bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] {I : Type*} {w s t : ℕ} {L : Set (Table F)} + {X Y C A B : Format} {x : I → X.obj} {y : I → Y.obj} {c : I → C.obj} + {a : I → A.obj} {b : I → B.obj} {weight : I → F} + +open scoped Classical in +theorem Computes.with_channels (h : Computes F w L X (.pair Y C) x (fun i => (y i, c i)) weight s) + (k : Computes F w L (.pair C A) B (fun i => (c i, a i)) b (fun _ => 1) t) : + Computes F w L (.pair X A) (.pair Y B) (fun i => (x i, a i)) (fun i => (y i, b i)) weight (s + + t) := by + let _ := Fintype.ofFinite C.obj + obtain ⟨f, hf, he⟩ := h + obtain ⟨g, hg, hj⟩ := k + refine ⟨_, hf.with_channels hg, ?_⟩ + rintro i ⟨z, v⟩ + change (∑ t, f (x i) (z, t) * g (t, a i) v) = + @ite F ((y i, b i) = (z, v)) (Classical.propDecidable _) (weight i) 0 + simp only [he, ite_mul, zero_mul] + by_cases h : y i = z + · simp only [Prod.mk.injEq, h, true_and, Finset.sum_ite_eq, Finset.mem_univ, ite_true, hj, + mul_ite, mul_one, mul_zero] + · simp only [Prod.mk.injEq, h, false_and, ite_false, Finset.sum_const_zero] + +variable {m V k m' V' k' p l n v c₁ c₂ : ℕ} +local notation "Ch" => PeerLayout.S m V k m' V' k' (2 ^ p) +local notation "Cmd" => Payload.Script m m' p l n + +open scoped Classical in +/-- The bound obtained by adding the component charges `4 * Y.width + (Payload.Script.cost m k +m' k' p l v c₁ c₂ + Payload.Script.commandCost m V k m' V' k' (2 ^ p) p l n)`. -/ +def shipCost (Y : Format) (m V k m' V' k' p l n v c₁ c₂ : ℕ) := + 4 * Y.width + (Payload.Script.cost m k m' k' p l v c₁ c₂ + + Payload.Script.commandCost m V k m' V' k' (2 ^ p) p l n) + +open scoped Classical in +theorem Computes.shipped {cmd : I → (Cmd).obj} {f : I → (Fmt.payload m V k).obj} + {g : I → (Fmt.payload m' V' k').obj} + (h : Computes F w L X (.pair Y Cmd) x (fun i => (y i, cmd i)) weight s) + (ok : ∀ i b, (Ch).Carries (Payload.Script.decode le_rfl (cmd i)) (f i) b ↔ g i = b) + (hw : 3 ≤ w) (sc : Radix.Tag F m v c₁) (dt : Radix.Tag F m' v c₂) + (room : (Payload.Script.item l p n).width ≤ v) + (run : Kernel F w L ((Ch).control.pair (Fmt.payload m V k)) (Fmt.payload m' V' k') ((Ch).kernel + F) t) : + Computes F w L (.pair X (Fmt.payload m V k)) (.pair Y (Fmt.payload m' V' k')) + (fun i => (x i, f i)) (fun i => (y i, g i)) weight (s + + shipCost Y m V k m' V' k' p l n v c₁ c₂ + t) := by + let action : (Cmd).obj → (Ch).control.obj := Payload.Script.decode le_rfl + have decode := Payload.Script.decode_net (V := V) (k := k) (V' := V') (k' := k') + (L := L) hw (le_rfl : 2 ^ p ≤ 2 ^ p) sc dt room + have keep := Map.circuit (L := L) hw (Circuit.id F Y) + have move := Computes.of_map (x := fun i => (y i, cmd i)) + (y := fun i => (y i, action (cmd i))) (keep.par decode) (fun _ => rfl) + have cmds := h.comp move + simp only [mul_one] at cmds + apply cmds.with_channels + let _ : DecidableEq (Fmt.payload m' V' k').obj := Classical.typeDecidableEq _ + exact ⟨_, run, fun i b => if_congr (ok i b) rfl rfl⟩ + +universe v +open scoped Classical in +theorem Transforms.deterministic {x y : Wire} {X Y : Snapshot.{v} F x y} + (q : X.state → Y.state) (he : ∀ i, X.eval i = Y.eval (q i)) + (h : Computes F w L X.port Y.port + (fun p : X.state × Val x × Val y => X.encode p.1 p.2.1 p.2.2) + (fun p => Y.encode (q p.1) p.2.1 p.2.2) (fun _ => 1) n) : + Transforms F w L X Y n := by + obtain ⟨k, hk, hc⟩ := h + refine ⟨k, hk, fun i => ⟨Unit, inferInstance, fun _ => q i, fun _ => 1, ?_, ?_⟩⟩ + · intro a b; simp only [he, Fintype.sum_unique, one_mul] + · intro a b t; simpa only [Fintype.sum_unique] using hc (i, a, b) t + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Redistributing exposed spans to children of the same parent + +A fixed table reads the old label and the block index. Its output +specifies the channel, length, and relative order at both ends. +The bank offsets are then prefix sums in the two displayed orders. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} (S : Scheme F) (z w l : ℕ) + +namespace SpanProgram +open scoped Classical in +/-- The quantity computed by `Format.vec l (SpanPlan.header w z (S.h + l))`. -/ +abbrev Paths := Format.vec l (SpanPlan.header w z (S.h + l)) +open scoped Classical in +/-- Computes the response by the application `Format.pair (Paths S z w l) (.vec z (Paths S z w +l))`. -/ +abbrev Response := Format.pair (Paths S z w l) (.vec z (Paths S z w l)) +open scoped Classical in +/-- The value specified by `Format.pair (.addr S.ℓ) (.addr S.h)`. -/ +abbrev Question := Format.pair (.addr S.ℓ) (.addr S.h) +open scoped Classical in +/-- Computes the grid by the application `Format.vec S.m (.vec S.h A)`. -/ +abbrev Grid (A : Format) := Format.vec S.m (.vec S.h A) +open scoped Classical in +/-- The quantity computed by `SpanPlan.Ports S.m (S.m + z) (SpanPlan.entries w z (S.h + l)) +(SpanPlan.entries w z (S.h + l))`. -/ +abbrev Bank := SpanPlan.Ports S.m (S.m + z) (SpanPlan.entries w z (S.h + + l)) (SpanPlan.entries w z (S.h + l)) +end SpanProgram + +open scoped Classical in +/-- The indexing data represented by `B S.ℓ → B S.h → (SpanProgram.Response S z w l).obj`. -/ +abbrev SpanProgram := B S.ℓ → B S.h → (SpanProgram.Response S z w l).obj + +namespace SpanProgram +variable {S z w l} +local notation "I" => Question S +local notation "O" => Response S z w l + +open scoped Classical in +/-- Evaluates `((x v).2 k, k)` at the input `v k`. -/ +def query (S : Scheme F) (x : S.format.obj) : (Grid S (Question S)).obj := fun v k => ((x v).2 k, k) + +open scoped Classical in +/-- The reorder of type `(Bank S z w l).obj`, constructed using `Match.rowIndex S.h l j`. -/ +def reorder (x : (Grid S O).obj) : (Bank S z w l).obj := + (fun v j => + let a := Match.rowIndex S.h l j + (x v a.1).1 a.2, + fun v j => + let b := Match.rowIndex S.m z v + let a := Match.rowIndex S.h l j + (x b.1 a.1).2 b.2 a.2) + +open scoped Classical in +/-- The quantity computed by `(Match.rowIndex (m + z) z).symm (i, 0)`. -/ +def peer (m z : ℕ) (i : B (m + z)) := (Match.rowIndex (m + z) z).symm (i, 0) + +variable (g : SpanProgram S z w l) (x : S.format.obj) + +open scoped Classical in +/-- The indexed operation `reorder (S := S) (z := z) (w := w) (l := l) (fun v k => g ((x v).2 k) +k)`. -/ +def plan := reorder (S := S) (z := z) (w := w) (l := l) (fun v k => g ((x v).2 k) k) +open scoped Classical in +/-- The value specified by `(plan g x).1`. -/ +abbrev send := (plan g x).1 +open scoped Classical in +/-- The value specified by `(plan g x).2`. -/ +abbrev take := (plan g x).2 + +open scoped Classical in +/-- Computes the commands by the application `SpanPlan.emit (peer S.m z) (plan g x)`. -/ +def commands := SpanPlan.emit (peer S.m z) (plan g x) + +variable [Field F] + +open scoped Classical in +/-- The indexed operation `lookup F I O (fun a b => @ite F (g a.1 a.2 = b) +(Classical.propDecidable _) 1 0)`. -/ +def gate := lookup F I O (fun a b => @ite F (g a.1 a.2 = b) (Classical.propDecidable _) 1 0) + +open scoped Classical in +/-- The quantity computed by `(Question S).width + (Response S z w l).width`. -/ +def size (S : Scheme F) (z w l : ℕ) := (Question S).width + (Response S z w l).width + +open scoped Classical in +/-- The cost used in the `SpanProgram` construction. -/ +def cost (S : Scheme F) (z w l : ℕ) := + 4 * (S.format.width + 34 * (Grid S (Question S)).width) + + 2 ^ S.m * (2 ^ S.h * (1 + (Question S).width + (Response S z w l).width)) + + 4 * ((Grid S (Response S z w l)).width + 2 * (Bank S z w l).width) + + 4 * SpanPlan.emitCost S.m (S.m + z) w z (S.h + l) + +open scoped Classical in +theorem action {u : ℕ} {P : Set (Table F)} (hu : 3 ≤ u) (hw : size S z w l ≤ u) (hg : gate g ∈ P) : + Map F u P S.format (Payload.Script S.m (S.m + z) z w (S.h + l)) (commands g) (cost S z w l) + := by + have start : Circuit F S.format (Grid S I) (query S) + (S.format.width + 34 * (Grid S I).width) := by + apply Window.Tile.project_const + rintro ⟨v, k, j|j⟩ + · exact .inl ⟨(v, .inr (k, j)), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr S.h).code k j, fun _ => rfl⟩ + have one : Map F u P I O (fun a => g a.1 a.2) (1 + (I).width + (O).width) := Kernel.lookup hw hg + have all := Map.vec _ (fun _ : B S.m => Map.vec _ (fun _ : B S.h => one)) + have split : Circuit F (Grid S O) (Bank S z w l) reorder + ((Grid S O).width + 2 * (Bank S z w l).width) := by + let tap : (Bank S z w l).pins → (Grid S O).pins + | .inl (v, j, t) => (v, (Match.rowIndex S.h l j).1, .inl ((Match.rowIndex S.h l j).2, t)) + | .inr (v, j, t) => ((Match.rowIndex S.m z v).1, (Match.rowIndex S.h l j).1, + .inr ((Match.rowIndex S.m z v).2, (Match.rowIndex S.h l j).2, t)) + exact Circuit.project tap (by rintro _ (⟨v, j, t⟩|⟨v, j, t⟩) <;> rfl) + have post := SpanPlan.emit_net (w := w) (n := S.h + l) (peer S.m z) F + exact (((Map.circuit hu start).comp all).comp (Map.circuit hu split)).comp (Map.circuit hu post) + +end SpanProgram +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- A sort and one parallel table read return the children's declarations. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan.Scatter +open Coloring + +variable (F : Type) [Field F] (w z n : ℕ) +local notation "h" => depth z n +local notation "l" => 4 + 3 * (z + n + w) +local notation "M" => header w z n +local notation "C" => Format.vec (depth z n) (header w z n) + +private theorem cheap_mark (j : B h) : Cheap F 0 (l) M (Key n) (mark j) 20 := by + have ha : (M).width ≤ 2 ^ 0 * (100 + (l)) ^ 1 := by simp [header]; omega + have hw : (Format.addr w).width ≤ 2 ^ 0 * (100 + (l)) ^ 1 := by simp; omega + have hb : Format.bit.width ≤ 2 ^ 0 * (100 + (l)) ^ 1 := by simp; omega + have i := Cheap.id F ha + unfold mark + by_cases he : (address j).1 = 0 + · simp only [ite_eq_left he] + have eq := (i.snd.fst.pair (Cheap.const F ha hw 0)).comp (cheap_eq F (show w ≤ l by omega)) + exact (eq.pair i.snd.snd).mono (by decide) + · simp only [ite_eq_right he] + exact ((Cheap.const F ha hb false).pair i.snd.snd).mono (by decide) + +private theorem body_net : Circuit F (Family w z n) C body ((Family w z n).width + 34 * (C).width) + := by + apply Window.Tile.project_const + rintro ⟨j, i⟩ + by_cases he : (address j).1 = 0 + · cases i with + | inl a => + refine .inr ⟨(Format.addr z).code (address j).2.1 a, ?_⟩ + intro x + change (Format.addr z).code (body x j).1 a = _ + rw [body, ite_eq_left he] + | inr b => + refine .inl ⟨((address j).2.1, (address j).2.2, .inr b), ?_⟩ + intro x + change (Format.pair (.addr w) (.addr n)).code (body x j).2 b = _ + rw [body, ite_eq_left he] + rfl + · refine .inr ⟨(M).code (0, 0, (address j).2.2) i, ?_⟩ + intro x + change (M).code (body x j) i = _ + rw [body, ite_eq_right he] + +theorem cheap : Cheap F h (l) (Family w z n) (entries w z n) run 200 := by + have hm : (M).width ≤ l := by simp [header]; omega + have big : (C).width ≤ 2 ^ h * (100 + (l)) ^ 1 := by + rw [Format.width_vec, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have mid : (Family w z n).width ≤ (C).width := by + simp only [Family, entries, Format.width_vec, ← mul_assoc, ← pow_add] + gcongr + unfold depth + omega + have low : (entries w z n).width ≤ (C).width := by + simp only [entries, Format.width_vec] + gcongr + unfold depth + omega + have init : Cheap F h (l) (Family w z n) C body 2 := by + refine ⟨_, body_net F w z n, ?_⟩ + calc + _ ≤ 100 * (2 ^ h * (100 + (l)) ^ 1) := by omega + _ ≤ _ := by rw [mul_comm 100, pow_succ (100 + (l)) 1, ← mul_assoc]; gcongr; omega + have room : h + (Key n).width ≤ l := by simp [Key, depth]; omega + have mark' := Cheap.map _ (fun j => cheap_mark F w z n j) + have key := mark'.comp (cheap_keys (Key n) F h (k := l) (by omega)) + have find := key.comp ((cheap_first F h (Key n).width).widen room) + have read := ((Cheap.id F big).pair find).comp (Cheap.lookup F h (l) M (by omega) hm) + have out : Cheap F h (l) C (entries w z n) (fun x i => x (query i)) 2 := + Cheap.project F big (low.trans big) (fun i => (query i.1, i.2)) (fun _ _ => rfl) + exact ((init.comp read).comp out).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan.Scatter +end + +section +/- +# Counting the controls for child payload transfers + +The long address term is paid only per host and contact. The +per-occurrence arithmetic cost uses only the short coordinates. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +namespace SpanPlan + +variable (m m' w p n : ℕ) + +private theorem width_row : (Row w p n).width = w + 2 ^ p * w + 2 ^ n * (p + 3 * w) := by + simp only [Row, Fragments.Input, Fragments.Entry, Intervals.span, Format.width_pair, + Format.width_vec, Format.width_addr] + ring + +theorem emit_price : emitCost m m' w p n = + (2 ^ m + 2 ^ m') * (2 ^ (n + p) * (100 + (2 * n + p + w)) ^ 140 + 35 * (w + 2 ^ p * w + + 2 ^ n * (p + 3 * w))) + + 34 * 2 ^ (m + p) * (m' + p) := by + have hs : (Payload.Script m m' p w n).width = + (2 ^ m + 2 ^ m') * (Row w p n).width + 2 ^ (m + p) * (m' + p) := by + simp only [Payload.Script, PeerLayout.input, PeerLayout.lengths, Row, Fragments.Input, + Format.width_pair, Format.width_vec, Format.width_addr] + ring + rw [emitCost, hs, Ports, Format.width_pair, Format.width_vec, Format.width_vec, width_row] + generalize (100 + (2 * n + p + w)) ^ 140 = B + ring + +end SpanPlan + +namespace SpanProgram +variable {F : Type} (S : Scheme F) (z w l : ℕ) + +theorem size_eq : size S z w l = S.ℓ + S.h + (1 + 2 ^ z) * 2 ^ l * (z + w + (S.h + l)) := by + simp only [size, Question, Response, Paths, SpanPlan.header, Format.width_vec, Format.width_pair, + Format.width_addr] + ring + +theorem price : cost S z w l = + 4 * 2 ^ S.m * (2 ^ S.d * S.m) + + 2 ^ (S.m + S.h) * (1 + 4 * S.ℓ + 137 * (S.ℓ + S.h) + 13 * (1 + 2 ^ z) * 2 ^ l * (z + w + (S.h + + l))) + + 4 * SpanPlan.emitCost S.m (S.m + z) w z (S.h + l) := by + simp only [cost, Scheme.format, Grid, Question, Response, Paths, Bank, + SpanPlan.Ports, SpanPlan.entries, SpanPlan.header, Format.width_pair, Format.width_vec, + Format.width_addr, pow_add] + ring + +end SpanProgram +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Exterior spans tile both banks in logical order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring + +variable {F : Type} [Field F] {S U : Scheme F} {x : S.format.obj} {y : U.format.obj} + {a b : Wire} {G H : Diagram F a b} {p : S.Presentation x G} {q : U.Presentation y H} + {z w n : ℕ} + +open scoped Classical in +theorem sub_lt (p : S.Presentation x G) (i : Edge a b) : + sub p i < S.borderLen x (span p i) := by + rw [S.len_at x (p.boundary i)] + exact (p.boundary i).val.2.isLt + +open scoped Classical in +theorem span_pos (p : S.Presentation x G) (i : Edge a b) : + 0 < S.borderLen x (span p i) := Nat.zero_lt_of_lt (sub_lt p i) + +open scoped Classical in +theorem exists_bit (p : S.Presentation x G) (t : S.Span) (k : ℕ) + (hk : k < S.borderLen x t) : ∃ i, span p i = t ∧ sub p i = k := by + unfold Scheme.borderLen at hk + split_ifs at hk with ht + · obtain ⟨i, he⟩ := p.boundary.surjective ⟨⟨t, ⟨k, hk⟩⟩, ht⟩ + exact ⟨i, congrArg (fun u => u.val.1) he, congrArg (fun u => u.val.2.val) he⟩ + · omega + +open scoped Classical in +private theorem bit_eq {i j : Edge a b} (hh : span p i = span p j) (hs : sub p i = sub p j) : + i = j := by + apply p.boundary.injective + apply Subtype.ext + exact Sigma.ext hh ((Fin.heq_ext_iff (congrArg (S.width x) hh)).mpr hs) + +namespace Spec + +variable {child : B U.m ≃ B S.m × B z} {shift : S.Span → U.Span} + {skip : S.Span → ℕ} {left right : S.Span → B n} + {send : Entries S.m w z n} {take : Entries U.m w z n} + (h : Spec p q child shift skip left right send take) +include h + +open scoped Classical in +theorem left_inj {t t' : S.Span} (ht : 0 < S.borderLen x t) (ht' : 0 < S.borderLen x t') + (hv : t.1.1 = t'.1.1) (he : left t = left t') : t = t' := by + rcases lt_trichotomy (S.spanOrd t) (S.spanOrd t') with hh|hh|hh + · exact ((h.ordered t t' ht ht' hv hh).ne he).elim + · exact S.ext_span hv hh + · exact ((h.ordered t' t ht' ht hv.symm hh).ne he.symm).elim + +open scoped Classical in +theorem right_inj {t t' : S.Span} (ht : 0 < S.borderLen x t) (ht' : 0 < S.borderLen x t') + (hv : (shift t).1.1 = (shift t').1.1) (he : right t = right t') : t = t' := by + apply h.left_inj ht ht' + · rw [← h.parent _ ht, ← h.parent _ ht', hv] + · rw [← (h.target _ ht).2.2, ← (h.target _ ht').2.2, hv, he] + +open scoped Classical in +private theorem moved (i : Edge a b) : here q i = (shift (span p i)).1.1 := + congrArg (fun t : U.Span => t.1.1) (h.bits i).1 + +open scoped Classical in +theorem leftTiles : Tiles p send (left ∘ span p) (sub p) where + bound i := (sub_lt p i).trans_eq (h.source _ (span_pos p i)).2.1.symm + full v j k hk := by + obtain ⟨t, ht, rfl, rfl⟩ := h.sourceCover v j (Nat.zero_lt_of_lt hk) + obtain ⟨i, rfl, hi⟩ := exists_bit p t k (hk.trans_eq (h.source t ht).2.1) + exact ⟨i, rfl, rfl, hi⟩ + apart i j hv he hs := bit_eq (h.left_inj (span_pos p i) (span_pos p j) hv he) hs + sorted i j hv hh := by + rcases hh with hl|⟨he, hs⟩ + · left + change left (span p i) < left (span p j) at hl + rcases lt_trichotomy (S.spanOrd (span p i)) (S.spanOrd (span p j)) with ho|ho|ho + · exact ho + · exact (hl.ne (congrArg left (S.ext_span hv ho))).elim + · exact (hl.not_gt (h.ordered _ _ (span_pos p j) (span_pos p i) hv.symm ho)).elim + · exact .inr ⟨h.left_inj (span_pos p i) (span_pos p j) hv he, hs⟩ + +open scoped Classical in +theorem rightTiles : Tiles q take (right ∘ span p) (sub p) where + bound i := by + rw [h.moved i] + exact (sub_lt p i).trans_eq (h.target _ (span_pos p i)).2.1.symm + full v j k hk := by + obtain ⟨t, ht, rfl, rfl⟩ := h.targetCover v j (Nat.zero_lt_of_lt hk) + obtain ⟨i, rfl, hi⟩ := exists_bit p t k (hk.trans_eq (h.target t ht).2.1) + exact ⟨i, h.moved i, rfl, hi⟩ + apart i j hv he hs := by + rw [h.moved i, h.moved j] at hv + exact bit_eq (h.right_inj (span_pos p i) (span_pos p j) hv he) hs + sorted i j hv hh := by + rw [h.moved i, h.moved j] at hv + have hi : span q i = shift (span p i) ∧ sub q i = skip (span p i) + sub p i := h.bits i + have hj : span q j = shift (span p j) ∧ sub q j = skip (span p j) + sub p j := h.bits j + simp only [hi.1, hj.1, hi.2, hj.2] + rcases hh with hl|⟨he, hs⟩ + · rcases h.merged _ _ (span_pos p i) (span_pos p j) hv hl with ho|⟨he, hk⟩ + · exact .inl ho + · exact .inr ⟨he, by have := sub_lt p i; omega⟩ + · rw [h.right_inj (span_pos p i) (span_pos p j) hv he] + exact .inr ⟨rfl, Nat.add_lt_add_left hs _⟩ + +end Spec +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- # Matching the source and child entries of each exterior span -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring + +open scoped Classical in +/-- Embeds `B m` into `B m × B z`. -/ +def childDst (m z : ℕ) : B m ↪ B m × B z := + ⟨fun v => (v, 0), fun _ _ he => congrArg Prod.fst he⟩ + +namespace Spec +variable {F : Type} [Field F] {S U : Scheme F} {x : S.format.obj} {y : U.format.obj} + {a b : Wire} {G H : Diagram F a b} {p : S.Presentation x G} {q : U.Presentation y H} + {z w n : ℕ} {child : B U.m ≃ B S.m × B z} {shift : S.Span → U.Span} + {skip : S.Span → ℕ} {left right : S.Span → B n} + {send : Entries S.m w z n} {take : Entries U.m w z n} + (h : Spec p q child shift skip left right send take) +include h + +open scoped Classical in +private theorem send_hit {v : B U.m} {i o : B n} + (hp : 0 < len (offsets (send (child v).1)) i) + (hc : port (offsets (send (child v).1)) i = (child v).2) + (ho : pos (offsets (send (child v).1)) i = o) : + ∃ t, 0 < S.borderLen x t ∧ left t = i ∧ left t = o ∧ (shift t).1.1 = v := by + obtain ⟨t, ht, hv, hi⟩ := h.sourceCover _ _ hp + obtain ⟨hs, _, he⟩ := h.source t ht + rw [hv, hi] at hs he + exact ⟨t, ht, hi, hi.trans (he.symm.trans ho), + child.injective (Prod.ext ((h.parent _ ht).trans hv) (hs.symm.trans hc))⟩ + +open scoped Classical in +private theorem take_hit {v : B U.m} {j o : B n} + (hp : 0 < len (offsets (take v)) j) + (ho : pos (offsets (take v)) j = o) : + ∃ t, 0 < S.borderLen x t ∧ right t = j ∧ left t = o ∧ (shift t).1.1 = v := by + obtain ⟨t, ht, hv, hj⟩ := h.targetCover _ _ hp + have he := (h.target t ht).2.2 + rw [hv, hj] at he + exact ⟨t, ht, hj, he.symm.trans ho, hv⟩ + +open scoped Classical in +theorem is_pair {v : B U.m} {i j : B n} + (hp : Paired le_rfl child.toEmbedding (childDst U.m z) (offsets ∘ send) (offsets ∘ take) v i j) + : + ∃ t, 0 < S.borderLen x t ∧ left t = i ∧ right t = j ∧ (shift t).1.1 = v := by + obtain ⟨s, _, hi, ho, _⟩ := h.send_hit hp.left hp.source hp.order + obtain ⟨t, ht, hj, he, hv⟩ := h.take_hit hp.right rfl + exact ⟨t, ht, he.trans (ho.symm.trans hi), hj, hv⟩ + +open scoped Classical in +theorem matched (hl : ∀ v, Unique (offsets (send v))) (hr : ∀ v, Unique (offsets (take v))) : + Match le_rfl child.toEmbedding (childDst U.m z) (offsets ∘ send) (offsets ∘ take) := by + intro v o + let l := offsets (send (child v).1) + let r := offsets (take v) + change amount l (child v).2 o = amount r 0 o + have agree (t : S.Span) (ht : 0 < S.borderLen x t) (ho : left t = o) (hv : (shift t).1.1 = v) : + amount l (child v).2 o = amount r 0 o := by + have hs := h.source t ht + have hd := h.target t ht + rw [← h.parent t ht, hv] at hs + rw [hv] at hd + have hs' : port l (left t) = _ ∧ len l (left t) = _ ∧ pos l (left t) = _ := hs + have hd' : port r (right t) = _ ∧ len r (right t) = _ ∧ pos r (right t) = _ := hd + have a := amount_at l (hl _) _ (hs'.2.1.symm ▸ ht) + have b := amount_at r (hr _) _ (hd'.2.1.symm ▸ ht) + rw [hs'.1, hs'.2.2, hs'.2.1, ho] at a + rw [hd'.1, hd'.2.2, hd'.2.1, ho] at b + exact a.trans b.symm + by_cases hs : 0 < amount l (child v).2 o + · obtain ⟨i, hi, hc, ho⟩ := amount_pos _ _ _ hs + obtain ⟨t, ht, _, he, hv⟩ := h.send_hit hi hc ho + exact agree t ht he hv + by_cases hd : 0 < amount r 0 o + · obtain ⟨j, hj, _, ho⟩ := amount_pos _ _ _ hd + obtain ⟨t, ht, _, he, hv⟩ := h.take_hit hj ho + exact agree t ht he hv + omega + +end Spec +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- # Prefix-sum offsets fill the exterior bank exactly -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan.Tiles +open Coloring Finset + +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} + {a b : Wire} {G : Diagram F a b} {p : S.Presentation r G} {z w n V k : ℕ} + {x : Entries S.m w z n} {row : Edge a b → B n} {off : Edge a b → ℕ} + (h : Tiles p x row off) (hs : S.Fits r V k) (hk : k < w) +include h hs hk + +open scoped Classical in +theorem small (v : B S.m) : (∑ i, (x v i).2.1.val) < 2 ^ w := by + rw [h.total_eq v] + exact (hs.2 v).trans_lt (Nat.pow_lt_pow_right (by decide) hk) + +open scoped Classical in +theorem total_at (v : B S.m) : (total (x v)).val = (S.payload r hs).length v := + (total_val _ (h.small hs hk v)).trans (h.total_eq v) + +open scoped Classical in +theorem at_bit (i : Edge a b) : + (S.index r hs (p.boundary i)).2.val = offset (offsets (x (here p i))) (row i) + off i := by + rw [h.ordinal hs i] + exact congrArg (· + off i) (offset_val _ (h.small hs hk _) _).symm + +open scoped Classical in +theorem covers : Covers (S.payload r hs) (offsets ∘ x) := by + intro v t ht + obtain ⟨i, hi⟩ := (p.boundary.trans (S.index r hs)).surjective ⟨v, ⟨t, ht⟩⟩ + have hv : here p i = v := congrArg Sigma.fst hi + have ho : (S.index r hs (p.boundary i)).2.val = t := congrArg (fun z => z.2.val) hi + rw [h.at_bit hs hk i, hv] at ho + exact ⟨row i, off i, hv ▸ h.bound i, ho⟩ + +open scoped Classical in +theorem side {E : Type} {d : ℕ} (hd : d ≤ 2 ^ z) (place : E ↪ B S.m × Fin d) + (hu : ∀ v, Unique (offsets (x v))) + (hp : ∀ v j, 0 < (x v j).2.1.val → + ∃ e, (place e).1 = v ∧ name hd place e = (x v j).1) : + Side (S.payload r hs) hd place (offsets ∘ x) := by + have val v i : offset ((offsets ∘ x) v) i = Routing.offset (fun j => (x v j).2.1.val) Fin.val i := + offset_val _ (h.small hs hk v) i + refine ⟨?_, hu, ?_, ?_, hp⟩ + · intro v c + exact (sum_le_sum_of_subset (subset_univ _)).trans_lt (h.small hs hk v) + · intro v i hi + let l := len ((offsets ∘ x) v) i + have hh := (Routing.offsetIndex (fun j => (x v j).2.1.val) Fin.val + ⟨i, ⟨l - 1, Nat.sub_lt hi Nat.one_pos⟩⟩).isLt + change Routing.offset _ _ i + (l - 1) < _ at hh + rw [← val, h.total_eq] at hh + change _ + l ≤ S.load r v + omega + · intro v i j a t hi hj he + rw [val, val] at he + let l := fun i => (x v i).2.1.val + let e := Routing.pack l Fin.val (fun _ _ _ _ eq => Fin.ext eq) + have eq : e ⟨i, ⟨a, hi⟩⟩ = e ⟨j, ⟨t, hj⟩⟩ := Fin.ext he + exact congrArg Sigma.fst (e.injective eq) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan.Tiles +end + +/- +# Transfer of independent exterior bits + +The two prefix sums give each bit its physical address. Matching +rows by the old span index ensures the same bit is read at both ends +even when the destination merges spans or changes block numbers. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan.Spec +open Coloring + +variable {F : Type} [Field F] {S U : Scheme F} {x : S.format.obj} {y : U.format.obj} + {a b : Wire} {G H : Diagram F a b} {p : S.Presentation x G} {q : U.Presentation y H} + {z w n V k V' k' : ℕ} {child : B U.m ≃ B S.m × B z} {shift : S.Span → U.Span} + {skip : S.Span → ℕ} {left right : S.Span → B n} + {send : Entries S.m w z n} {take : Entries U.m w z n} + (h : Spec p q child shift skip left right send take) + (hx : S.Fits x V k) (hy : U.Fits y V' k') (hs : k < w) (ht : k' < w) +include h + +open scoped Classical in +private theorem sourceUnique (v : B S.m) : Unique (offsets (send v)) := by + intro i j hi hj _ he + obtain ⟨t, ht, hv, rfl⟩ := h.sourceCover v i hi + obtain ⟨t', ht', hv', rfl⟩ := h.sourceCover v j hj + change (send v (left t)).2.2 = (send v (left t')).2.2 at he + have hh := (h.source _ ht).2.2 + have hh' := (h.source _ ht').2.2 + rw [hv] at hh + rw [hv'] at hh' + rwa [hh, hh'] at he + +open scoped Classical in +private theorem targetUnique (v : B U.m) : Unique (offsets (take v)) := by + intro i j hi hj _ he + obtain ⟨t, ht, hv, rfl⟩ := h.targetCover v i hi + obtain ⟨t', ht', hv', rfl⟩ := h.targetCover v j hj + apply congrArg right + apply h.left_inj ht ht' + · rw [← h.parent _ ht, ← h.parent _ ht', hv, hv'] + · rw [← (h.target _ ht).2.2, ← (h.target _ ht').2.2, hv, hv'] + exact he + +include hs in +open scoped Classical in +private theorem srcSide : Side (S.payload x hx) le_rfl child.toEmbedding (offsets ∘ send) := by + apply h.leftTiles.side hx hs le_rfl _ h.sourceUnique + intro v j _ + exact ⟨child.symm (v, (send v j).1), by simp, by simp [name]⟩ + +include ht in +open scoped Classical in +private theorem dstSide : Side (U.payload y hy) le_rfl (childDst U.m z) (offsets ∘ take) := by + apply h.rightTiles.side hy ht le_rfl _ h.targetUnique + intro v j hj + obtain ⟨t, ht, rfl, rfl⟩ := h.targetCover v j hj + exact ⟨(shift t).1.1, rfl, (h.target t ht).1.symm⟩ + +include hs ht in +open scoped Classical in +theorem supplies : + p.Supplies q hx hy + (emit (fun i => (Match.rowIndex U.m z).symm (child.symm (Match.rowIndex S.m z i), 0)) + (send, take)) := by + have a := h.srcSide hx hs + have b := h.dstSide hy ht + have c := h.matched h.sourceUnique h.targetUnique + have d := h.rightTiles.covers hy ht + let M := traffic a b c d + refine ⟨M, ?_, ?_⟩ + · refine valid a b c d _ _ _ (h.leftTiles.total_at hx hs) (h.rightTiles.total_at hy ht) ?_ + intro e _ + change (Match.rowIndex U.m z).symm + (child.symm (Match.rowIndex S.m z ((Match.rowIndex S.m z).symm (child e))), 0) = + (Match.rowIndex U.m z).symm (e, 0) + simp + · intro e k + obtain ⟨i, j, n, paired, hn, hi, hj⟩ := transmission a b c d e k + obtain ⟨t, hp, rfl, rfl, hv⟩ := h.is_pair paired + have hu : (child e).1 = t.1.1 := hv ▸ h.parent t hp + change n < (send (child e).1 (left t)).2.1.val at hn + rw [hu, (h.source t hp).2.1] at hn + obtain ⟨z, hz, hoff⟩ := exists_bit p t n hn + have hleft : here p z = (child e).1 := (congrArg (fun t : S.Span => t.1.1) hz).trans hu.symm + have hright : here q z = e := (congrArg (fun u : U.Span => u.1.1) (h.bits z).1).trans + ((congrArg (fun t => (shift t).1.1) hz).trans hv) + have hl : S.index x hx (p.boundary z) = M.source e k := by + refine Sigma.ext hleft ((Fin.heq_ext_iff (congrArg (S.payload x hx).length hleft)).mpr ?_) + rw [h.leftTiles.at_bit hx hs, hleft, Function.comp_apply, hz, hoff] + exact hi.symm + have hr : U.index y hy (q.boundary z) = M.target e k := by + refine Sigma.ext hright ((Fin.heq_ext_iff (congrArg (U.payload y hy).length hright)).mpr ?_) + rw [h.rightTiles.at_bit hy ht, hright, Function.comp_apply, hz, hoff] + exact hj.symm + rw [← hr, ← hl, p.transfer_named] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan.Spec +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/SpanTiles.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/SpanTiles.lean new file mode 100644 index 0000000000..46094155c3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/SpanTiles.lean @@ -0,0 +1,980 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.PayloadProgram +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Fragments +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.BoardPush +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Keys + +/-! The cost of packing host records is linear in the transported width. -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload.Script +open Coloring Transcript + +/-- The value specified by `50000 * (k + k' + 2) * (c + c' + (2 ^ m + 2 ^ m') * (v + (101 + m + +m' + w + k') ^ 60) + 2 ^ (m + p) * (m' + p))`. -/ +def cost (m k m' k' p w v c c' : ℕ) := + 50000 * (k + k' + 2) * (c + c' + (2 ^ m + 2 ^ m') * (v + (101 + m + m' + w + k') ^ 60) + 2 ^ (m + + p) * (m' + p)) + +variable {m V k m' V' k' p w n v c c' : ℕ} + +private theorem bound (ha : (item w p n).width ≤ v) : + rawCost m V k m' V' k' p w n v c c' ≤ cost m k m' k' p w v c c' := by + let K := k + k' + 2 + let N := 2 ^ m + 2 ^ m' + let B := (101 + m + m' + w + k') ^ 60 + let X := c + c' + N * (v + B) + 2 ^ (m + p) * (m' + p) + let I := (item w p n).width + let C := Fintype.card (Slot (2 ^ m) V k) + let C' := Fintype.card (Slot (2 ^ m') V' k') + let a := (Fragments.Input w p n).width + let P := (PeerLayout.input m m' p w).width + have hi : I = a + w := by simp only [I, a, Format.width_pair, Format.width_addr] + have hv : N * I ≤ N * (v + B) := Nat.mul_le_mul_left _ (ha.trans (Nat.le_add_right _ _)) + have hs : (Script m m' p w n).width ≤ X := by + have e : (Script m m' p w n).width = N * I + 2 ^ (m + p) * (m' + p) := by + simp only [Script, PeerLayout.input, PeerLayout.lengths, I, Fragments.Input, + Format.width_pair, Format.width_vec, Format.width_addr, N] + ring + rw [e] + unfold X + omega + have hP : P ≤ X := by + rw [Format.width_pair] at hs + exact (Nat.le_add_right _ _).trans hs + have hf : (first m m' p w n).width ≤ 3 * X := by + have e : (first m m' p w n).width = N * (w + I) + P := by + simp only [first, Redistribute.input, Format.width_pair, Format.width_vec, Format.width_addr, + N, I, P] + ring + rw [e] + have hb : N * (w + I) ≤ 2 * X := calc + _ ≤ N * (2 * I) := Nat.mul_le_mul_left _ (by omega) + _ ≤ _ := by rw [mul_left_comm]; exact Nat.mul_le_mul_left _ (hv.trans (by unfold X; omega)) + omega + have hb : C + C' ≤ K * N := by + unfold C C' N + rw [mul_add] + exact Nat.add_le_add ((Transcript.card_slots ..).trans (Nat.mul_le_mul_right _ (by omega))) + ((Transcript.card_slots ..).trans (Nat.mul_le_mul_right _ (by omega))) + have hh : (C + C') * (I + B) ≤ K * X := calc + _ ≤ (K * N) * (v + B) := Nat.mul_le_mul hb (Nat.add_le_add_right ha _) + _ ≤ _ := by rw [mul_assoc]; exact Nat.mul_le_mul_left _ (by unfold X; omega) + have hrec : ((payloadBank m V k m' V' k').records w p n).width = (C + C') * a := by + simp only [Bank.records, Fmt.width_pi, Finset.sum_const, Finset.card_univ, smul_eq_mul] + change Fintype.card (Slot (2 ^ m) V k ⊕ Slot (2 ^ m') V' k') * a = _ + rw [Fintype.card_sum] + have hmove : (moved m V k m' V' k' p w n).width = (C + C') * I + P := by + simp only [I, C, C', P, moved, Format.width_pair, Redistribute.output, Fmt.width_pi, + Finset.sum_const, + Finset.card_univ, smul_eq_mul, add_mul] + have hstage : (staged m V k m' V' k' p w n).width = (C + C') * a + (P + C' * w) := by + unfold staged + rw [Format.width_pair, hrec, Format.width_pair, Fmt.width_pi] + simp only [Format.width_addr, Finset.sum_const, Finset.card_univ, smul_eq_mul] + rfl + have hpow : (100 + (w + k' + 1)) ^ 2 ≤ B := + (Nat.pow_le_pow_left (by omega : 100 + (w + k' + 1) ≤ 101 + m + m' + w + k') _).trans + (Nat.pow_le_pow_right (by omega) (by decide)) + have hr (l b c₀ : ℕ) (hl : l ≤ m + m') (hn : 2 ^ l ≤ N) (hb : b + 1 ≤ K) (hc : c₀ ≤ c + c') : + Redistribute.cost l b w v c₀ ≤ 10000 * (K * X) := by + have hp : (101 + l + w) ^ 60 ≤ B := Nat.pow_le_pow_left (by omega) _ + have hle : Redistribute.budget l w v ≤ N * (v + B) + := Nat.mul_le_mul hn (Nat.add_le_add_left hp v) + unfold Redistribute.cost + rw [mul_assoc] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul hb ((Nat.add_le_add hc hle).trans (Nat.le_add_right + _ _))) + have hr₁ := hr m k c (by omega) (Nat.le_add_right _ _) (by omega) (by omega) + have hr₂ := hr m' k' c' (by omega) (Nat.le_add_left _ _) (by omega) (by omega) + have hX : X ≤ K * X := Nat.le_mul_of_pos_left _ (by omega) + have hsize : cost m k m' k' p w v c c' = 50000 * (K * X) := mul_assoc .. + unfold rawCost + rw [hsize, hrec, hstage, hmove] + have he := Nat.mul_le_mul_left C' hpow + rw [hi] at hh ⊢ + linarith only [he, hh, hr₁, hr₂, hX, hP, hf, hs, Nat.zero_le (C * w), Nat.zero_le (C' * w), + Nat.zero_le (C * B), Nat.zero_le (C' * B), Nat.zero_le ((C + C') * a), Nat.zero_le (K * X)] + +theorem realize {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} + (hu : 3 ≤ u) (ht : Radix.Tag F m v c) (ht' : Radix.Tag F m' v c') + (ha : (item w p n).width ≤ v) : + Map F u L (Script m m' p w n) (Out m V k m' V' k' p w n) pack (cost m k m' k' p w v c c') := + (build hu ht ht' ha).mono (bound ha) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload.Script +end + +/- # Correctness criteria on logical host records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload.Script + +open Coloring +variable {m V k m' V' k' d p w n : ℕ} {x : Payload m V k} {y : Payload m' V' k'} + {M : Traffic x y d} {hd : d ≤ 2 ^ p} {q : (Script m m' p w n).obj} + +open scoped Classical in +/-- The data for the bounds construction, including `inside`, `apart`. -/ +structure Bounds (z : (Fragments.Input w p n).obj) : Prop where + inside : ∀ i, let a := z.2 i + a.2.1.val + a.2.2.1.val ≤ (z.1 a.1).val + apart : ∀ i j t, (z.2 i).1 = (z.2 j).1 → + Intervals.covers (z.2 i).2 t → Intervals.covers (z.2 j).2 t → j = i + +open scoped Classical in +/-- The condition `∃ i, (z i).1 = port ∧ Intervals.covers (z i).2 pos ∧ (z i).2.2.2.val + (pos - +(z i).2.1.val) = value` on the specified data. -/ +def At (z : B n → (Fragments.Entry w p).obj) (port : B p) (pos value : ℕ) : Prop := + ∃ i, (z i).1 = port ∧ Intervals.covers (z i).2 pos ∧ + (z i).2.2.2.val + (pos - (z i).2.1.val) = value + +open scoped Classical in +/-- The data for the valid construction, including `peer`, `left`, `right`, `send`, `get`. -/ +structure Valid (M : Traffic x y d) (hd : d ≤ 2 ^ p) (q : (Script m m' p w n).obj) : Prop where + peer : PeerLayout.Fits M hd q.1 + left : ∀ s, Bounds (q.1.1.1.2 s, q.2.1 s) + right : ∀ s, Bounds (q.1.1.2.2 s, q.2.2 s) + send : ∀ e j, At (q.2.1 (M.src e).1) ((M.src e).2.castLE hd) j.val (M.send e j).val + get : ∀ e j, At (q.2.2 (M.dst e).1) ((M.dst e).2.castLE hd) j.val (M.get e j).val + +open scoped Classical in +theorem Valid.pieces (h : Valid M hd q) : M.links.Pieces hd (pack q).1 := by + let t := pack (V := V) (k := k) (V' := V') (k' := k') q + have hempty : Bounds (empty w p n) := by + constructor + · simp [empty] + · simp [Intervals.covers, empty] + have hs (s) : Bounds (t.1 s) := by + unfold t + rcases s with s | s + · cases he : x.seat.read s with + | none => rw [empty_source h.peer s he]; exact hempty + | some a => rw [(x.seat.valid _ _).mp he, source h.peer a]; exact h.left a + · cases he : y.seat.read s with + | none => rw [empty_destination h.peer s he]; exact hempty + | some a => rw [(y.seat.valid _ _).mp he, destination h.peer a]; exact h.right a + refine ⟨fits h.peer, fun s => (hs s).inside, fun s => (hs s).apart, ?_⟩ + rintro ⟨e, _|_⟩ j + · change At (t.1 (.inl (x.seat.write (M.src e).1))).2 ((M.src e).2.castLE hd) j.val (M.send e + j).val + unfold t + rw [source h.peer] + exact h.send _ _ + · change At (t.1 (.inr (y.seat.write (M.dst e).1))).2 ((M.dst e).2.castLE hd) j.val (M.get e + j).val + unfold t + rw [destination h.peer] + exact h.get _ _ + +open scoped Classical in +/-- The value specified by `command hd ∘ pack`. -/ +def decode (hd : d ≤ 2 ^ p) : (Script m m' p w n).obj → + (PeerLayout.S m V k m' V' k' d).control.obj := command hd ∘ pack + +open scoped Classical in +theorem Valid.represents (h : Valid M hd q) : M.links.Represents (decode hd q) := + Script.represents hd M h.peer h.pieces + +open scoped Classical in +theorem Valid.carries (h : Valid M hd q) (a : (Fmt.payload m V k).obj) (b : (Fmt.payload m' V' + k').obj) : + (PeerLayout.S m V k m' V' k' d).Carries (decode hd q) a b ↔ M.links.Matches a b := + Bank.Links.Represents.carries M.links h.represents a b + +open scoped Classical in +theorem decode_net {F : Type} [Field F] {u : ℕ} {L : Set (Table F)} {v c c' : ℕ} + (hu : 3 ≤ u) (hd : d ≤ 2 ^ p) (ht : Radix.Tag F m v c) (ht' : Radix.Tag F m' v c') + (ha : (item w p n).width ≤ v) : + Map F u L (Script m m' p w n) (PeerLayout.S m V k m' V' k' d).control + (decode hd) (cost m k m' k' p w v c c' + commandCost m V k m' V' k' d p w n) := by + have h := realize (V := V) (V' := V') (k := k) (k' := k') (L := L) hu ht ht' ha + have hc := command_net (m := m) (m' := m') (V := V) (V' := V') (k := k) (k' := k') + (w := w) (n := n) hd (F := F) (L := L) hu + unfold decode + exact h.comp hc + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Payload.Script +end + +/- The positive spans of each contact partition its channel positions. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring Finset + +variable {w p n : ℕ} (x : (Input w p n).obj) + +/-- The value specified by `(x i).1`. -/ +abbrev port (i : B n) := (x i).1 +/-- The value specified by `(x i).2.1.val`. -/ +abbrev len (i : B n) := (x i).2.1.val +/-- The value specified by `(x i).2.2.1`. -/ +abbrev pos (i : B n) := (x i).2.2.1 +/-- The value specified by `(x i).2.2.2.val`. -/ +abbrev offset (i : B n) := (x i).2.2.2.val +/-- The value specified by `((pack x).1 c).val`. -/ +def extent (c : B p) := ((pack x).1 c).val +/-- The value specified by `((pack x).2 i).2.1.val`. -/ +def start (i : B n) := ((pack x).2 i).2.1.val + +/-- The condition `∀ i j, 0 < len x i → 0 < len x j → port x i = port x j → pos x i = pos x j → +i = j` on the specified data. -/ +def Unique : Prop := ∀ i j, 0 < len x i → 0 < len x j → + port x i = port x j → pos x i = pos x j → i = j + +theorem inside (hx : Fits x) (i : B n) : start x i + len x i ≤ extent x (port x i) := by + rw [start, starts _ hx, extent, lengths _ hx] + let f := univ.filter fun j => port x j = port x i ∧ pos x j < pos x i + change (∑ j ∈ f, len x j) + len x i ≤ _ + rw [add_comm, ← sum_insert (by simp [f] : i ∉ f)] + exact sum_le_sum_of_subset (insert_subset (by simp) (by + intro j hj + simpa using (mem_filter.mp hj).2.1)) + +theorem earlier_le (hx : Fits x) {i j : B n} (hc : port x i = port x j) + (ho : pos x i < pos x j) : start x i + len x i ≤ start x j := by + rw [start, start, starts _ hx, starts _ hx] + let f := univ.filter fun u => port x u = port x i ∧ pos x u < pos x i + change (∑ u ∈ f, len x u) + len x i ≤ _ + rw [add_comm, ← sum_insert (by simp [f] : i ∉ f)] + refine sum_le_sum_of_subset (insert_subset (mem_filter.mpr ⟨mem_univ _, hc, ho⟩) ?_) + intro u hu + exact mem_filter.mpr ⟨mem_univ _, (mem_filter.mp hu).2.1.trans hc, + (mem_filter.mp hu).2.2.trans ho⟩ + +theorem bounds (hx : Fits x) (hu : Unique x) : Payload.Script.Bounds (pack x) := by + refine ⟨inside _ hx, fun i j t h hi hj => ?_⟩ + change port x i = port x j at h + change start x i ≤ t ∧ t < start x i + len x i at hi + change start x j ≤ t ∧ t < start x j + len x j at hj + rcases lt_trichotomy (pos x i) (pos x j) with hlt|he|hgt + · have := earlier_le x hx h hlt + omega + · exact (hu _ _ (by omega) (by omega) h he).symm + · have := earlier_le x hx h.symm hgt + omega + +/-- Indexes the block by the coordinates of `Σ i : {i // port x i = c}, Fin (len x i.val)`. -/ +abbrev Block (c : B p) := Σ i : {i // port x i = c}, Fin (len x i.val) + +/-- The value specified by `⟨start x i.1.val + i.2.val, (Nat.add_lt_add_left i.2.isLt +_).trans_le ((inside x hx _).trans_eq (congrArg (extent x) i.1.2))⟩`. -/ +def index (hx : Fits x) (c : B p) (i : Block x c) : Fin (extent x c) := + ⟨start x i.1.val + i.2.val, (Nat.add_lt_add_left i.2.isLt _).trans_le + ((inside x hx _).trans_eq (congrArg (extent x) i.1.2))⟩ + +theorem index_covers (hx : Fits x) (c : B p) (i : Block x c) : + Intervals.covers ((pack x).2 i.1.val).2 (index x hx c i).val := + ⟨Nat.le_add_right _ _, Nat.add_lt_add_left i.2.isLt _⟩ + +theorem index_bijective (hx : Fits x) (hu : Unique x) (c : B p) : + Function.Bijective (index x hx c) := by + apply (Fintype.bijective_iff_injective_and_card _).mpr + constructor + · rintro ⟨i, a⟩ ⟨j, b⟩ he + have ha := index_covers x hx c ⟨i, a⟩ + have hb := index_covers x hx c ⟨j, b⟩ + rw [he] at ha + have eq : j = i := Subtype.ext ((bounds x hx hu).apart i.val j.val _ (i.2.trans j.2.symm) ha hb) + subst j + have h := congrArg Fin.val he + have : a = b := Fin.ext (Nat.add_left_cancel h) + rw [this] + · simp only [Block, Fintype.card_sigma, Fintype.card_fin] + rw [extent, lengths _ hx] + exact (sum_subtype _ (by simp) (len x)).symm + +/-- The equivalence obtained by `Equiv.ofBijective (index x hx c) (index_bijective x hx hu c)`. -/ +def channel (hx : Fits x) (hu : Unique x) (c : B p) : Block x c ≃ Fin (extent x c) := + Equiv.ofBijective (index x hx c) (index_bijective x hx hu c) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- Local bank conditions for one side of a payload transfer. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan + +open Coloring Finset +variable {E : Type} {m V k d p w n : ℕ} + +/-- The indexing data represented by `B m → (Input w p n).obj`. -/ +abbrev Rows (m w p n : ℕ) := B m → (Input w p n).obj + +/-- The value specified by `(place e).2.castLE hd`. -/ +def name (hd : d ≤ 2 ^ p) (place : E ↪ B m × Fin d) (e : E) := (place e).2.castLE hd + +/-- Computes the size by the application `extent (x (place e).1) (name hd place e)`. -/ +def size (hd : d ≤ 2 ^ p) (place : E ↪ B m × Fin d) (x : Rows m w p n) (e : E) := + extent (x (place e).1) (name hd place e) + +/-- The data for the side construction, including `fits`, `unique`, `bound`, `apart`, +`assigned`. -/ +structure Side (u : Payload m V k) (hd : d ≤ 2 ^ p) (place : E ↪ B m × Fin d) + (x : Rows m w p n) : Prop where + fits : ∀ b, Fits (x b) + unique : ∀ b, Unique (x b) + bound : ∀ b i, 0 < len (x b) i → offset (x b) i + len (x b) i ≤ u.length b + apart : ∀ b i j a t, a < len (x b) i → t < len (x b) j → + offset (x b) i + a = offset (x b) j + t → i = j + assigned : ∀ b i, 0 < len (x b) i → ∃ e, (place e).1 = b ∧ name hd place e = port (x b) i + +/-- The condition `∀ b t, t < u.length b → ∃ i a, a < len (x b) i ∧ offset (x b) i + a = t` on +the specified data. -/ +def Covers (u : Payload m V k) (x : Rows m w p n) : Prop := + ∀ b t, t < u.length b → ∃ i a, a < len (x b) i ∧ offset (x b) i + a = t + +/-- A particular occurrence of a bit on a contact. -/ +def Hit (x : (Input w p n).obj) (c : B p) (t z : ℕ) : Prop := + ∃ i a, port x i = c ∧ a < len x i ∧ start x i + a = t ∧ offset x i + a = z + +namespace Hit +variable {x : (Input w p n).obj} {c : B p} {t z z' : ℕ} + +theorem at_bit (h : Hit x c t z) : Payload.Script.At (pack x).2 c t z := by + obtain ⟨i, a, hc, ha, rfl, rfl⟩ := h + refine ⟨i, hc, ⟨Nat.le_add_right _ _, Nat.add_lt_add_left ha _⟩, ?_⟩ + change offset x i + (start x i + a - start x i) = _ + omega + +theorem determined (hx : Fits x) (hu : Unique x) (h : Hit x c t z) (h' : Hit x c t z') : z = z' + := by + obtain ⟨i, hi, ht, he⟩ := h.at_bit + obtain ⟨j, hj, ht', he'⟩ := h'.at_bit + have hij := (bounds x hx hu).apart i j t (hi.trans hj.symm) ht ht' + subst j + exact he.symm.trans he' + +end Hit + +namespace Side + +variable {u : Payload m V k} {hd : d ≤ 2 ^ p} {place : E ↪ B m × Fin d} {x : Rows m w p n} + (h : Side u hd place x) + +include h in +theorem filled (e : E) (t : Fin (size hd place x e)) : + ∃ v : Fin (u.length (place e).1), Hit (x (place e).1) (name hd place e) t.val v.val := by + let Y := x (place e).1 + let c := name hd place e + obtain ⟨⟨i, a⟩, ha⟩ := (index_bijective Y (h.fits _) (h.unique _) c).2 t + have hb := (Nat.add_lt_add_left a.isLt (offset Y i.val)).trans_le + (h.bound _ _ (Nat.zero_lt_of_lt a.isLt)) + exact ⟨⟨_, hb⟩, i.val, a.val, i.2, a.isLt, congrArg Fin.val ha, rfl⟩ + +include h in +theorem separate {e e' : E} {a b v : ℕ} (he : (place e).1 = (place e').1) + (ha : Hit (x (place e).1) (name hd place e) a v) + (hb : Hit (x (place e').1) (name hd place e') b v) : e = e' ∧ a = b := by + rw [he] at ha + obtain ⟨i, k, hi, hk, ht, hu⟩ := ha + obtain ⟨j, l, hj, hl, ht', hu'⟩ := hb + have hij := h.apart _ _ _ _ _ hk hl (hu.trans hu'.symm) + subst j + have hn : name hd place e = name hd place e' := hi.symm.trans hj + have hkl : k = l := Nat.add_left_cancel (hu.trans hu'.symm) + have hv := congrArg Fin.val hn + exact ⟨place.injective (Prod.ext he (Fin.ext hv)), by rw [← ht, ← ht', hkl]⟩ + +/-- Embeds `Fin (size hd place x e)` into `Fin (u.length (place e).1) where toFun t`. -/ +def point (e : E) : Fin (size hd place x e) ↪ Fin (u.length (place e).1) where + toFun t := (h.filled e t).choose + inj' := by + intro a b he + have ha := (h.filled e a).choose_spec + have hb := (h.filled e b).choose_spec + change (h.filled e a).choose = (h.filled e b).choose at he + rw [he] at ha + exact Fin.ext (h.separate rfl ha hb).2 + +theorem spec (e : E) (t : Fin (size hd place x e)) : + Hit (x (place e).1) (name hd place e) t.val (h.point e t).val := + (h.filled e t).choose_spec + +theorem used (e : E) (i : B n) (hi : port (x (place e).1) i = name hd place e) + (a : ℕ) (ha : a < len (x (place e).1) i) : + ∃ t : Fin (size hd place x e), t.val = start (x (place e).1) i + a ∧ + (h.point e t).val = offset (x (place e).1) i + a := by + let t := index _ (h.fits _) _ ⟨⟨i, hi⟩, ⟨a, ha⟩⟩ + exact ⟨t, rfl, Hit.determined (h.fits _) (h.unique _) (h.spec e t) ⟨i, a, hi, ha, rfl, rfl⟩⟩ + +include h in +theorem occupied (b : B m) (c : B p) (hc : 0 < extent (x b) c) : + ∃ e, (place e).1 = b ∧ name hd place e = c := by + obtain ⟨⟨i, a⟩, _⟩ := (index_bijective _ (h.fits b) (h.unique b) c).2 ⟨0, hc⟩ + obtain ⟨e, he, hi⟩ := h.assigned b i.val (Nat.zero_lt_of_lt a.isLt) + exact ⟨e, he, hi.trans i.2⟩ + +theorem onto (hc : Covers u x) (j : u.Bit) : + ∃ e t, (⟨(place e).1, h.point e t⟩ : u.Bit) = j := by + obtain ⟨b, ⟨t, ht⟩⟩ := j + obtain ⟨i, a, ha, rfl⟩ := hc b t ht + obtain ⟨e, rfl, he⟩ := h.assigned b i (Nat.zero_lt_of_lt ha) + obtain ⟨j, _, hj⟩ := h.used e i he.symm a ha + exact ⟨e, j, congrArg (Sigma.mk _) (Fin.ext hj)⟩ + +end Side +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- Pairing spans by order gives the same offsets at both ends. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring Finset + +variable {w p n : ℕ} (x : (Input w p n).obj) + +/-- The sum of `len x i` indexed by `i with port x i = c ∧ pos x i = o`. -/ +def amount (c : B p) (o : B n) := ∑ i with port x i = c ∧ pos x i = o, len x i + +theorem amount_pos (c : B p) (o : B n) (h : 0 < amount x c o) : + ∃ i, 0 < len x i ∧ port x i = c ∧ pos x i = o := by + obtain ⟨i, hi, he⟩ := exists_ne_zero_of_sum_ne_zero h.ne' + exact ⟨i, Nat.pos_of_ne_zero he, (mem_filter.mp hi).2⟩ + +theorem amount_at (hu : Unique x) (i : B n) (hi : 0 < len x i) : + amount x (port x i) (pos x i) = len x i := by + refine sum_eq_single i (fun j hj hn => ?_) (by simp) + obtain ⟨hc, ho⟩ := (mem_filter.mp hj).2 + by_contra! hz + exact hn (hu _ _ (Nat.pos_of_ne_zero hz) hi hc ho) + +private theorem grouped (c : B p) (s : Finset (B n)) : + ∑ j ∈ s, amount x c j = ∑ i with port x i = c ∧ pos x i ∈ s, len x i := by + simpa only [amount, filter_filter] using + sum_fiberwise_eq_sum_filter (univ.filter (fun i => port x i = c)) s (pos x) (len x) + +theorem extent_eq (h : Fits x) (c : B p) : extent x c = ∑ j, amount x c j := by + rw [extent, lengths _ h, grouped] + simp only [mem_univ, and_true] + +theorem start_eq_sum (h : Fits x) (i : B n) : + start x i = ∑ j ∈ Iio (pos x i), amount x (port x i) j := by + rw [start, starts _ h, grouped] + simp only [mem_Iio] + +variable {E : Type} {m V k m' V' k' d : ℕ} + +/-- The condition `∀ e o, amount (x (src e).1) (name hd src e) o = amount (y (dst e).1) (name hd +dst e) o` on the specified data. -/ +def Match (hd : d ≤ 2 ^ p) (src : E ↪ B m × Fin d) (dst : E ↪ B m' × Fin d) + (x : Rows m w p n) (y : Rows m' w p n) : Prop := + ∀ e o, amount (x (src e).1) (name hd src e) o = amount (y (dst e).1) (name hd dst e) o + +variable {hd : d ≤ 2 ^ p} {src : E ↪ B m × Fin d} {dst : E ↪ B m' × Fin d} + {x : Rows m w p n} {y : Rows m' w p n} {u : Payload m V k} {v : Payload m' V' k'} + (hx : Side u hd src x) (hy : Side v hd dst y) (h : Match hd src dst x y) + +include hx hy h in +theorem Match.size_eq (e : E) : size hd src x e = size hd dst y e := by + unfold size + rw [extent_eq _ (hx.fits _), extent_eq _ (hy.fits _)] + exact sum_congr rfl fun j _ => h e j + +/-- The data for the paired construction, including `source`, `target`, `order`, `left`, +`right`. -/ +structure Paired (hd : d ≤ 2 ^ p) (src : E ↪ B m × Fin d) (dst : E ↪ B m' × Fin d) + (x : Rows m w p n) (y : Rows m' w p n) (e : E) (i j : B n) : Prop where + source : port (x (src e).1) i = name hd src e + target : port (y (dst e).1) j = name hd dst e + order : pos (x (src e).1) i = pos (y (dst e).1) j + left : 0 < len (x (src e).1) i + right : 0 < len (y (dst e).1) j + +include hx hy h in +theorem Match.aligned {e : E} {i j : B n} (hp : Paired hd src dst x y e i j) : + len (x (src e).1) i = len (y (dst e).1) j ∧ start (x (src e).1) i = start (y (dst e).1) j := by + constructor + · rw [← amount_at _ (hx.unique _) i hp.left, ← amount_at _ (hy.unique _) j hp.right, + hp.source, hp.target, hp.order] + exact h _ _ + · rw [start_eq_sum _ (hx.fits _), start_eq_sum _ (hy.fits _), hp.source, hp.target, hp.order] + exact sum_congr rfl fun j _ => h e j + +include hx h in +theorem Match.partner {e : E} {i : B n} (hc : port (x (src e).1) i = name hd src e) + (hi : 0 < len (x (src e).1) i) : ∃ j, Paired hd src dst x y e i j := by + have he := amount_at _ (hx.unique _) i hi + rw [hc, h] at he + obtain ⟨j, hj, hc', ho⟩ := amount_pos _ _ _ (he.symm ▸ hi) + exact ⟨j, hc, hc', ho.symm, hi, hj⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- Construct actual payload transfers from matched local span lists. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring + +variable {E : Type} {w p n m V k m' V' k' d : ℕ} +variable {hd : d ≤ 2 ^ p} {src : E ↪ B m × Fin d} {dst : E ↪ B m' × Fin d} + {x : Rows m w p n} {y : Rows m' w p n} {u : Payload m V k} {v : Payload m' V' k'} + (hx : Side u hd src x) (hy : Side v hd dst y) (h : Match hd src dst x y) (hc : Covers v y) + +/-- Builds `Payload.Traffic u v d where E` with the specified `src`, `dst`, `length`, `send`. -/ +def traffic : Payload.Traffic u v d where + E := E + src := src + dst := dst + length := size hd src x + send := hx.point + get e := (finCongr (h.size_eq hx hy e)).toEmbedding.trans (hy.point e) + disjoint_send e e' i j he hv := hx.separate he (hx.spec e i) (hv.symm ▸ hx.spec e' j) + disjoint_get e e' i j he hv := by + let i' := i.cast (h.size_eq hx hy e) + let j' := j.cast (h.size_eq hx hy e') + change (hy.point e i').val = (hy.point e' j').val at hv + exact hy.separate he (hy.spec e i') (hv.symm ▸ hy.spec e' j') + covers j := by + obtain ⟨e, t, ht⟩ := hy.onto hc j + exact ⟨e, t.cast (h.size_eq hx hy e).symm, ht⟩ + +/-- The indexed operation `((((u, fun i => (pack (x i)).1), (v, fun i => (pack (y i)).1)), +peer), (fun i => (pack (x i)).2), (fun i => (pack (y i)).2))`. -/ +def assemble (u : B m → B w) (v : B m' → B w) (x : Rows m w p n) (y : Rows m' w p n) + (peer : B (m + p) → B (m' + p)) : (Payload.Script m m' p w n).obj := + ((((u, fun i => (pack (x i)).1), (v, fun i => (pack (y i)).1)), peer), + (fun i => (pack (x i)).2), (fun i => (pack (y i)).2)) + +theorem valid (a : B m → B w) (b : B m' → B w) (peer : B (m + p) → B (m' + p)) + (ha : ∀ i, (a i).val = u.length i) (hb : ∀ i, (b i).val = v.length i) + (hp : ∀ e, 0 < size hd src x e → peer (PeerLayout.post hd (src e)) + = PeerLayout.post hd (dst e)) : + Payload.Script.Valid (traffic hx hy h hc) hd (assemble a b x y peer) := by + refine ⟨⟨ha, hb, fun _ => rfl, fun e => (h.size_eq hx hy e).symm, + hx.occupied, hy.occupied, hp⟩, fun _ => bounds _ (hx.fits _) (hx.unique _), + fun _ => bounds _ (hy.fits _) (hy.unique _), fun e j => (hx.spec e j).at_bit, + fun e j => (hy.spec e (j.cast (h.size_eq hx hy e))).at_bit⟩ + +theorem get_of_paired {e : E} {i j : B n} (hp : Paired hd src dst x y e i j) {a : ℕ} + (ha : a < len (x (src e).1) i) : + ∃ t : Fin ((traffic hx hy h hc).length e), t.val = start (x (src e).1) i + a ∧ + ((traffic hx hy h hc).send e t).val = offset (x (src e).1) i + a ∧ + ((traffic hx hy h hc).get e t).val = offset (y (dst e).1) j + a := by + obtain ⟨he, hs⟩ := h.aligned hx hy hp + obtain ⟨t, ht, hu⟩ := hx.used e i hp.source a ha + obtain ⟨r, hr, hv⟩ := hy.used e j hp.target a (ha.trans_eq he) + have eq : t.cast (h.size_eq hx hy e) = r := Fin.ext (ht.trans (by rw [hs, hr])) + refine ⟨t, ht, hu, ?_⟩ + change (hy.point e (t.cast (h.size_eq hx hy e))).val = _ + rwa [eq] + +theorem transmission (e : E) (t : Fin ((traffic hx hy h hc).length e)) : + ∃ i j a, Paired hd src dst x y e i j ∧ a < len (x (src e).1) i ∧ + ((traffic hx hy h hc).send e t).val = offset (x (src e).1) i + a ∧ + ((traffic hx hy h hc).get e t).val = offset (y (dst e).1) j + a := by + obtain ⟨i, a, hp, ha, ht, _⟩ := hx.spec e t + obtain ⟨j, hj⟩ := h.partner hx hp (Nat.zero_lt_of_lt ha) + obtain ⟨r, hr, hs, hg⟩ := get_of_paired hx hy h hc hj ha + rw [show t = r from Fin.ext (ht.symm.trans hr.symm)] + exact ⟨i, j, a, hj, ha, hs, hg⟩ + +/-- This equivalence applies to bit equality and to arbitrary predicates +on the two bank addresses. -/ +theorem carries_iff (P : E → ℕ → ℕ → Prop) : + (∀ e t, P e ((traffic hx hy h hc).send e t).val ((traffic hx hy h hc).get e t).val) ↔ + ∀ e i j, Paired hd src dst x y e i j → ∀ a, a < len (x (src e).1) i → + P e (offset (x (src e).1) i + a) (offset (y (dst e).1) j + a) := by + constructor + · intro H e i j hp a ha + obtain ⟨t, _, hs, hg⟩ := get_of_paired hx hy h hc hp ha + rw [← hs, ← hg] + exact H e t + · intro H e t + obtain ⟨i, j, a, hp, ha, hs, hg⟩ := transmission hx hy h hc e t + rw [hs, hg] + exact H _ _ _ hp _ ha + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- # Verifying a command against the two named exterior boundaries -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Coloring + +variable {F : Type} [Field F] {S U : Scheme F} {x : S.format.obj} {y : U.format.obj} + {a b : Wire} {G H : Diagram F a b} (p : S.Presentation x G) (q : U.Presentation y H) + {V k V' k' : ℕ} (hx : S.Fits x V k) (hy : U.Fits y V' k') + +open scoped Classical in +/-- The value specified by `S.transfer U hx hy (p.boundary ∘ q.boundary.symm)`. -/ +def transferTo := S.transfer U hx hy (p.boundary ∘ q.boundary.symm) + +open scoped Classical in +theorem transfer_named (i : slots a ⊕ slots b) : + p.transferTo q hx hy (U.index y hy (q.boundary i)) = S.index x hx (p.boundary i) := by + simp only [transferTo, transfer, Function.comp_apply, Equiv.symm_apply_apply] + +variable {l w n : ℕ} (cmd : (Payload.Script S.m U.m l w n).obj) + +open scoped Classical in +/-- The supplies of type `Prop` for the given inputs. -/ +def Supplies : Prop := + ∃ M : Payload.Traffic (S.payload x hx) (U.payload y hy) (2 ^ l), + Payload.Script.Valid M le_rfl cmd ∧ ∀ e t, p.transferTo q hx hy (M.target e t) = M.source e t + +variable {p q hx hy cmd} +local notation "Z" => PeerLayout.S S.m V k U.m V' k' (2 ^ l) + +open scoped Classical in +theorem Supplies.carries (hs : p.Supplies q hx hy cmd) (i : Val a) (j : Val b) + (out : (Fmt.payload U.m V' k').obj) : + (Z).Carries (Payload.Script.decode le_rfl cmd) (S.store x hx (p.exterior i j)) out ↔ + U.store y hy (q.exterior i j) = out := by + obtain ⟨M, hv, he⟩ := hs + have hp : (p.exterior i j ∘ (S.index x hx).symm) ∘ p.transferTo q hx hy = + q.exterior i j ∘ (U.index y hy).symm := by + funext z + obtain ⟨t, rfl⟩ := (U.index y hy).surjective z + obtain ⟨k, rfl⟩ := q.boundary.surjective t + simp only [Function.comp_apply, transfer_named, Equiv.symm_apply_apply, exterior_boundary] + unfold store + exact (hv.carries _ _).trans ((M.matches_iff _ he _ _).trans (by rw [hp, eq_comm])) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- # Compiling endpoint words for a fixed list of payload contacts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring + +open scoped Classical in +/-- Computes the ports by the application `Format.pair (.vec m E) (.vec m' D)`. -/ +abbrev Ports (m m' : ℕ) (E D : Format) := Format.pair (.vec m E) (.vec m' D) + +variable {m m' w p n : ℕ} (q : B (m + p) → B (m' + p)) +local notation "I" => entries w p n +local notation "R" => Row w p n +local notation "S" => Payload.Script m m' p w n + +open scoped Classical in +/-- The organize of type `(S).obj` for the given inputs. -/ +def organize (x : (Ports m m' R R).obj) : (S).obj := + ((((fun i => (x.1 i).1, fun i => (x.1 i).2.1), (fun i => (x.2 i).1, fun i => (x.2 i).2.1)), q), + (fun i => (x.1 i).2.2), (fun i => (x.2 i).2.2)) + +open scoped Classical in +/-- The value specified by `assemble (total ∘ x.1) (total ∘ x.2) (offsets ∘ x.1) (offsets ∘ x.2) +q`. -/ +def emit (x : (Ports m m' I I).obj) : (S).obj := + assemble (total ∘ x.1) (total ∘ x.2) (offsets ∘ x.1) (offsets ∘ x.2) q + +open scoped Classical in +/-- The emit cost used in the `SpanPlan` construction. -/ +def emitCost (m m' w p n : ℕ) := + (2 ^ m + 2 ^ m') * (2 ^ (n + p) * (100 + (2 * n + p + w)) ^ 140) + + ((Ports m m' (Row w p n) (Row w p n)).width + 34 * (Payload.Script m m' p w n).width) + +open scoped Classical in +private theorem send (F : Type) [Field F] : Circuit F (Ports m m' R R) S (organize q) + ((Ports m m' R R).width + 34 * (S).width) := by + apply Window.Tile.project_const + rintro ((((⟨i, j⟩|⟨i, j⟩)|(⟨i, j⟩|⟨i, j⟩))|⟨i, j⟩)|⟨i, j⟩|⟨i, j⟩) + · exact .inl ⟨.inl (i, .inl j), fun _ => rfl⟩ + · exact .inl ⟨.inl (i, .inr (.inl j)), fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inl j), fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inr (.inl j)), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr (m' + p)).code (q i) j, fun _ => rfl⟩ + · exact .inl ⟨.inl (i, .inr (.inr j)), fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inr (.inr j)), fun _ => rfl⟩ + +open scoped Classical in +theorem emit_net (F : Type) [Field F] : + Circuit F (Ports m m' I I) S (emit q) (emitCost m m' w p n) := by + let M := 2 ^ (n + p) * (100 + (2 * n + p + w)) ^ 140 + obtain ⟨k, hk, he⟩ := cheap_entries F w p n + have make : Circuit F I R compile M := hk.mono (by unfold M; omega) + have both := (Circuit.map _ (fun _ : B m => make)).par (Circuit.map _ (fun _ : B m' => make)) + have go := both.comp (send (w := w) (n := n) q F) + have equal : (organize q ∘ Prod.map (fun (x : (Format.vec m I).obj) i => compile (x i)) + (fun (x : (Format.vec m' I).obj) i => compile (x i))) = emit q := rfl + rw [equal] at go + simpa only [emitCost, add_mul] using go + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- +# Returning length declarations to a parent host + +Append a query for each key after all the children's messages. The +first row of each key is a live message if present and an empty query +otherwise. A separate tag excludes zero-length declarations. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan.Scatter +open Coloring + +/-- Computes the family by the application `Format.vec z (entries w z n)`. -/ +abbrev Family (w z n : ℕ) := Format.vec z (entries w z n) +/-- The quantity computed by `1 + (z + n)`. -/ +abbrev depth (z n : ℕ) := 1 + (z + n) +/-- Computes the key by the application `Format.pair .bit (.addr n)`. -/ +abbrev Key (n : ℕ) := Format.pair .bit (.addr n) + +variable {z n w : ℕ} + +/-- Reindexes `B (depth z n)` and `B 1 × B z × B n` by an equivalence. -/ +def address : B (depth z n) ≃ B 1 × B z × B n := + (Assembly.Match.rowIndex 1 (z + n)).trans ((Equiv.refl _).prodCongr (Assembly.Match.rowIndex z n)) + +/-- The value specified by `address.symm (1, 0, i)`. -/ +def query (i : B n) : B (depth z n) := address.symm (1, 0, i) + +/-- The body of type `(header w z n).obj`, constructed using `address t`. -/ +def body (x : (Family w z n).obj) (t : B (depth z n)) : (header w z n).obj := + let a := address t + if a.1 = 0 then (a.2.1, (x a.2.1 a.2.2).2) else (0, 0, a.2.2) + +/-- The value specified by `(if (address t).1 = 0 then decide (v.2.1 = 0) else false, v.2.2)`. -/ +def mark (t : B (depth z n)) (v : (header w z n).obj) : (Key n).obj := + (if (address t).1 = 0 then decide (v.2.1 = 0) else false, v.2.2) + +/-- The indexed operation `(Key n).keys (fun t => mark t (body x t))`. -/ +def keys (x : (Family w z n).obj) := (Key n).keys (fun t => mark t (body x t)) + +/-- Computes the run by the application `body x (groupFirst (keys x) (query i))`. -/ +def run (x : (Family w z n).obj) (i : B n) := body x (groupFirst (keys x) (query i)) + +private theorem first_key (x : (Family w z n).obj) (i : B n) : + let t := groupFirst (keys x) (query i) + mark t (body x t) = (false, i) := by + have h := (Key n).serial.injective (first_spec (keys x) (query i)).1 + exact h.trans (by simp [mark, query, body]) + +theorem origin (x : (Family w z n).obj) (i : B n) (hi : 0 < (run x i).2.1.val) : + ∃ c j, 0 < (x c j).2.1.val ∧ (x c j).2.2 = i ∧ run x i = (c, (x c j).2) := by + let t := groupFirst (keys x) (query i) + change 0 < (body x t).2.1.val at hi + by_cases he : (address t).1 = 0 + · have hk : (body x t).2.2 = i := congrArg Prod.snd (first_key x i) + simp only [body, he, ite_true] at hi hk + exact ⟨_, _, hi, hk, ite_eq_left he⟩ + · simp [body, he] at hi + +theorem positive (x : (Family w z n).obj) (c : B z) (j : B n) + (hj : 0 < (x c j).2.1.val) : 0 < (run x (x c j).2.2).2.1.val := by + let i := (x c j).2.2 + let t := groupFirst (keys x) (query i) + let r : B (depth z n) := address.symm (0, c, j) + have hn : (x c j).2.1 ≠ 0 := (show 0 < (x c j).2.1 from hj).ne' + have eq : keys x r = keys x (query i) := by + simp [keys, Format.keys, r, query, mark, body, hn, i] + have hle : t ≤ r := (first_spec _ _).2 _ eq + have he : (address t).1 = 0 := by + by_contra he + apply hle.not_gt + rw [← address.symm_apply_apply t] + exact (Scheme.rowIndex_lt _ _).mpr (.inl (pos_iff_ne_zero.mpr he)) + have hk : (mark t (body x t)).1 = false := congrArg Prod.fst (first_key x i) + simp only [mark, he, ite_true, decide_eq_false_iff_not] at hk + exact (show 0 < (body x t).2.1 from pos_iff_ne_zero.mpr hk) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan.Scatter +end + +/- # Moving old exterior spans to subintervals of new exterior spans -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring + +variable {F : Type} [Field F] {S U : Scheme F} {x : S.format.obj} {y : U.format.obj} + {a b : Wire} {G H : Diagram F a b} (p : S.Presentation x G) (q : U.Presentation y H) + {z w n : ℕ} + +open scoped Classical in +/-- The indexing data represented by `B m → (entries w z n).obj`. -/ +abbrev Entries (m w z n : ℕ) := B m → (entries w z n).obj + +open scoped Classical in +/-- A single contact carries all bits assigned to a given child. The +physical rows at both ends use the old row index as their pairing key. -/ +structure Spec (child : B U.m ≃ B S.m × B z) (shift : S.Span → U.Span) + (skip : S.Span → ℕ) (left right : S.Span → B n) + (send : Entries S.m w z n) (take : Entries U.m w z n) : Prop where + parent : ∀ t, 0 < S.borderLen x t → (child (shift t).1.1).1 = t.1.1 + bits : ∀ i, let u := (p.boundary i).val; let v := (q.boundary i).val + v.1 = shift u.1 ∧ v.2.val = skip u.1 + u.2.val + ordered : ∀ t t', 0 < S.borderLen x t → 0 < S.borderLen x t' → + t.1.1 = t'.1.1 → S.spanOrd t < S.spanOrd t' → left t < left t' + merged : ∀ t t', 0 < S.borderLen x t → 0 < S.borderLen x t' → + (shift t).1.1 = (shift t').1.1 → right t < right t' → + U.spanOrd (shift t) < U.spanOrd (shift t') ∨ + (shift t = shift t' ∧ skip t + S.borderLen x t ≤ skip t') + source : ∀ t, 0 < S.borderLen x t → + let a := send t.1.1 (left t) + a.1 = (child (shift t).1.1).2 ∧ a.2.1.val = S.borderLen x t ∧ a.2.2 = left t + target : ∀ t, 0 < S.borderLen x t → + let a := take (shift t).1.1 (right t) + a.1 = 0 ∧ a.2.1.val = S.borderLen x t ∧ a.2.2 = left t + sourceCover : ∀ v i, 0 < (send v i).2.1.val → + ∃ t, 0 < S.borderLen x t ∧ t.1.1 = v ∧ left t = i + targetCover : ∀ v i, 0 < (take v i).2.1.val → + ∃ t, 0 < S.borderLen x t ∧ (shift t).1.1 = v ∧ right t = i + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- # Comparing the physical span order with the logical bank order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Finset + +namespace SpanPlan +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} + {a b : Wire} {G : Diagram F a b} (p : S.Presentation r G) {z w n : ℕ} + +open scoped Classical in +/-- Indexes the edge by the coordinates of `slots a ⊕ slots b`. -/ +abbrev Edge (a b : Wire) := slots a ⊕ slots b +open scoped Classical in +/-- Computes the here by the application `S.owner r (p.boundary i)`. -/ +abbrev here (i : Edge a b) := S.owner r (p.boundary i) +open scoped Classical in +/-- The value specified by `(p.boundary i).val.1`. -/ +abbrev span (i : Edge a b) := (p.boundary i).val.1 +open scoped Classical in +/-- The value specified by `(p.boundary i).val.2.val`. -/ +abbrev sub (i : Edge a b) := (p.boundary i).val.2.val + +open scoped Classical in +/-- The data for the tiles construction, including `bound`, `full`, `apart`, `sorted`. -/ +structure Tiles (x : Entries S.m w z n) (row : Edge a b → B n) (off : Edge a b → ℕ) : Prop where + bound : ∀ i, off i < (x (here p i) (row i)).2.1.val + full : ∀ v j k, k < (x v j).2.1.val → ∃ i, here p i = v ∧ row i = j ∧ off i = k + apart : ∀ i j, here p i = here p j → row i = row j → off i = off j → i = j + sorted : ∀ i j, here p i = here p j → row i < row j ∨ row i = row j ∧ off i < off j → + S.spanOrd (span p i) < S.spanOrd (span p j) ∨ span p i = span p j ∧ sub p i < sub p j + +namespace Tiles +variable {p} {x : Entries S.m w z n} {row : Edge a b → B n} {off : Edge a b → ℕ} + (h : Tiles p x row off) (v : B S.m) + +open scoped Classical in +private def orig (i : S.fiber r v) := p.boundary.symm i.val +open scoped Classical in +private theorem local_host (i : S.fiber r v) : here p (orig (p:=p) v i) = v := by + simp only [here, orig, Equiv.apply_symm_apply]; exact i.property + +open scoped Classical in +private abbrev L (x : Entries S.m w z n) (i : B n) := (x v i).2.1.val + +open scoped Classical in +private def tile : S.fiber r v ≃ Σ i : B n, Fin (L v x i) := by + let g (i : S.fiber r v) := orig (p:=p) v i + have host (i) : here p (g i) = v := local_host v i + let f (i : S.fiber r v) : Σ j, Fin (L v x j) := + ⟨row (g i), ⟨off (g i), by simpa only [host] using h.bound (g i)⟩⟩ + refine Equiv.ofBijective f ⟨?_, ?_⟩ + · intro i j eq + have e := h.apart (g i) (g j) ((host i).trans (host j).symm) + (congrArg Sigma.fst eq) (congrArg (fun a => a.2.val) eq) + exact Subtype.ext (p.boundary.symm.injective e) + · rintro ⟨j, k⟩ + obtain ⟨i, hi, hj, hk⟩ := h.full _ _ k.val k.isLt + refine ⟨⟨p.boundary i, hi⟩, ?_⟩ + apply Sigma.ext + · simpa only [f, g, orig, Equiv.symm_apply_apply] using hj + · apply (Fin.heq_ext_iff (by simp [f, g, orig, hj])).mpr + simpa only [f, g, orig, Equiv.symm_apply_apply] using hk + +include h in +open scoped Classical in +theorem total_eq : (∑ i, (x v i).2.1.val) = S.load r v := by + simpa only [Fintype.card_sigma, Fintype.card_fin, Scheme.load] + using (Fintype.card_congr (h.tile v)).symm + +variable {V k : ℕ} (hs : S.Fits r V k) + +omit [Field F] in +open scoped Classical in +private theorem index_lt (i j : S.exposed r) (hh : S.owner r i = S.owner r j) + (ho : S.spanOrd i.val.1 < S.spanOrd j.val.1 ∨ i.val.1 = j.val.1 ∧ i.val.2.val < j.val.2.val) : + (S.index r hs i).2.val < (S.index r hs j).2.val := by + rw [S.index_val, S.index_val, hh] + rcases ho with ho|⟨eq, hij⟩ + · have less : S.spanIndex i.val.1 < S.spanIndex j.val.1 := by + change (Match.rowIndex _ _).symm + ((Match.rowIndex S.h S.k).symm i.val.1.1.2, i.val.1.2) < + (Match.rowIndex _ _).symm ((Match.rowIndex S.h S.k).symm j.val.1.1.2, j.val.1.2) + simp [Scheme.spanOrd, Scheme.row, Scheme.rowIndex_lt, Prod.ext_iff] at ho ⊢ + tauto + have small (u : S.exposed r) : u.val.2.val < S.extent r (S.owner r u) (S.spanIndex u.val.1) + := by + simp [Scheme.extent, Scheme.owner, u.property] + have hi := small i + rw [hh] at hi + exact Routing.offset_lt (S.extent r (S.owner r j)) Fin.val + (u := ⟨_, ⟨_, hi⟩⟩) (z := ⟨_, ⟨_, small j⟩⟩) less + · rw [congrArg S.spanIndex eq] + exact Nat.add_lt_add_left hij _ + +include h in +open scoped Classical in +theorem ordinal (a : Edge a b) : + (S.index r hs (p.boundary a)).2.val = + (∑ j with j < row a, (x (here p a) j).2.1.val) + off a := by + let v := here p a + let e := (h.tile v).trans ((Routing.pack (L v x) Fin.val + (fun _ _ _ _ he => Fin.ext he)).trans (finCongr (h.total_eq v))) + let f (q : S.fiber r v) := orig (p:=p) v q + have key (i j : S.fiber r v) (hi : e i < e j) : + row (f i) < row (f j) ∨ row (f i) = row (f j) ∧ off (f i) < off (f j) := by + rcases lt_trichotomy (row (f i)) (row (f j)) with lt|eq|gt + · exact .inl lt + · change Routing.offset (L v x) Fin.val (row (f i)) + off (f i) < + Routing.offset (L v x) Fin.val (row (f j)) + off (f j) at hi + exact .inr ⟨eq, by rw [eq] at hi; omega⟩ + · exact (hi.not_gt (Routing.offset_lt (L v x) Fin.val (u := h.tile v j) (z + := h.tile v i) gt)).elim + let idx (i : S.fiber r v) : Fin (S.load r v) := + ⟨(S.index r hs i.val).2.val, by + have hb := (S.index r hs i.val).2.isLt + change _ < S.load r (S.owner r i.val) at hb + rwa [i.property] at hb⟩ + have mono : StrictMono (idx ∘ e.symm) := by + intro i j hij + let u := e.symm i + let w := e.symm j + have ho := h.sorted (f u) (f w) ((local_host v u).trans (local_host v w).symm) + (key u w (by simpa [u, w] using hij)) + have ea (t : S.fiber r v) : p.boundary (f t) = t.val := p.boundary.apply_symm_apply _ + change (S.index r hs u.val).2.val < (S.index r hs w.val).2.val + apply index_lt hs _ _ (u.property.trans w.property.symm) + unfold span sub at ho + rwa [ea u, ea w] at ho + let i : S.fiber r v := ⟨p.boundary a, rfl⟩ + have he := congrFun mono.eq_id (e i) + simp only [Function.comp_apply, Equiv.symm_apply_apply, id_eq] at he + have hi := congrArg Fin.val he + change _ = (∑ j with j < row (f i), (x v j).2.1.val) + off (f i) at hi + rwa [show f i = a from p.boundary.symm_apply_apply a] at hi + +end Tiles +end SpanPlan +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Issue.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Issue.lean new file mode 100644 index 0000000000..5a198e1331 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Issue.lean @@ -0,0 +1,829 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.BoardPush +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Length +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Checks + +/-! # Controlled construction of child windows from the elected poll -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F : Type} [Field F] (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (b Δ C : ℕ) + +open scoped Classical in +/-- The quantity computed by `Window.Tile.raw D.scheme.m D.scheme.d a (D.scheme.h - a) (D.degree +a Δ C) (D.WithCount a b)`. -/ +abbrev Raw := Window.Tile.raw D.scheme.m D.scheme.d a (D.scheme.h - a) (D.degree a Δ C) + (D.WithCount a b) + +open scoped Classical in +/-- The value specified by `(D.childLive a x.1, D.layout a b P x, D.childNav a ha Δ C x.1, +D.counted a ha b x)`. -/ +def pollRaw (P : Gadget F) (x : (D.Poll a b).obj) : (D.Raw a b Δ C).obj := + (D.childLive a x.1, D.layout a b P x, D.childNav a ha Δ C x.1, D.counted a ha b x) + +open scoped Classical in +/-- Computes the copies by the application `Format.pair D.format (.pair (D.Poll a b) (D.Poll a +b))`. -/ +abbrev Copies := Format.pair D.format (.pair (D.Poll a b) (D.Poll a b)) +open scoped Classical in +/-- The value specified by `Format.pair (.pair (D.Status a) (D.Graph a Δ C)) (.pair .bit +(D.Counted a b))`. -/ +abbrev Fields := Format.pair (.pair (D.Status a) (D.Graph a Δ C)) (.pair .bit (D.Counted a + b)) + +open scoped Classical in +/-- The raw cost used in the `Template` construction. -/ +def rawCost (t : ℕ) := + 4 * ((D.Poll a b).width + 2 * (D.Copies a b).width) + + (D.childCost a Δ C + (D.layoutCost a b t + 4 * ((D.Poll a b).width + + 2 * (D.Counted a b).width))) + + 4 * ((D.Fields a b Δ C).width + 2 * (D.Raw a b Δ C).width) + +open scoped Classical in +/-- Every poll has a deterministic result. Invalid padded selectors have zero weight. -/ +theorem raw_net {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + (fit : (D.PollRow a b).width + (Side.Input (D.scheme.h - a + D.scheme.e) b).width ≤ u) + (allow : D.markTable a b ∈ L) (P : Gadget F) (t : ℕ) (hw : 2 ^ b ≤ t) (hp : 4 * P.b ≤ 2 ^ t) : + Action F u L (D.Poll a b) (D.Raw a b Δ C) (D.pollRaw a ha b Δ C P) (D.valid a b P) + (D.rawCost a b Δ C t) := by + have copy : Circuit F (D.Poll a b) (D.Copies a b) (fun x => (x.1, x, x)) + ((D.Poll a b).width + 2 * (D.Copies a b).width) := + Circuit.project (Sum.elim Sum.inl (Sum.elim id id)) (by rintro x (i | (i | i)) <;> rfl) + let pin : (D.Raw a b Δ C).pins → (D.Fields a b Δ C).pins + | .inl i => .inl (.inl i) + | .inr (.inl i) => .inr (.inl i) + | .inr (.inr (.inl i)) => .inl (.inr i) + | .inr (.inr (.inr i)) => .inr (.inr i) + have reorder : Circuit F (D.Fields a b Δ C) (D.Raw a b Δ C) (fun x => (x.1.1, x.2.1, x.1.2, + x.2.2)) + ((D.Fields a b Δ C).width + 2 * (D.Raw a b Δ C).width) := + Circuit.project pin (by rintro x (i | (i | (i | i))) <;> rfl) + have H := (Action.of_map (D.child_map a ha Δ C hu)).par + ((D.layout_net a b hu fit allow P t hw hp).par (Action.of_map (Map.circuit hu + (D.counted_circuit a ha b)))) + have K := (H.pre (Map.circuit hu copy)).post (Map.circuit hu reorder) + simp only [mul_one, one_mul] at K + exact K + +namespace Selection +variable {D a ha b Δ C} {T : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} + {P : Gadget F} {z k : ℕ} {r : D.format.obj} {G : HostNet F L D.scheme.h (P.b * z)} + {p : D.Encodes r G} {B' σ : ℝ} {hu : 0 < P.b * z} (s : D.Selection a ha b k B' Δ C p σ hu) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (i : s.choices) (v : Site (G.V × Cell a) (D.scheme.h + - a)) + +open scoped Classical in +/-- The value specified by `s.board hb i v (D.childNav a ha Δ C r) (D.childLive a r) +(D.childSelf a ha Δ C r)`. -/ +def canonicalBoard : (s.state hb i v).Board (D.degree a Δ C) (D.WithCount a b) Prod.fst := + s.board hb i v (D.childNav a ha Δ C r) (D.childLive a r) (D.childSelf a ha Δ C r) + +open scoped Classical in +theorem canonical_live : (s.canonicalBoard hb i v).Live := D.child_live a p + +open scoped Classical in +theorem poll_raw_eq : + D.pollRaw a ha b Δ C P (D.prepared a ha b k B' Δ C (r, (s.selector hb).write i)) = + (s.canonicalBoard hb i v).raw := by + rw [pollRaw, s.layout_eq hb i] + rfl + +end Selection +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Combining selector checks with the child host headers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F : Type} [Field F] (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (b Δ C : ℕ) + +open scoped Classical in +/-- The value specified by `(D.Raw a b Δ C).pair (D.ChildHeader a Δ C)`. -/ +abbrev Headed := (D.Raw a b Δ C).pair (D.ChildHeader a Δ C) + +open scoped Classical in +/-- The value specified by `(D.poll_raw a ha b Δ C P x, D.childHeader a ha Δ C x.1)`. -/ +def headed (P : Gadget F) (x : (D.Poll a b).obj) : (D.Headed a b Δ C).obj := + (D.pollRaw a ha b Δ C P x, D.childHeader a ha Δ C x.1) + +open scoped Classical in +/-- The bound obtained by adding the component charges `4 * ((D.Poll a b).width + 2 * ((D.Poll a +b).pair D.format).width) + (D.rawCost a b Δ C t + 4 * D.headerCost a Δ C)`. -/ +def headedCost (t : ℕ) := + 4 * ((D.Poll a b).width + 2 * ((D.Poll a b).pair D.format).width) + + (D.rawCost a b Δ C t + 4 * D.headerCost a Δ C) + +open scoped Classical in +theorem headed_net {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + (fit : (D.PollRow a b).width + (Side.Input (D.scheme.h - a + D.scheme.e) b).width ≤ u) + (allow : D.markTable a b ∈ L) (P : Gadget F) (t : ℕ) (hw : 2 ^ b ≤ t) (hp : 4 * P.b ≤ 2 ^ t) : + Action F u L (D.Poll a b) (D.Headed a b Δ C) (D.headed a ha b Δ C P) (D.valid a b P) + (D.headedCost a b Δ C t) := by + have copy : Circuit F (D.Poll a b) ((D.Poll a b).pair D.format) (fun x => (x, x.1)) + ((D.Poll a b).width + 2 * ((D.Poll a b).pair D.format).width) := + Circuit.project (Sum.elim id Sum.inl) (by rintro x (i | i) <;> rfl) + have H := ((D.raw_net a ha b Δ C hu fit allow P t hw hp).par + (Action.of_map (Map.circuit hu (D.header_net a ha Δ C)))).pre (Map.circuit hu copy) + simp only [mul_one] at H + exact H + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Reading the new charges from the same window as the new table -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing + +namespace State.Board +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} + {a h z Δ D k b d : ℕ} {B' : ℝ} {u v : State S P a h z Δ D k B'} {A : Format} + {read : A.obj → (Window.Source S (h - a) b).obj} + +open scoped Classical in +/-- The indexed operation `push (Function.uncurry (u.g.route u.m u.col)) (fun t => f ((p.parent +(u.p.placeGroup a t.1).1).2 (u.p.placeGroup a t.1).2) t.2) u.v`. -/ +def routed (p : u.Board d A read) (f : A.obj → Cell (h - a) → ℝ) := + push (Function.uncurry (u.g.route u.m u.col)) (fun t => + f ((p.parent (u.p.placeGroup a t.1).1).2 (u.p.placeGroup a t.1).2) t.2) u.v + +open scoped Classical in +theorem routed_eq {p : u.Board d A read} {q : v.Board d A read} (he : p.look = q.look) + (f : A.obj → Cell (h - a) → ℝ) : p.routed f = q.routed f := + push_eq he _ _ (fun _ _ hr t => congrArg (fun s => f s t) (source_eq he hr)) + +end State.Board + +namespace Template +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} + (D : Template F) (a b : ℕ) + +open scoped Classical in +/-- Computes the before park by the application `D.park (x.2 (cellIndex _ t))`. -/ +def beforePark (x : (D.WithCount a b).obj) (t : Cell (D.scheme.h - a)) := + D.park (x.2 (cellIndex _ t)) + +open scoped Classical in +/-- The quantity computed by `(D.past (x.2 (cellIndex _ t)) + (D.scheme.decode (x.1.1 (cellIndex +_ t))).volume true : ℕ)`. -/ +def beforePast (x : (D.WithCount a b).obj) (t : Cell (D.scheme.h - a)) : ℝ := + (D.past (x.2 (cellIndex _ t)) + (D.scheme.decode (x.1.1 (cellIndex _ t))).volume true : ℕ) + +namespace Selection + +variable {D a b} {P : Gadget F} {z k Δ C : ℕ} {ha : a ≤ D.scheme.h} + {r : D.format.obj} {G : HostNet F L D.scheme.h (P.b * z)} {p : D.Encodes r G} + {B' σ : ℝ} {hu : 0 < P.b * z} (s : D.Selection a ha b k B' Δ C p σ hu) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) + (i : s.choices) (v : Site (G.V × Cell a) (D.scheme.h - a)) (hc : Δ ≤ C) + +local notation "E" => splitAddr G.V a ha +local notation "H" => G.regroup a ha +local notation "pr" => G.project a ha Δ C hc +local notation "Q" => HostNet.contracted pr s.group s.matching (Nat.pos_of_mul_pos_left hu) hc i +local notation "bd" => s.canonicalBoard hb i v + +open scoped Classical in +private theorem pos (w : G.V × Cell D.scheme.h) : + D.position a ha (cellIndex _ (E w).1.2) (cellIndex _ (E w).2) = p.post.block w.2 := by + change D.position a ha (cellIndex _ ((splitCell a ha) w.2).1) + (cellIndex _ ((splitCell a ha) w.2).2) = _ + simp only [position, Equiv.symm_apply_apply, Prod.mk.eta, p.block] + +open scoped Classical in +theorem routed_park : + (bd).routed (D.beforePark a b) = push (Q).park L.charge ((pr).place v) := by + refine Eq.trans ?_ (HostNet.park_route pr s.group s.matching _ hc i v) + apply congrArg (fun f => push (Function.uncurry (s.group.route s.matching + (s.group.layout s.matching P i))) f v) + funext w + obtain ⟨w, rfl⟩ := (E).surjective w + change D.park (D.counter r (p.post.host w.1) + (D.position a ha (cellIndex _ (E w).1.2) (cellIndex _ (E w).2))) = push (H).park L.charge (E w) + rw [pos (p := p), p.park, G.regroup_park] + +open scoped Classical in +theorem routed_past : + (bd).routed (D.beforePast a b) = ((Q).past ((pr).place v) : ℝ) := by + refine Eq.trans ?_ (HostNet.past_route pr s.group s.matching _ hc i v) + apply congrArg (fun f => push (Function.uncurry (s.group.route s.matching + (s.group.layout s.matching P i))) f v) + funext w + obtain ⟨w, rfl⟩ := (E).surjective w + let j := D.position a ha (cellIndex _ (E w).1.2) (cellIndex _ (E w).2) + change ((D.past (D.counter r (p.post.host w.1) j) + + (D.scheme.decode ((r.1 (p.post.host w.1)).2 j)).volume true : ℕ) : ℝ) = + (G.past ((E).symm (E w)) + Packing.degree (H).pair (E w) * (P.b * z) : ℕ) + rw [show j = p.post.block w.2 from pos (p := p) w, p.past, Equiv.symm_apply_apply, + G.regroup_degree] + exact congrArg (fun k => ((G.past w + k : ℕ) : ℝ)) (p.post.internal_volume w) + +end Selection +end Template +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# The first, validating half of a wire-saving controller + +The scheme and optional side information are retained so that the +second half can move exterior records along the selected assignment. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F : Type} [Field F] (D : Template F) (P : Gadget F) (a : ℕ) (ha : a ≤ D.scheme.h) + (b k : ℕ) (cost : ℝ) (Δ C : ℕ) (A : Format) + +local notation "n" => (D.scheme.h - a) +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "q" => ((d + 1) * n) +local notation "X" => Format.pair (D.format.pair A) (D.Candidate a b) +local notation "Y" => D.scheme.format.pair A +local notation "Z" => Format.pair (D.Headed a b Δ C) Y + +open scoped Classical in +/-- The value specified by `(D.headed a ha b Δ C P (D.prepared a ha b k cost Δ C (x.1.1, x.2)), +x.1.1.1, x.1.2)`. -/ +def start (x : (X).obj) : (Z).obj := + (D.headed a ha b Δ C P (D.prepared a ha b k cost Δ C (x.1.1, x.2)), x.1.1.1, x.1.2) + +open scoped Classical in +/-- The value specified by `D.valid a b P (D.prepared a ha b k cost Δ C (x.1.1, x.2))`. -/ +def check (x : (X).obj) := D.valid a b P (D.prepared a ha b k cost Δ C (x.1.1, x.2)) + +variable {u N N' v v' : ℕ} {L : Set (Table F)} {I : Type*} + +open scoped Classical in +theorem start_net (hu : 3 ≤ u) (hn : 0 < n) + (hg : Access F u L (m + q) v N) (hv : (Group.Parcel d a n D.count).width ≤ v) + (hc : Access F u L (m + d) v' N') (hv' : (Window.LabelSet a n).width ≤ v') + (hb : D.arity a b ≤ u) (hL : (D.keys a b k cost Δ C : Set _) ⊆ L) + (fit : (D.PollRow a b).width + (Side.Input (n + D.scheme.e) b).width ≤ u) + (allow : D.markTable a b ∈ L) (t : ℕ) (hw : 2 ^ b ≤ t) (hp : 4 * P.b ≤ 2 ^ t) + (x : I → (X).obj) + (recip : ∀ i, Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) (x i).1.1.1) : + Computes F u L X Z x (D.start P a ha b k cost Δ C A ∘ x) (D.check P a ha b k cost Δ C A ∘ x) + (100 * (X).width + D.prepareCost a b v N v' N' + D.headedCost a b Δ C t) := by + let R := D.Request a b + let load : (X).obj → R.obj := fun x => (x.1.1, x.2) + let save : (X).obj → (Y).obj := fun x => (x.1.1.1, x.1.2) + have hload : Circuit F X R load ((X).width + 2 * R.width) := + Circuit.project (Sum.elim (Sum.inl ∘ Sum.inl) Sum.inr) (by rintro x (i|i) <;> rfl) + have hsave : Circuit F X Y save ((X).width + 2 * (Y).width) := + Circuit.project (Sum.elim (Sum.inl ∘ Sum.inl ∘ Sum.inl) (Sum.inl ∘ Sum.inr)) + (by rintro x (i|i) <;> rfl) + have h₁ := Computes.of_map (L := L) (x := x) (Map.circuit hu hload) (fun _ => rfl) + have h₂ := D.prepare_net a ha b k cost Δ C hu hn hg hv hc hv' hb hL (load ∘ x) recip + have h₃ := D.headed_net a ha b Δ C hu fit allow P t hw hp + have h₄ := Computes.of_map (L := L) (x := x) (Map.circuit hu hsave) (fun _ => rfl) + have h := ((h₁.comp h₂).comp (Computes.of_action h₃ (fun _ => rfl) (fun _ => rfl))).pair hu h₄ + simp only [one_mul, mul_one] at h + refine h.mono ?_ + simp only [R, Request, format, Format.width_pair] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Widths of the lookup tables in the first half of the contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring +variable {F : Type} [Field F] (D : Template F) (a b k : ℕ) (cost : ℝ) (Δ C : ℕ) + +open scoped Classical in +theorem keys_width (s : Table F) (hs : s ∈ D.keys a b k cost Δ C) : + Processor.arity s ≤ D.arity a b := by + simp only [keys, Finset.mem_insert] at hs + unfold arity + rcases hs with rfl | rfl | rfl | h + · simp only [stubTable, Processor.arity, weightTable, lookup, wd_word, Format.width_addr, + tableWidth] + omega + · simp only [lightTable, Processor.arity, weightTable, lookup, wd_word] + rw [Format.width_addr] + omega + · simp only [voteTable, Processor.arity, weightTable, lookup, wd_word] + omega + · have := Group.arity_keys F h + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # A family of elected wire-saving branches with one common decoder -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing History + +variable {F : Type} [Field F] (D : Template F) (P : Gadget F) (a : ℕ) (ha : a ≤ D.scheme.h) + (b k : ℕ) (cost : ℝ) (Δ C z : ℕ) (σ : ℝ) (hu : 0 < P.b * z) + +open scoped Classical in +/-- The data for the branch construction, including `T`, `[finite`, `x`, `y`, `L`. -/ +structure Branch where + /-- The `Branch` component of type `Type`. -/ + T : Type + [finite : Fintype T] + /-- The `Branch` component of type `Wire`. -/ + x : Wire + /-- The `Branch` component of type `Wire`. -/ + y : Wire + /-- The `Branch` component of type `Fringe x y T`. -/ + L : Fringe x y T + /-- The `Branch` component of type `HostNet F L D.scheme.h (P.b * z)`. -/ + G : HostNet F L D.scheme.h (P.b * z) + /-- The `Branch` component of type `D.format.obj`. -/ + r : D.format.obj + /-- The `Branch` component of type `D.Encodes r G`. -/ + p : D.Encodes r G + /-- The `Branch` component of type `D.Selection a ha b k cost Δ C p σ hu`. -/ + s : D.Selection a ha b k cost Δ C p σ hu + /-- The `Branch` component of type `s.choices`. -/ + i : s.choices + /-- The `Branch` component of type `Site (G.V × Cell a) (D.scheme.h - a)`. -/ + v : Site (G.V × Cell a) (D.scheme.h - a) + +attribute [instance] Branch.finite + +variable {P z} {hz : 0 < z} + +open scoped Classical in +/-- Builds `Template F where scheme` with the specified `scheme`, `count`, `load`, `park`. -/ +abbrev after (M : Book D.scheme P z hz) (e cap : ℕ) (K : Meter) : Template F where + scheme := M.scheme (D.size a) (D.degree a Δ C) a e cap + count := K.count + load := K.load + park := K.park + past := K.past + order := Post.order (D.degree a Δ C) e M.d cap + full := D.full + +namespace Branch +variable {D a ha b k cost Δ C σ hu} (t : D.Branch P a ha b k cost Δ C z σ hu) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (hc : Δ ≤ C) + +open scoped Classical in +/-- Uses `t.s.state hb t.i t.v` as the representation. -/ +abbrev state := t.s.state hb t.i t.v +open scoped Classical in +/-- Computes the board by the application `t.s.canonicalBoard hb t.i t.v`. -/ +abbrev board := t.s.canonicalBoard hb t.i t.v +open scoped Classical in +/-- The value specified by `HostNet.contracted (t.G.project a ha Δ C hc) t.s.group t.s.matching +(Nat.pos_of_mul_pos_left hu) hc t.i`. -/ +abbrev layout := HostNet.contracted (t.G.project a ha Δ C hc) t.s.group t.s.matching + (Nat.pos_of_mul_pos_left hu) hc t.i + +variable {e : ℕ} (M : Book D.scheme P z hz) (room : (t.state hb).Room e) (cap : ℕ) + +open scoped Classical in +/-- The value specified by `(t.board hb).assign M room cap hc`. -/ +abbrev assign := (t.board hb).assign M room cap hc +open scoped Classical in +/-- The value specified by `(t.state hb).Ready M room cap (t.assign hb hc M room cap) +(D.childNav a ha Δ C t.r)`. -/ +abbrev Ready := (t.state hb).Ready M room cap (t.assign hb hc M room cap) (D.childNav a ha Δ C t.r) +open scoped Classical in +/-- The value specified by `(t.state hb).records M room cap (t.assign hb hc M room cap)`. -/ +abbrev records := (t.state hb).records M room cap (t.assign hb hc M room cap) +open scoped Classical in +/-- The value specified by `(t.state hb).output M room cap (t.assign hb hc M room cap) +(D.childNav a ha Δ C t.r)`. -/ +abbrev written := (t.state hb).output M room cap (t.assign hb hc M room cap) (D.childNav a ha Δ C + t.r) + +open scoped Classical in +/-- Only occupied child addresses carry counters. -/ +def counters (K : Meter) : B (D.size a) → B a → B K.count := + Function.extend (Child.host t.p.post.host (D.scheme.h - a)) + (fun v j => K.read (t.layout hc) (v, (cellIndex a).symm j)) (fun _ _ => 0) + +open scoped Classical in +theorem counters_at (K : Meter) (v : Site t.G.V (D.scheme.h - a)) (j : Cell a) : + t.counters hc K (Child.host t.p.post.host (D.scheme.h - a) v) (cellIndex a j) = + K.read (t.layout hc) (v, j) := by + rw [counters, (Child.host _ _).injective.extend_apply, Equiv.symm_apply_apply] + +open scoped Classical in +theorem counters_vacant (K : Meter) (i : B (D.size a)) (j : B a) (hi : D.childLive a t.r i + = false) : + t.counters hc K i j = 0 := by + rw [counters, Function.extend_apply' _ _ _ (fun h + => Bool.noConfusion (hi.symm.trans ((D.child_live a t.p i).mpr h)))] + +end Branch +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # The charge counter of a child depends only on its local window -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Branch +open Coloring Packing History State.Board + +variable {F : Type} [Field F] {D : Template F} {P : Gadget F} {a : ℕ} {ha : a ≤ D.scheme.h} + {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} {hu : 0 < P.b * z} {hz : 0 < z} {e : ℕ} + {s t : D.Branch P a ha b k cost Δ C z σ hu} + {hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b} {hc : Δ ≤ C} + {M : Book D.scheme P z hz} {rs : (s.state hb).Room e} {rt : (t.state hb).Room e} {cap : ℕ} + (hs : s.Ready hb hc M rs cap) (ht : t.Ready hb hc M rt cap) + {v : Site (s.G.V × Cell a) (D.scheme.h - a)} {w : Site (t.G.V × Cell a) (D.scheme.h - a)} + +include hs ht in +open scoped Classical in +theorem counters_eq (he : ((s.board hb).recenter v).look + = ((t.board hb).recenter w).look) (K : Meter) : + s.counters hc K (Child.host s.p.post.host (D.scheme.h - a) (v.1.1, v.2)) (cellIndex a v.1.2) = + t.counters hc K (Child.host t.p.post.host (D.scheme.h - a) (w.1.1, w.2)) (cellIndex a w.1.2) + := by + let X := (s.G.project a ha Δ C hc).place v + let Y := (t.G.project a ha Δ C hc).place w + have h := (agrees he).1.localRecord (le_refl 8) M (rs.recenter v) (rt.recenter w) + cap (s.assign hb hc M rs cap) (t.assign hb hc M rt cap) (index_eq he) hs.ranked ht.ranked + have hr := ((s.state hb).record_at M rs cap (s.assign hb hc M rs cap) v).trans + (h.trans ((t.state hb).record_at M rt cap (t.assign hb hc M rt cap) w).symm) + let Z := M.scheme (D.size a) (D.degree a Δ C) a e cap + have eq : hs.posting.atBlock X = ht.posting.atBlock Y := + congrArg (Z.decode ∘ (Post.record (D.degree a Δ C) e M.d (.addr cap)).serial) hr + have internal := (hs.posting.internal_volume X).symm.trans + ((congrArg (fun r => r.volume true) eq).trans (ht.posting.internal_volume Y)) + have external := (hs.posting.exterior_volume X).symm.trans + ((congrArg (fun r => r.volume false) eq).trans (ht.posting.exterior_volume Y)) + have park := (s.s.routed_park hb s.i v hc).symm.trans + ((routed_eq he (D.beforePark a b)).trans (t.s.routed_park hb t.i w hc)) + have past := (s.s.routed_past hb s.i v hc).symm.trans + ((routed_eq he (D.beforePast a b)).trans (t.s.routed_past hb t.i w hc)) + rw [counters_at, counters_at] + exact congr (congrArg₂ K.encode (congrArg₂ (· + ·) external internal) park) (Nat.cast_injective + past) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Branch +end + +/- # The encoded output of a selected subround -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Branch +open Coloring Packing History + +variable {F : Type} [Field F] {D : Template F} {P : Gadget F} {a : ℕ} {ha : a ≤ D.scheme.h} + {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} {hu : 0 < P.b * z} {hz : 0 < z} {e : ℕ} + (t : D.Branch P a ha b k cost Δ C z σ hu) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (hc : Δ ≤ C) + (M : Book D.scheme P z hz) (room : (t.state hb).Room e) (cap : ℕ) (K : Meter) + +open scoped Classical in +/-- The indexed operation `(t.written hb hc M room cap, fun i => let q := D.childHeader a ha Δ C +t.r i (q.1, q.2, t.counters hc K i))`. -/ +def output : (D.after a Δ C M e cap K).format.obj := + (t.written hb hc M room cap, fun i => + let q := D.childHeader a ha Δ C t.r i + (q.1, q.2, t.counters hc K i)) + +open scoped Classical in +/-- Builds `(D.after a Δ C M e cap K).Encodes (t.output hb hc M room cap K) (t.layout hc) where +post` with the specified `post`, `block`, `live`, `frozen`. -/ +def encodes (hd : 0 < Δ) (ready : t.Ready hb hc M room cap) (valid : K.Valid (t.layout hc)) : + (D.after a Δ C M e cap K).Encodes (t.output hb hc M room cap K) (t.layout hc) where + post := ready.posting + block _ := rfl + live := D.child_live a t.p + frozen := D.child_frozen a t.p + closed := D.child_closed a ha Δ C t.p hd hc + reciprocal := D.child_reciprocal a ha Δ C t.p hd hc _ (fun i => (t.written hb hc M room cap i).2) + edge := D.child_edge a ha Δ C t.p hd hc + core := D.child_core a ha Δ C t.p hd hc + load v j := (congrArg K.load (t.counters_at hc K v j)).trans (valid (v, j)).1 + park v j := (congrArg K.park (t.counters_at hc K v j)).trans (valid (v, j)).2.1 + past v j := (congrArg K.past (t.counters_at hc K v j)).trans (valid (v, j)).2.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Branch +end + +/- # Separating short child labels from the common graph and headers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing History Window + +variable {F : Type} [Field F] (D : Template F) (a b Δ C : ℕ) + {P : Gadget F} {z : ℕ} {hz : 0 < z} (M : Book D.scheme P z hz) (e cap : ℕ) (K : Meter) (W : + Format) + +local notation "Z" => D.after a Δ C M e cap K +local notation "Out" => Tile.output D.scheme.m a (D.scheme.h - a) + +open scoped Classical in +/-- The value specified by `(D.Graph a Δ C).pair (D.ChildHeader a Δ C)`. -/ +abbrev Envelope := (D.Graph a Δ C).pair (D.ChildHeader a Δ C) +open scoped Classical in +/-- The value specified by `Format.pair (.addr (Z).scheme.ℓ) (.pair (.addr K.count) W)`. -/ +abbrev Label := Format.pair (.addr (Z).scheme.ℓ) (.pair (.addr K.count) W) +open scoped Classical in +/-- The value specified by `Out (D.Label a Δ C M e cap K W)`. -/ +abbrev Labels := Out (D.Label a Δ C M e cap K W) +open scoped Classical in +/-- The value specified by `(Z).format.pair (Out W)`. -/ +abbrev Issued := (Z).format.pair (Out W) + +open scoped Classical in +/-- The value specified by `(x.1.2.2.1, x.2)`. -/ +def envelope (x : (D.Headed a b Δ C).obj) : (D.Envelope a Δ C).obj := (x.1.2.2.1, x.2) + +open scoped Classical in +/-- The indexed operation `((fun i => (x.1.1 i, fun j => (x.2 i j).1), fun i => ((x.1.2 i).1, +(x.1.2 i).2, fun j => (x.2 i j).2.1)), fun i j => (x.2 i j).2.2)`. -/ +def joinLabels (x : ((D.Envelope a Δ C).pair (D.Labels a Δ C M e cap K W)).obj) : + (D.Issued a Δ C M e cap K W).obj := + ((fun i => (x.1.1 i, fun j => (x.2 i j).1), + fun i => ((x.1.2 i).1, (x.1.2 i).2, fun j => (x.2 i j).2.1)), fun i j => (x.2 i j).2.2) + +local notation "A₀" => D.Headed a b Δ C +local notation "A₁" => D.Envelope a Δ C +local notation "A₂" => D.Raw a b Δ C +local notation "A₃" => D.Labels a Δ C M e cap K W +local notation "A₄" => D.Issued a Δ C M e cap K W + +open scoped Classical in +private theorem join_net : Circuit F ((A₁).pair A₃) A₄ (D.joinLabels a Δ C M e cap K W) + (((A₁).pair A₃).width + 2 * (A₄).width) := by + let pin : (A₄).pins → ((A₁).pair A₃).pins + | .inl (.inl (i, .inl q)) => .inl (.inl (i, q)) + | .inl (.inl (i, .inr (j, q))) => .inr (i, j, .inl q) + | .inl (.inr (i, .inl q)) => .inl (.inr (i, .inl q)) + | .inl (.inr (i, .inr (.inl q))) => .inl (.inr (i, .inr q)) + | .inl (.inr (i, .inr (.inr (j, q)))) => .inr (i, j, .inr (.inl q)) + | .inr (i, j, q) => .inr (i, j, .inr (.inr q)) + refine Circuit.project pin ?_ + rintro x ((⟨i, q | ⟨j, q⟩⟩ | ⟨i, q | (q | ⟨j, q⟩)⟩) | ⟨i, j, q⟩) <;> rfl + +open scoped Classical in +/-- The bound obtained by adding the component charges `20 * (A₀).width + (4 * ((A₀).width + 2 * +(A₁).width) + (4 * ((A₀).width + 2 * (A₂).width) + N)) + 4 * (((A₁).pair A₃).width + 2 * +(A₄).width)`. -/ +def joinCost (N : ℕ) := + 20 * (A₀).width + (4 * ((A₀).width + 2 * (A₁).width) + (4 * ((A₀).width + 2 * (A₂).width) + N)) + + 4 * (((A₁).pair A₃).width + 2 * (A₄).width) + +open scoped Classical in +theorem join_computes {u N : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + {I : Type*} (x : I → (A₀).obj) (y : I → (A₃).obj) + (net : Computes F u L A₂ A₃ (fun i => (x i).1) y (fun _ => 1) N) : + Computes F u L A₀ A₄ x (fun i => D.joinLabels a Δ C M e cap K W (D.envelope a b Δ C (x i), y i)) + (fun _ => 1) (D.joinCost a b Δ C M e cap K W N) := by + have keep : Circuit F A₀ A₁ (D.envelope a b Δ C) ((A₀).width + 2 * (A₁).width) := + Circuit.project (Sum.elim (fun q => .inl (.inr (.inr (.inl q)))) Sum.inr) (by rintro x (i|i) + <;> rfl) + have pr : Circuit F A₀ A₂ Prod.fst ((A₀).width + 2 * (A₂).width) := + Circuit.project Sum.inl (fun _ _ => rfl) + have h := Computes.of_map (L := L) (x := x) (Map.circuit hu keep) (fun _ => rfl) + have k := Computes.of_map (L := L) (x := x) (Map.circuit hu pr) (fun _ => rfl) + have all := (h.pair hu (k.comp net)).comp + (Computes.of_map (Map.circuit hu (D.join_net a Δ C M e cap K W)) (fun _ => rfl)) + simp only [mul_one] at all + exact all + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Fitting the contraction history and propagating the tag estimate -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Branch +open Coloring Packing History + +variable {F : Type} [Field F] {D : Template F} {P : Gadget F} {a : ℕ} {ha : a ≤ D.scheme.h} + {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} {hu : 0 < P.b * z} {hz : 0 < z} {e : ℕ} + (t : D.Branch P a ha b k cost Δ C z σ hu) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (hc : Δ ≤ C) + (hd : 0 < Δ) (hs : 0 ≤ σ) (hp : 0 ≤ cost) (bounds : t.G.Bounded Δ C cost) + +local notation "H" => t.layout hc +local notation "A" => t.state hb + +include hd hs hp bounds in +open scoped Classical in +theorem estimates : + (H).Bounded ((4 * Δ) ^ 900) ((4 * C) ^ 900) (9 * ((4 * Δ) ^ 300 : ℕ) * ((2 : ℝ) ^ k * cost)) ∧ + ((H).X : ℝ) ≤ (1 - 1 / (8 * (P.b : ℝ))) * t.G.X + (t.L.Z + σ) ∧ + t.G.Preserves H ∧ (H).mass = t.G.mass + 2 * t.G.X ∧ t.G.Tracks H ((Δ + 1) * 2) := + (t.G.projected_bounds P (Nat.pos_of_mul_pos_left hu) a k Δ C hd hc ha cost σ hp hs bounds + t.s.group t.s.matching t.s.saving t.i).2 + +include hp hd bounds in +open scoped Classical in +theorem room (he : (10 : ℝ) * (4 * Δ) ^ 300 * 2 ^ k * cost ≤ 2 ^ e * z) + (floor : ∀ j, P.b * z ≤ t.p.post.toPresentation.borderWidth j) : (A).Room e where + budget := ⟨Nat.pos_of_mul_pos_left hu, hp, hd, (t.G.regroup_bounded a ha bounds).1, he⟩ + contacts := Scheme.Presentation.contacts («H» := t.G.regroup a ha) t.p.post.toPresentation floor + floor j := (Nat.le_mul_of_pos_left _ P.pos).trans (floor j) + +variable (M : Book D.scheme P z hz) (rm : (t.state hb).Room e) {unit c B cap : ℕ} + +include hd in +open scoped Classical in +theorem fitted (neutral : ∀ v, t.G.diagram.arity v = 0 → ∀ x, + Transcript.sample (t.G.diagram.table v) x = 1) + (sizes : ∀ j, M.len (M.put (t.p.post.toPresentation.borderWidth j)) + = t.p.post.toPresentation.borderWidth j) + (tag : (A).Charged M.ord unit c) (hv : 0 < unit) + (mass : (H).mass ≤ t.L.cap) (bound : ∀ v i, (H).load v i ≤ (B : ℝ) * unit) + (budget : M.overhead e + c * (2 ^ t.L.discount * B) ≤ cap) : + t.Ready hb hc M rm cap := by + constructor + · exact fun _ => rfl + · exact sizes + · exact D.child_hop a ha Δ C t.p hd hc + · exact neutral + · intro v + exact (Nat.add_le_add_left (((A).recenter v).inherited_bound hc tag hv B mass bound) _).trans + budget + +open scoped Classical in +theorem charged_after (ready : t.Ready hb hc M rm cap) (K : Meter) + (tag : (A).Charged M.ord unit c) (hv : 0 < unit) (hle : unit ≤ z) + (w : (H).V × Cell a) (active : 0 < (H).tetherLoad w + Packing.degree (H).pair w * z) : + (D.after a Δ C M e cap K).tagLength (t.output hb hc M rm cap K) + (ready.posting.host w.1) (ready.posting.block w.2) * unit ≤ + (c + (Post.headerFmt (D.degree a Δ C) e M.d).width + M.overhead e) * (H).footprint w := by + have floor := (H).active_floor (ready.posting.toPresentation.contacts (State.Ready.floor ready + (State.Room.floor rm))) w active + let v := (t.G.project a ha Δ C hc).place.symm w + let W := (Post.headerFmt (D.degree a Δ C) e M.d).width + M.overhead e + have ho := ready.stored v + have hi := ((A).recenter v).inherited_charge hc tag hv + have hf : W * unit ≤ W * (H).footprint w := Nat.mul_le_mul_left W (hle.trans floor) + change ((A).recenter v).inherited M.ord * unit ≤ c * (H).footprint w at hi + calc + _ ≤ (W + ((A).recenter v).inherited M.ord) * unit := Nat.mul_le_mul_right _ ho + _ ≤ W * (H).footprint w + c * (H).footprint w := by rw [Nat.add_mul]; exact Nat.add_le_add hf hi + _ = _ := by rw [← Nat.add_mul, Nat.add_comm W, Nat.add_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Branch +end + +/- +# Producing contracted descriptions for a family of branches + +One shared local table emits the new atom, counter, and any extra +fields determined by the same window. The host names bypass the table. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing History Window State.Board + +variable {F : Type} [Field F] {D : Template F} {P : Gadget F} {a : ℕ} {ha : a ≤ D.scheme.h} + {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} {hu : 0 < P.b * z} {hz : 0 < z} + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) + +open scoped Classical in +/-- The value specified by `((t.board hb).raw, D.childHeader a ha Δ C t.r)`. -/ +def Branch.head (t : D.Branch P a ha b k cost Δ C z σ hu) : (D.Headed a b Δ C).obj := + ((t.board hb).raw, D.childHeader a ha Δ C t.r) + +open scoped Classical in +theorem Branch.headed_eq (t : D.Branch P a ha b k cost Δ C z σ hu) : + D.headed a ha b Δ C P (D.prepared a ha b k cost Δ C (t.r, (t.s.selector hb).write t.i)) = + t.head hb := Prod.ext (t.s.poll_raw_eq hb t.i t.v) rfl + +variable (D a b Δ C) (M : Book D.scheme P z hz) (e cap : ℕ) (K : Meter) (W : Format) + +local notation "Y" => D.Label a Δ C M e cap K W +local notation "A" => D.WithCount a b +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "n" => (D.scheme.h - a) +local notation "q" => D.degree a Δ C + +open scoped Classical in +/-- The quantity computed by `(Tile.word d a n q A).width + (Y).width`. -/ +def issueWidth := (Tile.word d a n q A).width + (Y).width + +open scoped Classical in +/-- The quantity computed by `D.joinCost a b Δ C M e cap K W (Tile.bankCost m d a n q A v N l + +Tile.cost m d a n q A Y)`. -/ +def issueCost (v N l : ℕ) := D.joinCost a b Δ C M e cap K W + (Tile.bankCost m d a n q A v N l + Tile.cost m d a n q A Y) + +variable {a b Δ C e} (hc : Δ ≤ C) {I : Type*} + (t : I → D.Branch P a ha b k cost Δ C z σ hu) + (room : ∀ i, ((t i).state hb).Room e) + (ready : ∀ i, (t i).Ready hb hc M (room i) cap) + (extra : I → (Tile.output D.scheme.m a (D.scheme.h - a) W).obj) + +include ready in +open scoped Classical in +theorem issue_net (blank : W.obj) + (agree : ∀ i j x y, (((t i).board hb).recenter x).look = (((t j).board hb).recenter y).look → + extra i (childAt x) (cellIndex a x.1.2) = extra j (childAt y) (cellIndex a y.1.2)) + (vacant : ∀ i x y, D.childLive a (t i).r x = false → extra i x y = blank) : + ∃ table : Table F, wd table.1 + wd table.2.1 = D.issueWidth a b Δ C M e cap K W ∧ + ∀ {u v N l : ℕ} {L : Set (Table F)}, + 3 ≤ u → table ∈ L → D.issueWidth a b Δ C M e cap K W ≤ u → + Access F u L (m + d) v N → 2 ^ a * (Walks 8 d A).width ≤ v → + D.size a ≤ l → 2 ^ (Tile.radius d + (n + 1)) ≤ l → 2 ^ q ≤ l → + Computes F u L (D.Headed a b Δ C) (D.Issued a Δ C M e cap K W) + (fun i => (t i).head hb) (fun i => ((t i).output hb hc M (room i) cap K, extra i)) + (fun _ => 1) (D.issueCost a b Δ C M e cap K W v N l) := by + let X := Post.record q e M.d (.addr cap) + let post (i : I) (x : B (D.size a)) (y : B a) (v : X.obj) : (Y).obj := + (X.serial v, (t i).counters hc K x y, extra i x y) + let idle : (Y).obj := (X.serial Post.vacant, 0, blank) + obtain ⟨gate, size, h⟩ := print_net M cap hc (fun i => (t i).state hb) (fun i => (t i).board hb) + room Y idle post (fun i => (t i).s.canonical_live hb (t i).i (t i).v) + (fun i j x y he v => Prod.ext rfl (Prod.ext (Branch.counters_eq (ready i) (ready j) he K) + (agree i j x y he))) + (fun i x y hv => Prod.ext rfl (Prod.ext ((t i).counters_vacant hc K x y hv) (vacant i x y hv))) + (fun i => (t i).p.reciprocal) + refine ⟨gate, size, ?_⟩ + intro u v N l L h3 hg fit acc bound hm hr hq + have net := h h3 hg fit acc bound hm hr hq + exact D.join_computes a b Δ C M e cap K W h3 (fun i => (t i).head hb) _ net + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- +# A fixed number of contractions + +When the number of steps and the ratio of the load to a unit are +bounded in advance, the local atom count gives a direct estimate +without any global reserve for the retired ports. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing History + +namespace State +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + {u : State S P a h z Δ D k B'} {e : ℕ} + +open scoped Classical in +theorem Room.inherited (rm : u.Room e) (ord : B S.ℓ ≃ B S.ℓ) : + u.inherited ord ≤ 2 ^ e * S.ℓ := by + let J := History.Subround.Receipt P u.H u.g u.m u.i u.v + have hi (i : J) : Kind.carried S P (S.e + 2) ord (u.kind i.val) ≤ S.ℓ := by + rcases u.kind i.val with ⟨x, j⟩ | t + · exact Dense.used_le.mpr (ord x).isLt + · simp + have hcard : Fintype.card J ≤ 2 ^ e := by + simpa only [Fintype.card_fin] using Fintype.card_le_of_injective rm.atoms rm.atoms.injective + calc + _ ≤ ∑ _ : J, S.ℓ := Finset.sum_le_sum fun i _ => hi i + _ = Fintype.card J * S.ℓ := by simp + _ ≤ _ := Nat.mul_le_mul_right _ hcard + +end State + +namespace Template.Branch +variable {F : Type} [Field F] {D : Template F} {P : Gadget F} {a : ℕ} {ha : a ≤ D.scheme.h} + {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} {hu : 0 < P.b * z} {hz : 0 < z} {e : ℕ} + (t : D.Branch P a ha b k cost Δ C z σ hu) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (hc : Δ ≤ C) (hd : 0 < Δ) + (M : Book D.scheme P z hz) (rm : (t.state hb).Room e) + +include hd in +open scoped Classical in +theorem direct + (neutral : ∀ v, t.G.diagram.arity v = 0 → ∀ x, Transcript.sample (t.G.diagram.table v) x = 1) + (sizes : ∀ j, M.len (M.put (t.p.post.toPresentation.borderWidth j)) + = t.p.post.toPresentation.borderWidth j) : + t.Ready hb hc M rm (M.overhead e + 2 ^ e * D.scheme.ℓ) := by + constructor + · exact fun _ => rfl + · exact sizes + · exact D.child_hop a ha Δ C t.p hd hc + · exact neutral + · exact fun v => Nat.add_le_add_left ((rm.recenter v).inherited M.ord) _ + +end Template.Branch +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Network.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Network.lean new file mode 100644 index 0000000000..3fb7015034 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Network.lean @@ -0,0 +1,1046 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.BoardPush +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Guard + +/-! # Recovering both projected graph masks on the child address list -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F T : Type} (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (Δ C : ℕ) + +open scoped Classical in +/-- The value specified by `Format.vec (D.size a) (.pair (.pair .bit .bit) (Group.Flags +(D.degree a Δ C)))`. -/ +abbrev ChildHeader := Format.vec (D.size a) (.pair (.pair .bit .bit) (Group.Flags (D.degree a Δ C))) + +open scoped Classical in +/-- The child header of type `(D.ChildHeader a Δ C).obj` for the given inputs. -/ +def childHeader (r : D.format.obj) : (D.ChildHeader a Δ C).obj := + fun i => ((D.childLive a r i, D.childFrozen a r i), + fun j => (true, Child.coreFlags (D.childNav a ha Δ C r) (D.childCore a ha Δ r) i j)) + +variable [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} {r : D.format.obj} + {G : HostNet F L D.scheme.h u} (p : D.Encodes r G) (hd : 0 < Δ) (hc : Δ ≤ C) + +local notation "H" => Child.host p.post.host (D.scheme.h - a) +local notation "nav" => D.childNav a ha Δ C r +local notation "meta" => D.childHeader a ha Δ C r +local notation "Q" => G.project a ha Δ C hc + +open scoped Classical in +theorem child_frozen (v : Site G.V (D.scheme.h - a)) : + D.childFrozen a r (H v) = true ↔ G.frozen v.1 := by + rw [childFrozen, Child.host_parts] + exact p.frozen v.1 + +include hd hc in +open scoped Classical in +theorem child_closed (v : Site G.V (D.scheme.h - a)) (j : B (D.degree a Δ C)) : + nav (H v) j ∈ Set.range H := by + obtain ⟨w, _, hw⟩ := ((D.child_presents a ha p).mem (D.bound_pos Δ C hd hc) v _).mp ⟨j, rfl⟩ + exact ⟨w, hw⟩ + +include hd in +open scoped Classical in +theorem child_edge (v w : Site G.V (D.scheme.h - a)) : + w ∈ (if D.full then (Q).N else (Q).C) v ↔ + ∃ j, nav (H v) j = H w ∧ ((meta (H v)).2 j).1 = true := by + have he : (∃ j, nav (H v) j = H w) ↔ w ∈ cube (near (D.adj G) (D.bound Δ C)) v := by + refine ((D.child_presents a ha p).mem (D.bound_pos Δ C hd hc) v _).trans ?_ + simp + simp only [childHeader, and_true] + rw [he] + by_cases ht : D.full = true + · rw [adj, bound, ite_eq_left ht, ite_eq_left ht, ite_eq_left ht] + rfl + · rw [adj, bound, ite_eq_right ht, ite_eq_right ht, ite_eq_right ht] + rfl + +include hd in +open scoped Classical in +theorem child_core (v w : Site G.V (D.scheme.h - a)) : + w ∈ (Q).C v ↔ ∃ j, nav (H v) j = H w ∧ ((meta (H v)).2 j).2 = true := by + have he : (∃ j, D.childCore a ha Δ r (H v) j = H w) ↔ w ∈ (Q).C v := by + refine ((D.core_presents a ha p).mem hd v _).trans ?_ + change (∃ u ∈ cube (near G.C Δ) v, H u = H w) ↔ w ∈ cube (near G.C Δ) v + simp + simp only [childHeader, Child.coreFlags, decide_eq_true_eq] + constructor + · intro hw + have hh := D.child_hop a ha Δ C p hd hc v w hw + exact ⟨_, hh, by rw [hh]; exact he.mpr hw⟩ + · rintro ⟨j, hj, k, hk⟩ + exact he.mp ⟨k, hk.trans hj⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- +# Computing the common affine color on grouped records + +The first pass only reads the interval tags and outgoing stubs. Each +group at a live host votes for all the colors at once. Unused hosts +always give a zero ballot. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F T : Type} [Field F] (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (b : ℕ) + +open scoped Classical in +/-- The quantity computed by `Branches.format D.scheme.m a ((D.scheme.h - a) + D.scheme.e) b`. -/ +abbrev Candidate := Branches.format D.scheme.m a ((D.scheme.h - a) + D.scheme.e) b + +open scoped Classical in +/-- The quantity computed by `Window.Source D.scheme (D.scheme.h - a) b`. -/ +abbrev Source := Window.Source D.scheme (D.scheme.h - a) b +open scoped Classical in +/-- Computes the batch by the application `Fmt.groups D.scheme.m D.scheme.d a (D.Source a b)`. -/ +abbrev Batch := Fmt.groups D.scheme.m D.scheme.d a (D.Source a b) + +open scoped Classical in +/-- Tests whether `thick (colorIndex (D.scheme.h - a) i) ((cellIndex (D.scheme.h - a)).symm j)` +holds. -/ +def light (i : B ((D.scheme.h - a) + 1)) (j : B (D.scheme.h - a)) + := decide (thick (colorIndex (D.scheme.h - a) i) ((cellIndex (D.scheme.h - a)).symm j)) + +open scoped Classical in +/-- The value specified by `(x.1, x.2.1, D.light a c, x.2.2.2)`. -/ +def recolor (x : (D.Source a b).obj) (c : B ((D.scheme.h - a) + 1)) : (D.Source a b).obj := + (x.1, x.2.1, D.light a c, x.2.2.2) + +open scoped Classical in +/-- The score of type `B ((D.scheme.h - a) + D.scheme.e + 1)`, constructed using `Match.rows +(D.recolor a b x c).2.2`. -/ +def score (x : (D.Source a b).obj) (c : B ((D.scheme.h - a) + 1)) : B ((D.scheme.h - a) + + D.scheme.e + 1) := + let row := Match.rows (D.recolor a b x c).2.2 + ⟨(Finset.univ.filter fun i => row.control.1 i).card, by + refine (Finset.card_filter_le _ _).trans_lt ?_ + rw [Finset.card_univ, Fintype.card_fin, pow_succ] + have : 0 < (2 : ℕ) ^ ((D.scheme.h - a) + D.scheme.e) := by positivity + omega⟩ + +open scoped Classical in +/-- The quantity computed by `Format.vec ((D.scheme.h - a) + 1) (.addr ((D.scheme.h - a) + +D.scheme.e + 1))`. -/ +abbrev Vote := Format.vec ((D.scheme.h - a) + 1) (.addr ((D.scheme.h - a) + D.scheme.e + 1)) +open scoped Classical in +/-- Returns `D.score a b x.2` when `x.1` holds, and `fun _ => 0` otherwise. -/ +def vote (x : Bool × (D.Source a b).obj) : (D.Vote a).obj := + if x.1 then D.score a b x.2 else fun _ => 0 + +open scoped Classical in +/-- The construction uses `Match.rowIndex D.scheme.m a i` for its intermediate `y`. -/ +def sample (r : D.format.obj) (X : (D.Batch a b).obj) (i : B (D.scheme.m + a)) := + let y := Match.rowIndex D.scheme.m a i + (D.live r y.1, (X y.1).2 y.2) + +open scoped Classical in +/-- The indexed operation `elect ⊤ (fun c i => D.vote a b (D.sample a b r X i) c)`. -/ +def winner (r : D.format.obj) (X : (D.Batch a b).obj) : B ((D.scheme.h - a) + 1) := + elect ⊤ (fun c i => D.vote a b (D.sample a b r X i) c) + +open scoped Classical in +/-- The quantity computed by `Window.gather D.scheme a (D.scheme.h - a) b (D.position a ha) +(r.1, labels, fun _ => false, x)`. -/ +def scout (r : D.format.obj) (labels : (Window.Tags D.scheme a (D.scheme.h - a)).obj) + (x : (D.Candidate a b).obj) : (D.Batch a b).obj := + Window.gather D.scheme a (D.scheme.h - a) b (D.position a ha) (r.1, labels, fun _ => false, x) + +variable [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} {r : D.format.obj} + {G : HostNet F L D.scheme.h u} (p : D.Encodes r G) + {Δ C k : ℕ} {cost : ℝ} + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ C k cost (G.regroup a ha).load) + +open scoped Classical in +theorem nav_eq (v : G.V) (t : B D.scheme.d) : + p.post.host (p.post.nav v t) = D.nav r (p.post.host v) t := by + have h : ∃ w, p.post.host w = (r.1 (p.post.host v)).1 t := p.closed v t + rw [Scheme.Posting.nav, dite_eq_left h] + exact h.choose_spec + +variable (labels : (Window.Tags D.scheme a (D.scheme.h - a)).obj) (z : (D.Candidate a b).obj) + (hl : ∀ v i j, labels (p.post.host v) (cellIndex a i) (cellIndex (D.scheme.h - a) j) + = intervalCode (D.scheme.h - a) (g.here (v, i) j).2) + +include hl in +open scoped Classical in +theorem records (c : B ((D.scheme.h - a) + 1)) (v : G.V) (i : Cell a) : + (D.recolor a b ((D.scout a ha b r labels z (p.post.host v)).2 (cellIndex a i)) c).2.2 = + p.post.records a ha g (colorIndex (D.scheme.h - a) c) (v, i) := by + refine Prod.ext rfl (Prod.ext ?_ ?_) + · funext j + obtain ⟨j, rfl⟩ := (cellIndex (D.scheme.h - a)).surjective j + let w := (splitCell a ha).symm (i, j) + simp only [recolor, scout, Window.gather, Scheme.Posting.records, position, + Equiv.symm_apply_apply] + exact Prod.ext (hl v i j) (by rw [Scheme.Posting.localStub, p.block]) + · funext j t + obtain ⟨j, rfl⟩ := (cellIndex (D.scheme.h - a)).surjective j + simp only [recolor, scout, Window.gather, Scheme.Posting.records, Equiv.symm_apply_apply] + change labels (D.nav r (p.post.host v) t) _ _ = _ + rw [← D.nav_eq p] + exact hl _ _ _ + +include hl in +open scoped Classical in +theorem winner_eq : colorIndex (D.scheme.h - a) (D.winner a b r (D.scout a ha b r labels z)) = + p.post.color a ha g (Group.embed p.post.host a) := by + let X := D.scout a ha b r labels z + let f := Group.embed p.post.host a + have he : (fun c i => D.vote a b (D.sample a b r X i) c) = ballots f (p.post.colorScore a ha g) + := by + funext c i + by_cases h : i ∈ Set.range f + · obtain ⟨⟨v, j⟩, rfl⟩ := h + simp only [ballots, f.injective.extend_apply, sample, f, Group.row_embed, vote, + (p.live _).mpr ⟨v, rfl⟩, ↓reduceIte] + apply Fin.ext + simp only [score, Scheme.Posting.colorScore] + erw [D.records a ha b p g labels z hl c v j] + · have hz : D.live r (Match.rowIndex D.scheme.m a i).1 ≠ true := by + intro h' + obtain ⟨v, hv⟩ := (p.live _).mp h' + let j := (cellIndex a).symm (Match.rowIndex D.scheme.m a i).2 + refine h ⟨(v, j), (Match.rowIndex _ _).injective ?_⟩ + simp only [f, Group.row_embed, hv, j, Equiv.apply_symm_apply] + simp only [ballots, Function.extend_apply' _ _ _ h, sample, vote] + erw [ite_eq_right hz] + exact congrArg (fun x => colorIndex (D.scheme.h - a) (elect ⊤ x)) he + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Recovering both projected graph masks on the child address list -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F : Type} [Field F] (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (Δ C : ℕ) + +local notation "m" => D.size a +local notation "d" => D.degree a Δ C +local notation "q" => Child.nextWidth (D.scheme.h - a) Δ D.scheme.d + +open scoped Classical in +/-- Computes the lists by the application `Format.pair (.pair (D.Status a) (D.Status a)) (.vec m +(.vec d .bit))`. -/ +abbrev Lists := Format.pair (.pair (D.Status a) (D.Status a)) (.vec m (.vec d .bit)) + +open scoped Classical in +private def collate (x : (D.Lists a Δ C).obj) : (D.ChildHeader a Δ C).obj := + fun i => ((x.1.1 i, x.1.2 i), fun j => (true, x.2 i j)) + +open scoped Classical in +private theorem collate_net : Circuit F (D.Lists a Δ C) (D.ChildHeader a Δ C) + (D.collate a Δ C) ((D.Lists a Δ C).width + 34 * (D.ChildHeader a Δ C).width) := by + have h : Install.Depends ((D.ChildHeader a Δ C).code ∘ D.collate a Δ C ∘ (D.Lists a Δ + C).code.symm) 1 := by + rintro ⟨i, (⟨⟩ | ⟨⟩) | ⟨j, ⟨⟩ | ⟨⟩⟩⟩ + · exact ⟨{.inl (.inl (i, ()))}, by simp, fun x y h => h _ (Finset.mem_singleton_self _)⟩ + · exact ⟨{.inl (.inr (i, ()))}, by simp, fun x y h => h _ (Finset.mem_singleton_self _)⟩ + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + · exact ⟨{.inr (i, j, ())}, by simp, fun x y h => h _ (Finset.mem_singleton_self _)⟩ + exact h.bnet F + +open scoped Classical in +/-- The header cost used in the `Template` construction. -/ +def headerCost := + 5 * D.format.width + (5 * D.format.width + D.statusCost a + (D.format.width + + 2 * (D.Status a).width)) + + (5 * D.format.width + D.navCost a d + D.navCost a q + 2 ^ m * (100 + (m + 2 ^ d + 2 ^ q)) ^ 16) + + + ((D.Lists a Δ C).width + 34 * (D.ChildHeader a Δ C).width) + +open scoped Classical in +theorem header_net : Circuit F D.format (D.ChildHeader a Δ C) + (D.childHeader a ha Δ C) (D.headerCost a Δ C) := by + have hf : Circuit F D.format (D.Status a) (D.childFrozen a) (D.format.width + + 2 * (D.Status a).width) := + Circuit.project (fun i => .inr ((Match.rowIndex _ _ i.1).1, .inl (.inr i.2))) (fun _ _ => rfl) + obtain ⟨k, hk, h⟩ := Child.cheap_coreFlags F (t := m + 2 ^ d + 2 ^ q) + ((Nat.le_add_right m (2 ^ d)).trans (Nat.le_add_right _ _)) + ((Nat.le_add_left (2 ^ d) m).trans (Nat.le_add_right _ _)) (Nat.le_add_left (2 ^ q) _) + have flags := hk.mono (show k ≤ 2 ^ m * (100 + (m + 2 ^ d + + 2 ^ q)) ^ 16 from le_trans (Nat.le_add_left _ _) h) + have nav : Circuit F D.format (Neighborhood.Rows m d) (D.childNav a ha Δ C) (D.navCost a d) := + D.nav_net a ha false (D.bound Δ C) + have core : Circuit F D.format (Neighborhood.Rows m q) (D.childCore a ha Δ) (D.navCost a q) := + D.nav_net a ha true Δ + have lists := nav.pair core + have all := (((D.status_net a).pair hf).pair (lists.comp flags)).comp (D.collate_net a Δ C) + unfold headerCost + exact all + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- +# Cost of the common color decision + +Only a local group is inspected by a lookup. The large array +of ballots is then reduced by a trivalent integer summation tree. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring + +variable {F : Type} [Field F] (D : Template F) (a b : ℕ) + {u : ℕ} {L : Set (Table F)} +local notation "j" => (D.scheme.m + a) +local notation "n" => (D.scheme.h - a) +local notation "c" => (n + 1) +local notation "w" => (n + D.scheme.e + 1) + +open scoped Classical in +/-- Computes the poll by the application `D.format.pair (D.Batch a b)`. -/ +abbrev Poll := D.format.pair (D.Batch a b) +open scoped Classical in +/-- Computes the poll row by the application `Format.pair .bit (D.Source a b)`. -/ +abbrev PollRow := Format.pair .bit (D.Source a b) +open scoped Classical in +/-- Computes the polls by the application `Format.vec j (D.PollRow a b)`. -/ +abbrev Polls := Format.vec j (D.PollRow a b) +open scoped Classical in +/-- Computes the votes by the application `Format.vec j (D.Vote a)`. -/ +abbrev Votes := Format.vec j (D.Vote a) + +open scoped Classical in +/-- The indexed operation `weightTable (A := D.PollRow a b) (D := D.Vote a) (D.vote a b) (fun _ +=> (1 : F))`. -/ +def voteTable := weightTable (A := D.PollRow a b) (D := D.Vote a) (D.vote a b) (fun _ => (1 : F)) + +open scoped Classical in +/-- The poll cost used in the `Template` construction. -/ +def pollCost := 4 * ((D.Poll a b).width + 2 * (D.Polls a b).width) + + 2 ^ j * (1 + (D.PollRow a b).width + (D.Vote a).width) + + 4 * (3 * (D.Votes a).width + 2 ^ c * (2 ^ j * (100 + w) ^ 5 + (100 + (c + (w + j))) ^ 42)) + +open scoped Classical in +theorem sampling : + Circuit F (D.Poll a b) (D.Polls a b) (fun x => D.sample a b x.1 x.2) + ((D.Poll a b).width + 2 * (D.Polls a b).width) := by + let pins : (D.Polls a b).pins → (D.Poll a b).pins + | (i, .inl t) => .inl (.inr ((Match.rowIndex D.scheme.m a i).1, .inl (.inl t))) + | (i, .inr t) => .inr ((Match.rowIndex D.scheme.m a i).1, + .inr ((Match.rowIndex D.scheme.m a i).2, t)) + exact Circuit.project pins (by rintro _ ⟨i, t|t⟩ <;> rfl) + +open scoped Classical in +private theorem tally : + Circuit F (D.Votes a) (.addr c) (fun x => elect ⊤ fun y t => x t y) + (3 * (D.Votes a).width + 2 ^ c * (2 ^ j * (100 + w) ^ 5 + (100 + (c + (w + j))) ^ 42)) := by + let X := Format.vec c (.vec j (.addr w)) + have flip : Circuit F (D.Votes a) X (fun x i t => x t i) ((D.Votes a).width + 2 * X.width) := + Circuit.project (fun t => (t.2.1, t.1, t.2.2)) fun _ _ => rfl + have eq : X.width = (D.Votes a).width := by + simp only [X, Votes, Vote, Format.width_vec, mul_left_comm] + rw [eq, show (D.Votes a).width + 2 * (D.Votes a).width = 3 * (D.Votes a).width by omega] at flip + have hk := flip.comp (election F j c w ⊤) + simp only [Function.comp_def] at hk + exact hk + +open scoped Classical in +theorem map_winner (hu : 3 ≤ u) (hw : (D.PollRow a b).width + (D.Vote a).width ≤ u) + (hl : D.voteTable a b ∈ L) : + Map F u L (D.Poll a b) (.addr c) (fun x => D.winner a b x.1 x.2) (D.pollCost a b) := by + have lk : Map F u L (D.PollRow a b) (D.Vote a) (D.vote a b) + (1 + (D.PollRow a b).width + (D.Vote a).width) := Kernel.lookup hw hl + have v := Map.vec _ (fun _ : B j => lk) + exact ((Map.circuit hu (D.sampling a b)).comp v).comp (Map.circuit hu (D.tally a)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Retaining the parent counters in each grouped window -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring + +variable {F : Type} [Field F] (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (b : ℕ) + +/-- The quantity computed by `Format.pair (D.Source a b) (.vec (D.scheme.h - a) (.addr +D.count))`. -/ +abbrev WithCount := Format.pair (D.Source a b) (.vec (D.scheme.h - a) (.addr D.count)) + +/-- Computes the counted by the application `Fmt.groups D.scheme.m D.scheme.d a (D.WithCount a +b)`. -/ +abbrev Counted := Fmt.groups D.scheme.m D.scheme.d a (D.WithCount a b) + +/-- Evaluates `((x.2 i).1, fun j => ((x.2 i).2 j, fun k => D.counter x.1 i (D.position a ha j +k)))` at the input `i`. -/ +def counted (x : (D.Poll a b).obj) : (D.Counted a b).obj := + fun i => ((x.2 i).1, fun j => ((x.2 i).2 j, fun k => D.counter x.1 i (D.position a ha j k))) + +theorem counted_circuit : Circuit F (D.Poll a b) (D.Counted a b) (D.counted a ha b) + ((D.Poll a b).width + 2 * (D.Counted a b).width) := by + let pins : (D.Counted a b).pins → (D.Poll a b).pins + | (i, .inl q) => .inr (i, .inl q) + | (i, .inr (j, .inl q)) => .inr (i, .inr (j, q)) + | (i, .inr (j, .inr (k, q))) => .inl (.inr (i, .inr (.inr (D.position a ha j k, q)))) + exact Circuit.project pins (by rintro x ⟨i, q | ⟨j, q | ⟨k, q⟩⟩⟩ <;> rfl) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- +# Preparing the color ballot + +Group labels are already determined when the selector seats are +inspected. The first collection uses a dummy color column. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring + +variable {F : Type} [Field F] (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (b : ℕ) +local notation "S" => D.scheme +local notation "n" => (D.scheme.h - a) +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "q" => ((d + 1) * n) +open scoped Classical in +/-- Computes the request by the application `D.format.pair (D.Candidate a b)`. -/ +abbrev Request := D.format.pair (D.Candidate a b) +open scoped Classical in +/-- The quantity computed by `Format.vec (m + a) (Group.Labels n)`. -/ +abbrev Elected := Format.vec (m + a) (Group.Labels n) + +open scoped Classical in +/-- Evaluates `y ((Match.rowIndex m a).symm (v, i))` at the input `v i`. -/ +def columns (y : (D.Elected a).obj) : (Window.Tags S a n).obj := + fun v i => y ((Match.rowIndex m a).symm (v, i)) + +open scoped Classical in +/-- The indexed operation `(x.1.1.1, D.columns a x.2, fun _ => false, x.1.2)`. -/ +def setup (x : (D.Request a b).obj × (D.Elected a).obj) : (Window.Fields S a n b).obj := + (x.1.1.1, D.columns a x.2, fun _ => false, x.1.2) + +open scoped Classical in +private theorem setup_net : + Circuit F ((D.Request a b).pair (D.Elected a)) (Window.Fields S a n b) (D.setup a b) + (((D.Request a b).pair (D.Elected a)).width + 34 * (Window.Fields S a n b).width) := by + let A := (D.Request a b).pair (D.Elected a) + let B := Window.Fields S a n b + have h : Install.Depends (B.code ∘ D.setup a b ∘ A.code.symm) 1 := by + have pin (v : B.pins) (t : A.pins) (ht : ∀ x, B.code (D.setup a b x) v = A.code x t) : + ∃ s : Finset A.pins, s.card ≤ 1 ∧ ∀ x y, (∀ i ∈ s, x i = y i) → + (B.code ∘ D.setup a b ∘ A.code.symm) x v = (B.code ∘ D.setup a b ∘ A.code.symm) y v := by + refine ⟨{t}, by simp, fun x y he => ?_⟩ + simp only [Function.comp_apply, ht, Equiv.apply_symm_apply] + exact he t (by simp) + rintro (i | (⟨v, i, j⟩ | (j | k))) + · exact pin _ (.inl (.inl (.inl i))) fun _ => rfl + · exact pin _ (.inr ((Match.rowIndex m a).symm (v, i), j)) fun _ => rfl + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + · exact pin _ (.inl (.inr k)) fun _ => rfl + exact h.bnet F + +variable (k : ℕ) (B' : ℝ) (Δ C : ℕ) + +open scoped Classical in +/-- The value specified by `D.columns a (D.intervals a ha k B' Δ C r)`. -/ +def tags (r : D.format.obj) := D.columns a (D.intervals a ha k B' Δ C r) + +open scoped Classical in +/-- The value specified by `D.scout a ha b z.1 (D.tags a ha k B' Δ C z.1) z.2`. -/ +def collect (z : (D.Request a b).obj) := + D.scout a ha b z.1 (D.tags a ha k B' Δ C z.1) z.2 + +open scoped Classical in +/-- The collect cost used in the `Template` construction. -/ +def collectCost (v N v' N' p : ℕ) := + 200 * ((D.Request a b).width + (D.groupInput a).width + (D.Elected a).width + + (Window.Fields S a n b).width) + + Group.patchCost m d a n D.count v N + Group.cost (m + a) q n D.count + + Window.collectCost S a n b v' N' p + +variable {v N v' N' p u : ℕ} {L : Set (Table F)} {I : Type*} + +open scoped Classical in +theorem computes_collect (hu : 3 ≤ u) (hn : 0 < n) + (hg : Access F u L (m + q) v N) (hv : (Group.Parcel d a n D.count).width ≤ v) + (hc : Access F u L (m + d) v' N') (hv' : (Window.LabelSet a n).width ≤ v') + (hb : Group.arity q n D.count ≤ u) + (hL : (Group.keys F q n D.count Δ C (D.relative k B') : Set _) ⊆ L) + (out : Map F u L (.addr D.scheme.ℓ) (Window.Outgoing S) (fun i + => (D.scheme.decode i).outgoing) p) + (X : I → (D.Request a b).obj) + (hx : ∀ i, Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) (X i).1.1) : + Computes F u L (D.Request a b) (D.Batch a b) X (D.collect a ha b k B' Δ C ∘ X) + (fun _ => 1) (D.collectCost a b v N v' N' p) := by + let A := D.Request a b + have pr : Circuit F A D.format Prod.fst (A.width + 2 * D.format.width) := + Circuit.project Sum.inl fun _ _ => rfl + let Y i := D.groups a ha (X i).1 + have g := Computes.of_map (L := L) (x := X) (y := Y) + (Map.circuit hu (pr.comp (D.groups_circuit a ha))) (fun _ => rfl) + have h := g.comp (Group.labels_net hu hn hg hv Y hx hb hL) + have keep := Computes.of_map (L := L) (x := X) (y := X) (Map.circuit hu (Circuit.id F A)) (fun _ + => rfl) + let Z i := D.setup a b (X i, D.intervals a ha k B' Δ C (X i).1) + have fields := (keep.pair hu h).comp + (Computes.of_map (y := Z) (Map.circuit hu (D.setup_net a b)) (fun _ => rfl)) + have hit := fields.comp (Window.computes_gather S a n b hu hc hv' out (D.position a ha) Z hx) + simp only [one_mul] at hit + refine hit.mono ?_ + have hA : D.format.width ≤ A.width := by simp [A, Request] + unfold collectCost + rw [Format.width_pair (D.Request a b) (D.Elected a)] + unfold A at * + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- +# A common grouping and matching decision + +Inactive hosts cast a zero ballot. The score uses only outgoing +stubs and interval labels; branch selectors cannot affect it. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F T : Type} [Field F] (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (b k : ℕ) + (cost : ℝ) (Δ C : ℕ) +local notation "n" => (D.scheme.h - a) + +open scoped Classical in +/-- The indexed operation `D.winner a b r (D.collect a ha b k cost Δ C (r, fun _ => 0))`. -/ +def chosen (r : D.format.obj) : B (n + 1) := + D.winner a b r (D.collect a ha b k cost Δ C (r, fun _ => 0)) + +omit [Field F] in +open scoped Classical in +theorem choose_eq (v : (D.Request a b).obj) : + D.chosen a ha b k cost Δ C v.1 = D.winner a b v.1 (D.collect a ha b k cost Δ C v) := by + unfold chosen winner + apply congrArg (elect ⊤) + funext c i + unfold vote sample + split <;> rfl + +open scoped Classical in +/-- The prepared of type `(D.Poll a b).obj` for the given inputs. -/ +def prepared (v : (D.Request a b).obj) : (D.Poll a b).obj := + (v.1, Window.gather D.scheme a n b (D.position a ha) + (v.1.1, D.tags a ha k cost Δ C v.1, D.light a (D.chosen a ha b k cost Δ C v.1), v.2)) + +variable [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} {r : D.format.obj} + {G : HostNet F L D.scheme.h u} (p : D.Encodes r G) (σ : ℝ) (hu : 0 < u) + +open scoped Classical in +/-- The data for the selection construction, including `group`, `tags`, `matching`, `color`, +`control`. -/ +structure Selection where + /-- The `Selection` component of type `Grouping (inGroup a G.N) (inGroup a G.C) Δ C k cost + (G.regroup a ha).load`. -/ + group : Grouping (inGroup a G.N) (inGroup a G.C) Δ C k cost (G.regroup a ha).load + tags : ∀ v i j, D.tags a ha k cost Δ C r (p.post.host v) (cellIndex a i) (cellIndex n j) = + intervalCode n (group.here (v, i) j).2 + /-- The `Selection` component of type `Scheme.Posting.Matchings a ha group`. -/ + matching : Scheme.Posting.Matchings a ha group + color : matching.color = colorIndex n (D.chosen a ha b k cost Δ C r) + control : p.post.Controls hu a ha group matching + saving : (G.X : ℝ) / 4 - (L.Z + σ) ≤ u * (matching.count : ℝ) + +open scoped Classical in +theorem selection (hΔ : 0 < Δ) (hC : 0 < C) (hk : 1 ≤ k) (hn : k ≤ n) (hb : 0 < cost) + (hG : G.Bounded Δ C cost) (hbins : 256 * (coreBins Δ + 1) ≤ 2 ^ k) + (slack : (2 : ℝ) ^ k * cost * (Fintype.card G.V * 2 ^ a : ℕ) ≤ σ) + (delayed : D.full = false → n ≤ 32 * Nat.clog 2 (2 * C)) : + Nonempty (D.Selection a ha b k cost Δ C p σ hu) := by + obtain ⟨g, hg⟩ := D.grouping a ha p k cost Δ C hΔ hC hk hn hb hG delayed + have ht v i j : D.tags a ha k cost Δ C r (p.post.host v) (cellIndex a i) (cellIndex n j) = + intervalCode n (g.here (v, i) j).2 := hg (v, i) j + obtain ⟨t, hc, hctl, hshrink⟩ := + p.post.elected_matching hu a ha g (Group.embed p.post.host a) σ hb hG hbins slack + exact ⟨⟨g, ht, t, hc.trans (D.winner_eq a ha b p g _ _ ht).symm, hctl, hshrink⟩⟩ + +namespace Selection +variable {a ha b k cost Δ C p σ hu} + +open scoped Classical in +theorem prepared_at (s : D.Selection a ha b k cost Δ C p σ hu) + (z : (D.Candidate a b).obj) (v : G.V) (i : Cell a) : + Window.matching D.scheme + (((D.prepared a ha b k cost Δ C (r, z)).2 (p.post.host v)).2 (cellIndex a i)) = + p.post.records a ha s.group s.matching.color (v, i) := by + rw [s.color] + exact D.records a ha b p s.group _ z s.tags _ v i + +end Selection +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Reading the elected grouping and matching at every child host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Selection +open Coloring Packing + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} + {D : Template F} {P : Gadget F} {z a b k Δ C : ℕ} {ha : a ≤ D.scheme.h} + {r : D.format.obj} {G : HostNet F L D.scheme.h (P.b * z)} {p : D.Encodes r G} + {B' σ : ℝ} {hu : 0 < P.b * z} (s : D.Selection a ha b k B' Δ C p σ hu) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) + +local notation "n" => (D.scheme.h - a) + +open scoped Classical in +/-- Computes the choices by the application `s.group.Choice s.matching P`. -/ +abbrev choices := s.group.Choice s.matching P + +open scoped Classical in +/-- Computes the selector by the application `p.post.branches hu a ha s.group s.matching +s.control P hb`. -/ +def selector : Transcript.Selector s.choices (D.Candidate a b).obj := + p.post.branches hu a ha s.group s.matching s.control P hb + +variable (i : s.choices) (v : Site (G.V × Cell a) (D.scheme.h - a)) + +open scoped Classical in +/-- Builds `State D.scheme P a D.scheme.h z Δ C k B' where T` with the specified `ha`, `hz`, +`ctl`, `selector`. -/ +def state : State D.scheme P a D.scheme.h z Δ C k B' where + T := T + x := x + y := y + L := L + G := G + r := r.1 + p := p.post + ha := ha + hz := Nat.pos_of_mul_pos_left hu + g := s.group + m := s.matching + ctl := s.control + i := i + selector j := Branches.read P ((s.selector hb).write i (p.post.placeGroup a j.1, j.2)) + selected t := p.post.read_branch hu a ha s.group s.matching s.control P hb i t + v := v + +open scoped Classical in +/-- The value specified by `(r.1, D.tags a ha k B' Δ C r, D.light a (D.chosen a ha b k B' Δ C +r), (s.selector hb).write i)`. -/ +def fields : (Window.Fields D.scheme a n b).obj := + (r.1, D.tags a ha k B' Δ C r, D.light a (D.chosen a ha b k B' Δ C r), (s.selector hb).write i) + +open scoped Classical in +theorem supplied : (s.state hb i v).Supplied (D.position a ha) (s.fields hb i) where + old := rfl + closed := p.closed + index t j := by + change D.position a ha (cellIndex a t) j = p.post.block _ + rw [position, Equiv.symm_apply_apply, p.block] + label v c j := by + obtain ⟨j, rfl⟩ := (cellIndex n).surjective j + rw [Equiv.symm_apply_apply] + exact s.tags v c j + color j := by + change decide (thick (colorIndex _ (D.chosen a ha b k B' Δ C r)) ((cellIndex _).symm j)) = + decide (thick s.matching.color _) + rw [s.color] + choice _ _ := rfl + +open scoped Classical in +/-- The value specified by `D.counted a ha b (D.prepared a ha b k B' Δ C (r, (s.selector +hb).write i))`. -/ +abbrev parents := D.counted a ha b (D.prepared a ha b k B' Δ C (r, (s.selector hb).write i)) + +open scoped Classical in +/-- Builds `(s.state hb i v).Board d (D.WithCount a b) Prod.fst where parent` with the specified +`parent`, `child`, `live`, `self`. -/ +def board {d : ℕ} (child : (Neighborhood.Rows (D.scheme.m + (n + 1)) d).obj) + (live : B (D.scheme.m + (n + 1)) → Bool) (self : ∀ j, child j 0 = j) : + (s.state hb i v).Board d (D.WithCount a b) Prod.fst where + parent := s.parents hb i + child := child + live := live + self := self + view := by + have H := (s.supplied hb i v).view + exact ⟨H.nav, H.data, H.recv, H.extra⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Selection +end + +/- +# Selecting a common contraction and checking its branch encoding + +At a vacant parent the seat mask is zero. The selector word itself +is retained even there, since nonzero padding must fail the guard. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F : Type} [Field F] (D : Template F) (a b : ℕ) (P : Gadget F) + +local notation "n" => (D.scheme.h - a + D.scheme.e) +local notation "M" => D.scheme.m + +open scoped Classical in +/-- Computes the slots by the application `Branches.Slot M a n`. -/ +abbrev Slots := Branches.Slot M a n + +open scoped Classical in +/-- Reindexes `B ((M + a) + n)` and `D.Slots a` by an equivalence. -/ +def seatIndex : B ((M + a) + n) ≃ D.Slots a := + (Match.rowIndex (M + a) n).trans ((Match.rowIndex M a).prodCongr (.refl _)) + +open scoped Classical in +/-- Evaluates `(x.1 && (Match.rows (Window.matching D.scheme x.2)).control.1 i, x.2.2.1 i)` at +the input `i`. -/ +def mark (x : (D.PollRow a b).obj) : (Side.Input n b).obj := + fun i => (x.1 && (Match.rows (Window.matching D.scheme x.2)).control.1 i, x.2.2.1 i) + +open scoped Classical in +/-- Evaluates `D.mark a b (D.live x.1 t.1.1, (x.2 t.1.1).2 t.1.2) t.2` at the input `t`. -/ +def marks (x : (D.Poll a b).obj) : (Branches.Marked (D.Slots a) b).obj := + fun t => D.mark a b (D.live x.1 t.1.1, (x.2 t.1.1).2 t.1.2) t.2 + +open scoped Classical in +/-- The value specified by `Side.pick (profileOf P ∘ Branches.read P) (D.marks a b x ∘ +D.seatIndex a)`. -/ +def layout (x : (D.Poll a b).obj) : Bool := + Side.pick (profileOf P ∘ Branches.read P) (D.marks a b x ∘ D.seatIndex a) + +open scoped Classical in +/-- The value specified by `∏ i, Branches.test F (Fintype.card (Branches.Tag P)) (D.marks a b x +i).1 (D.marks a b x i).2`. -/ +def valid (x : (D.Poll a b).obj) : F := + ∏ i, Branches.test F (Fintype.card (Branches.Tag P)) (D.marks a b x i).1 (D.marks a b x i).2 + +namespace Selection + +variable {T : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} + {D a b P} {z k Δ C : ℕ} {ha : a ≤ D.scheme.h} + {r : D.format.obj} {G : HostNet F L D.scheme.h (P.b * z)} {p : D.Encodes r G} + {B' σ : ℝ} {hu : 0 < P.b * z} (s : D.Selection a ha b k B' Δ C p σ hu) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) + +local notation "seats" => p.post.seats hu a ha s.group s.matching s.control + +open scoped Classical in +theorem mask (t : (D.Candidate a b).obj) (j : D.Slots a) : + (D.marks a b (D.prepared a ha b k B' Δ C (r, t)) j).1 = true ↔ + j ∈ Set.range seats := by + let y := D.prepared a ha b k B' Δ C (r, t) + apply p.post.seats_iff hu a ha s.group s.matching s.control (fun i => (D.marks a b y i).1) + · rintro ⟨v, i⟩ j + have hl := (p.live _).mpr ⟨v, rfl⟩ + change (D.live r (p.post.host v) && + (Match.rows (Window.matching D.scheme ((y.2 (p.post.host v)).2 (cellIndex a i)))).control.1 + j) = _ + rw [hl, Bool.true_and, show Window.matching _ _ = _ from prepared_at D s t v i] + · rintro ⟨v, i⟩ hv j + have hl : D.live r v = false := by + apply Bool.eq_false_iff.mpr + intro he + obtain ⟨w, hw⟩ := (p.live v).mp he + exact hv ⟨(w, (cellIndex a).symm i), Prod.ext hw ((cellIndex _).apply_symm_apply _)⟩ + change (D.live r v && _) = false + rw [hl, Bool.false_and] + +open scoped Classical in +theorem valid_eq (t : (D.Candidate a b).obj) : + D.valid a b P (D.prepared a ha b k B' Δ C (r, t)) = ((s.selector hb).read t).elim 0 (fun _ + => 1) := + p.post.guard_branch hu a ha s.group s.matching s.control P hb _ (s.mask t) t + +open scoped Classical in +theorem layout_eq (i : s.choices) : + D.layout a b P (D.prepared a ha b k B' Δ C (r, (s.selector hb).write i)) = + s.group.layout s.matching P i := by + let t := (s.selector hb).write i + let j := D.seatIndex a + let w := (seats).trans j.symm.toEmbedding + unfold layout Grouping.layout + apply Side.pick_eq_side _ (s.group.profile s.matching i) _ w + · intro z + refine (s.mask t (j z)).trans ?_ + exact ⟨fun ⟨x, he⟩ => ⟨x, j.symm_apply_eq.mpr he⟩, + fun ⟨x, he⟩ => ⟨x, j.symm_apply_eq.mp he⟩⟩ + · intro z + change profileOf P (Branches.read P (t (j (j.symm ((seats) z))))) = _ + rw [Equiv.apply_symm_apply] + exact congrArg (profileOf P) (p.post.read_branch hu a ha s.group s.matching s.control P hb i z) + +end Selection +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Checking gadget seats and computing the layout on the same records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F : Type} [Field F] (D : Template F) (a b : ℕ) +local notation "n" => (D.scheme.h - a + D.scheme.e) +local notation "j" => (D.scheme.m + a) + +open scoped Classical in +/-- Computes the entries by the application `Branches.Marked (D.Slots a) b`. -/ +abbrev Entries := Branches.Marked (D.Slots a) b +open scoped Classical in +/-- Computes the groups by the application `Format.vec j (Side.Input n b)`. -/ +abbrev Groups := Format.vec j (Side.Input n b) + +open scoped Classical in +/-- The indexed operation `weightTable (A := D.PollRow a b) (D := Side.Input n b) (D.mark a b) +(fun _ => (1 : F))`. -/ +def markTable := weightTable (A := D.PollRow a b) (D := Side.Input n b) (D.mark a b) (fun _ + => (1 : F)) + +open scoped Classical in +/-- The mark cost used in the `Template` construction. -/ +def markCost := + 4 * ((D.Poll a b).width + 2 * (D.Polls a b).width) + + 2 ^ j * (1 + (D.PollRow a b).width + (Side.Input n b).width) + + 4 * ((D.Groups a b).width + 2 * (D.Entries a b).width) + +variable {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + (size : (D.PollRow a b).width + (Side.Input (D.scheme.h - a + D.scheme.e) b).width + ≤ u) (allowed : D.markTable a b ∈ L) + +include hu size allowed in +open scoped Classical in +theorem map_marks : + Map F u L (D.Poll a b) (D.Entries a b) (D.marks a b) (D.markCost a b) := by + let f (x : (D.Groups a b).obj) (i : D.Slots a) := x ((Match.rowIndex _ _).symm i.1) i.2 + have post : Circuit F (D.Groups a b) (D.Entries a b) f + ((D.Groups a b).width + 2 * (D.Entries a b).width) := + Circuit.project (fun t => ((Match.rowIndex _ _).symm t.1.1, t.1.2, t.2)) (fun _ _ => rfl) + have lk : Map F u L (D.PollRow a b) (Side.Input n b) (D.mark a b) + (1 + (D.PollRow a b).width + (Side.Input n b).width) := Kernel.lookup size allowed + have H := ((Map.circuit hu (D.sampling a b)).comp (Map.vec _ (fun _ : B j => lk))).comp + (Map.circuit hu post) + convert H using 1 + · funext x i + simp only [Function.comp_apply, marks, f, sample, Equiv.apply_symm_apply] + · rfl + +open scoped Classical in +/-- The layout cost used in the `Template` construction. -/ +def layoutCost (t : ℕ) := + D.markCost a b + Fintype.card (D.Slots a) * Branches.charge b + + 4 * ((D.Entries a b).width + 2 * (Side.Input (j + n) b).width) + 4 * (2 ^ (j + n) * (100 + + t) ^ 8) + +include hu size allowed in +open scoped Classical in +theorem layout_net (P : Gadget F) (t : ℕ) (hw : 2 ^ b ≤ t) (hp : 4 * P.b ≤ 2 ^ t) : + Action F u L (D.Poll a b) .bit (D.layout a b P) (D.valid a b P) (D.layoutCost a b t) := by + let profile (i : B b) := profileOf P (Branches.read P i) + have bound (i : B b) : ∑ s, profile i s < 2 ^ t := by + unfold profile + cases Branches.read P i with + | none => simp [profileOf] + | some q => exact (P.cost _ q.2.property).trans_le hp + have perm : Circuit F (D.Entries a b) (Side.Input (j + n) b) (fun x => x ∘ D.seatIndex a) + ((D.Entries a b).width + 2 * (Side.Input (j + n) b).width) := + Circuit.project (fun i => ⟨D.seatIndex a i.1, i.2⟩) (fun _ _ => rfl) + have mask := D.map_marks a b hu size allowed + have valid := (Branches.check (J := D.Slots a) (b + := b) hu (Fintype.card (Branches.Tag P))).pre mask + exact (valid.post (Map.circuit hu perm)).post (Side.map_pick profile F hu L _ t hw bound) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- +# Broadcasting the elected color +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring + +variable {F : Type} [Field F] (D : Template F) (a b : ℕ) {u : ℕ} {L : Set (Table F)} +local notation "n" => (D.scheme.h - a) + +open scoped Classical in +/-- Computes the colors by the application `Format.vec n .bit`. -/ +abbrev Colors := Format.vec n .bit +open scoped Classical in +/-- The value specified by `(D.Poll a b).pair (D.Colors a)`. -/ +abbrev Colored := (D.Poll a b).pair (D.Colors a) + +open scoped Classical in +/-- The indexed operation `(x.1.1, fun i => ((x.1.2 i).1, fun j => let r := (x.1.2 i).2 j (r.1, +r.2.1, x.2, r.2.2.2)))`. -/ +def relight (x : (D.Colored a b).obj) : (D.Poll a b).obj := + (x.1.1, fun i => ((x.1.2 i).1, fun j => + let r := (x.1.2 i).2 j + (r.1, r.2.1, x.2, r.2.2.2))) + +open scoped Classical in +/-- The quantity computed by `weightTable (A := .addr (n + 1)) (D := D.Colors a) (D.light a) +(fun _ => (1 : F))`. -/ +def lightTable := weightTable (A := .addr (n + 1)) (D := D.Colors a) (D.light a) (fun _ => (1 : F)) + +open scoped Classical in +theorem relight_net : + Circuit F (D.Colored a b) (D.Poll a b) (D.relight a b) + ((D.Colored a b).width + 2 * (D.Poll a b).width) := by + let read : (D.Poll a b).pins → (D.Colored a b).pins + | .inr (_, .inr (_, .inr (.inr (.inl k)))) => .inr k + | i => .inl i + exact Circuit.project read (by rintro x (i | ⟨i, j|⟨j, k|(k|(k|k))⟩⟩) <;> rfl) + +open scoped Classical in +/-- The quantity computed by `D.pollCost a b + 1 + (n + 1) + (D.Colors a).width + 40 * +(D.Colored a b).width`. -/ +def lightCost := D.pollCost a b + 1 + (n + 1) + (D.Colors a).width + + 40 * (D.Colored a b).width + +open scoped Classical in +theorem computes_relight {I : Type*} (hu : 3 ≤ u) + (hw : (D.PollRow a b).width + (D.Vote a).width ≤ u) (hl : D.voteTable a b ∈ L) + (hd : n + 1 + (D.Colors a).width ≤ u) (hk : D.lightTable a ∈ L) + (X : I → (D.Poll a b).obj) : + Computes F u L (D.Poll a b) (D.Poll a b) X + (fun i => D.relight a b (X i, D.light a (D.winner a b (X i).1 (X i).2))) + (fun _ => 1) (D.lightCost a b) := by + have he : Map F u L (.addr (n + 1)) (D.Colors a) (D.light a) + (1 + (Format.addr (n + 1)).width + (D.Colors a).width) := + Kernel.lookup (by rwa [Format.width_addr]) hk + have hm := (D.map_winner a b hu hw hl).comp he + have ht := Computes.of_map (x := X) hm (fun _ => rfl) + have hi := Computes.of_map (L := L) (x := X) (y := X) + (Map.circuit hu (Circuit.id F (D.Poll a b))) (fun _ => rfl) + have h := (hi.pair hu ht).comp (Computes.of_map (Map.circuit hu (D.relight_net a b)) (fun _ + => rfl)) + simp only [one_mul, Function.comp_apply] at h + refine h.mono ?_ + unfold lightCost + rw [Format.width_addr] + have hp : (D.Poll a b).width ≤ (D.Colored a b).width := by simp [Colored] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- +# Grouping and coloring cost from a common input template +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring + +variable {F : Type} [Field F] (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (b k : ℕ) + (cost : ℝ) (Δ C : ℕ) +local notation "S" => D.scheme +local notation "n" => (D.scheme.h - a) +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "q" => ((d + 1) * n) +local notation "X₀" => D.Request a b + +open scoped Classical in +/-- The indexed operation `weightTable (A := .addr D.scheme.ℓ) (D := Window.Outgoing S) (fun i +=> (D.scheme.decode i).outgoing) (fun _ => (1 : F))`. -/ +def stubTable := weightTable (A := .addr D.scheme.ℓ) (D := Window.Outgoing S) + (fun i => (D.scheme.decode i).outgoing) (fun _ => (1 : F)) + +open scoped Classical in +/-- The quantity computed by `D.scheme.ℓ + (Window.Outgoing S).width`. -/ +def tableWidth := D.scheme.ℓ + (Window.Outgoing S).width + +open scoped Classical in +/-- The value specified by `insert D.stubTable (insert (D.lightTable a) (insert (D.voteTable a +b) (Group.keys F q n D.count Δ C (D.relative k cost))))`. -/ +def keys : Finset (Table F) := + insert D.stubTable (insert (D.lightTable a) (insert (D.voteTable a b) + (Group.keys F q n D.count Δ C (D.relative k cost)))) + +open scoped Classical in +theorem card_keys : (D.keys a b k cost Δ C).card ≤ 5 := by + unfold keys + apply (Finset.card_insert_le _ _).trans + apply Nat.add_le_add_right + apply (Finset.card_insert_le _ _).trans + apply Nat.add_le_add_right + apply (Finset.card_insert_le _ _).trans + exact Nat.add_le_add_right (Group.card_keys F) _ + +open scoped Classical in +/-- The value specified by `D.tableWidth + Group.arity q n D.count + (n + 1 + (D.Colors +a).width) + ((D.PollRow a b).width + (D.Vote a).width)`. -/ +def arity := D.tableWidth + Group.arity q n D.count + (n + 1 + (D.Colors a).width) + + ((D.PollRow a b).width + (D.Vote a).width) + +open scoped Classical in +/-- The quantity computed by `40 * (X₀).width + D.collectCost a b v N v' N' (1 + D.tableWidth) + +D.lightCost a b`. -/ +def prepareCost (v N v' N' : ℕ) := + 40 * (X₀).width + D.collectCost a b v N v' N' (1 + D.tableWidth) + D.lightCost a b + +variable {v N v' N' u : ℕ} {L : Set (Table F)} {I : Type*} + +open scoped Classical in +theorem prepare_net (hu : 3 ≤ u) (hn : 0 < n) + (hg : Access F u L (m + q) v N) (hv : (Group.Parcel d a n D.count).width ≤ v) + (hc : Access F u L (m + d) v' N') (hv' : (Window.LabelSet a n).width ≤ v') + (hb : D.arity a b ≤ u) (hL : (D.keys a b k cost Δ C : Set _) ⊆ L) + (X : I → (X₀).obj) + (hx : ∀ i, Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) (X i).1.1) : + Computes F u L X₀ (D.Poll a b) X (D.prepared a ha b k cost Δ C ∘ X) + (fun _ => 1) (D.prepareCost a b v N v' N') := by + unfold arity at hb + simp only [keys, Finset.coe_insert, Set.insert_subset_iff] at hL + have out : Map F u L (.addr D.scheme.ℓ) (Window.Outgoing S) + (fun i => (D.scheme.decode i).outgoing) (1 + D.tableWidth) := by + have he : (Format.addr D.scheme.ℓ).width + (Window.Outgoing S).width = D.tableWidth := by + simp [tableWidth] + rw [← he, ← add_assoc] + exact Kernel.lookup (by rw [he]; omega) hL.1 + have h := D.computes_collect a ha b k cost Δ C hu hn hg hv hc hv' (by omega) hL.2.2.2 out X hx + have pr : Circuit F X₀ D.format Prod.fst ((X₀).width + 2 * D.format.width) := + Circuit.project Sum.inl fun _ _ => rfl + have keep := Computes.of_map (L := L) (x := X) (Map.circuit hu pr) (fun _ => rfl) + let Y i := ((X i).1, D.collect a ha b k cost Δ C (X i)) + have step := D.computes_relight a b hu (by omega) hL.2.2.1 (by omega) hL.2.1 Y + have val : (fun i => D.relight a b (Y i, D.light a (D.winner a b (Y i).1 (Y i).2))) = + D.prepared a ha b k cost Δ C ∘ X := by + funext i + simp only [Function.comp_apply, prepared, D.choose_eq a ha b k cost Δ C (X i)] + rfl + rw [val] at step + have all := (keep.pair hu h).comp step + simp only [mul_one] at all + refine all.mono ?_ + unfold prepareCost + have he : D.format.width ≤ (X₀).width := by simp [Request] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Presents.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Presents.lean new file mode 100644 index 0000000000..6a981e3078 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Presents.lean @@ -0,0 +1,555 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Bins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Group.ChildPaths + +/-! +# A uniform representation of intermediate core networks + +The scheme contains the table and port data. At each host a common +header records occupancy, frozen status and graph masks. A short +second field in each block encodes its load and history counters. +The decoder and the ordering for measuring tag lengths are shared +by all branches at this stage. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing + +open scoped Classical in +/-- The data for the template construction, including `scheme`, `count`, `load`, `park`, `past`. -/ +structure Template (F : Type) where + /-- The `Template` component of type `Scheme F`. -/ + scheme : Scheme F + /-- The number of entries. -/ + count : ℕ + /-- The `Template` component of type `B count → ℝ`. -/ + load : B count → ℝ + /-- The `Template` component of type `B count → ℝ`. -/ + park : B count → ℝ + /-- The `Template` component of type `B count → ℕ`. -/ + past : B count → ℕ + /-- Reindexes the data using `B scheme.ℓ ≃ B scheme.ℓ`. -/ + order : B scheme.ℓ ≃ B scheme.ℓ + /-- The `Template` component of type `Bool`. -/ + full : Bool := true + +namespace Template +variable {F T : Type} (D : Template F) + +open scoped Classical in +/-- Computes the header by the application `Format.pair (.pair .bit .bit) (.pair (Group.Flags +D.scheme.d) (.vec D.scheme.h (.addr D.count)))`. -/ +abbrev header := Format.pair (.pair .bit .bit) + (.pair (Group.Flags D.scheme.d) (.vec D.scheme.h (.addr D.count))) + +open scoped Classical in +/-- Computes the format by the application `D.scheme.format.pair (.vec D.scheme.m D.header)`. -/ +abbrev format := D.scheme.format.pair (.vec D.scheme.m D.header) + +open scoped Classical in +theorem width : D.format.width = 2 ^ D.scheme.m * + (2 ^ D.scheme.d * (D.scheme.m + 2) + 2 + 2 ^ D.scheme.h * (D.scheme.ℓ + D.count)) := by + simp only [format, header, Scheme.format, Fmt.rows, Group.Flags, Format.width_pair, + Format.width_vec, + Format.width_addr] + rw [Format.width_bit] + ring + +open scoped Classical in +theorem scheme_width_le : D.scheme.format.width ≤ D.format.width := by + rw [Format.width_pair] + exact Nat.le_add_right .. + +variable (r : D.format.obj) + +open scoped Classical in +/-- The value specified by `(r.1 i).1`. -/ +abbrev nav (i : B D.scheme.m) := (r.1 i).1 +open scoped Classical in +/-- The value specified by `(r.2 i).1.1`. -/ +abbrev live (i : B D.scheme.m) := (r.2 i).1.1 +open scoped Classical in +/-- The value specified by `(r.2 i).1.2`. -/ +abbrev frozen (i : B D.scheme.m) := (r.2 i).1.2 +open scoped Classical in +/-- The value specified by `(r.2 i).2.1`. -/ +abbrev flags (i : B D.scheme.m) := (r.2 i).2.1 +open scoped Classical in +/-- The value specified by `(r.2 i).2.2`. -/ +abbrev counter (i : B D.scheme.m) := (r.2 i).2.2 + +variable [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} + (G : HostNet F L D.scheme.h u) + +open scoped Classical in +/-- If noncore propagation is too slow to cross an edge in one +phase, the controller need only store the core graph. -/ +abbrev adj := if D.full then G.N else G.C + +open scoped Classical in +/-- The data for the encodes construction, including `post`, `block`, `live`, `frozen`, +`closed`. -/ +structure Encodes where + /-- The `Encodes` component of type `D.scheme.Posting r.1 G`. -/ + post : D.scheme.Posting r.1 G + block : ∀ i, post.block i = cellIndex _ i + live : ∀ i, D.live r i = true ↔ i ∈ Set.range post.host + frozen : ∀ v, D.frozen r (post.host v) = true ↔ G.frozen v + closed : ∀ v j, D.nav r (post.host v) j ∈ Set.range post.host + reciprocal : Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) r.1 + edge : ∀ v w, w ∈ D.adj G v ↔ ∃ j, D.nav r (post.host v) j = post.host w ∧ + (D.flags r (post.host v) j).1 = true + core : ∀ v w, w ∈ G.C v ↔ ∃ j, D.nav r (post.host v) j = post.host w ∧ + (D.flags r (post.host v) j).2 = true + load : ∀ v i, D.load (D.counter r (post.host v) (post.block i)) = G.load v i + park : ∀ v i, D.park (D.counter r (post.host v) (post.block i)) = push G.park L.charge (v, i) + past : ∀ v i, D.past (D.counter r (post.host v) (post.block i)) = G.past (v, i) + +open scoped Classical in +/-- Computes the tag length by the application `History.Dense.used (D.order ((r.1 i).2 t)).val`. -/ +def tagLength (i : B D.scheme.m) (t : B D.scheme.h) := + History.Dense.used (D.order ((r.1 i).2 t)).val + +end Template +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # A board with one station per occurrence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing Rounds + +variable {F : Type} [Field F] {x y : Wire} (D : Template F) + (r : D.format.obj) (P : Rounds.Board F x y D.scheme.h) + +/-- The data for the presents construction, including `pres`, `host`, `vertex`, `directed`, +`live`. -/ +structure Presents where + /-- The `Presents` component of type `D.scheme.Presentation r.1 P.diagram`. -/ + pres : D.scheme.Presentation r.1 P.diagram + /-- Embeds the coordinates as `P.V ↪ B D.scheme.m`. -/ + host : P.V ↪ B D.scheme.m + vertex : ∀ v, pres.vertex v = (host (P.place v).1, cellIndex _ (P.place v).2, 0) + directed : pres.Directed + live : ∀ i, D.live r i = true ↔ i ∈ Set.range host + closed : ∀ v j, D.nav r (host v) j ∈ Set.range host + reciprocal : Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) r.1 + edge : ∀ v w, w ∈ P.adj v ↔ ∃ j, D.nav r (host v) j = host w ∧ + (D.flags r (host v) j).1 = true + core : ∀ v w, w ∈ P.adj v ↔ ∃ j, D.nav r (host v) j = host w ∧ + (D.flags r (host v) j).2 = true + load : ∀ v i, D.load (D.counter r (host v) (cellIndex _ i)) = push P.place P.charge (v, i) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # A presentation of one concentrated term before cutting off its border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing Rounds +variable {F : Type} [Field F] {x y : Wire} {u : ℕ} + +open scoped Classical in +/-- The data for the shows construction, including `pres`, `host`, `vertex`, `directed`, +`uniform`. -/ +structure Shows (D : Template F) (r : D.format.obj) (Q : LocalTerm F x y D.scheme.h u) where + /-- The `Shows` component of type `D.scheme.Presentation r.1 Q.diagram`. -/ + pres : D.scheme.Presentation r.1 Q.diagram + /-- Embeds the coordinates as `Q.V ↪ B D.scheme.m`. -/ + host : Q.V ↪ B D.scheme.m + vertex : ∀ v, pres.vertex v = (host (Q.frame.place v).1, cellIndex _ (Q.frame.place v).2, 0) + directed : pres.Directed + uniform : pres.Uniform u + /-- The identification of the indices of type `Q.V → Q.V → B D.scheme.d`. -/ + index : Q.V → Q.V → B D.scheme.d + neighbor : ∀ v w i j, D.scheme.peer r.1 (pres.vertex v, i) = some (pres.vertex w, j) → + (D.scheme.pattern r.1 (pres.vertex v)).peer 0 i = + some (index (Q.frame.place v).1 (Q.frame.place w).1, 0, j) + live : ∀ i, D.live r i = true ↔ i ∈ Set.range host + frozen : ∀ v, D.frozen r (host v) = true ↔ Q.frame.frozen v + closed : ∀ v j, D.nav r (host v) j ∈ Set.range host + reciprocal : Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) r.1 + edge : ∀ v w, w ∈ Q.frame.N v ↔ ∃ j, D.nav r (host v) j = host w ∧ (D.flags r (host v) j).1 = true + core : ∀ v w, w ∈ Q.frame.C v ↔ ∃ j, D.nav r (host v) j = host w ∧ (D.flags r (host v) j).2 = true + charge : ∀ v, Q.charge v = Q.diagram.arity v + (u : ℝ) + amount : ∀ i j, D.load (D.counter r i j) = + ∑ v, if (pres.vertex v).1 = i ∧ (pres.vertex v).2.1 = j then Q.charge v else 0 + +variable (D : Template F) + +open scoped Classical in +/-- Computes the cut counter by the application `Format.pair .bit (.addr D.count)`. -/ +abbrev cutCounter := Format.pair .bit (.addr D.count) + +open scoped Classical in +/-- Builds `Template F where scheme` with the specified `scheme`, `count`, `load`, `let`. -/ +abbrev cut (u : ℕ) (scale : ℝ) : Template F where + scheme := D.scheme.cut + count := D.cutCounter.width + load j := + let x := D.cutCounter.serial.symm j + if x.1 then scale * D.load x.2 else max 0 (D.load x.2 - u) + park j := + let x := D.cutCounter.serial.symm j + if x.1 then D.load x.2 else 0 + past _ := 0 + order := Equiv.refl _ + full := true + +open scoped Classical in +/-- The value specified by `!(D.frozen r i)`. -/ +def mobile (r : D.format.obj) (i : B D.scheme.m) := !(D.frozen r i) + +open scoped Classical in +/-- The indexed operation `(D.scheme.remove r.1 (D.mobile r), fun i => ((r.2 i).1, (D.flags r i, +fun j => D.cutCounter.serial (D.frozen r i, D.counter r i j))))`. -/ +def remove (u : ℕ) (scale : ℝ) (r : D.format.obj) : (D.cut u scale).format.obj := + (D.scheme.remove r.1 (D.mobile r), fun i => + ((r.2 i).1, (D.flags r i, fun j => D.cutCounter.serial (D.frozen r i, D.counter r i j)))) + +namespace Shows +variable {D} {r : D.format.obj} {Q : LocalTerm F x y D.scheme.h u} (s : D.Shows r Q) + +open scoped Classical in +theorem kept (v : Q.diagram.V) : D.mobile r (s.pres.vertex v).1 = true ↔ ¬ Q.freeze.frozen v := by + rw [s.vertex] + have h := (s.frozen (Q.frame.place v).1).trans (Q.frame.keep v) + simp only [mobile, Bool.not_eq_true', ← h, Bool.eq_false_iff] + +open scoped Classical in +/-- Computes the presentation by the application `s.pres.freeze Q.freeze (D.mobile r) s.kept`. -/ +abbrev presentation := s.pres.freeze Q.freeze (D.mobile r) s.kept +open scoped Classical in +/-- Computes the oriented by the application `s.pres.freeze_directed Q.freeze (D.mobile r) +s.kept s.directed`. -/ +abbrev oriented := s.pres.freeze_directed Q.freeze (D.mobile r) s.kept s.directed +open scoped Classical in +/-- The indexed operation `s.pres.freeze_uniform Q.freeze (D.mobile r) s.kept (fun e => +s.uniform e.val)`. -/ +abbrev sizes := s.pres.freeze_uniform Q.freeze (D.mobile r) s.kept (fun e => s.uniform e.val) +open scoped Classical in +/-- Uses `s.presentation.packets s.oriented s.sizes` as the representation. -/ +abbrev packets := s.presentation.packets s.oriented s.sizes + +open scoped Classical in +/-- The posting of type `D.scheme.cut.Posting (D.scheme.remove r.1 (D.mobile r)) (Q.frame.hostOf +hu L hL s.packets)` for the given inputs. -/ +abbrev posting (hu : 0 < u) (L : Fringe Q.freeze.x Q.freeze.y Q.freeze.Fixed) + (hL : L.tensor = Q.freeze.border.tensor) : + D.scheme.cut.Posting (D.scheme.remove r.1 (D.mobile r)) (Q.frame.hostOf hu L hL s.packets) := + s.pres.freezePosting Q.freeze (D.mobile r) s.kept s.directed (fun e => s.uniform e.val) + Q.frame hu L hL s.host (cellIndex _).toEmbedding s.index s.vertex s.neighbor + +end Shows +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- +# Reading loads and electing a grouping from the encoded host +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F T : Type} (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) +local notation "M" => D.scheme.m +local notation "d" => D.scheme.d +local notation "n" => (D.scheme.h - a) + +open scoped Classical in +/-- The value specified by `cellIndex _ ((splitCell a ha).symm ((cellIndex a).symm u, (cellIndex +_).symm v))`. -/ +def position (u : B a) (v : B n) : B D.scheme.h := + cellIndex _ ((splitCell a ha).symm ((cellIndex a).symm u, (cellIndex _).symm v)) + +open scoped Classical in +/-- Computes the group input by the application `Group.Input M d a n D.count`. -/ +abbrev groupInput := Group.Input M d a n D.count + +open scoped Classical in +/-- Evaluates `(D.nav r i, D.live r i, D.flags r i, fun x y => D.counter r i (D.position a ha x +y))` at the input `i`. -/ +def groups (r : D.format.obj) : (D.groupInput a).obj := + fun i => (D.nav r i, D.live r i, D.flags r i, fun x y => D.counter r i (D.position a ha x y)) + +open scoped Classical in +/-- The quantity computed by `D.load v / ((2 : ℝ) ^ k * b)`. -/ +def relative (k : ℕ) (b : ℝ) (v : B D.count) := D.load v / ((2 : ℝ) ^ k * b) + +variable [Field F] + +open scoped Classical in +theorem groups_circuit : Circuit F D.format (D.groupInput a) (D.groups a ha) + (D.format.width + 2 * (D.groupInput a).width) := by + let f : (D.groupInput a).pins → D.format.pins + | (i, .inl j) => .inl (i, .inl j) + | (i, .inr (.inl j)) => .inr (i, .inl (.inl j)) + | (i, .inr (.inr (.inl j))) => .inr (i, .inr (.inl j)) + | (i, .inr (.inr (.inr (x, y, j)))) => .inr (i, .inr (.inr (D.position a ha x y, j))) + exact Circuit.project f (by rintro _ ⟨_, _ | (_ | (_ | ⟨_, _, _⟩))⟩ <;> rfl) + +variable [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} {r : D.format.obj} + {G : HostNet F L D.scheme.h u} (p : D.Encodes r G) (k : ℕ) (b : ℝ) + +open scoped Classical in +theorem presents : + Group.Presents (D.groups a ha r) p.post.host (D.adj G) G.C + (Packing.relative k b (G.regroup a ha).load) (D.relative k b) := by + refine ⟨p.live, p.closed, p.edge, p.core, ?_⟩ + intro v i j + let q := (splitCell a ha).symm (i, j) + have he : splitAddr G.V a ha (v, q) = ((v, i), j) := by + unfold splitAddr + simp [q] + have hl := G.regroup_load a ha (v, q) + rw [he] at hl + have ht := p.load v q + rw [p.block] at ht + have hh : D.position a ha (cellIndex a i) (cellIndex n j) = cellIndex _ q := by + simp [position, q] + change D.load (D.counter r (p.post.host v) (D.position a ha _ _)) / _ = _ + rw [hh, ht] + exact congrArg (fun a => a / ((2 : ℝ) ^ k * b)) hl.symm + +variable (Δ C : ℕ) +open scoped Classical in +/-- The value specified by `Group.labels Δ C (D.relative k b) (D.groups a ha r)`. -/ +def intervals (r : D.format.obj) := Group.labels Δ C (D.relative k b) (D.groups a ha r) + +open scoped Classical in +theorem grouping (hΔ : 0 < Δ) (hC : 0 < C) (hk : 1 ≤ k) (hn : k ≤ n) (hb : 0 < b) + (hG : G.Bounded Δ C b) (delayed : D.full = false → n ≤ 32 * Nat.clog 2 (2 * C)) : + ∃ g : Grouping (inGroup a G.N) (inGroup a G.C) Δ C k b (G.regroup a ha).load, + ∀ v i, D.intervals a ha k b Δ C r (Group.embed p.post.host a v) (cellIndex n i) = + intervalCode n (g.here v i).2 := by + have hg := G.regroup_bounded a ha hG + have hs : ∀ v w, w ∈ D.adj G v → v ∈ D.adj G w := by + unfold adj + split + · exact G.ns + · exact G.cs + have hc : ∀ v, G.C v ⊆ D.adj G v := by + unfold adj + split + · exact G.sub + · exact fun _ => Finset.Subset.rfl + have hsize : ∀ v, (D.adj G v).card ≤ C := by + unfold adj + split + · exact hG.2.1 + · exact fun v => (Finset.card_le_card (G.sub v)).trans (hG.2.1 v) + obtain ⟨q, hq⟩ := (D.presents a ha p k b).grouping hΔ hC hk hn hb hs G.cs hc hsize hG.1 + (fun v i => ⟨(G.regroup a ha).load_nonneg _ _, hg.2.2 _ _⟩) + refine ⟨{ q with edge := ?_ }, hq⟩ + intro v w hw i + by_cases e : w ∈ inGroup a (D.adj G) v + · exact q.edge v w e i + have hf : D.full = false := Bool.eq_false_iff.mpr (by + intro h + exact e (by simpa only [adj, ite_eq_left h] using hw)) + have e' : w ∉ inGroup a G.C v := by simpa [adj, hf] using e + rw [ite_eq_right e'] + have h := (q.part w _ (q.mem w i)).1 + have hd := delayed hf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- +# Common addresses of child hosts + +In core-only mode the stored neighbor width depends on the core +degree. Delayed noncore contacts are tracked separately. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +variable {F T : Type} (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) (Δ C : ℕ) +local notation "n" => (D.scheme.h - a) +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d + +open scoped Classical in +/-- Returns `C` when `D.full` holds, and `Δ` otherwise. -/ +abbrev bound := if D.full then C else Δ +open scoped Classical in +/-- The quantity computed by `m + (n + 1)`. -/ +abbrev size := m + (n + 1) +open scoped Classical in +/-- The value specified by `Child.nextWidth n (D.bound Δ C) d`. -/ +abbrev degree := Child.nextWidth n (D.bound Δ C) d +open scoped Classical in +/-- The value specified by `Neighborhood.Rows (D.size a) (D.degree a Δ C)`. -/ +abbrev Graph := Neighborhood.Rows (D.size a) (D.degree a Δ C) +open scoped Classical in +/-- Computes the status by the application `Format.vec (D.size a) .bit`. -/ +abbrev Status := Format.vec (D.size a) .bit + +open scoped Classical in +/-- The value specified by `Child.neighbors n (D.bound Δ C) (Child.fromGroup (D.groups a ha r) +false)`. -/ +def childNav (r : D.format.obj) : (D.Graph a Δ C).obj := + Child.neighbors n (D.bound Δ C) (Child.fromGroup (D.groups a ha r) false) + +open scoped Classical in +/-- The value specified by `Child.neighbors n Δ (Child.fromGroup (D.groups a ha r) true)`. -/ +def childCore (r : D.format.obj) := + Child.neighbors n Δ (Child.fromGroup (D.groups a ha r) true) + +open scoped Classical in +/-- The construction uses `Match.rowIndex m (n + 1) j` for its intermediate `t`. -/ +def childLive (r : D.format.obj) (j : B (D.size a)) := + let t := Match.rowIndex m (n + 1) j + D.live r t.1 && decide (t.2 ∈ Set.range (intervalCode n)) + +open scoped Classical in +/-- The quantity computed by `D.frozen r (Match.rowIndex m (n + 1) j).1`. -/ +def childFrozen (r : D.format.obj) (j : B (D.size a)) := + D.frozen r (Match.rowIndex m (n + 1) j).1 + +open scoped Classical in +theorem childSelf (r : D.format.obj) (j : B (D.size a)) : D.childNav a ha Δ C r j 0 = j := + Neighborhood.origin + +variable [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {u : ℕ} {r : D.format.obj} + {G : HostNet F L D.scheme.h u} (p : D.Encodes r G) + +open scoped Classical in +theorem child_live (j : B (D.size a)) : + D.childLive a r j = true ↔ j ∈ Set.range (Child.host p.post.host n) := by + simp only [childLive, Bool.and_eq_true, decide_eq_true_eq, p.live] + constructor + · rintro ⟨⟨v, hv⟩, ⟨t, ht⟩⟩ + refine ⟨(v, t), (Match.rowIndex m (n + 1)).injective ?_⟩ + rw [Child.host_parts] + exact Prod.ext hv ht + · rintro ⟨v, rfl⟩ + rw [Child.host_parts] + exact ⟨⟨_, rfl⟩, ⟨_, rfl⟩⟩ + +open scoped Classical in +theorem child_presents : + Child.Presents (D.adj G) p.post.host (Child.fromGroup (D.groups a ha r) false) := + Child.presents (D.presents a ha p 0 1) false + +open scoped Classical in +theorem core_presents : + Child.Presents G.C p.post.host (Child.fromGroup (D.groups a ha r) true) := + Child.presents (D.presents a ha p 0 1) true + +omit [Field F] in +open scoped Classical in +theorem bound_pos (hd : 0 < Δ) (hc : Δ ≤ C) : 0 < D.bound Δ C := by + unfold bound + split <;> omega + +include p in +open scoped Classical in +theorem child_reciprocal (hd : 0 < Δ) (hc : Δ ≤ C) (A : Format) (f : B (D.size a) → A.obj) : + Fmt.Reciprocal A (fun i => (D.childNav a ha Δ C r i, f i)) := by + refine (D.child_presents a ha p).reciprocal (D.bound_pos Δ C hd hc) ?_ A f + unfold adj + split + · exact G.ns + · exact G.cs + +open scoped Classical in +theorem child_hop (hd : 0 < Δ) (hc : Δ ≤ C) (v w : Site G.V n) + (hw : w ∈ (G.project a ha Δ C hc).C v) : + let nav := D.childNav a ha Δ C r + let H := Child.host p.post.host n + nav (H v) (Child.index nav (H v) (H w)) = H w := by + apply (D.child_presents a ha p).nav (D.bound_pos Δ C hd hc) + by_cases h : D.full = true + · rw [adj, bound, ite_eq_left h, ite_eq_left h] + exact (G.project a ha Δ C hc).sub v hw + · rw [adj, bound, ite_eq_right h, ite_eq_right h] + exact hw + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Cost of the common child address and mask computations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring + +variable {F : Type} [Field F] (D : Template F) (a : ℕ) (ha : a ≤ D.scheme.h) + (Δ C : ℕ) +local notation "n" => (D.scheme.h - a) +local notation "m" => D.scheme.m +local notation "d" => D.scheme.d +local notation "j" => D.size a +local notation "v" => D.degree a Δ C + +open scoped Classical in +/-- The bound obtained by adding the component charges `D.format.width + 3 * (D.groupInput +a).width + 68 * (Child.Input m d).width + 2 ^ j * (100 + (j + 2 ^ degree)) ^ 201`. -/ +def navCost (degree : ℕ) := + D.format.width + 3 * (D.groupInput a).width + 68 * (Child.Input m d).width + + 2 ^ j * (100 + (j + 2 ^ degree)) ^ 201 + +open scoped Classical in +theorem nav_net (core : Bool) (deg : ℕ) : + Circuit F D.format (Neighborhood.Rows j (Child.nextWidth n deg d)) + (fun r => Child.neighbors n deg (Child.fromGroup (D.groups a ha r) core)) + (D.navCost a (Child.nextWidth n deg d)) := by + let prep := (D.groups_circuit a ha).comp (Child.fromGroup_circuit F core) + obtain ⟨k, hk, h⟩ := Child.cheap F m d n deg + refine (prep.comp hk).mono ?_ + change _ + _ + k ≤ 2 ^ j * (100 + (j + 2 ^ Child.nextWidth n deg d)) ^ 201 at h + unfold navCost + change D.format.width + 2 * (D.groupInput a).width + + ((D.groupInput a).width + 68 * (Child.Input m d).width) + k ≤ _ + omega + +open scoped Classical in +/-- The quantity computed by `D.format.width + 34 * (D.Status a).width`. -/ +def statusCost := D.format.width + 34 * (D.Status a).width + +open scoped Classical in +theorem status_net : + Circuit F D.format (D.Status a) (D.childLive a) (D.statusCost a) := by + have h : Install.Depends ((D.Status a).code ∘ D.childLive a ∘ D.format.code.symm) 1 := by + rintro ⟨i, ⟨⟩⟩ + let p := (Match.rowIndex m (n + 1) i).1 + let pin : D.format.pins := .inr (p, .inl (.inl ())) + refine ⟨{pin}, by simp, fun x y he => ?_⟩ + change (x pin && _) = (y pin && _) + rw [he pin (by simp)] + exact h.bnet F + +open scoped Classical in +/-- The quantity computed by `4 * (5 * D.format.width + D.statusCost a + D.navCost a v)`. -/ +def childCost := 4 * (5 * D.format.width + D.statusCost a + D.navCost a v) + +open scoped Classical in +theorem child_map {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) : + Map F u L D.format ((D.Status a).pair (D.Graph a Δ C)) + (fun r => (D.childLive a r, D.childNav a ha Δ C r)) (D.childCost a Δ C) := + Map.circuit hu ((D.status_net a).pair (D.nav_net a ha false (D.bound Δ C))) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Sweep.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Sweep.lean new file mode 100644 index 0000000000..3b8bac216b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Template/Sweep.lean @@ -0,0 +1,933 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.FieldLift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Mixer.Choice +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow + +/-! +# Charging decoded histories to current and retired ports + +Retired internal ports follow the same assignment as tether +endpoints. New core contacts increase the available budget. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +open Finset + +variable {F T : Type} {x y : Wire} {L : Fringe x y T} {h a u z Δ D k : ℕ} + (G : HostNet F L h u) + +open scoped Classical in +/-- The quantity computed by `G.past v + G.tetherLoad v + degree G.pair v * u`. -/ +def footprint (v : G.V × Cell h) := G.past v + G.tetherLoad v + degree G.pair v * u + +open scoped Classical in +theorem regroup_degree (ha : a ≤ h) (v : G.V × Cell h) : + degree (G.regroup a ha).pair (splitAddr G.V a ha v) = degree G.pair v := by + let e := splitAddr G.V a ha + change degree (fun i => Prod.map e e (G.pair i)) (e v) = _ + rw [degree_map] + simp + +open scoped Classical in +theorem regroup_footprint (ha : a ≤ h) (v : G.V × Cell h) : + (G.regroup a ha).footprint (splitAddr G.V a ha v) = G.footprint v := by + let e := splitAddr G.V a ha + have ext : (exterior G.diagram (e ∘ G.units.place) (e v) : ℝ) = G.tetherLoad v := by + rw [exterior_comp] + simp [push, tetherLoad] + unfold footprint + rw [G.regroup_degree] + change G.past (e.symm (e v)) + _ + _ = _ + rw [Equiv.symm_apply_apply, show (G.regroup a ha).tetherLoad _ = _ from Nat.cast_injective ext] + +variable [Fintype T] + +open scoped Classical in +theorem footprint_le (hm : G.mass ≤ L.cap) (v : G.V × Cell h) : + G.footprint v ≤ (2 : ℝ) ^ L.discount * G.load v.1 v.2 := by + have hr := G.rate_le + have hs := mul_nonneg L.pos.le (push_nonneg G.park L.charge L.nonneg v) + have hi := mul_le_of_le_one_left + (show 0 ≤ (G.tetherLoad v : ℝ) + degree G.pair v * (u : ℝ) by positivity) hr + have hv : G.rate * (G.footprint v : ℝ) ≤ G.load v.1 v.2 := by + simp only [load, footprint, Nat.cast_add, Nat.cast_mul] + linarith only [hi, hs] + rw [rate, ite_eq_left hm, one_div_mul_eq_div] at hv + exact ((div_le_iff₀ (by positivity)).mp hv).trans_eq (mul_comm _ _) + +open scoped Classical in +theorem regroup_park (ha : a ≤ h) (v : G.V × Cell h) : + push (G.regroup a ha).park L.charge (splitAddr G.V a ha v) = push G.park L.charge v := by + let e := splitAddr G.V a ha + change push (e ∘ G.park) L.charge (e v) = _ + simp only [push, Function.comp_apply, Equiv.apply_eq_iff_eq] + congr! 2 + +variable [Field F] {B : ℝ} {P : Gadget F} {H : HostNet F L h (P.b * z)} + (s : H.Projection Δ D a) (g : Grouping H.N H.C Δ D k B H.load) + (m : Matching (g.ends H.src H.ix) (g.ends H.dst H.ix) H.ix) + (hz : 0 < z) (hle : Δ ≤ D) (i : g.Choice m P) (v : Site H.V h) + +local notation "Q" => contracted s g m hz hle i +local notation "f" => Function.uncurry (g.route m (g.layout m P i)) + +open scoped Classical in +theorem push_route (l : H.V × Cell h → ℝ) : + push f l v = push (assignment s g m i) l (s.place v) := by + simp only [push, assignment, s.place.injective.eq_iff, Function.uncurry_def] + refine Finset.sum_congr rfl fun w _ => ?_ + split_ifs with h + · exact ite_eq_left h + · exact ite_eq_right h + +open scoped Classical in +theorem park_route : push f (push H.park L.charge) v = push (Q).park L.charge (s.place v) := by + rw [push_route s g m i, push_comp] + rfl + +open scoped Classical in +theorem past_route : + push f (fun t => (H.past t + degree H.pair t * (P.b * z) : ℕ)) v = (Q).past (s.place v) := by + rw [push_route s g m i] + change _ = (H.carried (assignment s g m i) (s.place v) : ℝ) + simp only [carried, Nat.cast_sum, Nat.cast_ite, Nat.cast_zero, push] + +open scoped Classical in +theorem footprint_route : push f (fun t => (H.footprint t : ℝ)) v ≤ (Q).footprint (s.place v) := by + have ext : push f (fun t => (H.tetherLoad t : ℝ)) v = (Q).tetherLoad (s.place v) := by + rw [push_route s g m i] + unfold tetherLoad + erw [← exterior_comp, port_load] + have add : push f (fun t => (H.footprint t : ℝ)) v = + push f (fun t => (H.past t + degree H.pair t * (P.b * z) : ℕ)) v + + push f (fun t => (H.tetherLoad t : ℝ)) v := by + unfold push + rw [← sum_add_distrib] + refine sum_congr rfl fun p _ => ?_ + split_ifs + · simp only [footprint, Nat.cast_add]; exact add_right_comm _ _ _ + · exact (add_zero _).symm + erw [add, ext, past_route s g m hz hle i] + simp only [footprint, Nat.cast_add] + exact le_add_of_nonneg_right (Nat.cast_nonneg (α := ℝ) _) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- # Splitting the recorded charge into core arity and frozen weight -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Shows +open Coloring Packing Rounds +variable {F : Type} [Field F] {x y : Wire} {u : ℕ} + {D : Template F} {r : D.format.obj} {Q : LocalTerm F x y D.scheme.h u} (s : D.Shows r Q) + +open scoped Classical in +/-- Computes the weight by the application `D.load (D.counter r (s.host a.1) (cellIndex _ +a.2))`. -/ +def weight (a : Q.V × Cell D.scheme.h) := + D.load (D.counter r (s.host a.1) (cellIndex _ a.2)) + +open scoped Classical in +theorem weight_eq (a : Q.V × Cell D.scheme.h) : s.weight a = push Q.frame.place Q.charge a := by + rw [weight, s.amount] + unfold push + refine Finset.sum_congr rfl fun v _ => ?_ + rw [s.vertex] + simp only [s.host.injective.eq_iff, (cellIndex _).injective.eq_iff, ← Prod.ext_iff] + congr + +open scoped Classical in +theorem weight_at (v : Q.diagram.V) : s.weight (Q.frame.place v) = Q.charge v := by + rw [weight_eq] + simp [push, Q.one.eq_iff] + +open scoped Classical in +theorem amount_at (v : Q.diagram.V) : + D.load (D.counter r (s.pres.vertex v).1 (s.pres.vertex v).2.1) = Q.charge v := by + rw [s.vertex] + exact s.weight_at v + +open scoped Classical in +theorem occupied (hu : 0 < u) (i : B D.scheme.m) (j : B D.scheme.h) : + 0 < D.load (D.counter r i j) ↔ (i, j, 0) ∈ Set.range s.pres.vertex := by + constructor + · intro h + by_contra hc + have hz : D.load (D.counter r i j) = 0 := by + rw [s.amount] + refine Finset.sum_eq_zero fun v _ => ite_eq_right ?_ + rintro ⟨hi, hj⟩ + exact hc ⟨v, Prod.ext hi (Prod.ext hj (by rw [s.vertex]))⟩ + linarith + · rintro ⟨v, hv⟩ + have := s.amount_at v + rw [hv] at this + rw [this] + exact (Nat.cast_pos.mpr hu).trans_le (Q.floor v) + +open scoped Classical in +private theorem missing {J I : Type} [Fintype J] {f : J → I} {a : I} (l : J → ℝ) + (h : ∀ j, f j ≠ a) : push f l a = 0 := by simp [push, h] + +open scoped Classical in +theorem frozen_weight (a : Q.V × Cell D.scheme.h) : + push (fun t : Q.freeze.Fixed => Q.frame.place t.val) (fun t => Q.charge t.val) a = + if D.frozen r (s.host a.1) then s.weight a else 0 := by + by_cases h : ∃ v, Q.frame.place v = a + · obtain ⟨v, rfl⟩ := h + rw [s.weight_at] + have hv := (s.frozen (Q.frame.place v).1).trans (Q.frame.keep v) + by_cases f : Q.freeze.frozen v + · rw [ite_eq_left (hv.mpr f)] + let w : Q.freeze.Fixed := ⟨v, f⟩ + change push _ _ (Q.frame.place w.val) = Q.charge w.val + simp [push, Q.one.eq_iff, Subtype.val_inj] + · rw [ite_eq_right (mt hv.mp f)] + exact missing _ fun j he => f (Q.one he ▸ j.property) + · have ha v : Q.frame.place v ≠ a := fun he => h ⟨v, he⟩ + rw [s.weight_eq, missing Q.charge ha, ite_self] + exact missing _ fun j => ha j.val + +open scoped Classical in +theorem mobile_weight (a : Q.V × Cell D.scheme.h) : + push (fun t : Q.freeze.Core => Q.frame.place t.val) (fun t => (Q.diagram.arity t.val : ℝ)) a = + if D.frozen r (s.host a.1) then 0 else max 0 (s.weight a - u) := by + by_cases h : ∃ v, Q.frame.place v = a + · obtain ⟨v, rfl⟩ := h + rw [s.weight_at, s.charge, add_sub_cancel_right, max_eq_right (Nat.cast_nonneg _)] + have hv := (s.frozen (Q.frame.place v).1).trans (Q.frame.keep v) + by_cases f : Q.freeze.frozen v + · rw [ite_eq_left (hv.mpr f)] + exact missing _ fun j he => j.property ((Q.one he).symm ▸ f) + · rw [ite_eq_right (mt hv.mp f)] + let w : Q.freeze.Core := ⟨v, f⟩ + change push _ _ (Q.frame.place w.val) = (Q.diagram.arity w.val : ℝ) + simp [push, Q.one.eq_iff, Subtype.val_inj] + · have ha v : Q.frame.place v ≠ a := fun he => h ⟨v, he⟩ + rw [s.weight_eq, missing Q.charge ha, max_eq_left (sub_nonpos.mpr (Nat.cast_nonneg _)), + ite_self] + exact missing _ fun j => ha j.val + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Shows +end + +/- # The core encoded by a cut presentation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Shows +open Coloring Packing Rounds +variable {F : Type} [Field F] {x y : Wire} {u : ℕ} + {D : Template F} {r : D.format.obj} {Q : LocalTerm F x y D.scheme.h u} + (s : D.Shows r Q) (hu : 0 < u) (L : Fringe Q.freeze.x Q.freeze.y Q.freeze.Fixed) + (hL : L.tensor = Q.freeze.border.tensor) (hc : L.charge = fun i => Q.charge i.val) + +local notation "G" => Q.frame.hostOf hu L hL s.packets +local notation "Y" => D.cut u L.scale +local notation "t" => D.remove u L.scale r + +include hc in +open scoped Classical in +theorem park_at (v : Q.V) (i : Cell D.scheme.h) : + (Y).park ((Y).counter t (s.host v) (cellIndex _ i)) = push (G).park L.charge (v, i) := by + have hf := s.frozen_weight (v, i) + rw [← hc] at hf + refine Eq.trans ?_ hf.symm + simp only [weight, Template.counter, Template.cut, Template.remove, Equiv.symm_apply_apply] + +include hc in +open scoped Classical in +theorem load_at (v : Q.V) (i : Cell D.scheme.h) : + (Y).load ((Y).counter t (s.host v) (cellIndex _ i)) = (G).load v i := by + have h := HostNet.load_eq (G) (v, i) + rw [show (G).past (v, i) = 0 from rfl, Nat.cast_zero, mul_zero, add_zero] at h + have hf := s.frozen_weight (v, i) + rw [← hc] at hf + refine Eq.trans ?_ h.symm + change _ = push (fun j : Q.freeze.Core => Q.frame.place j.val) (fun j + => (Q.diagram.arity j.val : ℝ)) (v, i) + + L.scale * push (fun j : Q.freeze.Fixed => Q.frame.place j.val) L.charge (v, i) + rw [s.mobile_weight, hf] + simp only [weight, Template.counter, Template.cut, Template.remove, Equiv.symm_apply_apply] + split <;> simp only [zero_add, mul_zero, add_zero] + +open scoped Classical in +/-- Builds `(Y).Encodes t (G) where post` with the specified `post`, `block`, `live`, `frozen`. -/ +def encode : (Y).Encodes t (G) where + post := s.posting hu L hL + block _ := rfl + live := s.live + frozen := s.frozen + closed := s.closed + reciprocal := s.reciprocal + edge := s.edge + core := s.core + load := s.load_at hu L hL hc + park := s.park_at hu L hL hc + past _ _ := rfl + +open scoped Classical in +theorem span (j : (s.encode hu L hL hc).post.toPresentation.BorderSpan) : + (s.encode hu L hL hc).post.toPresentation.borderWidth j = u := + s.pres.freeze_borderWidth Q.freeze (D.mobile r) s.kept s.uniform j + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Shows +end + +/- # Exterior payload height of a presented board -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents +open Coloring + +variable {F : Type} [Field F] {a b : Wire} {D : Template F} + {r : D.format.obj} {P : Rounds.Board F a b D.scheme.h} (p : D.Presents r P) + +include p in +open scoped Classical in +/-- A host has at most one station in each block. Index an exterior bit +by its block and its ordinal among all ports of that station. -/ +theorem fits {t : ℕ} (bound : ∀ v, P.diagram.arity v ≤ 2 ^ t) : + D.scheme.Fits r.1 (2 ^ D.scheme.m + wd a + wd b) (D.scheme.h + t) := by + refine p.pres.fits le_rfl fun i => ?_ + let e := Equiv.ofBijective p.pres.toSeating.atPin p.pres.toSeating.atPin_bijective + let locate (q : D.scheme.fiber r.1 i) := e.symm q.val.val + have loc (q : D.scheme.fiber r.1 i) : (p.pres.vertex (locate q).1).1 = i := + (congrArg (fun z => z.1.1.1) (e.apply_symm_apply q.val.val)).trans q.property + let rank (v : P.diagram.V) : P.diagram.Port v ↪ B t := + Classical.choice (Function.Embedding.nonempty_of_card_le + (by simpa [Diagram.Port, Diagram.arity] using bound v)) + let encode (q : Σ v, P.diagram.Port v) := ((p.pres.vertex q.1).2.1, rank q.1 q.2) + have eq_of_code (q s : Σ v, P.diagram.Port v) + (he : (p.pres.vertex q.1).1 = (p.pres.vertex s.1).1) (hh : encode q = encode s) : q = s := by + obtain ⟨v, k⟩ := q + obtain ⟨w, l⟩ := s + have hv : v = w := p.pres.vertex.injective (Prod.ext he + (Prod.ext (congrArg (fun z : B D.scheme.h × B t => z.1) hh) (by rw [p.vertex, p.vertex]))) + subst w + exact congrArg (Sigma.mk v) ((rank v).injective (congrArg Prod.snd hh)) + have hinj : Function.Injective (encode ∘ locate) := fun q s h => + Subtype.ext (Subtype.ext (e.symm.injective (eq_of_code _ _ ((loc q).trans (loc s).symm) h))) + simpa [Scheme.load, pow_add] using Fintype.card_le_of_injective _ hinj + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Presents +end + +/- # Encoding arity, parked charge, and accumulated history in one word -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing + +open scoped Classical in +/-- The data for the meter construction, including `count`, `load`, `park`, `past`, `encode`. -/ +structure Meter where + /-- The number of entries. -/ + count : ℕ + /-- The `Meter` component of type `B count → ℝ`. -/ + load : B count → ℝ + /-- The `Meter` component of type `B count → ℝ`. -/ + park : B count → ℝ + /-- The `Meter` component of type `B count → ℕ`. -/ + past : B count → ℕ + /-- The `Meter` component of type `ℕ → ℝ → ℕ → B count`. -/ + encode : ℕ → ℝ → ℕ → B count + +namespace Meter +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} {h u : ℕ} + (M : Meter) (H : HostNet F L h u) + +open scoped Classical in +/-- The quantity computed by `M.encode (H.tetherLoad w + Packing.degree H.pair w * u) (push +H.park L.charge w) (H.past w)`. -/ +def read (w : H.V × Cell h) := + M.encode (H.tetherLoad w + Packing.degree H.pair w * u) (push H.park L.charge w) (H.past w) + +open scoped Classical in +/-- The condition `∀ w, M.load (M.read H w) = H.load w.1 w.2 ∧ M.park (M.read H w) = push H.park +L.charge w ∧ M.past (M.read H w) = H.past w` on the specified data. -/ +def Valid : Prop := + ∀ w, M.load (M.read H w) = H.load w.1 w.2 ∧ + M.park (M.read H w) = push H.park L.charge w ∧ M.past (M.read H w) = H.past w + +end Meter +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Bounded integer counters for arity, parked charge, and history -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Meter +open Coloring Packing + +open scoped Classical in +/-- Indexes the words by the coordinates of `B n × B n × B n`. -/ +abbrev words (n : ℕ) := B n × B n × B n + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def pack (n : ℕ) : words n ≃ B (3 * n) := Fintype.equivOfCardEq (by + simp only [words, Fintype.card_prod, Fintype.card_fin, ← pow_add] + congr 1; omega) + +open scoped Classical in +/-- Returns `⟨x, h⟩` when `h : x < 2 ^ n` holds, and `0` otherwise. -/ +def word (n x : ℕ) : B n := if h : x < 2 ^ n then ⟨x, h⟩ else 0 + +open scoped Classical in +private theorem exact_word {n x : ℕ} (h : x < 2 ^ n) : (word n x).val = x := by simp [word, h] + +open scoped Classical in +/-- Builds `Meter where count` with the specified `count`, `load`, `park`, `past`. -/ +def bounded (n : ℕ) (scale rate : ℝ) : Meter where + count := 3 * n + load i := let w := (pack n).symm i + w.1.val + scale * w.2.1.val + rate * w.2.2.val + park i := ((pack n).symm i).2.1.val + past i := ((pack n).symm i).2.2.val + encode a p c := pack n (word n a, word n ⌊p⌋₊, word n c) + +variable {F T : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} {h u : ℕ} + (G : HostNet F L h u) + +open scoped Classical in +theorem bounded_valid (n : ℕ) (rate : ℝ) (hr : G.rate = rate) + (hi : ∀ v, G.footprint v < 2 ^ n) + (hp : ∀ v, ∃ j : ℕ, j < 2 ^ n ∧ push G.park L.charge v = j) : + (bounded n L.scale rate).Valid G := by + intro v + obtain ⟨j, hj, hp⟩ := hp v + have ha : G.tetherLoad v + Packing.degree G.pair v * u < 2 ^ n := by + have := hi v; unfold HostNet.footprint at this; omega + have hc : G.past v < 2 ^ n := by + have := hi v; unfold HostNet.footprint at this; omega + simp only [read, bounded, hp, Nat.floor_natCast, Equiv.symm_apply_apply, exact_word ha, + exact_word hj, exact_word hc, HostNet.load, hr, Prod.mk.eta, Nat.cast_add, Nat.cast_mul, + and_self] + +open scoped Classical in +theorem parked (n : ℕ) (hl : ∀ v i, G.load v i < L.scale * (2 : ℝ) ^ n) + (charge : ∀ t, ∃ x : ℕ, L.charge t = x) (v : G.V × Cell h) : + ∃ j : ℕ, j < 2 ^ n ∧ push G.park L.charge v = j := by + choose f hf using charge + let j := ∑ t, if G.park t = v then f t else 0 + have hj : push G.park L.charge v = (j : ℝ) := by + simp only [push, j, Nat.cast_sum, Nat.cast_ite, Nat.cast_zero, hf] + refine ⟨j, ?_, hj⟩ + have he : L.scale * j ≤ G.load v.1 v.2 := by + unfold HostNet.load + rw [hj] + exact (le_add_of_nonneg_left (by positivity)).trans + (le_add_of_nonneg_right (mul_nonneg G.rate_nonneg (Nat.cast_nonneg _))) + have hh := lt_of_mul_lt_mul_left (he.trans_lt (hl _ _)) L.pos.le + exact_mod_cast hh + +open scoped Classical in +theorem valid_of_charge (n : ℕ) (B : ℝ) + (mass : G.mass ≤ L.cap) (load : ∀ v i, G.load v i ≤ B) + (scale : B < L.scale * (2 : ℝ) ^ n) (size : (2 : ℝ) ^ L.discount * B < (2 : ℝ) ^ n) + (charge : ∀ t, ∃ x : ℕ, L.charge t = x) : + (bounded n L.scale (1 / (2 : ℝ) ^ L.discount)).Valid G := by + refine bounded_valid G n _ (ite_eq_left mass) ?_ ?_ + · intro v + have hv := (G.footprint_le mass v).trans (mul_le_mul_of_nonneg_left (load v.1 v.2) (by + positivity)) + exact_mod_cast hv.trans_lt size + · exact parked G n (fun v i => (load v i).trans_lt scale) charge + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Meter +end + +/- # Keeping host metadata while withdrawing isolated scalars -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} + +namespace Assembly.Template +variable (T : Template F) + +open scoped Classical in +/-- Uses `{ T with scheme := T.scheme.sweep }` as the representation. -/ +abbrev sweep : Template F := { T with scheme := T.scheme.sweep } + +variable {T} {Z : Type} [Fintype Z] {L : Packing.Fringe x y Z} {u : ℕ} + {r : T.format.obj} {G : Packing.HostNet F L T.scheme.h u} + +open scoped Classical in +/-- Uses `{ e with post := e.post.sweep }` as the representation. -/ +def Encodes.sweep (e : T.Encodes r G) : T.sweep.Encodes r G.sweep := + { e with post := e.post.sweep } + +end Assembly.Template + +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- # Combining short controller records and reading neighboring headers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +variable {F : Type} [Field F] {u m n k : ℕ} {L : Set (Table F)} {A D E : Format} + +theorem Map.pair {f : A.obj → D.obj} {g : A.obj → E.obj} (hu : 3 ≤ u) + (hf : Map F u L A D f m) (hg : Map F u L A E g n) : + Map F u L A (.pair D E) (fun x => (f x, g x)) (20 * A.width + m + n) := by + have h : Circuit F A (.pair A A) (fun x => (x, x)) (5 * A.width) := by + refine (Circuit.project (D := .pair A A) (Sum.elim id id) ?_).mono ?_ + · rintro x (i|i) <;> rfl + · simp only [Format.width_pair]; omega + exact ((Map.circuit hu h).comp (hf.par hg)).mono (by omega) + +theorem Map.project {f : A.obj → D.obj} (hu : 3 ≤ u) (e : D.pins → A.pins) + (he : ∀ x i, D.code (f x) i = A.code x (e i)) : + Map F u L A D f (4 * (A.width + 2 * D.width)) := Map.circuit hu (Circuit.project e he) + +theorem Map.cheap {h b d : ℕ} {f : A.obj → D.obj} (hu : 3 ≤ u) (hf : Cheap F h b A D f d) : + Map F u L A D f (4 * (2 ^ h * (100 + b) ^ d)) := by + obtain ⟨_, ht, hc⟩ := hf + exact Map.circuit hu (ht.mono (by omega)) + +namespace Template + +variable (D : Template F) (k : ℕ) +/-- Computes the depths by the application `Mixing.Num D.scheme.m k`. -/ +abbrev Depths := Mixing.Num D.scheme.m k +/-- Computes the next by the application `Mixing.Matrix D.scheme.m D.scheme.d k`. -/ +abbrev Next := Mixing.Matrix D.scheme.m D.scheme.d k +/-- Computes the network depths by the application `D.format.pair (D.Depths k)`. -/ +abbrev NetworkDepths := D.format.pair (D.Depths k) +/-- The value specified by `(D.Depths k).pair (.vec D.scheme.d (Perm D.scheme.m))`. -/ +abbrev Queries := (D.Depths k).pair (.vec D.scheme.d (Perm D.scheme.m)) + +/-- Evaluates `x.2 (D.nav x.1 i j)` at the input `i j`. -/ +def nearDepth (x : (D.NetworkDepths k).obj) : (D.Next k).obj := + fun i j => x.2 (D.nav x.1 i j) + +/-- The bound obtained by adding the component charges `4 * ((D.NetworkDepths k).width + 2 * +(D.Queries k).width) + 4 * (2 ^ D.scheme.m * (100 + (D.scheme.m + k + 2 ^ D.scheme.d)) ^ +12)`. -/ +def nearCost := 4 * ((D.NetworkDepths k).width + 2 * (D.Queries k).width) + + 4 * (2 ^ D.scheme.m * (100 + (D.scheme.m + k + 2 ^ D.scheme.d)) ^ 12) + +theorem near_net (hu : 3 ≤ u) : + Map F u L (D.NetworkDepths k) (D.Next k) (D.nearDepth k) (D.nearCost k) := by + let X := D.NetworkDepths k + let Y := D.Queries k + let b := D.scheme.m + k + 2 ^ D.scheme.d + have prep : Map F u L X Y (fun x => (x.2, fun i j => D.nav x.1 j i)) (4 * (X.width + + 2 * Y.width)) := by + apply Map.project hu (Sum.elim Sum.inr (fun t => .inl (.inl (t.2.1, .inl (t.1, t.2.2))))) + rintro x (i|i) <;> rfl + have he : 0 < 2 ^ D.scheme.d := by positivity + have hn := Cheap.neighbors F (.addr k) D.scheme.m b D.scheme.d + (by unfold b; omega) (by rw [Format.width_addr]; unfold b; omega) (by unfold b; omega) + exact prep.comp (Map.cheap hu hn) + +end Template +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Formats and costs for computing the mixer and depth records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +open Coloring +variable {F : Type} (T : Template F) (k d : ℕ) +local notation "m" => T.scheme.m +local notation "h" => T.scheme.h +local notation "b" => T.scheme.d + +/-- Computes the sources by the application `Format.vec m (.vec h T.MixSource)`. -/ +abbrev Sources := Format.vec m (.vec h T.MixSource) +/-- Computes the digits by the application `Format.vec h (T.Summand d)`. -/ +abbrev Digits := Format.vec h (T.Summand d) +/-- Computes the split by the application `Format.pair (Mixing.Num h d) (Mixing.Matrix h b +T.CounterBits)`. -/ +abbrev Split := Format.pair (Mixing.Num h d) (Mixing.Matrix h b T.CounterBits) +/-- Computes the stats by the application `Format.vec m (T.Statistics k)`. -/ +abbrev Stats := Format.vec m (T.Statistics k) +/-- Computes the window by the application `Format.pair .bit ((Group.Flags b).pair (.pair (.addr +k) (Mixing.Num b k)))`. -/ +abbrev Window := Format.pair .bit ((Group.Flags b).pair (.pair (.addr k) (Mixing.Num b k))) +/-- Computes the windows by the application `Format.vec m (Window T k)`. -/ +abbrev Windows := Format.vec m (Window T k) +/-- The value specified by `(T.NetworkDepths k).pair (T.Depths k)`. -/ +abbrev Travel := (T.NetworkDepths k).pair (T.Depths k) +/-- Computes the heads by the application `Format.vec T.widthCols (Mixing.Header k)`. -/ +abbrev Heads := Format.vec T.widthCols (Mixing.Header k) +/-- Computes the sides by the application `Format.pair (.vec m (Heads T k)) (Mixing.Matrix m h +T.profileBits)`. -/ +abbrev Sides := Format.pair (.vec m (Heads T k)) (Mixing.Matrix m h T.profileBits) +/-- Computes the first by the application `T.format.pair (Stats T k)`. -/ +abbrev First := T.format.pair (Stats T k) +/-- The value specified by `(First T k).pair (T.Depths k)`. -/ +abbrev Both := (First T k).pair (T.Depths k) + +/-- The quantity computed by `4 * (A.width + 2 * B.width)`. -/ +def project (A B : Format) := 4 * (A.width + 2 * B.width) + +/-- The arity used in the `Mix` construction. -/ +def arity := 3 + T.MixSource.width + (T.Summand d).width + (d + h) + k + + (Window T k).width + (Heads T k).width + T.profileBits + + Mixing.arity T.widthCols h k T.profileBits d + +/-- The local cost used in the `Mix` construction. -/ +def localCost := 2 ^ h * (1 + arity T k d) + project (Digits T d) (Split T d) + + (4 * (2 ^ h * (100 + d) ^ 5) + (1 + arity T k d) + 4 * Mixing.collectCost h b T.CounterBits) + +/-- The quantity computed by `project T.format (Sources T) + 2 ^ m * localCost T k d`. -/ +def tallyCost := project T.format (Sources T) + 2 ^ m * localCost T k d + +/-- The bound obtained by adding the component charges `24 * (Travel T k).width + project +(Travel T k) (T.NetworkDepths k) + T.nearCost k + project ((Travel T k).pair (T.Next k)) +(Windows T k)`. -/ +def gatherCost := 24 * (Travel T k).width + project (Travel T k) (T.NetworkDepths k) + + T.nearCost k + project ((Travel T k).pair (T.Next k)) (Windows T k) + +/-- The bound obtained by adding the component charges `project (T.NetworkDepths k) (T.Depths k) ++ n * (24 * (T.NetworkDepths k).width + gatherCost T k + 2 ^ m * (1 + arity T k d))`. -/ +def waveCost (n : ℕ) := project (T.NetworkDepths k) (T.Depths k) + + n * (24 * (T.NetworkDepths k).width + gatherCost T k + 2 ^ m * (1 + arity T k d)) + +/-- The profile cost used in the `Mix` construction. -/ +def profileCost := 20 * (T.NetworkDepths k).width + + (project (T.NetworkDepths k) (Travel T k) + gatherCost T k + 2 ^ m * (1 + arity T k d)) + + (project (T.NetworkDepths k) (Sources T) + 2 ^ m * (2 ^ h * (1 + arity T k d))) + + project (Sides T k) (T.profileShape k) + +/-- The cost used in the `Mix` construction. -/ +def cost (n : ℕ) := 48 * T.format.width + tallyCost T k d + + 24 * (First T k).width + project (First T k) (T.NetworkDepths k) + waveCost T k d n + + 20 * (Both T k).width + project (Both T k) (T.NetworkDepths k) + profileCost T k d + + Mixing.extractionCost m T.widthCols h k T.profileBits d + Mixing.cost (m + T.widthCols) h k d + + project (Both T k) (Stats T k) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +end + +/- # The short tables used to select a mixer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +open Coloring +variable {F : Type} (T : Template F) (k d : ℕ) +local notation "m" => T.scheme.m +local notation "h" => T.scheme.h +local notation "b" => T.scheme.d + +/-- The data for the params construction, including `a`, `u`, `Δ`, `D`, `Z`. -/ +structure Params where + /-- The left component. -/ + a : ℕ + /-- The `Params` field of type `ℕ`. -/ + u : ℕ + /-- The `Params` field of type `ℕ`. -/ + Δ : ℕ + /-- The `Params` field of type `ℕ`. -/ + D : ℕ + /-- The `Params` field of type `ℕ`. -/ + Z : ℕ + /-- The `Params` field of type `ℕ`. -/ + g : ℕ + /-- The `Params` field of type `ℝ`. -/ + W : ℝ + +variable (C : Params) + +/-- The indexed operation `Fin.ofNat _ (Mixing.update C.Δ C.D z.2.1 z.2.2.1.val (fun j => +(z.2.2.2 j).val))`. -/ +def step (z : (Window T k).obj) : B k := + Fin.ofNat _ (Mixing.update C.Δ C.D z.2.1 z.2.2.1.val (fun j => (z.2.2.2 j).val)) + +/-- Uses `T.heads z.1 z.2.2.1 z.2.2.2` as the representation. -/ +def heads (z : (Window T k).obj) : (Heads T k).obj := T.heads z.1 z.2.2.1 z.2.2.2 + +/-- The value specified by `(Match.rowIndex _ _).symm z`. -/ +def pack (z : T.MixSource.obj) : B T.profileBits := (Match.rowIndex _ _).symm z + +variable [Field F] + +open scoped Classical in +/-- Computes the election by the application `Mixing.rowKeys C.g (T.getLoad C.u C.Z d) F h k`. -/ +abbrev election := Mixing.rowKeys C.g (T.getLoad C.u C.Z d) F h k + +open scoped Classical in +/-- The keys used in the `Mix` construction. -/ +def keys := + insert (Mixing.graph F T.MixSource (T.Summand d) (T.summand C.Z d)) + (insert (Mixing.graph F (.addr (d + h)) (.addr k) (request C.a C.Z k C.W)) + (insert (Mixing.graph F (Window T k) (.addr k) (step T k C)) + (insert (Mixing.graph F (Window T k) (Heads T k) (heads T k)) + (insert (Mixing.graph F T.MixSource (.addr T.profileBits) (pack T)) + (election T k d C))))) + +open scoped Classical in +theorem few : (keys T k d C).card ≤ 12 := by + unfold keys + iterate 5 + apply (Finset.card_insert_le _ _).trans + apply Nat.add_le_add_right + exact Mixing.rowKeys_size .. + +open scoped Classical in +theorem narrow {v : Table F} (hv : v ∈ keys T k d C) : + wd v.1 + wd v.2.1 ≤ arity T k d := by + unfold arity + simp only [keys, Finset.mem_insert] at hv + rcases hv with rfl | rfl | rfl | rfl | rfl | hv + · simp only [Mixing.graph, lookup, wd_word]; omega + · simp only [Mixing.graph, lookup, wd_word, Format.width_addr]; omega + · simp only [Mixing.graph, lookup, wd_word, Format.width_addr]; omega + · simp only [Mixing.graph, lookup, wd_word]; omega + · simp only [Mixing.graph, lookup, wd_word, Format.width_addr]; omega + · exact (Mixing.rowKeys_arity _ _ hv).trans (Nat.le_add_left ..) + +variable {u : ℕ} {L : Set (Table F)} (ha : arity T k d ≤ u) (hl : (keys T k d C : Set _) ⊆ L) + +omit [Field F] in +include ha in +open scoped Classical in +theorem three : 3 ≤ u := by unfold arity at ha; omega + +include ha hl in +open scoped Classical in +theorem gate (A D : Format) (f : A.obj → D.obj) (hf : Mixing.graph F A D f ∈ keys T k d C) : + Map F u L A D f (1 + arity T k d) := by + have hb : A.width + D.width ≤ arity T k d := by + simpa only [Mixing.graph, lookup, wd_word] using narrow T k d C hf + exact (Mixing.gate (hb.trans ha) (hl hf)).mono (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +end + +/- # Summing the scaled load and contact counts at each host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +open Coloring +variable {F : Type} (T : Template F) (k d : ℕ) +local notation "m" => T.scheme.m +local notation "h" => T.scheme.h +local notation "b" => T.scheme.d +variable [Field F] (C : Params) {u : ℕ} {L : Set (Table F)} + (ha : arity T k d ≤ u) (hl : (keys T k d C : Set _) ⊆ L) + +open scoped Classical in +/-- In the case `(i, j, .inl x)`, this construction gives `.inl (i, .inr (j, x))`. -/ +def readSource : (Sources T).pins → T.format.pins + | (i, j, .inl x) => .inl (i, .inr (j, x)) + | (i, j, .inr x) => .inr (i, .inr (.inr (j, x))) + +omit [Field F] in +open scoped Classical in +theorem source_read (r : T.format.obj) (i : (Sources T).pins) : + (Sources T).code (T.source r) i = T.format.code r (readSource T i) := by + rcases i with ⟨i, j, x|x⟩ <;> rfl + +include ha hl in +open scoped Classical in +private theorem summary_net : + Map F u L (.vec h T.MixSource) (T.Statistics k) (T.summary C.a C.Z k d C.W) + (localCost T k d) := by + have hu := three T k d ha + have h₁ := gate T k d C ha hl T.MixSource (T.Summand d) (T.summand C.Z d) + (Finset.mem_insert_self ..) + have h₂ := gate T k d C ha hl (.addr (d + h)) (.addr k) (request C.a C.Z k C.W) + (Finset.mem_insert_of_mem (Finset.mem_insert_self ..)) + have split : Map F u L (Digits T d) (Split T d) (fun q => (fun j => (q j).1, fun j => (q j).2)) + (project (Digits T d) (Split T d)) := by + refine Map.project hu (Sum.elim (fun p => (p.1, .inl p.2)) (fun p => (p.1, .inr p.2))) ?_ + rintro q (i|i) <;> rfl + have h₃ := (Map.cheap (L:=L) hu (cheap_total F h d)).comp h₂ + have h₄ := Map.circuit (L:=L) hu (Mixing.collect_net F h b T.CounterBits) + exact ((Map.vec (t:=h) _ (fun _ => h₁)).comp split).comp (h₃.par h₄) + +open scoped Classical in +/-- Evaluates `(T.startDepth C.a C.Z k d C.W r v, T.unitCount r v)` at the input `v`. -/ +def tally (r : T.format.obj) : (Stats T k).obj := fun v => + (T.startDepth C.a C.Z k d C.W r v, T.unitCount r v) + +include ha hl in +open scoped Classical in +theorem tally_net : Map F u L T.format (Stats T k) (tally T k d C) (tallyCost T k d) := by + have prep := Map.project (L:=L) (three T k d ha) (readSource T) (source_read T) + exact prep.comp (Map.vec _ (fun _ => summary_net T k d C ha hl)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +end + +/- # Propagating the base depths through the host graph -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +open Coloring +variable {F : Type} (T : Template F) (k d : ℕ) +local notation "m" => T.scheme.m +local notation "h" => T.scheme.h +local notation "b" => T.scheme.d +variable [Field F] (C : Params) {u : ℕ} {L : Set (Table F)} + (ha : arity T k d ≤ u) (hl : (keys T k d C : Set _) ⊆ L) + +open scoped Classical in +/-- Evaluates `(T.live x.1.1 v, T.flags x.1.1 v, x.1.2 v, x.2 ∘ T.nav x.1.1 v)` at the input +`v`. -/ +def gather (x : (Travel T k).obj) : (Windows T k).obj := + fun v => (T.live x.1.1 v, T.flags x.1.1 v, x.1.2 v, x.2 ∘ T.nav x.1.1 v) + +open scoped Classical in +theorem gather_net (hu : 3 ≤ u) : Map F u L (Travel T k) (Windows T k) (gather T k) + (gatherCost T k) := by + let A := Travel T k + let B := T.NetworkDepths k + let D := A.pair (T.Next k) + have pick : Map F u L A B (fun x => (x.1.1, x.2)) (project A B) := by + apply Map.project hu (Sum.elim (fun i => .inl (.inl i)) Sum.inr) + rintro x (i|i) <;> rfl + let f (x : D.obj) (v : Coloring.B m) := (T.live x.1.1.1 v, T.flags x.1.1.1 v, x.1.1.2 v, x.2 v) + have last : Map F u L D (Windows T k) f (project D (Windows T k)) := by + let j : (Windows T k).pins → D.pins + | (v, .inl i) => .inl (.inl (.inl (.inr (v, .inl (.inl i))))) + | (v, .inr (.inl i)) => .inl (.inl (.inl (.inr (v, .inr (.inl i))))) + | (v, .inr (.inr (.inl i))) => .inl (.inl (.inr (v, i))) + | (v, .inr (.inr (.inr i))) => .inr (v, i) + apply Map.project hu j + rintro x ⟨v, i|i|i|i⟩ <;> rfl + have mid := (Map.circuit hu (Circuit.id F A)).pair hu (pick.comp (T.near_net k hu)) + exact (mid.comp last).mono (by unfold gatherCost; dsimp only [A, B, D]; omega) + +open scoped Classical in +/-- The value specified by `Mixing.wave C.Δ C.D (T.nav x.1) (T.flags x.1) x.2 n`. -/ +def wave (n : ℕ) (x : (T.NetworkDepths k).obj) := + Mixing.wave C.Δ C.D (T.nav x.1) (T.flags x.1) x.2 n + +include ha hl in +open scoped Classical in +theorem wave_net (n : ℕ) : Map F u L (T.NetworkDepths k) (T.Depths k) (wave T k C n) + (waveCost T k d n) := by + have hu := three T k d ha + induction n with + | zero => + rw [waveCost, zero_mul, add_zero] + exact Map.project hu Sum.inr (fun _ _ => rfl) + | succ n ih => + have g := gate T k d C ha hl (Window T k) (.addr k) (step T k C) (by simp [keys]) + have upd := (gather_net T k hu).comp (Map.vec (t:=m) _ (fun _ => g)) + have data := (Map.circuit hu (Circuit.id F (T.NetworkDepths k))).pair hu ih + exact (data.comp upd).mono (by unfold waveCost; rw [Nat.succ_mul n]; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +end + +/- # Preparing the matrix of rows used by the mixer election -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +open Coloring +variable {F : Type} (T : Template F) (k d : ℕ) +local notation "m" => T.scheme.m +local notation "h" => T.scheme.h +local notation "b" => T.scheme.d +variable [Field F] (C : Params) {u : ℕ} {L : Set (Table F)} + (ha : arity T k d ≤ u) (hl : (keys T k d C : Set _) ⊆ L) + +include ha hl in +open scoped Classical in +theorem profile_net : Map F u L (T.NetworkDepths k) (T.profileShape k) (fun x => T.profile x.1 x.2) + (profileCost T k d) := by + have hu := three T k d ha + let A := T.NetworkDepths k + have dup : Map F u L A (Travel T k) (fun x => (x, x.2)) (project A (Travel T k)) := by + apply Map.project hu (Sum.elim id Sum.inr) + rintro x (j|j) <;> rfl + have head := gate T k d C ha hl (Window T k) (Heads T k) (heads T k) (by simp [keys]) + have first := (dup.comp (gather_net T k hu)).comp (Map.vec (t:=m) _ (fun _ => head)) + have data : Map F u L A (Sources T) (fun x => T.source x.1) (project A (Sources T)) := + Map.project hu (Sum.inl ∘ readSource T) (fun x i => source_read T x.1 i) + have encode := gate T k d C ha hl T.MixSource (.addr T.profileBits) (pack T) (by simp [keys]) + have second := data.comp (Map.vec (t:=m) _ (fun _ => Map.vec (t:=h) _ (fun _ => encode))) + have zip : Map F u L (Sides T k) (T.profileShape k) (fun x v => (x.1 v, x.2 v)) + (project (Sides T k) (T.profileShape k)) := by + apply Map.project (A:=Sides T k) hu (fun p : (T.profileShape k).pins => p.2.elim (fun i + => .inl (p.1, i)) (fun i => .inr (p.1, i))) + rintro x ⟨v, i|i⟩ <;> rfl + exact (Map.pair hu first second).comp zip + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +end + +/- # Joint circuit for the elected mixer, final depths and contact totals -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +open Coloring +variable {F : Type} (T : Template F) (k d : ℕ) +local notation "m" => T.scheme.m +local notation "h" => T.scheme.h +local notation "b" => T.scheme.d +variable [Field F] (C : Params) {u : ℕ} {L : Set (Table F)} + (ha : arity T k d ≤ u) (hl : (keys T k d C : Set _) ⊆ L) + +open scoped Classical in +/-- The indexed operation `(r, T.mixerChoice C.a t C.Δ C.D C.u C.g C.Z k d hk C.W r, fun v => +(T.baseDepth C.a t C.Δ C.D C.Z k d C.W r v, T.unitCount r v))`. -/ +def prepare (t : ℕ) (hk : h < 2 ^ k) (r : T.format.obj) : (History.Reset.Tile.pair T k).obj := + (r, T.mixerChoice C.a t C.Δ C.D C.u C.g C.Z k d hk C.W r, + fun v => (T.baseDepth C.a t C.Δ C.D C.Z k d C.W r v, T.unitCount r v)) + +include ha hl in +open scoped Classical in +theorem prepare_net (t : ℕ) (hk : h < 2 ^ k) : + Map F u L T.format (History.Reset.Tile.pair T k) (prepare T k d C t hk) (cost T k d (h - t - + C.a)) := by + have hu := three T k d ha + let A := First T k + let D := Both T k + let Y := T.NetworkDepths k + have start : Map F u L A Y (fun x => (x.1, fun v => (x.2 v).1)) (project A Y) := by + apply Map.project hu (Sum.map id (fun p => (p.1, .inl p.2))) + rintro q (i|⟨i, j⟩) <;> rfl + have select : Map F u L D Y (fun x => (x.1.1, x.2)) (project D Y) := by + apply Map.project hu (Sum.map Sum.inl id) + rintro q (i|i) <;> rfl + have stats : Map F u L D (Stats T k) (fun x v => (x.2 v, (x.1.2 v).2)) (project D (Stats T k)) + := by + apply Map.project (A:=D) hu (fun p : (Stats T k).pins => p.2.elim (fun i => .inr (p.1, + i)) (fun i => .inl (.inr (p.1, .inr i)))) + rintro q ⟨i, j|j⟩ <;> rfl + have input := Map.circuit (L:=L) hu (Circuit.id F T.format) + have sums := Map.pair hu input (tally_net T k d C ha hl) + have run := start.comp (wave_net T k d C ha hl (h - t - C.a)) + have mid := sums.comp (Map.pair hu (Map.circuit hu (Circuit.id F A)) run) + have prof := select.comp (profile_net T k d C ha hl) + have keys' : (election T k d C : Set (Table F)) ⊆ L := by + intro i hi + apply hl + iterate 5 apply Finset.mem_insert_of_mem + exact hi + have win := Mixing.elect_records («m»:=m) C.g (T.getLoad C.u C.Z d) hk + ((Nat.le_add_left ..).trans ha) keys' + have elect := mid.comp (Map.pair hu (prof.comp win) stats) + exact (Map.pair hu input elect).mono (by unfold cost; dsimp only [A, D, Y, First, Both]; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/ContractRates.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/ContractRates.lean new file mode 100644 index 0000000000..1c9a86e2f6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/ContractRates.lean @@ -0,0 +1,1042 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.DictionaryHeaders +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.BoardPush +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Shipment.Bound + +/-! +# Pairing the two contacts of a terminal wire + +One extra bit distinguishes self from a numbered neighbor. +Positions naming their own host, including unused positions, +are fixed individually. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring + +open scoped Classical in +/-- Embeds `Option (B d)` into `B (d + 1)`. -/ +def hop {d : ℕ} : Option (B d) ↪ B (d + 1) := + (⟨fun i => i.elim (0, 0) (fun j => (j, 1)), by + rintro (_|i) (_|j) h + · rfl + · exact ((by decide : (0 : B 1) ≠ 1) (congrArg Prod.snd h)).elim + · exact ((by decide : (1 : B 1) ≠ 0) (congrArg Prod.snd h)).elim + · exact congrArg some (Prod.mk.inj h).1⟩ : Option (B d) ↪ B d × B 1).trans + (Match.rowIndex d 1).symm.toEmbedding + +open scoped Classical in +/-- The indexed operation `(Format.addr (d + 1)).code.symm fun i => decide (∃ j, p j = true ∧ +(Format.addr (d + 1)).code (hop (some j)) i = true)`. -/ +def reverseHop (d : ℕ) (p : B d → Bool) : B (d + 1) := + (Format.addr (d + 1)).code.symm fun i => + decide (∃ j, p j = true ∧ (Format.addr (d + 1)).code (hop (some j)) i = true) + +open scoped Classical in +private theorem reverse_of_unique {d : ℕ} {p : B d → Bool} (j : B d) + (h : ∀ k, p k = true ↔ k = j) : reverseHop d p = hop (some j) := by + unfold reverseHop + apply (Format.addr (d + 1)).code.symm_apply_eq.mpr + funext i + simp [h] + +variable {F : Type} (S : Scheme F) (r : S.format.obj) +local notation "idx" => Match.rowIndex S.m (S.d + 1) + +open scoped Classical in +/-- Computes the flags by the application `Format.vec S.m (.vec S.d .bit)`. -/ +abbrev Flags := Format.vec S.m (.vec S.d .bit) +open scoped Classical in +/-- Evaluates `decide ((r i).1 j = i)` at the input `i j`. -/ +def flags : (Flags S).obj := fun i j => decide ((r i).1 j = i) +open scoped Classical in +/-- The value specified by `(idx).symm (v, hop i)`. -/ +abbrev contact (v : B S.m) (i : Option (B S.d)) := (idx).symm (v, hop i) + +open scoped Classical in +/-- The construction uses `Match.rowIndex S.d 1 i` for its intermediate `j`. -/ +def extended (v : B S.m) (i : B (S.d + 1)) := + let j := Match.rowIndex S.d 1 i + if j.2 = 1 then (r v).1 j.1 else v + +open scoped Classical in +theorem extended_self (v : B S.m) : extended S r v (hop none) = v := by + change extended S r v ((Match.rowIndex _ _).symm (0, 0)) = v + simp [extended] + +open scoped Classical in +theorem extended_peer (v : B S.m) (j : B S.d) : extended S r v (hop (some j)) = (r v).1 j := by + change extended S r v ((Match.rowIndex _ _).symm (j, 1)) = _ + simp only [extended, Equiv.apply_symm_apply, ite_true] + +open scoped Classical in +/-- The construction uses `idx i` for its intermediate `x`. -/ +def perm (i : B (S.m + (S.d + 1))) := + let x := idx i + let y := extended S r x.1 x.2 + (idx).symm (y, if y = x.1 then x.2 else reverseHop S.d (fun j => decide ((r y).1 j = x.1))) + +open scoped Classical in +theorem perm_self (v : B S.m) : perm S r (contact S v none) = contact S v none := by + simp only [perm, contact, Equiv.apply_symm_apply, extended_self, ite_true] + +variable (hr : Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) r) +include hr + +open scoped Classical in +theorem perm_link (v w : B S.m) (i j : B S.d) (h : v ≠ w) (hv : (r v).1 i = w) (hw : (r w).1 j + = v) : + perm S r (contact S v (some i)) = contact S w (some j) := by + have he := hr v i (hv.trans_ne h.symm) + rw [hv] at he + have eq : reverseHop S.d (fun l => decide ((r w).1 l = v)) = hop (some j) := by + apply reverse_of_unique + intro k + rw [decide_eq_true_eq] + exact ⟨fun h => he.unique h hw, fun h => h ▸ hw⟩ + simp only [perm, contact, Equiv.apply_symm_apply, extended_peer, hv, ite_eq_right h.symm, eq] + +open scoped Classical in +theorem perm_involutive : Function.Involutive (perm S r) := by + intro i + obtain ⟨⟨v, j⟩, rfl⟩ := (idx).symm.surjective i + by_cases he : extended S r v j = v + · have hh : perm S r ((idx).symm (v, j)) = (idx).symm (v, j) := by + simp only [perm, Equiv.apply_symm_apply, he, ite_true] + rw [hh, hh] + let a := Match.rowIndex S.d 1 j + have ht : a.2 = 1 := by + by_contra hn + exact he (ite_eq_right hn) + have hj : j = hop (some a.1) := (Match.rowIndex S.d 1).eq_symm_apply.mpr (Prod.ext rfl ht) + rw [hj, extended_peer] at he + obtain ⟨k, hk, _⟩ := hr v a.1 he + rw [hj] + change perm S r (perm S r (contact S v (some a.1))) = _ + rw [perm_link S r hr _ _ _ k (Ne.symm he) rfl hk, perm_link S r hr _ _ _ _ he hk rfl] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- # A reverse address from simultaneous neighbor flags -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring Install + +open scoped Classical in +private theorem any_net (F : Type) [Field F] (d : ℕ) : + Circuit F (.vec d .bit) .bit (fun x => decide (∃ i, x i = true)) (2 * 2 ^ d + 1) := by + have h := (BNet.any F (B d)).rename (Equiv.prodUnique (B d) Unit).symm (.refl _) + rw [Fintype.card_fin] at h + unfold Circuit + convert h using 1 + funext x u + change decide (∃ i, x (i, ()) = true) = _ + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply, decide_eq_true_eq] + rfl + +open scoped Classical in +theorem reverseNet (F : Type) [Field F] (d : ℕ) : + Circuit F (.vec d .bit) (.addr (d + 1)) (reverseHop d) (100 * (2 ^ d) ^ 2) := by + let X := Format.vec d .bit + let Y := Format.vec d X + let A := Format.addr (d + 1) + have hd : d + 1 ≤ 2 ^ d := Nat.lt_two_pow_self + let e : A.pins ↪ B d := (Fintype.equivFin A.pins).toEmbedding.trans + (Fin.castLEEmb ((Format.width_addr _).le.trans hd)) + let mask (i j : B d) := Function.extend e (A.code (hop (some j))) (fun _ => false) i + let send (x : X.obj) : Y.obj := fun i j => x j && mask i j + let take (x : X.obj) : A.obj := A.code.symm (fun i => x (e i)) + have hs : Depends (Y.code ∘ send ∘ X.code.symm) 1 := by + rintro ⟨i, j, t⟩ + exact ⟨{(j, ())}, by simp, fun _ _ h => congrArg (· && mask i j) (h (j, ()) (by simp))⟩ + have hr : Circuit F X A take (X.width + 2 * A.width) := + Circuit.project (fun i => (e i, ())) (fun x i => congrFun (A.code.apply_symm_apply _) i) + let row (x : X.obj) := decide (∃ j, x j = true) + have ho : Circuit F Y X (fun x i => row (x i)) (2 ^ d * (2 * 2 ^ d + 1)) := + Circuit.map _ (fun _ => any_net F d) + have hm : Circuit F X Y send (X.width + 34 * Y.width) := hs.bnet F + have eqn : take ∘ (fun x i => row (x i)) ∘ send = reverseHop d := by + funext x + apply congrArg A.code.symm + funext i + apply Bool.eq_iff_iff.mpr + simp [row, send, mask, e.injective.extend_apply, A] + rw [← eqn] + refine ((hm.comp ho).comp hr).mono ?_ + simp only [X, Y, A, Format.width_vec] + rw [Format.width_bit, Format.width_addr, mul_one] + have hp : 1 ≤ 2 ^ d := Nat.two_pow_pos d + nlinarith + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- +# Testing one proposed transfer + +Both banks may contain arbitrary bits. Retain the exact indicator +on all inputs, including malformed local control records. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring Rounds.Contraction + +variable {F : Type} [Field F] (W : Prices F) +variable {m k k' V V' p w n : ℕ} +local notation "Z" => Fmt.payload m V k +local notation "X" => Fmt.payload m V' k' +local notation "C" => PeerLayout.S m V k m V' k' (2 ^ p) +local notation "U" => Payload.Script m m p w n + +open scoped Classical in +/-- The value specified by `(C).kernel F (Payload.Script.decode le_rfl z.1, z.2) x`. -/ +def checker (z : ((U).pair Z).obj) (x : (X).obj) : F := + (C).kernel F (Payload.Script.decode le_rfl z.1, z.2) x + +open scoped Classical in +theorem checker_net {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) (hm : 1 ≤ m) + (ht : 2 ^ p * ((max k k' + 1) * (2 ^ m + 2 ^ m)) < 2 ^ W.w) : + Kernel F u L ((U).pair Z) X checker (W.shipment (Z).width m V k m V' k' p w n) := by + let v := (Payload.Script.item w p n).width + W.w ^ W.power + have hm' : m ≤ W.w := ((Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp + (((Nat.le_add_left _ _).trans ((Nat.le_mul_of_pos_left _ (Nat.succ_pos _)).trans + (Nat.le_mul_of_pos_left _ (Nat.two_pow_pos _)))).trans_lt ht)).le + obtain ⟨a, ha, tag⟩ := W.tag m v hm hm' (Nat.le_add_left ..) + have decode := Payload.Script.decode_net (L := L) (V := V) (k := k) (V' := V') (k' := k') + (w := w) (n := n) hu (le_rfl : 2 ^ p ≤ 2 ^ p) tag tag (Nat.le_add_right _ _) + have kernel : Kernel F u L ((C).control.pair Z) X ((C).kernel F) + (W.transferCost m V k m V' k' p) := by + have h := payload_kernel (K := F) (L := L) m V k m V' k' (2 ^ p) hu ht W.tag + simp only [payloadChannels] at h + unfold PeerLayout.S PeerLayout.P Prices.transferCost + exact h + have go := (decode.par (Map.circuit (L := L) hu (Circuit.id F Z))).then_kernel kernel + have hb : Payload.Script.cost m k m k' p w v a a ≤ + Payload.Script.cost m k m k' p w v (W.W * (2 ^ m * v)) (W.W * (2 ^ m * v)) := by + unfold Payload.Script.cost; gcongr + refine go.mono ?_ + rw [add_comm _ (4 * (Z).width)] + exact Nat.add_le_add_right (Nat.add_le_add_left (Nat.add_le_add_right hb _) _) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- # Closing the two checks and the station dictionary on a common tape -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring Rounds.Contraction + +variable {F : Type} [Field F] (S : Scheme F) + +open scoped Classical in +/-- The value specified by `((Payload.Script S.m S.m p w n).pair (Payload.Script S.m S.m 0 w +n)).pair (Dictionary.headers S V t)`. -/ +abbrev instruction (V t p w n : ℕ) := + ((Payload.Script S.m S.m p w n).pair (Payload.Script S.m S.m 0 w n)).pair (Dictionary.headers S V + t) + +open scoped Classical in +/-- The construction uses `height S t` for its intermediate `k`. -/ +def price (W : Prices F) (S : Scheme F) (V t V' k' p w n : ℕ) := + let k := height S t + let a := (Fmt.payload S.m V k).width + W.shipment a S.m V k S.m V k p w n + W.shipment a S.m V k S.m V' k' 0 w n + + Dictionary.price S V t + 64 * ((instruction S V t p w n).width + (Fmt.payload S.m V' k').width + + a) + +variable (V t V' k' p w n : ℕ) +local notation "J" => instruction S V t p w n +local notation "E" => Fmt.payload S.m V' k' +local notation "Z" => Fmt.payload S.m V (height S t) + +open scoped Classical in +/-- The value specified by `∑ z : Tape S V t, checker (F := F) (x.1.1, z) z * checker (F := F) +(x.1.2, z) y * Dictionary.weight S V t x.2 z`. -/ +def value (x : (J).obj) (y : (E).obj) := + ∑ z : Tape S V t, checker (F := F) (x.1.1, z) z * checker (F := F) (x.1.2, z) y * + Dictionary.weight S V t x.2 z + +open scoped Classical in +theorem evaluate (W : Prices F) {u : ℕ} {L : Set (Table F)} + (hu : 3 ≤ u) (hm : 1 ≤ S.m) + (ht : 2 ^ p * ((max (height S t) k' + 1) * (2 ^ S.m + 2 ^ S.m)) < 2 ^ W.w) + (size : Dictionary.arity S t ≤ u) (label : Dictionary.label S t ∈ L) : + Kernel F u L ((J).pair E) (.wire .unit) + (fun z _ => value S V t V' k' p w n z.1 z.2) (price W S V t V' k' p w n) := by + let k := height S t + have hc : 2 ^ p * ((max k k + 1) * (2 ^ S.m + 2 ^ S.m)) < 2 ^ W.w := by + refine lt_of_le_of_lt ?_ ht + rw [max_self] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ (Nat.succ_le_succ (le_max_left ..))) + have hd : 2 ^ 0 * ((max k k' + 1) * (2 ^ S.m + 2 ^ S.m)) < 2 ^ W.w := + lt_of_le_of_lt (Nat.mul_le_mul_right _ (Nat.two_pow_pos _)) ht + have left := checker_net (V := V) (V' := V) (w := w) (n := n) (L := L) W hu hm hc + have right := checker_net (V := V) (V' := V') (w := w) (n := n) (L := L) W hu hm hd + have station := Dictionary.realize (V := V) hu size label + have h := Kernel.contract hu left right station + unfold price + dsimp only + rw [Format.width_pair, Format.width_pair] + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- # Computing the complete dictionary header vector from the original control rows -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Header + +open Coloring Dictionary +variable {F : Type} [Field F] (S : Scheme F) (V t : ℕ) + +open scoped Classical in +/-- The quantity computed by `(key S).width + (header S).width`. -/ +def arity := (key S).width + (header S).width +open scoped Classical in +/-- The value specified by `lookup F A B (fun x y => if f x = y then 1 else 0)`. -/ +def mapLabel (A B : Format) (f : A.obj → B.obj) := + lookup F A B (fun x y => if f x = y then 1 else 0) + +open scoped Classical in +/-- The value specified by `mapLabel (F:=F) (key S) (header S) (select S)`. -/ +def label := mapLabel (F:=F) (key S) (header S) (select S) + +open scoped Classical in +/-- Computes the names by the application `Format.vec S.m (.vec (n S) (key S))`. -/ +abbrev names := Format.vec S.m (.vec (n S) (key S)) +open scoped Classical in +/-- Computes the lines by the application `Format.vec S.m (line S)`. -/ +abbrev lines := Format.vec S.m (line S) +open scoped Classical in +/-- The bound obtained by adding the component charges `4 * (S.format.width + 34 * (names +S).width) + 2 ^ S.m * (2 ^ (n S) * (1 + (key S).width + (header S).width))`. -/ +def rowCost := 4 * (S.format.width + 34 * (names S).width) + + 2 ^ S.m * (2 ^ (n S) * (1 + (key S).width + (header S).width)) + +variable {S V t} {u v c : ℕ} {L : Set (Table F)} + +open scoped Classical in +theorem rows_net (hu : 3 ≤ u) (ha : arity S ≤ u) (hl : label S ∈ L) : + Map F u L S.format (lines S) (row S) (rowCost S) := by + have a : Circuit F S.format (names S) (labels S) (S.format.width + 34 * (names S).width) := by + apply Window.Tile.project_const + rintro ⟨i, j, k|k⟩ + · exact .inl ⟨(i, .inr ((Match.rowIndex S.h S.k j).1, k)), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr S.k).code (Match.rowIndex S.h S.k j).2 k, fun _ => rfl⟩ + have b : Map F u L (key S) (header S) (select S) (1 + (key S).width + (header S).width) := + Kernel.lookup ha hl + exact (Map.circuit hu a).comp (Map.vec _ fun _ : B S.m => Map.vec _ fun _ : B (n S) => b) + +open scoped Classical in +private theorem unary {A : Format} {δ : ℕ} (hw : A.width ≤ δ) (f : Bool → A.obj) : + Cheap F 0 δ .bit A f 2 := by + have dep : Install.Depends (A.code ∘ f ∘ Format.bit.code.symm) 1 := by + intro i + refine ⟨Finset.univ, le_rfl, fun x y he => ?_⟩ + rw [funext (fun j => he j (Finset.mem_univ _))] + refine ⟨_, dep.bnet F, ?_⟩ + change 1 + A.width + (1 + 34 * A.width) ≤ _ + ring_nf + omega + +open scoped Classical in +/-- The quantity computed by `wordSize S t + (header S).width`. -/ +def scale (S : Scheme F) (t : ℕ) := wordSize S t + (header S).width + +open scoped Classical in +private theorem host : + Cheap F (n S) (scale S t) (line S) (.pair (.addr (wordSize S t)) (line S)) + (fun x => (length S t x, pack S x)) 50 := by + let δ := scale S t + have hn : n S + 1 ≤ δ := by unfold δ scale wordSize; omega + have he : S.e + t + 1 ≤ δ := by unfold δ scale wordSize; omega + have hh : (header S).width ≤ δ := Nat.le_add_left _ _ + have hw : (header S).width ≤ 2 ^ 0 * (100 + δ) ^ 1 + := by simp only [pow_zero, one_mul, pow_one]; omega + have get := (Cheap.id F hw).fst + have fl := get.comp (unary (F:=F) (A:=.addr 1) (δ:=δ) (by rw [Format.width_addr]; omega) flag) + have size_width : (Format.addr (S.e + t + 1)).width ≤ δ := by + rwa [Format.width_addr] + have sz := get.comp (unary (F:=F) (A:=.addr (S.e + t + 1)) size_width (amount S t)) + have len := (Cheap.map _ fun _ : B (n S) => sz).comp ((cheap_total F (n S) (S.e + t + + 1)).widen he) + have σ := (Cheap.map _ fun _ : B (n S) => fl).comp ((cheap_order F (n S) 1).widen hn) + have hd : (line S).width ≤ 2 ^ (n S) * (100 + δ) ^ 1 := by + rw [Format.width_vec, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have sorted := ((Cheap.id F hd).pair σ).comp (Cheap.lookup F (n S) δ (header S) (by omega) hh) + exact (len.pair sorted).mono (by decide) + +open scoped Classical in +/-- The quantity computed by `4 * (2 ^ S.m * (2 ^ (n S) * (100 + scale S t) ^ 50) + 3 * (source +S t).width)`. -/ +def localCost (S : Scheme F) (t : ℕ) := + 4 * (2 ^ S.m * (2 ^ (n S) * (100 + scale S t) ^ 50) + 3 * (source S t).width) + +open scoped Classical in +theorem paired_net (hu : 3 ≤ u) (ha : arity S ≤ u) (hl : label S ∈ L) : + Map F u L S.format (source S t) (paired S t) (rowCost S + localCost S t) := by + let D := Format.vec S.m (.pair (.addr (wordSize S t)) (line S)) + have hw : D.width = (source S t).width := by simp [D, source, Redistribute.input, mul_add] + have unzip : Circuit F D (source S t) (fun x => (fun i => (x i).1, fun i => (x i).2)) + (D.width + 2 * (source S t).width) := by + apply Circuit.project (Sum.elim (fun p => (p.1, .inl p.2)) (fun p => (p.1, .inr p.2))) + rintro x (i|i) <;> rfl + obtain ⟨s, hs, hb⟩ := host (S:=S) (t:=t) + have hc := (Circuit.map _ (fun _ : B S.m => hs)).comp unzip + have hle : s ≤ 2 ^ (n S) * (100 + scale S t) ^ 50 := by omega + have hm := Nat.mul_le_mul_left (2 ^ S.m) hle + refine (rows_net hu ha hl).comp ((Map.circuit hu hc).mono (n:=localCost S t) ?_) + unfold localCost + omega + +open scoped Classical in +/-- The cost used in the `Header` construction. -/ +def cost (S : Scheme F) (V t v c : ℕ) := rowCost S + localCost S t + + Redistribute.cost S.m (height S t) (wordSize S t) v c + + 4 * ((dest S V t).width + 2 * (headers S V t).width) + +open scoped Classical in +theorem realize (hu : 3 ≤ u) (ha : arity S ≤ u) (hl : label S ∈ L) + (ht : Radix.Tag F S.m v c) (hv : (line S).width ≤ v) : + Map F u L S.format (headers S V t) (eval S V t) (cost S V t v c) := by + have a := paired_net (t:=t) hu ha hl + have b := Redistribute.realize (L:=L) (w:=wordSize S t) (k:=height S t) (V:=V) + hu ht (line S) hv (fun _ => pad S) + have d : Circuit F (dest S V t) (headers S V t) (cut S V t) + ((dest S V t).width + 2 * (headers S V t).width) := + Circuit.project (fun i => ⟨i.1.1, pick S V t i.1, i.2⟩) (fun _ _ => rfl) + exact (a.comp b).comp (Map.circuit hu d) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Header +end + +/- # Header work is charged to hosts and the data charge is linear in bank capacity -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Header +open Coloring Dictionary + +private theorem majorant (R x y H z d W : ℕ) (hR : 1000 ≤ R) + (hx : x ≤ R) (hy : y ≤ R) (hh : H ≤ R) (hz : z ≤ R) + (hd : d ≤ R) (hw : W + 1 ≤ R) : + 137 * x + 1 + 13 * y + 12 * z + 52 * H * y + 4 * d ^ 50 + 10000 * H * (W + 1) * (y + 1) + ≤ R ^ 80 := by + have hr : 0 < R := by omega + have h₀ : 1 ≤ R ^ 50 := Nat.one_le_pow _ _ hr + have h₁ : R ≤ R ^ 50 := Nat.le_pow (by decide) + have h₂ : R ^ 2 ≤ R ^ 50 := Nat.pow_le_pow_right hr (by decide) + have h₃ : R ^ 3 ≤ R ^ 50 := Nat.pow_le_pow_right hr (by decide) + calc + _ ≤ 137 * R + 1 + 13 * R + 12 * R + 52 * R * R + 4 * R ^ 50 + 10000 * R * R * (R + 1) + := by gcongr + _ = 1 + 162 * R + 10052 * R ^ 2 + 10000 * R ^ 3 + 4 * R ^ 50 := by ring + _ ≤ 1000000 * R ^ 50 := by omega + _ ≤ R ^ 2 * R ^ 50 := Nat.mul_le_mul_right _ (Nat.pow_le_pow_left hR 2) + _ = R ^ 52 := (pow_add R 2 50).symm + _ ≤ R ^ 80 := Nat.pow_le_pow_right hr (by decide) + +private theorem account (A M N H x y z d W P B V v c D E Y : ℕ) + (hn : 0 < N) (hv : v ≤ N * y + P) (hc : c ≤ W * (M * v)) + (hD : D ≤ H * (M * (N * y))) (hE : E ≤ D) (hY : Y ≤ H * (2 * V)) : + 4 * (A + 34 * (M * (N * x))) + M * (N * (1 + x + y)) + + 4 * (M * (N * d ^ 50) + 3 * (M * z + M * (N * y))) + + 10000 * H * (c + M * (v + B)) + 4 * (D + 2 * E) + 40 * (E + Y) ≤ + 4 * A + (M * (P + B) + M * N) * (137 * x + 1 + 13 * y + 12 * z + 52 * H * y + 4 * d ^ 50 + + 10000 * H * (W + 1) * (y + 1)) + 80 * H * V := by + have hm := Nat.le_mul_of_pos_right M hn + have hg : c ≤ W * (M * (N * y + P + B)) := hc.trans (by gcongr; omega) + have he := hE.trans hD + calc + _ ≤ 4 * (A + 34 * (M * (N * x))) + M * (N * (1 + x + y)) + + 4 * (M * (N * d ^ 50) + 3 * (M * N * z + M * (N * y))) + + 10000 * H * (W * (M * (N * y + P + B)) + M * (N * y + P + B)) + + 4 * (H * (M * (N * y)) + 2 * (H * (M * (N * y)))) + 40 * (H * (M * (N * y)) + H * (2 * V)) + := by gcongr + _ ≤ _ := by ring_nf; omega + +variable {F : Type} {S : Scheme F} {V t v c P W : ℕ} + +theorem cost_bound (hv : v ≤ (line S).width + P) (hc : c ≤ W * (2 ^ S.m * v)) : + cost S V t v c + Dictionary.price S V t ≤ + 4 * S.format.width + (2 ^ S.m * (P + (101 + S.m + wordSize S t) ^ 60) + 2 ^ (S.m + S.h + + S.k))* + (1000 + W + scale S t) ^ 80 + 80 * (height S t + 1) * V := by + have hu := account S.format.width (2 ^ S.m) (2 ^ (n S)) (height S t + 1) + (key S).width (header S).width (wordSize S t) (100 + scale S t) W P + ((101 + S.m + wordSize S t) ^ 60) V v c (dest S V t).width (headers S V t).width + (Fmt.payload S.m V (height S t)).width (Nat.two_pow_pos _) (by simpa only [line, + Format.width_vec] using hv) hc + (by simpa only [line, Format.width_vec] using width_dest S V t) + (width_headers S V t) (Fmt.width_payload ..) + have hb := majorant (1000 + W + scale S t) (key S).width (header S).width (height S t + 1) + (wordSize S t) (100 + scale S t) W (by omega) + (by simp only [scale, key, header, Format.width_pair]; omega) + (by unfold scale; omega) (by unfold scale wordSize height n; omega) + (by unfold scale; omega) (by omega) (by omega) + have hn : 2 ^ (S.m + S.h + S.k) = 2 ^ S.m * 2 ^ (n S) := by rw [add_assoc, pow_add] + rw [hn] + refine le_trans ?_ (Nat.add_le_add_right (Nat.add_le_add_left (Nat.mul_le_mul_left _ hb) _) _) + simpa only [cost, Dictionary.price, rowCost, localCost, names, source, Redistribute.input, + Redistribute.cost, + Redistribute.budget, line, Format.width_pair, Format.width_vec, Format.width_addr] using hu + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Header +end + +/- # Reading reciprocal contacts from a matrix of address comparisons -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring + +variable {F : Type} (S : Scheme F) +open scoped Classical in +/-- The quantity computed by `(Perm (S.m + (S.d + 1))).pair (Flags S)`. -/ +abbrev LinkGrid := (Perm (S.m + (S.d + 1))).pair (Flags S) +open scoped Classical in +/-- The value specified by `(perm S r, flags S r)`. -/ +def links (r : S.format.obj) : (LinkGrid S).obj := (perm S r, flags S r) + +namespace Links +local notation "m" => S.m +local notation "d" => S.d +local notation "idx" => Match.rowIndex m (d + 1) + +open scoped Classical in +/-- The quantity computed by `Neighborhood.Rows m (d + 1)`. -/ +abbrev Rows := Neighborhood.Rows m (d + 1) +open scoped Classical in +/-- The quantity computed by `Neighborhood.Mask m (d + 1) (d + 1)`. -/ +abbrev Mask := Neighborhood.Mask m (d + 1) (d + 1) +open scoped Classical in +/-- The quantity computed by `Format.vec m (.vec (d + 1) (.vec d .bit))`. -/ +abbrev Query := Format.vec m (.vec (d + 1) (.vec d .bit)) +open scoped Classical in +/-- The quantity computed by `Format.vec m (.vec (d + 1) (.addr (d + 1)))`. -/ +abbrev Reply := Format.vec m (.vec (d + 1) (.addr (d + 1))) +open scoped Classical in +/-- The value specified by `(Mask S).pair (Reply S)`. -/ +abbrev Status := (Mask S).pair (Reply S) +open scoped Classical in +/-- The value specified by `(Rows S).pair (Status S)`. -/ +abbrev Data := (Rows S).pair (Status S) + +open scoped Classical in +/-- Evaluates `x v i (hop (some j)) (hop none)` at the input `v i j`. -/ +def query (x : (Mask S).obj) : (Query S).obj := fun v i j => x v i (hop (some j)) (hop none) +open scoped Classical in +/-- Evaluates `reverseHop d (x v i)` at the input `v i`. -/ +def reply (x : (Query S).obj) : (Reply S).obj := fun v i => reverseHop d (x v i) +open scoped Classical in +/-- The value specified by `(x, reply S (query S x))`. -/ +def status (x : (Mask S).obj) : (Status S).obj := (x, reply S (query S x)) +open scoped Classical in +/-- The value specified by `(x, status S (Neighborhood.maskRows x x))`. -/ +def data (x : (Rows S).obj) : (Data S).obj := (x, status S (Neighborhood.maskRows x x)) +open scoped Classical in +/-- Computes the self by the application `x.2.1 v (hop none) j (hop none)`. -/ +def self (x : (Data S).obj) (v : B m) (j : B (d + 1)) := x.2.1 v (hop none) j (hop none) + +open scoped Classical in +/-- The finish of type `(LinkGrid S).obj`, constructed using `idx i`. -/ +def finish (x : (Data S).obj) : (LinkGrid S).obj := + (fun i => + let j := idx i + (idx).symm (x.1 j.1 j.2, if self S x j.1 j.2 then j.2 else x.2.2 j.1 j.2), + fun i j => self S x i (hop (some j))) + +open scoped Classical in +theorem correct : finish S ∘ data S ∘ extended S = links S := by + funext r + have a (i : B m) (j : B (d + 1)) : self S (data S (extended S r)) i j = decide (extended S r i j + = i) := by + simp only [self, data, status, Neighborhood.maskRows, extended_self] + have b (i : B m) (j : B (d + 1)) : + (data S (extended S r)).2.2 i j = reverseHop d (fun k => decide ((r (extended S r i j)).1 k + = i)) := by + apply congrArg (reverseHop d) + funext k + simp only [query, Neighborhood.maskRows, extended_self, extended_peer] + apply Prod.ext + · funext i + simp only [Function.comp_apply, finish, links, perm, a, b, decide_eq_true_eq] + rfl + · funext i j + simp only [Function.comp_apply, finish, links, flags, a, extended_peer] + +variable [Field F] + +open scoped Classical in +theorem extend_net : Circuit F S.format (Rows S) (extended S) (S.format.width + + 34 * (Rows S).width) := by + apply Window.Tile.project_const + rintro ⟨v, i, k⟩ + by_cases h : (Match.rowIndex S.d 1 i).2 = 1 + · refine .inl ⟨(v, .inl ((Match.rowIndex S.d 1 i).1, k)), fun r => ?_⟩ + change (Format.addr m).code (extended S r v i) k = _ + rw [extended, ite_eq_left h] + rfl + · refine .inr ⟨(Format.addr m).code v k, fun r => ?_⟩ + change (Format.addr m).code (extended S r v i) k = _ + rw [extended, ite_eq_right h] + +open scoped Classical in +theorem query_net : Circuit F (Mask S) (Query S) (query S) ((Mask S).width + 2 * (Query S).width) := + Circuit.project (fun x => (x.1, x.2.1, hop (some x.2.2.1), hop none, x.2.2.2)) (fun _ _ => rfl) + +open scoped Classical in +theorem finish_net : Circuit F (Data S) (LinkGrid S) (finish S) ((Data S).width + + 68 * (LinkGrid S).width) := by + let A := Data S + let C := LinkGrid S + have he : Install.Depends (C.code ∘ finish S ∘ A.code.symm) 2 := by + have pin (i : C.pins) (j : A.pins) (h : ∀ x, C.code (finish S x) i = A.code x j) : + ∃ s : Finset A.pins, s.card ≤ 2 ∧ ∀ x y, (∀ l ∈ s, x l = y l) → + (C.code ∘ finish S ∘ A.code.symm) x i = (C.code ∘ finish S ∘ A.code.symm) y i := by + refine ⟨{j}, by simp, fun x y he => ?_⟩ + simp only [Function.comp_apply, h, Equiv.apply_symm_apply] + exact he j (by simp) + rintro (⟨i, t⟩|⟨j, k, ⟨⟩⟩) + · let v := (idx i).1 + let w := (idx i).2 + obtain ⟨k, hk⟩ := Match.append_pin m (d + 1) t + cases k with + | inl k => + exact pin _ (.inl (v, w, k)) (fun x => hk _ _) + | inr k => + let j : A.pins := .inr (.inl (v, hop none, w, hop none, ())) + let l : A.pins := .inr (.inr (v, w, k)) + have eq (x : A.obj) : C.code (finish S x) (.inl (i, t)) = + if A.code x j then (Format.addr (d + 1)).code w k else A.code x l := by + change (Format.addr _).code ((idx).symm (x.1 v w, + if self S x v w then w else x.2.2 v w)) t = _ + rw [hk] + change (Format.addr (d + 1)).code (if self S x v w then w else x.2.2 v w) k = + if self S x v w then _ else _ + split <;> rfl + refine ⟨{j, l}, Finset.card_le_two, fun x y h => ?_⟩ + simp only [Function.comp_apply, eq, Equiv.apply_symm_apply, h j (by simp), h l (by simp)] + · exact pin _ (.inr (.inl (j, hop none, hop (some k), hop none, ()))) (fun _ => rfl) + exact he.bnet F + +end Links +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- +# Cost of constructing the terminal contact permutation + +A shared mask compares only addresses in the host's neighborhood. +Recover each reciprocal index from the unique successful comparison. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring Links + +variable {F : Type} (S : Scheme F) + +local notation "m" => S.m +local notation "d" => S.d +local notation "t" => (S.m + 2 ^ (S.d + 1)) +local notation "W" => (2 ^ m * (100 + t) ^ 24) + +open scoped Classical in +/-- The quantity computed by `S.format.width + 512 * W`. -/ +def linkCost := S.format.width + 512 * W + +open scoped Classical in +private theorem product (x y z : ℕ) (hx : x ≤ 100 + t) (hy : y ≤ 100 + t) (hz : z ≤ 100 + t) : + 2 ^ m * (x * (y * z)) ≤ W := by + apply Nat.mul_le_mul_left + calc + _ ≤ (100 + t) * ((100 + t) * (100 + t)) := Nat.mul_le_mul hx (Nat.mul_le_mul hy hz) + _ = (100 + t) ^ 3 := by rw [pow_succ' (100 + t) 2, pow_two] + _ ≤ _ := Nat.pow_le_pow_right (by positivity) (by decide) + +open scoped Classical in +private theorem bounds : + (Query S).width ≤ W ∧ (Reply S).width ≤ W ∧ (LinkGrid S).width ≤ 2 * W ∧ + 2 ^ m * (2 ^ (d + 1) * (100 * (2 ^ d) ^ 2)) ≤ 100 * W := by + have hs : 2 ^ (d + 1) ≤ 100 + t := (Nat.le_add_left _ _).trans (Nat.le_add_left _ _) + have hd : 2 ^ d ≤ 100 + t := (Nat.pow_le_pow_right (by decide) (Nat.le_succ d)).trans hs + have h₁ : 1 ≤ 100 + t := (by decide : 1 ≤ 100).trans (Nat.le_add_right ..) + have ha : m + (d + 1) ≤ 100 + t := + (Nat.add_le_add_left Nat.lt_two_pow_self.le m).trans (Nat.le_add_left ..) + refine ⟨?_, ?_, ?_, ?_⟩ + · rw [Query, Format.width_vec, Format.width_vec, Format.width_vec, Format.width_bit] + exact product S _ _ _ hs hd h₁ + · rw [Reply, Format.width_vec, Format.width_vec, Format.width_addr] + simpa only [mul_one] using product S _ _ 1 hs ((Nat.le_add_left _ _).trans ha) h₁ + · rw [LinkGrid, Format.width_pair, Perm, Flags, Format.width_vec, Format.width_addr, + Format.width_vec, + Format.width_vec, Format.width_bit, pow_add, mul_assoc, two_mul] + have hP := product S _ _ 1 hs ha h₁ + have hQ := product S _ _ 1 hd h₁ h₁ + simp only [mul_one] at hP hQ ⊢ + exact Nat.add_le_add hP hQ + · rw [mul_left_comm (2 ^ (d + 1)) 100, mul_left_comm (2 ^ m) 100, pow_two] + exact Nat.mul_le_mul_left 100 (product S _ _ _ hs hd hd) + +open scoped Classical in +private theorem assemble [Field F] {A B C : Format} {f : (A.pair A).obj → B.obj} + {g : B.obj → C.obj} {k l w : ℕ} + (first : Circuit F (A.pair A) B f k) (next : Circuit F B C g l) + (hk : (A.pair A).width + B.width + k ≤ w) (hl : l ≤ 104 * w) : + Circuit F A (A.pair (B.pair C)) (fun x => (x, f (x, x), g (f (x, x)))) (200 * w) := by + have h := Circuit.id F A + refine (h.pair (((h.pair h).comp first).comp ((Circuit.id F B).pair next))).mono ?_ + rw [Format.width_pair] at hk + omega + +open scoped Classical in +private theorem mask_net [Field F] : ∃ a, + Circuit F ((Rows S).pair (Rows S)) (Mask S) (fun x => Neighborhood.maskRows x.1 x.2) a ∧ + ((Rows S).pair (Rows S)).width + (Mask S).width + a ≤ W := + Neighborhood.cheap_maskRows F (Nat.le_add_right m (2 ^ (d + 1))) + (Nat.le_add_left (2 ^ (d + 1)) m) (Nat.le_add_left (2 ^ (d + 1)) m) + +open scoped Classical in +private theorem twice [Field F] {A B : Format} {f : A.obj → B.obj} {c : ℕ} + (h : Circuit F A B f c) (i j : ℕ) : + Circuit F (.vec i (.vec j A)) (.vec i (.vec j B)) (fun x v y + => f (x v y)) (2 ^ i * (2 ^ j * c)) := + Circuit.map _ fun _ => Circuit.map _ fun _ => h + +open scoped Classical in +private theorem r_net [Field F] : Circuit F (Query S) (Reply S) (Links.reply S) (2 ^ m * (2 ^ (d + + 1) * (100 * (2 ^ d) ^ 2))) := by + unfold Links.reply Query Reply + exact twice (reverseNet F d) m (d + 1) + +open scoped Classical in +private theorem data_net [Field F] : Circuit F (Rows S) (Links.Data S) (Links.data S) (200 * W) + := by + obtain ⟨a, k, h⟩ := mask_net S + have hl : (Mask S).width + 2 * (Query S).width + 2 ^ m * (2 ^ (d + 1) * (100 * (2 ^ d) ^ 2)) + ≤ 104 * W := by + obtain ⟨h₁, _, _, h₄⟩ := bounds S + omega + have h' := assemble k ((query_net S).comp (r_net S)) h hl + simp only [Function.comp_apply] at h' + unfold Links.data Links.status Links.Data Links.Status + exact h' + +open scoped Classical in +theorem links_net [Field F] : Circuit F S.format (LinkGrid S) (links S) (linkCost S) := by + rw [← correct] + refine ((extend_net S).comp ((data_net S).comp (finish_net S))).mono ?_ + obtain ⟨_, _, h⟩ := mask_net S + obtain ⟨_, h₂, h₃, _⟩ := bounds S + rw [Format.width_pair] at h + unfold linkCost + rw [Links.Data, Format.width_pair, Links.Status, Format.width_pair] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- +# Uniform cost scales of the terminal contraction + +Host names, station labels and physical payloads have separate +coefficients. Each estimate is uniform over fields and schemes. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +open BatchDescent.Phase Rounds.Contraction + +/-- The data for the size construction, including `F`, `[field`, `S`, `W`, `V`. -/ +structure Size where + /-- The `Size` component of type `Type`. -/ + F : Type + [field : Field F] + /-- The `Size` component of type `Scheme F`. -/ + S : Scheme F + /-- The `Size` component of type `Prices F`. -/ + W : Prices F + /-- The `Size` field of type `ℕ`. -/ + V : ℕ + /-- The `Size` field of type `ℕ`. -/ + t : ℕ + /-- The `Size` field of type `ℕ`. -/ + V' : ℕ + /-- The `Size` field of type `ℕ`. -/ + k' : ℕ + +attribute [instance] Size.field + +namespace Size +variable (i : Size) + +/-- Computes the k by the application `height i.S i.t`. -/ +abbrev k := height i.S i.t +/-- The maximum of the quantities in `i.k i.k' + 1`. -/ +abbrev w := max i.k i.k' + 1 +/-- The quantity computed by `i.S.d + 1`. -/ +abbrev p := i.S.d + 1 +/-- Uses `i.S.spanRows` as the representation. -/ +abbrev n := i.S.spanRows +/-- The quantity computed by `1000 + i.W.W + i.k + i.k'`. -/ +abbrev B := 1000 + i.W.W + i.k + i.k' +/-- The quantity computed by `i.B + 2 ^ i.S.d + i.S.ℓ`. -/ +abbrev T := i.B + 2 ^ i.S.d + i.S.ℓ +/-- The quantity computed by `i.T + i.S.m + i.W.w + i.W.w ^ i.W.power`. -/ +abbrev M := i.T + i.S.m + i.W.w + i.W.w ^ i.W.power +/-- The quantity computed by `2 ^ i.S.m`. -/ +abbrev hosts := 2 ^ i.S.m +/-- The quantity computed by `i.hosts * 2 ^ i.n`. -/ +abbrev spans := i.hosts * 2 ^ i.n +/-- The quantity computed by `i.V + i.V'`. -/ +abbrev volume := i.V + i.V' +/-- The quantity computed by `i.hosts * i.M ^ K + i.spans * i.T ^ K + i.volume * i.B ^ K`. -/ +abbrev bound (K : ℕ) := i.hosts * i.M ^ K + i.spans * i.T ^ K + i.volume * i.B ^ K + +theorem b_two : 2 ≤ i.B := by unfold B; omega +theorem bt : i.B ≤ i.T := (Nat.le_add_right ..).trans (Nat.le_add_right ..) +theorem tm : i.T ≤ i.M := by unfold M; omega +theorem t_two : 2 ≤ i.T := i.b_two.trans i.bt +theorem m_two : 2 ≤ i.M := i.t_two.trans i.tm + +private def charges : List (ℕ × ℕ) := + [(i.hosts, i.M), (i.spans, i.T), (i.volume, i.B)] + +private theorem charges_base (charge : ℕ × ℕ) (h : charge ∈ i.charges) : i.B ≤ charge.2 := by + simp only [charges, List.mem_cons, List.not_mem_nil, or_false] at h + rcases h with rfl | rfl | rfl + · exact i.bt.trans i.tm + · exact i.bt + · exact le_rfl +end Size + +/-- Computes the outer by the application `Poly Size.B`. -/ +abbrev Outer := Poly Size.B +/-- Computes the short by the application `Poly Size.T`. -/ +abbrev Short := Poly Size.T +/-- Computes the long by the application `Poly Size.M`. -/ +abbrev Long := Poly Size.M +/-- The condition `∃ K, ∀ i, f i ≤ i.bound K` on the specified data. -/ +def Work (f : Size → ℕ) := ∃ K, ∀ i, f i ≤ i.bound K + +variable {f g : Size → ℕ} +theorem Outer.short (h : Outer f) : Short f := h.grow Size.bt +theorem Short.long (h : Short f) : Long f := h.grow Size.tm +theorem Outer.long (h : Outer f) : Long f := h.short.long + +theorem num (a : ℕ) : Outer (fun _ => a) := Poly.const Size.b_two a +theorem k : Outer Size.k := Poly.of_le Size.b_two fun i => by unfold Size.B; omega +theorem k' : Outer Size.k' := Poly.of_le Size.b_two fun i => by unfold Size.B; omega +theorem w : Outer Size.w := Poly.of_le Size.b_two fun i => by unfold Size.B Size.w; omega +theorem rate : Outer (fun i => i.W.W) := Poly.of_le Size.b_two fun i => by unfold Size.B; omega +theorem n : Outer Size.n := k.mono fun i => by unfold Size.k Size.n height Scheme.spanRows; omega +theorem neighbors : Short (fun i => 2 ^ i.S.d) := Poly.of_le Size.t_two fun i + => by unfold Size.T; omega +theorem d : Short (fun i => i.S.d) := neighbors.of_exp +theorem labels : Short (fun i => i.S.ℓ) := Poly.of_le Size.t_two fun _ => Nat.le_add_left .. +theorem p : Short Size.p := d.add (num 1).short +theorem links : Short (fun i => 2 ^ i.p) := by + simpa only [Size.p, pow_succ] using neighbors.mul (num 2).short +theorem m : Long (fun i => i.S.m) := Poly.of_le Size.m_two fun i => by unfold Size.M; omega +theorem limit : Long (fun i => i.W.w) := Poly.of_le Size.m_two fun i => by unfold Size.M; omega +theorem threshold : Long (fun i => i.W.w ^ i.W.power) := + Poly.of_le Size.m_two fun i => by unfold Size.M; omega + +namespace Work + +private theorem weighted_iff : Work f ↔ WeightedCost Size.charges f := by + simp only [Work, WeightedCost, Size.charges, Size.bound, weightedPower, List.map_cons, + List.map_nil, List.sum_cons, List.sum_nil, Nat.add_zero, Nat.add_assoc] + +theorem mono (hf : Work f) (h : ∀ i, g i ≤ f i) : Work g := + weighted_iff.mpr ((weighted_iff.mp hf).mono h) + +theorem add (hf : Work f) (hg : Work g) : Work (fun i => f i + g i) := + weighted_iff.mpr ((weighted_iff.mp hf).add (weighted_iff.mp hg) + fun i charge h => i.b_two.trans (i.charges_base charge h)) + +theorem mul (hf : Work f) (hg : Outer g) : Work (fun i => f i * g i) := + weighted_iff.mpr ((weighted_iff.mp hf).mul hg Size.charges_base) + +theorem scale (hf : Work f) (hg : Outer g) : Work (fun i => g i * f i) := + (hf.mul hg).mono fun _ => (mul_comm ..).le + +theorem hosts (hf : Long f) : Work (fun i => i.hosts * f i) := + let ⟨s, hs⟩ := hf.bound + ⟨s, fun i => (Nat.mul_le_mul_left _ (hs i)).trans ((Nat.le_add_right ..).trans (Nat.le_add_right + ..))⟩ + +theorem spans (hf : Short f) : Work (fun i => i.spans * f i) := + let ⟨s, hs⟩ := hf.bound + ⟨s, fun i => (Nat.mul_le_mul_left _ (hs i)).trans ((Nat.le_add_left ..).trans (Nat.le_add_right + ..))⟩ + +theorem volume (hf : Outer f) : Work (fun i => i.volume * f i) := + let ⟨s, hs⟩ := hf.bound + ⟨s, fun i => (Nat.mul_le_mul_left _ (hs i)).trans (Nat.le_add_left ..)⟩ +end Work + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +end + +/- # Uniform bound for constructing and evaluating the terminal dictionary -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +open Coloring + +namespace Size +variable (i : Size) +/-- The quantity computed by `(Header.line i.S).width + i.W.w ^ i.W.power`. -/ +abbrev v := (Header.line i.S).width + i.W.w ^ i.W.power +/-- The quantity computed by `i.W.W * (2 ^ i.S.m * i.v)`. -/ +abbrev c := i.W.W * (2 ^ i.S.m * i.v) +/-- Computes the header by the application `Header.cost i.S i.V i.t i.v i.c`. -/ +abbrev header := Header.cost i.S i.V i.t i.v i.c +/-- Computes the dictionary by the application `Dictionary.price i.S i.V i.t`. -/ +abbrev dictionary := Dictionary.price i.S i.V i.t +/-- The value specified by `(Fmt.payload i.S.m i.V i.k).width`. -/ +abbrev inner := (Fmt.payload i.S.m i.V i.k).width +/-- The value specified by `(Fmt.payload i.S.m i.V' i.k').width`. -/ +abbrev outer := (Fmt.payload i.S.m i.V' i.k').width + +theorem stations : 2 ^ (i.S.m + i.S.h + i.S.k) ≤ i.spans := by + rw [add_assoc, pow_add] + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide) (Nat.le_add_right ..)) + +end Size + +theorem format : Work (fun i => i.S.format.width) := by + refine ((Work.hosts (neighbors.long.mul m)).add (Work.spans labels)).mono fun i => ?_ + rw [Scheme.format, Fmt.width_rows, Format.width_addr, mul_add, + ← mul_assoc (2 ^ i.S.m) (2 ^ i.S.h)] + have width : i.S.h ≤ i.n := by + unfold Size.n Scheme.spanRows + omega + have he : 2 ^ i.S.h ≤ 2 ^ i.n := Nat.pow_le_pow_right (by decide) width + exact Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ he)) _ + +theorem inner : Work Size.inner := by + refine (Work.volume ((k.add (num 1)).mul (num 2))).mono fun i => ?_ + refine (Fmt.width_payload ..).trans ?_ + rw [← mul_assoc, mul_comm _ i.V] + exact Nat.mul_le_mul_right _ (Nat.le_add_right ..) + +theorem outer : Work Size.outer := by + refine (Work.volume ((k'.add (num 1)).mul (num 2))).mono fun i => ?_ + refine (Fmt.width_payload ..).trans ?_ + rw [← mul_assoc, mul_comm _ i.V'] + exact Nat.mul_le_mul_right _ (Nat.le_add_left ..) + +private theorem word : Outer (fun i => Header.wordSize i.S i.t) := + (k.add (num 1)).mono fun i => by unfold Header.wordSize Header.n Size.k height; omega + +theorem scale : Short (fun i => Header.scale i.S i.t) := by + have hk : Outer (fun i => i.S.k) := n.mono fun i => by unfold Size.n Scheme.spanRows; omega + refine (word.short.add ((num 1).short.add (labels.add hk.short))).mono fun i => ?_ + simp only [Header.scale, Dictionary.header, Format.width_pair, Format.width_addr] + rw [Format.width_bit] + +theorem both : Work (fun i => i.header + i.dictionary) := by + have factor := ((((num 1000).short.add rate.short).add scale).pow 80) + have total := threshold.add ((((num 101).long.add m).add word.long).pow 60) + have names := Work.hosts (total.mul (Short.long factor)) + have rows := Work.spans factor + have bits := Work.volume ((num 80).mul (k.add (num 1))) + refine (((format.scale (num 4)).add (names.add rows)).add bits).mono fun i => ?_ + refine (Header.cost_bound (S:=i.S) (V:=i.V) (t:=i.t) (v:=i.v) (c:=i.c) + (P:=i.W.w ^ i.W.power) (W:=i.W.W) le_rfl le_rfl).trans ?_ + rw [add_mul, mul_assoc (2 ^ i.S.m), mul_comm _ i.V] + exact Nat.add_le_add (Nat.add_le_add_left (Nat.add_le_add_left + (Nat.mul_le_mul_right _ i.stations) _) _) (Nat.mul_le_mul_right _ (Nat.le_add_right ..)) + +theorem header : Work Size.header := both.mono fun _ => Nat.le_add_right .. +theorem dictionary : Work Size.dictionary := both.mono fun _ => Nat.le_add_left .. +theorem headers : Work (fun i => (Dictionary.headers i.S i.V i.t).width) := + dictionary.mono fun i => by unfold Size.dictionary Dictionary.price; omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +end + +/- # Uniform terminal contraction cost -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +open Coloring Rounds.Contraction + +/-- Uses `Terminal.instruction i.S i.V i.t i.p i.w i.n` as the representation. -/ +abbrev Size.instruction (i : Size) := Terminal.instruction i.S i.V i.t i.p i.w i.n +/-- The value specified by `Terminal.price i.W i.S i.V i.t i.V' i.k' i.p i.w i.n`. -/ +abbrev Size.price (i : Size) := Terminal.price i.W i.S i.V i.t i.V' i.k' i.p i.w i.n + +private theorem script (a : Size → ℕ) (ha : Short a) (he : Short (fun i => 2 ^ a i)) : + Work (fun i => (Payload.Script i.S.m i.S.m (a i) i.w i.n).width) := by + have row := Work.hosts (Short.long (w.short.add (he.mul w.short))) + have span := Work.spans (ha.add ((num 3).short.mul w.short)) + have peer := Work.hosts (he.long.mul (m.add ha.long)) + refine (((row.add span).scale (num 2)).add peer).mono fun i => ?_ + simp only [Payload.Script, PeerLayout.input, PeerLayout.lengths, Fragments.Entry, Intervals.span, + Format.width_pair, Format.width_vec, Format.width_addr, Size.spans, Size.hosts, pow_add] + rw [Format.width_addr] + exact le_of_eq (by ring) + +theorem instruction : Work (fun i => i.instruction.width) := by + have h := script Size.p p links + have e := script (fun _ => 0) (num 0).short (num 1).short + refine ((h.add e).add headers).mono fun i => ?_ + rw [Size.instruction, Terminal.instruction, Format.width_pair, Format.width_pair] + +private theorem shipping (X J a : Size → ℕ) (hx : ∀ i, X i ≤ i.volume) + (hj : Outer J) (ha : Short a) (he : Short (fun i => 2 ^ a i)) : + Work (fun i => i.W.shipment i.inner i.S.m i.V i.k i.S.m (X i) (J i) (a i) i.w i.n) := by + obtain ⟨K, hK⟩ := Prices.shipment_le + have b := (((num 1000).add rate).add k).add hj + have s := (((Outer.short b).add ha).add w.short).add n.short + have l := ((((Short.long s).add m).add m).add limit).add threshold + have posts := (num 2).short.mul he + have names := Work.hosts ((Short.long posts).mul (l.pow K)) + have rows := Work.spans (posts.mul (s.pow K)) + have bits := Work.volume ((num 2).mul (b.pow K)) + refine (((inner.scale (num 4)).add (names.add rows)).add bits).mono fun i => ?_ + refine (hK i.F i.W i.inner i.S.m i.V i.k i.S.m (X i) (J i) (a i) i.w i.n).trans ?_ + apply Nat.add_le_add + · apply Nat.add_le_add_left + unfold Size.spans Size.hosts + exact le_of_eq (by ring) + · have hv := Nat.add_le_add (show i.V ≤ i.volume from Nat.le_add_right ..) (hx i) + rw [← Nat.mul_two] at hv + exact (Nat.mul_le_mul_right _ hv).trans_eq (mul_assoc ..) + +theorem price : Work Size.price := by + have a := shipping Size.V Size.k Size.p (fun _ => Nat.le_add_right ..) k p links + have b := shipping Size.V' Size.k' (fun _ => 0) (fun _ + => Nat.le_add_left ..) k' (num 0).short (num 1).short + exact (((a.add b).add dictionary).add (((instruction.add outer).add inner).scale (num 64))) + +theorem total : ∃ K, ∀ i : Size, i.header + i.price ≤ + 2 ^ i.S.m * (i.M ^ K + 2 ^ i.n * i.T ^ K) + (i.V + i.V') * i.B ^ K := by + obtain ⟨K, hK⟩ := header.add price + exact ⟨K, fun i => (hK i).trans_eq (by unfold Size.bound Size.spans Size.hosts Size.volume; ring)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/DictionaryHeaders.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/DictionaryHeaders.lean new file mode 100644 index 0000000000..8de604a0a7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/DictionaryHeaders.lean @@ -0,0 +1,925 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortBack +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import Mathlib.Order.Interval.Finset.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress + +/-! # Contracting two copies of a channel test with a station weight -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Kernel +open Coloring + +variable {F : Type} [Field F] {u m n k : ℕ} {L : Set (Table F)} {A B C X Z : Format} + +open scoped Classical in +/-- Move the output record of a kernel to its input. -/ +private theorem close {f : A.obj → B.obj → F} (h : Kernel F u L A B f m) (hu : 3 ≤ u) : + Kernel F u L (A.pair B) (.wire .unit) (fun p _ => f p.1 p.2) (m + 4 * B.width) := by + let a := word A.width + let b := word B.width + obtain ⟨s, hs, hf⟩ := h a b (names A) (names B) + obtain ⟨t, ht, hg⟩ := (Tagged.cap (F := F) b).includeWide (L := L) hu + have hw := (((hf.par hg).pre (Rewire.assoc a b b)).post (Rewire.swap .unit b)).trace + refine of_layout (a := .pair a b) (b := .unit) ((names A).sumCongr (names B)) (.refl _) + ⟨s + t, Nat.add_le_add hs (by simpa [b] using ht), ?_⟩ + simp only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] at hw + exact hw + +open scoped Classical in +/-- Contract one latent tape with two constraints and a dictionary. +The exterior tape remains available as an independent argument. -/ +theorem contract [Fintype Z.obj] + {f : (A.pair Z).obj → Z.obj → F} + {g : (B.pair Z).obj → X.obj → F} {c : C.obj → Z.obj → F} + (hu : 3 ≤ u) (hf : Kernel F u L (A.pair Z) Z f m) + (hg : Kernel F u L (B.pair Z) X g n) (hc : Kernel F u L C Z c k) : + Kernel F u L (((A.pair B).pair C).pair X) (.wire .unit) + (fun p _ => ∑ z, f (p.1.1.1, z) z * g (p.1.1.2, z) p.2 * c p.1.2 z) + (m + n + k + 64 * (A.width + B.width + C.width + X.width + Z.width)) := by + let Y := ((A.pair B).pair C).pair X + let P := Y.pair Z + let Q := (((A.pair Z).pair (B.pair Z)).pair C).pair ((Z.pair X).pair Z) + let gather (p : P.obj) : Q.obj := ((((p.1.1.1.1, p.2), (p.1.1.1.2, p.2)), p.1.1.2), ((p.2, + p.1.2), p.2)) + have hp : Circuit F P Q gather (P.width + 2 * Q.width) := by + let atBit : Q.pins → P.pins + | .inl (.inl (.inl (.inl i))) => .inl (.inl (.inl (.inl i))) + | .inl (.inl (.inl (.inr i))) => .inr i + | .inl (.inl (.inr (.inl i))) => .inl (.inl (.inl (.inr i))) + | .inl (.inl (.inr (.inr i))) => .inr i + | .inl (.inr i) => .inl (.inl (.inr i)) + | .inr (.inl (.inl i)) => .inr i + | .inr (.inl (.inr i)) => .inl (.inr i) + | .inr (.inr i) => .inr i + exact Circuit.project atBit (by rintro _ ((((i|i)|(i|i))|i)|((i|i)|i)) <;> rfl) + have joined := ((hf.par hg).par hc).close hu + have result := (Map.circuit hu hp).then_kernel joined + refine (sum_hidden (C := Z) hu result).mono ?_ + simp only [P, Q, Y, Format.width_pair] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Kernel +end + +/- +# A bank for the arguments of the live stations + +The block order is unchanged. A station with no bits uses no +positions in the bank. Each live station uses a fixed-width record +of padded spans. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal + +open Coloring +variable {F : Type} (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +/-- Computes the active by the application `Nonempty (S.LocalPin r v)`. -/ +def Active (v : S.Vtx) := Nonempty (S.LocalPin r v) + +open scoped Classical in +/-- The subtype of `v` satisfying `Active S r v`. -/ +abbrev Live := {v // Active S r v} + +open scoped Classical in +/-- Uses `v.val.1` as the representation. -/ +def position (v : Live S r) := v.val.1 + +open scoped Classical in +/-- The subtype of `v : Live S r` satisfying `position S r v = i`. -/ +abbrev localLive (i : B S.m) := {v : Live S r // position S r v = i} + +open scoped Classical in +/-- Counts the elements of `(localLive S r i)`. -/ +def count (i : B S.m) := Fintype.card (localLive S r i) + +open scoped Classical in +/-- The value specified by `(Match.rowIndex S.h S.k).symm v.val.val.2`. -/ +def localIndex {i : B S.m} (v : localLive S r i) := (Match.rowIndex S.h S.k).symm v.val.val.2 + +open scoped Classical in +theorem local_inj {i : B S.m} : Function.Injective (localIndex S r (i := i)) := by + intro a b h + exact Subtype.ext (Subtype.ext (Prod.ext (a.2.trans b.2.symm) + ((Match.rowIndex _ _).symm.injective h))) + +open scoped Classical in +/-- Reindexes `localLive S r i` and `Fin (count S r i)` by an equivalence. -/ +def ordinal (i : B S.m) : localLive S r i ≃ Fin (count S r i) := + letI : LinearOrder (localLive S r i) := LinearOrder.lift' _ (local_inj S r) + (Fintype.orderIsoFinOfCardEq _ rfl).toEquiv.symm + +open scoped Classical in +/-- Reindexes `Live S r` and `Σ i, Fin (count S r i)` by an equivalence. -/ +def serial : Live S r ≃ Σ i, Fin (count S r i) := + (Equiv.sigmaFiberEquiv (position S r)).symm.trans (Equiv.sigmaCongrRight (ordinal S r)) + +open scoped Classical in +/-- The quantity computed by `S.h + S.k + (S.e + t)`. -/ +def height (t : ℕ) := S.h + S.k + (S.e + t) + +open scoped Classical in +/-- The data for the fits construction, including `width`, `total`. -/ +structure Fits (V t : ℕ) : Prop where + width : ∀ p, S.width r p ≤ 2 ^ t + total : 2 ^ S.m + Fintype.card (Live S r) * 2 ^ (S.e + t) ≤ V + +variable {V t : ℕ} (h : Fits S r V t) + +open scoped Classical in +/-- Builds `Payload S.m V (height S t) where length i` with the specified `length`, `total`, +`refine`, `simpa`. -/ +def bank : Payload S.m V (height S t) where + length i := count S r i * 2 ^ (S.e + t) + total := by + have hc : Fintype.card (Live S r) = ∑ i, count S r i := by + rw [Fintype.card_congr (serial S r), Fintype.card_sigma] + simp + refine le_trans ?_ h.total + rw [hc, Finset.sum_mul] + have := Finset.sum_le_sum (s := Finset.univ) fun i (_ : i ∈ Finset.univ) => + show max 1 (count S r i * 2 ^ (S.e + t)) ≤ 1 + count S r i * 2 ^ (S.e + t) by omega + simpa [Finset.sum_add_distrib] using this + longest i := by + have he := Fintype.card_le_of_injective _ (local_inj S r (i := i)) + rw [Fintype.card_fin] at he + unfold height + rw [pow_add 2 (S.h + S.k) (S.e + t)] + exact Nat.mul_le_mul_right _ he + +open scoped Classical in +/-- Indexes the row by the coordinates of `B S.e × B t`. -/ +abbrev Row (S : Scheme F) (t : ℕ) := B S.e × B t +open scoped Classical in +/-- Indexes the data by the coordinates of `Live S r × Row S t`. -/ +abbrev Data (t : ℕ) := Live S r × Row S t + +open scoped Classical in +/-- Reindexes `Data S r t` and `(bank S r h).Bit` by an equivalence. -/ +def index : Data S r t ≃ (bank S r h).Bit := + ((serial S r).prodCongr (Match.rowIndex S.e t).symm).trans + ((Equiv.sigmaProdDistrib _ _).trans (Equiv.sigmaCongrRight fun _ => finProdFinEquiv)) + +open scoped Classical in +/-- Embeds `S.Pin r` into `Data S r t where toFun i`. -/ +def pin : S.Pin r ↪ Data S r t where + toFun i := (⟨i.1.1, ⟨i.1.2, i.2⟩⟩, i.1.2, i.2.castLE (h.width i.1)) + inj' x y he := by + have ha : x.1.1 = y.1.1 := congrArg (fun i => i.1.val) he + have hb : x.1.2 = y.1.2 := congrArg (fun i => i.2.1) he + have hc : x.2.val = y.2.val := congrArg (fun i => i.2.2.val) he + have hd : x.1 = y.1 := Prod.ext ha hb + exact Sigma.ext hd ((Fin.heq_ext_iff (congrArg _ hd)).mpr hc) + +open scoped Classical in +/-- Embeds `S.Pin r` into `(bank S r h).Bit`. -/ +def place : S.Pin r ↪ (bank S r h).Bit := (pin S r h).trans (index S r h).toEmbedding + +open scoped Classical in +/-- Embeds `Data S r t` into `Fmt.Port S.m V (height S t)`. -/ +def slot : Data S r t ↪ Fmt.Port S.m V (height S t) := + (index S r h).toEmbedding.trans (bank S r h).wire + +open scoped Classical in +/-- Embeds `S.Pin r` into `Fmt.Port S.m V (height S t)`. -/ +def wire : S.Pin r ↪ Fmt.Port S.m V (height S t) := (pin S r h).trans (slot S r h) + +open scoped Classical in +/-- The indexed operation `(bank S r h).store (Function.extend (place S r h) z (fun _ => +false))`. -/ +def store (z : S.Pin r → Bool) : (Fmt.payload S.m V (height S t)).obj := + (bank S r h).store (Function.extend (place S r h) z (fun _ => false)) + +open scoped Classical in +@[simp] theorem read_store (z : S.Pin r → Bool) (i : S.Pin r) : + store S r h z (wire S r h i) = z i := by + change (bank S r h).store _ ((bank S r h).wire (place S r h i)) = _ + rw [Payload.read_store, (place S r h).injective.extend_apply] + +open scoped Classical in +theorem store_injective : Function.Injective (store S r h) := by + intro x y he + funext i + simpa using congrFun he (wire S r h i) + +open scoped Classical in +theorem pin_range (i : Data S r t) : i ∈ Set.range (pin S r h) ↔ i.2.2.val < S.width r (i.1.val, + i.2.1) := by + constructor + · rintro ⟨p, rfl⟩ + exact p.2.isLt + · intro hp + exact ⟨⟨(i.1.val, i.2.1), i.2.2.val, hp⟩, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- # Reserved payload space for each lane at an active station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring Finset + +variable {F : Type} (S : Scheme F) (r : S.format.obj) (t : ℕ) + +open scoped Classical in +/-- Returns `2 ^ t` when `Active S r s.1` holds, and `0` otherwise. -/ +def chunk (s : S.Span) : ℕ := if Active S r s.1 then 2 ^ t else 0 + +open scoped Classical in +/-- The value specified by `∑ j with j < S.spanIndex s, chunk S r t (S.hostSpan (s.1.1, j))`. -/ +def chunkStart (s : S.Span) := + ∑ j with j < S.spanIndex s, chunk S r t (S.hostSpan (s.1.1, j)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- +# Addresses in the padded terminal bank + +Compaction removes inactive stations in order. Every lane of a +surviving station has one chunk, even if the lane itself is empty. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring Finset + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {v : B S.m} + +open scoped Classical in +private abbrev Lane (S : Scheme F) (r : S.format.obj) (v : B S.m) := localLive S r v × B S.e + +open scoped Classical in +private def original (p : Lane S r v) := S.spanIndex (p.1.val.val, p.2) + +open scoped Classical in +private theorem restore (p : Lane S r v) : S.hostSpan (v, original p) = (p.1.val.val, p.2) := + (congrArg (fun j => S.hostSpan (j, original p)) p.1.property.symm).trans + (S.hostSpan_spanIndex (p.1.val.val, p.2)) + +open scoped Classical in +private def ordinalLane (S : Scheme F) (r : S.format.obj) (v : B S.m) : + Lane S r v ≃ Fin (count S r v * 2 ^ S.e) := + ((ordinal S r v).prodCongr (Equiv.refl _)).trans finProdFinEquiv + +open scoped Classical in +private theorem sum_lanes (f : B S.spanRows → ℕ) : + (∑ j, if Active S r (S.hostSpan (v, j)).1 then f j else 0) = + ∑ p : Lane S r v, f (original p) := by + rw [←sum_filter] + symm + refine sum_bij (fun p _ => original p) ?_ ?_ ?_ (fun _ _ => rfl) + · intro p _ + rw [mem_filter, restore] + exact ⟨mem_univ _, p.1.val.property⟩ + · intro p _ q _ he + have h := (restore p).symm.trans ((congrArg (fun j => S.hostSpan (v, j)) he).trans (restore q)) + exact Prod.ext (Subtype.ext (Subtype.ext (Prod.mk.inj h).1)) (Prod.mk.inj h).2 + · intro j hj + let x := S.hostSpan (v, j) + exact ⟨(⟨⟨x.1, (mem_filter.mp hj).2⟩, rfl⟩, x.2), mem_univ _, S.spanIndex_hostSpan v j⟩ + +open scoped Classical in +private theorem pair_lt {n m : ℕ} (i j : Fin n) (p q : Fin m) : + p.val + m * i.val < q.val + m * j.val ↔ i < j ∨ i = j ∧ p < q := by + rcases lt_trichotomy i j with h|rfl|h + · have := Nat.mul_le_mul_left m (show i.val + 1 ≤ j.val from h) + rw [mul_add, mul_one] at this + omega + · simp + · have := Nat.mul_le_mul_left m (show j.val + 1 ≤ i.val from h) + rw [mul_add, mul_one] at this + omega + +open scoped Classical in +private theorem lift_lt {I : Type} [Fintype I] {n : ℕ} (f : I → B n) + (hf : Function.Injective f) (i j : I) : + letI := LinearOrder.lift' f hf + let o := (Fintype.orderIsoFinOfCardEq I rfl).symm + o i < o j ↔ f i < f j := by + let : LinearOrder I := LinearOrder.lift' f hf + exact (Fintype.orderIsoFinOfCardEq I rfl).symm.lt_iff_lt + +open scoped Classical in +private theorem original_lt (p q : Lane S r v) : + original p < original q ↔ ordinalLane S r v p < ordinalLane S r v q := by + have hf : Function.Injective (localIndex S r (i := v)) := by + intro x y h + exact Subtype.ext (Subtype.ext (Prod.ext (x.property.trans y.property.symm) + ((Match.rowIndex _ _).symm.injective h))) + have h : ordinal S r v p.1 < ordinal S r v q.1 ↔ localIndex S r p.1 < localIndex S r q.1 := + lift_lt _ hf p.1 q.1 + change (p.2.val + 2 ^ S.e * (localIndex S r p.1).val < q.2.val + + 2 ^ S.e * (localIndex S r q.1).val) ↔ + (p.2.val + 2 ^ S.e * (ordinal S r v p.1).val < q.2.val + 2 ^ S.e * (ordinal S r v q.1).val) + simp only [pair_lt, h, hf.eq_iff, (ordinal S r v).injective.eq_iff] + +variable {V t : ℕ} (h : Fits S r V t) + +open scoped Classical in +theorem chunks_sum (i : B S.m) : + (∑ j, chunk S r t (S.hostSpan (i, j))) = (bank S r h).length i := by + unfold chunk + rw [sum_lanes] + simp [bank, Lane, count, pow_add, mul_assoc] + +open scoped Classical in +private theorem chunk_start (p : Lane S r v) : + chunkStart S r t (p.1.val.val, p.2) = (ordinalLane S r v p).val * 2 ^ t := by + have he : p.1.val.val.1 = v := p.1.property + simp only [chunkStart, he, sum_filter, chunk] + have swap (i : B S.spanRows) : + (if i < S.spanIndex (p.1.val.val, p.2) then if Active S r (S.hostSpan (v, + i)).1 then 2 ^ t else 0 else 0) = + if Active S r (S.hostSpan (v, i)).1 then if i < original p then 2 ^ t else 0 else 0 := by + unfold original + split_ifs <;> rfl + simp_rw [swap] + rw [sum_lanes] + simp_rw [original_lt] + rw [Equiv.sum_comp (ordinalLane S r v) (fun i => if i < ordinalLane S r v p then 2 ^ t else 0), + ←sum_filter] + rw [show (univ.filter fun i => i < ordinalLane S r v p) = Iio (ordinalLane S r v p) by ext; simp] + simp + +open scoped Classical in +theorem index_val (i : Data S r t) : + (index S r h i).2.val = chunkStart S r t (i.1.val, i.2.1) + i.2.2.val := by + let v := position S r i.1 + let p : Lane S r v := (⟨i.1, rfl⟩, i.2.1) + change (index S r h i).2.val = chunkStart S r t (p.1.val.val, p.2) + i.2.2.val + rw [chunk_start] + change i.2.2.val + 2 ^ t * i.2.1.val + 2 ^ (S.e + t) * (ordinal S r v p.1).val = + (i.2.1.val + 2 ^ S.e * (ordinal S r v p.1).val) * 2 ^ t + i.2.2.val + rw [pow_add] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- # Summing over a padded bank of station arguments -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal + +open Coloring + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {V t : ℕ} + (h : Fits S r V t) + +open scoped Classical in +/-- The value specified by `(Fmt.payload S.m V (height S t)).obj`. -/ +abbrev Tape (S : Scheme F) (V t : ℕ) := (Fmt.payload S.m V (height S t)).obj + +open scoped Classical in +/-- The condition `∀ i ∉ Set.range (bank S r h).wire, z i = false` on the specified data. -/ +def outerZero (z : Tape S V t) := ∀ i ∉ Set.range (bank S r h).wire, z i = false + +open scoped Classical in +/-- The condition `∀ i : Data S r t, S.width r (i.1.val, i.2.1) ≤ i.2.2.val → z (slot S r h i) = +false` on the specified data. -/ +def innerZero (z : Tape S V t) := + ∀ i : Data S r t, S.width r (i.1.val, i.2.1) ≤ i.2.2.val → z (slot S r h i) = false + +open scoped Classical in +theorem padded (z : S.Pin r → Bool) : + outerZero h (store S r h z) ∧ innerZero h (store S r h z) := by + refine ⟨(bank S r h).padding _, fun i hi => ?_⟩ + have he : index S r h i ∉ Set.range (place S r h) := by + rintro ⟨p, he⟩ + exact hi.not_gt ((pin_range S r h i).mp ⟨p, (index S r h).injective he⟩) + change (bank S r h).store _ ((bank S r h).wire _) = false + rw [Payload.read_store] + exact Function.extend_apply' _ _ _ he + +open scoped Classical in +theorem unpack (z : Tape S V t) (ho : outerZero h z) (hi : innerZero h z) : + z = store S r h (z ∘ wire S r h) := by + apply Payload.store_unique _ _ _ _ ho + intro j + by_cases he : j ∈ Set.range (place S r h) + · obtain ⟨p, rfl⟩ := he + rw [(place S r h).injective.extend_apply] + rfl + · rw [Function.extend_apply' _ _ _ he] + obtain ⟨i, rfl⟩ := (index S r h).surjective j + apply hi + apply le_of_not_gt + intro hb + obtain ⟨p, rfl⟩ := (pin_range S r h i).mpr hb + exact he ⟨p, rfl⟩ + +variable [Field F] + +open scoped Classical in +/-- Empty stations outside the bank are neutral. -/ +def Neutral (S : Scheme F) (r : S.format.obj) := + ∀ v, ¬Active S r v → ∀ z, S.table r v z = 1 + +open scoped Classical in +/-- Returns `∏ v : Live S r, S.table r v.val (z ∘ wire S r h ∘ S.port r v.val)` when `innerZero +h z` holds, and `0` otherwise. -/ +def localValue (z : Tape S V t) : F := + if innerZero h z then ∏ v : Live S r, S.table r v.val (z ∘ wire S r h ∘ S.port r v.val) else 0 + +open scoped Classical in +theorem localValue_store (hn : Neutral S r) (z : S.Pin r → Bool) : + localValue h (store S r h z) = ∏ v, S.table r v (z ∘ S.port r v) := by + rw [localValue, ite_eq_left (padded h z).2] + have he (v : Live S r) : store S r h z ∘ wire S r h ∘ S.port r v.val = z ∘ S.port r v.val := + funext (fun i => read_store _ _ _ _ _) + simp_rw [he] + rw [← Finset.prod_subtype (Finset.univ.filter (Active S r)) Finset.mem_filter_univ + (fun v => S.table r v (z ∘ S.port r v))] + exact Finset.prod_subset (Finset.subset_univ _) fun i _ hi => + hn i (fun ha => hi (Finset.mem_filter.mpr ⟨Finset.mem_univ i, ha⟩)) _ + +open scoped Classical in +/-- Equality checks need only be characterized on canonical encodings. +On rejected outer padding they must vanish. -/ +theorem contract (hn : Neutral S r) (x : S.exposed r → Bool) + (check : Tape S V t → F) (hmask : ∀ z, check z ≠ 0 → outerZero h z) + (he : ∀ z, check (store S r h z) = if S.Agrees r x z then 1 else 0) : + ∑ z, check z * localValue h z = S.eval r x := by + rw [← Finset.sum_subset (Finset.subset_univ (Finset.univ.image (store S r h)))] + · rw [Finset.sum_image (store_injective S r h).injOn] + unfold Scheme.eval + simp only [he, localValue_store h hn, ite_mul, one_mul, zero_mul] + · intro z _ hout + by_cases h₀ : check z = 0 + · simp only [h₀, zero_mul] + by_cases hi : innerZero h z + · exact (hout (Finset.mem_image.mpr ⟨_, Finset.mem_univ _, + (unpack h z (hmask z h₀) hi).symm⟩)).elim + · simp only [localValue, hi, ite_false, mul_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- # A shared station table on complete records of the physical bank -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Dictionary + +open Coloring Transcript +variable {F : Type} (S : Scheme F) (V t : ℕ) + +open scoped Classical in +/-- Indexes the seat by the coordinates of `Σ s : Slot (2 ^ S.m) V (height S t), Fin (capacity s +/ 2 ^ (S.e + t))`. -/ +abbrev Seat := Σ s : Slot (2 ^ S.m) V (height S t), Fin (capacity s / 2 ^ (S.e + t)) +open scoped Classical in +/-- The value specified by `Format.pair .bit (.pair (.addr S.ℓ) (.addr S.k))`. -/ +abbrev header := Format.pair .bit (.pair (.addr S.ℓ) (.addr S.k)) +open scoped Classical in +/-- The indexed operation `Fmt.pi (fun _ : Seat S V t => header S)`. -/ +abbrev headers := Fmt.pi (fun _ : Seat S V t => header S) + +open scoped Classical in +/-- Uses `⟨a.1, (finProdFinEquiv (a.2, (Match.rowIndex S.e t).symm i)).castLE +(Nat.div_mul_le_self _ _)⟩` as the representation. -/ +def port (a : Seat S V t) (i : Row S t) : Fmt.Port S.m V (height S t) := + ⟨a.1, (finProdFinEquiv (a.2, (Match.rowIndex S.e t).symm i)).castLE (Nat.div_mul_le_self _ _)⟩ + +open scoped Classical in +theorem footprint : Fintype.card (Seat S V t) * 2 ^ (S.e + t) ≤ + (Fmt.payload S.m V (height S t)).width := by + simp only [Seat, Format.width, Fmt.payload, Fmt.Port, Fintype.card_sigma, Fintype.card_fin, + Finset.sum_mul] + exact Finset.sum_le_sum fun _ _ => Nat.div_mul_le_self _ _ + +open scoped Classical in +/-- The value specified by `(false, 0, 0)`. -/ +def pad : (header S).obj := (false, 0, 0) + +open scoped Classical in +/-- The value specified by `(true, (r v.val.1).2 v.val.2.1, v.val.2.2)`. -/ +def name (r : S.format.obj) (v : Live S r) : (header S).obj := + (true, (r v.val.1).2 v.val.2.1, v.val.2.2) + +variable {S V t} {r : S.format.obj} (h : Fits S r V t) + +open scoped Classical in +/-- Embeds `Live S r` into `Seat S V t`. -/ +def seat : Live S r ↪ Seat S V t := + (serial S r).toEmbedding.trans (Function.Embedding.sigmaMap + ⟨(bank S r h).seat.write, (bank S r h).seat.injective⟩ + (fun i => Fin.castLEEmb ((Nat.le_div_iff_mul_le (Nat.two_pow_pos _)).mpr + ((bank S r h).fits i)))) + +open scoped Classical in +theorem seat_port (v : Live S r) (i : Row S t) : + port S V t (seat h v) i = slot S r h (v, i) := rfl + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def encode : (headers S V t).obj := + Function.extend (seat h) (name S r) (fun _ => pad S) + +open scoped Classical in +@[simp] theorem encode_seat (v : Live S r) : encode h (seat h v) = name S r v := + (seat h).injective.extend_apply _ _ _ + +open scoped Classical in +theorem encode_pad (a : Seat S V t) (ha : a ∉ Set.range (seat h)) : + encode h a = pad S := Function.extend_apply' _ _ _ ha + +variable [Field F] (S V t) + +open scoped Classical in +/-- The entry of type `F`, constructed using `S.decode q.2.1`. -/ +def entry (q : (header S).obj) (x : Row S t → Bool) : F := + let p := S.decode q.2.1 + let j := q.2.2 + if q.1 then + if ∀ i : Row S t, p.width j i.1 ≤ i.2.val → x i = false then + p.value j (fun s i => x (s, Fin.ofNat _ i.val)) + else 0 + else 1 + +open scoped Classical in +/-- The product of `entry S t (q a) (z ∘ port S V t a)` indexed by `a`. -/ +def weight (q : (headers S V t).obj) (z : Tape S V t) : F := + ∏ a, entry S t (q a) (z ∘ port S V t a) + +variable {S V t} + +open scoped Classical in +private theorem entry_seat (z : Tape S V t) (v : Live S r) : + entry S t (name S r v) (z ∘ port S V t (seat h v)) = + if ∀ i : Row S t, S.width r (v.val, i.1) ≤ i.2.val → z (slot S r h (v, i)) = false then + S.table r v.val (z ∘ wire S r h ∘ S.port r v.val) else 0 := by + unfold entry name + simp only [ite_true, Function.comp_apply, seat_port] + congr 1 + apply congrArg ((S.pattern r v.val).value v.val.2.2) + funext s i + have he : Fin.ofNat (2 ^ t) i.val = i.castLE (h.width (v.val, s)) := + Fin.ext (Nat.mod_eq_of_lt (lt_of_lt_of_le i.isLt (h.width (v.val, s)))) + rw [he] + rfl + +open scoped Classical in +theorem weight_encode (z : Tape S V t) : weight S V t (encode h) z = localValue h z := by + unfold weight + rw [← Finset.prod_subset (Finset.subset_univ (Finset.univ.image (seat h)))] + · rw [Finset.prod_image (seat h).injective.injOn] + simp_rw [encode_seat, entry_seat] + unfold localValue + by_cases hi : innerZero h z + · rw [ite_eq_left hi] + exact Finset.prod_congr rfl fun v _ => ite_eq_left (fun i => hi (v, i)) + · rw [ite_eq_right hi] + obtain ⟨⟨v, i⟩, hv⟩ := not_forall.mp hi + exact Finset.prod_eq_zero (Finset.mem_univ v) (ite_eq_right (fun hh => hv (hh i))) + · intro a _ ha + have he : a ∉ Set.range (seat h) := by simpa using ha + rw [encode_pad h a he] + rfl + +variable (S V t) + +open scoped Classical in +/-- The indexing data represented by `Format.pair (header S) ⟨Row S t → Bool, Row S t, +Equiv.refl _⟩`. -/ +abbrev record := Format.pair (header S) ⟨Row S t → Bool, Row S t, Equiv.refl _⟩ +open scoped Classical in +/-- The quantity computed by `(header S).width + 2 ^ (S.e + t)`. -/ +def arity := (header S).width + 2 ^ (S.e + t) +open scoped Classical in +/-- The quantity computed by `40 * ((headers S V t).width + (Fmt.payload S.m V (height S +t)).width)`. -/ +def price := 40 * ((headers S V t).width + (Fmt.payload S.m V (height S t)).width) + +omit [Field F] in +open scoped Classical in +theorem width_record : (record S t).width = arity S t := by + rw [Format.width_pair] + simp [arity, Format.width, Row, pow_add] + +open scoped Classical in +/-- The look of type `F`, constructed using `(record S t).code.symm z`. -/ +def look (z : (record S t).pins → Bool) : F := + let x := (record S t).code.symm z + entry S t x.1 x.2 + +open scoped Classical in +/-- The label of type `Table F`, constructed using `record S t`. -/ +def label : Table F := + let A := record S t + ⟨word A.width, .unit, fun x _ => look S t (bits (word A.width) x ∘ names A)⟩ + +variable {S V t} {u : ℕ} {L : Set (Table F)} + +open scoped Classical in +private theorem one (ha : arity S t ≤ u) (hl : label S t ∈ L) : + WideWeight F u L (look S t) (1 + arity S t) := by + let A := record S t + let a := word A.width + let f := fun (x : Val a) (_ : Val .unit) => look S t (bits a x ∘ names A) + have he : wd a = arity S t := (wd_word _).trans (width_record S t) + have hw : Wide F u L a .unit f (1 + wd a) := + Wide.table _ _ _ (he.le.trans ha) (.inr hl) + intro b j + refine ⟨1 + wd a, by rw [he], ?_⟩ + simpa [f, Function.comp_def] using hw.pre (rewire_reindex ((names A).symm.trans j)) + +open scoped Classical in +theorem realize (hu : 3 ≤ u) (ha : arity S t ≤ u) (hl : label S t ∈ L) : + Kernel F u L (headers S V t) (Fmt.payload S.m V (height S t)) + (weight S V t) (price S V t) := by + let A := headers S V t + let D := Fmt.payload S.m V (height S t) + let k := fun _ : Seat S V t => look S t + let read (i : Seat S V t) : (record S t).pins → (A.pins ⊕ D.pins) ⊕ Empty + | .inl p => .inl (.inl ⟨i, p⟩) + | .inr p => .inl (.inr (port S V t i p)) + have hw := Kernel.factors (A := A) (B := D) k read (fun _ => 1 + arity S t) hu + (fun _ => one ha hl) + have he (q : A.obj) (z : D.obj) : + weightedSum k read (Sum.elim (A.code q) (D.code z)) = weight S V t q z := by + unfold weightedSum weight + rw [Fintype.sum_unique] + apply Finset.prod_congr rfl + intro i _ + change entry S t ((header S).code.symm ((header S).code (q i))) _ = _ + rw [Equiv.symm_apply_apply] + rfl + simp only [he] at hw + apply hw.mono + have hb := footprint S V t + have hc := (Nat.le_mul_of_pos_right (Fintype.card (Seat S V t)) (Nat.two_pow_pos (S.e + + t))).trans hb + simp only [price, A, D, arity, headers, Fmt.width_pi, Finset.sum_const, Finset.card_univ, + Nat.nsmul_eq_mul, Fintype.card_empty, mul_add, mul_one] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Dictionary +end + +/- # Stable compaction of station headers on one host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Header + +open Coloring Dictionary +variable {F : Type} (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +/-- The quantity computed by `S.h + S.k`. -/ +abbrev n := S.h + S.k +open scoped Classical in +/-- The value specified by `Format.pair (.addr S.ℓ) (.addr S.k)`. -/ +abbrev key := Format.pair (.addr S.ℓ) (.addr S.k) +open scoped Classical in +/-- Computes the line by the application `Format.vec (n S) (header S)`. -/ +abbrev line := Format.vec (n S) (header S) +open scoped Classical in +/-- The quantity computed by `S.e + t + 1 + n S`. -/ +abbrev wordSize (t : ℕ) := S.e + t + 1 + n S + +open scoped Classical in +/-- The value specified by `((r i).2 (Match.rowIndex S.h S.k j).1, (Match.rowIndex S.h S.k +j).2)`. -/ +def labels (i : B S.m) (j : B (n S)) : (key S).obj := + ((r i).2 (Match.rowIndex S.h S.k j).1, (Match.rowIndex S.h S.k j).2) + +open scoped Classical in +/-- Returns `(true, x)` when `Nonempty (Σ s, Fin ((S.decode x.1).width x.2 s))` holds, and `pad +S` otherwise. -/ +def select (x : (key S).obj) : (header S).obj := + if Nonempty (Σ s, Fin ((S.decode x.1).width x.2 s)) then (true, x) else pad S + +open scoped Classical in +/-- The value specified by `select S ∘ labels S r i`. -/ +def row (i : B S.m) : (line S).obj := select S ∘ labels S r i + +open scoped Classical in +/-- Returns `0` when `b` holds, and `1` otherwise. -/ +def flag (b : Bool) : B 1 := if b then 0 else 1 + +open scoped Classical in +/-- Evaluates `flag (x j).1` at the input `j`. -/ +def keys (x : (line S).obj) := fun j => flag (x j).1 + +open scoped Classical in +/-- The value specified by `x ∘ Coloring.order (keys S x)`. -/ +def pack (x : (line S).obj) := x ∘ Coloring.order (keys S x) + +open scoped Classical in +/-- Returns `⟨2 ^ (S.e + t), Nat.pow_lt_pow_right (by decide) (by omega)⟩` when `b` holds, and +`0` otherwise. -/ +def amount (t : ℕ) (b : Bool) : B (S.e + t + 1) := + if b then ⟨2 ^ (S.e + t), Nat.pow_lt_pow_right (by decide) (by omega)⟩ else 0 + +open scoped Classical in +/-- The quantity computed by `total (n S) (S.e + t + 1) (fun j => amount S t (x j).1)`. -/ +def length (t : ℕ) (x : (line S).obj) := total (n S) (S.e + t + 1) (fun j => amount S t (x j).1) + +variable {S r} {i : B S.m} + +open scoped Classical in +theorem local_inj : Function.Injective (localIndex S r (i := i)) := by + intro a b h + exact Subtype.ext (Subtype.ext (Prod.ext (a.2.trans b.2.symm) + ((Match.rowIndex _ _).symm.injective h))) + +open scoped Classical in +private theorem row_live (v : localLive S r i) : + row S r i (localIndex S r v) = name S r v.val := by + rcases v with ⟨⟨⟨a, b⟩, hv⟩, rfl⟩ + simp only [row, Function.comp_apply, labels, localIndex, Equiv.apply_symm_apply] + exact ite_eq_left hv + +open scoped Classical in +private theorem row_other (j : B (n S)) (hj : j ∉ Set.range (localIndex S r (i := i))) : + row S r i j = pad S := by + apply ite_eq_right + intro hv + exact hj ⟨⟨⟨(i, Match.rowIndex S.h S.k j), hv⟩, rfl⟩, (Match.rowIndex _ _).symm_apply_apply j⟩ + +open scoped Classical in +private theorem marked (j : B (n S)) : + keys S (row S r i) j = 0 ↔ j ∈ Set.range (localIndex S r (i := i)) := by + by_cases hj : j ∈ Set.range (localIndex S r (i := i)) + · obtain ⟨v, rfl⟩ := hj + simp [keys, row_live, name, flag] + · simp [keys, row_other j hj, pad, flag, hj] + +open scoped Classical in +theorem length_row (t : ℕ) (i : B S.m) : + (length S t (row S r i)).val = count S r i * 2 ^ (S.e + t) := by + change ∑ j, (amount S t (row S r i j).1).val = _ + rw [← Finset.sum_subset (Finset.subset_univ (Finset.univ.image (localIndex S r (i := i))))] + · rw [Finset.sum_image local_inj.injOn] + simp [row_live, name, amount, count] + · intro j _ hj + have ho : j ∉ Set.range (localIndex S r (i := i)) := by simpa using hj + rw [row_other j ho] + rfl + +open scoped Classical in +private theorem rank_index {I : Type} [Fintype I] {m : ℕ} (f : B m → B 1) + (index : I → B m) (hindex : Function.Injective index) + (h : ∀ u, f (index u) = 0) (hc : Control.histogram f 0 none = Fintype.card I) (v : I) : + letI := LinearOrder.lift' index hindex + ((Coloring.order f).symm (index v)).val = ((Fintype.orderIsoFinOfCardEq I rfl).symm v).val := by + let a := f ∘ Coloring.order f + let j := (Coloring.order f).symm (index v) + have hj : a j = 0 := by simp [a, j, h] + have hz : a 0 = a j := by + refine le_antisymm (order_mono f (Fin.zero_le j)) ?_ + change a j ≤ a 0 + rw [hj] + exact Fin.zero_le _ + have hl : leader a j = 0 := + le_antisymm ((leader_spec a (order_mono f) j).2 0 hz) (Fin.zero_le _) + let g (u : I) : Fin (Fintype.card I) := ⟨Control.rank f (index u), by + simpa only [h, hc] using Control.rank_lt f (index u)⟩ + let _ : LinearOrder I := LinearOrder.lift' _ hindex + let e := Fintype.orderIsoFinOfCardEq (I) rfl + have hm : StrictMono (g ∘ e) := fun x y hxy => + Control.rank_mono f ((h _).trans (h _).symm) (e.strictMono hxy) + have he := congrFun hm.eq_id (e.symm v) + simp only [Function.comp_apply, OrderIso.apply_symm_apply, id_eq] at he + change j.val = (e.symm v).val + rw [← he] + change _ = Control.rank f (index v) + rw [← groupRank_val] + change _ = (j - leader a j).val + rw [hl, sub_zero] + +open scoped Classical in +private theorem rank_live (v : localLive S r i) : + ((Coloring.order (keys S (row S r i))).symm (localIndex S r v)).val = + (ordinal S r i v).val := by + let f := keys S (row S r i) + have h (u : localLive S r i) : f (localIndex S r u) = 0 := (marked _).mpr ⟨u, rfl⟩ + have hc : Control.histogram f 0 none = count S r i := by + rw [Control.histogram_none] + have he : Finset.univ.filter (fun j => f j = 0) = Finset.univ.image (localIndex S r (i := i)) + := by + ext j + simpa only [Finset.mem_filter_univ, Finset.mem_image, Finset.mem_univ, true_and, + Set.mem_range] + using (marked (S:=S) (r:=r) (i := i) j) + rw [he, Finset.card_image_of_injective _ local_inj] + rfl + exact rank_index f (localIndex S r) local_inj h hc v + +open scoped Classical in +theorem pack_live (v : localLive S r i) (j : B (n S)) (hj : j.val = (ordinal S r i v).val) : + pack S (row S r i) j = name S r v.val := by + have he := Fin.ext (hj.trans (rank_live v).symm) + rw [pack, Function.comp_apply, he, Equiv.apply_symm_apply, row_live] + +open scoped Classical in +theorem pack_other (j : B (n S)) (hj : ∀ v : localLive S r i, j.val ≠ (ordinal S r i v).val) : + pack S (row S r i) j = pad S := by + apply row_other + rintro ⟨v, hv⟩ + apply hj v + rw [← rank_live v, hv, Equiv.symm_apply_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Header +end + +/- # Distributing station headers into the physical dictionary -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Header +open Coloring Transcript Dictionary +variable {F : Type} (S : Scheme F) (V t : ℕ) + +open scoped Classical in +/-- Computes the source by the application `Redistribute.input S.m (wordSize S t) (line S)`. -/ +abbrev source := Redistribute.input S.m (wordSize S t) (line S) +open scoped Classical in +/-- Computes the dest by the application `Redistribute.output S.m V (height S t) (line S)`. -/ +abbrev dest := Redistribute.output S.m V (height S t) (line S) + +open scoped Classical in +/-- The indexed operation `(fun i => length S t (row S r i), fun i => pack S (row S r i))`. -/ +def paired (r : S.format.obj) : (source S t).obj := + (fun i => length S t (row S r i), fun i => pack S (row S r i)) + +open scoped Classical in +theorem limit (a : Slot (2 ^ S.m) V (height S t)) : + capacity a / 2 ^ (S.e + t) ≤ 2 ^ (n S) := by + have he : capacity a ≤ 2 ^ (n S) * 2 ^ (S.e + t) := by + rw [← pow_add] + exact Nat.pow_le_pow_right (by decide) (Nat.le_of_lt_succ a.1.isLt) + exact Nat.div_le_of_le_mul (by simpa only [mul_comm] using he) + +open scoped Classical in +/-- Computes the pick by the application `a.2.castLE (limit S V t a.1)`. -/ +def pick (a : Seat S V t) : B (n S) := a.2.castLE (limit S V t a.1) + +open scoped Classical in +/-- Computes the cut by the application `z a.1 (pick S V t a)`. -/ +def cut (z : (dest S V t).obj) (a : Seat S V t) := z a.1 (pick S V t a) + +open scoped Classical in +/-- The indexed operation `cut S V t (Redistribute.eval (line S) (fun _ => pad S) (paired S t +r))`. -/ +def eval (r : S.format.obj) : (headers S V t).obj := + cut S V t (Redistribute.eval (line S) (fun _ => pad S) (paired S t r)) + +open scoped Classical in +theorem width_dest : (dest S V t).width ≤ (height S t + 1) * (2 ^ S.m * (line S).width) := by + simp only [dest, Redistribute.output, Fmt.width_pi, Finset.sum_const, Finset.card_univ, + Nat.nsmul_eq_mul, ← mul_assoc] + exact Nat.mul_le_mul_right _ (Transcript.card_slots _ _ _) + +open scoped Classical in +theorem width_headers : (headers S V t).width ≤ (dest S V t).width := by + simp only [headers, dest, Redistribute.output, Fmt.width_pi, line, Format.width_vec] + rw [Fintype.sum_sigma] + apply Finset.sum_le_sum + intro a _ + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, Nat.nsmul_eq_mul] + exact Nat.mul_le_mul_right _ (limit S V t a) + +variable {S V t} {r : S.format.obj} (h : Fits S r V t) + +open scoped Classical in +theorem correct : eval S V t r = encode h := by + unfold eval + rw [Redistribute.correct (bank S r h) _ _ _ (length_row t)] + funext a + simp only [cut] + by_cases he : a ∈ Set.range (seat h) + · obtain ⟨v, rfl⟩ := he + have hs : (bank S r h).seat.read (seat h v).1 = some (position S r v) := + ((bank S r h).seat.valid _ _).mpr rfl + rw [hs, encode_seat] + exact pack_live (⟨v, rfl⟩ : localLive S r (position S r v)) _ rfl + · rw [encode_pad h a he] + cases hs : (bank S r h).seat.read a.1 with + | none => rfl + | some i => + refine pack_other (S:=S) (r:=r) (i := i) (pick S V t a) ?_ + rintro ⟨v, rfl⟩ hv + apply he + have hf : (seat h v).1 = a.1 := (((bank S r h).seat.valid _ _).mp hs).symm + exact ⟨v, Sigma.ext hf ((Fin.heq_ext_iff (congrArg (fun s => capacity s / 2 ^ (S.e + + t)) hf)).mpr hv.symm)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Header +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/Outer.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/Outer.lean new file mode 100644 index 0000000000..0e2648c45d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/Outer.lean @@ -0,0 +1,1010 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.DictionaryHeaders +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanTiles +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Keys +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.OuterRows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.ContractRates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.BoardPush +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep + +/-! Permute whole padded chunks, fixing each zero-width or exterior span. -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring + +variable {F : Type} (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +/-- Returns `s` when `S.width r s = 0` holds, and `(S.peer r s).getD s` otherwise. -/ +def partner (s : S.Span) := if S.width r s = 0 then s else (S.peer r s).getD s + +open scoped Classical in +theorem partner_edge {s v : S.Span} (h : S.peer r s = some v) (hw : 0 < S.width r s) : + partner S r s = v := by simp [partner, h, hw.ne'] + +open scoped Classical in +theorem partner_cases (s : S.Span) : partner S r s = s ∨ + (S.peer r s = some (partner S r s) ∧ 0 < S.width r s) := by + by_cases h : S.width r s = 0 + · exact .inl (ite_eq_left h) + cases hs : S.peer r s with + | none => simp [partner, h, hs] + | some v => exact .inr ⟨by simp [partner, h, hs], Nat.pos_of_ne_zero h⟩ + +open scoped Classical in +theorem partner_width (ok : S.Proper r) (s : S.Span) : S.width r (partner S r s) = S.width r s := by + rcases partner_cases S r s with h|⟨h, _⟩ + · rw [h] + · exact (ok _ _ h).2.1.symm + +open scoped Classical in +theorem partner_inv (ok : S.Proper r) : Function.Involutive (partner S r) := by + intro s + rcases partner_cases S r s with h|⟨h, hp⟩ + · rw [h, h] + · exact partner_edge _ _ (ok _ _ h).1 ((partner_width S r ok s).symm ▸ hp) + +open scoped Classical in +theorem partner_live (ok : S.Proper r) (s : S.Span) (h : Active S r s.1) : + Active S r (partner S r s).1 := by + rcases partner_cases S r s with he|⟨_, hp⟩ + · rwa [he] + · exact ⟨(partner S r s).2, 0, (partner_width S r ok s).symm ▸ hp⟩ + +open scoped Classical in +theorem partner_chunk (ok : S.Proper r) (t : ℕ) (s : S.Span) : + chunk S r t (partner S r s) = chunk S r t s := by + have hi : Active S r (partner S r s).1 ↔ Active S r s.1 := + ⟨fun h => by simpa only [partner_inv S r ok s] using partner_live S r ok _ h, + partner_live S r ok s⟩ + simp only [chunk, hi] + +variable (t : ℕ) {w z : ℕ} + +open scoped Classical in +/-- The condition `∀ s, (a s.1.1 (S.spanIndex s)).2.1.val = chunk S r t s` on the specified +data. -/ +def Lengths (a : SpanPlan.Entries S.m w z S.spanRows) : Prop := + ∀ s, (a s.1.1 (S.spanIndex s)).2.1.val = chunk S r t s + +open scoped Classical in +/-- The value specified by `(Match.rowIndex S.m z).symm (s.1.1, (a s.1.1 (S.spanIndex s)).1)`. -/ +def endpoint (a : SpanPlan.Entries S.m w z S.spanRows) (s : S.Span) := + (Match.rowIndex S.m z).symm (s.1.1, (a s.1.1 (S.spanIndex s)).1) + +open scoped Classical in +/-- The data for the inner construction, including `S.spanRows)`, `bij`, `lengths`, `paired`, +`order`. -/ +structure Inner (peer : B (S.m + z) → B (S.m + z)) (send take : SpanPlan.Entries S.m w z + S.spanRows) : Prop where + bij : Function.Bijective peer + lengths : Lengths S r t send + paired : ∀ s, send s.1.1 (S.spanIndex s) = + ((take s.1.1 (S.spanIndex s)).1, (take s.1.1 (S.spanIndex s)).2.1, S.spanIndex (partner S r s)) + order : ∀ s, (take s.1.1 (S.spanIndex s)).2.2 = S.spanIndex s + contacts : ∀ s, 0 < chunk S r t s → peer (endpoint S send s) = endpoint S take (partner S r s) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- The two sides of each contact reserve the same space in destination order. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Inner +open Coloring + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {t w z : ℕ} + {peer : B (S.m + z) → B (S.m + z)} {send take : SpanPlan.Entries S.m w z S.spanRows} + (h : Inner S r t peer send take) (ok : S.Proper r) + +/-- Computes the src by the application `Match.rowIndex S.m z`. -/ +abbrev src (S : Scheme F) (z : ℕ) := Match.rowIndex S.m z +/-- The value specified by `(Equiv.ofBijective peer h.bij).trans (src S z)`. -/ +def dst := (Equiv.ofBijective peer h.bij).trans (src S z) + +local notation "A" => Equiv.toEmbedding (src S z) +local notation "D" => Equiv.toEmbedding (dst h) +local notation "L" => SpanPlan.offsets ∘ send +local notation "R" => SpanPlan.offsets ∘ take + +include h +theorem target_lengths : Lengths S r t take := by + intro s + have hh := h.lengths s + rwa [h.paired] at hh + +theorem send_order (s : S.Span) : + (send s.1.1 (S.spanIndex s)).2.2 = S.spanIndex (partner S r s) := by rw [h.paired] + +theorem taken (s : S.Span) (hs : 0 < chunk S r t s) : + h.dst (endpoint S send s) = + ((partner S r s).1.1, (take (partner S r s).1.1 (S.spanIndex (partner S r s))).1) := by + change src S z (peer (endpoint S send s)) = _ + rw [h.contacts s hs] + exact (src S z).apply_symm_apply _ + +theorem target_unique (v : B S.m) : SpanPlan.Unique (SpanPlan.offsets (take v)) := by + have key (i : B S.spanRows) : (take v i).2.2 = i := by + simpa only [Scheme.hostSpan_owner, Scheme.spanIndex_hostSpan] using h.order (S.hostSpan (v, i)) + intro i j _ _ _ he + exact (key i).symm.trans (he.trans (key j)) + +omit h in +private theorem source_endpoint (e : B (S.m + z)) (i : B S.spanRows) + (hi : SpanPlan.port ((L) (src S z e).1) i = (src S z e).2) : + endpoint S send (S.hostSpan ((src S z e).1, i)) = e := by + simp only [endpoint, Scheme.hostSpan_owner, Scheme.spanIndex_hostSpan] + change (send _ _).1 = _ at hi + rw [hi] + exact (src S z).symm_apply_apply _ + +theorem is_pair {e : B (S.m + z)} {i j : B S.spanRows} (q : SpanPlan.Paired le_rfl A D (L) (R) e i + j) : + partner S r (S.hostSpan ((src S z e).1, i)) = S.hostSpan ((h.dst e).1, j) := by + let s := S.hostSpan ((src S z e).1, i) + have hp : 0 < chunk S r t s := by + rw [← h.lengths s, S.spanIndex_hostSpan] + exact q.left + have he := h.taken s hp + rw [source_endpoint (send := send) e i q.source] at he + let v := S.hostSpan ((h.dst e).1, j) + have ho : S.spanIndex (partner S r s) = S.spanIndex v := by + rw [← h.send_order, ← h.order v] + simp only [s, v, Scheme.hostSpan_owner, Scheme.spanIndex_hostSpan] + exact q.order + exact S.hostSpan.symm.injective (Prod.ext (congrArg Prod.fst he).symm ho) + +include ok +theorem source_unique (v : B S.m) : SpanPlan.Unique (SpanPlan.offsets (send v)) := by + intro i j hi hj hc ho + let s := S.hostSpan (v, i) + let u := S.hostSpan (v, j) + have hs : 0 < chunk S r t s := by rw [← h.lengths s, S.spanIndex_hostSpan]; exact hi + have hu : 0 < chunk S r t u := by rw [← h.lengths u, S.spanIndex_hostSpan]; exact hj + have hh : endpoint S send s = endpoint S send u := by + simp only [endpoint, s, u, Scheme.hostSpan_owner, Scheme.spanIndex_hostSpan] + exact congrArg (fun a => (src S z).symm (v, a)) hc + have ha := (h.taken s hs).symm.trans ((congrArg h.dst hh).trans (h.taken u hu)) + have hb : S.spanIndex (partner S r s) = S.spanIndex (partner S r u) := by + rw [← h.send_order, ← h.send_order] + simp only [s, u, Scheme.hostSpan_owner, Scheme.spanIndex_hostSpan] + exact ho + have hv : (partner S r s).1.1 = (partner S r u).1.1 := by + have eq := congrArg Prod.fst ha + exact eq + have eq : partner S r s = partner S r u := + S.hostSpan.symm.injective (Prod.ext hv hb) + exact congrArg Prod.snd (S.hostSpan.injective ((partner_inv S r ok).injective eq)) + +theorem matched : SpanPlan.Match le_rfl A D (L) (R) := by + intro e o + let x := SpanPlan.offsets (send (src S z e).1) + let y := SpanPlan.offsets (take (h.dst e).1) + change SpanPlan.amount x (src S z e).2 o = SpanPlan.amount y (h.dst e).2 o + have equal (s : S.Span) (hs : 0 < chunk S r t s) + (he : endpoint S send s = e) (ho : S.spanIndex (partner S r s) = o) : + SpanPlan.amount x (src S z e).2 o = SpanPlan.amount y (h.dst e).2 o := by + have hv := h.taken s hs + rw [he] at hv + have hu : src S z e = (s.1.1, (send s.1.1 (S.spanIndex s)).1) := by + rw [← he]; exact (src S z).apply_symm_apply _ + let a := partner S r s + have A₁ := SpanPlan.amount_at _ (h.source_unique ok s.1.1) (S.spanIndex s) (hs.trans_eq + (h.lengths s).symm) + have A₂ := SpanPlan.amount_at _ (h.target_unique a.1.1) (S.spanIndex a) + ((hs.trans_eq (partner_chunk S r ok t s).symm).trans_eq (h.target_lengths a).symm) + unfold x y + rw [hu, hv, ← ho] + simp only [SpanPlan.port, SpanPlan.pos, SpanPlan.len, SpanPlan.offsets] at A₁ A₂ + rw [h.send_order s, h.lengths s] at A₁ + rw [h.order a, h.target_lengths a, partner_chunk S r ok] at A₂ + exact A₁.trans A₂.symm + by_cases hs : 0 < SpanPlan.amount x (src S z e).2 o + · obtain ⟨i, hi, hc, ho⟩ := SpanPlan.amount_pos _ _ _ hs + let s := S.hostSpan ((src S z e).1, i) + refine equal s ?_ (source_endpoint (send := send) _ _ hc) ?_ + · rwa [← h.lengths s, S.spanIndex_hostSpan] + · rwa [← h.send_order, S.spanIndex_hostSpan] + by_cases ht : 0 < SpanPlan.amount y (h.dst e).2 o + · obtain ⟨i, hi, hc, ho⟩ := SpanPlan.amount_pos _ _ _ ht + let u := S.hostSpan ((h.dst e).1, i) + let s := partner S r u + have hp : 0 < chunk S r t s := by + rw [partner_chunk S r ok, ← h.target_lengths u, S.spanIndex_hostSpan] + exact hi + have hv : partner S r s = u := partner_inv S r ok u + apply equal s hp + · apply h.dst.injective + rw [h.taken s hp, hv, S.spanIndex_hostSpan] + exact Prod.ext rfl hc + · rw [hv, ← h.order u, S.spanIndex_hostSpan] + exact ho + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Inner +end + +/- Matching full padded chunks is exactly the internal-wire condition. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {t V : ℕ} + +open scoped Classical in +/-- The value specified by `(i.1.val, i.2.1)`. -/ +def segment (i : Data S r t) : S.Span := (i.1.val, i.2.1) + +open scoped Classical in +/-- The mate of type `Data S r t`, constructed using `partner S r (segment i)`. -/ +def mate (ok : S.Proper r) (i : Data S r t) : Data S r t := + let u := partner S r (segment i) + (⟨u.1, partner_live _ _ ok _ i.1.property⟩, u.2, i.2.2) + +open scoped Classical in +theorem data_ext {a b : Data S r t} (hs : segment a = segment b) (hi : a.2.2 = b.2.2) : a = b := + Prod.ext (Subtype.ext (congrArg Prod.fst hs)) (Prod.ext (congrArg Prod.snd hs) hi) + +open scoped Classical in +theorem mate_inv (ok : S.Proper r) : Function.Involutive (mate (t := t) ok) := + fun i => data_ext (partner_inv S r ok (segment i)) rfl + +variable (h : Fits S r V t) (ok : S.Proper r) + +open scoped Classical in +theorem mate_join (i j : S.Pin r) (e : S.Joins r i j) : mate ok (pin S r h i) = pin S r h j := + data_ext (partner_edge S r e.1 (Nat.zero_lt_of_lt i.2.isLt)) (Fin.ext e.2) + +open scoped Classical in +theorem mate_iff (a : S.Pin r → Bool) : + (∀ i, store S r h a (slot S r h i) = store S r h a (slot S r h (mate ok i))) ↔ + ∀ i j, S.Joins r i j → a i = a j := by + constructor + · intro eq i j he + have e := eq (pin S r h i) + rw [mate_join h ok i j he] at e + exact (read_store S r h a i).symm.trans (e.trans (read_store S r h a j)) + · intro eq i + by_cases hi : i ∈ Set.range (pin S r h) + · obtain ⟨p, rfl⟩ := hi + rcases partner_cases S r p.1 with he|⟨he, _⟩ + · rw [show mate ok (pin S r h p) = pin S r h p from data_ext he rfl] + · let q : S.Pin r := ⟨partner S r p.1, p.2.cast (partner_width S r ok p.1).symm⟩ + have e : S.Joins r p q := ⟨he, rfl⟩ + rw [mate_join h ok p q e] + exact (read_store S r h a p).trans ((eq p q e).trans (read_store S r h a q).symm) + · have le : S.width r (segment i) ≤ i.2.2.val := le_of_not_gt (mt (pin_range S r h i).mpr hi) + have le' : S.width r (partner S r (segment i)) ≤ i.2.2.val + := (partner_width S r ok _).trans_le le + exact ((padded h a).2 i le).trans ((padded h a).2 (mate ok i) le').symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- Turning length declarations into actual addresses in the padded argument bank. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {t V w z : ℕ} + +open scoped Classical in +theorem segment_lt (i : Data S r t) : i.2.2.val < chunk S r t (segment i) := by + rw [chunk, ite_eq_left (show Active S r (segment i).1 from i.1.property)] + exact i.2.2.isLt + +open scoped Classical in +/-- The cell of type `Data S r t`, constructed using `by by_contra he; simp [chunk, he] at hj`. -/ +def cell (s : S.Span) (j : ℕ) (hj : j < chunk S r t s) : Data S r t := + let hp : Active S r s.1 := by by_contra he; simp [chunk, he] at hj + (⟨s.1, hp⟩, s.2, ⟨j, by simpa only [chunk, ite_eq_left hp] using hj⟩) + +namespace Lengths +variable {a : SpanPlan.Entries S.m w z S.spanRows} (hl : Lengths S r t a) + (h : Fits S r V t) (hw : height S t < w) +include hl + +open scoped Classical in +theorem at_row (v : B S.m) (j : B S.spanRows) : + (a v j).2.1.val = chunk S r t (S.hostSpan (v, j)) := by + simpa only [Scheme.hostSpan_owner, Scheme.spanIndex_hostSpan] using hl (S.hostSpan (v, j)) + +open scoped Classical in +theorem sum (v : B S.m) : (∑ j, (a v j).2.1.val) = (bank S r h).length v := by + simp_rw [hl.at_row] + exact chunks_sum h v + +include h hw + +open scoped Classical in +theorem small (v : B S.m) : (∑ j, (a v j).2.1.val) < 2 ^ w := + (hl.sum h v).trans_lt (((bank S r h).longest v).trans_lt (Nat.pow_lt_pow_right (by decide) hw)) + +open scoped Classical in +theorem total (v : B S.m) : (SpanPlan.total (a v)).val = (bank S r h).length v := + (SpanPlan.total_val _ (hl.small h hw v)).trans (hl.sum h v) + +open scoped Classical in +theorem offset (s : S.Span) : + SpanPlan.offset (SpanPlan.offsets (a s.1.1)) (S.spanIndex s) = chunkStart S r t s := by + change ((SpanPlan.offsets (a s.1.1) (S.spanIndex s)).2.2.2).val = _ + rw [SpanPlan.offset_val _ (hl.small h hw _)] + simp_rw [hl.at_row] + rfl + +open scoped Classical in +theorem offset_row (v : B S.m) (j : B S.spanRows) : + SpanPlan.offset ((SpanPlan.offsets ∘ a) v) j = chunkStart S r t (S.hostSpan (v, j)) := by + simpa only [Scheme.hostSpan_owner, Scheme.spanIndex_hostSpan, Function.comp_apply] using + hl.offset h hw (S.hostSpan (v, j)) + +open scoped Classical in +theorem covers : SpanPlan.Covers (bank S r h) (SpanPlan.offsets ∘ a) := by + intro v j hj + obtain ⟨i, hi⟩ := (index S r h).surjective ⟨v, j, hj⟩ + have hv : (segment i).1.1 = v := congrArg Sigma.fst hi + have ho : (index S r h i).2.val = j := congrArg (fun b => b.2.val) hi + rw [← hv] + refine ⟨S.spanIndex (segment i), i.2.2.val, ?_, ?_⟩ + · exact (segment_lt i).trans_eq (hl _).symm + · rw [Function.comp_apply, hl.offset h hw] + exact (index_val h i).symm.trans ho + +open scoped Classical in +theorem side (place : B (S.m + z) ≃ B S.m × B z) (hu : ∀ v, + SpanPlan.Unique (SpanPlan.offsets (a v))) : + SpanPlan.Side (bank S r h) le_rfl place.toEmbedding (SpanPlan.offsets ∘ a) := by + let length (v : B S.m) (i : B S.spanRows) := (a v i).2.1.val + have address (v i) : SpanPlan.offset ((SpanPlan.offsets ∘ a) v) i + = Routing.offset (length v) Fin.val i := + SpanPlan.offset_val _ (hl.small h hw v) i + refine ⟨?_, hu, ?_, ?_, ?_⟩ + · intro v c + exact (Finset.sum_le_sum_of_subset (Finset.subset_univ _)).trans_lt (hl.small h hw v) + · intro v i hi + rw [address, ← hl.sum h v] + change Routing.offset (length v) Fin.val i + length v i ≤ ∑ k, length v k + have hp : 0 < length v i := hi + have lt := (Routing.offsetIndex (length v) Fin.val ⟨i, _, Nat.sub_lt hp Nat.one_pos⟩).isLt + change Routing.offset (length v) Fin.val i + (length v i - 1) < _ at lt + omega + · intro v i j k l hk hl' he + rw [address, address] at he + let order := Routing.pack (length v) Fin.val (fun _ _ _ _ eq => Fin.ext eq) + have eq : order ⟨i, k, hk⟩ = order ⟨j, l, hl'⟩ := Fin.ext he + exact congrArg Sigma.fst (order.injective eq) + · intro v j _ + exact ⟨place.symm (v, (a v j).1), congrArg Prod.fst (place.apply_symm_apply _), + congrArg Prod.snd (place.apply_symm_apply _)⟩ + +end Lengths +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- Each physical transmission carries one padded bit to its partner. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Inner +open Coloring + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {t V w z : ℕ} + {peer : B (S.m + z) → B (S.m + z)} {send take : SpanPlan.Entries S.m w z S.spanRows} + (h : Inner S r t peer send take) (ok : S.Proper r) (fit : Fits S r V t) (hw : height S t < w) + +open scoped Classical in +/-- The traffic of type `Payload.Traffic (bank S r fit) (bank S r fit) (2 ^ z)` for the given +inputs. -/ +def traffic : Payload.Traffic (bank S r fit) (bank S r fit) (2 ^ z) := + SpanPlan.traffic (h.lengths.side fit hw (src S z) (h.source_unique ok)) + (h.target_lengths.side fit hw h.dst h.target_unique) (h.matched ok) + (h.target_lengths.covers fit hw) + +open scoped Classical in +theorem valid : Payload.Script.Valid (h.traffic ok fit hw) le_rfl (SpanPlan.emit peer (send, take)) + := by + refine SpanPlan.valid _ _ _ _ _ _ _ (h.lengths.total fit hw) (h.target_lengths.total fit hw) ?_ + intro e _ + change peer ((src S z).symm (src S z e)) = (src S z).symm (src S z (peer e)) + simp + +open scoped Classical in +private theorem eq_bit {m V k : ℕ} (P : Payload m V k) {a b : P.Bit} + (he : a.1 = b.1) (hb : a.2.val = b.2.val) : a = b := + Sigma.ext he ((Fin.heq_ext_iff (congrArg _ he)).mpr hb) + +open scoped Classical in +theorem carries_bit (e : B (S.m + z)) (i : Fin ((h.traffic ok fit hw).length e)) : + ∃ a : Data S r t, (h.traffic ok fit hw).source e i = index S r fit a ∧ + (h.traffic ok fit hw).target e i = index S r fit (mate ok a) := by + obtain ⟨u, v, j, q, hj, hs, hd⟩ := SpanPlan.transmission + (h.lengths.side fit hw (src S z) (h.source_unique ok)) + (h.target_lengths.side fit hw h.dst h.target_unique) (h.matched ok) + (h.target_lengths.covers fit hw) e i + let s := S.hostSpan ((src S z e).1, u) + let a := cell s j (hj.trans_eq (h.lengths.at_row _ _)) + have he : partner S r s = S.hostSpan ((h.dst e).1, v) := h.is_pair q + refine ⟨a, ?_, ?_⟩ + · have hi := index_val fit a + change _ = chunkStart S r t s + j at hi + rw [h.lengths.offset_row fit hw] at hs + exact eq_bit (bank S r fit) rfl (hs.trans hi.symm) + · have hv : (h.dst e).1 = (index S r fit (mate ok a)).1 := + (congrArg (fun t : S.Span => t.1.1) he).symm + have hi := index_val fit (mate ok a) + change _ = chunkStart S r t (partner S r s) + j at hi + rw [he] at hi + rw [h.target_lengths.offset_row fit hw] at hd + exact eq_bit (bank S r fit) hv (hd.trans hi.symm) + +local notation "P" => PeerLayout.S S.m V (height S t) S.m V (height S t) (2 ^ z) +local notation "C" => Payload.Script.decode le_rfl (SpanPlan.emit peer (send, take)) + +include h hw in +open scoped Classical in +theorem carries (a : Tape S V t) : + (P).Carries C a a ↔ outerZero fit a ∧ ∀ i, a (slot S r fit i) = a (slot S r fit (mate ok i)) + := by + let M := h.traffic ok fit hw + rw [(h.valid ok fit hw).carries] + change M.links.Matches a a ↔ _ + unfold Bank.Links.Matches + simp only [show ∀ i, M.links.pad i = true ↔ i ∉ Set.range (bank S r fit).wire from + fun _ => decide_eq_true_iff] + apply and_congr_right + intro _ + change (∀ e j, a ((bank S r fit).wire (M.source e j)) = a ((bank S r fit).wire (M.target e j))) + ↔ _ + constructor + · intro eq i + obtain ⟨e, j, hj⟩ := M.covers (index S r fit (mate ok i)) + change M.target e j = _ at hj + obtain ⟨b, hb, hb'⟩ := h.carries_bit ok fit hw e j + have eq' := eq e j + rw [hb, hb'] at eq' + have he : b = i := (mate_inv ok).injective ((index S r fit).injective (hb'.symm.trans hj)) + rwa [he] at eq' + · intro eq e j + obtain ⟨i, hi, hi'⟩ := h.carries_bit ok fit hw e j + rw [hi, hi'] + exact eq i + +include h hw ok in +open scoped Classical in +theorem carries_store (a : S.Pin r → Bool) : + (P).Carries C (store S r fit a) (store S r fit a) ↔ ∀ i j, S.Joins r i j → a i = a j := by + rw [h.carries ok fit hw, and_iff_right (padded fit a).1, mate_iff] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Inner +end + +/- # Projecting the terminal assignment to its exterior payload -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Outer +open Coloring + +variable {F : Type} {S : Scheme F} {r : S.format.obj} + {V t V' k' w z : ℕ} (h : Fits S r V t) (hx : S.Fits r V' k') + +open scoped Classical in +private def fromBank (i : (S.payload r hx).Bit) := + place S r h ((S.index r hx).symm i).val + +open scoped Classical in +private theorem from_host (i : (S.payload r hx).Bit) : (fromBank h hx i).1 = i.1 := by + obtain ⟨i, rfl⟩ := (S.index r hx).surjective i + rw [fromBank, Equiv.symm_apply_apply] + rfl + +open scoped Classical in +private def send (v : B S.m) : Fin (S.load r v) ↪ Fin ((bank S r h).length v) where + toFun i := ⟨(fromBank h hx ⟨v, i⟩).2.val, by + have := (fromBank h hx ⟨v, i⟩).2.isLt + exact this.trans_eq (congrArg _ (from_host h hx ⟨v, i⟩))⟩ + inj' i j he := by + have eq : fromBank h hx ⟨v, i⟩ = fromBank h hx ⟨v, j⟩ := by + have e := (from_host h hx ⟨v, i⟩).trans (from_host h hx ⟨v, j⟩).symm + exact Sigma.ext e ((Fin.heq_ext_iff (congrArg _ e)).mpr (congrArg Fin.val he)) + have hv := (S.index r hx).symm.injective (Subtype.ext ((place S r h).injective eq)) + exact eq_of_heq (Sigma.mk.inj hv).2 + +open scoped Classical in +private def post (m : ℕ) : B m ↪ B m × Fin 1 := + ⟨fun v => (v, 0), fun _ _ he => congrArg Prod.fst he⟩ + +open scoped Classical in +private def traffic : Payload.Traffic (bank S r h) (S.payload r hx) 1 where + E := B S.m + src := post _ + dst := post _ + length := S.load r + send := send h hx + get _ := .refl _ + disjoint_send i j a b he hv := by + change i = j at he + subst j + exact ⟨rfl, congrArg Fin.val ((send h hx i).injective (Fin.ext hv))⟩ + disjoint_get _ _ _ _ he hv := ⟨he, hv⟩ + covers i := ⟨i.1, i.2, rfl⟩ + +open scoped Classical in +private theorem transfer (v : B S.m) (i : Fin (S.load r v)) : + fromBank h hx ((traffic h hx).target v i) = (traffic h hx).source v i := + Sigma.ext (from_host h hx ⟨v, i⟩) + ((Fin.heq_ext_iff (congrArg _ (from_host h hx ⟨v, i⟩))).mpr rfl) + +open scoped Classical in +private theorem matches_named (v : S.Pin r → Bool) (x : S.exposed r → Bool) : + (traffic h hx).links.Matches (store S r h v) (S.store r hx x) ↔ ∀ i, v i.val = x i := by + unfold store + rw [(traffic h hx).matches_iff _ (transfer h hx)] + have eq : Function.extend (place S r h) v (fun _ => false) ∘ fromBank h hx = + (fun i : S.exposed r => v i.val) ∘ (S.index r hx).symm := by + funext i + exact (place S r h).injective.extend_apply _ _ _ + rw [eq] + change S.store r hx x = S.store r hx _ ↔ _ + constructor + · intro he i + simpa using congrFun he.symm (S.wire r hx i) + · intro he; rw [funext he] + +variable (a : SpanPlan.Entries S.m w z S.spanRows) (b : SpanPlan.Entries S.m w 0 S.spanRows) + (hw : height S t < w) (hw' : k' < w) + (ha : Lengths S r t a) (hb : ∀ i j, (b i j).2.1.val = S.extent r i j) + (ho : ∀ i j, (b i j).2.2 = j) +include hw hw' ha hb ho + +open scoped Classical in +private theorem valid : Payload.Script.Valid (traffic h hx) le_rfl (script (a, b)) := by + let l := fun i => outgoing (a i) (b i) + let u := SpanPlan.offsets ∘ b + have hl : Aligned S r l := ⟨hb, ho⟩ + have hu : Aligned S r u := ⟨hb, ho⟩ + have total (v : B S.m) : (SpanPlan.total (b v)).val = S.load r v := by + rw [SpanPlan.total_val _ (hu.small hx hw' v)] + simp only [hb, S.load_eq] + have src (i : S.exposed r) : + Payload.Script.At (SpanPlan.pack (l (S.owner r i))).2 0 (S.index r hx i).2.val + (place S r h i.val).2.val := by + have H := hl.at_bit hx hw' i + change Payload.Script.At _ _ _ + (SpanPlan.offset (SpanPlan.offsets (a i.val.1.1.1)) (S.spanIndex i.val.1) + i.val.2.val) at H + rw [ha.offset h hw i.val.1] at H + change Payload.Script.At _ _ _ (index S r h (pin S r h i.val)).2.val + rw [index_val] + exact H + have dst (i : S.exposed r) : Payload.Script.At (SpanPlan.pack (u (S.owner r i))).2 0 + (S.index r hx i).2.val (S.index r hx i).2.val := by + have he : SpanPlan.offset (u (S.owner r i)) (S.spanIndex i.val.1) = + S.start r (S.owner r i) (S.spanIndex i.val.1) := by + refine (SpanPlan.offset_val _ (hu.small hx hw' _) _).trans ?_ + simp only [hb, Scheme.start] + have hh := hu.at_bit hx hw' i + dsimp only at hh + rwa [he, ← S.index_val r hx i] at hh + refine ⟨?_, fun i => SpanPlan.bounds (l i) (hl.fits hx hw' _) (hl.unique _), + fun i => SpanPlan.bounds (u i) (hu.fits hx hw' _) (hu.unique _), ?_, ?_⟩ + · exact ⟨ha.total h hw, total, hl.length hx hw', hu.length hx hw', + fun i j _ => ⟨i, rfl, (zero j).symm⟩, fun i j _ => ⟨i, rfl, (zero j).symm⟩, fun _ _ => rfl⟩ + · intro v j + let i := (S.index r hx).symm ⟨v, j⟩ + have hi : S.index r hx i = ⟨v, j⟩ := (S.index r hx).apply_symm_apply _ + have hv : S.owner r i = v := congrArg Sigma.fst hi + have he := src i + rw [hi, hv] at he + exact he + · intro v j + let i := (S.index r hx).symm ⟨v, j⟩ + have hi : S.index r hx i = ⟨v, j⟩ := (S.index r hx).apply_symm_apply _ + have hv : S.owner r i = v := congrArg Sigma.fst hi + have he := dst i + rw [hi, hv] at he + exact he + +open scoped Classical in +/-- The one-port script reads only exterior bits from the padded +argument bank, in the order of the original exterior payload. -/ +theorem correct (v : S.Pin r → Bool) (x : S.exposed r → Bool) : + (PeerLayout.S S.m V (height S t) S.m V' k' 1).Carries + (Payload.Script.decode le_rfl (script (a, b))) (store S r h v) (S.store r hx x) ↔ + ∀ i, v i.val = x i := + ((valid h hx a b hw hw' ha hb ho).carries _ _).trans (matches_named h hx v x) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Outer +end + +/- # Span records for the two terminal transfers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring +variable {F : Type} (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +/-- Returns `none` when `(partner S r s).1.1 = s.1.1` holds, and `((S.pattern r s.1).peer +s.1.2.2 s.2).map Prod.fst` otherwise. -/ +def path (s : S.Span) : Option (B S.d) := + if (partner S r s).1.1 = s.1.1 then none else ((S.pattern r s.1).peer s.1.2.2 s.2).map Prod.fst + +open scoped Classical in +private theorem path_link {s q : S.Span} (h : partner S r s = q) (ne : s.1.1 ≠ q.1.1) : + ∃ i, path S r s = some i ∧ (r s.1.1).1 i = q.1.1 := by + rcases partner_cases S r s with e|⟨a, _⟩ + · exact (ne (congrArg (fun p => p.1.1) (e.symm.trans h))).elim + rw [h, Scheme.peer] at a + cases b : (S.pattern r s.1).peer s.1.2.2 s.2 with + | none => simp [b] at a + | some v => + rw [b, Option.map_some, Option.some.injEq] at a + exact ⟨v.1, by simp only [path, h, ite_eq_right ne.symm, b, Option.map_some], + congrArg (fun p => p.1.1) a⟩ + +open scoped Classical in +private theorem route (proper : S.Proper r) (hr : Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) r) (s : + S.Span) : + perm S r (contact S s.1.1 (path S r s)) = + contact S (partner S r s).1.1 (path S r (partner S r s)) := by + have inv := partner_inv S r proper s + by_cases he : s.1.1 = (partner S r s).1.1 + · simp only [path, inv, ← he, ite_true, perm_self] + · obtain ⟨i, hi, hi'⟩ := path_link S r rfl he + obtain ⟨j, hj, hj'⟩ := path_link S r inv (Ne.symm he) + rw [hi, hj] + exact perm_link S r hr _ _ _ _ he hi' hj' + +open scoped Classical in +/-- The quantity computed by `SpanPlan.Entries S.m w (S.d + 1) S.spanRows`. -/ +abbrev flanks (w : ℕ) := SpanPlan.Entries S.m w (S.d + 1) S.spanRows + +open scoped Classical in +/-- The indexed operation `fun i j => let s := S.hostSpan (i, j) (hop (path S r s), Fin.ofNat _ +(chunk S r t s), S.spanIndex (partner S r s))`. -/ +def send (S : Scheme F) (t w : ℕ) (r : S.format.obj) : flanks S w := fun i j => + let s := S.hostSpan (i, j) + (hop (path S r s), Fin.ofNat _ (chunk S r t s), S.spanIndex (partner S r s)) + +open scoped Classical in +/-- Evaluates `let s := S.hostSpan (i, j) (hop (path S r s), Fin.ofNat _ (chunk S r t s), j)` at +the input `i j`. -/ +def take (S : Scheme F) (t w : ℕ) (r : S.format.obj) : flanks S w := fun i j => + let s := S.hostSpan (i, j) + (hop (path S r s), Fin.ofNat _ (chunk S r t s), j) + +open scoped Classical in +/-- Evaluates `(0, Fin.ofNat _ (S.extent r i j), j)` at the input `i j`. -/ +def outer (S : Scheme F) (w : ℕ) (r : S.format.obj) : SpanPlan.Entries S.m w 0 S.spanRows := + fun i j => (0, Fin.ofNat _ (S.extent r i j), j) + +open scoped Classical in +theorem inner_plan (proper : S.Proper r) (hr : Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) r) + {t w : ℕ} (ht : t < w) : Inner S r t (perm S r) (send S t w r) (take S t w r) where + bij := (perm_involutive S r hr).bijective + lengths s := by + simp only [send, Scheme.hostSpan_spanIndex] + have le : chunk S r t s ≤ 2 ^ t := by unfold chunk; split <;> simp + exact Nat.mod_eq_of_lt (le.trans_lt (Nat.pow_lt_pow_right (by decide) ht)) + paired s := by simp only [send, take, Scheme.hostSpan_spanIndex] + order _ := rfl + contacts s _ := by + simp only [endpoint, send, take, Scheme.hostSpan_spanIndex] + exact route S r proper hr s + +open scoped Classical in +theorem outer_length {V t w : ℕ} (h : Fits S r V t) (ht : t < w) (i : B S.m) (j : B S.spanRows) : + (outer S w r i j).2.1.val = S.extent r i j := by + have he : S.extent r i j ≤ 2 ^ t := by + dsimp only [Scheme.extent] + split + · exact h.width _ + · exact Nat.zero_le _ + exact Nat.mod_eq_of_lt (he.trans_lt (Nat.pow_lt_pow_right (by decide) ht)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- # Terminal commands and station headers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal + +variable {F : Type} (S : Scheme F) (V t w : ℕ) + +/-- The value specified by `((SpanPlan.emit (perm S r) (send S t w r, take S t w r), +Outer.script (send S t w r, outer S w r)), Header.eval S V t r)`. -/ +def orders (r : S.format.obj) : (instruction S V t (S.d + 1) w S.spanRows).obj := + ((SpanPlan.emit (perm S r) (send S t w r, take S t w r), + Outer.script (send S t w r, outer S w r)), Header.eval S V t r) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- +# Preparing a terminal lane + +The local table reads the short block label, lane index, and flags +indicating which neighbors are aliases of the same host. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Prepare +open Coloring +variable {F : Type} (S : Scheme F) (t w : ℕ) + +open scoped Classical in +/-- The value specified by `Format.pair (.addr S.spanRows) (.pair (.addr S.ℓ) (.vec S.d .bit))`. -/ +abbrev key := Format.pair (.addr S.spanRows) (.pair (.addr S.ℓ) (.vec S.d .bit)) +open scoped Classical in +/-- The answer used in the `Prepare` construction. -/ +abbrev answer := Format.pair (SpanPlan.header w (S.d + 1) S.spanRows) + (.pair (SpanPlan.header w (S.d + 1) S.spanRows) (SpanPlan.header w 0 S.spanRows)) + +open scoped Classical in +/-- The value specified by `(S.spanIndex s, (r s.1.1).2 s.1.2.1, b s.1.1)`. -/ +def get (r : S.format.obj) (b : (Flags S).obj) (s : S.Span) : (key S).obj := + (S.spanIndex s, (r s.1.1).2 s.1.2.1, b s.1.1) + +open scoped Classical in +/-- The read of type `(answer S w).obj`, constructed using `S.hostSpan (0, x.1)`. -/ +def read (x : (key S).obj) : (answer S w).obj := + let s := S.hostSpan (0, x.1) + let p := S.decode x.2.1 + let v := s.1.2.2 + let L := p.width v s.2 + let R := p.peer v s.2 + let A := if L = 0 then none else R + let c := hop (A.bind fun i => if x.2.2 i.1 then none else some i.1) + let j := A.elim x.1 fun i => S.spanIndex ((0, s.1.2.1, i.2.1), i.2.2) + let n := Fin.ofNat (2 ^ w) (if Nonempty (Σ i, Fin (p.width v i)) then 2 ^ t else 0) + ((c, n, j), (c, n, x.1), (0, Fin.ofNat _ (if R = none then L else 0), x.1)) + +open scoped Classical in +theorem read_get (r : S.format.obj) (s : S.Span) : + read S t w (get S r (flags S r) s) = + (send S t w r s.1.1 (S.spanIndex s), take S t w r s.1.1 (S.spanIndex s), + outer S w r s.1.1 (S.spanIndex s)) := by + have he : S.hostSpan (0, S.spanIndex s) = ((0, s.1.2), s.2) := by + exact S.hostSpan_spanIndex ((0, s.1.2), s.2) + let R := (S.pattern r s.1).peer s.1.2.2 s.2 + let A := if S.width r s = 0 then none else R + have hp : (A.bind fun i => if flags S r s.1.1 i.1 then none else some i.1) = path S r s := by + unfold path partner + by_cases h : S.width r s = 0 + · simp [A, h] + unfold Scheme.peer + simp only [A, R, h, ite_false] + cases (S.pattern r s.1).peer s.1.2.2 s.2 <;> simp [flags] + have hj : (A.elim (S.spanIndex s) fun i => S.spanIndex ((0, s.1.2.1, i.2.1), i.2.2)) = + S.spanIndex (partner S r s) := by + unfold partner + by_cases h : S.width r s = 0 + · simp [A, h] + unfold Scheme.peer + simp only [A, R, h, ite_false] + cases (S.pattern r s.1).peer s.1.2.2 s.2 <;> rfl + have hR : R = none ↔ S.peer r s = none := by simp [R, Scheme.peer] + simp only [read, get, he, send, take, outer, Scheme.extent, Scheme.hostSpan_spanIndex] + simp only [← hp, ← hj, ← hR] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Prepare +end + +/- # Parallel span instructions from one shared lookup table -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Prepare +open Coloring +variable {F : Type} [Field F] (S : Scheme F) (t w : ℕ) + +open scoped Classical in +/-- The quantity computed by `Perm (S.m + (S.d + 1))`. -/ +abbrev permFmt := Perm (S.m + (S.d + 1)) +open scoped Classical in +/-- The value specified by `(permFmt S).pair (Flags S)`. -/ +abbrev nav := (permFmt S).pair (Flags S) +open scoped Classical in +/-- Computes the input by the application `S.format.pair (nav S)`. -/ +abbrev input := S.format.pair (nav S) +open scoped Classical in +/-- The value specified by `(permFmt S).pair (.vec S.m (.vec S.spanRows A))`. -/ +abbrev grid (A : Format) := (permFmt S).pair (.vec S.m (.vec S.spanRows A)) +open scoped Classical in +/-- Computes the source by the application `grid S (key S)`. -/ +abbrev source := grid S (key S) +open scoped Classical in +/-- Computes the target by the application `grid S (answer S w)`. -/ +abbrev target := grid S (answer S w) + +open scoped Classical in +/-- The indexed operation `(x.2.1, fun i j => get S x.1 x.2.2 (S.hostSpan (i, j)))`. -/ +def query (x : (input S).obj) : (source S).obj := + (x.2.1, fun i j => get S x.1 x.2.2 (S.hostSpan (i, j))) + +open scoped Classical in +/-- The indexed operation `(perm S r, fun i j => (send S t w r i j, take S t w r i j, outer S w +r i j))`. -/ +def plan (r : S.format.obj) : (target S w).obj := + (perm S r, fun i j => (send S t w r i j, take S t w r i j, outer S w r i j)) + +open scoped Classical in +/-- The quantity computed by `(key S).width + (answer S w).width`. -/ +def arity := (key S).width + (answer S w).width + +open scoped Classical in +/-- The indexed operation `lookup F (key S) (answer S w) (fun x y => @ite F (read S t w x = y) +(Classical.propDecidable _) 1 0)`. -/ +def label : Table F := lookup F (key S) (answer S w) (fun x y => @ite F (read S t w x + = y) (Classical.propDecidable _) 1 0) + +open scoped Classical in +/-- The cost used in the `Prepare` construction. -/ +def cost (n : ℕ) := + 4 * (5 * S.format.width + S.format.width + n + ((input S).width + 34 * (source S).width)) + + (4 * (permFmt S).width + 2 ^ S.m * (2 ^ S.spanRows * (1 + (key S).width + (answer S w).width))) + +open scoped Classical in +private theorem query_net : Circuit F (input S) (source S) (query S) + ((input S).width + 34 * (source S).width) := by + apply Window.Tile.project_const + rintro (i | ⟨i, j, k|k|k⟩) + · exact .inl ⟨.inr (.inl i), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr S.spanRows).code (S.spanIndex (S.hostSpan (i, j))) k, fun _ => rfl⟩ + · exact .inl ⟨.inl (i, .inr ((S.hostSpan (i, j)).1.2.1, k)), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inr (i, k)), fun _ => rfl⟩ + +open scoped Classical in +theorem realize {u n : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + (ha : arity S w ≤ u) (hl : label S t w ∈ L) + (hn : Circuit F S.format (nav S) (fun r => (perm S r, flags S r)) n) : + Map F u L S.format (target S w) (plan S t w) (cost S w n) := by + have a := ((Circuit.id F S.format).pair hn).comp (query_net S) + have b : Map F u L (key S) (answer S w) (read S t w) (1 + (key S).width + (answer S w).width) := + Kernel.lookup ha hl + have c := (Map.circuit (L:=L) hu (Circuit.id F (permFmt S))).par + (Map.vec _ fun _ : B S.m => Map.vec _ fun _ : B S.spanRows => b) + have h := (Map.circuit hu a).comp c + have e : (fun r => (perm S r, fun i j => read S t w (get S r (flags S r) (S.hostSpan (i, j))))) = + plan S t w := by + funext r + refine Prod.ext rfl ?_ + funext i j + simpa only [plan, Scheme.spanIndex_hostSpan, Scheme.hostSpan_owner] + using read_get S t w r (S.hostSpan (i, j)) + rw [← e] + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Prepare +end + +/- # The three shared terminal lookup tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring +variable {F : Type} [Field F] (S : Scheme F) (t w : ℕ) + +open scoped Classical in +/-- Uses `{Dictionary.label S t, Header.label S, Prepare.label S t w}` as the representation. -/ +def labels : Finset (Table F) := {Dictionary.label S t, Header.label S, Prepare.label S t w} + +open scoped Classical in +theorem labels_card : (labels S t w).card ≤ 3 := by + unfold labels + have := Finset.card_insert_le (Header.label S) {Prepare.label S t w} + have := Finset.card_insert_le (Dictionary.label S t) {Header.label S, Prepare.label S t w} + simp only [Finset.card_singleton] at * + omega + +open scoped Classical in +/-- The quantity computed by `Dictionary.arity S t + Header.arity S + Prepare.arity S w`. -/ +def arity := Dictionary.arity S t + Header.arity S + Prepare.arity S w + +open scoped Classical in +theorem arity_le (i : Rates.Size) : arity i.S i.t i.w ≤ 2 ^ (i.S.e + i.t) + 64 * i.T := by + simp only [arity, Dictionary.arity, Dictionary.header, Header.arity, Header.key, Prepare.arity, + Prepare.key, Prepare.answer, SpanPlan.header] + repeat' rw [Format.width_pair] + rw [Format.width_vec, Format.width_bit, mul_one] + repeat' rw [Format.width_addr] + unfold Scheme.spanRows Rates.Size.w Rates.Size.T Rates.Size.B Rates.Size.k height + have := Nat.lt_two_pow_self (n := i.S.d) + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end + +/- # Compiling both transfer scripts in parallel -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Prepare +open Coloring +variable {F : Type} (S : Scheme F) (t w : ℕ) +local notation "m" => S.m +local notation "z" => S.d + 1 +local notation "n" => S.spanRows + +/-- The value specified by `(Emit.source m z w n).pair (Outer.input m z w n)`. -/ +abbrev both := (Emit.source m z w n).pair (Outer.input m z w n) +/-- The value specified by `(Payload.Script m m z w n).pair (Payload.Script m m 0 w n)`. -/ +abbrev commands := (Payload.Script m m z w n).pair (Payload.Script m m 0 w n) + +/-- The separate of type `(both S w).obj`, constructed using `fun i j => (x.2 i j).1`. -/ +def separate (x : (target S w).obj) : (both S w).obj := + let a := fun i j => (x.2 i j).1 + ((x.1, a, fun i j => (x.2 i j).2.1), (a, fun i j => (x.2 i j).2.2)) + +/-- The value specified by `(SpanPlan.emit (perm S r) (send S t w r, take S t w r), Outer.script +(send S t w r, outer S w r))`. -/ +def programs (r : S.format.obj) : (commands S w).obj := + (SpanPlan.emit (perm S r) (send S t w r, take S t w r), Outer.script (send S t w r, outer S w r)) + +/-- The value specified by `cost S w c + 4 * ((target S w).width + 2 * (both S w).width + +(Emit.cost m z w n + Outer.cost m z w n))`. -/ +def spending (c : ℕ) := cost S w c + + 4 * ((target S w).width + 2 * (both S w).width + (Emit.cost m z w n + Outer.cost m z w n)) + +variable [Field F] + +private theorem divide : Circuit F (target S w) (both S w) (separate S w) + ((target S w).width + 2 * (both S w).width) := by + let e : (both S w).pins → (target S w).pins + | .inl (.inl i) => .inl i + | .inl (.inr (.inl (i, j, k))) => .inr (i, j, .inl k) + | .inl (.inr (.inr (i, j, k))) => .inr (i, j, .inr (.inl k)) + | .inr (.inl (i, j, k)) => .inr (i, j, .inl k) + | .inr (.inr (i, j, k)) => .inr (i, j, .inr (.inr k)) + exact Circuit.project e (by rintro _ ((i|i|i)|i|i) <;> rfl) + +theorem scripts {u c : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) + (ha : arity S w ≤ u) (hl : label S t w ∈ L) + (hn : Circuit F S.format (nav S) (fun r => (perm S r, flags S r)) c) : + Map F u L S.format (commands S w) (programs S t w) (spending S w c) := by + have send := (Emit.circuit m z w n F).par (Outer.circuit F m z w n) + exact (realize S t w hu ha hl hn).comp (Map.circuit hu ((divide S w).comp send)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Prepare +end + +/- # Computing all the terminal instructions from the common records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +open Coloring +variable (i : Rates.Size) + +open scoped Classical in +/-- The quantity computed by `20 * i.S.format.width + Prepare.spending i.S i.w (linkCost i.S) + +i.header`. -/ +def orderCost := 20 * i.S.format.width + Prepare.spending i.S i.w (linkCost i.S) + i.header + +open scoped Classical in +theorem generate (hm : 1 ≤ i.S.m) (hi : i.S.m ≤ i.W.w) {u : ℕ} {L : Set (Table i.F)} + (hu : 3 ≤ u) (ha : arity i.S i.t i.w ≤ u) (hl : (↑(labels i.S i.t i.w) : Set _) ⊆ L) : + Map i.F u L i.S.format (instruction i.S i.V i.t i.p i.w i.n) + (orders i.S i.V i.t i.w) (orderCost i) := by + have hs : Prepare.arity i.S i.w ≤ u := by unfold arity at ha; omega + have hh : Header.arity i.S ≤ u := by unfold arity at ha; omega + obtain ⟨c, hc, tag⟩ := i.W.tag i.S.m i.v hm hi (Nat.le_add_left ..) + have e : Header.cost i.S i.V i.t i.v c ≤ i.header := by + unfold Rates.Size.header Rates.Size.c Header.cost Redistribute.cost + gcongr + have h₁ := Prepare.scripts i.S i.t i.w hu hs (hl (by simp [labels])) (links_net i.S) + have h₂ := (Header.realize (V:=i.V) (t:=i.t) hu hh (hl (by simp [labels])) tag + (Nat.le_add_right ..)).mono e + exact Map.pair hu h₁ h₂ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/OuterRows.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/OuterRows.lean new file mode 100644 index 0000000000..cdcfd12db8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Terminal/OuterRows.lean @@ -0,0 +1,259 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanTiles +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.ContractRates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.DictionaryHeaders + +/-! # Emitting a script whose contacts are part of the input -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Emit +open Coloring SpanPlan +variable (m p w n : ℕ) +local notation "P" => Perm (m + p) +local notation "C" => Payload.Script m m p w n +local notation "E" => Ports m m (entries w p n) (entries w p n) + +/-- The value specified by `(P).pair E`. -/ +abbrev source := (P).pair E +/-- Uses `SpanPlan.emit z.1 z.2` as the representation. -/ +def emit (z : (source m p w n).obj) : (C).obj := SpanPlan.emit z.1 z.2 +/-- The quantity computed by `(P).width + emitCost m m w p n + (((P).pair C).width + 2 * +(C).width)`. -/ +def cost := (P).width + emitCost m m w p n + (((P).pair C).width + 2 * (C).width) + +theorem circuit (F : Type) [Field F] : Circuit F (source m p w n) C (emit m p w n) (cost m p w n) + := by + let g : ((P).pair C).obj → (C).obj := fun z => ((z.2.1.1, z.1), z.2.2) + have patch : Circuit F ((P).pair C) C g + (((P).pair C).width + 2 * (C).width) := by + let atBit : (C).pins → ((P).pair C).pins + | .inl (.inl i) => .inr (.inl (.inl i)) + | .inl (.inr i) => .inl i + | .inr i => .inr (.inr i) + exact Circuit.project atBit (by rintro _ ((i|i)|i) <;> rfl) + have write := emit_net (m:=m) (m':=m) (w:=w) (p:=p) (n:=n) id F + have eq : g ∘ Prod.map id (SpanPlan.emit (m:=m) (m':=m) (w:=w) (p:=p) (n:=n) id) = + emit m p w n := by + funext x + simp only [g, emit, SpanPlan.emit, SpanPlan.assemble, Function.comp_apply, Prod.map, id_eq] + rw [← eq] + exact ((Circuit.id F P).par write).comp patch + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Emit +end + +/- # Extracting exterior bits from padded station records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Outer +open Coloring SpanPlan + +/-- Computes the input by the application `Format.pair (.vec m (entries w z n)) (.vec m (entries +w 0 n))`. -/ +abbrev input (m z w n : ℕ) := + Format.pair (.vec m (entries w z n)) (.vec m (entries w 0 n)) + +/-- Computes the middle by the application `Format.pair (.vec m (SpanPlan.Row w z n)) (.vec m +(SpanPlan.Row w 0 n))`. -/ +abbrev middle (m z w n : ℕ) := + Format.pair (.vec m (SpanPlan.Row w z n)) (.vec m (SpanPlan.Row w 0 n)) + +variable {m z w n : ℕ} + +/-- Evaluates `((b i).1, (b i).2.1, (b i).2.2, (offsets a i).2.2.2)` at the input `i`. -/ +def outgoing (a : (entries w z n).obj) (b : (entries w 0 n).obj) : (Input w 0 n).obj := + fun i => ((b i).1, (b i).2.1, (b i).2.2, (offsets a i).2.2.2) + +/-- The indexed operation `SpanPlan.assemble (SpanPlan.total ∘ x.1) (SpanPlan.total ∘ x.2) (fun +i => outgoing (x.1 i) (x.2 i)) (offsets ∘ x.2) id`. -/ +def script (x : (input m z w n).obj) : (Payload.Script m m 0 w n).obj := + SpanPlan.assemble (SpanPlan.total ∘ x.1) (SpanPlan.total ∘ x.2) (fun i + => outgoing (x.1 i) (x.2 i)) (offsets ∘ x.2) id + +private def gather (x : (middle m z w n).obj) : (Payload.Script m m 0 w n).obj := + organize id (fun i => ((x.1 i).1, (x.2 i).2.1, fun j => + let u := (x.2 i).2.2 j + (u.1, u.2.1, u.2.2.1, ((x.1 i).2.2 j).2.2.2)), x.2) + +/-- The quantity computed by `2 ^ (n + p) * (100 + (2 * n + p + w)) ^ 140`. -/ +def price (w p n : ℕ) := 2 ^ (n + p) * (100 + (2 * n + p + w)) ^ 140 + +/-- The value specified by `2 ^ m * price w z n + 2 ^ m * price w 0 n + ((middle m z w n).width ++ 34 * (Payload.Script m m 0 w n).width)`. -/ +def cost (m z w n : ℕ) := + 2 ^ m * price w z n + 2 ^ m * price w 0 n + + ((middle m z w n).width + 34 * (Payload.Script m m 0 w n).width) + +private theorem gather_eq : gather ∘ Prod.map (fun (x : (Format.vec m (entries w z n)).obj) i + => compile (x i)) + (fun (x : (Format.vec m (entries w 0 n)).obj) i => compile (x i)) = script := by + rfl + +private theorem final (F : Type) [Field F] : Circuit F (middle m z w n) (Payload.Script m m 0 w n) + gather + ((middle m z w n).width + 34 * (Payload.Script m m 0 w n).width) := by + apply Window.Tile.project_const + rintro ((((⟨i, j⟩|⟨i, j⟩)|(⟨i, j⟩|⟨i, j⟩))|⟨i, j⟩)|⟨i, k, j|j|j|j⟩|⟨i, j⟩) + · exact .inl ⟨.inl (i, .inl j), fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inr (.inl j)), fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inl j), fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inr (.inl j)), fun _ => rfl⟩ + · exact .inr ⟨(Format.addr _).code i j, fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inr (.inr (k, .inl j))), fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inr (.inr (k, .inr (.inl j)))), fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inr (.inr (k, .inr (.inr (.inl j))))), fun _ => rfl⟩ + · exact .inl ⟨.inl (i, .inr (.inr (k, .inr (.inr (.inr j))))), fun _ => rfl⟩ + · exact .inl ⟨.inr (i, .inr (.inr j)), fun _ => rfl⟩ + +theorem circuit (F : Type) [Field F] (m z w n : ℕ) : + Circuit F (input m z w n) (Payload.Script m m 0 w n) script (cost m z w n) := by + have stage (p : ℕ) : Circuit F (entries w p n) (SpanPlan.Row w p n) compile (price w p n) := by + obtain ⟨k, hk, he⟩ := cheap_entries F w p n + exact hk.mono (by unfold price; omega) + have out := ((Circuit.map _ (fun _ : B m => stage z)).par (Circuit.map _ (fun _ : B m + => stage 0))).comp (final F) + rw [gather_eq] at out + exact out + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Outer +end + +/- # Compiling both terminal payload scripts on the three cost scales -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +open Coloring + +private def effort (i : Size) (a : ℕ) := 2 ^ i.S.m * (2 ^ (i.n + a) * (100 + (2 * i.n + a + + i.w)) ^ 140) + +private theorem compile (a : Size → ℕ) (ha : Short a) (he : Short (fun i => 2 ^ a i)) : + Work (fun i => effort i (a i)) := by + have step := (num 100).short.add ((((num 2).short.mul n.short).add ha).add w.short) + refine (Work.spans (he.mul (step.pow 140))).mono fun i => ?_ + simp only [effort, Size.spans, Size.hosts, pow_add, mul_assoc, le_refl] + +private theorem rows {a : Size → ℕ} (h : Work (fun i => effort i (a i))) : + Work (fun i => (Format.vec i.S.m (SpanPlan.Row i.w (a i) i.n)).width) := by + refine h.mono fun i => ?_ + obtain ⟨s, _, hs⟩ := SpanPlan.cheap_entries i.F i.w (a i) i.n + rw [Format.width_vec] + exact Nat.mul_le_mul_left _ (le_trans ((Nat.le_add_left ..).trans (Nat.le_add_right ..)) hs) + +private theorem internal : Work (fun i => (Payload.Script i.S.m i.S.m i.p i.w i.n).width) := by + refine instruction.mono fun i => ?_ + unfold Size.instruction Terminal.instruction + simp only [Format.width_pair] + omega + +private theorem external : Work (fun i => (Payload.Script i.S.m i.S.m 0 i.w i.n).width) := by + refine instruction.mono fun i => ?_ + unfold Size.instruction Terminal.instruction + simp only [Format.width_pair] + omega + +theorem names : Work (fun i => (Perm (i.S.m + i.p)).width) := by + refine internal.mono fun i => ?_ + unfold Payload.Script PeerLayout.input Perm + simp only [Format.width_pair] + omega + +theorem emit : Work (fun i => Emit.cost i.S.m i.p i.w i.n) := by + have h := compile Size.p p links + have r := rows h + have write := (h.add h).add ((r.add r).add (internal.scale (num 34))) + have patch := (names.add internal).add (internal.scale (num 2)) + refine ((names.add write).add patch).mono fun i => ?_ + simp only [Emit.cost, SpanPlan.emitCost, SpanPlan.Ports, effort, Format.width_pair, add_mul, + le_refl] + +theorem project : Work (fun i => Terminal.Outer.cost i.S.m i.p i.w i.n) := by + have a := compile Size.p p links + have b := compile (fun _ => 0) (num 0).short (num 1).short + refine ((a.add b).add (((rows a).add (rows b)).add (external.scale (num 34)))).mono fun i => ?_ + change effort i i.p + effort i 0 + + ((Format.pair (.vec i.S.m (SpanPlan.Row i.w i.p i.n)) (.vec i.S.m (SpanPlan.Row i.w 0 + i.n))).width + + 34 * (Payload.Script i.S.m i.S.m 0 i.w i.n).width) ≤ _ + rw [Format.width_pair] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Rates +end + +/- # Exterior channel extents in span order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Outer +open Finset Coloring + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {V k w : ℕ} + {u : SpanPlan.Rows S.m w 0 S.spanRows} + +open scoped Classical in +/-- The data for the aligned construction, including `size`, `order`. -/ +structure Aligned (S : Scheme F) (r : S.format.obj) (u : SpanPlan.Rows S.m w 0 S.spanRows) : Prop + where + size : ∀ i j, SpanPlan.len (u i) j = S.extent r i j + order : ∀ i j, SpanPlan.pos (u i) j = j + +open scoped Classical in +theorem zero (i : B 0) : i = 0 := Fin.eq_zero i + +namespace Aligned +variable (ha : Aligned S r u) (h : S.Fits r V k) (hk : k < w) +include ha + +open scoped Classical in +theorem unique (v : B S.m) : SpanPlan.Unique (u v) := by + intro i j _ _ _ he + simpa only [ha.order] using he + +include h hk + +open scoped Classical in +theorem small (v : B S.m) : (∑ j, SpanPlan.len (u v) j) < 2 ^ w := by + simp_rw [ha.size, ← S.load_eq] + exact (h.2 v).trans_lt (Nat.pow_lt_pow_right (by decide) hk) + +open scoped Classical in +theorem fits (v : B S.m) : SpanPlan.Fits (u v) := + fun _ => (sum_le_sum_of_subset (subset_univ _)).trans_lt (ha.small h hk v) + +open scoped Classical in +theorem length (v : B S.m) : (((SpanPlan.pack (u v)).1 0).val) = S.load r v := by + rw [SpanPlan.lengths _ (ha.fits h hk _) 0, S.load_eq] + change (∑ j with SpanPlan.port (u v) j = 0, SpanPlan.len (u v) j) = _ + simp [zero, ha.size] + +open scoped Classical in +theorem start (v : B S.m) (j : B S.spanRows) : SpanPlan.start (u v) j = S.start r v j := by + rw [SpanPlan.start, SpanPlan.starts _ (ha.fits h hk _), Scheme.start] + change (∑ i with SpanPlan.port (u v) i = SpanPlan.port (u v) j ∧ + SpanPlan.pos (u v) i < SpanPlan.pos (u v) j, SpanPlan.len (u v) i) = _ + simp only [zero, true_and, ha.order, ha.size] + +open scoped Classical in +theorem at_bit (i : S.exposed r) : + let v := S.owner r i + let j := S.spanIndex i.val.1 + Payload.Script.At (SpanPlan.pack (u v)).2 0 (S.index r h i).2.val + (SpanPlan.offset (u v) j + i.val.2.val) := by + intro v j + apply SpanPlan.Hit.at_bit + refine ⟨j, i.val.2.val, zero _, ?_, ?_, rfl⟩ + · rw [ha.size] + simp [j, v, Scheme.extent, Scheme.owner, i.property] + · rw [ha.start h hk, S.index_val] + +end Aligned +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Terminal.Outer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Volumes.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Volumes.lean new file mode 100644 index 0000000000..624140c382 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Assembly/Volumes.lean @@ -0,0 +1,868 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Fragments +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.PortRelay + +/-! +# Joining a controller to its data path + +The controller may have a weighted sum of possible outputs. Contract +only its command block against the transfer operation. New metadata +and transferred payload remain available for the next stage. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Kernel + +open Coloring +variable {F : Type} [Field F] {u m n : ℕ} {L : Set (Table F)} + {X Y C A B : Format} + +open scoped Classical in +/-- Feed the command block across, without copying either payload. -/ +theorem with_channels [Fintype C.obj] {f : X.obj → (Y.pair C).obj → F} + {g : (C.pair A).obj → B.obj → F} (hf : Kernel F u L X (.pair Y C) f n) + (hg : Kernel F u L (.pair C A) B g m) : + Kernel F u L (.pair X A) (.pair Y B) + (fun x y => ∑ t, f x.1 (y.1, t) * g (t, x.2) y.2) (n + m) := by + let a := word A.width + let b := word B.width + let c := word C.width + let x := word X.width + let y := word Y.width + obtain ⟨s, hs, hf⟩ := hf x (.pair y c) (names X) ((names Y).sumCongr (names C)) + obtain ⟨t, ht, hg⟩ := hg (.pair c a) b ((names C).sumCongr (names A)) (names B) + let pre := (Rewire.assoc x a c).comp ((Rewire.id x).par (Rewire.swap a c)) + let post := ((Rewire.assoc y b c).comp ((Rewire.id y).par (Rewire.swap b c))).comp + (Rewire.assoc' y c b) + have h := (((hf.par hg).pre pre).post post).trace + apply of_layout (a := .pair x a) (b := .pair y b) ((names X).sumCongr (names A)) + ((names Y).sumCongr (names B)) + refine ⟨s + t, Nat.add_le_add hs ht, ?_⟩ + convert h using 1 + funext i j + exact ((view C (names C)).sum_comp (fun w => + f (view X (names X) i.1) (view Y (names Y) j.1, w) * + g (w, view A (names A) i.2) (view B (names B) j.2))).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Kernel +end + +/- +# Computing loads from local span widths + +No exterior bit identifier or global neighbor name enters a count. +The two ends of a loop both contribute to the internal degree. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Packing + +variable {F T : Type} {m d k e : ℕ} + +open scoped Classical in +/-- The sum of `if (P.peer 0 i).isSome = inside then P.width 0 i else 0` indexed by `i`. -/ +def Pattern.volume (P : Pattern F d k e) (inside : Bool) := + ∑ i, if (P.peer 0 i).isSome = inside then P.width 0 i else 0 + +namespace Scheme +variable (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +private theorem by_span (v : B S.m) (c : B S.h) (inside : Bool) : + ∑ q : S.Pin r, (if q.1.1 = (v, c, 0) ∧ (S.peer r q.1).isSome = inside then 1 else 0) = + (S.decode ((r v).2 c)).volume inside := by + change (∑ q : Σ p : S.Span, Fin (S.width r p), _) = _ + rw [Fintype.sum_sigma] + change (∑ p : S.Span, ∑ _ : Fin (S.width r p), + if p.1 = (v, c, 0) ∧ (S.peer r p).isSome = inside then (1 : ℕ) else 0) = _ + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, Nat.nsmul_eq_mul, mul_ite, + mul_one, mul_zero] + rw [Fintype.sum_prod_type] + rw [Fintype.sum_eq_single ((v, c, 0) : S.Vtx)] + · unfold Pattern.volume + refine Finset.sum_congr rfl fun i _ => ?_ + simp only [peer, Option.isSome_map, true_and] + rfl + · intro i hi + simp [hi] + +namespace Posting +variable [Field F] {S r} {x y : Wire} {L : Fringe x y T} {u h : ℕ} + {G : HostNet F L h u} (p : S.Posting r G) (v : G.V × Cell h) + +open scoped Classical in +/-- Computes the at block by the application `S.decode ((r (p.host v.1)).2 (p.block v.2))`. -/ +def atBlock := S.decode ((r (p.host v.1)).2 (p.block v.2)) + +open scoped Classical in +private theorem end_at (t : G.diagram.End) : + (p.toSeating.ends t).1.1 = (p.host v.1, p.block v.2, 0) ↔ G.units.place (G.diagram.station t) + = v := by + obtain ⟨⟨w, i⟩, rfl⟩ := G.diagram.portEquiv.surjective t + rw [p.toSeating.ends_at, Diagram.station_port] + change p.vertex w = _ ↔ _ + rw [p.vertex_eq] + simp only [Prod.mk.injEq, p.host.injective.eq_iff, p.block.injective.eq_iff, and_true] + exact Prod.ext_iff.symm + +open scoped Classical in +private theorem tabs (i : G.diagram.E) : + (S.peer r (p.toSeating.ends (.inl (.inr i))).1).isSome = true ∧ + (S.peer r (p.toSeating.ends (.inr (.inr i))).1).isSome = true := by + rw [(p.internal i).1, (p.proper _ _ (p.internal i).1).1] + exact ⟨rfl, rfl⟩ + +open scoped Classical in +theorem internal_volume : (p.atBlock v).volume true = degree G.pair v * u := by + unfold atBlock + rw [← S.by_span r, ← p.toSeating.ends.sum_comp] + simp only [Fintype.sum_sum_type, p.input, p.output, (p.tabs _).1, (p.tabs _).2, + Option.isSome_none, + Bool.false_eq_true, and_false, ite_false, Finset.sum_const_zero, zero_add, and_true, p.end_at] + rw [← degree_bundle G.pair u v, degree_sum, ← Finset.sum_add_distrib] + refine Fintype.sum_equiv G.units.bits _ _ fun i => ?_ + change (if G.units.place (G.diagram.source i) = v then 1 else 0) + + (if G.units.place (G.diagram.target i) = v then 1 else 0) = _ + rw [G.units.left, G.units.right] + unfold arityCost HostNet.pair + congr + +open scoped Classical in +theorem exterior_volume : (p.atBlock v).volume false = G.tetherLoad v := by + unfold atBlock + rw [← S.by_span r, ← p.toSeating.ends.sum_comp] + simp only [Fintype.sum_sum_type, p.input, p.output, (p.tabs _).1, (p.tabs _).2, + Option.isSome_none, + Bool.true_eq_false, and_false, ite_false, Finset.sum_const_zero, add_zero, and_true, p.end_at] + unfold HostNet.tetherLoad Packing.exterior + simp only [Fintype.card_subtype, Finset.card_filter] + congr + +end Posting +end Scheme +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# A weighted stage controller and an independent payload transfer + +The controller never reads exterior bits. It writes the new state +and commands, charges the scalar factors, and rejects spare selector +words. Only legal commands need to specify a transfer. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Encoding +open Coloring Transcript + +universe v +variable {F : Type} [Field F] {x y : Wire} {I J : Type v} + {G : I → Diagram F x y} {H : J → Diagram F x y} + (E : Encoding G) (D : Encoding H) {C T : Format} {u m n : ℕ} {L : Set (Table F)} + +open scoped Classical in +/-- The value specified by `(E.rows i, E.data i)`. -/ +abbrev info (i : I) : E.control.obj := (E.rows i, E.data i) + +open scoped Classical in +/-- The value specified by `(E.frame i a b).2`. -/ +def body (i : I) (a : Val x) (b : Val y) : E.payload.obj := (E.frame i a b).2 + +variable (R : Selected E.snapshot D.snapshot C) + +open scoped Classical in +/-- A shared port between the controller and payload check carries +exactly one command record per branch. -/ +theorem transfer (hu : 3 ≤ u) (cmd : ∀ i, R.choice i → T.obj) + {f : (E.control.pair C).obj → (D.control.pair T).obj → F} + (hk : Kernel F u L (.pair E.control C) (.pair D.control T) f m) + (he : ∀ i c y, f (E.info i, c) y = ((R.index i).read c).elim 0 fun j => + if (D.info (R.next i j), cmd i j) = y then R.scalar i j else 0) + {g : (T.pair E.payload).obj → D.payload.obj → F} + (hg : Kernel F u L (.pair T E.payload) D.payload g n) + (hv : ∀ i j a b y, g (cmd i j, E.body i a b) y = + if D.body (R.next i j) a b = y then 1 else 0) : + Transforms F u L E.snapshot D.snapshot (m + 4 * C.width + n) := by + let _ := Fintype.ofFinite C.obj + let _ := Fintype.ofFinite T.obj + have h := (Kernel.sum_hidden hu hk).with_channels hg + refine ⟨_, h, fun i => ⟨R.choice i, inferInstance, R.next i, R.scalar i, R.expands i, ?_⟩⟩ + rintro a b ⟨z, w⟩ + change I at i + let _ := R.finite i + change (∑ t, (∑ c, f (E.info i, c) (z, t)) * g (t, E.body i a b) w) = _ + have hs (t : T.obj) : (∑ c, f (E.info i, c) (z, t)) = + ∑ j, if (D.info (R.next i j), cmd i j) = (z, t) then R.scalar i j else 0 := + (Finset.sum_congr rfl fun c _ => he i c (z, t)).trans ((R.index i).sum _) + simp only [hs, Finset.sum_mul] + rw [Finset.sum_comm] + refine Finset.sum_congr rfl fun j _ => ?_ + change _ = @ite F ((D.info (R.next i j), D.body (R.next i j) a b) = (z, w)) + (Classical.propDecidable _) (R.scalar i j) 0 + by_cases e : D.info (R.next i j) = z + · simp only [Prod.mk.injEq, e, true_and, ite_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, + ite_true] + rw [hv i j a b w, mul_ite, mul_one, mul_zero] + · simp only [Prod.mk.injEq, e, false_and, ite_false, zero_mul, Finset.sum_const_zero] + +open scoped Classical in +/-- A partially specified computation is enough. On a rejected selector +there is no constraint on its output, since its weight is zero. -/ +theorem transfer_of_computes (hu : 3 ≤ u) (cmd : ∀ i, R.choice i → T.obj) + (out : I × C.obj → (D.control.pair T).obj) + (ho : ∀ i j, out (i, (R.index i).write j) = (D.info (R.next i j), cmd i j)) + (h : Computes F u L (.pair E.control C) (.pair D.control T) + (fun z => (E.info z.1, z.2)) out (fun z => ((R.index z.1).read z.2).elim 0 (R.scalar z.1)) m) + {g : (T.pair E.payload).obj → D.payload.obj → F} + (hg : Kernel F u L (.pair T E.payload) D.payload g n) + (hv : ∀ i j a b y, g (cmd i j, E.body i a b) y = + if D.body (R.next i j) a b = y then 1 else 0) : + Transforms F u L E.snapshot D.snapshot (m + 4 * C.width + n) := by + obtain ⟨f, hf, he⟩ := h + refine E.transfer D R hu cmd hf ?_ hg hv + intro i c y + have h := he (i, c) y + cases e : (R.index i).read c with + | none => simp only [e, Option.elim_none, ite_self] at h ⊢; exact h + | some j => + have ho' := ho i j + rw [← ((R.index i).valid _ _).mp e] at ho' + simp only [ho', e, Option.elim_some] at h + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Encoding +end + +/- +# A weighted scalar-withdrawal stage + +One common short table is used at every occurrence. Physical labels, +the supplemental record, and all external bits pass through unchanged. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring + +universe v +variable {F : Type} [Field F] {x y : Wire} {I : Type v} {u n : ℕ} {L : Set (Table F)} + +open scoped Classical in +theorem Transforms.of_action {X Y : Snapshot.{v} F x y} (q : X.state → Y.state) + (c : X.state → F) (f : X.port.obj → Y.port.obj) (w : X.port.obj → F) + (h : Action F u L X.port Y.port f w n) + (he : ∀ i a b, X.eval i a b = c i * Y.eval (q i) a b) + (hf : ∀ i a b, f (X.encode i a b) = Y.encode (q i) a b) + (hw : ∀ i a b, w (X.encode i a b) = c i) : Transforms F u L X Y n := by + refine ⟨_, h, fun i => ⟨Unit, inferInstance, fun _ => q i, fun _ => c i, ?_, ?_⟩⟩ + · intro a b + simp only [he, Fintype.sum_unique] + · intro a b t + simp only [hf, hw, Fintype.sum_unique] + +namespace Encoding +variable {G : I → Diagram F x y} (E : Encoding G) + +open scoped Classical in +/-- Uses `{ E with scheme := E.scheme.sweep, presents := fun i => (E.presents i).sweep }` as the +representation. -/ +abbrev sweep : Encoding (fun i => (G i).sweep) := + { E with scheme := E.scheme.sweep, presents := fun i => (E.presents i).sweep } + +open scoped Classical in +/-- The value specified by `weightTable (A := .addr E.scheme.ℓ) (D := .addr E.scheme.ℓ) id +E.scheme.scalar`. -/ +def sweepTable := weightTable (A := .addr E.scheme.ℓ) (D := .addr E.scheme.ℓ) id E.scheme.scalar + +open scoped Classical in +/-- The bound obtained by adding the component charges `updateCost E.scheme.m E.scheme.d +E.scheme.h (.addr E.scheme.ℓ) (.addr E.scheme.ℓ) + 4 * E.extra.width + 4 * E.payload.width`. -/ +def sweepCost := updateCost E.scheme.m E.scheme.d E.scheme.h (.addr E.scheme.ℓ) (.addr E.scheme.ℓ) + + 4 * E.extra.width + 4 * E.payload.width + +open scoped Classical in +theorem sweep_stage (hu : 3 ≤ u) (hw : 2 * E.scheme.ℓ ≤ u) (hl : E.sweepTable ∈ L) : + Transforms F u L E.snapshot E.sweep.snapshot E.sweepCost := by + let A := Format.addr E.scheme.ℓ + have h := update (m := E.scheme.m) (d := E.scheme.d) (h := E.scheme.h) + (A := A) (D := A) id E.scheme.scalar hu (by simpa [A, two_mul] using hw) hl + have keep (X : Format) := Action.of_map (Map.circuit (L := L) hu (Circuit.id F X)) + have k := (h.par (keep E.extra)).par (keep E.payload) + simp only [mul_one] at k + refine Transforms.of_action (X := E.snapshot) (Y := E.sweep.snapshot) (fun i => i) + (fun i => Fmt.weight E.scheme.scalar (E.rows i)) _ _ k ?_ ?_ ?_ + · exact fun i a b => (E.presents i).sweep_eval a b + · intro i a b + rfl + · exact fun _ _ _ => rfl + +end Encoding +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # A cut through a bundle exposes its full width -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Coloring Packing + +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} {x y : Wire} + {G : Diagram F x y} (p : S.Presentation r G) (Z : Freeze G) (live : B S.m → Bool) + (hl : ∀ v, live (p.vertex v).1 = true ↔ ¬Z.frozen v) + +open scoped Classical in +theorem freeze_borderWidth {u : ℕ} (hw : p.Uniform u) (j : (p.freeze Z live hl).BorderSpan) : + (p.freeze Z live hl).borderWidth j = u := by + let q := p.freeze Z live hl + let b : q.BorderBit := ⟨j, ⟨0, j.property.1⟩⟩ + let i := q.exteriorBits b + have ht : S.width r (p.toSeating.ends (fullEnd Z (boundaryEnd Z.core i))).1 = u := by + cases i with + | inl t => exact p.wirePin_width hw (Z.input t).val false + | inr t => exact p.wirePin_width hw (Z.output t).val true + have he : (p.toSeating.ends (fullEnd Z (boundaryEnd Z.core i))).1 = (q.vertex j.val.1, j.val.2) := + (p.span_full Z live hl _).symm.trans (congrArg Sigma.fst (q.border_pin b)) + rw [he] at ht + unfold borderWidth + have ha : live ((p.freeze Z live hl).vertex j.val.1).1 = true := (hl _).mpr j.val.1.property + rw [S.width_cut, ite_eq_left ha] + exact ht + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- +# Payload and header costs + +The field extension is used for station weights. A tagged permutation +over the ground field already gives the required graph over the extension. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring Transcript +variable {F K : Type} [Field F] [Field K] [Algebra F K] + +open scoped Classical in +theorem tag_map {j v m : ℕ} (ht : Radix.Tag F j v m) : Radix.Tag K j v m := by + unfold Radix.Tag Tagged.tag Tagged.permuted at ht ⊢ + simpa only [apply_ite (algebraMap F K), map_one, map_zero] using ht.map (algebraMap F K) + +open scoped Classical in +theorem wide_cost (h : Radix.WideTag F) {ζ : ℝ} (hζ : 0 < ζ) : + ∃ A : ℕ, ∃ C : ℝ, 0 ≤ C ∧ ∀ n j v : ℕ, 1 ≤ j → j ≤ n → n ^ A ≤ v → + ∃ m ≤ ⌈C * (n : ℝ) ^ ζ⌉₊*(2 ^ j * v), Radix.Tag F j v m := by + obtain ⟨A, _, C, ht⟩ := h ζ hζ + refine ⟨A, max C 0, le_max_right _ _, fun n j v hj hle hv => ?_⟩ + obtain ⟨m, hm, hb⟩ := ht j v hj ((Nat.pow_le_pow_left hle _).trans hv) + refine ⟨m, ?_, hm⟩ + have h' : (m : ℝ) ≤ ⌈max C 0 * (n : ℝ) ^ ζ⌉₊ * ((2 : ℝ) ^ j * v) := by + calc + _ ≤ (C * (j : ℝ) ^ ζ) * ((2 : ℝ) ^ j * v) := by linarith only [hb] + _ ≤ (max C 0 * (n : ℝ) ^ ζ) * ((2 : ℝ) ^ j * v) := by gcongr; exact le_max_left _ _ + _ ≤ _ := mul_le_mul_of_nonneg_right (Nat.le_ceil _) (by positivity) + exact_mod_cast h' + +variable (m V k m' V' k' d : ℕ) + +open scoped Classical in +/-- The value specified by `(payloadBank m V k m' V' k').channels (max k k') d`. -/ +abbrev payloadChannels := (payloadBank m V k m' V' k').channels (max k k') d + +open scoped Classical in +theorem bank_capacity : (payloadBank m V k m' V' k').capacity = + (Fmt.payload m V k).width + (Fmt.payload m' V' k').width := by + unfold Bank.capacity payloadBank + rw [Fintype.sum_sum_type] + simp only [Sum.elim_inl, Sum.elim_inr, Fmt.payload, Format.width, Fintype.card_sigma, + Fintype.card_fin] + rfl + +open scoped Classical in +theorem bank_slots : Fintype.card (payloadBank m V k m' V' k').Slot ≤ + (max k k' + 1) * (2 ^ m + 2 ^ m') := by + change Fintype.card (Slot (2 ^ m) V k ⊕ Slot (2 ^ m') V' k') ≤ _ + rw [Fintype.card_sum, mul_add] + refine Nat.add_le_add ((Transcript.card_slots ..).trans ?_) ((Transcript.card_slots ..).trans ?_) + · exact Nat.mul_le_mul_right _ (Nat.add_le_add_right (le_max_left _ _) _) + · exact Nat.mul_le_mul_right _ (Nat.add_le_add_right (le_max_right _ _) _) + +open scoped Classical in +private theorem budget {q a b H V d T v : ℕ} (ha : a ≤ 2 * (q + 1) * V) (hb : b ≤ (q + 1) * H) : + 20000 * T * (1 + a + (q + 1) * (10 * a + 4 * d * b * v)) ≤ 500000 * T * (q + 1) ^ 2 * (1 + V + + d * H * v) := by + calc + _ ≤ 20000 * T * (1 + 2 * (q + 1) * V + (q + 1) * (10 * (2 * (q + 1) * V) + 4 * d * ((q + + 1) * H) * v)) := by gcongr + _ ≤ _ := by ring_nf; omega + +open scoped Classical in +theorem payload_kernel {L : Set (Table K)} {u H W A : ℕ} + (hu : 3 ≤ u) (hn : d * ((max k k' + 1) * (2 ^ m + 2 ^ m')) < 2 ^ H) + (ht : ∀ j v, 1 ≤ j → j ≤ H → H ^ A ≤ v → ∃ s ≤ W * (2 ^ j * v), Radix.Tag F j v s) : + let S := payloadChannels m V k m' V' k' d + let ℓ := max k k' + Kernel K u L (S.control.pair (Fmt.payload m V k)) (Fmt.payload m' V' k') (S.kernel K) + (500000 * ((102 + ℓ) ^ 8 + W) * (ℓ + 1) ^ 2 * (1 + (V + V') + d * (2 ^ m + 2 ^ m') * (H ^ A + + H + 1))) := by + intro S ℓ + let P := payloadBank m V k m' V' k' + let T := (102 + ℓ) ^ 8 + W + let v := H ^ A + H + 1 + have hdepth (i : P.Slot) : P.depth i ≤ ℓ := by + rcases i with i | i + · exact (Nat.lt_succ_iff.mp i.1.isLt).trans (le_max_left _ _) + · exact (Nat.lt_succ_iff.mp i.1.isLt).trans (le_max_right _ _) + have hs := bank_slots m V k m' V' k' + have hw := P.realize (F := K) (L := L) ℓ d H T v hu hdepth + ((Nat.mul_le_mul_left d hs).trans_lt hn) + (Nat.le_add_right _ _) (by unfold v; omega) (by + intro a b ha hb hbig + obtain ⟨t, he, ht⟩ := ht a b ha hb (le_trans (by unfold v; omega) hbig) + exact ⟨t, he.trans (Nat.mul_le_mul_right _ (Nat.le_add_left _ _)), tag_map ht⟩) + have hcap : P.capacity ≤ 2 * (ℓ + 1) * (V + V') := by + rw [bank_capacity] + calc + _ ≤ (k + 1) * (2 * V) + (k' + 1) * (2 * V') + := Nat.add_le_add (Fmt.width_payload ..) (Fmt.width_payload ..) + _ ≤ (ℓ + 1) * (2 * V) + (ℓ + 1) * (2 * V') := by gcongr <;> unfold ℓ <;> omega + _ = _ := by ring + have sameChannels : P.channels ℓ d = S := rfl + rw [sameChannels] at hw + intro a b i j + obtain ⟨s, hs', hnet⟩ := hw a b i j + refine ⟨s, hs'.trans ?_, hnet⟩ + rw [add_assoc 1, ← bank_capacity] + exact budget (q := ℓ) (T := T) (v := v) (d := d) hcap hs + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Exterior transfer between snapshots + +An exterior position has a name independent of the snapshot. The +two boundary bijections therefore determine a permutation between +the occupied prefixes of the banks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly + +open Coloring + +namespace Encoding + +universe v +variable {F : Type} [Field F] {x y : Wire} {I J : Type v} + {G : I → Diagram F x y} {H : J → Diagram F x y} + (E : Encoding G) (D : Encoding H) + +open scoped Classical in +/-- Reindexes `D.scheme.exposed (D.rows j)` and `E.scheme.exposed (E.rows i)` by an equivalence. -/ +def relabel (i : I) (j : J) : D.scheme.exposed (D.rows j) ≃ E.scheme.exposed (E.rows i) := + (D.presents j).boundary.symm.trans (E.presents i).boundary + +open scoped Classical in +/-- Reindexes `(D.scheme.payload (D.rows j) (D.fits j)).Bit` and `(E.scheme.payload (E.rows i) +(E.fits i)).Bit` by an equivalence. -/ +def sources (i : I) (j : J) : (D.scheme.payload (D.rows j) (D.fits j)).Bit ≃ + (E.scheme.payload (E.rows i) (E.fits i)).Bit := + (D.scheme.index _ _).symm.trans ((E.relabel D i j).trans (E.scheme.index _ _)) + +open scoped Classical in +/-- Computes the channels by the application `payloadChannels E.scheme.m E.volume E.height +D.scheme.m D.volume D.height d`. -/ +abbrev channels (d : ℕ) := + payloadChannels E.scheme.m E.volume E.height D.scheme.m D.volume D.height d + +end Encoding +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- +# Contiguous spans in one channel bank + +The weighted prefix includes exactly the earlier order indices in the +same contact. Equal order indices are never counted against one +another, so inactive rows can safely duplicate any index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring Finset + +variable {w p n : ℕ} + +/-- Fields are contact, length, order and bank start. -/ +abbrev Entry (w p n : ℕ) := Format.pair (.addr p) (.pair (.addr w) (.pair (.addr n) (.addr w))) +/-- Computes the input by the application `Format.vec n (Entry w p n)`. -/ +abbrev Input (w p n : ℕ) := Format.vec n (Entry w p n) + +/-- The pack of type `(Fragments.Input w p n).obj` for the given inputs. -/ +def pack (x : (Input w p n).obj) : (Fragments.Input w p n).obj := + (fun c => ∑ j with (x j).1 = c, (x j).2.1, + fun i => ((x i).1, (∑ j with (x j).1 = (x i).1 ∧ (x j).2.2.1 < (x i).2.2.1, (x j).2.1), + (x i).2.1, (x i).2.2.2)) + +/-- The condition `∀ c, (∑ i with (x i).1 = c, (x i).2.1.val) < 2 ^ w` on the specified data. -/ +def Fits (x : (Input w p n).obj) : Prop := + ∀ c, (∑ i with (x i).1 = c, (x i).2.1.val) < 2 ^ w + +theorem val_sum {I : Type} (S : Finset I) (y : I → B w) + (h : (∑ i ∈ S, (y i).val) < 2 ^ w) : + (∑ i ∈ S, y i).val = ∑ i ∈ S, (y i).val := by + classical + induction S using Finset.induction_on with + | empty => simp + | @insert i S hi ih => + rw [sum_insert hi] at h + rw [sum_insert hi, sum_insert hi, Fin.val_add, ih (by omega), Nat.mod_eq_of_lt h] + +theorem lengths (x : (Input w p n).obj) (h : Fits x) (c : B p) : + ((pack x).1 c).val = ∑ j with (x j).1 = c, (x j).2.1.val := val_sum _ _ (h c) + +theorem starts (x : (Input w p n).obj) (h : Fits x) (i : B n) : + ((pack x).2 i).2.1.val = ∑ j with (x j).1 = (x i).1 ∧ (x j).2.2.1 < (x i).2.2.1, + (x j).2.1.val := by + apply val_sum + exact (sum_le_sum_of_subset (by intro j hj; simpa using (mem_filter.mp hj).2.1)).trans_lt (h (x + i).1) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- Compute strict weighted prefixes by looking up the start of the sorted run. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring Finset +variable {w k n : ℕ} + +/-- The sum of `x j` indexed by `j with f j < f i`. -/ +def earlier (f : B n → B k) (x : B n → B w) (i : B n) := ∑ j with f j < f i, x j + +private theorem earlier_sorted (f : B n → B k) (x : B n → B w) (i : B n) : + earlier f x i = ∑ j with j < leader (f ∘ order f) ((order f).symm i), x (order f j) := by + have hm := order_mono f + let j := leader (f ∘ order f) ((order f).symm i) + obtain ⟨he, hl⟩ := leader_spec _ hm ((order f).symm i) + have hj : f (order f j) = f i := by simpa using he + have key (t : B n) : f (order f t) < f i ↔ t < j := by + constructor + · exact fun h => lt_of_not_ge fun hu => h.not_ge (hj ▸ hm hu) + · intro h + refine lt_of_le_of_ne ((hm h.le).trans_eq hj) (fun eq => h.not_ge (hl t ?_)) + simpa using eq + unfold earlier + simp only [sum_filter] + rw [← Equiv.sum_comp (order f) (fun t => if f t < f i then x t else 0)] + simp only [key, j] + +variable (F : Type) [Field F] {t : ℕ} + +theorem cheap_prefix (hw : w ≤ t) : + Cheap F n t (Column n w) (Column n w) (fun x j => ∑ i with i < j, x i) 5 := by + refine ⟨_, BatchDescent.prefix_sum F n w, ?_⟩ + have he : 2 * w + 100000 * (1 + w) ≤ (100 + t) ^ 5 := by ring_nf; omega + simp only [Column, Format.width_vec, Format.width_addr] + linarith only [Nat.mul_le_mul_left (2 ^ n) he] + +/-- Computes the columns by the application `Format.pair (Column n k) (Column n w)`. -/ +abbrev Columns (n k w : ℕ) := Format.pair (Column n k) (Column n w) + +theorem cheap_earlier (h : n + k + w ≤ t) : + Cheap F n t (Columns n k w) (Column n w) (fun z => earlier z.1 z.2) 110 := by + have hk : n + k ≤ t := by omega + have hn : n ≤ t := by omega + have hw : w ≤ t := by omega + have hi : (Columns n k w).width ≤ 2 ^ n * (100 + t) ^ 1 := by + simp only [Columns, Column, Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add, + pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have z := Cheap.id F hi + have σ := z.fst.comp ((cheap_order F n k).widen hk) + have read := Cheap.lookup F n t (.addr w) hn (by simpa using hw) + have weights := (z.snd.pair σ).comp read + have scan := weights.comp (cheap_prefix F hw) + have l := z.fst.comp ((cheap_sorted_leader F n k).widen hk) + have inv := z.fst.comp ((cheap_inverse_order F n k).widen hk) + have key := (l.pair inv).comp (Cheap.lookup F n t (.addr n) hn (by simpa using hn)) + have net := ((scan.pair key).comp read).mono (d := 110) (by decide) + convert net using 1 + funext z i + exact earlier_sorted z.1 z.2 i + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- +# Channel starts + +Subtract the prefix in contact order from the prefix in lexicographic +(contact, position) order. Modular arithmetic suffices even if the sum +across different channels overflows. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan + +open Coloring Finset +variable {w p n t : ℕ} + +private def joint (x : (Entry w p n).obj) : B (p + n) := + (Match.rowIndex p n).symm (x.1, x.2.2.1) + +private theorem joint_lt (x y : (Entry w p n).obj) : + joint x < joint y ↔ x.1 < y.1 ∨ (x.1 = y.1 ∧ x.2.2.1 < y.2.2.1) := by + have h (x y : (Entry w p n).obj) (h : x.1 < y.1) : joint x < joint y := by + change x.2.2.1.val + 2 ^ n * x.1.val < y.2.2.1.val + 2 ^ n * y.1.val + have he := Nat.mul_le_mul_left (2 ^ n) (show x.1.val + 1 ≤ y.1.val from h) + rw [mul_add, mul_one] at he + have hx := x.2.2.1.isLt + omega + rcases lt_trichotomy x.1 y.1 with he | he | he + · simp [he, h x y he] + · change (x.2.2.1.val + 2 ^ n * x.1.val < y.2.2.1.val + 2 ^ n * y.1.val) ↔ _ + rw [he] + simp + · simp [he.not_gt, he.ne', (h y x he).not_gt] + +private theorem start_eq (x : (Input w p n).obj) (i : B n) : + ((pack x).2 i).2.1 = + earlier (joint ∘ x) (fun j => (x j).2.1) i - + earlier (fun j => (x j).1) (fun j => (x j).2.1) i := by + simp only [pack, earlier, sum_filter, Function.comp_apply, ← sum_sub_distrib, joint_lt] + refine sum_congr rfl fun j _ => ?_ + by_cases h : (x j).1 < (x i).1 + · simp [h, h.ne] + · simp [h] + +variable (F : Type) [Field F] + +theorem entry_width (h : 2 * n + p + w ≤ t) : (Entry w p n).width ≤ 2 ^ 0 * (100 + t) ^ 2 := by + simp [Entry]; ring_nf; omega + +private theorem cheap_joint (h : 2 * n + p + w ≤ t) : + Cheap F 0 t (Entry w p n) (.addr (p + n)) joint 10 := by + have x := Cheap.id F (entry_width h) + have a : Cheap F 0 t (.pair (.addr p) (.addr n)) (.addr (p + n)) (Match.rowIndex p n).symm 2 := by + refine ⟨_, Match.append_address F p n, ?_⟩ + simp; ring_nf; omega + exact ((x.fst.pair x.snd.snd.fst).comp a).mono (by decide) + +private theorem cheap_sub (h : w ≤ t) : + Cheap F 0 t (.pair (.addr w) (.addr w)) (.addr w) (fun y => y.1 - y.2) 20 := by + have x := Cheap.id F (show (Format.pair (.addr w) (.addr w)).width ≤ 2 ^ 0 * (100 + t) ^ 2 by + simp; ring_nf; omega) + have neg := x.snd.comp ((Intervals.cheap_neg F w).widen h) + convert ((x.fst.pair neg).comp (Intervals.cheap_add F h)).mono (d := 20) (by decide) using 1 + funext y + exact sub_eq_add_neg _ _ + +theorem cheap_fragments (h : 2 * n + p + w ≤ t) : + Cheap F n t (Input w p n) (.vec n (Fragments.Entry w p)) (fun x => (pack x).2) 130 := by + have x := Cheap.id F (entry_width h) + have keys := Cheap.map _ (fun _ : B n => cheap_joint F h) + have contacts := Cheap.map _ (fun _ : B n => x.fst) + have weights := Cheap.map _ (fun _ : B n => x.snd.fst) + have banks := Cheap.map _ (fun _ : B n => x.snd.snd.snd) + have before := (keys.pair weights).comp (cheap_earlier F (show n + (p + n) + w ≤ t by omega)) + have base := (contacts.pair weights).comp (cheap_earlier F (show n + p + w ≤ t by omega)) + have sub := Cheap.map _ (fun _ : B n => cheap_sub F (show w ≤ t by omega)) + have start := (before.pair base).zip.comp sub + have lenPtr := (weights.pair banks).zip + have record := (contacts.pair (start.pair lenPtr).zip).zip + convert record.mono (d := 130) (by decide) using 1 + funext x i + exact Prod.ext rfl (Prod.ext (start_eq x i) rfl) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- Generate the channel totals and contiguous fragment runs. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring Finset +variable (F : Type) [Field F] {w p n t : ℕ} + +theorem cheap_sum (h : w ≤ t) : + Cheap F n t (Column n w) (.addr w) (fun y => ∑ i, y i) 10 := by + have ha : (Format.addr w).width ≤ 2 ^ n * (100 + t) ^ 1 := by + rw [Format.width_addr, pow_one] + exact le_trans (by omega) (Nat.le_mul_of_pos_left _ (by positivity)) + have get := Cheap.project F (A := Column n w) (D := .addr w) (f := fun y => y ⊤) + (column_width n h) ha (fun j => (⊤, j)) (fun _ _ => rfl) + have add := Peers.lift F (Intervals.cheap_add F h) (Nat.zero_le n) + have total := (((cheap_prefix F h).comp get).pair get).comp add + convert total.mono (d := 10) (by decide) using 1 + funext y + change (∑ i, y i) = (∑ i with i < ⊤, y i) + y ⊤ + rw [show ({i : B n | i < ⊤} : Finset _) = univ.erase ⊤ by ext; simp [lt_top_iff_ne_top]] + exact (sum_erase_add _ _ (mem_univ _)).symm + +private theorem cheap_amount (h : 2 * n + p + w ≤ t) (a : B p) : + Cheap F 0 t (Entry w p n) (.addr w) (fun x => if x.1 = a then x.2.1 else 0) 12 := by + have hi := entry_width h + have hp : (Format.addr p).width ≤ 2 ^ 0 * (100 + t) ^ 2 := by simp; ring_nf; omega + have hw : (Format.addr w).width ≤ 2 ^ 0 * (100 + t) ^ 2 := by simp; ring_nf; omega + have x := Cheap.id F hi + have eq := (x.fst.pair (Cheap.const F hi hp a)).comp (cheap_eq F (show p ≤ t by omega)) + have args := (x.snd.fst.pair (Cheap.const F hi hw 0)).pair eq + have net := args.comp ((cheap_select F w).widen (show w ≤ t by omega)) + convert net.mono (d := 12) (by decide) using 1 + funext z + simp + +private theorem cheap_lengths (h : 2 * n + p + w ≤ t) : + Cheap F (n + p) t (Input w p n) (Column p w) (fun x => (pack x).1) 15 := by + let A := Input w p n + have one (a : B p) : Cheap F n t A (.addr w) (fun x => (pack x).1 a) 13 := by + have f := (Cheap.map _ (fun _ : B n => cheap_amount F h a)).comp + (cheap_sum F (show w ≤ t by omega)) + convert f.mono (d := 13) (by decide) using 1 + funext x + simp only [pack, Function.comp_apply, sum_filter] + let C := 2 ^ n * (100 + t) ^ 13 + have each (a : B p) : Circuit F A (.addr w) (fun x => (pack x).1 a) C := by + obtain ⟨m, hm, hb⟩ := one a + exact hm.mono (by unfold C; omega) + let D := Format.vec p A + have copy : Circuit F A D (fun x _ => x) (A.width + 2 * D.width) := + Circuit.project (fun i => i.2) (fun _ _ => rfl) + have k := copy.comp (Circuit.map _ each) + refine ⟨_, k, ?_⟩ + obtain ⟨m, _, hb⟩ := one 0 + change A.width + (Format.addr w).width + m ≤ C at hb + have he := Nat.mul_le_mul_left (2 ^ p) hb + have hc := Nat.le_mul_of_pos_left C (Nat.two_pow_pos p) + have hu : 10 * (2 ^ p * C) ≤ 2 ^ (n + p) * (100 + t) ^ 15 := by + rw [show 2 ^ (n + p) * (100 + t) ^ 15 = (2 ^ p * C) * (100 + t) ^ 2 by + unfold C; rw [pow_add, show 15 = 13 + 2 from rfl, pow_add]; ac_rfl, mul_comm 10] + exact Nat.mul_le_mul_left _ (by ring_nf; omega) + change A.width + (Column p w).width + (A.width + 2 * D.width + 2 ^ p * C) ≤ _ + simp only [Column, D, Format.width_vec] + linarith only [hu, hb, he, hc, Nat.zero_le (2 ^ p * m), + Nat.zero_le (2 ^ p * (Format.addr w).width)] + +theorem cheap (w p n : ℕ) : + Cheap F (n + p) (2 * n + p + w) (Input w p n) (Fragments.Input w p n) pack 131 := by + have h₁ := cheap_lengths F (le_rfl : 2 * n + p + w ≤ 2 * n + p + w) + have h₂ := Peers.lift F (cheap_fragments F (le_rfl : 2 * n + p + w ≤ 2 * n + p + + w)) (Nat.le_add_right n p) + exact h₁.pair h₂ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- # Computing bank offsets and lengths from the ordered spans -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +open Coloring Finset + +/-- Computes the header by the application `Format.pair (.addr p) (.pair (.addr w) (.addr n))`. -/ +abbrev header (w p n : ℕ) := Format.pair (.addr p) (.pair (.addr w) (.addr n)) +/-- Computes the entries by the application `Format.vec n (header w p n)`. -/ +abbrev entries (w p n : ℕ) := Format.vec n (header w p n) + +variable {w p n : ℕ} (x : (entries w p n).obj) + +/-- The sum of `(x i).2.1` indexed by `i`. -/ +def total := ∑ i, (x i).2.1 + +/-- Evaluates `((x i).1, (x i).2.1, (x i).2.2, ∑ j with j < i, (x j).2.1)` at the input `i`. -/ +def offsets : (Input w p n).obj := fun i => + ((x i).1, (x i).2.1, (x i).2.2, ∑ j with j < i, (x j).2.1) + +theorem total_val (hx : (∑ i, (x i).2.1.val) < 2 ^ w) : + (total x).val = ∑ i, (x i).2.1.val := val_sum _ _ hx + +theorem offset_val (hx : (∑ i, (x i).2.1.val) < 2 ^ w) (i : B n) : + ((offsets x i).2.2.2).val = ∑ j with j < i, (x j).2.1.val := + val_sum _ _ ((sum_le_sum_of_subset (subset_univ _)).trans_lt hx) + +/-- Computes the row by the application `Format.pair (.addr w) (Fragments.Input w p n)`. -/ +abbrev Row (w p n : ℕ) := Format.pair (.addr w) (Fragments.Input w p n) + +/-- The value specified by `(total x, pack (offsets x))`. -/ +def compile : (Row w p n).obj := (total x, pack (offsets x)) + +variable (F : Type) [Field F] + +theorem cheap_entries (w p n : ℕ) : + Cheap F (n + p) (2 * n + p + w) (entries w p n) (Row w p n) compile 140 := by + let t := 2 * n + p + w + have ht : w ≤ t := Nat.le_add_left _ _ + have h₁ : (header w p n).width ≤ 2 ^ 0 * (100 + t) ^ 2 := by + simp only [header, Format.width_pair, Format.width_addr, pow_zero, one_mul] + ring_nf + omega + have h₂ : (Format.pair (header w p n) (.addr w)).width ≤ 2 ^ 0 * (100 + t) ^ 2 := by + simp only [header, Format.width_pair, Format.width_addr, pow_zero, one_mul] + ring_nf + omega + have h₃ : (entries w p n).width ≤ 2 ^ n * (100 + t) ^ 2 := by + rw [entries, Format.width_vec] + exact Nat.mul_le_mul_left _ (by simpa using h₁) + have strip := Cheap.map _ (fun _ : B n => (Cheap.id F h₁).snd.fst) + have size := strip.comp (cheap_sum F ht) + have offsets' := strip.comp (cheap_prefix F ht) + have rekey : Cheap F 0 t (.pair (header w p n) (.addr w)) (Entry w p n) + (fun x => (x.1.1, x.1.2.1, x.1.2.2, x.2)) 3 := by + let key : (Entry w p n).pins → (Format.pair (header w p n) (.addr w)).pins + | .inl i => .inl (.inl i) + | .inr (.inl i) => .inl (.inr (.inl i)) + | .inr (.inr (.inl i)) => .inl (.inr (.inr i)) + | .inr (.inr (.inr i)) => .inr i + exact Cheap.project F h₂ (entry_width le_rfl) key (by rintro _ (i|i|i|i) <;> rfl) + have h := (((Cheap.id F h₃).pair offsets').zip.comp (Cheap.map _ (fun _ => rekey))) + have h' := (Peers.lift F h (Nat.le_add_right n p)).comp (cheap F w p n) + exact ((Peers.lift F size (Nat.le_add_right n p)).pair h').mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.SpanPlan +end + +/- # Recording coincidences among paths from one host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +open Coloring +variable (F : Type) [Field F] {m q t : ℕ} + +theorem cheap_equal (hm : m ≤ t) (hq : 2 ^ q ≤ t) : + Cheap F m t (Rows m q) (.vec m (Format.vec q (.vec q .bit))) + (fun a x i j => decide (a x i = a x j)) 25 := by + have cols (i j : B q) := ((column F hm hq i).pair (column F hm hq j)).zip + have test (i j : B q) := (cols i j).comp (Cheap.map _ (fun _ => cheap_eq F hm)) + have all := Cheap.share _ (fun i => Cheap.share _ (test i) hq) hq + let X := Format.vec q (.vec q (.vec m .bit)) + let Y := Format.vec m (Format.vec q (.vec q .bit)) + have hb : Y.width ≤ 2 ^ m * (100 + t) ^ 2 := by + simp only [Y, Format.width_vec] + rw [Format.width_bit, mul_one] + apply Nat.mul_le_mul_left + nlinarith only [Nat.mul_le_mul hq hq] + have hc : X.width = Y.width := by simp only [X, Y, Format.width_vec]; ring + have copy : Cheap F m t X Y (fun a x i j => a i j x) 3 := + Cheap.project F (hc.le.trans hb) hb (fun z => (z.2.1, z.2.2.1, z.1, z.2.2.2)) fun _ _ => rfl + exact (all.comp copy).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Beat/HeaderCost.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Beat/HeaderCost.lean new file mode 100644 index 0000000000..a54a9cbe16 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Beat/HeaderCost.lean @@ -0,0 +1,965 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.TemplateCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Issue +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Length +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Phase.ResetRate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.TraceNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.One +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Transform + +/-! # A common description for all branches of one wire-saving step -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Assembly Assembly.History +variable {F : Type} [Field F] {x y : Wire} (P : Gadget F) + (S : Setup F x y) (T : Template F) (z : ℕ) (hz : 0 < z) (Δ : ℕ) (R : Budget) (a : ℕ) + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def k := Nat.clog 2 (256 * (coreBins Δ + 1)) +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def b := Nat.clog 2 (Fintype.card (Branches.Tag P)) +open scoped Classical in +/-- The quantity computed by `10 * (4 * Δ) ^ 300 * 2 ^ (k Δ)`. -/ +def gain := 10 * (4 * Δ) ^ 300 * 2 ^ (k Δ) +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def e := Nat.clog 2 (gain Δ * R.load) +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def c := Nat.clog 2 (2 ^ S.discount * (gain Δ * R.load) * S.U + 1) + +open scoped Classical in +/-- The quantity computed by `Template.Meter.bounded (c S Δ R) 1 (1 / (2 : ℝ) ^ S.discount)`. -/ +abbrev meter := Template.Meter.bounded (c S Δ R) 1 (1 / (2 : ℝ) ^ S.discount) +open scoped Classical in +/-- The value specified by `Book.make T.scheme P z hz T.order {S.U}`. -/ +abbrev book := Book.make T.scheme P z hz T.order {S.U} +open scoped Classical in +/-- The quantity computed by `(book P S T z hz).overhead (e Δ R) + R.tag * (2 ^ S.discount * +(gain Δ * R.load))`. -/ +abbrev cap := (book P S T z hz).overhead (e Δ R) + R.tag * (2 ^ S.discount * (gain Δ * R.load)) +open scoped Classical in +/-- The value specified by `T.after a Δ (degreeBound S T Δ) (book P S T z hz) (e Δ R) (cap P S T +z hz Δ R) (meter S Δ R)`. -/ +abbrev next := T.after a Δ (degreeBound S T Δ) (book P S T z hz) (e Δ R) + (cap P S T z hz Δ R) (meter S Δ R) +open scoped Classical in +/-- The value specified by `(Post.headerFmt (T.degree a Δ (degreeBound S T Δ)) (e Δ R) (book P S +T z hz).d).width + (book P S T z hz).overhead (e Δ R)`. -/ +abbrev added := (Post.headerFmt (T.degree a Δ (degreeBound S T Δ)) (e Δ R) + (book P S T z hz).d).width + (book P S T z hz).overhead (e Δ R) + +open scoped Classical in +theorem choices : Fintype.card (Branches.Tag P) ≤ 2 ^ (b P) := Nat.le_pow_clog (by decide) _ + +open scoped Classical in +theorem bins : 256 * (coreBins Δ + 1) ≤ 2 ^ (k Δ) := Nat.le_pow_clog (by decide) _ + +open scoped Classical in +theorem positive : 1 ≤ k Δ := by + have := bins Δ + by_contra! h + rw [show k Δ = 0 by omega, pow_zero] at this + omega + +omit [Field F] in +open scoped Classical in +theorem degree_le : Δ ≤ degreeBound S T Δ := + (Nat.le_add_right _ _).trans (Nat.le_add_right _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Format widths and hardware costs for one batch step -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Assembly Coloring +variable {F : Type} [Field F] {x y : Wire} (P : Gadget F) + (S : Setup F x y) (T : Template F) (z : ℕ) (hz : 0 < z) (Δ : ℕ) (R : Budget) (r : ℕ) + +local notation "a" => (T.scheme.h - r) +local notation "n" => (T.scheme.h - a) +local notation "C" => degreeBound S T Δ +local notation "m" => T.scheme.m +local notation "d" => T.scheme.d +local notation "q" => ((d + 1) * n) +local notation "Y" => next P S T z hz Δ R a +local notation "M" => book P S T z hz +local notation "𝓔" => e Δ R +local notation "𝓒" => cap P S T z hz Δ R +local notation "𝓚" => meter S Δ R + +/-- The value specified by `(S.format T).pair (T.Candidate a (b P))`. -/ +abbrev In := (S.format T).pair (T.Candidate a (b P)) +/-- Computes the saved by the application `Trail.source T.scheme S.h S.d S.e`. -/ +abbrev Saved := Trail.source T.scheme S.h S.d S.e +/-- The value specified by `(T.Headed a (b P) Δ C).pair (Saved S T)`. -/ +abbrev Mid := (T.Headed a (b P) Δ C).pair (Saved S T) + +/-- The quantity computed by `1000000 * 2 ^ j * (j + v + 1)`. -/ +def accessCost (j v : ℕ) := 1000000 * 2 ^ j * (j + v + 1) +/-- The value specified by `(Group.Parcel d a n T.count).width`. -/ +def parcel := (Group.Parcel d a n T.count).width +/-- The value specified by `(Window.LabelSet a n).width`. -/ +def labels := (Window.LabelSet a n).width +/-- The quantity computed by `2 ^ a * (Window.Walks 8 d (T.WithCount a (b P))).width`. -/ +def walk := 2 ^ a * (Window.Walks 8 d (T.WithCount a (b P))).width +/-- The value specified by `(Trail.rowFormat T.scheme S.h S.d S.e).width`. -/ +def origin := (Trail.rowFormat T.scheme S.h S.d S.e).width +/-- The quantity computed by `T.size a + 2 ^ (Window.Tile.radius d + (n + 1)) + 2 ^ (T.degree a +Δ C)`. -/ +def precision := T.size a + 2 ^ (Window.Tile.radius d + (n + 1)) + 2 ^ (T.degree a Δ C) +/-- The quantity computed by `2 ^ (b P) + 4 * P.b`. -/ +def profile := 2 ^ (b P) + 4 * P.b + +/-- The bound obtained by adding the component charges `T.prepareCost a (b P) (parcel T r) +(accessCost (m + q) (parcel T r)) (labels T r) (accessCost (m + d) (labels T r))`. -/ +def prepareCost := T.prepareCost a (b P) (parcel T r) (accessCost (m + q) (parcel T r)) + (labels T r) (accessCost (m + d) (labels T r)) +/-- The cost bound `T.headedCost a (b P) Δ C (profile P)` for this construction. -/ +def headedCost := T.headedCost a (b P) Δ C (profile P) +/-- The bound obtained by adding the component charges `T.issueCost a (b P) Δ C M 𝓔 𝓒 𝓚 +(T.Pointers 𝓔) (walk P T r) (accessCost (m + d) (walk P T r)) (precision S T Δ r)`. -/ +def issueCost := T.issueCost a (b P) Δ C M 𝓔 𝓒 𝓚 (T.Pointers 𝓔) + (walk P T r) (accessCost (m + d) (walk P T r)) (precision S T Δ r) + +/-- The quantity computed by `(T.PollRow a (b P)).width + (Side.Input (n + T.scheme.e) (b +P)).width`. -/ +def markWidth := (T.PollRow a (b P)).width + (Side.Input (n + T.scheme.e) (b P)).width +/-- The value specified by `T.issueWidth a (b P) Δ C M 𝓔 𝓒 𝓚 (T.Pointers 𝓔)`. -/ +def issueWidth := T.issueWidth a (b P) Δ C M 𝓔 𝓒 𝓚 (T.Pointers 𝓔) +/-- The quantity computed by `T.arity a (b P) + markWidth P T r + issueWidth P S T z hz Δ R r + +2 * (Y).scheme.ℓ`. -/ +def arity := T.arity a (b P) + markWidth P T r + issueWidth P S T z hz Δ R r + 2 * (Y).scheme.ℓ + +/-- The quantity computed by `100 * (In P S T r).width + prepareCost P T r + headedCost P S T Δ +r`. -/ +def firstCost := 100 * (In P S T r).width + prepareCost P T r + headedCost P S T Δ r +/-- The second cost used in the `Beat` construction. -/ +def secondCost := 100 * (Mid P S T Δ r).width + issueCost P S T z hz Δ R r + + Trail.gatherBound T.scheme (Y).scheme S.h S.d S.e (origin S T) (accessCost (m + d) (origin S T)) + + Trail.carryCost T.scheme (Y).scheme (d + 1) S.h S.d S.d S.e (Mid P S T Δ r) (Y).format +/-- The bound obtained by adding the component charges `firstCost P S T Δ r + secondCost P S T z +hz Δ R r + 4 * (T.Candidate a (b P)).width + Snapshot.sweepCost S Y`. -/ +def totalCost := firstCost P S T Δ r + secondCost P S T z hz Δ R r + + 4 * (T.Candidate a (b P)).width + Snapshot.sweepCost S Y + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Numerical bounds for exchanges with dynamically addressed neighbors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Assembly Packing Phase Phase.Case + +variable {F : Type} [Field F] (b d : ℕ) + {j v : Case F b d → ℕ} (hj : Short (fun i => 2 ^ (j i))) (hv : Case.Row v) +local notation "I" => Case F b d + +include hj hv + +private theorem packet_bound : Cost (fun i : I => 2 ^ (i.m + j i) * (i.m + j i + v i + 1)) := + Row.expand (((Long.row (hosts.add hj.long.of_exp)).add hv).add (long_const 1).row) hj + +theorem access_bound : Cost (fun i : I => accessCost (i.m + j i) (v i)) := by + refine ((packet_bound b d hj hv).scale 1000000).mono fun i => ?_ + rw [accessCost, mul_assoc] + +theorem gather_bound : Cost (fun i : I => gatherCost i.m (j i) (v i) (accessCost (i.m + + j i) (v i))) := by + have hi : Long (fun i : I => (100 + (i.m + j i + 3 * i.m + 1)) ^ 200) := + ((long_const 100).add (((hosts.add hj.long.of_exp).add ((long_const 3).mul hosts)).add + (long_const 1))).pow _ + refine ((((access_bound b d hj hv).scale 4).add ((hi.row.expand hj).scale 4)).add + ((packet_bound b d hj hv).scale 1100)).mono fun i => ?_ + rw [gatherCost, mul_assoc 1100] + +theorem read_bound : Cost (fun i : I => Window.readCost i.m (j i) (v i) (accessCost (i.m + + j i) (v i))) := + (gather_bound b d hj hv).add ((Row.hosts (((hosts.row.add hv).left hj).add hv)).scale 1000) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Electing the common layout and matching in an encoded batch -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Assembly + +variable {F : Type} [Field F] {x y : Wire} {P : Gadget F} + {S : Setup F x y} {T : Template F} {z Δ : ℕ} {R : Budget} {w r d K : ℕ} {σ : ℝ} + (h : Phase.Input S T R w r P.b (P.b * z) z d K σ) + +local notation "a" => (T.scheme.h - r) +local notation "C" => degreeBound S T Δ +local notation "cost" => ((R.load : ℝ) * S.z) + +include h in +open scoped Classical in +theorem scale_le : S.z ≤ z := Nat.le_of_dvd h.vpos h.divides + +include h in +open scoped Classical in +theorem reserve : 0 < S.U := (Nat.mul_pos P.pos h.vpos).trans_le h.ceiling + +include h in +open scoped Classical in +theorem slack_pos : 0 ≤ σ := + nonneg_of_mul_nonneg_left (le_trans (by positivity) h.slack) (by positivity) + +include h in +open scoped Classical in +theorem enough (hK : 2 ^ (k Δ) ≤ K) : k Δ ≤ T.scheme.h - a := by + rw [Nat.sub_sub_self h.group] + exact (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp (hK.trans h.room) + +include h in +open scoped Classical in +theorem slack (hK : 2 ^ (k Δ) ≤ K) (v : ℕ) (hv : v ≤ 2 ^ T.scheme.m) : + (2 : ℝ) ^ (k Δ) * cost * (v * 2 ^ a : ℕ) ≤ σ := by + exact BatchDescent.slack_of_width_count (by positivity) h.group hK hv + (by simpa only [Nat.cast_mul] using h.slack) + +include h in +open scoped Classical in +theorem delayed : T.scheme.h - a ≤ 32 * Nat.clog 2 (2 * C) := by + have hh : 2 ^ S.h ≤ 2 * C := by + unfold degreeBound + have := Nat.two_pow_pos T.scheme.m + have := Nat.two_pow_pos S.h + omega + have ht := (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp + (hh.trans (Nat.le_pow_clog (by decide : 1 < 2) _)) + have := h.height + omega + +variable (q : (frame S T (P.b * z) Δ R).state) + +open scoped Classical in +/-- The value specified by `T.Selection a (Nat.sub_le _ _) (b P) (k Δ) cost Δ C q.val.encodes σ +(Nat.mul_pos P.pos h.vpos)`. -/ +abbrev Poll := T.Selection a (Nat.sub_le _ _) (b P) (k Δ) cost Δ C q.val.encodes σ + (Nat.mul_pos P.pos h.vpos) + +open scoped Classical in +theorem elect (hd : 0 < Δ) (hk : 2 ^ (k Δ) ≤ K) : Nonempty (Poll h q) := by + have hv : Fintype.card q.val.G.V ≤ 2 ^ T.scheme.m := by + simpa using Fintype.card_le_of_injective _ q.val.encodes.post.host.injective + have hl : 0 < cost := by exact_mod_cast (Nat.mul_pos P.pos h.vpos).trans_le h.load + exact T.selection a (Nat.sub_le _ _) (b P) (k Δ) cost Δ C q.val.encodes σ _ + hd (hd.trans_le (degree_le S T Δ)) (positive Δ) (enough h hk) hl q.property.bounded + (bins Δ) (slack h hk _ hv) (fun _ => delayed h) + +open scoped Classical in +/-- The value specified by `T.Branch P a (Nat.sub_le _ _) (b P) (k Δ) cost Δ C z σ (Nat.mul_pos +P.pos h.vpos)`. -/ +abbrev Ticket := T.Branch P a (Nat.sub_le _ _) (b P) (k Δ) cost Δ C z σ (Nat.mul_pos P.pos h.vpos) + +open scoped Classical in +/-- The ticket of type `Ticket (Δ := Δ) h where T` for the given inputs. -/ +def ticket (s : Poll h q) (i : s.choices) : Ticket (Δ := Δ) h where + T := Stack.Outer S.input S.output + x := S.input + y := S.output + L := S.fringe + G := q.val.G + r := q.val.rows + p := q.val.encodes + s := s + i := i + v := ((Classical.choice q.property.live, 0), ⟨0, 0⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Validation and permutation ranges for a batch of wire-saving gadgets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {P : Gadget F} + {S : Setup F x y} {T : Template F} {z Δ : ℕ} {R : Budget} {w r d K : ℕ} {σ : ℝ} + (h : Phase.Input S T R w r P.b (P.b * z) z d K σ) + +local notation "a" => (T.scheme.h - r) +local notation "C" => degreeBound S T Δ +local notation "Y" => next P S T z h.vpos Δ R a +local notation "n" => (T.scheme.h - a) +local notation "j" => (T.scheme.m + T.scheme.d) +local notation "q" => (T.scheme.m + (T.scheme.d + 1) * n) +local notation "cost" => ((R.load : ℝ) * S.z) + +open scoped Classical in +/-- The quantity computed by `3 + arity P S T z h.vpos Δ R r + 2 * 2 ^ (2 * w) * (4 * w)`. -/ +def scale (Δ : ℕ) := 3 + arity P S T z h.vpos Δ R r + 2 * 2 ^ (2 * w) * (4 * w) + +open scoped Classical in +/-- The tables used in the `Beat` construction. -/ +def tables (Δ : ℕ) (gate : Table F) := + insert gate (insert (Snapshot.sweepTable (next P S T z h.vpos Δ R a)) + (insert (T.markTable a (b P)) (T.keys a (b P) (k Δ) cost Δ (degreeBound S T Δ)))) + +open scoped Classical in +/-- The value specified by `Allowed F w ∪ (tables h Δ gate : Set (Table F))`. -/ +abbrev allowed (Δ : ℕ) (gate : Table F) := Allowed F w ∪ (tables h Δ gate : Set (Table F)) + +open scoped Classical in +theorem three : 3 ≤ scale h Δ := (Nat.le_add_right ..).trans (Nat.le_add_right ..) + +open scoped Classical in +theorem fits : arity P S T z h.vpos Δ R r ≤ scale h Δ := + (Nat.le_add_left ..).trans (Nat.le_add_right ..) + +variable (gate : Table F) (hk : 2 ^ (k Δ) ≤ K) (hd : d + 1 ≤ K) + +include hk hd in +open scoped Classical in +theorem access (v : ℕ) : Access F (scale h Δ) (allowed h Δ gate) j v (accessCost j v) ∧ + Access F (scale h Δ) (allowed h Δ gate) q v (accessCost q v) := by + have hh : q ≤ 2 * w := by + refine le_trans ?_ h.upper + exact Nat.add_le_add_left (Nat.mul_le_mul ((Nat.add_le_add_right h.degree 1).trans hd) + ((Nat.sub_le ..).trans (h.height.trans (Nat.le_add_right ..)))) _ + have hpos := (positive Δ).trans (enough h hk) + have hj : j ≤ q := Nat.add_le_add_left + ((Nat.le_succ _).trans (Nat.le_mul_of_pos_right _ hpos)) _ + have hw : 0 < w := by + have hq : 0 < q := Nat.lt_of_lt_of_le (Nat.mul_pos (by omega) hpos) (Nat.le_add_left ..) + omega + have read (i : ℕ) (hl : w ≤ i) (hr : i ≤ 2 * w) : + Access F (scale h Δ) (allowed h Δ gate) i v (accessCost i v) := by + have size : 2 * 2 ^ i * (4 * w) ≤ scale h Δ := by + refine le_trans ?_ (Nat.le_add_left ..) + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide) hr)) + exact (exchange F v hw hl hr size).widen le_rfl (fun _ ht => Or.inl (sort_allowed ht)) + exact ⟨read _ (h.lower.trans (Nat.le_add_right ..)) (hj.trans hh), + read _ (h.lower.trans (Nat.le_add_right ..)) hh⟩ + +variable (s : ∀ t : (frame S T (P.b * z) Δ R).state, Poll h t) + +open scoped Classical in +/-- The value specified by `T.start P a (Nat.sub_le ..) (b P) (k Δ) cost Δ C (Trail.format +T.scheme S.h S.d S.e) (i.val.code, l)`. -/ +def start (i : (frame S T (P.b * z) Δ R).state) (l : (T.Candidate a (b P)).obj) : (Mid P S T Δ + r).obj := + T.start P a (Nat.sub_le ..) (b P) (k Δ) cost Δ C (Trail.format T.scheme S.h S.d S.e) (i.val.code, + l) + +include hk hd in +open scoped Classical in +theorem first : Computes F (scale h Δ) (allowed h Δ gate) (In P S T r) (Mid P S T Δ r) + (fun t : (frame S T (P.b * z) Δ R).state × (T.Candidate a (b P)).obj => (t.1.val.code, t.2)) + (fun t => start (P := P) (r := r) t.1 t.2) + (fun t => if (((s t.1).selector (choices P)).read t.2).isSome then 1 else 0) + (firstCost P S T Δ r) := by + have fit := fits (Δ := Δ) h + unfold arity at fit + let X (t : (frame S T (P.b * z) Δ R).state × (T.Candidate a (b P)).obj) : (In P S T r).obj := + (t.1.val.code, t.2) + have allow : (T.keys a (b P) (k Δ) cost Δ C : Set _) ⊆ allowed h Δ gate := + fun _ ht => Or.inr (Finset.mem_insert_of_mem (Finset.mem_insert_of_mem + (Finset.mem_insert_of_mem ht))) + have ar : markWidth P T r ≤ scale h Δ := by omega + have hp : 4 * P.b ≤ 2 ^ (profile P) := (Nat.le_add_left ..).trans (Nat.lt_two_pow_self.le) + have all := T.start_net P a (Nat.sub_le ..) (b P) (k Δ) cost Δ C (Trail.format T.scheme S.h S.d + S.e) + (three h) ((positive Δ).trans (enough h hk)) (access h gate hk hd (parcel T r)).2 le_rfl + (access h gate hk hd (labels T r)).1 le_rfl (by omega) allow ar + (Or.inr (Finset.mem_insert_of_mem (Finset.mem_insert_of_mem (Finset.mem_insert_self ..)))) + (profile P) (Nat.le_add_right ..) hp X (fun t => t.1.val.encodes.reciprocal) + obtain ⟨f, hf, he⟩ := all + refine ⟨f, hf, fun t v => ?_⟩ + refine (he t v).trans ?_ + have hw := (s t.1).valid_eq (choices P) t.2 + change (if start (P := P) (r := r) t.1 t.2 = v then T.valid a (b P) P + (T.prepared a (Nat.sub_le ..) (b P) (k Δ) cost Δ C (t.1.val.rows, t.2)) else 0) = _ + rw [hw] + dsimp only + cases ((s t.1).selector (choices P)).read t.2 <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Polynomial description lengths for one wire-saving step -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Assembly History Packing Phase Phase.Case Coloring + +variable {F : Type} [Field F] (P : Gadget F) (Δ d : ℕ) +local notation "I" => Case F P.b d + +open scoped Classical in +theorem spans_bound : Base (fun i : I => 2 ^ e Δ i.R) := + ((base_const (gain Δ)).mul load).exp_clog + +open scoped Classical in +theorem history_factor : Base (fun i : I => 2 ^ i.S.discount * (gain Δ * i.R.load)) := + discount.mul ((base_const (gain Δ)).mul load) + +open scoped Classical in +theorem meter_bound : Base (fun i : I => (meter i.S Δ i.R).count) := by + refine (base_const 3).mul (((history_factor P Δ d).add Case.units).mono fun i => ?_) + exact BatchDescent.Phase.clog_le_add_of_le_mul_succ _ _ _ + (by simp only [add_mul, mul_add, one_mul, mul_one]; omega) + +open scoped Classical in +/-- The quantity computed by `(d + Nat.clog 2 ((4 * Δ) ^ 300) + 1) * 3`. -/ +abbrev maxDegree := Assembly.Child.degreeLimit Δ d + +open scoped Classical in +theorem child_degree (i : I) : + i.T.degree i.a Δ (degreeBound i.S i.T Δ) ≤ maxDegree Δ d := by + simpa only [Template.degree, Template.bound, i.h.core, Bool.false_eq_true, ↓reduceIte] using + Assembly.Child.nextWidth_le_degreeLimit (i.T.scheme.h - i.a) Δ i.h.degree + +open scoped Classical in +theorem child_slots : Base (fun i : I => 2 ^ i.T.degree i.a Δ (degreeBound i.S i.T Δ)) := + (base_const (2 ^ maxDegree Δ d)).mono fun i => Nat.pow_le_pow_right (by decide) (child_degree P Δ + d i) + +open scoped Classical in +private theorem role_bound : Rate (fun i : I => Kind.width i.T.scheme P (i.T.scheme.e + 2)) := by + have h : Rate (fun i : I => 1 + (Fintype.card (Role P) + 2 ^ (i.T.scheme.e + 2))) := + (rate_const 1).add ((rate_const _).add (spans.exp_add (rate_const (2 ^ 2)))) + refine ((h.add (rate_const 1)).clog).mono fun i => ?_ + simp only [Kind.width, Kind.Small, Fintype.card_sum, Fintype.card_fin, Dense.used, i.h.single, + pow_zero] + rfl + +open scoped Classical in +theorem overhead_bound : Rate (fun i : I => (book P i.S i.T i.v i.h.vpos).overhead (e Δ i.R)) := by + have he := (spans_bound P Δ d).rate + have hs : Rate (fun i : I => 2 ^ (book P i.S i.T i.v i.h.vpos).s) := + (spans.exp_add (rate_const (2 ^ 2))).exp_add (rate_const (2 ^ Nat.clog 2 (P.b + 1))) + have hd : Rate (fun i : I => (book P i.S i.T i.v i.h.vpos).d) := by + simpa only [book, Book.make, Book.lenBits, History.lengthBits, Finset.card_singleton] using + (rate_const (Nat.clog 2 (1 + 3)) : Rate (fun _ : I => _)) + have hr := role_bound P d + have hl : Rate (fun i : I => Dense.used (i.T.scheme.ℓ + Kind.width i.T.scheme P (i.T.scheme.e + + 2))) := + (hr.add lengths).mono fun i => by + refine BatchDescent.Phase.clog_le_add_of_le_mul_succ _ _ _ ?_ + simp only [add_mul, mul_add, one_mul, mul_one] + omega + have hw := (he.mul hd).add (he.mul ((rate_const 1).add + ((rate_const 0).add (hs.mul ((rate_const 1).add (he.of_exp.add hd)))))) + refine ((hw.add (he.mul hl)).add (he.mul hr)).mono fun i => ?_ + rw [Book.overhead, Post.bookkeeping, Dense.overhead, width_code] + +open scoped Classical in +theorem added_bound : Rate (fun i : I => added P i.S i.T i.v i.h.vpos Δ i.R i.a) := by + have he := (spans_bound P Δ d).rate + have hq := (child_slots P Δ d).rate.of_exp + have hd : Rate (fun i : I => (book P i.S i.T i.v i.h.vpos).d) := by + simpa only [book, Book.make, Book.lenBits, History.lengthBits, Finset.card_singleton] using + (rate_const (Nat.clog 2 (1 + 3)) : Rate (fun _ : I => _)) + have h := (rate_const 1).add (he.mul (hd.add ((rate_const 1).add ((rate_const 1).add (hq.add + he.of_exp))))) + refine (h.add (overhead_bound P Δ d)).mono fun i => ?_ + simp only [added, Post.headerFmt, Post.field, Format.width_pair, Format.width_vec, + Format.width_addr] + rw [Format.width_bit] + +open scoped Classical in +theorem bits_bound : ∃ k : ℕ, ∀ i : I, + (next P i.S i.T i.v i.h.vpos Δ i.R i.a).scheme.ℓ ≤ (1 + i.R.tag) * i.rate ^ k := by + obtain ⟨k, h⟩ := ((added_bound P Δ d).add (history_factor P Δ d).rate).bound + refine ⟨k, fun i => ?_⟩ + let t := added P i.S i.T i.v i.h.vpos Δ i.R i.a + let f := 2 ^ i.S.discount * (gain Δ * i.R.load) + calc + _ = t + i.R.tag * f := by + change (Post.record _ _ _ (.addr _)).width = _ + simp only [t, f, added, cap, Post.record, Post.headerFmt, Format.width_pair, + Format.width_addr, add_assoc] + _ ≤ (1 + i.R.tag) * (t + f) := by simp only [add_mul, mul_add, one_mul]; omega + _ ≤ _ := Nat.mul_le_mul_left _ (h i) + +open scoped Classical in +theorem next_bits : Short (fun i : I => (next P i.S i.T i.v i.h.vpos Δ i.R i.a).scheme.ℓ) := by + obtain ⟨k, h⟩ := bits_bound P Δ d + exact (((short_const 1).add tags).mul ((Poly.of_le short_two rate_short).pow k)).mono h + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Widths of the local lookup tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Assembly History Packing Phase Phase.Case Coloring Window + +variable {F : Type} [Field F] (P : Gadget F) (Δ d : ℕ) +local notation "I" => Case F P.b d + +theorem child_factor : Short (fun i : I => 2 ^ (i.n + 1)) := + tiles.rate.short.exp_add (short_const (2 ^ 1)) + +theorem seat_factor : Short (fun i : I => 2 ^ (i.n + i.T.scheme.e)) := + tiles.rate.short.exp_add spans.short + +theorem radius_factor : Short (fun i : I => 2 ^ (Tile.radius i.T.scheme.d)) := + (short_const (2 ^ (Tile.radius d))).mono fun i => + Tile.exp_radius_mono i.h.degree + +theorem mask_factor : Short (fun i : I => 2 ^ (Tile.radius i.T.scheme.d + (i.n + 1))) := + (radius_factor P d).exp_add (child_factor P d) + +theorem source_bound : Short (fun i : I => (i.T.Source i.a (b P)).width) := by + have hn : Short (fun i : I => 2 ^ i.n) := tiles.rate.short + have he : Short (fun i : I => 2 ^ i.T.scheme.e) := spans.short + have hd : Short (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.rate.short + have hw := (child_factor P d).of_exp + have occ := hw.add (he.mul ((short_const 1).add (hd.of_exp.add he.of_exp))) + have mat := (hn.mul (short_const 1)).add ((hn.mul occ).add (hn.mul (hd.mul hw))) + refine ((hn.mul Case.bits).add (((seat_factor P d).mul (short_const (b P))).add mat)).mono fun i + => ?_ + simp only [Template.Source, Window.Source, Match.Input, Format.width_pair, Format.width_vec, + Format.width_addr] + rw [Format.width_bit, Format.width_addr (i.T.scheme.h - i.a + 1)] + +theorem count_bound : Short (fun i : I => (i.T.WithCount i.a (b P)).width) := by + refine ((source_bound P d).add (tiles.rate.short.mul counters)).mono fun i => ?_ + rw [Template.WithCount, Format.width_pair, Format.width_vec, Format.width_addr] + +theorem pollRow_bound : Short (fun i : I => (i.T.PollRow i.a (b P)).width) := by + refine ((short_const 1).add (source_bound P d)).mono fun i => ?_ + rw [Template.PollRow, Format.width_pair, Format.width_bit] + +theorem side_bound : Short (fun i : I => (Side.Input (i.n + i.T.scheme.e) (b P)).width) := by + refine ((seat_factor P d).mul (short_const (Side.Entry (b P)).width)).mono fun i => ?_ + rw [Side.Input, Format.width_vec] + +theorem markWidth_bound : Short (fun i : I => markWidth P i.T i.r) := + (pollRow_bound P d).add (side_bound P d) + +theorem pointers_bound : Short (fun i : I => (i.T.Pointers (e Δ i.R)).width) := by + have hh : Short (fun i : I => i.height) := levels.rate.short.mono fun i => i.h.height + have hd : Short (fun i : I => i.T.scheme.d + 1) + := Case.slots.rate.short.of_exp.add (short_const 1) + have hp := (short_const 1).add (hd.add (hh.add ((short_const 0).add spans.short.of_exp))) + refine ((spans_bound P Δ d).rate.short.mul hp).mono fun i => ?_ + simp only [Template.Pointers, Trail.pointer, Format.width_pair, Format.width_vec, + Format.width_addr, pow_zero, one_mul] + rw [i.h.single, Format.width_bit, Format.width_addr (i.T.scheme.d + 1)] + +theorem label_bound : Short (fun i : I => (i.T.Label i.a Δ (degreeBound i.S i.T Δ) + (book P i.S i.T i.v i.h.vpos) (e Δ i.R) (cap P i.S i.T i.v i.h.vpos Δ i.R) + (meter i.S Δ i.R) (i.T.Pointers (e Δ i.R))).width) := by + refine ((next_bits P Δ d).add ((meter_bound P Δ d).rate.short.add (pointers_bound P Δ d))).mono + fun i => ?_ + rw [Template.Label, Format.width_pair, Format.width_pair, Format.width_addr, Format.width_addr] + +theorem mask_bound : Short (fun i : I => (Tile.mask i.T.scheme.d i.n + (i.T.degree i.a Δ (degreeBound i.S i.T Δ))).width) := by + have h := mask_factor P d + refine (h.mul ((child_slots P Δ d).rate.short.mul h)).mono fun i => ?_ + simp only [Tile.mask, Format.width_vec] + rw [Format.width_bit, mul_one] + +theorem word_bound : Short (fun i : I => (Tile.word i.T.scheme.d i.a i.n + (i.T.degree i.a Δ (degreeBound i.S i.T Δ)) (i.T.WithCount i.a (b P))).width) := by + have h := mask_factor P d + have hw := (short_const 2).add (groups.rate.short : Short (fun i : I => i.a)) + refine (((hw.add (child_factor P d).of_exp).add (h.mul ((child_slots P Δ d).rate.short.mul + h))).add + ((radius_factor P d).mul (count_bound P d))).mono fun i => ?_ + rw [Tile.width] + +theorem issueWidth_bound : Short (fun i : I => issueWidth P i.S i.T i.v i.h.vpos Δ i.R i.r) := + (word_bound P Δ d).add (label_bound P Δ d) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # The next frame of a contraction satisfies the host and block bounds -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Phase Phase.Case +variable {F : Type} [Field F] (P : Gadget F) (Δ d : ℕ) +local notation "I" => Case F P.b d + +theorem child_bound : Child (fun i : I => next P i.S i.T i.v i.h.vpos Δ i.R i.a) + (fun i => i.n + 1) := + ⟨fun _ => Nat.sub_le .., fun _ => le_rfl, child_factor P d, fun _ => rfl, + (spans_bound P Δ d).rate.short, (child_slots P Δ d).rate.short, + next_bits P Δ d, (meter_bound P Δ d).rate.short⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Arity of a grouping and voting table -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat + +open Assembly Packing Phase Phase.Case Coloring + +variable {F : Type} [Field F] (P : Gadget F) (d : ℕ) +local notation "I" => Case F P.b d + +theorem path_factor : Short (fun i : I => 2 ^ ((i.T.scheme.d + 1) * i.n)) := by + have h : Short (fun i : I => 2 ^ i.n) := tiles.rate.short + refine (h.pow (d + 1)).mono fun i => ?_ + rw [← pow_mul, mul_comm i.n] + exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ (Nat.succ_le_succ i.h.degree)) + +theorem tableWidth_bound : Short (fun i : I => i.T.tableWidth) := by + have he : Short (fun i : I => 2 ^ i.T.scheme.e) := spans.short + have hd : Short (fun i : I => i.T.scheme.d) := Case.slots.rate.short.of_exp + refine (Case.bits.add (he.mul ((short_const 1).add (hd.add he.of_exp)))).mono fun i => ?_ + simp only [Template.tableWidth, Window.Outgoing, Format.width_vec, Format.width_pair, + Format.width_addr] + rw [Format.width_bit] + +theorem patch_bound : Short (fun i : I => (Group.Patch ((i.T.scheme.d + + 1) * i.n) i.n i.T.count).width) := by + have hp := path_factor P d + refine ((short_const 1).add (hp.mul ((hp.mul (short_const 2)).add + (tiles.rate.short.mul counters)))).mono fun i => ?_ + rw [Group.width_patch] + +theorem groupLabels_bound : Short (fun i : I => (Group.Labels i.n).width) := by + refine (tiles.rate.short.mul (child_factor P d).of_exp).mono fun i => ?_ + rw [Group.Labels, Format.width_vec, Format.width_addr] + +theorem groupArity_bound : Short (fun i : I => Group.arity ((i.T.scheme.d + + 1) * i.n) i.n i.T.count) := by + have ht : Short (fun i : I => 2 ^ i.n) := tiles.rate.short + have hw := (child_factor P d).of_exp + have hs : Short (fun i : I => (Group.Summary i.n).width) := + (ht.mul (ht.of_exp.add (ht.mul hw))).mono fun i => by rw [Group.width_summary] + exact (((patch_bound P d).add hs).add ht.of_exp).add (groupLabels_bound P d) + +theorem colors_bound : Short (fun i : I => (i.T.Colors i.a).width) := by + refine tiles.rate.short.mono fun i => ?_ + rw [Template.Colors, Format.width_vec, Format.width_bit, mul_one] + +theorem vote_bound : Short (fun i : I => (i.T.Vote i.a).width) := by + refine ((child_factor P d).mul ((seat_factor P d).of_exp.add (short_const 1))).mono fun i => ?_ + rw [Template.Vote, Format.width_vec, Format.width_addr] + +theorem prepareWidth_bound : Short (fun i : I => i.T.arity i.a (b P)) := + (((tableWidth_bound P d).add (groupArity_bound P d)).add + ((child_factor P d).of_exp.add (colors_bound P d))).add ((pollRow_bound P d).add (vote_bound P + d)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Common graph widths and charge per occupied block -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Assembly History Packing Phase Phase.Case Coloring Window + +variable {F : Type} [Field F] (P : Gadget F) (Δ d : ℕ) +local notation "I" => Case F P.b d + +theorem size_bound : Long (fun i : I => i.T.size i.a) := + hosts.add (child_factor P d).long.of_exp + +theorem expanded {f : I → ℕ} (h : Case.Row f) : Cost (fun i : I => 2 ^ (i.T.size i.a) * f i) := + h.expand (child_factor P d) + +theorem format_bound : Cost (fun i : I => i.T.format.width) := Case.Child.parent.format + +theorem next_bound : Cost (fun i : I => (next P i.S i.T i.v i.h.vpos Δ i.R i.a).format.width) := + (child_bound P Δ d).format + +theorem grouped {A : I → Format} (h : Short (fun i => (A i).width)) : + Cost (fun i : I => (Fmt.groups i.m i.T.scheme.d i.a (A i)).width) := by + have hc : Long (fun i : I => 2 ^ i.T.scheme.d * i.m) := Case.slots.rate.short.long.mul hosts + refine (Row.hosts (hc.row.add h.groups)).mono fun i => ?_ + exact le_of_eq (Fmt.width_rows _ _ _ _) + +theorem counted_bound : Cost (fun i : I => (i.T.Counted i.a (b P)).width) := + grouped P d (count_bound P d) + +theorem poll_bound : Cost (fun i : I => (i.T.Poll i.a (b P)).width) := by + refine ((format_bound P d).add (grouped P d (source_bound P d))).mono fun i => ?_ + rw [Template.Poll, Format.width_pair] + +theorem seats_bound : Cost (fun i : I => Fintype.card (i.T.Slots i.a)) := by + refine (seat_factor P d).groups.hosts.mono fun i => ?_ + rw [Fintype.card_congr (i.T.seatIndex i.a).symm, Fintype.card_fin, pow_add, pow_add, mul_assoc] + +theorem candidate_bound : Cost (fun i : I => (i.T.Candidate i.a (b P)).width) := by + refine ((seats_bound P d).mul (short_const (b P))).mono fun i => ?_ + simp only [Template.Candidate, Branches.format, Fmt.width_pi, Format.width_addr, Finset.sum_const, + Finset.card_univ, smul_eq_mul] + rfl + +theorem status_bound : Cost (fun i : I => (i.T.Status i.a).width) := by + refine (expanded P d (long_const 1).row).mono fun i => ?_ + rw [Template.Status, Format.width_vec, Format.width_bit] + +theorem graph_bound : Cost (fun i : I => (i.T.Graph i.a Δ (degreeBound i.S i.T Δ)).width) := by + have h := (child_slots P Δ d).rate.short.long.mul (size_bound P d) + refine (expanded P d (Long.row h)).mono fun i => ?_ + rw [Template.Graph, Neighborhood.Rows, Format.width_vec, Format.width_vec, Format.width_addr] + +theorem header_bound : Cost (fun i : I => (i.T.ChildHeader i.a Δ (degreeBound i.S i.T Δ)).width) + := by + have h := (long_const 2).add ((child_slots P Δ d).rate.short.long.mul (long_const 2)) + refine (expanded P d (Long.row h)).mono fun i => ?_ + simp only [Template.ChildHeader, Group.Flags, Format.width_vec, Format.width_pair] + rw [Format.width_bit] + +theorem raw_bound : Cost (fun i : I => (i.T.Raw i.a (b P) Δ (degreeBound i.S i.T Δ)).width) := by + have hb : Cost (fun _ : I => Format.bit.width) := (long_const _).row.cost + refine ((status_bound P d).add (hb.add ((graph_bound P Δ d).add (counted_bound P d)))).mono fun i + => ?_ + rw [Template.Raw, Tile.raw, Format.width_pair, Format.width_pair, Format.width_pair] + +theorem headed_bound : Cost (fun i : I => (i.T.Headed i.a (b P) Δ (degreeBound i.S i.T Δ)).width) + := by + refine ((raw_bound P Δ d).add (header_bound P Δ d)).mono fun i => ?_ + rw [Template.Headed, Format.width_pair] + +theorem output_bound {A : I → Format} (h : Short (fun i => (A i).width)) : + Cost (fun i : I => (Tile.output i.m i.a i.n (A i)).width) := by + refine (expanded P d h.groups).mono fun i => ?_ + rw [Tile.output, Format.width_vec, Format.width_vec] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Cost of simultaneous history updates with long host addresses -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Assembly Packing Phase Phase.Case Coloring Window + +variable {F : Type} [Field F] (P : Gadget F) (Δ d : ℕ) +local notation "I" => Case F P.b d + +private abbrev slot (i : I) := i.T.degree i.a Δ (degreeBound i.S i.T Δ) +private abbrev label (i : I) := i.T.Label i.a Δ (degreeBound i.S i.T Δ) + (book P i.S i.T i.v i.h.vpos) (e Δ i.R) (cap P i.S i.T i.v i.h.vpos Δ i.R) + (meter i.S Δ i.R) (i.T.Pointers (e Δ i.R)) + +theorem pair_cost {A B : I → Format} (h : Cost (fun i => (A i).width)) (k : Cost (fun i + => (B i).width)) : + Cost (fun i => ((A i).pair (B i)).width) := + (h.add k).mono fun _ => (Format.width_pair ..).le + +private theorem walk_bound : Short (fun i : I => (Walks 8 i.T.scheme.d (i.T.WithCount i.a (b + P))).width) := by + refine ((radius_factor P d).mul (count_bound P d)).mono fun i => ?_ + rw [Walks, Format.width_vec] + +private theorem incoming_bound : Cost (fun i : I => + (Tile.incoming i.m i.T.scheme.d i.a i.n (slot P Δ d i) (i.T.WithCount i.a (b P))).width) := by + have masks : Cost (fun i : I => (Format.vec i.m (Tile.mask i.T.scheme.d i.n (slot P Δ d + i))).width) := by + refine (mask_bound P Δ d).long.row.hosts.mono fun i => ?_ + rw [Format.width_vec] + have h := pair_cost P d masks (grouped P d (walk_bound P d)) + have hb : Cost (fun _ : I => Format.bit.width) := (long_const _).row.cost + exact pair_cost P d (status_bound P d) (pair_cost P d hb h) + +private theorem tile_bound : Cost (fun i : I => + Tile.cost i.m i.T.scheme.d i.a i.n (slot P Δ d i) (i.T.WithCount i.a (b P)) (label P Δ d i)) + := by + have h := ((short_const 1).add ((short_const 137).mul (word_bound P Δ d))).add (label_bound P Δ d) + refine (((incoming_bound P Δ d).scale 4).add (expanded P d (Short.groups h))).mono fun i => ?_ + rw [Tile.cost, mul_assoc] + +private theorem bank_bound : Cost (fun i : I => Tile.bankCost i.m i.T.scheme.d i.a i.n (slot P Δ d + i) + (i.T.WithCount i.a (b P)) (walk P i.T i.r) (accessCost (i.m + i.T.scheme.d) (walk P i.T i.r)) + (precision i.S i.T Δ i.r)) := by + have hp : Long (fun i : I => precision i.S i.T Δ i.r) := + ((size_bound P d).add (mask_factor P d).long).add (child_slots P Δ d).rate.short.long + have hv : Case.Row (fun i : I => walk P i.T i.r) := (walk_bound P d).groups + have h := Mixed.long Case.m (((long_const 100).add (hosts.add (radius_factor P d).long)).pow 20) + have k := expanded P d (Long.row (((long_const 100).add hp).pow 40)) + exact (((raw_bound P Δ d).scale 24).add ((h.add k).scale 4)).add + ((read_bound P.b d Case.slots.rate.short hv).scale 9) + +theorem issueCost_bound : Cost (fun i : I => issueCost P i.S i.T i.v i.h.vpos Δ i.R i.r) := by + have h₀ := headed_bound P Δ d + have h₁ := pair_cost P d (graph_bound P Δ d) (header_bound P Δ d) + have h₂ := raw_bound P Δ d + have h₃ := output_bound P d (label_bound P Δ d) + have h₄ := pair_cost P d (next_bound P Δ d) (output_bound P d (pointers_bound P Δ d)) + have N := (bank_bound P Δ d).add (tile_bound P Δ d) + have keep := (h₀.add (h₁.scale 2)).scale 4 + have run := ((h₀.add (h₂.scale 2)).scale 4).add N + exact ((h₀.scale 20).add (keep.add run)).add (((pair_cost P d h₁ h₃).add (h₄.scale 2)).scale 4) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Cost of choosing a layout and constructing the common graph masks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Assembly Packing Phase Phase.Case Coloring + +variable {F : Type} [Field F] (P : Gadget F) (Δ d : ℕ) +local notation "I" => Case F P.b d + +theorem groupInput_bound : Cost (fun i : I => (i.T.groupInput i.a).width) := by + have hd : Long (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.rate.short.long + have hn := Long.row (hd.mul hosts) + have hf := Long.row (hd.mul (long_const 2)) + have hv : Case.Row (fun i : I => 2 ^ i.a * (2 ^ i.n * i.T.count)) := + Short.groups (tiles.rate.short.mul counters) + refine (Row.hosts (hn.add ((long_const 1).row.add (hf.add hv)))).mono fun i => ?_ + simp only [Template.groupInput, Group.Input, Fmt.bank, Group.Parcel, Group.Flags, + Format.width_vec, + Format.width_pair, Format.width_addr] + rw [Format.width_bit] + +private theorem childInput_bound : Cost (fun i : I => (Child.Input i.m i.T.scheme.d).width) := by + have hd : Long (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.rate.short.long + refine (Mixed.long Case.m (hd.mul ((long_const 1).add hosts))).mono fun i => ?_ + simp only [Child.Input, Format.width_vec, Format.width_pair, Format.width_addr] + rw [Format.width_bit] + +private theorem nav_bound {q : I → ℕ} (h : Short (fun i => 2 ^ (q i))) : + Cost (fun i : I => i.T.navCost i.a (q i)) := by + have bits := Template.navComputation (size_bound P d) h.long + exact Template.navCost_mixed (large := Case.long) (small := Case.short) + (height := Case.height) (hosts := Case.m) (F := fun _ => F) + (T := fun i : I => i.T) (a := fun i => i.a) + (degree := q) (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (format_bound P d) (groupInput_bound P d) (childInput_bound P d) + (expanded P d (Long.row bits)) + +private theorem childCost_bound : Cost (fun i : I => i.T.childCost i.a Δ (degreeBound i.S i.T Δ)) + := by + exact Template.childCost_mixed (large := Case.long) (small := Case.short) + (height := Case.height) (hosts := Case.m) (F := fun _ => F) + (T := fun i : I => i.T) (a := fun i => i.a) + (delta := fun _ => Δ) (C := fun i => degreeBound i.S i.T Δ) + (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (format_bound P d) (status_bound P d) (nav_bound P d (child_slots P Δ d).rate.short) + +private theorem headerCost_bound : Cost (fun i : I => i.T.headerCost i.a Δ (degreeBound i.S i.T Δ)) + := by + have p := (child_slots P Δ d).rate.short + have q : Short (fun i : I => 2 ^ (Child.nextWidth i.n Δ i.T.scheme.d)) := by + refine p.mono fun i => ?_ + simp only [Template.degree, Template.bound, i.h.core, Bool.false_eq_true, ↓reduceIte] + rfl + have bits := Template.headerComputation (size_bound P d) p.long q.long + have flags : Cost (fun i : I => (Format.vec (i.T.size i.a) + (.vec (i.T.degree i.a Δ (degreeBound i.S i.T Δ)) .bit)).width) := by + refine (expanded P d p.long.row).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_bit, mul_one] + exact Template.headerCost_mixed (large := Case.long) (small := Case.short) + (height := Case.height) (hosts := Case.m) (F := fun _ => F) + (T := fun i : I => i.T) (a := fun i => i.a) + (delta := fun _ => Δ) (C := fun i => degreeBound i.S i.T Δ) + (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (format_bound P d) (status_bound P d) (nav_bound P d p) (nav_bound P d q) + (expanded P d (Long.row bits)) flags (header_bound P Δ d) + +theorem groups_cost {f : I → ℕ} (hf : Short f) : Cost (fun i : I => 2 ^ (i.m + i.a) * f i) := by + simpa only [pow_add, mul_assoc] using hf.groups.hosts + +private theorem groups_width {A : I → Format} (h : Short (fun i => (A i).width)) : + Cost (fun i : I => (Format.vec (i.m + i.a) (A i)).width) := + (groups_cost P d h).mono fun _ => (Format.width_vec ..).le + +private theorem entries_bound : Cost (fun i : I => (i.T.Entries i.a (b P)).width) := by + refine ((seats_bound P d).mul (short_const (Side.Entry (b P)).width)).mono fun i => ?_ + simp only [Template.Entries, Branches.Marked, Fmt.width_pi, Finset.sum_const, Finset.card_univ, + smul_eq_mul] + rfl + +private theorem markCost_bound : Cost (fun i : I => i.T.markCost i.a (b P)) := by + have p := pollRow_bound P d + have s := side_bound P d + exact Template.markCost_mixed (large := Case.long) (small := Case.short) + (height := Case.height) (hosts := Case.m) (F := fun _ => F) + (T := fun i : I => i.T) (a := fun i => i.a) + (b := fun _ => b P) + (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (poll_bound P d) (groups_width P d p) (groups_width P d s) + (entries_bound P d) (groups_cost P d (((short_const 1).add p).add s)) + +private theorem layoutCost_bound : Cost (fun i : I => i.T.layoutCost i.a (b P) (profile P)) := by + exact Template.layoutCost_mixed (large := Case.long) (small := Case.short) + (height := Case.height) (hosts := Case.m) (F := fun _ => F) + (T := fun i : I => i.T) (a := fun i => i.a) + (bits := b P) + (profile := profile P) (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (markCost_bound P d) (seats_bound P d) (entries_bound P d) + +private theorem rawCost_bound : Cost (fun i : I => + i.T.rawCost i.a (b P) Δ (degreeBound i.S i.T Δ) (profile P)) := by + have hb : Cost (fun _ : I => Format.bit.width) := (long_const _).row.cost + exact Template.rawCost_mixed (large := Case.long) (small := Case.short) + (height := Case.height) (hosts := Case.m) (F := fun _ => F) + (T := fun i : I => i.T) (a := fun i => i.a) + (b := fun _ => b P) + (delta := fun _ => Δ) (C := fun i => degreeBound i.S i.T Δ) (profile := profile P) + (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (format_bound P d) (poll_bound P d) (counted_bound P d) (status_bound P d) + (graph_bound P Δ d) hb (childCost_bound P Δ d) + (layoutCost_bound P d) (raw_bound P Δ d) + +theorem headedCost_bound : Cost (fun i : I => headedCost P i.S i.T Δ i.r) := by + exact Template.headedCost_mixed (large := Case.long) (small := Case.short) + (height := Case.height) (hosts := Case.m) (F := fun _ => F) + (T := fun i : I => i.T) (a := fun i => i.a) + (b := fun _ => b P) (delta := fun _ => Δ) (C := fun i => degreeBound i.S i.T Δ) + (profile := profile P) (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (format_bound P d) (poll_bound P d) (rawCost_bound P Δ d) (headerCost_bound P Δ d) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Costs of the input, exterior history and scalar sweep of a contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Phase Phase.Case +variable {F : Type} [Field F] (P : Gadget F) (Δ d : ℕ) +local notation "I" => Case F P.b d + +theorem input_bound : Cost (fun i : I => (In P i.S i.T i.r).width) := + pair_cost P d Child.parent.full (candidate_bound P d) + +theorem sweepCost_bound : + Cost (fun i : I => Snapshot.sweepCost i.S (next P i.S i.T i.v i.h.vpos Δ i.R i.a)) := + (child_bound P Δ d).sweep + +theorem secondCost_bound : Cost (fun i : I => secondCost P i.S i.T i.v i.h.vpos Δ i.R i.r) := by + have hm : Cost (fun i : I => (Mid P i.S i.T Δ i.r).width) := + pair_cost P d (headed_bound P Δ d) Child.current + have hg := gather_bound (F := F) P.b d Child.parent.neighbors Child.parent.row + have H := child_bound P Δ d + have hs := H.gather (c := fun i => accessCost (i.m + i.T.scheme.d) (origin i.S i.T)) hg + have hk := H.carry (k := fun i => i.T.scheme.d + 1) (A := fun i + => Mid P i.S i.T Δ i.r) Child.fan hm + refine ((((hm.scale 100).add (issueCost_bound P Δ d)).add hs).add hk).mono fun i => ?_ + simp only [secondCost, origin, Case.a, Case.m, Case.height, le_refl] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Beat/Rule.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Beat/Rule.lean new file mode 100644 index 0000000000..d0cecfa437 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Beat/Rule.lean @@ -0,0 +1,564 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.HeaderCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Issue +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.TraceNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanSupplies + +/-! # Preparation cost with common addresses and short per-block records -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat + +open Assembly Packing Phase Phase.Case Coloring + +variable {F : Type} [Field F] (P : Gadget F) (d : ℕ) +local notation "I" => Case F P.b d + +private theorem parcel_bound : Case.Row (fun i : I => parcel i.T i.r) := by + have hd : Long (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.rate.short.long + have hv : Case.Row (fun i : I => 2 ^ i.a * (2 ^ i.n * i.T.count)) := + Short.groups (tiles.rate.short.mul counters) + refine ((long_const 1).row.add ((Long.row (hd.mul (long_const 2))).add hv)).mono fun i => ?_ + simp only [parcel, Group.Parcel, Group.Flags, Format.width_vec, Format.width_pair, + Format.width_addr] + rw [Format.width_bit] + +private theorem labels_bound : Case.Row (fun i : I => labels i.T i.r) := by + refine (groupLabels_bound P d).groups.mono fun i => ?_ + rw [labels, Window.LabelSet, Format.width_vec] + +private theorem request_bound : Cost (fun i : I => (i.T.Request i.a (b P)).width) := + pair_cost P d (format_bound P d) (candidate_bound P d) + +private theorem fields_bound : + Cost (fun i : I => (Window.Fields i.T.scheme i.a i.n (b P)).width) := by + have hs : Cost (fun i : I => i.T.scheme.format.width) := + (format_bound P d).mono fun i => by + rw [Template.format, Format.width_pair] + exact Nat.le_add_right .. + have ht : Cost (fun i : I => (Window.Tags i.T.scheme i.a i.n).width) := + (labels_bound P d).hosts.mono fun i => by rw [Window.Tags, Format.width_vec]; exact le_rfl + exact pair_cost P d hs (pair_cost P d ht (pair_cost P d (colors_bound P d).long.row.cost + (candidate_bound P d))) + +private theorem patchCost_bound : + Cost (fun i : I => Group.patchCost i.m i.T.scheme.d i.a i.n i.T.count (parcel i.T i.r) + (accessCost (i.m + (i.T.scheme.d + 1) * i.n) (parcel i.T i.r))) := by + have hp := path_factor P d + have hw := parcel_bound P d + have patches : Cost (fun i : I => (Group.Patches i.m i.T.scheme.d i.a i.n i.T.count).width) := + (groups_cost P d (patch_bound P d)).mono fun i => by rw [Group.Patches, Format.width_vec] + have loads : Cost (fun i : I => (Format.vec i.m (.vec ((i.T.scheme.d + 1) * i.n) + (Group.Parcel i.T.scheme.d i.a i.n i.T.count))).width) := + (Row.hosts (hw.left hp)).mono fun i => by rw [Format.width_vec, Format.width_vec]; exact le_rfl + have cost := Mixed.long Case.m (((long_const 100).add (hosts.add hp.long)).pow 220) + exact (((((groupInput_bound P d).add patches).add loads).add cost).scale 1000).add (gather_bound + P.b d hp hw) + +private theorem election_bound {c w : I → ℕ} (hc : Short (fun i => 2 ^ c i)) (hw : Short w) : + Cost (fun i : I => 2 ^ c i * (2 ^ (i.m + i.a) * (100 + w i) ^ 5 + + (100 + (c i + (w i + (i.m + i.a)))) ^ 42)) := by + have h := groups_cost P d (((short_const 100).add hw).pow 5) + have hm : Long (fun i : I => i.m + i.a) := hosts.add Case.groups.rate.short.long + have h' := Template.electionComputation hc.long.of_exp hw.long hm + exact (h.add (Long.row h').cost).left hc + +private theorem groupCost_bound : + Cost (fun i : I => Group.cost (i.m + i.a) ((i.T.scheme.d + 1) * i.n) i.n i.T.count) := by + have hn : Short (fun i : I => 2 ^ i.n) := tiles.rate.short + exact Template.groupCost_mixed (dimension := fun i : I => i.m + i.a) + (query := fun i => (i.T.scheme.d + 1) * i.n) (width := fun i => i.n) + (labels := fun i => i.T.count) (fun i => i.long_two) (fun i => i.short_two) + (fun i => i.short_long) (groups_cost P d ((short_const 1).add (groupArity_bound P d))) + (election_bound P d hn hn.of_exp) + +private theorem light_bound : Cost (fun i : I => i.T.lightCost i.a (b P)) := by + have hc := colors_bound P d + have hv := vote_bound P d + have hr := pollRow_bound P d + have hp := poll_bound P d + have polls : Cost (fun i : I => (i.T.Polls i.a (b P)).width) := + (groups_cost P d hr).mono fun i => by rw [Template.Polls, Format.width_vec] + have votes : Cost (fun i : I => (i.T.Votes i.a).width) := + (groups_cost P d hv).mono fun i => by rw [Template.Votes, Format.width_vec] + have ht := groups_cost P d (((short_const 1).add hr).add hv) + have he := election_bound P d (child_factor P d) ((seat_factor P d).of_exp.add (short_const 1)) + have cost := (((hp.add (polls.scale 2)).scale 4).add ht).add (((votes.scale 3).add he).scale 4) + have hdr := (cost.add (long_const 1).row.cost).add (Long.row (child_factor P d).long.of_exp).cost + exact (hdr.add hc.long.row.cost).add ((pair_cost P d hp hc.long.row.cost).scale 40) + +theorem prepareCost_bound : Cost (fun i : I => prepareCost P i.T i.r) := by + have hr := request_bound P d + have hf := fields_bound P d + have elected : Cost (fun i : I => (i.T.Elected i.a).width) := + (groups_cost P d (groupLabels_bound P d)).mono fun i + => by rw [Template.Elected, Format.width_vec] + have hv := gather_bound P.b d Case.slots.rate.short (labels_bound P d) + have records := (hf.add (grouped P d (source_bound P d))).scale 100 + have install : Cost (fun i : I => 2 ^ i.m * 2 ^ i.a * 2 ^ i.n * (1 + i.T.tableWidth)) := by + refine (groups_cost P d (tiles.rate.short.mul ((short_const 1).add (tableWidth_bound P + d)))).mono fun i => ?_ + rw [pow_add, mul_assoc] + have gather := (hv.add records).add install + have setup := (((hr.add (groupInput_bound P d)).add elected).add hf).scale 200 + have collect := ((setup.add (patchCost_bound P d)).add (groupCost_bound P d)).add gather + exact ((hr.scale 40).add collect).add (light_bound P d) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Local load, mass and code budgets for one batch contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Assembly + +variable {F : Type} [Field F] {x y : Wire} {P : Gadget F} + {S : Setup F x y} {T : Template F} {z Δ : ℕ} {R : Budget} {w r d K : ℕ} {σ : ℝ} + (h : Phase.Input S T R w r P.b (P.b * z) z d K σ) + (q : (frame S T (P.b * z) Δ R).state) (s : Poll h q) (i : s.choices) (hd : 0 < Δ) + +local notation "t" => ticket h q s i +local notation "hc" => degree_le S T Δ +local notation "hb" => choices P +local notation "H" => Template.Branch.layout t hc +local notation "A" => Template.Branch.state t hb +local notation "B₁" => (gain Δ * R.load) +local notation "M" => book P S T z h.vpos + +include hd in +open scoped Classical in +theorem estimates : + (H).Bounded ((4 * Δ) ^ 900) ((4 * degreeBound S T Δ) ^ 900) ((B₁ : ℕ)* (S.z : ℝ)) ∧ + ((H).X : ℝ) ≤ P.ratio * R.width + (S.fringe.Z + σ) ∧ + S.first.Preserves H ∧ ((H).mass : ℝ) ≤ R.mass + 2 * R.width ∧ + S.first.Tracks H (((Δ + 1) * 2) * R.reach) := by + obtain ⟨bounds, width, preserve, mass, tracks⟩ := + (t).estimates hc hd (slack_pos h) (by positivity) q.property.bounded + refine ⟨⟨bounds.1, bounds.2.1, ?_⟩, ?_, q.val.preserved.trans preserve, ?_, + q.property.tracks.trans tracks h.height (Nat.sub_le _ _)⟩ + · intro v j + refine (bounds.2.2 v j).trans ?_ + simp only [gain, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, mul_assoc] + gcongr; norm_num + · exact width.trans (add_le_add_left (mul_le_mul_of_nonneg_left q.property.width + P.ratio_bounds.1) _) + · rw [mass, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat] + exact add_le_add q.property.mass (mul_le_mul_of_nonneg_left q.property.width (by norm_num)) + +include hd in +open scoped Classical in +theorem mass : (H).mass ≤ S.cap := + Nat.cast_le.mp ((estimates h q s i hd).2.2.2.1.trans h.history) + +open scoped Classical in +private theorem widths (j : (t).p.post.toPresentation.BorderSpan) : + (t).p.post.toPresentation.borderWidth j = S.U := + q.val.exterior_width _ j.property.2 j.property.1 + +include hd in +open scoped Classical in +theorem room : (A).Room (e Δ R) := by + apply (t).room hb hd (by positivity) q.property.bounded + · have hh := Nat.le_pow_clog (by decide : 1 < 2) B₁ + have hv : B₁ * S.z ≤ 2 ^ (e Δ R) * z := Nat.mul_le_mul hh (scale_le h) + unfold gain at hv + rw [← mul_assoc] + exact_mod_cast hv + · intro j + exact h.ceiling.trans_eq (widths h q s i j).symm + +local notation "rm" => room h q s i hd + +open scoped Classical in +theorem tagged : (A).Charged (M).ord S.z R.tag := fun v => q.property.tagged v.1 v.2 + +open scoped Classical in +theorem ready : (t).Ready hb hc M rm (cap P S T z h.vpos Δ R) := by + refine (t).fitted hb hc hd M rm q.property.neutral ?_ (tagged h q s i) h.zpos + (mass h q s i hd) (estimates h q s i hd).1.2.2 le_rfl + intro j + exact History.Book.represent T.scheme P z h.vpos T.order {S.U} + (Finset.mem_singleton.mpr (widths h q s i j)) + +include hd in +open scoped Classical in +theorem valid : (meter S Δ R).Valid H := by + have hU : S.z ≤ S.U := (scale_le h).trans ((Nat.le_mul_of_pos_left _ P.pos).trans h.ceiling) + have hn : 2 ^ S.discount * B₁ * S.z < 2 ^ (c S Δ R) := + (Nat.mul_le_mul_left _ hU).trans_lt (Nat.lt_of_succ_le (Nat.le_pow_clog (by decide) _)) + have ht : (2 : ℝ) ^ S.discount * ((B₁ : ℕ) * (S.z : ℝ)) < 2 ^ (c S Δ R) := by + rw [← mul_assoc] + exact_mod_cast hn + have scale : (B₁ : ℕ) * (S.z : ℝ) < 1 * (2 : ℝ) ^ (c S Δ R) := by + rw [one_mul] + exact (le_mul_of_one_le_left (mul_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) + (one_le_pow₀ (by norm_num : (1 : ℝ) ≤ 2))).trans_lt ht + exact Template.Meter.valid_of_charge (H) (c S Δ R) _ (mass h q s i hd) + (estimates h q s i hd).1.2.2 scale ht (fun _ => ⟨1, Nat.cast_one.symm⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # The selected contraction, including exterior stack names -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Assembly + +variable {F : Type} [Field F] {x y : Wire} {P : Gadget F} + {S : Setup F x y} {T : Template F} {z Δ : ℕ} {R : Budget} {w r d K : ℕ} {σ : ℝ} + (h : Phase.Input S T R w r P.b (P.b * z) z d K σ) + (q : (frame S T (P.b * z) Δ R).state) (s : Poll h q) (i : s.choices) (hd : 0 < Δ) + +local notation "a" => (T.scheme.h - r) +local notation "t" => ticket h q s i +local notation "hc" => degree_le S T Δ +local notation "hb" => choices P +local notation "H" => Template.Branch.layout t hc +local notation "M" => book P S T z h.vpos +local notation "𝓒" => cap P S T z h.vpos Δ R +local notation "𝓚" => meter S Δ R +local notation "rm" => room h q s i hd +local notation "Y" => next P S T z h.vpos Δ R a + +open scoped Classical in +/-- The value specified by `(t).encodes hb hc M rm 𝓒 𝓚 hd (ready h q s i hd) (valid h q s i +hd)`. -/ +abbrev emitted := (t).encodes hb hc M rm 𝓒 𝓚 hd (ready h q s i hd) (valid h q s i hd) +open scoped Classical in +/-- The value specified by `(t).move hb hc M rm 𝓒`. -/ +abbrev move := (t).move hb hc M rm 𝓒 + +open scoped Classical in +/-- Builds `Snapshot.Data S Y z where rows` with the specified `rows`, `encodes`, `trail`, +`tracks`. -/ +def result (hr : (Δ + 1) * 2 ≤ K) : Snapshot.Data S Y z where + rows := (t).output hb hc M rm 𝓒 𝓚 + G := H + encodes := emitted h q s i hd + trail := (move h q s i hd).update S.d q.val.trail + tracks := by + have env := estimates h q s i hd + have slots : 0 < S.d := by + have hh : 0 < K := by omega + exact (Nat.mul_pos (by norm_num) (Nat.mul_pos hh h.reach)).trans_le h.origins + refine q.val.tracks.update ((t).move_agrees hb hc M rm 𝓒 (ready h q s i hd)) (reserve h) slots + ?_ + intro v + exact (S.origins H (emitted h q s i hd).post env.2.2.1 + (env.2.2.2.2.mono (Nat.mul_le_mul_right _ hr)) (reserve h) h.trivalent v).trans h.origins + preserved := (estimates h q s i hd).2.2.1 + +variable (hr : (Δ + 1) * 2 ≤ K) + +open scoped Classical in +theorem tagged_result : (result h q s i hd hr).Tagged (R.tag + added P S T z h.vpos Δ R a) := by + intro v j hv + rw [added, ← add_assoc] + exact (t).charged_after hb hc M rm (ready h q s i hd) 𝓚 + (tagged h q s i) h.zpos (scale_le h) (v, j) hv + +include hd hr in +open scoped Classical in +theorem expands (u : Val S.input) (v : Val S.output) : + ∑ i, (result h q s i hd hr).G.diagram.eval u v = q.val.G.diagram.eval u v := + s.group.eval_contract s.matching P (q.val.G.regroup a (Nat.sub_le _ _)).units h.vpos u v + +open scoped Classical in +private theorem core_growth (hΔ : 3 ≤ Δ) : (4 * Δ) ^ 900 ≤ Δ ^ degreePower := by + have hs : 4 ≤ Δ ^ 2 := by nlinarith + have grow (n : ℕ) : (4 * Δ) ^ n ≤ Δ ^ (3 * n) := by + rw [pow_mul] + exact Nat.pow_le_pow_left ((Nat.mul_le_mul_right Δ hs).trans_eq (pow_succ _ _).symm) _ + have h := grow 900 + rw [show 3 * (900 : ℕ) = degreePower from rfl] at h + exact h + +open scoped Classical in +private theorem preserved_bounds (hΔ : 3 ≤ Δ) (hg : gain Δ ≤ K) : + (result h q s i hd hr).sweep.G.Bounded (Δ ^ degreePower) + (degreeBound S (Y).sweep (Δ ^ degreePower)) + ((Phase.after S T r R K P.ratio 1 σ).load * S.z) := by + obtain ⟨bounds, _, _, _, _⟩ := estimates h q s i hd + let E := result h q s i hd hr + refine ⟨?_, ?_, ?_⟩ + · exact fun j => (bounds.1 j).trans (core_growth hΔ) + · intro j + have he : Fintype.card E.sweep.G.V ≤ 2 ^ (Y).scheme.m := by + simpa using Fintype.card_le_of_injective _ E.sweep.encodes.post.host.injective + exact (Finset.card_le_univ _).trans (he.trans (Nat.le_add_left _ _)) + · intro v j + change (H).load v j ≤ (K * R.load : ℕ) * (S.z : ℝ) + exact (bounds.2.2 v j).trans (mul_le_mul_of_nonneg_right + (Nat.cast_le.mpr (Nat.mul_le_mul_right _ hg)) (Nat.cast_nonneg _)) + +open scoped Classical in +theorem preserved (hΔ : 3 ≤ Δ) (hg : gain Δ ≤ K) + (ht : added P S T z h.vpos Δ R a ≤ (Phase.rate S T r R) ^ K) : + Ready (Δ ^ degreePower) (Phase.after S T r R K P.ratio 1 σ) (result h q s i hd hr).sweep := by + obtain ⟨_, width, _, mass, tracks⟩ := estimates h q s i hd + let E := result h q s i hd hr + refine ⟨⟨((t).v.1.1, (t).v.2)⟩, E.sweep_neutral, ?_, + preserved_bounds h q s i hd hr hΔ hg, tracks.mono (Nat.mul_le_mul_right R.reach hr), ?_, mass⟩ + · apply (E.sweep_tagged _).mpr + intro v j hv + refine ((tagged_result h q s i hd hr) v j hv).trans ?_ + exact Nat.mul_le_mul_right _ (Nat.add_le_add_left ht _) + · change ((H).X : ℝ) ≤ P.ratio * R.width + 1 * (S.fringe.Z + σ) + rw [one_mul] + exact width + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Printing the next table names and updating their exterior labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {P : Gadget F} + {S : Setup F x y} {T : Template F} {z Δ : ℕ} {R : Budget} {w r d K : ℕ} {σ : ℝ} + (h : Phase.Input S T R w r P.b (P.b * z) z d K σ) + (s : ∀ q : (frame S T (P.b * z) Δ R).state, Poll h q) + (hd : 0 < Δ) (hr : (Δ + 1) * 2 ≤ K) + +local notation "a" => (T.scheme.h - r) +local notation "hc" => degree_le S T Δ +local notation "hb" => choices P +local notation "M" => book P S T z h.vpos +local notation "𝓒" => cap P S T z h.vpos Δ R +local notation "𝓚" => meter S Δ R +local notation "Y" => next P S T z h.vpos Δ R a +local notation "A" => Mid P S T Δ r +local notation "j" => (T.scheme.m + T.scheme.d) + +open scoped Classical in +/-- Indexes the path by the coordinates of `Σ q : (frame S T (P.b * z) Δ R).state, (s +q).choices`. -/ +abbrev Path := Σ q : (frame S T (P.b * z) Δ R).state, (s q).choices + +open scoped Classical in +/-- The value specified by `((ticket h i.1 (s i.1) i.2).head hb, i.1.val.rows.1, +i.1.val.trail)`. -/ +def mid (i : Path h s) : (A).obj := + ((ticket h i.1 (s i.1) i.2).head hb, i.1.val.rows.1, i.1.val.trail) + +open scoped Classical in +theorem second : ∃ table : Table F, Processor.arity table = issueWidth P S T z h.vpos Δ R r ∧ + ∀ {u : ℕ} {L : Set (Table F)}, 3 ≤ u → table ∈ L → issueWidth P S T z h.vpos Δ R r ≤ u → + (∀ v, Access F u L j v (accessCost j v)) → + Computes F u L A (S.format Y) (mid h s) + (fun i => (result h i.1 (s i.1) i.2 hd hr).code) (fun _ => 1) + (secondCost P S T z h.vpos Δ R r) := by + let q (i : Path h s) := ticket h i.1 (s i.1) i.2 + let E := T.Headed a (b P) Δ (degreeBound S T Δ) + let D := Saved S T + let rm (i : Path h s) := room h i.1 (s i.1) i.2 hd + obtain ⟨table, hwidth, hgate⟩ := T.trace_net hb hc M 𝓒 𝓚 q rm (fun i + => ready h i.1 (s i.1) i.2 hd) + refine ⟨table, hwidth, ?_⟩ + intro u L hu hm hw acc + let l := precision S T Δ r + have hl : T.size a ≤ l := (Nat.le_add_right ..).trans (Nat.le_add_right ..) + have hh : 2 ^ (Window.Tile.radius T.scheme.d + ((T.scheme.h - a) + 1)) ≤ l := + (Nat.le_add_left ..).trans (Nat.le_add_right ..) + have hq : 2 ^ (T.degree a Δ (degreeBound S T Δ)) ≤ l := Nat.le_add_left .. + have gate := hgate hu hm hw (acc (walk P T r)) le_rfl hl hh hq + have left : Circuit F A E Prod.fst ((A).width + 2 * E.width) := + Circuit.project Sum.inl (fun _ _ => rfl) + have right : Circuit F A D Prod.snd ((A).width + 2 * D.width) := + Circuit.project Sum.inr (fun _ _ => rfl) + have labels := (Computes.of_map (x := mid h s) (L := L) (Map.circuit hu left) (fun _ + => rfl)).comp gate + have read := Computes.of_map (x := mid h s) (L := L) (Map.circuit hu right) (fun _ => rfl) + simp only [one_mul] at labels + let mv (i : Path h s) := move h i.1 (s i.1) i.2 hd + have hw' := Trail.propagate hu S.d (acc (origin S T)) le_rfl + (fun i : Path h s => i.1.val.rows.1) (fun i : Path h s => i.1.val.trail) + mv (T.parent a) (fun i => i.1.val.encodes.reciprocal) (fun _ => rfl) labels read + refine hw'.mono ?_ + unfold secondCost issueCost + apply Nat.add_le_add_right + apply Nat.add_le_add_right + have he : (A).width = E.width + D.width := Format.width_pair .. + unfold l + omega + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- +# Summing the selector tape in one batch subround + +Selectors have a unique representation and an invalid selector has +zero weight. The resulting next state includes the transported +exterior names. The final scalar withdrawal restores neutrality. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {P : Gadget F} + {S : Setup F x y} {T : Template F} {z Δ : ℕ} {R : Budget} {w r d K : ℕ} {σ : ℝ} + (h : Phase.Input S T R w r P.b (P.b * z) z d K σ) + +local notation "a" => (T.scheme.h - r) +local notation "B₁" => Phase.after S T r R K P.ratio 1 σ +local notation "Y" => next P S T z h.vpos Δ R a +local notation "X" => frame S T (P.b * z) Δ R +local notation "Z" => T.Candidate a (b P) + +open scoped Classical in +/-- The indexed operation `Snapshot.restrict (fun e : Snapshot.Data S (next P S T z h.vpos Δ R +(T.scheme.h - r)) z => Ready (Δ ^ degreePower) B₁ e.sweep)`. -/ +def interim (Δ : ℕ) := Snapshot.restrict (fun e : Snapshot.Data S + (next P S T z h.vpos Δ R (T.scheme.h - r)) z => Ready (Δ ^ degreePower) B₁ e.sweep) + +variable (hd : 3 ≤ Δ) (hr : (Δ + 1) * 2 ≤ K) (hg : gain Δ ≤ K) + (ht : added P S T z h.vpos Δ R (T.scheme.h - r) ≤ (Phase.rate S T r R) ^ K) + +open scoped Classical in +private def assign (s : ∀ q : (X).state, Poll h q) : Selected X (interim h Δ) Z where + choice q := (s q).choices + index q := (s q).selector (choices P) + next q i := ⟨result h q (s q) i (by omega) hr, preserved h q (s q) i (by omega) hr hd hg ht⟩ + scalar _ _ := 1 + expands q x y := by + simp only [one_mul] + exact (expands h q (s q) (by omega) hr x y).symm + +open scoped Classical in +private theorem start_at (s : ∀ q : (X).state, Poll h q) (i : Path h s) : + start (P := P) (r := r) i.1 (((s i.1).selector (choices P)).write i.2) = mid h s i := + Prod.ext ((ticket h i.1 (s i.1) i.2).headed_eq (choices P)) rfl + +include hd hr hg ht in +open scoped Classical in +theorem controller (hk : 2 ^ (k Δ) ≤ K) (hq : d + 1 ≤ K) : + ∃ gate : Table F, Processor.arity gate = issueWidth P S T z h.vpos Δ R r ∧ + Transforms F (scale h Δ) (allowed h Δ gate) X (frame S (Y).sweep z (Δ ^ degreePower) B₁) + (totalCost P S T z h.vpos Δ R r) := by + have pos : 0 < Δ := by omega + let s (q : (X).state) := Classical.choice (elect h q pos hk) + obtain ⟨gate, hw, hnet⟩ := second h s pos hr + refine ⟨gate, hw, ?_⟩ + let L := allowed h Δ gate + have fit := fits (Δ := Δ) h + unfold arity at fit + have h₁ := first h gate hk hq s + have h₂ := hnet (L := L) (three h) (Or.inr (Finset.mem_insert_self ..)) (by omega) + (fun v => (access h gate hk hq v).1) + have eqn : mid h s = fun i : Path h s => + start (P := P) (r := r) i.1 (((s i.1).selector (choices P)).write i.2) := + funext fun i => (start_at h s i).symm + rw [eqn] at h₂ + let Q := assign h hd hr hg ht s + have run := Transforms.checked (three h) Q (fun i c _ _ => start (P := P) (r := r) i c) + (h₁.restrict Prod.fst) (h₂.restrict Prod.fst) + have hs : Snapshot.sweepTable Y ∈ L := Or.inr (Finset.mem_insert_of_mem (Finset.mem_insert_self + ..)) + refine run.comp (Snapshot.sweep (fun _ h => h) (three h) ?_ hs) + exact (Nat.le_add_left ..).trans fit + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end + +/- # Uniformizing the estimates for a wire-saving phase -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +open Packing Assembly Coloring Phase + +variable {F : Type} [Field F] {x y : Wire} {P : Gadget F} + {S : Setup F x y} {T : Template F} {z Δ : ℕ} {R : Budget} {w r d K : ℕ} {σ : ℝ} + (h : Phase.Input S T R w r P.b (P.b * z) z d K σ) (gate : Table F) + +local notation "a" => (T.scheme.h - r) +local notation "Y" => next P S T z h.vpos Δ R a + +open scoped Classical in +theorem few : (tables h Δ gate).card ≤ 8 := by + unfold tables + iterate 3 + apply (Finset.card_insert_le _ _).trans + apply Nat.add_le_add_right + exact T.card_keys .. + +open scoped Classical in +theorem narrow (hg : Processor.arity gate = issueWidth P S T z h.vpos Δ R r) + (t : Table F) (ht : t ∈ tables h Δ gate) : Processor.arity t ≤ arity P S T z h.vpos Δ R r := by + simp only [tables, Finset.mem_insert] at ht + unfold arity + rcases ht with rfl | rfl | rfl | ht + · rw [hg]; omega + · simp only [Snapshot.sweepTable, Processor.arity, weightTable, Assembly.lookup, wd_word, + Format.width_addr] + omega + · simp only [Template.markTable, Processor.arity, weightTable, Assembly.lookup, wd_word, + markWidth] + omega + · have := T.keys_width _ _ _ _ _ _ _ ht + omega + +variable (P Δ d) + +open scoped Classical in +private theorem raise {n k K : ℕ} (hn : 2 ≤ n) (hk : k ≤ K) : n ^ k ≤ n ^ K := + Nat.pow_le_pow_right (by omega) hk + +open scoped Classical in +theorem rule_of_bounds (hΔ : 3 ≤ Δ) + (hwidth : Case.Short (fun i : Case F P.b d => arity P i.S i.T i.v i.h.vpos Δ i.R i.r)) + (hsize : Case.Cost (fun i : Case F P.b d => totalCost P i.S i.T i.v i.h.vpos Δ i.R i.r)) : + ∃ d' K, 0 < K ∧ Phase F Δ (Δ ^ degreePower) d d' P.b K P.ratio 1 := by + obtain ⟨j₁, h₁⟩ := (added_bound P Δ d).bound + obtain ⟨j₂, h₂⟩ := (spans_bound P Δ d).bound + obtain ⟨j₃, h₃⟩ := (meter_bound P Δ d).bound + obtain ⟨j₄, h₄⟩ := bits_bound P Δ d + obtain ⟨j₅, h₅⟩ := hwidth.bound + obtain ⟨j₆, h₆⟩ := hsize + let K := 8 + (Δ + 1) * 2 + gain Δ + 2 ^ (k Δ) + (d + 1) + j₁ + j₂ + j₃ + j₄ + j₅ + j₆ + have hk : 0 < 2 ^ (k Δ) := by positivity + have hk₈ : 8 ≤ K := by unfold K; omega + refine ⟨maxDegree Δ d, K, by omega, ?_⟩ + intro x y S T R w r u z σ h + have eq := h.units + subst u + let i : Case F P.b d := ⟨x, y, S, T, R, w, r, P.b * z, z, K, σ, h⟩ + have raised {n l : ℕ} (hn : 2 ≤ n) (hl : l ≤ K) : n ^ l ≤ n ^ K := raise hn hl + have ht := (h₁ i).trans (raised i.rate_two (by unfold K; omega)) + obtain ⟨gate, hw, he⟩ := controller h hΔ (by unfold K; omega) (by unfold K; omega) ht + (by unfold K; omega) (by unfold K; omega) + let U := next P S T z h.vpos Δ R (T.scheme.h - r) + refine ⟨⟨U.sweep, Nat.sub_add_cancel h.group, Nat.le_add_right .., ?_, child_degree P Δ d i, + h.core, rfl, ?_, ?_, ?_, tables h Δ gate, ?_, ?_, scale h Δ, totalCost P S T z h.vpos Δ R r, + ?_, he⟩⟩ + · change T.scheme.m + (T.scheme.h - (T.scheme.h - r) + 1) ≤ _ + rw [Nat.sub_sub_self h.group] + omega + · exact (h₂ i).trans (raised i.base_two (by unfold K; omega)) + · exact (h₃ i).trans (raised i.base_two (by unfold K; omega)) + · exact (h₄ i).trans (Nat.mul_le_mul_left _ (raised i.rate_two (by unfold K; omega))) + · exact (few h gate).trans (hk₈.trans (Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left + i.short_two K))) + · intro g hg + exact (narrow h gate hw g hg).trans ((h₅ i).trans (raised i.short_two (by unfold K; omega))) + · exact (h₆ i).trans (Nat.add_le_add + (Nat.mul_le_mul_left _ (raised i.long_two (by unfold K; omega))) + (Nat.mul_le_mul_left _ (raised i.short_two (by unfold K; omega)))) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Beat +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Beat/TemplateCost.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Beat/TemplateCost.lean new file mode 100644 index 0000000000..b9413d66d2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Beat/TemplateCost.lean @@ -0,0 +1,188 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Issue +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact + +/-! # Polynomial bounds for the common template charges -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open BatchDescent.Phase Packing Coloring + +variable {I : Type*} {F : I → Type} {T : (i : I) → Template (F i)} + {a b delta C : I → ℕ} {large small height hosts : I → ℕ} + (largeTwo : ∀ i, 2 ≤ large i) (smallTwo : ∀ i, 2 ≤ small i) + (smallLeLarge : ∀ i, small i ≤ large i) + +local notation "Cost" => MixedCost large small height hosts + +/-- Bound the polynomial in the size and degree in the navigation overhead. -/ +theorem navComputation {size degree : I → ℕ} (hs : Poly large size) (hd : Poly large degree) : + Poly large (fun i => (100 + (size i + degree i)) ^ 201) := + ((Poly.const hs.two 100).add (hs.add hd)).pow 201 + +/-- Bound the polynomial in the size and both degrees in the header overhead. -/ +theorem headerComputation {size full core : I → ℕ} (hs : Poly large size) + (hf : Poly large full) (hc : Poly large core) : + Poly large (fun i => (100 + (size i + full i + core i)) ^ 16) := + ((Poly.const hs.two 100).add ((hs.add hf).add hc)).pow 16 + +/-- Bound the election computation from the count, width, and group size. -/ +theorem electionComputation {count width groups : I → ℕ} (hn : Poly large count) + (hw : Poly large width) (hg : Poly large groups) : + Poly large (fun i => (100 + (count i + (width i + groups i))) ^ 42) := + ((Poly.const hn.two 100).add (hn.add (hw.add hg))).pow 42 + +include largeTwo smallTwo smallLeLarge in +/-- Charge group preparation and election at the two fixed rates. -/ +theorem groupCost_mixed {dimension query width labels : I → ℕ} + (prepare : Cost (fun i => 2 ^ dimension i * (1 + Group.arity (query i) (width i) (labels i)))) + (elect : Cost (fun i => Group.electionCost (dimension i) (width i))) : + Cost (fun i => Group.cost (dimension i) (query i) (width i) (labels i)) := + (prepare.scale 100 smallTwo smallLeLarge).add + (elect.scale 4 smallTwo smallLeLarge) largeTwo smallTwo + +include largeTwo smallTwo smallLeLarge in +/-- Apply the two fixed rates to the input widths and add the navigation computation. -/ +theorem navCost_mixed {degree : I → ℕ} + (format : Cost (fun i => (T i).format.width)) + (groups : Cost (fun i => ((T i).groupInput (a i)).width)) + (child : Cost (fun i => (Child.Input (T i).scheme.m (T i).scheme.d).width)) + (compute : Cost (fun i => 2 ^ (T i).size (a i) * + (100 + ((T i).size (a i) + 2 ^ degree i)) ^ 201)) : + Cost (fun i => (T i).navCost (a i) (degree i)) := by + have h := format.add (groups.scale 3 smallTwo smallLeLarge) largeTwo smallTwo + have h := h.add (child.scale 68 smallTwo smallLeLarge) largeTwo smallTwo + exact h.add compute largeTwo smallTwo + +include largeTwo smallTwo smallLeLarge in +/-- Charge the status circuit from the format and status widths. -/ +theorem statusCost_mixed (format : Cost (fun i => (T i).format.width)) + (status : Cost (fun i => ((T i).Status (a i)).width)) : + Cost (fun i => (T i).statusCost (a i)) := + format.add (status.scale 34 smallTwo smallLeLarge) largeTwo smallTwo + +include largeTwo smallTwo smallLeLarge in +/-- Charge four runs of the child construction at the full template degree. -/ +theorem childCost_mixed (format : Cost (fun i => (T i).format.width)) + (status : Cost (fun i => ((T i).Status (a i)).width)) + (navigate : Cost (fun i => (T i).navCost (a i) ((T i).degree (a i) (delta i) (C i)))) : + Cost (fun i => (T i).childCost (a i) (delta i) (C i)) := by + have status := statusCost_mixed largeTwo smallTwo smallLeLarge format status + have h := (format.scale 5 smallTwo smallLeLarge).add status largeTwo smallTwo + exact (h.add navigate largeTwo smallTwo).scale 4 smallTwo smallLeLarge + +include largeTwo smallTwo smallLeLarge in +/-- Combine the full and core navigation, both status records, and the output header. -/ +theorem headerCost_mixed (format : Cost (fun i => (T i).format.width)) + (status : Cost (fun i => ((T i).Status (a i)).width)) + (navigate : Cost (fun i => (T i).navCost (a i) ((T i).degree (a i) (delta i) (C i)))) + (navigateCore : Cost (fun i => (T i).navCost (a i) + (Child.nextWidth ((T i).scheme.h - a i) (delta i) (T i).scheme.d))) + (compute : Cost (fun i => 2 ^ (T i).size (a i) * (100 + ((T i).size (a i) + + 2 ^ (T i).degree (a i) (delta i) (C i) + + 2 ^ Child.nextWidth ((T i).scheme.h - a i) (delta i) (T i).scheme.d)) ^ 16)) + (flags : Cost (fun i => + (Format.vec ((T i).size (a i)) (.vec ((T i).degree (a i) (delta i) (C i)) .bit)).width)) + (header : Cost (fun i => ((T i).ChildHeader (a i) (delta i) (C i)).width)) : + Cost (fun i => (T i).headerCost (a i) (delta i) (C i)) := by + have formatFive := format.scale 5 smallTwo smallLeLarge + have frozen := format.add (status.scale 2 smallTwo smallLeLarge) largeTwo smallTwo + have statusCharge := statusCost_mixed largeTwo smallTwo smallLeLarge format status + have preparation := ((formatFive.add statusCharge largeTwo smallTwo).add frozen largeTwo smallTwo) + have navigation := (formatFive.add navigate largeTwo smallTwo).add navigateCore largeTwo smallTwo + have navigation := navigation.add compute largeTwo smallTwo + have lists : Cost (fun i => ((T i).Lists (a i) (delta i) (C i)).width) := by + refine ((status.add status largeTwo smallTwo).add flags largeTwo smallTwo).mono fun i => ?_ + simp only [Lists, Format.width_pair, le_refl] + have finish := lists.add (header.scale 34 smallTwo smallLeLarge) largeTwo smallTwo + exact ((formatFive.add preparation largeTwo smallTwo).add navigation largeTwo smallTwo) + |>.add finish largeTwo smallTwo + +include largeTwo smallTwo smallLeLarge in +/-- Combine the input sampling, group lookups, and projection of the marked entries. -/ +theorem markCost_mixed (poll : Cost (fun i => ((T i).Poll (a i) (b i)).width)) + (polls : Cost (fun i => ((T i).Polls (a i) (b i)).width)) + (groups : Cost (fun i => ((T i).Groups (a i) (b i)).width)) + (entries : Cost (fun i => ((T i).Entries (a i) (b i)).width)) + (lookups : Cost (fun i => 2 ^ ((T i).scheme.m + a i) * + (1 + ((T i).PollRow (a i) (b i)).width + + (Side.Input ((T i).scheme.h - a i + (T i).scheme.e) (b i)).width))) : + Cost (fun i => (T i).markCost (a i) (b i)) := by + have sampling := (poll.add (polls.scale 2 smallTwo smallLeLarge) largeTwo smallTwo) + |>.scale 4 smallTwo smallLeLarge + have project := (groups.add (entries.scale 2 smallTwo smallLeLarge) largeTwo smallTwo) + |>.scale 4 smallTwo smallLeLarge + exact (sampling.add lookups largeTwo smallTwo).add project largeTwo smallTwo + +include largeTwo smallTwo smallLeLarge in +/-- Use the seat count to bound the layout input and the profile computation. -/ +theorem layoutCost_mixed {bits profile : ℕ} (mark : Cost (fun i => (T i).markCost (a i) bits)) + (seats : Cost (fun i => Fintype.card ((T i).Slots (a i)))) + (entries : Cost (fun i => ((T i).Entries (a i) bits).width)) : + Cost (fun i => (T i).layoutCost (a i) bits profile) := by + let width (i : I) := (T i).scheme.m + a i + ((T i).scheme.h - a i + (T i).scheme.e) + have slots : Cost (fun i => 2 ^ width i) := by + refine seats.mono fun i => ?_ + rw [Fintype.card_congr ((T i).seatIndex (a i)).symm, Fintype.card_fin] + have input : Cost (fun i => (Side.Input (width i) bits).width) := + (slots.scale (Side.Entry bits).width smallTwo smallLeLarge).mono fun i => by + rw [Side.Input, Format.width_vec, mul_comm] + have mark := mark.add (seats.scale (Branches.charge bits) smallTwo smallLeLarge |>.mono + (fun i => le_of_eq (mul_comm _ _))) largeTwo smallTwo + have input := ((entries.add (input.scale 2 smallTwo smallLeLarge) largeTwo smallTwo).scale 4 + smallTwo smallLeLarge) + have compute := slots.mul (Poly.const smallTwo ((100 + profile) ^ 8)) smallLeLarge + exact (mark.add input largeTwo smallTwo).add (compute.scale 4 smallTwo smallLeLarge) + largeTwo smallTwo + +include largeTwo smallTwo in +private theorem pair_mixed {A B : I → Format} + (hA : Cost (fun i => (A i).width)) (hB : Cost (fun i => (B i).width)) : + Cost (fun i => ((A i).pair (B i)).width) := + (hA.add hB largeTwo smallTwo).mono fun _ => (Format.width_pair ..).le + +include largeTwo smallTwo smallLeLarge in +/-- Assemble the raw fields and account for the copies, child, layout, and final projection. -/ +theorem rawCost_mixed {profile : ℕ} (format : Cost (fun i => (T i).format.width)) + (poll : Cost (fun i => ((T i).Poll (a i) (b i)).width)) + (counted : Cost (fun i => ((T i).Counted (a i) (b i)).width)) + (status : Cost (fun i => ((T i).Status (a i)).width)) + (graph : Cost (fun i => ((T i).Graph (a i) (delta i) (C i)).width)) + (bit : Cost (fun _ => Format.bit.width)) + (child : Cost (fun i => (T i).childCost (a i) (delta i) (C i))) + (layout : Cost (fun i => (T i).layoutCost (a i) (b i) profile)) + (raw : Cost (fun i => ((T i).Raw (a i) (b i) (delta i) (C i)).width)) : + Cost (fun i => (T i).rawCost (a i) (b i) (delta i) (C i) profile) := by + have copies := pair_mixed largeTwo smallTwo format (pair_mixed largeTwo smallTwo poll poll) + have fields := pair_mixed largeTwo smallTwo (pair_mixed largeTwo smallTwo status graph) + (pair_mixed largeTwo smallTwo bit counted) + have x := (poll.add (copies.scale 2 smallTwo smallLeLarge) largeTwo smallTwo) + |>.scale 4 smallTwo smallLeLarge + have count := (poll.add (counted.scale 2 smallTwo smallLeLarge) largeTwo smallTwo) + |>.scale 4 smallTwo smallLeLarge + have y := child.add (layout.add count largeTwo smallTwo) largeTwo smallTwo + have z := (fields.add (raw.scale 2 smallTwo smallLeLarge) largeTwo smallTwo) + |>.scale 4 smallTwo smallLeLarge + exact (x.add y largeTwo smallTwo).add z largeTwo smallTwo + +include largeTwo smallTwo smallLeLarge in +/-- Charge the poll copy and attach the completed header to the raw record. -/ +theorem headedCost_mixed {profile : ℕ} (format : Cost (fun i => (T i).format.width)) + (poll : Cost (fun i => ((T i).Poll (a i) (b i)).width)) + (raw : Cost (fun i => (T i).rawCost (a i) (b i) (delta i) (C i) profile)) + (header : Cost (fun i => (T i).headerCost (a i) (delta i) (C i))) : + Cost (fun i => (T i).headedCost (a i) (b i) (delta i) (C i) profile) := by + have copies := (pair_mixed largeTwo smallTwo poll format).scale 2 smallTwo smallLeLarge + have prepare := (poll.add copies largeTwo smallTwo).scale 4 smallTwo smallLeLarge + exact prepare.add (raw.add (header.scale 4 smallTwo smallLeLarge) largeTwo smallTwo) + largeTwo smallTwo + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Compilation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Compilation.lean new file mode 100644 index 0000000000..a476877045 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Compilation.lean @@ -0,0 +1,909 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Transform +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Encoded +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Exterior.Strips +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Exterior.Fields +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Encoding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Elect +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Rule + +/-! +# Batching all small labels in a network + +Read the exceptional tables from one dictionary on the diagram tape. +All other stations keep their original labels. This works for loops, +repeated wires and zero-valued tables in arbitrary characteristic. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Finset Transcript Install Processor Label + +variable {F V : Type} [Field F] [Fintype V] {a b c : Wire} {w u s : ℕ} + +open Classical in +/-- On a fixed transcript, replace the exceptional factors by a single +factor that reads the whole tape. -/ +private theorem batch_tape (hw : 64 ≤ w) (L : Finset (Table F)) + (hL : L.card ≤ 2 ^ (w / 4)) (ht : ∀ T ∈ L, arity T ≤ w / 4) + (T : V → Table F) (hs : ∑ v, (1 + arity (T v)) ≤ s) (hs' : s ≤ 2 ^ (2 * w - 1)) + (hu : 3 ≤ u) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ u) + (hvalid : ∀ v, T v ∉ L → arity (T v) ≤ u ∧ (arity (T v) ≤ 3 ∨ T v ∈ Allowed F w)) + (r : ∀ v, slots (args (T v)) → slots (.pair (.pair a b) c)) + (htape : wd a + wd b + wd c ≤ s) : + ∃ n, Wide F u (Allowed F w) a b + (value (fun v => args (T v)) (fun v => applyTable (T v)) r) n ∧ n ≤ 10 ^ 8 * (s + w * 2 ^ w) + := by + let d := Wire.pair (.pair a b) c + let J := Option {v // T v ∉ L} + let A : J → Wire := fun i => i.elim d fun v => args (T v) + let f (x : Val d) (v : V) := applyTable (T v) (project (r v) x) + let k : (i : J) → Val (A i) → F + | none, x => ∏ v : {v // T v ∈ L}, f x v + | some v, x => applyTable (T v) x + let read : (i : J) → slots (A i) → slots d + | none => id + | some v => r v + let N := 4 * s + 440000 * (s + w * 2 ^ w) + let cost : J → ℕ := fun i => i.elim N fun v => 9 * (1 + arity (T v)) + have ready (i : J) : ∃ t ≤ cost i, Wide F u (Allowed F w) (A i) .unit (fun x _ => k i x) t := by + cases i with + | some v => exact bend hu _ (hvalid v v.property).1 (hvalid v v.property).2 + | none => + obtain ⟨n, hn, hk⟩ := tape T L hw hu ha hL ht hs hs' r d (Equiv.refl _) + rw [card_slots] at hn + exact ⟨n, hn.trans (Nat.add_le_add_right (Nat.mul_le_mul_left 4 htape) _), + hk.mono le_rfl sort_allowed⟩ + obtain ⟨n, hn, h⟩ := wide A k cost read hu ready + refine ⟨n, ?_, ?_⟩ + · convert h using 1 + funext x y + apply sum_congr rfl + intro z _ + rw [Fintype.prod_option] + have hp : project (a := d) id ((x, y), z) = ((x, y), z) := (bits d).symm_apply_apply _ + change (∏ v, f ((x, y), z) v) = + (∏ v : {v // T v ∈ L}, f (project id ((x, y), z)) v) * ∏ v : {v // T v ∉ L}, f ((x, y), z) v + rw [hp] + exact (Fintype.prod_subtype_mul_prod_subtype (fun v => T v ∈ L) _).symm + · have hc := Fintype.sum_subtype_add_sum_subtype (fun v => T v ∈ L) (fun v => 1 + arity (T v)) + have hc' : (∑ v : {v // T v ∉ L}, (1 + arity (T v))) ≤ s + := (Nat.le_add_left _ _).trans (hc.le.trans hs) + rw [Fintype.sum_option] at hn + change n ≤ 8 * (wd a + wd b + wd c) + 9 * (N + ∑ v : {v // T v ∉ L}, 9 * (1 + + arity (T v))) at hn + rw [← mul_sum] at hn + unfold N at hn + omega + +open Classical in +theorem batch_labels {k : Val a → Val b → F} + (hw : 64 ≤ w) (L : Finset (Table F)) (hL : L.card ≤ 2 ^ (w / 4)) (ht : ∀ T ∈ L, arity T ≤ w / 4) + (h : Wide F u (Allowed F w ∪ (L : Set (Table F))) a b k s) (hs : s ≤ 2 ^ (2 * w - 1)) : + ∃ v n, Wide F v (Allowed F w) a b k n ∧ n ≤ 10 ^ 8 * (s + w * 2 ^ w) := by + obtain ⟨G, rfl, hG, hcost⟩ := h.diagram + let v := max (max u 3) (2 * 2 ^ (2 * w) * (4 * w)) + let c := word (Fintype.card G.E) + let e : G.E ≃ slots (word (Fintype.card G.E)) := Fintype.equivOfCardEq (by simp) + let read (i : G.V) : slots (args (G.table i)) → slots (.pair (.pair a b) c) := Sum.elim + (fun j => Sum.elim (fun t => .inl (.inl t)) (fun t => .inr (e t)) (G.src ⟨i, j⟩)) + (fun j => Sum.elim (fun t => .inl (.inr t)) (fun t => .inr (e t)) (G.dst ⟨i, j⟩)) + have hvalid (i : G.V) (hi : G.table i ∉ L) : + arity (G.table i) ≤ v ∧ (arity (G.table i) ≤ 3 ∨ G.table i ∈ Allowed F w) := + ⟨(hG i).1.trans (by unfold v; omega), (hG i).2.imp_right (fun t => t.resolve_right hi)⟩ + have hsize : wd a + wd b + wd c ≤ s := by + rw [← hcost, Diagram.cost_eq, show wd c = Fintype.card G.E from wd_word _] + omega + obtain ⟨n, hn, hb⟩ := batch_tape (u := v) hw L hL ht G.table hcost.le hs (by unfold v; omega) + (le_max_right _ _) hvalid read hsize + refine ⟨v, n, ?_, hb⟩ + convert hn using 1 + funext x y + let f := (bits c).trans (e.symm.arrowCongr (Equiv.refl Bool)) + symm + unfold value Diagram.eval + refine @Fintype.sum_equiv (Val c) (G.E → Bool) F (valFintype c) _ _ f _ _ ?_ + intro z + apply prod_congr rfl + intro i _ + apply congrArg₂ (G.table i).2.2 + · apply congrArg (bits (G.table i).1).symm + funext j + change bits (.pair (.pair a b) c) ((x, y), z) (read i (.inl j)) = _ + unfold read + cases he : G.src ⟨i, j⟩ <;> simp only [Sum.elim_inl, he, Sum.elim_inr] <;> rfl + · apply congrArg (bits (G.table i).2.1).symm + funext j + change bits (.pair (.pair a b) c) ((x, y), z) (read i (.inr j)) = _ + unfold read + cases he : G.dst ⟨i, j⟩ <;> simp only [Sum.elim_inr, he, Sum.elim_inl] <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- +# Extra block reserve + +The upper bounds on the work per host may be polynomial in the +address width. Keep an extra quadratic number of block-index bits +throughout the beats, then move them to the host coordinate before +applying the terminal packing. This leaves the replication subpolynomial. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Recipe +open Filter + +variable {F : Type} [Field F] (P : Recipe F) + +theorem reserve_height (R J : ℕ) : P.blocks (R + J) J = P.blocks R J + J ^ 2 := by + unfold blocks + ring + +theorem reserve_width (R J : ℕ) : + P.blocks (R + J) J ≤ (R + 1 + P.n * (P.H + 5)) * J ^ 2 := by + unfold blocks group + have := Nat.mul_le_mul_left R (show J ≤ J ^ 2 by nlinarith) + nlinarith only [this] + +theorem reserve_parameters (R Q V B J : ℕ) (hB : 5 + Q + P.b + V ≤ B) + {κ : ℝ} (hk : 0 < κ) : + ∀ᶠ w : ℕ in atTop, ∃ j z : ℕ, J ≤ j ∧ 1 ≤ j ∧ 2 ^ (B * j) ≤ w ∧ w ≤ 2 ^ (2 * B * j) ∧ + 0 < z ∧ 2 ^ (V * j) ∣ z ∧ 16 * (2 ^ (Q * j) * P.b ^ j) * z ≤ w ∧ w + ≤ 32 * (2 ^ (Q * j) * P.b ^ j) * z ∧ + 0 < P.batch (R + j) j z ∧ (P.batch (R + j) j z : ℝ) ≤ ((2 : ℝ) ^ w : ℝ) ^ κ := by + obtain ⟨N, hN⟩ := eventually_atTop.mp (replication (half_pos hk) 1) + filter_upwards [P.parameters R Q V B (max J N) hB (half_pos hk)] with w hw + obtain ⟨j, z, hj, hj', hl, hu, hz, hv, hn, he, hs, hp⟩ := hw + have hh : 2 ^ j ≤ w := (Nat.pow_le_pow_right (by decide) + (Nat.le_mul_of_pos_left _ (by omega : 0 < B))).trans hl + have ht := hN j (by omega) w hh + have hsize : P.batch (R + j) j z = 2 ^ (j ^ 2) * P.batch R j z := by + unfold batch + rw [P.reserve_height, pow_add] + ring + refine ⟨j, z, by omega, hj', hl, hu, hz, hv, hn, he, ?_, ?_⟩ + · rw [hsize]; positivity + · rw [hsize, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat] + rw [one_mul] at ht + refine (mul_le_mul ht hp (by positivity) (by positivity)).trans_eq ?_ + rw [← Real.rpow_add (by positivity), add_halves] + +theorem reserve_limits (R Q B : ℕ) (hB : 6 + Q ≤ B) : + ∀ᶠ j : ℕ in atTop, ∀ z w : ℕ, 2 ^ (B * j) ≤ w → w ≤ 2 ^ (2 * B * j) → + 16 * (2 ^ (Q * j) * P.b ^ j) * z ≤ w → w ≤ 32 * (2 ^ (Q * j) * P.b ^ j) * z → + let h := P.blocks (R + j) j + let p := P.b ^ j * z + h + 4 ≤ p ∧ 2 * 2 ^ (h + 2) * (h + 1 + p + 2) ≤ min (2 ^ ((Nat.clog 2 w) ^ 3)) (2 ^ (w / 2)) + := by + filter_upwards [eventually_ge_atTop 1, Exterior.limits (R + 1 + P.n * (P.H + 5)) B] + with j hj ht z w hl hu hlo hup + apply ht _ _ w (P.reserve_width R j) _ _ hu + · have hd : 32 * 2 ^ (Q * j) * 2 ^ j ≤ 32 * 2 ^ (Q * j) * (P.b ^ j * z) := calc + _ = 2 ^ (5 + Q * j + j) := by simp [pow_add] + _ ≤ 2 ^ (B * j) := Nat.pow_le_pow_right (by decide) (by nlinarith) + _ ≤ w := hl + _ ≤ _ := by simpa [mul_assoc] using hup + exact Nat.le_of_mul_le_mul_left hd (by positivity) + · exact (Nat.le_mul_of_pos_left _ (by positivity : 0 < 16 * 2 ^ (Q * j))).trans + (by simpa [mul_assoc] using hlo) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Recipe +end + +/- +# Completing a controlled descent + +Each supported state uniquely determines its whole decision tape. +The same terminal tensor closes every such state, including different +states sharing the same code. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Coloring Assembly Transcript PackRows + +variable {F Z : Type} [Field F] [Fintype Z] {D : Dimensions} {S : Scheme F} + {x y : Wire} {w j cap u v : ℕ} {A : Format} + +omit [Field F] in +open Classical in +private theorem decisions_width (h : D.FitsControls S Z w j cap u v) : + Fintype.card (D.Decisions S) ≤ 10 * 2 ^ j * (1 + w) := by + have hb : Fintype.card (D.BinOutput S) ≤ 2 * w := by + have := h.short + have := h.upper + omega + have hc : D.a + 2 + D.e ≤ 8 * w := by have := h.head; have := h.names; omega + have hd : D.K * (2 * D.v) ≤ 2 ^ j := (Nat.le_add_left _ _).trans h.slots + have hK : D.K ≤ 2 ^ j := (Nat.le_mul_of_pos_right _ (by positivity)).trans hd + change Fintype.card ((Fin D.K × D.BinOutput S) ⊕ + (D.Addr × (slots (word (D.a + 2)) ⊕ Fin D.e))) ≤ _ + rw [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + show Fintype.card (D.Addr × (slots (word (D.a + 2)) ⊕ Fin D.e)) = + (D.K * (2 * D.v)) * (D.a + 2 + D.e) by simp; omega] + exact (Nat.add_le_add (Nat.mul_le_mul hK hb) (Nat.mul_le_mul hd hc)).trans (by ring_nf; omega) + +namespace View +variable (V : View D S x y A Z) + +open Classical in +private theorem controls (h : D.FitsControls S Z w j cap u v) : + ∃ f : ((form A D x y).pins ⊕ D.Decisions S → Bool) → F, + WideWeight F cap (Allowed F w) f + (10 ^ 16 * (Fintype.card ((form A D x y).pins ⊕ D.Decisions S) + 2 ^ j * (1 + w))) ∧ + ∀ (G : Diagram F x y) (t : Assignment D S G) (ht : t.Fits) (a : (form A D x y).obj), + V.Valid t ht a.1 → ∀ z, f (Sum.elim ((form A D x y).code a) z) = + if V.display t ht h.code a.1 = z then 1 else 0 := by + let lift : A.pins ⊕ Bool → ((form A D x y).pins ⊕ D.Decisions S) ⊕ Bool := + Sum.map (fun i => .inl (.inl i)) id + let dst : D.Decisions S → ((form A D x y).pins ⊕ D.Decisions S) ⊕ Bool := fun i => .inl (.inr i) + obtain ⟨f, hf, he⟩ := D.controls_net S h (lift ∘ V.rows) + (fun i j => lift ∘ V.long i j) (fun i => lift ∘ V.short i) dst V.code V.user + refine ⟨f, fun a i => ?_, fun G t ht a ha z => ?_⟩ + · obtain ⟨n, hn, hnet⟩ := hf a i + exact ⟨n, hn, hnet.mono le_rfl sort_allowed⟩ + · let x' := Sum.elim ((form A D x y).code a) z + have taps {Y : Type} (g : Y → A.pins ⊕ Bool) : + Sum.elim x' id ∘ lift ∘ g = Sum.elim (A.code a.1) id ∘ g := by + funext b + simp only [Function.comp_apply] + cases g b <;> rfl + have eq := he x' t.inventory ht.position ht.reserve (fun i => by + rw [taps]; exact V.lengths t ht ha i) + simp only [taps, ← ha.rows, Equiv.symm_apply_apply] at eq + refine eq.trans ?_ + congr 1 + exact propext eq_comm + +open Classical in +theorem evaluate (hc : D.FitsControls S Z w j cap u v) (hr : D.FitsScreen S x y w j cap) : + ∃ f : ((form A D x y).pins → Bool) → F, + WideWeight F cap (Allowed F w) f (10 ^ 20 * ((form A D x y).width + 2 ^ j * (1 + w))) ∧ + ∀ (G : Diagram F x y) (t : Assignment D S G) (ht : t.Fits) (a : (form A D x y).obj), + V.Valid t ht a.1 → f ((form A D x y).code a) = t.state.diagram.eval a.2.1 a.2.2 := by + obtain ⟨k, hk, ek⟩ := V.controls hc + obtain ⟨f, hf, ef⟩ := V.screen.run hr + obtain ⟨g, hg, eg⟩ := hide_unique hc.gates hk hf + refine ⟨g, fun a i => ?_, fun G t ht a ha => ?_⟩ + · obtain ⟨n, hn, hn'⟩ := hg a i + refine ⟨n, ?_, hn'⟩ + have ht := decisions_width hc + rw [mul_assoc] at ht + rw [show Fintype.card ((form A D x y).pins ⊕ D.Decisions S) = + Fintype.card (form A D x y).pins + Fintype.card (D.Decisions S) from Fintype.card_sum] at hn + unfold Format.width + omega + · rw [eg _ _ (ek G t ht a ha), ef _ _ _ _ (V.flags t ht hc.code a ha), V.supplied] + exact t.post.toPresentation.eval .. + +end View + +universe v + +open Classical in +theorem terminal (X : Snapshot.{v} F (copies x D.copies) (copies y D.copies)) (V : View D S x y + X.port Z) + (hc : D.FitsControls S Z w j cap u v) (hr : D.FitsScreen S x y w j cap) + (hs : ∀ i a b, ∃ (G : Diagram F x y) (t : Assignment D S G) (hw : t.Fits), + X.eval i a b = t.state.diagram.eval a b ∧ V.Valid t hw (X.encode i a b)) : + Finishes F cap (Allowed F w) X.public (10 ^ 20 * (X.public.port.width + 2 ^ j * (1 + w))) := by + obtain ⟨f, hf, he⟩ := V.evaluate hc hr + refine ⟨fun a => f (X.public.port.code a), ?_, fun i a b => ?_⟩ + · intro a b i j + obtain ⟨m, hm, H⟩ := hf a i + refine ⟨m, hm, ?_⟩ + have H' := H.post (rewire_reindex (a := b) (b := .unit) j) + simp only [view_apply, Equiv.apply_symm_apply] + exact H' + · obtain ⟨G, t, hw, hv, hk⟩ := hs i a b + exact (he G t hw (X.encode i a b, a, b) hk).trans hv.symm + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- +# Sizing the terminal checks + +Use 32 slices per half-bin row to carry long names. These slices +are independent of the whole apparent bit size of a local table. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +open Assembly Coloring PackRows + +variable {F Z : Type} [Fintype Z] (D : Dimensions) (S : Scheme F) + +/-- The short width of type `ℕ` for the given inputs. -/ +def shortWidth (c : ℕ) : ℕ := + D.v * (1 + c) + (4 * D.v * D.u) ^ 2 + + 2 * D.v * (2 ^ S.h * (1 + S.ℓ + 2 * D.u ^ 2) + 2 * D.v + (D.r + 2) + 1 + D.q * (1 + D.h)) + +theorem controls_card : Fintype.card (BinKey D.v Z) + Fintype.card (D.BinOutput S) = + D.shortWidth S (Fintype.card Z) := by + simp only [shortWidth, Fintype.card_prod, Fintype.card_sum, Fintype.card_option, Fintype.card_fin, + Fintype.card_unit, card_slots, wd_word] + ring + +theorem shortWidth_le {c t : ℕ} (hc : c ≤ t) (hb : 2 ^ S.h ≤ t) (he : S.ℓ ≤ t) + (hr : D.r ≤ t) (hh : D.h ≤ t) (hq : D.q ≤ t) (hu : D.u ≤ t) (hv : D.v ≤ t) : + 8 * D.shortWidth S c ≤ (100 + t) ^ 8 := by + unfold shortWidth + calc + _ ≤ 8 * (t * (1 + t) + (4 * t * t) ^ 2 + 2 * t * (t * (1 + t + 2 * t ^ 2) + 2 * t + (t + 2) + 1 + + t * (1 + t))) := by gcongr + _ ≤ _ := by ring_nf; omega + +private theorem short_bounds (c : ℕ) : + let k := D.shortWidth S c + c ≤ k ∧ D.r ≤ k ∧ 4 * D.v ≤ k ∧ (2 * D.v) ^ 2 ≤ k ∧ (4 * D.v * D.u) ^ 2 ≤ k ∧ + 2 ^ S.h * (1 + S.ℓ + 2 * D.u ^ 2) ≤ k := by + let a := 2 ^ S.h * (1 + S.ℓ + 2 * D.u ^ 2) + let b := a + 2 * D.v + (D.r + 2) + 1 + D.q * (1 + D.h) + have hv := Nat.two_pow_pos D.r + have h : b ≤ 2 * D.v * b := Nat.le_mul_of_pos_left _ (by positivity) + have he : c ≤ D.v * (1 + c) := (Nat.le_add_left ..).trans (Nat.le_mul_of_pos_left _ hv) + have hu := Nat.le_mul_of_pos_right (4 * D.v) D.upos + have hp : (2 * D.v) ^ 2 ≤ (4 * D.v * D.u) ^ 2 := Nat.pow_le_pow_left (by omega) _ + have hq : 4 * D.v ≤ (2 * D.v) ^ 2 := by nlinarith only [show 0 < D.v from hv] + change let k := D.v * (1 + c) + (4 * D.v * D.u) ^ 2 + 2 * D.v * b + c ≤ k ∧ D.r ≤ k ∧ 4 * D.v ≤ k ∧ (2 * D.v) ^ 2 ≤ k ∧ (4 * D.v * D.u) ^ 2 ≤ k ∧ a ≤ k + have : a ≤ b ∧ D.r ≤ b := by unfold b; omega + dsimp only + omega + +/-- The quantity computed by `2 ^ S.m * D.PortCount S + 32 * D.K * D.v + (wd x + wd y) * D.n`. -/ +def rows (x y : Wire) := 2 ^ S.m * D.PortCount S + 32 * D.K * D.v + (wd x + wd y) * D.n + +theorem room {x y : Wire} {w j cap : ℕ} (hw : 64 ≤ w) + (hj : w ≤ j) (hj' : 4 * j ≤ 5 * w) (hm : 4 * S.m ≤ 5 * w) + (he : D.e = 2 * w) (ha : D.a = 3 * w) + (hh : 8 * D.shortWidth S (Fintype.card Z) ≤ w) + (ht : 16 * (D.q * D.b) * D.z ≤ w) (hext : D.h + 4 ≤ D.b * D.z) + (hrows : D.rows S x y ≤ 2 ^ j) (hu : 2 * 2 ^ (2 * w) * (4 * w) ≤ cap) + (hsmall : 2 * 2 ^ (D.h + 2) * (D.h + 1 + D.b * D.z + 2) + ≤ min (2 ^ ((Nat.clog 2 w) ^ 3)) (2 ^ (w / 2))) : + FitsControls D S Z w j cap (32 * D.v) (w / (8 * D.v) + 1) ∧ FitsScreen D S x y w j cap := by + obtain ⟨hz, hr, hv, hv', hmove, htag⟩ := D.short_bounds S (Fintype.card Z) + have hcap : 2 ^ (w / 2) ≤ cap := + (Nat.pow_le_pow_right (by decide) (show w / 2 ≤ 2 * w by omega)).trans <| + ((Nat.le_mul_of_pos_left _ (by decide : 0 < 2)).trans + (Nat.le_mul_of_pos_right _ (by omega : 0 < 4 * w))).trans hu + have h3 : 3 ≤ cap := by + have := Nat.pow_le_pow_right (by decide : 0 < 2) (show 2 ≤ w / 2 by omega) + omega + have hu' : 16 * (2 * D.u * D.z) ≤ w := by rwa [← D.width, ← mul_assoc] + have hd : 8 * (D.q * D.recordWidth) ≤ w := by + calc + _ ≤ 8 * (D.q * (2 * (D.b * D.z))) := by gcongr; unfold recordWidth; omega + _ = 16 * (D.q * D.b) * D.z := by ring + _ ≤ _ := ht + have ht' : 2 ^ S.m * D.PortCount S + 32 * (D.K * D.v) + (wd x + wd y) * D.n ≤ 2 ^ j := by + simpa only [rows, mul_assoc] using hrows + have hr' : D.K * (2 * D.v) = 2 * (D.K * D.v) := by ring + have hh' := D.controls_card S (Z := Z) + let x' := w / (8 * D.v) + 1 + have hc : w < 8 * D.v * x' := Nat.lt_mul_div_succ _ (by positivity) + have hs : 8 * D.v * x' ≤ w + 8 * D.v := by + unfold x' + rw [mul_add, mul_one] + exact Nat.add_le_add_right (Nat.mul_div_le _ _) _ + have lift : 4 * w ≤ 32 * D.v * x' := by nlinarith only [hc] + have fits : (2 * D.v) ^ 2 + 2 * (2 * D.v * x') < j := by nlinarith only [hs, hv, hv', hh, hj, hw] + constructor + · exact ⟨hj, by omega, h3, hu, by omega, by omega, by omega, by omega, by omega, + by unfold CodeFits; omega, by omega, (by omega : 2 * S.m ≤ 4 * w).trans lift, + (by omega : D.e ≤ 4 * w).trans lift, fits, by rw [mul_left_comm]; omega⟩ + · refine ⟨⟨hj, by omega, h3, hu, by omega, ?_, ?_, ?_, ?_⟩, + by omega, by omega, by omega, by omega, + by omega, ?_⟩ + · change (4 * D.v * D.u) ^ 2 + 2 * (2 * D.u * D.z) < j + omega + · change 2 ^ S.h * (1 + S.ℓ + 2 * D.u ^ 2) + 2 * D.u * D.z < j + omega + · change w ≤ D.a + 2 * D.u * D.z + 2 + omega + · change D.a + 2 * D.u * D.z + 2 ≤ 4 * w + omega + · exact (Nat.mul_le_mul_left _ (show D.recordWidth + 1 ≤ D.h + 1 + D.b * D.z + 2 by + unfold recordWidth; omega)).trans (le_min ((hsmall.trans (min_le_right ..)).trans hcap) + hsmall) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +end + +section +/- +# Converting a bit budget into one array size + +Reserve sufficient rows before seeing the chosen summand. All the +sorting calls then use the same dyadic height. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +open Assembly PackRows + +variable {F : Type} (D : Dimensions) (S : Scheme F) (x y : Wire) (w T : ℕ) + +/-- The data for the budget construction, including `min`, `narrow`, `wide`, `bins`, `host`. -/ +structure Budget : Prop where + min : 64 ≤ w + narrow : 16 * (D.q * D.b) * D.z ≤ w + wide : w ≤ 32 * (D.q * D.b) * D.z + bins : D.K = 512 * T / (D.v * w) + 1 + host : 2 ^ S.m * (D.PortCount S + 2) * w ≤ T + exterior : (wd x + wd y) * D.copies ≤ T + slack : D.v * w ≤ T + base : 2 ^ w * w ≤ T + upper : 50000 * T ≤ 2 ^ (5 * w / 4) + +/-- The maximum of the quantities in `w (Nat.clog 2 (D.rows S x y))`. -/ +def height := max w (Nat.clog 2 (D.rows S x y)) + +namespace Budget +variable {D S x y w T} (B : D.Budget S x y w T) + +include B + +private theorem bin_budget : 512 * T ≤ D.K * (D.v * w) ∧ D.K * (D.v * w) ≤ 513 * T := by + rw [B.bins] + have hm := B.min + have hv : 0 < D.v * w := Nat.mul_pos (by positivity) (by omega) + refine ⟨?_, ?_⟩ + · exact (Nat.lt_mul_div_succ _ hv).le.trans_eq (mul_comm _ _) + · rw [add_mul, one_mul] + have := Nat.div_mul_le_self (512 * T) (D.v * w) + have := B.slack + omega + +theorem fits [Field F] {G : Diagram F x y} (t : Assignment D S G) + (hl : ∀ i j, t.state.load i j ≤ (D.u * D.z : ℕ)) (hc : t.state.X ≤ T) + (hr : D.PortCount S + 2 + 2 * 2 ^ S.h ≤ D.v) : t.Fits := by + apply t.fits hl hr + have hs : D.u * D.z ≤ w := by + have h := B.narrow + rw [D.width] at h + nlinarith only [h] + have he : w ≤ 64 * (D.u * D.z) := by + refine B.wide.trans_eq ?_ + rw [D.width]; ring + have hk : 8 * T ≤ D.K * D.v * D.u * D.z := by + have h := B.bin_budget.1.trans (Nat.mul_le_mul_left D.K (Nat.mul_le_mul_left D.v he)) + nlinarith only [h] + have hh := (Nat.mul_le_mul_left (2 ^ S.m * (D.PortCount S + 2)) hs).trans B.host + have hv := (Nat.mul_le_mul_left D.v hs).trans B.slack + exact le_trans (by nlinarith only [hc, hh, hv, B.exterior]) hk + +theorem row_count : D.rows S x y * w ≤ 16500 * T := by + have h₁ := B.host + have h₂ := B.bin_budget.2 + have h₃ : (wd x + wd y) * D.n * w ≤ 64 * T := by + calc + _ ≤ (wd x + wd y) * D.n * (32 * (D.q * D.b) * D.z) := Nat.mul_le_mul_left _ B.wide + _ = 32 * (wd x + wd y) * (D.n * D.q) * (D.b * D.z) := by ring + _ = 64 * ((wd x + wd y) * D.copies) := by rw [D.cover]; unfold copies; ring + _ ≤ _ := Nat.mul_le_mul_left _ B.exterior + unfold rows + ring_nf at h₁ h₂ h₃ ⊢ + omega + +private theorem height_bounds : + 4 * S.m ≤ 5 * w ∧ 4 * D.height S x y w ≤ 5 * w ∧ 2 ^ (D.height S x y w) * (1 + w) ≤ 100000 * T + := by + let u := D.rows S x y + have hm := B.min + have hu : 2 ^ S.m ≤ u := by + unfold u rows + have hd : 0 < D.PortCount S := by unfold PortCount; positivity + have := Nat.le_mul_of_pos_right (2 ^ S.m) hd + omega + have hu' : 0 < u := lt_of_lt_of_le (by positivity) hu + have ht : u ≤ 2 ^ (5 * w / 4) := + (Nat.le_mul_of_pos_right _ (by omega : 0 < w)).trans + (B.row_count.trans ((by omega : 16500 * T ≤ 50000 * T).trans B.upper)) + have hH := (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp (hu.trans ht) + have hJ := Nat.clog_le_of_le_pow ht + change 4 * S.m ≤ 5 * w ∧ 4 * max w (Nat.clog 2 u) ≤ 5 * w ∧ _ + refine ⟨by omega, by omega, ?_⟩ + have he : 2 ^ (Nat.clog 2 u) ≤ 2 * u := by + cases eq : Nat.clog 2 u with + | zero => simp; omega + | succ k => + have h : 2 ^ k < u := Nat.pow_lt_of_lt_clog (by omega) + rw [pow_succ']; omega + have hk : 2 ^ (D.height S x y w) ≤ 2 * u + 2 ^ w := by + change 2 ^ (max w (Nat.clog 2 u)) ≤ _ + rcases le_total w (Nat.clog 2 u) with ht | ht + · rw [max_eq_right ht]; exact he.trans (Nat.le_add_right ..) + · rw [max_eq_left ht]; exact Nat.le_add_left .. + refine (Nat.mul_le_mul hk (show 1 + w ≤ 2 * w by omega)).trans ?_ + have hr : u * w ≤ 16500 * T := B.row_count + nlinarith only [hr, B.base] + +theorem charge : 2 ^ (D.height S x y w) * (1 + w) ≤ 100000 * T := B.height_bounds.2.2 + +theorem room {Z : Type} [Fintype Z] {cap : ℕ} (he : D.e = 2 * w) (ha : D.a = 3 * w) + (hh : 8 * D.shortWidth S (Fintype.card Z) ≤ w) (hext : D.h + 4 ≤ D.b * D.z) + (hu : 2 * 2 ^ (2 * w) * (4 * w) ≤ cap) + (hsmall : 2 * 2 ^ (D.h + 2) * (D.h + 1 + D.b * D.z + 2) + ≤ Min.min (2 ^ ((Nat.clog 2 w) ^ 3)) (2 ^ (w / 2))) : + let j := D.height S x y w + FitsControls D S Z w j cap (32 * D.v) (w / (8 * D.v) + 1) ∧ FitsScreen D S x y w j cap := + D.room S B.min (le_max_left ..) B.height_bounds.2.1 B.height_bounds.1 he ha hh B.narrow hext + ((Nat.le_pow_clog (by decide) _).trans (Nat.pow_le_pow_right (by decide) (le_max_right ..))) hu + hsmall + +end Budget +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +end + +section +/- +# Paying for the transfer and the terminal host + +Long names are charged once per potential contact. The surviving +blocks absorb this cost, while the stack width pays for the short +controls at individual occurrences. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +variable {F : Type} [Field F] {x y : Wire} {G : Diagram F x y} {D : Dimensions} + {M C c e R J w : ℕ} + +theorem Transfer.funded (b : Transfer G D M C c e R J w) (Q V B : ℕ) + (hj : 1 ≤ J) (hr : Q + 2 * c + 10 ≤ R) (hv : R + c + 5 ≤ V) + (hb : 100 * (1 + V + e) ≤ B) (hrsv : R * J ≤ D.h) (hsize : 2 ^ w ≤ M) + (hwidth : 2 ^ (B * J) ≤ w) (hn : 16 * (D.q * D.b) * D.z ≤ w) (hu : w ≤ 32 * (D.q * D.b) * D.z) + (fq : D.q = 2 ^ (Q * J)) (fv : 2 * D.v = 2 ^ (V * J)) (fd : D.d ≤ 2 ^ (c * J)) + (T : ℕ) (hT : T = allowance C D.h J (D.b * D.z) M (wd x + wd y)) + (fk : D.K = 512 * T / (D.v * w) + 1) (ht : 10 ^ 38 * T ≤ 2 ^ (5 * w / 4)) : + D.Budget b.scheme x y w T ∧ D.shortBudget M e J ≤ T ∧ D.longBudget M c R J w ≤ T ∧ + D.PortCount b.scheme + 2 + 2 * 2 ^ b.scheme.h ≤ D.v := by + let p (a : ℕ) := 2 ^ (a * J) + have add (a d : ℕ) : p (a + d) = p a * p d := by simp [p, add_mul, pow_add] + have pos (a : ℕ) : 0 < p a := Nat.two_pow_pos _ + have le (a : ℕ) : 2 ^ a ≤ p a := + Nat.pow_le_pow_right (by decide) (Nat.le_mul_of_pos_right _ hj) + have mono : Monotone p := fun _ _ h => Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ h) + let N := 2 ^ (D.h - R * J) + let L := 2 ^ (D.h - J) + let k := D.b * D.z + have hJ : J ≤ D.h := (Nat.le_mul_of_pos_left _ (by omega : 0 < R)).trans hrsv + have sumR : N * p R = 2 ^ D.h := by unfold N p; rw [← pow_add, Nat.sub_add_cancel hrsv] + have sumJ : L * p 1 = 2 ^ D.h := by unfold L p; rw [one_mul, ← pow_add, Nat.sub_add_cancel hJ] + have core : L * k * M ≤ T := by + rw [hT, allowance] + exact (Nat.le_add_right _ _).trans (Nat.le_mul_of_pos_left _ (by omega)) + have outer : (wd x + wd y) * D.copies ≤ T := by + rw [hT, allowance, Dimensions.copies, mul_comm (wd x + wd y)] + exact (Nat.le_add_left _ _).trans (Nat.le_mul_of_pos_left _ (by omega)) + have upper : w ≤ p (5 + Q) * k := calc + _ ≤ 32 * (D.q * D.b) * D.z := hu + _ = (2 ^ 5 * p Q) * k := by rw [fq]; unfold k p; ring + _ ≤ _ := by rw [add]; exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (le 5)) + have stack : p (1 + e) ≤ k := by + apply Nat.le_of_mul_le_mul_left _ (pos (5 + Q)) + rw [← add] + exact (mono (by omega : 5 + Q + (1 + e) ≤ B)).trans (hwidth.trans upper) + have short : D.shortBudget M e J ≤ T := calc + _ = L * p (1 + e) * M := by + change M * 2 ^ D.h * p e = _ + rw [add, ← sumJ]; ring + _ ≤ L * k * M := Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ stack) + _ ≤ _ := core + have ports : D.PortCount b.scheme + 2 ≤ 5 * p c := by + have h := Nat.pow_le_pow_right (by decide : 0 < 2) b.lanes + have := pos c + unfold Dimensions.PortCount p at * + omega + have port_exp : D.PortCount b.scheme + 2 ≤ p (3 + c) := by + rw [add] + exact ports.trans (Nat.mul_le_mul_right _ ((by decide : 5 ≤ 2 ^ 3).trans (le 3))) + have hosts : 2 ^ b.scheme.m ≤ M * N * p c := by + apply Nat.le_of_mul_le_mul_right _ (pos R) + refine b.hosts.trans_eq ?_ + change M * 2 ^ D.h * p c = _ + rw [← sumR]; ring + have allocation : N * p c * p (3 + c) * p (5 + Q) ≤ L := by + apply Nat.le_of_mul_le_mul_right _ (pos 1) + rw [sumJ, ← sumR] + simp only [mul_assoc, ← add] + exact Nat.mul_le_mul_left _ (mono (by omega)) + have paid : (M * N * p c) * p (3 + c) * w ≤ T := calc + _ ≤ (M * N * p c) * p (3 + c) * (p (5 + Q) * k) := Nat.mul_le_mul_left _ upper + _ = (N * p c * p (3 + c) * p (5 + Q)) * k * M := by ring + _ ≤ L * k * M := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ allocation) + _ ≤ _ := core + have long : D.longBudget M c R J w ≤ T := + (Nat.mul_le_mul_right w (Nat.le_mul_of_pos_right _ (pos (3 + c)))).trans paid + have host : 2 ^ b.scheme.m * (D.PortCount b.scheme + 2) * w ≤ T := + (Nat.mul_le_mul_right _ (Nat.mul_le_mul hosts port_exp)).trans paid + have base : 2 ^ w * w ≤ T := by + have h := (Nat.le_mul_of_pos_right M (show 0 < N from Nat.two_pow_pos _)).trans + (Nat.le_mul_of_pos_right _ (pos c)) + exact (Nat.mul_le_mul_right _ (hsize.trans h)).trans long + have hv' : D.v ≤ 2 ^ w := calc + _ ≤ 2 * D.v := by omega + _ = p V := fv + _ ≤ p B := mono (by omega) + _ ≤ w := hwidth + _ ≤ _ := Nat.lt_two_pow_self.le + have hmin : 64 ≤ w := (le 6).trans ((mono (by omega : 6 ≤ B)).trans hwidth) + refine ⟨⟨hmin, hn, hu, fk, host, outer, (Nat.mul_le_mul_right _ hv').trans base, base, + (Nat.mul_le_mul_right _ (by norm_num : 50000 ≤ 10 ^ 38)).trans ht⟩, short, long, ?_⟩ + have hp := mono (show c ≤ R + c by omega) + have hk : 2 ^ b.scheme.h ≤ p (R + c) := Nat.pow_le_pow_right (by decide) b.blocks + have hh : 14 * p (R + c) ≤ 2 * D.v := calc + _ ≤ p 5 * p (R + c) := Nat.mul_le_mul_right _ ((by decide : 14 ≤ 2 ^ 5).trans (le 5)) + _ ≤ p V := by rw [← add]; exact mono (by omega) + _ = _ := fv.symm + omega + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- +# Cost of one controlled transfer + +Pass the public bits through once, then close the terminal layouts. +Batch the remaining short tables after composing every stage. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Transfer +open Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {G : Diagram F x y} {D : Dimensions} + {M C c e R J w T : ℕ} (b : Transfer G D M C c e R J w) + +private theorem endpoints (budget : D.Budget b.scheme x y w T) + (hT : T = allowance C D.h J (D.b * D.z) M (wd x + wd y)) (hJ : J ≤ D.h) + (hu : 2 ^ (c * J) * D.b ≤ D.u) (hv : D.PortCount b.scheme + 2 + 2 * 2 ^ b.scheme.h ≤ D.v) : + ∀ i a v, ∃ (G : Diagram F x y) (t : Assignment D b.scheme G) (hw : t.Fits), + b.stop.eval i a v = t.state.diagram.eval a v ∧ b.view.Valid t hw (b.stop.encode i a v) := by + intro i a v + obtain ⟨t, hw, hl, hv', hc⟩ := b.correct i a v + have hx : t.state.X ≤ T := by + apply Nat.cast_le (α := ℝ) |>.mp + rw [hT, allowance_value _ _ _ _ _ _ hJ] + refine hw.trans ?_ + unfold Dimensions.copies + gcongr + linarith + have ht (u j) : t.state.load u j ≤ (D.u * D.z : ℕ) := + (hl u j).trans (Nat.cast_le.mpr (Nat.mul_le_mul_right D.z hu)) + exact ⟨G, t, budget.fits t ht hx hv, hv', hc _⟩ + +theorem build (budget : D.Budget b.scheme x y w T) + (hT : T = allowance C D.h J (D.b * D.z) M (wd x + wd y)) (hJ : J ≤ D.h) + (hu : 2 ^ (c * J) * D.b ≤ D.u) (hv : D.PortCount b.scheme + 2 + 2 * 2 ^ b.scheme.h ≤ D.v) + (hs : D.shortBudget M e J ≤ T) (hl : D.longBudget M c R J w ≤ T) + (he : D.e = 2 * w) (ha : D.a = 3 * w) (hh : 8 * D.shortWidth b.scheme (Fintype.card b.Z) ≤ w) + (hext : D.h + 4 ≤ D.b * D.z) + (hsmall : 2 * 2 ^ (D.h + 2) * (D.h + 1 + D.b * D.z + 2) + ≤ min (2 ^ ((Nat.clog 2 w) ^ 3)) (2 ^ (w / 2))) + (htop : 10 ^ 38 * T ≤ 2 ^ (5 * w / 4)) : + ∃ u s, Wide F u (Allowed F w) (copies x D.copies) (copies y D.copies) + (MatrixExponent.power G.eval D.copies) s ∧ s ≤ 10 ^ 35 * T := by + let cap := max b.scale (2 * 2 ^ (2 * w) * (4 * w)) + let L := Allowed F w ∪ (b.labels : Set (Table F)) + let j := D.height b.scheme x y w + obtain ⟨hc, hr⟩ := budget.room he ha hh hext (show 2 * 2 ^ (2 * w) * (4 * w) + ≤ cap from le_max_right ..) hsmall + have done := terminal b.stop b.view hc hr (b.endpoints budget hT hJ hu hv) + have large : Allowed F w ⊆ L := Set.subset_union_left + have prog := b.transfer.widen (le_max_left b.scale (2 * 2 ^ (2 * w) * (4 * w))) (Set.Subset.refl + L) + obtain ⟨n, hn, net⟩ := prog.public_end hc.gates (done.widen le_rfl large) b.first b.code b.encoded + have hb := b.cost + have hex : wd (copies x D.copies) + wd (copies y D.copies) ≤ T := by + rw [wd_copies, wd_copies, ← mul_add, mul_comm] + exact budget.exterior + have width : b.stop.public.port.width = b.stop.port.width + + (wd (copies x D.copies) + wd (copies y D.copies)) := by + rw [show b.stop.public.port = b.stop.port.pair (.wire (.pair _ _)) from rfl, Format.width_pair] + exact congrArg _ (card_slots (.pair _ _)) + have hcost := budget.charge + rw [width] at hn + have h₁ : n ≤ 10 ^ 26 * T := by omega + have h₃ := budget.min + have hn' : n ≤ 2 ^ (2 * w - 1) := (h₁.trans ((by omega : 10 ^ 26 * T + ≤ 10 ^ 38 * T).trans htop)).trans + (Nat.pow_le_pow_right (by decide) (by omega)) + rw [b.power] at net + obtain ⟨u, s, hs, hsize⟩ := batch_labels h₃ b.labels b.few b.small net hn' + have hw := budget.base + rw [mul_comm (2 ^ w)] at hw + exact ⟨u, s, hs, by omega⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Transfer +end + +section +/- # Fitting short descriptions below the sorting address width -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Filter +variable {F : Type} [Field F] + +theorem Recipe.shallow (P : Recipe F) (R : ℕ) : + ∀ᶠ J : ℕ in atTop, P.blocks (R + J) J ≤ 2 ^ J := by + filter_upwards [replication (by norm_num : (0 : ℝ) < 1) (R + 1 + P.n * (P.H + 5))] with j hj + have hb := hj _ le_rfl + rw [Real.rpow_one] at hb + have he : (2 : ℕ) ^ ((R + 1 + P.n * (P.H + 5)) * j ^ 2) ≤ 2 ^ (2 ^ j) := by exact_mod_cast hb + exact (P.reserve_width R j).trans ((Nat.pow_le_pow_iff_right (by decide)).mp he) + +private theorem bound (e j B : ℕ) (he : 1 ≤ e) (hj : 1 ≤ j) (hB : 100 * e ≤ B) : + (100 + 2 ^ (e * j)) ^ 8 ≤ 2 ^ (B * j) := by + have hl := Nat.mul_pos he hj + have ha : 100 + 2 ^ (e * j) ≤ 2 ^ (7 + e * j) := by + rw [pow_add]; have := Nat.two_pow_pos (e * j); omega + calc + _ ≤ (2 ^ (7 + e * j)) ^ 8 := Nat.pow_le_pow_left ha _ + _ = 2 ^ ((7 + e * j) * 8) := (pow_mul ..).symm + _ ≤ 2 ^ (B * j) := Nat.pow_le_pow_right (by decide) (by + have := Nat.mul_le_mul_right j hB + rw [mul_assoc] at this + omega) + +theorem Transfer.short {x y : Wire} {G : Diagram F x y} {D : Dimensions} + {M C c e R J w Q V B b : ℕ} (t : Transfer G D M C c e R J w) + (hj : 1 ≤ J) (hr : Q ≤ R) (hv : R + c + 5 ≤ V) (hb : 100 * (1 + b + V + e) ≤ B) + (hh : D.h ≤ 2 ^ J) (hb' : D.b = b ^ J) (hq : D.q = 2 ^ (Q * J)) (hrow : D.r ≤ V * J) + (hw : 2 ^ (B * J) ≤ w) : 8 * D.shortWidth t.scheme (Fintype.card t.Z) ≤ w := by + let L := 1 + b + V + e + have pow (n : ℕ) (hn : n ≤ L) : 2 ^ (n * J) ≤ 2 ^ (L * J) := + Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ hn) + have huge := bound L J B (by unfold L; omega) hj hb + have unit : D.u ≤ 2 ^ (L * J) := by + calc + D.u ≤ D.q * D.b := by rw [D.width]; omega + _ ≤ 2 ^ (Q * J) * (2 ^ b) ^ J := by rw [hq, hb']; gcongr; exact Nat.lt_two_pow_self.le + _ = 2 ^ ((Q + b) * J) := by rw [add_mul, pow_add, pow_mul 2 b] + _ ≤ _ := pow (Q + b) (by unfold L; omega) + have hpow := pow V (by unfold L; omega) + apply le_trans _ (huge.trans hw) + apply D.shortWidth_le + · exact t.bits.trans (pow _ (by unfold L; omega)) + · exact (Nat.pow_le_pow_right (by decide) t.blocks).trans (pow _ (by unfold L; omega)) + · exact t.tag.trans (pow _ (by unfold L; omega)) + · exact hrow.trans ((Nat.lt_two_pow_self.le).trans hpow) + · exact hh.trans (by simpa using pow 1 (by unfold L; omega)) + · rw [hq]; exact pow _ (by unfold L; omega) + · exact unit + · exact (Nat.pow_le_pow_right (by decide) hrow).trans hpow + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- +# A succinct transfer yields the many-list compiler + +Fix the exponent of the long-name cost before the terminal reserve. +Then choose the width scale after the short-record exponent is known. +The logarithmic number of beats yields a power saving in that width. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Filter + +variable {F : Type} [Field F] + +private theorem final_cost (B J w C h k M E s : ℕ) (hB : 0 < B) (hw : 1 ≤ w) + (hu : w ≤ 2 ^ (2 * B * J)) (hJ : J ≤ h) (hs : s ≤ 10 ^ 35 * allowance C h J k M E) : + (s : ℝ) ≤ (10 ^ 35 * (C + 1) : ℕ) * (2 ^ h * k : ℕ) * + ((M : ℝ) * (w : ℝ) ^ (-(1 / (2 * B : ℝ))) + E) := by + have h := Nat.cast_le (α := ℝ) |>.mpr hs + rw [Nat.cast_mul, allowance_value _ _ _ _ _ _ hJ] at h + refine h.trans ?_ + push_cast + rw [mul_comm (M : ℝ), ← mul_assoc, ← mul_assoc] + gcongr + exact saving hB hw hu + +theorem compilation_of_encoded (h : Encoded F) : Compilation F := by + obtain ⟨P, C, c, d, hd, h⟩ := h + let Q := c + 2 + let R := Q + 2 * c + 10 + let V := R + c + 5 + obtain ⟨e, H⟩ := h Q R V le_rfl le_rfl le_rfl + let B := 100 * (1 + P.b + V + e) + have hQR : Q ≤ R := by unfold R; omega + have hVQ : Q ≤ V := by unfold V; omega + have hB : 5 + Q + P.b + V ≤ B := by unfold B; omega + have hb : 0 < B := by omega + obtain ⟨L, hL⟩ := eventually_atTop.mp <| (H B le_rfl).and <| + (P.reserve_limits R Q B (by omega)).and (P.shallow R) + refine ⟨10 ^ 35 * (C + 1), 1 / (2 * (B : ℝ)), by positivity, fun κ hk => ?_⟩ + let δ := min κ (1 / 20 : ℝ) + filter_upwards [P.reserve_parameters R Q V B L hB (show 0 < δ by unfold δ; positivity), + allowance_small C, eventually_ge_atTop 1] with w hw hall hw' + obtain ⟨J, z, hL', hJ, hl, hu, hz, hdiv, hlo, hhi, hp, hdim⟩ := hw + obtain ⟨run, limits, shallow⟩ := hL J hL' + intro x y k v M net h₀ low high + obtain ⟨G, rfl, hg, hcard⟩ := net.diagram + by_cases hG : Nonempty G.V + swap + · let _ := not_nonempty_iff.mp hG + have hv : v = 0 := hcard.symm.trans Fintype.card_of_isEmpty + obtain ⟨n, hn, hnet⟩ := (net.power 1).includeWide (L := Allowed F w) (le_rfl : 3 ≤ 3) + have hzero : n = 0 := by simpa [hv] using hn + refine ⟨1, 3, n, le_rfl, ?_, hnet, ?_⟩ + · rw [Nat.cast_one] + apply Real.one_le_rpow _ hk.le + exact_mod_cast Nat.one_le_pow w 2 (by decide) + · rw [hzero, Nat.cast_zero] + positivity + let b := P.blocks (R + J) J + let T := allowance C b J (P.b ^ J * z) M (wd x + wd y) + have hq : 0 < Q * J := Nat.mul_pos (by unfold Q; omega) hJ + have hv : 0 < V * J := Nat.mul_pos (by unfold V; omega) hJ + have hr : R * J ≤ b := by + unfold b Recipe.blocks + exact (Nat.mul_le_mul_right J (Nat.le_add_right ..)).trans (Nat.le_add_right ..) + have hr' : J ≤ b := (Nat.le_mul_of_pos_left _ (by unfold R; omega)).trans hr + have hh : Q * J ≤ b + 1 := (Nat.mul_le_mul_right _ hQR).trans (hr.trans (Nat.le_succ b)) + let D := P.dimensions w J z (R + J) Q V (2 ^ (d * J)) T hq hv hh hz hdiv + have hZ : D.z = z := P.dimensions_z .. + have copies : D.copies = P.batch (R + J) J z := P.dimensions_copies .. + have hT : T = allowance C D.h J (D.b * D.z) M (wd x + wd y) := by rw [hZ]; rfl + obtain ⟨a⟩ := run w z T hq hv hh hz hdiv hl hu hlo hhi x y G M hG hg (by omega) low high + change Transfer G D M C c e R J w at a + have hn : (D.copies : ℝ) ≤ (2 ^ w : ℕ) ^ δ := by + simpa only [copies, Nat.cast_pow, Nat.cast_ofNat] using hdim + have big : 1 ≤ (↑(2 ^ w : ℕ) : ℝ) := by exact_mod_cast Nat.one_le_pow w 2 (by decide) + have top : 10 ^ 38 * T ≤ 2 ^ (5 * w / 4) := by + rw [hT] + exact hall _ _ _ _ _ hr' (by omega) high + (hn.trans (Real.rpow_le_rpow_of_exponent_le big (min_le_right ..))) + have hsmall : 8 * D.shortWidth a.scheme (Fintype.card a.Z) ≤ w := + a.short hJ hQR (le_rfl : R + c + 5 ≤ V) (le_rfl : 100 * (1 + P.b + V + e) ≤ B) shallow rfl rfl + (Nat.sub_le ..) hl + obtain ⟨budget, short, long, room⟩ := a.funded Q V B hJ le_rfl le_rfl + (by unfold B; omega) hr low hl (by rw [hZ]; exact hlo) (by rw [hZ]; exact hhi) rfl + (P.dimensions_rows ..) (Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ hd)) + T hT rfl top + have hunit : 2 ^ (c * J) * D.b ≤ D.u := by + apply Nat.mul_le_mul_right + apply Nat.pow_le_pow_right (by decide) + unfold Q + rw [add_mul] + omega + obtain ⟨hdepth, hsort⟩ := limits z w hl hu hlo hhi + obtain ⟨u, s, hwide, hcost⟩ := a.build budget hT hr' hunit room short long rfl rfl hsmall + (by rw [hZ]; exact hdepth) (by rw [hZ]; exact hsort) top + refine ⟨D.copies, u, s, by rw [copies]; exact hp, + hn.trans (Real.rpow_le_rpow_of_exponent_le big (min_le_left ..)), hwide, ?_⟩ + rw [hT] at hcost + exact final_cost B J w C D.h (D.b * D.z) M (wd x + wd y) s hb hw' hu hr' hcost + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- # Many-list encoding at a failed hardness test -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +theorem encoded {F : Type} [Field F] [Finite F] (h : ¬ Tagged.Hard F) : Encoded F := by + let _ := Fintype.ofFinite F + exact encoded_of_rules h (subroundRule F) (resetRule F) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Dictionary.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Dictionary.lean new file mode 100644 index 0000000000..b1e76fda8a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Dictionary.lean @@ -0,0 +1,990 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Restore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortOne +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Batcher +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Bins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Hard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Scan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Single +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import Mathlib.Algebra.BigOperators.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Beat +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Budget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement + +/-! +# Compact initial stacks + +Use one product table at each original station in each block. Keep all +old wires, including loops, and expose the copies in the original order. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Finset Packing Transcript + +variable {F : Type} [Field F] {a b : Wire} {h u n : ℕ} + +open scoped Classical in +/-- The tensor of type `Table F` for the given inputs. -/ +abbrev tensor (B : Table F) (u : ℕ) : Table F := + ⟨copies B.1 u, copies B.2.1 u, fun x y => ∏ i : Fin u, + B.2.2 ((bits B.1).symm (fun k => bits (copies B.1 u) x ((Diagonal.port B.1 u).symm (i, k)))) + ((bits B.2.1).symm (fun k => bits (copies B.2.1 u) y ((Diagonal.port B.2.1 u).symm (i, k))))⟩ + +open scoped Classical in +/-- Reindexes `Ports (tensor B u)` and `Fin u × Ports B` by an equivalence. -/ +def pin (B : Table F) (u : ℕ) : Ports (tensor B u) ≃ Fin u × Ports B := + ((Diagonal.port B.1 u).sumCongr (Diagonal.port B.2.1 u)).trans + (Equiv.prodSumDistrib _ _ _).symm + +open scoped Classical in +theorem sample_tensor (B : Table F) (u : ℕ) (z : Ports (tensor B u) → Bool) : + sample (tensor B u) z = ∏ i : Fin u, sample B (fun p => z ((pin B u).symm (i, p))) := by + unfold sample tensor + simp only [Equiv.apply_symm_apply] + rfl + +variable (G : Diagram F a b) (c : Cell h × Fin u ≃ Fin n) + +open scoped Classical in +/-- Reindexes `(Σ v : Cell h × G.V, slots (copies (W v.2) u))` and `(Σ v : (Cell h × Fin u) × +G.V, slots (W v.2)) where toFun q` by an equivalence. -/ +def unpack (W : G.V → Wire) : + (Σ v : Cell h × G.V, slots (copies (W v.2) u)) ≃ + (Σ v : (Cell h × Fin u) × G.V, slots (W v.2)) where + toFun q := + let p := Diagonal.port (W q.1.2) u q.2 + ⟨((q.1.1, p.1), q.1.2), p.2⟩ + invFun q := ⟨(q.1.1.1, q.1.2), (Diagonal.port (W q.1.2) u).symm (q.1.1.2, q.2)⟩ + left_inv q := by simp + right_inv q := by obtain ⟨⟨⟨i, t⟩, v⟩, k⟩ := q; simp + +open scoped Classical in +/-- Builds `Diagram F (copies a n) (copies b n) where V` with the specified `table`, `src`, +`dst`. -/ +abbrev gathered : Diagram F (copies a n) (copies b n) where + V := Cell h × G.V + E := (G.replicate c).E + table v := tensor (G.table v.2) u + src := (unpack G (fun v => (G.table v).1)).trans (G.replicate c).src + dst := (unpack G (fun v => (G.table v).2.1)).trans (G.replicate c).dst + +open scoped Classical in +private theorem gather_src (i : Cell h) (t : Fin u) (v : G.V) (p : slots (G.table v).1) : + (gathered G c).src ⟨(i, v), (Diagonal.port (G.table v).1 u).symm (t, p)⟩ = + (G.replicate c).src ⟨((i, t), v), p⟩ := by simp [gathered, unpack, Equiv.trans_apply] + +open scoped Classical in +private theorem gather_dst (i : Cell h) (t : Fin u) (v : G.V) (p : slots (G.table v).2.1) : + (gathered G c).dst ⟨(i, v), (Diagonal.port (G.table v).2.1 u).symm (t, p)⟩ = + (G.replicate c).dst ⟨((i, t), v), p⟩ := by simp [gathered, unpack, Equiv.trans_apply] + +open scoped Classical in +private theorem vertex_gathered (x : Val (copies a n)) (y : Val (copies b n)) + (z : (G.replicate c).E → Bool) (i : Cell h) (v : G.V) : + (gathered G c).vertex x y z (i, v) = ∏ t, (G.replicate c).vertex x y z ((i, t), v) := by + unfold Diagram.vertex + dsimp only [gathered, tensor] + simp only [Equiv.apply_symm_apply] + refine prod_congr rfl fun t _ => ?_ + apply congrArg₂ (G.table v).2.2 <;> apply congrArg <;> funext p + · exact congrArg _ (gather_src G c i t v p) + · exact congrArg _ (gather_dst G c i t v p) + +open scoped Classical in +theorem eval_gathered : (gathered G c).eval = (G.replicate c).eval := by + funext x y + unfold Diagram.eval + refine sum_congr rfl fun z _ => ?_ + simp only [Fintype.prod_prod_type, vertex_gathered] + exact prod_congr rfl fun _ _ => prod_comm + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end + +section +/- +# Sorting services for the diagonal descent + +Large sorting tables are permitted only if their entries themselves +have efficient trivalent realizations. Column sorting lifts both kinds +of network while charging each layer for every constituent short sort. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +variable (F : Type) [Field F] + +/-- Requires `DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) (10000 * (wd a + 1))`. -/ +def Fast (a : Wire) [L : LinearOrder (Val a)] : Prop := + DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) (10000 * (wd a + 1)) + +theorem select_net (a : Wire) : + DNet F (.pair (.pair a a) .bit) a (fun x => if x.2 then x.1.1 else x.1.2) (10 * wd a + 2) := by + obtain ⟨f, hf, _⟩ := Rewire.exists_of_width (a := a) (b := word (wd a)) (wd_word _).symm + obtain ⟨g, hg, he⟩ := hf.inverse + have k := ((selectWord F (wd a)).pre ((hf.par hf).par (.id _))).post hg + convert k using 1 + funext ⟨⟨x, y⟩, b⟩ + cases b <;> exact (he _ _).mp rfl + +variable (a : Wire) [LinearOrder (Val a)] + +theorem Fast.exchange (h : Fast F a) : + DNet F (.pair a a) (.pair a a) (fun x => (min x.1 x.2, max x.1 x.2)) (11000 * (wd a + 1)) := by + have lo := select_net F a + have hi := lo.pre ((Rewire.swap a a).par (.id .bit)) + have k := ((DNet.id F (.pair a a)).pair h).comp (lo.pair hi) + convert k.mono (n := 11000 * (wd a + 1)) (by simp only [wd]; omega) using 1 + funext ⟨x, y⟩ + by_cases hh : x < y + · simp [hh, min_eq_left hh.le, max_eq_right hh.le] + · simp [hh, min_eq_right (le_of_not_gt hh), max_eq_left (le_of_not_gt hh)] + +/-- Uses `⟨tree j a, tree j a, fun x y => if sortTree j x = y then 1 else 0⟩` as the +representation. -/ +def sorter (j : ℕ) : Table F := + ⟨tree j a, tree j a, fun x y => if sortTree j x = y then 1 else 0⟩ + +@[simp] theorem arity_sorter (j : ℕ) : Processor.arity (sorter F a j) = 2 * 2 ^ j * wd a := by + simp [Processor.arity, sorter, wd_tree] + ring + +theorem sort_cheap (hf : Fast F a) (j : ℕ) (hb : 1 ≤ wd a) : + sorter F a j ∈ Processor.Cheap F 50000 2 := by + obtain ⟨m, hm, h⟩ := sortTree_net (Fast.exchange F a hf) j + refine ⟨m, ?_, h⟩ + simp only [arity_sorter] + have hj : j ≤ Nat.clog 2 (1 + 2 * 2 ^ j * wd a) := by + calc + _ = Nat.clog 2 (2 ^ j) := (Nat.clog_pow 2 j (by decide)).symm + _ ≤ _ := Nat.clog_mono_right 2 (by have := Nat.le_mul_of_pos_right (2 * 2 ^ j) hb; omega) + calc + _ ≤ 2 ^ j * (j + 1) ^ 2 * (50000 * wd a) := hm.trans (by gcongr; omega) + _ = (2 ^ j * wd a) * 50000 * (1 + j) ^ 2 := by ring + _ ≤ _ := by gcongr; nlinarith [Nat.zero_le (2 ^ j)] + +/-- Lift cheap sorting gates of short length to a whole long sort. -/ +theorem sort_wide (hf : Fast F a) (j l D k : ℕ) (hb : 1 ≤ wd a) (hj : 2 ≤ j) + (harity : 2 * 2 ^ j * wd a ≤ D) (hl : 2 ^ k * (j + l - 2) ≤ 3 ^ k * (j - 2)) : + DWide F D (Processor.Cheap F 50000 2) (tree (j + l) a) (tree (j + l) a) + (sortTree (j + l)) (4 ^ k * (2 ^ l * (1 + 2 * 2 ^ j * wd a))) := by + have h : DWide F D (Processor.Cheap F 50000 2) (tree j a) (tree j a) + (sortTree j) (1 + 2 * 2 ^ j * wd a) := by + have ha := arity_sorter F a j + change wd (tree j a) + wd (tree j a) = _ at ha + rw [← ha] + exact ⟨_, le_rfl, Wide.table _ _ _ (ha.trans_le harity) (.inr (sort_cheap F a hf j hb))⟩ + exact (DWide.columnModel F D (Processor.Cheap F 50000 2)).sort_lift_iterate hj k hl (h.many (2 ^ + l)) + +theorem sort_trivalent (hf : Fast F a) (w l m k : ℕ) (hw : 2 ≤ w) (hb : wd a ≤ 4 * w) + (tag : Net F (Tagged.inputs w (word w)) .unit (Tagged.tag F w (word w)) m) + (hl : 2 ^ k * (w + l - 2) ≤ 3 ^ k * (w - 2)) : + DNet F (tree (w + l) a) (tree (w + l) a) + (sortTree (w + l)) (4 ^ k * (2 ^ l * (4 * m + 10000 * 2 ^ w * (w + 10000 * (wd a + 1) + 1)))) + := by + have h := Tagged.sort_one tag hb hf + let n := 4 * m + 10000 * 2 ^ w * (w + 10000 * (wd a + 1) + 1) + have many (t : ℕ) : DNet F (copies (tree w a) t) (copies (tree w a) t) + (mapCopies (sortTree w) t) (t * n) := by + induction t with + | zero => exact ⟨0, Nat.zero_le _, Net.empty⟩ + | succ t ih => rw [Nat.succ_mul, Nat.add_comm (t * n)]; exact h.par ih + exact Columns.sort_lift_iterate hw k hl (many (2 ^ l)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# A trivalent network with its exterior bits held fixed + +Use two host positions per original station. One holds all copies +in the current block, the other holds their exterior ends. The +frozen charge is exactly the number of exterior bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Finset Packing Rounds.Stack + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +open Classical in +private theorem other_other (e : G.End) : other G (other G e) = e := by + rcases e with (i|e)|(i|e) <;> rfl + +open Classical in +/-- The indexed operation `insert v ((univ.filter (fun e => G.station e = v)).image (fun e => +G.station (other G e)))`. -/ +def near (v : G.V) : Finset G.V := + insert v ((univ.filter (fun e => G.station e = v)).image (fun e => G.station (other G e))) + +open Classical in +theorem near_symm (v w : G.V) (h : w ∈ near G v) : v ∈ near G w := by + simp only [near, mem_insert, mem_image, mem_filter, mem_univ, true_and] at h ⊢ + rcases h with rfl|⟨e, hv, hw⟩ + · exact .inl rfl + · exact .inr ⟨other G e, hw, by rw [other_other, hv]⟩ + +open Classical in +theorem card_near (v : G.V) : (near G v).card ≤ G.arity v + 1 := by + rw [← G.degree, Fintype.card_subtype] + exact (card_insert_le _ _).trans (Nat.add_le_add_right card_image_le _) + +open Classical in +theorem target_mem (e : G.E) : G.target e ∈ near G (G.source e) := + mem_insert_of_mem (mem_image.mpr ⟨.inl (.inr e), mem_filter.mpr ⟨mem_univ _, rfl⟩, rfl⟩) + +open Classical in +/-- The value specified by `(near G v.1) ×ˢ (univ : Finset Bool)`. -/ +def adjacent (v : G.V × Bool) := (near G v.1) ×ˢ (univ : Finset Bool) + +open Classical in +theorem adj_symm (v w) (h : w ∈ adjacent G v) : v ∈ adjacent G w := + mem_product.mpr ⟨near_symm G _ _ (mem_product.mp h).1, mem_univ _⟩ + +open Classical in +theorem adj_size (ht : G.Trivalent) (v) : (adjacent G v).card ≤ 8 := by + rw [adjacent, card_product, card_univ, Fintype.card_bool] + exact Nat.mul_le_mul_right 2 ((card_near G v.1).trans (Nat.add_le_add_right (ht v.1) 1)) + +open Classical in +/-- Indexes the outer by the coordinates of `slots a ⊕ slots b`. -/ +abbrev Outer (a b : Wire) := slots a ⊕ slots b + +open Classical in +/-- Builds `Fringe a b (Outer a b) where tensor` with the specified `tensor`, `charge`, `cover`, +`scale`. -/ +def fringe (a b : Wire) : Fringe a b (Outer a b) where + tensor := id + charge _ := 1 + cover t := by simp + scale := 1 + pos := zero_lt_one + le := le_rfl + +open Classical in +theorem fringe_total (a b : Wire) : (fringe a b).Z = wd a + wd b := by + simp [Fringe.Z, Fringe.reserve, fringe, Outer] + +variable [Field F] {h n u : ℕ} (c : Cell h × Fin u ≃ Fin n) + +open Classical in +/-- The value specified by `((v.2, s), v.1)`. -/ +def locate (s : Bool) (v : (gathered G c).V) : (G.V × Bool) × Cell h := ((v.2, s), v.1) + +open Classical in +/-- Indexes the groups by the coordinates of `gathered G c V := G.V × Bool E := G.E × Cell h src +e := (G.source e.1, false) dst e := (G.target e.1, false)`. -/ +def groups : HostNet F (fringe (copies a n) (copies b n)) h u where + diagram := gathered G c + V := G.V × Bool + E := G.E × Cell h + src e := (G.source e.1, false) + dst e := (G.target e.1, false) + ix := Prod.snd + units := { + place := locate G c false + bits := (Equiv.prodComm _ _).trans (Equiv.prodAssoc _ _ _).symm + left := fun ⟨_, _⟩ => rfl + right := fun ⟨_, _⟩ => rfl } + park := locate G c true ∘ portEnd (gathered G c) + frozen p := p.2 = true + N := adjacent G + C := adjacent G + ns := adj_symm G + cs := adj_symm G + sub _ := Subset.rfl + kept _ := rfl + core _ := ⟨Bool.false_ne_true, Bool.false_ne_true⟩ + edge e := mem_product.mpr ⟨target_mem G e.1, mem_univ _⟩ + tether _ := ⟨Bool.false_ne_true, rfl, mem_product.mpr ⟨mem_insert_self _ _, mem_univ _⟩⟩ + +open Classical in +private theorem arity_sum (ht : G.Trivalent) (s : Bool) (v : (G.V × Bool) × Cell h) : + push (locate G c s) (fun i => ((gathered G c).arity i : ℝ)) v ≤ + if s = v.1.2 then 3 * u else 0 := by + have bound (i : (gathered G c).V) : ((gathered G c).arity i : ℝ) ≤ 3 * u := by + have he : (gathered G c).arity i = u * G.arity i.2 := by + simp only [Diagram.arity, wd_copies, mul_add] + rw [he, Nat.cast_mul, mul_comm] + exact mul_le_mul_of_nonneg_right (Nat.cast_le.mpr (ht i.2)) (Nat.cast_nonneg _) + refine (push_le_push _ bound v).trans ?_ + unfold push + change (∑ i : Cell h × G.V, @ite ℝ (((i.2, s), i.1) = v) (propDecidable _) (3 * u) 0) ≤ _ + obtain ⟨⟨z, r⟩, i⟩ := v + simp only [Fintype.sum_prod_type, Prod.mk.injEq] + by_cases eq : s = r <;> simp [eq, ite_and] + +open Classical in +theorem bounded (ht : G.Trivalent) : (groups G c).Bounded 8 8 (3 * u) := by + refine ⟨adj_size G ht, adj_size G ht, fun v i => ?_⟩ + rw [(groups G c).load_eq (v, i)] + simp only [show (groups G c).past (v, i) = 0 from rfl, Nat.cast_zero, mul_zero, add_zero] + change push (locate G c false) _ (v, i) + + 1 * push (locate G c true ∘ portEnd (gathered G c)) (fun _ => 1) (v, i) ≤ _ + rw [one_mul, ← port_load] + have h₁ := arity_sum G c ht false (v, i) + have h₂ := arity_sum G c ht true (v, i) + rw [site_arity] at h₂ + refine (add_le_add h₁ ((le_add_of_nonneg_right (Nat.cast_nonneg _)).trans h₂)).trans_eq ?_ + cases v.2 <;> simp + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end + +section +/- +# Sorting on the exceptional length sequence + +One version uses trivalent tables and pays for the exceptional tag +verifier. The other uses cheap sorting tables of bounded arity and has +a constant cost per bit. All exponents below refer to bit lengths. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Filter + +variable {F : Type} [Field F] + +/-- One cost measured in two models at the same length. -/ +def Service (F : Type) [Field F] (w : ℕ) (C : ℝ) (a b : Wire) + (k : Val a → Val b → F) (budget : ℕ) : Prop := + (∃ v, Net F a b k v ∧ (v : ℝ) ≤ C * budget) ∧ + ∃ s ≤ budget, Wide F (2 ^ (w / 2)) (Processor.Cheap F 50000 2) a b k s + +theorem arity_cap (w : ℕ) : (2 ^ (w / 2)) ^ 2 ≤ 2 ^ w := by + rw [← pow_mul] + apply Nat.pow_le_pow_right (by decide) + omega + +private theorem row_cap {w : ℕ} (hw : 64 ≤ w) : 8 * w ≤ 2 ^ (w / 4) := by + have aux (n : ℕ) (hn : 16 ≤ n) : 32 * (n + 1) ≤ 2 ^ n := by + induction n, hn using Nat.le_induction with + | base => norm_num + | succ k _ ih => rw [pow_succ]; omega + have := aux (w / 4) (by omega) + omega + +theorem cheap_arity {w b : ℕ} (hw : 64 ≤ w) (hb : b ≤ 4 * w) : + 2 * 2 ^ (w / 4) * b ≤ 2 ^ (w / 2) := by + calc + _ ≤ 2 ^ (w / 4) * (8 * w) := by + rw [show 2 * 2 ^ (w / 4) * b = 2 ^ (w / 4) * (2 * b) by ring] + exact Nat.mul_le_mul_left _ (by omega) + _ ≤ 2 ^ (w / 4) * 2 ^ (w / 4) := Nat.mul_le_mul_left _ (row_cap hw) + _ ≤ _ := by rw [← pow_add]; apply Nat.pow_le_pow_right (by decide); omega + +/-- Four to the sixth is an upper bound on the number of layers for +height ratios up to eight. -/ +theorem sort_service {a : Wire} [LinearOrder (Val a)] (hf : Fast F a) {w j m : ℕ} {C : ℝ} (hw : 64 + ≤ w) (hj : w ≤ j) (hj' : j ≤ 2 * w) + (hb : 1 ≤ wd a) (hb' : wd a ≤ 4 * w) (hC : 1 ≤ C) + (tag : Net F (Tagged.inputs w (word w)) .unit (Tagged.tag F w (word w)) m) + (hc : (m : ℝ) ≤ C * (2 : ℝ) ^ w * w) : + Service F w C (tree j a) (tree j a) (sorter F a j).2.2 (10 ^ 12 * 2 ^ j * w) := by + have hp (k : ℕ) (hk : k ≤ j) : 2 ^ (j - k) * 2 ^ k = (2 ^ j : ℕ) := by + rw [← pow_add, Nat.sub_add_cancel hk] + constructor + · have ht := sort_trivalent F a hf w (j - w) m 2 (by omega) hb' tag (by omega) + rw [Nat.add_sub_of_le hj] at ht + obtain ⟨v, hv, hv'⟩ := ht + refine ⟨v, hv', ?_⟩ + have hp' : (2 : ℝ) ^ (j - w) * 2 ^ w = 2 ^ j := by exact_mod_cast hp w hj + have hs : (w + 10000 * (wd a + 1) + 1 : ℕ) ≤ C * (50000 * (w : ℝ)) := by + have : w + 10000 * (wd a + 1) + 1 ≤ 50000 * w := by omega + exact (show (w + 10000 * (wd a + 1) + 1 : ℕ) ≤ 50000 * (w : ℝ) by exact_mod_cast this).trans + (le_mul_of_one_le_left (by positivity) hC) + calc + _ ≤ (4 : ℝ) ^ 2 * (2 ^ (j - w) * (4 * m + 10000 * 2 ^ w * (w + 10000 * (wd a + 1) + 1 : ℕ))) + := by exact_mod_cast hv + _ ≤ 4 ^ 2 * (2 ^ (j - w) * (4 * (C * 2 ^ w * w) + 10000 * 2 ^ w * (C * (50000 * w)))) + := by gcongr + _ = C * (8000000064 * 2 ^ j * w) := by rw [← hp']; ring + _ ≤ _ := by push_cast; gcongr; norm_num + · have hle : w / 4 ≤ j := by omega + have ht := sort_wide F a hf (w / 4) (j - w / 4) (2 ^ (w / 2)) 6 hb (by omega) + (cheap_arity hw hb') (by omega) + rw [Nat.add_sub_of_le hle] at ht + obtain ⟨v, hv, hv'⟩ := ht + refine ⟨v, hv.trans ?_, hv'⟩ + have hs : 1 + 2 * 2 ^ (w / 4) * wd a ≤ 9 * 2 ^ (w / 4) * w := by + have : 0 < 2 ^ (w / 4) := by positivity + nlinarith + calc + _ ≤ 4 ^ 6 * (2 ^ (j - w / 4) * (9 * 2 ^ (w / 4) * w)) := by gcongr + _ = (4 ^ 6 * 9) * 2 ^ j * w := by rw [← hp _ hle]; ring + _ ≤ _ := by gcongr; norm_num + +theorem frequent_tags (bad : ¬ Tagged.Hard F) {ε : ℝ} (hε : 0 < ε) : + ∃ᶠ w : ℕ in atTop, ∃ m, Net F (Tagged.inputs w (word w)) .unit (Tagged.tag F w (word w)) m ∧ + (m : ℝ) ≤ (w : ℝ) ^ ε * (2 : ℝ) ^ w * w := by + by_contra! h + refine bad ⟨ε, hε, ?_⟩ + filter_upwards [h] with w hw m hm + simpa only [mul_comm, mul_left_comm, mul_assoc] using (hw m hm).le + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- # Substituting short or high-arity sorts on the same graph -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Finset + +variable {F : Type} [Field F] {a b : Wire} {w : ℕ} {C : ℝ} + +theorem Service.mono {k : Val a → Val b → F} {m n : ℕ} + (h : Service F w C a b k m) (hmn : m ≤ n) (hc : 0 ≤ C) : Service F w C a b k n := by + obtain ⟨⟨v, hv, hcost⟩, s, hs, hw⟩ := h + exact ⟨⟨v, hv, hcost.trans (mul_le_mul_of_nonneg_left (Nat.cast_le.mpr hmn) hc)⟩, s, + hs.trans hmn, hw⟩ + +/-- The sort tables of type `Set (Table F)` for the given inputs. -/ +def SortTables (F : Type) [Field F] (w : ℕ) : Set (Table F) := + {T | ∃ (j : ℕ) (a : Wire) (_ : LinearOrder (Val a)), Fast F a ∧ + w ≤ j ∧ j ≤ 2 * w ∧ w ≤ wd a ∧ wd a ≤ 4 * w ∧ T = sorter F a j} + +/-- Short tables have a pointwise trivalent simulation. Long sorts +use a tag verifier at an exceptional height. -/ +def Allowed (F : Type) [Field F] (w : ℕ) : Set (Table F) := + SortTables F w ∪ {T | T ∈ Processor.Cheap F 50000 2 ∧ + Processor.arity T ≤ 2 ^ ((Nat.clog 2 w) ^ 3) ∧ Processor.arity T ≤ 2 ^ (w / 2)} + +theorem sort_allowed : SortTables F w ⊆ Allowed F w := fun _ h => Or.inl h + +theorem service_of_diagram (G : Diagram F a b) (cost : G.V → ℕ) + (h : ∀ v, Service F w C (G.table v).1 (G.table v).2.1 (G.table v).2.2 (cost v)) : + Service F w C a b G.eval (∑ v, cost v) := by + classical + constructor + · choose v hv hcost using fun i => (h i).1 + refine ⟨∑ i, v i, Diagram.realize (Net F) Net.empty Net.par Net.pre Net.post Net.trace G v hv, + ?_⟩ + simp only [Nat.cast_sum, mul_sum] + exact sum_le_sum fun i _ => hcost i + · choose s hs hw using fun i => (h i).2 + exact ⟨∑ i, s i, sum_le_sum (fun i _ => hs i), + Diagram.realize _ Wide.empty Wide.par Wide.pre Wide.post Wide.trace G s hw⟩ + +/-- The one-time length overhead is avoided by padding full sorting +vertices to at least `2^w` records of at least `w` bits. -/ +theorem expand {u v m : ℕ} {k : Val a → Val b → F} (hw : 64 ≤ w) (hC : 1 ≤ C) + (tag : Net F (Tagged.inputs w (word w)) .unit (Tagged.tag F w (word w)) m) + (hc : (m : ℝ) ≤ C * (2 : ℝ) ^ w * w) + (hl : ((2 + (Nat.clog 2 w) ^ 3) ^ 2 : ℕ) ≤ C) + (h : Wide F u (Allowed F w) a b k v) : Service F w C a b k (10 ^ 12 * v) := by + have table (T : Table F) (ht : Processor.arity T ≤ 3 ∨ T ∈ Allowed F w) : + Service F w C T.1 T.2.1 T.2.2 (10 ^ 12 * (1 + Processor.arity T)) := by + rcases ht with ht | ⟨j, b, _, hf, hj, hj', hb, hb', rfl⟩ | ⟨hcheap, hsmall, hD⟩ + · have hk := Net.table (F := F) T.1 T.2.1 T.2.2 ht + have hu : 3 ≤ 2 ^ (w / 2) := by + have := Nat.pow_le_pow_right (n := 2) (by decide) (show 2 ≤ w / 2 by omega) + omega + obtain ⟨s, hs, h⟩ := hk.includeWide (L := Processor.Cheap F 50000 2) hu + have h' : Service F w C T.1 T.2.1 T.2.2 4 := ⟨⟨1, hk, by norm_num; linarith⟩, s, hs, h⟩ + exact h'.mono (by omega) (by linarith) + · refine (sort_service hf hw hj hj' (by omega) hb' hC tag hc).mono ?_ (by linarith) + rw [arity_sorter, mul_assoc (10 ^ 12)] + apply Nat.mul_le_mul_left + have := Nat.mul_le_mul_left (2 ^ j) hb + rw [mul_assoc 2] + omega + · let n := Processor.arity T + have hlog : Nat.clog 2 (1 + n) ≤ (Nat.clog 2 w) ^ 3 + 1 := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_succ] + have := Nat.two_pow_pos ((Nat.clog 2 w) ^ 3) + omega + obtain ⟨v, hv, hnet⟩ := show T ∈ Processor.Cheap F 50000 2 from hcheap + refine ⟨⟨v, hnet, ?_⟩, 1 + n, by omega, Wide.table _ _ _ hD (.inr hcheap)⟩ + have hv' : v ≤ 10 ^ 12 * (1 + n) * ((2 + (Nat.clog 2 w) ^ 3) ^ 2) := calc + _ ≤ (1 + n) * 50000 * (1 + Nat.clog 2 (1 + n)) ^ 2 := hv + _ ≤ _ := by + rw [mul_comm (1 + n) 50000] + apply Nat.mul_le_mul + · exact Nat.mul_le_mul_right _ (by norm_num) + · exact Nat.pow_le_pow_left (by omega) 2 + rw [mul_comm C] + exact (Nat.cast_le.mpr hv').trans (by rw [Nat.cast_mul]; gcongr) + obtain ⟨G, he, had, hs⟩ := h.diagram + have hv := service_of_diagram G (fun i => 10 ^ 12 * (1 + G.arity i)) (fun i => table _ (had i).2) + rw [he, ← mul_sum] at hv + rw [← hs] + exact hv + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- +# Fixed-length simultaneous dictionary lookup + +A length cap on the address permits all table values, even zero. The +only additional gate is one sorting relation in the permitted range. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Lookup + +variable {F : Type} [Field F] {w u : ℕ} + +theorem lookup (a : Wire) (f : Val a → F) (hbig : w ≤ wd a) + (hsmall : wd a + 1 ≤ 2 * w) + (harity : 2 * 2 ^ (wd a + 1) * (2 * wd a + 2) ≤ u) (hu : 3 ≤ u) : + ∃ s ≤ 10000 * 2 ^ (wd a) * (1 + wd a), + Wide F u (SortTables F w) (tree (wd a) a) .unit + (fun x _ => ((flatten (wd a) x).map f).prod) s := by + let t := wd a + let L := SortTables F w + let _ := keyOrder a + let _ := rowOrder a + obtain ⟨z, hn, hall, he⟩ := sort_dict a (row_query a) (row_key a) + have hr : wd (row a) = 2 * t + 2 := by simp [wd, t]; omega + have cmp : Fast F (row a) := (row_compare F a).mono (by rw [hr]; omega) + have hd : Processor.arity (sorter F (row a) (t + 1)) = 2 * 2 ^ (t + 1) * (2 * t + 2) := by + rw [arity_sorter, hr] + have ok : sorter F (row a) (t + 1) ∈ L := + ⟨t + 1, row a, inferInstance, cmp, by omega, hsmall, by omega, by omega, rfl⟩ + have hs : DWide F u L (tree (t + 1) (row a)) (tree (t + 1) (row a)) + (sortTree (t + 1)) (1 + 2 * 2 ^ (t + 1) * (2 * t + 2)) := by + rw [← hd] + exact ⟨_, le_rfl, Wide.table _ _ _ (hd.trans_le harity) (.inr ok)⟩ + have prep := (queries_net F a t).par (dict_net F a t z) + have accept := ((DWide.of_dnet hu prep).comp hs).comp (DWide.of_dnet hu (scan_net F a (t + 1))) + obtain ⟨v, hv, check⟩ := accept + have pin := Wide.table (K := F) (labels := L) .bit .unit (fun b _ => if b then 1 else 0) + (show wd .bit + wd .unit ≤ u by simp only [wd]; omega) (.inl (by decide)) + have valid : Wide F u L (.pair (tree t a) (tree t (count a))) .unit + (fun y _ => if expected a (flatten t y.1) t z = y.2 then 1 else 0) (v + 2) := by + convert check.comp pin using 1 <;> try rfl + funext y _ + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + have eqn : scan a (t + 1) (sortTree (t + 1) (queries a t y.1, dict a t z y.2)) = + decide (expected a (flatten t y.1) t z = y.2) := by + unfold scan + rw [he, fold_dict a (flatten t y.1) t z y.2 true, Bool.true_and] + simp only [eqn, decide_eq_true_eq] + obtain ⟨r, hc, weights⟩ := (weights_net F a f t z).includeWide (L := L) hu + have out := ((valid.par weights).pre (.unit' _)).trace + refine ⟨v + 2 + r, ?_, ?_⟩ + · have h2 : 0 < 2 ^ t := pow_pos (by decide) _ + simp only [hr, pow_succ] at hv + change v + 2 + r ≤ 10000 * 2 ^ t * (1 + wd a) + dsimp only [t] at * + nlinarith only [h2, hv, hc] + · simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, + t, weight_lookup a f _ z hn hall] using out + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# A common lookup table for partial batches + +Reserve one bit of the address as an enable bit. Inactive rows +contribute one and require no inverse, even when table entries vanish. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Finset Install Transcript + +variable {F X I R : Type} [Field F] [Fintype X] [Fintype I] [Fintype R] + +omit [Fintype X] in +open Classical in +theorem tap_depends {Y : Type} (read : Y → X ⊕ Bool) : + Depends (fun x => Sum.elim x id ∘ read) 1 := by + intro i + cases h : read i with + | inl t => exact ⟨{t}, by simp, fun x y he => by simp [h, he t (by simp)]⟩ + | inr v => exact ⟨∅, by simp, fun x y _ => by simp [h]⟩ + +open Classical in +/-- A batch of at most `2^j` independent, partially hardwired calls. -/ +theorem dictionary {w j u : ℕ} (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) + (hu : 3 ≤ u) (ha : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ u) + (hI : Fintype.card I < j) (hR : Fintype.card R ≤ 2 ^ j) + (k : (I → Bool) → F) (r : R → I → X ⊕ Bool) : + WideWeight F u (SortTables F w) + (fun x => ∏ p, k (Sum.elim x id ∘ r p)) + (4 * Fintype.card X + 11000 * 2 ^ j * (1 + j)) := by + let b := word j + let names : Option I ↪ slots (word j) := + (Function.Embedding.nonempty_of_card_le (by simpa using hI)).some + let row : R ↪ Fin (2 ^ j) := (Function.Embedding.nonempty_of_card_le (by simpa using hR)).some + let data (p : R) (i : Option I) : X ⊕ Bool := i.elim (.inr true) (r p) + let taps := Function.extend row + (fun p => Function.extend names (data p) (fun _ => .inr false)) (fun _ _ => .inr false) + let f (x : Val (word j)) := if bits b x (names none) then k (fun i + => bits b x (names (some i))) else 1 + have all (x : X → Bool) : + (∏ i : Fin (2 ^ j), f ((bits b).symm (Sum.elim x id ∘ taps i))) = + ∏ p, k (Sum.elim x id ∘ r p) := by + rw [← prod_subset (subset_univ (univ.image row))] + · rw [prod_image row.injective.injOn] + refine prod_congr rfl fun p _ => ?_ + simp only [f, taps, Equiv.apply_symm_apply, Function.comp_apply, + row.injective.extend_apply, names.injective.extend_apply, data, Option.elim_none, + Option.elim_some, Sum.elim_inr, id_eq, ite_true] + rfl + · intro i _ hi + have hn : ¬∃ p, row p = i := by simpa only [mem_image, mem_univ, true_and] using hi + simp [taps, Function.extend_apply' _ _ _ hn, f] + have hlookup := lookup (word j) f (w := w) (u := u) + (by simpa using hj) (by simpa using hj') (by simpa using ha) hu + rw [wd_word] at hlookup + obtain ⟨m, hm, hnet⟩ := hlookup + obtain ⟨L, hL⟩ := Layout.exists_tree (word j) j + let read : Fin (2 ^ j) × slots (word j) → X ⊕ Bool := Function.uncurry taps + intro a ix + have g := (tap_depends read).bnet F a (tree j (word j)) ix L.positions + obtain ⟨n, hn, net⟩ := DWide.of_dnet (L := SortTables F w) hu g + refine ⟨n + m, ?_, ?_⟩ + · simp only [Fintype.card_prod, Fintype.card_fin, MatrixExponent.card_slots, wd_word, localCost] + at hn + change n ≤ 4 * (Fintype.card X + 34 * (2 ^ j * j)) at hn + nlinarith only [hn, hm, Nat.zero_le (2 ^ j * j), Nat.zero_le (2 ^ j)] + · have comp := net.comp hnet + simp only [ite_mul, one_mul, zero_mul, sum_ite_eq, mem_univ, ite_true] at comp + convert comp using 1 + funext x _ + rw [← hL, List.map_ofFn, List.prod_ofFn] + refine (all _).symm.trans ?_ + refine prod_congr rfl fun i _ => ?_ + simp only [Function.comp_apply, Layout.read, Equiv.apply_symm_apply, Equiv.symm_apply_apply] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Applying any number of beats to the trivalent input + +The number of selectors is charged in the smallest bundle units, +independently of how many *bits* each unit carries. Tether names +remain separately recoverable through the preserved fringe. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Packing + +variable {F : Type} [Field F] {x y : Wire} {u h : ℕ} + +/-- Reindexes two finite types using equality of cardinalities. -/ +def ordinal (h u : ℕ) : Cell h × Fin u ≃ Fin (2 ^ h * u) := + Fintype.equivOfCardEq (by simp [Cell]) + +/-- Computes the start by the application `groups G (ordinal h u)`. -/ +abbrev start (G : Diagram F x y) (h u : ℕ) := groups G (ordinal h u) + +theorem start_seats (G : Diagram F x y) : + (start G h u).seats = 2 * Fintype.card G.V * 2 ^ h := by + change Fintype.card (G.V × Bool) * 2 ^ h = _ + rw [Fintype.card_prod, Fintype.card_bool, mul_comm (Fintype.card G.V)] + +theorem start_width (G : Diagram F x y) : + (start G h u).X = 2 ^ h * u * Fintype.card G.E := by + change Fintype.card (G.E × Cell h) * u = _ + rw [Fintype.card_prod, card_cell] + ring + +theorem start_exact (G : Diagram F x y) : + (start G h u).diagram.eval = power G.eval (2 ^ h * u) := + (eval_gathered G _).trans (G.eval_replicate _) + +theorem reduce {b n e K : ℕ} {ρ C : ℝ} (R : Reduction F 8 3 b n e K ρ C) (hρ : ρ ≤ 1) + (G : Diagram F x y) (hg : G.Trivalent) (M r a z : ℕ) + (hsize : Fintype.card G.V + wd x + wd y ≤ M) (hz : 0 < z) (hu : u = b * z) + (hh : a + n * r ≤ h) (hsl : 12 * K ≤ ρ * (2 : ℝ) ^ r) : + let d := 2 ^ h * u + (start G h u).Expands (K * (5 * 2 ^ h * M * b)) (fun Q : HostNet F _ a z => + Q.seats ≤ K * (2 * M * 2 ^ h) ∧ Q.Bounded 3 (8 ^ e) (K * (6 * (u : ℝ))) ∧ + Q.X ≤ (d : ℝ) * ((3 + C) * ρ * M + C * (wd x + wd y : ℕ)) ∧ + Q.seats ≤ K * (start G h u).seats ∧ Q.mass ≤ 10 * K * d * M ∧ + (∀ p, Q.past p ≤ 6 * u * K * 2 ^ r) ∧ (start G h u).Tracks Q K) := by + let d := 2 ^ h * u + let cap := 10 * K * d * M + let H := (start G h u).reserve cap (r + 1) + let L := { (fringe (copies x d) (copies y d)) with cap, discount := r + 1 } + let σ := ρ * d * M / 2 + have hp := R.factor + have hc := R.loss + have hσ : 0 ≤ σ := by unfold σ; positivity + have hV : Fintype.card G.V ≤ M := by omega + have hE : Fintype.card G.E ≤ 3 * M := by have := G.volume_trivalent hg; omega + have hS : H.seats ≤ 2 * M * 2 ^ h := by + change (start G h u).seats ≤ _ + rw [start_seats] + gcongr + have hX : (H.X : ℝ) ≤ d * (3 * M : ℕ) := by + change ((start G h u).X : ℝ) ≤ _ + rw [start_width, Nat.cast_mul] + gcongr + -- Active and frozen charges occupy disjoint sites. Half the slack + -- suffices for the active part, leaving half for eliminated incidences. + have reserve : L.reserve ≤ σ := by + change (cap : ℝ) / (2 : ℝ) ^ (r + 1) ≤ ρ * d * M / 2 + rw [div_le_iff₀ (by positivity), pow_succ] + have he : 10 * (K : ℝ) ≤ ρ * (2 : ℝ) ^ r := by linarith [Nat.cast_nonneg (α := ℝ) K] + unfold cap + push_cast + linarith only [mul_le_mul_of_nonneg_right he (show (0 : ℝ) ≤ d * M by positivity)] + have hZ : L.Z + σ ≤ d * (wd x + wd y : ℕ) + ρ * d * M := by + have he : L.Z = (fringe (copies x d) (copies y d)).Z + L.reserve := by + unfold Fringe.Z + rw [show (fringe (copies x d) (copies y d)).reserve = 0 by simp [Fringe.reserve, fringe], + add_zero] + rw [he, fringe_total, wd_copies, wd_copies] + push_cast + unfold σ at reserve ⊢ + linarith only [reserve] + have hk : K ≤ 2 ^ r := by + have : (K : ℝ) ≤ (2 : ℝ) ^ r := calc + _ ≤ (12 : ℝ) * K := by linarith [Nat.cast_nonneg (α := ℝ) K] + _ ≤ _ := hsl.trans (mul_le_of_le_one_left (by positivity) hρ) + exact_mod_cast this + have hslack : (K : ℝ) * (3 * u) * H.seats ≤ σ * (2 : ℝ) ^ r := calc + _ ≤ (K : ℝ) * (3 * u) * (2 * M * 2 ^ h : ℕ) := by gcongr + _ = (12 * K) * (d : ℝ) * M / 2 := by unfold d; push_cast; ring + _ ≤ (ρ * (2 : ℝ) ^ r) * (d : ℝ) * M / 2 := by gcongr + _ = _ := by unfold σ; ring + have enough : H.X + (L.Z + σ) ≤ 5 * (d : ℝ) * M := calc + _ ≤ (d : ℝ) * (3 * M : ℕ) + (d * (wd x + wd y : ℕ) + ρ * d * M) := add_le_add hX hZ + _ ≤ (d : ℝ) * (3 * M : ℕ) + (d * (M : ℝ) + 1 * d * M) := by + have hxy : wd x + wd y ≤ M := by omega + gcongr + _ = _ := by push_cast; ring + have budget : H.X + (L.Z + σ) ≤ ((5 * 2 ^ h * M * b : ℕ) : ℝ) * z := + enough.trans_eq (by unfold d; rw [hu]; push_cast; ring) + have empty : (start G h u).mass = 0 := by + change ∑ _ : (start G h u).V × Cell h, (0 : ℕ) = 0 + simp + have hb : H.Bounded 8 8 (3 * u) := + (bounded G (ordinal h u) hg).start_budget _ empty cap (r + 1) + obtain ⟨I, _, Q, num, ev, ok⟩ := R.run H z r a 8 (5 * 2 ^ h * M * b) (3 * u) σ hz hu + (by linarith [Nat.cast_nonneg (α := ℝ) u]) le_rfl hb hσ hh hk hslack budget + -- Dropping the reserve preserves every weight and address in each diagram. + refine ⟨I, inferInstance, fun i => (Q i).reserve 0 0, num, ev, fun i => ?_⟩ + obtain ⟨same, hs, hb, hx, hm, tk⟩ := ok i + have hcap : (Q i).mass ≤ cap := by + apply (Nat.cast_le (α := ℝ)).mp + calc + _ ≤ (H.mass : ℝ) + 2 * (K : ℝ) * (H.X + (L.Z + σ)) := hm + _ ≤ 0 + 2 * (K : ℝ) * (5 * (d : ℝ) * M) := by + rw [show H.mass = 0 from empty, Nat.cast_zero] + gcongr + _ = (cap : ℝ) := by unfold cap; push_cast; ring + have hpast (p : (Q i).V × Cell a) : (Q i).past p ≤ 6 * u * K * 2 ^ r := by + apply (Nat.cast_le (α := ℝ)).mp + calc + _ ≤ ((K : ℝ) * (3 * u)) * (2 : ℝ) ^ (r + 1) := hb.past _ hcap p + _ = _ := by push_cast; ring + refine ⟨same, hs.trans (Nat.mul_le_mul_left K hS), + (hb.drop_budget _ 0).mono le_rfl le_rfl (by gcongr; norm_num), hx.trans ?_, hs, hcap, hpast, tk⟩ + calc + _ ≤ ρ * ((d : ℝ) * (3 * M : ℕ)) + C * (d * (wd x + wd y : ℕ) + ρ * d * M) := + add_le_add (mul_le_mul_of_nonneg_left hX hp) (mul_le_mul_of_nonneg_left hZ hc) + _ = _ := by unfold d; push_cast; ring + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end + +/- +# Addressing the exterior stacks after contraction + +All bits of a stack stay together. The block coordinate is common +and linear. Slot numbers may change with the summand, but they are +relative to the *original* exterior station. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +open Finset + +open scoped Classical in +theorem Preserves.code {F T : Type} {x y : Wire} {L : Fringe x y T} {h a u z K : ℕ} + {G : HostNet F L h u} {Q : HostNet F L a z} + (p : G.Preserves Q) (size : Q.seats ≤ K * G.seats) : + ∃ f : Q.V ↪ G.V × Fin (K * 2 ^ (h - a)), ∀ t, (f (Q.park t).1).1 = (G.park t).1 := by + obtain ⟨_, _, _, ⟨m, hm, _⟩, B, _, e, he⟩ := p + by_cases hn : Nonempty G.V + swap + · let f : Q.V ↪ G.V × Fin (K * 2 ^ (h - a)) := + ⟨fun v => (hn ⟨(e v).1⟩).elim, fun v _ _ => (hn ⟨(e v).1⟩).elim⟩ + exact ⟨f, fun t => (hn ⟨(G.park t).1⟩).elim⟩ + have ha : a ≤ h := by + have ht := Fintype.card_le_of_surjective m hm + simpa only [card_cell, Nat.pow_le_pow_iff_right (by decide : 1 < 2)] using ht + have lim : Fintype.card B ≤ K * 2 ^ (h - a) := by + unfold seats at size + rw [Fintype.card_congr e, Fintype.card_prod, show (2 : ℕ) ^ h = 2 ^ (h - a) * 2 ^ a by + rw [← pow_add, Nat.sub_add_cancel ha]] at size + have hv : 0 < Fintype.card G.V * 2 ^ a := by + exact Nat.mul_pos (Fintype.card_pos_iff.mpr hn) (by positivity) + apply Nat.le_of_mul_le_mul_left _ hv + simpa only [mul_assoc, mul_left_comm, mul_comm] using size + obtain ⟨g⟩ : Nonempty (B ↪ Fin (K * 2 ^ (h - a))) + := Function.Embedding.nonempty_of_card_le (by simpa) + exact ⟨e.toEmbedding.trans ((Function.Embedding.refl _).prodMap g), he⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Packing Finset + +open scoped Classical in +/-- Reindexes `((Cell h × Fin u) × Outer x y)` and `Outer (copies x (2 ^ h * u)) (copies y (2 ^ +h * u))` by an equivalence. -/ +def bit (h u : ℕ) (x y : Wire) : + ((Cell h × Fin u) × Outer x y) ≃ Outer (copies x (2 ^ h * u)) (copies y (2 ^ h * u)) := + ((ordinal h u).prodCongr (.refl _)).trans <| + (Equiv.prodSumDistrib _ _ _).trans ((Diagonal.port x _).symm.sumCongr (Diagonal.port y _).symm) + +variable {F : Type} [Field F] {x y : Wire} {h u a z K : ℕ} (G : Diagram F x y) + +open scoped Classical in +theorem start_locate (side : Bool) (i : Outer x y) (s : Cell h) (t : Fin u) : + locate G (ordinal h u) side (portEnd (start G h u).diagram (bit h u x y ((s, t), i))) + = ((portEnd G i, side), s) := by + cases i with + | inl i => + let q := (Diagonal.port x (2 ^ h * u)) ((Diagonal.port x (2 ^ h * u)).symm ((ordinal h u) (s, + t), i)) + change (((G.src.symm (.inl q.2)).1, side), ((ordinal h u).symm q.1).1) = _ + simp [q, portEnd] + | inr i => + let q := (Diagonal.port y (2 ^ h * u)) ((Diagonal.port y (2 ^ h * u)).symm ((ordinal h u) (s, + t), i)) + change (((G.dst.symm (.inl q.2)).1, side), ((ordinal h u).symm q.1).1) = _ + simp [q, portEnd] + +open scoped Classical in +theorem start_far (i : Outer x y) (s : Cell h) (t : Fin u) : + (start G h u).units.place (portEnd (start G h u).diagram (bit h u x y ((s, t), i))) = + ((portEnd G i, false), s) := + start_locate G false i s t + +open scoped Classical in +theorem start_park (i : Outer x y) (s : Cell h) (t : Fin u) : + (start G h u).park (bit h u x y ((s, t), i)) = ((portEnd G i, true), s) := + start_locate G true i s t + +variable (Q : HostNet F (fringe (copies x (2 ^ h * u)) (copies y (2 ^ h * u))) a z) + +open scoped Classical in +/-- The data for the holders construction, including `block`, `onto`, `host`, `core`, `code`. -/ +structure Holders (K : ℕ) where + /-- The `Holders` component of type `Cell h →ₗ[ZMod 2] Cell a`. -/ + block : Cell h →ₗ[ZMod 2] Cell a + onto : Function.Surjective block + /-- The `Holders` component of type `Outer x y → Cell h → Q.V`. -/ + host : Outer x y → Cell h → Q.V + /-- The `Holders` component of type `Outer x y → Cell h → Q.V`. -/ + core : Outer x y → Cell h → Q.V + /-- The encoding map carried by `Holders`, with type `Q.V ↪ (G.V × Bool) × Fin (K * 2 ^ (h - + a))`. -/ + code : Q.V ↪ (G.V × Bool) × Fin (K * 2 ^ (h - a)) + park : ∀ i s t, Q.park (bit h u x y ((s, t), i)) = (host i s, block s) + tip : ∀ i s t, Q.units.place (portEnd Q.diagram (bit h u x y ((s, t), i))) = (core i s, block s) + original : ∀ i s, (code (host i s)).1 = (portEnd G i, true) + +open scoped Classical in +theorem holders (hu : 0 < u) (same : (start G h u).Preserves Q) + (size : Q.seats ≤ K * (start G h u).seats) : Nonempty (Holders G Q K) := by + obtain ⟨code, hcode⟩ := same.code size + obtain ⟨o, ho, ht, ⟨b, hb, he⟩, _⟩ := same + let core i s := (o ((portEnd G i, false), s)).1 + let host i s := (o ((portEnd G i, true), s)).1 + have park i s t : Q.park (bit h u x y ((s, t), i)) = (host i s, b s) := by + rw [ho, Function.comp_apply, start_park] + exact Prod.ext rfl (he _) + have tip i s t : Q.units.place (portEnd Q.diagram (bit h u x y ((s, t), i))) = (core i s, b s) + := by + rw [ht, show (start G h u).units.place _ = _ from start_locate G false i s t] + exact Prod.ext rfl (he _) + refine ⟨⟨b, hb, host, core, code, park, tip, fun i s => ?_⟩⟩ + have eq := hcode (bit h u x y ((s, ⟨0, hu⟩), i)) + rw [park, start_park] at eq + exact eq + +omit [Field F] in +open scoped Classical in +private theorem original_names (w : G.V) : + (univ.filter fun i : Outer x y => portEnd G i = w).card ≤ G.arity w := by + have ha := site_arity G id w + rw [port_load] at ha + simp only [Function.id_comp, push, sum_boole, id_eq, sum_ite_eq', mem_univ, ite_true] at ha + exact_mod_cast le_trans (le_add_of_nonneg_right (Nat.cast_nonneg (α := ℝ) _)) ha.ge + +omit [Field F] in +open scoped Classical in +theorem Holders.names (p : Holders G Q K) (ht : G.Trivalent) (v : Q.V) : + (univ.filter fun i : Outer x y => ∃ s, p.host i s = v).card ≤ 3 := by + let w := (p.code v).1.1 + have sub : (univ.filter fun i : Outer x y => ∃ s, p.host i s = v) ⊆ + univ.filter (fun i => portEnd G i = w) := by + intro i hi + obtain ⟨s, h⟩ := (mem_filter.mp hi).2 + exact mem_filter.mpr ⟨mem_univ _, congrArg Prod.fst ((p.original i s).symm.trans + (congrArg (fun v => (p.code v).1) h))⟩ + refine (card_le_card sub).trans (le_trans ?_ (ht w)) + exact original_names G w + +variable {G Q} {k : ℕ} (p : Holders G Q K) + +open scoped Classical in +theorem Holders.pair (i : Outer x y) (s : Cell h) (t : Fin u) : + let e := bit h u x y ((s, t), i) + (start G h u).tip e = (portEnd G i, false) ∧ Q.tip e = p.core i s := + ⟨congrArg Prod.fst (start_locate G false i s t), congrArg Prod.fst (p.tip i s t)⟩ + +open scoped Classical in +/-- All copies of one original input have a short menu of core sites. -/ +theorem Holders.reach (hu : 0 < u) (tk : (start G h u).Tracks Q k) (i : Outer x y) : + (univ.image (p.core i)).card ≤ k * 2 ^ (h - a) := by + refine (card_le_card ?_).trans (tk.2 (portEnd G i, false)) + intro v hv + obtain ⟨s, _, rfl⟩ := mem_image.mp hv + exact (HostNet.mem_reach _ _).mpr ⟨_, p.pair i s ⟨0, hu⟩⟩ + +open scoped Classical in +/-- At most three original exterior names can originate at each old site. -/ +theorem Holders.origins (hg : G.Trivalent) (hu : 0 < u) (tk : (start G h u).Tracks Q k) + (v : Q.V) : + (univ.filter fun i : Outer x y => ∃ s, p.core i s = v).card ≤ 3 * k := by + let names (w : (start G h u).V) := univ.filter fun i : Outer x y => portEnd G i = w.1 + have bound w : (names w).card ≤ 3 := (original_names G w.1).trans (hg _) + have sub : (univ.filter fun i : Outer x y => ∃ s, p.core i s = v) ⊆ + (Q.reach (start G h u) v).biUnion names := by + intro i hi + obtain ⟨s, hs⟩ := (mem_filter.mp hi).2 + have he := p.pair i s ⟨0, hu⟩ + have hit : (portEnd G i, false) ∈ Q.reach (start G h u) v := + (HostNet.mem_reach _ _).mpr ⟨_, he.2.trans hs, he.1⟩ + exact mem_biUnion.mpr ⟨_, hit, mem_filter.mpr ⟨mem_univ _, rfl⟩⟩ + refine (card_le_card sub).trans (card_biUnion_le.trans ((sum_le_sum (fun q _ + => bound q)).trans ?_)) + rw [sum_const, Nat.nsmul_eq_mul, mul_comm] + exact Nat.mul_le_mul_left _ (tk.1 v) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Encoded.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Encoded.lean new file mode 100644 index 0000000000..5e35b56f34 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Encoded.lean @@ -0,0 +1,642 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Bounds +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Observed +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Exterior.Fields +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Plan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold + +/-! # Specialization of a sorting-based descent to exceptional widths -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Filter + +/-- The compiler uses full-length sorting gates on ordinary records and +cheap short tables. Its cost counts every port, including those of sorts. -/ +def Compilation (F : Type) [Field F] : Prop := + ∃ K : ℕ, ∃ a : ℝ, 0 < a ∧ ∀ κ : ℝ, 0 < κ → + ∀ᶠ w : ℕ in atTop, ∀ (x y : Wire) (k : Val x → Val y → F) (v M : ℕ), + Net F x y k v → v + wd x + wd y ≤ M → 2 ^ w ≤ M → + (M : ℝ) ≤ (2 ^ w : ℕ) ^ (21 / 20 : ℝ) → + ∃ d u s : ℕ, 1 ≤ d ∧ (d : ℝ) ≤ (2 ^ w : ℕ) ^ κ ∧ + Wide F u (Allowed F w) (copies x d) (copies y d) (power k d) s ∧ + (s : ℝ) ≤ K * d * ((M : ℝ) * (w : ℝ) ^ (-a) + (wd x + wd y : ℕ)) + +-- Ordinary sorting on a polylogarithmic number of address bits is +-- affordable on the same exceptional sequence as the full-length sorts. +private theorem short_cost {ε : ℝ} (he : 0 < ε) : + ∀ᶠ w : ℕ in atTop, ((2 + (Nat.clog 2 w) ^ 3) ^ 2 : ℕ) ≤ (w : ℝ) ^ ε := by + let C := 1 + 1 / Real.log 2 + have h2 : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hc : 0 < C := by unfold C; positivity + have hlog := Real.tendsto_log_atTop.comp tendsto_natCast_atTop_atTop + have hg := (isLittleO_log_rpow_rpow_atTop 6 he).const_mul_left ((2 + C ^ 3) ^ 2) + filter_upwards [eventually_gt_atTop 1, hlog.eventually_ge_atTop 1, + tendsto_natCast_atTop_atTop.eventually hg.eventuallyLE] with w hw hp hh + change 1 ≤ Real.log (w : ℝ) at hp + have hs : (Nat.clog 2 w : ℝ) ≤ C * Real.log w := by + have hn : (2 : ℝ) ^ (Nat.clog 2 w).pred ≤ w := by + exact_mod_cast (Nat.pow_pred_clog_lt_self 2 hw).le + have hl := Real.log_le_log (by positivity) hn + rw [Real.log_pow] at hl + have := (le_div_iff₀ h2).mpr hl + have heq : (Nat.clog 2 w : ℝ) = (Nat.clog 2 w).pred + 1 := by + exact_mod_cast (Nat.succ_pred_eq_of_pos (Nat.clog_pos (by decide : 1 < 2) hw)).symm + rw [heq, show C * Real.log w = Real.log w + Real.log w / Real.log 2 by unfold C; ring] + linarith + rw [show (6 : ℝ) = (6 : ℕ) from rfl, Real.rpow_natCast, + Real.norm_of_nonneg (Real.rpow_nonneg (Nat.cast_nonneg _) _)] at hh + push_cast + calc + _ ≤ (2 * (Real.log w) ^ 3 + (C * Real.log w) ^ 3) ^ 2 := by + have ht : 1 ≤ (Real.log w) ^ 3 := one_le_pow₀ hp + gcongr; linarith + _ = (2 + C ^ 3) ^ 2 * (Real.log w) ^ 6 := by ring + _ ≤ _ := (le_abs_self _).trans hh + +private theorem cost {K d M e s v w a : ℝ} + (hd : 0 ≤ d) (hM : 0 ≤ M) (he : 0 ≤ e) (hw : 1 ≤ w) (ha : 0 < a) + (hbig : K + 1 ≤ w ^ (a / 16)) (hc : s ≤ K * d * (M * w ^ (-a) + e)) (hv : v + ≤ w ^ (a / 16) * s) : + v + d * e ≤ d * (M * w ^ (-(a / 2)) + e * w ^ (a / 2 / 4)) := by + have hu : 1 ≤ w ^ (a / 16) := Real.one_le_rpow hw (by linarith) + have hw' : 0 < w := zero_lt_one.trans_le hw + let u := w ^ (a / 16) + let S := d * (M * w ^ (-a) + e) + have hS : 0 ≤ S := by unfold S; positivity + have hex : d * e ≤ S := mul_le_mul_of_nonneg_left (le_add_of_nonneg_left (by positivity)) hd + have hs : s ≤ K * S := by rwa [mul_assoc] at hc + have hprod : u * u = w ^ (a / 2 / 4) := by unfold u; rw [← Real.rpow_add hw']; congr 1; ring + have hpow : w ^ (a / 2 / 4) * w ^ (-a) ≤ w ^ (-(a / 2)) := by + rw [← Real.rpow_add hw'] + exact Real.rpow_le_rpow_of_exponent_le hw (by linarith) + calc + _ ≤ u * (K * S) + u * S := add_le_add (hv.trans (by gcongr)) (hex.trans (le_mul_of_one_le_left + hS hu)) + _ = u * (K + 1) * S := by ring + _ ≤ u * u * S := by gcongr + _ = d * (M * (w ^ (a / 2 / 4) * w ^ (-a)) + e * w ^ (a / 2 / 4)) + := by rw [hprod]; unfold S; ring + _ ≤ _ := by gcongr + +/-- A single compiled graph yields both versions of the descent theorem +at the same length and with the same exponent. -/ +theorem descent {F : Type} [Field F] (compile : ¬Tagged.Hard F → Compilation F) : + Diagonal.Descent F (Processor.Cheap F 50000 2) := by + intro bad + obtain ⟨K, a, ha, h⟩ := compile bad + let C := 4 + 10 ^ 12 * K + refine ⟨C, by unfold C; omega, a / 2, half_pos ha, fun κ hκ => ?_⟩ + have hp : 0 < a / 16 := by linarith + have large := ((tendsto_rpow_atTop hp).comp tendsto_natCast_atTop_atTop).eventually_ge_atTop ((C + : ℝ) + 1) + refine ((frequent_tags bad hp).and_eventually ((eventually_ge_atTop 64).and + (large.and ((short_cost hp).and (h κ hκ))))).mono ?_ + rintro w ⟨⟨m, tag, cheap⟩, hw, hlarge, hshort, g⟩ + dsimp only + intro x y k v M hv hm hn hM + obtain ⟨d, u, s, hd, hd', network, hs⟩ := g x y k v M hv hm hn hM + let e := wd x + wd y + have hw' : 1 ≤ (w : ℝ) := by exact_mod_cast (show 1 ≤ w by omega) + have hC : 1 ≤ (w : ℝ) ^ (a / 16) := Real.one_le_rpow hw' hp.le + obtain ⟨⟨r, ht, hr⟩, s', hs', hsnet⟩ := expand hw hC tag cheap hshort network + have hb : (10 ^ 12 * s : ℕ) ≤ (C : ℝ) * d * ((M : ℝ) * (w : ℝ) ^ (-a) + e) := by + have hl : (10 : ℝ) ^ 12 * K ≤ C := by unfold C; push_cast; linarith + rw [Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat] + calc + _ ≤ 10 ^ 12 * ((K : ℝ) * d * ((M : ℝ) * (w : ℝ) ^ (-a) + e)) := by gcongr + _ = (10 ^ 12 * (K : ℝ)) * d * ((M : ℝ) * (w : ℝ) ^ (-a) + e) := by ring + _ ≤ _ := by gcongr + constructor + · refine ⟨d, r + d * e, hd, hd', ⟨r, ht, rfl⟩, ?_⟩ + rw [Nat.cast_add, Nat.cast_mul] + exact cost (by positivity) (by positivity) (by positivity) hw' ha hlarge hb hr + · refine ⟨d, 2 ^ (w / 2), s', hd, hd', arity_cap w, hsnet, ?_⟩ + refine ((Nat.cast_le.mpr hs').trans hb).trans ?_ + gcongr; linarith + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Recovering the lane and ordinal of each bundle from its short record -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly PackRows Coloring + +variable {F : Type} {x y : Wire} {S : Scheme F} + +open Classical in +/-- In the case `some (c, s, j)`, this construction gives `some (Fin.natAdd _ c, Exterior.prior +D src c s * D.b + j.val)`. -/ +def Dimensions.position (D : Dimensions) (A : Pattern F S.d S.k S.e) (src : D.Source) + (h : Fintype.card (Parts.Unit A D.z) ≤ D.u) (q : Parts.Unit A D.z) : + Option (Fin (D.PortCount S) × ℕ) := + match src (Parts.number _ _ h q) with + | some (c, s, j) => some (Fin.natAdd _ c, Exterior.prior D src c s * D.b + j.val) + | none => (A.inner q.1.2).map (fun t => (Fin.castAdd D.d t.1, A.innerPrior t.1 t.2)) + +namespace Assignment + +variable [Field F] {D : Dimensions} {G : Diagram F x y} + (t : Assignment D S G) (hw : t.Fits) + +open Classical in +theorem coordinate_inj {a b : Endpoints t.inventory} + (h₁ : a.1 = b.1) (h₂ : a.2.1 = b.2.1) (h₃ : t.coordinate hw a = t.coordinate hw b) : + a = b := by + rcases a with ⟨i, j, a⟩ + rcases b with ⟨k, l, b⟩ + change i = k at h₁ + change j = l at h₂ + subst k; subst l + exact congrArg (fun x => (⟨i, j, x⟩ : Endpoints t.inventory)) ((t.index hw i j).injective h₃) + +open Classical in +theorem coordinate_equiv (a : units S t.rows D.z) : + t.coordinate hw (t.pieces.equiv a) = + Parts.number _ _ (t.pieces.fits hw.room a.1 a.2.1) a.2.2 := by + obtain ⟨i, j, q⟩ := a + change Parts.number _ _ (t.pieces.fits hw.room i j) ((t.pieces.locate i j).symm (t.pieces.locate + i j q)) = _ + rw [Equiv.symm_apply_apply] + +variable {s : B S.m → B S.h → D.Source} (hs : t.Registered hw s) + +include hs in +open Classical in +private theorem unmarked (q : Endpoints t.inner.inventory) : + s q.1 q.2.1 (t.coordinate hw (extendL _ t.outerCount q)) = none := by + cases he : s q.1 q.2.1 (t.coordinate hw (extendL _ t.outerCount q)) with + | none => rfl + | some x => + rcases x with ⟨c, b, k⟩ + obtain ⟨i, hl, _, hk⟩ := (hs ..).mp he + have hpos : extendL _ t.outerCount q = t.endpoint i b k := + t.coordinate_inj hw (congrArg Prod.fst hl.symm) (congrArg Prod.snd hl.symm) hk.symm + exact (channels_disjoint _ _ q _ (congrArg (fun a => a.2.2.1) hpos)).elim + +include hs in +open Classical in +theorem position_eq (hc : Exterior.Accurate D t.loc t.lane s) (q : units S t.rows D.z) : + D.position (S := S) (pattern S t.rows q.1 q.2.1) (s q.1 q.2.1) + (t.pieces.fits hw.room q.1 q.2.1) q.2.2 = + some ((t.pieces.equiv q).2.2.1, (t.pieces.equiv q).2.2.2.val) := by + unfold Dimensions.position + rw [← t.coordinate_equiv hw q] + rcases t.post.unit_cases D.zpos q with h | ⟨i, b, rfl⟩ + · let a : outer S t.rows D.z := ⟨q, h⟩ + obtain ⟨⟨⟨i, b⟩, k⟩, he⟩ := (Exterior.point t.loc t.lane D.b).surjective (t.external a) + have hu : t.pieces.equiv q = t.endpoint i b k := + (t.post.pieces_outer _ _ _ _ a).trans (congrArg (extendR _ _) he.symm) + have hl : t.loc i b = (q.1, q.2.1) := (congrArg (fun j => (j.1, j.2.1)) hu).symm + have hm := (hs q.1 q.2.1 _ _ b k).mpr ⟨i, hl, rfl, rfl⟩ + rw [hu, hm] + have ho := hc.point_slot t.inject_names i b k + rw [hl] at ho + exact congrArg some (Prod.ext (congrArg (fun a => Fin.natAdd _ (t.lane a i)) + (congrArg Prod.fst hl.symm)) ho.symm) + · have hu : t.pieces.equiv (t.post.unitOf D.zpos i b) = + extendL _ _ (t.inner.point (i, b)) := t.post.pieces_inner .. + rw [hu] + have hm := t.unmarked hw hs (t.inner.point (i, b)) + change s (t.post.unitOf D.zpos i b).1 (t.post.unitOf D.zpos i b).2.1 _ = none at hm + rw [hm] + change ((S.pattern t.rows (t.post.span i b).1).inner (t.post.stub i b)).map _ = _ + rw [t.post.inner_spec D.zpos] + exact congrArg some (Prod.ext rfl (t.post.channels_prior D.zpos i b).symm) + +end Assignment +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # A dictionary for the short per-host descriptions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Coloring PackRows + +variable {F : Type} {x y : Wire} + +namespace Dimensions +variable (D : Dimensions) (S : Scheme F) + +open Classical in +/-- Invert the local ordinal map. Outside a valid record the value +is immaterial; choose zero if no input bundle has this ordinal. -/ +def lookupSlot (P : Pattern F S.d S.k S.e) (a : D.Source) (s : Fin (D.PortCount S)) (k : ℕ) : ℕ := + if hh : Fintype.card (Parts.Unit P D.z) ≤ D.u then + if h : ∃ i, D.position (S := S) P a hh i = some (s, k) then + (Parts.number P D.z hh h.choose).val else 0 + else 0 + +open Classical in +/-- Builds `PackRows.Descriptor (2 ^ S.h) (D.PortCount S) S.ℓ where len j` with the specified +`len`, `label`, `slot`. -/ +def describe (label : B S.h → B S.ℓ) (src : B S.h → D.Source) : + PackRows.Descriptor (2 ^ S.h) (D.PortCount S) S.ℓ where + len j := Fin.append (S.decode (label j)).innerCount (Exterior.countAt D (src j)) + label j := keys _ (label j) + slot j := D.lookupSlot S (S.decode (label j)) (src j) + +end Dimensions + +namespace Assignment +variable [Field F] {D : Dimensions} {S : Scheme F} {G : Diagram F x y} + (t : Assignment D S G) (hw : t.Fits) {src : B S.m → B S.h → D.Source} + (hs : t.Registered hw src) (hc : Exterior.Accurate D t.loc t.lane src) + +include hc in +open Classical in +theorem describe_len (i : B S.m) : + (D.describe S (t.rows i).2 (src i)).len = t.inventory i := by + funext j k + change Fin.append (S.decode ((t.rows i).2 j)).innerCount (Exterior.countAt D (src i j)) k = + Fin.append (t.inner.inventory i j) (t.outerCount i j) k + induction k using Fin.addCases with + | left k => rw [Fin.append_left, Fin.append_left]; exact (t.post.channels_count D.zpos i j k).symm + | right k => rw [Fin.append_right, Fin.append_right]; exact hc.countAt t.inject_names i j k + +include hs hc in +open Classical in +theorem describe_slot (i : B S.m) (j : B S.h) (s : Fin (D.PortCount S)) + (k : Fin (t.inventory i j s)) : + (D.describe S (t.rows i).2 (src i)).slot j s k.val = (t.index hw i j ⟨s, k⟩).val := by + let P := pattern S t.rows i j + let e := t.pieces.locate i j + have hh : Fintype.card (Parts.Unit P D.z) ≤ D.u := t.pieces.fits hw.room i j + have ok (a : Parts.Unit P D.z) : + D.position (S := S) P (src i j) hh a = some (s, k.val) ↔ e a = ⟨s, k⟩ := by + have he := t.position_eq hw hs hc ⟨i, j, a⟩ + change D.position P (src i j) hh a = some ((e a).1, (e a).2.val) at he + rw [he, Option.some.injEq, Prod.mk.injEq] + constructor + · rintro ⟨h₁, h₂⟩ + exact Sigma.ext h₁ ((Fin.heq_ext_iff (congrArg (t.inventory i j) h₁)).mpr h₂) + · intro h; rw [h]; exact ⟨rfl, rfl⟩ + have found : ∃ a, D.position (S := S) P (src i j) hh a = some (s, k.val) := + ⟨e.symm ⟨s, k⟩, (ok _).mpr (e.apply_symm_apply _)⟩ + change D.lookupSlot S P (src i j) s k.val = _ + rw [Dimensions.lookupSlot, dite_eq_left hh, dite_eq_left found, + e.eq_symm_apply.mpr ((ok _).mp found.choose_spec)] + rfl + +end Assignment +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- # Dyadic row and bin capacities for a batch recipe -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Recipe +variable {F : Type} [Field F] (P : Recipe F) (w J z R Q V d T : ℕ) + (hQ : 0 < Q * J) (hV : 0 < V * J) (hh : Q * J ≤ P.blocks R J + 1) + (hz : 0 < z) (hv : 2 ^ (V * J) ∣ z) + +private theorem two_half (i : ℕ) (hi : 0 < i) : 2 * 2 ^ (i - 1) = 2 ^ i := by + rw [← pow_succ', Nat.sub_add_cancel hi] + +/-- One budget unit is one bit of the total incidence allowance. -/ +def dimensions : Dimensions where + h := P.blocks R J + b := P.b ^ J + q := 2 ^ (Q * J) + u := 2 ^ (Q * J - 1) * P.b ^ J + r := V * J - 1 + p := z / 2 ^ (V * J) + K := 512 * T / (2 ^ (V * J - 1) * w) + 1 + d := d + n := 2 ^ (P.blocks R J + 1 - Q * J) + a := 3 * w + e := 2 * w + width := by rw [← mul_assoc, two_half _ hQ] + cover := by rw [← pow_add, Nat.sub_add_cancel hh, pow_succ'] + bpos := pow_pos P.b_pos _ + qpos := Nat.two_pow_pos _ + ppos := Nat.div_pos (Nat.le_of_dvd hz hv) (by rw [← two_half _ hV]; positivity) + +local notation "D" => dimensions P w J z R Q V d T hQ hV hh hz hv + +theorem dimensions_z : (D).z = z := by + change 2 * 2 ^ (V * J - 1) * (z / 2 ^ (V * J)) = z + rw [two_half _ hV, Nat.mul_div_cancel' hv] + +theorem dimensions_copies : (D).copies = P.batch R J z := by + unfold Dimensions.copies + rw [dimensions_z] + rfl + +theorem dimensions_rows : 2 * (D).v = 2 ^ (V * J) := two_half _ hV + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Recipe +end + +/- # Reading the exterior decisions of all bins -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Assignment +open Packing Coloring PackRows Assembly + +variable {F : Type} [Field F] {x y : Wire} {D : Dimensions} {S : Scheme F} {G : Diagram F x y} + (t : Assignment D S G) (hw : t.Fits) + +open scoped Classical in +/-- Every active exterior row has an exterior channel and a +representative stack on that channel. -/ +theorem owner_location {i : D.Addr} {j : Stack.Outer x y} + (h : (t.descriptor hw).owner i = some j) : + ∃ (r : PortRows t.inventory D.u) (s : Cell D.h), (t.layout hw).portLoc r = i ∧ + (t.loc j s).1 = r.1 ∧ r.2.1 = Fin.natAdd (2 * 2 ^ S.d) (t.lane r.1 j) := by + obtain ⟨s, hs⟩ := ((t.descriptor hw).owner_eq i j).mp h + let e := t.endpoint j s ⟨0, D.bpos⟩ + let r := portRow t.inventory D.u e + have he : (t.layout hw).portLoc r = i := + ((t.layout hw).locate e).symm.trans ((t.placement hw j s _).1.trans hs) + exact ⟨r, s, he, rfl, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Assignment + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Packing Coloring PackRows Assembly + +variable {F X Z : Type} [Field F] {x y : Wire} {D : Dimensions} {S : Scheme F} {G : Diagram F x y} + +omit [Field F] in +open scoped Classical in +private theorem lane_eq (j : Fin (D.PortCount S)) (c : Fin D.d) : + D.exteriorLane S j = some c ↔ j = Fin.natAdd (2 * 2 ^ S.d) c := by + unfold Dimensions.exteriorLane + split_ifs <;> simp [Fin.ext_iff] <;> omega + +open scoped Classical in +/-- The common bin computation supplies both exterior checks. A long +name is needed only once per channel, regardless of the stack count. -/ +theorem Screen.observed (Q : Screen D S x y X) (t : Assignment D S G) (hw : t.Fits) (hc : + D.CodeFits S) + {user : D.Extras Z} {sd : B S.m → Z → Bool} {ext : B S.m → Fin D.d → D.Names → Bool} + {rows : B S.m → B S.h → D.Source} (registered : t.Registered hw rows) + (flags : ∀ i, user (sd i) = Exterior.program D (rows i)) + (name : ∀ j s, ext (t.loc j s).1 (t.lane (t.loc j s).1 j) = Q.names j) + (v : X → Bool) (h : t.Observed hw hc user sd ext (v ∘ Q.tape)) : Q.Flags t hw hc v := by + let pos := (t.layout hw).portLoc + let bit i b := (v ∘ Q.tape) (D.userBit S i b) + let ord (r : PortRows t.inventory D.u) := r.2.2.castLE (ports_le hw.position r.1 r.2.1) + have get (r : PortRows t.inventory D.u) (c : Fin D.d) (he : r.2.1 + = Fin.natAdd (2 * 2 ^ S.d) c) b : + bit (pos r) b = Exterior.program D (rows r.1) c (ord r) b := by + unfold bit pos Dimensions.userBit + rw [h.flags, (lane_eq _ _).mpr he, Option.elim_some, flags] + refine ⟨h.moves, h.format, h.head, ?_, ?_⟩ + · intro i + change Exterior.flag (bit i (.inl ())) _ = _ + cases hi : (t.descriptor hw).owner i with + | none => + have inactive : bit i (.inl ()) = false := by + by_cases hp : i ∈ Set.range pos + · obtain ⟨r, rfl⟩ := hp + cases hl : D.exteriorLane S r.2.1 with + | none => + exact (h.flags r _).trans (by rw [hl]; rfl) + | some c => + have he := (lane_eq _ _).mp hl + rw [get r c he, t.program_active hw registered r c (ord r) he rfl] + exact congrArg Option.isSome hi + · exact h.flags_off _ hp _ + rw [inactive]; rfl + | some j => + obtain ⟨r, s, hp, hl, he⟩ := t.owner_location hw hi + subst i + have active : bit (pos r) (.inl ()) = true := by + rw [get r _ he, t.program_active hw registered r _ (ord r) he rfl, hi]; rfl + rw [active] + apply congrArg some + funext b + rw [h.name, Dimensions.extNames, (lane_eq _ _).mpr he, Option.elim_some] + simpa only [hl] using congrFun (name j s) b + · intro i j hi q + obtain ⟨r, _, rfl, _, he⟩ := t.owner_location hw hi + change Exterior.decode (fun b => bit (pos r) (.inr (q, b))) = _ + simp_rw [get r _ he] + rw [t.program_addr hw registered r _ (ord r) he rfl q hi, Exterior.decode_encode] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Terminal metadata + +Apart from the long names, one short descriptor per host determines +all the data used in its bin. Its decoder can be arbitrary. The +controller that produced these bits is accounted for by the stages. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Coloring + +variable {F Z : Type} {x y : Wire} {D : Dimensions} {S : Scheme F} {A : Format} + +open Classical in +/-- The data for the view construction, including `names`, `rows`, `short`, `long`, `pattern`. -/ +structure View (D : Dimensions) (S : Scheme F) (x y : Wire) (A : Format) (Z : Type) where + /-- The indexed names of type `Stack.Outer x y ↪ (D.Names → Bool)`. -/ + names : Stack.Outer x y ↪ (D.Names → Bool) + /-- The indexed rows of type `S.format.pins → A.pins ⊕ Bool`. -/ + rows : S.format.pins → A.pins ⊕ Bool + /-- The `View` component of type `B S.m → Z → A.pins ⊕ Bool`. -/ + short : B S.m → Z → A.pins ⊕ Bool + /-- The `View` component of type `B S.m → Fin D.d → D.Names → A.pins ⊕ Bool`. -/ + long : B S.m → Fin D.d → D.Names → A.pins ⊕ Bool + /-- The `View` component of type `(Z → Bool) → B S.h → B S.ℓ`. -/ + pattern : (Z → Bool) → B S.h → B S.ℓ + /-- The source vertex of each edge. -/ + source : (Z → Bool) → B S.h → D.Source + +namespace View +variable (V : View D S x y A Z) + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def record (a : A.obj) (i : B S.m) : Z → Bool := Sum.elim (A.code a) id ∘ V.short i +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def origins (a : A.obj) (i : B S.m) (b : Fin D.d) := Sum.elim (A.code a) id ∘ V.long i b + +open Classical in +/-- Evaluates `D.describe S (V.pattern t) (V.source t)` at the input `t`. -/ +def code : D.Description S Z := fun t => D.describe S (V.pattern t) (V.source t) +open Classical in +/-- Evaluates `Exterior.program D (V.source t)` at the input `t`. -/ +def user : D.Extras Z := fun t => Exterior.program D (V.source t) + +variable [Field F] {G : Diagram F x y} + +open Classical in +/-- The data for the valid construction, including `rows`, `label`, `source`, `name`. -/ +structure Valid (t : Assignment D S G) (hw : t.Fits) (a : A.obj) : Prop where + rows : S.format.code t.rows = Sum.elim (A.code a) id ∘ V.rows + label : ∀ i, V.pattern (V.record a i) = (t.rows i).2 + source : t.Registered hw (V.source ∘ V.record a) + name : ∀ j s, V.origins a (t.loc j s).1 (t.lane (t.loc j s).1 j) = V.names j + +end View +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- +# Quantitative interface for encoded beat sequences + +Keep the exponent charged to long global names independent of the +terminal block reserve. The exponent charged to short records may +depend on the reserve. No payload passes through the control stages. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Filter + +variable {F : Type} [Field F] {x y : Wire} + +/-- The quantity computed by `M * 2 ^ D.h * 2 ^ (e * J)`. -/ +def Dimensions.shortBudget (D : Dimensions) (M e J : ℕ) := M * 2 ^ D.h * 2 ^ (e * J) +/-- The quantity computed by `M * 2 ^ (D.h - R * J) * 2 ^ (c * J) * w`. -/ +def Dimensions.longBudget (D : Dimensions) (M c R J w : ℕ) + := M * 2 ^ (D.h - R * J) * 2 ^ (c * J) * w + +/-- The data for the transfer construction, including `start`, `stop`, `scale`, `size`, +`labels`. -/ +structure Transfer (G : Diagram F x y) (D : Dimensions) (M C c e R J w : ℕ) where + /-- The initial point of type `Snapshot.{1} F (copies x D.copies) (copies y D.copies)`. -/ + start : Snapshot.{1} F (copies x D.copies) (copies y D.copies) + /-- The `Transfer` component of type `Snapshot.{1} F (copies x D.copies) (copies y D.copies)`. -/ + stop : Snapshot.{1} F (copies x D.copies) (copies y D.copies) + /-- Stores the scale associated with this `Transfer`. -/ + scale : ℕ + /-- The size parameter carried by `Transfer`, with type `ℕ`. -/ + size : ℕ + /-- The label data of type `Finset (Table F)`. -/ + labels : Finset (Table F) + few : labels.card ≤ 2 ^ (w / 4) + small : ∀ a ∈ labels, Processor.arity a ≤ w / 4 + transfer : Transforms F scale (Allowed F w ∪ (labels : Set (Table F))) start stop size + /-- The `Transfer` component of type `start.state`. -/ + first : start.state + /-- The encoding map carried by `Transfer`, with type `start.port.obj`. -/ + code : start.port.obj + encoded : ∀ a b, start.encode first a b = code + power : start.eval first = MatrixExponent.power G.eval D.copies + cost : size + start.port.width + stop.port.width ≤ + D.shortBudget M e J + D.longBudget M c R J w + /-- The `Transfer` component of type `Scheme F`. -/ + scheme : Scheme F + hosts : 2 ^ scheme.m * 2 ^ (R * J) ≤ M * 2 ^ D.h * 2 ^ (c * J) + blocks : scheme.h ≤ (R + c) * J + lanes : scheme.d ≤ c * J + tag : scheme.ℓ ≤ 2 ^ (e * J) + /-- The `Transfer` component of type `Type`. -/ + Z : Type + [finite : Fintype Z] + bits : Fintype.card Z ≤ 2 ^ (e * J) + /-- The `Transfer` component of type `View D scheme x y stop.port Z`. -/ + view : View D scheme x y stop.port Z + correct : ∀ i a b, ∃ t : Assignment D scheme G, + (t.state.X : ℝ) ≤ C * (D.copies : ℝ) * ((1 / 2 : ℝ) ^ J * M + (wd x + wd y : ℕ)) ∧ + (∀ u v, t.state.load u v ≤ (2 ^ (c * J) * D.b * D.z : ℕ)) ∧ + stop.eval i a b = t.state.diagram.eval a b ∧ ∀ hw, view.Valid t hw (stop.encode i a b) + +attribute [instance] Transfer.finite + +/-- Uniform controls for logarithmically many beats. -/ +def Encoded (F : Type) [Field F] : Prop := + ∃ (P : Recipe F) (C c d : ℕ), d ≤ c ∧ + ∀ Q R V : ℕ, c + 2 ≤ Q → Q + 2 * c + 10 ≤ R → R + c + 5 ≤ V → + ∃ e : ℕ, ∀ B : ℕ, 100 * (1 + P.b + V + e) ≤ B → + ∀ᶠ J : ℕ in atTop, + ∀ (w z T : ℕ) (hQ : 0 < Q * J) (hV : 0 < V * J) (hh : Q * J ≤ P.blocks (R + J) J + 1) + (hz : 0 < z) (hv : 2 ^ (V * J) ∣ z), + 2 ^ (B * J) ≤ w → w ≤ 2 ^ (2 * B * J) → + 16 * (2 ^ (Q * J) * P.b ^ J) * z ≤ w → w ≤ 32 * (2 ^ (Q * J) * P.b ^ J) * z → + ∀ (x y : Wire) (G : Diagram F x y) (M : ℕ), Nonempty G.V → G.Trivalent → + Fintype.card G.V + wd x + wd y ≤ M → 2 ^ w ≤ M → + (M : ℝ) ≤ (2 ^ w : ℕ) ^ (21 / 20 : ℝ) → + let D := P.dimensions w J z (R + J) Q V (2 ^ (d * J)) T hQ hV hh hz hv + Nonempty (Transfer G D M C c e R J w) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Interpreting the short and long fields of terminal metadata -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.View + +open Assembly Coloring PackRows + +variable {F Z : Type} [Field F] {x y : Wire} {D : Dimensions} {S : Scheme F} {A : Format} + (V : View D S x y A Z) {G : Diagram F x y} (t : Assignment D S G) (hw : t.Fits) + +open Classical in +/-- Computes the form by the application `A.pair (.wire (.pair (copies x D.copies) (copies y +D.copies)))`. -/ +abbrev form (A : Format) (D : Dimensions) (x y : Wire) := + A.pair (.wire (.pair (copies x D.copies) (copies y D.copies))) + +open Classical in +/-- Builds `Screen D S x y ((form A D x y).pins ⊕ D.Decisions S) where source i` with the +specified `source`, `tape`, `names`. -/ +def screen : Screen D S x y ((form A D x y).pins ⊕ D.Decisions S) where + source i := .inl (.inr (Stack.strips D.h D.b D.z x y ((i.1, i.2.1), i.2.2))) + tape := Sum.inr + names := V.names + +open Classical in +/-- Computes the display by the application `D.decideRows S hn V.code V.user (V.record a) t.rows +(V.origins a) t.inventory hw.position hw.reserve`. -/ +def display (hn : D.CodeFits S) (a : A.obj) := + D.decideRows S hn V.code V.user (V.record a) t.rows (V.origins a) + t.inventory hw.position hw.reserve + +open Classical in +theorem lengths {a : A.obj} (he : V.Valid t hw a) (i : B S.m) : + (V.code (V.record a i)).len = t.inventory i := by + rw [code, he.label] + exact t.describe_len (t.accurate hw he.source) i + +open Classical in +theorem flags (hn : D.CodeFits S) (a : (form A D x y).obj) (he : V.Valid t hw a.1) : + V.screen.Flags t hw hn (Sum.elim ((form A D x y).code a) (V.display t hw hn a.1)) := by + have hl (i) : (V.code (V.record a.1 i)).label = labels S t.rows i := by + rw [code, he.label] + rfl + have hx i j u (k : Fin (t.inventory i j u)) : + (V.code (V.record a.1 i)).slot j u k.val = (t.index hw i j ⟨u, k⟩).val := by + rw [code, he.label] + exact t.describe_slot hw he.source (t.accurate hw he.source) i j u k + have ok := t.observed hw hn V.user (V.record a.1) (V.origins a.1) V.code + (V.lengths t hw he) hl hx + exact V.screen.observed t hw hn he.source (fun _ => rfl) he.name _ ok + +open Classical in +theorem supplied (a : (form A D x y).obj) (b : D.Decisions S → Bool) : + V.screen.supplied t (Sum.elim ((form A D x y).code a) b) = + t.post.toPresentation.exterior a.2.1 a.2.2 := by + funext i + obtain ⟨⟨⟨⟨j, r⟩, k⟩, s⟩, rfl⟩ := (Exterior.ports t.post).surjective i + rw [V.screen.supplied_at] + exact (t.post.toPresentation.exterior_boundary a.2.1 a.2.2 + (Stack.strips D.h D.b D.z x y (((j, r), k), s))).symm + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.View +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Encoding.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Encoding.lean new file mode 100644 index 0000000000..2147c42379 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Encoding.lean @@ -0,0 +1,943 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Elect +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Stack.StartBound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Encoded +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Phase.ResetRate + +/-! +# Size allowance for a replicated transfer + +After J halvings the internal budget contributes at the reduced rate. +Exterior bits are still charged once per copy. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Filter + +/-- The quantity computed by `(C + 1) * (2 ^ (h - J) * k * M + 2 ^ h * k * E)`. -/ +def allowance (C h J k M E : ℕ) : ℕ := + (C + 1) * (2 ^ (h - J) * k * M + 2 ^ h * k * E) + +theorem allowance_value (C h J k M E : ℕ) (hj : J ≤ h) : + (allowance C h J k M E : ℝ) = + (C + 1) * (2 ^ h * k : ℕ) * ((1 / 2 : ℝ) ^ J * M + E) := by + unfold allowance + push_cast + rw [pow_sub₀ (2 : ℝ) (by norm_num) hj, one_div, inv_pow] + ring + +theorem allowance_small (C : ℕ) : + ∀ᶠ w : ℕ in atTop, ∀ h J k M E : ℕ, J ≤ h → E ≤ M → + (M : ℝ) ≤ (2 ^ w : ℕ) ^ (21 / 20 : ℝ) → ((2 ^ h * k : ℕ) : ℝ) ≤ (2 ^ w : ℕ) ^ (1 / 20 : ℝ) → + 10 ^ 38 * allowance C h J k M E ≤ 2 ^ (5 * w / 4) := by + have ht := (tendsto_rpow_atTop (by norm_num : (0 : ℝ) < 1 / 10)).comp + (tendsto_pow_atTop_atTop_of_one_lt (by norm_num : (1 : ℝ) < 2)) + filter_upwards [eventually_ge_atTop 20, ht.eventually_ge_atTop (10 ^ 38 * (C + 1) * 2)] + with w hw hc h J k M E hj hE hM hk + let N := (2 : ℝ) ^ w + have hp : 0 < N := pow_pos (by norm_num) _ + change 10 ^ 38 * ((C : ℝ) + 1) * 2 ≤ N ^ (1 / 10 : ℝ) at hc + simp only [Nat.cast_pow, Nat.cast_ofNat] at hM hk + have hs : (1 / 2 : ℝ) ^ J * M + E ≤ 2 * M := by + have he : (E : ℝ) ≤ M := Nat.cast_le.mpr hE + have hu : (1 / 2 : ℝ) ^ J ≤ 1 := pow_le_one₀ (by norm_num) (by norm_num) + linarith [mul_le_mul_of_nonneg_right hu (Nat.cast_nonneg (α := ℝ) M)] + have hf : (w : ℝ) * (6 / 5 : ℝ) ≤ (5 * w / 4 : ℕ) := by + have he : 6 * w ≤ 5 * (5 * w / 4) := by omega + have hr : 6 * (w : ℝ) ≤ 5 * (5 * w / 4 : ℕ) := by exact_mod_cast he + linarith + have hb : (10 : ℝ) ^ 38 * allowance C h J k M E ≤ (2 : ℝ) ^ (5 * w / 4) := calc + _ ≤ 10 ^ 38 * (((C : ℝ) + 1) * (2 ^ h * k : ℕ) * (2 * M)) + := by rw [allowance_value _ _ _ _ _ _ hj]; gcongr + _ = (10 ^ 38 * ((C : ℝ) + 1) * 2) * (2 ^ h * k : ℕ) * M := by ring + _ ≤ N ^ (1 / 10 : ℝ) * N ^ (1 / 20 : ℝ) * N ^ (21 / 20 : ℝ) := by gcongr + _ = N ^ (6 / 5 : ℝ) := by rw [← Real.rpow_add hp, ← Real.rpow_add hp]; norm_num + _ = (2 : ℝ) ^ ((w : ℝ) * (6 / 5 : ℝ)) := (Real.rpow_natCast_mul (by norm_num) _ _).symm + _ ≤ _ := by rw [← Real.rpow_natCast]; exact Real.rpow_le_rpow_of_exponent_le (by norm_num) hf + exact_mod_cast hb + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- # A polynomial bound for the short control fields -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +theorem Limits.polynomial (L : Limits) (ha : 100 ≤ L.A) (hk : 1 ≤ L.K) + (hs : L.steps ≤ L.A) (ht : L.start.tag ≤ L.A) : + 1 + L.code + (1 + L.steps) * L.small ^ L.K ≤ L.A ^ ((L.K + 3) ^ 5) := by + let X := L.A ^ ((L.K + 3) ^ 2) + have ha' : 0 < L.A := by omega + have hAX : L.A ≤ X := by + simpa using Nat.pow_le_pow_right ha' (show 1 ≤ (L.K + 3) ^ 2 by nlinarith) + have hx : 100 ≤ X := ha.trans hAX + have mono {i j : ℕ} (he : i ≤ j) : X ^ i ≤ X ^ j := Nat.pow_le_pow_right (by omega) he + have hpow : L.A ^ L.K ≤ X := Nat.pow_le_pow_right ha' (by nlinarith) + have he : L.extra ≤ X := calc + _ ≤ (L.A ^ (L.K + 1)) ^ L.K := Nat.pow_le_pow_left + (by rw [pow_succ']; exact Nat.mul_le_mul_right _ (by omega)) _ + _ ≤ X := by rw [← pow_mul]; exact Nat.pow_le_pow_right ha' (by nlinarith) + have htag : L.maxTag ≤ X ^ 3 := calc + _ ≤ X + X * X := Nat.add_le_add (ht.trans hAX) (Nat.mul_le_mul (hs.trans hAX) he) + _ ≤ X ^ 3 := by nlinarith [Nat.mul_le_mul_right (X ^ 2) hx] + have hcode : L.code ≤ X ^ 5 := calc + _ ≤ (1 + X ^ 3) * X := Nat.mul_le_mul (Nat.add_le_add_left htag 1) he + _ ≤ (X ^ 3 + X ^ 3) * X := by gcongr; exact Nat.one_le_pow _ _ (by omega) + _ = 2 * X ^ 4 := by ring + _ ≤ X ^ 5 := by rw [show X ^ 5 = X * X ^ 4 by ring]; gcongr; omega + have hsmall : L.small ≤ X ^ 6 := calc + _ ≤ 4 * X + X ^ 5 + X ^ 3 := by unfold Limits.small; gcongr + _ ≤ 6 * X ^ 5 := by + have := mono (show 3 ≤ 5 by decide) + have := mono (show 1 ≤ 5 by decide) + simp only [pow_one] at this + omega + _ ≤ X ^ 6 := by rw [show X ^ 6 = X * X ^ 5 by ring]; gcongr; omega + have hbig : L.small ^ L.K ≤ X ^ (6 * L.K) := by rw [pow_mul]; gcongr + have hbig' : L.code ≤ X ^ (6 * L.K) := hcode.trans (mono (by omega)) + have hone := Nat.one_le_pow (6 * L.K) X (by omega) + calc + _ ≤ X ^ (6 * L.K) + X ^ (6 * L.K) + (1 + X) * X ^ (6 * L.K) := by + have := hs.trans hAX + gcongr + _ = (3 + X) * X ^ (6 * L.K) := by ring + _ ≤ X ^ 2 * X ^ (6 * L.K) := Nat.mul_le_mul_right _ (by nlinarith) + _ = L.A ^ ((L.K + 3) ^ 2 * (2 + 6 * L.K)) := by unfold X; rw [← pow_add, ← pow_mul] + _ ≤ _ := Nat.pow_le_pow_right ha' (by ring_nf; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- # Padding the initial set of hosts to a power of two -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack + +theorem hostCount {w M : ℕ} (hw : 100 ≤ w) + (hl : 2 ^ w ≤ M) (hu : (M : ℝ) ≤ (2 ^ w : ℕ) ^ (21 / 20 : ℝ)) : + let m := max w (Nat.clog 2 (2 * M)) + m ≤ 3 * w / 2 ∧ 2 ^ m ≤ 4 * M := by + have hw' : (w : ℝ) * (21 / 20 : ℝ) + 1 ≤ (3 * w / 2 : ℕ) := by + have hb : 21 * w + 20 ≤ 20 * (3 * w / 2) := by omega + have : 21 * (w : ℝ) + 20 ≤ 20 * (3 * w / 2 : ℕ) := by exact_mod_cast hb + linarith + have hb : 2 * M ≤ 2 ^ (3 * w / 2) := by + have hb' : (2 : ℝ) * M ≤ (2 : ℝ) ^ (3 * w / 2) := calc + _ ≤ 2 * ((2 : ℝ) ^ w) ^ (21 / 20 : ℝ) := by + simpa only [Nat.cast_pow, Nat.cast_ofNat] + using (mul_le_mul_of_nonneg_left hu (by norm_num : (0 : ℝ) ≤ 2)) + _ = (2 : ℝ) ^ ((w : ℝ) * (21 / 20 : ℝ) + 1) := by + rw [Real.rpow_add (by norm_num), Real.rpow_one, Real.rpow_natCast_mul (by norm_num), + mul_comm] + _ ≤ _ := by + rw [← Real.rpow_natCast] + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) hw' + exact_mod_cast hb' + let m := Nat.clog 2 (2 * M) + have hlo : w < m := (Nat.lt_clog_iff_pow_lt (by decide)).mpr (by have := Nat.two_pow_pos w; omega) + have hhi : m ≤ 3 * w / 2 := (Nat.clog_le_iff_le_pow (by decide)).mpr hb + change max w m ≤ _ ∧ 2 ^ (max w m) ≤ _ + rw [max_eq_right hlo.le] + refine ⟨hhi, ?_⟩ + have hh : 2 ^ (m - 1) < 2 * M := (Nat.lt_clog_iff_pow_lt (by decide)).mp (by omega : m - 1 < m) + rw [show m = (m - 1) + 1 by omega, pow_succ] + omega + +theorem name_exists {x y : Wire} {M w : ℕ} + (size : wd x + wd y ≤ M) (bound : Nat.clog 2 (2 * M) ≤ 3 * w / 2) : + Nonempty (Outer x y ↪ (Fin (2 * w) → Bool)) := by + classical + apply Function.Embedding.nonempty_of_card_le + simp only [Outer, Fintype.card_sum, card_slots, Fintype.card_fun, Fintype.card_fin, + Fintype.card_bool] + exact size.trans ((by omega : M ≤ 2 * M).trans + ((Nat.le_pow_clog (by decide : 1 < 2) (2 * M)).trans + (Nat.pow_le_pow_right (by decide) (by omega)))) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end + +section +/- +# Paying for the last transfer of control records + +The cost per host of long addresses must have an exponent independent +of the reserve. This calculation keeps it separate from the short +record cost per occurrence until after regrouping. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup + +theorem raised {a b J n : ℕ} (hn : n * a ≤ b) : (2 ^ (a * J) : ℕ) ^ n ≤ 2 ^ (b * J) := by + rw [← pow_mul, show a * J * n = (n * a) * J by ring] + exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ hn) + +theorem capacities {M h m t R J k L : ℕ} (ht : t = k + R * J) (hh : t ≤ h) + (hs : 2 ^ m ≤ M * 2 ^ (h - t) * L) : + 2 ^ (m + t) ≤ M * 2 ^ h * L ∧ 2 ^ (m + k) ≤ M * 2 ^ (h - R * J) * L := by + have step (i : ℕ) : 2 ^ (m + i) ≤ M * 2 ^ (h - t + i) * L := by + rw [pow_add, pow_add] + calc + _ ≤ (M * 2 ^ (h - t) * L) * 2 ^ i := Nat.mul_le_mul_right _ hs + _ = _ := by ring + constructor + · simpa only [Nat.sub_add_cancel hh] using step t + · simpa only [show h - t + k = h - R * J by omega] using step k + +theorem expenses {M h m t R J k A L w n i f : ℕ} + (hl : 1000000 ≤ L) (ha : L ≤ A) (ht : t = k + R * J) (hh : t ≤ h) + (hs : 2 ^ m ≤ M * 2 ^ (h - t) * L) + (hn : n ≤ M * 2 ^ h * A) + (hi : i ≤ 100 * A ^ 3 * 2 ^ (m + t) + 100 * L * 2 ^ m * w) + (hf : f ≤ 100 * A ^ 3 * 2 ^ (m + k + (t - k)) + 100 * L * 2 ^ (m + k) * w) : + n + 1000 * (i + f) + f ≤ M * 2 ^ h * A ^ 5 + M * 2 ^ (h - R * J) * L ^ 3 * w := by + obtain ⟨hb, hp⟩ := capacities ht hh hs + have hp' := (Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.le_add_right m k)).trans hp + rw [show m + k + (t - k) = m + t by omega] at hf + let X := M * 2 ^ h + let Y := M * 2 ^ (h - R * J) + let B := 100 * A ^ 3 * (X * A) + 100 * L * (Y * L) * w + have hb' : 2 ^ (m + t) ≤ X * A := hb.trans (Nat.mul_le_mul_left _ ha) + have cost (s : ℕ) (h : s ≤ Y * L) : 100 * A ^ 3 * 2 ^ (m + t) + 100 * L * s * w ≤ B := by + exact Nat.add_le_add (Nat.mul_le_mul_left _ hb') + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ h)) + have hi' := hi.trans (cost _ hp') + have hf' := hf.trans (cost _ hp) + have hA : A ≤ A ^ 4 := by + simpa only [pow_one] using Nat.pow_le_pow_right (show 0 < A by omega) (by decide : 1 ≤ 4) + calc + _ ≤ X * A ^ 4 + 2001 * B := by + have hn' : n ≤ X * A ^ 4 := hn.trans (Nat.mul_le_mul_left _ hA) + omega + _ = X * A ^ 4 * 200101 + Y * L ^ 2 * 200100 * w := by unfold B; ring + _ ≤ X * A ^ 4 * A + Y * L ^ 2 * L * w := by gcongr <;> omega + _ = _ := by unfold X Y; ring + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +end + +/- +# Lengths of control records throughout a sequence of beats + +The loop executes a linear number of phases. Keeping an additional +quadratic number of block bits in reserve absorbs all fixed powers of +the global address width. Those extra bits are removed at the end. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +open Filter +variable {F : Type} [Field F] (P : Recipe F) (K d : ℕ) + +/-- The quantity computed by `20 + P.b + P.n * K + P.H + d`. -/ +def lane := 20 + P.b + P.n * K + P.H + d +/-- The quantity computed by `2 * lane P K d * (K + 3) ^ 5`. -/ +def label := 2 * lane P K d * (K + 3) ^ 5 +/-- The quantity computed by `R + label P K d + 10 * lane P K d`. -/ +def result (R : ℕ) := R + label P K d + 10 * lane P K d + +theorem lane_min : 20 ≤ lane P K d := by unfold lane; omega +theorem lane_label : lane P K d ≤ label P K d := by + unfold label + exact (by omega : _ ≤ 2 * lane P K d).trans (Nat.le_mul_of_pos_right _ (by positivity)) + +theorem dyad {i j : ℕ} (h : i ≤ j) : (2 : ℕ) ^ i ≤ 2 ^ j := Nat.pow_le_pow_right (by decide) h + +theorem mono (J : ℕ) {i j : ℕ} (h : i ≤ j) : (2 : ℕ) ^ (i * J) ≤ 2 ^ (j * J) := + dyad (Nat.mul_le_mul_right _ h) + +theorem power (n k : ℕ) : k ^ n ≤ 2 ^ (k * n) := by + rw [pow_mul] + exact Nat.pow_le_pow_left (Nat.lt_two_pow_self (n := k)).le _ + +private theorem quadratic (k : ℕ) : ∀ᶠ j : ℕ in atTop, k * j ^ 2 ≤ 2 ^ j := by + filter_upwards [replication (κ := 1) zero_lt_one k] with j h + have hh := h (2 ^ j) le_rfl + rw [Real.rpow_one] at hh + exact (pow_le_pow_iff_right₀ (by norm_num : (1 : ℝ) < 2)).mp hh + +/-- The bounds that only need to hold beyond a fixed beat count. -/ +structure Large [Fintype F] (R B J : ℕ) : Prop where + beats : 20 ≤ J + spare : (2 * B + 3) * K ≤ J + factors : 100 + Stack.length F + K + (P.n + label P K d + 2 * B) * J + + P.n * J * K + (K + 1) * (P.blocks (R + J) J + 1) ≤ 2 ^ J + +theorem large [Fintype F] (R B : ℕ) : ∀ᶠ J : ℕ in atTop, Large P K d R B J := by + let c := 100 + Stack.length F + K + (P.n + label P K d + 2 * B) + P.n * K + + (K + 1) * (R + 1 + P.n * (P.H + 5) + 1) + filter_upwards [eventually_ge_atTop 20, eventually_ge_atTop ((2 * B + 3) * K), quadratic c] + with j hj hr h + refine ⟨hj, hr, le_trans ?_ h⟩ + have hj' : j ≤ j ^ 2 := by nlinarith + have hj'' : 1 ≤ j ^ 2 := by omega + have hblocks : P.blocks (R + j) j + 1 ≤ (R + 1 + P.n * (P.H + 5) + 1) * j ^ 2 := by + unfold Recipe.blocks Recipe.group + nlinarith only [Nat.mul_le_mul_left R hj', hj''] + unfold c + nlinarith only [Nat.mul_le_mul_left (K + 1) hblocks, + Nat.mul_le_mul_left (100 + Stack.length F + K) hj'', + Nat.mul_le_mul_left (P.n + label P K d + 2 * B + P.n * K) hj'] + +theorem growth {J : ℕ} (hj : 1 ≤ J) : + 6 * K ^ (P.n * J) * P.b ^ J ≤ 2 ^ (lane P K d * J) ∧ + 4 * 2 ^ (P.n * J * K) ≤ 2 ^ (lane P K d * J) := by + have hm : 3 + K * (P.n * J) + P.b * J ≤ lane P K d * J := by + unfold lane + nlinarith only [hj, Nat.zero_le (P.H * J), Nat.zero_le (d * J)] + constructor + · calc + _ ≤ 2 ^ 3 * 2 ^ (K * (P.n * J)) * 2 ^ (P.b * J) := + Nat.mul_le_mul (Nat.mul_le_mul (by decide) (power _ _)) (power _ _) + _ ≤ _ := by rw [← pow_add, ← pow_add]; exact dyad hm + · rw [show (4 : ℕ) = 2 ^ 2 by decide, ← pow_add] + exact dyad (by nlinarith only [hm, Nat.zero_le (P.b * J)]) + +theorem tolerance {J : ℕ} (hj : 1 ≤ J) (hH : 4 ^ (P.n * (K + 2) + K + 2) ≤ P.H) : + (24 * K * K ^ (P.n * J) * 2 ^ (P.n * J * K) : ℕ) ≤ (1 / 2 : ℝ) ^ J * (2 : ℝ) ^ P.group J := by + have hp : 2 * K * K ^ (P.n * J) * 2 ^ (P.n * J * K) ≤ P.H ^ J := calc + _ ≤ 2 ^ 1 * 2 ^ K * 2 ^ (K * (P.n * J)) * 2 ^ (P.n * J * K) := + Nat.mul_le_mul_right _ (Nat.mul_le_mul + (Nat.mul_le_mul_left _ (Nat.lt_two_pow_self (n := K)).le) (power _ _)) + _ ≤ (4 ^ (P.n * (K + 2) + K + 2)) ^ J := by + rw [← pow_add, ← pow_add, ← pow_add, show (4 : ℕ) = 2 ^ 2 by decide, ← pow_mul, ← pow_mul] + apply dyad + nlinarith only [hj, Nat.mul_le_mul_left K hj, Nat.zero_le (P.n * J)] + _ ≤ _ := Nat.pow_le_pow_left hH _ + refine le_trans ?_ (P.group_room J hj) + have ht : 24 * K * K ^ (P.n * J) * 2 ^ (P.n * J * K) ≤ 12 * P.H ^ J := by + simpa only [← mul_assoc, show 12 * 2 = 24 from rfl] using Nat.mul_le_mul_left 12 hp + exact_mod_cast ht + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +end + +/- # Common limits for the elementary phases -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +variable {F : Type} [Field F] [Fintype F] {x y : Wire} + +/-- The quantity computed by `6 * K ^ (P.n * J) * M * copies`. -/ +def cap (P : Recipe F) (K J M copies : ℕ) := 6 * K ^ (P.n * J) * M * copies + +/-- The limits of type `Limits` for the given inputs. -/ +def limits (P : Recipe F) (K d J M w : ℕ) (S : Setup F x y) : Limits := + ⟨max w (Nat.clog 2 (2 * M)), P.n * J, w, P.group J, K, 2 ^ ((2 * lane P K d) * J), + Stack.initialBudget S M, (1 / 2 : ℝ) ^ J * M * S.count⟩ + +/-- The data for the fit construction, including `large`, `pos`, `room`, `gain`, `height`. -/ +structure Fit (P : Recipe F) (K d R B J M w : ℕ) (S : Setup F x y) : Prop where + large : Large P K d R B J + pos : 1 ≤ K + room : 4 ^ (P.n * (K + 2) + K + 2) ≤ P.H + gain : label P K d + 10 ≤ B + height : S.h = P.blocks (R + J) J + size : S.U = P.b ^ J * S.z + zpos : 0 < S.z + unit : S.U ≤ w + degree : S.d = 2 ^ (lane P K d * J) + names : S.e ≤ 3 * w + capacity : S.cap = cap P K J M S.count + discount : S.discount = P.group J + trivalent : S.G.Trivalent + diagram : Fintype.card S.G.V + wd x + wd y ≤ M + hosts : max w (Nat.clog 2 (2 * M)) ≤ 3 * w / 2 + padding : 2 ^ (max w (Nat.clog 2 (2 * M))) ≤ 4 * M + lower : 2 ^ (B * J) ≤ w + upper : w ≤ 2 ^ (2 * B * J) + +variable {P : Recipe F} {K d R B J M w : ℕ} {S : Setup F x y} +variable (h : Fit P K d R B J M w S) +local notation "Λ" => limits P K d J M w S +local notation "l" => lane P K d +local notation "g" => label P K d +include h + +theorem Fit.factors : 100 + Stack.length F + K + (P.n * J + g * J + 2 * B * J) + + P.n * J * K + (K * (S.h + 1) + (S.h + 1)) ≤ 2 ^ J := by + simpa only [h.height, add_mul, one_mul] using h.large.factors + +theorem Fit.unit_load : (Λ).start.load = 6 * P.b ^ J := by + change 6 * (S.U / S.z) = _ + rw [h.size, Nat.mul_div_cancel _ h.zpos] + +theorem Fit.lanes : 2 ^ J ≤ S.d ∧ S.d ≤ (Λ).A := by + rw [h.degree] + refine ⟨dyad (Nat.le_mul_of_pos_left _ (by have := lane_min P K d; omega)), ?_⟩ + exact mono _ (by omega) + +theorem Fit.headroom : 4 * 2 ^ (g * J) ≤ w := calc + _ = 2 ^ (2 + g * J) := by rw [pow_add]; rfl + _ ≤ _ := (dyad (by + have := Nat.mul_le_mul_right J h.gain + rw [add_mul] at this + have := h.large.beats + omega)).trans h.lower + +theorem Fit.poly : 1 + (Λ).code + (1 + (Λ).steps) * (Λ).small ^ K ≤ 2 ^ (g * J) := by + have hh := h.factors + have hb := h.lanes.1.trans h.lanes.2 + have hp := (Λ).polynomial (by omega) h.pos (by change P.n * J ≤ _; omega) + (by change Stack.length F + 1 ≤ _; omega) + exact hp.trans (Regroup.raised (by unfold label; exact le_of_eq (mul_comm ..))) + +theorem Fit.address : + (Λ).host + K * (S.h + 1) ≤ 2 * w ∧ K ≤ 2 ^ (Λ).r ∧ (Λ).steps * (Λ).r ≤ S.h := by + have ht : P.n * J * P.group J ≤ S.h := by rw [h.height]; exact Nat.le_add_left .. + have hJ : 2 ^ J ≤ 2 ^ (g * J) := dyad (Nat.le_mul_of_pos_left _ + ((lane_min P K d).trans (lane_label P K d) |>.trans' (by decide : 1 ≤ 20))) + have hw := h.headroom + have hh := h.factors + have hhi := h.hosts + have hK : 2 ^ J ≤ 2 ^ P.group J := + dyad (Nat.le_mul_of_pos_left _ (show 0 < P.H + 5 by omega)) + refine ⟨?_, (show K ≤ 2 ^ J by omega).trans hK, ht⟩ + change max w (Nat.clog 2 (2 * M)) + P.n * J * (P.group J + K) + K * (S.h + 1) ≤ 2 * w + rw [mul_add] + omega + +theorem Fit.basic : + 100 + 2 ^ (Λ).r + S.h + Nat.clog 2 (1 + S.U) + 2 ^ S.discount + + K ^ (P.n * J) * (Λ).start.load + S.d ≤ (Λ).A := by + have hj := h.large.beats + have hu : Nat.clog 2 (1 + S.U) ≤ 2 * B * J + 1 := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_succ] + have := h.unit.trans h.upper + have := Nat.two_pow_pos (2 * B * J) + omega + have hr : 2 ^ P.group J ≤ S.d := by + rw [h.degree] + exact mono _ (by unfold lane; omega) + have hb : K ^ (P.n * J)* (Λ).start.load ≤ S.d := by + rw [h.unit_load, h.degree, ← mul_assoc, mul_comm _ 6] + exact (growth P K d (by omega)).1 + have hh := h.factors + have hd := h.lanes.1 + have hs : 5 * S.d ≤ (Λ).A := by + change 5 * S.d ≤ 2 ^ ((2 * l) * J) + rw [show 2 * l * J = l * J + l * J by ring, pow_add, ← h.degree] + exact Nat.mul_le_mul_right _ (by omega) + change 100 + 2 ^ P.group J + _ + _ + _ + _ + _ ≤ _ + rw [h.discount] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +end + +/- +# Uniform headroom through a batch + +Reserve enough space for all incidence histories. Their discounted +mass costs at most one additional copy of the prescribed width error. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +variable {F : Type} [Field F] [Fintype F] {x y : Wire} +variable {P : Recipe F} {K d R B J M w : ℕ} {S : Setup F x y} +variable (h : Fit P K d R B J M w S) +local notation "Λ" => limits P K d J M w S +local notation "l" => lane P K d +local notation "g" => label P K d + +include h + +private theorem loss : + ((24 * K * K ^ (P.n * J) * 2 ^ (P.n * J * K) * M * S.count : ℕ) : ℝ) + ≤ (Λ).σ * (2 : ℝ) ^ P.group J := by + have he := tolerance P K (J := J) (by have := h.large.beats; omega) h.room + rw [Nat.cast_mul, Nat.cast_mul] + calc + _ ≤ ((1 / 2 : ℝ) ^ J * (2 : ℝ) ^ P.group J) * M * S.count := by gcongr + _ = _ := by unfold limits; dsimp only; ring + +theorem Fit.exterior : + S.fringe.Z ≤ (S.count : ℝ) * (wd x + wd y : ℕ) + (Λ).σ := by + have hc : S.cap ≤ 24 * K * K ^ (P.n * J) * 2 ^ (P.n * J * K) * M * S.count := by + rw [h.capacity] + unfold cap + have hk := h.pos + have hK : 6 * K ^ (P.n * J) ≤ 24 * K * K ^ (P.n * J) := Nat.mul_le_mul_right _ (by omega) + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ + (hK.trans (Nat.le_mul_of_pos_right _ (by positivity)))) + have hr : S.fringe.reserve ≤ (Λ).σ := by + change (S.cap : ℝ) / (2 : ℝ) ^ S.discount ≤ _ + rw [h.discount, div_le_iff₀ (by positivity)] + exact (Nat.cast_le.mpr hc).trans (loss h) + change (∑ _ : Stack.Outer S.input S.output, (1 : ℝ)) + _ ≤ _ + refine add_le_add ?_ hr + simp [Stack.Outer, Setup.input, Setup.output, wd_copies, mul_add] + +private theorem history : + (K ^ (P.n * J) : ℕ) * ((Λ).start.mass + (Λ).start.width + (S.fringe.Z + (Λ).σ)) ≤ S.cap := by + have he := h.exterior + have hs : (Λ).σ ≤ (M : ℝ) * S.count := by + have hb : (1 / 2 : ℝ) ^ J ≤ 1 := pow_le_one₀ (by norm_num) (by norm_num) + exact mul_le_mul_of_nonneg_right (mul_le_of_le_one_left (Nat.cast_nonneg _) hb) (by positivity) + have hm : wd x + wd y ≤ M := by have := h.diagram; omega + have hE : (S.count : ℝ) * (wd x + wd y : ℕ) ≤ M * S.count := by rw [mul_comm]; gcongr + have ht : (Λ).start.mass + (Λ).start.width + (S.fringe.Z + (Λ).σ) ≤ 6 * M * S.count := by + change 0 + 3 * (M : ℝ) * S.count + _ ≤ _ + linarith only [he, hE, hs] + rw [h.capacity] + calc + _ ≤ (K ^ (P.n * J) : ℕ) * (6 * (M : ℝ) * S.count) + := mul_le_mul_of_nonneg_left ht (by positivity) + _ = _ := by unfold cap; push_cast; ring + +private theorem slack : + ((K * (K ^ (P.n * J) * (Λ).start.load * S.z) * 2 ^ ((Λ).seats S.h) : ℕ) : ℝ) + ≤ (Λ).σ * (2 : ℝ) ^ P.group J := by + refine le_trans (Nat.cast_le.mpr ?_) (loss h) + rw [h.unit_load] + have hm : 2 ^ ((Λ).seats S.h) ≤ (4 * M) * 2 ^ S.h * 2 ^ (P.n * J * K) := by + unfold Limits.seats + rw [pow_add, pow_add] + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ h.padding) + calc + _ ≤ K * (K ^ (P.n * J) * (6 * P.b ^ J) * S.z) * ((4 * M) * 2 ^ S.h * 2 ^ (P.n * J * K)) + := Nat.mul_le_mul_left _ hm + _ = _ := by unfold Setup.count; rw [h.size]; ring + +theorem Fit.enough : Enough S Λ := by + obtain ⟨hh, hk, ht⟩ := h.address + have hp := h.poly + have he := h.headroom + have hj := h.large.beats + have hb := h.factors + have hu := h.lanes.1.trans h.lanes.2 + refine ⟨h.trivalent, h.zpos, h.names, h.pos, ht, hk, le_max_left .., hh, h.basic, ?_, ?_, ?_, + history h, slack h⟩ + · have hz : Nat.clog 2 (1 + (Λ).code) ≤ g * J := + (Nat.clog_le_iff_le_pow (by decide)).mpr (by omega) + have hx := Nat.pow_le_pow_right (show 0 < (Λ).A by omega) h.pos + rw [pow_one] at hx + exact hz.trans ((show g * J ≤ (Λ).A by omega).trans hx) + · change (Λ).small ^ K ≤ w / 4 + have := Nat.le_mul_of_pos_left ((Λ).small ^ K) (show 0 < 1 + (Λ).steps by omega) + omega + · change 3 * (K ^ (P.n * J) * 1) ≤ S.d + rw [h.degree, mul_one] + refine le_trans ?_ (growth P K d (J := J) (by omega)).1 + have hb' := P.b_pos + exact (Nat.mul_le_mul_right _ (by decide : 3 ≤ 6)).trans (Nat.le_mul_of_pos_right _ (by + positivity)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +end + +/- # Uniform bounds on global computations and short labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +variable {F : Type} [Field F] [Fintype F] {x y : Wire} +variable {P : Recipe F} {K d R B J M w : ℕ} {S : Setup F x y} +variable (h : Fit P K d R B J M w S) +local notation "Λ" => limits P K d J M w S +local notation "l" => lane P K d +local notation "g" => label P K d +local notation "X" => (2 ^ (l * J) : ℕ) +local notation "Y" => (2 ^ (g * J) : ℕ) +local notation "T₀" => Stack.initialTemplate S w M +include h + +theorem Fit.dominate : 10000 ≤ X ∧ 2 ^ J ≤ X ∧ X ≤ Y ∧ (Λ).A ^ K ≤ Y := by + have hx : 2 ^ J ≤ X := h.lanes.1.trans_eq h.degree + have hi := dyad h.large.beats + refine ⟨(by omega), hx, mono J (lane_label P K d), ?_⟩ + apply Regroup.raised + unfold label + rw [mul_comm K] + gcongr + exact (Nat.le_add_right _ _).trans (Nat.le_self_pow (by decide) _) + +theorem Fit.terminalHeight : S.h = (Λ).steps * (Λ).r + (J ^ 2 + R * J) := by + change S.h = P.n * J * P.group J + (J ^ 2 + R * J) + rw [h.height, Recipe.blocks] + ring + +theorem Fit.reservePower : (100 + w + (Λ).small) ^ K ≤ 2 ^ (J ^ 2) ∧ w ≤ 2 ^ S.h := by + obtain ⟨hx, hj, hxy, _⟩ := h.dominate + have hw := h.headroom + have hu := h.upper + have hk := h.pos + have hb : (Λ).small ≤ w := by + have hsmall : (Λ).small ^ K ≤ w / 4 := h.enough.labels + have hh := Nat.le_self_pow (by omega : K ≠ 0) (Λ).small + omega + have ht : 100 + w + (Λ).small ≤ 2 ^ (2 * B * J + 3) := by rw [pow_add]; omega + have ha : (100 + w + (Λ).small) ^ K ≤ 2 ^ (J ^ 2) := calc + _ ≤ (2 ^ (2 * B * J + 3)) ^ K := Nat.pow_le_pow_left ht _ + _ ≤ _ := by + rw [← pow_mul] + apply dyad + have hJ := h.large.beats + have hR := Nat.mul_le_mul_right J h.large.spare + nlinarith only [hR, Nat.mul_le_mul_left K (show 1 ≤ J by omega)] + refine ⟨ha, le_trans ?_ (ha.trans (dyad (by have := h.terminalHeight; omega)))⟩ + exact (by omega : w ≤ 100 + w + (Λ).small).trans (Nat.le_self_pow (by omega) _) + +theorem Fit.hosts_bound : 2 ^ (Λ).host ≤ M * 2 ^ ((Λ).steps * (Λ).r) * X ∧ + 2 ^ ((Λ).seats S.h) ≤ M * 2 ^ S.h * X := by + have hj := h.large.beats + have hs : 4 * 2 ^ ((Λ).steps * (Λ).K) ≤ X := (growth P K d (by omega)).2 + have hm (t : ℕ) : 2 ^ ((Λ).m + t + (Λ).steps * (Λ).K) ≤ M * 2 ^ t * X := calc + _ = 2 ^ (Λ).m * 2 ^ t * 2 ^ ((Λ).steps * (Λ).K) := by rw [pow_add, pow_add] + _ ≤ (4 * M) * 2 ^ t * 2 ^ ((Λ).steps * (Λ).K) + := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ h.padding) + _ = M * 2 ^ t * (4 * 2 ^ ((Λ).steps * (Λ).K)) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ hs + exact ⟨by rw [Limits.host, mul_add, ← add_assoc]; exact hm _, hm _⟩ + +private theorem phases : (Λ).steps * (Λ).cost S.h ≤ M * 2 ^ S.h * (2 * X * Y) := by + have hp := h.poly + have hh : (Λ).steps * (Λ).small ^ K ≤ Y := + (Nat.mul_le_mul_right _ (Nat.le_add_left _ 1)).trans (by omega) + have hi : (Λ).steps ≤ Y := by + obtain ⟨_, hx, hy, _⟩ := h.dominate + have := h.factors + change P.n * J ≤ Y + omega + have ht : (Λ).host + J ^ 2 ≤ (Λ).seats S.h := by + have := h.terminalHeight + unfold Limits.host Limits.seats + rw [mul_add] + omega + have hw : 2 ^ (Λ).host * (100 + w + (Λ).small) ^ K ≤ 2 ^ ((Λ).seats S.h) := calc + _ ≤ 2 ^ (Λ).host * 2 ^ (J ^ 2) := Nat.mul_le_mul_left _ h.reservePower.1 + _ ≤ _ := by rw [← pow_add]; exact dyad ht + have hs := h.hosts_bound.2 + change (Λ).steps * (2 ^ (Λ).host * (100 + w + (Λ).small) ^ K + + 2 ^ ((Λ).seats S.h) * (Λ).small ^ K) ≤ _ + calc + _ = (Λ).steps * (2 ^ (Λ).host * (100 + w + (Λ).small) ^ K) + + 2 ^ ((Λ).seats S.h) * ((Λ).steps * (Λ).small ^ K) := by ring + _ ≤ Y * (M * 2 ^ S.h * X) + (M * 2 ^ S.h * X) * Y + := Nat.add_le_add (Nat.mul_le_mul hi (hw.trans hs)) (Nat.mul_le_mul hs hh) + _ = _ := by ring + +theorem Fit.cost : Snapshot.sweepCost S T₀ + (Λ).steps * (Λ).cost S.h + (S.format T₀).width ≤ + M * 2 ^ S.h * 2 ^ (result P K d R * J) := by + obtain ⟨hx, hx', hy, _⟩ := h.dominate + have hF := h.factors + have hM := h.hosts + have hw := h.headroom + have hpre := Stack.start_bound (S := S) (w := w) (M := M) + (by omega : 8 ≤ X) le_rfl (by omega) (by omega) h.names h.degree.le (by omega) (by omega) + have hinit : Snapshot.sweepCost S T₀ + (S.format T₀).width ≤ M * 2 ^ S.h * (4800 * X ^ 3) := calc + _ ≤ _ := hpre + _ ≤ 600 * X ^ 3 * ((4 * M) * 2 ^ S.h) + 600 * X ^ 3 * (4 * M) * 2 ^ S.h := by + have hm : 2 ^ (T₀).scheme.m ≤ 4 * M := h.padding + have hd := h.reservePower.2 + have he : X ≤ X ^ 3 := Nat.le_self_pow (by decide) _ + rw [pow_add] + exact Nat.add_le_add (Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ hm)) + (Nat.mul_le_mul (Nat.mul_le_mul (Nat.mul_le_mul_left _ he) hm) hd) + _ = _ := by ring + have hc : 4800 * X ^ 3 + 2 * X * Y ≤ X ^ 4 * Y := calc + _ ≤ 4800 * X ^ 3 * Y + 2 * X ^ 3 * Y := Nat.add_le_add (Nat.le_mul_of_pos_right _ (by + positivity)) + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ (Nat.le_self_pow (by decide) _))) + _ = 4802 * (X ^ 3 * Y) := by ring + _ ≤ X * (X ^ 3 * Y) := Nat.mul_le_mul_right _ (by omega) + _ = _ := by ring + have hd : X ^ 4 * Y ≤ 2 ^ (result P K d R * J) := by + rw [← pow_mul, ← pow_add, show l * J * 4 + g * J = (4 * l + g) * J by ring] + exact mono _ (by unfold result; omega) + rw [add_right_comm] + refine (Nat.add_le_add hinit (phases h)).trans ?_ + rw [← mul_add] + exact Nat.mul_le_mul_left _ (hc.trans hd) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +end + +/- # Finishing an iteration of framed phases -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +open Assembly + +variable {F : Type} [Field F] {x y : Wire} + {D : Dimensions} {G : Diagram F x y} {name : Stack.Outer x y ↪ (Fin D.e → Bool)} + {cap discount k Δ : ℕ} {T : Template F} + {P : Budget} {M C c e R J w a l : ℕ} + +local notation "src" => D.setup G name cap discount +local notation "dst" => target T.scheme k +local notation "A" => (2 ^ (a * J) : ℕ) +local notation "L" => (2 ^ (l * J) : ℕ) + +theorem transfer (hn : Nonempty G.V) (hj : 20 ≤ J) (hl : 1 ≤ l) (ha : l ≤ a) + (hc : 3 * l ≤ c) (he : 5 * a ≤ e) (hr : R ≤ a) (hw : 1 ≤ w) + (ht : T.scheme.h = k + R * J) (hh : T.scheme.h ≤ D.h) + (hk : T.scheme.k = 0) (hm : T.scheme.m + k ≤ 3 * w) (hw' : D.e ≤ 3 * w) + (hd : T.scheme.d ≤ l * J) (hd' : D.d ≤ L) (hh' : D.h ≤ A) + (tag : T.scheme.ℓ ≤ A) (spans : 2 ^ T.scheme.e ≤ A) (cnt : T.count ≤ A) + (hosts : 2 ^ T.scheme.m ≤ M * 2 ^ (D.h - T.scheme.h) * L) + (reach : P.reach * D.q ≤ 2 ^ (R * J)) (load : P.load ≤ 2 ^ (c * J) * D.b) + (width : P.width ≤ C * (D.copies : ℝ) * ((1 / 2 : ℝ) ^ J * M + (wd x + wd y : ℕ))) + {X : Assembly.Snapshot.{1} F (src).input (src).output} + {u n : ℕ} (labels : Finset (Table F)) (few : labels.card ≤ 2 ^ (w / 4)) + (small : ∀ v ∈ labels, Processor.arity v ≤ w / 4) + (f : Transforms F u (Allowed F w ∪ (labels : Set (Table F))) X (frame src T D.z Δ P) n) + (first : X.state) (code : X.port.obj) (enc : ∀ i j, X.encode first i j = code) + (eq : X.eval first = MatrixExponent.power G.eval D.copies) + (hcost : n + X.port.width ≤ M * 2 ^ D.h * A) : + Nonempty (Transfer G D M C c e R J w) := by + have hp {i j : ℕ} (h : i ≤ j) : (2 : ℕ) ^ (i * J) ≤ 2 ^ (j * J) := + Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ h) + have large : 1000000 ≤ L := calc + _ ≤ 2 ^ 20 := by norm_num + _ ≤ _ := Nat.pow_le_pow_right (by decide) (hj.trans (Nat.le_mul_of_pos_left _ hl)) + have ha' := hp ha + have hf : (dst).h = R * J := by change T.scheme.h - k = _; omega + have hs := Nat.pow_le_pow_right (by decide : 0 < 2) hd + obtain ⟨Y, V, hy, net, ok⟩ := terminal (name := name) (k := k) hn (by omega) hh + (Ready (S := src) Δ P) (by change P.reach * D.q ≤ 2 ^ (dst).h; rwa [hf]) (fun _ r + => r.tracks) (le_max_left 3 u) + (Allowed F w ∪ (labels : Set (Table F))) + have f' := (f.widen (le_max_right 3 u) Set.Subset.rfl).comp net + refine ⟨⟨X, Y, _, _, labels, few, small, f', first, code, enc, eq, ?_, dst, ?_, ?_, ?_, ?_, _, + ?_, V, ?_⟩⟩ + · have hpre := format_bound (S := src) (T := T) (by omega : 2 ≤ L) ha' hw hk + (by omega : T.scheme.m ≤ 3 * w) hw' hs hd' hh' tag spans cnt + have hpost := tape_bound (S := src) (N := dst) (by omega : 2 ≤ L) ha' hw hk + hm hw' hs hd' hh' tag spans + have bound := expenses large ha' ht hh hosts hcost hpre (hy.le.trans hpost) + have hsmall := Nat.mul_le_mul_left (M * 2 ^ D.h) (raised (J := J) he) + have hlong := Nat.mul_le_mul_right w (Nat.mul_le_mul_left (M * 2 ^ (D.h - R * J)) (raised (J + := J) hc)) + exact (by omega : _ ≤ (n + X.port.width) + 1000 * (((src).format T).width + Y.port.width) + + Y.port.width).trans + (bound.trans (Nat.add_le_add hsmall hlong)) + · change 2 ^ (T.scheme.m + k) * 2 ^ (R * J) ≤ _ + rw [← pow_add, add_assoc, ← ht] + exact (capacities ht hh hosts).1.trans (Nat.mul_le_mul_left _ (hp (by omega))) + · rw [hf] + exact Nat.mul_le_mul_right _ (Nat.le_add_right _ _) + · exact hd.trans (Nat.mul_le_mul_right J (by omega)) + · exact tag.trans (hp (by omega)) + · calc + _ ≤ 100 * A ^ 3 * 2 ^ (dst).h := meta_bound (S := src) (N := dst) (by omega) hk + (hd'.trans ha') hh' tag spans + _ ≤ A * A ^ 3 * A := by + rw [hf] + exact Nat.mul_le_mul (Nat.mul_le_mul_right _ (by omega)) (hp hr) + _ = A ^ 5 := by ring + _ ≤ _ := raised he + · intro i p q + obtain ⟨v, t, ready, hx, load', heval, hv⟩ := ok i p q + refine ⟨t, ?_, ?_, heval, hv⟩ + · rw [hx] + exact ready.width.trans width + · apply load' + intro v b + refine (ready.bounded.2.2 v b).trans ?_ + exact_mod_cast Nat.mul_le_mul_right D.z load + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +end + +/- # Joining the initial sweep, the contraction sequence and the last transfer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +open Assembly + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} +variable {P : Recipe F} {K d R B J M w C : ℕ} {S : Setup F x y} + +open scoped Classical in +private theorem width (h : Fit P K d R B J M w S) (hc : P.C ≤ C) : + let L := limits P K d J M w S + (1 / 2 : ℝ) ^ J * L.start.width + P.C * (S.fringe.Z + L.σ) ≤ + (3 + 2 * C : ℕ) * (S.count : ℝ) * ((1 / 2 : ℝ) ^ J * M + (wd x + wd y : ℕ)) := by + let L := limits P K d J M w S + have hz : 0 ≤ S.fringe.Z := add_nonneg (Finset.sum_nonneg (fun i _ + => S.fringe.nonneg i)) S.fringe.reserve_nonneg + have hσ : 0 ≤ L.σ := by change 0 ≤ (1 / 2 : ℝ) ^ J * M * S.count; positivity + have hb : P.C * (S.fringe.Z + L.σ) ≤ C * ((S.count : ℝ) * (wd x + wd y : ℕ) + 2 * L.σ) := + mul_le_mul hc (by linarith only [h.exterior]) (by positivity) (by positivity) + change (1 / 2 : ℝ) ^ J * (3 * (M : ℝ) * S.count) + P.C * (S.fringe.Z + L.σ) ≤ _ + refine (add_le_add_right hb _).trans ?_ + change _ + C * ((S.count : ℝ) * (wd x + wd y : ℕ) + 2 * ((1 / 2 : ℝ) ^ J * M * S.count)) ≤ _ + rw [show ((3 + 2 * C : ℕ) : ℝ) = 3 + 2 * C by norm_cast] + nlinarith only [show 0 ≤ (3 + (C : ℝ)) * (S.count : ℝ) * (wd x + wd y : ℕ) by positivity] + +variable {D : Dimensions} {G : Diagram F x y} + {name : Stack.Outer x y ↪ (Fin D.e → Bool)} {budget discount : ℕ} + +local notation "src" => D.setup G name budget discount +local notation "Λ" => limits P K d J M w src +local notation "T₀" => Stack.initialTemplate src w M +local notation "lanes" => lane P K d +local notation "g" => label P K d +local notation "gains" => result P K d R + +open scoped Classical in +theorem collected (h : Fit P K d R B J M w src) (hc : P.C ≤ C) + (hn : Nonempty G.V) (hq : 2 ^ (lanes * J) * D.q ≤ 2 ^ (R * J)) + (z : Completion src Λ (T₀).sweep (Stack.initialBudget src M) + (src).U D.z 8 8 d 0 (P.n * J) ((1 / 2) ^ J) P.C) : + Nonempty (Transfer G D M (3 + 2 * C) (3 * lanes) (5 * gains) R J w) := by + have hj := h.large.beats + have hl := lane_min P K d + obtain ⟨hx, hx', hy, hy'⟩ := h.dominate + have hf := h.factors + have hw := h.headroom + have hz : (src).z ∣ (src).U := dvd_mul_left _ _ + have hU : 0 < (src).U := Nat.mul_pos D.bpos D.zpos + obtain ⟨X, i, b, hX, hi, hb, net⟩ := Stack.begin_frame src w M h.trivalent hn + (by have := h.diagram; omega) hU hz (by rw [h.degree]; omega) + let L := insert (Snapshot.sweepTable T₀) z.labels + let allowed := Allowed F w ∪ (L : Set (Table F)) + let scale := max (3 + 2 * Stack.length F) z.scale + have h₁ := net.widen (v := scale) (L' := allowed) (le_max_left ..) + (Set.singleton_subset_iff.mpr (.inr (Finset.mem_insert_self ..))) + have h₂ := z.transfer.widen (v := scale) (L' := allowed) (le_max_right ..) + (Set.union_subset_union_right _ (Finset.subset_insert ..)) + have ht : Inside src Λ z.next z.budget D.z d (Λ).steps := by + rw [show (Λ).steps = P.n * J from rfl] + simpa only [zero_add] using z.inside + have hh : z.next.scheme.h + (Λ).steps * (Λ).r = D.h := ht.height + have hheight : D.h = (Λ).steps * (Λ).r + (J ^ 2 + R * J) := h.terminalHeight + have hu : z.next.scheme.m ≤ (Λ).host := ht.upper + have htop : (Λ).host + K * (D.h + 1) ≤ 2 * w := h.address.1 + have ha' : 2 ^ (g * J) ≤ 2 ^ (gains * J) := mono _ (by unfold result; omega) + have hpoly := h.poly + have hsize : D.h ≤ 2 ^ J := by + have ht' : (src).h ≤ 2 ^ J := by omega + exact ht' + refine Regroup.transfer (k := J ^ 2) (l := lane P K d) (a := result P K d R) + (name := name) (cap := budget) (discount := discount) + hn hj (by omega) (by unfold result; omega) le_rfl le_rfl (by unfold result; omega) + (by omega) (by omega) (by omega) ht.single (by omega) h.names ?_ h.degree.le + (hsize.trans (hx'.trans (hy.trans ha'))) ?_ (ht.spans.trans (hy'.trans ha')) + (ht.counters.trans (hy'.trans ha')) ?_ ?_ ?_ (z.width.trans (width h hc)) + L ?_ ?_ (h₁.comp h₂) i b hb hi ?_ + · have hd : d ≤ lanes := by unfold lane; omega + exact ht.degree.trans (hd.trans (Nat.le_mul_of_pos_right _ (by omega))) + · exact ht.bits.trans ((by omega : (Λ).code ≤ 2 ^ (g * J)).trans ha') + · rw [show D.h - z.next.scheme.h = (Λ).steps * (Λ).r by omega] + exact (dyad hu).trans h.hosts_bound.1 + · have ht' : z.budget.reach ≤ 2 ^ (lanes * J) := + (ht.origins.trans ((Nat.le_mul_of_pos_left _ (by decide : 0 + < 3)).trans h.enough.origins)).trans_eq h.degree + exact (Nat.mul_le_mul_right _ ht').trans hq + · have hp : K ^ (P.n * J) * (Λ).start.load ≤ 2 ^ (lanes * J) := by + rw [h.unit_load, ← mul_assoc, mul_comm _ 6] + exact (growth P K d (by omega)).1 + exact (ht.load.trans hp).trans ((mono J (by omega)).trans (Nat.le_mul_of_pos_right _ D.bpos)) + · have sz := Finset.card_insert_le (Snapshot.sweepTable T₀) z.labels + have hh' : z.labels.card ≤ (1 + (Λ).steps) * (Λ).small ^ K := + z.few.trans (Nat.mul_le_mul_right _ (Nat.le_add_left _ 1)) + have hl' : L.card ≤ w / 4 := by unfold L; omega + exact hl'.trans (Nat.lt_two_pow_self (n := w / 4)).le + · intro q hq' + rcases Finset.mem_insert.mp hq' with rfl|hq' + · change wd (word (Coloring.Format.addr (Stack.length F)).width) + + wd (word (Coloring.Format.addr (Stack.length F)).width) ≤ w / 4 + rw [wd_word, Coloring.Format.width_addr] + have he := dyad (show J + 1 ≤ lanes * J by nlinarith only [hj, hl]) + rw [pow_succ] at he + omega + · exact (z.small _ hq').trans h.enough.labels + · rw [hX] + refine le_trans ?_ h.cost + exact Nat.add_le_add_right (Nat.add_le_add_left z.cost _) _ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Horizon +end + +/- +# Encoding the sequence of contractions + +Choose the exponent for the number of lanes first. The reserve can +then be chosen arbitrarily large before setting the exponent charged +to short control records. A single sequence of circuits handles +every branch of the resulting weighted expansion. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Filter Horizon + +variable {F : Type} [Field F] [Fintype F] + +private theorem complete {x y : Wire} {S : Setup F x y} {P : Recipe F} + {K d R B J M w : ℕ} (h : Fit P K d R B J M w S) (hd : 3 ≤ d) + (q : Sequence F K 8 8 d d (P.b ^ J) (P.n * J) ((1 / 2) ^ J) P.C) : + Nonempty (Completion S (limits P K d J M w S) (Stack.initialTemplate S w M).sweep + (Stack.initialBudget S M) S.U S.z 8 8 d 0 (P.n * J) ((1 / 2) ^ J) P.C) := by + let L := limits P K d J M w S + have hz : S.z ∣ S.U := by rw [h.size]; exact dvd_mul_left _ _ + have hl : Stack.length F + 1 ≤ L.A := by + have := h.factors + have hx : 2 ^ J ≤ L.A := h.lanes.1.trans h.lanes.2 + omega + have ht := Stack.first_inside S L M d h.enough hd rfl rfl hz hl + have hσ : 0 ≤ L.σ := by change 0 ≤ (1 / 2 : ℝ) ^ J * M * S.count; positivity + exact q.run h.enough hσ ht (by rw [zero_add]; exact le_rfl) h.size h.zpos (dvd_refl _) (dvd_refl + _) le_rfl + +omit [Fintype F] in +theorem encoded_of_rules [Finite F] (ht : ¬Tagged.Hard F) + (hgroup : SubroundRule F) (hreset : ResetRule F) : + Encoded F := by + let : Fintype F := Fintype.ofFinite F + obtain ⟨P, K, d, hK, hd, hH, seq⟩ := sequence_recipe ht hgroup hreset + obtain ⟨C, hC⟩ := exists_nat_gt P.C + let l := lane P K d + refine ⟨P, 3 + 2 * C, 3 * l, l, by omega, ?_⟩ + intro Q R V _ hR _ + refine ⟨5 * result P K d R, ?_⟩ + intro B hB + have hg : label P K d + 10 ≤ B := by unfold result at hB; omega + filter_upwards [large P K d R B] with J hJ + intro w z T hQ hV hh hz hv hlo hhi hwidth _ x y G M hn htri hsize hM hM' + let D := P.dimensions w J z (R + J) Q V (2 ^ (l * J)) T hQ hV hh hz hv + have hj := hJ.beats + have hw : 100 ≤ w := by + have hb : J ≤ B * J := Nat.le_mul_of_pos_left _ (by omega) + have := (dyad (hj.trans hb)).trans hlo + omega + obtain ⟨hm, hp⟩ := Stack.hostCount hw hM hM' + obtain ⟨e⟩ := Stack.name_exists (x := x) (y := y) + (by omega : wd x + wd y ≤ M) ((le_max_right _ _).trans hm) + let S := D.setup G e (cap P K J M D.copies) (P.group J) + have hu : S.U ≤ w := by + change P.b ^ J * D.z ≤ w + rw [Recipe.dimensions_z] + refine le_trans ?_ hwidth + rw [← mul_assoc 16, mul_assoc (16 * 2 ^ (Q * J))] + exact Nat.le_mul_of_pos_left _ (by positivity) + have h : Fit P K d R B J M w S := + ⟨hJ, hK, hH, hg, rfl, rfl, D.zpos, hu, rfl, by change 2 * w ≤ _; omega, + rfl, rfl, htri, hsize, hm, hp, hlo, hhi⟩ + obtain ⟨t⟩ := complete h hd (seq J (by omega)) + have hr : 2 ^ (l * J) * D.q ≤ 2 ^ (R * J) := by + change 2 ^ (l * J) * 2 ^ (Q * J) ≤ _ + rw [← pow_add, ← add_mul] + exact mono J (by omega) + exact collected h hC.le hn hr t + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Exterior/Fields.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Exterior/Fields.lean new file mode 100644 index 0000000000..9f00e5b589 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Exterior/Fields.lean @@ -0,0 +1,680 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Header +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Observed + +/-! +# Summing the port tape + +Use an independent service to check the original exterior positions. +The zero pad outside the image of the pin embedding ensures that every +setting of the free interior wires contributes once. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +open Assembly Coloring Transcript + +variable {F X : Type} [Field F] {S : Scheme F} {r : S.format.obj} + {u v K p d a : ℕ} {l : Inventory (2 ^ S.m) (2 ^ S.h) d} + +namespace Wires +variable (T : Wires S u v K p a (X ⊕ Tape u v K p)) + +open Classical in +/-- The correct packet of type `Prop` for the given inputs. -/ +def correctPacket (A : Pieces S r l v p) (L : PackRows.Layout l u v K) + (π : PacketPlan (Address v K) a) : Prop := + ∀ y : Tape u v K p → Bool, Links.pad (A.inside L) y → + ((∀ i, (π.head i).1 = true → Function.curry y (π.peer i) = Function.curry y i) ↔ + ∀ i j, S.Joins r i j → y (A.inside L i) = y (A.inside L j)) + +open Classical in +/-- The condition `∀ y, Links.pad (A.inside L) y → g (Sum.elim x y) = if ∀ i, y (A.inside L +i.val) = z i then 1 else 0` on the specified data. -/ +def correctExterior (A : Pieces S r l v p) (L : PackRows.Layout l u v K) (z : S.exposed r → Bool) + (g : (X ⊕ Tape u v K p → Bool) → F) (x : X → Bool) : Prop := + ∀ y, Links.pad (A.inside L) y → + g (Sum.elim x y) = if ∀ i, y (A.inside L i.val) = z i then 1 else 0 + +open Classical in +/-- Decidable equality of tapes used when comparing candidate packed rows. -/ +local instance : DecidableEq (Tape u v K p) := Classical.decEq _ + +omit [Field F] in +open Classical in +private theorem condition (p q : Prop) [Decidable p] [Decidable q] {d : Decidable (p + ∧ q)} (a b : F) : + @ite F (p ∧ q) d a b = if p then if q then a else b else b := by + by_cases hp : p <;> by_cases hq : q <;> simp [hp, hq] + +open Classical in +private theorem sum_tape (x : X → Bool) (A : Pieces S r l v p) (L : PackRows.Layout l u v K) + (π : PacketPlan (Address v K) a) (z : S.exposed r → Bool) + (g : (X ⊕ Tape u v K p → Bool) → F) + (hr : ∀ y, T.read (Sum.elim x y) = y) + (hp : correctPacket A L π) (he : correctExterior A L z g x) : + (∑ y, T.test A L π (Sum.elim x y) * g (Sum.elim x y)) = S.eval r z := by + let e := A.inside L + have hi : Function.Injective (Links.put e) := by + intro a b eq + rw [← Links.read_put e a, eq, Links.read_put] + symm + unfold Scheme.eval + refine Fintype.sum_of_injective (Links.put e) hi _ _ ?_ ?_ + · intro y hy + have hn : ¬ Links.pad e y := fun h => hy ⟨_, Links.put_read _ h⟩ + simp [test, hr, hn, e] + · intro y + have h := Links.padded e y + have hy := Links.read_put e y + have hj (i) : Links.put e y (e i) = y i := congrFun hy i + unfold test + rw [hr, he _ h] + simp only [hp _ h, hj, Scheme.Agrees, ← Function.comp_assoc, show A.inside L = e from rfl, + h, true_and, hy, mul_ite, mul_one, mul_zero] + exact condition (∀ i : S.exposed r, y i.val = z i) (∀ i j, S.Joins r i j → y i = y j) _ _ + +open Classical in +theorem evaluator [Fintype X] {w j cap m : ℕ} {U : Set (Table F)} + (ok : Fits S u v K p a w j cap) (hU : SortTables F w ⊆ U) + (g : (X ⊕ Tape u v K p → Bool) → F) (hg : WideWeight F cap U g m) : + ∃ f : (X → Bool) → F, WideWeight F cap U f + (10000000 * (Fintype.card X + 2 ^ j * (1 + w) + m)) ∧ + ∀ (r : S.format.obj) (d : ℕ) (l : Inventory (2 ^ S.m) (2 ^ S.h) d) + (A : Pieces S r l v p) (ha : Pieces.Room (l := l) (u := u)) + (L : PackRows.Layout l u v K) (π : PacketPlan (Address v K) a) + (z : S.exposed r → Bool) (x : X → Bool), + (∀ y, T.Supplied A ha L π.head (Sum.elim x y)) → (∀ y, T.read (Sum.elim x y) = y) → + correctPacket A L π → correctExterior A L z g x → f x = S.eval r z := by + obtain ⟨f, hf, he⟩ := T.service ok + let Y := Tape u v K p + let cost := 500000 * (Fintype.card (X ⊕ Y) + 2 ^ j * (1 + w)) + let job (b : Bool) := if b then f else g + let charge (b : Bool) := if b then cost else m + have H (b : Bool) : WideWeight F cap U (job b) (charge b) := by + cases b + · exact hg + · intro v i + obtain ⟨k, hk, h⟩ := hf v i + exact ⟨k, hk, h.mono le_rfl hU⟩ + have net := wide_sum job (fun _ => id) charge ok.gates H + have hY : Fintype.card Y ≤ 2 ^ j * w := by + simp only [Y, Fintype.card_prod, Fintype.card_fin] + apply Nat.mul_le_mul ok.slots + have := ok.move + have := ok.upper + change 2 * u * bundleSize v p ≤ w + omega + refine ⟨fun x => ∑ y : Y → Bool, f (Sum.elim x y) * g (Sum.elim x y), ?_, ?_⟩ + · intro v i + obtain ⟨k, hk, hn⟩ := net v i + refine ⟨k, ?_, ?_⟩ + · simp only [Fintype.sum_bool, charge, Bool.false_eq_true, ite_true, ite_false, cost, + Fintype.card_sum] at hk + have small : Fintype.card Y ≤ 2 ^ j * (1 + w) := hY.trans (Nat.mul_le_mul_left _ (by omega)) + dsimp only [Y] at small hk; omega + · simpa [weightedSum, job] using hn + · intro r d l A ha L π z x hs hr hp hg + trans ∑ y, T.test A L π (Sum.elim x y) * g (Sum.elim x y) + · exact Finset.sum_congr rfl (fun y _ => congrArg (· * _) (he _ _ _ _ _ _ _ _ (hs y))) + · exact T.sum_tape x A L π z g hr hp hg + +end Wires +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- +# Computing exterior controls from one host's short labels + +Each block lists only channel, stack number and segment. Count distinct +stacks, order them by the fixed stack index, and take prefixes across +blocks. Global exterior names do not enter this computation. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Packing Finset + +variable (D : Dimensions) {J : Type} {H k : ℕ} + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun s : Cell D.h => ∃ i t, l i = some (c, s, +t)`. -/ +def listed (l : D.Source) (c : Fin D.d) := + univ.filter fun s : Cell D.h => ∃ i t, l i = some (c, s, t) + +open scoped Classical in +/-- The quantity computed by `(listed D l c).card * D.b`. -/ +def countAt (l : D.Source) (c : Fin D.d) := (listed D l c).card * D.b + +open scoped Classical in +/-- The indexed operation `((listed D l c).filter fun t => Fintype.equivFin (Cell D.h) t < +Fintype.equivFin _ s).card`. -/ +def prior (l : D.Source) (c : Fin D.d) (s : Cell D.h) := + ((listed D l c).filter fun t => Fintype.equivFin (Cell D.h) t < Fintype.equivFin _ s).card + +open scoped Classical in +/-- The quantity computed by `PackRows.start (fun x => (listed D (l x) c).card) t + prior D (l +t) c s`. -/ +def ordinal (l : Fin k → D.Source) (c : Fin D.d) (t : Fin k) (s : Cell D.h) := + PackRows.start (fun x => (listed D (l x) c).card) t + prior D (l t) c s + +open scoped Classical in +/-- The condition `∃ t, s ∈ listed D (l t) c ∧ ordinal D l c t s / D.q = r.val ∧ ordinal D l c t +s % D.q = i.val` on the specified data. -/ +def occupied (l : Fin k → D.Source) (c : Fin D.d) (r : Fin D.v) (i : Fin D.q) (s : Cell D.h) : Prop + := + ∃ t, s ∈ listed D (l t) c ∧ + ordinal D l c t s / D.q = r.val ∧ ordinal D l c t s % D.q = i.val + +open scoped Classical in +/-- Returns `some h.choose` when `h : ∃ s, occupied D l c r i s` holds, and `none` otherwise. -/ +def readAddr (l : Fin k → D.Source) (c : Fin D.d) (r : Fin D.v) (i : Fin D.q) : Option (Cell D.h) := + if h : ∃ s, occupied D l c r i s then some h.choose else none + +open scoped Classical in +/-- In the case `.inl _`, this construction gives `decide (∃ i s, occupied D rows channel ord i +s)`. -/ +def program (rows : Fin k → D.Source) (channel : Fin D.d) (ord : Fin D.v) : D.ExteriorBits → Bool + | .inl _ => decide (∃ i s, occupied D rows channel ord i s) + | .inr (i, j) => encode ((readAddr D rows channel ord i).map D.cellCode) j + +variable (loc : J → Cell D.h → Fin H × Fin k) (χ : Fin H → J → Fin D.d) + (rows : Fin H → Fin k → D.Source) + +open scoped Classical in +/-- The condition `∀ i j c s, s ∈ listed D (rows i j) c ↔ ∃ t, loc t s = (i, j) ∧ χ i t = c` on +the specified data. -/ +def Accurate : Prop := ∀ i j c s, s ∈ listed D (rows i j) c ↔ ∃ t, loc t s = (i, j) ∧ χ i t = c + +open scoped Classical in +/-- The condition `∀ i j a b, (loc i a).1 = (loc j b).1 → χ (loc i a).1 i = χ (loc j b).1 j → i += j` on the specified data. -/ +def Separate : Prop := + ∀ i j a b, (loc i a).1 = (loc j b).1 → χ (loc i a).1 i = χ (loc j b).1 j → i = j + +namespace Accurate +variable {D loc χ rows} (a : Accurate D loc χ rows) (sep : Separate D loc χ) +include a sep + +open scoped Classical in +theorem listed_eq (i : J) (s : Cell D.h) (t : Fin k) : + let v := (loc i s).1 + listed D (rows v t) (χ v i) = univ.filter (fun j => loc i j = (v, t)) := by + intro v + ext j + rw [a, mem_filter_univ] + refine ⟨?_, fun h => ⟨i, h, rfl⟩⟩ + rintro ⟨l, hl, hc⟩ + have hv : (loc l j).1 = (loc i s).1 := by rw [hl] + have e := sep l i j s hv (by rwa [hv]) + subst l; exact hl + +open scoped Classical in +theorem prior_eq (i : J) (s : Cell D.h) : + prior D (rows (loc i s).1 (loc i s).2) (χ (loc i s).1 i) s = + (univ.filter fun t => loc i t = loc i s ∧ + Fintype.equivFin (Cell D.h) t < Fintype.equivFin _ s).card := by + rw [prior, a.listed_eq sep i s, filter_filter] + +variable [Fintype J] + +open scoped Classical in +theorem counts_eq (v : Fin H) (t : Fin k) (c : Fin D.d) : + counts loc χ v t c = (listed D (rows v t) c).card := by + have hf := lengths_eq loc χ 1 v t c + simp only [lengths, mul_one] at hf + rw [hf] + apply card_bij (fun x _ => x.2) + · intro x hx + obtain ⟨hl, hc⟩ := (mem_filter.mp hx).2 + exact (a _ _ _ _).mpr ⟨x.1, hl, by simpa only [hl] using hc⟩ + · intro x hx y hy he + obtain ⟨hl, hc⟩ := (mem_filter.mp hx).2 + obtain ⟨hl', hc'⟩ := (mem_filter.mp hy).2 + exact Prod.ext (sep _ _ _ _ (congrArg Prod.fst (hl.trans hl'.symm)) (hc.trans hc'.symm)) he + · intro i hi + obtain ⟨j, hj, hc⟩ := (a _ _ _ _).mp hi + exact ⟨(j, i), mem_filter.mpr ⟨mem_univ _, hj, by simpa only [hj] using hc⟩, rfl⟩ + +open scoped Classical in +theorem countAt (v : Fin H) (t : Fin k) (c : Fin D.d) : + Exterior.countAt D (rows v t) c = lengths loc χ D.b v t c := by + rw [lengths, Exterior.countAt, a.counts_eq sep] + +open scoped Classical in +theorem point_slot (i : J) (s : Cell D.h) (q : Fin D.b) : + (point loc χ D.b ((i, s), q)).2.2.2.val = + prior D (rows (loc i s).1 (loc i s).2) (χ (loc i s).1 i) s * D.b + q.val := by + rw [Exterior.point_slot, stack_slot loc χ sep, a.prior_eq sep] + +open scoped Classical in +theorem rank (i : J) (s : Cell D.h) : PackRows.rank _ (stack loc χ (i, s)) = + ordinal D (rows (loc i s).1) (χ (loc i s).1 i) (loc i s).2 s := by + unfold PackRows.rank ordinal + rw [stack_slot loc χ sep, a.prior_eq sep] + congr 2 + funext t + exact a.counts_eq sep _ _ _ + +end Accurate +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +/- # Reading the exterior stacks of a registered assignment -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Assignment +open Packing Coloring PackRows Assembly + +variable {F : Type} [Field F] {x y : Wire} {D : Dimensions} {S : Scheme F} {G : Diagram F x y} + (t : Assignment D S G) (hw : t.Fits) + +open scoped Classical in +theorem accurate {rows : B S.m → B S.h → D.Source} (h : t.Registered hw rows) : + Exterior.Accurate D t.loc t.lane rows := by + intro i j c s + simp only [Exterior.listed, Finset.mem_filter_univ] + constructor + · rintro ⟨k, b, hh⟩ + obtain ⟨a, h₁, h₂, _⟩ := (h _ _ _ _ _ _).mp hh + exact ⟨a, h₁, h₂⟩ + · rintro ⟨a, h₁, h₂⟩ + let b : Fin D.b := ⟨0, D.bpos⟩ + exact ⟨t.coordinate hw (t.endpoint a s b), b, (h _ _ _ _ _ _).mpr ⟨a, h₁, h₂, rfl⟩⟩ + +open scoped Classical in +/-- The descriptor of type `Exterior.Descriptor (Stack.Outer x y) (Cell D.h) D.Addr (Fin D.q) +D.n` for the given inputs. -/ +def descriptor : Exterior.Descriptor (Stack.Outer x y) (Cell D.h) D.Addr (Fin D.q) D.n := + (Exterior.make_descriptor t.loc t.lane t.inject_names D.bpos D.qpos t.cap + (by simpa using D.cover) D.width _ (t.layout hw)).choose + +open scoped Classical in +theorem placement (i : Stack.Outer x y) (s : Cell D.h) (k : Fin D.b) : + let slot := (t.layout hw).portSlots (t.endpoint i s k) + slot.1 = ((t.descriptor hw).place (i, s)).1 ∧ + slot.2.val = ((t.descriptor hw).place (i, s)).2.val * D.b + k.val := + (Exterior.make_descriptor t.loc t.lane t.inject_names D.bpos D.qpos t.cap + (by simpa using D.cover) D.width _ (t.layout hw)).choose_spec i s k + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Assignment +end + +/- # Correct exterior fields at every occupied port -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Assignment +open Packing Coloring PackRows Assembly + +variable {F : Type} [Field F] {x y : Wire} {D : Dimensions} {S : Scheme F} {G : Diagram F x y} + (t : Assignment D S G) (hw : t.Fits) + +open scoped Classical in +private theorem portrow_iff {H m d u : ℕ} {l : Inventory H m d} (s : Endpoints l) (r : PortRows l + u) : + portRow l u s = r ↔ s.1 = r.1 ∧ s.2.2.1 = r.2.1 ∧ rank l s / (2 * u) = r.2.2.val := by + constructor + · intro h; subst r; exact ⟨rfl, rfl, rfl⟩ + · obtain ⟨v, c, k⟩ := r + rintro ⟨rfl, rfl, he⟩ + exact congrArg (fun z => (⟨s.1, s.2.2.1, z⟩ : PortRows l u)) (Fin.ext he) + +open scoped Classical in +/-- Identify a stack at an inside address by its host, channel, and +ordinal in the concatenation of the blocks of that channel. -/ +theorem placed_iff (r : PortRows t.inventory D.u) (q : Fin D.q) (i : Stack.Outer x y) (s : Cell + D.h) : + let n := rank _ (Exterior.stack t.loc t.lane (i, s)) + (t.descriptor hw).place (i, s) = ((t.layout hw).portLoc r, q) ↔ + (t.loc i s).1 = r.1 ∧ Fin.natAdd (2 * 2 ^ S.d) (t.lane (t.loc i s).1 i) = r.2.1 ∧ + n / D.q = r.2.2.val ∧ n % D.q = q.val := by + intro n + let j : Fin D.b := ⟨0, D.bpos⟩ + have h := t.placement hw i s j + have eq : rank t.inventory (t.endpoint i s j) = n * D.b := by + unfold endpoint inventory outerCount + rw [rank_extendR, Exterior.point_rank]; rfl + have col : ((t.descriptor hw).place (i, s)).2.val = n % D.q := by + have hh := h.2 + rw [(t.layout hw).ordinal, eq, ← D.width, Nat.mul_mod_mul_right] at hh + exact Nat.mul_right_cancel D.bpos hh.symm + rw [Prod.ext_iff, ← h.1, (t.layout hw).locate, (t.layout hw).portLoc.injective.eq_iff, + portrow_iff, eq, ← D.width, Nat.mul_div_mul_right _ _ D.bpos] + simp only [Fin.ext_iff, col, and_assoc] + rfl + +variable {rows : B S.m → B S.h → D.Source} (ok : t.Registered hw rows) + (r : PortRows t.inventory D.u) (c : Fin D.d) (o : Fin D.v) + (hc : r.2.1 = Fin.natAdd (2 * 2 ^ S.d) c) (hr : r.2.2.val = o.val) +include ok hc hr + +open scoped Classical in +theorem occupied_iff (q : Fin D.q) (s : Cell D.h) : + Exterior.occupied D (rows r.1) c o q s ↔ + ∃ i, (t.descriptor hw).place (i, s) = ((t.layout hw).portLoc r, q) := by + have ac := t.accurate hw ok + constructor + · rintro ⟨j, hj, h₁, h₂⟩ + obtain ⟨i, hi, he⟩ := (ac _ _ _ _).mp hj + refine ⟨i, (t.placed_iff hw r q i s).mpr ?_⟩ + simp only [ac.rank t.inject_names, hi, he, hc, hr, h₁, h₂, and_self] + · rintro ⟨i, h⟩ + obtain ⟨hi, he, h₁, h₂⟩ := (t.placed_iff hw r q i s).mp h + rw [hc, Fin.natAdd_inj, hi] at he + rw [ac.rank t.inject_names, hi, he] at h₁ h₂ + exact ⟨(t.loc i s).2, (ac _ _ _ _).mpr ⟨i, Prod.ext hi rfl, he⟩, h₁.trans hr, h₂⟩ + +open scoped Classical in +theorem program_active : + Exterior.program D (rows r.1) c o (.inl ()) = ((t.descriptor hw).owner ((t.layout hw).portLoc + r)).isSome := by + apply Bool.eq_iff_iff.mpr + simp only [Exterior.program, decide_eq_true_eq, Option.isSome_iff_exists] + constructor + · rintro ⟨q, s, h⟩ + obtain ⟨i, hi⟩ := (t.occupied_iff hw ok r c o hc hr q s).mp h + exact ⟨i, ((t.descriptor hw).addr_eq _ _ _ _).mpr hi |>.1⟩ + · rintro ⟨i, hi⟩ + obtain ⟨s, hs⟩ := ((t.descriptor hw).owner_eq _ _).mp hi + exact ⟨_, s, (t.occupied_iff hw ok r c o hc hr _ s).mpr ⟨i, Prod.ext hs rfl⟩⟩ + +open scoped Classical in +theorem program_addr (q : Fin D.q) {i : Stack.Outer x y} + (hi : (t.descriptor hw).owner ((t.layout hw).portLoc r) = some i) : + (fun j => Exterior.program D (rows r.1) c o (.inr (q, j))) = + Exterior.encode (((t.descriptor hw).addr ((t.layout hw).portLoc r) q).map D.cellCode) := by + have eq s : Exterior.occupied D (rows r.1) c o q s ↔ + (t.descriptor hw).addr ((t.layout hw).portLoc r) q = some s := by + rw [t.occupied_iff hw ok r c o hc hr] + simp only [← (t.descriptor hw).addr_eq, hi, Option.some.injEq, exists_eq_left'] + have he : Exterior.readAddr D (rows r.1) c o q = + (t.descriptor hw).addr ((t.layout hw).portLoc r) q := by + unfold Exterior.readAddr + split + · rename_i h + exact ((eq _).mp h.choose_spec).symm + · rename_i h + cases hx : (t.descriptor hw).addr _ q with + | none => rfl + | some s => exact (h ⟨s, (eq s).mpr hx⟩).elim + simp only [Exterior.program, he] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Assignment +end + +/- +# Fixed taps for the two terminal checks + +A complete row groups stacks for the exterior test. The same offsets +are read as finest bundles for the table and internal-wire tests. +No payload bits are identified when forming the arrays. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Coloring PackRows + +variable {F X : Type} {x y : Wire} {S : Scheme F} {D : Dimensions} + +open Classical in +/-- Uses `PackRows.Tape D.u D.v D.K D.p` as the representation. -/ +abbrev Dimensions.Tape (D : Dimensions) := PackRows.Tape D.u D.v D.K D.p + +open Classical in +/-- The value specified by `.inl (i.1, .inr (i.2, .inr (.inr (.inr k))))`. -/ +def Dimensions.userBit (D : Dimensions) (S : Scheme F) (i : D.Addr) (k : D.ExteriorBits) : + D.Decisions S := .inl (i.1, .inr (i.2, .inr (.inr (.inr k)))) + +open Classical in +/-- The value specified by `((finProdFinEquiv (j, p.1)).cast D.width, finProdFinEquiv.symm +p.2)`. -/ +def Dimensions.offset (D : Dimensions) (j : Fin D.q) (p : D.StackBits) : Body D.u D.v D.p := + ((finProdFinEquiv (j, p.1)).cast D.width, finProdFinEquiv.symm p.2) + +open Classical in +/-- The data for the screen construction, including `source`, `tape`, `names`. -/ +structure Screen (D : Dimensions) (S : Scheme F) (x y : Wire) (X : Type) where + /-- The source vertex of each edge. -/ + source : D.Originals x y → X + /-- The `Screen` component of type `D.Decisions S → X`. -/ + tape : D.Decisions S → X + /-- The indexed names of type `Stack.Outer x y ↪ (D.Names → Bool)`. -/ + names : Stack.Outer x y ↪ (D.Names → Bool) + +namespace Screen +variable (Q : Screen D S x y X) + +open Classical in +/-- Builds `Wires S D.u D.v D.K D.p D.a (X ⊕ D.Tape) where control i k` with the specified +`control`, `format`, `head`, `body`. -/ +def int : Wires S D.u D.v D.K D.p D.a (X ⊕ D.Tape) where + control i k := .inl (.inl (Q.tape (.inl (i, .inl k)))) + format i k := .inl (.inl (Q.tape (.inl (i.1, .inr (i.2, .inl k))))) + head i k := .inl (.inl (Q.tape (.inr (i, .inl k)))) + body i := .inl (.inr i) + +open Classical in +/-- In the case `none`, this construction gives `.inl (.inl (Q.tape (D.userBit S i (.inl +()))))`. -/ +def ext : Exterior.Input (X ⊕ D.Tape) D.Addr (Stack.Outer x y) (Packing.Cell D.h) + (Fin D.q) D.Names (Fin D.h) D.StackBits where + names := Q.names + keys := D.cellCode + header i + | none => .inl (.inl (Q.tape (D.userBit S i (.inl ())))) + | some k => .inl (.inl (Q.tape (.inr (i, .inr k)))) + body i + | (j, .inl k) => .inl (.inl (Q.tape (D.userBit S i (.inr (j, k))))) + | (j, .inr p) => .inl (.inr (i, D.offset j p)) + source i s k := .inl (Q.source ((i, s), k)) + +variable [Field F] {G : Diagram F x y} (t : Assignment D S G) (hw : t.Fits) + +open Classical in +/-- The flags of type `Prop`, constructed using `t.layout hw`. -/ +def Flags (hn : 2 * S.m + D.r ≤ D.a) (z : X → Bool) : Prop := + let L := t.layout hw + let c := z ∘ Q.tape + (∀ i b, c (.inl (i, .inl b)) = L.moves i b) ∧ + (∀ i b, c (.inl (i.1, .inr (i.2, .inl b))) = L.format (t.index hw) (labels S t.rows) i b) ∧ + (∀ i b, c (.inr (i, .inl b)) = + bits (word (D.a + 2)) (t.inner.header L hw.position (Channels.code hn) i) b) ∧ + (∀ i, Exterior.flag (c (D.userBit S i (.inl ()))) (fun b => c (.inr (i, .inr b))) = + ((t.descriptor hw).owner i).map Q.names) ∧ + ∀ i j, (t.descriptor hw).owner i = some j → ∀ k, + Exterior.decode (fun b => c (D.userBit S i (.inr (k, b)))) = + ((t.descriptor hw).addr i k).map D.cellCode + +open Classical in +/-- The supplied of type `Bool`, constructed using `(Exterior.ports t.post).symm i`. -/ +def supplied (z : X → Bool) (i : S.exposed t.rows) : Bool := + let a := (Exterior.ports t.post).symm i + z (Q.source (a.1.1, a.1.2, a.2)) + +open Classical in +theorem supplied_at (z : X → Bool) (i : Stack.Outer x y) (s : Packing.Cell D.h) + (j : Fin D.b) (k : Fin D.z) : + Q.supplied t z (Exterior.ports t.post (((i, s), j), k)) = z (Q.source ((i, s), j, k)) := by + simp [supplied] + +open Classical in +theorem inside_at (i : Stack.Outer x y) (s : Packing.Cell D.h) (j : Fin D.b) (k : Fin D.z) : + t.pieces.inside (t.layout hw) (Exterior.ports t.post (((i, s), j), k)).val = + (((t.descriptor hw).place (i, s)).1, D.offset ((t.descriptor hw).place (i, s)).2 (j, k)) := by + unfold Pieces.inside + simp only [Function.Embedding.trans_apply, Equiv.toEmbedding_apply, t.end_bit] + obtain ⟨ha, hb⟩ := t.placement hw i s j + refine Prod.ext ha (Prod.ext (Fin.ext ?_) rfl) + change _ = j.val + D.b * ((t.descriptor hw).place (i, s)).2.val + exact hb.trans (by ring) + +open Classical in +theorem correct_ext (z : X → Bool) (v : D.Tape → Bool) : + Q.ext.Supplied (Sum.elim z v) (t.descriptor hw).owner (t.descriptor hw).addr ↔ + ∀ i, v (t.pieces.inside (t.layout hw) i.val) = Q.supplied t z i := by + rw [Exterior.Descriptor.supplied] + constructor + · intro h i + obtain ⟨⟨⟨⟨j, s⟩, u⟩, k⟩, rfl⟩ := (Exterior.ports t.post).surjective i + rw [inside_at, Q.supplied_at] + exact h j s (u, k) + · rintro h j s ⟨u, k⟩ + specialize h (Exterior.ports t.post (((j, s), u), k)) + rw [inside_at, Q.supplied_at] at h + exact h + +end Screen +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- # Capacity bounds for checking the exterior and interior arrays -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +open PackRows + +variable {F : Type} (D : Dimensions) (S : Assembly.Scheme F) + +/-- A stack has one activity bit, its address and its payload. -/ +abbrev recordWidth := D.h + 1 + D.b * D.z + +/-- The data for the fits screen construction, including `core`, `code`, `wide`, `narrow`, +`small`. -/ +structure FitsScreen (x y : Wire) (w j cap : ℕ) : Prop where + core : Wires.Fits S D.u D.v D.K D.p D.a w j cap + code : 2 * S.m + D.r ≤ D.a + wide : w ≤ D.e + D.q * D.recordWidth + 2 + narrow : D.e + D.q * D.recordWidth + 2 ≤ 4 * w + small : 2 * (D.q * D.recordWidth + 1) < j + slots : D.K * (2 * D.v) + (wd x + wd y) * D.n ≤ 2 ^ j + arity : 2 * 2 ^ (D.h + 2) * (D.recordWidth + 1) + ≤ min cap (min (2 ^ ((Nat.clog 2 w) ^ 3)) (2 ^ (w / 2))) + +variable {D S} {x y : Wire} {w j cap : ℕ} + +theorem FitsScreen.tape (f : D.FitsScreen S x y w j cap) : + Fintype.card D.Tape ≤ 2 ^ j * w := by + simp only [Fintype.card_prod, Fintype.card_fin] + apply Nat.mul_le_mul f.core.slots + change 2 * D.u * D.z ≤ w + have hm := f.core.move + have := f.core.upper + change (4 * D.v * D.u) ^ 2 + 2 * (2 * D.u * D.z) < j at hm + omega + +theorem FitsScreen.supply (f : D.FitsScreen S x y w j cap) : + (wd x + wd y) * 2 ^ (D.h + 2) * (D.h + D.b * D.z + 3) ≤ 6 * 2 ^ j * w := by + have h := f.small + have := f.core.upper + have hw : D.q * D.recordWidth ≤ w := by omega + have hr : D.h + D.b * D.z + 3 ≤ 3 * D.recordWidth := by unfold recordWidth; omega + have hs : (wd x + wd y) * D.n ≤ 2 ^ j := (Nat.le_add_left ..).trans f.slots + calc + _ ≤ (wd x + wd y) * 2 ^ (D.h + 2) * (3 * D.recordWidth) := Nat.mul_le_mul_left _ hr + _ = 6 * ((wd x + wd y) * D.n) * (D.q * D.recordWidth) := by + rw [show 2 ^ (D.h + 2) = 2 * (D.n * D.q) by rw [D.cover, pow_add]; ring] + ring + _ ≤ 6 * 2 ^ j * w := Nat.mul_le_mul (Nat.mul_le_mul_left _ hs) hw + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +end + +/- +# A single terminal evaluator for all supported layouts + +The same weighted network receives original data and all row decisions. +Its scalar value is the ordered-span contraction named by the decisions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Screen +open Assembly PackRows Transcript + +variable {F X : Type} [Field F] {x y : Wire} {S : Scheme F} {D : Dimensions} + (Q : Screen D S x y X) {w j cap : ℕ} + +open Classical in +private theorem valid {G : Diagram F x y} (t : Assignment D S G) (hw : t.Fits) + (hn : 2 * S.m + D.r ≤ D.a) (x : X → Bool) (hx : Q.Flags t hw hn x) (y : D.Tape → Bool) : + Q.ext.Valid D.n (Sum.elim x y) (t.descriptor hw).owner (t.descriptor hw).addr := + (t.descriptor hw).valid _ _ hx.2.2.2.1 hx.2.2.2.2 + +variable [Fintype X] + +open Classical in +private theorem exterior (h : D.FitsScreen S x y w j cap) : + ∃ g : (X ⊕ D.Tape → Bool) → F, + WideWeight F cap (Allowed F w) g (10000000 * (Fintype.card X + 2 ^ j * (1 + w))) ∧ + ∀ (G : Diagram F x y) (t : Assignment D S G) (hw : t.Fits) b, + Q.Flags t hw h.code b → + Wires.correctExterior t.pieces (t.layout hw) (Q.supplied t b) g b := by + have hc : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ cap := by + apply le_trans _ h.core.large + have := h.core.upper + gcongr; omega + have hcard : Fintype.card (Exterior.Body (Fin D.q) (Fin D.h) D.StackBits) = D.q * D.recordWidth + := by + simp [Dimensions.recordWidth] + have hsrc : Fintype.card (Stack.Outer x y) = wd x + wd y := by simp + have room : Fintype.card (Packing.Cell D.h) + D.n * Fintype.card (Fin D.q) ≤ 2 ^ (D.h + 2) := by + rw [Packing.card_cell, Fintype.card_fin, D.cover, pow_add] + omega + obtain ⟨g, hg, he⟩ := Q.ext.supply (F := F) h.core.gates h.core.lower h.core.upper hc + (by rw [hcard, Fintype.card_fin]; exact h.wide) + (by rw [hcard, Fintype.card_fin]; exact h.narrow) + (by rw [hcard]; exact h.small) + (by rw [hsrc, Fintype.card_prod, Fintype.card_fin, Fintype.card_fin]; exact h.slots) room + (by + simp only [Fintype.card_fin, Fintype.card_prod] + have hr := h.arity + rw [show D.recordWidth + 1 = D.h + D.b * D.z + + 2 by unfold Dimensions.recordWidth; omega] at hr + exact hr) + refine ⟨g, ?_, fun G t hw b hb y _ => ?_⟩ + · intro a i + obtain ⟨v, hv, hnet⟩ := hg a i + refine ⟨v, ?_, hnet⟩ + rw [hsrc, Fintype.card_sum, Fintype.card_fin, + show Fintype.card D.StackBits = D.b * D.z by simp] at hv + have ht := h.tape + have hS := h.supply + rw [mul_assoc 6] at hS + have := Nat.mul_le_mul_left (2 ^ j) (Nat.le_add_left w 1) + omega + · rw [he _ _ _ (Q.valid t hw h.code b hb y), Q.correct_ext] + split <;> rfl + +open Classical in +theorem run (h : D.FitsScreen S x y w j cap) : + ∃ g : (X → Bool) → F, WideWeight F cap (Allowed F w) g + (10 ^ 15 * (Fintype.card X + 2 ^ j * (1 + w))) ∧ + ∀ (G : Diagram F x y) (t : Assignment D S G) (hw : t.Fits) b, + Q.Flags t hw h.code b → g b = S.eval t.rows (Q.supplied t b) := by + obtain ⟨f, hf, ef⟩ := Q.exterior h + obtain ⟨g, hg, eg⟩ := Q.int.evaluator h.core sort_allowed f hf + refine ⟨g, ?_, fun G t hw b hb => ?_⟩ + · intro a i + obtain ⟨v, hv, hnet⟩ := hg a i + exact ⟨v, by omega, hnet⟩ + · obtain ⟨π, hπ, hlinks⟩ := t.post.core_plan D.zpos (t.strips.uniform D.zpos) t.external + t.ext_location (t.layout hw) hw.position (Channels.code h.code) + apply eg _ _ _ t.pieces hw.room (t.layout hw) π (Q.supplied t b) b _ + (fun _ => rfl) hlinks (ef _ _ _ _ hb) + intro y + rw [hπ] + exact ⟨fun i => funext (hb.1 i), fun i => funext (hb.2.1 i), + fun i => funext fun k => (hb.2.2.1 i k).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Screen +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Exterior/Strips.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Exterior/Strips.lean new file mode 100644 index 0000000000..32c989cf87 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Exterior/Strips.lean @@ -0,0 +1,811 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Pieces +public import Mathlib.Logic.Equiv.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Plan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.PortRelay +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Exterior.Supply + +/-! +# Padding exterior stacks to whole rows + +Reserve one partial row per occupied holder. Unused slots receive +dummy stacks so the reindexing is a bijection on a fixed tape. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Finset + +variable {S I : Type} [Fintype S] [DecidableEq I] + +open scoped Classical in +/-- A genuine stack and its padding copy occupy distinct slots. -/ +structure Grouping (holder : S → I) (C Q : Type) [Fintype Q] where + /-- Reindexes the data using `S ⊕ S ≃ C × Q`. -/ + order : S ⊕ S ≃ C × Q + same : ∀ s t, (order (.inl s)).1 = (order (.inl t)).1 → holder s = holder t + rows : ∀ i, ((univ.filter fun s => holder s = i).image fun s => (order (.inl s)).1).card ≤ + 1 + Fintype.card {s // holder s = i} / Fintype.card Q + +open scoped Classical in +private theorem padded {B : Type} [Fintype B] (e : S ↪ B) + (hc : Fintype.card B = 2 * Fintype.card S) : + ∃ f : S ⊕ S ≃ B, ∀ s, f (.inl s) = e s := by + let u := Equiv.ofInjective e e.injective + let v := Equiv.Set.sumCompl (Set.range e) + have hb := Fintype.card_congr v + rw [Fintype.card_sum, ← Fintype.card_congr u, hc] at hb + let w : S ≃ ↥(Set.range e)ᶜ := Fintype.equivOfCardEq (by omega) + exact ⟨(u.sumCongr w).trans v, fun _ => rfl⟩ + +open scoped Classical in +/-- The subtype of `t` satisfying `holder t = i`. -/ +abbrev Fiber (holder : S → I) (i : I) := {t // holder t = i} + +open scoped Classical in +/-- Ceiling of the stack count divided by the capacity `q`, with +zero rows for an unoccupied holder. -/ +def needed (holder : S → I) (q : ℕ) (i : I) := + if i ∈ univ.image holder then (Fintype.card (Fiber holder i) - 1) / q + 1 else 0 + +open scoped Classical in +private theorem needed_le (holder : S → I) (q : ℕ) (i : I) : + needed holder q i ≤ (if i ∈ univ.image holder then 1 else 0) + + Fintype.card (Fiber holder i) / q := by + unfold needed + have ht := Nat.div_le_div_right (c := q) (Nat.sub_le (Fintype.card (Fiber holder i)) 1) + split_ifs + · omega + · exact Nat.zero_le _ + +open scoped Classical in +/-- Within each holder the rank fixes both the local row and offset. -/ +def orderedSlot (holder : S → I) (q : ℕ) (hq : 0 < q) (i : I) + (rank : Fiber holder i ≃ Fin (Fintype.card (Fiber holder i))) : + Fiber holder i ↪ Fin (needed holder q i) × Fin q where + toFun t := (⟨(rank t).val / q, by + rw [needed, ite_eq_left (mem_image.mpr ⟨t.val, mem_univ _, t.property⟩)] + exact Nat.lt_succ_of_le (Nat.div_le_div_right (Nat.le_pred_of_lt (rank t).isLt))⟩, + ⟨(rank t).val % q, Nat.mod_lt _ hq⟩) + inj' := by + intro t t' h + apply rank.injective + apply Fin.ext + simpa only [Nat.div_add_mod] using congrArg (fun z => q * z.1.val + z.2.val) h + +open scoped Classical in +private theorem assigned [Finite I] (holder : S → I) (C Q : Type) [Fintype C] [Fintype Q] + (q : ℕ) (hQ : Fintype.card Q = q) (hq : 0 < q) + (hp : (univ.image holder).card * q ≤ Fintype.card S) + (hsize : Fintype.card C * q = 2 * Fintype.card S) + (slot : ∀ i, Fiber holder i ↪ Fin (needed holder q i) × Q) : + ∃ (e : Grouping holder C Q) (r : (Σ i, Fin (needed holder q i)) ↪ C), + ∀ i (s : Fiber holder i), e.order (.inl s.val) = (r ⟨i, (slot i s).1⟩, (slot i s).2) := by + let : Fintype I := Fintype.ofFinite I + let used := univ.image holder + let n := needed holder q + have hsum : (∑ i, Fintype.card (Fiber holder i)) = Fintype.card S := by + rw [← Fintype.card_sigma] + exact Fintype.card_congr (Equiv.sigmaFiberEquiv holder) + have total : (∑ i, n i) * q ≤ Fintype.card C * q := calc + _ ≤ (∑ i, ((if i ∈ used then 1 else 0) + Fintype.card (Fiber holder i) / q)) * q := + Nat.mul_le_mul_right _ (sum_le_sum fun i _ => needed_le holder q i) + _ = used.card * q + ∑ i, Fintype.card (Fiber holder i) / q * q := by + simp [sum_add_distrib, add_mul, sum_mul] + _ ≤ used.card * q + Fintype.card S := by + rw [← hsum] + exact Nat.add_le_add_left (sum_le_sum fun i _ => Nat.div_mul_le_self _ _) _ + _ ≤ _ := by unfold used; omega + obtain ⟨rows⟩ : Nonempty ((Σ i, Fin (n i)) ↪ C) := + Function.Embedding.nonempty_of_card_le (by + simpa using Nat.le_of_mul_le_mul_right total hq) + let e : S ↪ C × Q := (Equiv.sigmaFiberEquiv holder).symm.toEmbedding.trans <| + ((Function.Embedding.refl I).sigmaMap slot).trans <| + (Equiv.sigmaProdDistrib _ _).symm.toEmbedding.trans (rows.prodMap (.refl Q)) + obtain ⟨f, hf⟩ := padded e (by simpa [hQ] using hsize) + have position (i : I) (s : Fiber holder i) : + f (.inl s.val) = (rows ⟨i, (slot i s).1⟩, (slot i s).2) := by + rcases s with ⟨s, rfl⟩ + rw [hf] + rfl + refine ⟨⟨f, ?_, ?_⟩, rows, position⟩ + · intro s t h + rw [position _ ⟨s, rfl⟩, position _ ⟨t, rfl⟩] at h + exact congrArg Sigma.fst (rows.injective h) + · intro i + calc + _ ≤ (univ.image fun j : Fin (n i) => rows ⟨i, j⟩).card := by + apply card_le_card + intro c hc + obtain ⟨s, hs, rfl⟩ := mem_image.mp hc + rw [position _ ⟨s, (mem_filter.mp hs).2⟩] + exact mem_image_of_mem _ (mem_univ _) + _ ≤ n i := by simpa using (card_image_le (s := univ) (f := fun j : Fin (n i) => rows ⟨i, j⟩)) + _ ≤ _ := by + rw [hQ] + exact (needed_le holder q i).trans (Nat.add_le_add_right (by split_ifs <;> omega) _) + +open scoped Classical in +/-- If one row per occupied holder fits in the padding budget, doubling +the stack count suffices, preserving any prescribed order inside each holder. -/ +theorem group_order [Finite I] (holder : S → I) (C : Type) [Fintype C] (q : ℕ) (hq : 0 < q) + (hp : (univ.image holder).card * q ≤ Fintype.card S) + (hsize : Fintype.card C * q = 2 * Fintype.card S) + (rank : ∀ i, Fiber holder i ≃ Fin (Fintype.card (Fiber holder i))) : + ∃ (e : Grouping holder C (Fin q)) (r : (Σ i, Fin (needed holder q i)) ↪ C), + ∀ i (s : Fiber holder i), e.order (.inl s.val) = + (r ⟨i, (orderedSlot holder q hq i (rank i) s).1⟩, (orderedSlot holder q hq i (rank i) s).2) + := + assigned holder C (Fin q) q (Fintype.card_fin _) hq hp hsize + (fun i => orderedSlot holder q hq i (rank i)) + +open scoped Classical in +theorem group [Finite I] (holder : S → I) (C Q : Type) [Fintype C] [Fintype Q] + (hq : 0 < Fintype.card Q) (hp : (univ.image holder).card * Fintype.card Q ≤ Fintype.card S) + (hsize : Fintype.card C * Fintype.card Q = 2 * Fintype.card S) : + Nonempty (Grouping holder C Q) := by + let : Fintype I := Fintype.ofFinite I + obtain ⟨e, _⟩ := assigned holder C Q _ rfl hq hp hsize fun i => + (orderedSlot holder _ hq i (Fintype.equivFin _)).trans <| + (Function.Embedding.refl _).prodMap (Fintype.equivFin Q).symm.toEmbedding + exact ⟨e⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +/- # Canonical port ordinals for exterior stacks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Finset + +variable {J S : Type} [Fintype J] [Fintype S] {H m d : ℕ} + (loc : J → S → Fin H × Fin m) (χ : Fin H → J → Fin d) + +open scoped Classical in +/-- The value specified by `(loc x.1 x.2, χ (loc x.1 x.2).1 x.1)`. -/ +def position (x : J × S) := (loc x.1 x.2, χ (loc x.1 x.2).1 x.1) + +open scoped Classical in +/-- Evaluates `Fintype.card {x // position loc χ x = ((i, t), c)}` at the input `i t c`. -/ +def counts : PackRows.Inventory H m d := + fun i t c => Fintype.card {x // position loc χ x = ((i, t), c)} + +open scoped Classical in +/-- Evaluates `counts loc χ i t c * b` at the input `i t c`. -/ +def lengths (b : ℕ) : PackRows.Inventory H m d := fun i t c => counts loc χ i t c * b + +open scoped Classical in +theorem lengths_eq (b : ℕ) (i : Fin H) (t : Fin m) (c : Fin d) : + lengths loc χ b i t c = + (univ.filter fun x : J × S => loc x.1 x.2 = (i, t) ∧ χ (loc x.1 x.2).1 x.1 = c).card * b := by + simp only [lengths, counts, Fintype.card_subtype, position, Prod.mk.injEq] + +open scoped Classical in +/-- Reindexes `(Σ z : (Fin H × Fin m) × Fin d, Fin (l z.1.1 z.1.2 z.2))` and `PackRows.Endpoints +l where toFun p` by an equivalence. -/ +def flattenFromPoints (l : PackRows.Inventory H m d) : + (Σ z : (Fin H × Fin m) × Fin d, Fin (l z.1.1 z.1.2 z.2)) ≃ PackRows.Endpoints l where + toFun p := ⟨p.1.1.1, p.1.1.2, p.1.2, p.2⟩ + invFun p := ⟨((p.1, p.2.1), p.2.2.1), p.2.2.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +open scoped Classical in +/-- Reindexes `A` and `Fin (Fintype.card A)` by an equivalence. -/ +def sortedIndex {A : Type} [Fintype A] (key : A → ℕ) (hk : Function.Injective key) : + A ≃ Fin (Fintype.card A) := + let e : A ≃ Σ _ : A, Fin 1 := + ⟨fun x => ⟨x, 0⟩, Sigma.fst, fun _ => rfl, fun x => by + rcases x with ⟨x, i⟩; rw [Fin.eq_zero i]⟩ + (e.trans (Routing.pack (fun _ => 1) key (fun _ _ _ _ he => hk he))).trans (finCongr (by simp)) + +open scoped Classical in +/-- Reindexes `J × S` and `Fin (Fintype.card J * Fintype.card S)` by an equivalence. -/ +def index : J × S ≃ Fin (Fintype.card J * Fintype.card S) := + ((Fintype.equivFin J).prodCongr (Fintype.equivFin S)).trans finProdFinEquiv + +open scoped Classical in +/-- Reindexes `Fiber (position loc χ) z` and `Fin (Fintype.card (Fiber (position loc χ) z))` by +an equivalence. -/ +def orderedAt (z : (Fin H × Fin m) × Fin d) : + Fiber (position loc χ) z ≃ Fin (Fintype.card (Fiber (position loc χ) z)) := + sortedIndex (fun t => (index t.val).val) + (Fin.val_injective.comp (index.injective.comp Subtype.val_injective)) + +open scoped Classical in +/-- Reindexes `J × S` and `PackRows.Endpoints (counts loc χ)` by an equivalence. -/ +def stack : J × S ≃ PackRows.Endpoints (counts loc χ) := + (Equiv.sigmaFiberEquiv (position loc χ)).symm.trans <| + (Equiv.sigmaCongrRight (orderedAt loc χ)).trans + (flattenFromPoints (counts loc χ)) + +open scoped Classical in +/-- The position of a stack on its channel depends only on the +stack indices present at the same occurrence. -/ +theorem stack_slot + (sep : ∀ i j a b, (loc i a).1 = (loc j b).1 → χ (loc i a).1 i = χ (loc j b).1 j → i = j) + (i : J) (s : S) : + (stack loc χ (i, s)).2.2.2.val = + (univ.filter fun t => loc i t = loc i s ∧ Fintype.equivFin S t < Fintype.equivFin S s).card + := by + let pos := position loc χ + let key : J × S → ℕ := fun t => (index t).val + change (∑ _t ∈ (univ.filter fun t : Fiber pos (pos (i, s)) => key t.val < key (i, s)), 1) = _ + rw [sum_filter, ← sum_subtype (univ.filter fun z => pos z = pos (i, s)) + (fun _ => mem_filter_univ _) (fun z => if key z < key (i, s) then 1 else 0), sum_filter, + Fintype.sum_prod_type, sum_eq_single i] + · rw [card_eq_sum_ones, sum_filter] + refine sum_congr rfl fun t _ => ?_ + have he : key (i, t) < key (i, s) ↔ Fintype.equivFin S t < Fintype.equivFin S s := by + change _ + Fintype.card S * (Fintype.equivFin J i).val < + _ + Fintype.card S * (Fintype.equivFin J i).val ↔ _ + exact Nat.add_lt_add_iff_right + by_cases h : loc i t = loc i s <;> simp [pos, position, h, he] + · intro j _ hj + refine sum_eq_zero fun t _ => ite_eq_right ?_ + intro he + exact hj (sep j i t s (congrArg (fun z => z.1.1) he) (congrArg Prod.snd he)) + · simp + +open scoped Classical in +/-- Reindexes `PackRows.Endpoints l × Fin b` and `PackRows.Endpoints (fun i t c => l i t c * b) +where toFun p` by an equivalence. -/ +def scale (l : PackRows.Inventory H m d) (b : ℕ) : + PackRows.Endpoints l × Fin b ≃ PackRows.Endpoints (fun i t c => l i t c * b) where + toFun p := ⟨p.1.1, p.1.2.1, p.1.2.2.1, finProdFinEquiv (p.1.2.2.2, p.2)⟩ + invFun p := (⟨p.1, p.2.1, p.2.2.1, (finProdFinEquiv.symm p.2.2.2).1⟩, + (finProdFinEquiv.symm p.2.2.2).2) + left_inv p := by simp + right_inv p := by + obtain ⟨i, t, c, j⟩ := p + simp only [Prod.mk.eta, Equiv.apply_symm_apply] + +open scoped Classical in +/-- All finest bundles of a stack are consecutive at its port. -/ +def point (b : ℕ) : (J × S) × Fin b ≃ PackRows.Endpoints (lengths loc χ b) := + ((stack loc χ).prodCongr (.refl _)).trans (scale _ b) + +open scoped Classical in +@[simp] theorem point_host {b : ℕ} (i : J) (s : S) (k : Fin b) : + (point loc χ b ((i, s), k)).1 = (loc i s).1 := rfl + +open scoped Classical in +@[simp] theorem point_block {b : ℕ} (i : J) (s : S) (k : Fin b) : + (point loc χ b ((i, s), k)).2.1 = (loc i s).2 := rfl + +open scoped Classical in +@[simp] theorem point_channel {b : ℕ} (i : J) (s : S) (k : Fin b) : + (point loc χ b ((i, s), k)).2.2.1 = χ (loc i s).1 i := rfl + +open scoped Classical in +theorem point_slot {b : ℕ} (x : J × S) (k : Fin b) : + (point loc χ b (x, k)).2.2.2.val = (stack loc χ x).2.2.2.val * b + k.val := by + change k.val + b * (stack loc χ x).2.2.2.val = _ + ac_rfl + +open scoped Classical in +theorem point_rank {b : ℕ} (x : J × S) (k : Fin b) : + PackRows.rank _ (point loc χ b (x, k)) = PackRows.rank _ (stack loc χ x) * b + k.val := by + let z := stack loc χ x + change PackRows.start (fun i => counts loc χ z.1 i z.2.2.1 * b) z.2.1 + + (finProdFinEquiv (z.2.2.2, k)).val = PackRows.rank _ z * b + k.val + simp only [PackRows.rank, PackRows.start, PackRows.port, Routing.offset, ← sum_mul, + show (finProdFinEquiv (z.2.2.2, k)).val = k.val + b * z.2.2.2.val from rfl, Nat.add_mul] + ac_rfl + +open scoped Classical in +private def listPorts (l : PackRows.Inventory H m d) : + PackRows.Endpoints l ≃ (Σ z : Fin H × Fin d, PackRows.Blocks (PackRows.port (l z.1) z.2)) where + toFun p := ⟨(p.1, p.2.2.1), p.2.1, p.2.2.2⟩ + invFun p := ⟨p.1.1, p.2.1, p.1.2, p.2.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +open scoped Classical in +/-- If names sharing a holder always use different channels, the +port ordinals enumerate exactly the stacks of one name at that holder. -/ +theorem port_ordinals + (sep : ∀ i j a b, (loc i a).1 = (loc j b).1 → χ (loc i a).1 i = χ (loc j b).1 j → i + = j) (i : J) (v : Fin H) : + let A := Fiber (fun s => (loc i s).1) v + ∃ rank : A ≃ Fin (Fintype.card A), ∀ s : A, + (rank s).val = PackRows.rank _ (stack loc χ (i, s.val)) := by + intro A + by_cases hn : Nonempty A + swap + · exact ⟨Fintype.equivFin _, fun s => (hn ⟨s⟩).elim⟩ + let n (z : Fin H × Fin d) := ∑ t, counts loc χ z.1 t z.2 + let e : J × S ≃ Σ z, Fin (n z) := ((stack loc χ).trans (listPorts _)).trans + (Equiv.sigmaCongrRight fun _ => PackRows.order _) + have key (s : A) : (e (i, s.val)).1 = (v, χ v i) := + Prod.ext s.property (congrArg (fun a => χ a i) s.property) + let pos (s : A) : Fin (n (v, χ v i)) := (e (i, s.val)).2.cast (congrArg n (key s)) + have hi : Function.Injective pos := by + intro s t h + have he := (key s).trans (key t).symm + have eq : e (i, s.val) = e (i, t.val) := + Sigma.ext he ((Fin.heq_ext_iff (congrArg n he)).mpr (congrArg Fin.val h)) + exact Subtype.ext (congrArg Prod.snd (e.injective eq)) + have hr : Function.Surjective pos := by + intro k + obtain ⟨⟨j, t⟩, he⟩ := e.surjective ⟨(v, χ v i), k⟩ + have hv : (loc j t).1 = v := congrArg (fun a => a.1.1) he + have hc : χ (loc j t).1 j = χ v i := congrArg (fun a => a.1.2) he + have := sep j i t hn.some.val (hv.trans hn.some.property.symm) + (hc.trans (congrArg (fun a => χ a i) hn.some.property.symm)) + subst j + exact ⟨⟨t, hv⟩, Fin.ext (congrArg (fun z => z.2.val) he)⟩ + let f := Equiv.ofBijective pos ⟨hi, hr⟩ + have hc : n (v, χ v i) = Fintype.card A := by simpa using Fintype.card_congr f.symm + exact ⟨f.trans (finCongr hc), fun _ => rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +/- # Aligning exterior stacks with the port rows of a contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Finset PackRows + +variable {J S C : Type} [Fintype J] [Fintype S] [Fintype C] {H m d b q u v K : ℕ} + +open scoped Classical in +private theorem split (n q b : ℕ) (hq : 0 < q) (k : Fin b) : + (n * b + k.val) / (q * b) = n / q ∧ (n * b + k.val) % (q * b) = n % q * b + k.val := by + have hb : 0 < b := by have := k.isLt; omega + have lo : n % q * b + k.val < q * b := calc + _ < n % q * b + b := Nat.add_lt_add_left k.isLt _ + _ = (n % q + 1) * b := by rw [Nat.add_mul, Nat.one_mul] + _ ≤ _ := Nat.mul_le_mul_right _ (Nat.mod_lt n hq) + have he : n * b + k.val = (q * b) * (n / q) + (n % q * b + k.val) := by + rw [← Nat.add_assoc, Nat.mul_right_comm q b, ← Nat.add_mul, Nat.div_add_mod] + rw [he, Nat.mul_add_div (Nat.mul_pos hq hb), Nat.div_eq_of_lt lo, Nat.add_zero, + Nat.mul_add_mod, Nat.mod_eq_of_lt lo] + exact ⟨rfl, rfl⟩ + +open scoped Classical in +private theorem aligned (holder : S → Fin H) (ordinal : S → ℕ) + (rank : ∀ i, Fiber holder i ≃ Fin (Fintype.card (Fiber holder i))) + (hr : ∀ i s, (rank i s).val = ordinal s.val) + (hq : 0 < q) (hp : (univ.image holder).card * q ≤ Fintype.card S) + (hsize : Fintype.card C * q = 2 * Fintype.card S) : + ∃ e : S ⊕ S ≃ C × Fin q, + (∀ s, (e (.inl s)).2.val = ordinal s % q) ∧ + (∀ s t, (e (.inl s)).1 = (e (.inl t)).1 ↔ + holder s = holder t ∧ ordinal s / q = ordinal t / q) := by + obtain ⟨e, r, he⟩ := group_order holder C q hq hp hsize rank + have pos (s : S) := he (holder s) ⟨s, rfl⟩ + refine ⟨e.order, fun s => ?_, fun s t => ?_⟩ + · rw [pos s] + change (rank _ _).val % q = _ + rw [hr] + · constructor + · intro h + refine ⟨e.same _ _ h, ?_⟩ + rw [pos s, pos t] at h + have h' := congrArg (fun z => z.2.val) (r.injective h) + change (rank _ _).val / q = (rank _ _).val / q at h' + simpa only [hr] using h' + · rintro ⟨hh, ho⟩ + rw [he (holder t) ⟨s, hh⟩, pos t] + apply congrArg (fun j => r ⟨holder t, j⟩) + apply Fin.ext + change (rank _ _).val / q = (rank _ _).val / q + simpa only [hr] using ho + +variable (loc : J → S → Fin H × Fin m) (χ : Fin H → J → Fin d) {d' : ℕ} + +open scoped Classical in +/-- For the prescribed port order, all active exterior rows pair +one-to-one with their inside rows. The within-row offset is unchanged. -/ +theorem pack_ports (sep : ∀ i j a b, (loc i a).1 = (loc j b).1 → χ (loc i a).1 i + = χ (loc j b).1 j → i = j) + (hq : 0 < q) (cap : ∀ i, (univ.image fun s => (loc i s).1).card * q ≤ Fintype.card S) + (hsize : Fintype.card C * q = 2 * Fintype.card S) (width : q * b = 2 * u) + (l : Inventory H m d') (L : PackRows.Layout (append l (lengths loc χ b)) u v K) : + let slot := fun i s k => L.portSlots (extendR l _ (point loc χ b ((i, s), k))) + ∃ e : J → S ⊕ S ≃ C × Fin q, + (∀ i s k, (slot i s k).2.val = (e i (.inl s)).2.val * b + k.val) ∧ + (∀ i j s t k a, (slot i s k).1 = (slot j t a).1 ↔ + i = j ∧ (e i (.inl s)).1 = (e j (.inl t)).1) := by + intro slot + let ord i s := rank _ (stack loc χ (i, s)) + choose f hf using port_ordinals loc χ sep + choose e epos erow using fun i => aligned (fun s => (loc i s).1) (ord i) + (f i) (hf i) hq (cap i) hsize + refine ⟨e, ?_, ?_⟩ + · intro i s k + rw [epos] + unfold slot + rw [L.ordinal, rank_extendR, point_rank, ← width] + exact (split (ord i s) q b hq k).2 + · intro i j s t k a + unfold slot + rw [L.row_eq, and_assoc, rank_extendR, rank_extendR, point_rank, point_rank, ← width, + (split _ q b hq k).1, (split _ q b hq a).1] + change ((loc i s).1 = (loc j t).1 ∧ Fin.natAdd d' (χ (loc i s).1 i) + = Fin.natAdd d' (χ (loc j t).1 j) ∧ + ord i s / q = ord j t / q) ↔ _ + constructor + · rintro ⟨hm, hh, ho⟩ + have := sep i j s t hm ((Fin.natAddEmb d').injective hh) + subst j + exact ⟨rfl, (erow i s t).mpr ⟨hm, ho⟩⟩ + · rintro ⟨rfl, hh⟩ + obtain ⟨hm, ho⟩ := (erow i s t).mp hh + exact ⟨hm, by rw [hm], ho⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +section +/- +# Arity of the short exterior sorts + +Stack addresses grow at most quadratically in the beat count. The +payload covers the address, and the logarithm of the entire table +arity fits both caps for a short sorting vertex. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Filter + +theorem limits (v B : ℕ) : + ∀ᶠ j : ℕ in atTop, ∀ h p w : ℕ, h ≤ v * j ^ 2 → 2 ^ j ≤ p → p ≤ w → w ≤ 2 ^ (2 * B * j) → + h + 4 ≤ p ∧ 2 * 2 ^ (h + 2) * (h + 1 + p + 2) ≤ min (2 ^ ((Nat.clog 2 w) ^ 3)) (2 ^ (w / 2)) + := by + let k := v + 4 + 2 * B + filter_upwards [eventually_ge_atTop (2 * k), replication (by norm_num : (0 : ℝ) < 1) (2 * k)] + with j hj hr h p w hh hp hw he + have hj' : 1 ≤ j := by unfold k at hj; omega + have hq : h + 4 + 2 * B * j ≤ k * j ^ 2 := by + unfold k + nlinarith only [hh, Nat.mul_le_mul_left (2 * B) (show j ≤ j ^ 2 by nlinarith), + show 1 ≤ j ^ 2 by nlinarith] + have hf : 2 * (k * j ^ 2) ≤ 2 ^ j := by + have hm := hr (2 ^ j) le_rfl + rw [Real.rpow_one] at hm + have hn : (2 : ℕ) ^ (2 * k * j ^ 2) ≤ 2 ^ (2 ^ j) := by exact_mod_cast hm + simpa [mul_assoc] using (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp hn + have hl : h + 4 ≤ p := by omega + have hn : j ≤ Nat.clog 2 w := + (Nat.clog_pow 2 j (by decide)).symm.le.trans (Nat.clog_mono_right 2 (hp.trans hw)) + have htop : k * j ^ 2 ≤ (Nat.clog 2 w) ^ 3 := calc + _ ≤ j * j ^ 2 := Nat.mul_le_mul_right _ (by omega) + _ = j ^ 3 := by ring + _ ≤ _ := Nat.pow_le_pow_left hn _ + refine ⟨hl, le_trans ?_ (le_min (Nat.pow_le_pow_right (by decide) (hq.trans htop)) + (Nat.pow_le_pow_right (by decide) (show h + 4 + 2 * B * j ≤ w / 2 by omega)))⟩ + calc + _ ≤ 2 * 2 ^ (h + 2) * (2 * 2 ^ (2 * B * j)) := Nat.mul_le_mul_left _ (by omega) + _ = _ := by simp only [pow_add]; ring + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +/- # Exterior row capacity and channels on the reduced host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Finset Packing PackRows + +namespace Exterior + +open scoped Classical in +theorem arity {J S : Type} [Fintype J] [Fintype S] {H m d : ℕ} + (loc : J → S → Fin H × Fin m) (χ : Fin H → J → Fin d) (b : ℕ) (i : Fin H) (t : Fin m) : + PackRows.arity (lengths loc χ b i) t = + (univ.filter fun x : J × S => loc x.1 x.2 = (i, t)).card * b := by + simp only [PackRows.arity, lengths_eq, ← sum_mul] + congr 1 + simp only [card_eq_sum_ones, sum_filter] + rw [sum_comm] + apply sum_congr rfl + intro x _ + by_cases h : loc x.1 x.2 = (i, t) <;> simp [h] + +end Exterior +namespace Stack.Holders + +variable {F : Type} {x y : Wire} {h u a z K H m : ℕ} {G : Diagram F x y} + {Q : HostNet F (fringe (copies x (2 ^ h * u)) (copies y (2 ^ h * u))) a z} + (p : Holders G Q K) (f : Q.V ↪ Fin H) (g : Cell a ↪ Fin m) + +open scoped Classical in +/-- The value specified by `(f (p.core i t), g (p.block t))`. -/ +def loc (i : Outer x y) (t : Cell h) := (f (p.core i t), g (p.block t)) + +open scoped Classical in +/-- Assign local channels to exactly the exterior names reaching a site. -/ +theorem channels (d : ℕ) (hd : 0 < d) + (names : ∀ v, (univ.filter fun i : Outer x y => ∃ t, p.core i t = v).card ≤ d) : + ∃ χ : Fin H → Outer x y → Fin d, ∀ i j s t, + (p.loc f g i s).1 = (p.loc f g j t).1 → + χ (p.loc f g i s).1 i = χ (p.loc f g j t).1 j → i = j := by + let A (v : Fin H) := univ.filter fun i => ∃ t, (p.loc f g i t).1 = v + have lim (v : Fin H) : (A v).card ≤ d := by + by_cases hv : ∃ z, f z = v + · obtain ⟨z, rfl⟩ := hv + simpa [A, loc, f.injective.eq_iff] using names z + · have no i t : (p.loc f g i t).1 ≠ v := fun he => hv ⟨_, he⟩ + simp [A, no] + let code (v : Fin H) : ↥(A v) ↪ Fin d := + Classical.choice (Function.Embedding.nonempty_of_card_le (by simpa using lim v)) + let χ (v : Fin H) (i : Outer x y) := if hi : i ∈ A v then code v ⟨i, hi⟩ else ⟨0, hd⟩ + refine ⟨χ, fun i j s t eq he => ?_⟩ + have hi : i ∈ A (p.loc f g j t).1 := mem_filter.mpr ⟨mem_univ _, s, eq⟩ + have hj : j ∈ A (p.loc f g j t).1 := mem_filter.mpr ⟨mem_univ _, t, rfl⟩ + rw [eq] at he + simp only [χ, dite_eq_left hi, dite_eq_left hj] at he + exact congrArg Subtype.val ((code _).injective he) + +open scoped Classical in +/-- Relative to one original name, the tail blocks pay for the final +partial row at every holder. -/ +theorem capacity (k q : ℕ) (ha : a ≤ h) (hK : k * q ≤ 2 ^ a) + (reach : ∀ i, (univ.image (p.core i)).card ≤ k * 2 ^ (h - a)) (i : Outer x y) : + (univ.image fun t => (p.loc f g i t).1).card * q ≤ Fintype.card (Cell h) := by + have hc : (univ.image fun t => (p.loc f g i t).1).card ≤ (univ.image (p.core i)).card := by + change (univ.image (f ∘ p.core i)).card ≤ _ + rw [← image_image] + exact card_image_le + calc + _ ≤ (k * 2 ^ (h - a)) * q := Nat.mul_le_mul_right _ (hc.trans (reach i)) + _ = k * q * 2 ^ (h - a) := by ring + _ ≤ 2 ^ a * 2 ^ (h - a) := Nat.mul_le_mul_right _ hK + _ = _ := by rw [← pow_add, Nat.add_sub_of_le ha, card_cell] + +open scoped Classical in +/-- The external port inventory counts all exposed bits, in units of +final bundle width. -/ +theorem load_eq {d b : ℕ} (χ : Fin H → Outer x y → Fin d) (hu : u = b * z) (v : Q.V) (t : Cell a) : + (PackRows.arity (Exterior.lengths (p.loc f g) χ b (f v)) (g t) : ℝ) * z = + (Q.tetherLoad (v, t) : ℝ) := by + rw [HostNet.tetherLoad, port_load] + rw [Exterior.arity, Nat.cast_mul, mul_assoc, ← Nat.cast_mul, ← hu, push, + ← (bit h u x y).sum_comp] + rw [Fintype.sum_prod_type, sum_comm] + simp_rw [Fintype.sum_prod_type, Function.comp_apply, p.tip, sum_const, card_univ, + Fintype.card_fin, nsmul_eq_mul] + rw [← sum_boole, sum_mul, Fintype.sum_prod_type] + simp only [loc, Prod.mk.injEq, f.injective.eq_iff, g.injective.eq_iff, mul_comm] + +end Stack.Holders +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Naming the finest exterior bundles by their source stack -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {h z c a K : ℕ} + +namespace Stack + +/-- Reindexes `((Outer x y × Cell h) × Fin c) × Fin z` and `Outer (copies x (2 ^ h * (c * z))) +(copies y (2 ^ h * (c * z)))` by an equivalence. -/ +abbrev strips (h c z : ℕ) (x y : Wire) : + ((Outer x y × Cell h) × Fin c) × Fin z ≃ + Outer (copies x (2 ^ h * (c * z))) (copies y (2 ^ h * (c * z))) := + (Equiv.prodAssoc _ _ _).trans <| ((Equiv.refl _).prodCongr finProdFinEquiv).trans <| + (Equiv.prodAssoc _ _ _).trans <| (Equiv.prodComm _ _).trans (bit h (c * z) x y) + +end Stack + +namespace Exterior + +variable {S : Scheme F} {r : S.format.obj} {D : Diagram F x y} + +theorem boundary_owner (p : S.Presentation r D) (i : Stack.Outer x y) : + (p.boundary i).val.1.1 = p.vertex (portEnd D i) := by + have H (j : D.End) : (p.toSeating.ends j).1.1 = p.vertex (D.station j) := by + obtain ⟨⟨k, t⟩, rfl⟩ := D.portEquiv.surjective j + rw [p.toSeating.ends_at, D.station_port] + rfl + cases i with + | inl i => exact H (.inl (.inl i)) + | inr i => exact H (.inr (.inl i)) + +variable {Q : HostNet F (Stack.fringe (copies x (2 ^ h * (c * z))) (copies y (2 ^ h * (c * z)))) a + z} + (p : S.Posting r Q) (L : Stack.Holders D Q K) + +/-- The value specified by `(Stack.strips h c z x y).trans p.toPresentation.boundary`. -/ +abbrev ports := (Stack.strips h c z x y).trans p.toPresentation.boundary + +theorem ports_at (i : Stack.Outer x y) (b : Cell h) (j : Fin c) (t : Fin z) : + (ports p (((i, b), j), t)).val.1.1 = (p.host (L.core i b), p.block (L.block b), 0) := by + change (p.toPresentation.boundary (Stack.bit _ _ _ _ ((b, finProdFinEquiv (j, t)), i))).val.1.1 + = _ + rw [boundary_owner, p.vertex_eq, L.tip] + +theorem addresses {d : ℕ} (χ : Fin (2 ^ S.m) → Stack.Outer x y → Fin d) + (hz : 0 < z) (he : Strips (ports p)) : + let loc := L.loc p.host p.block + ∃ e : outer S r z ≃ PackRows.Endpoints (lengths loc χ c), + (∀ j, (e j).1 = j.val.1 ∧ (e j).2.1 = j.val.2.1) ∧ + ∀ i t, ports p (i, t) = + toOuter (p.all_uniform (he.uniform hz)) (e.symm (point loc χ c i)) t := by + intro loc + obtain ⟨f, hf⟩ := Strips.segments (p.all_uniform (he.uniform hz)) he hz + let e := f.symm.trans (point loc χ c) + refine ⟨e, ?_, ?_⟩ + · intro j + obtain ⟨⟨⟨i, b⟩, u⟩, rfl⟩ := f.surjective j + rw [show e (f ((i, b), u)) = point loc χ c ((i, b), u) from + congrArg (point loc χ c) (f.symm_apply_apply _)] + have hv := ports_at p L i b u ⟨0, hz⟩ + rw [hf] at hv + exact ⟨(congrArg Prod.fst hv).symm, (congrArg (fun a => a.2.1) hv).symm⟩ + · intro i t + simp only [e, Equiv.symm_trans_apply, Equiv.symm_symm, Equiv.symm_apply_apply] + exact hf i t + +end Exterior +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Exterior descriptors for a canonical port layout -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Finset + +open scoped Classical in +/-- The name belongs to the row. Only the stack address is needed for +each active payload inside that row. -/ +structure Descriptor (J S I Q : Type) [Fintype I] (n : ℕ) where + /-- Embeds the coordinates as `J × S ↪ I × Q`. -/ + place : J × S ↪ I × Q + /-- The owner assigned to each element of type `I → Option J`. -/ + owner : I → Option J + /-- The `Descriptor` component of type `I → Q → Option S`. -/ + addr : I → Q → Option S + owner_eq : ∀ i j, owner i = some j ↔ ∃ s, (place (j, s)).1 = i + addr_eq : ∀ i q j s, owner i = some j ∧ addr i q = some s ↔ place (j, s) = (i, q) + bound : ∀ j, count owner j ≤ n + +variable {J S I Q : Type} [Fintype I] {n : ℕ} + +namespace Descriptor +variable (D : Descriptor J S I Q n) + +open scoped Classical in +theorem cover (j : J) (s : S) : ∃! a : I × Q, D.owner a.1 = some j ∧ D.addr a.1 a.2 = some s := + ⟨D.place (j, s), (D.addr_eq _ _ _ _).mpr rfl, fun _ h => ((D.addr_eq _ _ _ _).mp h).symm⟩ + +variable {X N K P : Type} (B : Input X I J S Q N K P) (x : X → Bool) + +open scoped Classical in +theorem valid (name : ∀ i, (B.header i).read x = (D.owner i).map B.names) + (addr : ∀ i j, D.owner i = some j → ∀ q, decode (fun k => B.payload x i (q, .inl k)) = + (D.addr i q).map B.keys) : B.Valid n x D.owner D.addr := by + refine ⟨name, ?_, D.cover, D.bound⟩ + intro i j hi q + have := addr i j hi q + have h := congrArg (Option.map (fun f : K → Bool => Sum.elim f (fun p => B.payload x i (q, + .inr p)))) this + unfold stackRead + unfold decode at h + cases hb : B.payload x i (q, .inl none) <;> simp only [hb, Bool.false_eq_true, ite_false, + ite_true, + Option.map_none, Option.map_some, Option.map_map] at h ⊢ <;> exact h + +open scoped Classical in +theorem supplied : B.Supplied x D.owner D.addr ↔ ∀ j s t, + B.payload x (D.place (j, s)).1 ((D.place (j, s)).2, .inr t) = x (B.source j s t) := by + constructor + · intro h j s t + obtain ⟨hv, hs⟩ := (D.addr_eq _ _ j s).mpr (Prod.mk.eta (p := D.place (j, s))).symm + exact congrFun (h _ _ _ _ hv hs) t + · intro h i j k s hv hs + have he := (D.addr_eq i k j s).mp ⟨hv, hs⟩ + funext t + simpa only [he, Function.comp_apply] using h j s t + +end Descriptor + +open scoped Classical in +private theorem descriptor [Fintype S] (loc : J × S ↪ I × Q) + (same : ∀ a b, (loc a).1 = (loc b).1 → a.1 = b.1) + (cap : ∀ j, (univ.image fun s => (loc (j, s)).1).card ≤ n) : + ∃ D : Descriptor J S I Q n, D.place = loc := by + let owner i := if h : ∃ x, (loc x).1 = i then some h.choose.1 else none + let addr i q := if h : ∃ x, loc x = (i, q) then some h.choose.2 else none + have ho i j : owner i = some j ↔ ∃ s, (loc (j, s)).1 = i := by + unfold owner + split + · rename_i h + refine ⟨fun he => ?_, fun ⟨s, hs⟩ => congrArg some (same _ _ (h.choose_spec.trans hs.symm))⟩ + rw [← Option.some.inj he] + exact ⟨h.choose.2, h.choose_spec⟩ + · rename_i h + exact iff_of_false (by simp) (fun ⟨s, hs⟩ => h ⟨(j, s), hs⟩) + refine ⟨⟨loc, owner, addr, ho, ?_, ?_⟩, rfl⟩ + · intro i q j s + constructor + · rintro ⟨ho', ha⟩ + unfold addr at ha + split at ha + · rename_i h + obtain ⟨t, ht⟩ := (ho i j).mp ho' + have hj := same h.choose (j, t) ((congrArg Prod.fst h.choose_spec).trans ht.symm) + have eq : h.choose = (j, s) := Prod.ext hj (Option.some.inj ha) + exact eq ▸ h.choose_spec + · cases ha + · intro he + have h : ∃ x, loc x = (i, q) := ⟨_, he⟩ + exact ⟨(ho i j).mpr ⟨s, congrArg Prod.fst he⟩, + by simp only [addr, dite_eq_left h, loc.injective (h.choose_spec.trans he.symm)]⟩ + · intro j + rw [count, sum_boole, Nat.cast_id] + refine le_trans (card_le_card ?_) (cap j) + intro i hi + obtain ⟨s, hs⟩ := (ho i j).mp (mem_filter.mp hi).2 + exact mem_image.mpr ⟨s, mem_univ _, hs⟩ + +variable [Fintype J] [Fintype S] {H m d b q u v K d' : ℕ} + (loc : J → S → Fin H × Fin m) (χ : Fin H → J → Fin d) + +open scoped Classical in +/-- Construct a descriptor for the rows that actually carry exterior +stacks. The output agreement is stated at every finest bundle. -/ +theorem make_descriptor (sep : ∀ i j a b, (loc i a).1 = (loc j b).1 → + χ (loc i a).1 i = χ (loc j b).1 j → i = j) + (hb : 0 < b) (hq : 0 < q) + (cap : ∀ i, (univ.image fun s => (loc i s).1).card * q ≤ Fintype.card S) + (size : n * q = 2 * Fintype.card S) (width : q * b = 2 * u) + (l : PackRows.Inventory H m d') (L : PackRows.Layout (PackRows.append l (lengths loc χ b)) u v + K) : + let slot := fun i s k => L.portSlots (PackRows.extendR l _ (point loc χ b ((i, s), k))) + ∃ D : Descriptor J S (PackRows.Address v K) (Fin q) n, + ∀ i s k, (slot i s k).1 = (D.place (i, s)).1 ∧ + (slot i s k).2.val = (D.place (i, s)).2.val * b + k.val := by + intro slot + obtain ⟨e, he, hr⟩ := pack_ports (C := Fin n) loc χ sep hq cap (by simpa using size) width l L + let k : Fin b := ⟨0, hb⟩ + let f (z : J × S) := ((slot z.1 z.2 k).1, (e z.1 (.inl z.2)).2) + have same (x y : J × S) (h : (f x).1 = (f y).1) : x.1 = y.1 := ((hr _ _ _ _ _ _).mp h).1 + have inj : Function.Injective f := by + rintro ⟨i, s⟩ ⟨j, t⟩ h + obtain ⟨h, h'⟩ := Prod.mk.inj h + obtain ⟨rfl, r⟩ := (hr i j s t k k).mp h + exact Prod.ext rfl (Sum.inl.inj ((e i).injective (Prod.ext r h'))) + let pos := Function.Embedding.mk f inj + have capacity (i : J) : (univ.image fun s => (pos (i, s)).1).card ≤ n := by + let A := univ.image fun s => (pos (i, s)).1 + have rep (a : A) : ∃ s, (slot i s k).1 = a.val := by + obtain ⟨s, _, hs⟩ := mem_image.mp a.property + exact ⟨s, hs⟩ + choose witness hw using rep + let g (a : A) := (e i (.inl (witness a))).1 + have hg : Function.Injective g := by + intro a b hab + exact Subtype.ext ((hw a).symm.trans (((hr _ _ _ _ k k).mpr ⟨rfl, hab⟩).trans (hw b))) + simpa only [Fintype.card_coe, Fintype.card_fin] using Fintype.card_le_of_injective g hg + obtain ⟨D, hD⟩ := descriptor pos same (by convert! capacity using 1; congr! 3) + refine ⟨D, fun i s z => ?_⟩ + rw [hD] + exact ⟨(hr i i s s z k).mpr ⟨rfl, rfl⟩, he i s z⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Exterior/Supply.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Exterior/Supply.lean new file mode 100644 index 0000000000..ef1ec43e26 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Exterior/Supply.lean @@ -0,0 +1,891 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Transform +public import Mathlib.Data.Fintype.EquivFin + +/-! +# Matching active rows with multiplicity + +An inactive row contributes no condition. Active rows can have +repeated identifiers, so compare the complete records as multisets. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Finset Transcript + +variable {A I J : Type} [Fintype I] [Fintype J] + +open scoped Classical in +/-- The sum of `if x i = some a then 1 else 0` indexed by `i`. -/ +def count (x : I → Option A) (a : A) : ℕ := ∑ i, if x i = some a then 1 else 0 + +open scoped Classical in +/-- The condition `∀ a, count x a = count y a` on the specified data. -/ +def Match (x : I → Option A) (y : J → Option A) : Prop := ∀ a, count x a = count y a + +open scoped Classical in +theorem count_ofFn [DecidableEq A] [BEq A] [LawfulBEq A] {n : ℕ} (x : Fin n → A) (a : A) : + (List.ofFn x).count a = ∑ i, if x i = a then 1 else 0 := by + induction n with + | zero => simp + | succ n ih => + rw [List.ofFn_succ, List.count_cons, Fin.sum_univ_succ, ih] + simp [add_comm] + +open scoped Classical in +private theorem count_pad {k : ℕ} (e : I ↪ Fin k) (f : Fin k → ℕ) + (zero : ∀ i, i ∉ Set.range e → f i = 0) : + ∑ i, f i = ∑ i, f (e i) := by + rw [← sum_subset (subset_univ (univ.image e)), sum_image e.injective.injOn] + exact fun i _ h => zero i (by simpa using h) + +open scoped Classical in +private theorem paired_iff {h n : ℕ} (rec : Fin n → Val (Messages.row h 0)) : + paired (List.ofFn rec) ↔ + ∀ z : Val (word h), (∑ i, if rec i = (true, false, z) then 1 else 0) = + ∑ i, if rec i = (true, true, z) then 1 else 0 := by + have eq (x y : Val (Messages.row h 0)) : + Messages.reverse h 0 x = y ↔ x = Messages.reverse h 0 y := + (Messages.reverse_involutive h 0).eq_iff + simp only [paired, List.map_ofFn, List.perm_iff_count, count_ofFn, Function.comp_apply, eq] + constructor + · intro H z + exact H (true, true, z) + · rintro H ⟨_|_, _|_, z⟩ + · rfl + · rfl + · exact (H z).symm + · exact H z + +open scoped Classical in +/-- Returns `some a` when `v` holds, and `none` otherwise. -/ +def flag {A : Type} (v : Bool) (a : A) := if v then some a else none + +open scoped Classical in +private theorem pair_iff {h n : ℕ} (rec : Fin n → Val (Messages.row h 0)) + (e : I ⊕ J ↪ Fin n) (a : I → Bool) (b : J → Bool) (f : I → Val (word h)) + (g : J → Val (word h)) (hl : ∀ i, rec (e (.inl i)) = (a i, false, f i)) + (hr : ∀ i, rec (e (.inr i)) = (b i, true, g i)) + (off : ∀ i, i ∉ Set.range e → (rec i).1 = false) : + paired (List.ofFn rec) ↔ Match (fun i => flag (a i) (f i)) (fun j => flag (b j) (g j)) := by + rw [paired_iff] + have sub (t : Bool) (z : Val (word h)) : + (∑ i, if rec i = (true, t, z) then 1 else 0) = + ∑ i, if rec (e i) = (true, t, z) then 1 else 0 := by + refine count_pad e _ fun i hi => ite_eq_right ?_ + intro he + exact Bool.false_ne_true ((off i hi).symm.trans (congrArg Prod.fst he)) + unfold Match count + simp only [sub, Fintype.sum_sum_type, hl, hr] + have hf (v : Bool) (x y : Val (word h)) : flag v x = some y ↔ v = true ∧ x = y := by + cases v <;> simp [flag] + simp only [Prod.mk.injEq, true_and, and_false, false_and, Bool.true_eq_false, + Bool.false_eq_true, ite_false, sum_const_zero, zero_add, add_zero, hf] + +variable {X : Type} [Fintype X] + +open scoped Classical in +/-- Each row has one activity bit followed by an arbitrary set of +named data bits. Taps may specify constants. -/ +abbrev RowTap (X B : Type) := Option B → X ⊕ Bool + +open scoped Classical in +/-- The indexed operation `flag (Sum.elim x id (a none)) (fun b => Sum.elim x id (a (some b)))`. -/ +def RowTap.read {B : Type} (a : RowTap X B) (x : X → Bool) : Option (B → Bool) := + flag (Sum.elim x id (a none)) (fun b => Sum.elim x id (a (some b))) + +open scoped Classical in +/-- Two sorts check equality of multisets without any promise that the +active addresses provide a permutation. -/ +theorem match_rows {F B : Type} [Field F] [Fintype B] {w j u : ℕ} {L : Set (Table F)} + (ok : ∀ (_ : LinearOrder (Val (Messages.row (Fintype.card B) 0))), + Fast F (Messages.row (Fintype.card B) 0) → sorter F (Messages.row (Fintype.card B) 0) j ∈ L) + (hu : 3 ≤ u) (room : 2 * 2 ^ j * (Fintype.card B + 2) ≤ u) (width : Fintype.card B + 2 ≤ 4 * w) + (n : Fintype.card I + Fintype.card J ≤ 2 ^ j) + (f : I → RowTap X B) (g : J → RowTap X B) : + WideWeight F u L (fun x => if Match (fun i => (f i).read x) (fun i + => (g i).read x) then 1 else 0) + (4 * Fintype.card X + 1000 * 2 ^ j * (1 + w)) := by + let h := Fintype.card B + let e : I ⊕ J ↪ Fin (2 ^ j) := Classical.choice (Function.Embedding.nonempty_of_card_le (by simpa + using n)) + let p : slots (word h) ≃ B := Fintype.equivOfCardEq (by simp [h]) + let code : (B → Bool) ≃ Val (word h) := (p.symm.arrowCongr (.refl _)).trans (bits (word h)).symm + let row (t : Bool) (r : RowTap X B) : slots (Messages.row h 0) → X ⊕ Bool := + Sum.elim (fun _ => r none) (Sum.elim (fun _ => .inr t) (fun j => r (some (p j)))) + let tap := Function.extend e (Sum.elim (row false ∘ f) (row true ∘ g)) (fun _ _ => .inr false) + have H := packet_with F (H := h) (z := 0) ok hu room width tap + convert H using 1 + funext x + let recd (i : Fin (2 ^ j)) := (bits (Messages.row h 0)).symm (Sum.elim x id ∘ tap i) + let a (t : RowTap X B) := Sum.elim x id (t none) + let b (t : RowTap X B) := code (fun i => Sum.elim x id (t (some i))) + have hl (i : I) : recd (e (.inl i)) = (a (f i), false, b (f i)) := by + unfold recd tap + rw [e.injective.extend_apply] + rfl + have hr (i : J) : recd (e (.inr i)) = (a (g i), true, b (g i)) := by + unfold recd tap + rw [e.injective.extend_apply] + rfl + have off i (hi : i ∉ Set.range e) : (recd i).1 = false := by + unfold recd tap + rw [Function.extend_apply' _ _ _ hi] + rfl + have he := pair_iff recd e _ _ _ _ hl hr off + have hv (t : RowTap X B) (z : B → Bool) : + flag (a t) (b t) = some (code z) ↔ t.read x = some z := by + unfold RowTap.read flag a b + split_ifs <;> simp + have eq : paired (packetRows tap x) ↔ Match (fun i => (f i).read x) (fun i => (g i).read x) := by + change paired (List.ofFn recd) ↔ _ + rw [he] + unfold Match count + constructor + · intro hm z + have hx := hm (code z) + simp only [hv] at hx + convert! hx using 1 <;> congr! 2 + · intro hm z + obtain ⟨z, rfl⟩ := code.surjective z + simp only [hv] + convert! hm z using 1 <;> congr! 2 + simp only [eq] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +/- +# Canonical allocation to bands + +A band has a fixed number of rows for one exterior name. Sort the +active data together with empty rows. The multiset fixes the entire +sorted band, so guessing it adds no multiplicity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Finset + +variable {I J A B : Type} [Fintype I] [Fintype J] + +open scoped Classical in +theorem match_map (f : I → Option A) (g : J → Option A) (e : A ↪ B) : + Match (fun i => (f i).map e) (fun j => (g j).map e) ↔ Match f g := by + have same (x : Option A) (a : A) : x.map e = some (e a) ↔ x = some a := by + cases x <;> simp + unfold Match count + constructor + · intro h a + simpa only [same] using h (e a) + · intro h b + by_cases hb : ∃ a, e a = b + · obtain ⟨a, rfl⟩ := hb + simpa only [same] using h a + · have hn (x : Option A) : x.map e ≠ some b := by + cases x with + | none => simp + | some a => exact fun h => hb ⟨a, Option.some.inj h⟩ + simp [hn] + +open scoped Classical in +theorem count_pos (f : I → Option A) (a : A) : 0 < count f a ↔ ∃ i, f i = some a := by + simp only [count, sum_boole, Nat.cast_id, card_pos, filter_nonempty_iff, mem_univ, true_and] + +open scoped Classical in +/-- Match transfers any condition on the active records. -/ +theorem Match.all {f : I → Option A} {g : J → Option A} (h : Match f g) (P : A → Prop) : + (∀ i a, f i = some a → P a) ↔ (∀ j a, g j = some a → P a) := by + have hh a : (∃ i, f i = some a) ↔ ∃ j, g j = some a := by rw [← count_pos, ← count_pos, h a] + constructor + · intro h j a he + obtain ⟨i, hi⟩ := (hh a).mpr ⟨j, he⟩ + exact h i a hi + · intro h i a he + obtain ⟨j, hj⟩ := (hh a).mp ⟨i, he⟩ + exact h j a hj + +open scoped Classical in +private theorem zeros [Fintype A] (x : I → Option A) : + (∑ i, if x i = none then 1 else 0) + (∑ a, count x a) = Fintype.card I := by + unfold count + rw [sum_comm, ← sum_add_distrib] + trans ∑ _i : I, 1 + · apply sum_congr rfl + intro i _ + cases x i <;> simp + · simp + +open scoped Classical in +private theorem monotone_unique [Finite A] [LinearOrder (Option A)] {n : ℕ} + (x y : Fin n → Option A) (hx : Monotone x) (hy : Monotone y) (h : Match x y) : x = y := by + let : Fintype A := Fintype.ofFinite A + apply List.ofFn_injective + apply List.Perm.eq_of_pairwise' hx.sortedLE_ofFn.pairwise hy.sortedLE_ofFn.pairwise + apply List.perm_iff_count.mpr + intro a + rw [count_ofFn, count_ofFn] + cases a with + | some a => exact h a + | none => + have h₁ := zeros x + have h₂ := zeros y + have hs : count x = count y := funext h + rw [hs] at h₁ + omega + +open scoped Classical in +theorem band [Finite A] [LinearOrder (Option A)] (x : I → Option A) (n : ℕ) + (cap : (univ.filter fun i => x i ≠ none).card ≤ n) : + ∃! y : Fin n → Option A, Monotone y ∧ Match x y := by + let : Fintype A := Fintype.ofFinite A + let live := univ.filter fun i => x i ≠ none + obtain ⟨e⟩ : Nonempty (↥live ↪ Fin n) := + Function.Embedding.nonempty_of_card_le (by simpa only [Fintype.card_coe, Fintype.card_fin] + using cap) + let z := Function.extend e (fun i => x i.val) (fun _ => none) + have he : Match x z := by + intro a + unfold count + rw [← sum_subset (subset_univ live), ← sum_subset (subset_univ (univ.image e))] + · rw [sum_image e.injective.injOn, ← sum_coe_sort live] + apply sum_congr rfl + intro i _ + rw [show z (e i) = x i.val from e.injective.extend_apply _ _ _] + · intro i _ hi + rw [show z i = none from Function.extend_apply' _ _ _ (by simpa using hi)] + rfl + · intro i _ hi + have : x i = none := by simpa [live] using hi + simp [this] + let y := z ∘ Tuple.sort z + have hy : Match x y := fun a => (he a).trans + (Equiv.sum_comp (Tuple.sort z) (fun i => if z i = some a then 1 else 0)).symm + exact ⟨y, ⟨Tuple.monotone_sort z, hy⟩, fun w hw => + monotone_unique _ _ hw.1 (Tuple.monotone_sort z) (fun a => (hw.2 a).symm.trans (hy a))⟩ + +open scoped Classical in +/-- Transforms the indexed data by `(f i).map (fun j => (j, x i))`. -/ +def label (f : I → Option J) (x : I → A) (i : I) := (f i).map (fun j => (j, x i)) +open scoped Classical in +/-- Transforms the indexed data by `(y p.1 p.2).map (Prod.mk p.1)`. -/ +def names {n : ℕ} (y : J → Fin n → Option A) (p : J × Fin n) := (y p.1 p.2).map (Prod.mk p.1) + +open scoped Classical in +theorem by_name {n : ℕ} (f : I → Option J) (x : I → A) (y : J → Fin n → Option A) : + Match (label f x) (names y) ↔ + ∀ j, Match (fun i => if f i = some j then some (x i) else none) (y j) := by + have first (j : J) (a : A) : count (label f x) (j, a) = + count (fun i => if f i = some j then some (x i) else none) a := by + unfold count label + refine sum_congr rfl fun i _ => ?_ + cases he : f i with + | none => simp [he] + | some k => by_cases hk : k = j <;> simp [he, hk] + have second (j : J) (a : A) : count (names y) (j, a) = count (y j) a := by + unfold count names + rw [Fintype.sum_prod_type, sum_eq_single j] + · exact sum_congr rfl fun t _ => by cases y j t <;> simp + · intro k _ hk + exact sum_eq_zero fun t _ => by cases y k t <;> simp [hk] + · simp + unfold Match + simp only [Prod.forall, first, second] + +open scoped Classical in +/-- Padding and monotonicity remove any selector multiplicity. -/ +theorem bands [Finite A] [LinearOrder (Option A)] (f : I → Option J) (x : I → A) (n : ℕ) + (cap : ∀ j, count f j ≤ n) : + ∃! y : J → Fin n → Option A, (∀ j, Monotone (y j)) ∧ Match (label f x) (names y) := by + let : Fintype A := Fintype.ofFinite A + have each (j : J) := band (fun i => if f i = some j then some (x i) else none) n + (by simpa [count, sum_boole] using cap j) + choose y hy uniq using each + exact ⟨y, ⟨fun j => (hy j).1, (by_name f x y).mpr fun j => (hy j).2⟩, + fun t ht => funext fun j => uniq j _ ⟨ht.1 j, (by_name _ _ _).mp ht.2 j⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +/- # Canonical Boolean encoding of a band and the adjacent-row check -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Finset Transcript + +variable {F X Y B I J : Type} [Field F] + +open scoped Classical in +/-- In the case `none`, this construction gives `s.isSome`. -/ +def encode (s : Option (B → Bool)) : Option B → Bool + | none => s.isSome + | some i => (s.getD (fun _ => false)) i + +open scoped Classical in +/-- Returns `some (fun i => f (some i))` when `f none` holds, and `none` otherwise. -/ +def decode (f : Option B → Bool) : Option (B → Bool) := + if f none then some (fun i => f (some i)) else none + +open scoped Classical in +@[simp] theorem decode_encode (s : Option (B → Bool)) : decode (encode s) = s := by + cases s <;> rfl + +open scoped Classical in +/-- Indexes the store by the coordinates of `J × Fin n × Option B`. -/ +abbrev Store (J : Type) (n : ℕ) (B : Type) := J × Fin n × Option B + +open scoped Classical in +/-- The value specified by `z (j, i, p)`. -/ +def line {n : ℕ} (z : Store J n B → Bool) (j : J) (i : Fin n) (p : Option B) := z (j, i, p) + +open scoped Classical in +/-- Computes the data by the application `decode (line z j i)`. -/ +def data {n : ℕ} (z : Store J n B → Bool) (j : J) (i : Fin n) := decode (line z j i) + +open scoped Classical in +/-- Requires `(∀ j i, line z j i = encode (data z j i)) ∧ ∀ j, Monotone (data z j)`. -/ +def Canonical [LinearOrder (Option (B → Bool))] {n : ℕ} (z : Store J n B → Bool) : Prop := + (∀ j i, line z j i = encode (data z j i)) ∧ ∀ j, Monotone (data z j) + +open scoped Classical in +theorem unique_store [Finite B] [LinearOrder (Option (B → Bool))] [Fintype I] [Fintype J] + (f : I → Option J) (x : I → B → Bool) (n : ℕ) (cap : ∀ j, count f j ≤ n) : + ∃! z : Store J n B → Bool, Canonical z ∧ Match (label f x) (names (data z)) := by + let : Fintype B := Fintype.ofFinite B + obtain ⟨y, ⟨hm, hp⟩, uniq⟩ := bands f x n cap + let z (u : Store J n B) := encode (y u.1 u.2.1) u.2.2 + have eq : data z = y := funext fun j => funext fun i => decode_encode _ + refine ⟨z, ?_, ?_⟩ + · change Canonical z ∧ Match _ (names (data z)) + unfold Canonical + rw [eq] + exact ⟨⟨fun _ _ => rfl, hm⟩, hp⟩ + · intro t ht + have he := uniq _ ⟨ht.1.2, ht.2⟩ + funext ⟨j, i, p⟩ + have := ht.1.1 j i + rw [he] at this + exact congrFun this p + +open scoped Classical in +private def next {n : ℕ} (k : Fin n) : Fin n := + if h : k.val + 1 < n then ⟨k.val + 1, h⟩ else k + +open scoped Classical in +private theorem monotone {A : Type} [Preorder A] {n : ℕ} (f : Fin n → A) : + Monotone f ↔ ∀ i, f i ≤ f (next i) := by + refine ⟨fun h i => h ?_, fun h => ?_⟩ + · unfold next + split <;> simp [Fin.le_def] + cases n with + | zero => exact fun i => i.elim0 + | succ n => + apply Fin.monotone_iff_le_succ.mpr + intro i + have he : next i.castSucc = i.succ := by ext; simp [next] + rw [← he] + exact h _ + +open scoped Classical in +theorem all_flags [Fintype I] (p : I → Prop) [DecidablePred p] : + (∏ i, if p i then (1 : F) else 0) = if ∀ i, p i then 1 else 0 := by + by_cases h : ∀ i, p i + · simp [h] + · rw [ite_eq_right h] + obtain ⟨i, hi⟩ := not_forall.mp h + exact prod_eq_zero (mem_univ i) (ite_eq_right hi) + +variable [Fintype X] [Fintype B] [LinearOrder (Option (B → Bool))] [Fintype J] + +open scoped Classical in +/-- Verify canonical order and inactive padding by overlapping pairs of +rows. The dictionary needs no name bits. -/ +theorem check_store {w j u n : ℕ} (tap : Store J n B → X) (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) + (hu : 3 ≤ u) (ha : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ u) + (small : 2 * (Fintype.card B + 1) < j) (rows : Fintype.card J * n ≤ 2 ^ j) : + WideWeight F u (Allowed F w) (fun x => if Canonical (x ∘ tap) then 1 else 0) + (4 * Fintype.card X + 11000 * 2 ^ j * (1 + j)) := by + let : LE (Option (B → Bool)) := (inferInstance : LinearOrder (Option (B → Bool))).toLE + let test (a b : Option B → Bool) := a = encode (decode a) ∧ decode a ≤ decode b + let f (x : Option B ⊕ Option B → Bool) : F := + if test (x ∘ Sum.inl) (x ∘ Sum.inr) then 1 else 0 + let read (i : J × Fin n) : Option B ⊕ Option B → X ⊕ Bool := + Sum.elim (fun k => .inl (tap (i.1, i.2, k))) (fun k => .inl (tap (i.1, next i.2, k))) + have h := dictionary hj hj' hu ha (by simpa [two_mul] using small) + (by simpa using rows) f read + have eq (x : X → Bool) : (∏ i, f (Sum.elim x id ∘ read i)) = + if Canonical (x ∘ tap) then 1 else 0 := by + let z := x ∘ tap + have eq (i : J × Fin n) : f (Sum.elim x id ∘ read i) = + if test (line z i.1 i.2) (line z i.1 (next i.2)) then 1 else 0 := rfl + simp_rw [eq] + rw [all_flags] + simp only [Prod.forall, test, forall_and, Canonical, monotone, data, z] + simp_rw [eq] at h + intro a i + obtain ⟨v, hv, hnet⟩ := h a i + exact ⟨v, hv, hnet.mono le_rfl sort_allowed⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +/- # Soundness of checking an exterior band against its original stacks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Finset + +variable {I J S Q A B : Type} [Fintype I] [Fintype J] + +open scoped Classical in +private theorem sum_active [Fintype A] (x : I → Option A) (f : Option A → ℕ) (hf : f none = 0) : + (∑ i, f (x i)) = ∑ a, count x a * f (some a) := by + simp only [count, sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro i _ + cases x i <;> simp [hf, ite_mul] + +open scoped Classical in +/-- Expand active records into their active slots. -/ +def flatten (f : A → Q → Option B) (x : I → Option A) (i : I × Q) := + (x i.1).bind fun a => f a i.2 + +open scoped Classical in +theorem Match.flatten [Fintype Q] [Finite A] {x : I → Option A} {y : J → Option A} + (h : Match x y) (f : A → Q → Option B) : + Match (flatten f x) (flatten f y) := by + let : Fintype A := Fintype.ofFinite A + intro b + let wt (a : Option A) := ∑ q, if a.bind (fun v => f v q) = some b then 1 else 0 + have zero : wt none = 0 := by simp [wt] + simp only [count, Fintype.sum_prod_type] + change ∑ i, wt (x i) = ∑ j, wt (y j) + rw [sum_active x wt zero, sum_active y wt zero] + exact sum_congr rfl fun a _ => congrArg (· * wt (some a)) (h a) + +open scoped Classical in +theorem originals [Fintype S] (src : S → A) (keys : I → Option S) (payload : I → A) + (unique : ∀ s, ∃! i, keys i = some s) : + Match (fun s => some (s, src s)) (label keys payload) ↔ + ∀ i s, keys i = some s → payload i = src s := by + constructor + · intro h i s hi + have ht := (h.all (fun k => k.2 = src k.1)).mp (by intro j _ he; cases he; rfl) + exact ht i (s, payload i) (by simp [label, hi]) + · intro h + rintro ⟨s, a⟩ + obtain ⟨i, hi, hu⟩ := unique s + unfold count + rw [sum_eq_single s, sum_eq_single i] + · simp [label, hi, h i s hi] + · intro j _ hn + apply ite_eq_right + intro he + have hj : keys j = some s := by + simpa [label, Function.comp_def] using congrArg (Option.map Prod.fst) he + exact hn (hu j hj) + · simp + · intro t _ ht; simp [ht] + · simp + +open scoped Classical in +/-- Indexes the body by the coordinates of `Q × (Option K ⊕ P)`. -/ +abbrev Body (Q K P : Type) := Q × (Option K ⊕ P) + +open scoped Classical in +/-- Selects the appropriate branch of `if x (q, .inl none) then some (Sum.elim (fun i => x (q, +.inl (some i))) (fun i => x (q, .inr i))) else none`. -/ +def stackRead {K P : Type} (x : Body Q K P → Bool) (q : Q) : Option (K ⊕ P → Bool) := + if x (q, .inl none) then some (Sum.elim (fun i => x (q, .inl (some i))) (fun i => x (q, .inr i))) + else none + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def concat {K P : Type} (code : A ↪ (K → Bool)) : A × (P → Bool) ↪ (K ⊕ P → Bool) where + toFun x := Sum.elim (code x.1) x.2 + inj' _ _ h := Prod.ext (code.injective (congrArg (· ∘ Sum.inl) h)) (congrArg (· ∘ Sum.inr) h) + +variable {K P : Type} [Fintype S] [Fintype Q] [Fintype K] [Fintype P] {n : ℕ} + +open scoped Classical in +omit [Fintype K] [Fintype P] in +/-- Input locations are known only through the descriptors on the +active internal rows. No addresses of padding stacks are required. -/ +theorem compare [Finite K] [Finite P] (f : I → Option J) (g : I → Q → Option S) + (cover : ∀ j s, ∃! i : I × Q, f i.1 = some j ∧ g i.1 i.2 = some s) + (code : S ↪ (K → Bool)) (src : J → S → P → Bool) + (x : I → Body Q K P → Bool) + (ok : ∀ i j, f i = some j → ∀ q, stackRead (x i) q = + (g i q).map (fun s => concat code (s, fun p => x i (q, .inr p)))) + (y : J → Fin n → Option (Body Q K P → Bool)) (copied : Match (label f x) (names y)) : + (∀ j, Match (fun s => some (concat code (s, src j s))) (flatten stackRead (y j))) ↔ + ∀ i j q s, f i = some j → g i q = some s → (fun p => x i (q, .inr p)) = src j s := by + let : Fintype K := Fintype.ofFinite K + let : Fintype P := Fintype.ofFinite P + have each (j : J) : Match (fun s => some (concat code (s, src j s))) (flatten stackRead (y j)) ↔ + ∀ i q s, f i = some j → g i q = some s → (fun p => x i (q, .inr p)) = src j s := by + let key (t : I × Q) := if f t.1 = some j then g t.1 t.2 else none + let pay (t : I × Q) (p : P) := x t.1 (t.2, .inr p) + have hit (a : I × Q) (s : S) : key a = some s ↔ f a.1 = some j ∧ g a.1 a.2 = some s := by + unfold key; split_ifs <;> simp_all + have uniq (s : S) : ∃! a, key a = some s := by simpa only [hit] using cover j s + have eq : flatten stackRead (fun i => if f i = some j then some (x i) else none) = + fun i => (label key pay i).map (concat code) := by + funext ⟨i, q⟩ + by_cases hi : f i = some j + · simp only [flatten, label, key, ite_eq_left hi, Option.bind_some, ok _ _ hi, Option.map_map] + rfl + · simp [flatten, label, key, hi] + have he := ((by_name f x y).mp copied j).flatten stackRead + rw [eq] at he + change Match (fun s => (some (s, src j s)).map (concat code)) _ ↔ _ + have transfer (p : S → Option (K ⊕ P → Bool)) : + Match p (flatten stackRead (y j)) ↔ Match p (fun i => (label key pay i).map (concat code)) + := + ⟨fun h a => (h a).trans (he a).symm, fun h a => (h a).trans (he a)⟩ + rw [transfer, match_map, originals _ _ _ uniq] + simp only [hit, Prod.forall, and_imp, pay] + exact ⟨fun h i j => (each j).mp (h j) i, fun h j => (each j).mpr (fun i => h i j)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +/- +# Supplying exterior addresses from ordinary port headers + +Only an active exterior row needs its original name. Its stack +addresses live inside its short descriptor, in the same order as +the payloads. A long sort puts all such descriptors in fixed bands. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +open Transcript + +open scoped Classical in +/-- The data for the input construction, including `names`, `keys`, `header`, `body`, `source`. -/ +structure Input (X I J S Q N K P : Type) where + /-- The indexed names of type `J ↪ (N → Bool)`. -/ + names : J ↪ (N → Bool) + /-- Embeds the coordinates as `S ↪ (K → Bool)`. -/ + keys : S ↪ (K → Bool) + /-- The `Input` component of type `I → RowTap X N`. -/ + header : I → RowTap X N + /-- The `Input` component of type `I → Body Q K P → X ⊕ Bool`. -/ + body : I → Body Q K P → X ⊕ Bool + /-- The source vertex of each edge. -/ + source : J → S → P → X + +namespace Input +variable {X I J S Q N K P : Type} (A : Input X I J S Q N K P) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def payload (x : X → Bool) (i : I) := Sum.elim x id ∘ A.body i + +variable [Fintype I] {n : ℕ} + +open scoped Classical in +/-- The data for the valid construction, including `names`, `stack`, `cover`, `cap`. -/ +structure Valid (n : ℕ) (x : X → Bool) (f : I → Option J) (id : I → Q → Option S) : Prop where + names : ∀ i, (A.header i).read x = (f i).map A.names + stack : ∀ i j, f i = some j → ∀ q, stackRead (A.payload x i) q = + (id i q).map (fun s => concat A.keys (s, fun p => A.payload x i (q, .inr p))) + cover : ∀ j s, ∃! a : I × Q, f a.1 = some j ∧ id a.1 a.2 = some s + cap : ∀ j, count f j ≤ n + +open scoped Classical in +/-- The condition `∀ i j q s, f i = some j → id i q = some s → (fun p => A.payload x i (q, .inr +p)) = x ∘ A.source j s` on the specified data. -/ +def Supplied (x : X → Bool) (f : I → Option J) (id : I → Q → Option S) : Prop := + ∀ i j q s, f i = some j → id i q = some s → + (fun p => A.payload x i (q, .inr p)) = x ∘ A.source j s + +variable [Fintype J] [Fintype Q] [Fintype N] [Fintype K] [Fintype P] [Fintype X] + {F : Type} [Field F] {j w u : ℕ} + +local notation "Z" => Store J n (Body Q K P) +local notation "B" => N ⊕ Body Q K P + +open scoped Classical in +theorem long_sort (hu : 3 ≤ u) (hj : w ≤ j) (hj' : j ≤ 2 * w) + (room : 2 * 2 ^ j * (Fintype.card B + 2) ≤ u) + (hb : w ≤ Fintype.card B + 2) (hw : Fintype.card B + 2 ≤ 4 * w) + (hn : Fintype.card I + Fintype.card J * n ≤ 2 ^ j) : + ∃ f : (X ⊕ Z → Bool) → F, + WideWeight F u (Allowed F w) f (4 * Fintype.card (X ⊕ Z) + 1000 * 2 ^ j * (1 + w)) ∧ + ∀ (x : X → Bool) (own : I → Option J), + (∀ i, (A.header i).read x = (own i).map A.names) → ∀ z : Z → Bool, + f (Sum.elim x z) = if Match (label own (A.payload x)) (Exterior.names (data z)) then 1 else + 0 := by + let left (i : I) : RowTap (X ⊕ Z) B + | none => Sum.map Sum.inl id (A.header i none) + | some (.inl k) => Sum.map Sum.inl id (A.header i (some k)) + | some (.inr k) => Sum.map Sum.inl id (A.body i k) + let right (q : J × Fin n) : RowTap (X ⊕ Z) B + | none => .inl (.inr (q.1, q.2, none)) + | some (.inl k) => .inr (A.names q.1 k) + | some (.inr k) => .inl (.inr (q.1, q.2, some k)) + let a := Messages.row (Fintype.card B) 0 + have ha : wd a = Fintype.card B + 2 := wd_word _ + have ok (o : LinearOrder (Val a)) (hf : Fast F a) : sorter F a j ∈ Allowed F w := + .inl ⟨j, a, o, hf, hj, hj', hb.trans_eq ha.symm, ha.le.trans hw, rfl⟩ + have h := match_rows ok hu room hw (by simpa using hn) left right + refine ⟨_, h, fun x own ho z => ?_⟩ + have eval (k : X ⊕ Bool) : Sum.elim (Sum.elim x z) id (Sum.map Sum.inl id k) = Sum.elim x id k + := by + cases k <;> rfl + have hl (i : I) : (left i).read (Sum.elim x z) = + (label own (A.payload x) i).map (concat A.names) := by + let head := (A.header i).read x + have key : (left i).read (Sum.elim x z) = head.map (fun f => Sum.elim f (A.payload x i)) := by + change (if _ then some _ else none) = Option.map _ (if _ then some _ else none) + simp only [left, eval] + split_ifs + · apply congrArg some + funext k; cases k <;> exact eval _ + · rfl + rw [key, show head = _ from ho i] + cases he : own i <;> simp only [label, he, Option.map_none, Option.map_some] + rfl + have hr (i : J × Fin n) : (right i).read (Sum.elim x z) = + (Exterior.names (data z) i).map (concat A.names) := by + change (if z (i.1, i.2, none) then some _ else none) = + Option.map _ (Option.map _ (if z (i.1, i.2, none) then some _ else none)) + split_ifs + · apply congrArg some + funext k; cases k <;> rfl + · rfl + simp only [hl, hr, match_map] + +end Input +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior +end + +/- # Checking the contents of each exterior band by short sorts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior.Input +open Transcript + +variable {X I J S Q N K P : Type} [Fintype X] [Fintype J] [Fintype S] + [Fintype Q] [Fintype K] [Fintype P] (A : Input X I J S Q N K P) + {F : Type} [Field F] {w h u n : ℕ} + +local notation "Z" => Store J n (Body Q K P) +local notation "B" => Body Q K P + +open scoped Classical in +/-- The condition `∀ j, Match (fun s => some (concat A.keys (s, x ∘ A.source j s))) (flatten +stackRead (data z j))` on the specified data. -/ +def Short (x : X → Bool) (z : Z → Bool) : Prop := + ∀ j, Match (fun s => some (concat A.keys (s, x ∘ A.source j s))) (flatten stackRead (data z j)) + +open scoped Classical in +/-- Each short sort uses only a stack identifier and one stack. It +does not carry a host address or the name of the exterior bit. -/ +theorem short_sort [LinearOrder (Option (B → Bool))] (hu : 3 ≤ u) + (size : Fintype.card S + n * Fintype.card Q ≤ 2 ^ h) + (small : 2 * 2 ^ h * (Fintype.card K + Fintype.card P + 2) + ≤ min u (min (2 ^ ((Nat.clog 2 w) ^ 3)) (2 ^ (w / 2)))) : + ∃ f : (X ⊕ Z → Bool) → F, + WideWeight F u (Allowed F w) f + (8 * Fintype.card (X ⊕ Z) + 10000 * Fintype.card J * 2 ^ h * (Fintype.card K + + Fintype.card P + 3)) ∧ + ∀ x z, Canonical z → f (Sum.elim x z) = if A.Short x z then 1 else 0 := by + let L := Fintype.card (K ⊕ P) + let T := (S × P) ⊕ (Fin n × B) + let left (s : S) : RowTap T (K ⊕ P) + | none => .inr true + | some (.inl i) => .inr (A.keys s i) + | some (.inr i) => .inl (.inl (s, i)) + let right (c : Fin n × Q) : RowTap T (K ⊕ P) + | none => .inl (.inr (c.1, c.2, .inl none)) + | some (.inl i) => .inl (.inr (c.1, c.2, .inl (some i))) + | some (.inr i) => .inl (.inr (c.1, c.2, .inr i)) + let b := Messages.row L 0 + have hb : wd b = L + 2 := wd_word _ + have hl : L = Fintype.card K + Fintype.card P := Fintype.card_sum + have ok (o : LinearOrder (Val b)) (hf : Fast F b) : sorter F b h ∈ Allowed F w := by + refine Or.inr ⟨sort_cheap _ _ hf _ (by omega), ?_⟩ + rw [arity_sorter, hb, hl] + exact le_min_iff.mp (le_min_iff.mp small).2 + let f (x : T → Bool) : F := if Match (fun i => (left i).read x) (fun c + => (right c).read x) then 1 else 0 + let cost := 4 * Fintype.card T + 1000 * 2 ^ h * (1 + (L + 2)) + have key : WideWeight F u (Allowed F w) f cost := + match_rows (w := L + 2) ok hu (by simpa using (le_min_iff.mp small).1) + (by unfold L; omega) (by simpa using size) left right + let loc (j : J) : T → X ⊕ Z + | .inl (s, t) => .inl (A.source j s t) + | .inr (i, k) => .inr (j, i, some k) + have net := wide_sum (fun _ : J => f) (fun i t => (Sum.inl (loc i t) : (X ⊕ Z) ⊕ Empty)) + (fun _ => cost) hu (fun _ => key) + let g (x : X ⊕ Z → Bool) := ∏ j, f (x ∘ loc j) + have hg : WideWeight F u (Allowed F w) g (8 * Fintype.card (X ⊕ Z) + 9 * (Fintype.card J * cost)) + := by + convert net using 1 + · funext x; simp [g, weightedSum, Function.comp_def] + · simp + refine ⟨g, ?_, fun x z hp => ?_⟩ + · have hT : Fintype.card T ≤ 2 ^ h * (L + 1) := by + simp only [T, Body, Fintype.card_sum, Fintype.card_prod, Fintype.card_option, + Fintype.card_fin, hl] + have := Nat.mul_le_mul_right (Fintype.card K + Fintype.card P + 1) size + nlinarith only [this, Nat.zero_le (Fintype.card S * Fintype.card K), + Nat.zero_le (Fintype.card S)] + have hc : 9 * cost ≤ 10000 * 2 ^ h * (L + 3) := by + unfold cost + nlinarith only [hT, Nat.zero_le (2 ^ h), Nat.zero_le (2 ^ h * L)] + intro a ix + obtain ⟨v, hv, hn⟩ := hg a ix + refine ⟨v, hv.trans (Nat.add_le_add_left ?_ _), hn⟩ + rw [← hl] + nlinarith only [Nat.mul_le_mul_left (Fintype.card J) hc] + · have hleft j s : (left s).read (Sum.elim x z ∘ loc j) = + some (concat A.keys (s, x ∘ A.source j s)) := by + apply congrArg some + funext i; cases i <;> rfl + have hright (j : J) (a : Fin n × Q) : + (right a).read (Sum.elim x z ∘ loc j) = flatten stackRead (data z j) a := by + let y := line z j a.1 + have he : (right a).read (Sum.elim x z ∘ loc j) = stackRead (y ∘ some) a.2 := by + change (if y _ then some _ else none) = (if y _ then some _ else none) + split_ifs + · apply congrArg some + funext i; cases i <;> rfl + · rfl + have hc : y = encode (data z j a.1) := hp.1 _ _ + rw [he, hc] + unfold flatten + cases data z j a.1 <;> rfl + change (∏ j, f (Sum.elim x z ∘ loc j)) = _ + simp only [f, hleft, hright] + rw [all_flags] + unfold Short + congr! 1 + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior.Input +end + +/- +# Exterior supply without a prescribed permutation of the blocks + +Use one long sort to identify the assigned bands, a dictionary to +make their ordering and padding unique, and one short sort per +exterior name to compare each complete stack. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior.Input +open Transcript Finset + +variable {X Z F : Type} [Field F] [Fintype X] [Fintype Z] {w u : ℕ} + +open scoped Classical in +private theorem combine {a b c : (X ⊕ Z → Bool) → F} {p q r : ℕ} (hu : 3 ≤ u) + (ha : WideWeight F u (Allowed F w) a p) + (hb : WideWeight F u (Allowed F w) b q) + (hc : WideWeight F u (Allowed F w) c r) : + WideWeight F u (Allowed F w) + (fun x => ∑ z, a (Sum.elim x z) * b (Sum.elim x z) * c (Sum.elim x z)) + (8 * Fintype.card (X ⊕ Z) + 9 * (p + q + r)) := by + let f : Fin 3 → (X ⊕ Z → Bool) → F := ![a, b, c] + let t : Fin 3 → ℕ := ![p, q, r] + have h : ∀ i, WideWeight F u (Allowed F w) (f i) (t i) := by + intro i + fin_cases i + · exact ha + · exact hb + · exact hc + convert wide_sum f (fun _ => id) t hu h using 1 + · funext x + simp [weightedSum, Fin.prod_univ_three, f] + · simp [Fin.sum_univ_three, t] + +variable {I J S Q N K P : Type} [Fintype I] [Fintype J] [Fintype S] + [Fintype Q] [Fintype N] [Fintype K] [Fintype P] + (A : Input X I J S Q N K P) {h j n : ℕ} + +local notation "B" => Body Q K P +local notation "Tape" => Store J n B + +open scoped Classical in +/-- On any valid assignment of row names and local stack addresses, +the test compares exactly the required exterior bits. It receives no +inverse permutation or addresses for empty slots. -/ +theorem supply (hu : 3 ≤ u) (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) + (ha : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ u) + (low : w ≤ Fintype.card N + Fintype.card B + 2) + (high : Fintype.card N + Fintype.card B + 2 ≤ 4 * w) + (small : 2 * (Fintype.card B + 1) < j) + (rows : Fintype.card I + Fintype.card J * n ≤ 2 ^ j) + (size : Fintype.card S + n * Fintype.card Q ≤ 2 ^ h) + (arity : 2 * 2 ^ h * (Fintype.card K + Fintype.card P + 2) + ≤ min u (min (2 ^ ((Nat.clog 2 w) ^ 3)) (2 ^ (w / 2)))) : + ∃ f : (X → Bool) → F, + WideWeight F u (Allowed F w) f + (1000000 * (Fintype.card X + 2 ^ j * (1 + w) + Fintype.card J * 2 ^ h * (Fintype.card K + + Fintype.card P + 3))) ∧ + ∀ x owner idx, A.Valid n x owner idx → + f x = if A.Supplied x owner idx then 1 else 0 := by + let order := Fintype.equivFin (Option (B → Bool)) + let : LinearOrder (Option (B → Bool)) := LinearOrder.lift' order order.injective + have room : 2 * 2 ^ j * (Fintype.card (N ⊕ B) + 2) ≤ u := by + rw [Fintype.card_sum] + calc + _ ≤ 2 * 2 ^ j * (4 * w) := Nat.mul_le_mul_left _ high + _ ≤ 2 * 2 ^ (j + 1) * (2 * j + 2) := by + rw [pow_succ] + nlinarith only [Nat.mul_le_mul_left (2 ^ j) hj, Nat.zero_le (2 ^ j)] + _ ≤ _ := ha + obtain ⟨f, hf, ef⟩ := A.long_sort (F := F) hu hj (by omega) room + (by rwa [Fintype.card_sum]) (by rwa [Fintype.card_sum]) rows + have ht := check_store (F := F) (Sum.inr : Tape → X ⊕ Tape) hj hj' hu ha small (by omega) + obtain ⟨g, hg, eg⟩ := A.short_sort (F := F) hu size arity + let check (x : X → Bool) (z : Tape → Bool) := + f (Sum.elim x z) * (if Canonical z then 1 else 0) * g (Sum.elim x z) + refine ⟨fun x => ∑ z, check x z, ?_, ?_⟩ + · have net := combine hu hf ht hg + intro a ix + obtain ⟨v, hv, hn⟩ := net a ix + refine ⟨v, hv.trans ?_, hn⟩ + have hstore : Fintype.card Tape ≤ 2 ^ j * w := by + rw [Fintype.card_prod, Fintype.card_prod, Fintype.card_fin, Fintype.card_option, ← mul_assoc] + exact Nat.mul_le_mul (by omega) (by omega) + rw [Fintype.card_sum] + have hh := Nat.mul_le_mul_left (2 ^ j) hj' + have hshort := Nat.zero_le (Fintype.card J * 2 ^ h * (Fintype.card K + Fintype.card P + 3)) + nlinarith only [hh, hstore, Nat.zero_le (2 ^ j), Nat.zero_le (2 ^ j * w), + Nat.zero_le (Fintype.card X), hshort] + · intro x owner idx hvalid + obtain ⟨z, ⟨hz, hcopy⟩, uniq⟩ := unique_store owner (A.payload x) n hvalid.cap + change (∑ z, check x z) = _ + rw [sum_eq_single z] + · unfold check + rw [ef x owner hvalid.names, ite_eq_left hcopy, ite_eq_left hz, one_mul, one_mul, eg x z hz] + have hs : A.Short x z ↔ A.Supplied x owner idx := + compare owner idx hvalid.cover A.keys (fun j s => x ∘ A.source j s) + (A.payload x) hvalid.stack (data z) hcopy + simp only [hs] + · intro t _ hn + unfold check + by_cases hp : Canonical t + · have hc : ¬Match (label owner (A.payload x)) (Exterior.names (data t)) := + fun hh => hn (uniq _ ⟨hp, hh⟩) + rw [ef x owner hvalid.names, ite_eq_right hc, zero_mul, zero_mul] + · rw [ite_eq_right hp, mul_zero, zero_mul] + · simp + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Exterior.Input +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Hard.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Hard.lean new file mode 100644 index 0000000000..1810e5aa7f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Hard.lean @@ -0,0 +1,39 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Compilation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Encoded +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Resistance +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Reduction + +/-! +# Exact many-list hardness over finite fields + +A failure of tagged permutation hardness supplies the compiled +descent. Applying it to the resistant family yields a contradiction. +The distinctness reduction retains the full range of batch sizes. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Filter + +theorem hard (F : Type) [Field F] [Finite F] : Tagged.Hard F := + Processor.hard_of_descent (descent fun bad => compilation_of_encoded (encoded bad)) + +theorem manyList_full (F : Type) [Field F] [Finite F] : + ∃ η : ℝ, 0 < η ∧ ∀ᶠ w : ℕ in atTop, ∀ t m : ℕ, + 1 ≤ t → (t : ℝ) ≤ (2 : ℝ) ^ ((w : ℝ) ^ (1 + η)) → Realizes F w t m → + (t : ℝ) * listBits w * (w : ℝ) ^ η < m := + Tagged.manyList_full (hard F) + +theorem manyList (F : Type) [Field F] [Finite F] : ManyList (Realizes F) := + Tagged.manyList_of_tag (hard F) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Header.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Header.lean new file mode 100644 index 0000000000..0751a4fda5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Header.lean @@ -0,0 +1,938 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Plan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Transform + +/-! +# Splitting posted diagrams into ordered pieces + +A positive internal span is one entire unit. Exterior spans may +contain several units. Their ordering is supplied independently. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent + +namespace BatchDescent +open Assembly + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {z : ℕ} + +/-- The value specified by `((t.1, t.2.1, t.2.2.1.1), t.2.2.1.2)`. -/ +def unitSpan (t : units S r z) : S.Span := ((t.1, t.2.1, t.2.2.1.1), t.2.2.1.2) + +/-- The subtype of `t : units S r z` satisfying `S.peer r (unitSpan t) = none`. -/ +abbrev outer (S : Scheme F) (r : S.format.obj) (z : ℕ) := + {t : units S r z // S.peer r (unitSpan t) = none} + +theorem unit_ext {a b : units S r z} (h : unitSpan a = unitSpan b) + (hk : a.2.2.2.val = b.2.2.2.val) : a = b := by + obtain ⟨i, j, ⟨k, s⟩, t⟩ := a + obtain ⟨i', j', ⟨k', s'⟩, t'⟩ := b + simp only [unitSpan, Prod.mk.injEq] at h + obtain ⟨⟨rfl, rfl, rfl⟩, rfl⟩ := h + have he : t = t' := Fin.ext hk + rw [he] + +end BatchDescent + +namespace Assembly.Scheme.Posting +open BatchDescent BatchDescent.PackRows Packing Coloring + +variable {F T : Type} [Field F] {x y : Wire} {L : Fringe x y T} {h z : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h z} (p : S.Posting r G) (hz : 0 < z) + +open scoped Classical in +/-- The unit of of type `units S r z` for the given inputs. -/ +def unitOf (i : G.E) (b : Bool) : units S r z := + ⟨p.host (side G i b), p.block (G.ix i), (0, p.stub i b), ⟨0, by + change 0 < S.width r (p.span i b) / z + rw [p.length, Nat.div_self hz] + decide⟩⟩ + +open scoped Classical in +@[simp] theorem unitSpan_unitOf (i : G.E) (b : Bool) : + unitSpan (p.unitOf hz i b) = p.span i b := rfl + +include hz in +open scoped Classical in +theorem span_peer (i : G.E) (b : Bool) : + S.peer r (p.span i b) = some (p.span i (!b)) := by + rw [peer, p.link] + simp only [Option.map_some, span, spanAt, p.neighbor hz] + +open scoped Classical in +private theorem unitOf_eq {u : units S r z} (i : G.E) (b : Bool) (hs : unitSpan u = p.span i b) : + u = p.unitOf hz i b := by + refine unit_ext hs ?_ + have hl : u.2.2.2.val < S.width r (unitSpan u) / z := u.2.2.2.isLt + rw [hs, p.length, Nat.div_self hz] at hl + exact Nat.eq_zero_of_le_zero (Nat.le_of_lt_succ hl) + +open scoped Classical in +theorem unit_cases (u : units S r z) : + S.peer r (unitSpan u) = none ∨ ∃ i b, u = p.unitOf hz i b := by + cases hs : S.peer r (unitSpan u) with + | none => exact .inl rfl + | some t => + have hl : 0 < S.width r (unitSpan u) := + (show 0 < S.width r (unitSpan u) / z from u.2.2.2.pos).trans_le (Nat.div_le_self _ _) + obtain ⟨⟨i, b⟩, he⟩ := p.found _ hl (by simp [hs]) + exact .inr ⟨i, b, p.unitOf_eq hz i b he.symm⟩ + +open scoped Classical in +theorem joined (uniform : ∀ i j, Parts.Uniform (BatchDescent.pattern S r i j) z) + {s t : units S r z} {i j : Fin z} + (he : S.Joins r (BatchDescent.join S r z uniform (s, i)) (BatchDescent.join S r z uniform (t, + j))) : + i = j ∧ ∃ e b, s = p.unitOf hz e b ∧ t = p.unitOf hz e (!b) := by + have hs : S.peer r (unitSpan s) = some (unitSpan t) := he.1 + rcases p.unit_cases hz s with hn | ⟨e, b, rfl⟩ + · rw [hn] at hs; cases hs + rw [unitSpan_unitOf, p.span_peer hz] at hs + have ht := p.unitOf_eq hz e (!b) (Option.some.inj hs).symm + subst t + exact ⟨Fin.ext he.2, e, b, rfl, rfl⟩ + +open scoped Classical in +theorem unitOf_inj : Function.Injective (Function.uncurry (p.unitOf hz)) := by + rintro ⟨i, b⟩ ⟨j, c⟩ hh + have he : p.span i b = p.span j c := congrArg unitSpan hh + have ho := congrArg (S.direction r) he + rw [p.dir, p.dir] at ho + subst c + have eq : i = j := by + apply p.distinct hz + cases b + · exact he + · have h' := congrArg (S.peer r) he + rw [p.span_peer hz, p.span_peer hz] at h' + exact Option.some.inj h' + rw [eq] + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def unitLayout : (G.E × Bool) ⊕ outer S r z ≃ units S r z := + Equiv.ofBijective (Sum.elim (Function.uncurry (p.unitOf hz)) Subtype.val) (by + have ne (i : G.E × Bool) (j : outer S r z) : p.unitOf hz i.1 i.2 ≠ j.val := by + intro eq + have h := j.property + rw [← eq, unitSpan_unitOf, p.span_peer hz] at h + cases h + constructor + · rintro (i|i) (j|j) he + · exact congrArg Sum.inl (p.unitOf_inj hz he) + · exact (ne i j he).elim + · exact (ne j i he.symm).elim + · exact congrArg Sum.inr (Subtype.ext he) + · intro i + rcases p.unit_cases hz i with he | ⟨e, b, rfl⟩ + · exact ⟨.inr ⟨i, he⟩, rfl⟩ + · exact ⟨.inl (e, b), rfl⟩) + +include p in +open scoped Classical in +theorem all_uniform (hm : ∀ a, S.peer r a = none → z ∣ S.width r a) (i j) : + Parts.Uniform (BatchDescent.pattern S r i j) z := by + intro k t + let a : S.Span := ((i, j, k), t) + change z ∣ S.width r a + by_cases he : S.width r a = 0 + · rw [he]; exact dvd_zero _ + cases hp : S.peer r a with + | none => exact hm _ hp + | some v => + obtain ⟨⟨e, b⟩, h⟩ := p.found a (Nat.pos_of_ne_zero he) (by simp [hp]) + rw [← h, p.length] + +open scoped Classical in +private theorem localize {I J : Type} {U V : I → J → Type} + (f : (Σ i, Σ j, U i j) ≃ Σ i, Σ j, V i j) + (hf : ∀ x, (f x).1 = x.1 ∧ (f x).2.1 = x.2.1) (i : I) (j : J) : + ∃ e : U i j ≃ V i j, ∀ x, f ⟨i, j, x⟩ = ⟨i, j, e x⟩ := by + have hit (x : U i j) : ∃ y : V i j, f ⟨i, j, x⟩ = ⟨i, j, y⟩ := by + have he := hf ⟨i, j, x⟩ + generalize f ⟨i, j, x⟩ = v at * + obtain ⟨a, b, t⟩ := v + obtain ⟨rfl, rfl⟩ := he + exact ⟨t, rfl⟩ + choose g hg using hit + have bij : Function.Bijective g := by + constructor + · intro a b he + have ht : f ⟨i, j, a⟩ = f ⟨i, j, b⟩ := by rw [hg, hg, he] + simpa using f.injective ht + · intro y + obtain ⟨⟨a, b, x⟩, he⟩ := f.surjective ⟨i, j, y⟩ + have ht := hf ⟨a, b, x⟩ + rw [he] at ht + obtain ⟨rfl, rfl⟩ := ht + exact ⟨x, by simpa [hg] using he⟩ + exact ⟨Equiv.ofBijective g bij, hg⟩ + +variable {v q d : ℕ} {G' : HostNet F L h (bundleSize v q)} + (p : S.Posting r G') (hz : 0 < bundleSize v q) + (hm : ∀ a, S.peer r a = none → bundleSize v q ∣ S.width r a) + {l : Inventory (2 ^ S.m) (2 ^ S.h) d} + (ex : outer S r (bundleSize v q) ≃ Endpoints l) + (hx : ∀ j, (ex j).1 = j.val.1 ∧ (ex j).2.1 = j.val.2.1) + +include hm hx in +open scoped Classical in +theorem exists_pieces : + ∃ b : Pieces S r (append (p.channels hz).inventory l) v q, + (∀ i t, b.equiv (p.unitOf hz i t) = extendL _ l ((p.channels hz).point (i, t))) ∧ + ∀ j, b.equiv j.val = extendR (p.channels hz).inventory l (ex j) := by + let A := p.channels hz + let e := p.unitLayout hz + let f := e.symm.trans ((A.point.sumCongr ex).trans (combined A.inventory l)) + have inner (i : G'.E × Bool) : f (p.unitOf hz i.1 i.2) = extendL A.inventory l (A.point i) := by + change f (e (.inl i)) = _ + simp only [f, Equiv.trans_apply, Equiv.symm_apply_apply] + rfl + have out (i : outer S r (bundleSize v q)) : f i.val = extendR A.inventory l (ex i) := by + change f (e (.inr i)) = _ + simp only [f, Equiv.trans_apply, Equiv.symm_apply_apply] + rfl + have hf (i) : (f i).1 = i.1 ∧ (f i).2.1 = i.2.1 := by + rcases p.unit_cases hz i with he | ⟨j, b, rfl⟩ + · rw [out ⟨i, he⟩] + exact hx _ + · rw [inner (j, b)] + exact ⟨rfl, rfl⟩ + choose g hg using localize f hf + let b : Pieces S r (append A.inventory l) v q := ⟨p.all_uniform hm, g⟩ + have he (i) : b.equiv i = f i := by obtain ⟨s, t, i⟩ := i; exact (hg s t i).symm + exact ⟨b, fun i t => (he _).trans (inner (i, t)), fun j => (he _).trans (out j)⟩ + +open scoped Classical in +/-- The value specified by `(p.exists_pieces hz hm ex hx).choose`. -/ +def pieces : Pieces S r (append (p.channels hz).inventory l) v q := + (p.exists_pieces hz hm ex hx).choose + +open scoped Classical in +theorem pieces_inner (i : G'.E) (b : Bool) : + (p.pieces hz hm ex hx).equiv (p.unitOf hz i b) = extendL _ l ((p.channels hz).point (i, b)) := + (p.exists_pieces hz hm ex hx).choose_spec.1 i b + +open scoped Classical in +theorem pieces_outer (j : outer S r (bundleSize v q)) : + (p.pieces hz hm ex hx).equiv j.val = extendR (p.channels hz).inventory l (ex j) := + (p.exists_pieces hz hm ex hx).choose_spec.2 j + +end Assembly.Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- +# Checking an injective scatter + +A source presents its variable destination address. At each named +destination, a flag activates the opposite packet. Pairing checks +the flags as well as the transmitted payloads. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Transcript Messages Install + +variable {F X I J D : Type} {A j z w u : ℕ} + +open scoped Classical in +private theorem pairing (name : J ↪ Val (word A)) (e : I ↪ J) (r : I ⊕ J ↪ Fin (2 ^ j)) + (v : Fin (2 ^ j) → Val (row A z)) (active : J → Bool) + (src : I → Val (word z)) (dst : J → Val (word z)) + (left : ∀ i, v (r (.inl i)) = assemble (true, false, name (e i)) (src i)) + (right : ∀ k, v (r (.inr k)) = assemble (active k, true, name k) (dst k)) + (pad : ∀ k, k ∉ Set.range r → v k = Lookup.zero _) : + paired (List.ofFn v) ↔ (∀ k, active k = true ↔ k ∈ Set.range e) ∧ ∀ i, dst (e i) = src i := by + constructor + · intro h + have mate (k) (hk : (v k).1 = true) : ∃ l, v (r l) = reverse A z (v k) := by + have hs : reverse A z (v k) ∈ List.ofFn v := + h.subset (List.mem_map_of_mem (List.mem_ofFn.mpr ⟨k, rfl⟩)) + obtain ⟨l, hl⟩ := List.mem_ofFn.mp hs + by_cases h' : l ∈ Set.range r + · obtain ⟨i, rfl⟩ := h' + exact ⟨i, hl⟩ + rw [pad _ h'] at hl + have he := congrArg Prod.fst hl + change false = (v k).1 at he + rw [hk] at he + contradiction + have send (i) : active (e i) = true ∧ dst (e i) = src i := by + obtain ⟨k, hk⟩ := mate (r (.inl i)) (by rw [left]; rfl) + rw [left, reverse_assemble] at hk + cases k with + | inl l => + rw [left] at hk + have h' := congrArg (header A z) hk + simp [header_assemble, opposite] at h' + | inr l => + rw [right] at hk + have h' : active l = true ∧ l = e i := by + simpa [header_assemble, opposite] using congrArg (header A z) hk + obtain ⟨hflag, rfl⟩ := h' + rw [hflag] at hk + exact ⟨hflag, assemble_injective _ hk⟩ + refine ⟨fun k => ⟨fun hk => ?_, by rintro ⟨i, rfl⟩; exact (send i).1⟩, fun i => (send i).2⟩ + obtain ⟨l, hl⟩ := mate (r (.inr k)) (by rw [right]; exact hk) + rw [right, hk, reverse_assemble] at hl + cases l with + | inl i => + rw [left] at hl + have h' : e i = k := by + simpa [header_assemble, opposite] using congrArg (header A z) hl + exact ⟨i, h'⟩ + | inr i => + rw [right] at hl + have h' := congrArg (header A z) hl + simp [header_assemble, opposite] at h' + · rintro ⟨flags, payload⟩ + let g := ((Function.Embedding.refl I).sumMap e).trans r + let s : Equiv.Perm (I ⊕ I) := Equiv.sumComm I I + have on (i) := (flags (e i)).mpr ⟨i, rfl⟩ + have he : reverse A z ∘ v = v ∘ s.viaEmbedding g := by + funext k + simp only [Function.comp_apply] + by_cases hk : k ∈ Set.range g + · obtain ⟨p, rfl⟩ := hk + rw [Equiv.Perm.viaEmbedding_apply] + cases p with + | inl i => + change reverse A z (v (r (.inl i))) = v (r (.inr (e i))) + rw [left, right, on, payload, reverse_assemble] + rfl + | inr i => + change reverse A z (v (r (.inr (e i)))) = v (r (.inl i)) + rw [left, right, on, payload, reverse_assemble] + rfl + rw [Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ hk] + by_cases hp : k ∈ Set.range r + · obtain ⟨i | l, rfl⟩ := hp + · exact (hk ⟨.inl i, rfl⟩).elim + · have hoff : active l = false := Bool.eq_false_iff.mpr fun h => by + obtain ⟨i, rfl⟩ := (flags l).mp h + exact hk ⟨.inr i, rfl⟩ + rw [right, hoff, reverse_assemble] + rfl + rw [pad _ hp] + rfl + unfold paired + rw [List.map_ofFn, he] + exact Equiv.Perm.ofFn_comp_perm _ _ + +variable [Field F] [Fintype X] [Fintype J] [Fintype D] + +open scoped Classical in +private def blank (used : J → X ⊕ Bool) (dst : J → D → X ⊕ Bool) (x : X → Bool) := + ∀ v k, Sum.elim x id (used v) ≠ true → Sum.elim x id (dst v k) = false + +open scoped Classical in +private theorem blank_net (used : J → X ⊕ Bool) (dst : J → D → X ⊕ Bool) : + Weight F (fun x => if blank used dst x then 1 else 0) + (Fintype.card X + 70 * (Fintype.card J * Fintype.card D) + 17) := by + let bad (x : X → Bool) (p : J × D) := + decide (Sum.elim x id (used p.1) ≠ true ∧ Sum.elim x id (dst p.1 p.2) ≠ false) + have h : Depends bad 2 := by + rintro ⟨v, k⟩ + obtain ⟨S, hS, hs⟩ := tap_depends used v + obtain ⟨T, hT, ht⟩ := tap_depends (dst v) k + refine ⟨S ∪ T, (Finset.card_union_le S T).trans (by omega), fun x y he => ?_⟩ + have h₁ := hs x y (fun i hi => he i (Finset.mem_union_left _ hi)) + have h₂ := ht x y (fun i hi => he i (Finset.mem_union_right _ hi)) + simp only [Function.comp_apply] at h₁ h₂ + simp only [bad, h₁, h₂] + have net := ((h.bnet F).comp (BNet.any F (J × D))).weight + (Weight.dense F Unit (fun v => if v () then 0 else 1)) + convert net using 1 + · funext x + have e : (∃ p, bad x p = true) ↔ ¬ blank used dst x := by + simp [bad, blank] + simp only [Function.comp_apply, decide_eq_true_eq, e, ite_not] + · simp [localCost] + omega + +open scoped Classical in +theorem wide_mul {G : Set (Table F)} (hu : 3 ≤ u) + {f g : (X → Bool) → F} {m n : ℕ} (hf : WideWeight F u G f m) (hg : WideWeight F u G g n) : + WideWeight F u G (fun x => f x * g x) (4 * Fintype.card X + m + n) := by + intro a i + obtain ⟨v, hv, hf⟩ := hf a i + obtain ⟨r, hr, hg⟩ := hg a i + obtain ⟨d, hd, dup⟩ := DWide.of_dnet (L := G) hu (DNet.dup F a) + rw [Fintype.card_congr i, card_slots] + refine ⟨d + (v + r), by omega, ?_⟩ + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + using dup.comp ((hf.par hg).post (.unit' _)) + +open scoped Classical in +/-- A fixed checker works for every injective address assignment. It +forces values outside the image to zero and determines the use flags. -/ +theorem scatter (F : Type) [Field F] [Fintype I] (name : J ↪ Val (word A)) + (addr : I → slots (word A) → X ⊕ Bool) (src : I → D → X ⊕ Bool) + (dst : J → D → X ⊕ Bool) (used : J → X ⊕ Bool) + (hj : w ≤ j) (hj' : j ≤ 2 * w) (hu : 3 ≤ u) (ha : 2 * 2 ^ j * (4 * w) ≤ u) + (hh : A + Fintype.card D + 2 ≤ 4 * w) (hi : Fintype.card I + Fintype.card J ≤ 2 ^ j) : + ∃ f : (X → Bool) → F, WideWeight F u (SortTables F w) f (10000 * (Fintype.card X + 2 ^ j * w)) ∧ + ∀ (x : X → Bool) (e : I ↪ J), + (∀ i, bits (word A) (name (e i)) = Sum.elim x id ∘ addr i) → + f x = if (∀ v, Sum.elim x id (used v) = true ↔ v ∈ Set.range e) ∧ + ∀ v k, Sum.elim x id (dst v k) = + Function.extend e (fun i => Sum.elim x id (src i k)) (fun _ => false) v + then 1 else 0 := by + let z := 4 * w - (A + 2) + have hz : A + z + 2 = 4 * w := by unfold z; omega + let r : I ⊕ J ↪ Fin (2 ^ j) := (Function.Embedding.nonempty_of_card_le (by simpa using hi)).some + let p : D ↪ slots (word z) := (Function.Embedding.nonempty_of_card_le (by + rw [card_slots, wd_word]; omega)).some + let body (k : D → X ⊕ Bool) := Function.extend p k (fun _ => Sum.inr false) + let head : I ⊕ J → slots (word (A + 2)) → X ⊕ Bool := Sum.elim + (fun i => Sum.elim (fun _ => .inr true) (Sum.elim (fun _ => .inr false) (addr i))) + (fun v => Sum.elim (fun _ => used v) (Sum.elim (fun _ + => .inr true) (Sum.inr ∘ bits (word A) (name v)))) + let tap := Function.extend r (fun k => joinTap (head k) (body (Sum.elim src dst k))) + (fun _ => Sum.inr ∘ bits (row A z) (Lookup.zero _)) + have net := wide_mul hu (packet F hj hj' hu (by rw [hz]; exact ha) (by omega) hz.le tap) + (of_weight hu (blank_net (F := F) used dst)) + refine ⟨fun x => (if paired (packetRows tap x) then 1 else 0) * + (if blank used dst x then 1 else 0), ?_, fun x e he => ?_⟩ + · intro a ix + obtain ⟨n, hn, hnet⟩ := net a ix + refine ⟨n, ?_, hnet⟩ + have hJD := Nat.mul_le_mul (show Fintype.card J ≤ 2 ^ j by omega) + (show Fintype.card D ≤ 4 * w by omega) + have hp := Nat.le_mul_of_pos_right (2 ^ j) (by omega : 0 < w) + have hp' := Nat.two_pow_pos j + ring_nf at hn hJD hp ⊢ + omega + let val := Sum.elim x id + let data (k : D → X ⊕ Bool) := (bits (word z)).symm (val ∘ body k) + let v (k : Fin (2 ^ j)) := (bits (row A z)).symm (val ∘ tap k) + have left (i) : v (r (.inl i)) = assemble (true, false, name (e i)) (data (src i)) := by + unfold v tap + rw [r.injective.extend_apply, decode_join] + have hh : bits (word (A + 2)) (true, false, name (e i)) = val ∘ head (.inl i) := by + funext k + rcases k with _ | _ | k + · rfl + · rfl + · exact congrFun (he i) k + rw [← hh, Equiv.symm_apply_apply] + rfl + have right (k) : v (r (.inr k)) = assemble (val (used k), true, name k) (data (dst k)) := by + unfold v tap + rw [r.injective.extend_apply, decode_join] + have hh : bits (word (A + 2)) (val (used k), true, name k) = val ∘ head (.inr k) := by + funext l + rcases l with _ | _ | l <;> rfl + rw [← hh, Equiv.symm_apply_apply] + rfl + have pad (k) (hk : k ∉ Set.range r) : v k = Lookup.zero _ := by + unfold v tap + rw [Function.extend_apply' _ _ _ hk] + exact (bits _).symm_apply_apply _ + have same (k l : D → X ⊕ Bool) : data k = data l ↔ ∀ i, val (k i) = val (l i) := by + unfold data + rw [(bits _).symm.injective.eq_iff] + constructor + · intro h i + simpa [body, p.injective.extend_apply] using congrFun h (p i) + · intro h + funext j + by_cases hj : j ∈ Set.range p + · obtain ⟨i, rfl⟩ := hj + simp [body, p.injective.extend_apply, h] + · simp [body, Function.extend_apply' _ _ _ hj] + have iff' : paired (packetRows tap x) ∧ blank used dst x ↔ + (∀ v, val (used v) = true ↔ v ∈ Set.range e) ∧ + ∀ v k, val (dst v k) = Function.extend e (fun i => val (src i k)) (fun _ => false) v := by + change paired (List.ofFn v) ∧ _ ↔ _ + rw [pairing name e r v (val ∘ used) (data ∘ src) (data ∘ dst) left right pad] + simp only [Function.comp_apply, same] + constructor + · rintro ⟨⟨flags, payload⟩, blank⟩ + refine ⟨flags, fun j k => ?_⟩ + by_cases hj : j ∈ Set.range e + · obtain ⟨i, rfl⟩ := hj + rw [e.injective.extend_apply, payload] + · rw [Function.extend_apply' _ _ _ hj] + exact blank j k (fun h => hj ((flags j).mp h)) + · rintro ⟨flags, payload⟩ + refine ⟨⟨flags, fun i k => ?_⟩, fun j k hj => ?_⟩ + · rw [payload, e.injective.extend_apply] + · have h : j ∉ Set.range e := fun he => hj ((flags j).mpr he) + exact (payload j k).trans (Function.extend_apply' _ _ _ h) + simp only [ite_mul, one_mul, zero_mul, ← ite_and, iff'] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Pairing internal port rows + +A key contains the two ordered hosts and a row ordinal shared by +both ends. Exterior slots use other lanes and never participate in +this test. Padding makes comparison of entire rows exact. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent + +namespace BatchDescent.PackRows.Channels + +variable {E : Type} [Fintype E] {H m d d' u v K n : ℕ} + (A : Channels E H m d) {r : Inventory H m d'} + (L : Layout (append A.inventory r) u v K) (hs : ∀ i, size (append A.inventory r i) u ≤ v) + +include hs in +theorem number_lt (i : E) : rank A.inventory (A.point (i, false)) / (2 * u) < v := by + let a := append A.inventory r + let t := extendL A.inventory r (A.point (i, false)) + have hl : rank a t / (2 * u) < ports (a t.1) u t.2.2.1 := (portRow a u t).2.2.isLt + have hp : ports (a t.1) u t.2.2.1 ≤ size (a t.1) u := by + have he := Finset.single_le_sum (f := ports (a t.1) u) (fun _ _ => Nat.zero_le _) + (Finset.mem_univ t.2.2.1) + unfold size + omega + have hn := hl.trans_le (hp.trans (hs t.1)) + simpa only [a, t, rank_extendL] using hn + +/-- The value specified by `(x.2, A.host false x.1, A.host true x.1, ⟨rank A.inventory (A.point +(x.1, false)) / (2 * u), A.number_lt hs _⟩)`. -/ +def label (_L : Layout (append A.inventory r) u v K) (hs : ∀ i, size (append A.inventory r i) u ≤ v) + (x : E × Bool) : Bool × (Fin H × Fin H × Fin v) := + (x.2, A.host false x.1, A.host true x.1, + ⟨rank A.inventory (A.point (x.1, false)) / (2 * u), A.number_lt hs _⟩) + +private theorem same (x y : E × Bool) : + A.label L hs x = A.label L hs y ↔ (A.loc L x.1 x.2).1 = (A.loc L y.1 y.2).1 := by + rw [A.row_eq] + simp [label, Prod.ext_iff, Fin.ext_iff] + +variable (code : (Fin H × Fin H × Fin v) ↪ Val (word n)) + +/-- Indexes the header by the coordinates of `Links.header (fun x : E × Bool => (A.loc L x.1 +x.2).1) (A.label L hs) code i`. -/ +def header (i : Address v K) := + Links.header (fun x : E × Bool => (A.loc L x.1 x.2).1) (A.label L hs) code i + +theorem header_at (i : E) (b : Bool) : + A.header L hs code (A.loc L i b).1 = (true, b, code (A.label L hs (i, b)).2) := + Links.header_at _ _ _ (A.same L hs) (i, b) + +theorem header_other (j : Address v K) (hj : ∀ i b, (A.loc L i b).1 ≠ j) : + A.header L hs code j = (false, false, Lookup.zero n) := by + apply Links.header_other + rintro ⟨⟨i, b⟩, he⟩ + exact hj i b he + +theorem header_outer (t : Endpoints r) : + A.header L hs code (L.portSlots (extendR A.inventory r t)).1 = (false, false, Lookup.zero n) + := by + apply header_other + intro i b he + exact channels_disjoint _ _ _ _ ((L.row_eq _ _).mp he).1.2 + +private theorem plan : + ∃ plan : PacketPlan (Address v K) n, plan.head = A.header L hs code ∧ + ∀ i b, plan.peer (A.loc L i b).1 = (A.loc L i (!b)).1 := by + obtain ⟨plan, hp, hr⟩ := Links.build_packet (fun x : E × Bool => (A.loc L x.1 x.2).1) + (A.label L hs) code (A.same L hs) (fun x => ⟨(x.1, !x.2), rfl⟩) + exact ⟨plan, hp, fun i b => hr (i, b) (i, !b) rfl⟩ + +end BatchDescent.PackRows.Channels +namespace Assembly.Scheme.Posting +open BatchDescent BatchDescent.PackRows Packing Coloring + +variable {F T : Type} [Field F] {x y : Wire} {e : Fringe x y T} {h q v u K d n : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F e h (bundleSize v q)} + (p : S.Posting r G) (hz : 0 < bundleSize v q) + (hm : ∀ a, S.peer r a = none → bundleSize v q ∣ S.width r a) + {l : Inventory (2 ^ S.m) (2 ^ S.h) d} + (ex : outer S r (bundleSize v q) ≃ Endpoints l) + (hx : ∀ j, (ex j).1 = j.val.1 ∧ (ex j).2.1 = j.val.2.1) + (L : PackRows.Layout (append (p.channels hz).inventory l) u v K) + (hs : ∀ i, size (append (p.channels hz).inventory l i) u ≤ v) + (code : (Fin (2 ^ S.m) × Fin (2 ^ S.m) × Fin v) ↪ Val (word n)) + +theorem core_plan : + let B := p.pieces hz hm ex hx + ∃ plan : PacketPlan (Address v K) n, plan.head = (p.channels hz).header L hs code ∧ + ∀ y : Address v K × Row (Fin (2 * v)) (Fin (2 * u)) (Fin q) → Bool, + Links.pad (B.inside L) y → + ((∀ i, (plan.head i).1 = true → Function.curry y (plan.peer i) = Function.curry y i) ↔ + ∀ a b, S.Joins r a b → y (B.inside L a) = y (B.inside L b)) := by + let B := p.pieces hz hm ex hx + let A := p.channels hz + let join := BatchDescent.join S r _ B.uniform + let pin (i : G.E) (b : Bool) (t : Fin (bundleSize v q)) := join (p.unitOf hz i b, t) + have loc (i b t) : B.inside L (pin i b t) = + ((A.loc L i b).1, (A.loc L i b).2, finProdFinEquiv.symm t) := by + unfold pin join + rw [B.inside_join, p.pieces_inner] + rfl + have pair (i b t) : S.Joins r (pin i b t) (pin i (!b) t) := ⟨p.span_peer hz _ _, rfl⟩ + obtain ⟨plan, he, peer⟩ := A.plan L hs code + refine ⟨plan, he, fun y hy => ?_⟩ + constructor + · intro check s t hst + obtain ⟨⟨s, i⟩, rfl⟩ := join.surjective s + obtain ⟨⟨t, j⟩, rfl⟩ := join.surjective t + obtain ⟨rfl, k, b, rfl, rfl⟩ := p.joined hz B.uniform hst + have hh := check (A.loc L k b).1 (by rw [he, A.header_at]) + change y (B.inside L (pin k b i)) = y (B.inside L (pin k (!b) i)) + rw [loc, loc, ← A.col_eq L k b, ← peer] + exact (congrFun hh _).symm + · intro links + have present (i : Address v K) (hi : (plan.head i).1 = true) + (t : Row (Fin (2 * v)) (Fin (2 * u)) (Fin q)) (ht : y (i, t) = true) : + y (plan.peer i, t) = true := by + obtain ⟨a, ha⟩ : (i, t) ∈ Set.range (B.inside L) := by + by_contra hh + exact Bool.false_ne_true ((hy _ hh).symm.trans ht) + obtain ⟨⟨a, j⟩, rfl⟩ := join.surjective a + rcases p.unit_cases hz a with ha' | ⟨k, b, rfl⟩ + · have hf := show B.equiv a = _ from p.pieces_outer hz hm ex hx ⟨a, ha'⟩ + unfold join at ha + rw [B.inside_join, hf] at ha + rw [he, ← (Prod.mk.inj ha).1, A.header_outer] at hi + cases hi + · have hval := links _ _ (pair k b j) + change B.inside L (pin k b j) = (i, t) at ha + rw [loc] at ha + obtain ⟨rfl, rfl⟩ := Prod.mk.inj ha + rw [loc, loc, ← A.col_eq L k b, ← peer] at hval + exact hval.symm.trans ht + intro i hi + have hp : (plan.head (plan.peer i)).1 = true := by rw [plan.pairs]; exact hi + funext t + apply Bool.eq_iff_iff.mpr + exact ⟨fun h => by simpa [plan.square] using present _ hp t h, present i hi t⟩ + +end Assembly.Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- +# Generating the internal packet headers + +The group of rows at a port shares a pair of host names. Local +lengths suffice to determine whether a row is active and to produce +its direction and ordinal. No payload bits enter these decisions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows.Channels + +variable {E : Type} [Fintype E] {H m d e u v K n : ℕ} + +/-- Computes the decode lane by the application `Prod.map finTwoEquiv id (finProdFinEquiv.symm +j)`. -/ +def decodeLane (j : Fin (2 * d)) : Bool × Fin d := + Prod.map finTwoEquiv id (finProdFinEquiv.symm j) + +/-- Returns `some ((decodeLane ⟨j.val, h.1⟩).1, ⟨k, h.2.1⟩)` when `h : j.val < 2 * d ∧ k < v ∧ k +* (2 * u) < ∑ i, l i j` holds, and `none` otherwise. -/ +def source (d e u v : ℕ) (l : Lengths m (2 * d + e)) (j : Fin (2 * d + e)) (k : ℕ) : + Option (Bool × Fin v) := + if h : j.val < 2 * d ∧ k < v ∧ k * (2 * u) < ∑ i, l i j then + some ((decodeLane ⟨j.val, h.1⟩).1, ⟨k, h.2.1⟩) + else none + +/-- The names of type `Fin H × Fin H`, constructed using `decodeLane ⟨j.val, h⟩`. -/ +def names (neighbor : Fin H → Fin d → Fin H) (i : Fin H) (j : Fin (2 * d + e)) : Fin H × Fin H := + if h : j.val < 2 * d then + let lane := decodeLane ⟨j.val, h⟩ + let other := neighbor i lane.2 + if lane.1 then (other, i) else (i, other) + else (i, i) + +/-- In the case `some (b, k)`, this construction gives `(true, b, code (names.1, names.2, k))`. -/ +def fill (code : (Fin H × Fin H × Fin v) ↪ Val (word n)) (names : Fin H × Fin H) : + Option (Bool × Fin v) → Val (word (n + 2)) + | some (b, k) => (true, b, code (names.1, names.2, k)) + | none => (false, false, Lookup.zero n) + +variable (A : Channels E H m (2 * d)) {x : Inventory H m e} + (L : Layout (append A.inventory x) u v K) (hs : ∀ i, size (append A.inventory x i) u ≤ v) + (code : (Fin H × Fin H × Fin v) ↪ Val (word n)) + +/-- The condition `∀ i b, (decodeLane (A.lane b i)).1 = b ∧ neighbor (A.host b i) (decodeLane +(A.lane b i)).2 = A.host (!b) i` on the specified data. -/ +def Names (neighbor : Fin H → Fin d → Fin H) : Prop := + ∀ i b, (decodeLane (A.lane b i)).1 = b ∧ + neighbor (A.host b i) (decodeLane (A.lane b i)).2 = A.host (!b) i + +omit [Fintype E] in +private theorem names_at (neighbor : Fin H → Fin d → Fin H) (hn : A.Names neighbor) + (i : E) (b : Bool) : + names neighbor (A.host b i) (Fin.castAdd e (A.lane b i)) = (A.host false i, A.host true i) := by + unfold names + rw [dite_eq_left (show (Fin.castAdd e (A.lane b i)).val < 2 * d from (A.lane b i).isLt)] + change (if (decodeLane (A.lane b i)).1 then _ else _) = _ + rw [(hn i b).1] + cases b + · exact Prod.ext rfl (hn i false).2 + · exact Prod.ext (hn i true).2 rfl + +private theorem rank_lt {d' : ℕ} (l : Inventory H m d') (t : Endpoints l) : + rank l t < ∑ i, l t.1 i t.2.2.1 := + (order (port (l t.1) t.2.2.1) ⟨t.2.1, t.2.2.2⟩).isLt + +private theorem live (i : Fin H) (j : Fin (2 * d + e)) (k : Fin (ports (append A.inventory x i) u + j)) + (hu : 0 < u) (hj : j.val < 2 * d) (hk : k.val * (2 * u) < ∑ t, append A.inventory x i t j) : + ∃ t b, (A.loc L t b).1 = L.portLoc ⟨i, j, k⟩ := by + let l : Fin (2 * d) := ⟨j.val, hj⟩ + have he : Fin.castAdd e l = j := rfl + have hv : k.val * (2 * u) < ∑ t, port (A.inventory i) l t := by + simpa only [← he, append_left, port] using hk + let o := order (port (A.inventory i) l) + let p := o.symm ⟨_, hv⟩ + let q : Endpoints A.inventory := ⟨i, p.1, l, p.2⟩ + have hr : rank A.inventory q = k.val * (2 * u) := congrArg Fin.val (o.apply_symm_apply ⟨_, hv⟩) + obtain ⟨⟨t, b⟩, hb⟩ := A.point.surjective q + refine ⟨t, b, ?_⟩ + unfold loc + rw [hb, L.locate] + apply congrArg L.portLoc + change (⟨i, j, _⟩ : PortRows (append A.inventory x) u) = _ + apply congrArg (fun q => (⟨i, j, q⟩ : PortRows (append A.inventory x) u)) + apply Fin.ext + change rank _ (extendL A.inventory x q) / (2 * u) = k.val + rw [rank_extendL, hr, Nat.mul_div_cancel _ (by omega)] + +theorem header_eq_fill (hu : 0 < u) (neighbor : Fin H → Fin d → Fin H) (hn : A.Names neighbor) + (i : Fin H) (j : Fin (2 * d + e)) (k : Fin (ports (append A.inventory x i) u j)) : + A.header L hs code (L.portLoc ⟨i, j, k⟩) = fill code (names neighbor i j) + (source d e u v (append A.inventory x i) j k.val) := by + classical + by_cases occurs : ∃ t b, (A.loc L t b).1 = L.portLoc ⟨i, j, k⟩ + · obtain ⟨t, b, he⟩ := occurs + let s := extendL A.inventory x (A.point (t, b)) + have hp : portRow _ u s = ⟨i, j, k⟩ := L.portLoc.injective ((L.locate s).symm.trans he) + have hi : A.host b t = i := congrArg Sigma.fst hp + have hj : Fin.castAdd e (A.lane b t) = j := congrArg (·.2.1) hp + have hk : rank _ s / (2 * u) = k.val := congrArg (·.2.2.val) hp + have hl : (A.label L hs (t, b)).2.2.2.val = k.val := by + simpa only [label, s, rank_extendL, A.rank_eq t b] using hk + have hok : j.val < 2 * d ∧ k.val < v ∧ k.val * (2 * u) < ∑ a, append A.inventory x i a j := by + refine ⟨hj ▸ (A.lane b t).isLt, hl ▸ (A.label L hs (t, b)).2.2.2.isLt, ?_⟩ + have h := (Nat.div_mul_le_self (rank _ s) (2 * u)).trans_lt (rank_lt _ s) + rw [hk, show s.2.2.1 = j from hj, show s.1 = i from hi] at h + exact h + rw [← he, header_at, source, dite_eq_left hok, fill] + have eq : (⟨j.val, hok.1⟩ : Fin (2 * d)) = A.lane b t := + Fin.ext (congrArg (fun z : Fin (2 * d + e) => z.val) hj.symm) + have names_eq : names neighbor i j = (A.host false t, A.host true t) := by + rw [← hi, ← hj, A.names_at neighbor hn] + rw [names_eq, eq, (hn t b).1, show (⟨k.val, hok.2.1⟩ : Fin v) = _ from Fin.ext hl.symm] + rfl + · have he : ∀ t b, (A.loc L t b).1 ≠ L.portLoc ⟨i, j, k⟩ := fun t b hh => occurs ⟨t, b, hh⟩ + have no : ¬ (j.val < 2 * d ∧ k.val < v ∧ k.val * (2 * u) < ∑ t, append A.inventory x i t j) := + fun h => occurs (A.live L i j k hu h.1 h.2.2) + rw [source, dite_eq_right no, fill, A.header_other L hs code _ he] + +theorem header_absent (i : Address v K) (h : i ∉ Set.range L.portLoc) : + A.header L hs code i = (false, false, Lookup.zero n) := by + apply header_other + intro e b he + exact h ⟨_, (L.locate _).symm.trans he⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows.Channels + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +open BatchDescent BatchDescent.PackRows Packing Coloring + +variable {F T : Type} [Field F] {x y : Wire} {f : Fringe x y T} {h z : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F f h z} (p : S.Posting r G) (hz : 0 < z) + +theorem names : (p.channels hz).Names (fun i => (r i).1) := by + intro i b + simp only [channels, lane, Channels.decodeLane, Equiv.symm_apply_apply, + Prod.map, Equiv.apply_symm_apply, id_eq, true_and] + exact p.neighbor hz i b + +theorem header_eq_fill {d u v K n : ℕ} {l : Inventory (2 ^ S.m) (2 ^ S.h) d} + (L : PackRows.Layout (append (p.channels hz).inventory l) u v K) + (hs : ∀ i, size (append (p.channels hz).inventory l i) u ≤ v) + (code : (Fin (2 ^ S.m) × Fin (2 ^ S.m) × Fin v) ↪ Val (word n)) (hu : 0 < u) + (i : B S.m) (j : Fin (2 * 2 ^ S.d + d)) (k : Fin (ports (append (p.channels hz).inventory l i) + u j)) : + (p.channels hz).header L hs code (L.portLoc ⟨i, j, k⟩) = + Channels.fill code (Channels.names (fun i => (r i).1) i j) + (Channels.source (2 ^ S.d) d u v (append (p.channels hz).inventory l i) j k.val) := + (p.channels hz).header_eq_fill L hs code hu _ (p.names hz) i j k + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Posting +end + +/- +# Evaluating all terminal tables and checking the internal links + +Port rows, including padding, are actual bits on the common tape. +A single tensor works for every layout described on that tape. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +open Assembly Coloring Transcript + +open Classical in +/-- The quantity computed by `Row (Fin (2 * v)) (Fin (2 * u)) (Fin p)`. -/ +abbrev Body (u v p : ℕ) := Row (Fin (2 * v)) (Fin (2 * u)) (Fin p) +open Classical in +/-- Indexes the tape by the coordinates of `Address v K × Body u v p`. -/ +abbrev Tape (u v K p : ℕ) := Address v K × Body u v p + +variable {F X : Type} {S : Scheme F} {r : S.format.obj} + {u v K p d a : ℕ} {l : Inventory (2 ^ S.m) (2 ^ S.h) d} + +open Classical in +theorem pad_iff (A : Pieces S r l v p) (L : PackRows.Layout l u v K) + (y : Tape u v K p → Bool) : + Links.pad (A.inside L) y ↔ L.Padded (fun i t => y (i.1, i.2, t)) := by + have eq (i : Address v K × Fin (2 * u)) (t : Payload v (Fin p)) : + (i.1, i.2, t) ∈ Set.range (A.inside L) ↔ i ∈ Set.range L.portSlots := by + constructor + · rintro ⟨q, hq⟩ + exact ⟨(A.slots q).1, congrArg (fun j => (j.1, j.2.1)) hq⟩ + · rintro ⟨q, rfl⟩ + refine ⟨A.slots.symm (q, t), ?_⟩ + unfold Pieces.inside + simp + constructor + · exact fun h i hi t => h (i.1, i.2, t) (mt (eq _ _).mp hi) + · rintro h ⟨j, k, t⟩ he + exact h (j, k) (mt (eq _ _).mpr he) t + +open Classical in +/-- The data for the wires construction, including `control`, `format`, `head`, `body`. -/ +structure Wires (S : Scheme F) (u v K p a : ℕ) (X : Type) where + /-- The control datum of type `Fin K → Route v u → X ⊕ Bool`. -/ + control : Fin K → Route v u → X ⊕ Bool + /-- The `Wires` component of type `Address v K → Tag (2 ^ S.h) S.ℓ u → X ⊕ Bool`. -/ + format : Address v K → Tag (2 ^ S.h) S.ℓ u → X ⊕ Bool + /-- The `Wires` component of type `Address v K → slots (word (a + 2)) → X ⊕ Bool`. -/ + head : Address v K → slots (word (a + 2)) → X ⊕ Bool + /-- The `Wires` component of type `Tape u v K p → X ⊕ Bool`. -/ + body : Tape u v K p → X ⊕ Bool + +namespace Wires +variable (t : Wires S u v K p a X) + +open Classical in +/-- The value specified by `t.body ((i, s.1), s.2, b)`. -/ +def port (i : Fin K) (s : Socket v u) (b : Payload v (Fin p)) := + t.body ((i, s.1), s.2, b) + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def read (x : X → Bool) : Tape u v K p → Bool := Sum.elim x id ∘ t.body + +open Classical in +/-- The supplied of type `Prop` for the given inputs. -/ +def Supplied (A : Pieces S r l v p) (ha : Pieces.Room (l := l) (u := u)) + (L : PackRows.Layout l u v K) (heads : Address v K → Val (word (a + 2))) (x : X → Bool) : Prop + := + (∀ g, Sum.elim x id ∘ t.control g = L.moves g) ∧ + (∀ i, Sum.elim x id ∘ t.format i = L.format (A.index ha) (labels S r) i) ∧ + ∀ i, bits (word (a + 2)) (heads i) = Sum.elim x id ∘ t.head i + +variable [Field F] + +open Classical in +/-- The test of type `F`, constructed using `t.read x`. -/ +def test (A : Pieces S r l v p) (L : PackRows.Layout l u v K) + (π : PacketPlan (Address v K) a) (x : X → Bool) : F := + let y := t.read x + if Links.pad (A.inside L) y ∧ + (∀ i, (π.head i).1 = true → Function.curry y (π.peer i) = Function.curry y i) + then ∏ j, S.table r j (y ∘ A.inside L ∘ S.port r j) else 0 + +open Classical in +/-- The data for the fits construction, including `lower`, `upper`, `gates`, `large`, `slots`. -/ +structure Fits (S : Scheme F) (u v K p a w j cap : ℕ) : Prop where + lower : w ≤ j + upper : j + 1 ≤ 2 * w + gates : 3 ≤ cap + large : 2 * 2 ^ (2 * w) * (4 * w) ≤ cap + slots : K * (2 * v) ≤ 2 ^ j + move : (4 * v * u) ^ 2 + 2 * (2 * u * bundleSize v p) < j + table : 2 ^ S.h * (1 + S.ℓ + 2 * u ^ 2) + 2 * u * bundleSize v p < j + wide : w ≤ a + 2 * u * bundleSize v p + 2 + narrow : a + 2 * u * bundleSize v p + 2 ≤ 4 * w + +open Classical in +theorem service [Fintype X] {w j cap : ℕ} (ok : Fits S u v K p a w j cap) : + ∃ f : (X → Bool) → F, WideWeight F cap (SortTables F w) f + (500000 * (Fintype.card X + 2 ^ j * (1 + w))) ∧ + ∀ (r : S.format.obj) (d : ℕ) (l : Inventory (2 ^ S.m) (2 ^ S.h) d) + (A : Pieces S r l v p) (ha : Pieces.Room (l := l) (u := u)) + (L : PackRows.Layout l u v K) (π : PacketPlan (Address v K) a) x, + t.Supplied A ha L π.head x → f x = t.test A L π x := by + have ar : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ cap := by + apply le_trans _ ok.large + have := ok.upper + gcongr; omega + have ht : Fintype.card (Body u v p) = 2 * u * bundleSize v p := by simp [Body, bundleSize] + have rows : Fintype.card (Address v K) ≤ 2 ^ j := by simpa using ok.slots + have move : Fintype.card (Route v u) + 2 * Fintype.card (Body u v p) < j := by + rw [width_route, ht]; exact ok.move + have ev : Fintype.card (Tag (2 ^ S.h) S.ℓ u) + Fintype.card (Body u v p) < j := by + rw [width_tag, ht]; exact ok.table + have h₁ := (packTables (entry S u v p) t.control t.format t.port).reassemble + ok.lower ok.upper ok.gates ar move ev rows + have h₂ := packed_zero (F := F) t.control t.port ok.lower ok.upper ok.gates ar + (show Fintype.card (Route v u) + Fintype.card (Body u v p) < j by omega) rows + let e : slots (word (2 * u * bundleSize v p)) ≃ Body u v p := + Fintype.equivOfCardEq (by rw [card_slots, wd_word, ht]) + obtain ⟨g, h₃, hg⟩ := packet_plan F ok.lower (by have := ok.upper; omega) ok.gates + (show 2 * 2 ^ j * (a + 2 * u * bundleSize v p + 2) ≤ cap by + apply le_trans _ ok.large + have := ok.upper + have := ok.narrow + gcongr; omega) ok.wide ok.narrow rows t.head (fun i k => t.body (i, e k)) + have H := wide_mul ok.gates h₂ (wide_mul ok.gates h₃ h₁) + refine ⟨fun x => zeroTest F t.control t.port x * + (g x * (packTables (entry S u v p) t.control t.format t.port).value x), ?_, ?_⟩ + · intro b i + obtain ⟨m, hm, hm'⟩ := H b i + refine ⟨m, ?_, hm'⟩ + have := Nat.mul_le_mul_left (2 ^ j) ok.upper + linarith + · rintro r d l A ha L π x ⟨hc, hf, hh⟩ + let y := t.read x + have check (i k : Address v K) : + (Sum.elim x id ∘ (fun b => t.body (i, e b))) = + (Sum.elim x id ∘ (fun b => t.body (k, e b))) ↔ + Function.curry y i = Function.curry y k := by + constructor + · intro h + funext b + obtain ⟨b, rfl⟩ := e.surjective b + exact congrFun h b + · exact fun h => congrArg (· ∘ e) h + have padded : L.Padded (readPort t.port x) ↔ Links.pad (A.inside L) y := + (pad_iff A L y).symm + have value : (packTables (entry S u v p) t.control t.format t.port).value x = + ∏ i, S.table r i (y ∘ A.inside L ∘ S.port r i) := + (packed_value L (A.index ha) _ x hc hf).trans (A.product ha L y) + dsimp only + rw [zeroTest_eq (F := F) L x hc, hg x π hh, value] + simp only [check, padded, test, y, ite_mul, one_mul, zero_mul, ite_and] + +end Wires +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Observed.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Observed.lean new file mode 100644 index 0000000000..610d0da9c0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Observed.lean @@ -0,0 +1,1043 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Pieces +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.PortRelay +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Header +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Exterior.Strips + +/-! # Checking short bin controls while hiding the unique anchor tape -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +open Coloring Transcript + +variable {H v K m d ℓ u : ℕ} {D Z X : Type} + +open Classical in +/-- The indexed operation `p.2.elim (decide ((i, p.1) ∈ Set.range e)) (fun k => Function.extend +e (fun j => src j k) (fun _ => false) (i, p.1))`. -/ +def anchored (e : Fin H ↪ Anchor v K) (src : Fin H → D → Bool) + (i : Fin K) (p : BinKey v D) : Bool := + p.2.elim (decide ((i, p.1) ∈ Set.range e)) + (fun k => Function.extend e (fun j => src j k) (fun _ => false) (i, p.1)) + +open Classical in +theorem BinData.anchored {code : (D → Bool) → Descriptor m d ℓ} {l : Inventory H m d} + (hv : 0 < v) (hs : ∀ i, size (l i) u ≤ v) (hk : bins l u v ≤ K) + {ix : Index l u} {f : Label H m ℓ} {src : Fin H → D → Bool} + (hlen : ∀ i, (code (src i)).len = l i) (hf : ∀ i, (code (src i)).label = f i) + (hi : ∀ i j p (k : Fin (l i j p)), (code (src i)).slot j p k.val = (ix i j ⟨p, k⟩).val) : + BinData code l u v K hv hs hk ix f src (PackRows.anchored (anchor l u v K hv hs hk) src) := + ⟨fun _ _ => decide_eq_true_iff, + fun i k => (anchor l u v K hv hs hk).injective.extend_apply (fun j => src j k) (fun _ + => false) i, hlen, hf, hi⟩ + +variable [Fintype X] [Fintype D] [Fintype Z] {w j h r cap : ℕ} + +open Classical in +/-- The public input determines every anchor bit. Summing over that +intermediate tape therefore preserves the scalar weight. -/ +theorem bin_service (F : Type) [Field F] (len : (D → Bool) → ℕ) + (code : (D → Bool) → Descriptor m d ℓ) (user : (D → Bool) → Fin d → Fin (2 ^ r) → Z → Bool) + (src : B h → D → X ⊕ Bool) (dst : Fin K → BinOut (2 ^ r) u m ℓ Z → X ⊕ Bool) + (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (hc : 3 ≤ cap) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ cap) + (hd : Fintype.card D + (r + 1) < j) (hsize : 2 ^ h + K * 2 ^ r ≤ 2 ^ j) + (hkey : Fintype.card (BinKey (2 ^ r) D) + Fintype.card (BinOut (2 ^ r) u m ℓ Z) < j) : + ∃ f : (X → Bool) → F, WideWeight F cap (SortTables F w) f (10 ^ 12 * (Fintype.card X + + 2 ^ j * (1 + w))) ∧ + ∀ (x : X → Bool) (l : Inventory (2 ^ h) m d) (hs : ∀ i, size (l i) u ≤ 2 ^ r) + (hk : bins l u (2 ^ r) ≤ K), + (∀ i, len (Sum.elim x id ∘ src i) = counts l u i) → + let t := anchored (anchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk) (fun i + => Sum.elim x id ∘ src i) + f x = if ∀ i, Sum.elim x id ∘ dst i = binFunction u code user (t i) then 1 else 0 := by + let Y := Fin K × BinKey (2 ^ r) D + let O := Fin K × BinOut (2 ^ r) u m ℓ Z + let get (i : Anchor (2 ^ r) K) (k : D) : (X ⊕ Y) ⊕ Bool := .inl (.inr (i.1, i.2, some k)) + let used (i : Anchor (2 ^ r) K) : (X ⊕ Y) ⊕ Bool := .inl (.inr (i.1, i.2, none)) + obtain ⟨t, ht, ht'⟩ := anchor_scatter (m := m) (d := d) (u := u) F len + (fun i => liftTap ∘ src i) get used hj hj' hc ha hd hsize + have hK : K ≤ 2 ^ j := (Nat.le_mul_of_pos_right K (Nat.two_pow_pos r)).trans + ((Nat.le_add_left _ _).trans hsize) + have hcap : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ cap := le_trans + (Nat.mul_le_mul (Nat.mul_le_mul_left 2 (Nat.pow_le_pow_right (by decide) hj')) (by omega)) ha + let input (i : Fin K) (k : BinKey (2 ^ r) D) : Y ⊕ Bool := .inl (i, k) + let tap : Y ⊕ O → (X ⊕ Y) ⊕ Bool := Sum.elim (fun y => .inl (.inr y)) (fun o + => liftTap (dst o.1 o.2)) + have hnet := binTransform F code user input (Equiv.refl O) hj hj' hc hcap hkey hK + obtain ⟨f, hf, hout⟩ := hide_unique hc ht (precompute hc ((tap_depends tap).bnet F) hnet) + refine ⟨f, ?_, fun x l hs hk hl => ?_⟩ + · have hy : Fintype.card Y + Fintype.card O ≤ 2 ^ j * (2 * w) := by + rw [show Fintype.card Y = K * Fintype.card (BinKey (2 ^ r) D) by + rw [Fintype.card_prod, Fintype.card_fin], + show Fintype.card O = K * Fintype.card (BinOut (2 ^ r) u m ℓ Z) by + rw [Fintype.card_prod, Fintype.card_fin], ← mul_add] + exact Nat.mul_le_mul hK (hkey.le.trans (by omega)) + intro a i + obtain ⟨q, hq, hn⟩ := hf a i + refine ⟨q, hq.trans ?_, hn⟩ + have hh := Nat.mul_le_mul_left (2 ^ j) (show j ≤ 2 * w by omega) + simp only [Fintype.card_sum, Install.localCost] + ring_nf at hy hh ⊢ + omega + let e := anchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk + let val := anchored e (fun i => Sum.elim x id ∘ src i) + let y : Y → Bool := Function.uncurry val + have unique (z : Y → Bool) : t (Sum.elim x z) = if y = z then 1 else 0 := by + rw [ht' _ l hs hk (by simpa only [read_lift_fun] using hl)] + simp only [get, used, Sum.elim_inl, Sum.elim_inr, Function.comp_apply, read_lift] + congr 1 + apply propext + constructor + · rintro ⟨on, data⟩ + funext ⟨i, k, q⟩ + cases q with + | none => exact Bool.eq_iff_iff.mpr (decide_eq_true_iff.trans (on (i, k)).symm) + | some j => exact (data (i, k) j).symm + · rintro rfl + exact ⟨fun _ => decide_eq_true_iff, fun _ _ => rfl⟩ + rw [hout x y unique] + simp only [Function.comp_apply] + congr 1 + apply propext + simp only [funext_iff, applyRows, tap, input, + Sum.elim_inl, Sum.elim_inr, Function.comp_def, read_lift] + exact ⟨fun h i k => (h (i, k)).symm, fun h p => (h p.1 p.2).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- +# Joining the two host names to a local header + +The physical layout of the identifier is fixed in advance. Each output +bit needs only the activity flag and one bit of the short or long record. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows.Channels +open Coloring Install Transcript + +variable {h r n : ℕ} + +open Classical in +/-- The quantity computed by `slots (word (r + 2))`. -/ +abbrev Short (r : ℕ) := slots (word (r + 2)) +open Classical in +/-- Indexes the long by the coordinates of `slots (word h) ⊕ slots (word h)`. -/ +abbrev Long (h : ℕ) := slots (word h) ⊕ slots (word h) + +open Classical in +/-- In the case `none => fun _`, this construction gives `false`. -/ +def short : Option (Bool × B r) → Short r → Bool + | none => fun _ => false + | some (b, i) => Sum.elim (fun _ => true) (Sum.elim (fun _ => b) ((Format.addr r).code i)) + +open Classical in +/-- The value specified by `(Format.pair (.addr h) (.addr h)).code x`. -/ +def long (x : B h × B h) : Long h → Bool := (Format.pair (.addr h) (.addr h)).code x + +open Classical in +/-- Indexes the fields by the coordinates of `Long h ⊕ slots (word r)`. -/ +abbrev Fields (h r : ℕ) := Long h ⊕ slots (word r) + +variable (hn : 2 * h + r ≤ n) + +open Classical in +/-- Embeds `Fields h r` into `slots (word n)`. -/ +def placeBits : Fields h r ↪ slots (word n) := + (Function.Embedding.nonempty_of_card_le (show Fintype.card (Fields h r) + ≤ Fintype.card (slots (word n)) + by simpa [Fields, Long, two_mul] using hn)).some + +open Classical in +/-- Returns `some hit.choose` when `hit : ∃ j, placeBits hn j = i` holds, and `none` otherwise. -/ +def takeBit (i : slots (word n)) : Option (Fields h r) := + if hit : ∃ j, placeBits hn j = i then some hit.choose else none + +open Classical in +theorem take_place (j : Fields h r) : takeBit hn (placeBits hn j) = some j := by + have h : ∃ i, placeBits hn i = placeBits hn j := ⟨j, rfl⟩ + rw [takeBit, dite_eq_left h, (placeBits hn).injective h.choose_spec] + +open Classical in +/-- The value specified by `(takeBit hn j).elim false (Sum.elim x y)`. -/ +def write (x : Long h → Bool) (y : slots (word r) → Bool) (j : slots (word n)) := + (takeBit hn j).elim false (Sum.elim x y) + +open Classical in +/-- Embeds `(B h × B h × B r)` into `Val (word n) where toFun x`. -/ +def code : (B h × B h × B r) ↪ Val (word n) where + toFun x := (bits (word n)).symm (write hn (long (x.1, x.2.1)) ((Format.addr r).code x.2.2)) + inj' := by + rintro ⟨i, j, k⟩ ⟨i', j', k'⟩ eq + have he := (bits (word n)).symm.injective eq + have hx : (i, j) = (i', j') := by + apply (Format.pair (.addr h) (.addr h)).code.injective + funext t + simpa only [write, take_place, Option.elim_some, Sum.elim_inl, long] using + congrFun he (placeBits hn (.inl t)) + have hy : k = k' := by + apply (Format.addr r).code.injective + funext t + simpa only [write, take_place, Option.elim_some, Sum.elim_inr] using + congrFun he (placeBits hn (.inr t)) + obtain ⟨rfl, rfl⟩ := Prod.mk.inj hx + rw [hy] + +open Classical in +/-- The merge of type `Short n → Bool` for the given inputs. -/ +def merge (x : Long h → Bool) (y : Short r → Bool) : Short n → Bool := + if y (.inl ()) then Sum.elim (fun _ => true) + (Sum.elim (fun _ => y (.inr (.inl ()))) (write hn x (fun i => y (.inr (.inr i))))) + else bits (word (n + 2)) (false, false, Lookup.zero n) + +open Classical in +theorem merge_none (x : Long h → Bool) : + merge hn x (short none) = bits (word (n + 2)) (false, false, Lookup.zero n) := rfl + +open Classical in +theorem merge_eq (x : B h × B h) (y : Option (Bool × B r)) : + merge hn (long x) (short y) = bits (word (n + 2)) (fill (code hn) x y) := by + cases y with + | none => rfl + | some s => + obtain ⟨b, k⟩ := s + funext t + rcases t with _|_|i + · rfl + · rfl + · exact congrFun ((bits (word n)).apply_symm_apply (write hn (long x) ((Format.addr r).code + k))).symm i + +open Classical in +private theorem merge_bit (i : Short n) : + ∃ j : Long h ⊕ Short r, ∀ a b c d, b (.inl ()) = d (.inl ()) → + Sum.elim a b j = Sum.elim c d j → merge hn a b i = merge hn c d i := by + rcases i with _ | _ | k + · refine ⟨.inr (.inl ()), fun a b c d he _ => ?_⟩ + simp only [merge, he, ite_apply, Sum.elim_inl] + · refine ⟨.inr (.inr (.inl ())), fun a b c d he hf => ?_⟩ + change b _ = d _ at hf + simp only [merge, he, ite_apply, Sum.elim_inr, Sum.elim_inl, hf] + · cases hk : takeBit hn k with + | none => + refine ⟨.inr (.inl ()), fun a b c d he _ => ?_⟩ + simp only [merge, he, ite_apply, Sum.elim_inr, write, hk, Option.elim_none] + | some j => + refine ⟨Sum.map id (fun v => .inr (.inr v)) j, fun a b c d he hf => ?_⟩ + simp only [merge, he, ite_apply, Sum.elim_inr, write, hk, Option.elim_some] + cases j <;> simp_all + +variable {F I X : Type} [Field F] [Fintype I] [Fintype X] + (lg : I → Long h → X ⊕ Bool) (sm : I → Short r → X ⊕ Bool) (out : I → Short n → X ⊕ Bool) + +open Classical in +/-- The condition `∀ i, Sum.elim x id ∘ out i = merge hn (Sum.elim x id ∘ lg i) (Sum.elim x id ∘ +sm i)` on the specified data. -/ +def written (x : X → Bool) : Prop := + ∀ i, Sum.elim x id ∘ out i = merge hn (Sum.elim x id ∘ lg i) (Sum.elim x id ∘ sm i) + +open Classical in +theorem merge_net : Weight F (fun x => if written hn lg sm out x then 1 else 0) + (Fintype.card X + 136 * (Fintype.card I * (n + 2)) + 17) := by + let bad (x : X → Bool) (p : I × Short n) := + decide (Sum.elim x id (out p.1 p.2) ≠ merge hn (Sum.elim x id ∘ lg p.1) (Sum.elim x id ∘ sm + p.1) p.2) + have hb : Depends bad 3 := by + rintro ⟨i, j⟩ + obtain ⟨k, hk⟩ := merge_bit hn j + obtain ⟨A, ha, h₁⟩ := tap_depends (sm i) (.inl ()) + obtain ⟨B, hb, h₂⟩ := tap_depends (Sum.elim (lg i) (sm i)) k + obtain ⟨D, hd, h₃⟩ := tap_depends (out i) j + refine ⟨(A ∪ B) ∪ D, ?_, fun x y he => ?_⟩ + · have := Finset.card_union_le A B + have := Finset.card_union_le (A ∪ B) D + omega + have h₁ := h₁ x y (fun _ h => he _ (Finset.mem_union_left _ (Finset.mem_union_left _ h))) + have h₂ := h₂ x y (fun _ h => he _ (Finset.mem_union_left _ (Finset.mem_union_right _ h))) + have h₃ := h₃ x y (fun _ h => he _ (Finset.mem_union_right _ h)) + have eq : merge hn (Sum.elim x id ∘ lg i) (Sum.elim x id ∘ sm i) j = + merge hn (Sum.elim y id ∘ lg i) (Sum.elim y id ∘ sm i) j := + hk _ _ _ _ h₁ (by cases k <;> exact h₂) + simp only [Function.comp_apply] at h₃ + simp only [bad, eq, h₃] + have net := ((hb.bnet F).comp (BNet.any F (I × Short n))).weight + (Weight.dense F Unit (fun x => if x () then 0 else 1)) + convert net using 1 + · funext x + have eq : (∃ i, bad x i = true) ↔ ¬written hn lg sm out x := by + simp only [bad, written, Prod.exists, funext_iff, decide_eq_true_eq, not_forall, + Function.comp_apply] + simp only [Function.comp_apply, decide_eq_true_eq, eq, ite_not] + · simp only [localCost, Fintype.card_prod, Fintype.card_unit, Short] + rw [card_slots (word (n + 2)), wd_word] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows.Channels +end + +/- # Routing and checking normalized internal headers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +open Transcript Coloring + +variable {X Y D L T P : Type} {h r K d u j w m n cap : ℕ} + +open Classical in +/-- Maps the coordinate `c i` to `if he : ∃ j, c (i, j) = true then some he.choose else none`. -/ +def readIndex (r : ℕ) : RelayRead (Fin (2 * 2 ^ r) × Fin (2 * 2 ^ r)) r := + fun c i => if he : ∃ j, c (i, j) = true then some he.choose else none + +open Classical in +theorem readIndex_eq {c : Fin (2 * 2 ^ r) × Fin (2 * 2 ^ r) → Bool} {i j : Fin (2 * 2 ^ r)} + (hc : ∀ k, c (i, k) = true ↔ k = j) : readIndex r c i = some j := by + have he : ∃ k, c (i, k) = true := ⟨j, (hc j).mpr rfl⟩ + rw [readIndex, dite_eq_left he, (hc _).mp he.choose_spec] + +open Classical in +theorem delivered_at {Z : Type} (e : B h × Fin d ↪ Address (2 ^ r) K) + (srcLong : B h × Fin d → Z → X ⊕ Bool) (read : RelayRead L r) (ctrl : Fin K → L → X ⊕ Bool) + (x : X → Bool) (v : Address (2 ^ r) K) (i : B h × Fin d) + (hb : v.1 = (e i).1) (hr : read (Sum.elim x id ∘ ctrl v.1) v.2 = some (e i).2) : + delivered e srcLong read ctrl x v = Sum.elim x id ∘ srcLong i := by + funext t + rw [delivered, hr, Option.elim_some, hb, Prod.mk.eta, e.injective.extend_apply] + rfl + +open Classical in +private theorem delivered_lift {Z : Type} (e : B h × Fin d ↪ Address (2 ^ r) K) + (srcLong : B h × Fin d → Z → X ⊕ Bool) (read : RelayRead L r) (ctrl : Fin K → L → X ⊕ Bool) + (x : X → Bool) (y : Y → Bool) (v : Address (2 ^ r) K) : + delivered e (fun i => liftTap ∘ srcLong i) read (fun i => liftTap ∘ ctrl i) (Sum.elim x y) v = + delivered e srcLong read ctrl x v := by + funext k + simp only [delivered, read_lift_fun, Function.comp_apply, read_lift] + +namespace Channels + +open Classical in +private theorem cost {X Y T N w : ℕ} (hp : 0 < N) (hy : Y ≤ N * (4 * w)) (ht : T ≤ N * (4 * w)) : + 8 * (X + Y) + 9 * (10 ^ 12 * (X + Y + N * (1 + w)) + 4 * (X + Y + 136 * T + 17)) ≤ 10 ^ 15 * (X + + N * (1 + w)) := by + ring_nf at * + omega + +open Classical in +theorem header_net (F : Type) [Field F] [Fintype X] [Fintype D] [Fintype L] [Fintype T] [Fintype P] + (len : (D → Bool) → ℕ) (src : B h → D → X ⊕ Bool) (srcLong : B h × Fin d → Long h → X ⊕ Bool) + (read : RelayRead L r) (ctrl : Fin K → L → X ⊕ Bool) + (sm : Address (2 ^ r) K → Short r → X ⊕ Bool) (out : Address (2 ^ r) K → Short n → X ⊕ Bool) + (hcode : 2 * h + r ≤ n) (hout : n + 2 ≤ 4 * w) (layout : Long h ↪ T × P) + (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (hc : 3 ≤ cap) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ cap) + (hd : Fintype.card D + (r + 1) < j) (hL : j + 2 * h + 2 ≤ 4 * w) + (hsize : 2 ^ h * d + K * (2 * 2 ^ r) ≤ 2 ^ j) (hdpos : 0 < d) + (hz : Fintype.card L + 2 * ((2 * 2 ^ r) * Fintype.card P) < j) (ht : K * Fintype.card T + ≤ 2 ^ j) : + ∃ f : (X → Bool) → F, WideWeight F cap (SortTables F w) f (10 ^ 15 * (Fintype.card X + + 2 ^ j * (1 + w))) ∧ + ∀ (x : X → Bool) (l : Inventory (2 ^ h) m d) (hs : ∀ i, size (l i) u ≤ 2 ^ r) + (hk : bins l u (2 ^ r) ≤ K), + (∀ i, len (Sum.elim x id ∘ src i) = counts l u i) → + f x = if ∀ v, Sum.elim x id ∘ out v = + merge hcode (delivered (portAnchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk) srcLong read + ctrl x v) + (Sum.elim x id ∘ sm v) then 1 else 0 := by + let A := Address (2 ^ r) K + let Y := A × Long h + let get (a : A) (k : Long h) : (X ⊕ Y) ⊕ Bool := .inl (.inr (a, k)) + have hw : Fintype.card (Long h) = 2 * h := by simp [Long, two_mul] + obtain ⟨t, ht₁, ht₂⟩ := port_relay (m := m) (u := u) F len (fun i => liftTap ∘ src i) + (fun i => liftTap ∘ srcLong i) read (fun i => liftTap ∘ ctrl i) get layout hj hj' hc ha hd + (by rwa [hw]) hsize hdpos hz ht + have hnet := merge_net (F := F) hcode get (fun i => liftTap ∘ sm i) (fun i => liftTap ∘ out i) + obtain ⟨f, hf, he⟩ := hide_unique hc ht₁ (of_weight hc hnet) + refine ⟨f, ?_, fun x l hs hk hl => ?_⟩ + · intro a i + obtain ⟨v, hv, net⟩ := hf a i + refine ⟨v, hv.trans ?_, net⟩ + have hi : Fintype.card A ≤ 2 ^ j := by + simp only [A, Address, Fintype.card_prod, Fintype.card_fin] + omega + have hh : Fintype.card Y ≤ 2 ^ j * (4 * w) := by + rw [show Fintype.card Y = Fintype.card A * Fintype.card (Long h) from Fintype.card_prod .., + hw] + exact Nat.mul_le_mul hi (by omega) + rw [Fintype.card_sum] + exact cost (Nat.two_pow_pos j) hh (Nat.mul_le_mul hi hout) + let e := portAnchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk + let values : Y → Bool := Function.uncurry (delivered e srcLong read ctrl x) + have unique (y : Y → Bool) : t (Sum.elim x y) = if values = y then 1 else 0 := by + rw [ht₂ _ l hs hk (by simpa only [read_lift_fun] using hl)] + simp only [delivered_lift] + congr 1 + exact propext ⟨fun h => funext fun ⟨i, j⟩ => (congrFun (h i) j).symm, by rintro rfl i; rfl⟩ + rw [he x values unique] + simp only [written, read_lift_fun] + rfl + +end Channels +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- # Coordinates of a terminal row layout -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Packing PackRows Coloring Assembly + +/-- The data for the dimensions construction, including `h`, `b`, `q`, `u`, `r`. -/ +structure Dimensions where + /-- Logarithm of the original number of stacks. -/ + h : ℕ + /-- Number of finest bundles per stack. -/ + b : ℕ + /-- Number of stacks per row. -/ + q : ℕ + /-- Half the row capacity in finest bundles. -/ + u : ℕ + /-- Logarithm of the half-bin capacity in rows. -/ + r : ℕ + /-- Bits per slice of a finest bundle. -/ + p : ℕ + /-- Bin count. -/ + K : ℕ + /-- Number of exterior channels per host. -/ + d : ℕ + /-- Rows reserved per original exterior name. -/ + n : ℕ + /-- Bit lengths of a paired internal identifier and an exterior name. -/ + a : ℕ + /-- The `Dimensions` field of type `ℕ`. -/ + e : ℕ + width : q * b = 2 * u + cover : n * q = 2 * 2 ^ h + bpos : 0 < b + qpos : 0 < q + ppos : 0 < p + +namespace Dimensions +variable (D : Dimensions) {F : Type} (S : Scheme F) + +/-- The quantity computed by `2 ^ D.r`. -/ +abbrev v := 2 ^ D.r +/-- Computes the z by the application `bundleSize D.v D.p`. -/ +abbrev z := bundleSize D.v D.p +/-- Computes the addr by the application `PackRows.Address D.v D.K`. -/ +abbrev Addr := PackRows.Address D.v D.K +/-- The quantity computed by `2 * 2 ^ S.d + D.d`. -/ +abbrev PortCount := 2 * 2 ^ S.d + D.d + +/-- Indexes the stack bits by the coordinates of `Fin D.b × Fin D.z`. -/ +abbrev StackBits := Fin D.b × Fin D.z +/-- Indexes the label by the coordinates of `Fin D.d × Cell D.h × Fin D.b`. -/ +abbrev Label := Fin D.d × Cell D.h × Fin D.b +/-- The indexing data represented by `Fin D.u → Option D.Label`. -/ +abbrev Source := Fin D.u → Option D.Label + +/-- Indexes the exterior bits by the coordinates of `Unit ⊕ (Fin D.q × Option (Fin D.h))`. -/ +abbrev ExteriorBits := Unit ⊕ (Fin D.q × Option (Fin D.h)) +/-- Indexes the user by the coordinates of `Channels.Short D.r ⊕ D.ExteriorBits`. -/ +abbrev User := Channels.Short D.r ⊕ D.ExteriorBits +/-- Computes the names by the application `Fin D.e`. -/ +abbrev Names := Fin D.e +/-- The quantity computed by `BinOut D.v D.u (2 ^ S.h) S.ℓ D.User`. -/ +abbrev BinOutput := BinOut D.v D.u (2 ^ S.h) S.ℓ D.User +/-- Indexes the decisions by the coordinates of `(Fin D.K × D.BinOutput S) ⊕ (D.Addr × +(Channels.Short D.a ⊕ D.Names))`. -/ +abbrev Decisions := (Fin D.K × D.BinOutput S) ⊕ (D.Addr × (Channels.Short D.a ⊕ D.Names)) +/-- Indexes the originals by the coordinates of `(Stack.Outer x y × Cell D.h) × D.StackBits`. -/ +abbrev Originals (x y : Wire) := (Stack.Outer x y × Cell D.h) × D.StackBits + +theorem upos : 0 < D.u := by + have h := D.width + have := Nat.mul_pos D.qpos D.bpos + omega + +theorem zpos : 0 < D.z := Nat.mul_pos (by positivity) D.ppos + +/-- Embeds `Cell D.h` into `(Fin D.h → Bool)`. -/ +def cellCode : Cell D.h ↪ (Fin D.h → Bool) := + (Fintype.equivOfCardEq (by simp [Cell])).toEmbedding + +end Dimensions +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# The assignment of endpoint bundles at the terminal stage + +Each original stack carries a fixed number of consecutive finest +bundles. Only the local channel and stack key are needed on the +short record. Long exterior names are shared by a host's blocks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Assembly Coloring PackRows + +variable {F : Type} [Field F] {x y : Wire} + +open Classical in +/-- The quantity computed by `2 ^ D.h * (D.b * D.z)`. -/ +abbrev Dimensions.copies (D : Dimensions) := 2 ^ D.h * (D.b * D.z) + +open Classical in +/-- The data for the assignment construction, including `depth`, `state`, `rows`, `post`, +`capacity`. -/ +structure Assignment (D : Dimensions) (S : Scheme F) (G : Diagram F x y) where + /-- The depth of each indexed node carried by `Assignment`, with type `ℕ`. -/ + depth : ℕ + /-- The `Assignment` component of type `Packing.HostNet F (Stack.fringe (copies x D.copies) + (copies y D.copies)) depth D.z`. -/ + state : Packing.HostNet F (Stack.fringe (copies x D.copies) (copies y D.copies)) depth D.z + /-- The indexed rows of type `S.format.obj`. -/ + rows : S.format.obj + /-- The `Assignment` component of type `S.Posting rows state`. -/ + post : S.Posting rows state + /-- The maximum capacity carried by `Assignment`, with type `ℕ`. -/ + capacity : ℕ + /-- The `Assignment` component of type `Stack.Holders G state capacity`. -/ + holders : Stack.Holders G state capacity + /-- The `Assignment` component of type `B S.m → Stack.Outer x y → Fin D.d`. -/ + lane : B S.m → Stack.Outer x y → Fin D.d + separate : ∀ i j a b, holders.core i a = holders.core j b → + lane (post.host (holders.core i a)) i = lane (post.host (holders.core j b)) j → i = j + reach : ∀ i, (Finset.univ.image (holders.core i)).card * D.q ≤ 2 ^ D.h + strips : Strips (Exterior.ports post) + +namespace Assignment +variable {D : Dimensions} {S : Scheme F} {G : Diagram F x y} (t : Assignment D S G) + +open Classical in +/-- Computes the inner by the application `t.post.channels D.zpos`. -/ +abbrev inner := t.post.channels D.zpos +open Classical in +/-- Uses `t.holders.loc t.post.host t.post.block` as the representation. -/ +abbrev loc := t.holders.loc t.post.host t.post.block +open Classical in +/-- Computes the outer count by the application `Exterior.lengths t.loc t.lane D.b`. -/ +abbrev outerCount := Exterior.lengths t.loc t.lane D.b +open Classical in +/-- Computes the inventory by the application `append t.inner.inventory t.outerCount`. -/ +abbrev inventory := append t.inner.inventory t.outerCount + +open Classical in +theorem inject_names (i j a b) (h : (t.loc i a).1 = (t.loc j b).1) + (e : t.lane (t.loc i a).1 i = t.lane (t.loc j b).1 j) : i = j := + t.separate _ _ _ _ (t.post.host.injective h) e + +open Classical in +theorem cap (i : Stack.Outer x y) : + (Finset.univ.image fun s => (t.loc i s).1).card * D.q ≤ Fintype.card (Packing.Cell D.h) := by + change (Finset.univ.image (t.post.host ∘ t.holders.core i)).card * D.q ≤ _ + rw [← Finset.image_image, Packing.card_cell] + exact (Nat.mul_le_mul_right _ Finset.card_image_le).trans (t.reach i) + +open Classical in +/-- The value specified by `(Exterior.addresses t.post t.holders t.lane D.zpos +t.strips).choose`. -/ +def external := (Exterior.addresses t.post t.holders t.lane D.zpos t.strips).choose + +open Classical in +theorem ext_location (j : outer S t.rows D.z) : + (t.external j).1 = j.val.1 ∧ (t.external j).2.1 = j.val.2.1 := + (Exterior.addresses t.post t.holders t.lane D.zpos t.strips).choose_spec.1 j + +open Classical in +/-- The value specified by `t.post.pieces D.zpos (t.strips.uniform D.zpos) t.external +t.ext_location`. -/ +def pieces : Pieces S t.rows t.inventory D.v D.p := + t.post.pieces D.zpos (t.strips.uniform D.zpos) t.external t.ext_location + +open Classical in +/-- The data for the fits construction, including `room`, `position`, `reserve`. -/ +structure Fits : Prop where + room : Pieces.Room (l := t.inventory) (u := D.u) + position : ∀ i, size (t.inventory i) D.u ≤ D.v + reserve : bins t.inventory D.u D.v ≤ D.K + +variable (hw : t.Fits) + +open Classical in +/-- Computes the layout by the application `make t.inventory D.u D.v D.K D.upos (by positivity) +hw.room hw.position hw.reserve`. -/ +abbrev layout := make t.inventory D.u D.v D.K D.upos (by positivity) hw.room hw.position hw.reserve +open Classical in +/-- Uses `t.pieces.index hw.room` as the representation. -/ +abbrev index := t.pieces.index hw.room + +open Classical in +/-- The value specified by `extendR _ _ (Exterior.point t.loc t.lane D.b ((i, s), k))`. -/ +def endpoint (i : Stack.Outer x y) (s : Packing.Cell D.h) (k : Fin D.b) : Endpoints t.inventory := + extendR _ _ (Exterior.point t.loc t.lane D.b ((i, s), k)) + +open Classical in +/-- Computes the coordinate by the application `t.index hw q.1 q.2.1 q.2.2`. -/ +def coordinate (q : Endpoints t.inventory) : Fin D.u := + t.index hw q.1 q.2.1 q.2.2 + +open Classical in +/-- The defining condition `∀ i j k c s b, rows i j k = some (c, s, b) ↔ ∃ a : Stack.Outer x y, +t.loc a s = (i, j) ∧ t.lane i a = c ∧ t.coordinate hw (t.endpoint a s b) = k`. -/ +def Registered (rows : B S.m → B S.h → D.Source) : Prop := + ∀ i j k c s b, rows i j k = some (c, s, b) ↔ + ∃ a : Stack.Outer x y, t.loc a s = (i, j) ∧ t.lane i a = c ∧ t.coordinate hw (t.endpoint a s b) + = k + +open Classical in +theorem end_bit (i : Stack.Outer x y) (s : Packing.Cell D.h) (k : Fin D.b) (j : Fin D.z) : + t.pieces.slots (Exterior.ports t.post (((i, s), k), j)).val = + (t.endpoint i s k, finProdFinEquiv.symm j) := by + have e := (Exterior.addresses t.post t.holders t.lane D.zpos t.strips).choose_spec.2 ((i, s), k) j + let u := t.external.symm (Exterior.point t.loc t.lane D.b ((i, s), k)) + change Exterior.ports t.post (((i, s), k), j) = toOuter t.pieces.uniform u j at e + rw [e] + unfold toOuter Pieces.slots + simp only [Equiv.trans_apply, Equiv.symm_apply_apply, Equiv.prodCongr_apply, Prod.map] + unfold pieces + rw [t.post.pieces_outer _ _ _ _ u] + simp only [u, Equiv.apply_symm_apply, endpoint] + +end Assignment +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Canonical row decisions + +Short descriptors stay within their bins. Host names and exterior +names follow the selected port anchors. The three parts of the tape +are functional, including every unused bit. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +open PackRows Coloring Assembly + +variable {F Z X : Type} (D : Dimensions) (S : Scheme F) + +open Classical in +/-- The quantity computed by `(Z → Bool) → Descriptor (2 ^ S.h) (D.PortCount S) S.ℓ`. -/ +abbrev Description (Z : Type) := (Z → Bool) → Descriptor (2 ^ S.h) (D.PortCount S) S.ℓ +open Classical in +/-- The indexing data represented by `(Z → Bool) → Fin D.d → Fin D.v → D.ExteriorBits → Bool`. -/ +abbrev Extras (Z : Type) := (Z → Bool) → Fin D.d → Fin D.v → D.ExteriorBits → Bool +open Classical in +/-- Indexes the group by the coordinates of `B S.m × Fin (D.PortCount S)`. -/ +abbrev Group := B S.m × Fin (D.PortCount S) +open Classical in +/-- The quantity computed by `Inventory (2 ^ S.m) (2 ^ S.h) (D.PortCount S)`. -/ +abbrev Counts := Inventory (2 ^ S.m) (2 ^ S.h) (D.PortCount S) +open Classical in +/-- The quantity computed by `2 * S.m + D.r ≤ D.a`. -/ +abbrev CodeFits := 2 * S.m + D.r ≤ D.a + +open Classical in +/-- The data for the fits controls construction, including `lower`, `upper`, `gates`, `large`, +`desc`. -/ +structure FitsControls (Z : Type) [Fintype Z] (w j cap t p : ℕ) : Prop where + lower : w ≤ j + upper : j + 1 ≤ 2 * w + gates : 3 ≤ cap + large : 2 * 2 ^ (2 * w) * (4 * w) ≤ cap + desc : Fintype.card Z + (D.r + 1) < j + short : Fintype.card (BinKey D.v Z) + Fintype.card (D.BinOutput S) < j + hosts : j + 2 * S.m + 2 ≤ 4 * w + names : j + D.e + 2 ≤ 4 * w + slots : 2 ^ S.m * (D.PortCount S) + D.K * (2 * D.v) ≤ 2 ^ j + code : D.CodeFits S + head : D.a + 2 ≤ 4 * w + hosts_fit : 2 * S.m ≤ t * p + names_fit : D.e ≤ t * p + slice : (2 * D.v) ^ 2 + 2 * (2 * D.v * p) < j + slices : D.K * t ≤ 2 ^ j + +open Classical in +/-- Selects the appropriate branch of `if h : j.val < 2 * 2 ^ S.d then none else some ⟨j.val - 2 +* 2 ^ S.d, by have := j.isLt; unfold PortCount at this; omega⟩`. -/ +def exteriorLane (j : Fin (D.PortCount S)) : Option (Fin D.d) := + if h : j.val < 2 * 2 ^ S.d then none else + some ⟨j.val - 2 * 2 ^ S.d, by have := j.isLt; unfold PortCount at this; omega⟩ + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def flags (code : D.Description S Z) (user : D.Extras Z) + (x : Z → Bool) (j : Fin (D.PortCount S)) (k : Fin D.v) : D.User → Bool := + Sum.elim (Channels.short (Channels.source (2 ^ S.d) D.d D.u D.v (code x).len j k.val)) + (fun z => (D.exteriorLane S j).elim false (fun p => user x p k z)) + +open Classical in +/-- The indexed operation `Channels.long (Channels.names (fun i => (s i).1) p.1 p.2)`. -/ +def longNames (s : S.format.obj) (p : D.Group S) : Channels.Long S.m → Bool := + Channels.long (Channels.names (fun i => (s i).1) p.1 p.2) + +open Classical in +/-- Evaluates `(D.exteriorLane S p.2).elim false (fun k => names p.1 k j)` at the input `j`. -/ +def extNames (names : B S.m → Fin D.d → D.Names → Bool) (p : D.Group S) : D.Names → Bool := + fun j => (D.exteriorLane S p.2).elim false (fun k => names p.1 k j) + +open Classical in +/-- The value specified by `f i (.inr (p.1, .inr (.inl p.2)))`. -/ +def chooseBits {Y : Type} (f : Fin D.K → D.BinOutput S → Y) (i : Fin D.K) + (p : Fin (2 * D.v) × Fin (2 * D.v)) : Y := f i (.inr (p.1, .inr (.inl p.2))) + +open Classical in +/-- The value specified by `f r.1 (.inr (r.2, .inr (.inr (.inl j))))`. -/ +def shortBits {Y : Type} (f : Fin D.K → D.BinOutput S → Y) (r : D.Addr) + (j : Channels.Short D.r) : Y := f r.1 (.inr (r.2, .inr (.inr (.inl j)))) + +open Classical in +/-- The indexed operation `(readIndex D.r (D.chooseBits S b i.1) i.2).elim false fun j => +Function.extend anc (fun a => labels a k) (fun _ => false) (i.1, j)`. -/ +def fetch {Y : Type} (anc : D.Group S ↪ D.Addr) (b : Fin D.K → D.BinOutput S → Bool) + (labels : D.Group S → Y → Bool) (i : D.Addr) (k : Y) : Bool := + (readIndex D.r (D.chooseBits S b i.1) i.2).elim false fun j => + Function.extend anc (fun a => labels a k) (fun _ => false) (i.1, j) + +open Classical in +/-- The decide rows of type `D.Decisions S → Bool`, constructed using `anchor l D.u D.v D.K +(Nat.two_pow_pos _) hs hk`. -/ +def decideRows (hn : D.CodeFits S) (code : D.Description S Z) (user : D.Extras Z) + (sd : B S.m → Z → Bool) (r : S.format.obj) (ext : B S.m → Fin D.d → D.Names → Bool) + (l : D.Counts S) (hs : ∀ i, size (l i) D.u ≤ D.v) (hk : bins l D.u D.v ≤ D.K) : + D.Decisions S → Bool := + let a := anchor l D.u D.v D.K (Nat.two_pow_pos _) hs hk + let b g := binFunction D.u code (D.flags S code user) (anchored a sd g) + let e := portAnchor l D.u D.v D.K (Nat.two_pow_pos _) hs hk + Sum.elim (Function.uncurry b) fun i => + Sum.elim (Channels.merge hn (D.fetch S e b (D.longNames S r) i.1) (D.shortBits S b i.1)) + (D.fetch S e b (D.extNames S ext) i.1) i.2 + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +end + +/- # Checking the terminal decisions from short and long descriptors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +open PackRows Coloring Assembly Transcript + +variable {F Z X : Type} (D : Dimensions) (S : Scheme F) + +open Classical in +private def hostTap (ts : S.format.pins → X ⊕ Bool) (a : D.Group S) : Channels.Long S.m → X ⊕ Bool + := + let own := Sum.inr ∘ (Format.addr S.m).code a.1 + if h : a.2.val < 2 * 2 ^ S.d then + let k := Channels.decodeLane ⟨a.2.val, h⟩ + let other j := ts (a.1, .inl (k.2, j)) + if k.1 then Sum.elim other own else Sum.elim own other + else Sum.elim own own + +open Classical in +private theorem hostTap_eq (ts : S.format.pins → X ⊕ Bool) (x : X → Bool) : + (fun a => Sum.elim x id ∘ D.hostTap S ts a) = + D.longNames S (S.format.code.symm (Sum.elim x id ∘ ts)) := by + let r := S.format.code.symm (Sum.elim x id ∘ ts) + have he (i : B S.m) (j : B S.d) (t : slots (word S.m)) : + Sum.elim x id (ts (i, .inl (j, t))) = (Format.addr S.m).code ((r i).1 j) t := + (congrFun (S.format.code.apply_symm_apply (Sum.elim x id ∘ ts)) (i, .inl (j, t))).symm + funext a t + unfold hostTap longNames Channels.names + by_cases h : a.2.val < 2 * 2 ^ S.d + · simp only [dite_eq_left h] + cases (Channels.decodeLane ⟨a.2.val, h⟩).1 <;> cases t <;> first | rfl | exact he _ _ _ + · simp only [dite_eq_right h] + cases t <;> rfl + +open Classical in +private def extTap (ext : B S.m → Fin D.d → D.Names → X ⊕ Bool) (p : D.Group S) + (j : D.Names) : X ⊕ Bool := + (D.exteriorLane S p.2).elim (.inr false) (fun k => ext p.1 k j) + +open Classical in +private theorem extTap_eq (ext : B S.m → Fin D.d → D.Names → X ⊕ Bool) (x : X → Bool) : + (fun p => Sum.elim x id ∘ D.extTap S ext p) = D.extNames S (fun i j => Sum.elim x id ∘ ext i j) + := by + funext p k + unfold extTap extNames + simp only [Function.comp_apply] + cases D.exteriorLane S p.2 <;> rfl + +open Classical in +private theorem fetch_eq {Y : Type} (e : D.Group S ↪ D.Addr) + (b : Fin D.K → D.BinOutput S → X ⊕ Bool) (src : D.Group S → Y → X ⊕ Bool) (x : X → Bool) : + delivered e src (readIndex D.r) (D.chooseBits S b) x = + D.fetch S e (fun i => Sum.elim x id ∘ b i) (fun p => Sum.elim x id ∘ src p) := rfl + +open Classical in +private theorem tape_ok {A B C Y Z : Type} (b : A → B → Bool) + (l : (A → B → Bool) → C → Y → Bool) (r : (A → B → Bool) → C → Z → Bool) + (x : (A × B) ⊕ (C × (Y ⊕ Z)) → Bool) : + let p i j := x (.inl (i, j)) + (∀ i, p i = b i) ∧ (∀ i, (fun j => x (.inr (i, .inl j))) = l p i) ∧ + (∀ i, (fun j => x (.inr (i, .inr j))) = r p i) ↔ + x = Sum.elim (Function.uncurry b) (fun i => Sum.elim (l b i.1) (r b i.1) i.2) := by + intro p + constructor + · rintro ⟨a, h, k⟩ + rw [funext a] at h k + funext i + rcases i with ⟨i, j⟩ | ⟨i, j|j⟩ + · exact congrFun (a i) j + · exact congrFun (h i) j + · exact congrFun (k i) j + · rintro rfl + exact ⟨fun _ => rfl, fun _ => rfl, fun _ => rfl⟩ + +variable [Field F] [Fintype X] [Fintype Z] {w j cap t p : ℕ} (h : D.FitsControls S Z w j cap t p) + (ts : S.format.pins → X ⊕ Bool) (ext : B S.m → Fin D.d → D.Names → X ⊕ Bool) + (sd : B S.m → Z → X ⊕ Bool) (dst : D.Decisions S → X ⊕ Bool) + (code : D.Description S Z) (user : D.Extras Z) + +open Classical in +theorem controls_net : + ∃ f : (X → Bool) → F, WideWeight F cap (SortTables F w) f (10 ^ 16 * (Fintype.card X + + 2 ^ j * (1 + w))) ∧ + ∀ (x : X → Bool) (l : D.Counts S) (hs : ∀ i, size (l i) D.u ≤ D.v) (hk : bins l D.u D.v + ≤ D.K), + (∀ i, (code (Sum.elim x id ∘ sd i)).len = l i) → + f x = if Sum.elim x id ∘ dst = D.decideRows S h.code code user (fun i + => Sum.elim x id ∘ sd i) + (S.format.code.symm (Sum.elim x id ∘ ts)) (fun i j => Sum.elim x id ∘ ext i j) l hs hk + then 1 else 0 := by + let len x := size (code x).len D.u + let b i j := dst (.inl (i, j)) + let head i j := dst (.inr (i, .inl j)) + let name i j := dst (.inr (i, .inr j)) + let read := readIndex D.r + let ctrl := D.chooseBits S b + have hp : 0 < D.PortCount S := by unfold PortCount; positivity + have hsize : 2 ^ S.m + D.K * D.v ≤ 2 ^ j := + (Nat.add_le_add (Nat.le_mul_of_pos_right _ hp) (Nat.mul_le_mul_left _ (by omega))).trans h.slots + have hsli : Fintype.card (Fin (2 * D.v) × Fin (2 * D.v)) + 2 * ((2 * D.v) * Fintype.card (Fin p)) + < j := by + simpa [pow_two] using h.slice + have ht : D.K * Fintype.card (Fin t) ≤ 2 ^ j := by simpa using h.slices + obtain ⟨a, ha, ea⟩ := bin_service F len code (D.flags S code user) sd b h.lower h.upper h.gates + h.large + h.desc hsize h.short + obtain ⟨e₁⟩ : Nonempty (Channels.Long S.m ↪ Fin t × Fin p) := + Function.Embedding.nonempty_of_card_le (by simpa [Channels.Long, two_mul] using h.hosts_fit) + obtain ⟨g, hg, eg⟩ := Channels.header_net (m := 2 ^ S.h) (u := D.u) F len sd (D.hostTap S ts) + read ctrl (D.shortBits S b) head h.code h.head e₁ h.lower h.upper h.gates h.large + h.desc h.hosts h.slots hp hsli ht + obtain ⟨e₂⟩ : Nonempty (D.Names ↪ Fin t × Fin p) := + Function.Embedding.nonempty_of_card_le (by simpa [Names] using h.names_fit) + obtain ⟨k, hk, ek⟩ := port_relay (m := 2 ^ S.h) (u := D.u) F len sd (D.extTap S ext) + read ctrl name e₂ h.lower h.upper h.gates h.large h.desc (by simpa [Names] using h.names) + h.slots hp hsli ht + have net := wide_mul h.gates ha (wide_mul h.gates hg hk) + refine ⟨fun x => a x * (g x * k x), ?_, fun x l hs hr he => ?_⟩ + · intro a i + obtain ⟨s, hv, hv'⟩ := net a i + exact ⟨s, hv.trans (by omega), hv'⟩ + have hl (i) : len (Sum.elim x id ∘ sd i) = counts l D.u i := by unfold len counts; rw [he] + change a x * (g x * k x) = _ + rw [ea _ l hs hr hl, eg _ l hs hr hl, ek _ l hs hr hl] + simp only [read, ctrl, D.fetch_eq, D.hostTap_eq, D.extTap_eq, ite_mul, one_mul, zero_mul, + ← ite_and] + let e := portAnchor l D.u D.v D.K (Nat.two_pow_pos _) hs hr + let left y i := Channels.merge h.code + (D.fetch S e y (D.longNames S (S.format.code.symm (Sum.elim x id ∘ ts))) i) (D.shortBits S y i) + let right y := D.fetch S e y (D.extNames S (fun i j => Sum.elim x id ∘ ext i j)) + congr 1 + exact propext (tape_ok _ left right (Sum.elim x id ∘ dst)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Dimensions +end + +/- # Reading the controls at an allocated port row -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +variable {Z A : Type} {H u K m d ℓ r : ℕ} {code : (Z → Bool) → Descriptor m d ℓ} + {l : Inventory H m d} {hs : ∀ i, size (l i) u ≤ 2 ^ r} {hk : bins l u (2 ^ r) ≤ K} + {ix : Index l u} {f : Label H m ℓ} {src : Fin H → Z → Bool} + {inp : Fin K → BinKey (2 ^ r) Z → Bool} (b : BinData code l u (2 ^ r) K (Nat.two_pow_pos _) hs + hk ix f src inp) + (flags : (Z → Bool) → Fin d → Fin (2 ^ r) → A → Bool) + (hu : 0 < u) (ha : ∀ i j, arity (l i) j ≤ u) + +local notation "arr" => make l u (2 ^ r) K hu (Nat.two_pow_pos r) ha hs hk +local notation "anc" => portAnchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk + +include b in +theorem BinData.user_at (p : PortRows l u) (a : A) : + let i := (arr).portLoc p + binFunction u code flags (inp i.1) (.inr (i.2, .inr (.inr a))) = + flags (src p.1) p.2.1 (p.2.2.castLE (ports_le hs ..)) a := by + intro i + apply Bool.eq_iff_iff.mpr + rw [b.user flags hu ha] + constructor + · rintro ⟨p', h, k, hk', hw⟩ + have := (arr).portLoc.injective h + subst p' + rw [show k = p.2.2.castLE (ports_le hs ..) from Fin.ext hk'] at hw + exact hw + · exact fun hh => ⟨p, rfl, _, rfl, hh⟩ + +include b in +theorem BinData.user_off (i : Address (2 ^ r) K) (hi : i ∉ Set.range (arr).portLoc) (a : A) : + binFunction u code flags (inp i.1) (.inr (i.2, .inr (.inr a))) = false := by + apply Bool.eq_false_iff.mpr + intro h + obtain ⟨p, hp, _⟩ := (b.user flags hu ha i a).mp h + exact hi ⟨p, hp⟩ + +include b in +theorem BinData.read_port (p : PortRows l u) : + let i := (arr).portLoc p + readIndex r (fun y => binFunction u code flags (inp i.1) (.inr (y.1, .inr (.inl y.2)))) i.2 = + some ((anc) (p.1, p.2.1)).2 := by + intro i + refine readIndex_eq (fun k => ?_) + rw [b.choose flags hu ha] + exact ⟨fun ⟨q, hq, eq⟩ => (arr).portLoc.injective hq ▸ eq, fun h => ⟨p, rfl, h⟩⟩ + +include b in +theorem BinData.read_off (i : Address (2 ^ r) K) (hi : i ∉ Set.range (arr).portLoc) : + readIndex r (fun y => binFunction u code flags (inp i.1) (.inr (y.1, .inr (.inl y.2)))) i.2 + = none := by + apply dite_eq_right + rintro ⟨j, hj⟩ + obtain ⟨p, hp, _⟩ := (b.choose flags hu ha i j).mp hj + exact hi ⟨p, hp⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- # Interpreting the decisions for a registered placement -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly PackRows Coloring + +namespace Dimensions + +variable {F Z Y : Type} {D : Dimensions} {S : Scheme F} + {l : D.Counts S} {hs : ∀ i, size (l i) D.u ≤ D.v} {hk : bins l D.u D.v ≤ D.K} + {code : D.Description S Z} {ix : Index l D.u} {f : PackRows.Label (2 ^ S.m) (2 ^ S.h) S.ℓ} + {sd : B S.m → Z → Bool} {inp : Fin D.K → BinKey D.v Z → Bool} + (data : BinData code l D.u D.v D.K (Nat.two_pow_pos _) hs hk ix f sd inp) + (user : D.Extras Z) (ha : ∀ i j, arity (l i) j ≤ D.u) + +local notation "out" => (fun g => binFunction D.u code (D.flags S code user) (inp g)) +local notation "arr" => make l D.u D.v D.K D.upos (Nat.two_pow_pos _) ha hs hk +local notation "anc" => portAnchor l D.u D.v D.K (Nat.two_pow_pos _) hs hk + +include data in +open Classical in +private theorem fetch_at (y : D.Group S → Y → Bool) (p : PortRows l D.u) : + D.fetch S anc out y ((arr).portLoc p) = y (p.1, p.2.1) := by + let i := (arr).portLoc p + have hb : i.1 = ((anc) (p.1, p.2.1)).1 := rfl + have hr : readIndex D.r (D.chooseBits S out i.1) i.2 = some ((anc) (p.1, p.2.1)).2 := + data.read_port (D.flags S code user) D.upos ha p + funext k + change D.fetch S anc out y i k = _ + rw [fetch, hr, Option.elim_some, hb, Prod.mk.eta, (anc).injective.extend_apply] + +include data in +open Classical in +private theorem fetch_off (y : D.Group S → Y → Bool) (i : D.Addr) (h : i ∉ Set.range (arr).portLoc) + : + D.fetch S anc out y i = fun _ => false := by + have hr : readIndex D.r (D.chooseBits S out i.1) i.2 = none := + data.read_off (D.flags S code user) D.upos ha i h + funext k + rw [fetch, hr, Option.elim_none] + +end Dimensions + +namespace Assignment + +variable {F Z : Type} [Field F] {x y : Wire} {S : Scheme F} {D : Dimensions} {G : Diagram F x y} + (t : Assignment D S G) (hw : t.Fits) (hc : D.CodeFits S) (user : D.Extras Z) (sd : B S.m → Z → + Bool) + (ext : B S.m → Fin D.d → D.Names → Bool) + +open Classical in +/-- The data for the observed construction, including `moves`, `format`, `head`, `flags`, +`name`. -/ +structure Observed (v : D.Decisions S → Bool) : Prop where + moves : ∀ i b, v (.inl (i, .inl b)) = (t.layout hw).moves i b + format : ∀ i b, v (.inl (i.1, .inr (i.2, .inl b))) + = (t.layout hw).format (t.index hw) (labels S t.rows) i b + head : ∀ i b, v (.inr (i, .inl b)) = + MatrixExponent.bits (word (D.a + 2)) (t.inner.header (t.layout hw) hw.position (Channels.code + hc) i) b + flags : ∀ (a : PortRows t.inventory D.u) b, let i := (t.layout hw).portLoc a + v (.inl (i.1, .inr (i.2, .inr (.inr (.inr b))))) = + (D.exteriorLane S a.2.1).elim false + (fun k => user (sd a.1) k (a.2.2.castLE (ports_le hw.position ..)) b) + name : ∀ (a : PortRows t.inventory D.u) b, + v (.inr ((t.layout hw).portLoc a, .inr b)) = D.extNames S ext (a.1, a.2.1) b + flags_off : ∀ i ∉ Set.range (t.layout hw).portLoc, ∀ b, + v (.inl (i.1, .inr (i.2, .inr (.inr (.inr b))))) = false + name_off : ∀ i ∉ Set.range (t.layout hw).portLoc, ∀ b, v (.inr (i, .inr b)) = false + +open Classical in +theorem observed (code : D.Description S Z) + (hlen : ∀ i, (code (sd i)).len = t.inventory i) + (hlabel : ∀ i, (code (sd i)).label = labels S t.rows i) + (hslot : ∀ i j p (k : Fin (t.inventory i j p)), + (code (sd i)).slot j p k.val = (t.index hw i j ⟨p, k⟩).val) : + t.Observed hw hc user sd ext + (D.decideRows S hc code user sd t.rows ext t.inventory hw.position hw.reserve) := by + let flags := D.flags S code user + let a := anchor t.inventory D.u D.v D.K (Nat.two_pow_pos _) hw.position hw.reserve + let e := portAnchor t.inventory D.u D.v D.K (Nat.two_pow_pos _) hw.position hw.reserve + let b (g) := binFunction D.u code flags (anchored a sd g) + let L := t.layout hw + have data := BinData.anchored (Nat.two_pow_pos _) hw.position hw.reserve hlen hlabel hslot + have atPort (p : PortRows t.inventory D.u) (j : D.User) : + b (L.portLoc p).1 (.inr ((L.portLoc p).2, .inr (.inr j))) = + flags (sd p.1) p.2.1 (p.2.2.castLE (ports_le hw.position ..)) j := + data.user_at flags D.upos hw.room p j + have offPort (i : D.Addr) (h : i ∉ Set.range L.portLoc) (j : D.User) : + b i.1 (.inr (i.2, .inr (.inr j))) = false := data.user_off flags D.upos hw.room i h j + refine ⟨data.moves flags D.upos hw.room, data.format flags D.upos hw.room, + ?_, ?_, ?_, ?_, ?_⟩ + · intro i k + change Channels.merge hc (D.fetch S e b (D.longNames S t.rows) i) (D.shortBits S b i) k = + MatrixExponent.bits (word (D.a + 2)) (t.inner.header L hw.position (Channels.code hc) i) k + by_cases hi : i ∈ Set.range L.portLoc + · obtain ⟨p, rfl⟩ := hi + have hlong : D.fetch S e b (D.longNames S t.rows) (L.portLoc p) = + Channels.long (Channels.names (fun i => (t.rows i).1) p.1 p.2.1) := + Dimensions.fetch_at data user hw.room _ p + have hshort : D.shortBits S b (L.portLoc p) = Channels.short + (Channels.source (2 ^ S.d) D.d D.u D.v (t.inventory p.1) p.2.1 p.2.2.val) := by + funext j + have he := atPort p (.inl j) + simpa only [Dimensions.shortBits, flags, Dimensions.flags, Sum.elim_inl, hlen, + Fin.val_castLE] using he + rw [hlong, hshort, Channels.merge_eq] + obtain ⟨i, j, r⟩ := p + rw [t.post.header_eq_fill D.zpos L hw.position (Channels.code hc) D.upos] + · have hshort : D.shortBits S b i = Channels.short none := funext fun j => offPort i hi (.inl j) + rw [hshort, Channels.merge_none, t.inner.header_absent L hw.position (Channels.code hc) i hi] + · exact fun p j => atPort p (.inr j) + · exact fun p j => congrFun (Dimensions.fetch_at data user hw.room (D.extNames S ext) p) j + · exact fun i hi j => offPort i hi (.inr j) + · exact fun i hi j => congrFun (Dimensions.fetch_off data user hw.room (D.extNames S ext) i hi) j + +end Assignment +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Phase/ResetRate.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Phase/ResetRate.lean new file mode 100644 index 0000000000..fb9ad365c2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Phase/ResetRate.lean @@ -0,0 +1,562 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Raw.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Hop +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.One + +/-! +# Quantitative contract for one encoded contraction or reset + +A phase reduces block height by exactly `r`. Its constants are +independent of the number of hosts and blocks. Only the charge on +long addresses can involve a polynomial of the global width `w`. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Packing + +/-- A charge for all hosts and blocks bounds the charge for the occupied hosts. -/ +theorem slack_of_width_count {exponent limit group height hosts count : ℕ} {load budget : ℝ} + (load_nonneg : 0 ≤ load) (group_le : group ≤ height) + (exponent_le : 2 ^ exponent ≤ limit) (count_le : count ≤ 2 ^ hosts) + (slack : (limit : ℝ) * load * (2 ^ (hosts + height) : ℕ) ≤ budget * (2 : ℝ) ^ group) : + (2 : ℝ) ^ exponent * load * (count * 2 ^ (height - group) : ℕ) ≤ budget := by + apply le_of_mul_le_mul_right _ (show (0 : ℝ) < 2 ^ group by positivity) + apply le_trans _ slack + push_cast + rw [mul_assoc, mul_assoc (count : ℝ), ← pow_add, Nat.sub_add_cancel group_le, pow_add] + gcongr + · exact_mod_cast exponent_le + · exact_mod_cast count_le + +/-- The data for the budget construction, including `load`, `tag`, `reach`, `width`, `mass`. -/ +structure Budget where + /-- Stores the load associated with this `Budget`. -/ + load : ℕ + /-- Stores the tag associated with this `Budget`. -/ + tag : ℕ + /-- Stores the reach associated with this `Budget`. -/ + reach : ℕ + /-- The width parameter carried by `Budget`, with type `ℝ`. -/ + width : ℝ + /-- Stores the mass associated with this `Budget`. -/ + mass : ℝ + +variable {F : Type} [Field F] {x y : Wire} {S : Setup F x y} {T : Template F} {u : ℕ} + +/-- Choose an artificially large full degree so noncore marks cannot +propagate. Only the small core graph needs to be stored. -/ +def degreeBound (S : Setup F x y) (T : Template F) (Δ : ℕ) := Δ + 2 ^ S.h + 2 ^ T.scheme.m + +/-- The data for the ready construction, including `live`, `neutral`, `tagged`, `bounded`, +`tracks`. -/ +structure Ready (Δ : ℕ) (P : Budget) (s : Snapshot.Data S T u) : Prop where + live : Nonempty s.G.V + neutral : s.Neutral + tagged : s.Tagged P.tag + bounded : s.G.Bounded Δ (degreeBound S T Δ) (P.load * S.z) + tracks : S.first.Tracks s.G P.reach + width : (s.G.X : ℝ) ≤ P.width + mass : (s.G.mass : ℝ) ≤ P.mass + +/-- The value specified by `Snapshot.restrict (Ready (S := S) (T := T) (u := u) Δ P)`. -/ +abbrev frame (S : Setup F x y) (T : Template F) (u Δ : ℕ) (P : Budget) := + Snapshot.restrict (Ready (S := S) (T := T) (u := u) Δ P) + +namespace Phase + +/-- The quantity computed by `100 + 2 ^ r + S.h + Nat.clog 2 (1 + S.U) + 2 ^ S.discount + P.load ++ S.d`. -/ +def base (S : Setup F x y) (r : ℕ) (P : Budget) := + 100 + 2 ^ r + S.h + Nat.clog 2 (1 + S.U) + 2 ^ S.discount + P.load + S.d + +/-- The quantity computed by `base S r P + 2 ^ T.scheme.e + Nat.clog 2 (1 + T.scheme.ℓ)`. -/ +def rate (S : Setup F x y) (T : Template F) (r : ℕ) (P : Budget) := + base S r P + 2 ^ T.scheme.e + Nat.clog 2 (1 + T.scheme.ℓ) + +/-- The quantity computed by `rate S T r P + T.count + T.scheme.ℓ + P.tag`. -/ +def short (S : Setup F x y) (T : Template F) (r : ℕ) (P : Budget) := + rate S T r P + T.count + T.scheme.ℓ + P.tag + +/-- The value specified by `⟨K * P.load, P.tag + (rate S T r P) ^ K, K * P.reach, ρ * P.width + +C * (S.fringe.Z + σ), P.mass + 2 * P.width⟩`. -/ +def after (S : Setup F x y) (T : Template F) (r : ℕ) (P : Budget) (K : ℕ) (ρ C σ : ℝ) : Budget := + ⟨K * P.load, P.tag + (rate S T r P) ^ K, K * P.reach, + ρ * P.width + C * (S.fringe.Z + σ), P.mass + 2 * P.width⟩ + +/-- Preconditions shared by all encoded inputs at a phase boundary. -/ +structure Input (S : Setup F x y) (T : Template F) (P : Budget) (w r b u v d K : ℕ) + (σ : ℝ) : Prop where + trivalent : S.G.Trivalent + zpos : 0 < S.z + vpos : 0 < v + divides : S.z ∣ v + units : u = b * v + initial : u ∣ S.U + ceiling : u ≤ S.U + load : u ≤ P.load * S.z + group : r ≤ T.scheme.h + height : T.scheme.h ≤ S.h + room : K ≤ 2 ^ r + positive : 0 < K + degree : T.scheme.d ≤ d + core : T.full = false + single : T.scheme.k = 0 + names : S.e ≤ 3 * w + lower : w ≤ T.scheme.m + upper : T.scheme.m + K * (S.h + 1) ≤ 2 * w + small : (short S T r P) ^ K ≤ w / 4 + origins : 3 * (K * P.reach) ≤ S.d + reach : 0 < P.reach + width : 0 ≤ P.width + mass : 0 ≤ P.mass + history : P.mass + 2 * P.width ≤ S.cap + slack : K * (P.load * S.z : ℕ) * (2 ^ (T.scheme.m + T.scheme.h) : ℕ) ≤ σ * (2 : ℝ) ^ r + +/-- The data for the output construction, including `next`, `height`, `lower`, `upper`, +`degree`. -/ +structure Output (S : Setup F x y) (T : Template F) (P : Budget) (w r u v Δ Δ' d' K : ℕ) + (ρ C σ : ℝ) where + /-- The successor of each choice of type `Template F`. -/ + next : Template F + height : next.scheme.h + r = T.scheme.h + lower : T.scheme.m ≤ next.scheme.m + upper : next.scheme.m ≤ T.scheme.m + r + K + degree : next.scheme.d ≤ d' + core : next.full = false + single : next.scheme.k = 0 + spans : 2 ^ next.scheme.e ≤ (base S r P) ^ K + counters : next.count ≤ (base S r P) ^ K + bits : next.scheme.ℓ ≤ (1 + P.tag) * (rate S T r P) ^ K + /-- The label data of type `Finset (Table F)`. -/ + labels : Finset (Table F) + few : labels.card ≤ (short S T r P) ^ K + small : ∀ k ∈ labels, Processor.arity k ≤ (short S T r P) ^ K + /-- Stores the scale associated with this `Output`. -/ + scale : ℕ + /-- The size parameter carried by `Output`, with type `ℕ`. -/ + size : ℕ + cost : size ≤ 2 ^ T.scheme.m * (100 + w + short S T r P) ^ K + + 2 ^ (T.scheme.m + T.scheme.h) * (short S T r P) ^ K + transfer : Transforms F scale (Allowed F w ∪ (labels : Set (Table F))) + (frame S T u Δ P) (frame S next v Δ' (after S T r P K ρ C σ)) size + +end Phase + +/-- The phase of type `Prop` for the given inputs. -/ +def Phase (F : Type) [Field F] (Δ Δ' d d' b K : ℕ) (ρ C : ℝ) : Prop := + ∀ {x y : Wire} (S : Setup F x y) (T : Template F) (P : Budget) + (w r u v : ℕ) (σ : ℝ), Phase.Input S T P w r b u v d K σ → + Nonempty (Phase.Output S T P w r u v Δ Δ' d' K ρ C σ) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # A common domain for bounds uniform in the host and block counts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase +open Assembly Packing + +/-- The data for the case construction, including `x`, `y`, `S`, `T`, `R`. -/ +structure Case (F : Type) [Field F] (b d : ℕ) where + /-- The `Case` component of type `Wire`. -/ + x : Wire + /-- The `Case` component of type `Wire`. -/ + y : Wire + /-- The `Case` component of type `Setup F x y`. -/ + S : Setup F x y + /-- The `Case` component of type `Template F`. -/ + T : Template F + /-- The `Case` component of type `Budget`. -/ + R : Budget + /-- The `Case` field of type `ℕ`. -/ + w : ℕ + /-- The `Case` field of type `ℕ`. -/ + r : ℕ + /-- The `Case` field of type `ℕ`. -/ + u : ℕ + /-- The `Case` field of type `ℕ`. -/ + v : ℕ + /-- The `Case` field of type `ℕ`. -/ + K : ℕ + /-- The `Case` field of type `ℝ`. -/ + σ : ℝ + h : Input S T R w r b u v d K σ + +namespace Case +variable {F : Type} [Field F] {b d : ℕ} (i : Case F b d) + +/-- Uses `i.T.scheme.m` as the representation. -/ +abbrev m := i.T.scheme.m +/-- Uses `i.T.scheme.h` as the representation. -/ +abbrev height := i.T.scheme.h +/-- The quantity computed by `i.height - i.r`. -/ +abbrev a := i.height - i.r +/-- The quantity computed by `i.height - i.a`. -/ +abbrev n := i.height - i.a +/-- Uses `Phase.base i.S i.r i.R` as the representation. -/ +abbrev base := Phase.base i.S i.r i.R +/-- Uses `Phase.rate i.S i.T i.r i.R` as the representation. -/ +abbrev rate := Phase.rate i.S i.T i.r i.R +/-- Uses `Phase.short i.S i.T i.r i.R` as the representation. -/ +abbrev short := Phase.short i.S i.T i.r i.R +/-- The quantity computed by `100 + i.w + i.short`. -/ +abbrev long := 100 + i.w + i.short + +theorem n_eq : i.n = i.r := Nat.sub_sub_self i.h.group + +private theorem nonneg (i : Case F b d) : 0 ≤ 2 ^ i.r ∧ 0 ≤ 2 ^ i.S.discount ∧ 0 ≤ 2 ^ i.T.scheme.e + := + ⟨Nat.zero_le _, Nat.zero_le _, Nat.zero_le _⟩ + +theorem base_two : 2 ≤ i.base := by unfold base Phase.base; have := nonneg i; omega +theorem base_rate : i.base ≤ i.rate := by unfold rate Phase.rate base; have := nonneg i; omega +theorem rate_short : i.rate ≤ i.short := by unfold short Phase.short rate; omega +theorem short_long : i.short ≤ i.long := Nat.le_add_left .. +theorem rate_two : 2 ≤ i.rate := i.base_two.trans i.base_rate +theorem short_two : 2 ≤ i.short := i.rate_two.trans i.rate_short +theorem long_two : 2 ≤ i.long := i.short_two.trans i.short_long + +/-- Computes the base by the application `Poly base f`. -/ +abbrev Base (f : Case F b d → ℕ) := Poly base f +/-- Computes the rate by the application `Poly rate f`. -/ +abbrev Rate (f : Case F b d → ℕ) := Poly rate f +/-- Computes the short by the application `Poly short f`. -/ +abbrev Short (f : Case F b d → ℕ) := Poly short f +/-- Computes the long by the application `Poly long f`. -/ +abbrev Long (f : Case F b d → ℕ) := Poly long f + +variable {f : Case F b d → ℕ} +theorem Base.rate (h : Base f) : Rate f := h.grow base_rate +theorem Rate.short (h : Rate f) : Short f := h.grow rate_short +theorem Short.long (h : Short f) : Long f := h.grow short_long + +local notation "I" => Case F b d + +theorem base_const (c : ℕ) : Base (fun _ : I => c) := Poly.const base_two c +theorem rate_const (c : ℕ) : Rate (fun _ : I => c) := Poly.const rate_two c +theorem short_const (c : ℕ) : Short (fun _ : I => c) := Poly.const short_two c +theorem long_const (c : ℕ) : Long (fun _ : I => c) := Poly.const long_two c + +theorem blocks : Base (fun i : I => 2 ^ i.r) := + Poly.of_le base_two (fun i => by unfold base Phase.base; have := nonneg i; omega) +theorem levels : Base (fun i : I => i.S.h) := + Poly.of_le base_two (fun i => by unfold base Phase.base; have := nonneg i; omega) +theorem units : Base (fun i : I => Nat.clog 2 (1 + i.S.U)) := + Poly.of_le base_two (fun i => by unfold base Phase.base; have := nonneg i; omega) +theorem discount : Base (fun i : I => 2 ^ i.S.discount) := + Poly.of_le base_two (fun i => by unfold base Phase.base; have := nonneg i; omega) +theorem load : Base (fun i : I => i.R.load) := + Poly.of_le base_two (fun i => by unfold base Phase.base; have := nonneg i; omega) +theorem lanes : Base (fun i : I => i.S.d) := + Poly.of_le base_two (fun i => by unfold base Phase.base; have := nonneg i; omega) +theorem spans : Rate (fun i : I => 2 ^ i.T.scheme.e) := + Poly.of_le rate_two (fun i => by unfold rate Phase.rate; have := nonneg i; omega) +theorem lengths : Rate (fun i : I => Nat.clog 2 (1 + i.T.scheme.ℓ)) := + Poly.of_le rate_two (fun i => by unfold rate Phase.rate; have := nonneg i; omega) +theorem counters : Short (fun i : I => i.T.count) := + Poly.of_le short_two (fun i => by unfold short Phase.short; omega) +theorem bits : Short (fun i : I => i.T.scheme.ℓ) := + Poly.of_le short_two (fun i => by unfold short Phase.short; omega) +theorem tags : Short (fun i : I => i.R.tag) := + Poly.of_le short_two (fun i => by unfold short Phase.short; omega) +theorem world : Long (fun i : I => i.w) := + Poly.of_le long_two (fun i => by unfold long; omega) +theorem hosts : Long (fun i : I => i.m) := + ((long_const 2).mul world).mono (fun i => (Nat.le_add_right ..).trans i.h.upper) +theorem groups : Base (fun i : I => i.a) := + levels.mono fun i => (Nat.sub_le ..).trans i.h.height +theorem tiles : Base (fun i : I => 2 ^ i.n) := by + simpa only [n_eq] using (blocks : Base (fun i : I => _)) +theorem slots : Base (fun i : I => 2 ^ i.T.scheme.d) := + (base_const (2 ^ d)).mono fun i => Nat.pow_le_pow_right (by decide) i.h.degree + +end Case +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase +end + +/- +# Charges on host addresses and short block records + +Multiplication by a short quantity is allowed in both terms of the +budget. Multiplication by the world size is confined to the first. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case +variable {F : Type} [Field F] {b d : ℕ} +local notation "I" => Case F b d + +/-- The condition `∃ k : ℕ, ∀ i, f i ≤ 2 ^ (j i) * i.long ^ k + 2 ^ (j i + i.height) * i.short ^ +k` on the specified data. -/ +abbrev Mixed (j f : I → ℕ) : Prop := + MixedCost (fun i => i.long) (fun i => i.short) (fun i => i.height) j f + +/-- Computes the cost by the application `Mixed m f`. -/ +abbrev Cost (f : I → ℕ) := Mixed m f +/-- The indexed operation `Mixed (fun _ => 0) f`. -/ +abbrev Row (f : I → ℕ) := Mixed (fun _ => 0) f + +variable {j f g n : Case F b d → ℕ} + +namespace Mixed + +theorem mono (h : Mixed j f) (hg : ∀ i, g i ≤ f i) : Mixed j g := + MixedCost.mono h hg + +theorem add (h : Mixed j f) (h' : Mixed j g) : Mixed j (fun i => f i + g i) := + MixedCost.add h h' (fun i => i.long_two) (fun i => i.short_two) + +theorem mul (h : Mixed j f) (h' : Short g) : Mixed j (fun i => f i * g i) := + MixedCost.mul h h' (fun i => i.short_long) + +theorem left (h : Mixed j f) (h' : Short g) : Mixed j (fun i => g i * f i) := + (h.mul h').mono fun _ => le_of_eq (mul_comm ..) + +theorem scale (h : Mixed j f) (k : ℕ) : Mixed j (fun i => k * f i) := h.left (short_const k) + +theorem long (j : I → ℕ) (h : Long f) : Mixed j (fun i => 2 ^ (j i) * f i) := + MixedCost.long j h + +theorem short (j : I → ℕ) (h : Short f) : Mixed j (fun i => 2 ^ (j i + i.height) * f i) := + MixedCost.short j h + +end Mixed + +theorem Long.row (h : Long f) : Row f := by + simpa only [pow_zero, one_mul] using Mixed.long (fun _ => 0) h + +theorem Short.blocks (h : Short f) : Row (fun i => 2 ^ i.height * f i) := by + simpa only [zero_add] using Mixed.short (fun _ => 0) h + +theorem Short.groups (h : Short f) : Row (fun i => 2 ^ i.a * f i) := + h.blocks.mono (fun i => Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (Nat.sub_le ..))) + +theorem Row.hosts (h : Row f) : Cost (fun i => 2 ^ i.m * f i) := + MixedCost.hosts (fun i => i.m) h + +theorem Row.expand (h : Row f) (h' : Short (fun i => 2 ^ n i)) : + Cost (fun i => 2 ^ (i.m + n i) * f i) := by + simpa only [pow_add, mul_assoc] using Row.hosts (h.left h') + +theorem Row.cost (h : Row f) : Cost f := + h.hosts.mono fun _ => Nat.le_mul_of_pos_left _ (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case +end + +/- # Polynomial cost of the new table controls after a host reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case +open Coloring Assembly History + +variable {F : Type} [Field F] [Fintype F] {b d : ℕ} +local notation "I" => Case F b d + +theorem reset_overhead {e : I → ℕ} (he : Rate (fun i => 2 ^ (e i))) : + Rate (fun i => Reset.overhead i.T.scheme (e i)) := by + have hl : Rate (fun i : I => Dense.used i.T.scheme.ℓ) := by + simpa only [Dense.used, Nat.add_comm] using (lengths : Rate (fun i : I => _)) + have hk : Rate (fun i : I => 1 + i.T.scheme.k) := + (rate_const 1).mono fun i => by rw [i.h.single, Nat.add_zero] + have hy := he.of_exp.add (rate_const 1) + have ht := (((he.add he).add (rate_const 1)).pow 3).mul (rate_const 8) + have hc := ht.mul (rate_const (Nat.clog 2 (Fintype.card F))) + have hh := (hy.add (he.mul (hk.add (spans.mul hy)))).add hc + refine (hh.add (he.mul hl)).mono fun i => ?_ + simp only [Reset.overhead, Reset.shapeWidth, Reset.tripleCost, Reset.Addr, B, Fintype.card_sum, + Fintype.card_fin] + rfl + +theorem reset_added {n e k : I → ℕ} (hn : Rate n) (he : Rate (fun i => 2 ^ (e i))) (hk : Rate k) : + Rate (fun i => (Post.headerFmt (n i) (e i) (k i)).width + Reset.overhead i.T.scheme (e i)) := by + have one := (rate_const 1 : Rate (fun _ : I => _)) + refine ((one.add (he.mul (hk.add (one.add (one.add (hn.add he.of_exp)))))).add + (reset_overhead he)).mono fun i => ?_ + simp only [Post.headerFmt, Post.field, Format.width_pair, Format.width_vec, Format.width_addr] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case +end + +/- # Controlling widths after an expansion of hosts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case +open Assembly Coloring +variable {F : Type} [Field F] {b d : ℕ} +local notation "I" => Case F b d + +/-- The data for the child construction, including `extent`, `allocation`, `growth`, `single`, +`spans`. -/ +structure Child (N : I → Template F) (δ : I → ℕ) : Prop where + extent : ∀ i, (N i).scheme.h ≤ i.height + allocation : ∀ i, (N i).scheme.m ≤ i.m + δ i + growth : Short (fun i : I => 2 ^ δ i) + single : ∀ i, (N i).scheme.k = 0 + spans : Short (fun i : I => 2 ^ (N i).scheme.e) + neighbors : Short (fun i : I => 2 ^ (N i).scheme.d) + bits : Short (fun i : I => (N i).scheme.ℓ) + count : Short (fun i : I => (N i).count) + +namespace Child + +theorem parent : Child (fun i : I => i.T) (fun _ => 0) := + ⟨fun _ => le_rfl, fun _ => le_rfl, short_const 1, fun i : I => i.h.single, + Case.spans.short, Case.slots.rate.short, Case.bits, counters⟩ + +theorem names : Long (fun i : I => i.S.e) := + ((long_const 3).mul world).mono (fun i : I => i.h.names) + +variable {N : Case F b d → Template F} {δ f : Case F b d → ℕ} (H : Child N δ) +include H + +theorem layer (h : Short f) : Row (fun i : I => 2 ^ (N i).scheme.h * f i) := + MixedCost.exp_mul_mono h.blocks H.extent + +theorem cost (h : Row f) : Cost (fun i : I => 2 ^ (N i).scheme.m * f i) := + MixedCost.exp_mul_mono (h.expand H.growth) H.allocation + +theorem address : Long (fun i : I => (N i).scheme.m) := + (hosts.add H.growth.long.of_exp).mono H.allocation + +theorem format : Cost (fun i : I => (N i).format.width) := by + have top := Long.row (((H.neighbors.long.mul (H.address.add (long_const 2))).add (long_const 2))) + have body := H.layer (H.bits.add H.count) + refine (H.cost (top.add body)).mono fun i : I => ?_ + rw [Template.width] + +theorem scheme : Cost (fun i : I => (N i).scheme.format.width) := + H.format.mono fun i => (N i).scheme_width_le + +theorem row : Row (fun i : I => (Trail.rowFormat (N i).scheme i.S.h i.S.d i.S.e).width) := by + have body := H.layer (H.spans.mul (lanes.rate.short.add levels.rate.short)) + have head : Row (fun i : I => i.S.d * i.S.e) := Long.row ((lanes.rate.short.long.mul names)) + refine (body.add head).mono fun i : I => ?_ + rw [Trail.width_row, H.single, add_zero, pow_add, mul_assoc] + +theorem trail : Cost (fun i : I => (Trail.format (N i).scheme i.S.h i.S.d i.S.e).width) := by + refine (H.cost H.row).mono fun i : I => ?_ + rw [Trail.width_format] + +theorem full : Cost (fun i : I => (i.S.format (N i)).width) := by + refine (H.format.add H.trail).mono fun i : I => ?_ + rw [Format.width_pair] + +theorem sweep : Cost (fun i : I => Snapshot.sweepCost i.S (N i)) := by + have tags := H.layer (((short_const 1).add H.bits).add H.bits) + have address := Long.row (((long_const 4).mul (H.neighbors.long.mul H.address))) + have aux : Cost (fun i : I => (Format.vec (N i).scheme.m (N i).header).width) := by + refine H.format.mono fun i : I => ?_ + rw [Format.width_pair] + exact Nat.le_add_left .. + refine (((H.cost (address.add tags)).add (aux.scale 4)).add (H.trail.scale 4)).mono fun i : I + => ?_ + rw [Snapshot.sweepCost, updateCost, Format.width_addr] + +end Child +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case +end + +/- # The cost of retaining exterior labels after an expansion -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case.Child +open Assembly Coloring +variable {F : Type} [Field F] {b d : ℕ} +local notation "I" => Case F b d +variable {N : Case F b d → Template F} {δ k : Case F b d → ℕ} (H : Child N δ) + (hk : Short (fun i => 2 ^ k i)) + +private theorem old_height : Short (fun i : I => i.height) := + levels.rate.short.mono (fun i : I => i.h.height) + +include H hk + +theorem receipts : + Cost (fun i : I => (Trail.receipts i.T.scheme (N i).scheme (k i) i.S.h i.S.d i.S.e).width) := by + refine (H.cost (parent.row.left hk)).mono fun i : I => ?_ + rw [Format.width_vec, Format.width_vec] + +theorem controls : Cost (fun i : I => (Trail.controls i.T.scheme (N i).scheme (k i)).width) := by + have len := (((short_const 1).add hk.of_exp).add old_height).add parent.spans.of_exp + refine (H.cost (H.layer (H.spans.mul len))).mono fun i : I => ?_ + rw [Trail.width_controls, H.single, i.h.single, add_zero, add_zero, pow_add, mul_assoc, mul_assoc] + +private theorem execution : Cost (fun i : I => Trail.cost i.T.scheme (N i).scheme (k i) i.S.h i.S.d + i.S.d i.S.e) := by + let w := fun i : I => Trail.addressWidth i.T.scheme (N i).scheme (k i) + let a := fun i : I => 1 + k i + i.T.scheme.e + (N i).scheme.e + have wa (i : I) : w i ≤ i.height + a i := by + unfold w Trail.addressWidth a + rw [H.single, i.h.single] + have := H.extent i + unfold Case.height at * + omega + have ha : Short (fun i : I => 2 ^ a i) := + (((short_const (2 ^ 1)).exp_add hk).exp_add parent.spans).exp_add H.spans + have hw : Short w := (old_height.add ha.of_exp).mono wa + have hw' : Row (fun i : I => 2 ^ w i) := by + refine ha.blocks.mono fun i : I => ?_ + rw [← pow_add] + exact Nat.pow_le_pow_right (by decide) (wa i) + have lane := (lanes (F := F) (b := b) (d := d)).rate.short + have hs := (((((short_const 100).add hw).add (hk.mul (lane.add (short_const 1)))).add + levels.rate.short).add lane).add lane + exact H.cost ((hw'.mul (hs.pow 10)).add (Long.row (((Short.long hs).add names).pow 104))) + +theorem carry {A : I → Format} (h : Cost (fun i : I => (A i).width)) : + Cost (fun i : I => Trail.carryCost i.T.scheme (N i).scheme (k i) + i.S.h i.S.d i.S.d i.S.e (A i) (N i).format) := by + have feed := (H.receipts hk).add (H.controls hk) + refine (((h.scale 20).add ((H.format.add feed).scale 16)).add ((execution H hk).scale 4)).mono + fun i : I => ?_ + rw [Trail.carryCost, show (Trail.feed _ _ _ _ _ _).width = _ from Format.width_pair ..] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case.Child +end + +/- # Gathering neighboring records without duplicating long addresses per block -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case.Child +open Assembly Coloring +variable {F : Type} [Field F] {b d : ℕ} +local notation "I" => Case F b d + +theorem current : Cost (fun i : I => (Trail.source i.T.scheme i.S.h i.S.d i.S.e).width) := by + refine (parent.scheme.add parent.trail).mono fun i : I => ?_ + rw [Format.width_pair] + +private theorem bank : Cost (fun i : I => (Trail.bank i.T.scheme i.S.h i.S.d i.S.e).width) := by + have h : Long (fun i : I => 2 ^ i.T.scheme.d * i.m) := parent.neighbors.long.mul hosts + refine (Row.hosts (h.row.add parent.row)).mono fun i : I => ?_ + rw [Format.width_vec, Format.width_pair, Format.width_vec, Format.width_addr] + +theorem fan : Short (fun i : I => 2 ^ (i.T.scheme.d + 1)) := + parent.neighbors.exp_add (short_const (2 ^ 1)) + +theorem gather {N : I → Template F} {δ c : I → ℕ} (H : Child N δ) + (h : Cost (fun i : I => gatherCost i.m i.T.scheme.d (Trail.rowFormat i.T.scheme i.S.h i.S.d + i.S.e).width (c i))) : + Cost (fun i : I => Trail.gatherBound i.T.scheme (N i).scheme i.S.h i.S.d i.S.e + (Trail.rowFormat i.T.scheme i.S.h i.S.d i.S.e).width (c i)) := by + have extra := ((current.add bank).add (parent.receipts parent.neighbors)).add (H.receipts fan) + exact h.add (extra.scale 64) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase.Case.Child +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Pieces.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Pieces.lean new file mode 100644 index 0000000000..da31ebf4f2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Pieces.lean @@ -0,0 +1,1077 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Keys +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Transform +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood + +/-! +# Packing port and table rows + +Keep a tuple of size at most `u` intact by assigning it to the row of +its first slot and allowing `2*u` slots per row. Both coordinates use +prefix sums. The same construction packs whole positions into bins. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +variable {m d H : ℕ} + +/-- Indexes the blocks by the coordinates of `Σ i, Fin (l i)`. -/ +abbrev Blocks (l : Fin m → ℕ) := Σ i, Fin (l i) + +/-- Computes the start by the application `Routing.offset l Fin.val i`. -/ +def start (l : Fin m → ℕ) (i : Fin m) := Routing.offset l Fin.val i + +theorem ordered (l : Fin m → ℕ) : Routing.Ordered l Fin.val := + fun _ _ _ _ he => Fin.ext he + +/-- Computes the order by the application `Routing.pack l Fin.val (ordered l)`. -/ +noncomputable def order (l : Fin m → ℕ) : Blocks l ≃ Fin (∑ i, l i) := + Routing.pack l Fin.val (ordered l) + +theorem order_val (l : Fin m → ℕ) (i : Fin m) (j : Fin (l i)) : + (order l ⟨i, j⟩).val = start l i + j.val := rfl + +/-- The quantity computed by `(∑ i, l i) / u + 1`. -/ +def rows (l : Fin m → ℕ) (u : ℕ) := (∑ i, l i) / u + 1 + +theorem rows_cost (l : Fin m → ℕ) (u : ℕ) : + rows l u * u ≤ (∑ i, l i) + u := by + rw [rows, Nat.add_mul, Nat.one_mul] + exact Nat.add_le_add_right (Nat.div_mul_le_self _ _) _ + +/-- The last row is always available, even for an empty trailing tuple. -/ +def row (l : Fin m → ℕ) (u : ℕ) (i : Fin m) : Fin (rows l u) := + ⟨start l i / u, Nat.lt_succ_of_le (Nat.div_le_div_right + (by unfold start Routing.offset; exact Finset.sum_le_sum_of_subset (Finset.filter_subset _ _)))⟩ + +/-- Embeds `Blocks l` into `Fin (rows l u) × Fin (2 * u) where toFun t`. -/ +def pack (l : Fin m → ℕ) (u : ℕ) (hu : 0 < u) (hl : ∀ i, l i ≤ u) : + Blocks l ↪ Fin (rows l u) × Fin (2 * u) where + toFun t := (row l u t.1, ⟨start l t.1 % u + t.2.val, by + have := Nat.mod_lt (start l t.1) hu + have := t.2.isLt.trans_le (hl _) + omega⟩) + inj' := by + rintro ⟨i, j⟩ ⟨i', j'⟩ he + apply (order l).injective + apply Fin.ext + have h := congrArg (fun z => u * z.1.val + z.2.val) he + simpa only [row, ← Nat.add_assoc, Nat.div_add_mod, order_val] using h + +/-- Occurrences are indexed first, incident ports second. -/ +abbrev Lengths (m d : ℕ) := Fin m → Fin d → ℕ +/-- Indexes the slots by the coordinates of `Σ i, Blocks (l i)`. -/ +abbrev Slots (l : Lengths m d) := Σ i, Blocks (l i) + +/-- The sum of `l i j` indexed by `j`. -/ +def arity (l : Lengths m d) (i : Fin m) := ∑ j, l i j + +/-- The sum of `arity l i` indexed by `i`. -/ +def total (l : Lengths m d) := ∑ i, arity l i + +/-- Computes the tables by the application `rows (arity l) u`. -/ +def tables (l : Lengths m d) (u : ℕ) := rows (arity l) u + +/-- Computes the port by the application `l i j`. -/ +def port (l : Lengths m d) (j : Fin d) (i : Fin m) := l i j + +/-- The quantity computed by `rows (port l j) (2 * u)`. -/ +def ports (l : Lengths m d) (u : ℕ) (j : Fin d) := rows (port l j) (2 * u) + +/-- The quantity computed by `tables l u + (∑ j, ports l u j) + 1`. -/ +def size (l : Lengths m d) (u : ℕ) := tables l u + (∑ j, ports l u j) + 1 + +theorem size_cost (l : Lengths m d) (u : ℕ) : + size l u * u ≤ (d + 2) * u + 2 * total l := by + have ht : tables l u * u ≤ total l + u := rows_cost _ _ + have hp (j : Fin d) : ports l u j * u ≤ (∑ i, l i j) + u := by + unfold ports rows + rw [Nat.add_mul, Nat.one_mul] + refine Nat.add_le_add_right ?_ _ + exact (Nat.mul_le_mul_left _ (show u ≤ 2 * u by omega)).trans (Nat.div_mul_le_self _ _) + have hs : (∑ j, ports l u j) * u ≤ total l + d * u := by + rw [Finset.sum_mul] + refine le_trans (Finset.sum_le_sum fun j _ => hp j) ?_ + rw [Finset.sum_add_distrib, Finset.sum_comm] + simp [total, arity] + unfold size + simp only [Nat.add_mul, Nat.one_mul] + omega + +/-- Embeds `Slots l` into `Fin (tables l u) × Fin (2 * u)`. -/ +noncomputable def tableSlot (l : Lengths m d) (u : ℕ) (hu : 0 < u) (hl : ∀ i, arity l i ≤ u) : + Slots l ↪ Fin (tables l u) × Fin (2 * u) := + (Equiv.sigmaCongrRight (fun i => order (l i))).toEmbedding.trans (pack (arity l) u hu hl) + +theorem tableSlot_val (l : Lengths m d) (u : ℕ) (hu : 0 < u) (hl : ∀ i, arity l i ≤ u) + (i : Fin m) (j : Fin d) (t : Fin (l i j)) : + let pos := tableSlot l u hu hl ⟨i, j, t⟩ + pos.1.val = start (arity l) i / u ∧ + pos.2.val = start (arity l) i % u + (start (l i) j + t.val) := ⟨rfl, rfl⟩ + +/-- Reindexes `Slots l` and `Σ j, Blocks (port l j) where toFun t` by an equivalence. -/ +def byPort (l : Lengths m d) : Slots l ≃ Σ j, Blocks (port l j) where + toFun t := ⟨t.2.1, t.1, t.2.2⟩ + invFun t := ⟨t.2.1, t.1, t.2.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +/-- Embeds `Fin n` into `Fin (n / u + 1) × Fin u where toFun t`. -/ +def divmod (n u : ℕ) (hu : 0 < u) : Fin n ↪ Fin (n / u + 1) × Fin u where + toFun t := (⟨t.val / u, Nat.lt_succ_of_le (Nat.div_le_div_right t.isLt.le)⟩, + ⟨t.val % u, Nat.mod_lt _ hu⟩) + inj' := by + intro i j h + apply Fin.ext + simpa only [Nat.div_add_mod] using congrArg (fun z => u * z.1.val + z.2.val) h + +/-- Embeds `Slots l` into `Fin (∑ j, ports l u j) × Fin (2 * u)`. -/ +noncomputable def portSlot (l : Lengths m d) (u : ℕ) (hu : 0 < u) : + Slots l ↪ Fin (∑ j, ports l u j) × Fin (2 * u) := by + let e (j : Fin d) : Blocks (port l j) ↪ Fin (ports l u j) × Fin (2 * u) := + (order (port l j)).toEmbedding.trans (divmod _ _ (by omega)) + let f : (Σ j, Blocks (port l j)) ↪ Σ j, Fin (ports l u j) × Fin (2 * u) := + (Function.Embedding.refl _).sigmaMap e + exact (byPort l).toEmbedding.trans <| f.trans <| + (Equiv.sigmaProdDistrib _ _).symm.toEmbedding.trans <| + (order (ports l u)).toEmbedding.prodMap (.refl _) + +theorem portSlot_val (l : Lengths m d) (u : ℕ) (hu : 0 < u) + (i : Fin m) (j : Fin d) (t : Fin (l i j)) : + let pos := portSlot l u hu ⟨i, j, t⟩ + let rank := start (port l j) i + t.val + pos.1.val = start (ports l u) j + rank / (2 * u) ∧ + pos.2.val = rank % (2 * u) := ⟨rfl, rfl⟩ + +/-- Row reservations for each position include a spare row. -/ +def counts (l : Fin H → Lengths m d) (u : ℕ) (i : Fin H) := size (l i) u + +/-- Computes the bins by the application `rows (counts l u) v`. -/ +def bins (l : Fin H → Lengths m d) (u v : ℕ) := rows (counts l u) v + +/-- Computes the place by the application `pack (counts l u) v hv hl`. -/ +def place (l : Fin H → Lengths m d) (u v : ℕ) (hv : 0 < v) (hl : ∀ i, size (l i) u ≤ v) : + Blocks (counts l u) ↪ Fin (bins l u v) × Fin (2 * v) := + pack (counts l u) v hv hl + +theorem place_val (l : Fin H → Lengths m d) (u v : ℕ) (hv : 0 < v) + (hl : ∀ i, size (l i) u ≤ v) (i : Fin H) (j : Fin (size (l i) u)) : + let pos := place l u v hv hl ⟨i, j⟩ + pos.1.val = start (counts l u) i / v ∧ pos.2.val = start (counts l u) i % v + j.val := + ⟨rfl, rfl⟩ + +theorem bins_cost (l : Fin H → Lengths m d) (u v : ℕ) : + bins l u v * v * u ≤ H * ((d + 2) * u) + 2 * (∑ i, total (l i)) + v * u := by + have cost : (∑ i, counts l u i) * u ≤ H * ((d + 2) * u) + 2 * (∑ i, total (l i)) := by + rw [Finset.sum_mul] + calc + _ ≤ ∑ i : Fin H, ((d + 2) * u + 2 * total (l i)) := + Finset.sum_le_sum (fun i _ => size_cost (l i) u) + _ = _ := by simp [Finset.sum_add_distrib, Finset.mul_sum] + refine (Nat.mul_le_mul_right u (rows_cost (counts l u) v)).trans ?_ + rw [Nat.add_mul] + exact Nat.add_le_add_right cost _ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +section +/- +# Common bins for the two endpoint orders + +The table rows, port rows and spare row of one position all occupy +the same bin. Slots in each order are injectively placed, so a bit +assignment can be transferred between orders without duplication. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +variable {H m d u v K : ℕ} + +/-- The indexing data represented by `Fin H → Lengths m d`. -/ +abbrev Inventory (H m d : ℕ) := Fin H → Lengths m d +/-- Indexes the endpoints by the coordinates of `Σ i, Slots (l i)`. -/ +abbrev Endpoints (l : Inventory H m d) := Σ i, Slots (l i) +/-- Indexes the port rows by the coordinates of `Σ i, Blocks (ports (l i) u)`. -/ +abbrev PortRows (l : Inventory H m d) (u : ℕ) := Σ i, Blocks (ports (l i) u) +/-- Indexes the address by the coordinates of `Fin K × Fin (2 * v)`. -/ +abbrev Address (v K : ℕ) := Fin K × Fin (2 * v) + +/-- The ordinal in the list at one port, independent of its row address. -/ +def rank (l : Inventory H m d) (x : Endpoints l) : ℕ := + start (port (l x.1) x.2.2.1) x.2.1 + x.2.2.2.val + +/-- The port row of type `PortRows l u` for the given inputs. -/ +def portRow (l : Inventory H m d) (u : ℕ) (x : Endpoints l) : PortRows l u := + ⟨x.1, x.2.2.1, ⟨rank l x / (2 * u), Nat.lt_succ_of_le (Nat.div_le_div_right + (order (port (l x.1) x.2.2.1) ⟨x.2.1, x.2.2.2⟩).isLt.le)⟩⟩ + +/-- The data for the layout construction, including `tableLoc`, `tableSlots`, `portSlots`, +`portLoc`, `tuple`. -/ +structure Layout (l : Inventory H m d) (u v K : ℕ) where + /-- The `Layout` component of type `Fin H → Fin m → Address v K`. -/ + tableLoc : Fin H → Fin m → Address v K + /-- Embeds the coordinates as `Endpoints l ↪ Address v K × Fin (2 * u)`. -/ + tableSlots : Endpoints l ↪ Address v K × Fin (2 * u) + /-- Embeds the coordinates as `Endpoints l ↪ Address v K × Fin (2 * u)`. -/ + portSlots : Endpoints l ↪ Address v K × Fin (2 * u) + /-- Embeds the coordinates as `PortRows l u ↪ Address v K`. -/ + portLoc : PortRows l u ↪ Address v K + tuple : ∀ x, (tableSlots x).1 = tableLoc x.1 x.2.1 + separate : ∀ i j i' j', tableLoc i j = tableLoc i' j' → i = i' + sameBin : ∀ i j r, (tableLoc i j).1 = (portLoc ⟨i, r⟩).1 + locate : ∀ x, (portSlots x).1 = portLoc (portRow l u x) + ordinal : ∀ x, (portSlots x).2.val = rank l x % (2 * u) + +variable {l : Inventory H m d} + +theorem Layout.bin_eq (L : Layout l u v K) (x : Endpoints l) : + (L.tableSlots x).1.1 = (L.portSlots x).1.1 := by + rw [L.tuple, L.locate] + exact L.sameBin _ _ _ + +theorem Layout.port_iff (L : Layout l u v K) (x : Endpoints l) (r : PortRows l u) (j : Fin (2 * u)) + : + L.portSlots x = (L.portLoc r, j) ↔ portRow l u x = r ∧ rank l x % (2 * u) = j.val := by + simp only [Prod.ext_iff, L.locate, L.portLoc.injective.eq_iff, Fin.ext_iff, L.ordinal] + +theorem Layout.row_eq (L : Layout l u v K) (x y : Endpoints l) : + (L.portSlots x).1 = (L.portSlots y).1 ↔ (x.1 = y.1 ∧ x.2.2.1 = y.2.2.1) ∧ + rank l x / (2 * u) = rank l y / (2 * u) := by + rw [L.locate, L.locate, L.portLoc.injective.eq_iff] + constructor + · exact fun h => ⟨⟨congrArg (fun z : PortRows l u => z.1) h, + congrArg (fun z : PortRows l u => z.2.1) h⟩, + congrArg (fun k => k.2.2.val) h⟩ + · obtain ⟨i, j, p, t⟩ := x + obtain ⟨i', j', p', t'⟩ := y + rintro ⟨⟨rfl, rfl⟩, he⟩ + apply congrArg (fun n : Fin (ports (l i) u p) => (⟨i, p, n⟩ : PortRows l u)) + exact Fin.ext he + +/-- Embeds `Fin (tables l u)` into `Fin (size l u)`. -/ +def enterTable (l : Lengths m d) (u : ℕ) : Fin (tables l u) ↪ Fin (size l u) := + Fin.castLEEmb (by unfold size; omega) + +/-- Embeds `Fin (∑ j, ports l u j)` into `Fin (size l u) where toFun j`. -/ +def enterPort (l : Lengths m d) (u : ℕ) : + Fin (∑ j, ports l u j) ↪ Fin (size l u) where + toFun j := ⟨tables l u + j.val, by unfold size; have := j.isLt; omega⟩ + inj' := fun _ _ he => Fin.ext (Nat.add_left_cancel (congrArg Fin.val he)) + +/-- Embeds `Endpoints l` into `Address v K × Fin (2 * u)`. -/ +def stack (e : Blocks (counts l u) ↪ Address v K) + (f : ∀ i, Slots (l i) ↪ Fin (size (l i) u) × Fin (2 * u)) : + Endpoints l ↪ Address v K × Fin (2 * u) := + ((Function.Embedding.refl _).sigmaMap f).trans + ((Equiv.sigmaProdDistrib _ _).symm.toEmbedding.trans (e.prodMap (.refl _))) + +variable (l : Inventory H m d) (u v K : ℕ) (hu : 0 < u) (hv : 0 < v) + (ha : ∀ i j, arity (l i) j ≤ u) (hs : ∀ i, size (l i) u ≤ v) (hk : bins l u v ≤ K) + +/-- The make of type `Layout l u v K`, constructed using `(place l u v hv hs).trans +((Fin.castLEEmb hk).prodMap (.refl _))`. -/ +noncomputable def make : Layout l u v K := by + let e : Blocks (counts l u) ↪ Address v K := + (place l u v hv hs).trans ((Fin.castLEEmb hk).prodMap (.refl _)) + let a (i) := (tableSlot (l i) u hu (ha i)).trans ((enterTable (l i) u).prodMap (.refl _)) + let b (i) := (portSlot (l i) u hu).trans ((enterPort (l i) u).prodMap (.refl _)) + let c (i) := (order (ports (l i) u)).toEmbedding.trans (enterPort (l i) u) + let t i j := e ⟨i, enterTable (l i) u (row (arity (l i)) u j)⟩ + let p : PortRows l u ↪ Address v K := ((Function.Embedding.refl _).sigmaMap c).trans e + exact ⟨t, stack e a, stack e b, p, fun _ => rfl, + fun _ _ _ _ h => congrArg Sigma.fst (e.injective h), fun _ _ _ => rfl, + fun _ => rfl, fun _ => rfl⟩ + +theorem make_table (i : Fin H) (j : Fin m) : + let a := (make l u v K hu hv ha hs hk).tableLoc i j + a.1.val = start (counts l u) i / v ∧ + a.2.val = start (counts l u) i % v + start (arity (l i)) j / u := ⟨rfl, rfl⟩ + +theorem make_tuple (i : Fin H) (j : Fin m) (p : Fin d) (t : Fin (l i j p)) : + ((make l u v K hu hv ha hs hk).tableSlots ⟨i, j, p, t⟩).2.val = + start (arity (l i)) j % u + (start (l i j) p + t.val) := rfl + +theorem make_port (i : Fin H) (p : Fin d) (j : Fin (ports (l i) u p)) : + let a := (make l u v K hu hv ha hs hk).portLoc ⟨i, p, j⟩ + a.1.val = start (counts l u) i / v ∧ + a.2.val = start (counts l u) i % v + (tables (l i) u + (start (ports (l i) u) p + j.val)) := + ⟨rfl, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +section +/- # The anchor of a position and its consecutive port headers -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +variable {H m d : ℕ} + +/-- Indexes the anchor by the coordinates of `Fin K × Fin v`. -/ +abbrev Anchor (v K : ℕ) := Fin K × Fin v + +theorem size_lower (l : Lengths m d) (u : ℕ) : d + 2 ≤ size l u := by + have hp : d ≤ ∑ j, ports l u j := by + simpa using Finset.sum_le_sum (s := Finset.univ) (fun j _ => + show 1 ≤ ports l u j from Nat.le_add_left _ _) + have ht : 1 ≤ tables l u := Nat.le_add_left _ _ + unfold size + omega + +variable (l : Inventory H m d) (u v K : ℕ) + (hv : 0 < v) (hs : ∀ i, size (l i) u ≤ v) (hk : bins l u v ≤ K) + +/-- A header for the entire position fits in the first half of its bin. -/ +def anchor : Fin H ↪ Anchor v K where + toFun i := (Fin.castLE hk (row (counts l u) v i), ⟨start (counts l u) i % v, Nat.mod_lt _ hv⟩) + inj' := by + intro i j he + let atStart (k : Fin H) : Blocks (counts l u) := + ⟨k, ⟨0, lt_of_lt_of_le (by omega) (size_lower _ _)⟩⟩ + have eq : place l u v hv hs (atStart i) = place l u v hv hs (atStart j) := + Prod.ext (Fin.ext (congrArg (fun p => p.1.val) he)) (Fin.ext (congrArg (fun p => p.2.val) he)) + exact congrArg Sigma.fst ((place l u v hv hs).injective eq) + +theorem anchor_val (i : Fin H) : + let a := anchor l u v K hv hs hk i + a.1.val = start (counts l u) i / v ∧ a.2.val = start (counts l u) i % v := ⟨rfl, rfl⟩ + +/-- The port headers use distinct consecutive slots in the same bin. -/ +def portAnchor : Fin H × Fin d ↪ Address v K := + let emb : Fin H × Fin d ↪ Blocks (counts l u) := + { toFun := fun p => ⟨p.1, ⟨p.2.val, lt_of_lt_of_le p.2.isLt + ((Nat.le_add_right d 2).trans (size_lower _ _))⟩⟩ + inj' := fun _ _ he => Prod.ext (congrArg Sigma.fst he) (Fin.ext (congrArg (fun x + => x.2.val) he)) } + (emb.trans (place l u v hv hs)).trans ((Fin.castLEEmb hk).prodMap (.refl _)) + +theorem portAnchor_val (p : Fin H × Fin d) : + let a := portAnchor l u v K hv hs hk p + a.1.val = start (counts l u) p.1 / v ∧ a.2.val = start (counts l u) p.1 % v + p.2.val := + ⟨rfl, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- +# Reassembling port rows into table rows + +Each bin holds rows indexed by `R`, with slots indexed by `S`. Split +each slot into `R` pieces with bit positions `P`. A slice takes one +piece from every slot of every row, so it has the width of one row. +The same list of sources determines the rearrangement in each slice. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Transcript + +open Classical in +/-- Indexes the piece by the coordinates of `R × P`. -/ +abbrev Piece (R P : Type) := R × P +open Classical in +/-- Indexes the row by the coordinates of `S × Piece R P`. -/ +abbrev Row (R S P : Type) := S × Piece R P +open Classical in +/-- Indexes the slice by the coordinates of `(R × S) × P`. -/ +abbrev Slice (R S P : Type) := (R × S) × P + +variable {G R S P A D X F : Type} + +open Classical in +/-- A common routing dictionary and a common table dictionary. Taps +may read any exterior or private position of a larger transcript. -/ +structure Bins (F G R S P A D X : Type) where + /-- The selected move of type `(A → Bool) → R × S → Option (R × S)`. -/ + move : (A → Bool) → R × S → Option (R × S) + /-- The scalar prefactor of type `(D → Bool) → (Row R S P → Bool) → F`. -/ + scalar : (D → Bool) → (Row R S P → Bool) → F + /-- The control datum of type `G → A → X ⊕ Bool`. -/ + control : G → A → X ⊕ Bool + /-- The `Bins` component of type `G × R → D → X ⊕ Bool`. -/ + format : G × R → D → X ⊕ Bool + /-- The `Bins` component of type `G → R × S → Piece R P → X ⊕ Bool`. -/ + port : G → R × S → Piece R P → X ⊕ Bool + +namespace Bins +variable (B : Bins F G R S P A D X) + +open Classical in +/-- The indexed operation `(B.move (Sum.elim x id ∘ B.control g) (r, i.1)).elim false (fun v => +Sum.elim x id (B.port g v i.2))`. -/ +def data (x : X → Bool) (g : G) (r : R) (i : Row R S P) : Bool := + (B.move (Sum.elim x id ∘ B.control g) (r, i.1)).elim false + (fun v => Sum.elim x id (B.port g v i.2)) + +variable [Field F] [Fintype G] [Fintype R] + +open Classical in +/-- The product of `B.scalar (Sum.elim x id ∘ B.format i) (B.data x i.1 i.2)` indexed by `i : G +× R`. -/ +def value (x : X → Bool) : F := + ∏ i : G × R, B.scalar (Sum.elim x id ∘ B.format i) (B.data x i.1 i.2) + +open Classical in +private abbrev Stage (G R S P : Type) := (G × R) × Slice R S P + +variable [Fintype S] [Fintype P] [Fintype A] [Fintype D] [Fintype X] + +open Classical in +/-- All slices are checked in one batch. The second batch multiplies the +entries for the resulting rows, with no restriction on the entries. -/ +theorem reassemble {w j u : ℕ} (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) + (hu : 3 ≤ u) (ha : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ u) + (hmove : Fintype.card A + 2 * Fintype.card (Row R S P) < j) + (heval : Fintype.card D + Fintype.card (Row R S P) < j) + (hrows : Fintype.card (G × R) ≤ 2 ^ j) : + WideWeight F u (SortTables F w) B.value (100 * Fintype.card X + 200000 * 2 ^ j * (1 + j)) := by + let T := Slice R S P + let Y := Stage G R S P + have width : Fintype.card T = Fintype.card (Row R S P) := by + simp only [T, Fintype.card_prod]; ring + let copy (x : A ⊕ T → Bool) (v : T) := + (B.move (x ∘ Sum.inl) v.1).elim false (fun i => x (.inr (i, v.2))) + let src (i : G × R) : A ⊕ T → X ⊕ Bool := + Sum.elim (B.control i.1) (fun v => B.port i.1 v.1 (i.2, v.2)) + let f := applyRows copy src (Equiv.refl Y) + have h₁ := transform (F := F) copy src (Equiv.refl Y) hj hj' hu ha + (by rw [Fintype.card_sum, width]; omega) hrows + let k (x : D ⊕ Row R S P → Bool) := B.scalar (x ∘ Sum.inl) (x ∘ Sum.inr) + let read (i : G × R) : D ⊕ Row R S P → (X ⊕ Y) ⊕ Bool := + Sum.elim (fun v => Sum.map Sum.inl id (B.format i v)) + (fun v => .inl (.inr ((i.1, v.2.1), (i.2, v.1), v.2.2))) + have h₂ := dictionary hj hj' hu ha (by rw [Fintype.card_sum]; exact heval) hrows k read + have H := bind hu h₁ h₂ + have eqn (x : X → Bool) : + (∏ i, k (Sum.elim (Sum.elim x (f x)) id ∘ read i)) = B.value x := by + apply Finset.prod_congr rfl + intro i _ + unfold k + apply congrArg₂ B.scalar + · funext v + simp only [Function.comp_apply, read, Sum.elim_inl] + cases B.format i v <;> rfl + · rfl + have bound : Fintype.card Y ≤ 2 ^ j * j := by + change Fintype.card ((G × R) × T) ≤ _ + rw [Fintype.card_prod, width] + exact Nat.mul_le_mul hrows (by omega) + rw [← funext eqn] + intro a i + obtain ⟨v, hv, hw⟩ := H a i + refine ⟨v, ?_, hw⟩ + rw [Fintype.card_sum] at hv + change v ≤ 8 * (Fintype.card X + Fintype.card Y) + 9 * ( + (4 * (Fintype.card X + Fintype.card Y) + 11000 * 2 ^ j * (1 + j)) + + (4 * (Fintype.card X + Fintype.card Y) + 11000 * 2 ^ j * (1 + j))) at hv + have arithmetic (z x y p j : ℕ) (hb : y ≤ p * j) + (ht : z ≤ 8 * (x + y) + 9 * ((4 * (x + y) + 11000 * p * (1 + j)) + (4 * (x + y) + + 11000 * p * (1 + j)))) : + z ≤ 100 * x + 200000 * p * (1 + j) := by linarith + exact arithmetic _ _ _ _ _ bound hv + +end Bins +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Descriptions of packed table rows + +A bin stores a one-hot map from table sockets to port sockets. A row +stores the presence bit, label and argument positions of each occurrence +there. These descriptions contain no payload bits. An unused argument +is read as zero, and an arity-zero occurrence still contributes its entry. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +open Classical in +/-- Indexes the socket by the coordinates of `Fin (2 * v) × Fin (2 * u)`. -/ +abbrev Socket (v u : ℕ) := Fin (2 * v) × Fin (2 * u) +open Classical in +/-- Indexes the route by the coordinates of `Socket v u × Socket v u`. -/ +abbrev Route (v u : ℕ) := Socket v u × Socket v u +open Classical in +/-- Indexes the tag by the coordinates of `Fin m × (Unit ⊕ Fin ℓ ⊕ Fin u × Fin (2 * u))`. -/ +abbrev Tag (m ℓ u : ℕ) := Fin m × (Unit ⊕ Fin ℓ ⊕ Fin u × Fin (2 * u)) + +open Classical in +theorem width_route (v u : ℕ) : Fintype.card (Route v u) = (4 * v * u) ^ 2 := by + simp only [Route, Socket, Fintype.card_prod, Fintype.card_fin] + ring + +open Classical in +theorem width_tag (m ℓ u : ℕ) : Fintype.card (Tag m ℓ u) = m * (1 + ℓ + 2 * u ^ 2) := by + simp only [Tag, Fintype.card_sum, Fintype.card_prod, Fintype.card_unit, Fintype.card_fin] + ring + +variable {H m d u v K ℓ : ℕ} {l : Inventory H m d} {F P X : Type} + +open Classical in +/-- The condition `∀ i j, Blocks (l i j) ↪ Fin u` on the specified data. -/ +abbrev Index (l : Inventory H m d) (u : ℕ) := ∀ i j, Blocks (l i j) ↪ Fin u +open Classical in +/-- The indexing data represented by `Fin H → Fin m → Fin ℓ → Bool`. -/ +abbrev Label (H m ℓ : ℕ) := Fin H → Fin m → Fin ℓ → Bool + +open Classical in +/-- Evaluates `(order (l i j)).toEmbedding.trans (Fin.castLEEmb (ha i j))` at the input `i j`. -/ +def naturalSlot (ha : ∀ i j, arity (l i) j ≤ u) : Index l u := + fun i j => (order (l i j)).toEmbedding.trans (Fin.castLEEmb (ha i j)) + +open Classical in +theorem naturalSlot_val (ha : ∀ i j, arity (l i) j ≤ u) (i j k) (r : Fin (l i j k)) : + (naturalSlot ha i j ⟨k, r⟩).val = start (l i j) k + r.val := rfl + +open Classical in +/-- The quantity computed by `Piece (Fin (2 * v)) P`. -/ +abbrev Payload (v : ℕ) (P : Type) := Piece (Fin (2 * v)) P +open Classical in +/-- Indexes the entry by the coordinates of `(Fin ℓ → Bool) → (Fin u × Payload v P → Bool) → F`. -/ +abbrev Entry (F P : Type) (ℓ u v : ℕ) := (Fin ℓ → Bool) → (Fin u × Payload v P → Bool) → F + +open Classical in +/-- Tests whether `∃ i, L.tableSlots i = ((g, j.1.1), j.1.2) ∧ L.portSlots i = ((g, j.2.1), +j.2.2)` holds. -/ +def Layout.moves (L : Layout l u v K) (g : Fin K) (j : Route v u) : Bool := + decide (∃ i, L.tableSlots i = ((g, j.1.1), j.1.2) ∧ L.portSlots i = ((g, j.2.1), j.2.2)) + +open Classical in +/-- In the case `(j, .inl _)`, this construction gives `decide (∃ i, L.tableLoc i j = r)`. -/ +def Layout.format (L : Layout l u v K) (ix : Index l u) (f : Label H m ℓ) + (r : Address v K) : Tag m ℓ u → Bool + | (j, .inl _) => decide (∃ i, L.tableLoc i j = r) + | (j, .inr (.inl k)) => decide (∃ i, L.tableLoc i j = r ∧ f i j k = true) + | (j, .inr (.inr (k, b))) => + decide (∃ i t, L.tableLoc i j = r ∧ ix i j t = k ∧ (L.tableSlots ⟨i, j, t⟩).2 = b) + +open Classical in +/-- Returns `some h.choose` when `h : ∃ j, y (i, j) = true` holds, and `none` otherwise. -/ +def move (y : Route v u → Bool) (i : Socket v u) : Option (Socket v u) := + if h : ∃ j, y (i, j) = true then some h.choose else none + +open Classical in +/-- Tests whether `∃ i, c (j, .inr (.inr (t.1, i))) = true ∧ x (i, t.2) = true` holds. -/ +def args (c : Tag m ℓ u → Bool) (x : Fin (2 * u) × Payload v P → Bool) (j : Fin m) + (t : Fin u × Payload v P) := + decide (∃ i, c (j, .inr (.inr (t.1, i))) = true ∧ x (i, t.2) = true) + +open Classical in +/-- The value specified by `∏ j, if c (j, .inl ()) then k (fun i => c (j, .inr (.inl i))) (args +c x j) else 1`. -/ +def scalar [Field F] (k : Entry F P ℓ u v) (c : Tag m ℓ u → Bool) + (x : Fin (2 * u) × Payload v P → Bool) : F := + ∏ j, if c (j, .inl ()) then k (fun i => c (j, .inr (.inl i))) (args c x j) else 1 + +open Classical in +/-- Uses `⟨move, scalar k, control, format, port⟩` as the representation. -/ +def packTables [Field F] (k : Entry F P ℓ u v) + (control : Fin K → Route v u → X ⊕ Bool) (format : Address v K → Tag m ℓ u → X ⊕ Bool) + (port : Fin K → Socket v u → Payload v P → X ⊕ Bool) : + Bins F (Fin K) (Fin (2 * v)) (Fin (2 * u)) P (Route v u) (Tag m ℓ u) X := + ⟨move, scalar k, control, format, port⟩ + +open Classical in +/-- Reindex a tuple of active slot payloads; fill the other entries with zero. -/ +def padded (ix : Index l u) (x : Endpoints l → Payload v P → Bool) (i : Fin H) (j : Fin m) + (t : Fin u × Payload v P) := + decide (∃ a, ix i j a = t.1 ∧ x ⟨i, j, a⟩ t.2 = true) + +open Classical in +theorem padded_at (ix : Index l u) (x : Endpoints l → Payload v P → Bool) (i j a t) : + padded ix x i j (ix i j a, t) = x ⟨i, j, a⟩ t := by + simp [padded, (ix i j).injective.eq_iff] + +open Classical in +theorem padded_other (ix : Index l u) (x : Endpoints l → Payload v P → Bool) + (i j a t) (ha : a ∉ Set.range (ix i j)) : padded ix x i j (a, t) = false := by + have hh (b) : ix i j b ≠ a := fun h => ha ⟨b, h⟩ + simp [padded, hh] + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def readPort (port : Fin K → Socket v u → Payload v P → X ⊕ Bool) (x : X → Bool) + (i : Address v K × Fin (2 * u)) (t : Payload v P) := + Sum.elim x id (port i.1.1 (i.1.2, i.2) t) + +variable (L : Layout l u v K) + +open Classical in +private theorem selected (i : Endpoints l) : + let r := L.tableSlots i + let p := L.portSlots i + move (L.moves r.1.1) (r.1.2, r.2) = some (p.1.2, p.2) := by + let r := L.tableSlots i + let p := L.portSlots i + have eq (j : Socket v u) : L.moves r.1.1 ((r.1.2, r.2), j) = true ↔ j = (p.1.2, p.2) := by + simp only [Layout.moves, decide_eq_true_eq] + change (∃ x, L.tableSlots x = L.tableSlots i ∧ L.portSlots x = ((r.1.1, j.1), j.2)) ↔ _ + simp only [L.tableSlots.injective.eq_iff, exists_eq_left] + rw [show r.1.1 = p.1.1 from L.bin_eq i] + simp [p, Prod.ext_iff, eq_comm] + have h : ∃ j, L.moves r.1.1 ((r.1.2, r.2), j) = true := ⟨_, (eq _).mpr rfl⟩ + change move (L.moves r.1.1) (r.1.2, r.2) = some _ + rw [move, dite_eq_left h, (eq _).mp h.choose_spec] + +open Classical in +private theorem format_key (ix : Index l u) (f : Label H m ℓ) (i : Fin H) (j : Fin m) : + (fun t => L.format ix f (L.tableLoc i j) (j, .inr (.inl t))) = f i j := by + have eq (a) : L.tableLoc a j = L.tableLoc i j ↔ a = i := + ⟨L.separate _ _ _ _, fun h => by rw [h]⟩ + funext t + simp [Layout.format, eq] + +open Classical in +private theorem format_args (ix : Index l u) (f : Label H m ℓ) (i : Fin H) (j : Fin m) + (row : Fin (2 * u) × Payload v P → Bool) (y : Endpoints l → Payload v P → Bool) + (hy : ∀ k t, row ((L.tableSlots ⟨i, j, k⟩).2, t) = y ⟨i, j, k⟩ t) : + args (L.format ix f (L.tableLoc i j)) row j = padded ix y i j := by + funext ⟨q, t⟩ + apply Bool.eq_iff_iff.mpr + simp only [args, Layout.format, padded, decide_eq_true_eq] + constructor + · rintro ⟨a, ⟨i', k, he, hk, rfl⟩, hb⟩ + have := L.separate _ _ _ _ he + subst i' + exact ⟨k, hk, (hy k t).symm.trans hb⟩ + · rintro ⟨k, hk, hb⟩ + exact ⟨_, ⟨i, k, rfl, hk, rfl⟩, (hy k t).trans hb⟩ + +variable [Field F] {k : Entry F P ℓ u v} + {control : Fin K → Route v u → X ⊕ Bool} {format : Address v K → Tag m ℓ u → X ⊕ Bool} + {port : Fin K → Socket v u → Payload v P → X ⊕ Bool} + +open Classical in +private theorem data_eq (x : X → Bool) (hm : ∀ g, Sum.elim x id ∘ control g = L.moves g) + (s : Endpoints l) (t : Payload v P) : + (packTables k control format port).data x (L.tableSlots s).1.1 (L.tableSlots s).1.2 + ((L.tableSlots s).2, t) = readPort port x (L.portSlots s) t := by + simp only [Bins.data, packTables, hm] + rw [selected L s, L.bin_eq] + rfl + +open Classical in +theorem packed_value (ix : Index l u) (f : Label H m ℓ) (x : X → Bool) + (hm : ∀ g, Sum.elim x id ∘ control g = L.moves g) + (hf : ∀ r, Sum.elim x id ∘ format r = L.format ix f r) : + (packTables k control format port).value x = + ∏ i, ∏ j, k (f i j) (padded ix (readPort port x ∘ L.portSlots) i j) := by + let B := packTables k control format port + let entry (r : Address v K) (j : Fin m) := + let c := L.format ix f r + if c (j, .inl ()) then k (fun i => c (j, .inr (.inl i))) (args c (B.data x r.1 r.2) j) else 1 + have eq : B.value x = ∏ r, ∏ j, entry r j := by + unfold Bins.value + apply Finset.prod_congr rfl + intro r _ + change scalar k (Sum.elim x id ∘ format r) _ = _ + rw [hf] + rfl + change B.value x = _ + rw [eq, Finset.prod_comm] + conv_rhs => rw [Finset.prod_comm] + refine Finset.prod_congr rfl fun j _ => ?_ + let e : Fin H ↪ Address v K := ⟨fun i => L.tableLoc i j, fun _ _ => L.separate _ _ _ _⟩ + have absent (r : Address v K) (hr : r ∉ Finset.univ.map e) : entry r j = 1 := by + have he : ¬∃ i, L.tableLoc i j = r := fun ⟨i, hi⟩ => hr (Finset.mem_map.mpr ⟨i, by simp, hi⟩) + simp [entry, Layout.format, he] + rw [← Finset.prod_subset (Finset.subset_univ _) (fun r _ h => absent r h), Finset.prod_map] + refine Finset.prod_congr rfl fun i _ => ?_ + have live : L.format ix f (L.tableLoc i j) (j, .inl ()) = true := decide_eq_true ⟨i, rfl⟩ + change entry (L.tableLoc i j) j = _ + simp only [entry, live, ite_true, format_key] + apply congrArg + apply format_args L + intro q t + have he := data_eq (k := k) (format := format) (port := port) L x hm ⟨i, j, q⟩ t + rw [L.tuple] at he + exact he + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- +# Ordered spans as bundles + +All spans at an occurrence split into pieces of a common width. A +numbering of those pieces depends only on the short pattern label. +It is independent of the rest of the host and of the row allocation. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Assembly Coloring PackRows + +variable {F : Type} {d k e u v p : ℕ} + +namespace Parts +variable (A : Pattern F d k e) (z : ℕ) + +open Classical in +/-- Indexes the span by the coordinates of `B k × B e`. -/ +abbrev Span := B k × B e +open Classical in +/-- Indexes the pin by the coordinates of `Σ i : Span (k := k) (e := e), Fin (A.width i.1 i.2)`. -/ +abbrev Pin := Σ i : Span (k := k) (e := e), Fin (A.width i.1 i.2) +open Classical in +/-- Indexes the unit by the coordinates of `Σ i : Span (k := k) (e := e), Fin (A.width i.1 i.2 / +z)`. -/ +abbrev Unit := Σ i : Span (k := k) (e := e), Fin (A.width i.1 i.2 / z) + +open Classical in +/-- The condition `∀ i j, z ∣ A.width i j` on the specified data. -/ +def Uniform : Prop := ∀ i j, z ∣ A.width i j + +open Classical in +/-- Reindexes `Unit A z × Fin z` and `Pin A` by an equivalence. -/ +def join (ha : Uniform A z) : Unit A z × Fin z ≃ Pin A := + (Equiv.sigmaProdDistrib _ _).trans (Equiv.sigmaCongrRight fun i => + finProdFinEquiv.trans (finCongr (Nat.div_mul_cancel (ha i.1 i.2)))) + +open Classical in +/-- Embeds `Unit A z` into `Fin u`. -/ +def number (ha : Fintype.card (Unit A z) ≤ u) : Unit A z ↪ Fin u := + (Fintype.equivFin _).toEmbedding.trans (Fin.castLEEmb ha) + +open Classical in +/-- One label describes all stations at an occurrence. -/ +def value [Field F] (data : Pin A → Bool) : F := + ∏ i : B k, A.value i (fun j t => data ⟨(i, j), t⟩) + +end Parts + +variable (S : Scheme F) (r : S.format.obj) + +open Classical in +/-- Computes the pattern by the application `S.decode ((r i).2 j)`. -/ +abbrev pattern (i : B S.m) (j : B S.h) := S.decode ((r i).2 j) +open Classical in +/-- Indexes the units by the coordinates of `Σ i : B S.m, Σ j : B S.h, Parts.Unit (pattern S r i +j) z`. -/ +abbrev units (z : ℕ) := Σ i : B S.m, Σ j : B S.h, Parts.Unit (pattern S r i j) z + +open Classical in +/-- Reindexes `S.Pin r` and `(Σ i : B S.m, Σ j : B S.h, Parts.Pin (pattern S r i j)) where toFun +x` by an equivalence. -/ +def fields : S.Pin r ≃ (Σ i : B S.m, Σ j : B S.h, Parts.Pin (pattern S r i j)) where + toFun x := ⟨x.1.1.1, x.1.1.2.1, (x.1.1.2.2, x.1.2), x.2⟩ + invFun x := ⟨((x.1, x.2.1, x.2.2.1.1), x.2.2.1.2), x.2.2.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +open Classical in +/-- Reindexes `units S r z × Fin z` and `S.Pin r` by an equivalence. -/ +def join (z : ℕ) (h : ∀ i j, Parts.Uniform (pattern S r i j) z) : + units S r z × Fin z ≃ S.Pin r := + (Equiv.sigmaProdDistrib _ _).trans <| + (Equiv.sigmaCongrRight fun i => (Equiv.sigmaProdDistrib _ _).trans + (Equiv.sigmaCongrRight fun j => Parts.join _ _ (h i j))).trans (fields S r).symm + +open Classical in +theorem join_val (z : ℕ) (h : ∀ i j, Parts.Uniform (pattern S r i j) z) + (x : units S r z) (a : Fin z) : + let t := join S r z h (x, a) + t.1 = ((x.1, x.2.1, x.2.2.1.1), x.2.2.1.2) ∧ t.2.val = a.val + z * x.2.2.2.val := + ⟨rfl, rfl⟩ + +open Classical in +/-- The quantity computed by `2 * v * p`. -/ +abbrev bundleSize (v p : ℕ) := 2 * v * p + +open Classical in +/-- The data for the pieces construction, including `uniform`, `locate`. -/ +structure Pieces (l : Inventory (2 ^ S.m) (2 ^ S.h) d) (v p : ℕ) where + uniform : ∀ i j, Parts.Uniform (pattern S r i j) (bundleSize v p) + /-- Reindexes the data using `∀ i j, Parts.Unit (pattern S r i j) (bundleSize v p) ≃ Blocks (l + i j)`. -/ + locate : ∀ i j, Parts.Unit (pattern S r i j) (bundleSize v p) ≃ Blocks (l i j) + +open Classical in +/-- Computes the keys by the application `Fintype.equivOfCardEq (by simp)`. -/ +def keys (ℓ : ℕ) : B ℓ ≃ (Fin ℓ → Bool) := Fintype.equivOfCardEq (by simp) + +open Classical in +/-- Evaluates `keys _ ((r i).2 j)` at the input `i j`. -/ +def labels : Label (2 ^ S.m) (2 ^ S.h) S.ℓ := fun i j => keys _ ((r i).2 j) + +open Classical in +/-- The entry at of type `F`, constructed using `bundleSize v p`. -/ +def entryAt [Field F] (u v p : ℕ) (A : Pattern F d k e) (x : Fin u × Payload v (Fin p) → Bool) : F + := + let z := bundleSize v p + if h : Parts.Uniform A z ∧ Fintype.card (Parts.Unit A z) ≤ u then + Parts.value A (fun k => + let t := (Parts.join A z h.1).symm k + x (Parts.number A z h.2 t.1, finProdFinEquiv.symm t.2)) + else 0 + +open Classical in +/-- Evaluates `entryAt u v p (S.decode ((keys _).symm code))` at the input `code`. -/ +def entry [Field F] (u v p : ℕ) : Entry F (Fin p) S.ℓ u v := fun code => + entryAt u v p (S.decode ((keys _).symm code)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Local description of a bin, independent of host and bin identifiers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +open scoped Classical in +/-- The data for the descriptor construction, including `len`, `label`, `slot`. -/ +structure Descriptor (m d ℓ : ℕ) where + /-- The `Descriptor` component of type `Lengths m d`. -/ + len : Lengths m d + /-- The label at each coordinate of type `Fin m → Fin ℓ → Bool`. -/ + label : Fin m → Fin ℓ → Bool + /-- The `Descriptor` component of type `Fin m → Fin d → ℕ → ℕ`. -/ + slot : Fin m → Fin d → ℕ → ℕ + +open scoped Classical in +/-- Indexes the bin key by the coordinates of `Fin v × Option D`. -/ +abbrev BinKey (v : ℕ) (D : Type) := Fin v × Option D +open scoped Classical in +/-- Indexes the bin out by the coordinates of `Route v u ⊕ (Fin (2 * v) × (Tag m ℓ u ⊕ Fin (2 * +v) ⊕ Z))`. -/ +abbrev BinOut (v u m ℓ : ℕ) (Z : Type) := + Route v u ⊕ (Fin (2 * v) × (Tag m ℓ u ⊕ Fin (2 * v) ⊕ Z)) + +variable {D Z : Type} {H m d ℓ v : ℕ} + +namespace Descriptor + +variable (u : ℕ) (l : Lengths m d) + +open scoped Classical in +/-- The quantity computed by `b.val + start (arity l) j / u`. -/ +def tableRow (b : Fin v) (j : Fin m) := b.val + start (arity l) j / u +open scoped Classical in +/-- The quantity computed by `start (arity l) j % u + (start (l j) p + r)`. -/ +def tableCol (j : Fin m) (p : Fin d) (r : ℕ) := start (arity l) j % u + (start (l j) p + r) +open scoped Classical in +/-- The quantity computed by `b.val + (tables l u + (start (ports l u) p + r))`. -/ +def channel (b : Fin v) (p : Fin d) (r : ℕ) := b.val + (tables l u + (start (ports l u) p + r)) + +open scoped Classical in +/-- The routed of type `Prop`, constructed using `start (port l p) j + r`. -/ +def routed (b : Fin v) (t : Route v u) : Prop := + ∃ j p r, r < l j p ∧ tableRow u l b j = t.1.1.val ∧ tableCol u l j p r = t.1.2.val ∧ + let k := start (port l p) j + r + channel u l b p (k / (2 * u)) = t.2.1.val ∧ k % (2 * u) = t.2.2.val + +open scoped Classical in +/-- In the case `.inl _`, this construction gives `True`. -/ +def tagged (a : Descriptor m d ℓ) (b : Fin v) (k : Fin (2 * v)) (t : Tag m ℓ u) : Prop := + tableRow u a.len b t.1 = k.val ∧ + match t.2 with + | .inl _ => True + | .inr (.inl i) => a.label t.1 i = true + | .inr (.inr (i, x)) => ∃ p r, r < a.len t.1 p ∧ a.slot t.1 p r = i.val ∧ + tableCol u a.len t.1 p r = x.val + +open scoped Classical in +/-- The condition `∃ p t, t.val < ports l u p ∧ channel u l b p t.val = k.val ∧ P p t` on the +specified data. -/ +def atPort (b : Fin v) (k : Fin (2 * v)) (P : Fin d → Fin v → Prop) : Prop := + ∃ p t, t.val < ports l u p ∧ channel u l b p t.val = k.val ∧ P p t + +end Descriptor + +open Descriptor + +open scoped Classical in +/-- In the case `.inl t`, this construction gives `routed u (code x).len b t`. -/ +def binQuery (u : ℕ) (code : (D → Bool) → Descriptor m d ℓ) + (user : (D → Bool) → Fin d → Fin v → Z → Bool) (b : Fin v) (x : D → Bool) : + BinOut v u m ℓ Z → Prop + | .inl t => routed u (code x).len b t + | .inr (k, .inl t) => tagged u (code x) b k t + | .inr (k, .inr (.inl i)) => atPort u (code x).len b k (fun p _ => i.val = b.val + p.val) + | .inr (k, .inr (.inr z)) => atPort u (code x).len b k (fun p t => user x p t z = true) + +open scoped Classical in +/-- The query only inspects descriptors with their validity flag set. -/ +def binFunction (u : ℕ) (code : (D → Bool) → Descriptor m d ℓ) + (user : (D → Bool) → Fin d → Fin v → Z → Bool) (input : BinKey v D → Bool) + (out : BinOut v u m ℓ Z) : Bool := + decide (∃ b, input (b, none) = true ∧ binQuery u code user b (fun k => input (b, some k)) out) + +open scoped Classical in +/-- The data for the bin data construction, including `live`, `bits`, `len`, `label`, `slot`. -/ +structure BinData (code : (D → Bool) → Descriptor m d ℓ) (l : Inventory H m d) (u v K : ℕ) + (hv : 0 < v) (hs : ∀ i, size (l i) u ≤ v) (hk : bins l u v ≤ K) + (ix : Index l u) (f : Label H m ℓ) (src : Fin H → D → Bool) (inp : Fin K → BinKey v D → Bool) : + Prop where + live : ∀ b j, inp b (j, none) = true ↔ (b, j) ∈ Set.range (anchor l u v K hv hs hk) + bits : ∀ i k, inp (anchor l u v K hv hs hk i).1 ((anchor l u v K hv hs hk i).2, some k) = src i k + len : ∀ i, (code (src i)).len = l i + label : ∀ i, (code (src i)).label = f i + slot : ∀ i j p (k : Fin (l i j p)), (code (src i)).slot j p k.val = (ix i j ⟨p, k⟩).val + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- # Generating the two socket orders and the local controls from bin keys -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +open Descriptor + +variable {H m d ℓ u v K : ℕ} {D Z : Type} + {code : (D → Bool) → Descriptor m d ℓ} {l : Inventory H m d} + {hv : 0 < v} {hs : ∀ i, size (l i) u ≤ v} {hk : bins l u v ≤ K} + {ix : Index l u} {f : Label H m ℓ} {src : Fin H → D → Bool} {inp : Fin K → BinKey v D → Bool} + (data : BinData code l u v K hv hs hk ix f src inp) + (flags : (D → Bool) → Fin d → Fin v → Z → Bool) (hu : 0 < u) (ha : ∀ i j, arity (l i) j ≤ u) + +local notation "anc" => anchor l u v K hv hs hk +local notation "packed" => make l u v K hu hv ha hs hk + +include data in +open scoped Classical in +private theorem query (g : Fin K) (t : BinOut v u m ℓ Z) : + binFunction u code flags (inp g) t = true ↔ + ∃ i, (anc i).1 = g ∧ binQuery u code flags (anc i).2 (src i) t := by + simp only [binFunction, decide_eq_true_eq, data.live] + constructor + · rintro ⟨b, ⟨i, hi⟩, h⟩ + obtain ⟨rfl, rfl⟩ := Prod.ext_iff.mp hi + exact ⟨i, rfl, by simpa only [data.bits] using h⟩ + · rintro ⟨i, rfl, h⟩ + exact ⟨(anc i).2, ⟨i, rfl⟩, by simpa only [data.bits] using h⟩ + +open scoped Classical in +private theorem table_eq (i : Fin H) (j : Fin m) (r : Address v K) : + (packed).tableLoc i j = r ↔ (anc i).1 = r.1 ∧ tableRow u (l i) (anc i).2 j = r.2.val := by + simp only [Prod.ext_iff, Fin.ext_iff] + rfl + +open scoped Classical in +private theorem port_eq (i : Fin H) (p : Fin d) (j : Fin (ports (l i) u p)) (r : Address v K) : + (packed).portLoc ⟨i, p, j⟩ = r ↔ + (anc i).1 = r.1 ∧ channel u (l i) (anc i).2 p j.val = r.2.val := by + simp only [Prod.ext_iff, Fin.ext_iff] + rfl + +include data in +open scoped Classical in +theorem BinData.moves (g : Fin K) (t : Route v u) : + binFunction u code flags (inp g) (.inl t) = (packed).moves g t := by + apply Bool.eq_iff_iff.mpr + rw [query data] + simp only [binQuery, data.len, routed, Layout.moves, decide_eq_true_eq] + constructor + · rintro ⟨i, hi, j, p, r, hr, h₁, h₂, h₃, h₄⟩ + let x : Endpoints l := ⟨i, j, p, ⟨r, hr⟩⟩ + refine ⟨x, Prod.ext ?_ (Fin.ext h₂), Prod.ext ?_ (Fin.ext h₄)⟩ + · rw [Layout.tuple] + exact (table_eq hu ha i j _).mpr ⟨hi, h₁⟩ + · rw [Layout.locate] + exact (port_eq hu ha i p _ _).mpr ⟨hi, h₃⟩ + · rintro ⟨⟨i, j, p, r⟩, h₁, h₂⟩ + have ht := congrArg Prod.fst h₁ + have hp := congrArg Prod.fst h₂ + rw [Layout.tuple] at ht + rw [Layout.locate] at hp + obtain ⟨hi, ht⟩ := (table_eq hu ha _ _ _).mp ht + refine ⟨i, hi, j, p, r.val, r.isLt, ht, congrArg (fun x => x.2.val) h₁, + (port_eq hu ha i p _ _).mp hp |>.2, congrArg (fun x => x.2.val) h₂⟩ + +include data in +open scoped Classical in +theorem BinData.format (r : Address v K) (t : Tag m ℓ u) : + binFunction u code flags (inp r.1) (.inr (r.2, .inl t)) = (packed).format ix f r t := by + apply Bool.eq_iff_iff.mpr + rw [query data] + rcases t with ⟨j, _ | b | ⟨k, z⟩⟩ <;> + simp only [binQuery, tagged, data.len, data.label, Layout.format, decide_eq_true_eq, and_true] + · simp only [table_eq hu ha] + · simp only [table_eq hu ha, and_assoc] + · constructor + · rintro ⟨i, hi, hr, p, n, hn, hk', hz⟩ + let a : Fin (l i j p) := ⟨n, hn⟩ + refine ⟨i, ⟨p, a⟩, (table_eq hu ha i j r).mpr ⟨hi, hr⟩, ?_, Fin.ext hz⟩ + exact Fin.ext ((data.slot i j p a).symm.trans hk') + · rintro ⟨i, ⟨p, n⟩, he, hk', hz⟩ + obtain ⟨hi, hr⟩ := (table_eq hu ha i j r).mp he + exact ⟨i, hi, hr, p, n.val, n.isLt, (data.slot i j p n).trans (congrArg Fin.val hk'), + congrArg Fin.val hz⟩ + +open scoped Classical in +private theorem port_spec (r : Address v K) (P : Fin H → Fin d → Fin v → Prop) : + (∃ i, (anc i).1 = r.1 ∧ atPort u (l i) (anc i).2 r.2 (P i)) ↔ + ∃ p : PortRows l u, (packed).portLoc p = r ∧ + ∃ k : Fin v, k.val = p.2.2.val ∧ P p.1 p.2.1 k := by + constructor + · rintro ⟨i, hi, p, k, hk', he, hp⟩ + exact ⟨⟨i, p, ⟨k.val, hk'⟩⟩, (port_eq hu ha i p _ r).mpr ⟨hi, he⟩, k, rfl, hp⟩ + · rintro ⟨⟨i, p, j⟩, he, k, hk', hp⟩ + obtain ⟨hi, hr⟩ := (port_eq hu ha i p j r).mp he + exact ⟨i, hi, p, k, hk'.trans_lt j.isLt, hk' ▸ hr, hp⟩ + +open scoped Classical in +theorem ports_le (hs : ∀ i, size (l i) u ≤ v) (i : Fin H) (p : Fin d) : + ports (l i) u p ≤ v := by + have h := Finset.single_le_sum (f := ports (l i) u) (fun j _ => Nat.zero_le _) (Finset.mem_univ p) + have h' := hs i + unfold size at h' + omega + +include data in +open scoped Classical in +theorem BinData.choose (r : Address v K) (t : Fin (2 * v)) : + binFunction u code flags (inp r.1) (.inr (r.2, .inr (.inl t))) = true ↔ + ∃ p : PortRows l u, (packed).portLoc p = r ∧ + t = (portAnchor l u v K hv hs hk (p.1, p.2.1)).2 := by + rw [query data] + simp only [binQuery, data.len] + rw [port_spec hu ha r (fun i p _ => t.val = (anc i).2.val + p.val)] + constructor + · rintro ⟨p, hp, _, _, he⟩ + exact ⟨p, hp, Fin.ext he⟩ + · rintro ⟨p, hp, he⟩ + exact ⟨p, hp, Fin.castLE (ports_le hs p.1 p.2.1) p.2.2, rfl, congrArg Fin.val he⟩ + +include data in +open scoped Classical in +theorem BinData.user (r : Address v K) (z : Z) : + binFunction u code flags (inp r.1) (.inr (r.2, .inr (.inr z))) = true ↔ + ∃ p : PortRows l u, (packed).portLoc p = r ∧ + ∃ k : Fin v, k.val = p.2.2.val ∧ flags (src p.1) p.2.1 k z = true := by + rw [query data] + simp only [binQuery, data.len] + exact port_spec hu ha r (fun i p k => flags (src i) p k z = true) + +open scoped Classical in +/-- One dictionary handles every physical bin. No host or bin number +is included in its key. -/ +theorem binTransform (F : Type) [Field F] {X Y : Type} [Fintype X] [Fintype Y] + [Fintype Z] [Fintype D] {w j cap : ℕ} (code : (D → Bool) → Descriptor m d ℓ) + (flags : (D → Bool) → Fin d → Fin v → Z → Bool) + (input : Fin K → BinKey v D → X ⊕ Bool) (output : Fin K × BinOut v u m ℓ Z ≃ Y) + (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (hc : 3 ≤ cap) (ha : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ cap) + (hd : Fintype.card (BinKey v D) + Fintype.card (BinOut v u m ℓ Z) < j) (hk : K ≤ 2 ^ j) : + Transcript.WideWeight F cap (SortTables F w) + (fun x : X ⊕ Y → Bool => if applyRows (binFunction u code flags) input output (x ∘ Sum.inl) = + x ∘ Sum.inr then 1 else 0) (4 * Fintype.card (X ⊕ Y) + 11000 * 2 ^ j * (1 + j)) := + transform _ input output hj hj' hc ha hd (by simpa using hk) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Plan.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Plan.lean new file mode 100644 index 0000000000..2a40495883 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Plan.lean @@ -0,0 +1,880 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Data.Nat.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Pieces +public import Mathlib.Algebra.BigOperators.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary + +/-! +# Dyadic scales for the many-list descent + +The beat count grows like a small fixed multiple of the logarithm of +the tag width. A quadratic exponent in that count is still affordable +for replication, while exponential losses must fit in the width. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Filter + +theorem scales (B J : ℕ) (hB : 0 < B) : + ∀ᶠ w : ℕ in atTop, ∃ j : ℕ, J ≤ j ∧ 1 ≤ j ∧ 2 ^ (B * j) ≤ w ∧ w ≤ 2 ^ (2 * B * j) := by + filter_upwards [eventually_ge_atTop (2 ^ (B * (J + 1)))] with w hw + have hw' : 0 < w := (pow_pos (by decide : 0 < 2) _).trans_le hw + let j := Nat.log 2 w / B + have low : J + 1 ≤ j := (Nat.le_div_iff_mul_le hB).mpr (by + rw [mul_comm] + exact Nat.le_log_of_pow_le (by decide) hw) + have h₁ : B * j ≤ Nat.log 2 w := Nat.mul_div_le _ _ + have h₂ : Nat.log 2 w < (j + 1) * B := (Nat.div_lt_iff_lt_mul hB).mp (Nat.lt_succ_self j) + have h₃ : Nat.log 2 w + 1 ≤ 2 * B * j := by nlinarith + exact ⟨j, by omega, by omega, + (Nat.pow_le_pow_right (by decide) h₁).trans (Nat.pow_log_le_self 2 hw'.ne'), + (Nat.lt_pow_succ_log_self (by decide : 1 < 2) w).le.trans + (Nat.pow_le_pow_right (by decide) h₃)⟩ + +private theorem cube_le {j : ℕ} (hj : 16 ≤ j) : j ^ 3 ≤ 2 ^ j := by + induction j, hj using Nat.le_induction with + | base => norm_num + | succ j hj ih => + calc + _ ≤ 2 * j ^ 3 := by nlinarith [Nat.mul_le_mul_left (j ^ 2) hj] + _ ≤ _ := by rw [pow_succ' 2 j]; gcongr + +theorem replication {κ : ℝ} (hk : 0 < κ) (v : ℕ) : + ∀ᶠ j : ℕ in atTop, ∀ w : ℕ, 2 ^ j ≤ w → + (2 : ℝ) ^ (v * j ^ 2 : ℕ) ≤ ((2 : ℝ) ^ w : ℝ) ^ κ := by + obtain ⟨J, hJ⟩ := exists_nat_gt ((v : ℝ) / κ) + filter_upwards [eventually_ge_atTop 16, eventually_ge_atTop J] with j hj hj' w hw + rw [← Real.rpow_natCast_mul (by norm_num), ← Real.rpow_natCast] + apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + have h : (v : ℝ) ≤ j * κ := (div_le_iff₀ hk).mp (hJ.le.trans (Nat.cast_le.mpr hj')) + have hpow : (j : ℝ) ^ 3 ≤ w := by exact_mod_cast (cube_le hj).trans hw + push_cast + calc + _ ≤ (j * κ) * (j : ℝ) ^ 2 := by gcongr + _ = (j : ℝ) ^ 3 * κ := by ring + _ ≤ _ := by gcongr + +theorem saving {B j w : ℕ} (hB : 0 < B) (hw : 1 ≤ w) (hu : w ≤ 2 ^ (2 * B * j)) : + (1 / 2 : ℝ) ^ j ≤ (w : ℝ) ^ (-(1 / (2 * B : ℝ))) := by + have hb : 0 < (B : ℝ) := Nat.cast_pos.mpr hB + have hp : (w : ℝ) ^ (1 / (2 * B : ℝ)) ≤ (2 : ℝ) ^ j := calc + _ ≤ ((2 : ℝ) ^ (2 * B * j : ℕ) : ℝ) ^ (1 / (2 * B : ℝ)) := by gcongr; exact_mod_cast hu + _ = _ := by + rw [← Real.rpow_natCast_mul (by norm_num)] + have : ((2 * B * j : ℕ) : ℝ) * (1 / (2 * B : ℝ)) = j := by push_cast; field_simp + rw [this, Real.rpow_natCast] + rw [one_div_pow, Real.rpow_neg (Nat.cast_nonneg _), ← one_div] + exact one_div_le_one_div_of_le (by positivity) hp + +/-- Round the slot width down to a multiple of the bin size. Keeping +half of the available space suffices for a uniform per-bit bound. -/ +theorem fill {q W w : ℕ} (hq : 0 < q) (hW : 0 < W) (hw : 32 * q * W ≤ w) : + ∃ z, 0 < z ∧ W ∣ z ∧ 16 * q * z ≤ w ∧ w ≤ 32 * q * z := by + let b := 16 * q * W + have hb : 0 < b := by unfold b; positivity + have hbig : 2 * b ≤ w := by unfold b; nlinarith only [hw] + let l := w / b + have hl : 2 ≤ l := (Nat.le_div_iff_mul_le hb).mpr hbig + refine ⟨W * l, by positivity, dvd_mul_right _ _, ?_, ?_⟩ + · rw [← mul_assoc]; exact Nat.mul_div_le w b + · have ht : w < (l + 1) * b := (Nat.div_lt_iff_lt_mul hb).mp (Nat.lt_succ_self l) + calc + _ ≤ (l + 1) * b := ht.le + _ ≤ 2 * l * b := Nat.mul_le_mul_right _ (by omega) + _ = _ := by unfold b; ring + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- # Combining the core and exterior port inventories -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +variable {H m d e : ℕ} (l : Inventory H m d) (r : Inventory H m e) + +/-- Evaluates `Fin.append (l i j) (r i j)` at the input `i j`. -/ +def append : Inventory H m (d + e) := fun i j => Fin.append (l i j) (r i j) + +@[simp] theorem append_left (i j k) : append l r i j (Fin.castAdd e k) = l i j k := by + simp [append] + +@[simp] theorem append_right (i j k) : append l r i j (Fin.natAdd d k) = r i j k := by + simp [append] + +@[simp] theorem arity_append (i j) : arity (append l r i) j = arity (l i) j + arity (r i) j := by + simp [arity, Fin.sum_univ_add] + +/-- Embeds `Endpoints l` into `Endpoints l' where toFun x`. -/ +def lift {d' : ℕ} (l' : Inventory H m d') (f : Fin d ↪ Fin d') + (hf : ∀ i j k, l' i j (f k) = l i j k) : Endpoints l ↪ Endpoints l' where + toFun x := ⟨x.1, x.2.1, f x.2.2.1, x.2.2.2.cast (hf _ _ _).symm⟩ + inj' := by + rintro ⟨i, j, k, b⟩ ⟨i', j', k', b'⟩ he + have hi : i = i' := congrArg Sigma.fst he + have hj : j = j' := congrArg (fun x => x.2.1) he + have hk : k = k' := f.injective (congrArg (fun x => x.2.2.1) he) + subst i'; subst j'; subst k' + have hb : b = b' := Fin.ext (congrArg (fun x => x.2.2.2.val) he) + subst b' + rfl + +private theorem rank_lift {d' : ℕ} (l' : Inventory H m d') (f : Fin d ↪ Fin d') + (hf : ∀ i j k, l' i j (f k) = l i j k) (x : Endpoints l) : + rank l' (lift l l' f hf x) = rank l x := by + have he : port (l' x.1) (f x.2.2.1) = port (l x.1) x.2.2.1 := + funext fun k => hf _ k _ + change start (port (l' x.1) (f x.2.2.1)) _ + _ = _ + rw [he] + rfl + +/-- Computes the extend l by the application `lift l _ (Fin.castAddEmb e) (append_left l r)`. -/ +def extendL : Endpoints l ↪ Endpoints (append l r) := + lift l _ (Fin.castAddEmb e) (append_left l r) + +/-- Computes the extend r by the application `lift r _ (Fin.natAddEmb d) (append_right l r)`. -/ +def extendR : Endpoints r ↪ Endpoints (append l r) := + lift r _ (Fin.natAddEmb d) (append_right l r) + +@[simp] theorem rank_extendL (x : Endpoints l) : rank (append l r) (extendL l r x) = rank l x := + rank_lift .. + +@[simp] theorem rank_extendR (x : Endpoints r) : rank (append l r) (extendR l r x) = rank r x := + rank_lift .. + +theorem channels_disjoint (x : Endpoints l) (y : Endpoints r) : + (extendL l r x).2.2.1 ≠ (extendR l r y).2.2.1 := by + intro he + have hx := x.2.2.1.isLt + have hh : x.2.2.1.val = d + y.2.2.1.val := congrArg Fin.val he + omega + +/-- Bundles the indexing function as an equivalence. -/ +noncomputable def combined : Endpoints l ⊕ Endpoints r ≃ Endpoints (append l r) := + Equiv.ofBijective (Sum.elim (extendL l r) (extendR l r)) (by + constructor + · rintro (x|x) (y|y) he + · exact congrArg Sum.inl ((extendL l r).injective he) + · exact (channels_disjoint l r x y (congrArg (fun x => x.2.2.1) he)).elim + · exact (channels_disjoint l r y x (congrArg (fun x => x.2.2.1) he.symm)).elim + · exact congrArg Sum.inr ((extendR l r).injective he) + · rintro ⟨i, j, k, b⟩ + induction k using Fin.addCases with + | left k => exact ⟨.inl ⟨i, j, k, b.cast (append_left ..)⟩, rfl⟩ + | right k => exact ⟨.inr ⟨i, j, k, b.cast (append_right ..)⟩, rfl⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +section +/- +# Ordering internal channels + +An oriented lane identifies its two hosts and its direction. Within a +lane order bundles by block, breaking ties by an edge key. Hence each +end computes the same ordinal in its own lane, including for loops. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +/-- The data for the channels construction, including `host`, `block`, `lane`, `key`, `lanes`. -/ +structure Channels (E : Type) (H m d : ℕ) where + /-- The `Channels` component of type `Bool → E → Fin H`. -/ + host : Bool → E → Fin H + /-- The `Channels` component of type `E → Fin m`. -/ + block : E → Fin m + /-- The `Channels` component of type `Bool → E → Fin d`. -/ + lane : Bool → E → Fin d + /-- The `Channels` component of type `E → ℕ`. -/ + key : E → ℕ + lanes : ∀ i j b c, (host b i = host c j ∧ lane b i = lane c j) ↔ + b = c ∧ host false i = host false j ∧ host true i = host true j + unique : ∀ i j, host false i = host false j → block i = block j → key i = key j → i = j + +namespace Channels + +open Finset +variable {E : Type} [Fintype E] {H m d : ℕ} (A : Channels E H m d) + +/-- The value specified by `(A.host x.2 x.1, A.block x.1, A.lane x.2 x.1)`. -/ +def position (x : E × Bool) := (A.host x.2 x.1, A.block x.1, A.lane x.2 x.1) + +/-- Selects the elements of all indices satisfying `(fun x => A.position x = p)`. -/ +def pool (p : Fin H × Fin m × Fin d) := univ.filter (fun x => A.position x = p) + +/-- Evaluates `(A.pool (a, b, c)).card` at the input `a b c`. -/ +def inventory : Inventory H m d := fun a b c => (A.pool (a, b, c)).card + +/-- The indexed operation `((A.pool (A.position x)).filter (fun y => A.key y.1 < A.key +x.1)).card`. -/ +def prior (x : E × Bool) := + ((A.pool (A.position x)).filter (fun y => A.key y.1 < A.key x.1)).card + +theorem prior_lt (x : E × Bool) : + A.prior x < A.inventory (A.host x.2 x.1) (A.block x.1) (A.lane x.2 x.1) := by + apply card_lt_card + refine (ssubset_iff_of_subset (filter_subset _ _)).mpr ⟨x, ?_, ?_⟩ + · simp [pool] + · simp + +private theorem prior_mono (x y : E × Bool) (he : A.position x = A.position y) + (hl : A.key x.1 < A.key y.1) : A.prior x < A.prior y := by + unfold prior + rw [← he] + apply card_lt_card + refine (ssubset_iff_of_subset ?_).mpr ⟨x, by simp [pool, hl], by simp⟩ + intro i hi + exact mem_filter.mpr ⟨(mem_filter.mp hi).1, (mem_filter.mp hi).2.trans hl⟩ + +/-- Uses `⟨A.host x.2 x.1, A.block x.1, A.lane x.2 x.1, ⟨A.prior x, A.prior_lt x⟩⟩` as the +representation. -/ +def assign (x : E × Bool) : Endpoints A.inventory := + ⟨A.host x.2 x.1, A.block x.1, A.lane x.2 x.1, ⟨A.prior x, A.prior_lt x⟩⟩ + +theorem assign_injective : Function.Injective A.assign := by + intro x y h + have hp : A.position x = A.position y := + congrArg (fun p : Endpoints A.inventory => (p.1, p.2.1, p.2.2.1)) h + have he : A.prior x = A.prior y := congrArg (fun p => p.2.2.2.val) h + have hk : A.key x.1 = A.key y.1 := by + rcases lt_trichotomy (A.key x.1) (A.key y.1) with l | l | l + · exact ((A.prior_mono x y hp l).ne he).elim + · exact l + · exact ((A.prior_mono y x hp.symm l).ne he.symm).elim + obtain ⟨hb, h₁, _⟩ := (A.lanes x.1 y.1 x.2 y.2).mp + ⟨congrArg Prod.fst hp, congrArg (·.2.2) hp⟩ + exact Prod.ext (A.unique _ _ h₁ (congrArg (·.2.1) hp) hk) hb + +theorem card_endpoints : Fintype.card (E × Bool) = Fintype.card (Endpoints A.inventory) + := by + have he := card_eq_sum_card_fiberwise (s := univ) (f := A.position) (fun i _ => mem_univ _) + rw [Fintype.sum_prod_type] at he + simp only [card_univ, Fintype.sum_prod_type] at he + unfold Endpoints Slots Blocks + simp_rw [Fintype.card_sigma, Fintype.card_fin] + exact he + +/-- The equivalence obtained by `Equiv.ofBijective A.assign +((Fintype.bijective_iff_injective_and_card _).mpr ⟨A.assign_injective, A.card_endpoints⟩)`. -/ +noncomputable def point : E × Bool ≃ Endpoints A.inventory := + Equiv.ofBijective A.assign ((Fintype.bijective_iff_injective_and_card _).mpr + ⟨A.assign_injective, A.card_endpoints⟩) + +theorem point_val (i : E) (b : Bool) : A.point (i, b) = + ⟨A.host b i, A.block i, A.lane b i, ⟨A.prior (i, b), A.prior_lt (i, b)⟩⟩ := rfl + +/-- The indexed operation `univ.filter fun j => A.host false j = A.host false i ∧ A.host true j += A.host true i ∧ A.block j = v`. -/ +def family (i : E) (v : Fin m) : Finset E := + univ.filter fun j => A.host false j = A.host false i ∧ A.host true j = A.host true i ∧ A.block j + = v + +private def flag (b : Bool) : E ↪ E × Bool := ⟨fun i => (i, b), fun _ _ h => congrArg Prod.fst h⟩ + +private theorem pool_at (i : E) (b : Bool) (v : Fin m) : + A.pool (A.host b i, v, A.lane b i) = (A.family i v).map (flag b) := by + ext ⟨j, c⟩ + simp only [pool, position, family, mem_filter, mem_univ, true_and, Prod.mk.injEq, mem_map] + constructor + · rintro ⟨hs, hv, hp⟩ + obtain ⟨rfl, he, he'⟩ := (A.lanes _ _ _ _).mp ⟨hs, hp⟩ + exact ⟨j, ⟨he, he', hv⟩, rfl⟩ + · rintro ⟨x, ⟨hs, ht, hv⟩, eq⟩ + obtain ⟨rfl, rfl⟩ := Prod.mk.inj eq + obtain ⟨hs', hp⟩ := (A.lanes x i b b).mpr ⟨rfl, hs, ht⟩ + exact ⟨hs', hv, hp⟩ + +theorem inventory_at (i : E) (b : Bool) (v : Fin m) : + A.inventory (A.host b i) v (A.lane b i) = (A.family i v).card := by + rw [inventory, pool_at, card_map] + +theorem prior_at (i : E) (b : Bool) : + A.prior (i, b) = ((A.family i (A.block i)).filter (fun j => A.key j < A.key i)).card := by + rw [prior, position, pool_at, filter_map, card_map] + rfl + +theorem rank_eq (i : E) (b : Bool) : + rank A.inventory (A.point (i, b)) = rank A.inventory (A.point (i, false)) := by + have he : port (A.inventory (A.host b i)) (A.lane b i) = + port (A.inventory (A.host false i)) (A.lane false i) := by + funext v + simp only [port, inventory_at] + simp only [rank, point_val, he, prior_at] + +variable {u v K d' : ℕ} {r : Inventory H m d'} (L : Layout (append A.inventory r) u v K) + +/-- The value specified by `L.portSlots (extendL A.inventory r (A.point (i, b)))`. -/ +noncomputable def loc (i : E) (b : Bool) := L.portSlots (extendL A.inventory r (A.point (i, b))) + +theorem col_eq (i : E) (b : Bool) : (A.loc L i b).2 = (A.loc L i (!b)).2 := by + apply Fin.ext + unfold loc + rw [L.ordinal, L.ordinal, rank_extendL, rank_extendL, A.rank_eq i b, A.rank_eq i (!b)] + +theorem row_eq (i j : E) (b c : Bool) : + (A.loc L i b).1 = (A.loc L j c).1 ↔ b = c ∧ + A.host false i = A.host false j ∧ A.host true i = A.host true j ∧ + rank A.inventory (A.point (i, false)) / (2 * u) = rank A.inventory (A.point (j, + false)) / (2 * u) := by + unfold loc + rw [L.row_eq, rank_extendL, rank_extendL, A.rank_eq i b, A.rank_eq j c] + change (A.host b i = A.host c j ∧ (Fin.castAddEmb d') (A.lane b i) + = (Fin.castAddEmb d') (A.lane c j)) ∧ _ ↔ _ + rw [(Fin.castAddEmb d').injective.eq_iff, A.lanes, and_assoc, and_assoc] + +end Channels +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- # Internal channel inventories from a posted core diagram -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent + +namespace BatchDescent.PackRows.Channels + +variable {E : Type} [Fintype E] {H m d : ℕ} (A : Channels E H m d) + +theorem total_eq : ∑ i, total (A.inventory i) = 2 * Fintype.card E := by + have he := Fintype.card_congr A.point + unfold Endpoints Slots Blocks at he + simp_rw [Fintype.card_sigma, Fintype.card_fin] at he + rw [Fintype.card_prod, Fintype.card_bool, mul_comm] at he + exact he.symm + +theorem arity_eq (i : Fin H) (j : Fin m) : + arity (A.inventory i) j = + ∑ e, ((if A.host false e = i ∧ A.block e = j then 1 else 0) + + (if A.host true e = i ∧ A.block e = j then 1 else 0)) := by + let s := Finset.univ.filter (fun t : E × Bool => A.host t.2 t.1 = i ∧ A.block t.1 = j) + have h (k : Fin d) : A.inventory i j k = (s.filter (fun t => A.lane t.2 t.1 = k)).card := by + simp only [inventory, pool, position, s, Finset.filter_filter, Prod.mk.injEq, and_assoc] + unfold arity + simp_rw [h] + rw [← Finset.card_eq_sum_card_fiberwise (fun x _ => Finset.mem_univ _)] + unfold s + rw [Finset.card_filter, Fintype.sum_prod_type] + exact Finset.sum_congr rfl fun e _ => (Fintype.sum_bool _).trans (Nat.add_comm ..) + +end BatchDescent.PackRows.Channels + +namespace Assembly.Scheme.Posting +open BatchDescent.PackRows Packing Coloring + +variable {F T : Type} [Field F] {x y : Wire} {L : Fringe x y T} {h z : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h z} + (p : S.Posting r G) (hz : 0 < z) + +include hz in +open scoped Classical in +theorem neighbor (i : G.E) (b : Bool) : + (r (p.host (side G i b))).1 (p.index (side G i b) (side G i (!b))) = + p.host (side G i (!b)) := by + cases b + · exact p.target hz i + · have he := (p.internal (G.units.bits.symm (i, ⟨0, hz⟩))).1 + change S.peer r (p.toSeating.ends (endBit G i false _)).1 = + some (p.toSeating.ends (endBit G i true _)).1 at he + rw [(p.ordered _ _ _).1, (p.ordered _ _ _).1] at he + have hr := (p.proper _ _ he).1 + rw [peer, p.link] at hr + exact congrArg (fun j : S.Span => j.1.1) (Option.some.inj hr) + +open scoped Classical in +/-- The value specified by `finProdFinEquiv (finTwoEquiv.symm b, p.index (side G i b) (side G i +(!b)))`. -/ +def lane (b : Bool) (i : G.E) : Fin (2 * 2 ^ S.d) := + finProdFinEquiv (finTwoEquiv.symm b, p.index (side G i b) (side G i (!b))) + +open scoped Classical in +/-- Builds `Channels G.E (2 ^ S.m) (2 ^ S.h) (2 * 2 ^ S.d) where host b i` with the specified +`host`, `block`, `lane`, `key`. -/ +def channels (p : S.Posting r G) (hz : 0 < z) : Channels G.E (2 ^ S.m) (2 ^ S.h) (2 * 2 ^ S.d) where + host b i := p.host (side G i b) + block i := p.block (G.ix i) + lane := p.lane + key i := (p.stub i false).val + lanes i j b c := by + constructor + · rintro ⟨he, hl⟩ + obtain ⟨hb, ht⟩ := Prod.mk.inj (finProdFinEquiv.injective hl) + have eq := finTwoEquiv.symm.injective hb + subst c + have ho : p.host (side G i (!b)) = p.host (side G j (!b)) := by + rw [← p.neighbor hz i b, ← p.neighbor hz j b, he, ht] + cases b + · exact ⟨rfl, he, ho⟩ + · exact ⟨rfl, ho, he⟩ + · rintro ⟨rfl, hl, hr⟩ + have eq (b) : side G i b = side G j b := by + cases b + · exact p.host.injective hl + · exact p.host.injective hr + simp only [lane, eq, and_self] + unique i j hi hb he := by + apply p.distinct hz + unfold span spanAt + rw [hi, hb, Fin.ext he] + +open scoped Classical in +theorem channels_arity (i : G.V) (j : Cell h) : + arity ((p.channels hz).inventory (p.host i)) (p.block j) = degree G.pair (i, j) := by + rw [Channels.arity_eq, degree_sum] + apply Finset.sum_congr rfl + intro e _ + simp [channels, side, arityCost, HostNet.pair, Prod.ext_iff] + +end Assembly.Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- +# Recovering the internal channel order from local metadata + +The key of a source endpoint is its own stub index. At a destination +it is the peer stub index in the local pattern. Lane sizes and copy +ordinals can thus be computed without looking at other host positions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring BatchDescent.PackRows Packing + +namespace Pattern + +variable {F : Type} {d k e : ℕ} (p : Pattern F d k e) + +open scoped Classical in +/-- The oriented lane and source stub of a positive internal span. -/ +def inner (i : B e) : Option (Fin (2 * 2 ^ d) × B e) := + if p.width 0 i = 0 then none else + (p.peer 0 i).map fun a => + let t := p.direction 0 i + (finProdFinEquiv (finTwoEquiv.symm t, a.1), if t then a.2.2 else i) + +open scoped Classical in +/-- The indexed operation `(Finset.univ.filter fun i => ∃ a, p.inner i = some (j, a)).card`. -/ +def innerCount (j : Fin (2 * 2 ^ d)) := + (Finset.univ.filter fun i => ∃ a, p.inner i = some (j, a)).card + +open scoped Classical in +/-- The indexed operation `(Finset.univ.filter fun i => ∃ a, p.inner i = some (j, a) ∧ a < +z).card`. -/ +def innerPrior (j : Fin (2 * 2 ^ d)) (z : B e) := + (Finset.univ.filter fun i => ∃ a, p.inner i = some (j, a) ∧ a < z).card + +end Pattern + +namespace Scheme.Posting + +variable {F T : Type} [Field F] {x y : Wire} {L : Fringe x y T} {h z : ℕ} + {S : Scheme F} {r : S.format.obj} {G : HostNet F L h z} + (p : S.Posting r G) (hz : 0 < z) + +include hz in +open scoped Classical in +theorem inner_spec (i : G.E) (t : Bool) : + (S.pattern r (p.span i t).1).inner (p.stub i t) = some (p.lane t i, p.stub i false) := by + have hw := p.length i t + have hd := p.dir i t + have hp := p.link i t + change (S.pattern r (p.span i t).1).width 0 (p.stub i t) = z at hw + change (S.pattern r (p.span i t).1).direction 0 (p.stub i t) = t at hd + change (S.pattern r (p.span i t).1).peer 0 (p.stub i t) = _ at hp + rw [Pattern.inner, hw, ite_eq_right hz.ne', hp, hd] + cases t <;> rfl + +open scoped Classical in +theorem found (a : S.Span) (hs : 0 < S.width r a) (hv : (S.peer r a).isSome) : + ∃ i : G.E × Bool, p.span i.1 i.2 = a := by + obtain ⟨q, hq⟩ := p.toSeating.ends.surjective ⟨a, ⟨0, hs⟩⟩ + have he : (p.toSeating.ends q).1 = a := congrArg Sigma.fst hq + rcases q with (i|e)|(i|e) + · rw [← he, p.input] at hv + cases hv + · obtain ⟨⟨i, j⟩, rfl⟩ := G.units.bits.symm.surjective e + exact ⟨(i, false), (p.ordered i false j).1.symm.trans he⟩ + · rw [← he, p.output] at hv + cases hv + · obtain ⟨⟨i, j⟩, rfl⟩ := G.units.bits.symm.surjective e + exact ⟨(i, true), (p.ordered i true j).1.symm.trans he⟩ + +include hz in +open scoped Classical in +theorem inner_iff (i : B S.m) (j : B S.h) (s : B S.e) (l : Fin (2 * 2 ^ S.d)) (u : B S.e) : + (S.pattern r (i, j, 0)).inner s = some (l, u) ↔ + ∃ w : G.E × Bool, (p.channels hz).position w = (i, j, l) ∧ + p.stub w.1 w.2 = s ∧ p.stub w.1 false = u := by + constructor + · intro he + let a : S.Span := ((i, j, 0), s) + have hw : 0 < S.width r a := by + by_contra! h + have ha : (S.pattern r (i, j, 0)).width 0 s = 0 := Nat.eq_zero_of_le_zero h + simp [Pattern.inner, ha] at he + have hv : (S.peer r a).isSome := by + cases hl : (S.pattern r (i, j, 0)).peer 0 s with + | none => simp [Pattern.inner, hl] at he + | some v => simp [a, peer, hl] + obtain ⟨⟨w, t⟩, eq⟩ := p.found a hw hv + have hp := p.inner_spec hz w t + have hs : p.stub w t = s := congrArg Prod.snd eq + rw [hs, eq, he] at hp + obtain ⟨hl, hu⟩ := Prod.mk.inj (Option.some.inj hp.symm) + exact ⟨(w, t), Prod.ext (congrArg (·.1.1) eq) (Prod.ext (congrArg (·.1.2.1) eq) hl), hs, hu⟩ + · rintro ⟨⟨w, t⟩, hp, rfl, rfl⟩ + change (p.host (side G w t), p.block (G.ix w), p.lane t w) = (i, j, l) at hp + obtain ⟨rfl, rfl, rfl⟩ := Prod.mk.inj hp |>.imp_right Prod.mk.inj + exact p.inner_spec hz w t + +open scoped Classical in +private theorem filtered (i : B S.m) (j : B S.h) (l : Fin (2 * 2 ^ S.d)) (P : B S.e → Prop) + [DecidablePred P] : + (((p.channels hz).pool (i, j, l)).filter (fun w => P (p.stub w.1 false))).card = + (Finset.univ.filter fun s => ∃ u, (S.pattern r (i, j, 0)).inner s = some (l, u) ∧ P u).card + := by + let A := p.channels hz + have get (w : G.E × Bool) (hw : w ∈ A.pool (i, j, l)) : + (S.pattern r (i, j, 0)).inner (p.stub w.1 w.2) = some (l, p.stub w.1 false) := + (p.inner_iff hz _ _ _ _ _).mpr ⟨w, (Finset.mem_filter.mp hw).2, rfl, rfl⟩ + refine Finset.card_bij (fun w _ => p.stub w.1 w.2) ?_ ?_ ?_ + · intro w hw + obtain ⟨hw, hp⟩ := Finset.mem_filter.mp hw + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, _, get w hw, hp⟩ + · intro x hx y hy he + have hx' := (Finset.mem_filter.mp hx).1 + have hy' := (Finset.mem_filter.mp hy).1 + have hh := get x hx' + rw [he, get y hy'] at hh + have hk : A.key x.1 = A.key y.1 := congrArg Fin.val (Prod.mk.inj (Option.some.inj hh.symm)).2 + have ht := (Finset.mem_filter.mp hx').2.trans (Finset.mem_filter.mp hy').2.symm + obtain ⟨hb, hl, _⟩ := (A.lanes _ _ _ _).mp ⟨congrArg Prod.fst ht, congrArg (·.2.2) ht⟩ + exact Prod.ext (A.unique _ _ hl (congrArg (·.2.1) ht) hk) hb + · intro s hs + obtain ⟨u, hu, hp⟩ := (Finset.mem_filter.mp hs).2 + obtain ⟨w, hw, he, hf⟩ := (p.inner_iff hz _ _ _ _ _).mp hu + refine ⟨w, Finset.mem_filter.mpr ⟨Finset.mem_filter.mpr ⟨Finset.mem_univ _, hw⟩, ?_⟩, he⟩ + rwa [hf] + +open scoped Classical in +theorem channels_count (i : B S.m) (j : B S.h) (l : Fin (2 * 2 ^ S.d)) : + (p.channels hz).inventory i j l = (S.pattern r (i, j, 0)).innerCount l := by + simpa [Channels.inventory, Pattern.innerCount] using p.filtered hz i j l (fun _ => True) + +open scoped Classical in +theorem channels_prior (i : G.E) (b : Bool) : + (p.channels hz).prior (i, b) = + (S.pattern r (p.span i b).1).innerPrior (p.lane b i) (p.stub i false) := + p.filtered hz _ _ _ (fun k => k < p.stub i false) + +end Scheme.Posting +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # The dictionary product equals the product of occurrence tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Pieces +open Assembly Coloring PackRows + +variable {F : Type} {S : Scheme F} {r : S.format.obj} {d u v K p : ℕ} + {l : Inventory (2 ^ S.m) (2 ^ S.h) d} (B : Pieces S r l v p) + +open Classical in +/-- The equivalence obtained by `Equiv.sigmaCongrRight fun i => Equiv.sigmaCongrRight (B.locate +i)`. -/ +def equiv : units S r (bundleSize v p) ≃ Endpoints l := + Equiv.sigmaCongrRight fun i => Equiv.sigmaCongrRight (B.locate i) + +open Classical in +/-- Reindexes `S.Pin r` and `Endpoints l × Payload v (Fin p)` by an equivalence. -/ +def slots : S.Pin r ≃ Endpoints l × Payload v (Fin p) := + (join S r _ B.uniform).symm.trans (B.equiv.prodCongr finProdFinEquiv.symm) + +open Classical in +/-- Embeds `S.Pin r` into `Address v K × Row (Fin (2 * v)) (Fin (2 * u)) (Fin p)`. -/ +def inside (L : PackRows.Layout l u v K) : S.Pin r ↪ Address v K × Row (Fin (2 * v)) (Fin (2 * u)) + (Fin p) := + B.slots.toEmbedding.trans <| (L.portSlots.prodMap (.refl _)).trans + (Equiv.prodAssoc _ _ _).toEmbedding + +open Classical in +theorem inside_join (L : PackRows.Layout l u v K) (x : units S r (bundleSize v p)) + (t : Fin (bundleSize v p)) : + B.inside L (join S r _ B.uniform (x, t)) = + ((L.portSlots (B.equiv x)).1, (L.portSlots (B.equiv x)).2, finProdFinEquiv.symm t) := by + unfold inside slots + simp only [Function.Embedding.trans_apply, Equiv.toEmbedding_apply, Equiv.trans_apply, + Equiv.symm_apply_apply] + rfl + +open Classical in +/-- The condition `∀ i j, arity (l i) j ≤ u` on the specified data. -/ +def Room := ∀ i j, arity (l i) j ≤ u + +include B in +open Classical in +theorem fits (ha : Room (l := l) (u := u)) (i j) : + Fintype.card (Parts.Unit (pattern S r i j) (bundleSize v p)) ≤ u := by + rw [Fintype.card_congr (B.locate i j), Fintype.card_sigma] + simpa only [Fintype.card_fin, arity] using ha i j + +open Classical in +/-- Maps the coordinate `i j` to `(B.locate i j).symm.toEmbedding.trans (Parts.number _ _ +(B.fits ha i j))`. -/ +def index (ha : Room (l := l) (u := u)) : Index l u := + fun i j => (B.locate i j).symm.toEmbedding.trans (Parts.number _ _ (B.fits ha i j)) + +variable [Field F] + +open Classical in +private theorem eval_entry (ha : Room (l := l) (u := u)) + (y : Endpoints l → Payload v (Fin p) → Bool) (i j) : + entry S u v p (labels S r i j) (padded (B.index ha) y i j) = + ∏ k : Coloring.B S.k, S.table r (i, j, k) (Function.uncurry y ∘ B.slots ∘ S.port r (i, j, k)) + := by + unfold entry labels + rw [Equiv.symm_apply_apply] + unfold entryAt + dsimp only + rw [dite_eq_left ⟨B.uniform i j, B.fits ha i j⟩] + unfold Parts.value + apply Finset.prod_congr rfl + intro k _ + unfold Scheme.table + apply congrArg + funext s t + let a := (Parts.join _ _ (B.uniform i j)).symm ⟨(k, s), t⟩ + have he : B.index ha i j (B.locate i j a.1) = Parts.number _ _ (B.fits ha i j) a.1 := by + simp [index] + change padded (B.index ha) y i j (Parts.number _ _ (B.fits ha i j) a.1, finProdFinEquiv.symm a.2) + = + y ⟨i, j, B.locate i j a.1⟩ (finProdFinEquiv.symm a.2) + rw [← he, padded_at] + +open Classical in +theorem product (ha : Room (l := l) (u := u)) (L : PackRows.Layout l u v K) + (y : Address v K × Row (Fin (2 * v)) (Fin (2 * u)) (Fin p) → Bool) : + (∏ i, ∏ j, entry S u v p (labels S r i j) + (padded (B.index ha) (fun z t => y ((L.portSlots z).1, (L.portSlots z).2, t)) i j)) = + ∏ v, S.table r v (y ∘ B.inside L ∘ S.port r v) := by + simp only [Fintype.prod_prod_type, eval_entry] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Pieces +end + +/- +# Padded port slots + +Check one row at a time by table lookup. The routing description names +the port sockets actually consumed. Every other socket must be zero +to avoid introducing multiplicities when summing over private wires. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +open Transcript + +variable {H m d u v K : ℕ} {l : Inventory H m d} {P X : Type} + +open Classical in +/-- The condition `∀ i ∉ Set.range L.portSlots, ∀ t, x i t = false` on the specified data. -/ +def Layout.Padded (L : Layout l u v K) (x : Address v K × Fin (2 * u) → Payload v P → Bool) : Prop + := + ∀ i ∉ Set.range L.portSlots, ∀ t, x i t = false + +open Classical in +private theorem used (L : Layout l u v K) (r : Address v K) (s : Fin (2 * u)) : + (∃ j, L.moves r.1 (j, r.2, s) = true) ↔ (r, s) ∈ Set.range L.portSlots := by + simp only [Layout.moves, decide_eq_true_eq] + constructor + · rintro ⟨_, i, _, hi⟩ + exact ⟨i, hi⟩ + · rintro ⟨i, hi⟩ + refine ⟨((L.tableSlots i).1.2, (L.tableSlots i).2), i, ?_, hi⟩ + exact Prod.ext (Prod.ext ((L.bin_eq i).trans (congrArg (·.1.1) hi)) rfl) rfl + +open Classical in +/-- Indexes the pins by the coordinates of `Route v u ⊕ (Fin (2 * u) × Payload v P)`. -/ +abbrev Pins (v u : ℕ) (P : Type) := Route v u ⊕ (Fin (2 * u) × Payload v P) + +open Classical in +/-- The condition `∀ s, (¬∃ j : Socket v u, x (.inl (j, j.1, s)) = true) → ∀ t, x (.inr (s, t)) += false` on the specified data. -/ +def ok (x : Pins v u P → Bool) : Prop := + ∀ s, (¬∃ j : Socket v u, x (.inl (j, j.1, s)) = true) → ∀ t, x (.inr (s, t)) = false + +variable (F : Type) [Field F] (control : Fin K → Route v u → X ⊕ Bool) + (port : Fin K → Socket v u → Payload v P → X ⊕ Bool) + +open Classical in +/-- In the case `.inl j`, this construction gives `control r.1 (j.1, r.2, j.2.2)`. -/ +def tap (r : Address v K) : Pins v u P → X ⊕ Bool + | .inl j => control r.1 (j.1, r.2, j.2.2) + | .inr t => port r.1 (r.2, t.1) t.2 + +open Classical in +/-- The product of `if ok (Sum.elim x id ∘ tap control port r) then 1 else 0` indexed by `r`. -/ +def zeroTest (x : X → Bool) : F := + ∏ r, if ok (Sum.elim x id ∘ tap control port r) then 1 else 0 + +variable {F} + +open Classical in +theorem packed_zero [Fintype P] [Fintype X] {w j a : ℕ} + (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (ha : 3 ≤ a) (hb : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ a) + (hwidth : Fintype.card (Route v u) + Fintype.card (Fin (2 * u) × Payload v P) < j) + (hrows : Fintype.card (Address v K) ≤ 2 ^ j) : + WideWeight F a (SortTables F w) (zeroTest F control port) (4 * Fintype.card X + + 11000 * 2 ^ j * (1 + j)) := + dictionary hj hj' ha hb (by rw [Fintype.card_sum]; exact hwidth) hrows + (fun x => if ok x then 1 else 0) (tap control port) + +variable {control port} + +open Classical in +theorem zeroTest_eq (L : Layout l u v K) (x : X → Bool) (hm : ∀ g, Sum.elim x id ∘ control g + = L.moves g) : + zeroTest F control port x = if L.Padded (readPort port x) then 1 else 0 := by + have eq (r : Address v K) : ok (Sum.elim x id ∘ tap control port r) ↔ + ∀ s, (r, s) ∉ Set.range L.portSlots → ∀ t, readPort port x (r, s) t = false := by + change (∀ s, (¬∃ j, (Sum.elim x id ∘ control r.1) (j, r.2, s) = true) → + ∀ t, readPort port x (r, s) t = false) ↔ _ + simp only [hm, used] + simp only [zeroTest, Finset.prod_boole, Finset.mem_univ, forall_const, eq] + congr 1 + exact propext ⟨fun h i => h i.1 i.2, fun h r s => h (r, s)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- +# Uniform scale choices for the exact batch descent + +The number of terminal blocks and the maximum number of rows in a +bin have independent polynomial bounds in the desired width saving. +Only after fixing these bounds do we choose the fraction of the +address length available for a bundle. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Packing Filter + +variable (F : Type) [Field F] + +/-- The data for the recipe construction, including `b`, `n`, `e`, `H`, `C`. -/ +structure Recipe where + /-- The right component. -/ + b : ℕ + /-- The `Recipe` field of type `ℕ`. -/ + n : ℕ + /-- The `Recipe` field of type `ℕ`. -/ + e : ℕ + /-- The `Recipe` field of type `ℕ`. -/ + H : ℕ + /-- The `Recipe` field of type `ℝ`. -/ + C : ℝ + beats : ∀ j : ℕ, 0 < j → Reduction F 8 3 (b ^ j) (n * j) (e ^ j) (H ^ j) ((1 / 2) ^ j) C + +theorem recipe (h : ¬Tagged.Hard F) : Nonempty (Recipe F) := by + obtain ⟨b, n, e, H, C, _, _, beat⟩ := Packing.beats (.inr h) 8 (by decide) + exact ⟨⟨b, n, e, H, C, fun j hj => beat j hj F⟩⟩ + +namespace Recipe +variable {F} (P : Recipe F) + +theorem b_pos : 0 < P.b := by simpa using (P.beats 1 Nat.one_pos).unit +theorem H_pos : 0 < P.H := by simpa using (P.beats 1 Nat.one_pos).overhead + +/-- The quantity computed by `(P.H + 5) * j`. -/ +def group (j : ℕ) := (P.H + 5) * j +/-- The quantity computed by `R * j + (P.n * j) * P.group j`. -/ +def blocks (R j : ℕ) := R * j + (P.n * j) * P.group j +/-- The quantity computed by `2 ^ (P.blocks R j) * (P.b ^ j * z)`. -/ +def batch (R j z : ℕ) := 2 ^ (P.blocks R j) * (P.b ^ j * z) + +theorem group_room (j : ℕ) (hj : 1 ≤ j) : + 12 * (P.H ^ j : ℕ) ≤ (1 / 2 : ℝ) ^ j * (2 : ℝ) ^ (P.group j) := by + have hp : (P.H : ℝ) ≤ (2 : ℝ) ^ P.H := by exact_mod_cast (Nat.lt_two_pow_self (n := P.H)).le + rw [group, pow_mul, ← mul_pow, pow_add, Nat.cast_pow] + calc + _ ≤ (12 : ℝ) ^ j * ((2 : ℝ) ^ P.H) ^ j := by + gcongr + simpa using pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 12) hj + _ = (12 * (2 : ℝ) ^ P.H) ^ j := (mul_pow _ _ _).symm + _ ≤ _ := by + apply pow_le_pow_left₀ (by positivity) + linarith [pow_pos (by norm_num : (0 : ℝ) < 2) P.H] + +theorem expand {a b : Wire} (G : Diagram F a b) (hg : G.Trivalent) + {M j z : ℕ} (hsize : Fintype.card G.V + wd a + wd b ≤ M) + (hj : 1 ≤ j) (hz : 0 < z) (R : ℕ) : + let h := P.blocks R j + let u := P.b ^ j * z + (Stack.start G h u).Expands (P.H ^ j * (5 * 2 ^ h * M * P.b ^ j)) (fun Q : HostNet F _ (R * j) + z => + Q.seats ≤ P.H ^ j * (2 * M * 2 ^ h) ∧ Q.Bounded 3 (8 ^ (P.e ^ j)) ((P.H ^ j : ℕ) * (6 * (u : + ℝ))) ∧ + Q.X ≤ (P.batch R j z : ℝ) * ((3 + P.C) * (1 / 2 : ℝ) ^ j * M + P.C * (wd a + wd b : ℕ)) ∧ + Q.seats ≤ P.H ^ j * (Stack.start G h u).seats ∧ Q.mass ≤ 10 * (P.H ^ j) * (P.batch R j z) * M + ∧ + (∀ p, Q.past p ≤ 6 * u * (P.H ^ j) * 2 ^ (P.group j)) + ∧ (Stack.start G h u).Tracks Q (P.H ^ j)) := + Stack.reduce (P.beats j hj) (pow_le_one₀ (by norm_num) (by norm_num)) G hg M (P.group j) + (R * j) z hsize hz rfl le_rfl (P.group_room j hj) + +private theorem power_le (b j : ℕ) : b ^ j ≤ 2 ^ (b * j) := by + rw [pow_mul] + exact Nat.pow_le_pow_left (Nat.lt_two_pow_self (n := b)).le j + +theorem parameters (R Q W B J : ℕ) (hB : 5 + Q + P.b + W ≤ B) + {κ : ℝ} (hk : 0 < κ) : + ∀ᶠ w : ℕ in atTop, ∃ j z : ℕ, J ≤ j ∧ 1 ≤ j ∧ 2 ^ (B * j) ≤ w ∧ w ≤ 2 ^ (2 * B * j) ∧ + 0 < z ∧ 2 ^ (W * j) ∣ z ∧ + 16 * (2 ^ (Q * j) * P.b ^ j) * z ≤ w ∧ w ≤ 32 * (2 ^ (Q * j) * P.b ^ j) * z ∧ + 0 < P.batch R j z ∧ (P.batch R j z : ℝ) ≤ ((2 : ℝ) ^ w : ℝ) ^ κ := by + let v := R + 2 * B + P.n * (P.H + 5) + obtain ⟨j₀, h₀⟩ := eventually_atTop.mp (replication hk v) + filter_upwards [scales B (max j₀ J) (by omega)] with w hw + obtain ⟨j, hj, hj', hl, hu⟩ := hw + have hr : 32 * (2 ^ (Q * j) * P.b ^ j) * 2 ^ (W * j) ≤ w := calc + _ ≤ 2 ^ 5 * (2 ^ (Q * j) * 2 ^ (P.b * j)) * 2 ^ (W * j) := by + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_left 32 (Nat.mul_le_mul_left _ (power_le P.b j))) + _ = 2 ^ (5 + (Q * j + P.b * j) + W * j) := by simp only [pow_add] + _ ≤ 2 ^ (B * j) := Nat.pow_le_pow_right (by decide) (by nlinarith) + _ ≤ _ := hl + have hb := P.b_pos + obtain ⟨z, hz, hdz, hlo, hup⟩ := fill (by positivity) (by positivity) hr + have hd : 0 < P.batch R j z := by unfold batch; positivity + refine ⟨j, z, (le_max_right _ _).trans hj, hj', hl, hu, hz, hdz, hlo, hup, hd, ?_⟩ + have hjw : 2 ^ j ≤ w := (Nat.pow_le_pow_right (by decide) (by nlinarith : j ≤ B * j)).trans hl + have hwidth : P.b ^ j * z ≤ w := calc + _ ≤ (16 * 2 ^ (Q * j)) * (P.b ^ j * z) := Nat.le_mul_of_pos_left _ (by positivity) + _ ≤ _ := by simpa [mul_assoc] using hlo + have hlayers : P.blocks R j + 2 * B * j ≤ v * j ^ 2 := by + unfold blocks group v + nlinarith only [Nat.mul_le_mul_left (R + 2 * B) (show j ≤ j ^ 2 by nlinarith)] + have hbatch : P.batch R j z ≤ 2 ^ (v * j ^ 2) := calc + _ ≤ 2 ^ (P.blocks R j) * 2 ^ (2 * B * j) := Nat.mul_le_mul_left _ (hwidth.trans hu) + _ ≤ _ := by rw [← pow_add]; exact Nat.pow_le_pow_right (by decide) hlayers + exact (show (P.batch R j z : ℝ) ≤ (2 : ℝ) ^ (v * j ^ 2) by exact_mod_cast hbatch).trans + (h₀ j ((le_max_left _ _).trans hj) w hjw) + +end Recipe +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/PortRelay.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/PortRelay.lean new file mode 100644 index 0000000000..ddbea18513 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/PortRelay.lean @@ -0,0 +1,832 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Add +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Transform +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Header +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.SumOut +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Pieces + +/-! # Exclusive prefix sums of modular addresses -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Coloring Control + +private def step (a : ℕ) (x : Val (.pair (word a) (word a))) := + (index a).symm (index a x.1 + index a x.2) + +private theorem step_net (F : Type) [Field F] (a : ℕ) : + DNet F (.pair (word a) (word a)) (word a) (step a) (10000 * (1 + a)) := by + have k := numeric_add F a (.pair (word a) (word a)) (word a) (.refl _) (.refl _) + convert k using 1 + funext x + change step a x = (bits (word a)).symm ((Format.addr a).code + (let p := (Format.pair (.addr a) (.addr a)).code.symm (bits (.pair (word a) (word a)) x); p.1 + + p.2)) + rw [decode_pair] + apply (bits _).injective + rw [Equiv.apply_symm_apply, ← code_addr] + simp [step] + +private def scan (a : ℕ) : + (n : ℕ) → Val (.pair (word a) (copies (word a) n)) → Val (copies (word a) n) + | 0, _ => () + | n + 1, x => (x.1, scan a n (step a (x.1, x.2.1), x.2.2)) + +private theorem scan_net (F : Type) [Field F] (a n : ℕ) : + DNet F (.pair (word a) (copies (word a) n)) (copies (word a) n) + (scan a n) (a + 20000 * n * (1 + a)) := by + induction n with + | zero => + exact (DNet.discard F _).mono (by simp [wd]) + | succ n ih => + have k := (DNet.fst F (word a) (word a)).pair (step_net F a) + refine ((k.plug ih).pre (.assoc' _ _ _)).mono ?_ + simp only [wd, wd_word] + ring_nf + omega + +private theorem layout_scan (a n : ℕ) : + ∃ L : Layout (word a) (copies (word a) n) (Fin n), ∀ u x j, + index a (L.read (scan a n (u, x)) j) = + index a u + ∑ i ∈ Finset.univ.filter (· < j), index a (L.read x i) := by + induction n with + | zero => exact ⟨⟨Equiv.equivEmpty _⟩, fun _ _ j => j.elim0⟩ + | succ n ih => + obtain ⟨L, hL⟩ := ih + let M : Layout (word a) (copies (word a) (n + 1)) (Fin (n + 1)) := + ⟨((finSuccEquiv n).prodCongr (.refl _)).trans + (optionProdEquiv.trans ((Equiv.refl _).sumCongr L.positions))⟩ + have h0 (x : Val (copies (word a) (n + 1))) : M.read x 0 = x.1 := by + unfold Layout.read + simp [M, bits] + have hs (x : Val (copies (word a) (n + 1))) (i : Fin n) : + M.read x i.succ = L.read x.2 i := by + unfold Layout.read + simp [M, bits] + refine ⟨M, fun u x j => ?_⟩ + induction j using Fin.cases with + | zero => simp [scan, h0] + | succ i => + rw [Finset.sum_filter, Fin.sum_univ_succ] + simp [scan, h0, hs, hL, step, Finset.sum_filter, add_assoc] + +/-- Output the incoming accumulator at every position, then add the +current record modulo the address-space size. -/ +theorem prefix_sum (F : Type) [Field F] (h a : ℕ) : + Circuit F (.vec h (.addr a)) (.vec h (.addr a)) + (fun x j => ∑ i ∈ Finset.univ.filter (· < j), x i) (100000 * 2 ^ h * (1 + a)) := by + let n := 2 ^ h + let z := (index a).symm 0 + obtain ⟨L, hL⟩ := layout_scan a n + have init := ((Lookup.const_net F (word a) z).par (DNet.id F (copies (word a) n))).pre + ((Rewire.unit' _).comp (.swap _ _)) + have net := init.comp (scan_net F a n) + refine Circuit.of_dnet L.positions L.positions (net.mono ?_) ?_ + · simp only [wd_word, wd_copies] + have hn : 1 ≤ n := Nat.one_le_pow _ _ (by decide) + change _ ≤ 100000 * n * (1 + a) + nlinarith only [Nat.mul_le_mul_right a hn] + · intro x + funext ⟨i, k⟩ + have he := hL z x i + rw [show index a z = 0 from (index a).apply_symm_apply _, zero_add] at he + let y := scan a n (z, x) + have hb := congrFun (code_addr a (L.read y i)) k + rw [he] at hb + unfold Layout.read at hb + rw [Equiv.apply_symm_apply] at hb + exact hb.symm + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- # The exterior bits of each stack stay together in ordered units -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +variable {F A : Type} {S : Assembly.Scheme F} {r : S.format.obj} {z : ℕ} + +/-- Each unit is one aligned interval of an exterior span. -/ +def Strips (e : A × Fin z ≃ S.exposed r) : Prop := + ∀ i, ∃ (a : S.Span) (k : ℕ), ∀ t, + (e (i, t)).val.1 = a ∧ (e (i, t)).val.2.val = t.val + z * k + +theorem Strips.uniform {e : A × Fin z ≃ S.exposed r} (h : Strips e) (hz : 0 < z) + (a : S.Span) (ha : S.peer r a = none) : z ∣ S.width r a := by + by_cases hzero : S.width r a = 0 + · simp [hzero] + let j : S.exposed r := ⟨⟨a, ⟨S.width r a - 1, by omega⟩⟩, ha⟩ + obtain ⟨⟨i, t⟩, he⟩ := e.surjective j + obtain ⟨b, k, hk⟩ := h i + have hb : a = b := by simpa only [he] using (hk t).1 + subst b + have hl : S.width r a - 1 = t.val + z * k := + (congrArg (fun q : S.exposed r => q.val.2.val) he).symm.trans (hk t).2 + let u : Fin z := ⟨z - 1, by omega⟩ + have hr := (e (i, u)).val.2.isLt + rw [(hk u).2, (hk u).1] at hr + change z - 1 + z * k < S.width r a at hr + exact ⟨k + 1, by rw [Nat.mul_succ]; have := t.isLt; omega⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Exclusive address sums from short length fields -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Coloring Control Transcript Install + +/-- In the case `0, _`, this construction gives `Lookup.bits a 0`. -/ +def extend (a : ℕ) : (b : ℕ) → Val (word b) → Val (word (a + b)) + | 0, _ => Lookup.bits a 0 + | b + 1, x => (x.1, extend a b x.2) + +private theorem value_extend (a b : ℕ) (x : Val (word b)) : + Lookup.value (a + b) (extend a b x) = Lookup.value b x := by + induction b with + | zero => exact Lookup.value_bits (by positivity) + | succ b ih => + change x.1.toNat + 2 * Lookup.value (a + b) (extend a b x.2) = _ + rw [ih] + rfl + +variable (F : Type) [Field F] + +private theorem extend_net (a b : ℕ) : DNet F (word b) (word (a + b)) (extend a b) (a + b) := by + induction b with + | zero => exact (Lookup.const_net F (word a) _).mono (by simp) + | succ b ih => exact ((DNet.id F .bit).par ih).mono (by simp [wd]; omega) + +theorem widen {r j : ℕ} (hr : r ≤ j) : + Circuit F (.addr r) (.addr j) (Fin.castLE (Nat.pow_le_pow_right (by decide : 0 < 2) hr)) j := by + obtain ⟨a, rfl⟩ := Nat.exists_eq_add_of_le' hr + apply Circuit.of_dnet (.refl _) (.refl _) (extend_net F a r) + intro x + simp only [Equiv.coe_refl, Function.comp_id] + rw [decode_addr, ← code_addr] + congr 1 + exact Fin.ext (value_extend a r x) + +/-- The sum of `Fin.castLE (Nat.pow_le_pow_right (by decide : 0 < 2) hr) (x k)` indexed by `k ∈ +Finset.univ.filter (· < i)`. -/ +def offsets {r j : ℕ} (hr : r ≤ j) (h : ℕ) (x : B h → B r) (i : B h) : B j := + ∑ k ∈ Finset.univ.filter (· < i), Fin.castLE (Nat.pow_le_pow_right (by decide : 0 < 2) hr) (x k) + +theorem offsets_net {r j : ℕ} (hr : r ≤ j) (h : ℕ) : + Circuit F (.vec h (.addr r)) (.vec h (.addr j)) (offsets hr h) (100001 * 2 ^ h * (1 + j)) := by + have H := (Circuit.map (h := h) _ (fun _ => widen F hr)).comp (prefix_sum F h j) + exact H.mono (by ring_nf; omega) + +private theorem val_sum {I : Type} {j : ℕ} (s : Finset I) (f : I → B j) + (h : ∑ i ∈ s, (f i).val < 2 ^ j) : (∑ i ∈ s, f i).val = ∑ i ∈ s, (f i).val := by + classical + induction s using Finset.induction_on with + | empty => simp + | insert i s hi ih => + simp only [Finset.sum_insert hi] at h ⊢ + rw [Fin.val_add, ih (by omega), Nat.mod_eq_of_lt h] + +theorem offsets_val {r j : ℕ} (hr : r ≤ j) (h : ℕ) (x : B h → B r) (i : B h) + (hi : ∑ k ∈ Finset.univ.filter (· < i), (x k).val < 2 ^ j) : + (offsets hr h x i).val = ∑ k ∈ Finset.univ.filter (· < i), (x k).val := + val_sum _ (fun k => Fin.castLE (Nat.pow_le_pow_right (by decide : 0 < 2) hr) (x k)) hi + +variable {F} {X Y : Type} [Fintype Y] {u m n : ℕ} {L : Set (Table F)} + +omit [Fintype Y] in +theorem precompute [Finite Y] (hu : 3 ≤ u) {f : (X → Bool) → Y → Bool} {k : (Y → Bool) → F} + (hf : BNet F f m) (hk : WideWeight F u L k n) : WideWeight F u L (k ∘ f) (4 * m + n) := by + let : Fintype Y := Fintype.ofFinite Y + intro a ix + let iy : Y ≃ slots (word (Fintype.card Y)) := Fintype.equivOfCardEq (by simp) + obtain ⟨v, hv, net⟩ := DWide.of_dnet (L := L) hu (hf a _ ix iy) + obtain ⟨t, ht, h⟩ := hk _ iy + refine ⟨v + t, Nat.add_le_add hv ht, ?_⟩ + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, + Function.comp_def, Equiv.apply_symm_apply, Equiv.symm_apply_apply] using net.comp h + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Relaying long headers inside bins + +A short description selects the source header for each target row; +sources may be reused. Work on narrow vertical slices of the entire +bin. Lengths need not be divisible by the slice count. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Transcript + +variable {F G R L D X T P : Type} [Field F] [Fintype G] [Fintype R] [Fintype L] + [Fintype D] [Fintype X] [Fintype T] [Fintype P] + +open Classical in +/-- The indexed operation `(read (Sum.elim x id ∘ ctrl g) i).elim false (fun t => Sum.elim x id +(src g t k))`. -/ +def relay (read : (D → Bool) → R → Option R) (ctrl : G → D → X ⊕ Bool) + (src : G → R → L → X ⊕ Bool) (x : X → Bool) (g : G) (i : R) (k : L) : Bool := + (read (Sum.elim x id ∘ ctrl g) i).elim false (fun t => Sum.elim x id (src g t k)) + +open Classical in +theorem relay_net {w j u : ℕ} (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (hu : 3 ≤ u) + (ha : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ u) + (read : (D → Bool) → R → Option R) (ctrl : G → D → X ⊕ Bool) + (src dst : G → R → L → X ⊕ Bool) (layout : L ↪ T × P) + (hk : Fintype.card D + 2 * (Fintype.card R * Fintype.card P) < j) + (hn : Fintype.card G * Fintype.card T ≤ 2 ^ j) : + WideWeight F u (SortTables F w) + (fun x => if ∀ g i k, Sum.elim x id (dst g i k) = relay read ctrl src x g i k then 1 else 0) + (4 * Fintype.card X + 11000 * 2 ^ j * (1 + j)) := by + let tape (tap : G → R → L → X ⊕ Bool) (a : G × T) (z : R × P) := + Function.extend layout (tap a.1 z.1) (fun _ => Sum.inr false) (a.2, z.2) + let calls (a : G × T) := Sum.elim (ctrl a.1) (Sum.elim (tape src a) (tape dst a)) + let eqn (x : D ⊕ (R × P) ⊕ (R × P) → Bool) := + ∀ i k, x (.inr (.inr (i, k))) = + (read (x ∘ Sum.inl) i).elim false (fun t => x (.inr (.inl (t, k)))) + let test x : F := if eqn x then 1 else 0 + have H := dictionary hj hj' hu ha + (by simp only [Fintype.card_sum, Fintype.card_prod]; omega) + (by simpa using hn) test calls + convert H using 1 + funext x + have arg (a : G × T) : eqn (Sum.elim x id ∘ calls a) ↔ ∀ i k, + Sum.elim x id (tape dst a (i, k)) = + (read (Sum.elim x id ∘ ctrl a.1) i).elim false (fun t => Sum.elim x id (tape src a (t, k))) + := + Iff.rfl + have valid : (∀ a, eqn (Sum.elim x id ∘ calls a)) ↔ + ∀ g i k, Sum.elim x id (dst g i k) = relay read ctrl src x g i k := by + simp only [arg, relay] + constructor + · intro h g i k + simpa only [tape, Prod.mk.eta, layout.injective.extend_apply] using + h (g, (layout k).1) i (layout k).2 + · rintro h ⟨g, t⟩ i k + by_cases he : (t, k) ∈ Set.range layout + · obtain ⟨l, hl⟩ := he + simpa only [tape, ← hl, layout.injective.extend_apply] using h g i l + · have ht (f) (r) : tape f (g, t) (r, k) = .inr false := + Function.extend_apply' _ _ _ he + simp only [ht, Sum.elim_inr, id_eq] + cases read _ i <;> rfl + simp only [← valid, test] + by_cases h : ∀ a, eqn (Sum.elim x id ∘ calls a) + · simp [h] + · rw [ite_eq_right h, eq_comm] + obtain ⟨a, ha⟩ := not_forall.mp h + exact Finset.prod_eq_zero (Finset.mem_univ a) (ite_eq_right ha) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Recovering the ordered exterior units + +An aligned equivalence on bits descends to an equivalence on units +without changing the within-unit index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +variable {F A : Type} {S : Assembly.Scheme F} {r : S.format.obj} {z : ℕ} + (hu : ∀ i j, Parts.Uniform (pattern S r i j) z) + +/-- Uses `⟨join S r z hu (x.val, t), x.property⟩` as the representation. -/ +def toOuter (x : outer S r z) (t : Fin z) : S.exposed r := + ⟨join S r z hu (x.val, t), x.property⟩ + +namespace Strips +variable {e : A × Fin z ≃ S.exposed r} + +private theorem one (h : Strips e) (hz : 0 < z) (i : A) : + ∃ a : outer S r z, ∀ t, e (i, t) = toOuter hu a t := by + obtain ⟨s, k, hk⟩ := h i + let last : Fin z := ⟨z - 1, by omega⟩ + have hl := (e (i, last)).val.2.isLt + rw [(hk last).2, (hk last).1] at hl + change z - 1 + z * k < S.width r s at hl + have hd : k + 1 ≤ S.width r s / z := by + apply (Nat.le_div_iff_mul_le hz).mpr + rw [mul_comm, Nat.mul_add, Nat.mul_one] + omega + let w : units S r z := ⟨s.1.1, s.1.2.1, (s.1.2.2, s.2), ⟨k, hd⟩⟩ + have hv : S.peer r (unitSpan w) = none := by + change S.peer r s = none + rw [← (hk last).1] + exact (e (i, last)).property + refine ⟨⟨w, hv⟩, fun t => Subtype.ext ?_⟩ + refine Sigma.ext (hk t).1 ((Fin.heq_ext_iff (congrArg (S.width r) (hk t).1)).mpr ?_) + exact (hk t).2 + +theorem segments (h : Strips e) (hz : 0 < z) : + ∃ f : A ≃ outer S r z, ∀ i t, e (i, t) = toOuter hu (f i) t := by + choose f hf using one hu h hz + let t : Fin z := ⟨0, hz⟩ + have hi : Function.Injective f := by + intro i j he + have hh : e (i, t) = e (j, t) := by rw [hf, he, hf] + exact congrArg Prod.fst (e.injective hh) + have hs : Function.Surjective f := by + intro b + obtain ⟨⟨i, j⟩, he⟩ := e.surjective (toOuter hu b t) + rw [hf] at he + have hh := (join S r z hu).injective (congrArg Subtype.val he) + exact ⟨i, Subtype.ext (congrArg Prod.fst hh)⟩ + exact ⟨Equiv.ofBijective f ⟨hi, hs⟩, hf⟩ + +end Strips +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Placing host descriptors at their start offsets + +A shared dictionary computes lengths. Exclusive prefix sums give +destinations; scattering checks the entire proposed output including +the blank positions. Arithmetic cannot wrap at a valid destination. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Coloring Control Transcript Install + +variable {F X D T : Type} [Field F] [Fintype X] [Fintype D] [Fintype T] {w j h u r : ℕ} + +open Classical in +/-- A named array of binary addresses of width `j` bits. -/ +abbrev Addresses (I : Type) [Fintype I] (j : ℕ) : Format := + ⟨I → B j, I × slots (word j), + (Equiv.piCongrRight (fun _ => (Format.addr j).code)).trans (Equiv.curry _ _ _).symm⟩ + +open Classical in +private theorem cost_bound {M H I J w j r : ℕ} (hh : H ≤ J) (hi : I ≤ J) + (hr : r ≤ j) (hj : j ≤ 2 * w) : + 8 * (M + H * r) + 9 * (4 * (M + H * r) + 11000 * J * (1 + j) + + (4 * (M + (100001 * H * (1 + j) + 100000 * J * (1 + j))) + 10000 * (M + I * j + J * w))) + ≤ 10 ^ 9 * (M + J * (1 + w)) := by + have h₁ := Nat.mul_le_mul hh (hr.trans hj) + have h₂ := Nat.mul_le_mul hh hj + have h₃ := Nat.mul_le_mul_left J hj + have h₄ := Nat.mul_le_mul hi hj + ring_nf at * + omega + +open Classical in +/-- Compute destinations from the exclusive count offsets before +scattering a possibly different collection of records. -/ +theorem scatter_with {I L : Type} [Fintype I] [Fintype L] + (len : (D → Bool) → ℕ) (src : Fin (2 ^ h) → D → X ⊕ Bool) (data : I → L → X ⊕ Bool) + (dst : T → L → X ⊕ Bool) (used : T → X ⊕ Bool) (name : T ↪ Fin (2 ^ j)) + (post : (B h → B j) → I → B j) + (net : Circuit F (.vec h (.addr j)) (Addresses I j) post (100000 * 2 ^ j * (1 + j))) + (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (hu : 3 ≤ u) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ u) + (hd : Fintype.card D + r < j) (hH : 2 ^ h ≤ 2 ^ j) + (hL : j + Fintype.card L + 2 ≤ 4 * w) (hsize : Fintype.card I + Fintype.card T ≤ 2 ^ j) : + ∃ f : (X → Bool) → F, WideWeight F u (SortTables F w) f (10 ^ 9 * (Fintype.card X + 2 ^ j * (1 + + w))) ∧ + ∀ (x : X → Bool) (e : I ↪ T) (p : B h → B j), + (∀ i, len (Sum.elim x id ∘ src i) < 2 ^ r) → + (∀ i, (p i).val = ∑ v ∈ Finset.univ.filter (· < i), len (Sum.elim x id ∘ src v)) → + (∀ i, post p i = name (e i)) → + f x = if (∀ v, Sum.elim x id (used v) = true ↔ v ∈ Set.range e) ∧ + ∀ v k, Sum.elim x id (dst v k) = + Function.extend e (fun i => Sum.elim x id (data i k)) (fun _ => false) v + then 1 else 0 := by + have hr : r ≤ j := by omega + let A := Format.vec h (.addr r) + let Z := Addresses I j + let ask (y : D → Bool) := bits (word r) (Lookup.bits r (len y)) + let lengths := applyRows ask src (Equiv.refl A.pins) + have hu' : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ u := by + refine le_trans ?_ ha + exact Nat.mul_le_mul (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide) hj')) (by omega) + have grab := transform (F := F) ask src (Equiv.refl A.pins) hj hj' hu hu' + (by simpa using hd) (by simp; omega) + let expand : X ⊕ Bool → (X ⊕ Z.pins) ⊕ Bool := Sum.map Sum.inl id + let adr (i : I) (k : slots (word j)) : (X ⊕ Z.pins) ⊕ Bool := .inl (.inr (i, k)) + have hu'' : 2 * 2 ^ j * (4 * w) ≤ u := by + refine le_trans ?_ ha + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide) (by + omega))) + obtain ⟨f, hf, he⟩ := scatter F (name.trans (index j).symm.toEmbedding) adr + (fun i => expand ∘ data i) (fun i => expand ∘ dst i) (expand ∘ used) hj (by omega) hu hu'' + hL hsize + let next := Z.code ∘ (post ∘ offsets hr h) ∘ A.code.symm + let join (y : X ⊕ A.pins → Bool) := Sum.elim (y ∘ Sum.inl) (next (y ∘ Sum.inr)) + have step : BNet F join (Fintype.card X + (100001 * 2 ^ h * (1 + j) + 100000 * 2 ^ j * (1 + j))) + := + (BNet.id F X).parallel ((offsets_net F hr h).comp net) + have check := bind hu grab (precompute hu step hf) + let run (x : X → Bool) := Sum.elim x (next (lengths x)) + refine ⟨f ∘ run, ?_, fun x e p hl hn hp => ?_⟩ + · intro a ix + obtain ⟨q, hq, hnet⟩ := check a ix + refine ⟨q, hq.trans ?_, hnet⟩ + simp only [Fintype.card_sum, A, Z, Fintype.card_prod, Fintype.card_fin, card_slots, wd_word] + exact cost_bound hH (by omega) hr (by omega) + · have hv (i) : (A.code.symm (lengths x) i).val = len (Sum.elim x id ∘ src i) := by + change (index r ((bits (word r)).symm (ask (Sum.elim x id ∘ src i)))).val = _ + unfold ask + rw [Equiv.symm_apply_apply] + exact Lookup.value_bits (hl i) + have hpos : offsets hr h (A.code.symm (lengths x)) = p := by + funext i + apply Fin.ext + rw [offsets_val, hn] + · simp only [hv] + · simp only [hv, ← hn i] + exact (p i).isLt + have hok (i) : bits (word j) ((name.trans (index j).symm.toEmbedding) (e i)) = + Sum.elim (run x) id ∘ adr i := by + change bits (word j) ((index j).symm (name (e i))) = + (Format.addr j).code (post (offsets hr h (A.code.symm (lengths x))) i) + rw [hpos, hp] + rfl + have tap (i : X ⊕ Bool) : Sum.elim (run x) id (expand i) = Sum.elim x id i := by cases i <;> rfl + simpa only [Function.comp_apply, tap] using he (run x) e hok + +open Classical in +theorem short_scatter (len : (D → Bool) → ℕ) (src : Fin (2 ^ h) → D → X ⊕ Bool) + (dst : T → D → X ⊕ Bool) (used : T → X ⊕ Bool) (name : T ↪ Fin (2 ^ j)) + (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (hu : 3 ≤ u) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ u) + (hd : Fintype.card D + r < j) (hsize : 2 ^ h + Fintype.card T ≤ 2 ^ j) : + ∃ f : (X → Bool) → F, WideWeight F u (SortTables F w) f (10 ^ 9 * (Fintype.card X + 2 ^ j * (1 + + w))) ∧ + ∀ (x : X → Bool) (e : Fin (2 ^ h) ↪ T), + (∀ i, len (Sum.elim x id ∘ src i) < 2 ^ r) → + (∀ i, (name (e i)).val = ∑ v ∈ Finset.univ.filter (· < i), len (Sum.elim x id ∘ src v)) → + f x = if (∀ v, Sum.elim x id (used v) = true ↔ v ∈ Set.range e) ∧ + ∀ v k, Sum.elim x id (dst v k) = + Function.extend e (fun i => Sum.elim x id (src i k)) (fun _ => false) v + then 1 else 0 := by + have hH : 2 ^ h ≤ 2 ^ j := by omega + have net : Circuit F (.vec h (.addr j)) (Addresses (B h) j) id (100000 * 2 ^ j * (1 + j)) := by + refine (Circuit.id F (.vec h (.addr j))).mono ?_ + rw [Format.width_vec, Format.width_addr] + have := Nat.mul_le_mul_right j hH + ring_nf at this ⊢ + omega + obtain ⟨f, hf, he⟩ := scatter_with len src src dst used name id net hj hj' hu ha hd hH + (by omega) (by simpa using hsize) + exact ⟨f, hf, fun x e hl hp => he x e (name ∘ e) hl hp (fun _ => rfl)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- # Binary addresses of consecutive port headers -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +open Coloring Install Control + +private def clearLow (a : ℕ) : (r : ℕ) → Val (word (a + r)) → Val (word (a + r)) + | 0, x => x + | r + 1, x => (false, clearLow a r x.2) + +private theorem clear_val (a r : ℕ) (x : Val (word (a + r))) : + Lookup.value (a + r) (clearLow a r x) = Lookup.value (a + r) x / 2 ^ r * 2 ^ r := by + induction r with + | zero => simp [clearLow] + | succ r ih => + have hx : Lookup.value (a + (r + 1)) x / 2 = Lookup.value (a + r) x.2 := by + change (x.1.toNat + 2 * Lookup.value (a + r) x.2) / 2 = _ + cases x.1 <;> simp + omega + rw [pow_succ', ← Nat.div_div_eq_div_mul, hx] + change 0 + 2 * Lookup.value (a + r) (clearLow a r x.2) = _ + rw [ih] + ring + +variable (F : Type) [Field F] + +private theorem clear_net (a r : ℕ) : + DNet F (word (a + r)) (word (a + r)) (clearLow a r) (a + r) := by + induction r with + | zero => exact (DNet.id F (word a)).mono (by simp) + | succ r ih => + exact ((DNet.table F .bit .bit (fun _ => false) (by decide)).par ih).mono (by omega) + +/-- The quantity computed by `⟨i.val / 2 ^ r * 2 ^ r, (Nat.div_mul_le_self ..).trans_lt +i.isLt⟩`. -/ +def high (r j : ℕ) (i : B j) : B j := + ⟨i.val / 2 ^ r * 2 ^ r, (Nat.div_mul_le_self ..).trans_lt i.isLt⟩ + +private theorem high_net {r j : ℕ} (hr : r ≤ j) : + Circuit F (.addr j) (.addr j) (high r j) j := by + obtain ⟨a, rfl⟩ := Nat.exists_eq_add_of_le' hr + apply Circuit.of_dnet (.refl _) (.refl _) (clear_net F a r) + intro x + simp only [Equiv.coe_refl, Function.comp_id] + rw [decode_addr, ← code_addr] + congr 1 + exact Fin.ext (clear_val a r x) + +/-- Double the bin stride, preserving the offset and adding the port number. -/ +def portOffset {j : ℕ} (r k : ℕ) (i : B j) : B j := + i + high r j i + Fin.ofNat _ k + +theorem portOffset_val {j : ℕ} (r k : ℕ) (i : B j) : + (portOffset r k i).val = (i.val / 2 ^ r * (2 * 2 ^ r) + i.val % 2 ^ r + k) % 2 ^ j := by + unfold portOffset + simp only [Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod, Nat.mod_add_mod, high] + have := Nat.div_add_mod i.val (2 ^ r) + congr 1 + nlinarith + +private theorem port_net {r j : ℕ} (hr : r ≤ j) (k : ℕ) : + Circuit F (.addr j) (.addr j) (portOffset r k) (30000 * (1 + j)) := by + have fixed : Circuit F (.addr j) (.addr j) (fun _ => Fin.ofNat _ k) (2 * j) := by + let c := (index j).symm (Fin.ofNat (2 ^ j) k) + have h := (DNet.discard F (word j)).comp (Lookup.const_net F (word j) c) + apply Circuit.of_dnet (.refl _) (.refl _) (h.mono (n := 2 * j) (by simp; omega)) + intro x + rfl + have h := ((Circuit.id F (.addr j)).pair (high_net F hr)).comp (numeric_add F j) + exact ((h.pair fixed).comp (numeric_add F j)).mono (by simp; omega) + +theorem portOffsets {r j h d : ℕ} (hr : r ≤ j) (hh : 2 ^ h ≤ 2 ^ j) (hd : 2 ^ h * d ≤ 2 ^ j) : + Circuit F (.vec h (.addr j)) (Addresses (B h × Fin d) j) + (fun x p => portOffset r p.2.val (x p.1)) (100000 * 2 ^ j * (1 + j)) := by + let A := Format.vec h (.addr j) + have one (i : Fin d) : + Circuit F A A (fun x k => portOffset r i.val (x k)) (2 ^ h * (30000 * (1 + j))) := + Circuit.map _ (fun _ => port_net F hr i.val) + let e : Fin d × A.pins ≃ (B h × Fin d) × slots (word j) := + (Equiv.prodAssoc _ _ _).symm.trans ((Equiv.prodComm _ _).prodCongr (.refl _)) + have net := (BNet.finite_share _ one).rename (.refl _) e + refine net.mono ?_ + change A.width + Fintype.card (Fin d) * (5 * A.width + 2 ^ h * (30000 * (1 + j))) ≤ _ + rw [Fintype.card_fin, Format.width_vec, Format.width_addr] + have h₁ := Nat.mul_le_mul_right j hh + have h₂ := Nat.mul_le_mul_right j hd + ring_nf at h₁ h₂ hd ⊢ + omega + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- +# Scattering short and long headers into bins + +Short headers use a bin stride of one half-bin. Long headers use the +full stride and one row per port. The packing inequalities exclude +modular wraparound in both address calculations. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows + +open Coloring Transcript + +variable {X D L : Type} {h j w u r K m d cap : ℕ} + +open Classical in +private def addressName {v : ℕ} (hk : K * v ≤ 2 ^ j) : Fin K × Fin v ↪ B j := + finProdFinEquiv.toEmbedding.trans (Fin.castLEEmb hk) + +open Classical in +private theorem name_anchor (l : Inventory (2 ^ h) m d) (hs : ∀ i, size (l i) u ≤ 2 ^ r) + (hk : bins l u (2 ^ r) ≤ K) (hab : K * 2 ^ r ≤ 2 ^ j) (i : B h) : + (addressName hab (anchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk i)).val = start (counts l u) i + := + Nat.mod_add_div _ _ + +open Classical in +private theorem length_bounds (l : Inventory (2 ^ h) m d) (hs : ∀ i, size (l i) u ≤ 2 ^ r) + (v : B h → ℕ) (he : ∀ i, v i = counts l u i) : + (∀ i, v i < 2 ^ (r + 1)) ∧ ∀ i, start (counts l u) i = ∑ k ∈ Finset.univ.filter (· < i), v k + := by + constructor + · intro i + rw [he] + exact (hs i).trans_lt (pow_lt_pow_right₀ (by decide) (by omega)) + · intro i + simp only [he] + rfl + +variable (F : Type) [Field F] [Fintype X] [Fintype D] + +open Classical in +theorem anchor_scatter (len : (D → Bool) → ℕ) (src : B h → D → X ⊕ Bool) + (dst : Anchor (2 ^ r) K → D → X ⊕ Bool) (used : Anchor (2 ^ r) K → X ⊕ Bool) + (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (hc : 3 ≤ cap) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ cap) + (hd : Fintype.card D + (r + 1) < j) (hsize : 2 ^ h + K * 2 ^ r ≤ 2 ^ j) : + ∃ f : (X → Bool) → F, WideWeight F cap (SortTables F w) f (10 ^ 9 * (Fintype.card X + + 2 ^ j * (1 + w))) ∧ + ∀ (x : X → Bool) (l : Inventory (2 ^ h) m d) (hs : ∀ i, size (l i) u ≤ 2 ^ r) + (hk : bins l u (2 ^ r) ≤ K), + (∀ i, len (Sum.elim x id ∘ src i) = counts l u i) → + let e := anchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk + f x = if (∀ v, Sum.elim x id (used v) = true ↔ v ∈ Set.range e) ∧ + ∀ v k, Sum.elim x id (dst v k) = + Function.extend e (fun i => Sum.elim x id (src i k)) (fun _ => false) v + then 1 else 0 := by + have hab : K * 2 ^ r ≤ 2 ^ j := (Nat.le_add_left _ _).trans hsize + obtain ⟨f, hf, he⟩ := short_scatter (F := F) len src dst used (addressName hab) hj hj' hc ha hd + (by simpa only [Anchor, Address, B, Fintype.card_prod, Fintype.card_fin] using hsize) + refine ⟨f, hf, fun x l hs hk hl => ?_⟩ + obtain ⟨small, offset⟩ := length_bounds l hs _ hl + let e := anchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk + have out := he x e small (fun i => (name_anchor l hs hk hab i).trans (offset i)) + refine out.trans ?_ + split <;> rfl + +open Classical in +theorem port_scatter [Fintype L] (len : (D → Bool) → ℕ) (src : B h → D → X ⊕ Bool) + (srcLong : B h × Fin d → L → X ⊕ Bool) + (dst : Address (2 ^ r) K → L → X ⊕ Bool) (used : Address (2 ^ r) K → X ⊕ Bool) + (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (hc : 3 ≤ cap) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ cap) + (hd : Fintype.card D + (r + 1) < j) (hL : j + Fintype.card L + 2 ≤ 4 * w) + (hsize : 2 ^ h * d + K * (2 * 2 ^ r) ≤ 2 ^ j) (hdpos : 0 < d) : + ∃ f : (X → Bool) → F, WideWeight F cap (SortTables F w) f (10 ^ 9 * (Fintype.card X + + 2 ^ j * (1 + w))) ∧ + ∀ (x : X → Bool) (l : Inventory (2 ^ h) m d) (hs : ∀ i, size (l i) u ≤ 2 ^ r) + (hk : bins l u (2 ^ r) ≤ K), + (∀ i, len (Sum.elim x id ∘ src i) = counts l u i) → + let e := portAnchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk + f x = if (∀ v, Sum.elim x id (used v) = true ↔ v ∈ Set.range e) ∧ + ∀ v k, Sum.elim x id (dst v k) = + Function.extend e (fun i => Sum.elim x id (srcLong i k)) (fun _ => false) v + then 1 else 0 := by + have hrow : 2 ^ h * d ≤ 2 ^ j := (Nat.le_add_right _ _).trans hsize + have hH : 2 ^ h ≤ 2 ^ j := (Nat.le_mul_of_pos_right _ hdpos).trans hrow + have hab : K * (2 * 2 ^ r) ≤ 2 ^ j := (Nat.le_add_left _ _).trans hsize + have hab' : K * 2 ^ r ≤ 2 ^ j := (Nat.mul_le_mul_left K (by omega)).trans hab + have hp := portOffsets F (show r ≤ j by omega) hH hrow + obtain ⟨f, hf, he⟩ := scatter_with len src srcLong dst used (addressName hab) _ hp hj hj' hc ha + hd hH hL + (by simpa only [Anchor, Address, B, Fintype.card_prod, Fintype.card_fin] using hsize) + refine ⟨f, hf, fun x l hs hk hl => ?_⟩ + obtain ⟨small, offset⟩ := length_bounds l hs _ hl + let pos (i : B h) := addressName hab' (anchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk i) + let e := portAnchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk + suffices ha : ∀ i, portOffset r i.2.val (pos i.1) = addressName hab (e i) by + have out := he x e pos small (fun i => (name_anchor l hs hk hab' i).trans (offset i)) ha + refine out.trans ?_ + split <;> rfl + intro i + apply Fin.ext + rw [portOffset_val, show (pos i.1).val = _ from name_anchor l hs hk hab' i.1] + have hv : (addressName hab (e i)).val = + start (counts l u) i.1 / 2 ^ r * (2 * 2 ^ r) + start (counts l u) i.1 % 2 ^ r + i.2.val := by + change (e i).2.val + (2 * 2 ^ r) * (e i).1.val = _ + obtain ⟨h₁, h₂⟩ := portAnchor_val l u (2 ^ r) K (Nat.two_pow_pos r) hs hk i + rw [h₁, h₂] + ring + rw [← hv, Nat.mod_eq_of_lt (addressName hab (e i)).isLt] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end + +/- +# Long port descriptors with private anchor tapes + +Scatter one descriptor per port to its anchor and relay it within +the bin. The activity bits and contents of every anchor are forced, +so summing over this intermediate tape has multiplicity one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +open Transcript Coloring + +variable {F X Y : Type} [Field F] [Fintype X] [Fintype Y] {m n cap : ℕ} + +open Classical in +/-- Hide a witness tape that is uniquely determined on valid inputs. -/ +theorem hide_unique {G : Set (Table F)} (hu : 3 ≤ cap) {f k : (X ⊕ Y → Bool) → F} + (hf : WideWeight F cap G f m) (hk : WideWeight F cap G k n) : + ∃ h, WideWeight F cap G h (8 * (Fintype.card X + Fintype.card Y) + 9 * (m + n)) ∧ + ∀ x y, (∀ z, f (Sum.elim x z) = if y = z then 1 else 0) → h x = k (Sum.elim x y) := by + let jobs (b : Bool) := if b then f else k + let costs (b : Bool) := if b then m else n + have ready (b : Bool) : WideWeight F cap G (jobs b) (costs b) := by + cases b + · exact hk + · exact hf + have H := wide_sum jobs (fun _ => id) costs hu ready + refine ⟨weightedSum jobs (fun _ => id), by simpa [costs] using H, ?_⟩ + intro x y h + simp [weightedSum, jobs, h, ite_mul] + +variable {Z D L T P : Type} {h r K d u j w : ℕ} +open Classical in +/-- The quantity computed by `(L → Bool) → Fin (2 * 2 ^ r) → Option (Fin (2 * 2 ^ r))`. -/ +abbrev RelayRead (L : Type) (r : ℕ) := (L → Bool) → Fin (2 * 2 ^ r) → Option (Fin (2 * 2 ^ r)) + +open Classical in +/-- The delivered of type `Bool` for the given inputs. -/ +def delivered (e : B h × Fin d ↪ Address (2 ^ r) K) + (srcLong : B h × Fin d → Z → X ⊕ Bool) (read : RelayRead L r) (ctrl : Fin K → L → X ⊕ Bool) + (x : X → Bool) (a : Address (2 ^ r) K) (k : Z) : Bool := + (read (Sum.elim x id ∘ ctrl a.1) a.2).elim false fun t => + Function.extend e (fun i => Sum.elim x id (srcLong i k)) (fun _ => false) (a.1, t) + +open Classical in +/-- Computes the lift tap by the application `Sum.map Sum.inl id t`. -/ +def liftTap (t : X ⊕ Bool) : (X ⊕ Y) ⊕ Bool := Sum.map Sum.inl id t + +omit [Fintype X] [Fintype Y] in +open Classical in +@[simp] theorem read_lift (x : X → Bool) (y : Y → Bool) (t : X ⊕ Bool) : + Sum.elim (Sum.elim x y) id (liftTap t) = Sum.elim x id t := by cases t <;> rfl + +omit [Fintype X] [Fintype Y] in +open Classical in +@[simp] theorem read_lift_fun (x : X → Bool) (y : Y → Bool) (f : T → X ⊕ Bool) : + Sum.elim (Sum.elim x y) id ∘ liftTap ∘ f = Sum.elim x id ∘ f := + funext (fun _ => read_lift _ _ _) + +open Classical in +private theorem bound {X Y w j : ℕ} (hj : j ≤ 2 * w) (hy : Y ≤ 2 ^ j * (4 * w + 1)) : + 8 * (X + Y) + 9 * (10 ^ 9 * (X + Y + 2 ^ j * (1 + w)) + (4 * (X + Y) + 11000 * 2 ^ j * (1 + + j))) ≤ + 10 ^ 12 * (X + 2 ^ j * (1 + w)) := by + have := Nat.mul_le_mul_left (2 ^ j) hj + ring_nf at * + omega + +open Classical in +theorem port_relay (F : Type) [Field F] [Fintype D] [Fintype Z] [Fintype L] [Fintype T] [Fintype P] + (len : (D → Bool) → ℕ) (src : B h → D → X ⊕ Bool) (srcLong : B h × Fin d → Z → X ⊕ Bool) + (read : RelayRead L r) (ctrl : Fin K → L → X ⊕ Bool) + (dst : Address (2 ^ r) K → Z → X ⊕ Bool) (layout : Z ↪ T × P) + (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) (hc : 3 ≤ cap) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ cap) + (hd : Fintype.card D + (r + 1) < j) (hL : j + Fintype.card Z + 2 ≤ 4 * w) + (hsize : 2 ^ h * d + K * (2 * 2 ^ r) ≤ 2 ^ j) (hdpos : 0 < d) + (hz : Fintype.card L + 2 * ((2 * 2 ^ r) * Fintype.card P) < j) (ht : K * Fintype.card T + ≤ 2 ^ j) : + ∃ f : (X → Bool) → F, WideWeight F cap (SortTables F w) f (10 ^ 12 * (Fintype.card X + + 2 ^ j * (1 + w))) ∧ + ∀ (x : X → Bool) (l : Inventory (2 ^ h) m d) (hs : ∀ i, size (l i) u ≤ 2 ^ r) + (hk : bins l u (2 ^ r) ≤ K), + (∀ i, len (Sum.elim x id ∘ src i) = counts l u i) → + f x = if ∀ v, Sum.elim x id ∘ dst v = + delivered (portAnchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk) srcLong read ctrl x v + then 1 else 0 := by + let Y := Address (2 ^ r) K × Option Z + let get (v : Address (2 ^ r) K) (k : Z) : (X ⊕ Y) ⊕ Bool := .inl (.inr (v, some k)) + let used (v : Address (2 ^ r) K) : (X ⊕ Y) ⊕ Bool := .inl (.inr (v, none)) + obtain ⟨t, ht₁, ht₂⟩ := port_scatter (m := m) (u := u) F len (fun i => liftTap ∘ src i) + (fun i => liftTap ∘ srcLong i) get used hj hj' hc ha hd hL hsize hdpos + have ha' : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ cap := le_trans + (Nat.mul_le_mul (Nat.mul_le_mul_left 2 (Nat.pow_le_pow_right (by decide) hj')) (by omega)) ha + have hnet := relay_net (F := F) hj hj' hc ha' read (fun i => liftTap ∘ ctrl i) + (Function.curry get) (fun i j => liftTap ∘ dst (i, + j)) layout (by simpa using hz) (by simpa using ht) + obtain ⟨f, hf, he⟩ := hide_unique hc ht₁ hnet + refine ⟨f, ?_, fun x l hs hk hl => ?_⟩ + · have hY : Fintype.card Y ≤ 2 ^ j * (4 * w + 1) := by + simp only [Y, Address, Fintype.card_prod, Fintype.card_option, Fintype.card_fin] + exact Nat.mul_le_mul (by omega) (by omega) + intro a i + obtain ⟨v, hv, he⟩ := hf a i + refine ⟨v, hv.trans ?_, he⟩ + rw [Fintype.card_sum] + exact bound (by omega) hY + let e := portAnchor l u (2 ^ r) K (Nat.two_pow_pos r) hs hk + let data (i : Address (2 ^ r) K) (k : Z) := + Function.extend e (fun j => Sum.elim x id (srcLong j k)) (fun _ => false) i + let values : Y → Bool := fun p => p.2.elim (decide (p.1 ∈ Set.range e)) (data p.1) + have unique (y : Y → Bool) : t (Sum.elim x y) = if values = y then 1 else 0 := by + rw [ht₂ _ l hs hk (by simpa only [read_lift_fun] using hl)] + simp only [used, get, Sum.elim_inl, Sum.elim_inr, Function.comp_apply, read_lift] + congr 1 + apply propext + constructor + · rintro ⟨h₁, h₂⟩ + funext ⟨i, q⟩ + rcases q with _|k + · exact Bool.eq_iff_iff.mpr (decide_eq_true_iff.trans (h₁ i).symm) + · exact (h₂ i k).symm + · rintro rfl + exact ⟨fun _ => decide_eq_true_iff, fun _ _ => rfl⟩ + rw [he x values unique] + simp only [relay, read_lift_fun, Function.comp_apply, read_lift, Function.curry_apply, get, + Sum.elim_inl, Sum.elim_inr] + congr 1 + exact propext ⟨fun h i => funext (h i.1 i.2), fun h i j => congrFun (h (i, j))⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.PackRows +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/Carry.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/Carry.lean new file mode 100644 index 0000000000..14288eaad3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/Carry.lean @@ -0,0 +1,591 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Phase.ResetRate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Elect +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Attachment.WriteNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.HeaderCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.MixCost + +/-! +# Carrying exterior marks through a reset + +Each new host has a fixed parent, so projection suffices to copy +the records required by the reset pointers. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Coloring + +variable {F : Type} {x y : Wire} (S : Setup F x y) (T N : Template F) + +/-- Computes the mail by the application `Trail.receipts T.scheme N.scheme 0 S.h S.d S.e`. -/ +abbrev mail := Trail.receipts T.scheme N.scheme 0 S.h S.d S.e + +/-- The bound obtained by adding the component charges `8 * (S.format T).width + 8 * +T.format.width + 8 * (mail S T N).width + Trail.carryCost T.scheme N.scheme 0 S.h S.d S.d +S.e (S.format T) N.format`. -/ +def applyCost := 8 * (S.format T).width + 8 * T.format.width + 8 * (mail S T N).width + + Trail.carryCost T.scheme N.scheme 0 S.h S.d S.d S.e (S.format T) N.format + +variable [Field F] {S T N} {I : Type*} {v u size : ℕ} {L : Set (Table F)} + +private theorem copy_net (parent : B N.scheme.m → B T.scheme.m) : + Circuit F (S.format T) (mail S T N) (fun x j _ => x.2.row (parent j)) + ((S.format T).width + 2 * (mail S T N).width) := by + let idx : (mail S T N).pins → (S.format T).pins + | (i, _, .inl (j, p)) => .inr (.inl (Trail.locate (parent i) j, p)) + | (i, _, .inr p) => .inr (.inr (parent i, p)) + apply Circuit.project idx + rintro x ⟨i, k, ⟨j, p⟩|p⟩ <;> rfl + +theorem apply_net (hv : 3 ≤ v) (X : I → Snapshot.Data S T u) (rows : I → N.format.obj) + (move : I → Trail.Move T.scheme N.scheme 0) (parent : B N.scheme.m → B T.scheme.m) + (hn : ∀ i, (move i).nav = fun j _ => parent j) + (commands : Computes F v L T.format (History.Reset.Tile.whole T N) + (fun i => (X i).rows) (fun i => (rows i, (move i).commands)) (fun _ => 1) size) : + Computes F v L (S.format T) (S.format N) (fun i => (X i).code) + (fun i => (rows i, (move i).update S.d (X i).trail)) (fun _ => 1) + (size + applyCost S T N) := by + have left : Circuit F (S.format T) T.format Prod.fst ((S.format T).width + 2 * T.format.width) := + Circuit.project Sum.inl (fun _ _ => rfl) + have cmd := (Computes.of_map (L := L) (x := fun i => (X i).code) (y := fun i => (X i).rows) + (Map.circuit hv left) (fun _ => rfl)).comp commands + simp only [one_mul] at cmd + have sent := Computes.of_map (L := L) (x := fun i => (X i).code) (y := fun i + => (move i).received (X i).trail) + (Map.circuit hv (copy_net (S := S) (T := T) (N := N) parent)) (by + intro i + unfold Trail.Move.received + rw [hn] + rfl) + refine (Trail.carry hv S.d move (fun i => (X i).trail) cmd sent).mono ?_ + unfold applyCost + omega + +open Phase.Case in +theorem applyCost_bound {b d : ℕ} {N : Phase.Case F b d → Template F} {δ : Phase.Case F b d → ℕ} + (H : Child N δ) : Cost (fun i => applyCost i.S i.T (N i)) := by + have hz : Short (fun _ : Phase.Case F b d => 2 ^ 0) := short_const 1 + have hm := H.receipts (k := fun _ => 0) hz + have ht := H.carry (k := fun _ => 0) hz Child.parent.full + exact (((Child.parent.full.scale 8).add (Child.parent.format.scale 8)).add (hm.scale 8)).add ht + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Uniform parameter bounds for a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore + +open Packing Assembly Assembly.History Phase Phase.Case Coloring +variable {F : Type} [Field F] {Y l : ℕ} (P : Rotor F Y l) (Δ t d : ℕ) +local notation "I" => Case F 1 d + +theorem spans_bound : Base (fun i : I => 2 ^ e t i.R) := + ((base_const (gain t)).mul load).exp_clog + +theorem history_factor : Base (fun i : I => 2 ^ i.S.discount * (gain t * i.R.load)) := + discount.mul ((base_const (gain t)).mul load) + +theorem meter_bound : Base (fun i : I => (meter i.S t i.R).count) := by + refine (base_const 3).mul (((history_factor t d).add Phase.Case.units).mono fun i => ?_) + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_add] + let n := 2 ^ i.S.discount * (gain t * i.R.load) + calc + n * i.S.U + 1 ≤ (n + 1) * (1 + i.S.U) := by + simp only [add_mul, mul_add, mul_one, one_mul] + omega + _ ≤ _ := Nat.mul_le_mul Nat.lt_two_pow_self (Nat.le_pow_clog (by decide) _) + +theorem child_degree (i : I) : Reset.Child.width (degreeBound i.S i.T Δ) Y i.T.full = 2 := by + simp only [Reset.Child.width, i.h.core, Bool.false_eq_true, ↓reduceIte] + +theorem child_factor : Base (fun i : I => 2 ^ Reset.Child.extra P Δ i.n) := + tiles.exp_add (base_const (2 ^ Nat.clog 2 (resetPositions P Δ))) + +variable [Fintype F] + +theorem added_bound (Y : ℕ) : Rate (fun i : I => added i.S i.T Δ t i.R Y) := by + apply reset_added _ (spans_bound t d).rate + · simpa only [Reset.Book.lenBits, History.lengthBits, Finset.card_singleton] using + (rate_const (Nat.clog 2 (1 + 3)) : Rate (fun _ : I => _)) + · exact (rate_const 2).mono fun i => (child_degree Δ d i).le + +theorem bits_bound : ∃ k : ℕ, ∀ i : I, + (next P i.S i.T i.u Δ t i.R i.a).scheme.ℓ ≤ (1 + i.R.tag) * i.rate ^ k := by + obtain ⟨k, h⟩ := ((added_bound (F := F) Δ t d Y).add (history_factor t d).rate).bound + refine ⟨k, fun i => ?_⟩ + let n := added i.S i.T Δ t i.R Y + let f := 2 ^ i.S.discount * (gain t * i.R.load) + calc + _ = n + i.R.tag * f := by + change (Post.record _ _ _ (.addr _)).width = _ + simp only [n, f, added, book, Reset.Book.make, cap, Post.record, Post.headerFmt, + Format.width_pair, + Format.width_addr, add_assoc] + _ ≤ (1 + i.R.tag) * (n + f) := by simp only [add_mul, mul_add, one_mul]; omega + _ ≤ _ := Nat.mul_le_mul_left _ (h i) + +theorem child_bound : Case.Child (fun i : I => next P i.S i.T i.u Δ t i.R i.a) + (fun i => Reset.Child.extra P Δ i.n) := by + obtain ⟨k, h⟩ := bits_bound P Δ t d + have hb := (((short_const 1).add tags).mul ((Poly.of_le short_two rate_short).pow k)).mono h + refine ⟨fun _ => Nat.sub_le .., fun _ => le_rfl, (child_factor P Δ d).rate.short, fun _ => rfl, + (spans_bound t d).rate.short, ?_, hb, (meter_bound t d).rate.short⟩ + exact (short_const (2 ^ 2)).mono fun i => (congrArg (2^·) (child_degree Δ d i)).le + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Width of a local reset decision -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Packing Assembly Assembly.History.Reset Phase Phase.Case Coloring + +variable {F : Type} [Field F] {Y l : ℕ} (P : Rotor F Y l) (Δ t d : ℕ) +local notation "I" => Case F 1 d + +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev keyBits (i : I) := Nat.clog 2 (i.height + 1) +/-- The quantity computed by `i.n + 8`. -/ +abbrev depth (i : I) := i.n + 8 +/-- Uses `History.Reset.Child.extra P Δ i.n` as the representation. -/ +abbrev expansion (i : I) := History.Reset.Child.extra P Δ i.n + +theorem walks_bound : Short (fun i : I => 2 ^ ((i.T.scheme.d + 1) * depth d i)) := by + have h : Short (fun i : I => 2 ^ (i.n + 8)) := tiles.rate.short.exp_add (short_const (2 ^ 8)) + refine (h.pow (d + 1)).mono fun i => ?_ + rw [← pow_mul, mul_comm (i.n + 8)] + exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ (Nat.add_le_add_right i.h.degree + 1)) + +theorem mask_bound : Short (fun i : I => (Tile.coincides i.T.scheme.d (depth d i)).width) := by + refine ((walks_bound (F := F) d).mul (walks_bound d)).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_bit, mul_one] + +theorem stats_bound : Short (fun i : I => (i.T.Statistics (keyBits d i)).width) := by + have hc : Short (fun i : I => i.T.CountBits) := + (spans.short.of_exp.add (short_const 1)).add height_short + refine (((height_short.add (short_const 1)).clog).add (Case.slots.rate.short.mul hc)).mono fun i + => ?_ + rw [Format.width_pair, Format.width_vec, Format.width_addr, Format.width_addr] + +theorem row_bound : Short (fun i : I => (Tile.row i.T i.a (keyBits d i)).width) := by + have hf : Short (fun i : I => (Group.Flags i.T.scheme.d).width) := by + refine (Case.slots.rate.short.mul (short_const 2)).mono fun i => ?_ + rw [Format.width_vec, Format.width_pair, Format.width_bit] + refine ((stats_bound d).add (hf.add (tiles.rate.short.mul data_short))).mono fun i => ?_ + rw [Format.width_pair, Format.width_pair (Group.Flags _), Format.width_vec (i.T.scheme.h - i.a)] + +theorem history_bound : + Short (fun i : I => (Window.Walks (depth d i) i.T.scheme.d (Tile.row i.T i.a (keyBits d + i))).width) := by + refine ((walks_bound d).mul (row_bound d)).mono fun i => ?_ + rw [Format.width_vec] + +theorem sample_bound : Short (fun i : I => + (Tile.sample i.T i.a (keyBits d i) (depth d i) (expansion P Δ d i)).width) := by + have extra := (child_factor P Δ d).rate.short.of_exp + have start := (short_const 1).add extra + have end' := (mask_bound (F := F) d).add (history_bound d) + refine (start.add ((height_short.add Case.groups.rate.short).add end')).mono fun i => ?_ + simp only [Tile.sample, Format.width_pair, Format.width_addr] + rfl + +variable [Fintype F] + +/-- Uses `next P i.S i.T i.u Δ t i.R i.a` as the representation. -/ +abbrev child (i : I) := next P i.S i.T i.u Δ t i.R i.a + +theorem answer_bound : Short (fun i : I => (Tile.output i.T (child P Δ t d i)).width) := by + have h := child_bound P Δ t d + have s : Short (fun i : I => (Trail.pointer i.T.scheme 0).width) := by + refine ((short_const 1).add (height_short.add spans.short.of_exp)).mono fun i => ?_ + simp only [Trail.pointer, Format.width_pair, Format.width_addr, i.h.single] + rw [Format.width_bit, Format.width_addr 0, zero_add, zero_add] + refine ((h.bits.add h.count).add (h.spans.mul s)).mono fun i => ?_ + rw [Format.width_pair, Format.width_pair, Format.width_addr, Format.width_addr, + Format.width_vec, Format.width_vec, show (child P Δ t d i).scheme.k = 0 from rfl, pow_zero, + one_mul] + +theorem printWidth_bound : Short (fun i : I => + Tile.printWidth i.T (child P Δ t d i) (keyBits d i) (depth d i) (expansion P Δ d i)) := + (sample_bound P Δ d).add (answer_bound P Δ t d) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Budgeting the selection of a mixer from position profiles -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Phase Phase.Case Coloring + +variable {F : Type} [Field F] (Δ d : ℕ) +local notation "I" => Case F 1 d +local notation "K" => keyBits d + +theorem indices_bound : Short (fun i : I => indices i.S i.r i.R Δ) := by + have h : Base (fun i : I => i.base) := Poly.of_le base_two (fun _ => le_rfl) + exact h.rate.short.add (short_const (4 * (Template.Encodes.margin Δ) ^ 2)) + +theorem keys_bound : Short (fun i : I => 2 ^ (K i)) := + (height_short.add (short_const 1)).exp_clog + +theorem cols_bound : Short (fun i : I => 2 ^ i.T.widthCols) := + Case.slots.rate.short.exp_add (short_const (2 ^ 1)) + +theorem profile_arity : Short (fun i : I => + Mixing.arity i.T.widthCols i.height (K i) i.T.profileBits (indices i.S i.r i.R Δ)) := + mixer_arity (cols_bound d) (keys_bound d) (indices_bound Δ d) (Case.bits.add counters) + +theorem profile_cost : Cost (fun i : I => + Mixing.extractionCost i.m i.T.widthCols i.height (K i) i.T.profileBits (indices i.S i.r i.R Δ) + + Mixing.cost (i.m + i.T.widthCols) i.height (K i) (indices i.S i.r i.R Δ)) := + (mixer_extract (cols_bound d) (keys_bound d) (indices_bound Δ d) (Case.bits.add counters)).add + (mixer_cost (cols_bound d) (keys_bound d) (indices_bound Δ d)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Bounds for gathering a reset window -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Packing Assembly Assembly.History.Reset Phase Phase.Case Coloring + +variable {F : Type} [Field F] {Y l : ℕ} (P : Rotor F Y l) (Δ t d : ℕ) +local notation "I" => Case F 1 d +local notation "keys" => keyBits d +local notation "walk" => depth d + +theorem pair_budget {A B : I → Format} + (h : Cost (fun i => (A i).width)) (k : Cost (fun i => (B i).width)) : + Cost (fun i => ((A i).pair (B i)).width) := + (h.add k).mono fun _ => (Format.width_pair ..).le + +private theorem vec_budget {A : I → Format} (h : Phase.Case.Row (fun i => (A i).width)) : + Cost (fun i => (Format.vec i.m (A i)).width) := + h.hosts.mono fun _ => (Format.width_vec ..).le + +private theorem height_budget : Cost (fun i : I => (Format.addr i.height).width) := by + refine height_short.long.row.cost.mono fun i => ?_ + rw [Format.width_addr] + +theorem pair_bound : Cost (fun i : I => (Tile.pair i.T (keys i)).width) := + pair_budget d Case.Child.parent.format (pair_budget d (height_budget d) (vec_budget d + (stats_bound d).long.row)) + +theorem window_groups {A : I → Format} (h : Short (fun i => (A i).width)) : + Cost (fun i : I => (Fmt.groups i.m i.T.scheme.d i.a (A i)).width) := by + have hc : Long (fun i : I => 2 ^ i.T.scheme.d * i.m) := Case.slots.rate.short.long.mul hosts + refine (Phase.Case.Row.hosts (hc.row.add h.groups)).mono fun i => ?_ + exact (Fmt.width_rows ..).le + +private theorem data_budget : Cost (fun i : I => (Mixing.Data i.height (Tile.data i.T) i.m).width) + := by + refine (data_short.blocks.hosts).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec] + +private theorem groups_budget : Cost (fun i : I => (Mixing.Groups i.height i.a (Tile.data i.T) + i.m).width) := by + refine (Phase.Case.Row.hosts (Short.groups (tiles.rate.short.mul data_short))).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_vec] + +theorem packet_bound : Cost (fun i : I => Tile.packetCost i.T i.a (keys i)) := by + have h₁ := pair_budget d (height_budget (F := F) d) (data_budget d) + have h₂ := window_groups d (row_bound (F := F) d) + exact MixedCost.resetPacket (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (pair_bound d) h₁ (groups_budget d) h₂ (apply_bound d) + +theorem maskCost_bound : Cost (fun i : I => Tile.maskCost i.T (walk i)) := by + have h : Long (fun i : I => (100 + (i.m + 2 ^ ((i.T.scheme.d + 1) * walk i))) ^ 50) := + ((long_const 100).add (hosts.add (walks_bound d).long)).pow 50 + exact Case.Child.parent.format.add (Mixed.long Case.m h) + +variable [Fintype F] +local notation "dest" => child P Δ t d +local notation "shift" => expansion P Δ d + +theorem carry_blocks {A : I → Format} (h : Short (fun i => (A i).width)) : + Cost (fun i : I => (Format.vec (dest i).scheme.m (.vec (dest i).scheme.h (A i))).width) := by + have H := child_bound P Δ t d + refine (H.cost (H.layer h)).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec] + +/-- The quantity computed by `Beat.accessCost (i.m + i.T.scheme.d) (Tile.volume i.T (dest i) +(keys i) (walk i))`. -/ +def readCost (i : I) := Beat.accessCost (i.m + i.T.scheme.d) (Tile.volume i.T (dest i) (keys i) + (walk i)) + +theorem windowCost_bound : Cost (fun i : I => + Tile.windowCost i.T (dest i) (keys i) (walk i) (shift i) (readCost P Δ t d i)) := by + have hc : Cost (fun i : I => (Tile.gathered i.T (dest i) (keys i) (walk i)).width) := + pair_budget d (pair_bound d) (pair_budget d (vec_budget d (mask_bound d).long.row) + (window_groups d (history_bound d))) + have hquery := carry_blocks P Δ t d (sample_bound P Δ d) + have hv : Phase.Case.Row (fun i : I => Tile.volume i.T (dest i) (keys i) (walk i)) := + (history_bound d).groups + have hread := Beat.read_bound 1 d Case.slots.rate.short hv + have hsteps : Short (fun i : I => walk i + 1) := + (tiles.rate.short.of_exp.add (short_const 8)).add (short_const 1) + exact MixedCost.resetWindow (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (pair_bound d) (packet_bound d) (maskCost_bound d) hc hquery (hread.left hsteps) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Cost of accumulating the summaries, propagating depths and electing the mixer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Phase Phase.Case Coloring Template + +variable {F : Type} [Field F] (Δ t d : ℕ) +local notation "I" => Case F 1 d +local notation "K" => keyBits d +private abbrev digits (Δ d : ℕ) (i : Case F 1 d) := indices i.S i.r i.R Δ +local notation "D" => digits Δ d + +private theorem counterBits : Short (fun i : I => i.T.CounterBits) := + spans.short.of_exp.add (short_const 1) + +private theorem headWidth : Short (fun i : I => (Mix.Heads i.T (K i)).width) := by + refine ((cols_bound d).mul ((short_const 1).add ((short_const 1).add (keys_bound d).of_exp))).mono + fun i => ?_ + simp only [Mix.Heads, Mixing.Header, Format.width_vec, Format.width_pair, Format.width_addr] + exact le_rfl + +private theorem windowWidth : Short (fun i : I => (Mix.Window i.T (K i)).width) := by + have a : Short (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.rate.short + have k := (keys_bound (F := F) d).of_exp + refine ((short_const 1).add ((a.mul (short_const 2)).add (k.add (a.mul k)))).mono fun i => ?_ + simp only [Mix.Window, Group.Flags, Mixing.Num, Format.width_vec, Format.width_pair, + Format.width_addr] + exact le_rfl + +private theorem summandWidth : Short (fun i : I => (i.T.Summand (D i)).width) := by + refine ((indices_bound Δ d).add (Case.slots.rate.short.mul (counterBits d))).mono fun i => ?_ + rw [Format.width_pair, Format.width_addr, Format.width_vec, Format.width_addr] + +theorem summaryWidth : Short (fun i : I => Mix.arity i.T (K i) (indices i.S i.r i.R Δ)) := by + have a := ((short_const 3).add (data_short (F := F) (d := d))).add (summandWidth Δ d) + have b := (a.add ((indices_bound Δ d).add height_short)).add (keys_bound d).of_exp + exact ((((b.add (windowWidth d)).add (headWidth d)).add (Case.bits.add counters)).add + (profile_arity Δ d)) + +private theorem vecSize {A : I → Format} (h : Phase.Case.Row (fun i => (A i).width)) : + Cost (fun i => (Format.vec i.m (A i)).width) := + h.hosts.mono fun _ => (Format.width_vec ..).le + +private theorem sourceSize : Cost (fun i : I => (Mix.Sources i.T).width) := by + refine data_short.blocks.hosts.mono fun i => ?_ + rw [Format.width_vec, Format.width_vec] + +private theorem callWidth : Short (fun i : I => 1 + Mix.arity i.T (K i) (D i)) := + (short_const 1).add (summaryWidth Δ d) + +private theorem tallySize : Cost (fun i : I => Mix.tallyCost i.T (K i) (D i)) := by + have hd := (summandWidth (F := F) Δ d).blocks + have h₁ : Phase.Case.Row (fun i : I => (Mix.Digits i.T (D i)).width) := + hd.mono fun _ => (Format.width_vec ..).le + have h₂ : Phase.Case.Row (fun i : I => (Mix.Split i.T (D i)).width) := by + refine hd.mono fun i => ?_ + simp only [Mix.Split, Summand, Mixing.Matrix, Mixing.Num, Format.width_pair, Format.width_vec, + Format.width_addr, mul_add, le_refl] + have c := counterBits (F := F) d + have hs := Short.blocks (((short_const 3).mul c).add (((short_const 100).add c).pow 5)) + have ht : Phase.Case.Row (fun i : I => Mixing.collectCost i.height i.T.scheme.d i.T.CounterBits) + := by + refine (hs.left Case.slots.rate.short).mono fun i => ?_ + rw [Mixing.collectCost, mul_assoc] + have hw := callWidth (F := F) Δ d + have hb := Short.blocks (((short_const 100).add (indices_bound (F := F) Δ d)).pow 5) + exact Mix.tallyCost_mixed (large := Case.long) (small := Case.short) + (F := (fun _ => F)) (T := fun i : I => i.T) + (k := K) (d := D) (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + Case.Child.parent.format (sourceSize d) h₁ h₂ hw.blocks hw.long.row hb ht + +private theorem depthSize : Cost (fun i : I => (i.T.Depths (K i)).width) := by + refine (Mixed.long Case.m (Short.long (keys_bound d).of_exp)).mono fun i => ?_ + rw [Format.width_vec, Format.width_addr] + +private theorem netSize : Cost (fun i : I => (i.T.NetworkDepths (K i)).width) := + pair_budget d Case.Child.parent.format (depthSize d) + +private theorem travelSize : Cost (fun i : I => (Mix.Travel i.T (K i)).width) := + pair_budget d (netSize d) (depthSize d) + +private theorem nearSize : Cost (fun i : I => i.T.nearCost (K i)) := by + have hq : Cost (fun i : I => (Format.vec i.T.scheme.d (Perm i.m)).width) := by + refine ((Mixed.long Case.m hosts).left Case.slots.rate.short).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_addr] + have projection := Mix.project_mixed (large := Case.long) (small := Case.short) + (height := Case.height) (hosts := Case.m) + (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (netSize d) (pair_budget d (depthSize d) hq) + have v := (hosts.add (keys_bound (F := F) d).long.of_exp).add Case.slots.rate.short.long + exact Mixed.add projection ((Mixed.long Case.m (((long_const 100).add v).pow 12)).scale 4) + +private theorem gatherSize : Cost (fun i : I => Mix.gatherCost i.T (K i)) := by + have hn : Cost (fun i : I => (i.T.Next (K i)).width) := by + refine (Mixed.long Case.m (Case.slots.rate.short.long.mul (keys_bound d).long.of_exp)).mono fun + i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_addr] + exact Mix.gatherCost_mixed (large := Case.long) (small := Case.short) + (F := (fun _ => F)) (T := fun i : I => i.T) + (height := Case.height) (hosts := Case.m) (k := K) + (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (travelSize d) (netSize d) (nearSize d) hn + (vecSize d (windowWidth d).long.row) + +private theorem waveSize : Cost (fun i : I => Mix.waveCost i.T (K i) (D i) (i.height - t - i.a)) + := by + have hn : Short (fun i : I => i.height - t - i.a) := + height_short.mono (fun i => (Nat.sub_le ..).trans (Nat.sub_le ..)) + exact Mix.waveCost_mixed (large := Case.long) (small := Case.short) + (F := (fun _ => F)) (T := fun i : I => i.T) + (k := K) (d := D) (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (netSize d) (depthSize d) (gatherSize d) + (callWidth Δ d).long.row hn + +private theorem profileSize : Cost (fun i : I => Mix.profileCost i.T (K i) (D i)) := by + have a := (headWidth (F := F) d).long.row + have b : Phase.Case.Row (fun i : I => (Mixing.Num i.height i.T.profileBits).width) := by + refine (Short.blocks (Case.bits.add counters)).mono fun i => ?_ + rw [Format.width_vec, Format.width_addr] + have sides := pair_budget d (vecSize d a) (vecSize d b) + have rows : Cost (fun i : I => (i.T.profileShape (K i)).width) := + vecSize d ((a.add b).mono (fun _ => (Format.width_pair ..).le)) + have w := callWidth (F := F) Δ d + exact Mix.profileCost_mixed (large := Case.long) (small := Case.short) + (F := (fun _ => F)) (T := fun i : I => i.T) + (k := K) (d := D) (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (netSize d) (travelSize d) (gatherSize d) (sourceSize d) + w.long.row w.blocks sides rows + +theorem summaryCost : Cost (fun i : I => + Mix.cost i.T (K i) (indices i.S i.r i.R Δ) (i.height - t - i.a)) := by + exact Mix.cost_mixed (large := Case.long) (small := Case.short) + (F := (fun _ => F)) (T := fun i : I => i.T) + (k := K) (d := D) (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + Case.Child.parent.format (vecSize d (stats_bound d).long.row) + (depthSize d) (netSize d) (tallySize Δ d) (waveSize Δ t d) + (profileSize Δ d) (profile_cost Δ d) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Bounds for the complete dictionary writer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Packing Assembly Assembly.History.Reset Phase Phase.Case Coloring + +variable {F : Type} + +variable [Field F] [Fintype F] {Y l : ℕ} (P : Rotor F Y l) (Δ t d : ℕ) +local notation "I" => Case F 1 d +local notation "keys" => keyBits d +local notation "walk" => depth d +local notation "dest" => child P Δ t d +local notation "shift" => expansion P Δ d + +theorem graph_bound : Cost (fun i : I => (Tile.graph (dest i)).width) := + (child_bound P Δ t d).format.mono (fun i => Tile.graph_width_le (dest i)) + +theorem whole_bound : Cost (fun i : I => (Tile.whole i.T (dest i)).width) := by + have H := child_bound P Δ t d + exact pair_budget d H.format (H.controls (k := fun _ => 0) (short_const 1)) + +theorem printCost_bound {H : I → ℕ} (hs : Cost H) : Cost (fun i : I => + Tile.printCost i.T (dest i) (keys i) (walk i) (shift i) (readCost P Δ t d i) (H i)) := by + have hd := child_bound P Δ t d + have hbody := carry_blocks P Δ t d (answer_bound P Δ t d) + have hg := hd.cost (hd.layer ((short_const 1).add (printWidth_bound P Δ t d))) + exact MixedCost.resetPrint (fun i => i.long_two) (fun i => i.short_two) (fun i => i.short_long) + (pair_bound d) hs (windowCost_bound P Δ t d) hg + (pair_budget d (graph_bound P Δ t d) hbody) (whole_bound P Δ t d) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Charging relative headers to short records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Packing Assembly Assembly.History.Reset Phase Phase.Case Coloring + +variable {F : Type} [Field F] [Fintype F] {Y l : ℕ} (P : Rotor F Y l) (Δ t d : ℕ) +local notation "I" => Case F 1 d +local notation "keys" => keyBits d +local notation "walk" => depth d +local notation "dest" => child P Δ t d +local notation "shift" => expansion P Δ d + +theorem vertex_bound : Short (fun i : I => (Tile.vertexFormat i.T (dest i) (keys i) (walk i) (shift + i)).width) := by + refine ((short_const 1).add (sample_bound P Δ d)).mono fun i => ?_ + rw [Format.width_pair, Format.width_bit] + +theorem suffix_bound : Short (fun i : I => (History.Reset.Child.Suffix i.T.scheme.d (shift i) (dest + i).scheme.d).width) := by + have H := child_bound P Δ t d + have addr := ((Case.slots.rate.short.of_exp.add (short_const 1)).add H.growth.of_exp) + refine ((short_const 2).add (H.neighbors.mul ((short_const 2).add addr))).mono fun i => ?_ + simp only [History.Reset.Child.Suffix, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit] + rw [Format.width_addr] + +theorem headerWidth_bound : Short (fun i : I => Tile.headerWidth i.T (dest i) (keys i) (walk i) + (shift i)) := + (vertex_bound P Δ t d).add (suffix_bound P Δ t d) + +theorem request_bound : Cost (fun i : I => (Tile.request i.T (dest i) (keys i) (walk i) (shift + i)).width) := by + have nav : Cost (fun i : I => (Neighborhood.Rows i.m i.T.scheme.d).width) := by + refine (Mixed.long Case.m (Case.slots.rate.short.long.mul hosts)).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_addr] + have keys' : Cost (fun i : I => + (Format.vec (i.m + shift i) (Tile.vertexFormat i.T (dest i) (keys i) (walk i) (shift + i))).width) := by + refine ((vertex_bound P Δ t d).long.row.expand (child_factor P Δ d).rate.short).mono fun i => ?_ + rw [Format.width_vec] + exact pair_budget d nav keys' + +theorem keyCost_bound : Cost (fun i : I => + Tile.headerCost i.T (dest i) (keys i) (walk i) (shift i) (readCost P Δ t d i)) := by + have query := carry_blocks P Δ t d (sample_bound P Δ d) + have init := (((pair_bound d).add query).add (request_bound P Δ t d)).scale 100 + have gate := ((short_const 1).add (headerWidth_bound P Δ t d)) + exact (init.add (windowCost_bound P Δ t d)).add + ((Short.long gate).row.expand (child_factor P Δ d).rate.short) + +theorem headerCost_bound : Cost (fun i : I => + Tile.headerCost i.T (dest i) (keys i) (walk i) (shift i) (readCost P Δ t d i) + + 4 * History.Reset.Child.buildCost i.m i.T.scheme.d (shift i) (dest i).scheme.d) := by + have old : Long (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.rate.short.long + have H := child_bound P Δ t d + have grow : Long (fun i : I => 2 ^ shift i) := H.growth.long + have new : Long (fun i : I => 2 ^ (dest i).scheme.d) := H.neighbors.long + have build := History.Reset.Child.buildCost_mixed + (large := Case.long) (small := Case.short) + (height := Case.height) (hosts := Case.m) + (fun i => i.long_two) hosts old grow new + exact (keyCost_bound P Δ t d).add (Mixed.scale build 4) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/Elect.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/Elect.lean new file mode 100644 index 0000000000..b7962132d7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/Elect.lean @@ -0,0 +1,955 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Ports.Eval +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Phase.ResetRate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Mixer.Apply +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Plan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.Rule +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.HeaderCost + +/-! # The common template and label capacity for a reset -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore + +open Packing Assembly Assembly.History +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y l : ℕ} (P : Rotor F Y l) + (S : Setup F x y) (T : Template F) (u Δ t : ℕ) (R : Budget) (a : ℕ) + +/-- The quantity computed by `89 * 2 ^ t`. -/ +def gain := 89 * 2 ^ t +/-- The least binary width whose power of two reaches the stated size. -/ +def e := Nat.clog 2 (gain t * R.load) +/-- The least binary width whose power of two reaches the stated size. -/ +def c := Nat.clog 2 (2 ^ S.discount * (gain t * R.load) * S.U + 1) + +/-- The quantity computed by `Template.Meter.bounded (c S t R) 1 (1 / (2 : ℝ) ^ S.discount)`. -/ +abbrev meter := Template.Meter.bounded (c S t R) 1 (1 / (2 : ℝ) ^ S.discount) +/-- The quantity computed by `Reset.overhead T.scheme (e t R) + R.tag * (2 ^ S.discount * (gain +t * R.load))`. -/ +abbrev cap := Reset.overhead T.scheme (e t R) + R.tag * (2 ^ S.discount * (gain t * R.load)) +/-- The value specified by `Reset.Book.make T.scheme u (e t R) (cap S T t R) T.order {S.U}`. -/ +abbrev book := Reset.Book.make T.scheme u (e t R) (cap S T t R) T.order {S.U} +/-- The value specified by `T.reset P Δ (degreeBound S T Δ) a (book S T u t R) (meter S t R)`. -/ +abbrev next := T.reset P Δ (degreeBound S T Δ) a (book S T u t R) (meter S t R) +/-- The added used in the `Restore` construction. -/ +abbrev added (Y : ℕ) := (Post.headerFmt (Reset.Child.width (degreeBound S T Δ) Y T.full) (e t R) + (Reset.Book.lenBits {S.U})).width + Reset.overhead T.scheme (e t R) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Electing a valid reset uniformly over a batch -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Packing Assembly + +open scoped Classical in +/-- The quantity computed by `1 / ((Detour.steps (terminalWidth Δ Y) : ℝ) + 1)`. -/ +def tolerance (Δ Y : ℕ) : ℝ := 1 / ((Detour.steps (terminalWidth Δ Y) : ℝ) + 1) + +open scoped Classical in +/-- The data for the slice construction, including `enough`, `space`, `small`, `core`. -/ +structure Slice (Δ Y l t : ℕ) : Prop where + enough : 4 * coreBins Δ ≤ Y + space : Y ^ 2 * l ≤ 2 ^ t + small : 144 * resetWeight t / (2 : ℝ) ^ t + 4 * (Template.Encodes.margin Δ : ℝ) ^ 2 / (2 : ℝ) ^ t + ≤ tolerance Δ Y + core : 3 ≤ Δ + +open scoped Classical in +theorem exists_slice (Δ Y l : ℕ) (he : 4 * coreBins Δ ≤ Y) (hd : 3 ≤ Δ) : ∃ t, Slice Δ Y l t := by + obtain ⟨t, ht, hs⟩ := small_resetWeight (Template.Encodes.margin Δ) (tolerance Δ Y) + (by unfold tolerance; positivity) (Nat.clog 2 (Y ^ 2 * l)) + exact ⟨t, he, (Nat.clog_le_iff_le_pow (by decide)).mp ht, hs, hd⟩ + +variable {F : Type} [Field F] {x y : Wire} + +open scoped Classical in +/-- The quantity computed by `Phase.base S r R + 4 * (Template.Encodes.margin Δ) ^ 2`. -/ +def indices (S : Setup F x y) (r : ℕ) (R : Budget) (Δ : ℕ) := + Phase.base S r R + 4 * (Template.Encodes.margin Δ) ^ 2 + +variable {S : Setup F x y} {T : Template F} {R : Budget} + {w r u d K Δ Y l t : ℕ} {σ : ℝ} (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) (q : (frame S T u Δ R).state) + +local notation "a" => (T.scheme.h - r) +local notation "D" => degreeBound S T Δ +local notation "W" => ((2 : ℝ) ^ t * (R.load * S.z : ℕ)) +local notation "g" => Template.Encodes.margin Δ +local notation "b" => indices S r R Δ + +include h in +omit [Field F] in +open scoped Classical in +private theorem capacity : 0 < W := by + have := h.vpos.trans_le h.load + positivity + +include h in +omit [Field F] in +open scoped Classical in +private theorem normalized (v : ℝ) (hv : v ≤ (R.load * S.z : ℕ)) : v / W ≤ 1 / (2 : ℝ) ^ t := by + rw [div_le_div_iff₀ (capacity h) (by positivity), one_mul, mul_comm v] + exact mul_le_mul_of_nonneg_left hv (by positivity) + +include h in +omit [Field F] in +open scoped Classical in +theorem unit : (u : ℝ) / W ≤ 1 / (2 : ℝ) ^ t + := normalized h u (Nat.cast_le.mpr h.load) + +include h in +open scoped Classical in +theorem slack (hk : 2 ^ t ≤ K) (q : (frame S T u Δ R).state) : W * + (Fintype.card q.val.G.V * 2 ^ a : ℕ) ≤ σ := by + have hv : Fintype.card q.val.G.V ≤ 2 ^ T.scheme.m := by + simpa using Fintype.card_le_of_injective _ q.val.encodes.post.host.injective + exact BatchDescent.slack_of_width_count (by positivity) h.group hk hv h.slack + +include h in +omit [Field F] in +open scoped Classical in +private theorem limits : + 4 * g ^ 2 < 2 ^ b ∧ 6 * 2 ^ T.scheme.h < 2 ^ b ∧ R.load * S.z * 2 ^ S.discount < 2 ^ b := by + have hbase : 3 + S.h + Nat.clog 2 (1 + S.U) + S.discount + R.load ≤ b := by + unfold indices Phase.base + have := Nat.two_pow_pos r + have := Nat.lt_two_pow_self (n := S.discount) + omega + refine ⟨(Nat.le_add_left ..).trans_lt (Nat.lt_two_pow_self (n := b)), ?_, ?_⟩ + · calc + _ < 2 ^ 3 * 2 ^ T.scheme.h := Nat.mul_lt_mul_of_pos_right (by decide) (by positivity) + _ = 2 ^ (3 + T.scheme.h) := (pow_add ..).symm + _ ≤ _ := Nat.pow_le_pow_right (by decide) (by have := h.height; omega) + · have hz := (Nat.le_of_dvd h.vpos h.divides).trans h.ceiling + have hz' : S.z ≤ 2 ^ Nat.clog 2 (1 + S.U) := + (hz.trans (Nat.le_add_left ..)).trans (Nat.le_pow_clog (by decide) _) + calc + _ < 2 ^ R.load * S.z * 2 ^ S.discount := by + gcongr + · exact h.zpos + · exact Nat.lt_two_pow_self + _ ≤ 2 ^ R.load * 2 ^ Nat.clog 2 (1 + S.U) * 2 ^ S.discount := by gcongr + _ = 2 ^ (R.load + Nat.clog 2 (1 + S.U) + S.discount) := by rw [pow_add, pow_add] + _ ≤ _ := Nat.pow_le_pow_right (by decide) (by omega) + +include h in +open scoped Classical in +private theorem integer (v : q.val.G.V) (i : Cell T.scheme.h) : + ∃ n : Coloring.B b, q.val.G.load v i * (2 ^ S.discount : ℕ) = n.val := by + let G := q.val.G + let c := (v, i) + have hm : G.mass ≤ S.fringe.cap := by + have hp := q.property.mass + have := h.width + exact_mod_cast (show (G.mass : ℝ) ≤ S.cap by linarith only [hp, h.history, this]) + let z := ∑ j, if G.park j = c then 1 else 0 + have hp : push G.park S.fringe.charge c = (z : ℝ) := by + simp only [z, Nat.cast_sum, Nat.cast_ite, Nat.cast_one, Nat.cast_zero, push] + rfl + let n := (G.tetherLoad c + degree G.pair c * u + z) * 2 ^ S.discount + G.past c + have he : G.load v i * (2 ^ S.discount : ℕ) = (n : ℝ) := by + rw [HostNet.load, hp, HostNet.rate, ite_eq_left hm] + change (_ + 1 * (z : ℝ) + (1 / (2 : ℝ) ^ S.discount) * G.past c) * _ = _ + simp only [n, c, Nat.cast_add, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, one_mul] + field_simp + have hn : n ≤ R.load * S.z * 2 ^ S.discount := by + apply (Nat.cast_le (α := ℝ)).mp + rw [← he, Nat.cast_mul, Nat.cast_mul] + exact mul_le_mul_of_nonneg_right (q.property.bounded.2.2 v i) (Nat.cast_nonneg _) + exact ⟨⟨n, hn.trans_lt (limits h).2.2⟩, he⟩ + +include h s hk in +open scoped Classical in +theorem ok : Template.Encodes.Fits (G := q.val.G) a t Δ D g (2 ^ S.discount) + (Nat.clog 2 (T.scheme.h + 1)) b W (tolerance Δ Y) where + corePos := by have := s.core; omega + full := (Nat.le_add_right ..).trans (Nat.le_add_right ..) + late _ := by + have he : 2 ^ S.h ≤ 2 * D := by + unfold degreeBound + have := Nat.two_pow_pos T.scheme.m + have := Nat.two_pow_pos S.h + omega + have ht := (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp + (he.trans (Nat.le_pow_clog (by decide) _)) + have := h.height + omega + gap := by + have := (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp (hk.trans h.room) + have := h.group + omega + depth := Nat.le_pow_clog (by decide : 1 < 2) _ + integer := integer h q + denominator := Nat.two_pow_pos _ + width := h.vpos + margin := by unfold Template.Encodes.margin; have := s.core; positivity + widthLimit := (limits h).1 + weightLimit := (limits h).2.1 + capacity := capacity h + bound v i := normalized h _ (by rw [Nat.cast_mul]; exact q.property.bounded.2.2 v i) + cdeg := q.property.bounded.1 + ndeg := q.property.bounded.2.1 + small := s.small + +open scoped Classical in +/-- Computes the poll by the application `q.val.encodes.elected (ok h s hk q) s.enough s.space +(unit (t := t) h)`. -/ +abbrev poll := q.val.encodes.elected (ok h s hk q) s.enough s.space (unit (t := t) h) + +open scoped Classical in +theorem fits (P : Rotor F Y l) {c : ℝ} (hc : 1 ≤ c) (cost : (Fintype.card P.E : ℝ) ≤ c * Y * l) : + (poll h s hk q).Fits P c where + upper := (ok h s hk q).full + full := q.property.bounded.2.1 + nonneg := zero_le_one.trans hc + cost := cost + small := by + change (Detour.steps (terminalWidth Δ Y) : ℝ) * tolerance Δ Y ≤ 1 + unfold tolerance + rw [mul_one_div, div_le_one (by positivity)] + exact le_add_of_nonneg_right zero_le_one + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- +# Budgeting a common permutation of old blocks + +The permutation table itself is computed once, then broadcast. +The work quadratic in the number of block indices fits in the +host budget. Per host the circuit is linear in the number of indices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore + +open Assembly Phase Phase.Case Coloring + +variable {F : Type} [Field F] {d : ℕ} +local notation "I" => Case F 1 d + +theorem height_short : Short (fun i : I => i.height) := + levels.rate.short.mono fun i => i.h.height + +theorem four_heights (i : I) : 4 * i.height ≤ i.m := by + have ha : i.S.h ≤ i.base := by + unfold Case.base Phase.base + have := Nat.zero_le (2 ^ i.r) + have := Nat.zero_le (2 ^ i.S.discount) + omega + have hb := (((i.h.height.trans ha).trans i.base_rate).trans i.rate_short).trans + ((Nat.le_self_pow i.h.positive.ne' i.short).trans i.h.small) + have hc := i.h.lower + unfold Case.height Case.m + omega + +theorem data_short : Short (fun i : I => (History.Reset.Tile.data i.T).width) := by + simpa only [History.Reset.Tile.data, Format.width_pair, Format.width_addr] using + (Case.bits.add counters : Short (fun i : I => _)) + +theorem application (h m : ℕ) (A : Format) (hh : h ≤ m) : + Mixing.applyCost h A m ≤ + 2 ^ (m + h) * (100 * (1 + h + A.width) ^ 2 + (100 + (h + A.width)) ^ 8) := by + let M := 2 ^ m + let H := 2 ^ h + let a := A.width + let p := (100 + (h + a)) ^ 8 + have hM : 0 < M := by unfold M; positivity + have hH : 0 < H := by unfold H; positivity + have hm : H ≤ M := Nat.pow_le_pow_right (by decide) hh + change h + Install.localCost h * (H * h) + (Mixing.Data h A m).width + (Perm h).width + + (Mixing.Data h A m).width + 2 * (Format.vec m (.pair (.vec h A) (Perm h))).width + + M * (H * p) + 3 * (Mixing.Data h A m).width ≤ _ + simp only [Mixing.Data, Perm, Format.width_vec, Format.width_pair, Format.width_addr, + Install.localCost, + pow_add, pow_one] + change h + (2 * h + 8 * (H * 2)) * (H * h) + M * (H * a) + H * h + M * (H * a) + 2 * (M * (H * a + + H * h)) + + M * (H * p) + 3 * (M * (H * a)) ≤ M * H * (100 * (1 + h + a) ^ 2 + p) + have h₁ := Nat.le_mul_of_pos_left (H * h) hM + have h₂ := Nat.le_mul_of_pos_left (H * h * h) hM + have h₃ := Nat.mul_le_mul_right (H * h) hm + have h₄ := Nat.le_mul_of_pos_left h hH + ring_nf at h₁ h₂ h₃ h₄ ⊢ + omega + +theorem apply_bound (d : ℕ) : Cost (fun i : Case F 1 d => + Mixing.applyCost i.height (History.Reset.Tile.data i.T) i.m) := by + let w (i : Case F 1 d) := (History.Reset.Tile.data i.T).width + have a : Short (fun i : Case F 1 d => 100 * (1 + i.height + w i) ^ 2 + (100 + (i.height + + w i)) ^ 8) := + ((short_const 100).mul ((((short_const 1).add height_short).add data_short).pow 2)).add + (((short_const 100).add (height_short.add data_short)).pow 8) + exact (Mixed.short Case.m a).mono (fun i => application _ _ _ (by have := four_heights i; omega)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- +# Electing a mixer + +All pairwise tests of block indices take place on a single aggregated +array. There are fewer such pairs than host addresses. The only +arithmetic repeated at every block operates on short words. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Phase Phase.Case Coloring + +variable {F : Type} [Field F] {d : ℕ} +local notation "I" => Case F 1 d +variable {g e k s : Case F 1 d → ℕ} + +private theorem once (hg : Long g) : Cost (fun i : I => 2 ^ i.height * g i) := + (Mixed.long Case.m hg).mono fun i : I => Nat.mul_le_mul_right _ + (Nat.pow_le_pow_right (by decide) (by have := four_heights i; omega)) + +private theorem twice (hg : Long g) : Cost (fun i : I => 2 ^ i.height * (2 ^ i.height * g i)) := by + refine (Mixed.long Case.m hg).mono fun i : I => ?_ + rw [← mul_assoc, ← pow_add] + exact Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (by have := four_heights i; omega)) + +private theorem precision (hg : Short g) : Short (fun i : I => Mixing.precision i.height (g i)) := + ((short_const 2).mul (height_short.add hg)).add (short_const 1) + +variable (he : Short (fun i : Case F 1 d => 2 ^ (e i))) (hk : Short (fun i : Case F 1 d + => 2 ^ (k i))) (hg : Short g) + +include he hk hg in +theorem mixer_arity (hs : Short s) : + Short (fun i : I => Mixing.arity (e i) i.height (k i) (s i) (g i)) := by + have h₁ := (short_const 4).mul (precision hg) + have h₂ := hs.add (he.mul hg) + have h₃ := ((short_const 2).add hk.of_exp).add (hk.mul hg) + refine (h₁.add (h₂.add h₃)).mono fun i : I => ?_ + unfold Mixing.arity + omega + +include hk hg in +private theorem row : Phase.Case.Row (fun i : I => Mixing.rowCost i.height (k i) (g i)) := by + let p := precision hg + let a := height_short (F := F) (d := d) + let x (j) := short_const (F := F) (b := 1) (d := d) j + have hcorr : Phase.Case.Row (fun i : I => Mixing.corrCost i.height (g i)) := + Short.blocks ((((x 1).add hg).add p).add ((((x 2).mul a).add (x 3)).mul + ((x 1).add ((x 4).mul p))) |>.add (((x 1).add p).add p)) + have small := Long.row (Short.long (hk.mul hg)) + have hp : Phase.Case.Row (fun i : I => Mixing.pairCost i.height (k i) (Mixing.precision i.height + (g i)) (g i)) := by + refine (((p.blocks.add small).add (((Short.blocks (p.add hg)).left hk).scale 2))).mono fun i : + I => ?_ + simp only [Mixing.pairCost, pow_add, mul_assoc] + exact le_rfl + have hword := p.add hg + have last := (Short.blocks (((x 1).add hword).add hword)).left hk + refine (((hcorr.add (small.scale 4)).add (hp.scale 4)).add last).mono fun i : I => ?_ + simp only [Mixing.rowCost, Mixing.wordLength, pow_add, mul_assoc] + exact le_rfl + +include he hk hg in +private theorem test : Cost (fun i : I => Mixing.testCost (i.m + e i) (k i + + i.height) (g i) i.height) := by + let M := hosts.add (Short.long he.of_exp) + let l := (hg.long.add M) + let c (n) := short_const (F := F) (b := 1) (d := d) n + have hc : Cost (fun i : I => Mixing.collectCost (i.m + e i) (k i + i.height) (g i)) := by + have a := ((c 3).mul hg).add (((c 100).add hg).pow 5) + refine ((Short.blocks a).expand he |>.left hk).mono fun i : I => ?_ + unfold Mixing.collectCost + rw [pow_add] + exact le_of_eq (by ac_rfl) + have hm : Cost (fun i : I => Mixing.maskCost (k i + i.height) i.height (g i + (i.m + e i))) := by + refine (((once l).left hk).add (((twice l).left hk).scale (Install.localCost 1))).mono fun i : + I => ?_ + unfold Mixing.maskCost + rw [pow_add] + exact le_of_eq (by ac_rfl) + let t := height_short (F := F) (d := d) + have h₁ := (twice (((long_const 100).add l).pow 5)).left hk + have h₂ := once (((long_const 100).add (t.long.add (l.add (Short.long (hk.of_exp.add t))))).pow + 42) + refine ((hc.add hm).add (h₁.add h₂)).mono fun i : I => ?_ + unfold Mixing.testCost + rw [mul_add, pow_add] + exact le_of_eq (by ac_rfl) + +include he hk hg in +theorem mixer_cost : Cost (fun i : I => Mixing.cost (i.m + e i) i.height (k i) (g i)) := + ((row hk hg).expand he).add ((test he hk ((precision hg).add hg)).scale 4) + +include he hk hg in +theorem mixer_extract (hs : Short s) : + Cost (fun i : I => Mixing.extractionCost i.m (e i) i.height (k i) (s i) (g i)) := by + let a := (short_const 1).add (mixer_arity he hk hg hs) + have hd := Long.row (Short.long (hk.mul hg)) + have h₁ := ((he.long.row.add ((short_const 1).blocks)).mul a) + have h₂ := ((hd.left he).add (Short.blocks (he.mul hg))) + have h₃ := Phase.Case.Row.expand (hg.blocks.add hd) he + refine ((Phase.Case.Row.hosts h₁).add (((Phase.Case.Row.hosts h₂).add (h₃.scale 2)).scale + 4)).mono fun i : I => ?_ + change _ + 4 * ((Format.vec i.m (.pair (Mixing.Matrix (e i) (k i) (g i)) + (Mixing.Matrix i.height (e i) (g i)))).width + 2 * (Mixing.Rows _ _ _ _).width) ≤ _ + simp only [Mixing.Matrix, Mixing.Rows, Mixing.Input, Mixing.Num, Format.width_vec, + Format.width_pair, + Format.width_addr, mul_one] + exact le_rfl + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- +# A sequence of encoded phases + +The bound on elementary coefficients stays fixed across concatenation. +The rate and additive loss compose affinely. Separate limits keep long +addresses out of the polynomial charged at every block. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} + +/-- The indices are incoming and outgoing core degrees and neighbor +widths, subdivision, step count, and the two affine coefficients. -/ +inductive Sequence (F : Type) [Field F] (K : ℕ) : + ℕ → ℕ → ℕ → ℕ → ℕ → ℕ → ℝ → ℝ → Prop + | one {Δ Δ' d d' b k ρ C} : Phase F Δ Δ' d d' b k ρ C → + 0 < b → 0 < k → k ≤ K → 0 ≤ ρ → 0 ≤ C → 4 + ρ + C ≤ K → + Sequence F K Δ Δ' d d' b 1 ρ C + | comp {Δ Δ' Δ'' d d' d'' b b' n n' ρ ρ' C C'} : + Sequence F K Δ Δ' d d' b n ρ C → Sequence F K Δ' Δ'' d' d'' b' n' ρ' C' → + Sequence F K Δ Δ'' d d'' (b * b') (n + n') (ρ' * ρ) (ρ' * C + C') + | relax {Δ Δ' Δ'' d d' d'' b n ρ ρ' C C'} : + Sequence F K Δ Δ' d d' b n ρ C → Δ' ≤ Δ'' → d' ≤ d'' → ρ ≤ ρ' → C ≤ C' → + Sequence F K Δ Δ'' d d'' b n ρ' C' + +/-- The data for the limits construction, including `m`, `steps`, `w`, `r`, `K`. -/ +structure Limits where + /-- The `Limits` field of type `ℕ`. -/ + m : ℕ + /-- The number of transitions. -/ + steps : ℕ + /-- The `Limits` field of type `ℕ`. -/ + w : ℕ + /-- The `Limits` field of type `ℕ`. -/ + r : ℕ + /-- The `Limits` field of type `ℕ`. -/ + K : ℕ + /-- The `Limits` field of type `ℕ`. -/ + A : ℕ + /-- The initial point of type `Budget`. -/ + start : Budget + /-- The `Limits` field of type `ℝ`. -/ + σ : ℝ + +namespace Limits +variable (L : Limits) +/-- The quantity computed by `(3 * L.A ^ L.K) ^ L.K`. -/ +def extra := (3 * L.A ^ L.K) ^ L.K +/-- The quantity computed by `L.start.tag + L.steps * L.extra`. -/ +def maxTag := L.start.tag + L.steps * L.extra +/-- The quantity computed by `(1 + L.maxTag) * L.extra`. -/ +def code := (1 + L.maxTag) * L.extra +/-- The quantity computed by `4 * L.A ^ L.K + L.code + L.maxTag`. -/ +def small := 4 * L.A ^ L.K + L.code + L.maxTag +/-- The quantity computed by `L.m + L.steps * (L.r + L.K)`. -/ +def host := L.m + L.steps * (L.r + L.K) +/-- The quantity computed by `L.m + h + L.steps * L.K`. -/ +def seats (h : ℕ) := L.m + h + L.steps * L.K +/-- The quantity computed by `2 ^ L.host * (100 + L.w + L.small) ^ L.K + 2 ^ (L.seats h) * +L.small ^ L.K`. -/ +def cost (h : ℕ) := + 2 ^ L.host * (100 + L.w + L.small) ^ L.K + 2 ^ (L.seats h) * L.small ^ L.K +end Limits + +variable (S : Setup F x y) (L : Limits) + +/-- Uniform headroom, established once for the whole sequence. -/ +structure Enough : Prop where + trivalent : S.G.Trivalent + zpos : 0 < S.z + names : S.e ≤ 3 * L.w + positive : 0 < L.K + height : L.steps * L.r ≤ S.h + room : L.K ≤ 2 ^ L.r + lower : L.w ≤ L.m + upper : L.host + L.K * (S.h + 1) ≤ 2 * L.w + basic : 100 + 2 ^ L.r + S.h + Nat.clog 2 (1 + S.U) + 2 ^ S.discount + + L.K ^ L.steps * L.start.load + S.d ≤ L.A + logarithm : Nat.clog 2 (1 + L.code) ≤ L.A ^ L.K + labels : L.small ^ L.K ≤ L.w / 4 + origins : 3 * (L.K ^ L.steps * L.start.reach) ≤ S.d + history : (L.K ^ L.steps : ℕ) * (L.start.mass + L.start.width + (S.fringe.Z + L.σ)) ≤ S.cap + slack : ((L.K * (L.K ^ L.steps * L.start.load * S.z) * 2 ^ (L.seats S.h) : ℕ) : ℝ) + ≤ L.σ * (2 : ℝ) ^ L.r + +/-- Invariants after exactly `i` elementary steps. -/ +structure Inside (T : Template F) (P : Budget) (u d i : ℕ) : Prop where + height : T.scheme.h + i * L.r = S.h + lower : L.w ≤ T.scheme.m + upper : T.scheme.m ≤ L.m + i * (L.r + L.K) + degree : T.scheme.d ≤ d + core : T.full = false + single : T.scheme.k = 0 + spans : 2 ^ T.scheme.e ≤ L.A ^ L.K + counters : T.count ≤ L.A ^ L.K + bits : T.scheme.ℓ ≤ L.code + tag : P.tag ≤ L.start.tag + i * L.extra + capacity : u ≤ P.load * S.z + load : P.load ≤ L.K ^ i * L.start.load + reach : 0 < P.reach + origins : P.reach ≤ L.K ^ i * L.start.reach + width : 0 ≤ P.width + mass : 0 ≤ P.mass + potential : P.mass + P.width + (S.fringe.Z + L.σ) ≤ + (L.K ^ i : ℕ) * (L.start.mass + L.start.width + (S.fringe.Z + L.σ)) + +/-- The data for the completion construction, including `next`, `budget`, `inside`, `width`, +`labels`. -/ +structure Completion (T : Template F) (P : Budget) (u v Δ Δ' d' i n : ℕ) (ρ C : ℝ) where + /-- The successor of each choice of type `Template F`. -/ + next : Template F + /-- The budget of type `Budget`. -/ + budget : Budget + inside : Inside S L next budget v d' (i + n) + width : budget.width ≤ ρ * P.width + C * (S.fringe.Z + L.σ) + /-- The label data of type `Finset (Table F)`. -/ + labels : Finset (Table F) + few : labels.card ≤ n * L.small ^ L.K + small : ∀ k ∈ labels, Processor.arity k ≤ L.small ^ L.K + /-- Stores the scale associated with this `Completion`. -/ + scale : ℕ + /-- The size parameter carried by `Completion`, with type `ℕ`. -/ + size : ℕ + cost : size ≤ n * L.cost S.h + transfer : Transforms F scale (Allowed F L.w ∪ (labels : Set (Table F))) + (frame S T u Δ P) (frame S next v Δ' budget) size + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Choosing one repeatable block of encoded phases + +Use the same gadget, subdivision and reset rotor for the quantitative +reduction and for the encoded sequence. The neighbor allowance after +reset is chosen before fixing the incoming allowance. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Packing + +/-- The condition `∀ (P : Gadget F) Δ, 3 ≤ Δ → ∀ d, ∃ d' K, 0 < K ∧ Phase F Δ (Δ ^ degreePower) +d d' P.b K P.ratio 1` on the specified data. -/ +def SubroundRule (F : Type) [Field F] : Prop := + ∀ (P : Gadget F) Δ, 3 ≤ Δ → ∀ d, ∃ d' K, 0 < K ∧ + Phase F Δ (Δ ^ degreePower) d d' P.b K P.ratio 1 + +/-- The reset rule of type `Prop` for the given inputs. -/ +def ResetRule (F : Type) [Field F] : Prop := + ∀ (y w Δ : ℕ) (R : Rotor F (2 ^ y) w) (c : ℝ), 0 < w → 3 ≤ Δ → 4 * coreBins Δ ≤ 2 ^ y → + 1 ≤ c → (Fintype.card R.E : ℝ) ≤ c * (2 : ℝ) ^ y * w → + ∃ d', ∀ d, ∃ K, 0 < K ∧ Phase F Δ 3 d d' 1 K (2 * resetWidth c w) (2 * resetWidth c w) + +variable {F : Type} [Field F] +namespace Sequence + +variable {Δ Δ' d d' b n K K' : ℕ} {ρ C : ℝ} + +theorem enlarge (q : Sequence F K Δ Δ' d d' b n ρ C) (hk : K ≤ K') : + Sequence F K' Δ Δ' d d' b n ρ C := by + induction q with + | one g hb hp hu hρ hc hm => exact .one g hb hp (hu.trans hk) hρ hc (hm.trans (Nat.cast_le.mpr + hk)) + | comp _ _ ih ih' => exact ih.comp ih' + | relax _ hΔ hd hρ hc ih => exact ih.relax hΔ hd hρ hc + +private theorem single {k : ℕ} (q : Phase F Δ Δ' d d' b k ρ C) (hb : 0 < b) (hk : 0 < k) + (hρ : 0 ≤ ρ) (hc : 0 ≤ C) : ∃ K, Sequence F K Δ Δ' d d' b 1 ρ C := + ⟨max k ⌈4 + ρ + C⌉₊, .one q hb hk (le_max_left _ _) hρ hc + ((Nat.le_ceil _).trans (Nat.cast_le.mpr (le_max_right _ _)))⟩ + +private theorem contractions (φ : SubroundRule F) (P : Gadget F) (Δ d : ℕ) + (hΔ : 3 ≤ Δ) (t : ℕ) (ht : 0 < t) : + ∃ d' K, Sequence F K Δ (Δ ^ (degreePower ^ t)) d d' (P.b ^ t) t (P.ratio ^ t) t := by + have hp : 0 < degreePower := by decide + have group (Δ d : ℕ) (hΔ : 3 ≤ Δ) : + ∃ d' K, Sequence F K Δ (Δ ^ degreePower) d d' P.b 1 P.ratio 1 := by + obtain ⟨d', k, hk, hq⟩ := φ P Δ hΔ d + exact ⟨d', single hq P.pos hk P.ratio_bounds.1 zero_le_one⟩ + induction t, ht using Nat.le_induction with + | base => simpa only [pow_one, Nat.cast_one] using group Δ d hΔ + | succ t _ ih => + obtain ⟨e, K, p⟩ := ih + obtain ⟨d', K', q⟩ := group (Δ ^ (degreePower ^ t)) e (hΔ.trans (Nat.le_self_pow (by + positivity) _)) + refine ⟨d', max K K', ?_⟩ + have h := (p.enlarge (le_max_left K K')).comp (q.enlarge (le_max_right K K')) + rw [← pow_mul Δ (degreePower ^ t) degreePower, ← pow_succ degreePower, ← pow_succ P.b, + ← pow_succ' P.ratio] at h + refine h.relax le_rfl le_rfl le_rfl ?_ + rw [Nat.cast_add, Nat.cast_one] + exact add_le_add_left (mul_le_of_le_one_left (Nat.cast_nonneg _) P.ratio_bounds.2.le) _ + +private theorem iterate (p : Sequence F K Δ Δ d d b n (1 / 2) C) (hC : 0 ≤ C) + (j : ℕ) (hj : 0 < j) : Sequence F K Δ Δ d d (b ^ j) (n * j) ((1 / 2) ^ j) (2 * C) := by + induction j, hj using Nat.le_induction with + | base => + simp only [Nat.succ_eq_add_one, Nat.zero_add, pow_one, mul_one] + exact p.relax le_rfl le_rfl le_rfl (by linarith) + | succ j _ ih => + rw [pow_succ b, Nat.mul_succ, pow_succ' (1 / 2 : ℝ)] + exact (ih.comp p).relax le_rfl le_rfl le_rfl (by linarith) + +end Sequence + +theorem sequence_recipe (ht : ¬Tagged.Hard F) (hgroup : SubroundRule F) (hreset : ResetRule F) : + ∃ (P : Recipe F) (K d : ℕ), 0 < K ∧ 3 ≤ d ∧ 4 ^ (P.n * (K + 2) + K + 2) ≤ P.H ∧ + ∀ j : ℕ, 0 < j → Sequence F K 8 8 d d (P.b ^ j) (P.n * j) ((1 / 2) ^ j) P.C := by + obtain ⟨P⟩ := gadget_exists F + obtain ⟨t, y, w, R, c, ht, hw, hc, hsize, en, hdecay⟩ := + choose_rotor (.inr ht) 8 degreePower P.ratio 250 P.ratio_bounds.1 P.ratio_bounds.2 (by norm_num) + let D := 8 ^ (degreePower ^ t) + have : 0 < degreePower := by decide + have hD : 3 ≤ D := (show 3 ≤ 8 by decide).trans (Nat.le_self_pow (by positivity) _) + have enough : 4 * coreBins D ≤ 2 ^ y := by simpa only [coreBins, mul_assoc] using en D le_rfl + have hR : (Fintype.card R.E : ℝ) ≤ c * (2 : ℝ) ^ y * w := + (le_add_of_nonneg_left (Nat.cast_nonneg _)).trans hsize + let r := 2 * resetWidth c w + have hr : 0 ≤ r := by unfold r resetWidth; positivity + have bound : r ≤ 250 * (1 + c + Nat.clog 2 w) := by + unfold r resetWidth + linarith [Nat.cast_nonneg (α := ℝ) (Nat.clog 2 w)] + have decrease := (mul_le_mul_of_nonneg_right bound (pow_nonneg P.ratio_bounds.1 t)).trans hdecay + let b := P.b ^ t * 1 + let n := t + 1 + let e := degreePower ^ t * (900 + 2 ^ y + 1) + let C := r * t + r + obtain ⟨X, g⟩ := Reduction.subrounds P 8 (by decide) t ht + obtain ⟨Y, q⟩ := Reduction.reset R (by positivity) hw hD enough c (by linarith) (by simpa using + hR) + let H₀ := Reduction.fee X (P.ratio ^ t) t * Y + have step : Reduction F 8 3 b n e H₀ (1 / 2) C := + ((g F).comp (q F)).relax le_rfl decrease le_rfl + obtain ⟨d', reset⟩ := hreset y w D R c hw hD enough hc hR + let d := max 3 d' + obtain ⟨v, k, hg⟩ := Sequence.contractions hgroup P 8 d (by decide) t ht + obtain ⟨k', hk, hq⟩ := reset v + obtain ⟨l, hl⟩ := Sequence.single hq (by decide) hk hr hr + let K := max k l + 1 + have seq : Sequence F K 8 8 d d b n (1 / 2) C := + ((hg.enlarge (show k ≤ K by unfold K; omega)).comp (hl.enlarge (by unfold K; omega))).relax + (by decide) (le_max_right _ _) decrease le_rfl + let H := max (Reduction.fee H₀ (1 / 2) C) (4 ^ (n * (K + 2) + K + 2)) + let recipe : Recipe F := ⟨b, n, e, H, 2 * C, fun j hj => + (step.iterate (by decide) (by unfold e; positivity) j hj).relax + (Nat.pow_le_pow_left (le_max_left _ _) j) le_rfl le_rfl⟩ + exact ⟨recipe, K, d, by unfold K; omega, le_max_left _ _, le_max_right _ _, seq.iterate step.loss⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Checking headroom at each phase boundary -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Assembly Packing + +variable {F : Type} {x y : Wire} {S : Setup F x y} {T : Template F} + {L : Limits} {P : Budget} {u d i k b v : ℕ} + +theorem Enough.pos (H : Enough S L) : 0 < L.A := lt_of_lt_of_le (by positivity) H.basic + +namespace Inside + +variable (D : Inside S L T P u d i) (H : Enough S L) (h : i ≤ L.steps) +include D h + +theorem hosts : T.scheme.m ≤ L.host := + D.upper.trans (Nat.add_le_add_left (Nat.mul_le_mul_right _ h) _) + +theorem seats : T.scheme.m + T.scheme.h ≤ L.seats S.h := by + have ht := D.upper + rw [mul_add] at ht + have hh := D.height + have hi := Nat.mul_le_mul_right L.K h + unfold Limits.seats + omega + +theorem tags : P.tag ≤ L.maxTag := + D.tag.trans (Nat.add_le_add_left (Nat.mul_le_mul_right _ h) _) + +include H + +theorem loads : P.load ≤ L.K ^ L.steps * L.start.load := + D.load.trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right H.positive h)) + +theorem base : Phase.base S L.r P ≤ L.A := by + have := D.loads H h + have := H.basic + unfold Phase.base + omega + +theorem rate : Phase.rate S T L.r P ≤ 3 * L.A ^ L.K := by + have ha := (D.base H h).trans (Nat.le_self_pow H.positive.ne' L.A) + have hs := D.spans + have ht := (Nat.clog_mono_right 2 (Nat.add_le_add_left D.bits 1)).trans H.logarithm + unfold Phase.rate + omega + +theorem short : Phase.short S T L.r P ≤ L.small := by + have := D.rate H h + have := D.tags h + have := D.bits + have := D.counters + unfold Phase.short Limits.small + omega + +omit h +theorem speed (hn : i + 1 ≤ L.steps) (k : ℕ) (hk : k ≤ L.K) : + k * P.reach ≤ L.K ^ L.steps * L.start.reach := calc + _ ≤ L.K * (L.K ^ i * L.start.reach) := Nat.mul_le_mul hk D.origins + _ = L.K ^ (i + 1) * L.start.reach := by rw [pow_succ', mul_assoc] + _ ≤ _ := Nat.mul_le_mul_right _ (Nat.pow_le_pow_right H.positive hn) + +theorem charge (hn : i + 1 ≤ L.steps) (hσ : 0 ≤ L.σ) (hk : 2 ≤ L.K) : + P.mass + 2 * P.width ≤ S.cap := by + let Z := S.fringe.Z + L.σ + let A := L.start.mass + L.start.width + Z + have hZ : 0 ≤ Z := add_nonneg S.fringe.total_nonneg hσ + have hp : P.mass + P.width + Z ≤ (L.K ^ i : ℕ) * A := D.potential + have ha : 0 ≤ A := by + have ht : (0 : ℝ) < (L.K ^ i : ℕ) := Nat.cast_pos.mpr (pow_pos H.positive _) + exact nonneg_of_mul_nonneg_right ((add_nonneg (add_nonneg D.mass D.width) hZ).trans hp) ht + calc + _ ≤ (L.K : ℝ) * (P.mass + P.width + Z) := by + have hK : (2 : ℝ) ≤ L.K := by exact_mod_cast hk + nlinarith only [mul_le_mul_of_nonneg_right hK (add_nonneg (add_nonneg D.mass D.width) hZ), + D.mass, hZ] + _ ≤ (L.K : ℝ) * ((L.K ^ i : ℕ) * A) := mul_le_mul_of_nonneg_left hp (Nat.cast_nonneg _) + _ = (L.K ^ (i + 1) : ℕ) * A := by rw [pow_succ', Nat.cast_mul, mul_assoc] + _ ≤ (L.K ^ L.steps : ℕ) * A := + mul_le_mul_of_nonneg_right (Nat.cast_le.mpr (Nat.pow_le_pow_right H.positive hn)) ha + _ ≤ _ := H.history + +theorem input (hσ : 0 ≤ L.σ) (hn : i + 1 ≤ L.steps) (hk : k ≤ L.K) (hK : 2 ≤ L.K) (hpos : 0 < k) + (hu : u = b * v) (hv : 0 < v) (hd : S.z ∣ v) (hU : u ∣ S.U) (hU' : u ≤ S.U) : + Phase.Input S T P L.w L.r b u v d k L.σ := by + have hi : i ≤ L.steps := by omega + refine ⟨H.trivalent, H.zpos, hv, hd, hu, hU, hU', D.capacity, ?_, by have := D.height; omega, + hk.trans H.room, hpos, D.degree, D.core, D.single, H.names, D.lower, ?_, ?_, ?_, D.reach, + D.width, D.mass, + D.charge H hn hσ hK, ?_⟩ + · have ht := (Nat.mul_le_mul_right L.r hn).trans H.height + have hh := D.height + rw [Nat.succ_mul] at ht + omega + · exact (Nat.add_le_add (D.hosts hi) (Nat.mul_le_mul_right _ hk)).trans H.upper + · have hs : 0 < L.small := by unfold Limits.small; have := H.pos; positivity + exact ((Nat.pow_le_pow_left (D.short H hi) k).trans (Nat.pow_le_pow_right hs hk)).trans H.labels + · exact (Nat.mul_le_mul_left 3 (D.speed H hn k hk)).trans H.origins + · refine le_trans ?_ H.slack + have hh := Nat.mul_le_mul (Nat.mul_le_mul hk (Nat.mul_le_mul_right S.z (D.loads H hi))) + (Nat.pow_le_pow_right (by decide : 0 < 2) (D.seats hi)) + exact_mod_cast hh + +end Inside +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Growth estimates for a single encoded phase -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {S : Setup F x y} {T : Template F} + {L : Limits} {P : Budget} {u d d' i k b v Δ Δ' : ℕ} {ρ C : ℝ} + +private theorem exponent {a b i j : ℕ} (h : a ≤ b) (hb : 0 < b) (hk : i ≤ j) : a ^ i ≤ b ^ j := + (Nat.pow_le_pow_left h _).trans (Nat.pow_le_pow_right hb hk) + +theorem Completion.one (D : Inside S L T P u d i) (H : Enough S L) (hσ : 0 ≤ L.σ) + (hn : i + 1 ≤ L.steps) (hk : 0 < k) (hr : k ≤ L.K) (hv : v ≤ u) + (hρ : 0 ≤ ρ) (hC : 0 ≤ C) (hl : 4 + ρ + C ≤ L.K) + (q : Phase.Output S T P L.w L.r u v Δ Δ' d' k ρ C L.σ) : + Nonempty (Completion S L T P u v Δ Δ' d' i 1 ρ C) := by + have hi : i ≤ L.steps := by omega + have hA := H.pos + have hB := exponent (D.base H hi) hA hr + have he : (Phase.rate S T L.r P) ^ k ≤ L.extra := exponent (D.rate H hi) (by positivity) hr + have hs : (Phase.short S T L.r P) ^ k ≤ L.small ^ L.K := + exponent (D.short H hi) (by unfold Limits.small; positivity) hr + have hz : 0 ≤ S.fringe.Z + L.σ := add_nonneg S.fringe.total_nonneg hσ + let Q := Phase.after S T L.r P k ρ C L.σ + have bound (a c : ℕ) (hb : a ≤ L.K ^ i * c) : k * a ≤ L.K ^ (i + 1) * c := by + rw [pow_succ', mul_assoc] + exact Nat.mul_le_mul hr hb + have hp : Inside S L q.next Q v d' (i + 1) := by + refine ⟨?_, D.lower.trans q.lower, ?_, q.degree, q.core, q.single, + q.spans.trans hB, q.counters.trans hB, ?_, ?_, ?_, bound _ _ D.load, + Nat.mul_pos hk D.reach, bound _ _ D.origins, ?_, ?_, ?_⟩ + · have := D.height + have := q.height + rw [Nat.succ_mul] + omega + · have := D.upper + have := q.upper + rw [Nat.succ_mul] + omega + · exact q.bits.trans (Nat.mul_le_mul (Nat.add_le_add_left (D.tags hi) 1) he) + · change P.tag + _ ≤ _ + rw [Nat.succ_mul, ← Nat.add_assoc] + exact Nat.add_le_add D.tag he + · exact (hv.trans D.capacity).trans + (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_left _ hk)) + · exact add_nonneg (mul_nonneg hρ D.width) (mul_nonneg hC hz) + · exact add_nonneg D.mass (mul_nonneg (by norm_num) D.width) + · let Z := S.fringe.Z + L.σ + change 0 ≤ Z at hz + change (P.mass + 2 * P.width) + (ρ * P.width + C * Z) + Z ≤ _ + calc + _ ≤ (4 + ρ + C) * (P.mass + P.width + Z) := by + nlinarith only [D.mass, D.width, hz, mul_nonneg hρ D.mass, mul_nonneg hC D.mass, + mul_nonneg hρ hz, mul_nonneg hC D.width] + _ ≤ (L.K : ℝ) * ((L.K ^ i : ℕ) * (L.start.mass + L.start.width + Z)) := + mul_le_mul hl D.potential (add_nonneg (add_nonneg D.mass D.width) hz) (Nat.cast_nonneg _) + _ = _ := by rw [pow_succ', Nat.cast_mul, mul_assoc] + refine ⟨⟨q.next, Q, hp, le_rfl, q.labels, by simpa using q.few.trans hs, + fun t ht => (q.small t ht).trans hs, q.scale, q.size, ?_, q.transfer⟩⟩ + rw [one_mul] + refine q.cost.trans (Nat.add_le_add (Nat.mul_le_mul (Nat.pow_le_pow_right (by decide) (D.hosts + hi)) ?_) + (Nat.mul_le_mul (Nat.pow_le_pow_right (by decide) (D.seats hi)) hs)) + exact exponent (Nat.add_le_add_left (D.short H hi) _) (by omega) hr + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Composition of an encoded sequence with uniform budgets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {S : Setup F x y} {T : Template F} + {L : Limits} {P : Budget} {u v w d d' d'' i k b n n' Δ Δ' Δ'' : ℕ} {ρ ρ' C C' : ℝ} + +open scoped Classical in +private theorem weaken {X : Assembly.Snapshot.{1} F S.input S.output} + {A B : Snapshot.Data S T u → Prop} (h : ∀ i, A i → B i) {G : Set (Table F)} + (ht : Transforms F k G X (Snapshot.restrict A) n) : + Transforms F k G X (Snapshot.restrict B) n := by + obtain ⟨f, hf, he⟩ := ht + refine ⟨f, hf, fun s => ?_⟩ + obtain ⟨I, _, q, c, hw, hc⟩ := he s + exact ⟨I, inferInstance, fun j => ⟨(q j).val, h _ (q j).property⟩, c, hw, hc⟩ + +open scoped Classical in +private theorem Completion.relax (p : Completion S L T P u v Δ Δ' d' i n ρ C) + (hd : d' ≤ d'') (hg : Δ' ≤ Δ'') (hρ : ρ ≤ ρ') (hc : C ≤ C') + (hx : 0 ≤ P.width) (hs : 0 ≤ L.σ) : + Nonempty (Completion S L T P u v Δ Δ'' d'' i n ρ' C') := by + have hi : Inside S L p.next p.budget v d'' (i + n) := + { p.inside with degree := p.inside.degree.trans hd } + have hZ := add_nonneg S.fringe.total_nonneg hs + refine ⟨⟨p.next, p.budget, hi, p.width.trans (by gcongr), p.labels, p.few, p.small, + p.scale, p.size, p.cost, ?_⟩⟩ + refine weaken ?_ p.transfer + intro t ht + exact { ht with bounded := ht.bounded.mono hg (by unfold degreeBound; omega) le_rfl } + +open scoped Classical in +private theorem Completion.chain (p : Completion S L T P u v Δ Δ' d' i n ρ C) + (q : Completion S L p.next p.budget v w Δ' Δ'' d'' (i + n) n' ρ' C') (hp : 0 ≤ ρ') : + Nonempty (Completion S L T P u w Δ Δ'' d'' i (n + n') (ρ' * ρ) (ρ' * C + C')) := by + let A := p.labels ∪ q.labels + let j := max p.scale q.scale + have hi := q.inside + rw [Nat.add_assoc] at hi + refine ⟨⟨q.next, q.budget, hi, ?_, A, ?_, ?_, j, p.size + q.size, ?_, ?_⟩⟩ + · linarith only [q.width, mul_le_mul_of_nonneg_left p.width hp] + · rw [add_mul] + exact (Finset.card_union_le _ _).trans (Nat.add_le_add p.few q.few) + · intro k hk + exact (Finset.mem_union.mp hk).elim (p.small k) (q.small k) + · rw [add_mul] + exact Nat.add_le_add p.cost q.cost + · have g := p.transfer.widen (v := j) (L' := Allowed F L.w ∪ ↑A) + (le_max_left _ _) (fun _ h => h.imp_right (Finset.mem_union_left _)) + have g' := q.transfer.widen (v := j) (L' := Allowed F L.w ∪ ↑A) + (le_max_right _ _) (fun _ h => h.imp_right (Finset.mem_union_right _)) + exact g.comp g' + +open scoped Classical in +private theorem Sequence.positive (q : Sequence F k Δ Δ' d d' b n ρ C) : + 0 < b ∧ 0 ≤ ρ := by + induction q with + | one _ hb _ _ hr _ _ => exact ⟨hb, hr⟩ + | comp _ _ ih ih' => exact ⟨Nat.mul_pos ih.1 ih'.1, mul_nonneg ih'.2 ih.2⟩ + | relax _ _ _ hr _ ih => exact ⟨ih.1, ih.2.trans hr⟩ + +open scoped Classical in +theorem Sequence.run (q : Sequence F L.K Δ Δ' d d' b n ρ C) + (H : Enough S L) (hσ : 0 ≤ L.σ) (t : Inside S L T P u d i) (hn : i + n ≤ L.steps) + (hu : u = b * v) (hv : 0 < v) (hdiv : S.z ∣ v) (hU : u ∣ S.U) (hU' : u ≤ S.U) : + Nonempty (Completion S L T P u v Δ Δ' d' i n ρ C) := by + induction q generalizing T P u v i with + | one q hb hp hr hρ hc hl => + have hk : 2 ≤ L.K := by exact_mod_cast (show (2 : ℝ) ≤ L.K by linarith) + have h := t.input H hσ hn hr hk hp hu hv hdiv hU hU' + obtain ⟨r⟩ := q _ _ _ _ _ _ _ _ h + exact Completion.one t H hσ hn hp hr (by rw [hu]; exact Nat.le_mul_of_pos_left _ hb) hρ hc hl r + | @comp Δ Δ' Δ'' d d' d'' b b' n n' ρ ρ' C C' p q ih ih' => + have hu' : u = b * (b' * v) := by rw [hu, mul_assoc] + have hm : 0 < b' * v := Nat.mul_pos q.positive.1 hv + have hmid : b' * v ≤ u := by rw [hu']; exact Nat.le_mul_of_pos_left _ p.positive.1 + have hd : b' * v ∣ u := by rw [hu']; exact dvd_mul_left _ _ + obtain ⟨a⟩ := ih t (by omega) hu' hm (hdiv.mul_left b') hU hU' + obtain ⟨f⟩ := ih' a.inside (by omega) rfl hv hdiv (hd.trans hU) (hmid.trans hU') + exact a.chain f q.positive.2 + | relax p hd hw hr hc ih => + obtain ⟨f⟩ := ih t hn hu hv hdiv hU hU' + exact f.relax hw hd hr hc t.width hσ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Unconditional realization of a wire-saving batch phase -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Beat Phase Phase.Case + +theorem subroundRule (F : Type) [Field F] : SubroundRule F := by + intro P Δ hd d + apply rule_of_bounds P Δ d hd + · exact (((prepareWidth_bound P d).add (markWidth_bound P d)).add + (issueWidth_bound P Δ d)).add ((short_const 2).mul (next_bits P Δ d)) + · have h₁ := (((input_bound P d).scale 100).add (prepareCost_bound P d)).add (headedCost_bound P + Δ d) + exact (((h₁.add (secondCost_bound P Δ d)).add ((candidate_bound P d).scale 4)).add + (sweepCost_bound P Δ d)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/MixCost.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/MixCost.lean new file mode 100644 index 0000000000..07e0c65211 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/MixCost.lean @@ -0,0 +1,165 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Headers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact +import Mathlib.Tactic.Ring + +/-! # Shared cost bounds for reset mixers -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix +open BatchDescent.Phase Coloring + +variable {I : Type*} {F : I → Type} {T : (i : I) → Template (F i)} + {k d n : I → ℕ} {large small height hosts : I → ℕ} + (largeTwo : ∀ i, 2 ≤ large i) (smallTwo : ∀ i, 2 ≤ small i) + (smallLeLarge : ∀ i, small i ≤ large i) + +local notation "Cost" => MixedCost large small height hosts +local notation "TemplateCost" => + MixedCost large small (fun i => Scheme.h (Template.scheme (T i))) + (fun i => Scheme.m (Template.scheme (T i))) +local notation "TemplateRow" => + MixedCost large small (fun i => Scheme.h (Template.scheme (T i))) (fun _ => 0) + +include largeTwo smallTwo in +private theorem pair_mixed {A B : I → Format} + (first : Cost (fun i => (A i).width)) (second : Cost (fun i => (B i).width)) : + Cost (fun i => ((A i).pair (B i)).width) := + (first.add second largeTwo smallTwo).mono fun _ => (Format.width_pair ..).le + +include largeTwo smallTwo smallLeLarge + +/-- Charge a projection from the two widths it reads. -/ +theorem project_mixed {A B : I → Format} + (first : Cost (fun i => (A i).width)) (second : Cost (fun i => (B i).width)) : + Cost (fun i => project (A i) (B i)) := + (first.add (second.scale 2 smallTwo smallLeLarge) largeTwo smallTwo).scale + 4 smallTwo smallLeLarge + +/-- Combine the source projection and the tally work at every host. -/ +theorem tallyCost_mixed + (format : TemplateCost (fun i => (T i).format.width)) + (sources : TemplateCost (fun i => (Sources (T i)).width)) + (digits : TemplateRow (fun i => (Digits (T i) (d i)).width)) + (split : TemplateRow (fun i => (Split (T i) (d i)).width)) + (shortCall : TemplateRow (fun i => 2 ^ (T i).scheme.h * (1 + arity (T i) (k i) (d i)))) + (longCall : TemplateRow (fun i => 1 + arity (T i) (k i) (d i))) + (batch : TemplateRow (fun i => 2 ^ (T i).scheme.h * (100 + d i) ^ 5)) + (collect : TemplateRow (fun i => + Mixing.collectCost (T i).scheme.h (T i).scheme.d (T i).CounterBits)) : + TemplateCost (fun i => tallyCost (T i) (k i) (d i)) := by + have projection := project_mixed largeTwo smallTwo smallLeLarge digits split + have rest := (batch.scale 4 smallTwo smallLeLarge).add longCall largeTwo smallTwo + have rest := rest.add (collect.scale 4 smallTwo smallLeLarge) largeTwo smallTwo + have tally := (shortCall.add projection largeTwo smallTwo).add rest largeTwo smallTwo + exact (project_mixed largeTwo smallTwo smallLeLarge format sources).add + (tally.hosts fun i => (T i).scheme.m) largeTwo smallTwo + +/-- Combine travel, neighborhood, and next-window charges. -/ +theorem gatherCost_mixed + (travel : Cost (fun i => (Travel (T i) (k i)).width)) + (network : Cost (fun i => ((T i).NetworkDepths (k i)).width)) + (near : Cost (fun i => (T i).nearCost (k i))) + (next : Cost (fun i => ((T i).Next (k i)).width)) + (windows : Cost (fun i => (Windows (T i) (k i)).width)) : + Cost (fun i => gatherCost (T i) (k i)) := by + have initial := (travel.scale 24 smallTwo smallLeLarge).add + (project_mixed largeTwo smallTwo smallLeLarge travel network) largeTwo smallTwo + have final := project_mixed largeTwo smallTwo smallLeLarge + (pair_mixed largeTwo smallTwo travel next) windows + exact (initial.add near largeTwo smallTwo).add final largeTwo smallTwo + +/-- Combine the one-time depth projection with the cost of each wave. -/ +theorem waveCost_mixed + (network : TemplateCost (fun i => ((T i).NetworkDepths (k i)).width)) + (depth : TemplateCost (fun i => ((T i).Depths (k i)).width)) + (gather : TemplateCost (fun i => gatherCost (T i) (k i))) + (call : TemplateRow (fun i => 1 + arity (T i) (k i) (d i))) + (waves : Poly small n) : + TemplateCost (fun i => waveCost (T i) (k i) (d i) (n i)) := by + have each := (network.scale 24 smallTwo smallLeLarge).add gather largeTwo smallTwo + have each := each.add (call.hosts fun i => (T i).scheme.m) largeTwo smallTwo + have all := (each.mul waves smallLeLarge).mono + (fun i => (Nat.mul_comm (n i) _).le) + exact (project_mixed largeTwo smallTwo smallLeLarge network depth).add + all largeTwo smallTwo + +/-- Combine the two passes over the host records with the final profile projection. -/ +theorem profileCost_mixed + (network : TemplateCost (fun i => ((T i).NetworkDepths (k i)).width)) + (travel : TemplateCost (fun i => (Travel (T i) (k i)).width)) + (gather : TemplateCost (fun i => gatherCost (T i) (k i))) + (sources : TemplateCost (fun i => (Sources (T i)).width)) + (longCall : TemplateRow (fun i => 1 + arity (T i) (k i) (d i))) + (shortCall : TemplateRow (fun i => 2 ^ (T i).scheme.h * (1 + arity (T i) (k i) (d i)))) + (sides : TemplateCost (fun i => (Sides (T i) (k i)).width)) + (rows : TemplateCost (fun i => ((T i).profileShape (k i)).width)) : + TemplateCost (fun i => profileCost (T i) (k i) (d i)) := by + have survey := project_mixed largeTwo smallTwo smallLeLarge network travel + have survey := (survey.add gather largeTwo smallTwo).add + (longCall.hosts fun i => (T i).scheme.m) largeTwo smallTwo + have collect := (project_mixed largeTwo smallTwo smallLeLarge network sources).add + (shortCall.hosts fun i => (T i).scheme.m) largeTwo smallTwo + have start := (network.scale 20 smallTwo smallLeLarge).add survey largeTwo smallTwo + exact (start.add collect largeTwo smallTwo).add + (project_mixed largeTwo smallTwo smallLeLarge sides rows) largeTwo smallTwo + +/-- Combine the reset mixer charges using the template's first and second record formats. -/ +theorem cost_mixed + (format : TemplateCost (fun i => (T i).format.width)) + (stats : TemplateCost (fun i => (Stats (T i) (k i)).width)) + (depth : TemplateCost (fun i => ((T i).Depths (k i)).width)) + (network : TemplateCost (fun i => ((T i).NetworkDepths (k i)).width)) + (tally : TemplateCost (fun i => tallyCost (T i) (k i) (d i))) + (wave : TemplateCost (fun i => waveCost (T i) (k i) (d i) (n i))) + (profile : TemplateCost (fun i => profileCost (T i) (k i) (d i))) + (extract : TemplateCost (fun i => Mixing.extractionCost (T i).scheme.m (T i).widthCols + (T i).scheme.h (k i) (T i).profileBits (d i) + + Mixing.cost ((T i).scheme.m + (T i).widthCols) (T i).scheme.h (k i) (d i))) : + TemplateCost (fun i => cost (T i) (k i) (d i) (n i)) := by + have first := pair_mixed largeTwo smallTwo format stats + have both := pair_mixed largeTwo smallTwo first depth + have start := (format.scale 48 smallTwo smallLeLarge).add tally largeTwo smallTwo + have start := start.add (first.scale 24 smallTwo smallLeLarge) largeTwo smallTwo + have start := start.add (project_mixed largeTwo smallTwo smallLeLarge first network) + largeTwo smallTwo + have middle := (start.add wave largeTwo smallTwo).add + (both.scale 20 smallTwo smallLeLarge) largeTwo smallTwo + have middle := middle.add (project_mixed largeTwo smallTwo smallLeLarge both network) + largeTwo smallTwo + have finish := (middle.add profile largeTwo smallTwo).add extract largeTwo smallTwo + refine (finish.add (project_mixed largeTwo smallTwo smallLeLarge both stats) + largeTwo smallTwo).mono fun i => ?_ + unfold cost + rw [add_assoc _ (Mixing.extractionCost ..)] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Mix + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child +open BatchDescent.Phase + +/-- The four exponential factors in the header builder share one host-indexed budget. -/ +theorem buildCost_mixed {I : Type*} {large small height hosts old growth new : I → ℕ} + (largeTwo : ∀ i, 2 ≤ large i) (hostBound : Poly large hosts) + (oldBound : Poly large (fun i => 2 ^ old i)) (growthBound : Poly large (fun i => 2 ^ growth i)) + (newBound : Poly large (fun i => 2 ^ new i)) : + MixedCost large small height hosts + (fun i => buildCost (hosts i) (old i) (growth i) (new i)) := by + have head := ((Poly.const largeTwo 1000).mul growthBound).mul newBound + have tail := ((Poly.const largeTwo 4).add growthBound.of_exp).add hostBound + refine (MixedCost.long hosts (((head.mul oldBound).mul + ((Poly.const largeTwo 2).add oldBound.of_exp)).mul tail)).mono fun i => ?_ + unfold buildCost + rw [pow_add, pow_add, pow_add] + exact le_of_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.History.Reset.Child diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/Rule.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/Rule.lean new file mode 100644 index 0000000000..9fcb8780b9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Restore/Rule.lean @@ -0,0 +1,834 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Elect +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Attachment.WriteNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Carry + +/-! # Load, width and table budgets of the elected reset -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Coloring + +variable {F : Type} [Field F] {x y : Wire} {Y l : ℕ} [NeZero Y] [NeZero l] + {S : Setup F x y} {T : Template F} {u Δ t : ℕ} {R : Budget} {w r d K : ℕ} {σ κ : ℝ} + (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) (q : (frame S T u Δ R).state) + (P : Rotor F Y l) (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +local notation "a" => (T.scheme.h - r) +local notation "U" => (poll h s hk q) +local notation "hf" => (fits h s hk q P hc cost) +local notation "Q" => (History.Reset.Setup.result U P hf) +local notation "G" => (History.Reset.Setup.graph U P hf) +local notation "D" => (degreeBound S T Δ) +local notation "B₁" => (gain t * R.load) +local notation "b" => (book S T u t R) +local notation "N" => (next P S T u Δ t R a) + +omit [NeZero Y] [NeZero l] in +open scoped Classical in +theorem gain_eq (t : ℕ) (R : Budget) (z : ℕ) : + 89 * ((2 : ℝ) ^ t * (R.load * z : ℕ)) = (gain t * R.load : ℕ) * (z : ℝ) := by + simp only [gain, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, mul_assoc] + +open scoped Classical in +theorem estimates : + (∀ x y, (G).diagram.eval x y = q.val.G.diagram.eval x y) ∧ + (G).Bounded 3 (3 + terminalWidth D Y) ((B₁ : ℕ) * (S.z : ℝ)) ∧ + ((G).X : ℝ) ≤ 2 * resetWidth κ l * R.width + 2 * resetWidth κ l * (S.fringe.Z + σ) ∧ + S.first.Preserves G ∧ ((G).mass : ℝ) ≤ R.mass + 2 * R.width ∧ + S.first.Tracks G ((resetPositions P Δ + 1) * R.reach) := by + obtain ⟨eval, _, bounds, width, preserve, mass, tracks⟩ := (U).bounds P hf (slack h hk q) + refine ⟨eval, ?_, ?_, q.val.preserved.trans preserve, ?_, + q.property.tracks.trans tracks h.height (Nat.sub_le ..)⟩ + · rw [← gain_eq]; exact bounds + · have hσ : 0 ≤ σ := + nonneg_of_mul_nonneg_left (le_trans (by positivity) h.slack) (by positivity) + have hc' : 0 ≤ resetWidth κ l := by unfold resetWidth; positivity + refine width.trans ?_ + calc + _ ≤ resetWidth κ l * (2 * σ + 2 * R.width + 2 * S.fringe.Z) := + mul_le_mul_of_nonneg_left (add_le_add_left + (add_le_add (by linarith only [hσ]) (mul_le_mul_of_nonneg_left q.property.width (by + norm_num))) _) hc' + _ = _ := by ring + · rw [mass] + change ((q.val.G.mass + 2 * q.val.G.X : ℕ) : ℝ) ≤ _ + rw [Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat] + exact add_le_add q.property.mass (mul_le_mul_of_nonneg_left q.property.width (by norm_num)) + +open scoped Classical in +theorem mass : (G).mass ≤ S.cap := + Nat.cast_le.mp ((estimates h s hk q P hc cost).2.2.2.2.1.trans h.history) + +open scoped Classical in +theorem valid : (meter S t R).Valid G := by + have hU := (Nat.le_of_dvd h.vpos h.divides).trans h.ceiling + have hn : 2 ^ S.discount * B₁ * S.z < 2 ^ (c S t R) := + (Nat.mul_le_mul_left _ hU).trans_lt (Nat.lt_of_succ_le (Nat.le_pow_clog (by decide) _)) + have ht : (2 : ℝ) ^ S.discount * ((B₁ : ℕ) * (S.z : ℝ)) < 2 ^ (c S t R) := by + rw [← mul_assoc] + exact_mod_cast hn + have scale : (B₁ : ℕ) * (S.z : ℝ) < 1 * (2 : ℝ) ^ (c S t R) := by + rw [one_mul] + exact (le_mul_of_one_le_left (mul_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) + (one_le_pow₀ (by norm_num : (1 : ℝ) ≤ 2))).trans_lt ht + exact Template.Meter.valid_of_charge G (c S t R) _ (mass h s hk q P hc cost) + (estimates h s hk q P hc cost).2.1.2.2 scale ht (fun _ => ⟨1, Nat.cast_one.symm⟩) + +omit [NeZero Y] [NeZero l] in +open scoped Classical in +private theorem widths (j : q.val.encodes.post.toPresentation.BorderSpan) : + q.val.encodes.post.toPresentation.borderWidth j = S.U := + q.val.exterior_width _ j.property.2 j.property.1 + +open scoped Classical in +theorem room (v : Cell a × (Q).vertex) : + Fintype.card (History.Reset.Visible q.val.encodes.post Q v) ≤ 2 ^ (e t R) := by + have ht := History.Reset.seats_fit q.val.encodes.post Q v h.zpos (Nat.le_of_dvd h.vpos h.divides) + (fun j => h.ceiling.trans_eq (widths q j).symm) (gain_eq t R S.z).le + exact ht.2.2.trans (Nat.le_pow_clog (by decide) _) + +open scoped Classical in +theorem ready [Fintype F] (A : History.Reset.Allocation q.val.encodes.post Q (N).scheme) + (nav : B (N).scheme.m → B (N).scheme.d → B (N).scheme.m) + (hop : ∀ (i : (Q).Survivors) z, + let host := History.Reset.Allocation.endHost (q := Q) + nav (A.host (host i z)) (A.index (host i z) (host i (!z))) = A.host (host i (!z))) : + (b).Ready A nav := by + have tag : History.Reset.Charged q.val.encodes.post (b).ord S.z R.tag := + fun v => q.property.tagged v.1 v.2 + apply (b).ready A nav _ hop ((U).result_simple P hf) q.property.neutral + tag h.zpos (Nat.le_of_dvd h.vpos h.divides) (fun j => h.ceiling.trans_eq (widths q j).symm) + (mass h s hk q P hc cost) (gain_eq t R S.z).le (Nat.le_pow_clog (by decide) _) le_rfl + intro j + exact History.Reset.Book.represent T.scheme u (e t R) (cap S T t R) T.order {S.U} + (Finset.mem_singleton.mpr (widths q j)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Tracking the exterior and the accumulated history through a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y l : ℕ} [NeZero Y] [NeZero l] + {S : Setup F x y} {T : Template F} {u Δ t : ℕ} {R : Budget} {w r d K : ℕ} {σ κ : ℝ} + (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) (q : (frame S T u Δ R).state) + (P : Rotor F Y l) (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +omit [Fintype F] in +open scoped Classical in +private theorem swept (M : Snapshot.Data S T u) (B : Budget) {D c : ℕ} (ht : c ≤ B.tag) + (live : Nonempty M.G.V) (tag : History.Reset.Charged M.encodes.post T.order S.z c) + (bd : M.G.Bounded 3 D (B.load * S.z)) (tracks : S.first.Tracks M.G B.reach) + (width : (M.G.X : ℝ) ≤ B.width) (mass : (M.G.mass : ℝ) ≤ B.mass) : Ready 3 B M.sweep := by + refine ⟨live, M.sweep_neutral, ?_, ⟨bd.1, ?_, bd.2.2⟩, tracks, width, mass⟩ + · apply (M.sweep_tagged _).mpr + intro v j hv + exact (tag (v, j) hv).trans (Nat.mul_le_mul_right _ ht) + · intro j + have he : Fintype.card M.sweep.G.V ≤ 2 ^ T.scheme.m := by + simpa using Fintype.card_le_of_injective _ M.sweep.encodes.post.host.injective + exact (Finset.card_le_univ _).trans (he.trans (Nat.le_add_left _ _)) + +local notation "a" => (T.scheme.h - r) +local notation "U" => (poll h s hk q) +local notation "hf" => (fits h s hk q P hc cost) +local notation "Q" => (History.Reset.Setup.result U P hf) +local notation "G" => (History.Reset.Setup.graph U P hf) +local notation "N" => (next P S T u Δ t R a) + +open scoped Classical in +/-- Information produced by the reset writer on each valid input. -/ +structure Print where + /-- The indexed rows of type `(N).format.obj`. -/ + rows : (N).format.obj + /-- The `Print` component of type `(N).Encodes rows G`. -/ + encodes : (N).Encodes rows G + /-- The selected move of type `Trail.Move T.scheme (N).scheme 0`. -/ + move : Trail.Move T.scheme (N).scheme 0 + agrees : move.Agrees q.val.encodes.post.toPresentation encodes.post.toPresentation + charged : History.Reset.Charged encodes.post (N).order S.z (R.tag + added S T Δ t R Y) + +namespace Print + +variable {h s hk q P hc cost} (m : Print h s hk q P hc cost) + (hr : resetPositions P Δ + 1 ≤ K) + +open scoped Classical in +/-- Builds `Snapshot.Data S N u where rows` with the specified `rows`, `encodes`, `trail`, +`tracks`. -/ +def result : Snapshot.Data S N u where + rows := m.rows + «G» := G + encodes := m.encodes + trail := m.move.update S.d q.val.trail + tracks := by + obtain ⟨_, _, _, preserve, _, tracks⟩ := estimates h s hk q P hc cost + have slots : 0 < S.d := by + have hk' : 0 < K := (Nat.two_pow_pos _).trans_le hk + exact (Nat.mul_pos (by norm_num) (Nat.mul_pos hk' h.reach)).trans_le h.origins + have hu := h.vpos.trans_le h.ceiling + refine q.val.tracks.update m.agrees hu slots ?_ + intro v + exact (S.origins G m.encodes.post preserve (tracks.mono (Nat.mul_le_mul_right _ hr)) + hu h.trivalent v).trans h.origins + preserved := (estimates h s hk q P hc cost).2.2.2.1 + +open scoped Classical in +private theorem result_bounds (hg : gain t ≤ K) : + (m.result hr).G.Bounded 3 (3 + terminalWidth (degreeBound S T Δ) Y) + ((K * R.load : ℕ) * (S.z : ℝ)) := by + have bounds := (estimates h s hk q P hc cost).2.1 + change (G).Bounded 3 _ _ + refine ⟨bounds.1, bounds.2.1, fun v j => (bounds.2.2 v j).trans ?_⟩ + exact mul_le_mul_of_nonneg_right + (Nat.cast_le.mpr (Nat.mul_le_mul_right R.load hg)) (Nat.cast_nonneg _) + +open scoped Classical in +private theorem result_tracks : + S.first.Tracks (m.result hr).G (K * R.reach) := by + have tracks := (estimates h s hk q P hc cost).2.2.2.2.2 + change S.first.Tracks G _ + exact tracks.mono (Nat.mul_le_mul_right R.reach hr) + +open scoped Classical in +private theorem result_live : Nonempty (m.result hr).G.V := + ⟨((Q).owner (Classical.choice q.property.live, 0)).2⟩ + +open scoped Classical in +private theorem result_charged : + History.Reset.Charged (m.result hr).encodes.post (N).order S.z + (R.tag + added S T Δ t R Y) := + m.charged + +open scoped Classical in +private theorem result_width : + ((m.result hr).G.X : ℝ) ≤ 2 * resetWidth κ l * R.width + + 2 * resetWidth κ l * (S.fringe.Z + σ) := + (estimates h s hk q P hc cost).2.2.1 + +open scoped Classical in +private theorem result_mass : + ((m.result hr).G.mass : ℝ) ≤ R.mass + 2 * R.width := + (estimates h s hk q P hc cost).2.2.2.2.1 + +open scoped Classical in +theorem preserved (hg : gain t ≤ K) (ht : added S T Δ t R Y ≤ (Phase.rate S T r R) ^ K) : + Ready 3 (Phase.after S T r R K (2 * resetWidth κ l) (2 * resetWidth κ l) σ) (m.result hr).sweep + := by + exact swept (D := 3 + terminalWidth (degreeBound S T Δ) Y) (m.result hr) + (Phase.after S T r R K (2 * resetWidth κ l) (2 * resetWidth κ l) σ) + (Nat.add_le_add_left ht R.tag) (result_live m hr) (result_charged m hr) + (result_bounds m hr hg) (result_tracks m hr) (result_width m hr) (result_mass m hr) + +end Print +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Validating one elected reset layout at the phase scale -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y l : ℕ} [NeZero Y] [NeZero l] + {S : Setup F x y} {T : Template F} {u Δ t : ℕ} {R : Budget} {w r d K : ℕ} {σ κ : ℝ} + (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) (q : (frame S T u Δ R).state) + (P : Rotor F Y l) (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +local notation "a" => (T.scheme.h - r) +local notation "U" => (poll h s hk q) +local notation "hf" => (fits h s hk q P hc cost) +local notation "Q" => (History.Reset.Setup.result U P hf) +local notation "G" => (History.Reset.Setup.graph U P hf) +local notation "D" => (degreeBound S T Δ) +local notation "b" => (book S T u t R) +local notation "N" => (next P S T u Δ t R a) +local notation "shift" => History.Reset.Child.extra P Δ (T.scheme.h - a) +local notation "mx" => T.scheme.m + shift +local notation "dx" => History.Reset.Child.width D Y T.full +local notation "M" => (meter S t R) +local notation "par" => (History.Reset.Setup.parent T shift) + +open scoped Classical in +/-- The assemble of type `Print h s hk q P hc cost` for the given inputs. -/ +def assemble (A : (U).Layout P hf b mx dx) (g : (History.Reset.Child.Graph mx dx).obj) + (blk : A.block = (cellIndex a).toEmbedding) + (parent : ∀ i, par (A.host i) = q.val.encodes.post.host ((Q).origin i)) + (head : History.Reset.Child.Describes (m := mx) (d := dx) T.full G A.host A.index g) : + Print h s hk q P hc cost := by + have H := ready h s hk q P hc cost A g.1 (History.Reset.Setup.hop A g head) + refine ⟨History.Reset.Setup.printed M A g, + History.Reset.Setup.outputEncodes M A g H blk head (valid h s hk q P hc cost), + A.move par, A.move_agrees H.lengths H.agrees par parent, ?_⟩ + have tag : History.Reset.Charged q.val.encodes.post (b).ord S.z R.tag := + fun v => q.property.tagged v.1 v.2 + have floor : ∀ j, u ≤ q.val.encodes.post.toPresentation.borderWidth j := + fun j => h.ceiling.trans_eq (q.val.exterior_width _ j.property.2 j.property.1).symm + rw [added, ← add_assoc] + exact H.charged tag h.zpos (Nat.le_of_dvd h.vpos h.divides) floor + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # A deterministic reset followed by scalar withdrawal -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {S : Setup F x y} {T N : Template F} + {u Δ : ℕ} {R R' : Budget} {L : Set (Table F)} {k size : ℕ} +local notation "X" => frame S T u Δ R + +open scoped Classical in +private theorem transfer (f : (X).state → Snapshot.Data S N u) + (hr : ∀ i, Ready 3 R' (f i).sweep) + (he : ∀ i x y, (f i).G.diagram.eval x y = i.val.G.diagram.eval x y) + (net : Computes F k L (S.format T) (S.format N) (fun i => i.val.code) + (fun i => (f i).code) (fun _ => 1) size) + (hk : 3 ≤ k) (hw : 2 * N.scheme.ℓ ≤ k) (hs : Snapshot.sweepTable N ∈ L) : + Transforms F k L X (frame S N.sweep u 3 R') (size + Snapshot.sweepCost S N) := by + let W := Snapshot.restrict (fun j : Snapshot.Data S N u => Ready 3 R' j.sweep) + have hw' : Transforms F k L X W size := by + obtain ⟨g, ng, hg⟩ := net + refine ⟨g, ng, fun i => ⟨Unit, inferInstance, fun _ => ⟨f i, hr i⟩, fun _ => 1, ?_, ?_⟩⟩ + · intro x y + rw [Fintype.sum_unique, one_mul] + exact (he i x y).symm + · intro x y r + rw [Fintype.sum_unique] + exact hg i r + exact hw'.comp (Snapshot.sweep (fun _ h => h) hk hw hs) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y l : ℕ} [NeZero Y] [NeZero l] + {S : Setup F x y} {T : Template F} {u Δ t : ℕ} {R : Budget} {w r d K : ℕ} {σ κ : ℝ} + (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) + (P : Rotor F Y l) (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +local notation "N" => (next P S T u Δ t R (T.scheme.h - r)) + +open scoped Classical in +/-- The writing circuit has to work only on the valid phase states. +The three numerical bounds describe fresh tables and the network cost. -/ +structure Writer (few arity size : ℕ) where + /-- The `Writer` component of type `∀ q, Print h s hk q P hc cost`. -/ + emit : ∀ q, Print h s hk q P hc cost + /-- Stores the scale associated with this `Writer`. -/ + scale : ℕ + /-- The label data of type `Finset (Table F)`. -/ + labels : Finset (Table F) + count : labels.card ≤ few + bound : ∀ i ∈ labels, Processor.arity i ≤ arity + net : Computes F scale (Allowed F w ∪ (labels : Set (Table F))) (S.format T) (S.format N) + (fun i => i.val.code) (fun i => ((emit i).rows, (emit i).move.update S.d i.val.trail)) (fun _ + => 1) size + +namespace Writer +variable {h s hk P hc cost} {few arity size : ℕ} (z : Writer h s hk P hc cost few arity size) + +local notation "R'" => Phase.after S T r R K (2 * resetWidth κ l) (2 * resetWidth κ l) σ + +open scoped Classical in +theorem finish (hr : resetPositions P Δ + 1 ≤ K) (hg : gain t ≤ K) + (ht : added S T Δ t R Y ≤ (Phase.rate S T r R) ^ K) : + Transforms F (3 + 2 * (N).scheme.ℓ + z.scale) + (Allowed F w ∪ (↑(insert (Snapshot.sweepTable N) z.labels) : Set (Table F))) + (frame S T u Δ R) (frame S (N).sweep u 3 R') (size + Snapshot.sweepCost S N) := by + let k := 3 + 2 * (N).scheme.ℓ + z.scale + let L := Allowed F w ∪ (↑(insert (Snapshot.sweepTable N) z.labels) : Set (Table F)) + let f (i : (frame S T u Δ R).state) := (z.emit i).result hr + have net : Computes F k L (S.format T) (S.format N) (fun i => i.val.code) + (fun i => (f i).code) (fun _ => 1) size := by + obtain ⟨g, hg, eqn⟩ := z.net + exact ⟨g, hg.widen (Nat.le_add_left ..) (Set.union_subset_union_right _ (fun _ ht => + Finset.mem_insert_of_mem ht)), eqn⟩ + exact transfer f (fun i => (z.emit i).preserved hr hg ht) + (fun i => (estimates h s hk i P hc cost).1) net + ((Nat.le_add_right ..).trans (Nat.le_add_right ..)) + ((Nat.le_add_left ..).trans (Nat.le_add_right ..)) (Or.inr (Finset.mem_insert_self ..)) + +end Writer +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- +# Uniformizing the parameters of a reset + +The next degree allowance is independent of the incoming degree +allowance. The constants in the resource bounds can depend on both. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Phase Phase.Case Coloring + +variable {F : Type} [Field F] {x y : Wire} {S : Setup F x y} {T : Template F} + {u d : ℕ} {R : Budget} {w r K : ℕ} {σ : ℝ} + +open scoped Classical in +/-- Uses `⟨x, y, S, T, R, w, r, u, u, K, σ, h⟩` as the representation. -/ +abbrev sample (h : Input S T R w r 1 u u d K σ) : Case F 1 d := + ⟨x, y, S, T, R, w, r, u, u, K, σ, h⟩ + +variable [Fintype F] {Y l : ℕ} [NeZero Y] [NeZero l] {Δ t : ℕ} + (P : Rotor F Y l) (s : Slice Δ Y l t) {κ : ℝ} + (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +local notation "I" => Case F 1 d + +open scoped Classical in +theorem rule_of_bounds {few arity size : I → ℕ} (M : ℕ) + (hcount : Short few) (hwidth : Short arity) (hsize : Cost size) + (build : ∀ {x y : Wire} {S : Setup F x y} {T : Template F} {R : Budget} + {w r u K : ℕ} {σ : ℝ} (h : Input S T R w r 1 u u d K σ) (hk : 2 ^ t ≤ K), M ≤ K → + Nonempty (Writer h s hk P hc cost (few (sample h)) (arity (sample h)) (size (sample h)))) : + ∃ K, 0 < K ∧ Phase F Δ 3 d 2 1 K (2 * resetWidth κ l) (2 * resetWidth κ l) := by + have child := child_bound P Δ t d + obtain ⟨j₁, h₁⟩ := (added_bound (F := F) Δ t d Y).bound + obtain ⟨j₂, h₂⟩ := (spans_bound (F := F) t d).bound + obtain ⟨j₃, h₃⟩ := (meter_bound (F := F) t d).bound + obtain ⟨j₄, h₄⟩ := bits_bound P Δ t d + obtain ⟨j₅, h₅⟩ := (hcount.add (short_const 1)).bound + obtain ⟨j₆, h₆⟩ := (hwidth.add (child.bits.add child.bits)).bound + obtain ⟨j₇, h₇⟩ := hsize.add child.sweep + let K := M + (resetPositions P Δ + 1) + Nat.clog 2 (resetPositions P Δ) + + gain t + 2 ^ t + j₁ + j₂ + j₃ + j₄ + j₅ + j₆ + j₇ + have hp := Nat.two_pow_pos t + have hk : 2 ^ t ≤ K := by unfold K; omega + refine ⟨K, hp.trans_le hk, ?_⟩ + intro x y S T R w r u v σ h + have he : u = v := h.units.trans (one_mul _) + subst v + let i := sample h + let N := next P S T u Δ t R (T.scheme.h - r) + obtain ⟨z⟩ := build h hk (by unfold K; omega) + have raised {n j : ℕ} (hn : 2 ≤ n) (hj : j ≤ K) : n ^ j ≤ n ^ K := + Nat.pow_le_pow_right (by omega) hj + have ht := (h₁ i).trans (raised i.rate_two (by unfold K; omega)) + have run := z.finish (by unfold K; omega) (by unfold K; omega) ht + refine ⟨⟨N.sweep, Nat.sub_add_cancel h.group, Nat.le_add_right .., ?_, (child_degree Δ d i).le, + h.core, rfl, ?_, ?_, ?_, insert (Snapshot.sweepTable N) z.labels, ?_, ?_, _, _, ?_, run⟩⟩ + · change T.scheme.m + (T.scheme.h - (T.scheme.h - r) + Nat.clog 2 (resetPositions P Δ)) ≤ _ + rw [Nat.sub_sub_self h.group] + unfold K + omega + · exact (h₂ i).trans (raised i.base_two (by unfold K; omega)) + · exact (h₃ i).trans (raised i.base_two (by unfold K; omega)) + · exact (h₄ i).trans (Nat.mul_le_mul_left _ (raised i.rate_two (by unfold K; omega))) + · exact (Finset.card_insert_le ..).trans ((Nat.add_le_add_right z.count 1).trans + ((h₅ i).trans (raised i.short_two (by unfold K; omega)))) + · intro k hmem + refine le_trans ?_ ((h₆ i).trans (raised i.short_two (by unfold K; omega))) + change Processor.arity k ≤ arity i + (N.scheme.ℓ + N.scheme.ℓ) + rcases Finset.mem_insert.mp hmem with rfl | h' + · simp only [Snapshot.sweepTable, Processor.arity, weightTable, Assembly.lookup, wd_word, + Format.width_addr] + exact Nat.le_add_left .. + · exact (z.bound k h').trans (Nat.le_add_right ..) + · exact (h₇ i).trans (Nat.add_le_add + (Nat.mul_le_mul_left _ (raised i.long_two (by unfold K; omega))) + (Nat.mul_le_mul_left _ (raised i.short_two (by unfold K; omega)))) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Input records, exchange capacity and local reset costs -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y l : ℕ} [NeZero Y] [NeZero l] + {S : Setup F x y} {T : Template F} {u Δ t : ℕ} {R : Budget} {w r d K : ℕ} {σ κ : ℝ} + (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) (q : (frame S T u Δ R).state) + (P : Rotor F Y l) (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +local notation "a" => (T.scheme.h - r) +local notation "N" => (next P S T u Δ t R a) +open History.Reset + +open scoped Classical in +/-- Computes the board by the application `History.Reset.electedBoard q.val.encodes (ok h s hk +q) s.enough s.space (unit (t := t) h)`. -/ +abbrev board := + History.Reset.electedBoard q.val.encodes (ok h s hk q) s.enough s.space (unit (t := t) h) + +include h in +omit [Fintype F] in +open scoped Classical in +theorem access (j v scale : ℕ) (hj : j ≤ K * (S.h + 1)) (L : Set (Table F)) + (hw : 2 * 2 ^ (2 * w) * (4 * w) ≤ scale) : + Access F scale (Allowed F w ∪ L) (T.scheme.m + j) v (Beat.accessCost (T.scheme.m + j) v) := by + have htop : T.scheme.m + j ≤ 2 * w := (Nat.add_le_add_left hj _).trans h.upper + have pos : 0 < w := by + have hh : 0 < K * (S.h + 1) := Nat.mul_pos h.positive (Nat.zero_lt_succ S.h) + have := h.upper + omega + have big : 2 * 2 ^ (T.scheme.m + j) * (4 * w) ≤ scale := + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide) htop))).trans + hw + exact (exchange F v pos (h.lower.trans (Nat.le_add_right ..)) htop big).widen le_rfl + (fun _ ht => Or.inl (sort_allowed ht)) + +open scoped Classical in +/-- The issue width used in the `Restore` construction. -/ +abbrev issueWidth (i : Phase.Case F 1 d) := + Tile.printWidth i.T (next P i.S i.T i.u Δ t i.R i.a) (Nat.clog 2 (i.height + 1)) + (i.n + 8) (History.Reset.Child.extra P Δ i.n) + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev issueCost (i : Phase.Case F 1 d) (head : ℕ) := + let U := next P i.S i.T i.u Δ t i.R i.a + let p := Nat.clog 2 (i.height + 1) + Tile.printCost i.T U p (i.n + 8) (History.Reset.Child.extra P Δ i.n) + (Beat.accessCost (i.m + i.T.scheme.d) (Tile.volume i.T U p (i.n + 8))) head + +variable {h s hk q P hc cost} + +open scoped Classical in +/-- The value specified by `(z.rows, z.move.commands)`. -/ +abbrev Print.whole (z : Print h s hk q P hc cost) : (Tile.whole T N).obj := + (z.rows, z.move.commands) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Local information needed for one deterministic reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y l : ℕ} [NeZero Y] [NeZero l] + {S : Setup F x y} {T : Template F} {u Δ t : ℕ} {R : Budget} {w r d K : ℕ} {σ κ : ℝ} + (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) + (P : Rotor F Y l) (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +open History.Reset +local notation "a" => (T.scheme.h - r) +local notation "N" => (next P S T u Δ t R a) +local notation "X" => (frame S T u Δ R) +local notation "k" => Nat.clog 2 (T.scheme.h + 1) +local notation "n" => (T.scheme.h - a + 8) +local notation "extra" => History.Reset.Child.extra P Δ (T.scheme.h - a) +local notation "mx" => T.scheme.m + extra +local notation "dx" => History.Reset.Child.width (degreeBound S T Δ) Y T.full +local notation "par" => (History.Reset.Setup.parent T extra) + +open scoped Classical in +/-- The data for the local print construction, including `out`, `nav`, `fields`, `headers`, +`control`. -/ +structure LocalPrint where + /-- The `LocalPrint` component of type `∀ i : (X).state, Print h s hk i P hc cost`. -/ + out : ∀ i : (X).state, Print h s hk i P hc cost + nav : ∀ i : (X).state, (out i).move.nav = fun j _ => par j + fields : Tile.Local T N k n extra (Nat.sub_le ..) rfl + (fun i : (X).state => (board h s hk i).tape) (fun i => (out i).whole) + /-- The `LocalPrint` component of type `(X).state → (Tile.headers T N extra).obj`. -/ + headers : (X).state → (Tile.headers T N extra).obj + control : Tile.HeaderLocal T N k n extra (Nat.sub_le ..) + (fun i : (X).state => (board h s hk i).tape) headers + build : ∀ i : (X).state, Child.build T.scheme.m T.scheme.d extra dx + (T.nav i.val.rows, headers i) = Tile.header N (out i).rows + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Sufficient local allocation properties for the two dictionary gates -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y l : ℕ} [NeZero Y] [NeZero l] + {S : Setup F x y} {T : Template F} {u Δ t : ℕ} {R : Budget} {w r d K : ℕ} {σ κ : ℝ} + (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) + (P : Rotor F Y l) (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +open History.Reset + +open scoped Classical in +/-- The selection used in the `Restore` construction. -/ +abbrev selection := History.Reset.Setup.Selection + (poll h s hk) P (fun i => fits h s hk i P hc cost) (board h s hk) + (book S T u t R) (meter S t R) (Nat.sub_le T.scheme.h r) + +variable {h s hk P hc cost} + +open scoped Classical in +/-- Builds `LocalPrint h s hk P hc cost where out i` with the specified `out`, `nav`, `fields`, +`intro`. -/ +def arrange (A : selection h s hk P hc cost) : LocalPrint h s hk P hc cost where + out i := assemble h s hk i P hc cost (A.layout i) (A.graph i) + (A.placed i).block (A.placed i).parent (A.describes i) + nav _ := rfl + fields := by + intro i + have d := ok h s hk i + exact A.fields (d.corePos.trans_le d.full) d.late (fun j => j.property.neutral) + (fun j => ready h s hk j P hc cost (A.layout j) (A.graph j).1 + (History.Reset.Setup.hop _ _ (A.describes j))) i + headers := A.headers + control := A.control + build := A.build + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Controller combining the mixer and the two local dictionary gates -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y l : ℕ} [NeZero Y] [NeZero l] + {S : Setup F x y} {T : Template F} {u Δ t : ℕ} {R : Budget} {w r d K : ℕ} {σ κ : ℝ} + (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) + (P : Rotor F Y l) (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +open History.Reset +local notation "N" => (next P S T u Δ t R (T.scheme.h - r)) +local notation "X" => (frame S T u Δ R) +local notation "k" => Nat.clog 2 (T.scheme.h + 1) +local notation "n" => (T.scheme.h - (T.scheme.h - r) + 8) +local notation "extra" => History.Reset.Child.extra P Δ (T.scheme.h - (T.scheme.h - r)) +local notation "mx" => T.scheme.m + extra +local notation "dx" => History.Reset.Child.width (degreeBound S T Δ) Y T.full +local notation "par" => (History.Reset.Setup.parent T extra) + +open scoped Classical in +/-- The value specified by `Template.Mix.arity i.T (keyBits d i) (indices i.S i.r i.R Δ)`. -/ +abbrev setupWidth (i : Phase.Case F 1 d) := Template.Mix.arity i.T (keyBits d i) (indices i.S i.r + i.R Δ) +open scoped Classical in +/-- The quantity computed by `Template.Mix.cost i.T (keyBits d i) (indices i.S i.r i.R Δ) +(i.height - t - i.a)`. -/ +abbrev setupCost (i : Phase.Case F 1 d) := + Template.Mix.cost i.T (keyBits d i) (indices i.S i.r i.R Δ) (i.height - t - i.a) +open scoped Classical in +/-- The value specified by `Tile.headerWidth i.T (child P Δ t d i) (keyBits d i) (depth d i) +(expansion P Δ d i)`. -/ +abbrev graphWidth (i : Phase.Case F 1 d) := + Tile.headerWidth i.T (child P Δ t d i) (keyBits d i) (depth d i) (expansion P Δ d i) +open scoped Classical in +/-- The graph cost used in the `Restore` construction. -/ +abbrev graphCost (i : Phase.Case F 1 d) := + Tile.headerCost i.T (child P Δ t d i) (keyBits d i) (depth d i) (expansion P Δ d i) (readCost P Δ + t d i) + + 4 * Child.buildCost i.m i.T.scheme.d (expansion P Δ d i) (child P Δ t d i).scheme.d + +open scoped Classical in +/-- The quantity computed by `setupWidth (Δ:=Δ) i + graphWidth (Δ:=Δ) (t:=t) P i + issueWidth +(Δ:=Δ) (t:=t) P i`. -/ +abbrev width (i : Phase.Case F 1 d) := setupWidth (Δ:=Δ) i + graphWidth (Δ:=Δ) (t:=t) P i + + issueWidth (Δ:=Δ) (t:=t) P i +open scoped Classical in +/-- The value specified by `setupCost (Δ:=Δ) (t:=t) i + issueCost (Δ:=Δ) (t:=t) P i (graphCost +(Δ:=Δ) (t:=t) P i) + applyCost i.S i.T (child P Δ t d i)`. -/ +abbrev total (i : Phase.Case F 1 d) := setupCost (Δ:=Δ) (t:=t) i + + issueCost (Δ:=Δ) (t:=t) P i (graphCost (Δ:=Δ) (t:=t) P i) + applyCost i.S i.T (child P Δ t d i) + +variable {h s hk P hc cost} +local notation "z" => indices S r R Δ +local notation "i₀" => sample h + +open scoped Classical in +private theorem LocalPrint.write_computes (L : LocalPrint h s hk P hc cost) + {v : ℕ} {allow : Set (Table F)} (three : 3 ≤ v) + (pre : Computes F v allow T.format (Tile.pair T k) + (fun i : (X).state => i.val.rows) (fun i => (board h s hk i).tape) + (fun _ => 1) (setupCost (Δ := Δ) (t := t) i₀)) + (body : Computes F v allow (Tile.pair T k) (Tile.whole T N) + (fun i : (X).state => (board h s hk i).tape) (fun i => (L.out i).whole) + (fun _ => 1) (issueCost (Δ := Δ) (t := t) P i₀ (graphCost (Δ := Δ) (t := t) P i₀))) : + Computes F v allow (S.format T) (S.format N) (fun i => i.val.code) + (fun i => ((L.out i).rows, (L.out i).move.update S.d i.val.trail)) + (fun _ => 1) (total (Δ := Δ) (t := t) P i₀) := by + have run := pre.comp body + simp only [one_mul] at run + exact apply_net three (fun i : (X).state => i.val) (fun i => (L.out i).rows) + (fun i => (L.out i).move) par L.nav run + +private abbrev mixParameters (S : Setup F x y) (T : Template F) (u Δ t r : ℕ) (R : Budget) : + Template.Mix.Params := + ⟨T.scheme.h - r, u, Δ, degreeBound S T Δ, 2 ^ S.discount, Template.Encodes.margin Δ, + (2 : ℝ) ^ t * (R.load * S.z : ℕ)⟩ + +omit [Fintype F] [NeZero Y] [NeZero l] in +open scoped Classical in +private theorem write_prepares {v : ℕ} {allow : Set (Table F)} + (fits : Template.Mix.arity T k z ≤ v) + (keys : (Template.Mix.keys T k z (mixParameters S T u Δ t r R) : Set (Table F)) ⊆ allow) : + Computes F v allow T.format (Tile.pair T k) + (fun i : (X).state => i.val.rows) (fun i => (board h s hk i).tape) + (fun _ => 1) (setupCost (Δ := Δ) (t := t) i₀) := by + have hkey : T.scheme.h < 2 ^ k := Nat.le_pow_clog (by decide : 1 < 2) _ + exact Computes.of_map + (Template.Mix.prepare_net T k z (mixParameters S T u Δ t r R) fits keys t hkey) + (fun _ => rfl) + +omit [Field F] [Fintype F] in +open scoped Classical in +private theorem write_label_bounds (keys : Finset (Table F)) (body gate : Table F) {g f b : ℕ} + (few : keys.card ≤ 12) (limited : ∀ j ∈ keys, Processor.arity j ≤ g) + (bodyArity : Processor.arity body ≤ b) (gateArity : Processor.arity gate ≤ f) : + (insert body (insert gate keys)).card ≤ 14 ∧ + ∀ j ∈ insert body (insert gate keys), Processor.arity j ≤ g + f + b := by + constructor + · iterate 2 + apply (Finset.card_insert_le ..).trans + apply Nat.add_le_add_right + exact few + · intro j hj + simp only [Finset.mem_insert] at hj + rcases hj with rfl | rfl | hj + · exact bodyArity.trans (Nat.le_add_left ..) + · exact (gateArity.trans (Nat.le_add_left ..)).trans (Nat.le_add_right ..) + · exact ((limited j hj).trans (Nat.le_add_right ..)).trans (Nat.le_add_right ..) + +omit [NeZero Y] [NeZero l] in +open scoped Classical in +private theorem sample_width : + width (Δ := Δ) (t := t) P i₀ = + Template.Mix.arity T k z + Tile.headerWidth T N k n extra + Tile.printWidth T N k n extra := + rfl + +open scoped Classical in +theorem LocalPrint.write (L : LocalPrint h s hk P hc cost) (hd : d ≤ K) : + Nonempty (Writer h s hk P hc cost 14 (width (Δ:=Δ) (t:=t) P i₀) (total (Δ:=Δ) (t:=t) P i₀)) + := by + obtain ⟨body, gate, hbody, eqn, net⟩ := Tile.writer_net T N k n extra (Nat.sub_le ..) rfl + (fun i : (X).state => (board h s hk i).tape) (fun i : (X).state => (L.out i).whole) + L.headers L.fields L.control L.build (fun i => i.val.encodes.reciprocal) (by omega) + let C := mixParameters S T u Δ t r R + let keys := Template.Mix.keys T k z C + let labels := insert body (insert gate keys) + let allow := Allowed F w ∪ (labels : Set (Table F)) + let g := Template.Mix.arity T k z + let f := Tile.headerWidth T N k n extra + let b := Tile.printWidth T N k n extra + let v := 3 + g + f + b + 2 * 2 ^ (2 * w) * (4 * w) + have three : 3 ≤ v := by unfold v; omega + have gf : g ≤ v := by unfold v; omega + have ff : f ≤ v := by unfold v; omega + have bf : b ≤ v := by unfold v; omega + have acc := access h T.scheme.d (Tile.volume T N k n) v + (h.degree.trans (hd.trans (Nat.le_mul_of_pos_right _ (Nat.zero_lt_succ _)))) + (↑labels) (Nat.le_add_left ..) + have kernels : (keys : Set (Table F)) ⊆ allow := + fun _ ht => Or.inr (Finset.mem_insert_of_mem (Finset.mem_insert_of_mem ht)) + have pre := write_prepares (h := h) (s := s) (hk := hk) gf kernels + have both : Computes F v allow (Tile.pair T k) (Tile.whole T N) + (fun i : (X).state => (board h s hk i).tape) (fun i => (L.out i).whole) + (fun _ => 1) (issueCost (Δ := Δ) (t := t) P i₀ (graphCost (Δ := Δ) (t := t) P i₀)) := + net (L := allow) three bf ff (Or.inr (Finset.mem_insert_self ..)) + (Or.inr (Finset.mem_insert_of_mem (Finset.mem_insert_self ..))) acc + have final := L.write_computes three pre both + obtain ⟨count, narrow⟩ := write_label_bounds keys body gate (Template.Mix.few T k z C) + (fun _ hj => Template.Mix.narrow T k z C hj) hbody.le eqn.le + refine ⟨⟨L.out, v, labels, count, ?_, ?_⟩⟩ + · rw [sample_width (h := h)] + exact narrow + · exact final + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- # Closing the uniform reset bounds -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Phase Phase.Case +variable {F : Type} [Field F] [Fintype F] + +theorem phase_of_local {Y l Δ t d : ℕ} [NeZero Y] [NeZero l] (P : Rotor F Y l) + (s : Slice Δ Y l t) {κ : ℝ} (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + (build : ∀ {x y : Wire} {S : Setup F x y} {T : Template F} {R : Budget} + {w r u K : ℕ} {σ : ℝ} (h : Input S T R w r 1 u u d K σ) (hk : 2 ^ t ≤ K), + Nonempty (LocalPrint h s hk P hc cost)) : + ∃ K, 0 < K ∧ Phase F Δ 3 d 2 1 K (2 * resetWidth κ l) (2 * resetWidth κ l) := by + have hw : Short (width (Δ:=Δ) (t:=t) (d:=d) P) := + ((summaryWidth Δ d).add (headerWidth_bound P Δ t d)).add (printWidth_bound P Δ t d) + have hm : Cost (total (Δ:=Δ) (t:=t) (d:=d) P) := + ((summaryCost Δ t d).add (printCost_bound P Δ t d (headerCost_bound P Δ t d))).add + (applyCost_bound (child_bound P Δ t d)) + refine rule_of_bounds P s hc cost d (short_const 14) hw hm ?_ + intro x y S T R w r u K σ h hk hd + obtain ⟨out⟩ := build h hk + exact out.write hd + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +end + +/- +# A controlled degree reset over a finite field + +The elected layout supplies both the local tensor description and +the graph header. The two resulting gates work on every input +branch of the phase with the same cost bounds. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y l : ℕ} [NeZero Y] [NeZero l] + {S : Setup F x y} {T : Template F} {u Δ t : ℕ} {R : Budget} {w r d K : ℕ} {σ κ : ℝ} + (h : Phase.Input S T R w r 1 u u d K σ) + (s : Slice Δ Y l t) (hk : 2 ^ t ≤ K) + (P : Rotor F Y l) (hc : 1 ≤ κ) (cost : (Fintype.card P.E : ℝ) ≤ κ * Y * l) + +open scoped Classical in +theorem choose_layout : Nonempty (LocalPrint h s hk P hc cost) := by + have enough (i : (frame S T u Δ R).state) : (poll h s hk i).Room P (fits h s hk i P hc cost) + (next P S T u Δ t R (T.scheme.h - r)).scheme := room h s hk i P hc cost + let A : selection h s hk P hc cost := History.Reset.Setup.select + (poll h s hk) P (fun i => fits h s hk i P hc cost) (board h s hk) + (book S T u t R) (meter S t R) (Nat.sub_le T.scheme.h r) enough + exact ⟨arrange A⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Restore + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Restore Packing + +theorem resetRule (F : Type) [Field F] [Finite F] : ResetRule F := by + let : Fintype F := Fintype.ofFinite F + intro y w Δ P κ hw hΔ hy hc hcost + let _ : NeZero w := ⟨hw.ne'⟩ + have cost : (Fintype.card P.E : ℝ) ≤ κ * (2 ^ y : ℕ) * w + := by simpa only [Nat.cast_pow, Nat.cast_ofNat] using hcost + obtain ⟨t, s⟩ := exists_slice Δ (2 ^ y) w hy hΔ + refine ⟨2, fun d => phase_of_local P s hc cost ?_⟩ + intro x y S T R w r u K σ h hk + exact choose_layout h s hk P hc cost + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Stack/StartBound.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Stack/StartBound.lean new file mode 100644 index 0000000000..9c49579ba7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Stack/StartBound.lean @@ -0,0 +1,1007 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.TraceNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Phase.ResetRate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Elect + +/-! # Short neighbor and port indices for the initial host -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Coloring Assembly Packing Finset + +variable {F : Type} {x y : Wire} (G : Diagram F x y) (m : ℕ) + +open scoped Classical in +/-- The data for the addresses construction, including `host`, `link`, `localPort`. -/ +structure Addresses where + /-- Embeds the coordinates as `G.V × Bool ↪ B m`. -/ + host : G.V × Bool ↪ B m + /-- Embeds the coordinates as `∀ v, ↥(adjacent G v) ↪ B 3`. -/ + link : ∀ v, ↥(adjacent G v) ↪ B 3 + /-- Embeds the coordinates as `∀ v, G.Port v ↪ B 2`. -/ + localPort : ∀ v, G.Port v ↪ B 2 + +open scoped Classical in +theorem addresses (ht : G.Trivalent) (hm : 2 * Fintype.card G.V ≤ 2 ^ m) : + Nonempty (Addresses G m) := by + obtain ⟨host⟩ : Nonempty (G.V × Bool ↪ B m) := + Function.Embedding.nonempty_of_card_le (by simpa [mul_comm] using hm) + have link v : Nonempty (↥(adjacent G v) ↪ B 3) := + Function.Embedding.nonempty_of_card_le (by simpa using adj_size G ht v) + have localPort v : Nonempty (G.Port v ↪ B 2) := by + apply Function.Embedding.nonempty_of_card_le + simpa [Diagram.Port, Diagram.arity] using (ht v).trans (by decide : 3 ≤ 4) + exact ⟨⟨host, fun v => (link v).some, fun v => (localPort v).some⟩⟩ + +namespace Addresses +variable {G m} (A : Addresses G m) + +open scoped Classical in +/-- Padding names the host itself. The mask separates padding from +true self contacts. Initially the full and core lists coincide. -/ +def get (i : B m) (j : B 3) : Option (B m) := + if h : ∃ v, A.host v = i then + if g : ∃ w, A.link h.choose w = j then some (A.host g.choose.val) else none + else none + +open scoped Classical in +/-- The value specified by `(A.get i j).getD i`. -/ +def nav (i : B m) (j : B 3) := (A.get i j).getD i + +open scoped Classical in +/-- The value specified by `((A.get i j).isSome, (A.get i j).isSome)`. -/ +def mask (i : B m) (j : B 3) : Bool × Bool := ((A.get i j).isSome, (A.get i j).isSome) + +open scoped Classical in +/-- Returns `A.link v ⟨z, h⟩` when `h : z ∈ adjacent G v` holds, and `0` otherwise. -/ +def index (v z : G.V × Bool) := if h : z ∈ adjacent G v then A.link v ⟨z, h⟩ else 0 + +open scoped Classical in +theorem get_iff (i : B m) (j : B 3) (w : B m) : + A.get i j = some w ↔ ∃ v, A.host v = i ∧ ∃ t : ↥(adjacent G v), + A.link v t = j ∧ A.host t.val = w := by + unfold get + split + · rename_i h + split + · rename_i g + refine ⟨fun he => ⟨_, h.choose_spec, _, g.choose_spec, Option.some.inj he⟩, ?_⟩ + rintro ⟨v, hv, t, ht, hw⟩ + have := A.host.injective (hv.trans h.choose_spec.symm) + subst v + rw [(A.link _).injective (g.choose_spec.trans ht.symm), hw] + · rename_i g + refine iff_of_false (by simp) ?_ + rintro ⟨v, hv, t, ht, _⟩ + have := A.host.injective (hv.trans h.choose_spec.symm) + subst v + exact g ⟨t, ht⟩ + · rename_i h + exact iff_of_false (by simp) fun ⟨v, hv, _⟩ => h ⟨v, hv⟩ + +open scoped Classical in +theorem get_link {v z : G.V × Bool} (hz : z ∈ adjacent G v) : + A.get (A.host v) (A.index v z) = some (A.host z) := + (A.get_iff ..).mpr ⟨v, rfl, ⟨z, hz⟩, by simp [index, hz], rfl⟩ + +open scoped Classical in +theorem nav_link {v z : G.V × Bool} (hz : z ∈ adjacent G v) : + A.nav (A.host v) (A.index v z) = A.host z := by simp [nav, A.get_link hz] + +open scoped Classical in +theorem closed (v : G.V × Bool) (j : B 3) : A.nav (A.host v) j ∈ Set.range A.host := by + unfold nav + cases h : A.get _ _ with + | none => exact ⟨v, rfl⟩ + | some w => + obtain ⟨_, _, q, _, hq⟩ := (A.get_iff ..).mp h + exact ⟨q.val, hq⟩ + +open scoped Classical in +theorem mask_eq (v z : G.V × Bool) : z ∈ adjacent G v ↔ + ∃ j, A.nav (A.host v) j = A.host z ∧ (A.mask (A.host v) j).1 = true := by + refine ⟨fun h => ⟨A.index v z, A.nav_link h, by simp [mask, A.get_link h]⟩, ?_⟩ + rintro ⟨j, hj, ht⟩ + obtain ⟨a, ha⟩ := Option.isSome_iff_exists.mp ht + obtain ⟨u, hu, t, _, he⟩ := (A.get_iff ..).mp ha + have := A.host.injective hu + subst u + simp only [nav, ha, Option.getD_some] at hj + exact A.host.injective (he.trans hj) ▸ t.property + +open scoped Classical in +private theorem occupiedFromAddresses {i j w} (hw : A.nav i j = w) (hne : w ≠ i) : + A.get i j = some w := by + unfold nav at hw + cases he : A.get i j with + | none => rw [he] at hw; exact (hne hw.symm).elim + | some _ => simpa [he] using hw + +open scoped Classical in +theorem unique {i a b} (hne : A.nav i a ≠ i) (h : A.nav i a = A.nav i b) : a = b := by + obtain ⟨v, hv, t, ht, he⟩ := (A.get_iff ..).mp (A.occupiedFromAddresses rfl hne) + obtain ⟨v', hv', t', ht', he'⟩ := (A.get_iff ..).mp (A.occupiedFromAddresses h.symm hne) + have := A.host.injective (hv'.trans hv.symm) + subst v' + have : t = t' := Subtype.ext (A.host.injective (he.trans he'.symm)) + rw [← ht, ← ht', this] + +open scoped Classical in +theorem reciprocal (i : B m) (j : B 3) (h : A.nav i j ≠ i) : + ∃! k, A.nav (A.nav i j) k = i := by + obtain ⟨v, hv, t, _, he⟩ := (A.get_iff ..).mp (A.occupiedFromAddresses rfl h) + have hk : A.nav (A.nav i j) (A.index t.val v) = i := by + rw [← he, A.nav_link (adj_symm G _ _ t.property), hv] + exact ⟨_, hk, fun k hm => A.unique (fun e => h (e.symm.trans hm)) (hm.trans hk.symm)⟩ + +end Addresses +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end + +/- +# A fixed palette for all initial stacks + +A pattern stores one trivalent table and the short names of its +incident ports. Its dictionary entry evaluates the product across +the stack. The label length depends only on the ground field. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Coloring Assembly Packing Transcript + +open scoped Classical in +/-- Indexes the port info by the coordinates of `Bool × Option (B 3 × B 0 × B 2)`. -/ +abbrev PortInfo := Bool × Option (B 3 × B 0 × B 2) +open scoped Classical in +/-- Indexes the atom by the coordinates of `(B 2 → Option PortInfo) × ((B 2 → Bool) → F)`. -/ +abbrev Atom (F : Type) := (B 2 → Option PortInfo) × ((B 2 → Bool) → F) + +variable {F : Type} [Field F] {a b : Wire} {m h u : ℕ} {G : Diagram F a b} + +open scoped Classical in +/-- Returns `u` when `i.isSome` holds, and `0` otherwise. -/ +def width (u : ℕ) (i : Option PortInfo) := if i.isSome then u else 0 + +open scoped Classical in +/-- Builds `Pattern F 3 0 2 where width _ q` with the specified `width`, `direction`, `peer`, +`value`. -/ +def pattern (u : ℕ) (a : Atom F) : Pattern F 3 0 2 where + width _ q := width u (a.1 q) + direction _ q := ((a.1 q).map Prod.fst).getD false + peer _ q := (a.1 q).bind Prod.snd + value _ z := ∏ i : Fin u, a.2 fun q => + if h : i.val < width u (a.1 q) then z q ⟨i.val, h⟩ else false + +namespace Addresses +variable (A : Addresses G m) + +open scoped Classical in +/-- Computes the stub by the application `A.localPort (G.portEquiv.symm q).1 (G.portEquiv.symm +q).2`. -/ +def stub (q : G.End) : B 2 := + A.localPort (G.portEquiv.symm q).1 (G.portEquiv.symm q).2 + +omit [Field F] in +open scoped Classical in +@[simp] theorem stub_port (v : G.V) (t : G.Port v) : + A.stub (G.portEquiv ⟨v, t⟩) = A.localPort v t := + congrArg (fun z : Σ i, G.Port i => A.localPort z.1 z.2) (G.portEquiv.symm_apply_apply ⟨v, t⟩) + +open scoped Classical in +/-- The value specified by `(A.host (G.station q, false), A.stub q)`. -/ +def key (q : G.End) := (A.host (G.station q, false), A.stub q) + +omit [Field F] in +open scoped Classical in +theorem key_inj : Function.Injective A.key := by + intro p q he + obtain ⟨⟨v, i⟩, rfl⟩ := G.portEquiv.surjective p + obtain ⟨⟨w, j⟩, rfl⟩ := G.portEquiv.surjective q + simp only [key, Diagram.station_port, stub_port, Prod.mk.injEq, A.host.injective.eq_iff, + and_true] at he + obtain ⟨rfl, h⟩ := he + rw [(A.localPort _).injective h] + +open scoped Classical in +/-- The link at of type `PortInfo` for the given inputs. -/ +def linkAt (q : G.End) : PortInfo := + (q.isRight, match q with + | .inl (.inr e) => some (A.index (G.source e, false) (G.target e, false), 0, + A.stub (.inr (.inr e))) + | .inr (.inr e) => some (A.index (G.target e, false) (G.source e, false), 0, + A.stub (.inl (.inr e))) + | _ => none) + +open scoped Classical in +/-- The atom of type `Atom F` for the given inputs. -/ +def atom (v : B m) : Atom F := + (fun i => Function.extend A.key (fun q => some (A.linkAt q)) (fun _ => none) (v, i), + if h : ∃ z, A.host (z, false) = v then + fun x => sample (G.table h.choose) (x ∘ A.localPort h.choose) + else fun _ => 1) + +open scoped Classical in +theorem info (q : G.End) : (A.atom (A.key q).1).1 (A.key q).2 = some (A.linkAt q) := + A.key_inj.extend_apply (fun q => some (A.linkAt q)) (fun _ => none) q + +open scoped Classical in +theorem info_of (v : B m) (i : B 2) (hi : (A.atom v).1 i ≠ none) : + ∃ q, A.key q = (v, i) := by + by_contra h + exact hi (Function.extend_apply' (fun q => some (A.linkAt q)) (fun _ => none) _ h) + +open scoped Classical in +theorem scalar (v : G.V) : (A.atom (A.host (v, false))).2 = + fun x => sample (G.table v) (x ∘ A.localPort v) := by + have h : ∃ z, A.host (z, false) = A.host (v, false) := ⟨v, rfl⟩ + unfold atom + rw [dite_eq_left h, (Prod.mk.inj (A.host.injective h.choose_spec)).1] + +end Addresses + +variable (F) [Fintype F] + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def length := Nat.clog 2 (Nat.card (Atom F)) + +open scoped Classical in +/-- Embeds `Atom F` into `B (length F)`. -/ +def label : Atom F ↪ B (length F) := + Classical.choice (Function.Embedding.nonempty_of_card_le (by + rw [Fintype.card_fin, length, Nat.card_eq_fintype_card] + exact Nat.le_pow_clog (by decide) _)) + +open scoped Classical in +/-- The scheme of type `Scheme F where m` for the given inputs. -/ +abbrev scheme (m h u : ℕ) : Scheme F where + m := m + h := h + k := 0 + e := 2 + d := 3 + ℓ := length F + decode := Function.extend (label F) (pattern u) (fun _ => pattern u (fun _ => none, fun _ => 1)) + +variable {F} (A : Addresses G m) + +open scoped Classical in +/-- Evaluates `(A.nav i, fun _ => (label F) (A.atom i))` at the input `i`. -/ +def records (h u : ℕ) : (scheme F m h u).format.obj := + fun i => (A.nav i, fun _ => (label F) (A.atom i)) + +open scoped Classical in +theorem pattern_at (i : (scheme F m h u).Vtx) : + (scheme F m h u).pattern (records A h u) i = pattern u (A.atom i.1) := + (label F).injective.extend_apply (pattern u) (fun _ => pattern u (fun _ => none, fun _ + => 1)) (A.atom i.1) + +open scoped Classical in +theorem records_reciprocal (h u : ℕ) : + Fmt.Reciprocal (.vec h (.addr (length F))) (records A h u) := A.reciprocal + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end + +/- # Spans of the initial posting -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack.Addresses +open Coloring Assembly Packing + +variable {F : Type} [Field F] [Fintype F] {a b : Wire} {m h u : ℕ} {G : Diagram F a b} + (A : Addresses G m) + +local notation "S" => scheme F m h u +local notation "R" => records A h u + +open scoped Classical in +/-- Embeds `Cell h × G.V` into `B m × B h × B 0 where toFun x`. -/ +def vertex (h : ℕ) : Cell h × G.V ↪ B m × B h × B 0 where + toFun x := (A.host (x.2, false), cellIndex h x.1, 0) + inj' := by + intro x y he + obtain ⟨hv, hb, _⟩ := Prod.mk.inj he |>.imp_right Prod.mk.inj + exact Prod.ext ((cellIndex h).injective hb) (Prod.mk.inj (A.host.injective hv)).1 + +open scoped Classical in +/-- The value specified by `(A.vertex h (z, G.station e), A.stub e)`. -/ +def span (z : Cell h) (e : G.End) := (A.vertex h (z, G.station e), A.stub e) + +open scoped Classical in +theorem width_eq (p : (S).Span) : (S).width R p = width u ((A.atom p.1.1).1 p.2) := by + rw [Scheme.width, pattern_at]; rfl + +open scoped Classical in +theorem width_at (z : Cell h) (e : G.End) : (S).width R (A.span z e) = u := by + rw [width_eq] + change width u ((A.atom (A.key e).1).1 (A.key e).2) = u + rw [A.info]; rfl + +open scoped Classical in +theorem direction_at (z : Cell h) (e : G.End) : (S).direction R (A.span z e) = e.isRight := by + rw [Scheme.direction, pattern_at] + change (((A.atom (A.key e).1).1 (A.key e).2).map Prod.fst).getD false = _ + rw [A.info]; rfl + +open scoped Classical in +theorem link_at (z : Cell h) (e : G.End) : + ((S).pattern R (A.span z e).1).peer (A.span z e).1.2.2 (A.span z e).2 = (A.linkAt e).2 := by + rw [pattern_at] + change ((A.atom (A.key e).1).1 (A.key e).2).bind Prod.snd = _ + rw [A.info]; rfl + +open scoped Classical in +theorem represent (p : (S).Span) (hp : (A.atom p.1.1).1 p.2 ≠ none) : + ∃ z e, p = A.span z e := by + obtain ⟨e, h⟩ := A.info_of _ _ hp + obtain ⟨hx, hy⟩ := Prod.mk.inj h + refine ⟨(cellIndex _).symm p.1.2.1, e, Prod.ext ?_ hy.symm⟩ + exact Prod.ext hx.symm (Prod.ext ((cellIndex _).apply_symm_apply _).symm (Fin.eq_zero _)) + +open scoped Classical in +theorem occupied (p : (S).Span) (hp : 0 < (S).width R p) : ∃ z e, p = A.span z e := by + refine A.represent p fun he => ?_ + simp [width_eq, he, width] at hp + +open scoped Classical in +/-- An internal edge has two named ends. -/ +def edgeEnd (e : G.E) (b : Bool) : G.End := cond b (.inr (.inr e)) (.inl (.inr e)) + +open scoped Classical in +theorem peer_edge (z : Cell h) (e : G.E) (t : Bool) : + (S).peer R (A.span z (edgeEnd e t)) = some (A.span z (edgeEnd e (!t))) := by + have hz : (G.target e, false) ∈ adjacent G (G.source e, false) := + Finset.mem_product.mpr ⟨target_mem G e, Finset.mem_univ _⟩ + rw [Scheme.peer, link_at] + cases t + · exact congrArg (fun x => some ((x, cellIndex h z, 0), A.stub (.inr (.inr e)))) (A.nav_link hz) + · exact congrArg (fun x => some ((x, cellIndex h z, 0), A.stub (.inl (.inr e)))) + (A.nav_link (adj_symm G _ _ hz)) + +open scoped Classical in +theorem peer_outer (z : Cell h) (i : Outer a b) : + (S).peer R (A.span z (boundaryEnd G i)) = none := by + rw [Scheme.peer, link_at] + cases i <;> rfl + +open scoped Classical in +theorem proper : (S).Proper R := by + intro p q hp + have used : (A.atom p.1.1).1 p.2 ≠ none := by + intro hh + rw [Scheme.peer, pattern_at] at hp + simp [pattern, hh] at hp + obtain ⟨z, e, rfl⟩ := A.represent p used + have internal (e : G.E) (t : Bool) (hp : (S).peer R (A.span z (edgeEnd e t)) = some q) : + (S).peer R q = some (A.span z (edgeEnd e t)) ∧ + (S).width R (A.span z (edgeEnd e t)) = (S).width R q ∧ + (S).direction R (A.span z (edgeEnd e t)) ≠ (S).direction R q := by + rw [peer_edge, Option.some.injEq] at hp + subst q + rw [peer_edge, Bool.not_not, width_at, width_at, direction_at, direction_at] + exact ⟨rfl, rfl, by cases t <;> simp [edgeEnd]⟩ + rcases e with (i|e)|(j|e) + · have := (A.peer_outer (u := u) z (.inl i)).symm.trans hp; cases this + · exact internal e false hp + · have := (A.peer_outer (u := u) z (.inr j)).symm.trans hp; cases this + · exact internal e true hp + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack.Addresses +end + +/- # Local pin bijections for the initial product tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack.Addresses +open Assembly Packing Coloring Transcript + +variable {F : Type} [Field F] [Fintype F] {a b : Wire} {m h u n : ℕ} {G : Diagram F a b} + (A : Addresses G m) + +local notation "S" => scheme F m h u +local notation "R" => records A h u + +open scoped Classical in +theorem port_width (v : Cell h × G.V) (p : G.Port v.2) : + (S).width R (A.vertex h v, A.localPort v.2 p) = u := by + simpa only [span, Diagram.station_port, stub_port] using A.width_at (u + := u) v.1 (G.portEquiv ⟨v.2, p⟩) + +open scoped Classical in +/-- Uses `⟨A.localPort v.2 p.2, p.1.cast (A.port_width v p.2).symm⟩` as the representation. -/ +def carrying (v : Cell h × G.V) (p : Fin u × G.Port v.2) : + (S).LocalPin R (A.vertex h v) := ⟨A.localPort v.2 p.2, p.1.cast (A.port_width v p.2).symm⟩ + +open scoped Classical in +theorem bijective (v : Cell h × G.V) : Function.Bijective (A.carrying (u := u) v) := by + constructor + · intro x y he + have hi := congrArg (fun p => p.2.val) he + have hs := congrArg Sigma.fst he + exact Prod.ext (Fin.ext hi) ((A.localPort _).injective hs) + · rintro ⟨s, j⟩ + obtain ⟨z, e, he⟩ := A.occupied (A.vertex h v, s) (Nat.zero_lt_of_lt j.isLt) + obtain ⟨⟨a, i⟩, rfl⟩ := G.portEquiv.surjective e + simp only [span, Diagram.station_port, stub_port, Prod.mk.injEq, (A.vertex h).injective.eq_iff] + at he + obtain ⟨rfl, rfl⟩ := he + exact ⟨(j.cast (A.port_width (z, a) i), i), rfl⟩ + +open scoped Classical in +/-- Reindexes `Ports (tensor (G.table v.2) u)` and `(S).LocalPin R (A.vertex h v)` by an +equivalence. -/ +def pins (v : Cell h × G.V) : Ports (tensor (G.table v.2) u) ≃ (S).LocalPin R (A.vertex h v) := + (pin (G.table v.2) u).trans (Equiv.ofBijective _ (A.bijective v)) + +omit [Fintype F] in +open scoped Classical in +private theorem eval_pattern (p : Pattern F 3 0 2) (a : Atom F) (he : p = pattern u a) + (k : B 0) (x : ∀ s, Fin (p.width k s) → Bool) : + p.value k x = ∏ i : Fin u, a.2 (fun s => if h : i.val < p.width k s then x s ⟨i.val, h⟩ + else false) := by + subst p; rfl + +open scoped Classical in +theorem value_at (v : (S).Vtx) (x : (S).LocalPin R v → Bool) : + (S).table R v x = ∏ i : Fin u, (A.atom v.1).2 + (fun q => if h : i.val < (S).width R (v, q) then x ⟨q, ⟨i.val, h⟩⟩ else false) := + eval_pattern _ _ (pattern_at A v) v.2.2 (fun q i => x ⟨q, i⟩) + +open scoped Classical in +theorem sample_at (v : Cell h × G.V) (x : (S).LocalPin R (A.vertex h v) → Bool) : + (S).table R (A.vertex h v) x = sample (tensor (G.table v.2) u) (x ∘ A.pins v) := by + rw [value_at, sample_tensor, show (A.vertex h v).1 = A.host (v.2, false) from rfl, A.scalar] + apply Finset.prod_congr rfl + intro i _ + apply congrArg (sample (G.table v.2)) + funext q + have lt : i.val < (S).width R (A.vertex h v, A.localPort v.2 q) + := by rw [port_width]; exact i.isLt + simp only [Function.comp_apply, dite_eq_left lt, pins, Equiv.trans_apply, Equiv.apply_symm_apply] + rfl + +open scoped Classical in +theorem vacant (v : (S).Vtx) (hv : v ∉ Set.range (A.vertex h)) (x : (S).LocalPin R v → Bool) : + (S).table R v x = 1 := by + have hn : ¬∃ z, A.host (z, false) = v.1 := by + rintro ⟨z, hz⟩ + refine hv ⟨((cellIndex _).symm v.2.1, z), ?_⟩ + exact Prod.ext hz (Prod.ext ((cellIndex _).apply_symm_apply _) (Fin.eq_zero _).symm) + rw [value_at] + simp only [atom, dite_eq_right hn, Finset.prod_const_one] + +open scoped Classical in +/-- Builds `(S).Seating R (gathered G c) where vertex` with the specified `vertex`, `pin`, +`cover`, `obtain`. -/ +def seating (c : Cell h × Fin u ≃ Fin n) : (S).Seating R (gathered G c) where + vertex := A.vertex h + pin := A.pins + cover p := by + obtain ⟨z, e, he⟩ := A.occupied p.1 (Nat.zero_lt_of_lt p.2.isLt) + exact ⟨(z, G.station e), congrArg Prod.fst he.symm⟩ + sample := A.sample_at + vacant := A.vacant + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack.Addresses +end + +/- # A posting with one span for each original stack -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack.Addresses +open Assembly Coloring Packing + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {m h u n : ℕ} {G : Diagram F x y} + (A : Addresses G m) (c : Cell h × Fin u ≃ Fin n) + +local notation "S" => scheme F m h u +local notation "R" => records A h u + +open scoped Classical in +private def copyPort (t : Cell h × Fin u) (p : Σ v, G.Port v) : Σ j, (gathered G c).Port j := + ⟨(t.1, p.1), (pin (G.table p.1) u).symm (t.2, p.2)⟩ + +open scoped Classical in +private theorem read (t : Cell h × Fin u) (p : G.End) (q : (gathered G c).End) + (hp : (gathered G c).portEquiv.symm q = copyPort c t (G.portEquiv.symm p)) : + ((A.seating c).ends q).1 = A.span t.1 p ∧ ((A.seating c).ends q).2.val = t.2.val := by + obtain ⟨⟨v, i⟩, rfl⟩ := G.portEquiv.surjective p + rw [Equiv.symm_apply_apply] at hp + rw [← (gathered G c).portEquiv.apply_symm_apply q, hp, copyPort, (A.seating c).ends_at] + have eq : (A.seating c).pin (t.1, v) ((pin (G.table v) u).symm (t.2, i)) = + A.carrying (t.1, v) (t.2, i) := + congrArg (A.carrying (t.1, v)) ((pin (G.table v) u).apply_symm_apply (t.2, i)) + rw [eq] + simp only [span, stub_port, Diagram.station_port] + exact ⟨rfl, rfl⟩ + +open scoped Classical in +theorem read_edge (t : Cell h × Fin u) (e : G.E) (s : Bool) : + let q := (A.seating c).ends (edgeEnd (t, e) s) + q.1 = A.span t.1 (edgeEnd e s) ∧ q.2.val = t.2.val := by + apply A.read c + cases s <;> rfl + +open scoped Classical in +theorem read_input (i : slots (copies x n)) : + let r := Diagonal.port x n i + let t := c.symm r.1 + let q := (A.seating c).ends (.inl (.inl i)) + q.1 = A.span t.1 (.inl (.inl r.2)) ∧ q.2.val = t.2.val := + A.read c _ _ _ rfl + +open scoped Classical in +theorem read_output (i : slots (copies y n)) : + let r := Diagonal.port y n i + let t := c.symm r.1 + let q := (A.seating c).ends (.inr (.inl i)) + q.1 = A.span t.1 (.inr (.inl r.2)) ∧ q.2.val = t.2.val := + A.read c _ _ _ rfl + +open scoped Classical in +/-- Builds `(S).Presentation R (gathered G c) where toSeating` with the specified `toSeating`, +`proper`, `internal`, `obtain`. -/ +def presentation : (S).Presentation R (gathered G c) where + toSeating := A.seating c + proper := A.proper + internal e := by + obtain ⟨t, e⟩ := e + have a := A.read_edge c t e false + have b := A.read_edge c t e true + change (S).Joins R ((A.seating c).ends (edgeEnd (t, e) false)) ((A.seating c).ends (edgeEnd (t, + e) true)) + exact ⟨by rw [a.1, b.1, peer_edge]; rfl, a.2.trans b.2.symm⟩ + input i := by rw [(A.read_input c i).1]; exact A.peer_outer _ (.inl _) + output i := by rw [(A.read_output c i).1]; exact A.peer_outer _ (.inr _) + +open scoped Classical in +/-- Builds `(S).Posting R (groups G c) where toPresentation` with the specified +`toPresentation`, `host`, `block`, `stub`. -/ +def posting : (S).Posting R (groups G c) where + toPresentation := A.presentation c + host := A.host + block := (cellIndex h).toEmbedding + stub i t := A.stub (edgeEnd i.1 t) + index := A.index + vertex_eq _ := rfl + ordered i t j := by + have h := A.read_edge c (i.2, j) i.1 t + cases t <;> exact h + length i t := by + have h := A.width_at (u := u) i.2 (edgeEnd i.1 t) + cases t <;> exact h + dir i t := by + have h := A.direction_at (u := u) i.2 (edgeEnd i.1 t) + cases t <;> exact h + link i t := by + have h := A.link_at (u := u) i.2 (edgeEnd i.1 t) + cases t <;> exact h + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack.Addresses +end + +/- # Exterior history and initial occurrence loads -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Assembly Coloring Packing Finset + +variable {F : Type} [Field F] {x y : Wire} {h u m : ℕ} {G : Diagram F x y} + +open scoped Classical in +theorem parked (v : G.V) (t : Bool) (z : Cell h) : + push (start G h u).park (fun _ => 1) ((v, t), z) = + if t then (exterior G id v : ℝ) * u else 0 := by + rw [push, ← (bit h u x y).sum_comp, Fintype.sum_prod_type, sum_comm] + simp_rw [Fintype.sum_prod_type, start_park] + rw [port_load] + change (∑ i : Outer x y, ∑ s : Cell h, ∑ _ : Fin u, + @ite ℝ (((portEnd G i, true), s) = ((v, t), z)) (Classical.propDecidable _) 1 0) = _ + simp only [Prod.mk.injEq] + cases t <;> simp [ite_and, push, add_mul, sum_mul, ite_mul, -sum_boole] + +open scoped Classical in +theorem load_initial (v : G.V) (t : Bool) (z : Cell h) (k l : ℕ) : + ((start G h u).reserve k l).load (v, t) z = + (if t then exterior G id v else G.arity v : ℕ) * (u : ℝ) := by + let Q := (start G h u).reserve k l + rw [Q.load_eq ((v, t), z)] + simp only [show Q.past ((v, t), z) = 0 from rfl, Nat.cast_zero, mul_zero, add_zero] + change push (locate G (ordinal h u) false) (fun i => ((gathered G (ordinal h u)).arity i : ℝ)) _ + + 1 * push (start G h u).park (fun _ => 1) ((v, t), z) = _ + rw [parked, one_mul] + have eq (i : Cell h × G.V) : (gathered G (ordinal h u)).arity i = u * G.arity i.2 := by + simp only [Diagram.arity, wd_copies, mul_add] + unfold push + simp_rw [eq] + change (∑ i : Cell h × G.V, @ite ℝ (((i.2, false), i.1) = ((v, t), z)) (Classical.propDecidable _) + (↑(u * G.arity i.2)) 0) + _ = _ + simp only [Fintype.sum_prod_type, Prod.mk.injEq] + cases t <;> simp [ite_and, mul_comm] + +namespace Addresses +variable [Fintype F] (A : Addresses G m) +local notation "S" => scheme F m h u +local notation "R" => records A h u + +open scoped Classical in +/-- The initial of type `(S).Posting R ((start G h u).reserve k l)`, constructed using +`A.posting (ordinal h u)`. -/ +def initial (k l : ℕ) : (S).Posting R ((start G h u).reserve k l) := + let p := A.posting (ordinal h u) + ⟨p.toPresentation, p.host, p.block, p.stub, p.index, p.vertex_eq, p.ordered, p.length, p.dir, + p.link⟩ + +open scoped Classical in +theorem boundary (k l : ℕ) (i : Outer x y) (z : Cell h) (t : Fin u) : + let q := ((A.initial (h := h) (u := u) k l).toPresentation.boundary (bit h u x y ((z, t), + i))).val + q.1 = A.span z (boundaryEnd G i) ∧ q.2.val = t.val := by + let c := ordinal h u + cases i with + | inl i => + have hx := A.read_input c ((Diagonal.port x (2 ^ h * u)).symm (c (z, t), i)) + simp only [Equiv.apply_symm_apply, Equiv.symm_apply_apply] at hx + exact hx + | inr i => + have hy := A.read_output c ((Diagonal.port y (2 ^ h * u)).symm (c (z, t), i)) + simp only [Equiv.apply_symm_apply, Equiv.symm_apply_apply] at hy + exact hy + +open scoped Classical in +theorem history (ht : G.Trivalent) (k l : ℕ) (hu : 0 < u) {d e : ℕ} (hd : 3 ≤ d) + (name : Outer x y ↪ (Fin e → Bool)) : + ∃ a : Trail.Record (scheme F m h u) h d e, + Trail.Tracks (A.initial (h := h) (u := u) k l).toPresentation name a := by + let host : G.V ↪ B m := ⟨fun v => A.host (v, false), fun _ _ h + => (Prod.mk.inj (A.host.injective h)).1⟩ + refine Trail.initial G ht _ host hu hd name fun i z => ?_ + refine ⟨A.span z (boundaryEnd G i), A.width_at z _, ?_, A.boundary k l i z⟩ + change A.host (G.station (boundaryEnd G i), false) = _ + rw [station_boundary]; rfl + +end Addresses +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end + +/- +# Initial template with constant-length block records + +The counter names a side and a multiplicity from zero to three. +Both the palette and the counter length are independent of the +stack width, the number of stations and the replication factor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Assembly Coloring Packing Finset + +open scoped Classical in +/-- Computes the counter code by the application `Fintype.equivOfCardEq (by simp)`. -/ +def counterCode : Bool × Fin 4 ≃ B 3 := Fintype.equivOfCardEq (by simp) + +variable (F : Type) [Field F] [Fintype F] + +open scoped Classical in +/-- Builds `Template F where scheme` with the specified `scheme`, `count`, `load`, `park`. -/ +abbrev template (m h u : ℕ) : Template F where + scheme := scheme F m h u + count := 3 + load i := (counterCode.symm i).2.val * (u : ℝ) + park i := if (counterCode.symm i).1 then (counterCode.symm i).2.val * (u : ℝ) else 0 + past _ := 0 + order := Equiv.refl _ + full := false + +open scoped Classical in +theorem template_width (m h u : ℕ) : + (template F m h u).format.width = 2 ^ m * (8 * (m + 2) + 2 + 2 ^ h * (length F + 3)) := + (template F m h u).width + +namespace Addresses +variable {F} {a b : Wire} {h u m : ℕ} {G : Diagram F a b} (A : Addresses G m) (ht : G.Trivalent) + +omit [Field F] [Fintype F] in +open scoped Classical in +theorem exterior_le (v : G.V) : exterior G id v ≤ G.arity v := by + have := site_arity G id v + simp only [push, id_eq, sum_ite_eq', mem_univ, ite_true] at this + apply Nat.cast_le (α := ℝ) |>.mp + rw [this] + exact le_add_of_nonneg_right (Nat.cast_nonneg _) + +open scoped Classical in +/-- The meter of type `B 3` for the given inputs. -/ +def meter (v : G.V × Bool) : B 3 := + counterCode (v.2, ⟨if v.2 then exterior G id v.1 else G.arity v.1, by + have := ht v.1 + have := exterior_le v.1 + split_ifs <;> omega⟩) + +open scoped Classical in +/-- The indexed operation `((true, v.2), A.mask (A.host v), fun _ => meter ht v)`. -/ +def header (h : ℕ) (v : G.V × Bool) : (Bool × Bool) × ((B 3 → Bool × Bool) × (B h → B 3)) := + ((true, v.2), A.mask (A.host v), fun _ => meter ht v) + +open scoped Classical in +/-- The indexed operation `((false, false), fun _ => (false, false), fun _ => 0)`. -/ +def idle (h : ℕ) : (Bool × Bool) × ((B 3 → Bool × Bool) × (B h → B 3)) := + ((false, false), fun _ => (false, false), fun _ => 0) + +open scoped Classical in +/-- The indexed operation `(records A h u, Function.extend A.host (A.header ht h) (fun _ => idle +h))`. -/ +def snapshot (h u : ℕ) : (template F m h u).format.obj := + (records A h u, Function.extend A.host (A.header ht h) + (fun _ => idle h)) + +open scoped Classical in +theorem header_at (v : G.V × Bool) : + (A.snapshot ht h u).2 (A.host v) = A.header ht h v := + A.host.injective.extend_apply (A.header ht h) (fun _ => idle h) v + +open scoped Classical in +/-- The same initial metadata works with any history budget. -/ +def encodes (h u k l : ℕ) : + (template F m h u).Encodes (A.snapshot ht h u) ((start G h u).reserve k l) where + post := A.initial k l + block _ := rfl + live i := by + change ((A.snapshot ht h u).2 i).1.1 = true ↔ i ∈ Set.range A.host + by_cases hi : i ∈ Set.range A.host + · obtain ⟨v, rfl⟩ := hi + rw [header_at] + exact iff_of_true rfl ⟨v, rfl⟩ + · have he : ((A.snapshot ht h u).2 i).1.1 = false := by + exact congrArg (fun x => x.1.1) (Function.extend_apply' (A.header ht h) (fun _ + => idle h) i hi) + simp [he, hi] + frozen v := by + change G.V × Bool at v + change ((A.snapshot ht h u).2 (A.host v)).1.2 = true ↔ v.2 = true + rw [header_at]; rfl + closed := A.closed + reciprocal := records_reciprocal A h u + edge v z := by + change G.V × Bool at v z + change _ ↔ ∃ j, A.nav (A.host v) j = A.host z ∧ (((A.snapshot ht h u).2 (A.host v)).2.1 j).1 + = true + rw [header_at] + exact A.mask_eq v z + core v z := by + change G.V × Bool at v z + change _ ↔ ∃ j, A.nav (A.host v) j = A.host z ∧ (((A.snapshot ht h u).2 (A.host v)).2.1 j).2 + = true + rw [header_at] + exact A.mask_eq v z + load v i := by + change G.V × Bool at v + change (template F m h u).load (((A.snapshot ht h u).2 (A.host v)).2.2 _) = _ + rw [header_at] + obtain ⟨v, b⟩ := v + rw [load_initial] + simp only [template, header, meter, Equiv.symm_apply_apply] + park v i := by + change G.V × Bool at v + change (template F m h u).park (((A.snapshot ht h u).2 (A.host v)).2.2 _) = + push (start G h u).park (fun _ => 1) (v, i) + rw [header_at] + obtain ⟨v, b⟩ := v + rw [parked] + cases b <;> simp [template, header, meter] + past _ _ := rfl + +end Addresses +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end + +/- +# Initial data for the descent + +Each nonempty active position carries at least one whole stack. +This pays for its constant-length label. A sweep extracts the +coefficients of isolated scalar stations before the first phase. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Assembly Coloring Packing Finset + +variable {F : Type} [Field F] {x y : Wire} (S : Setup F x y) + +open scoped Classical in +private theorem incidence (v : S.G.V) (t : Bool) (b : Cell S.h) : + S.first.tetherLoad ((v, t), b) + degree S.first.pair ((v, t), b) * S.U = + (if t then 0 else S.G.arity v) * S.U := by + have he := load_initial (G := S.G) (u := S.U) v t b S.cap S.discount + change (S.first.tetherLoad ((v, t), b) : ℝ) + degree S.first.pair ((v, t), b) * (S.U : ℝ) + + 1 * push (start S.G S.h S.U).park (fun _ => 1) ((v, t), b) + + S.first.rate * (0 : ℕ) = _ at he + rw [parked] at he + apply Nat.cast_injective (R := ℝ) + push_cast + cases t <;> simp at he ⊢ <;> linarith + +open scoped Classical in +private theorem first_tracks : S.first.Tracks S.first 1 := by + have he (v : S.first.V) : (S.first.reach S.first v).card ≤ 1 := by + refine (card_le_card (t := {v}) ?_).trans_eq (card_singleton v) + intro i hi + obtain ⟨_, h, h'⟩ := (HostNet.mem_reach _ _).mp hi + exact mem_singleton.mpr (h'.symm.trans h) + exact ⟨he, by simpa using he⟩ + +variable [Fintype F] (w M : ℕ) + +open scoped Classical in +/-- The quantity computed by `template F (max w (Nat.clog 2 (2 * M))) S.h S.U`. -/ +abbrev initialTemplate := template F (max w (Nat.clog 2 (2 * M))) S.h S.U + +open scoped Classical in +/-- The quantity computed by `⟨6 * (S.U / S.z), length F + 1, 1, 3 * (M : ℝ) * S.count, 0⟩`. -/ +def initialBudget (S : Setup F x y) (M : ℕ) : Budget := + ⟨6 * (S.U / S.z), length F + 1, 1, 3 * (M : ℝ) * S.count, 0⟩ + +local notation "T" => initialTemplate S w M + +open scoped Classical in +private theorem first_ready (ht : S.G.Trivalent) (hn : Nonempty S.G.V) + (hM : Fintype.card S.G.V ≤ M) (hu : 0 < S.U) (hz : S.z ∣ S.U) (hd : 3 ≤ S.d) : + ∃ d : Snapshot.Data S T S.U, d.G.diagram.eval = power S.G.eval S.count ∧ + Ready 8 (initialBudget S M) d.sweep := by + let m := max w (Nat.clog 2 (2 * M)) + have hm : 2 * Fintype.card S.G.V ≤ 2 ^ m := + (Nat.mul_le_mul_left _ hM).trans ((Nat.le_pow_clog (by decide : 1 < 2) _).trans + (Nat.pow_le_pow_right (by decide) (le_max_right _ _))) + obtain ⟨a⟩ := addresses S.G m ht hm + obtain ⟨trail, htrail⟩ := a.history (h := S.h) ht S.cap S.discount hu hd S.name + let d : Snapshot.Data S T S.U := + ⟨S.first, a.snapshot ht S.h S.U, trail, a.encodes ht S.h S.U S.cap S.discount, + htrail, HostNet.Preserves.refl _⟩ + have empty : (start S.G S.h S.U).mass = 0 := by + change ∑ _ : (start S.G S.h S.U).V × Cell S.h, (0 : ℕ) = 0 + simp + refine ⟨d, start_exact _, ⟨⟨(hn.some, false)⟩, d.sweep_neutral, ?_, ?_, first_tracks S, ?_, ?_⟩⟩ + · apply (d.sweep_tagged _).mpr + rintro ⟨v, t⟩ b hab + have hl : S.z ≤ S.first.tetherLoad ((v, t), b) + degree S.first.pair ((v, t), b) * S.U := by + change 0 < S.first.tetherLoad ((v, t), b) + degree S.first.pair ((v, t), b) * S.U at hab + rw [incidence] at hab ⊢ + exact (Nat.le_of_dvd hu hz).trans (Nat.le_mul_of_pos_left S.U (Nat.pos_of_mul_pos_right hab)) + apply Nat.mul_le_mul + · exact (History.Dense.used_le.mpr (Fin.isLt _)).trans (Nat.le_succ _) + · exact hl.trans (by change _ ≤ 0 + S.first.tetherLoad _ + degree S.first.pair _ * S.U; omega) + · have hb : S.first.Bounded 8 8 (3 * (S.U : ℝ)) := + (bounded S.G (ordinal S.h S.U) ht).start_budget _ empty S.cap S.discount + have hb' : 8 ≤ degreeBound S (T).sweep 8 := + (Nat.le_add_right _ _).trans (Nat.le_add_right _ _) + refine ⟨hb.1, fun v => (hb.2.1 v).trans hb', ?_⟩ + intro v i + refine (hb.2.2 v i).trans ?_ + change 3 * (S.U : ℝ) ≤ (6 * (S.U / S.z) : ℕ) * (S.z : ℝ) + rw [← Nat.cast_mul, mul_assoc, Nat.div_mul_cancel hz, Nat.cast_mul] + norm_num + linarith [Nat.cast_nonneg (α := ℝ) S.U] + · have hh := S.G.cost_trivalent ht + rw [S.G.cost_eq] at hh + have hE : Fintype.card S.G.E ≤ 3 * M := by omega + change ((start S.G S.h S.U).X : ℝ) ≤ 3 * (M : ℝ) * S.count + rw [start_width, Nat.cast_mul, mul_comm] + exact mul_le_mul_of_nonneg_right (by exact_mod_cast hE) (by positivity) + · change ((start S.G S.h S.U).mass : ℝ) ≤ 0 + rw [empty, Nat.cast_zero] + +open scoped Classical in +theorem begin_frame (ht : S.G.Trivalent) (hn : Nonempty S.G.V) + (hM : Fintype.card S.G.V ≤ M) (hu : 0 < S.U) (hz : S.z ∣ S.U) (hd : 3 ≤ S.d) : + ∃ (X : Assembly.Snapshot.{1} F S.input S.output) (i : X.state) (v : X.port.obj), + X.port.width = (S.format T).width ∧ X.eval i = power S.G.eval S.count ∧ + (∀ a b, X.encode i a b = v) ∧ + Transforms F (3 + 2 * length F) {Snapshot.sweepTable T} X + (frame S (T).sweep S.U 8 (initialBudget S M)) (Snapshot.sweepCost S T) := by + obtain ⟨d, he, h⟩ := first_ready S w M ht hn hM hu hz hd + let P := fun q : Snapshot.Data S T S.U => Ready 8 (initialBudget S M) q.sweep + refine ⟨Snapshot.restrict P, ⟨d, h⟩, d.code, rfl, he, fun _ _ => rfl, ?_⟩ + exact Snapshot.sweep (fun _ h => h) (by omega) + (show 2 * length F ≤ 3 + 2 * length F by omega) (Set.mem_singleton _) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end + +section +/- # Cost and control limits for the initial frame -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +open Assembly Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} + +omit [Field F] [Fintype F] in +private theorem sweep_cost (S : Setup F x y) (T : Template F) (hc : 1 ≤ T.count) : + Snapshot.sweepCost S T + (S.format T).width ≤ 6 * (S.format T).width := by + have he : (S.format T).width = T.scheme.format.width + + (Format.vec T.scheme.m T.header).width + (Trail.format T.scheme S.h S.d S.e).width := by + rw [Format.width_pair, Format.width_pair] + have hw : 2 ^ T.scheme.m * 2 ^ T.scheme.h ≤ (S.format T).width := by + rw [Format.width_pair, Template.width] + apply le_trans _ (Nat.le_add_right _ _) + apply Nat.mul_le_mul_left + exact (Nat.le_mul_of_pos_right _ (by omega)).trans (Nat.le_add_left _ _) + have hu : updateCost T.scheme.m T.scheme.d T.scheme.h (.addr T.scheme.ℓ) (.addr T.scheme.ℓ) ≤ + 4 * T.scheme.format.width + 2 ^ T.scheme.m * 2 ^ T.scheme.h := by + rw [updateCost, Fmt.width_rows, Format.width_addr] + ring_nf + omega + unfold Snapshot.sweepCost + omega + +theorem start_bound {S : Setup F x y} {w M A L : ℕ} (hL : 8 ≤ L) (ha : L ≤ A) (hw : 1 ≤ w) + (hm : max w (Nat.clog 2 (2 * M)) ≤ 3 * w) (he : S.e ≤ 3 * w) + (hd : S.d ≤ L) (hh : S.h ≤ A) (ht : length F ≤ A) : + let T := initialTemplate S w M + Snapshot.sweepCost S T + (S.format T).width ≤ + 600 * A ^ 3 * 2 ^ (T.scheme.m + S.h) + 600 * L * 2 ^ T.scheme.m * w := by + let T := initialTemplate S w M + have hv := Regroup.format_bound (T := T) (by omega : 2 ≤ L) ha hw rfl hm he hL hd hh ht + (show 4 ≤ A by omega) (show 3 ≤ A by omega) + calc + _ ≤ 6 * (S.format T).width := sweep_cost S T (show 1 ≤ 3 by decide) + _ ≤ 6 * (100 * A ^ 3 * 2 ^ (T.scheme.m + S.h) + 100 * L * 2 ^ T.scheme.m * w) + := Nat.mul_le_mul_left 6 hv + _ = _ := by ring + +theorem first_inside (S : Setup F x y) (L : Limits) (M d : ℕ) (H : Enough S L) (hd : 3 ≤ d) + (hp : L.start = initialBudget S M) (hm : L.m = max L.w (Nat.clog 2 (2 * M))) + (hz : S.z ∣ S.U) (hlen : length F + 1 ≤ L.A) : + Inside S L (initialTemplate S L.w M).sweep (initialBudget S M) S.U d 0 := by + have hA : 4 ≤ L.A := by + have := H.basic + have := Nat.two_pow_pos L.r + have := Nat.two_pow_pos S.discount + omega + have hw := Nat.pow_le_pow_right (by omega : 0 < L.A) H.positive + have ha : L.A ≤ L.A ^ L.K := by simpa using hw + have hc : L.A ≤ L.code := calc + _ ≤ 3 * L.A ^ L.K := by omega + _ ≤ L.extra := by + simpa only [pow_one, Limits.extra] using + Nat.pow_le_pow_right (by omega : 0 < 3 * L.A ^ L.K) H.positive + _ ≤ L.code := Nat.le_mul_of_pos_left _ (by omega) + refine ⟨?_, le_max_left _ _, ?_, hd, rfl, rfl, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · change S.h + 0 * L.r = S.h + omega + · rw [hm, zero_mul, add_zero] + · exact hA.trans ha + · exact le_trans (by decide : 3 ≤ 4) (hA.trans ha) + · exact (Nat.le_succ _).trans (hlen.trans hc) + · simp [hp] + · change S.U ≤ 6 * (S.U / S.z) * S.z + rw [mul_assoc, Nat.div_mul_cancel hz] + omega + · simp [hp] + · exact Nat.zero_lt_one + · simp [hp] + · exact mul_nonneg (by positivity) (by positivity) + · exact le_rfl + · simp [hp] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Stack +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Sweep.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Sweep.lean new file mode 100644 index 0000000000..68c1e7781a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Sweep.lean @@ -0,0 +1,845 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Hop +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Observed +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Budget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.TraceNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes + +/-! +# Moving a block prefix into the host coordinate + +The table labels stay unchanged. Each neighbor address acquires the +same prefix as the current host, independently of the label data. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +open Assembly Coloring Packing + +variable {F : Type} + +/-- The quantity computed by `{ S with m := S.m + k, h := S.h - k }`. -/ +abbrev target (S : Scheme F) (k : ℕ) : Scheme F := { S with m := S.m + k, h := S.h - k } + +variable {S : Scheme F} (k : ℕ) (hk : k ≤ S.h) + +/-- Reindexes `B S.h` and `B k × B (S.h - k)` by an equivalence. -/ +def blocks : B S.h ≃ B k × B (S.h - k) := + (cellIndex _).symm.trans ((splitCell k hk).trans ((cellIndex _).prodCongr (cellIndex _))) + +/-- Reindexes `S.Vtx` and `(target S k).Vtx where toFun v` by an equivalence. -/ +def room : S.Vtx ≃ (target S k).Vtx where + toFun v := ((Match.rowIndex S.m k).symm (v.1, (blocks k hk v.2.1).1), + (blocks k hk v.2.1).2, v.2.2) + invFun v := ((Match.rowIndex S.m k v.1).1, + (blocks k hk).symm ((Match.rowIndex S.m k v.1).2, v.2.1), v.2.2) + left_inv v := by simp + right_inv v := by simp + +/-- Reindexes `S.Span` and `(target S k).Span` by an equivalence. -/ +def span : S.Span ≃ (target S k).Span := (room k hk).prodCongr (.refl _) + +/-- The rows of type `(target S k).format.obj`, constructed using `Match.rowIndex S.m k i`. -/ +def rows (r : S.format.obj) : (target S k).format.obj := fun i => + let a := Match.rowIndex S.m k i + (fun j => (Match.rowIndex S.m k).symm ((r a.1).1 j, a.2), + fun j => (r a.1).2 ((blocks k hk).symm (a.2, j))) + +/-- Builds `Trail.Record (target S k) h d e where short` with the specified `short`, `long`. -/ +def trail {h d e : ℕ} (data : Trail.Record S h d e) : Trail.Record (target S k) h d e where + short := data.short ∘ (span k hk).symm + long := fun i => data.long (Match.rowIndex S.m k i).1 + +variable (r : S.format.obj) + +theorem pattern (v : S.Vtx) : + (target S k).pattern (rows k hk r) (room k hk v) = S.pattern r v := by + simp [Scheme.pattern, rows, room, target] + +theorem width (q : S.Span) : + (target S k).width (rows k hk r) (span k hk q) = S.width r q := by + exact congrArg (fun t => t.width q.1.2.2 q.2) (pattern k hk r q.1) + +theorem direction (q : S.Span) : + (target S k).direction (rows k hk r) (span k hk q) = S.direction r q := by + exact congrArg (fun t => t.direction q.1.2.2 q.2) (pattern k hk r q.1) + +theorem peer (q : S.Span) : + (target S k).peer (rows k hk r) (span k hk q) = (S.peer r q).map (span k hk) := by + unfold Scheme.peer + change (((target S k).pattern (rows k hk r) (room k hk q.1)).peer q.1.2.2 q.2).map _ = _ + rw [pattern, Option.map_map] + congr 1 + funext x + simp [span, room, rows] + +theorem proper (hp : S.Proper r) : (target S k).Proper (rows k hk r) := by + intro a b h + obtain ⟨q, rfl⟩ := (span k hk).surjective a + obtain ⟨w, rfl⟩ := (span k hk).surjective b + rw [peer, Option.map_eq_some_iff] at h + obtain ⟨t, ht, he⟩ := h + have := (span k hk).injective he + subst t + obtain ⟨hw, hl, hd⟩ := hp _ _ ht + rw [peer, hw, width, width, direction, direction] + exact ⟨rfl, hl, hd⟩ + +/-- Indexes the pins by the coordinates of `Σ t, Fin (P.width j t)`. -/ +abbrev Pins {d l e : ℕ} (P : Pattern F d l e) (j : B l) := + Σ t, Fin (P.width j t) + +/-- The equivalence obtained by `Equiv.sigmaCongrRight fun t => finCongr (congrArg (fun a => +a.width j t) he.symm)`. -/ +def pins {d l e : ℕ} {P Q : Pattern F d l e} (he : Q = P) (j : B l) : + Pins P j ≃ Pins Q j := + Equiv.sigmaCongrRight fun t => finCongr (congrArg (fun a => a.width j t) he.symm) + +private theorem value {d l e : ℕ} {P Q : Pattern F d l e} (he : Q = P) (j : B l) + (t : Pins Q j → Bool) : + Q.value j (fun s i => t ⟨s, i⟩) = P.value j (fun s i => t (pins he j ⟨s, i⟩)) := by + cases he + rfl + +/-- Computes the ports by the application `pins (pattern k hk r v) v.2.2`. -/ +def ports (v : S.Vtx) : + S.LocalPin r v ≃ (target S k).LocalPin (rows k hk r) (room k hk v) := + pins (pattern k hk r v) v.2.2 + +theorem table (v : S.Vtx) + (t : (target S k).LocalPin (rows k hk r) (room k hk v) → Bool) : + (target S k).table (rows k hk r) (room k hk v) t = S.table r v (t ∘ ports k hk r v) := + value (pattern k hk r v) v.2.2 t + +variable {r} [Field F] {x y : Wire} {G : Diagram F x y} + +/-- Builds `(target S k).Seating (rows k hk r) G where vertex` with the specified `vertex`, +`pin`, `cover`, `rintro`. -/ +def seat (p : S.Seating r G) : (target S k).Seating (rows k hk r) G where + vertex := p.vertex.trans (room k hk).toEmbedding + pin v := (p.pin v).trans (ports k hk r _) + cover := by + rintro ⟨q, i⟩ + obtain ⟨a, rfl⟩ := (span k hk).surjective q + obtain ⟨v, hv⟩ := p.cover ⟨a, finCongr (width k hk r a) i⟩ + exact ⟨v, congrArg (room k hk) hv⟩ + sample v t := (table k hk r _ t).trans (p.sample v _) + vacant := by + intro v hv t + obtain ⟨z, rfl⟩ := (room k hk).surjective v + rw [table] + apply p.vacant + rintro ⟨i, rfl⟩ + exact hv ⟨i, rfl⟩ + +theorem seat_ends (p : S.Seating r G) (z : G.End) : + ((seat k hk p).ends z).1 = span k hk (p.ends z).1 ∧ + ((seat k hk p).ends z).2.val = (p.ends z).2.val := by + obtain ⟨⟨v, i⟩, rfl⟩ := G.portEquiv.surjective z + rw [Scheme.Seating.ends_at, Scheme.Seating.ends_at] + exact ⟨rfl, rfl⟩ + +/-- Builds `(target S k).Presentation (rows k hk r) G where toSeating` with the specified +`toSeating`, `proper`, `internal`, `obtain`. -/ +def presentation (p : S.Presentation r G) : (target S k).Presentation (rows k hk r) G where + toSeating := seat k hk p.toSeating + proper := proper k hk r p.proper + internal i := by + obtain ⟨h, hi⟩ := p.internal i + obtain ⟨hl, he⟩ := seat_ends k hk p.toSeating (.inl (.inr i)) + obtain ⟨hr, hf⟩ := seat_ends k hk p.toSeating (.inr (.inr i)) + exact ⟨by rw [hl, hr, peer, h]; rfl, he.trans (hi.trans hf.symm)⟩ + input i := by rw [(seat_ends k hk p.toSeating _).1, peer, p.input]; rfl + output i := by rw [(seat_ends k hk p.toSeating _).1, peer, p.output]; rfl + +theorem outer (p : S.Presentation r G) (z : slots x ⊕ slots y) : + ((presentation k hk p).boundary z).val.1 = span k hk (p.boundary z).val.1 ∧ + ((presentation k hk p).boundary z).val.2.val = (p.boundary z).val.2.val := by + cases z with + | inl i => exact seat_ends k hk p.toSeating (.inl (.inl i)) + | inr i => exact seat_ends k hk p.toSeating (.inr (.inl i)) + +section +variable {T : Type} {L : Fringe x y T} {u : ℕ} {Q : HostNet F L S.h u} + (p : S.Posting r Q) (hb : p.block = (cellIndex S.h).toEmbedding) + +/-- Embeds `(Q.regroup k hk).V` into `B (S.m + k)`. -/ +def host : (Q.regroup k hk).V ↪ B (S.m + k) := + (p.host.prodMap (cellIndex k).toEmbedding).trans (Match.rowIndex S.m k).symm.toEmbedding + +include hb in +theorem place (v : Q.V) (c : Cell S.h) : + room k hk (p.host v, p.block c, 0) = + (host k hk p (v, ancestor hk c), cellIndex _ (suffix k c), 0) := by + rw [hb] + simp [room, blocks, host, splitCell] + rfl + +include hb in +theorem spanAt (i : Q.E) (t : Bool) : + (target S k).spanAt (Q.regroup k hk) (host k hk p) (cellIndex _).toEmbedding p.stub i t = + span k hk (p.span i t) := by + cases t <;> exact Prod.ext (place k hk p hb _ _).symm rfl + +/-- Builds `(target S k).Posting (rows k hk r) (Q.regroup k hk) where toPresentation` with the +specified `toPresentation`, `host`, `block`, `stub`. -/ +def post : (target S k).Posting (rows k hk r) (Q.regroup k hk) where + toPresentation := presentation k hk p.toPresentation + host := host k hk p + block := (cellIndex _).toEmbedding + stub := p.stub + index i j := p.index i.1 j.1 + vertex_eq v := by + change room k hk (p.vertex v) = _ + rw [p.vertex_eq v] + exact place k hk p hb _ _ + ordered i t j := by + obtain ⟨hs, he⟩ := seat_ends k hk p.toSeating (Scheme.endBit Q i t j) + obtain ⟨hp, hj⟩ := p.ordered i t j + exact ⟨hs.trans ((congrArg (span k hk) hp).trans (spanAt k hk p hb i t).symm), he.trans hj⟩ + length i t := by rw [spanAt k hk p hb i t, width]; exact p.length i t + dir i t := by rw [spanAt k hk p hb i t, direction]; exact p.dir i t + link i t := by + rw [spanAt k hk p hb i t] + change ((target S k).pattern (rows k hk r) (room k hk (p.span i t).1)).peer + (p.span i t).1.2.2 (p.span i t).2 = _ + rw [pattern] + cases t + · exact p.link i false + · exact p.link i true + +end + +variable {h u d e : ℕ} {T : Type} {L : Fringe (copies x (2 ^ h * u)) (copies y (2 ^ h * u)) T} + {z : ℕ} {Q : HostNet F L S.h z} (p : S.Posting r Q) + (hb : p.block = (cellIndex S.h).toEmbedding) + {name : Stack.Outer x y ↪ (Fin e → Bool)} {data : Trail.Record S h d e} + +theorem marked {lane : B S.m → Stack.Outer x y → Fin d} + (hp : Trail.Marked p.toPresentation name data lane) : + Trail.Marked (post k hk p hb).toPresentation name (trail k hk data) + (fun j => lane (Match.rowIndex S.m k j).1) := by + intro i c + obtain ⟨a, hw, hs, hl, he⟩ := hp i c + have host_eq : (Match.rowIndex S.m k (span k hk a).1.1).1 = a.1.1 := by simp [span, room] + refine ⟨span k hk a, (width k hk r a).trans hw, ?_, ?_, fun t => ?_⟩ + · simpa only [trail, Function.comp_apply, Equiv.symm_apply_apply, host_eq] using hs + · simpa only [trail, host_eq] using hl + · obtain ⟨h₁, h₂⟩ := outer k hk p.toPresentation (Stack.bit h u x y ((c, t), i)) + exact ⟨h₁.trans (congrArg (span k hk) (he t).1), h₂.trans (he t).2⟩ + +theorem tracks (hp : Trail.Tracks p.toPresentation name data) : + Trail.Tracks (post k hk p hb).toPresentation name (trail k hk data) := + ⟨_, marked k hk p hb hp.choose_spec⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +end + +/- # The cost of transferring labels when blocks are regrouped -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +open Assembly Coloring Packing + +variable {F : Type} {S : Scheme F} (k : ℕ) (hk : k ≤ S.h) (h d e : ℕ) + +/-- Computes the tape by the application `S.format.pair (Trail.format S h d e)`. -/ +abbrev tape (S : Scheme F) (h d e : ℕ) := S.format.pair (Trail.format S h d e) + +/-- The value specified by `(rows k hk x.1, trail k hk x.2)`. -/ +def repack (x : (tape S h d e).obj) : (tape (target S k) h d e).obj := + (rows k hk x.1, trail k hk x.2) + +local notation "A" => tape S h d e +local notation "D" => tape (target S k) h d e + +private theorem wiring (q : (D).pins) : + (∃ p : (A).pins, ∀ x, (D).code (repack k hk h d e x) q = (A).code x p) ∨ + (∃ b, ∀ x, (D).code (repack k hk h d e x) q = b) := by + rcases q with ⟨i, ⟨j, l⟩ | ⟨j, l⟩⟩ | (⟨v, t⟩ | ⟨i, j, t⟩) + · obtain ⟨s | s, hs⟩ := Match.append_pin S.m k l + · left + exact ⟨.inl ((Match.rowIndex S.m k i).1, .inl (j, s)), fun x => hs _ _⟩ + · right + exact ⟨(Format.addr k).code (Match.rowIndex S.m k i).2 s, fun x => hs _ _⟩ + · left + let a := Match.rowIndex S.m k i + exact ⟨.inl (a.1, .inr ((blocks k hk).symm (a.2, j), l)), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inl ((span k hk).symm v, t)), fun _ => rfl⟩ + · exact .inl ⟨.inr (.inr ((Match.rowIndex S.m k i).1, j, t)), fun _ => rfl⟩ + +theorem circuit [Field F] : Circuit F A D (repack k hk h d e) ((A).width + 34 * (D).width) := by + classical + have hd : Install.Depends ((D).code ∘ repack k hk h d e ∘ (A).code.symm) 1 := by + intro q + rcases wiring k hk h d e q with ⟨p, hp⟩ | ⟨b, hb⟩ + · refine ⟨{p}, by simp, fun x y he => ?_⟩ + simpa only [Function.comp_apply, hp, Equiv.apply_symm_apply] using he p (by simp) + · exact ⟨∅, by simp, fun _ _ _ => (hb _).trans (hb _).symm⟩ + exact hd.bnet F + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet + +variable {F T : Type} {x y : Wire} {L : Fringe x y T} {h u : ℕ} + (G : HostNet F L h u) (k : ℕ) (hk : k ≤ h) + +theorem regroup_preserves : G.Preserves (G.regroup k hk) := by + let f : Cell h →ₗ[ZMod 2] Cell (h - k) := + { toFun := suffix k + map_add' := fun _ _ => rfl + map_smul' := fun _ _ => rfl } + have onto : Function.Surjective f := by + intro j + obtain ⟨i, hi⟩ := (splitCell k hk).surjective (0, j) + exact ⟨i, congrArg Prod.snd hi⟩ + exact ⟨splitAddr G.V k hk, rfl, fun _ => rfl, ⟨f, onto, fun _ => rfl⟩, + Cell k, inferInstance, Equiv.refl _, fun _ => rfl⟩ + +theorem regroup_tracks : G.Tracks (G.regroup k hk) 1 := by + classical + apply tracks_of_slots (H := 1) (K := 1) (Q := G.regroup k hk) (A := Cell k) + (Equiv.refl _) (fun v => {v}) + · simp [eq_comm] + · simp + · decide + · change Fintype.card (G.V × Cell k) ≤ _ + rw [Fintype.card_prod, card_cell, one_mul, show h - (h - k) = k by omega, mul_comm] + · exact fun _ => Finset.mem_singleton_self _ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- +# Space for the two row orders + +Occurrence arities use the width of a finest bundle as their unit. +The incidence budget counts each core bundle twice and each exterior +bundle once. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Assignment +open Coloring Assembly PackRows + +variable {F : Type} [Field F] {D : Dimensions} {S : Scheme F} {x y : Wire} {G : Diagram F x y} + (t : Assignment D S G) + +open Classical in +theorem inventory_total : + (∑ i, total (t.inventory i)) * D.z = 2 * t.state.X + (wd x + wd y) * D.copies := by + have he := Fintype.card_congr (Exterior.point t.loc t.lane D.b) + simp only [Fintype.card_prod, Fintype.card_fin, Packing.card_cell, Fintype.card_sum, + card_slots] at he + unfold Endpoints Slots Blocks at he + simp_rw [Fintype.card_sigma, Fintype.card_fin] at he + have hc := t.inner.total_eq + change (wd x + wd y) * 2 ^ D.h * D.b = ∑ i, total (t.outerCount i) at he + have sum (i) : total (t.inventory i) = total (t.inner.inventory i) + total (t.outerCount i) := by + simp [inventory, PackRows.total, Finset.sum_add_distrib] + simp_rw [sum] + rw [Finset.sum_add_distrib, hc, ← he] + unfold Packing.HostNet.X Dimensions.copies + ring + +open Classical in +theorem room (hl : ∀ i j, t.state.load i j ≤ (D.u * D.z : ℕ)) : + Pieces.Room (l := t.inventory) (u := D.u) := by + intro i j + rw [inventory, arity_append] + by_cases h : ∃ a b, t.post.host a = i ∧ t.post.block b = j + · obtain ⟨a, b, rfl, rfl⟩ := h + rw [t.post.channels_arity] + have hc := t.state.core_le_load a b + have he := t.holders.load_eq t.post.host t.post.block t.lane rfl a b + have hb := hl a b + apply Nat.le_of_mul_le_mul_right _ D.zpos + exact_mod_cast (show ((Packing.degree t.state.pair (a, b) : ℝ) + + arity (t.outerCount (t.post.host a)) (t.post.block b)) * D.z ≤ (D.u * D.z : ℕ) by + rw [add_mul, he, add_comm] + exact hc.trans hb) + · have hc (e : t.state.E) (d : Bool) : ¬(t.inner.host d e = i ∧ t.inner.block e = j) := + fun he => h ⟨_, _, he⟩ + have he (a : Stack.Outer x y × Packing.Cell D.h) : t.loc a.1 a.2 ≠ (i, j) := + fun he => h ⟨_, _, Prod.mk.inj he⟩ + rw [Channels.arity_eq, Exterior.arity] + simp [hc, he] + +open Classical in +theorem fits (hl : ∀ i j, t.state.load i j ≤ (D.u * D.z : ℕ)) + (hv : D.PortCount S + 2 + 2 * 2 ^ S.h ≤ D.v) + (hr : 2 ^ S.m * ((D.PortCount S + 2) * D.u) * D.z + 2 * (2 * t.state.X + (wd x + + wd y) * D.copies) + + D.v * D.u * D.z ≤ D.K * D.v * D.u * D.z) : t.Fits := by + have hm := t.room hl + refine ⟨hm, fun i => ?_, ?_⟩ + · have ht : total (t.inventory i) ≤ 2 ^ S.h * D.u := by + unfold PackRows.total + simpa using Finset.sum_le_sum (s := Finset.univ) (fun j _ => hm i j) + apply Nat.le_of_mul_le_mul_right _ D.upos + calc + _ ≤ (D.PortCount S + 2) * D.u + 2 * total (t.inventory i) := size_cost _ _ + _ ≤ (D.PortCount S + 2 + 2 * 2 ^ S.h) * D.u := by grw [ht]; exact le_of_eq (by ring) + _ ≤ _ := Nat.mul_le_mul_right _ hv + · apply Nat.le_of_mul_le_mul_right _ (by positivity : 0 < D.v) + apply Nat.le_of_mul_le_mul_right _ D.upos + apply Nat.le_of_mul_le_mul_right _ D.zpos + refine (Nat.mul_le_mul_right _ (bins_cost t.inventory D.u D.v)).trans ?_ + rw [add_mul, add_mul, mul_assoc 2, t.inventory_total] + exact hr + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Assignment +end + +/- # Fixed data and varying controls of a batch descent -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Assembly Coloring Packing + +open scoped Classical in +/-- The data for the setup construction, including `G`, `h`, `U`, `z`, `d`. -/ +structure Setup (F : Type) (x y : Wire) where + /-- The `Setup` component of type `Diagram F x y`. -/ + G : Diagram F x y + /-- The `Setup` field of type `ℕ`. -/ + h : ℕ + /-- The `Setup` field of type `ℕ`. -/ + U : ℕ + /-- The `Setup` field of type `ℕ`. -/ + z : ℕ + /-- The `Setup` field of type `ℕ`. -/ + d : ℕ + /-- The `Setup` field of type `ℕ`. -/ + e : ℕ + /-- The name assigned to each index of type `Stack.Outer x y ↪ (Fin e → Bool)`. -/ + name : Stack.Outer x y ↪ (Fin e → Bool) + /-- The capacity bound. -/ + cap : ℕ + /-- Stores the discount associated with this `Setup`. -/ + discount : ℕ + +namespace Setup +variable {F : Type} {x y : Wire} (S : Setup F x y) + +open scoped Classical in +/-- The quantity computed by `2 ^ S.h * S.U`. -/ +abbrev count := 2 ^ S.h * S.U +open scoped Classical in +/-- Computes the input by the application `copies x S.count`. -/ +abbrev input := copies x S.count +open scoped Classical in +/-- Computes the output by the application `copies y S.count`. -/ +abbrev output := copies y S.count +open scoped Classical in +/-- Uses `{ Stack.fringe S.input S.output with cap := S.cap, discount := S.discount }` as the +representation. -/ +abbrev fringe := { Stack.fringe S.input S.output with cap := S.cap, discount := S.discount } +open scoped Classical in +/-- The value specified by `(Stack.start S.G S.h S.U).reserve S.cap S.discount`. -/ +abbrev first [Field F] := (Stack.start S.G S.h S.U).reserve S.cap S.discount +open scoped Classical in +/-- Computes the format by the application `T.format.pair (Trail.format T.scheme S.h S.d S.e)`. -/ +abbrev format (T : Template F) := T.format.pair (Trail.format T.scheme S.h S.d S.e) +end Setup + +namespace Snapshot +variable {F : Type} [Field F] {x y : Wire} (S : Setup F x y) (T : Template F) (u : ℕ) + +open scoped Classical in +/-- The data for the data construction, including `G`, `rows`, `trail`, `encodes`, `tracks`. -/ +structure Data where + /-- The `Data` component of type `HostNet F S.fringe T.scheme.h u`. -/ + G : HostNet F S.fringe T.scheme.h u + /-- The indexed rows of type `T.format.obj`. -/ + rows : T.format.obj + /-- The `Data` component of type `Trail.Record T.scheme S.h S.d S.e`. -/ + trail : Trail.Record T.scheme S.h S.d S.e + /-- The `Data` component of type `T.Encodes rows G`. -/ + encodes : T.Encodes rows G + tracks : Trail.Tracks encodes.post.toPresentation S.name trail + preserved : S.first.Preserves G + +variable {S T u} + +open scoped Classical in +/-- The value specified by `(x.rows, x.trail)`. -/ +def Data.code (x : Data S T u) : (S.format T).obj := (x.rows, x.trail) + +open scoped Classical in +/-- The condition `∀ v, x.G.diagram.arity v = 0 → ∀ t, Transcript.sample (x.G.diagram.table v) t += 1` on the specified data. -/ +def Data.Neutral (x : Data S T u) : Prop := + ∀ v, x.G.diagram.arity v = 0 → ∀ t, Transcript.sample (x.G.diagram.table v) t = 1 + +open scoped Classical in +/-- The tagged of type `Prop` for the given inputs. -/ +def Data.Tagged (x : Data S T u) (cost : ℕ) : Prop := + ∀ v b, 0 < x.G.tetherLoad (v, b) + degree x.G.pair (v, b) * u → + T.tagLength x.rows (x.encodes.post.host v) (x.encodes.post.block b) * S.z ≤ + cost * (x.G.past (v, b) + x.G.tetherLoad (v, b) + degree x.G.pair (v, b) * u) + +open scoped Classical in +/-- Uses `{x // P x} eval q := q.val.G.diagram.eval port := S.format T encode q _ _ := +q.val.code` as the representation. -/ +def restrict (P : Data S T u → Prop) : Assembly.Snapshot.{1} F S.input S.output where + state := {x // P x} + eval q := q.val.G.diagram.eval + port := S.format T + encode q _ _ := q.val.code + +end Snapshot +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +section +/- +# Separating short and long records in the terminal budget + +Charge the short record at each block of each host. Charge the neighbor +addresses and long exterior names just once at each host. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +open Assembly Coloring + +variable {F : Type} {x y : Wire} {S : Setup F x y} {T : Template F} {N : Scheme F} + {A L w : ℕ} + +private theorem short_bound {c : ℕ} (hA : 2 ≤ A) (hd : S.d ≤ A) (hh : S.h ≤ A) + (ht : N.ℓ ≤ A) (he : 2 ^ N.e ≤ A) (hc : c ≤ A) : + N.ℓ + c + 2 ^ N.e * (S.d + S.h) ≤ 100 * A ^ 3 := by + calc + _ ≤ A + A + A * (A + A) := by gcongr + _ ≤ 100 * A ^ 3 := by nlinarith [Nat.mul_le_mul_right (A ^ 2) hA] + +private theorem long_bound (hL : 2 ≤ L) (hw : 1 ≤ w) (hm : N.m ≤ 3 * w) (he : S.e ≤ 3 * w) + (hf : 2 ^ N.d ≤ L) (hd : S.d ≤ L) : + 2 ^ N.d * (N.m + 2) + 2 + S.d * S.e ≤ 100 * L * w := by + calc + _ ≤ L * (3 * w + 2) + 2 + L * (3 * w) := by gcongr + _ ≤ _ := by nlinarith + +theorem format_bound (hL : 2 ≤ L) (ha : L ≤ A) (hw : 1 ≤ w) + (hk : T.scheme.k = 0) (hm : T.scheme.m ≤ 3 * w) (he : S.e ≤ 3 * w) + (hf : 2 ^ T.scheme.d ≤ L) (hd : S.d ≤ L) (hh : S.h ≤ A) (ht : T.scheme.ℓ ≤ A) + (hp : 2 ^ T.scheme.e ≤ A) (hc : T.count ≤ A) : + (S.format T).width ≤ 100 * A ^ 3 * 2 ^ (T.scheme.m + T.scheme.h) + 100 * L * 2 ^ T.scheme.m * w + := by + have small := short_bound (hL.trans ha) (hd.trans ha) hh ht hp hc + have large := long_bound hL hw hm he hf hd + calc + _ = (T.scheme.ℓ + T.count + 2 ^ T.scheme.e * (S.d + S.h)) * 2 ^ (T.scheme.m + T.scheme.h) + + (2 ^ T.scheme.d * (T.scheme.m + 2) + 2 + S.d * S.e) * 2 ^ T.scheme.m := by + rw [Format.width_pair, Template.width, Trail.width_format, Trail.width_row, hk, + add_zero, pow_add, pow_add] + ring + _ ≤ 100 * A ^ 3 * 2 ^ (T.scheme.m + T.scheme.h) + (100 * L * w) * 2 ^ T.scheme.m := + Nat.add_le_add (Nat.mul_le_mul_right _ small) (Nat.mul_le_mul_right _ large) + _ = _ := by ring + +theorem tape_bound (hL : 2 ≤ L) (ha : L ≤ A) (hw : 1 ≤ w) (hk : N.k = 0) + (hm : N.m ≤ 3 * w) (he : S.e ≤ 3 * w) (hf : 2 ^ N.d ≤ L) (hd : S.d ≤ L) + (hh : S.h ≤ A) (ht : N.ℓ ≤ A) (hp : 2 ^ N.e ≤ A) : + (tape N S.h S.d S.e).width ≤ 100 * A ^ 3 * 2 ^ (N.m + N.h) + 100 * L * 2 ^ N.m * w := by + have small := short_bound (hL.trans ha) (hd.trans ha) hh ht hp (Nat.zero_le A) + have large : 2 ^ N.d * N.m + S.d * S.e ≤ 100 * L * w := + le_trans (by rw [mul_add]; omega) (long_bound hL hw hm he hf hd) + calc + _ = (N.ℓ + 2 ^ N.e * (S.d + S.h)) * 2 ^ (N.m + N.h) + (2 ^ N.d * N.m + S.d * S.e) * 2 ^ N.m + := by + rw [Format.width_pair, Fmt.width_rows, Format.width_addr, Trail.width_format, + Trail.width_row, hk, add_zero, pow_add, pow_add] + ring + _ ≤ 100 * A ^ 3 * 2 ^ (N.m + N.h) + (100 * L * w) * 2 ^ N.m := + Nat.add_le_add (Nat.mul_le_mul_right _ small) (Nat.mul_le_mul_right _ large) + _ = _ := by ring + +theorem meta_bound (hA : 2 ≤ A) (hk : N.k = 0) (hd : S.d ≤ A) (hh : S.h ≤ A) + (ht : N.ℓ ≤ A) (hp : 2 ^ N.e ≤ A) : + Fintype.card (Trail.Meta N S.h S.d) ≤ 100 * A ^ 3 * 2 ^ N.h := by + rw [Trail.card_meta, hk, zero_add, mul_comm] + exact Nat.mul_le_mul_right _ (short_bound hA hd hh ht hp (Nat.zero_le A)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +end + +/- +# Withdrawing isolated scalar entries + +The same labels and trail markers remain on the tape. Every empty +station's old value becomes a coefficient of the transition. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} + +namespace BatchDescent.Snapshot +variable {S : Setup F x y} {T : Template F} {u : ℕ} (d : Data S T u) + +open scoped Classical in +/-- Uses `⟨t.short, t.long⟩` as the representation. -/ +def recode (t : Trail.Record T.scheme S.h S.d S.e) : Trail.Record T.sweep.scheme S.h S.d S.e := + ⟨t.short, t.long⟩ + +open scoped Classical in +/-- Builds `Data S T.sweep u where G` with the specified `rows`, `trail`, `encodes`, `tracks`. -/ +def Data.sweep : Data S T.sweep u where + G := d.G.sweep + rows := d.rows + trail := recode d.trail + encodes := d.encodes.sweep + tracks := d.tracks + preserved := d.preserved + +open scoped Classical in +theorem Data.sweep_neutral : d.sweep.Neutral := d.G.diagram.sweep_neutral + +open scoped Classical in +theorem Data.sweep_tagged (n : ℕ) : d.sweep.Tagged n ↔ d.Tagged n := Iff.rfl + +open scoped Classical in +/-- The value specified by `weightTable (A := .addr T.scheme.ℓ) (D := .addr T.scheme.ℓ) id +T.scheme.scalar`. -/ +def sweepTable (T : Template F) := weightTable (A := .addr T.scheme.ℓ) (D := .addr T.scheme.ℓ) + id T.scheme.scalar + +open scoped Classical in +/-- The sweep cost used in the `Snapshot` construction. -/ +def sweepCost (S : Setup F x y) (T : Template F) := + updateCost T.scheme.m T.scheme.d T.scheme.h (.addr T.scheme.ℓ) (.addr T.scheme.ℓ) + + 4 * (Format.vec T.scheme.m T.header).width + 4 * (Trail.format T.scheme S.h S.d S.e).width + +open scoped Classical in +theorem sweep {P : Data S T u → Prop} {Q : Data S T.sweep u → Prop} + (h : ∀ d, P d → Q d.sweep) {cap : ℕ} {L : Set (Table F)} (hu : 3 ≤ cap) + (ha : 2 * T.scheme.ℓ ≤ cap) (hl : sweepTable T ∈ L) : + Transforms F cap L (restrict P) (restrict Q) (sweepCost S T) := by + let A := Format.addr T.scheme.ℓ + have update := Assembly.update (m := T.scheme.m) (d := T.scheme.d) (h := T.scheme.h) + (A := A) (D := A) id T.scheme.scalar hu (by simpa [A, two_mul] using ha) hl + have header := Map.circuit (L := L) hu (Circuit.id F (.vec T.scheme.m T.header)) + let left := Trail.format T.scheme S.h S.d S.e + let right := Trail.format T.sweep.scheme S.h S.d S.e + have trail : Circuit F left right (recode (S := S) (T := T)) left.width := by + unfold Circuit + convert Install.BNet.id F left.pins using 1 + funext k i + rcases i with i | i <;> rfl + have k := (update.par (Action.of_map header)).par (Action.of_map (Map.circuit (L := L) hu trail)) + simp only [mul_one] at k + refine Transforms.of_action (X := restrict P) (Y := restrict Q) + (fun i => ⟨i.val.sweep, h i.val i.property⟩) + (fun i => Fmt.weight T.scheme.scalar i.val.rows.1) _ _ k ?_ ?_ ?_ + · exact fun i a b => i.val.encodes.post.toPresentation.sweep_eval a b + · exact fun _ _ _ => rfl + · exact fun _ _ _ => rfl + +end BatchDescent.Snapshot +end MatrixMultiplicationAllFields.MatrixExponent +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Snapshot.Data +open Assembly +variable {F : Type} [Field F] {x y : Wire} {S : Setup F x y} {T : Template F} {u : ℕ} + (q : Data S T u) + +/-- Every positive exterior span carries a whole original stack. -/ +theorem exterior_width (p : T.scheme.Span) (he : T.scheme.peer q.rows.1 p = none) + (hw : 0 < T.scheme.width q.rows.1 p) : T.scheme.width q.rows.1 p = S.U := by + let a : T.scheme.exposed q.rows.1 := ⟨⟨p, ⟨0, hw⟩⟩, he⟩ + obtain ⟨i, hi⟩ := q.encodes.post.toPresentation.boundary.surjective a + obtain ⟨⟨⟨s, t⟩, b⟩, rfl⟩ := (Stack.bit S.h S.U x y).surjective i + obtain ⟨_, hl⟩ := q.tracks + obtain ⟨w, hz, _, _, hs⟩ := hl b s + have h : w = p := (hs t).1.symm.trans (congrArg (fun j => j.val.1) hi) + rwa [← h] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Snapshot.Data +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +/-- Initialize the descent from the width and replication parameters +used in the terminal packing. -/ +abbrev Dimensions.setup {F : Type} {x y : Wire} (D : Dimensions) (G : Diagram F x y) + (name : Stack.Outer x y ↪ (Fin D.e → Bool)) (cap discount : ℕ) : Setup F x y := + ⟨G, D.h, D.b * D.z, D.z, D.d, D.e, name, cap, discount⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # The history allowance leaves exterior origins unchanged -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Assembly Coloring Packing + +variable {F : Type} [Field F] {x y : Wire} + +open Classical in +/-- Builds `S.Posting r (Q.reserve 0 0) where toPresentation` with the specified +`toPresentation`, `host`, `block`, `stub`. -/ +def Regroup.unreserve {A : Type} {f : Fringe x y A} {h z : ℕ} {Q : HostNet F f h z} + {S : Scheme F} {r : S.format.obj} (p : S.Posting r Q) : + S.Posting r (Q.reserve 0 0) where + toPresentation := p.toPresentation + host := p.host + block := p.block + stub := p.stub + index := p.index + vertex_eq := p.vertex_eq + ordered := p.ordered + length := p.length + dir := p.dir + link := p.link + +open Classical in +theorem Setup.origins (S : Setup F x y) {a u : ℕ} (H : HostNet F S.fringe a u) + {T : Scheme F} {r : T.format.obj} (p : T.Posting r H) {k : ℕ} + (hp : S.first.Preserves H) (hk : S.first.Tracks H k) (hu : 0 < S.U) (ht : S.G.Trivalent) + (v : B T.m) : (Trail.origins p.toPresentation v).card ≤ 3 * k := by + by_cases hn : Nonempty S.G.V + · let Q : HostNet F (Stack.fringe S.input S.output) a u := H.reserve 0 0 + let G := Stack.start S.G S.h S.U + have h : 0 < G.seats := by + rw [Stack.start_seats] + have := Fintype.card_pos_iff.mpr hn + positivity + obtain ⟨L⟩ := Stack.holders S.G Q hu hp (Nat.le_mul_of_pos_right Q.seats h) + exact Trail.origins_bound (Regroup.unreserve p) L hu ht hk v + · have he : Trail.origins p.toPresentation v = ∅ := + Finset.eq_empty_iff_forall_notMem.mpr fun i _ => hn ⟨portEnd S.G i⟩ + rw [he, Finset.card_empty] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# The terminal assignment after the final beat + +Drop the incidence-history budget and move spare block bits to the host +coordinate. This step sends the short records and exterior names to the +terminal view. It leaves all diagram entries unchanged. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +open Assembly Coloring Packing + +variable {F : Type} [Field F] {x y : Wire} + +variable {D : Dimensions} {G : Diagram F x y} {name : Stack.Outer x y ↪ (Fin D.e → Bool)} + {cap discount K k u : ℕ} {T : Template F} + +local notation "s" => D.setup G name cap discount +local notation "U" => target T.scheme k + +open scoped Classical in +private theorem assignment (hn : Nonempty G.V) (hk : k ≤ T.scheme.h) (ht : T.scheme.h ≤ D.h) + (d : Snapshot.Data s T D.z) (hq : K * D.q ≤ 2 ^ (T.scheme.h - k)) + (hc : (s).first.Tracks d.G K) : + ∃ t : Assignment D U G, t.state.X = d.G.X ∧ + (∀ B : ℝ, (∀ i j, d.G.load i j ≤ B) → ∀ i j, t.state.load i j ≤ B) ∧ + d.G.diagram.eval = t.state.diagram.eval ∧ + ∀ hw, (Trail.view D U name).Valid t hw (rows k hk d.rows.1, trail k hk d.trail) := by + let R := d.G.regroup k hk + let Q : HostNet F (Stack.fringe (copies x D.copies) (copies y D.copies)) (T.scheme.h - k) D.z := + R.reserve 0 0 + let H := Stack.start G D.h (D.b * D.z) + have hpre : H.Preserves Q := d.preserved.trans (d.G.regroup_preserves k hk) + have htracks : H.Tracks Q K := by + have ht' := hc.trans (d.G.regroup_tracks k hk) ht (Nat.sub_le _ _) + rw [one_mul] at ht' + exact ht' + have hpos : 0 < H.seats := by + rw [Stack.start_seats] + have := Fintype.card_pos_iff.mpr hn + positivity + have hseats := Nat.le_mul_of_pos_right Q.seats hpos + have hp := Nat.mul_pos D.bpos D.zpos + obtain ⟨L⟩ := Stack.holders G Q hp hpre hseats + have reach (i) : (Finset.univ.image (L.core i)).card * D.q ≤ 2 ^ D.h := calc + _ ≤ (K * 2 ^ (D.h - (T.scheme.h - k))) * D.q := Nat.mul_le_mul_right _ (L.reach hp htracks i) + _ = (K * D.q) * 2 ^ (D.h - (T.scheme.h - k)) := by ring + _ ≤ 2 ^ (T.scheme.h - k) * 2 ^ (D.h - (T.scheme.h - k)) := Nat.mul_le_mul_right _ hq + _ = _ := by rw [← pow_add, Nat.add_sub_of_le (by omega)] + have hb : d.encodes.post.block = (cellIndex T.scheme.h).toEmbedding := + DFunLike.ext _ _ d.encodes.block + let q : (U).Posting (rows k hk d.rows.1) Q := unreserve (post k hk d.encodes.post hb) + have marked' : Trail.Tracks q.toPresentation name (trail k hk d.trail) := + tracks k hk d.encodes.post hb d.tracks + obtain ⟨lane, hl⟩ := marked' + let t := Trail.Marked.assign (D := D) (p := q) hl L reach + refine ⟨t, rfl, ?_, rfl, fun hw => Trail.view_valid t hw name (trail k hk d.trail) hl⟩ + intro B hB i j + change Q.V at i + change Cell (T.scheme.h - k) at j + have hu : Q.load i j ≤ R.load i j := by + rw [HostNet.load, HostNet.unpaid _ rfl, add_zero] + exact le_add_of_nonneg_right (mul_nonneg R.rate_nonneg (Nat.cast_nonneg _)) + obtain ⟨p, he⟩ := (splitAddr d.G.V k hk).surjective (i, j) + have hh := d.G.regroup_load k hk p + rw [he] at hh + exact hu.trans (hh.le.trans (hB ..)) + +local notation "src" => Setup.format s T +local notation "mid" => tape T.scheme D.h D.d D.e +local notation "dst" => tape U D.h D.d D.e + +open scoped Classical in +theorem terminal (hn : Nonempty G.V) (hk : k ≤ T.scheme.h) (ht : T.scheme.h ≤ D.h) + (P : Snapshot.Data s T D.z → Prop) (hq : K * D.q ≤ 2 ^ (T.scheme.h - k)) + (bounds : ∀ d, P d → (s).first.Tracks d.G K) + (hu : 3 ≤ u) (L : Set (Table F)) : + ∃ (Y : Assembly.Snapshot.{1} F (s).input (s).output) + (V : View D U x y Y.port (Trail.Meta U D.h D.d)), + Y.port.width = (dst).width ∧ + Transforms F u L (Snapshot.restrict P) Y (1000 * ((src).width + Y.port.width)) ∧ + ∀ i a b, ∃ (d : Snapshot.Data s T D.z) (t : Assignment D U G), + P d ∧ t.state.X = d.G.X ∧ + (∀ B : ℝ, (∀ i j, d.G.load i j ≤ B) → ∀ i j, t.state.load i j ≤ B) ∧ + Y.eval i a b = t.state.diagram.eval a b ∧ ∀ hw, V.Valid t hw (Y.encode i a b) := by + let drop : (src).obj → (mid).obj := fun x => (x.1.1, x.2) + have drop_net : Circuit F src mid drop ((src).width + 2 * (mid).width) := + Circuit.project (A := src) (D := mid) (Sum.map Sum.inl id) (by rintro _ (i|i) <;> rfl) + have small : (mid).width ≤ (src).width := by + rw [Format.width_pair, Format.width_pair, Format.width_pair] + exact Nat.add_le_add_right (Nat.le_add_right _ _) _ + let f := repack k hk D.h D.d D.e ∘ drop + have cost := Map.circuit (L := L) hu (drop_net.comp (circuit k hk D.h D.d D.e)) + have ctrl : Map F u L src dst f (1000 * ((src).width + (dst).width)) := cost.mono (by omega) + let X := Snapshot.restrict P + let Y : Assembly.Snapshot.{1} F (s).input (s).output := + { X with port := dst, encode := fun i a b => f (X.encode i a b) } + refine ⟨Y, Trail.view D U name, rfl, Transforms.of_map f id ctrl (fun _ => rfl) + (fun _ _ _ => rfl), ?_⟩ + rintro ⟨d, hd⟩ a b + obtain ⟨t, hx, hl, he, hv⟩ := assignment hn hk ht d hq (bounds d hd) + exact ⟨d, t, hd, hx, hl, congrFun (congrFun he a) b, hv⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Regroup +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/Compact.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/Compact.lean new file mode 100644 index 0000000000..433736aa32 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/Compact.lean @@ -0,0 +1,625 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Data.Nat.Log +public import Mathlib.Tactic.GCongr +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels + +/-! # Uniform polynomial bounds with a variable base -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase + +theorem clog_le_add_of_le_mul_succ (x y z : ℕ) (h : z ≤ (x + 1) * (1 + y)) : + Nat.clog 2 z ≤ x + Nat.clog 2 (1 + y) := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_add] + exact h.trans (Nat.mul_le_mul Nat.lt_two_pow_self (Nat.le_pow_clog (by decide) _)) + +/-- The data for the poly construction, including `two`, `bound`. -/ +structure Poly {I : Type*} (s f : I → ℕ) : Prop where + two : ∀ i, 2 ≤ s i + bound : ∃ k : ℕ, ∀ i, f i ≤ s i ^ k + +namespace Poly +variable {I : Type*} {s t f g : I → ℕ} + +theorem const (h : ∀ i, 2 ≤ s i) (n : ℕ) : Poly s (fun _ => n) := + ⟨h, n, fun i => Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left (h i) n)⟩ + +theorem of_le (h : ∀ i, 2 ≤ s i) (hf : ∀ i, f i ≤ s i) : Poly s f := + ⟨h, 1, by simpa using hf⟩ + +theorem mono (h : Poly s f) (hg : ∀ i, g i ≤ f i) : Poly s g := + let ⟨k, hk⟩ := h.bound + ⟨h.two, k, fun i => (hg i).trans (hk i)⟩ + +theorem grow (h : Poly s f) (ht : ∀ i, s i ≤ t i) : Poly t f := + let ⟨k, hk⟩ := h.bound + ⟨fun i => (h.two i).trans (ht i), k, fun i => (hk i).trans (Nat.pow_le_pow_left (ht i) k)⟩ + +theorem pow_sum {n : ℕ} (h : 2 ≤ n) (i j : ℕ) : n ^ i + n ^ j ≤ n ^ (max i j + 1) := by + have hi := Nat.pow_le_pow_right (show 0 < n by omega) (le_max_left i j) + have hj := Nat.pow_le_pow_right (show 0 < n by omega) (le_max_right i j) + rw [pow_succ] + exact (Nat.add_le_add hi hj).trans (by rw [← Nat.mul_two]; exact Nat.mul_le_mul_left _ h) + +theorem add (h : Poly s f) (h' : Poly s g) : Poly s (fun i => f i + g i) := + let ⟨j, hj⟩ := h.bound + let ⟨k, hk⟩ := h'.bound + ⟨h.two, max j k + 1, fun i => (Nat.add_le_add (hj i) (hk i)).trans (pow_sum (h.two i) ..)⟩ + +theorem mul (h : Poly s f) (h' : Poly s g) : Poly s (fun i => f i * g i) := + let ⟨j, hj⟩ := h.bound + let ⟨k, hk⟩ := h'.bound + ⟨h.two, j + k, fun i => (Nat.mul_le_mul (hj i) (hk i)).trans_eq (pow_add ..).symm⟩ + +theorem pow (h : Poly s f) (n : ℕ) : Poly s (fun i => f i ^ n) := + let ⟨j, hj⟩ := h.bound + ⟨h.two, j * n, fun i => (Nat.pow_le_pow_left (hj i) n).trans_eq (pow_mul ..).symm⟩ + +theorem of_exp (h : Poly s (fun i => 2 ^ f i)) : Poly s f := + h.mono (fun _ => Nat.lt_two_pow_self.le) + +theorem exp_add (h : Poly s (fun i => 2 ^ f i)) (h' : Poly s (fun i => 2 ^ g i)) : + Poly s (fun i => 2 ^ (f i + g i)) := by + simpa only [pow_add] using h.mul h' + +theorem clog (h : Poly s f) : Poly s (fun i => Nat.clog 2 (f i)) := + h.mono (fun _ => (Nat.clog_le_iff_le_pow (by decide)).mpr Nat.lt_two_pow_self.le) + +theorem exp_clog (h : Poly s f) : Poly s (fun i => 2 ^ Nat.clog 2 (f i)) := by + refine ((h.add (const h.two 1)).mul (const h.two 2)).mono fun i => ?_ + cases he : Nat.clog 2 (f i) with + | zero => rw [pow_zero]; omega + | succ k => + have ht : ¬ f i ≤ 2 ^ k := fun hn => by + have := (Nat.clog_le_iff_le_pow (by decide : 1 < 2)).mpr hn + omega + rw [pow_succ] + exact Nat.mul_le_mul_right 2 (by omega) + +end Poly + +/-- Sum charges with a common degree. Each charge gives a weight and its base. -/ +def weightedPower (charges : List (ℕ × ℕ)) (degree : ℕ) : ℕ := + (charges.map fun charge => charge.1 * charge.2 ^ degree).sum + +theorem weightedPower_add (charges : List (ℕ × ℕ)) (s t : ℕ) + (bases : ∀ charge ∈ charges, 2 ≤ charge.2) : + weightedPower charges s + weightedPower charges t ≤ weightedPower charges (max s t + 1) := by + induction charges with + | nil => simp [weightedPower] + | cons charge charges ih => + have tail := ih fun c hc => bases c (List.mem_cons_of_mem _ hc) + simp only [weightedPower, List.map_cons, List.sum_cons] at tail ⊢ + rw [add_add_add_comm, ← mul_add] + exact Nat.add_le_add + (Nat.mul_le_mul_left _ (Poly.pow_sum (bases charge (List.mem_cons_self ..)) s t)) tail + +theorem weightedPower_mul (charges : List (ℕ × ℕ)) (base s t : ℕ) + (bases : ∀ charge ∈ charges, base ≤ charge.2) : + weightedPower charges s * base ^ t ≤ weightedPower charges (s + t) := by + induction charges with + | nil => simp [weightedPower] + | cons charge charges ih => + have tail := ih fun c hc => bases c (List.mem_cons_of_mem _ hc) + simp only [weightedPower, List.map_cons, List.sum_cons] at tail ⊢ + rw [add_mul, mul_assoc, pow_add] + exact Nat.add_le_add (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ + (Nat.pow_le_pow_left (bases charge (List.mem_cons_self ..)) t))) tail + +/-- A uniform polynomial degree controls a sum of separately weighted charges. -/ +def WeightedCost {I : Type*} (charges : I → List (ℕ × ℕ)) (f : I → ℕ) : Prop := + ∃ degree, ∀ i, f i ≤ weightedPower (charges i) degree + +namespace WeightedCost + +variable {I : Type*} {charges : I → List (ℕ × ℕ)} {f g scale : I → ℕ} + +theorem mono (hf : WeightedCost charges f) (h : ∀ i, g i ≤ f i) : WeightedCost charges g := + let ⟨s, hs⟩ := hf + ⟨s, fun i => (h i).trans (hs i)⟩ + +theorem add (hf : WeightedCost charges f) (hg : WeightedCost charges g) + (bases : ∀ i charge, charge ∈ charges i → 2 ≤ charge.2) : + WeightedCost charges (fun i => f i + g i) := by + obtain ⟨s, hs⟩ := hf + obtain ⟨t, ht⟩ := hg + exact ⟨max s t + 1, fun i => (Nat.add_le_add (hs i) (ht i)).trans + (weightedPower_add (charges i) s t (bases i))⟩ + +theorem mul (hf : WeightedCost charges f) (hg : Poly scale g) + (bases : ∀ i charge, charge ∈ charges i → scale i ≤ charge.2) : + WeightedCost charges (fun i => f i * g i) := by + obtain ⟨s, hs⟩ := hf + obtain ⟨t, ht⟩ := hg.bound + exact ⟨s + t, fun i => (Nat.mul_le_mul (hs i) (ht i)).trans + (weightedPower_mul (charges i) (scale i) s t (bases i))⟩ + +end WeightedCost + +/-- A common-degree polynomial budget with a host term and a smaller block term. -/ +def MixedCost {I : Type*} (long short height j f : I → ℕ) : Prop := + ∃ k : ℕ, ∀ i, f i ≤ 2 ^ (j i) * long i ^ k + 2 ^ (j i + height i) * short i ^ k + +namespace MixedCost + +variable {I : Type*} {large small height j f g : I → ℕ} + +private def charges (large small height j : I → ℕ) (i : I) : List (ℕ × ℕ) := + [(2 ^ (j i), large i), (2 ^ (j i + height i), small i)] + +private theorem weighted_iff : + MixedCost large small height j f ↔ WeightedCost (charges large small height j) f := by + simp only [MixedCost, WeightedCost, charges, weightedPower, List.map_cons, List.map_nil, + List.sum_cons, List.sum_nil, Nat.add_zero] + +theorem mono (h : MixedCost large small height j f) (hg : ∀ i, g i ≤ f i) : + MixedCost large small height j g := + weighted_iff.mpr ((weighted_iff.mp h).mono hg) + +theorem exp_mul_mono {actual upper : I → ℕ} + (h : MixedCost large small height j (fun i => 2 ^ upper i * f i)) + (bound : ∀ i, actual i ≤ upper i) : + MixedCost large small height j (fun i => 2 ^ actual i * f i) := + h.mono fun i => Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (bound i)) + +theorem add (h : MixedCost large small height j f) (h' : MixedCost large small height j g) + (largeTwo : ∀ i, 2 ≤ large i) (smallTwo : ∀ i, 2 ≤ small i) : + MixedCost large small height j (fun i => f i + g i) := by + refine weighted_iff.mpr ((weighted_iff.mp h).add (weighted_iff.mp h') fun i charge member => ?_) + simp only [charges, List.mem_cons, List.not_mem_nil, or_false] at member + rcases member with rfl | rfl + · exact largeTwo i + · exact smallTwo i + +theorem mul (h : MixedCost large small height j f) (h' : Poly small g) + (smallLeLarge : ∀ i, small i ≤ large i) : + MixedCost large small height j (fun i => f i * g i) := by + refine weighted_iff.mpr ((weighted_iff.mp h).mul h' fun i charge member => ?_) + simp only [charges, List.mem_cons, List.not_mem_nil, or_false] at member + rcases member with rfl | rfl + · exact smallLeLarge i + · exact le_rfl + +theorem long (j : I → ℕ) (h : Poly large f) : + MixedCost large small height j (fun i => 2 ^ (j i) * f i) := + let ⟨k, hk⟩ := h.bound + ⟨k, fun i => (Nat.mul_le_mul_left _ (hk i)).trans (Nat.le_add_right ..)⟩ + +theorem short (j : I → ℕ) (h : Poly small f) : + MixedCost large small height j (fun i => 2 ^ (j i + height i) * f i) := + let ⟨k, hk⟩ := h.bound + ⟨k, fun i => (Nat.mul_le_mul_left _ (hk i)).trans (Nat.le_add_left ..)⟩ + +theorem scale (h : MixedCost large small height j f) (k : ℕ) + (smallTwo : ∀ i, 2 ≤ small i) (smallLeLarge : ∀ i, small i ≤ large i) : + MixedCost large small height j (fun i => k * f i) := + (h.mul (Poly.const smallTwo k) smallLeLarge).mono fun _ => le_of_eq (mul_comm ..) + +variable (largeTwo : ∀ i, 2 ≤ large i) (smallTwo : ∀ i, 2 ≤ small i) + (smallLeLarge : ∀ i, small i ≤ large i) + +include largeTwo smallTwo smallLeLarge in +/-- Combine the five charges in the reset packet. -/ +theorem resetPacket {input data groups bank applyCost : I → ℕ} + (hInput : MixedCost large small height j input) (hData : MixedCost large small height j data) + (hGroups : MixedCost large small height j groups) (hBank : MixedCost large small height j bank) + (hApply : MixedCost large small height j applyCost) : + MixedCost large small height j + (fun i => 10 * input i + 2 * data i + groups i + 2 * bank i + applyCost i) := by + have h := (hInput.scale 10 smallTwo smallLeLarge).add (hData.scale 2 smallTwo smallLeLarge) + largeTwo smallTwo + have h := (h.add hGroups largeTwo smallTwo).add (hBank.scale 2 smallTwo smallLeLarge) + largeTwo smallTwo + exact h.add hApply largeTwo smallTwo + +include largeTwo smallTwo smallLeLarge in +/-- Charge preparation and queries at fixed rates and add the model's read charge. -/ +theorem resetWindow {input packet mask gathered queries reads : I → ℕ} + (hInput : MixedCost large small height j input) + (hPacket : MixedCost large small height j packet) + (hMask : MixedCost large small height j mask) + (hGathered : MixedCost large small height j gathered) + (hQueries : MixedCost large small height j queries) + (hReads : MixedCost large small height j reads) : + MixedCost large small height j (fun i => + 100 * (input i + packet i + mask i + gathered i) + 136 * queries i + reads i) := by + have h := (((hInput.add hPacket largeTwo smallTwo).add hMask largeTwo smallTwo).add hGathered + largeTwo smallTwo).scale 100 smallTwo smallLeLarge + exact (h.add (hQueries.scale 136 smallTwo smallLeLarge) largeTwo smallTwo).add + hReads largeTwo smallTwo + +include largeTwo smallTwo smallLeLarge in +/-- Combine the window, output and assembly charges for printing a reset. -/ +theorem resetPrint {input extra window output pieces assembled : I → ℕ} + (hInput : MixedCost large small height j input) (hExtra : MixedCost large small height j extra) + (hWindow : MixedCost large small height j window) + (hOutput : MixedCost large small height j output) + (hPieces : MixedCost large small height j pieces) + (hAssembled : MixedCost large small height j assembled) : + MixedCost large small height j + (fun i => 20 * input i + extra i + window i + output i + + 4 * (pieces i + 2 * assembled i)) := by + have hPrep := ((hInput.scale 20 smallTwo smallLeLarge).add hExtra largeTwo smallTwo).add hWindow + largeTwo smallTwo + have hAssemble := hPieces.add (hAssembled.scale 2 smallTwo smallLeLarge) largeTwo smallTwo + exact (hPrep.add hOutput largeTwo smallTwo).add (hAssemble.scale 4 smallTwo smallLeLarge) + largeTwo smallTwo + +theorem hosts (m : I → ℕ) (h : MixedCost large small height (fun _ => 0) f) : + MixedCost large small height m (fun i => 2 ^ m i * f i) := by + obtain ⟨k, hk⟩ := h + refine ⟨k, fun i => ?_⟩ + simpa only [pow_zero, one_mul, zero_add, mul_add, ← mul_assoc, ← pow_add] + using Nat.mul_le_mul_left (2 ^ m i) (hk i) + +end MixedCost + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Phase +end + +/- # Circuits for counting marked candidates -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail.Compact + +open Finset Install +variable {F I J : Type} [Field F] [Fintype I] [Fintype J] {a b M : ℕ} + +open Classical in +private theorem countTest (p : ℕ → Prop) (hM : 2 ≤ M) (hJ : Fintype.card J ≤ M ^ 2) : + BNet F (fun (x : J → Bool) (_ : Unit) => decide (p (univ.filter (fun j => x j = true)).card)) + (M ^ 25) := by + let w := Nat.log 2 (M ^ 2) + 1 + have hp : M ^ 2 < 2 ^ w := Nat.lt_pow_succ_log_self (by decide) _ + have ht : 2 ^ w ≤ 2 * M ^ 2 := by + unfold w + rw [pow_succ'] + exact Nat.mul_le_mul_left _ (Nat.pow_log_le_self _ (by positivity)) + have hw := (Nat.lt_two_pow_self (n := w)).trans_le ht + clear_value w + let f (x : slots (word w) → Bool) (_ : Unit) := decide (p (Control.decode w x).val) + have hdep : Depends f w := by + intro i + exact ⟨univ, by simp, fun x y h => congrArg (fun t => f t i) (funext fun j => h j (mem_univ _))⟩ + have h := BNet.comp (Processor.Register.weighted F w (fun _ : J => 1)) (hdep.bnet F) + have hs : 20000 * (1 + Fintype.card J) * (1 + w) + (w + localCost w) ≤ M ^ 25 := by + have hl : localCost w ≤ 40 * M ^ 2 := by unfold localCost; rw [pow_succ]; omega + have hz : 1 ≤ M ^ 2 := Nat.one_le_pow _ _ (by omega) + calc + _ ≤ 20000 * (2 * M ^ 2) * (2 * M ^ 2) + 42 * M ^ 2 := by gcongr <;> omega + _ ≤ 80042 * M ^ 4 := by nlinarith only [hz] + _ ≤ _ := by + rw [show M ^ 25 = M ^ 21 * M ^ 4 from pow_add M 21 4] + exact Nat.mul_le_mul_right _ ((by decide : 80042 ≤ 2 ^ 21).trans (Nat.pow_le_pow_left hM _)) + simp only [card_slots, wd_word, Fintype.card_unit, mul_one] at h + convert h.mono hs using 1 + funext x t + have hc : (univ.filter (fun j => x j = true)).card < 2 ^ w := + ((card_filter_le _ _).trans hJ).trans_lt hp + simp only [f, Function.comp_apply, Processor.digits, Equiv.apply_symm_apply, + Fin.val_ofNat, sum_boole, Nat.cast_id, Nat.mod_eq_of_lt hc] + +open Classical in +/-- The quantity computed by `M ^ (25 + 6 * k)`. -/ +def bound (M k : ℕ) := M ^ (25 + 6 * k) + +open Classical in +/-- The indexed operation `BNet F (fun x (_ : Unit) => decide (p x)) (bound M k)`. -/ +def Gate (F : Type) [Field F] (M k : ℕ) (p : (I → Bool) → Prop) := + BNet F (fun x (_ : Unit) => decide (p x)) (bound M k) + +namespace Gate + +variable {p q : (I → Bool) → Prop} (hM : 2 ≤ M) (hI : Fintype.card I ≤ M ^ 2) + +omit [Fintype I] in +open Classical in +theorem congr (h : Gate F M a p) (he : ∀ x, p x ↔ q x) : Gate F M a q := by + simpa only [Gate, he] using h + +include hM in +omit [Fintype I] in +open Classical in +theorem mono (h : Gate F M a p) (hab : a ≤ b) : Gate F M b p := + BNet.mono h (Nat.pow_le_pow_right (by omega) (by omega)) + +include hM in +open Classical in +private theorem slack (k : ℕ) {t u : ℕ} (ht : t ≤ M ^ 2) (hu : u ≤ M ^ 2) : + t + u * (2 * t + bound M k) + bound M 0 ≤ bound M (k + 1) := by + let v := bound M k + have ht' : t ≤ v := ht.trans (Nat.pow_le_pow_right (by omega) (by omega)) + have hb : bound M 0 ≤ v := Nat.pow_le_pow_right (by omega) (by omega) + calc + _ ≤ v + M ^ 2 * (2 * v + v) + v := by gcongr + _ = (2 + 3 * M ^ 2) * v := by ring + _ ≤ M ^ 6 * v := by + apply Nat.mul_le_mul_right + have h4 : 16 ≤ M ^ 4 := Nat.pow_le_pow_left hM 4 + have h2 : 4 ≤ M ^ 2 := Nat.pow_le_pow_left hM 2 + nlinarith only [h4, h2] + _ = _ := by unfold v bound; rw [← pow_add]; congr 1; omega + +include hM hI in +open Classical in +theorem atom (p : Bool → Bool → Prop) (i j : I) : + Gate F M 0 (fun x => p (x i) (x j)) := by + have hp : Depends (fun (x : I → Bool) (_ : Unit) => decide (p (x i) (x j))) 2 := + fun _ => ⟨{i, j}, card_le_two, fun x y h => by dsimp only; rw [h i (by simp), h j (by simp)]⟩ + apply (hp.bnet F).mono + rw [Fintype.card_unit, mul_one] + have he : M ^ 2 + localCost 2 ≤ M ^ 23 * M ^ 2 := by + have h₁ : 100 ≤ M ^ 23 := (by decide : 100 ≤ 2 ^ 23).trans (Nat.pow_le_pow_left hM _) + have h₂ : 4 ≤ M ^ 2 := Nat.pow_le_pow_left hM 2 + change M ^ 2 + 68 ≤ _ + nlinarith only [h₁, h₂] + exact (Nat.add_le_add_right hI _).trans (he.trans_eq (pow_add M 23 2).symm) + +include hM hI in +open Classical in +theorem collect (hJ : Fintype.card J ≤ M ^ 2) (P : J → (I → Bool) → Prop) + (h : ∀ j, Gate F M a (P j)) : + BNet F (fun x j => decide (P j x)) (bound M (a + 1)) := by + have ht := (BNet.collect _ h).rename (.refl I) (Equiv.prodUnique _ Unit) + exact ht.mono ((Nat.le_add_right ..).trans (slack hM a hI hJ)) + +include hM hI in +open Classical in +theorem count (hJ : Fintype.card J ≤ M ^ 2) (P : J → (I → Bool) → Prop) + (h : ∀ j, Gate F M a (P j)) (f : ℕ → Prop) : + Gate F M (a + 1) (fun x => f (univ.filter (fun j => P j x)).card) := by + have ht := (BNet.collect _ h).rename (.refl I) (Equiv.prodUnique _ Unit) + have k := (ht.comp (countTest f hM hJ)).mono (slack hM a hI hJ) + change BNet F (fun x (_ : Unit) => decide (f (univ.filter (fun j => decide (P j x) + = true)).card)) _ at k + simpa only [Gate, decide_eq_true_eq] using k + +include hM hI in +open Classical in +theorem every (hJ : Fintype.card J ≤ M ^ 2) (P : J → (I → Bool) → Prop) + (h : ∀ j, Gate F M a (P j)) : Gate F M (a + 1) (fun x => ∀ j, P j x) := by + apply (count hM hI hJ P h (· = Fintype.card J)).congr + intro x + rw [← card_univ, card_filter_eq_iff] + simp + +include hM hI in +open Classical in +theorem any (hJ : Fintype.card J ≤ M ^ 2) (P : J → (I → Bool) → Prop) + (h : ∀ j, Gate F M a (P j)) : Gate F M (a + 1) (fun x => ∃ j, P j x) := by + apply (count hM hI hJ P h (0 < ·)).congr + intro x + simp [card_pos, filter_nonempty_iff] + +include hM hI in +open Classical in +theorem absent (hJ : Fintype.card J ≤ M ^ 2) (P : J → (I → Bool) → Prop) + (h : ∀ j, Gate F M a (P j)) : Gate F M (a + 1) (fun x => ¬∃ j, P j x) := by + apply (count hM hI hJ P h (· = 0)).congr + intro x + simp [card_eq_zero, filter_eq_empty_iff] + +include hM hI in +open Classical in +theorem both (h : Gate F M a p) (k : Gate F M a q) : + Gate F M (a + 1) (fun x => p x ∧ q x) := by + let P (b : Bool) := if b then q else p + have t : ∀ b, Gate F M a (P b) := by + intro b + cases b + · exact h + · exact k + exact (every hM hI (by simpa using hM.trans (Nat.le_pow (by decide : 0 < 2))) P t).congr + (fun _ => by simp [P]) + +end Gate +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail.Compact +end + +/- +# Compacting marked names + +The first marked occurrence of each name is its representative. +Its channel number is the count of earlier representatives. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail.Compact + +open Finset +open Classical in +/-- Indexes the input by the coordinates of `K × Option (Fin e)`. -/ +abbrev Input (K : Type) (e : ℕ) := K × Option (Fin e) +open Classical in +/-- Indexes the output by the coordinates of `(Fin d × Fin e) ⊕ (K × Fin d)`. -/ +abbrev Output (K : Type) (d e : ℕ) := (Fin d × Fin e) ⊕ (K × Fin d) + +variable {K : Type} [Fintype K] {d e : ℕ} + +open Classical in +/-- The value specified by `x (k, some j)`. -/ +def name (x : Input K e → Bool) (k : K) (j : Fin e) := x (k, some j) + +open Classical in +/-- The indexed operation `(univ.filter (fun k => x (k, none) = true)).image (name x)`. -/ +def names (x : Input K e → Bool) := + (univ.filter (fun k => x (k, none) = true)).image (name x) + +open Classical in +/-- The value specified by `(Fintype.equivFin K k).val`. -/ +def pos (k : K) := (Fintype.equivFin K k).val + +open Classical in +/-- Requires `x (k, none) = true ∧ ¬∃ j, (pos j < pos k ∧ x (j, none) = true) ∧ name x j = name +x k`. -/ +def lead (x : Input K e → Bool) (k : K) : Prop := + x (k, none) = true ∧ ¬∃ j, (pos j < pos k ∧ x (j, none) = true) ∧ name x j = name x k + +open Classical in +/-- Selects the elements of all indices satisfying `(fun j => pos j < pos k ∧ lead x j)`. -/ +def before (x : Input K e → Bool) (k : K) := + univ.filter (fun j => pos j < pos k ∧ lead x j) + +open Classical in +/-- Requires `lead x k ∧ (before x k).card = i.val`. -/ +def atRank (x : Input K e → Bool) (k : K) (i : Fin d) : Prop := + lead x k ∧ (before x k).card = i.val + +open Classical in +/-- In the case `.inl (i, j)`, this construction gives `decide (∃ k, atRank x k i ∧ name x k j = +true)`. -/ +def run (d : ℕ) (x : Input K e → Bool) : Output K d e → Bool + | .inl (i, j) => decide (∃ k, atRank x k i ∧ name x k j = true) + | .inr (k, i) => decide (∃ t, atRank x t i ∧ name x t = name x k) + +variable (x : Input K e → Bool) + +open Classical in +private theorem pos_injective : Function.Injective (pos (K := K)) := + Fin.val_injective.comp (Fintype.equivFin K).injective + +open Classical in +private theorem lead_exists (k : K) (hk : x (k, none) = true) : + ∃ j, lead x j ∧ name x j = name x k := by + let s := univ.filter (fun j => x (j, none) = true ∧ name x j = name x k) + obtain ⟨j, hj, hle⟩ := exists_min_image s pos ⟨k, by simp [s, hk]⟩ + obtain ⟨hu, he⟩ := (mem_filter.mp hj).2 + refine ⟨j, ⟨hu, ?_⟩, he⟩ + rintro ⟨t, ⟨ht, hv⟩, h⟩ + exact ht.not_ge (hle t (mem_filter.mpr ⟨mem_univ _, hv, h.trans he⟩)) + +open Classical in +private theorem lead_unique {k j : K} (hk : lead x k) (hj : lead x j) + (he : name x k = name x j) : k = j := by + apply pos_injective + exact le_antisymm (le_of_not_gt (fun h => hk.2 ⟨j, ⟨h, hj.1⟩, he.symm⟩)) + (le_of_not_gt (fun h => hj.2 ⟨k, ⟨h, hk.1⟩, he⟩)) + +open Classical in +private theorem rank_lt {k : K} (s : Finset K) + (hm : k ∈ s) (hu : before x k ⊆ s) : (before x k).card < s.card := + card_lt_card (Finset.ssubset_iff_subset_ne.mpr ⟨hu, by + intro he + rw [← he] at hm + exact (mem_filter.mp hm).2.1.false⟩) + +open Classical in +private theorem rank_bound {k : K} (hk : lead x k) : (before x k).card < (names x).card := by + let s := univ.filter (lead x) + have h := rank_lt x (k := k) s (by simp [s, hk]) (fun _ hj => mem_filter.mpr + ⟨mem_univ _, (mem_filter.mp hj).2.2⟩) + apply h.trans_le + apply card_le_card_of_injOn (name x) + · exact fun j hj => mem_image.mpr ⟨j, mem_filter.mpr ⟨mem_univ _, (mem_filter.mp hj).2.1⟩, rfl⟩ + · exact fun _ hj _ ht => lead_unique x (mem_filter.mp hj).2 (mem_filter.mp ht).2 + +open Classical in +private theorem rank_unique {k j : K} {i : Fin d} (hk : atRank x k i) (hj : atRank x j i) : + k = j := by + have lt {u v : K} (hu : lead x u) (hv : pos u < pos v) : + (before x u).card < (before x v).card := by + refine rank_lt x (k := u) _ (mem_filter.mpr ⟨mem_univ _, hv, hu⟩) ?_ + intro t ht + obtain ⟨h, h'⟩ := (mem_filter.mp ht).2 + exact mem_filter.mpr ⟨mem_univ _, h.trans hv, h'⟩ + rcases lt_trichotomy (pos k) (pos j) with h | h | h + · exact ((lt hk.1 h).ne (hk.2.trans hj.2.symm)).elim + · exact pos_injective h + · exact ((lt hj.1 h).ne (hj.2.trans hk.2.symm)).elim + +open Classical in +/-- Under the distinct-name bound the long names and the one-hot fields +use the same channel assignment at every active occurrence. -/ +theorem correct (hd : 0 < d) (x : Input K e → Bool) (hx : (names x).card ≤ d) : + ∃ f : (Fin e → Bool) → Fin d, ∀ k, x (k, none) = true → + (∀ j, run d x (.inl (f (name x k), j)) = name x k j) ∧ + (∀ i, run d x (.inr (k, i)) = decide (i = f (name x k))) := by + have pick (v : Fin e → Bool) : ∃ i : Fin d, ∀ k, lead x k → name x k = v → atRank x k i := by + by_cases h : ∃ k, lead x k ∧ name x k = v + · obtain ⟨k, hk, he⟩ := h + refine ⟨⟨_, (rank_bound x hk).trans_le hx⟩, fun j hj hj' => ?_⟩ + rw [lead_unique x hj hk (hj'.trans he.symm)] + exact ⟨hk, rfl⟩ + · exact ⟨⟨0, hd⟩, fun k hk he => (h ⟨k, hk, he⟩).elim⟩ + choose f hf using pick + refine ⟨f, fun k hk => ?_⟩ + obtain ⟨t, ht, he⟩ := lead_exists x k hk + have h := hf _ t ht he + constructor + · intro j + apply Bool.eq_iff_iff.mpr + simp only [run, decide_eq_true_eq] + constructor + · rintro ⟨q, hq, hj⟩ + rwa [rank_unique x hq h, he] at hj + · exact fun hj => ⟨t, h, he.symm ▸ hj⟩ + · intro i + simp only [run, decide_eq_decide] + exact ⟨fun ⟨q, hq, hq'⟩ => Fin.ext (hq.2.symm.trans (hf _ q hq.1 hq').2), fun e => ⟨t, e ▸ h, + he⟩⟩ + +open Classical in +/-- The network is defined even on inputs with more names than channels. -/ +theorem net (F K : Type) [Field F] [Fintype K] (d e : ℕ) : + Install.BNet F (run (K := K) (e := e) d) ((Fintype.card K + d + e + 2) ^ 100) := by + let M := Fintype.card K + d + e + 2 + let I := Input K e + have hm : 2 ≤ M := by omega + have hi : Fintype.card I ≤ M ^ 2 := by + simp only [I, Input, Fintype.card_prod, Fintype.card_option, Fintype.card_fin, pow_two] + exact Nat.mul_le_mul (by omega) (by omega) + have hk : Fintype.card K ≤ M ^ 2 := + (by omega : Fintype.card K ≤ M).trans (Nat.le_pow (by decide)) + have he : Fintype.card (Fin e) ≤ M ^ 2 := by + rw [Fintype.card_fin] + exact (by omega : e ≤ M).trans (Nat.le_pow (by decide)) + have hatom := Gate.atom (F := F) hm hi + have used (k : K) : Gate F M 0 (fun x : I → Bool => x (k, none) = true) := + hatom (fun t _ => t = true) (k, none) (k, none) + have same (j k : K) : Gate F M 1 (fun x : I → Bool => name x j = name x k) := by + apply (Gate.every hm hi he _ (fun t => hatom Eq (j, some t) (k, some t))).congr + exact fun x => funext_iff.symm + have leads (k : K) : Gate F M 4 (fun x : I → Bool => lead x k) := by + have prev (j : K) := hatom (fun t _ => pos j < pos k ∧ t = true) (j, none) (j, none) + have both (j : K) := Gate.both hm hi ((prev j).mono hm (by decide : 0 ≤ 1)) (same j k) + exact Gate.both hm hi ((used k).mono hm (by decide : 0 ≤ 3)) (Gate.absent hm hi hk _ both) + have rank (k : K) (i : Fin d) : Gate F M 7 (fun x : I → Bool => atRank x k i) := by + have prev (j : K) := hatom (fun _ _ => pos j < pos k) (j, none) (j, none) + have both (j : K) := Gate.both hm hi ((prev j).mono hm (by decide : 0 ≤ 4)) (leads j) + have hcnt := Gate.count hm hi hk _ both (· = i.val) + apply Gate.both hm hi ((leads k).mono hm (by decide : 4 ≤ 6)) + apply hcnt.congr + intro x + simp only [before] + congr! 4 + have output (j : Output K d e) : Gate F M 9 (fun x : I → Bool => run d x j = true) := by + rcases j with ⟨i, t⟩ | ⟨k, i⟩ + · have bit (k : K) := hatom (fun a _ => a = true) (k, some t) (k, some t) + have both (k : K) := Gate.both hm hi (rank k i) ((bit k).mono hm (by decide : 0 ≤ 7)) + exact (Gate.any hm hi hk _ both).congr (fun _ => by simp only [run, decide_eq_true_eq]; rfl) + · have both (t : K) := Gate.both hm hi (rank t i) ((same t k).mono hm (by decide : 1 ≤ 7)) + exact (Gate.any hm hi hk _ both).congr (fun _ => by simp only [run, decide_eq_true_eq]) + have ho : Fintype.card (Output K d e) ≤ M ^ 2 := by + simp only [Output, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + rw [Nat.mul_comm d, ← Nat.add_mul, pow_two] + exact Nat.mul_le_mul (by omega) (by omega) + have H := Gate.collect hm hi ho _ output + have heq : (fun x j => @decide (run d x j = true) (propDecidable _)) = + run (K := K) (e := e) d := by funext x j; simp + rw [heq] at H + exact H.mono (Nat.pow_le_pow_right (by omega) (by decide)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail.Compact +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/Hop.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/Hop.lean new file mode 100644 index 0000000000..600ac24d26 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/Hop.lean @@ -0,0 +1,1010 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact + +/-! +# Following original exterior stacks + +A span carries a local channel and the original stack key. The +long global name of the channel is shared by every block at its host. +This record contains no values of the exterior input bits. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail + +open Assembly Coloring Packing +variable {F : Type} {x y : Wire} {h u d e : ℕ} + +open Classical in +/-- Indexes the short by the coordinates of `Fin d ⊕ Fin h`. -/ +abbrev Short (h d : ℕ) := Fin d ⊕ Fin h + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def tag (c : Fin d) (s : Cell h) : Short h d → Bool := + Sum.elim (fun j => decide (j = c)) (Fintype.equivOfCardEq + (show Fintype.card (Cell h) = Fintype.card (Fin h → Bool) by simp [Cell]) s) + +open Classical in +theorem tag_injective {c c' : Fin d} {s s' : Cell h} (ht : tag c s = tag c' s') : + c = c' ∧ s = s' := by + have h₁ := congrFun ht (.inl c) + have h₂ := congrArg (fun f => f ∘ Sum.inr) ht + refine ⟨by simpa [tag] using h₁.symm, ?_⟩ + exact (Fintype.equivOfCardEq + (show Fintype.card (Cell h) = Fintype.card (Fin h → Bool) by simp [Cell])).injective h₂ + +open Classical in +/-- The data for the record construction, including `short`, `long`. -/ +structure Record (S : Scheme F) (h d e : ℕ) where + /-- The `Record` component of type `S.Span → Short h d → Bool`. -/ + short : S.Span → Short h d → Bool + /-- The `Record` component of type `B S.m → Fin d → Fin e → Bool`. -/ + long : B S.m → Fin d → Fin e → Bool + +open Classical in +/-- Builds `Format where obj` with the specified `obj`, `pins`, `code`. -/ +abbrev format (S : Scheme F) (h d e : ℕ) : Format where + obj := Record S h d e + pins := (S.Span × Short h d) ⊕ (B S.m × Fin d × Fin e) + code := + { toFun := fun t => Sum.elim (fun v => t.short v.1 v.2) (fun v => t.long v.1 v.2.1 v.2.2) + invFun := fun x => ⟨fun a b => x (.inl (a, b)), fun a b c => x (.inr (a, b, c))⟩ + left_inv := fun _ => rfl + right_inv := by intro f; funext i; cases i <;> rfl } + +variable [Field F] {S : Scheme F} {r : S.format.obj} + {G : Diagram F (copies x (2 ^ h * u)) (copies y (2 ^ h * u))} (p : S.Presentation r G) + (name : Stack.Outer x y ↪ (Fin e → Bool)) (data : Record S h d e) + +open Classical in +/-- The marked of type `Prop`, constructed using `(p.boundary (Stack.bit h u x y ((s, t), +i))).val`. -/ +def Marked (lane : B S.m → Stack.Outer x y → Fin d) : Prop := + ∀ (i : Stack.Outer x y) (s : Cell h), ∃ a : S.Span, + S.width r a = u ∧ data.short a = tag (lane a.1.1 i) s ∧ + data.long a.1.1 (lane a.1.1 i) = name i ∧ ∀ t : Fin u, + let v := (p.boundary (Stack.bit h u x y ((s, t), i))).val + v.1 = a ∧ v.2.val = t.val + +open Classical in +/-- The condition `∃ lane, Marked p name data lane` on the specified data. -/ +def Tracks : Prop := ∃ lane, Marked p name data lane + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- +# Tracking the incoming exterior spans at a new host + +A host receives a bounded bank of old names. Each occupied exterior +span points into that bank and selects one old span. Pointwise +preservation of offsets and widths implies preservation of entire +stacks, by injectivity of the two boundary maps. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring Packing +variable {F : Type} {S U : Scheme F} {k : ℕ} + +open Classical in +/-- Indexes the stub by the coordinates of `B S.h × B S.k × B S.e`. -/ +abbrev Stub (S : Scheme F) := B S.h × B S.k × B S.e + +open Classical in +/-- The value specified by `((i, q.1, q.2.1), q.2.2)`. -/ +def locate (i : B S.m) (q : Stub S) : S.Span := ((i, q.1, q.2.1), q.2.2) +open Classical in +/-- The value specified by `(x.1.2.1, x.1.2.2, x.2)`. -/ +def stub (x : S.Span) : Stub S := (x.1.2.1, x.1.2.2, x.2) + +open Classical in +/-- The data for the move construction, including `nav`, `read`. -/ +structure Move (S U : Scheme F) (k : ℕ) where + /-- The `Move` component of type `B U.m → B k → B S.m`. -/ + nav : B U.m → B k → B S.m + /-- The read operation of type `U.Span → Option (B k × Stub S)`. -/ + read : U.Span → Option (B k × Stub S) + +namespace Move +variable (M : Move S U k) + +open Classical in +/-- Transforms the indexed data by `(M.read q).map (fun p => locate (M.nav q.1.1 p.1) p.2)`. -/ +def previous (q : U.Span) := (M.read q).map (fun p => locate (M.nav q.1.1 p.1) p.2) + +variable [Field F] {x y : Wire} {G G' : Diagram F x y} {r : S.format.obj} {R : U.format.obj} + (p : S.Presentation r G) (q : U.Presentation R G') + +open Classical in +/-- The data for the agrees construction, including `mapped`, `active`. -/ +structure Agrees : Prop where + mapped : ∀ j, + let a := (p.boundary j).val + let b := (q.boundary j).val + M.previous b.1 = some a.1 ∧ U.width R b.1 = S.width r a.1 ∧ b.2.val = a.2.val + active : ∀ w, (M.read w).isSome → ∃ j, (q.boundary j).val.1 = w + +variable {M p q} + +open Classical in +theorem Agrees.same (h : M.Agrees p q) {a b : slots x ⊕ slots y} + (hs : (p.boundary a).val.1 = (p.boundary b).val.1) : + (q.boundary a).val.1 = (q.boundary b).val.1 := by + let n := (p.boundary b).val.2.val + have hn : n < U.width R (q.boundary a).val.1 := by + rw [(h.mapped a).2.1, hs] + exact (p.boundary b).val.2.isLt + let t : U.exposed R := ⟨⟨_, ⟨n, hn⟩⟩, (q.boundary a).property⟩ + obtain ⟨c, hc⟩ := q.boundary.surjective t + have hc' : (q.boundary c).val.1 = (q.boundary a).val.1 := congrArg (fun x => x.val.1) hc + have he : (p.boundary c).val.1 = (p.boundary b).val.1 := by + apply Eq.trans _ hs + apply Option.some.inj + rw [← (h.mapped c).1, ← (h.mapped a).1, hc'] + have hd : (p.boundary c).val.2.val = (p.boundary b).val.2.val := by + rw [← (h.mapped c).2.2, hc] + have : c = b := p.boundary.injective (Subtype.ext (Sigma.ext he + ((Fin.heq_ext_iff (congrArg (S.width r) he)).mpr hd))) + exact this ▸ hc'.symm + +end Move +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- +# Candidate origin marks + +An incoming channel consists of a local hop and a channel at the +corresponding previous host. Only channels used by an actual span +contribute to the bound on the number of distinct source names. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring Packing + +open Classical in +/-- Indexes the candidate by the coordinates of `B k × Fin d`. -/ +abbrev Candidate (k d : ℕ) := B k × Fin d +open Classical in +/-- Indexes the bits by the coordinates of `(J × (K ⊕ Fin h)) ⊕ (K × Fin e)`. -/ +abbrev Bits (J K : Type) (h e : ℕ) := (J × (K ⊕ Fin h)) ⊕ (K × Fin e) +open Classical in +/-- Computes the local by the application `Bits (Stub S) (Fin d) h e`. -/ +abbrev Local {F : Type} (S : Scheme F) (h d e : ℕ) := Bits (Stub S) (Fin d) h e + +variable {F : Type} {S U : Scheme F} {k h d e : ℕ} + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def Record.row (a : Record S h d e) (v : B S.m) : Local S h d e → Bool := + Sum.elim (fun i => a.short (locate v i.1) i.2) (fun t => a.long v t.1 t.2) + +open Classical in +/-- Translate a short lane number to a pair of hop and lane number. -/ +def mark (p : B k) (x : Short h d → Bool) : Candidate k d ⊕ Fin h → Bool + | .inl (j, i) => if j = p then x (.inl i) else false + | .inr t => x (.inr t) + +open Classical in +/-- In the case `.inl j`, this construction gives `decide (j = c)`. -/ +def flagged (c : Candidate k d) (s : Cell h) : Candidate k d ⊕ Fin h → Bool + | .inl j => decide (j = c) + | .inr t => tag c.2 s (.inr t) + +open Classical in +theorem mark_tag (p : B k) (c : Fin d) (s : Cell h) : + mark p (tag c s) = flagged (p, c) s := by + funext q + rcases q with ⟨j, i⟩ | t + · by_cases he : j = p <;> simp [mark, tag, flagged, he] + · rfl + +open Classical in +/-- The indexed operation `(M.read q).elim (fun _ => false) (fun t => mark t.1 (a.short (locate +(M.nav q.1.1 t.1) t.2)))`. -/ +def Move.marked (M : Move S U k) (a : Record S h d e) (q : U.Span) := + (M.read q).elim (fun _ => false) (fun t => + mark t.1 (a.short (locate (M.nav q.1.1 t.1) t.2))) + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def Move.incoming (M : Move S U k) (a : Record S h d e) (v : B U.m) : + Bits (Stub U) (Candidate k d) h e → Bool := + Sum.elim (fun t => M.marked a (locate v t.1) t.2) + (fun t => a.long (M.nav v t.1.1) t.1.2 t.2) + +variable [Field F] {x y : Wire} {u : ℕ} + {G H : Diagram F (copies x (2 ^ h * u)) (copies y (2 ^ h * u))} + {r : S.format.obj} {R : U.format.obj} {p : S.Presentation r G} {q : U.Presentation R H} + {name : Stack.Outer x y ↪ (Fin e → Bool)} {a : Record S h d e} {M : Move S U k} + +open Classical in +/-- One original stack becomes one entire span with exactly one incoming +mark. The name may occur through different hops for other stacks. -/ +theorem Tracks.incoming (hT : Tracks p name a) (hM : M.Agrees p q) (hu : 0 < u) + (i : Stack.Outer x y) (s : Cell h) : + ∃ v c, U.width R v = u ∧ M.marked a v = flagged c s ∧ + a.long (M.nav v.1.1 c.1) c.2 = name i ∧ ∀ t : Fin u, + let b := (q.boundary (Stack.bit h u x y ((s, t), i))).val + b.1 = v ∧ b.2.val = t.val := by + obtain ⟨lane, ht⟩ := hT + obtain ⟨o, hw, ho, he, hb⟩ := ht i s + let bit (t : Fin u) := Stack.bit h u x y ((s, t), i) + let j : Fin u := ⟨0, hu⟩ + let v := (q.boundary (bit j)).val.1 + have h₀ := hM.mapped (bit j) + have hv : M.previous v = some o := h₀.1.trans (congrArg some (hb j).1) + obtain ⟨⟨w, t⟩, hr, hs⟩ := Option.map_eq_some_iff.mp hv + have hloc : locate (M.nav v.1.1 w) t = o := hs + have hname : M.nav v.1.1 w = o.1.1 := congrArg (fun z => z.1.1) hloc + refine ⟨v, (w, lane o.1.1 i), h₀.2.1.trans ?_, ?_, ?_, fun t => ?_⟩ + · rw [(hb j).1, hw] + · simp only [Move.marked, hr, Option.elim_some, hloc, ho, mark_tag] + · exact hname ▸ he + · exact ⟨hM.same ((hb t).1.trans (hb j).1.symm), ((hM.mapped _).2.2).trans (hb t).2⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +section +/- # A short return hop and predecessor-span address -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Coloring Assembly + +variable {F : Type} + +/-- Computes the pointer by the application `Format.pair .bit (.pair (.addr k) (.pair (.addr +S.h) (.pair (.addr S.k) (.addr S.e))))`. -/ +abbrev pointer (S : Scheme F) (k : ℕ) := + Format.pair .bit (.pair (.addr k) (.pair (.addr S.h) (.pair (.addr S.k) (.addr S.e)))) + +/-- In the case `none`, this construction gives `(false, 0, 0, 0, 0)`. -/ +def point {k : ℕ} (S : Scheme F) : Option (B k × Stub S) → (pointer S k).obj + | none => (false, 0, 0, 0, 0) + | some p => (true, p) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- # Padding short predecessor pointers to batch-read addresses -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail + +open Assembly Coloring +variable {F : Type} (S U : Scheme F) (k : ℕ) + +open Classical in +/-- The quantity computed by `1 + max (k + S.h + S.k + S.e) (U.h + U.k + U.e)`. -/ +def addressWidth := 1 + max (k + S.h + S.k + S.e) (U.h + U.k + U.e) + +open Classical in +/-- Embeds `(pointer S k).pins` into `slots (word (addressWidth S U k))`. -/ +def pointerSlot : (pointer S k).pins ↪ slots (word (addressWidth S U k)) := + choice (Function.Embedding.nonempty_of_card_le (by + change (pointer S k).width ≤ Fintype.card (slots (word (addressWidth S U k))) + rw [card_slots, wd_word] + simp only [pointer, Format.width_pair, Format.width_addr, addressWidth] + change 1 + (k + (S.h + (S.k + S.e))) ≤ _ + omega)) + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def projection : slots (word (addressWidth S U k)) → (pointer S k).pins ⊕ Bool := + Function.extend (pointerSlot S U k) Sum.inl (fun _ => .inr false) + +open Classical in +/-- Embeds `Option (B k × Stub S)` into `B (addressWidth S U k) where toFun p`. -/ +def addresses : Option (B k × Stub S) ↪ B (addressWidth S U k) where + toFun p := Control.decode _ (Sum.elim ((pointer S k).code (point S p)) id ∘ projection S U k) + inj' := by + intro x y he + have h := (Control.decode _).injective he + have hx : point S x = point S y := by + apply (pointer S k).code.injective + funext j + have hh := congrFun h (pointerSlot S U k j) + simpa only [Function.comp_apply, projection, (pointerSlot S U k).injective.extend_apply, + Sum.elim_inl] using hh + cases x <;> cases y <;> + simp only [point, Prod.mk.injEq, reduceCtorEq, true_and, false_and, Option.some.injEq] + at hx ⊢ + exact hx + +open Classical in +/-- Indexes the controls by the coordinates of `Stub U × slots (word (addressWidth S U k))`. -/ +abbrev Controls := Stub U × slots (word (addressWidth S U k)) + +variable {S U k} + +open Classical in +/-- The value specified by `(Control.decode _).symm (addresses S U k (M.read (locate v q.1))) +q.2`. -/ +def Move.control (M : Move S U k) (v : B U.m) (q : Controls S U k) : Bool := + (Control.decode _).symm (addresses S U k (M.read (locate v q.1))) q.2 + +open Classical in +theorem Move.control_eq (M : Move S U k) (v : B U.m) (q : Controls S U k) : + M.control v q = Sum.elim ((pointer S k).code (point S (M.read (locate v q.1)))) id + (projection S U k q.2) := + congrFun ((Control.decode _).symm_apply_apply _) q.2 + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- # Long and short fields of an exterior-tracking step -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring +variable {F : Type} {S U : Scheme F} {k h d e : ℕ} + +/-- The indexing data represented by `⟨Local S h d e → Bool, Local S h d e, .refl _⟩`. -/ +abbrev rowFormat (S : Scheme F) (h d e : ℕ) : Format := + ⟨Local S h d e → Bool, Local S h d e, .refl _⟩ + +/-- The value specified by `.vec U.h (.vec U.k (.vec U.e (pointer S k)))`. -/ +abbrev localCommands (S U : Scheme F) (k : ℕ) : Format := + .vec U.h (.vec U.k (.vec U.e (pointer S k))) + +/-- The value specified by `(localCommands S U k).vec U.m`. -/ +abbrev controls (S U : Scheme F) (k : ℕ) := (localCommands S U k).vec U.m + +/-- Computes the receipts by the application `Format.vec U.m (.vec k (rowFormat S h d e))`. -/ +abbrev receipts (S U : Scheme F) (k h d e : ℕ) := + Format.vec U.m (.vec k (rowFormat S h d e)) + +/-- Evaluates `point S (M.read ((a, b, c), d))` at the input `a b c d`. -/ +def Move.commands (M : Move S U k) : (controls S U k).obj := + fun a b c d => point S (M.read ((a, b, c), d)) + +/-- Evaluates `data.row (M.nav a b)` at the input `a b`. -/ +def Move.received (M : Move S U k) (data : Record S h d e) : (receipts S U k h d e).obj := + fun a b => data.row (M.nav a b) + +theorem width_row (S : Scheme F) (h d e : ℕ) : + (rowFormat S h d e).width = 2 ^ (S.h + S.k + S.e) * (d + h) + d * e := by + simp [rowFormat, Format.width, Local, Bits, Stub, pow_add, mul_assoc] + +theorem width_format (S : Scheme F) (h d e : ℕ) : + (format S h d e).width = 2 ^ S.m * (rowFormat S h d e).width := by + simp only [format, rowFormat, Format.width, Local, Bits, Stub, Short, Scheme.Span, Scheme.Vtx, + Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + ring + +theorem width_controls (S U : Scheme F) (k : ℕ) : + (controls S U k).width = 2 ^ U.m * 2 ^ (U.h + U.k + U.e) * (1 + k + S.h + S.k + S.e) := by + simp only [controls, localCommands, pointer, Format.width_vec, Format.width_pair, + Format.width_addr, pow_add] + rw [Format.width_bit] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Coloring Assembly + +/-- In the case `some i`, this construction gives `⟨i.val, by have := i.isLt; rw [pow_succ]; +omega⟩`. -/ +def hop (k : ℕ) : Option (B k) → B (k + 1) + | some i => ⟨i.val, by have := i.isLt; rw [pow_succ]; omega⟩ + | none => ⟨2 ^ k, by have := Nat.two_pow_pos k; rw [pow_succ]; omega⟩ + +/-- Returns `(r (parent i)).1 ⟨j.val, hj⟩` when `hj : j.val < 2 ^ S.d` holds, and `parent i` +otherwise. -/ +def subroundNav {F : Type} {S U : Scheme F} (parent : B U.m → B S.m) (r : S.format.obj) + (i : B U.m) (j : B (S.d + 1)) : B S.m := + if hj : j.val < 2 ^ S.d then (r (parent i)).1 ⟨j.val, hj⟩ else parent i + +theorem nav_hop {F : Type} {S U : Scheme F} (parent : B U.m → B S.m) (r : S.format.obj) + (i : B U.m) (j : Option (B S.d)) : + subroundNav (U := U) parent r i (hop S.d j) = j.elim (parent i) (r (parent i)).1 := by + cases j <;> simp [subroundNav, hop] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- +# Looking up a batch of incoming markers + +Each bit of a translated marker is either constant or an old marker +bit. Read the resulting columns at the predecessor pointers, then +append the long names, which require no indirect reads. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail + +open Assembly Coloring Install +variable {F : Type} (S U : Scheme F) (k h d e : ℕ) + +open Classical in +/-- Indexes the read input by the coordinates of `(B k × Local S h d e) ⊕ Controls S U k`. -/ +abbrev ReadInput := (B k × Local S h d e) ⊕ Controls S U k +open Classical in +/-- Indexes the flag by the coordinates of `Candidate k d ⊕ Fin h`. -/ +abbrev Flag := Candidate k d ⊕ Fin h +open Classical in +/-- Indexes the column by the coordinates of `B w ⊕ B w × slots (word w)`. -/ +abbrev Column (w : ℕ) := B w ⊕ B w × slots (word w) + +open Classical in +private theorem stub_card : Fintype.card (Stub S) = 2 ^ (S.h + S.k + S.e) := by + simp [Stub, B, pow_add, mul_assoc] + +open Classical in +theorem target_le : Fintype.card (Stub U) ≤ 2 ^ addressWidth S U k := by + rw [stub_card] + exact Nat.pow_le_pow_right (by decide) (by unfold addressWidth; omega) + +open Classical in +/-- Embeds `Stub U` into `B (addressWidth S U k)`. -/ +def target : Stub U ↪ B (addressWidth S U k) := + choice (Function.Embedding.nonempty_of_card_le (by rw [Fintype.card_fin]; exact target_le S U k)) + +open Classical in +/-- In the case `none`, this construction gives `.inr false`. -/ +def tap (q : Flag k h d) : Option (B k × Stub S) → ReadInput S U k h d e ⊕ Bool + | none => .inr false + | some (j, i) => match q with + | .inl (p, b) => if p = j then .inl (.inl (j, .inl (i, .inl b))) else .inr false + | .inr b => .inl (.inl (j, .inl (i, .inr b))) + +open Classical in +/-- In the case `(j, .inl i)`, this construction gives `tap S U k h d e j (Function.invFun +(addresses S U k) i)`. -/ +def collect : Flag k h d × Column (addressWidth S U k) → ReadInput S U k h d e ⊕ Bool + | (j, .inl i) => tap S U k h d e j (Function.invFun (addresses S U k) i) + | (_, .inr (i, b)) => .inl (.inr (Function.invFun (target S U k) i, b)) + +open Classical in +private def select (q : Stub U × Flag k h d) := (q.2, target S U k q.1) + +open Classical in +/-- The value specified by `.inl (q.1.1, .inr (q.1.2, q.2))`. -/ +def longTap (q : Candidate k d × Fin e) : ReadInput S U k h d e := + .inl (q.1.1, .inr (q.1.2, q.2)) + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def incoming (x : ReadInput S U k h d e → Bool) : Bits (Stub U) (Candidate k d) h e → Bool + := + Sum.elim (fun q => Control.read (addressWidth S U k) + (fun j => Sum.elim x id (collect S U k h d e (q.2, j))) (target S U k q.1)) + (x ∘ longTap S U k h d e) + +open Classical in +private theorem incoming_eq (M : Move S U k) (a : Record S h d e) (v : B U.m) : + incoming S U k h d e (Sum.elim (fun p => a.row (M.nav v p.1) p.2) (M.control v)) = + M.incoming a v := by + funext t + rcases t with ⟨i, j⟩|⟨⟨p, i⟩, z⟩ + · have hi := Function.leftInverse_invFun (target S U k).injective i + have ha (p) := Function.leftInverse_invFun (addresses S U k).injective p + simp only [incoming, Sum.elim_inl, Control.read, collect, hi, Sum.elim_inr, Move.control, + Equiv.apply_symm_apply, ha, Move.incoming, Move.marked] + cases hp : M.read (locate v i) with + | none => rfl + | some q => + rcases j with ⟨p, b⟩|b + · by_cases h : p = q.1 <;> simp [tap, mark, h, Record.row, locate] + · rfl + · rfl + +open Classical in +private theorem total {x f o l w n m : ℕ} (hw : w + 1 ≤ m) (hm : 100 ≤ m) + (hc : 2 ^ w ≤ n) (hx : x ≤ 4 * n * m ^ 2) (hf : f ≤ m ^ 2) (ho : o ≤ n) (hl : l ≤ n * m ^ 2) : + 5 * x + (x + 34 * (f * (2 ^ w + 2 ^ w * w)) + f * (10000 * 2 ^ w * (w + 1) ^ 3) + + (f * 2 ^ w + 2 * (o * f) + o * f)) + (x + 2 * l + l) ≤ n * m ^ 8 := by + have hw' : w ≤ m := by omega + have hpow (j : ℕ) (hj : j ≤ 5) : m ^ j ≤ m ^ 5 := Nat.pow_le_pow_right (by omega) hj + calc + _ ≤ 5 * (4 * n * m ^ 2) + (4 * n * m ^ 2 + 34 * (m ^ 2 * (n + n * m)) + + m ^ 2 * (10000 * n * m ^ 3) + + (m ^ 2 * n + 2 * (n * m ^ 2) + n * m ^ 2)) + (4 * n * m ^ 2 + 2 * (n * m ^ 2) + n * m ^ 2) + := by gcongr + _ = n * (69 * m ^ 2 + 34 * m ^ 3 + 10000 * m ^ 5) := by ring + _ ≤ n * (10103 * m ^ 5) := by + apply Nat.mul_le_mul_left + have := hpow 2 (by decide) + have := hpow 3 (by decide) + omega + _ ≤ _ := by + have h : 10103 ≤ m ^ 3 := (by decide : 10103 ≤ 100 ^ 3) |>.trans (Nat.pow_le_pow_left hm _) + rw [show m ^ 8 = m ^ 3 * m ^ 5 by ring] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ h) + +variable (F : Type) [Field F] + +open Classical in +theorem incoming_net (S U : Scheme F) (k h d e : ℕ) : + let w := addressWidth S U k + ∃ f : (ReadInput S U k h d e → Bool) → Bits (Stub U) (Candidate k d) h e → Bool, + BNet F f ((2 ^ w + e) * (100 + w + 2 ^ k + h + d) ^ 8) ∧ + ∀ (M : Move S U k) (a : Record S h d e) (v : B U.m), + f (Sum.elim (fun p => a.row (M.nav v p.1) p.2) (M.control v)) = M.incoming a v := by + intro w + refine ⟨incoming S U k h d e, ?_, incoming_eq S U k h d e⟩ + have prep := (tap_depends (collect S U k h d e)).bnet F + have read := (Control.read_net F w).copies (Flag k h d) + have out := (BNet.id F (Stub U × Flag k h d)).pull (select S U k h d) + have long := (BNet.id F (Candidate k d × Fin e)).pull (longTap S U k h d e) + apply (((prep.comp read).comp out).pair long).mono + let n := 2 ^ w + e + let m := 100 + w + 2 ^ k + h + d + have hkpos : 0 < 2 ^ k := by positivity + have hwpos : 0 < 2 ^ w := by positivity + have hc : 2 ^ w ≤ n := by omega + have hm : 100 ≤ m := by omega + have hk : 2 ^ k * d + h ≤ m ^ 2 := by + calc + _ ≤ (2 ^ k + h) * (d + 1) := by rw [mul_add, add_mul, mul_one]; omega + _ ≤ _ := by rw [pow_two]; exact Nat.mul_le_mul (by omega) (by omega) + have ho := (target_le S U k).trans hc + have hs : 2 ^ k * Fintype.card (Stub S) ≤ n := by + rw [stub_card, ← pow_add] + apply le_trans _ hc + exact Nat.pow_le_pow_right (by decide) (by unfold w addressWidth; omega) + have hl : Fintype.card (Candidate k d × Fin e) ≤ n * m ^ 2 := by + simp only [Candidate, B, Fintype.card_prod, Fintype.card_fin] + rw [mul_comm] + exact Nat.mul_le_mul (by omega) (by omega) + have hf : Fintype.card (Flag k h d) ≤ m ^ 2 := by simpa [Flag, Candidate, B] using hk + have hx : Fintype.card (ReadInput S U k h d e) ≤ 4 * n * m ^ 2 := by + have hz := Nat.le_pow (a := m) (by decide : 0 < 2) + have hb : d + h ≤ m ^ 2 := by omega + have hw : w ≤ m ^ 2 := by omega + calc + _ = (2 ^ k * Fintype.card (Stub S)) * (d + h) + Fintype.card (Candidate k d × Fin e) + + Fintype.card (Stub U) * w := by + simp only [ReadInput, Local, Bits, Controls, Candidate, Fintype.card_sum, Fintype.card_prod, + B, Fintype.card_fin, card_slots, wd_word, w] + ring + _ ≤ n * m ^ 2 + n * m ^ 2 + n * m ^ 2 := by gcongr + _ ≤ _ := by ring_nf; omega + have H := total (by omega : w + 1 ≤ m) hm hc hx hf ho hl + simpa only [Column, B, Fintype.card_prod, Fintype.card_sum, Fintype.card_fin, + card_slots, wd_word, show localCost 1 = 34 by decide, n, m, w] using H + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +section +/- # Cost of updating long names and short marks separately -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring +variable {F : Type} (S U : Scheme F) (k h d d' e : ℕ) + +/-- The construction uses `addressWidth S U k` for its intermediate `w`. -/ +def cost := + let w := addressWidth S U k + let m := 100 + w + 2 ^ k * (d + 1) + h + d + d' + 2 ^ U.m * (2 ^ w * m ^ 10 + (m + e) ^ 104) + +private theorem overhead (m e n : ℕ) (hm : 100 ≤ m) : + 160 * (n * m ^ 8 + (m + e) ^ 102) ≤ n * m ^ 10 + (m + e) ^ 104 := by + have h (x j : ℕ) (hx : 100 ≤ x) : 160 * x ^ j ≤ x ^ (j + 2) := by + rw [pow_add, mul_comm (x ^ j)] + exact Nat.mul_le_mul_right _ ((by decide : 160 ≤ 100 ^ 2) |>.trans (Nat.pow_le_pow_left hx 2)) + rw [mul_add, mul_left_comm 160 n] + exact Nat.add_le_add (Nat.mul_le_mul_left n (h m 8 hm)) (h (m + e) 102 (by omega)) + +private theorem mixed (m e n : ℕ) (hm : 100 ≤ m) : + (n + e) * m ^ 8 ≤ n * m ^ 8 + (m + e) ^ 102 := by + rw [add_mul] + apply Nat.add_le_add_left + calc + _ ≤ (m + e) * (m + e) ^ 8 := by gcongr <;> omega + _ = (m + e) ^ 9 := (pow_succ' _ _).symm + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide) + +theorem execute_bound : + let w := addressWidth S U k + let readCost := (2 ^ w + e) * (100 + w + 2 ^ k + h + d) ^ 8 + let x := 100 + Fintype.card (Candidate k d) + d' + h + let updateCost := Fintype.card (Stub U) * x ^ 8 + (x + e) ^ 102 + ((receipts S U k h d e).pair (controls S U k)).width + + 34 * (2 ^ U.m * Fintype.card (ReadInput S U k h d e)) + + 2 ^ U.m * (readCost + updateCost) + 3 * (format U h d' e).width ≤ cost S U k h d d' e := by + intro w readCost x updateCost + let m := 100 + w + 2 ^ k * (d + 1) + h + d + d' + let T := 2 ^ w * m ^ 8 + (m + e) ^ 102 + have hm : 100 + w + 2 ^ k + 2 ^ k * d + h + d + d' = m := by unfold m; ring + have hp : 1 ≤ 2 ^ k := by exact Nat.one_le_pow _ _ (by decide) + have hm' : 100 ≤ m := by omega + have ho : 2 ^ (U.h + U.k + U.e) ≤ 2 ^ w := by + apply Nat.pow_le_pow_right (by decide) + unfold w addressWidth + omega + have hi : 2 ^ k * 2 ^ (S.h + S.k + S.e) ≤ 2 ^ w := by + rw [← pow_add] + exact Nat.pow_le_pow_right (by decide) (by unfold w addressWidth; omega) + have hmix : (2 ^ w + e) * m ≤ T := + (Nat.mul_le_mul_left _ (Nat.le_pow (by decide : 0 < 8))).trans (mixed m e (2 ^ w) hm') + have hr : readCost ≤ T := by + exact (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) 8)).trans (mixed m e (2 ^ w) hm') + have hc : updateCost ≤ T := by + have h₁ : Fintype.card (Stub U) ≤ 2 ^ w := by simpa [Stub, B, pow_add, mul_assoc] using ho + have h₂ : x ≤ m := by + simp only [x, Candidate, B, Fintype.card_prod, Fintype.card_fin] + omega + unfold updateCost T + gcongr + have ha : 2 ^ k * (rowFormat S h d e).width ≤ T := by + rw [width_row] + calc + _ = (2 ^ k * 2 ^ (S.h + S.k + S.e)) * (d + h) + e * (2 ^ k * d) := by ring + _ ≤ 2 ^ w * m + e * m := Nat.add_le_add (Nat.mul_le_mul hi (by omega)) (Nat.mul_le_mul_left _ + (by omega)) + _ ≤ T := by rw [← add_mul]; exact hmix + have hb : 2 ^ (U.h + U.k + U.e) * w ≤ T := + (Nat.mul_le_mul (ho.trans (Nat.le_add_right _ _)) (by omega)).trans hmix + have hin : Fintype.card (ReadInput S U k h d e) ≤ 2 * T := by + rw [Fintype.card_sum, Fintype.card_prod (B k), Fintype.card_fin, + Fintype.card_prod (Stub U), card_slots, wd_word, + show Fintype.card (Stub U) = 2 ^ (U.h + U.k + + U.e) by simp [Stub, B, pow_add, mul_assoc], two_mul] + exact Nat.add_le_add ha hb + have hfeed : ((receipts S U k h d e).pair (controls S U k)).width ≤ 2 ^ U.m * (2 * T) := by + rw [Format.width_pair, width_controls, Format.width_vec, Format.width_vec, mul_assoc, + ← mul_add, two_mul] + apply Nat.mul_le_mul_left + exact Nat.add_le_add ha ((Nat.mul_le_mul_left _ (by unfold w addressWidth; omega)).trans hb) + have hout : (format U h d' e).width ≤ 2 ^ U.m * T := by + rw [width_format, width_row, mul_comm d'] + apply Nat.mul_le_mul_left + refine le_trans ?_ hmix + rw [add_mul] + exact Nat.add_le_add (Nat.mul_le_mul ho (by omega)) (Nat.mul_le_mul_left _ (by omega)) + calc + _ ≤ 2 ^ U.m * (2 * T) + 34 * (2 ^ U.m * (2 * T)) + 2 ^ U.m * (T + T) + 3 * (2 ^ U.m * T) + := by gcongr + _ ≤ 2 ^ U.m * (160 * T) := by ring_nf; omega + _ ≤ _ := Nat.mul_le_mul_left _ (overhead m e _ hm') + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- # Relabeling incoming spans by a compact table of distinct names -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring Packing Finset + +variable {F J K : Type} [Fintype J] [Fintype K] {S U : Scheme F} {k h d e : ℕ} + +open Classical in +/-- In the case `(c, none)`, this construction gives `decide (∃ j, x (.inl (j, .inl c)) = +true)`. -/ +def pool (x : Bits J K h e → Bool) : Compact.Input K e → Bool + | (c, none) => decide (∃ j, x (.inl (j, .inl c)) = true) + | (c, some i) => x (.inr (c, i)) + +open Classical in +/-- In the case `.inl (j, .inl i)`, this construction gives `decide (∃ c, x (.inl (j, .inl c)) = +true ∧ y (.inr (c, i)) = true)`. -/ +def rename (x : Bits J K h e → Bool) (y : Compact.Output K d e → Bool) : + Bits J (Fin d) h e → Bool + | .inl (j, .inl i) => decide (∃ c, x (.inl (j, .inl c)) = true ∧ y (.inr (c, i)) = true) + | .inl (j, .inr t) => x (.inl (j, .inr t)) + | .inr (i, s) => y (.inl (i, s)) + +open Classical in +/-- Computes the update by the application `rename x (Compact.run d (pool x))`. -/ +def update (d : ℕ) (x : Bits J K h e → Bool) := rename x (Compact.run d (pool x)) + +open Classical in +/-- Builds `Record S h d e where short j t` with the specified `short`, `long`. -/ +def fromRows (x : B S.m → Local S h d e → Bool) : Record S h d e where + short j t := x j.1.1 (.inl (stub j, t)) + long j c p := x j (.inr (c, p)) + +open Classical in +/-- The indexed operation `fromRows (fun v => Trail.update d' (M.incoming a v))`. -/ +def Move.update (M : Move S U k) (d' : ℕ) (a : Record S h d e) : Record U h d' e := + fromRows (fun v => Trail.update d' (M.incoming a v)) + +variable [Field F] {x y : Wire} {u : ℕ} + {G H : Diagram F (copies x (2 ^ h * u)) (copies y (2 ^ h * u))} + {r : S.format.obj} {R : U.format.obj} {p : S.Presentation r G} {q : U.Presentation R H} + {name : Stack.Outer x y ↪ (Fin e → Bool)} {a : Record S h d e} {M : Move S U k} + +open Classical in +/-- The indexed operation `univ.filter (fun j : Stack.Outer x y => ∃ s t, (q.boundary (Stack.bit +h u x y ((s, t), j))).val.1.1.1 = v)`. -/ +def origins (q : U.Presentation R H) (v : B U.m) := + univ.filter (fun j : Stack.Outer x y => ∃ s t, (q.boundary (Stack.bit h u x y ((s, t), + j))).val.1.1.1 = v) + +open Classical in +private theorem names_subset (hT : Tracks p name a) (hM : M.Agrees p q) (hu : 0 < u) (v : B U.m) : + Compact.names (pool (M.incoming a v)) ⊆ (origins q v).image name := by + rintro _ hname + obtain ⟨c, hc, rfl⟩ := mem_image.mp hname + obtain ⟨j, hj⟩ := of_decide_eq_true (mem_filter.mp hc).2 + change M.marked a (locate v j) (.inl c) = true at hj + have has : (M.read (locate v j)).isSome := by + cases hp : M.read (locate v j) with + | none => simp [Move.marked, hp] at hj + | some v => rfl + obtain ⟨t, ht⟩ := hM.active _ has + obtain ⟨⟨⟨s, t⟩, i⟩, rfl⟩ := (Stack.bit h u x y).surjective t + obtain ⟨v', c', _, hm, he, hb⟩ := hT.incoming hM hu i s + have hv := (hb t).1.symm.trans ht + rw [hv] at hm he + rw [hm] at hj + have : c = c' := of_decide_eq_true hj + subst c' + refine mem_image.mpr ⟨i, mem_filter.mpr ⟨mem_univ _, s, t, ?_⟩, he.symm⟩ + exact congrArg (fun v => v.1.1) ht + +open Classical in +/-- The name width is paid once per channel, independently of how +many exterior spans and blocks use it. -/ +theorem Tracks.update (hT : Tracks p name a) (hM : M.Agrees p q) (hu : 0 < u) + {d' : ℕ} (hd : 0 < d') (cap : ∀ v, (origins q v).card ≤ d') : + Tracks q name (M.update d' a) := by + let b v := M.incoming a v + have hc (v) : (Compact.names (pool (b v))).card ≤ d' := + (card_le_card (names_subset hT hM hu v)).trans (card_image_le.trans (cap v)) + choose f hf using fun v => Compact.correct hd (pool (b v)) (hc v) + refine ⟨fun z i => f z (name i), fun i s => ?_⟩ + obtain ⟨v, c, hw, hv, he, hb⟩ := hT.incoming hM hu i s + let z := v.1.1 + have ht (t) : b z (.inl (stub v, t)) = flagged c s t := congrFun hv t + have hp : pool (b z) (c, none) = true := + decide_eq_true ⟨stub v, by rw [ht]; simp [flagged]⟩ + have hn : Compact.name (pool (b z)) c = name i := he + obtain ⟨hl, hs⟩ := hf z c hp + rw [hn] at hl hs + refine ⟨v, hw, ?_, funext hl, hb⟩ + funext t + change Trail.update d' (b z) (.inl (stub v, t)) = tag (f z (name i)) s t + cases t with + | inl t => + simp only [Trail.update, rename, ht, flagged, decide_eq_true_eq, exists_eq_left, hs, tag, + Sum.elim_inl] + | inr t => exact ht (.inr t) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- # Routing channel flags without repeating the long names per block -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Install + +variable {F I J K : Type} [Field F] [Fintype I] [Fintype J] [Fintype K] + +open Classical in +private theorem any_gate (p : (I → Bool) → J × K → Bool) (hp : Depends p 2) : + BNet F (fun x j => decide (∃ k, p x (j, k) = true)) + (Fintype.card I + Fintype.card J * (70 * Fintype.card K + 1)) := by + have h := (hp.bnet F).comp ((BNet.any F K).copies J) + apply (h.rename (.refl _) (Equiv.prodUnique J Unit)).mono + rw [Fintype.card_prod, show localCost 2 = 68 by decide] + exact le_of_eq (by ring) + +open Classical in +private theorem join_gate {p : (I → Bool) → K → Bool} {m : ℕ} (hp : BNet F p m) + (e : J → I ⊕ K) : + BNet F (fun x => Sum.elim x (p x) ∘ e) + (7 * Fintype.card I + Fintype.card K + 3 * Fintype.card J + m) := by + have h := ((BNet.id F I).pair hp).comp ((BNet.id F J).pull e) + apply h.mono + rw [Fintype.card_sum] + omega + +variable {h e d : ℕ} + +open Classical in +/-- The bound obtained by adding the component charges `8 * Fintype.card (Bits J K h e)+ 3 * +Fintype.card (Compact.Input K e) + Fintype.card K * (70 * Fintype.card J + 2)`. -/ +def poolCost (J K : Type) [Fintype J] [Fintype K] (h e : ℕ) := + 8 * Fintype.card (Bits J K h e)+ 3 * Fintype.card (Compact.Input K e) + + Fintype.card K * (70 * Fintype.card J + 2) + +open Classical in +theorem pool_net : BNet F (pool (J := J) (K := K) (h := h) (e := e)) (poolCost J K h e) := by + let p (x : Bits J K h e → Bool) (k : K × J) := x (.inl (k.2, .inl k.1)) + have hd : Depends p 2 := by + intro k + exact ⟨{.inl (k.2, .inl k.1)}, by simp, fun _ _ H => H _ (by simp)⟩ + let f : Compact.Input K e → Bits J K h e ⊕ K + | (k, none) => .inr k + | (k, some j) => .inl (.inr (k, j)) + have hb := join_gate (any_gate (F := F) p hd) f + convert hb using 1 + · funext x j + rcases j with ⟨k, _|t⟩ <;> rfl + · unfold poolCost + ring + +open Classical in +/-- Indexes the join by the coordinates of `Bits J K h e ⊕ Compact.Output K d e`. -/ +abbrev Join (J K : Type) (h d e : ℕ) := Bits J K h e ⊕ Compact.Output K d e + +open Classical in +/-- The bound obtained by adding the component charges `8 * Fintype.card (Join J K h d e) + 3 * +Fintype.card (Bits J (Fin d) h e) + Fintype.card (J × Fin d) * (70 * Fintype.card K + 2)`. -/ +def renameCost (J K : Type) [Fintype J] [Fintype K] (h d e : ℕ) := + 8 * Fintype.card (Join J K h d e) + 3 * Fintype.card (Bits J (Fin d) h e) + + Fintype.card (J × Fin d) * (70 * Fintype.card K + 2) + +open Classical in +theorem rename_net : + BNet F (fun x : Join J K h d e → Bool => rename (x ∘ Sum.inl) (x ∘ Sum.inr)) + (renameCost J K h d e) := by + let p (x : Join J K h d e → Bool) (k : (J × Fin d) × K) := + x (.inl (.inl (k.1.1, .inl k.2))) && x (.inr (.inr (k.2, k.1.2))) + have hd : Depends p 2 := by + intro k + let a : Join J K h d e := .inl (.inl (k.1.1, .inl k.2)) + let b : Join J K h d e := .inr (.inr (k.2, k.1.2)) + exact ⟨{a, b}, Finset.card_le_two, fun _ _ H => congrArg₂ Bool.and (H a (by simp)) (H b (by + simp))⟩ + let f : Bits J (Fin d) h e → Join J K h d e ⊕ (J × Fin d) + | .inl (j, .inl t) => .inr (j, t) + | .inl (j, .inr t) => .inl (.inl (.inl (j, .inr t))) + | .inr p => .inl (.inr (.inl p)) + have hb := join_gate (any_gate (F := F) p hd) f + convert hb using 1 + · funext x t + rcases t with ⟨j, i|i⟩|⟨k, u⟩ + · simp only [rename, Function.comp_apply, f, Sum.elim_inr, p, Bool.and_eq_true] + · rfl + · rfl + · unfold renameCost + ring + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +section +/- # Cost of updating long channel names and short span tags -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail + +open Install + +private theorem update_bound (J K : Type) [Fintype J] [Fintype K] (h d e : ℕ) : + 5 * Fintype.card (Bits J K h e) + Fintype.card (Bits J K h e) + + (poolCost J K h e + (Fintype.card K + d + e + 2) ^ 100) + renameCost J K h d e ≤ + Fintype.card J * (100 + Fintype.card K + d + h) ^ 8 + + (100 + Fintype.card K + d + h + e) ^ 102 := by + let k := Fintype.card K + let T := 100 + k + d + h + let U := T + e + let per := 22 * (k + h) + 70 * k + 3 * (d + h) + d * (70 * k + 2) + let common := 22 * k * e + 3 * k * (e + 1) + 2 * k + 8 * (d * e + k * d) + 3 * d * e + have hp : per ≤ 200 * T ^ 2 := by unfold per T; ring_nf; omega + have he : common ≤ 200 * U ^ 2 := by unfold common U T; ring_nf; omega + have aux (m : ℕ) (hm : 100 ≤ m) : 200 * m ^ 2 ≤ m ^ 4 := by + rw [show m ^ 4 = m ^ 2 * m ^ 2 from pow_add m 2 2] + exact Nat.mul_le_mul_right _ ((by decide : 200 ≤ 100 ^ 2).trans (Nat.pow_le_pow_left hm _)) + have hp' : per ≤ T ^ 8 := + (hp.trans (aux T (by omega))).trans (Nat.pow_le_pow_right (by omega) (by decide)) + have he' : common ≤ U ^ 100 := + (he.trans (aux U (by omega))).trans (Nat.pow_le_pow_right (by omega) (by decide)) + calc + _ = Fintype.card J * per + (common + (k + d + e + 2) ^ 100) := by + simp only [poolCost, renameCost, Join, Bits, Compact.Input, Compact.Output, + Fintype.card_sum, Fintype.card_prod, Fintype.card_option, Fintype.card_fin] + unfold per common k + generalize (Fintype.card K + d + e + 2) ^ 100 = c + ring + _ ≤ Fintype.card J * T ^ 8 + (U ^ 100 + U ^ 100) := by + exact Nat.add_le_add (Nat.mul_le_mul_left _ hp') + (Nat.add_le_add he' (Nat.pow_le_pow_left (by omega) _)) + _ ≤ _ := by + apply Nat.add_le_add_left + change U ^ 100 + U ^ 100 ≤ U ^ 102 + rw [← mul_two, show U ^ 102 = U ^ 100 * U ^ 2 from pow_add U 100 2] + exact Nat.mul_le_mul_left _ ((by omega : 2 ≤ U).trans (Nat.le_pow (by decide))) + +theorem update_net (F J K : Type) [Field F] [Fintype J] [Fintype K] (h d e : ℕ) : + BNet F (Trail.update (J := J) (K := K) (h := h) (e := e) d) + (Fintype.card J * (100 + Fintype.card K + d + h) ^ 8 + + (100 + Fintype.card K + d + h + e) ^ 102) := by + have hc := (pool_net (J := J) (h := h)).comp (Compact.net F K d e) + exact (((BNet.id F _).pair hc).comp rename_net).mono (update_bound J K h d e) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- # Executing a trail update simultaneously at all hosts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail + +open Assembly Coloring Install +variable {F : Type} (S U : Scheme F) (k h d e : ℕ) + +open Classical in +/-- The value specified by `(receipts S U k h d e).pair (controls S U k)`. -/ +abbrev feed := (receipts S U k h d e).pair (controls S U k) +open Classical in +private abbrev inputRow : Format := ⟨ReadInput S U k h d e → Bool, _, .refl _⟩ + +open Classical in +private def wires : B U.m × ReadInput S U k h d e → (feed S U k h d e).pins ⊕ Bool + | (v, .inl a) => .inl (.inl (v, a)) + | (v, .inr (a, b)) => Sum.map (fun j => .inr (v, a.1, a.2.1, a.2.2, j)) id (projection S U k b) + +open Classical in +private def prepare (x : (feed S U k h d e).obj) (v : B U.m) (i : ReadInput S U k h d e) := + Sum.elim ((feed S U k h d e).code x) id (wires S U k h d e (v, i)) + +open Classical in +private theorem prepare_eq (M : Move S U k) (a : Record S h d e) (v : B U.m) : + prepare S U k h d e (M.received a, M.commands) v = + Sum.elim (fun p => a.row (M.nav v p.1) p.2) (M.control v) := by + funext i + rcases i with ⟨j, b⟩ | ⟨⟨j, p, q⟩, b⟩ + · rfl + · simp only [prepare, wires, Sum.elim_inr, Move.control_eq] + cases projection S U k b <;> rfl + +open Classical in +private theorem prepare_net [Field F] : + Circuit F (feed S U k h d e) (.vec U.m (inputRow S U k h d e)) (prepare S U k h d e) + ((feed S U k h d e).width + 34 * (2 ^ U.m * Fintype.card (ReadInput S U k h d e))) := by + have ht := (tap_depends (wires S U k h d e)).bnet F + unfold Circuit + convert ht using 1 + · funext x ⟨v, i⟩ + change Sum.elim ((feed S U k h d e).code ((feed S U k h d e).code.symm x)) id _ = _ + rw [Equiv.apply_symm_apply] + rfl + · rw [Fintype.card_prod (B U.m), Fintype.card_fin, show localCost 1 = 34 by decide] + +open Classical in +private theorem fromRows_net [Field F] : + Circuit F (.vec U.m (rowFormat U h d e)) (format U h d e) fromRows + (3 * (format U h d e).width) := by + let p : (format U h d e).pins → B U.m × Local U h d e + | .inl (j, b) => (j.1.1, .inl (stub j, b)) + | .inr (v, j, b) => (v, .inr (j, b)) + have q := Circuit.project (F := F) (A := .vec U.m (rowFormat U h d e)) + (D := format U h d e) (f := fromRows) p (by rintro x (j | j) <;> rfl) + apply q.mono + rw [width_format, Format.width_vec] + omega + +open Classical in +theorem execute_net (F : Type) [Field F] (S U : Scheme F) (k h d d' e : ℕ) : + ∃ f, Circuit F (feed S U k h d e) (format U h d' e) f (cost S U k h d d' e) ∧ + ∀ (M : Move S U k) (a : Record S h d e), f (M.received a, M.commands) = M.update d' a := by + obtain ⟨r, hr, he⟩ := incoming_net F S U k h d e + have up := update_net F (Stub U) (Candidate k d) h d' e + have step := Circuit.map (F := F) (A := inputRow S U k h d e) (D := rowFormat U h d' e) + (fun _ : B U.m => Trail.update d' ∘ r) (fun _ => hr.comp up) + have net := ((prepare_net S U k h d e).comp step).comp (fromRows_net U h d' e) + refine ⟨_, net.mono (execute_bound S U k h d d' e), fun M a => ?_⟩ + unfold Move.update + apply congrArg fromRows + funext i + exact congrArg (Trail.update d') ((congrArg r (prepare_eq S U k h d e M a i)).trans (he M a i)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/One.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/One.lean new file mode 100644 index 0000000000..cbbcb69c70 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/One.lean @@ -0,0 +1,216 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Hop + +/-! +# Receiving origin labels from neighboring hosts + +Relay one dictionary and one short mark per span. The upper half +of the hop bank contains the record at the static parent itself. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring + +variable {F : Type} {S U : Scheme F} {h d e : ℕ} + +open scoped Classical in +/-- Computes the source by the application `S.format.pair (format S h d e)`. -/ +abbrev source (S : Scheme F) (h d e : ℕ) := S.format.pair (format S h d e) +open scoped Classical in +/-- The value specified by `Fmt.bank S.m S.d (rowFormat S h d e)`. -/ +abbrev bank (S : Scheme F) (h d e : ℕ) := Fmt.bank S.m S.d (rowFormat S h d e) +open scoped Classical in +/-- Computes the mail by the application `receipts S S S.d h d e`. -/ +abbrev mail (S : Scheme F) (h d e : ℕ) := receipts S S S.d h d e + +open scoped Classical in +private def rebank (x : (source S h d e).obj) : (bank S h d e).obj := + fun i => ((x.1 i).1, x.2.row i) + +open scoped Classical in +private def dispatch (parent : B U.m → B S.m) (x : (bank S h d e).obj × (mail S h d e).obj) : + (receipts S U (S.d + 1) h d e).obj := + fun i j => if hj : j.val < 2 ^ S.d then x.2 (parent i) ⟨j.val, hj⟩ else (x.1 (parent i)).2 + +open scoped Classical in +/-- The gather bound used in the `Trail` construction. -/ +def gatherBound (S U : Scheme F) (h d e v n : ℕ) := + gatherCost S.m S.d v n + 64 * ((source S h d e).width + (bank S h d e).width + + (mail S h d e).width + (receipts S U (S.d + 1) h d e).width) + +variable [Field F] {I : Type*} {u v n : ℕ} {L : Set (Table F)} + +open scoped Classical in +private theorem rebank_net : + Circuit F (source S h d e) (bank S h d e) rebank + ((source S h d e).width + 2 * (bank S h d e).width) := by + let read : (bank S h d e).pins → (source S h d e).pins + | (i, .inl p) => .inl (i, .inl p) + | (i, .inr (.inl (j, p))) => .inr (.inl (locate i j, p)) + | (i, .inr (.inr p)) => .inr (.inr (i, p)) + apply Circuit.project read + rintro x ⟨i, p | ⟨j, p⟩ | p⟩ <;> rfl + +open scoped Classical in +private theorem dispatch_net (parent : B U.m → B S.m) : + Circuit F (.pair (bank S h d e) (mail S h d e)) (receipts S U (S.d + 1) h d e) (dispatch parent) + ((Format.pair (bank S h d e) (mail S h d e)).width + 2 * (receipts S U (S.d + + 1) h d e).width) := by + let read : (receipts S U (S.d + 1) h d e).pins → (Format.pair (bank S h d e) (mail S h d e)).pins + | (i, j, p) => if hj : j.val < 2 ^ S.d then .inr (parent i, ⟨j.val, hj⟩, p) + else .inl (parent i, .inr p) + apply Circuit.project read + rintro x ⟨i, j, p⟩ + change dispatch parent x i j p = _ + unfold dispatch read + dsimp only + split <;> rfl + +open scoped Classical in +theorem gather (hu : 3 ≤ u) (ht : Access F u L (S.m + S.d) v n) (hv : (rowFormat S h d e).width ≤ v) + (r : I → S.format.obj) (a : I → Record S h d e) (M : I → Move S U (S.d + 1)) + (parent : B U.m → B S.m) + (hr : ∀ i, Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) (r i)) + (hn : ∀ i, (M i).nav = subroundNav (U := U) parent (r i)) : + Computes F u L (source S h d e) (receipts S U (S.d + 1) h d e) (fun i => (r i, a i)) + (fun i => (M i).received (a i)) (fun _ => 1) (gatherBound S U h d e v n) := by + let Y (i : I) := rebank (S := S) (r i, a i) + let A := rowFormat S h d e + have start := Computes.of_map (L := L) (x := fun i => (r i, a i)) (y := Y) + (Map.circuit hu (rebank_net (S := S))) (fun _ => rfl) + have keep := Computes.of_map (L := L) (x := Y) (y := Y) + (Map.circuit hu (Circuit.id F (bank S h d e))) (fun _ => rfl) + have send := gather_neighbors A hu ht hv Y hr + have post := Computes.of_map (L := L) (x := fun i => (Y i, Fmt.gather A (Y i))) + (y := fun i => (M i).received (a i)) (Map.circuit hu (dispatch_net (U := U) parent)) (by + intro i + funext j k + unfold dispatch Move.received + rw [hn] + unfold subroundNav + split <;> rfl) + have all := (start.comp (keep.pair hu send)).comp post + simp only [one_mul] at all + refine all.mono ?_ + simp only [gatherBound, Format.width_pair] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- +# Carrying exterior data through a weighted step + +The ordinary transition produces the return pointers. In parallel, +the previous origins are gathered and then compacted using those pointers. +Only the ordinary transition supplies a weight. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring + +variable {F : Type} {S U : Scheme F} {k h d e : ℕ} + +/-- The quantity computed by `20 * A.width + 16 * (T.width + (feed S U k h d e).width) + 4 * +cost S U k h d d' e`. -/ +def carryCost (S U : Scheme F) (k h d d' e : ℕ) (A T : Format) := + 20 * A.width + 16 * (T.width + (feed S U k h d e).width) + 4 * cost S U k h d d' e + +variable [Field F] {I : Type*} {u m n : ℕ} {L : Set (Table F)} + {A T : Format} {x : I → A.obj} {y : I → T.obj} {w : I → F} + +theorem carry (hu : 3 ≤ u) (d' : ℕ) (M : I → Move S U k) (a : I → Record S h d e) + (commands : Computes F u L A (.pair T (controls S U k)) + x (fun i => (y i, (M i).commands)) w m) + (mail : Computes F u L A (receipts S U k h d e) + x (fun i => (M i).received (a i)) (fun _ => 1) n) : + Computes F u L A (.pair T (format U h d' e)) + x (fun i => (y i, (M i).update d' (a i))) w (m + n + carryCost S U k h d d' e A T) := by + let C := controls S U k + let R := receipts S U k h d e + let X := (T.pair C).pair R + let Y := T.pair (R.pair C) + have order : Circuit F X Y (fun z => (z.1.1, z.2, z.1.2)) (X.width + 2 * Y.width) := by + apply Circuit.project (Sum.elim (Sum.inl ∘ Sum.inl) (Sum.elim Sum.inr (Sum.inl ∘ Sum.inr))) + rintro _ (i|i|i) <;> rfl + obtain ⟨f, hf, he⟩ := execute_net F S U k h d d' e + have post := Map.circuit (L := L) hu (order.comp ((Circuit.id F T).par hf)) + have run := (commands.pair hu mail).comp (Computes.of_map post + (y := fun i => (y i, (M i).update d' (a i))) (by + intro i + exact congrArg (Prod.mk (y i)) (he (M i) (a i)))) + simp only [mul_one] at run + refine run.mono ?_ + simp only [carryCost, feed, X, Y, C, R, Format.width_pair] + omega + +theorem propagate {v s : ℕ} (hu : 3 ≤ u) (d' : ℕ) + (ht : Access F u L (S.m + S.d) v s) (hv : (rowFormat S h d e).width ≤ v) + (r : I → S.format.obj) (a : I → Record S h d e) (M : I → Move S U (S.d + 1)) + (parent : B U.m → B S.m) + (hr : ∀ i, Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) (r i)) + (hn : ∀ i, (M i).nav = subroundNav (U := U) parent (r i)) + (commands : Computes F u L A (.pair T (controls S U (S.d + 1))) + x (fun i => (y i, (M i).commands)) w m) + (read : Computes F u L A (source S h d e) x (fun i => (r i, a i)) (fun _ => 1) n) : + Computes F u L A (.pair T (format U h d' e)) + x (fun i => (y i, (M i).update d' (a i))) w + (m + n + gatherBound S U h d e v s + carryCost S U (S.d + 1) h d d' e A T) := by + have mail := read.comp (gather hu ht hv r a M parent hr hn) + simp only [one_mul] at mail + simpa only [add_assoc] using carry hu d' M a commands mail + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- # A reset gathers origin marks only at the static parent -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring +variable {F : Type} [Field F] {S U : Scheme F} {I : Type*} {h d d' e u m : ℕ} + {L : Set (Table F)} {A T : Format} {x : I → A.obj} {y : I → T.obj} {w : I → F} + +theorem one (hu : 3 ≤ u) (M : I → Move S U 0) (a : I → Record S h d e) + (parent : B U.m → B S.m) (hp : ∀ i j b, (M i).nav j b = parent j) + (commands : Computes F u L A (.pair T (controls S U 0)) + x (fun i => (y i, (M i).commands)) w m) : + Computes F u L (.pair A (format S h d e)) (.pair T (format U h d' e)) + (fun i => (x i, a i)) (fun i => (y i, (M i).update d' (a i))) w + (m + 2 * carryCost S U 0 h d d' e (.pair A (format S h d e)) T) := by + let D := A.pair (format S h d e) + let R := receipts S U 0 h d e + let old : I → D.obj := fun i => (x i, a i) + have read : Circuit F D A Prod.fst (D.width + 2 * A.width) := Circuit.project Sum.inl fun _ _ + => rfl + let f (s : D.obj) : R.obj := fun j _ => s.2.row (parent j) + let pins : R.pins → D.pins + | (j, _, .inl (i, b)) => .inr (.inl (locate (parent j) i, b)) + | (j, _, .inr p) => .inr (.inr (parent j, p)) + have send : Circuit F D R f (D.width + 2 * R.width) := by + apply Circuit.project pins + rintro b ⟨j, k, i|p⟩ <;> rfl + have step := (Computes.of_map (x := old) (y := x) (Map.circuit (L := L) hu read) + (fun _ => rfl)).comp commands + have mail := Computes.of_map (x := old) (y := fun i => (M i).received (a i)) + (Map.circuit (L := L) hu send) (by + intro i; funext j k; simp only [f, old, Move.received, hp]) + simp only [one_mul] at step + refine (carry hu d' M a step mail).mono ?_ + simp only [carryCost, feed, D, R, Format.width_pair] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/TraceNet.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/TraceNet.lean new file mode 100644 index 0000000000..57b6f6995d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Trail/TraceNet.lean @@ -0,0 +1,674 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Hop +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Length +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Observed +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Encoded +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Issue + +/-! +# Initial names of exterior stacks + +The trivalent input gives at most three exterior channels per host. +The first bit of a nonempty stack identifies its span injectively. +All names can therefore be installed as fixed initial data. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring Packing + +variable {F : Type} {x y : Wire} {a u d e m : ℕ} + +open Classical in +private theorem channel_names (G : Diagram F x y) (hG : G.Trivalent) (host : G.V ↪ B m) (hd : 3 + ≤ d) : + ∃ f : Stack.Outer x y ↪ B m × Fin d, ∀ i, (f i).1 = host (portEnd G i) := by + have pick (v : G.V) : Nonempty (G.Port v ↪ Fin d) := by + apply Function.Embedding.nonempty_of_card_le + simpa [Diagram.Port, Diagram.arity] using (hG v).trans hd + let code (v) := (pick v).some + let f : (Σ v, G.Port v) ↪ B m × Fin d := + { toFun i := (host i.1, code i.1 i.2) + inj' := by + rintro ⟨i, s⟩ ⟨j, t⟩ h + obtain ⟨h, h'⟩ := Prod.mk.inj h + have he : i = j := host.injective h + subst j + exact congrArg (Sigma.mk i) ((code i).injective h') } + refine ⟨(boundaryEnd G).trans (G.portEquiv.symm.toEmbedding.trans f), fun i => ?_⟩ + change host (G.portEquiv.symm (boundaryEnd G i)).1 = _ + rw [← G.station_port, Equiv.apply_symm_apply, station_boundary] + +variable [Field F] {S : Scheme F} {r : S.format.obj} + {H : Diagram F (copies x (2 ^ a * u)) (copies y (2 ^ a * u))} + +open Classical in +theorem initial (G : Diagram F x y) (hG : G.Trivalent) (p : S.Presentation r H) + (host : G.V ↪ B S.m) (hu : 0 < u) (hd : 3 ≤ d) + (name : Stack.Outer x y ↪ (Fin e → Bool)) + (h : ∀ (i : Stack.Outer x y) (s : Cell a), ∃ w : S.Span, + S.width r w = u ∧ w.1.1 = host (portEnd G i) ∧ ∀ t, + let v := (p.boundary (Stack.bit a u x y ((s, t), i))).val + v.1 = w ∧ v.2.val = t.val) : + ∃ data : Record S a d e, Tracks p name data := by + obtain ⟨f, hf⟩ := channel_names G hG host hd + choose w hw hg hp using h + let w' (q : Stack.Outer x y × Cell a) := w q.1 q.2 + have hinj : Function.Injective w' := by + rintro ⟨i, s⟩ ⟨j, t⟩ he + let l : Fin u := ⟨0, hu⟩ + have e₁ := (hp i s l).1.trans (he.trans (hp j t l).1.symm) + have e₂ := (hp i s l).2.trans (hp j t l).2.symm + have eq : ((s, l), i) = ((t, l), j) := by + apply (Stack.bit a u x y).injective + apply p.boundary.injective + exact Subtype.ext (Sigma.ext e₁ ((Fin.heq_ext_iff (congrArg (S.width r) e₁)).mpr e₂)) + exact Prod.ext (congrArg Prod.snd eq) (congrArg (·.1.1) eq) + let data : Record S a d e := + { short := Function.extend w' (fun q => tag (f q.1).2 q.2) (fun _ _ => false) + long := Function.curry (Function.extend f name (fun _ _ => false)) } + refine ⟨data, fun _ i => (f i).2, fun i s => ⟨w i s, hw i s, ?_, ?_, hp i s⟩⟩ + · exact hinj.extend_apply (fun q => tag (f q.1).2 q.2) (fun _ _ => false) (i, s) + · rw [hg, ← hf] + exact f.injective.extend_apply name (fun _ _ => false) i + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- +# Local return pointers in a subround + +Use the lower half of an address bank for neighbors and the upper +half for the parent itself. An internal or absent span has no pointer. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +open Coloring Packing History BatchDescent + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') {hle : Δ ≤ D} {Z : Scheme F} + +open scoped Classical in +/-- The value specified by `(Trail.hop S.d t.1, t.2.1, 0, t.2.2)`. -/ +def encodePointer (t : Option (B S.d) × B S.h × B S.e) : B (S.d + 1) × Trail.Stub S := + (Trail.hop S.d t.1, t.2.1, 0, t.2.2) + +open scoped Classical in +/-- In the case `.inl j`, this construction gives `some (encodePointer (u.predecessor j))`. -/ +def facePointer : u.Faces → Option (B (S.d + 1) × Trail.Stub S) + | .inl j => some (encodePointer (u.predecessor j)) + | .inr _ => none + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def pointerList (α : u.Assignment hle Z) (w : Site (u.G.V × Cell a) (h - a)) : + B Z.e → Option (B (S.d + 1) × Trail.Stub S) := + Function.extend (α.seat w) (fun i => u.facePointer i.val) (fun _ => none) + +open scoped Classical in +/-- The value specified by `Trail.point S ∘ u.pointerList α u.v`. -/ +def localPointers (α : u.Assignment hle Z) : (Format.vec Z.e (Trail.pointer S (S.d + 1))).obj := + Trail.point S ∘ u.pointerList α u.v + +variable {u} {v : State S P a h z Δ D k B'} {n : ℕ} + {m' d' a' e' ℓ n' l s : ℕ} {Y : Format} {M : Menu F l s ℓ} + {unpack : Y.obj → (History.code n' e' l s ℓ).obj} + +open scoped Classical in +private theorem pointer_same {i : u.localFaces} {j : v.localFaces} + (hg : u.v.1.2 = v.v.1.2) (hk : u.p.block = v.p.block) + (he : u.faceName i.val = v.faceName j.val) : u.facePointer i.val = v.facePointer j.val := by + rcases i with ⟨i|i, hi⟩ <;> rcases j with ⟨j|j, hj⟩ + · exact congrArg (fun t => some (encodePointer t)) (predecessor_eq hi hj he hg hk) + · cases he + · cases he + · rfl + +open scoped Classical in +theorem Same.localPointers (same : u.Same v n) (hn : 8 ≤ n) + (α : u.Assignment hle (Post.scheme m' d' a' e' Y M unpack)) + (β : v.Assignment hle (Post.scheme m' d' a' e' Y M unpack)) + (ha : u.Ranked α) (hb : v.Ranked β) (hg : u.v.1.2 = v.v.1.2) (hk : u.p.block = v.p.block) : + u.localPointers α = v.localPointers β := by + unfold State.localPointers + apply congrArg (Trail.point S ∘ ·) + funext r + unfold pointerList + by_cases hr : r ∈ Set.range (α.seat u.v) + · obtain ⟨i, rfl⟩ := hr + obtain ⟨j, hj, he⟩ := match_seat same hn α β ha hb i + rw [(α.seat u.v).injective.extend_apply, he] + refine (pointer_same hg hk hj).trans ?_ + exact ((β.seat v.v).injective.extend_apply (fun t => v.facePointer t.val) (fun _ + => none) j).symm + · have hr' : r ∉ Set.range (β.seat v.v) := by + rintro ⟨j, hj⟩ + obtain ⟨i, _, he⟩ := match_seat same.symm hn β α hb ha j + exact hr ⟨i, he.symm.trans hj⟩ + rw [Function.extend_apply' _ _ _ hr, Function.extend_apply' _ _ _ hr'] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Preserving exterior labels through an emitted subround -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.State + +open Coloring Packing History History.Subround BatchDescent + +variable {F : Type} [Field F] {S : Scheme F} {P : Gadget F} {a h z Δ D k : ℕ} {B' : ℝ} + (u : State S P a h z Δ D k B') {hle : Δ ≤ D} {Z : Scheme F} + (α : u.Assignment hle Z) (parent : B Z.m → B S.m) + +open scoped Classical in +/-- Builds `Trail.Move S Z (S.d + 1) where nav` with the specified `nav`, `read`. -/ +def subround : Trail.Move S Z (S.d + 1) where + nav := Trail.subroundNav (U := Z) parent u.r + read x := Function.extend α.vertex (u.pointerList α) (fun _ _ => none) x.1 x.2 + +open scoped Classical in +theorem subround_at (w : Site (u.G.V × Cell a) (h - a)) : + let v := α.vertex w + (u.subround α parent).commands v.1 v.2.1 v.2.2 = (u.recenter w).localPointers α := by + funext i + change Trail.point S (Function.extend α.vertex (u.pointerList α) (fun _ _ + => none) (α.vertex w) i) = _ + erw [α.vertex.injective.extend_apply] + have he : u.facePointer = (u.recenter w).facePointer := by funext j; cases j <;> rfl + unfold pointerList + erw [he] + rfl + +open scoped Classical in +theorem subround_vacant (v : Z.Vtx) (hv : v ∉ Set.range α.vertex) : + (u.subround α parent).commands v.1 v.2.1 v.2.2 = fun _ => Trail.point S none := by + funext i + change Trail.point S (Function.extend α.vertex (u.pointerList α) (fun _ _ => none) v i) = _ + erw [Function.extend_apply' _ _ _ hv] + +open scoped Classical in +private theorem read_span (j : u.Faces) : + (u.subround α parent).read (α.span j) = u.facePointer j := by + let w := whereAt u.g u.m P u.H.units u.i u.p.toPresentation j + change Function.extend α.vertex (u.pointerList α) (fun _ _ => none) (α.vertex w) (α.seat w ⟨j, + rfl⟩) = _ + erw [α.vertex.injective.extend_apply, pointerList, (α.seat w).injective.extend_apply] + +open scoped Classical in +private theorem read_live {t : Z.Span} (ht : ((u.subround α parent).read t).isSome) : + ∃ j : u.p.toPresentation.BorderSpan, α.span (.inl j) = t := by + obtain ⟨v, r⟩ := t + change (Function.extend α.vertex (u.pointerList α) (fun _ _ => none) v r).isSome = true at ht + by_cases hv : v ∈ Set.range α.vertex + swap + · erw [Function.extend_apply' _ _ _ hv] at ht + cases ht + obtain ⟨w, rfl⟩ := hv + erw [α.vertex.injective.extend_apply, pointerList] at ht + by_cases hr : r ∈ Set.range (α.seat w) + swap + · erw [Function.extend_apply' _ _ _ hr] at ht + cases ht + obtain ⟨j, rfl⟩ := hr + erw [(α.seat w).injective.extend_apply] at ht + obtain ⟨j|j, hj⟩ := j + · exact ⟨j, Prod.ext (congrArg α.vertex hj) (α.slot_eq w ⟨.inl j, hj⟩)⟩ + · cases ht + +open scoped Classical in +private theorem recover_host (w : u.G.V × Cell a) (b : Cell (h - a)) : + let v := (u.g.route u.m u.col w b).1 + (u.q.reverse v w).elim (u.p.host v.1) (u.r (u.p.host v.1)).1 = u.p.host w.1 := by + intro v + have he : u.q.recover v (u.q.reverse v w) = w := u.q.recover_reverse u.g u.m u.col w b + by_cases hv : v = w + · have hh : u.q.reverse v w = none := ite_eq_left hv + rw [hh, Option.elim_none, hv] + · have hh : u.q.reverse v w = some (u.q.slot v w) := ite_eq_right hv + rw [hh, Option.elim_some] + rw [hh] at he + let i := u.q.slot v w + change (u.p.nav v.1 i, v.2) = w at he + unfold Scheme.Posting.nav at he + split at he + · rename_i ht + exact ht.choose_spec.symm.trans (congrArg (fun p => u.p.host p.1) he) + · exact (hv he).elim + +open scoped Classical in +private theorem previous_span (hp : ∀ w, parent (α.vertex w).1 = u.p.host w.1.1) + (j : u.p.toPresentation.BorderSpan) : + (u.subround α parent).previous (α.span (.inl j)) = some (u.p.vertex j.val.1, j.val.2) := by + erw [Trail.Move.previous, u.read_span α parent (.inl j)] + let b := u.H.units.place j.val.1 + let w := u.g.route u.m u.col b.1 b.2 + let old := u.p.vertex j.val.1 + change some ((Trail.subroundNav (U := Z) parent u.r (α.vertex w).1 + (Trail.hop S.d (u.q.reverse w.1 b.1)), old.2.1, 0), j.val.2) = _ + erw [Trail.nav_hop, hp w, u.recover_host b.1 b.2] + unfold old + rw [u.p.vertex_eq] + rfl + +open scoped Classical in +theorem subround_agrees (hp : ∀ w, parent (α.vertex w).1 = u.p.host w.1.1) + {out : Z.format.obj} (l : α.Lengths out) (ha : α.Agrees l u.hz) : + (u.subround α parent).Agrees u.p.toPresentation (α.presentation l u.hz ha) := by + let p := u.p.toPresentation + have eq (j : p.BorderBit) : + ((α.presentation l u.hz ha).boundary (p.exteriorBits j)).val = + ⟨α.span (.inl j.1), j.2.cast (l.used (.inl j.1)).symm⟩ := by + rw [Scheme.Presentation.boundary_val] + exact α.exposed_pin l u.hz ha j + constructor + · intro i + obtain ⟨j, rfl⟩ := p.exteriorBits.surjective i + rw [eq, Scheme.Presentation.boundary_val, p.border_pin] + exact ⟨u.previous_span α parent hp _, l.used (.inl j.1), rfl⟩ + · intro w hw + obtain ⟨j, rfl⟩ := u.read_live α parent hw + let t : p.BorderBit := ⟨j, ⟨0, j.property.1⟩⟩ + exact ⟨p.exteriorBits t, congrArg Sigma.fst (eq t)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.State +end + +/- # Assigning tracked spans to ordered finest bundles -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring Packing + +variable {F : Type} [Field F] {x y : Wire} {D : Dimensions} {S : Scheme F} + {r : S.format.obj} {a K : ℕ} {G : Diagram F x y} + {Q : HostNet F (Stack.fringe (copies x D.copies) (copies y D.copies)) a D.z} + {p : S.Posting r Q} {name : Stack.Outer x y ↪ (Fin D.e → Bool)} + {rec : Record S D.h D.d D.e} {lane : B S.m → Stack.Outer x y → Fin D.d} + +open Classical in +theorem Marked.strips (h : Marked p.toPresentation name rec lane) : Strips (Exterior.ports p) := by + rintro ⟨⟨i, s⟩, j⟩ + obtain ⟨q, _, _, _, hq⟩ := h i s + exact ⟨q, j.val, fun t => hq (finProdFinEquiv (j, t))⟩ + +open Classical in +theorem Marked.long_at (h : Marked p.toPresentation name rec lane) + (L : Stack.Holders G Q K) (i : Stack.Outer x y) (s : Cell D.h) : + let H := p.host (L.core i s) + rec.long H (lane H i) = name i := by + obtain ⟨q, _, _, he, hq⟩ := h i s + let j : Fin D.b := ⟨0, D.bpos⟩ + let t : Fin D.z := ⟨0, D.zpos⟩ + have ht : (Exterior.ports p (((i, s), j), t)).val.1 = q := (hq (finProdFinEquiv (j, t))).1 + have hu := Exterior.ports_at p L i s j t + rw [ht] at hu + rw [hu] at he + exact he + +open Classical in +theorem Marked.separate (h : Marked p.toPresentation name rec lane) + (L : Stack.Holders G Q K) (i j : Stack.Outer x y) (s t : Cell D.h) + (hs : L.core i s = L.core j t) + (ht : lane (p.host (L.core i s)) i = lane (p.host (L.core j t)) j) : i = j := by + apply name.injective + simpa only [ht, hs] using ((h.long_at L i s).symm.trans (by rw [ht, hs]; exact h.long_at L j t)) + +open Classical in +/-- Uses `⟨a, Q, r, p, K, L, lane, h.separate L, hc, h.strips⟩` as the representation. -/ +def Marked.assign (h : Marked p.toPresentation name rec lane) + (L : Stack.Holders G Q K) (hc : ∀ i, (Finset.univ.image (L.core i)).card * D.q ≤ 2 ^ D.h) : + Assignment D S G := + ⟨a, Q, r, p, K, L, lane, h.separate L, hc, h.strips⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- # Capacity from the bound on distinct origins at a core station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +open Assembly Coloring Packing Finset + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {r : S.format.obj} + {h u a z K k : ℕ} {G : Diagram F x y} + {Q : HostNet F (Stack.fringe (copies x (2 ^ h * u)) (copies y (2 ^ h * u))) a z} + (p : S.Posting r Q) (L : Stack.Holders G Q K) + +open Classical in +theorem owners (i : Stack.Outer x y) (s : Cell h) (t : Fin u) : + (p.toPresentation.boundary (Stack.bit h u x y ((s, t), i))).val.1.1.1 = p.host (L.core i s) + := by + rw [Exterior.boundary_owner, p.vertex_eq, L.tip] + +include L in +open Classical in +/-- Count origins across all blocks of one host, including the empty +hosts reserved by the controller. -/ +theorem origins_bound (hu : 0 < u) (hg : G.Trivalent) + (tk : (Stack.start G h u).Tracks Q k) (v : B S.m) : + (origins p.toPresentation v).card ≤ 3 * k := by + by_cases hv : ∃ w, p.host w = v + · obtain ⟨w, rfl⟩ := hv + apply le_trans _ (L.origins hg hu tk w) + apply card_le_card + intro j hj + obtain ⟨_, s, t, ht⟩ := mem_filter.mp hj + rw [owners p L] at ht + exact mem_filter.mpr ⟨mem_univ _, s, p.host.injective ht⟩ + · suffices origins p.toPresentation v = ∅ by rw [this, card_empty]; omega + apply eq_empty_iff_forall_notMem.mpr + intro j hj + obtain ⟨_, s, t, ht⟩ := mem_filter.mp hj + rw [owners p L] at ht + exact hv ⟨_, ht⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- # Reading an exterior stack from the short fields of its host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail + +open Assembly Coloring +variable {F : Type} [Field F] {D : Dimensions} {S : Scheme F} {x y : Wire} + {G : Diagram F x y} (t : Assignment D S G) (hw : t.Fits) + +open Classical in +private def unitAt (a : Stack.Outer x y) (s : Packing.Cell D.h) (b : Fin D.b) := + t.pieces.equiv.symm (t.endpoint a s b) + +open Classical in +private theorem unitAt_pin (a : Stack.Outer x y) (s : Packing.Cell D.h) (b : Fin D.b) (k : Fin D.z) + : + (Exterior.ports t.post (((a, s), b), k)).val = join S t.rows D.z t.pieces.uniform (unitAt t a s + b, k) := by + apply t.pieces.slots.injective + rw [t.end_bit] + unfold Pieces.slots + simp only [Equiv.trans_apply, Equiv.symm_apply_apply, Equiv.prodCongr_apply, Prod.map, unitAt, + Equiv.apply_symm_apply] + +open Classical in +private theorem unitAt_loc (a : Stack.Outer x y) (s : Packing.Cell D.h) (b : Fin D.b) : + let j := unitAt t a s b + (j.1, j.2.1) = t.loc a s := by + have h := Exterior.ports_at t.post t.holders a s b ⟨0, D.zpos⟩ + rw [unitAt_pin] at h + exact congrArg (fun k => (k.1, k.2.1)) h + +open Classical in +private theorem unitAt_surj (q : units S t.rows D.z) (he : S.peer t.rows (unitSpan q) = none) : + ∃ j s b, unitAt t j s b = q := by + obtain ⟨⟨⟨⟨j, s⟩, b⟩, k⟩, h⟩ := + (Exterior.ports t.post).surjective (toOuter t.pieces.uniform ⟨q, he⟩ ⟨0, D.zpos⟩) + have hh := congrArg Subtype.val h + rw [unitAt_pin] at hh + exact ⟨j, s, b, congrArg Prod.fst ((join S t.rows D.z t.pieces.uniform).injective hh)⟩ + +variable (name : Stack.Outer x y ↪ (D.Names → Bool)) (data : Record S D.h D.d D.e) + (ht : Marked t.post.toPresentation name data t.lane) + +include ht in +open Classical in +private theorem unitAt_mark (a : Stack.Outer x y) (s : Packing.Cell D.h) (b : Fin D.b) : + let q := unitAt t a s b + S.peer t.rows (unitSpan q) = none ∧ + data.short (unitSpan q) = tag (t.lane q.1 a) s ∧ q.2.2.2.val = b.val ∧ + data.long q.1 (t.lane q.1 a) = name a := by + intro q + obtain ⟨v, _, hs, he, hv⟩ := ht a s + let z : Fin D.z := ⟨0, D.zpos⟩ + let u := Exterior.ports t.post (((a, s), b), z) + have hp : u.val = join S t.rows D.z t.pieces.uniform (q, z) := unitAt_pin t a s b z + have hv' : u.val.1 = v ∧ u.val.2.val = z.val + D.z * b.val := hv (finProdFinEquiv (b, z)) + have hu := u.property + rw [hp] at hv' hu + change unitSpan q = v ∧ z.val + D.z * q.2.2.2.val = z.val + D.z * b.val at hv' + rw [← hv'.1] at hs he + exact ⟨hu, hs, Nat.eq_of_mul_eq_mul_left D.zpos (Nat.add_left_cancel hv'.2), he⟩ + +variable (D S) + +open Classical in +/-- Indexes the meta by the coordinates of `(B S.h × slots (word S.ℓ)) ⊕ (Stub S × Short h d)`. -/ +abbrev Meta (S : Scheme F) (h d : ℕ) := + (B S.h × slots (word S.ℓ)) ⊕ (Stub S × Short h d) + +omit [Field F] in +open Classical in +theorem card_meta (h d : ℕ) : + Fintype.card (Meta S h d) = 2 ^ S.h * (S.ℓ + 2 ^ (S.k + S.e) * (d + h)) := by + simp only [Meta, Stub, Short, B, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + card_slots, wd_word, pow_add] + ring + +open Classical in +/-- The indexed operation `Control.decode _ (fun k => z (.inl (j, k)))`. -/ +def readLabel (z : Meta S D.h D.d → Bool) (j : B S.h) : B S.ℓ := + Control.decode _ (fun k => z (.inl (j, k))) + +open Classical in +/-- A local number encodes a stack only at an exterior span. -/ +def Found (z : Meta S D.h D.d → Bool) (j : B S.h) (k : Fin D.u) (v : D.Label) : Prop := + let P := S.decode (readLabel D S z j) + ∃ (h : Fintype.card (Parts.Unit P D.z) ≤ D.u) (q : Parts.Unit P D.z), + Parts.number P D.z h q = k ∧ P.peer q.1.1 q.1.2 = none ∧ + (fun a => z (.inr ((j, q.1), a))) = tag v.1 v.2.1 ∧ q.2.val = v.2.2.val + +open Classical in +/-- Maps the coordinate `k` to `if h : ∃ v, Found D S z j k v then some h.choose else none`. -/ +def readSource (z : Meta S D.h D.d → Bool) (j : B S.h) : D.Source := + fun k => if h : ∃ v, Found D S z j k v then some h.choose else none + +omit [Field F] in +open Classical in +private theorem found_iff (z : Meta S D.h D.d → Bool) (j : B S.h) (k : Fin D.u) (v : D.Label) : + readSource D S z j k = some v ↔ Found D S z j k v := by + unfold readSource + split + · rename_i h + rw [Option.some.injEq] + refine ⟨fun hv => hv ▸ h.choose_spec, fun hv => ?_⟩ + obtain ⟨h₁, q, hq, _, ht, he⟩ := h.choose_spec + obtain ⟨h₂, q', hq', _, ht', he'⟩ := hv + have := (Parts.number _ _ h₁).injective (hq'.trans hq.symm) + subst q' + obtain ⟨hc, hs⟩ := tag_injective (ht.symm.trans ht') + exact Prod.ext hc (Prod.ext hs (Fin.ext (he.symm.trans he'))) + · rename_i h + exact iff_of_false (by simp) (fun hv => h ⟨v, hv⟩) + +open Classical in +/-- Builds `View D S x y (S.format.pair (format S D.h D.d D.e)) (Meta S D.h D.d) where names` +with the specified `View`, `rows`, `short`, `long`. -/ +def view (name : Stack.Outer x y ↪ (D.Names → Bool)) : + View D S x y (S.format.pair (format S D.h D.d D.e)) (Meta S D.h D.d) where + names := name + rows := fun j => .inl (.inl j) + short := fun i => Sum.elim (fun q => .inl (.inl (i, .inr q))) + (fun q => .inl (.inr (.inl (locate i q.1, q.2)))) + long := fun i c j => .inl (.inr (.inr (i, c, j))) + pattern := readLabel D S + source := readSource D S + +variable {D S} + +open Classical in +private theorem readLabel_eq (i : B S.m) (j : B S.h) : + readLabel D S ((view D S name).record (t.rows, data) i) j = (t.rows i).2 j := + (Control.decode S.ℓ).apply_symm_apply ((t.rows i).2 j) + +open Classical in +private theorem found_data (i : B S.m) (j : B S.h) (k : Fin D.u) (v : D.Label) : + Found D S ((view D S name).record (t.rows, data) i) j k v ↔ + ∃ q : units S t.rows D.z, + (q.1, q.2.1) = (i, j) ∧ t.coordinate hw (t.pieces.equiv q) = k ∧ + S.peer t.rows (unitSpan q) = none ∧ data.short (unitSpan q) = tag v.1 v.2.1 ∧ + q.2.2.2.val = v.2.2.val := by + unfold Found + rw [readLabel_eq t name data] + constructor + · rintro ⟨h, q, hk, he, hz, hb⟩ + refine ⟨⟨i, j, q⟩, rfl, (t.coordinate_equiv hw _).trans hk, ?_, hz, hb⟩ + simp only [Scheme.peer, Scheme.pattern, unitSpan, he, Option.map_none] + · rintro ⟨⟨u, a, q⟩, hl, hk, he, hz, hb⟩ + obtain ⟨rfl, rfl⟩ := Prod.mk.inj hl + refine ⟨t.pieces.fits hw.room _ _, q, (t.coordinate_equiv hw _).symm.trans hk, ?_, hz, hb⟩ + simpa only [Scheme.peer, Scheme.pattern, unitSpan, Option.map_eq_none_iff] using he + +include ht in +open Classical in +theorem view_valid : (view D S name).Valid t hw (t.rows, data) := by + refine ⟨rfl, fun i => funext (readLabel_eq t name data i), ?_, ?_⟩ + · intro i j k c s b + change readSource D S _ j k = some (c, s, b) ↔ _ + rw [found_iff, found_data t hw name data] + constructor + · rintro ⟨q, hl, hk, hp, hz, hb⟩ + obtain ⟨a, s', b', rfl⟩ := unitAt_surj t q hp + obtain ⟨_, hz', hb', _⟩ := unitAt_mark t name data ht a s' b' + obtain ⟨hc, rfl⟩ := tag_injective (hz'.symm.trans hz) + have := Fin.ext (hb'.symm.trans hb) + subst b' + refine ⟨a, (unitAt_loc t a _ _).symm.trans hl, ?_, ?_⟩ + · exact (congrArg (fun q => t.lane q.1 a) hl.symm).trans hc + · simpa only [unitAt, Equiv.apply_symm_apply] using hk + · rintro ⟨a, hl, hc, hk⟩ + have he := (unitAt_loc t a s b).trans hl + obtain ⟨hp, hz, hb, _⟩ := unitAt_mark t name data ht a s b + refine ⟨unitAt t a s b, he, ?_, hp, ?_, hb⟩ + · simpa only [unitAt, Equiv.apply_symm_apply] using hk + · exact hz.trans (congrArg (fun c => tag c s) ((congrArg (fun q + => t.lane q.1 a) he).trans hc)) + · intro a s + let b : Fin D.b := ⟨0, D.bpos⟩ + have h := (unitAt_mark t name data ht a s b).2.2.2 + have he := congrArg Prod.fst (unitAt_loc t a s b) + change data.long (t.loc a s).1 (t.lane (t.loc a s).1 a) = name a + rw [← he] + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Trail +end + +/- # Exterior predecessor commands on canonical child addresses -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing History State.Board BatchDescent + +variable {F : Type} [Field F] (D : Template F) (a : ℕ) + +open scoped Classical in +/-- The quantity computed by `(Match.rowIndex D.scheme.m (D.scheme.h - a + 1) x).1`. -/ +def parent (x : B (D.size a)) := (Match.rowIndex D.scheme.m (D.scheme.h - a + 1) x).1 + +open scoped Classical in +/-- The quantity computed by `Format.vec 0 (.vec e (Trail.pointer D.scheme (D.scheme.d + 1)))`. -/ +abbrev Pointers (e : ℕ) := Format.vec 0 (.vec e (Trail.pointer D.scheme (D.scheme.d + 1))) + +namespace Branch +variable {D a} {P : Gadget F} {ha : a ≤ D.scheme.h} + {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} {hu : 0 < P.b * z} {hz : 0 < z} {e : ℕ} + (t : D.Branch P a ha b k cost Δ C z σ hu) + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (hc : Δ ≤ C) + (M : Book D.scheme P z hz) (room : (t.state hb).Room e) (cap : ℕ) + +open scoped Classical in +/-- The value specified by `(t.state hb).subround (t.assign hb hc M room cap) (D.parent a)`. -/ +abbrev move := (t.state hb).subround (t.assign hb hc M room cap) (D.parent a) + +open scoped Classical in +theorem move_agrees (h : t.Ready hb hc M room cap) : + (t.move hb hc M room cap).Agrees t.p.post.toPresentation h.posting.toPresentation := by + refine (t.state hb).subround_agrees _ _ ?_ h.emitted.lengths h.agrees + intro w + change D.parent a (Child.host t.p.post.host (D.scheme.h - a) (w.1.1, w.2)) = _ + rw [parent, Child.host_parts] + rfl + +open scoped Classical in +theorem commands_vacant (i : B (D.size a)) (j : B a) (hi : D.childLive a t.r i = false) : + (t.move hb hc M room cap).commands i j = fun _ _ => Trail.point D.scheme none := by + funext l + have hz' : l = 0 := Fin.eq_zero _ + subst l + have hv := (t.board hb).live_at M room cap hc (t.s.canonical_live hb t.i t.v) i j + exact (t.state hb).subround_vacant (t.assign hb hc M room cap) (D.parent a) (i, j, 0) + (fun h => Bool.noConfusion (hi.symm.trans (hv.mpr h))) + +variable {t hb hc M cap} {s : D.Branch P a ha b k cost Δ C z σ hu} + {rs : (s.state hb).Room e} {rt : (t.state hb).Room e} + +open scoped Classical in +theorem commands_eq (hs : s.Ready hb hc M rs cap) (ht : t.Ready hb hc M rt cap) + {v : Site (s.G.V × Cell a) (D.scheme.h - a)} {w : Site (t.G.V × Cell a) (D.scheme.h - a)} + (he : ((s.board hb).recenter v).look = ((t.board hb).recenter w).look) : + (s.move hb hc M rs cap).commands (Child.host s.p.post.host _ (v.1.1, v.2)) (cellIndex a v.1.2) = + (t.move hb hc M rt cap).commands (Child.host t.p.post.host _ (w.1.1, w.2)) (cellIndex a w.1.2) + := by + funext l + have hz' : l = 0 := Fin.eq_zero _ + subst l + have block : s.p.post.block = t.p.post.block := by + ext i : 1 + exact (s.p.block i).trans (t.p.block i).symm + have h := (agrees he).1.localPointers (le_refl 8) (s.assign hb hc M rs cap) + (t.assign hb hc M rt cap) hs.ranked ht.ranked (agrees he).2 block + exact ((s.state hb).subround_at _ (D.parent a) v).trans + (h.trans ((t.state hb).subround_at _ (D.parent a) w).symm) + +end Branch +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end + +/- # Simultaneous output of history labels and exterior predecessor commands -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +open Coloring Packing History Window BatchDescent + +variable {F : Type} [Field F] (D : Template F) {P : Gadget F} {a : ℕ} {ha : a ≤ D.scheme.h} + {b k : ℕ} {cost : ℝ} {Δ C z : ℕ} {σ : ℝ} {hu : 0 < P.b * z} {hz : 0 < z} {e : ℕ} + (hb : Fintype.card (Branches.Tag P) ≤ 2 ^ b) (hc : Δ ≤ C) + (M : Book D.scheme P z hz) (cap : ℕ) (K : Meter) {I : Type*} + (t : I → D.Branch P a ha b k cost Δ C z σ hu) + (room : ∀ i, ((t i).state hb).Room e) + +local notation "Y" => D.after a Δ C M e cap K +local notation "W" => D.Pointers e + +open scoped Classical in +theorem trace_net (ready : ∀ i, (t i).Ready hb hc M (room i) cap) : + ∃ table : Table F, wd table.1 + wd table.2.1 = D.issueWidth a b Δ C M e cap K W ∧ + ∀ {u v N l : ℕ} {L : Set (Table F)}, + 3 ≤ u → table ∈ L → D.issueWidth a b Δ C M e cap K W ≤ u → + Access F u L (D.scheme.m + D.scheme.d) v N → 2 ^ a * (Walks 8 D.scheme.d (D.WithCount a + b)).width ≤ v → + D.size a ≤ l → 2 ^ (Tile.radius D.scheme.d + ((D.scheme.h - a) + 1)) + ≤ l → 2 ^ (D.degree a Δ C) ≤ l → + Computes F u L (D.Headed a b Δ C) ((Y).format.pair (Trail.controls D.scheme (Y).scheme + (D.scheme.d + 1))) + (fun i => (t i).head hb) + (fun i => ((t i).output hb hc M (room i) cap K, ((t i).move hb hc M (room i) cap).commands)) + (fun _ => 1) (D.issueCost a b Δ C M e cap K W v N l) := + D.issue_net hb M cap K W hc t room ready (fun i => ((t i).move hb hc M (room i) cap).commands) + (fun _ _ => Trail.point D.scheme none) + (fun i j _ _ he => Branch.commands_eq (ready i) (ready j) he) + (fun i => (t i).commands_vacant hb hc M (room i) cap) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Transform.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Transform.lean new file mode 100644 index 0000000000..e22512b37e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BatchDescent/Transform.lean @@ -0,0 +1,979 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Nat.Log +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Tactic.Linarith +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortBack +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Packets +public import Mathlib.GroupTheory.Perm.ViaEmbedding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute + +/-! # Budget for packing calls with a common table label -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Label + +open Finset + +/-- Allow one enable bit per call. The rest of the address can encode +the shared label and the dictionary's enable bit. -/ +def cap (w a : ℕ) := (w / 2) / (1 + a) + +/-- The minimum of the quantities in `n (n / cap w a + 1)`. -/ +def blocks (w a n : ℕ) := min n (n / cap w a + 1) + +theorem cap_bound (w a : ℕ) : cap w a * (1 + a) ≤ w / 2 := Nat.div_mul_le_self _ _ + +theorem block_space {w a : ℕ} (hw : 64 ≤ w) (ha : a ≤ w / 4) (n : ℕ) : + n ≤ blocks w a n * cap w a := by + have hc : 0 < cap w a := Nat.div_pos (by omega) (by omega) + unfold blocks + rcases min_choice n (n / cap w a + 1) with h|h <;> rw [h] + · exact Nat.le_mul_of_pos_right _ hc + · rw [mul_comm]; exact (Nat.lt_mul_div_succ n hc).le + +private theorem block_cost {w a : ℕ} (hw : 64 ≤ w) (ha : a ≤ w / 4) (n : ℕ) : + w * blocks w a n ≤ 8 * ((1 + a) * n) + w := by + have h : w / 2 < (1 + a) * (cap w a + 1) := Nat.lt_mul_div_succ _ (by omega) + have h' : w ≤ 8 * ((1 + a) * cap w a) := by rw [mul_add, mul_one] at h; omega + calc + _ ≤ w * (n / cap w a + 1) := Nat.mul_le_mul_left _ (min_le_right _ _) + _ ≤ 8 * ((1 + a) * cap w a) * (n / cap w a) + w := by + rw [mul_add, mul_one] + exact Nat.add_le_add_right (Nat.mul_le_mul_right _ h') _ + _ ≤ _ := by + rw [mul_assoc, mul_assoc] + gcongr + exact Nat.mul_div_le _ _ + +theorem choose_rows {I : Type} [Fintype I] {w s : ℕ} (hw : 64 ≤ w) + (hI : Fintype.card I ≤ 2 ^ (w / 4)) (a n : I → ℕ) (ha : ∀ i, a i ≤ w / 4) + (hs : ∑ i, (1 + a i) * n i ≤ s) (hs' : s ≤ 2 ^ (2 * w - 1)) : + ∃ j : ℕ, w ≤ j ∧ j + 1 ≤ 2 * w ∧ (∑ i, blocks w (a i) (n i)) ≤ 2 ^ j ∧ + 2 ^ j * (1 + j) ≤ 40 * (s + w * 2 ^ w) := by + let R := ∑ i, blocks w (a i) (n i) + have ht : R ≤ s := le_trans (sum_le_sum fun i _ => + (min_le_left _ _).trans (Nat.le_mul_of_pos_left _ (by omega))) hs + have hc : w * R ≤ 8 * s + w * 2 ^ w := by + have h := sum_le_sum (s := univ) fun i _ => block_cost hw (ha i) (n i) + simp only [sum_add_distrib, ← mul_sum, sum_const, card_univ, nsmul_eq_mul, Nat.cast_id] at h + have hcard := hI.trans (Nat.pow_le_pow_right (by decide : 0 < 2) (show w / 4 ≤ w by omega)) + exact h.trans (Nat.add_le_add (Nat.mul_le_mul_left 8 hs) (by rw [mul_comm _ w]; gcongr)) + by_cases hR : R ≤ 2 ^ w + · refine ⟨w, le_rfl, by omega, hR, ?_⟩ + nlinarith [Nat.mul_le_mul_left (2 ^ w) (show 1 ≤ w by omega)] + let j := Nat.clog 2 R + have hlo : w < j := (Nat.lt_clog_iff_pow_lt (by decide)).mpr (lt_of_not_ge hR) + have hhi : j ≤ 2 * w - 1 := (Nat.clog_le_iff_le_pow (by decide)).mpr (ht.trans hs') + refine ⟨j, hlo.le, by omega, Nat.le_pow_clog (by decide) _, ?_⟩ + have hp : 2 ^ j ≤ 2 * R := by + have he : 2 ^ (j - 1) < R := (Nat.lt_clog_iff_pow_lt (by decide)).mp (by omega) + conv_lhs => rw [show j = (j - 1) + 1 by omega, pow_succ] + omega + calc + _ ≤ (2 * R) * (2 * w) := Nat.mul_le_mul hp (by omega) + _ ≤ _ := by nlinarith only [hc, Nat.zero_le s, Nat.zero_le (w * 2 ^ w)] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Label +end + +/- +# One dictionary for heterogeneous calls + +A row contains one table label and several argument tuples for that +same table. Unused positions contribute the scalar one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Label +open Finset Transcript + +variable {F X I R : Type} [Field F] [Fintype I] + +open Classical in +private theorem group [Fintype R] {w : ℕ} (hw : 64 ≤ w) (hI : Fintype.card I ≤ w / 4) + (k : (I → Bool) → F) (r : R → I → X) : + ∃ (f : (Fin (w / 2) → Bool) → F) + (q : Fin (blocks w (Fintype.card I) (Fintype.card R)) → Fin (w / 2) → X ⊕ Bool), + ∀ x : X → Bool, ∏ i, f (Sum.elim x id ∘ q i) = ∏ j, k (x ∘ r j) := by + let C := Fin (cap w (Fintype.card I)) + let B := Fin (blocks w (Fintype.card I) (Fintype.card R)) + let col : C × Option I ↪ Fin (w / 2) := (Function.Embedding.nonempty_of_card_le + (by simpa [C, add_comm] using cap_bound w (Fintype.card I))).some + let idx : R ↪ B × C := (Function.Embedding.nonempty_of_card_le + (by simpa [B, C] using block_space hw hI (Fintype.card R))).some + let taps (j : R) (i : Option I) : X ⊕ Bool := i.elim (.inr true) (fun t => .inl (r j t)) + let p := Function.extend idx taps (fun _ _ => .inr false) + let q (b : B) := Function.extend col (fun i => p (b, i.1) i.2) (fun _ => .inr false) + let f (y : Fin (w / 2) → Bool) := + ∏ c : C, if y (col (c, none)) then k (fun i => y (col (c, some i))) else 1 + refine ⟨f, q, fun x => ?_⟩ + let g (i : B × C) := if Sum.elim x id (p i none) + then k (fun j => Sum.elim x id (p i (some j))) else 1 + have he (b : B) : f (Sum.elim x id ∘ q b) = ∏ c, g (b, c) := by + simp only [f, q, Function.comp_apply, col.injective.extend_apply, g] + simp only [he] + rw [← Fintype.prod_prod_type g, ← prod_subset (subset_univ (univ.image idx))] + · rw [prod_image idx.injective.injOn] + simp [g, p, idx.injective.extend_apply, taps, Function.comp_def] + · intro i _ hi + have hn : ¬∃ j, idx j = i := by simpa using hi + simp [g, p, Function.extend_apply' _ _ _ hn] + +variable [Fintype X] {A B : I → Type} [∀ i, Fintype (A i)] [∀ i, Fintype (B i)] + +open Classical in +/-- The arity bound for the output can be chosen independently of the +labels. It suffices to admit all required sorting tables. -/ +theorem packed_calls {w u s : ℕ} (hw : 64 ≤ w) (hu : 3 ≤ u) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ u) + (hI : Fintype.card I ≤ 2 ^ (w / 4)) (hA : ∀ i, Fintype.card (A i) ≤ w / 4) + (hs : ∑ i, (1 + Fintype.card (A i)) * Fintype.card (B i) ≤ s) (hs' : s ≤ 2 ^ (2 * w - 1)) + (k : (i : I) → (A i → Bool) → F) (r : (i : I) → B i → A i → X) : + WideWeight F u (SortTables F w) (fun x => ∏ i, ∏ j, k i (x ∘ r i j)) + (4 * Fintype.card X + 440000 * (s + w * 2 ^ w)) := by + obtain ⟨j, hj, hj', hrows, hcost⟩ := choose_rows hw hI _ _ hA hs hs' + choose f t ht using fun i => group hw (hA i) (k i) (r i) + let R := Σ i, Fin (blocks w (Fintype.card (A i)) (Fintype.card (B i))) + let Y := Fin (w / 4) ⊕ Fin (w / 2) + let name : I ↪ (Fin (w / 4) → Bool) := (Function.Embedding.nonempty_of_card_le (by simpa using + hI)).some + let F₀ (y : Y → Bool) := Function.extend name f (fun _ _ => 1) (y ∘ Sum.inl) (y ∘ Sum.inr) + let read (a : R) : Y → X ⊕ Bool := Sum.elim (Sum.inr ∘ name a.1) (t a.1 a.2) + have he (x : X → Bool) (a : R) : F₀ (Sum.elim x id ∘ read a) = + f a.1 (Sum.elim x id ∘ t a.1 a.2) := by + change Function.extend name f _ (name a.1) _ = _ + rw [name.injective.extend_apply] + rfl + have hu' : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ u := by + refine le_trans ?_ ha + exact Nat.mul_le_mul (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide) hj')) (by omega) + have h := dictionary hj hj' hu hu' (by simp [Y]; omega) (by simpa [R] using hrows) F₀ read + intro a e + obtain ⟨n, hn, h⟩ := h a e + refine ⟨n, by rw [mul_assoc] at hn; omega, ?_⟩ + have eq (x : X → Bool) : (∏ i : R, F₀ (Sum.elim x id ∘ read i)) = ∏ i, ∏ j, k i (x ∘ r i j) := by + simp only [he, R, Fintype.prod_sigma, ht] + simpa only [eq] using h + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Label +end + +/- # Reading labeled gates on a common tape -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Label +open Finset Transcript Install Processor + +variable {F V X : Type} [Field F] [Fintype V] [Fintype X] + +open Classical in +/-- Computes the args by the application `Wire.pair T.1 T.2.1`. -/ +abbrev args (T : Table F) := Wire.pair T.1 T.2.1 + +open Classical in +/-- Computes the apply table by the application `T.2.2 x.1 x.2`. -/ +def applyTable (T : Table F) (x : Val (args T)) : F := T.2.2 x.1 x.2 + +open Classical in +/-- Computes the table bits by the application `applyTable T ((bits (args T)).symm x)`. -/ +def tableBits (T : Table F) (x : slots (args T) → Bool) : F := + applyTable T ((bits (args T)).symm x) + +open Classical in +theorem bend {u : ℕ} {M : Set (Table F)} (hu : 3 ≤ u) (T : Table F) + (ht : arity T ≤ u) (hk : arity T ≤ 3 ∨ T ∈ M) : + ∃ s ≤ 9 * (1 + arity T), Wide F u M (args T) .unit (fun x _ => applyTable T x) s := by + obtain ⟨a, b, k⟩ := T + let v := Wide.table a b k ht hk + obtain ⟨m, hm, l⟩ := DNet.id F b + obtain ⟨n, hn, l⟩ := l.includeWide (L := M) hu + obtain ⟨p, hp, r⟩ := (Tagged.cap (F := F) b).includeWide (L := M) hu + have h := (v.par l).comp r + refine ⟨1 + (wd a + wd b) + n + p, by unfold arity; dsimp; omega, ?_⟩ + convert h using 1 + funext x _ + change k x.1 x.2 = ∑ y : Val b × Val b, + (k x.1 y.1 * if x.2 = y.2 then 1 else 0) * if y.1 = y.2 then 1 else 0 + simp [Fintype.sum_prod_type, mul_ite] + +variable (T : V → Table F) (L : Finset (Table F)) + +open Classical in +private def regroup : (Σ t : ↥L, {v // T v = t.val}) ≃ {v // T v ∈ L} where + toFun x := ⟨x.2.val, x.2.property.symm ▸ x.1.property⟩ + invFun x := ⟨⟨T x.val, x.property⟩, ⟨x.val, rfl⟩⟩ + left_inv := by rintro ⟨⟨t, ht⟩, ⟨v, h⟩⟩; change T v = t at h; subst t; rfl + right_inv _ := rfl + +open Classical in +/-- Replace just the labeled factors by one dictionary. -/ +theorem tape {w u s : ℕ} (hw : 64 ≤ w) (hu : 3 ≤ u) (ha : 2 * 2 ^ (2 * w) * (4 * w) ≤ u) + (hL : L.card ≤ 2 ^ (w / 4)) (ht : ∀ t ∈ L, arity t ≤ w / 4) + (hs : ∑ v, (1 + arity (T v)) ≤ s) (hs' : s ≤ 2 ^ (2 * w - 1)) + (r : ∀ v, slots (args (T v)) → X) : + WideWeight F u (SortTables F w) (fun x => ∏ v : {v // T v ∈ L}, tableBits (T v) (x ∘ r v)) + (4 * Fintype.card X + 440000 * (s + w * 2 ^ w)) := by + let A (t : ↥L) := slots (args t.val) + let B (t : ↥L) := {v // T v = t.val} + let read (t : ↥L) (v : B t) : A t → X := cast (congrArg (fun t + => slots (args t) → X) v.property) (r v.val) + have card (t : ↥L) : Fintype.card (A t) = arity t.val := card_slots _ + have cost : ∑ t, (1 + Fintype.card (A t)) * Fintype.card (B t) ≤ s := by + have h := Fintype.sum_subtype_add_sum_subtype (fun v => T v ∈ L) (fun v => 1 + arity (T v)) + have h' : (∑ v : {v // T v ∈ L}, (1 + arity (T v))) ≤ s + := (Nat.le_add_right _ _).trans (h.le.trans hs) + rw [← (regroup T L).sum_comp, Fintype.sum_sigma] at h' + refine le_trans ?_ h' + apply sum_le_sum + intro t _ + have he (v : B t) : T ((regroup T L ⟨t, v⟩).val) = t.val := v.property + simp [he, card, B, mul_comm] + have H := packed_calls hw hu ha (by simpa using hL) (fun t => by rw [card]; exact ht _ t.property) + cost hs' (fun t => tableBits t.val) read + convert H using 1 + funext x + rw [← (regroup T L).prod_comp, Fintype.prod_sigma] + apply prod_congr rfl + intro t _ + apply prod_congr rfl + intro v _ + obtain ⟨t, ht⟩ := t + obtain ⟨v, hv⟩ := v + change T v = t at hv + subst t + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Label +end + +/- +# Applying small dictionaries with many output bits + +Guess the output bits and check each complete answer with one scalar +dictionary call. The tape then has a unique extension, so the output +can feed a second weighted computation without a multiplicity factor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +open Transcript Install + +variable {F I J X Y R : Type} [Field F] [Fintype I] [Fintype J] [Fintype X] [Fintype Y] + [Fintype R] {w j u m n : ℕ} + +variable (f : (I → Bool) → J → Bool) (input : R → I → X ⊕ Bool) (output : R × J ≃ Y) + +open Classical in +/-- The apply rows of type `Bool`, constructed using `output.symm y`. -/ +def applyRows (x : X → Bool) (y : Y) : Bool := + let z := output.symm y + f (Sum.elim x id ∘ input z.1) z.2 + +open Classical in +theorem transform (hj : w ≤ j) (hj' : j + 1 ≤ 2 * w) + (hu : 3 ≤ u) (ha : 2 * 2 ^ (j + 1) * (2 * j + 2) ≤ u) + (hI : Fintype.card I + Fintype.card J < j) (hR : Fintype.card R ≤ 2 ^ j) : + WideWeight F u (SortTables F w) + (fun x : X ⊕ Y → Bool => if applyRows f input output (x ∘ Sum.inl) + = x ∘ Sum.inr then 1 else 0) + (4 * Fintype.card (X ⊕ Y) + 11000 * 2 ^ j * (1 + j)) := by + let k (v : I ⊕ J → Bool) : F := if f (v ∘ Sum.inl) = v ∘ Sum.inr then 1 else 0 + let r (p : R) : I ⊕ J → (X ⊕ Y) ⊕ Bool := + Sum.elim (fun i => Sum.map Sum.inl id (input p i)) (fun t => .inl (.inr (output (p, t)))) + have H := dictionary hj hj' hu ha (by simpa using hI) hR k r + convert H using 1 + funext x + have hk (p) : k (Sum.elim x id ∘ r p) = + if ∀ t, applyRows f input output (x ∘ Sum.inl) (output (p, t)) = x (.inr (output (p, t))) + then 1 else 0 := by + have e : (Sum.elim x id ∘ r p) ∘ Sum.inl = Sum.elim (x ∘ Sum.inl) id ∘ input p := by + funext t + simp only [Function.comp_apply, r, Sum.elim_inl] + cases input p t <;> rfl + simp only [k, e, funext_iff, applyRows, Equiv.symm_apply_apply] + rfl + simp_rw [hk] + by_cases he : applyRows f input output (x ∘ Sum.inl) = x ∘ Sum.inr + · simp [he] + · rw [ite_eq_right he, eq_comm] + obtain ⟨y, hy⟩ := Function.ne_iff.mp he + obtain ⟨⟨p, t⟩, rfl⟩ := output.surjective y + exact Finset.prod_eq_zero (Finset.mem_univ p) (ite_eq_right (fun h => hy (h t))) + +open Classical in +/-- Existentially hide the unique output tape after weighting it. -/ +theorem bind {L : Set (Table F)} {f : (X → Bool) → Y → Bool} {k : (X ⊕ Y → Bool) → F} + (hu : 3 ≤ u) + (hf : WideWeight F u L (fun x => if f (x ∘ Sum.inl) = x ∘ Sum.inr then 1 else 0) m) + (hk : WideWeight F u L k n) : + WideWeight F u L (fun x => k (Sum.elim x (f x))) + (8 * (Fintype.card X + Fintype.card Y) + 9 * (m + n)) := by + let test (x : X ⊕ Y → Bool) : F := if f (x ∘ Sum.inl) = x ∘ Sum.inr then 1 else 0 + let jobs (b : Bool) := if b then test else k + let costs (b : Bool) := if b then m else n + have ready (b : Bool) : WideWeight F u L (jobs b) (costs b) := by + cases b + · exact hk + · exact hf + have H := wide_sum jobs (fun _ => id) costs hu ready + convert H using 1 + · funext x + simp only [weightedSum, jobs, test, Function.comp_def, Fintype.prod_bool, + Bool.false_eq_true, ite_true, ite_false] + change k (Sum.elim x (f x)) = ∑ y, (if f x = y then 1 else 0) * k (Sum.elim x y) + simp [ite_mul] + · simp [costs] + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Packet matching with two permitted long sorts + +Compare the sorted list before and after reversing active directions. +No distinctness test is needed for the inactive records. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Transcript Messages Install + +variable (F : Type) [Field F] {X : Type} [Fintype X] {w j u H z : ℕ} + +open scoped Classical in +/-- Lists the values in order of their bounded index. -/ +def packetRows (tap : Fin (2 ^ j) → slots (Messages.row H z) → X ⊕ Bool) (x : X → Bool) := + List.ofFn (fun i => (bits (Messages.row H z)).symm (Sum.elim x id ∘ tap i)) + +open scoped Classical in +/-- Requires `(l.map (reverse H z)).Perm l`. -/ +def paired (l : List (Val (Messages.row H z))) : Prop := (l.map (reverse H z)).Perm l + +open scoped Classical in +theorem sorted_iff {a : Wire} [LinearOrder (Val a)] (x y : Val (tree j a)) : + sortTree j x = sortTree j y ↔ (flatten j y).Perm (flatten j x) := by + constructor + · intro h; exact (sortTree_perm j y).symm.trans (h ▸ sortTree_perm j x) + · intro h + exact Tagged.unique_sort j y (sortTree j x) ((sortTree_perm ..).trans h.symm) (sortTree_sorted + ..) + +open scoped Classical in +theorem packet_with {G : Set (Table F)} + (admitSort : ∀ (_ : LinearOrder (Val (Messages.row H z))), + Fast F (Messages.row H z) → sorter F (Messages.row H z) j ∈ G) + (hu : 3 ≤ u) + (ha : 2 * 2 ^ j * (H + z + 2) ≤ u) (hh : H + z + 2 ≤ 4 * w) + (tap : Fin (2 ^ j) → slots (Messages.row H z) → X ⊕ Bool) : + WideWeight F u G (fun x => if paired (packetRows tap x) then 1 else 0) + (4 * Fintype.card X + 1000 * 2 ^ j * (1 + w)) := by + let a := Messages.row H z + let b := tree j a + have hw : wd a = H + z + 2 := wd_word _ + obtain ⟨o, ho⟩ := Tagged.exists_comparator F a + let _ := o + have hf : Fast F a := ho.mono (by omega) + have hsort : DWide F u G b b (sortTree j) (1 + 2 * 2 ^ j * wd a) := by + rw [← arity_sorter F a j] + refine ⟨_, le_rfl, Wide.table _ _ _ ?_ (.inr (admitSort o hf))⟩ + change Processor.arity (sorter F a j) ≤ u + rw [arity_sorter, hw] + exact ha + obtain ⟨L, hL⟩ := Layout.exists_tree a j + let f := Function.uncurry tap + intro c e + have read := (tap_depends f).bnet F c b e L.positions + have prep := (DNet.id F b).pair (Tagged.mapRows_net (reverse_net F H z) j) + obtain ⟨m, hm, h⟩ := (DWide.of_dnet hu (read.comp prep)).comp (hsort.par hsort) + obtain ⟨n, hn, cap⟩ := (Tagged.cap (F := F) b).includeWide (L := G) hu + refine ⟨m + n, ?_, ?_⟩ + · simp only [b, wd_tree, hw, Fintype.card_prod, Fintype.card_fin, localCost] at hm hn + rw [MatrixExponent.card_slots, wd_word] at hm + have hk := Nat.mul_le_mul_left (2 ^ j) hh + have := Nat.two_pow_pos j + ring_nf at hm hn hk ⊢ + omega + · have hc := h.comp cap + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] at hc + convert hc using 1 + funext x _ + let y := (bits b).symm (Sum.elim (bits c x ∘ e) id ∘ f ∘ L.positions.symm) + have hy : flatten j y = packetRows tap (bits c x ∘ e) := by + rw [← hL] + unfold packetRows + congr 1 + funext i + simp only [Layout.read, y, b, Equiv.apply_symm_apply, Function.comp_apply, + Equiv.symm_apply_apply] + rfl + change (if paired _ then (1 : F) else 0) = + if sortTree j y = sortTree j (Tagged.mapRows (reverse H z) j y) then 1 else 0 + simp only [sorted_iff, Tagged.flatten_mapRows, hy, paired] + split <;> simp_all + +open scoped Classical in +theorem packet (hj : w ≤ j) (hj' : j ≤ 2 * w) (hu : 3 ≤ u) + (ha : 2 * 2 ^ j * (H + z + 2) ≤ u) (hl : w ≤ H + z + 2) (hh : H + z + 2 ≤ 4 * w) + (tap : Fin (2 ^ j) → slots (Messages.row H z) → X ⊕ Bool) : + WideWeight F u (SortTables F w) (fun x => if paired (packetRows tap x) then 1 else 0) + (4 * Fintype.card X + 1000 * 2 ^ j * (1 + w)) := by + apply packet_with F _ hu ha hh tap + intro o hf + have hw : wd (Messages.row H z) = H + z + 2 := wd_word _ + exact ⟨j, Messages.row H z, o, hf, hj, hj', hw.ge.trans' hl, hw.le.trans hh, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # A packet plan may have repeated inactive headers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Transcript.Messages + +open scoped Classical in +/-- The data for the packet plan construction, including `head`, `peer`, `inactive`, `pairs`, +`unique`. -/ +structure PacketPlan (I : Type) (H : ℕ) where + /-- The `PacketPlan` component of type `I → Val (word (H + 2))`. -/ + head : I → Val (word (H + 2)) + /-- The `PacketPlan` component of type `Equiv.Perm I`. -/ + peer : Equiv.Perm I + inactive : ∀ i, (head i).1 = false → peer i = i + pairs : ∀ i, head (peer i) = opposite (head i) + unique : ∀ i k, (head i).1 = true → head i = head k → i = k + +namespace PacketPlan +variable {I : Type} {H z j : ℕ} (p : PacketPlan I H) (e : I ↪ Fin (2 ^ j)) + (v : I → Val (word z)) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def packed : Fin (2 ^ j) → Val (row H z) := + Function.extend e (fun i => assemble (p.head i) (v i)) (fun _ => Lookup.zero _) + +open scoped Classical in +@[simp] theorem packed_apply (i : I) : p.packed e v (e i) = assemble (p.head i) (v i) := + e.injective.extend_apply _ _ _ + +open scoped Classical in +theorem packed_other (i : Fin (2 ^ j)) (hi : i ∉ Set.range e) : + p.packed e v i = Lookup.zero _ := + Function.extend_apply' _ _ _ hi + +open scoped Classical in +/-- The long-sort test now checks exactly one equality of payloads per +active pair. Padded positions and inactive records require no pairing. -/ +theorem matching : paired (List.ofFn (p.packed e v)) ↔ + ∀ i, (p.head i).1 = true → v (p.peer i) = v i := by + unfold paired + constructor + · intro hs i hi + have hh : reverse H z (p.packed e v (e i)) ∈ List.ofFn (p.packed e v) := + hs.subset (List.mem_map_of_mem (List.mem_ofFn.mpr ⟨_, rfl⟩)) + obtain ⟨k, hk⟩ := List.mem_ofFn.mp hh + rw [packed_apply, reverse_assemble, ← p.pairs] at hk + have hp : (p.head (p.peer i)).1 = true := by rw [p.pairs]; exact hi + by_cases he : k ∈ Set.range e + · obtain ⟨l, rfl⟩ := he + rw [packed_apply] at hk + have he := congrArg (header H z) hk + simp only [header_assemble] at he + have := p.unique _ _ hp he.symm + subst l + exact assemble_injective _ hk + · rw [packed_other _ _ _ _ he] at hk + have h := congrArg Prod.fst hk + change false = (p.head (p.peer i)).1 at h + rw [hp] at h + contradiction + · intro h + rw [List.map_ofFn] + have he : reverse H z ∘ p.packed e v = p.packed e v ∘ p.peer.viaEmbedding e := by + funext k + simp only [Function.comp_apply] + by_cases hk : k ∈ Set.range e + · obtain ⟨i, rfl⟩ := hk + rw [Equiv.Perm.viaEmbedding_apply, packed_apply, packed_apply, reverse_assemble, ← p.pairs] + cases hi : (p.head i).1 + · rw [p.inactive i hi] + · rw [h i hi] + · rw [Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ hk, packed_other _ _ _ _ hk] + rfl + rw [he] + exact Equiv.Perm.ofFn_comp_perm _ _ + +end PacketPlan +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Hardwired packet layouts for a partial batch -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Transcript Transcript.Messages + +variable {X I : Type} {H z : ℕ} + +open scoped Classical in +/-- In the case `0, _, a`, this construction gives `a`. -/ +def appendTap (H : ℕ) : (z : ℕ) → + (slots (word z) → X) → (slots (word H) → X) → slots (word (H + z)) → X + | 0, _, a => a + | z + 1, b, a => Sum.elim (b ∘ Sum.inl) (appendTap H z (b ∘ Sum.inr) a) + +open scoped Classical in +private theorem decode_append (x : X → Bool) (a : slots (word H) → X) + (b : slots (word z) → X) : + (bits (word (H + z))).symm (x ∘ appendTap H z b a) = + appendWord H z ((bits (word z)).symm (x ∘ b)) ((bits (word H)).symm (x ∘ a)) := by + induction z with + | zero => rfl + | succ z ih => exact Prod.ext rfl (ih _) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def joinTap (a : slots (word (H + 2)) → X) (b : slots (word z) → X) : + slots (row H z) → X := + Sum.elim (a ∘ Sum.inl) (Sum.elim (a ∘ Sum.inr ∘ Sum.inl) + (appendTap H z b (a ∘ Sum.inr ∘ Sum.inr))) + +open scoped Classical in +theorem decode_join (x : X → Bool) (a : slots (word (H + 2)) → X) + (b : slots (word z) → X) : + (bits (row H z)).symm (x ∘ joinTap a b) = + assemble ((bits (word (H + 2))).symm (x ∘ a)) ((bits (word z)).symm (x ∘ b)) := + Prod.ext rfl (Prod.ext rfl (decode_append x _ b)) + +open scoped Classical in +/-- The tensor is fixed before the headers are known. The semantic +description only requires well-formedness on inputs where it is used. -/ +theorem packet_plan_with (F : Type) [Field F] [Fintype X] [Fintype I] {w j u : ℕ} + {G : Set (Table F)} + (admitSort : ∀ (_ : LinearOrder (Val (row H z))), Fast F (row H z) → sorter F (row H z) j ∈ G) + (hu : 3 ≤ u) + (ha : 2 * 2 ^ j * (H + z + 2) ≤ u) (hh : H + z + 2 ≤ 4 * w) + (hi : Fintype.card I ≤ 2 ^ j) + (head : I → slots (word (H + 2)) → X ⊕ Bool) (body : I → slots (word z) → X ⊕ Bool) : + ∃ f : (X → Bool) → F, WideWeight F u G f + (4 * Fintype.card X + 1000 * 2 ^ j * (1 + w)) ∧ + ∀ (x : X → Bool) (p : PacketPlan I H), + (∀ i, bits (word (H + 2)) (p.head i) = Sum.elim x id ∘ head i) → + f x = if ∀ i, (p.head i).1 = true → + Sum.elim x id ∘ body (p.peer i) = Sum.elim x id ∘ body i then 1 else 0 := by + let e : I ↪ Fin (2 ^ j) := (Function.Embedding.nonempty_of_card_le (by simpa using hi)).some + let tap := Function.extend e (fun i => joinTap (head i) (body i)) + (fun _ => Sum.inr ∘ bits (row H z) (Lookup.zero _)) + refine ⟨_, packet_with F admitSort hu ha hh tap, ?_⟩ + intro x p hp + let v := fun i => (bits (word z)).symm (Sum.elim x id ∘ body i) + have eq : packetRows tap x = List.ofFn (p.packed e v) := by + unfold packetRows + congr 1 + funext i + by_cases hi : i ∈ Set.range e + · obtain ⟨k, rfl⟩ := hi + simp only [tap, e.injective.extend_apply, PacketPlan.packed_apply] + rw [decode_join, ← hp, Equiv.symm_apply_apply] + · rw [p.packed_other _ _ _ hi] + unfold tap + rw [Function.extend_apply' _ _ _ hi] + exact (bits (row H z)).symm_apply_apply _ + simp only [eq, p.matching, v, Equiv.symm_apply_eq, Equiv.apply_symm_apply] + +open scoped Classical in +theorem packet_plan (F : Type) [Field F] [Fintype X] [Fintype I] {w j u : ℕ} + (hj : w ≤ j) (hj' : j ≤ 2 * w) (hu : 3 ≤ u) + (ha : 2 * 2 ^ j * (H + z + 2) ≤ u) (hl : w ≤ H + z + 2) (hh : H + z + 2 ≤ 4 * w) + (hi : Fintype.card I ≤ 2 ^ j) + (head : I → slots (word (H + 2)) → X ⊕ Bool) (body : I → slots (word z) → X ⊕ Bool) : + ∃ f : (X → Bool) → F, WideWeight F u (SortTables F w) f + (4 * Fintype.card X + 1000 * 2 ^ j * (1 + w)) ∧ + ∀ (x : X → Bool) (p : PacketPlan I H), + (∀ i, bits (word (H + 2)) (p.head i) = Sum.elim x id ∘ head i) → + f x = if ∀ i, (p.head i).1 = true → + Sum.elim x id ∘ body (p.peer i) = Sum.elim x id ∘ body i then 1 else 0 := by + apply packet_plan_with F _ hu ha hh hi head body + intro o hf + have hw : wd (Messages.row H z) = H + z + 2 := wd_word _ + exact ⟨j, row H z, o, hf, hj, hj', hw.ge.trans' hl, hw.le.trans hh, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- # Pairing and padding bit positions on a shared row tape -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +variable {I : Type} {H : ℕ} + +open Classical in +theorem PacketPlan.square (a : PacketPlan I H) (i : I) : a.peer (a.peer i) = i := by + by_cases h : (a.head i).1 = true + · symm + apply a.unique _ _ h + rw [a.pairs, a.pairs] + simpa [Transcript.Messages.opposite, h] using + (Prod.ext h rfl : a.head i = (true, (a.head i).2)) + · rw [a.inactive _ (Bool.eq_false_iff.mpr h), a.inactive _ (Bool.eq_false_iff.mpr h)] + +namespace Links + +open Classical in +/-- The condition `∀ i, i ∉ Set.range f → x i = false` on the specified data. -/ +def pad {A B : Type} (f : A ↪ B) (x : B → Bool) : Prop := + ∀ i, i ∉ Set.range f → x i = false + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def put {A B : Type} (f : A ↪ B) (x : A → Bool) : B → Bool := + Function.extend f x (fun _ => false) + +open Classical in +theorem read_put {A B : Type} (f : A ↪ B) (x : A → Bool) : put f x ∘ f = x := + funext fun i => f.injective.extend_apply x (fun _ => false) i + +open Classical in +theorem padded {A B : Type} (f : A ↪ B) (x : A → Bool) : pad f (put f x) := + fun _ h => Function.extend_apply' _ _ _ h + +open Classical in +theorem put_read {A B : Type} (f : A ↪ B) {x : B → Bool} (hx : pad f x) : + put f (x ∘ f) = x := by + funext i + by_cases h : i ∈ Set.range f + · obtain ⟨k, rfl⟩ := h + exact congrFun (read_put f _) k + · exact ((padded f _) _ h).trans (hx _ h).symm + +end Links +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end + +/- +# Naming whole rows by signed identifiers + +Several pins can share one header. It suffices that equality of signed +identifiers coincide with equality of rows. Every live row then has a +unique opposite row, even if the unused headers are all identical. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Links + +variable {A B K : Type} {H : ℕ} + +open Classical in +/-- The value specified by `(!x.1, x.2)`. -/ +def flipped (x : Bool × K) := (!x.1, x.2) + +open Classical in +private theorem flip_twice (x : Bool × K) : flipped (flipped x) = x := by simp [flipped] + +variable (place : A → B) (key : A → Bool × K) (code : K ↪ Val (word H)) + +open Classical in +/-- Returns `(true, (key h.choose).1, code (key h.choose).2)` when `h : ∃ x, place x = i` holds, +and `(false, false, Lookup.zero H)` otherwise. -/ +def header (i : B) : Val (word (H + 2)) := + if h : ∃ x, place x = i then (true, (key h.choose).1, code (key h.choose).2) + else (false, false, Lookup.zero H) + +open Classical in +theorem header_at (he : ∀ i j, key i = key j ↔ place i = place j) (p : A) : + header place key code (place p) = (true, (key p).1, code (key p).2) := by + have hp : ∃ x, place x = place p := ⟨p, rfl⟩ + rw [header, dite_eq_left hp, (he _ _).mpr hp.choose_spec] + +open Classical in +theorem header_other (i : B) (h : i ∉ Set.range place) : + header place key code i = (false, false, Lookup.zero H) := dite_eq_right h + +open Classical in +theorem build_packet (he : ∀ i j, key i = key j ↔ place i = place j) + (hp : ∀ x, ∃ y, key y = flipped (key x)) : + ∃ p : PacketPlan B H, p.head = header place key code ∧ + ∀ x y, key y = flipped (key x) → p.peer (place x) = place y := by + choose mate hm using hp + let f (i : B) := if h : ∃ x, place x = i then place (mate h.choose) else i + have route (x y : A) (h : key y = flipped (key x)) : f (place x) = place y := by + have hh : ∃ a, place a = place x := ⟨x, rfl⟩ + unfold f + rw [dite_eq_left hh, ← he, hm, (he _ _).mpr hh.choose_spec, h] + have off (i : B) (hi : i ∉ Set.range place) : f i = i := dite_eq_right hi + have inv : Function.Involutive f := by + intro i + by_cases hi : i ∈ Set.range place + · obtain ⟨x, rfl⟩ := hi + rw [route x (mate x) (hm x)] + exact route _ x (by rw [hm, flip_twice]) + · rw [off i hi, off i hi] + refine ⟨⟨header place key code, inv.toPerm, ?_, ?_, ?_⟩, rfl, route⟩ + · intro i hi + apply off + rintro ⟨x, rfl⟩ + rw [header_at _ _ _ he] at hi + cases hi + · intro i + change header _ _ _ (f i) = _ + by_cases hi : i ∈ Set.range place + · obtain ⟨x, rfl⟩ := hi + rw [route x (mate x) (hm x), header_at _ _ _ he, header_at _ _ _ he, hm] + rfl + · rw [off i hi, header_other _ _ _ _ hi] + rfl + · intro i j hi hj + have live (i : B) (hi : (header place key code i).1 = true) : i ∈ Set.range place := by + by_contra hn + rw [header_other _ _ _ _ hn] at hi + cases hi + obtain ⟨x, rfl⟩ := live i hi + obtain ⟨y, rfl⟩ := live j (hj ▸ hi) + rw [header_at _ _ _ he, header_at _ _ _ he] at hj + obtain ⟨hd, heq⟩ := Prod.mk.inj (Prod.mk.inj hj).2 + exact (he x y).mp (Prod.ext hd (code.injective heq)) + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent.Links +end + +/- +# Routing arbitrarily wide records by short sorts + +Repeat the same permutation test with successive slices of the payload. +Each test compares two sorted arrays of pairs. Source addresses are +constants, and all the tests share a single array of target addresses. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.BatchDescent + +open Assembly Coloring Install Transcript + +variable (F : Type) [Field F] {w j u m : ℕ} + +open scoped Classical in +private abbrev RowFromExchange (j m : ℕ) := Wire.pair (word j) (word m) + +open scoped Classical in +private def taps : (B j × slots (RowFromExchange j m)) ⊕ (B j × slots (RowFromExchange j m)) → + PermBus j m ⊕ Bool + | .inl (i, .inl p) => .inr ((Control.decode j).symm i p) + | .inl (i, .inr p) => .inl (.inl (i, p)) + | .inr p => .inl (.inr p) + +open scoped Classical in +private theorem taps_perm (L : Layout (RowFromExchange j m) (tree j (RowFromExchange j m)) (B j)) + (hL : ∀ x, List.ofFn (L.read x) = flatten j x) (z : PermBus j m → Bool) : + let e := L.positions.sumCongr L.positions + let b := tree j (RowFromExchange j m) + let x := (bits (.pair b b)).symm (Sum.elim z id ∘ taps ∘ e.symm) + (flatten j x.2).Perm (flatten j x.1) ↔ PermBus.valid z := by + intro e b x + let n := (Control.index j).symm + let s i := (bits (word m)).symm (fun p => z (.inl (i, p))) + let t i := (bits (word m)).symm (fun p => z (.inr (i, .inr p))) + let a := n ∘ PermBus.address z + have he (i : B j) (r : slots (RowFromExchange j m)) : + bits (RowFromExchange j m) (L.read x.1 i) r = Sum.elim z id (taps (.inl (i, r))) ∧ + bits (RowFromExchange j m) (L.read x.2 i) r = Sum.elim z id (taps (.inr (i, r))) := by + simp only [Layout.read, Equiv.apply_symm_apply] + change bits (.pair b b) x (e (.inl (i, r))) = _ ∧ bits (.pair b b) x (e (.inr (i, r))) = _ + simp [x] + have h₁ : L.read x.1 = fun i => (n i, s i) := by + funext i + apply (bits (RowFromExchange j m)).injective + funext r + rw [(he i r).1] + cases r with + | inl p => rfl + | inr p => exact (congrFun ((bits (word m)).apply_symm_apply (fun r => z (.inl (i, r)))) p).symm + have h₂ : L.read x.2 = fun i => (a i, t i) := by + funext i + apply (bits (RowFromExchange j m)).injective + funext r + rw [(he i r).2] + cases r with + | inl p => exact (congrFun ((Control.decode j).symm_apply_apply (fun r => z (.inr (i, + .inl r)))) p).symm + | inr p => exact (congrFun ((bits (word m)).apply_symm_apply (fun r => z (.inr (i, + .inr r)))) p).symm + have ha : Function.Bijective a ↔ Function.Bijective (PermBus.address z) := by + constructor + · intro h + simpa only [a, Function.comp_def, Equiv.symm_apply_apply] using n.symm.bijective.comp h + · exact n.bijective.comp + rw [← hL, ← hL, h₁, h₂, labeled_perm, ha] + simp only [a, s, t, Function.comp_apply, Equiv.symm_apply_apply, + (bits (word m)).symm.injective.eq_iff, funext_iff, PermBus.valid] + +open scoped Classical in +private theorem slice_weight (hu : 3 ≤ u) (hl : w ≤ j) (hr : j ≤ 2 * w) + (ha : 2 * 2 ^ j * (4 * w) ≤ u) (hm : m ≤ w) : + WideWeight F u (SortTables F w) + (fun z : PermBus j m → Bool => if PermBus.valid z then 1 else 0) + (2000 * 2 ^ j * (w + 1)) := by + let a := RowFromExchange j m + let b := tree j a + have hw : wd a = j + m := by simp [a, wd] + obtain ⟨o, ho⟩ := Tagged.exists_comparator F a + let _ := o + have hf : Fast F a := ho.mono (by omega) + have ok : sorter F a j ∈ SortTables F w := ⟨j, a, o, hf, hl, hr, by omega, by omega, rfl⟩ + have small : Processor.arity (sorter F a j) ≤ u := by + rw [arity_sorter] + exact (Nat.mul_le_mul_left _ (show wd a ≤ 4 * w by omega)).trans ha + have hsort : DWide F u (SortTables F w) b b (sortTree j) (1 + 2 * 2 ^ j * wd a) := by + rw [← arity_sorter F a j] + exact ⟨_, le_rfl, Wide.table _ _ _ small (.inr ok)⟩ + obtain ⟨L, hL⟩ := Layout.exists_tree a j + intro c e + let p := L.positions.sumCongr L.positions + have read := (tap_depends (taps (j := j) (m := m))).bnet F c (.pair b b) e p + obtain ⟨k, hk, net⟩ := (DWide.of_dnet hu read).comp (hsort.par hsort) + obtain ⟨l, hl', cap⟩ := (Tagged.cap (F := F) b).includeWide (L := SortTables F w) hu + refine ⟨k + l, ?_, ?_⟩ + · simp only [b, wd_tree, hw, PermBus, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + MatrixExponent.card_slots, wd_word, localCost] at hk hl' + have h₁ := Nat.mul_le_mul_left (2 ^ j) hr + have h₂ := Nat.mul_le_mul_left (2 ^ j) hm + have := Nat.two_pow_pos j + ring_nf at hk hl' h₁ h₂ ⊢ + omega + · have h := net.comp cap + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] at h + convert h using 1 + funext x _ + let y := (bits (.pair b b)).symm (Sum.elim (bits c x ∘ e) id ∘ taps ∘ p.symm) + change (if PermBus.valid _ then (1 : F) else 0) = if sortTree j y.1 + = sortTree j y.2 then 1 else 0 + have he : (flatten j y.2).Perm (flatten j y.1) ↔ PermBus.valid (bits c x ∘ e) + := taps_perm L hL _ + simp only [sorted_iff, he] + +open scoped Classical in +private theorem cover (A : Format) (v w : ℕ) (hw : 0 < w) (hv : A.width ≤ v) : + ∃ m ≤ w, ∃ f : Fin (v / w + 1) × slots (word m) → A.pins, Function.Surjective f := by + cases isEmpty_or_nonempty A.pins with + | inl h => + let _ := h + exact ⟨0, Nat.zero_le _, fun p => Empty.elim p.2, fun i => isEmptyElim i⟩ + | inr h => + let _ := h + have h' : v ≤ (v / w + 1) * w := by + have := Nat.mod_lt v hw + have := Nat.mod_add_div v w + rw [add_mul, one_mul, mul_comm (v / w) w] + omega + obtain ⟨g⟩ : Nonempty (A.pins ↪ Fin (v / w + 1) × slots (word w)) := + Function.Embedding.nonempty_of_card_le (by simpa [Format.width] using hv.trans h') + exact ⟨w, le_rfl, Function.invFun g, fun i => ⟨g i, Function.leftInverse_invFun g.injective i⟩⟩ + +open scoped Classical in +private abbrev Shuttle (A : Format) (j : ℕ) := (exchangeIn A j).pins ⊕ (exchangeOut A j).pins + +open scoped Classical in +private def slice {A : Format} (p : slots (word m) → A.pins) : PermBus j m → Shuttle A j + | .inl (i, t) => .inl (.inr (i, p t)) + | .inr (i, .inl t) => .inl (.inl (i, t)) + | .inr (i, .inr t) => .inr (i, p t) + +open scoped Classical in +private theorem slices (A : Format) {c : ℕ} (f : Fin (c + 1) × slots (word m) → A.pins) + (hf : Function.Surjective f) (z : Shuttle A j → Bool) : + (∏ i, if PermBus.valid (z ∘ slice (fun t => f (i, t))) then (1 : F) else 0) = + exchangeCheck A F z := by + let x := (exchangeIn A j).code.symm (z ∘ Sum.inl) + let y := (exchangeOut A j).code.symm (z ∘ Sum.inr) + let pass := fun i => PermBus.valid (z ∘ slice (fun t => f (i, t))) + have he (i) : pass i ↔ Function.Bijective x.1 ∧ + ∀ l t, z (.inr (l, f (i, t))) = z (.inl (.inr (x.1 l, f (i, t)))) := Iff.rfl + have hb (l) : y l = x.2 (x.1 l) ↔ + ∀ p, z (.inr (l, p)) = z (.inl (.inr (x.1 l, p))) := by + change A.code.symm _ = A.code.symm _ ↔ _ + rw [A.code.symm.injective.eq_iff, funext_iff] + rfl + have ok : (∀ i, pass i) ↔ Function.Bijective x.1 ∧ y = x.2 ∘ x.1 := by + constructor + · intro h + refine ⟨((he 0).mp (h 0)).1, funext fun l => (hb l).mpr ?_⟩ + intro p + obtain ⟨⟨i, t⟩, rfl⟩ := hf p + exact ((he i).mp (h i)).2 l t + · rintro ⟨ha, hy⟩ i + exact (he i).mpr ⟨ha, fun l t => (hb l).mp (congrFun hy l) _⟩ + change (∏ i, if pass i then (1 : F) else 0) = + if Function.Bijective x.1 ∧ y = x.2 ∘ x.1 then 1 else 0 + simp only [← ok] + by_cases h : ∀ i, pass i + · simp [h] + · rw [ite_eq_right h] + obtain ⟨i, hi⟩ := not_forall.mp h + exact Finset.prod_eq_zero (Finset.mem_univ i) (ite_eq_right hi) + +open scoped Classical in +private theorem exchange_weight (A : Format) (v : ℕ) (hw : 0 < w) (hl : w ≤ j) (hr : j ≤ 2 * w) + (hu : 3 ≤ u) (ha : 2 * 2 ^ j * (4 * w) ≤ u) (hv : A.width ≤ v) : + WideWeight F u (SortTables F w) (exchangeCheck (j := j) A F) (100000 * 2 ^ j * (j + v + 1)) + := by + obtain ⟨m, hm, f, hf⟩ := cover A v w hw hv + let test (_ : Fin (v / w + 1)) (z : PermBus j m → Bool) := if PermBus.valid z then (1 : F) else 0 + let read i : PermBus j m → Shuttle A j ⊕ Empty := Sum.inl ∘ slice (fun t => f (i, t)) + have g := wide_sum test read (fun _ => 2000 * 2 ^ j * (w + 1)) hu (fun _ + => slice_weight F hu hl hr ha hm) + have he : weightedSum test read = exchangeCheck A F := by + funext z + simpa [weightedSum, test, read, Function.comp_def] using slices F A f hf z + rw [he] at g + intro a e + obtain ⟨l, hk, h⟩ := g a e + refine ⟨l, hk.trans ?_, h⟩ + have hp : Fintype.card (Shuttle A j) = 2 ^ j * j + 2 ^ j * A.width + 2 ^ j * A.width := by + rw [Fintype.card_sum] + change (exchangeIn A j).width + (exchangeOut A j).width = _ + simp [exchangeIn, exchangeOut, Perm] + have hs : (v / w + 1) * (w + 1) ≤ 2 * v + j + 1 := by + have := Nat.div_mul_le_self v w + have := Nat.div_le_self v w + rw [add_mul, mul_add, mul_one, one_mul] + omega + have ht := Nat.mul_le_mul_left (2 ^ j) hs + have hz := Nat.mul_le_mul_left (2 ^ j) hv + simp only [hp, Fintype.card_empty, add_zero, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + nsmul_eq_mul, Nat.cast_id] + ring_nf at ht hz ⊢ + omega + +open scoped Classical in +theorem exchange (v : ℕ) (hw : 0 < w) (hl : w ≤ j) (hr : j ≤ 2 * w) + (ha : 2 * 2 ^ j * (4 * w) ≤ u) : + Access F u (SortTables F w) j v (1000000 * 2 ^ j * (j + v + 1)) := by + have hu : 3 ≤ u := by + have := Nat.le_mul_of_pos_left (4 * w) (show 0 < 2 * 2 ^ j by positivity) + omega + intro A hv + have h := Kernel.of_weight hu (exchange_weight F A v hw hl hr hu ha hv) + have hh : 100000 * 2 ^ j * (j + v + 1) + 4 * (exchangeOut A j).width ≤ + 4 * (1000000 * 2 ^ j * (j + v + 1)) + 1000 * 2 ^ j * (j + v + 1) := by + rw [Format.width_vec] + have := Nat.mul_le_mul_left (2 ^ j) hv + ring_nf at this ⊢ + omega + simpa [exchangeCheck, Function.comp_def] using h.mono hh + +end MatrixMultiplicationAllFields.MatrixExponent.BatchDescent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Batcher.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Batcher.lean new file mode 100644 index 0000000000..1561faec1f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Batcher.lean @@ -0,0 +1,67 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BitonicSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FunctionNetwork +public import Mathlib.Tactic.Ring + +/-! +# Trivalent realization of Batcher's sorting network + +Splitting applies one layer of comparators to corresponding records. +Merging adds at most one such layer per level. Sorting merges at every level. +The cost includes identities on single records. Reversals and the +permutations between layers only relabel ports. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +private theorem rewire_reverseTree (w : ℕ) (a : Wire) : + Rewire (tree w a) (tree w a) (reverseTree w) := by + induction w with + | zero => exact Rewire.id a + | succ w ih => exact (Rewire.swap _ _).comp (ih.par ih) + +variable {F : Type} [Field F] {a : Wire} [LinearOrder (Val a)] {k : ℕ} + (h : DNet F (.pair a a) (.pair a a) (fun x => (min x.1 x.2, max x.1 x.2)) k) + +include h + +private theorem splitTree_net (w : ℕ) : + DNet F (tree (w + 1) a) (tree (w + 1) a) (splitTree w) (2 ^ w * k) := by + induction w with + | zero => rw [pow_zero, one_mul]; exact h + | succ w ih => + have hm := Rewire.middle (tree w a) (tree w a) (tree w a) (tree w a) + rw [show 2 ^ (w + 1) * k = 2 ^ w * k + 2 ^ w * k by ring] + exact ((ih.par ih).pre hm).post hm + +private theorem mergeTree_net (w : ℕ) : + DNet F (tree w a) (tree w a) (mergeTree w) (2 ^ w * (w * k + wd a)) := by + induction w with + | zero => + rw [pow_zero, one_mul, zero_mul, zero_add] + exact DNet.id F a + | succ w ih => + refine ((splitTree_net h w).comp (ih.par ih)).mono ?_ + ring_nf + omega + +theorem sortTree_net (w : ℕ) : + DNet F (tree w a) (tree w a) (sortTree w) (2 ^ w * (w + 1) ^ 2 * (k + wd a)) := by + induction w with + | zero => exact (DNet.id F a).mono (by simp) + | succ w ih => + have hp := ih.par (ih.post (rewire_reverseTree w a)) + refine (hp.comp (mergeTree_net h (w + 1))).mono ?_ + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Bilinearize.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Bilinearize.lean new file mode 100644 index 0000000000..440c40c873 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Bilinearize.lean @@ -0,0 +1,140 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Derivatives +public import Mathlib.LinearAlgebra.Finsupp.LinearCombination + +/-! +# Bilinearization in the rational function field + +Track the matrix of mixed left/right partials of each available wire. A gate +enlarges a common spanning family by at most two outer products. Work at the +generic point, so division never requires choosing a regular point in the +ground field. This also avoids polarization in characteristic two. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} [Field F] {I J K : ℕ} + +private abbrev Factors (F : Type*) [Field F] (I J K : ℕ) := + (Pos I K → Rat F I J K) × (Pos K J → Rat F I J K) + +private def outer (v : Factors F I J K) (i : Pos I K) (j : Pos K J) : Rat F I J K := v.1 i * v.2 j + +private def cross (x y : Rat F I J K) : Factors F I J K := + (fun i => partialD (.inl i) x, fun j => partialD (.inr j) y) + +private def mixed (x : Rat F I J K) (i : Pos I K) (j : Pos K J) : Rat F I J K := + partialD (.inl i) (partialD (.inr j) x) + +private theorem mixed_mul (x y : Rat F I J K) : + mixed (x * y) = y • mixed x + (x • mixed y + (outer (cross x y) + outer (cross y x))) := by + funext i j + simp only [mixed, Derivation.leibniz, smul_eq_mul, map_add, Pi.add_apply, + Pi.smul_apply, outer, cross] + ring + +private theorem mixed_output (i : Pos I K) (j : Pos K J) (p : Pos I J) : + mixed (output F p) i j = + if i.1 = p.1 ∧ i.2 = j.1 ∧ j.2 = p.2 then 1 else 0 := by + have hy : partialD (.inr j) (output F p) = + if j.2 = p.2 then input F (.inl (p.1, j.1)) else 0 := by + by_cases h : j.2 = p.2 <;> + simp [output, map_sum, Derivation.leibniz, smul_eq_mul, input, partialD_X, + Prod.ext_iff, h, mul_ite] + rw [mixed, hy] + by_cases h : j.2 = p.2 <;> simp [h, input, partialD_X, Prod.ext_iff] + +private def Covered (T : Set (Rat F I J K)) (d : ℕ) : Prop := + ∃ v : Fin d → Factors F I J K, ∀ x ∈ T, + mixed x ∈ Submodule.span (Rat F I J K) (Set.range fun i => outer (v i)) + +private theorem Covered.step {T : Set (Rat F I J K)} {d : ℕ} (h : Covered T d) + {z : Rat F I J K} (a b : Rat F I J K) + (hz : ∀ U : Submodule (Rat F I J K) (Pos I K → Pos K J → Rat F I J K), + (∀ x ∈ T, mixed x ∈ U) → outer (cross a b) ∈ U → outer (cross b a) ∈ U → mixed z ∈ U) : + Covered (insert z T) (d + 2) := by + obtain ⟨v, hv⟩ := h + let w : Fin (d + 2) → Factors F I J K := Fin.cons (cross a b) (Fin.cons (cross b a) v) + let U := Submodule.span (Rat F I J K) (Set.range fun i => outer (w i)) + have hw (i) : outer (w i) ∈ U := Submodule.subset_span ⟨i, rfl⟩ + have hold : Submodule.span (Rat F I J K) (Set.range fun i => outer (v i)) ≤ U := by + apply Submodule.span_le.mpr + rintro _ ⟨i, rfl⟩ + simpa [w] using hw i.succ.succ + refine ⟨w, ?_⟩ + rintro x (rfl | hx) + · exact hz U (fun x hx => hold (hv x hx)) (hw 0) (hw (Fin.succ 0)) + · exact hold (hv x hx) + +private theorem covered_build {m : ℕ} {T : Set (Rat F I J K)} + (h : Build (initial F I J K) m T) : Covered T (2 * m) := by + induction h with + | nil => + refine ⟨Fin.elim0, fun x hx => ?_⟩ + have hz : mixed x = 0 := by + funext i j + rcases hx with ⟨c, rfl⟩ | ⟨k, rfl⟩ + · simp [mixed] + · simp only [mixed, input, partialD_X] + split_ifs <;> simp + rw [hz] + exact Submodule.zero_mem _ + | @add m T x y _ hx hy ih => + apply ih.step x y + intro U hu _ _ + have he : mixed (x + y) = mixed x + mixed y := by funext i j; simp [mixed] + rw [he] + exact U.add_mem (hu x hx) (hu y hy) + | @sub m T x y _ hx hy ih => + apply ih.step x y + intro U hu _ _ + have he : mixed (x - y) = mixed x - mixed y := by funext i j; simp [mixed] + rw [he] + exact U.sub_mem (hu x hx) (hu y hy) + | @mul m T x y _ hx hy ih => + apply ih.step x y + intro U hu ha hb + rw [mixed_mul] + exact U.add_mem (U.smul_mem y (hu x hx)) (U.add_mem (U.smul_mem x (hu y hy)) (U.add_mem ha hb)) + | @div m T x y _ hx hy hne ih => + apply ih.step (x / y) y + intro U hu ha hb + have hm : mixed ((x / y) * y) ∈ U := by rw [div_mul_cancel₀ _ hne]; exact hu x hx + rw [mixed_mul] at hm + have hr := U.sub_mem hm (U.add_mem (U.smul_mem (x / y) (hu y hy)) (U.add_mem ha hb)) + rw [add_sub_cancel_right] at hr + simpa [smul_smul, hne] using U.smul_mem y⁻¹ hr + +/-- The multiplication tensor has rank at most twice the arithmetic cost over +the rational function field of the inputs. -/ +theorem bilinearize {m : ℕ} (h : Computes F I J K m) : RankLE (Rat F I J K) I J K (2 * m) := by + obtain ⟨T, hT, hout⟩ := h + obtain ⟨v, hv⟩ := covered_build hT + have hc (p : Pos I J) := (Submodule.mem_span_range_iff_exists_fun _).mp (hv _ (hout p)) + choose c he using hc + refine ⟨fun l => (v l).1, fun l => (v l).2, fun l p => c p l, ?_⟩ + intro i j p + rw [← mixed_output i j p, ← he p] + simp only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul, outer] + exact Finset.sum_congr rfl (fun _ _ => mul_comm _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem bilinearize {F : Type*} [Field F] {n m : ℕ} (h : Computes F n m) : + RankLE (Rat F n) n (2 * m) := + Rectangle.bilinearize h + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BitonicMerge.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BitonicMerge.lean new file mode 100644 index 0000000000..bfdcb7f28d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BitonicMerge.lean @@ -0,0 +1,185 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BitonicSort + +/-! +# Bitonic merge + +Bitonicity is expressed by forbidding four ordered positions alternating +between the two classes `x ≤ b` and `b < x`, for every threshold `b`. +Opposite-position comparisons separate the two halves and preserve +bitonicity within each half. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {a : Wire} + +private def read : (w : ℕ) → Val (tree w a) → ℕ → Val a + | 0, x, _ => x + | w + 1, x, i => + if i < 2 ^ w then read w x.1 i else read w x.2 (i - 2 ^ w) + +private theorem read_left (w : ℕ) (x : Val (tree (w + 1) a)) {i : ℕ} (h : i < 2 ^ w) : + read (w + 1) x i = read w x.1 i := by + simp [read, h] + +private theorem read_right (w : ℕ) (x : Val (tree (w + 1) a)) (i : ℕ) : + read (w + 1) x (2 ^ w + i) = read w x.2 i := by + simp [read] + +private theorem mem_flatten (w : ℕ) (x : Val (tree w a)) (y : Val a) : + y ∈ flatten w x ↔ ∃ i < 2 ^ w, read w x i = y := by + induction w with + | zero => simp [read, flatten, eq_comm] + | succ w ih => + rw [flatten, List.mem_append, ih, ih, pow_succ] + constructor + · rintro (⟨i, hi, hy⟩ | ⟨i, hi, hy⟩) + · exact ⟨i, by omega, (read_left w x hi).trans hy⟩ + · exact ⟨2 ^ w + i, by omega, (read_right w x i).trans hy⟩ + · rintro ⟨i, hi, hy⟩ + rw [read] at hy + split at hy + · exact .inl ⟨i, by omega, hy⟩ + · exact .inr ⟨i - 2 ^ w, by omega, hy⟩ + +private theorem read_pairwise (w : ℕ) (x : Val (tree w a)) {R : Val a → Val a → Prop} + (h : (flatten w x).Pairwise R) {i j : ℕ} (hij : i < j) (hj : j < 2 ^ w) : + R (read w x i) (read w x j) := by + induction w generalizing i j with + | zero => simp at hj; omega + | succ w ih => + rw [flatten, List.pairwise_append] at h + rw [pow_succ] at hj + rw [read, read] + split <;> split + · exact ih _ h.1 hij (by omega) + · exact h.2.2 _ ((mem_flatten ..).2 ⟨i, by omega, rfl⟩) + _ ((mem_flatten ..).2 ⟨j - 2 ^ w, by omega, rfl⟩) + · omega + · exact ih _ h.2.1 (by omega) (by omega) + +variable [LinearOrder (Val a)] + +private theorem read_split (w : ℕ) (x : Val (tree (w + 1) a)) (i : ℕ) : + read w (splitTree w x).1 i = min (read w x.1 i) (read w x.2 i) ∧ + read w (splitTree w x).2 i = max (read w x.1 i) (read w x.2 i) := by + induction w generalizing i with + | zero => exact ⟨rfl, rfl⟩ + | succ w ih => + by_cases h : i < 2 ^ w + · simpa [read, h, splitTree] using ih (x.1.1, x.2.1) i + · simpa [read, h, splitTree] using ih (x.1.2, x.2.2) (i - 2 ^ w) + +private def NoAlt (u v s t : Prop) : Prop := + (u → s → v ∨ t) ∧ (v → t → u ∨ s) + +private def Bitonic (w : ℕ) (x : Val (tree w a)) : Prop := + ∀ i j k l : ℕ, i < j → j < k → k < l → l < 2 ^ w → ∀ b : Val a, + NoAlt (read w x i ≤ b) (read w x j ≤ b) (read w x k ≤ b) (read w x l ≤ b) + +/-- Test the cut at four positions and their four opposites. Six inherited +constraints suffice for the minima (or) and the maxima (and). -/ +private theorem split_cuts {p q r s t u v z : Prop} + (h₁ : NoAlt p q r s) (h₂ : NoAlt p q r z) + (h₃ : NoAlt s t u v) (h₄ : NoAlt t u v z) + (h₅ : NoAlt p q v z) (h₆ : NoAlt r s t u) : + NoAlt (p ∨ t) (q ∨ u) (r ∨ v) (s ∨ z) ∧ + NoAlt (p ∧ t) (q ∧ u) (r ∧ v) (s ∧ z) := by + unfold NoAlt at * + grind + +private theorem bitonic_split (w : ℕ) (x : Val (tree (w + 1) a)) (hx : Bitonic (w + 1) x) : + Bitonic w (splitTree w x).1 ∧ Bitonic w (splitTree w x).2 := by + have both (i j k l : ℕ) (h₁ : i < j) (h₂ : j < k) (h₃ : k < l) (h₄ : l < 2 ^ w) + (b : Val a) : + let cut := fun y => NoAlt (read w y i ≤ b) (read w y j ≤ b) + (read w y k ≤ b) (read w y l ≤ b) + cut (splitTree w x).1 ∧ cut (splitTree w x).2 := by + have hi : i < 2 ^ w := by omega + have hj : j < 2 ^ w := by omega + have hk : k < 2 ^ w := by omega + have hw : 2 ^ (w + 1) = 2 ^ w * 2 := pow_succ .. + have H := split_cuts + (hx i j k l h₁ h₂ h₃ (by omega) b) + (hx i j k (2 ^ w + l) h₁ h₂ (by omega) (by omega) b) + (hx l (2 ^ w + i) (2 ^ w + j) (2 ^ w + k) (by omega) (by omega) (by omega) (by omega) b) + (hx (2 ^ w + i) (2 ^ w + j) (2 ^ w + k) (2 ^ w + + l) (by omega) (by omega) (by omega) (by omega) b) + (hx i j (2 ^ w + k) (2 ^ w + l) h₁ (by omega) (by omega) (by omega) b) + (hx k l (2 ^ w + i) (2 ^ w + j) h₃ (by omega) (by omega) (by omega) b) + simpa only [read_split, min_le_iff, max_le_iff, read_left w x hi, read_left w x hj, + read_left w x hk, read_left w x h₄, read_right] using H + exact ⟨fun i j k l h₁ h₂ h₃ h₄ b => (both i j k l h₁ h₂ h₃ h₄ b).1, + fun i j k l h₁ h₂ h₃ h₄ b => (both i j k l h₁ h₂ h₃ h₄ b).2⟩ + +private theorem split_le (w : ℕ) (x : Val (tree (w + 1) a)) (hx : Bitonic (w + 1) x) + (u : Val a) (hu : u ∈ flatten w (splitTree w x).1) + (v : Val a) (hv : v ∈ flatten w (splitTree w x).2) : u ≤ v := by + obtain ⟨i, hi, rfl⟩ := (mem_flatten ..).1 hu + obtain ⟨j, hj, rfl⟩ := (mem_flatten ..).1 hv + rw [(read_split ..).1, (read_split ..).2, min_le_iff] + have hw : 2 ^ (w + 1) = 2 ^ w * 2 := pow_succ .. + rcases lt_trichotomy i j with hij | rfl | hji + · have h := hx i j (2 ^ w + i) (2 ^ w + j) hij (by omega) (by omega) (by omega) + (max (read w x.1 j) (read w x.2 j)) + rw [read_left w x hi, read_left w x hj, read_right, read_right] at h + exact h.2 (le_max_left ..) (le_max_right ..) + · exact Or.inl (le_max_left ..) + · have h := hx j i (2 ^ w + j) (2 ^ w + i) hji (by omega) (by omega) (by omega) + (max (read w x.1 j) (read w x.2 j)) + rw [read_left w x hi, read_left w x hj, read_right, read_right] at h + exact h.1 (le_max_left ..) (le_max_right ..) + +private theorem bitonic_of_pairwise (w : ℕ) (x : Val (tree (w + 1) a)) + (hl : (flatten w x.1).Pairwise (· ≤ ·)) (hr : (flatten w x.2).Pairwise (· ≥ ·)) : + Bitonic (w + 1) x := by + intro i j k l h₁ h₂ h₃ h₄ b + rw [pow_succ] at h₄ + have prevOrNext (p q r : ℕ) (hp : p < q) (hq : q < r) (hr' : r < 2 ^ w * 2) + (hb : read (w + 1) x q ≤ b) : read (w + 1) x p ≤ b ∨ read (w + 1) x r ≤ b := by + by_cases hq' : q < 2 ^ w + · left + rw [read_left w x hq'] at hb + rw [read_left w x (by omega : p < 2 ^ w)] + exact (read_pairwise w x.1 hl hp hq').trans hb + · right + rw [read, ite_eq_right hq'] at hb + rw [read, ite_eq_right (by omega : ¬ r < 2 ^ w)] + exact (read_pairwise w x.2 hr (by omega : q - 2 ^ w < r - 2 ^ w) (by omega)).trans hb + exact ⟨fun _ hk => prevOrNext j k l h₂ h₃ h₄ hk, + fun hj _ => prevOrNext i j k h₁ h₂ (by omega) hj⟩ + +private theorem mergeTree_sorted (w : ℕ) (x : Val (tree w a)) (hx : Bitonic w x) : + (flatten w (mergeTree w x)).Pairwise (· ≤ ·) := by + induction w with + | zero => simp [flatten] + | succ w ih => + rw [mergeTree, flatten, List.pairwise_append] + obtain ⟨hl, hr⟩ := bitonic_split w x hx + refine ⟨ih _ hl, ih _ hr, fun u hu v hv => ?_⟩ + exact split_le w x hx u ((mergeTree_perm ..).mem_iff.mp hu) + v ((mergeTree_perm ..).mem_iff.mp hv) + +theorem sortTree_sorted (w : ℕ) (x : Val (tree w a)) : + (flatten w (sortTree w x)).Pairwise (· ≤ ·) := by + induction w with + | zero => simp [flatten] + | succ w ih => + rw [sortTree] + apply mergeTree_sorted + apply bitonic_of_pairwise + · exact ih _ + · rw [flatten_reverseTree, List.pairwise_reverse] + exact ih _ + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BitonicSort.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BitonicSort.lean new file mode 100644 index 0000000000..08b2658737 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BitonicSort.lean @@ -0,0 +1,90 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network + +/-! # Batcher's bitonic sorting network on balanced arrays -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- In the case `0, x`, this construction gives `x`. -/ +def reverseTree {a : Wire} : (w : ℕ) → Val (tree w a) → Val (tree w a) + | 0, x => x + | w + 1, x => (reverseTree w x.2, reverseTree w x.1) + +theorem flatten_reverseTree {a : Wire} (w : ℕ) (x : Val (tree w a)) : + flatten w (reverseTree w x) = (flatten w x).reverse := by + induction w with + | zero => rfl + | succ w ih => simp only [reverseTree, flatten, List.reverse_append, ih] + +variable {a : Wire} [LinearOrder (Val a)] + +/-- Compare opposite entries, putting the smaller one in the left subtree. -/ +def splitTree : (w : ℕ) → Val (tree (w + 1) a) → Val (tree (w + 1) a) + | 0, x => (min x.1 x.2, max x.1 x.2) + | w + 1, x => + let p := splitTree w (x.1.1, x.2.1) + let q := splitTree w (x.1.2, x.2.2) + ((p.1, q.1), (p.2, q.2)) + +/-- In the case `0, x`, this construction gives `x`. -/ +def mergeTree : (w : ℕ) → Val (tree w a) → Val (tree w a) + | 0, x => x + | w + 1, x => + let p := splitTree w x + (mergeTree w p.1, mergeTree w p.2) + +/-- In the case `0, x`, this construction gives `x`. -/ +def sortTree : (w : ℕ) → Val (tree w a) → Val (tree w a) + | 0, x => x + | w + 1, x => + mergeTree (w + 1) (sortTree w x.1, reverseTree w (sortTree w x.2)) + +private theorem perm_swap_middle {α : Type} (l₁ l₂ l₃ l₄ : List α) : + ((l₁ ++ l₂) ++ (l₃ ++ l₄)).Perm ((l₁ ++ l₃) ++ (l₂ ++ l₄)) := by + simpa only [List.append_assoc] using + (List.perm_append_comm_assoc l₂ l₃ l₄).append_left l₁ + +theorem splitTree_perm (w : ℕ) (x : Val (tree (w + 1) a)) : + (flatten (w + 1) (splitTree w x)).Perm (flatten (w + 1) x) := by + induction w with + | zero => + change [min x.1 x.2, max x.1 x.2].Perm [x.1, x.2] + rcases le_total x.1 x.2 with h | h + · rw [min_eq_left h, max_eq_right h] + · rw [min_eq_right h, max_eq_left h] + exact List.Perm.swap .. + | succ w ih => + let p := splitTree w (x.1.1, x.2.1) + let q := splitTree w (x.1.2, x.2.2) + exact (perm_swap_middle (flatten w p.1) (flatten w q.1) + (flatten w p.2) (flatten w q.2)).trans + (((ih (x.1.1, x.2.1)).append (ih (x.1.2, x.2.2))).trans + (perm_swap_middle (flatten w x.1.1) (flatten w x.2.1) + (flatten w x.1.2) (flatten w x.2.2))) + +theorem mergeTree_perm (w : ℕ) (x : Val (tree w a)) : + (flatten w (mergeTree w x)).Perm (flatten w x) := by + induction w with + | zero => exact List.Perm.refl _ + | succ w ih => + exact ((ih (splitTree w x).1).append (ih (splitTree w x).2)).trans (splitTree_perm w x) + +theorem sortTree_perm (w : ℕ) (x : Val (tree w a)) : + (flatten w (sortTree w x)).Perm (flatten w x) := by + induction w with + | zero => exact List.Perm.refl _ + | succ w ih => + apply (mergeTree_perm (w + 1) (sortTree w x.1, reverseTree w (sortTree w x.2))).trans + simp only [flatten, flatten_reverseTree] + exact (ih x.1).append ((List.reverse_perm _).trans (ih x.2)) + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BlockProducts.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BlockProducts.lean new file mode 100644 index 0000000000..ee309f70ef --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BlockProducts.lean @@ -0,0 +1,99 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Model +public import Mathlib.Logic.Equiv.Fin.Basic +public import Mathlib.Algebra.BigOperators.Group.Finset.Sigma + +/-! +# Applying a scalar rank decomposition to blocks + +The coefficients belong to the base ring. The input entries may live in an +algebra, in particular the polynomial ring of a smaller padded input. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F K : Type*} [CommRing F] [CommRing K] [Algebra F K] {i j k r d e f : ℕ} + +/-- The value specified by `(finProdFinEquiv (z.1, p.1), finProdFinEquiv (z.2, p.2))`. -/ +def joinPos (z : Pos i j) (p : Pos d e) : Pos (i * d) (j * e) := + (finProdFinEquiv (z.1, p.1), finProdFinEquiv (z.2, p.2)) + +/-- The quantity computed by `∑ l, X (p.1, l) * Y (l, p.2)`. -/ +def mm (X : Pos i k → K) (Y : Pos k j → K) (p : Pos i j) : K := + ∑ l, X (p.1, l) * Y (l, p.2) + +/-- The sum of `algebraMap F K (a z) * X (joinPos z p)` indexed by `z`. -/ +def linBlock (a : Pos i j → F) (X : Pos (i * d) (j * e) → K) (p : Pos d e) : K := + ∑ z, algebraMap F K (a z) * X (joinPos z p) + +private theorem eval_formula (a : Fin r → Pos i k → F) (b : Fin r → Pos k j → F) + (c : Fin r → Pos i j → F) (h : ∀ x y z, ∑ l, a l x * b l y * c l z = + if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then 1 else 0) + (v : Pos i k → K) (w : Pos k j → K) (z : Pos i j) : + ∑ l, algebraMap F K (c l z) * + ((∑ x, algebraMap F K (a l x) * v x) * (∑ y, algebraMap F K (b l y) * w y)) = + mm v w z := by + classical + calc + _ = ∑ l, ∑ x, ∑ y, algebraMap F K (a l x * b l y * c l z) * v x * w y := by + simp only [Finset.sum_mul] + simp only [Finset.mul_sum, map_mul, mul_comm, mul_left_comm] + _ = ∑ x, ∑ y, algebraMap F K (∑ l, a l x * b l y * c l z) * v x * w y := by + simp only [map_sum, Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + rw [Finset.sum_comm] + _ = mm v w z := by + simp [h, apply_ite, ite_mul, ite_and, Fintype.sum_prod_type, Finset.sum_ite_irrel, mm] + +theorem block_formula (h : Integral.Rank F i j k r) : + ∃ (a : Fin r → Pos i k → F) (b : Fin r → Pos k j → F) (c : Fin r → Pos i j → F), + ∀ (X : Pos (i * d) (k * f) → K) (Y : Pos (k * f) (j * e) → K) + (z : Pos i j) (p : Pos d e), + mm X Y (joinPos z p) = + ∑ l, algebraMap F K (c l z) * mm (linBlock (a l) X) (linBlock (b l) Y) p := by + obtain ⟨a, b, c, habc⟩ := h + refine ⟨a, b, c, ?_⟩ + intro X Y z p + simp only [mm, Finset.mul_sum] + rw [← finProdFinEquiv.sum_comp, Fintype.sum_prod_type, Finset.sum_comm] + conv_rhs => rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro l _ + exact (eval_formula a b c habc (fun x => X (joinPos x (p.1, l))) + (fun y => Y (joinPos y (l, p.2))) z).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {F K : Type*} [Field F] [Field K] [Algebra F K] {n r d : ℕ} + +/-- Uses `Rectangle.joinPos z p` as the representation. -/ +abbrev joinPos (z : Pos n) (p : Pos d) : Pos (n * d) := Rectangle.joinPos z p + +/-- Uses `Rectangle.mm X Y p` as the representation. -/ +abbrev mm (X Y : Pos n → K) (p : Pos n) : K := Rectangle.mm X Y p + +/-- Uses `Rectangle.linBlock a X p` as the representation. -/ +abbrev linBlock (a : Pos n → F) (X : Pos (n * d) → K) (p : Pos d) : K := + Rectangle.linBlock a X p + +theorem block_formula (h : RankLE F n r) : + ∃ a b c : Fin r → Pos n → F, ∀ (X Y : Pos (n * d) → K) (z : Pos n) (p : Pos d), + mm X Y (joinPos z p) = + ∑ i, algebraMap F K (c i z) * mm (linBlock (a i) X) (linBlock (b i) Y) p := + Rectangle.block_formula h + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BlockRecursion.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BlockRecursion.lean new file mode 100644 index 0000000000..251645fb59 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/BlockRecursion.lean @@ -0,0 +1,153 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Nodes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BlockProducts +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CircuitCost +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Tactic.Ring + +/-! +# Recursion on blocks and zero padding + +A recursive call may have inputs that are already computed values. Work over +an arbitrary algebra `K` with only the constants of `F` supplied for free, +then instantiate `K` with the polynomial ring of the padded problem. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +private def Multiplies (F K : Type*) [CommRing F] [CommRing K] [Algebra F K] + (i j k cost : ℕ) : Prop := + ∀ (S : Set K) (X : Pos i k → K) (Y : Pos k j → K), (∀ x, algebraMap F K x ∈ S) → + (∀ p, X p ∈ S) → (∀ p, Y p ∈ S) → CanMake S cost (Set.range (mm X Y)) + +variable {F K : Type*} [CommRing F] [CommRing K] [Algebra F K] + +private lemma multiplies_one : Multiplies F K 1 1 1 1 := by + intro S X Y _ hX hY + refine (CanMake.mul (hX (0, 0)) (hY (0, 0))).mono_output ?_ + rintro _ ⟨p, rfl⟩ + rw [Subsingleton.elim p (0, 0)] + simp [mm] + +private lemma joinPos_surj {i j d e : ℕ} (u : Pos (i * d) (j * e)) : + ∃ z p, joinPos z p = u := by + obtain ⟨⟨x, x'⟩, hx⟩ := finProdFinEquiv.surjective u.1 + obtain ⟨⟨y, y'⟩, hy⟩ := finProdFinEquiv.surjective u.2 + exact ⟨(x, y), (x', y'), Prod.ext hx hy⟩ + +/-- First form two families of linear combinations, then compute and +recombine the `r` smaller matrix products. -/ +private lemma multiplies_step {i j k r d e f cost : ℕ} (h : Integral.Rank F i j k r) + (ih : Multiplies F K d e f cost) : + Multiplies F K (i * d) (j * e) (k * f) + (r * cost + 2 * r * (i * j * (d * e) + i * k * (d * f) + j * k * (e * f))) := by + intro S X Y hS hX hY + obtain ⟨a, b, c, hc⟩ := block_formula (K := K) (d := d) (e := e) (f := f) h + have h0 : (0 : K) ∈ S := by simpa using hS 0 + let A l := linBlock (a l) X + let B l := linBlock (b l) Y + have prep {n m u v : ℕ} (g : Fin r → Pos n m → F) (Z : Pos (n * u) (m * v) → K) + (hZ : ∀ p, Z p ∈ S) : + CanMake S (r * (u * v * (n * m * 2))) (⋃ l, Set.range (linBlock (g l) Z)) := by + have entry (l : Fin r) (p : Pos u v) : + CanMake S (Fintype.card (Pos n m) * 2) {linBlock (g l) Z p} := + CanMake.linear h0 (fun z => hS (g l z)) (fun z => hZ (joinPos z p)) + simpa only [Pos, Fintype.card_prod, Fintype.card_fin] using + CanMake.iUnion (fun l => CanMake.range (entry l)) + let T := S ∪ ((⋃ l, Set.range (A l)) ∪ (⋃ l, Set.range (B l))) + have prod (l : Fin r) : CanMake T cost (Set.range (mm (A l) (B l))) := + ih T (A l) (B l) (fun x => Or.inl (hS x)) + (fun p => Or.inr (Or.inl (Set.mem_iUnion_of_mem l ⟨p, rfl⟩))) + (fun p => Or.inr (Or.inr (Set.mem_iUnion_of_mem l ⟨p, rfl⟩))) + let U := T ∪ (⋃ l, Set.range (mm (A l) (B l))) + have finish (u : Pos (i * d) (j * e)) : CanMake U (Fintype.card (Fin r) * 2) {mm X Y u} := by + obtain ⟨z, p, rfl⟩ := joinPos_surj u + rw [hc] + exact CanMake.linear (Or.inl (Or.inl h0)) (fun l => Or.inl (Or.inl (hS (c l z)))) + (fun l => Or.inr (Set.mem_iUnion_of_mem l ⟨p, rfl⟩)) + have start := ((prep a X hX).union (prep b Y hY)).keep + have whole := (start.trans (CanMake.iUnion prod).keep).trans (CanMake.range finish) + refine whole.mono_cost ?_ + simp only [Pos, Fintype.card_prod, Fintype.card_fin] + exact le_of_eq (by ring) + +private def pad {i j : ℕ} (d e : ℕ) (X : Pos i j → K) (p : Pos (i + d) (j + e)) : K := + if h : p.1.val < i ∧ p.2.val < j then X (⟨p.1.val, h.1⟩, ⟨p.2.val, h.2⟩) else 0 + +private lemma multiplies_smaller {i j k u v w cost : ℕ} (hi : i ≤ u) (hj : j ≤ v) (hk : k ≤ w) + (h : Multiplies F K u v w cost) : Multiplies F K i j k cost := by + obtain ⟨d, rfl⟩ := Nat.exists_eq_add_of_le hi + obtain ⟨e, rfl⟩ := Nat.exists_eq_add_of_le hj + obtain ⟨f, rfl⟩ := Nat.exists_eq_add_of_le hk + intro S X Y hS hX hY + have hpad {m n a b : ℕ} (Z : Pos m n → K) (hZ : ∀ p, Z p ∈ S) (p : Pos (m + a) (n + b)) : + pad a b Z p ∈ S := by + unfold pad + split + · exact hZ _ + · simpa using hS 0 + refine (h S (pad d f X) (pad f e Y) hS (hpad X hX) (hpad Y hY)).mono_output ?_ + rintro _ ⟨⟨x, y⟩, rfl⟩ + refine ⟨(Fin.castAdd d x, Fin.castAdd e y), ?_⟩ + simp [mm, Fin.sum_univ_add, pad] + +private def powerCost (i j k r : ℕ) : ℕ → ℕ + | 0 => 1 + | t + 1 => r * powerCost i j k r t + 2 * r * (i * j * (i * j) ^ t + i * k * (i * k) ^ t + + j * k * (j * k) ^ t) + +private lemma multiplies_power {i j k r : ℕ} (h : Integral.Rank F i j k r) (t : ℕ) : + Multiplies F K (i ^ t) (j ^ t) (k ^ t) (powerCost i j k r t) := by + induction t with + | zero => simpa only [pow_zero, powerCost] using (multiplies_one (F := F) (K := K)) + | succ t ih => simpa only [powerCost, pow_succ', mul_pow] using multiplies_step h ih + +/-- A rank witness gives a cost recurrence valid up to each power of the +block dimensions. The overhead grows with the largest of the three areas. -/ +theorem integral_power_cost {i j k r : ℕ} (h : Integral.Rank F i j k r) : + ∃ D : ℕ, ∃ a : ℕ → ℕ, (∀ t, a (t + 1) ≤ r * a t + D * (max (i * j) (max (i * k) (j * k))) ^ t) ∧ + ∀ t I J K : ℕ, I ≤ i ^ t → J ≤ j ^ t → K ≤ k ^ t → ∃ m, Integral.Computes F I J K m ∧ m ≤ a t + := by + refine ⟨2 * r * (i * j + i * k + j * k), powerCost i j k r, ?_, ?_⟩ + · intro t + rw [powerCost, mul_assoc (2 * r), add_mul, add_mul] + gcongr <;> omega + · intro t I J K hI hJ hK + have hmul := multiplies_smaller hI hJ hK (multiplies_power (K := Integral.Poly F I J K) h t) + obtain ⟨m, hm, T, hT, hout⟩ := + hmul (Integral.initial F I J K) (fun p => Integral.input F (.inl p)) (fun p + => Integral.input F (.inr p)) + (fun x => Or.inl ⟨x, rfl⟩) (fun p => Or.inr ⟨.inl p, rfl⟩) + (fun p => Or.inr ⟨.inr p, rfl⟩) + exact ⟨m, ⟨T, hT, fun p => hout ⟨p, rfl⟩⟩, hm⟩ + +theorem power_cost {F : Type*} [Field F] {i j k r : ℕ} (h : RankLE F i j k r) : + ∃ D : ℕ, ∃ a : ℕ → ℕ, (∀ t, a (t + 1) ≤ r * a t + D * (max (i * j) (max (i * k) (j * k))) ^ t) ∧ + ∀ t I J K : ℕ, I ≤ i ^ t → J ≤ j ^ t → K ≤ k ^ t → ∃ m, Computes F I J K m ∧ m ≤ a t := by + obtain ⟨D, a, hstep, hpad⟩ := integral_power_cost h + refine ⟨D, a, hstep, fun t I J K hI hJ hK => ?_⟩ + obtain ⟨m, hm, hcost⟩ := hpad t I J K hI hJ hK + exact ⟨m, hm.field (RingHom.id F), hcost⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem power_cost {F : Type*} [Field F] {n r : ℕ} (h : RankLE F n r) : + ∃ D : ℕ, ∃ a : ℕ → ℕ, (∀ j, a (j + 1) ≤ r * a j + D * (n ^ j) ^ 2) ∧ + ∀ j m : ℕ, m ≤ n ^ j → ∃ t, Computes F m t ∧ t ≤ a j := by + obtain ⟨D, a, hstep, hpad⟩ := Rectangle.power_cost h + refine ⟨D, a, ?_, fun j m hm => hpad j m m m hm hm hm⟩ + simpa only [max_self, mul_pow, pow_two] using hstep + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/CircuitCost.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/CircuitCost.lean new file mode 100644 index 0000000000..5c44153579 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/CircuitCost.lean @@ -0,0 +1,115 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Model + +/-! +# Composition and costs of straight-line circuits +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {K : Type*} [CommRing K] {S S' T T' U : Set K} {m n : ℕ} + +private theorem Integral.Build.retains (h : Integral.Build S m T) : S ⊆ T := by + induction h with + | nil => exact Set.Subset.rfl + | add _ _ _ ih | sub _ _ _ ih | mul _ _ _ ih => + exact ih.trans (Set.subset_insert _ _) + +/-- Replay a circuit after any computation making its inputs available. -/ +private theorem Integral.Build.append (h : Integral.Build S m T) (g : Integral.Build T' n U) (ht : + T' ⊆ T) : + ∃ V, Integral.Build S (m + n) V ∧ U ⊆ V := by + induction g with + | nil => exact ⟨T, h, ht⟩ + | add _ hx hy ih => + obtain ⟨V, hV, hv⟩ := ih + exact ⟨_, hV.add (hv hx) (hv hy), Set.insert_subset_insert hv⟩ + | sub _ hx hy ih => + obtain ⟨V, hV, hv⟩ := ih + exact ⟨_, hV.sub (hv hx) (hv hy), Set.insert_subset_insert hv⟩ + | mul _ hx hy ih => + obtain ⟨V, hV, hv⟩ := ih + exact ⟨_, hV.mul (hv hx) (hv hy), Set.insert_subset_insert hv⟩ + +/-- A cost bound on producing a set of values. The registers may contain +additional intermediate values. -/ +def CanMake (S : Set K) (m : ℕ) (T : Set K) : Prop := + ∃ c ≤ m, ∃ U, Integral.Build S c U ∧ T ⊆ U + +namespace CanMake + +theorem of_subset (h : T ⊆ S) : CanMake S 0 T := + ⟨0, le_rfl, S, .nil, h⟩ + +theorem mono_cost (h : CanMake S m T) (hc : m ≤ n) : CanMake S n T := by + obtain ⟨c, hc', V, hv, ht⟩ := h + exact ⟨c, hc'.trans hc, V, hv, ht⟩ + +theorem mono_output (h : CanMake S m T) (ht : T' ⊆ T) : CanMake S m T' := by + obtain ⟨c, hc, V, hv, ht'⟩ := h + exact ⟨c, hc, V, hv, ht.trans ht'⟩ + +theorem trans (h : CanMake S m T) (g : CanMake T n U) : CanMake S (m + n) U := by + obtain ⟨a, ha, A, hA, hT⟩ := h + obtain ⟨b, hb, B, hB, hU⟩ := g + obtain ⟨V, hV, hv⟩ := hA.append hB hT + exact ⟨a + b, Nat.add_le_add ha hb, V, hV, hU.trans hv⟩ + +theorem mono_input (h : CanMake S m T) (hs : S ⊆ S') : CanMake S' m T := by + simpa using (of_subset hs).trans h + +theorem keep (h : CanMake S m T) : CanMake S m (S ∪ T) := by + obtain ⟨c, hc, V, hv, ht⟩ := h + exact ⟨c, hc, V, hv, Set.union_subset hv.retains ht⟩ + +theorem union (h : CanMake S m T) (g : CanMake S n U) : CanMake S (m + n) (T ∪ U) := by + have g' : CanMake (S ∪ T) n U := g.mono_input Set.subset_union_left + exact (h.keep.trans g'.keep).mono_output (Set.union_subset_union_left U Set.subset_union_right) + +theorem iUnion {ι : Type*} [Fintype ι] {T : ι → Set K} + (h : ∀ i, CanMake S m (T i)) : CanMake S (Fintype.card ι * m) (⋃ i, T i) := by + classical + have aux (s : Finset ι) : CanMake S (s.card * m) (⋃ i ∈ s, T i) := by + induction s using Finset.induction_on with + | empty => simpa using of_subset (Set.empty_subset S) + | @insert i s hi ih => + rw [Finset.card_insert_of_notMem hi, Nat.add_mul, Nat.one_mul, add_comm] + simpa using (h i).union ih + simpa using aux Finset.univ + +theorem range {ι : Type*} [Fintype ι] {f : ι → K} + (h : ∀ i, CanMake S m {f i}) : CanMake S (Fintype.card ι * m) (Set.range f) := by + refine (iUnion h).mono_output ?_ + rintro _ ⟨i, rfl⟩ + exact Set.mem_iUnion_of_mem i rfl + +theorem mul {x y : K} (hx : x ∈ S) (hy : y ∈ S) : CanMake S 1 {x * y} := + ⟨1, le_rfl, _, Integral.Build.nil.mul hx hy, Set.singleton_subset_iff.mpr (Set.mem_insert _ _)⟩ + +theorem add {x y : K} (hx : x ∈ S) (hy : y ∈ S) : CanMake S 1 {x + y} := + ⟨1, le_rfl, _, Integral.Build.nil.add hx hy, Set.singleton_subset_iff.mpr (Set.mem_insert _ _)⟩ + +/-- Two operations per term suffice, including the first addition to zero. -/ +theorem linear {ι : Type*} [Fintype ι] {a x : ι → K} + (h0 : 0 ∈ S) (ha : ∀ i, a i ∈ S) (hx : ∀ i, x i ∈ S) : + CanMake S (Fintype.card ι * 2) {∑ i, a i * x i} := by + classical + have aux (s : Finset ι) : CanMake S (s.card * 2) {∑ i ∈ s, a i * x i} := by + induction s using Finset.induction_on with + | empty => simpa using of_subset (Set.singleton_subset_iff.mpr h0) + | @insert i s hi ih => + rw [Finset.card_insert_of_notMem hi, Nat.add_mul, Nat.one_mul, Finset.sum_insert hi] + exact (ih.union (mul (ha i) (hx i))).trans (add (Or.inr rfl) (Or.inl rfl)) + exact aux Finset.univ + +end CanMake +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coefficients.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coefficients.lean new file mode 100644 index 0000000000..4fa8dfb2df --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coefficients.lean @@ -0,0 +1,86 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Mask +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Pairing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.LocalTensor +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexMatrixTensor +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure + +/-! +# Choosing coefficients for the upper bound + +The tensor semiring is monomorphic. To reuse it without assuming +characteristic zero, choose an algebraically closed counterexample if one +exists. The tensor argument only uses the field axioms and algebraic closure. +-/ + +@[expose] public section + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- The data for the closed field construction, including `carrier`, `[field`, `[closed`. -/ +structure ClosedField where + /-- The `ClosedField` component of type `Type`. -/ + carrier : Type + [field : Field carrier] + [closed : IsAlgClosed carrier] + +attribute [instance] ClosedField.field ClosedField.closed + +instance : Nonempty ClosedField := ⟨⟨AlgebraicClosure ℚ⟩⟩ + +/-- The defining condition `∀ A B C : ℕ, 0 < A → 0 < B → 0 < C → Rectangle.exponent F ((A : ℝ) * +B) ((A : ℝ) * C) ((B : ℝ) * C) ≤ ((A : ℝ) + B + C) ^ 2 / 4`. -/ +def Rectangle.DiscreteBound (F : Type*) [Field F] : Prop := + ∀ A B C : ℕ, 0 < A → 0 < B → 0 < C → + Rectangle.exponent F ((A : ℝ) * B) ((A : ℝ) * C) ((B : ℝ) * C) ≤ ((A : ℝ) + B + C) ^ 2 / 4 + +/-- Field-independent consequences of the shared-tag inequality. No +law assumes square equality or any conjecture about spectral contacts. -/ +structure Fulfills (F : Type) [Field F] : Prop where + discrete : Rectangle.DiscreteBound F + density : Rectangle.DensityBound F + cells : Rectangle.CellBound F + binary : Rectangle.Profile.BinaryLaw F + degrees : Rectangle.Sparse.DegreeBound F + +/-- The indexed operation `Classical.epsilon (fun k : ClosedField => ¬ Fulfills k.carrier)`. -/ +def candidate : ClosedField := + Classical.epsilon (fun k : ClosedField => ¬ Fulfills k.carrier) + +/-- Uses `candidate.carrier` as the representation. -/ +abbrev Coeff := candidate.carrier + +theorem closed_laws (h : Fulfills Coeff) (K : Type) [Field K] [IsAlgClosed K] : + Fulfills K := by + by_contra bad + have ex : ∃ k : ClosedField, ¬ Fulfills k.carrier := ⟨⟨K⟩, bad⟩ + exact Classical.epsilon_spec ex h + +theorem exists_nonzero_nodes {F : Type*} [Zero F] [Infinite F] (n : ℕ) : + ∃ nodes : Fin n → F, Function.Injective nodes ∧ ∀ i, nodes i ≠ 0 := by + let e : Fin n ↪ ({0}ᶜ : Set F) := + Fin.valEmbedding.trans ((Set.finite_singleton (0 : F)).infinite_compl.natEmbedding _) + exact ⟨fun i => e i, Subtype.val_injective.comp e.injective, fun i => (e i).property⟩ + +end MatrixMultiplicationAllFields.MatrixExponent + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +/-- Computes the matrix tensor by the application `Tensor.matrixCoefficients (Fin a) (Fin b) +(Fin c)`. -/ +def matrixTensor (a b c : ℕ) : + Tensor Coeff (Fin a × Fin b) (Fin b × Fin c) (Fin c × Fin a) := + Tensor.matrixCoefficients (Fin a) (Fin b) (Fin c) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Add.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Add.lean new file mode 100644 index 0000000000..cf9756bbed --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Add.lean @@ -0,0 +1,211 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Shift + +/-! # Ripple-carry addition of addresses modulo `2^n` -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +/-- Computes the adder input by the application `Wire.pair .bit (.pair (word n) (word n))`. -/ +abbrev adderInput (n : ℕ) := Wire.pair .bit (.pair (word n) (word n)) +/-- Computes the adder result by the application `Wire.pair .bit .bit`. -/ +abbrev adderResult := Wire.pair .bit .bit + +private def full (x : Val (.pair .bit adderResult)) : Val adderResult := + let k := x.1.toNat + x.2.1.toNat + x.2.2.toNat + (decide (k % 2 = 1), decide (2 ≤ k)) + +private theorem full_sum (b p q : Bool) : + b.toNat + p.toNat + q.toNat = (full (b, p, q)).1.toNat + 2 * (full (b, p, q)).2.toNat := by + cases b <;> cases p <;> cases q <;> decide + +private def addBits : (n : ℕ) → Val (adderInput n) → Val (word n) + | 0, _ => () + | n + 1, x => + let z := full (x.1, x.2.1.1, x.2.2.1) + (z.1, addBits n (z.2, x.2.1.2, x.2.2.2)) + +private theorem add_value (n : ℕ) (b : Bool) (x y : Val (word n)) : + ∃ k, b.toNat + Lookup.value n x + Lookup.value n y = + Lookup.value n (addBits n (b, x, y)) + k * 2 ^ n := by + induction n generalizing b with + | zero => exact ⟨b.toNat, by simp [Lookup.value]⟩ + | succ n ih => + let z := full (b, x.1, y.1) + obtain ⟨k, hk⟩ := ih z.2 x.2 y.2 + refine ⟨k, ?_⟩ + simp only [Lookup.value, addBits, pow_succ, ← mul_assoc] + have := full_sum b x.1 y.1 + unfold z at hk + omega + +variable (F : Type) [Field F] + +private theorem addBits_net (n : ℕ) : DNet F (adderInput n) (word n) (addBits n) (256 * n + 1) := by + induction n with + | zero => exact DNet.table F _ _ _ (by decide) + | succ n ih => + have gate : DNet F (.pair .bit adderResult) adderResult full 256 := by + obtain ⟨m, hm, hle⟩ := Net.dense (.pair .bit adderResult) adderResult (fun x y => if full x + = y then (1 : F) else 0) + exact ⟨m, hle, hm⟩ + have r := ((Rewire.id .bit).par (.middle .bit (word n) .bit (word n))).comp (.assoc' _ _ _) + exact ((gate.plug ih).pre r).mono (by omega) + +theorem numeric_add (n : ℕ) : + Circuit F (.pair (.addr n) (.addr n)) (.addr n) (fun x => x.1 + x.2) (10000 * (1 + n)) := by + have seed := ((Lookup.const_net F .bit false).par (DNet.id F (.pair (word n) (word n)))).pre + ((Rewire.unit' _).comp (.swap _ _)) + have h := seed.comp (addBits_net F n) + apply Circuit.of_dnet (.refl _) (.refl _) (h.mono (n := 10000 * (1 + n)) (by simp [wd]; omega)) + intro x + simp only [Equiv.coe_refl, Function.comp_id] + rw [decode_pair, ← code_addr] + congr 1 + apply Fin.ext + change Lookup.value n (addBits n (false, x)) = (Lookup.value n x.1 + Lookup.value n x.2) % 2 ^ n + obtain ⟨k, hk⟩ := add_value n false x.1 x.2 + simp only [Bool.toNat_false, zero_add] at hk + rw [hk, Nat.add_mul_mod_self_right, Nat.mod_eq_of_lt (Control.value_lt ..)] + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- +# A circuit for alternating colours + +Keep the orbit minimum and the next pointer at every position. +Two gathers and a pointwise minimum double the range in one step. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +private abbrev tables (h : ℕ) := Format.pair (Perm h) (Perm h) + +private def tick (h : ℕ) (x : (tables h).obj) : (tables h).obj := + (x.1 ∘ x.1, fun i => min (x.2 i) (x.2 (x.1 i))) + +private theorem ticks (h k : ℕ) (P : B h → B h) : + (tick h)^[k] (P, id) = (jump P k, low P k) := by + induction k with + | zero => rfl + | succ k ih => rw [Function.iterate_succ_apply', ih]; rfl + +variable (F : Type) [Field F] + +theorem cheap_colour (h : ℕ) : + Cheap F h h (.pair (Perm h) (Perm h)) (.vec h .bit) (fun x => colour h x.1 x.2) 50 := by + have hw : (tables h).width ≤ 2 ^ h * (100 + h) ^ 2 := by + simp only [Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add] + gcongr + nlinarith + have hv : (Perm h).width ≤ 2 ^ h * (100 + h) ^ 2 := + le_trans (by rw [Format.width_pair]; omega) hw + have base := Cheap.id F hw + have first := base.fst + have second := base.snd + have minimum : Cheap F 0 h (.pair (.addr h) (.addr h)) (.addr h) (fun x => min x.1 x.2) 3 := + ⟨_, numeric_min F h, by simp only [Format.width_addr, Format.width_pair]; ring_nf; omega⟩ + have cmp : Cheap F 0 h (.pair (.addr h) (.addr h)) .bit (fun x => decide (x.1 < x.2)) 3 := + ⟨_, numeric_lt F h, by + simp only [Format.width_addr, Format.width_pair] + have := Format.width_bit + ring_nf + omega⟩ + have gather := Cheap.lookup F h h (.addr h) le_rfl (Format.width_addr h).le + have stride := (first.pair first).comp gather + have next := (second.pair first).comp gather + have merge := (second.pair next).zip.comp (Cheap.map _ (fun _ : B h => minimum)) + have step : Cheap F h h (tables h) (tables h) (tick h) 15 := + (stride.pair merge).mono (by decide) + have start := next.pair (Cheap.const F hw hv id) + have scan := (start.comp (step.iterate le_rfl)).snd + have mins : Cheap F h h (tables h) (Perm h) (fun x => low (x.2 ∘ x.1) h) 20 := by + convert scan.mono (d := 20) (by decide) using 1 + funext x + exact (congrArg Prod.snd (ticks h h (x.2 ∘ x.1))).symm + have mirror := (mins.pair first).comp gather + exact ((mins.pair mirror).zip.comp (Cheap.map _ (fun _ : B h => cmp))).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- +# Computing balanced edge splits + +Sort edges by endpoint and activity. At every active edge, use the +inverse order to find its rank, pair neighboring ranks, and retrieve +the partner. The two resulting arrays determine the colouring. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +/-- Computes the graph input by the application `Format.pair (.pair (.vec h (.addr k)) (.vec h +(.addr k))) (.vec h .bit)`. -/ +abbrev GraphInput (h k : ℕ) := Format.pair (.pair (.vec h (.addr k)) (.vec h (.addr k))) (.vec h + .bit) + +theorem graph_width (h k : ℕ) : (GraphInput h k).width = 2 ^ h * (2 * k + 1) := by + simp only [Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit]; ring + +variable (F : Type) [Field F] + +theorem cheap_select (n : ℕ) : + Cheap F 0 n (.pair (.pair (.addr n) (.addr n)) .bit) (.addr n) + (fun x => if x.2 then x.1.1 else x.1.2) 3 := + ⟨_, numeric_select F n, by + simp only [Format.width_pair, Format.width_addr] + rw [Format.width_bit]; ring_nf; omega⟩ + +private abbrev endInput (h k : ℕ) := Format.pair (.vec h (.addr k)) (.vec h .bit) + +theorem cheap_partner (h k : ℕ) : + Cheap F h (h + k) (.pair (.vec h (.addr k)) (.vec h .bit)) (Perm h) + (fun x => partner x.1 x.2) 120 := by + have hi : (endInput h k).width ≤ 2 ^ h * (100 + (h + k)) ^ 1 := by + simp only [Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add, pow_one] + rw [Format.width_bit]; apply Nat.mul_le_mul_left; omega + have hp : (Perm h).width ≤ 2 ^ h * (100 + (h + k)) ^ 1 := by + simp only [Format.width_vec, Format.width_addr, pow_one]; apply Nat.mul_le_mul_left; omega + have base := Cheap.id F hi + have self := Cheap.const F hi hp id + have flip := Cheap.const F hi hp (toggle h) + have get := Cheap.lookup F h (h + k) (.addr h) (by omega) (by rw [Format.width_addr]; omega) + have perm := cheap_permutation F h k + obtain ⟨f, hf, he⟩ := cheap_inverse F h + have inv' : Cheap F h (h + k) (endInput h k) (Perm h) + (fun x => ⇑(permutation x.1 x.2).symm) 101 := by + convert (perm.comp (hf.widen (l := h + k) (by omega))).mono (d := 101) (by decide) using 1 + funext x + exact (he _).symm + have other := (perm.pair ((flip.pair inv').comp get)).comp get + have args := ((other.pair self).zip.pair base.snd).zip + have choose := Cheap.map _ (fun _ : B h => (cheap_select F h).widen (l := h + k) (by omega)) + exact (args.comp choose).mono (by decide) + +theorem cheap_split (h k : ℕ) : + Cheap F h (h + k) (GraphInput h k) (.vec h .bit) (fun x => split x.1.1 x.1.2 x.2) 130 := by + have hw : (GraphInput h k).width ≤ 2 ^ h * (100 + (h + k)) ^ 2 := by + rw [graph_width]; apply Nat.mul_le_mul_left; ring_nf; omega + have base := Cheap.id F hw + have other := cheap_partner F h k + have left := (base.fst.fst.pair base.snd).comp other + have right := (base.fst.snd.pair base.snd).comp other + exact ((left.pair right).comp ((cheap_colour F h).widen (l := h + k) (by omega))).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Chart.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Chart.lean new file mode 100644 index 0000000000..42d5424aba --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Chart.lean @@ -0,0 +1,207 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Formula +public import Mathlib.Data.Fintype.EquivFin + +/-! +# Three-stage routing on a packed product + +At each end of an edge, add the edge colour to the fixed offset of +its fiber. Proper colouring makes both assignments permutations. +Composing one with the inverse of the other moves between fibers +while preserving colour. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable {h d : ℕ} {X A : Type} [Fintype X] [Fintype A] + +private def pack (hs : Fintype.card A * d ≤ 2 ^ h) : A × Fin d ↪ B h := + (((Fintype.equivFin A).prodCongr (.refl _)).trans finProdFinEquiv).toEmbedding.trans + (Fin.castLEEmb hs) + +private def offset (hs : Fintype.card A * d ≤ 2 ^ h) (hd : 0 < d) : A ↪ B h := + ⟨fun i => pack hs (i, ⟨0, hd⟩), fun _ _ he => congrArg Prod.fst ((pack hs).injective he)⟩ + +private theorem offset_add (hs : Fintype.card A * d ≤ 2 ^ h) (hd : 0 < d) + (i : A) (j : B h) (hj : j.val < d) : + offset hs hd i + j = pack hs (i, ⟨j.val, hj⟩) := by + apply Fin.ext + change ((finProdFinEquiv (Fintype.equivFin A i, ⟨0, hd⟩)).val + j.val) % 2 ^ h = + (finProdFinEquiv (Fintype.equivFin A i, ⟨j.val, hj⟩)).val + have hl := (finProdFinEquiv (Fintype.equivFin A i, ⟨j.val, hj⟩)).isLt.trans_le hs + simp only [finProdFinEquiv_apply_val, zero_add] at hl ⊢ + rw [Nat.add_comm, Nat.mod_eq_of_lt hl] + +omit [Fintype X] in +private theorem degree_packed [Finite X] (t : X ≃ A × Fin d) (e : X ↪ B h) (o : A ↪ B h) + (mask : B h → Bool) (hm : ∀ i, mask i = true ↔ ∃ z, e z = i) + (f : B h → B h) (hf : ∀ i, f (e i) = o (t i).1) (j : B h) : + degree f mask j = if j ∈ Finset.univ.image o then d else 0 := by + classical + let : Fintype X := Fintype.ofFinite X + unfold degree + by_cases hi : j ∈ Finset.univ.image o + · rw [ite_eq_left hi] + obtain ⟨u, _, rfl⟩ := Finset.mem_image.mp hi + let z (a : Fin d) := e (t.symm (u, a)) + have hz : Function.Injective z := fun _ _ hh => + congrArg Prod.snd (t.symm.injective (e.injective hh)) + have he : (Finset.univ.filter (fun i => mask i = true ∧ f i = o u)) = Finset.univ.image z := by + ext i + simp only [Finset.mem_image, Finset.mem_filter, Finset.mem_univ, true_and, hm] + constructor + · rintro ⟨⟨v, rfl⟩, hv⟩ + rw [hf] at hv + refine ⟨(t v).2, ?_⟩ + simp [z, ← o.injective hv] + · rintro ⟨a, rfl⟩ + exact ⟨⟨t.symm (u, a), rfl⟩, by simp [z, hf]⟩ + rw [he, Finset.card_image_of_injective _ hz, Finset.card_fin] + · rw [ite_eq_right hi, Finset.card_eq_zero, Finset.eq_empty_iff_forall_notMem] + intro i hit + obtain ⟨⟨v, rfl⟩, hv⟩ := And.imp_left (hm i).mp (Finset.mem_filter.mp hit).2 + exact hi (Finset.mem_image.mpr ⟨(t v).1, Finset.mem_univ _, (hf v).symm.trans hv⟩) + +omit [Fintype X] in +private theorem inverse_agrees (e : X ↪ B h) (v : Equiv.Perm X) (f : B h → B h) + (hf : ∀ i, f (e i) = e (v i)) (hout : ∀ i, (¬∃ z, e z = i) → f i = i) + (inv : (B h → B h) → (B h → B h)) (hi : ∀ g : Equiv.Perm (B h), inv g = ⇑g.symm) : + ∀ i, inv f (e (v i)) = e i := by + have surj : Function.Surjective f := by + intro j + by_cases hh : ∃ i, e i = j + · obtain ⟨i, rfl⟩ := hh + exact ⟨e (v.symm i), by simp [hf]⟩ + · exact ⟨j, hout _ hh⟩ + let g := Equiv.ofBijective f (Finite.surjective_iff_bijective.mp surj) + intro i + rw [← hf] + change inv g (g (e i)) = e i + rw [hi, Equiv.symm_apply_apply] + +omit [Fintype A] [Fintype X] in +private theorem product_routes [Finite A] [Finite X] [Nonempty X] (t : X ≃ A × Fin d) (e : X ↪ B h) + (inv : (B h → B h) → (B h → B h)) (hi : ∀ g : Equiv.Perm (B h), inv g = ⇑g.symm) : + ∃ p : Chart h, ∀ (g : Equiv.Perm X) (y : B h → B h), (∀ i, y (e i) = e (g i)) → + ∃ w v : Equiv.Perm X, (∀ i, (t (w i)).1 = (t i).1 ∧ + (t (v i)).1 = (t (g i)).1 ∧ (t (w i)).2 = (t (v i)).2) ∧ + (∀ i, (p.run inv y).1 (e (v i)) = e (g i)) ∧ + (∀ i, (p.run inv y).2.1 (e (w i)) = e (v i)) ∧ + (∀ i, (p.run inv y).2.2 (e i) = e (w i)) := by + classical + let : Fintype A := Fintype.ofFinite A + let : Fintype X := Fintype.ofFinite X + let z := t (Classical.arbitrary X) + let _ : Nonempty (A × Fin d) := ⟨z⟩ + have hd : 0 < d := Nat.zero_lt_of_lt z.2.isLt + have hs : Fintype.card A * d ≤ 2 ^ h := by + simpa [Fintype.card_congr t] using Fintype.card_le_of_injective _ e.injective + have hd' : d ≤ 2 ^ h := + (Nat.le_mul_of_pos_left _ (Fintype.card_pos_iff.mpr ⟨z.1⟩)).trans hs + let o := offset hs hd + let p : Chart h := + { base := fun i => o (t (Function.invFun e i)).1 + location := fun i => e (t.symm (Function.invFun (pack hs) i)) + support := Finset.univ.image o + mask := fun i => decide (∃ j, e j = i) + degree := d } + have hmask (i) : p.mask i = true ↔ ∃ j, e j = i := decide_eq_true_iff + have live (i) : p.mask (e i) = true := (hmask _).mpr ⟨i, rfl⟩ + have base (i) : p.base (e i) = o (t i).1 := by + simp only [p, Function.leftInverse_invFun e.injective i] + have loc (a : A) (i : B h) (hi : i.val < d) : + p.location (o a + i) = e (t.symm (a, ⟨i.val, hi⟩)) := by + rw [offset_add hs hd a i hi] + exact congrArg (e ∘ t.symm) (Function.leftInverse_invFun (pack hs).injective _) + refine ⟨p, fun g y hy => ?_⟩ + have target (i) : (p.base ∘ y) (e i) = o (t (g i)).1 + := by simp only [Function.comp_apply, hy, base] + have reg : Regular p.support d p.base (p.base ∘ y) p.mask := + ⟨degree_packed t e o p.mask hmask _ base, + degree_packed (g.trans t) e o p.mask hmask _ target⟩ + have bound : p.support.card * d ≤ 2 ^ h := by + simpa only [p, Finset.card_image_of_injective _ o.injective, Finset.card_univ] using hs + have col := edge_coloring p.support d hd' bound p.base (p.base ∘ y) p.mask reg + let c (i : X) : Fin d := ⟨(p.label y (e i)).val, (col _ (live i)).1⟩ + have route (f : B h → B h) (u : X → A) (hu : ∀ i, f (e i) = o (u i)) + (hf : f = p.base ∨ f = p.base ∘ y) : + ∃ v : Equiv.Perm X, (∀ i, t (v i) = (u i, c i)) ∧ + (∀ i, p.route f (p.label y) (e i) = e (v i)) ∧ + (∀ i, inv (p.route f (p.label y)) (e (v i)) = e i) := by + let move i := t.symm (u i, c i) + have inject : Function.Injective move := by + intro i j he + obtain ⟨hl, hr⟩ := Prod.mk.inj (t.symm.injective he) + have ends : f (e i) = f (e j) := by rw [hu, hu, hl] + apply e.injective + apply (col _ (live i)).2 _ (live j) (Fin.ext (congrArg (fun z : Fin d => z.val) hr)) + rcases hf with rfl | rfl + · exact .inl ends + · exact .inr ends + let v := Equiv.ofBijective move inject.bijective_of_finite + have hv (i) : p.route f (p.label y) (e i) = e (v i) := by + rw [Chart.route, ite_eq_left (live i), hu, loc _ _ (c i).isLt] + rfl + exact ⟨v, fun _ => t.apply_symm_apply _, hv, + inverse_agrees e v _ hv (fun i h => ite_eq_right (mt (hmask i).mp h)) inv hi⟩ + obtain ⟨w, hw, hl, hil⟩ := route _ (fun i => (t i).1) base (.inl rfl) + obtain ⟨v, hv, hr, hir⟩ := route _ (fun i => (t (g i)).1) target (.inr rfl) + refine ⟨w, v, fun i => by simp only [hw, hv, and_self], ?_, ?_, hl⟩ + · intro i + exact (congrArg y (hir i)).trans (hy i) + · intro i + exact (congrArg (p.right y) (hil i)).trans (hr i) + +theorem chart_exists (h : ℕ) (X C A D : Type) [Finite X] [Finite C] [Finite A] [Finite D] + (s : X ≃ C × (A × D)) (e : X ↪ B h) (inv : (B h → B h) → (B h → B h)) + (hi : ∀ g : Equiv.Perm (B h), inv g = ⇑g.symm) : + ∃ p : Chart h, ∀ (g : Equiv.Perm X), (∀ i, (s (g i)).1 = (s i).1) → + ∀ y : (Perm h).obj, (∀ i, y (e i) = e (g i)) → + ∃ u v w : Equiv.Perm X, g = u * v * w ∧ + (∀ i, (s (u i)).1 = (s i).1 ∧ (s (u i)).2.1 = (s i).2.1) ∧ + (∀ i, (s (v i)).1 = (s i).1 ∧ (s (v i)).2.2 = (s i).2.2) ∧ + (∀ i, (s (w i)).1 = (s i).1 ∧ (s (w i)).2.1 = (s i).2.1) ∧ + (∀ i, (p.run inv y).1 (e i) = e (u i)) ∧ (∀ i, (p.run inv y).2.1 (e i) = e (v i)) ∧ + (∀ i, (p.run inv y).2.2 (e i) = e (w i)) := by + classical + let : Fintype A := Fintype.ofFinite A + let : Fintype C := Fintype.ofFinite C + let : Fintype D := Fintype.ofFinite D + let : Fintype X := Fintype.ofFinite X + rcases isEmpty_or_nonempty X with _ | _ + · refine ⟨⟨id, id, fun _ => false, ∅, 0⟩, fun g _ _ _ => ⟨g, 1, 1, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩⟩ + · simp + all_goals exact fun i => isEmptyElim i + let t := (s.trans (Equiv.prodAssoc C A D).symm).trans + ((Equiv.refl (C × A)).prodCongr (Fintype.equivFin D)) + obtain ⟨p, hp⟩ := product_routes t e inv hi + refine ⟨p, fun g hg y hy => ?_⟩ + obtain ⟨w, z, hz, hu, hv, hw⟩ := hp g y hy + have first (i) : (s (w i)).1 = (s i).1 ∧ (s (w i)).2.1 = (s i).2.1 := + Prod.mk.inj (hz i).1 + have last (i) : (s (g i)).1 = (s (z i)).1 ∧ (s (g i)).2.1 = (s (z i)).2.1 := + Prod.mk.inj (hz i).2.1.symm + have middle (i) : (s (z i)).1 = (s (w i)).1 ∧ (s (z i)).2.2 = (s (w i)).2.2 := + ⟨(last i).1.symm.trans ((hg i).trans (first i).1.symm), + (Fintype.equivFin D).injective (hz i).2.2.symm⟩ + refine ⟨g * z⁻¹, z * w⁻¹, w, by simp [mul_assoc], ?_, ?_, first, ?_, ?_, hw⟩ + · intro i + simpa using last (z.symm i) + · intro i + simpa using middle (w.symm i) + · intro i + simpa using hu (z.symm i) + · intro i + simpa using hv (w.symm i) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Edges.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Edges.lean new file mode 100644 index 0000000000..e45608c46d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Edges.lean @@ -0,0 +1,233 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Shift + +/-! +# Parallel bisection of a regular bipartite graph + +At odd degree a perfect matching takes the last colour. In the even +remainder, append the split bit to both endpoints. This encodes *both* +subproblems on the original edge array. One recursive call suffices. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable {h k : ℕ} + +/-- Returns `fun _ => false` when `d % 2 = 0` holds, and `matching S d L R x` otherwise. -/ +def retired (S : Finset (B k)) (d : ℕ) (L R : B h → B k) + (x : B h → Bool) : B h → Bool := + if d % 2 = 0 then fun _ => false else matching S d L R x + +/-- The value specified by `x i && !y i`. -/ +def rest (x y : B h → Bool) (i : B h) := x i && !y i + +/-- The selected finite family `(S ×ˢ Finset.univ).image (Function.uncurry double)`. -/ +def enlarge (S : Finset (B k)) : Finset (B (k + 1)) := + (S ×ˢ Finset.univ).image (Function.uncurry double) + +/-- Computes the next end by the application `double (L i) (b i)`. -/ +def nextEnd (L : B h → B k) (b : B h → Bool) (i : B h) := + double (L i) (b i) + +/-- The quantity computed by `⟨(if z then d - 1 else 2 * j.val + b.toNat) % 2 ^ h, Nat.mod_lt _ +(Nat.two_pow_pos h)⟩`. -/ +def combine (d : ℕ) (z b : Bool) (j : B h) : B h := + ⟨(if z then d - 1 else 2 * j.val + b.toNat) % 2 ^ h, Nat.mod_lt _ (Nat.two_pow_pos h)⟩ + +/-- In the case `0 => fun _`, this construction gives `0`. -/ +def recurse {k : ℕ} (fuel : ℕ) (S : Finset (B k)) (d : ℕ) (L R : B h → B k) + (x : B h → Bool) : B h → B h := + match fuel with + | 0 => fun _ => 0 + | n + 1 => + let y := retired S d L R x + let a := rest x y + let b := split L R a + let c := recurse n (enlarge S) (d / 2) (nextEnd L b) (nextEnd R b) a + fun i => combine d (y i) (b i) (c i) + +/-- The quantity computed by `recurse (h + 1) S d L R x`. -/ +def colours (S : Finset (B k)) (d : ℕ) (L R : B h → B k) + (x : B h → Bool) : B h → B h := + recurse (h + 1) S d L R x + +variable {S : Finset (B k)} {d : ℕ} {L R : B h → B k} +variable {x y : B h → Bool} {i j : B h} + +private theorem degree_pos (hi : x i = true) : 0 < degree L x (L i) := + Finset.card_pos.mpr ⟨i, by simp [hi]⟩ + +private theorem Regular.degree_pos (he : Regular S d L R x) (hi : x i = true) : 0 < d := by + have hp := Coloring.degree_pos (L := L) hi + rw [he.1] at hp + split_ifs at hp <;> omega + +private theorem Regular.unique (he : Regular S d L R x) (hd : d ≤ 1) + (hi : x i = true) (hj : x j = true) (hp : L i = L j ∨ R i = R j) : i = j := by + have aux (f : B h → B k) (hf : ∀ u, degree f x u = if u ∈ S then d else 0) + (eq : f i = f j) : i = j := by + have hn : degree f x (f i) ≤ 1 := by rw [hf]; split <;> omega + exact Finset.card_le_one.mp hn i (by simp [hi]) j (by simp [hj, eq]) + exact hp.elim (aux L he.1) (aux R he.2) + +private theorem outgoing (he : Regular S d L R x) (hs : S.card * d ≤ 2 ^ h) : + Regular S (d % 2) L R (retired S d L R x) ∧ ∀ i, retired S d L R x i = true → x i = true := by + by_cases hd : d % 2 = 0 + · simp [retired, hd, Regular, degree] + · rw [retired, ite_eq_right hd, show d % 2 = 1 by omega] + exact he.matching (by omega) hs + +private theorem remaining (he : Regular S d L R x) (hy : Regular S (d % 2) L R y) + (hsub : ∀ i, y i = true → x i = true) : + Regular S (2 * (d / 2)) L R (rest x y) := by + have aux (f : B h → B k) (j : B k) : + degree f (rest x y) j + degree f y j = degree f x j := by + let U := Finset.univ.filter (fun i => x i = true ∧ f i = j) + let V := Finset.univ.filter (fun i => y i = true ∧ f i = j) + have h : V ⊆ U := by + intro i hi + obtain ⟨hi, he⟩ := (Finset.mem_filter.mp hi).2 + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, hsub i hi, he⟩ + have hz : Finset.univ.filter (fun i => rest x y i = true ∧ f i = j) = U \ V := by + ext i + cases e : y i <;> simp [U, V, rest, e] + unfold degree + rw [hz] + exact Finset.card_sdiff_add_card_eq_card h + constructor + · intro j + have := aux L j + rw [he.1, hy.1] at this + split_ifs at * <;> omega + · intro j + have := aux R j + rw [he.2, hy.2] at this + split_ifs at * <;> omega + +private theorem double_eq {i j : B k} {a b : Bool} : + double i a = double j b ↔ i = j ∧ a = b := by + rw [Fin.ext_iff] + cases a <;> cases b <;> simp [double, Fin.ext_iff] <;> omega + +private theorem double_surj (i : B (k + 1)) : ∃ j : B k, ∃ b, double j b = i := by + have hi := i.isLt + simp only [pow_succ] at hi + refine ⟨⟨i.val / 2, by omega⟩, decide (i.val % 2 = 1), Fin.ext ?_⟩ + by_cases e : i.val % 2 = 1 <;> simp [double, e] <;> omega + +private theorem mem_enlarge (u : B k) (b : Bool) : double u b ∈ enlarge S ↔ u ∈ S := by + simp only [enlarge, Finset.mem_image, Finset.mem_product, Finset.mem_univ, and_true] + constructor + · rintro ⟨⟨i, z⟩, hi, he⟩ + exact (double_eq.mp he).1 ▸ hi + · exact fun h => ⟨(u, b), h, rfl⟩ + +private theorem enlarge_cost (hs : S.card * d ≤ 2 ^ h) : (enlarge S).card * (d / 2) ≤ 2 ^ h := by + have he : (enlarge S).card ≤ S.card * 2 := + Finset.card_image_le.trans_eq (by simp) + calc + _ ≤ S.card * 2 * (d / 2) := Nat.mul_le_mul_right _ he + _ ≤ S.card * d := by rw [mul_assoc]; exact Nat.mul_le_mul_left _ (by omega) + _ ≤ _ := hs + +private theorem bisect (he : Regular S (2 * d) L R x) : + Regular (enlarge S) d (nextEnd L (split L R x)) (nextEnd R (split L R x)) x := by + have even (f : B h → B k) (hf : ∀ j, degree f x j = if j ∈ S then 2 * d else 0) : + EvenFibers f x := by + intro j + change Even (degree f x j) + rw [hf] + split + · exact ⟨d, two_mul d⟩ + · exact ⟨0, rfl⟩ + have eq (u : B (k + 1)) : + degree (nextEnd L (split L R x)) x u = (if u ∈ enlarge S then d else 0) ∧ + degree (nextEnd R (split L R x)) x u = (if u ∈ enlarge S then d else 0) := by + obtain ⟨j, b, rfl⟩ := double_surj u + obtain ⟨hl, hr⟩ := split_balanced (even L he.1) (even R he.2) j b + change _ = degree L x j at hl + change _ = degree R x j at hr + rw [he.1] at hl + rw [he.2] at hr + simp only [degree, nextEnd, mem_enlarge, double_eq] + split_ifs at * <;> omega + exact ⟨fun u => (eq u).1, fun u => (eq u).2⟩ + +private def Proper (d : ℕ) (L R : B h → B k) (x : B h → Bool) (c : B h → B h) := + ∀ i, x i = true → (c i).val < d ∧ + ∀ j, x j = true → c i = c j → (L i = L j ∨ R i = R j) → i = j + +private theorem merge_proper {b : B h → Bool} {c : B h → B h} (hd : d ≤ 2 ^ h) + (hy : Regular S (d % 2) L R y) + (hc : Proper (d / 2) (nextEnd L b) (nextEnd R b) (rest x y) c) : + Proper d L R x (fun i => combine d (y i) (b i) (c i)) := by + let out i := combine d (y i) (b i) (c i) + have literal (i : B h) (hi : x i = true) : + (y i = true ∧ d % 2 = 1 ∧ (out i).val = d - 1) ∨ + (rest x y i = true ∧ (out i).val = 2 * (c i).val + (b i).toNat ∧ + (out i).val < 2 * (d / 2)) := by + cases ey : y i + · have hi' : rest x y i = true := by simp [rest, hi, ey] + have hb : (b i).toNat < 2 := by cases b i <;> decide + have ht := (hc i hi').1 + have he : (out i).val = 2 * (c i).val + (b i).toNat := by + simp only [out, combine, ey, Bool.false_eq_true, ite_false] + exact Nat.mod_eq_of_lt (by omega) + exact .inr ⟨hi', he, by omega⟩ + · have ht := hy.degree_pos ey + refine .inl ⟨rfl, by omega, ?_⟩ + simp only [out, combine, ey, ite_true] + exact Nat.mod_eq_of_lt (by omega) + intro i hi + change (out i).val < d ∧ _ + refine ⟨by rcases literal i hi with h | h <;> omega, ?_⟩ + intro j hj he eq + change out i = out j at he + have hv := congrArg Fin.val he + rcases literal i hi with ⟨hi, hdi, ei⟩ | ⟨hi, ei, hdi⟩ <;> + rcases literal j hj with ⟨hj, hdj, ej⟩ | ⟨hj, ej, hdj⟩ + · exact hy.unique (by omega) hi hj eq + · omega + · omega + · have ee : double (c i) (b i) = double (c j) (b j) := + Fin.ext (ei.symm.trans (hv.trans ej)) + obtain ⟨ec, eb⟩ := double_eq.mp ee + apply (hc i hi).2 j hj ec + exact eq.imp (fun h => double_eq.mpr ⟨h, eb⟩) (fun h => double_eq.mpr ⟨h, eb⟩) + +private theorem proper (fuel : ℕ) (hd : d ≤ 2 ^ h) (hf : d < 2 ^ fuel) + (hs : S.card * d ≤ 2 ^ h) (he : Regular S d L R x) : + Proper d L R x (recurse fuel S d L R x) := by + induction fuel generalizing k d x with + | zero => + intro i hi + have := he.degree_pos hi + simp only [pow_zero] at hf + omega + | succ fuel ih => + obtain ⟨hy, hsub⟩ := outgoing he hs + have hr := bisect (remaining he hy hsub) + rw [pow_succ] at hf + have hp := ih (d := d / 2) (by omega) (by omega) (enlarge_cost hs) hr + rw [recurse] + exact merge_proper hd hy hp + +theorem edge_coloring {h k : ℕ} (S : Finset (B k)) (d : ℕ) (hd : d ≤ 2 ^ h) + (hs : S.card * d ≤ 2 ^ h) (L R : B h → B k) (x : B h → Bool) (he : Regular S d L R x) : + ∀ i, x i = true → (colours S d L R x i).val < d ∧ + ∀ j, x j = true → colours S d L R x i = colours S d L R x j → + (L i = L j ∨ R i = R j) → i = j := + proper (h + 1) hd (by rw [pow_succ]; have := Nat.two_pow_pos h; omega) hs he + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Formula.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Formula.lean new file mode 100644 index 0000000000..a3a4c1903a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Formula.lean @@ -0,0 +1,125 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Edges +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort + +/-! # Indexing the three stages of a product permutation -/ + +@[expose] public section + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +/-- The data for the chart construction, including `base`, `location`, `mask`, `support`, +`degree`. -/ +structure Chart (h : ℕ) where + /-- The `Chart` component of type `B h → B h`. -/ + base : B h → B h + /-- The `Chart` component of type `B h → B h`. -/ + location : B h → B h + /-- The `Chart` component of type `B h → Bool`. -/ + mask : B h → Bool + /-- The active indices of type `Finset (B h)`. -/ + support : Finset (B h) + /-- The incidence count carried by `Chart`, with type `ℕ`. -/ + degree : ℕ + +namespace Chart + +variable {h : ℕ} (p : Chart h) + +/-- Colors edges joining the base classes before and after the input permutation. -/ +def label (y : B h → B h) := colours p.support p.degree p.base (p.base ∘ y) p.mask + +/-- Moves each active position to the location indexed by its class and color. -/ +def route (b c : B h → B h) (i : B h) : B h := + if p.mask i then p.location (b i + c i) else i + +/-- Routes the positions using their initial base classes. -/ +def left (y : B h → B h) := p.route p.base (p.label y) +/-- Routes the positions using the base classes after the input permutation. -/ +def right (y : B h → B h) := p.route (p.base ∘ y) (p.label y) + +/-- Produces the three routing stages using the supplied inversion operation. -/ +def run (inv : (B h → B h) → (B h → B h)) (y : B h → B h) := + (y ∘ inv (p.right y), p.right y ∘ inv (p.left y), p.left y) + +end Chart +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +/- +# Checking relations on a finite alphabet in parallel + +Reject malformed encodings. The relation can be an arbitrary finite +table. Only the address inputs have unbounded width. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable {V : Type*} {t q : ℕ} (e : V ↪ B q) (R : V → (B t → V) → Prop) + +open scoped Classical in +/-- Embeds `V` into `B (Fintype.card V)`. -/ +def encode (V : Type*) [Fintype V] : V ↪ B (Fintype.card V) := + (Fintype.equivFin V).toEmbedding.trans (Fin.castLEEmb Nat.lt_two_pow_self.le) + +open scoped Classical in +/-- Tests whether `∃ y z, e y = x.1 ∧ e ∘ z = x.2 ∧ R y z` holds. -/ +def test (x : B q × (B t → B q)) : Bool := + decide (∃ y z, e y = x.1 ∧ e ∘ z = x.2 ∧ R y z) + +open scoped Classical in +/-- The indexed operation `test e R (x.1 i, fun j => x.1 (x.2 j i))`. -/ +def check (h : ℕ) (x : (B h → B q) × (B t → B h → B h)) (i : B h) : Bool := + test e R (x.1 i, fun j => x.1 (x.2 j i)) + +open scoped Classical in +theorem check_iff (h : ℕ) (x : B h → B q) (g : B t → B h → B h) : + (∀ i, check e R h (x, g) i = true) ↔ + ∃! y : B h → V, e ∘ y = x ∧ ∀ i, R (y i) (fun j => y (g j i)) := by + simp only [check, test, decide_eq_true_eq] + constructor + · intro H + choose y z hy hz he using H + refine ⟨y, ⟨funext hy, fun i => ?_⟩, fun w hw => funext fun i => ?_⟩ + · have hh : z i = fun j => y (g j i) := + funext fun j => e.injective ((congrFun (hz i) j).trans (hy _).symm) + rw [← hh] + exact he i + · exact e.injective ((congrFun hw.1 i).trans (hy i).symm) + · rintro ⟨y, ⟨rfl, hy⟩, _⟩ i + exact ⟨y i, fun j => y (g j i), rfl, rfl, hy i⟩ + +open scoped Classical in +theorem cheap_check (F : Type) [Field F] : + ∃ k₀, ∀ h k : ℕ, h ≤ k → k₀ ≤ k → + Cheap F h k (.pair (.vec h (.addr q)) (.vec t (Perm h))) (.vec h .bit) + (check e R h) 17 := by + let A := Format.addr q + let Y := Format.pair A (.vec t A) + let k₀ := 2 * Y.width + Format.bit.width + Install.localCost Y.width * Format.bit.width + refine ⟨max k₀ (max A.width (2 ^ t)), fun h k hh hk => ?_⟩ + obtain ⟨hl, ht⟩ := max_le_iff.mp hk + obtain ⟨ha, ht⟩ := max_le_iff.mp ht + let X := Format.pair (.vec h A) (.vec t (Perm h)) + have g := Cheap.neighbors F A h k t hh ha ht + have hx : X.width ≤ 2 ^ h * (100 + k) ^ 12 := by + obtain ⟨m, _, hm⟩ := g + exact (Nat.le_add_right _ _).trans ((Nat.le_add_right _ _).trans hm) + have hf : Cheap F 0 k Y .bit (test e R) 1 := Cheap.fixed F _ hl + have hv := Cheap.map (A := Y) (D := .bit) (h := h) (fun _ => test e R) (fun _ => hf) + have ans := (((Cheap.id F hx).fst.pair g).zip).comp hv + simp only [Function.comp_def, id_eq] at ans + exact ans + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Matching.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Matching.lean new file mode 100644 index 0000000000..6bf2037cf4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Matching.lean @@ -0,0 +1,173 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Shift +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Logic.Equiv.Fin.Basic + +/-! +# A perfect matching at arbitrary positive degree + +Enlarge the edge array by one bit. Its second half contains a fixed +dummy matching of the supported vertices. Give each real and dummy +edge the quotient and remainder, respectively, when a power of two +is divided by the degree. Repeated halving deletes every dummy edge. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable {h k : ℕ} + +/-- The indexed operation `(Finset.univ.filter fun i => x i = true ∧ f i = j).card`. -/ +def degree (f : Fin (2 ^ h) → Fin (2 ^ k)) (x : Fin (2 ^ h) → Bool) (j : Fin (2 ^ k)) := + (Finset.univ.filter fun i => x i = true ∧ f i = j).card + +/-- Requires `(∀ j, degree L x j = if j ∈ S then d else 0) ∧ (∀ j, degree R x j = if j ∈ S then +d else 0)`. -/ +def Regular (S : Finset (Fin (2 ^ k))) (d : ℕ) (L R : Fin (2 ^ h) → Fin (2 ^ k)) + (x : Fin (2 ^ h) → Bool) : Prop := + (∀ j, degree L x j = if j ∈ S then d else 0) ∧ + (∀ j, degree R x j = if j ∈ S then d else 0) + +/-- Reindexes `Fin (2 ^ h) ⊕ Fin (2 ^ h)` and `Fin (2 ^ (h + 1))` by an equivalence. -/ +def halves (h : ℕ) : Fin (2 ^ h) ⊕ Fin (2 ^ h) ≃ Fin (2 ^ (h + 1)) := + finSumFinEquiv.trans (finCongr (by rw [pow_succ, mul_two])) + +/-- Chooses the operation for the left or right summand. -/ +def join {α : Type} (f g : Fin (2 ^ h) → α) := Sum.elim f g ∘ (halves h).symm + +/-- Returns `(S.equivFin.symm ⟨i.val, ha⟩).val` when `ha : i.val < S.card` holds, and `0` +otherwise. -/ +def dummyLabel (S : Finset (Fin (2 ^ k))) (i : Fin (2 ^ h)) : Fin (2 ^ k) := + if ha : i.val < S.card then (S.equivFin.symm ⟨i.val, ha⟩).val else 0 + +/-- The indexed operation `join (fun _ => false) (fun _ => true)`. -/ +def dummy (h : ℕ) : Fin (2 ^ (h + 1)) → Bool := join (fun _ => false) (fun _ => true) + +/-- The value specified by `join (fun i => if x i then 2 ^ (h + 1) / d else 0) (fun i => if +i.val < S.card then 2 ^ (h + 1) % d else 0)`. -/ +def weights (S : Finset (Fin (2 ^ k))) (d : ℕ) (x : Fin (2 ^ h) → Bool) := + join (fun i => if x i then 2 ^ (h + 1) / d else 0) + (fun i => if i.val < S.card then 2 ^ (h + 1) % d else 0) + +/-- The matching of type `Bool` for the given inputs. -/ +def matching (S : Finset (Fin (2 ^ k))) (d : ℕ) (L R : Fin (2 ^ h) → Fin (2 ^ k)) + (x : Fin (2 ^ h) → Bool) (i : Fin (2 ^ h)) : Bool := + let y := (halve (join L (dummyLabel S)) (join R (dummyLabel S)) (dummy h))^[h + 1] + (weights S d x) + decide (y (halves h (.inl i)) = 1) + +private theorem sum_halves (m : Fin (2 ^ (h + 1)) → ℕ) : + ∑ i, m i = ∑ i, m (halves h (.inl i)) + ∑ i, m (halves h (.inr i)) := by + rw [← (halves h).sum_comp, Fintype.sum_sum_type] + +private theorem stock_join (f g : Fin (2 ^ h) → Fin (2 ^ k)) (m : Fin (2 ^ (h + 1)) → ℕ) + (j : Fin (2 ^ k)) : + stock (join f g) m j = stock f (fun i => m (halves h (.inl i))) j + + stock g (fun i => m (halves h (.inr i))) j := by + simp only [stock, Finset.sum_filter] + rw [sum_halves] + simp only [join, Function.comp_apply, Equiv.symm_apply_apply, Sum.elim_inl, Sum.elim_inr] + +private theorem stock_uniform (f : Fin (2 ^ h) → Fin (2 ^ k)) (x : Fin (2 ^ h) → Bool) + (a : ℕ) (j : Fin (2 ^ k)) : + stock f (fun i => if x i then a else 0) j = degree f x j * a := by + unfold stock degree + rw [← Finset.sum_filter, Finset.sum_const, Finset.filter_filter] + simp only [and_comm, nsmul_eq_mul, Nat.cast_id] + +private theorem dummy_degree (S : Finset (Fin (2 ^ k))) (hs : S.card ≤ 2 ^ h) (j : Fin (2 ^ k)) : + degree (dummyLabel (h := h) S) (fun i => decide (i.val < S.card)) j = + if j ∈ S then 1 else 0 := by + let P := Finset.univ.filter (fun i : Fin (2 ^ h) => i.val < S.card ∧ dummyLabel S i = j) + suffices P.card = if j ∈ S then 1 else 0 by simpa [P, degree] using this + by_cases hj : j ∈ S + · let i := (S.equivFin ⟨j, hj⟩).castLE hs + have h : P = {i} := by + ext t + simp only [P, Finset.mem_filter, Finset.mem_univ, true_and, Finset.mem_singleton] + constructor + · rintro ⟨ht, he⟩ + rw [dummyLabel, dite_eq_left ht] at he + have hh : S.equivFin.symm ⟨t.val, ht⟩ = ⟨j, hj⟩ := Subtype.ext he + exact Fin.ext (congrArg (fun t : Fin S.card => t.val) (S.equivFin.symm_apply_eq.mp hh)) + · rintro rfl + simp [dummyLabel, i] + simp [h, hj] + · have h : P = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + intro i hi + obtain ⟨ht, he⟩ := (Finset.mem_filter.mp hi).2 + rw [dummyLabel, dite_eq_left ht] at he + exact hj (he ▸ (S.equivFin.symm ⟨i.val, ht⟩).property) + simp [h, hj] + +variable {S : Finset (Fin (2 ^ k))} {d : ℕ} {L R : Fin (2 ^ h) → Fin (2 ^ k)} {x : Fin (2 ^ h) → + Bool} + +private theorem regular_stock (hs : S.card ≤ 2 ^ h) + (he : ∀ j, degree L x j = if j ∈ S then d else 0) (j : Fin (2 ^ k)) : + stock (join L (dummyLabel S)) (weights S d x) j = if j ∈ S then 2 ^ (h + 1) else 0 := by + rw [stock_join] + simp only [weights, join, Function.comp_apply, Equiv.symm_apply_apply, Sum.elim_inl, Sum.elim_inr] + have hg := stock_uniform (dummyLabel (h := h) S) (fun i => decide (i.val < S.card)) + (2 ^ (h + 1) % d) j + simp only [decide_eq_true_eq, dummy_degree S hs] at hg + rw [stock_uniform, he, hg] + by_cases hj : j ∈ S + · simp only [hj, ite_true, one_mul, Nat.div_add_mod] + · simp [hj] + +private theorem few_dummies (hd : 1 ≤ d) (hs : S.card * d ≤ 2 ^ h) : + dummyStock (dummy h) (weights S d x) < 2 ^ (h + 1) := by + rw [dummyStock, Finset.sum_filter, sum_halves] + simp only [dummy, weights, join, Function.comp_apply, Equiv.symm_apply_apply, + Sum.elim_inl, Sum.elim_inr, Bool.false_eq_true, ite_false, ite_true, Finset.sum_const_zero, + zero_add] + rw [← Finset.sum_filter, Finset.sum_const, nsmul_eq_mul, Nat.cast_id] + have hb : (Finset.univ.filter fun i : Fin (2 ^ h) => i.val < S.card).card ≤ S.card := by + refine le_trans (Finset.card_le_card_of_injOn (t := Finset.range S.card) + Fin.val ?_ Fin.val_injective.injOn) (Finset.card_range _).le + exact fun _ hi => Finset.mem_range.mpr (Finset.mem_filter.mp hi).2 + exact ((Nat.mul_le_mul hb (Nat.mod_lt _ hd).le).trans hs).trans_lt + (by rw [pow_succ]; have := Nat.two_pow_pos h; omega) + +theorem Regular.matching (he : Regular S d L R x) (hd : 1 ≤ d) (hs : S.card * d ≤ 2 ^ h) : + Regular S 1 L R (matching S d L R x) ∧ ∀ i, matching S d L R x i = true → x i = true := by + have sz := (Nat.le_mul_of_pos_right _ hd).trans hs + let y := (halve (join L (dummyLabel S)) (join R (dummyLabel S)) (dummy h))^[h + 1] (weights S d x) + obtain ⟨hl, hr, hm, hz⟩ := perfect S (regular_stock sz he.1) (regular_stock sz he.2) (few_dummies + hd hs) + have hz' (i : Fin (2 ^ h)) : y (halves h (.inr i)) = 0 := hz _ (by simp [dummy, join]) + let Y := MatrixExponent.Coloring.matching S d L R x + have hy (i) : Y i = true ↔ y (halves h (.inl i)) = 1 := decide_eq_true_iff + have aux (p : Fin (2 ^ h) → Fin (2 ^ k)) + (hp : ∀ j, stock (join p (dummyLabel S)) y j = if j ∈ S then 1 else 0) (j : Fin (2 ^ k)) : + degree p Y j = if j ∈ S then 1 else 0 := by + let m (i) := y (halves h (.inl i)) + have hv (k) : stock p m k = if k ∈ S then 1 else 0 := by + rw [← hp, stock_join] + simp [stock, hz', m] + have hunit : m = (fun i => if Y i then 1 else 0) := by + funext i + have hh : m i ≤ stock p m (p i) := Finset.single_le_sum (fun _ _ => Nat.zero_le _) (by simp) + rw [hv] at hh + simp only [hy] + change m i = if m i = 1 then 1 else 0 + split_ifs at * <;> omega + simpa [hunit, stock_uniform] using hv j + refine ⟨⟨aux L hl, aux R hr⟩, fun i hi => ?_⟩ + have hc : y (halves h (.inl i)) ≤ weights S d x (halves h (.inl i)) := hm _ + rw [(hy i).mp hi] at hc + by_contra e + simp [weights, join, e] at hc + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Pad.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Pad.lean new file mode 100644 index 0000000000..1d68108b89 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Pad.lean @@ -0,0 +1,25 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector + +/-! # Extending a listed function by fixed points -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Coloring + +/-- Embeds `B h` into `B (h + 1)`. -/ +def lowerHalf (h : ℕ) : B h ↪ B (h + 1) := Fin.castLEEmb (by rw [pow_succ]; omega) + +/-- Returns `lowerHalf h (x ⟨a, ha⟩)` when `ha : a.val < 2 ^ h` holds, and `a` otherwise. -/ +def inflate (h : ℕ) (x : (Perm h).obj) (a : B (h + 1)) : B (h + 1) := + if ha : a.val < 2 ^ h then lowerHalf h (x ⟨a, ha⟩) else a + +end MatrixMultiplicationAllFields.MatrixExponent.Routing diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Run.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Run.lean new file mode 100644 index 0000000000..c49b259b44 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Run.lean @@ -0,0 +1,600 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Shift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Add +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Edges +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Chart +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Parameters + +/-! # Comparing the sizes of two colour classes -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +private def count (h : ℕ) (x : B h → Bool) : B (h + 1) := + ⟨Control.histogram x true none, (Control.histogram_le ..).trans_lt + (Nat.pow_lt_pow_right (by decide) (by omega))⟩ + +variable (F : Type) [Field F] + +private theorem cheap_count (h : ℕ) : Cheap F h h (.vec h .bit) (.addr (h + 1)) (count h) 3 := by + obtain ⟨L, hL⟩ := Layout.exists_tree .bit h + have hc := (Control.prefix_net F h).comp (DNet.snd F _ _) + have hr : Circuit F (.vec h .bit) (.addr (h + 1)) (count h) + (500 * 2 ^ h * (h + 1) + wd (.pair (tree h (word (h + 1))) (word (h + 1)))) := by + apply Circuit.of_dnet L.positions (.refl _) hc + intro x + change bits (word (h + 1)) (Control.bitPrefix h x).2 = + bits (word (h + 1)) (Lookup.bits (h + 1) (Control.histogram (L.read x) true none)) + rw [(Control.prefix_eq h x _ (hL _)).2] + refine ⟨_, hr, ?_⟩ + rw [Format.width_vec, Format.width_bit, Format.width_addr] + simp only [wd, wd_word, wd_tree] + have hh := Nat.mul_le_mul_right (h + 1) (Nat.one_le_pow h 2 (by decide)) + ring_nf at hh ⊢ + omega + +private abbrev masks (h : ℕ) := Format.pair (.pair (.vec h .bit) (.vec h .bit)) (.vec h .bit) +/-- Computes the triple by the application `Format.pair (.pair .bit .bit) .bit`. -/ +abbrev Triple := Format.pair (.pair .bit .bit) .bit + +private def marked (b : Bool) (x : Triple.obj) : Bool := + decide (x.1.1 = true ∧ x.1.2 = true ∧ x.2 = b) + +theorem cheap_triple (h : ℕ) (f : Triple.obj → Bool) : Cheap F 0 h Triple .bit f 2 := by + refine ⟨_, small (F := F) (A := Triple) (by simp [Triple]) _, ?_⟩ + simp only [Format.width_pair] + rw [Format.width_bit] + ring_nf + omega + +private theorem cheap_cmp (h : ℕ) : + Cheap F h h (.pair (.addr (h + 1)) (.addr (h + 1))) .bit + (fun x => !(decide (x.1 < x.2))) 3 := by + refine ⟨_, (numeric_lt F (h + 1)).comp (small (F := F) (A := .bit) (by simp) Bool.not), ?_⟩ + rw [Format.width_pair, Format.width_addr, Format.width_bit] + apply le_trans _ (Nat.le_mul_of_pos_left _ (Nat.two_pow_pos h)) + ring_nf; omega + +theorem cheap_minority (h : ℕ) : + Cheap F h h (.pair (.pair (.vec h .bit) (.vec h .bit)) (.vec h .bit)) .bit + (fun x => minority x.1.1 x.1.2 x.2) 30 := by + have hw : (masks h).width ≤ 2 ^ h * (100 + h) ^ 1 := by + simp only [Format.width_pair, Format.width_vec] + rw [Format.width_bit, ← mul_add, ← mul_add, pow_one] + apply Nat.mul_le_mul_left; omega + have base := Cheap.id F hw + have get := (base.fst.zip.pair base.snd).zip + have hc (b : Bool) := (get.comp (Cheap.map _ (fun _ : B h => cheap_triple F h (marked b)))).comp + (cheap_count F h) + convert (((hc false).pair (hc true)).comp (cheap_cmp F h)).mono (d := 30) (by decide) using 1 + funext x + apply Bool.eq_iff_iff.mpr + simp [minority, count, Control.histogram_none, marked, Function.comp_def] + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- +# Halving multiplicities with bounded counters + +The counters never overflow. A unit is added only at an odd edge of +the chosen colour, after dividing the previous count by two. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +/-- Computes the weighted by the application `Format.pair (GraphInput h k) (.vec h (.addr r))`. -/ +abbrev Weighted (h k r : ℕ) := Format.pair (GraphInput h k) (.vec h (.addr r)) + +/-- Returns `half v + 1` when `b` holds, and `half v` otherwise. -/ +def reduce {r : ℕ} (v : B r) (b : Bool) : B r := + if b then half v + 1 else half v + +private theorem reduce_val {r : ℕ} (v : B r) (b : Bool) (hb : b = true → odd v = true) : + (reduce v b).val = v.val / 2 + if b then 1 else 0 := by + cases b + · rfl + · have hv : v.val % 2 = 1 := of_decide_eq_true (hb rfl) + have := v.isLt + change (v.val / 2 + 1 % 2 ^ r) % 2 ^ r = v.val / 2 + 1 + rw [Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)] + +variable {h k r : ℕ} + +/-- The halve step of type `(Weighted h k r).obj`, constructed using `fun i => odd (x.2 i)`. -/ +def halveStep (x : (Weighted h k r).obj) : (Weighted h k r).obj := + let a := fun i => odd (x.2 i) + let c := split x.1.1.1 x.1.1.2 a + (x.1, fun i => reduce (x.2 i) (a i && (c i == minority x.1.2 a c))) + +private theorem halve_val (x : (Weighted h k r).obj) : + Fin.val ∘ (halveStep x).2 = halve x.1.1.1 x.1.1.2 x.1.2 (Fin.val ∘ x.2) := by + funext i + exact reduce_val _ _ (fun h => (Bool.and_eq_true_iff.mp h).1) + +theorem halve_steps (x : (Weighted h k r).obj) (d : ℕ) : + (halveStep^[d] x).1 = x.1 ∧ + Fin.val ∘ (halveStep^[d] x).2 = (halve x.1.1.1 x.1.1.2 x.1.2)^[d] (Fin.val ∘ x.2) := by + induction d with + | zero => exact ⟨rfl, rfl⟩ + | succ d ih => + rw [Function.iterate_succ_apply', Function.iterate_succ_apply'] + refine ⟨ih.1, ?_⟩ + rw [halve_val, ih.1, ih.2] + +variable (F : Type) [Field F] + +private theorem unary {r : ℕ} {A : Format} {f : B r → A.obj} + (hw : A.width ≤ 1 + r) (hc : Circuit F (.addr r) A f (1000 * (1 + r))) : + Cheap F 0 r (.addr r) A f 3 := by + refine ⟨_, hc, ?_⟩ + rw [Format.width_addr] + ring_nf + omega + +private theorem cheap_reduce (r : ℕ) : + Cheap F 0 r (.pair (.addr r) .bit) (.addr r) (fun x => reduce x.1 x.2) 10 := by + have hw : (Format.pair (.addr r) .bit).width ≤ 2 ^ 0 * (100 + r) ^ 1 := by + rw [Format.width_pair, Format.width_addr, Format.width_bit]; simp + have haddr : (Format.addr r).width ≤ 1 + r := by simp + have base := Cheap.id F hw + have a := base.fst.comp (unary F haddr (numeric_half F r)) + have b := a.comp (unary F haddr (numeric_inc F r)) + exact (((b.pair a).pair base.snd).comp (cheap_select F r)).mono (by decide) + +private theorem broadcast (h t : ℕ) : + Cheap F h t .bit (.vec h .bit) (fun b _ => b) 1 := by + apply Cheap.project (c := 0) F _ _ Prod.snd (fun _ _ => rfl) + · rw [Format.width_bit, pow_zero, mul_one] + exact Nat.one_le_pow h 2 (by decide) + · rw [Format.width_vec, Format.width_bit, pow_zero] + +theorem cheap_halve (h k r : ℕ) : + Cheap F h (h + k + r) (Weighted h k r) (Weighted h k r) halveStep 160 := by + let t := h + k + r + have hw : (Weighted h k r).width ≤ 2 ^ h * (100 + t) ^ 2 := by + rw [Format.width_pair, graph_width, Format.width_vec, Format.width_addr, ← mul_add] + apply Nat.mul_le_mul_left + dsimp [t]; ring_nf; omega + have base := Cheap.id F hw + have m := base.snd + have bit := unary F (A := .bit) (by rw [Format.width_bit]; omega) (numeric_odd F r) + have a := m.comp (Cheap.map _ (fun _ : B h => bit.widen (l := t) (by omega))) + have c := (base.fst.fst.pair a).comp ((cheap_split F h k).widen (l := t) (by omega)) + have hm := cheap_minority F h + have b := ((base.fst.snd.pair a).pair c).comp (hm.widen (l := t) (by omega)) + have args := ((a.pair c).zip.pair (b.comp (broadcast F h t))).zip + have mark := cheap_triple F t (fun x => x.1.1 && (x.1.2 == x.2)) + have flag := args.comp (Cheap.map _ (fun _ : B h => mark)) + have next := (m.pair flag).zip.comp + (Cheap.map _ (fun _ : B h => (cheap_reduce F r).widen (l := t) (by omega))) + exact (base.fst.pair next).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +/- +# Computing a perfect matching + +The degree and support are fixed. Append dummy edges, initialize bounded +counters, halve repeatedly, then retain real edges with final count one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable (F : Type) [Field F] {h k r : ℕ} + +private theorem cheap_join (A : Format) (ha : A.width ≤ r) : + Cheap F h r (.pair (.vec h A) (.vec h A)) (.vec (h + 1) A) + (fun x => join x.1 x.2) 3 := by + have hw : 2 ^ h * (2 * A.width) ≤ 2 ^ h * (100 + r) ^ 2 := by + apply Nat.mul_le_mul_left; nlinarith + let p (ij : B (h + 1) × A.pins) := + Sum.map (fun i => (i, ij.2)) (fun i => (i, ij.2)) ((halves h).symm ij.1) + apply Cheap.project (c := 2) F _ _ p + · intro x ⟨i, j⟩ + obtain ⟨i | i, rfl⟩ := (halves h).surjective i <;> + simp only [p, Equiv.symm_apply_apply, Sum.map_inl, Sum.map_inr] <;> + change A.code (join x.1 x.2 _) j = _ <;> + simp only [join, Function.comp_apply, Equiv.symm_apply_apply] <;> rfl + · rw [Format.width_pair, Format.width_vec, ← mul_add, ← two_mul] + exact hw + · rw [Format.width_vec, pow_succ, mul_assoc]; exact hw + +private theorem cheap_from_bit {A : Format} (ha : A.width ≤ r) (f : Bool → A.obj) : + Cheap F 0 r .bit A f 2 := by + have t : Install.Depends (A.code ∘ f ∘ Format.bit.code.symm) 1 := by + intro i + exact ⟨Finset.univ, by rfl, fun x y he => by rw [funext (fun j => he j (Finset.mem_univ _))]⟩ + refine ⟨_, t.bnet F, ?_⟩ + change 1 + A.width + (1 + 34 * A.width) ≤ _ + nlinarith + +private def coeff (h d : ℕ) (rem : Bool) : B (h + 2) := + ⟨if rem then 2 ^ (h + 1) % d else 2 ^ (h + 1) / d, by + have he : 2 ^ (h + 1) < 2 ^ (h + 2) := Nat.pow_lt_pow_right (by decide) (by omega) + split + · exact (Nat.mod_le ..).trans_lt he + · exact (Nat.div_le_self ..).trans_lt he⟩ + +private abbrev extent (h k : ℕ) := (h + 1) + k + (h + 2) +private abbrev enlarged (h k : ℕ) := Weighted (h + 1) k (h + 2) + +private def init (S : Finset (B k)) (d : ℕ) (x : (GraphInput h k).obj) : (enlarged h k).obj := + (((join x.1.1 (dummyLabel S), join x.1.2 (dummyLabel S)), dummy h), + join (fun i => if x.2 i then coeff h d false else 0) + (fun i => if i.val < S.card then coeff h d true else 0)) + +private theorem init_val (S : Finset (B k)) (d : ℕ) (x : (GraphInput h k).obj) : + Fin.val ∘ (init S d x).2 = weights S d x.2 := by + funext i + obtain ⟨i | i, rfl⟩ := (halves h).surjective i <;> + simp only [init, weights, join, Function.comp_apply, Equiv.symm_apply_apply, + Sum.elim_inl, Sum.elim_inr] <;> split <;> rfl + +private theorem cheap_init (h k : ℕ) (S : Finset (B k)) (d : ℕ) : + Cheap F h (extent h k) (GraphInput h k) (enlarged h k) (init S d) 20 := by + let r := extent h k + have ha : (Format.addr k).width ≤ r := by rw [Format.width_addr]; unfold r extent; omega + have hz : (Format.addr (h + 2)).width ≤ r := by rw [Format.width_addr]; unfold r extent; omega + have hw : (GraphInput h k).width ≤ 2 ^ h * (100 + r) ^ 2 := by + rw [graph_width] + apply Nat.mul_le_mul_left + dsimp [r, extent]; ring_nf; omega + have vec (A : Format) (ha : A.width ≤ r) : (Format.vec h A).width ≤ 2 ^ h * (100 + r) ^ 2 := by + rw [Format.width_vec]; apply Nat.mul_le_mul_left; nlinarith + have flag : (Format.vec (h + 1) .bit).width ≤ 2 ^ h * (100 + r) ^ 2 := by + rw [Format.width_vec, Format.width_bit, mul_one, pow_succ] + apply Nat.mul_le_mul_left; nlinarith + have base := Cheap.id F hw + have label := Cheap.const F hw (vec _ ha) (dummyLabel S) + have add := cheap_join (h := h) F (.addr k) ha + have left := (base.fst.fst.pair label).comp add + have right := (base.fst.snd.pair label).comp add + have graph := (left.pair right).pair (Cheap.const F hw flag (dummy h)) + have pick := cheap_from_bit F hz (fun b => if b then coeff h d false else 0) + have real := base.snd.comp (Cheap.map _ (fun _ : B h => pick)) + have fill := Cheap.const F hw (vec _ hz) (fun i => if i.val < S.card then coeff h d true else 0) + have nums := (real.pair fill).comp (cheap_join (h := h) F (.addr (h + 2)) hz) + exact (graph.pair nums).mono (by decide) + +private theorem cheap_one (r : ℕ) : + Cheap F 0 r (.addr r) .bit (fun i => decide (i.val = 1)) 3 := by + refine ⟨10 * r + 1, ?_, by rw [Format.width_addr, Format.width_bit]; ring_nf; omega⟩ + apply Circuit.of_dnet (.refl _) (.refl _) (Control.quotient_test F r 0 1) + intro i + simp only [Equiv.coe_refl, Function.comp_id, pow_zero, Nat.div_one] + exact congrArg (fun j : B r => bits .bit (decide (j.val = 1))) (decode_addr r i).symm + +private def finish (x : (enlarged h k).obj) (i : B h) : Bool := + decide ((x.2 (halves h (.inl i))).val = 1) + +private theorem cheap_finish (h k : ℕ) : + Cheap F h (extent h k) (enlarged h k) (.vec h .bit) finish 5 := by + let A := Format.vec h (.addr (h + 2)) + have hw : (enlarged h k).width ≤ 2 ^ h * (100 + extent h k) ^ 2 := by + rw [Format.width_pair, graph_width, Format.width_vec, Format.width_addr, + ← mul_add, pow_succ, mul_assoc] + apply Nat.mul_le_mul_left + dsimp [extent]; ring_nf; omega + have hv : A.width ≤ 2 ^ h * (100 + extent h k) ^ 2 := by + rw [Format.width_vec, Format.width_addr] + apply Nat.mul_le_mul_left + dsimp [extent]; ring_nf; omega + have extract := Cheap.project (A := enlarged h k) (D := A) F hw hv (f := fun x i + => x.2 (halves h (.inl i))) + (fun ij => Sum.inr (halves h (.inl ij.1), ij.2)) (fun _ _ => rfl) + have test := (cheap_one F (h + 2)).widen (l := extent h k) (by unfold extent; omega) + exact (extract.comp (Cheap.map _ (fun _ : B h => test))).mono (by decide) + +private theorem recost {A D : Format} {f : A.obj → D.obj} {c : ℕ} + (hf : Cheap F (h + 1) r A D f c) : Cheap F h r A D f (c + 1) := by + obtain ⟨m, hm, hw⟩ := hf + refine ⟨m, hm, hw.trans ?_⟩ + rw [pow_succ, pow_succ', mul_assoc] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ (by omega)) + +private theorem extent_cost {A D : Format} {f : A.obj → D.obj} {c : ℕ} + (hf : Cheap F h (extent h k) A D f c) : Cheap F h (h + k) A D f (2 * c) := by + obtain ⟨m, hm, hw⟩ := hf + refine ⟨m, hm, hw.trans ?_⟩ + rw [pow_mul] + apply Nat.mul_le_mul_left + apply Nat.pow_le_pow_left + dsimp [extent]; ring_nf; omega + +theorem cheap_matching (h k : ℕ) (S : Finset (B k)) (d : ℕ) : + Cheap F h (h + k) (GraphInput h k) (.vec h .bit) + (fun x => matching S d x.1.1 x.1.2 x.2) 400 := by + have hc := cheap_halve F (h + 1) k (h + 2) + have it := recost F (hc.iterate (r := h + 1) (by omega)) + have t := ((cheap_init F h k S d).comp it).comp (cheap_finish F h k) + convert (extent_cost F t).mono (d := 400) (by decide) using 1 + funext x i + have hv := (halve_steps (init S d x) (h + 1)).2 + rw [init_val] at hv + exact congrArg (fun y : B (h + 1) → ℕ => decide (y (halves h (.inl i)) = 1)) hv.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- +# Circuits for the full edge colouring + +Both halves of a bisection occupy one array. The circuit carries +only the two decision bits per edge around the recursive call. Each +level adds one bounded polynomial overhead to the total cost. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable (F : Type) [Field F] + +private abbrev Mask (h : ℕ) := Format.vec h .bit +private abbrev Flags (h : ℕ) := Format.pair (Mask h) (Mask h) +private abbrev Local (h : ℕ) := Format.pair (.pair .bit .bit) (.addr h) +private abbrev Final (h : ℕ) := Format.pair (Flags h) (Perm h) + +private theorem cheap_combine (h d : ℕ) : Cheap F 0 h (Local h) (.addr h) + (fun x => combine d x.1.1 x.1.2 x.2) 30 := by + have hw : (Local h).width ≤ 2 ^ 0 * (100 + h) ^ 1 := by simp [Local] + have hw' : (Format.addr h).width ≤ 2 ^ 0 * (100 + h) ^ 1 := by simp + have inp := Cheap.id F hw + let z : B h := ⟨(d - 1) % 2 ^ h, Nat.mod_lt _ (Nat.two_pow_pos h)⟩ + have fixed := Cheap.const F hw hw' z + have add : Cheap F 0 h (.pair (.addr h) (.addr h)) (.addr h) (fun x => x.1 + x.2) 3 := + ⟨_, numeric_add F h, by simp only [Format.width_pair, Format.width_addr]; ring_nf; omega⟩ + have inc : Cheap F 0 h (.addr h) (.addr h) (fun x => x + 1) 3 := + ⟨_, numeric_inc F h, by simp only [Format.width_addr]; ring_nf; omega⟩ + have dbl := (inp.snd.pair inp.snd).comp add + have c := (((dbl.comp inc).pair dbl).pair inp.fst.snd).comp (cheap_select F h) + have t := ((fixed.pair c).pair inp.fst.fst).comp (cheap_select F h) + convert t.mono (d := 30) (by decide) using 1 + funext ⟨⟨p, q⟩, j⟩ + change combine d p q j = if p then z else if q then j + j + 1 else j + j + cases p <;> cases q <;> apply Fin.ext <;> simp [combine, z, Fin.add_def, two_mul] + +private def collect (h d : ℕ) (x : (Final h).obj) (i : B h) : B h := + combine d (x.1.1 i) (x.1.2 i) (x.2 i) + +private theorem cheap_collect (h d : ℕ) : + Cheap F h h (Final h) (Perm h) (collect h d) 32 := by + have hw : (Final h).width ≤ 2 ^ h * (100 + h) ^ 1 := by + simp only [Format.width_pair, Format.width_vec, Format.width_addr, + pow_one, ← mul_add] + rw [Format.width_bit] + gcongr + omega + have inp := Cheap.id F hw + have args := (inp.fst.zip.pair inp.snd).zip + exact (args.comp (Cheap.map _ (fun _ : B h => cheap_combine F h d))).mono (by decide) + +private theorem cheap_rest : Cheap F 0 0 (.pair .bit .bit) .bit + (fun x => x.1 && !x.2) 1 := by + have h := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 && !x.2) (by decide) + exact ⟨1, Circuit.of_dnet (.refl _) (.refl _) h (by intro x; rfl), by simp⟩ + +private theorem cheap_double (k : ℕ) : Cheap F 0 k (.pair (.addr k) .bit) (.addr (k + 1)) + (fun x => double x.1 x.2) 3 := + ⟨_, numeric_double F k, by + rw [Format.width_pair, Format.width_addr, Format.width_addr, Format.width_bit]; ring_nf; omega⟩ + +private noncomputable def prepare (h k : ℕ) (S : Finset (B k)) (d : ℕ) + (x : (GraphInput h k).obj) : (Flags h).obj × (GraphInput h (k + 1)).obj := + let y := retired S d x.1.1 x.1.2 x.2 + let a := rest x.2 y + let b := split x.1.1 x.1.2 a + ((y, b), (nextEnd x.1.1 b, nextEnd x.1.2 b), a) + +private theorem width_input (h k : ℕ) : (GraphInput h k).width ≤ 2 ^ h * (100 + (h + k)) ^ 2 := by + rw [graph_width] + gcongr + ring_nf + omega + +private theorem cheap_prepare (h k : ℕ) (S : Finset (B k)) (d : ℕ) : + Cheap F h (h + k) (GraphInput h k) (.pair (Flags h) (GraphInput h (k + 1))) + (prepare h k S d) 415 := by + have hw := width_input h k + have mask : (Mask h).width ≤ 2 ^ h * (100 + (h + k)) ^ 2 := by + rw [Format.width_vec, Format.width_bit] + gcongr + ring_nf + omega + have inp := Cheap.id F hw + have y : Cheap F h (h + k) (GraphInput h k) (Mask h) + (fun x => retired S d x.1.1 x.1.2 x.2) 400 := by + by_cases he : d % 2 = 0 + · simp only [retired, he, ite_true] + exact (Cheap.const F hw mask (fun _ => false)).mono (by decide) + · simp only [retired, he, ite_false] + exact cheap_matching F h k S d + have a := ((inp.snd.pair y).zip).comp + (Cheap.map _ (fun _ : B h => (cheap_rest F).widen (l := h + k) (by omega))) + have b := (inp.fst.pair a).comp (cheap_split F h k) + have ext := Cheap.map _ (fun _ : B h => (cheap_double F k).widen (l := h + k) (by omega)) + have left := ((inp.fst.fst.pair b).zip).comp ext + have right := ((inp.fst.snd.pair b).zip).comp ext + exact ((y.pair b).pair ((left.pair right).pair a)).mono (by decide) + +private theorem recurse_cost (fuel h k K : ℕ) (hk : h + k + fuel ≤ K) (S : Finset (B k)) (d : ℕ) : + ∃ m, Circuit F (GraphInput h k) (Perm h) (fun x => recurse fuel S d x.1.1 x.1.2 x.2) m ∧ + (GraphInput h k).width + (Perm h).width + m ≤ (2 * fuel + 1) * (2 ^ h * (100 + K) ^ 415) := by + induction fuel generalizing k d with + | zero => + have ho : (Perm h).width ≤ 2 ^ h * (100 + (h + k)) ^ 2 := by + rw [Format.width_vec, Format.width_addr] + gcongr + ring_nf + omega + have c := Cheap.const F (width_input h k) ho (fun _ => 0) + obtain ⟨m, hm, le⟩ := (c.widen (l := K) (by omega)).mono (d := 415) (by decide) + exact ⟨m, hm, by simpa only [mul_zero, zero_add, one_mul] using le⟩ + | succ n ih => + obtain ⟨a, ha, la⟩ := (cheap_prepare F h k S d).widen (l := K) (by omega) + obtain ⟨b, hb, lb⟩ := ih (k + 1) (by omega) (enlarge S) (d / 2) + obtain ⟨c, hc, lc⟩ := ((cheap_collect F h d).widen (l := K) (by omega)).mono + (d := 415) (by decide) + have net := (ha.comp ((Circuit.id F (Flags h)).par hb)).comp hc + refine ⟨a + ((Flags h).width + b) + c, ?_, ?_⟩ + · simp only [recurse] + exact net + · rw [Format.width_pair (Flags h) _] at la + rw [show 2 * (n + 1) + 1 = (2 * n + 1) + 2 by omega, add_mul] + omega + +private theorem total_cost (h k c d : ℕ) (le : 2 + 2 * c ≤ d) : + (2 * (h + 1) + 1) * (2 ^ h * (100 + (h + k + (h + 1))) ^ c) ≤ 2 ^ h * (100 + (h + k)) ^ d := by + let x := 100 + (h + k) + have ha : 100 + (h + k + (h + 1)) ≤ x ^ 2 := by unfold x; ring_nf; omega + have hb : 2 * (h + 1) + 1 ≤ x ^ 2 := by unfold x; ring_nf; omega + have hx : 0 < x := by omega + calc + _ ≤ x ^ 2 * (2 ^ h * (x ^ 2) ^ c) := Nat.mul_le_mul hb (Nat.mul_le_mul_left _ + (Nat.pow_le_pow_left ha _)) + _ = 2 ^ h * x ^ (2 + 2 * c) := by rw [pow_add, pow_mul, mul_left_comm] + _ ≤ 2 ^ h * x ^ d := Nat.mul_le_mul_left (2 ^ h) (Nat.pow_le_pow_right hx le) + +theorem cheap_colours (h k : ℕ) (S : Finset (B k)) (d : ℕ) : + Cheap F h (h + k) (GraphInput h k) (Perm h) + (fun x => colours S d x.1.1 x.1.2 x.2) 860 := by + obtain ⟨m, hm, hc⟩ := recurse_cost F (h + 1) h k (h + k + (h + 1)) le_rfl S d + refine ⟨m, hm, hc.trans ?_⟩ + exact total_cost h k 415 860 (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- +# Cost of the three permutation controllers + +Fixed chart tables are read in parallel. A colour determines an offset +in a fiber. Two permutation inversions and two more reads suffice to +construct all three factor lists. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +private theorem cheap_add (F : Type) [Field F] (h : ℕ) : + Cheap F 0 h (.pair (.addr h) (.addr h)) (.addr h) (fun x => x.1 + x.2) 4 := by + refine ⟨_, numeric_add F h, ?_⟩ + simp only [Format.width_pair, Format.width_addr] + ring_nf + omega + +namespace Chart + +variable (F : Type) [Field F] {h : ℕ} (p : Chart h) + +private theorem width_perm : (Perm h).width ≤ 2 ^ h * (100 + h) ^ 1 := by + simp [Perm] + +private theorem width_mask : (Format.vec h .bit).width ≤ 2 ^ h * (100 + h) ^ 1 := by + rw [Format.width_vec, Format.width_bit, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + +private theorem read_table (h : ℕ) : Cheap F h h (.pair (Perm h) (Perm h)) (Perm h) + (fun x => x.1 ∘ x.2) 8 := + Cheap.lookup F h h (.addr h) le_rfl (by rw [Format.width_addr]) + +private theorem route_cheap {b c : (Perm h).obj → (Perm h).obj} {n : ℕ} + (hb : Cheap F h h (Perm h) (Perm h) b n) (hc : Cheap F h h (Perm h) (Perm h) c n) : + Cheap F h h (Perm h) (Perm h) (fun y => p.route (b y) (c y)) (n + 20) := by + have add := Cheap.map _ (fun _ : B h => cheap_add F h) + have pos := ((hb.pair hc).zip).comp add + have table := Cheap.const F (width_perm (h := h)) width_perm p.location + have self := Cheap.const F (width_perm (h := h)) width_perm id + have mask := Cheap.const F (width_perm (h := h)) width_mask p.mask + have get := (table.pair pos).comp (read_table F h) + have data := ((get.pair self).zip.pair mask).zip + exact (data.comp (Cheap.map _ (fun _ : B h => cheap_select F h))).mono (by omega) + +private theorem twice_height (h n m : ℕ) (hm : m = 2 * n) : (100 + (h + h)) ^ n ≤ (100 + h) ^ m + := by + rw [hm, pow_mul] + exact Nat.pow_le_pow_left (by ring_nf; omega) n + +private theorem unstack_width {A D : Format} {f : A.obj → D.obj} + (hc : Cheap F h (h + h) A D f 860) : Cheap F h h A D f 1720 := by + obtain ⟨m, hm, hb⟩ := hc + have bound := Nat.mul_le_mul_left (2 ^ h) (twice_height h 860 1720 rfl) + exact ⟨m, hm, hb.trans bound⟩ + +private theorem label_cheap + (hl : Cheap F h (h + h) (GraphInput h h) (Perm h) + (fun x => colours p.support p.degree x.1.1 x.1.2 x.2) 860) : + Cheap F h h (Perm h) (Perm h) p.label 1721 := by + have cheapLabel := unstack_width F hl + have y : Cheap F h h (Perm h) (Perm h) id 2 := + Cheap.id F (width_perm (h := h)) + have mask : Cheap F h h (Perm h) (Format.vec h .bit) (fun _ => p.mask) 2 := + Cheap.const F width_perm width_mask p.mask + have a : Cheap F h h (Perm h) (Perm h) (fun _ => p.base) 2 := + Cheap.const F width_perm width_perm p.base + have b : Cheap F h h (Perm h) (Perm h) (fun y => p.base ∘ y) 9 := + (a.pair y).comp (read_table F h) + have graph : Cheap F h h (Perm h) (GraphInput h h) + (fun z => ((p.base, p.base ∘ z), p.mask)) 11 := + (a.pair b).pair mask + have joined := graph.comp cheapLabel + have equation : (fun x : (GraphInput h h).obj => + colours p.support p.degree x.1.1 x.1.2 x.2) ∘ + (fun z : (Perm h).obj => ((p.base, p.base ∘ z), p.mask)) = p.label := rfl + rw [equation] at joined + exact joined + +private theorem routes_cheap + (c : Cheap F h h (Perm h) (Perm h) p.label 1721) : + Cheap F h h (Perm h) (Perm h) p.left 1741 ∧ + Cheap F h h (Perm h) (Perm h) p.right 1741 := by + have y : Cheap F h h (Perm h) (Perm h) id 2 := + Cheap.id F (width_perm (h := h)) + have a : Cheap F h h (Perm h) (Perm h) (fun _ => p.base) 2 := + Cheap.const F width_perm width_perm p.base + have b : Cheap F h h (Perm h) (Perm h) (fun y => p.base ∘ y) 9 := + (a.pair y).comp (read_table F h) + refine ⟨?_, ?_⟩ + · exact route_cheap F p (a.mono (d := 1721) (by decide)) c + · exact route_cheap F p (b.mono (d := 1721) (by decide)) c + +theorem run_cheap (inv : (B h → B h) → (B h → B h)) + (hi : Cheap F h h (Perm h) (Perm h) inv 100) + (hl : Cheap F h (h + h) (GraphInput h h) (Perm h) + (fun x => colours p.support p.degree x.1.1 x.1.2 x.2) 860) : + Cheap F h h (Perm h) (.pair (Perm h) (.pair (Perm h) (Perm h))) (p.run inv) 1800 := by + obtain ⟨left, right⟩ := routes_cheap F p (label_cheap F p hl) + have y : Cheap F h h (Perm h) (Perm h) id 2 := + Cheap.id F (width_perm (h := h)) + have u : Cheap F h h (Perm h) (Perm h) (fun z => z ∘ inv (p.right z)) 1744 := + (y.pair (right.comp hi)).comp (read_table F h) + have v : Cheap F h h (Perm h) (Perm h) (fun z => p.right z ∘ inv (p.left z)) 1744 := + (right.pair (left.comp hi)).comp (read_table F h) + exact (u.pair (v.pair left)).mono (by decide) + +end Chart + +theorem factors (F : Type) [Field F] : Factors F 1800 := by + intro h X C A D _ _ _ _ s e + obtain ⟨inv, hcost, hi⟩ := cheap_inverse F h + obtain ⟨p, hp⟩ := chart_exists h X C A D s e inv hi + exact ⟨p.run inv, p.run_cheap F inv hcost (cheap_colours F h h p.support p.degree), hp⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Shift.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Shift.lean new file mode 100644 index 0000000000..c3cfcbf04d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Shift.lean @@ -0,0 +1,348 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import Mathlib.Order.Preorder.Finite + +/-! +# Halving integral edge multiplicities + +Split the edges of odd multiplicity at both sets of vertices. Keeping +the colour with fewer odd dummy edges halves every vertex degree and +at least halves the total number of dummy edges. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable {h k : ℕ} + +/-- The sum of `m i` indexed by `i ∈ Finset.univ.filter (fun i => f i = j)`. -/ +def stock (f : Fin (2 ^ h) → Fin (2 ^ k)) (m : Fin (2 ^ h) → ℕ) (j : Fin (2 ^ k)) := + ∑ i ∈ Finset.univ.filter (fun i => f i = j), m i + +/-- The sum of `m i` indexed by `i ∈ Finset.univ.filter (fun i => δ i)`. -/ +def dummyStock (δ : Fin (2 ^ h) → Bool) (m : Fin (2 ^ h) → ℕ) := + ∑ i ∈ Finset.univ.filter (fun i => δ i), m i + +/-- Tests whether `m i % 2 = 1` holds. -/ +def oddMask (m : Fin (2 ^ h) → ℕ) (i : Fin (2 ^ h)) := decide (m i % 2 = 1) + +/-- The minority of type `Bool` for the given inputs. -/ +def minority (δ a c : Fin (2 ^ h) → Bool) : Bool := + decide ((Finset.univ.filter (fun i => δ i = true ∧ a i = true ∧ c i = true)).card ≤ + (Finset.univ.filter (fun i => δ i = true ∧ a i = true ∧ c i = false)).card) + +/-- The halve of type `ℕ`, constructed using `oddMask m`. -/ +def halve (f g : Fin (2 ^ h) → Fin (2 ^ k)) (δ : Fin (2 ^ h) → Bool) (m : Fin (2 ^ h) → ℕ) + (i : Fin (2 ^ h)) : ℕ := + let a := oddMask m + let c := split f g a + m i / 2 + if a i && (c i == minority δ a c) then 1 else 0 + +variable {f g : Fin (2 ^ h) → Fin (2 ^ k)} {δ : Fin (2 ^ h) → Bool} {m : Fin (2 ^ h) → ℕ} + +private theorem stock_sum (S : Finset (Fin (2 ^ h))) (m : Fin (2 ^ h) → ℕ) : + ∑ i ∈ S, m i = 2 * (∑ i ∈ S, m i / 2) + (S.filter (fun i => oddMask m i)).card := by + rw [Finset.mul_sum, Finset.card_filter, ← Finset.sum_add_distrib] + refine Finset.sum_congr rfl fun i _ => ?_ + simp only [oddMask, decide_eq_true_eq] + split <;> omega + +private theorem halve_sum (S : Finset (Fin (2 ^ h))) : + ∑ i ∈ S, halve f g δ m i = (∑ i ∈ S, m i / 2) + + (S.filter (fun i => oddMask m i = true ∧ + split f g (oddMask m) i = minority δ (oddMask m) (split f g (oddMask m)))).card := by + simp only [halve, Bool.and_eq_true, beq_iff_eq, Finset.sum_add_distrib, Finset.card_filter] + +private theorem even_mask (hf : ∀ j, Even (stock f m j)) : EvenFibers f (oddMask m) := by + intro j + obtain ⟨n, hn⟩ := hf j + rw [stock, stock_sum] at hn + simp only [Finset.filter_filter, and_comm (a := f _ = j)] at hn + refine ⟨n - ∑ i ∈ Finset.univ.filter (fun i => f i = j), m i / 2, ?_⟩ + omega + +theorem stock_halve (hf : ∀ j, Even (stock f m j)) (hg : ∀ j, Even (stock g m j)) + (δ : Fin (2 ^ h) → Bool) (j : Fin (2 ^ k)) : + 2 * stock f (halve f g δ m) j = stock f m j ∧ + 2 * stock g (halve f g δ m) j = stock g m j := by + let a := oddMask m + let c := split f g a + let b := minority δ a c + have aux (p : Fin (2 ^ h) → Fin (2 ^ k)) + (hp : 2 * (Finset.univ.filter (fun i => a i = true ∧ p i = j ∧ c i = b)).card = + (Finset.univ.filter (fun i => a i = true ∧ p i = j)).card) : + 2 * stock p (halve f g δ m) j = stock p m j := by + unfold stock + rw [halve_sum, stock_sum _ m, mul_add] + simp only [Finset.filter_filter, and_comm (a := p _ = j) (b := oddMask m _ = true), + and_left_comm (a := p _ = j)] + exact congrArg _ hp + obtain ⟨hl, hr⟩ := split_balanced (even_mask hf) (even_mask hg) j b + exact ⟨aux f hl, aux g hr⟩ + +private theorem minority_le (δ a c : Fin (2 ^ h) → Bool) : + 2 * (Finset.univ.filter fun i => δ i = true ∧ a i = true ∧ c i = minority δ a c).card ≤ + (Finset.univ.filter fun i => δ i = true ∧ a i = true).card := by + let S := Finset.univ.filter (fun i => δ i = true ∧ a i = true) + let num (b : Bool) := (Finset.univ.filter fun i => δ i = true ∧ a i = true ∧ c i = b).card + have hs : num true + num false = S.card := by + have he := Finset.card_filter_add_card_filter_not (s := S) (fun i => c i = true) + simpa [S, num, Finset.filter_filter, and_assoc] using he + change 2 * num (decide (num true ≤ num false)) ≤ S.card + by_cases hd : num true ≤ num false + · rw [decide_eq_true hd] + omega + · rw [decide_eq_false hd] + omega + +theorem dummy_halve (f g : Fin (2 ^ h) → Fin (2 ^ k)) (δ : Fin (2 ^ h) → Bool) (m : Fin (2 ^ h) → + ℕ) : + 2 * dummyStock δ (halve f g δ m) ≤ dummyStock δ m := by + unfold dummyStock + rw [halve_sum, stock_sum _ m, mul_add] + simp only [Finset.filter_filter] + exact Nat.add_le_add_left (minority_le δ _ _) _ + +theorem halve_le (f g : Fin (2 ^ h) → Fin (2 ^ k)) (δ : Fin (2 ^ h) → Bool) + (m : Fin (2 ^ h) → ℕ) (i : Fin (2 ^ h)) : halve f g δ m i ≤ m i := by + simp only [halve, Bool.and_eq_true, oddMask, decide_eq_true_eq] + split <;> omega + +/-- Starting at power-of-two degree, repeated halving selects one edge +at each supported vertex. A strictly smaller dummy budget vanishes. -/ +theorem perfect {d : ℕ} (S : Finset (Fin (2 ^ k))) + (hf : ∀ j, stock f m j = if j ∈ S then 2 ^ d else 0) + (hg : ∀ j, stock g m j = if j ∈ S then 2 ^ d else 0) (hd : dummyStock δ m < 2 ^ d) : + let y := (halve f g δ)^[d] m + (∀ j, stock f y j = if j ∈ S then 1 else 0) ∧ + (∀ j, stock g y j = if j ∈ S then 1 else 0) ∧ + (∀ i, y i ≤ m i) ∧ ∀ i, δ i = true → y i = 0 := by + induction d generalizing m with + | zero => + refine ⟨hf, hg, fun i => le_rfl, fun i hi => ?_⟩ + change m i = 0 + have h : m i ≤ dummyStock δ m := Finset.single_le_sum (fun _ _ => Nat.zero_le _) (by simp [hi]) + omega + | succ d ih => + have he (j : Fin (2 ^ k)) : Even (if j ∈ S then 2 ^ (d + 1) else 0 : ℕ) := by + split + · exact ⟨2 ^ d, by rw [pow_succ, mul_two]⟩ + · exact ⟨0, rfl⟩ + have hp := stock_halve (fun j => (hf j).symm ▸ he j) (fun j => (hg j).symm ▸ he j) δ + have next (j : Fin (2 ^ k)) : + stock f (halve f g δ m) j = (if j ∈ S then 2 ^ d else 0) ∧ + stock g (halve f g δ m) j = (if j ∈ S then 2 ^ d else 0) := by + obtain ⟨hl, hr⟩ := hp j + rw [hf, pow_succ] at hl + rw [hg, pow_succ] at hr + split_ifs at * <;> omega + have hs := dummy_halve f g δ m + rw [pow_succ] at hd + obtain ⟨hl, hr, hm, hz⟩ := ih (fun j => (next j).1) (fun j => (next j).2) (by omega) + rw [Function.iterate_succ_apply] + exact ⟨hl, hr, fun i => (hm i).trans (halve_le f g δ m i), hz⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- # Incrementing and shifting little-endian addresses -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +/-- The quantity computed by `⟨2 * x.val + b.toNat, by have := x.isLt; cases b <;> simp +[pow_succ] <;> omega⟩`. -/ +def double {n : ℕ} (x : B n) (b : Bool) : B (n + 1) := + ⟨2 * x.val + b.toNat, by have := x.isLt; cases b <;> simp [pow_succ] <;> omega⟩ + +/-- The quantity computed by `⟨x.val / 2, (Nat.div_le_self ..).trans_lt x.isLt⟩`. -/ +def half {n : ℕ} (x : B n) : B n := ⟨x.val / 2, (Nat.div_le_self ..).trans_lt x.isLt⟩ + +/-- Tests whether `x.val % 2 = 1` holds. -/ +def odd {n : ℕ} (x : B n) : Bool := decide (x.val % 2 = 1) + +private theorem inc_value (n : ℕ) (x : Val (word n)) : + Lookup.value n (Lookup.inc n x) = + if Lookup.value n x + 1 < 2 ^ n then Lookup.value n x + 1 else 0 := by + induction n with + | zero => rfl + | succ n ih => + obtain ⟨b, y⟩ := x + have := Control.value_lt n y + cases b <;> simp [Lookup.inc, Lookup.value, ih, pow_succ] <;> split_ifs <;> omega + +private def extend : (n : ℕ) → Val (word n) → Val (word (n + 1)) + | 0, _ => (false, ()) + | n + 1, x => (x.1, extend n x.2) + +private theorem extend_value (n : ℕ) (x : Val (word n)) : + Lookup.value (n + 1) (extend n x) = Lookup.value n x := by + induction n with + | zero => rfl + | succ n ih => + change x.1.toNat + 2 * Lookup.value (n + 1) (extend n x.2) = _ + rw [ih] + rfl + +variable (F : Type) [Field F] + +private theorem extend_net (n : ℕ) : DNet F (word n) (word (n + 1)) (extend n) (n + 1) := by + induction n with + | zero => exact DNet.table F _ _ _ (by decide) + | succ n ih => exact ((DNet.id F .bit).par ih).mono (by simp [wd]; omega) + +/-- Append a zero as the new most significant bit. -/ +theorem numeric_extend (n : ℕ) : + Circuit F (.addr n) (.addr (n + 1)) + (fun x => Fin.castLE (by rw [pow_succ]; omega) x) (n + 1) := by + apply Circuit.of_dnet (.refl _) (.refl _) (extend_net F n) + intro x + simp only [Equiv.coe_refl, Function.comp_id] + rw [decode_addr, ← code_addr] + congr 1 + exact Fin.ext (extend_value n x) + +theorem numeric_select (n : ℕ) : + Circuit F (.pair (.pair (.addr n) (.addr n)) .bit) (.addr n) + (fun x => if x.2 then x.1.1 else x.1.2) (1000 * (1 + n)) := by + apply Circuit.of_dnet (.refl _) (.refl _) ((selectWord F n).mono (n := 1000 * (1 + n)) (by omega)) + intro x + let f (p : (B n × B n) × Bool) := (Format.addr n).code (if p.2 then p.1.1 else p.1.2) + have hd : (Format.pair (.pair (.addr n) (.addr n)) .bit).code.symm + (bits (.pair (.pair (word n) (word n)) .bit) x) = + ((Control.index n x.1.1, Control.index n x.1.2), x.2) := + Prod.ext (decode_pair n x.1) rfl + refine Eq.trans ?_ (congrArg f hd.symm) + obtain ⟨⟨a, b⟩, c⟩ := x + cases c <;> exact (code_addr n _).symm + +theorem numeric_inc (n : ℕ) : + Circuit F (.addr n) (.addr n) (fun x => x + 1) (1000 * (1 + n)) := by + apply Circuit.of_dnet (.refl _) (.refl _) ((Lookup.inc_net F n).mono (n := 1000 * (1 + + n)) (by omega)) + intro x + simp only [Equiv.coe_refl, Function.comp_id] + rw [decode_addr n x, ← code_addr n (Lookup.inc n x)] + congr 1 + apply Fin.ext + change Lookup.value n (Lookup.inc n x) = (Lookup.value n x + 1 % 2 ^ n) % 2 ^ n + rw [Nat.add_mod_mod, inc_value] + have := Control.value_lt n x + split_ifs with h + · exact (Nat.mod_eq_of_lt h).symm + · rw [show Lookup.value n x + 1 = 2 ^ n by omega, Nat.mod_self] + +theorem numeric_double (n : ℕ) : + Circuit F (.pair (.addr n) .bit) (.addr (n + 1)) (fun x => double x.1 x.2) (1000 * (1 + n)) + := by + have h := (DNet.id F (.pair (word n) .bit)).post (.swap _ _) + apply Circuit.of_dnet (.refl _) (.refl _) (h.mono (n := 1000 * (1 + n)) (by simp [wd]; omega)) + intro x + change bits (word (n + 1)) (x.2, x.1) = + (Format.addr (n + 1)).code (double ((Format.addr n).code.symm (bits (word n) x.1)) x.2) + rw [decode_addr, ← code_addr] + congr 1 + apply Fin.ext + exact Nat.add_comm _ _ + +theorem numeric_half (n : ℕ) : + Circuit F (.addr n) (.addr n) half (1000 * (1 + n)) := by + cases n with + | zero => + convert (Circuit.id F (.addr 0)).mono (n := 1000 * (1 + 0)) (by simp) using 1 + funext x + exact @Subsingleton.elim (Fin 1) _ _ _ + | succ n => + have h := (DNet.snd F .bit (word n)).comp (extend_net F n) + apply Circuit.of_dnet (.refl _) (.refl _) (h.mono (n := 1000 * (1 + (n + 1))) (by + simp [wd] + omega)) + intro x + change bits (word (n + 1)) (extend n x.2) = + (Format.addr (n + 1)).code (half ((Format.addr (n + 1)).code.symm (bits (word (n + 1)) x))) + rw [decode_addr, ← code_addr] + congr 1 + apply Fin.ext + change Lookup.value (n + 1) (extend n x.2) = Lookup.value (n + 1) x / 2 + obtain ⟨b, x⟩ := x + rw [extend_value] + cases b <;> simp [Lookup.value] + omega + +theorem numeric_odd (n : ℕ) : + Circuit F (.addr n) .bit odd (1000 * (1 + n)) := by + cases n with + | zero => + have h := Lookup.const_net F .bit false + apply Circuit.of_dnet (.refl _) (.refl _) (h.mono (n := 1000 * (1 + 0)) (by decide)) + intro x + rfl + | succ n => + have h := DNet.fst F .bit (word n) + apply Circuit.of_dnet (.refl _) (.refl _) (h.mono (n := 1000 * (1 + (n + 1))) (by + simp [wd] + omega)) + intro x + change bits .bit x.1 = bits .bit (odd ((Format.addr (n + 1)).code.symm (bits (word (n + 1)) x))) + rw [decode_addr] + congr 1 + change x.1 = decide (Lookup.value (n + 1) x % 2 = 1) + obtain ⟨b, x⟩ := x + cases b <;> simp [Lookup.value] + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- # Inverting an explicitly listed permutation by sorting -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +private theorem sorted_inverse {h : ℕ} (g : Equiv.Perm (B h)) : + permutation g (fun _ => true) = g.symm := by + let σ := permutation g (fun _ => true) + have hm : Monotone (g ∘ σ) := by + intro i j hij + have he := Tuple.monotone_sort (fun a => toLex (false, toLex (g a, a))) hij + change toLex (false, toLex (g (σ i), σ i)) ≤ toLex (false, toLex (g (σ j), σ j)) at he + rcases Prod.Lex.toLex_le_toLex.mp he with he | ⟨_, he⟩ + · exact (lt_irrefl _ he).elim + rcases Prod.Lex.toLex_le_toLex.mp he with hl | ⟨he, _⟩ + · exact hl.le + · exact he.le + have he := (hm.strictMono_of_injective (g.injective.comp σ.injective)).eq_id + exact Equiv.ext (fun i => g.eq_symm_apply.mpr (congrFun he i)) + +theorem cheap_inverse (F : Type) [Field F] (h : ℕ) : + ∃ f, Cheap F h h (Perm h) (Perm h) f 100 ∧ + ∀ g : Equiv.Perm (B h), f g = ⇑g.symm := by + have hp : (Perm h).width ≤ 2 ^ h * (100 + h) ^ 1 := by simp [Perm] + have hb : (Format.vec h .bit).width ≤ 2 ^ h * (100 + h) ^ 1 := by + rw [Format.width_vec, Format.width_bit, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have he : Cheap F h h (.pair (Perm h) (.vec h .bit)) (Perm h) + (fun x => ⇑(permutation x.1 x.2)) 80 := by + obtain ⟨m, hm, hc⟩ := cheap_permutation F h h + refine ⟨m, hm, hc.trans (Nat.mul_le_mul_left _ ?_)⟩ + rw [show 80 = 2 * 40 from rfl, pow_mul] + exact Nat.pow_le_pow_left (by nlinarith) _ + have hi := (Cheap.id F hp).pair (Cheap.const F hp hb (fun _ => true)) + refine ⟨_, (hi.comp he).mono (by decide), fun g => ?_⟩ + change ⇑(permutation g (fun _ => true)) = ⇑g.symm + rw [sorted_inverse] + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Vector.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Vector.lean new file mode 100644 index 0000000000..b01dedcacc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/Vector.lean @@ -0,0 +1,136 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Address + +/-! +# Circuits on encoded data + +A format is a bijection between data and assignments to named bits. +Cost includes the lengths of both boundaries when accounting for +near-linear computation with polynomial overhead in the address width. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +open Install +/-- The quantity computed by `Fin (2 ^ h)`. -/ +abbrev B (h : ℕ) := Fin (2 ^ h) + +/-- The data for the format construction, including `obj`, `pins`, `[finite`, `code`. -/ +structure Format where + /-- The type represented by the encoding. -/ + obj : Type + /-- The bit positions of the representation. -/ + pins : Type + [finite : Fintype pins] + /-- An equivalence between represented values and assignments to their bit positions. -/ + code : obj ≃ (pins → Bool) + +attribute [instance] Format.finite + +namespace Format + +/-- The number of bit positions in the encoding. -/ +abbrev width (A : Format) := Fintype.card A.pins + +/-- Uses the slot encoding of a circuit wire as a bit format. -/ +abbrev wire (a : Wire) : Format := ⟨Val a, slots a, bits a⟩ + +/-- The encoding of a single Boolean value. -/ +abbrev bit := wire .bit +/-- The little-endian bit format for a bounded natural-number address. -/ +abbrev addr (h : ℕ) : Format := ⟨B h, slots (word h), (Control.decode h).symm⟩ + +/-- Encodes a pair by concatenating the bit positions of its two components. -/ +abbrev pair (A D : Format) : Format := + ⟨A.obj × D.obj, A.pins ⊕ D.pins, + (A.code.prodCongr D.code).trans (Equiv.sumPiEquivProdPi (fun _ => Bool)).symm⟩ + +/-- Encodes a vector of values with one copy of the format per address. -/ +abbrev vec (h : ℕ) (A : Format) : Format := + ⟨B h → A.obj, B h × A.pins, + (Equiv.piCongrRight (fun _ => A.code)).trans (Equiv.curry _ _ _).symm⟩ + +theorem width_bit : bit.width = 1 := rfl +@[simp] theorem width_addr (h : ℕ) : (addr h).width = h := by simp [width] +@[simp] theorem width_pair (A D : Format) : (pair A D).width = A.width + D.width := + Fintype.card_sum +@[simp] theorem width_vec (h : ℕ) (A : Format) : (vec h A).width = 2 ^ h * A.width := by + simp [width, Fintype.card_prod] + +end Format + +/-- Computes the perm by the application `Format.vec h (.addr h)`. -/ +abbrev Perm (h : ℕ) := Format.vec h (.addr h) + +/-- Requires `BNet F (D.code ∘ f ∘ A.code.symm) m`. -/ +def Circuit (F : Type) [Field F] (A D : Format) (f : A.obj → D.obj) (m : ℕ) : Prop := + BNet F (D.code ∘ f ∘ A.code.symm) m + +/-- The condition `∃ m, Circuit F A D f m ∧ A.width + D.width + m ≤ 2 ^ h * (100 + k) ^ c` on +the specified data. -/ +def Cheap (F : Type) [Field F] (h k : ℕ) (A D : Format) (f : A.obj → D.obj) (c : ℕ) : Prop := + ∃ m, Circuit F A D f m ∧ A.width + D.width + m ≤ 2 ^ h * (100 + k) ^ c + +namespace Circuit + +variable {F : Type} [Field F] {A D E G : Format} {m n h : ℕ} {f : A.obj → D.obj} + +theorem mono (hf : Circuit F A D f m) (h : m ≤ n) : Circuit F A D f n := + BNet.mono hf h + +theorem comp {g : D.obj → E.obj} (hf : Circuit F A D f m) (hg : Circuit F D E g n) : + Circuit F A E (g ∘ f) (m + n) := by + simpa only [Circuit, Function.comp_def, Equiv.symm_apply_apply] using BNet.comp hf hg + +theorem pair {g : A.obj → E.obj} (hf : Circuit F A D f m) (hg : Circuit F A E g n) : + Circuit F A (.pair D E) (fun x => (f x, g x)) (5 * A.width + m + n) := + BNet.pair hf hg + +theorem par {g : E.obj → G.obj} (hf : Circuit F A D f m) (hg : Circuit F E G g n) : + Circuit F (.pair A E) (.pair D G) (Prod.map f g) (m + n) := + BNet.parallel hf hg + +theorem map (f : B h → A.obj → D.obj) (hf : ∀ i, Circuit F A D (f i) m) : + Circuit F (.vec h A) (.vec h D) (fun x i => f i (x i)) (2 ^ h * m) := + BNet.family h _ hf + +theorem id (F : Type) [Field F] (A : Format) : Circuit F A A _root_.id A.width := by + simp only [Circuit, Function.comp_def, id_eq, Equiv.apply_symm_apply] + exact BNet.id F A.pins + +/-- A structural projection can reuse bits arbitrarily. -/ +theorem project (e : D.pins → A.pins) (he : ∀ x i, D.code (f x) i = A.code x (e i)) : + Circuit F A D f (A.width + 2 * D.width) := by + intro a b i j + unfold Format.width + rw [Fintype.card_congr i, Fintype.card_congr j, card_slots, card_slots] + convert Install.project_net F (i ∘ e ∘ j.symm) using 1 + funext x + apply (bits b).injective + funext k + simp only [bits_project, Function.comp_apply, Equiv.apply_symm_apply, he] + +theorem of_dnet {a b : Wire} (i : A.pins ≃ slots a) (j : D.pins ≃ slots b) + {g : Val a → Val b} (hg : DNet F a b g m) + (he : ∀ x, bits b (g x) ∘ j = D.code (f (A.code.symm (bits a x ∘ i)))) : + Circuit F A D f m := by + apply BNet.of_layout i j + convert hg using 1 + funext x + apply (bits b).injective + rw [Equiv.apply_symm_apply] + funext k + simpa only [Function.comp_apply, Equiv.apply_symm_apply] using (congrFun (he x) (j.symm k)).symm + +end Circuit +end MatrixMultiplicationAllFields.MatrixExponent.Coloring diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/VectorSort.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/VectorSort.lean new file mode 100644 index 0000000000..c25c13757c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Coloring/VectorSort.lean @@ -0,0 +1,921 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Dynamics.PeriodicPts.Lemmas +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Algebra.BigOperators.Group.Finset.Basic +public import Mathlib.Data.Fin.Tuple.Sort +public import Mathlib.Order.Prod.Lex.Basic +public import Mathlib.Algebra.Ring.Parity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Batcher +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Scan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Named + +/-! +# Alternating colours on paired edges + +The two endpoint involutions share their fixed points. On the remaining +edges each alternating cycle splits into two disjoint orbits of the +two-step permutation. Comparing the least indices of the two orbits +chooses one of the two possible colourings. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +/-- In the case `0`, this construction gives `P`. -/ +def jump {α : Type} (P : α → α) : ℕ → α → α + | 0 => P + | k + 1 => fun x => jump P k (jump P k x) + +/-- In the case `0`, this construction gives `id`. -/ +def low {α : Type} [LinearOrder α] (P : α → α) : ℕ → α → α + | 0 => id + | k + 1 => fun x => min (low P k x) (low P k (jump P k x)) + +/-- Tests whether `low (R ∘ L) h x < low (R ∘ L) h (L x)` holds. -/ +def colour (h : ℕ) (L R : Fin (2 ^ h) → Fin (2 ^ h)) (x : Fin (2 ^ h)) : Bool := + decide (low (R ∘ L) h x < low (R ∘ L) h (L x)) + +open Function + +variable {α : Type} + +private theorem jump_iterate (P : α → α) (k : ℕ) (x : α) : + jump P k x = P^[2 ^ k] x := by + induction k generalizing x with + | zero => rfl + | succ k ih => simp only [jump, ih, pow_succ, mul_two, iterate_add_apply] + +private theorem low_hit [LinearOrder α] (P : α → α) (k : ℕ) (x : α) : + ∃ i : ℕ, low P k x = P^[i] x := by + induction k generalizing x with + | zero => exact ⟨0, rfl⟩ + | succ k ih => + simp only [low] + rcases min_choice (low P k x) (low P k (jump P k x)) with h | h + · rw [h]; exact ih x + · obtain ⟨i, hi⟩ := ih (jump P k x) + exact ⟨i + 2 ^ k, by rw [h, hi, jump_iterate, iterate_add_apply]⟩ + +private theorem low_le [LinearOrder α] (P : α → α) (k : ℕ) (x : α) + (i : ℕ) (hi : i < 2 ^ k) : low P k x ≤ P^[i] x := by + induction k generalizing x i with + | zero => + have : i = 0 := by simpa using hi + subst i + rfl + | succ k ih => + simp only [low] + by_cases h : i < 2 ^ k + · exact (min_le_left ..).trans (ih _ _ h) + rw [pow_succ] at hi + calc + _ ≤ low P k (jump P k x) := min_le_right .. + _ ≤ P^[i - 2 ^ k] (jump P k x) := ih _ _ (by omega) + _ = P^[i] x := by rw [jump_iterate, ← iterate_add_apply, Nat.sub_add_cancel (by omega)] + +private theorem low_step {h : ℕ} {P : Fin (2 ^ h) → Fin (2 ^ h)} + (hp : Injective P) (x : Fin (2 ^ h)) : low P h (P x) = low P h x := by + have hpos (y) : 0 < minimalPeriod P y := + minimalPeriod_pos_of_mem_periodicPts (by rw [injective_iff_periodicPts_eq_univ.mp hp]; trivial) + have hmin (y) (i : ℕ) : low P h y ≤ P^[i] y := by + rw [← iterate_mod_minimalPeriod_eq] + apply low_le + exact (Nat.mod_lt _ (hpos y)).trans_le (minimalPeriod_le_card.trans_eq (Fintype.card_fin _)) + apply le_antisymm + · obtain ⟨i, hi⟩ := low_hit P h x + have he : P^[minimalPeriod P x - 1] (P x) = x := by + rw [← iterate_succ_apply, Nat.succ_eq_add_one, Nat.sub_add_cancel (hpos x)] + exact isPeriodicPt_minimalPeriod _ _ + rw [hi] + simpa only [iterate_add_apply, he] using hmin (P x) (i + (minimalPeriod P x - 1)) + · obtain ⟨i, hi⟩ := low_hit P h (P x) + rw [hi, ← iterate_succ_apply] + exact hmin x _ + +private theorem no_mirror {L R : α → α} (hl : Involutive L) (hr : Involutive R) + (hf : ∀ x, L x = x ↔ R x = x) (k : ℕ) (x : α) (hx : L x ≠ x) : + (R ∘ L)^[k] x ≠ L x := by + have hL (y) (hy : L y ≠ y) : L (L y) ≠ L y := hl.injective.ne hy + have hR (y) (hy : L y ≠ y) : L (R y) ≠ R y := + (hf _).not.mpr (hr.injective.ne ((hf _).not.mp hy)) + induction k using Nat.twoStepInduction generalizing x with + | zero => exact hx.symm + | one => exact (hf _).not.mp (hL x hx) + | more k ih _ => + intro h + rw [iterate_succ_apply', iterate_succ_apply] at h + have he : (R ∘ L) (L ((R ∘ L) x)) = L x := by simp only [comp_apply, hl _, hr _] + exact ih ((R ∘ L) x) (hR _ (hL x hx)) + ((hr.injective.comp hl.injective) (h.trans he.symm)) + +variable {h : ℕ} {L R : Fin (2 ^ h) → Fin (2 ^ h)} + +private theorem low_ne (hl : Involutive L) (hr : Involutive R) (hf : ∀ x, L x = x ↔ R x = x) + {x : Fin (2 ^ h)} (hx : L x ≠ x) : low (R ∘ L) h x ≠ low (R ∘ L) h (L x) := by + intro e + obtain ⟨i, hi⟩ := low_hit (R ∘ L) h x + obtain ⟨j, hj⟩ := low_hit (R ∘ L) h (L x) + rw [hi, hj] at e + have hp := hr.injective.comp hl.injective + rcases le_total j i with hh | hh + · obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le hh + rw [iterate_add_apply] at e + exact no_mirror hl hr hf k x hx ((hp.iterate j) e) + · obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le hh + rw [iterate_add_apply] at e + exact no_mirror hl hr hf k (L x) (hl.injective.ne hx) (((hp.iterate i) e.symm).trans (hl + x).symm) + +theorem colour_left (hl : Involutive L) (hr : Involutive R) (hf : ∀ x, L x = x ↔ R x = x) + {x : Fin (2 ^ h)} (hx : L x ≠ x) : colour h L R (L x) = !(colour h L R x) := by + unfold colour + rw [hl x] + rcases lt_or_gt_of_ne (low_ne hl hr hf hx) with h | h <;> simp [h, h.not_gt] + +theorem colour_right (hl : Involutive L) (hr : Involutive R) (hf : ∀ x, L x = x ↔ R x = x) + {x : Fin (2 ^ h)} (hx : L x ≠ x) : colour h L R (R x) = !(colour h L R x) := by + rw [← colour_left hl hr hf hx] + have hp := hr.injective.comp hl.injective + have h₁ := low_step hp (L x) + have h₂ := low_step hp (L (R x)) + simp only [comp_apply, hl _, hr _] at h₁ h₂ + simp only [colour, h₁, ← h₂, hl _] + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- +# Pairing adjacent active edges + +After sorting, the active edges incident to any initial segment of +vertices form a prefix. Its length is even, so adjacent pairs never +straddle a change of vertex or the end of the active region. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable {h k : ℕ} + +/-- The indexed operation `Tuple.sort (fun i => toLex (!a i, toLex (f i, i)))`. -/ +def permutation (f : Fin (2 ^ h) → Fin (2 ^ k)) (a : Fin (2 ^ h) → Bool) := + Tuple.sort (fun i => toLex (!a i, toLex (f i, i))) + +/-- In the case `0, i`, this construction gives `i`. -/ +def toggle : (h : ℕ) → Fin (2 ^ h) → Fin (2 ^ h) + | 0, i => i + | h + 1, i => ⟨if i.val % 2 = 0 then i.val + 1 else i.val - 1, by + have := i.isLt + simp only [pow_succ] at * + split <;> omega⟩ + +/-- Returns `permutation f a (toggle h ((permutation f a).symm i))` when `a i` holds, and `i` +otherwise. -/ +def partner (f : Fin (2 ^ h) → Fin (2 ^ k)) (a : Fin (2 ^ h) → Bool) (i : Fin (2 ^ h)) : Fin (2 ^ + h) := + if a i then permutation f a (toggle h ((permutation f a).symm i)) else i + +/-- The condition `∀ j, Even (Finset.univ.filter fun i => a i = true ∧ f i = j).card` on the +specified data. -/ +def EvenFibers (f : Fin (2 ^ h) → Fin (2 ^ k)) (a : Fin (2 ^ h) → Bool) : Prop := + ∀ j, Even (Finset.univ.filter fun i => a i = true ∧ f i = j).card + +theorem toggle_involutive (h : ℕ) : Function.Involutive (toggle h) := by + intro i + cases h with + | zero => rfl + | succ h => + apply Fin.ext + simp only [toggle] + split_ifs <;> omega + +variable {f : Fin (2 ^ h) → Fin (2 ^ k)} {a : Fin (2 ^ h) → Bool} + +private theorem ordered {i j : Fin (2 ^ h)} (hij : i ≤ j) (ha : a (permutation f a j) = true) : + a (permutation f a i) = true ∧ f (permutation f a i) ≤ f (permutation f a j) := by + have hs := Tuple.monotone_sort (fun i => toLex (!a i, toLex (f i, i))) hij + let σ := permutation f a + change toLex (!a (σ i), toLex (f (σ i), σ i)) ≤ toLex (!a (σ j), toLex (f (σ j), σ j)) at hs + rw [Prod.Lex.toLex_le_toLex, ha] at hs + rcases hs with he | ⟨he, hr⟩ + · rcases Bool.dichotomy (a (σ i)) with e | e + · exact ((by decide : ¬ (true < false)) (by simpa [e] using he)).elim + · simp only [e, Bool.not_true, lt_irrefl] at he + · refine ⟨by simpa using he, ?_⟩ + rcases Prod.Lex.toLex_le_toLex.mp hr with hl | hl + · exact hl.le + · exact hl.1.le + +private theorem EvenFibers.prefix_even (he : EvenFibers f a) (j : Fin (2 ^ k)) : + Even (Finset.univ.filter fun i => a i = true ∧ f i ≤ j).card := by + let S := Finset.univ.filter (fun i => a i) + have hh := Finset.sum_card_fiberwise_eq_card_filter S (Finset.Iic j) f + simp only [S, Finset.filter_filter, Finset.mem_Iic] at hh + rw [← hh] + choose b hb using he + exact ⟨∑ t ∈ Finset.Iic j, b t, by simp only [hb, Finset.sum_add_distrib]⟩ + +private theorem EvenFibers.adjacent (he : EvenFibers f a) {i j : Fin (2 ^ h)} + (hi : i.val % 2 = 0) (hj : j.val = i.val + 1) (ha : a (permutation f a i) = true) : + a (permutation f a j) = true ∧ f (permutation f a j) = f (permutation f a i) := by + let σ := permutation f a + by_contra bad + have hn : (Finset.Iic i).card = (Finset.univ.filter fun l => a l = true ∧ f l ≤ f (σ i)).card + := by + apply Finset.card_equiv σ + intro s + simp only [Finset.mem_Iic, Finset.mem_filter, Finset.mem_univ, true_and] + refine ⟨fun hsi => ordered hsi ha, fun ⟨hs, hf⟩ => ?_⟩ + by_contra! hlt + obtain ⟨ha', hf'⟩ := ordered (show j ≤ s by omega) hs + exact bad ⟨ha', le_antisymm (hf'.trans hf) (ordered (show i ≤ j by omega) ha').2⟩ + obtain ⟨t, ht⟩ := he.prefix_even (f (σ i)) + rw [← hn, Fin.card_Iic] at ht + omega + +private theorem EvenFibers.neighbor (he : EvenFibers f a) (i : Fin (2 ^ h)) + (ha : a (permutation f a i) = true) : + a (permutation f a (toggle h i)) = true ∧ + f (permutation f a (toggle h i)) = f (permutation f a i) ∧ toggle h i ≠ i := by + cases h with + | zero => + let z := permutation f a i + let S := Finset.univ.filter (fun j => a j = true ∧ f j = f z) + have hp : 0 < S.card := Finset.card_pos.mpr ⟨z, Finset.mem_filter.mpr ⟨Finset.mem_univ _, ha, + rfl⟩⟩ + have hle : S.card ≤ 1 := by simpa using Finset.card_le_univ S + obtain ⟨b, hb⟩ : Even S.card := he (f z) + omega + | succ h => + let j := toggle (h + 1) i + by_cases ht : i.val % 2 = 0 + · have hj : j.val = i.val + 1 := by simp [j, toggle, ht] + obtain ⟨ha', heq⟩ := he.adjacent ht hj ha + exact ⟨ha', heq, show j ≠ i by omega⟩ + · have hj : j.val = i.val - 1 := by simp [j, toggle, ht] + have ha' := (ordered (show j ≤ i by omega) ha).1 + obtain ⟨_, heq⟩ := he.adjacent (i := j) (j := i) (by omega) (by omega) ha' + exact ⟨ha', heq.symm, show j ≠ i by omega⟩ + +private theorem EvenFibers.active (he : EvenFibers f a) {i : Fin (2 ^ h)} (hi : a i = true) : + a (partner f a i) = true ∧ f (partner f a i) = f i ∧ partner f a i ≠ i := by + obtain ⟨j, rfl⟩ := (permutation f a).surjective i + simpa [partner, hi] using he.neighbor j hi + +theorem EvenFibers.fixed (he : EvenFibers f a) (i : Fin (2 ^ h)) : + partner f a i = i ↔ a i = false := by + cases hi : a i + · simp [partner, hi] + · simp [(he.active hi).2.2] + +theorem EvenFibers.preserve (he : EvenFibers f a) (i : Fin (2 ^ h)) : f (partner f a i) = f i := by + cases hi : a i + · rw [(he.fixed i).mpr hi] + · exact (he.active hi).2.1 + +theorem EvenFibers.involutive (he : EvenFibers f a) : Function.Involutive (partner f a) := by + intro i + cases hi : a i + · rw [(he.fixed i).mpr hi, (he.fixed i).mpr hi] + · have ha := (he.active hi).1 + rw [partner, ite_eq_left ha, partner, ite_eq_left hi, Equiv.symm_apply_apply, + toggle_involutive, Equiv.apply_symm_apply] + +/-- Computes the split by the application `colour h (partner f a) (partner g a)`. -/ +def split {h k : ℕ} (f g : Fin (2 ^ h) → Fin (2 ^ k)) (a : Fin (2 ^ h) → Bool) := + colour h (partner f a) (partner g a) + +private theorem EvenFibers.half (he : EvenFibers f a) {c : Fin (2 ^ h) → Bool} + (hc : ∀ i, a i = true → c (partner f a i) = !(c i)) (j : Fin (2 ^ k)) (b : Bool) : + 2 * (Finset.univ.filter fun i => a i = true ∧ f i = j ∧ c i = b).card = + (Finset.univ.filter fun i => a i = true ∧ f i = j).card := by + let S := Finset.univ.filter (fun i => a i = true ∧ f i = j) + have eq : (S.filter fun i => c i = b).card = (S.filter fun i => c i ≠ b).card := by + apply Finset.card_equiv he.involutive.toPerm + intro i + change i ∈ _ ↔ partner f a i ∈ _ + simp only [Finset.mem_filter, S, Finset.mem_univ, true_and, he.preserve] + cases hi : a i + · rw [(he.fixed i).mpr hi, hi] + simp + · rw [(he.active hi).1, hc i hi] + cases b <;> cases c i <;> simp + have sum := Finset.card_filter_add_card_filter_not (s := S) (fun i => c i = b) + rw [← eq, ← two_mul] at sum + simpa only [S, Finset.filter_filter, and_assoc] using sum + +theorem split_balanced {g : Fin (2 ^ h) → Fin (2 ^ k)} (hf : EvenFibers f a) (hg : EvenFibers g a) + (j : Fin (2 ^ k)) (b : Bool) : + 2 * (Finset.univ.filter fun i => a i = true ∧ f i = j ∧ split f g a i = b).card = + (Finset.univ.filter fun i => a i = true ∧ f i = j).card ∧ + 2 * (Finset.univ.filter fun i => a i = true ∧ g i = j ∧ split f g a i = b).card = + (Finset.univ.filter fun i => a i = true ∧ g i = j).card := by + have eq (i) : partner f a i = i ↔ partner g a i = i := (hf.fixed i).trans (hg.fixed i).symm + exact ⟨hf.half (fun i hi => colour_left hf.involutive hg.involutive eq (hf.active hi).2.2) j b, + hg.half (fun i hi => colour_right hf.involutive hg.involutive eq (hf.active hi).2.2) j b⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- # Polynomial overhead for compositions and parallel operations -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable {F : Type} [Field F] {h k c d : ℕ} {A D E : Format} {f : A.obj → D.obj} + +private theorem grow (h k c : ℕ) : + 100 * (2 ^ h * (100 + k) ^ c) ≤ 2 ^ h * (100 + k) ^ (c + 1) := by + rw [mul_comm 100, pow_succ, ← mul_assoc] + exact Nat.mul_le_mul_left _ (by omega) + +namespace Cheap + +theorem mono (hf : Cheap F h k A D f c) (le : c ≤ d) : Cheap F h k A D f d := by + obtain ⟨m, hf, hm⟩ := hf + exact ⟨m, hf, hm.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) le))⟩ + +theorem widen {l : ℕ} (hf : Cheap F h k A D f c) (le : k ≤ l) : Cheap F h l A D f c := by + obtain ⟨m, hf, hm⟩ := hf + exact ⟨m, hf, hm.trans (by gcongr)⟩ + +theorem comp {g : D.obj → E.obj} (hf : Cheap F h k A D f c) (hg : Cheap F h k D E g d) : + Cheap F h k A E (g ∘ f) (max c d + 1) := by + obtain ⟨m, hf, hm⟩ := hf.mono (le_max_left c d) + obtain ⟨n, hg, hn⟩ := hg.mono (le_max_right c d) + exact ⟨_, hf.comp hg, le_trans (by omega) (grow h k (max c d))⟩ + +theorem pair {g : A.obj → E.obj} (hf : Cheap F h k A D f c) (hg : Cheap F h k A E g d) : + Cheap F h k A (.pair D E) (fun x => (f x, g x)) (max c d + 1) := by + obtain ⟨m, hf, hm⟩ := hf.mono (le_max_left c d) + obtain ⟨n, hg, hn⟩ := hg.mono (le_max_right c d) + refine ⟨_, hf.pair hg, le_trans ?_ (grow h k (max c d))⟩ + rw [Format.width_pair] + omega + +theorem id (F : Type) [Field F] (ha : A.width ≤ 2 ^ h * (100 + k) ^ c) : + Cheap F h k A A _root_.id (c + 1) := + ⟨_, Circuit.id F A, le_trans (by omega) (grow h k c)⟩ + +theorem const (F : Type) [Field F] (ha : A.width ≤ 2 ^ h * (100 + k) ^ c) + (hd : D.width ≤ 2 ^ h * (100 + k) ^ c) (x : D.obj) : + Cheap F h k A D (fun _ => x) (c + 1) := by + have t : Install.Depends (fun _ : A.pins → Bool => D.code x) 0 := + fun _ => ⟨∅, by simp, fun _ _ _ => rfl⟩ + refine ⟨_, t.bnet F, le_trans ?_ (grow h k c)⟩ + change A.width + D.width + (A.width + 16 * D.width) ≤ _ + omega + +theorem project (F : Type) [Field F] (ha : A.width ≤ 2 ^ h * (100 + k) ^ c) + (hd : D.width ≤ 2 ^ h * (100 + k) ^ c) (e : D.pins → A.pins) + (he : ∀ x i, D.code (f x) i = A.code x (e i)) : Cheap F h k A D f (c + 1) := + ⟨_, Circuit.project e he, le_trans (by omega) (grow h k c)⟩ + +theorem fst {f : A.obj → D.obj × E.obj} (hf : Cheap F h k A (.pair D E) f c) : + Cheap F h k A D (fun x => (f x).1) (c + 1) := by + obtain ⟨m, hf, hm⟩ := hf + have hp := Circuit.project (F := F) (A := .pair D E) (D := D) (f := Prod.fst) Sum.inl + (fun _ _ => rfl) + refine ⟨_, hf.comp hp, le_trans ?_ (grow h k c)⟩ + simp only [Format.width_pair] at hm ⊢ + omega + +theorem snd {f : A.obj → D.obj × E.obj} (hf : Cheap F h k A (.pair D E) f c) : + Cheap F h k A E (fun x => (f x).2) (c + 1) := by + obtain ⟨m, hf, hm⟩ := hf + have hp := Circuit.project (F := F) (A := .pair D E) (D := E) (f := Prod.snd) Sum.inr + (fun _ _ => rfl) + refine ⟨_, hf.comp hp, le_trans ?_ (grow h k c)⟩ + simp only [Format.width_pair] at hm ⊢ + omega + +theorem map (f : B h → A.obj → D.obj) (hf : ∀ i, Cheap F 0 k A D (f i) c) : + Cheap F h k (.vec h A) (.vec h D) (fun x i => f i (x i)) c := by + let m := (100 + k) ^ c - (A.width + D.width) + have hc (i) : Circuit F A D (f i) m := by + obtain ⟨_, hh, hm⟩ := hf i + exact hh.mono (by simp [m] at *; omega) + refine ⟨_, Circuit.map f hc, ?_⟩ + obtain ⟨_, _, hm⟩ := hf 0 + simp only [Format.width_vec, ← mul_add] + exact Nat.mul_le_mul_left _ (by simp [m] at *; omega) + +theorem zip {B : Format} {f : A.obj → (Coloring.B h → D.obj) × (Coloring.B h → B.obj)} + (hf : Cheap F h k A (.pair (.vec h D) (.vec h B)) f c) : + Cheap F h k A (.vec h (.pair D B)) (fun x i => ((f x).1 i, (f x).2 i)) (c + 1) := by + let g (y : (Coloring.B h → D.obj) × (Coloring.B h → B.obj)) (i : Coloring.B h) := (y.1 i, y.2 i) + have hz := Circuit.project (F := F) (A := .pair (.vec h D) (.vec h B)) + (D := .vec h (.pair D B)) (f := g) (Equiv.prodSumDistrib _ _ _) + (by rintro x ⟨i, j | j⟩ <;> rfl) + obtain ⟨_, hf, hm⟩ := hf + refine ⟨_, hf.comp hz, le_trans ?_ (grow h k c)⟩ + simp only [Format.width_vec, Format.width_pair, mul_add] at hm ⊢ + omega + +theorem iterate {f : A.obj → A.obj} (hf : Cheap F h k A A f c) {r : ℕ} (hr : r ≤ k) : + Cheap F h k A A (f^[r]) (c + 1) := by + obtain ⟨m, hf, hm⟩ := hf + have it (r : ℕ) : Circuit F A A (f^[r]) (A.width + r * m) := by + induction r with + | zero => simpa using Circuit.id F A + | succ r ih => + rw [Function.iterate_succ', Nat.succ_mul, ← Nat.add_assoc] + exact ih.comp hf + refine ⟨_, it r, ?_⟩ + rw [pow_succ, ← mul_assoc] + have := Nat.mul_le_mul hr (show m ≤ 2 ^ h * (100 + k) ^ c by omega) + rw [mul_add, mul_comm _ 100, mul_comm _ k] + omega + +end Cheap +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +/- # Bitonic sorting in a prescribed order on encoded records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +private theorem exchange {F : Type} [Field F] (t : ℕ) [L : LinearOrder (Val (word t))] + {m : ℕ} (p : DNet F (.pair (word t) (word t)) .bit (fun x => decide (L.lt x.1 x.2)) m) : + DNet F (.pair (word t) (word t)) (.pair (word t) (word t)) + (fun x => (min x.1 x.2, max x.1 x.2)) (m + 100 * (1 + t)) := by + let a := word t + have lo := selectWord F t + have hi := lo.pre ((Rewire.swap a a).par (.id .bit)) + have k := ((DNet.id F (.pair a a)).pair p).comp (lo.pair hi) + convert k.mono (n := m + 100 * (1 + t)) (by simp [wd, a]; omega) using 1 + funext ⟨x, y⟩ + by_cases hh : x < y + · simp [hh, min_eq_left hh.le, max_eq_right hh.le] + · simp [hh, min_eq_right (le_of_not_gt hh), max_eq_left (le_of_not_gt hh)] + +variable {F : Type} [Field F] {A : Format} [LinearOrder A.obj] {m : ℕ} + +theorem Circuit.sort (cmp : Circuit F (.pair A A) .bit (fun x => decide (x.1 < x.2)) m) + (h : ℕ) : + Circuit F (.vec h A) (.vec h A) (fun x => x ∘ Tuple.sort x) + (2 ^ h * (h + 1) ^ 2 * (m + 100 * (1 + A.width) + A.width)) := by + let t := A.width + let a := word t + let e : A.pins ≃ slots (word A.width) := Fintype.equivOfCardEq (by simp [Format.width]) + let decode (x : Val a) := A.code.symm (bits a x ∘ e) + have inj : Function.Injective decode := by + intro x y eq + have hh := A.code.symm.injective eq + apply (bits a).injective + funext j + simpa using congrFun hh (e.symm j) + let ord : LinearOrder (Val a) := LinearOrder.lift' decode inj + let _ := ord + have hd : DNet F (.pair a a) .bit (fun x => decide (ord.lt x.1 x.2)) m := + cmp (.pair a a) .bit (e.sumCongr e) (.refl _) + have hn := sortTree_net (exchange t hd) h + rw [wd_word] at hn + obtain ⟨L, hL⟩ := Layout.exists_tree a h + let i := ((Equiv.refl (B h)).prodCongr e).trans L.positions + apply Circuit.of_dnet (a := tree h a) (b := tree h a) i i hn + intro x + let read (y : Val (tree h a)) := decode ∘ L.read y + have er (y : Val (tree h a)) : + (Format.vec h A).code.symm (bits (tree h a) y ∘ i) = read y := by + funext j + change A.code.symm _ = A.code.symm _ + simp [Layout.read, i, Function.comp_def] + rfl + have ho : read (sortTree h x) = read x ∘ Tuple.sort (read x) := by + apply List.ofFn_injective + have ep (y : Val (tree h a)) : List.ofFn (read y) = (flatten h y).map decode := by + rw [← hL y, List.map_ofFn] + rw [ep] + refine List.Perm.eq_of_pairwise' ?_ (Tuple.monotone_sort _).sortedLE_ofFn.pairwise ?_ + · exact List.pairwise_map.mpr (sortTree_sorted h x) + · exact ((sortTree_perm h x).map decode).trans + ((ep x).symm ▸ (Equiv.Perm.ofFn_comp_perm ..).symm) + apply (Format.vec h A).code.symm.injective + rw [Equiv.symm_apply_apply, er, er] + exact ho + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- # Comparing little-endian addresses -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +/-- Computes the comparison bits by the application `Wire.pair .bit .bit`. -/ +abbrev comparisonBits := Wire.pair .bit .bit +/-- Computes the two words by the application `Wire.pair (word n) (word n)`. -/ +abbrev twoWords (n : ℕ) := Wire.pair (word n) (word n) + +/-- The value specified by `(decide (Lookup.value n x.1 < Lookup.value n x.2), decide +(Lookup.value n x.1 = Lookup.value n x.2))`. -/ +def cmp (n : ℕ) (x : Val (twoWords n)) : Val comparisonBits := + (decide (Lookup.value n x.1 < Lookup.value n x.2), + decide (Lookup.value n x.1 = Lookup.value n x.2)) + +variable (F : Type) [Field F] + +private theorem cmp_net (n : ℕ) : DNet F (twoWords n) comparisonBits (cmp n) (514 * n + 1) := by + induction n with + | zero => exact DNet.table F _ _ _ (by decide) + | succ n ih => + let combine (x : Val (.pair comparisonBits comparisonBits)) : Val comparisonBits := + (x.2.1 || (x.2.2 && !x.1.1 && x.1.2), x.2.2 && (x.1.1 == x.1.2)) + have gate : DNet F (.pair comparisonBits comparisonBits) comparisonBits combine 512 := by + obtain ⟨m, hm, hc⟩ := Net.dense (.pair comparisonBits comparisonBits) comparisonBits + (fun x y => if combine x = y then (1 : F) else 0) + exact ⟨m, hc, hm⟩ + have f := + (((DNet.id F comparisonBits).par ih).pre (.middle .bit (word n) .bit (word n))).comp gate + convert f.mono (n := 514 * (n + 1) + 1) (by simp [wd]; omega) using 1 + funext ⟨⟨i, x⟩, ⟨j, y⟩⟩ + cases i <;> cases j <;> apply Prod.ext <;> apply Bool.eq_iff_iff.mpr <;> + simp [cmp, combine, Lookup.value] <;> omega + +theorem lt_net (n : ℕ) : DNet F (twoWords n) .bit + (fun x => decide (Lookup.value n x.1 < Lookup.value n x.2)) (520 * (1 + n)) := + ((cmp_net F n).comp (DNet.fst F .bit .bit)).mono (by simp [wd]; omega) + +theorem code_addr (n : ℕ) (x : Val (word n)) : + (Format.addr n).code (Control.index n x) = bits (word n) x := by + change bits (word n) ((Control.index n).symm (Control.index n x)) = _ + rw [Equiv.symm_apply_apply] + +theorem decode_addr (n : ℕ) (x : Val (word n)) : + (Format.addr n).code.symm (bits (word n) x) = Control.index n x := by + rw [← code_addr, Equiv.symm_apply_apply] + +theorem decode_pair (n : ℕ) (x : Val (twoWords n)) : + (Format.pair (.addr n) (.addr n)).code.symm (bits (twoWords n) x) = + (Control.index n x.1, Control.index n x.2) := + Prod.ext (decode_addr n x.1) (decode_addr n x.2) + +theorem numeric_lt (n : ℕ) : + Circuit F (.pair (.addr n) (.addr n)) .bit (fun x => decide (x.1 < x.2)) (1000 * (1 + n)) := by + apply Circuit.of_dnet (.refl _) (.refl _) ((lt_net F n).mono (n := 1000 * (1 + n)) (by omega)) + intro x + exact congrArg (fun y : B n × B n => bits .bit (decide (y.1 < y.2))) (decode_pair n x).symm + +theorem numeric_min (n : ℕ) : + Circuit F (.pair (.addr n) (.addr n)) (.addr n) (fun x => min x.1 x.2) (1000 * (1 + n)) := by + have h := ((DNet.id F (twoWords n)).pair (lt_net F n)).comp (selectWord F n) + apply Circuit.of_dnet (.refl _) (.refl _) (h.mono (n := 1000 * (1 + n)) (by simp [wd]; omega)) + intro x + simp only [Equiv.coe_refl, Function.comp_id, decide_eq_true_eq] + rw [decode_pair n x] + by_cases hx : Lookup.value n x.1 < Lookup.value n x.2 + · rw [ite_eq_left hx, min_eq_left (show Control.index n x.1 ≤ Control.index n x.2 from hx.le), + code_addr] + · rw [ite_eq_right hx, min_eq_right (show Control.index n x.2 + ≤ Control.index n x.1 from le_of_not_gt hx), + code_addr] + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- # Computing the ordered permutation of an array -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +/-- Indexes the lex by the coordinates of `⟨Lex (A.obj × D.obj), A.pins ⊕ D.pins, (Format.pair A +D).code⟩`. -/ +abbrev Format.lex (A D : Format) : Format := + ⟨Lex (A.obj × D.obj), A.pins ⊕ D.pins, (Format.pair A D).code⟩ + +@[simp] theorem Format.width_lex (A D : Format) : + (A.lex D).width = A.width + D.width := Format.width_pair A D + +variable {F : Type} [Field F] + +theorem small {A : Format} (hw : A.width ≤ 3) (f : A.obj → Bool) : + Circuit F A .bit f 200 := by + have hh : Install.Depends (Format.bit.code ∘ f ∘ A.code.symm) 3 := by + intro i + refine ⟨Finset.univ, hw, ?_⟩ + intro x y he + rw [funext (fun j => he j (Finset.mem_univ _))] + exact (hh.bnet F).mono (by change A.width + 134 * 1 ≤ 200; omega) + +theorem lex_lt {A D : Format} [LinearOrder A.obj] [LinearOrder D.obj] {m n : ℕ} + (ha : Circuit F (.pair A A) .bit (fun x => decide (x.1 < x.2)) m) + (hd : Circuit F (.pair D D) .bit (fun x => decide (x.1 < x.2)) n) : + Circuit F (.pair (.lex A D) (.lex A D)) .bit (fun x => decide (x.1 < x.2)) + (50 * (A.width + D.width) + 2 * m + n + 200) := by + let X := Format.pair (.lex A D) (.lex A D) + have l := Circuit.project (F := F) (A := X) (D := .pair A A) + (f := fun x => (x.1.1, x.2.1)) (Sum.map Sum.inl Sum.inl) + (by rintro x (i|j) <;> rfl) + have r := Circuit.project (F := F) (A := X) (D := .pair A A) + (f := fun x => (x.2.1, x.1.1)) (Sum.swap ∘ Sum.map Sum.inl Sum.inl) + (by rintro x (i|j) <;> rfl) + have u := Circuit.project (F := F) (A := X) (D := .pair D D) + (f := fun x => (x.1.2, x.2.2)) (Sum.map Sum.inr Sum.inr) + (by rintro x (i|j) <;> rfl) + have g := small (F := F) (A := .pair .bit (.pair .bit .bit)) (by simp) + (fun x => x.1 || (!x.2.1 && x.2.2)) + have net := ((l.comp ha).pair ((r.comp ha).pair (u.comp hd))).comp g + convert net.mono (n := 50 * (A.width + D.width) + 2 * m + n + 200) + (by simp only [X, Format.width_pair, Format.width_lex]; omega) using 1 + funext ⟨x, y⟩ + change decide (toLex (x.1, x.2) < toLex (y.1, y.2)) = _ + rw [Bool.eq_iff_iff] + simp only [Function.comp_apply, Bool.or_eq_true, Bool.and_eq_true, Bool.not_eq_true', + decide_eq_true_eq, decide_eq_false_iff_not, Prod.Lex.toLex_lt_toLex] + grind + +private abbrev Fields (h k : ℕ) := Format.pair (.vec h (.addr k)) (.vec h .bit) +private abbrev Row (h k : ℕ) := Format.lex .bit (.lex (.addr k) (.addr h)) + +private def rows (h k : ℕ) (x : (Fields h k).obj) (i : B h) : (Row h k).obj := + toLex (!x.2 i, toLex (x.1 i, i)) + +private theorem prepared (F : Type) [Field F] (h k : ℕ) : + Circuit F (Fields h k) (.vec h (Row h k)) (rows h k) + ((Fields h k).width + 34 * (Format.vec h (Row h k)).width) := by + classical + have t : Install.Depends ((Format.vec h (Row h k)).code ∘ rows h k ∘ (Fields h k).code.symm) 1 + := by + rintro ⟨i, j | j | j⟩ + · refine ⟨{Sum.inr (i, ())}, by simp, fun x y e => ?_⟩ + exact congrArg Bool.not (e _ (by simp)) + · refine ⟨{Sum.inl (i, j)}, by simp, fun x y e => ?_⟩ + change (Format.addr k).code ((Format.addr k).code.symm _) _ = + (Format.addr k).code ((Format.addr k).code.symm _) _ + rw [Equiv.apply_symm_apply, Equiv.apply_symm_apply] + exact e _ (by simp) + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + exact t.bnet F + +theorem cheap_permutation (F : Type) [Field F] (h k : ℕ) : + Cheap F h (h + k) (.pair (.vec h (.addr k)) (.vec h .bit)) (Perm h) + (fun x => ⇑(permutation x.1 x.2)) 40 := by + have flag := small (F := F) (A := .pair .bit .bit) (by simp) (fun x => decide (x.1 < x.2)) + have cmp := lex_lt flag (lex_lt (numeric_lt F k) (numeric_lt F h)) + have hs := cmp.sort h + have out := Circuit.project (F := F) (A := .vec h (Row h k)) (D := Perm h) + (f := fun x i => (x i).2.2) (fun z => (z.1, .inr (.inr z.2))) (fun _ _ => rfl) + have net := ((prepared F h k).comp hs).comp out + refine (show Cheap F h (h + k) (Fields h k) (Perm h) _ 5 from ⟨_, net, ?_⟩).mono (by decide) + simp only [Format.width_pair, Format.width_lex, Format.width_addr, + Format.width_vec] + rw [Format.width_bit] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- # Simultaneous indirect reads of encoded data -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install.BNet + +variable {F I J : Type} [Field F] [Fintype I] [Fintype J] +variable {f : (I → Bool) → (J → Bool)} {m : ℕ} + +omit [Fintype I] [Fintype J] in +private theorem copiesFin [Finite I] [Finite J] (h : BNet F f m) (n : ℕ) : + BNet F (fun (x : Fin n × I → Bool) (p : Fin n × J) => + f (fun j => x (p.1, j)) p.2) (n * m) := by + let : Fintype I := Fintype.ofFinite I + let : Fintype J := Fintype.ofFinite J + induction n with + | zero => + have hp := (BNet.id F (Fin 0 × I)).rename (.refl _) (Equiv.equivOfIsEmpty _ (Fin 0 × J)) + convert hp using 1 + · funext x p + exact p.1.elim0 + · simp + | succ n ih => + let e (M : Type) := (Equiv.sumProdDistrib (Fin n) (Fin 1) M).symm.trans + (finSumFinEquiv.prodCongr (.refl M)) + have k := (h.rename (Equiv.uniqueProd I (Fin 1)).symm (Equiv.uniqueProd J (Fin 1)).symm) + rw [Nat.succ_mul] + convert (ih.parallel k).rename (e I) (e J) using 1 + funext x p + obtain ⟨⟨i, j⟩ | ⟨i, j⟩, rfl⟩ := (e J).surjective p + · simp only [Function.comp_apply, Equiv.symm_apply_apply] + rfl + · rw [Fin.eq_zero i] + simp only [Function.comp_apply, Equiv.symm_apply_apply] + rfl + +omit [Fintype I] [Fintype J] in +theorem copies [Finite I] [Finite J] (h : BNet F f m) (P : Type) [Fintype P] : + BNet F (fun (x : P × I → Bool) (p : P × J) => f (fun j => x (p.1, j)) p.2) + (Fintype.card P * m) := by + let : Fintype I := Fintype.ofFinite I + let : Fintype J := Fintype.ofFinite J + let e := (Fintype.equivFin P).symm + convert (h.copiesFin _).rename (e.prodCongr (.refl I)) (e.prodCongr (.refl J)) using 1 + funext x p + simp + +end MatrixMultiplicationAllFields.MatrixExponent.Install.BNet + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring +open Install + +private theorem read_all (F : Type) [Field F] (h : ℕ) (A : Format) : + Circuit F (.pair (.vec h A) (Perm h)) (.vec h A) (fun y i => y.1 (y.2 i)) + ((2 ^ h * A.width + 2 ^ h * h) + 2 * (A.width * (2 ^ h + 2 ^ h * h)) + + A.width * (10000 * 2 ^ h * (h + 1) ^ 3)) := by + let e : A.pins × (B h ⊕ (B h × slots (word h))) → + (Format.pair (.vec h A) (Perm h)).pins := + fun ⟨j, p⟩ => Sum.elim (fun i => .inl (i, j)) Sum.inr p + have r := ((Control.read_net F h).copies A.pins).pull e + have f := r.rename (.refl _) (Equiv.prodComm A.pins (B h)) + unfold Circuit + convert f using 1 + · funext x ⟨i, j⟩ + change A.code (A.code.symm (fun j => x (.inl (Control.decode h (fun k => x (.inr (i, k))), + j)))) j = _ + rw [Equiv.apply_symm_apply] + rfl + · simp [Format.width, Fintype.card_sum, Fintype.card_prod] + +theorem Cheap.lookup (F : Type) [Field F] (h k : ℕ) (A : Format) + (hh : h ≤ k) (ha : A.width ≤ k) : + Cheap F h k (.pair (.vec h A) (Perm h)) (.vec h A) (fun y i => y.1 (y.2 i)) 8 := by + refine ⟨_, read_all F h A, ?_⟩ + simp only [Format.width_pair, Format.width_vec, Format.width_addr] + calc + _ = 2 ^ h * (5 * A.width + 2 * h + 2 * A.width * h + A.width * (10000 * (h + 1) ^ 3)) := by ring + _ ≤ 2 ^ h * (5 * k + 2 * k + 2 * k * k + k * (10000 * (k + 1) ^ 3)) := by gcongr + _ ≤ 2 ^ h * (100 + k) ^ 8 := by gcongr; ring_nf; omega + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +/- +# Simultaneous finite local tables with indirect addressing + +The number of neighbors and the record format stay fixed as the +address width grows. The local truth table may depend on the center. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring +open Install + +variable {F : Type} [Field F] {A D : Format} {h k c t : ℕ} + +theorem Circuit.share (f : B t → A.obj → D.obj) {m : ℕ} (hf : ∀ i, Circuit F A D (f i) m) : + Circuit F A (.vec t D) (fun x i => f i x) (2 ^ t * (3 * A.width + m)) := + BNet.share t _ hf + +theorem Cheap.share (f : B t → A.obj → D.obj) (hf : ∀ i, Cheap F h k A D (f i) c) + (ht : 2 ^ t ≤ k) : Cheap F h k A (.vec t D) (fun x i => f i x) (c + 2) := by + let x := 2 ^ h * (100 + k) ^ c + have hx (i) : Circuit F A D (f i) x := by + obtain ⟨m, hm, he⟩ := hf i + exact hm.mono (by unfold x; omega) + obtain ⟨m, _, hm⟩ := hf 0 + have ha : A.width ≤ x := by unfold x; omega + have hd : D.width ≤ x := by unfold x; omega + refine ⟨_, Circuit.share f hx, ?_⟩ + rw [Format.width_vec, pow_add, ← mul_assoc] + change A.width + 2 ^ t * D.width + 2 ^ t * (3 * A.width + x) ≤ x * (100 + k) ^ 2 + calc + _ ≤ x + k * x + k * (3 * x + x) := by gcongr + _ = x * (1 + 5 * k) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ (by nlinarith) + +theorem Cheap.fixed (F : Type) [Field F] (f : A.obj → D.obj) + (hk : 2 * A.width + D.width + localCost A.width * D.width ≤ k) : + Cheap F 0 k A D f 1 := by + have hd : Depends (D.code ∘ f ∘ A.code.symm) A.width := + fun _ => ⟨Finset.univ, le_rfl, fun _ _ h => by rw [funext fun i => h i (Finset.mem_univ _)]⟩ + refine ⟨_, hd.bnet F, ?_⟩ + change A.width + D.width + (A.width + localCost A.width * D.width) ≤ _ + simp only [pow_zero, one_mul, pow_one] + omega + +private theorem pick (F : Type) [Field F] (A : Format) (h k t : ℕ) + (hh : h ≤ k) (ha : A.width ≤ k) (ht : 2 ^ t ≤ k) (j : B t) : + Cheap F h k (.pair (.vec h A) (.vec t (Perm h))) (.pair (.vec h A) (Perm h)) + (fun x => (x.1, x.2 j)) 3 := by + let X := Format.pair (.vec h A) (.vec t (Perm h)) + let Y := Format.pair (.vec h A) (Perm h) + have bound : A.width + 2 ^ t * h ≤ (100 + k) ^ 2 := by + nlinarith only [ha, Nat.mul_le_mul ht hh] + have bx : X.width ≤ 2 ^ h * (100 + k) ^ 2 := by + simp only [X, Format.width_pair, Format.width_vec, Format.width_addr] + rw [mul_left_comm (2 ^ t), ← mul_add] + exact Nat.mul_le_mul_left _ bound + have by' : Y.width ≤ 2 ^ h * (100 + k) ^ 2 := by + simp only [Y, Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add] + exact Nat.mul_le_mul_left _ (by nlinarith only [ha, hh]) + apply Cheap.project F bx by' (Sum.map _root_.id (fun i => (j, i))) + rintro x (a | b) <;> rfl + +/-- Gather a bounded number of neighbors from arbitrary address vectors. -/ +theorem Cheap.neighbors (F : Type) [Field F] (A : Format) (h k t : ℕ) + (hh : h ≤ k) (ha : A.width ≤ k) (ht : 2 ^ t ≤ k) : + Cheap F h k (.pair (.vec h A) (.vec t (Perm h))) (.vec h (.vec t A)) + (fun x i j => x.1 (x.2 j i)) 12 := by + let X := Format.pair (.vec h A) (.vec t (Perm h)) + have each (j : B t) : Cheap F h k X (.vec h A) (fun x i => x.1 (x.2 j i)) 9 := + (pick F A h k t hh ha ht j).comp (Cheap.lookup F h k A hh ha) + have all := Cheap.share _ each ht + let Z := Format.vec t (.vec h A) + let W := Format.vec h (.vec t A) + have bw : W.width ≤ 2 ^ h * (100 + k) ^ 2 := by + simp only [W, Format.width_vec] + exact Nat.mul_le_mul_left _ (by nlinarith only [Nat.mul_le_mul ht ha]) + have bz : Z.width ≤ 2 ^ h * (100 + k) ^ 2 := by + simpa only [Z, W, Format.width_vec, mul_left_comm] using bw + have flip : Cheap F h k Z W (fun x i j => x j i) 3 := + Cheap.project F bz bw (fun p => (p.2.1, p.1, p.2.2)) fun _ _ => rfl + have ans := all.comp flip + simp only [Function.comp_def] at ans + exact ans + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- +# Evaluating address coincidences + +Transpose the address lists and compare every pair at the same center. +Only the fixed-size matrix of equality bits enters the arbitrary table. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +theorem numeric_eq (F : Type) [Field F] (h : ℕ) : + Circuit F (.pair (.addr h) (.addr h)) .bit (fun x => decide (x.1 = x.2)) (2 * h + 1) := by + apply Circuit.of_dnet (.refl _) (.refl _) (Lookup.eq_net F h) + intro x + simp only [Equiv.coe_refl, Function.comp_id] + change bits .bit (decide (x.1 = x.2)) = + bits .bit (decide (((Format.pair (.addr h) (.addr h)).code.symm (bits (twoWords h) x)).1 = + ((Format.pair (.addr h) (.addr h)).code.symm (bits (twoWords h) x)).2)) + rw [decode_pair h x] + simp only [(Control.index h).injective.eq_iff] + +private abbrev row (t h : ℕ) := Format.vec t (.addr h) +private abbrev pattern (t : ℕ) := Format.vec t (.vec t .bit) + +private theorem row_pattern (F : Type) [Field F] (t h k : ℕ) (hh : h ≤ k) (ht : 2 ^ t ≤ k) : + Cheap F 0 k (row t h) (pattern t) (fun x j l => decide (x j = x l)) 8 := by + let A := Format.pair (.addr h) (.addr h) + have bx : (row t h).width ≤ 2 ^ 0 * (100 + k) ^ 2 := by + simp only [Format.width_vec, Format.width_addr, pow_zero, one_mul] + nlinarith only [Nat.mul_le_mul ht hh] + have ba : A.width ≤ 2 ^ 0 * (100 + k) ^ 2 := by + simp only [A, Format.width_pair, Format.width_addr, pow_zero, one_mul] + nlinarith only [hh] + have pick (j l : B t) : Cheap F 0 k (row t h) A (fun x => (x j, x l)) 3 := by + apply Cheap.project F bx ba (Sum.elim (fun i => (j, i)) (fun i => (l, i))) + rintro x (i | i) <;> rfl + have cmp : Cheap F 0 k A .bit (fun x => decide (x.1 = x.2)) 2 := by + refine ⟨_, numeric_eq F h, ?_⟩ + simp only [A, Format.width_pair, Format.width_addr, pow_zero, one_mul] + change h + h + 1 + (2 * h + 1) ≤ (100 + k) ^ 2 + nlinarith only [hh] + have each (j l : B t) : Cheap F 0 k (row t h) .bit (fun x => decide (x j = x l)) 4 := + (pick j l).comp cmp + exact Cheap.share _ (fun j => Cheap.share _ (each j) ht) ht + +theorem Cheap.equalityTable (F : Type) [Field F] (t q : ℕ) : + ∃ k₀, ∀ h k : ℕ, h ≤ k → k₀ ≤ k → ∀ f : (B t → B t → Bool) → B q, + Cheap F h k (.vec t (Perm h)) (.vec h (.addr q)) + (fun w i => f (fun j l => decide (w j i = w l i))) 30 := by + let P := pattern t + let D := Format.addr q + let c := 2 * P.width + D.width + Install.localCost P.width * D.width + refine ⟨max c (2 ^ t), fun h k hh hk f => ?_⟩ + obtain ⟨hc, ht⟩ := max_le_iff.mp hk + let X := Format.vec t (Perm h) + let Y := Format.vec h (row t h) + have hy : Y.width ≤ 2 ^ h * (100 + k) ^ 2 := by + simp only [Y, Format.width_vec, Format.width_addr] + exact Nat.mul_le_mul_left _ (by nlinarith only [Nat.mul_le_mul ht hh]) + have hx : X.width ≤ 2 ^ h * (100 + k) ^ 2 := by + simpa only [X, Y, Format.width_vec, mul_left_comm] using hy + have tr : Cheap F h k X Y (fun w i j => w j i) 3 := + Cheap.project F hx hy (fun p => (p.2.1, p.1, p.2.2)) fun _ _ => rfl + have table : Cheap F 0 k P D f 1 := Cheap.fixed F _ hc + have one := (row_pattern F t h k hh ht).comp table + have net := tr.comp (Cheap.map _ (fun _ => one)) + exact net.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/CompareExchange.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/CompareExchange.lean new file mode 100644 index 0000000000..cc054aa06d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/CompareExchange.lean @@ -0,0 +1,128 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FunctionNetwork +public import Mathlib.Order.Prod.Lex.Basic + +/-! +# A linear-size compare-and-exchange network on words + +Comparison folds a single bit of state up the word. Selection copies that bit +to all positions, then multiplexes them in parallel. This avoids paying for +identity on a shrinking word at each step of a sequential selection. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +@[simp] theorem wd_word (n : ℕ) : wd (word n) = n := by + induction n with + | zero => rfl + | succ n ih => simp [wd, ih, Nat.add_comm] + +/-- Lexicographic order with the first bit most significant. -/ +instance wordOrder : (n : ℕ) → LinearOrder (Val (word n)) + | 0 => inferInstanceAs (LinearOrder Unit) + | n + 1 => @Prod.Lex.instLinearOrder Bool (Val (word n)) _ (wordOrder n) + +private theorem word_lt_succ (n : ℕ) (x y : Val (word (n + 1))) : + @LT.lt _ (wordOrder (n + 1)).toLT x y ↔ x.1 < y.1 ∨ x.1 = y.1 ∧ x.2 < y.2 := by + exact Prod.Lex.toLex_lt_toLex (x := x) (y := y) + +variable (F : Type) [Field F] + +private abbrev two := Wire.pair .bit .bit + +private theorem selectBit : + DNet F (.pair two .bit) .bit (fun x => if x.2 then x.1.1 else x.1.2) 6 := by + have dup := ((DNet.id F two).par (DNet.dup F .bit)).post (.middle .bit .bit .bit .bit) + have yes := DNet.table F two .bit (fun x => x.1 && x.2) (by decide) + have no := DNet.table F two .bit (fun x => x.1 && !x.2) (by decide) + have join := DNet.table F two .bit (fun x => x.1 || x.2) (by decide) + convert (dup.comp (yes.par no)).comp join using 1 <;> try rfl + funext ⟨⟨p, q⟩, b⟩ + cases b <;> simp + +/-- Evaluate both two-input branches and select with the third bit. -/ +private theorem ternary (f : Val (.pair two .bit) → Bool) : + DNet F (.pair two .bit) .bit f 11 := by + have branch (b : Bool) := DNet.table F two .bit (fun x => f (x, b)) (by decide) + convert (((branch true).pair (branch false)).par (DNet.id F .bit)).comp (selectBit F) using 1 + <;> try rfl + funext ⟨x, b⟩ + cases b <;> rfl + +/-- A strict comparator using a linear number of trivalent vertices. -/ +theorem compare_lt (n : ℕ) : + DNet F (.pair (word n) (word n)) .bit (fun x => decide (x.1 < x.2)) (100 * (n + 1)) := by + induction n with + | zero => exact (DNet.table F _ _ _ (by decide)).mono (by decide) + | succ n ih => + have step := ternary F (fun x => decide (x.1.1 < x.1.2 ∨ x.1.1 = x.1.2 ∧ x.2 = true)) + have h := (((DNet.id F two).par ih).pre (.middle .bit (word n) .bit (word n))).comp step + convert h.mono (n := 100 * (n + 1 + 1)) (by simp only [wd]; omega) using 1 + funext ⟨x, y⟩ + simp only [decide_eq_true_eq, decide_eq_decide] + exact word_lt_succ n x y + +private def repeatBit : (n : ℕ) → Bool → Val (word n) + | 0, _ => () + | n + 1, b => (b, repeatBit n b) + +private theorem broadcast (n : ℕ) : DNet F .bit (word n) (repeatBit n) (2 * n + 1) := by + induction n with + | zero => exact DNet.discard F .bit + | succ n ih => exact ((DNet.id F .bit).pair ih).mono (by simp only [wd]; omega) + +private def selectBits : (n : ℕ) → Val (word n) → Val (word n) → Val (word n) → Val (word n) + | 0, _, _, _ => () + | n + 1, x, y, mask => + (if mask.1 then x.1 else y.1, selectBits n x.2 y.2 mask.2) + +private theorem selectBits_repeat (n : ℕ) (x y : Val (word n)) (b : Bool) : + selectBits n x y (repeatBit n b) = if b then x else y := by + induction n with + | zero => rfl + | succ n ih => simp only [selectBits, repeatBit, ih]; cases b <;> rfl + +/-- Computes the inputs by the application `Wire.pair (word n) (word n)`. -/ +abbrev inputs (n : ℕ) := Wire.pair (word n) (word n) + +private theorem selectParallel (n : ℕ) : + DNet F (.pair (inputs n) (word n)) (word n) + (fun x => selectBits n x.1.1 x.1.2 x.2) (6 * n + 1) := by + induction n with + | zero => exact DNet.table F _ _ _ (by decide) + | succ n ih => + have r := ((Rewire.middle .bit (word n) .bit (word n)).par (Rewire.id (word (n + 1)))).comp + (Rewire.middle two (inputs n) .bit (word n)) + exact (((selectBit F).par ih).pre r).mono (by omega) + +theorem selectWord (n : ℕ) : + DNet F (.pair (inputs n) .bit) (word n) + (fun x => if x.2 then x.1.1 else x.1.2) (10 * n + 2) := by + have h := ((DNet.id F (inputs n)).par (broadcast F n)).comp (selectParallel F n) + simpa only [selectBits_repeat] using + h.mono (n := 10 * n + 2) (by simp only [wd, wd_word]; omega) + +/-- Order the two words while retaining both of them. -/ +theorem compare_exchange (n : ℕ) : + DNet F (.pair (word n) (word n)) (.pair (word n) (word n)) + (fun x => (min x.1 x.2, max x.1 x.2)) (200 * (n + 1)) := by + have compare := (DNet.id F (inputs n)).pair (compare_lt F n) + have lower := selectWord F n + have upper := lower.pre ((Rewire.swap (word n) (word n)).par (.id .bit)) + have h := compare.comp (lower.pair upper) + convert h.mono (n := 200 * (n + 1)) (by simp only [wd, wd_word]; omega) using 1 + funext ⟨x, y⟩ + by_cases hxy : x < y + · simp [hxy, min_eq_left hxy.le, max_eq_right hxy.le] + · simp [hxy, min_eq_right (le_of_not_gt hxy), max_eq_left (le_of_not_gt hxy)] + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/Address.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/Address.lean new file mode 100644 index 0000000000..a2fcc2ce77 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/Address.lean @@ -0,0 +1,56 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Counter +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute + +/-! # Little-endian binary addresses -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Control + +theorem value_lt (h : ℕ) (x : Val (word h)) : Lookup.value h x < 2 ^ h := by + induction h with + | zero => simp [Lookup.value] + | succ h ih => + obtain ⟨b, y⟩ := x + have := ih y + cases b <;> simp [Lookup.value, pow_succ] <;> omega + +theorem value_injective (h : ℕ) : Function.Injective (Lookup.value h) := by + induction h with + | zero => exact fun _ _ _ => rfl + | succ h ih => + rintro ⟨i, x⟩ ⟨j, y⟩ he + change i.toNat + 2 * Lookup.value h x = j.toNat + 2 * Lookup.value h y at he + cases i <;> cases j <;> simp only [Bool.toNat_false, Bool.toNat_true, zero_add] at he + · have hxy : Lookup.value h x = Lookup.value h y := by omega + exact Prod.ext rfl (ih hxy) + · omega + · omega + · have hxy : Lookup.value h x = Lookup.value h y := by omega + exact Prod.ext rfl (ih hxy) + +/-- Reindexes `Val (word w)` and `Fin (2 ^ w) where toFun k` by an equivalence. -/ +def index (w : ℕ) : Val (word w) ≃ Fin (2 ^ w) where + toFun k := ⟨Lookup.value w k, value_lt w k⟩ + invFun k := Lookup.bits w k + left_inv k := value_injective w (Lookup.value_bits (value_lt w k)) + right_inv k := Fin.ext (Lookup.value_bits k.isLt) + +/-- Reindexes `(slots (word w) → Bool)` and `Fin (2 ^ w)` by an equivalence. -/ +def decode (w : ℕ) : (slots (word w) → Bool) ≃ Fin (2 ^ w) := + (bits (word w)).symm.trans (index w) + +/-- The indexed operation `x (.inl (decode w (fun j => x (.inr (i, j)))))`. -/ +def read (w : ℕ) (x : Fin (2 ^ w) ⊕ (Fin (2 ^ w) × slots (word w)) → Bool) (i : Fin (2 ^ w)) : Bool + := + x (.inl (decode w (fun j => x (.inr (i, j))))) + +end MatrixMultiplicationAllFields.MatrixExponent.Control diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/BucketNet.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/BucketNet.lean new file mode 100644 index 0000000000..fce7e53d1c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/BucketNet.lean @@ -0,0 +1,336 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Finset.Card +public import Mathlib.Data.Fintype.Card +public import Mathlib.Data.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Scan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Address + +/-! # Occurrence ranks in a finite sequence -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Control +open Finset + +variable {n : ℕ} {A : Type} [DecidableEq A] + +/-- Count occurrences at earlier positions, or in the whole sequence for `none`. -/ +def histogram (x : Fin n → A) (z : A) (j : Option (Fin n)) : ℕ := + (univ.filter fun i => x i = z ∧ ∀ k, j = some k → i < k).card + +/-- Computes the rank by the application `histogram x (x i) (some i)`. -/ +def rank (x : Fin n → A) (i : Fin n) : ℕ := histogram x (x i) (some i) + +variable (x : Fin n → A) + +theorem histogram_some (z : A) (j : Fin n) : + histogram x z (some j) = (univ.filter fun i => x i = z ∧ i < j).card := by + simp [histogram] + +theorem histogram_none (z : A) : + histogram x z none = (univ.filter fun i => x i = z).card := by + simp [histogram] + +theorem histogram_le (z : A) (j : Option (Fin n)) : histogram x z j ≤ n := by + unfold histogram + exact (card_filter_le ..).trans_eq (card_fin n) + +theorem rank_lt (i : Fin n) : rank x i < histogram x (x i) none := by + rw [rank, histogram_some, histogram_none] + apply card_lt_card + apply ssubset_iff_subset_ne.mpr + refine ⟨?_, ?_⟩ + · intro j hj + exact mem_filter.mpr ⟨mem_univ _, (mem_filter.mp hj).2.1⟩ + · intro he + have := congrArg (i ∈ ·) he + simp at this + +theorem rank_mono {i j : Fin n} (he : x i = x j) (h : i < j) : rank x i < rank x j := by + rw [rank, rank, histogram_some, histogram_some, he] + apply card_lt_card + apply ssubset_iff_subset_ne.mpr + refine ⟨?_, ?_⟩ + · intro l hl + obtain ⟨_, hz, hi⟩ := mem_filter.mp hl + exact mem_filter.mpr ⟨mem_univ _, hz, hi.trans h⟩ + · intro hh + have := congrArg (i ∈ ·) hh + simp [h, he] at this + +theorem rank_injective : Function.Injective (fun i => (x i, rank x i)) := by + intro i j he + obtain ⟨hz, hr⟩ := Prod.mk.inj he + rcases lt_trichotomy i j with hij | hij | hij + · exact ((rank_mono x hz hij).ne hr).elim + · exact hij + · exact ((rank_mono x hz.symm hij).ne hr.symm).elim + +theorem rank_range (z : A) (r : ℕ) : + (∃ i, x i = z ∧ rank x i = r) ↔ r < histogram x z none := by + let S := univ.filter (fun i => x i = z) + have hi : Set.InjOn (rank x) ↑S := by + intro i h₁ j h₂ h + exact rank_injective x (Prod.ext ((mem_filter.mp h₁).2.trans (mem_filter.mp h₂).2.symm) h) + have he : S.image (rank x) = range (histogram x z none) := by + apply eq_of_subset_of_card_le + · rintro k hk + obtain ⟨i, hz, rfl⟩ := mem_image.mp hk + exact mem_range.mpr ((mem_filter.mp hz).2 ▸ rank_lt x i) + · rw [card_range, card_image_of_injOn hi, histogram_none] + simpa [S] using congrArg (r ∈ ·) he + +end MatrixMultiplicationAllFields.MatrixExponent.Control +end + +section +/- +# Binary prefix counts + +At each bit, keep the old count and send the updated one to the next +position. Only that counter is connected between two blocks. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Control + +/-- In the case `0, x`, this construction gives `(x.1, if x.2 then Lookup.inc t x.1 else x.1)`. -/ +def run (t : ℕ) : + (h : ℕ) → Val (.pair (word t) (tree h .bit)) → Val (.pair (tree h (word t)) (word t)) + | 0, x => (x.1, if x.2 then Lookup.inc t x.1 else x.1) + | h + 1, x => + let l := run t h (x.1, x.2.1) + let r := run t h (l.2, x.2.2) + ((l.1, r.1), r.2) + +private theorem run_net (F : Type) [Field F] (t h : ℕ) : + DNet F (.pair (word t) (tree h .bit)) (.pair (tree h (word t)) (word t)) + (run t h) (2 ^ h * (200 * (1 + t))) := by + induction h with + | zero => + have a := DNet.fst F (word t) .bit + have b := DNet.snd F (word t) .bit + have next := (((a.comp (Lookup.inc_net F t)).pair a).pair b).comp (selectWord F t) + exact (a.pair next).mono (by simp only [pow_zero, one_mul, wd_word, wd]; omega) + | succ h ih => + rw [pow_succ, mul_two, add_mul] + exact ((ih.plug ih).pre (.assoc' _ _ _)).post (.assoc' _ _ _) + +private def counts (t k : ℕ) : List Bool → List (Val (word t)) + | [] => [] + | b::bs => Lookup.bits t k :: counts t (k + b.toNat) bs + +private theorem counts_append (t k : ℕ) (xs ys : List Bool) : + counts t k (xs ++ ys) = counts t k xs ++ counts t (k + xs.count true) ys := by + induction xs generalizing k with + | nil => simp [counts] + | cons b xs ih => cases b <;> simp [counts, ih, Nat.add_left_comm, Nat.add_comm] + +private theorem run_eq (t h k : ℕ) (x : Val (tree h .bit)) : + flatten h (run t h (Lookup.bits t k, x)).1 = counts t k (flatten h x) ∧ + (run t h (Lookup.bits t k, x)).2 = Lookup.bits t (k + (flatten h x).count true) := by + induction h generalizing k with + | zero => + cases x <;> simp [flatten, counts, run, Lookup.bits, Function.iterate_succ_apply'] + | succ h ih => + simp only [run, flatten, counts_append, List.count_append, (ih _ x.1).1, (ih _ x.1).2, + (ih _ x.2).1, (ih _ x.2).2, Nat.add_assoc, and_self] + +private theorem histogram_succ {n : ℕ} (x : Fin (n + 1) → Bool) (i : Fin n) : + histogram x true (some i.succ) = (x 0).toNat + histogram (fun j => x j.succ) true (some i) := by + rw [histogram_some, histogram_some, Finset.card_filter, Finset.card_filter, Fin.sum_univ_succ] + cases x 0 <;> simp + +private theorem counts_ofFn {n : ℕ} (x : Fin n → Bool) (t k : ℕ) : + counts t k (List.ofFn x) = + List.ofFn (fun i => Lookup.bits t (k + histogram x true (some i))) ∧ + (List.ofFn x).count true = histogram x true none := by + induction n generalizing k with + | zero => simp [counts, histogram_none] + | succ n ih => + obtain ⟨h, he⟩ := ih (fun i => x i.succ) (k + (x 0).toNat) + have hz : histogram x true (some 0) = 0 := by simp [histogram_some] + constructor + · rw [List.ofFn_succ, List.ofFn_succ, counts, h] + simp only [hz, Nat.add_zero, histogram_succ, Nat.add_assoc] + · rw [List.ofFn_succ, List.count_cons, he, histogram_none, histogram_none, + Finset.card_filter, Finset.card_filter, Fin.sum_univ_succ] + cases x 0 <;> simp [add_comm] + +/-- The quantity computed by `run (h + 1) h (Lookup.zero _, x)`. -/ +def bitPrefix (h : ℕ) (x : Val (tree h .bit)) : + Val (.pair (tree h (word (h + 1))) (word (h + 1))) := + run (h + 1) h (Lookup.zero _, x) + +theorem prefix_net (F : Type) [Field F] (h : ℕ) : + DNet F (tree h .bit) (.pair (tree h (word (h + 1))) (word (h + 1))) + (bitPrefix h) (500 * 2 ^ h * (h + 1)) := by + have init := ((Lookup.const_net F (word (h + 1)) (Lookup.zero _)).par (DNet.id F (tree h + .bit))).pre + ((Rewire.unit' _).comp (.swap _ _)) + apply (init.comp (run_net F (h + 1) h)).mono + simp only [wd_tree, wd, wd_word] + have hh := Nat.one_le_pow h 2 (by decide) + nlinarith [Nat.mul_le_mul_right h hh] + +theorem prefix_eq (h : ℕ) (x : Val (tree h .bit)) (r : Fin (2 ^ h) → Bool) + (he : List.ofFn r = flatten h x) : + flatten h (bitPrefix h x).1 = List.ofFn (fun i => Lookup.bits (h + + 1) (histogram r true (some i))) ∧ + (bitPrefix h x).2 = Lookup.bits (h + 1) (histogram r true none) := by + have hh := run_eq (h + 1) h 0 x + obtain ⟨ha, hb⟩ := counts_ofFn r (h + 1) 0 + rw [← he, ha, hb] at hh + simpa only [Nat.zero_add, bitPrefix, Lookup.bits, Function.iterate_zero_apply] using hh + +theorem equal_net (F : Type) [Field F] (a : Wire) (z : Val a) : + DNet F a .bit (fun y => decide (y = z)) (10 * wd a + 1) := by + obtain ⟨e, he, hi⟩ := Rewire.exists_of_width (wd_word (wd a)).symm + have h := ((DNet.id F a).par (Lookup.const_net F a z)).pre (.unit' _) + have cmp := h.comp ((Lookup.eq_net F (wd a)).pre (he.par he)) + simpa only [hi.eq_iff] using cmp.mono (n := 10 * wd a + 1) (by omega) + +theorem histogram_net (F : Type) [Field F] (a : Wire) (h : ℕ) (z : Val a) : + ∃ f, DNet F (tree h a) (.pair (tree h (word (h + 1))) (word (h + 1))) + f (2 ^ h * (wd a * 20 + 1000 * (h + 1))) ∧ + ∀ (x : Val (tree h a)) (r : Fin (2 ^ h) → Val a), List.ofFn r = flatten h x → + flatten h (f x).1 = List.ofFn (fun i => Lookup.bits (h + 1) (histogram r z (some i))) ∧ + (f x).2 = Lookup.bits (h + 1) (histogram r z none) := by + have hn := (Tagged.mapRows_net (equal_net F a z) h).comp (prefix_net F h) + refine ⟨_, hn.mono (by ring_nf; omega), fun x r he => ?_⟩ + have hh := prefix_eq h (Tagged.mapRows (b := .bit) (fun y => decide (y = z)) h x) + (fun i => decide (r i = z)) (by rw [Tagged.flatten_mapRows, ← he, List.map_ofFn]; rfl) + simpa only [histogram, decide_eq_true_eq] using hh + +/-- Reindexes `Fin (2 ^ h)` and `slots (tree h .bit)` by an equivalence. -/ +def bitLayout {h : ℕ} (L : Layout .bit (tree h .bit) (Fin (2 ^ h))) : + Fin (2 ^ h) ≃ slots (tree h .bit) := + (Equiv.prodUnique _ Unit).symm.trans L.positions + +private def outputs {a : Wire} {h : ℕ} (L : Layout a (tree h a) (Fin (2 ^ h))) : + Option (Fin (2 ^ h)) × slots a ≃ slots (.pair (tree h a) a) := + ((Equiv.optionEquivSumPUnit _).prodCongr (.refl _)).trans + ((Equiv.sumProdDistrib _ Unit _).trans (L.positions.sumCongr (Equiv.uniqueProd _ Unit))) + +theorem prefix_bnet (F : Type) [Field F] (h : ℕ) : + Install.BNet F (fun (x : Fin (2 ^ h) → Bool) (p : Option (Fin (2 ^ h)) × slots (word (h + 1))) + => + bits (word (h + 1)) (Lookup.bits (h + 1) (histogram x true p.1)) p.2) + (1000 * 2 ^ h * (h + 1)) := by + obtain ⟨L, hL⟩ := Layout.exists_tree .bit h + obtain ⟨P, hP⟩ := Layout.exists_tree (word (h + 1)) h + apply Install.BNet.of_layout (bitLayout L) (outputs P) + convert (prefix_net F h).mono (n := 1000 * 2 ^ h * (h + 1)) (by gcongr; decide) using 1 + funext x + apply (bits _).injective + rw [Equiv.apply_symm_apply] + obtain ⟨hs, hn⟩ := prefix_eq h x (L.read x) (hL _) + have hs' := List.ofFn_injective ((hP _).trans hs) + funext z + obtain ⟨⟨i, k⟩, rfl⟩ := (outputs P).surjective z + simp only [Function.comp_apply, Equiv.symm_apply_apply] + change bits (word (h + 1)) (Lookup.bits (h + 1) (histogram (L.read x) true i)) k = _ + cases i with + | none => rw [← hn]; rfl + | some i => + have hp := congrFun hs' i + rw [← hp, Layout.read, Equiv.apply_symm_apply] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Control +end + +section +/- +# Selecting positions by occurrence rank + +Dividing a little-endian count by a power of two discards leading wires. +A comparison with a constant selects the required bucket. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Control + +private theorem value_test (F : Type) [Field F] (t j : ℕ) : + DNet F (word t) .bit (fun x => decide (Lookup.value t x = j)) (10 * t + 1) := by + by_cases h : j < 2 ^ t + · have e (x) : Lookup.value t x = j ↔ x = Lookup.bits t j := by + rw [← (value_injective t).eq_iff, Lookup.value_bits h] + simpa only [e, wd_word] using equal_net F (word t) (Lookup.bits t j) + · have e (x) : Lookup.value t x ≠ j := (value_lt t x).trans_le (le_of_not_gt h) |>.ne + have hs := (DNet.discard F (word t)).comp (Lookup.const_net F .bit false) + simpa only [e, decide_false] using hs.mono (n := 10 * t + 1) (by simp [wd]; omega) + +theorem quotient_test (F : Type) [Field F] (t q j : ℕ) : + DNet F (word t) .bit (fun x => decide (Lookup.value t x / 2 ^ q = j)) (10 * t + 1) := by + induction t generalizing q with + | zero => exact DNet.table F _ _ _ (by decide) + | succ t ih => + cases q with + | zero => simpa only [pow_zero, Nat.div_one] using value_test F (t + 1) j + | succ q => + have hs := ((DNet.discard F .bit).par (ih q)).post ((Rewire.swap _ _).comp (.unit _)) + convert hs.mono (n := 10 * (t + 1) + 1) (by simp only [wd]; omega) using 1 + funext x + have he : Lookup.value (t + 1) x / 2 = Lookup.value t x.2 := by + obtain ⟨b, x⟩ := x + cases b <;> simp [Lookup.value] + omega + rw [pow_succ', ← Nat.div_div_eq_div_mul, he] + +theorem flatten_zip {a b c : Wire} (f : Val a → Val b → Val c) + (h : ℕ) (x : Val (tree h a)) (y : Val (tree h b)) : + flatten h (Tagged.zipRows f h x y) = List.zipWith f (flatten h x) (flatten h y) := by + induction h with + | zero => rfl + | succ h ih => + simp only [flatten, Tagged.zipRows, ih] + rw [List.zipWith_append (by simp [Tagged.length_flatten])] + +theorem zip_ofFn {A B C : Type} {n : ℕ} (f : A → B → C) (x : Fin n → A) (y : Fin n → B) : + List.zipWith f (List.ofFn x) (List.ofFn y) = List.ofFn (fun i => f (x i) (y i)) := by + induction n with + | zero => simp + | succ n ih => simp [List.ofFn_succ, ih] + +theorem bucket_bnet (F : Type) [Field F] (h q j : ℕ) : + Install.BNet F (fun (x : Fin (2 ^ h) → Bool) (i : Fin (2 ^ h)) => + x i && decide (histogram x true (some i) / 2 ^ q = j)) (1000 * 2 ^ h * (h + 1)) := by + let test (b : Bool) (v : Val (word (h + 1))) := b && decide (Lookup.value _ v / 2 ^ q = j) + have ht := ((DNet.id F .bit).par (quotient_test F (h + 1) q j)).comp + (DNet.table F (.pair .bit .bit) .bit (fun x => x.1 && x.2) (by decide)) + have hp := (prefix_net F h).comp (DNet.fst F _ _) + have hs := ((DNet.id F (tree h .bit)).pair hp).comp + (Tagged.zipRows_net (a := .bit) (b := word (h + 1)) (c := .bit) (f := test) ht h) + have hc := hs.mono (n := 1000 * 2 ^ h * (h + 1)) (by + simp only [wd, wd_tree, wd_word] + have := Nat.one_le_pow h 2 (by decide) + nlinarith [Nat.mul_le_mul_right h this]) + obtain ⟨L, hL⟩ := Layout.exists_tree .bit h + apply Install.BNet.of_layout (bitLayout L) (bitLayout L) + convert hc using 1 + funext x + have hx := (prefix_eq h x (L.read x) (hL _)).1 + apply L.injective + apply List.ofFn_injective + rw [hL (Tagged.zipRows ..), flatten_zip, hx, ← hL x, zip_ofFn] + congr 1 + funext i + have hv : histogram (L.read x) true (some i) < 2 ^ (h + 1) := + (histogram_le ..).trans_lt (Nat.pow_lt_pow_right (by decide) (by omega)) + simp only [test, Lookup.value_bits hv] + change bits (tree h .bit) ((bits (tree h .bit)).symm _) (bitLayout L i) = _ + rw [Equiv.apply_symm_apply, Function.comp_apply, Equiv.symm_apply_apply] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Control +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/Named.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/Named.lean new file mode 100644 index 0000000000..ba4be849e0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/Named.lean @@ -0,0 +1,254 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Batcher +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BitonicMerge +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Address +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Scan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight + +/-! +# Checking agreement on repeated addresses + +Sort by address and then by bit. Complement the bit on every row and +test whether the list is still sorted. This holds exactly when all +rows with the same address agree. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Control + +/-- Computes the entry by the application `Wire.pair (word h) .bit`. -/ +abbrev entry (h : ℕ) := Wire.pair (word h) .bit + +/-- The condition `∀ i ∈ xs, ∀ j ∈ xs, i.1 = j.1 → i.2 = j.2` on the specified data. -/ +def Agree {h : ℕ} (xs : List (Val (entry h))) : Prop := + ∀ i ∈ xs, ∀ j ∈ xs, i.1 = j.1 → i.2 = j.2 + +private local instance order (h : ℕ) : LinearOrder (Val (entry h)) := + @Prod.Lex.instLinearOrder _ _ (wordOrder h) inferInstance + +private local instance (h : ℕ) : LT (Val (entry h)) := (order h).toLT +private local instance (h : ℕ) : LE (Val (entry h)) := (order h).toLE +private local instance (h : ℕ) : Min (Val (entry h)) := (order h).toMin +private local instance (h : ℕ) : Max (Val (entry h)) := (order h).toMax +private local instance (h : ℕ) : Preorder (Val (entry h)) := (order h).toPreorder + +private def flip (h : ℕ) (i : Val (entry h)) : Val (entry h) := (i.1, !i.2) + +private theorem le_iff {h : ℕ} (i j : Val (entry h)) : + i ≤ j ↔ i.1 < j.1 ∨ i.1 = j.1 ∧ i.2 ≤ j.2 := + Prod.Lex.toLex_le_toLex + +private theorem both {h : ℕ} (i j : Val (entry h)) (ho : i ≤ j) : + flip h i ≤ flip h j ↔ (i.1 = j.1 → i.2 = j.2) := by + rw [le_iff] at ho ⊢ + rcases ho with ho | ⟨he, hb⟩ + · simp [flip, ho, ho.ne] + · simp only [flip, he, lt_self_iff_false, true_and, false_or, true_implies] + exact (show ∀ x y : Bool, x ≤ y → ((!x) ≤ (!y) ↔ x = y) by decide) i.2 j.2 hb + +private theorem agree_iff {h : ℕ} (xs : List (Val (entry h))) (hs : xs.Pairwise (· ≤ ·)) : + (xs.map (flip h)).Pairwise (· ≤ ·) ↔ Agree xs := by + rw [List.pairwise_map] + constructor + · intro ht + have hp := (hs.and ht).imp (fun e => (both _ _ e.1).mp e.2) + intro i hi j hj he + obtain ⟨a, ha, rfl⟩ := List.getElem_of_mem hi + obtain ⟨b, hb, rfl⟩ := List.getElem_of_mem hj + rcases lt_trichotomy a b with h | rfl | h + · exact List.pairwise_iff_getElem.mp hp a b ha hb h he + · rfl + · exact (List.pairwise_iff_getElem.mp hp b a hb ha h he.symm).symm + · intro ht + exact hs.imp_of_mem fun hi hj h => (both _ _ h).mpr (ht _ hi _ hj) + +variable (F : Type) [Field F] (h : ℕ) + +private theorem compare_net : DNet F (.pair (entry h) (entry h)) .bit + (fun x => decide (x.1 < x.2)) (250 * (h + 1)) := by + have bit := DNet.table F (.pair .bit .bit) .bit (fun x => decide (x.1 < x.2)) (by decide) + exact (Tagged.lex_compare (compare_lt F h) bit).mono (by simp only [wd_word]; omega) + +private theorem exchange : DNet F (.pair (entry h) (entry h)) (.pair (entry h) (entry h)) + (fun x => (min x.1 x.2, max x.1 x.2)) (500 * (h + 1)) := by + let a := entry h + have rev := Rewire.swap (word h) .bit + have sel := ((selectWord F (h + 1)).pre ((rev.par rev).par (.id .bit))).post (.swap _ _) + have cmp := (DNet.id F (.pair a a)).pair (compare_net F h) + have net := cmp.comp (sel.pair (sel.pre ((Rewire.swap a a).par (.id .bit)))) + convert net.mono (n := 500 * (h + 1)) (by simp only [a, wd, wd_word]; omega) using 1 + funext ⟨x, y⟩ + by_cases ho : x < y + · simp [ho, min_eq_left ho.le, max_eq_right ho.le] + · simp [ho, min_eq_right (le_of_not_gt ho), max_eq_left (le_of_not_gt ho)] + +theorem agree_net (w : ℕ) : + ∃ f, DNet F (tree w (entry h)) .bit f (800 * 2 ^ w * (w + 1) ^ 2 * (h + 1)) ∧ + ∀ x, f x = true ↔ Agree (flatten w x) := by + have flip_net : DNet F (entry h) (entry h) (flip h) (wd (word h) + 1) := + (DNet.id F (word h)).par (DNet.table F .bit .bit Bool.not (by decide)) + have sort := sortTree_net (exchange F h) w + have net := (sort.comp (Tagged.mapRows_net flip_net w)).comp (Tagged.check_order (compare_net F + h) w) + refine ⟨_, net.mono ?_, fun x => ?_⟩ + · simp only [wd, wd_word] + ring_nf + omega + · simp only [decide_eq_true_eq, Tagged.flatten_mapRows, agree_iff _ (sortTree_sorted w x)] + simp only [Agree, (sortTree_perm w x).mem_iff] + +end MatrixMultiplicationAllFields.MatrixExponent.Control +end + +section +/- +# Simultaneous reads from an array of bits + +Pair each data bit with its fixed address and each proposed output bit +with its requested address. Consistency on the combined list uniquely +determines every output, even when the same address is requested often. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Control +open Tagged + +/-- The value specified by `(flatten h data)[Lookup.value h addr]'(by rw [length_flatten]; exact +value_lt h addr)`. -/ +def fetch (h : ℕ) (data : Val (tree h .bit)) (addr : Val (word h)) : Bool := + (flatten h data)[Lookup.value h addr]'(by rw [length_flatten]; exact value_lt h addr) + +/-- The value specified by `mapRows (a := word h) (b := .bit) (fetch h x.1) h x.2`. -/ +def batchRead (h : ℕ) (x : Val (.pair (tree h .bit) (tree h (word h)))) : Val (tree h .bit) := + mapRows (a := word h) (b := .bit) (fetch h x.1) h x.2 + +private def pairs (h w : ℕ) := + zipRows (a := word h) (b := .bit) (c := entry h) Prod.mk w + +private theorem entries (h w : ℕ) (f : Val (word h) → Bool) + (a : Val (tree w (word h))) (b : Val (tree w .bit)) : + (∀ p ∈ flatten w (pairs h w a b), f p.1 = p.2) ↔ + mapRows (b := .bit) f w a = b := by + induction w with + | zero => simp [flatten, pairs, mapRows, zipRows] + | succ w ih => + change (∀ p ∈ flatten w (pairs h w a.1 b.1) ++ flatten w (pairs h w a.2 b.2), + f p.1 = p.2) ↔ _ + rw [List.forall_mem_append, ih, ih] + simp only [mapRows, Prod.ext_iff] + +private theorem entry_mem (h w : ℕ) (a : Val (tree w (word h))) (b : Val (tree w .bit)) + (i : Val (word h)) (hi : i ∈ flatten w a) : + ∃ y, (i, y) ∈ flatten w (pairs h w a b) := by + induction w with + | zero => + rw [List.mem_singleton.mp hi] + exact ⟨b, List.mem_singleton_self _⟩ + | succ w ih => + rcases List.mem_append.mp hi with hl | hr + · obtain ⟨y, hy⟩ := ih a.1 b.1 hl + exact ⟨y, List.mem_append_left _ hy⟩ + · obtain ⟨y, hy⟩ := ih a.2 b.2 hr + exact ⟨y, List.mem_append_right _ hy⟩ + +private theorem dictionary (h : ℕ) : + ∃ keys : Val (tree h (word h)), (∀ i, i ∈ flatten h keys) ∧ + ∀ b : Val (tree h .bit), mapRows (b := .bit) (fetch h b) h keys = b := by + let code (i : Fin (2 ^ h)) := Lookup.bits h i + obtain ⟨keys, hk⟩ := Lookup.as_tree (a := word h) h (List.ofFn code) List.length_ofFn + refine ⟨keys, ?_, fun b => flatten_inj h ?_⟩ + · intro i + rw [hk, List.mem_ofFn] + exact ⟨⟨Lookup.value h i, value_lt h i⟩, value_injective h (Lookup.value_bits (value_lt h i))⟩ + · rw [flatten_mapRows, hk] + have hb := length_flatten h b + apply List.ext_getElem (by simp [hb]) + intro i hi hj + simp [code, fetch, Lookup.value_bits (show i < 2 ^ h by rw [← hb]; exact hj)] + +private theorem read_iff (h : ℕ) (keys : Val (tree h (word h))) (ha : ∀ i, i ∈ flatten h keys) + (hk : ∀ b : Val (tree h .bit), mapRows (b := .bit) (fetch h b) h keys = b) + (b : Val (tree h .bit)) (a : Val (tree h (word h))) (y : Val (tree h .bit)) : + Agree (flatten h (pairs h h keys b) ++ flatten h (pairs h h a y)) ↔ + batchRead h (b, a) = y := by + have hl := (entries h h (fetch h b) keys b).mpr (hk b) + unfold batchRead + rw [← entries] + constructor + · intro he i hi + obtain ⟨c, hc⟩ := entry_mem h h keys b i.1 (ha _) + exact (hl _ hc).trans (he _ (List.mem_append_left _ hc) _ (List.mem_append_right _ hi) rfl) + · intro hr i hi j hj he + have all := List.forall_mem_append.mpr ⟨hl, hr⟩ + exact (all i hi).symm.trans (he ▸ all j hj) + +theorem batch_read_net (F : Type) [Field F] (h : ℕ) : + DNet F (.pair (tree h .bit) (tree h (word h))) (tree h .bit) + (batchRead h) (10000 * 2 ^ h * (h + 1) ^ 3) := by + obtain ⟨keys, ha, hk⟩ := dictionary h + obtain ⟨f, checker, ok⟩ := agree_net F h (h + 1) + have zip := zipRows_net (a := word h) (b := .bit) (c := entry h) (f := Prod.mk) + (DNet.id F (entry h)) h + have left := (((literal_net F _ keys).par (DNet.id F (tree h .bit))).pre + ((Rewire.unit' _).comp (.swap _ _))).comp zip + obtain ⟨v, hv, net⟩ := ((left.par zip).pre (.assoc _ _ _)).comp checker + have pin := Net.table (F := F) .bit .unit (fun b _ => if b then 1 else 0) (by decide) + refine ⟨v + 1 + wd (tree h .bit), ?_, Net.curry ?_⟩ + · simp only [wd_tree, wd_word, wd, pow_succ] at hv ⊢ + have hp := Nat.one_le_pow h 2 (by decide) + ring_nf at hv ⊢ + omega + · convert net.comp pin using 1 + funext ⟨⟨b, a⟩, y⟩ u + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + have he := ok (pairs h h keys b, pairs h h a y) + exact if_congr (he.trans (read_iff h keys ha hk b a y)).symm rfl rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Control +end + +section +/- # Reading an array in any exterior bit layout -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Control + +private theorem read_eq {a : Wire} {w : ℕ} (L : Layout a (tree w a) (Fin (2 ^ w))) + (hL : ∀ x, List.ofFn (L.read x) = flatten w x) (x : Val (tree w a)) (i : Fin (2 ^ w)) : + L.read x i = (flatten w x)[i.val]'(by rw [Tagged.length_flatten]; exact i.isLt) := by + simp [← hL] + +theorem read_net (F : Type) [Field F] (w : ℕ) : + Install.BNet F (read w) (10000 * 2 ^ w * (w + 1) ^ 3) := by + obtain ⟨D, hD⟩ := Layout.exists_tree .bit w + obtain ⟨A, hA⟩ := Layout.exists_tree (word w) w + let b : Fin (2 ^ w) ≃ slots (tree w .bit) := + (Equiv.prodUnique _ Unit).symm.trans D.positions + let a := b.sumCongr A.positions + apply Install.BNet.of_layout (a := .pair (tree w .bit) (tree w (word w))) (b := tree w .bit) a b + convert batch_read_net F w using 1 + funext x + apply D.injective + funext i + have deref (data : Val (tree w .bit)) (k : Val (word w)) : + fetch w data k = D.read data (index w k) := + (read_eq D hD data (index w k)).symm + have hmap : D.read (batchRead w x) i = fetch w x.1 (A.read x.2 i) := by + simp only [read_eq D hD, read_eq A hA, batchRead, Tagged.flatten_mapRows, List.getElem_map] + rw [hmap, deref] + change (bits (tree w .bit)) ((bits (tree w .bit)).symm _) (b i) = _ + rw [Equiv.apply_symm_apply, Function.comp_apply, Equiv.symm_apply_apply] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Control +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/Ranks.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/Ranks.lean new file mode 100644 index 0000000000..9962ba780f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Control/Ranks.lean @@ -0,0 +1,170 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort + +/-! +# Histograms and occurrence ranks for fixed alphabets + +Run one prefix counter per symbol. At each position select the counter +for its own symbol. The alphabet and its bit encoding enter only the +constant in the bound. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Control +open Install + +/-- The indexed operation `D (fun j => x (i, j))`. -/ +def letters {I A : Type} {n : ℕ} (D : (I → Bool) → A) (x : Fin n × I → Bool) (i : Fin n) : A := + D (fun j => x (i, j)) + +/-- The indexed operation `bits (word (h + 1)) (Lookup.bits (h + 1) (Sum.elim (fun z => +histogram (letters D x) z none) (rank (letters D x)) ij.1)) ij.2`. -/ +def ranks {I A : Type} [DecidableEq A] (D : (I → Bool) → A) (h : ℕ) + (x : Fin (2 ^ h) × I → Bool) (ij : (A ⊕ Fin (2 ^ h)) × slots (word (h + 1))) : Bool := + bits (word (h + 1)) (Lookup.bits (h + 1) (Sum.elim + (fun z => histogram (letters D x) z none) (rank (letters D x)) ij.1)) ij.2 + +/-- The rank cost used in the `Control` construction. -/ +def rankCost (I A : Type) [Fintype I] [Fintype A] := + 7 * Fintype.card I + 2 ^ (Nat.clog 2 (Fintype.card A)) * + (4 * Fintype.card I + localCost (Fintype.card I) + 1002) + + localCost (1 + Fintype.card A + Fintype.card I) * (Fintype.card A + 1) + +theorem predicate_bnet (F I : Type) [Field F] [Fintype I] (P : (I → Bool) → Bool) (n : ℕ) : + BNet F (letters (n := n) P) (n * Fintype.card I + localCost (Fintype.card I) * n) := by + classical + have h : Depends (letters (n := n) P) (Fintype.card I) := by + intro i + refine ⟨Finset.univ.image (i, ·), Finset.card_image_le, fun x y h => ?_⟩ + exact congrArg P (funext fun j => h (i, j) (Finset.mem_image_of_mem _ (Finset.mem_univ j))) + simpa using h.bnet F + +variable {I A : Type} {h t : ℕ} + +private abbrev Source (I : Type) (h t : ℕ) := + (Fin (2 ^ h) × I) ⊕ (Fin (2 ^ t) × Option (Fin (2 ^ h)) × slots (word (h + 1))) + +private def pick (D : (I → Bool) → A) (e : A ↪ Fin (2 ^ t)) (x : Source I h t → Bool) + (ij : (A ⊕ Fin (2 ^ h)) × slots (word (h + 1))) : Bool := + match ij.1 with + | .inl z => x (.inr (e z, none, ij.2)) + | .inr i => x (.inr (e (letters D (x ∘ Sum.inl) i), some i, ij.2)) + +private theorem pick_depends [Fintype I] [Fintype A] (D : (I → Bool) → A) (e : A ↪ Fin (2 ^ t)) : + Depends (pick (h := h) D e) (1 + Fintype.card A + Fintype.card I) := by + classical + rintro ⟨z | i, k⟩ + · exact ⟨{.inr (e z, none, k)}, by simp; omega, fun x y h => h _ (by simp)⟩ + · let s : Finset (Source I h t) := Finset.univ.image (fun z => Sum.inr (e z, some i, k)) + let r : Finset (Source I h t) := Finset.univ.image (fun j => Sum.inl (i, j)) + refine ⟨s ∪ r, ?_, fun x y H => ?_⟩ + · have hs : s.card ≤ Fintype.card A := Finset.card_image_le + have hr : r.card ≤ Fintype.card I := Finset.card_image_le + exact (Finset.card_union_le s r).trans (by omega) + · have he : letters D (x ∘ Sum.inl) i = letters D (y ∘ Sum.inl) i := + congrArg D (funext fun j => H (.inl (i, j)) + (Finset.mem_union_right _ (Finset.mem_image_of_mem _ (Finset.mem_univ j)))) + simp only [pick, he] + exact H _ (Finset.mem_union_left _ (Finset.mem_image_of_mem _ (Finset.mem_univ _))) + +private theorem cost_bound (N R T I A L M : ℕ) (hN : 0 < N) (hR : 0 < R) : + 5 * (N * I) + N * I + T * (3 * (N * I) + (N * I + L * N + 1000 * N * R)) + + (N * I + T * ((N + 1) * R) + M * ((A + N) * R)) ≤ + (7 * I + T * (4 * I + L + 1002) + M * (A + 1)) * N * R := by + have h : A + N ≤ (A + 1) * N := by nlinarith + calc + _ ≤ 5 * (N * I * R) + N * I * R + T * (3 * (N * I * R) + (N * I * R + L * N * R + + 1000 * N * R)) + + (N * I * R + T * ((2 * N) * R) + M * (((A + 1) * N) * R)) := by + have hi := Nat.le_mul_of_pos_right (N * I) hR + have hl := Nat.le_mul_of_pos_right (L * N) hR + gcongr + omega + _ = _ := by ring + +theorem ranks_bnet (F I A : Type) [Field F] [Fintype I] [Fintype A] [DecidableEq A] + (D : (I → Bool) → A) (h : ℕ) : + BNet F (ranks D h) (rankCost I A * 2 ^ h * (h + 1)) := by + let t := Nat.clog 2 (Fintype.card A) + have he : Fintype.card A ≤ Fintype.card (Fin (2 ^ t)) := by + rw [Fintype.card_fin] + exact Nat.le_pow_clog (by decide) _ + let e := Classical.choice (Function.Embedding.nonempty_of_card_le he) + let P (z : Fin (2 ^ t)) (x : I → Bool) := decide (e (D x) = z) + have hc := BNet.share t _ (fun z => (predicate_bnet F I (P z) (2 ^ h)).comp (prefix_bnet F h)) + have hh := ((BNet.id F (Fin (2 ^ h) × I)).pair hc).comp ((pick_depends (h := h) D e).bnet F) + have ht := hh.mono (n := rankCost I A * 2 ^ h * (h + 1)) (by + simp only [Source, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, Fintype.card_option, + card_slots, wd_word, rankCost, show Fintype.card (slots .bit) = 1 from rfl, Nat.add_comm 1 h] + exact cost_bound (2 ^ h) (h + 1) (2 ^ t) _ _ _ _ (by positivity) (by omega)) + convert ht using 1 + funext x p + have hz (z : A) (j : Option (Fin (2 ^ h))) : + histogram (letters (P (e z)) x) true j = histogram (letters D x) z j := by + unfold histogram + congr 1 + ext i + simp only [Finset.mem_filter, Finset.mem_univ, true_and] + simp only [letters, P, decide_eq_true_eq, e.injective.eq_iff] + rcases p with ⟨z | i, k⟩ + · change _ = bits (word (h + 1)) (Lookup.bits _ (histogram (letters (P (e z)) x) true none)) k + rw [hz]; rfl + · change _ = bits (word (h + 1)) + (Lookup.bits _ (histogram (letters (P (e (letters D x i))) x) true (some i))) k + rw [hz]; rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Control +end + +section +/- # Comparing an encoded count to fixed thresholds -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Control +open Install + +variable (F : Type) [Field F] + +private theorem threshold_test (h n : ℕ) : + DNet F (word h) .bit (fun x => decide (Lookup.value h x ≤ n)) (1000 * (h + 1)) := by + by_cases hn : n + 1 < 2 ^ h + · have k := ((DNet.id F (word h)).par (Lookup.const_net F (word h) (Lookup.bits h (n + 1)))).pre + (.unit' _) + have t := k.comp (Coloring.lt_net F h) + simpa only [Lookup.value_bits hn, Nat.lt_succ_iff] using t.mono (n := 1000 * (h + 1)) + (by simp; omega) + · have e (x) : Lookup.value h x ≤ n := by have := value_lt h x; omega + have t := (DNet.discard F (word h)).comp (Lookup.const_net F .bit true) + simpa only [e, decide_true] using t.mono (n := 1000 * (h + 1)) (by simp [wd]) + +theorem threshold_one (h n : ℕ) : + BNet F (fun (x : slots (word h) → Bool) (_ : Unit) => decide ((decode h x).val ≤ n)) + (1000 * (h + 1)) := by + apply BNet.of_layout (a := word h) (b := .bit) (.refl _) (.refl _) + convert threshold_test F h n using 1 + funext x + change decide (Lookup.value h ((bits (word h)).symm (bits (word h) x)) ≤ n) = _ + rw [Equiv.symm_apply_apply] + +theorem threshold_bnet (h : ℕ) : + BNet F (fun (x : slots (word h) → Bool) (i : Fin (2 ^ h)) => decide ((decode h x).val ≤ i.val)) + (2000 * 2 ^ h * (h + 1)) := by + have t := BNet.share h _ fun i => threshold_one F h i.val + apply (t.rename (.refl _) (Equiv.prodUnique _ Unit)).mono + rw [card_slots, wd_word] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Control +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Derivatives.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Derivatives.lean new file mode 100644 index 0000000000..f0993492cc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Derivatives.lean @@ -0,0 +1,89 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.DualNumber +public import Mathlib.Algebra.MvPolynomial.Eval +public import Mathlib.RingTheory.Derivation.Basic +public import Mathlib.RingTheory.Localization.FractionRing + +/-! +# Partial derivatives at the generic point + +Perturb one input by a square-zero variable. Projection to the constant +term is the identity, so every nonzero polynomial maps to a unit. The +perturbation thus extends to rational functions in any characteristic. +-/ + +@[expose] public section + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {F : Type*} [Field F] {σ : Type} + +local notation "P" => MvPolynomial σ F +local notation "K" => FractionRing P + +/-- The image of a polynomial variable when coordinate `i` is perturbed. -/ +def shiftedX (i j : σ) : DualNumber K := by + classical + exact (algebraMap P K (MvPolynomial.X j), if i = j then 1 else 0) + +/-- Polynomial evaluation at the perturbed generic point. -/ +def shiftPoly (i : σ) : P →ₐ[F] DualNumber K := + MvPolynomial.aeval (shiftedX i) + +private theorem fst_shiftPoly (i : σ) (p : P) : + (shiftPoly i p).fst = algebraMap P K p := by + have h : (TrivSqZeroExt.fstHom F K K).comp (shiftPoly i) = Algebra.algHom F P K := by + apply MvPolynomial.algHom_ext + intro j + rw [AlgHom.comp_apply, shiftPoly, MvPolynomial.aeval_X] + rfl + exact DFunLike.congr_fun h p + +theorem shiftPoly_unit (i : σ) (p : nonZeroDivisors P) : + IsUnit (shiftPoly (F := F) i p) := by + rw [TrivSqZeroExt.isUnit_iff_isUnit_fst, fst_shiftPoly] + exact IsLocalization.map_units K p + +/-- Computes the shift by the application `IsLocalization.liftAlgHom (shiftPoly_unit i)`. -/ +def shift (i : σ) : K →ₐ[F] DualNumber K := + IsLocalization.liftAlgHom (shiftPoly_unit i) + +private theorem shift_poly (i : σ) (p : P) : + shift i (algebraMap P K p) = shiftPoly i p := + IsLocalization.lift_eq (shiftPoly_unit i) p + +private theorem fst_shift (i : σ) (x : K) : (shift i x).fst = x := by + have h : (TrivSqZeroExt.fstHom F K K).comp (shift i) = AlgHom.id F K := by + apply IsLocalization.algHom_ext (nonZeroDivisors P) + apply AlgHom.ext + intro p + change (shift i (algebraMap P K p)).fst = algebraMap P K p + rw [shift_poly, fst_shiftPoly] + exact DFunLike.congr_fun h x + +/-- Formal partial differentiation on the field of rational functions. -/ +def partialD (i : σ) : Derivation F K K where + toLinearMap := ((TrivSqZeroExt.sndHom K K).restrictScalars F).comp (shift i).toLinearMap + map_one_eq_zero' := by + change (shift (F := F) i 1).snd = 0 + simp + leibniz' x y := by + change (shift i (x * y)).snd = x * (shift i y).snd + y * (shift i x).snd + rw [map_mul, DualNumber.snd_mul, fst_shift, fst_shift, mul_comm _ y] + +@[simp] theorem partialD_X [DecidableEq σ] (i j : σ) : + partialD (F := F) i (algebraMap P K (MvPolynomial.X j)) = if i = j then 1 else 0 := by + change (shift i (algebraMap P K (MvPolynomial.X j))).snd = _ + rw [shift_poly, shiftPoly, MvPolynomial.aeval_X] + by_cases h : i = j <;> simp [shiftedX, h, TrivSqZeroExt.snd] + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Descent.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Descent.lean new file mode 100644 index 0000000000..2543e5d5d7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Descent.lean @@ -0,0 +1,58 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.RankDescent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights +public import Mathlib.LinearAlgebra.Dual.Lemmas + +/-! # Descent of weighted rank along finite field extensions -/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +/-- A degree-`d` extension increases the cost of descending a rank witness +by at most a factor of `d²`. Only the two input legs are expanded in a basis. +A linear functional sending one to one recovers the output coefficients, +even in characteristics dividing `d`. -/ +theorem descendWeighted {F : Type*} {L : Type*} [Field F] [Field L] [Algebra F L] + [Module.Finite F L] + {i j k r : ℕ} {W : Fin i → Fin j → Fin k → F} + (h : WeightedRankLE (fun x y z => algebraMap F L (W x y z)) r) : + WeightedRankLE W (r * Module.finrank F L ^ 2) := by + classical + obtain ⟨π, hπ⟩ := Module.Projective.exists_dual_eq_one F (one_ne_zero : (1 : L) ≠ 0) + let T : Tensor F (Pos i k) (Pos k j) (Pos i j) := fun x y z => + if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then W x.1 y.2 x.2 else 0 + have hT : Tensor.RankAtMost (fun x y z => algebraMap F L (T x y z)) r := by + obtain ⟨a, b, c, habc⟩ := h + refine ⟨a, b, c, ?_⟩ + funext x y z + simp only [Tensor.rankOne] + dsimp only [T] + rw [habc, apply_ite (algebraMap F L), map_zero] + obtain ⟨a, b, c, habc⟩ := hT.descend_algebra (Module.finBasis F L) π hπ + exact ⟨a, b, c, fun x y z => (congrFun (congrFun (congrFun habc x) y) z).symm⟩ + +theorem descendRank {F : Type*} {L : Type*} [Field F] [Field L] [Algebra F L] [Module.Finite F L] + {i j k r : ℕ} (h : RankLE L i j k r) : RankLE F i j k (r * Module.finrank F L ^ 2) := by + have h' : WeightedRankLE (fun (_ : Fin i) (_ : Fin j) (_ : Fin k) => algebraMap F L 1) r := by + simpa only [map_one, WeightedRankLE, RankLE, TensorSpectrum.MatrixRank] using h + exact descendWeighted (F := F) (W := fun _ _ _ => 1) h' + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem descendRank {F : Type*} {L : Type*} [Field F] [Field L] [Algebra F L] [Module.Finite F L] + {n r : ℕ} (h : RankLE L n r) : RankLE F n (r * Module.finrank F L ^ 2) := + Rectangle.descendRank h + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/AlphabetCode.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/AlphabetCode.lean new file mode 100644 index 0000000000..78d0c42d2d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/AlphabetCode.lean @@ -0,0 +1,997 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Cuts +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Packets +public import Mathlib.Order.Sigma + +/-! # Uniformity of the two group names of a packet -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +variable {A B Z : Type} [Fintype A] [Fintype B] [Fintype Z] [DecidableEq Z] + +omit [Fintype B] in +/-- A product parametrization makes the number of points per label exact. -/ +private theorem uniform [Finite B] (e : A ≃ Z × B) (z : Z) : + multiplicity (fun a => (e a).1) z * Fintype.card Z = Fintype.card A := by + let : Fintype B := Fintype.ofFinite B + have ht : multiplicity (fun a => (e a).1) z = Fintype.card B := by + apply Fintype.card_congr + exact { + toFun := fun a => (e a.val).2 + invFun := fun b => ⟨e.symm (z, b), congrArg Prod.fst (e.apply_symm_apply (z, b))⟩ + left_inv := fun a => Subtype.ext (e.symm_apply_eq.mpr (Prod.ext a.2.symm rfl)) + right_inv := by intro b; simp } + rw [ht, Fintype.card_congr e, Fintype.card_prod, mul_comm] + +variable {n r d : ℕ} + +theorem label_uniform (i : Fin n) (g : Fin r) : + multiplicity (fun a : Label n r => a i) g * r = r ^ n := by + have H := uniform (Equiv.funSplitAt i (Fin r)) g + change multiplicity (fun a : Label n r => a i) g * _ = _ at H + simpa using H + +/-- Each of the two labels has one independently variable symbol per coordinate. -/ +abbrev Key (n : ℕ) := Fin n × Bool + +/-- Reindexes `Template n r` and `(Key n → Fin r) where toFun p i` by an equivalence. -/ +def symbols (n r : ℕ) : Template n r ≃ (Key n → Fin r) where + toFun p i := group p i.1 i.2 + invFun f := (fun i => f (i, false), fun i => f (i, true)) + left_inv _ := rfl + right_inv _ := by funext ⟨i, b⟩; cases b <;> rfl + +theorem group_uniform (i : Fin n) (b : Bool) (g : Fin r) : + multiplicity (fun p : Packet n r d => group p.1 i b) g * r = + Fintype.card (Packet n r d) := by + let e := (symbols n r).trans (Equiv.funSplitAt (i, b) (Fin r)) + let t := (e.prodCongr (Equiv.refl (Fin d))).trans (Equiv.prodAssoc _ _ _) + have H := uniform t g + change multiplicity (fun p : Packet n r d => group p.1 i b) g * _ = _ at H + simpa only [Fintype.card_fin] using H + +theorem pair_uniform (i j : Key n) (hne : j ≠ i) (g g' : Fin r) : + multiplicity (fun p : Packet n r d => (symbols n r p.1 i, symbols n r p.1 j)) (g, g') * r ^ 2 = + Fintype.card (Packet n r d) := by + let e := (symbols n r).trans (Equiv.funSplitAt i (Fin r)) + let a := Equiv.funSplitAt (⟨j, hne⟩ : {u : Key n // u ≠ i}) (Fin r) + let f := (e.trans ((Equiv.refl _).prodCongr a)).trans (Equiv.prodAssoc _ _ _).symm + let t := (f.prodCongr (Equiv.refl (Fin d))).trans (Equiv.prodAssoc _ _ _) + have H := uniform t (g, g') + change multiplicity (fun p : Packet n r d => (symbols n r p.1 i, symbols n r p.1 j)) + (g, g') * _ = _ at H + simpa only [Fintype.card_prod, Fintype.card_fin, pow_two] using H + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- +# Two coordinate assignments for overloaded groups + +Keep light work at its group. Assign heavy work by a different +coordinate of its label. The bound below applies both to the reassigned +work and to each light group's contacts with heavy groups. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal +open Finset + +variable {n r d : ℕ} + +/-- The packet touches a heavy group at the cut and a given group +at the worker coordinate. -/ +def contact (i j : Fin n) (H : Finset (Fin r)) (g : Fin r) : Finset (Packet n r d) := + univ.filter (fun p => (∃ s, group p.1 i s ∈ H) ∧ (∃ s, group p.1 j s = g)) + +private theorem contact_pair (i j : Fin n) (g e : Fin r) (b c : Bool) + (hne : i ≠ j ∨ g ≠ e) : + (univ.filter (fun p : Packet n r d => group p.1 i b = g ∧ group p.1 j c = e)).card * r ^ 2 ≤ + Fintype.card (Packet n r d) := by + by_cases hpair : (j, c) = (i, b) + · obtain ⟨rfl, rfl⟩ := Prod.mk.inj hpair + have hne' := hne.resolve_left (not_ne_iff.mpr rfl) + have he (p : Packet n r d) : ¬ (group p.1 j c = g ∧ group p.1 j c = e) := + fun h => hne' (h.1.symm.trans h.2) + simp [he] + · have he := pair_uniform (d := d) (i, b) (j, c) hpair g e + change multiplicity (fun p : Packet n r d => (group p.1 i b, group p.1 j c)) (g, e) * r ^ 2 + = _ at he + simpa [multiplicity, Fintype.card_subtype] using he.le + +theorem contact_bound (i j : Fin n) (H : Finset (Fin r)) (g : Fin r) (h : i ≠ j ∨ g ∉ H) : + (contact (d := d) i j H g).card * r ^ 2 ≤ 4 * H.card * Fintype.card (Packet n r d) := by + let S := H ×ˢ (univ : Finset (Bool × Bool)) + let T (a : Fin r × Bool × Bool) := univ.filter (fun p : Packet n r d => + group p.1 i a.2.1 = a.1 ∧ group p.1 j a.2.2 = g) + have sub : contact (d := d) i j H g ⊆ S.biUnion T := by + intro p hp + obtain ⟨_, ⟨b, hb⟩, ⟨c, hc⟩⟩ := mem_filter.mp hp + exact mem_biUnion.mpr ⟨(group p.1 i b, b, c), mem_product.mpr ⟨hb, mem_univ _⟩, + mem_filter.mpr ⟨mem_univ _, rfl, hc⟩⟩ + calc + _ ≤ (∑ i ∈ S, (T i).card) * r ^ 2 := + Nat.mul_le_mul_right _ ((card_le_card sub).trans card_biUnion_le) + _ = ∑ i ∈ S, (T i).card * r ^ 2 := sum_mul .. + _ ≤ ∑ _ ∈ S, Fintype.card (Packet n r d) := sum_le_sum (fun u hu => by + apply contact_pair + rcases h with h | h + · exact .inl h + · exact .inr (fun he => h (he ▸ (mem_product.mp hu).1))) + _ = _ := by simp [S, mul_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- +# Bounding communication with two fixed pools of workers + +A light home can afford the crossing bits of its light pairs. Packets +touching a heavy group are evaluated whole, assigning workers by a +second coordinate. Each such packet costs at most two full blocks of +slots at any one worker. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal +open Finset + +variable {n r d : ℕ} + +/-- Count both incidences, even if they belong to the same group. -/ +def charge (i : Fin n) (q : Packet n r d → ℕ) (g : Fin r) := + ∑ p, ((if group p.1 i false = g then q p else 0) + (if group p.1 i true = g then q p else 0)) + +theorem charge_total (i : Fin n) (q : Packet n r d → ℕ) : + ∑ g, charge i q g = 2 * ∑ p, q p := by + unfold charge + rw [sum_comm] + simp only [sum_add_distrib, sum_ite_eq, mem_univ, ite_true, two_mul] + +/-- Selects the elements of all indices satisfying `(fun g => N < T * charge i q g)`. -/ +def heavy (T N : ℕ) (i : Fin n) (q : Packet n r d → ℕ) := + univ.filter (fun g => N < T * charge i q g) + +private theorem heavy_bound {C L W T N : ℕ} (hN : 0 < N) + (hw : Fintype.card (Packet n r d) * W ≤ C * r * N) (i : Fin n) (q : Packet n r d → ℕ) + (hs : L * ∑ p, q p ≤ 2 * Fintype.card (Packet n r d) * W) : + (heavy T N i q).card * L ≤ 4 * T * C * r := by + let H := heavy T N i q + have hb : H.card * N ≤ T * ∑ g, charge i q g := by + calc + _ = ∑ _ ∈ H, N := by simp + _ ≤ ∑ g ∈ H, T * charge i q g := sum_le_sum (fun g hg => (mem_filter.mp hg).2.le) + _ ≤ ∑ g, T * charge i q g := sum_le_sum_of_subset (subset_univ _) + _ = _ := (mul_sum ..).symm + rw [charge_total] at hb + apply (Nat.mul_le_mul_right_iff hN).mp + calc + _ = (H.card * N) * L := by unfold H; ring + _ ≤ (T * (2*∑ p, q p)) * L := Nat.mul_le_mul_right _ hb + _ = (2 * T) * (L * ∑ p, q p) := by ring + _ ≤ (2 * T) * (2 * Fintype.card (Packet n r d) * W) := Nat.mul_le_mul_left _ hs + _ = 4 * T * (Fintype.card (Packet n r d) * W) := by ring + _ ≤ 4 * T * (C * r * N) := Nat.mul_le_mul_left _ hw + _ = _ := by ring + +/-- Bound the entire workload of each reassigned worker (`i ≠ j`) +or the work sent to heavy partners by any light home (`g ∉ H`). -/ +theorem workload {C L W T N : ℕ} (hN : 0 < N) (hL : 0 < L) + (hsave : 32 * T ^ 2 * C ^ 2 ≤ L) (hw : Fintype.card (Packet n r d) * W ≤ C * r * N) + (i j : Fin n) (q : Packet n r d → ℕ) (hs : L * ∑ p, q p ≤ 2 * Fintype.card (Packet n r d) * W) + (g : Fin r) (hg : i ≠ j ∨ g ∉ heavy T N i q) : + T * (2 * W * (contact (d := d) i j (heavy T N i q) g).card) ≤ N := by + let H := heavy T N i q + let K := (contact (d := d) i j H g).card + have hH : H.card * L ≤ 4 * T * C * r := heavy_bound hN hw i q hs + have hK : K * r ^ 2 ≤ 4 * H.card * Fintype.card (Packet n r d) := contact_bound i j H g hg + have hr : 0 < r := g.isLt |> Nat.zero_lt_of_lt + apply (Nat.mul_le_mul_right_iff (by positivity : 0 < L * r ^ 2)).mp + change (T * (2 * W * K)) * (L * r ^ 2) ≤ N * (L * r ^ 2) + calc + _ = (2 * T * W * L) * (K * r ^ 2) := by ring + _ ≤ (2 * T * W * L) * (4 * H.card * Fintype.card (Packet n r d)) := Nat.mul_le_mul_left _ hK + _ = 8 * T * (H.card * L) * (Fintype.card (Packet n r d) * W) := by ring + _ ≤ 8 * T * (4 * T * C * r) * (C * r * N) := by gcongr + _ = 32 * T ^ 2 * C ^ 2 * (N * r ^ 2) := by ring + _ ≤ L * (N * r ^ 2) := Nat.mul_le_mul_right _ hsave + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- +# Assigning each virtual bit to two processors + +Two pools indexed by the auxiliary coordinate handle the heavy groups. +This makes the locations of the workers independent of the internal +wiring of the batch. Self-links may remain private. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Spectral +variable {n r d h : ℕ} + +/-- The worker used in the `Diagonal` construction. -/ +inductive Worker (r : ℕ) where + | home (g : Fin r) + | station (g : Fin r) + | packet (g : Fin r) + deriving DecidableEq, Fintype + +/-- The data for the plan construction, including `cut`, `aux`, `groups`, `q`. -/ +structure Plan (n r d : ℕ) where + /-- The `Plan` component of type `Fin n`. -/ + cut : Fin n + /-- The `Plan` component of type `Fin n`. -/ + aux : Fin n + /-- The `Plan` component of type `Finset (Fin r)`. -/ + groups : Finset (Fin r) + /-- The `Plan` component of type `Packet n r d → ℕ`. -/ + q : Packet n r d → ℕ + +namespace Plan +variable (π : Plan n r d) + +/-- Returns `.station (x π.aux)` when `x π.cut ∈ π.groups` holds, and `.home (x π.cut)` +otherwise. -/ +def base (x : Label n r) : Worker r := + if x π.cut ∈ π.groups then .station (x π.aux) else .home (x π.cut) + +/-- The condition `∃ s, group p.1 π.cut s ∈ π.groups deriving Decidable` on the specified data. -/ +def marked (p : Packet n r d) : Prop := ∃ s, group p.1 π.cut s ∈ π.groups + deriving Decidable + +/-- Heavy packets share both blocks of slots. Light packets share +the selector and the wire bits at the chosen cut. -/ +abbrev Message (h : ℕ) (p : Packet n r d) := + { _m : Bool × Cube n × Fin h // π.marked p } ⊕ { _m : Fin (π.q p) // ¬π.marked p } + +/-- The sender used in the `Plan` construction. -/ +def sender (p : Packet n r d) : π.Message h p → Worker r + | .inl m => π.base (corner p.1 (if m.1.1 then Cube.flip Finset.univ m.1.2.1 else m.1.2.1)) + | .inr _ => .home (group p.1 π.cut false) + +/-- In the case `.inl _`, this construction gives `.packet (group p.1 π.aux false)`. -/ +def receiver (p : Packet n r d) : π.Message h p → Worker r + | .inl _ => .packet (group p.1 π.aux false) + | .inr _ => .home (group p.1 π.cut true) + +/-- The value specified by `Fintype.card {m : π.Message h p // π.sender p m = u ∨ π.receiver p m += u}`. -/ +def slotsAt (h : ℕ) (u : Worker r) (p : Packet n r d) := + Fintype.card {m : π.Message h p // π.sender p m = u ∨ π.receiver p m = u} + +/-- In the case `.home g`, this construction gives `if g ∈ π.groups then ∅ else contact π.cut +π.cut π.groups g`. -/ +def eligible (u : Worker r) : Finset (Packet n r d) := + match u with + | .home g => if g ∈ π.groups then ∅ else contact π.cut π.cut π.groups g + | .station g | .packet g => contact π.cut π.aux π.groups g + +private theorem base_mem (p : Packet n r d) (hm : π.marked p) (x : Cube n) : + p ∈ π.eligible (π.base (corner p.1 x)) := by + unfold base + split_ifs with h + · exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, hm, ⟨x π.aux, rfl⟩⟩ + · simp only [eligible, h, ite_false] + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, hm, ⟨x π.cut, rfl⟩⟩ + +private theorem receiver_mem (p : Packet n r d) (hm : π.marked p) : + p ∈ π.eligible (.packet (group p.1 π.aux false)) := + Finset.mem_filter.mpr ⟨Finset.mem_univ _, hm, ⟨false, rfl⟩⟩ + +private def light (p : Packet n r d) : Worker r → ℕ + | .home g => if g ∈ π.groups then 0 else + (if group p.1 π.cut false = g then π.q p else 0) + + (if group p.1 π.cut true = g then π.q p else 0) + | _ => 0 + +private theorem light_le (p : Packet n r d) (hm : ¬π.marked p) (b : Bool) : + π.q p ≤ π.light p (.home (group p.1 π.cut b)) := by + have he : group p.1 π.cut b ∉ π.groups := fun h => hm ⟨b, h⟩ + simp only [light, he, ite_false] + cases b <;> simp + +private theorem slotsAt_le (u : Worker r) (p : Packet n r d) : + π.slotsAt h u p ≤ π.light p u + + if p ∈ π.eligible u then 2 * (Fintype.card (Cube n) * h) else 0 := by + classical + by_cases hz : π.slotsAt h u p = 0 + · rw [hz]; exact Nat.zero_le _ + have hc : π.slotsAt h u p ≤ Fintype.card (π.Message h p) := Fintype.card_subtype_le _ + obtain ⟨⟨m, hs⟩⟩ := Fintype.card_pos_iff.mp (Nat.pos_of_ne_zero hz) + rcases m with m|m + · have he : p ∈ π.eligible u := by + rcases hs with rfl | rfl + · exact π.base_mem p m.2 _ + · exact π.receiver_mem p m.2 + rw [ite_eq_left he] + refine hc.trans (le_trans ?_ (Nat.le_add_left _ _)) + simp [Message, m.2] + · have he : π.q p ≤ π.light p u := by + rcases hs with rfl | rfl + · exact π.light_le p m.2 false + · exact π.light_le p m.2 true + refine hc.trans (le_trans ?_ (he.trans (Nat.le_add_right _ _))) + simp [Message, m.2] + +/-- The endpoint budget for all packets, including every padded position. -/ +theorem capacity {C L T N : ℕ} (hN : 0 < N) (hL : 0 < L) (hsave : 32 * T ^ 2 * C ^ 2 ≤ L) + (hw : Fintype.card (Position n r d h) ≤ C * r * N) (hne : π.cut ≠ π.aux) + (hH : π.groups = heavy T N π.cut π.q) + (hs : L * ∑ p, π.q p ≤ 2 * Fintype.card (Position n r d h)) (u : Worker r) : + T * ∑ p, π.slotsAt h u p ≤ 2 * N := by + let W := Fintype.card (Cube n) * h + have size : Fintype.card (Position n r d h) = Fintype.card (Packet n r d) * W := by + simp only [Position, Fintype.card_prod, Fintype.card_fin, W] + rw [size] at hw + rw [size, ← mul_assoc] at hs + have hl : T * ∑ p, π.light p u ≤ N := by + cases u with + | station g | packet g => simp [light] + | home g => + by_cases hg : g ∈ π.groups + · simp [light, hg] + · simp only [light, hg, ite_false] + change T * charge π.cut π.q g ≤ N + simpa only [hH, heavy, Finset.mem_filter, Finset.mem_univ, true_and, not_lt] using hg + have he : T * (2 * W * (π.eligible u).card) ≤ N := by + cases u with + | station g | packet g => + simp only [eligible, hH] + exact workload hN hL hsave hw _ _ _ hs _ (.inl hne) + | home g => + simp only [eligible, hH] + split_ifs with hg + · simp + · exact workload hN hL hsave hw _ _ _ hs _ (.inr hg) + calc + _ ≤ T * ∑ p, (π.light p u + if p ∈ π.eligible u then 2 * W else 0) := + Nat.mul_le_mul_left T (Finset.sum_le_sum (fun p _ => π.slotsAt_le u p)) + _ = T * (∑ p, π.light p u) + T * (2 * W * (π.eligible u).card) := by + simp [Finset.sum_add_distrib, mul_add, mul_comm] + _ ≤ _ := by omega + +end Plan +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- # Adaptive packet expansion for independent copies of a diagram -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout + +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} {n r h B : ℕ} +variable (L : Layout G n r h) + +open Classical in +/-- Keep the cube template and combine the batch and repetition indices. -/ +def batchLoad (x : Fin B → G.End → Bool) (p : Packet n r (B * L.d)) : Block n h := + L.load (x (finProdFinEquiv.symm p.2).1) (p.1, (finProdFinEquiv.symm p.2).2) + +open Classical in +theorem batchLoad_injective : Function.Injective (L.batchLoad (B := B)) := by + intro x y he + funext j + apply L.load_injective + funext p + simpa only [batchLoad, Equiv.symm_apply_apply] using + congrFun he (p.1, finProdFinEquiv (j, p.2)) + +open Classical in +/-- All copies may share a single coordinate choice based on all selectors. +Station and junction bits remain separate until the packet sum restores their +equality. -/ +theorem eval_batch (A : Expansion F n h) (x : Fin B → Val a) (y : Fin B → Val b) + (cut : (Packet n r (B * L.d) → A.I) → Fin n) + (split : (Packet n r (B * L.d) → A.I) → Packet n r (B * L.d) → Bool) : + ∏ j, G.eval (x j) (y j) = + ∑ u : Fin B → G.End → Bool, ∑ v : Fin B → G.End → Bool, + (∏ j, ∏ i : G.V, G.normalized.vertex (x j) (y j) (u j) (.inl i)) * + (∏ j, ∏ i : G.Joint, G.normalized.vertex (x j) (y j) (v j) (.inr i)) * + ∑ s, ∑ z : A.Wires s (cut s) (split s), ∏ p, + A.value (s p) (cut s) (L.batchLoad u p) (L.batchLoad v p) (split s p) (z p) := by + simp only [A.adaptive, L.batchLoad_injective.eq_iff, mul_ite, mul_one, mul_zero, + Finset.sum_ite_eq, Finset.mem_univ, ite_true, ← Finset.prod_mul_distrib] + simp_rw [L.eval A, A.full_product, L.load_injective.eq_iff, mul_ite, mul_one, + mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + exact Fintype.prod_sum _ + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +/- +# Cutting a packet across one cube coordinate + +Partition the supply edges into crossing edges and two sets of internal +edges. Fixing the crossing bits leaves independent contractions on the +two sides. Each supply edge is charged at exactly one coordinate. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Spectral +variable {F J : Type} [Field F] [Fintype J] + +namespace Cut + +open Classical in +/-- The edges with no privately assigned side. -/ +abbrev Shared (κ : J → Option Bool) := {e // κ e = none} +open Classical in +/-- The subtype of `e` satisfying `κ e = some b`. -/ +abbrev Own (κ : J → Option Bool) (b : Bool) := {e // κ e = some b} + +open Classical in +private def combine (κ : J → Option Bool) : + (Shared κ → Bool) × (Own κ false → Bool) × (Own κ true → Bool) ≃ (J → Bool) where + toFun u e := if h : κ e = none then u.1 ⟨e, h⟩ else + if g : κ e = some false then u.2.1 ⟨e, g⟩ else u.2.2 ⟨e, by + cases he : κ e with + | none => contradiction + | some b => cases b <;> simp_all⟩ + invFun p := (fun e => p e, fun e => p e, fun e => p e) + left_inv u := by + ext ⟨e, he⟩ <;> simp [he] + right_inv p := by funext e; simp + +open Classical in +/-- Selects the appropriate branch of `if h : κ e = none then u ⟨e, h⟩ else if h : κ e = some b +then v ⟨e, h⟩ else false`. -/ +def patch (κ : J → Option Bool) (b : Bool) (u : Shared κ → Bool) + (v : Own κ b → Bool) (e : J) : Bool := + if h : κ e = none then u ⟨e, h⟩ else if h : κ e = some b then v ⟨e, h⟩ else false + +open Classical in +/-- The sum of `φ b (patch κ b (u ∘ Fintype.equivFin (Shared κ)) v)` indexed by `v`. -/ +def part (κ : J → Option Bool) (φ : Bool → (J → Bool) → F) (b : Bool) + (u : Fin (Fintype.card (Shared κ)) → Bool) : F := + ∑ v, φ b (patch κ b (u ∘ Fintype.equivFin (Shared κ)) v) + +open Classical in +theorem split (κ : J → Option Bool) (φ : Bool → (J → Bool) → F) + (h : ∀ b u v, (∀ e, κ e = none ∨ κ e = some b → u e = v e) → φ b u = φ b v) : + (∑ u, φ false u * φ true u) = ∑ z, part κ φ false z * part κ φ true z := by + have hf (u v w) : φ false (combine κ (u, v, w)) = φ false (patch κ false u v) := + h _ _ _ (fun e he => by rcases he with he | he <;> simp [combine, patch, he]) + have ht (u v w) : φ true (combine κ (u, v, w)) = φ true (patch κ true u w) := + h _ _ _ (fun e he => by rcases he with he | he <;> simp [combine, patch, he]) + rw [← (combine κ).sum_comp, Fintype.sum_prod_type] + let E := Equiv.arrowCongr (Fintype.equivFin (Shared κ)).symm (Equiv.refl Bool) + rw [← E.sum_comp] + apply Finset.sum_congr rfl + intro z _ + rw [Fintype.sum_prod_type] + simp only [hf, ht, ← Finset.mul_sum, ← Finset.sum_mul] + rfl + +end Cut + +variable {n h : ℕ} + +open Classical in +/-- Charge each supply bit to the unique coordinate changed by its edge. -/ +private def region (p : Cube n × Fin n) (i : Fin n) : Option Bool := + if p.2 = i then none else some (p.1 i) + +open Classical in +private theorem region_card (t : J → Cube n × Fin n) : + ∑ i, Fintype.card {e // region (t e) i = none} = Fintype.card J := by + simp [region, Fintype.card_subtype, Finset.sum_card_fiberwise_eq_card_filter] + +open Classical in +private def half (i : Fin n) (g : Cube n → F) (b : Bool) : F := + ∏ v, if v i = b then g v else 1 + +open Classical in +private theorem prod_half (i : Fin n) (g : Cube n → F) : + (∏ v, g v) = half i g false * half i g true := by + rw [half, half, ← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro v _ + cases v i <;> simp + +open Classical in +private theorem half_congr {i : Fin n} {g g' : Cube n → F} {b : Bool} + (he : ∀ v, v i = b → g v = g' v) : half i g b = half i g' b := by + apply Finset.prod_congr rfl + intro v _ + split + · apply he; assumption + · rfl + +open Classical in +theorem expand_packet {I : Type} {A : I → Type} [Fintype I] [∀ s, Fintype (A s)] + (edges : (s : I) → A s → Cube n × Fin n) + (packet : Spectral.Packet F (fun p : Cube n × Fin h => (p.1, Cube.flip Finset.univ p.1)) + (fun s e => ((edges s e).1, Cube.flip {(edges s e).2} (edges s e).1))) : + ∃ E : Expansion F n h, Fintype.card E.I = Fintype.card I ∧ + ∀ s, ∃ t : I, ∑ i, E.cross s i = Fintype.card (A t) := by + obtain ⟨f, hf, full⟩ := packet + let κ (s : I) (i : Fin n) (e : A s) := region (edges s e) i + let φ (s : I) (i : Fin n) (x y : Block n h) (b : Bool) (u : A s → Bool) := + half i (fun v => f s v x y u) b + let E : Expansion F n h := { + I := I + weight := fun s x y => ∑ u, ∏ v, f s v x y u + cross := fun s i => Fintype.card {e // κ s i e = none} + side := fun s i b x y z => Cut.part (κ s i) (φ s i x y) b z + full := fun x y => (full x y).symm + split := by + intro s i x y + simp_rw [prod_half i] + apply Cut.split (κ s i) (φ s i x y) + intro b u u' he + apply half_congr + intro v hv + refine hf _ _ _ _ _ _ _ _ (fun _ _ => rfl) (fun _ _ => rfl) (fun e hh => he e ?_) + by_cases hc : (edges s e).2 = i + · exact .inl (by simp [κ, region, hc]) + · right + rcases hh with h₁ | h₂ + · change (edges s e).1 = v at h₁ + simp [κ, region, hc, h₁, hv] + · have h₃ := (congrFun h₂ i).trans hv + simpa [κ, region, Cube.flip, hc, Ne.symm hc] using h₃ + depends := by + intro s i b x x' y y' z hx hy + apply Finset.sum_congr rfl + intro u _ + apply half_congr + intro v hv + apply hf + · intro e he + exact hx e ((congrFun he i).trans hv) + · intro e he + apply hy + have h₁ := (congrFun he i).trans hv + simp [Cube.flip] at h₁ + grind + · intro e _; rfl + } + exact ⟨E, rfl, fun s => ⟨s, region_card (edges s)⟩⟩ + +open Classical in +/-- A cube of arbitrarily large dimension with a packet expansion. +The average crossing cost and the selector length can both be made +arbitrarily small compared with the number of demanded bits. -/ +theorem expansion (F : Type) [Field F] (L n₀ : ℕ) (hL : 0 < L) : + ∃ n ≥ n₀, ∃ h : ℕ, ∃ E : Expansion F n h, 0 < h ∧ + L * Nat.clog 2 (Fintype.card E.I) ≤ h ∧ + ∀ s, L * ∑ i, E.cross s i < n * Fintype.card (Cube n) * h := by + obtain ⟨n, hn, b, C, H, hb, hc, hp⟩ := Spectral.Tensor.cube_packets F L n₀ hL + let z := L * Nat.clog 2 (Fintype.card (Fin C × ↥H)) + 1 + have hz : 0 < z := Nat.zero_lt_succ _ + let edges (s : Fin C × ↥H) (e : Σ j : Cube n × Fin n, Fin (s.2.val j * z)) := e.1 + obtain ⟨E, he, hcost⟩ := expand_packet edges (hp z hz) + refine ⟨n, hn, b * z, E, Nat.mul_pos hb hz, ?_, ?_⟩ + · rw [he] + exact (Nat.le_add_right _ _).trans (Nat.le_mul_of_pos_left z hb) + · intro s + obtain ⟨t, ht⟩ := hcost s + rw [ht, Fintype.card_sigma] + simp only [Fintype.card_fin, ← Finset.sum_mul, ← mul_assoc] + exact Nat.mul_lt_mul_of_pos_right (hc t.2.val t.2.property) hz + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- # Uniform communication plans for exact packet expansions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Spectral +variable {F : Type} [Field F] {n h d r : ℕ} + +theorem exists_first (hn : 2 ≤ n) (c : Fin n → ℕ) : + ∃ i, ∀ j, c i < c j ∨ c i = c j ∧ i ≤ j := by + obtain ⟨i, -, hi⟩ := Finset.exists_min_image Finset.univ (fun j => toLex (c j, j)) + ⟨⟨0, by omega⟩, Finset.mem_univ _⟩ + exact ⟨i, fun j => Prod.Lex.toLex_le_toLex.mp (hi j (Finset.mem_univ _))⟩ + +/-- The value specified by `(exists_first hn c).choose`. -/ +def first (hn : 2 ≤ n) (c : Fin n → ℕ) : Fin n := (exists_first hn c).choose + +theorem first_spec (hn : 2 ≤ n) (c : Fin n → ℕ) (j : Fin n) : + c (first hn c) < c j ∨ c (first hn c) = c j ∧ first hn c ≤ j := + (exists_first hn c).choose_spec j + +/-- Returns `⟨1, by omega⟩` when `i.val = 0` holds, and `⟨0, by omega⟩` otherwise. -/ +def other (hn : 2 ≤ n) (i : Fin n) : Fin n := + if i.val = 0 then ⟨1, by omega⟩ else ⟨0, by omega⟩ + +theorem other_ne (hn : 2 ≤ n) (i : Fin n) : i ≠ other hn i := by + unfold other + split_ifs <;> intro h <;> have := congrArg Fin.val h <;> simp_all + +namespace Expansion + +variable (A : Expansion F n h) + +/-- The plan of type `Plan n r d`, constructed using `first hn (fun j => ∑ p, A.cross (s p) j)`. -/ +def plan (hn : 2 ≤ n) (N : ℕ) (s : Packet n r d → A.I) : Plan n r d := + let i := first hn (fun j => ∑ p, A.cross (s p) j) + let q := fun p => A.cross (s p) i + Nat.clog 2 (Fintype.card A.I) + ⟨i, other hn i, heavy 256 N i q, q⟩ + +/-- Tests whether `¬(A.plan hn N s).marked p` holds. -/ +def splitPacket (hn : 2 ≤ n) (N : ℕ) (s : Packet n r d → A.I) (p : Packet n r d) : Bool := + decide (¬(A.plan hn N s).marked p) + +private theorem plan_bound (hn : 2 ≤ n) (N C L : ℕ) (s : Packet n r d → A.I) + (hN : 0 < N) (hL : 0 < L) (hsave : 32 * 256 ^ 2 * C ^ 2 ≤ L) + (hw : Fintype.card (Position n r d h) ≤ C * r * N) + (hc : ∀ s, L * ∑ i, A.cross s i ≤ n * Fintype.card (Cube n) * h) + (hl : L * Nat.clog 2 (Fintype.card A.I) ≤ h) (u : Worker r) : + 128 * ∑ p, (A.plan hn N s).slotsAt h u p ≤ N := by + let π := A.plan hn N s + obtain ⟨i, hi, hm⟩ := A.coordinate (by omega) L hc hl s + have he : ∑ p, A.cross (s p) π.cut = ∑ p, A.cross (s p) i := by + refine le_antisymm ?_ (hi _) + exact (first_spec hn (fun j => ∑ p, A.cross (s p) j) i).elim + (fun h => h.le) (fun h => h.1.le) + have hb : L * ∑ p, π.q p ≤ 2 * Fintype.card (Position n r d h) := by + change L * (∑ p, (A.cross (s p) π.cut + Nat.clog 2 (Fintype.card A.I))) ≤ _ + rw [Finset.sum_add_distrib, he, ← Finset.sum_add_distrib] + simpa only [Position, Fintype.card_prod, Fintype.card_fin, mul_assoc] using hm + have := π.capacity hN hL hsave hw (other_ne hn π.cut) rfl hb u + change 128 * ∑ p, π.slotsAt h u p ≤ N + omega + +end Expansion + +/-- One exact cube identity works for every problem size and every tuple +of selectors. The packet links consume at most half of each worker's +virtual bit budget, leaving room for the literal pins. -/ +theorem bounded_expansion (F : Type) [Field F] (C : ℕ) : + ∃ n, ∃ hn : 2 ≤ n, ∃ h, ∃ A : Expansion F n h, 0 < h ∧ + ∀ (r d N : ℕ), 0 < N → Fintype.card (Position n r d h) ≤ C * r * N → + ∀ (s : Packet n r d → A.I) (u : Worker r), + 128 * ∑ p, (A.plan hn N s).slotsAt h u p ≤ N := by + let L := 32 * 256 ^ 2 * C ^ 2 + 1 + have hl : 0 < L := Nat.zero_lt_succ _ + obtain ⟨n, hn, h, A, hh, hs, hc⟩ := expansion F L 2 hl + exact ⟨n, hn, h, A, hh, fun _ _ N hN hw s u => + A.plan_bound hn N C L s hN hl (Nat.le_succ _) hw (fun t => (hc t).le) hs u⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- +# A public report for the adaptive plan + +Packets in one class have the same pair of homes and the same packet +worker. Report selector counts by class. A report gives the costs at +all candidate cuts, so one can check the minimizing rule even though +the partition into classes itself depends on the proposed cut. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Finset +variable {F : Type} [Field F] {n h d r : ℕ} + +open Classical in +/-- Indexes the class by the coordinates of `Fin r × Fin r × Fin r`. -/ +abbrev Class (r : ℕ) := Fin r × Fin r × Fin r + +open Classical in +/-- The value specified by `(group p.1 i false, group p.1 i true, group p.1 (other hn i) +false)`. -/ +def packetClass (hn : 2 ≤ n) (i : Fin n) (p : Packet n r d) : Class r := + (group p.1 i false, group p.1 i true, group p.1 (other hn i) false) + +namespace Expansion + +variable (A : Expansion F n h) (hn : 2 ≤ n) + +open Classical in +/-- A class can report at most the total number of packets. -/ +abbrev Report (r d : ℕ) := + Fin n × (Class r × A.I → Fin (Fintype.card (Packet n r d) + 1)) + +open Classical in +/-- Uses `⟨multiplicity (fun p => (packetClass hn i p, s p)) z, Nat.lt_succ_of_le +(Fintype.card_subtype_le _)⟩` as the representation. -/ +def counts (s : Packet n r d → A.I) (i : Fin n) + (z : Class r × A.I) : Fin (Fintype.card (Packet n r d) + 1) := + ⟨multiplicity (fun p => (packetClass hn i p, s p)) z, + Nat.lt_succ_of_le (Fintype.card_subtype_le _)⟩ + +open Classical in +/-- The sum of `(R.2 z).val * f z.1 z.2` indexed by `z`. -/ +def total (R : A.Report r d) (f : Class r → A.I → ℕ) := + ∑ z, (R.2 z).val * f z.1 z.2 + +open Classical in +theorem total_counts (s : Packet n r d → A.I) (i : Fin n) (f : Class r → A.I → ℕ) : + A.total (i, A.counts hn s i) f = ∑ p, f (packetClass hn i p) (s p) := by + simp only [total, counts, multiplicity, Fintype.card_subtype] + have he (p : Packet n r d → Prop) [DecidablePred p] : (univ.filter p).card = ∑ i, + if p i then 1 else 0 := by + simp + simp_rw [he, sum_mul, ite_mul, one_mul, zero_mul] + rw [sum_comm] + simp only [sum_ite_eq, mem_univ, ite_true] + +open Classical in +/-- The report of type `A.Report r d`, constructed using `first hn (fun j => ∑ p, A.cross (s p) +j)`. -/ +def report (s : Packet n r d → A.I) : A.Report r d := + let i := first hn (fun j => ∑ p, A.cross (s p) j) + (i, A.counts hn s i) + +open Classical in +/-- Requires `R.1 = first hn (fun j => A.total R (fun _ t => A.cross t j)) ∧ ∀ c, R.2 c = +A.counts hn s R.1 c`. -/ +def checks (R : A.Report r d) (s : Packet n r d → A.I) : Prop := + R.1 = first hn (fun j => A.total R (fun _ t => A.cross t j)) ∧ + ∀ c, R.2 c = A.counts hn s R.1 c + +open Classical in +/-- Every selector assignment has exactly one valid report. -/ +theorem checks_iff (R : A.Report r d) (s : Packet n r d → A.I) : + A.checks hn R s ↔ R = A.report hn s := by + constructor + · rcases R with ⟨i, N⟩ + rintro ⟨hi, hs⟩ + have he : N = A.counts hn s i := funext hs + subst N + simp only [total_counts] at hi + exact congrArg (fun i => (i, A.counts hn s i)) hi + · rintro rfl + unfold checks report + simp only [total_counts, implies_true, and_self] + +open Classical in +/-- The report groups of type `Finset (Fin r)`, constructed using `A.cross t R.1 + Nat.clog 2 +(Fintype.card A.I)`. -/ +def reportGroups (N : ℕ) (R : A.Report r d) : Finset (Fin r) := + univ.filter (fun g => N < 256 * A.total R (fun c t => + let w := A.cross t R.1 + Nat.clog 2 (Fintype.card A.I) + (if c.1 = g then w else 0) + (if c.2.1 = g then w else 0))) + +open Classical in +theorem report_groups (N : ℕ) (s : Packet n r d → A.I) : + A.reportGroups N (A.report hn s) = (A.plan hn N s).groups := by + simp only [reportGroups, report, total_counts, packetClass, plan, heavy, charge] + rfl + +open Classical in +/-- The public report has polynomially many count fields, each of +logarithmic bit length, at fixed cube and coefficient field. -/ +theorem report_size : + Fintype.card (A.Report r d) ≤ + 2 ^ (Nat.clog 2 n + r ^ 3 * Fintype.card A.I * Nat.clog 2 (Fintype.card (Packet n r d) + 1)) + := by + change Fintype.card (Fin n × (Class r × A.I → Fin (Fintype.card (Packet n r d) + 1))) ≤ _ + rw [Fintype.card_prod, Fintype.card_fin, Fintype.card_fun, Fintype.card_fin, + Fintype.card_prod (Class r) A.I] + have he : Fintype.card (Class r) = r ^ 3 := by simp [Class]; ring + rw [he, pow_add, mul_comm (r ^ 3 * Fintype.card A.I), pow_mul (2 : ℕ)] + exact Nat.mul_le_mul (Nat.le_pow_clog (by decide : 1 < 2) n) + (Nat.pow_le_pow_left (Nat.le_pow_clog (by decide : 1 < 2) _) _) + +end Expansion +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- +# Encoding the choices of one packet class + +Once the report is fixed the total crossing width is independent of the +assignment of selectors in a class. The selectors and their crossing +bits therefore fit in a single bit string of the reported length. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Finset +variable {F : Type} [Field F] {n h d r : ℕ} (A : Expansion F n h) + +open Classical in +/-- The subtype of `p : Packet n r d` satisfying `packetClass hn R.1 p = c`. -/ +abbrev Members (hn : 2 ≤ n) (R : A.Report r d) (c : Class r) := + {p : Packet n r d // packetClass hn R.1 p = c} + +open Classical in +/-- The subtype of `s : A.Members hn R c → A.I` satisfying `∀ z, multiplicity s z = (R.2 (c, +z)).val`. -/ +abbrev Selectors (hn : 2 ≤ n) (R : A.Report r d) (c : Class r) := + {s : A.Members hn R c → A.I // ∀ z, multiplicity s z = (R.2 (c, z)).val} + +open Classical in +/-- Tests whether `c.1 ∉ A.reportGroups N R ∧ c.2.1 ∉ A.reportGroups N R` holds. -/ +def shared (N : ℕ) (R : A.Report r d) (c : Class r) : Bool := + decide (c.1 ∉ A.reportGroups N R ∧ c.2.1 ∉ A.reportGroups N R) + +open Classical in +/-- Indexes the alphabet by the coordinates of `Σ s : A.Selectors hn R c, A.Wires s.val R.1 (fun +_ => A.shared N R c)`. -/ +abbrev Alphabet (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) (c : Class r) := + Σ s : A.Selectors hn R c, A.Wires s.val R.1 (fun _ => A.shared N R c) + +open Classical in +/-- The quantity computed by `∑ z, (R.2 (c, z)).val * (A.cross z R.1 + Nat.clog 2 (Fintype.card +A.I))`. -/ +def classWidth (R : A.Report r d) (c : Class r) := + ∑ z, (R.2 (c, z)).val * (A.cross z R.1 + Nat.clog 2 (Fintype.card A.I)) + +variable {hn : 2 ≤ n} {R : A.Report r d} {c : Class r} + +open Classical in +instance selectorFintype : Fintype (A.Selectors hn R c) := by + unfold Selectors + infer_instance + +open Classical in +instance wiresFintype {N : ℕ} (s : A.Selectors hn R c) : + Fintype (A.Wires s.val R.1 (fun _ => A.shared N R c)) := by + unfold Wires + infer_instance + +open Classical in +instance alphabetFintype {N : ℕ} : Fintype (A.Alphabet hn N R c) := by + unfold Alphabet + infer_instance + +open Classical in +theorem classWidth_spec (s : A.Selectors hn R c) : + A.classWidth R c = ∑ p, (A.cross (s.val p) R.1 + Nat.clog 2 (Fintype.card A.I)) := by + unfold classWidth + simp_rw [← s.property, multiplicity, Fintype.card_subtype] + have he (p : A.Members hn R c → Prop) [DecidablePred p] : + (univ.filter p).card = ∑ i, if p i then 1 else 0 := by + simp + simp_rw [he, sum_mul, ite_mul, one_mul, zero_mul] + rw [sum_comm] + simp only [sum_ite_eq, mem_univ, ite_true] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +/- # Packing one selector class in packet order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +open Finset + +section Pack +variable {P : Type} [LinearOrder P] [Fintype P] (f : P → ℕ) + +open Classical in +/-- Computes the pack order by the application `Fintype.orderIsoFinOfCardEq _ (by simp)`. -/ +def packOrder : Fin (∑ p, f p) ≃o Lex (Σ p, Fin (f p)) := + Fintype.orderIsoFinOfCardEq _ (by simp) + +variable {l : ℕ} (hl : ∑ p, f p ≤ l) + +open Classical in +/-- Concatenate blocks in packet order, padding with zero when necessary. -/ +def pack : ((p : P) → Fin (f p) → Bool) ↪ (Fin l → Bool) := by + let e := (packOrder f).symm.toEquiv.toEmbedding.trans (Fin.castLEEmb hl) + refine ⟨fun x => Function.extend e (fun z => x z.1 z.2) (fun _ => false), ?_⟩ + intro x y he + funext p i + have hh := congrFun he (e ⟨p, i⟩) + exact ((e.injective.extend_apply (fun z => x z.1 z.2) _ ⟨p, i⟩).symm.trans hh).trans + (e.injective.extend_apply (fun z => y z.1 z.2) _ ⟨p, i⟩) + +open Classical in +theorem pack_at (x : (p : P) → Fin (f p) → Bool) (z : Lex (Σ p, Fin (f p))) : + pack f hl x (Fin.castLE hl ((packOrder f).symm z)) = x z.1 z.2 := by + let e := (packOrder f).symm.toEquiv.toEmbedding.trans (Fin.castLEEmb hl) + exact e.injective.extend_apply (fun y => x y.1 y.2) (fun _ => false) z + +end Pack + +variable {F : Type} [Field F] {n h d r : ℕ} (A : Expansion F n h) + +open Classical in +/-- Embeds `A.I` into `(Fin (Nat.clog 2 (Fintype.card A.I)) → Bool)`. -/ +def selectorCode : A.I ↪ (Fin (Nat.clog 2 (Fintype.card A.I)) → Bool) := + Classical.choice (Function.Embedding.nonempty_of_card_le + (by simpa using Nat.le_pow_clog (by decide : 1 < 2) (Fintype.card A.I))) + +variable (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) (c : Class r) + +open Classical in +/-- The member order of type `LinearOrder (A.Members hn R c)` for the given inputs. -/ +@[instance_reducible] def memberOrder : LinearOrder (A.Members hn R c) := by + letI : LinearOrder (Packet n r d) := + inferInstanceAs (LinearOrder (Lex (Lex (Lex (Label n r) × Lex (Label n r)) × Fin d))) + exact LinearOrder.lift' Subtype.val Subtype.val_injective + +attribute [local instance] memberOrder + +open Classical in +/-- The sum of `Nat.clog 2 (Fintype.card A.I)` indexed by `_ : A.Members hn R c`. -/ +def selectorWidth := ∑ _ : A.Members hn R c, Nat.clog 2 (Fintype.card A.I) + +variable {hn R c} + +open Classical in +theorem classWidth_split (s : A.Selectors hn R c) : + A.classWidth R c = A.selectorWidth hn R c + ∑ p, A.cross (s.val p) R.1 := by + rw [A.classWidth_spec s, sum_add_distrib, add_comm] + rfl + +open Classical in +theorem tail_bound (s : A.Selectors hn R c) : + ∑ p, A.width (s.val p) R.1 (A.shared N R c) ≤ A.classWidth R c - A.selectorWidth hn R c := by + rw [A.classWidth_split s, Nat.add_sub_cancel_left] + apply sum_le_sum + intro p _ + unfold width + split_ifs <;> omega + +open Classical in +/-- The indexed operation `pack (fun _ : A.Members hn R c => Nat.clog 2 (Fintype.card A.I)) +le_rfl (fun p => A.selectorCode (s.val p))`. -/ +def selectorPrefix (s : A.Selectors hn R c) : Fin (A.selectorWidth hn R c) → Bool := + pack (fun _ : A.Members hn R c => Nat.clog 2 (Fintype.card A.I)) le_rfl + (fun p => A.selectorCode (s.val p)) + +open Classical in +/-- Computes the crossing suffix by the application `pack _ (A.tail_bound N z.1) z.2`. -/ +def crossingSuffix (z : A.Alphabet hn N R c) : Fin (A.classWidth R c - A.selectorWidth hn R c) → + Bool := + pack _ (A.tail_bound N z.1) z.2 + +open Classical in +/-- Reindexes `Fin (A.classWidth R c)` and `Fin (A.selectorWidth hn R c + (A.classWidth R c - +A.selectorWidth hn R c))` by an equivalence. -/ +def codeSplit (s : A.Selectors hn R c) : + Fin (A.classWidth R c) ≃ Fin (A.selectorWidth hn R c + + (A.classWidth R c - A.selectorWidth hn R c)) := + finCongr (by have := A.classWidth_split s; omega) + +open Classical in +/-- The fixed prefix determines the lengths of the crossing blocks. -/ +def alphabetCode (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) (c : Class r) : + A.Alphabet hn N R c ↪ (Fin (A.classWidth R c) → Bool) where + toFun z i := Fin.append (A.selectorPrefix z.1) (A.crossingSuffix N z) (A.codeSplit z.1 i) + inj' := by + rintro ⟨s, x⟩ ⟨s', y⟩ he + have he' (i) : + Fin.append (A.selectorPrefix s) (A.crossingSuffix N ⟨s, x⟩) i = + Fin.append (A.selectorPrefix s') (A.crossingSuffix N ⟨s', y⟩) i := by + have hi : A.codeSplit s' = A.codeSplit s := rfl + simpa only [hi, Equiv.apply_symm_apply] using congrFun he ((A.codeSplit s).symm i) + have hs : A.selectorPrefix s = A.selectorPrefix s' := funext fun i => by + simpa only [Fin.append_left] using he' (Fin.castAdd _ i) + unfold selectorPrefix at hs + have hs' := (pack _ le_rfl).injective hs + have : s = s' := Subtype.ext (funext fun p => A.selectorCode.injective (congrFun hs' p)) + subst s' + have ht : A.crossingSuffix N ⟨s, x⟩ = A.crossingSuffix N ⟨s, y⟩ := funext fun i => by + simpa only [Fin.append_right] using he' (Fin.natAdd _ i) + have : x = y := (pack _ (A.tail_bound N s)).injective ht + rw [this] + +open Classical in +theorem alphabetCode_eq (z : A.Alphabet hn N R c) : + A.alphabetCode hn N R c z = + Fin.append (A.selectorPrefix z.1) (A.crossingSuffix N z) ∘ A.codeSplit z.1 := rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Bounds.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Bounds.lean new file mode 100644 index 0000000000..cee81c81a3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Bounds.lean @@ -0,0 +1,46 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Hard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Defs + +/-! # The two size estimates in the tagged-permutation argument -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal +open Filter + +/-- At every large scale and every fixed linear cost, some cheaply +realizable tensor resists simultaneous implementation for all small +powers. The permitted high-arity tables are specified by `L`. -/ +def Resists (F : Type) [Field F] (L : Set (Table F)) : Prop := + ∀ C : ℕ, 4 ≤ C → ∃ k : ℕ, ∃ δ : ℝ, 0 < δ ∧ ∀ᶠ w : ℕ in atTop, + let N : ℕ := 2 ^ w + ∃ (a : Wire) (U : Val a → Val .unit → F) (v : ℕ), + wd a ≤ N ∧ Net F a .unit U v ∧ v ≤ N * w ^ k ∧ + ∀ d D m : ℕ, 1 ≤ d → (d : ℝ) ≤ (N : ℝ) ^ δ → D ^ 2 ≤ N → + Wide F D L (copies a d) (copies .unit d) (power U d) m → C * N * d < m + +/-- A uniform descent step along the exceptional lengths. The first +version pays a small power of the logarithm in exterior cost. The +second version allows special tables and pays constant exterior cost. -/ +def Descent (F : Type) [Field F] (L : Set (Table F)) : Prop := + ¬Tagged.Hard F → ∃ C : ℕ, 4 ≤ C ∧ ∃ α : ℝ, 0 < α ∧ ∀ κ : ℝ, 0 < κ → + ∃ᶠ w : ℕ in atTop, + let N : ℕ := 2 ^ w + ∀ (a b : Wire) (U : Val a → Val b → F) (v M : ℕ), + Net F a b U v → v + wd a + wd b ≤ M → N ≤ M → + (M : ℝ) ≤ (N : ℝ) ^ (21 / 20 : ℝ) → + (∃ d m : ℕ, 1 ≤ d ∧ (d : ℝ) ≤ (N : ℝ) ^ κ ∧ PowerSize U d m ∧ + (m : ℝ) ≤ d * ((M : ℝ) * (w : ℝ) ^ (-α) + (wd a + wd b : ℕ) * (w : ℝ) ^ (α / 4))) ∧ + (∃ d D m : ℕ, 1 ≤ d ∧ (d : ℝ) ≤ (N : ℝ) ^ κ ∧ D ^ 2 ≤ N ∧ + Wide F D L (copies a d) (copies b d) (power U d) m ∧ + (m : ℝ) ≤ C * d * ((M : ℝ) * (w : ℝ) ^ (-α) + (wd a + wd b : ℕ))) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Broadcast.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Broadcast.lean new file mode 100644 index 0000000000..6ffd79b191 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Broadcast.lean @@ -0,0 +1,896 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Data.Nat.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Replay +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.TemplateSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Fixing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Bounds +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Input +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Present +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Reduction + +/-! # Choosing processor, batch, and broadcast lengths -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Filter + +/-- Simultaneous bounds for the cube layout, packet budget, and processor tape. -/ +structure Scales (C k h I N r l b d D B : ℕ) : Prop where + pos : 0 < r + labels : r ^ k ≤ l + tape : l + b + N / 4 ≤ N + literal : 1024 * l ≤ N + links : 64 * (3 * r) ^ 2 ≤ N + cover : 3 * r ≤ B * d + copies : B * d ≤ 4 * r + degree : (D + 1) * (r ^ k) ^ 4 ≤ C * N * d + padding : (r ^ k) ^ 2 * 2 ^ k * h ≤ C * N * d + broadcast : Nat.clog 2 k + r ^ 3 * I * Nat.clog 2 (52 * C * N * r + 1) + 1 ≤ b + +private theorem batch_size (d r : ℕ) (hd : 1 ≤ d) (hr : d ^ 2 ≤ r) : + 3 * r ≤ ((3 * r + d - 1) / d) * d ∧ ((3 * r + d - 1) / d) * d ≤ 4 * r := by + have := (Nat.le_pow (by decide : 0 < 2)).trans hr + have hm := Nat.mod_lt (3 * r + d - 1) hd + have he := Nat.mod_add_div (3 * r + d - 1) d + rw [Nat.mul_comm d] at he + omega + +private theorem scale_bounds {C k h I N r d D : ℕ} (hc : 4 ≤ C) (hk : 2 ≤ k) + (hr : 6144 ≤ r) (hp : r ^ (8 * k) ≤ N) (hpad : 2 ^ k * h ≤ r) + (hi : I ≤ r) (hk' : Nat.clog 2 k ≤ r) (hrep : Nat.clog 2 (52 * C * N * r + 1) ≤ r) + (hd : 1 ≤ d) (hd' : d ^ 2 ≤ r) (hD : D ^ 2 ≤ N) : + Scales C k h I N r (N / 2048) (N / 2048) d D ((3 * r + d - 1) / d) := by + have pow_bound (j : ℕ) (hj : j ≤ 8 * k) : r ^ j ≤ N := + (Nat.pow_le_pow_right (by omega) hj).trans hp + have hCN : 2 * N ≤ C * N * d := by + exact (Nat.mul_le_mul_right N (by omega : 2 ≤ C)).trans (Nat.le_mul_of_pos_right _ hd) + obtain ⟨hlo, hhi⟩ := batch_size d r hd hd' + refine ⟨by omega, ?_, by omega, by omega, ?_, hlo, hhi, ?_, ?_, ?_⟩ + · apply (Nat.le_div_iff_mul_le (by decide)).mpr + calc + _ ≤ r ^ k * r := Nat.mul_le_mul_left _ (by omega) + _ ≤ N := by rw [← pow_succ]; exact pow_bound _ (by omega) + · calc + _ = r ^ 2 * 576 := by ring + _ ≤ r ^ 2 * r := Nat.mul_le_mul_left _ (by omega) + _ ≤ N := pow_bound 3 (by omega) + · let p := (r ^ k) ^ 4 + have hs : p ^ 2 ≤ N := by + unfold p + rw [← pow_mul, ← pow_mul] + exact pow_bound _ (by omega) + have hv : D * p ≤ N := by + rcases le_total D p with h | h + · exact (Nat.mul_le_mul_right p h).trans (by rwa [pow_two] at hs) + · exact (Nat.mul_le_mul_left D h).trans (by rwa [pow_two] at hD) + change (D + 1) * p ≤ _ + rw [Nat.add_mul, one_mul] + have := (Nat.le_pow (by decide : 0 < 2)).trans hs + omega + · calc + _ ≤ (r ^ k) ^ 2 * r := by rw [mul_assoc]; exact Nat.mul_le_mul_left _ hpad + _ ≤ N := by rw [← pow_mul, ← pow_succ]; exact pow_bound _ (by omega) + _ ≤ C * N * d := by omega + · have hfive : r ≤ r ^ 5 := Nat.le_pow (by decide) + have hb : Nat.clog 2 k + r ^ 3 * I * Nat.clog 2 (52 * C * N * r + 1) + 1 ≤ 3 * r ^ 5 := by + have : r ^ 3 * I * Nat.clog 2 (52 * C * N * r + 1) ≤ r ^ 5 := + Nat.mul_le_mul (Nat.mul_le_mul_left _ hi) hrep + omega + apply (Nat.le_div_iff_mul_le (by decide)).mpr + calc + _ ≤ (3 * r ^ 5) * 2048 := Nat.mul_le_mul_right _ hb + _ = r ^ 5 * 6144 := by ring + _ ≤ r ^ 5 * r := Nat.mul_le_mul_left _ hr + _ ≤ N := pow_bound 6 (by omega) + +private theorem square_exp (m : ℕ) (hm : 4 ≤ m) : m ^ 2 ≤ 2 ^ m := by + induction m, hm using Nat.le_induction with + | base => decide + | succ m hm ih => rw [pow_succ 2]; nlinarith + +private theorem small_batch {d w K m : ℕ} (hk : 0 < K) (hw : w ≤ 2 * K * m) + (hd : (d : ℝ) ≤ ((2 : ℝ) ^ w) ^ (1 / (4 * (K : ℝ)))) : d ^ 2 ≤ 2 ^ m := by + have hk' : 0 < (K : ℝ) := by exact_mod_cast hk + have he : (w : ℝ) * (1 / (4 * (K : ℝ))) * 2 ≤ (m : ℝ) := by + rw [show (w : ℝ) * (1 / (4 * (K : ℝ))) * 2 = w / (2 * (K : ℝ)) by ring, + div_le_iff₀ (by positivity)] + rw [mul_comm] + exact_mod_cast hw + have h : (d : ℝ) ^ 2 ≤ (2 : ℝ) ^ m := calc + _ ≤ (((2 : ℝ) ^ w) ^ (1 / (4 * (K : ℝ)))) ^ 2 := by gcongr + _ = (2 : ℝ) ^ ((w : ℝ) * (1 / (4 * (K : ℝ))) * 2) := by + rw [← Real.rpow_natCast_mul (by positivity), ← Real.rpow_mul_natCast (by positivity)] + rfl + _ ≤ _ := by rw [← Real.rpow_natCast]; exact Real.rpow_le_rpow_of_exponent_le (by norm_num) he + exact_mod_cast h + +/-- Choose the sizes before the batch and degree are known. A fixed +positive exponent suffices for the batch hypothesis. -/ +theorem scales (C k h I : ℕ) (hc : 4 ≤ C) (hk : 2 ≤ k) : + ∃ δ : ℝ, 0 < δ ∧ ∀ᶠ w : ℕ in atTop, + let N : ℕ := 2 ^ w + let r := 2 ^ (w / (16 * k)) + let l := N / 2048 + (∀ d : ℕ, (d : ℝ) ≤ (N : ℝ) ^ δ → d ^ 2 ≤ r) ∧ + (∀ d D : ℕ, 1 ≤ d → d ^ 2 ≤ r → D ^ 2 ≤ N → + Scales C k h I N r l l d D ((3 * r + d - 1) / d)) := by + let K := 16 * k + have hK : 0 < K := by omega + let T := 6144 + 2 ^ k * h + I + Nat.clog 2 k + 52 * C + 6 * K + refine ⟨1 / (4 * (K : ℝ)), by positivity, ?_⟩ + filter_upwards [eventually_ge_atTop (T * K)] with w hw + intro N r l + let m := w / K + have hm : T ≤ m := (Nat.le_div_iff_mul_le hK).mpr hw + have hm' : 4 ≤ m := by omega + have hw' : w ≤ 2 * K * m := by + have he := Nat.mod_add_div w K + have hd := Nat.mod_lt w hK + change w % K + K * m = w at he + have := Nat.le_mul_of_pos_right K (by omega : 0 < m) + rw [mul_assoc] + omega + constructor + · intro d hd + apply small_batch hK hw' + simpa only [N, Nat.cast_pow, Nat.cast_ofNat] using hd + · have hr : m ^ 2 ≤ r := square_exp m hm' + have hmr := (Nat.le_pow (by decide : 0 < 2)).trans hr + have hp : r ^ (8 * k) ≤ N := by + change (2 ^ m) ^ (8 * k) ≤ 2 ^ w + rw [← pow_mul] + exact Nat.pow_le_pow_right (by decide) + ((Nat.mul_le_mul_left m (by omega : 8 * k ≤ K)).trans (Nat.div_mul_le_self w K)) + have hrN := (Nat.le_pow (by omega : 0 < 8 * k)).trans hp + have hw3 : 3 * w ≤ r := calc + _ ≤ 3 * (2 * K * m) := Nat.mul_le_mul_left _ hw' + _ = (6 * K) * m := by ring + _ ≤ m * m := Nat.mul_le_mul_right m (by omega) + _ ≤ _ := by rwa [← pow_two] + have hrep : Nat.clog 2 (52 * C * N * r + 1) ≤ 3 * w := by + apply Nat.clog_le_of_le_pow + rw [mul_comm 3, pow_mul] + change _ ≤ N ^ 3 + have hz : 1 ≤ N * r := Nat.mul_pos (by omega) (by omega) + calc + _ ≤ 52 * C * N * r + N * r := Nat.add_le_add_left hz _ + _ = (52 * C + 1) * N * r := by ring + _ ≤ N * N * N := by gcongr; omega + _ = _ := by ring + intro d D hd hd' hD + exact scale_bounds hc hk (by omega) hp (by omega) (by omega) (by omega) + (hrep.trans hw3) hd hd' hD + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- # Balanced exterior labels shared across all copies -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +variable {N l b r n : ℕ} + +/-- Balance literals separately so that rerouting them has a small cost +even on a tape dominated by communication bits. -/ +theorem exterior (hr : 0 < r) (hl : r ^ n ≤ l) (hs : l + b + N / 4 ≤ N) : + ∃ fa : Machine.Ports N l b → Label n r, + (∀ g, multiplicity fa g * r ^ n ≤ 4 * N) ∧ + (∀ i g, multiplicity (fun t : Fin l => fa (.inl t) i) g * r ≤ 2 * l) := by + have : Nonempty (Fin r) := ⟨⟨0, hr⟩⟩ + have bal (k : ℕ) : ∃ f : Fin k → Label n r, ∀ z, multiplicity f z * r ^ n ≤ k + r ^ n := by + simpa [Label] using (even_labels (A := Fin k) (Z := Label n r)) + obtain ⟨x, hx⟩ := bal l + obtain ⟨y, hy⟩ := bal b + obtain ⟨z, hz⟩ := bal (N / 4) + refine ⟨Sum.elim x (Sum.elim y z), ?_, fun i g => (project_bound x hx i g).trans (by omega)⟩ + intro g + rw [multiplicity_elim, multiplicity_elim, add_mul, add_mul] + have := hx g + have := hy g + have := hz g + omega + +theorem exterior_copies (fa : Machine.Ports N l b → Label n r) + (hfa : ∀ g, multiplicity fa g * r ^ n ≤ 4 * N) (d : ℕ) (g : Label n r) : + multiplicity (fun s : slots (copies (Machine.tape N l b) d) => + fa (Machine.address N l b (port (Machine.tape N l b) d s).2)) g * r ^ n ≤ 4 * N * d := by + let e := (port (Machine.tape N l b) d).trans + ((Equiv.refl _).prodCongr (Machine.address N l b)) + have he : multiplicity (fun s => fa (e s).2) g ≤ d * multiplicity fa g := by + let f : {s // fa (e s).2 = g} → Fin d × {p // fa p = g} := + fun s => ((e s.1).1, ⟨(e s.1).2, s.2⟩) + have hf : Function.Injective f := by + intro x y h + apply Subtype.ext + apply e.injective + exact congrArg (fun p => (p.1, p.2.1)) h + simpa only [multiplicity, Fintype.card_prod, Fintype.card_fin] using + Fintype.card_le_of_injective f hf + calc + _ ≤ d * multiplicity fa g * r ^ n := Nat.mul_le_mul_right _ he + _ ≤ 4 * N * d := by rw [mul_assoc, mul_comm d]; exact Nat.mul_le_mul_right _ (hfa g) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- +# Communication budget for literal pins + +Each worker sends at most one copy of its own literal string. For +incoming literals a single label coordinate bounds the number of +relevant positions, shared across all processors. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +variable {F : Type} [Field F] {n h d r N l b : ℕ} + (A : Expansion F n h) (hn : 2 ≤ n) (R : A.Report r d) + +theorem Expansion.owner_coordinate (u : Worker r) : + ∃ (i : Fin n) (g : Fin r), ∀ z, A.owner hn N R z = u → z i = g := by + cases u with + | home g => + refine ⟨R.1, g, ?_⟩ + intro z h + unfold Expansion.owner at h + split_ifs at h + exact Worker.home.inj h + | station g => + refine ⟨other hn R.1, g, ?_⟩ + intro z h + unfold Expansion.owner at h + split_ifs at h + exact Worker.station.inj h + | packet g => + refine ⟨R.1, g, ?_⟩ + intro z h + unfold Expansion.owner at h + split_ifs at h + +theorem Pin.budget (fa : Machine.Ports N l b → Label n r) + (hf : ∀ i g, multiplicity (fun t : Fin l => fa (.inl t) i) g * r ≤ 2 * l) + (hl : 1024 * l ≤ N) (u : Worker r) : + let f := A.owner hn N R ∘ fa + 128 * Fintype.card {e : Pin N l b r // + Pin.src f e ≠ Pin.dst f e ∧ (Pin.src f e = u ∨ Pin.dst f e = u)} ≤ N := by + classical + intro f + obtain ⟨i, g, hg⟩ := A.owner_coordinate (N := N) hn R u + let E := {e : Pin N l b r // Pin.src f e ≠ Pin.dst f e ∧ (Pin.src f e = u ∨ Pin.dst f e = u)} + let T := Fin l ⊕ (Fin (3 * r) × {t : Fin l // fa (.inl t) i = g}) + let pin : T → Pin N l b r := + Sum.elim (fun t => .inl (Worker.index r u, t)) (fun x => .inl (x.1, x.2.val)) + have cover (e : E) : ∃ t, pin t = e.val := by + rcases e with ⟨⟨v, t⟩|e, hn', he⟩ + · rcases he with h | h + · exact ⟨.inl t, by simp [pin, ← h, Pin.src]⟩ + · exact ⟨.inr (v, ⟨t, hg _ h⟩), rfl⟩ + · exact (hn' rfl).elim + choose pick hp using cover + have hi : Function.Injective pick := + fun x y h => Subtype.ext ((hp x).symm.trans ((congrArg pin h).trans (hp y))) + have he := Fintype.card_le_of_injective pick hi + have hT : Fintype.card T ≤ 7 * l := by + simp only [T, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + have hh : Fintype.card {t : Fin l // fa (.inl t) i = g} * r ≤ 2 * l := hf i g + rw [mul_assoc, mul_comm r] + omega + change 128 * Fintype.card E ≤ N + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- +# Encoding the public report + +The first bit distinguishes an ordinary report from the extra branch. +A binary cut index and fixed-width binary counts follow, in lexicographic +class order. All unused bits are zero. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +/-- Embeds `Fin n` into `(Fin (Nat.clog 2 n) → Bool) where toFun`. -/ +def binary (n : ℕ) : Fin n ↪ (Fin (Nat.clog 2 n) → Bool) where + toFun := fun x i => x.val.testBit i + inj' := by + intro x y h + apply Fin.ext + apply Nat.eq_of_testBit_eq + intro i + by_cases hi : i < Nat.clog 2 n + · exact congrFun h ⟨i, hi⟩ + · have hm : n ≤ 2 ^ i := (Nat.le_pow_clog (by decide : 1 < 2) n).trans + (Nat.pow_le_pow_right (by decide) (le_of_not_gt hi)) + rw [Nat.testBit_lt_two_pow (x.isLt.trans_le hm), Nat.testBit_lt_two_pow (y.isLt.trans_le hm)] + +variable {F : Type} [Field F] {n h : ℕ} (A : Expansion F n h) + (hn : 2 ≤ n) (N r d : ℕ) + +/-- Counts the elements of `(Packet n r d) + 1`. -/ +abbrev Count (n r d : ℕ) := Fintype.card (Packet n r d) + 1 + +/-- Indexes the count bit by the coordinates of `(Class r × A.I) × Fin (Nat.clog 2 (Fintype.card +(Packet n r d) + 1))`. -/ +abbrev CountBit := (Class r × A.I) × Fin (Nat.clog 2 (Fintype.card (Packet n r d) + 1)) + +/-- The value specified by `(R.2 j.1).val.testBit j.2.val`. -/ +def countBits {r d : ℕ} (R : A.Report r d) (j : A.CountBit r d) : Bool := + (R.2 j.1).val.testBit j.2.val + +/-- Indexes the cell by the coordinates of `Unit ⊕ Fin (Nat.clog 2 n) ⊕ A.CountBit r d`. -/ +abbrev Cell := Unit ⊕ Fin (Nat.clog 2 n) ⊕ A.CountBit r d + +/-- In the case `none, _`, this construction gives `false`. -/ +def fields : Option (A.Accepted (r := r) (d := d) hn (A.budget hn N)) → A.Cell r d → Bool + | none, _ => false + | some _, .inl _ => true + | some R, .inr (.inl i) => binary n R.1.1 i + | some R, .inr (.inr (z, i)) => binary (Count n r d) (R.1.2 z) i + +theorem fields_injective : Function.Injective (A.fields hn N r d) := by + intro x y he + have hf := congrFun he (.inl ()) + cases x <;> cases y + · rfl + · exact (Bool.false_ne_true hf).elim + · exact (Bool.false_ne_true hf.symm).elim + · apply congrArg some + apply Subtype.ext + apply Prod.ext + · exact (binary n).injective (funext fun i => congrFun he (.inr (.inl i))) + · funext z + exact (binary (Count n r d)).injective (funext fun i => congrFun he (.inr (.inr (z, i)))) + +variable (b : ℕ) + (hb : Nat.clog 2 n + r ^ 3 * Fintype.card A.I * + Nat.clog 2 (Fintype.card (Packet n r d) + 1) + 1 ≤ b) + +/-- Embeds `A.Cell r d` into `Fin b`. -/ +def reportPort : A.Cell r d ↪ Fin b := by + let e := Fintype.equivFin A.I + letI : LinearOrder A.I := LinearOrder.lift' e e.injective + let Z := Lex (Lex (Fin r × Lex (Fin r × Fin r)) × A.I) + letI : LinearOrder (A.Cell r d) := inferInstanceAs + (LinearOrder (Lex (Unit ⊕ Lex (Fin (Nat.clog 2 n) ⊕ Lex (Z × Fin (Nat.clog 2 (Count n r d))))))) + have hc : Fintype.card (A.Cell r d) ≤ b := by + have hr : Fintype.card (Class r) = r ^ 3 := by simp [Class]; ring + rw [Fintype.card_sum, Fintype.card_sum, Fintype.card_prod, Fintype.card_prod, hr] + simp only [Fintype.card_unit, Fintype.card_fin] + omega + exact (Fintype.orderIsoFinOfCardEq (A.Cell r d) rfl).toEquiv.symm.toEmbedding.trans + (Fin.castLEEmb hc) + +/-- Reports and the extra branch have disjoint broadcast strings. -/ +def encodeReport : Option (A.Accepted (r := r) (d := d) hn (A.budget hn N)) ↪ (Fin b → Bool) := by + let idx := A.reportPort r d b hb + refine ⟨fun R => Function.extend idx (A.fields hn N r d R) (fun _ => false), ?_⟩ + intro R R' he + apply A.fields_injective hn N r d + funext i + exact ((idx.injective.extend_apply _ _ i).symm.trans (congrFun he (idx i))).trans + (idx.injective.extend_apply _ _ i) + +private theorem encodeReport_at (R) (i : A.Cell r d) : + A.encodeReport hn N r d b hb R (A.reportPort r d b hb i) = A.fields hn N r d R i := + (A.reportPort r d b hb).injective.extend_apply (A.fields hn N r d R) (fun _ => false) i + +theorem encodeReport_pad (R) (i : Fin b) (hi : i ∉ Set.range (A.reportPort r d b hb)) : + A.encodeReport hn N r d b hb R i = false := + Function.extend_apply' (A.fields hn N r d R) (fun _ => false) i hi + +@[simp] theorem encodeReport_none (i : Fin b) : A.encodeReport hn N r d b hb none i = false := by + by_cases hi : i ∈ Set.range (A.reportPort r d b hb) + · obtain ⟨j, rfl⟩ := hi + exact A.encodeReport_at hn N r d b hb none j + · exact A.encodeReport_pad hn N r d b hb none i hi + +variable (R : A.Accepted (r := r) (d := d) hn (A.budget hn N)) + +@[simp] theorem encodeReport_flag : + A.encodeReport hn N r d b hb (some R) (A.reportPort r d b hb (.inl ())) = true := + A.encodeReport_at hn N r d b hb (some R) (.inl ()) + +@[simp] theorem encodeReport_cut (i : Fin (Nat.clog 2 n)) : + A.encodeReport hn N r d b hb (some R) (A.reportPort r d b hb (.inr (.inl i))) = + R.val.1.val.testBit i.val := + A.encodeReport_at hn N r d b hb (some R) (.inr (.inl i)) + +@[simp] theorem encodeReport_count (j : A.CountBit r d) : + A.encodeReport hn N r d b hb (some R) (A.reportPort r d b hb (.inr (.inr j))) = + A.countBits R.val j := + A.encodeReport_at hn N r d b hb (some R) (.inr (.inr j)) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Scheme + +variable {F : Type} [Field F] {N l b n h d B r : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {G : MachineDiagram F N l b d} + (S : Scheme A hn G r B) + +/-- Specialize the public encoding to the batch dimensions of this scheme. -/ +abbrev encodeReport + (hb : Nat.clog 2 n + r ^ 3 * Fintype.card A.I * + Nat.clog 2 (Fintype.card (Packet n r (B * S.layout.d)) + 1) + 1 ≤ b) : + Option S.Report ↪ (Fin b → Bool) := + A.encodeReport hn N r (B * S.layout.d) b hb + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Scheme +end + +section +/- # Choosing a communication scheme with prescribed exterior labels -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Machine +variable {F : Type} [Field F] {N l b n h d B r C D : ℕ} + +/-- The colors can be chosen by `exterior` before the diagram is known. +The two density bounds concern a single copy of the diagram. -/ +theorem prepare (A : Expansion F n h) (hn : 2 ≤ n) (hh : 0 < h) (hr : 0 < r) (hC : 4 ≤ C) + (hA : ∀ d', Fintype.card (Position n r d' h) ≤ 52 * C * r * N → + ∀ (s : Packet n r d' → A.I) (u : Worker r), 128 * ∑ p, (A.plan hn N s).slotsAt h u p ≤ N) + (fa : Ports N l b → Label n r) (hfa : ∀ g, multiplicity fa g * r ^ n ≤ 4 * N) + (hlit : ∀ i g, multiplicity (fun t : Fin l => fa (.inl t) i) g * r ≤ 2 * l) + (hl : 1024 * l ≤ N) (hlink : 64 * (3 * r) ^ 2 ≤ N) (hB : B * d ≤ 4 * r) + (G : MachineDiagram F N l b d) (hc : G.cost ≤ C * N * d) (hd : ∀ v, G.arity v ≤ D) + (hsize : (D + 1) * (r ^ n) ^ 4 ≤ C * N * d) (hpad : (r ^ n) ^ 2 * 2 ^ n * h ≤ C * N * d) : + ∃ S : Scheme A hn G r B, S.colors = fa ∧ + S.layout.d = rounds n r h (12 * (C * N * d)) ∧ + Fintype.card (Position n r S.layout.d h) ≤ 13 * C * N * d ∧ + ∀ z, multiplicity S.layout.color z * r ^ n ≤ 16 * C * N * d := by + let f := fun s => fa (address N l b (port (tape N l b) d s).2) + let g : slots (copies .unit d) → Label n r := fun s => (port .unit d s).2.elim + have hf (z) : multiplicity f z * r ^ n ≤ C * N * d := + (exterior_copies fa hfa d z).trans (by gcongr) + have hg (z) : multiplicity g z * r ^ n ≤ C * N * d := by + have : IsEmpty (slots (copies .unit d)) := ⟨fun s => (port .unit d s).2.elim⟩ + simp [multiplicity] + obtain ⟨L, heq, hpos, hf', _, hv⟩ := layout G f g hc hd hr hh hf hg hsize hpad + have hall : Fintype.card (Position n r (B * L.d) h) ≤ 52 * C * r * N := by + calc + _ = B * Fintype.card (Position n r L.d h) := by + simp only [Position, Packet, Fintype.card_prod, Fintype.card_fin] + ring + _ ≤ B * (13 * (C * N * d)) := Nat.mul_le_mul_left B hpos + _ = 13 * C * N * (B * d) := by ring + _ ≤ 13 * C * N * (4 * r) := Nat.mul_le_mul_left _ hB + _ = _ := by ring + let S : Scheme A hn G r B := + ⟨hlink, L, fa, hf', fun s => A.report_budget hn N s (hA _ hall s), + fun R u => Pin.budget A hn R fa hlit hl u⟩ + exact ⟨S, rfl, heq, by simpa only [S, mul_assoc] using hpos, + fun z => by simpa only [S, mul_assoc] using hv z⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- # Diagonalization over a fixed coefficient field -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Scheme + +open Machine +variable {F : Type} [Field F] {N l b n h d B r : ℕ} {A : Expansion F n h} + {hn : 2 ≤ n} {G : MachineDiagram F N l b d} (S : Scheme A hn G r B) + (pad : Val (tape N l b)) (U : Val (tape N l b) → Val .unit → F) + +open Classical in +/-- Each processor has a literal programming the unit branch and +the explicit local evaluation of the replacement graph. -/ +def Programs (code : Option S.Report ↪ (Fin b → Bool)) : Prop := + ∃ serial : (R : S.Report) → S.Serial R, ∀ i : Fin (3 * r), ∃ ξ : Fin l → Bool, + ∀ z y, U (feed ξ z y) () = branch code (fun R => S.simulate pad R (serial R) i ξ) z y + +open Classical in +/-- No graph implementing a batch of these processors can have all +its replacement computations programmed back into the processors. -/ +theorem diagonal (code : Option S.Report ↪ (Fin b → Bool)) + (hr : 0 < r) (hR : 3 * r ≤ B * d) (hx : U pad () = 1) + (hU : S.Programs pad U code) : G.eval ≠ power U d := by + intro hG + obtain ⟨serial, hprog⟩ := hU + choose ξ hξ using hprog + have h := S.replay pad ξ U serial hR hx hG + unfold scalar at h + simp_rw [hξ] at h + rw [branch_sum (by omega : 0 < 3 * r) code + (fun i R => S.simulate pad R (serial R) i (ξ i))] at h + exact one_ne_zero (add_eq_right.mp h) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Scheme +end + +section +/- +# Descent and tagged-permutation hardness + +At each step the wide version of descent gives a lower bound on the +current per-copy cost. This absorbs the exterior cost of the trivalent +version. A fixed number of iterations then contradicts the lower bound. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal +open Filter + +variable {F : Type} [Field F] {L : Set (Table F)} + +theorem join {x y : Wire} {U : Val x → Val y → F} {t d m D : ℕ} + (h : Wide F D L (copies (copies x t) d) (copies (copies y t) d) (power (power U t) d) m) : + Wide F D L (copies x (t * d)) (copies y (t * d)) (power U (t * d)) m := by + obtain ⟨f, hf, ef⟩ := (Rewire.joinCopies x t d).inverse + obtain ⟨g, hg, eg⟩ := (Rewire.joinCopies y t d).inverse + have he : (fun a b => power (power U t) d (f a) (g b)) = power U (t * d) := by + funext a b + rw [← power_join, (ef _ a).mpr rfl, (eg _ b).mpr rfl] + exact he ▸ (h.pre hf).post hg + +private theorem large {α : ℝ} (hα : 0 < α) (k : ℕ) : + ∀ᶠ w : ℕ in atTop, 2 ≤ w ∧ 3 ≤ (w : ℝ) ^ (α / 4) ∧ + (w : ℝ) ^ ((k : ℝ) + 1) ≤ ((2 ^ w : ℕ) : ℝ) ^ (1 / 40 : ℝ) := by + have ht : Tendsto (fun w : ℕ => (w : ℝ)) atTop atTop := tendsto_natCast_atTop_atTop + have he := isLittleO_rpow_exp_pos_mul_atTop ((k : ℝ) + 1) (by positivity : 0 < Real.log 2 / 40) + filter_upwards [eventually_ge_atTop 2, ((tendsto_rpow_atTop (by positivity : 0 + < α / 4)).comp ht).eventually_ge_atTop 3, + ht.eventually he.eventuallyLE] with w hw hb he' + refine ⟨hw, hb, ?_⟩ + calc + _ ≤ Real.exp (Real.log 2 / 40 * w) := by + simpa only [Real.norm_of_nonneg (by positivity : 0 ≤ (w : ℝ) ^ ((k : ℝ) + 1)), + Real.norm_of_nonneg (Real.exp_nonneg _)] using he' + _ = _ := by + rw [Nat.cast_pow, Nat.cast_ofNat, Real.rpow_def_of_pos (by positivity), Real.log_pow] + congr 1 + ring + +private theorem absorb {w α x y : ℝ} (hw : 0 < w) (hx : 0 ≤ x) + (hlarge : 3 ≤ w ^ (α / 4)) (hy : y ≤ x * w ^ (-α)) : + x * w ^ (-α) + y * w ^ (α / 4) + y ≤ x * w ^ (-(α / 2)) := by + calc + _ ≤ x * w ^ (-α) + (x * w ^ (-α)) * w ^ (α / 4) + x * w ^ (-α) := by gcongr + _ = x * w ^ (-α) * (2 + w ^ (α / 4)) := by ring + _ ≤ x * w ^ (-α) * (w ^ (α / 4) * w ^ (α / 4)) := by gcongr; nlinarith + _ = _ := by + rw [mul_assoc, ← Real.rpow_add hw, ← Real.rpow_add hw] + congr 2 + ring + +theorem hard_of_resists (hr : Resists F L) (hd : Descent F L) : Tagged.Hard F := by + by_contra bad + obtain ⟨C, hC, α, hα, step⟩ := hd bad + obtain ⟨k, δ, hδ, resist⟩ := hr (2 * C) (by omega) + let b := α / 2 + have hb : 0 < b := half_pos hα + obtain ⟨J, hJ⟩ := exists_nat_gt (((k : ℝ) + 1) / b) + have hstop : (k : ℝ) + 1 < J * b := (div_lt_iff₀ hb).mp hJ + have hJpos : 0 < (J : ℝ) := lt_trans (by positivity) hJ + let κ := min δ (1 / 40 : ℝ) / J + have hκ : 0 < κ := by unfold κ; positivity + obtain ⟨w, hstep, ⟨hw, hlarge, hexp⟩, a, U, v, ha, hv, hcost, hard⟩ := + ((step κ hκ).and_eventually ((large hα k).and resist)).exists + let N : ℕ := 2 ^ w + have hw₁ : 1 < (w : ℝ) := by exact_mod_cast (by omega : 1 < w) + have hN : 1 ≤ (N : ℝ) := by exact_mod_cast (one_le_pow₀ (by decide : 1 ≤ 2) : 1 ≤ 2 ^ w) + have hN₀ : 0 < (N : ℝ) := zero_lt_one.trans_le hN + have budget {j : ℕ} (hj : j ≤ J) : (j : ℝ) * κ ≤ min δ (1 / 40 : ℝ) := by + calc + _ ≤ (J : ℝ) * κ := by gcongr + _ = _ := by unfold κ; field_simp + have iterate (j : ℕ) (hj : j ≤ J) : + ∃ t u : ℕ, 1 ≤ t ∧ (t : ℝ) ≤ (N : ℝ) ^ ((j : ℝ) * κ) ∧ + Net F (copies a t) (copies .unit t) (power U t) u ∧ + (u : ℝ) + t * (N : ℝ) ≤ t * N * (w : ℝ) ^ ((k : ℝ) + 1 - j * b) := by + induction j with + | zero => + refine ⟨1, v, le_rfl, by simp, by simpa only [one_mul] using hv.power 1, ?_⟩ + have h : v + N ≤ N * w ^ (k + 1) := by + calc + _ ≤ N * w ^ k + N * 1 := by rw [mul_one]; exact Nat.add_le_add_right hcost _ + _ ≤ _ := by + rw [← mul_add, pow_succ] + gcongr + nlinarith [Nat.one_le_pow k w (by omega)] + simp only [Nat.cast_one, Nat.cast_zero, one_mul, zero_mul, sub_zero, + ← Nat.cast_add_one, Real.rpow_natCast] + exact_mod_cast h + | succ j ih => + obtain ⟨t, u, ht, ht', hnet, hu⟩ := ih (by omega) + let M := u + t * N + let e := wd (copies a t) + wd (copies .unit t) + have he : e ≤ t * N := by + simp only [e, wd_copies, wd, Nat.mul_zero, Nat.add_zero] + exact Nat.mul_le_mul_left t ha + have hM : (M : ℝ) ≤ t * N * (w : ℝ) ^ ((k : ℝ) + 1 - j * b) + := by simpa only [M, Nat.cast_add, Nat.cast_mul] + have ht₀ := ht'.trans (Real.rpow_le_rpow_of_exponent_le hN + ((budget (j := j) (by omega)).trans (min_le_right _ _))) + have hsize : (M : ℝ) ≤ (N : ℝ) ^ (21 / 20 : ℝ) := by + calc + _ ≤ _ := hM + _ ≤ (N : ℝ) ^ (1 / 40 : ℝ) * N * (N : ℝ) ^ (1 / 40 : ℝ) := by + gcongr + exact (Real.rpow_le_rpow_of_exponent_le hw₁.le (sub_le_self _ (by positivity))).trans + hexp + _ = _ := by + rw [show (21 / 20 : ℝ) = 1 / 40 + 1 + 1 / 40 by norm_num, + Real.rpow_add hN₀, Real.rpow_add hN₀, Real.rpow_one] + have copies_le {d : ℕ} (hd : (d : ℝ) ≤ (N : ℝ) ^ κ) : + ((t * d : ℕ) : ℝ) ≤ (N : ℝ) ^ ((j.succ : ℝ) * κ) := by + rw [Nat.cast_mul, Nat.cast_succ, add_mul, one_mul, Real.rpow_add hN₀] + exact mul_le_mul ht' hd (by positivity) (by positivity) + obtain ⟨htri, hwide⟩ := hstep _ _ _ _ M hnet (by omega) + ((Nat.le_mul_of_pos_left N ht).trans (Nat.le_add_left _ _)) hsize + have he' : (e : ℝ) ≤ t * (N : ℝ) := by exact_mod_cast he + have hl : (t : ℝ) * N ≤ M * (w : ℝ) ^ (-α) := by + obtain ⟨d, D, m, hd, hdk, hD, hwide, hm⟩ := hwide + have hc := (copies_le hdk).trans + (Real.rpow_le_rpow_of_exponent_le hN ((budget hj).trans (min_le_left _ _))) + have hlow := hard (t * d) D m (Nat.mul_pos ht hd) hc hD (join hwide) + have hlo : 2 * (C : ℝ) * N * (t * (d : ℝ)) < m := by exact_mod_cast hlow + have hc' : 0 < (C : ℝ) * d := by positivity + have h : 2 * ((t : ℝ) * N) < M * (w : ℝ) ^ (-α) + (e : ℝ) := + (mul_lt_mul_iff_right₀ hc').mp (by + calc + _ = 2 * (C : ℝ) * N * (t * (d : ℝ)) := by ring + _ < _ := hlo.trans_le hm) + linarith + obtain ⟨d, m, hd, hdk, ⟨u', hnet', hm'⟩, hm⟩ := htri + have hvm : (u' : ℝ) ≤ m := by exact_mod_cast (show u' ≤ m by omega) + refine ⟨t * d, u', Nat.mul_pos ht hd, copies_le hdk, + hnet'.rewire (.joinCopies a t d) (.joinCopies .unit t d) (power_join U t d), ?_⟩ + calc + _ ≤ (d : ℝ) * (M * (w : ℝ) ^ (-α) + (e : ℝ) * (w : ℝ) ^ (α / 4)) + (t * d : ℕ) * (N : ℝ) := + add_le_add_left (hvm.trans hm) _ + _ ≤ (d : ℝ) * (M * (w : ℝ) ^ (-α) + ((t : ℝ) * N) * (w : ℝ) ^ (α / 4) + (t : ℝ) * N) := by + rw [Nat.cast_mul, mul_add (d : ℝ) _ ((t : ℝ) * N), mul_comm (t : ℝ) (d : ℝ), mul_assoc] + gcongr + _ ≤ (d : ℝ) * (M * (w : ℝ) ^ (-b)) := mul_le_mul_of_nonneg_left + (absorb (by linarith) (by positivity) hlarge hl) (by positivity) + _ ≤ (d : ℝ) * ((t * N * (w : ℝ) ^ ((k : ℝ) + 1 - j * b)) * (w : ℝ) ^ (-b)) := by gcongr + _ = _ := by + rw [Nat.cast_mul, Nat.cast_succ, show (k : ℝ) + 1 - (j + 1) * b = + ((k : ℝ) + 1 - j * b) + -b by ring, Real.rpow_add (by linarith : 0 < (w : ℝ))] + ring + obtain ⟨t, u, ht, _, _, hu⟩ := iterate J le_rfl + have hlt : (w : ℝ) ^ ((k : ℝ) + 1 - J * b) < 1 := Real.rpow_lt_one_of_one_lt_of_neg hw₁ (by + linarith) + have := mul_lt_mul_of_pos_left hlt (by positivity : 0 < (t : ℝ) * N) + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- +# A common batch size independent of the replacement + +Repeat any proposed small network until it reaches the prescribed +power. Feed surplus copies an input of weight one. This allows all +processor array dimensions to be fixed before choosing a diagram. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +variable {F : Type} [Field F] {D : ℕ} {L : Set (Table F)} {a b : Wire} {m d : ℕ} + +private theorem repeat_wide {k : Val a → Val b → F} (h : Wide F D L a b k m) (e : ℕ) : + Wide F D L (copies a e) (copies b e) (power k e) (e * m) := by + induction e with + | zero => rw [Nat.zero_mul]; exact .empty + | succ e ih => rw [Nat.succ_mul, Nat.add_comm (e * m) m]; exact h.par ih + +variable {U : Val a → Val .unit → F} (pad : Val a) (hp : U pad () = 1) + +include hp in +private theorem trim (hD : 3 ≤ D) {s : ℕ} (hs : s ≤ d) + (h : Wide F D L (copies a d) (copies .unit d) (power U d) m) : + ∃ v ≤ m + 4 * d * wd a, Wide F D L (copies a s) (copies .unit s) (power U s) v := by + obtain ⟨j, rfl⟩ := Nat.exists_eq_add_of_le hs + let z := bundle a j (fun _ => pad) + have hz : power U j z (unitCopies j) = 1 := by + rw [← eq_unitCopies j (bundle .unit j (fun _ => ()))] + unfold z + rw [power_bundle] + simp only [hp, Finset.prod_const_one] + have p := ((Tagged.literal_net F _ z).par (DNet.id F (copies a s))).pre + ((Rewire.unit' _).comp (.swap _ _)) + obtain ⟨n, hn, g⟩ := p.post (.appendCopies a j s) + obtain ⟨v, hv, hg⟩ := g.includeWide (L := L) hD + have out := (Rewire.copiesUnit s).comp (Rewire.unitCopies (s + j)) + refine ⟨v + m, ?_, ?_⟩ + · simp only [wd_copies] at hn + ring_nf at hn ⊢ + omega + · convert hg.comp (h.post out) using 1 + funext y r + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + rw [← eq_unitCopies _ (appendCopies .unit j s (unitCopies j, r)), power_append, hz, one_mul] + +include hp in +theorem repeat_trim {N C e : ℕ} (hd : 1 ≤ d) (he : d ≤ 2 * e) (ha : wd a ≤ N) + (h : Wide F D L (copies a d) (copies .unit d) (power U d) m) (hm : m ≤ C * N * d) : + ∃ v ≤ (3 * C + 12) * N * e, Wide F (max D 3) L (copies a e) (copies .unit e) (power U e) v := by + let k := e / d + 1 + have hcover : e ≤ d * k ∧ d * k ≤ 3 * e := by + have := Nat.mod_lt e hd + have := Nat.mod_add_div e d + simp only [k, mul_add, mul_one] + omega + have hh := join (repeat_wide (h.mono (le_max_left D 3) (Set.Subset.refl _)) k) + obtain ⟨v, hv, hnet⟩ := trim pad hp (le_max_right _ _) hcover.1 hh + refine ⟨v, hv.trans ?_, hnet⟩ + calc + _ ≤ k * (C * N * d) + 4 * (d * k) * N := by gcongr + _ = (C + 4) * N * (d * k) := by ring + _ ≤ (C + 4) * N * (3 * e) := Nat.mul_le_mul_left _ hcover.2 + _ = _ := by ring + +/-- A power of two within a factor of two of the square root +of the number of homes. -/ +theorem batch_floor (w n : ℕ) : + let m := 2 ^ (w / (32 * n)) + let r := 2 ^ (w / (16 * n)) + 0 < m ∧ m ^ 2 ≤ r ∧ ∀ d : ℕ, d ^ 2 ≤ r → d ≤ 2 * m := by + have h : w / (32 * n) = w / (16 * n) / 2 := by + rw [Nat.div_div_eq_div_mul, show 16 * n * 2 = 32 * n by ring] + rw [h] + generalize w / (16 * n) = j + intro m r + refine ⟨by unfold m; positivity, ?_, ?_⟩ + · unfold m r + rw [← pow_mul] + exact Nat.pow_le_pow_right (by decide) (by omega) + · have hr : r ≤ 2 * m ^ 2 := by + unfold m r + rw [← pow_mul, ← pow_succ'] + exact Nat.pow_le_pow_right (by decide) (by omega) + intro d hd + nlinarith + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- +# The local processor implementation requirement + +The implementation must be chosen before any replacement diagram is +given. Only the literal settings, wire numbering and report code can +depend on the diagram. This requirement is a hypothesis. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal +open Filter Machine + +variable {F : Type} [Field F] {n h r d N l B : ℕ} {A : Expansion F n h} + {hn : 2 ≤ n} {G : MachineDiagram F N l l d} + +/-- Counts the elements of `(Position n r S.layout.d h) ≤ 13 * C * N * d ∧`. -/ +def Scheme.compact (S : Scheme A hn G r B) (C : ℕ) := + Fintype.card (Position n r S.layout.d h) ≤ 13 * C * N * d ∧ + ∀ z, multiplicity S.layout.color z * r ^ n ≤ 16 * C * N * d + +/-- The least binary width whose power of two reaches the stated size. -/ +def Scheme.fits (S : Scheme A hn G r B) := + Nat.clog 2 n + r ^ 3 * Fintype.card A.I * Nat.clog 2 (Fintype.card (Packet n r (B * S.layout.d)) + + 1) + + 1 ≤ l + +theorem Scheme.fits_of_compact (S : Scheme A hn G r B) {C D : ℕ} (hh : 0 < h) + (scale : Scales C n h (Fintype.card A.I) N r l l d D B) (hc : S.compact C) : + S.fits := by + have hp : Fintype.card (Packet n r (B * S.layout.d)) ≤ 52 * C * N * r := by + calc + _ = B * Fintype.card (Packet n r S.layout.d) := by + simp only [Packet, Fintype.card_prod, Fintype.card_fin]; ring + _ ≤ B * Fintype.card (Position n r S.layout.d h) := by + gcongr + rw [Fintype.card_prod (Packet n r S.layout.d)] + have : Nonempty (Fin h) := ⟨⟨0, hh⟩⟩ + exact Nat.le_mul_of_pos_right _ Fintype.card_pos + _ ≤ B * (13 * C * N * d) := Nat.mul_le_mul_left _ hc.1 + _ = 13 * C * N * (B * d) := by ring + _ ≤ 13 * C * N * (4 * r) := Nat.mul_le_mul_left _ scale.copies + _ = _ := by ring + refine le_trans ?_ scale.broadcast + gcongr + +/-- Every admissible diagram of the indicated size must have a local +program at each site, without any promise about the tensor it computes. -/ +def Implements (L : Set (Table F)) (C k w : ℕ) (A : Expansion F n h) (hn : 2 ≤ n) : Prop := + let N := 2 ^ w + let r := 2 ^ (w / (16 * n)) + let l := N / 2048 + ∀ fa : Ports N l l → Label n r, + (∀ z, multiplicity fa z * r ^ n ≤ 4 * N) → + (∀ i g, multiplicity (fun t : Fin l => fa (.inl t) i) g * r ≤ 2 * l) → + ∃ (U : Val (tape N l l) → Val .unit → F) (pad : Val (tape N l l)) (v : ℕ), + U pad () = 1 ∧ Net F (tape N l l) .unit U v ∧ v ≤ N * w ^ k ∧ + let d := 2 ^ (w / (32 * n)) + ∀ D : ℕ, D ^ 2 ≤ N → + ∀ G : MachineDiagram F N l l d, G.cost ≤ C * N * d → G.Admits D L → + ∀ S : Scheme A hn G r ((3 * r + d - 1) / d), S.colors = fa → + S.layout.d = rounds n r h (12 * (C * N * d)) → S.compact C → + ∀ hb : S.fits, S.Programs pad U (S.encodeReport hb) + +/-- A quasi-linear universal processor for the concrete local evaluations. -/ +def Programmable (F : Type) [Field F] (L : Set (Table F)) : Prop := + ∀ C : ℕ, 4 ≤ C → ∀ (n h : ℕ) (hn : 2 ≤ n), 0 < h → ∀ A : Expansion F n h, + ∃ k : ℕ, ∀ᶠ w : ℕ in atTop, Implements L C k w A hn + +theorem resists_of_programmable {L : Set (Table F)} (hU : Programmable F L) : Resists F L := by + intro C₀ hC₀ + let C := 3 * C₀ + 12 + have hC : 4 ≤ C := by omega + obtain ⟨n, hn, h, A, hh, ha⟩ := bounded_expansion F (52 * C) + obtain ⟨k, hk⟩ := hU C hC n h hn hh A + obtain ⟨δ, hδ, hscale⟩ := scales C n h (Fintype.card A.I) hC hn + refine ⟨k, δ, hδ, ?_⟩ + filter_upwards [hk, hscale] with w impl scale + let N := 2 ^ w + let r := 2 ^ (w / (16 * n)) + let l := N / 2048 + have hN : 0 < N := by unfold N; positivity + have hr : 0 < r := by unfold r; positivity + obtain ⟨hδd, hs⟩ := scale + have s := hs 1 0 (by decide) (by exact hr) (by exact hN.le) + obtain ⟨fa, hfa, hfl⟩ := exterior s.pos s.labels s.tape + obtain ⟨U, pad, v, hpad, hnet, hv, hp⟩ := impl fa hfa hfl + have hwd : wd (tape N l l) ≤ N := by rw [wd_word]; exact s.tape + refine ⟨tape N l l, U, v, hwd, hnet, hv, ?_⟩ + intro d D m hd hsmall hD hwide + by_contra! hm + let d₀ := 2 ^ (w / (32 * n)) + obtain ⟨hd₀, hsmall₀, hcmp⟩ := batch_floor w n + have hmax : (max D 3) ^ 2 ≤ N := by + rcases le_total 3 D with h | h + · rw [max_eq_left h]; exact hD + · rw [max_eq_right h] + have hli : 64 * (3 * r) ^ 2 ≤ N := s.links + have : 0 < (3 * r) ^ 2 := by positivity + omega + obtain ⟨v', hm', hfixed⟩ := repeat_trim pad hpad hd (hcmp d (hδd d hsmall)) hwd hwide hm + obtain ⟨G, hG, had, hcost⟩ := hfixed.diagram + have sc := hs d₀ (max D 3) hd₀ hsmall₀ hmax + obtain ⟨S, hcolors, hshape, hcomp⟩ := prepare A hn hh hr hC (fun d' => ha r d' N hN) + fa hfa hfl sc.literal sc.links sc.copies G (hcost.le.trans hm') (fun v => (had v).1) + sc.degree sc.padding + have hb := S.fits_of_compact hh sc hcomp + have prog := hp (max D 3) hmax G (hcost.le.trans hm') had S hcolors hshape hcomp hb + exact S.diagonal pad U (S.encodeReport hb) hr sc.cover hpad prog hG + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- # The remaining estimates for exact many-list hardness -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +theorem manyList {F : Type} [Field F] {L : Set (Table F)} + (hU : Programmable F L) (hD : Descent F L) : ManyList (Realizes F) := + Tagged.manyList_of_tag (hard_of_resists (resists_of_programmable hU) hD) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Cuts.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Cuts.lean new file mode 100644 index 0000000000..21e2a10099 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Cuts.lean @@ -0,0 +1,716 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +public import Mathlib.Algebra.BigOperators.Field +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Ring +public import Mathlib.Data.Fintype.BigOperators +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Normalize + +/-! +# Balancing finitely many weight classes + +The squared discrepancies are summed over every color and class. +At each vertex some color makes the total cross term nonpositive. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Finset +variable {X Z I : Type*} [Fintype Z] [Nonempty Z] [DecidableEq Z] + +private noncomputable def dev (s : Finset X) (f : X → Z) (w : X → ℝ) (z : Z) : ℝ := + ∑ x ∈ s, ((if f x = z then w x else 0) - w x / Fintype.card Z) + +private theorem sum_dev (s : Finset X) (f : X → Z) (w : X → ℝ) : + ∑ z, dev s f w z = 0 := by + unfold dev + rw [sum_comm] + apply sum_eq_zero + intro x _ + simp [sum_sub_distrib, mul_div_cancel₀, Fintype.card_ne_zero] + +private theorem step (d : Z → ℝ) (hd : ∑ z, d z = 0) (u : ℝ) (c : Z) : + ∑ z, (d z + ((if c = z then u else 0) - u / Fintype.card Z)) ^ 2 ≤ + (∑ z, (d z) ^ 2) + 2 * u * d c + u ^ 2 := by + let k : ℝ := Fintype.card Z + have hk : 0 < k := by unfold k; exact_mod_cast Fintype.card_pos (α := Z) + have expand (z : Z) : (d z + ((if c = z then u else 0) - u / k)) ^ 2 = + (d z) ^ 2 + (if c = z then 2 * u * d z + u ^ 2 - 2 * u * (u / k) else 0) + + (u / k) ^ 2 - 2 * (u / k) * d z := by split <;> ring + change (∑ z, (d z + ((if c = z then u else 0) - u / k)) ^ 2) ≤ _ + simp only [expand, sum_sub_distrib, sum_add_distrib, sum_ite_eq, mem_univ, ite_true, + sum_const, card_univ, nsmul_eq_mul, ← mul_sum, hd, mul_zero, sub_zero] + have he : k * (u / k) ^ 2 - 2 * u * (u / k) = -(u ^ 2 / k) := by field_simp; ring + dsimp only [k] at he hk ⊢ + linarith [div_nonneg (sq_nonneg u) hk.le] + +variable [Fintype I] + +private theorem energy (w : I → X → ℝ) (s : Finset X) : + ∃ f : X → Z, ∑ i, ∑ z, (dev s f (w i) z) ^ 2 ≤ ∑ i, ∑ x ∈ s, (w i x) ^ 2 := by + classical + induction s using Finset.induction_on with + | empty => exact ⟨fun _ => Classical.choice inferInstance, by simp [dev]⟩ + | @insert x s hx ih => + obtain ⟨f, hf⟩ := ih + have hsum : ∑ z, (∑ i, 2 * w i x * dev s f (w i) z) ≤ ∑ _z : Z, (0 : ℝ) := by + rw [sum_comm] + simp [← mul_sum, sum_dev] + obtain ⟨c, _, hc⟩ := exists_le_of_sum_le univ_nonempty hsum + let g (y : X) := if y = x then c else f y + have hg (i : I) (z : Z) : dev (insert x s) g (w i) z = + dev s f (w i) z + ((if c = z then w i x else 0) - w i x / Fintype.card Z) := by + unfold dev + rw [sum_insert hx, add_comm, show g x = c by simp [g]] + congr 1 + apply sum_congr rfl + intro y hy + rw [show g y = f y by simp [g, show y ≠ x by rintro rfl; exact hx hy]] + refine ⟨g, ?_⟩ + simp only [hg, sum_insert hx] + have hb := sum_le_sum (s := univ) (fun i _ => step _ (sum_dev s f (w i)) (w i x) c) + simp only [sum_add_distrib] at hb ⊢ + linarith + +/-- Every class and color has squared discrepancy at most the sum of +squared weights across all classes. Weights may have either sign. -/ +theorem color [Fintype X] (w : I → X → ℝ) : + ∃ f : X → Z, ∀ i z, + ((∑ x, if f x = z then w i x else 0) - (∑ x, w i x) / Fintype.card Z) ^ 2 ≤ + ∑ j, ∑ x, (w j x) ^ 2 := by + obtain ⟨f, hf⟩ := energy (Z := Z) w univ + refine ⟨f, fun i z => ?_⟩ + rw [sum_div, ← sum_sub_distrib] + calc + _ ≤ ∑ y, (dev univ f (w i) y) ^ 2 := single_le_sum (fun _ _ => sq_nonneg _) (mem_univ z) + _ ≤ _ := (single_le_sum (fun _ _ => sum_nonneg (fun _ _ => sq_nonneg _)) (mem_univ i)).trans hf + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- +# Coloring one side of a bipartite graph + +Group edges by the prescribed color of their far endpoint. The load of +a vertex in any class is at most its degree, so the sum of squared +loads is at most the maximum degree times the number of edges. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Finset +variable {V E Z : Type*} [Fintype V] [Fintype E] [Fintype Z] [DecidableEq V] [DecidableEq Z] + +private def load (src : E → V) (col : E → Z) (y : Z) (v : V) : ℝ := + Fintype.card {e // src e = v ∧ col e = y} + +omit [Fintype Z] in +private theorem load_sum (src : E → V) (col : E → Z) (y : Z) (p : V → Prop) [DecidablePred p] : + ∑ v, (if p v then load src col y v else 0) = Fintype.card {e // p (src e) ∧ col e = y} := by + rw [← sum_filter] + have h := sum_card_fiberwise_eq_card_filter (univ.filter (fun e => col e = y)) + (univ.filter p) src + simp only [load, Fintype.card_subtype, ← Nat.cast_sum] + congr 1 + simpa only [filter_filter, mem_filter, mem_univ, true_and, and_comm] using h + +omit [Fintype Z] in +private theorem load_total (src : E → V) (col : E → Z) (y : Z) : + ∑ v, load src col y v = Fintype.card {e // col e = y} := by + simpa using load_sum src col y (fun _ => True) + +private theorem load_sq (src : E → V) (col : E → Z) {D : ℕ} + (hd : ∀ v, Fintype.card {e // src e = v} ≤ D) : + ∑ y, ∑ v, (load src col y v) ^ 2 ≤ (D : ℝ) * Fintype.card E := by + calc + _ ≤ ∑ y, ∑ v, (D : ℝ) * load src col y v := by + apply sum_le_sum + intro y _ + apply sum_le_sum + intro v _ + have h := (Fintype.card_subtype_mono (fun e => src e = v ∧ col e = y) + (fun e => src e = v) (fun _ h => h.1)).trans (hd v) + rw [pow_two, load] + exact mul_le_mul_of_nonneg_right (Nat.cast_le.mpr h) (Nat.cast_nonneg _) + _ = _ := by + simp only [← mul_sum, load_total, Fintype.card_subtype, ← Nat.cast_sum] + rw [sum_card_fiberwise_eq_card_filter] + simp + +private theorem scaled {x y d k m : ℝ} (hm : 0 ≤ m) (hk : 0 < k) + (h : (x - y / k) ^ 2 ≤ (d + 1) * m) (hsize : (d + 1) * k ^ 4 ≤ m) : + x * k ^ 2 ≤ y * k + m := by + have hsq : (x * k ^ 2 - y * k) ^ 2 ≤ m ^ 2 := calc + _ = (x - y / k) ^ 2 * k ^ 4 := by field_simp + _ ≤ (d + 1) * m * k ^ 4 := mul_le_mul_of_nonneg_right h (by positivity) + _ = ((d + 1) * k ^ 4) * m := by ring + _ ≤ m ^ 2 := by rw [pow_two]; exact mul_le_mul_of_nonneg_right hsize hm + linarith only [le_of_sq_le_sq hsq hm] + +/-- Color the free endpoints, controlling both the number of vertices +in each color and the number of edges of each ordered color pair. -/ +theorem bipartite [Nonempty Z] (src : E → V) (col : E → Z) {M D : ℕ} + (hv : Fintype.card V ≤ M) (he : Fintype.card E ≤ M) + (hd : ∀ v, Fintype.card {e // src e = v} ≤ D) + (hc : ∀ y, Fintype.card {e // col e = y} * Fintype.card Z ≤ M) + (hsize : (D + 1) * (Fintype.card Z) ^ 4 ≤ M) : + ∃ f : V → Z, + (∀ z, Fintype.card {v // f v = z} * Fintype.card Z ≤ 2 * M) ∧ + (∀ z y, Fintype.card {e // f (src e) = z ∧ col e = y} * (Fintype.card Z) ^ 2 ≤ 2 * M) := by + let w : Option Z → V → ℝ + | none, _ => 1 + | some y, v => load src col y v + have hsq : ∑ i, ∑ v, (w i v) ^ 2 ≤ ((D : ℝ) + 1) * M := by + rw [Fintype.sum_option] + simp only [w, one_pow, sum_const, card_univ, nsmul_eq_mul, mul_one] + calc + _ ≤ (Fintype.card V : ℝ) + D * Fintype.card E := add_le_add_right (load_sq src col hd) _ + _ ≤ (M : ℝ) + D * M := by gcongr + _ = _ := by ring + obtain ⟨f, hf⟩ := color (Z := Z) w + have hk : 0 < Fintype.card Z := Fintype.card_pos + have h (i : Option Z) (z : Z) : + (∑ v, if f v = z then w i v else 0) * (Fintype.card Z : ℝ) ^ 2 ≤ + (∑ v, w i v) * Fintype.card Z + M := + scaled (by positivity) (by exact_mod_cast hk) ((hf i z).trans hsq) (by exact_mod_cast hsize) + refine ⟨f, ?_, ?_⟩ + · intro z + have hh := h none z + simp only [w, sum_boole, sum_const, card_univ, nsmul_eq_mul, mul_one, + ← Fintype.card_subtype] at hh + have hh' : Fintype.card {v // f v = z} * (Fintype.card Z) ^ 2 ≤ + Fintype.card V * Fintype.card Z + M := by exact_mod_cast hh + apply Nat.le_of_mul_le_mul_right _ hk + rw [mul_assoc, ← pow_two] + exact hh'.trans (by nlinarith) + · intro z y + have hh := h (some y) z + simp only [w, load_sum, load_total] at hh + have hh' : Fintype.card {e // f (src e) = z ∧ col e = y} * (Fintype.card Z) ^ 2 ≤ + Fintype.card {e // col e = y} * Fintype.card Z + M := by exact_mod_cast hh + have := hc y + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- # Distributing wires among finitely many labels -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +variable {A B Z : Type} [Fintype A] [Fintype B] [Fintype Z] [DecidableEq Z] + +/-- Count sites carrying the specified label. -/ +def multiplicity (f : A → Z) (z : Z) := Fintype.card {a // f a = z} + +omit [Fintype Z] in +theorem multiplicity_sum (f : A ⊕ B → Z) (z : Z) : + multiplicity f z = multiplicity (f ∘ Sum.inl) z + multiplicity (f ∘ Sum.inr) z := by + unfold multiplicity + rw [Fintype.card_congr Equiv.subtypeSum, Fintype.card_sum] + rfl + +omit [Fintype Z] in +theorem multiplicity_elim (f : A → Z) (g : B → Z) (z : Z) : + multiplicity (Sum.elim f g) z = multiplicity f z + multiplicity g z := + multiplicity_sum _ z + +theorem even_labels [Nonempty Z] : + ∃ f : A → Z, ∀ z, multiplicity f z * Fintype.card Z ≤ Fintype.card A + Fintype.card Z := by + let r := Fintype.card Z + let n := Fintype.card A + let m := n / r + 1 + have h : n ≤ r * m ∧ r * m ≤ n + r := by + have : n % r < r := Nat.mod_lt n (Fintype.card_pos (α := Z)) + have := Nat.mod_add_div n r + simp only [m, Nat.mul_add, mul_one] + omega + obtain ⟨e⟩ : Nonempty (A ↪ Z × Fin m) := Function.Embedding.nonempty_of_card_le + (by rw [Fintype.card_prod, Fintype.card_fin]; exact h.1) + refine ⟨fun x => (e x).1, fun z => ?_⟩ + have hinj : Function.Injective (fun x : {x // (e x).1 = z} => (e x.val).2) := + fun x y he => Subtype.ext (e.injective (Prod.ext (x.2.trans y.2.symm) he)) + have hm := Fintype.card_le_of_injective _ hinj + rw [Fintype.card_fin] at hm + exact (Nat.mul_le_mul_right r hm).trans (by rw [mul_comm]; exact h.2) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- +# Packing directed wires into binary cubes + +Use every ordered pair of labels as a template, allowing coincidences +in individual coordinates. The corners are labelled by choosing one +symbol or the other in each coordinate. For a fixed corner, the +map from templates to opposite pairs of labels is an involution. +Consequently every demand occurs equally often, even if some of the +corner labels coincide. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Spectral +variable {n r d h : ℕ} + +/-- The indexing data represented by `Fin n → Fin r`. -/ +abbrev Label (n r : ℕ) := Fin n → Fin r +/-- Indexes the template by the coordinates of `Label n r × Label n r`. -/ +abbrev Template (n r : ℕ) := Label n r × Label n r +/-- Indexes the packet by the coordinates of `Template n r × Fin d`. -/ +abbrev Packet (n r d : ℕ) := Template n r × Fin d +/-- Indexes the position by the coordinates of `Packet n r d × Cube n × Fin h`. -/ +abbrev Position (n r d h : ℕ) := Packet n r d × Cube n × Fin h + +/-- Evaluates `if x i then p.2 i else p.1 i` at the input `i`. -/ +def corner (p : Template n r) (x : Cube n) : Label n r := + fun i => if x i then p.2 i else p.1 i + +/-- The value specified by `(corner p x, corner p (Cube.flip Finset.univ x))`. -/ +def opposite (x : Cube n) (p : Template n r) : Template n r := + (corner p x, corner p (Cube.flip Finset.univ x)) + +theorem opposite_opposite (x : Cube n) (p : Template n r) : + opposite x (opposite x p) = p := by + apply Prod.ext <;> funext i <;> cases hx : x i <;> simp [opposite, corner, Cube.flip, hx] + +theorem corner_flip (p : Template n r) (x : Cube n) {i j : Fin n} (hij : i ≠ j) : + corner p (Cube.flip {j} x) i = corner p x i := by + simp [corner, Cube.flip, hij] + +/-- The ordered pair served by a particular wire in a packet. -/ +def endpoints (s : Position n r d h) : Template n r := + opposite s.2.1 s.1.1 + +/-- Reindexes `Template n r × (Fin d × Cube n × Fin h)` and `Position n r d h where toFun s` by +an equivalence. -/ +def positions (n r d h : ℕ) : + Template n r × (Fin d × Cube n × Fin h) ≃ Position n r d h where + toFun s := ((opposite s.2.2.1 s.1, s.2.1), s.2.2) + invFun s := (endpoints s, s.1.2, s.2) + left_inv _ := by simp [endpoints, opposite_opposite] + right_inv _ := by simp [endpoints, opposite_opposite] + +theorem endpoints_positions (s : Template n r × (Fin d × Cube n × Fin h)) : + endpoints (positions n r d h s) = s.1 := + opposite_opposite _ _ + +private theorem place {E Z Y : Type} [Fintype E] [Fintype Y] [DecidableEq Z] + (f : E → Z) (hf : ∀ z, multiplicity f z ≤ Fintype.card Y) : + ∃ g : E ↪ Z × Y, ∀ e, (g e).1 = f e := by + let a (z : Z) : {e // f e = z} ↪ Y := + Classical.choice (Function.Embedding.nonempty_of_card_le (hf z)) + let g : (Σ z, {e // f e = z}) → Z × Y := fun p => (p.1, a p.1 p.2) + have hi : Function.Injective g := by + rintro ⟨z, e⟩ ⟨y, k⟩ he + have : z = y := congrArg Prod.fst he + subst y + have : e = k := (a z).injective (congrArg Prod.snd he) + rw [this] + exact ⟨(Equiv.sigmaFiberEquiv f).symm.toEmbedding.trans ⟨g, hi⟩, fun _ => rfl⟩ + +/-- Repetition count fixed from the capacity before laying out any diagram. -/ +def rounds (n r h M : ℕ) := + M / (Fintype.card (Label n r) ^ 2 * Fintype.card (Cube n) * h) + 1 + +/-- A uniform supply of cube packets suffices. The rounding error +costs at most one full packet for every ordered pair of labels. -/ +theorem pack {E : Type} [Fintype E] {M : ℕ} (f : E → Template n r) (hr : 0 < r) (hh : 0 < h) + (hb : ∀ p, multiplicity f p * Fintype.card (Label n r) ^ 2 ≤ M) : + let d := rounds n r h M + Fintype.card (Position n r d h) ≤ + M + Fintype.card (Label n r) ^ 2 * Fintype.card (Cube n) * h ∧ + ∃ g : E ↪ Position n r d h, ∀ e, endpoints (g e) = f e := by + let z := Fintype.card (Label n r) + let B := z ^ 2 * Fintype.card (Cube n) * h + let d := M / B + 1 + have hz : 0 < z := by simpa [z, Label] using pow_pos hr n + have hB : 0 < B := mul_pos (mul_pos (pow_pos hz 2) Fintype.card_pos) hh + have hsize : M ≤ d * B ∧ d * B ≤ M + B := by + have := Nat.mod_lt M hB + have := Nat.mod_add_div M B + rw [mul_comm d, show d = M / B + 1 from rfl, mul_add, mul_one] + omega + have hc : Fintype.card (Position n r d h) = d * B := by + simp only [Position, Packet, Template, Fintype.card_prod, Fintype.card_fin, B, z] + ring + refine ⟨hc.le.trans hsize.2, ?_⟩ + obtain ⟨g, hg⟩ := place (Y := Fin d × Cube n × Fin h) f (fun p => by + apply (Nat.mul_le_mul_right_iff (pow_pos hz 2)).1 + calc + _ ≤ M := hb p + _ ≤ d * B := hsize.1 + _ = _ := by simp only [Fintype.card_prod, Fintype.card_fin, B]; ring) + refine ⟨g.trans (positions n r d h).toEmbedding, fun e => ?_⟩ + exact (endpoints_positions (g e)).trans (hg e) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- +# Assigning labels to a subdivided batch + +Exterior slots may have prescribed labels. Place the remaining junctions +first, then simultaneously balance all incidence counts at the stations. +This avoids any independence assumption about repeated edges or loops. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +variable {F : Type} {a b : Wire} (G : Diagram F a b) {Z : Type} + [Fintype Z] [DecidableEq Z] [Nonempty Z] (fa : slots a → Z) (fb : slots b → Z) + +omit [Fintype Z] [Nonempty Z] in +private theorem count_ends (fe : G.E → Z) (z : Z) : + multiplicity ((Sum.elim fa (Sum.elim fb fe)) ∘ G.junction) z = + multiplicity fa z + multiplicity fb z + 2 * multiplicity fe z := by + have he : (Sum.elim fa (Sum.elim fb fe)) ∘ G.junction = + Sum.elim (Sum.elim fa fe) (Sum.elim fb fe) := by + funext x + rcases x with (i|e)|(j|e) <;> rfl + rw [he, multiplicity_elim, multiplicity_elim, multiplicity_elim] + omega + +/-- Orient each subdivided edge from its junction to its original station. +Every ordered pair of labels has bounded edge multiplicity. -/ +theorem label_diagram [Field F] {M D : ℕ} (hm : G.cost ≤ M) + (hd : ∀ v, G.arity v ≤ D) (hz : Fintype.card Z ≤ M) + (ha : ∀ z, multiplicity fa z * Fintype.card Z ≤ M) + (hb : ∀ z, multiplicity fb z * Fintype.card Z ≤ M) + (hsize : (D + 1) * Fintype.card Z ^ 4 ≤ M) : + ∃ f : G.normalized.V → Z, + (∀ i, f (.inr (.inl i)) = fa i) ∧ + (∀ j, f (.inr (.inr (.inl j))) = fb j) ∧ + (∀ z, multiplicity f z * Fintype.card Z ≤ 16 * M) ∧ + (∀ z y, Fintype.card {e : G.End // + f (.inl (G.station e)) = z ∧ f (.inr (G.junction e)) = y} * + Fintype.card Z ^ 2 ≤ 12 * M) := by + classical + rw [Diagram.cost_eq] at hm + obtain ⟨fe, hfe⟩ := even_labels (A := G.E) (Z := Z) + let g : G.Joint → Z := Sum.elim fa (Sum.elim fb fe) + have hg (z : Z) : multiplicity g z * Fintype.card Z ≤ 4 * M := by + unfold g + rw [multiplicity_elim, multiplicity_elim, add_mul, add_mul] + have := ha z + have := hb z + have := hfe z + omega + have hge (z : Z) : multiplicity (g ∘ G.junction) z * Fintype.card Z ≤ 6 * M := by + unfold g + rw [count_ends, add_mul, add_mul, mul_assoc] + have := ha z + have := hb z + have := hfe z + omega + obtain ⟨f, hf, hp⟩ := bipartite G.station (g ∘ G.junction) (M := 6 * M) (D := D) + (by omega) (by rw [Diagram.card_end]; omega) (fun v => (G.degree v).le.trans (hd v)) + hge (by omega) + refine ⟨Sum.elim f g, fun _ => rfl, fun _ => rfl, ?_, ?_⟩ + · intro z + rw [multiplicity_elim, add_mul] + have h : multiplicity f z * Fintype.card Z ≤ 2 * (6 * M) := hf z + have := hg z + omega + · intro z y + exact (hp z y).trans (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- # A bounded cube layout for every network of small maximum arity -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Spectral +variable {F : Type} [Field F] {a b : Wire} (G : Diagram F a b) {n r h : ℕ} + +/-- Each wire of the normalized diagram occupies its own directed +position. The orientation convention is independent of the local tables. -/ +structure Layout (n r h : ℕ) where + /-- The `Layout` field of type `ℕ`. -/ + d : ℕ + /-- The `Layout` component of type `G.normalized.V → Label n r`. -/ + color : G.normalized.V → Label n r + /-- Embeds the coordinates as `G.End ↪ Position n r d h`. -/ + assign : G.End ↪ Position n r d h + follows : ∀ e, endpoints (assign e) = (color (.inl (G.station e)), color (.inr (G.junction e))) + +theorem layout {M D : ℕ} (fa : slots a → Label n r) (fb : slots b → Label n r) + (hm : G.cost ≤ M) (hd : ∀ v, G.arity v ≤ D) (hr : 0 < r) (hh : 0 < h) + (ha : ∀ z, multiplicity fa z * r ^ n ≤ M) (hb : ∀ z, multiplicity fb z * r ^ n ≤ M) + (hsize : (D + 1) * (r ^ n) ^ 4 ≤ M) (hpad : (r ^ n) ^ 2 * 2 ^ n * h ≤ M) : + ∃ L : Layout G n r h, L.d = rounds n r h (12 * M) ∧ Fintype.card (Position n r L.d h) ≤ 13 * M ∧ + (∀ i, L.color (.inr (.inl i)) = fa i) ∧ + (∀ j, L.color (.inr (.inr (.inl j))) = fb j) ∧ + (∀ z, multiplicity L.color z * r ^ n ≤ 16 * M) := by + let _ : Nonempty (Fin r) := ⟨⟨0, hr⟩⟩ + have hz : Fintype.card (Label n r) = r ^ n := by simp [Label] + have hc : Fintype.card (Cube n) = 2 ^ n := by simp [Cube] + have hN : Fintype.card (Label n r) ≤ M := by + rw [hz] + exact (Nat.le_pow (by decide : 0 < 4)).trans + ((Nat.le_mul_of_pos_left _ (Nat.succ_pos D)).trans hsize) + obtain ⟨f, hfa, hfb, hf, hg⟩ := label_diagram G fa fb hm hd hN + (by rwa [hz]) (by rwa [hz]) (by rwa [hz]) + let g : G.End → Template n r := fun e => (f (.inl (G.station e)), f (.inr (G.junction e))) + obtain ⟨hcost, v, hv⟩ := pack (M := 12 * M) g hr hh (by + rintro ⟨x, y⟩ + simpa [multiplicity, g, Fintype.card_subtype] using hg x y) + refine ⟨⟨_, f, v, hv⟩, rfl, ?_, hfa, hfb, ?_⟩ + · rw [hz, hc] at hcost + exact hcost.trans (by omega) + · rwa [hz] at hf + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- # Exact wire identities with a cut along every cube coordinate -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +/-- Indexes the block by the coordinates of `Spectral.Cube n × Fin h → Bool`. -/ +abbrev Block (n h : ℕ) := Spectral.Cube n × Fin h → Bool + +/-- Each corner sends a word to the opposite corner. Index both words +by the sending corner. At any cut the sending and receiving positions +belong to opposite sides. -/ +structure Expansion (F : Type) [Field F] (n h : ℕ) where + /-- The `Expansion` component of type `Type`. -/ + I : Type + [fi : Fintype I] + /-- The weight function carried by `Expansion`, with type `I → Block n h → Block n h → F`. -/ + weight : I → Block n h → Block n h → F + /-- The `Expansion` component of type `I → Fin n → ℕ`. -/ + cross : I → Fin n → ℕ + /-- The `Expansion` component of type `(s : I) → (i : Fin n) → Bool → Block n h → Block n h → + (Fin (cross s i) → Bool) → F`. -/ + side : (s : I) → (i : Fin n) → Bool → Block n h → Block n h → (Fin (cross s i) → Bool) → F + full : ∀ x y, (∑ s, weight s x y) = if x = y then 1 else 0 + split : ∀ s i x y, weight s x y = ∑ z, side s i false x y z * side s i true x y z + depends : ∀ s i b x x' y y' z, (∀ p, p.1 i = b → x p = x' p) → + (∀ p, p.1 i ≠ b → y p = y' p) → side s i b x y z = side s i b x' y' z + +attribute [instance] Expansion.fi + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- +# Expanding an exact contraction by packets + +Unoccupied positions are pinned to zero on both sides. Summing freely +over them instead could change the scalar in positive characteristic. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Spectral +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} {n r h : ℕ} + +namespace Layout + +variable (L : Layout G n r h) + +/-- Evaluates `Function.extend L.assign x (fun _ => false) (p, i)` at the input `i`. -/ +def load (x : G.End → Bool) (p : Packet n r L.d) : Block n h := + fun i => Function.extend L.assign x (fun _ => false) (p, i) + +theorem load_assign (x : G.End → Bool) (e : G.End) : + L.load x (L.assign e).1 (L.assign e).2 = x e := + L.assign.injective.extend_apply _ _ _ + +theorem load_injective : Function.Injective L.load := by + intro x y he + funext e + rw [← L.load_assign x e, ← L.load_assign y e, he] + +theorem load_local (x y : G.End → Bool) (p : Packet n r L.d) (i : Cube n × Fin h) + (he : ∀ e, L.assign e = (p, i) → x e = y e) : L.load x p i = L.load y p i := by + by_cases ho : ∃ e, L.assign e = (p, i) + · obtain ⟨e, h⟩ := ho + simpa [load, ← h, L.assign.injective.extend_apply] using he e h + · simp [load, Function.extend_apply' _ _ _ ho] + +end Layout + +theorem Expansion.full_product {P : Type} [Fintype P] [DecidableEq P] + (A : Expansion F n h) (x y : P → Block n h) : + (∑ s : P → A.I, ∏ p, A.weight (s p) (x p) (y p)) = if x = y then 1 else 0 := by + rw [← Fintype.prod_sum (fun p j => A.weight j (x p) (y p))] + simp_rw [A.full] + by_cases he : x = y + · simp [he] + · rw [ite_eq_right he] + obtain ⟨i, hi⟩ := Function.ne_iff.mp he + exact Finset.prod_eq_zero (Finset.mem_univ i) (ite_eq_right hi) + +open Classical in +/-- A network with independent slot bits on the two sides of every edge. +The full sum over packet selectors restores all the wire equalities. -/ +theorem Layout.eval (L : Layout G n r h) (A : Expansion F n h) (x : Val a) (y : Val b) : + G.eval x y = + ∑ u : G.End → Bool, ∑ v : G.End → Bool, + (∏ i : G.V, G.normalized.vertex x y u (.inl i)) * + (∏ i : G.Joint, G.normalized.vertex x y v (.inr i)) * + ∑ s : Packet n r L.d → A.I, ∏ p, A.weight (s p) (L.load u p) (L.load v p) := by + simp only [A.full_product, L.load_injective.eq_iff, mul_ite, mul_one, mul_zero, + Finset.sum_ite_eq, Finset.mem_univ, ite_true] + rw [← G.eval_normalized] + unfold Diagram.eval + apply Finset.sum_congr + · ext; simp + · exact fun _ _ => Fintype.prod_sum_type _ + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- # Locality and cost of a coordinate cut -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Spectral +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} {n r h : ℕ} + +/-- A template meets at most two groups at a fixed coordinate. -/ +def group (p : Template n r) (i : Fin n) (s : Bool) : Fin r := + if s then p.2 i else p.1 i + +theorem Layout.end_groups (L : Layout G n r h) (e : G.End) (i : Fin n) : + let p := L.assign e + L.color (.inl (G.station e)) i = group p.1.1 i (p.2.1 i) ∧ + L.color (.inr (G.junction e)) i = group p.1.1 i (!(p.2.1 i)) := by + have h := L.follows e + exact ⟨(congrArg (fun x => x.1 i) h).symm, by + simpa [endpoints, opposite, corner, group, Cube.flip] using + (congrArg (fun x => x.2 i) h).symm⟩ + +/-- A side table needs no slot bits from other groups. -/ +theorem Layout.side_local (L : Layout G n r h) (A : Expansion F n h) + (p : Packet n r L.d) (s : A.I) (i : Fin n) (b : Bool) + (u u' v v' : G.End → Bool) (z : Fin (A.cross s i) → Bool) + (hu : ∀ e, L.color (.inl (G.station e)) i = group p.1 i b → u e = u' e) + (hv : ∀ e, L.color (.inr (G.junction e)) i = group p.1 i b → v e = v' e) : + A.side s i b (L.load u p) (L.load v p) z = A.side s i b (L.load u' p) (L.load v' p) z := by + apply A.depends + · intro q hq + apply L.load_local + intro e he + apply hu + rw [(L.end_groups e i).1, he, hq] + · intro q hq + apply L.load_local + intro e he + apply hv + have heq : (!(q.1 i)) = b := by cases ha : q.1 i <;> cases b <;> simp_all + rw [(L.end_groups e i).2, he, heq] + +variable {P : Type} [Fintype P] + +/-- The cut may depend on the complete selector tuple. The cost is +bounded uniformly over all such tuples. -/ +theorem Expansion.coordinate (A : Expansion F n h) (hn : 0 < n) (L : ℕ) + (hc : ∀ s, L * ∑ i, A.cross s i ≤ n * Fintype.card (Cube n) * h) + (hl : L * Nat.clog 2 (Fintype.card A.I) ≤ h) (s : P → A.I) : + ∃ i : Fin n, (∀ j, ∑ p, A.cross (s p) i ≤ ∑ p, A.cross (s p) j) ∧ + L * (∑ p, (A.cross (s p) i + Nat.clog 2 (Fintype.card A.I))) ≤ + 2 * Fintype.card P * Fintype.card (Cube n) * h := by + let c (i : Fin n) := ∑ p, A.cross (s p) i + obtain ⟨i, -, hi⟩ := Finset.exists_min_image Finset.univ c ⟨⟨0, hn⟩, Finset.mem_univ _⟩ + have hsum : n * (L * c i) ≤ n * (Fintype.card P * Fintype.card (Cube n) * h) := by + calc + _ = ∑ _ : Fin n, L * c i := by simp + _ ≤ ∑ j : Fin n, L * c j := + Finset.sum_le_sum (fun j hj => Nat.mul_le_mul_left _ (hi j hj)) + _ = ∑ p, L * ∑ j, A.cross (s p) j := by + simp only [c, Finset.mul_sum] + rw [Finset.sum_comm] + _ ≤ ∑ _p : P, n * Fintype.card (Cube n) * h := Finset.sum_le_sum (fun p _ => hc (s p)) + _ = _ := by simp only [Finset.sum_const, Finset.card_univ, smul_eq_mul]; ring + have hcross := (Nat.mul_le_mul_left_iff hn).1 hsum + refine ⟨i, fun j => hi j (Finset.mem_univ j), ?_⟩ + have hbits := Nat.mul_le_mul_left (Fintype.card P) + (hl.trans (Nat.le_mul_of_pos_left h (Fintype.card_pos (α := Cube n)))) + rw [Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, smul_eq_mul, mul_add] + exact (Nat.add_le_add hcross (by simpa only [mul_left_comm, mul_assoc] using hbits)).trans_eq + (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +section +/- # Choosing which packets to cut after their selectors are known -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +variable {F : Type} [Field F] {n h : ℕ} (A : Expansion F n h) + +/-- Returns `A.cross s i` when `b` holds, and `0` otherwise. -/ +def width (s : A.I) (i : Fin n) (b : Bool) : ℕ := + if b then A.cross s i else 0 + +/-- In the case `false, _`, this construction gives `A.weight s x y`. -/ +def value (s : A.I) (i : Fin n) (x y : Block n h) : + (b : Bool) → (Fin (A.width s i b) → Bool) → F + | false, _ => A.weight s x y + | true, z => A.side s i false x y z * A.side s i true x y z + +/-- An uncut packet has exactly one assignment of zero bits, avoiding +an extra multiplicity in the field. -/ +theorem sum_value (s : A.I) (i : Fin n) (x y : Block n h) (b : Bool) : + ∑ z, A.value s i x y b z = A.weight s x y := by + cases b + · change (∑ _z : Fin 0 → Bool, A.weight s x y) = _ + simp + · exact (A.split s i x y).symm + +variable {P : Type} + +/-- The indexing data represented by `(p : P) → Fin (A.width (s p) i (b p)) → Bool`. -/ +abbrev Wires (s : P → A.I) (i : Fin n) (b : P → Bool) := + (p : P) → Fin (A.width (s p) i (b p)) → Bool + +variable [Fintype P] [DecidableEq P] + +theorem sum_wires (x y : P → Block n h) (s : P → A.I) (i : Fin n) (b : P → Bool) : + (∑ z : A.Wires s i b, ∏ p, A.value (s p) i (x p) (y p) (b p) (z p)) = + ∏ p, A.weight (s p) (x p) (y p) := by + rw [← Fintype.prod_sum (fun p z => A.value (s p) i (x p) (y p) (b p) z)] + simp only [sum_value] + +/-- Both the coordinate and the subset of packets to split may depend +on the entire selector tuple. -/ +theorem adaptive (x y : P → Block n h) (cut : (P → A.I) → Fin n) + (split : (P → A.I) → P → Bool) : + (∑ s, ∑ z : A.Wires s (cut s) (split s), + ∏ p, A.value (s p) (cut s) (x p) (y p) (split s p) (z p)) = + if x = y then 1 else 0 := by + simp only [sum_wires, A.full_product] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Fixing.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Fixing.lean new file mode 100644 index 0000000000..d475e8298a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Fixing.lean @@ -0,0 +1,110 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Physical + +/-! +# Reconnecting processor inputs + +Copies at the same input position have the same label. Consequently +all occurrences of a broadcast or physical bit are colocated at a +single worker. Only literal bits may require additional communication. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +/-- Indexes the pin by the coordinates of `(Fin (3 * r) × Fin l) ⊕ Fin b ⊕ Links.Slot (3 * r) +N`. -/ +abbrev Pin (N l b r : ℕ) := (Fin (3 * r) × Fin l) ⊕ Fin b ⊕ Links.Slot (3 * r) N + +namespace Pin + +variable {N l b r : ℕ} + +/-- In the case `.inl (_, i)`, this construction gives `.inl i`. -/ +def position : Pin N l b r → Fin l ⊕ Fin b ⊕ Fin (N / 4) + | .inl (_, i) => .inl i + | .inr (.inl i) => .inr (.inl i) + | .inr (.inr i) => .inr (.inr (Links.address i)) + +/-- The value specified by `y (.inl (u, i))`. -/ +def literal (y : Pin N l b r → Bool) (u : Fin (3 * r)) (i : Fin l) := y (.inl (u, i)) + +/-- Computes the broadcast by the application `y (.inr (.inl i))`. -/ +def broadcast (y : Pin N l b r → Bool) (i : Fin b) := y (.inr (.inl i)) + +/-- Computes the link by the application `y (.inr (.inr i))`. -/ +def link (y : Pin N l b r → Bool) (i : Links.Slot (3 * r) N) := y (.inr (.inr i)) + +variable (f : Fin l ⊕ Fin b ⊕ Fin (N / 4) → Worker r) + +/-- Computes the dst by the application `f e.position`. -/ +def dst (e : Pin N l b r) : Worker r := f e.position + +/-- In the case `.inl (u, _)`, this construction gives `(Worker.index r).symm u`. -/ +def src (e : Pin N l b r) : Worker r := + match e with + | .inl (u, _) => (Worker.index r).symm u + | .inr _ => dst f e + +end Pin +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- # Summing over copies of the literal bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Pin + +open Finset +variable {F : Type} [Field F] {N l b r : ℕ} + +/-- Each worker imposes only its own literal, without knowing the +program or wiring information provided to any other processor. -/ +def mask (F : Type) [Field F] (u : Worker r) (s : Fin l → Bool) (y : Pin N l b r → Bool) : F := + if literal y (Worker.index r u) = s then 1 else 0 + +theorem mask_local (u : Worker r) (s : Fin l → Bool) (y z : Pin N l b r → Bool) + (f : Fin l ⊕ Fin b ⊕ Fin (N / 4) → Worker r) (he : ∀ e, src f e = u → y e = z e) : + mask F u s y = mask F u s z := by + have h : literal y (Worker.index r u) = literal z (Worker.index r u) := + funext (fun i => he (.inl (Worker.index r u, i)) ((Worker.index r).symm_apply_apply u)) + rw [mask, mask, h] + +private theorem masks (ξ : Fin (3 * r) → Fin l → Bool) (y : Pin N l b r → Bool) : + (∏ u, mask F u (ξ (Worker.index r u)) y) = if literal y = ξ then 1 else 0 := by + by_cases h : literal y = ξ + · simp [mask, h] + · rw [ite_eq_right h] + obtain ⟨u, hu⟩ := Function.ne_iff.mp h + refine prod_eq_zero (mem_univ ((Worker.index r).symm u)) ?_ + simp [mask, hu] + +private def coordinates (N l b r : ℕ) : + (Pin N l b r → Bool) ≃ (Fin (3 * r) → Fin l → Bool) × (Fin b → Bool) × (Links.Slot (3 * r) N → + Bool) := + (Equiv.sumPiEquivProdPi (fun _ => Bool)).trans + ((Equiv.curry _ _ _).prodCongr (Equiv.sumPiEquivProdPi (fun _ => Bool))) + +theorem sum_masks (ξ : Fin (3 * r) → Fin l → Bool) + (g : (Fin (3 * r) → Fin l → Bool) → (Fin b → Bool) → (Links.Slot (3 * r) N → Bool) → F) : + (∑ y : Pin N l b r → Bool, (∏ u, mask F u (ξ (Worker.index r u)) y) * + g (literal y) (broadcast y) (link y)) = ∑ z, ∑ t, g ξ z t := by + simp only [masks] + rw [← (coordinates N l b r).symm.sum_comp, Fintype.sum_prod_type] + change (∑ a, ∑ x : (Fin b → Bool) × (Links.Slot (3 * r) N → Bool), + (if a = ξ then (1 : F) else 0) * g a x.1 x.2) = _ + rw [sum_comm] + simp only [ite_mul, one_mul, zero_mul, sum_ite_eq', mem_univ, ite_true] + rw [Fintype.sum_prod_type] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Pin +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Input.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Input.lean new file mode 100644 index 0000000000..99575e86d5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Input.lean @@ -0,0 +1,54 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Wide +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute + +/-! # Indexing independent copies of a bit bundle -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +/-- Add a copy at index zero and shift the indices of existing copies. -/ +def nextPort {α β : Type} {d : ℕ} (e : β ≃ Fin d × α) : + α ⊕ β ≃ Fin (d + 1) × α where + toFun := Sum.elim (fun i => (0, i)) (fun j => ((e j).1.succ, (e j).2)) + invFun := fun p => Fin.cases (.inl p.2) (fun i => .inr (e.symm (i, p.2))) p.1 + left_inv := by rintro (i | j) <;> simp + right_inv := by + rintro ⟨j, i⟩ + induction j using Fin.cases <;> simp + +/-- The first copy has index zero. Positions inside each copy are unchanged. -/ +def port (a : Wire) : (d : ℕ) → slots (copies a d) ≃ Fin d × slots a + | 0 => (Equiv.equivEmpty _).symm + | d + 1 => nextPort (port a d) + +/-- In the case `0, _`, this construction gives `()`. -/ +def bundle (a : Wire) : (d : ℕ) → (Fin d → Val a) → Val (copies a d) + | 0, _ => () + | d + 1, x => (x 0, bundle a d (fun i => x i.succ)) + +theorem bits_bundle (a : Wire) (d : ℕ) (x : Fin d → Val a) (i : slots (copies a d)) : + bits (copies a d) (bundle a d x) i = bits a (x (port a d i).1) (port a d i).2 := by + induction d with + | zero => exact i.elim + | succ d ih => + cases i with + | inl i => rfl + | inr i => exact ih (fun j => x j.succ) i + +theorem power_bundle {F : Type} [Field F] {a b : Wire} (k : Val a → Val b → F) + (d : ℕ) (x : Fin d → Val a) (y : Fin d → Val b) : + power k d (bundle a d x) (bundle b d y) = ∏ i, k (x i) (y i) := by + induction d with + | zero => simp [power] + | succ d ih => rw [Fin.prod_univ_succ, bundle, bundle, power, ih] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Physical.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Physical.lean new file mode 100644 index 0000000000..20ec5f29be --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Physical.lean @@ -0,0 +1,986 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Algebra.Group.Fin.Basic +public import Mathlib.Logic.Equiv.Fin.Basic +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Order.Interval.Finset.Fin +public import Mathlib.Tactic.Linarith +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.TemplateSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.AlphabetCode + +/-! +# Routing virtual bits over complete physical links + +Bit number `i` of a pair passes through processor `i % R`. If that +processor is an endpoint, the path is direct. The two orientations of +each physical link use even and odd positions. At a given endpoint, +each other endpoint is allotted a disjoint interval of quotients `i/R`. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +open Finset +variable {R n : ℕ} + +/-- The subtype of `p : Fin R × Fin R` satisfying `p.1 < p.2`. -/ +abbrev Link (R : ℕ) := {p : Fin R × Fin R // p.1 < p.2} +/-- Indexes the slot by the coordinates of `Link R × Fin (n / (4 * R))`. -/ +abbrev Slot (R n : ℕ) := Link R × Fin (n / (4 * R)) + +/-- The sum of the two processor indices modulo R gives at most R +matchings. Both endpoints use the very same address for a shared bit. -/ +def address (s : Slot R n) : Fin (n / 4) := + Fin.castLE (by rw [← Nat.div_div_eq_div_mul]; exact Nat.mul_div_le _ _) + (finProdFinEquiv (s.1.val.1 + s.1.val.2, s.2)) + +theorem address_injective {s t : Slot R n} (u : Fin R) + (hs : u = s.1.val.1 ∨ u = s.1.val.2) (ht : u = t.1.val.1 ∨ u = t.1.val.2) + (h : address s = address t) : s = t := by + have he : (s.1.val.1 + s.1.val.2, s.2) = (t.1.val.1 + t.1.val.2, t.2) := + finProdFinEquiv.injective (Fin.ext (congrArg (fun i : Fin (n / 4) => i.val) h)) + obtain ⟨he, hp⟩ := Prod.mk.inj he + refine Prod.ext (Subtype.ext ?_) hp + have h₁ := s.1.property + have h₂ := t.1.property + rcases hs with hs | hs <;> rcases ht with ht | ht <;> + simp [← hs, ← ht, add_comm] at he <;> apply Prod.ext <;> omega + +/-- Indexes the virtual by the coordinates of `Σ p : Link R, Fin (q p.val.1 p.val.2)`. -/ +abbrev Virtual (q : Fin R → Fin R → ℕ) := Σ p : Link R, Fin (q p.val.1 p.val.2) + +variable {q : Fin R → Fin R → ℕ} + +/-- Uses `⟨b.2.val % R, Nat.mod_lt _ b.1.val.1.pos⟩` as the representation. -/ +def via (b : Virtual q) : Fin R := + ⟨b.2.val % R, Nat.mod_lt _ b.1.val.1.pos⟩ + +/-- There is a leg from each endpoint to the intermediate processor, +except when they coincide. -/ +abbrev Leg (q : Fin R → Fin R → ℕ) := + Σ b : Virtual q, {u : Fin R // (u = b.1.val.1 ∨ u = b.1.val.2) ∧ u ≠ via b} + +/-- Returns `l.1.1.val.2` when `l.2.val = l.1.1.val.1` holds, and `l.1.1.val.1` otherwise. -/ +def other (l : Leg q) : Fin R := + if l.2.val = l.1.1.val.1 then l.1.1.val.2 else l.1.1.val.1 + +theorem has_leg (b : Virtual q) : ∃ l : Leg q, l.1 = b := by + by_cases h : b.1.val.1 = via b + · exact ⟨⟨b, b.1.val.2, .inr rfl, h ▸ b.1.property.ne'⟩, rfl⟩ + · exact ⟨⟨b, b.1.val.1, .inl rfl, h⟩, rfl⟩ + +private theorem endpoints (l : Leg q) : + (l.2.val = l.1.1.val.1 ∧ other l = l.1.1.val.2) ∨ + (l.2.val = l.1.1.val.2 ∧ other l = l.1.1.val.1) := by + unfold other + split + · exact .inl ⟨by assumption, rfl⟩ + · exact .inr ⟨l.2.property.1.resolve_left (by assumption), rfl⟩ + +theorem index_lt (hs : ∀ u v, q u v = q v u) (l : Leg q) : + l.1.2.val < q l.2.val (other l) := by + rcases endpoints l with ⟨h, h'⟩ | ⟨h, h'⟩ + · rw [h, h']; exact l.1.2.isLt + · rw [h, h']; exact l.1.2.isLt.trans_eq (hs _ _) + +/-- The sum of `(p z / R + 1)` indexed by `z ∈ Iio v`. -/ +def offset (p : Fin R → ℕ) (v : Fin R) : ℕ := + ∑ z ∈ Iio v, (p z / R + 1) + +private theorem offset_le (p : Fin R → ℕ) (v : Fin R) (s : Finset (Fin R)) + (hs : ∀ z ≤ v, z ∈ s) : + offset p v + p v / R + 1 ≤ ∑ z ∈ s, (p z / R + 1) := by + have h : insert v (Iio v) ⊆ s := by + intro z hz + simp only [mem_insert, mem_Iio] at hz + exact hs z (by omega) + have hb := sum_le_sum_of_subset (f := fun z => p z / R + 1) h + rw [sum_insert (by simp)] at hb + unfold offset + omega + +private theorem offset_unique (p : Fin R → ℕ) {v z : Fin R} {i j : ℕ} + (hi : i < p v) (hj : j < p z) + (h : offset p v + i / R = offset p z + j / R) : v = z ∧ i / R = j / R := by + have before (a b : Fin R) (hab : a < b) : offset p a + p a / R + 1 ≤ offset p b := + offset_le p a (Iio b) (fun _ hx => mem_Iio.mpr (lt_of_le_of_lt hx hab)) + have := Nat.zero_le (i / R) + have := Nat.zero_le (j / R) + rcases lt_trichotomy v z with hv | rfl | hv + · have := before v z hv + have := Nat.div_le_div_right (c := R) hi.le + omega + · exact ⟨rfl, Nat.add_left_cancel h⟩ + · have := before z v hv + have := Nat.div_le_div_right (c := R) hj.le + omega + +theorem capacity (p : Fin R → ℕ) (hp : ∑ v, p v ≤ n / 64) (hn : 64 * R ^ 2 ≤ n) + (v : Fin R) {i : ℕ} (hi : i < p v) : + 2 * (offset p v + i / R) + 1 < n / (4 * R) := by + have hb : offset p v + i / R + 1 ≤ ∑ z, (p z / R + 1) := by + have := offset_le p v univ (fun z _ => mem_univ z) + have := Nat.div_le_div_right (c := R) hi.le + omega + have hd : (offset p v + i / R + 1) * R ≤ n / 64 + R ^ 2 := by + calc + _ ≤ (∑ z, (p z / R + 1)) * R := Nat.mul_le_mul_right R hb + _ ≤ ∑ z, (p z + R) := by + rw [sum_mul] + apply sum_le_sum + intro z _ + rw [Nat.add_mul, Nat.one_mul] + exact Nat.add_le_add_right (Nat.div_mul_le_self _ _) _ + _ ≤ n / 64 + R ^ 2 := by + simp only [sum_add_distrib, sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul, pow_two] + exact Nat.add_le_add_right hp _ + have hr := v.pos + apply Nat.lt_of_succ_le + apply (Nat.le_div_iff_mul_le (by omega)).mpr + nlinarith only [hd, hn, Nat.div_mul_le_self n 64] + +/-- The actual unordered processor pair carrying a leg. -/ +def link (l : Leg q) : Link R := + if h : l.2.val < via l.1 then ⟨(l.2.val, via l.1), h⟩ + else ⟨(via l.1, l.2.val), lt_of_le_of_ne (le_of_not_gt h) l.2.property.2.symm⟩ + +theorem incident (l : Leg q) (u : Fin R) : + (u = (link l).val.1 ∨ u = (link l).val.2) ↔ (u = l.2.val ∨ u = via l.1) := by + unfold link + split + · rfl + · exact or_comm + +/-- Both endpoints can read the bit, including on a direct path. -/ +theorem at_endpoint (b : Virtual q) (u : Fin R) (h : u = b.1.val.1 ∨ u = b.1.val.2) : + ∃ l : Leg q, l.1 = b ∧ (u = (link l).val.1 ∨ u = (link l).val.2) := by + by_cases he : u = via b + · obtain ⟨l, hl⟩ := has_leg b + exact ⟨l, hl, (incident l u).mpr (.inr (by rw [hl, he]))⟩ + · let l : Leg q := ⟨b, u, h, he⟩ + exact ⟨l, rfl, (incident l u).mpr (.inl rfl)⟩ + +/-- The quantity computed by `2 * (offset (q l.2.val) (other l) + l.1.2.val / R) + if l.2.val < +via l.1 then 0 else 1`. -/ +def position (l : Leg q) : ℕ := + 2 * (offset (q l.2.val) (other l) + l.1.2.val / R) + if l.2.val < via l.1 then 0 else 1 + +private theorem leg_ext {l k : Leg q} (hu : l.2.val = k.2.val) (hv : other l = other k) + (hi : l.1.2.val = k.1.2.val) : l = k := by + have he : l.1.1 = k.1.1 := by + apply Subtype.ext + have h₁ := l.1.1.property + have h₂ := k.1.1.property + rcases endpoints l with ⟨h, h'⟩ | ⟨h, h'⟩ <;> + rcases endpoints k with ⟨g, g'⟩ | ⟨g, g'⟩ <;> apply Prod.ext <;> omega + rcases l with ⟨⟨a, i⟩, u⟩ + rcases k with ⟨⟨b, j⟩, v⟩ + change a = b at he + subst b + have hh : i = j := Fin.ext hi + subst j + have : u = v := Subtype.ext hu + subst v + rfl + +variable (hs : ∀ u v, q u v = q v u) (hq : ∀ u, ∑ v, q u v ≤ n / 64) (hn : 64 * R ^ 2 ≤ n) + +/-- The value specified by `(link l, ⟨position l, by have hb := capacity _ (hq l.2.val) hn _ +(index_lt hs l) unfold position split <;> omega⟩)`. -/ +def slot (l : Leg q) : Slot R n := + (link l, ⟨position l, by + have hb := capacity _ (hq l.2.val) hn _ (index_lt hs l) + unfold position + split <;> omega⟩) + +theorem injective : Function.Injective (slot hs hq hn) := by + intro l k h + have he : (link l).val = (link k).val := congrArg (fun s => s.1.val) h + have hp : position l = position k := congrArg (fun s => s.2.val) h + have hh : l.2.val = k.2.val ∧ via l.1 = via k.1 ∧ + offset (q l.2.val) (other l) + l.1.2.val / R = + offset (q k.2.val) (other k) + k.1.2.val / R := by + unfold link at he + unfold position at hp + split_ifs at he hp <;> simp only [Prod.mk.injEq] at he <;> omega + obtain ⟨hu, hm, ho⟩ := hh + have ha := index_lt hs k + rw [← hu] at ho ha + obtain ⟨hv, hd⟩ := offset_unique _ (index_lt hs l) ha ho + apply leg_ext hu hv + have hr : l.1.2.val % R = k.1.2.val % R := congrArg Fin.val hm + calc + _ = l.1.2.val % R + R * (l.1.2.val / R) := (Nat.mod_add_div ..).symm + _ = _ := by rw [hr, hd, Nat.mod_add_div] + +/-- Fixing unused slots to zero makes the physical encoding unique. -/ +theorem encode (x : Virtual q → Bool) : + ∃! y : Slot R n → Bool, (∀ l, y (slot hs hq hn l) = x l.1) ∧ + (∀ s ∉ Set.range (slot hs hq hn), y s = false) := by + let y := Function.extend (slot hs hq hn) (fun l => x l.1) (fun _ => false) + have hy (l : Leg q) : y (slot hs hq hn l) = x l.1 := + (injective hs hq hn).extend_apply _ _ _ + have hz (s : Slot R n) (h : s ∉ Set.range (slot hs hq hn)) : y s = false := + Function.extend_apply' _ _ _ h + refine ⟨y, ⟨hy, hz⟩, fun z h => ?_⟩ + funext s + by_cases hr : s ∈ Set.range (slot hs hq hn) + · obtain ⟨l, rfl⟩ := hr + rw [hy, h.1] + · rw [hz s hr, h.2 s hr] + +/-- When the two legs agree at their shared intermediate processor, +they determine a unique virtual bit assignment. -/ +theorem decode (y : Slot R n → Bool) + (h : ∀ l k, l.1 = k.1 → y (slot hs hq hn l) = y (slot hs hq hn k)) : + ∃! x : Virtual q → Bool, ∀ l, y (slot hs hq hn l) = x l.1 := by + choose g hg using (has_leg (q := q)) + refine ⟨fun b => y (slot hs hq hn (g b)), fun l => h _ _ (hg _).symm, ?_⟩ + intro x hx + funext b + exact (congrArg x (hg b)).symm.trans (hx (g b)).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links +end + +/- +# Contracting local tables over physical links + +A processor sees the shared positions of its incident links. It tests +equality at every relay and pins unused positions to zero. Each virtual +assignment then contributes exactly once, in any characteristic. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +variable {R n : ℕ} {q : Fin R → Fin R → ℕ} + +open Classical in +/-- Requires `u = p.val.1 ∨ u = p.val.2`. -/ +def sees (u : Fin R) (p : Link R) : Prop := u = p.val.1 ∨ u = p.val.2 + +open Classical in +/-- Read the incident bits at synchronized addresses. Other positions +in the reserved link interval contain zero. -/ +def view (u : Fin R) (y : Slot R n → Bool) : Fin (n / 4) → Bool := + Function.extend (fun s : {s : Slot R n // sees u s.1} => address s.val) + (fun s => y s.val) (fun _ => false) + +open Classical in +theorem view_address (u : Fin R) (y : Slot R n → Bool) (s : Slot R n) (h : sees u s.1) : + view u y (address s) = y s := by + have hi : Function.Injective (fun t : {s : Slot R n // sees u s.1} => address t.val) := + fun a b he => Subtype.ext (address_injective u a.2 b.2 he) + exact hi.extend_apply _ _ ⟨s, h⟩ + +variable (hs : ∀ u v, q u v = q v u) (hq : ∀ u, ∑ v, q u v ≤ n / 64) (hn : 64 * R ^ 2 ≤ n) + +open Classical in +/-- The valid of type `Prop` for the given inputs. -/ +def valid (u : Fin R) (t : Fin (n / 4) → Bool) : Prop := + (∀ l k, l.1 = k.1 → via l.1 = u → + t (address (slot hs hq hn l)) = t (address (slot hs hq hn k))) ∧ + (∀ s ∉ Set.range (slot hs hq hn), u = s.1.val.1 → t (address s) = false) + +open Classical in +/-- Returns `t (address (slot hs hq hn (at_endpoint b u h).choose))` when `h : sees u b.1` +holds, and `false` otherwise. -/ +def receive (u : Fin R) (t : Fin (n / 4) → Bool) (b : Virtual q) : Bool := + if h : sees u b.1 then t (address (slot hs hq hn (at_endpoint b u h).choose)) else false + +open Classical in +private def Tied (x : Virtual q → Bool) (y : Slot R n → Bool) : Prop := + (∀ l, y (slot hs hq hn l) = x l.1) ∧ ∀ s ∉ Set.range (slot hs hq hn), y s = false + +open Classical in +private theorem via_sees (l : Leg q) : sees (via l.1) (slot hs hq hn l).1 := + (incident l _).mpr (.inr rfl) + +open Classical in +private theorem valid_of_tied {x y} (h : Tied hs hq hn x y) (u : Fin R) : + valid hs hq hn u (view u y) := by + constructor + · intro l k hl hu + subst u + have hk : sees (via l.1) (slot hs hq hn k).1 := hl ▸ via_sees hs hq hn k + rw [view_address _ _ _ (via_sees hs hq hn l), view_address _ _ _ hk, h.1, h.1, hl] + · intro s he hu + rw [view_address _ _ _ (.inl hu), h.2 s he] + +open Classical in +private theorem tied_of_valid (y : Slot R n → Bool) + (hy : ∀ u, valid hs hq hn u (view u y)) : ∃! x, Tied hs hq hn x y := by + have he (l k : Leg q) (h : l.1 = k.1) : y (slot hs hq hn l) = y (slot hs hq hn k) := by + have hh := (hy (via l.1)).1 l k h rfl + have hk : sees (via l.1) (slot hs hq hn k).1 := h ▸ via_sees hs hq hn k + rwa [view_address _ _ _ (via_sees hs hq hn l), view_address _ _ _ hk] at hh + obtain ⟨x, hx, hu⟩ := decode hs hq hn y he + refine ⟨x, ⟨hx, ?_⟩, fun z hz => hu z hz.1⟩ + intro s h + have := (hy s.1.val.1).2 s h rfl + rwa [view_address _ _ _ (.inl rfl)] at this + +variable {F : Type} [Field F] + +open Classical in +/-- A table whose input is only the processor's reserved interval. -/ +def site (g : Fin R → (Virtual q → Bool) → F) (u : Fin R) (t : Fin (n / 4) → Bool) : F := + if valid hs hq hn u t then g u (receive hs hq hn u t) else 0 + +open Classical in +theorem eval (g : Fin R → (Virtual q → Bool) → F) + (hg : ∀ u x x', (∀ b, sees u b.1 → x b = x' b) → g u x = g u x') : + (∑ x, ∏ u, g u x) = ∑ y, ∏ u, site hs hq hn g u (view u y) := by + have heq (x y) (h : Tied hs hq hn x y) (u : Fin R) : + site hs hq hn g u (view u y) = g u x := by + rw [site, ite_eq_left (valid_of_tied hs hq hn h u)] + apply hg + intro b hb + rw [receive, dite_eq_left hb] + obtain ⟨he, hl⟩ := (at_endpoint b u hb).choose_spec + rw [view_address u y (slot hs hq hn _) hl, h.1, he] + calc + _ = ∑ x, ∑ y, if Tied hs hq hn x y then ∏ u, g u x else 0 := by + apply Finset.sum_congr rfl + intro x _ + obtain ⟨y, hy, hu⟩ : ∃! y, Tied hs hq hn x y := encode hs hq hn x + rw [Fintype.sum_eq_single y (fun z hz => ite_eq_right (fun h => hz (hu z h))), ite_eq_left hy] + _ = ∑ y, ∑ x, if Tied hs hq hn x y then ∏ u, g u x else 0 := Finset.sum_comm + _ = _ := by + apply Finset.sum_congr rfl + intro y _ + by_cases h : ∀ u, valid hs hq hn u (view u y) + · obtain ⟨x, hx, hu⟩ := tied_of_valid hs hq hn y h + rw [Fintype.sum_eq_single x (fun z hz => ite_eq_right (fun h => hz (hu z h))), + ite_eq_left hx] + simp_rw [heq x y hx] + · obtain ⟨u, hu⟩ := not_forall.mp h + have hb (x) : ¬ Tied hs hq hn x y := fun h => hu (valid_of_tied hs hq hn h u) + simp only [hb, ite_false, Finset.sum_const_zero] + exact (Finset.prod_eq_zero (Finset.mem_univ u) (ite_eq_right hu)).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links +end + +/- +# Local contraction with arbitrary virtual links + +Parallel edges may be numbered in any prescribed order. Loops are +summed privately so they consume no physical links. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +variable {R n : ℕ} {M : Type} [Fintype M] (src dst : M → Fin R) + +open Classical in +/-- The subtype of `e` satisfying `(src e = u ∧ dst e = v) ∨ (src e = v ∧ dst e = u)`. -/ +abbrev Between (u v : Fin R) := + {e // (src e = u ∧ dst e = v) ∨ (src e = v ∧ dst e = u)} + +open Classical in +/-- Counts the elements of `(Between src dst u v)`. -/ +def count (u v : Fin R) : ℕ := Fintype.card (Between src dst u v) + +open Classical in +/-- The condition `∀ u v, Fin (count src dst u v) ≃ Between src dst u v` on the specified data. -/ +abbrev Numbering := ∀ u v, Fin (count src dst u v) ≃ Between src dst u v + +open Classical in +theorem count_symm (u v : Fin R) : count src dst u v = count src dst v u := by + simp only [count, Between, or_comm] + +open Classical in +theorem count_le (u : Fin R) : + ∑ v, count src dst u v ≤ Fintype.card {e // src e = u ∨ dst e = u} := by + let f : (Σ v, Between src dst u v) → {e // src e = u ∨ dst e = u} := + fun t => ⟨t.2.val, by rcases t.2.property with h | h <;> grind⟩ + have hi : Function.Injective f := by + rintro ⟨v, e⟩ ⟨w, k⟩ he + have eqn : e.val = k.val := congrArg Subtype.val he + have h₁ := e.property + have h₂ := k.property + have : v = w := by grind + subst w + rw [Subtype.ext eqn] + simpa only [Fintype.card_sigma, count] using Fintype.card_le_of_injective f hi + +variable (serial : Numbering src dst) + +open Classical in +/-- Computes the private by the application `Fin (count src dst u u)`. -/ +abbrev Private (u : Fin R) := Fin (count src dst u u) +open Classical in +/-- Indexes the edges by the coordinates of `Virtual (count src dst) ⊕ Σ u, Private src dst u`. -/ +abbrev Edges := Virtual (count src dst) ⊕ Σ u, Private src dst u + +open Classical in +/-- In the case `.inl ⟨p, i⟩`, this construction gives `(serial p.val.1 p.val.2 i).val`. -/ +def edge : Edges src dst → M + | .inl ⟨p, i⟩ => (serial p.val.1 p.val.2 i).val + | .inr ⟨u, i⟩ => (serial u u i).val + +open Classical in +theorem edge_injective : Function.Injective (edge src dst serial) := by + have distinct (p : Link R) (u : Fin R) i j : + (serial p.val.1 p.val.2 i).val ≠ (serial u u j).val := by + have hj := (serial u u j).property + grind + rintro (⟨p, i⟩ | ⟨u, i⟩) (⟨q, j⟩ | ⟨v, j⟩) he <;> dsimp only [edge] at he + · have hj := (serial q.val.1 q.val.2 j).property + have hp := p.property + have hq := q.property + have : p = q := Subtype.ext (Prod.ext (by grind) (by grind)) + subst q + rw [(serial _ _).injective (Subtype.ext he)] + · exact (distinct p v i j he).elim + · exact (distinct q u j i he.symm).elim + · have hi := (serial u u i).property + have hj := (serial v v j).property + have : u = v := by grind + subst v + rw [(serial _ _).injective (Subtype.ext he)] + +open Classical in +theorem edge_surjective : Function.Surjective (edge src dst serial) := by + intro e + have h (u v : Fin R) (huv : u < v) + (he : (src e = u ∧ dst e = v) ∨ (src e = v ∧ dst e = u)) : + ∃ i, edge src dst serial i = e := by + obtain ⟨i, hi⟩ := (serial u v).surjective ⟨e, he⟩ + exact ⟨.inl ⟨⟨(u, v), huv⟩, i⟩, congrArg Subtype.val hi⟩ + rcases lt_trichotomy (src e) (dst e) with hl | he | hl + · exact h _ _ hl (.inl ⟨rfl, rfl⟩) + · obtain ⟨i, hi⟩ := (serial (src e) (src e)).surjective ⟨e, .inl ⟨rfl, he.symm⟩⟩ + exact ⟨.inr ⟨src e, i⟩, congrArg Subtype.val hi⟩ + · exact h _ _ hl (.inr ⟨rfl, rfl⟩) + +open Classical in +/-- The equivalence obtained by `Equiv.ofBijective (edge src dst serial) ⟨edge_injective src dst +serial, edge_surjective src dst serial⟩`. -/ +def ports : Edges src dst ≃ M := + Equiv.ofBijective (edge src dst serial) ⟨edge_injective src dst serial, + edge_surjective src dst serial⟩ + +open Classical in +/-- Reindexes `(Virtual (count src dst) → Bool) × ((u : Fin R) → Private src dst u → Bool)` and +`(M → Bool)` by an equivalence. -/ +def assignments : + (Virtual (count src dst) → Bool) × ((u : Fin R) → Private src dst u → Bool) ≃ (M → Bool) := + ((Equiv.refl _).prodCongr (Equiv.piCurry (fun _ _ => Bool)).symm).trans + ((Equiv.sumArrowEquivProdArrow _ _ _).symm.trans + ((ports src dst serial).arrowCongr (.refl _))) + +open Classical in +private theorem assignments_at (x z) (e : Edges src dst) : + assignments src dst serial (x, z) (ports src dst serial e) = + Sum.elim x (fun p => z p.1 p.2) e := by + unfold assignments + simp only [Equiv.trans_apply, Equiv.arrowCongr_apply, Function.comp_apply, Equiv.symm_apply_apply, + Equiv.refl_apply] + cases e <;> rfl + +open Classical in +private theorem assignments_local (u : Fin R) (x x' z z') + (hx : ∀ b, sees u b.1 → x b = x' b) (hz : z u = z' u) + (e : M) (he : src e = u ∨ dst e = u) : + assignments src dst serial (x, z) e = assignments src dst serial (x', z') e := by + obtain ⟨k, rfl⟩ := (ports src dst serial).surjective e + rw [assignments_at, assignments_at] + rcases k with ⟨p, i⟩ | ⟨v, i⟩ + · apply hx + have h := (serial p.val.1 p.val.2 i).property + change src (serial p.val.1 p.val.2 i).val = u ∨ dst (serial p.val.1 p.val.2 i).val = u at he + change u = p.val.1 ∨ u = p.val.2 + grind + · have h := (serial v v i).property + change src (serial v v i).val = u ∨ dst (serial v v i).val = u at he + have hv : v = u := by grind + subst v + exact congrFun hz i + +variable (hd : ∀ u, Fintype.card {e // src e = u ∨ dst e = u} ≤ n / 64) (hn : 64 * R ^ 2 ≤ n) +variable {F : Type} [Field F] (g : Fin R → (M → Bool) → F) + +open Classical in +/-- The indexed operation `∑ z : Private src dst u → Bool, g u (assignments src dst serial (x, +Function.update (fun _ _ => false) u z))`. -/ +def tally (u : Fin R) (x : Virtual (count src dst) → Bool) : F := + ∑ z : Private src dst u → Bool, + g u (assignments src dst serial (x, Function.update (fun _ _ => false) u z)) + +open Classical in +/-- The indexed operation `site (count_symm src dst) (fun u => (count_le src dst u).trans (hd +u)) hn (tally src dst serial g) u t`. -/ +def worker (u : Fin R) (t : Fin (n / 4) → Bool) : F := + site (count_symm src dst) (fun u => (count_le src dst u).trans (hd u)) hn + (tally src dst serial g) u t + +open Classical in +theorem contract [DecidableEq M] + (hg : ∀ u x y, (∀ e, src e = u ∨ dst e = u → x e = y e) → g u x = g u y) : + (∑ x, ∏ u, g u x) = ∑ y, ∏ u, worker src dst serial hd hn g u (view u y) := by + have ht (u : Fin R) (x x' : Virtual (count src dst) → Bool) + (hx : ∀ b, sees u b.1 → x b = x' b) : + tally src dst serial g u x = tally src dst serial g u x' := by + apply Finset.sum_congr rfl + intro z _ + exact hg _ _ _ (assignments_local src dst serial u _ _ _ _ hx rfl) + unfold worker + rw [← eval _ _ _ _ ht, ← (assignments src dst serial).sum_comp, Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro x _ + unfold tally + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro z _ + apply Finset.prod_congr rfl + intro u _ + exact hg _ _ _ (assignments_local src dst serial u _ _ _ _ (fun _ _ => rfl) + (by simp)) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links +end + +/- +# Routing finite alphabets + +At each endpoint, privately sum over the incident symbols and require +their encodings to match the shared bits. An injective code forces the +same symbol at both ends. A loop needs no shared bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Encoded + +variable {R n : ℕ} {M : Type} (src dst : M → Fin R) +variable (alph : M → Type) (w : M → ℕ) (code : ∀ e, alph e ↪ (Fin (w e) → Bool)) + +open Classical in +/-- The subtype of `e` satisfying `src e ≠ dst e`. -/ +abbrev Shared := {e // src e ≠ dst e} +open Classical in +/-- Indexes the bits by the coordinates of `Σ e : Shared src dst, Fin (w e.val)`. -/ +abbrev Bits := Σ e : Shared src dst, Fin (w e.val) +open Classical in +/-- The indexing data represented by `(e : {e // src e = u ∨ dst e = u}) → alph e.val`. -/ +abbrev Local (u : Fin R) := (e : {e // src e = u ∨ dst e = u}) → alph e.val + +open Classical in +/-- Computes the left by the application `src b.1.val`. -/ +abbrev left (b : Bits src dst w) := src b.1.val +open Classical in +/-- Computes the right by the application `dst b.1.val`. -/ +abbrev right (b : Bits src dst w) := dst b.1.val + +open Classical in +/-- Evaluates `x e.val` at the input `e`. -/ +def restrict (u : Fin R) (x : ∀ e, alph e) : Local src dst alph u := + fun e => x e.val + +open Classical in +/-- The condition `∀ (e : Shared src dst) (he : src e.val = u ∨ dst e.val = u) (j : Fin (w +e.val)), code e.val (t ⟨e.val, he⟩) j = b ⟨e, j⟩` on the specified data. -/ +def agrees (u : Fin R) (b : Bits src dst w → Bool) (t : Local src dst alph u) : Prop := + ∀ (e : Shared src dst) (he : src e.val = u ∨ dst e.val = u) (j : Fin (w e.val)), + code e.val (t ⟨e.val, he⟩) j = b ⟨e, j⟩ + +open Classical in +private abbrev State := (Bits src dst w → Bool) × ((u : Fin R) → Local src dst alph u) + +open Classical in +private def encode (x : ∀ e, alph e) : State src dst alph w := + (fun b => code b.1.val (x b.1.val) b.2, fun u => restrict src dst alph u x) + +open Classical in +private theorem injective : Function.Injective (encode src dst alph w code) := by + intro x y he + funext e + exact congrArg (fun s : State src dst alph w => s.2 (src e) ⟨e, .inl rfl⟩) he + +open Classical in +private theorem coherent (s : State src dst alph w) : + (∀ u, agrees src dst alph w code u s.1 (s.2 u)) ↔ + ∃ x, encode src dst alph w code x = s := by + constructor + · intro ok + let x (e : M) := s.2 (src e) ⟨e, .inl rfl⟩ + refine ⟨x, Prod.ext ?_ ?_⟩ + · funext ⟨e, j⟩ + exact ok (src e.val) e (.inl rfl) j + · funext u ⟨e, he⟩ + by_cases h : src e = u + · subst u; rfl + · have hne : src e ≠ dst e := fun heq => h (heq.trans (he.resolve_left h)) + apply (code e).injective + funext j + exact (ok (src e) ⟨e, hne⟩ (.inl rfl) j).trans (ok u ⟨e, hne⟩ he j).symm + · rintro ⟨x, rfl⟩ _ _ _ _ + rfl + +variable [Fintype M] [∀ e, Fintype (alph e)] + +open Classical in +theorem load (u : Fin R) : + Fintype.card {b : Bits src dst w // left src dst w b = u ∨ right src dst w b = u} = + ∑ e ∈ Finset.univ.filter (fun e => src e ≠ dst e ∧ (src e = u ∨ dst e = u)), w e := by + let T := {e // src e ≠ dst e ∧ (src e = u ∨ dst e = u)} + let E : {b : Bits src dst w // left src dst w b = u ∨ right src dst w b = u} ≃ + (Σ e : T, Fin (w e.val)) := { + toFun := fun b => ⟨⟨b.1.1.val, b.1.1.property, b.2⟩, b.1.2⟩ + invFun := fun s => ⟨⟨⟨s.1.val, s.1.property.1⟩, s.2⟩, s.1.property.2⟩ + left_inv _ := rfl + right_inv _ := rfl + } + rw [Fintype.card_congr E, Fintype.card_sigma] + simp only [Fintype.card_fin] + exact (Finset.sum_subtype _ (by simp) w).symm + +variable [DecidableEq M] +variable (hd : ∀ u, ∑ e ∈ Finset.univ.filter + (fun e => src e ≠ dst e ∧ (src e = u ∨ dst e = u)), w e ≤ n / 64) (hn : 64 * R ^ 2 ≤ n) + +variable {F : Type} [Field F] (g : Fin R → (∀ e, alph e) → F) + +open Classical in +/-- Selects the appropriate branch of `if h : Nonempty (∀ e, alph e) then g u (fun e => if he : +src e = u ∨ dst e = u then t ⟨e, he⟩ else (choice h) e) else 0`. -/ +def localize (u : Fin R) (t : Local src dst alph u) : F := + if h : Nonempty (∀ e, alph e) then + g u (fun e => if he : src e = u ∨ dst e = u then t ⟨e, he⟩ else (choice h) e) + else 0 + +open Classical in +/-- The value specified by `∑ t, if agrees src dst alph w code u b t then localize src dst alph +g u t else 0`. -/ +def bitSite (u : Fin R) (b : Bits src dst w → Bool) : F := + ∑ t, if agrees src dst alph w code u b t then localize src dst alph g u t else 0 + +open Classical in +private theorem bitSite_local (u : Fin R) (x y : Bits src dst w → Bool) + (he : ∀ e, left src dst w e = u ∨ right src dst w e = u → x e = y e) : + bitSite src dst alph w code g u x = bitSite src dst alph w code g u y := by + have ho (t) : agrees src dst alph w code u x t ↔ agrees src dst alph w code u y t := + ⟨fun h e h' j => (h e h' j).trans (he ⟨e, j⟩ h'), + fun h e h' j => (h e h' j).trans (he ⟨e, j⟩ h').symm⟩ + simp only [bitSite, ho] + +open Classical in +private theorem bit_sum + (hg : ∀ u x y, (∀ e, src e = u ∨ dst e = u → x e = y e) → g u x = g u y) : + (∑ x, ∏ u, g u x) = ∑ b, ∏ u, bitSite src dst alph w code g u b := by + let enc := encode src dst alph w code + let ok := agrees src dst alph w code + let v := localize src dst alph g + have hv (u) (x) : v u ((enc x).2 u) = g u x := by + unfold v localize + rw [dite_eq_left (show Nonempty (∀ e, alph e) from ⟨x⟩)] + exact hg _ _ _ (fun e he => by rw [dite_eq_left he]; rfl) + have heq (s : State src dst alph w) : + (∑ x, if enc x = s then ∏ u, g u x else 0) = + ∏ u, if ok u s.1 (s.2 u) then v u (s.2 u) else 0 := by + by_cases h : ∀ u, ok u s.1 (s.2 u) + · obtain ⟨x, hx⟩ := (coherent src dst alph w code s).mp h + change enc x = s at hx + simp only [h, ite_true] + rw [← hx] + have hi : Function.Injective enc := injective src dst alph w code + simp only [hi.eq_iff, Finset.sum_ite_eq', Finset.mem_univ, ite_true, hv] + · have hn (x) : enc x ≠ s := + fun e => h ((coherent src dst alph w code s).mpr ⟨x, e⟩) + obtain ⟨u, hu⟩ := not_forall.mp h + simp only [hn, ite_false, Finset.sum_const_zero] + exact (Finset.prod_eq_zero (Finset.mem_univ u) (ite_eq_right hu)).symm + calc + _ = ∑ x, ∑ s, if enc x = s then ∏ u, g u x else 0 := by simp + _ = ∑ s, ∑ x, if enc x = s then ∏ u, g u x else 0 := Finset.sum_comm + _ = _ := by + simp_rw [heq] + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro b _ + unfold bitSite + rw [Fintype.prod_sum] + +open Classical in +/-- The indexed operation `Links.worker _ _ serial (fun u => (load src dst w u).le.trans (hd u)) +hn (bitSite src dst alph w code g)`. -/ +def worker (serial : Links.Numbering (left src dst w) (right src dst w)) : + Fin R → (Fin (n / 4) → Bool) → F := + Links.worker _ _ serial (fun u => (load src dst w u).le.trans (hd u)) hn + (bitSite src dst alph w code g) + +open Classical in +/-- The alphabet on each edge may be empty. Only edges joining distinct +processors contribute to the bandwidth condition. -/ +theorem contract + (hg : ∀ u x y, (∀ e, src e = u ∨ dst e = u → x e = y e) → g u x = g u y) + (serial : Links.Numbering (left src dst w) (right src dst w) := + fun _ _ => (Fintype.equivFin _).symm) : + (∑ x, ∏ u, g u x) = + ∑ y, ∏ u, worker src dst alph w code hd hn g serial u (Links.view u y) := by + rw [bit_sum src dst alph w code g hg] + exact Links.contract _ _ serial _ hn _ (bitSite_local src dst alph w code g) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Encoded +end + +/- +# Link usage under a valid report + +A shared class transmits its selector and crossing bits. Other classes +transmit the individual packet positions. Loops consume no bandwidth. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Spectral Finset +variable {F : Type} [Field F] {n h d r : ℕ} (A : Expansion F n h) + (hn : 2 ≤ n) (N : ℕ) (s : Packet n r d → A.I) (u : Worker r) + +private theorem owner_plan (x : Label n r) : + A.owner hn N (A.report hn s) x = (A.plan hn N s).base x := by + rw [owner, report_groups] + rfl + +private theorem shared_plan (p : Packet n r d) : + A.shared N (A.report hn s) (packetClass hn (A.report hn s).1 p) = true ↔ + ¬(A.plan hn N s).marked p := by + rw [shared, decide_eq_true_eq, report_groups] + change (_ ∉ _ ∧ _ ∉ _) ↔ ¬ ∃ b, group p.1 (A.report hn s).1 b ∈ _ + simp only [packetClass, Bool.exists_bool, not_or] + +private def bill (R : A.Report r d) (e : Edge n r d h) (k : ℕ) : ℕ := + if A.src hn N R e ≠ A.dst hn N R e ∧ (A.src hn N R e = u ∨ A.dst hn N R e = u) + then k else 0 + +private theorem class_sumFromSiteBound : + let R := A.report hn s + ∑ c, A.bill hn N u R (.inr c) (A.classWidth R c) = + ∑ p, A.bill hn N u R (.inr (packetClass hn R.1 p)) ((A.plan hn N s).q p) := by + intro R + let f (c : Class r) (z : A.I) := A.bill hn N u R (.inr c) + (A.cross z R.1 + Nat.clog 2 (Fintype.card A.I)) + calc + _ = A.total R f := by + unfold total + conv_rhs => rw [Fintype.sum_prod_type] + apply sum_congr rfl + intro c _ + unfold f bill classWidth + split <;> simp_all + _ = _ := A.total_counts hn s R.1 f + +private abbrev Index (n h : ℕ) := Bool × Cube n × Fin h + +private def positionPair : Packet n r d × Index n h ≃ Position n r d h × Bool where + toFun t := ((t.1, t.2.2), t.2.1) + invFun t := (t.1.1, t.2, t.1.2) + left_inv _ := rfl + right_inv _ := rfl + +private theorem packet_bill (p : Packet n r d) : + let R := A.report hn s + let π := A.plan hn N s + (∑ k, A.bill hn N u R (.inl (positionPair (p, k))) 1) + + A.bill hn N u R (.inr (packetClass hn R.1 p)) (π.q p) ≤ π.slotsAt h u p := by + intro R π + let c := packetClass hn R.1 p + let e (k : Index n h) : Edge n r d h := .inl (positionPair (p, k)) + let T := {m : π.Message h p // π.sender p m = u ∨ π.receiver p m = u} + change (∑ k, A.bill hn N u R (e k) 1) + A.bill hn N u R (.inr c) (π.q p) ≤ Fintype.card T + have hm : A.shared N R c = true ↔ ¬π.marked p := A.shared_plan hn N s p + have hd (k) : A.dst hn N R (e k) = if A.shared N R c then A.src hn N R (e k) + else .packet c.2.2 := rfl + by_cases hs : A.shared N R c = true + · have hb (k) : A.bill hn N u R (e k) 1 = 0 := by simp [bill, hd, hs] + simp only [hb, sum_const_zero, zero_add] + simp only [bill, src, dst, hs, ite_true] + split + · rename_i hu + let f : Fin (π.q p) → T := fun i => ⟨.inr ⟨i, hm.mp hs⟩, hu.2⟩ + have hf : Function.Injective f := by + intro i j he + exact congrArg Subtype.val (Sum.inr.inj (congrArg Subtype.val he)) + simpa using Fintype.card_le_of_injective f hf + · exact Nat.zero_le _ + · have hb : A.bill hn N u R (.inr c) (π.q p) = 0 := by simp [bill, src, dst, hs] + rw [hb, add_zero] + let P (k : Index n h) := A.src hn N R (e k) = u ∨ Worker.packet c.2.2 = u + have he (k) : A.bill hn N u R (e k) 1 ≤ if P k then 1 else 0 := by + simp only [bill, hd, ite_eq_right hs, P] + split_ifs <;> grind + refine (sum_le_sum (fun k _ => he k)).trans ?_ + rw [sum_boole, ← Fintype.card_subtype] + have marked : π.marked p := by tauto + have hu (k : Index n h) : A.src hn N R (e k) = π.sender p (.inl ⟨k, marked⟩) := + owner_plan A hn N s _ + let f : {k // P k} → T := fun k => + ⟨.inl ⟨k.val, marked⟩, k.2.imp (fun h => (hu _).symm.trans h) id⟩ + apply Fintype.card_le_of_injective f + intro i j he + apply Subtype.ext + have e := Sum.inl.inj (congrArg Subtype.val he) + exact congrArg (fun x : {_k : Index n h // π.marked p} => x.val) e + +theorem site_bound (hb : 128 * ∑ p, (A.plan hn N s).slotsAt h u p ≤ N) : + let R := A.report hn s + 128 * ∑ e ∈ univ.filter (fun e => A.src hn N R e ≠ A.dst hn N R e ∧ + (A.src hn N R e = u ∨ A.dst hn N R e = u)), A.size R e ≤ N := by + intro R + apply le_trans _ hb + apply Nat.mul_le_mul_left + rw [sum_filter] + change (∑ e, A.bill hn N u R e (A.size R e)) ≤ _ + rw [Fintype.sum_sum_type] + simp only [size] + rw [← positionPair.sum_comp, Fintype.sum_prod_type, class_sumFromSiteBound, ← sum_add_distrib] + exact sum_le_sum (fun p _ => A.packet_bill hn N s u p) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +/- # Assignments of a reported network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +variable {F : Type} [Field F] {n h r d : ℕ} (A : Expansion F n h) + (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) + +open Classical in +/-- Embeds `A.symbol hn N R e` into `(Fin (A.size R e) → Bool)`. -/ +def symbolCode (e : Edge n r d h) : A.symbol hn N R e ↪ (Fin (A.size R e) → Bool) := + match e with + | .inl _ => ⟨fun b _ => b, fun _ _ he => congrFun he (0 : Fin 1)⟩ + | .inr c => A.alphabetCode hn N R c + +open Classical in +private def coordinates : A.Assignment hn N R ≃ + (Packet n r d → Block n h) × (Packet n r d → Block n h) × + ((c : Class r) → A.Alphabet hn N R c) where + toFun a := (A.rows a false, A.rows a true, fun c => a (.inr c)) + invFun z + | .inl ((p, i), false) => z.1 p i + | .inl ((p, i), true) => z.2.1 p i + | .inr c => z.2.2 c + left_inv a := by + funext e + rcases e with ⟨⟨p, i⟩, b⟩ | c + · cases b <;> rfl + · rfl + right_inv _ := rfl + +open Classical in +theorem sum_assignment (f : (Packet n r d → Block n h) → (Packet n r d → Block n h) → + ((c : Class r) → A.Alphabet hn N R c) → F) : + (∑ a : A.Assignment hn N R, f (A.rows a false) (A.rows a true) (fun c => a (.inr c))) = + ∑ x, ∑ y, ∑ z, f x y z := by + let _ : Fintype (Packet n r d → Block n h) := inferInstance + let _ : Fintype ((c : Class r) → A.Alphabet hn N R c) := inferInstance + rw [← (A.coordinates hn N R).symm.sum_comp] + simp only [Fintype.sum_prod_type] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +/- # Physical links for a reported packet network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +/-- Reindexes `Worker r` and `Fin 3 × Fin r where toFun | .home i => (0, i) | .station i => (1, +i) | .packet i => (2, i) invFun v` by an equivalence. -/ +def pools (r : ℕ) : Worker r ≃ Fin 3 × Fin r where + toFun + | .home i => (0, i) + | .station i => (1, i) + | .packet i => (2, i) + invFun v := if v.1 = 0 then .home v.2 else if v.1 = 1 then .station v.2 else .packet v.2 + left_inv w := by cases w <;> rfl + right_inv v := by obtain ⟨i, j⟩ := v; fin_cases i <;> rfl + +/-- Number homes first, then station workers and finally packet workers. -/ +def Worker.index (r : ℕ) : Worker r ≃ Fin (3 * r) := + (pools r).trans finProdFinEquiv + +namespace Expansion + +variable {F : Type} [Field F] {n h d r : ℕ} (A : Expansion F n h) + (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) + +open Classical in +/-- Only links between distinct workers use the communication budget. -/ +def budget : Prop := + ∀ u : Worker r, 128 * ∑ e ∈ Finset.univ.filter (fun e => A.src hn N R e ≠ A.dst hn N R e ∧ + (A.src hn N R e = u ∨ A.dst hn N R e = u)), A.size R e ≤ N + +open Classical in +theorem report_budget (s : Packet n r d → A.I) + (hb : ∀ u, 128 * ∑ p, (A.plan hn N s).slotsAt h u p ≤ N) : + A.budget hn N (A.report hn s) := fun u => A.site_bound hn N s u (hb u) + +variable (idx : Worker r ≃ Fin (3 * r)) + +open Classical in +theorem indexed (hb : A.budget hn N R) (i : Fin (3 * r)) : + ∑ e ∈ Finset.univ.filter (fun e => idx (A.src hn N R e) ≠ idx (A.dst hn N R e) ∧ + (idx (A.src hn N R e) = i ∨ idx (A.dst hn N R e) = i)), A.size R e ≤ N / 64 := by + obtain ⟨u, rfl⟩ := idx.surjective i + have hb' := hb u + simp only [ne_eq, idx.injective.eq_iff] at hb' ⊢ + omega + +open Classical in +/-- The serial used in the `Expansion` construction. -/ +abbrev Serial := + Links.Numbering (Encoded.left (idx ∘ A.src hn N R) (idx ∘ A.dst hn N R) (A.size R)) + (Encoded.right (idx ∘ A.src hn N R) (idx ∘ A.dst hn N R) (A.size R)) + +variable (hb : A.budget hn N R) (hN : 64 * (3 * r) ^ 2 ≤ N) + (g : Worker r → A.Assignment hn N R → F) + +open Classical in +/-- The processor table acts on its own input interval. Simultaneous +numbering of the parallel wires is specified by the caller. -/ +def processor (serial : A.Serial hn N R idx) : Fin (3 * r) → (Fin (N / 4) → Bool) → F := + Encoded.worker (idx ∘ A.src hn N R) (idx ∘ A.dst hn N R) (A.symbol hn N R) (A.size R) + (A.symbolCode hn N R) (A.indexed hn N R idx hb) hN (g ∘ idx.symm) serial + +open Classical in +theorem physical + (hg : ∀ u x y, (∀ e, A.src hn N R e = u ∨ A.dst hn N R e = u → x e = y e) → g u x = g u y) + (serial : A.Serial hn N R idx := fun _ _ => (Fintype.equivFin _).symm) : + (∑ a, ∏ u, g u a) = + ∑ y, ∏ u, A.processor hn N R idx hb hN g serial u (Links.view u y) := by + calc + _ = ∑ a, ∏ i, g (idx.symm i) a := by + apply Finset.sum_congr rfl + intro a _ + exact (idx.symm.prod_comp (fun u => g u a)).symm + _ = _ := by + apply Encoded.contract (idx ∘ A.src hn N R) (idx ∘ A.dst hn N R) (A.symbol hn N R) + (A.size R) (A.symbolCode hn N R) (A.indexed hn N R idx hb) hN (g ∘ idx.symm) _ serial + intro i x y he + apply hg + intro e h + exact he e (h.imp idx.eq_symm_apply.mp idx.eq_symm_apply.mp) + +end Expansion +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Replay.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Replay.lean new file mode 100644 index 0000000000..1887687131 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/Replay.lean @@ -0,0 +1,1020 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Input +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Physical +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Cuts +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.AlphabetCode +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.TemplateSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Fixing + +/-! +# Substitution in a closed network of processors + +Each processor sees its own literals, the same broadcast and its +incident link bits. Pad incomplete batches with a fixed input of weight +one before substituting a diagram that realizes a batch exactly. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Machine + +/-- Indexes the ports by the coordinates of `Fin l ⊕ Fin b ⊕ Fin (N / 4)`. -/ +abbrev Ports (N l b : ℕ) := Fin l ⊕ Fin b ⊕ Fin (N / 4) +/-- The quantity computed by `word (l + b + N / 4)`. -/ +abbrev tape (N l b : ℕ) := word (l + b + N / 4) + +/-- Reindexes two finite types using equality of cardinalities. -/ +def address (N l b : ℕ) : slots (tape N l b) ≃ Ports N l b := + Fintype.equivOfCardEq (by simp [tape, Ports, Nat.add_assoc]) + +variable {N l b R B d : ℕ} + +/-- The value specified by `(bits (tape N l b)).symm (Sum.elim ξ (Sum.elim z s) ∘ address N l +b)`. -/ +def feed (ξ : Fin l → Bool) (z : Fin b → Bool) (s : Fin (N / 4) → Bool) : Val (tape N l b) := + (bits (tape N l b)).symm (Sum.elim ξ (Sum.elim z s) ∘ address N l b) + +theorem bits_feed (ξ : Fin l → Bool) (z : Fin b → Bool) (s : Fin (N / 4) → Bool) + (i : slots (tape N l b)) : + bits (tape N l b) (feed ξ z s) i = Sum.elim ξ (Sum.elim z s) (address N l b i) := + congrFun ((bits _).apply_symm_apply _) i + +/-- Returns `feed (ξ ⟨u.val, h⟩) z (Links.view ⟨u.val, h⟩ y)` when `h : u.val < R` holds, and +`x` otherwise. -/ +def padded (x : Val (tape N l b)) (ξ : Fin R → Fin l → Bool) (z : Fin b → Bool) + (y : Links.Slot R N → Bool) (u : Fin (B * d)) : Val (tape N l b) := + if h : u.val < R then feed (ξ ⟨u.val, h⟩) z (Links.view ⟨u.val, h⟩ y) else x + +/-- The indexed operation `bundle _ d (fun i => padded x ξ z y (finProdFinEquiv (j, i)))`. -/ +def inputs (x : Val (tape N l b)) (ξ : Fin R → Fin l → Bool) (z : Fin b → Bool) + (y : Links.Slot R N → Bool) (j : Fin B) : Val (copies (tape N l b) d) := + bundle _ d (fun i => padded x ξ z y (finProdFinEquiv (j, i))) + +variable {F : Type} [Field F] (U : Val (tape N l b) → Val .unit → F) (ξ : Fin R → Fin l → Bool) + +/-- The indexing data represented by `∑ z : Fin b → Bool, ∑ y : Links.Slot R N → Bool, ∏ u, U +(feed (ξ u) z (Links.view u y)) ()`. -/ +def scalar : F := + ∑ z : Fin b → Bool, ∑ y : Links.Slot R N → Bool, ∏ u, U (feed (ξ u) z (Links.view u y)) () + +private theorem product_pad {K : ℕ} (h : R ≤ K) (f : Fin R → F) : + (∏ u : Fin K, if hp : u.val < R then f ⟨u.val, hp⟩ else 1) = ∏ u, f u := by + obtain ⟨m, rfl⟩ := Nat.exists_eq_add_of_le h + rw [Fin.prod_univ_add] + simp + +/-- Replacing each complete batch preserves the scalar for all literal +settings, including literal settings depending on the replacement diagram. -/ +theorem substitute (x : Val (tape N l b)) + (G : Diagram F (copies (tape N l b) d) (copies .unit d)) + (hR : R ≤ B * d) (hx : U x () = 1) (hG : G.eval = power U d) : + scalar U ξ = ∑ z, ∑ y, ∏ j : Fin B, G.eval (inputs x ξ z y j) (unitCopies d) := by + unfold scalar + apply Finset.sum_congr rfl + intro z _ + apply Finset.sum_congr rfl + intro y _ + let f (u : Fin R) := U (feed (ξ u) z (Links.view u y)) () + have he (u : Fin (B * d)) : U (padded x ξ z y u) () = + if hp : u.val < R then f ⟨u.val, hp⟩ else 1 := by + unfold padded + split <;> simp_all [f] + symm + rw [hG, ← eq_unitCopies d (bundle .unit d (fun _ => ()))] + simp_rw [inputs, power_bundle] + rw [← Fintype.prod_prod_type (fun ji => U (padded x ξ z y (finProdFinEquiv ji)) ()), + Equiv.prod_comp finProdFinEquiv (fun u => U (padded x ξ z y u) ())] + simp_rw [he] + exact product_pad hR f + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Machine +end + +/- # The unit branch in the diagonal computation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Machine + +open Finset +variable {F : Type} [Field F] {N R b : ℕ} {Q : Type} [Fintype Q] + +open Classical in +private theorem view_zero (u : Fin R) : + Links.view u (fun _ : Links.Slot R N => false) = fun _ => false := by + funext i + by_cases hi : ∃ s : {s : Links.Slot R N // Links.sees u s.1}, Links.address s.1 = i + · obtain ⟨s, rfl⟩ := hi + exact Links.view_address u _ s.val s.2 + · simp [Links.view, Function.extend_apply' _ _ _ hi] + +open Classical in +private theorem zero_iff (y : Links.Slot R N → Bool) : + (∀ u, Links.view u y = fun _ => false) ↔ y = fun _ => false := by + constructor + · intro hv + funext e + rw [← Links.view_address e.1.1.1 y e (.inl rfl), hv] + · rintro rfl u + exact view_zero u + +open Classical in +/-- A broadcast code chooses a report or the extra unit. Unused +codes reject. The unit branch pins all physical links. -/ +def branch (code : Option Q ↪ (Fin b → Bool)) (run : Q → (Fin (N / 4) → Bool) → F) + (z : Fin b → Bool) (y : Fin (N / 4) → Bool) : F := + Function.extend code (fun q => q.elim (if y = (fun _ => false) then 1 else 0) (fun t => run t y)) + (fun _ => 0) z + +open Classical in +theorem branch_sum (hR : 0 < R) (code : Option Q ↪ (Fin b → Bool)) + (run : Fin R → Q → (Fin (N / 4) → Bool) → F) : + (∑ z, ∑ y, ∏ u, branch code (run u) z (Links.view u y)) = + 1 + ∑ q, ∑ y, ∏ u, run u q (Links.view u y) := by + rw [← sum_subset (subset_univ (univ.map code)), sum_map] + · simp only [branch, code.injective.extend_apply] + rw [Fintype.sum_option] + simp only [Option.elim_none, Option.elim_some, prod_ite_zero, mem_univ, forall_const, + prod_const_one, zero_iff, sum_ite_eq', ite_true] + · intro z _ h + have hz : ¬∃ q, code q = z := by + rintro ⟨q, rfl⟩ + exact h (mem_map.mpr ⟨q, mem_univ q, rfl⟩) + apply sum_eq_zero + intro y _ + apply prod_eq_zero (mem_univ (⟨0, hR⟩ : Fin R)) + exact Function.extend_apply' _ _ _ hz + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Machine +end + +/- # Independent restrictions on classes of variables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal +open Finset + +variable {P C I F : Type} [Fintype P] [Fintype C] [Fintype I] [Field F] + [DecidableEq P] [DecidableEq C] [DecidableEq I] + +omit [Fintype C] [Fintype I] [DecidableEq P] in +open Classical in +theorem count_in_class (key : P → C) (s : P → I) (c : C) (i : I) : + multiplicity (fun p : {p // key p = c} => s p.1) i = + multiplicity (fun p => (key p, s p)) (c, i) := by + refine Fintype.card_congr ?_ + exact (Equiv.subtypeSubtypeEquivSubtypeInter _ (fun p => s p = i)).trans + (Equiv.subtypeEquivRight (fun _ => by simp)) + +omit [DecidableEq P] in +open Classical in +theorem prod_class (key : P → C) (w : P → F) : + ∏ c, ∏ p : {p // key p = c}, w p.val = ∏ p, w p := by + let e := Equiv.sigmaFiberEquiv key + rw [← e.prod_comp, Fintype.prod_sigma] + rfl + +open Classical in +private theorem sum_condition {A : Type} [Fintype A] (p : A → Prop) [DecidablePred p] + [Fintype {x // p x}] (w : A → F) : + ∑ a : {a // p a}, w a.1 = ∑ a, if p a then w a else 0 := by + rw [← sum_filter] + exact (sum_subtype _ (by simp) _).symm + +omit [DecidableEq I] in +open Classical in +/-- An independent constraint on each class can be tested on the +corresponding restriction of a single global assignment. -/ +theorem sum_classes (key : P → C) (p : (c : C) → ({u // key u = c} → I) → Prop) + [∀ c, DecidablePred (p c)] [∀ c, Fintype {s // p c s}] (w : P → I → F) : + (∏ c, ∑ s : {s // p c s}, ∏ i : {u // key u = c}, w i.1 (s.1 i)) = + ∑ s : P → I, if ∀ c, p c (fun i => s i.val) then ∏ i, w i (s i) else 0 := by + let e := ((Equiv.sigmaFiberEquiv key).symm.arrowCongr (Equiv.refl I)).trans + (Equiv.piCurry (fun _ _ => I)) + have h (c : C) : + (∑ s : {s // p c s}, ∏ i : {u // key u = c}, w i.1 (s.1 i)) = + ∑ s, if p c s then ∏ i : {u // key u = c}, w i.1 (s i) else 0 := + sum_condition (p c) (fun s => ∏ i, w i.1 (s i)) + simp_rw [h] + rw [Fintype.prod_sum, ← e.sum_comp] + apply sum_congr rfl + intro s _ + change (∏ c, if p c (fun i => s i.val) then + ∏ i : {u // key u = c}, w i.1 (s i.val) else 0) = _ + rw [prod_ite_zero, prod_class key (fun i => w i (s i))] + simp only [mem_univ, forall_const] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- +# Evaluation on padded slot assignments + +Unoccupied positions are pinned on the station side. On the junction +side equality in the sum over all selectors forces the same padding. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout + +open Finset +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {n r h B : ℕ} (L : Layout G n r h) + +open Classical in +/-- The quantity computed by `Packet n r (B * L.d) → Block n h`. -/ +abbrev Slots (B : ℕ) := Packet n r (B * L.d) → Block n h + +open Classical in +/-- The pos of type `Position n r (B * L.d) h`, constructed using `L.assign e`. -/ +def pos (j : Fin B) (e : G.End) : Position n r (B * L.d) h := + let s := L.assign e + ((s.1.1, finProdFinEquiv (j, s.1.2)), s.2) + +open Classical in +/-- Computes the read by the application `u (L.pos j e).1 (L.pos j e).2`. -/ +def read (u : L.Slots B) (j : Fin B) (e : G.End) := u (L.pos j e).1 (L.pos j e).2 + +open Classical in +theorem read_load (u : Fin B → G.End → Bool) : L.read (L.batchLoad u) = u := by + funext j e + simp only [read, pos, batchLoad, Equiv.symm_apply_apply] + exact L.load_assign _ _ + +open Classical in +/-- Returns `1` when `u s.1 s.2 = false ∨ ∃ (j : Fin B) (e : G.End), L.pos j e = s` holds, and +`0` otherwise. -/ +def pin (u : L.Slots B) (s : Position n r (B * L.d) h) : F := + if u s.1 s.2 = false ∨ ∃ (j : Fin B) (e : G.End), L.pos j e = s then 1 else 0 + +open Classical in +private theorem unoccupied (v : Fin B → G.End → Bool) (s : Position n r (B * L.d) h) + (hs : ¬ ∃ (j : Fin B) (e : G.End), L.pos j e = s) : L.batchLoad v s.1 s.2 = false := by + unfold batchLoad load + apply Function.extend_apply' + rintro ⟨e, he⟩ + apply hs + refine ⟨(finProdFinEquiv.symm s.1.2).1, e, ?_⟩ + simp only [pos, he, Prod.mk.eta, Equiv.apply_symm_apply] + +open Classical in +theorem pin_load (v : Fin B → G.End → Bool) (s : Position n r (B * L.d) h) : + L.pin (L.batchLoad v) s = 1 := by + unfold pin + by_cases he : ∃ (j : Fin B) (e : G.End), L.pos j e = s + · exact ite_eq_left (.inr he) + · exact ite_eq_left (.inl (L.unoccupied v s he)) + +open Classical in +private theorem restore (u : L.Slots B) (hpin : ∏ s, L.pin u s ≠ 0) : + L.batchLoad (L.read u) = u := by + funext p i + let s := (p, i) + change L.batchLoad (L.read u) s.1 s.2 = u s.1 s.2 + by_cases he : ∃ (j : Fin B) (e : G.End), L.pos j e = s + · obtain ⟨j, e, he⟩ := he + rw [← he] + exact congrFun (congrFun (L.read_load (L.read u)) j) e + · have hp := prod_ne_zero_iff.mp hpin s (mem_univ _) + rw [L.unoccupied _ _ he] + by_contra hh + exact hp (ite_eq_right (not_or.mpr ⟨Ne.symm hh, he⟩)) + +open Classical in +/-- The ground of type `F` for the given inputs. -/ +def ground (x : Fin B → Val a) (y : Fin B → Val b) (u v : L.Slots B) : F := + (∏ j, ∏ q : G.V, G.normalized.vertex (x j) (y j) (L.read u j) (.inl q)) * + (∏ j, ∏ q : G.Joint, G.normalized.vertex (x j) (y j) (L.read v j) (.inr q)) * + ∏ s, L.pin u s + +open Classical in +theorem ground_sum (x : Fin B → Val a) (y : Fin B → Val b) : + ∑ u : L.Slots B, L.ground x y u u = ∏ j, G.eval (x j) (y j) := by + let e : (Fin B → G.End → Bool) ↪ L.Slots B := ⟨L.batchLoad, L.batchLoad_injective⟩ + rw [← sum_subset (subset_univ (univ.map e)), sum_map] + · change (∑ u, L.ground x y (L.batchLoad u) (L.batchLoad u)) = _ + simp only [ground, read_load, pin_load, prod_const_one, mul_one, ← prod_mul_distrib] + have he (j : Fin B) : G.eval (x j) (y j) = ∑ s : G.End → Bool, + (∏ q : G.V, G.normalized.vertex (x j) (y j) s (.inl q)) * + (∏ q : G.Joint, G.normalized.vertex (x j) (y j) s (.inr q)) := by + rw [← G.eval_normalized] + unfold Diagram.eval + apply sum_congr + · ext; simp + · exact fun _ _ => Fintype.prod_sum_type _ + simp_rw [he] + rw [Fintype.prod_sum] + · intro u _ hu + have hpin : ∏ s, L.pin u s = 0 := by + by_contra hn + exact hu (mem_map.mpr ⟨_, mem_univ _, L.restore u hn⟩) + simp only [ground, hpin, mul_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +/- +# Independent selector alphabets after fixing the public report + +Every assignment occurs with multiplicity one. In particular, +reports for which a class has no possible selector contribute zero. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Finset +variable {F : Type} [Field F] {n h d r : ℕ} (A : Expansion F n h) + (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) + +open Classical in +/-- The value specified by `∏ p, A.value (z.1.val p) R.1 (x p.val) (y p.val) (A.shared N R c) +(z.2 p)`. -/ +def classFactor (x y : Packet n r d → Block n h) (c : Class r) + (z : A.Alphabet hn N R c) : F := + ∏ p, A.value (z.1.val p) R.1 (x p.val) (y p.val) (A.shared N R c) (z.2 p) + +open Classical in +theorem class_sum (x y : Packet n r d → Block n h) (c : Class r) : + ∑ z, A.classFactor hn N R x y c z = + ∑ s : A.Selectors hn R c, ∏ p, A.weight (s.val p) (x p.val) (y p.val) := by + rw [Fintype.sum_sigma] + apply sum_congr rfl + intro s _ + exact A.sum_wires _ _ _ _ _ + +open Classical in +theorem counts_match (s : Packet n r d → A.I) : + (∀ c z, multiplicity (fun p : A.Members hn R c => s p.1) z = (R.2 (c, z)).val) ↔ + ∀ c, R.2 c = A.counts hn s R.1 c := by + constructor + · rintro h ⟨c, z⟩ + apply Fin.ext + exact (h c z).symm.trans (count_in_class (packetClass hn R.1) s c z) + · intro h c z + rw [h (c, z)] + exact count_in_class _ s c z + +open Classical in +/-- Requires `R.1 = first hn (fun j => A.total R (fun _ t => A.cross t j))`. -/ +def valid : Prop := R.1 = first hn (fun j => A.total R (fun _ t => A.cross t j)) + +open Classical in +theorem report_sum (x y : Packet n r d → Block n h) : + (if A.valid hn R then ∏ c, ∑ z, A.classFactor hn N R x y c z else 0) = + ∑ s, if R = A.report hn s then ∏ p, A.weight (s p) (x p) (y p) else 0 := by + have eq (s) : A.checks hn R s ↔ A.valid hn R ∧ ∀ c, R.2 c = A.counts hn s R.1 c := Iff.rfl + simp_rw [← checks_iff, eq] + by_cases hv : A.valid hn R + · rw [ite_eq_left hv] + simp only [hv, true_and] + simp_rw [class_sum] + have he := sum_classes (packetClass hn R.1) + (fun c s => ∀ z, multiplicity s z = (R.2 (c, z)).val) + (fun p t => A.weight t (x p) (y p)) + simp only [← A.counts_match hn R] + exact he + · rw [ite_eq_right hv] + simp only [hv, false_and, ite_false, sum_const_zero] + +open Classical in +theorem partitioned (x y : Packet n r d → Block n h) : + (∑ R, if A.valid hn R then ∏ c, ∑ z, A.classFactor hn N R x y c z else 0) = + if x = y then 1 else 0 := by + simp_rw [A.report_sum hn N] + rw [sum_comm] + simp only [sum_ite_eq', mem_univ, ite_true, A.full_product] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +/- +# Local factors of a reported contraction + +Light classes contribute one factor at each home. For a heavy class +the packet worker alone evaluates the entire packet weight. If two +homes coincide their factors are multiplied at the same worker. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Finset Spectral +variable {F : Type} [Field F] {n h d r : ℕ} (A : Expansion F n h) + +/-- In the case `true, z`, this construction gives `A.side s i b x y z`. -/ +def piece (s : A.I) (i : Fin n) (x y : Block n h) (b : Bool) : + (l : Bool) → (Fin (A.width s i l) → Bool) → F + | true, z => A.side s i b x y z + | false, _ => if b then 1 else A.weight s x y + +private theorem prod_piece (s : A.I) (i : Fin n) (x y : Block n h) + (l : Bool) (z : Fin (A.width s i l) → Bool) : + (∏ b, A.piece s i x y b l z) = A.value s i x y l z := by + cases l <;> simp [piece, value, mul_comm] + +theorem piece_local (s : A.I) (i : Fin n) (x x' y y' : Block n h) + (b l : Bool) (z : Fin (A.width s i l) → Bool) + (hx : ∀ p, (l = true → p.1 i = b) → x p = x' p) + (hy : ∀ p, (l = true → p.1 i ≠ b) → y p = y' p) : + A.piece s i x y b l z = A.piece s i x' y' b l z := by + cases l + · have : x = x' := funext (fun p => hx p (by simp)) + have : y = y' := funext (fun p => hy p (by simp)) + subst x' + subst y' + rfl + · exact A.depends s i b x x' y y' z (fun p h => hx p (fun _ => h)) + (fun p h => hy p (fun _ => h)) + +variable (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) + +/-- Returns `A.dst hn N R (.inr c)` when `b` holds, and `A.src hn N R (.inr c)` otherwise. -/ +def worker (c : Class r) (b : Bool) := + if b then A.dst hn N R (.inr c) else A.src hn N R (.inr c) + +theorem row_dst (c : Class r) (p : A.Members hn R c) + (i : Cube n × Fin h) (v b : Bool) (hi : A.shared N R c = true → + (if v then !(i.1 R.1) else i.1 R.1) = b) : + A.dst hn N R (.inl ((p.val, i), v)) = A.worker hn N R c b := by + simp only [worker, dst, src, p.property] + by_cases hl : A.shared N R c = true + · have hg : c.1 ∉ A.reportGroups N R ∧ c.2.1 ∉ A.reportGroups N R := + of_decide_eq_true hl + have he : endpoint (p.val, i) v R.1 = group p.val.1 R.1 b := by + rw [← hi hl] + cases v <;> simp [endpoint, corner, group, Cube.flip] + have h₀ : group p.val.1 R.1 false = c.1 := congrArg Prod.fst p.property + have h₁ : group p.val.1 R.1 true = c.2.1 := congrArg (fun c => c.2.1) p.property + cases b <;> simp [hl, owner, he, h₀, h₁, hg] + · simp [hl] + +variable {hn N R} + +/-- The construction uses `a (.inr c)` for its intermediate `z`. -/ +def half (a : A.Assignment hn N R) (c : Class r) (b : Bool) := + let z := a (.inr c) + ∏ p, A.piece (z.1.val p) R.1 (A.rows a false p.val) (A.rows a true p.val) b + (A.shared N R c) (z.2 p) + +/-- Product of the packet factors assigned to this worker. -/ +def factor (a : A.Assignment hn N R) (u : Worker r) := + ∏ c, ∏ b, if A.worker hn N R c b = u then A.half a c b else 1 + +theorem prod_factor (a : A.Assignment hn N R) : + (∏ u, A.factor a u) = + ∏ c, A.classFactor hn N R (A.rows a false) (A.rows a true) c (a (.inr c)) := by + unfold factor + rw [prod_comm] + apply prod_congr rfl + intro c _ + rw [prod_comm] + simp only [prod_ite_eq, mem_univ, ite_true, half, classFactor] + rw [prod_comm] + exact prod_congr rfl fun p _ => A.prod_piece _ _ _ _ _ _ + +theorem factor_local (a a' : A.Assignment hn N R) (u : Worker r) + (ha : ∀ e, A.src hn N R e = u ∨ A.dst hn N R e = u → a e = a' e) : + A.factor a u = A.factor a' u := by + unfold factor + apply prod_congr rfl + intro c _ + apply prod_congr rfl + intro b _ + by_cases he : A.worker hn N R c b = u + · simp only [ite_eq_left he, half] + have hz : a (.inr c) = a' (.inr c) := ha _ (by + cases b + · exact .inl he + · exact .inr he) + rw [hz] + apply prod_congr rfl + intro p _ + apply A.piece_local + · intro i hi + exact ha _ (.inr ((A.row_dst hn N R c p i false b hi).trans he)) + · intro i hi + have hj : A.shared N R c = true → (!(i.1 R.1)) = b := by + intro hl + exact (show ∀ x y : Bool, x ≠ y → (!x) = y by decide) _ _ (hi hl) + exact ha _ (.inr ((A.row_dst hn N R c p i true b hj).trans he)) + · simp [he] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +/- # Assigning original station weights and padding pins to workers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +open Finset + +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {n r h B : ℕ} (L : Layout G n r h) + +open Classical in +/-- Indexes the atom by the coordinates of `(Fin B × G.normalized.V) ⊕ Position n r (B * L.d) +h`. -/ +abbrev Atom (B : ℕ) := (Fin B × G.normalized.V) ⊕ Position n r (B * L.d) h + +open Classical in +/-- In the case `.inl q`, this construction gives `L.color q.2`. -/ +def loc : L.Atom B → Label n r + | .inl q => L.color q.2 + | .inr p => Expansion.endpoint p false + +open Classical in +/-- In the case `.inl (j, .inl v)`, this construction gives `G.normalized.vertex (x j) (y j) +(L.read s j) (.inl v)`. -/ +def atom (x : Fin B → Val a) (y : Fin B → Val b) (s t : L.Slots B) : L.Atom B → F + | .inl (j, .inl v) => G.normalized.vertex (x j) (y j) (L.read s j) (.inl v) + | .inl (j, .inr v) => G.normalized.vertex (x j) (y j) (L.read t j) (.inr v) + | .inr p => L.pin s p + +open Classical in +private theorem atom_prod (x : Fin B → Val a) (y : Fin B → Val b) (s t : L.Slots B) : + ∏ v, L.atom x y s t v = L.ground x y s t := by + rw [Fintype.prod_sum_type, Fintype.prod_prod_type] + have H (j : Fin B) : + (∏ v, L.atom x y s t (.inl (j, v))) = + (∏ v : G.V, G.normalized.vertex (x j) (y j) (L.read s j) (.inl v)) * + (∏ v : G.Joint, G.normalized.vertex (x j) (y j) (L.read t j) (.inr v)) := + Fintype.prod_sum_type _ + simp_rw [H, prod_mul_distrib] + rfl + +open Classical in +theorem endpoint_false (j : Fin B) (e : G.End) : + Expansion.endpoint (L.pos j e) false = L.color (.inl (G.station e)) := + congrArg Prod.fst (L.follows e) + +open Classical in +theorem endpoint_true (j : Fin B) (e : G.End) : + Expansion.endpoint (L.pos j e) true = L.color (.inr (G.junction e)) := + congrArg Prod.snd (L.follows e) + +variable (A : Expansion F n h) {hn : 2 ≤ n} {N : ℕ} {R : A.Report r (B * L.d)} + +open Classical in +/-- The value specified by `∏ q : L.Atom B, if A.owner hn N R (L.loc q) = u then L.atom x y +(A.rows s false) (A.rows s true) q else 1`. -/ +def base (x : Fin B → Val a) (y : Fin B → Val b) (s : A.Assignment hn N R) (u : Worker r) : F := + ∏ q : L.Atom B, if A.owner hn N R (L.loc q) = u then + L.atom x y (A.rows s false) (A.rows s true) q else 1 + +open Classical in +theorem prod_base (x : Fin B → Val a) (y : Fin B → Val b) (s : A.Assignment hn N R) : + ∏ u, L.base A x y s u = L.ground x y (A.rows s false) (A.rows s true) := by + unfold base + rw [prod_comm] + simpa only [prod_ite_eq, mem_univ, ite_true] using L.atom_prod x y (A.rows s false) (A.rows s + true) + +open Classical in +theorem base_local {x x' : Fin B → Val a} {y y' : Fin B → Val b} + {s t : A.Assignment hn N R} (u : Worker r) + (hx : ∀ j i, A.owner hn N R (L.color (.inr (.inl i))) = u → bits a (x j) i = bits a (x' j) i) + (hy : ∀ j i, A.owner hn N R (L.color (.inr (.inr (.inl i)))) = u → + bits b (y j) i = bits b (y' j) i) + (he : ∀ e, A.src hn N R e = u → s e = t e) : + L.base A x y s u = L.base A x' y' t u := by + apply prod_congr rfl + intro q _ + split_ifs with hq + · rcases q with ⟨j, v|v⟩|p + · apply G.station_local + intro e h + apply he (.inl (L.pos j e, false)) + simpa only [loc, Expansion.src, endpoint_false, h] using hq + · apply G.junction_local + · intro i hi + exact hx j i (by rw [hi]; exact hq) + · intro i hi + exact hy j i (by rw [hi]; exact hq) + · intro e h + apply he (.inl (L.pos j e, true)) + simpa only [loc, Expansion.src, endpoint_true, h] using hq + · have hp : A.rows s false p.1 p.2 = A.rows t false p.1 p.2 := he (.inl (p, false)) hq + simp only [atom, pin, hp] + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +/- +# A distributed contraction on the virtual links + +For a fixed report all communication is along a fixed graph. The +local factors depend only on their incident symbols and exterior bits. +Any additional filter accepting every honest report preserves the sum. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal +open Finset + +variable {F : Type} [Field F] {n h d r : ℕ} + +namespace Expansion +variable (A : Expansion F n h) (hn : 2 ≤ n) (N : ℕ) + +open Classical in +/-- The subtype of `R` satisfying `A.valid hn R ∧ ok R`. -/ +abbrev Accepted (ok : A.Report r d → Prop) := {R // A.valid hn R ∧ ok R} + +open Classical in +theorem partitioned_filter (ok : A.Report r d → Prop) + (ho : ∀ s, ok (A.report hn s)) (x y : Packet n r d → Block n h) : + (∑ R : A.Accepted hn ok, ∏ c, ∑ z, A.classFactor hn N R.1 x y c z) = + if x = y then 1 else 0 := by + let f (R : A.Report r d) := ∏ c, ∑ z, A.classFactor hn N R x y c z + have he (R : A.Report r d) (hv : A.valid hn R) (hbad : ¬ok R) : f R = 0 := by + have h := A.report_sum hn N R x y + rw [ite_eq_left hv] at h + refine h.trans (sum_eq_zero ?_) + intro s _ + have he : R ≠ A.report hn s := fun hs => hbad (hs.symm ▸ ho s) + exact ite_eq_right he + have hi := sum_subtype (F := inferInstanceAs (Fintype (A.Accepted hn ok))) (univ.filter (fun R + => A.valid hn R ∧ ok R)) + (p := fun R => A.valid hn R ∧ ok R) (by simp) f + change (∑ R : A.Accepted hn ok, f R.1) = _ + rw [← hi, sum_filter, ← A.partitioned hn N] + apply sum_congr rfl + intro R _ + change (if A.valid hn R ∧ ok R then f R else 0) = if A.valid hn R then f R else 0 + by_cases hv : A.valid hn R + · by_cases hg : ok R + · simp [hv, hg] + · simp [hv, hg, he R hv hg] + · simp [hv] + +end Expansion + +namespace Layout + +variable {a b : Wire} {G : Diagram F a b} {B : ℕ} (L : Layout G n r h) + (A : Expansion F n h) {hn : 2 ≤ n} {N : ℕ} {R : A.Report r (B * L.d)} + +open Classical in +/-- The quantity computed by `L.base A x y s u * A.factor s u`. -/ +def localWeight (x : Fin B → Val a) (y : Fin B → Val b) (u : Worker r) + (s : A.Assignment hn N R) : F := L.base A x y s u * A.factor s u + +open Classical in +theorem localWeight_depends {x x' : Fin B → Val a} {y y' : Fin B → Val b} + (u : Worker r) (s t : A.Assignment hn N R) + (hx : ∀ j i, A.owner hn N R (L.color (.inr (.inl i))) = u → bits a (x j) i = bits a (x' j) i) + (hy : ∀ j i, A.owner hn N R (L.color (.inr (.inr (.inl i)))) = u → + bits b (y j) i = bits b (y' j) i) + (he : ∀ e, A.src hn N R e = u ∨ A.dst hn N R e = u → s e = t e) : + L.localWeight A x y u s = L.localWeight A x' y' u t := + congrArg₂ (· * ·) (L.base_local A u hx hy (fun e h => he e (.inl h))) (A.factor_local s t u he) + +open Classical in +private theorem localWeight_sum (x : Fin B → Val a) (y : Fin B → Val b) : + (∑ s : A.Assignment hn N R, ∏ u, L.localWeight A x y u s) = + ∑ v, ∑ w, L.ground x y v w * ∏ c, ∑ z, A.classFactor hn N R v w c z := by + simp only [localWeight, prod_mul_distrib, prod_base, Expansion.prod_factor] + rw [A.sum_assignment hn N R + (fun v w z => L.ground x y v w * ∏ c, A.classFactor hn N R v w c (z c))] + simp only [← mul_sum, ← Fintype.prod_sum] + +open Classical in +/-- The public information is summed once, including any reports with +impossible histograms. Those reports have no symbol assignments. -/ +theorem virtual (hn : 2 ≤ n) (N : ℕ) (ok : A.Report r (B * L.d) → Prop) + (ho : ∀ s, ok (A.report hn s)) (x : Fin B → Val a) (y : Fin B → Val b) : + (∏ j, G.eval (x j) (y j)) = + ∑ R : A.Accepted hn ok, ∑ s : A.Assignment hn N R.1, ∏ u, L.localWeight A x y u s := by + rw [← L.ground_sum] + simp_rw [localWeight_sum] + rw [sum_comm] + apply sum_congr rfl + intro v _ + rw [sum_comm] + simp only [← mul_sum, A.partitioned_filter hn N ok ho, mul_ite, mul_one, mul_zero, + sum_ite_eq, mem_univ, ite_true] + +end Layout +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- +# Additional links for literal pins and exterior values + +A reported contraction uses at most half of each worker's virtual +bandwidth. The other half can carry arbitrary additional bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Finset +variable {F : Type} [Field F] {n h d r : ℕ} (A : Expansion F n h) + (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) (idx : Worker r ≃ Fin (3 * r)) + (hb : A.budget hn N R) (hN : 64 * (3 * r) ^ 2 ≤ N) {T : Type} [Fintype T] + (s t : T → Worker r) + +open Classical in +/-- The value specified by `idx ∘ Sum.elim s (A.src hn N R)`. -/ +def extraSrc := idx ∘ Sum.elim s (A.src hn N R) +open Classical in +/-- The value specified by `idx ∘ Sum.elim t (A.dst hn N R)`. -/ +def extraDst := idx ∘ Sum.elim t (A.dst hn N R) +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def extraSize := Sum.elim (fun _ : T => 1) (A.size R) +open Classical in +/-- Chooses the operation for the left or right summand. -/ +abbrev ExtraSymbol := Sum.elim (fun _ : T => Bool) (A.symbol hn N R) + +open Classical in +instance extraFintype : (e : T ⊕ Edge n r d h) → Fintype (A.ExtraSymbol hn N R e) + | .inl _ => inferInstanceAs (Fintype Bool) + | .inr e => inferInstanceAs (Fintype (A.symbol hn N R e)) + +open Classical in +/-- Embeds `A.ExtraSymbol hn N R e` into `(Fin (A.extraSize R e) → Bool)`. -/ +def extraCode (e : T ⊕ Edge n r d h) : A.ExtraSymbol hn N R e ↪ (Fin (A.extraSize R e) → Bool) := + match e with + | .inl _ => ⟨fun b _ => b, fun _ _ he => congrFun he (0 : Fin 1)⟩ + | .inr e => A.symbolCode hn N R e + +variable (ht : ∀ u, 128 * Fintype.card {e // s e ≠ t e ∧ (s e = u ∨ t e = u)} ≤ N) + +include hb ht in +open Classical in +theorem extra_bound (i : Fin (3 * r)) : + ∑ e ∈ univ.filter (fun e => A.extraSrc hn N R idx s e ≠ A.extraDst hn N R idx t e ∧ + (A.extraSrc hn N R idx s e = i ∨ A.extraDst hn N R idx t e = i)), A.extraSize R e ≤ N / 64 + := by + obtain ⟨u, rfl⟩ := idx.surjective i + have hb' := hb u + have ht' := ht u + rw [sum_filter, Fintype.sum_sum_type] + simp only [extraSrc, extraDst, extraSize, Function.comp_apply, Sum.elim_inl, Sum.elim_inr, + ne_eq, idx.injective.eq_iff, sum_boole, Nat.cast_id] + simp only [ne_eq, sum_filter, Fintype.card_subtype] at hb' ht' + omega + +open Classical in +/-- The extra serial used in the `Expansion` construction. -/ +abbrev ExtraSerial := + Links.Numbering (Encoded.left (A.extraSrc hn N R idx s) (A.extraDst hn N R idx t) (A.extraSize R)) + (Encoded.right (A.extraSrc hn N R idx s) (A.extraDst hn N R idx t) (A.extraSize R)) + +variable [DecidableEq T] (g : Worker r → (T → Bool) → A.Assignment hn N R → F) + +open Classical in +/-- The indexed operation `g (idx.symm i) (fun e => x (.inl e)) (fun e => x (.inr e))`. -/ +def joint (i : Fin (3 * r)) (x : (e : T ⊕ Edge n r d h) → A.ExtraSymbol hn N R e) : F := + g (idx.symm i) (fun e => x (.inl e)) (fun e => x (.inr e)) + +open Classical in +/-- The extra processor of type `Fin (3 * r) → (Fin (N / 4) → Bool) → F` for the given inputs. -/ +def extraProcessor (serial : A.ExtraSerial hn N R idx s t) : Fin (3 * r) → (Fin (N / 4) → Bool) → F + := + Encoded.worker (A.extraSrc hn N R idx s) (A.extraDst hn N R idx t) (A.ExtraSymbol hn N R) + (A.extraSize R) (A.extraCode hn N R) (A.extra_bound hn N R idx hb s t ht) hN + (A.joint hn N R idx g) serial + +open Classical in +theorem extraProcessor_congr {g g' : Worker r → (T → Bool) → A.Assignment hn N R → F} + (serial : A.ExtraSerial hn N R idx s t) (u : Fin (3 * r)) (he : g (idx.symm u) + = g' (idx.symm u)) : + A.extraProcessor hn N R idx hb hN s t ht g serial u = + A.extraProcessor hn N R idx hb hN s t ht g' serial u := by + funext v + simp only [extraProcessor, Encoded.worker, Links.worker, Links.site, Links.tally, + Encoded.bitSite, Encoded.localize, joint, he] + +open Classical in +theorem physical_extra + (hg : ∀ u y y' a a', (∀ e, s e = u ∨ t e = u → y e = y' e) → + (∀ e, A.src hn N R e = u ∨ A.dst hn N R e = u → a e = a' e) → g u y a = g u y' a') + (serial : A.ExtraSerial hn N R idx s t := fun _ _ => (Fintype.equivFin _).symm) : + (∑ y, ∑ a, ∏ u, g u y a) = + ∑ z, ∏ i, A.extraProcessor hn N R idx hb hN s t ht g serial i (Links.view i z) := by + calc + _ = ∑ x, ∏ i, A.joint hn N R idx g i x := by + let e := Equiv.sumPiEquivProdPi (A.ExtraSymbol (T := T) hn N R) + rw [← e.symm.sum_comp, Fintype.sum_prod_type] + apply sum_congr rfl + intro y _ + apply sum_congr rfl + intro a _ + exact (idx.symm.prod_comp (fun u => g u y a)).symm + _ = _ := by + apply Encoded.contract (A.extraSrc hn N R idx s) (A.extraDst hn N R idx t) + (A.ExtraSymbol hn N R) (A.extraSize R) (A.extraCode hn N R) + (A.extra_bound hn N R idx hb s t ht) hN (A.joint hn N R idx g) _ serial + intro i x y he + apply hg + · intro e h + exact he (.inl e) (h.imp idx.eq_symm_apply.mp idx.eq_symm_apply.mp) + · intro e h + exact he (.inr e) (h.imp idx.eq_symm_apply.mp idx.eq_symm_apply.mp) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +/- # Every processor sees shared bits at the same tape position -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Pin + +open Machine +variable {N l b r B d : ℕ} (pad : Val (tape N l b)) + +/-- Computes the input by the application `Machine.inputs pad (literal y) (broadcast y) (link y) +j`. -/ +def input (y : Pin N l b r → Bool) (j : Fin B) : Val (copies (tape N l b) d) := + Machine.inputs pad (literal y) (broadcast y) (link y) j + +private theorem view_local {R : ℕ} (x y : Links.Slot R N → Bool) (u : Fin R) + (i : Fin (N / 4)) (he : ∀ e, Links.address e = i → x e = y e) : + Links.view u x i = Links.view u y i := by + by_cases h : ∃ s : {s : Links.Slot R N // Links.sees u s.1}, Links.address s.1 = i + · obtain ⟨s, rfl⟩ := h + rw [Links.view_address _ _ _ s.2, Links.view_address _ _ _ s.2] + exact he s.1 rfl + · simp [Links.view, Function.extend_apply' _ _ _ h] + +/-- The old literals, broadcasts, and links are visible wherever the same +position is requested, including when the last batch uses padding. -/ +theorem input_local (x y : Pin N l b r → Bool) (j : Fin B) + (i : slots (copies (tape N l b) d)) + (he : ∀ e, position e = address N l b (port (tape N l b) d i).2 → x e = y e) : + bits (copies (tape N l b) d) (input pad x j) i = bits (copies (tape N l b) d) (input pad y j) i + := by + rw [input, input, Machine.inputs, Machine.inputs, bits_bundle, bits_bundle] + unfold padded + split + · rw [bits_feed, bits_feed] + generalize address N l b (port (tape N l b) d i).2 = t at he ⊢ + rcases t with k|k|k + · exact he (.inl (_, k)) rfl + · exact he (.inr (.inl k)) rfl + · apply view_local + exact fun e h => he (.inr (.inr e)) (congrArg (fun s => (.inr (.inr s) : Ports N l b)) h) + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Pin +end + +/- +# Distributing a substituted block + +The processor count is fixed before the number of copies in a batch +is known. Extra copies may be fed an accepting constant input. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Machine +variable {F : Type} [Field F] {N l b n h d B r : ℕ} + +open Classical in +/-- Computes the machine diagram by the application `Diagram F (copies (tape N l b) d) (copies +.unit d)`. -/ +abbrev MachineDiagram (F : Type) (N l b d : ℕ) := + Diagram F (copies (tape N l b) d) (copies .unit d) + +open Classical in +/-- The data for the scheme construction, including `links`, `layout`, `colors`, `exterior`, +`packets`. -/ +structure Scheme (A : Expansion F n h) (hn : 2 ≤ n) (G : MachineDiagram F N l b d) (r B : ℕ) where + links : 64 * (3 * r) ^ 2 ≤ N + /-- The `Scheme` component of type `Layout G n r h`. -/ + layout : Layout G n r h + /-- The `Scheme` component of type `Ports N l b → Label n r`. -/ + colors : Ports N l b → Label n r + exterior : ∀ i, layout.color (.inr (.inl i)) = colors (address N l b (port (tape N l b) d i).2) + packets : ∀ s : Packet n r (B * layout.d) → A.I, A.budget hn N (A.report hn s) + pins : ∀ (R : A.Report r (B * layout.d)) (u : Worker r), + let f := A.owner hn N R ∘ colors + 128 * Fintype.card {e : Pin N l b r // Pin.src f e ≠ Pin.dst f e ∧ + (Pin.src f e = u ∨ Pin.dst f e = u)} ≤ N + +namespace Scheme + +variable {A : Expansion F n h} {hn : 2 ≤ n} {G : MachineDiagram F N l b d} + (S : Scheme A hn G r B) + +open Classical in +/-- The quantity computed by `A.Accepted (r := r) (d := B * S.layout.d) hn (A.budget hn N)`. -/ +abbrev Report := A.Accepted (r := r) (d := B * S.layout.d) hn (A.budget hn N) + +open Classical in +/-- The value specified by `A.owner hn N R.1 ∘ S.colors`. -/ +def toSite (R : S.Report) := A.owner hn N R.1 ∘ S.colors + +open Classical in +/-- Computes the serial by the application `A.ExtraSerial hn N R.1 (Worker.index r) (Pin.src +(S.toSite R)) (Pin.dst (S.toSite R))`. -/ +abbrev Serial (R : S.Report) := + A.ExtraSerial hn N R.1 (Worker.index r) (Pin.src (S.toSite R)) (Pin.dst (S.toSite R)) + +variable (pad : Val (tape N l b)) (R : S.Report) + +open Classical in +/-- The supplied literal at a site is used only there. Other literal +bits are transmitted as part of the virtual assignment. -/ +def joint (ξ : Fin l → Bool) (u : Worker r) (y : Pin N l b r → Bool) + (z : A.Assignment hn N R.1) : F := + Pin.mask F u ξ y * S.layout.localWeight A (Pin.input pad y) (fun _ => unitCopies d) u z + +open Classical in +theorem joint_local (ξ : Fin l → Bool) (u : Worker r) (y y' : Pin N l b r → Bool) + (s t : A.Assignment hn N R.1) + (hy : ∀ e, Pin.src (S.toSite R) e = u ∨ Pin.dst (S.toSite R) e = u → y e = y' e) + (hs : ∀ e, A.src hn N R.1 e = u ∨ A.dst hn N R.1 e = u → s e = t e) : + S.joint pad R ξ u y s = S.joint pad R ξ u y' t := by + unfold joint + apply congrArg₂ (· * ·) (Pin.mask_local u ξ y y' _ (fun e h => hy e (.inl h))) + apply S.layout.localWeight_depends A u s t _ (fun _ _ _ => rfl) hs + intro j i hi + apply Pin.input_local + intro e he + apply hy e + right + unfold Pin.dst toSite Function.comp + rw [he, ← S.exterior] + exact hi + +open Classical in +/-- The simulate of type `F` for the given inputs. -/ +def simulate (serial : S.Serial R) (u : Fin (3 * r)) (ξ : Fin l → Bool) (bits : Fin (N / 4) → Bool) + : F := + A.extraProcessor hn N R.1 (Worker.index r) R.2.2 S.links + (Pin.src (S.toSite R)) (Pin.dst (S.toSite R)) (S.pins R.1) (S.joint pad R ξ) serial u bits + +end Scheme +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end + +/- +# Scalar equality for the physical simulation + +The literal strings may depend on the entire replacement graph. +At run time each processor sees only its own string. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Scheme + +open Finset Machine +variable {F : Type} [Field F] {N l b n h d B r : ℕ} {A : Expansion F n h} + {hn : 2 ≤ n} {G : MachineDiagram F N l b d} (S : Scheme A hn G r B) + (pad : Val (tape N l b)) (ξ : Fin (3 * r) → Fin l → Bool) + +open Classical in +private theorem route (R : S.Report) (serial : S.Serial R) : + (∑ y, ∑ a : A.Assignment hn N R.1, ∏ u, S.joint pad R (ξ (Worker.index r u)) u y a) = + ∑ t, ∏ i, S.simulate pad R serial i (ξ i) (Links.view i t) := by + let g := fun u => S.joint pad R (ξ (Worker.index r u)) u + have he := A.physical_extra hn N R.1 (Worker.index r) R.2.2 S.links + (Pin.src (S.toSite R)) (Pin.dst (S.toSite R)) (S.pins R.1) g + (fun u => S.joint_local pad R _ u) serial + refine he.trans (sum_congr rfl (fun t _ => prod_congr rfl (fun i _ => ?_))) + unfold simulate + apply congrFun + apply A.extraProcessor_congr + simp only [g, Equiv.apply_symm_apply] + +open Classical in +theorem unpinned (serial : (R : S.Report) → S.Serial R) : + (∑ z, ∑ y, ∏ j : Fin B, G.eval (Machine.inputs pad ξ z y j) (unitCopies d)) = + ∑ R, ∑ t, ∏ i, S.simulate pad R (serial R) i (ξ i) (Links.view i t) := by + rw [← Pin.sum_masks ξ (fun s z y => + ∏ j : Fin B, G.eval (Machine.inputs pad s z y j) (unitCopies d))] + have he (y : Pin N l b r → Bool) := + S.layout.virtual A hn N (A.budget hn N) S.packets (Pin.input pad y) (fun _ => unitCopies d) + simp only [Pin.input] at he + simp_rw [he, mul_sum, ← prod_mul_distrib] + rw [sum_comm] + apply sum_congr rfl + intro R _ + exact S.route pad ξ R (serial R) + +open Classical in +/-- All sums in the simulation are over assignments with multiplicity +one. The width of a physical processor's view is only `N / 4`. -/ +theorem replay (U : Val (tape N l b) → Val .unit → F) (serial : (R : S.Report) → S.Serial R) + (hR : 3 * r ≤ B * d) (hx : U pad () = 1) (hG : G.eval = power U d) : + scalar U ξ = ∑ R, ∑ t, ∏ i, S.simulate pad R (serial R) i (ξ i) (Links.view i t) := + (substitute U ξ pad G hR hx hG).trans (S.unpinned pad ξ serial) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Scheme +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/TemplateSize.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/TemplateSize.lean new file mode 100644 index 0000000000..67dd553ee8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagonal/TemplateSize.lean @@ -0,0 +1,190 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.AlphabetCode + +/-! # Locality at stations and junctions of a subdivided graph -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} [Field F] {a b : Wire} (G : Diagram F a b) + {x x' : Val a} {y y' : Val b} {s s' : G.End → Bool} + +theorem station_local (v : G.V) (hs : ∀ e, G.station e = v → s e = s' e) : + G.normalized.vertex x y s (.inl v) = G.normalized.vertex x' y' s' (.inl v) := by + unfold vertex + apply congrArg₂ (G.table v).2.2 + · apply congrArg (bits (G.table v).1).symm + funext i + exact hs (.inl (G.src ⟨v, i⟩)) (congrArg Sigma.fst (G.src.symm_apply_apply _)) + · apply congrArg (bits (G.table v).2.1).symm + funext i + exact hs (.inr (G.dst ⟨v, i⟩)) (congrArg Sigma.fst (G.dst.symm_apply_apply _)) + +theorem junction_local (v : G.Joint) + (hx : ∀ i, Sum.inl i = v → bits a x i = bits a x' i) + (hy : ∀ j, Sum.inr (.inl j) = v → bits b y j = bits b y' j) + (hs : ∀ e, G.junction e = v → s e = s' e) : + G.normalized.vertex x y s (.inr v) = G.normalized.vertex x' y' s' (.inr v) := by + let f (a b : Bool) : F := if a = b then 1 else 0 + rcases v with i|j|e + · exact congrArg₂ f (hx i rfl) (hs (.inl (.inl i)) rfl) + · exact congrArg₂ f (hs (.inr (.inl j)) rfl) (hy j rfl) + · exact congrArg₂ f (hs (.inr (.inr e)) rfl) (hs (.inl (.inr e)) rfl) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- # Shared and private symbols of a reported contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Spectral +variable {F : Type} [Field F] {n h d r : ℕ} (A : Expansion F n h) + (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) + +/-- Indexes the edge by the coordinates of `(Position n r d h × Bool) ⊕ Class r`. -/ +abbrev Edge (n r d h : ℕ) := (Position n r d h × Bool) ⊕ Class r + +/-- Returns `.station (x (other hn R.1))` when `x R.1 ∈ A.reportGroups N R` holds, and `.home (x +R.1)` otherwise. -/ +def owner (x : Label n r) : Worker r := + if x R.1 ∈ A.reportGroups N R then .station (x (other hn R.1)) else .home (x R.1) + +/-- Computes the endpoint by the application `corner p.1.1 (if b then Cube.flip Finset.univ +p.2.1 else p.2.1)`. -/ +def endpoint (p : Position n r d h) (b : Bool) : Label n r := + corner p.1.1 (if b then Cube.flip Finset.univ p.2.1 else p.2.1) + +/-- In the case `.inl (p, b)`, this construction gives `A.owner hn N R (endpoint p b)`. -/ +def src : Edge n r d h → Worker r + | .inl (p, b) => A.owner hn N R (endpoint p b) + | .inr c => if A.shared N R c then .home c.1 else .packet c.2.2 + +/-- In the case `.inl (p, b)`, this construction gives `let c := packetClass hn R.1 p.1`. -/ +def dst : Edge n r d h → Worker r + | .inl (p, b) => + let c := packetClass hn R.1 p.1 + if A.shared N R c then A.owner hn N R (endpoint p b) else .packet c.2.2 + | .inr c => if A.shared N R c then .home c.2.1 else .packet c.2.2 + +/-- In the case `.inl _`, this construction gives `1`. -/ +def size : Edge n r d h → ℕ + | .inl _ => 1 + | .inr c => A.classWidth R c + +/-- In the case `.inl _`, this construction gives `Bool`. -/ +abbrev symbol : Edge n r d h → Type + | .inl _ => Bool + | .inr c => A.Alphabet hn N R c + +open Classical in +instance symbolFintype : (e : Edge n r d h) → Fintype (A.symbol hn N R e) + | .inl _ => inferInstanceAs (Fintype Bool) + | .inr c => inferInstanceAs (Fintype (A.Alphabet hn N R c)) + +/-- The indexing data represented by `(e : Edge n r d h) → A.symbol hn N R e`. -/ +abbrev Assignment := (e : Edge n r d h) → A.symbol hn N R e + +/-- Evaluates `a (.inl ((p, i), b))` at the input `p i`. -/ +def rows {hn : 2 ≤ n} {N : ℕ} {R : A.Report r d} (a : A.Assignment hn N R) (b : Bool) : + Packet n r d → Block n h := fun p i => a (.inl ((p, i), b)) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +section +/- +# Sizes of worker templates + +Projecting the vertex labels to any one coordinate preserves the +density bound. The two endpoints of the padded slots are exactly +uniform in each coordinate, so the same estimate covers padding pins. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal + +open Finset Spectral +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {n r d h M : ℕ} (L : Layout G n r h) + +theorem project_bound {V : Type} [Fintype V] (f : V → Label n r) + (hv : ∀ z, multiplicity f z * r ^ n ≤ M) + (i : Fin n) (g : Fin r) : + multiplicity (fun v => f v i) g * r ≤ M := by + classical + let Z := {z : Label n r // z i = g} + let e : {v // f v i = g} ≃ (Σ z : Z, {v // f v = z.val}) := + { toFun := fun v => ⟨⟨f v.val, v.property⟩, v.val, rfl⟩ + invFun := fun p => ⟨p.2.val, by rw [p.2.property, p.1.property]⟩ + left_inv := fun _ => rfl + right_inv := by rintro ⟨⟨z, hz⟩, v, hv⟩; change f v = z at hv; subst z; rfl } + have he : multiplicity (fun v => f v i) g = ∑ z : Z, multiplicity f z.val := by + unfold multiplicity + rw [Fintype.card_congr e, Fintype.card_sigma] + have hz : Fintype.card Z * r = r ^ n := label_uniform i g + apply Nat.le_of_mul_le_mul_right (c := r ^ n) _ (pow_pos (Fin.pos g) _) + calc + _ = (∑ z : Z, multiplicity f z.val * r ^ n) * r := by rw [he, ← sum_mul, mul_right_comm] + _ ≤ (∑ _z : Z, M) * r := Nat.mul_le_mul_right r (sum_le_sum fun z _ => hv z.val) + _ = M * r ^ n := by simp only [sum_const, card_univ, nsmul_eq_mul, Nat.cast_id]; rw [← hz]; ring + +theorem Layout.vertex_bound (hv : ∀ z, multiplicity L.color z * r ^ n ≤ 16 * M) + (i : Fin n) (g : Fin r) : + multiplicity (fun v => L.color v i) g * r ≤ 16 * M := project_bound L.color hv i g + +/-- In particular this counts every location of an input padding pin. -/ +theorem endpoint_uniform (b : Bool) (i : Fin n) (g : Fin r) : + multiplicity (fun p : Position n r d h => Expansion.endpoint p b i) g * r = + Fintype.card (Position n r d h) := by + let f (j : Cube n × Fin h) := if b then !(j.1 i) else j.1 i + have he (p : Packet n r d) (j : Cube n × Fin h) : + Expansion.endpoint (p, j) b i = group p.1 i (f j) := by + cases b <;> simp [Expansion.endpoint, corner, group, Cube.flip, f] + have hm : multiplicity (fun p : Position n r d h => Expansion.endpoint p b i) g = + ∑ j : Cube n × Fin h, multiplicity (fun p : Packet n r d => group p.1 i (f j)) g := by + simp only [multiplicity, Fintype.card_subtype] + have hcard (p : Position n r d h → Prop) [DecidablePred p] : + (univ.filter p).card = ∑ i, if p i then 1 else 0 := by simp + rw [hcard, Fintype.sum_prod_type, sum_comm] + simp only [he, sum_boole, Nat.cast_id] + rw [hm, sum_mul] + simp only [group_uniform, sum_const, card_univ, nsmul_eq_mul, Nat.cast_id, + Position, Fintype.card_prod] + ring + +theorem Layout.end_bound (hv : Fintype.card (Position n r L.d h) ≤ 13 * M) + (i : Fin n) (g : Fin r) : + (multiplicity (fun e => L.color (.inl (G.station e)) i) g + + multiplicity (fun e => L.color (.inr (G.junction e)) i) g) * r ≤ 26 * M := by + have bound (b : Bool) (f : G.End → Fin r) + (hf : ∀ e, Expansion.endpoint (L.assign e) b i = f e) : + multiplicity f g * r ≤ 13 * M := by + have he : multiplicity f g ≤ + multiplicity (fun p : Position n r L.d h => Expansion.endpoint p b i) g := by + let lift : {e // f e = g} → {p // Expansion.endpoint p b i = g} := + fun e => ⟨L.assign e.val, (hf e.val).trans e.property⟩ + apply Fintype.card_le_of_injective lift + intro x y hxy + exact Subtype.ext (L.assign.injective (congrArg Subtype.val hxy)) + exact (Nat.mul_le_mul_right r he).trans ((endpoint_uniform b i g).le.trans hv) + have h₀ := bound false (fun e => L.color (.inl (G.station e)) i) + (fun e => congrArg (fun t => t.1 i) (L.follows e)) + have h₁ := bound true (fun e => L.color (.inr (G.junction e)) i) + (fun e => congrArg (fun t => t.2 i) (L.follows e)) + rw [add_mul] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Basic.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Basic.lean new file mode 100644 index 0000000000..18b56ed048 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Basic.lean @@ -0,0 +1,72 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Wide + +/-! +# Bit networks as finite directed multigraphs + +Every argument slot belongs either to a named exterior position or to +one end of an internal edge. The two bijections specify this incidence +without requiring a topological order. In particular, loops are allowed. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- The data for the diagram construction, including `V`, `[fv`, `E`, `[fe`, `table`. -/ +structure Diagram (F : Type) (a b : Wire) where + /-- The type of vertices. -/ + V : Type + [fv : Fintype V] + /-- The type of edges. -/ + E : Type + [fe : Fintype E] + /-- The local table at each indexed position carried by `Diagram`, with type `V → Table F`. -/ + table : V → Table F + /-- Names all input-side ports by either a boundary input or an internal edge. -/ + src : (Σ v, slots (table v).1) ≃ slots a ⊕ E + /-- Names all output-side ports by either a boundary output or an internal edge. -/ + dst : (Σ v, slots (table v).2.1) ≃ slots b ⊕ E + +attribute [instance] Diagram.fv Diagram.fe + +namespace Diagram +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +/-- The quantity computed by `wd (G.table v).1 + wd (G.table v).2.1`. -/ +def arity (v : G.V) : ℕ := wd (G.table v).1 + wd (G.table v).2.1 +/-- The sum of `(1 + G.arity v)` indexed by `v`. -/ +def cost : ℕ := ∑ v, (1 + G.arity v) + +/-- The condition `∀ v, G.arity v ≤ 3` on the specified data. -/ +def Trivalent : Prop := ∀ v, G.arity v ≤ 3 +/-- The condition `∀ v, G.arity v ≤ u ∧ (G.arity v ≤ 3 ∨ G.table v ∈ L)` on the specified data. -/ +def Admits (u : ℕ) (L : Set (Table F)) : Prop := + ∀ v, G.arity v ≤ u ∧ (G.arity v ≤ 3 ∨ G.table v ∈ L) + +/-- The value specified by `(G.src.symm (.inr e)).1`. -/ +def source (e : G.E) : G.V := (G.src.symm (.inr e)).1 +/-- The value specified by `(G.dst.symm (.inr e)).1`. -/ +def target (e : G.E) : G.V := (G.dst.symm (.inr e)).1 + +/-- Weight of one station before the internal edge bits are summed. -/ +def vertex (x : Val a) (y : Val b) (z : G.E → Bool) (v : G.V) : F := + (G.table v).2.2 + ((bits (G.table v).1).symm (fun i => Sum.elim (bits a x) z (G.src ⟨v, i⟩))) + ((bits (G.table v).2.1).symm (fun i => Sum.elim (bits b y) z (G.dst ⟨v, i⟩))) + +/-- The eval of type `F` for the given inputs. -/ +noncomputable def eval [Field F] (x : Val a) (y : Val b) : F := by + classical + exact ∑ z : G.E → Bool, ∏ v, G.vertex x y z v + +end Diagram +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Canonical.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Canonical.lean new file mode 100644 index 0000000000..358033bec4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Canonical.lean @@ -0,0 +1,242 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Normalize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement + +/-! +# Canonical port shapes + +Replace each local bundle by a word of the same length. A fixed port +order for each shape is essential because distinct nestings of pairs +and units can represent arbitrarily many trivalent table labels. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram +open Finset + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def order (a : Wire) : slots (word (wd a)) ≃ slots a := + Fintype.equivOfCardEq (by rw [card_slots, wd_word, card_slots]) + +open scoped Classical in +/-- The indexed operation `⟨word (wd T.1), word (wd T.2.1), fun x y => T.2.2 (reindex (order +T.1).symm x) (reindex (order T.2.1).symm y)⟩`. -/ +abbrev relabel (T : Table F) : Table F := + ⟨word (wd T.1), word (wd T.2.1), + fun x y => T.2.2 (reindex (order T.1).symm x) (reindex (order T.2.1).symm y)⟩ + +open scoped Classical in +/-- Builds `Diagram F a b where V` with the specified `table`, `src`, `dst`. -/ +abbrev canonical : Diagram F a b where + V := G.V + E := G.E + table v := relabel (G.table v) + src := (Equiv.sigmaCongrRight fun v => order (G.table v).1).trans G.src + dst := (Equiv.sigmaCongrRight fun v => order (G.table v).2.1).trans G.dst + +open scoped Classical in +theorem source_canonical (e : G.E) : G.canonical.source e = G.source e := rfl +open scoped Classical in +theorem target_canonical (e : G.E) : G.canonical.target e = G.target e := rfl + +open scoped Classical in +@[simp] theorem arity_canonical (v : G.V) : G.canonical.arity v = G.arity v := by + simp only [arity, wd_word] + +open scoped Classical in +@[simp] theorem cost_canonical : G.canonical.cost = G.cost := by + unfold cost + exact sum_congr rfl fun v _ => congrArg (1 + ·) (G.arity_canonical v) + +open scoped Classical in +private theorem recover (a : Wire) (f : slots a → Bool) : + reindex (order a).symm ((bits (word (wd a))).symm (f ∘ order a)) = (bits a).symm f := by + apply (bits a).injective + funext j + simp [Function.comp_def] + +open scoped Classical in +@[simp] theorem vertex_canonical (x : Val a) (y : Val b) (z : G.E → Bool) (v : G.V) : + G.canonical.vertex x y z v = G.vertex x y z v := by + apply congrArg₂ (G.table v).2.2 + · exact recover _ (fun i => Sum.elim (bits a x) z (G.src ⟨v, i⟩)) + · exact recover _ (fun i => Sum.elim (bits b y) z (G.dst ⟨v, i⟩)) + +open scoped Classical in +@[simp] theorem eval_canonical [Field F] : G.canonical.eval = G.eval := by + funext x y + unfold eval + exact sum_congr rfl fun z _ => prod_congr rfl fun v _ => G.vertex_canonical x y z v + +variable [Field F] [Fintype F] + +open scoped Classical in +private abbrev Shape := {p : Fin 4 × Fin 4 // p.1.val + p.2.val ≤ 3} + +open scoped Classical in +private def small (p : Shape) : Finset (Table F) := + univ.image (fun f : Val (word p.val.1) → Val (word p.val.2) → F => + ⟨word p.val.1, word p.val.2, f⟩) + +open scoped Classical in +private theorem small_bound (p : Shape) : (small (F := F) p).card ≤ Fintype.card F ^ 8 := by + have hv (a : Wire) : Fintype.card (Val a) = 2 ^ wd a := by + rw [Fintype.card_congr (bits a), Fintype.card_fun, Fintype.card_bool, card_slots] + refine card_image_le.trans ?_ + simp only [card_univ, Fintype.card_fun, hv, wd_word, ←pow_mul, ←pow_add] + apply Nat.pow_le_pow_right Fintype.card_pos + exact Nat.pow_le_pow_right (by decide : 0 < 2) (by omega : p.val.2.val + p.val.1.val ≤ 3) + +open scoped Classical in +/-- All trivalent tables fit in a finite dictionary. Every prescribed +wide table contributes at most one additional entry. -/ +theorem canonical_palette {u : ℕ} {L : Finset (Table F)} (h : G.Admits u ↑L) : + (univ.image G.canonical.table).card ≤ L.card + 16 * Fintype.card F ^ 8 := by + have sub : univ.image G.canonical.table ⊆ L.image relabel ∪ univ.biUnion small := by + rintro _ hq + obtain ⟨v, _, rfl⟩ := mem_image.mp hq + rcases (h v).2 with hs | hl + · let i := wd (G.table v).1 + let j := wd (G.table v).2.1 + change i + j ≤ 3 at hs + let p : Shape := ⟨(⟨i, by omega⟩, ⟨j, by omega⟩), hs⟩ + refine mem_union_right _ (mem_biUnion.mpr ⟨p, mem_univ _, ?_⟩) + exact mem_image.mpr ⟨(G.canonical.table v).2.2, mem_univ _, rfl⟩ + · exact mem_union_left _ (mem_image_of_mem _ hl) + have hc : Fintype.card Shape ≤ 16 := by + simpa using Fintype.card_subtype_le (fun p : Fin 4 × Fin 4 => p.1.val + p.2.val ≤ 3) + refine (card_le_card sub).trans ((card_union_le ..).trans (Nat.add_le_add card_image_le ?_)) + calc + _ ≤ ∑ p, (small (F := F) p).card := card_biUnion_le + _ ≤ ∑ _ : Shape, Fintype.card F ^ 8 := sum_le_sum fun p _ => small_bound p + _ ≤ _ := by simpa using Nat.mul_le_mul_right (Fintype.card F ^ 8) hc + +open scoped Classical in +/-- Subdivide edges and relabel the resulting diagram, including the +new equality tables. The exterior positions remain unchanged. -/ +theorem canonical_normalized {u : ℕ} {L : Finset (Table F)} (h : G.Admits u ↑L) : + let H := G.normalized.canonical + H.eval = G.eval ∧ H.cost ≤ 4 * G.cost ∧ (∀ v, H.arity v ≤ max 2 u) ∧ + (∀ e, H.source e ≠ H.target e) ∧ + (univ.image H.table).card ≤ L.card + 16 * Fintype.card F ^ 8 := by + have hn : G.normalized.Admits (max 2 u) ↑L := G.admits_normalized (le_max_left ..) + (fun v => ⟨(h v).1.trans (le_max_right ..), (h v).2⟩) + exact ⟨G.normalized.eval_canonical.trans (funext fun x => funext fun y => G.eval_normalized x y), + G.normalized.cost_canonical.le.trans G.cost_normalized, + fun v => (G.normalized.arity_canonical v).le.trans (hn v).1, + G.normalized_loopless, G.normalized.canonical_palette hn⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- +# Replacing each station by a diagram + +Every old wire end is attached to the corresponding exterior position +of a replacement. Internal wires of different replacements are disjoint. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + (q : ∀ v, Diagram F (G.table v).1 (G.table v).2.1) + +/-- Reindexes `(Σ v, P v ⊕ Q v)` and `A ⊕ E ⊕ (Σ v, Q v)` by an equivalence. -/ +def splice {V A E : Type} {P Q : V → Type} (e : (Σ v, P v) ≃ A ⊕ E) : + (Σ v, P v ⊕ Q v) ≃ A ⊕ E ⊕ (Σ v, Q v) := + (Equiv.sigmaSumDistrib _ _).trans ((e.sumCongr (.refl _)).trans (Equiv.sumAssoc _ _ _)) + +/-- Builds `Diagram F a b where V` with the specified `table`, `src`, `dst`. -/ +abbrev plug : Diagram F a b where + V := Σ v, (q v).V + E := G.E ⊕ (Σ v, (q v).E) + table t := (q t.1).table t.2 + src := (Equiv.sigmaAssoc (fun v w => slots ((q v).table w).1)).trans + ((Equiv.sigmaCongrRight (fun v => (q v).src)).trans (splice G.src)) + dst := (Equiv.sigmaAssoc (fun v w => slots ((q v).table w).2.1)).trans + ((Equiv.sigmaCongrRight (fun v => (q v).dst)).trans (splice G.dst)) + +/-- Reindexes `(Σ v, (q v).End)` and `(G.plug q).End` by an equivalence. -/ +def plugEnd : (Σ v, (q v).End) ≃ (G.plug q).End := + (Equiv.sigmaSumDistrib _ _).trans ((splice G.src).sumCongr (splice G.dst)) + +theorem plugEnd_port (v : G.V) (p : Σ w, (q v).Port w) : + G.plugEnd q ⟨v, (q v).portEquiv p⟩ = (G.plug q).portEquiv ⟨⟨v, p.1⟩, p.2⟩ := by + rcases p with ⟨w, i|j⟩ <;> rfl + +theorem station_plugEnd (v : G.V) (e : (q v).End) : + (G.plug q).station (G.plugEnd q ⟨v, e⟩) = ⟨v, (q v).station e⟩ := by + obtain ⟨p, rfl⟩ := (q v).portEquiv.surjective e + rw [plugEnd_port, station_port, station_port] + +private theorem splice_eval {V A E : Type} {P Q : V → Type} (e : (Σ v, P v) ≃ A ⊕ E) + (x : A → Bool) (z : E → Bool) (t : ∀ v, Q v → Bool) (v : V) (i : P v ⊕ Q v) : + Sum.elim x (Sum.elim z (fun p => t p.1 p.2)) (splice e ⟨v, i⟩) = + Sum.elim (fun j => Sum.elim x z (e ⟨v, j⟩)) (t v) i := by + cases i with + | inr _ => rfl + | inl j => + change Sum.elim _ _ (Equiv.sumAssoc _ _ _ (.inl (e ⟨v, j⟩))) = Sum.elim x z (e ⟨v, j⟩) + cases e ⟨v, j⟩ <;> rfl + +private def inputAt (x : Val a) (z : G.E → Bool) (v : G.V) := + (bits (G.table v).1).symm (fun i => Sum.elim (bits a x) z (G.src ⟨v, i⟩)) + +private def outputAt (y : Val b) (z : G.E → Bool) (v : G.V) := + (bits (G.table v).2.1).symm (fun i => Sum.elim (bits b y) z (G.dst ⟨v, i⟩)) + +private def assignments : (G.E → Bool) × (∀ v, (q v).E → Bool) ≃ ((G.plug q).E → Bool) := + ((Equiv.refl _).prodCongr (Equiv.piCurry (fun v (_ : (q v).E) => Bool)).symm).trans + (Equiv.sumArrowEquivProdArrow _ _ _).symm + +private theorem vertex_plug (x : Val a) (y : Val b) (z : G.E → Bool) (t : ∀ v, (q v).E → Bool) + (v : G.V) (w : (q v).V) : + (G.plug q).vertex x y (assignments G q (z, t)) ⟨v, w⟩ = + (q v).vertex (G.inputAt x z v) (G.outputAt y z v) (t v) w := by + unfold vertex inputAt outputAt + simp only [Equiv.apply_symm_apply] + apply congrArg₂ ((q v).table w).2.2 + · exact congrArg (bits ((q v).table w).1).symm + (funext fun i => splice_eval G.src (bits a x) z t v ((q v).src ⟨w, i⟩)) + · exact congrArg (bits ((q v).table w).2.1).symm + (funext fun i => splice_eval G.dst (bits b y) z t v ((q v).dst ⟨w, i⟩)) + +/-- After fixing the old wire bits, all local contractions are independent. -/ +theorem eval_plug [Field F] (hf : ∀ v, (q v).eval = (G.table v).2.2) : + (G.plug q).eval = G.eval := by + classical + funext x y + unfold eval + trans ∑ u, ∏ v, (G.plug q).vertex x y (assignments G q u) v + · symm + refine ((assignments G q).sum_comp (fun z => ∏ v, (G.plug q).vertex x y z v)).trans ?_ + exact Finset.sum_congr (by ext; simp) (fun _ _ => rfl) + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro z _ + have he (v : G.V) : G.vertex x y z v = + ∑ t, ∏ w, (q v).vertex (G.inputAt x z v) (G.outputAt y z v) t w := + congrFun (congrFun (hf v).symm _) _ + simp only [he, Fintype.prod_sum] + apply Finset.sum_congr rfl + intro t _ + rw [Fintype.prod_sigma] + exact Finset.prod_congr rfl fun v _ => Finset.prod_congr rfl fun w _ + => vertex_plug G q x y z t v w + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Normalize.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Normalize.lean new file mode 100644 index 0000000000..be82844e06 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Normalize.lean @@ -0,0 +1,237 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import Mathlib.Algebra.BigOperators.Ring.Finset + +/-! # Subdivision preserves the contraction in every characteristic -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} [Field F] {a b : Wire} (G : Diagram F a b) (x : Val a) (y : Val b) + +private def inflate (s : G.E → Bool) : G.End → Bool := + Sum.elim (Sum.elim (bits a x) s) (Sum.elim (bits b y) s) + +private theorem joint_one (s : G.E → Bool) (j : G.Joint) : + G.normalized.vertex x y (G.inflate x y s) (.inr j) = 1 := by + rcases j with i | j | e + · change (if bits a x i = bits a x i then 1 else 0) = 1 + simp + · change (if bits b y j = bits b y j then 1 else 0) = 1 + simp + · change (if s e = s e then 1 else 0) = 1 + simp + +private theorem product_inflate (s : G.E → Bool) : + ∏ v, G.normalized.vertex x y (G.inflate x y s) v = ∏ v, G.vertex x y s v := by + rw [Fintype.prod_sum_type] + have hj : (∏ j : G.Joint, G.normalized.vertex x y (G.inflate x y s) (.inr j)) = 1 := + Finset.prod_eq_one (fun j _ => G.joint_one x y s j) + rw [hj, mul_one] + rfl + +private theorem exists_inflate (z : G.End → Bool) + (hz : ∏ v, G.normalized.vertex x y z v ≠ 0) : + ∃ s, G.inflate x y s = z := by + classical + have ne (j : G.Joint) := Finset.prod_ne_zero_iff.mp hz (.inr j) (Finset.mem_univ _) + refine ⟨fun e => z (.inl (.inr e)), funext ?_⟩ + rintro ((i|e)|(j|e)) + · have h := ne (.inl i) + change (if bits a x i = z (.inl (.inl i)) then (1 : F) else 0) ≠ 0 at h + simpa [inflate] using h + · rfl + · have h := ne (.inr (.inl j)) + change (if z (.inr (.inl j)) = bits b y j then (1 : F) else 0) ≠ 0 at h + simpa [inflate, eq_comm] using h + · have h := ne (.inr (.inr e)) + change (if z (.inr (.inr e)) = z (.inl (.inr e)) then (1 : F) else 0) ≠ 0 at h + simpa [inflate, eq_comm] using h + +/-- Any nonzero assignment agrees on both halves of every subdivided +edge, so it comes from a unique assignment of the original edges. -/ +theorem eval_normalized : G.normalized.eval x y = G.eval x y := by + classical + unfold eval + let _ : DecidableEq G.End := fun _ _ => Classical.propDecidable _ + let e : (G.E → Bool) ↪ (G.End → Bool) := ⟨G.inflate x y, + fun _ _ h => funext (fun i => congrFun h (.inl (.inr i)))⟩ + rw [← Finset.sum_subset (Finset.subset_univ (Finset.univ.map e)), Finset.sum_map] + · exact Finset.sum_congr rfl (fun s _ => G.product_inflate x y s) + · intro z _ h + by_contra hn + obtain ⟨s, rfl⟩ := G.exists_inflate x y z hn + exact h (Finset.mem_map.mpr ⟨s, Finset.mem_univ s, rfl⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- # Contracting a self-loop inside its station's table -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram +open Finset + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +open scoped Classical in +/-- The subtype of `e : G.E` satisfying `G.source e ≠ G.target e`. -/ +abbrev Cross := {e : G.E // G.source e ≠ G.target e} +open scoped Classical in +/-- The subtype of `e : G.E` satisfying `G.source e = v ∧ G.target e = v`. -/ +abbrev Loop (v : G.V) := {e : G.E // G.source e = v ∧ G.target e = v} + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def loopSrc : slots a ⊕ G.Cross → G.V := + Sum.elim (fun i => (G.src.symm (.inl i)).1) (fun e => G.source e.val) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def loopDst : slots b ⊕ G.Cross → G.V := + Sum.elim (fun i => (G.dst.symm (.inl i)).1) (fun e => G.target e.val) + +open scoped Classical in +/-- In the case `.inl i`, this construction gives `z (.inl i)`. -/ +def extendPort {I : Type} (v : G.V) (z : I ⊕ G.Cross → Bool) + (l : G.Loop v → Bool) : I ⊕ G.E → Bool + | .inl i => z (.inl i) + | .inr e => if h : G.source e ≠ G.target e then z (.inr ⟨e, h⟩) + else if hv : G.source e = v ∧ G.target e = v then l ⟨e, hv⟩ else false + +variable [Field F] + +open scoped Classical in +/-- The sum of `G.weight v (G.extendPort v x l) (G.extendPort v y l)` indexed by `l : G.Loop v → +Bool`. -/ +def loopWeight (v : G.V) (x : slots a ⊕ G.Cross → Bool) (y : slots b ⊕ G.Cross → Bool) : F + := + ∑ l : G.Loop v → Bool, G.weight v (G.extendPort v x l) (G.extendPort v y l) + +open scoped Classical in +private theorem loopWeight_local : Local G.loopSrc G.loopDst G.loopWeight := by + intro v x y x' y' hx hy + apply sum_congr rfl + intro l _ + apply G.local_weight + · rintro (i|e) hi + · exact hx (.inl i) hi + · by_cases h : G.source e ≠ G.target e + · simpa only [extendPort, dite_eq_left h] using hx (.inr ⟨e, h⟩) hi + · simp only [extendPort, dite_eq_right h] + · rintro (i|e) hi + · exact hy (.inl i) hi + · by_cases h : G.source e ≠ G.target e + · simpa only [extendPort, dite_eq_left h] using hy (.inr ⟨e, h⟩) hi + · simp only [extendPort, dite_eq_right h] + +open scoped Classical in +/-- The vertex indices and exterior ports stay in place. Every self-loop +is summed inside a single table, with no scalar divisions. -/ +abbrev removeLoops : Diagram F a b := ofLocal G.loopSrc G.loopDst G.loopWeight + +open scoped Classical in +theorem removeLoops_loopless (e : G.removeLoops.E) : G.removeLoops.source e ≠ G.removeLoops.target + e := e.2 + +open scoped Classical in +theorem arity_removeLoops (v : G.V) : G.removeLoops.arity v ≤ G.arity v := by + let c : G.Cross ↪ G.E := ⟨Subtype.val, Subtype.val_injective⟩ + let f := ((Function.Embedding.refl (slots a)).sumMap c).sumMap + ((Function.Embedding.refl (slots b)).sumMap c) + have same (p : G.removeLoops.End) : G.station (f p) = G.removeLoops.station p := by + rcases p with (p|p)|(p|p) <;> rfl + rw [← G.degree, ← G.removeLoops.degree] + apply Fintype.card_le_of_injective + (fun p : {p : G.removeLoops.End // G.removeLoops.station p = v} => + (⟨f p.val, (same p.val).trans p.property⟩ : {p : G.End // G.station p = v})) + intro p q hpq + exact Subtype.ext (f.injective (congrArg Subtype.val hpq)) + +open scoped Classical in +private def fuse (z : G.Cross → Bool) (l : ∀ v, G.Loop v → Bool) (e : G.E) : Bool := + if h : G.source e ≠ G.target e then z ⟨e, h⟩ + else l (G.source e) ⟨e, rfl, (not_ne_iff.mp h).symm⟩ + +open scoped Classical in +private def split : (G.E → Bool) ≃ (G.Cross → Bool) × (∀ v, G.Loop v → Bool) where + toFun z := (fun e => z e.val, fun _ e => z e.val) + invFun p := G.fuse p.1 p.2 + left_inv z := by + funext e + by_cases h : G.source e ≠ G.target e <;> simp [fuse, h] + right_inv p := by + apply Prod.ext + · funext e + simp [fuse, e.property] + · funext v e + rcases e with ⟨e, h₁, h₂⟩ + have he : G.source e = G.target e := h₁.trans h₂.symm + subst v + simp [fuse, he] + +omit [Field F] in +open scoped Classical in +private theorem read_fuse {I : Type} (f : G.E → G.V) (hf : f = G.source ∨ f = G.target) + (x : I → Bool) (z : G.Cross → Bool) (l : ∀ v, G.Loop v → Bool) (v : G.V) (e : G.E) + (he : f e = v) : + G.extendPort v (Sum.elim x z) (l v) (.inr e) = G.fuse z l e := by + by_cases h : G.source e ≠ G.target e + · simp [extendPort, fuse, h] + · have H : G.source e = G.target e := not_ne_iff.mp h + have h₁ : G.source e = v := by rcases hf with rfl|rfl <;> simpa [H] using he + have hv : G.source e = v ∧ G.target e = v := ⟨h₁, H.symm.trans h₁⟩ + rw [extendPort, dite_eq_right h, dite_eq_left hv, fuse, dite_eq_right h] + cases h₁ + rfl + +open scoped Classical in +theorem eval_removeLoops : G.removeLoops.eval = G.eval := by + classical + let : DecidableEq G.Cross := fun _ _ => Classical.propDecidable _ + funext x y + rw [eval, eval] + calc + (∑ z : G.Cross → Bool, ∏ v, G.removeLoops.vertex x y z v) = + ∑ z : G.Cross → Bool, ∑ l : ∀ v, G.Loop v → Bool, ∏ v, + G.weight v (G.extendPort v (Sum.elim (bits a x) z) (l v)) + (G.extendPort v (Sum.elim (bits b y) z) (l v)) := by + apply sum_congr rfl + intro z _ + simp only [vertex_ofLocal _ _ _ G.loopWeight_local, loopWeight] + exact Fintype.prod_sum _ + _ = ∑ z : G.Cross → Bool, ∑ l : ∀ v, G.Loop v → Bool, ∏ v, G.vertex x y (G.fuse z l) v := by + apply sum_congr rfl + intro z _ + apply sum_congr rfl + intro l _ + apply prod_congr rfl + intro v _ + change G.weight v _ _ = G.weight v (Sum.elim (bits a x) (G.fuse z l)) + (Sum.elim (bits b y) (G.fuse z l)) + apply G.local_weight + · rintro (i|e) hi + · rfl + · exact G.read_fuse G.source (.inl rfl) _ z l v e hi + · rintro (i|e) hi + · rfl + · exact G.read_fuse G.target (.inr rfl) _ z l v e hi + _ = _ := by + let f (p : (G.Cross → Bool) × (∀ v, G.Loop v → Bool)) := + ∏ v, G.vertex x y (G.fuse p.1 p.2) v + calc + _ = ∑ p, f p := (Fintype.sum_prod_type f).symm + _ = _ := Fintype.sum_equiv G.split.symm _ _ (fun _ => rfl) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Pad.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Pad.lean new file mode 100644 index 0000000000..546ff02fb2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Pad.lean @@ -0,0 +1,456 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Input +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.ColumnNetwork +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Encode + +/-! # Removing scalar stations from a diagram -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +theorem slot_pos {d : Wire} (i : slots d) : 0 < wd d := + (card_slots d) ▸ Fintype.card_pos_iff.mpr ⟨i⟩ + +/-- Reindexes `(Σ v : {v // 0 < G.arity v}, slots (d v.val))` and `Σ v, slots (d v) where toFun +i` by an equivalence. -/ +def keepSlots (d : G.V → Wire) (h : ∀ v, wd (d v) ≤ G.arity v) : + (Σ v : {v // 0 < G.arity v}, slots (d v.val)) ≃ Σ v, slots (d v) where + toFun i := ⟨i.1.val, i.2⟩ + invFun i := ⟨⟨i.1, (slot_pos i.2).trans_le (h i.1)⟩, i.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +/-- Every wire end already belongs to a station of positive arity. -/ +abbrev prune : Diagram F a b where + V := {v : G.V // 0 < G.arity v} + E := G.E + table v := G.table v.val + src := (G.keepSlots (fun v => (G.table v).1) (fun _ => Nat.le_add_right _ _)).trans G.src + dst := (G.keepSlots (fun v => (G.table v).2.1) (fun _ => Nat.le_add_left _ _)).trans G.dst + +theorem arity_prune (v : G.prune.V) : G.prune.arity v = G.arity v.val := rfl + +theorem source_prune (e : G.E) : (G.prune.source e).val = G.source e := rfl + +theorem target_prune (e : G.E) : (G.prune.target e).val = G.target e := rfl + +private theorem scalar_vertex (v : G.V) (hv : ¬0 < G.arity v) + (x x' : Val a) (y y' : Val b) (z z' : G.E → Bool) : + G.vertex x y z v = G.vertex x' y' z' v := by + unfold vertex + apply congrArg₂ (G.table v).2.2 <;> apply congrArg <;> funext i + · exact (hv ((slot_pos i).trans_le (Nat.le_add_right _ _))).elim + · exact (hv ((slot_pos i).trans_le (Nat.le_add_left _ _))).elim + +/-- The product of the removed tables is independent of all bit assignments. +It may vanish, so we factor it out without dividing by it. -/ +theorem eval_prune [Field F] : ∃ c : F, ∀ x y, c * G.prune.eval x y = G.eval x y := by + classical + let x₀ := (bits a).symm (fun _ => false) + let y₀ := (bits b).symm (fun _ => false) + refine ⟨∏ v : {v // ¬0 < G.arity v}, G.vertex x₀ y₀ (fun _ => false) v.val, ?_⟩ + intro x y + rw [eval, eval, Finset.mul_sum] + apply Finset.sum_congr rfl + intro z _ + rw [mul_comm, ← Fintype.prod_subtype_mul_prod_subtype (fun v => 0 < G.arity v) + (G.vertex x y z)] + apply congrArg + exact Finset.prod_congr rfl fun v _ => G.scalar_vertex v.val v.property _ _ _ _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- # Independent copies of a directed network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram +open Diagonal + +variable {F I : Type} {n : ℕ} {a b : Wire} (G : Diagram F a b) (c : I ≃ Fin n) + +open Classical in +/-- Reindexes `(Σ q : I × G.V, Z q.2)` and `I × (Σ v, Z v) where toFun q` by an equivalence. -/ +def collect (Z : G.V → Type) : (Σ q : I × G.V, Z q.2) ≃ I × (Σ v, Z v) where + toFun q := (q.1.1, ⟨q.1.2, q.2⟩) + invFun q := ⟨(q.1, q.2.1), q.2.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +open Classical in +/-- Reindexes `(Σ q : I × G.V, Z q.2)` and `slots (copies d n) ⊕ (I × G.E)` by an equivalence. -/ +def io (d : Wire) (Z : G.V → Type) (p : (Σ v, Z v) ≃ slots d ⊕ G.E) : + (Σ q : I × G.V, Z q.2) ≃ slots (copies d n) ⊕ (I × G.E) := + (G.collect Z).trans <| ((Equiv.refl I).prodCongr p).trans <| + (Equiv.prodSumDistrib _ _ _).trans <| + (((c.prodCongr (.refl _)).trans (Diagonal.port d n).symm).sumCongr (.refl _)) + +open Classical in +/-- Builds `Diagram F (copies a n) (copies b n) where V` with the specified `table`, `src`, +`dst`. -/ +abbrev replicate [Fintype I] : Diagram F (copies a n) (copies b n) where + V := I × G.V + E := I × G.E + table v := G.table v.2 + src := G.io c a (fun v => slots (G.table v).1) G.src + dst := G.io c b (fun v => slots (G.table v).2.1) G.dst + +open Classical in +private theorem read_io (d : Wire) (Z : G.V → Type) (p : (Σ v, Z v) ≃ slots d ⊕ G.E) + (x : Fin n → Val d) (z : I → G.E → Bool) (i : I) (v : G.V) (t : Z v) : + Sum.elim (bits (copies d n) (Diagonal.bundle d n x)) (Function.uncurry z) + (G.io c d Z p ⟨(i, v), t⟩) = Sum.elim (bits d (x (c i))) (z i) (p ⟨v, t⟩) := by + change Sum.elim _ _ (Sum.map _ _ (Equiv.prodSumDistrib I _ _ (i, p ⟨v, t⟩))) = _ + cases p ⟨v, t⟩ with + | inl s => + change bits (copies d n) (Diagonal.bundle d n x) ((Diagonal.port d n).symm (c i, s)) = _ + simp [bits_bundle] + | inr e => rfl + +open Classical in +theorem bundle_surj (d : Wire) (n : ℕ) : Function.Surjective (Diagonal.bundle d n) := by + intro x + let v := fun i => (bits d).symm (fun s => bits (copies d n) x ((Diagonal.port d n).symm (i, s))) + refine ⟨v, (bits _).injective (funext fun s => ?_)⟩ + simp only [bits_bundle, v, Equiv.apply_symm_apply, Prod.mk.eta, Equiv.symm_apply_apply] + +variable [Fintype I] + +open Classical in +@[simp] theorem source_replicate (i : I) (e : G.E) : + (G.replicate c).source (i, e) = (i, G.source e) := rfl + +open Classical in +@[simp] theorem target_replicate (i : I) (e : G.E) : + (G.replicate c).target (i, e) = (i, G.target e) := rfl + +open Classical in +theorem vertex_replicate (x : Fin n → Val a) (y : Fin n → Val b) (z : I → G.E → Bool) + (i : I) (v : G.V) : + (G.replicate c).vertex (Diagonal.bundle a n x) (Diagonal.bundle b n y) + (Function.uncurry z) (i, v) = + G.vertex (x (c i)) (y (c i)) (z i) v := by + unfold vertex + apply congrArg₂ (G.table v).2.2 <;> apply congrArg <;> funext t + · exact G.read_io c a _ G.src x z i v t + · exact G.read_io c b _ G.dst y z i v t + +open Classical in +private theorem eval_curry [Field F] {E : Type} [Fintype E] + (e : G.E ≃ I × E) (x : Val a) (y : Val b) : + G.eval x y = ∑ z : I → E → Bool, ∏ v, G.vertex x y (Function.uncurry z ∘ e) v := by + let q := (e.arrowCongr (Equiv.refl Bool)).trans (Equiv.curry I E Bool) + unfold eval + rw [← q.symm.sum_comp] + rfl + +open Classical in +theorem eval_replicate [Field F] : (G.replicate c).eval = power G.eval n := by + funext x y + obtain ⟨X, rfl⟩ := bundle_surj _ _ x + obtain ⟨Y, rfl⟩ := bundle_surj _ _ y + rw [power_bundle, ← c.prod_comp] + rw [eval_curry (G.replicate c) (I := I) (E := G.E) (Equiv.refl _)] + unfold eval + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro z _ + rw [Fintype.prod_prod_type] + exact Finset.prod_congr rfl (fun i _ => Finset.prod_congr rfl + (fun v _ => G.vertex_replicate c X Y z i v)) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- # Deterministic circuits with a specified set of additional tables -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {F : Type} [Field F] + +/-- The condition `∃ s ≤ m, Wide F u L a b (fun x y => if f x = y then 1 else 0) s` on the +specified data. -/ +def DWide (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) + (a b : Wire) (f : Val a → Val b) (m : ℕ) : Prop := + ∃ s ≤ m, Wide F u L a b (fun x y => if f x = y then 1 else 0) s + +namespace DWide +variable {u m n : ℕ} {L : Set (Table F)} {a b c d : Wire} +variable {f : Val a → Val b} + +theorem mono (h : DWide F u L a b f m) (hv : m ≤ n) : DWide F u L a b f n := + let ⟨s, hs, hw⟩ := h + ⟨s, hs.trans hv, hw⟩ + +theorem pre {g : Val b → Val c} (h : DWide F u L b c g m) (k : Rewire a b f) : + DWide F u L a c (fun x => g (f x)) m := + let ⟨s, hs, hw⟩ := h + ⟨s, hs, hw.pre k⟩ + +theorem post {g : Val b → Val c} (h : DWide F u L a b f m) (k : Rewire b c g) : + DWide F u L a c (fun x => g (f x)) m := by + obtain ⟨s, hs, hw⟩ := h + obtain ⟨_, hk, he⟩ := k.inverse + exact ⟨s, hs, by simpa only [he] using hw.post hk⟩ + +theorem comp {g : Val b → Val c} (h : DWide F u L a b f m) (k : DWide F u L b c g n) : + DWide F u L a c (fun x => g (f x)) (m + n) := by + obtain ⟨s, hs, hw⟩ := h + obtain ⟨t, ht, hv⟩ := k + refine ⟨s + t, Nat.add_le_add hs ht, ?_⟩ + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + using hw.comp hv + +theorem par {g : Val c → Val d} (h : DWide F u L a b f m) (k : DWide F u L c d g n) : + DWide F u L (.pair a c) (.pair b d) (fun x => (f x.1, g x.2)) (m + n) := by + obtain ⟨s, hs, hw⟩ := h + obtain ⟨t, ht, hv⟩ := k + refine ⟨s + t, Nat.add_le_add hs ht, ?_⟩ + simpa only [Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul] using hw.par hv + +theorem of_dnet (hu : 3 ≤ u) (h : DNet F a b f m) : DWide F u L a b f (4 * m) := by + obtain ⟨s, hs, hw⟩ := h + obtain ⟨v, hv, hv'⟩ := hw.includeWide (L := L) hu + exact ⟨v, hv.trans (Nat.mul_le_mul_left _ hs), hv'⟩ + +theorem many (h : DWide F u L a b f m) (t : ℕ) : + DWide F u L (copies a t) (copies b t) (mapCopies f t) (t * m) := by + induction t with + | zero => exact ⟨0, Nat.zero_le _, Wide.empty⟩ + | succ t ih => rw [Nat.succ_mul, Nat.add_comm (t * m)]; exact h.par ih + +/-- Uses `⟨DWide F u L, pre, post, comp, mono⟩` as the representation. -/ +def columnModel (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) : Columns.Model := + ⟨DWide F u L, pre, post, comp, mono⟩ + +end DWide +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- +# Padding ordered bundles of parallel wires + +Collect the bits between each ordered pair of stations, then extend +their binary word by zeros. Empty bundles remain empty. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +open Finset Sphere.Layout + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +open scoped Classical in +/-- Counts the elements of `{e // G.source e = v ∧ G.target e = w}`. -/ +def width (v w : G.V) : ℕ := Fintype.card {e // G.source e = v ∧ G.target e = w} + +open scoped Classical in +/-- The quantity computed by `n + if R ∣ n then 0 else R - n % R`. -/ +def padWidth (R n : ℕ) : ℕ := n + if R ∣ n then 0 else R - n % R + +open scoped Classical in +@[simp] theorem padWidth_zero (R : ℕ) : padWidth R 0 = 0 := by simp [padWidth] + +open scoped Classical in +theorem le_padWidth (R n : ℕ) : n ≤ padWidth R n := Nat.le_add_right _ _ + +open scoped Classical in +theorem padWidth_le (R n : ℕ) : padWidth R n ≤ n + R := by + unfold padWidth + split_ifs <;> omega + +open scoped Classical in +theorem dvd_padWidth {R : ℕ} (hR : 0 < R) (n : ℕ) : R ∣ padWidth R n := by + unfold padWidth + split_ifs with hd + · simpa using hd + · refine ⟨n / R + 1, ?_⟩ + rw [mul_add, mul_one] + have := Nat.mod_add_div n R + have := Nat.mod_lt n hR + omega + +open scoped Classical in +/-- The subtype of `e` satisfying `G.source e = p.1 ∧ G.target e = p.2`. -/ +abbrev EdgeBundle (p : G.V × G.V) := {e // G.source e = p.1 ∧ G.target e = p.2} + +open scoped Classical in +/-- Returns `z ((Fintype.equivFin (G.EdgeBundle p)).symm ⟨i.val, hi⟩)` when `hi : i.val < +G.width p.1 p.2` holds, and `false inj' x y he := by funext e` otherwise. -/ +def padCode (R : ℕ) (p : G.V × G.V) : + (G.EdgeBundle p → Bool) ↪ (Fin (padWidth R (G.width p.1 p.2)) → Bool) where + toFun z i := if hi : i.val < G.width p.1 p.2 then + z ((Fintype.equivFin (G.EdgeBundle p)).symm ⟨i.val, hi⟩) else false + inj' x y he := by + funext e + let i := Fintype.equivFin (G.EdgeBundle p) e + have hi : i.val < G.width p.1 p.2 := i.isLt + have h := congrFun he ⟨i.val, hi.trans_le (le_padWidth R _)⟩ + simp only [dite_eq_left hi] at h + change x ((Fintype.equivFin _).symm i) = y ((Fintype.equivFin _).symm i) at h + simpa only [i, Equiv.symm_apply_apply] using h + +open scoped Classical in +/-- Identifies bits indexed by endpoint pairs and their edge bundles with bits indexed by all +edges. -/ +def bundleBits : (∀ p, G.EdgeBundle p → Bool) ≃ (G.E → Bool) where + toFun z e := z (G.source e, G.target e) ⟨e, rfl, rfl⟩ + invFun z _ e := z e.val + left_inv z := by + funext p e + rcases p with ⟨v, w⟩ + rcases e with ⟨e, hv, hw⟩ + cases hv + cases hw + rfl + right_inv _ := rfl + +open scoped Classical in +/-- Indexes the padded by the coordinates of `G.V E := G.V × G.V state p := G.EdgeBundle p → +Bool width p := padWidth R (G.width p.1 p.2) code := G.padCode R`. -/ +abbrev padded (R : ℕ) : Bundled F a b where + V := G.V + E := G.V × G.V + state p := G.EdgeBundle p → Bool + width p := padWidth R (G.width p.1 p.2) + code := G.padCode R + src := Prod.fst + dst := Prod.snd + left i := (G.src.symm (.inl i)).1 + right i := (G.dst.symm (.inl i)).1 + station v x y z := G.vertex x y (G.bundleBits z) v + locality v x y z x' y' z' hx hy hz := by + apply G.local_weight + · rintro (i | e) hi + · exact hx i hi + · exact congrFun (hz (G.source e, G.target e) (.inl hi)) ⟨e, rfl, rfl⟩ + · rintro (i | e) hi + · exact hy i hi + · exact congrFun (hz (G.source e, G.target e) (.inr hi)) ⟨e, rfl, rfl⟩ + +variable [Field F] + +open scoped Classical in +/-- The value specified by `(G.padded R).diagram`. -/ +abbrev pad (R : ℕ) : Diagram F a b := (G.padded R).diagram + +open scoped Classical in +theorem eval_pad (R : ℕ) : (G.pad R).eval = G.eval := by + refine (G.padded R).eval_diagram.trans ?_ + let : DecidableEq (G.V × G.V) := Classical.typeDecidableEq _ + funext x y + unfold Bundled.eval eval + apply Fintype.sum_equiv G.bundleBits + exact fun _ => rfl + +open scoped Classical in +theorem width_pad (R : ℕ) (v w : G.V) : + (G.pad R).width v w = padWidth R (G.width v w) := by + trans ∑ p : G.V × G.V, if p.1 = v ∧ p.2 = w then padWidth R (G.width p.1 p.2) else 0 + · exact (G.padded R).card_bits (fun p => p.1 = v ∧ p.2 = w) + · rw [Fintype.sum_prod_type] + simp [ite_and] + +open scoped Classical in +theorem divisible_pad {R : ℕ} (hR : 0 < R) (v w : G.V) : R ∣ (G.pad R).width v w := by + rw [width_pad] + exact dvd_padWidth hR _ + +open scoped Classical in +theorem contact_pad (R : ℕ) (e : (G.pad R).E) : + ∃ t : G.E, G.source t = (G.pad R).source e ∧ G.target t = (G.pad R).target e := by + have hp : 0 < G.width e.1.1 e.1.2 := by + have he : 0 < padWidth R (G.width e.1.1 e.1.2) := Nat.zero_lt_of_lt e.2.isLt + by_contra! hn + rw [Nat.eq_zero_of_le_zero hn, padWidth_zero] at he + exact he.false + obtain ⟨t⟩ := Fintype.card_pos_iff.mp hp + exact ⟨t.val, t.property⟩ + +open scoped Classical in +private def outerArity (v : G.V) := + Fintype.card {i // (G.src.symm (.inl i)).1 = v} + + Fintype.card {i // (G.dst.symm (.inl i)).1 = v} + +omit [Field F] in +open scoped Classical in +private theorem arity_width (v : G.V) : + G.arity v = G.outerArity v + ∑ w, (G.width v w + G.width w v) := by + have row : (∑ w, G.width v w) = ∑ e, if G.source e = v then 1 else 0 := by + simp only [width, Fintype.card_subtype, card_filter] + rw [sum_comm] + simp [and_comm (a := G.source _ = v), ite_and] + have col : (∑ w, G.width w v) = ∑ e, if G.target e = v then 1 else 0 := by + simp only [width, Fintype.card_subtype, card_filter] + rw [sum_comm] + simp [ite_and] + rw [sum_add_distrib, row, col, ← G.degree, Fintype.card_subtype, card_filter, + Fintype.sum_sum_type] + simp only [outerArity, Fintype.card_subtype, card_filter, Fintype.sum_sum_type, station, + Sum.elim_inl, Sum.elim_inr, source, target] + ac_rfl + +open scoped Classical in +private theorem arity_pad_eq (R : ℕ) (v : G.V) : + (G.pad R).arity v = G.outerArity v + + ∑ w, (padWidth R (G.width v w) + padWidth R (G.width w v)) := by + rw [arity_width] + congr 1 + apply sum_congr rfl + intro w _ + rw [width_pad, width_pad] + +open scoped Classical in +theorem arity_le_pad (R : ℕ) (v : G.V) : G.arity v ≤ (G.pad R).arity v := by + rw [arity_pad_eq, arity_width] + exact Nat.add_le_add_left (sum_le_sum fun w _ => + Nat.add_le_add (le_padWidth R (G.width v w)) (le_padWidth R (G.width w v))) _ + +open scoped Classical in +theorem arity_pad (R : ℕ) (v : G.V) : + (G.pad R).arity v ≤ G.arity v + 2 * R * Fintype.card {w // 0 < G.width v w ∨ 0 < G.width w v} + := by + rw [arity_pad_eq, arity_width, Fintype.card_subtype, card_filter, mul_sum, add_assoc, + ← sum_add_distrib] + apply Nat.add_le_add_left + apply sum_le_sum + intro w _ + split_ifs with hw + · have := padWidth_le R (G.width v w) + have := padWidth_le R (G.width w v) + omega + · have h₁ : G.width v w = 0 := by omega + have h₂ : G.width w v = 0 := by omega + simp [h₁, h₂] + +open scoped Classical in +theorem arity_pad_le_twice (R : ℕ) (h : ∀ v w, 0 < G.width v w → R ≤ G.width v w) (v : G.V) : + (G.pad R).arity v ≤ 2 * G.arity v := by + have hw (v w : G.V) : padWidth R (G.width v w) ≤ 2 * G.width v w := by + by_cases hz : G.width v w = 0 + · simp [hz] + · have := h v w (Nat.pos_of_ne_zero hz) + have := padWidth_le R (G.width v w) + omega + rw [arity_pad_eq, arity_width, mul_add, mul_sum] + apply Nat.add_le_add (by omega) + exact sum_le_sum fun w _ => by rw [mul_add]; exact Nat.add_le_add (hw v w) (hw w v) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Permute.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Permute.lean new file mode 100644 index 0000000000..a2b5d7cec2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Permute.lean @@ -0,0 +1,200 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FunctionNetwork + +/-! +# Reindexing individual wire positions + +An arbitrary bijection of the exterior positions is a structural rewiring. +We pull out the requested bits one at a time, keeping track of the positions +of all remaining bits. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- In the case `.bit`, this construction gives `Unit`. -/ +abbrev slots : Wire → Type + | .bit => Unit + | .unit => Empty + | .pair a b => slots a ⊕ slots b + +instance slotsFintype : (a : Wire) → Fintype (slots a) + | .bit => inferInstanceAs (Fintype Unit) + | .unit => inferInstanceAs (Fintype Empty) + | .pair a b => + letI := slotsFintype a + letI := slotsFintype b + inferInstanceAs (Fintype (slots a ⊕ slots b)) + +instance slotsDecidableEq : (a : Wire) → DecidableEq (slots a) + | .bit => inferInstanceAs (DecidableEq Unit) + | .unit => inferInstanceAs (DecidableEq Empty) + | .pair a b => + letI := slotsDecidableEq a + letI := slotsDecidableEq b + inferInstanceAs (DecidableEq (slots a ⊕ slots b)) + +@[simp] theorem card_slots (a : Wire) : Fintype.card (slots a) = wd a := by + induction a with + | bit => rfl + | unit => rfl + | pair a b ha hb => simpa [slots, wd] using congrArg₂ (· + ·) ha hb + +/-- The bits used in the `MatrixExponent` construction. -/ +def bits : (a : Wire) → Val a ≃ (slots a → Bool) + | .bit => ⟨fun x _ => x, fun f => f (), fun _ => rfl, fun _ => rfl⟩ + | .unit => ⟨fun _ => Empty.elim, fun _ => (), fun _ => rfl, fun _ => funext fun i => i.elim⟩ + | .pair a b => ((bits a).prodCongr (bits b)).trans + (Equiv.sumPiEquivProdPi (fun _ : slots a ⊕ slots b => Bool)).symm + +variable {a b : Wire} + +/-- The indexed operation `(bits b).symm (fun i => bits a x (e i))`. -/ +def reindex (e : slots b ≃ slots a) (x : Val a) : Val b := + (bits b).symm (fun i => bits a x (e i)) + +@[simp] theorem bits_reindex (e : slots b ≃ slots a) (x : Val a) (i : slots b) : + bits b (reindex e x) i = bits a x (e i) := + congrFun ((bits b).apply_symm_apply _) i + +private theorem pluck (a : Wire) (i : slots a) : + ∃ (b : Wire) (e : Unit ⊕ slots b ≃ slots a) (f : Val a → Val (.pair .bit b)), + Rewire a (.pair .bit b) f ∧ e (.inl ()) = i ∧ + ∀ x j, bits (.pair .bit b) (f x) j = bits a x (e j) := by + induction a with + | bit => + refine ⟨.unit, Equiv.sumEmpty Unit Empty, _, .unit' _, rfl, ?_⟩ + intro x j + cases j with + | inl => rfl + | inr k => exact k.elim + | unit => exact i.elim + | pair a b ha hb => + cases i with + | inl i => + obtain ⟨c, e, f, hf, hi, he⟩ := ha i + refine ⟨.pair c b, (Equiv.sumAssoc _ _ _).symm.trans (e.sumCongr (.refl _)), + _, (hf.par (.id b)).comp (.assoc _ _ _), congrArg Sum.inl hi, ?_⟩ + rintro x (j | j | j) + · exact he x.1 (.inl j) + · exact he x.1 (.inr j) + · rfl + | inr i => + obtain ⟨c, e, f, hf, hi, he⟩ := hb i + refine ⟨.pair c a, ((Equiv.sumAssoc _ _ _).symm.trans (e.sumCongr (.refl _))).trans + (Equiv.sumComm _ _), _, (Rewire.swap a b).comp ((hf.par (.id a)).comp (.assoc _ _ _)), + congrArg Sum.inr hi, ?_⟩ + rintro x (j | j | j) + · exact he x.2 (.inl j) + · exact he x.2 (.inr j) + · rfl + +private theorem matchRest {α β γ : Type} (e : Unit ⊕ α ≃ γ) (d : Unit ⊕ β ≃ γ) + (h : d (.inl ()) = e (.inl ())) : + ∃ q : α ≃ β, ∀ i, d (.inr (q i)) = e (.inr i) := by + have ex (i : α) : ∃ j : β, d (.inr j) = e (.inr i) := by + obtain ⟨_ | j, hj⟩ := d.surjective (e (.inr i)) + · cases e.injective (h.symm.trans hj) + · exact ⟨j, hj⟩ + choose q hq using ex + have bij : Function.Bijective q := by + constructor + · intro i j hij + apply Sum.inr.inj + apply e.injective + rw [← hq, ← hq, hij] + · intro j + obtain ⟨_ | i, hi⟩ := e.surjective (d (.inr j)) + · cases d.injective (h.trans hi) + · exact ⟨i, Sum.inr.inj (d.injective ((hq i).trans hi))⟩ + exact ⟨Equiv.ofBijective q bij, hq⟩ + +/-- Extract the requested bundle, retaining the remaining positions indexed by `α`. -/ +private theorem extract (b : Wire) {a : Wire} {α : Type} (e : slots b ⊕ α ≃ slots a) : + ∃ (c : Wire) (q : α ≃ slots c) (f : Val a → Val (.pair b c)), + Rewire a (.pair b c) f ∧ + (∀ x i, bits b (f x).1 i = bits a x (e (.inl i))) ∧ + (∀ x i, bits c (f x).2 (q i) = bits a x (e (.inr i))) := by + induction b generalizing a α with + | unit => + exact ⟨a, (Equiv.emptySum Empty α).symm.trans e, _, (Rewire.unit' a).comp (.swap _ _), + fun _ i => i.elim, fun _ _ => rfl⟩ + | bit => + obtain ⟨c, d, f, hf, hi, hd⟩ := pluck a (e (.inl ())) + obtain ⟨q, hq⟩ := matchRest e d hi + exact ⟨c, q, f, hf, fun x i => (hd x (.inl i)).trans (congrArg (bits a x) hi), + fun x i => (hd x (.inr (q i))).trans (congrArg (bits a x) (hq i))⟩ + | pair b c hb hc => + obtain ⟨d, p, f, hf, hf₁, hf₂⟩ := hb ((Equiv.sumAssoc _ _ _).symm.trans e) + obtain ⟨g, q, k, hk, hk₁, hk₂⟩ := hc p + refine ⟨g, q, _, (hf.comp ((Rewire.id b).par hk)).comp (.assoc' _ _ _), ?_, ?_⟩ + · rintro x (i | i) + · exact hf₁ x i + · exact (hk₁ (f x).2 i).trans (hf₂ x (.inl i)) + · exact fun x i => (hk₂ (f x).2 i).trans (hf₂ x (.inr i)) + +private theorem empty_rewire (a : Wire) (h : slots a → Empty) : + Rewire a .unit (fun _ => ()) := by + induction a with + | bit => exact (h ()).elim + | unit => exact .id _ + | pair a b ha hb => exact ((ha (h ∘ Sum.inl)).par (hb (h ∘ Sum.inr))).comp (.unit _) + +theorem rewire_reindex (e : slots b ≃ slots a) : Rewire a b (reindex e) := by + obtain ⟨c, q, f, hf, hi, _⟩ := extract b ((Equiv.sumEmpty _ Empty).trans e) + have he : reindex e = fun x => (f x).1 := by + funext x + apply (bits b).injective + funext i + rw [bits_reindex] + exact (hi x i).symm + rw [he] + exact (hf.comp ((Rewire.id b).par (empty_rewire c q.symm))).comp (.unit b) + +theorem Rewire.exists_of_width (h : wd a = wd b) : + ∃ f, Rewire a b f ∧ Function.Injective f := by + let e : slots b ≃ slots a := Fintype.equivOfCardEq (by simp [h]) + refine ⟨reindex e, rewire_reindex e, ?_⟩ + intro x y hxy + apply (bits a).injective + funext i + simpa using congrArg (fun z => bits b z (e.symm i)) hxy + +theorem Rewire.reindex_exists {f : Val a → Val b} (h : Rewire a b f) : + ∃ e : slots b ≃ slots a, f = reindex e := by + suffices ∃ e : slots b ≃ slots a, ∀ x i, bits b (f x) i = bits a x (e i) by + obtain ⟨e, he⟩ := this + refine ⟨e, funext fun x => (bits b).injective (funext fun i => ?_)⟩ + rw [bits_reindex, he] + induction h with + | id a => exact ⟨.refl _, fun _ _ => rfl⟩ + | swap a b => exact ⟨Equiv.sumComm _ _, by rintro x (i | i) <;> rfl⟩ + | assoc a b c => exact ⟨(Equiv.sumAssoc _ _ _).symm, by rintro x (i | i | i) <;> rfl⟩ + | assoc' a b c => exact ⟨Equiv.sumAssoc _ _ _, by rintro x ((i | i) | i) <;> rfl⟩ + | unit a => exact ⟨(Equiv.sumEmpty _ Empty).symm, fun _ _ => rfl⟩ + | unit' a => + refine ⟨Equiv.sumEmpty _ Empty, ?_⟩ + rintro x (i | i) + · rfl + · exact i.elim + | comp _ _ ih ik => + obtain ⟨e, he⟩ := ih + obtain ⟨d, hd⟩ := ik + exact ⟨d.trans e, fun x i => (hd _ i).trans (he x (d i))⟩ + | par _ _ ih ik => + obtain ⟨e, he⟩ := ih + obtain ⟨d, hd⟩ := ik + refine ⟨e.sumCongr d, ?_⟩ + rintro x (i | i) + · exact he x.1 i + · exact hd x.2 i + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Present.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Present.lean new file mode 100644 index 0000000000..d122dcc2c0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Present.lean @@ -0,0 +1,432 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange + +/-! +# Realizing a directed multigraph by structural network operations + +Juxtapose the tables, keeping track of where each argument slot went. +Reorder the slots to expose the exterior bits and a copy of the internal +edge bundle on each side. One trace now sums over all edge assignments. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {V : Type} (T : V → Wire) + +/-- A bundle containing exactly the argument positions indexed by `s`. -/ +private structure Bundle (s : Finset V) where + wire : Wire + slot : slots wire → Σ v, slots (T v) + inj : Function.Injective slot + image : ∀ i, (∃ j, slot j = i) ↔ i.1 ∈ s + +namespace Bundle + +private def empty : Bundle T ∅ where + wire := .unit + slot := Empty.elim + inj i := i.elim + image i := by simp + +variable {T} {s : Finset V} + +private def cons [DecidableEq V] (v : V) (hv : v ∉ s) (b : Bundle T s) : + Bundle T (insert v s) where + wire := .pair (T v) b.wire + slot := Sum.elim (fun i => ⟨v, i⟩) b.slot + inj := by + have h (i) : (b.slot i).1 ≠ v := fun e => hv (e ▸ (b.image _).mp ⟨i, rfl⟩) + rintro (i | i) (j | j) he + · cases he; rfl + · exact (h j (congrArg Sigma.fst he.symm)).elim + · exact (h i (congrArg Sigma.fst he)).elim + · exact congrArg Sum.inr (b.inj he) + image := by + rintro ⟨w, i⟩ + rw [Finset.mem_insert, ← b.image] + constructor + · rintro ⟨j | j, he⟩ + · exact .inl (congrArg Sigma.fst he.symm) + · exact .inr ⟨j, he⟩ + · rintro (rfl | ⟨j, he⟩) + · exact ⟨.inl i, rfl⟩ + · exact ⟨.inr j, he⟩ + +private def read (b : Bundle T s) (x : (Σ v, slots (T v)) → Bool) : Val b.wire := + (bits b.wire).symm (x ∘ b.slot) + +private noncomputable def equiv [Fintype V] (b : Bundle T Finset.univ) : + slots b.wire ≃ Σ v, slots (T v) := + Equiv.ofBijective b.slot ⟨b.inj, fun i => (b.image i).mpr (Finset.mem_univ _)⟩ + +end Bundle + +variable {F : Type} [Field F] {a b : Wire} + +theorem realize + (N : (a b : Wire) → (Val a → Val b → F) → ℕ → Prop) + (empty : N .unit .unit (fun _ _ => 1) 0) + (par : ∀ {a b c d k l m n}, N a b k m → N c d l n → + N (.pair a c) (.pair b d) (fun x y => k x.1 y.1 * l x.2 y.2) (m + n)) + (pre : ∀ {a b c f k m}, N b c k m → Rewire a b f → N a c (fun x y => k (f x) y) m) + (post : ∀ {a b c f k m}, N a b k m → Rewire c b f → N a c (fun x y => k x (f y)) m) + (trace : ∀ {a b c k m}, N (.pair a c) (.pair b c) k m → + N a b (fun x y => ∑ z : Val c, k (x, z) (y, z)) m) + (G : Diagram F a b) (m : G.V → ℕ) + (ht : ∀ v, N (G.table v).1 (G.table v).2.1 (G.table v).2.2 (m v)) : + N a b G.eval (∑ v, m v) := by + classical + let A v := (G.table v).1 + let B v := (G.table v).2.1 + have collect (s : Finset G.V) : + ∃ (u : Bundle A s) (v : Bundle B s) (k : Val u.wire → Val v.wire → F), + N u.wire v.wire k (∑ i ∈ s, m i) ∧ + ∀ x y z, k (u.read (Sum.elim (bits a x) z ∘ G.src)) + (v.read (Sum.elim (bits b y) z ∘ G.dst)) = ∏ i ∈ s, G.vertex x y z i := by + induction s using Finset.induction_on with + | empty => exact ⟨.empty A, .empty B, _, empty, by simp⟩ + | @insert i s hi ih => + obtain ⟨u, v, k, hk, he⟩ := ih + rw [Finset.sum_insert hi] + refine ⟨u.cons i hi, v.cons i hi, _, par (ht i) hk, ?_⟩ + intro x y z + rw [Finset.prod_insert hi, ← he] + rfl + obtain ⟨u, v, k, hk, he⟩ := collect Finset.univ + obtain ⟨c, hc⟩ : ∃ c, wd c = Fintype.card G.E := ⟨_, wd_word _⟩ + let e : G.E ≃ slots c := Fintype.equivOfCardEq ((card_slots c).trans hc).symm + let h := (bits c).trans (e.symm.arrowCongr (Equiv.refl Bool)) + let index {T : G.V → Wire} {d : Wire} (w : Bundle T Finset.univ) + (t : (Σ v, slots (T v)) ≃ slots d ⊕ G.E) : slots w.wire ≃ slots (.pair d c) := + (w.equiv.trans t).trans ((Equiv.refl _).sumCongr e) + have read {T : G.V → Wire} {d : Wire} (w : Bundle T Finset.univ) + (t : (Σ v, slots (T v)) ≃ slots d ⊕ G.E) (x : Val d) (z : Val c) : + reindex (index w t) (x, z) = w.read (Sum.elim (bits d x) (h z) ∘ t) := by + unfold reindex Bundle.read + congr 1 + funext i + change Sum.elim (bits d x) (bits c z) ((Sum.map id e) (t (w.slot i))) = + Sum.elim (bits d x) (h z) (t (w.slot i)) + cases t (w.slot i) <;> rfl + have eqn : G.eval = fun x y => ∑ z : Val c, + k (reindex (index u G.src) (x, z)) (reindex (index v G.dst) (y, z)) := by + funext x y + simp_rw [read, he] + exact (Equiv.sum_comp h _).symm + rw [eqn] + exact trace (post (pre hk (rewire_reindex (index u G.src))) (rewire_reindex (index v G.dst))) + +theorem net (G : Diagram F a b) (h : G.Trivalent) : + Net F a b G.eval (Fintype.card G.V) := by + simpa using realize (Net F) Net.empty Net.par Net.pre Net.post Net.trace G + (fun _ => 1) (fun i => Net.table _ _ _ (h i)) + +theorem wide (G : Diagram F a b) {u : ℕ} {L : Set (Table F)} (h : G.Admits u L) : + Wide F u L a b G.eval G.cost := + realize (Wide F u L) Wide.empty Wide.par Wide.pre Wide.post Wide.trace G + (fun i => 1 + G.arity i) (fun i => Wide.table _ _ _ (h i).1 (h i).2) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- # Disjoint unions of networks -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b c d : Wire} (G : Diagram F a b) (H : Diagram F c d) + +/-- Builds `Diagram F (.pair a c) (.pair b d) where V` with the specified `table`, `src`, `dst`. -/ +abbrev par : Diagram F (.pair a c) (.pair b d) where + V := G.V ⊕ H.V + E := G.E ⊕ H.E + table := Sum.elim G.table H.table + src := (Equiv.sumSigmaDistrib _).trans ((G.src.sumCongr H.src).trans (Equiv.sumSumSumComm _ _ _ + _)) + dst := (Equiv.sumSigmaDistrib _).trans ((G.dst.sumCongr H.dst).trans (Equiv.sumSumSumComm _ _ _ + _)) + +theorem cost_par : (G.par H).cost = G.cost + H.cost := + Fintype.sum_sum_type _ + +theorem card_par : Fintype.card (G.par H).V = Fintype.card G.V + Fintype.card H.V := + Fintype.card_sum + +theorem admits_par {u : ℕ} {L : Set (Table F)} (hg : G.Admits u L) (hh : H.Admits u L) : + (G.par H).Admits u L := by + rintro (i | i) + · exact hg i + · exact hh i + +theorem trivalent_par (hg : G.Trivalent) (hh : H.Trivalent) : (G.par H).Trivalent := by + rintro (i | i) + · exact hg i + · exact hh i + +private theorem value_left {A B : Wire} {X Y : Type} (x : Val (.pair A B)) + (s : X → Bool) (t : Y → Bool) (i : slots A ⊕ X) : + Sum.elim (bits (.pair A B) x) (Sum.elim s t) + (Equiv.sumSumSumComm (slots A) X (slots B) Y (.inl i)) = Sum.elim (bits A x.1) s i := by + cases i <;> rfl + +private theorem value_right {A B : Wire} {X Y : Type} (x : Val (.pair A B)) + (s : X → Bool) (t : Y → Bool) (i : slots B ⊕ Y) : + Sum.elim (bits (.pair A B) x) (Sum.elim s t) + (Equiv.sumSumSumComm (slots A) X (slots B) Y (.inr i)) = Sum.elim (bits B x.2) t i := by + cases i <;> rfl + +theorem vertex_left (x : Val (.pair a c)) (y : Val (.pair b d)) + (s : G.E → Bool) (t : H.E → Bool) (v : G.V) : + (G.par H).vertex x y (Sum.elim s t) (.inl v) = G.vertex x.1 y.1 s v := by + unfold vertex + apply congrArg₂ (G.table v).2.2 + · exact congrArg (bits (G.table v).1).symm (funext fun i => value_left x s t (G.src ⟨v, i⟩)) + · exact congrArg (bits (G.table v).2.1).symm (funext fun i => value_left y s t (G.dst ⟨v, i⟩)) + +theorem vertex_right (x : Val (.pair a c)) (y : Val (.pair b d)) + (s : G.E → Bool) (t : H.E → Bool) (v : H.V) : + (G.par H).vertex x y (Sum.elim s t) (.inr v) = H.vertex x.2 y.2 t v := by + unfold vertex + apply congrArg₂ (H.table v).2.2 + · exact congrArg (bits (H.table v).1).symm (funext fun i => value_right x s t (H.src ⟨v, i⟩)) + · exact congrArg (bits (H.table v).2.1).symm (funext fun i => value_right y s t (H.dst ⟨v, i⟩)) + +theorem eval_par [Field F] (x : Val (.pair a c)) (y : Val (.pair b d)) : + (G.par H).eval x y = G.eval x.1 y.1 * H.eval x.2 y.2 := by + classical + unfold eval + let _ : DecidableEq (G.E ⊕ H.E) := fun _ _ => Classical.propDecidable _ + let e := (Equiv.sumPiEquivProdPi (fun _ : G.E ⊕ H.E => Bool)).symm + rw [← e.sum_comp, Fintype.sum_prod_type, Finset.sum_mul_sum] + apply Finset.sum_congr rfl + intro s _ + apply Finset.sum_congr rfl + intro t _ + change (∏ v, (G.par H).vertex x y (Sum.elim s t) v) = _ + rw [Fintype.prod_sum_type] + exact congrArg₂ (· * ·) + (Finset.prod_congr rfl (fun v _ => vertex_left G H x y s t v)) + (Finset.prod_congr rfl (fun v _ => vertex_right G H x y s t v)) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- # Closing and permuting exterior slots -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b c d : Wire} + +/-- Indexes the close by the coordinates of `G.V E := slots c ⊕ G.E table := G.table src := +G.src.trans (Equiv.sumAssoc _ _ _) dst := G.dst.trans (Equiv.sumAssoc _ _ _)`. -/ +abbrev close (G : Diagram F (.pair a c) (.pair b c)) : Diagram F a b where + V := G.V + E := slots c ⊕ G.E + table := G.table + src := G.src.trans (Equiv.sumAssoc _ _ _) + dst := G.dst.trans (Equiv.sumAssoc _ _ _) + +private theorem value_close {E : Type} (x : Val a) (z : Val c) + (s : E → Bool) (i : (slots a ⊕ slots c) ⊕ E) : + Sum.elim (bits a x) (Sum.elim (bits c z) s) (Equiv.sumAssoc _ _ _ i) = + Sum.elim (bits (.pair a c) (x, z)) s i := by + rcases i with (i | i) | i <;> rfl + +theorem vertex_close (G : Diagram F (.pair a c) (.pair b c)) + (x : Val a) (y : Val b) (z : Val c) (s : G.E → Bool) (v : G.V) : + G.close.vertex x y (Sum.elim (bits c z) s) v = G.vertex (x, z) (y, z) s v := by + unfold vertex + apply congrArg₂ (G.table v).2.2 + · exact congrArg (bits (G.table v).1).symm (funext fun i => value_close x z s (G.src ⟨v, i⟩)) + · exact congrArg (bits (G.table v).2.1).symm (funext fun i => value_close y z s (G.dst ⟨v, i⟩)) + +theorem eval_close [Field F] (G : Diagram F (.pair a c) (.pair b c)) (x : Val a) (y : Val b) : + G.close.eval x y = ∑ z : Val c, G.eval (x, z) (y, z) := by + classical + unfold eval + let _ : DecidableEq (slots c ⊕ G.E) := fun _ _ => Classical.propDecidable _ + let e := ((bits c).prodCongr (Equiv.refl (G.E → Bool))).trans + (Equiv.sumPiEquivProdPi (fun _ : slots c ⊕ G.E => Bool)).symm + rw [← e.sum_comp, Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro z _ + apply Finset.sum_congr rfl + intro s _ + exact Finset.prod_congr rfl (fun v _ => vertex_close G x y z s v) + +/-- Builds `Diagram F c d where V` with the specified `Diagram`, `table`, `src`, `dst`. -/ +abbrev rename (G : Diagram F a b) (f : slots a ≃ slots c) (g : slots b ≃ slots d) : + Diagram F c d where + V := G.V + E := G.E + table := G.table + src := G.src.trans (f.sumCongr (.refl _)) + dst := G.dst.trans (g.sumCongr (.refl _)) + +private theorem value_rename {E : Type} (f : slots a ≃ slots c) (x : Val c) + (s : E → Bool) (i : slots a ⊕ E) : + Sum.elim (bits c x) s ((f.sumCongr (.refl _)) i) = Sum.elim (bits a (reindex f x)) s i := by + rcases i with i | i + · exact (bits_reindex f x i).symm + · rfl + +theorem eval_rename [Field F] (G : Diagram F a b) (f : slots a ≃ slots c) (g : slots b ≃ slots d) + (x : Val c) (y : Val d) : (G.rename f g).eval x y = G.eval (reindex f x) (reindex g y) := by + classical + unfold eval + apply Finset.sum_congr rfl + intro s _ + apply Finset.prod_congr rfl + intro v _ + unfold vertex + apply congrArg₂ (G.table v).2.2 + · exact congrArg (bits (G.table v).1).symm (funext fun i => value_rename f x s (G.src ⟨v, i⟩)) + · exact congrArg (bits (G.table v).2.1).symm (funext fun i => value_rename g y s (G.dst ⟨v, i⟩)) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- # Networks with zero or one station -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b : Wire} + +/-- Builds `Diagram F .unit .unit where V` with the specified `table`, `src`, `fun`. -/ +abbrev empty (F : Type) : Diagram F .unit .unit where + V := Empty + E := Empty + table := Empty.elim + src := ⟨fun i => i.1.elim, Sum.elim Empty.elim Empty.elim, + fun i => i.1.elim, fun i => (Sum.elim id id i).elim⟩ + dst := ⟨fun i => i.1.elim, Sum.elim Empty.elim Empty.elim, + fun i => i.1.elim, fun i => (Sum.elim id id i).elim⟩ + +theorem eval_empty [Field F] (x y : Val .unit) : (empty F).eval x y = 1 := by + simp [eval] + +/-- Identify a single vertex's ports with the boundary ports and no internal wires. -/ +def singlePort (X : Type) : (Σ _ : Unit, X) ≃ X ⊕ Empty := + ⟨fun i => .inl i.2, Sum.elim (fun i => ⟨(), i⟩) Empty.elim, + fun _ => rfl, by + rintro (i | i) + · rfl + · exact i.elim⟩ + +/-- Builds `Diagram F a b where V` with the specified `table`, `src`, `dst`. -/ +abbrev single (k : Val a → Val b → F) : Diagram F a b where + V := Unit + E := Empty + table _ := ⟨a, b, k⟩ + src := singlePort _ + dst := singlePort _ + +theorem eval_single [Field F] (k : Val a → Val b → F) (x : Val a) (y : Val b) : + (single k).eval x y = k x y := by + unfold eval + rw [Fintype.sum_unique, Fintype.prod_unique] + change k ((bits a).symm (bits a x)) ((bits b).symm (bits b y)) = _ + rw [Equiv.symm_apply_apply, Equiv.symm_apply_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- # From compositional networks to indexed wiring diagrams -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {F : Type} [Field F] {a b c d : Wire} {m n : ℕ} + +private def Presents (P : Table F → Prop) (price : Table F → ℕ) + (a b : Wire) (k : Val a → Val b → F) (m : ℕ) : Prop := + ∃ G : Diagram F a b, G.eval = k ∧ (∀ v, P (G.table v)) ∧ ∑ v, price (G.table v) = m + +namespace Presents + +variable {P : Table F → Prop} {price : Table F → ℕ} {k : Val a → Val b → F} + +private theorem empty : Presents P price .unit .unit (fun _ _ => 1) 0 := + ⟨.empty F, funext fun x => funext (Diagram.eval_empty x), fun v => v.elim, by simp⟩ + +private theorem table (h : P ⟨a, b, k⟩) : Presents P price a b k (price ⟨a, b, k⟩) := + ⟨.single k, funext fun x => funext (Diagram.eval_single k x), fun _ => h, Fintype.sum_unique _⟩ + +private theorem par {l : Val c → Val d → F} + (h : Presents P price a b k m) (g : Presents P price c d l n) : + Presents P price (.pair a c) (.pair b d) (fun x y => k x.1 y.1 * l x.2 y.2) (m + n) := by + obtain ⟨G, rfl, hk, rfl⟩ := h + obtain ⟨H, rfl, hl, rfl⟩ := g + refine ⟨G.par H, funext fun x => funext (Diagram.eval_par G H x), ?_, Fintype.sum_sum_type _⟩ + rintro (v | v) + · exact hk v + · exact hl v + +private theorem trace {l : Val (.pair a c) → Val (.pair b c) → F} + (h : Presents P price (.pair a c) (.pair b c) l m) : + Presents P price a b (fun x y => ∑ z : Val c, l (x, z) (y, z)) m := by + obtain ⟨G, rfl, hp, hm⟩ := h + exact ⟨G.close, funext fun x => funext (G.eval_close x), hp, hm⟩ + +private theorem rename {f : Val c → Val a} {g : Val d → Val b} + (h : Presents P price a b k m) (hf : Rewire c a f) (hg : Rewire d b g) : + Presents P price c d (fun x y => k (f x) (g y)) m := by + obtain ⟨G, rfl, hp, hm⟩ := h + obtain ⟨f, rfl⟩ := hf.reindex_exists + obtain ⟨g, rfl⟩ := hg.reindex_exists + exact ⟨G.rename f g, funext fun x => funext (G.eval_rename f g x), hp, hm⟩ + +private theorem comp {l : Val b → Val c → F} + (h : Presents P price a b k m) (g : Presents P price b c l n) : + Presents P price a c (fun x y => ∑ z : Val b, k x z * l z y) (m + n) := + ((h.par g).rename (.id _) (.swap _ _)).trace + +end Presents + +private def arity (A : Table F) := wd A.1 + wd A.2.1 + +variable {k : Val a → Val b → F} + +theorem Net.diagram (h : Net F a b k m) : + ∃ G : Diagram F a b, G.eval = k ∧ G.Trivalent ∧ Fintype.card G.V = m := by + have hp : Presents (fun A => arity A ≤ 3) (fun _ => 1) a b k m := by + induction h with + | empty => exact .empty + | table _ _ _ h => exact .table h + | par _ _ ih ig => exact ih.par ig + | comp _ _ ih ig => exact ih.comp ig + | trace _ ih => exact ih.trace + | pre _ hr ih => exact ih.rename hr (.id _) + | post _ hr ih => exact ih.rename (.id _) hr + obtain ⟨G, hg, ht, hm⟩ := hp + exact ⟨G, hg, ht, by simpa using hm⟩ + +theorem Wide.diagram {u : ℕ} {L : Set (Table F)} (h : Wide F u L a b k m) : + ∃ G : Diagram F a b, G.eval = k ∧ G.Admits u L ∧ G.cost = m := by + change Presents (fun A => arity A ≤ u ∧ (arity A ≤ 3 ∨ A ∈ L)) + (fun A => 1 + arity A) a b k m + induction h with + | empty => exact .empty + | table _ _ _ ht hl => exact .table ⟨ht, hl⟩ + | par _ _ ih ig => exact ih.par ig + | comp _ _ ih ig => exact ih.comp ig + | trace _ ih => exact ih.trace + | pre _ hr ih => exact ih.rename hr (.id _) + | post _ hr ih => exact ih.rename (.id _) hr + +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Replacement.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Replacement.lean new file mode 100644 index 0000000000..1914364c71 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Replacement.lean @@ -0,0 +1,738 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rule + +/-! # Comparing size and volume conventions -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +/-- Each internal edge contributes two argument positions and each +exterior bit contributes one. -/ +theorem sum_arity : ∑ v, G.arity v = wd a + wd b + 2 * Fintype.card G.E := by + have hi := Fintype.card_congr G.src + have ho := Fintype.card_congr G.dst + simp only [Fintype.card_sigma, Fintype.card_sum, card_slots] at hi ho + simp only [arity, Finset.sum_add_distrib] + omega + +theorem cost_eq : G.cost = Fintype.card G.V + wd a + wd b + 2 * Fintype.card G.E := by + simp [cost, Finset.sum_add_distrib, G.sum_arity, add_assoc] + +theorem cost_trivalent (h : G.Trivalent) : G.cost ≤ 4 * Fintype.card G.V := by + calc + _ ≤ ∑ _ : G.V, 4 := Finset.sum_le_sum (fun v _ => Nat.add_le_add_left (h v) 1) + _ = _ := by simp [mul_comm] + +/-- Wire-inclusive volume is at most three times vertices plus exterior bits. -/ +theorem volume_trivalent (h : G.Trivalent) : + Fintype.card G.V + Fintype.card G.E + wd a + wd b ≤ + 3 * (Fintype.card G.V + wd a + wd b) := by + have := G.cost_trivalent h + rw [cost_eq] at this + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- +# A bipartite presentation + +Insert one binary equality table on each internal and external wire. +Each of the original argument positions now has its own edge. All +these edges join an original vertex and a junction. Exterior positions +have distinct equality leaves and even an old loop is subdivided. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +/-- Indexes the joint by the coordinates of `slots a ⊕ slots b ⊕ G.E`. -/ +abbrev Joint := slots a ⊕ slots b ⊕ G.E +/-- Indexes the end by the coordinates of `(slots a ⊕ G.E) ⊕ slots b ⊕ G.E`. -/ +abbrev End := (slots a ⊕ G.E) ⊕ slots b ⊕ G.E + +/-- In the case `.inl (.inl i)`, this construction gives `.inl i`. -/ +def junction : G.End → G.Joint + | .inl (.inl i) => .inl i + | .inl (.inr e) => .inr (.inr e) + | .inr (.inl j) => .inr (.inl j) + | .inr (.inr e) => .inr (.inr e) + +/-- Chooses the operation for the left or right summand. -/ +def station : G.End → G.V := + Sum.elim (fun i => (G.src.symm i).1) (fun j => (G.dst.symm j).1) + +/-- In the case `.inl i`, this construction gives `.inr (.inl i)`. -/ +def srcNorm : (slots a ⊕ G.E) ⊕ G.Joint ≃ slots a ⊕ G.End where + toFun + | .inl i => .inr (.inl i) + | .inr (.inl i) => .inl i + | .inr (.inr j) => .inr (.inr j) + invFun + | .inl i => .inr (.inl i) + | .inr (.inl i) => .inl i + | .inr (.inr j) => .inr (.inr j) + left_inv := by rintro (i | i | j) <;> rfl + right_inv := by rintro (i | i | j) <;> rfl + +/-- In the case `.inl j`, this construction gives `.inr (.inr j)`. -/ +def dstNorm : (slots b ⊕ G.E) ⊕ G.Joint ≃ slots b ⊕ G.End where + toFun + | .inl j => .inr (.inr j) + | .inr (.inl i) => .inr (.inl (.inl i)) + | .inr (.inr (.inl j)) => .inl j + | .inr (.inr (.inr e)) => .inr (.inl (.inr e)) + invFun + | .inl j => .inr (.inr (.inl j)) + | .inr (.inl (.inl i)) => .inr (.inl i) + | .inr (.inl (.inr e)) => .inr (.inr (.inr e)) + | .inr (.inr j) => .inl j + left_inv := by rintro (j | i | j | e) <;> rfl + right_inv := by rintro (j | (i | e) | j) <;> rfl + +/-- Builds `Diagram F a b where V` with the specified `table`, `src`, `dst`. -/ +abbrev normalized [Field F] : Diagram F a b where + V := G.V ⊕ G.Joint + E := G.End + table := Sum.elim G.table (fun _ => ⟨.bit, .bit, fun i j => if i = j then 1 else 0⟩) + src := (Equiv.sumSigmaDistrib _).trans + ((G.src.sumCongr (Equiv.sigmaUnique G.Joint (fun _ => Unit))).trans G.srcNorm) + dst := (Equiv.sumSigmaDistrib _).trans + ((G.dst.sumCongr (Equiv.sigmaUnique G.Joint (fun _ => Unit))).trans G.dstNorm) + +theorem card_end : Fintype.card G.End = wd a + wd b + 2 * Fintype.card G.E := by + simp only [End, Fintype.card_sum, card_slots] + omega + +theorem card_joint : Fintype.card G.Joint = wd a + wd b + Fintype.card G.E := by + simp only [Joint, Fintype.card_sum, card_slots, add_assoc] + +variable [Field F] + +theorem cost_normalized : G.normalized.cost ≤ 4 * G.cost := by + rw [cost_eq, cost_eq, Fintype.card_sum, card_joint, card_end] + omega + +theorem admits_normalized {u : ℕ} {L : Set (Table F)} (hu : 2 ≤ u) (h : G.Admits u L) : + G.normalized.Admits u L := by + rintro (v|v) + · exact h v + · exact ⟨hu, Or.inl (by change 2 ≤ 3; decide)⟩ + +theorem trivalent_normalized (h : G.Trivalent) : G.normalized.Trivalent := by + rintro (v|v) + · exact h v + · change 2 ≤ 3 + decide + +theorem bipartite (e : G.End) : + G.normalized.source e = Sum.inl (G.station e) ∧ + G.normalized.target e = Sum.inr (G.junction e) ∨ + G.normalized.target e = Sum.inl (G.station e) ∧ + G.normalized.source e = Sum.inr (G.junction e) := by + rcases e with (i | e) | (j | e) + · exact .inl ⟨rfl, rfl⟩ + · exact .inl ⟨rfl, rfl⟩ + · exact .inr ⟨rfl, rfl⟩ + · exact .inr ⟨rfl, rfl⟩ + +theorem normalized_loopless (e : G.End) : G.normalized.source e ≠ G.normalized.target e := by + rcases G.bipartite e with ⟨h, g⟩ | ⟨g, h⟩ <;> rw [h, g] <;> simp + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- # The degree of an original station in the subdivided network -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +/-- Indexes the port by the coordinates of `slots (G.table v).1 ⊕ slots (G.table v).2.1`. -/ +abbrev Port (v : G.V) := slots (G.table v).1 ⊕ slots (G.table v).2.1 + +/-- Reindexes `(Σ v, G.Port v)` and `G.End` by an equivalence. -/ +def portEquiv : (Σ v, G.Port v) ≃ G.End := + (Equiv.sigmaSumDistrib _ _).trans (G.src.sumCongr G.dst) + +theorem station_port (p : Σ v, G.Port v) : G.station (G.portEquiv p) = p.1 := by + rcases p with ⟨v, i|j⟩ + · exact congrArg Sigma.fst (G.src.symm_apply_apply ⟨v, i⟩) + · exact congrArg Sigma.fst (G.dst.symm_apply_apply ⟨v, j⟩) + +/-- Reindexes `G.Port v` and `{p : Σ x, G.Port x // p.1 = v} where toFun i` by an equivalence. -/ +def atStation (v : G.V) : G.Port v ≃ {p : Σ x, G.Port x // p.1 = v} where + toFun i := ⟨⟨v, i⟩, rfl⟩ + invFun p := p.2 ▸ p.1.2 + left_inv _ := rfl + right_inv := by rintro ⟨⟨x, i⟩, rfl⟩; rfl + +/-- Reindexes `G.Port v` and `{e : G.End // G.station e = v}` by an equivalence. -/ +def incident (v : G.V) : G.Port v ≃ {e : G.End // G.station e = v} := + (G.atStation v).trans (G.portEquiv.subtypeEquiv (fun p => by rw [station_port])) + +theorem degree [DecidableEq G.V] (v : G.V) : + Fintype.card {e : G.End // G.station e = v} = G.arity v := by + rw [← Fintype.card_congr (G.incident v)] + simp only [Port, Fintype.card_sum, card_slots, arity] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- +# Networks with unoriented local functions + +Use one owner per port rather than specifying a local port order. Evaluating +a station only needs the values on its own ports. Choosing an enumeration +converts such a description into a diagram with the same edges and weights. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {V E I F : Type} [Fintype V] [Fintype E] {a b : Wire} + +open Classical in +/-- The value specified by `word (Fintype.card {i // f i = v})`. -/ +abbrev bundle [Fintype I] (f : I → V) (v : V) := + word (Fintype.card {i // f i = v}) + +open Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def port [Fintype I] (f : I → V) (v : V) : + slots (bundle f v) ≃ {i // f i = v} := + Fintype.equivOfCardEq (by rw [card_slots, wd_word]) + +open Classical in +/-- Reindexes `(Σ v, slots (bundle f v))` and `I` by an equivalence. -/ +def connect [Fintype I] (f : I → V) : (Σ v, slots (bundle f v)) ≃ I := + (Equiv.sigmaCongrRight (port f)).trans (Equiv.sigmaFiberEquiv f) + +open Classical in +/-- Returns `bits (bundle f v) x ((port f v).symm ⟨i, h⟩)` when `h : f i = v` holds, and `false` +otherwise. -/ +def fill [Fintype I] (f : I → V) (v : V) (x : Val (bundle f v)) (i : I) := + if h : f i = v then bits (bundle f v) x ((port f v).symm ⟨i, h⟩) else false + +omit [Fintype V] in +open Classical in +private theorem fill_read [Fintype I] (f : I → V) (v : V) (x : I → Bool) + (i : I) (hi : f i = v) : + fill f v ((bits (bundle f v)).symm (fun j => x (connect f ⟨v, j⟩))) i = x i := by + rw [fill, dite_eq_left hi, Equiv.apply_symm_apply] + change x ((port f v) ((port f v).symm ⟨i, hi⟩)).val = _ + rw [Equiv.apply_symm_apply] + +variable (src : slots a ⊕ E → V) (dst : slots b ⊕ E → V) +variable (k : V → (slots a ⊕ E → Bool) → (slots b ⊕ E → Bool) → F) + +open Classical in +/-- The condition `∀ v x y x' y', (∀ i, src i = v → x i = x' i) → (∀ i, dst i = v → y i = y' i) +→ k v x y = k v x' y'` on the specified data. -/ +def Local : Prop := + ∀ v x y x' y', (∀ i, src i = v → x i = x' i) → (∀ i, dst i = v → y i = y' i) → + k v x y = k v x' y' + +open Classical in +/-- Builds `Diagram F a b where V` with the specified `table`, `src`, `dst`. -/ +abbrev ofLocal : Diagram F a b where + V := V + E := E + table v := ⟨bundle src v, bundle dst v, fun x y => k v (fill src v x) (fill dst v y)⟩ + src := connect src + dst := connect dst + +open Classical in +theorem arity_ofLocal (v : V) : + (ofLocal src dst k).arity v = + Fintype.card {i // src i = v} + Fintype.card {i // dst i = v} := by + simp only [arity, wd_word] + +open Classical in +theorem source_ofLocal (e : E) : (ofLocal src dst k).source e = src (.inr e) := rfl + +open Classical in +theorem target_ofLocal (e : E) : (ofLocal src dst k).target e = dst (.inr e) := rfl + +open Classical in +theorem vertex_ofLocal (hk : Local src dst k) + (x : Val a) (y : Val b) (z : E → Bool) (v : V) : + (ofLocal src dst k).vertex x y z v = + k v (Sum.elim (bits a x) z) (Sum.elim (bits b y) z) := + hk _ _ _ _ _ (fill_read src _ _) (fill_read dst _ _) + +variable (G : Diagram F a b) + +open Classical in +/-- Allow the two ends of an edge to carry different values until contraction. -/ +def weight (v : G.V) (x : slots a ⊕ G.E → Bool) (y : slots b ⊕ G.E → Bool) : F := + (G.table v).2.2 + ((bits (G.table v).1).symm (fun i => x (G.src ⟨v, i⟩))) + ((bits (G.table v).2.1).symm (fun j => y (G.dst ⟨v, j⟩))) + +open Classical in +theorem local_weight : + Local (fun i => (G.src.symm i).1) (fun j => (G.dst.symm j).1) G.weight := by + intro v x y x' y' hx hy + unfold weight + apply congrArg₂ (G.table v).2.2 <;> apply congrArg + · funext i; exact hx _ (by simp) + · funext i; exact hy _ (by simp) + +open Classical in +/-- Local weights are independent of the chosen enumeration of ports. -/ +theorem weight_ofLocal (hk : Local src dst k) (v : V) (x : slots a ⊕ E → Bool) + (y : slots b ⊕ E → Bool) : (ofLocal src dst k).weight v x y = k v x y := + hk _ _ _ _ _ (fill_read src _ _) (fill_read dst _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- +# Contracting clusters + +Split the old edges into the visible edges and a disjoint family of +edges internal to the clusters. Sum the latter inside each new table. +This identity allows loops, empty clusters and scalar vertices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b : Wire} (G : Diagram F a b) (V E : Type) + +open Classical in +/-- The data for the clustering construction, including `owner`, `hidden`, `[finite`, `edges`, +`src_hidden`. -/ +structure Clustering where + /-- The owner assigned to each element of type `G.V → V`. -/ + owner : G.V → V + /-- The private coordinates at each index of type `V → Type`. -/ + hidden : V → Type + [finite : ∀ v, Fintype (hidden v)] + /-- The finite set of connections carried by `Clustering`, with type `E ⊕ (Σ v, hidden v) ≃ + G.E`. -/ + edges : E ⊕ (Σ v, hidden v) ≃ G.E + src_hidden : ∀ v e, owner (G.source (edges (.inr ⟨v, e⟩))) = v + dst_hidden : ∀ v e, owner (G.target (edges (.inr ⟨v, e⟩))) = v + +attribute [instance] Clustering.finite + +namespace Clustering + +variable {G V E} (C : Clustering G V E) + +open Classical in +/-- Transforms the indexed data by `C.owner (G.src.symm (i.map id (fun e => C.edges (.inl +e)))).1`. -/ +def src (i : slots a ⊕ E) : V := + C.owner (G.src.symm (i.map id (fun e => C.edges (.inl e)))).1 + +open Classical in +/-- Transforms the indexed data by `C.owner (G.dst.symm (i.map id (fun e => C.edges (.inl +e)))).1`. -/ +def dst (i : slots b ⊕ E) : V := + C.owner (G.dst.symm (i.map id (fun e => C.edges (.inl e)))).1 + +open Classical in +/-- The condition `∀ v, C.hidden v → Bool` on the specified data. -/ +abbrev Inside := ∀ v, C.hidden v → Bool + +open Classical in +/-- Reindexes `(E → Bool) × C.Inside` and `(G.E → Bool)` by an equivalence. -/ +def assignments : (E → Bool) × C.Inside ≃ (G.E → Bool) := + ((Equiv.refl _).prodCongr (Equiv.piCurry (fun v (_ : C.hidden v) => Bool)).symm).trans + ((Equiv.sumArrowEquivProdArrow _ _ _).symm.trans (C.edges.arrowCongr (Equiv.refl _))) + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def lift {X : Type} (x : X ⊕ E → Bool) (w : C.Inside) : X ⊕ G.E → Bool := + Sum.elim (x ∘ Sum.inl) (C.assignments (x ∘ Sum.inr, w)) + +open Classical in +private theorem lift_local {X : Type} (o : X ⊕ G.E → V) + (ho : ∀ v e, o (.inr (C.edges (.inr ⟨v, e⟩))) = v) + {v : V} {x x' : X ⊕ E → Bool} {w w' : C.Inside} + (hx : ∀ i, o (i.map id (fun e => C.edges (.inl e))) = v → x i = x' i) + (hw : w v = w' v) (i : X ⊕ G.E) (hi : o i = v) : C.lift x w i = C.lift x' w' i := by + rcases i with i|e + · exact hx (.inl i) hi + obtain ⟨j, rfl⟩ := C.edges.surjective e + change Sum.elim (x ∘ Sum.inr) _ (C.edges.symm (C.edges j)) = + Sum.elim (x' ∘ Sum.inr) _ (C.edges.symm (C.edges j)) + rw [Equiv.symm_apply_apply] + rcases j with j|⟨u, t⟩ + · exact hx (.inr j) hi + · rw [ho] at hi + subst u + exact congrFun hw t + +variable [Field F] + +open Classical in +/-- The product of `G.weight t (C.lift x w) (C.lift y w)` indexed by `t : {t // C.owner t = v}`. -/ +def term (v : V) (x : slots a ⊕ E → Bool) (y : slots b ⊕ E → Bool) + (w : C.Inside) : F := + ∏ t : {t // C.owner t = v}, G.weight t (C.lift x w) (C.lift y w) + +open Classical in +private theorem term_local {v : V} {x x' y y'} {w w' : C.Inside} + (hx : ∀ i, C.src i = v → x i = x' i) (hy : ∀ i, C.dst i = v → y i = y' i) + (hw : w v = w' v) : C.term v x y w = C.term v x' y' w' := by + apply Finset.prod_congr rfl + intro t _ + apply G.local_weight + · intro i hi + exact C.lift_local (fun i => C.owner (G.src.symm i).1) C.src_hidden hx hw i + ((congrArg C.owner hi).trans t.property) + · intro i hi + exact C.lift_local (fun i => C.owner (G.dst.symm i).1) C.dst_hidden hy hw i + ((congrArg C.owner hi).trans t.property) + +open Classical in +/-- The sum of `C.term v x y (Function.update (fun _ _ => false) v w)` indexed by `w : C.hidden +v → Bool`. -/ +def total (v : V) (x : slots a ⊕ E → Bool) (y : slots b ⊕ E → Bool) : F := + ∑ w : C.hidden v → Bool, C.term v x y (Function.update (fun _ _ => false) v w) + +open Classical in +private theorem total_local : Local C.src C.dst C.total := by + intro v x y x' y' hx hy + exact Finset.sum_congr rfl fun _ _ => C.term_local hx hy rfl + +variable [Fintype V] [Fintype E] + +open Classical in +/-- Computes the collapse by the application `ofLocal C.src C.dst C.total`. -/ +abbrev collapse : Diagram F a b := ofLocal C.src C.dst C.total + +open Classical in +/-- The local kernel at one cluster uses only its own hidden bits. +It can be read in any port order. -/ +theorem weight_collapse (v : V) (x : slots a ⊕ E → Bool) (y : slots b ⊕ E → Bool) : + C.collapse.weight v x y = + ∑ z : C.hidden v → Bool, ∏ t : {t // C.owner t = v}, + G.weight t (C.lift x (Function.update (fun _ _ => false) v z)) + (C.lift y (Function.update (fun _ _ => false) v z)) := + weight_ofLocal _ _ _ C.total_local _ _ _ + +open Classical in +theorem eval_collapse : C.collapse.eval = G.eval := by + funext x y + have prod_eq (z : E → Bool) : + (∏ v, C.collapse.vertex x y z v) = + ∑ w : C.Inside, ∏ v, G.vertex x y (C.assignments (z, w)) v := by + simp only [collapse, vertex_ofLocal _ _ _ C.total_local, total, Fintype.prod_sum] + apply Finset.sum_congr rfl + intro w _ + rw [← Fintype.prod_fiberwise C.owner] + apply Finset.prod_congr rfl + intro v _ + change C.term v _ _ _ = C.term v (Sum.elim (bits a x) z) (Sum.elim (bits b y) z) w + exact C.term_local (fun _ _ => rfl) (fun _ _ => rfl) (Function.update_self _ _ _) + unfold eval + simp_rw [prod_eq] + rw [← Equiv.sum_comp C.assignments, Fintype.sum_prod_type] + +end Clustering + +variable {V} (o : G.V → V) + +open Classical in +/-- Keep only wires that cross the partition. -/ +abbrev Between := {e : G.E // o (G.source e) ≠ o (G.target e)} + +open Classical in +/-- Builds `Clustering G V (G.Between o) where owner` with the specified `owner`, `hidden`, +`edges`, `src_hidden`. -/ +def partition : Clustering G V (G.Between o) where + owner := o + hidden v := {e : {e : G.E // o (G.source e) = o (G.target e)} // o (G.source e) = v} + edges := + ((Equiv.refl _).sumCongr (Equiv.sigmaFiberEquiv _)).trans + ((Equiv.sumComm _ _).trans (Equiv.sumCompl (fun e => o (G.source e) = o (G.target e)))) + src_hidden _ e := e.property + dst_hidden _ e := e.val.property.symm.trans e.property + +variable [Field F] [Fintype V] + +open Classical in +/-- The value specified by `(G.partition o).collapse`. -/ +abbrev coarsen := (G.partition o).collapse + +open Classical in +theorem eval_coarsen : (G.coarsen o).eval = G.eval := (G.partition o).eval_collapse + +open Classical in +theorem source_coarsen (e : G.Between o) : (G.coarsen o).source e = o (G.source e) := rfl + +open Classical in +theorem target_coarsen (e : G.Between o) : (G.coarsen o).target e = o (G.target e) := rfl + +open Classical in +theorem cost_coarsen : (G.coarsen o).cost = + Fintype.card V + wd a + wd b + 2 * Fintype.card (G.Between o) := + (G.coarsen o).cost_eq + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- +# Expanding a network by a simultaneous wire identity + +Cut each edge into two half-edges. Insert the two copies of its bit +into the demand ports of the packet. The new sites and the old stations +are disjoint, even when several demands have a common endpoint. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} [Field F] {a b : Wire} (G : Diagram F a b) +variable {S I : Type} {J : I → Type} [Fintype S] [Fintype I] [∀ i, Fintype (J i)] +variable {D : G.E → S × S} {W : (i : I) → J i → S × S} + +namespace Expansion + +open Classical in +/-- Indexes the edge by the coordinates of `G.E ⊕ G.E ⊕ T`. -/ +abbrev Edge (T : Type) := G.E ⊕ G.E ⊕ T + +open Classical in +/-- In the case `.inl i`, this construction gives `.inl (G.src.symm (.inl i)).1`. -/ +def src {T : Type} (D : G.E → S × S) (w : T → S × S) : slots a ⊕ Edge G T → G.V ⊕ S + | .inl i => .inl (G.src.symm (.inl i)).1 + | .inr (.inl e) => .inl (G.source e) + | .inr (.inr (.inl e)) => .inr (D e).2 + | .inr (.inr (.inr j)) => .inr (w j).1 + +open Classical in +/-- In the case `.inl i`, this construction gives `.inl (G.dst.symm (.inl i)).1`. -/ +def dst {T : Type} (D : G.E → S × S) (w : T → S × S) : slots b ⊕ Edge G T → G.V ⊕ S + | .inl i => .inl (G.dst.symm (.inl i)).1 + | .inr (.inl e) => .inr (D e).1 + | .inr (.inr (.inl e)) => .inl (G.target e) + | .inr (.inr (.inr j)) => .inr (w j).2 + +open Classical in +/-- The entry of type `F` for the given inputs. -/ +def entry (P : Spectral.Packet.Rule F D W) (i : I) (v : G.V ⊕ S) + (x : slots a ⊕ Edge G (J i) → Bool) (y : slots b ⊕ Edge G (J i) → Bool) : F := + match v with + | .inl t => G.weight t (Sum.elim (x ∘ Sum.inl) (fun e => x (.inr (.inl e)))) + (Sum.elim (y ∘ Sum.inl) (fun e => y (.inr (.inr (.inl e))))) + | .inr s => P.entry i s (fun e => y (.inr (.inl e))) (fun e => x (.inr (.inr (.inl e)))) + (fun j => if (W i j).1 = s then x (.inr (.inr (.inr j))) else y (.inr (.inr (.inr j)))) + +open Classical in +theorem entry_local (P : Spectral.Packet.Rule F D W) (i : I) : + Local (src G D (W i)) (dst G D (W i)) (entry G P i) := by + rintro (v|s) x y x' y' hx hy + · apply G.local_weight + · rintro (t|e) he + · exact hx (.inl t) (congrArg Sum.inl he) + · exact hx (.inr (.inl e)) (congrArg Sum.inl he) + · rintro (t|e) he + · exact hy (.inl t) (congrArg Sum.inl he) + · exact hy (.inr (.inr (.inl e))) (congrArg Sum.inl he) + · apply P.local' + · exact fun e he => hy (.inr (.inl e)) (congrArg Sum.inr he) + · exact fun e he => hx (.inr (.inr (.inl e))) (congrArg Sum.inr he) + · intro j hj + by_cases h : (W i j).1 = s + · simpa only [ite_eq_left h] using hx (.inr (.inr (.inr j))) (congrArg Sum.inr h) + · simpa only [ite_eq_right h] using hy (.inr (.inr (.inr j))) (congrArg Sum.inr + (hj.resolve_left h)) + +end Expansion + +open Classical in +/-- Computes the expanded by the application `ofLocal (Expansion.src G D (W i)) (Expansion.dst G +D (W i)) (Expansion.entry G P i)`. -/ +abbrev expanded (P : Spectral.Packet.Rule F D W) (i : I) := + ofLocal (Expansion.src G D (W i)) (Expansion.dst G D (W i)) (Expansion.entry G P i) + +open Classical in +theorem weight_expanded (P : Spectral.Packet.Rule F D W) (i : I) (v : G.V ⊕ S) + (x : slots a ⊕ Expansion.Edge G (J i) → Bool) + (y : slots b ⊕ Expansion.Edge G (J i) → Bool) : + (G.expanded P i).weight v x y = Expansion.entry G P i v x y := + weight_ofLocal _ _ _ (Expansion.entry_local G P i) v x y + +open Classical in +private theorem eval_split {U V T : Type} [Fintype U] [Fintype V] [Fintype T] + (g : G.E ≃ U ⊕ V ⊕ T) (x : Val a) (y : Val b) : + G.eval x y = ∑ l : U → Bool, ∑ r : V → Bool, ∑ z : T → Bool, + ∏ v, G.vertex x y (Sum.elim l (Sum.elim r z) ∘ g) v := by + let e : (G.E → Bool) ≃ (U → Bool) × (V → Bool) × (T → Bool) := + ((g.arrowCongr (Equiv.refl Bool)).trans (Equiv.sumArrowEquivProdArrow _ _ _)).trans + ((Equiv.refl _).prodCongr (Equiv.sumArrowEquivProdArrow _ _ _)) + unfold eval + rw [← Equiv.sum_comp e.symm] + simp only [Fintype.sum_prod_type] + rfl + +open Classical in +theorem eval_expanded (P : Spectral.Packet.Rule F D W) (x : Val a) (y : Val b) : + ∑ i, (G.expanded P i).eval x y = G.eval x y := by + let H (l r : G.E → Bool) := ∏ v, G.weight v (Sum.elim (bits a x) l) (Sum.elim (bits b y) r) + have each (i : I) : (G.expanded P i).eval x y = + ∑ l, ∑ r, H l r * ∑ z, ∏ s, P.entry i s l r z := by + rw [eval_split (G.expanded P i) (U := G.E) (V := G.E) (T := J i) (Equiv.refl _)] + simp_rw [expanded, vertex_ofLocal _ _ _ (Expansion.entry_local G P i)] + refine Finset.sum_congr rfl fun l _ => ?_ + refine Finset.sum_congr rfl fun r _ => ?_ + rw [Finset.mul_sum] + refine Finset.sum_congr rfl fun z _ => ?_ + rw [Fintype.prod_sum_type] + simp only [Expansion.entry, Function.comp_apply, Equiv.refl_apply, Sum.elim_inl, Sum.elim_inr, + ite_self] + rfl + simp_rw [each] + rw [Finset.sum_comm] + unfold eval + apply Finset.sum_congr rfl + intro l _ + rw [Finset.sum_comm] + simp_rw [← Finset.mul_sum, ← P.eval] + simp only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- +# Contracting a summand of the simultaneous wire identity + +The partition may depend on the selector. When each cut end meets its +assigned packet site, the surviving graph has just the crossing supplies. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} [Field F] {a b : Wire} (G : Diagram F a b) +variable {S I : Type} {J : I → Type} [Fintype S] [Fintype I] [∀ i, Fintype (J i)] +variable {D : G.E → S × S} {W : (i : I) → J i → S × S} (P : Spectral.Packet.Rule F D W) +variable {V : Type} [Fintype V] (o : I → G.V → V) (q : I → S → V) + +open Classical in +/-- The value specified by `(G.expanded P i).coarsen (Sum.elim (o i) (q i))`. -/ +abbrev replaced (i : I) := (G.expanded P i).coarsen (Sum.elim (o i) (q i)) + +open Classical in +theorem eval_replaced (x : Val a) (y : Val b) : + ∑ i, (G.replaced P o q i).eval x y = G.eval x y := by + simp only [replaced, eval_coarsen, eval_expanded] + +open Classical in +/-- The condition `∀ i e, o i (G.source e) = q i (D e).1 ∧ o i (G.target e) = q i (D e).2` on +the specified data. -/ +def Aligned (D : G.E → S × S) : Prop := + ∀ i e, o i (G.source e) = q i (D e).1 ∧ o i (G.target e) = q i (D e).2 + +open Classical in +/-- The subtype of `e : J i` satisfying `q i (W i e).1 ≠ q i (W i e).2`. -/ +abbrev Cut (i : I) := {e : J i // q i (W i e).1 ≠ q i (W i e).2} + +open Classical in +/-- Reindexes `Cut (W := W) q i` and `(G.replaced P o q i).E` by an equivalence. -/ +def cutEdges (h : G.Aligned o q D) (i : I) : + Cut (W := W) q i ≃ (G.replaced P o q i).E := by + let f : Cut (W := W) q i → (G.replaced P o q i).E := + fun e => ⟨.inr (.inr e.val), e.property⟩ + refine Equiv.ofBijective f ⟨?_, ?_⟩ + · intro e t he + exact Subtype.ext (Sum.inr.inj (Sum.inr.inj (congrArg Subtype.val he))) + · rintro ⟨e | e | j, he⟩ + · exact (he (h i e).1).elim + · exact (he (h i e).2.symm).elim + · exact ⟨⟨j, he⟩, rfl⟩ + +open Classical in +theorem source_cut (h : G.Aligned o q D) (i : I) (e : Cut (W := W) q i) : + (G.replaced P o q i).source (G.cutEdges P o q h i e) = q i (W i e).1 := rfl + +open Classical in +theorem target_cut (h : G.Aligned o q D) (i : I) (e : Cut (W := W) q i) : + (G.replaced P o q i).target (G.cutEdges P o q h i e) = q i (W i e).2 := rfl + +open Classical in +theorem cost_replaced (h : G.Aligned o q D) (i : I) : + (G.replaced P o q i).cost = + Fintype.card V + wd a + wd b + 2 * Fintype.card (Cut (W := W) q i) := by + rw [cost_eq, Fintype.card_congr (G.cutEdges P o q h i)] + +open Classical in +theorem source_exterior (i : I) (t : slots a) : + ((G.replaced P o q i).src.symm (.inl t)).1 = o i (G.src.symm (.inl t)).1 := rfl + +open Classical in +theorem target_exterior (i : I) (t : slots b) : + ((G.replaced P o q i).dst.symm (.inl t)).1 = o i (G.dst.symm (.inl t)).1 := rfl + +omit [Fintype V] in +open Classical in +private theorem ends_le {X Y Z : Type} [Fintype X] [Fintype Y] [Fintype Z] + (u : X ⊕ Y → V) (f : X → V) (g : Z → V) (m : Y ↪ Z) + (he : ∀ x, u (.inl x) = f x) (hi : ∀ y, u (.inr y) = g (m y)) (v : V) : + Fintype.card {t // u t = v} ≤ Fintype.card {t // f t = v} + Fintype.card {t // g t = v} := by + let p : {t // u t = v} → {t // f t = v} ⊕ {t // g t = v} + | ⟨.inl x, h⟩ => .inl ⟨x, (he x).symm.trans h⟩ + | ⟨.inr y, h⟩ => .inr ⟨m y, (hi y).symm.trans h⟩ + rw [← Fintype.card_sum] + apply Fintype.card_le_of_injective p + rintro ⟨x|y, h⟩ ⟨x'|y', h'⟩ eq + · exact Subtype.ext (congrArg Sum.inl (congrArg Subtype.val (Sum.inl.inj eq))) + · cases eq + · cases eq + · exact Subtype.ext (congrArg Sum.inr (m.injective (congrArg Subtype.val (Sum.inr.inj eq)))) + +open Classical in +/-- Including all local supplies only increases the bound on a cluster's arity. -/ +theorem arity_replaced (h : G.Aligned o q D) (i : I) (v : V) : + (G.replaced P o q i).arity v ≤ + (Fintype.card {t : slots a // o i (G.src.symm (.inl t)).1 = v} + + Fintype.card {t : slots b // o i (G.dst.symm (.inl t)).1 = v}) + + (Fintype.card {e : J i // q i (W i e).1 = v} + + Fintype.card {e : J i // q i (W i e).2 = v}) := by + let c := (G.expanded P i).partition (Sum.elim (o i) (q i)) + let inj := (G.cutEdges P o q h i).symm.toEmbedding.trans + (Function.Embedding.subtype (fun j : J i => q i (W i j).1 ≠ q i (W i j).2)) + have h₁ := ends_le c.src (fun t => o i (G.src.symm (.inl t)).1) (fun e => q i (W i e).1) inj + (fun _ => rfl) (fun e => by + obtain ⟨t, rfl⟩ := (G.cutEdges P o q h i).surjective e + simp only [inj, Function.Embedding.trans_apply, Equiv.toEmbedding_apply, + Equiv.symm_apply_apply, + Function.Embedding.subtype_apply] + rfl) v + have h₂ := ends_le c.dst (fun t => o i (G.dst.symm (.inl t)).1) (fun e => q i (W i e).2) inj + (fun _ => rfl) (fun e => by + obtain ⟨t, rfl⟩ := (G.cutEdges P o q h i).surjective e + simp only [inj, Function.Embedding.trans_apply, Equiv.toEmbedding_apply, + Equiv.symm_apply_apply, + Function.Embedding.subtype_apply] + rfl) v + change (ofLocal c.src c.dst _).arity v ≤ _ + rw [arity_ofLocal] + exact (Nat.add_le_add h₁ h₂).trans_eq (add_add_add_comm _ _ _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Substitute.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Substitute.lean new file mode 100644 index 0000000000..416e84701a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Substitute.lean @@ -0,0 +1,92 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Wide + +/-! +# Substitution in powered networks + +Each replacement handles the same number of copies. Summing over the +internal bits of a bundle then factors as independent sums in each copy. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent +variable {F : Type} [Field F] {a b c : Wire} + +theorem power_comp (k : Val a → Val b → F) (l : Val b → Val c → F) (d : ℕ) + (x : Val (copies a d)) (z : Val (copies c d)) : + power (fun s t => ∑ y : Val b, k s y * l y t) d x z = + ∑ y : Val (copies b d), power k d x y * power l d y z := by + induction d with + | zero => simp [power] + | succ d ih => + rw [power, ih, Finset.sum_mul_sum, Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro y _ + apply Finset.sum_congr rfl + intro v _ + exact mul_mul_mul_comm _ _ _ _ + +theorem power_trace (k : Val (.pair a c) → Val (.pair b c) → F) (d : ℕ) + (x : Val (copies a d)) (y : Val (copies b d)) : + power (fun (s : Val a) (t : Val b) => ∑ z : Val c, k (s, z) (t, z)) d x y = + ∑ z : Val (copies c d), power k d (zipCopies a c d (x, z)) (zipCopies b c d (y, z)) := by + induction d with + | zero => simp [power] + | succ d ih => + rw [power, ih, Finset.sum_mul_sum, Fintype.sum_prod_type] + rfl + +private theorem power_pre (k : Val b → Val c → F) (f : Val a → Val b) (d : ℕ) + (x : Val (copies a d)) (y : Val (copies c d)) : + power (fun s t => k (f s) t) d x y = power k d (mapCopies f d x) y := by + induction d with + | zero => rfl + | succ d ih => simp only [power, mapCopies, ih] + +private theorem power_post (k : Val a → Val b → F) (f : Val c → Val b) (d : ℕ) + (x : Val (copies a d)) (y : Val (copies c d)) : + power (fun s t => k s (f t)) d x y = power k d x (mapCopies f d y) := by + induction d with + | zero => rfl + | succ d ih => simp only [power, mapCopies, ih] + +theorem Wide.substitute {u d m : ℕ} {C : ℝ} {L : Set (Table F)} {k : Val a → Val b → F} + (h : Wide F u L a b k m) + (ht : ∀ A B : Wire, ∀ k : Val A → Val B → F, wd A + wd B ≤ u → + ∃ v, Net F (copies A d) (copies B d) (power k d) v ∧ + (v : ℝ) ≤ C * (1 + (wd A + wd B : ℕ))) : + ∃ v, Net F (copies a d) (copies b d) (power k d) v ∧ (v : ℝ) ≤ C * m := by + induction h with + | empty => exact ⟨_, Net.empty.power d, by simp⟩ + | table a b k ha _ => simpa only [Nat.cast_add, Nat.cast_one] using ht a b k ha + | @par a b c e k l m n _ _ ih ig => + obtain ⟨v, hv, ev⟩ := ih + obtain ⟨w, hw, ew⟩ := ig + refine ⟨v + w, (hv.par hw).rewire (.zipCopies a c d) (.zipCopies b e d) (power_zip k l d), ?_⟩ + simpa only [Nat.cast_add, mul_add] using add_le_add ev ew + | @comp a b c k l m n _ _ ih ig => + obtain ⟨v, hv, ev⟩ := ih + obtain ⟨w, hw, ew⟩ := ig + refine ⟨v + w, ?_, ?_⟩ + · simpa only [← power_comp] using hv.comp hw + · simpa only [Nat.cast_add, mul_add] using add_le_add ev ew + | @trace a b c k m _ ih => + obtain ⟨v, hv, ev⟩ := ih + refine ⟨v, ?_, ev⟩ + simpa only [← power_trace] using ((hv.pre (.zipCopies a c d)).post (.zipCopies b c d)).trace + | pre _ hf ih => + obtain ⟨v, hv, ev⟩ := ih + exact ⟨v, by simpa only [← power_pre] using hv.pre (hf.mapCopies d), ev⟩ + | post _ hf ih => + obtain ⟨v, hv, ev⟩ := ih + exact ⟨v, by simpa only [← power_post] using hv.post (hf.mapCopies d), ev⟩ + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Wide.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Wide.lean new file mode 100644 index 0000000000..602cf5ac89 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Diagram/Wide.lean @@ -0,0 +1,347 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FunctionNetwork +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network + +/-! +# Tensor powers on independent bit bundles + +Products, concatenation and regrouping are witnessed by structural +permutations of the exterior positions. No gates identify or discard bits. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- In the case `0`, this construction gives `.unit`. -/ +abbrev copies (a : Wire) : ℕ → Wire + | 0 => .unit + | d + 1 => .pair a (copies a d) + +@[simp] theorem wd_copies (a : Wire) (d : ℕ) : wd (copies a d) = d * wd a := by + induction d with + | zero => simp [wd] + | succ d ih => simp [wd, ih, Nat.succ_mul, Nat.add_comm] + +/-- In the case `0`, this construction gives `()`. -/ +def unitCopies : (d : ℕ) → Val (copies .unit d) + | 0 => () + | d + 1 => ((), unitCopies d) + +theorem Rewire.unitCopies (d : ℕ) : Rewire .unit (copies .unit d) (fun _ + => MatrixExponent.unitCopies d) := by + induction d with + | zero => exact .id .unit + | succ d ih => exact (Rewire.unit' .unit).comp ((Rewire.id .unit).par ih) + +theorem Rewire.copiesUnit (d : ℕ) : Rewire (copies .unit d) .unit (fun _ => ()) := by + obtain ⟨_, h, _⟩ := (unitCopies d).inverse + exact h + +theorem eq_unitCopies (d : ℕ) (x : Val (copies .unit d)) : x = unitCopies d := by + induction d with + | zero => rfl + | succ d ih => exact Prod.ext rfl (ih x.2) + +variable {F : Type} [Field F] {a b c d : Wire} + +/-- Transport a network along permutations in the forward direction. -/ +theorem Net.rewire {k : Val a → Val b → F} {l : Val c → Val d → F} + {f : Val a → Val c} {g : Val b → Val d} {m : ℕ} + (h : Net F a b k m) (hf : Rewire a c f) (hg : Rewire b d g) + (he : ∀ x y, l (f x) (g y) = k x y) : Net F c d l m := by + obtain ⟨f', hf', ef⟩ := hf.inverse + obtain ⟨g', hg', eg⟩ := hg.inverse + have hl : l = fun x y => k (f' x) (g' y) := by + funext x y + rw [← he, (ef _ x).mpr rfl, (eg _ y).mpr rfl] + rw [hl] + exact (h.pre hf').post hg' + +/-- In the case `0, _, _`, this construction gives `1`. -/ +def power (k : Val a → Val b → F) : (d : ℕ) → Val (copies a d) → Val (copies b d) → F + | 0, _, _ => 1 + | d + 1, x, y => k x.1 y.1 * power k d x.2 y.2 + +theorem Net.power {k : Val a → Val b → F} {m : ℕ} (h : Net F a b k m) (d : ℕ) : + Net F (copies a d) (copies b d) (MatrixExponent.power k d) (d * m) := by + induction d with + | zero => rw [Nat.zero_mul]; exact .empty + | succ d ih => rw [Nat.succ_mul, Nat.add_comm (d * m) m]; exact h.par ih + +/-- In the case `0, _`, this construction gives `()`. -/ +def zipCopies (a b : Wire) : + (t : ℕ) → Val (.pair (copies a t) (copies b t)) → Val (copies (.pair a b) t) + | 0, _ => () + | t + 1, x => ((x.1.1, x.2.1), zipCopies a b t (x.1.2, x.2.2)) + +theorem Rewire.zipCopies (a b : Wire) (t : ℕ) : + Rewire (.pair (copies a t) (copies b t)) (copies (.pair a b) t) (MatrixExponent.zipCopies a b + t) := by + induction t with + | zero => exact .unit .unit + | succ t ih => + exact (Rewire.middle a _ b _).comp ((Rewire.id (.pair a b)).par ih) + +theorem power_zip (k : Val a → Val b → F) (l : Val c → Val d → F) (t : ℕ) + (x : Val (.pair (copies a t) (copies c t))) (y : Val (.pair (copies b t) (copies d t))) : + power (fun (s : Val (.pair a c)) (u : Val (.pair b d)) => k s.1 u.1 * l s.2 u.2) t + (zipCopies a c t x) (zipCopies b d t y) = power k t x.1 y.1 * power l t x.2 y.2 := by + induction t with + | zero => simp [power] + | succ t ih => + simp only [power, zipCopies, ih] + exact mul_mul_mul_comm _ _ _ _ + +/-- The first block has length m. Writing the sum as n+m exposes Lean's +recursion on the first block without casts. -/ +def appendCopies (a : Wire) : + (m n : ℕ) → Val (.pair (copies a m) (copies a n)) → Val (copies a (n + m)) + | 0, _, x => x.2 + | m + 1, n, x => (x.1.1, appendCopies a m n (x.1.2, x.2)) + +theorem Rewire.appendCopies (a : Wire) (m n : ℕ) : + Rewire (.pair (copies a m) (copies a n)) (copies a (n + m)) (MatrixExponent.appendCopies a m n) + := by + induction m with + | zero => exact (Rewire.swap .unit _).comp (.unit _) + | succ m ih => exact (Rewire.assoc a _ _).comp ((Rewire.id a).par ih) + +theorem power_append (k : Val a → Val b → F) (m n : ℕ) + (x : Val (.pair (copies a m) (copies a n))) (y : Val (.pair (copies b m) (copies b n))) : + power k (n + m) (appendCopies a m n x) (appendCopies b m n y) = + power k m x.1 y.1 * power k n x.2 y.2 := by + induction m with + | zero => simp [appendCopies, power] + | succ m ih => + change k x.1.1 y.1.1 * power k (n + m) (appendCopies a m n _) (appendCopies b m n _) = _ + rw [ih] + exact (mul_assoc _ _ _).symm + +/-- In the case `0, _`, this construction gives `()`. -/ +def joinCopies (a : Wire) (d : ℕ) : + (t : ℕ) → Val (copies (copies a d) t) → Val (copies a (d * t)) + | 0, _ => () + | t + 1, x => appendCopies a d (d * t) (x.1, joinCopies a d t x.2) + +theorem Rewire.joinCopies (a : Wire) (d t : ℕ) : + Rewire (copies (copies a d) t) (copies a (d * t)) (MatrixExponent.joinCopies a d t) := by + induction t with + | zero => exact .id .unit + | succ t ih => exact ((Rewire.id _).par ih).comp (appendCopies a d (d * t)) + +theorem power_join (k : Val a → Val b → F) (d t : ℕ) + (x : Val (copies (copies a d) t)) (y : Val (copies (copies b d) t)) : + power k (d * t) (joinCopies a d t x) (joinCopies b d t y) = power (power k d) t x y := by + induction t with + | zero => rfl + | succ t ih => + change power k (d * t + d) (appendCopies a d (d * t) _) (appendCopies b d (d * t) _) = _ + rw [power_append, ih] + rfl + +/-- In the case `0, _`, this construction gives `()`. -/ +def mapCopies (f : Val a → Val b) : (t : ℕ) → Val (copies a t) → Val (copies b t) + | 0, _ => () + | t + 1, x => (f x.1, mapCopies f t x.2) + +theorem Rewire.mapCopies {f : Val a → Val b} (h : Rewire a b f) (t : ℕ) : + Rewire (copies a t) (copies b t) (MatrixExponent.mapCopies f t) := by + induction t with + | zero => exact .id .unit + | succ t ih => exact h.par ih + +theorem power_map {f : Val a → Val c} {g : Val b → Val d} + {k : Val a → Val b → F} {l : Val c → Val d → F} + (he : ∀ x y, l (f x) (g y) = k x y) (t : ℕ) (x : Val (copies a t)) (y : Val (copies b t)) : + power l t (mapCopies f t x) (mapCopies g t y) = power k t x y := by + induction t with + | zero => rfl + | succ t ih => simp only [power, mapCopies, he, ih] + +/-- In the case `0, _`, this construction gives `()`. -/ +def listCopies (w : ℕ) : + (t : ℕ) → Val (lists w t) → Val (copies (tree w (word (2 * w))) t) + | 0, _ => () + | t + 1, x => (x.1, listCopies w t x.2) + +theorem Rewire.listCopies (w t : ℕ) : + Rewire (lists w t) (copies (tree w (word (2 * w))) t) (MatrixExponent.listCopies w t) := by + induction t with + | zero => exact .id .unit + | succ t ih => exact (Rewire.id _).par ih + +theorem power_distinct (F : Type) [Field F] (w t : ℕ) (x : Val (lists w t)) + (y : Val (copies .unit t)) : + power (fun (z : Val (tree w (word (2 * w)))) (_ : Val .unit) => + if (flatten w z).Nodup then (1 : F) else 0) t (listCopies w t x) y = + distinctPower F w t x := by + induction t with + | zero => rfl + | succ t ih => + simp only [power, listCopies, distinctPower, ih] + rfl + +/-- Taking d copies of a batch of t lists keeps all t*d lists independent. -/ +theorem Net.power_lists {w t d v : ℕ} + (h : Net F (copies (lists w t) d) (copies .unit d) + (MatrixExponent.power (fun x (_ : Val .unit) => distinctPower F w t x) d) v) : + Net F (lists w (t * d)) .unit (fun x _ => distinctPower F w (t * d) x) v := by + let a := tree w (word (2 * w)) + let k (z : Val a) (_ : Val .unit) : F := if (flatten w z).Nodup then 1 else 0 + have h₁ : Net F (copies (copies a t) d) (copies (copies .unit t) d) + (MatrixExponent.power (MatrixExponent.power k t) d) v := + h.rewire ((Rewire.listCopies w t).mapCopies d) ((Rewire.unitCopies t).mapCopies d) + (power_map (fun x _ => power_distinct F w t x (unitCopies t)) d) + have h₂ := h₁.rewire (Rewire.joinCopies a t d) (Rewire.joinCopies .unit t d) (power_join k t d) + have h₃ := (h₂.pre (Rewire.listCopies w (t * d))).post (Rewire.unitCopies (t * d)) + have e : (fun x (_ : Val .unit) => + MatrixExponent.power k (t * d) (listCopies w (t * d) x) (unitCopies (t * d))) = + (fun x _ => distinctPower F w (t * d) x) := by + funext x y + exact power_distinct F w (t * d) x (unitCopies (t * d)) + rw [← e] + exact h₃ + +/-- The value specified by `h ▸ x`. -/ +def castCopies (a : Wire) {m n : ℕ} (h : m = n) (x : Val (copies a m)) : + Val (copies a n) := h ▸ x + +private theorem rewire_castCopies (a : Wire) {m n : ℕ} (h : m = n) : + Rewire (copies a m) (copies a n) (castCopies a h) := by + subst n + exact .id _ + +private theorem power_cast (k : Val a → Val .unit → F) {m n : ℕ} (h : m = n) x y : + power k n (castCopies a h x) y = power k m x (unitCopies m) := by + subst n + rw [eq_unitCopies _ y] + rfl + +theorem two_pow_add (u : ℕ) : 2 ^ u + 2 ^ u = 2 ^ (u + 1) := by rw [pow_succ, mul_two] + +/-- In the case `0, x`, this construction gives `(x, ())`. -/ +def treeCopies (a : Wire) : (u : ℕ) → Val (tree u a) → Val (copies a (2 ^ u)) + | 0, x => (x, ()) + | u + 1, x => castCopies a (two_pow_add u) + (appendCopies a (2 ^ u) (2 ^ u) (treeCopies a u x.1, treeCopies a u x.2)) + +theorem Rewire.treeCopies (a : Wire) (u : ℕ) : + Rewire (tree u a) (copies a (2 ^ u)) (MatrixExponent.treeCopies a u) := by + induction u with + | zero => exact .unit' a + | succ u ih => + exact ((ih.par ih).comp (appendCopies a _ _)).comp (rewire_castCopies a (two_pow_add u)) + +theorem power_tree (k : Val a → Val .unit → F) (u : ℕ) + (x : Val (tree u a)) (y : Val (copies .unit (2 ^ u))) : + power k (2 ^ u) (treeCopies a u x) y = ((flatten u x).map (fun z => k z ())).prod := by + induction u with + | zero => + change k x () * 1 = _ + simp [flatten] + | succ u ih => + let z := unitCopies (2 ^ u) + rw [treeCopies, power_cast, ← eq_unitCopies _ (appendCopies .unit (2 ^ u) (2 ^ u) (z, z)), + power_append, ih, ih, flatten, List.map_append, List.prod_append] + +end MatrixMultiplicationAllFields.MatrixExponent +end + +section +/- +# Networks of arbitrary arity + +The cost of a station is one plus its arity. A predicate on tables +tracks allowed labels. Joins and reordering expose no new positions. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent + +section +variable {F K : Type} [Field F] [Field K] {a b : Wire} +variable {k : Val a → Val b → F} {m : ℕ} + +theorem Net.map (h : Net F a b k m) (f : F →+* K) : + Net K a b (fun x y => f (k x y)) m := by + induction h with + | empty => simpa only [map_one] using (Net.empty (F := K)) + | table _ _ _ ht => exact .table _ _ _ ht + | par _ _ ih ig => simpa only [map_mul] using ih.par ig + | comp _ _ ih ig => simpa only [map_sum, map_mul] using ih.comp ig + | trace _ ih => simpa only [map_sum] using ih.trace + | pre _ hr ih => exact ih.pre hr + | post _ hr ih => exact ih.post hr + +theorem Rewire.width {f : Val a → Val b} (h : Rewire a b f) : wd a = wd b := by + induction h <;> simp_all only [wd] <;> omega + +end + +/-- Indexes the table by the coordinates of `Σ a b : Wire, Val a → Val b → K`. -/ +abbrev Table (K : Type) := Σ a b : Wire, Val a → Val b → K + +/-- The wide used in the `MatrixExponent` construction. -/ +inductive Wide (K : Type) [Field K] (u : ℕ) (labels : Set (Table K)) : + (a b : Wire) → (Val a → Val b → K) → ℕ → Prop + | empty : Wide K u labels .unit .unit (fun _ _ => 1) 0 + | table (a b) (k : Val a → Val b → K) (arity : wd a + wd b ≤ u) + (label : wd a + wd b ≤ 3 ∨ ⟨a, b, k⟩ ∈ labels) : + Wide K u labels a b k (1 + (wd a + wd b)) + | par {a b c d k l m n} : Wide K u labels a b k m → Wide K u labels c d l n → + Wide K u labels (.pair a c) (.pair b d) (fun x y => k x.1 y.1 * l x.2 y.2) (m + n) + | comp {a b c k l m n} : Wide K u labels a b k m → Wide K u labels b c l n → + Wide K u labels a c (fun x z => ∑ y : Val b, k x y * l y z) (m + n) + | trace {a b c k m} : Wide K u labels (.pair a c) (.pair b c) k m → + Wide K u labels a b (fun x y => ∑ z : Val c, k (x, z) (y, z)) m + | pre {a b c f k m} : Wide K u labels b c k m → Rewire a b f → + Wide K u labels a c (fun x y => k (f x) y) m + | post {a b c f k m} : Wide K u labels a b k m → Rewire c b f → + Wide K u labels a c (fun x y => k x (f y)) m + +variable {F : Type} [Field F] {a b : Wire} {k : Val a → Val b → F} {m : ℕ} + +theorem Wide.width {u : ℕ} {L : Set (Table F)} (h : Wide F u L a b k m) : + wd a + wd b ≤ m := by + induction h with + | empty => simp [wd] + | table => omega + | par _ _ ih ig => simp only [wd]; omega + | comp _ _ ih ig => omega + | trace _ ih => simp only [wd] at ih; omega + | pre _ hf ih => rwa [hf.width] + | post _ hf ih => rwa [hf.width] + +theorem Net.wide (h : Net F a b k m) : ∃ s ≤ 4 * m, Wide F 3 ∅ a b k s := by + induction h with + | empty => exact ⟨_, le_rfl, .empty⟩ + | table _ _ _ ht => exact ⟨_, by omega, .table _ _ _ ht (.inl ht)⟩ + | par _ _ ih ig => + obtain ⟨s, hs, h⟩ := ih + obtain ⟨t, ht, g⟩ := ig + exact ⟨_, by omega, h.par g⟩ + | comp _ _ ih ig => + obtain ⟨s, hs, h⟩ := ih + obtain ⟨t, ht, g⟩ := ig + exact ⟨_, by omega, h.comp g⟩ + | trace _ ih => + obtain ⟨s, hs, h⟩ := ih + exact ⟨s, hs, h.trace⟩ + | pre _ hr ih => + obtain ⟨s, hs, h⟩ := ih + exact ⟨s, hs, h.pre hr⟩ + | post _ hr ih => + obtain ⟨s, hs, h⟩ := ih + exact ⟨s, hs, h.post hr⟩ + +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Distinctness.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Distinctness.lean new file mode 100644 index 0000000000..9a77ceeba0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Distinctness.lean @@ -0,0 +1,67 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.AdjacentDuplicates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Batcher +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BitonicMerge + +/-! # Initial exact network for element distinctness -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- Each bit of each record of each list occupies a separate exterior position. -/ +theorem wd_lists (w t : ℕ) : wd (lists w t) = t * listBits w := by + induction t with + | zero => simp [wd] + | succ t ih => + change wd (tree w (word (2 * w))) + wd (lists w t) = _ + rw [wd_tree, wd_word, ih] + unfold listBits + ring + +variable (F : Type) [Field F] + +private theorem pin {a : Wire} {f : Val a → Bool} {m : ℕ} (h : DNet F a .bit f m) : + ∃ v ≤ m + 1, Net F a .unit (fun x _ => if f x = true then 1 else 0) v := by + obtain ⟨v, hv, h⟩ := h + refine ⟨v + 1, Nat.add_le_add_right hv 1, ?_⟩ + have ht := Net.table (F := F) .bit .unit (fun b _ => if b = true then 1 else 0) (by decide) + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + using h.comp ht + +/-- Sorting preserves the multiset. On the result, strict inequalities +between adjacent words characterize distinctness. -/ +private theorem seed_size (w : ℕ) (hw : 1 ≤ w) : + ∃ m, Realizes F w 1 m ∧ m ≤ 2000 * listBits w * w ^ 2 := by + have sort := sortTree_net (compare_exchange F (2 * w)) w + have test := adjacent_net (compare_lt F (2 * w)) w + obtain ⟨v, hv, h⟩ := pin F (sort.comp test) + refine ⟨v + listBits w, ⟨v, ?_, by simp⟩, ?_⟩ + · have ok (x : Val (tree w (word (2 * w)))) : + adjacent w (sortTree w x) = true ↔ (flatten w x).Nodup := + (adjacent_iff _ _ (sortTree_sorted w x)).trans (sortTree_perm w x).nodup_iff + simpa only [distinctPower, mul_one, ok] using h.pre (.unit _) + · refine (Nat.add_le_add_right hv _).trans ?_ + rw [wd_word] + obtain ⟨j, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : w ≠ 0) + unfold listBits + rw [Nat.succ_eq_add_one, pow_succ 2 j] + have hp : 0 < 2 ^ j := by positivity + ring_nf + omega + +theorem seed : Seed (Realizes F) := by + refine ⟨2000, ?_⟩ + filter_upwards [Filter.eventually_ge_atTop 1] with w hw + obtain ⟨m, h, hm⟩ := seed_size F w hw + exact ⟨m, h, by exact_mod_cast hm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/FieldExtension.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/FieldExtension.lean new file mode 100644 index 0000000000..ad6526e7b2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/FieldExtension.lean @@ -0,0 +1,142 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.RankCriterion +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Descent + +/-! +# Invariance under field extension + +Specialize the finitely many coefficients to a finite extension, take +tensor powers there, then pay the degree-squared overhead just once. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +theorem RankLE.cut {F : Type*} [CommSemiring F] {i j k i' j' k' r : ℕ} (h : RankLE F i j k r) + (hi : i' ≤ i) (hj : j' ≤ j) (hk : k' ≤ k) : RankLE F i' j' k' r := by + obtain ⟨A, B, C, h⟩ := h + let e {i j i' j' : ℕ} (hi : i' ≤ i) (hj : j' ≤ j) (x : Pos i' j') : Pos i j := + (Fin.castLE hi x.1, Fin.castLE hj x.2) + refine ⟨fun l x => A l (e hi hk x), fun l y => B l (e hk hj y), + fun l z => C l (e hi hj z), ?_⟩ + intro x y z + simpa [e, Fin.ext_iff] using h (e hi hk x) (e hk hj y) (e hi hj z) + +variable {F K : Type*} [Field F] [Field K] {a b c s : ℝ} + +theorem exponent_le_of_rank {n i j k r : ℕ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (hn : 2 ≤ n) (hi : side n a ≤ i) (hj : side n b ≤ j) (hk : side n c ≤ k) + (hr : RankLE F i j k r) (hs : (r : ℝ) ≤ (n : ℝ) ^ s) : exponent F a b c ≤ s := + csInf_le ⟨_, fun _ h => areas_le_admissible h⟩ (admissible_of_rank hn ha hb hc hi hj hk hr hs) + +private theorem rank_pos {n r : ℕ} (hn : 2 ≤ n) + (hr : RankLE F (side n a) (side n b) (side n c) r) : 0 < (r : ℝ) := by + have h : 0 < n := by omega + exact_mod_cast (Nat.mul_pos (side_pos h a) (side_pos h b)).trans_le (hr.area (side_pos h c)) + +theorem exponent_lt_of_rank {n r : ℕ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) (hn : 2 ≤ n) + (hr : RankLE F (side n a) (side n b) (side n c) r) + (hs : (r : ℝ) < (n : ℝ) ^ s) : exponent F a b c < s := by + have hn1 : 1 < (n : ℝ) := by exact_mod_cast hn + let t := Real.log (r : ℝ) / Real.log (n : ℝ) + have ht : (n : ℝ) ^ t = r := by + rw [Real.rpow_def_of_pos (by linarith), show Real.log (n : ℝ) * t = Real.log (r : ℝ) by + dsimp [t]; exact mul_div_cancel₀ _ (Real.log_pos hn1).ne', Real.exp_log (rank_pos hn hr)] + exact (exponent_le_of_rank ha hb hc hn le_rfl le_rfl le_rfl hr ht.ge).trans_lt + ((Real.rpow_lt_rpow_left_iff hn1).mp (ht.trans_lt hs)) + +/-- A fixed cost multiplier is absorbed in a single sufficiently high power. -/ +theorem absorb_overhead {n r D : ℕ} (hn : 2 ≤ n) (hr : 0 < (r : ℝ)) + (hs : (r : ℝ) < (n : ℝ) ^ s) : + ∃ k : ℕ, 2 ≤ n ^ k ∧ ((r ^ k * D : ℕ) : ℝ) < ((n ^ k : ℕ) : ℝ) ^ s := by + have ht := tendsto_pow_atTop_atTop_of_one_lt ((one_lt_div hr).mpr hs) + obtain ⟨k, hk, hbig⟩ := + ((eventually_ge_atTop 1).and (ht.eventually_gt_atTop (D : ℝ))).exists + refine ⟨k, hn.trans ?_, ?_⟩ + · simpa using pow_le_pow_right₀ (show 1 ≤ n by omega) hk + · rw [div_pow, lt_div_iff₀ (pow_pos hr k)] at hbig + rw [Nat.cast_mul, Nat.cast_pow r, Nat.cast_pow n, mul_comm] + rw [← Real.rpow_natCast_mul (Nat.cast_nonneg n), mul_comm (k : ℝ), + Real.rpow_mul_natCast (Nat.cast_nonneg n)] + exact hbig + +private theorem descend_saving [Algebra F K] {n r : ℕ} (hn : 2 ≤ n) + (hr : RankLE K (side n a) (side n b) (side n c) r) (hs : (r : ℝ) < (n : ℝ) ^ s) : + ∃ N R : ℕ, 2 ≤ N ∧ RankLE F (side N a) (side N b) (side N c) R ∧ + (R : ℝ) < (N : ℝ) ^ s := by + obtain ⟨L, _, _, _, hL⟩ := finiteExtensionRank (F := F) hr + obtain ⟨k, hk, hbig⟩ := absorb_overhead (D := Module.finrank F L ^ 2) hn (rank_pos hn hr) hs + have h := descendRank (F := F) (hL.pow k) + exact ⟨_, _, hk, h.cut (side_pow le_rfl k) (side_pow le_rfl k) (side_pow le_rfl k), hbig⟩ + +theorem exponent_lt_iff_rank (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + exponent F a b c < s ↔ + ∃ n r : ℕ, 2 ≤ n ∧ RankLE F (side n a) (side n b) (side n c) r ∧ + (r : ℝ) < (n : ℝ) ^ s := by + constructor + · intro h + obtain ⟨t, ht, hts⟩ := exists_lt_of_csInf_lt ⟨_, volume_admissible F ha hb hc⟩ h + by_contra! hn + apply hts.not_ge (le_admissible_of_cost ht ?_) + intro n m hn' hm + by_contra! hm' + let L := Rat F (side n a) (side n b) (side n c) + have rank : RankLE L (side n a) (side n b) (side n c) (2 * m) := bilinearize hm + have saving : ((2 * m : ℕ) : ℝ) < (n : ℝ) ^ s := by exact_mod_cast hm' + obtain ⟨N, R, hN, hR, hsave⟩ := + descend_saving (F := F) (K := L) (a := a) (b := b) (c := c) hn' rank saving + exact hsave.not_ge (hn N R hN hR) + · rintro ⟨n, r, hn, hr, hs⟩ + exact exponent_lt_of_rank ha hb hc hn hr hs + +theorem exponent_extension (F K : Type*) [Field F] [Field K] [Algebra F K] + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : exponent K a b c = exponent F a b c := by + apply le_antisymm + · by_contra! h + obtain ⟨n, r, hn, hr, hs⟩ := (exponent_lt_iff_rank ha hb hc).mp h + exact lt_irrefl _ (exponent_lt_of_rank ha hb hc hn (hr.map (algebraMap F K)) hs) + · by_contra! h + obtain ⟨n, r, hn, hr, hs⟩ := (exponent_lt_iff_rank ha hb hc).mp h + exact lt_irrefl _ ((exponent_lt_iff_rank ha hb hc).mpr (descend_saving (F := F) hn hr hs)) + +theorem cycle (F : Type*) [Field F] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + exponent F a b c = exponent F b c a := by + apply le_antisymm <;> by_contra! h + · obtain ⟨n, r, hn, hr, hs⟩ := (exponent_lt_iff_rank hb hc ha).mp h + exact lt_irrefl _ (exponent_lt_of_rank ha hb hc hn hr.cycle.cycle hs) + · obtain ⟨n, r, hn, hr, hs⟩ := (exponent_lt_iff_rank ha hb hc).mp h + exact lt_irrefl _ (exponent_lt_of_rank hb hc ha hn hr.cycle hs) + +theorem transpose (F : Type*) [Field F] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + exponent F a b c = exponent F b a c := by + apply le_antisymm <;> by_contra! h + · obtain ⟨n, r, hn, hr, hs⟩ := (exponent_lt_iff_rank hb ha hc).mp h + exact lt_irrefl _ (exponent_lt_of_rank ha hb hc hn hr.transpose hs) + · obtain ⟨n, r, hn, hr, hs⟩ := (exponent_lt_iff_rank ha hb hc).mp h + exact lt_irrefl _ (exponent_lt_of_rank hb ha hc hn hr.transpose hs) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- The rank characterization for circuits with formal division. -/ +theorem omega_lt_iff_rank {F : Type*} [Field F] {s : ℝ} : omega F < s ↔ + ∃ n r : ℕ, 2 ≤ n ∧ RankLE F n r ∧ (r : ℝ) < (n : ℝ) ^ s := by + rw [← Rectangle.square, Rectangle.exponent_lt_iff_rank zero_le_one zero_le_one zero_le_one] + simp only [Rectangle.side_one] + +theorem omega_extension (F K : Type*) [Field F] [Field K] [Algebra F K] : + omega K = omega F := by + simpa only [Rectangle.square] using + Rectangle.exponent_extension F K zero_le_one zero_le_one zero_le_one + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/FieldFormula.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/FieldFormula.lean new file mode 100644 index 0000000000..57757cc4ed --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/FieldFormula.lean @@ -0,0 +1,34 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Realization +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Installation + +/-! # The square exponent and rectangular rigidity over every field -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem omega_eq_and_rigidity (F : Type*) [Field F] : omega F = 9 / 4 ∧ Rectangle.Rigidity F := + contact_of_installations (fun p _ => Rounds.installable (ZMod p)) F + +/-- The exponent of square matrix multiplication by rational circuits over any field. -/ +theorem omega_eq (F : Type*) [Field F] : omega F = 9 / 4 := + (omega_eq_and_rigidity F).1 + +theorem nine_fourths_le_omega (F : Type*) [Field F] : 9 / 4 ≤ omega F := + (omega_eq F).ge + +/-- The rectangular exponent is the symmetric benchmark, including on the coordinate planes. -/ +theorem Rectangle.exponent_eq (F : Type*) [Field F] {a b c : ℝ} + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : exponent F a b c = U a b c := by + obtain ⟨square, rigid⟩ := omega_eq_and_rigidity F + exact all_shapes rigid square ha hb hc + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Flattening.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Flattening.lean new file mode 100644 index 0000000000..461d3242a6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Flattening.lean @@ -0,0 +1,25 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law + +/-! # Rank lower bound from flattening the square multiplication tensor -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- The square output flattening has rank equal to the area. -/ +theorem rank_lower {F : Type*} [Field F] {n r : ℕ} (h : RankLE F n r) : + n ^ 2 ≤ r := by + by_cases hn : n = 0 + · simp [hn] + · rw [pow_two] + exact Rectangle.RankLE.area h (Nat.pos_of_ne_zero hn) + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Fourier.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Fourier.lean new file mode 100644 index 0000000000..d0b38a86ad --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Fourier.lean @@ -0,0 +1,64 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import Mathlib.Algebra.Field.GeomSum +public import Mathlib.RingTheory.RootsOfUnity.AlgebraicallyClosed + +/-! +# Characteristic-independent Fourier separation + +Only phases of absolute value below `3 * M` occur. Either `5 * M` or +`5 * M - 1` is invertible in the coefficient field. Use a primitive root +of that order and pad the average with zero to keep exactly `5 * M` copies. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Fourier + +theorem exists_weights {M : ℕ} (hM : 0 < M) : + ∃ (ζ : Coeff) (w : Fin (5 * M) → Coeff), ζ ≠ 0 ∧ + ∀ e : ℤ, -(3 * (M : ℤ)) < e → e < 3 * (M : ℤ) → + (∑ r : Fin (5 * M), w r * ζ ^ ((r : ℤ) * e)) = if e = 0 then 1 else 0 := by + obtain ⟨L, hlow, hhigh, hL⟩ : + ∃ L : ℕ, 3 * M ≤ L ∧ L ≤ 5 * M ∧ (L : Coeff) ≠ 0 := by + by_cases h : ((5 * M : ℕ) : Coeff) = 0 + · refine ⟨5 * M - 1, by omega, by omega, ?_⟩ + rw [Nat.cast_sub (by omega), h, Nat.cast_one, zero_sub] + exact neg_ne_zero.mpr one_ne_zero + · exact ⟨5 * M, by omega, le_rfl, h⟩ + have : NeZero (L : Coeff) := ⟨hL⟩ + obtain ⟨ζ, hζ⟩ := HasEnoughRootsOfUnity.exists_isPrimitiveRoot Coeff L + let w (r : ℕ) : Coeff := if r < L then (L : Coeff)⁻¹ else 0 + refine ⟨ζ, fun r => w r, hζ.ne_zero (by omega), ?_⟩ + intro e he he' + have hs : (∑ r : Fin (5 * M), w r * ζ ^ ((r : ℤ) * e)) = + (L : Coeff)⁻¹ * ∑ r ∈ Finset.range L, (ζ ^ e) ^ r := by + simp_rw [zpow_mul', zpow_natCast] + rw [← Finset.sum_range (fun r => w r * (ζ ^ e) ^ r), Finset.mul_sum] + rw [← Finset.sum_subset (Finset.range_mono hhigh) (by + intro r _ hr + simp [w, Finset.mem_range.not.mp hr])] + apply Finset.sum_congr rfl + intro r hr + simp [w, Finset.mem_range.mp hr] + rw [hs] + by_cases he0 : e = 0 + · simp [he0, hL] + · have hne : ζ ^ e ≠ 1 := by + intro h + exact he0 (Int.eq_zero_of_dvd_of_natAbs_lt_natAbs ((hζ.zpow_eq_one_iff_dvd e).mp h) + (by omega)) + have hperiod : (ζ ^ e) ^ L = 1 := by + rw [← zpow_natCast, ← zpow_mul, hζ.zpow_eq_one_iff_dvd] + exact dvd_mul_left _ _ + rw [geom_sum_eq hne, hperiod] + simp [he0] + +end MatrixMultiplicationAllFields.MatrixExponent.Fourier diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/FunctionNetwork.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/FunctionNetwork.lean new file mode 100644 index 0000000000..0f0bab01e3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/FunctionNetwork.lean @@ -0,0 +1,129 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network + +/-! +# Networks representing graphs of functions + +Composition sums over the shared bits. For a graph tensor exactly one +assignment to those bits survives, independently of the characteristic. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {a b c d : Wire} + +theorem Rewire.middle (a b c d : Wire) : + Rewire (.pair (.pair a b) (.pair c d)) (.pair (.pair a c) (.pair b d)) + (fun x => ((x.1.1, x.2.1), (x.1.2, x.2.2))) := + (Rewire.assoc a b _).comp <| + ((Rewire.id a).par <| (Rewire.assoc' b c d).comp <| + ((Rewire.swap b c).par (Rewire.id d)).comp (Rewire.assoc c b d)).comp <| + Rewire.assoc' a c _ + +theorem Rewire.inverse {f : Val a → Val b} (h : Rewire a b f) : + ∃ g, Rewire b a g ∧ ∀ x y, f x = y ↔ x = g y := by + induction h with + | id a => exact ⟨_, .id a, fun _ _ => Iff.rfl⟩ + | swap a b => exact ⟨_, .swap b a, by simp [Prod.ext_iff, and_comm]⟩ + | assoc a b c => exact ⟨_, .assoc' a b c, by simp [Prod.ext_iff, and_assoc]⟩ + | assoc' a b c => exact ⟨_, .assoc a b c, by simp [Prod.ext_iff, and_assoc]⟩ + | unit a => exact ⟨_, .unit' a, by simp [Prod.ext_iff]⟩ + | unit' a => exact ⟨_, .unit a, by simp [Prod.ext_iff]⟩ + | comp _ _ ih ik => + obtain ⟨_, h₁, e₁⟩ := ih + obtain ⟨_, h₂, e₂⟩ := ik + exact ⟨_, h₂.comp h₁, fun _ _ => (e₂ _ _).trans (e₁ _ _)⟩ + | par _ _ ih ik => + obtain ⟨_, h₁, e₁⟩ := ih + obtain ⟨_, h₂, e₂⟩ := ik + exact ⟨_, h₁.par h₂, by simp [Prod.ext_iff, e₁, e₂]⟩ + +/-- The graph tensor of `f` can be realized with at most `m` vertices. -/ +def DNet (F : Type) [Field F] (a b : Wire) (f : Val a → Val b) (m : ℕ) : Prop := + ∃ v ≤ m, Net F a b (fun x y => if f x = y then 1 else 0) v + +namespace DNet + +variable {F : Type} [Field F] {m n : ℕ} {f : Val a → Val b} + +theorem mono (h : DNet F a b f m) (hm : m ≤ n) : DNet F a b f n := by + obtain ⟨v, hv, h⟩ := h + exact ⟨v, hv.trans hm, h⟩ + +theorem table (F : Type) [Field F] (a b : Wire) (f : Val a → Val b) + (h : wd a + wd b ≤ 3) : DNet F a b f 1 := + ⟨1, le_rfl, .table a b _ h⟩ + +theorem pre {g : Val b → Val c} (h : DNet F b c g m) (k : Rewire a b f) : + DNet F a c (fun x => g (f x)) m := by + obtain ⟨v, hv, h⟩ := h + exact ⟨v, hv, h.pre k⟩ + +theorem post {g : Val b → Val c} (h : DNet F a b f m) (k : Rewire b c g) : + DNet F a c (fun x => g (f x)) m := by + obtain ⟨v, hv, h⟩ := h + obtain ⟨l, hl, he⟩ := k.inverse + exact ⟨v, hv, by simpa only [he] using h.post hl⟩ + +theorem comp {g : Val b → Val c} (h : DNet F a b f m) (k : DNet F b c g n) : + DNet F a c (fun x => g (f x)) (m + n) := by + obtain ⟨v, hv, h⟩ := h + obtain ⟨u, hu, k⟩ := k + refine ⟨_, Nat.add_le_add hv hu, ?_⟩ + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + using h.comp k + +theorem par {g : Val c → Val d} (h : DNet F a b f m) (k : DNet F c d g n) : + DNet F (.pair a c) (.pair b d) (fun x => (f x.1, g x.2)) (m + n) := by + obtain ⟨v, hv, h⟩ := h + obtain ⟨u, hu, k⟩ := k + refine ⟨_, Nat.add_le_add hv hu, ?_⟩ + simpa only [Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul] using h.par k + +private theorem empty (F : Type) [Field F] : DNet F .unit .unit (fun x => x) 0 := + ⟨0, le_rfl, .empty⟩ + +theorem id (F : Type) [Field F] (a : Wire) : DNet F a a (fun x => x) (wd a) := by + induction a with + | unit => exact empty F + | bit => exact table F .bit .bit _ (by decide) + | pair a b ha hb => exact ha.par hb + +theorem dup (F : Type) [Field F] (a : Wire) : + DNet F a (.pair a a) (fun x => (x, x)) (wd a) := by + induction a with + | unit => exact (empty F).post (.unit' _) + | bit => exact table F .bit (.pair .bit .bit) _ (by decide) + | pair a b ha hb => exact (ha.par hb).post (.middle a a b b) + +theorem discard (F : Type) [Field F] (a : Wire) : + DNet F a .unit (fun _ => ()) (wd a) := by + induction a with + | unit => exact empty F + | bit => exact table F .bit .unit _ (by decide) + | pair a b ha hb => exact (ha.par hb).post (.unit _) + +theorem fst (F : Type) [Field F] (a b : Wire) : + DNet F (.pair a b) a (fun x => x.1) (wd (.pair a b)) := + ((id F a).par (discard F b)).post (.unit _) + +theorem snd (F : Type) [Field F] (a b : Wire) : + DNet F (.pair a b) b (fun x => x.2) (wd (.pair a b)) := + ((discard F a).par (id F b)).post ((Rewire.swap _ _).comp (.unit _)) + +theorem pair {g : Val a → Val c} (h : DNet F a b f m) (k : DNet F a c g n) : + DNet F a (.pair b c) (fun x => (f x, g x)) (wd a + m + n) := by + rw [Nat.add_assoc] + exact (dup F a).comp (h.par k) + +end DNet +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Growth.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Growth.lean new file mode 100644 index 0000000000..579250e805 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Growth.lean @@ -0,0 +1,128 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BlockRecursion +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Bounds +public import Mathlib.Data.Nat.Log + +/-! +# From a fixed block to every dimension + +Positive exponent slack pays for linear combinations even when the +block rank equals the largest of the input and output areas. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +private theorem bound_powers {r A D : ℕ} {cost : ℕ → ℕ} {t : ℝ} + (hA : A ≤ r) (hr : (r : ℝ) < t) + (ha : ∀ j, cost (j + 1) ≤ r * cost j + D * A ^ j) : + ∃ M : ℝ, 0 < M ∧ ∀ j, (cost j : ℝ) ≤ M * t ^ j := by + have ht : 0 < t := (Nat.cast_nonneg _).trans_lt hr + let M := max ((cost 0 : ℝ) + 1) ((D : ℝ) / (t - r)) + have hbase : (cost 0 : ℝ) < M := lt_of_lt_of_le (lt_add_one _) (le_max_left _ _) + have hstep : (r : ℝ) * M + D ≤ M * t := by + have h : (D : ℝ) ≤ M * (t - r) := + (div_le_iff₀ (sub_pos.mpr hr)).mp (le_max_right _ _) + linarith + refine ⟨M, (Nat.cast_nonneg _).trans_lt hbase, ?_⟩ + intro j + induction j with + | zero => simpa using hbase.le + | succ j ih => + have harea : (A : ℝ) ^ j ≤ t ^ j := + pow_le_pow_left₀ (by positivity) ((Nat.cast_le.mpr hA).trans hr.le) _ + calc + (cost (j + 1) : ℝ) ≤ (r : ℝ) * cost j + D * (A : ℝ) ^ j := by exact_mod_cast ha j + _ ≤ (r : ℝ) * (M * t ^ j) + D * t ^ j := by gcongr + _ = ((r : ℝ) * M + D) * t ^ j := by ring + _ ≤ (M * t) * t ^ j := mul_le_mul_of_nonneg_right hstep (by positivity) + _ = M * t ^ (j + 1) := by rw [pow_succ', mul_assoc] + +theorem side_pow {n i : ℕ} {a : ℝ} (hi : side n a ≤ i) (p : ℕ) : + side (n ^ p) a ≤ i ^ p := by + apply Nat.ceil_le.mpr + rw [Nat.cast_pow, Nat.cast_pow, ← Real.rpow_natCast_mul (by positivity), + mul_comm, Real.rpow_mul_natCast (by positivity)] + exact pow_le_pow_left₀ (by positivity) (Nat.ceil_le.mp hi) _ + +/-- A block whose three side lengths dominate the prescribed dimensions +at a single base `n` suffices at all dimensions. -/ +theorem integral_of_rank {F : Type*} [CommRing F] {n i j k r : ℕ} {a b c s : ℝ} + (hn : 2 ≤ n) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (hi : side n a ≤ i) (hj : side n b ≤ j) (hk : side n c ≤ k) + (hr : Integral.Rank F i j k r) (hA : max (i * j) (max (i * k) (j * k)) ≤ r) (hrs : (r : ℝ) + ≤ (n : ℝ) ^ s) : + Integral.Admissible F a b c s := by + have hn₁ : 1 < (n : ℝ) := by exact_mod_cast (show 1 < n by omega) + have hi₀ := (side_pos (by omega) a).trans_le hi + have hj₀ := (side_pos (by omega) b).trans_le hj + have hs : 0 ≤ s := by + apply (Real.rpow_le_rpow_left_iff hn₁).mp + rw [Real.rpow_zero] + exact le_trans (by exact_mod_cast (Nat.mul_pos hi₀ hj₀).trans_le ((le_max_left _ _).trans hA)) + hrs + intro ε hε + have hr' : (r : ℝ) < (n : ℝ) ^ (s + ε) := + hrs.trans_lt (Real.rpow_lt_rpow_of_exponent_lt hn₁ (lt_add_of_pos_right s hε)) + obtain ⟨D, cost, hstep, hpad⟩ := integral_power_cost hr + obtain ⟨M, hM, hbound⟩ := bound_powers hA hr' hstep + refine ⟨M * (n : ℝ) ^ (s + ε), by positivity, ?_⟩ + intro m hm + let p := Nat.log n m + 1 + have hlo : m ≤ n ^ p := (Nat.lt_pow_succ_log_self (by omega : 1 < n) m).le + have hhi : n ^ p ≤ n * m := by + rw [show p = Nat.log n m + 1 from rfl, pow_succ'] + exact Nat.mul_le_mul_left n (Nat.pow_log_le_self n (by omega)) + have pad {a : ℝ} {i : ℕ} (ha : 0 ≤ a) (hi : side n a ≤ i) : side m a ≤ i ^ p := + (Nat.ceil_mono (Real.rpow_le_rpow (by positivity) (by exact_mod_cast hlo) ha)).trans + (side_pow hi p) + obtain ⟨t, ht, hcost⟩ := hpad p _ _ _ (pad ha hi) (pad hb hj) (pad hc hk) + refine ⟨t, ht, ?_⟩ + calc + (t : ℝ) ≤ (cost p : ℝ) := by exact_mod_cast hcost + _ ≤ M * ((n : ℝ) ^ (s + ε)) ^ p := hbound p + _ = M * ((n : ℝ) ^ p) ^ (s + ε) := by + rw [← Real.rpow_mul_natCast (by positivity), ← Real.rpow_natCast_mul (by positivity), + mul_comm (s + ε)] + _ ≤ M * ((n : ℝ) * m) ^ (s + ε) := + mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow (by positivity) (by exact_mod_cast hhi) (by linarith)) hM.le + _ = M * (n : ℝ) ^ (s + ε) * (m : ℝ) ^ (s + ε) := by + rw [Real.mul_rpow (by positivity) (by positivity), mul_assoc] + +theorem admissible_of_rank {F : Type*} [Field F] {n i j k r : ℕ} {a b c s : ℝ} + (hn : 2 ≤ n) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (hi : side n a ≤ i) (hj : side n b ≤ j) (hk : side n c ≤ k) + (hr : RankLE F i j k r) (hrs : (r : ℝ) ≤ (n : ℝ) ^ s) : + Admissible F a b c s := by + have hi₀ := (side_pos (by omega) a).trans_le hi + have hj₀ := (side_pos (by omega) b).trans_le hj + have hk₀ := (side_pos (by omega) c).trans_le hk + have hA : max (i * j) (max (i * k) (j * k)) ≤ r := + max_le (hr.area hk₀) (max_le (hr.transpose.cycle.area hj₀) (hr.cycle.area hi₀)) + exact (integral_of_rank hn ha hb hc hi hj hk hr hA hrs).field (RingHom.id F) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem admissible_of_rank {F : Type*} [Field F] {n r : ℕ} {s : ℝ} + (hn : 2 ≤ n) (hr : RankLE F n r) (hrs : (r : ℝ) ≤ (n : ℝ) ^ s) : + Admissible F s := by + have h := Rectangle.admissible_of_rank hn zero_le_one zero_le_one zero_le_one + (Rectangle.side_one n).le (Rectangle.side_one n).le (Rectangle.side_one n).le hr hrs + simp only [Rectangle.Admissible, Rectangle.side_one] at h + exact h + +theorem admissible_three (F : Type*) [Field F] : Admissible F 3 := + admissible_of_rank (by decide) (Rectangle.rank_volume F 2 2 2) (by norm_num) + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/Close.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/Close.lean new file mode 100644 index 0000000000..cbce1785b9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/Close.lean @@ -0,0 +1,952 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import Mathlib.Analysis.Complex.ExponentialBounds +public import Mathlib.Data.Nat.Choose.Bounds +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Data.Finset.Powerset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Protocol +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Address +public import Mathlib.Logic.Equiv.Fin.Basic + +/-! +# Packing a mask into batches + +A marked slot's zero-based rank determines both its batch and its +position within the batch. Hence each batch has at most `2^q` slots +and the total capacity of the used batches wastes at most one batch. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {b : ℕ} + +/-- The quantity computed by `x i && decide (Control.histogram x true (some i) / 2 ^ q = z)`. -/ +def bucket (q z : ℕ) (x : Fin (2 ^ b) → Bool) (i : Fin (2 ^ b)) : Bool := + x i && decide (Control.histogram x true (some i) / 2 ^ q = z) + +private abbrev rank (x : Fin (2 ^ b) → Bool) (i : Fin (2 ^ b)) := Control.histogram x true (some i) + +private theorem rank_lt {x : Fin (2 ^ b) → Bool} {i : Fin (2 ^ b)} (hi : x i = true) : + rank x i < (Finset.univ.filter fun j => x j).card := by + simpa only [Control.rank, hi, Control.histogram_none] using Control.rank_lt x i + +theorem bucket_card (q z : ℕ) (x : Fin (2 ^ b) → Bool) : + (Finset.univ.filter fun i => bucket q z x i).card ≤ 2 ^ q := by + rw [← Finset.card_range (2 ^ q)] + apply Finset.card_le_card_of_injOn (fun i => rank x i % 2 ^ q) + · exact fun _ _ => Finset.mem_range.mpr (Nat.mod_lt _ (Nat.two_pow_pos q)) + intro i hi j hj eq + simp only [Finset.mem_coe, Finset.mem_filter, Finset.mem_univ, true_and, bucket, + Bool.and_eq_true, decide_eq_true_eq] at hi hj + have he : rank x i = rank x j := by + rw [← Nat.mod_add_div (rank x i) (2 ^ q), ← Nat.mod_add_div (rank x j) (2 ^ q)] + exact congrArg₂ (fun r d => r + 2 ^ q * d) eq (hi.2.trans hj.2.symm) + apply Control.rank_injective x + exact Prod.ext (hi.1.trans hj.1.symm) (by simpa only [Control.rank, hi.1, hj.1] using he) + +theorem buckets_card (c q : ℕ) (x : Fin (2 ^ b) → Bool) : + (Finset.univ.filter fun z : Fin (2 ^ c) => ∃ i, bucket q z.val x i = true).card * 2 ^ q ≤ + (Finset.univ.filter fun i => x i).card + 2 ^ q := by + let n := (Finset.univ.filter fun i => x i).card + have hc : (Finset.univ.filter fun z : Fin (2 ^ c) => ∃ i, bucket q z.val x i = true).card ≤ + n / 2 ^ q + 1 := by + rw [← Finset.card_range (n / 2 ^ q + 1)] + refine Finset.card_le_card_of_injOn Fin.val ?_ Fin.val_injective.injOn + intro z hz + obtain ⟨i, hi⟩ := (Finset.mem_filter.mp hz).2 + simp only [bucket, Bool.and_eq_true, decide_eq_true_eq] at hi + apply Finset.mem_range.mpr + rw [← hi.2] + exact Nat.lt_succ_of_le (Nat.div_le_div_right (rank_lt hi.1).le) + calc + _ ≤ (n / 2 ^ q + 1) * 2 ^ q := Nat.mul_le_mul_right _ hc + _ ≤ n + 2 ^ q := by + rw [Nat.add_mul, Nat.one_mul] + exact Nat.add_le_add_right (Nat.div_mul_le_self _ _) _ + +theorem mem_bucket {c q : ℕ} (h : b ≤ c + q) {x : Fin (2 ^ b) → Bool} {i : Fin (2 ^ b)} + (hi : x i = true) : ∃! z : Fin (2 ^ c), bucket q z.val x i = true := by + have hr : rank x i / 2 ^ q < 2 ^ c := by + apply (Nat.div_lt_iff_lt_mul (Nat.two_pow_pos q)).mpr + rw [← Nat.pow_add] + calc + rank x i < (Finset.univ.filter fun j => x j).card := rank_lt hi + _ ≤ 2 ^ b := by simpa using Finset.card_le_univ (Finset.univ.filter fun j => x j) + _ ≤ 2 ^ (c + q) := Nat.pow_le_pow_right (by decide) h + refine ⟨⟨_, hr⟩, by simp [bucket, hi], fun z hz => ?_⟩ + simp only [bucket, Bool.and_eq_true, decide_eq_true_eq] at hz + exact Fin.ext hz.2.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# A six-choice graph for sparse routing + +Count all functions assigning six neighbors per source, allowing repetitions. +For r sources and 4r candidate destinations the fraction trapped in those +destinations is (4r/n)^(6r). Summing over both sets and then over r leaves +a graph with the required expansion. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install +open Finset + +private theorem choose_bound (n r : ℕ) (hr : 0 < r) : + (n.choose r : ℝ) ≤ (3 * n / r : ℝ) ^ r := by + have h : (r : ℝ) ^ r / r.factorial ≤ (3 : ℝ) ^ r := calc + _ ≤ Real.exp (r : ℝ) := Real.pow_div_factorial_le_exp _ (by positivity) _ + _ = (Real.exp 1) ^ r := by rw [← Real.exp_nat_mul, mul_one] + _ ≤ 3 ^ r := pow_le_pow_left₀ (Real.exp_nonneg _) Real.exp_one_lt_three.le _ + calc + _ ≤ (n : ℝ) ^ r / r.factorial := Nat.choose_le_pow_div r n + _ = ((n : ℝ) / r) ^ r * ((r : ℝ) ^ r / r.factorial) := by + rw [div_pow, div_mul_div_cancel₀ (by positivity)] + _ ≤ ((n : ℝ) / r) ^ r * 3 ^ r := mul_le_mul_of_nonneg_left h (by positivity) + _ = _ := by rw [← mul_pow]; ring + +private theorem failure_bound {n r : ℕ} (hr : 0 < r) (hn : 0 < n) (hs : r * 65536 ≤ n) : + ((2 * (2 * n)).choose r : ℝ) * n.choose (4 * r) * (4 * r / n : ℝ) ^ (6 * r) ≤ (1 / 2 : ℝ) ^ r + := by + have h₁ := choose_bound (2 * (2 * n)) r hr + have h₂ := choose_bound n (4 * r) (by omega) + push_cast at h₁ h₂ + calc + _ ≤ (3 * (2 * (2 * n)) / r : ℝ) ^ r * (3 * n / (4 * r) : ℝ) ^ (4 * r) * (4 * r / n : ℝ) ^ (6 * + r) := by gcongr + _ = (15552 * r / n : ℝ) ^ r := by + rw [pow_mul, pow_mul, ← mul_pow, ← mul_pow] + congr 1 + field_simp + ring + _ ≤ _ := by + apply pow_le_pow_left₀ (by positivity) + rw [div_le_iff₀ (by positivity)] + have : (r : ℝ) * 65536 ≤ n := by exact_mod_cast hs + linarith + +private abbrev Raw (n : ℕ) := Candidate (2 * n) → Fin 6 → Fin n + +private def trapped {n : ℕ} (S : Finset (Candidate (2 * n))) (T : Finset (Fin n)) : Finset (Raw n) + := + Fintype.piFinset fun i => Fintype.piFinset fun _ => if i ∈ S then T else univ + +private theorem trapped_count {n : ℕ} (hn : 0 < n) (S : Finset (Candidate (2 * n))) (T : Finset + (Fin n)) : + ((trapped S T).card : ℝ) = + Fintype.card (Raw n) * (T.card / n : ℝ) ^ (6 * S.card) := by + rw [trapped, Fintype.card_piFinset, Nat.cast_prod] + calc + _ = ∏ i : Candidate (2 * n), ((n : ℝ) ^ 6 * (if i ∈ S then (T.card / n : ℝ) ^ 6 else 1)) := by + apply prod_congr rfl + intro i _ + rw [Fintype.card_piFinset_const] + by_cases h : i ∈ S + · rw [ite_eq_left h, ite_eq_left h, Nat.cast_pow, ← mul_pow, + mul_div_cancel₀ _ (by positivity)] + · simp [h] + _ = _ := by + rw [prod_mul_distrib, prod_ite_mem, univ_inter, prod_const, prod_const, pow_mul] + simp [Raw] + +private def failures (n r : ℕ) : Finset (Raw n) := + ((univ.powersetCard r) ×ˢ (univ.powersetCard (4 * r))).biUnion fun st => trapped st.1 st.2 + +private theorem failures_count {n r : ℕ} (hn : 0 < n) (hr : 0 < r) (hs : r * 65536 ≤ n) : + ((failures n r).card : ℝ) ≤ Fintype.card (Raw n) * (1 / 2 : ℝ) ^ r := by + let st := (univ : Finset (Candidate (2 * n))).powersetCard r ×ˢ + (univ : Finset (Fin n)).powersetCard (4 * r) + calc + _ ≤ ∑ p ∈ st, ((trapped p.1 p.2).card : ℝ) := by + rw [← Nat.cast_sum, Nat.cast_le] + exact card_biUnion_le + _ = st.card * (Fintype.card (Raw n) * (4 * r / n : ℝ) ^ (6 * r)) := by + rw [← nsmul_eq_mul, ← sum_const] + apply sum_congr rfl + intro p hp + obtain ⟨h₁, h₂⟩ := mem_product.mp hp + rw [trapped_count hn, (mem_powersetCard.mp h₁).2, (mem_powersetCard.mp h₂).2] + push_cast + rfl + _ = Fintype.card (Raw n) * (((2 * (2 * n)).choose r : ℝ) * n.choose (4 * r) * (4 * r / n : ℝ) ^ + (6 * r)) := by + simp only [st, card_product, card_powersetCard, card_univ, Fintype.card_fin, Nat.cast_mul] + ring + _ ≤ _ := mul_le_mul_of_nonneg_left (failure_bound hr hn hs) (by positivity) + +private theorem half_sum (k : ℕ) : + (∑ i ∈ range k, (1 / 2 : ℝ) ^ (i + 1)) = 1 - (1 / 2 : ℝ) ^ k := by + induction k with + | zero => simp + | succ k ih => rw [sum_range_succ, ih, pow_succ]; ring + +private theorem raw_exists (n : ℕ) (hn : 0 < n) : + ∃ g : Raw n, ∀ S : Finset (Candidate (2 * n)), S.card * 65536 ≤ n → + 4 * S.card ≤ (S.biUnion (fun i => univ.image (g i))).card := by + let k := n / 65536 + let bad := (range k).biUnion fun i => failures n (i + 1) + have : Nonempty (Fin n) := ⟨⟨0, hn⟩⟩ + have hb : (bad.card : ℝ) < Fintype.card (Raw n) := calc + _ ≤ ∑ i ∈ range k, ((failures n (i + 1)).card : ℝ) := by + rw [← Nat.cast_sum, Nat.cast_le] + exact card_biUnion_le + _ ≤ ∑ i ∈ range k, Fintype.card (Raw n) * (1 / 2 : ℝ) ^ (i + 1) := by + apply sum_le_sum + intro i hi + have := mem_range.mp hi + exact failures_count hn (by omega) (by omega) + _ = Fintype.card (Raw n) * (1 - (1 / 2 : ℝ) ^ k) := by rw [← mul_sum, half_sum] + _ < _ := mul_lt_of_lt_one_right (by exact_mod_cast Fintype.card_pos (α := Raw n)) + (sub_lt_self _ (by positivity)) + obtain ⟨g, _, hg⟩ := exists_mem_notMem_of_card_lt_card + (show bad.card < (univ : Finset (Raw n)).card from Nat.cast_lt.mp hb) + refine ⟨g, fun S hS => ?_⟩ + by_contra! hlt + obtain ⟨T, hT, hc⟩ := exists_superset_card_eq hlt.le + (by simpa using (show 4 * S.card ≤ n by omega)) + apply hg + refine mem_biUnion.mpr ⟨S.card - 1, mem_range.mpr (by omega), ?_⟩ + rw [show S.card - 1 + 1 = S.card by omega, failures] + refine mem_biUnion.mpr ⟨(S, T), by simp [hc], ?_⟩ + refine Fintype.mem_piFinset.mpr (fun i => Fintype.mem_piFinset.mpr (fun j => ?_)) + by_cases hi : i ∈ S + · simpa only [ite_eq_left hi] using hT (mem_biUnion.mpr ⟨i, hi, mem_image_of_mem _ (mem_univ j)⟩) + · simp [hi] + +/-- Split each target into groups of at most 24 links. At most one +partially filled group per old target is charged in addition to the +total number of links divided by 24. -/ +private theorem split_links (n : ℕ) (hn : 0 < n) (f : Link (2 * n) → Fin n) : + ∃ (e : Link (2 * n) → Fin (2 * n) × Fin 24) (old : Fin (2 * n) → Fin n), + Function.Injective e ∧ ∀ x, old (e x).1 = f x := by + classical + let fiber := fun j => {x // f x = j} + let block := fun j => Fin (Fintype.card (fiber j) / 24 + 1) + have hl : (∑ j, Fintype.card (fiber j)) = 24 * n := by + rw [← Fintype.card_sigma, Fintype.card_congr (Equiv.sigmaFiberEquiv f)] + simp [Link, Candidate] + omega + have hb : Fintype.card (Sigma block) ≤ Fintype.card (Fin (2 * n)) := by + have he : (∑ j, Fintype.card (fiber j) / 24) * 24 ≤ 24 * n := by + rw [sum_mul, ← hl] + exact sum_le_sum (fun j _ => Nat.div_mul_le_self _ _) + simp only [Fintype.card_sigma, block, Fintype.card_fin, sum_add_distrib, sum_const, + card_univ, nsmul_eq_mul, Nat.cast_id, mul_one] + omega + let enc := Classical.choice (Function.Embedding.nonempty_of_card_le hb) + have : Nonempty (Sigma block) := ⟨⟨⟨0, hn⟩, ⟨0, by omega⟩⟩⟩ + obtain ⟨dec, hdec⟩ := enc.injective.hasLeftInverse + have hsize (j) : Fintype.card (fiber j) ≤ Fintype.card (block j × Fin 24) := by + simp only [block, Fintype.card_prod, Fintype.card_fin] + omega + let spot (j) := Classical.choice (Function.Embedding.nonempty_of_card_le (hsize j)) + let route (x : Sigma fiber) : Fin (2 * n) × Fin 24 := + (enc ⟨x.1, (spot x.1 x.2).1⟩, (spot x.1 x.2).2) + have hi : Function.Injective route := by + rintro ⟨i, x⟩ ⟨j, y⟩ h + have he := enc.injective (congrArg Prod.fst h) + have hij : i = j := congrArg Sigma.fst he + subst j + have hs := congrArg Prod.snd h + have hxy : spot i x = spot i y := + Prod.ext (eq_of_heq (Sigma.mk.inj he).2) hs + rw [(spot i).injective hxy] + refine ⟨route ∘ (Equiv.sigmaFiberEquiv f).symm, fun j => (dec j).1, + hi.comp (Equiv.sigmaFiberEquiv f).symm.injective, ?_⟩ + intro x + exact congrArg Sigma.fst (hdec _) + +theorem graph_exists (n : ℕ) (hn : 0 < n) : + ∃ g : Graph (2 * n), Expands g ∧ ∀ j, degree g univ j ≤ 24 := by + obtain ⟨f, hf⟩ := raw_exists n hn + obtain ⟨e, old, he, hold⟩ := split_links n hn (Function.uncurry f) + let g : Graph (2 * n) := fun i j => (e (i, j)).1 + refine ⟨g, ?_, fun j => ?_⟩ + · intro S hS + have hS' : S.card * 65536 ≤ n := by linarith only [hS] + refine (hf S hS').trans (card_le_card_of_surjOn old ?_) + intro y hy + obtain ⟨i, hi, hj⟩ := mem_biUnion.mp hy + obtain ⟨k, hk, rfl⟩ := mem_image.mp hj + exact ⟨g i k, mem_biUnion.mpr ⟨i, hi, mem_image_of_mem _ hk⟩, hold (i, k)⟩ + · unfold degree + rw [← card_fin 24] + apply card_le_card_of_injOn (fun x => (e x).2) (fun _ _ => mem_univ _) + intro x hx y hy hxy + exact he (Prod.ext ((mem_filter.mp hx).2.trans (mem_filter.mp hy).2.symm) hxy) + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- # Implementing the peeling rounds by bounded local updates -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {n : ℕ} {g : Graph n} + +theorem depends_init (n : ℕ) : Depends (init (n := n)) 1 := by + rintro ⟨i, k⟩ + refine ⟨{i}, by simp, fun x y h => ?_⟩ + cases k + · exact h _ (by simp) + · rfl + +/-- Six lists of at most 24 incident links suffice to compute the current +degrees. The previous value of the output and its activity bit are also read. -/ +theorem depends_step (h : ∀ j, degree g Finset.univ j ≤ 24) : Depends (step g) 200 := by + rintro ⟨i, r⟩ + let links (j : Fin n) : Finset (Link n) := + (Finset.univ ×ˢ Finset.univ).filter (fun e => g e.1 e.2 = j) + let neighbors (k : Fin 6) : Finset (Status n) := + (links (g i k)).image (fun e => (e.1, none)) + let U := Finset.univ.biUnion neighbors + refine ⟨insert (i, r) (insert (i, none) U), ?_, fun x y he => ?_⟩ + · have hu : U.card ≤ 144 := calc + U.card ≤ ∑ k, (neighbors k).card := Finset.card_biUnion_le + _ ≤ ∑ _ : Fin 6, 24 := Finset.sum_le_sum (fun k _ => Finset.card_image_le.trans (h (g i k))) + _ = _ := by simp + have := Finset.card_insert_le (i, r) (insert (i, none) U) + have := Finset.card_insert_le (i, none) U + omega + have hd (k : Fin 6) : degree g (active x) (g i k) = degree g (active y) (g i k) := by + unfold degree + apply congrArg Finset.card + ext e + simp only [Finset.mem_filter, Finset.mem_product, mem_active, Finset.mem_univ, and_true] + by_cases hj : g e.1 e.2 = g i k + · have hm : (e.1, none) ∈ U := Finset.mem_biUnion.mpr + ⟨k, Finset.mem_univ _, Finset.mem_image.mpr ⟨e, by simp [links, hj], rfl⟩⟩ + rw [he _ (Finset.mem_insert_of_mem (Finset.mem_insert_of_mem hm))] + · simp only [hj, and_false] + have hf : first g (active x) i = first g (active y) i := by simp only [first, hd] + have ha := he (i, none) (by simp) + have hb := he (i, r) (by simp) + cases r <;> simp only [step, hf, ha, hb] + +private def readLinks (x : Status n → Bool) (e : Link n) := x (e.1, some e.2) + +private theorem depends_read (n : ℕ) : Depends (readLinks (n := n)) 1 := + fun e => ⟨{(e.1, some e.2)}, by simp, fun _ _ h => h _ (by simp)⟩ + +/-- The quantity computed by `100 * (1 + localCost 1 + localCost 200)`. -/ +def assignCost := 100 * (1 + localCost 1 + localCost 200) + +theorem assign_net (F : Type) [Field F] (h : ∀ j, degree g Finset.univ j ≤ 24) : + BNet F (fun mask (e : Link n) => assign g mask e.1 e.2) (assignCost * n * (1 + rounds n)) := by + let M := 14 * (1 + localCost 1 + localCost 200) * n + have seed : BNet F (init (n := n)) M := by + apply ((depends_init n).bnet F).mono + simp only [Fintype.card_prod, Fintype.card_fin, Fintype.card_option, M] + ring_nf + omega + have next : BNet F (step g) M := by + apply ((depends_step h).bnet F).mono + simp only [Fintype.card_prod, Fintype.card_fin, Fintype.card_option, M] + ring_nf + omega + have last : BNet F (readLinks (n := n)) M := by + apply ((depends_read n).bnet F).mono + simp only [Fintype.card_prod, Fintype.card_fin, Fintype.card_option, M] + ring_nf + omega + have run (r : ℕ) : BNet F (fun mask => (step g)^[r] (init mask)) (M + r * M) := by + induction r with + | zero => simpa using seed + | succ r ih => + simpa only [Function.comp_def, Function.iterate_succ_apply', Nat.succ_mul, Nat.add_assoc] + using + ih.comp next + apply ((run (rounds n)).comp last).mono + unfold M assignCost + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Sparse compaction into a fixed dyadic capacity + +The costs of successive halvings sum to a geometric series. In +particular there is no logarithmic factor multiplying the payload. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +/-- The quantity computed by `20 * (assignCost + localCost 48 + 1)`. -/ +def switchCost := 20 * (assignCost + localCost 48 + 1) + +variable (F J : Type) [Field F] [Fintype J] + +private theorem half_net (l : ℕ) (hl : 1 ≤ l) : + ∃ f : Records (Fin (2 * 2 ^ l)) J → Records (Fin (2 ^ l)) J, + BNet F f (switchCost * 2 ^ l * (1 + l + Fintype.card J)) ∧ + ∀ x, (marked x).card * 131072 ≤ 2 ^ l → Carries x (f x) := by + have hex : ∃ g : Graph (2 ^ l), Expands g ∧ ∀ j, degree g Finset.univ j ≤ 24 := by + cases l with + | zero => omega + | succ l => + rw [pow_succ'] + exact graph_exists (2 ^ l) (by positivity) + obtain ⟨g, he, hd⟩ := hex + have sig := (assign_net F hd).parallel (BNet.id F (Candidate (2 ^ l) × J)) + have sw := (depends_switch (J := J) g hd).bnet F + refine ⟨switch g ∘ signal g, (sig.comp sw).mono ?_, switch_carries g (by positivity) he⟩ + simp only [rounds, Nat.clog_pow _ _ (by decide : 1 < 2), switchCost, + Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + ring_nf + omega + +/-- Compact the marked records from `2^(h+k)` candidate slots to `2^h` slots. -/ +theorem compact (h k : ℕ) (hh : 1 ≤ h) : + ∃ f : Records (Fin (2 ^ (h + k))) J → Records (Fin (2 ^ h)) J, + BNet F f ((switchCost + 1) * 2 ^ (h + k) * (1 + h + k + Fintype.card J)) ∧ + ∀ x, (marked x).card * 131072 ≤ 2 ^ h → Carries x (f x) := by + induction k with + | zero => + refine ⟨id, (BNet.id F _).mono ?_, fun _ _ => ⟨.refl _, fun _ _ => rfl⟩⟩ + simp only [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, Nat.add_zero] + ring_nf + omega + | succ k ih => + rw [← Nat.add_assoc h k, pow_succ'] + obtain ⟨f, hf, ef⟩ := half_net F J (h + k) (by omega) + obtain ⟨g, hg, eg⟩ := ih + refine ⟨_, (hf.comp hg).mono ?_, fun x hx => ?_⟩ + · ring_nf + omega + · have ht := ef x (hx.trans (Nat.pow_le_pow_right (by decide) (Nat.le_add_right h k))) + exact ht.trans (eg _ (by rwa [ht.card])) + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Pooling queries to the same scalar table + +Only marked arguments contribute. Compact them into the smaller bank of +table calls and fill unused positions with an argument of weight one. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {F I J K : Type} [Field F] + +theorem Carries.prod [Fintype I] [Fintype K] {x : Records I J} {y : Records K J} + (h : Carries x y) (f : (J → Bool) → F) : + (∏ i ∈ marked y, f (payload y i)) = ∏ i ∈ marked x, f (payload x i) := by + rw [← Finset.prod_coe_sort (marked y), ← Finset.prod_coe_sort (marked x)] + symm + exact Fintype.prod_equiv h.choose _ _ (fun i => congrArg f (funext (h.choose_spec i)).symm) + +private def fill (dummy : J → Bool) (x : Records I J) (ij : I × J) : Bool := + if x (.inl ij.1) then x (.inr ij) else dummy ij.2 + +private theorem fill_depends (dummy : J → Bool) : Depends (fill (I := I) dummy) 2 := by + classical + intro ij + refine ⟨{.inl ij.1, .inr ij}, by simp, fun x y h => ?_⟩ + simp only [fill, h (.inl ij.1) (by simp), h (.inr ij) (by simp)] + +private theorem filled_prod [Fintype I] {f : (J → Bool) → F} {dummy : J → Bool} + (he : f dummy = 1) (x : Records I J) : + (∏ i, f (fun j => fill dummy x (i, j))) = ∏ i ∈ marked x, f (payload x i) := by + rw [marked, Finset.prod_filter] + apply Finset.prod_congr rfl + intro i _ + by_cases h : x (.inl i) = true + · simp [h, fill]; rfl + · simp [h, fill, he] + +/-- The quantity computed by `switchCost + 2 + localCost 2`. -/ +def poolCost := switchCost + 2 + localCost 2 + +theorem pool [Fintype J] {h k m : ℕ} {f : (J → Bool) → F} + (hh : 1 ≤ h) (hf : Weight F f m) (dummy : J → Bool) (he : f dummy = 1) : + ∃ g : Records (Fin (2 ^ (h + k))) J → F, + Weight F g (2 ^ h * m + poolCost * 2 ^ (h + k) * (1 + h + k + Fintype.card J)) ∧ + ∀ x, (marked x).card * 131072 ≤ 2 ^ h → g x = ∏ i ∈ marked x, f (payload x i) := by + obtain ⟨c, hc, heq⟩ := compact F J h k hh + have ht := (fill_depends (I := Fin (2 ^ h)) dummy).bnet F + have hw := (hc.comp ht).weight (hf.prod h) + refine ⟨_, hw.mono ?_, fun x hx => (filled_prod he (c x)).trans ((heq x hx).prod f)⟩ + have hk : 2 ^ h ≤ 2 ^ (h + k) := Nat.pow_le_pow_right (by decide) (by omega) + simp only [Bus, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + have hu : 2 ^ h + 2 ^ h * Fintype.card J + localCost 2 * (2 ^ h * Fintype.card J) ≤ + (1 + localCost 2) * 2 ^ (h + k) * (1 + h + k + Fintype.card J) := by + calc + _ ≤ (1 + localCost 2) * 2 ^ h * (1 + Fintype.card J) := by ring_nf; omega + _ ≤ _ := by gcongr; omega + unfold poolCost + grw [hu] + exact le_of_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Dividing one group of transports into batches + +Each marked endpoint identifies the physical slot of its source. Both +endpoints consult the same source slot to determine their batch. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +/-- The quantity computed by `Fin (2 ^ s)`. -/ +abbrev Idx (s : ℕ) := Fin (2 ^ s) + +variable {s r : ℕ} + +/-- Requires `(∀ i ∈ marked x, idOf (payload x i) ∈ marked x) ∧ Set.InjOn (fun i => (idOf +(payload x i), payload x i o)) (marked x)`. -/ +def Aligned (o : Fin r) (idOf : (Fin r → Bool) → Idx s) + (x : Records (Idx s) (Fin r)) : Prop := + (∀ i ∈ marked x, idOf (payload x i) ∈ marked x) ∧ + Set.InjOn (fun i => (idOf (payload x i), payload x i o)) (marked x) + +/-- Chooses the operation for the left or right summand. -/ +def select (idOf : (Fin r → Bool) → Idx s) (q j : ℕ) + (x : Records (Idx s) (Fin r)) : Records (Idx s) (Fin r) := + Sum.elim (fun i => x (.inl i) && bucket q j (x ∘ Sum.inl) (idOf (payload x i))) (x ∘ Sum.inr) + +/-- Chooses the operation for the left or right summand. -/ +def batches (idOf : (Fin r → Bool) → Idx s) (q c : ℕ) + (x : Records (Idx s) (Fin r)) : Records (Idx c) (Bus (Idx s) (Fin r)) := + Sum.elim (fun j => decide (∃ i, bucket q j.val (x ∘ Sum.inl) i = true)) + (fun z => select idOf q z.1.val x z.2) + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Dividing a group preserves oriented pairing + +Both orientations consult the same identifier. Injectivity of +(identifier, orientation) bounds the selected endpoints by twice the +number of identifiers in the batch. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {s r q c : ℕ} {idOf : (Fin r → Bool) → Idx s} +variable {x : Records (Idx s) (Fin r)} {o : Fin r} + +private theorem mem_select {z : ℕ} {i : Idx s} : i ∈ marked (select idOf q z x) ↔ + i ∈ marked x ∧ bucket q z (x ∘ Sum.inl) (idOf (payload x i)) = true := by + simp [select] + +private theorem selected (hx : Aligned o idOf x) (q z : ℕ) : + (marked (select idOf q z x)).card ≤ 2 * 2 ^ q ∧ Unambiguous (select idOf q z x) := by + let f (i) := (idOf (payload x i), payload x i o) + let S := Finset.univ.filter (fun i => bucket q z (x ∘ Sum.inl) i) + have inj : Set.InjOn f (marked (select idOf q z x)) := + fun _ hi _ hj => hx.2 (mem_select.mp hi).1 (mem_select.mp hj).1 + constructor + · calc + _ ≤ (S ×ˢ (Finset.univ : Finset Bool)).card := by + refine Finset.card_le_card_of_injOn f ?_ inj + intro i hi + exact Finset.mem_product.mpr + ⟨Finset.mem_filter.mpr ⟨Finset.mem_univ _, (mem_select.mp hi).2⟩, Finset.mem_univ _⟩ + _ = 2 * S.card := by simp [mul_comm] + _ ≤ _ := Nat.mul_le_mul_left _ (bucket_card q z _) + · intro i hi j hj h + apply inj hi hj + exact congrArg (fun p => (idOf p, p o)) h + +theorem divide {s r q c : ℕ} (o : Fin r) (idOf : (Fin r → Bool) → Idx s) + (hf : ∀ p, idOf (flip o p) = idOf p) (hc : s ≤ c + q) + (x : Records (Idx s) (Fin r)) (hx : Aligned o idOf x) : + let y := batches idOf q c x + (marked y).card * 2 ^ q ≤ (marked x).card + 2 ^ q ∧ + (∀ j ∈ marked y, (marked (payload y j)).card ≤ 2 * 2 ^ q ∧ Unambiguous (payload y j)) ∧ + ((∀ j ∈ marked y, Closed o (payload y j)) ↔ Closed o x) := by + let y := batches idOf q c x + have hy : marked y = Finset.univ.filter (fun z : Idx c => ∃ i, bucket q z.val (x ∘ Sum.inl) i + = true) := + by ext; simp [y, batches] + refine ⟨?_, fun j _ => selected hx q j.val, ?_, ?_⟩ + · rw [hy] + exact buckets_card c q (x ∘ Sum.inl) + · intro h i hi + obtain ⟨z, hz, _⟩ := mem_bucket hc (x := x ∘ Sum.inl) (mem_marked.mp (hx.1 i hi)) + have hzy : z ∈ marked y := by + rw [hy] + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, _, hz⟩ + have hh : Closed o (select idOf q z.val x) := h z hzy + obtain ⟨j, hj, he⟩ := hh i (mem_select.mpr ⟨hi, hz⟩) + exact ⟨j, (mem_select.mp hj).1, he⟩ + · intro h z _ + change Closed o (select idOf q z.val x) + intro i hi + obtain ⟨hi, hb⟩ := mem_select.mp hi + obtain ⟨j, hj, he⟩ := h i hi + exact ⟨j, mem_select.mpr ⟨hj, by rw [he, hf]; exact hb⟩, he⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# A layer of shorter permutation calls + +A candidate module lists oriented ends of chunk transports. Its closure +tests that opposite ends have matching identifiers and payloads. Both +the set of modules in use and the set of endpoints within each module +may depend on the selector and the input. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +/-- The data for the layer construction, including `l`, `u`, `o`, `c`, `d`. -/ +structure Layer where + /-- Height of a shorter call. -/ + l : ℕ + /-- Width of a shorter call. -/ + u : ℕ + /-- The installation reserves `2^o` physical modules. -/ + o : ℕ + /-- Excess log count of candidate modules. -/ + c : ℕ + /-- Excess log count of candidate endpoints per module. -/ + d : ℕ + /-- Endpoint width including the orientation bit. -/ + r : ℕ + /-- The `Layer` component of type `Fin r`. -/ + orientation : Fin r + l_pos : 1 ≤ l + o_pos : 1 ≤ o + fits : 1 + l + r ≤ u + +namespace Layer + +variable (p : Layer) + +/-- The quantity computed by `Bus (Fin (2 ^ (p.l + p.d))) (Fin p.r)`. -/ +abbrev Footprint := Bus (Fin (2 ^ (p.l + p.d))) (Fin p.r) +/-- The quantity computed by `Bus (Fin (2 ^ (p.o + p.c))) p.Footprint`. -/ +abbrev Ports := Bus (Fin (2 ^ (p.o + p.c))) p.Footprint + +/-- The defining condition `(marked x).card * 131072 ≤ 2 ^ p.o ∧ ∀ i ∈ marked x, (marked +(payload x i)).card * 131072 ≤ 2 ^ p.l ∧ Unambiguous (payload x i)`. -/ +def Valid (x : p.Ports → Bool) : Prop := + (marked x).card * 131072 ≤ 2 ^ p.o ∧ ∀ i ∈ marked x, + (marked (payload x i)).card * 131072 ≤ 2 ^ p.l ∧ Unambiguous (payload x i) + +open Classical in +/-- The product of `if Closed p.orientation (payload x i) then 1 else 0` indexed by `i ∈ marked +x`. -/ +noncomputable def close (F : Type) [Field F] (x : p.Ports → Bool) : F := + ∏ i ∈ marked x, if Closed p.orientation (payload x i) then 1 else 0 + +/-- The cost of handling candidate endpoints and the module masks. -/ +def work : ℕ := + 2 ^ (p.o + p.c) * (1 + p.o + p.c + 2 ^ (p.l + p.d) * (1 + p.l + p.d + p.u)) + +/-- The network up to the point where the chunk transports must be wired. +Invalid configurations have coefficient zero before any transports are checked. -/ +def Open (F : Type) [Field F] (h v m : ℕ) : Prop := + ∃ (b : Wire) (e : p.Ports ≃ slots b) (f : Val (Tagged.inputs h (word v)) → Val b → F), + Net F (Tagged.inputs h (word v)) b f m ∧ + (∀ x y, f x y ≠ 0 → p.Valid (bits b y ∘ e)) ∧ + ∀ x, Tagged.tag F h (word v) x () = ∑ y, f x y * p.close F (bits b y ∘ e) + +end Layer + +/-- Protocol construction before installing the recursive calls. -/ +def OpenProtocol (F : Type) [Field F] : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ τ : ℝ, 0 < τ → ∃ Y : ℝ, 0 < Y ∧ ∃ J : ℕ, + ∀ A : ℕ, J ≤ A → ∀ ζ : ℝ, 0 < ζ → ∀ᶠ h : ℕ in Filter.atTop, + ∃ (p : Layer) (m : ℕ), (p.l : ℝ) ≤ τ * h ∧ Y * (h : ℝ) ^ A ≤ p.u ∧ + (2 : ℝ) ^ p.o * (2 : ℝ) ^ p.l * p.u ≤ C * (2 : ℝ) ^ h * (h : ℝ) ^ A ∧ + (m + p.work : ℕ) ≤ (2 : ℝ) ^ h * (h : ℝ) ^ A * (h : ℝ) ^ ζ ∧ p.Open F h (h ^ A) m + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Installing the transport modules + +First compact endpoints inside a candidate module, then compact the +selected modules as whole records. Only physical module slots invoke +the smaller tagged permutation verifier. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {F : Type} [Field F] {m : ℕ} + +open Classical in +private def cost := poolCost + switchCost + 1002 + +open Classical in +private theorem Layer.bill (p : Layer) (m : ℕ) : + 2 ^ p.o * ((switchCost + 1) * 2 ^ (p.l + p.d) * (1 + p.l + p.d + p.r) + (m + + 1000 * 2 ^ p.l * p.u)) + + poolCost * 2 ^ (p.o + p.c) * (1 + p.o + p.c + Fintype.card p.Footprint) ≤ + 2 ^ p.o * m + cost * p.work := by + have hr := p.fits + have ho : 2 ^ p.o ≤ 2 ^ (p.o + p.c) := Nat.pow_le_pow_right (by decide) (by omega) + have hl : 2 ^ p.l ≤ 2 ^ (p.l + p.d) := Nat.pow_le_pow_right (by decide) (by omega) + have a : 2 ^ p.o * 2 ^ (p.l + p.d) * (1 + p.l + p.d + p.r) ≤ p.work := by + unfold work + rw [mul_assoc] + apply Nat.mul_le_mul ho + exact (Nat.mul_le_mul_left _ (show 1 + p.l + p.d + p.r ≤ 1 + p.l + p.d + p.u by omega)).trans + (Nat.le_add_left ..) + have b : 2 ^ p.o * 2 ^ p.l * p.u ≤ p.work := by + unfold work + rw [mul_assoc] + apply Nat.mul_le_mul ho + exact (Nat.mul_le_mul hl (Nat.le_add_left ..)).trans (Nat.le_add_left ..) + have c : 2 ^ (p.o + p.c) * (1 + p.o + p.c + Fintype.card p.Footprint) ≤ p.work := by + unfold work + gcongr + simp only [Footprint, Bus, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + rw [← mul_one_add] + exact Nat.mul_le_mul_left _ (by omega) + have h₁ := Nat.mul_le_mul_left (switchCost + 1) a + have h₂ := Nat.mul_le_mul_left 1000 b + have h₃ := Nat.mul_le_mul_left poolCost c + unfold cost + ring_nf at h₁ h₂ h₃ ⊢ + omega + +open Classical in +private theorem Layer.install (p : Layer) (ht : Radix.Tag F p.l p.u m) : + ∃ f : (p.Ports → Bool) → F, Weight F f (2 ^ p.o * m + cost * p.work) ∧ + ∀ x, p.Valid x → f x = p.close F x := by + obtain ⟨s, hs, es⟩ := compact F (Fin p.r) p.l p.d p.l_pos + obtain ⟨g, hg, eg⟩ := check_turns p.orientation (by simpa using p.fits) ht + have verify (x : p.Footprint → Bool) (hx : (marked x).card * 131072 ≤ 2 ^ p.l) + (hy : Unambiguous x) : (g ∘ s) x = if Closed p.orientation x then 1 else 0 := by + have he := es x hx + simp only [Function.comp_apply, eg _ (he.unambiguous hy), he.closed_iff] + let dummy : p.Footprint → Bool := fun _ => false + have hd : marked dummy = ∅ := by simp [marked, dummy] + have he : (g ∘ s) dummy = 1 := by + rw [verify dummy (by simp [hd]) (by simp [Unambiguous, hd])] + simp [Closed, hd] + obtain ⟨f, hf, ef⟩ := pool (k := p.c) p.o_pos (hs.weight hg) dummy he + refine ⟨f, hf.mono ?_, fun x hx => ?_⟩ + · simpa only [Fintype.card_fin] using p.bill m + · rw [ef x hx.1] + exact Finset.prod_congr rfl fun i hi => verify _ (hx.2 i hi).1 (hx.2 i hi).2 + +open Classical in +private theorem Layer.contract (p : Layer) {h v s : ℕ} (ho : p.Open F h v m) + (ht : Radix.Tag F p.l p.u s) : + ∃ n ≤ (m + cost * p.work) + 2 ^ p.o * s, Radix.Tag F h v n := by + obtain ⟨g, hg, he⟩ := p.install ht + obtain ⟨b, e, f, hf, hv, hsum⟩ := ho + obtain ⟨u, hu, hk⟩ := hg b e + refine ⟨m + u, by omega, ?_⟩ + unfold Radix.Tag + convert hf.comp hk using 1 + funext x _ + rw [hsum x] + apply Finset.sum_congr rfl + intro y _ + by_cases hy : f x y = 0 + · simp only [hy, zero_mul] + · rw [he _ (hv x y hy)] + +open Classical in +/-- Uniformly bounded installed width suffices for the inductive +protocol. Control, switching and padding cost subpolynomial overhead. -/ +theorem protocol_of_open (ho : OpenProtocol F) : Radix.Protocol F := by + obtain ⟨C, hC, hh⟩ := ho + refine ⟨C, hC, fun τ hτ => ?_⟩ + obtain ⟨Y, hY, J, hJ⟩ := hh τ hτ + refine ⟨Y, hY, J, fun A hA ζ hζ => ?_⟩ + have grow := ((tendsto_rpow_atTop (half_pos hζ)).comp tendsto_natCast_atTop_atTop) + filter_upwards [hJ A hA _ (half_pos hζ), grow.eventually_ge_atTop (cost + 1 : ℕ), + Filter.eventually_gt_atTop 0] with h H hb hp + obtain ⟨p, m, hl, hu, hL, hm, hg⟩ := H + refine ⟨p.l, p.u, m + cost * p.work, 2 ^ p.o, p.l_pos, hl, hu, by simpa using hL, ?_, + fun s ht => p.contract hg ht⟩ + calc + (↑(m + cost * p.work) : ℝ) ≤ (↑(m + p.work) : ℝ) * (cost + 1 : ℕ) := by + exact_mod_cast (show m + cost * p.work ≤ (m + p.work) * (cost + 1) by ring_nf; omega) + _ ≤ ((2 : ℝ) ^ h * (h : ℝ) ^ A * (h : ℝ) ^ (ζ / 2)) * (h : ℝ) ^ (ζ / 2) := + mul_le_mul hm hb (by positivity) (by positivity) + _ = _ := by rw [mul_assoc, ← Real.rpow_add (by positivity), add_halves] + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# A fixed partition of the available transport slots + +The local circuits supply endpoints in groups. Which slots are used, +their matching, and their payload may depend on the input and selector. +A group needs only a bound on total capacity. The circuit itself finds +the active batches within each group. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +/-- The data for the plan construction, including `layer`, `g`, `t`, `q`, `partition`. -/ +structure Plan where + /-- The `Plan` field of type `Layer`. -/ + layer : Layer + /-- Number of groups, in log scale. -/ + g : ℕ + /-- Number of batches per group, in log scale. -/ + t : ℕ + /-- Number of identifiers in a batch, in log scale. -/ + q : ℕ + /-- Reindexes the data using `Idx g × Idx t ≃ Idx (layer.o + layer.c)`. -/ + partition : Idx g × Idx t ≃ Idx (layer.o + layer.c) + enough : layer.l + layer.d ≤ t + q + fits : q + 18 ≤ layer.l + /-- The `Plan` component of type `slots (word (layer.l + layer.d)) → Fin layer.r`. -/ + ids : slots (word (layer.l + layer.d)) → Fin layer.r + disjoint : ∀ i, ids i ≠ layer.orientation + +namespace Plan + +variable (p : Plan) + +/-- The quantity computed by `p.layer.l + p.layer.d`. -/ +abbrev width := p.layer.l + p.layer.d +/-- Indexes the ports by the coordinates of `Idx p.g × p.layer.Footprint`. -/ +abbrev Ports := Idx p.g × p.layer.Footprint + +/-- The value specified by `x (i, j)`. -/ +def block (x : p.Ports → Bool) (i : Idx p.g) (j : p.layer.Footprint) : Bool := x (i, j) + +/-- The value specified by `Control.decode p.width (v ∘ p.ids)`. -/ +noncomputable def idOf (v : Fin p.layer.r → Bool) : Idx p.width := + Control.decode p.width (v ∘ p.ids) + +/-- The defining condition `(∀ i, Aligned p.layer.orientation p.idOf (p.block x i)) ∧ ((∑ i, +(marked (p.block x i)).card) + 2 ^ p.g * 2 ^ p.q) * 131072 ≤ 2 ^ p.layer.o * 2 ^ p.q`. -/ +def Valid (x : p.Ports → Bool) : Prop := + (∀ i, Aligned p.layer.orientation p.idOf (p.block x i)) ∧ + ((∑ i, (marked (p.block x i)).card) + 2 ^ p.g * 2 ^ p.q) * 131072 ≤ 2 ^ p.layer.o * 2 ^ p.q + +open Classical in +/-- Returns `1` when `∀ i, Closed p.layer.orientation (p.block x i)` holds, and `0` otherwise. -/ +noncomputable def close (F : Type) [Field F] (x : p.Ports → Bool) : F := + if ∀ i, Closed p.layer.orientation (p.block x i) then 1 else 0 + +/-- Reindexes `Idx p.g × Bus (Idx p.t) p.layer.Footprint` and `p.layer.Ports` by an equivalence. -/ +def layout : Idx p.g × Bus (Idx p.t) p.layer.Footprint ≃ p.layer.Ports := + (Equiv.prodSumDistrib _ _ _).trans + (p.partition.sumCongr ((Equiv.prodAssoc _ _ _).symm.trans + (p.partition.prodCongr (.refl _)))) + +/-- The distribute of type `Bool`, constructed using `p.layout.symm j`. -/ +noncomputable def distribute (x : p.Ports → Bool) (j : p.layer.Ports) : Bool := + let z := p.layout.symm j + batches p.idOf p.q p.t (p.block x z.1) z.2 + +end Plan +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- # Distributing groups of endpoint pairs among the candidate modules -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install.Plan + +variable (p : Plan) (x : p.Ports → Bool) + +private noncomputable abbrev split (i : Idx p.g) := batches p.idOf p.q p.t (p.block x i) + +private theorem flags (i : Idx p.g) (j : Idx p.t) : + p.distribute x (.inl (p.partition (i, j))) = p.split x i (.inl j) := by + change p.distribute x (p.layout (i, .inl j)) = _ + simp only [distribute, Equiv.symm_apply_apply] + +private theorem values (i : Idx p.g) (j : Idx p.t) : + payload (p.distribute x) (p.partition (i, j)) = payload (p.split x i) j := by + funext k + change p.distribute x (p.layout (i, .inr (j, k))) = _ + simp only [distribute, Equiv.symm_apply_apply] + rfl + +private theorem in_partition (i : Idx p.g) (j : Idx p.t) : + p.partition (i, j) ∈ marked (p.distribute x) ↔ j ∈ marked (p.split x i) := by + rw [mem_marked, flags, mem_marked] + +private theorem count_distributed : + (marked (p.distribute x)).card = ∑ i, (marked (p.split x i)).card := by + simp only [marked, Finset.card_filter] + rw [← p.partition.sum_comp, Fintype.sum_prod_type] + simp only [flags] + +private theorem idOf_flip (y : Fin p.layer.r → Bool) : + p.idOf (flip p.layer.orientation y) = p.idOf y := by + unfold idOf + apply congrArg + funext j + simp [flip, p.disjoint j] + +theorem distributed (p : Plan) (F : Type) [Field F] (x : p.Ports → Bool) (h : p.Valid x) : + p.layer.Valid (p.distribute x) ∧ p.layer.close F (p.distribute x) = p.close F x := by + have hd (i : Idx p.g) := divide _ _ p.idOf_flip p.enough (p.block x i) (h.1 i) + have hc : (marked (p.distribute x)).card * 2 ^ p.q ≤ + (∑ i, (marked (p.block x i)).card) + 2 ^ p.g * 2 ^ p.q := by + rw [count_distributed, Finset.sum_mul] + calc + _ ≤ ∑ i, ((marked (p.block x i)).card + 2 ^ p.q) := + Finset.sum_le_sum fun i _ => (hd i).1 + _ = _ := by simp [Finset.sum_add_distrib] + refine ⟨⟨?_, ?_⟩, ?_⟩ + · apply Nat.le_of_mul_le_mul_right _ (Nat.two_pow_pos p.q) + rw [Nat.mul_right_comm] + exact (Nat.mul_le_mul_right 131072 hc).trans h.2 + · intro k hk + obtain ⟨⟨i, j⟩, rfl⟩ := p.partition.surjective k + rw [values] + obtain ⟨hb, hu⟩ := (hd i).2.1 j ((p.in_partition x i j).mp hk) + refine ⟨(Nat.mul_le_mul_right _ hb).trans ?_, hu⟩ + calc + 2 * 2 ^ p.q * 131072 = 2 ^ (p.q + 18) := by rw [pow_add]; ring + _ ≤ _ := Nat.pow_le_pow_right (by decide) p.fits + · have iffClosed : (∀ k ∈ marked (p.distribute x), + Closed p.layer.orientation (payload (p.distribute x) k)) ↔ + ∀ i, Closed p.layer.orientation (p.block x i) := by + constructor + · intro H i + apply (hd i).2.2.mp + intro j hj + have hm := H _ ((p.in_partition x i j).mpr hj) + rw [values] at hm + exact hm + · intro H k hk + obtain ⟨⟨i, j⟩, rfl⟩ := p.partition.surjective k + rw [values] + exact (hd i).2.2.mpr (H i) j ((p.in_partition x i j).mp hk) + classical + rw [Layer.close, Finset.prod_boole, close] + congr 1 + exact propext iffClosed + +end MatrixMultiplicationAllFields.MatrixExponent.Install.Plan +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/ControlWeight.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/ControlWeight.lean new file mode 100644 index 0000000000..2e5dc3f500 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/ControlWeight.lean @@ -0,0 +1,75 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products + +/-! +# Selecting a network by a fixed number of control bits + +Multiply one factor per control word. Inactive factors evaluate at a +fixed nonzero entry and divide by that entry. An identically zero table +only needs to test the control bits. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Install.Weight + +variable {K R I : Type} [Field K] [Fintype R] [Fintype I] {m : ℕ} + +open Classical in +/-- The quantity computed by `r + 1 + 2 ^ r * (14 * (r + 1) + localCost (r + 1) + 8 * 2 ^ r + +1)`. -/ +def switchCost (r : ℕ) : ℕ := r + 1 + 2 ^ r * (14 * (r + 1) + localCost (r + 1) + 8 * 2 ^ r + 1) + +open Classical in +private theorem activated (f : (I → Bool) → K) (hf : Weight K f m) (r : R → Bool) : + Weight K (fun x : R ⊕ I → Bool => if x ∘ Sum.inl = r then f (x ∘ Sum.inr) else 1) + (9 * Fintype.card (R ⊕ I) + localCost (Fintype.card R + 1) * Fintype.card I + + 8 * 2 ^ Fintype.card R + m) := by + by_cases hz : ∀ x, f x = 0 + · simp only [hz] + apply ((dense K R (fun y => if y = r then 0 else 1)).pull (Sum.inl : R → R ⊕ I)).mono + rw [Fintype.card_sum] + omega + obtain ⟨x₀, h₀⟩ := not_forall.mp hz + let g (x : R ⊕ I → Bool) := if x ∘ Sum.inl = r then x ∘ Sum.inr else x₀ + have hg : Depends g (Fintype.card R + 1) := by + intro i + let S := Finset.univ.image (Sum.inl : R → R ⊕ I) + refine ⟨insert (.inr i) S, (Finset.card_insert_le ..).trans ?_, fun x y he => ?_⟩ + · exact Nat.add_le_add_right Finset.card_image_le 1 + · have h : x ∘ Sum.inl = y ∘ Sum.inl := funext fun j => + he _ (Finset.mem_insert_of_mem (Finset.mem_image_of_mem _ (Finset.mem_univ j))) + simp only [g, ite_apply, h, Function.comp_apply, he _ (Finset.mem_insert_self ..)] + let k (y : R → Bool) := if y = r then 1 else (f x₀)⁻¹ + have hk := (dense K R k).pull (Sum.inl : R → R ⊕ I) + have he (x : R ⊕ I → Bool) : (f ∘ g) x * k (x ∘ Sum.inl) = + if x ∘ Sum.inl = r then f (x ∘ Sum.inr) else 1 := by + by_cases h : x ∘ Sum.inl = r <;> simp [g, k, h, h₀] + have hp := ((hg.bnet K).weight hf).mul hk + simp only [he] at hp + apply hp.mono + rw [Fintype.card_sum] + omega + +open Classical in +/-- The cost is linear in the payload width and the largest branch cost +when the number of control bits is fixed. -/ +theorem switch (f : (R → Bool) → (I → Bool) → K) (hf : ∀ r, Weight K (f r) m) : + Weight K (fun x : R ⊕ I → Bool => f (x ∘ Sum.inl) (x ∘ Sum.inr)) + (switchCost (Fintype.card R) * (Fintype.card I + m + 1)) := by + have h := finite_product _ (fun r => activated (f r) (hf r) r) + simp only [Finset.prod_ite_eq, Finset.mem_univ, ite_true] at h + apply h.mono + simp only [switchCost, Fintype.card_sum, Fintype.card_fun, Fintype.card_bool] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Install.Weight diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/Products.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/Products.lean new file mode 100644 index 0000000000..6deb07338c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/Products.lean @@ -0,0 +1,743 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.WideTag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortBack + +/-! # Products of local weights on named bit indices -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install.Weight + +variable {F I J A : Type} [Field F] [Fintype I] [Fintype J] [Fintype A] + {m n : ℕ} {f : (I → Bool) → F} + +theorem dense (F I : Type) [Field F] [Fintype I] (f : (I → Bool) → F) : + Weight F f (8 * 2 ^ Fintype.card I) := by + intro a e + obtain ⟨v, h, hv⟩ := Net.dense a .unit (fun x _ => f (bits a x ∘ e)) + exact ⟨v, by simpa [Fintype.card_congr e, wd] using hv, h⟩ + +omit [Fintype I] [Fintype J] in +theorem parallel [Finite I] [Finite J] {g : (J → Bool) → F} (h : Weight F f m) (k : Weight F g n) : + Weight F (fun x => f (x ∘ Sum.inl) * g (x ∘ Sum.inr)) (m + n) := by + let : Fintype I := Fintype.ofFinite I + let : Fintype J := Fintype.ofFinite J + let a := word (Fintype.card I) + let b := word (Fintype.card J) + let i : I ≃ slots (word (Fintype.card I)) := Fintype.equivOfCardEq (by simp) + let j : J ≃ slots (word (Fintype.card J)) := Fintype.equivOfCardEq (by simp) + obtain ⟨v, hv, h⟩ := h a i + obtain ⟨w, hw, k⟩ := k b j + apply of_layout (a := .pair a b) (i.sumCongr j) + exact ⟨v + w, Nat.add_le_add hv hw, (h.par k).post (.unit' _)⟩ + +theorem pull (h : Weight F f m) (e : I → J) : + Weight F (fun x => f (x ∘ e)) (Fintype.card J + 2 * Fintype.card I + m) := by + have hp : BNet F (fun x => x ∘ e) (Fintype.card J + 2 * Fintype.card I) := by + intro a b i j + rw [Fintype.card_congr i, Fintype.card_congr j, card_slots, card_slots] + exact project_net F (i ∘ e ∘ j.symm) + exact hp.weight h + +theorem mul {g : (I → Bool) → F} (h : Weight F f m) (k : Weight F g n) : + Weight F (fun x => f x * g x) (5 * Fintype.card I + m + n) := by + have hp := (h.parallel k).pull (Sum.elim id id) + exact hp.mono (by rw [Fintype.card_sum]; omega) + +theorem finite_product (f : A → (I → Bool) → F) (h : ∀ a, Weight F (f a) m) : + Weight F (fun x => ∏ a, f a x) + (Fintype.card I + Fintype.card A * (5 * Fintype.card I + m)) := by + classical + suffices ∀ u : Finset A, Weight F (fun x => ∏ a ∈ u, f a x) + (Fintype.card I + u.card * (5 * Fintype.card I + m)) from this Finset.univ + intro u + induction u using Finset.induction_on with + | empty => + simp only [Finset.prod_empty, Finset.card_empty, zero_mul, add_zero] + intro a e + rw [Fintype.card_congr e, card_slots] + exact DNet.discard F a + | insert a u ha ih => + simp only [Finset.prod_insert ha, Finset.card_insert_of_notMem ha] + exact ((h a).mul ih).mono (by rw [add_mul]; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Install.Weight +end + +section +/- +# Sparse assignment + +Candidate `i` has six possible links. In each synchronous round an +active candidate takes its first uncontested link, if any. No still +active candidate can subsequently use that target. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +/-- The quantity computed by `Fin (2 * n)`. -/ +abbrev Candidate (n : ℕ) := Fin (2 * n) +/-- Indexes the link by the coordinates of `Candidate n × Fin 6`. -/ +abbrev Link (n : ℕ) := Candidate n × Fin 6 +/-- Indexes the status by the coordinates of `Candidate n × Option (Fin 6)`. -/ +abbrev Status (n : ℕ) := Candidate n × Option (Fin 6) +/-- The indexing data represented by `Candidate n → Fin 6 → Fin n`. -/ +abbrev Graph (n : ℕ) := Candidate n → Fin 6 → Fin n + +variable {n : ℕ} + +/-- The condition `∀ S : Finset (Candidate n), S.card * 131072 ≤ n → 4 * S.card ≤ (S.biUnion +(fun i => Finset.univ.image (g i))).card` on the specified data. -/ +def Expands (g : Graph n) : Prop := + ∀ S : Finset (Candidate n), S.card * 131072 ≤ n → + 4 * S.card ≤ (S.biUnion (fun i => Finset.univ.image (g i))).card + +/-- The indexed operation `((S ×ˢ Finset.univ).filter (fun e => g e.1 e.2 = j)).card`. -/ +def degree (g : Graph n) (S : Finset (Candidate n)) (j : Fin n) : ℕ := + ((S ×ˢ Finset.univ).filter (fun e => g e.1 e.2 = j)).card + +/-- Selects the elements of `S` satisfying `(fun i => ∀ k, degree g S (g i k) ≠ 1)`. -/ +def remain (g : Graph n) (S : Finset (Candidate n)) : Finset (Candidate n) := + S.filter (fun i => ∀ k, degree g S (g i k) ≠ 1) + +/-- The quantity computed by `4 * (Nat.clog 2 n + 1)`. -/ +def rounds (n : ℕ) : ℕ := 4 * (Nat.clog 2 n + 1) + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Peeling sparse sets + +Every reached target accounts for two links when links from retiring +sources are counted twice. This remains valid for parallel links. +Expansion therefore guarantees that at least a third of the sources retire. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {n : ℕ} {g : Graph n} + +theorem remain_subset (g : Graph n) (S : Finset (Candidate n)) : remain g S ⊆ S := + Finset.filter_subset _ _ + +private theorem peel (he : Expands g) (S : Finset (Candidate n)) (hs : S.card * 131072 ≤ n) : + 3 * (remain g S).card ≤ 2 * S.card := by + let U := S.biUnion (fun i => Finset.univ.image (g i)) + have sum_deg (T : Finset (Candidate n)) (hT : T ⊆ S) : + ∑ j ∈ U, degree g T j = 6 * T.card := by + have h : Set.MapsTo (fun e : Link n => g e.1 e.2) + (↑(T ×ˢ (Finset.univ : Finset (Fin 6)))) ↑U := by + intro e h + exact Finset.mem_biUnion.mpr ⟨e.1, hT (Finset.mem_product.mp h).1, + Finset.mem_image.mpr ⟨e.2, Finset.mem_univ _, rfl⟩⟩ + simpa [degree, mul_comm] using (Finset.card_eq_sum_card_fiberwise h).symm + have bound (j) (hj : j ∈ U) : 2 ≤ degree g S j + degree g (S \ remain g S) j := by + obtain ⟨i, hi, hk⟩ := Finset.mem_biUnion.mp hj + obtain ⟨k, _, rfl⟩ := Finset.mem_image.mp hk + have pos (T : Finset (Candidate n)) (hi : i ∈ T) : 0 < degree g T (g i k) := + Finset.card_pos.mpr ⟨(i, k), by simp [hi]⟩ + have := pos S hi + by_cases h : degree g S (g i k) = 1 + · have ni : i ∉ remain g S := fun hr => (Finset.mem_filter.mp hr).2 k h + have := pos _ (Finset.mem_sdiff.mpr ⟨hi, ni⟩) + omega + · omega + have ht := Finset.sum_le_sum bound + rw [Finset.sum_add_distrib, sum_deg _ (by rfl), sum_deg _ Finset.sdiff_subset] at ht + simp only [Finset.sum_const, nsmul_eq_mul, Nat.cast_id] at ht + have hc := Finset.card_sdiff_add_card_eq_card (remain_subset g S) + have hex : 4 * S.card ≤ U.card := he S hs + omega + +theorem cleared {n : ℕ} {g : Graph n} (hn : 0 < n) (he : Expands g) + (S : Finset (Candidate n)) (hs : S.card * 131072 ≤ n) : + (remain g)^[rounds n] S = ∅ := by + have keep (T : Finset (Candidate n)) (hT : T.card * 131072 ≤ n) : + (remain g T).card * 131072 ≤ n := + (Nat.mul_le_mul_right _ (Finset.card_le_card (remain_subset g T))).trans hT + have aux (k : ℕ) (T : Finset (Candidate n)) (hT : T.card * 131072 ≤ n) + (hsize : T.card < 2 ^ k) : (remain g)^[4 * k] T = ∅ := by + induction k generalizing T with + | zero => exact Finset.card_eq_zero.mp (by simpa using hsize) + | succ k ih => + have h₁ := peel he T hT + have h₂ := peel he _ (keep _ hT) + have h₃ := peel he _ (keep _ (keep _ hT)) + have h₄ := peel he _ (keep _ (keep _ (keep _ hT))) + have half : 2 * ((remain g)^[4] T).card ≤ T.card := by + change 2 * (remain g (remain g (remain g (remain g T)))).card ≤ T.card + omega + rw [Nat.mul_succ, Function.iterate_add_apply] + rw [pow_succ] at hsize + exact ih _ (keep _ (keep _ (keep _ (keep _ hT)))) (by omega) + apply aux _ S hs + have hp := Nat.le_pow_clog (by decide : 1 < 2) n + rw [pow_succ] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Deterministic sparse assignment + +Only the activity bits and the six selected-link bits at each candidate +are stored. A retiring candidate takes its first uncontested link. +The invariant forbids every active candidate from hitting an occupied +target, so a later round can never reuse that target. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {n : ℕ} + +/-- The subset of all indices on which the defining predicate holds. -/ +def active (x : Status n → Bool) : Finset (Candidate n) := + Finset.univ.filter (fun i => x (i, none)) + +/-- In the case `(i, none)`, this construction gives `mask i`. -/ +def init (mask : Candidate n → Bool) : Status n → Bool + | (i, none) => mask i + | (_, some _) => false + +/-- The first of type `Option (Fin 6)`, constructed using `Finset.univ.filter (fun k => degree g +S (g i k) = 1)`. -/ +def first (g : Graph n) (S : Finset (Candidate n)) (i : Candidate n) : Option (Fin 6) := + let ks := Finset.univ.filter (fun k => degree g S (g i k) = 1) + if h : ks.Nonempty then some (ks.min' h) else none + +/-- In the case `(i, none)`, this construction gives `x (i, none) && (first g (active x) +i).isNone`. -/ +def step (g : Graph n) (x : Status n → Bool) : Status n → Bool + | (i, none) => x (i, none) && (first g (active x) i).isNone + | (i, some k) => x (i, some k) || (x (i, none) && decide (first g (active x) i = some k)) + +/-- The value specified by `(step g)^[rounds n] (init mask) (i, some k)`. -/ +def assign (g : Graph n) (mask : Candidate n → Bool) (i : Candidate n) (k : Fin 6) : Bool := + (step g)^[rounds n] (init mask) (i, some k) + +variable {g : Graph n} {S : Finset (Candidate n)} {mask : Candidate n → Bool} +variable {x : Status n → Bool} {i j : Candidate n} {k l : Fin 6} + +@[simp] theorem mem_active : i ∈ active x ↔ x (i, none) = true := by simp [active] + +private theorem first_none : first g S i = none ↔ ∀ k, degree g S (g i k) ≠ 1 := by + simp [first, Finset.filter_nonempty_iff] + +private theorem first_unique (hi : i ∈ S) (hj : j ∈ S) + (hk : first g S i = some k) (h : g i k = g j l) : i = j := by + have hd : degree g S (g i k) = 1 := by + unfold first at hk + dsimp only at hk + split at hk + · rename_i has + cases Option.some.inj hk + exact (Finset.mem_filter.mp (Finset.min'_mem _ has)).2 + · cases hk + unfold degree at hd + have eq : (i, k) = (j, l) := Finset.card_le_one.mp hd.le _ (by simp [hi]) _ (by simp [hj, h]) + exact congrArg Prod.fst eq + +private theorem after_active : i ∈ active (step g x) ↔ i ∈ active x ∧ first g (active x) i = none + := by + simp [mem_active, step] + +private theorem after_select : step g x (i, some k) = true ↔ + x (i, some k) = true ∨ i ∈ active x ∧ first g (active x) i = some k := by + simp [step] + +private theorem active_iterate (r : ℕ) : + active ((step g)^[r] x) = (remain g)^[r] (active x) := by + induction r with + | zero => rfl + | succ r ih => + simp only [Function.iterate_succ_apply', ← ih] + ext i + rw [after_active, first_none, remain, Finset.mem_filter] + +private structure Valid (g : Graph n) (mask : Candidate n → Bool) (x : Status n → Bool) : Prop where + cover : ∀ i, mask i = true ↔ i ∈ active x ∨ ∃ k, x (i, some k) = true + unique : ∀ {i k l}, x (i, some k) = true → x (i, some l) = true → k = l + separate : ∀ {i j k l}, x (i, some k) = true → x (j, some l) = true → g i k = g j l → i = j + free : ∀ {i j k l}, x (i, some k) = true → j ∈ active x → g i k ≠ g j l + +private theorem Valid.next (H : Valid g mask x) : Valid g mask (step g x) := by + constructor + · intro i + rw [H.cover, after_active] + simp only [after_select] + cases first g (active x) i <;> aesop + · intro i k l hk hl + rcases after_select.mp hk with hk | ⟨hi, hk⟩ <;> + rcases after_select.mp hl with hl | ⟨hi', hl⟩ + · exact H.unique hk hl + · exact (H.free hk hi' rfl).elim + · exact (H.free hl hi rfl).elim + · exact Option.some.inj (hk.symm.trans hl) + · intro i j k l hk hl heq + rcases after_select.mp hk with hk | ⟨hi, hk⟩ <;> + rcases after_select.mp hl with hl | ⟨hj, hl⟩ + · exact H.separate hk hl heq + · exact (H.free hk hj heq).elim + · exact (H.free hl hi heq.symm).elim + · exact first_unique hi hj hk heq + · intro i j k l hk hj heq + obtain ⟨ha, he⟩ := after_active.mp hj + rcases after_select.mp hk with hk | ⟨hi, hk⟩ + · exact H.free hk ha heq + · rw [first_unique hi ha hk heq, he] at hk + cases hk + +private theorem valid_iterate (g : Graph n) (mask : Candidate n → Bool) (r : ℕ) : + Valid g mask ((step g)^[r] (init mask)) := by + induction r with + | zero => + rw [Function.iterate_zero_apply] + constructor <;> simp [init] + | succ r ih => + rw [Function.iterate_succ_apply'] + exact ih.next + +theorem assign_iff (hn : 0 < n) (he : Expands g) (hs : (active (init mask)).card * 131072 ≤ n) + (i : Candidate n) : (∃ k, assign g mask i k = true) ↔ mask i = true := by + have h := (valid_iterate g mask (rounds n)).cover i + rw [active_iterate, cleared hn he _ hs] at h + simpa [assign] using h.symm + +theorem assign_unique (hx : assign g mask i k = true) (hy : assign g mask i l = true) : k = l := + (valid_iterate g mask (rounds n)).unique hx hy + +theorem assign_injective (hx : assign g mask i k = true) (hy : assign g mask j l = true) + (h : g i k = g j l) : i = j := + (valid_iterate g mask (rounds n)).separate hx hy h + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Switching the payload after sparse assignment + +Keep the activation mask separate from the payload bits, so only the +control bits need to pass through each round of the assignment algorithm. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +/-- Indexes the bus by the coordinates of `I ⊕ (I × J)`. -/ +abbrev Bus (I J : Type) := I ⊕ (I × J) +/-- The indexing data represented by `Bus I J → Bool`. -/ +abbrev Records (I J : Type) := Bus I J → Bool + +variable {I K L J : Type} [Fintype I] [Fintype K] [Fintype L] + +/-- The subset of all indices on which the defining predicate holds. -/ +def marked (x : Records I J) : Finset I := Finset.univ.filter (fun i => x (.inl i)) + +@[simp] theorem mem_marked {x : Records I J} {i : I} : + i ∈ marked x ↔ x (.inl i) = true := by simp [marked] + +/-- The condition `∃ f : marked x ≃ marked y, ∀ (i : marked x) j, y (.inr (f i, j)) = x (.inr +(i, j))` on the specified data. -/ +def Carries (x : Records I J) (y : Records K J) : Prop := + ∃ f : marked x ≃ marked y, ∀ (i : marked x) j, y (.inr (f i, j)) = x (.inr (i, j)) + +theorem Carries.card {x : Records I J} {y : Records K J} (h : Carries x y) : + (marked y).card = (marked x).card := by + simpa only [Fintype.card_coe] using (Fintype.card_congr h.choose).symm + +theorem Carries.trans {x : Records I J} {y : Records K J} {z : Records L J} + (h : Carries x y) (g : Carries y z) : Carries x z := + ⟨h.choose.trans g.choose, fun i j => (g.choose_spec _ j).trans (h.choose_spec i j)⟩ + +variable {n : ℕ} (g : Graph n) + +/-- Indexes the traffic by the coordinates of `Link n ⊕ (Candidate n × J)`. -/ +abbrev Traffic (n : ℕ) (J : Type) := Link n ⊕ (Candidate n × J) + +/-- Chooses the operation for the left or right summand. -/ +def signal (x : Records (Candidate n) J) : Traffic n J → Bool := + Sum.elim (fun e => assign g (x ∘ Sum.inl) e.1 e.2) (x ∘ Sum.inr) + +/-- Selects the elements of `(Finset.univ ×ˢ Finset.univ)` satisfying `(fun e => g e.1 e.2 = +i)`. -/ +def into (i : Fin n) : Finset (Link n) := + (Finset.univ ×ˢ Finset.univ).filter (fun e => g e.1 e.2 = i) + +@[simp] theorem mem_into (e : Link n) (i : Fin n) : e ∈ into g i ↔ g e.1 e.2 = i := by + simp [into] + +/-- In the case `.inl i`, this construction gives `decide (∃ e ∈ into g i, x (.inl e) = true)`. -/ +def switch (x : Traffic n J → Bool) : Records (Fin n) J + | .inl i => decide (∃ e ∈ into g i, x (.inl e) = true) + | .inr (i, j) => decide (∃ e ∈ into g i, x (.inl e) = true ∧ x (.inr (e.1, j)) = true) + +theorem depends_switch (h : ∀ i, degree g Finset.univ i ≤ 24) : Depends (switch (J := J) g) 48 := by + classical + let flags (i : Fin n) := (into g i).image (Sum.inl : Link n → Traffic n J) + have hf (i) : (flags i).card ≤ 24 := Finset.card_image_le.trans (h i) + rintro (i | ⟨i, j⟩) + · refine ⟨flags i, (hf i).trans (by decide), fun x y he => ?_⟩ + simp only [switch, decide_eq_decide] + apply exists_congr + intro e + exact and_congr_right fun hi => by rw [he _ (Finset.mem_image_of_mem _ hi)] + · let data := (into g i).image (fun e => (Sum.inr (e.1, j) : Traffic n J)) + have hd : data.card ≤ 24 := Finset.card_image_le.trans (h i) + refine ⟨flags i ∪ data, (Finset.card_union_le ..).trans (Nat.add_le_add (hf i) hd), + fun x y he => ?_⟩ + simp only [switch, decide_eq_decide] + apply exists_congr + intro e + refine and_congr_right fun hi => ?_ + rw [he _ (Finset.mem_union_left _ (Finset.mem_image_of_mem _ hi)), + he _ (Finset.mem_union_right _ (Finset.mem_image_of_mem _ hi))] + +theorem switch_carries (hn : 0 < n) (he : Expands g) (x : Records (Candidate n) J) + (hs : (marked x).card * 131072 ≤ n) : Carries x (switch g (signal g x)) := by + let mask := x ∘ Sum.inl + let y := switch g (signal g x) + have cov (i : Candidate n) : (∃ k, assign g mask i k = true) ↔ i ∈ marked x := + (assign_iff hn he hs i).trans mem_marked.symm + choose k hk using fun i : marked x => (cov i).mpr i.property + have hit (i : Fin n) : i ∈ marked y ↔ ∃ e : Link n, g e.1 e.2 = i ∧ assign g mask e.1 e.2 = true + := by + simp [y, switch, signal, mask] + let f (i : marked x) : marked y := + ⟨g i (k i), (hit _).mpr ⟨(i, k i), rfl, hk i⟩⟩ + have hi : Function.Injective f := fun i j h => + Subtype.ext (assign_injective (hk i) (hk j) (congrArg Subtype.val h)) + have hg : Function.Surjective f := by + intro j + obtain ⟨⟨i, r⟩, hj, hr⟩ := (hit _).mp j.property + let a : marked x := ⟨i, (cov _).mp ⟨r, hr⟩⟩ + exact ⟨a, Subtype.ext (by change g i (k a) = j; rw [assign_unique (hk a) hr]; exact hj)⟩ + refine ⟨Equiv.ofBijective f ⟨hi, hg⟩, fun i j => ?_⟩ + change y (.inr (g i (k i), j)) = _ + apply Bool.eq_iff_iff.mpr + simp only [y, switch, signal, Sum.elim_inl, Sum.elim_inr, Function.comp_apply, decide_eq_true_eq, + mem_into] + constructor + · rintro ⟨e, hh, hr, hv⟩ + rwa [assign_injective hr (hk i) hh] at hv + · exact fun hv => ⟨(i, k i), rfl, hk i, hv⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Oriented pairs of records + +Both ends of a transport carry its identifier and its data. Flipping +the orientation bit must send each marked record to another marked +record. Unambiguous identifiers make the matching unique. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {I J K : Type} + +/-- The value specified by `x (.inr (i, j))`. -/ +def payload (x : Records I J) (i : I) (j : J) : Bool := x (.inr (i, j)) + +/-- Returns `!(x j)` when `j = o` holds, and `x j` otherwise. -/ +def flip [DecidableEq J] (o : J) (x : J → Bool) (j : J) : Bool := + if j = o then !(x j) else x j + +theorem flip_involutive [DecidableEq J] (o : J) : Function.Involutive (flip o) := by + intro x + funext j + by_cases h : j = o <;> simp [flip, h] + +variable [Fintype I] [Fintype K] + +/-- Computes the unambiguous by the application `Set.InjOn (payload x) (marked x)`. -/ +def Unambiguous (x : Records I J) : Prop := Set.InjOn (payload x) (marked x) + +/-- The condition `∀ i ∈ marked x, ∃ j ∈ marked x, payload x j = flip o (payload x i)` on the +specified data. -/ +def Closed [DecidableEq J] (o : J) (x : Records I J) : Prop := + ∀ i ∈ marked x, ∃ j ∈ marked x, payload x j = flip o (payload x i) + +namespace Carries + +variable {x : Records I J} {y : Records K J} + +theorem symm (h : Carries x y) : Carries y x := by + obtain ⟨e, he⟩ := h + exact ⟨e.symm, fun i j => by simpa using (he (e.symm i) j).symm⟩ + +theorem unambiguous (h : Carries x y) (hx : Unambiguous x) : Unambiguous y := by + obtain ⟨e, he⟩ := h.symm + intro i hi j hj eq + let a : marked y := ⟨i, hi⟩ + let b : marked y := ⟨j, hj⟩ + have hd : payload x (e a) = payload x (e b) := + (funext (he a)).trans (eq.trans (funext (he b)).symm) + have heq : e a = e b := Subtype.ext (hx (e a).property (e b).property hd) + exact congrArg Subtype.val (e.injective heq) + +private theorem closed [DecidableEq J] {o : J} (h : Carries x y) (hx : Closed o x) : Closed o y + := by + obtain ⟨e, he⟩ := h + intro i hi + let a := e.symm ⟨i, hi⟩ + obtain ⟨j, hj, hj'⟩ := hx _ a.property + have ha : payload y i = payload x a := by + funext k + simpa [a, payload] using he a k + exact ⟨e ⟨j, hj⟩, (e ⟨j, hj⟩).property, (funext (he ⟨j, hj⟩)).trans (ha ▸ hj')⟩ + +theorem closed_iff [DecidableEq J] {o : J} (h : Carries x y) : Closed o y ↔ Closed o x := + ⟨h.symm.closed, h.closed⟩ + +end Carries +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Hiding the tags + +For lists of distinct payloads, a proposed permutation has exactly one +valid assignment of positional tags. Summing over those tags therefore +works even over a field of positive characteristic. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install +open Tagged + +variable {F : Type} [Field F] {a : Wire} {w : ℕ} + +private theorem erase (z : Val (tree w (row w a))) : + flatten w (payloads w z) = (flatten w z).map Prod.snd := flatten_mapRows _ _ _ + +/-- On a permutation of a distinct labelled list, erasure is invertible. -/ +private theorem recover (x : Val (tree w a)) (hx : (flatten w x).Nodup) : + ∃ f : Val a → Val (row w a), (∀ y, (f y).2 = y) ∧ + ∀ z, (flatten w z).Perm (flatten w (label w x)) → mapRows f w (payloads w z) = z := by + classical + let L := flatten w (label w x) + have hd : (L.map Prod.snd).Nodup := by rw [← erase, label_payloads]; exact hx + have hi := (List.nodup_map_iff_inj_on (label_nodup w x)).mp hd + have exists_idx (y : Val a) : ∃ i, ∀ j, (j, y) ∈ L → i = j := by + by_cases h : ∃ j, (j, y) ∈ L + · obtain ⟨i, h⟩ := h + exact ⟨i, fun j h' => congrArg Prod.fst (hi _ h _ h' rfl)⟩ + · exact ⟨Lookup.zero w, fun j hj => (h ⟨j, hj⟩).elim⟩ + choose idx hidx using exists_idx + refine ⟨fun y => (idx y, y), fun _ => rfl, fun z hp => flatten_inj w ?_⟩ + rw [flatten_mapRows, erase, List.map_map] + refine (List.map_congr_left ?_).trans (List.map_id _) + intro r hr + change (idx r.2, r.2) = r + rw [hidx r.2 r.1 (hp.subset hr)] + +private theorem untag (x y : Val (tree w a)) (hx : (flatten w x).Nodup) : + (∑ z : Val (tree w (row w a)), tag F w a (x, z) () * + if payloads w z = y then 1 else 0) = permuted F w x y := by + classical + obtain ⟨f, hi, hf⟩ := recover x hx + let Z := mapRows f w y + have hy : payloads w Z = y := by + apply flatten_inj w + simp [erase, Z, flatten_mapRows, List.map_map, Function.comp_def, hi] + have hl : mapRows f w x = label w x := by + simpa only [label_payloads] using hf (label w x) (.refl _) + have hp : (flatten w Z).Perm (flatten w (label w x)) ↔ (flatten w y).Perm (flatten w x) := by + rw [← hl, show Z = mapRows f w y from rfl, flatten_mapRows, flatten_mapRows] + exact List.map_perm_map_iff (Function.LeftInverse.injective hi) + rw [Finset.sum_eq_single Z] + · simp only [hy, ite_true, mul_one, tag, permuted, hp] + · intro z _ hz + by_cases h : (flatten w z).Perm (flatten w (label w x)) + · have : payloads w z ≠ y := fun h' => hz ((hf z h).symm.trans (congrArg (mapRows f w) h')) + simp [this] + · simp [tag, permuted, h] + · simp + +theorem blind {w u m : ℕ} (ht : Radix.Tag F w u m) : + ∃ (k : Val (tree w (word u)) → Val (tree w (word u)) → F) (v : ℕ), + Net F (tree w (word u)) (tree w (word u)) k v ∧ v ≤ m + 10 * 2 ^ w * (u + w + 1) ∧ + ∀ x y, (flatten w x).Nodup → k x y = Tagged.permuted F w x y := by + let a := word u + have h := Net.curry (k := fun x z => tag F w a (x, z) ()) ht + obtain ⟨v, hv, strip⟩ := mapRows_net (DNet.snd F (word w) a) w + refine ⟨_, _, h.comp strip, ?_, untag⟩ + simp only [wd_tree, wd_word, wd, a] at hv ⊢ + ring_nf at hv ⊢ + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Checking opposite ends of transports + +Compare the list of active records with the same list after reversing +orientation. Unmarked slots receive separate addresses. This keeps all +records distinct, so hiding positional tags introduces no multiplicities. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {F J : Type} [Field F] [DecidableEq J] {w u N : ℕ} + +private abbrev Key (N : ℕ) (J : Type) := Fin N ⊕ (J → Bool) + +private def key (o : J) (x : Records (Fin N) J) (b : Bool) (i : Fin N) : Key N J := + if i ∈ marked x then .inr (if b then flip o (payload x i) else payload x i) else .inl i + +private theorem key_injective (o : J) (x : Records (Fin N) J) (hx : Unambiguous x) : + Function.Injective (key o x true) := by + intro i j he + unfold key at he + by_cases hi : i ∈ marked x <;> by_cases hj : j ∈ marked x + · simp only [hi, hj, ite_true, Sum.inr.injEq] at he + exact hx hi hj ((flip_involutive o).injective he) + · simp [hi, hj] at he + · simp [hi, hj] at he + · simpa only [hi, hj, ite_false, Sum.inl.injEq] using he + +private theorem key_perm (o : J) (x : Records (Fin N) J) (hx : Unambiguous x) : + (List.ofFn (key o x false)).Perm (List.ofFn (key o x true)) ↔ Closed o x := by + classical + constructor + · intro h i hi + have := h.symm.subset (List.mem_ofFn.mpr ⟨i, rfl⟩) + obtain ⟨j, hj⟩ := List.mem_ofFn.mp this + by_cases he : j ∈ marked x + · exact ⟨j, he, by simpa [key, hi, he] using hj⟩ + · simp [key, hi, he] at hj + · intro h + have hsub : List.ofFn (key o x true) ⊆ List.ofFn (key o x false) := by + intro r hr + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hr + by_cases hi : i ∈ marked x + · obtain ⟨j, hj, he⟩ := h i hi + exact List.mem_ofFn.mpr ⟨j, by simp [key, hi, hj, he]⟩ + · exact List.mem_ofFn.mpr ⟨i, by simp [key, hi]⟩ + have hn := List.nodup_ofFn.mpr (key_injective o x hx) + exact ((hn.subperm hsub).perm_of_length_le (by simp)).symm + +variable [Fintype J] + +private abbrev Pos (J : Type) [Fintype J] (w u : ℕ) := + Unit ⊕ Fin w ⊕ J ⊕ Fin (u - (1 + w + Fintype.card J)) + +private def code (e : Fin (2 ^ w) ≃ (Fin w → Bool)) : Key (2 ^ w) J → Pos J w u → Bool + | .inl i, .inr (.inl j) => e i j + | .inr _, .inl _ => true + | .inr d, .inr (.inr (.inl j)) => d j + | _, _ => false + +omit [DecidableEq J] in +private theorem code_injective (e : Fin (2 ^ w) ≃ (Fin w → Bool)) : + Function.Injective (code (J := J) (u := u) e) := by + rintro (i | x) (j | y) h + · exact congrArg Sum.inl (e.injective (funext fun k => congrFun h (.inr (.inl k)))) + · exact (Bool.false_ne_true (congrFun h (.inl ()))).elim + · exact (Bool.false_ne_true (congrFun h (.inl ())).symm).elim + · exact congrArg Sum.inr (funext fun k => congrFun h (.inr (.inr (.inl k)))) + +private theorem code_depends (o : J) (e : Fin (2 ^ w) ≃ (Fin w → Bool)) + (b : Bool) (i : Fin (2 ^ w)) (j : Pos J w u) : + ∃ S : Finset (Bus (Fin (2 ^ w)) J), S.card ≤ 2 ∧ ∀ x y, (∀ k ∈ S, x k = y k) → + code e (key o x b i) j = code e (key o y b i) j := by + let p : J := match j with + | .inr (.inr (.inl t)) => t + | _ => o + refine ⟨{.inl i, .inr (i, p)}, by simp, fun x y h => ?_⟩ + have hi := h (.inl i) (by simp) + have hj := h (.inr (i, p)) (by simp) + simp only [key, mem_marked, hi] + by_cases hm : y (.inl i) = true + · simp only [hm, ite_true] + rcases j with _ | _ | p' | _ + · rfl + · rfl + · change payload x i p' = payload y i p' at hj + cases b <;> simp [code, flip, hj] + · rfl + · simp [hm] + +theorem uncurry {a : Wire} {k : Val a → Val a → F} {v : ℕ} + (h : Net F a a k v) : Net F (.pair a a) .unit (fun x _ => k x.1 x.2) (v + wd a) := by + have both := (h.par (Tagged.cap a)).pre (.assoc a a a) + simpa only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] using + (both.post (.swap _ _)).trace + +open Classical in +/-- One verifier on words suffices for a group of oriented transports. -/ +theorem check_turns {F J : Type} [Field F] [Fintype J] [DecidableEq J] {w u m : ℕ} + (o : J) (hu : 1 + w + Fintype.card J ≤ u) (ht : Radix.Tag F w u m) : + ∃ g : Records (Fin (2 ^ w)) J → F, Weight F g (m + 1000 * 2 ^ w * u) ∧ + ∀ x, Unambiguous x → g x = if Closed o x then 1 else 0 := by + let e : Fin (2 ^ w) ≃ (Fin w → Bool) := Fintype.equivOfCardEq (by simp) + let a := word u + let t := tree w a + let p : slots (word u) ≃ Pos J w u := Fintype.equivOfCardEq (by simp [Pos]; omega) + let encode (z : Key (2 ^ w) J) := (bits a).symm (code e z ∘ p) + have enc : Function.Injective encode := by + intro x y hh + apply code_injective (u := u) e + funext j + obtain ⟨i, rfl⟩ := p.surjective j + exact congrFun ((bits a).symm.injective hh) i + obtain ⟨L, hL⟩ := Layout.exists_tree a w + let get (x : Records (Fin (2 ^ w)) J) (b : Bool) (j : slots t) := + code e (key o x b (L.positions.symm j).1) (p (L.positions.symm j).2) + let prep (x : Records (Fin (2 ^ w)) J) : slots (.pair t t) → Bool := + Sum.elim (get x true) (get x false) + have hp : Depends prep 2 := by + rintro (j | j) + · exact code_depends o e true _ _ + · exact code_depends o e false _ _ + let rows (x : Records (Fin (2 ^ w)) J) (b : Bool) := (bits t).symm (get x b) + have hr (x) (b) : flatten w (rows x b) = (List.ofFn (key o x b)).map encode := by + rw [← hL, List.map_ofFn] + apply congrArg List.ofFn + funext i + simp [Layout.read, rows, get, encode, Function.comp_def, t] + obtain ⟨k, v, hk, hv, check⟩ := blind ht + let test (x : slots (.pair t t) → Bool) := + k ((bits (.pair t t)).symm x).1 ((bits (.pair t t)).symm x).2 + have test_net : Weight F test (v + wd t) := by + apply Weight.of_layout (a := .pair t t) (Equiv.refl _) + refine ⟨_, le_rfl, ?_⟩ + simpa [test, Function.comp_def] using uncurry hk + refine ⟨test ∘ prep, ((hp.bnet F).weight test_net).mono ?_, fun x hx => ?_⟩ + · simp only [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, card_slots, + t, a, wd_word, wd_tree, localCost] + have := Nat.mul_le_mul_left (2 ^ w) hu + ring_nf at this hv ⊢ + omega + · change k (rows x true) (rows x false) = _ + have hn : (flatten w (rows x true)).Nodup := by + rw [hr] + exact (List.nodup_ofFn.mpr (key_injective o x hx)).map enc + simp only [check _ _ hn, Tagged.permuted, hr, + List.map_perm_map_iff enc, key_perm o x hx] + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/SumOut.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/SumOut.lean new file mode 100644 index 0000000000..d4a37a9f5a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/SumOut.lean @@ -0,0 +1,598 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Combinatorics.Pigeonhole +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import Mathlib.Data.Fintype.Option +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Close +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Named +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet +public import Mathlib.Data.Nat.Log +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics + +/-! # Packing whole fibres into bins of twice the average capacity -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install +open Finset + +theorem exists_bins {α β : Type} [Fintype α] [DecidableEq β] (group : α → β) (u v : ℕ) + (hs : ∀ y, (Finset.univ.filter (fun x => group x = y)).card ≤ u) + (hu : 0 < u) (hc : Fintype.card α ≤ v * u) : + ∃ e : α ↪ Fin v × Fin (2 * u), ∀ x y, group x = group y → (e x).1 = (e y).1 := by + classical + by_cases hv : v = 0 + · have : IsEmpty α := Fintype.card_eq_zero_iff.mp (by simpa [hv] using hc) + exact ⟨⟨isEmptyElim, fun x => isEmptyElim x⟩, fun x => isEmptyElim x⟩ + let _ : NeZero v := ⟨hv⟩ + let bin (p : β → Fin v) (s : Finset β) (j : Fin v) := + univ.filter (fun x => group x ∈ s ∧ p (group x) = j) + have assign (s : Finset β) : ∃ p, ∀ j, (bin p s j).card ≤ 2 * u := by + induction s using Finset.induction with + | empty => exact ⟨fun _ => 0, by simp [bin]⟩ + | insert y s hy ih => + obtain ⟨p, hp⟩ := ih + obtain ⟨i, hi⟩ := Fintype.exists_card_fiber_le_of_card_le_mul (f := p ∘ group) + (n := u) (by simpa using hc) + let q := Function.update p y i + refine ⟨q, fun j => ?_⟩ + by_cases he : i = j + · subst j + have sub : bin q (insert y s) i ⊆ + univ.filter (fun x => (p ∘ group) x = i) ∪ univ.filter (fun x => group x = y) := by + intro x hx + by_cases h : group x = y + · simp [h] + · have := (mem_filter.mp hx).2.2 + simp [q, h] at this + simp [this] + have hcard := Nat.add_le_add hi (hs y) + exact (card_le_card sub).trans ((card_union_le _ _).trans (by + simpa [two_mul] using hcard)) + · apply (card_le_card ?_).trans (hp j) + intro x hx + by_cases h : group x = y + · simp [bin, q, h, he] at hx + · simpa [bin, q, h] using hx + let s := univ.image group + obtain ⟨p, hp⟩ := assign s + have index (j : Fin v) : ∃ f : α → Fin (2 * u), Set.InjOn f (bin p s j) := by + obtain ⟨e⟩ : Nonempty (bin p s j ↪ Fin (2 * u)) := + Function.Embedding.nonempty_of_card_le (by simpa using hp j) + refine ⟨fun x => if h : x ∈ bin p s j then e ⟨x, h⟩ else ⟨0, by omega⟩, ?_⟩ + intro x hx y hy he + simp only [mem_coe] at hx hy + simp only [dite_eq_left hx, dite_eq_left hy] at he + exact congrArg Subtype.val (e.injective he) + choose f hf using index + have mem (x : α) : x ∈ bin p s (p (group x)) := by simp [bin, s] + let pack (x : α) := (p (group x), f (p (group x)) x) + have inj : Function.Injective pack := by + intro x y e + obtain ⟨h₁, h₂⟩ := Prod.mk.inj e + rw [h₁] at h₂ + exact hf _ (h₁ ▸ mem x) (mem y) h₂ + exact ⟨⟨pack, inj⟩, fun _ _ h => congrArg p h⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- # Pushing a weighted network through deterministic postprocessing -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +theorem push {F I J : Type} [Field F] [Finite J] {a b : Wire} + {f : Val a → Val b → F} {m n : ℕ} (hf : Net F a b f m) (i : I ≃ slots b) + {g : (I → Bool) → (J → Bool)} (hg : BNet F g n) + (valid : (J → Bool) → Prop) (orig : (I → Bool) → F) (result : (J → Bool) → F) + (h : ∀ x y, f x y ≠ 0 → let z := bits b y ∘ i + valid (g z) ∧ result (g z) = orig z) : + ∃ v ≤ m + n, ∃ (c : Wire) (j : J ≃ slots c) (k : Val a → Val c → F), + Net F a c k v ∧ (∀ x y, k x y ≠ 0 → valid (bits c y ∘ j)) ∧ + ∀ x, (∑ y, f x y * orig (bits b y ∘ i)) = ∑ y, k x y * result (bits c y ∘ j) := by + let : Fintype J := Fintype.ofFinite J + let c := word (Fintype.card J) + let _ : DecidableEq (Val c) := valDecidableEq c + let j : J ≃ slots (word (Fintype.card J)) := Fintype.equivOfCardEq (by simp) + let emit (y : Val b) := (bits c).symm (g (bits b y ∘ i) ∘ j.symm) + have eqn (y) : bits c (emit y) ∘ j = g (bits b y ∘ i) := by + simp [emit, Function.comp_def] + obtain ⟨u, hu, emit_net⟩ := hg b c i j + refine ⟨m + u, Nat.add_le_add_left hu m, c, j, _, hf.comp emit_net, ?_, ?_⟩ + · intro x z hz + by_contra hn + apply hz + apply Finset.sum_eq_zero + intro y _ + change f x y * (@ite F (emit y = z) (valDecidableEq c _ _) 1 0) = 0 + by_cases hy : f x y = 0 + · simp [hy] + · have ne : emit y ≠ z := by + rintro rfl + exact hn (by rw [eqn]; exact (h x y hy).1) + simp [ne] + · intro x + simp only [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro y _ + simp only [mul_ite, mul_one, mul_zero, ite_mul, zero_mul, Finset.sum_ite_eq, + Finset.mem_univ, ite_true] + change _ = f x y * result (bits c (emit y) ∘ j) + by_cases hy : f x y = 0 + · simp [hy] + · rw [eqn, (h x y hy).2] + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +/- # Summing a weight over hidden indices -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Install.Weight + +variable {F I J : Type} [Field F] [Fintype I] [Fintype J] + +open Classical in +private theorem free (a : Wire) : Net F .unit a (fun _ _ => 1) (wd a) := by + induction a with + | unit => exact Net.empty + | bit => exact Net.table _ _ _ (by decide) + | pair a b ha hb => + simpa only [one_mul, wd] using (ha.par hb).pre (.unit' _) + +open Classical in +private theorem sum_aux (b : Wire) (j : J ≃ slots b) {f : (I ⊕ J → Bool) → F} {m : ℕ} (h : Weight F + f m) : + Weight F (fun x => ∑ y : J → Bool, f (Sum.elim x y)) (Fintype.card I + Fintype.card J + m) := by + intro a i + obtain ⟨n, hn, k⟩ := h (.pair a b) (i.sumCongr j) + obtain ⟨u, hu, id⟩ := DNet.id F a + have G := ((id.par (free b)).pre (.unit' _)).comp k + refine ⟨u + wd b + n, ?_, ?_⟩ + · simpa [Fintype.card_congr i, Fintype.card_congr j] + using Nat.add_le_add (Nat.add_le_add_right hu (wd b)) hn + have he (x : Val a) (y : Val b) : bits (.pair a b) (x, y) ∘ (i.sumCongr j) = + Sum.elim (bits a x ∘ i) (bits b y ∘ j) := by funext z; cases z <;> rfl + convert G using 1 + funext x _ + change (∑ y : J → Bool, f (Sum.elim (bits a x ∘ i) y)) = ∑ p : Val a × Val b, + ((if x = p.1 then 1 else 0) * 1) * f (bits (.pair a b) p ∘ (i.sumCongr j)) + rw [Fintype.sum_prod_type, Finset.sum_comm] + simp only [mul_one, ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, he] + let e := (bits b).trans (j.symm.arrowCongr (Equiv.refl Bool)) + exact (e.sum_comp (fun y => f (Sum.elim (bits a x ∘ i) y))).symm + +open Classical in +theorem sum_out {f : (I ⊕ J → Bool) → F} {m : ℕ} (h : Weight F f m) : + Weight F (fun x => ∑ y : J → Bool, f (Sum.elim x y)) (Fintype.card I + Fintype.card J + m) := + sum_aux (word (Fintype.card J)) (Fintype.equivOfCardEq (by simp)) h + +end MatrixMultiplicationAllFields.MatrixExponent.Install.Weight +end + +section +/- # Running a finite family of circuits on shared input bits -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install.BNet + +theorem finite_share {F I J C : Type} [Field F] [Fintype I] [Finite J] [Fintype C] + {m : ℕ} (f : C → (I → Bool) → J → Bool) (h : ∀ c, BNet F (f c) m) : + BNet F (fun x (p : C × J) => f p.1 x p.2) + (Fintype.card I + Fintype.card C * (5 * Fintype.card I + m)) := by + classical + let : Fintype J := Fintype.ofFinite J + refine Fintype.induction_empty_option + (P := fun T => ∀ f : T → (I → Bool) → J → Bool, (∀ c, BNet F (f c) m) → + BNet F (fun x (p : T × J) => f p.1 x p.2) + (Fintype.card I + Fintype.card T * (5 * Fintype.card I + m))) + ?_ ?_ ?_ C f h + · intro A B _ e ih g hg + let := Fintype.ofEquiv B e.symm + have h' := (ih (g ∘ e) (fun c => hg (e c))).rename (.refl I) (e.prodCongr (.refl J)) + rw [Fintype.card_congr e] at h' + convert h' using 1 + funext x ⟨b, j⟩ + simp + · intro g _ + have h' : Depends (fun x (p : PEmpty × J) => g p.1 x p.2) 0 := fun p => p.1.elim + simpa using h'.bnet F + · intro A _ ih g hg + have h' := (hg none).pair (ih (fun a => g (some a)) (fun a => hg (some a))) + convert h'.rename (.refl I) optionProdEquiv.symm using 1 + · funext x ⟨a, j⟩ + cases a <;> rfl + · rw [Fintype.card_option] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Install.BNet +end + +section +/- +# Assigning endpoint records to batches + +Compute a bucket mask for each batch and look up the mask bit at +each endpoint's source. The batch is active if the mask is nonempty. +The lookup works for repeated source identifiers. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {I J : Type} + +private def masked (x : Bus I J ⊕ I → Bool) : Records I J := + Sum.elim (fun i => x (.inl (.inl i)) && x (.inr i)) (fun z => x (.inl (.inr z))) + +private theorem masked_local : Depends (masked (I := I) (J := J)) 2 := by + classical + rintro (i | z) + · refine ⟨{.inl (.inl i), .inr i}, by simp, fun x y he => ?_⟩ + exact congrArg₂ Bool.and (he _ (by simp)) (he _ (by simp)) + · exact ⟨{.inl (.inr z)}, by simp, fun _ _ he => he _ (by simp)⟩ + +variable (F : Type) [Field F] {w r : ℕ} (ids : slots (word w) → Fin r) + +private abbrev Port (w r : ℕ) := Bus (Idx w) (Fin r) + +private def oneBatch (q j : ℕ) (x : Port w r → Bool) : Unit ⊕ Port w r → Bool := + Sum.elim (fun _ => decide (∃ i, bucket q j (x ∘ Sum.inl) i = true)) + (select (fun v => Control.decode w (v ∘ ids)) q j x) + +private theorem oneBatch_net (q j : ℕ) : + BNet F (oneBatch ids q j) (100000 * 2 ^ w * ((1 + w) ^ 4 + r)) := by + have hb := Control.bucket_bnet F w q j + have test := (hb.pull (Sum.inl : Idx w → Port w r)).comp (BNet.any F (Idx w)) + have both := hb.parallel (BNet.id F (Idx w × Fin r)) + have get := (Control.read_net F w).pull (Sum.map id (Prod.map id ids)) + have mask := (BNet.id F (Port w r)).pair (both.comp get) + have mark := (masked_local (I := Idx w) (J := Fin r)).bnet F + have all := test.pair (mask.comp mark) + convert all.mono (n := 100000 * 2 ^ w * ((1 + w) ^ 4 + r)) (by + simp only [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, card_slots, wd_word, + localCost] + have hp := Nat.one_le_pow w 2 (by decide) + ring_nf + omega) using 1 + funext x z + cases z with + | inl b => + rw [Bool.eq_iff_iff] + simp only [oneBatch, Sum.elim_inl, Function.comp_apply, decide_eq_true_eq] + rfl + | inr z => cases z <;> rfl + +private theorem batches_net (q t : ℕ) : + BNet F (batches (fun v => Control.decode w (v ∘ ids)) q t) + (10000000 * 2 ^ t * 2 ^ w * ((1 + w) ^ 4 + r)) := by + have k := BNet.share t (fun j => oneBatch ids q j.val) (fun j => oneBatch_net F ids q j.val) + let layout : Idx t × (Unit ⊕ Port w r) ≃ Bus (Idx t) (Port w r) := + (Equiv.prodSumDistrib _ _ _).trans ((Equiv.prodUnique _ Unit).sumCongr (.refl _)) + have h := k.rename (.refl _) layout + convert h.mono (n := 10000000 * 2 ^ t * 2 ^ w * ((1 + w) ^ 4 + r)) (by + simp only [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + ring_nf + omega) using 1 + funext x z + cases z <;> rfl + +theorem Plan.distribute_net (p : Plan) (F : Type) [Field F] : + BNet F p.distribute (10000000 * 2 ^ (p.g + p.t) * 2 ^ p.width * ((1 + p.width) ^ 4 + + p.layer.r)) := by + have k := BNet.family p.g (fun _ => batches p.idOf p.q p.t) + (fun _ => batches_net F p.ids p.q p.t) + apply (k.rename (.refl _) p.layout).mono + rw [pow_add] + exact le_of_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Grouped transports before batching + +The count and width of candidate groups may depend on the fixed +height ratio. The total width actually used must have a uniform bound. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +/-- The data for the grid construction, including `g`, `b`, `r`, `orientation`, `ids`. -/ +structure Grid where + /-- The `Grid` field of type `ℕ`. -/ + g : ℕ + /-- The right component. -/ + b : ℕ + /-- The `Grid` field of type `ℕ`. -/ + r : ℕ + /-- The `Grid` component of type `Fin r`. -/ + orientation : Fin r + /-- The `Grid` component of type `slots (word b) → Fin r`. -/ + ids : slots (word b) → Fin r + disjoint : ∀ i, ids i ≠ orientation + +namespace Grid + +variable (p : Grid) + +/-- Indexes the ports by the coordinates of `Idx p.g × Bus (Idx p.b) (Fin p.r)`. -/ +abbrev Ports := Idx p.g × Bus (Idx p.b) (Fin p.r) + +/-- The value specified by `x (i, j)`. -/ +def block (x : p.Ports → Bool) (i : Idx p.g) (j : Bus (Idx p.b) (Fin p.r)) : Bool := x (i, j) + +/-- The value specified by `Control.decode p.b (v ∘ p.ids)`. -/ +noncomputable def idOf (v : Fin p.r → Bool) : Idx p.b := + Control.decode p.b (v ∘ p.ids) + +/-- Requires `(∀ i, Aligned p.orientation p.idOf (p.block x i)) ∧ (∑ i, (marked (p.block x +i)).card) ≤ n`. -/ +def Valid (n : ℕ) (x : p.Ports → Bool) : Prop := + (∀ i, Aligned p.orientation p.idOf (p.block x i)) ∧ + (∑ i, (marked (p.block x i)).card) ≤ n + +open Classical in +/-- Returns `1` when `∀ i, Closed p.orientation (p.block x i)` holds, and `0` otherwise. -/ +noncomputable def close (F : Type) [Field F] (x : p.Ports → Bool) : F := + if ∀ i, Closed p.orientation (p.block x i) then 1 else 0 + +/-- The open of type `Prop` for the given inputs. -/ +def Open (F : Type) [Field F] (h v m n : ℕ) : Prop := + ∃ (b : Wire) (e : p.Ports ≃ slots b) (f : Val (Tagged.inputs h (word v)) → Val b → F), + Net F (Tagged.inputs h (word v)) b f m ∧ + (∀ x y, f x y ≠ 0 → p.Valid n (bits b y ∘ e)) ∧ + ∀ x, Tagged.tag F h (word v) x () = ∑ y, f x y * p.close F (bits b y ∘ e) + +end Grid + +/-- Uses `⟨p.g, p.width, p.layer.r, p.layer.orientation, p.ids, p.disjoint⟩` as the +representation. -/ +def Plan.grid (p : Plan) : Grid := + ⟨p.g, p.width, p.layer.r, p.layer.orientation, p.ids, p.disjoint⟩ + +/-- Configurable core transports in fixed groups, with endpoint +payloads padded to a common chunk length. -/ +def GroupProtocol (F : Type) [Field F] : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ τ : ℝ, 0 < τ → ∃ Y : ℝ, 0 < Y ∧ ∃ B J : ℕ, + ∀ A : ℕ, J ≤ A → ∀ ζ : ℝ, 0 < ζ → ∀ᶠ h : ℕ in Filter.atTop, + ∃ (p : Grid) (m n : ℕ), (p.b : ℝ) ≤ τ * h ∧ B + 18 ≤ p.b ∧ p.g + p.b ≤ h + B ∧ + Y * (h : ℝ) ^ A ≤ p.r ∧ 1 + p.b ≤ p.r ∧ p.r ≤ h ^ A ∧ + (n : ℝ) * p.r ≤ C * (2 : ℝ) ^ h * (h : ℝ) ^ A ∧ + (m : ℝ) ≤ (2 : ℝ) ^ h * (h : ℝ) ^ A * (h : ℝ) ^ ζ ∧ p.Open F h (h ^ A) m n + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Sizing the installation + +The slack in each group is one batch. Choosing its exponent below the +group height absorbs the excess candidate capacity. Rounding the total +installed width to a power of two costs a factor at most two. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +private theorem round_up (n : ℕ) (hn : 0 < n) : 2 ^ Nat.clog 2 n ≤ 2 * n := by + cases h : Nat.clog 2 n with + | zero => simp; omega + | succ k => + have hk : 2 ^ k < n := Nat.pow_lt_of_lt_clog (by omega) + rw [pow_succ] + omega + +private theorem reserve (g q B h n : ℕ) (hh : g + q ≤ h) (hn : n ≤ 2 ^ (g + (q + 18 + B))) : + ∃ o, 1 ≤ o ∧ o ≤ g + (B + 36) ∧ + (n + 2 ^ g * 2 ^ q) * 131072 ≤ 2 ^ o * 2 ^ q ∧ + 2 ^ o * 2 ^ (q + 18) * 2 ≤ 2 ^ 37 * (n + 2 ^ h) := by + let N := n + 2 ^ g * 2 ^ q + let a := Nat.clog 2 N + have hq : q ≤ a := by + have h : 2 ^ q ≤ N := by + apply le_trans _ (Nat.le_add_left ..) + exact Nat.le_mul_of_pos_left _ (Nat.two_pow_pos _) + simpa [a, Nat.clog_pow] using Nat.clog_mono_right 2 h + have ha : a ≤ g + (q + 18 + B) + 1 := by + apply Nat.clog_le_of_le_pow + have hl : 2 ^ (g + q) ≤ 2 ^ (g + (q + 18 + B)) := Nat.pow_le_pow_right (by decide) (by omega) + rw [pow_add] at hl + rw [pow_succ] + omega + let o := 17 + a - q + have he : 2 ^ o * 2 ^ q = 2 ^ 17 * 2 ^ a := by + rw [← pow_add, show o + q = 17 + a by omega, pow_add] + refine ⟨o, by omega, by omega, ?_, ?_⟩ + · rw [he, mul_comm] + exact Nat.mul_le_mul_left _ (Nat.le_pow_clog (by decide : 1 < 2) N) + · have hp : N ≤ n + 2 ^ h := by + unfold N + rw [← pow_add] + exact Nat.add_le_add_left (Nat.pow_le_pow_right (by decide) hh) _ + have hs := (round_up N (by unfold N; positivity)).trans (Nat.mul_le_mul_left 2 hp) + calc + 2 ^ o * 2 ^ (q + 18) * 2 = (2 ^ o * 2 ^ q) * 2 ^ 18 * 2 := by rw [pow_add]; ring + _ = 2 ^ 36 * 2 ^ a := by rw [he]; ring + _ ≤ 2 ^ 36 * (2 * (n + 2 ^ h)) := Nat.mul_le_mul_left _ hs + _ = _ := by ring + +theorem Grid.plan_exists (G : Grid) (h B n : ℕ) + (hb : B + 18 ≤ G.b) (hc : G.g + G.b ≤ h + B) (hr : 1 + G.b ≤ G.r) + (hn : n ≤ 2 ^ (G.g + G.b)) : + ∃ p : Plan, p.grid = G ∧ p.layer.l ≤ G.b ∧ G.r ≤ p.layer.u ∧ + p.layer.u ≤ 2 * G.r ∧ p.g + p.t ≤ G.g + B + 36 ∧ + (n + 2 ^ G.g * 2 ^ p.q) * 131072 ≤ 2 ^ p.layer.o * 2 ^ p.q ∧ + 2 ^ p.layer.o * 2 ^ p.layer.l * p.layer.u ≤ 2 ^ 37 * (n + 2 ^ h) * G.r := by + obtain ⟨g, b, r, orientation, ids, disjoint⟩ := G + change B + 18 ≤ b at hb + change g + b ≤ h + B at hc + change 1 + b ≤ r at hr + obtain ⟨q, hq⟩ : ∃ q, b = q + 18 + B := ⟨b - B - 18, by omega⟩ + subst b + obtain ⟨o, ho, ht, hcap, hcost⟩ := reserve g q B h n (by omega) hn + let l : Layer := ⟨q + 18, 2 * r, o, g + (B + 36) - o, B, r, orientation, by omega, ho, by omega⟩ + have he : o + (g + (B + 36) - o) = g + (B + 36) := by omega + let f : Idx g × Idx (B + 36) ≃ Idx (o + (g + (B + 36) - o)) := + Fintype.equivOfCardEq (by simp only [Fintype.card_prod, Fintype.card_fin, he, pow_add]) + let p : Plan := ⟨l, g, B + 36, q, f, by change q + 18 + B ≤ B + 36 + q; omega, + le_rfl, ids, disjoint⟩ + refine ⟨p, rfl, Nat.le_add_right .., ?_, le_rfl, ?_, hcap, ?_⟩ + · change r ≤ 2 * r + omega + · exact (Nat.add_assoc g B 36).ge + · change 2 ^ o * 2 ^ (q + 18) * (2 * r) ≤ 2 ^ 37 * (n + 2 ^ h) * r + rw [← mul_assoc] + exact Nat.mul_le_mul_right r hcost + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- # Converting bounded groups into candidate batches -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {F : Type} [Field F] {h v m n : ℕ} + +theorem Grid.Open.trim {G : Grid} (ho : G.Open F h v m n) : + G.Open F h v m (min n (2 ^ (G.g + G.b))) := by + obtain ⟨b, e, f, hf, hx, he⟩ := ho + refine ⟨b, e, f, hf, fun x y hy => ?_, he⟩ + obtain ⟨ha, hb⟩ := hx x y hy + refine ⟨ha, le_min hb ?_⟩ + trans ∑ _ : Idx G.g, 2 ^ G.b + · exact Finset.sum_le_sum (fun _ _ => (Finset.card_le_card (Finset.subset_univ _)).trans_eq + (Finset.card_fin _)) + · simp [pow_add] + +theorem Plan.compile (p : Plan) (ho : p.grid.Open F h v m n) + (hc : (n + 2 ^ p.g * 2 ^ p.q) * 131072 ≤ 2 ^ p.layer.o * 2 ^ p.q) : + ∃ m' ≤ m + 10000000 * 2 ^ (p.g + p.t) * 2 ^ p.width * ((1 + p.width) ^ 4 + p.layer.r), + p.layer.Open F h v m' := by + obtain ⟨b, e, f, hf, hv, hs⟩ := ho + have hw (x y) (hne : f x y ≠ 0) : p.Valid (bits b y ∘ e) := by + obtain ⟨ha, hb⟩ := hv x y hne + exact ⟨ha, (Nat.mul_le_mul_right _ (Nat.add_le_add_right hb _)).trans hc⟩ + obtain ⟨t, ht, c, i, g, hg, hw, he⟩ := push hf e (p.distribute_net F) + p.layer.Valid (p.close F) (p.layer.close F) (fun x y hy => p.distributed F _ (hw x y hy)) + exact ⟨t, ht, c, i, g, hg, hw, fun x => (hs x).trans (he x)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Cost of distributing the transports + +The distribution cost can depend on the excess capacity `B`, which +is fixed before the height tends to infinity. The coefficient in the +bound on installed payload is independent of `B`. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +private theorem Plan.capacity (p : Plan) : p.layer.o + p.layer.c = p.g + p.t := by + have he := Fintype.card_congr p.partition + simp only [Fintype.card_prod, Fintype.card_fin, ← pow_add] at he + exact Nat.pow_right_injective (by decide : 2 ≤ 2) he.symm + +private theorem Plan.expense (p : Plan) {h B A : ℕ} (hh : B + 36 ≤ h) (ha : 4 ≤ A) + (hg : p.g + p.width ≤ h + B) (ht : p.g + p.t ≤ p.g + B + 36) + (hu : p.layer.u ≤ 2 * p.layer.r) (hr : p.layer.r ≤ h ^ A) : + 10000000 * 2 ^ (p.g + p.t) * 2 ^ p.width * ((1 + p.width) ^ 4 + p.layer.r) + p.layer.work ≤ + 1000000000 * 2 ^ (2 * B + 36) * 2 ^ h * h ^ A := by + have scale : 2 ^ (p.g + p.t) * 2 ^ p.width ≤ 2 ^ (2 * B + 36) * 2 ^ h := by + rw [← pow_add, ← pow_add] + exact Nat.pow_le_pow_right (by decide) (by omega) + have big : h ≤ h ^ A := Nat.le_pow (by omega) + have fourth : (1 + p.width) ^ 4 ≤ 81 * h ^ A := calc + (1 + p.width) ^ 4 ≤ (3 * h) ^ 4 := Nat.pow_le_pow_left (by omega) _ + _ = 81 * h ^ 4 := by ring + _ ≤ 81 * h ^ A := Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) ha) + have overhead : (1 + p.width) ^ 4 + p.layer.r ≤ 82 * h ^ A := by omega + have inner : 1 + p.layer.o + p.layer.c + 2 ^ p.width * (1 + p.width + p.layer.u) ≤ + 2 ^ p.width * (10 * h ^ A) := by + have cap := p.capacity + calc + _ ≤ 2 ^ p.width * (1 + p.layer.o + p.layer.c) + 2 ^ p.width * (1 + p.width + p.layer.u) := + Nat.add_le_add_right (Nat.le_mul_of_pos_left _ (Nat.two_pow_pos _)) _ + _ ≤ _ := by rw [← mul_add]; exact Nat.mul_le_mul_left _ (by omega) + have hw : p.layer.work ≤ 2 ^ (p.g + p.t) * 2 ^ p.width * (10 * h ^ A) := by + unfold Layer.work + rw [p.capacity, Nat.add_assoc 1 p.layer.l, mul_assoc] + exact Nat.mul_le_mul_left _ inner + calc + _ ≤ 10000000 * 2 ^ (p.g + p.t) * 2 ^ p.width * (82 * h ^ A) + 2 ^ (p.g + + p.t) * 2 ^ p.width * (10 * h ^ A) := + Nat.add_le_add (Nat.mul_le_mul_left _ overhead) hw + _ = 820000010 * (2 ^ (p.g + p.t) * 2 ^ p.width) * h ^ A := by ring + _ ≤ 1000000000 * (2 ^ (2 * B + 36) * 2 ^ h) * h ^ A := + Nat.mul_le_mul_right _ (Nat.mul_le_mul (by decide) scale) + _ = _ := by ring + +private theorem Plan.installed (p : Plan) {n h A : ℕ} {C : ℝ} + (hr : p.layer.r ≤ h ^ A) + (hn : (n : ℝ) * p.layer.r ≤ C * (2 : ℝ) ^ h * (h : ℝ) ^ A) + (hc : 2 ^ p.layer.o * 2 ^ p.layer.l * p.layer.u ≤ 2 ^ 37 * (n + 2 ^ h) * p.layer.r) : + (2 : ℝ) ^ p.layer.o * (2 : ℝ) ^ p.layer.l * p.layer.u ≤ (2 ^ 37 * (C + + 1)) * (2 : ℝ) ^ h * (h : ℝ) ^ A := by + have hv : (p.layer.r : ℝ) ≤ (h : ℝ) ^ A := by exact_mod_cast hr + calc + _ ≤ (2 : ℝ) ^ 37 * (n + (2 : ℝ) ^ h) * p.layer.r := by exact_mod_cast hc + _ = (2 : ℝ) ^ 37 * (n * p.layer.r + (2 : ℝ) ^ h * p.layer.r) := by ring + _ ≤ (2 : ℝ) ^ 37 * (C * (2 : ℝ) ^ h * (h : ℝ) ^ A + (2 : ℝ) ^ h * (h : ℝ) ^ A) := by gcongr + _ = _ := by ring + +private theorem absorb {s h A m D : ℕ} {ζ : ℝ} (hh : 0 < h) + (hm : (m : ℝ) ≤ (2 : ℝ) ^ h * (h : ℝ) ^ A * (h : ℝ) ^ (ζ / 2)) + (hD : (↑(D + 2) : ℝ) ≤ (h : ℝ) ^ (ζ / 2)) (hcost : s ≤ m + D * 2 ^ h * h ^ A) : + (s : ℝ) ≤ (2 : ℝ) ^ h * (h : ℝ) ^ A * (h : ℝ) ^ ζ := by + have hd : (D : ℝ) + 2 ≤ (h : ℝ) ^ (ζ / 2) := by simpa using hD + have hsquared : (h : ℝ) ^ (ζ / 2) + D ≤ (h : ℝ) ^ ζ := by + have he : (h : ℝ) ^ ζ = (h : ℝ) ^ (ζ / 2) * (h : ℝ) ^ (ζ / 2) := by + rw [← Real.rpow_add (by exact_mod_cast hh), add_halves] + rw [he] + nlinarith [Nat.cast_nonneg (α := ℝ) D] + calc + (s : ℝ) ≤ m + (D : ℝ) * (2 : ℝ) ^ h * (h : ℝ) ^ A := by exact_mod_cast hcost + _ ≤ (2 : ℝ) ^ h * (h : ℝ) ^ A * ((h : ℝ) ^ (ζ / 2) + D) := by linarith only [hm] + _ ≤ _ := mul_le_mul_of_nonneg_left hsquared (by positivity) + +theorem open_of_groups {F : Type} [Field F] (hg : GroupProtocol F) : OpenProtocol F := by + obtain ⟨C, hC, H⟩ := hg + refine ⟨2 ^ 37 * (C + 1), by linarith, fun τ hτ => ?_⟩ + obtain ⟨Y, hY, B, J, hJ⟩ := H τ hτ + refine ⟨Y, hY, J + 4, fun A hA ζ hζ => ?_⟩ + let D := 1000000000 * 2 ^ (2 * B + 36) + have grow := (tendsto_rpow_atTop (half_pos hζ)).comp tendsto_natCast_atTop_atTop + filter_upwards [hJ A (by omega) _ (half_pos hζ), grow.eventually_ge_atTop (D + 2 : ℕ), + Filter.eventually_ge_atTop (B + 36)] with h Hh hD hh + obtain ⟨G, m, n, hl, hb, hcap, hwidth, hr, hr', hn, hm, ho⟩ := Hh + obtain ⟨p, rfl, hle, hu, hu', hpt, hp, hv⟩ := + G.plan_exists h B (min n (2 ^ (G.g + G.b))) hb hcap hr (min_le_right ..) + obtain ⟨s, hs, hs'⟩ := p.compile ho.trim hp + refine ⟨p.layer, s, le_trans (by exact_mod_cast hle) hl, + hwidth.trans (by exact_mod_cast hu), ?_, ?_, hs'⟩ + · apply p.installed hr' hn + exact hv.trans (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ (Nat.add_le_add_right + (min_le_left ..) _))) + · have hcost : s + p.layer.work ≤ m + D * 2 ^ h * h ^ A := by + have he := p.expense hh (by omega : 4 ≤ A) hcap hpt hu' hr' + exact (Nat.add_le_add_right hs _).trans ((Nat.add_assoc ..).le.trans (Nat.add_le_add_left he + m)) + exact absorb (by omega) hm hD hcost + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/Weight.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/Weight.lean new file mode 100644 index 0000000000..20bb918a2d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Install/Weight.lean @@ -0,0 +1,404 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Dense +public import Mathlib.Logic.Equiv.Fin.Basic + +/-! +# Deterministic networks on finite sets of named bits + +The names prescribe a layout only. Changing that layout is a free +permutation of the exterior wires. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +/-- The condition `∀ i : J, ∃ S : Finset I, S.card ≤ R ∧ ∀ x y, (∀ j ∈ S, x j = y j) → f x i = f +y i` on the specified data. -/ +def Depends {I J : Type} (f : (I → Bool) → (J → Bool)) (R : ℕ) : Prop := + ∀ i : J, ∃ S : Finset I, S.card ≤ R ∧ ∀ x y, (∀ j ∈ S, x j = y j) → f x i = f y i + +/-- The condition `∀ (a b : Wire) (i : I ≃ slots a) (j : J ≃ slots b), DNet F a b (fun x => +(bits b).symm (f (bits a x ∘ i) ∘ j.symm)) m` on the specified data. -/ +def BNet (F : Type) [Field F] {I J : Type} (f : (I → Bool) → (J → Bool)) (m : ℕ) : Prop := + ∀ (a b : Wire) (i : I ≃ slots a) (j : J ≃ slots b), + DNet F a b (fun x => (bits b).symm (f (bits a x ∘ i) ∘ j.symm)) m + +namespace BNet + +variable {F I J K : Type} [Field F] {f : (I → Bool) → (J → Bool)} {m n : ℕ} + +theorem mono (h : BNet F f m) (le : m ≤ n) : BNet F f n := + fun a b i j => (h a b i j).mono le + +private noncomputable def names (I : Type) [Fintype I] : I ≃ slots (word (Fintype.card I)) := + Fintype.equivOfCardEq (by simp) + +theorem comp [Finite J] {g : (J → Bool) → (K → Bool)} (h : BNet F f m) (k : BNet F g n) : + BNet F (g ∘ f) (m + n) := by + let : Fintype J := Fintype.ofFinite J + intro a c i l + let b := word (Fintype.card J) + let j : J ≃ slots b := names J + simpa only [Function.comp_def, Equiv.apply_symm_apply, Equiv.symm_apply_apply] using + (h a b i j).comp (k b c j l) + +theorem of_layout {a b : Wire} (i : I ≃ slots a) (j : J ≃ slots b) + (h : DNet F a b (fun x => (bits b).symm (f (bits a x ∘ i) ∘ j.symm)) m) : + BNet F f m := by + intro c d k l + have hp := (h.pre (rewire_reindex (i.symm.trans k))).post (rewire_reindex (l.symm.trans j)) + simpa [reindex, Function.comp_def] using hp + +theorem parallel [Finite I] [Finite J] [Finite K] {L : Type} [Finite L] + {g : (K → Bool) → (L → Bool)} (h : BNet F f m) (k : BNet F g n) : + BNet F (fun x => Sum.elim (f (x ∘ Sum.inl)) (g (x ∘ Sum.inr))) (m + n) := by + let : Fintype I := Fintype.ofFinite I + let : Fintype J := Fintype.ofFinite J + let : Fintype K := Fintype.ofFinite K + let : Fintype L := Fintype.ofFinite L + let a := word (Fintype.card I) + let b := word (Fintype.card J) + let c := word (Fintype.card K) + let d := word (Fintype.card L) + apply of_layout (a := .pair a c) (b := .pair b d) + ((names I).sumCongr (names K)) ((names J).sumCongr (names L)) + exact (h a b (names I) (names J)).par (k c d (names K) (names L)) + +theorem id (F I : Type) [Field F] [Fintype I] : + BNet F (_root_.id : (I → Bool) → _) (Fintype.card I) := by + intro a b i j + rw [Fintype.card_congr i, card_slots] + exact (DNet.id F a).post (rewire_reindex (j.symm.trans i)) + +end BNet +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Bounded dependence gives a linear circuit + +First copy and permute the needed wires. Each output bit can then be +computed independently on its own bounded input bundle. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +variable {F : Type} [Field F] {a b c : Wire} + +/-- The value specified by `(bits b).symm (bits a x ∘ f)`. -/ +def project (f : slots b → slots a) (x : Val a) : Val b := + (bits b).symm (bits a x ∘ f) + +@[simp] theorem bits_project (f : slots b → slots a) (x : Val a) (i : slots b) : + bits b (project f x) i = bits a x (f i) := + congrFun ((bits b).apply_symm_apply _) i + +private theorem split {U V : Type} (b : Wire) (f : slots b → U ⊕ V) : + ∃ (l r : Wire) (e : slots b ≃ slots l ⊕ slots r) + (u : slots l → U) (v : slots r → V), ∀ j, f j = Sum.map u v (e j) := by + induction b with + | unit => exact ⟨.unit, .unit, (Equiv.sumEmpty Empty Empty).symm, + Empty.elim, Empty.elim, fun j => j.elim⟩ + | bit => + rcases h : f () with x | y + · exact ⟨.bit, .unit, (Equiv.sumEmpty Unit Empty).symm, + fun _ => x, Empty.elim, fun _ => h⟩ + · exact ⟨.unit, .bit, (Equiv.emptySum Empty Unit).symm, + Empty.elim, fun _ => y, fun _ => h⟩ + | pair a b ha hb => + obtain ⟨l, r, e, u, v, h⟩ := ha (f ∘ Sum.inl) + obtain ⟨l', r', e', u', v', h'⟩ := hb (f ∘ Sum.inr) + refine ⟨.pair l l', .pair r r', (e.sumCongr e').trans (Equiv.sumSumSumComm _ _ _ _), + Sum.elim u u', Sum.elim v v', ?_⟩ + rintro (j | j) + · specialize h j + cases he : e j <;> simp_all + · specialize h' j + cases he : e' j <;> simp_all + +private theorem broadcast (F : Type) [Field F] (n : ℕ) : + DNet F .bit (word n) (fun x => (bits (word n)).symm (fun _ => x)) (1 + 2 * n) := by + induction n with + | zero => exact DNet.discard F .bit + | succ n ih => + exact ((DNet.id F .bit).pair ih).mono (by simp [wd]; omega) + +theorem project_net (F : Type) [Field F] (f : slots b → slots a) : + DNet F a b (project f) (wd a + 2 * wd b) := by + induction a generalizing b with + | unit => + let e : slots b ≃ slots .unit := + ⟨f, Empty.elim, fun i => (f i).elim, fun i => i.elim⟩ + exact ((DNet.id F .unit).post (rewire_reindex e)).mono (Nat.zero_le _) + | bit => + let e : slots b ≃ slots (word (wd b)) := Fintype.equivOfCardEq (by simp) + have h := (broadcast F (wd b)).post (rewire_reindex e) + convert h using 1 <;> try rfl + funext x + apply (bits b).injective + funext j + simp [bits_project, bits_reindex] + rfl + | pair a c ha hc => + obtain ⟨l, r, e, u, v, h⟩ := split b f + have hp := ((ha u).par (hc v)).post (rewire_reindex (a := .pair l r) e) + have hw : wd b = wd l + wd r := by simpa using Fintype.card_congr e + convert hp.mono (n := wd (.pair a c) + 2 * wd b) (by simp [wd, hw]; omega) using 1 + funext x + apply (bits b).injective + funext j + simp only [bits_project, bits_reindex, h j] + cases e j with + | inl i => exact (bits_project u x.1 i).symm + | inr i => exact (bits_project v x.2 i).symm + +private theorem assemble {I : Type} (F : Type) [Field F] (R : ℕ) + (b : Wire) (f : (I → Bool) → slots b → Bool) (h : Depends f R) : + ∃ (u : Wire) (p : slots u → I) (g : Val u → Val b), + wd u ≤ R * wd b ∧ DNet F u b g (8 * 2 ^ (R + 1) * wd b) ∧ + ∀ x, bits b (g ((bits u).symm (x ∘ p))) = f x := by + classical + induction b with + | unit => + refine ⟨.unit, Empty.elim, id, ?_, ?_, fun x => funext fun j => j.elim⟩ + · exact Nat.zero_le _ + · exact (DNet.id F .unit).mono (Nat.zero_le _) + | bit => + obtain ⟨S, hs, he⟩ := h () + let u := word S.card + let e : slots u ≃ S := @Fintype.equivOfCardEq (slots u) S (slotsFintype u) _ + ((card_slots u).trans ((wd_word _).trans (Fintype.card_coe S).symm)) + let g (v : Val u) := f (fun i => if hi : i ∈ S then bits u v (e.symm ⟨i, hi⟩) else false) () + refine ⟨u, fun j => ↑(e j), g, by simpa [wd, u], ?_, ?_⟩ + · obtain ⟨v, hv, hm⟩ := Net.dense u .bit (fun x y => if g x = y then (1 : F) else 0) + refine ⟨v, hm.trans ?_, hv⟩ + simp only [u, wd_word, wd, mul_one] + gcongr + · intro x + funext j + apply he + intro i hi + simp [hi] + | pair b c hb hc => + obtain ⟨u, p, g, hu, hg, he⟩ := hb (fun x i => f x (.inl i)) (fun i => h (.inl i)) + obtain ⟨v, r, l, hv, hl, hd⟩ := hc (fun x i => f x (.inr i)) (fun i => h (.inr i)) + refine ⟨.pair u v, Sum.elim p r, _, ?_, (hg.par hl).mono ?_, ?_⟩ + · simpa only [wd, mul_add] using Nat.add_le_add hu hv + · simp [wd, mul_add] + · intro x + funext j + rcases j with j | j + · exact congrFun (he x) j + · exact congrFun (hd x) j + +/-- The quantity computed by `2 * R + 8 * 2 ^ (R + 1)`. -/ +def localCost (R : ℕ) := 2 * R + 8 * 2 ^ (R + 1) + +theorem Depends.bnet {I J : Type} [Fintype I] [Fintype J] {R : ℕ} + {f : (I → Bool) → J → Bool} (h : Depends f R) (F : Type) [Field F] : + BNet F f (Fintype.card I + localCost R * Fintype.card J) := by + intro a b i j + obtain ⟨u, p, g, hu, hg, he⟩ := assemble F R b (fun x => f x ∘ j.symm) (fun z => h (j.symm z)) + have hn := (project_net F (i ∘ p)).comp hg + have hcost : wd a + 2 * wd u + 8 * 2 ^ (R + 1) * wd b ≤ + Fintype.card I + localCost R * Fintype.card J := by + rw [Fintype.card_congr i, Fintype.card_congr j, card_slots, card_slots, + localCost, add_mul, mul_assoc 2 R] + omega + convert hn.mono hcost using 1 + funext x + apply (bits b).injective + rw [Equiv.apply_symm_apply] + exact (he (bits a x ∘ i)).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- # Parallel computation on named bundles -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install.BNet + +variable {F I J K L : Type} [Field F] {f : (I → Bool) → (J → Bool)} {m n : ℕ} + +theorem rename (h : BNet F f m) (e : I ≃ K) (d : J ≃ L) : + BNet F (fun x => f (x ∘ e) ∘ d.symm) m := fun a b i j => h a b (e.trans i) (d.trans j) + +theorem pull [Fintype I] [Fintype K] (h : BNet F f m) (e : I → K) : + BNet F (fun x => f (x ∘ e)) (Fintype.card K + 2 * Fintype.card I + m) := by + have hp : BNet F (fun x => x ∘ e) (Fintype.card K + 2 * Fintype.card I) := by + intro a b i j + rw [Fintype.card_congr i, Fintype.card_congr j, card_slots, card_slots] + exact project_net F (i ∘ e ∘ j.symm) + exact hp.comp h + +theorem pair [Fintype I] [Finite J] [Finite K] {g : (I → Bool) → (K → Bool)} + (h : BNet F f m) (k : BNet F g n) : + BNet F (fun x => Sum.elim (f x) (g x)) (5 * Fintype.card I + m + n) := by + let : Fintype J := Fintype.ofFinite J + let : Fintype K := Fintype.ofFinite K + have t := (h.parallel k).pull (Sum.elim _root_.id _root_.id) + exact t.mono (by rw [Fintype.card_sum]; omega) + +theorem family [Finite I] [Finite J] (t : ℕ) + (f : Fin (2 ^ t) → (I → Bool) → (J → Bool)) (h : ∀ i, BNet F (f i) m) : + BNet F (fun (x : Fin (2 ^ t) × I → Bool) (p : Fin (2 ^ t) × J) => + f p.1 (fun j => x (p.1, j)) p.2) (2 ^ t * m) := by + let : Fintype I := Fintype.ofFinite I + let : Fintype J := Fintype.ofFinite J + induction t with + | zero => + have k := (h 0).rename (Equiv.uniqueProd I (Fin 1)).symm (Equiv.uniqueProd J (Fin 1)).symm + convert k using 1 + · funext x ⟨i, j⟩ + rw [Fin.eq_zero i] + rfl + · simp + | succ t ih => + generalize he : 2 ^ (t + 1) = r at * + rw [pow_succ, mul_two] at he + subst r + let e (M : Type) := (Equiv.sumProdDistrib (Fin (2 ^ t)) (Fin (2 ^ t)) M).symm.trans + (finSumFinEquiv.prodCongr (.refl M)) + have l := ih (fun i => f (Fin.castAdd _ i)) fun i => h _ + have r := ih (fun i => f (Fin.natAdd _ i)) fun i => h _ + rw [add_mul] + convert (l.parallel r).rename (e I) (e J) using 1 + funext x y + obtain ⟨⟨i, j⟩ | ⟨i, j⟩, rfl⟩ := (e J).surjective y <;> + simp only [Function.comp_apply, Equiv.symm_apply_apply] <;> rfl + +theorem share [Fintype I] [Finite J] (t : ℕ) + (f : Fin (2 ^ t) → (I → Bool) → (J → Bool)) (h : ∀ i, BNet F (f i) m) : + BNet F (fun x (p : Fin (2 ^ t) × J) => f p.1 x p.2) + (2 ^ t * (3 * Fintype.card I + m)) := by + let : Fintype J := Fintype.ofFinite J + apply ((family t f h).pull Prod.snd).mono + simp only [Fintype.card_prod, Fintype.card_fin] + nlinarith [Nat.mul_le_mul_right (Fintype.card I) (Nat.one_le_pow t 2 (by decide))] + +private theorem any_word (F : Type) [Field F] (n : ℕ) : + DNet F (word n) .bit (fun x => decide (∃ j, bits (word n) x j = true)) (2 * n + 1) := by + induction n with + | zero => exact .table _ _ _ _ (by decide) + | succ n ih => + have gate := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 || x.2) (by decide) + convert ((DNet.id F .bit).par ih).comp gate using 1 + · funext x + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq, Bool.or_eq_true] + constructor + · rintro ⟨j | j, hj⟩ + · exact .inl hj + · exact .inr ⟨j, hj⟩ + · rintro (hj | ⟨j, hj⟩) + · exact ⟨.inl (), hj⟩ + · exact ⟨.inr j, hj⟩ + · simp [wd]; omega + +theorem any (F I : Type) [Field F] [Fintype I] : + BNet F (fun (x : I → Bool) (_ : Unit) => decide (∃ i, x i = true)) (2 * Fintype.card I + 1) + := by + let n := Fintype.card I + let i : I ≃ slots (word (Fintype.card I)) := Fintype.equivOfCardEq (by simp) + apply of_layout (a := word n) (b := .bit) i (.refl Unit) + convert any_word F n using 1 + funext x + change decide (∃ j, bits (word n) x (i j) = true) = _ + simp only [decide_eq_decide] + exact ⟨fun ⟨j, hj⟩ => ⟨_, hj⟩, fun ⟨j, hj⟩ => ⟨i.symm j, by simpa⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Install.BNet +end + +section +/- +# Scalar weights on named exterior bits + +Deterministic preprocessing selects exactly one assignment in a contraction. +Disjoint copies of a weight multiply, with no extra vertices. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +/-- The condition `∀ (a : Wire) (i : I ≃ slots a), ∃ v ≤ m, Net F a .unit (fun x _ => f (bits a +x ∘ i)) v` on the specified data. -/ +def Weight (F : Type) [Field F] {I : Type} (f : (I → Bool) → F) (m : ℕ) : Prop := + ∀ (a : Wire) (i : I ≃ slots a), ∃ v ≤ m, Net F a .unit (fun x _ => f (bits a x ∘ i)) v + +variable {F I J : Type} [Field F] {m n : ℕ} + +theorem BNet.weight [Finite J] {f : (I → Bool) → J → Bool} {g : (J → Bool) → F} + (h : BNet F f m) (k : Weight F g n) : Weight F (g ∘ f) (m + n) := by + let : Fintype J := Fintype.ofFinite J + intro a i + let b := word (Fintype.card J) + let j : J ≃ slots (word (Fintype.card J)) := Fintype.equivOfCardEq (by simp) + obtain ⟨v, hv, h⟩ := h a b i j + obtain ⟨w, hw, k⟩ := k b j + refine ⟨v + w, Nat.add_le_add hv hw, ?_⟩ + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, + Function.comp_def, Equiv.apply_symm_apply, Equiv.symm_apply_apply] using h.comp k + +namespace Weight + +variable {f : (I → Bool) → F} + +theorem mono (h : Weight F f m) (le : m ≤ n) : Weight F f n := by + intro a i + obtain ⟨v, hv, h⟩ := h a i + exact ⟨v, hv.trans le, h⟩ + +theorem of_layout {a : Wire} (i : I ≃ slots a) + (h : ∃ v ≤ m, Net F a .unit (fun x _ => f (bits a x ∘ i)) v) : Weight F f m := by + intro b j + obtain ⟨v, hv, h⟩ := h + refine ⟨v, hv, ?_⟩ + simpa [Function.comp_def] using h.pre (rewire_reindex (i.symm.trans j)) + +theorem rename (h : Weight F f m) (e : I ≃ J) : Weight F (fun x => f (x ∘ e)) m := + fun a i => h a (e.trans i) + +private theorem twice [Finite I] (h : Weight F f m) : + Weight F (fun x => f (x ∘ Sum.inl) * f (x ∘ Sum.inr)) (m + m) := by + let : Fintype I := Fintype.ofFinite I + let a := word (Fintype.card I) + let i : I ≃ slots (word (Fintype.card I)) := Fintype.equivOfCardEq (by simp) + obtain ⟨v, hv, h⟩ := h a i + apply of_layout (a := .pair a a) (i.sumCongr i) + exact ⟨v + v, Nat.add_le_add hv hv, (h.par h).post (.unit' _)⟩ + +theorem prod [Finite I] (h : Weight F f m) (w : ℕ) : + Weight F (fun x : Fin (2 ^ w) × I → Bool => ∏ i : Fin (2 ^ w), f (fun j => x (i, j))) + (2 ^ w * m) := by + let : Fintype I := Fintype.ofFinite I + induction w with + | zero => + rw [pow_zero, one_mul] + simpa [Function.comp_def] using h.rename (Equiv.uniqueProd I (Fin 1)).symm + | succ w ih => + rw [pow_succ, mul_two, add_mul] + let e := (Equiv.sumProdDistrib (Fin (2 ^ w)) (Fin (2 ^ w)) I).symm.trans + (finSumFinEquiv.prodCongr (.refl I)) + convert ih.twice.rename e using 1 + funext x + rw [Fin.prod_univ_add] + rfl + +end Weight +end MatrixMultiplicationAllFields.MatrixExponent.Install +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Interpolation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Interpolation.lean new file mode 100644 index 0000000000..a5f4c06274 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Interpolation.lean @@ -0,0 +1,96 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Nodes +public import Mathlib.LinearAlgebra.Matrix.NonsingularInverse + +/-! # Polynomial interpolation over algebraic integers -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +open Finset Polynomial Matrix + +open scoped Classical in +theorem unit_nodes (n : ℕ) : ∃ v : Fin n → O, + IsUnit (vandermonde v).det ∧ ∀ i, IsUnit (v i) := by + obtain ⟨x, hx, h⟩ := nodes n + exact ⟨_, h, fun i => hx.pow i.val⟩ + +open scoped Classical in +/-- Returns `(vandermonde v)⁻¹ ⟨d, h⟩ i` when `h : d < n` holds, and `0` otherwise. -/ +def weight {n : ℕ} (v : Fin n → O) (i : Fin n) (d : ℕ) := + if h : d < n then (vandermonde v)⁻¹ ⟨d, h⟩ i else 0 + +open scoped Classical in +theorem interpolate {n : ℕ} (v : Fin n → O) (h : IsUnit (vandermonde v).det) + (p : Polynomial O) (d : ℕ) (hd : p.degree < Fintype.card (Fin n)) : + p.coeff d = ∑ i, p.eval (v i) * weight v i d := by + rw [Fintype.card_fin] at hd + by_cases hd' : d < n + · by_cases hp : p = 0 + · simp [hp] + let a (i : Fin n) := p.coeff i.val + let b (i : Fin n) := p.eval (v i) + have he : (vandermonde v).mulVec a = b := by + funext i + unfold b + rw [eval_eq_sum_range' ((natDegree_lt_iff_degree_lt hp).mpr hd), ← Fin.sum_univ_eq_sum_range] + change (∑ j : Fin n, v i ^ j.val * a j) = ∑ j : Fin n, a j * v i ^ j.val + exact sum_congr rfl (fun j _ => mul_comm (v i ^ j.val) (a j)) + have hh : (vandermonde v)⁻¹.mulVec b = a := by + rw [← he, mulVec_mulVec, nonsing_inv_mul _ h, one_mulVec] + have heq := congrFun hh ⟨d, hd'⟩ + simpa only [a, b, weight, dite_eq_left hd', Matrix.mulVec, dotProduct, mul_comm] using heq.symm + · simp only [weight, dite_eq_right hd', mul_zero, sum_const_zero] + exact coeff_eq_zero_of_degree_lt (hd.trans_le (by exact_mod_cast Nat.le_of_not_gt hd')) + +open scoped Classical in +/-- These integer powers are used only on units, apart from +nonnegative exponents. -/ +scoped instance : Pow O ℤ := ⟨fun x i => if h : IsUnit x then ((h.unit ^ i : Oˣ) : O) else x ^ + i.toNat⟩ + +open scoped Classical in +theorem upow_add {x : O} (h : IsUnit x) (i j : ℤ) : x ^ (i + j) = x ^ i * x ^ j := by + change (if h : IsUnit x then ((h.unit ^ (i + j) : Oˣ) : O) else _) = + (if h : IsUnit x then ((h.unit ^ i : Oˣ) : O) else _) * (if h : IsUnit x then ((h.unit ^ j : + Oˣ) : O) else _) + simp only [dite_eq_left h, zpow_add, Units.val_mul] + +open scoped Classical in +theorem upow_nat (x : O) (i : ℕ) : x ^ (i : ℤ) = x ^ i := by + change (if h : IsUnit x then ↑(h.unit ^ (i : ℤ)) else x ^ _) = _ + split <;> simp + +open scoped Classical in +/-- Shift signed exponents into a range of length six times the +branch count. Interpolation extracts the central coefficient. -/ +theorem phases {M : ℕ} : + ∃ (ζ : O) (w : Fin (6 * M) → O), IsUnit ζ ∧ + ∀ e : ℤ, -(3 * (M : ℤ)) < e → e < 3 * (M : ℤ) → + (∑ r : Fin (6 * M), w r * ζ ^ ((r : ℤ) * e)) = if e = 0 then 1 else 0 := by + obtain ⟨ζ, hζ, h⟩ := nodes (6 * M) + let v := fun i : Fin (6 * M) => ζ ^ i.val + refine ⟨ζ, fun i => weight v i (3 * M) * ζ ^ ((i : ℤ) * (3 * M)), hζ, fun e hlo hhi => ?_⟩ + let n := (3 * (M : ℤ) + e).toNat + have hn : (n : ℤ) = 3 * M + e := by unfold n; omega + have hc := interpolate v h (X ^ n) (3 * M) (by + rw [degree_X_pow, Fintype.card_fin] + exact_mod_cast (show n < 6 * M by omega)) + rw [coeff_X_pow] at hc + simp only [eval_pow, eval_X] at hc + calc + _ = ∑ i, v i ^ n * weight v i (3 * M) := by + apply sum_congr rfl + intro i _ + rw [mul_assoc, ← upow_add hζ, ← mul_add, ← hn, ← Nat.cast_mul, upow_nat, pow_mul, mul_comm] + _ = _ := by rw [← hc]; congr 1; exact propext (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Model.lean new file mode 100644 index 0000000000..c4b590ec9e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Model.lean @@ -0,0 +1,65 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Model + +/-! Division-free circuits computing formal polynomial identities over a ring. -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral + +/-- Uses `Rectangle.Pos` as the representation. -/ +abbrev Pos := Rectangle.Pos +/-- Uses `Rectangle.Var` as the representation. -/ +abbrev Var := Rectangle.Var +/-- Computes the poly by the application `MvPolynomial (Var i j k) F`. -/ +abbrev Poly (F : Type*) [CommRing F] (i j k : ℕ) := MvPolynomial (Var i j k) F +/-- Uses `Rectangle.side` as the representation. -/ +abbrev side := Rectangle.side + +/-- Computes the input by the application `MvPolynomial.X x`. -/ +abbrev input (F : Type*) [CommRing F] {i j k : ℕ} (x : Var i j k) : Poly F i j k := + MvPolynomial.X x + +/-- The build used in the `Integral` construction. -/ +inductive Build {K : Type*} [CommRing K] (S : Set K) : ℕ → Set K → Prop + | nil : Build S 0 S + | add {m T x y} : Build S m T → x ∈ T → y ∈ T → Build S (m + 1) (insert (x + y) T) + | sub {m T x y} : Build S m T → x ∈ T → y ∈ T → Build S (m + 1) (insert (x - y) T) + | mul {m T x y} : Build S m T → x ∈ T → y ∈ T → Build S (m + 1) (insert (x * y) T) + +/-- The set of values attained by `(algebraMap F (Poly F i j k)) ∪ Set.range (input F)`. -/ +def initial (F : Type*) [CommRing F] (i j k : ℕ) : Set (Poly F i j k) := + Set.range (algebraMap F (Poly F i j k)) ∪ Set.range (input F) + +/-- The quantity computed by `∑ l : Fin k, input F (.inl (p.1, l)) * input F (.inr (l, p.2))`. -/ +def output (F : Type*) [CommRing F] {i j k : ℕ} (p : Pos i j) : Poly F i j k := + ∑ l : Fin k, input F (.inl (p.1, l)) * input F (.inr (l, p.2)) + +/-- The condition `∃ T, Build (initial F i j k) m T ∧ ∀ p : Pos i j, output F p ∈ T` on the +specified data. -/ +def Computes (F : Type*) [CommRing F] (i j k m : ℕ) : Prop := + ∃ T, Build (initial F i j k) m T ∧ ∀ p : Pos i j, output F p ∈ T + +/-- The defining condition `∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ n : ℕ, 0 < n → ∃ m : ℕ, Computes +F (side n a) (side n b) (side n c) m ∧ (m : ℝ) ≤ C * (n : ℝ) ^ (s + ε)`. -/ +def Admissible (F : Type*) [CommRing F] (a b c s : ℝ) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ n : ℕ, 0 < n → + ∃ m : ℕ, Computes F (side n a) (side n b) (side n c) m ∧ + (m : ℝ) ≤ C * (n : ℝ) ^ (s + ε) + +/-- The infimum of `{s | Admissible F a b c s}`. -/ +def exponent (F : Type*) [CommRing F] (a b c : ℝ) : ℝ := sInf {s | Admissible F a b c s} + +/-- Coefficient rank for rectangular matrix multiplication over a commutative ring. -/ +abbrev Rank (F : Type*) [CommRing F] (i j k r : ℕ) : Prop := + TensorSpectrum.MatrixRank F i j k r + +end MatrixMultiplicationAllFields.MatrixExponent.Integral diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Nodes.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Nodes.lean new file mode 100644 index 0000000000..7030888c1d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Nodes.lean @@ -0,0 +1,131 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Model +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure +public import Mathlib.RingTheory.IntegralClosure.IntegrallyClosed +public import Mathlib.LinearAlgebra.Vandermonde +public import Mathlib.Algebra.MvPolynomial.Eval + +/-! +# Integral nodes for arbitrarily long interpolation + +Adjoin a root of X ∏ (X^j − 1) − 1. Its first powers are +units with pairwise unit differences. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +open Finset Polynomial + +/-- The value specified by `↥(integralClosure ℤ (AlgebraicClosure ℚ))`. -/ +abbrev O := ↥(integralClosure ℤ (AlgebraicClosure ℚ)) + +private theorem root (p : Polynomial ℤ) (hp : p.Monic) (hd : 0 < p.degree) : + ∃ x : O, aeval x p = 1 := by + let K := AlgebraicClosure ℚ + have hdeg : (1 : Polynomial ℤ).degree < p.degree := by simpa using hd + have hmon := hp.sub_of_left hdeg + obtain ⟨z, hz⟩ := IsAlgClosed.exists_aeval_eq_zero K (p - 1) + (by rw [degree_sub_eq_left_of_degree_lt hdeg]; exact hd.ne') + let x : O := ⟨z, p - 1, hmon, hz⟩ + refine ⟨x, ?_⟩ + apply (FaithfulSMul.algebraMap_injective O K) + rw [← aeval_algebraMap_apply, map_one] + change aeval z p = 1 + simpa only [map_sub, map_one, sub_eq_zero] using hz + +private theorem exceptional (n : ℕ) : + ∃ x : O, IsUnit x ∧ ∀ j : ℕ, 0 < j → j ≤ n → IsUnit (x ^ j - 1) := by + let P : Polynomial ℤ := X * ∏ j ∈ Icc 1 n, (X ^ j - 1) + have hP : P.Monic := monic_X.mul (monic_prod_of_monic _ _ (by + intro j hj + exact (monic_X.pow j).sub_of_left (by + rw [degree_one, degree_X_pow] + exact_mod_cast (mem_Icc.mp hj).1))) + have hdeg : 0 < P.degree := degree_pos_of_root hP.ne_zero (show P.IsRoot 0 by simp [P, IsRoot]) + obtain ⟨a, ha⟩ := root P hP hdeg + simp only [P, map_mul, map_prod, map_sub, map_one, map_pow, aeval_X] at ha + refine ⟨a, isUnit_of_dvd_one ⟨_, ha.symm⟩, fun j hj hj' => ?_⟩ + apply isUnit_of_dvd_one + apply dvd_trans (dvd_prod_of_mem (fun i => a ^ i - 1) (mem_Icc.mpr ⟨hj, hj'⟩)) + exact ⟨a, by rw [mul_comm]; exact ha.symm⟩ + +theorem nodes (n : ℕ) : ∃ x : O, IsUnit x ∧ + IsUnit (Matrix.vandermonde (fun i : Fin n => x ^ i.val)).det := by + obtain ⟨x, hx, he⟩ := exceptional n + refine ⟨x, hx, ?_⟩ + rw [Matrix.det_vandermonde] + apply IsUnit.prod_iff.mpr + intro i _ + apply IsUnit.prod_iff.mpr + intro j hj + have hij : i < j := mem_Ioi.mp hj + rw [show x ^ j.val - x ^ i.val = x ^ i.val * (x ^ (j.val - i.val) - 1) by + rw [mul_sub, mul_one, ← pow_add, Nat.add_sub_of_le hij.le]] + exact (hx.pow _).mul (he _ (by omega) (by omega)) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral +end + +section +/- # Interpreting a ring circuit along a homomorphism into a field -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral + +variable {A F : Type*} [CommRing A] [Field F] {i j k m : ℕ} {a b c s : ℝ} + +theorem Build.map {R : Type*} [CommRing R] {S T : Set A} {U : Set R} (h : Build S m T) (f : A →+* R) + (hu : ∀ x ∈ S, f x ∈ U) : ∃ V, Build U m V ∧ ∀ x ∈ T, f x ∈ V := by + induction h with + | nil => exact ⟨U, .nil, hu⟩ + | add _ hx hy ih => + obtain ⟨V, h, hV⟩ := ih + exact ⟨_, h.add (hV _ hx) (hV _ hy), by simpa only [Set.forall_mem_insert, map_add] using + ⟨Set.mem_insert _ _, fun x hx => Set.mem_insert_of_mem _ (hV x hx)⟩⟩ + | sub _ hx hy ih => + obtain ⟨V, h, hV⟩ := ih + exact ⟨_, h.sub (hV _ hx) (hV _ hy), by simpa only [Set.forall_mem_insert, map_sub] using + ⟨Set.mem_insert _ _, fun x hx => Set.mem_insert_of_mem _ (hV x hx)⟩⟩ + | mul _ hx hy ih => + obtain ⟨V, h, hV⟩ := ih + exact ⟨_, h.mul (hV _ hx) (hV _ hy), by simpa only [Set.forall_mem_insert, map_mul] using + ⟨Set.mem_insert _ _, fun x hx => Set.mem_insert_of_mem _ (hV x hx)⟩⟩ + +theorem Build.embed {S T : Set F} (h : Build S m T) : MatrixExponent.Build S m T := by + induction h with + | nil => exact .nil + | add _ hx hy ih => exact ih.add hx hy + | sub _ hx hy ih => exact ih.sub hx hy + | mul _ hx hy ih => exact ih.mul hx hy + +theorem Computes.field (h : Computes A i j k m) (f : A →+* F) : Rectangle.Computes F i j k m := by + let g := MvPolynomial.eval₂Hom ((algebraMap F (Rectangle.Rat F i j k)).comp f) (Rectangle.input F) + have he (u : Var i j k) : g (input A u) = Rectangle.input F u := by simp [g, input] + obtain ⟨T, hT, ho⟩ := h + obtain ⟨V, hV, hf⟩ := hT.map (U := Rectangle.initial F i j k) g (by + rintro _ (⟨x, rfl⟩ | ⟨x, rfl⟩) + · left + exact ⟨f x, by simp [g]⟩ + · right + exact ⟨x, (he _).symm⟩) + refine ⟨V, hV.embed, fun p => ?_⟩ + simpa only [output, Rectangle.output, map_sum, map_mul, he] using hf _ (ho p) + +theorem Admissible.field (h : Admissible A a b c s) (f : A →+* F) : Rectangle.Admissible F a b c s + := by + intro ε hε + obtain ⟨C, hC, hf⟩ := h ε hε + refine ⟨C, hC, fun n hn => ?_⟩ + obtain ⟨m, hm, hcost⟩ := hf n hn + exact ⟨m, hm.field f, hcost⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Integral +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/RingFormula.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/RingFormula.lean new file mode 100644 index 0000000000..7865df101a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/RingFormula.lean @@ -0,0 +1,27 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldFormula +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.UpperBound + +/-! # The division-free exponent over nonzero commutative rings -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral + +theorem exponent_eq (A : Type*) [CommRing A] [Nontrivial A] {a b c : ℝ} + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + exponent A a b c = Rectangle.U a b c := + of_fields A ha hb hc (fun F _ => Rectangle.exponent_eq F ha hb hc) + +theorem square_exponent (A : Type*) [CommRing A] [Nontrivial A] : exponent A 1 1 1 = 9 / 4 := by + rw [exponent_eq A zero_le_one zero_le_one zero_le_one] + norm_num [Rectangle.U, Rectangle.benchmark] + +end MatrixMultiplicationAllFields.MatrixExponent.Integral diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/ChargedSeparation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/ChargedSeparation.lean new file mode 100644 index 0000000000..5c642adcab --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/ChargedSeparation.lean @@ -0,0 +1,58 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Degeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Separation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialCharacterBounds + +/-! +# The charged separation inequality for actual characters + +The output is evaluated using full direct-sum additivity. Exactly `6*M` +source copies are paid for, and the auxiliary dot product is retained. In +the equal-value case the number of output blocks cancels the factor `M` in +that source cost, but never the auxiliary dot-product factor. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass + +theorem Character.charged_separation (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {M : ℕ} (A : Fin M → Tensor O X Y Z) : + (∑ h, f (ofTensor (A h))) * + f (ofTensor (Separation.dotPairingX (Fin M))) ≤ + (6 * M : ℝ≥0) * f (ofTensor (Separation.shared A)) := by + obtain ⟨P, hconstant, hdegree, heval⟩ := Separation.finite_charged_separation A + have h := f.polynomial_constant_le + (Tensor.directSum (fun _ : Fin (6 * M) => Separation.shared A)) + (Separation.separated A) P ((M - 1) ^ 2) hconstant hdegree heval + exact TensorSpectrum.TensorClass.Character.charged_separation f 6 A h + +/-- The block count pays the growing part of the separation cost. The +remaining factor six is fixed, and is removed only in a later power limit. -/ +theorem Character.charged_separation_equal (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {M : ℕ} (hM : 0 < M) (A : Fin M → Tensor O X Y Z) + (c : ℝ≥0) (hvalue : ∀ h, f (ofTensor (A h)) = c) : + c * f (ofTensor (Separation.dotPairingX (Fin M))) ≤ + 6 * f (ofTensor (Separation.shared A)) := + TensorSpectrum.TensorClass.Character.charged_separation_equal f 6 hM A c hvalue + (f.charged_separation A) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Degeneration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Degeneration.lean new file mode 100644 index 0000000000..f222855ff1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Degeneration.lean @@ -0,0 +1,63 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Powers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.SeparationInterpolation +public import Mathlib.Algebra.Order.Archimedean.Basic +public import Mathlib.Algebra.Order.Ring.Pow +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Positivity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterDegeneration + +/-! +# Characters and polynomial degenerations + +Restriction monotonicity suffices for a polynomial degeneration. For each +fixed family, interpolation of its tensor powers costs only linearly many +copies. The elementary estimate below removes that overhead without any +assumed continuity of the character. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum (le_of_pow_le_linear_mul_pow) + +namespace TensorClass + +/-- Every normalized restriction-monotone character is monotone on the +constant coefficient of an actual bounded polynomial restriction family. +The degree is fixed before the tensor-power argument is applied. -/ +theorem Character.polynomial_constant_le (f : Character) + {X Y Z U V W : Type*} + [Fintype X] [Fintype Y] [Fintype Z] + [Fintype U] [Fintype V] [Fintype W] + (T : Tensor O X Y Z) (D : Tensor O U V W) + (P : Tensor (Polynomial O) U V W) (K : ℕ) + (hconstant : ∀ u v w, (P u v w).coeff 0 = D u v w) + (hdegree : ∀ u v w, (P u v w).degree ≤ K) + (heval : ∀ t : O, IsUnit t → + (fun u v w => (P u v w).eval t) ∈ LocalTensor.orbit T) : + f (ofTensor D) ≤ f (ofTensor T) := + TensorSpectrum.TensorClass.Character.polynomial_constant_le f T D K + (Separation.polynomial_power_mem_restrictionOrbit T D P K hconstant hdegree heval) + +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/DirectSum.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/DirectSum.lean new file mode 100644 index 0000000000..8c9a47af0a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/DirectSum.lean @@ -0,0 +1,40 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Powers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDirectSum + +/-! +# Character values of full direct sums + +Every summand has independent coordinates on all three legs. This file does +not apply additivity to a tensor whose first leg is shared. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass (ofTensor_directSum_fin) + +theorem Character.map_directSum_fin (f : Character) {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (n : ℕ) + (A : Fin n → Tensor O X Y Z) : + f (ofTensor (Tensor.directSum A)) = ∑ i, f (ofTensor (A i)) := + TensorSpectrum.TensorClass.Character.map_directSum_fin f n A + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Dots.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Dots.lean new file mode 100644 index 0000000000..d969e0a1a5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Dots.lean @@ -0,0 +1,91 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.RankOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDots + +/-! +# The three auxiliary pairings as actual tensor classes + +The singleton leg is named in each pairing. Dimension comparisons select +coordinates, multiplication pairs coordinates, and the product of the three +orientations is the square matrix multiplication tensor. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper +namespace CoefficientTensor + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (dotUnitProduct dotTripleX dotTripleY dotTripleZ) + +/-- The specialization of `dotXCoeff` to these coefficients. -/ +abbrev dotXCoeff := + MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.dotXCoeff (K := O) + +end CoefficientTensor + +namespace TensorClass + +/-- The specialization of `dotX` to these coefficients. -/ +abbrev dotX := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.dotX (K := O) + +/-- The specialization of `dotY` to these coefficients. -/ +abbrev dotY := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.dotY (K := O) + +/-- The specialization of `dotZ` to these coefficients. -/ +abbrev dotZ := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.dotZ (K := O) + +theorem dotX_mul (m n : ℕ) : dotX m * dotX n = dotX (m * n) := + TensorSpectrum.TensorClass.dotX_mul m n + +theorem dotY_mul (m n : ℕ) : dotY m * dotY n = dotY (m * n) := + TensorSpectrum.TensorClass.dotY_mul m n + +theorem dotZ_mul (m n : ℕ) : dotZ m * dotZ n = dotZ (m * n) := + TensorSpectrum.TensorClass.dotZ_mul m n + +theorem one_le_dotX {n : ℕ} (hn : 0 < n) : 1 ≤ dotX n := + TensorSpectrum.TensorClass.one_le_dotX (n := n) hn + +theorem one_le_dotY {n : ℕ} (hn : 0 < n) : 1 ≤ dotY n := + TensorSpectrum.TensorClass.one_le_dotY (n := n) hn + +theorem one_le_dotZ {n : ℕ} (hn : 0 < n) : 1 ≤ dotZ n := + TensorSpectrum.TensorClass.one_le_dotZ (n := n) hn + +namespace Character + +/-- The specialization of `dotXValue` to this coefficient ring. -/ +abbrev dotXValue (f : Character) (n : ℕ) : ℝ := + TensorSpectrum.TensorClass.Character.dotXValue f n + +/-- The specialization of `dotYValue` to this coefficient ring. -/ +abbrev dotYValue (f : Character) (n : ℕ) : ℝ := + TensorSpectrum.TensorClass.Character.dotYValue f n + +/-- The specialization of `dotZValue` to this coefficient ring. -/ +abbrev dotZValue (f : Character) (n : ℕ) : ℝ := + TensorSpectrum.TensorClass.Character.dotZValue f n + +end Character +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/DotsPower.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/DotsPower.lean new file mode 100644 index 0000000000..b9380b6586 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/DotsPower.lean @@ -0,0 +1,61 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Dots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPowers + +/-! +# Character exponents of the auxiliary pairings + +The power laws follow from the actual coordinate restrictions and product +identities. Their exponents are constructed here, rather than supplied as +assumptions about a character. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass.Character + +/-- The specialization of `pX` to this coefficient ring. -/ +abbrev pX (f : Character) : ℝ := + TensorSpectrum.TensorClass.Character.pX f + +/-- The specialization of `pY` to this coefficient ring. -/ +abbrev pY (f : Character) : ℝ := + TensorSpectrum.TensorClass.Character.pY f + +/-- The specialization of `pZ` to this coefficient ring. -/ +abbrev pZ (f : Character) : ℝ := + TensorSpectrum.TensorClass.Character.pZ f + +theorem pX_nonneg (f : Character) : 0 ≤ f.pX := + TensorSpectrum.TensorClass.Character.pX_nonneg f + +theorem pY_nonneg (f : Character) : 0 ≤ f.pY := + TensorSpectrum.TensorClass.Character.pY_nonneg f + +theorem pZ_nonneg (f : Character) : 0 ≤ f.pZ := + TensorSpectrum.TensorClass.Character.pZ_nonneg f + +theorem pX_le_one (f : Character) : f.pX ≤ 1 := + TensorSpectrum.TensorClass.Character.pX_le_one f + +theorem pY_le_one (f : Character) : f.pY ≤ 1 := + TensorSpectrum.TensorClass.Character.pY_le_one f + +theorem pZ_le_one (f : Character) : f.pZ ≤ 1 := + TensorSpectrum.TensorClass.Character.pZ_le_one f + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass.Character diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Permutations.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Permutations.lean new file mode 100644 index 0000000000..25a7c8cf06 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Permutations.lean @@ -0,0 +1,78 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Dots +public import Mathlib.Data.Fin.VecNotation +public import Mathlib.Data.Multiset.AddSub +public import Mathlib.Tactic.FinCases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPermutations + +/-! +# Permuting the three actual tensor legs + +The two adjacent swaps act on coefficient arrays and on their actual local +restriction witnesses. Their quotient actions preserve the semiring operations. +The six induced characters therefore remain normalized restriction-monotone +characters; their six values form a multiset invariant under either swap. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper +namespace CoefficientTensor + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (swapXY swapYZ swapXY_blockSum swapYZ_blockSum swapXY_product swapYZ_product) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.Restricts + (swapXY swapYZ) + +end Restricts +end CoefficientTensor + +namespace TensorRep + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep + (swapXY swapYZ) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.Restricts + (swapXY swapYZ) + +end Restricts +end TensorRep + +namespace TensorClass + +/-- The specialization of `swapYZ` to these coefficients. -/ +abbrev swapYZ := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.swapYZ (K := O) + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (swapXY_ofTensor swapYZ_ofTensor swapXY_swapXY swapYZ_swapYZ swap_braid swapXY_add swapYZ_add + swapXY_mul swapYZ_mul permuteSwapXY permuteSwapYZ permute_swapXY permute_swapYZ) + +namespace Character + +end Character +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/PolynomialDegeneration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/PolynomialDegeneration.lean new file mode 100644 index 0000000000..b2be1600c8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/PolynomialDegeneration.lean @@ -0,0 +1,52 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Degeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.DotsPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialFiltrationFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialSectorFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialCharacterBounds + +/-! +# Character bounds from the two explicit polynomial families + +Both inequalities use the actual finite-degree restriction witnesses. In +the determinant case the two-dimensional pairing is explicitly charged. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass + +theorem binaryDotTensor_class : ofTensor binaryDotTensor = dotX 2 := + TensorSpectrum.TensorClass.binaryDotTensor_class (K := O) + +theorem Character.determinant_graded_le (f : Character) (a b : ℕ) : + (f (ofTensor (determinantGradedTensor a b)) : ℝ) ≤ + (2 : ℝ) ^ f.pX * (f (ofTensor (polynomialTensor (a + 1) (b + 2))) : ℝ) := + TensorSpectrum.TensorClass.Character.determinant_graded_le_of_evaluation f + (node := fun t : O => IsUnit t) f.polynomial_constant_le a b + (fun _ ht => determinantPolynomialFamily_eval_mem_restrictionOrbit a b ht) + +theorem Character.tripling_graded_le (f : Character) (a h : ℕ) + (ha : 1 ≤ a) (hh : 1 ≤ h) : + (f (ofTensor (triplingSectorTensor a h)) : ℝ) ≤ + (f (ofTensor (polynomialTensor a (3 * h + a - 1))) : ℝ) := + TensorSpectrum.TensorClass.Character.tripling_graded_le_of_evaluation f + (node := fun t : O => IsUnit t) f.polynomial_constant_le a h ha hh + (fun _ ht => triplingPolynomialFamily_eval_mem_restrictionOrbit a h ha hh ht) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/PolynomialValues.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/PolynomialValues.lean new file mode 100644 index 0000000000..1d124b0567 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/PolynomialValues.lean @@ -0,0 +1,46 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.TagFinite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterDegeneration + +/-! +# Positivity and rank bounds for polynomial character values + +The constant input monomials witness nonvanishing. The upper bound uses the +actual evaluation/interpolation rank decomposition of ordinary convolution. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +namespace TensorClass + +theorem Character.polynomial_value_pos (f : Character) (a b : ℕ) + (ha : 1 ≤ a) (hb : 1 ≤ b) : + 0 < (f (ofTensor (polynomialTensor a b)) : ℝ) := + TensorSpectrum.TensorClass.Character.polynomial_value_pos f a b ha hb + +theorem Character.polynomial_value_le (f : Character) (a b : ℕ) + (ha : 1 ≤ a) (hb : 1 ≤ b) : + (f (ofTensor (polynomialTensor a b)) : ℝ) ≤ (a : ℝ) + (b : ℝ) - 1 := + TensorSpectrum.TensorClass.Character.polynomial_value_le_of_rankAtMost + f a b ha hb (polynomialTensor_rankAtMost a b) + +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Rank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Rank.lean new file mode 100644 index 0000000000..0d521db778 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Rank.lean @@ -0,0 +1,48 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Bounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.DotsPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.RectangularRank + +/-! +# From the character estimate to rectangular algorithms + +Each pairing belongs to the two legs other than its named leg. Reading +the first two legs as inputs and the third as output gives a rank bound +on the formal product. Ceiling costs at most a factor of two per pairing. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +open Rectangle +open Upper Upper.TensorClass + +/-- The product of dot tensors for a rectangular matrix shape. -/ +abbrev dots := TensorSpectrum.TensorClass.dots (K := O) + +theorem dots_power (i j k t : ℕ) : + dots (i ^ t) (j ^ t) (k ^ t) = (dots i j k) ^ t := + TensorSpectrum.TensorClass.dots_power i j k t + +theorem rank_of_dots {i j k r : ℕ} (h : dots i j k ≤ (r : TensorClass)) : + Rank O i j k r := + TensorSpectrum.TensorClass.rank_of_dots h + +export MatrixMultiplicationAllFields.MatrixExponent.Rectangle (rounded_dot) + +theorem price_dots (f : Character) {n : ℕ} (hn : 0 < n) {a b c : ℝ} + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + (f (dots (side n a) (side n b) (side n c)) : ℝ) ≤ + 8 * (n : ℝ) ^ (b * f.pX + a * f.pY + c * f.pZ) := + TensorSpectrum.TensorClass.price_dots f hn ha hb hc + + +end MatrixMultiplicationAllFields.MatrixExponent.Integral diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Tag.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Tag.lean new file mode 100644 index 0000000000..8a4431512b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/Tag.lean @@ -0,0 +1,48 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.TagFinite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.TagOptimized +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagEntropy + +/-! +# Optimized tagging for actual tensor characters + +The finite count-fiber premise is discharged by the actual tensor restriction +and charged separation construction. Only then is the polynomial number of +fibers removed. No multinomial asymptotics or uncharged auxiliary tensor is +used. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass + +theorem Character.shared_tag_optimized_of_pos (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s : ℕ} (hs : 0 < s) (A : Fin s → Tensor O X Y Z) + (hA : ∀ i, 0 < (f (ofTensor (A i)) : ℝ)) (hp : 0 < f.pX) : + (∑ i, (f (ofTensor (A i)) : ℝ) ^ (1 / f.pX)) ^ f.pX ≤ + (f (ofTensor (Separation.shared A)) : ℝ) := by + apply Integral.tag_optimized_of_fiber_bounds hs f.pX hp + (fun i => (f (ofTensor (A i)) : ℝ)) hA + (f (ofTensor (Separation.shared A)) : ℝ) + (f (ofTensor (Separation.shared A))).coe_nonneg + intro N hN c hc + exact f.tag_count_fiber A c hc + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/TagFinite.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/TagFinite.lean new file mode 100644 index 0000000000..44759b25ca --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Character/TagFinite.lean @@ -0,0 +1,54 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.ChargedSeparation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.DotsPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagFiberBounds + +/-! +# The exact finite-word character inequality + +Every count fiber is selected by actual local coordinate maps from a tensor +power of the original shared-input tensor. Charged separation is then applied +to that finite fiber. This is the tensor input to the later scalar limit; +neither the separation nor the word restriction is an assumption here. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass + +theorem Character.shared_branch_le (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s : ℕ} (A : Fin s → Tensor O X Y Z) (i : Fin s) : + f (ofTensor (A i)) ≤ f (ofTensor (Separation.shared A)) := by + exact TensorSpectrum.TensorClass.Character.shared_branch_le f A i + +/-- The original word-fiber cost, including the fixed factor six. The +polynomial number of possible count vectors has not yet been removed. -/ +theorem Character.tag_count_fiber (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s N : ℕ} (A : Fin s → Tensor O X Y Z) + (c : TagWords.CountVector s N) (hc : 0 < (TagWords.fiber c).card) : + ((TagWords.fiber c).card : ℝ) ^ f.pX * + TagWords.countWeight (fun i => (f (ofTensor (A i)) : ℝ)) c ≤ + 6 * (f (ofTensor (Separation.shared A)) : ℝ) ^ N := by + apply TensorSpectrum.TensorClass.Character.tag_count_fiber f A c hc 6 + intro M hM B C hvalue + exact f.charged_separation_equal hM B C hvalue + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Coefficients.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Coefficients.lean new file mode 100644 index 0000000000..ce8e1643f4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Coefficients.lean @@ -0,0 +1,27 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Nodes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.LocalTensor +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexMatrixTensor + +/-! # Coefficient tensor for the integral upper bound -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +/-- Computes the matrix tensor by the application `Tensor.matrixCoefficients (Fin a) (Fin b) +(Fin c)`. -/ +def matrixTensor (a b c : ℕ) : + Tensor O (Fin a × Fin b) (Fin b × Fin c) (Fin c × Fin a) := + Tensor.matrixCoefficients (Fin a) (Fin b) (Fin c) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialDegeneration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialDegeneration.lean new file mode 100644 index 0000000000..506f54b79b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialDegeneration.lean @@ -0,0 +1,43 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Interpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.WeightedPolynomials +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition + +/-! # Polynomial degenerations of integral coefficient tensors -/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (weightedLimit weightedFamily weightedFamily_zero restrict_diagonal) + +variable {X Y Z : Type*} + +/-- At every nonzero parameter, the family is witnessed by actual +local substitutions: the diagonal entries are the respective integer powers. -/ +theorem weightedFamily_mem_restrictionOrbit + [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor O X Y Z) (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) + (h : ∀ x y z, T x y z ≠ 0 → 0 ≤ wx x + wy y + wz z) + {t : O} (ht : IsUnit t) : + weightedFamily T wx wy wz t ∈ LocalTensor.orbit T := + TensorSpectrum.PolynomialTensors.weightedFamily_mem_restrictionOrbit T wx wy wz h t + (fun n => t ^ n) (fun i j => upow_add ht i j) (fun n => upow_nat t n) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialFiltration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialFiltration.lean new file mode 100644 index 0000000000..40b1370cd4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialFiltration.lean @@ -0,0 +1,76 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialFiltration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialDegeneration +public import Lean.Elab.Tactic.Omega + +/-! +# The explicit determinant filtration + +We use positive dimensions `a+1` and `b+2`. The two old copies are the +coefficients of `s` and `w`. The new coordinates are quotient lifts `Q` and +kernel elements `K = W_j - S_(j+1)`. The first input is unchanged throughout. +All statements below are coefficient identities over the coefficient field. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + +noncomputable section +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (doubleIndexEquiv doubleOutputEquiv determinant_basis_change + determinantGraded_quotient determinantGraded_kernel determinantGraded_quotient_kernel + determinantGraded_kernel_quotient determinantInputWeight determinantOutputWeight + determinant_supported_weight determinant_weightedLimit) + +/-- The shared delta construction over the coefficient ring. -/ +abbrev delta {ι : Type*} [DecidableEq ι] (i j : ι) := + TensorSpectrum.PolynomialTensors.delta (K := O) i j + +/-- The shared doubledPolynomialTensor construction over the coefficient ring. -/ +abbrev doubledPolynomialTensor := + TensorSpectrum.PolynomialTensors.doubledPolynomialTensor (K := O) + +/-- The shared binaryDotTensor construction over the coefficient ring. -/ +abbrev binaryDotTensor := + TensorSpectrum.PolynomialTensors.binaryDotTensor (K := O) + +/-- The shared determinantInputMap construction over the coefficient ring. -/ +abbrev determinantInputMap := + TensorSpectrum.PolynomialTensors.determinantInputMap (K := O) + +/-- The shared determinantOutputMap construction over the coefficient ring. -/ +abbrev determinantOutputMap := + TensorSpectrum.PolynomialTensors.determinantOutputMap (K := O) + +/-- The shared determinantAdaptedTensor construction over the coefficient ring. -/ +abbrev determinantAdaptedTensor := + TensorSpectrum.PolynomialTensors.determinantAdaptedTensor (K := O) + +/-- The shared determinantGradedTensor construction over the coefficient ring. -/ +abbrev determinantGradedTensor := + TensorSpectrum.PolynomialTensors.determinantGradedTensor (K := O) + +/-- Relabeling gives two copies of convolution with the first input shared. -/ +theorem doubledPolynomialTensor_product (a b : ℕ) : + Tensor.pullback (fun i => (i, ())) (doubleIndexEquiv (b + 2)) + (doubleOutputEquiv a b) + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) = + doubledPolynomialTensor a b := + TensorSpectrum.PolynomialTensors.doubledPolynomialTensor_product (K := O) a b + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialFiltrationFamily.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialFiltrationFamily.lean new file mode 100644 index 0000000000..b6380efc3d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialFiltrationFamily.lean @@ -0,0 +1,64 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialFiltration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialWeightFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialFiltrationFamily + +/-! +# The finite-degree determinant family + +The constant coefficient is the two-branch graded tensor. Every nonzero +evaluation is an actual restriction of the original convolution tensor times +the two-dimensional pairing. These explicit data, rather than continuity of +an arbitrary tensor character, are the inputs to finite interpolation. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +theorem determinantAdapted_mem_restrictionOrbit (a b : ℕ) : + determinantAdaptedTensor a b ∈ LocalTensor.orbit + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) := + TensorSpectrum.PolynomialTensors.determinantAdapted_mem_restrictionOrbit a b + +/-- The determinant polynomial family over the coefficient ring. -/ +abbrev determinantPolynomialFamily := + TensorSpectrum.PolynomialTensors.determinantPolynomialFamily (K := O) + +theorem determinantPolynomialFamily_coeff_zero (a b : ℕ) : + (fun i y z => (determinantPolynomialFamily a b i y z).coeff 0) = + determinantGradedTensor a b := + TensorSpectrum.PolynomialTensors.determinantPolynomialFamily_coeff_zero a b + +theorem determinantPolynomialFamily_degree_le (a b : ℕ) + (i : Fin (a + 1)) (y : Fin (b + 3) ⊕ Fin (b + 1)) + (z : Fin (a + b + 3) ⊕ Fin (a + b + 1)) : + (determinantPolynomialFamily a b i y z).degree ≤ (1 : ℕ) := + TensorSpectrum.PolynomialTensors.determinantPolynomialFamily_degree_le a b i y z + +theorem determinantPolynomialFamily_eval_mem_restrictionOrbit (a b : ℕ) + {t : O} (ht : IsUnit t) : + (fun i y z => (determinantPolynomialFamily a b i y z).eval t) ∈ + LocalTensor.orbit + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) := + TensorSpectrum.PolynomialTensors.determinantPolynomialFamily_eval_mem_restrictionOrbit a b t + (weightedPolynomial_eval_mem_restrictionOrbit + (determinantAdaptedTensor a b) (fun _ => 0) + (determinantInputWeight b) (determinantOutputWeight a b) + (determinant_supported_weight a b) ht) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialSectorFamily.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialSectorFamily.lean new file mode 100644 index 0000000000..e4edb33646 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialSectorFamily.lean @@ -0,0 +1,60 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialSectors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialWeightFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialSectorFamily + +/-! +# The polynomial witness for the three-sector degeneration + +Every coefficient has degree at most one. Its constant coefficient is the +entire shared-first-input sector assembly. At each nonzero parameter the +evaluated tensor is an actual restriction of the original polynomial tensor. +These explicit facts support interpolation without assuming that an arbitrary +tensor character preserves topological limits. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +/-- The tripling polynomial family over the coefficient ring. -/ +abbrev triplingPolynomialFamily := + TensorSpectrum.PolynomialTensors.triplingPolynomialFamily (K := O) + +theorem triplingPolynomialFamily_coeff_zero (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (x : Fin a) (y : TriplingY a h) (z : TriplingZ a h) : + (triplingPolynomialFamily a h ha hh x y z).coeff 0 = triplingSectorTensor a h x y z := + TensorSpectrum.PolynomialTensors.triplingPolynomialFamily_coeff_zero a h ha hh x y z + +theorem triplingPolynomialFamily_degree_le (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (x : Fin a) (y : TriplingY a h) (z : TriplingZ a h) : + (triplingPolynomialFamily a h ha hh x y z).degree ≤ (1 : ℕ) := + TensorSpectrum.PolynomialTensors.triplingPolynomialFamily_degree_le a h ha hh x y z + +/-- Every nonzero evaluation is an exact restriction of the original source +tensor. The sector reindexing is one fixed pair of local maps, with identity +on the common first input, after the diagonal maps. -/ +theorem triplingPolynomialFamily_eval_mem_restrictionOrbit + (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) {t : O} (ht : IsUnit t) : + (fun x y z => (triplingPolynomialFamily a h ha hh x y z).eval t) ∈ + LocalTensor.orbit (polynomialTensor a (triplingWidth a h)) := + TensorSpectrum.PolynomialTensors.triplingPolynomialFamily_eval_mem_restrictionOrbit a h ha hh t + (weightedPolynomial_eval_mem_restrictionOrbit _ _ _ _ + (TensorSpectrum.PolynomialTensors.tripling_source_weights_nonneg a h ha) ht) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialSectors.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialSectors.lean new file mode 100644 index 0000000000..64137e8ba3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialSectors.lean @@ -0,0 +1,54 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialSectors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialDegeneration +public import Lean.Elab.Tactic.Omega + +/-! +# The three-sector polynomial degeneration + +The coefficient identities describe three sectors. The first input has +weight zero throughout the degeneration. Only when identifying the individual +middle branch do we reverse its first index; its other two indices are swapped. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (triplingWidth triplingYWeight triplingZWeight triplingMatched tripling_support_left + tripling_support_right tripling_support_middle tripling_weight_nonneg + tripling_weight_zero_iff tripling_weight_one_iff triplingGraded_of_weights + triplingGraded_coefficient triplingLeftY triplingLeftZ triplingMiddleY triplingMiddleZ + triplingRightY triplingRightZ triplingReverse triplingReverse_involutive + tripling_left_weights tripling_middle_weights tripling_right_weights + tripling_left_coefficient tripling_right_coefficient tripling_middle_coefficient + tripling_second_sectors_disjoint tripling_output_sectors_disjoint TriplingY TriplingZ + triplingYMap triplingZMap triplingYMap_injective triplingZMap_injective + triplingYMap_surjective triplingZMap_surjective triplingYEquiv triplingZEquiv + triplingGraded_sector_assembly) + +/-- The shared triplingGraded construction over the coefficient ring. -/ +abbrev triplingGraded := + MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors.triplingGraded (K := O) + +/-- The shared triplingSectorTensor construction over the coefficient ring. -/ +abbrev triplingSectorTensor := + MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors.triplingSectorTensor (K := O) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialTensor.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialTensor.lean new file mode 100644 index 0000000000..3da2e4e48b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialTensor.lean @@ -0,0 +1,52 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Interpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Polynomial.ComplexPolynomialApproximation +public import Lean.Elab.Tactic.Omega +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialRank + +/-! +# The polynomial multiplication tensor + +The coefficient tensor records ordinary, untruncated polynomial multiplication. +Evaluation at `a + b - 1` distinct field elements and uniform Lagrange +interpolation give an actual rank decomposition of that size. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (polynomialTensor_apply polynomialTensor_eq_coeff polynomialTensor_swap + polynomialTensor_one_left) + +/-- The shared polynomialTensor construction over the coefficient ring. -/ +abbrev polynomialTensor := + MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors.polynomialTensor (K := O) + +/-- Ordinary polynomial multiplication has an actual decomposition into +`a + b - 1` rank-one tensors. The degenerate empty-input cases are included. -/ +theorem polynomialTensor_rankAtMost (a b : ℕ) : + Tensor.RankAtMost (polynomialTensor a b) (a + b - 1) := by + classical + obtain ⟨nodes, hnodes, _⟩ := unit_nodes (a + b - 1) + exact TensorSpectrum.PolynomialTensors.polynomialTensor_rankAtMost_of_interpolation a b nodes + (Integral.weight nodes) (Integral.interpolate nodes hnodes) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialWeightFamily.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialWeightFamily.lean new file mode 100644 index 0000000000..9a77aa9ece --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/PolynomialWeightFamily.lean @@ -0,0 +1,55 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialDegeneration +public import Mathlib.Algebra.Polynomial.Degree.Defs +public import Mathlib.Algebra.Polynomial.Eval.Coeff +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.WeightedPolynomials + +/-! +# Explicit polynomial families for diagonal weight degenerations + +The diagonal degeneration has a polynomial coefficient family, not merely a +topological limit. Its constant coefficient is the retained tensor. Its degree +is controlled by the supported total weights. At every nonzero parameter its +evaluation is an exact restriction of the source tensor. These are the inputs +needed to extract tensor powers by finite interpolation. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +variable {X Y Z : Type*} + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (weightedPolynomial weightedPolynomial_eval weightedPolynomial_coeff_zero + weightedPolynomial_natDegree_le weightedPolynomial_degree_le + weightedPolynomial_degree_le_one) + +/-- Every nonzero evaluation has actual diagonal local restriction witnesses; +the polynomial family does not assume a character or a continuity principle. -/ +theorem weightedPolynomial_eval_mem_restrictionOrbit + [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor O X Y Z) (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) + (h : ∀ x y z, T x y z ≠ 0 → 0 ≤ wx x + wy y + wz z) + {t : O} (ht : IsUnit t) : + (fun x y z => (weightedPolynomial T wx wy wz x y z).eval t) ∈ + LocalTensor.orbit T := by + rw [weightedPolynomial_eval] + exact weightedFamily_mem_restrictionOrbit T wx wy wz h ht + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Separation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Separation.lean new file mode 100644 index 0000000000..896ed37d0b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Separation.lean @@ -0,0 +1,141 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Interpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationWeights +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Polynomial.ComplexPolynomialApproximation +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Blocks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationPolynomial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationFourier + +/-! +# Charged finite separation by local Fourier maps + +The source is exactly `6 * M` full copies of the shared-first-leg tensor. +The target is the full direct sum of the sector tensors, each multiplied by +a length-`M` pairing on the second and third legs. Local variables may have +negative weights; after Fourier projection every surviving total weight is +a nonnegative square, so the resulting coefficient array is polynomial. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.TensorSpectrum.Separation + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.Separation + +variable {X Y Z : Type*} + +/-- The branch labels occur only on the last two legs of the input. -/ +abbrev shared {M : ℕ} (A : Fin M → Tensor O X Y Z) : + Tensor O X (Fin M × Y) (Fin M × Z) := + Tensor.sharedFirst A + +export MatrixMultiplicationAllFields.TensorSpectrum.Separation + (dotPairingX separated phase projected squareDegree separationPolynomial + squareDegree_eq_zero_iff separationPolynomial_constant separationPolynomial_degree weightX + weightY weightZ) + +export MatrixMultiplicationAllFields.TensorSpectrum.Separation + (copyLocal restrict_copies restrict_scaled) + +section Projection + +variable {M : ℕ} +variable [Fintype X] [Fintype Y] [Fintype Z] +variable [DecidableEq X] [DecidableEq Y] [DecidableEq Z] + +/-- The quantity computed by `copyLocal (fun x => x.2.1) (fun x r => ζ ^ ((r : ℤ) * (2 * (x.1 : +ℤ))))`. -/ +abbrev fourierX (ζ : O) : + (Fin M × (X × Unit)) → (Fin (6 * M) × X) → O := + TensorSpectrum.Separation.fourierX (M := M) (L := 6 * M) (fun e => ζ ^ e) + +/-- The quantity computed by `copyLocal (fun y => (y.1, y.2.1)) (fun y r => ζ ^ ((r : ℤ) * +((y.2.2 : ℤ) - (y.1 : ℤ))))`. -/ +abbrev fourierY (ζ : O) : + (Fin M × (Y × Fin M)) → (Fin (6 * M) × (Fin M × Y)) → O := + TensorSpectrum.Separation.fourierY (M := M) (L := 6 * M) (fun e => ζ ^ e) + +/-- The quantity computed by `copyLocal (fun z => (z.1, z.2.1)) (fun z r => w r * ζ ^ ((r : ℤ) * +(-(z.2.2 : ℤ) - (z.1 : ℤ))))`. -/ +abbrev fourierZ (ζ : O) (w : Fin (6 * M) → O) : + (Fin M × (Z × Fin M)) → (Fin (6 * M) × (Fin M × Z)) → O := + TensorSpectrum.Separation.fourierZ (M := M) (L := 6 * M) (fun e => ζ ^ e) w + +/-- The actual independent local maps give exactly the projected tensor. -/ +theorem fourier_restrict (A : Fin M → Tensor O X Y Z) + (ζ : O) (w : Fin (6 * M) → O) (hζ : IsUnit ζ) + (haverage : ∀ e : ℤ, -(3 * (M : ℤ)) < e → e < 3 * (M : ℤ) → + (∑ r : Fin (6 * M), w r * ζ ^ ((r : ℤ) * e)) = if e = 0 then 1 else 0) : + Tensor.restrict (fourierX ζ) (fourierY ζ) (fourierZ ζ w) + (Tensor.directSum (fun _ : Fin (6 * M) => shared A)) = projected A := + TensorSpectrum.Separation.fourier_restrict A (fun e => ζ ^ e) w + (fun a b => upow_add hζ a b) haverage + +end Projection + +section Polynomial + +variable {M : ℕ} + +/-- On the complete projected support, the local weights add to the actual +polynomial degree, including all zero and mismatched coefficients. -/ +theorem separationPolynomial_eval (A : Fin M → Tensor O X Y Z) + (t : O) (ht : IsUnit t) : + (fun x y z => (separationPolynomial A x y z).eval t) = + fun x y z => t ^ weightX x * t ^ weightY y * t ^ weightZ z * projected A x y z := + TensorSpectrum.Separation.separationPolynomial_eval A t (fun e => t ^ e) + (fun a b => upow_add ht a b) (fun n => upow_nat t n) + +end Polynomial + +section Realization + +variable {M : ℕ} +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- Every nonzero specialization comes from exactly the charged number of +source copies by three actual local linear maps. -/ +theorem separationPolynomial_specializes + (A : Fin M → Tensor O X Y Z) (t : O) (ht : IsUnit t) : + (fun x y z => (separationPolynomial A x y z).eval t) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : Fin (6 * M) => shared A)) := by + classical + obtain ⟨ζ, w, hζ, haverage⟩ := phases (M := M) + exact TensorSpectrum.Separation.separationPolynomial_specializes (L := 6 * M) + A (fun e => ζ ^ e) w t (fun e => t ^ e) + (fourier_restrict A ζ w hζ haverage) (separationPolynomial_eval A t ht) + +/-- The complete finite construction, without a rank or character premise. +The nonzero-evaluation witnesses are restrictions of the full source direct +sum; the constant tensor is itself a full direct sum of products. -/ +theorem finite_charged_separation + (A : Fin M → Tensor O X Y Z) : + ∃ P : Tensor (Polynomial O) (Fin M × (X × Unit)) + (Fin M × (Y × Fin M)) (Fin M × (Z × Fin M)), + (∀ x y z, (P x y z).coeff 0 = separated A x y z) ∧ + (∀ x y z, (P x y z).degree ≤ ((M - 1) ^ 2 : ℕ)) ∧ + (∀ t : O, IsUnit t → (fun x y z => (P x y z).eval t) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : Fin (6 * M) => shared A))) := + TensorSpectrum.Separation.finite_charged_separation (L := 6 * M) A IsUnit + (separationPolynomial_specializes A) + +end Realization + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.Separation diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/SeparationInterpolation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/SeparationInterpolation.lean new file mode 100644 index 0000000000..f583bc342a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/SeparationInterpolation.lean @@ -0,0 +1,88 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Interpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Polynomial.ComplexPolynomialApproximation +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.RestrictionInterpolation + +/-! +# Polynomial coefficient extraction by actual restrictions + +Every coefficient of a bounded polynomial tensor is a linear combination of +evaluations at common interpolation nodes. If those evaluations are local +restrictions of one source tensor, the coefficient is a restriction of the +full direct sum of that many source copies. Applying this to tensor powers +gives the linear interpolation overhead required by restriction-monotone +characters. No continuity of a character on a Euclidean closure is assumed. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.Separation + +export MatrixMultiplicationAllFields.TensorSpectrum.RestrictionInterpolation + (restrict_directSum_sum restrict_scale_first restrict_power power_mem_restrictionOrbit + polynomial_power_constant polynomial_power_eval polynomial_power_degree) + +section Interpolation + +variable {X Y Z U V W : Type*} +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- Interpolation at any common family of distinct nonzero nodes turns actual +restriction witnesses for the evaluations into one restriction witness for the +coefficient. The full number of source copies is charged explicitly. -/ +theorem polynomial_coeff_mem_restrictionOrbit {n : ℕ} + (T : Tensor O X Y Z) (P : Tensor (Polynomial O) U V W) + (nodes : (Fin n) → O) (hinj : IsUnit (Matrix.vandermonde nodes).det) + (hnonzero : ∀ i, IsUnit (nodes i)) + (heval : ∀ t : O, IsUnit t → + (fun u v w => (P u v w).eval t) ∈ LocalTensor.orbit T) + (hdegree : ∀ u v w, (P u v w).degree < Fintype.card (Fin n)) (d : ℕ) : + (fun u v w => (P u v w).coeff d) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : (Fin n) => T)) := by + classical + refine TensorSpectrum.RestrictionInterpolation.coefficient_mem_restrictionOrbit T P + nodes (fun i => Integral.weight nodes i d) d (fun i => heval (nodes i) (hnonzero i)) ?_ + intro u v w + simpa only [mul_comm] using Integral.interpolate nodes hinj (P u v w) d (hdegree u v w) + +/-- The finite interpolation bound before applying any character. For every +power `j`, exactly `K*j+1` copies of the power of the original source suffice. +The interpolation nodes have this same cardinality. -/ +theorem polynomial_power_mem_restrictionOrbit + (T : Tensor O X Y Z) (D : Tensor O U V W) + (P : Tensor (Polynomial O) U V W) (K : ℕ) + (hconstant : ∀ u v w, (P u v w).coeff 0 = D u v w) + (hdegree : ∀ u v w, (P u v w).degree ≤ K) + (heval : ∀ t : O, IsUnit t → + (fun u v w => (P u v w).eval t) ∈ LocalTensor.orbit T) + (j : ℕ) : + Tensor.power D j ∈ LocalTensor.orbit + (Tensor.directSum (fun _ : Fin (K * j + 1) => Tensor.power T j)) := by + classical + apply TensorSpectrum.RestrictionInterpolation.polynomial_power_mem_restrictionOrbit + T D P K hconstant hdegree IsUnit heval j + intro hevalpower hdegreepower + obtain ⟨nodes, hinj, hnonzero⟩ := unit_nodes (K * j + 1) + exact polynomial_coeff_mem_restrictionOrbit (Tensor.power T j) (Tensor.power P j) + nodes hinj hnonzero hevalpower hdegreepower 0 + +end Interpolation + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.Separation diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/TagHeterogeneous.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/TagHeterogeneous.lean new file mode 100644 index 0000000000..62ba0ea7f7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/TagHeterogeneous.lean @@ -0,0 +1,59 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Separation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Base +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.PolynomialSectors +public import Mathlib.Tactic.FinCases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagHeterogeneous + +/-! +# Heterogeneous shared-first-leg tensors + +Padding a branch adds only zero coordinates. The extra uniform labels used by +the separation construction are removed by actual independent local maps. +The first leg is shared throughout; no direct-sum additivity is used here. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TagHeterogeneous + +export MatrixMultiplicationAllFields.TensorSpectrum.TagHeterogeneous + (sharedTwo padLeft padRight ofTensor_padLeft ofTensor_padRight maskedFamily + ofTensor_shared_maskedFamily twoLabel twoFamily twoFamily_eq_maskedFamily + ofTensor_shared_twoFamily ofTensor_twoFamily sharedThree threeLabel threeFamily + threeFamily_eq_maskedFamily ofTensor_shared_threeFamily ofTensor_threeFamily) + +/-- The polynomial branch with reversed first coordinate. -/ +abbrev triplingMiddleTensor := + TensorSpectrum.TagHeterogeneous.triplingMiddleTensor (K := O) + +/-- The heterogeneous tensor represents the three polynomial sectors. -/ +theorem triplingSectorTensor_eq_sharedThree (a h : ℕ) : + triplingSectorTensor a h = sharedThree (polynomialTensor a h) + (triplingMiddleTensor a h) (polynomialTensor a h) := + TensorSpectrum.TagHeterogeneous.triplingSectorTensor_eq_sharedThree a h + +/-- The three sectors and their uniform-label tensor have the same restriction class. -/ +theorem ofTensor_tripling_uniform (a h : ℕ) : + TensorClass.ofTensor (Separation.shared + (threeFamily (polynomialTensor a h) (triplingMiddleTensor a h) + (polynomialTensor a h))) = TensorClass.ofTensor (triplingSectorTensor a h) := + TensorSpectrum.TagHeterogeneous.ofTensor_tripling_uniform a h + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TagHeterogeneous diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/TagOptimized.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/TagOptimized.lean new file mode 100644 index 0000000000..1300ed9e60 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/TagOptimized.lean @@ -0,0 +1,27 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagOptimized + +/-! # Optimization of tag weights using finite fiber bounds -/ + +@[expose] public section + +open MatrixMultiplicationAllFields.TensorSpectrum +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +theorem tag_optimized_of_fiber_bounds + {s : ℕ} (hs : 0 < s) (p : ℝ) (hp : 0 < p) + (c : Fin s → ℝ) (hc : ∀ i, 0 < c i) (x : ℝ) (hx : 0 ≤ x) + (hfinite : ∀ N : ℕ, 1 ≤ N → ∀ v : TagWords.CountVector s N, + 0 < (TagWords.fiber v).card → + ((TagWords.fiber v).card : ℝ) ^ p * TagWords.countWeight c v ≤ + 6 * x ^ N) : + (∑ i, (c i) ^ (1 / p)) ^ p ≤ x := + TensorSpectrum.tag_optimized_of_fiber_bounds 6 (by norm_num) hs p hp c hc x hx hfinite + +end MatrixMultiplicationAllFields.MatrixExponent.Integral diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/TagTensorWords.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/TagTensorWords.lean new file mode 100644 index 0000000000..40d352b256 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/TagTensorWords.lean @@ -0,0 +1,44 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Separation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Powers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagWords +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagTensorWords + +/-! +# Coefficient tensor words and matched-label restrictions + +Tensor powers of a shared-first-leg tensor have one branch for each word. +The regrouping below preserves all coefficients, including the zero +coefficients between different words. Selecting words by an injection is an +actual local restriction. Multiplicativity is then applied to the actual +tensor product represented by each word. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TagTensorWords + +export MatrixMultiplicationAllFields.TensorSpectrum.TagTensorWords + (sharedLabels tensorWord wordBranch joinCoordinates power_shared_pullback + restricts_power_shared_words ofTensor_shared_words shared_injective_pullback + restricts_shared_injective restricts_power_shared_selected restricts_power_shared_fiber + restricts_power_shared_fiber_enumeration headTailCoordinates ofTensor_tensorWord + map_wordBranch map_wordBranch_of_mem_fiber) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TagTensorWords diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Base.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Base.lean new file mode 100644 index 0000000000..e47768f22f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Base.lean @@ -0,0 +1,64 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition +public import Mathlib.Basic.NNReal.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClass + +/-! # Tensor representatives and classes for the upper bound -/ + +@[expose] public section + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper + +namespace CoefficientTensor + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (Restricts) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.Restricts + (refl trans pullback rankAtMost) + +end Restricts + +end CoefficientTensor + +/-- Finite tensor representatives over the coefficient ring. -/ +abbrev TensorRep := MatrixMultiplicationAllFields.TensorSpectrum.TensorRep O + +namespace TensorRep + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep + (mk ofTensor Restricts Equivalent mutualRestriction restricts_ofTensor + ofTensor_restricts equivalent_ofTensor_coeff) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.Restricts + (refl trans ofTensor) + +end Restricts + +end TensorRep + +/-- Mutual-restriction classes over the coefficient ring. -/ +abbrev TensorClass := MatrixMultiplicationAllFields.TensorSpectrum.TensorClass O + +namespace TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (ofRep ofTensor ofRep_eq ofTensor_coeff ofTensor_eq ofTensor_pullback_equiv ofTensor_le) + +end TensorClass + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Blocks.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Blocks.lean new file mode 100644 index 0000000000..730cea0a56 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Blocks.lean @@ -0,0 +1,42 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Base +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Blocks + +/-! +# Heterogeneous direct sums and restrictions + +The two summands retain separate coordinates on every leg. Cross coefficients +are zero, and block diagonal local matrices give actual restriction witnesses. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.CoefficientTensor + +export MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + (blockSum blockMatrix blockSum_inl blockSum_inr restrict_blockSum pullback_blockSum) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.Restricts + (blockSum product) + +end Restricts + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.CoefficientTensor diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Matrix.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Matrix.lean new file mode 100644 index 0000000000..cfcde48133 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Matrix.lean @@ -0,0 +1,72 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Rank +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexMatrixTensor +public import Mathlib.Logic.Equiv.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDots + +/-! +# Square matrix tensors in the restriction semiring + +Dimension comparisons and multiplication are witnessed by the actual coordinate +maps. The cubic rank bound uses the ordinary sum over the three matrix indices. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper +namespace CoefficientTensor + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (matrixCoefficients_pullback_injective) + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor (squareProductCoordinates) + +/-- Relabeling the product coordinates gives the larger square multiplication tensor. -/ +theorem square_product_pullback (n m : ℕ) : + Tensor.pullback (squareProductCoordinates n m) (squareProductCoordinates n m) + (squareProductCoordinates n m) (Upper.matrixTensor (n * m) (n * m) (n * m)) = + Tensor.product (Upper.matrixTensor n n n) (Upper.matrixTensor m m m) := + MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.square_product_pullback + (K := O) n m + +/-- Restrict a square multiplication tensor by taking the first indices of each wire. -/ +theorem square_restricts_of_le {n m : ℕ} (h : n ≤ m) : + Restricts (Upper.matrixTensor m m m) (Upper.matrixTensor n n n) := + MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.square_restricts_of_le + (K := O) h + +/-- A sum over the triples of indices gives a cubic rank bound. -/ +theorem square_rankAtMost_cubic (n : ℕ) : + Tensor.RankAtMost (Upper.matrixTensor n n n) (n ^ 3) := + MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.square_rankAtMost_cubic + (K := O) n + +end CoefficientTensor + +namespace TensorClass + +/-- The class of the actual `n` by `n` matrix multiplication tensor. -/ +abbrev square := MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.square (K := O) + +theorem rank_square_le (n : ℕ) : rank (square n) ≤ n ^ 3 := + TensorSpectrum.TensorClass.rank_square_le n + +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Powers.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Powers.lean new file mode 100644 index 0000000000..42bdb2d596 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Powers.lean @@ -0,0 +1,49 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.RankOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPowers + +/-! +# Tensor powers and full repeated direct sums in the quotient + +These bridges preserve the actual coefficient tensors used by interpolation. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (ofTensor_power ofTensor_directSum_const) + +namespace Character + +theorem map_power_tensor (f : Character) {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (T : Tensor O X Y Z) (n : ℕ) : + f (ofTensor (Tensor.power T n)) = (f (ofTensor T)) ^ n := + TensorSpectrum.TensorClass.Character.map_power_tensor f T n + +theorem map_directSum_const (f : Character) {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (T : Tensor O X Y Z) (n : ℕ) : + f (ofTensor (Tensor.directSum (fun _ : Fin n => T))) = + (n : ℝ≥0) * f (ofTensor T) := + TensorSpectrum.TensorClass.Character.map_directSum_const f T n + +end Character + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Rank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Rank.lean new file mode 100644 index 0000000000..71db9d511e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Rank.lean @@ -0,0 +1,78 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Tensor +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorBatching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Blocks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRank + +/-! +# Actual finite tensor rank + +The natural tensor is the diagonal coefficient tensor. Its local restrictions +are exactly the tensors admitting the corresponding number of rank-one terms. +Every finite coefficient tensor has such a decomposition, obtained by expanding +its individual coefficients. Exact rank is therefore a genuine minimum. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper +namespace CoefficientTensor + +/-- The diagonal coefficient tensor for independent scalar products. -/ +abbrev natTensor := MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.natTensor + (K := O) + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (restrict_natTensor rankAtMost_natTensor rankAtMost_iff_natTensor_restricts + natTensor_add_pullback natTensor_add_restricts rankAtMost_blockSum natTensor_restricts_of_le + rankAtMost_mono rank rank_spec rank_le_iff rank_mono rank_product_le rank_blockSum_le + rank_eq_zero_iff unit_restricts_natTensor_one) + +end CoefficientTensor + +namespace TensorRep + +/-- The rank of the tensor in its chosen coordinates. -/ +abbrev rank (T : TensorRep) := MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.rank T + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.Restricts + (rank_le) + +end Restricts + +namespace Equivalent + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.Equivalent + (rank_eq) + +end Equivalent + +end TensorRep + +namespace TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (rank rank_ofRep rank_mono rank_ofTensor) + +end TensorClass + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/RankOrder.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/RankOrder.lean new file mode 100644 index 0000000000..f980076ed0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/RankOrder.lean @@ -0,0 +1,46 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRankOrder + +/-! +# Rank bounds and the concrete tensor order + +Natural numbers in the quotient semiring are precisely the diagonal tensors. +These lemmas connect ordinary finite decompositions to the order used by states. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.CoefficientTensor + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (ofTensor_zero natCast_eq_ofTensor_natTensor rank_add_le rank_mul_le le_rank_natCast + rank_eq_zero_iff mul_le_rank_mul) + +namespace Character + +theorem map_natCast (f : Character) (n : ℕ) : f n = n := + TensorSpectrum.TensorClass.Character.map_natCast f n + +theorem le_rank (f : Character) (A : TensorClass) : f A ≤ TensorSpectrum.TensorClass.rank A := + TensorSpectrum.TensorClass.Character.le_rank f A + +end Character + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Semiring.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Semiring.lean new file mode 100644 index 0000000000..54938f1b27 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/Upper/Tensor/Semiring.lean @@ -0,0 +1,67 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Tensor.Blocks +public import Mathlib.Logic.Equiv.Sum +public import Mathlib.Logic.Equiv.Prod +public import Mathlib.Algebra.Ring.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassSemiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassCharacter + +/-! +# The semiring of actual finite tensors + +Every law is obtained from an explicit coordinate relabeling. The quotient +identifies mutual restriction, not numerical ranks or an abstract tensor model. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent.Integral + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.CoefficientTensor +open scoped NNReal + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (ofTensor_add ofTensor_mul add_comm_aux add_assoc_aux zero_add_aux mul_comm_aux + mul_assoc_aux one_mul_aux zero_mul_aux left_distrib_aux add_mono mul_mono zero_le) + +/-- The empty tensor over the coefficient ring. -/ +abbrev emptyTensor := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.emptyTensor (K := O) + +/-- The unit tensor over the coefficient ring. -/ +abbrev unitTensor := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.unitTensor (K := O) + +/-- An order-preserving semiring homomorphism on these tensor classes. -/ +abbrev Character := MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character O + +namespace Character + +/-- The semiring homomorphism underlying the character. -/ +abbrev toHom (f : Character) : TensorClass →+* ℝ≥0 := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character.toHom f + +/-- Characters preserve the restriction order. -/ +theorem monotone' (f : Character) : Monotone f.toHom := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character.monotone' f + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character + (map_zero map_one map_add map_mul) + +end Character + +end MatrixMultiplicationAllFields.MatrixExponent.Integral.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/UpperBound.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/UpperBound.lean new file mode 100644 index 0000000000..d4c9d4746a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/UpperBound.lean @@ -0,0 +1,376 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.RankDescent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Comparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Nodes +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensor +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.LinearAlgebra.FreeModule.PID +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.WeightedGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Support +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Growth + +/-! Strict comparison for two elements that dominate the unit. -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +open scoped NNReal +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +/-- On the subsemiring of zero and the elements dominating one, every +nonzero element dominates one. Characters extend by translating by one. -/ +theorem strictComparison [Nontrivial S] + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + (hmul : ∀ a b c : S, a ≤ b → c * a ≤ c * b) + {x y : S} (hzero : ∀ a : S, 0 ≤ a) (hbound : ∀ a : S, ∃ n : ℕ, a ≤ (n : S)) + (hx : 1 ≤ x) (hy : 1 ≤ y) + (h : ∀ f : S →+* ℝ≥0, Monotone f → f x < f y) : + ∃ C : ℕ, ∀ r : ℕ, x ^ r ≤ (C : S) * y ^ r := by + have grow (a b : S) : b ≤ a + b := by simpa using hadd 0 a b (hzero a) + let T : Subsemiring S := + { carrier := {a | a = 0 ∨ 1 ≤ a} + zero_mem' := .inl rfl + one_mem' := .inr le_rfl + add_mem' := by + rintro a b ha (rfl | hb) + · simpa using ha + · exact .inr (hb.trans (grow a b)) + mul_mem' := by + rintro a b (rfl | ha) hb + · exact .inl (zero_mul _) + rcases hb with rfl | hb + · exact .inl (mul_zero _) + · exact .inr (ha.trans (by simpa using hmul 1 b a hb)) } + let X : T := ⟨x, .inr hx⟩ + let Y : T := ⟨y, .inr hy⟩ + have hn : Y ≠ 0 := by + intro he + have : y = 0 := congrArg Subtype.val he + exact one_ne_zero (le_antisymm (this ▸ hy) (hzero 1)) + have cmp (f : T →+* ℝ≥0) (hf : Monotone f) : f X < f Y := by + let up (a : S) : T := ⟨a + 1, .inr (grow a 1)⟩ + let g (a : S) := f (up a) - 1 + have plus (a : S) : g a + 1 = f (up a) := + tsub_add_cancel_of_le (by simpa using hf (show 1 ≤ up a from grow a 1)) + have ext (a : T) : g a = f a := by simp [g, show up a = a + 1 from rfl] + have add (a b : S) : g (a + b) = g a + g b := by + have e : up (a + b) + 1 = up a + up b := by + apply Subtype.ext + change a + b + 1 + 1 = (a + 1) + (b + 1) + ring + have e' := congrArg f e + simp only [map_add, map_one, ← plus] at e' + exact add_right_cancel (add_right_cancel (e'.trans (by ring))) + have mul (a b : S) : g (a * b) = g a * g b := by + have e : up (a * b + a + b) = up a * up b := + Subtype.ext (by change a * b + a + b + 1 = (a + 1) * (b + 1); ring) + have e' := congrArg f e + simp only [map_mul, ← plus, add] at e' + exact add_right_cancel (add_right_cancel (add_right_cancel (e'.trans (by ring)))) + let G : S →+* ℝ≥0 := + { toFun := g + map_add' := add + map_mul' := mul + map_one' := (ext 1).trans (map_one f) + map_zero' := (ext 0).trans (map_zero f) } + have hm : Monotone G := + fun _ _ hab => tsub_le_tsub_right (hf (hadd _ _ 1 hab)) _ + rw [← ext X, ← ext Y] + exact h G hm + obtain ⟨C, hC⟩ := Spectrum.strictComparison (S := T) (fun a b c => hadd a b c) + (fun a b c => hmul a b c) (fun a => hzero a) + (fun a ha => a.property.resolve_left (fun e => ha (Subtype.ext e))) + (fun a => hbound a) hn cmp + exact ⟨C, hC⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Integral +end + +section +/- A rank decomposition over the algebraic integers uses a finite order. +Descending from that order costs the same constant for every tensor power. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +variable {i j k r : ℕ} + +private theorem Rank.pow {A : Type*} [CommRing A] (h : Rank A i j k r) (n : ℕ) : + Rank A (i ^ n) (j ^ n) (k ^ n) (r ^ n) := + Rectangle.RankLE.pow h n + +/-- Put every coefficient in a single finite torsion-free ℤ-algebra. -/ +private theorem in_order (h : Rank O i j k r) : + ∃ A : Subalgebra ℤ O, Module.Finite ℤ A ∧ Rank A i j k r := by + obtain ⟨a, b, c, h⟩ := h + let S := Set.range (Function.uncurry a) ∪ Set.range (Function.uncurry b) ∪ + Set.range (Function.uncurry c) + let A := Algebra.adjoin ℤ S + have hf : S.Finite := ((Set.finite_range _).union (Set.finite_range _)).union (Set.finite_range _) + refine ⟨A, Algebra.finite_adjoin_of_finite_of_isIntegral hf + (fun x _ => Algebra.IsIntegral.isIntegral x), ?_⟩ + refine ⟨fun t x => ⟨a t x, Algebra.subset_adjoin (.inl (.inl ⟨(t, x), rfl⟩))⟩, + fun t y => ⟨b t y, Algebra.subset_adjoin (.inl (.inr ⟨(t, y), rfl⟩))⟩, + fun t z => ⟨c t z, Algebra.subset_adjoin (.inr ⟨(t, z), rfl⟩)⟩, ?_⟩ + intro x y z + apply Subtype.val_injective + change A.val _ = A.val _ + rw [map_sum, apply_ite A.val, map_one, map_zero] + exact h x y z + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation (Tensor) in +/-- A diagonal entry of the regular representation sends one to one. -/ +private theorem descend {L : Type*} [CommRing L] [Nontrivial L] + [Module.IsTorsionFree ℤ L] [Module.Finite ℤ L] + (h : Rank L i j k r) : Rank ℤ i j k (r * Module.finrank ℤ L ^ 2) := by + classical + let d := Module.finrank ℤ L + let B := Module.finBasis ℤ L + let t : Fin d := ⟨0, Module.finrank_pos⟩ + let π := (B.coord t).comp (LinearMap.mulRight ℤ (B t)) + have hπ : π 1 = 1 := by simp [π] + let T : Tensor ℤ (Pos i k) (Pos k j) (Pos i j) := fun x y z => + if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then 1 else 0 + have hT : Tensor.RankAtMost (fun x y z => algebraMap ℤ L (T x y z)) r := by + obtain ⟨a, b, c, habc⟩ := h + refine ⟨a, b, c, ?_⟩ + funext x y z + simp only [Tensor.rankOne] + dsimp only [T] + rw [habc, apply_ite (algebraMap ℤ L), map_zero, map_one] + obtain ⟨a, b, c, habc⟩ := hT.descend_algebra B π hπ + exact ⟨a, b, c, fun x y z => (congrFun (congrFun (congrFun habc x) y) z).symm⟩ + +/-- Expand the two input legs only after taking powers in the fixed order. -/ +theorem Rank.integer_powers (h : Rank O i j k r) : + ∃ C : ℕ, ∀ n : ℕ, Rank ℤ (i ^ n) (j ^ n) (k ^ n) (C * r ^ n) := by + obtain ⟨A, hf, hh⟩ := in_order h + refine ⟨Module.finrank ℤ A ^ 2, fun n => ?_⟩ + rw [mul_comm] + exact descend (hh.pow n) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral +end + +section +/- # From three nonnegative wire exponents to the rectangular upper bound -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +open Filter Rectangle + +variable {x y z a b c : ℝ} + +private theorem real_weights + (h : ∀ A B C : ℕ, 0 < A → 0 < B → 0 < C → + 4 * (x * B * C + y * A * C + z * A * B) ≤ ((A : ℝ) + B + C) ^ 2) + (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : + 4 * (x * b * c + y * a * c + z * a * b) ≤ (a + b + c) ^ 2 := by + have h₁ := tendsto_nat_ceil_mul_div_atTop ha.le + have h₂ := tendsto_nat_ceil_mul_div_atTop hb.le + have h₃ := tendsto_nat_ceil_mul_div_atTop hc.le + apply le_of_tendsto_of_tendsto + (((((h₂.const_mul x).mul h₃).add ((h₁.const_mul y).mul h₃)).add ((h₁.const_mul z).mul + h₂)).const_mul 4) + (((h₁.add h₂).add h₃).pow 2) + filter_upwards [eventually_gt_atTop (0 : ℝ)] with t ht + have he := h ⌈a * t⌉₊ ⌈b * t⌉₊ ⌈c * t⌉₊ (by positivity) (by positivity) (by positivity) + generalize ⌈a * t⌉₊ = A, ⌈b * t⌉₊ = B, ⌈c * t⌉₊ = C at he ⊢ + field_simp + linarith only [he] + +private theorem ordered (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) (hz : 0 ≤ z) + (h : ∀ s : ℝ, 0 < s → 4 * (a * x + b * y + s * z) * (a * b * s) ≤ ((a + b) * s + a * b) ^ 2) : + a * x + b * y + c * z ≤ benchmark a b c := by + have hq (s : ℝ) (hs : 0 < s) : a * x + b * y + s * z ≤ + a + b + ((a + b) * s - a * b) ^ 2 / (4 * a * b * s) := by + rw [← sub_le_iff_le_add', le_div_iff₀ (by positivity)] + linarith only [h s hs] + unfold benchmark + by_cases he : 0 ≤ (a + b) * c - a * b + · rw [max_eq_left he] + exact hq c hc + · rw [max_eq_right (le_of_not_ge he), zero_pow (by decide : 2 ≠ 0), zero_div, add_zero] + have h' := hq (a * b / (a + b)) (by positivity) + rw [mul_div_cancel₀ _ (by positivity : a + b ≠ 0), sub_self, zero_pow (by decide : 2 ≠ 0), + zero_div, add_zero] at h' + refine le_trans ?_ h' + gcongr + exact (le_div_iff₀ (by positivity)).mpr (by linarith) + +theorem shape_bound (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) (hx' : x ≤ 1) (hy' : y ≤ 1) (hz' : z ≤ 1) + (h : ∀ A B C : ℕ, 0 < A → 0 < B → 0 < C → + 4 * (x * B * C + y * A * C + z * A * B) ≤ ((A : ℝ) + B + C) ^ 2) : + a * x + b * y + c * z ≤ U a b c := by + by_cases he : a = 0 ∨ b = 0 ∨ c = 0 + · rw [U_plane ha hb hc he] + exact add_le_add (add_le_add (mul_le_of_le_one_right ha hx') (mul_le_of_le_one_right hb hy')) + (mul_le_of_le_one_right hc hz') + push Not at he + have ha' := ha.lt_of_ne' he.1 + have hb' := hb.lt_of_ne' he.2.1 + have hc' := hc.lt_of_ne' he.2.2 + have aux (i j k : ℝ) (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + 4 * (i * x + j * y + k * z) * (i * j * k) ≤ ((i + j) * k + i * j) ^ 2 := by + linarith only [real_weights h (mul_pos hj hk) (mul_pos hi hk) (mul_pos hi hj)] + unfold U + split_ifs + · exact ordered ha' hb' hc' hz (fun s hs => aux a b s ha' hb' hs) + · rw [show a * x + b * y + c * z = b * y + c * z + a * x by ring] + apply ordered hb' hc' ha' hx + intro s hs + linarith only [aux s b c hs hb' hc'] + · rw [show a * x + b * y + c * z = c * z + a * x + b * y by ring] + apply ordered hc' ha' hb' hy + intro s hs + linarith only [aux a s c ha' hs hc'] + +end MatrixMultiplicationAllFields.MatrixExponent.Integral +end + +/- # Near-optimal integral rank witnesses -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +open Rectangle Integral.Upper Integral.Upper.TensorClass + +variable {A B : Type*} [CommRing A] [CommRing B] {i j k r : ℕ} + +theorem Rank.map (h : Rank A i j k r) (f : A →+* B) : Rank B i j k r := + Rectangle.RankLE.map h f + +theorem Rank.areas {F : Type*} [Field F] (f : A →+* F) (h : Rank A i j k r) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : max (i * j) (max (i * k) (j * k)) ≤ r := by + have hr : Rectangle.RankLE F i j k r := h.map f + exact max_le (hr.area hk) (max_le (hr.transpose.cycle.area hj) (hr.cycle.area hi)) + +private instance : Nontrivial TensorClass := by + refine ⟨⟨dots 1 1 1, 0, fun he => ?_⟩⟩ + obtain ⟨a, b, c, he⟩ := rank_of_dots (r := 0) (by simpa using he.le) + simpa using he (0, 0) (0, 0) (0, 0) + +variable {a b c s : ℝ} + +private theorem comparison (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + {n r : ℕ} (hn : 2 ≤ n) (hlo : 8 * (n : ℝ) ^ U a b c < r) : + ∃ C : ℕ, ∀ p : ℕ, Rank O ((side n a) ^ p) ((side n b) ^ p) ((side n c) ^ p) (r ^ p * C) := by + let M := dots (side n a) (side n b) (side n c) + have hn' : 0 < n := by omega + have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast hn' + have hr : 0 < (r : ℝ) := lt_trans (by positivity) hlo + have hx : 1 ≤ M := by + simpa only [M, dots, TensorSpectrum.TensorClass.dots, one_mul] using + mul_mono (mul_mono (one_le_dotX (side_pos hn' b)) (one_le_dotY (side_pos hn' a))) + (one_le_dotZ (side_pos hn' c)) + have hy : 1 ≤ (r : TensorClass) := by + rw [← Nat.cast_one (R := TensorClass), natCast_eq_ofTensor_natTensor, + natCast_eq_ofTensor_natTensor] + exact ofTensor_le + (TensorSpectrum.CoefficientTensor.natTensor_restricts_of_le (by exact_mod_cast hr)) + have hp (g : TensorClass →+* NNReal) (hg : Monotone g) : g M < g (r : TensorClass) := by + let f : Character := ⟨g, hg⟩ + have h := shape_bound ha hb hc f.pY_nonneg f.pX_nonneg f.pZ_nonneg + f.pY_le_one f.pX_le_one f.pZ_le_one (fun A B C hA hB hC => by + linarith only [character_bound f B A C hB hA hC]) + rw [map_natCast] + apply NNReal.coe_lt_coe.mp + calc + (g M : ℝ) ≤ 8 * (n : ℝ) ^ (b * f.pX + a * f.pY + c * f.pZ) := price_dots f hn' ha hb hc + _ ≤ 8 * (n : ℝ) ^ U a b c := by gcongr; linarith + _ < r := hlo + obtain ⟨C, hC⟩ := strictComparison + (fun _ _ _ h => add_mono h le_rfl) (fun _ _ _ h => mul_mono le_rfl h) + TensorClass.zero_le (fun A => ⟨TensorSpectrum.TensorClass.rank A, le_rank_natCast A⟩) hx hy hp + refine ⟨C, fun p => rank_of_dots ?_⟩ + rw [dots_power, Nat.cast_mul, Nat.cast_pow, mul_comm] + exact hC p + +/-- Take powers twice. The first removes spectral overhead and the +second removes the cost of descending a fixed finite algebra. -/ +theorem witness (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) (hs : U a b c < s) : + ∃ n i j k r : ℕ, 2 ≤ n ∧ side n a ≤ i ∧ side n b ≤ j ∧ side n c ≤ k ∧ + Rank ℤ i j k r ∧ (r : ℝ) < (n : ℝ) ^ s := by + have hu : 0 ≤ U a b c := by unfold U benchmark; split_ifs <;> positivity + obtain ⟨n, r, hn, hlo, hhi⟩ := price_gap hu hs + obtain ⟨C, hC⟩ := comparison ha hb hc hn hlo + obtain ⟨p, hp, hsize⟩ := absorb_overhead (D := C) hn (lt_trans (by positivity) hlo) hhi + have hr := hC p + have hpos (x : ℝ) : 0 < side n x ^ p := pow_pos (side_pos (by omega) _) _ + have hi := hr.areas (algebraMap O (AlgebraicClosure ℚ)) (hpos a) (hpos b) (hpos c) + have hs' : 0 < ((r ^ p * C : ℕ) : ℝ) := Nat.cast_pos.mpr + ((Nat.mul_pos (hpos a) (hpos b)).trans_le ((le_max_left _ _).trans hi)) + obtain ⟨D, hD⟩ := hr.integer_powers + obtain ⟨q, hq, hbound⟩ := absorb_overhead (D := D) hp hs' hsize + refine ⟨_, _, _, _, _, hq, side_pow (side_pow le_rfl p) q, side_pow (side_pow le_rfl p) q, + side_pow (side_pow le_rfl p) q, hD q, ?_⟩ + rwa [mul_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Integral +end + +section +/- +# Division-free matrix multiplication over commutative rings + +Integral rank witnesses supply the upper bound over every ring. +For the opposite inequality, map a division-free circuit into +a residue field before applying the rectangular field formula. +-/ + +universe u +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +open Rectangle (U) +variable {a b c : ℝ} + +theorem arithmetic_upper (A : Type*) [CommRing A] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + Admissible A a b c (U a b c) := by + intro ε hε + obtain ⟨n, i, j, k, r, hn, hi, hj, hk, hr, hs⟩ := witness ha hb hc (lt_add_of_pos_right _ + (half_pos hε)) + have hpos (x : ℝ) := Rectangle.side_pos (show 0 < n by omega) x + have harea := hr.areas (Int.castRingHom ℚ) + ((hpos a).trans_le hi) ((hpos b).trans_le hj) ((hpos c).trans_le hk) + have h := Rectangle.integral_of_rank hn ha hb hc hi hj hk (hr.map (Int.castRingHom A)) harea hs.le + simpa only [add_assoc, add_halves] using h (ε / 2) (half_pos hε) + +theorem field_lower {A F : Type*} [CommRing A] [Field F] (f : A →+* F) + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + Rectangle.exponent F a b c ≤ exponent A a b c ∧ exponent A a b c ≤ U a b c := by + have hl (s : ℝ) (h : Admissible A a b c s) : Rectangle.exponent F a b c ≤ s := + csInf_le ⟨_, fun _ hs => Rectangle.areas_le_admissible hs⟩ (h.field f) + have hu := arithmetic_upper A ha hb hc + exact ⟨le_csInf ⟨_, hu⟩ hl, csInf_le ⟨_, hl⟩ hu⟩ + +/-- Over a field the two models have identical exponents, independently +of the square and rectangular equality theorems. -/ +theorem agreement (F : Type*) [Field F] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + exponent F a b c = Rectangle.exponent F a b c := by + apply le_antisymm _ (field_lower (RingHom.id F) ha hb hc).1 + by_contra! hlt + obtain ⟨s, hlo, hhi⟩ := exists_between hlt + obtain ⟨n, r, hn, hr, hs⟩ := (Rectangle.exponent_lt_iff_rank ha hb hc).mp hlo + have hpos (x : ℝ) := Rectangle.side_pos (show 0 < n by omega) x + have harea := Rank.areas (RingHom.id F) hr (hpos a) (hpos b) (hpos c) + have hu := Rectangle.integral_of_rank hn ha hb hc le_rfl le_rfl le_rfl hr harea hs.le + exact hhi.not_ge (csInf_le ⟨_, fun _ h => Rectangle.areas_le_admissible (Admissible.field h + (RingHom.id F))⟩ hu) + +theorem of_fields (A : Type u) [CommRing A] [Nontrivial A] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (h : ∀ (F : Type u) [Field F], Rectangle.exponent F a b c = U a b c) : + exponent A a b c = U a b c := by + obtain ⟨I, hI⟩ := Ideal.exists_maximal A + let : Field (A ⧸ I) := Ideal.Quotient.field I + obtain ⟨hl, hu⟩ := field_lower (Ideal.Quotient.mk I) ha hb hc + exact le_antisymm hu ((h _).ge.trans hl) + +end MatrixMultiplicationAllFields.MatrixExponent.Integral +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/WeightedGrowth.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/WeightedGrowth.lean new file mode 100644 index 0000000000..34e209cb7a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Integral/WeightedGrowth.lean @@ -0,0 +1,51 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Tag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.PolynomialDegeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.PolynomialValues +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagPolynomialBranches +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Upper.Character.Permutations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weighted +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialGrowth + +/-! +# The weighted growth bound for actual tensor characters + +Use the optimized tag inequality on the determinant and tripling +degenerations for each leg permutation separately. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Integral +open Rectangle +open Upper Upper.TensorClass + +/-- The character value of convolution with positive input lengths. -/ +abbrev poly (f : Character) (m n : ℕ) : ℝ := + TensorSpectrum.PolynomialGrowth.poly f m n + +theorem poly_row (f : Character) (hp : 0 < f.pX) (m : ℕ) : + Row (fun n => poly f m n ^ (1 / f.pX)) + (fun n => (f (swapYZ (ofTensor (polynomialTensor (m + 1) (n + 1)))) : ℝ) ^ (1 / f.pX)) m := + TensorSpectrum.PolynomialGrowth.poly_row + Character.polynomial_value_pos + Character.shared_tag_optimized_of_pos + Character.determinant_graded_le Character.tripling_graded_le f hp m + +theorem character_bound (f : Character) (A B C : ℕ) (hA : 0 < A) (hB : 0 < B) (hC : 0 < C) : + 4 * (f.pX * B * C + f.pY * A * C + f.pZ * A * B) ≤ ((A : ℝ) + B + C) ^ 2 := + TensorSpectrum.PolynomialGrowth.character_bound + Character.polynomial_value_pos + Character.shared_tag_optimized_of_pos + Character.determinant_graded_le Character.tripling_graded_le + Character.polynomial_value_le f A B C hA hB hC + +end MatrixMultiplicationAllFields.MatrixExponent.Integral diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Iteration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Iteration.lean new file mode 100644 index 0000000000..3798110f64 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Iteration.lean @@ -0,0 +1,174 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.ListBounds +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics + +/-! # Iterating compression at one list width -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent +open Filter + +private theorem clog_bounds {w : ℕ} (hw : 2 ≤ w) : + w ≤ Nat.clog 2 (listBits w) ∧ Nat.clog 2 (listBits w) ≤ w ^ 2 := by + have h : 2 * w ≤ 2 ^ w := by + induction w, hw using Nat.le_induction with + | base => norm_num + | succ k hk ih => rw [pow_succ]; omega + constructor + · have hh := Nat.clog_mono_right 2 + (show 2 ^ w ≤ listBits w from Nat.le_mul_of_pos_left _ (by omega)) + rwa [Nat.clog_pow 2 w (by decide)] at hh + · apply le_trans (b := w + w) _ (by nlinarith) + apply Nat.clog_le_of_le_pow + rw [listBits, pow_add] + exact Nat.mul_le_mul_right _ h + +private theorem large {b : ℝ} (hb : 0 < b) (C : ℝ) : + ∀ᶠ w : ℕ in atTop, 2 ≤ w ∧ C ≤ (w : ℝ) ∧ 4 ≤ (w : ℝ) ^ b ∧ + (w : ℝ) ^ (3 : ℝ) ≤ (listBits w : ℝ) ^ (1 / 40 : ℝ) := by + have ht : Tendsto (fun w : ℕ => (w : ℝ)) atTop atTop := tendsto_natCast_atTop_atTop + have he := isLittleO_rpow_exp_pos_mul_atTop 3 (by positivity : 0 < Real.log 2 / 40) + filter_upwards [eventually_ge_atTop 2, ht.eventually_ge_atTop C, + ((tendsto_rpow_atTop hb).comp ht).eventually_ge_atTop 4, + ht.eventually he.eventuallyLE] with w hw hC hb' he' + refine ⟨hw, hC, hb', ?_⟩ + calc + (w : ℝ) ^ (3 : ℝ) ≤ Real.exp (Real.log 2 / 40 * w) := by + simpa only [Real.norm_of_nonneg (by positivity : 0 ≤ (w : ℝ) ^ (3 : ℝ)), + Real.norm_of_nonneg (Real.exp_nonneg _)] using he' + _ = ((2 : ℝ) ^ w) ^ (1 / 40 : ℝ) := by + rw [Real.rpow_def_of_pos (by positivity), Real.log_pow] + congr 1 + ring + _ ≤ _ := by + apply Real.rpow_le_rpow (by positivity) _ (by positivity) + exact_mod_cast (show 2 ^ w ≤ listBits w from Nat.le_mul_of_pos_left _ (by omega)) + +/-- The lower bound lets us absorb the additive term into the contraction at +*each* step. This avoids estimating a geometric sum at the last step. -/ +private theorem absorb {w h e m γ σ b : ℝ} (hw : 1 ≤ w) + (hh : w ≤ h) (hh' : h ≤ w ^ 2) (hm : 0 ≤ m) (he : 0 ≤ e) + (hlarge : 4 ≤ w ^ b) (hb : 0 < b) (hg : 2 * b ≤ γ) (hs : 2 * b ≤ σ / 2) + (hlower : e * w ^ σ ≤ 3 * m) : + m * h ^ (-γ) + e * h ^ (σ / 4) ≤ m * w ^ (-b) := by + have hw' : 0 < w := zero_lt_one.trans_le hw + have hleft : m * h ^ (-γ) ≤ m * w ^ (-(2 * b)) := + mul_le_mul_of_nonneg_left ((Real.rpow_le_rpow_of_nonpos hw' hh (by linarith)).trans + (Real.rpow_le_rpow_of_exponent_le hw (neg_le_neg hg))) hm + have hright : e * h ^ (σ / 4) ≤ 3 * m * w ^ (-(2 * b)) := by + calc + _ ≤ e * (w ^ 2) ^ (σ / 4) := + mul_le_mul_of_nonneg_left (Real.rpow_le_rpow (hw'.le.trans hh) hh' (by linarith)) he + _ = (e * w ^ σ) * w ^ (-(σ / 2)) := by + rw [← Real.rpow_natCast_mul hw'.le, mul_assoc, ← Real.rpow_add hw'] + congr 2 + ring + _ ≤ 3 * m * w ^ (-(σ / 2)) := mul_le_mul_of_nonneg_right hlower (by positivity) + _ ≤ 3 * m * w ^ (-(2 * b)) := + mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hw (neg_le_neg hs)) + (by positivity) + calc + _ ≤ 4 * (m * w ^ (-(2 * b))) := by linarith + _ ≤ w ^ b * (m * w ^ (-(2 * b))) := mul_le_mul_of_nonneg_right hlarge (by positivity) + _ = m * w ^ (-b) := by + rw [mul_left_comm, ← Real.rpow_add hw', show b + -(2 * b) = -b by ring] + +/-- Fix a number of iterations before choosing the width. The total number +of copies and the size per bit each cost at most an extra exponent of 1/40. -/ +theorem incompatible {P : ℕ → ℕ → ℕ → Prop} + (seed : Seed P) (lower : ManyList P) (compress : Compression P) : False := by + obtain ⟨C, hseed⟩ := seed + obtain ⟨σ, hs, hlower⟩ := lower + obtain ⟨γ, hg, hcompress⟩ := compress (σ / 4) (by positivity) + let b := min γ (σ / 2) / 2 + have hb : 0 < b := half_pos (lt_min hg (half_pos hs)) + have hbg : 2 * b ≤ γ := by dsimp [b]; linarith [min_le_left γ (σ / 2)] + have hbs : 2 * b ≤ σ / 2 := by dsimp [b]; linarith [min_le_right γ (σ / 2)] + obtain ⟨J, hJ⟩ := exists_nat_gt (3 / b) + have hstop : 3 < (J : ℝ) * b := (div_lt_iff₀ hb).mp hJ + have hJpos : 0 < (J : ℝ) := lt_trans (by positivity) hJ + let δ := (1 / 40 : ℝ) / J + have hδ : 0 < δ := div_pos (by norm_num) hJpos + obtain ⟨w, ⟨hw, hC, hbpow, hcube⟩, ⟨m₀, h₀, hm₀⟩, hl, hc⟩ := + ((large hb C).and (hseed.and (hlower.and (hcompress δ hδ)))).exists + let n := listBits w + let h : ℝ := Nat.clog 2 n + have hh : (w : ℝ) ≤ h := by unfold h; exact_mod_cast (clog_bounds hw).1 + have hh' : h ≤ (w : ℝ) ^ 2 := by unfold h; exact_mod_cast (clog_bounds hw).2 + have hw₁ : 1 ≤ (w : ℝ) := by exact_mod_cast (by omega : 1 ≤ w) + have hw₀ : 0 < (w : ℝ) := zero_lt_one.trans_le hw₁ + have hn : 0 < n := by unfold n listBits; positivity + have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast hn + have hn₀ : 0 < (n : ℝ) := zero_lt_one.trans_le hn₁ + have copies {j t : ℕ} (hj : j ≤ J) (ht : (t : ℝ) ≤ (n : ℝ) ^ ((j : ℝ) * δ)) : + (t : ℝ) ≤ (n : ℝ) ^ (1 / 40 : ℝ) := by + apply ht.trans (Real.rpow_le_rpow_of_exponent_le hn₁ ?_) + calc + _ ≤ (J : ℝ) * δ := mul_le_mul_of_nonneg_right (by exact_mod_cast hj) hδ.le + _ = 1 / 40 := by unfold δ; field_simp + have within {t : ℕ} (ht : (t : ℝ) ≤ (n : ℝ) ^ (1 / 40 : ℝ)) : t ≤ n := by + have h : (n : ℝ) ^ (1 / 40 : ℝ) ≤ n := by + simpa using Real.rpow_le_rpow_of_exponent_le hn₁ (by norm_num : (1 / 40 : ℝ) ≤ 1) + exact_mod_cast ht.trans h + have iterate (j : ℕ) (hj : j ≤ J) : + ∃ t m : ℕ, 1 ≤ t ∧ P w t m ∧ (t : ℝ) ≤ (n : ℝ) ^ ((j : ℝ) * δ) ∧ + (m : ℝ) ≤ (t : ℝ) * n * (w : ℝ) ^ (3 - j * b) := by + induction j with + | zero => + refine ⟨1, m₀, le_rfl, h₀, by simp, ?_⟩ + simp only [Nat.cast_zero, Nat.cast_one, zero_mul, sub_zero, one_mul] + calc + _ ≤ C * (n : ℝ) * (w : ℝ) ^ 2 := hm₀ + _ ≤ (w : ℝ) * n * (w : ℝ) ^ 2 := by gcongr + _ = (n : ℝ) * (w : ℝ) ^ (3 : ℝ) := by norm_num; ring + | succ j ih => + have hj' : j ≤ J := Nat.le_of_succ_le hj + obtain ⟨t, m, ht, hp, htj, hmj⟩ := ih hj' + have ht' := copies hj' htj + have hl' := hl t m ht (within ht') hp + have hper : (w : ℝ) ^ (3 - j * b) ≤ (n : ℝ) ^ (1 / 40 : ℝ) := + (Real.rpow_le_rpow_of_exponent_le hw₁ (sub_le_self _ (by positivity))).trans hcube + have hsize : (m : ℝ) ≤ (n : ℝ) ^ (21 / 20 : ℝ) := by + calc + _ ≤ (t : ℝ) * n * (w : ℝ) ^ (3 - j * b) := hmj + _ ≤ (n : ℝ) ^ (1 / 40 : ℝ) * n * (n : ℝ) ^ (1 / 40 : ℝ) := + mul_le_mul (mul_le_mul_of_nonneg_right ht' hn₀.le) hper (by positivity) (by positivity) + _ = (n : ℝ) ^ (21 / 20 : ℝ) := by + rw [show (21 / 20 : ℝ) = 1 / 40 + 1 + 1 / 40 by norm_num, + Real.rpow_add hn₀, Real.rpow_add hn₀, Real.rpow_one] + obtain ⟨d, m', hd, hdδ, hp', hm'⟩ := hc t m ht hp hsize + refine ⟨t * d, m', Nat.mul_pos ht hd, hp', ?_, ?_⟩ + · rw [Nat.cast_mul, Nat.cast_succ, add_mul, one_mul, Real.rpow_add hn₀] + exact mul_le_mul htj hdδ (by positivity) (by positivity) + · calc + _ ≤ (d : ℝ) * ((m : ℝ) * h ^ (-γ) + t * (n : ℝ) * h ^ (σ / 4)) := hm' + _ ≤ (d : ℝ) * ((m : ℝ) * (w : ℝ) ^ (-b)) := + mul_le_mul_of_nonneg_left + (absorb hw₁ hh hh' (by positivity) (by positivity) hbpow hb hbg hbs hl'.le) + (by positivity) + _ ≤ (d : ℝ) * ((t : ℝ) * n * (w : ℝ) ^ (3 - j * b) * (w : ℝ) ^ (-b)) := by gcongr + _ = ((t * d : ℕ) : ℝ) * n * (w : ℝ) ^ (3 - (j.succ : ℝ) * b) := by + rw [Nat.cast_mul, Nat.cast_succ, show 3 - ((j : ℝ) + 1) * b = + (3 - (j : ℝ) * b) + -b by ring, Real.rpow_add hw₀] + ring + obtain ⟨t, m, ht, hp, htJ, hmJ⟩ := iterate J le_rfl + apply (hl t m ht (within (copies le_rfl htJ)) hp).not_ge + have hfinal : (m : ℝ) ≤ (t : ℝ) * n := by + apply hmJ.trans + exact mul_le_of_le_one_right (by positivity) + (Real.rpow_le_one_of_one_le_of_nonpos hw₁ (by linarith)) + have hthree : 3 ≤ (w : ℝ) ^ σ := (by linarith : 3 ≤ (w : ℝ) ^ b).trans + (Real.rpow_le_rpow_of_exponent_le hw₁ (by linarith)) + calc + 3 * (m : ℝ) = (m : ℝ) * 3 := mul_comm _ _ + _ ≤ (t : ℝ) * n * (w : ℝ) ^ σ := mul_le_mul hfinal hthree (by norm_num) (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/ListBounds.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/ListBounds.lean new file mode 100644 index 0000000000..3cdbec5da7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/ListBounds.lean @@ -0,0 +1,49 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Real + +/-! +# Bounds on independent lists + +Here `P w t m` means that the `t`-fold tensor power at width `w` admits +an exact realization of size `m`. The three premises only use this family. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent +open Filter + +/-- A list contains `2^w` records, each with `2*w` bits. -/ +def listBits (w : ℕ) : ℕ := 2 * w * 2 ^ w + +/-- The condition `∃ C : ℝ, ∀ᶠ w : ℕ in atTop, ∃ m : ℕ, P w 1 m ∧ (m : ℝ) ≤ C * listBits w * (w +: ℝ) ^ 2` on the specified data. -/ +def Seed (P : ℕ → ℕ → ℕ → Prop) : Prop := + ∃ C : ℝ, ∀ᶠ w : ℕ in atTop, ∃ m : ℕ, + P w 1 m ∧ (m : ℝ) ≤ C * listBits w * (w : ℝ) ^ 2 + +/-- The condition `∃ σ : ℝ, 0 < σ ∧ ∀ᶠ w : ℕ in atTop, ∀ t m : ℕ, 1 ≤ t → t ≤ listBits w → P w t +m → (t : ℝ) * listBits w * (w : ℝ) ^ σ < 3 * m` on the specified data. -/ +def ManyList (P : ℕ → ℕ → ℕ → Prop) : Prop := + ∃ σ : ℝ, 0 < σ ∧ ∀ᶠ w : ℕ in atTop, ∀ t m : ℕ, + 1 ≤ t → t ≤ listBits w → P w t m → + (t : ℝ) * listBits w * (w : ℝ) ^ σ < 3 * m + +/-- The compression of type `Prop`, constructed using `Nat.clog 2 (listBits w)`. -/ +def Compression (P : ℕ → ℕ → ℕ → Prop) : Prop := + ∀ η : ℝ, 0 < η → ∃ γ : ℝ, 0 < γ ∧ ∀ δ : ℝ, 0 < δ → + ∀ᶠ w : ℕ in atTop, ∀ t m : ℕ, 1 ≤ t → P w t m → + (m : ℝ) ≤ (listBits w : ℝ) ^ (21 / 20 : ℝ) → + ∃ d m' : ℕ, 1 ≤ d ∧ (d : ℝ) ≤ (listBits w : ℝ) ^ δ ∧ + P w (t * d) m' ∧ + let h : ℝ := Nat.clog 2 (listBits w) + (m' : ℝ) ≤ d * ((m : ℝ) * h ^ (-γ) + t * (listBits w : ℝ) * h ^ η) + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/LocalTensor.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/LocalTensor.lean new file mode 100644 index 0000000000..417061bf97 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/LocalTensor.lean @@ -0,0 +1,39 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition + +/-! # Tensor restrictions along separate linear maps -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.LocalTensor + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +variable {K X Y Z X' Y' Z' : Type*} [CommSemiring K] [Fintype X] [Fintype Y] [Fintype Z] + +/-- Tensors obtained by a linear map on each of the three factors. -/ +def orbit (T : Tensor K X Y Z) : Set (Tensor K X' Y' Z') := + {U | ∃ (A : X' → X → K) (B : Y' → Y → K) (C : Z' → Z → K), + U = Tensor.restrict A B C T} + +theorem restrict_mem {X'' Y'' Z'' : Type*} [Fintype X'] [Fintype Y'] [Fintype Z'] + {T : Tensor K X Y Z} {U : Tensor K X' Y' Z'} (h : U ∈ orbit T) + (D : X'' → X' → K) (E : Y'' → Y' → K) (F : Z'' → Z' → K) : + Tensor.restrict D E F U ∈ orbit T := by + obtain ⟨A, B, C, rfl⟩ := h + exact ⟨_, _, _, Tensor.restrict_restrict A B C D E F T⟩ + +theorem orbit_trans {X'' Y'' Z'' : Type*} [Fintype X'] [Fintype Y'] [Fintype Z'] + {T : Tensor K X Y Z} {U : Tensor K X' Y' Z'} {V : Tensor K X'' Y'' Z''} + (hTU : U ∈ orbit T) (hUV : V ∈ orbit U) : V ∈ orbit T := by + obtain ⟨a, b, c, rfl⟩ := hUV + exact restrict_mem hTU a b c + +end MatrixMultiplicationAllFields.MatrixExponent.LocalTensor diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Counter.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Counter.lean new file mode 100644 index 0000000000..8a6ef3a453 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Counter.lean @@ -0,0 +1,101 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Defs + +/-! +# Binary counts + +The first bit is least significant. Ripple carry and the unary field +weights both use a number of vertices linear in the number of bits. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- Join one output bundle to an input without charging for identity gates +on the untouched exterior bundles. -/ +theorem DNet.plug {F : Type} [Field F] {a b c d e : Wire} {m n : ℕ} + {f : Val a → Val (.pair b c)} {g : Val (.pair c d) → Val e} + (h : DNet F a (.pair b c) f m) (k : DNet F (.pair c d) e g n) : + DNet F (.pair a d) (.pair b e) (fun x => ((f x.1).1, g ((f x.1).2, x.2))) (m + n) := by + obtain ⟨v, hv, h⟩ := h + obtain ⟨w, hw, k⟩ := k + refine ⟨_, Nat.add_le_add hv hw, ?_⟩ + have rin := (Rewire.assoc a d c).comp ((Rewire.id a).par (Rewire.swap d c)) + have rout := ((Rewire.assoc b e c).comp + ((Rewire.id b).par (Rewire.swap e c))).comp (Rewire.assoc' b c e) + have ht := (((h.par k).pre rin).post rout).trace + convert ht using 1 + funext x y + simp only [Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul] + by_cases he : (f x.1).1 = y.1 <;> simp [he] + +namespace Lookup + +private theorem value_zero (n : ℕ) : value n (zero n) = 0 := by + induction n with + | zero => rfl + | succ n ih => simp [value, zero, ih] + +private theorem value_inc (n : ℕ) (x : Val (word n)) (h : value n x + 1 < 2 ^ n) : + value n (inc n x) = value n x + 1 := by + induction n with + | zero => simp [value] at h + | succ n ih => + obtain ⟨b, y⟩ := x + cases b + · simp [inc, value, Nat.add_comm] + · have hy : value n y + 1 < 2 ^ n := by + simp [value, pow_succ] at h + omega + simp [inc, value, ih y hy] + omega + +theorem value_bits {n k : ℕ} (h : k < 2 ^ n) : value n (bits n k) = k := by + induction k with + | zero => exact value_zero n + | succ k ih => + have he := ih (by omega) + rw [bits, Function.iterate_succ_apply', ← bits, value_inc _ _ (by omega), he] + +variable (F : Type) [Field F] + +private theorem carry_net (n : ℕ) : + DNet F (.pair .bit (word n)) (word n) + (fun x => if x.1 then inc n x.2 else x.2) (4 * n + 1) := by + induction n with + | zero => exact DNet.table F _ _ _ (by decide) + | succ n ih => + have sum := DNet.table F (.pair .bit .bit) .bit + (fun x => if x.1 then !x.2 else x.2) (by decide) + have carry := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 && x.2) (by decide) + have h := ((sum.pair carry).plug ih).pre (Rewire.assoc' .bit .bit (word n)) + convert h.mono (n := 4 * (n + 1) + 1) (by simp only [wd]; omega) using 1 + funext ⟨c, b, x⟩ + cases c <;> cases b <;> rfl + +theorem inc_net (n : ℕ) : DNet F (word n) (word n) (inc n) (100 * (1 + n)) := by + cases n with + | zero => exact (DNet.table F _ _ _ (by decide)).mono (by decide) + | succ n => + have h := DNet.table F .bit (.pair .bit .bit) (fun b => (!b, b)) (by decide) + exact (h.plug (carry_net F n)).mono (by omega) + +theorem weight_net (n : ℕ) (z : F) : + Net F .unit (word n) (fun _ y => z ^ value n y) n := by + induction n generalizing z with + | zero => simpa [value] using (Net.empty (F := F)) + | succ n ih => + have h := Net.table (F := F) .unit .bit (fun _ b => z ^ b.toNat) (by decide) + have hh := (h.par (ih (z ^ 2))).pre (Rewire.unit' .unit) + simpa [value, pow_add, pow_mul, Nat.add_comm] using hh + +end Lookup +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Defs.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Defs.lean new file mode 100644 index 0000000000..4844507f11 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Defs.lean @@ -0,0 +1,91 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FunctionNetwork + +/-! +# Sorting dictionary and query records + +A dictionary row has its marker set and carries a count as payload. A query +row has zero padding. At a given key, all its queries precede the unique +dictionary row. The sorting hypothesis below concerns only inputs of this +form and requires the complete ordered output. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Lookup + +/-- The quantity computed by `word (wd a + 1)`. -/ +abbrev count (a : Wire) := word (wd a + 1) +/-- Computes the row by the application `Wire.pair a (.pair .bit (count a))`. -/ +abbrev row (a : Wire) := Wire.pair a (.pair .bit (count a)) +/-- Computes the state by the application `Wire.pair .bit (count a)`. -/ +abbrev state (a : Wire) := Wire.pair .bit (count a) + +/-- In the case `0`, this construction gives `()`. -/ +def zero : (n : ℕ) → Val (word n) + | 0 => () + | n + 1 => (false, zero n) + +/-- In the case `0, _`, this construction gives `()`. -/ +def inc : (n : ℕ) → Val (word n) → Val (word n) + | 0, _ => () + | n + 1, x => (!x.1, if x.1 then inc n x.2 else x.2) + +/-- In the case `0, _`, this construction gives `0`. -/ +def value : (n : ℕ) → Val (word n) → ℕ + | 0, _ => 0 + | n + 1, x => x.1.toNat + 2 * value n x.2 + +/-- The value specified by `(inc n)^[k] (zero n)`. -/ +def bits (n k : ℕ) : Val (word n) := (inc n)^[k] (zero n) + +/-- Returns `(s.1 && decide (s.2 = r.2.2), zero _)` when `r.2.1` holds, and `(s.1, inc _ s.2)` +otherwise. -/ +def step (a : Wire) (s : Val (state a)) (r : Val (row a)) : Val (state a) := + if r.2.1 then (s.1 && decide (s.2 = r.2.2), zero _) else (s.1, inc _ s.2) + +/-- The value specified by `((flatten l x).foldl (step a) (true, zero _)).1`. -/ +def scan (a : Wire) (l : ℕ) (x : Val (tree l (row a))) : Bool := + ((flatten l x).foldl (step a) (true, zero _)).1 + +/-- The value specified by `(x, false, zero _)`. -/ +def query (a : Wire) (x : Val a) : Val (row a) := (x, false, zero _) + +/-- In the case `0, x`, this construction gives `query a x`. -/ +def queries (a : Wire) : (l : ℕ) → Val (tree l a) → Val (tree l (row a)) + | 0, x => query a x + | l + 1, x => (queries a l x.1, queries a l x.2) + +/-- In the case `0, z, c`, this construction gives `(z, true, c)`. -/ +def dict (a : Wire) : + (l : ℕ) → Val (tree l a) → Val (tree l (count a)) → Val (tree l (row a)) + | 0, z, c => (z, true, c) + | l + 1, z, c => (dict a l z.1 c.1, dict a l z.2 c.2) + +/-- Concatenates the components in the order `List.replicate (xs.count r.1) (query a r.1) ++ +[r]`. -/ +def group (a : Wire) (xs : List (Val a)) (r : Val (row a)) : List (Val (row a)) := + List.replicate (xs.count r.1) (query a r.1) ++ [r] + +/-- The ordinary-width sorting bound restricted to dictionary and query rows. +The keys enumerate all addresses once in key order. The second sort key is +the dictionary marker. Identical query rows require no tie breaking. -/ +def Sorting (F : Type) [Field F] (p : ℝ) : Prop := + ∃ C : ℝ, ∀ a : Wire, let t := wd a + ∃ (keys : Val (tree t a)) + (sort : Val (tree (t + 1) (row a)) → Val (tree (t + 1) (row a))) (m : ℕ), + (flatten t keys).Nodup ∧ (∀ z : Val a, z ∈ flatten t keys) ∧ + DNet F (tree (t + 1) (row a)) (tree (t + 1) (row a)) sort m ∧ + (m : ℝ) ≤ C * (2 : ℝ) ^ t * (1 + (t : ℝ)) ^ p ∧ + ∀ (x : Val (tree t a)) (c : Val (tree t (count a))), + flatten (t + 1) (sort (queries a t x, dict a t keys c)) = + (flatten t (dict a t keys c)).flatMap (group a (flatten t x)) + +end MatrixMultiplicationAllFields.MatrixExponent.Lookup diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Network.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Network.lean new file mode 100644 index 0000000000..2f53853089 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Network.lean @@ -0,0 +1,90 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Single +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Substitute + +/-! +# Substituting batched lookups into a wide network + +A vertex of arity `t` uses batches of `2^t` copies. Repeating these to reach +a common batch size `2^u` costs at most a constant times `(1 + u)^(p - 1)` +per incident bit per copy, with one extra unit per vertex. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Lookup + +variable {K : Type} [Field K] {a b : Wire} + +private def paired (k : Val a → Val b → K) (x : Val (.pair a b)) (_ : Val .unit) : K := + k x.1 x.2 + +private theorem power_paired (k : Val a → Val b → K) (d : ℕ) + (x : Val (.pair (copies a d) (copies b d))) : + power (paired k) d (zipCopies a b d x) (unitCopies d) = power k d x.1 x.2 := by + induction d with + | zero => rfl + | succ d ih => simp only [power, paired, zipCopies, unitCopies, ih] + +private theorem split_batch {k : Val a → Val b → K} {t v : ℕ} + (h : Net K (tree t (.pair a b)) .unit + (fun x _ => ((flatten t x).map (fun z => k z.1 z.2)).prod) v) : + Net K (copies a (2 ^ t)) (copies b (2 ^ t)) (power k (2 ^ t)) (v + 2 ^ t * wd b) := by + let d := 2 ^ t + have g : Net K (copies (.pair a b) d) (copies .unit d) (power (paired k) d) v := + h.rewire (.treeCopies (.pair a b) t) (.unitCopies d) + (fun x _ => power_tree (paired k) t x (unitCopies d)) + have j := (g.pre (.zipCopies a b d)).post (.unitCopies d) + simp only [power_paired] at j + simpa only [wd_copies] using j.curry + +private theorem vertex_cost {C p : ℝ} (hC : 1 ≤ C) (hp : 1 ≤ p) {t u v b : ℕ} + (ht : t ≤ u) (hb : b ≤ t) (hv : (v : ℝ) ≤ C * (2 : ℝ) ^ t * (1 + (t : ℝ)) ^ p) : + ((2 ^ (u - t) * (v + 2 ^ t * b) : ℕ) : ℝ) ≤ + (C + 1) * (2 : ℝ) ^ u * (1 + (u : ℝ)) ^ (p - 1) * (1 + (t : ℝ)) := by + have hbase : 1 ≤ 1 + (t : ℝ) := by simp + have hb' : (b : ℝ) ≤ (1 + (t : ℝ)) ^ p := calc + (b : ℝ) ≤ (t : ℝ) := by exact_mod_cast hb + _ ≤ 1 + (t : ℝ) := by linarith + _ ≤ _ := by simpa using Real.rpow_le_rpow_of_exponent_le hbase hp + have hpow : (2 : ℝ) ^ (u - t) * 2 ^ t = 2 ^ u := by rw [← pow_add, Nat.sub_add_cancel ht] + have hsplit : (1 + (t : ℝ)) ^ p = (1 + (t : ℝ)) ^ (p - 1) * (1 + (t : ℝ)) := by + rw [Real.rpow_sub (by positivity), Real.rpow_one, div_mul_cancel₀ _ (by positivity)] + push_cast + calc + _ ≤ 2 ^ (u - t) * (C * 2 ^ t * (1 + (t : ℝ)) ^ p + 2 ^ t * (1 + (t : ℝ)) ^ p) := by gcongr + _ = (C + 1) * (2 : ℝ) ^ u * (1 + (t : ℝ)) ^ (p - 1) * (1 + (t : ℝ)) + := by rw [← hpow, hsplit]; ring + _ ≤ _ := by gcongr + +/-- A uniform sorting bound suffices for arbitrary labels and all extensions. -/ +theorem lookup_network {F : Type} [Field F] {p : ℝ} (hp : 1 ≤ p) (hs : Sorting F p) : + ∃ C : ℝ, 1 ≤ C ∧ ∀ (K : Type) (_ : Field K) (_ : Algebra F K) + (u : ℕ) (L : Set (Table K)) (a b : Wire) (k : Val a → Val b → K) (s : ℕ), + Wide K u L a b k s → + ∃ v : ℕ, Net K (copies a (2 ^ u)) (copies b (2 ^ u)) (power k (2 ^ u)) v ∧ + (v : ℝ) ≤ C * (2 : ℝ) ^ u * s * (1 + (u : ℝ)) ^ (p - 1) := by + obtain ⟨C, hC, batch⟩ := lookup_net hp hs + refine ⟨C + 1, by linarith, ?_⟩ + intro K fk ak u L a b k s h + rw [mul_right_comm ((C + 1) * (2 : ℝ) ^ u)] + apply h.substitute + intro A B f hab + let t := wd A + wd B + obtain ⟨v, hv, hb⟩ := batch K fk ak (.pair A B) (fun z => f z.1 z.2) + let d := 2 ^ (u - t) + refine ⟨d * (v + 2 ^ t * wd B), ?_, vertex_cost hC hp hab (Nat.le_add_left _ _) hb⟩ + have hpow : 2 ^ t * d = 2 ^ u := by dsimp [d, t]; rw [← pow_add, Nat.add_sub_of_le hab] + rw [← hpow] + exact ((split_batch (k := f) hv).power d).rewire + (.joinCopies A (2 ^ t) d) (.joinCopies B (2 ^ t) d) (power_join f (2 ^ t) d) + +end MatrixMultiplicationAllFields.MatrixExponent.Lookup diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Scan.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Scan.lean new file mode 100644 index 0000000000..f660efbd72 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Scan.lean @@ -0,0 +1,296 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Counter +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.AdjacentDuplicates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortOne +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BitonicMerge +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.ShortTag +public import Mathlib.Data.Finset.Sort + +/-! # Grouping the queries gives a sorted permutation of the input rows -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Lookup + +private theorem flatten_queries (a : Wire) (l : ℕ) (x : Val (tree l a)) : + flatten l (queries a l x) = (flatten l x).map (query a) := by + induction l with + | zero => rfl + | succ l ih => simp [flatten, queries, ih] + +private theorem dict_keys (a : Wire) (l : ℕ) (z : Val (tree l a)) + (c : Val (tree l (count a))) : + (flatten l (dict a l z c)).map Prod.fst = flatten l z := by + induction l with + | zero => rfl + | succ l ih => simp [flatten, dict, ih] + +private theorem dict_marker (a : Wire) (l : ℕ) (z : Val (tree l a)) + (c : Val (tree l (count a))) (r : Val (row a)) + (hr : r ∈ flatten l (dict a l z c)) : r.2.1 = true := by + induction l with + | zero => rw [List.mem_singleton.mp hr]; rfl + | succ l ih => + rcases List.mem_append.mp hr with hr | hr + · exact ih _ _ hr + · exact ih _ _ hr + +private theorem perm_repeats (a : Wire) (xs zs : List (Val a)) (hn : zs.Nodup) + (hall : ∀ y, y ∈ zs) : + (zs.flatMap fun y => List.replicate (xs.count y) y).Perm xs := by + apply List.perm_iff_count.mpr + intro y + rw [List.count_flatMap, ← List.sum_toFinset _ hn] + simp [List.count_replicate, hall] + +theorem group_perm (a : Wire) (l : ℕ) (x z : Val (tree l a)) (c : Val (tree l (count a))) + (hn : (flatten l z).Nodup) (hall : ∀ y : Val a, y ∈ flatten l z) : + ((flatten l (dict a l z c)).flatMap (group a (flatten l x))).Perm + (flatten (l + 1) (a := row a) (queries a l x, dict a l z c)) := by + let rs := flatten l (dict a l z c) + let xs := flatten l x + have h := (perm_repeats a xs (flatten l z) hn hall).map (query a) + rw [← dict_keys a l z c, List.map_flatMap, List.flatMap_map] at h + simp only [List.map_replicate] at h + have p := List.flatMap_append_perm rs (fun r => List.replicate (xs.count r.1) (query a r.1)) + (fun r => [r]) + rw [flatten, flatten_queries] + exact p.symm.trans (h.append (by simp [rs])) + +private theorem key_eq (a : Wire) {xs : List (Val a)} {r q : Val (row a)} + (h : q ∈ group a xs r) : q.1 = r.1 := by + rcases List.mem_append.mp h with h | h + · rw [List.eq_of_mem_replicate h]; rfl + · rw [List.mem_singleton.mp h] + +theorem group_sorted (a : Wire) [LinearOrder (Val a)] (l : ℕ) (x z : Val (tree l a)) + (c : Val (tree l (count a))) (R : Val (row a) → Val (row a) → Prop) + (hr : ∀ i, R i i) (hq : ∀ y u, R (query a y) (y, true, u)) + (hkey : ∀ i j, i.1 < j.1 → R i j) (hs : (flatten l z).Pairwise (· < ·)) : + ((flatten l (dict a l z c)).flatMap (group a (flatten l x))).Pairwise R := by + refine List.pairwise_flatMap.mpr ⟨?_, ?_⟩ + · intro r hm + have he := dict_marker a l z c r hm + refine List.pairwise_append.mpr ⟨List.pairwise_replicate.mpr (.inr (hr _)), by simp, ?_⟩ + intro q hq' d hd + rw [List.eq_of_mem_replicate hq', List.mem_singleton.mp hd] + simpa only [← he, Prod.eta] using hq r.1 r.2.2 + · rw [← dict_keys a l z c, List.pairwise_map] at hs + refine hs.imp fun h i hi j hj => hkey i j ?_ + rw [key_eq a hi, key_eq a hj] + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Lookup +end + +section +/- +# Scanning dictionary rows + +Two adjacent blocks share only a counter and a validity bit. Joining their +networks along those wires avoids copying either block of rows. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Lookup + +variable (F : Type) [Field F] + +theorem const_net (a : Wire) (x : Val a) : DNet F .unit a (fun _ => x) (wd a) := by + induction a with + | unit => exact DNet.id F .unit + | bit => exact DNet.table F _ _ _ (by decide) + | pair a b ha hb => exact ((ha x.1).par (hb x.2)).pre (.unit' .unit) + +theorem eq_net (n : ℕ) : + DNet F (.pair (word n) (word n)) .bit (fun x => decide (x.1 = x.2)) (2 * n + 1) := by + induction n with + | zero => exact DNet.table F _ _ _ (by decide) + | succ n ih => + have head := DNet.table F (.pair .bit .bit) .bit (fun x => decide (x.1 = x.2)) (by decide) + have both := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 && x.2) (by decide) + have h := ((head.par ih).pre (.middle .bit (word n) .bit (word n))).comp both + convert h.mono (n := 2 * (n + 1) + 1) (by omega) using 1 + +private theorem step_net (a : Wire) : + DNet F (.pair (state a) (row a)) (state a) (fun x => step a x.1 x.2) + (500 * (1 + wd a)) := by + have old := DNet.fst F (state a) (row a) + have payload := (DNet.snd F (state a) (row a)).comp (DNet.snd F a (state a)) + have flag := DNet.fst F .bit (count a) + have counter := DNet.snd F .bit (count a) + have check := ((old.comp counter).pair (payload.comp counter)).comp (eq_net F (wd a + 1)) + have both := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 && x.2) (by decide) + have reset := (DNet.discard F (.pair (state a) (row a))).comp + (const_net F (count a) (zero _)) + have yes := (((old.comp flag).pair check).comp both).pair reset + have no := old.comp ((DNet.id F .bit).par (inc_net F (wd a + 1))) + have h := ((yes.pair no).pair (payload.comp flag)).comp (selectWord F (wd a + 2)) + exact h.mono (by simp only [wd, wd_word]; omega) + +theorem fold_net {a s : Wire} {f : Val s → Val a → Val s} {m : ℕ} + (h : DNet F (.pair s a) s (fun x => f x.1 x.2) m) (l : ℕ) : + DNet F (.pair s (tree l a)) s (fun x => (flatten l x.2).foldl f x.1) (2 ^ l * m) := by + induction l with + | zero => simpa [flatten] using h + | succ l ih => + have left := ih.post ((Rewire.unit' s).comp (.swap _ _)) + have h' := ((left.plug ih).pre (.assoc' _ _ _)).post ((Rewire.swap _ _).comp (.unit _)) + simpa only [flatten, List.foldl_append, pow_succ, mul_two, add_mul] using h' + +theorem scan_net (a : Wire) (l : ℕ) : + DNet F (tree l (row a)) .bit (scan a l) (1000 * 2 ^ l * (1 + wd a)) := by + have start := const_net F (state a) (true, zero _) + have seed := (start.par (DNet.id F (tree l (row a)))).pre + ((Rewire.unit' _).comp (.swap _ _)) + have h := (seed.comp (fold_net F (step_net F a) l)).comp (DNet.fst F .bit (count a)) + apply h.mono + simp only [wd_tree, wd, wd_word] + have hp : 1 ≤ 2 ^ l := Nat.one_le_pow _ _ (by decide) + nlinarith [Nat.mul_le_mul_right (wd a) hp] + +end MatrixMultiplicationAllFields.MatrixExponent.Lookup +end + +/- +# Ordering the dictionary and query rows + +Read a key's wire positions in a fixed order. After the key comes the +dictionary marker, then the count payload. The marker places every query +before the dictionary row for that same key. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Lookup + +theorem key_encoding (a : Wire) : + ∃ f, Rewire a (word (wd a)) f ∧ Function.Injective f := + Rewire.exists_of_width (wd_word _).symm + +/-- The value specified by `LinearOrder.lift' (key_encoding a).choose (key_encoding +a).choose_spec.2`. -/ +abbrev keyOrder (a : Wire) : LinearOrder (Val a) := + LinearOrder.lift' (key_encoding a).choose (key_encoding a).choose_spec.2 + +/-- The quantity computed by `@Prod.Lex.instLinearOrder _ _ (keyOrder a) (wordOrder (wd a + +2))`. -/ +abbrev rowOrder (a : Wire) : LinearOrder (Val (row a)) := + @Prod.Lex.instLinearOrder _ _ (keyOrder a) (wordOrder (wd a + 2)) + +theorem row_key (a : Wire) (i j : Val (row a)) (h : (keyOrder a).lt i.1 j.1) : + (rowOrder a).le i j := by + exact (@Prod.Lex.toLex_le_toLex _ _ (keyOrder a).toLT (wordOrder (wd a + + 2)).toLE i j).mpr (.inl h) + +theorem row_query (a : Wire) (y : Val a) (u : Val (count a)) : + (rowOrder a).le (query a y) (y, true, u) := by + refine (@Prod.Lex.toLex_le_toLex _ _ (keyOrder a).toLT (wordOrder (wd a + 2)).toLE + (query a y) (y, true, u)).mpr (.inr ⟨rfl, ?_⟩) + exact (@Prod.Lex.toLex_le_toLex _ _ _ (wordOrder (wd a + 1)).toLE + (false, zero (wd a + 1)) (true, u)).mpr (.inl (show false < true by decide)) + +theorem row_compare (F : Type) [Field F] (a : Wire) : + letI := rowOrder a + DNet F (.pair (row a) (row a)) .bit (fun x => decide (x.1 < x.2)) + (10000 * (wd a + 1)) := by + let _ := keyOrder a + let _ := wordOrder (wd a + 2) + have h := (key_encoding a).choose_spec.1 + have keys : DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) (100 * (wd a + 1)) := + (compare_lt F (wd a)).pre (h.par h) + exact (Tagged.lex_compare keys (compare_lt F (wd a + 2))).mono (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Lookup +end + +section +/- +# From tagged permutations to sorting dictionary and query rows + +At height `w=t+1` the payload has exactly `2w` bits. A sort on whole +rows suffices since the query payloads are all zero and the dictionary +has only one row for each address. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Lookup + +private theorem card_val (a : Wire) : Fintype.card (Val a) = 2 ^ wd a := by + induction a with + | bit => exact Fintype.card_bool + | unit => exact Fintype.card_unit + | pair a b ha hb => simp [Val, wd, pow_add, ha, hb] + +theorem as_tree {a : Wire} (l : ℕ) (xs : List (Val a)) (h : xs.length = 2 ^ l) : + ∃ x : Val (tree l a), flatten l x = xs := by + induction l generalizing xs with + | zero => + obtain ⟨y, rfl⟩ := List.length_eq_one_iff.mp h + exact ⟨y, rfl⟩ + | succ l ih => + rw [pow_succ] at h + obtain ⟨x, hx⟩ := ih (xs.take (2 ^ l)) (by rw [List.length_take, h]; omega) + obtain ⟨y, hy⟩ := ih (xs.drop (2 ^ l)) (by rw [List.length_drop, h]; omega) + exact ⟨(x, y), by simp [flatten, hx, hy]⟩ + +theorem ordered_keys (a : Wire) [LinearOrder (Val a)] : + ∃ z : Val (tree (wd a) a), (flatten (wd a) z).Nodup ∧ + (∀ y : Val a, y ∈ flatten (wd a) z) ∧ (flatten (wd a) z).Pairwise (· < ·) := by + let s : Finset (Val a) := Finset.univ + obtain ⟨z, hz⟩ := as_tree (wd a) (s.sort (· ≤ ·)) (by simp [s, card_val]) + refine ⟨z, ?_⟩ + rw [hz] + exact ⟨s.sort_nodup _, by simp [s], s.sortedLT_sort.pairwise⟩ + +theorem sort_dict (a : Wire) [LinearOrder (Val a)] [L : LinearOrder (Val (row a))] + (hq : ∀ y u, L.le (query a y) (y, true, u)) (hk : ∀ i j : Val (row a), i.1 < j.1 → L.le i j) : + ∃ z : Val (tree (wd a) a), (flatten (wd a) z).Nodup ∧ + (∀ y : Val a, y ∈ flatten (wd a) z) ∧ ∀ x c, + flatten (wd a + 1) (sortTree (a := row a) (wd a + 1) (queries a (wd a) x, dict a (wd a) z c)) + = + (flatten (wd a) (dict a (wd a) z c)).flatMap (group a (flatten (wd a) x)) := by + obtain ⟨z, hn, hall, hs⟩ := ordered_keys a + refine ⟨z, hn, hall, fun x c => ?_⟩ + have g := group_sorted a (wd a) x z c L.le L.le_refl hq hk hs + let input : Val (tree (wd a + 1) (row a)) := (queries a (wd a) x, dict a (wd a) z c) + exact List.Perm.eq_of_pairwise (fun _ _ _ _ => L.le_antisymm _ _) + (sortTree_sorted _ input) g ((sortTree_perm _ input).trans (group_perm _ _ _ _ _ hn hall).symm) + +private theorem cost {p C : ℝ} (hp : 1 ≤ p) {t m : ℕ} + (hm : (m : ℝ) ≤ C * (2 : ℝ) ^ (t + 1) * ((t + 1 : ℕ) : ℝ) ^ p) : + (↑(4 * m + 10000 * 2 ^ (t + 1) * ((t + 1) + 10000 * (t + 1) + 1) : ℕ) : ℝ) ≤ + (8 * C + 200040000) * (2 : ℝ) ^ t * (1 + (t : ℝ)) ^ p := by + push_cast at hm ⊢ + rw [pow_succ, add_comm (t : ℝ) 1] at hm ⊢ + have h : 1 + (t : ℝ) ≤ (1 + (t : ℝ)) ^ p := by + simpa using Real.rpow_le_rpow_of_exponent_le (show 1 ≤ 1 + (t : ℝ) by simp) hp + have e : (1 + (t : ℝ)) + 10000 * (1 + t) + 1 ≤ 10002 * (1 + (t : ℝ)) ^ p := by linarith + have hmul := mul_le_mul_of_nonneg_left e (by positivity : (0 : ℝ) ≤ 2 ^ t) + linarith + +theorem sorting_of_tag {F : Type} [Field F] {p : ℝ} (hp : 1 ≤ p) (h : ShortTag F p) : + Sorting F p := by + obtain ⟨C, hC⟩ := h + refine ⟨8 * C + 200040000, fun a => ?_⟩ + let t := wd a + let _ := keyOrder a + let _ := rowOrder a + obtain ⟨z, hn, hall, he⟩ := sort_dict a (row_query a) (row_key a) + obtain ⟨m, htag, hm⟩ := hC (t + 1) (by omega) + have hw : wd (row a) ≤ 4 * (t + 1) := by simp [wd, t]; omega + have hs := Tagged.sort_one htag hw (row_compare F a) + exact ⟨z, _, _, hn, hall, hs, cost hp hm, he⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Lookup +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/ShortTag.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/ShortTag.lean new file mode 100644 index 0000000000..6b111b2822 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/ShortTag.lean @@ -0,0 +1,23 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Tags + +/-! # Width estimates for tagged permutations -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Lookup + +/-- The ordinary-width tagged permutation estimate. -/ +def ShortTag (F : Type) [Field F] (p : ℝ) : Prop := + ∃ C : ℝ, ∀ w : ℕ, 1 ≤ w → ∃ v : ℕ, + Net F (Tagged.inputs w (word w)) .unit (Tagged.tag F w (word w)) v ∧ + (v : ℝ) ≤ C * (2 : ℝ) ^ w * (w : ℝ) ^ p + +end MatrixMultiplicationAllFields.MatrixExponent.Lookup diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Single.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Single.lean new file mode 100644 index 0000000000..f44d96b1c2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Lookup/Single.lean @@ -0,0 +1,195 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Counter +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Scan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Wide + +/-! # Uniqueness of the guessed multiplicities and their product -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Lookup + +variable {F : Type} [Field F] + +/-- In the case `0, z`, this construction gives `bits _ (xs.count z)`. -/ +def expected (a : Wire) (xs : List (Val a)) : + (l : ℕ) → Val (tree l a) → Val (tree l (count a)) + | 0, z => bits _ (xs.count z) + | l + 1, z => (expected a xs l z.1, expected a xs l z.2) + +/-- In the case `0, z, c`, this construction gives `f z ^ value _ c`. -/ +def weight (a : Wire) (f : Val a → F) : + (l : ℕ) → Val (tree l a) → Val (tree l (count a)) → F + | 0, z, c => f z ^ value _ c + | l + 1, z, c => weight a f l z.1 c.1 * weight a f l z.2 c.2 + +private theorem fold_queries (a : Wire) (z : Val a) (ok : Bool) (k : ℕ) : + (List.replicate k (query a z)).foldl (step a) (ok, zero _) = (ok, bits _ k) := by + induction k with + | zero => rfl + | succ k ih => + rw [List.replicate_succ', List.foldl_append, ih] + simp [step, query, bits, Function.iterate_succ_apply'] + +theorem fold_dict (a : Wire) (xs : List (Val a)) (l : ℕ) + (z : Val (tree l a)) (c : Val (tree l (count a))) (ok : Bool) : + ((flatten l (dict a l z c)).flatMap (group a xs)).foldl (step a) (ok, zero _) = + (ok && decide (expected a xs l z = c), zero _) := by + induction l generalizing ok with + | zero => + simp only [flatten, dict, List.flatMap_singleton, group, List.foldl_append] + rw [fold_queries a z ok] + rfl + | succ l ih => + simp only [flatten, dict, List.flatMap_append, List.foldl_append, ih, expected] + simp [Prod.ext_iff, Bool.and_assoc] + +private theorem product_counts (a : Wire) (xs zs : List (Val a)) (f : Val a → F) + (hn : zs.Nodup) (hall : ∀ z, z ∈ zs) : + (zs.map fun z => f z ^ xs.count z).prod = (xs.map f).prod := by + rw [← List.prod_toFinset _ hn, Finset.prod_list_map_count xs f] + symm + apply Finset.prod_subset + · exact fun i _ => List.mem_toFinset.mpr (hall i) + · intro i _ hi + rw [List.count_eq_zero_of_not_mem (mt List.mem_toFinset.mpr hi), pow_zero] + +private theorem weight_expected (a : Wire) (f : Val a → F) (xs : List (Val a)) + (hxs : xs.length < 2 ^ (wd a + 1)) (l : ℕ) (z : Val (tree l a)) : + weight a f l z (expected a xs l z) = ((flatten l z).map fun x => f x ^ xs.count x).prod := by + induction l with + | zero => + simp only [weight, expected, flatten, List.map_singleton, List.prod_singleton] + rw [value_bits (List.count_le_length.trans_lt hxs)] + | succ l ih => + simp only [weight, expected, flatten, List.map_append, List.prod_append, ih] + +theorem weight_lookup (a : Wire) (f : Val a → F) (x z : Val (tree (wd a) a)) + (hn : (flatten (wd a) z).Nodup) (hall : ∀ y : Val a, y ∈ flatten (wd a) z) : + weight a f (wd a) z (expected a (flatten (wd a) x) (wd a) z) = + ((flatten (wd a) x).map f).prod := by + have len (l : ℕ) (x : Val (tree l a)) : (flatten l x).length = 2 ^ l := by + induction l with + | zero => rfl + | succ l ih => simp [flatten, ih, pow_succ, mul_two] + have hxs : (flatten (wd a) x).length < 2 ^ (wd a + 1) := by + rw [len, pow_succ] + have := pow_pos (by decide : 0 < 2) (wd a) + omega + rw [weight_expected a f _ hxs, product_counts _ _ _ _ hn hall] + +end MatrixMultiplicationAllFields.MatrixExponent.Lookup +end + +section +/- +# Simultaneous evaluation at all query positions + +One sorting call handles query rows and a fixed dictionary carrying +guessed counts. The trace contracts the count wires with binary weights. +Exactly one assignment passes the scan, including in positive characteristic. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Lookup + +variable (K : Type) [Field K] (a : Wire) + +theorem queries_net (l : ℕ) : + DNet K (tree l a) (tree l (row a)) (queries a l) (2 ^ l * wd (row a)) := by + induction l with + | zero => + rw [pow_zero, one_mul] + exact ((DNet.id K a).par (const_net K (state a) (false, zero _))).pre (.unit' _) + | succ l ih => + rw [pow_succ, mul_two, add_mul] + exact ih.par ih + +theorem dict_net (l : ℕ) (z : Val (tree l a)) : + DNet K (tree l (count a)) (tree l (row a)) (dict a l z) (2 ^ l * wd (row a)) := by + induction l with + | zero => + rw [pow_zero, one_mul] + have payload := ((const_net K .bit true).par (DNet.id K (count a))).pre + ((Rewire.unit' _).comp (.swap _ _)) + exact ((const_net K a z).par payload).pre ((Rewire.unit' _).comp (.swap _ _)) + | succ l ih => + rw [pow_succ, mul_two, add_mul] + exact (ih z.1).par (ih z.2) + +theorem weights_net (f : Val a → K) (l : ℕ) (z : Val (tree l a)) : + Net K .unit (tree l (count a)) (fun _ y => weight a f l z y) (2 ^ l * (wd a + 1)) := by + induction l with + | zero => + rw [pow_zero, one_mul] + exact weight_net K _ (f z) + | succ l ih => + rw [pow_succ, mul_two, add_mul] + exact ((ih z.1).par (ih z.2)).pre (.unit' .unit) + +private theorem batch (f : Val a → K) (z : Val (tree (wd a) a)) + (hn : (flatten (wd a) z).Nodup) (hall : ∀ y : Val a, y ∈ flatten (wd a) z) + {sort : Val (tree (wd a + 1) (row a)) → Val (tree (wd a + 1) (row a))} {m : ℕ} + (hs : DNet K (tree (wd a + 1) (row a)) (tree (wd a + 1) (row a)) sort m) + (he : ∀ x c, flatten (wd a + 1) (sort (queries a (wd a) x, dict a (wd a) z c)) = + (flatten (wd a) (dict a (wd a) z c)).flatMap (group a (flatten (wd a) x))) : + ∃ v ≤ m + 2006 * 2 ^ (wd a) * (1 + wd a), + Net K (tree (wd a) a) .unit (fun x _ => ((flatten (wd a) x).map f).prod) v := by + let t := wd a + have prep := (queries_net K a t).par (dict_net K a t z) + obtain ⟨v, hv, accept⟩ := (prep.comp hs).comp (scan_net K a (t + 1)) + have pin := Net.table (F := K) .bit .unit (fun b _ => if b then 1 else 0) (by decide) + have test := accept.comp pin + have valid : Net K (.pair (tree t a) (tree t (count a))) .unit + (fun y _ => if expected a (flatten t y.1) t z = y.2 then 1 else 0) (v + 1) := by + convert test using 1 + funext y u + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + have eqn : scan a (t + 1) (sort (queries a t y.1, dict a t z y.2)) = + decide (expected a (flatten t y.1) t z = y.2) := by + unfold scan + rw [he, fold_dict a (flatten t y.1) t z y.2 true, Bool.true_and] + simp only [eqn, decide_eq_true_eq] + have out := ((valid.par (weights_net K a f t z)).pre (.unit' _)).trace + refine ⟨v + 1 + 2 ^ t * (wd a + 1), ?_, ?_⟩ + · have h2 : 0 < 2 ^ t := pow_pos (by decide) _ + simp only [wd, wd_word, pow_succ] at hv + change v + 1 + 2 ^ t * (wd a + 1) ≤ m + 2006 * 2 ^ t * (1 + wd a) + nlinarith only [h2, hv] + · simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, + t, weight_lookup a f _ z hn hall] using out + +/-- The constant is uniform over extensions, table arities and entries. -/ +theorem lookup_net {F : Type} [Field F] {p : ℝ} (hp : 1 ≤ p) (hs : Sorting F p) : + ∃ C : ℝ, 1 ≤ C ∧ ∀ (K : Type) (_ : Field K) (_ : Algebra F K) (a : Wire) (f : Val a → K), + ∃ v : ℕ, Net K (tree (wd a) a) .unit (fun x _ => ((flatten (wd a) x).map f).prod) v ∧ + (v : ℝ) ≤ C * (2 : ℝ) ^ wd a * (1 + (wd a : ℝ)) ^ p := by + obtain ⟨C, hC⟩ := hs + refine ⟨max C 0 + 2006, by linarith [le_max_right C 0], ?_⟩ + intro K _ _ a f + obtain ⟨z, sort, m, hn, hall, ⟨w, hw, hsort⟩, hm, he⟩ := hC a + have hsort' : DNet K (tree (wd a + 1) (row a)) (tree (wd a + 1) (row a)) sort m := by + refine ⟨w, hw, ?_⟩ + simpa only [apply_ite (algebraMap F K), map_one, map_zero] using hsort.map (algebraMap F K) + obtain ⟨v, hv, hnet⟩ := batch K a f z hn hall hsort' he + refine ⟨v, hnet, ?_⟩ + have h : (1 + (wd a : ℝ)) ≤ (1 + (wd a : ℝ)) ^ p := by + simpa using Real.rpow_le_rpow_of_exponent_le (show 1 ≤ 1 + (wd a : ℝ) by simp) hp + calc + (v : ℝ) ≤ m + 2006 * (2 : ℝ) ^ wd a * (1 + (wd a : ℝ)) := by exact_mod_cast hv + _ ≤ C * (2 : ℝ) ^ wd a * (1 + (wd a : ℝ)) ^ p + + 2006 * (2 : ℝ) ^ wd a * (1 + (wd a : ℝ)) ^ p := + add_le_add hm (mul_le_mul_of_nonneg_left h (by positivity)) + _ = (C + 2006) * (2 : ℝ) ^ wd a * (1 + (wd a : ℝ)) ^ p := by ring + _ ≤ _ := by gcongr; exact le_max_left _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Lookup +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Mixer/Score.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Mixer/Score.lean new file mode 100644 index 0000000000..356f53ab54 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Mixer/Score.lean @@ -0,0 +1,484 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.BadBases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad + +/-! +# Binary autocorrelations + +The unnormalized Walsh transform doubles at each level under iteration. +It diagonalizes convolution on binary addresses. The identities only +use commutative ring operations, including in characteristic two. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Mixer +open Packing Finset + +variable {K : Type} [CommRing K] {h : ℕ} + +/-- Computes the slice by the application `f (Fin.cons i x)`. -/ +def slice (i : ZMod 2) (f : Cell (h + 1) → K) (x : Cell h) := f (Fin.cons i x) + +omit [CommRing K] in +theorem slice_ext {f g : Cell (h + 1) → K} (h₀ : slice 0 f = slice 0 g) + (h₁ : slice 1 f = slice 1 g) : f = g := by + funext x + rw [← Fin.cons_self_tail x] + have bit : ∀ z : ZMod 2, z = 0 ∨ z = 1 := by decide + rcases bit (x 0) with h | h + · rw [h]; exact congrFun h₀ _ + · rw [h]; exact congrFun h₁ _ + +@[simp] theorem slice_add (i) (f g : Cell (h + 1) → K) : + slice i (f + g) = slice i f + slice i g := rfl + +@[simp] theorem slice_sub (i) (f g : Cell (h + 1) → K) : + slice i (f - g) = slice i f - slice i g := rfl + +@[simp] theorem slice_mul (i) (f g : Cell (h + 1) → K) : + slice i (f * g) = slice i f * slice i g := rfl + +omit [CommRing K] in +@[simp] theorem slice_const (i) (z : K) : + slice (h := h) i (fun _ => z) = fun _ => z := rfl + +/-- In the case `0, f, x`, this construction gives `f x`. -/ +def walsh : {h : ℕ} → (Cell h → K) → Cell h → K + | 0, f, x => f x + | _ + 1, f, x => + let a := walsh (slice 0 f) (Fin.tail x) + let b := walsh (slice 1 f) (Fin.tail x) + if x 0 = 0 then a + b else a - b + +@[simp] theorem slice₀ (f : Cell (h + 1) → K) : + slice 0 (walsh f) = walsh (slice 0 f) + walsh (slice 1 f) := by + funext x + simp [slice, walsh] + +@[simp] theorem slice₁ (f : Cell (h + 1) → K) : + slice 1 (walsh f) = walsh (slice 0 f) - walsh (slice 1 f) := by + funext x + simp [slice, walsh] + +@[simp] theorem walsh_add (f g : Cell h → K) : walsh (f + g) = walsh f + walsh g := by + induction h with + | zero => rfl + | succ h ih => + apply slice_ext <;> simp only [slice₀, slice₁, slice_add, ih] <;> + funext x <;> simp only [Pi.add_apply, Pi.sub_apply] <;> ring + +@[simp] theorem walsh_sub (f g : Cell h → K) : walsh (f - g) = walsh f - walsh g := by + induction h with + | zero => rfl + | succ h ih => + apply slice_ext <;> simp only [slice₀, slice₁, slice_sub, ih] <;> + funext x <;> simp only [Pi.add_apply, Pi.sub_apply] <;> ring + +theorem twice (f : Cell h → K) : walsh (walsh f) = (fun _ => (2 : K) ^ h) * f := by + induction h with + | zero => funext x; simp [walsh] + | succ h ih => + apply slice_ext <;> + simp only [slice₀, slice₁, slice_mul, slice_const, walsh_add, walsh_sub, ih] <;> + funext x <;> simp only [Pi.add_apply, Pi.sub_apply, Pi.mul_apply, pow_succ] <;> ring + +/-- The sum of `f x * g (x + z)` indexed by `x`. -/ +def conv (f g : Cell h → K) (z : Cell h) := ∑ x, f x * g (x + z) + +private theorem cons_add (i j : ZMod 2) (x y : Cell h) : + (Fin.cons i x : Cell (h + 1)) + Fin.cons j y = Fin.cons (i + j) (x + y) := by + funext r + induction r using Fin.cases <;> simp + +theorem split_conv (f g : Cell (h + 1) → K) (i : ZMod 2) : + slice i (conv f g) = conv (slice 0 f) (slice i g) + conv (slice 1 f) (slice (1 + i) g) := by + funext z + let e : ZMod 2 × Cell h ≃ Cell (h + 1) := Fin.consEquiv (fun _ => ZMod 2) + change (∑ x : Cell (h + 1), f x * g (x + Fin.cons i z)) = _ + have cons_apply (j : ZMod 2) (x : Cell h) : e (j, x) = Fin.cons j x := rfl + rw [← e.sum_comp, Fintype.sum_prod_type] + simp only [cons_apply] + rw [show (univ : Finset (ZMod 2)) = {0, 1} by decide, sum_pair (by decide : (0 : ZMod 2) ≠ 1)] + simp only [cons_add, zero_add, Pi.add_apply, conv, slice] + +theorem walsh_conv (f g : Cell h → K) : walsh (conv f g) = walsh f * walsh g := by + induction h with + | zero => + funext x + unfold walsh conv + rw [Fintype.sum_eq_single x (fun y hy => (hy (Subsingleton.elim _ _)).elim)] + rw [show x + x = x from Subsingleton.elim _ _] + rfl + | succ h ih => + apply slice_ext <;> simp only [slice₀, slice₁, slice_mul, split_conv, add_zero, + show (1 : ZMod 2) + 1 = 0 by decide, walsh_add, ih] <;> + funext x <;> simp only [Pi.add_apply, Pi.sub_apply, Pi.mul_apply] <;> ring + +/-- Two butterfly transforms and entrywise squaring compute the +autocorrelation times the number of blocks. -/ +theorem autocorrelation (f : Cell h → K) : + walsh (walsh f * walsh f) = (fun _ => (2 : K) ^ h) * conv f f := by + rw [← walsh_conv, twice] + +end MatrixMultiplicationAllFields.MatrixExponent.Mixer +end + +/- +# Aggregating the reset score by depth and binary difference + +Only the uncentered second moments depend on the mixer. Consequently +one array, indexed by depth and by block difference, suffices to +compare all linear mixers. The arrays of the individual positions +and contacts are formed from their autocorrelations. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Mixer +open Packing Finset + +open scoped Classical in +/-- The value specified by `Cell h ≃ₗ[ZMod 2] Cell h`. -/ +abbrev Perm (h : ℕ) := Cell h ≃ₗ[ZMod 2] Cell h +open scoped Classical in +/-- The quantity computed by `Fin (h + 1) → Cell h → ℝ`. -/ +abbrev Coeff (h : ℕ) := Fin (h + 1) → Cell h → ℝ + +variable {h : ℕ} (p : Perm h) + +open scoped Classical in +/-- Builds `Coeff h →ₗ[ℝ] ℝ where toFun f` with the specified `toFun`, `map_add'`, `simp`. -/ +def eval : Coeff h →ₗ[ℝ] ℝ where + toFun f := ∑ i : Fin (h + 1), ∑ z, if ancestor i.is_le (p z) = 0 then f i z else 0 + map_add' f g := by + simp only [Pi.add_apply, ← sum_add_distrib, ite_add_ite, add_zero] + map_smul' c f := by + simp only [Pi.smul_apply, smul_eq_mul, mul_sum, mul_ite, mul_zero, RingHom.id_apply] + +open scoped Classical in +/-- Evaluates `if j.val = i then conv l l z else 0` at the input `j z`. -/ +def atDepth (l : Cell h → ℝ) (i : ℕ) : Coeff h := + fun j z => if j.val = i then conv l l z else 0 + +open scoped Classical in +private theorem moment (l : Cell h → ℝ) {i : ℕ} (hi : i ≤ h) : + (∑ z, (load l p.toEquiv i z) ^ 2) = + ∑ z, if ancestor hi (p z) = 0 then conv l l z else 0 := by + rw [square_load _ _ _ hi] + have he (z : Cell h) : (if ancestor hi (p z) = 0 then conv l l z else 0) = + ∑ x, if ancestor hi (p z) = 0 then l x * l (x + z) else 0 := by + split_ifs <;> simp [conv] + simp_rw [he] + conv_rhs => rw [sum_comm] + apply sum_congr rfl + intro x _ + rw [← Equiv.sum_comp (Equiv.addLeft x)] + apply sum_congr rfl + intro z _ + change (if ancestor hi (p x) = ancestor hi (p (x + z)) then l x * l (x + z) else 0) = _ + rw [map_add, show ancestor hi (p x + p z) = ancestor hi (p x) + ancestor hi (p z) from rfl] + simp + +open scoped Classical in +theorem eval_atDepth (l : Cell h → ℝ) (i : ℕ) : + eval p (atDepth l i) = ∑ z, (load l p.toEquiv i z) ^ 2 := by + change (∑ j : Fin (h + 1), ∑ z, if ancestor j.is_le (p z) = 0 then atDepth l i j z else 0) = _ + by_cases hi : i ≤ h + · rw [Fintype.sum_eq_single (⟨i, by omega⟩ : Fin (h + 1))] + · simpa only [atDepth, ite_true] using (moment p l hi).symm + · intro j hj + have : j.val ≠ i := fun he => hj (Fin.ext he) + simp [atDepth, this] + · have hn (j : Fin (h + 1)) : j.val ≠ i := by have := j.isLt; omega + simp [atDepth, hn, load, hi] + +open scoped Classical in +private theorem estimate_diff (q : Perm h) (l : Cell h → ℝ) (k b j : ℕ) : + estimate l p.toEquiv k b j - estimate l q.toEquiv k b j = + 2 * (eval p - eval q) (atDepth l (b + j)) := by + rw [LinearMap.sub_apply, eval_atDepth, eval_atDepth] + unfold estimate + split_ifs with hi hk + · rw [variance_eq _ _ _ hi, variance_eq _ _ _ hi] + ring + · rw [sum_cross _ _ _ hi, sum_cross _ _ _ hi] + ring + · simp [load, hi] + +variable {V A : Type} [Fintype V] [Fintype A] + (base : V → ℕ) (depth : A → ℕ) (l : V → Cell h → ℝ) (y : A → Cell h → ℝ) (g : ℝ) + +open scoped Classical in +/-- The value specified by `3 • (∑ v, ∑ j ∈ range (h + 1), (2 * resetWeight j) • atDepth (l v) +(base v + j)) + 4 • ∑ c, g ^ 2 • atDepth (y c) (depth c)`. -/ +def coefficients : Coeff h := + 3 • (∑ v, ∑ j ∈ range (h + 1), (2 * resetWeight j) • atDepth (l v) (base v + j)) + + 4 • ∑ c, g ^ 2 • atDepth (y c) (depth c) + +open scoped Classical in +/-- The sign of the cost difference is exactly the sign of the difference +of the two tests on the aggregated array. -/ +theorem score_diff (q : Perm h) (hd : ∀ c, depth c ≤ h) (k : ℕ) : + score base depth l y g p.toEquiv k - score base depth l y g q.toEquiv k = + (eval p - eval q) (coefficients base depth l y g) := by + let f := eval p - eval q + have h₁ (v : V) : f (∑ j ∈ range (h + 1), (2 * resetWeight j) • atDepth (l v) (base v + j)) = + (∑ j ∈ range (h + 1), resetWeight j * estimate (l v) p.toEquiv k (base v) j) - + (∑ j ∈ range (h + 1), resetWeight j * estimate (l v) q.toEquiv k (base v) j) := by + rw [map_sum, ← sum_sub_distrib] + refine sum_congr rfl fun j _ => ?_ + rw [map_smul, smul_eq_mul, ← mul_sub, estimate_diff] + unfold f + ring + have h₂ c : f (g ^ 2 • atDepth (y c) (depth c)) = + g ^ 2 * variance (y c) p.toEquiv (depth c) - g ^ 2 * variance (y c) q.toEquiv (depth c) := by + unfold f + rw [map_smul, smul_eq_mul, LinearMap.sub_apply, eval_atDepth, eval_atDepth, + variance_eq _ _ _ (hd c), variance_eq _ _ _ (hd c)] + ring + change _ = f _ + rw [coefficients, map_add, map_nsmul, map_nsmul, map_sum, map_sum] + simp only [h₁, h₂, sum_sub_distrib, score, nsmul_eq_mul, Nat.cast_ofNat] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Mixer +end + +/- +# Butterfly circuits with a fixed dictionary + +All arithmetic uses encoded words. One table computes the two butterfly +outputs together. A second table squares a word. The tensor entries of +both tables are zero or one in the network's ground field. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Mixer + +open Packing + +variable {a : Wire} + +open scoped Classical in +/-- In the case `0, x, _`, this construction gives `x`. -/ +def read : (h : ℕ) → Val (tree h a) → Cell h → Val a + | 0, x, _ => x + | h + 1, x, j => if j 0 = 0 then read h x.1 (Fin.tail j) else read h x.2 (Fin.tail j) + +open scoped Classical in +/-- In the case `0, x`, this construction gives `s x`. -/ +def rows (s : Val a → Val a) : (h : ℕ) → Val (tree h a) → Val (tree h a) + | 0, x => s x + | h + 1, x => (rows s h x.1, rows s h x.2) + +open scoped Classical in +/-- In the case `0, x`, this construction gives `g x`. -/ +def both (g : Val (.pair a a) → Val (.pair a a)) : + (h : ℕ) → Val (tree (h + 1) a) → Val (tree (h + 1) a) + | 0, x => g x + | h + 1, x => + let u := both g h (x.1.1, x.2.1) + let v := both g h (x.1.2, x.2.2) + ((u.1, v.1), (u.2, v.2)) + +open scoped Classical in +private theorem read_rows (s : Val a → Val a) (h : ℕ) (x : Val (tree h a)) (j : Cell h) : + read h (rows s h x) j = s (read h x j) := by + induction h with + | zero => rfl + | succ h ih => simp only [read, rows]; split_ifs <;> exact ih _ _ + +open scoped Classical in +private theorem read_both (g : Val (.pair a a) → Val (.pair a a)) (h : ℕ) + (x : Val (tree (h + 1) a)) (j : Cell h) : + (read h (both g h x).1 j, read h (both g h x).2 j) = g (read h x.1 j, read h x.2 j) := by + induction h with + | zero => rfl + | succ h ih => simp only [read, both]; split_ifs <;> exact ih _ _ + +variable {K F : Type} [CommRing K] [Field F] (e : Val a ≃ K) + +open scoped Classical in +/-- The quantity computed by `(e.symm (e p.1 + e p.2), e.symm (e p.1 - e p.2))`. -/ +def step (p : Val (.pair a a)) : Val (.pair a a) := + (e.symm (e p.1 + e p.2), e.symm (e p.1 - e p.2)) + +open scoped Classical in +/-- The quantity computed by `e.symm (e x * e x)`. -/ +def square (x : Val a) : Val a := e.symm (e x * e x) + +open scoped Classical in +/-- In the case `0, x`, this construction gives `x`. -/ +def butterfly : (h : ℕ) → Val (tree h a) → Val (tree h a) + | 0, x => x + | h + 1, x => both (step e) h (butterfly h x.1, butterfly h x.2) + +open scoped Classical in +/-- Computes the correlation by the application `butterfly e h (rows (square e) h (butterfly e h +x))`. -/ +def correlation (h : ℕ) (x : Val (tree h a)) := + butterfly e h (rows (square e) h (butterfly e h x)) + +open scoped Classical in +/-- Computes the view by the application `e (read h x j)`. -/ +def view (h : ℕ) (x : Val (tree h a)) (j : Cell h) := e (read h x j) + +open scoped Classical in +theorem view_butterfly (h : ℕ) (x : Val (tree h a)) : + view e h (butterfly e h x) = walsh (view e h x) := by + induction h with + | zero => rfl + | succ h ih => + have h₀ : slice 0 (view e (h + 1) x) = view e h x.1 := by funext j; simp [view, read, slice] + have h₁ : slice 1 (view e (h + 1) x) = view e h x.2 := by funext j; simp [view, read, slice] + funext j + rw [walsh, h₀, h₁, ← ih, ← ih] + have hp := read_both (step e) h (butterfly e h x.1, butterfly e h x.2) (Fin.tail j) + obtain ⟨hl, hr⟩ := Prod.mk.inj hp + simp only [view, read, butterfly] + split_ifs <;> simp only [hl, hr, Equiv.apply_symm_apply] + +open scoped Classical in +theorem view_correlation (h : ℕ) (x : Val (tree h a)) : + view e h (correlation e h x) = (fun _ => (2 : K) ^ h) * conv (view e h x) (view e h x) := by + have sq y : view e h (rows (square e) h y) = view e h y * view e h y := by + funext j + simp [view, read_rows, square] + rw [correlation, view_butterfly, sq, view_butterfly, autocorrelation] + +variable {u m : ℕ} {L : Set (Table F)} + +open scoped Classical in +private theorem net_rows {s : Val a → Val a} (hs : DWide F u L a a s m) (h : ℕ) : + DWide F u L (tree h a) (tree h a) (rows s h) (2 ^ h * m) := by + induction h with + | zero => simpa [rows] using hs + | succ h ih => rw [pow_succ', mul_assoc, two_mul]; exact ih.par ih + +open scoped Classical in +private theorem net_both {s : Val (.pair a a) → Val (.pair a a)} + (hs : DWide F u L (.pair a a) (.pair a a) s m) (h : ℕ) : + DWide F u L (tree (h + 1) a) (tree (h + 1) a) (both s h) (2 ^ h * m) := by + induction h with + | zero => simpa [both] using hs + | succ h ih => + rw [pow_succ', mul_assoc, two_mul] + exact ((ih.par ih).pre (.middle _ _ _ _)).post (.middle _ _ _ _) + +open scoped Classical in +theorem net_butterfly (hu : 3 ≤ u) (hm : 4 * wd a ≤ m) + (hs : DWide F u L (.pair a a) (.pair a a) (step e) m) (h : ℕ) : + DWide F u L (tree h a) (tree h a) (butterfly e h) (2 ^ h * (h + 1) * m) := by + induction h with + | zero => + exact (DWide.of_dnet hu (DNet.id F a)).mono (by simpa using hm) + | succ h ih => + refine ((ih.par ih).comp (net_both hs h)).mono ?_ + rw [pow_succ] + nlinarith only [Nat.zero_le (2 ^ h * m)] + +open scoped Classical in +/-- Uses `⟨b, b, fun x y => if s x = y then 1 else 0⟩` as the representation. -/ +def operation (F : Type) [Field F] (b : Wire) (s : Val b → Val b) : Table F := + ⟨b, b, fun x y => if s x = y then 1 else 0⟩ + +open scoped Classical in +/-- Uses `{operation F (.pair a a) (step e), operation F a (square e)}` as the representation. -/ +def dictionary (F : Type) [Field F] : Finset (Table F) := + {operation F (.pair a a) (step e), operation F a (square e)} + +open scoped Classical in +theorem dictionary_size : (dictionary e F).card ≤ 2 := Finset.card_le_two + +open scoped Classical in +theorem dictionary_arity {t : Table F} (ht : t ∈ dictionary e F) : + wd t.1 + wd t.2.1 ≤ 4 * wd a := by + simp only [dictionary, Finset.mem_insert, Finset.mem_singleton] at ht + rcases ht with rfl | rfl <;> simp only [operation, wd] <;> omega + +open scoped Classical in +/-- Quasilinear station and port count, independent of the arithmetic +of the encoded ring. -/ +theorem correlation_net (h : ℕ) (hu : 3 ≤ u) (hw : 4 * wd a ≤ u) : + DWide F u (dictionary e F) (tree h a) (tree h a) (correlation e h) + (2 ^ h * (2 * h + 3) * (1 + 4 * wd a)) := by + let m := 1 + 4 * wd a + have table (b : Wire) (s : Val b → Val b) (hb : wd b + wd b ≤ 4 * wd a) + (ht : operation F b s ∈ dictionary e F) : DWide F u (dictionary e F) b b s m := + ⟨_, Nat.add_le_add_left hb _, .table _ _ _ (hb.trans hw) (.inr ht)⟩ + have t := net_butterfly e hu (by unfold m; omega) + (table (.pair a a) (step e) (by simp only [wd]; omega) (by simp [dictionary])) h + have b := net_rows (table a (square e) (by omega) (by simp [dictionary])) h + exact ((t.comp b).comp t).mono (by unfold m; exact le_of_eq (by ring)) + +end MatrixMultiplicationAllFields.MatrixExponent.Mixer +end + +/- +# Exact integer autocorrelations in bounded binary words + +For `2^h` inputs bounded by `2^d` choose `2(h+d)+1` bits per +word. Compute modulo that word size throughout the two transforms. +The final scaled integer is below the modulus. It can therefore be +recovered even though some intermediate operations may wrap. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Mixer + +open Packing Finset + +/-- Reindexes two finite types using equality of cardinalities. -/ +def wordCode (n : ℕ) : Val (word n) ≃ ZMod (2 ^ n) := + Fintype.equivOfCardEq (by + rw [Fintype.card_congr (bits (word n)), Fintype.card_fun, card_slots, wd_word, + Fintype.card_bool, ZMod.card]) + +/-- In the case `0, f`, this construction gives `f 0`. -/ +def write {a : Wire} : (h : ℕ) → (Cell h → Val a) → Val (tree h a) + | 0, f => f 0 + | h + 1, f => (write h (slice 0 f), write h (slice 1 f)) + +theorem read_write {a : Wire} (h : ℕ) (f : Cell h → Val a) : read h (write h f) = f := by + induction h with + | zero => funext x; exact congrArg f (Subsingleton.elim _ _) + | succ h ih => + apply slice_ext <;> funext x <;> simp [slice, read, write, ih] + +/-- The quantity computed by `write h (fun x => (wordCode n).symm (u x : ZMod (2 ^ n)))`. -/ +def encode (h n : ℕ) (u : Cell h → ℕ) := + write h (fun x => (wordCode n).symm (u x : ZMod (2 ^ n))) + +theorem exact_correlation (h d : ℕ) (u : Cell h → ℕ) (hu : ∀ x, u x ≤ 2 ^ d) (z : Cell h) : + let n := 2 * (h + d) + 1 + let e := wordCode n + (view e h (correlation e h (encode h n u)) z).val = 2 ^ h * ∑ x, u x * u (x + z) := by + intro n e + have he : view e h (encode h n u) = fun x => (u x : ZMod (2 ^ n)) := by + funext x + simp only [encode, view, read_write, e, Equiv.apply_symm_apply] + have hlim : 2 ^ h * (∑ x, u x * u (x + z)) < 2 ^ n := calc + _ ≤ 2 ^ h * ∑ _x : Cell h, 2 ^ d * 2 ^ d := + Nat.mul_le_mul_left _ (sum_le_sum fun x _ => Nat.mul_le_mul (hu x) (hu (x + z))) + _ = 2 ^ (2 * (h + d)) := by + rw [sum_const, card_univ, card_cell, Nat.nsmul_eq_mul, two_mul] + simp only [pow_add] + ring + _ < _ := Nat.pow_lt_pow_right (by decide) (by unfold n; omega) + rw [view_correlation, he] + change ((2 : ZMod (2 ^ n)) ^ h * ∑ x, (u x : ZMod (2 ^ n)) * u (x + z)).val = _ + simpa only [Nat.cast_mul, Nat.cast_sum, Nat.cast_pow, Nat.cast_ofNat] + using ZMod.val_natCast_of_lt hlim + +end MatrixMultiplicationAllFields.MatrixExponent.Mixer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Network.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Network.lean new file mode 100644 index 0000000000..0003010e7a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Network.lean @@ -0,0 +1,117 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.ListBounds + +/-! +# Trivalent bit networks + +A bundle is a binary tree of bit positions. Rewiring only permutes the +positions (with changes of parenthesization). Networks are built by +juxtaposing vertex tables and joining wires, summing over their shared +values. Trace allows internal cycles. Size counts vertices and exterior bits. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- The wire used in the `MatrixExponent` construction. -/ +inductive Wire + | bit + | unit + | pair (a b : Wire) + +/-- In the case `.bit`, this construction gives `Bool`. -/ +abbrev Val : Wire → Type + | .bit => Bool + | .unit => Unit + | .pair a b => Val a × Val b + +instance valFintype : (a : Wire) → Fintype (Val a) + | .bit => inferInstanceAs (Fintype Bool) + | .unit => inferInstanceAs (Fintype Unit) + | .pair a b => + letI := valFintype a + letI := valFintype b + inferInstanceAs (Fintype (Val a × Val b)) + +instance valDecidableEq : (a : Wire) → DecidableEq (Val a) + | .bit => inferInstanceAs (DecidableEq Bool) + | .unit => inferInstanceAs (DecidableEq Unit) + | .pair a b => + letI := valDecidableEq a + letI := valDecidableEq b + inferInstanceAs (DecidableEq (Val a × Val b)) + +/-- In the case `.bit`, this construction gives `1`. -/ +def wd : Wire → ℕ + | .bit => 1 + | .unit => 0 + | .pair a b => wd a + wd b + +/-- The rewire used in the `MatrixExponent` construction. -/ +inductive Rewire : (a b : Wire) → (Val a → Val b) → Prop + | id (a) : Rewire a a (fun x => x) + | swap (a b) : Rewire (.pair a b) (.pair b a) (fun x => (x.2, x.1)) + | assoc (a b c) : Rewire (.pair (.pair a b) c) (.pair a (.pair b c)) + (fun x => (x.1.1, x.1.2, x.2)) + | assoc' (a b c) : Rewire (.pair a (.pair b c)) (.pair (.pair a b) c) + (fun x => ((x.1, x.2.1), x.2.2)) + | unit (a) : Rewire (.pair a .unit) a (fun x => x.1) + | unit' (a) : Rewire a (.pair a .unit) (fun x => (x, ())) + | comp {a b c f g} : Rewire a b f → Rewire b c g → Rewire a c (fun x => g (f x)) + | par {a b c d f g} : Rewire a b f → Rewire c d g → + Rewire (.pair a c) (.pair b d) (fun x => (f x.1, g x.2)) + +/-- The last index counts vertices, excluding exterior wires. -/ +inductive Net (F : Type) [Field F] : (a b : Wire) → (Val a → Val b → F) → ℕ → Prop + | empty : Net F .unit .unit (fun _ _ => 1) 0 + | table (a b) (k : Val a → Val b → F) (h : wd a + wd b ≤ 3) : Net F a b k 1 + | par {a b c d k l m n} : Net F a b k m → Net F c d l n → + Net F (.pair a c) (.pair b d) (fun x y => k x.1 y.1 * l x.2 y.2) (m + n) + | comp {a b c k l m n} : Net F a b k m → Net F b c l n → + Net F a c (fun x z => ∑ y : Val b, k x y * l y z) (m + n) + | trace {a b c k m} : Net F (.pair a c) (.pair b c) k m → + Net F a b (fun x y => ∑ z : Val c, k (x, z) (y, z)) m + | pre {a b c f k m} : Net F b c k m → Rewire a b f → + Net F a c (fun x y => k (f x) y) m + | post {a b c f k m} : Net F a b k m → Rewire c b f → + Net F a c (fun x y => k x (f y)) m + +/-- In the case `0`, this construction gives `.unit`. -/ +abbrev word : ℕ → Wire + | 0 => .unit + | n + 1 => .pair .bit (word n) + +/-- In the case `0, a`, this construction gives `a`. -/ +abbrev tree : ℕ → Wire → Wire + | 0, a => a + | w + 1, a => .pair (tree w a) (tree w a) + +/-- In the case `0, x`, this construction gives `[x]`. -/ +def flatten {a : Wire} : (w : ℕ) → Val (tree w a) → List (Val a) + | 0, x => [x] + | w + 1, x => flatten w x.1 ++ flatten w x.2 + +/-- In the case `0`, this construction gives `.unit`. -/ +abbrev lists (w : ℕ) : ℕ → Wire + | 0 => .unit + | t + 1 => .pair (tree w (word (2 * w))) (lists w t) + +/-- In the case `0, _`, this construction gives `1`. -/ +def distinctPower (F : Type) [Field F] (w : ℕ) : (t : ℕ) → Val (lists w t) → F + | 0, _ => 1 + | t + 1, x => (if (flatten w x.1).Nodup then 1 else 0) * distinctPower F w t x.2 + +/-- The condition `∃ v, Net F (lists w t) .unit (fun x _ => distinctPower F w t x) v ∧ m = v + t +* listBits w` on the specified data. -/ +def Realizes (F : Type) [Field F] (w t m : ℕ) : Prop := + ∃ v, Net F (lists w t) .unit (fun x _ => distinctPower F w t x) v ∧ m = v + t * listBits w + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Network/Dense.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Network/Dense.lean new file mode 100644 index 0000000000..b258ffb6a2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Network/Dense.lean @@ -0,0 +1,102 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FunctionNetwork + +/-! +# Trivalent realization of arbitrary tables + +Give the table one enable bit. Splitting on the next address bit enables +exactly one of two subtables, while a disabled subtable contributes the +factor one. Copying the remaining bits costs their width at each split. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent +namespace Net + +variable {F : Type} [Field F] + +/-- A pair of identical bundles with no inputs. -/ +theorem cup (F : Type) [Field F] (a : Wire) : + Net F .unit (.pair a a) (fun _ y => if y.1 = y.2 then 1 else 0) (wd a) := by + induction a with + | bit => exact .table _ _ _ (by decide) + | unit => exact (Net.empty (F := F)).post (.unit _) + | pair a b ha hb => + simpa only [wd, Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul] using + ((ha.par hb).pre (.unit' _)).post (.middle a b a b) + +/-- Turn some inputs into outputs, paying for a pairwise equality test +on the corresponding bits. -/ +theorem curry {a b : Wire} {k : Val a → Val b → F} {m : ℕ} + (h : Net F (.pair a b) .unit (fun x _ => k x.1 x.2) m) : + Net F a b k (m + wd b) := by + have g := ((h.par (cup F b)).pre (.unit' _)).post ((Rewire.unit' _).comp (.swap _ _)) + simpa only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + using g.trace + +/-- The additive width term pays for copying the unprocessed address bits. -/ +private def Enabled (F : Type) [Field F] (a : Wire) : Prop := + ∀ k : Val a → F, ∃ m, Net F (.pair .bit a) .unit (fun x _ => if x.1 then k x.2 else 1) m ∧ + m + wd a + 5 ≤ 6 * 2 ^ wd a + +private theorem enabled_bit {a : Wire} (h : Enabled F a) : Enabled F (.pair .bit a) := by + intro k + obtain ⟨m, lo, hm⟩ := h (fun x => k (false, x)) + obtain ⟨n, hi, hn⟩ := h (fun x => k (true, x)) + have zero := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 && !x.2) (by decide) + have one := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 && x.2) (by decide) + obtain ⟨v, hv, split⟩ := + (((zero.pair one).par (DNet.dup F a)).pre (.assoc' .bit .bit a)).post (.middle .bit .bit a a) + refine ⟨v + (m + n), ?_, ?_⟩ + · have H := (split.comp (lo.par hi)).post (.unit' _) + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] at H + convert H using 1 + funext ⟨b, c, x⟩ y + cases b <;> cases c <;> simp + · simp only [wd, pow_add, pow_one] at hv ⊢ + omega + +private theorem enabled_extend (a : Wire) {b : Wire} (h : Enabled F b) : + Enabled F (.pair a b) := by + induction a generalizing b with + | bit => exact enabled_bit h + | unit => + intro k + obtain ⟨m, H, hm⟩ := h (fun x => k ((), x)) + exact ⟨m, H.pre ((Rewire.id _).par ((Rewire.swap _ _).comp (.unit _))), + by simpa only [wd, Nat.zero_add] using hm⟩ + | pair a c ha hc => + intro k + obtain ⟨m, H, hm⟩ := ha (hc h) (fun x => k ((x.1, x.2.1), x.2.2)) + exact ⟨m, H.pre ((Rewire.id _).par (.assoc _ _ _)), + by simpa only [wd, Nat.add_assoc] using hm⟩ + +private theorem dense_weight (a : Wire) (k : Val a → F) : + ∃ m, Net F a .unit (fun x _ => k x) m ∧ m ≤ 6 * 2 ^ wd a := by + have base : Enabled F .unit := fun _ => ⟨1, .table _ _ _ (by decide), by decide⟩ + obtain ⟨m, H, hm⟩ := enabled_extend a base (fun x => k x.1) + have pin := DNet.table F .unit .bit (fun _ => true) (by decide) + obtain ⟨v, hv, G⟩ := (pin.par (DNet.id F a)).pre ((Rewire.unit' a).comp (.swap _ _)) + refine ⟨v + m, ?_, by simp only [wd, Nat.add_zero] at hm; omega⟩ + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] using + G.comp (H.pre ((Rewire.id _).par (.unit' _))) + +/-- Any table on `r` exterior bits needs at most `8 * 2 ^ r` trivalent vertices. -/ +theorem dense (a b : Wire) (k : Val a → Val b → F) : + ∃ m, Net F a b k m ∧ m ≤ 8 * 2 ^ (wd a + wd b) := by + obtain ⟨m, H, hm⟩ := dense_weight (.pair a b) (fun x => k x.1 x.2) + refine ⟨m + wd b, H.curry, ?_⟩ + have := Nat.lt_two_pow_self (n := wd a + wd b) + simp only [wd] at hm + omega + +end Net +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Network/Matrix.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Network/Matrix.lean new file mode 100644 index 0000000000..d0ec80ee5b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Network/Matrix.lean @@ -0,0 +1,235 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange +public import Mathlib.Data.Matrix.Block +public import Mathlib.Data.Nat.Log +public import Mathlib.LinearAlgebra.FiniteDimensional.Basic +public import Mathlib.LinearAlgebra.Matrix.Reindex +public import Mathlib.LinearAlgebra.Matrix.ToLin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Dense + +/-! +# Returning a trivalent network to its ground field + +A matrix index passes through the original vertices in sequence. Parallel +composition concatenates two chains, and trace sums the original wires. A +single additional table selects the distinguished index at both ends. +-/ + +@[expose] public section + +section +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- A matrix encoding on binary indices. Padding by zeros preserves products +but need not preserve the identity matrix on unused indices. -/ +structure Representation (F L : Type) [Field F] [Field L] [Algebra F L] where + /-- The `Representation` component of type `Wire`. -/ + wire : Wire + /-- The root of type `Val wire`. -/ + root : Val wire + /-- The `Representation` component of type `L →ₗ[F] Matrix (Val wire) (Val wire) F`. -/ + M : L →ₗ[F] Matrix (Val wire) (Val wire) F + mul : ∀ u v, M (u * v) = M u * M v + scalar : ∀ x, M (algebraMap F L x) root root = x + width : 2 ^ wd wire ≤ 2 * Module.finrank F L + +private theorem card_word (n : ℕ) : Fintype.card (Val (word n)) = 2 ^ n := by + induction n with + | zero => change Fintype.card Unit = 1; simp + | succ n ih => + change Fintype.card (Bool × Val (word n)) = _ + rw [Fintype.card_prod, Fintype.card_bool, ih, pow_succ'] + +/-- Use the regular representation and pad the complementary block with zeros. +Any active diagonal index recovers base-field elements. -/ +theorem exists_representation (F L : Type) [Field F] [Field L] [Algebra F L] + [Module.Finite F L] : Nonempty (Representation F L) := by + classical + let d := Module.finrank F L + have hd : 0 < d := Module.finrank_pos + let c := Nat.clog 2 d + have hl : d ≤ 2 ^ c := Nat.le_pow_clog (by decide) d + have hu : 2 ^ c ≤ 2 * d := by + cases hc : c with + | zero => simp only [pow_zero]; omega + | succ n => + have hn : n < Nat.clog 2 d := by change n < c; omega + rw [pow_succ'] + exact Nat.mul_le_mul_left 2 (Nat.pow_lt_of_lt_clog hn).le + let I := Fin d ⊕ Fin (2 ^ c - d) + let e : I ≃ Val (word c) := Fintype.equivOfCardEq (by + rw [card_word] + simp only [I, Fintype.card_sum, Fintype.card_fin] + omega) + let A := Algebra.leftMulMatrix (Module.finBasis F L) + let B : L →ₗ[F] Matrix I I F := + { toFun := fun x => Matrix.fromBlocks (A x) 0 0 0 + map_add' := by intros; simp [I, Matrix.fromBlocks_add] + map_smul' := by intros; simp [I, Matrix.fromBlocks_smul] } + let E := Matrix.reindexAlgEquiv F F e + let i : Fin d := ⟨0, hd⟩ + refine ⟨⟨word c, e (.inl i), E.toLinearMap.comp B, ?_, ?_, ?_⟩⟩ + · intro x y + change E (B (x * y)) = E (B x) * E (B y) + rw [← map_mul] + apply congrArg E + simp [B, I, Matrix.fromBlocks_multiply] + · intro x + change B (algebraMap F L x) (e.symm (e (.inl i))) (e.symm (e (.inl i))) = x + rw [Equiv.symm_apply_apply] + change A (algebraMap F L x) i i = x + rw [A.commutes] + simp [Algebra.algebraMap_eq_smul_one] + · rw [wd_word] + exact hu + +end MatrixMultiplicationAllFields.MatrixExponent +end + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {F L : Type} [Field F] [Field L] [Algebra F L] +variable {a b c d : Wire} {m n : ℕ} + +namespace Representation + +variable (R : Representation F L) + +private def cost : ℕ := 8 * 2 ^ (wd R.wire + wd R.wire) + +private def lifted (k : Val a → Val b → L) : + Val (.pair a R.wire) → Val (.pair b R.wire) → F := + fun x y => R.M (k x.1 y.1) x.2 y.2 + +/-- The first branch handles empty networks without allocating an index. +Every nonempty chain reserves enough vertices to pin its ends once. -/ +private def Chain (a b : Wire) (k : Val a → Val b → L) (m : ℕ) : Prop := + (∃ g, Net F a b g 0 ∧ k = fun x y => algebraMap F L (g x y)) ∨ + ∃ v, Net F (.pair a R.wire) (.pair b R.wire) (R.lifted k) v ∧ + v + R.cost ≤ 9 * R.cost * m + +variable {R} + +private theorem Chain.pre {f : Val a → Val b} {k : Val b → Val c → L} + (h : R.Chain b c k m) (hf : Rewire a b f) : R.Chain a c (fun x y => k (f x) y) m := by + rcases h with ⟨g, hg, rfl⟩ | ⟨v, hv, hbound⟩ + · exact .inl ⟨_, hg.pre hf, rfl⟩ + · exact .inr ⟨v, hv.pre (hf.par (.id _)), hbound⟩ + +private theorem Chain.post {f : Val c → Val b} {k : Val a → Val b → L} + (h : R.Chain a b k m) (hf : Rewire c b f) : R.Chain a c (fun x y => k x (f y)) m := by + rcases h with ⟨g, hg, rfl⟩ | ⟨v, hv, hbound⟩ + · exact .inl ⟨_, hg.post hf, rfl⟩ + · exact .inr ⟨v, hv.post (hf.par (.id _)), hbound⟩ + +private theorem swapTail (a b c : Wire) : + Rewire (.pair (.pair a b) c) (.pair (.pair a c) b) + (fun x => ((x.1.1, x.2), x.1.2)) := + (Rewire.assoc a b c).comp (((Rewire.id a).par (.swap b c)).comp (.assoc' _ _ _)) + +private theorem Chain.trace {k : Val (.pair a c) → Val (.pair b c) → L} + (h : R.Chain (.pair a c) (.pair b c) k m) : + R.Chain a b (fun x y => ∑ z : Val c, k (x, z) (y, z)) m := by + rcases h with ⟨g, hg, rfl⟩ | ⟨v, hv, hbound⟩ + · exact .inl ⟨_, hg.trace, by simp only [map_sum]⟩ + · refine .inr ⟨v, ?_, hbound⟩ + unfold lifted + simpa only [lifted, map_sum, Matrix.sum_apply] using + ((hv.pre (swapTail a R.wire c)).post (swapTail b R.wire c)).trace + +private theorem Chain.par {k : Val a → Val b → L} {l : Val c → Val d → L} + (h : R.Chain a b k m) (i : R.Chain c d l n) : + R.Chain (.pair a c) (.pair b d) (fun x y => k x.1 y.1 * l x.2 y.2) (m + n) := by + rcases h with ⟨g, hg, rfl⟩ | ⟨u, hu, hbound⟩ <;> + rcases i with ⟨f, hf, rfl⟩ | ⟨v, hv, ibound⟩ + · exact .inl ⟨_, hg.par hf, by simp only [map_mul]⟩ + · refine .inr ⟨0 + v, ?_, by rw [mul_add]; omega⟩ + unfold lifted + simpa only [lifted, ← Algebra.smul_def, map_smul, Matrix.smul_apply, smul_eq_mul] using + ((hg.par hv).pre (.assoc a c R.wire)).post (.assoc b d R.wire) + · refine .inr ⟨u + 0, ?_, by rw [mul_add]; omega⟩ + have aux (s : L) (t : F) (x y : Val R.wire) : + R.M (s * algebraMap F L t) x y = R.M s x y * t := by + rw [mul_comm, ← Algebra.smul_def, map_smul, Matrix.smul_apply, smul_eq_mul, mul_comm] + unfold lifted + simpa only [lifted, aux] using + ((hu.par hf).pre (swapTail a c R.wire)).post (swapTail b d R.wire) + · refine .inr ⟨u + v, ?_, by rw [mul_add]; omega⟩ + let i := R.wire + have left (p q : Wire) := (Rewire.assoc (.pair p q) i i).comp (.middle p q i i) + have right := (swapTail (.pair b d) i i).comp (left b d) + unfold lifted + simpa only [lifted, R.mul, Matrix.mul_apply] using + (((hu.par hv).pre (left a c)).post right).trace + +variable (R) + +private theorem chain {k : Val a → Val b → L} (h : Net L a b k m) : R.Chain a b k m := by + induction h with + | empty => exact .inl ⟨_, .empty, by simp⟩ + | table a b k hk => + obtain ⟨v, hv, hb⟩ := Net.dense (.pair a R.wire) (.pair b R.wire) (R.lifted k) + refine .inr ⟨v, hv, ?_⟩ + have ht : v ≤ 8 * R.cost := calc + v ≤ 8 * 2 ^ (3 + (wd R.wire + wd R.wire)) := hb.trans (by + apply Nat.mul_le_mul_left + apply Nat.pow_le_pow_right (by decide) + simp only [wd] + omega) + _ = 8 * R.cost := by rw [pow_add]; rfl + omega + | par _ _ h i => exact h.par i + | comp _ _ h i => exact ((h.par i).post (.swap _ _)).trace + | trace _ h => exact h.trace + | pre _ hf h => exact h.pre hf + | post _ hf h => exact h.post hf + +private theorem descend {k : Val a → Val b → F} + (h : Net L a b (fun x y => algebraMap F L (k x y)) m) : + ∃ v, Net F a b k v ∧ v ≤ 9 * R.cost * m := by + rcases R.chain h with ⟨g, hg, he⟩ | ⟨v, hv, hb⟩ + · have : k = g := funext fun x => funext fun y => + (algebraMap F L).injective (congrFun (congrFun he x) y) + exact ⟨0, this.symm ▸ hg, Nat.zero_le _⟩ + · obtain ⟨p, hp, hp'⟩ := Net.dense R.wire R.wire + (fun x y => if x = R.root ∧ y = R.root then (1 : F) else 0) + refine ⟨v + p, ?_, (Nat.add_le_add_left hp' v).trans hb⟩ + have g := ((hv.par hp).post (swapTail b R.wire R.wire)).trace.trace + simpa only [lifted, ite_and, mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', + Finset.mem_univ, ite_true, R.scalar] using g + +private theorem cost_le : R.cost ≤ 32 * Module.finrank F L ^ 2 := by + unfold cost + rw [pow_add] + calc + _ ≤ 8 * ((2 * Module.finrank F L) * (2 * Module.finrank F L)) := + Nat.mul_le_mul_left 8 (Nat.mul_le_mul R.width R.width) + _ = _ := by ring + +end Representation + +/-- A trivalent network of ground-field values descends without changing any +exterior positions. The bound counts vertices and also holds when both sides +count the common exterior arity. -/ +theorem Net.descend [Module.Finite F L] {k : Val a → Val b → F} + (h : Net L a b (fun x y => algebraMap F L (k x y)) m) : + ∃ v, Net F a b k v ∧ v ≤ 288 * Module.finrank F L ^ 2 * m := by + obtain ⟨R⟩ := exists_representation F L + obtain ⟨v, hv, hb⟩ := R.descend h + refine ⟨v, hv, hb.trans ?_⟩ + calc + _ ≤ 9 * (32 * Module.finrank F L ^ 2) * m := + Nat.mul_le_mul_right m (Nat.mul_le_mul_left 9 R.cost_le) + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Obstruction.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Obstruction.lean new file mode 100644 index 0000000000..b7c20b5602 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Obstruction.lean @@ -0,0 +1,41 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Reduction +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Iteration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Network + +/-! +# The two alternatives on the spectral space + +Failure of shared pricing forces contact on a tripod. Shared pricing +supplies both kinds of sorting and local concentration. Two network +estimates over prime fields would exclude this second alternative. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- Square equality and rectangular rigidity follow simultaneously. -/ +theorem contact_of_network_estimates + (hard : ∀ (p : ℕ) [Fact p.Prime], Tagged.Hard (ZMod p)) + (stage : ∀ (p : ℕ) [Fact p.Prime], Prices.SharedPrice (AlgebraicClosure (ZMod p)) → + ArityReduction (ZMod p)) + (F : Type*) [Field F] : omega F = 9 / 4 ∧ Rectangle.Rigidity F := by + apply Rectangle.of_prime_fields _ F + intro p _ + apply contact_of_not_shared + intro sync + obtain ⟨q, hq, hq', sort⟩ := Routing.sorting_of_shared_price sync + have shrink := compresses_of_stages hq hq' sort (stage p sync) + exact incompatible (seed _) (Tagged.manyList_of_tag (hard p)) shrink.lists + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/BadBases.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/BadBases.lean new file mode 100644 index 0000000000..073697bb4a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/BadBases.lean @@ -0,0 +1,918 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Reservations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Delivery + +/-! +# Propagating dyadic splits across a host + +An edge with delay `d` moves a split up `2*d` levels. To bound all +propagated marks we sum a geometric majorant over neighbours. This +counts paths with multiplicity and needs no choice of shortest paths. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V : Type} + +/-- The spread used in the `Packing` construction. -/ +inductive Spread (E : V → Finset V) (d : V → V → ℕ) (M : V → (i : ℕ) → Cell i → Prop) : + V → (i : ℕ) → Cell i → Prop + | start {v i z} : M v i z → Spread E d M v i z + | move {v u i} (h : u ∈ E v) (z : Cell (i + 2 * d v u)) : + Spread E d M u (i + 2 * d v u) z → + Spread E d M v i (ancestor (Nat.le_add_right i _) z) + +variable {E : V → Finset V} {d : V → V → ℕ} {M : V → (i : ℕ) → Cell i → Prop} + +theorem Spread.depth {v i z h} (hz : Spread E d M v i z) + (bound : ∀ v i z, M v i z → i < h) : i < h := by + induction hz with + | start hz => exact bound _ _ _ hz + | move _ _ _ ih => omega + +theorem Spread.up {v i z} (hz : Spread E d M v i z) + (up : ∀ v i z, M v i z → ∀ j (h : j ≤ i), M v j (ancestor h z)) : + ∀ j (h : j ≤ i), Spread E d M v j (ancestor h z) := by + induction hz with + | start hz => exact fun j h => .start (up _ _ _ hz j h) + | @move v u i hv z _ ih => + intro j h + exact .move hv (ancestor (Nat.add_le_add_right h (2 * d v u)) z) + (ih _ (Nat.add_le_add_right h _)) + +noncomputable section + +open Classical in +/-- The sum of `if M v i z then 1 else 0` indexed by `z : Cell i`. -/ +def count (M : V → (i : ℕ) → Cell i → Prop) (v : V) (i : ℕ) : ℝ := + ∑ z : Cell i, if M v i z then 1 else 0 + +open Classical in +private theorem from_move {v i z} (hz : Spread E d M v i z) : + M v i z ∨ ∃ u ∈ E v, ∃ c : Cell (i + 2 * d v u), + Spread E d M u _ c ∧ ancestor (Nat.le_add_right i _) c = z := by + cases hz with + | start hx => exact .inl hx + | move e c hx => exact .inr ⟨_, e, c, hx, rfl⟩ + +open Classical in +theorem count_move (v : V) (i : ℕ) : + count (Spread E d M) v i ≤ count M v i + ∑ u ∈ E v, count (Spread E d M) u (i + 2 * d v u) := by + let f (u : V) (c : Cell (i + 2 * d v u)) (z : Cell i) : ℝ := + if ancestor (Nat.le_add_right i _) c = z then (if Spread E d M u _ c then 1 else 0) else 0 + have hf (u : V) (c : Cell (i + 2 * d v u)) (z : Cell i) : 0 ≤ f u c z := by unfold f; positivity + have point (z : Cell i) : + (if Spread E d M v i z then (1 : ℝ) else 0) ≤ + (if M v i z then 1 else 0) + ∑ u ∈ E v, ∑ c, f u c z := by + have h₀ : 0 ≤ ∑ u ∈ E v, ∑ c, f u c z := sum_nonneg fun u _ => sum_nonneg fun c _ => hf u c z + by_cases h : Spread E d M v i z + · rw [ite_eq_left h] + rcases from_move h with hz | ⟨u, hu, c, hc, he⟩ + · rw [ite_eq_left hz]; linarith + · calc + 1 = f u c z := by simp [f, he, hc] + _ ≤ ∑ c, f u c z := single_le_sum (fun a _ => hf u a z) (mem_univ c) + _ ≤ ∑ u ∈ E v, ∑ c, f u c z := + single_le_sum (f := fun u => ∑ c, f u c z) (fun u _ => sum_nonneg fun c _ + => hf u c z) hu + _ ≤ _ := le_add_of_nonneg_left (by positivity) + · rw [ite_eq_right h]; positivity + unfold count + refine (sum_le_sum (fun z (_ : z ∈ univ) => point z)).trans_eq ?_ + rw [sum_add_distrib, sum_comm] + congr 1 + apply sum_congr rfl + intro u _ + rw [sum_comm] + simp [f] + +open Classical in +private def envelope (E : V → Finset V) (d : V → V → ℕ) (x : V → ℝ) : ℕ → V → ℝ + | 0, _ => 0 + | j + 1, v => x v + ∑ u ∈ E v, envelope E d x j u / 2 ^ (d v u) + +open Classical in +private theorem positive {x : V → ℝ} (hx : ∀ v, 0 ≤ x v) (j : ℕ) (v : V) : + 0 ≤ envelope E d x j v := by + induction j generalizing v with + | zero => exact le_rfl + | succ j ih => exact add_nonneg (hx v) (sum_nonneg fun u _ => div_nonneg (ih u) (by positivity)) + +open Classical in +private theorem mass [Fintype V] {x : V → ℝ} (hx : ∀ v, 0 ≤ x v) + (hs : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) (j : ℕ) : + ∑ v, envelope E d x j v ≤ 2 * ∑ v, x v := by + induction j with + | zero => + simp only [envelope, sum_const_zero] + exact mul_nonneg (by norm_num) (sum_nonneg fun v _ => hx v) + | succ j ih => + let Y := envelope E d x j + have h (v : V) : (∑ u ∈ E v, Y u / (2 : ℝ) ^ (d v u)) = + ∑ u, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) * Y u := by + simp [ite_mul, div_eq_mul_inv, mul_comm] + change (∑ v, (x v + ∑ u ∈ E v, Y u / 2 ^ (d v u))) ≤ _ + simp_rw [sum_add_distrib, h] + rw [sum_comm] + simp_rw [← sum_mul] + have hb : (∑ u, (∑ v, if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) * Y u) ≤ + ∑ u, (1 / 2 : ℝ) * Y u := + sum_le_sum (fun u _ => mul_le_mul_of_nonneg_right (hs u) (positive hx j u)) + rw [← mul_sum] at hb + change (∑ v, Y v) ≤ _ at ih + linarith + +open Classical in +private theorem majorize {P : Type} [Fintype P] {M : P → V → (i : ℕ) → Cell i → Prop} + {h : ℕ} {x : V → ℝ} (hx : ∀ v, 0 ≤ x v) + (hd : ∀ v u, u ∈ E v → 0 < d v u) (hm : ∀ p v i z, M p v i z → i < h) + (he : ∀ v i, ∑ p, count (M p) v i ≤ (Fintype.card P : ℝ) * 2 * (x v) ^ 2 / (2 : ℝ) ^ i) + (j i : ℕ) (hij : h ≤ i + j) (v : V) : + ∑ p, count (Spread E d (M p)) v i ≤ + (Fintype.card P : ℝ) * 2 * (envelope E d x j v) ^ 2 / (2 : ℝ) ^ i := by + induction j generalizing i v with + | zero => + have no (p : P) (z : Cell i) : ¬Spread E d (M p) v i z := + fun hz => by have := hz.depth (hm p); omega + simp [count, no, envelope] + | succ j ih => + let C := (Fintype.card P : ℝ) * 2 / (2 : ℝ) ^ i + let y := fun u => envelope E d x j u / (2 : ℝ) ^ (d v u) + let Y := envelope E d x (j + 1) v + have hy (u : V) : 0 ≤ y u := div_nonneg (positive hx j u) (by positivity) + have hsum : 0 ≤ ∑ u ∈ E v, y u := sum_nonneg fun u _ => hy u + have hdirect : (∑ p, count (M p) v i) ≤ C * Y * x v := calc + _ ≤ (Fintype.card P : ℝ) * 2 * (x v) ^ 2 / (2 : ℝ) ^ i := he _ _ + _ = C * x v * x v := by unfold C; ring + _ ≤ _ := by + have : x v ≤ Y := le_add_of_nonneg_right hsum + have hC : 0 ≤ C := by + unfold C + positivity + exact mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left this hC) (hx v) + have hedge (u : V) (hu : u ∈ E v) : + (∑ p, count (Spread E d (M p)) u (i + 2 * d v u)) ≤ C * Y * y u := calc + _ ≤ (Fintype.card P : ℝ) * 2 * (envelope E d x j u) ^ 2 / (2 : ℝ) ^ (i + 2 * d v u) := + ih _ (by have := hd v u hu; omega) u + _ = C * y u * y u := by + unfold C y + rw [pow_add, mul_comm 2 (d v u), pow_mul] + ring + _ ≤ _ := by + have hle : y u ≤ Y := (single_le_sum (fun a _ + => hy a) hu).trans (le_add_of_nonneg_left (hx v)) + have hC : 0 ≤ C := by + unfold C + positivity + exact mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hle hC) (hy u) + calc + _ ≤ ∑ p, (count (M p) v i + ∑ u ∈ E v, count (Spread E d (M p)) u (i + 2 * d v u)) := + sum_le_sum fun p _ => count_move v i + _ ≤ C * Y * x v + ∑ u ∈ E v, C * Y * y u := by + rw [sum_add_distrib, sum_comm]; exact add_le_add hdirect (sum_le_sum hedge) + _ = _ := by + rw [← mul_sum, ← mul_add] + change C * Y * Y = _ + unfold C Y; ring + +-- A telescoping bound switches from the number of cells to the +-- collision estimate as the cell count passes the load envelope. +open Classical in +private def reserve (x t : ℝ) := if t ≤ x then 8 * x - t else 4 * x ^ 2 / t + +open Classical in +private theorem spend {x t : ℝ} (ht : 0 < t) : + min t (2 * x ^ 2 / t) + reserve x (2 * t) ≤ reserve x t := by + by_cases h : t ≤ x + · have hu := min_le_left t (2 * x ^ 2 / t) + by_cases h' : 2 * t ≤ x + · simp only [reserve, ite_eq_left h, ite_eq_left h']; linarith + · have : 4 * x ^ 2 / (2 * t) ≤ 4 * x := by + apply (div_le_iff₀ (by positivity)).mpr + nlinarith + simp only [reserve, ite_eq_left h, ite_eq_right h']; linarith + · have hu := min_le_right t (2 * x ^ 2 / t) + have h' : ¬ 2 * t ≤ x := by linarith + simp only [reserve, ite_eq_right h, ite_eq_right h'] + calc + _ ≤ 2 * x ^ 2 / t + 4 * x ^ 2 / (2 * t) := add_le_add_left hu _ + _ = _ := by ring + +open Classical in +private theorem dyadic {x : ℝ} (hx : 0 ≤ x) (h : ℕ) : + ∑ i ∈ range h, min ((2 : ℝ) ^ i) (2 * x ^ 2 / 2 ^ i) ≤ 8 * x := by + have hi (i : ℕ) : + min ((2 : ℝ) ^ i) (2 * x ^ 2 / 2 ^ i) ≤ reserve x (2 ^ i) - reserve x (2 ^ (i + 1)) := by + rw [le_sub_iff_add_le, pow_succ' (2 : ℝ) i] + exact spend (x := x) (t := (2 : ℝ) ^ i) (by positivity) + have hlast : 0 ≤ reserve x (2 ^ h) := by + unfold reserve + split <;> first | positivity | linarith + have hfirst : reserve x 1 ≤ 8 * x := by + unfold reserve + split <;> nlinarith + calc + _ ≤ ∑ i ∈ range h, (reserve x (2 ^ i) - reserve x (2 ^ (i + 1))) := + sum_le_sum (fun i _ => hi i) + _ = reserve x 1 - reserve x (2 ^ h) := by + simpa using sum_range_sub' (fun i => reserve x (2 ^ i)) h + _ ≤ _ := by linarith + +open Classical in +/-- A column-sum bound on the delay weights gives an absolute constant, +independent of the number of neighbours and the number of levels. -/ +theorem spread_bound {P : Type} [Fintype V] [Fintype P] + (E : V → Finset V) (d : V → V → ℕ) + (M : P → V → (i : ℕ) → Cell i → Prop) (x : V → ℝ) (h : ℕ) + (hx : ∀ v, 0 ≤ x v) (hd : ∀ v u, u ∈ E v → 0 < d v u) + (hs : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) + (hm : ∀ p v i z, M p v i z → i < h) + (he : ∀ v i, ∑ p, ∑ z : Cell i, (if M p v i z then (1 : ℝ) else 0) ≤ + (Fintype.card P : ℝ) * 2 * (x v) ^ 2 / (2 : ℝ) ^ i) : + ∑ p, ∑ v, ∑ i ∈ range h, ∑ z : Cell i, (if Spread E d (M p) v i z then (1 : ℝ) else 0) + ≤ (Fintype.card P : ℝ) * 16*∑ v, x v := by + let Y := envelope E d x h + let N : ℝ := Fintype.card P + have hN : 0 ≤ N := Nat.cast_nonneg _ + have depth (v : V) (i : ℕ) : + ∑ p, count (Spread E d (M p)) v i ≤ N * min (2 ^ i) (2 * (Y v) ^ 2 / 2 ^ i) := by + rw [mul_min_of_nonneg _ _ hN] + apply le_min + · calc + _ ≤ ∑ _p : P, ∑ _z : Cell i, (1 : ℝ) := + sum_le_sum fun _ _ => sum_le_sum fun _ _ => by split <;> norm_num + _ = _ := by simp [N, Cell] + · calc + _ ≤ N * 2 * (Y v) ^ 2 / (2 : ℝ) ^ i := majorize hx hd hm he h i (by omega) v + _ = _ := by ring + have vertex (v : V) : (∑ p, ∑ i ∈ range h, count (Spread E d (M p)) v i) ≤ N * (8 * Y v) := by + rw [sum_comm] + calc + _ ≤ ∑ i ∈ range h, N * min (2 ^ i) (2 * (Y v) ^ 2 / 2 ^ i) := sum_le_sum fun i _ => depth v i + _ ≤ _ := by + rw [← mul_sum] + exact mul_le_mul_of_nonneg_left (dyadic (positive hx h v) h) hN + rw [sum_comm] + calc + _ ≤ ∑ v, N * (8 * Y v) := sum_le_sum fun v _ => vertex v + _ ≤ N * (8 * (2 * ∑ v, x v)) := by + rw [← mul_sum, ← mul_sum] + exact mul_le_mul_of_nonneg_left (mul_le_mul_of_nonneg_left (mass hx hs h) (by norm_num)) hN + _ = _ := by unfold N; ring + +end +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Propagation through fixed bases + +Weight the count of splits by the depth below each vertex's base. Moving +a mark across an edge of length `16 * d` costs at least `8 * d` levels +relative to the respective bases, and thus a factor of at least `2 ^ d`. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +open scoped Classical in +private theorem shift_le (f : ℕ → ℝ) (n a : ℕ) (hf : ∀ j, 0 ≤ f j) + (hz : ∀ j, n ≤ j → f j = 0) : + ∑ j ∈ range n, f (a + j) ≤ ∑ j ∈ range n, f j := by + calc + _ ≤ ∑ j ∈ range (a + n), f j := by + rw [sum_range_add] + exact le_add_of_nonneg_left (sum_nonneg fun j _ => hf j) + _ = _ := by + rw [add_comm a n, sum_range_add, add_eq_left] + exact sum_eq_zero fun j _ => hz _ (Nat.le_add_right _ _) + +open scoped Classical in +private def weight (j : ℕ) : ℝ := 2 ^ ((j + 7) / 8) + +open scoped Classical in +private theorem edge_shift (f : ℕ → ℝ) (n a b d : ℕ) + (hf : ∀ j, 0 ≤ f j) (hz : ∀ j, n ≤ j → f j = 0) (hab : b ≤ a + 8 * d) : + ∑ j ∈ range n, weight j * f (a + j + 2 * (8 * d)) ≤ + 1 / (2 : ℝ) ^ d * (∑ j ∈ range n, weight j * f (b + j)) := by + let r := a + 16 * d - b + have hr : 8 * d ≤ r := by unfold r; omega + have hw (j : ℕ) : weight j ≤ 1 / (2 : ℝ) ^ d * weight (r + j) := by + rw [one_div_mul_eq_div, le_div_iff₀ (by positivity)] + unfold weight + rw [← pow_add] + exact pow_le_pow_right₀ (by norm_num) (by omega) + calc + _ ≤ 1 / (2 : ℝ) ^ d * (∑ j ∈ range n, weight (r + j) * f (b + (r + j))) := by + rw [mul_sum] + apply sum_le_sum + intro j _ + rw [show a + j + 2 * (8 * d) = b + (r + j) by unfold r; omega, ← mul_assoc] + exact mul_le_mul_of_nonneg_right (hw j) (hf _) + _ ≤ _ := mul_le_mul_of_nonneg_left (shift_le (fun j => weight j * f (b + j)) n r + (fun j => mul_nonneg (by unfold weight; positivity) (hf _)) + (fun j hj => by rw [hz (b + j) (by omega), mul_zero])) (by positivity) + +variable {V : Type} [Fintype V] + +open scoped Classical in +private theorem incoming (E : V → Finset V) (d : V → V → ℕ) + (budget : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) + (y : V → ℝ) (hy : ∀ u, 0 ≤ y u) : + (∑ v, ∑ u ∈ E v, 1 / (2 : ℝ) ^ (d v u) * y u) ≤ (1 / 2 : ℝ) * ∑ u, y u := by + have expand (v : V) : (∑ u ∈ E v, 1 / (2 : ℝ) ^ (d v u) * y u) = + ∑ u, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) * y u := by simp [ite_mul] + simp_rw [expand] + rw [sum_comm, mul_sum] + simp_rw [← sum_mul] + exact sum_le_sum fun u _ => mul_le_mul_of_nonneg_right (budget u) (hy u) + +open scoped Classical in +/-- Choose base depths from the total normalized loads, before mixing. +In a minimal feasible choice each depth is tight either locally or +along an edge. The incoming weight bound pays for all tight edges. -/ +theorem choose_bases (E : V → Finset V) (d : V → V → ℕ) + (budget : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) + (a b : ℕ) (hab : a ≤ b) (t : V → ℝ) (ht : ∀ v, 0 ≤ t v ∧ t v ≤ (2 : ℝ) ^ b) : + ∃ base : V → ℕ, (∀ v, a ≤ base v ∧ base v ≤ b ∧ t v ≤ (2 : ℝ) ^ (base v)) ∧ + (∀ v u, u ∈ E v → base u ≤ base v + 8 * d v u) ∧ + (∑ v, (2 : ℝ) ^ (base v)) ≤ 2 * Fintype.card V * (2 : ℝ) ^ a + 4 * (∑ v, t v) := by + let good (c : V → ℕ) := (∀ v, a ≤ c v ∧ c v ≤ b ∧ t v ≤ (2 : ℝ) ^ (c v)) ∧ + ∀ v u, u ∈ E v → c u ≤ c v + 8 * d v u + have hex : ∃ n, ∃ c, good c ∧ (∑ v, c v) = n := by + refine ⟨_, fun _ => b, ⟨fun v => ⟨hab, le_rfl, (ht v).2⟩, ?_⟩, rfl⟩ + exact fun _ _ _ => Nat.le_add_right _ _ + obtain ⟨c, ⟨hc, hadj⟩, hmin⟩ := Nat.find_spec hex + have tight (v : V) : c v = a ∨ (2 : ℝ) ^ (c v - 1) < t v ∨ + ∃ u ∈ E v, c u = c v + 8 * d v u := by + by_contra! bad + obtain ⟨hneq, hsmall, hslack⟩ := bad + have ha := (hc v).1 + let c' (u : V) := if u = v then c v - 1 else c u + have hle (u : V) : c' u ≤ c u := by + by_cases he : u = v <;> simp [c', he] + have hv : c' v = c v - 1 := ite_eq_left rfl + have ok : good c' := by + constructor + · intro u + by_cases he : u = v + · subst u; rw [hv] + exact ⟨by omega, (Nat.sub_le _ _).trans (hc v).2.1, hsmall⟩ + · simpa only [c', ite_eq_right he] using hc u + · intro w u hu + refine (hle u).trans ?_ + by_cases he : w = v + · subst w + have := hadj v u hu + have := hslack u hu + rw [hv] + omega + · simpa only [c', ite_eq_right he] using hadj w u hu + have hlt : (∑ u, c' u) < ∑ u, c u := + sum_lt_sum (fun u _ => hle u) ⟨v, mem_univ v, by rw [hv]; omega⟩ + exact Nat.find_min hex (hlt.trans_eq hmin) ⟨c', ok, rfl⟩ + refine ⟨c, hc, hadj, ?_⟩ + have step (v : V) : (2 : ℝ) ^ (c v) ≤ + (2 : ℝ) ^ a + 2 * t v + ∑ u ∈ E v, 1 / (2 : ℝ) ^ (d v u) * (2 : ℝ) ^ (c u) := by + have ht' := (ht v).1 + have hf (u : V) : 0 ≤ 1 / (2 : ℝ) ^ (d v u) * (2 : ℝ) ^ (c u) := by positivity + have hsum := sum_nonneg (fun u (_ : u ∈ E v) => hf u) + rcases tight v with ha | ht'' | ⟨u, hu, had⟩ + · rw [ha]; linarith + · have hp : (2 : ℝ) ^ (c v) ≤ (2 : ℝ) ^ (c v - 1) * 2 := by + rw [← pow_succ] + exact pow_le_pow_right₀ (by norm_num) (by omega) + linarith [show 0 ≤ (2 : ℝ) ^ a by positivity] + · refine (le_add_of_nonneg_left (by positivity)).trans' ?_ + calc + _ ≤ 1 / (2 : ℝ) ^ (d v u) * (2 : ℝ) ^ (c u) := by + rw [one_div_mul_eq_div, le_div_iff₀ (by positivity), ← pow_add] + exact pow_le_pow_right₀ (by norm_num) (by omega) + _ ≤ ∑ u ∈ E v, 1 / (2 : ℝ) ^ (d v u) * (2 : ℝ) ^ (c u) := + single_le_sum (fun u _ => hf u) hu + have hstep := sum_le_sum (fun v (_ : v ∈ univ) => step v) + simp only [sum_add_distrib, sum_const, card_univ, nsmul_eq_mul, ← mul_sum] at hstep + have hedge := incoming E d budget (fun v => (2 : ℝ) ^ (c v)) (fun _ => by positivity) + linarith + +open scoped Classical in +/-- Bound the number of base cells forced to split by the weighted initial +marks within all bases. The constant is independent of the host degree. -/ +theorem base_splits (E : V → Finset V) (d : V → V → ℕ) + (M : V → (i : ℕ) → Cell i → Prop) (base : V → ℕ) (h : ℕ) + (drop : ∀ v u, u ∈ E v → base u ≤ base v + 8 * d v u) + (budget : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) + (cut : ∀ v i z, M v i z → i < h + 1) : + (∑ v, ∑ z, if Spread E (fun v u => 8 * d v u) M v (base v) z then (1 : ℝ) else 0) ≤ + ∑ v, ∑ j ∈ range (h + 1), 2 * (2 : ℝ) ^ ((j + 7) / 8) * + (∑ z, if M v (base v + j) z then (1 : ℝ) else 0) := by + let S := Spread E (fun v u => 8 * d v u) M + let W (N : V → (i : ℕ) → Cell i → Prop) (v : V) := + ∑ j ∈ range (h + 1), weight j * count N v (base v + j) + have hw (j : ℕ) : 0 ≤ weight j := by unfold weight; positivity + have pos (v : V) (i : ℕ) : 0 ≤ count S v i := sum_nonneg fun _ _ => by positivity + have high (v : V) (i : ℕ) (hi : h + 1 ≤ i) : count S v i = 0 := by + have not_marked (z : Cell i) : ¬S v i z := fun hz => hi.not_gt (hz.depth cut) + simp [count, not_marked] + have hp (v : V) : 0 ≤ W S v := sum_nonneg fun j _ => mul_nonneg (hw j) (pos _ _) + have step (v : V) : W S v ≤ W M v + ∑ u ∈ E v, 1 / (2 : ℝ) ^ (d v u) * W S u := by + calc + _ ≤ ∑ j ∈ range (h + 1), weight j * (count M v (base v + j) + + ∑ u ∈ E v, count S u (base v + j + 2 * (8 * d v u))) := + sum_le_sum fun j _ => mul_le_mul_of_nonneg_left (count_move _ _) (hw j) + _ ≤ _ := by + simp_rw [mul_add, sum_add_distrib, mul_sum] + rw [sum_comm] + exact add_le_add_right (sum_le_sum fun u hu => + edge_shift _ _ _ _ _ (pos u) (high u) (drop v u hu)) _ + have edge := incoming E d budget (W S) hp + calc + _ ≤ ∑ v, W S v := by + apply sum_le_sum + intro v _ + have := single_le_sum (s := range (h + 1)) + (fun j _ => mul_nonneg (hw j) (pos v (base v + j))) (mem_range.mpr (Nat.zero_lt_succ h)) + change count S v (base v) ≤ W S v + simpa only [W, weight, Nat.zero_add, Nat.reduceDiv, pow_zero, one_mul, Nat.add_zero] + using this + _ ≤ 2 * ∑ v, W M v := by + have := sum_le_sum (fun v (_ : v ∈ univ) => step v) + rw [sum_add_distrib] at this + linarith + _ = _ := by simp only [W, weight, count, mul_sum, mul_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +section +/- +# Initial marks in the dyadic tree + +A heavy cell carries more than one unit of normalized load. Since no +block carries more than half a unit, at least half a unit of ordered +cross products lies in this cell. Only pairwise collisions are needed +to bound the mean number of initial marks. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +variable {h i j : ℕ} + +open scoped Classical in +/-- Load is normalized by the capacity of a colony. -/ +def heavy (l : Cell h → ℝ) (π : Equiv.Perm (Cell h)) (i : ℕ) (z : Cell i) : Prop := + ∃ hi : i ≤ h, 1 < ∑ x, if ancestor hi (π x) = z then l x else 0 + +open scoped Classical in +theorem heavy.ancestor {l : Cell h → ℝ} (hl : ∀ x, 0 ≤ l x) {π : Equiv.Perm (Cell h)} + {z : Cell j} (hz : heavy l π j z) (hi : i ≤ j) : heavy l π i (ancestor hi z) := by + obtain ⟨hj, hsum⟩ := hz + refine ⟨hi.trans hj, hsum.trans_le (Finset.sum_le_sum fun x _ => ?_)⟩ + by_cases hx : Packing.ancestor hj (π x) = z + · have : Packing.ancestor (hi.trans hj) (π x) = Packing.ancestor hi z := + congrArg (Packing.ancestor hi) hx + simp [hx, this] + · simp only [ite_eq_right hx] + split_ifs <;> first | exact hl _ | rfl + +open scoped Classical in +theorem heavy.lt {l : Cell h → ℝ} (hl : ∀ x, l x ≤ 1) {π : Equiv.Perm (Cell h)} + {z : Cell i} (hz : heavy l π i z) : i < h := by + obtain ⟨hi, hsum⟩ := hz + refine lt_of_le_of_ne hi ?_ + rintro rfl + simp only [ancestor_self, ← π.eq_symm_apply, Finset.sum_ite_eq', Finset.mem_univ, ite_true] + at hsum + exact (hl _).not_gt hsum + +open scoped Classical in +/-- If each block occupies at most a reciprocal power of two units, the +finest levels need no splits. -/ +theorem heavy.depth {l : Cell h → ℝ} {π : Equiv.Perm (Cell h)} {z : Cell i} {k : ℕ} + (hk : k ≤ h) (hl : ∀ x, l x ≤ 1 / (2 : ℝ) ^ k) (hz : heavy l π i z) : + i < h - k := by + obtain ⟨hi, hsum⟩ := hz + by_contra! hd + have hr : (2 : ℝ) ^ (h - i) ≤ 2 ^ k := pow_le_pow_right₀ (by norm_num) (by omega) + apply hsum.not_ge + calc + _ ≤ ∑ x, (if Packing.ancestor hi (π x) = z then (1 : ℝ) else 0) * (1 / 2 ^ k) := by + apply Finset.sum_le_sum + intro x _ + split_ifs <;> simp only [one_mul, zero_mul, le_refl, hl] + _ = (2 : ℝ) ^ (h - i) / 2 ^ k := by + rw [← Finset.sum_mul, Equiv.sum_comp π (fun x => if Packing.ancestor hi x + = z then (1 : ℝ) else 0), + Finset.sum_boole, ← Fintype.card_subtype, card_prefix] + simp [div_eq_mul_inv] + _ ≤ 1 := (div_le_one (by positivity)).mpr hr + +open scoped Classical in +theorem heavy_bound {M : Type} [Fintype M] (l : Cell h → ℝ) (hl : ∀ x, 0 ≤ l x ∧ l x ≤ 1 / 2) + (π : M → Equiv.Perm (Cell h)) (hπ : Mixes π) (i : ℕ) : + (∑ m : M, ∑ z : Cell i, if heavy l (π m) i z then (1 : ℝ) else 0) ≤ + (Fintype.card M : ℝ) * 2 * (∑ x, l x) ^ 2 / (2 : ℝ) ^ i := by + by_cases hi : i ≤ h + swap + · have hn m z : ¬ heavy l (π m) i z := fun h => hi h.choose + simp only [hn, ite_false, Finset.sum_const_zero] + positivity + have hl₀ x := (hl x).1 + calc + _ ≤ 2 * ∑ m, ∑ z, cross l (π m) i z := by + simp only [Finset.mul_sum] + apply Finset.sum_le_sum + intro m _ + apply Finset.sum_le_sum + intro z _ + split_ifs with hz + · have hb : 1 < load l (π m) i z := by simpa [load, hi] using hz.choose_spec + unfold cross + nlinarith [diagonal_le l (π m) i z hl] + · exact mul_nonneg (by norm_num) (cross_nonneg l (π m) i hl₀ z) + _ ≤ 2 * ((Fintype.card M : ℝ) * ((∑ x, l x) ^ 2 / (2 : ℝ) ^ i)) := + mul_le_mul_of_nonneg_left (cross_bound l i hπ hl₀ hi) (by norm_num) + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# A fixed menu of mixers for every block length + +The number of candidates is at most the block count. Repetitions and +unused entries are harmless because the election minimizes a score. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +open scoped Classical in +theorem menu_exists (h : ℕ) : + ∃ π : Fin (2 ^ h) → (Cell h ≃ₗ[ZMod 2] Cell h), + ∃ (P : Type) (_ : Fintype P) (_ : Nonempty P) (f : P → Fin (2 ^ h)), + Mixes (fun p => (π (f p)).toEquiv) := by + obtain ⟨P, _, _, s, hs, hlin, hcol⟩ := mixer h + choose g hg using hlin + obtain ⟨f⟩ : Nonempty (P ↪ Fin (2 ^ h)) := Function.Embedding.nonempty_of_card_le (by simpa) + let π i := if hi : ∃ q, f q = i then g hi.choose else LinearEquiv.refl _ _ + have he q : (π (f q)).toEquiv = s q := by + have hq : ∃ t, f t = f q := ⟨q, rfl⟩ + simpa only [π, dite_eq_left hq, f.injective hq.choose_spec] using hg q + exact ⟨π, P, inferInstance, inferInstance, f, by simpa only [he] using hcol⟩ + +open scoped Classical in +/-- The value specified by `(menu_exists h).choose`. -/ +def menu (h : ℕ) := (menu_exists h).choose + +open scoped Classical in +theorem menu_samples (h : ℕ) : ∃ (P : Type) (_ : Fintype P) (_ : Nonempty P) + (f : P → Fin (2 ^ h)), Mixes (fun p => (menu h (f p)).toEquiv) := + (menu_exists h).choose_spec + +variable {V : Type} {h : ℕ} (E : V → Finset V) (d : V → V → ℕ) + (l : V → Cell h → ℝ) (p : Fin (2 ^ h)) + +open scoped Classical in +/-- The indexed operation `Spread E d (fun v => heavy (l v) (menu h p).toEquiv)`. -/ +def marks := Spread E d (fun v => heavy (l v) (menu h p).toEquiv) + +open scoped Classical in +/-- The sum of `(univ.filter (marks E d l p v i)).card` indexed by `i ∈ range h`. -/ +def splits (v : V) := ∑ i ∈ range h, (univ.filter (marks E d l p v i)).card + +open scoped Classical in +theorem splits_le (v : V) : splits E d l p v < 2 ^ h := by + have sum (n : ℕ) : (∑ i ∈ range n, (2 : ℕ) ^ i) < 2 ^ n := by + induction n with + | zero => simp + | succ n ih => rw [sum_range_succ, pow_succ]; omega + refine lt_of_le_of_lt (sum_le_sum ?_) (sum h) + intro i _ + rw [← card_cell] + exact card_filter_le _ _ + +open scoped Classical in +/-- The condition `∀ q, ∑ v, splits E d l p v ≤ ∑ v, splits E d l q v` on the specified data. -/ +def best [Fintype V] : Prop := ∀ q, ∑ v, splits E d l p v ≤ ∑ v, splits E d l q v + +open scoped Classical in +theorem best_exists [Fintype V] : ∃ p, best E d l p := by + obtain ⟨p, _, hp⟩ := univ.exists_min_image (fun p => ∑ v, splits E d l p v) univ_nonempty + exact ⟨p, fun q => hp _ (mem_univ q)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Bad bases in a degree reset + +Index contacts by a family and a binary cell within it. Only their two +endpoints are charged on overflow. All positions and contacts use the +same permutation of the blocks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +open scoped Classical in +private theorem incident {X Y : Type} [Fintype X] [Fintype Y] + (endpt : Y → Bool → X) (bad : Y → Prop) : + (∑ x, if ∃ y b, bad y ∧ endpt y b = x then (1 : ℝ) else 0) ≤ + 2 * ∑ y, if bad y then (1 : ℝ) else 0 := by + let f (x : X) (p : Y × Bool) := if bad p.1 ∧ endpt p.1 p.2 = x then (1 : ℝ) else 0 + have hf x p : 0 ≤ f x p := by unfold f; split_ifs <;> norm_num + calc + _ ≤ ∑ x, ∑ p, f x p := by + apply sum_le_sum + intro x _ + split_ifs with hx + · obtain ⟨y, b, hy, hb⟩ := hx + have he : f x (y, b) = 1 := ite_eq_left ⟨hy, hb⟩ + rw [← he] + exact single_le_sum (fun p _ => hf x p) (mem_univ (y, b)) + · exact sum_nonneg fun p _ => hf x p + _ = _ := by + rw [sum_comm, Fintype.sum_prod_type, mul_sum] + apply sum_congr rfl + intro y _ + by_cases hy : bad y <;> simp [f, hy] + +open scoped Classical in +private theorem charge {X Y : Type} [Fintype X] [Fintype Y] + (endpt : Y → Bool → X) (mass : X → ℝ) (split : X → Prop) (spill : Y → Prop) : + (∑ x, if split x ∨ ∃ y b, spill y ∧ endpt y b = x then mass x else 0) ≤ + (∑ x, if 2 < mass x then mass x else 0) + + 2 * (∑ x, if split x then (1 : ℝ) else 0) + 4 * ∑ y, if spill y then (1 : ℝ) else 0 := by + let hit x := ∃ y b, spill y ∧ endpt y b = x + calc + _ ≤ ∑ x, ((if 2 < mass x then mass x else 0) + + 2 * (if split x then (1 : ℝ) else 0) + 2 * (if hit x then (1 : ℝ) else 0)) := by + apply sum_le_sum + intro x _ + change (if split x ∨ hit x then mass x else 0) ≤ _ + by_cases hs : split x <;> by_cases hh : hit x <;> + simp only [hs, hh, or_true, or_false, ite_true, ite_false] <;> split_ifs <;> linarith + _ ≤ _ := by + rw [sum_add_distrib, sum_add_distrib, ← mul_sum, ← mul_sum] + have := incident endpt spill + dsimp only [hit] + linarith + +variable {V A : Type} [Fintype V] [Fintype A] {h k : ℕ} +variable (E : V → Finset V) (d : V → V → ℕ) (base : V → ℕ) (q : A → ℕ) +variable (endpt : (Σ c, Cell (q c)) → Bool → Σ v, Cell (base v)) +variable (l : V → Cell h → ℝ) (y : A → Cell h → ℝ) (g : ℝ) +variable (π : Equiv.Perm (Cell h)) + +open scoped Classical in +/-- A split propagated from a cell of load greater than two, or an +endpoint of a contact with load exceeding its mean by more than `1/g`. -/ +def BadBase (z : Σ v, Cell (base v)) : Prop := + Spread E (fun v u => 8 * d v u) (fun v i z => 2 < load (l v) π i z) z.1 (base z.1) z.2 ∨ + ∃ c b, mean (y c.1) (q c.1) + 1 / g < load (y c.1) π (q c.1) c.2 ∧ endpt c b = z + +open scoped Classical in +/-- The value specified by `∑ z, if BadBase E d base q endpt l y g π z then load (l z.1) π (base +z.1) z.2 else 0`. -/ +def badLoad : ℝ := + ∑ z, if BadBase E d base q endpt l y g π z then load (l z.1) π (base z.1) z.2 else 0 + +open scoped Classical in +private theorem charge_splits + (drop : ∀ v u, u ∈ E v → base u ≤ base v + 8 * d v u) + (budget : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) : + badLoad E d base q endpt l y g π ≤ + 3 * (∑ v, ∑ j ∈ range (h + 1), resetWeight j * excess (l v) π (base v + j)) + + 4 * ∑ c, spills (y c) π (q c) g := by + let mark v i z := 2 < load (l v) π i z + have cut v i z (hz : mark v i z) : i < h + 1 := by + by_contra! bad + norm_num [mark, load, show ¬ i ≤ h by omega] at hz + let split (z : Σ v, Cell (base v)) := + Spread E (fun v u => 8 * d v u) mark z.1 (base z.1) z.2 + let spill (c : Σ c, Cell (q c)) := + mean (y c.1) (q c.1) + 1 / g < load (y c.1) π (q c.1) c.2 + let mass (z : Σ v, Cell (base v)) := load (l z.1) π (base z.1) z.2 + let Q v j := resetWeight j * excess (l v) π (base v + j) + have hQ v j : 0 ≤ Q v j := by + unfold Q resetWeight excess + apply mul_nonneg (by positivity) + exact sum_nonneg fun z _ => by split_ifs <;> linarith + have hs : (∑ z, if split z then (1 : ℝ) else 0) ≤ ∑ v, ∑ j ∈ range (h + 1), Q v j := by + rw [Fintype.sum_sigma] + apply (base_splits E d mark base h drop budget cut).trans + apply sum_le_sum + intro v _ + apply sum_le_sum + intro j _ + rw [mul_comm 2, mul_assoc] + exact mul_le_mul_of_nonneg_left (overload_count (l v) π _) (by positivity) + have hb : (∑ z, if 2 < mass z then mass z else 0) ≤ ∑ v, ∑ j ∈ range (h + 1), Q v j := by + rw [Fintype.sum_sigma] + apply sum_le_sum + intro v _ + have hzero : Q v 0 = excess (l v) π (base v) := by simp [Q, resetWeight] + exact hzero.symm.trans_le (single_le_sum (fun j _ + => hQ v j) (mem_range.mpr (Nat.zero_lt_succ h))) + have hc : (∑ c, if spill c then (1 : ℝ) else 0) = ∑ c, spills (y c) π (q c) g := by + rw [Fintype.sum_sigma] + rfl + refine le_trans ?_ ((charge endpt mass split spill).trans ?_) + · unfold badLoad BadBase split spill mass mark + apply sum_le_sum + intro z _ + split_ifs <;> rfl + rw [hc] + unfold Q at hs hb + linarith + +open scoped Classical in +/-- This quadratic upper bound on the exceptional load can be minimized +using aggregated difference counts. -/ +def score (k : ℕ) := + 3 * (∑ v, ∑ j ∈ range (h + 1), resetWeight j * estimate (l v) π k (base v) j) + + 4 * ∑ c, g ^ 2 * variance (y c) π (q c) + +open scoped Classical in +theorem bad_le_score + (drop : ∀ v u, u ∈ E v → base u ≤ base v + 8 * d v u) + (budget : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) + (hl : ∀ v x, 0 ≤ l v x ∧ l v x ≤ 1 / (2 : ℝ) ^ k) + (hb : ∀ v, ∑ x, l v x ≤ (2 : ℝ) ^ (base v)) (hg : 0 < g) : + badLoad E d base q endpt l y g π ≤ score base q l y g π k := by + refine (charge_splits E d base q endpt l y g π drop budget).trans ?_ + unfold score + apply add_le_add + · refine mul_le_mul_of_nonneg_left (sum_le_sum fun v _ => sum_le_sum fun j _ => ?_) (by norm_num) + exact mul_le_mul_of_nonneg_left (excess_le_estimate (l v) π (hl v) (hb v) j) + (by unfold resetWeight; positivity) + · exact mul_le_mul_of_nonneg_left (sum_le_sum fun c _ => spills_variance _ _ _ hg) (by norm_num) + +open scoped Classical in +theorem exists_score + (hl : ∀ v x, 0 ≤ l v x ∧ l v x ≤ 1 / (2 : ℝ) ^ k) + (hy : ∀ c x, 0 ≤ y c x ∧ y c x ≤ 1 / (2 : ℝ) ^ k) + (hb : ∀ v, ∑ x, l v x ≤ (2 : ℝ) ^ (base v)) + (hq : ∀ c, q c ≤ h) : + ∃ i : Fin (2 ^ h), + score base q l y g (menu h i).toEquiv k ≤ + 144 * resetWeight k / (2 : ℝ) ^ k * (∑ v, ∑ x, l v x) + + 4 * g ^ 2 / (2 : ℝ) ^ k * (∑ c, ∑ x, y c x) := by + obtain ⟨M, _, _, idx, hp⟩ := menu_samples h + let p (m : M) := (menu h (idx m)).toEquiv + let Q m v := ∑ j ∈ range (h + 1), resetWeight j * estimate (l v) (p m) k (base v) j + let S m c := g ^ 2 * variance (y c) (p m) (q c) + let L := 48 * resetWeight k / (2 : ℝ) ^ k * (∑ v, ∑ x, l v x) + let Y := g ^ 2 / (2 : ℝ) ^ k * (∑ c, ∑ x, y c x) + have hQ : (∑ m, ∑ v, Q m v) ≤ Fintype.card M * L := by + unfold L + rw [sum_comm, ← mul_assoc, mul_sum] + exact sum_le_sum fun v _ => weighted_estimate (l v) hp (hl v) (hb v) (h + 1) + have hS : (∑ m, ∑ c, S m c) ≤ Fintype.card M * Y := by + unfold Y + rw [sum_comm, ← mul_assoc, mul_sum] + exact sum_le_sum fun c _ => spill_estimate (y c) _ hp (hq c) (hy c) g + have havg : (∑ m, score base q l y g (p m) k) ≤ ∑ _m : M, (3 * L + 4 * Y) := calc + _ = ∑ m, (3 * (∑ v, Q m v) + 4 * (∑ c, S m c)) := rfl + _ ≤ _ := by + simp only [sum_add_distrib, ← mul_sum, sum_const, card_univ, nsmul_eq_mul] + linarith + obtain ⟨m, _, hm⟩ := exists_le_of_sum_le univ_nonempty havg + refine ⟨idx m, ?_⟩ + exact hm.trans_eq (by unfold L Y; ring) + +open scoped Classical in +/-- A single linear mixer bounds the total load of all bad bases. +The estimate is independent of the number of tether neighbors. -/ +theorem bad_bases + (drop : ∀ v u, u ∈ E v → base u ≤ base v + 8 * d v u) + (budget : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) + (hl : ∀ v x, 0 ≤ l v x ∧ l v x ≤ 1 / (2 : ℝ) ^ k) + (hy : ∀ c x, 0 ≤ y c x ∧ y c x ≤ 1 / (2 : ℝ) ^ k) + (hb : ∀ v, ∑ x, l v x ≤ (2 : ℝ) ^ (base v)) + (hq : ∀ c, q c ≤ h) (hg : 0 < g) : + ∃ f : Cell h ≃ₗ[ZMod 2] Cell h, + badLoad E d base q endpt l y g f.toEquiv ≤ + 144 * resetWeight k / (2 : ℝ) ^ k * (∑ v, ∑ x, l v x) + + 4 * g ^ 2 / (2 : ℝ) ^ k * (∑ c, ∑ x, y c x) := by + obtain ⟨f, hf⟩ := exists_score base q l y g hl hy hb hq + exact ⟨menu h f, (bad_le_score E d base q endpt l y g (menu h f).toEquiv drop budget hl hb + hg).trans hf⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Balanced dyadic partitions + +The vertices share a single linear permutation of the block indices. +Loads are normalized by the capacity of one part. The minimum length is +`A = 2 ^ k` and the edge delay is `2 * d`. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V : Type} [Fintype V] {h k : ℕ} + +open scoped Classical in +/-- The count is bounded across all vertices. Each label has exactly the +indicated prefix as its fiber, with bounded load and length at least `2 ^ k`. +The depth comparison applies in both directions on an undirected edge. -/ +theorem balanced_partition (E : V → Finset V) (d : V → V → ℕ) + (hd : ∀ v u, u ∈ E v → 0 < d v u) + (hs : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) + (hk : 1 ≤ k) (hkh : k ≤ h) (l : V → Cell h → ℝ) + (hl : ∀ v x, 0 ≤ l v x ∧ l v x ≤ 1 / (2 : ℝ) ^ k) + (pick : Fin (2 ^ h)) (opt : best E d l pick) : + let π := menu h pick + let parts := fun v => leaves (marks E d l pick v) h + let label := fun v x => leafAt (marks E d l pick v) (π x) + (∑ v, ((parts v).card : ℝ)) ≤ Fintype.card V + 16 * (∑ v, ∑ x, l v x) ∧ + (∀ v x, label v x ∈ parts v) ∧ + (∀ v c, c ∈ parts v → + c.1 ≤ h - k ∧ (∃ hi : c.1 ≤ h, ∀ x, label v x = c ↔ ancestor hi (π x) = c.2) ∧ + 2 ^ k ≤ (univ.filter fun x => label v x = c).card ∧ + (∑ x, if label v x = c then l v x else 0) ≤ 1) ∧ + (∀ v u, u ∈ E v → ∀ x, (label u x).1 ≤ (label v x).1 + 2 * d v u) := by + obtain ⟨P, _, _, sample, hcol⟩ := menu_samples h + let f (p : P) := (menu h (sample p)).toEquiv + let M (p : P) (v : V) := heavy (l v) (f p) + have depth (π : Equiv.Perm (Cell h)) v i z (hz : heavy (l v) π i z) : i < h - k := + heavy.depth hkh (fun x => (hl v x).2) hz + have half (v : V) (x : Cell h) : 0 ≤ l v x ∧ l v x ≤ 1 / 2 := by + refine ⟨(hl v x).1, (hl v x).2.trans (one_div_le_one_div_of_le (by norm_num) ?_)⟩ + simpa using pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) hk + have hb := spread_bound E d M (fun v => ∑ x, l v x) h + (fun v => sum_nonneg fun x _ => (hl v x).1) hd hs + (fun p v i z hz => (depth (f p) v i z hz).trans_le (Nat.sub_le _ _)) + (fun v i => heavy_bound (l v) (half v) f hcol i) + have havg : (∑ p, ∑ v, ∑ i ∈ range h, ∑ z : Cell i, + if Spread E d (M p) v i z then (1 : ℝ) else 0) ≤ ∑ _p : P, 16 * (∑ v, ∑ x, l v x) := by + simpa only [sum_const, card_univ, nsmul_eq_mul, mul_assoc] using hb + obtain ⟨p, _, hp⟩ := exists_le_of_sum_le univ_nonempty havg + let π := menu h pick + let S := marks E d l pick + have hopt : (∑ v, ∑ i ∈ range h, ∑ z, if S v i z then (1 : ℝ) else 0) ≤ + 16 * ∑ v, ∑ x, l v x := by + have hu := Nat.cast_le (α := ℝ) |>.mpr (opt (sample p)) + simp only [splits, Nat.cast_sum, ← sum_boole] at hu + exact hu.trans hp + have stop (v : V) (z : Cell h) : ¬S v h z := + fun hz => (Nat.sub_le h k).not_gt (hz.depth (depth π.toEquiv)) + have closed (v : V) (i : ℕ) (_hi : i ≤ h) (c : Cell i) (hm : S v i c) : Reached (S v) i c := by + intro j hj + exact hm.up (fun u _ _ hu _ hi => heavy.ancestor (fun x => (hl u x).1) hu hi) j hj.le + change (∑ v, ((leaves (S v) h).card : ℝ)) ≤ _ ∧ _ + refine ⟨?_, ?_, ?_, ?_⟩ + · have count (v : V) : ((leaves (S v) h).card : ℝ) = + 1 + ∑ i ∈ range h, ∑ z : Cell i, if S v i z then (1 : ℝ) else 0 := by + rw [card_leaves _ (closed v) (stop v), Nat.cast_add, Nat.cast_one, Nat.cast_sum] + simp only [sum_boole] + simp only [count, sum_add_distrib, sum_const, card_univ, nsmul_eq_mul, mul_one] + exact add_le_add_right hopt _ + · exact fun v x => leafAt_mem _ _ (stop v _) + · rintro v ⟨i, c⟩ hc + obtain ⟨hi, reached, unmarked⟩ := (mem_leaves (S v) _).mp hc + have small : i ≤ h - k := by + by_contra! bad + exact lt_irrefl _ ((reached _ bad).depth (depth π.toEquiv)) + have fiber (x : Cell h) : leafAt (S v) (π x) = ⟨i, c⟩ ↔ ancestor hi (π x) = c := + leafAt_eq_iff _ _ hi ⟨reached, unmarked⟩ + refine ⟨small, ⟨hi, ?_⟩, ?_, ?_⟩ + · exact fiber + · change 2 ^ k ≤ (univ.filter fun x => leafAt (S v) (π.toEquiv x) = ⟨i, c⟩).card + rw [card_leafAt _ _ hc] + exact Nat.pow_le_pow_right (by decide) (by omega : k ≤ h - i) + · apply le_of_not_gt + intro bad + change 1 < ∑ x, if leafAt (S v) (π x) = ⟨i, c⟩ then l v x else 0 at bad + apply unmarked + apply Spread.start + exact ⟨hi, by simpa only [fiber, π, LinearEquiv.coe_toEquiv] using bad⟩ + · intro v u hu x + exact leafDepth_le_add (S u) (S v) (2 * d v u) + (fun _ _ c hc => Spread.move hu c hc) (π x) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Beat.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Beat.lean new file mode 100644 index 0000000000..703288d8c5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Beat.lean @@ -0,0 +1,431 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.FieldLift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.TetherHost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Hard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.WideTag +public import Mathlib.Data.Nat.Log + +/-! # Quantitative reduction bounds for one subround and one reset -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open HostNet + +variable {F : Type} [Field F] + +/-- The quantity computed by `1 - 1 / (8 * (P.b : ℝ))`. -/ +def Gadget.ratio (P : Gadget F) : ℝ := 1 - 1 / (8 * (P.b : ℝ)) + +theorem Gadget.ratio_bounds (P : Gadget F) : 0 ≤ P.ratio ∧ P.ratio < 1 := by + have hp : (1 : ℝ) ≤ P.b := by exact_mod_cast P.pos + have hb : 1 ≤ 8 * (P.b : ℝ) := by linarith + exact ⟨sub_nonneg.mpr ((div_le_one (by linarith)).mpr hb), sub_lt_self _ (by positivity)⟩ + +/-- The fixed value `2700` used in this construction. -/ +def degreePower : ℕ := 2700 + +namespace Reduction + +/-- Each elementary step adds exactly the old bit incidences. -/ +private theorem mass_step {m n K x : ℕ} {z : ℝ} (hn : n = m + 2 * x) + (hK : 1 ≤ K) (hz : 0 ≤ z) : (n : ℝ) ≤ m + 2 * (K : ℝ) * (x + z) := by + rw [hn] + push_cast + have h : (1 : ℝ) ≤ K := by exact_mod_cast hK + exact add_le_add le_rfl + (mul_le_mul (by linarith) (le_add_of_nonneg_right hz) (by positivity) (by positivity)) + +private theorem scale {h k K r a H : ℕ} {B σ : ℝ} (hb : 0 ≤ B) (hk : 2 ^ k ≤ K) + (ha : a + 1 * r ≤ h) (hr : K ≤ 2 ^ r) (slack : (K : ℝ) * B * (H * 2 ^ h : ℕ) + ≤ σ * (2 : ℝ) ^ r) : + a + k ≤ h ∧ (2 : ℝ) ^ k * B * (H * 2 ^ a : ℕ) ≤ σ := by + have hkr : k ≤ r := (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp (hk.trans hr) + refine ⟨by omega, le_of_mul_le_mul_right ?_ (by positivity : (0 : ℝ) < 2 ^ r)⟩ + apply le_trans _ slack + push_cast + rw [mul_assoc, mul_assoc (H : ℝ), ← pow_add] + gcongr + · exact_mod_cast hk + · norm_num + · omega + +private theorem cubic {D : ℕ} (h : 3 ≤ D) : 4 * D ≤ D ^ 3 := by + have hs : 4 ≤ D ^ 2 := by nlinarith + exact (Nat.mul_le_mul_right D hs).trans_eq (pow_succ _ _).symm + +theorem power_growth {D : ℕ} (hd : 3 ≤ D) (n z : ℕ) (hz : z = 3 * n) : (4 * D) ^ n ≤ D ^ z := by + subst z + rw [pow_mul] + exact Nat.pow_le_pow_left (cubic hd) _ + +theorem subround (P₀ : Gadget F) (Δ : ℕ) (hΔ : 3 ≤ Δ) : + ∃ K, ∀ (L : Type) [Field L] [Algebra F L], + Reduction L Δ (Δ ^ degreePower) P₀.b 1 degreePower K P₀.ratio 1 := by + let k := 256 * (coreBins Δ + 1) + let T₀ := P₀.copies * P₀.shapes.card + 1 + let B₀ := 9 * (4 * Δ) ^ 300 * 2 ^ k + let K := 2 * (Δ + 1) + 2 ^ k + T₀ + B₀ + have hpos : 1 ≤ k := by unfold k; omega + have hk : 2 ^ k ≤ K := by unfold K; omega + have : 1 ≤ (2 : ℕ) ^ k := Nat.one_le_pow _ _ (by decide) + have htwo : 2 ≤ K := by unfold K; omega + have grow (D : ℕ) (hd : 3 ≤ D) : (4 * D) ^ 900 ≤ D ^ degreePower + := power_growth hd 900 degreePower rfl + refine ⟨K, fun L₀ _ _ => ?_⟩ + let P := P₀.extend L₀ + change Reduction L₀ Δ (Δ ^ degreePower) P.b 1 degreePower K P.ratio 1 + refine ⟨P.pos, by omega, fun D h => Nat.pow_le_pow_left h _, P.ratio_bounds.1, by norm_num, ?_⟩ + intro T _ x y L h u G z r a D M B σ hz hu huB hD hb hσ ha hr slack budget + subst u + have hzu : z ≤ P.b * z := Nat.le_mul_of_pos_left _ P.pos + have hB : 0 < B := (Nat.cast_pos.mpr (hz.trans_le hzu)).trans_le huB + obtain ⟨ha', hs⟩ := scale hB.le hk ha hr slack + obtain ⟨I, _, q, hc, he, ho⟩ := G.subround P hz a k Δ D (by omega) hD hpos ha' B σ hB hb + Nat.lt_two_pow_self.le hs + refine ⟨I, inferInstance, q, hc.trans ?_, he, fun i => ?_⟩ + · have hE : Fintype.card G.E ≤ M := by + have hx : (G.X : ℝ) ≤ (M : ℝ) * z := (le_add_of_nonneg_right (add_nonneg L.total_nonneg + hσ)).trans budget + have ht : G.X ≤ M * z := by exact_mod_cast hx + exact Nat.le_of_mul_le_mul_right ((Nat.mul_le_mul_left _ hzu).trans ht) hz + have ht : T₀ ≤ 2 ^ K := (show T₀ ≤ K by unfold K; omega).trans Nat.lt_two_pow_self.le + rw [pow_mul] + exact (Nat.pow_le_pow_left ht _).trans (Nat.pow_le_pow_right (by positivity) hE) + · obtain ⟨hs, hb, hw, hp, hmass, tk⟩ := ho i + refine ⟨hp, (G.seats_le (q i) (by omega) hs).trans (Nat.mul_le_mul_right _ htwo), + hb.mono (grow _ hΔ) (grow _ (hΔ.trans hD)) ?_, by simpa only [Gadget.ratio, one_mul], + mass_step hmass (by omega) (add_nonneg L.total_nonneg hσ), tk.mono (by unfold K; omega)⟩ + have ht : (B₀ : ℝ) ≤ K := Nat.cast_le.mpr (by unfold K; omega) + simpa only [B₀, Nat.cast_mul, Nat.cast_ofNat, Nat.cast_pow, mul_assoc] using + mul_le_mul_of_nonneg_right ht hB.le + +theorem degree_reset {D Y : ℕ} (hD : 3 ≤ D) : + 3 + terminalWidth D Y ≤ D ^ (900 + Y + 1) := by + have a : (4 * D) ^ 300 ≤ D ^ 900 := power_growth hD 300 900 rfl + have b : Y ≤ D ^ Y := Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left (by omega) _) + have c : 3 ≤ D ^ (900 + Y) := hD.trans (Nat.le_self_pow (by omega) _) + have ht : terminalWidth D Y ≤ D ^ (900 + Y) := by + rw [pow_add] + exact Nat.mul_le_mul a b + rw [pow_succ] + exact (Nat.add_le_add c ht).trans (by rw [← mul_two]; exact Nat.mul_le_mul_left _ (by omega)) + +theorem reset {Y w Δ : ℕ} (R : Rotor F Y w) (hY : 0 < Y) (hw : 0 < w) + (hΔ : 3 ≤ Δ) (enough : 4 * coreBins Δ ≤ Y) + (c : ℝ) (hc : 0 ≤ c) (hR : (Fintype.card R.E : ℝ) ≤ c * Y * w) : + ∃ K, ∀ (L : Type) [Field L] [Algebra F L], + Reduction L Δ 3 1 1 (900 + Y + 1) K (2 * resetWidth c w) (2 * resetWidth c w) := by + obtain ⟨k, step⟩ := HostNet.reset hY hw (by omega) enough c hc + let K := resetPositions R Δ + 89 * 2 ^ k + 1 + have hk : 2 ^ k ≤ K := by unfold K; omega + have hW : 0 ≤ resetWidth c w := by unfold resetWidth; positivity + refine ⟨K, fun L₀ _ _ => ?_⟩ + refine ⟨by decide, by unfold K; omega, + fun D hd => (hΔ.trans hd).trans (Nat.le_self_pow (by omega) _), + by positivity, by positivity, ?_⟩ + intro T _ x y L h u G z r a D M B σ hz hu huB hD hb hσ ha hr slack _ + rw [one_mul] at hu + subst z + have hB := (Nat.cast_nonneg u).trans huB + obtain ⟨ha', hs⟩ := scale hB hk ha hr slack + obtain ⟨Q, he, hq, hd, hw, hp, hmass, tk⟩ := step L₀ (R.extend L₀) hR T x y L h a u D B σ G ha' + hD hb hz huB hs + change Fintype.card Q.V ≤ resetPositions R Δ * 2 ^ (h - a) * Fintype.card G.V at hq + change G.Tracks Q (resetPositions R Δ + 1) at tk + refine Expands.single Q he hp ⟨(G.seats_le Q (by omega) hq).trans ?_, + hd.mono le_rfl (degree_reset (hΔ.trans hD)) ?_, hw.trans ?_, + mass_step hmass (by unfold K; omega) (add_nonneg L.total_nonneg hσ), + tk.mono (by unfold K; omega)⟩ + · exact Nat.mul_le_mul_right _ (by unfold K; omega) + · apply mul_le_mul_of_nonneg_right _ hB + exact_mod_cast (show 89 * 2 ^ k ≤ K by unfold K; omega) + · linarith [mul_nonneg hW hσ] + +end Reduction +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +section +/- +# Choosing the number of subrounds and the rotor + +Choose a sufficiently small tagged-permutation exponent, then let the +number of subrounds grow in fixed strides. The address length grows +exponentially in the number of strides. Its small power grows as +`2 ^ i`, which the contraction absorbs geometrically. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Filter + +private theorem enough_rows (D k t : ℕ) (ht : 0 < t) (Δ : ℕ) (hΔ : Δ ≤ D ^ (k ^ t)) : + 4 * Δ * 2 ^ (64 * Nat.clog 2 (2 * Δ)) ≤ 2 ^ (2 ^ (131 * (D + 1) * (k + 1) * t)) := by + let j := (D + 1) * (k + 1) ^ t + have hj : 0 < j := by unfold j; positivity + have hd : Δ ≤ 2 ^ j := calc + _ ≤ D ^ (k ^ t) := hΔ + _ ≤ (2 ^ D) ^ (k ^ t) := Nat.pow_le_pow_left Nat.lt_two_pow_self.le _ + _ ≤ 2 ^ j := by + rw [← pow_mul] + exact Nat.pow_le_pow_right (by decide) + (Nat.mul_le_mul (Nat.le_succ D) (Nat.pow_le_pow_left (Nat.le_succ k) _)) + have hl : Nat.clog 2 (2 * Δ) ≤ j + 1 := by + apply Nat.clog_le_of_le_pow + rw [pow_succ] + omega + have hy : 131 * j ≤ 2 ^ (131 * (D + 1) * (k + 1) * t) := calc + _ ≤ (131 * (D + 1) * (k + 1)) ^ t := by + rw [mul_pow] + simpa only [j, mul_assoc] using + Nat.mul_le_mul_right ((k + 1) ^ t) (Nat.le_self_pow ht.ne' (131 * (D + 1))) + _ ≤ _ := by rw [pow_mul]; exact Nat.pow_le_pow_left Nat.lt_two_pow_self.le _ + calc + _ ≤ 2 ^ 2 * 2 ^ j * 2 ^ (64 * Nat.clog 2 (2 * Δ)) := + Nat.mul_le_mul_right _ (Nat.mul_le_mul_left 4 hd) + _ ≤ _ := by + rw [← pow_add, ← pow_add] + exact Nat.pow_le_pow_right (by decide) (by omega) + +/-- Either source of inexpensive rotors supplies arbitrarily large +address lengths with a polynomially bounded payload. -/ +private theorem frequent_tag {F : Type} [Field F] (tag : Radix.WideTag F ∨ ¬Tagged.Hard F) + {ζ : ℝ} (hζ : 0 < ζ) : + ∃ (A : ℕ) (C : ℝ), ∀ n : ℕ, ∃ y m : ℕ, 0 < y ∧ n ≤ y ∧ Radix.Tag F y (y ^ A) m ∧ + (m : ℝ) ≤ C * (2 : ℝ) ^ y * (y ^ A : ℕ) * (y : ℝ) ^ ζ := by + rcases tag with h | h + · obtain ⟨A, _, C, h⟩ := h ζ hζ + refine ⟨A, C, fun n => ?_⟩ + obtain ⟨m, hm, hc⟩ := h (n + 1) _ (by omega) le_rfl + exact ⟨n + 1, m, by omega, by omega, hm, hc⟩ + refine ⟨1, 1, fun n => ?_⟩ + simp only [pow_one, one_mul] + by_contra! bad + apply h + refine ⟨ζ, hζ, ?_⟩ + filter_upwards [eventually_gt_atTop n] with y hy m hm + exact (bad y m (by omega) hy.le hm).le + +/-- Choose the contraction count from the available address length. +Even an arbitrarily sparse sequence of good lengths suffices. -/ +theorem choose_rotor {F : Type} [Field F] (tag : Radix.WideTag F ∨ ¬Tagged.Hard F) (D k : ℕ) + (ρ B : ℝ) (hρ : 0 ≤ ρ) (hρ' : ρ < 1) (hB : 0 ≤ B) : + ∃ (t y w : ℕ) (R : Rotor F (2 ^ y) w) (c : ℝ), + 0 < t ∧ 0 < w ∧ 1 ≤ c ∧ + (Fintype.card R.V : ℝ) + Fintype.card R.E ≤ c * (2 : ℝ) ^ y * w ∧ + (∀ Δ ≤ D ^ (k ^ t), 4 * Δ * 2 ^ (64 * Nat.clog 2 (2 * Δ)) ≤ 2 ^ y) ∧ + B * (1 + c + Nat.clog 2 w) * ρ ^ t ≤ 1 / 2 := by + let b := 131 * (D + 1) * (k + 1) + have hb : 0 < b := by unfold b; positivity + obtain ⟨p, hp, hsmall⟩ := ((eventually_gt_atTop 0).and + ((tendsto_pow_atTop_nhds_zero_of_lt_one hρ hρ').eventually_lt_const + (by norm_num : (0 : ℝ) < 1 / 4))).exists + let ζ : ℝ := 1 / ((b : ℝ) * p) + have hζ : 0 < ζ := by unfold ζ; positivity + obtain ⟨A, C, htag⟩ := frequent_tag tag hζ + let K := B * (2 + 6 * |C| + b * p * A) + have tend := tendsto_pow_atTop_nhds_zero_of_lt_one (show 0 ≤ 2 * ρ ^ p by positivity) + (show 2 * ρ ^ p < 1 by linarith) + have lim := tend.const_mul K + rw [mul_zero] at lim + obtain ⟨i₀, hi₀⟩ := eventually_atTop.mp ((eventually_gt_atTop 0).and + (lim.eventually_lt_const (by norm_num : (0 : ℝ) < 1 / 2))) + let u := 2 ^ (b * p) + have hu : 1 < u := one_lt_pow₀ (by decide) (Nat.mul_pos hb hp).ne' + obtain ⟨y, m, hy, hlo, hnet, hs⟩ := htag (u ^ i₀) + let i := Nat.log u y + obtain ⟨hi, hdec⟩ := hi₀ i (Nat.le_log_of_pow_le hu hlo) + let t := p * i + have ht : 0 < t := Nat.mul_pos hp hi + have low : 2 ^ (b * t) ≤ y := by + rw [show b * t = (b * p) * i from (mul_assoc _ _ _).symm, pow_mul] + exact Nat.pow_log_le_self u hy.ne' + have up : y ≤ 2 ^ (b * p * (i + 1)) := by + rw [pow_mul] + exact (Nat.lt_pow_of_log_lt hu (Nat.lt_succ_self i)).le + have scale : (y : ℝ) ^ ζ ≤ 2 * (2 : ℝ) ^ i := calc + _ ≤ ((2 : ℝ) ^ (b * p * (i + 1))) ^ ζ := + Real.rpow_le_rpow (by positivity) (by exact_mod_cast up) hζ.le + _ = (2 : ℝ) ^ (i + 1) := by + rw [← Real.rpow_natCast_mul (by norm_num), ← Real.rpow_natCast 2 (i + 1)] + congr 1 + simp only [ζ, Nat.cast_mul] + field_simp + _ = _ := pow_succ' _ _ + have clog : Nat.clog 2 (y ^ A) ≤ b * p * A * 2 ^ i := by + apply Nat.clog_le_of_le_pow + refine (Nat.pow_le_pow_left up A).trans ?_ + rw [← pow_mul, mul_right_comm (b * p)] + exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_left _ Nat.lt_two_pow_self) + obtain ⟨R, hv, he⟩ := Rotor.of_tag hnet + let c := 1 + 6 * |C| * (2 : ℝ) ^ i + refine ⟨t, y, y ^ A, R, c, ht, by positivity, le_add_of_nonneg_right (by positivity), ?_, ?_, ?_⟩ + · rw [hv] + have hem : (Fintype.card R.E : ℝ) ≤ 2 * m := by + exact_mod_cast (show Fintype.card R.E ≤ 2 * m by omega) + calc + _ ≤ 3 * (m : ℝ) := by linarith + _ ≤ 3 * (|C| * (2 : ℝ) ^ y * (y ^ A : ℕ) * (2 * (2 : ℝ) ^ i)) := by + apply mul_le_mul_of_nonneg_left (hs.trans ?_) (by norm_num) + gcongr + exact le_abs_self _ + _ ≤ _ := by unfold c; nlinarith [show 0 ≤ (2 : ℝ) ^ y * (y ^ A : ℕ) by positivity] + · intro Δ hΔ + exact (enough_rows D k t ht Δ hΔ).trans (Nat.pow_le_pow_right (by decide) low) + · have ha : (Nat.clog 2 (y ^ A) : ℝ) ≤ (b : ℝ) * p * A * (2 : ℝ) ^ i := by exact_mod_cast clog + have hfact : 1 + c + Nat.clog 2 (y ^ A) ≤ (2 + 6 * |C| + (b : ℝ) * p * A) * (2 : ℝ) ^ i := by + unfold c + linarith [one_le_pow₀ (by norm_num : (1 : ℝ) ≤ 2) (n := i)] + calc + _ ≤ B * ((2 + 6 * |C| + (b : ℝ) * p * A) * (2 : ℝ) ^ i) * ρ ^ t := + mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hfact hB) (by positivity) + _ = K * (2 * ρ ^ p) ^ i := by simp only [t, K, mul_pow, pow_mul, mul_assoc] + _ ≤ _ := hdec.le + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Reduction of core width + +Use a fixed number of contracting subrounds followed by a degree +reset. Choose the rotor large enough for the degree at the last +subround and cheap enough for the contraction to absorb its cost. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open HostNet + +variable {F : Type} [Field F] + +namespace Reduction + +theorem relax {Δ Δ' b n e K K' : ℕ} {ρ ρ' C C' : ℝ} + (p : Reduction F Δ Δ' b n e K ρ C) (hK : K ≤ K') (hρ : ρ ≤ ρ') (hc : C ≤ C') : + Reduction F Δ Δ' b n e K' ρ' C' := by + refine ⟨p.unit, p.overhead.trans_le hK, p.degree, p.factor.trans hρ, p.loss.trans hc, ?_⟩ + intro T _ x y L h u G z r a D M B σ hz hu hub hd hb hs ha hr hsl hbud + have hB := (Nat.cast_nonneg u).trans hub + have hKB := mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hK) hB + have he := p.run G z r a D M B σ hz hu hub hd hb hs ha (hK.trans hr) + ((mul_le_mul_of_nonneg_right hKB (Nat.cast_nonneg _)).trans hsl) hbud + refine he.mono (Nat.mul_le_mul_right _ hK) ?_ + rintro Q ⟨hs', hb', hw, hm, t⟩ + exact ⟨hs'.trans (Nat.mul_le_mul_right _ hK), hb'.mono le_rfl le_rfl hKB, + hw.trans (add_le_add (mul_le_mul_of_nonneg_right hρ (Nat.cast_nonneg _)) + (mul_le_mul_of_nonneg_right hc (add_nonneg L.total_nonneg hs))), + hm.trans (by have := L.total_nonneg; gcongr), t.mono hK⟩ + +theorem subrounds (P : Gadget F) (Δ : ℕ) (hΔ : 3 ≤ Δ) (t : ℕ) (ht : 0 < t) : + ∃ K, ∀ (L : Type) [Field L] [Algebra F L], + Reduction L Δ (Δ ^ (degreePower ^ t)) (P.b ^ t) t (degreePower ^ t) K (P.ratio ^ t) t := by + have : 0 < degreePower := by decide + induction t, ht using Nat.le_induction with + | base => simpa only [pow_one, Nat.cast_one] using subround P Δ hΔ + | succ t _ ih => + obtain ⟨K, p⟩ := ih + obtain ⟨K', q⟩ := subround P (Δ ^ (degreePower ^ t)) (hΔ.trans (Nat.le_self_pow (by positivity) + _)) + refine ⟨fee K (P.ratio ^ t) t * K', fun L _ _ => ?_⟩ + have h := (p L).comp (q L) + rw [← pow_mul Δ (degreePower ^ t) degreePower, ← pow_succ degreePower, ← pow_succ P.b, + ← pow_succ' P.ratio] at h + refine h.relax le_rfl le_rfl ?_ + rw [Nat.cast_add, Nat.cast_one] + exact add_le_add_left (mul_le_of_le_one_left (Nat.cast_nonneg _) P.ratio_bounds.2.le) _ + +end Reduction + +/-- Core width is halved up to the frozen charge and slack. The overheads +are uniform across field extensions and depend only on the incoming +core degree and the ground field. -/ +theorem beat (tag : Radix.WideTag F ∨ ¬Tagged.Hard F) (Δ : ℕ) (hΔ : 3 ≤ Δ) : + ∃ (b n e K : ℕ) (C : ℝ), 0 < n ∧ 0 < e ∧ + ∀ (L : Type) [Field L] [Algebra F L], Reduction L Δ 3 b n e K (1 / 2) C := by + obtain ⟨P⟩ := gadget_exists F + obtain ⟨t, y, w, R, c, ht, hw, hc, hsize, en, hdecay⟩ := + choose_rotor tag Δ degreePower P.ratio 250 P.ratio_bounds.1 P.ratio_bounds.2 (by norm_num) + obtain ⟨K, p⟩ := Reduction.subrounds P Δ hΔ t ht + have : 0 < degreePower := by decide + let D := Δ ^ (degreePower ^ t) + have hd : 3 ≤ D := hΔ.trans (Nat.le_self_pow (by positivity) _) + have enough : 4 * coreBins D ≤ 2 ^ y := by + simpa only [coreBins, mul_assoc] using en D le_rfl + have hR : (Fintype.card R.E : ℝ) ≤ c * (2 ^ y : ℕ) * w := by + push_cast + exact (le_add_of_nonneg_left (Nat.cast_nonneg _)).trans hsize + obtain ⟨K', q⟩ := Reduction.reset R (by positivity) hw hd enough c (by linarith) hR + have bound : 2 * resetWidth c w ≤ 250 * (1 + c + Nat.clog 2 w) := by + unfold resetWidth + linarith [Nat.cast_nonneg (α := ℝ) (Nat.clog 2 w)] + have decrease := (mul_le_mul_of_nonneg_right bound (pow_nonneg P.ratio_bounds.1 t)).trans hdecay + exact ⟨_, _, _, _, _, by positivity, by positivity, + fun L _ _ => ((p L).comp (q L)).relax le_rfl decrease le_rfl⟩ + + +/-- At the first halving the accumulated loss is the one-step charge. -/ +theorem half_loss_one (charge : ℝ) : 2 * charge * (1 - 1 / 2) = charge := by ring + +/-- Prepending one halving adds its charge weighted by the later halvings. -/ +theorem half_loss_succ (charge : ℝ) (t : ℕ) : + (1 / 2 : ℝ) ^ t * charge + 2 * charge * (1 - (1 / 2) ^ t) = + 2 * charge * (1 - (1 / 2) ^ (t + 1)) := by + rw [pow_succ] + ring + +theorem half_loss_le {charge : ℝ} (h : 0 ≤ charge) (t : ℕ) : + 2 * charge * (1 - (1 / 2) ^ t) ≤ 2 * charge := + mul_le_of_le_one_right (mul_nonneg (by norm_num) h) (sub_le_self _ (by positivity)) + +/-- Repeat a fixed beat while keeping both rates and the subdivision explicit. -/ +theorem Reduction.iterate {Δ b n e K : ℕ} {C : ℝ} (p : Reduction F Δ 3 b n e K (1 / 2) C) + (hΔ : 3 ≤ Δ) (he : 0 < e) (t : ℕ) (ht : 0 < t) : + Reduction F Δ 3 (b ^ t) (n * t) (e ^ t) ((fee K (1 / 2) C) ^ t) ((1 / 2) ^ t) (2 * C) := by + let H := Reduction.fee K (1 / 2) C + have w : Reduction F Δ Δ b n e K (1 / 2) C := by + refine ⟨p.unit, p.overhead, fun D hd => hd.trans (Nat.le_self_pow he.ne' D), + p.factor, p.loss, ?_⟩ + intro T _ x y L h u G z r a D M B σ hz hu hub hd hb hs ha hr hsl hbud + exact (p.run G z r a D M B σ hz hu hub hd hb hs ha hr hsl hbud).mono le_rfl + (fun q hq => ⟨hq.1, hq.2.1.mono hΔ le_rfl le_rfl, hq.2.2⟩) + have hk : K ≤ H := by unfold H Reduction.fee; omega + have hit (t : ℕ) (ht : 0 < t) : + Reduction F Δ 3 (b ^ t) (n * t) (e ^ t) (H ^ t) ((1 / 2) ^ t) (2 * C * (1 - (1 / 2) ^ t)) + := by + induction t, ht using Nat.le_induction with + | base => + simp only [Nat.succ_eq_add_one, Nat.zero_add, pow_one, mul_one, half_loss_one] + exact p.relax hk le_rfl le_rfl + | succ t _ ih => + have h := w.comp ih + rw [show Reduction.fee K (1 / 2) C = H from rfl, + ← pow_succ' b, ← pow_succ' e, ← pow_succ' H, ← pow_succ (1 / 2 : ℝ), + show n + n * t = n * (t + 1) by rw [Nat.mul_succ, add_comm], + half_loss_succ] at h + exact h + refine (hit t ht).relax le_rfl le_rfl ?_ + exact half_loss_le p.loss t + +/-- Iterate with a bounded additive loss and only exponential growth +of the subdivision, load and full-degree exponent. -/ +theorem beats (tag : Radix.WideTag F ∨ ¬Tagged.Hard F) (Δ : ℕ) (hΔ : 3 ≤ Δ) : + ∃ (b n e H : ℕ) (C : ℝ), 0 < n ∧ 0 < e ∧ ∀ t : ℕ, 0 < t → + ∀ (L : Type) [Field L] [Algebra F L], Reduction L Δ 3 (b ^ t) (n * t) (e ^ t) (H ^ t) ((1 / + 2) ^ t) C := by + obtain ⟨b, n, e, K, C, hn, he, step⟩ := beat tag Δ hΔ + let H := Reduction.fee K (1 / 2) C + refine ⟨b, n, e, H, 2 * C, hn, he, ?_⟩ + intro t ht L₀ _ _ + exact (step L₀).iterate hΔ he t ht + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Budget.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Budget.lean new file mode 100644 index 0000000000..30eb2c003d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Budget.lean @@ -0,0 +1,294 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.BadBases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.FieldLift + +/-! # Matching whole items in a linear stream of bins -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +variable {A I D : Type} (item : A → I) (bin : A → Option D) + +open scoped Classical in +/-- Keep exactly those items that fit entirely in a single bin. -/ +def plan (i : A) : Option D := + if ∀ j, item j = item i → bin j = bin i then bin i else none + +open scoped Classical in +/-- Charge a split item to a bin whose run ends inside it. Two distinct +items cannot be charged to the same bin. -/ +theorem straddles [Fintype A] [LinearOrder A] [DecidableEq I] [DecidableEq D] + (hitem : ∀ i j k, i ≤ j → j ≤ k → item i = item k → item j = item i) + (hbin : ∀ i j k, i ≤ j → j ≤ k → bin i = bin k → (bin i).isSome → bin j = bin i) + (hprefix : ∀ i j, i ≤ j → item i = item j → (bin j).isSome → (bin i).isSome) + (b : ℕ) (bound : ∀ t, (univ.filter fun i => item i = t).card ≤ b) : + (univ.filter fun i => (bin i).isSome).card ≤ + (univ.filter fun i => (plan item bin i).isSome).card + + b * ((univ.filter fun i => (bin i).isSome).image bin).card := by + let eligible := univ.filter fun i => (bin i).isSome + let matched := univ.filter fun i => (plan item bin i).isSome + let bad := eligible \ matched + have witness (i : A) : ∃ l r : A, i ∈ bad → + l ≤ r ∧ item l = item i ∧ item r = item i ∧ (bin l).isSome ∧ bin r ≠ bin l := by + by_cases hi : i ∈ bad + · have ha := (mem_filter.mp (mem_sdiff.mp hi).1).2 + have hn : ¬ ∀ j, item j = item i → bin j = bin i := by + intro h + apply (mem_sdiff.mp hi).2 + exact mem_filter.mpr ⟨mem_univ _, by simpa only [plan, ite_eq_left h] using ha⟩ + push Not at hn + obtain ⟨j, hj, hne⟩ := hn + rcases le_total i j with h | h + · exact ⟨i, j, fun _ => ⟨h, rfl, hj, ha, hne⟩⟩ + · exact ⟨j, i, fun _ => ⟨h, hj, rfl, hprefix j i h hj ha, hne.symm⟩⟩ + · exact ⟨i, i, fun h => (hi h).elim⟩ + choose l r hr using witness + have same (i j : A) (hi : i ∈ bad) (hj : j ∈ bad) + (he : bin (l i) = bin (l j)) (hle : l i ≤ l j) : item i = item j := by + obtain ⟨hil, hli, hri, hs, hne⟩ := hr i hi + rcases le_total (l j) (r i) with h | h + · have := hitem _ _ _ hle h (hli.trans hri.symm) + exact hli.symm.trans (this.symm.trans (hr j hj).2.1) + · exact (hne (hbin _ _ _ hil h he hs)).elim + have maps : Set.MapsTo (fun i => bin (l i)) bad (eligible.image bin) := by + intro i hi + exact mem_image.mpr ⟨l i, mem_filter.mpr ⟨mem_univ _, (hr i hi).2.2.2.1⟩, rfl⟩ + have hb : bad.card ≤ b * (eligible.image bin).card := by + rw [card_eq_sum_card_fiberwise maps] + calc + _ ≤ ∑ _d ∈ eligible.image bin, b := by + apply sum_le_sum + intro d _ + by_cases hd : (bad.filter fun i => bin (l i) = d).Nonempty + · obtain ⟨j, hj⟩ := hd + obtain ⟨hj, ej⟩ := mem_filter.mp hj + refine le_trans (card_le_card ?_) (bound (item j)) + intro i hi + obtain ⟨hi, ei⟩ := mem_filter.mp hi + refine mem_filter.mpr ⟨mem_univ _, ?_⟩ + rcases le_total (l i) (l j) with h | h + · exact same i j hi hj (ei.trans ej.symm) h + · exact (same j i hj hi (ej.trans ei.symm) h).symm + · simp only [not_nonempty_iff_eq_empty.mp hd, card_empty, Nat.zero_le] + _ = _ := by simp [Nat.mul_comm] + have h := card_sdiff_add_card_inter eligible matched + have h' := card_le_card (inter_subset_right : eligible ∩ matched ⊆ matched) + change eligible.card ≤ matched.card + b * (eligible.image bin).card + unfold bad at hb + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Computing base depths from mean loads + +Each neighbor update loses at least one level of influence. After +`b - a` updates the depths are stable. They are bounded pointwise by +every feasible choice, so the existing geometric count also applies. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +open scoped Classical in +/-- The maximum of the quantities in `a (Nat.clog 2 ⌈x⌉₊)`. -/ +def requested (a : ℕ) (x : ℝ) := max a (Nat.clog 2 ⌈x⌉₊) + +open scoped Classical in +theorem requested_le (a k : ℕ) (x : ℝ) : requested a x ≤ k ↔ a ≤ k ∧ x ≤ (2 : ℝ) ^ k := by + rw [requested, max_le_iff, Nat.clog_le_iff_le_pow (by decide), Nat.ceil_le, Nat.cast_pow, + Nat.cast_ofNat] + +variable {V : Type} (E : V → Finset V) (d : V → V → ℕ) (r : V → ℕ) + +open scoped Classical in +/-- In the case `0`, this construction gives `r`. -/ +def iterateDepth : ℕ → V → ℕ + | 0 => r + | t + 1 => fun v => max (r v) ((E v).sup fun w => iterateDepth t w - 8 * d v w) + +open scoped Classical in +theorem depth_ge (t : ℕ) (v : V) : r v ≤ iterateDepth E d r t v := by + cases t + · exact le_rfl + · exact le_max_left _ _ + +open scoped Classical in +theorem depth_bounded (c : V → ℕ) (hc : ∀ v, r v ≤ c v) + (h : ∀ v w, w ∈ E v → c w ≤ c v + 8 * d v w) (t : ℕ) (v : V) : + iterateDepth E d r t v ≤ c v := by + induction t generalizing v with + | zero => exact hc v + | succ t ih => + refine max_le (hc v) (Finset.sup_le fun w hw => ?_) + exact Nat.sub_le_iff_le_add.mpr ((ih w).trans (h v w hw)) + +open scoped Classical in +private theorem influence (b : ℕ) (hd : ∀ v w, w ∈ E v → 0 < d v w) + (hr : ∀ v, r v ≤ b) (t : ℕ) (v : V) : + iterateDepth E d r (t + 1) v ≤ max (iterateDepth E d r t v) (b - (t + 1)) := by + induction t generalizing v with + | zero => + refine max_le (le_max_left _ _) (Finset.sup_le fun w hw => le_max_of_le_right ?_) + have h := hd _ _ hw + have := hr w + change r w - 8 * d v w ≤ _ + omega + | succ t ih => + refine max_le ((depth_ge E d r _ v).trans (le_max_left _ _)) (Finset.sup_le fun w hw => ?_) + have ha : iterateDepth E d r t w - 8 * d v w ≤ iterateDepth E d r (t + 1) v := + (le_sup (f := fun w => iterateDepth E d r t w - 8 * d v w) hw).trans (le_max_right _ _) + have hm := ih w + have hx := hd _ _ hw + change iterateDepth E d r (t + 1) w - 8 * d v w ≤ _ + omega + +open scoped Classical in +theorem depth_drop (a b : ℕ) (hd : ∀ v w, w ∈ E v → 0 < d v w) + (hr : ∀ v, a ≤ r v ∧ r v ≤ b) (v w : V) (hw : w ∈ E v) : + iterateDepth E d r (b - a) w ≤ iterateDepth E d r (b - a) v + 8 * d v w := by + have hi := influence E d r b hd (fun v => (hr v).2) (b - a) v + have hl := (hr v).1.trans (depth_ge E d r (b - a) v) + have hs : iterateDepth E d r (b - a) w - 8 * d v w ≤ iterateDepth E d r (b - a + 1) v := + (le_sup (f := fun w => iterateDepth E d r (b - a) w - 8 * d v w) hw).trans (le_max_right _ _) + omega + +open scoped Classical in +/-- The quantity computed by `iterateDepth E d (requested a ∘ l) (b - a)`. -/ +def baseDepths (a b : ℕ) (l : V → ℝ) := iterateDepth E d (requested a ∘ l) (b - a) + +open scoped Classical in +theorem baseDepths_spec [Fintype V] + (budget : ∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) + (a b : ℕ) (hab : a ≤ b) (l : V → ℝ) (hl : ∀ v, 0 ≤ l v ∧ l v ≤ (2 : ℝ) ^ b) : + let base := baseDepths E d a b l + (∀ v, a ≤ base v ∧ base v ≤ b ∧ l v ≤ (2 : ℝ) ^ (base v)) ∧ + (∀ v u, u ∈ E v → base u ≤ base v + 8 * d v u) ∧ + (∑ v, (2 : ℝ) ^ (base v)) ≤ 2 * Fintype.card V * (2 : ℝ) ^ a + 4 * (∑ v, l v) := by + intro base + have hd v u (hu : u ∈ E v) : 0 < d v u := by + let cost v := if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0 + have ht : cost v ≤ 1 / 2 := (single_le_sum (fun x _ => show 0 + ≤ cost x by unfold cost; positivity) + (mem_univ v)).trans (budget u) + by_contra! bad + norm_num [cost, hu, show d v u = 0 by omega] at ht + obtain ⟨c, hc, he, hs⟩ := choose_bases E d budget a b hab l hl + have demand v : requested a (l v) ≤ c v := (requested_le _ _ _).mpr ⟨(hc v).1, (hc v).2.2⟩ + have bound v : base v ≤ c v := depth_bounded E d _ c demand he _ _ + refine ⟨fun v => ?_, depth_drop E d _ a b hd (fun v => ⟨le_max_left _ _, + (demand v).trans (hc v).2.1⟩), + (sum_le_sum (fun v _ => pow_le_pow_right₀ (by norm_num) (bound v))).trans hs⟩ + have hx := (requested_le a (base v) (l v)).mp (depth_ge E d (requested a ∘ l) (b - a) v) + exact ⟨hx.1, (bound v).trans (hc v).2.1, hx.2⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Reserving a separate budget for intermediate wire incidence histories -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +open Finset + +variable {F T : Type} {x y : Wire} {h u : ℕ} {L : Fringe x y T} + +/-- Uses `{ G with past := G.past }` as the representation. -/ +def reserve (G : HostNet F L h u) (cap discount : ℕ) : + HostNet F { L with cap, discount } h u := + { G with past := G.past } + +theorem past_le_mass (G : HostNet F L h u) (p : G.V × Cell h) : G.past p ≤ G.mass := + Finset.single_le_sum (f := G.past) (fun _ _ => Nat.zero_le _) (Finset.mem_univ p) + +theorem unpaid (G : HostNet F L h u) (hc : L.cap = 0) (p : G.V × Cell h) : + G.rate * (G.past p : ℝ) = 0 := by + by_cases h : G.mass ≤ L.cap + · have hp := (G.past_le_mass p).trans h + rw [show G.past p = 0 by omega, Nat.cast_zero, mul_zero] + · rw [rate, ite_eq_right h, zero_mul] + +variable [Fintype T] (G : HostNet F L h u) {B : ℝ} {Δ D : ℕ} + +theorem Bounded.start_budget (hG : G.Bounded Δ D B) (hg : G.mass = 0) (n r : ℕ) : + (G.reserve n r).Bounded Δ D B := by + refine ⟨hG.1, hG.2.1, fun v i => ?_⟩ + change G.V at v + have hp : G.past (v, i) = 0 := Nat.eq_zero_of_le_zero ((G.past_le_mass _).trans_eq hg) + have hb := hG.2.2 v i + simp only [load, reserve, hp, Nat.cast_zero, mul_zero] at hb ⊢ + exact hb + +theorem Bounded.drop_budget (hG : G.Bounded Δ D B) (r : ℕ) : + (G.reserve 0 r).Bounded Δ D B := by + refine ⟨hG.1, hG.2.1, fun v i => ?_⟩ + rw [load, unpaid _ rfl, add_zero] + exact (le_add_of_nonneg_right (mul_nonneg G.rate_nonneg (Nat.cast_nonneg _))).trans (hG.2.2 v i) + +theorem Bounded.past (hG : G.Bounded Δ D B) (hg : G.mass ≤ L.cap) (p : G.V × Cell h) : + (G.past p : ℝ) ≤ B * 2 ^ L.discount := by + apply (div_le_iff₀ (by positivity)).mp + have h := hG.2.2 p.1 p.2 + rw [load, rate, ite_eq_left hg, one_div_mul_eq_div] at h + exact (le_add_of_nonneg_left + (add_nonneg (by positivity) (mul_nonneg L.pos.le (push_nonneg _ _ L.nonneg _)))).trans h + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- +# The actual local tables inserted by a matched subround + +Only the basic six-site packet is chosen by existence. Its copies +are evaluated on their own selector and bit slices. Unmatched bits +are transported by equality constraints. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Grouping + +variable {F V E : Type} [Field F] [Fintype V] [Fintype E] {a b : Wire} + {N C : V → Finset V} {Δ D h k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (P : Gadget F) {G : Diagram F a b} {z : ℕ} + (s : Bundles G src dst ix (P.b * z)) (hz : 0 < z) + +open Classical in +theorem expansion_pair (i : g.Choice m P) (e : m.items) (j : Fin 6) (x y : G.E → Bool) + (u : g.Supply m P i × Fin z → Bool) : + (g.expansion m P s hz).entry i (.inl ⟨e, j⟩) x y u = + (P.packet z hz).rule.entry (i e) j + (fun p => x (s.bits.symm (m.pairEdge (e, p.1), p.2))) + (fun p => y (s.bits.symm (m.pairEdge (e, p.1), p.2))) + (fun p => u (.inl ⟨e, p.1, (finProdFinEquiv.symm p.2).1⟩, + (finProdFinEquiv.symm p.2).2)) := rfl + +open Classical in +theorem expansion_single (i : g.Choice m P) (v : V × Cell h) (x y : G.E → Bool) + (u : g.Supply m P i × Fin z → Bool) : + (g.expansion m P s hz).entry i (.inr v) x y u = + Spectral.Packet.checkAt F (fun p : m.unpaired × Fin (P.b * z) => (src p.1, ix p.1)) v + (fun p => x (s.bits.symm (p.1, p.2))) + (fun p => u (.inr (p.1, (finProdFinEquiv.symm p.2).1), (finProdFinEquiv.symm p.2).2)) * + Spectral.Packet.checkAt F (fun p : m.unpaired × Fin (P.b * z) => (dst p.1, ix p.1)) v + (fun p => y (s.bits.symm (p.1, p.2))) + (fun p => u (.inr (p.1, (finProdFinEquiv.symm p.2).1), (finProdFinEquiv.symm p.2).2)) := rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Grouping +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Delivery.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Delivery.lean new file mode 100644 index 0000000000..11ae00d427 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Delivery.lean @@ -0,0 +1,941 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection +public import Mathlib.Algebra.BigOperators.Field +public import Mathlib.Algebra.Order.Archimedean.Real.Basic +public import Mathlib.Algebra.Order.Floor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Reservations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix + +/-! +# Terminal loads at a good base + +Loads and reserved capacities are measured in units of `F B`. The +reservation slots depend only on capacities. The assignment of units +to slots on a contact can be used at both ends of that contact. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {T : Type} [Fintype T] {Y : ℕ} + +open scoped Classical in +private theorem assign_load (l : T → ℝ) (D : ℝ) (hD : 0 ≤ D) + (hl : ∀ t, 0 ≤ l t ∧ l t ≤ D) (hY : 0 < Y) : + ∃ p : T → Fin Y, ∀ i, (∑ t, if p t = i then l t else 0) * Y ≤ (∑ t, l t) + D * Y := by + have : Nonempty (Fin Y) := ⟨⟨0, hY⟩⟩ + have aux (s : Finset T) : ∃ p : T → Fin Y, ∀ i, + (∑ t ∈ s, if p t = i then l t else 0) * Y ≤ (∑ t ∈ s, l t) + D * Y := by + induction s using Finset.induction with + | empty => exact ⟨fun _ => ⟨0, hY⟩, fun _ => by simp [mul_nonneg hD]⟩ + | @insert t s ht ih => + obtain ⟨p, hp⟩ := ih + have avg : (∑ i : Fin Y, (∑ a ∈ s, if p a = i then l a else 0) * Y) ≤ + ∑ _i : Fin Y, ∑ a ∈ s, l a := by + rw [← sum_mul, sum_comm] + simp [mul_comm] + obtain ⟨j, _, hj⟩ := exists_le_of_sum_le univ_nonempty avg + refine ⟨Function.update p t j, fun i => ?_⟩ + have same : (∑ a ∈ s, if Function.update p t j a = i then l a else 0) = + ∑ a ∈ s, if p a = i then l a else 0 := by + refine sum_congr rfl fun a ha => ?_ + rw [Function.update_of_ne (show a ≠ t from fun e => ht (e ▸ ha))] + rw [sum_insert ht, sum_insert ht, Function.update_self, same] + by_cases he : j = i + · subst i + rw [ite_eq_left rfl, add_mul] + have := mul_le_mul_of_nonneg_right (hl t).2 (Nat.cast_nonneg Y) + linarith [(hl t).1] + · rw [ite_eq_right he, zero_add] + linarith [hp i, (hl t).1] + exact aux univ + +open scoped Classical in +/-- Assign each old tensor whole to one input terminal. -/ +theorem input_terminals (hY : 0 < Y) (l : T → ℝ) (hs : ∑ t, l t ≤ 2) + (hl : ∀ t, 0 ≤ l t ∧ l t * Y ≤ 1) : + ∃ p : T → Fin Y, ∀ i, (∑ t, if p t = i then l t else 0) * Y ≤ 3 := by + have hy : (0 : ℝ) < Y := Nat.cast_pos.mpr hY + obtain ⟨p, hp⟩ := assign_load l (1 / Y) (by positivity) + (fun t => ⟨(hl t).1, (le_div_iff₀ hy).mpr (hl t).2⟩) hY + rw [div_mul_cancel₀ _ hy.ne'] at hp + exact ⟨p, fun i => by linarith [hp i]⟩ + +open scoped Classical in +/-- Reserve disjoint output terminals using the contact capacities alone. -/ +theorem reserve_terminals (c : T → ℝ) (hc : ∀ t, 0 ≤ c t) + (hs : ∑ t, c t ≤ 2) (hcount : 4 * Fintype.card T ≤ Y) : + Nonempty ((Σ t, Fin ⌈c t * Y / 8⌉₊) ↪ Fin Y) := by + apply Function.Embedding.nonempty_of_card_le + simp only [Fintype.card_sigma, Fintype.card_fin] + have hy : (0 : ℝ) ≤ Y := Nat.cast_nonneg _ + have hnum : (4 : ℝ) * Fintype.card T ≤ Y := by exact_mod_cast hcount + have ht (t : T) : (⌈c t * Y / 8⌉₊ : ℝ) ≤ c t * Y / 8 + 1 := + (Nat.ceil_lt_add_one (div_nonneg (mul_nonneg (hc t) hy) (by norm_num))).le + have hsum := sum_le_sum (fun t (_ : t ∈ univ) => ht t) + rw [sum_add_distrib, ← sum_div, ← sum_mul, sum_const, card_univ, nsmul_eq_mul, mul_one] at hsum + have := mul_le_mul_of_nonneg_right hs hy + exact_mod_cast (show (∑ t, (⌈c t * Y / 8⌉₊ : ℝ)) ≤ Y by linarith) + +open scoped Classical in +/-- One slot choice per unit suffices at both endpoints of a contact. -/ +theorem contact_terminals (hY : 0 < Y) (l : T → ℝ) (c : ℝ) (hc : 0 < c) + (hs : ∑ t, l t ≤ c) (hl : ∀ t, 0 ≤ l t ∧ l t * Y ≤ 1) : + ∃ p : T → Fin ⌈c * Y / 8⌉₊, ∀ i, (∑ t, if p t = i then l t else 0) * Y ≤ 9 := by + have hy : (0 : ℝ) < Y := Nat.cast_pos.mpr hY + let r := ⌈c * Y / 8⌉₊ + have hr : 0 < r := Nat.ceil_pos.mpr (by positivity) + obtain ⟨p, hp⟩ := assign_load l (1 / Y) (by positivity) + (fun t => ⟨(hl t).1, (le_div_iff₀ hy).mpr (hl t).2⟩) hr + refine ⟨p, fun i => le_of_mul_le_mul_right ?_ (Nat.cast_pos.mpr hr : (0 : ℝ) < r)⟩ + have hslot : c * Y / 8 ≤ (r : ℝ) := Nat.le_ceil _ + have hload := mul_le_mul_of_nonneg_right (hp i) hy.le + have hsum := mul_le_mul_of_nonneg_right hs hy.le + rw [add_mul, mul_right_comm (1 / (Y : ℝ)), div_mul_cancel₀ _ hy.ne', one_mul] at hload + linarith + +open scoped Classical in +/-- Place a good base's demand matrix on permutations with total normalized +width at most ten. Each layer has `Y` rows of `w` ports of width `u`. -/ +theorem good_base_layers (hY : 0 < Y) {w : ℕ} (hw : 0 < w) (u : ℝ) (hu : 0 < u) + (overhead : (Y : ℝ) ^ 2 * w * u ≤ 1) (a : Fin Y → Fin Y → ℕ) + (rows : ∀ i, (∑ j, (a i j : ℝ)) * Y * u ≤ 9) + (cols : ∀ j, (∑ i, (a i j : ℝ)) * Y * u ≤ 9) : + ∃ (n : ℕ) (σ : Fin n → Equiv.Perm (Fin Y)), (n : ℝ) * Y * w * u ≤ 10 ∧ + ∀ i j, Nonempty (Fin (a i j) ↪ {t // σ t i = j} × Fin w) := by + have hpos : 0 < (Y : ℝ) * u := mul_pos (Nat.cast_pos.mpr hY) hu + let U := ⌊9 / ((Y : ℝ) * u)⌋₊ + have small (g : Fin Y → ℕ) (hg : (∑ i, (g i : ℝ)) * Y * u ≤ 9) : ∑ i, g i ≤ U := by + apply Nat.le_floor + rw [le_div_iff₀ hpos, Nat.cast_sum, ← mul_assoc] + exact hg + obtain ⟨σ, hσ⟩ := rotor_placement a U w hw (fun i => small _ (rows i)) (fun j => small _ (cols j)) + refine ⟨_, σ, ?_, hσ⟩ + have hU : (U : ℝ) * Y * u ≤ 9 * 1 := by + rw [mul_assoc, mul_one, ← le_div_iff₀ hpos] + exact Nat.floor_le (by positivity) + simpa only [Fintype.card_fin, mul_one] using rotor_cost U Y w u 1 hu.le hU overhead + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Consistent delivery slots at both ends of each contact -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +open scoped Classical in +/-- Assign a slot to each unit once, independently of the endpoint. A +contact carrying no units needs no slots, even when its capacity is zero. -/ +theorem delivery_slots {A W : Type} [Fintype A] (edge : A → W) (cap : W → ℝ) + (Y : ℕ) (hY : 0 < Y) (u : ℝ) (hu : 0 < u) (hunit : u * Y ≤ 1) + (bound : ∀ w, (∑ a, if edge a = w then u else 0) ≤ cap w) : + ∃ s : A → ℕ, (∀ a, s a < ⌈cap (edge a) * Y / 8⌉₊) ∧ + (∀ w k, (∑ a, if edge a = w ∧ s a = k then u else 0) * Y ≤ 9) := by + have assign (w : W) : + ∃ t : A → ℕ, (∀ a, edge a = w → t a < ⌈cap w * Y / 8⌉₊) ∧ + ∀ k, (∑ a, if edge a = w ∧ t a = k then u else 0) * Y ≤ 9 := by + by_cases hw : ∃ a, edge a = w + · let l (a : A) := if edge a = w then u else 0 + have hl (a : A) : 0 ≤ l a ∧ l a * Y ≤ 1 := by + by_cases ha : edge a = w <;> simp [l, ha, hunit, hu.le] + have hc : 0 < cap w := by + obtain ⟨a, ha⟩ := hw + exact lt_of_lt_of_le (sum_pos' (fun i _ => (hl i).1) + ⟨a, mem_univ a, by simpa [l, ha] using hu⟩) (bound w) + obtain ⟨p, hp⟩ := contact_terminals hY l (cap w) hc (bound w) hl + refine ⟨fun a => (p a).val, fun a _ => (p a).isLt, ?_⟩ + intro k + by_cases hk : k < ⌈cap w * Y / 8⌉₊ + · simpa only [and_comm (a := edge _ = w), ite_and, l, Fin.ext_iff] using hp ⟨k, hk⟩ + · have hn (a : A) : (p a).val ≠ k := fun e => hk (e ▸ (p a).isLt) + simp [hn] + · push Not at hw + exact ⟨fun _ => 0, by simp [hw], by simp [hw]⟩ + choose t ht hcap using assign + refine ⟨fun a => t (edge a) a, fun a => ht _ a rfl, fun w k => ?_⟩ + have he (a : A) : (edge a = w ∧ t (edge a) a = k) ↔ (edge a = w ∧ t w a = k) := by + by_cases ha : edge a = w <;> simp [ha] + simpa only [he] using hcap w k + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Leaves of a dyadic partition + +A mark splits its cell into two children. Following the prefix of a point +until the first unsplit cell gives its unique leaf. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable (M : (i : ℕ) → Cell i → Prop) {h i : ℕ} + +open scoped Classical in +/-- The cells reached by splitting marked cells, including the root. -/ +def Reached (i : ℕ) (c : Cell i) : Prop := + ∀ j (hj : j < i), M j (ancestor hj.le c) + +open scoped Classical in +/-- Requires `Reached M i c ∧ ¬M i c`. -/ +def Leaf (i : ℕ) (c : Cell i) : Prop := + Reached M i c ∧ ¬M i c + +open scoped Classical in +/-- The quantity computed by `(range (h + 1)).sigma fun i => univ.filter (Leaf M i)`. -/ +def leaves (h : ℕ) : Finset (Σ i, Cell i) := + (range (h + 1)).sigma fun i => univ.filter (Leaf M i) + +open scoped Classical in +@[simp] theorem mem_leaves (c : Σ i, Cell i) : + c ∈ leaves M h ↔ c.1 ≤ h ∧ Leaf M c.1 c.2 := by + simp [leaves] + +open scoped Classical in +theorem stop_exists (x : Cell h) : + ∃ i, ∀ hi : i < h, ¬M i (ancestor hi.le x) := + ⟨h, fun hi => (lt_irrefl h hi).elim⟩ + +open scoped Classical in +/-- Stop at the first unmarked prefix, or at full depth. -/ +def leafDepth (x : Cell h) : ℕ := + Nat.find (stop_exists M x) + +open scoped Classical in +theorem leafDepth_le (x : Cell h) : leafDepth M x ≤ h := + Nat.find_min' (stop_exists M x) fun hi => (lt_irrefl h hi).elim + +open scoped Classical in +theorem leafDepth_le_of_unmarked (x : Cell h) (hi : i ≤ h) (hc : ¬M i (ancestor hi x)) : + leafDepth M x ≤ i := + Nat.find_min' (stop_exists M x) fun _ => hc + +open scoped Classical in +theorem marked_before_leaf (x : Cell h) (hi : i ≤ h) (hd : i < leafDepth M x) : + M i (ancestor hi x) := by + by_contra hn + exact hd.not_ge (leafDepth_le_of_unmarked M x hi hn) + +open scoped Classical in +theorem leafDepth_spec (x : Cell h) (hstop : ¬M h x) : + Leaf M (leafDepth M x) (ancestor (leafDepth_le M x) x) := by + refine ⟨fun j hj => marked_before_leaf M x (hj.le.trans (leafDepth_le M x)) hj, ?_⟩ + have hm : ∀ i (hi : i ≤ h), i = h → ¬M i (ancestor hi x) := by + rintro _ _ rfl + exact hstop + rcases (leafDepth_le M x).lt_or_eq with hl | he + · exact Nat.find_spec (stop_exists M x) hl + · exact hm _ _ he + +open scoped Classical in +/-- Uses `⟨leafDepth M x, ancestor (leafDepth_le M x) x⟩` as the representation. -/ +def leafAt (x : Cell h) : Σ i, Cell i := + ⟨leafDepth M x, ancestor (leafDepth_le M x) x⟩ + +open scoped Classical in +theorem leafAt_mem (x : Cell h) (hstop : ¬M h x) : + leafAt M x ∈ leaves M h := + (mem_leaves M _).mpr ⟨leafDepth_le M x, leafDepth_spec M x hstop⟩ + +open scoped Classical in +/-- The fiber over a leaf consists of precisely the points with that prefix. -/ +theorem leafAt_eq_iff (x : Cell h) {c : Cell i} (hi : i ≤ h) (hl : Leaf M i c) : + leafAt M x = ⟨i, c⟩ ↔ ancestor hi x = c := by + constructor + · intro he + have hd : leafDepth M x = i := congrArg Sigma.fst he + subst i + exact eq_of_heq (Sigma.mk.inj he).2 + · rintro rfl + have hd : leafDepth M x = i := by + refine le_antisymm (leafDepth_le_of_unmarked M x hi hl.2) (le_of_not_gt ?_) + intro hlt + exact Nat.find_spec (stop_exists M x) (hlt.trans_le hi) (hl.1 _ hlt) + subst i + rfl + +open scoped Classical in +/-- A leaf of depth `i` contains exactly `2 ^ (h-i)` points, even +after a common permutation of the indices. -/ +theorem card_leafAt (π : Equiv.Perm (Cell h)) {c : Σ i, Cell i} (hc : c ∈ leaves M h) : + (univ.filter fun x => leafAt M (π x) = c).card = 2 ^ (h - c.1) := by + obtain ⟨i, c⟩ := c + obtain ⟨hi, hl⟩ := (mem_leaves M _).mp hc + rw [← card_prefix hi c, Fintype.card_subtype] + apply card_equiv π + intro x + simpa only [mem_filter, mem_univ, true_and] using leafAt_eq_iff M (π x) hi hl + +open scoped Classical in +/-- A split propagated up by `d` levels costs at most `d` levels of depth +at a common point. -/ +theorem leafDepth_le_add (N : (i : ℕ) → Cell i → Prop) (d : ℕ) + (propagate : ∀ i, i + d < h → ∀ c : Cell (i + d), + M (i + d) c → N i (ancestor (Nat.le_add_right i d) c)) + (x : Cell h) : leafDepth M x ≤ leafDepth N x + d := by + apply le_of_not_gt + intro bad + have hi := bad.trans_le (leafDepth_le M x) + have hm := marked_before_leaf M x hi.le bad + exact Nat.find_spec (stop_exists N x) ((Nat.le_add_right _ _).trans_lt hi) + (propagate _ hi _ hm) + +open scoped Classical in +private theorem split_level (hc : ∀ c, M i c → Reached M i c) : + (univ.filter (M i)).card + (univ.filter (Leaf M i)).card = + (univ.filter (Reached M i)).card := by + let s := univ.filter (Reached M i) + have hm : s.filter (M i) = univ.filter (M i) := by + ext c + simp only [s, mem_filter, mem_univ, true_and] + exact ⟨And.right, fun h => ⟨hc c h, h⟩⟩ + have hl : s.filter (fun c => ¬M i c) = univ.filter (Leaf M i) := by + ext c + simp [s, Leaf] + rw [← hm, ← hl] + exact card_filter_add_card_filter_not _ + +open scoped Classical in +private theorem reached_succ (hc : ∀ c, M i c → Reached M i c) : + (univ.filter (Reached M (i + 1))).card = 2 * (univ.filter (M i)).card := by + have he : (univ.filter (Reached M (i + 1))).card = + ((univ : Finset (ZMod 2)) ×ˢ univ.filter (M i)).card := by + apply card_equiv (Fin.snocEquiv (fun _ : Fin (i + 1) => ZMod 2)).symm + intro c + simp only [mem_filter, mem_univ, true_and, mem_product] + change Reached M (i + 1) c ↔ M i (ancestor (Nat.le_succ i) c) + refine ⟨fun h => h i (Nat.lt_succ_self i), fun hm j hj => ?_⟩ + rcases (Nat.le_of_lt_succ hj).lt_or_eq with hl | rfl + · exact hc _ hm j hl + · exact hm + simpa using he + +open scoped Classical in +/-- Each marked cell adds one leaf. -/ +theorem card_leaves (closed : ∀ i, i ≤ h → ∀ c, M i c → Reached M i c) + (stop : ∀ c, ¬M h c) : + (leaves M h).card = 1 + ∑ i ∈ range h, (univ.filter (M i)).card := by + have aux : ∀ k, k ≤ h → + (leaves M k).card + (univ.filter (M k)).card = + 1 + ∑ i ∈ range k, (univ.filter (M i)).card := by + intro k hk + induction k with + | zero => + have he := split_level M (closed _ hk) + have hr : univ.filter (Reached M 0) = univ := by ext; simp [Reached] + rw [hr] at he + simpa [leaves, card_sigma, add_comm] using he + | succ k ih => + have hp := ih ((Nat.le_succ k).trans hk) + have he := split_level M (closed _ hk) + rw [reached_succ M (closed _ ((Nat.le_succ k).trans hk))] at he + simp only [leaves, card_sigma] at hp ⊢ + rw [sum_range_succ, sum_range_succ (fun i => (univ.filter (M i)).card)] + omega + simpa [stop] using aux h le_rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Units routed through a good base + +The demand units are individually named. After assigning input items and +reserving output terminals, place each unit in a distinct port at each end +of its permutation layer. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {Y w : ℕ} {A T O : Type} [Fintype A] [Fintype T] + +open scoped Classical in +private theorem route_layers (hY : 0 < Y) (hw : 0 < w) (u : ℝ) (hu : 0 < u) + (overhead : (Y : ℝ) ^ 2 * w * u ≤ 1) (p q : A → Fin Y) + (hp : ∀ i, (∑ a, if p a = i then u else 0) * Y ≤ 9) + (hq : ∀ j, (∑ a, if q a = j then u else 0) * Y ≤ 9) : + ∃ (n : ℕ) (σ : Fin n → Equiv.Perm (Fin Y)) (r : A → Fin n × Fin w), + (n : ℝ) * Y * w * u ≤ 10 ∧ + (∀ a, σ (r a).1 (p a) = q a) ∧ + Function.Injective (fun a => (p a, r a)) ∧ Function.Injective (fun a => (q a, r a)) := by + let m (i j : Fin Y) := (univ.filter fun a => p a = i ∧ q a = j).card + have count (i j : Fin Y) : (m i j : ℝ) * u = ∑ a, if p a = i ∧ q a = j then u else 0 := by + rw [← sum_filter, sum_const, nsmul_eq_mul] + have rows i : (∑ j, (m i j : ℝ)) * Y * u ≤ 9 := by + rw [mul_right_comm, sum_mul] + simp_rw [count] + rw [sum_comm] + simpa [and_comm (a := p _ = i), ite_and] using hp i + have cols j : (∑ i, (m i j : ℝ)) * Y * u ≤ 9 := by + rw [mul_right_comm, sum_mul] + simp_rw [count] + rw [sum_comm] + simpa [ite_and] using hq j + obtain ⟨n, σ, hcost, layers⟩ := good_base_layers hY hw u hu overhead m rows cols + have slots i j : ∃ f : {a // p a = i ∧ q a = j} → Fin n × Fin w, + Function.Injective f ∧ ∀ a, σ (f a).1 i = j := by + obtain ⟨e⟩ := layers i j + let g := (Fintype.equivFinOfCardEq + (show Fintype.card {a // p a = i ∧ q a = j} + = m i j from Fintype.card_subtype _)).toEmbedding.trans e + refine ⟨fun a => ((g a).1.val, (g a).2), ?_, fun a => (g a).1.property⟩ + intro a b eq + exact g.injective (Prod.ext (Subtype.ext (Prod.mk.inj eq).1) (Prod.mk.inj eq).2) + choose f hf hs using slots + let r (a : A) := f (p a) (q a) ⟨a, rfl, rfl⟩ + have hr a : σ (r a).1 (p a) = q a := hs _ _ _ + have he a i j (hi : p a = i) (hj : q a = j) : r a = f i j ⟨a, hi, hj⟩ := by + subst i; subst j; rfl + have inj : Function.Injective (fun a => (p a, r a)) := by + intro a b eq + obtain ⟨hi, heq⟩ := Prod.mk.inj eq + have hj : q a = q b := by rw [← hr a, ← hr b, heq, hi] + rw [he a _ _ hi hj, he b _ _ rfl rfl] at heq + exact congrArg Subtype.val (hf _ _ heq) + refine ⟨n, σ, r, hcost, hr, inj, ?_⟩ + intro a b eq + obtain ⟨hj, heq⟩ := Prod.mk.inj eq + rw [← hr a, ← hr b, heq] at hj + exact inj (Prod.ext ((σ _).injective hj) heq) + +open scoped Classical in +/-- Route named units, keeping all input items whole and respecting the +predetermined assignment to reserved output slots. -/ +theorem route_good_base (hY : 0 < Y) (hw : 0 < w) (u : ℝ) (hu : 0 < u) + (overhead : (Y : ℝ) ^ 2 * w * u ≤ 1) (src : A → T) (dst : A → O) (out : O ↪ Fin Y) + (l : T → ℝ) (total : ∑ t, l t ≤ 2) (item : ∀ t, 0 ≤ l t ∧ l t * Y ≤ 1) + (hs : ∀ t, (∑ a, if src a = t then u else 0) ≤ l t) + (hd : ∀ o, (∑ a, if dst a = o then u else 0) * Y ≤ 9) : + ∃ (p : T → Fin Y) (n : ℕ) (σ : Fin n → Equiv.Perm (Fin Y)) (r : A → Fin n × Fin w), + (∀ i, (∑ t, if p t = i then l t else 0) * Y ≤ 3) ∧ (n : ℝ) * Y * w * u ≤ 10 ∧ + (∀ a, σ (r a).1 (p (src a)) = out (dst a)) ∧ + Function.Injective (fun a => (p (src a), r a)) ∧ + Function.Injective (fun a => (out (dst a), r a)) := by + obtain ⟨p, hp⟩ := input_terminals hY l total item + have source i : (∑ a, if p (src a) = i then u else 0) * Y ≤ 9 := by + refine le_trans ?_ ((hp i).trans (by norm_num : (3 : ℝ) ≤ 9)) + apply mul_le_mul_of_nonneg_right _ (Nat.cast_nonneg _) + calc + _ = ∑ t, ∑ a, if src a = t then (if p t = i then u else 0) else 0 := by + rw [sum_comm] + simp + _ ≤ _ := by + refine sum_le_sum fun t _ => ?_ + split_ifs with h + · exact hs t + · simp + have dest j : (∑ a, if out (dst a) = j then u else 0) * Y ≤ 9 := by + by_cases hr : ∃ o, out o = j + · obtain ⟨o, rfl⟩ := hr + simpa only [out.injective.eq_iff] using hd o + · push Not at hr + simp [hr] + obtain ⟨n, σ, r, hh⟩ := route_layers hY hw u hu overhead _ _ source dest + exact ⟨p, n, σ, r, hp, hh⟩ + +variable {V : Type} + +open scoped Classical in +/-- Each contact between two base cells has a slot at either endpoint. -/ +abbrev BaseContact (base : V → ℕ) (ends : A → Bool → V) (v : V) (z : Cell (base v)) := + {e : Σ c : A, Bool × Cell (contactDepth base ends c) // + contactEnd base ends ⟨e.1, e.2.2⟩ e.2.1 = ⟨v, z⟩} + +open scoped Classical in +/-- The capacities at both ends of a contact prescribe the same number +of slots. This reservation precedes the choice of a permutation. -/ +theorem reserve_base (base : V → ℕ) (ends : A → Bool → V) (v : V) (z : Cell (base v)) + (s : ℕ) (D : ℝ) (hD : 0 < D) (y : A → ℝ) (hy : ∀ c, 0 ≤ y c) + (gap : ∀ c t, ends c t = v → contactDepth base ends c ≤ base v + s) + (degree : (∑ c, ∑ t : Bool, if ends c t = v then (1 : ℝ) else 0) ≤ D) + (mass : (∑ c, ∑ t : Bool, if ends c t = v then y c else 0) ≤ (2 : ℝ) ^ (base v)) + (enough : 4 * (D * (2 : ℝ) ^ s) ≤ Y) : + let cap := fun c => y c / (2 : ℝ) ^ (contactDepth base ends c) + 1 / (D * (2 : ℝ) ^ s) + Nonempty ((Σ e : BaseContact base ends v z, Fin ⌈cap e.val.1 * Y / 8⌉₊) ↪ Fin Y) := by + intro cap + let C := BaseContact base ends v z + have sum_contacts (l : A → ℝ) : (∑ e : C, l e.val.1) = + ∑ c, ∑ t, ∑ w, if contactEnd base ends ⟨c, w⟩ t = ⟨v, z⟩ then l c else 0 := by + let p (e : Σ c : A, Bool × Cell (contactDepth base ends c)) := + contactEnd base ends ⟨e.1, e.2.2⟩ e.2.1 = ⟨v, z⟩ + rw [← sum_subtype (univ.filter p) (fun _ => mem_filter_univ _) (fun e => l e.1)] + simp only [sum_filter, Fintype.sum_sigma, Fintype.sum_prod_type, p] + apply reserve_terminals (fun e : C => cap e.val.1) + · intro e + have := hy e.val.1 + unfold cap + positivity + · rw [sum_contacts] + exact reservation_bound base ends y v z s D hD gap degree mass + · have hc : (Fintype.card C : ℝ) ≤ D * (2 : ℝ) ^ s := by + have hb := reservation_count base ends v z s D gap degree + rw [← sum_contacts (fun _ => 1)] at hb + simpa using hb + exact_mod_cast (show (4 : ℝ) * Fintype.card C ≤ Y by linarith) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Routing all good units through reserved output terminals + +Choose the same link slot at both ends, then apply the per-base routing +theorem independently at each leaf. No rotor layers are needed on leaves +without good demand. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +open scoped Classical in +theorem sub_sum {P : Type} [Fintype P] (p : P → Prop) [DecidablePred p] (l : P → ℝ) : + (∑ t : {i // p i}, l t.val) = ∑ t, if p t then l t else 0 := by + rw [← sum_subtype (univ.filter p) (fun _ => mem_filter_univ _) l, sum_filter] + +open scoped Classical in +private theorem units_mono {A B : Type} [Fintype A] [Fintype B] + (u : ℝ) (hu : 0 ≤ u) (s : A → Prop) (t : B → Prop) [DecidablePred t] + (f : A → B) (hs : ∀ a, s a → t (f a)) + (hi : ∀ a b, s a → s b → f a = f b → a = b) : + (∑ a, if s a then u else 0) ≤ ∑ b, if t b then u else 0 := by + simp only [← sum_filter, sum_const, nsmul_eq_mul] + refine mul_le_mul_of_nonneg_right (Nat.cast_le.mpr (card_le_card_of_injOn f ?_ ?_)) hu + · intro a ha + exact mem_filter_univ _ |>.mpr (hs a ((mem_filter.mp ha).2)) + · intro a ha b hb he + exact hi a b (mem_filter.mp ha).2 (mem_filter.mp hb).2 he + +variable {P U X W : Type} [Fintype P] [Fintype U] + +omit [Fintype P] in +open scoped Classical in +/-- Bounds at either end of a routing problem, independent of the +particular balanced choice of slots. -/ +theorem delivery_bound (leaf : P → X) (point : U → Bool → P) (good : U → Prop) + (edge : U → W) (outLeaf : W → Bool → X) (cap : W → ℝ) (Y : ℕ) (l : P → ℝ) (u : ℝ) + (hu : 0 < u) (agree : ∀ a, good a → ∀ t, leaf (point a t) = outLeaf (edge a) t) + (slot : ∀ a : {i // good i}, Fin ⌈cap (edge a.val) * Y / 8⌉₊) + (hs : ∀ p, push (Function.uncurry point) (fun _ => u) p ≤ l p) + (bound : ∀ i k, + (∑ a : {a // good a}, if edge a.val = i ∧ (slot a).val = k then u else 0) * Y ≤ 9) + (x : X) : + let src (q : GoodEnd leaf point good x) : {p // leaf p = x} := + ⟨point q.val.1.val q.val.2, q.property⟩ + let dst := portOf leaf point good edge outLeaf cap Y agree slot (x := x) + (∀ t, push src (fun _ => u) t ≤ l t.val) ∧ (∀ o, push dst (fun _ => u) o * Y ≤ 9) := by + let T x := {p // leaf p = x} + let Q x := GoodEnd leaf point good x + let src x (q : Q x) : T x := ⟨point q.val.1.val q.val.2, q.property⟩ + let dst x (q : Q x) := portOf leaf point good edge outLeaf cap Y agree slot q + have srcBound x (t : T x) : push (src x) (fun _ => u) t ≤ l t.val := by + apply le_trans _ (hs t.val) + apply units_mono u hu.le _ _ (fun q : Q x => (q.val.1.val, q.val.2)) + · intro q hq + exact congrArg Subtype.val hq + · intro a b _ _ h + exact Subtype.ext (Prod.ext (Subtype.ext (Prod.mk.inj h).1) (Prod.mk.inj h).2) + have dstBound x (o : Port outLeaf cap Y x) : + push (dst x) (fun _ => u) o * Y ≤ 9 := by + apply le_trans _ (bound o.1.val.1 o.2.val) + apply mul_le_mul_of_nonneg_right _ (Nat.cast_nonneg Y) + apply units_mono u hu.le _ _ (fun q : Q x => q.val.1) + · intro q hq + exact ⟨congrArg (fun a => a.1.val.1) hq, congrArg (fun a => a.2.val) hq⟩ + · intro a b ha hb h + exact Subtype.ext (Prod.ext h (congrArg (fun a => a.1.val.2) (ha.trans hb.symm))) + exact ⟨srcBound x, dstBound x⟩ + +open scoped Classical in +/-- All widths are measured in units of the common base capacity. -/ +theorem deliver (leaf : P → X) (point : U → Bool → P) (good : U → Prop) + (edge : U → W) (outLeaf : W → Bool → X) (cap : W → ℝ) (Y w : ℕ) + (out : ∀ x, Port outLeaf cap Y x ↪ Fin Y) (l : P → ℝ) (u : ℝ) + (hY : 0 < Y) (hw : 0 < w) (hu : 0 < u) (overhead : (Y : ℝ) ^ 2 * w * u ≤ 1) + (agree : ∀ a, good a → ∀ t, leaf (point a t) = outLeaf (edge a) t) + (total : ∀ x, push leaf l x ≤ 2) (item : ∀ p, 0 ≤ l p ∧ l p * Y ≤ 1) + (hs : ∀ p, push (Function.uncurry point) (fun _ => u) p ≤ l p) + (hd : ∀ i, push edge (fun a => if good a then u else 0) i ≤ cap i) : + Nonempty (Delivery leaf point good edge outLeaf cap Y w out l u) := by + have hunit : u * Y ≤ 1 := calc + _ ≤ (Y : ℝ) ^ 2 * w * u := by + rw [mul_comm u] + apply mul_le_mul_of_nonneg_right _ hu.le + exact_mod_cast (show Y ≤ Y ^ 2 * w from (by nlinarith [Nat.mul_le_mul_left (Y ^ 2) hw])) + _ ≤ 1 := overhead + let A := {i // good i} + have hcap (i : W) : (∑ a : A, if edge a.val = i then u else 0) ≤ cap i := by + apply le_trans _ (hd i) + rw [sub_sum good (fun a => if edge a = i then u else 0)] + exact sum_le_sum fun a _ => by dsimp; split_ifs <;> rfl + obtain ⟨s, hslot, bound⟩ := delivery_slots (fun a : A => edge a.val) cap Y hY u hu hunit hcap + let slot (a : A) : Fin ⌈cap (edge a.val) * Y / 8⌉₊ := ⟨s a, hslot a⟩ + let T x := {p // leaf p = x} + let Q x := GoodEnd leaf point good x + let src x (q : Q x) : T x := ⟨point q.val.1.val q.val.2, q.property⟩ + let dst x (q : Q x) := portOf leaf point good edge outLeaf cap Y agree slot q + have hroute := delivery_bound leaf point good edge outLeaf cap Y l u hu agree slot hs bound + have route (x : X) : + ∃ (p : T x → Fin Y) (n : ℕ) (σ : Fin n → Equiv.Perm (Fin Y)) (r : Q x → Fin n × Fin w), + (∀ i, (∑ t, if p t = i then l t.val else 0) * Y ≤ 3) ∧ + (n : ℝ) * Y * w * u ≤ 10 ∧ (IsEmpty (Q x) → n = 0) ∧ + (∀ a, σ (r a).1 (p (src x a)) = out x (dst x a)) ∧ + Function.Injective (fun a => (p (src x a), r a)) ∧ + Function.Injective (fun a => (out x (dst x a), r a)) := by + obtain ⟨p, n, σ, r, hp, hn, hr⟩ := route_good_base hY hw u hu overhead + (src x) (dst x) (out x) (fun t => l t.val) + ((sub_sum _ _).le.trans (total x)) (fun t => item t.val) (hroute x).1 (hroute x).2 + by_cases h : IsEmpty (Q x) + · exact ⟨p, 0, Fin.elim0, isEmptyElim, hp, by simp, fun _ => rfl, + isEmptyElim, isEmptyElim, isEmptyElim⟩ + · exact ⟨p, n, σ, r, hp, hn, fun he => (h he).elim, hr⟩ + choose p n σ r hp hn he hr hi ho using route + let terminal (a : P) := p (leaf a) ⟨a, rfl⟩ + have ht x (t : T x) : terminal t.val = p x t := by + rcases t with ⟨a, rfl⟩ + rfl + have hq x (q : Q x) : terminal (point q.val.1.val q.val.2) = p x (src x q) := ht x (src x q) + refine ⟨⟨agree, slot, terminal, n, σ, r, ?_, hn, he, ?_, ?_, ho⟩⟩ + · intro x i + have h := hp x i + simp_rw [← ht x] at h + rw [sub_sum (fun t => leaf t = x) (fun t => if terminal t = i then l t else 0)] at h + simpa only [push, Prod.mk.injEq, ite_and] using h + · intro x q + rw [hq] + exact hr x q + · intro x + simpa only [hq] using hi x + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Placing bases and their adaptive leaves on the common host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +variable {V : Type} {h : ℕ} + +open Classical in +/-- The value specified by `(z.1, ⟨⟨base z.1, Nat.lt_succ_of_le (hb z.1)⟩, z.2⟩)`. -/ +def baseSite (base : V → ℕ) (hb : ∀ v, base v ≤ h) (z : Σ v, Cell (base v)) : Site V h := + (z.1, ⟨⟨base z.1, Nat.lt_succ_of_le (hb z.1)⟩, z.2⟩) + +open Classical in +theorem baseSite_injective (base : V → ℕ) (hb : ∀ v, base v ≤ h) : + Function.Injective (baseSite base hb) := by + rintro ⟨v, x⟩ ⟨w, y⟩ he + have hv : v = w := congrArg Prod.fst he + subst w + have : x = y := by simpa [baseSite] using he + subst y + rfl + +open Classical in +/-- Indexes the link by the coordinates of `Σ c, Cell (contactDepth base ends c)`. -/ +abbrev Link {A : Type} (base : V → ℕ) (ends : A → Bool → V) := + Σ c, Cell (contactDepth base ends c) + +open Classical in +/-- Computes the out leaf by the application `baseSite base hb (contactEnd base ends z t)`. -/ +abbrev outLeaf {A : Type} (base : V → ℕ) (ends : A → Bool → V) (hb : ∀ v, base v ≤ h) + (z : Link base ends) (t : Bool) := baseSite base hb (contactEnd base ends z t) + +open Classical in +/-- The indexed operation `Port (outLeaf base ends hb) (fun z => capacity z.1) Y`. -/ +abbrev Slots {A : Type} (base : V → ℕ) (ends : A → Bool → V) (hb : ∀ v, base v ≤ h) + (capacity : A → ℝ) (Y : ℕ) := Port (outLeaf base ends hb) (fun z => capacity z.1) Y + +open Classical in +/-- Uses `⟨x.1, ancestor (hb x.1) (π x.2)⟩` as the representation. -/ +def prefixSite (base : V → ℕ) (hb : ∀ v, base v ≤ h) + (π : Equiv.Perm (Cell h)) (x : V × Cell h) : Σ v, Cell (base v) := + ⟨x.1, ancestor (hb x.1) (π x.2)⟩ + +variable (M : V → (i : ℕ) → Cell i → Prop) (π : Equiv.Perm (Cell h)) + +open Classical in +/-- The value specified by `(x.1, ⟨⟨leafDepth (M x.1) (π x.2), Nat.lt_succ_of_le (leafDepth_le _ +_)⟩, ancestor (leafDepth_le (M x.1) (π x.2)) (π x.2)⟩)`. -/ +def leafSite (x : V × Cell h) : Site V h := + (x.1, ⟨⟨leafDepth (M x.1) (π x.2), Nat.lt_succ_of_le (leafDepth_le _ _)⟩, + ancestor (leafDepth_le (M x.1) (π x.2)) (π x.2)⟩) + +open Classical in +theorem leafSite_contains (x : V × Cell h) : (leafSite M π x).contains (π x.2) := rfl + +open Classical in +private theorem site_ext (p q : Site V h) (hv : p.1 = q.1) + (hc : (⟨p.depth, p.2.2⟩ : Σ i, Cell i) = ⟨q.depth, q.2.2⟩) : p = q := by + obtain ⟨u, ⟨⟨i, hi⟩, x⟩⟩ := p + obtain ⟨v, ⟨⟨j, hj⟩, y⟩⟩ := q + cases hv + cases hc + rfl + +open Classical in +theorem leafSite_prefix (base : V → ℕ) (hb : ∀ v, base v ≤ h) (p : V × Cell h) + (hl : Leaf (M p.1) (base p.1) (ancestor (hb p.1) (π p.2))) : + leafSite M π p = baseSite base hb (prefixSite base hb π p) := by + exact site_ext _ _ rfl ((leafAt_eq_iff (M p.1) _ _ hl).mpr rfl) + +open Classical in +/-- Slots in the common host that are not used in this group have zero load. -/ +theorem leafSite_mass [Fintype V] (l : V → Cell h → ℝ) + (hm : ∀ v x, leafAt (M v) (π x) ∈ leaves (M v) h) + (hl : ∀ v c, c ∈ leaves (M v) h → + (∑ x, if leafAt (M v) (π x) = c then l v x else 0) ≤ 2) (p : Site V h) : + push (leafSite M π) (Function.uncurry l) p ≤ 2 := by + let c : Σ i, Cell i := ⟨p.depth, p.2.2⟩ + have he x : leafSite M π (p.1, x) = p ↔ leafAt (M p.1) (π x) = c := by + refine ⟨fun e => ?_, fun h => site_ext _ _ rfl h⟩ + exact congrArg (fun q : Site V h => (⟨q.depth, q.2.2⟩ : Σ i, Cell i)) e + unfold push + rw [Fintype.sum_prod_type, sum_eq_single p.1] + · simp only [he, Function.uncurry_apply_pair] + by_cases hc : c ∈ leaves (M p.1) h + · exact hl p.1 c hc + · have hn x : leafAt (M p.1) (π x) ≠ c := fun eq => hc (eq ▸ hm _ x) + simp [hn] + · intro v _ hv + have hn x : leafSite M π (v, x) ≠ p := fun eq => hv (congrArg Prod.fst eq) + simp [hn] + · simp + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Uniform reservations across groups + +Choose output terminal numbers using only the relative contact address. +At any given absolute base the relative slot map is injective, even +though all groups share the same terminal numbers. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V A : Type} {h Y : ℕ} {base : V → ℕ} {ends : A → Bool → V} + {hb : ∀ v, base v ≤ h} {cap : A → ℝ} + +open scoped Classical in +theorem drop_contact (a : ℕ) (hb : ∀ v, base v ≤ h) (z : Link base ends) (t : Bool) : + Site.drop a (outLeaf base ends hb z t) = + outLeaf (relBase a base) ends (relHi a hb) (dropContact a z) t := rfl + +open scoped Classical in +/-- Local slot numbers are preserved under removal of the group prefix. -/ +def dropSlot (a : ℕ) (lo : ∀ v, a ≤ base v) (x : Site V h) : + Slots base ends hb cap Y x ↪ Slots (relBase a base) ends (relHi a hb) cap Y (x.drop a) where + toFun p := ⟨⟨(dropContact a p.1.val.1, p.1.val.2), + (drop_contact a hb _ _).symm.trans (congrArg (Site.drop a) p.1.property)⟩, p.2⟩ + inj' := by + rintro ⟨⟨⟨e, t⟩, he⟩, i⟩ ⟨⟨⟨f, s⟩, hf⟩, j⟩ eq + obtain ⟨hz, hij⟩ := Sigma.mk.inj eq + obtain ⟨hr, rfl⟩ := Prod.mk.inj (congrArg Subtype.val hz) + have : e = f := dropContact_inj a lo t hr (baseSite_injective _ _ (he.trans hf.symm)) + subst f + cases eq_of_heq hij + rfl + +open scoped Classical in +/-- Embeds `Slots base ends hb cap Y x` into `Fin Y`. -/ +def liftSlots (a : ℕ) (lo : ∀ v, a ≤ base v) + (o : ∀ x, Slots (relBase a base) ends (relHi a hb) cap Y x ↪ Fin Y) + (x : Site V h) : Slots base ends hb cap Y x ↪ Fin Y := + (dropSlot a lo x).trans (o (x.drop a)) + +open scoped Classical in +private def toBaseContact (v : V) (z : Cell (base v)) : + Slots base ends hb cap Y (baseSite base hb ⟨v, z⟩) ↪ + Σ e : BaseContact base ends v z, Fin ⌈cap e.val.1 * Y / 8⌉₊ where + toFun p := ⟨⟨⟨p.1.val.1.1, p.1.val.2, p.1.val.1.2⟩, baseSite_injective _ _ p.1.property⟩, p.2⟩ + inj' := by + rintro ⟨⟨⟨⟨c, b⟩, t⟩, he⟩, i⟩ ⟨⟨⟨⟨d, w⟩, s⟩, hf⟩, j⟩ eq + obtain ⟨hz, hij⟩ := Sigma.mk.inj eq + obtain ⟨rfl, hts⟩ := Sigma.mk.inj (congrArg Subtype.val hz) + obtain ⟨rfl, rfl⟩ := Prod.mk.inj (eq_of_heq hts) + cases eq_of_heq hij + rfl + +variable [Fintype A] (base : V → ℕ) (ends : A → Bool → V) (hb : ∀ v, base v ≤ h) + (s : ℕ) (D : ℝ) (hD : 0 < D) (y : A → ℝ) (hy : ∀ c, 0 ≤ y c) + (gap : ∀ c t, contactDepth base ends c ≤ base (ends c t) + s) + (degree : letI := Classical.decEq V + ∀ v, (∑ c, ∑ t : Bool, if ends c t = v then (1 : ℝ) else 0) ≤ D) + (mass : letI := Classical.decEq V + ∀ v, (∑ c, ∑ t : Bool, if ends c t = v then y c else 0) ≤ (2 : ℝ) ^ (base v)) + (enough : 4 * (D * (2 : ℝ) ^ s) ≤ Y) + +include hD hy gap degree mass enough + +open scoped Classical in +theorem slots_exist (x : Site V h) : + let capacity := fun c => y c / (2 : ℝ) ^ (contactDepth base ends c) + 1 / (D * (2 : ℝ) ^ s) + Nonempty (Slots base ends hb capacity Y x ↪ Fin Y) := by + intro capacity + by_cases h : ∃ z, baseSite base hb z = x + · obtain ⟨⟨v, z⟩, rfl⟩ := h + obtain ⟨f⟩ := reserve_base base ends v z s D hD y hy (fun c t e => e ▸ gap c t) + (degree v) (mass v) enough + exact ⟨(toBaseContact v z).trans f⟩ + · have : IsEmpty (Slots base ends hb capacity Y x) := ⟨fun p => h ⟨_, p.1.property⟩⟩ + exact ⟨⟨isEmptyElim, isEmptyElim⟩⟩ + +open scoped Classical in +theorem relative_slots (a : ℕ) (lo : ∀ v, a ≤ base v) (x : Site V (h - a)) : + let capacity := fun c => y c / (2 : ℝ) ^ (contactDepth base ends c) + 1 / (D * (2 : ℝ) ^ s) + Nonempty (Slots (relBase a base) ends (relHi a hb) capacity Y x ↪ Fin Y) := by + intro capacity + let m := fun c => y c / (2 : ℝ) ^ a + have hg c t : contactDepth (relBase a base) ends c ≤ relBase a base (ends c t) + s := by + rw [relDepth, relBase] + have := gap c t + omega + have hm v : (∑ c, ∑ t : Bool, if ends c t = v then m c else 0) ≤ + (2 : ℝ) ^ (relBase a base v) := by + have hx := div_le_div_of_nonneg_right (mass v) (show 0 ≤ (2 : ℝ) ^ a by positivity) + simpa only [m, zero_mul, relBase, pow_sub₀ (2 : ℝ) (by norm_num) (lo v), div_eq_mul_inv, + sum_mul, ite_mul] using hx + have eqn : capacity = fun c => + m c / (2 : ℝ) ^ (contactDepth (relBase a base) ends c) + 1 / (D * (2 : ℝ) ^ s) := by + funext c + have hc := (lo _).trans (le_contactDepth base ends c false) + unfold capacity m + rw [div_div, ← pow_add, relDepth, Nat.add_sub_of_le hc] + rw [eqn] + exact slots_exist (relBase a base) ends (relHi a hb) s D hD m (fun c => div_nonneg (hy c) + (by positivity)) hg degree hm enough x + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Shared direct links on the reset host + +An output terminal used by a good contact has a unique peer. The +involution depends only on the reservations, and pairs the same +relative terminals in all groups when the reservations are lifted. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +variable {P U X W : Type} {outLeaf : W → Bool → X} {cap : W → ℝ} {Y w : ℕ} + (out : ∀ x, Port outLeaf cap Y x ↪ Fin Y) + +open scoped Classical in +/-- Indexes the socket by the coordinates of `(Σ c, Fin ⌈cap c * Y / 8⌉₊) × Bool`. -/ +abbrev Socket (cap : W → ℝ) (Y : ℕ) := (Σ c, Fin ⌈cap c * Y / 8⌉₊) × Bool + +open scoped Classical in +private def socket {x : X} (p : Port outLeaf cap Y x) : Socket cap Y := + (⟨p.1.val.1, p.2⟩, p.1.val.2) + +open scoped Classical in +/-- The value specified by `(outLeaf p.1.1 p.2, out _ ⟨⟨(p.1.1, p.2), rfl⟩, p.1.2⟩)`. -/ +def attach (p : Socket cap Y) : X × Fin Y := + (outLeaf p.1.1 p.2, out _ ⟨⟨(p.1.1, p.2), rfl⟩, p.1.2⟩) + +open scoped Classical in +private theorem attach_socket {x : X} (p : Port outLeaf cap Y x) : + attach out (socket p) = (x, out x p) := by + rcases p with ⟨⟨⟨c, t⟩, rfl⟩, i⟩ + rfl + +open scoped Classical in +private theorem attach_inj : Function.Injective (attach out) := by + have key {x y : X} (p : Port outLeaf cap Y x) (q : Port outLeaf cap Y y) + (h : (x, out x p) = (y, out y q)) : socket p = socket q := by + obtain ⟨rfl, he⟩ := Prod.mk.inj h + rw [(out x).injective he] + intro p q h + exact key _ _ h + +open scoped Classical in +/-- This involution fixes unused terminals. -/ +def peer (z : X × Fin Y) : X × Fin Y := + if h : ∃ p, attach out p = z then attach out (h.choose.1, !h.choose.2) else z + +open scoped Classical in +private theorem peer_attach (p : Socket cap Y) : + peer out (attach out p) = attach out (p.1, !p.2) := by + have h : ∃ q, attach out q = attach out p := ⟨p, rfl⟩ + rw [peer, dite_eq_left h, attach_inj out h.choose_spec] + +open scoped Classical in +theorem peer_involutive : Function.Involutive (peer out) := by + intro z + by_cases h : ∃ p, attach out p = z + · obtain ⟨p, rfl⟩ := h + rw [peer_attach, peer_attach, Bool.not_not] + · have he : peer out z = z := dite_eq_right h + rw [he, he] + +namespace Delivery +variable [Fintype P] {leaf : P → X} {point : U → Bool → P} {good : U → Prop} + {edge : U → W} {out} {l : P → ℝ} {u : ℝ} + (d : Delivery leaf point good edge outLeaf cap Y w out l u) + +open scoped Classical in +/-- The value specified by `(leaf (point q.val t), out _ (portOf leaf point good edge outLeaf +cap Y d.agree d.slot ⟨(q, t), rfl⟩))`. -/ +def plug (q : {i // good i}) (t : Bool) : X × Fin Y := + (leaf (point q.val t), out _ (portOf leaf point good edge outLeaf cap Y d.agree d.slot + ⟨(q, t), rfl⟩)) + +open scoped Classical in +private theorem plug_eq (q : {i // good i}) (t : Bool) : + d.plug q t = attach out (⟨edge q.val, d.slot q⟩, t) := + (attach_socket out (portOf leaf point good edge outLeaf cap Y d.agree d.slot + ⟨(q, t), rfl⟩)).symm + +open scoped Classical in +theorem peer_link (q : {i // good i}) (t : Bool) : + peer out (d.plug q t) = d.plug q (!t) := by rw [plug_eq, peer_attach, plug_eq] + +end Delivery + +variable {V A : Type} {h a : ℕ} {base : V → ℕ} {ends : A → Bool → V} + {hb : ∀ v, base v ≤ h} {capacity : A → ℝ} {lo : ∀ v, a ≤ base v} + {o : ∀ x, Slots (relBase a base) ends (relHi a hb) capacity Y x ↪ Fin Y} + [Fintype P] {leaf : P → Site V h} {point : U → Bool → P} {good : U → Prop} + {edge : U → Link base ends} {l : P → ℝ} {u : ℝ} + +open scoped Classical in +theorem Delivery.peer_relative + (d : Delivery leaf point good edge (Packing.outLeaf base ends hb) (fun z => capacity z.1) + Y w (liftSlots a lo o) l u) (q : {i // good i}) (t : Bool) : + peer o (Prod.map (Site.drop a) id (d.plug q t)) = + Prod.map (Site.drop a) id (d.plug q (!t)) := by + have he (t : Bool) : Prod.map (Site.drop a) id (d.plug q t) = + attach o (⟨dropContact a (edge q.val), d.slot q⟩, t) := by + let p := portOf leaf point good edge _ (fun z => capacity z.1) Y d.agree d.slot ⟨(q, t), rfl⟩ + exact (attach_socket o (dropSlot a lo _ p)).symm + rw [he, peer_attach, he] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/FieldLift.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/FieldLift.lean new file mode 100644 index 0000000000..31f19ce4c6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/FieldLift.lean @@ -0,0 +1,1005 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.ResetLocation +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.HostReset + +/-! +# Packing and matching one dyadic group + +Represent a colony by its host and dyadic interval. Each unit wire keeps +its block index, while its two hosts determine its two colonies. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V : Type} [Fintype V] {h : ℕ} + +namespace Grouping +variable {N C : V → Finset V} {Δ D k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) + +open scoped Classical in +/-- Decidable equality on the colonies used to index the lifted field records. -/ +local instance : DecidableEq g.Colony := Classical.typeDecidableEq _ + +variable {E : Type} [Fintype E] (src dst : E → V) (ix : E → Cell h) + +open scoped Classical in +theorem outgoing (u : ℝ) (hu : 0 ≤ u) + (hs : ∀ v x, u * (univ.filter fun e => src e = v ∧ ix e = x).card ≤ l v x) + (p : g.Colony) (x : Cell h) : + u * (univ.filter fun e => g.ends src ix e = p ∧ ix e = x).card ≤ l p.1 x := by + refine le_trans (mul_le_mul_of_nonneg_left (Nat.cast_le.mpr (card_le_card ?_)) hu) (hs _ _) + intro e he + obtain ⟨_, hp, hx⟩ := mem_filter.mp he + exact mem_filter.mpr ⟨mem_univ _, congrArg Sigma.fst hp, hx⟩ + +open scoped Classical in +theorem destinations (hd : ∀ e, dst e ∈ C (src e)) (p : g.Colony) : + ((univ.filter fun e => g.ends src ix e = p).image (g.ends dst ix)).card ≤ coreBins Δ := by + apply le_trans _ (g.bins p.1 p.2.val p.2.property) + rw [← card_sigma] + apply card_le_card_of_injOn (fun q : g.Colony => ⟨q.1, q.2.val⟩) + · intro q hq + obtain ⟨e, he, rfl⟩ := mem_image.mp hq + rw [← (mem_filter.mp he).2] + exact mem_sigma.mpr ⟨hd e, mem_image.mpr ⟨ix e, mem_filter.mpr ⟨mem_univ _, rfl⟩, rfl⟩⟩ + · rintro ⟨v, a⟩ _ ⟨w, b⟩ _ eq + obtain ⟨rfl, hab⟩ := Sigma.mk.inj eq + have he : a = b := Subtype.ext (eq_of_heq hab) + cases he + rfl + +open scoped Classical in +theorem card_bound : + (Fintype.card g.Colony : ℝ) ≤ + Fintype.card V + 16 * (∑ v, ∑ x, l v x) / ((2 : ℝ) ^ k * B) := by + simpa only [Colony, Fintype.card_sigma, Fintype.card_coe, Nat.cast_sum] using g.total + +end Grouping + +open scoped Classical in +/-- Pay for all core bins out of the total load and one allowance per host. -/ +theorem bin_charge {B S K P H L X Z σ : ℝ} + (hb : 0 < B) (hs : 0 < S) (hp : 0 ≤ P) (hz : 0 ≤ Z) (hσ : 0 ≤ σ) + (hk : 256 * (K + 1) ≤ S) (hh : S * B * H ≤ σ) + (hl : L ≤ 2 * (X + Z)) (hc : P ≤ H + 16 * L / (S * B)) : + B * (K + 1) * P ≤ X / 8 + (Z + σ) := by + have h₁ := mul_le_mul_of_nonneg_right hk (mul_nonneg hb.le hp) + have h₂ := (le_div_iff₀ (mul_pos hs hb)).mp (sub_le_iff_le_add'.mpr hc) + linarith + +open scoped Classical in +/-- A packing together with a compatible matching that internalizes at least +a quarter of the core width, less the tether and host allowances. -/ +theorem pack_subround {E : Type} [Fintype E] {k : ℕ} + (N C : V → Finset V) (Δ D : ℕ) (hΔ : 0 < Δ) (hD : 0 < D) + (eSym : ∀ v u, u ∈ N v → v ∈ N u) (cSym : ∀ v u, u ∈ C v → v ∈ C u) + (sub : ∀ v, C v ⊆ N v) (eDeg : ∀ v, (N v).card ≤ D) (cDeg : ∀ v, (C v).card ≤ Δ) + (hk : 1 ≤ k) (hkh : k ≤ h) (B : ℝ) (hB : 0 < B) + (l : V → Cell h → ℝ) (hl : ∀ v x, 0 ≤ l v x ∧ l v x ≤ B) + (src dst : E → V) (ix : E → Cell h) (u Z σ : ℝ) (hu : 0 < u) (hZ : 0 ≤ Z) + (hs : ∀ v x, u * (univ.filter fun e => src e = v ∧ ix e = x).card ≤ l v x) + (hd : ∀ e, dst e ∈ C (src e)) + (hbins : 256 * (coreBins Δ + 1) ≤ 2 ^ k) + (hhosts : (2 : ℝ) ^ k * B * Fintype.card V ≤ σ) + (hload : (∑ v, ∑ x, l v x) ≤ 2 * (u * Fintype.card E + Z)) : + ∃ (g : Grouping N C Δ D k B l) (m : Matching (g.ends src ix) (g.ends dst ix) ix), + u * Fintype.card E / 4 - (Z + σ) ≤ u * m.count := by + obtain ⟨g⟩ := pack_group N C Δ D hΔ hD eSym cSym sub eDeg cDeg hk hkh B hB l hl + obtain ⟨m, hm⟩ := subround (g.ends src ix) (g.ends dst ix) ix u B (coreBins Δ) hu hB.le + (fun p x => (g.outgoing src ix u hu.le hs p x).trans (hl p.1 x).2) + (g.destinations src dst ix hd) + have hb : (256 : ℝ) * (coreBins Δ + 1) ≤ 2 ^ k := by exact_mod_cast hbins + have hσ : 0 ≤ σ := le_trans (by positivity) hhosts + have hc := bin_charge hB (by positivity) (Nat.cast_nonneg _) hZ hσ hb hhosts hload g.card_bound + exact ⟨g, m, by linarith only [hc, hm]⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Charging the incidences of replacement wires + +Each gadget has fewer than `4*b` wires. Both ends of every wire are +charged to one of its four original endpoints. The matched pairs use +disjoint sets of original wires. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset Spectral.Tensor + +variable {V E : Type} [Fintype E] + +open scoped Classical in +private def weight (v x : V) : ℕ := if x = v then 1 else 0 + +namespace Grouping + +variable [Fintype V] {N C : V → Finset V} {Δ D h k : ℕ} + {B : ℝ} {l : V → Cell h → ℝ} (g : Grouping N C Δ D k B l) + {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + +open scoped Classical in +/-- The value specified by `(g.route m col (src e) (ix e), g.route m col (dst e) (ix e))`. -/ +def oldContact (col : Bool) (e : E) := + (g.route m col (src e) (ix e), g.route m col (dst e) (ix e)) + +open scoped Classical in +theorem contact_degree (b : ℕ) (f : m.items → Fin 8 → ℕ) + (hf : ∀ e, ∑ j, f e j < 4 * b) (col : Bool) (z : Site V h) : + degree (g.contact (b := b) (f := f) m col) z ≤ 8 * b * degree (g.oldContact m col) z := by + let old e := arityCost z (g.oldContact m col e) + let new (s : m.replaced b f) := arityCost z (g.contact m col s) + let wt := weight z + let mass e := old (m.mate e) + old e.val + have one (e : m.items) (i : Fin 6) : wt (g.party m col e i) ≤ mass e := by + have a : wt (g.party m col e 0) + wt (g.party m col e 1) + + (wt (g.party m col e 2) + wt (g.party m col e 3)) = mass e := rfl + have h₀ : wt (g.party m col e 0) ≤ mass e := by omega + have h₁ : wt (g.party m col e 1) ≤ mass e := by omega + have h₂ : wt (g.party m col e 2) ≤ mass e := by omega + have h₃ : wt (g.party m col e 3) ≤ mass e := by omega + fin_cases i + · exact h₀ + · exact h₁ + · exact h₂ + · exact h₃ + · cases col <;> assumption + · cases col <;> assumption + have gadget (e : m.items) : + (∑ j, ∑ i : Fin (f e j), new (.inl ⟨e, j, i⟩)) ≤ 8 * b * mass e := calc + _ ≤ ∑ j, ∑ _i : Fin (f e j), (mass e + mass e) := + sum_le_sum fun j _ => sum_le_sum fun i _ => + Nat.add_le_add (one e (sixPair j).1) (one e (sixPair j).2) + _ = (∑ j, f e j) * (mass e + mass e) := by simp [sum_mul] + _ ≤ 4 * b * (mass e + mass e) := Nat.mul_le_mul_right _ (hf e).le + _ = 8 * b * mass e := by ring + have unpaired (e : m.unpaired) : (∑ i : Fin b, new (.inr (e, i))) ≤ 8 * b * old e.val := by + change (∑ _i : Fin b, old e.val) ≤ _ + simpa using Nat.mul_le_mul_right (old e.val) (show b ≤ 8 * b by omega) + have split : (∑ e, old e) = (∑ e, mass e) + ∑ e : m.unpaired, old e.val := by + rw [← Equiv.sum_comp m.partition, Fintype.sum_sum_type, Fintype.sum_prod_type] + simp only [Fin.sum_univ_two] + rfl + rw [degree_sum, degree_sum] + change (∑ e, new e) ≤ 8 * b * (∑ e, old e) + rw [split, mul_add, mul_sum, mul_sum, Fintype.sum_sum_type, Fintype.sum_sigma, + Fintype.sum_prod_type] + simp_rw [Fintype.sum_sigma] + exact Nat.add_le_add (sum_le_sum fun e _ => gadget e) (sum_le_sum fun e _ => unpaired e) + +open scoped Classical in +/-- Each new wire has width `u / b`. Both endpoints count toward the load, +including two incidences at a common site when the wire is a loop. -/ +theorem contact_load (cs : ∀ v w, w ∈ C v → v ∈ C w) (sub : ∀ v, C v ⊆ N v) + (hedge : ∀ e, dst e ∈ C (src e)) (hl : ∀ v x, 0 ≤ l v x) (hB : 0 ≤ B) + (b : ℕ) (hb : 0 < b) (f : m.items → Fin 8 → ℕ) (hf : ∀ e, ∑ j, f e j < 4 * b) + (u : ℝ) (hu : 0 < u) + (hload : ∀ t : V × Cell h, + u * degree (fun e => ((src e, ix e), (dst e, ix e))) t ≤ l t.1 t.2) + (col : Bool) (z : Site V h) : + u / b * degree (g.contact (b := b) (f := f) m col) z ≤ + 8 * (near C Δ z).card * ((2 : ℝ) ^ k * B) := by + let pair (e : E) := ((src e, ix e), (dst e, ix e)) + let r (t : V × Cell h) := g.route m col t.1 t.2 + have hold : u * degree (g.oldContact m col) z ≤ (near C Δ z).card * ((2 : ℝ) ^ k * B) := by + refine le_trans ?_ (g.route_load m cs sub hedge hl hB col z) + change u * degree (fun e => Prod.map r r (pair e)) z ≤ _ + rw [degree_map, Nat.cast_sum, mul_sum] + apply sum_le_sum + intro t _ + by_cases htz : g.route m col t.1 t.2 = z + · simpa only [r, ite_eq_left htz] using hload t + · simp [r, htz] + have hb' : (0 : ℝ) < b := Nat.cast_pos.mpr hb + calc + _ ≤ u / b * (8 * b * degree (g.oldContact m col) z) := by + apply mul_le_mul_of_nonneg_left _ (div_nonneg hu.le hb'.le) + exact_mod_cast g.contact_degree m b f hf col z + _ = 8 * (u * degree (g.oldContact m col) z) := by + rw [← mul_assoc, mul_left_comm (u / _), div_mul_cancel₀ _ hb'.ne', mul_assoc] + _ ≤ _ := by + simpa only [mul_assoc] using mul_le_mul_of_nonneg_left hold (by norm_num : (0 : ℝ) ≤ 8) + +end Grouping +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Choosing the cheaper contraction before identifying any endpoints + +The profile alone gives two complementary upper bounds on the number +of crossings. Their comparison does not inspect the actual diagram. +Additional coincidences of endpoints can only reduce the chosen cost. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +open scoped Classical in +/-- The sum of `if c = decide (4 ≤ j.val) then 0 else f j` indexed by `j`. -/ +def profileScore (c : Bool) (f : Fin 8 → ℕ) := + ∑ j, if c = decide (4 ≤ j.val) then 0 else f j + +open scoped Classical in +theorem score_sum (f : Fin 8 → ℕ) : + profileScore true f + profileScore false f = ∑ j, f j := by + unfold profileScore + rw [← sum_add_distrib] + apply sum_congr rfl + intro j _ + cases decide (4 ≤ j.val) <;> simp + +open scoped Classical in +/-- Tests whether `(∑ i, profileScore true (f i)) < ∑ i, profileScore false (f i)` holds. -/ +def side {I : Type} [Fintype I] (f : I → Fin 8 → ℕ) : Bool := + decide ((∑ i, profileScore true (f i)) < ∑ i, profileScore false (f i)) + +open scoped Classical in +private theorem side_bound {I : Type} [Fintype I] (f : I → Fin 8 → ℕ) : + 2 * (∑ i, profileScore (side f) (f i)) ≤ ∑ i, ∑ j, f i j := by + simp_rw [← score_sum, sum_add_distrib] + unfold side + by_cases h : (∑ i, profileScore true (f i)) < ∑ i, profileScore false (f i) + · rw [decide_eq_true h]; omega + · rw [decide_eq_false h]; omega + +namespace Grouping + +variable {V E : Type} [Fintype V] [Fintype E] {N C : V → Finset V} {Δ D h k : ℕ} + {B : ℝ} {l : V → Cell h → ℝ} (g : Grouping N C Δ D k B l) + {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + +open scoped Classical in +theorem cross_side (b : ℕ) (f : m.items → Fin 8 → ℕ) (hf : ∀ e, ∑ j, f e j < 4 * b) : + 2 * Fintype.card {e : m.replaced b f // + (g.contact m (side f) e).1 ≠ (g.contact m (side f) e).2} + m.count ≤ + 2 * b * Fintype.card E := by + let col := side f + let cost (e : m.replaced b f) : ℕ := + if (g.contact m col e).1 ≠ (g.contact m col e).2 then 1 else 0 + have unit (e : m.replaced b f) : cost e ≤ 1 := by + unfold cost + split_ifs <;> omega + have first (e : m.items) (j : Fin 8) : + (∑ t : Fin (f e j), cost (.inl ⟨e, j, t⟩)) ≤ + if col = decide (4 ≤ j.val) then 0 else f e j := by + split_ifs with hc + · have he := g.party_closed m e j + rw [← hc] at he + have hz (t : Fin (f e j)) : cost (.inl ⟨e, j, t⟩) = 0 := ite_eq_right (not_not.mpr he) + simp only [hz, sum_const_zero, le_refl] + · simpa using sum_le_sum (s := univ) (fun t _ => unit (.inl ⟨e, j, t⟩)) + have bound : ∑ e, cost e ≤ (∑ e, profileScore col (f e)) + Fintype.card m.unpaired * b := by + rw [Fintype.sum_sum_type, Fintype.sum_sigma] + simp_rw [Fintype.sum_sigma] + apply Nat.add_le_add + · exact sum_le_sum fun e _ => sum_le_sum fun j _ => first e j + · simpa using sum_le_sum (s := univ) (fun e _ => unit (.inr e)) + have total : (∑ e, ∑ j, f e j) + m.count ≤ m.count * (4 * b) := by + have h := sum_le_sum (s := univ) (fun e _ => Nat.succ_le_of_lt (hf e)) + simpa only [Nat.succ_eq_add_one, sum_add_distrib, sum_const, card_univ, Nat.nsmul_eq_mul, + mul_one, m.card_items] using h + rw [Fintype.card_subtype, card_filter] + change 2 * (∑ e, cost e) + m.count ≤ _ + have hc := side_bound f + change 2 * (∑ e, profileScore col (f e)) ≤ _ at hc + calc + _ ≤ m.count * (4 * b) + 2 * (Fintype.card m.unpaired * b) := by omega + _ = _ := by rw [← m.card_partition]; ring + +open scoped Classical in +theorem cross_bound (b : ℕ) (f : m.items → Fin 8 → ℕ) (hf : ∀ e, ∑ j, f e j < 4 * b) : + ∃ col, 2 * Fintype.card {e : m.replaced b f // (g.contact m col e).1 ≠ (g.contact m col e).2} + + m.count ≤ 2 * b * Fintype.card E := + ⟨side f, g.cross_side m b f hf⟩ + +end Grouping +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Simultaneous replacement of matched bundles + +Each matched pair uses the same six-site identity, with its own +selector. Unmatched bundles pass through unchanged. The choices of +row or column contractions can be made after expanding this identity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Spectral Spectral.Tensor + +variable {V E : Type} [Fintype V] [Fintype E] {N C : V → Finset V} {Δ D h k : ℕ} + {B : ℝ} {l : V → Cell h → ℝ} (g : Grouping N C Δ D k B l) + {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + +namespace Grouping + +open Classical in +/-- Indexes the parties by the coordinates of `(Σ _ : m.items, Fin 6) ⊕ (V × Cell h)`. -/ +abbrev Parties := (Σ _ : m.items, Fin 6) ⊕ (V × Cell h) + +open Classical in +/-- In the case `.inl ⟨e, j⟩`, this construction gives `g.party m col e j`. -/ +def locate (col : Bool) : g.Parties m → Site V h + | .inl ⟨e, j⟩ => g.party m col e j + | .inr (v, x) => g.route m col v x + +open Classical in +/-- Indexes the demand by the coordinates of `(Σ _ : m.items, Fin 2 × Fin b) ⊕ (m.unpaired × Fin +b)`. -/ +abbrev Demand (b : ℕ) := (Σ _ : m.items, Fin 2 × Fin b) ⊕ (m.unpaired × Fin b) + +open Classical in +/-- Reindexes `Demand g m b` and `E × Fin b` by an equivalence. -/ +def demandIndex (b : ℕ) : Demand g m b ≃ E × Fin b := + (((((Equiv.sigmaEquivProd _ _).trans (Equiv.prodAssoc _ _ _).symm).sumCongr (.refl _)).trans + (Equiv.sumProdDistrib _ _ _).symm).trans (m.partition.prodCongr (.refl _))) + +open Classical in +/-- The value specified by `((src e.1.val, ix e.1.val), (dst e.1.val, ix e.1.val))`. -/ +def untouched {b : ℕ} (e : m.unpaired × Fin b) : (V × Cell h) × (V × Cell h) := + ((src e.1.val, ix e.1.val), (dst e.1.val, ix e.1.val)) + +open Classical in +/-- The indexed operation `Packet.together (Packet.parallelDemand (fun _ e => sixDemandPair +e.1)) (untouched g m)`. -/ +def demand0 {b : ℕ} : Demand g m b → g.Parties m × g.Parties m := + Packet.together (Packet.parallelDemand (fun _ e => sixDemandPair e.1)) (untouched g m) + +open Classical in +/-- The value specified by `demand0 g m ∘ (demandIndex g m b).symm`. -/ +def demand {b : ℕ} : E × Fin b → g.Parties m × g.Parties m := + demand0 g m ∘ (demandIndex g m b).symm + +open Classical in +theorem locate_demand {b : ℕ} (col : Bool) (e : E × Fin b) : + Prod.map (g.locate m col) (g.locate m col) (g.demand m e) = + (g.route m col (src e.1) (ix e.1), g.route m col (dst e.1) (ix e.1)) := by + obtain ⟨q, rfl⟩ := (demandIndex g m b).surjective e + rw [demand, Function.comp_apply, Equiv.symm_apply_apply] + rcases q with ⟨q, j, t⟩|⟨q, t⟩ + · exact congrArg (Prod.map (fun p => g.route m col p.1 p.2) + (fun p => g.route m col p.1 p.2)) (g.rep_demand m col q j) + · rfl + +open Classical in +/-- Indexes the selector by the coordinates of `m.items → Fin A × ↥H`. -/ +abbrev Selector (A : ℕ) (H : Finset (Fin 8 → ℕ)) := m.items → Fin A × ↥H + +open Classical in +/-- The value specified by `(i v).2.val`. -/ +def profile {A H} (i : g.Selector m A H) (v : m.items) : Fin 8 → ℕ := (i v).2.val + +open Classical in +/-- In the case `.inl ⟨e, j, _⟩`, this construction gives `(.inl ⟨e, (sixPair j).1⟩, .inl ⟨e, +(sixPair j).2⟩)`. -/ +def supplies {b : ℕ} {f : m.items → Fin 8 → ℕ} : m.replaced b f → g.Parties m × g.Parties m + | .inl ⟨e, j, _⟩ => (.inl ⟨e, (sixPair j).1⟩, .inl ⟨e, (sixPair j).2⟩) + | .inr t => (.inr (untouched g m t).1, .inr (untouched g m t).2) + +omit [Fintype E] in +open Classical in +theorem locate_supply {b : ℕ} {f : m.items → Fin 8 → ℕ} (col : Bool) (e : m.replaced b f) : + Prod.map (g.locate m col) (g.locate m col) (g.supplies m e) = g.contact m col e := by + rcases e with ⟨q, j, t⟩|⟨q, t⟩ <;> rfl + +open Classical in +/-- Reindexes `(m.replaced b f × Fin z)` and `m.replaced (b * z) (fun q j => f q j * z)` by an +equivalence. -/ +def supplyIndex (b z : ℕ) (f : m.items → Fin 8 → ℕ) : + (m.replaced b f × Fin z) ≃ m.replaced (b * z) (fun q j => f q j * z) := + (Equiv.sumProdDistrib _ _ _).trans <| Equiv.sumCongr + ((Equiv.sigmaProdDistrib _ _).trans <| Equiv.sigmaCongrRight fun _ => + (Equiv.sigmaProdDistrib _ _).trans <| Equiv.sigmaCongrRight fun _ => finProdFinEquiv) + ((Equiv.prodAssoc _ _ _).trans ((Equiv.refl _).prodCongr finProdFinEquiv)) + +open Classical in +/-- A profile of each selector counts sub-bundles of width `z`. -/ +def wireRule {K : Type} [Field K] {b z A : ℕ} {H : Finset (Fin 8 → ℕ)} + (P : Packet.Rule K (fun e : Fin 2 × Fin (b * z) => sixDemandPair e.1) + (fun i : Fin A × ↥H => fun e : Σ j : Fin 8, Fin (i.2.1 j * z) => sixPair e.1)) : + Packet.Rule K (g.demand (b := b * z) m) + (fun i : g.Selector m A H => fun e : m.replaced b (g.profile m i) × Fin z => + g.supplies m e.1) := by + let all := (Packet.Rule.parallel (fun _ : m.items => P)).keep (untouched g m (b := b * z)) + let old := all.reindex (demandIndex g m (b * z)).symm + let new := old.suppliesEquiv (fun i => supplyIndex g m b z (g.profile m i)) + refine new.congr rfl ?_ + funext i e + rcases e with ⟨⟨e, j, s⟩|⟨e, s⟩, t⟩ <;> rfl + +open Classical in +theorem wireIdentity {K : Type} [Field K] {b z A : ℕ} {H : Finset (Fin 8 → ℕ)} + (P : Packet K (fun e : Fin 2 × Fin (b * z) => sixDemandPair e.1) + (fun i : Fin A × ↥H => fun e : Σ j : Fin 8, Fin (i.2.1 j * z) => sixPair e.1)) : + Packet K (g.demand (b := b * z) m) + (fun i : g.Selector m A H => fun e : m.replaced b (g.profile m i) × Fin z => + g.supplies m e.1) := + (g.wireRule m P.rule).packet + +end Grouping +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Contracting a matched subround + +On the core diagram, tether ends are named exterior wires. The selector +determines which layout to contract. Every surviving bundle still has +exactly `z` bits and the sum of the diagrams is the unmodified tensor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Spectral + +open Classical in +/-- Fixed independently of the subdivision width. -/ +structure Gadget (F : Type) [Field F] where + /-- The right component. -/ + b : ℕ + /-- Stores the copies associated with this `Gadget`. -/ + copies : ℕ + /-- The `Gadget` component of type `Finset (Fin 8 → ℕ)`. -/ + shapes : Finset (Fin 8 → ℕ) + pos : 0 < b + cost : ∀ f ∈ shapes, ∑ j, f j < 4 * b + packet : ∀ z : ℕ, 0 < z → + Packet F (fun e : Fin 2 × Fin (b * z) => Tensor.sixDemandPair e.1) + (fun i : Fin copies × ↥shapes => fun e : Σ j : Fin 8, Fin (i.2.1 j * z) => Tensor.sixPair e.1) + +open Classical in +theorem gadget_exists (F : Type) [Field F] : Nonempty (Gadget F) := + let ⟨b, c, H, hb, hc, h⟩ := Tensor.six_packets F + ⟨⟨b, c, H, hb, hc, h⟩⟩ + +variable {F V E : Type} [Field F] [Fintype V] [Fintype E] {a b : Wire} + {N C : V → Finset V} {Δ D h k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (P : Gadget F) (G : Diagram F a b) (z : ℕ) + +namespace Grouping + +open Classical in +/-- Computes the choice by the application `g.Selector m P.copies P.shapes`. -/ +abbrev Choice := g.Selector m P.copies P.shapes + +open Classical in +/-- Computes the supply by the application `m.replaced P.b (g.profile m i)`. -/ +abbrev Supply (i : g.Choice m P) := m.replaced P.b (g.profile m i) + +open Classical in +/-- The subtype of `e : g.Supply m P i` satisfying `(g.contact m c e).1 ≠ (g.contact m c e).2`. -/ +abbrev Crossing (i : g.Choice m P) (c : Bool) := + {e : g.Supply m P i // (g.contact m c e).1 ≠ (g.contact m c e).2} + +open Classical in +/-- Computes the layout by the application `side (g.profile m i)`. -/ +def layout (i : g.Choice m P) := side (g.profile m i) + +open Classical in +/-- Computes the survivors by the application `g.Crossing m P i (g.layout m P i)`. -/ +abbrev Survivors (i : g.Choice m P) := g.Crossing m P i (g.layout m P i) + +open Classical in +/-- Computes the ends' by the application `g.contact m (g.layout m P i) e.1`. -/ +def ends' (i : g.Choice m P) (e : g.Survivors m P i) : Site V h × Site V h := + g.contact m (g.layout m P i) e.1 + +variable {G z} +variable (s : Bundles G src dst ix (P.b * z)) (hz : 0 < z) + +open Classical in +/-- Computes the assign by the application `g.route m (g.layout m P i) (s.place v).1 (s.place +v).2`. -/ +def assign (i : g.Choice m P) (v : G.V) := + g.route m (g.layout m P i) (s.place v).1 (s.place v).2 + +open Classical in +/-- Computes the station by the application `g.locate m (g.layout m P i)`. -/ +def station (i : g.Choice m P) := g.locate m (g.layout m P i) + +open Classical in +theorem aligned : + G.Aligned (g.assign m P s) (g.station m P) (g.demand m ∘ s.bits) := by + intro i e + have := g.locate_demand m (g.layout m P i) (s.bits e) + simp only [assign, s.left, s.right, station, Function.comp_apply] + exact ⟨(congrArg Prod.fst this).symm, (congrArg Prod.snd this).symm⟩ + +open Classical in +/-- The value specified by `(g.wireRule m (P.packet z hz).rule).reindex s.bits`. -/ +abbrev expansion := (g.wireRule m (P.packet z hz).rule).reindex s.bits + +open Classical in +/-- Computes the contract by the application `G.replaced (g.expansion m P s hz) (g.assign m P s) +(g.station m P) i`. -/ +abbrev contract (i : g.Choice m P) := + G.replaced (g.expansion m P s hz) (g.assign m P s) (g.station m P) i + +open Classical in +theorem eval_contract (x : Val a) (y : Val b) : + ∑ i, (g.contract m P s hz i).eval x y = G.eval x y := + G.eval_replaced _ _ _ x y + +open Classical in +theorem bound_survivors (i : g.Choice m P) : + 2 * Fintype.card (g.Survivors m P i) + m.count ≤ 2 * P.b * Fintype.card E := + g.cross_side m P.b (g.profile m i) (fun t => P.cost _ (i t).2.property) + +open Classical in +/-- Computes the supply end by the application `g.supplies m e.1`. -/ +abbrev SupplyEnd (i : g.Choice m P) (e : g.Supply m P i × Fin z) := + g.supplies m e.1 + +open Classical in +theorem across (i : g.Choice m P) (e : g.Supply m P i) : + (g.contact m (g.layout m P i) e).1 ≠ (g.contact m (g.layout m P i) e).2 ↔ + g.station m P i (g.supplies m e).1 ≠ g.station m P i (g.supplies m e).2 := by + rw [← g.locate_supply m (g.layout m P i)] + rfl + +open Classical in +/-- Reindexes `g.Survivors m P i × Fin z` and `Diagram.Cut (W := g.SupplyEnd m P (z := z)) +(g.station m P) i where toFun e` by an equivalence. -/ +def crossingIndex (i : g.Choice m P) : + g.Survivors m P i × Fin z ≃ Diagram.Cut (W := g.SupplyEnd m P (z := z)) (g.station m P) i where + toFun e := ⟨(e.1.val, e.2), (g.across m P i _).mp e.1.property⟩ + invFun e := (⟨e.val.1, (g.across m P i _).mpr e.property⟩, e.val.2) + left_inv _ := rfl + right_inv _ := rfl + +open Classical in +/-- Reindexes `g.Survivors m P i × Fin z` and `(g.contract m P s hz i).E` by an equivalence. -/ +def remaining (i : g.Choice m P) : + g.Survivors m P i × Fin z ≃ (g.contract m P s hz i).E := + (g.crossingIndex m P i).trans + (G.cutEdges (g.expansion m P s hz) _ _ (g.aligned m P s) i) + +open Classical in +theorem contact_contract (i : g.Choice m P) (t : g.Survivors m P i × Fin z) : + ((g.contract m P s hz i).source (g.remaining m P s hz i t), + (g.contract m P s hz i).target (g.remaining m P s hz i t)) = g.ends' m P i t.1 := + g.locate_supply m (g.layout m P i) t.1.val + +open Classical in +/-- The saving counts individual wire bits, even though matching was +performed on whole bundles. -/ +theorem width_contract (i : g.Choice m P) : + 2 * Fintype.card (g.contract m P s hz i).E + m.count * z ≤ 2 * Fintype.card G.E := by + rw [← Fintype.card_congr (g.remaining m P s hz i), Fintype.card_congr s.bits] + simp only [Fintype.card_prod, Fintype.card_fin] + have ht := Nat.mul_le_mul_right z (g.bound_survivors m P i) + rw [add_mul, mul_assoc 2] at ht + rw [show 2 * P.b * Fintype.card E * z = 2 * (Fintype.card E * (P.b * z)) by ring] at ht + exact ht + +open Classical in +theorem contraction (i : g.Choice m P) {Z : ℝ} (hZ : 0 ≤ Z) + (matched : (P.b * z : ℕ) * (Fintype.card E : ℝ) / 4 - Z ≤ (P.b * z : ℕ) * (m.count : ℝ)) : + (Fintype.card (g.contract m P s hz i).E : ℝ) ≤ + (1 - 1 / (8 * (P.b : ℝ))) * Fintype.card G.E + Z := by + have hw : 2 * (Fintype.card (g.contract m P s hz i).E : ℝ) + m.count * (z : ℝ) ≤ + 2 * (Fintype.card G.E : ℝ) := by exact_mod_cast g.width_contract m P s hz i + have hb : 1 ≤ (P.b : ℝ) := by exact_mod_cast P.pos + have hn : Fintype.card G.E = Fintype.card E * (P.b * z) := by + simpa using Fintype.card_congr s.bits + have hm : (Fintype.card G.E : ℝ) / (8 * (P.b : ℝ)) ≤ m.count * (z : ℝ) / 2 + Z := by + apply (div_le_iff₀ (by positivity)).mpr + rw [hn] + push_cast at matched ⊢ + nlinarith only [matched, mul_le_mul_of_nonneg_right hb hZ, hZ] + rw [sub_mul, one_mul, one_div_mul_eq_div] + linarith only [hw, hm] + +open Classical in +theorem input_contract (i : g.Choice m P) (t : slots a) : + ((g.contract m P s hz i).src.symm (.inl t)).1 = g.assign m P s i (G.src.symm (.inl t)).1 := rfl + +open Classical in +theorem output_contract (i : g.Choice m P) (t : slots b) : + ((g.contract m P s hz i).dst.symm (.inl t)).1 = g.assign m P s i (G.dst.symm (.inl t)).1 := rfl + +open Classical in +theorem arity_contract (i : g.Choice m P) (v : Site V h) : + (g.contract m P s hz i).arity v ≤ exterior G (g.assign m P s i) v + + degree (g.contact (b := P.b) (f := g.profile m i) m (g.layout m P i)) v * z := by + let col := g.layout m P i + let edge := g.contact (b := P.b) (f := g.profile m i) m col + let f (e : g.Supply m P i × Fin z) := + Prod.map (g.station m P i) (g.station m P i) (g.supplies m e.1) + have eqn : f = fun e => edge e.1 := funext fun e => g.locate_supply m col e.1 + have ht := G.arity_replaced (g.expansion m P s hz) (g.assign m P s) (g.station m P) + (g.aligned m P s) i v + change (g.contract m P s hz i).arity v ≤ exterior G (g.assign m P s i) v + degree f v at ht + rwa [eqn, degree_bundle] at ht + +open Classical in +theorem load_contract (cs : ∀ v w, w ∈ C v → v ∈ C w) (sub : ∀ v, C v ⊆ N v) + (hedge : ∀ e, dst e ∈ C (src e)) (hl : ∀ v x, 0 ≤ l v x) (hB : 0 ≤ B) + (hi : ∀ t : V × Cell h, + (P.b * z : ℕ) * (degree (fun e => ((src e, ix e), (dst e, ix e))) t : ℝ) ≤ l t.1 t.2) + (he : ∀ t, (exterior G s.place t : ℝ) ≤ l t.1 t.2) + (i : g.Choice m P) (v : Site V h) : + ((g.contract m P s hz i).arity v : ℝ) ≤ 9 * (near C Δ v).card * ((2 : ℝ) ^ k * B) := by + let col := g.layout m P i + let f (t : V × Cell h) := g.route m col t.1 t.2 + have h₁ : (exterior G (g.assign m P s i) v : ℝ) ≤ (near C Δ v).card * ((2 : ℝ) ^ k * B) := by + change (exterior G (f ∘ s.place) v : ℝ) ≤ _ + rw [exterior_comp] + refine le_trans ?_ (g.route_load m cs sub hedge hl hB col v) + exact Finset.sum_le_sum fun t _ => by split_ifs <;> first | exact he t | exact le_rfl + have hb : 0 < (P.b : ℝ) := Nat.cast_pos.mpr P.pos + have h₂ := g.contact_load m cs sub hedge hl hB P.b P.pos (g.profile m i) + (fun t => P.cost _ (i t).2.property) (P.b * z : ℕ) (Nat.cast_pos.mpr (Nat.mul_pos P.pos hz)) + hi col v + rw [Nat.cast_mul, mul_div_cancel_left₀ _ hb.ne'] at h₂ + have ht := (Nat.cast_le (α := ℝ)).mpr (g.arity_contract m P s hz i v) + rw [Nat.cast_add, Nat.cast_mul] at ht + dsimp only [col] at h₂ + linarith only [ht, h₁, h₂] + +end Grouping +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Contracting on a projected host + +Surviving core bundles have both ends in one group. Reassign tether +ends and frozen charges by the same layout, keeping their names intact. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet + +open Finset + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} + {h a z Δ D k : ℕ} {B : ℝ} {P : Gadget F} {G : HostNet F L h (P.b * z)} + (s : G.Projection Δ D a) (g : Grouping G.N G.C Δ D k B G.load) + (m : Matching (g.ends G.src G.ix) (g.ends G.dst G.ix) G.ix) + (hz : 0 < z) (hle : Δ ≤ D) (i : g.Choice m P) + +open scoped Classical in +theorem keep (col : Bool) (v : G.V) (t : Cell h) : + s.frozen (s.place (g.route m col v t)).1 ↔ G.frozen v := by + rw [s.keep] + rcases g.route_cases m col v t with he | ⟨e, he, _, _, ht⟩ + · rw [he]; rfl + · rw [ht, ← he] + exact iff_of_false (G.core (m.mate e)).2 (G.core e.val).1 + +open scoped Classical in +theorem active (col : Bool) (e : m.items) (j : Fin 6) : + ¬s.frozen (s.place (g.party m col e j)).1 := by + unfold Grouping.party + rw [keep] + obtain ⟨h₁, h₂⟩ := G.core (m.mate e) + obtain ⟨h₃, h₄⟩ := G.core e.val + fin_cases j + · exact h₁ + · exact h₂ + · exact h₃ + · exact h₄ + · cases col <;> assumption + · cases col <;> assumption + +open scoped Classical in +theorem surviving (e : g.Survivors m P i) : + let t := g.ends' m P i e + (s.place t.1).2 = (s.place t.2).2 ∧ (s.place t.2).1 ∈ s.C (s.place t.1).1 := + s.core _ _ (g.contact_mem m G.cs G.sub G.edge _ e.val) + +open scoped Classical in +/-- Computes the assignment by the application `s.place (g.route m (g.layout m P i) p.1 p.2)`. -/ +def assignment (p : G.V × Cell h) : s.W × Cell a := + s.place (g.route m (g.layout m P i) p.1 p.2) + +open scoped Classical in +theorem port_contract (q : slots x ⊕ slots y) : + s.place (portEnd (g.contract m P G.units hz i) q) = + assignment s g m i (G.units.place (portEnd G.diagram q)) := by + cases q <;> rfl + +open scoped Classical in +/-- Builds `HostNet F L a z where diagram` with the specified `diagram`, `src`, `dst`, `ix`. -/ +def contracted : HostNet F L a z where + diagram := g.contract m P G.units hz i + V := s.W + E := g.Survivors m P i + src e := (s.place (g.ends' m P i e).1).1 + dst e := (s.place (g.ends' m P i e).2).1 + ix e := (s.place (g.ends' m P i e).1).2 + units := { + place := s.place + bits := (g.remaining m P G.units hz i).symm + left e := by + obtain ⟨p, rfl⟩ := (g.remaining m P G.units hz i).surjective e + rw [Equiv.symm_apply_apply] + exact congrArg (fun q => s.place q.1) (g.contact_contract m P G.units hz i p) + right e := by + obtain ⟨p, rfl⟩ := (g.remaining m P G.units hz i).surjective e + rw [Equiv.symm_apply_apply, (surviving s g m i p.1).1] + exact congrArg (fun q => s.place q.2) (g.contact_contract m P G.units hz i p) } + past := G.carried (assignment s g m i) + park := assignment s g m i ∘ G.park + frozen := s.frozen + N := s.N + C := s.C + ns := s.ns + cs := s.cs + sub := s.sub + kept t := (keep s g m _ _ _).mpr (G.kept t) + core e := by + change ¬s.frozen (s.place (g.contact m _ e.val).1).1 ∧ + ¬s.frozen (s.place (g.contact m _ e.val).2).1 + rcases e with ⟨⟨e, j, t⟩ | ⟨e, t⟩, _⟩ + · exact ⟨active s g m _ e _, active s g m _ e _⟩ + · exact ⟨mt (keep s g m _ _ _).mp (G.core e.val).1, + mt (keep s g m _ _ _).mp (G.core e.val).2⟩ + edge e := (surviving s g m i e).2 + tether q := by + obtain ⟨hc, hi, he⟩ := G.tether q + dsimp only + rw [port_contract] + refine ⟨mt (keep s g m _ _ _).mp hc, ?_⟩ + unfold assignment + simp only [Function.comp_apply, ← hi] + exact s.full _ _ (g.contact_full m G.cs G.sub G.edge G.ns hle _ he _) + +open scoped Classical in +theorem contracted_X : (contracted s g m hz hle i).X = + Fintype.card (g.contract m P G.units hz i).E := by + rw [← Fintype.card_congr (g.remaining m P G.units hz i), Fintype.card_prod, Fintype.card_fin] + rfl + +open scoped Classical in +theorem choice_card : + Fintype.card (g.Choice m P) ≤ (P.copies * P.shapes.card + 1) ^ (Fintype.card G.E) := by + have hm : Fintype.card m.items ≤ Fintype.card G.E := Fintype.card_subtype_le _ + change Fintype.card (m.items → Fin P.copies × ↥P.shapes) ≤ _ + rw [Fintype.card_fun, Fintype.card_prod, + Fintype.card_fin, Fintype.card_coe] + exact (Nat.pow_le_pow_left (Nat.le_succ _) _).trans (Nat.pow_le_pow_right (by omega) hm) + +open scoped Classical in +theorem contracted_load (hB : 0 ≤ B) (p : Site G.V h) : + (contracted s g m hz hle i).load (s.place p).1 (s.place p).2 ≤ + 9 * (near G.C Δ p).card * ((2 : ℝ) ^ k * B) := by + let Q := contracted s g m hz hle i + let c := g.layout m P i + let r := assignment s g m i + have outside := G.reassign Q r rfl (port_contract s g m hz i) rfl (s.place p) + have hr : push r (Function.uncurry G.load) (s.place p) ≤ + (near G.C Δ p).card * ((2 : ℝ) ^ k * B) := by + have he := g.route_load m G.cs G.sub G.edge G.load_nonneg hB c p + simpa only [push, r, assignment, s.place.injective.eq_iff, c, Function.uncurry_def] using he + let edge := g.contact (b := P.b) (f := g.profile m i) m c + let emb : g.Survivors m P i ↪ g.Supply m P i := ⟨Subtype.val, Subtype.val_injective⟩ + have eqn : (Q.pair : g.Survivors m P i → _) = + fun e => Prod.map s.place s.place ((edge ∘ emb) e) := by + funext e + apply Prod.ext + · rfl + · exact Prod.ext rfl (surviving s g m i e).1 + have hd : degree Q.pair (s.place p) ≤ degree edge p := by + rw [eqn] + change degree (fun e => Prod.map s.place s.place ((edge ∘ emb) e)) (s.place p) ≤ degree edge p + rw [degree_map (edge ∘ emb) s.place] + simpa only [s.place.injective.eq_iff, sum_ite_eq', mem_univ, ite_true] + using degree_select edge emb p + have hi (t : G.V × Cell h) : ((P.b * z : ℕ) : ℝ) * degree G.pair t ≤ G.load t.1 t.2 := by + rw [mul_comm] + exact (le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load t.1 t.2) + have ht := g.contact_load m G.cs G.sub G.edge G.load_nonneg hB P.b P.pos (g.profile m i) + (fun t => P.cost _ (i t).2.property) (P.b * z : ℕ) (Nat.cast_pos.mpr (Nat.mul_pos P.pos hz)) + hi c p + rw [Nat.cast_mul, mul_div_cancel_left₀ _ (Nat.cast_ne_zero.mpr P.pos.ne')] at ht + have cost := mul_le_mul_of_nonneg_right ((Nat.cast_le (α := ℝ)).mpr hd) (Nat.cast_nonneg z) + change Q.load _ _ ≤ _ + change z * (degree edge p : ℝ) ≤ _ at ht + rw [mul_comm (z : ℝ)] at ht + exact (outside.trans (add_le_add hr (cost.trans ht))).trans_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- +# Simultaneous contraction of dyadic groups + +Treat the group prefix as an extra host coordinate while packing. +Projection then returns that prefix to the block index. The resulting +host bounds are independent of the number of groups. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet + +open Finset + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {L : Fringe x y T} + {h u z : ℕ} + +omit [Field F] in +open scoped Classical in +theorem outgoing (G : HostNet F L h u) (v : G.V) (i : Cell h) : + (u : ℝ) * (univ.filter fun e => G.src e = v ∧ G.ix e = i).card ≤ G.load v i := by + have count : (univ.filter fun e => G.src e = v ∧ G.ix e = i).card ≤ degree G.pair (v, i) := by + unfold degree + apply le_trans _ (Nat.le_add_right _ _) + simp [Fintype.card_subtype, pair] + rw [mul_comm] + exact (mul_le_mul_of_nonneg_right (Nat.cast_le.mpr count) (Nat.cast_nonneg _)).trans + ((le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load v i)) + +omit [Field F] [Fintype T] in +open scoped Classical in +theorem diagram_width (G : HostNet F L h u) : Fintype.card G.diagram.E = G.X := by + simpa [X] using Fintype.card_congr G.units.bits + +open scoped Classical in +theorem projected_bounds (P : Gadget F) (G : HostNet F L h (P.b * z)) (hz : 0 < z) + (a k Δ D : ℕ) (hΔ : 0 < Δ) (hle : Δ ≤ D) (ah : a ≤ h) + (B σ : ℝ) (hB : 0 ≤ B) (hσ : 0 ≤ σ) (bounds : G.Bounded Δ D B) + (g : Grouping (inGroup a G.N) (inGroup a G.C) Δ D k B (G.regroup a ah).load) + (m : Matching (g.ends (G.regroup a ah).src (G.regroup a ah).ix) + (g.ends (G.regroup a ah).dst (G.regroup a ah).ix) (G.regroup a ah).ix) + (matched : (G.X : ℝ) / 4 - (L.Z + σ) ≤ (P.b * z : ℕ) * (m.count : ℝ)) (i : g.Choice m P) : + let q := contracted (G.project a ah Δ D hle) g m hz hle + Fintype.card (q i).V ≤ 2 * 2 ^ (h - a) * Fintype.card G.V ∧ + (q i).Bounded ((4 * Δ) ^ 900) ((4 * D) ^ 900) (9 * ((4 * Δ) ^ 300 : ℕ) * ((2 : ℝ) ^ k * B)) + ∧ + ((q i).X : ℝ) ≤ (1 - 1 / (8 * (P.b : ℝ))) * G.X + (L.Z + σ) ∧ + G.Preserves (q i) ∧ (q i).mass = G.mass + 2 * G.X ∧ G.Tracks (q i) ((Δ + 1) * 2) := by + let H := G.regroup a ah + have hb := G.regroup_bounded a ah bounds + let s : H.Projection Δ D a := G.project a ah Δ D hle + let q := contracted s g m hz hle + refine ⟨Site.card _ _, ?_, ?_, ?_, ?_, ?_⟩ + · refine ⟨cube_near_card G.C Δ hΔ bounds.1, cube_near_card G.N D (hΔ.trans_le hle) bounds.2.1, + fun v x => ?_⟩ + obtain ⟨p, he⟩ := s.place.surjective (v, x) + have ht := contracted_load s g m hz hle i hB p + rw [he] at ht + refine ht.trans (mul_le_mul_of_nonneg_right ?_ (by positivity)) + exact mul_le_mul_of_nonneg_left (Nat.cast_le.mpr (near_card H.C Δ hΔ hb.1 p)) (by norm_num) + · have ht := g.contraction m P H.units hz i (add_nonneg L.total_nonneg hσ) (by + have he : Fintype.card (G.regroup a ah).E = Fintype.card G.E := rfl + simpa only [X, Nat.cast_mul, he, mul_comm (Fintype.card G.E : ℝ)] using matched) + erw [H.diagram_width, ← contracted_X s g m hz hle i] at ht + exact ht + · refine ⟨assignment s g m i ∘ splitAddr G.V a ah, rfl, port_contract s g m hz i, + ⟨prefixMap ah, prefixMap_onto ah, ?_⟩, + Σ d : Fin (h - a + 1), Cell d.val, inferInstance, Equiv.refl _, ?_⟩ + · intro q + let t := splitAddr G.V a ah q + have near := g.route_near m H.cs H.sub H.edge (g.layout m P i) t.1 t.2 + exact (split_near G.C Δ near).1.symm + · intro j + let t := H.park j + change (g.route m (g.layout m P i) t.1 t.2).1.1 = _ + rcases g.route_cases m (g.layout m P i) t.1 t.2 with he | ⟨e, he, _⟩ + · rw [he]; rfl + · exact ((H.core e.val).1 (he.symm ▸ H.kept j)).elim + · have hc := H.carry_sum (assignment s g m i) + rw [regroup_mass, regroup_X] at hc + exact hc + · let f : (q i).V ≃ G.V × (Σ j : Fin (h - a + 1), Cell j.val) := Equiv.refl _ + refine tracks_of_slots f (fun v => insert v (G.C v)) ?_ ?_ (by norm_num) + (Site.card _ _) ?_ + · intro u v he + rcases Finset.mem_insert.mp he with rfl | he + · exact Finset.mem_insert_self _ _ + · exact Finset.mem_insert_of_mem (G.cs _ _ he) + · exact fun v => (Finset.card_insert_le _ _).trans (Nat.add_le_add_right (bounds.1 v) _) + · intro j + let t := H.units.place (portEnd H.diagram j) + have he := (mem_near _ _ _ _).mp (g.route_near m H.cs H.sub H.edge (g.layout m P i) t.1 t.2) + unfold tip + rw [show (q i).units.place (portEnd (q i).diagram j) = _ from port_contract s g m hz i j] + change (g.route m (g.layout m P i) t.1 t.2).1.1 ∈ insert t.1.1 (G.C t.1.1) + rcases he with he | he + · rw [he]; exact Finset.mem_insert_self _ _ + · exact Finset.mem_insert_of_mem ((mem_inGroup _ _ _ _).mp he.1).1 + +open scoped Classical in +theorem subround (P : Gadget F) (G : HostNet F L h (P.b * z)) (hz : 0 < z) + (a k Δ D : ℕ) (hΔ : 0 < Δ) (hle : Δ ≤ D) (hk : 1 ≤ k) (ha : a + k ≤ h) + (B σ : ℝ) (hB : 0 < B) (bounds : G.Bounded Δ D B) + (hbins : 256 * (coreBins Δ + 1) ≤ 2 ^ k) + (slack : (2 : ℝ) ^ k * B * (Fintype.card G.V * 2 ^ a : ℕ) ≤ σ) : + ∃ (I : Type) (_ : Fintype I) (q : I → HostNet F L a z), + Fintype.card I ≤ (P.copies * P.shapes.card + 1) ^ (Fintype.card G.E) ∧ + (∀ x y, ∑ i, (q i).diagram.eval x y = G.diagram.eval x y) ∧ + ∀ i, Fintype.card (q i).V ≤ 2 * 2 ^ (h - a) * Fintype.card G.V ∧ + (q i).Bounded ((4 * Δ) ^ 900) ((4 * D) ^ 900) (9 * ((4 * Δ) ^ 300 : ℕ) * ((2 : ℝ) ^ k * B)) + ∧ + ((q i).X : ℝ) ≤ (1 - 1 / (8 * (P.b : ℝ))) * G.X + (L.Z + σ) ∧ + G.Preserves (q i) ∧ (q i).mass = G.mass + 2 * G.X ∧ G.Tracks (q i) ((Δ + 1) * 2) := by + have ah : a ≤ h := by omega + let H := G.regroup a ah + have hb : H.Bounded Δ D B := G.regroup_bounded a ah bounds + have hs : (2 : ℝ) ^ k * B * Fintype.card H.V ≤ σ := by + change (2 : ℝ) ^ k * B * Fintype.card (G.V × Cell a) ≤ σ + rwa [Fintype.card_prod, card_cell] + have hm : (∑ v, ∑ i, H.load v i) ≤ 2 * ((P.b * z : ℕ) * (Fintype.card H.E : ℝ) + L.Z) := by + simpa only [X, Nat.cast_mul, mul_add, mul_comm (Fintype.card H.E : ℝ)] using H.sum_load + obtain ⟨g, m, matched⟩ := pack_subround H.N H.C Δ D hΔ (hΔ.trans_le hle) + H.ns H.cs H.sub hb.2.1 hb.1 hk (by omega) B hB H.load + (fun v i => ⟨H.load_nonneg v i, hb.2.2 v i⟩) H.src H.dst H.ix (P.b * z : ℕ) + L.Z σ (Nat.cast_pos.mpr (Nat.mul_pos P.pos hz)) L.total_nonneg H.outgoing H.edge + hbins hs hm + let s : H.Projection Δ D a := G.project a ah Δ D hle + let q := contracted s g m hz hle + refine ⟨g.Choice m P, inferInstance, q, choice_card g m, + g.eval_contract m P H.units hz, ?_⟩ + apply G.projected_bounds P hz a k Δ D hΔ hle ah B σ hB.le (le_trans (by positivity) hs) bounds g m + have he : Fintype.card H.E = Fintype.card G.E := rfl + simp only [he, X, Nat.cast_mul, mul_comm (Fintype.card G.E : ℝ)] at matched ⊢ + exact matched + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- # Transporting a contraction and a reset to a larger field -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open HostNet + +variable {F : Type} [Field F] + +/-- Extend the local factors of a packet along a field homomorphism. +The supply graph and selector set are unchanged. -/ +theorem map_packet {S E I K : Type} {J : I → Type} + [Fintype S] [Fintype E] [Fintype I] [∀ i, Fintype (J i)] [Field K] + {D : E → S × S} {W : (i : I) → J i → S × S} + (f : F →+* K) (h : Spectral.Packet F D W) : Spectral.Packet K D W := by + classical + obtain ⟨a, hl, he⟩ := h + refine ⟨fun i v x y z => f (a i v x y z), + fun i v x y z x' y' z' hx hy hz => congrArg f (hl i v x y z x' y' z' hx hy hz), ?_⟩ + intro x y + simpa only [apply_ite, map_one, map_zero, map_sum, map_prod] using congrArg f (he x y) + +/-- Uses `⟨P.b, P.copies, P.shapes, P.pos, P.cost, fun z h => map_packet (algebraMap F K) +(P.packet z h)⟩` as the representation. -/ +abbrev Gadget.extend (P : Gadget F) (K : Type) [Field K] [Algebra F K] : Gadget K := + ⟨P.b, P.copies, P.shapes, P.pos, P.cost, fun z h => map_packet (algebraMap F K) (P.packet z h)⟩ + +/-- Uses `⟨R.V, R.E, R.pos, R.degree, fun σ => map_packet (algebraMap F K) (R.packet σ)⟩` as the +representation. -/ +abbrev Rotor.extend {Y w : ℕ} (R : Rotor F Y w) (K : Type) [Field K] [Algebra F K] : + Rotor K Y w := + ⟨R.V, R.E, R.pos, R.degree, fun σ => map_packet (algebraMap F K) (R.packet σ)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Frame.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Frame.lean new file mode 100644 index 0000000000..24ba707f4d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Frame.lean @@ -0,0 +1,1054 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange + +/-! # Double counting the two ends of directed wires -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V I : Type} [Fintype I] + +open scoped Classical in +theorem weighted_degree [Fintype V] (e : I → V × V) (f : V → ℕ) : + ∑ v, degree e v * f v = ∑ i, (f (e i).1 + f (e i).2) := by + simp_rw [degree_sum, sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro i _ + simp [arityCost, add_mul, sum_add_distrib, ite_mul] + +open scoped Classical in +theorem sum_degree [Fintype V] (e : I → V × V) : ∑ v, degree e v = 2 * Fintype.card I := by + simpa [mul_comm] using weighted_degree e (fun _ => 1) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Internal and exterior arity of an aggregate site -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {F V W E : Type} [Fintype E] {x y : Wire} + +open Classical in +theorem degree_bundle (P : E → V × V) (u : ℕ) (z : V) : + degree (fun q : E × Fin u => P q.1) z = degree P z * u := by + simp only [degree_sum, Fintype.sum_prod_type, sum_const, card_univ, Fintype.card_fin, + Nat.nsmul_eq_mul, mul_comm u, ← sum_mul] + +open Classical in +/-- Counts the elements of `{t : slots x // f (G.src.symm (.inl t)).1 = z} +`. -/ +def exterior (G : Diagram F x y) (f : G.V → V) (z : V) : ℕ := + Fintype.card {t : slots x // f (G.src.symm (.inl t)).1 = z} + + Fintype.card {t : slots y // f (G.dst.symm (.inl t)).1 = z} + +open Classical in +private theorem card_push (f : E → V) (z : V) : + (Fintype.card {t // f t = z} : ℝ) = push f (fun _ => 1) z := by + simp only [push, sum_boole, Fintype.card_subtype] + +open Classical in +theorem exterior_comp [Fintype V] (G : Diagram F x y) (f : G.V → V) (g : V → W) (z : W) : + (exterior G (g ∘ f) z : ℝ) = push g (fun v => (exterior G f v : ℝ)) z := by + let a := fun t : slots x => f (G.src.symm (.inl t)).1 + let b := fun t : slots y => f (G.dst.symm (.inl t)).1 + simp only [exterior, Nat.cast_add, card_push] + change push (g ∘ a) _ _ + push (g ∘ b) _ _ = _ + rw [← push_comp, ← push_comp] + unfold push + rw [← sum_add_distrib] + apply sum_congr rfl + intro v _ + split_ifs <;> first | rfl | simp + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Blocks on a common host + +Retain a separate exterior port of the core for every tether bit. +The frozen tensors and all their other exterior legs need no transformation. +Recording the incidence and charges suffices to reattach them, term by +term, at the end of a sequence of contractions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {F T : Type} {x y : Wire} {h u : ℕ} + +open scoped Classical in +/-- The data for the fringe construction, including `tensor`, `charge`, `cover`, `scale`, `pos`. -/ +structure Fringe (x y : Wire) (T : Type) where + /-- The `Fringe` component of type `slots x ⊕ slots y → T`. -/ + tensor : slots x ⊕ slots y → T + /-- The `Fringe` component of type `T → ℝ`. -/ + charge : T → ℝ + cover : ∀ t, Fintype.card {q // tensor q = t} ≤ charge t + /-- Stores the scale associated with this `Fringe`. -/ + scale : ℝ + pos : 0 < scale + le : scale ≤ 1 + /-- The capacity bound. -/ + cap : ℕ := 0 + /-- The fixed value `0` used in this construction. -/ + discount : ℕ := 0 + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def portEnd (G : Diagram F x y) : slots x ⊕ slots y → G.V := + Sum.elim (fun t => (G.src.symm (.inl t)).1) (fun t => (G.dst.symm (.inl t)).1) + +open scoped Classical in +/-- All internal edges lie in the core. Frozen tables are indexed by `T`, +independently of the grouping and contraction history. -/ +structure HostNet (F : Type) (L : Fringe x y T) (h u : ℕ) where + /-- The `HostNet` component of type `Diagram F x y`. -/ + diagram : Diagram F x y + /-- The type of vertices. -/ + V : Type + /-- The type of edges. -/ + E : Type + [fv : Fintype V] + [fe : Fintype E] + /-- Assigns the source of each connection. -/ + src : E → V + /-- Assigns the destination of each connection. -/ + dst : E → V + /-- The `HostNet` component of type `E → Cell h`. -/ + ix : E → Cell h + /-- The indexed units of type `Bundles diagram src dst ix u`. -/ + units : Bundles diagram src dst ix u + /-- The `HostNet` component of type `T → V × Cell h`. -/ + park : T → V × Cell h + /-- The `HostNet` component of type `V × Cell h → ℕ`. -/ + past : V × Cell h → ℕ := fun _ => 0 + /-- The `HostNet` component of type `V → Prop`. -/ + frozen : V → Prop + /-- The `HostNet` component of type `V → Finset V`. -/ + N : V → Finset V + /-- The `HostNet` component of type `V → Finset V`. -/ + C : V → Finset V + ns : ∀ v z, z ∈ N v → v ∈ N z + cs : ∀ v z, z ∈ C v → v ∈ C z + sub : ∀ v, C v ⊆ N v + kept : ∀ t, frozen (park t).1 + core : ∀ e, ¬frozen (src e) ∧ ¬frozen (dst e) + edge : ∀ e, dst e ∈ C (src e) + tether : ∀ q, let p := units.place (portEnd diagram q) + let z := park (L.tensor q) + ¬frozen p.1 ∧ p.2 = z.2 ∧ z.1 ∈ N p.1 + +attribute [instance] HostNet.fe HostNet.fv + +open scoped Classical in +/-- Reserved space for histories of eliminated wires. -/ +def Fringe.reserve (L : Fringe x y T) := L.cap / (2 : ℝ) ^ L.discount + +open scoped Classical in +/-- The quantity computed by `(∑ t, L.charge t) + L.reserve`. -/ +def Fringe.Z [Fintype T] (L : Fringe x y T) := (∑ t, L.charge t) + L.reserve + +open scoped Classical in +theorem Fringe.reserve_nonneg (L : Fringe x y T) : 0 ≤ L.reserve := by + unfold reserve; positivity + +open scoped Classical in +theorem Fringe.nonneg (L : Fringe x y T) (t : T) : 0 ≤ L.charge t := + (Nat.cast_nonneg _).trans (L.cover t) + +namespace HostNet + +variable {L : Fringe x y T} (G : HostNet F L h u) + +open scoped Classical in +/-- Counts the elements of `G.E * u`. -/ +def X := Fintype.card G.E * u + +open scoped Classical in +/-- The value specified by `((G.src e, G.ix e), (G.dst e, G.ix e))`. -/ +def pair (e : G.E) := ((G.src e, G.ix e), (G.dst e, G.ix e)) + +open scoped Classical in +/-- Computes the tether load by the application `exterior G.diagram G.units.place p`. -/ +def tetherLoad (p : G.V × Cell h) := exterior G.diagram G.units.place p + +open scoped Classical in +/-- Each eliminated internal port remains part of the local description. -/ +def mass := ∑ p, G.past p + +open scoped Classical in +/-- Returns `1 / (2 : ℝ) ^ L.discount` when `G.mass ≤ L.cap` holds, and `0` otherwise. -/ +def rate := if G.mass ≤ L.cap then 1 / (2 : ℝ) ^ L.discount else 0 + +open scoped Classical in +theorem rate_nonneg : 0 ≤ G.rate := by unfold rate; positivity + +open scoped Classical in +theorem rate_le : G.rate ≤ 1 := by + unfold rate + split + · exact (div_le_one (by positivity)).mpr (one_le_pow₀ (by norm_num)) + · norm_num + +open scoped Classical in +theorem rate_budget : G.rate * G.mass ≤ L.reserve := by + unfold rate + split + · rw [one_div_mul_eq_div] + exact div_le_div_of_nonneg_right (by exact_mod_cast ‹G.mass ≤ L.cap›) (by positivity) + · rw [zero_mul]; exact L.reserve_nonneg + +open scoped Classical in +/-- The sum of `if f p = v then G.past p + degree G.pair p * u else 0` indexed by `p`. -/ +def carried {W : Type} (f : G.V × Cell h → W) (v : W) := + ∑ p, if f p = v then G.past p + degree G.pair p * u else 0 + +variable [Fintype T] + +open scoped Classical in +/-- The value specified by `(G.tetherLoad (v, i) : ℝ) + degree G.pair (v, i) * (u : ℝ) + L.scale +* push G.park L.charge (v, i) + G.rate * G.past (v, i)`. -/ +def load (v : G.V) (i : Cell h) : ℝ := + (G.tetherLoad (v, i) : ℝ) + degree G.pair (v, i) * (u : ℝ) + + L.scale * push G.park L.charge (v, i) + G.rate * G.past (v, i) + +open scoped Classical in +/-- Requires `(∀ v, (G.C v).card ≤ Δ) ∧ (∀ v, (G.N v).card ≤ D) ∧ ∀ v i, G.load v i ≤ B`. -/ +def Bounded (Δ D : ℕ) (B : ℝ) : Prop := + (∀ v, (G.C v).card ≤ Δ) ∧ (∀ v, (G.N v).card ≤ D) ∧ ∀ v i, G.load v i ≤ B + +open scoped Classical in +theorem core_le_load (v : G.V) (i : Cell h) : + (G.tetherLoad (v, i) : ℝ) + degree G.pair (v, i) * (u : ℝ) ≤ G.load v i := + (le_add_of_nonneg_right (mul_nonneg L.pos.le (push_nonneg _ _ L.nonneg _))).trans + (le_add_of_nonneg_right (mul_nonneg G.rate_nonneg (Nat.cast_nonneg _))) + +open scoped Classical in +theorem load_nonneg (v : G.V) (i : Cell h) : 0 ≤ G.load v i := + le_trans (by positivity) (G.core_le_load v i) + +end HostNet +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Conservation of load in a grouped core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {F T V W : Type} {x y : Wire} + +open scoped Classical in +theorem port_load (G : Diagram F x y) (f : G.V → V) (v : V) : + (exterior G f v : ℝ) = push (f ∘ portEnd G) (fun _ => 1) v := by + unfold push + rw [Fintype.sum_sum_type] + change _ = (∑ t : slots x, if f (G.src.symm (.inl t)).1 = v then (1 : ℝ) else 0) + + ∑ t : slots y, if f (G.dst.symm (.inl t)).1 = v then (1 : ℝ) else 0 + simp only [exterior, Nat.cast_add, Fintype.card_subtype, sum_boole] + +open scoped Classical in +theorem Fringe.tethers [Fintype T] (L : Fringe x y T) : Fintype.card (slots x ⊕ slots y) ≤ L.Z := by + have hx : (∑ t, push L.tensor (fun _ => 1) t) ≤ L.Z := by + apply le_trans _ (le_add_of_nonneg_right L.reserve_nonneg) + apply sum_le_sum + intro t _ + simpa only [push, sum_boole, Fintype.card_subtype] using L.cover t + simpa only [sum_push, sum_const, card_univ, nsmul_eq_mul, mul_one] using hx + +open scoped Classical in +theorem Fringe.total_nonneg [Fintype T] (L : Fringe x y T) : 0 ≤ L.Z := + add_nonneg (sum_nonneg fun t _ => L.nonneg t) L.reserve_nonneg + +open scoped Classical in +/-- Restricts a bit string to its initial coordinates as a linear map over the two-element +field. -/ +def prefixMap {a h : ℕ} (ha : a ≤ h) : Cell h →ₗ[ZMod 2] Cell a where + toFun := ancestor ha + map_add' _ _ := rfl + map_smul' _ _ := rfl + +open scoped Classical in +theorem prefixMap_onto {a h : ℕ} (ha : a ≤ h) : Function.Surjective (prefixMap ha) := by + intro c + have : 0 < Fintype.card {x // ancestor ha x = c} := by rw [card_prefix]; positivity + obtain ⟨x⟩ := Fintype.card_pos_iff.mp this + exact ⟨x.val, x.property⟩ + +namespace HostNet + +variable {h u : ℕ} {L : Fringe x y T} (G : HostNet F L h u) [Fintype T] + +open scoped Classical in +theorem sum_load : (∑ v, ∑ i, G.load v i) ≤ 2 * (G.X : ℝ) + 2 * L.Z := by + let endpt (e : G.E) (t : Bool) := if t then (G.dst e, G.ix e) else (G.src e, G.ix e) + have ed (p : G.V × Cell h) : (degree G.pair p : ℝ) * u = + push (Function.uncurry endpt) (fun _ => (u : ℝ)) p := degree_push endpt _ p + have eq : (∑ v, ∑ i, G.load v i) = + Fintype.card (slots x ⊕ slots y) + 2 * (G.X : ℝ) + + L.scale * (∑ t, L.charge t) + G.rate * G.mass := by + rw [← Fintype.sum_prod_type (fun p : G.V × Cell h => G.load p.1 p.2)] + simp only [load, tetherLoad, port_load, ed, Prod.mk.eta, sum_add_distrib, ← mul_sum, sum_push, + sum_const, card_univ, nsmul_eq_mul, Fintype.card_prod, Fintype.card_bool, X, mass, + Nat.cast_sum, + Nat.cast_mul, Nat.cast_ofNat] + ring + rw [eq] + have hs : 0 ≤ ∑ t, L.charge t := sum_nonneg fun i _ => L.nonneg i + have ht := L.tethers + unfold Fringe.Z at ht ⊢ + linarith only [ht, mul_le_of_le_one_left hs L.le, G.rate_budget] + +open scoped Classical in +/-- Exterior and parked charges follow the site assignment. Only the +internal edges need a fresh estimate after contraction. -/ +theorem outside_le (o : G.V × Cell h → W) (z : W) : + (exterior G.diagram (o ∘ G.units.place) z : ℝ) + + L.scale * push (o ∘ G.park) L.charge z ≤ push o (Function.uncurry G.load) z := by + rw [exterior_comp, ← push_comp] + unfold push + rw [mul_sum, ← sum_add_distrib] + apply sum_le_sum + rintro ⟨v, i⟩ _ + split_ifs + · exact (add_le_add_left (le_add_of_nonneg_right (by positivity)) _).trans + (le_add_of_nonneg_right (mul_nonneg G.rate_nonneg (Nat.cast_nonneg _))) + · simp + +omit [Fintype T] in +open scoped Classical in +theorem carry_sum [Fintype W] (o : G.V × Cell h → W) : + ∑ v, G.carried o v = G.mass + 2 * G.X := by + unfold carried + rw [sum_comm] + simp only [sum_ite_eq, mem_univ, ite_true, sum_add_distrib, ← sum_mul] + unfold X mass + rw [sum_degree, mul_assoc] + +omit [Fintype T] in +open scoped Classical in +theorem rate_anti {a z : ℕ} (Q : HostNet F L a z) (hm : G.mass ≤ Q.mass) : + Q.rate ≤ G.rate := by + unfold rate + split_ifs <;> first | exact le_rfl | omega | positivity + +open scoped Classical in +/-- Absorb the discounted history of old incident edges into their +existing port charge. New edges are charged at full width. -/ +theorem reassign {a z : ℕ} (Q : HostNet F L a z) (o : G.V × Cell h → Q.V × Cell a) + (park : Q.park = o ∘ G.park) + (endpt : ∀ q, Q.units.place (portEnd Q.diagram q) = o (G.units.place (portEnd G.diagram q))) + (record : Q.past = G.carried o) (p : Q.V × Cell a) : + Q.load p.1 p.2 ≤ push o (Function.uncurry G.load) p + degree Q.pair p * (z : ℝ) := by + have hmass : G.mass ≤ Q.mass := by + change G.mass ≤ ∑ t, Q.past t + rw [record, carry_sum]; omega + have hr := G.rate_anti Q hmass + have he : Q.units.place ∘ portEnd Q.diagram = (o ∘ G.units.place) ∘ portEnd G.diagram := + funext endpt + have outside : (exterior Q.diagram Q.units.place p : ℝ) + + L.scale * push Q.park L.charge p + Q.rate * Q.past p ≤ push o (Function.uncurry G.load) p + := by + rw [park, port_load, he, ← port_load, exterior_comp, ← push_comp, record] + unfold carried push + rw [Nat.cast_sum, mul_sum, mul_sum, ← sum_add_distrib, ← sum_add_distrib] + apply sum_le_sum + rintro ⟨v, i⟩ _ + split_ifs with h + · rw [Nat.cast_add, Nat.cast_mul, mul_add] + have h₁ := mul_le_mul_of_nonneg_right hr (Nat.cast_nonneg (α := ℝ) (G.past (v, i))) + have h₂ := mul_le_mul_of_nonneg_right Q.rate_le + (show 0 ≤ (degree G.pair (v, i) : ℝ) * u by positivity) + dsimp only [Function.uncurry_apply_pair, load, tetherLoad, push] + linarith only [h₁, h₂] + · simp + change (exterior Q.diagram Q.units.place p : ℝ) + degree Q.pair p * (z : ℝ) + + L.scale * push Q.park L.charge p + Q.rate * Q.past p ≤ _ + linarith only [outside] + +open scoped Classical in +/-- Every old occurrence has one destination. Frozen labels and tether +ports that coincide at an occurrence stay together. A common surjective +linear map on binary block indices controls all occurrences. Every host +has a uniform number of slots per old position, and parked tensors never +leave the slots allocated to their position. -/ +def Preserves {a z : ℕ} (Q : HostNet F L a z) : Prop := + ∃ o : G.V × Cell h → Q.V × Cell a, Q.park = o ∘ G.park ∧ + (∀ p, Q.units.place (portEnd Q.diagram p) = o (G.units.place (portEnd G.diagram p))) ∧ + (∃ f : Cell h →ₗ[ZMod 2] Cell a, Function.Surjective f ∧ ∀ p, (o p).2 = f p.2) ∧ + ∃ (B : Type) (_ : Fintype B) (e : Q.V ≃ G.V × B), ∀ t, (e (Q.park t).1).1 = (G.park t).1 + +omit [Fintype T] in +open scoped Classical in +theorem Preserves.refl : G.Preserves G := + ⟨id, rfl, fun _ => rfl, ⟨LinearMap.id, Function.surjective_id, fun _ => rfl⟩, + Unit, inferInstance, (Equiv.prodUnique G.V Unit).symm, fun _ => rfl⟩ + +omit [Fintype T] in +open scoped Classical in +theorem Preserves.trans {a z b t : ℕ} {G : HostNet F L h u} + {Q : HostNet F L a z} {R : HostNet F L b t} + (h₁ : G.Preserves Q) (h₂ : Q.Preserves R) : G.Preserves R := by + obtain ⟨o, ho, ht, ⟨f, hf, ef⟩, A, _, j, hj⟩ := h₁ + obtain ⟨p, hp, hu, ⟨g, hg, eg⟩, B, _, k, hk⟩ := h₂ + exact ⟨p ∘ o, by rw [hp, ho]; rfl, fun z => (hu z).trans (congrArg p (ht z)), + ⟨g.comp f, hg.comp hf, fun z => (eg (o z)).trans (congrArg g (ef z))⟩, + A × B, inferInstance, k.trans ((j.prodCongr (.refl B)).trans (Equiv.prodAssoc _ _ _)), + fun t => (congrArg (fun q => (j q).1) (hk t)).trans (hj t)⟩ + +end HostNet +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Reattaching frozen tables + +Each exposed slot on the core becomes a separate wire to its original frozen +table. Only the ports of the frozen tables remain exterior. Contraction is +linear in the core tensor, so exact sums survive reattachment. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +/-- The data for the border construction, including `table`, `src`, `dst`. -/ +structure Border (F T : Type) (a b x y : Wire) where + /-- The local table at each indexed position carried by `Border`, with type `T → Table F`. -/ + table : T → Table F + /-- Assigns the source of each connection. -/ + src : (Σ v, slots (table v).1) ≃ slots a ⊕ slots y + /-- Assigns the destination of each connection. -/ + dst : (Σ v, slots (table v).2.1) ≃ slots b ⊕ slots x + +namespace Border + +variable {F T : Type} {a b x y : Wire} (B : Border F T a b x y) + +/-- Chooses the operation for the left or right summand. -/ +def tensor : slots x ⊕ slots y → T := + Sum.elim (fun i => (B.dst.symm (.inr i)).1) (fun i => (B.src.symm (.inr i)).1) + +/-- In the case `.inl (.inl i)`, this construction gives `.inr (.inr (.inl i))`. -/ +def merge (A E X Y : Type) : (X ⊕ E) ⊕ (A ⊕ Y) ≃ A ⊕ E ⊕ X ⊕ Y where + toFun + | .inl (.inl i) => .inr (.inr (.inl i)) + | .inl (.inr e) => .inr (.inl e) + | .inr (.inl s) => .inl s + | .inr (.inr j) => .inr (.inr (.inr j)) + invFun + | .inl s => .inr (.inl s) + | .inr (.inl e) => .inl (.inr e) + | .inr (.inr (.inl i)) => .inl (.inl i) + | .inr (.inr (.inr j)) => .inr (.inr j) + left_inv := by rintro ((_|_)|(_|_)) <;> rfl + right_inv := by rintro (_|_|_|_) <;> rfl + +variable [Fintype T] (G : Diagram F x y) + +/-- Builds `Diagram F a b where V` with the specified `table`, `src`, `dst`. -/ +abbrev attach : Diagram F a b where + V := G.V ⊕ T + E := G.E ⊕ slots x ⊕ slots y + table := Sum.elim G.table B.table + src := (Equiv.sumSigmaDistrib _).trans ((G.src.sumCongr B.src).trans (merge _ _ _ _)) + dst := (Equiv.sumSigmaDistrib _).trans ((G.dst.sumCongr B.dst).trans + ((merge _ _ _ _).trans ((Equiv.refl _).sumCongr ((Equiv.refl _).sumCongr (Equiv.sumComm _ _))))) + +theorem ends_core (e : G.E) : + ((B.attach G).source (.inl e), (B.attach G).target (.inl e)) = + (Sum.inl (G.source e), Sum.inl (G.target e)) := rfl + +theorem ends_input (i : slots x) : + ((B.attach G).source (.inr (.inl i)), (B.attach G).target (.inr (.inl i))) = + (Sum.inl (portEnd G (.inl i)), Sum.inr (B.tensor (.inl i))) := rfl + +theorem ends_output (i : slots y) : + ((B.attach G).source (.inr (.inr i)), (B.attach G).target (.inr (.inr i))) = + (Sum.inr (B.tensor (.inr i)), Sum.inl (portEnd G (.inr i))) := rfl + +variable [Field F] + +/-- The weight of type `F` for the given inputs. -/ +def weight (s : Val a) (t : Val b) (u : Val x) (v : Val y) : F := + ∏ j, (B.table j).2.2 + ((bits (B.table j).1).symm (fun i => Sum.elim (bits a s) (bits y v) (B.src ⟨j, i⟩))) + ((bits (B.table j).2.1).symm (fun i => Sum.elim (bits b t) (bits x u) (B.dst ⟨j, i⟩))) + +theorem eval_attach (s : Val a) (t : Val b) : + (B.attach G).eval s t = ∑ u : Val x, ∑ v : Val y, G.eval u v * B.weight s t u v := by + classical + let _ : DecidableEq (B.attach G).E := fun _ _ => Classical.propDecidable _ + let e : (Val x × Val y) × (G.E → Bool) ≃ ((B.attach G).E → Bool) := + (Equiv.prodComm _ _).trans (((Equiv.refl _).prodCongr (bits (.pair x y))).trans + (Equiv.sumArrowEquivProdArrow _ _ Bool).symm) + unfold Diagram.eval + rw [← e.sum_comp, Fintype.sum_prod_type, Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro u _ + apply Finset.sum_congr rfl + intro v _ + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro z _ + change (∏ j : G.V ⊕ T, (B.attach G).vertex s t (e ((u, v), z)) j) = _ + rw [Fintype.prod_sum_type] + apply congrArg₂ (· * ·) + · apply Finset.prod_congr rfl + intro j _ + apply congrArg₂ (G.table j).2.2 + · apply congrArg (bits (G.table j).1).symm + funext i + change Sum.elim _ _ (merge _ _ _ _ (.inl (G.src ⟨j, i⟩))) = _ + cases G.src ⟨j, i⟩ <;> rfl + · apply congrArg (bits (G.table j).2.1).symm + funext i + change Sum.elim _ _ (Sum.map id (Sum.map id Sum.swap) (merge _ _ _ _ (.inl (G.dst ⟨j, i⟩)))) + = _ + cases G.dst ⟨j, i⟩ <;> rfl + · apply Finset.prod_congr rfl + intro j _ + apply congrArg₂ (B.table j).2.2 + · apply congrArg (bits (B.table j).1).symm + funext i + change Sum.elim _ _ (merge _ _ _ _ (.inr (B.src ⟨j, i⟩))) = _ + cases B.src ⟨j, i⟩ <;> rfl + · apply congrArg (bits (B.table j).2.1).symm + funext i + change Sum.elim _ _ (Sum.map id (Sum.map id Sum.swap) (merge _ _ _ _ (.inr (B.dst ⟨j, i⟩)))) + = _ + cases B.dst ⟨j, i⟩ <;> rfl + +theorem attach_sum {I : Type} [Fintype I] (Q : I → Diagram F x y) + (H : ∀ u v, ∑ i, (Q i).eval u v = G.eval u v) (s : Val a) (t : Val b) : + ∑ i, (B.attach (Q i)).eval s t = (B.attach G).eval s t := by + simp_rw [eval_attach] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro u _ + rw [Finset.sum_comm] + simp_rw [← Finset.sum_mul, H] + +end Border +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Separating off the frozen vertices + +All exterior positions lie on frozen vertices. No internal wire +joins two frozen vertices. Partition the wires into core edges and +the two directions of tethers, giving each tether a separate name. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +variable {F : Type} {a b : Wire} + +open scoped Classical in +/-- The data for the freeze construction, including `frozen`, `exterior`, `separate`. -/ +structure Freeze (G : Diagram F a b) where + /-- The `Freeze` component of type `G.V → Prop`. -/ + frozen : G.V → Prop + exterior : ∀ q, frozen (portEnd G q) + separate : ∀ e, ¬(frozen (G.source e) ∧ frozen (G.target e)) + +namespace Freeze +variable {G : Diagram F a b} (Z : Freeze G) + +open scoped Classical in +/-- The subtype of vertices outside the frozen part of the diagram. -/ +abbrev Core := {v // ¬ Z.frozen v} +open scoped Classical in +/-- The subtype of `v` satisfying `Z.frozen v`. -/ +abbrev Fixed := {v // Z.frozen v} +open scoped Classical in +/-- The subtype of `e` satisfying `¬ Z.frozen (G.source e) ∧ ¬ Z.frozen (G.target e)`. -/ +abbrev Internal := {e // ¬ Z.frozen (G.source e) ∧ ¬ Z.frozen (G.target e)} +open scoped Classical in +/-- The subtype of `e` satisfying `Z.frozen (G.target e)`. -/ +abbrev Input := {e // Z.frozen (G.target e)} +open scoped Classical in +/-- The subtype of `e` satisfying `Z.frozen (G.source e)`. -/ +abbrev Output := {e // Z.frozen (G.source e)} + +open scoped Classical in +/-- Computes the x by the application `word (Fintype.card Z.Input)`. -/ +def x := word (Fintype.card Z.Input) +open scoped Classical in +/-- Computes the y by the application `word (Fintype.card Z.Output)`. -/ +def y := word (Fintype.card Z.Output) + +open scoped Classical in +/-- Computes the input by the application `Fintype.equivOfCardEq ((card_slots Z.x).trans +(wd_word _))`. -/ +def input : slots Z.x ≃ Z.Input := + Fintype.equivOfCardEq ((card_slots Z.x).trans (wd_word _)) + +open scoped Classical in +/-- Computes the output by the application `Fintype.equivOfCardEq ((card_slots Z.y).trans +(wd_word _))`. -/ +def output : slots Z.y ≃ Z.Output := + Fintype.equivOfCardEq ((card_slots Z.y).trans (wd_word _)) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def edges : Z.Internal ⊕ slots Z.x ⊕ slots Z.y ≃ G.E where + toFun := Sum.elim Subtype.val (Sum.elim (Subtype.val ∘ Z.input) (Subtype.val ∘ Z.output)) + invFun e := if hi : Z.frozen (G.target e) then .inr (.inl (Z.input.symm ⟨e, hi⟩)) + else if ho : Z.frozen (G.source e) then .inr (.inr (Z.output.symm ⟨e, ho⟩)) + else .inl ⟨e, ho, hi⟩ + left_inv := by + rintro (e | i | j) + · simp [e.property.1, e.property.2] + · simp [(Z.input i).property] + · have hn : ¬Z.frozen (G.target (Z.output j)) := + fun h => Z.separate _ ⟨(Z.output j).property, h⟩ + simp [hn, (Z.output j).property] + right_inv e := by dsimp; split_ifs <;> simp + +open scoped Classical in +/-- Uses `⟨z.1.val, z.2⟩` as the representation. -/ +def forget {V : Type} {I : V → Type} {p : V → Prop} + (z : Σ v : Subtype p, I v.val) : Σ v, I v := ⟨z.1.val, z.2⟩ + +open scoped Classical in +theorem forget_inj {V : Type} {I : V → Type} {p : V → Prop} : + Function.Injective (forget (I := I) (p := p)) := by + rintro ⟨⟨v, hv⟩, i⟩ ⟨⟨w, hw⟩, j⟩ h + cases h; rfl + +open scoped Classical in +/-- Reindexes `(Σ v : Subtype p, I v.val)` and `A` by an equivalence. -/ +def restrict {V A B : Type} {I : V → Type} (e : A ⊕ B ≃ Σ v, I v) (p : V → Prop) + (ha : ∀ x, p (e (.inl x)).1) (hb : ∀ x, ¬p (e (.inr x)).1) : + (Σ v : Subtype p, I v.val) ≃ A := + (Equiv.ofBijective (fun x => ⟨⟨(e (.inl x)).1, ha x⟩, (e (.inl x)).2⟩) (by + constructor + · intro i j he + exact Sum.inl.inj (e.injective (congrArg forget he)) + · intro z + obtain ⟨x|x, hx⟩ := e.surjective (forget z) + · exact ⟨x, forget_inj hx⟩ + · exact (hb x (hx.symm ▸ z.1.property)).elim)).symm + +open scoped Classical in +/-- The value specified by `((Border.merge (slots a) Z.Internal (slots Z.x) (slots Z.y)).trans +((Equiv.refl _).sumCongr Z.edges)).trans G.src.symm`. -/ +def srcOrder := ((Border.merge (slots a) Z.Internal (slots Z.x) (slots Z.y)).trans + ((Equiv.refl _).sumCongr Z.edges)).trans G.src.symm + +open scoped Classical in +/-- The dst order used in the `Freeze` construction. -/ +def dstOrder := (((Border.merge (slots b) Z.Internal (slots Z.y) (slots Z.x)).trans + ((Equiv.refl _).sumCongr ((Equiv.refl _).sumCongr (Equiv.sumComm _ _)))).trans + ((Equiv.refl _).sumCongr Z.edges)).trans G.dst.symm + +open scoped Classical in +theorem src_core (p : slots Z.x ⊕ Z.Internal) : ¬Z.frozen (Z.srcOrder (.inl p)).1 := by + cases p with + | inl i => exact fun h => Z.separate _ ⟨h, (Z.input i).property⟩ + | inr e => exact e.property.1 + +open scoped Classical in +theorem src_fixed (p : slots a ⊕ slots Z.y) : Z.frozen (Z.srcOrder (.inr p)).1 := by + cases p with + | inl i => exact Z.exterior (.inl i) + | inr i => exact (Z.output i).property + +open scoped Classical in +theorem dst_core (p : slots Z.y ⊕ Z.Internal) : ¬Z.frozen (Z.dstOrder (.inl p)).1 := by + cases p with + | inl i => exact fun h => Z.separate _ ⟨(Z.output i).property, h⟩ + | inr e => exact e.property.2 + +open scoped Classical in +theorem dst_fixed (p : slots b ⊕ slots Z.x) : Z.frozen (Z.dstOrder (.inr p)).1 := by + cases p with + | inl i => exact Z.exterior (.inr i) + | inr i => exact (Z.input i).property + +open scoped Classical in +/-- Builds `Diagram F Z.x Z.y where V` with the specified `table`, `src`, `dst`. -/ +abbrev core : Diagram F Z.x Z.y where + V := Z.Core + E := Z.Internal + table v := G.table v.val + src := restrict Z.srcOrder _ Z.src_core (fun i => not_not.mpr (Z.src_fixed i)) + dst := restrict Z.dstOrder _ Z.dst_core (fun i => not_not.mpr (Z.dst_fixed i)) + +open scoped Classical in +/-- Builds `Border F Z.Fixed a b Z.x Z.y where table v` with the specified `table`, `src`, +`dst`. -/ +def border : Border F Z.Fixed a b Z.x Z.y where + table v := G.table v.val + src := restrict ((Equiv.sumComm _ _).trans Z.srcOrder) Z.frozen Z.src_fixed Z.src_core + dst := restrict ((Equiv.sumComm _ _).trans Z.dstOrder) Z.frozen Z.dst_fixed Z.dst_core + +open scoped Classical in +theorem source (e : Z.Internal) : (Z.core.source e).val = G.source e.val := rfl +open scoped Classical in +theorem target (e : Z.Internal) : (Z.core.target e).val = G.target e.val := rfl + +open scoped Classical in +/-- Evaluates `Z.edges (.inr i)` at the input `i`. -/ +def tether : slots Z.x ⊕ slots Z.y → G.E := fun i => Z.edges (.inr i) + +open scoped Classical in +theorem ports (q : slots Z.x ⊕ slots Z.y) : + let c := (portEnd Z.core q).val + let t := (Z.border.tensor q).val + (G.source (Z.tether q), G.target (Z.tether q)) = + if q.isLeft then (c, t) else (t, c) := by cases q <;> rfl + +open scoped Classical in +private abbrev joined := Z.border.attach Z.core + +open scoped Classical in +private def vertices : Z.Core ⊕ Z.Fixed ≃ G.V := + (Equiv.sumComm _ _).trans (Equiv.sumCompl Z.frozen) + +open scoped Classical in +private theorem restrict_apply {V A B : Type} {I : V → Type} (e : A ⊕ B ≃ Σ v, I v) + (p : V → Prop) (ha : ∀ x, p (e (.inl x)).1) (hb : ∀ x, ¬p (e (.inr x)).1) + (z : Σ v : Subtype p, I v.val) : e (.inl (restrict e p ha hb z)) = forget z := + congrArg forget ((restrict e p ha hb).symm_apply_apply z) + +open scoped Classical in +private theorem read {A E E' : Type} (s : A → Bool) (z : E → Bool) + (e : E' ≃ E) (q : A ⊕ E') (r : A ⊕ E) (h : ((Equiv.refl _).sumCongr e) q = r) : + Sum.elim s (z ∘ e) q = Sum.elim s z r := by + subst r + cases q <;> rfl + +open scoped Classical in +private theorem vertex_join (s : Val a) (t : Val b) (z : G.E → Bool) (v : Z.Core ⊕ Z.Fixed) : + Z.joined.vertex s t (z ∘ Z.edges) v = G.vertex s t z (Z.vertices v) := by + cases v with + | inl v => + apply congrArg₂ (G.table v.val).2.2 + · apply congrArg (bits (G.table v.val).1).symm + funext i + apply read + apply G.src.symm_apply_eq.mp + exact restrict_apply Z.srcOrder _ Z.src_core (fun i => not_not.mpr (Z.src_fixed i)) ⟨v, i⟩ + · apply congrArg (bits (G.table v.val).2.1).symm + funext i + apply read + apply G.dst.symm_apply_eq.mp + exact restrict_apply Z.dstOrder _ Z.dst_core (fun i => not_not.mpr (Z.dst_fixed i)) ⟨v, i⟩ + | inr v => + apply congrArg₂ (G.table v.val).2.2 + · apply congrArg (bits (G.table v.val).1).symm + funext i + apply read + apply G.src.symm_apply_eq.mp + exact restrict_apply ((Equiv.sumComm _ _).trans Z.srcOrder) _ Z.src_fixed Z.src_core ⟨v, i⟩ + · apply congrArg (bits (G.table v.val).2.1).symm + funext i + apply read + apply G.dst.symm_apply_eq.mp + exact restrict_apply ((Equiv.sumComm _ _).trans Z.dstOrder) _ Z.dst_fixed Z.dst_core ⟨v, i⟩ + +open scoped Classical in +theorem reconstruct [Field F] (s : Val a) (t : Val b) : + (Z.border.attach Z.core).eval s t = G.eval s t := by + let _ : DecidableEq Z.joined.E := fun _ _ => Classical.propDecidable _ + let e := Z.edges.symm.arrowCongr (Equiv.refl Bool) + unfold Diagram.eval + rw [← e.sum_comp] + apply Finset.sum_congr rfl + intro z _ + exact Fintype.prod_equiv Z.vertices _ _ (fun v => Z.vertex_join s t z v) + +end Freeze +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Partitioning parallel core wires into equal bundles -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +variable {F : Type} {a b : Wire} + +open scoped Classical in +/-- Uniform packets of bits, each with one ordered pair of endpoints. -/ +structure Packets (G : Diagram F a b) (u : ℕ) where + /-- The type of edges. -/ + E : Type + [fe : Fintype E] + /-- Assigns the source of each connection. -/ + src : E → G.V + /-- Assigns the destination of each connection. -/ + dst : E → G.V + /-- Reindexes the data using `G.E ≃ E × Fin u`. -/ + bits : G.E ≃ E × Fin u + left : ∀ e, src (bits e).1 = G.source e + right : ∀ e, dst (bits e).1 = G.target e + +attribute [instance] Packets.fe + +open scoped Classical in +private theorem bundle_fibers {E V : Type} [Fintype E] [Finite V] [DecidableEq V] + (p : E → V) (u : ℕ) + (h : ∀ v, u ∣ Fintype.card {e // p e = v}) : + ∃ (A : Type) (_ : Fintype A) (f : A → V) (bits : E ≃ A × Fin u), + ∀ e, f (bits e).1 = p e := by + let : Fintype V := Fintype.ofFinite V + choose n hn using h + let index (v : V) : {e // p e = v} ≃ Fin (n v) × Fin u := + Fintype.equivOfCardEq (by simp [hn v, mul_comm]) + let A := Σ v, Fin (n v) + let flatten : (Σ v, Fin (n v) × Fin u) ≃ A × Fin u := + { toFun := fun p => (⟨p.1, p.2.1⟩, p.2.2) + invFun := fun p => ⟨p.1.1, p.1.2, p.2⟩ + left_inv _ := rfl, right_inv _ := rfl } + exact ⟨A, inferInstance, Sigma.fst, + (Equiv.sigmaFiberEquiv p).symm.trans ((Equiv.sigmaCongrRight index).trans flatten), + fun _ => rfl⟩ + +open scoped Classical in +theorem packets_exist (G : Diagram F a b) (u : ℕ) + (hw : ∀ v w, u ∣ Fintype.card {e // G.source e = v ∧ G.target e = w}) : + Nonempty (Packets G u) := by + let p (e : G.E) := (G.source e, G.target e) + have div (q : G.V × G.V) : u ∣ Fintype.card {e // p e = q} := by + obtain ⟨v, w⟩ := q + simpa [p, Fintype.card_subtype] using hw v w + obtain ⟨E, _, f, bits, hf⟩ := bundle_fibers p u div + exact ⟨⟨E, fun e => (f e).1, fun e => (f e).2, bits, + fun e => congrArg Prod.fst (hf e), fun e => congrArg Prod.snd (hf e)⟩⟩ + +namespace Freeze + +variable {G : Diagram F a b} (Z : Freeze G) + +open scoped Classical in +/-- The condition `∀ v w, ¬Z.frozen v → ¬Z.frozen w → u ∣ Fintype.card {e // G.source e = v ∧ +G.target e = w}` on the specified data. -/ +def Divisible (u : ℕ) : Prop := + ∀ v w, ¬Z.frozen v → ¬Z.frozen w → u ∣ Fintype.card {e // G.source e = v ∧ G.target e = w} + +open scoped Classical in +theorem bundles {u : ℕ} (h : Z.Divisible u) : Nonempty (Packets Z.core u) := by + let p (e : Z.Internal) := (Z.core.source e, Z.core.target e) + have div (q : Z.Core × Z.Core) : u ∣ Fintype.card {e // p e = q} := by + let eq : {e // p e = q} ≃ {e // G.source e = q.1.val ∧ G.target e = q.2.val} := + { toFun := fun e => ⟨e.val.val, congrArg (fun q => q.1.val) e.property, + congrArg (fun q => q.2.val) e.property⟩ + invFun := fun e => ⟨⟨e.val, e.property.1.symm ▸ q.1.property, + e.property.2.symm ▸ q.2.property⟩, Prod.ext (Subtype.ext e.property.1) + (Subtype.ext e.property.2)⟩ + left_inv _ := rfl, right_inv _ := rfl } + rw [Fintype.card_congr eq] + exact h _ _ q.1.property q.2.property + obtain ⟨E, _, f, bits, hf⟩ := bundle_fibers p u div + exact ⟨⟨E, fun e => (f e).1, fun e => (f e).2, bits, + fun e => congrArg Prod.fst (hf e), fun e => congrArg Prod.snd (hf e)⟩⟩ + +end Freeze +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Recovering loads from station arities -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +variable {F V T : Type} {a b : Wire} {h u : ℕ} + +open scoped Classical in +theorem site_arity (G : Diagram F a b) (p : G.V → V) (v : V) : + push p (fun i => (G.arity i : ℝ)) v = (exterior G p v : ℝ) + + degree (fun e => (p (G.source e), p (G.target e))) v := by + have arity (i : G.V) : (G.arity i : ℝ) = push G.station (fun _ => 1) i := by + rw [← G.degree] + simp only [push, sum_boole, Fintype.card_subtype] + rw [show (fun i => (G.arity i : ℝ)) = push G.station (fun _ => 1) from funext arity, push_comp] + rw [port_load, degree_sum, Nat.cast_sum] + simp only [arityCost, Nat.cast_add, Nat.cast_ite, Nat.cast_one, Nat.cast_zero, sum_add_distrib] + unfold push + rw [Fintype.sum_sum_type, Fintype.sum_sum_type, Fintype.sum_sum_type, Fintype.sum_sum_type] + exact add_add_add_comm _ _ _ _ + +open scoped Classical in +theorem HostNet.load_eq [Fintype T] {L : Fringe a b T} (H : HostNet F L h u) (v : H.V × Cell h) : + H.load v.1 v.2 = push H.units.place (fun i => (H.diagram.arity i : ℝ)) v + + L.scale * push H.park L.charge v + H.rate * H.past v := by + let p (e : H.diagram.E) := (H.units.place (H.diagram.source e), + H.units.place (H.diagram.target e)) + have deg : degree p v = degree H.pair v * u := by + rw [← degree_bundle H.pair u v, degree_sum, degree_sum] + exact Fintype.sum_equiv H.units.bits _ _ (fun e => + congrArg (arityCost v) (Prod.ext (H.units.left e) (H.units.right e))) + unfold HostNet.load HostNet.tetherLoad + rw [site_arity] + change _ = (exterior H.diagram H.units.place v : ℝ) + degree p v + _ + _ + rw [deg, Nat.cast_mul] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Each tether uses a distinct port of its frozen table -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Freeze + +variable {F : Type} {a b : Wire} {G : Diagram F a b} (Z : Freeze G) + +open scoped Classical in +theorem cover (t : Z.Fixed) : + Fintype.card {q // Z.border.tensor q = t} ≤ G.arity t.val := by + let endpt : slots Z.x ⊕ slots Z.y → G.End + | .inl i => .inr (.inr (Z.input i).val) + | .inr i => .inl (.inr (Z.output i).val) + have loc q : G.station (endpt q) = (Z.border.tensor q).val := by cases q <;> rfl + have hi : Function.Injective endpt := by + rintro (i|i) (j|j) h + · exact congrArg Sum.inl (Z.input.injective (Subtype.ext (Sum.inr.inj (Sum.inr.inj h)))) + · cases h + · cases h + · exact congrArg Sum.inr (Z.output.injective (Subtype.ext (Sum.inr.inj (Sum.inl.inj h)))) + let f (q : {q // Z.border.tensor q = t}) : {e // G.station e = t.val} := + ⟨endpt q.val, (loc _).trans (congrArg Subtype.val q.property)⟩ + rw [← G.degree] + exact Fintype.card_le_of_injective f fun _ _ h => Subtype.ext (hi (congrArg Subtype.val h)) + +open scoped Classical in +/-- Builds `Fringe Z.x Z.y Z.Fixed where tensor` with the specified `tensor`, `charge`, `cover`, +`scale`. -/ +def fringe (charge : Z.Fixed → ℝ) (hc : ∀ t, (G.arity t.val : ℝ) ≤ charge t) + (s : ℝ) (hs : 0 < s) (hs' : s ≤ 1) : Fringe Z.x Z.y Z.Fixed where + tensor := Z.border.tensor + charge := charge + cover t := by convert! (Nat.cast_le.mpr (Z.cover t)).trans (hc t) using 3 + scale := s + pos := hs + le := hs' + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Freeze +end + +/- +# Placing the split diagram on its block host + +Uniform internal multiplicities suffice to construct the core bundles. +The two exterior legs of the core consist precisely of its tethers. +Every other leg stays attached to the original frozen table. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Freeze + +variable {F : Type} {a b : Wire} {G : Diagram F a b} (Z : Freeze G) + +open scoped Classical in +/-- The data for the frame construction, including `place`, `frozen`, `keep`, `N`, `C`. -/ +structure Frame (V : Type) (h : ℕ) where + /-- The `Frame` component of type `G.V → V × Cell h`. -/ + place : G.V → V × Cell h + /-- The `Frame` component of type `V → Prop`. -/ + frozen : V → Prop + keep : ∀ v, frozen (place v).1 ↔ Z.frozen v + /-- The `Frame` component of type `V → Finset V`. -/ + N : V → Finset V + /-- The `Frame` component of type `V → Finset V`. -/ + C : V → Finset V + ns : ∀ v z, z ∈ N v → v ∈ N z + cs : ∀ v z, z ∈ C v → v ∈ C z + sub : ∀ v, C v ⊆ N v + group : ∀ e, (place (G.source e)).2 = (place (G.target e)).2 + edge : ∀ e : Z.Internal, (place (G.target e.val)).1 ∈ C (place (G.source e.val)).1 + full : ∀ e, (place (G.target e)).1 ∈ N (place (G.source e)).1 + +namespace Frame + +variable {V : Type} {h u : ℕ} {Z} (H : Z.Frame V h) (hu : 0 < u) (hd : Z.Divisible u) + (L : Fringe Z.x Z.y Z.Fixed) (hL : L.tensor = Z.border.tensor) + +open scoped Classical in +theorem tether (q : slots Z.x ⊕ slots Z.y) : + let p := H.place (portEnd Z.core q).val + let z := H.place (Z.border.tensor q).val + ¬H.frozen p.1 ∧ p.2 = z.2 ∧ z.1 ∈ H.N p.1 := by + refine ⟨mt (H.keep _).mp (portEnd Z.core q).property, ?_⟩ + cases q with + | inl i => exact ⟨H.group (Z.input i).val, H.full (Z.input i).val⟩ + | inr i => exact ⟨(H.group (Z.output i).val).symm, H.ns _ _ (H.full (Z.output i).val)⟩ + +variable [Fintype V] + +open scoped Classical in +/-- The caller may specify the ordering within each packet. -/ +def hostOf (r : Packets Z.core u) : HostNet F L h u := by + let p (v : Z.Core) := H.place v.val + have hh (e : r.E) : (p (r.src e)).2 = (p (r.dst e)).2 ∧ + (p (r.dst e)).1 ∈ H.C (p (r.src e)).1 := by + obtain ⟨j, hj⟩ := r.bits.surjective (e, ⟨0, hu⟩) + have hs := r.left j + have ht := r.right j + rw [hj] at hs ht + rw [hs, ht] + exact ⟨H.group j.val, H.edge j⟩ + exact { + diagram := Z.core + V := V + E := r.E + src e := (p (r.src e)).1 + dst e := (p (r.dst e)).1 + ix e := (p (r.src e)).2 + units := { + place := p + bits := r.bits + left e := by rw [r.left] + right e := by rw [(hh _).1, r.right] } + park t := H.place t.val + frozen := H.frozen + N := H.N, C := H.C, ns := H.ns, cs := H.cs, sub := H.sub + kept t := (H.keep _).mpr t.property + core e := ⟨mt (H.keep _).mp (r.src e).property, mt (H.keep _).mp (r.dst e).property⟩ + edge e := (hh e).2 + tether q := by rw [hL]; exact H.tether q } + +open scoped Classical in +/-- Computes the host by the application `H.hostOf hu L hL (Classical.choice (Z.bundles hd))`. -/ +def host : HostNet F L h u := + H.hostOf hu L hL (Classical.choice (Z.bundles hd)) + +open scoped Classical in +theorem host_load (p : V × Cell h) : + (H.host hu hd L hL).load p.1 p.2 = + push (fun v : Z.Core => H.place v.val) (fun v => (G.arity v.val : ℝ)) p + + L.scale * push (fun t : Z.Fixed => H.place t.val) L.charge p := + by + have ht := HostNet.load_eq (H.host hu hd L hL) p + rw [show (H.host hu hd L hL).past p = 0 from rfl, Nat.cast_zero, mul_zero, add_zero] at ht + exact ht + +end Frame +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Freeze +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/HostReset.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/HostReset.lean new file mode 100644 index 0000000000..dbb64cb560 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/HostReset.lean @@ -0,0 +1,971 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import Mathlib.Algebra.BigOperators.Field +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rule +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.ResetLocation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.TetherHost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.RestoreCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection + +/-! +# The result of resetting a host + +Group-prefixed endpoints keep distinct blocks independent. The common +host contains both core links and possible tethers. Width is measured +in the same unit before and after the reset. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +variable {V U : Type} [Fintype V] [Fintype U] {h : ℕ} + +/-- The data for the reset result construction, including `vertex`, `wire`, `[fv`, `[fw`, +`core`. -/ +structure ResetResult (F : Type) [Field F] (a : ℕ) (N : V → Finset V) + (src dst : U → V) (ix : U → Cell h) (l : V → Cell h → ℝ) + (u B W : ℝ) (H D : ℕ) where + /-- The placement of the vertices carried by `ResetResult`, with type `Type`. -/ + vertex : Type + /-- The `ResetResult` component of type `Type`. -/ + wire : Type + [fv : Fintype vertex] + [fw : Fintype wire] + /-- The `ResetResult` component of type `vertex → Finset vertex`. -/ + core : vertex → Finset vertex + /-- The `ResetResult` component of type `vertex → Finset vertex`. -/ + full : vertex → Finset vertex + core_symm : ∀ v w, w ∈ core v → v ∈ core w + full_symm : ∀ v w, w ∈ full v → v ∈ full w + sub : ∀ v, core v ⊆ full v + core_degree : ∀ v, (core v).card ≤ 3 + full_degree : ∀ v, (full v).card ≤ D + positions : Fintype.card vertex ≤ H * 2 ^ (h - a) * Fintype.card V + le : a ≤ h + /-- Reindexes the data using `Cell h ≃ₗ[ZMod 2] Cell h`. -/ + mix : Cell h ≃ₗ[ZMod 2] Cell h + /-- The owner assigned to each element of type `V × Cell h → Cell a × vertex`. -/ + owner : V × Cell h → Cell a × vertex + /-- The starting coordinate of type `vertex → V`. -/ + origin : vertex → V + uniform : ∃ (Y : Type) (_ : Fintype Y) (e : vertex ≃ V × Y), ∀ t, (e t).1 = origin t + group : ∀ p, (owner p).1 = ancestor le (mix p.2) + origin_owner : ∀ p, origin (owner p).2 = p.1 + tether : ∀ v z, z ∈ N v → ∀ x, (owner (z, x)).2 ∈ full (owner (v, x)).2 + /-- The supplied data of type `wire → (Cell a × vertex) × (Cell a × vertex)`. -/ + supply : wire → (Cell a × vertex) × (Cell a × vertex) + support : ∀ e, (supply e).1.1 = (supply e).2.1 ∧ (supply e).2.2 ∈ core (supply e).1.2 + active : ∀ e t, ∃ q, src q = origin (cond t (supply e).2 (supply e).1).2 ∨ + dst q = origin (cond t (supply e).2 (supply e).1).2 + /-- The `ResetResult` component of type `Spectral.Packet.Rule F (fun i => (owner (src i, ix + i), owner (dst i, ix i))) (fun _ : Unit => supply)`. -/ + rule : Spectral.Packet.Rule F (fun i => (owner (src i, ix i), owner (dst i, ix i))) + (fun _ : Unit => supply) + cost : Fintype.card wire * u ≤ W * (Fintype.card V * (2 : ℝ) ^ a * B + ∑ v, ∑ x, l v x) + load : ∀ p, push owner (Function.uncurry l) p + degree supply p * u ≤ 89 * B + +attribute [instance] ResetResult.fv ResetResult.fw + +/-- Undo the normalization by a single base's capacity. -/ +noncomputable def ResetResult.unscale {F : Type} [Field F] {a H D : ℕ} {N : V → Finset V} + {src dst : U → V} {ix : U → Cell h} {l : V → Cell h → ℝ} {u B W : ℝ} (hb : 0 < B) + (G : ResetResult F a N src dst ix (fun v x => l v x / B) (u / B) 1 W H D) : + ResetResult F a N src dst ix l u B W H D := by + refine { G with cost := ?_, load := ?_ } + · have hc := G.cost + simp only [mul_one, ← Finset.sum_div] at hc + calc + _ = (Fintype.card G.wire : ℝ) * (u / B) * B := by field_simp + _ ≤ _ := (mul_le_mul_of_nonneg_right hc hb.le).trans_eq (by field_simp) + · intro p + have hc := G.load p + rw [show Function.uncurry (fun v x => l v x / B) = fun p => Function.uncurry l p / B from rfl, + push_div, ← mul_div_assoc, ← add_div, mul_one, div_le_iff₀ hb] at hc + exact hc + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# The reset as an exact wire packet + +Good contacts use the fixed reserved links. Exceptional ones have their +own paths in the contact trees. All sites project to a group and a slot +in the common trivalent host. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Schedule + +open Finset + +variable {V A U F : Type} [Fintype V] [Fintype U] [Field F] {h a k Y w L : ℕ} +variable {T : Demands V A U h} {N : V → Finset V} {d : V → V → ℕ} +variable {l : V → Cell h → ℝ} {u g ε : ℝ} +variable (Z : Schedule T N d a k l u g ε) {o : Z.Plugs Y} +variable (D : Z.Dispatch o w) (R : Rotor F Y w) + +-- Freeze the same finite enumeration as the delivery packet. +open scoped Classical in +instance {P U' X W : Type} [Fintype P] [Fintype X] [Fintype U'] + {leaf : P → X} {point : U' → Bool → P} {good : U' → Prop} + {edge : U' → W} {outLeaf : W → Bool → X} {cap : W → ℝ} + {out : ∀ x, Port outLeaf cap Y x ↪ Fin Y} {l' : P → ℝ} + (p : Delivery leaf point good edge outLeaf cap Y w out l' u) : + Fintype (p.Wires R) := inferInstance + +open scoped Classical in +/-- The quantity computed by `R.Host (Site V (h - a)) L`. -/ +abbrev Space (V : Type) (h a L : ℕ) := R.Host (Site V (h - a)) L + +open scoped Classical in +/-- The value specified by `((Z.leaf p).drop a, D.terminal p)`. -/ +def terminal (p : V × Cell h) := ((Z.leaf p).drop a, D.terminal p) + +open scoped Classical in +/-- The value specified by `(Z.group p.2, R.input (Z.terminal D p))`. -/ +def owner (p : V × Cell h) : Cell a × Space R V h a L := + (Z.group p.2, R.input (Z.terminal D p)) + +open scoped Classical in +/-- The value specified by `(x.1.group a, Sum.inl (x.1.drop a, x.2))`. -/ +def mainPlace (x : Site V h × R.Hardware) : Cell a × Space R V h a L := + (x.1.group a, Sum.inl (x.1.drop a, x.2)) + +open scoped Classical in +/-- The value specified by `(x.1, R.hub x.2)`. -/ +def treePlace (x : Cell a × Detour.Hub (Site V (h - a) × Fin Y) L) : Cell a × Space R V h a L := + (x.1, R.hub x.2) + +open scoped Classical in +theorem place_source (q : {i // Z.good i}) (t : Bool) : + mainPlace R (D.source R q t) = Z.owner (L := L) D R (T.point q.val t) := by + exact Prod.ext (Z.group_end _ t) rfl + +variable (sw : Detour.Switch (Site V (h - a) × Fin Y) L) +variable (ok : ∀ i : U, Z.terminal D (T.point i true) ∈ sw.near (Z.terminal D (T.point i false))) + +open scoped Classical in +/-- The subtype of `i : U` satisfying `¬Z.good i`. -/ +abbrev Exceptional := {i : U // ¬Z.good i} +open scoped Classical in +/-- Indexes the wires by the coordinates of `D.Wires R ⊕ (Fin (Detour.steps L) × +Z.Exceptional)`. -/ +abbrev Wires := D.Wires R ⊕ (Fin (Detour.steps L) × Z.Exceptional) + +open scoped Classical in +/-- The indexed operation `sw.route (fun i : Z.Exceptional => Z.group (T.ix i.val)) (fun i t => +Z.terminal D (T.point i.val t)) (fun i => ok i.val)`. -/ +def treeRoute := sw.route (fun i : Z.Exceptional => Z.group (T.ix i.val)) + (fun i t => Z.terminal D (T.point i.val t)) (fun i => ok i.val) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def supply : Z.Wires (L := L) D R → (Cell a × Space R V h a L) × (Cell a × Space R V h a L) := + Sum.elim (fun e => Prod.map (mainPlace R) (mainPlace R) (D.supply R e)) + (fun e => Prod.map (treePlace R) (treePlace R) (Z.treeRoute D sw ok e)) + +open scoped Classical in +/-- The rule used in the `Schedule` construction. -/ +def rule : + Spectral.Packet.Rule F (fun i => (Z.owner D R (T.point i false), Z.owner D R (T.point i true))) + (fun _ : Unit => Z.supply D R sw ok) := by + have hf := D.deployRule R + have hp := hf.place (mainPlace (V := V) (h := h) (a := a) (L := L) R) + apply Spectral.Packet.Rule.partition Z.good + · exact hp.congr (by simp only [Z.place_source]) rfl + · exact (sw.rule (fun i : Z.Exceptional => Z.group (T.ix i.val)) + (fun i t => Z.terminal D (T.point i.val t)) (fun i => ok i.val) F).place (treePlace R) + +open scoped Classical in +theorem supported (e : Z.Wires (L := L) D R) : + let z := Z.supply D R sw ok e + z.1.1 = z.2.1 ∧ z.2.2 ∈ R.links sw (peer o) z.1.2 := by + cases e with + | inl e => + refine ⟨D.same_group R (Site.group a) (fun i _ => ?_) e, R.links_net sw _ ?_⟩ + · rw [Z.group_end, Z.group_end] + · exact D.supply_mem R (Site.drop a) (peer o) (fun q => D.peer_relative q false) e + | inr e => + have ha := sw.route_adj (fun i : Z.Exceptional => Z.group (T.ix i.val)) + (fun i t => Z.terminal D (T.point i.val t)) (fun i => ok i.val) e + exact ⟨ha.1, R.links_detour sw _ ha.2⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Schedule +end + +/- # Incidence budget on the permutation hardware -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +open scoped Classical in +private theorem add_degree {S A B : Type} [Fintype A] [Fintype B] + (f : A → S × S) (g : B → S × S) (v : S) : + degree (Sum.elim f g) v = degree f v + degree g v := by + rw [degree_sum, degree_sum, degree_sum, Fintype.sum_sum_type] + rfl + +variable {F : Type} [Field F] {Y w n : ℕ} (R : Rotor F Y w) + +namespace Rotor + +open scoped Classical in +private theorem walk_inj (t : Bool) (i : Fin Y) (j : Fin w) {k l : ℕ} + (hk : k ≤ Nat.clog 2 w + 1) (hl : l ≤ Nat.clog 2 w + 1) + (he : R.walk t i j k = R.walk t i j l) : k = l := by + cases k <;> cases l + · rfl + · cases he + · cases he + · rename_i k l + have eq : Tree.climb j k = Tree.climb j l := by simpa [walk] using he + exact congrArg (fun a => a.val + 1) + (Tree.climb_injective j (a₁ := ⟨k, by omega⟩) (a₂ := ⟨l, by omega⟩) eq) + +open scoped Classical in +private theorem layer_degree (v : R.Hardware) : + Packing.degree (R.layerEdge (n := n)) v ≤ 3 * n := by + rw [degree_sum, Fintype.sum_sigma] + calc + _ ≤ ∑ _i : Fin n, 3 := by + apply sum_le_sum + intro i _ + rcases v with v | v + · have ht : (∑ e, if R.pos e = v then 1 else 0) ≤ 3 := by + simpa only [sum_boole, Nat.cast_id, Fintype.card_subtype] using R.degree v + simp only [Fintype.sum_sum_type] at ht + simp only [arityCost, layerEdge, edge, Sum.inl.injEq, sum_add_distrib] + omega + · simp [arityCost, layerEdge] + _ = _ := by simp [mul_comm] + +variable {A : Type} [Fintype A] (p q : A → Fin Y) (lane : A → Fin n × Fin w) + +open scoped Classical in +/-- A path visits each vertex at most once, hence contributes at most +two incidences there. -/ +private theorem path_degree (t : Bool) (v : R.Hardware) : + Packing.degree (R.pathEdge t p lane) v ≤ 2 * Fintype.card A := by + let : DecidableEq R.Hardware := Classical.typeDecidableEq _ + have once (a : A) (k : ℕ) (hk : k ≤ 1) : + (∑ j : Fin (Nat.clog 2 w + 1), if R.walk t (p a) (lane a).2 (j.val + k) = v then 1 else 0) + ≤ 1 := by + rw [sum_boole, Nat.cast_id] + apply card_le_one.mpr + intro i hi j hj + have he := (mem_filter.mp hi).2.trans (mem_filter.mp hj).2.symm + exact Fin.ext (Nat.add_right_cancel (R.walk_inj _ _ _ (by omega) (by omega) he)) + rw [degree_sum, Fintype.sum_prod_type, sum_comm] + calc + _ ≤ ∑ _a : A, 2 := by + refine sum_le_sum fun a _ => ?_ + simp only [arityCost, pathEdge, sum_add_distrib] + exact Nat.add_le_add (once a 0 (by decide)) (once a 1 le_rfl) + _ = _ := by simp [mul_comm] + +open scoped Classical in +theorem supply_degree (v : R.Hardware) : + Packing.degree (R.supply p q lane) v ≤ 3 * n + 4 * Fintype.card A := by + rw [supply, add_degree, add_degree] + have := R.layer_degree (n := n) v + have := R.path_degree p lane false v + have := R.path_degree q lane true v + omega + +end Rotor + +namespace Delivery + +variable {P U X W : Type} [Fintype P] [Fintype U] [Fintype X] + {leaf : P → X} {point : U → Bool → P} {good : U → Prop} + {edge : U → W} {outLeaf : W → Bool → X} {cap : W → ℝ} + {out : ∀ x, Port outLeaf cap Y x ↪ Fin Y} {l : P → ℝ} {u : ℝ} + (d : Delivery leaf point good edge outLeaf cap Y w out l u) + +open scoped Classical in +private theorem degree_inside (x : X) (v : R.Hardware) : + degree (d.inside R) (x, v) = degree (R.supply (d.inputAt x) (d.outputAt x) (d.lane x)) v := by + let : DecidableEq R.Hardware := Classical.typeDecidableEq _ + rw [degree_sum, degree_sum, Fintype.sum_sigma, sum_eq_single x] + · simp only [inside, arityCost, Prod.mk.injEq, true_and] + exact sum_congr rfl (fun _ _ => by congr 1) + · intro y _ hy + simp [inside, arityCost, hy] + · simp + +omit [Fintype X] in +open scoped Classical in +private theorem degree_links (x : X) (v : R.Hardware) : + degree (fun q => (d.target R q false, d.target R q true)) (x, v) ≤ + Fintype.card (GoodEnd leaf point good x) := by + let : DecidableEq (X × R.Hardware) := Classical.typeDecidableEq _ + have hb : (∑ q : {i // good i}, ∑ t : Bool, if leaf (point q.val t) = x then 1 else 0) = + Fintype.card (GoodEnd leaf point good x) := by + rw [Fintype.card_subtype, card_eq_sum_ones, sum_filter, Fintype.sum_prod_type] + have h (q : {i // good i}) (t : Bool) : + (if d.target R q t = (x, v) then 1 else 0) ≤ if leaf (point q.val t) = x then 1 else 0 := by + by_cases ht : d.target R q t = (x, v) + · have he : leaf (point q.val t) = x := congrArg Prod.fst ht + simp [he, ht] + · simp [ht] + rw [degree_sum, ← hb] + apply sum_le_sum + intro q _ + rw [Fintype.sum_bool, add_comm] + unfold arityCost + exact Nat.add_le_add (h q false) (h q true) + +open scoped Classical in +/-- Bound both endpoints of all supply wires on each absolute host site. +This includes repeated incidences and both ends of a loop. -/ +theorem incidence (hY : 0 < Y) (hw : 0 < w) (x : X × R.Hardware) : + degree (d.supply R) x ≤ 8 * (d.layers x.1 * Y * w) := by + obtain ⟨x, v⟩ := x + rw [supply, add_degree, degree_inside] + have hi := R.supply_degree (d.inputAt x) (d.outputAt x) (d.lane x) v + have hd := degree_links R d x v + have he := d.card_ends x + have hl : d.layers x ≤ d.layers x * Y * w := + (Nat.le_mul_of_pos_right _ hY).trans (Nat.le_mul_of_pos_right _ hw) + change _ ≤ 8 * (d.layers x * Y * w) + omega + +end Delivery +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Per-site bounds on loads and wires in the reset packet -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Schedule + +open Finset + +variable {V A U F : Type} [Fintype V] [Fintype U] [Field F] {h a k Y w L : ℕ} +variable {T : Demands V A U h} {N : V → Finset V} {d : V → V → ℕ} +variable {l : V → Cell h → ℝ} {u g ε : ℝ} +variable (Z : Schedule T N d a k l u g ε) {o : Z.Plugs Y} +variable (D : Z.Dispatch o w) (R : Rotor F Y w) + +open scoped Classical in +private def dest (p : V × Cell h) := (Z.group p.2, Z.terminal D p) + +open scoped Classical in +private theorem leaf_of_dest {p q : V × Cell h} (e : Z.dest D p = Z.dest D q) : + Z.leaf p = Z.leaf q := by + apply Site.group_drop (Z.leaf_depth p) (Z.leaf_depth q) + · rw [Z.leaf_group, Z.leaf_group] + exact congrArg Prod.fst e + · exact congrArg (fun z => z.2.1) e + +open scoped Classical in +private theorem leaf_bound {X : Type} (f : V × Cell h → X) + (he : ∀ p q, f p = f q → Z.leaf p = Z.leaf q) (x : X) : + push f (Function.uncurry l) x ≤ 3 := by + by_cases h : ∃ p, f p = x + · obtain ⟨p, rfl⟩ := h + refine le_trans ?_ ((Z.at_leaf (Z.leaf p)).trans (by norm_num)) + unfold push + apply sum_le_sum + intro q _ + by_cases hc : f q = f p + · rw [ite_eq_left hc, ite_eq_left (he _ _ hc)] + · rw [ite_eq_right hc] + split_ifs <;> first | exact (Z.sizes _ _).1 | exact le_rfl + · push Not at h + simp [push, h] + +open scoped Classical in +theorem owner_load (p : Cell a × Space R V h a L) : + push (Z.owner D R) (Function.uncurry l) p ≤ 3 := by + apply Z.leaf_bound + intro q r he + apply Z.leaf_of_dest D + obtain ⟨h₁, h₂⟩ := Prod.mk.inj he + exact Prod.ext h₁ (R.input_injective h₂) + +open scoped Classical in +private theorem core_load (z : Cell a × (Site V (h - a) × Fin Y)) : + degree (fun i => (Z.dest D (T.point i false), Z.dest D (T.point i true))) z * u ≤ 3 := by + rw [degree_push (fun i t => Z.dest D (T.point i t))] + change push (Z.dest D ∘ Function.uncurry T.point) _ _ ≤ _ + rw [← push_comp] + exact (push_le_push (Z.dest D) (fun p => Z.mass p.1 p.2) z).trans + (Z.leaf_bound _ (fun _ _ => Z.leaf_of_dest D) z) + +open scoped Classical in +private theorem main_degree (hY : 0 < Y) (hw : 0 < w) (z : Cell a × Space R V h a L) : + degree (fun e => Prod.map (mainPlace R) (mainPlace R) (D.supply R e)) z * u ≤ 80 := by + apply degree_le_map (D.supply R) (mainPlace R) (fun x => a ≤ x.1.depth) u 80 (by norm_num) + · intro x + have cost {i n : ℕ} (hi : i ≤ 8 * (n * Y * w)) (hn : (n : ℝ) * Y * w * u ≤ 10) : + (i : ℝ) * u ≤ 80 := by + have hc : (i : ℝ) ≤ 8 * ((n : ℝ) * Y * w) := by exact_mod_cast hi + linarith only [mul_le_mul_of_nonneg_right hc Z.width.le, hn] + exact cost (D.incidence R hY hw x) (D.cost x.1) + · intro x hx + have hempty : IsEmpty (GoodEnd Z.leaf T.point Z.good x.1) := + ⟨fun p => hx (p.property ▸ Z.leaf_depth _)⟩ + simpa only [D.empty x.1 hempty, zero_mul, mul_zero, Nat.le_zero] using D.incidence R hY hw x + · intro x hx y hy he + obtain ⟨hg, he'⟩ := Prod.mk.inj he + obtain ⟨hd, hr⟩ := Prod.mk.inj (Sum.inl.inj he') + exact Prod.ext (Site.group_drop hx hy hg hd) hr + +variable (sw : Detour.Switch (Site V (h - a) × Fin Y) L) +variable (ok : ∀ i : U, Z.terminal D (T.point i true) ∈ sw.near (Z.terminal D (T.point i false))) + +open scoped Classical in +private theorem tree_degree (z : Cell a × Space R V h a L) : + degree (fun e => Prod.map (treePlace R) (treePlace R) (Z.treeRoute D sw ok e)) z * u ≤ 6 := by + apply degree_le_map _ _ (fun _ => True) _ _ (by norm_num) + · intro p + let v := (p.1, Detour.owner p.2) + let f i := (Z.dest D (T.point i false), Z.dest D (T.point i true)) + let e : Z.Exceptional ↪ U := ⟨Subtype.val, Subtype.val_injective⟩ + have ht : degree (Z.treeRoute D sw ok) p ≤ 2 * degree (f ∘ e) v := + sw.route_degree (fun i : Z.Exceptional => Z.group (T.ix i.val)) + (fun i t => Z.terminal D (T.point i.val t)) (fun i => ok i.val) p + have hi : (degree (Z.treeRoute D sw ok) p : ℝ) ≤ 2 * degree f v := by + exact_mod_cast ht.trans (Nat.mul_le_mul_left 2 (degree_select f e v)) + have hc : degree f v * u ≤ 3 := Z.core_load D v + linarith only [mul_le_mul_of_nonneg_right hi Z.width.le, hc] + · simp + · intro x _ y _ he + obtain ⟨hg, hx⟩ := Prod.mk.inj he + exact Prod.ext hg (R.hub_injective hx) + +open scoped Classical in +theorem incidence (hY : 0 < Y) (hw : 0 < w) (p : Cell a × Space R V h a L) : + degree (Z.supply D R sw ok) p * u ≤ 86 := by + rw [supply, degree_partition, Nat.cast_add, add_mul] + linarith only [Z.main_degree D R hY hw p, Z.tree_degree D R sw ok p] + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def origin : Space R V h a L → V := + Sum.elim (fun z => z.1.1) (fun z => z.1.1.1) + +open scoped Classical in +/-- No core wiring is introduced at a frozen host position. -/ +theorem active (e : Z.Wires (L := L) D R) (t : Bool) : + ∃ q b, (T.point q b).1 = + origin R (cond t (Z.supply D R sw ok e).2 (Z.supply D R sw ok e).1).2 := by + rcases e with (⟨x, e⟩ | q) | ⟨i, q⟩ + · have hn : Nonempty (GoodEnd Z.leaf T.point Z.good x) := by + rcases e with e | e | e + · exact ⟨e.2⟩ + · by_contra h + have he := D.empty x (not_nonempty_iff.mp h) + have := e.1.isLt + omega + · exact ⟨e.2⟩ + obtain ⟨p⟩ := hn + have hp := congrArg Prod.fst p.property + refine ⟨p.val.1.val, p.val.2, ?_⟩ + cases t <;> exact hp + · exact ⟨q.val, t, by cases t <;> rfl⟩ + · have hub (s : Detour.Hub (Site V (h - a) × Fin Y) L) : + origin R (R.hub s) = (Detour.owner s).1.1 := by cases s <;> rfl + have path (n : ℕ) : + ∃ b, (T.point q.val b).1 = origin R (R.hub (sw.path (ok q.val) n)) := by + rw [hub, sw.path_owner] + split_ifs + · exact ⟨true, rfl⟩ + · exact ⟨false, rfl⟩ + refine ⟨q.val, ?_⟩ + cases t + · exact path i.val + · exact path (i.val + 1) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Schedule +end + +/- # Total core width after the degree reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Schedule + +open Finset + +variable {V A U F : Type} [Fintype V] [Fintype U] [Field F] {h a k Y w L : ℕ} +variable {T : Demands V A U h} {N : V → Finset V} {d : V → V → ℕ} +variable {l : V → Cell h → ℝ} {u g ε : ℝ} +variable (Z : Schedule T N d a k l u g ε) {o : Z.Plugs Y} +variable (D : Z.Dispatch o w) (R : Rotor F Y w) + +open scoped Classical in +/-- Width is measured relative to the capacity of one base. -/ +theorem total_cost (c : ℝ) (hc : 0 ≤ c) (hR : (Fintype.card R.E : ℝ) ≤ c * Y * w) + (he : Detour.steps L * ε ≤ 1) : + (Fintype.card (Z.Wires (L := L) D R) : ℝ) * u ≤ + (40 * (c + 2 * (Nat.clog 2 w + 1) + 1) + 1) * + (Fintype.card V * (2 : ℝ) ^ a + ∑ v, ∑ x, l v x) := by + let A := (univ : Finset (Σ v, Cell (Z.base v))).image (baseSite Z.base Z.depth) + have act i (hi : Z.good i) t : Z.leaf (T.point i t) ∈ A := by + rw [Z.routes i hi t] + exact mem_image_of_mem _ (mem_univ _) + let M := ∑ v, ∑ x, l v x + have hM : 0 ≤ M := sum_nonneg fun v _ => sum_nonneg fun x _ => (Z.sizes v x).1 + let X := Fintype.card V * (2 : ℝ) ^ a + have hX : 0 ≤ X := by unfold X; positivity + have count : (A.card : ℝ) ≤ 4 * (X + M) := calc + _ ≤ (Fintype.card (Σ v, Cell (Z.base v)) : ℝ) := Nat.cast_le.mpr card_image_le + _ ≤ 2 * X + 4 * M := by + simp only [Fintype.card_sigma, card_cell, Nat.cast_sum, Nat.cast_pow, Nat.cast_ofNat] + simpa only [X, M, mul_assoc] using Z.count + _ ≤ _ := by linarith + let C : ℝ := c + 2 * (Nat.clog 2 w + 1) + 1 + have hC : 0 ≤ C := by unfold C; positivity + have hr : (Fintype.card (D.Wires R) : ℝ) * u ≤ 40 * C * (X + M) := calc + _ ≤ 10 * C * A.card := D.width_le R c hc Z.width.le hR A act + _ ≤ 10 * C * (4 * (X + M)) := mul_le_mul_of_nonneg_left count (by positivity) + _ = _ := by ring + have ex : (Fintype.card Z.Exceptional : ℝ) * u ≤ ε * M := by + have hy := Z.exceptional + unfold Exceptional + rw [Fintype.card_subtype, ← nsmul_eq_mul, ← sum_const, sum_filter] + simpa only [ite_not] using hy + have hd : (Detour.steps L : ℝ) * (Fintype.card Z.Exceptional : ℝ) * u ≤ X + M := calc + _ ≤ (Detour.steps L : ℝ) * (ε * M) := by + rw [mul_assoc] + exact mul_le_mul_of_nonneg_left ex (by positivity) + _ ≤ M := by rw [← mul_assoc]; exact mul_le_of_le_one_left hM he + _ ≤ X + M := le_add_of_nonneg_left hX + change _ ≤ (40 * C + 1) * (X + M) + unfold Wires + rw [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, Nat.cast_add, Nat.cast_mul, add_mul] + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Schedule +end + +/- +# Resetting the core degree + +The rotor and the core degree determine the depth, load and position +overheads. The full degree, which counts tethers, enters only the bound +on the new full degree. Every core demand is transmitted exactly. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {F V U : Type} [Field F] [Fintype V] [Fintype U] {Y w Δ D h a k : ℕ} + +open scoped Classical in +/-- The quantity computed by `40 * (c + 2 * (Nat.clog 2 w + 1) + 1) + 1`. -/ +def resetWidth (c : ℝ) (w : ℕ) := 40 * (c + 2 * (Nat.clog 2 w + 1) + 1) + 1 + +open scoped Classical in +/-- The quantity computed by `2 * (Fintype.card R.Hardware + Y * Fintype.card (Tree.Node +(terminalWidth Δ Y)))`. -/ +def resetPositions (R : Rotor F Y w) (Δ : ℕ) := + 2 * (Fintype.card R.Hardware + Y * Fintype.card (Tree.Node (terminalWidth Δ Y))) + +open scoped Classical in +/-- Indexes the address by the coordinates of `Σ i : Fin (h + 1), Cell i.val`. -/ +abbrev Schedule.Address (h : ℕ) := Σ i : Fin (h + 1), Cell i.val + +open scoped Classical in +/-- In the case `.inl ((v, j), z)`, this construction gives `(v, .inl (j, z))`. -/ +def Schedule.splitHost (R : Rotor F Y w) (a h L : ℕ) : + Schedule.Space R V h a L ≃ V × R.Host (Schedule.Address (h - a)) L where + toFun + | .inl ((v, j), z) => (v, .inl (j, z)) + | .inr (((v, j), t), r) => (v, .inr ((j, t), r)) + invFun + | (v, .inl (j, z)) => .inl ((v, j), z) + | (v, .inr ((j, t), r)) => .inr (((v, j), t), r) + left_inv := by rintro (x|y) <;> rfl + right_inv := by rintro ⟨v, x|y⟩ <;> rfl + +open scoped Classical in +theorem size_limit (R : Rotor F Y w) : + Fintype.card (Schedule.Space R V h a (terminalWidth Δ Y)) ≤ + resetPositions R Δ * 2 ^ (h - a) * Fintype.card V := by + unfold Schedule.Space Rotor.Host + unfold resetPositions + calc + _ = Fintype.card (Site V (h - a)) * + (Fintype.card R.Hardware + Y * Fintype.card (Tree.Node (terminalWidth Δ Y))) := by + simp only [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + ring + _ ≤ (2 * 2 ^ (h - a) * Fintype.card V) * + (Fintype.card R.Hardware + Y * Fintype.card (Tree.Node (terminalWidth Δ Y))) := + Nat.mul_le_mul_right _ (Site.card _ _) + _ = _ := by ring + +open scoped Classical in +/-- The result of type `ResetResult F a N src dst ix l u 1 (resetWidth c w) (resetPositions R Δ) +(3 + terminalWidth D Y)`, constructed using `terminalWidth Δ Y`. -/ +def Schedule.result {N C : V → Finset V} {src dst : U → V} {ix : U → Cell h} + {edge : ∀ i, dst i ∈ C (src i)} {l : V → Cell h → ℝ} {u g ε : ℝ} + (Z : Schedule (coreDemands ix edge) N (resetDelay C Δ D) a k l u g ε) + {o : Z.Plugs Y} (q : Z.Dispatch o w) (R : Rotor F Y w) (hY : 0 < Y) (hw : 0 < w) + (hΔ : 0 < Δ) (hD : Δ ≤ D) + (ns : ∀ v z, z ∈ N v → v ∈ N z) (cs : ∀ v z, z ∈ C v → v ∈ C z) + (sub : ∀ v, C v ⊆ N v) (ndeg : ∀ v, (N v).card ≤ D) + (pin : ∀ x : Site V (h - a) × Fin Y, ↥(terminalNear C Δ Y x) ↪ Fin (terminalWidth Δ Y)) + (c : ℝ) (hc : 0 ≤ c) (hR : (Fintype.card R.E : ℝ) ≤ c * Y * w) + (he : Detour.steps (terminalWidth Δ Y) * ε ≤ 1) : + ResetResult F a N src dst ix l u 1 (resetWidth c w) + (resetPositions R Δ) (3 + terminalWidth D Y) := by + let L := terminalWidth Δ Y + let sw : Detour.Switch (Site V (h - a) × Fin Y) L := + ⟨terminalNear C Δ Y, terminal_symm cs _ _, pin⟩ + have ok (i : U) : Z.terminal q (dst i, ix i) ∈ sw.near (Z.terminal q (src i, ix i)) := + mem_product.mpr ⟨Z.leaf_near cs sub (fun _ _ he => by simp [he]) (edge i) (ix i), mem_univ _⟩ + let A := terminalNear (h := h - a) N D Y + refine { + vertex := Schedule.Space R V h a L + wire := Z.Wires (L := L) q R + core := R.links sw (peer o) + full := R.full sw (peer o) A + core_symm := R.links_symm sw _ (peer_involutive o) + full_symm := R.full_symm sw _ _ (peer_involutive o) (terminal_symm ns _ _) + sub := R.links_sub sw _ _ + core_degree := R.links_degree sw _ + full_degree := R.full_degree sw _ _ (terminal_card _ _ _ (hΔ.trans_le hD) ndeg) + positions := size_limit R + le := (Nat.le_add_right _ _).trans Z.block + mix := Z.π + owner := Z.owner q R + origin := Schedule.origin R + uniform := ⟨_, inferInstance, Schedule.splitHost R a h L, by rintro (x|y) <;> rfl⟩ + group := fun _ => rfl + origin_owner := fun _ => rfl + tether := ?_ + supply := Z.supply q R sw ok + support := Z.supported q R sw ok + active := ?_ + rule := Z.rule q R sw ok + cost := ?_ + load := ?_ } + · intro v z hz x + apply R.input_full + exact mem_product.mpr ⟨Z.leaf_near ns (fun _ => subset_rfl) + (fun _ _ _ => by split_ifs <;> omega) hz x, mem_univ _⟩ + · intro e t + obtain ⟨i, b, hb⟩ := Z.active q R sw ok e t + cases b + · exact ⟨i, .inl hb⟩ + · exact ⟨i, .inr hb⟩ + · rw [mul_one] + exact Z.total_cost q R c hc hR he + · intro p + have lo := Z.owner_load q R p + have hi := Z.incidence q R sw ok hY hw p + linarith + +open scoped Classical in +/-- A trivalent rotor of width `w` resets arbitrarily many independent +graphs on a common host. The cutoff for the group length is independent +of the number of frozen neighbors. -/ +theorem reset_exists (hY : 0 < Y) (hw : 0 < w) + (hΔ : 0 < Δ) (enough : 4 * coreBins Δ ≤ Y) + (c : ℝ) (hc : 0 ≤ c) : + ∃ k, Y ^ 2 * w ≤ 2 ^ k ∧ + ∀ (F : Type) [Field F] (R : Rotor F Y w), (Fintype.card R.E : ℝ) ≤ c * Y * w → + ∀ (V U : Type) [Fintype V] [Fintype U] (h a D : ℕ), a + k ≤ h → Δ ≤ D → + ∀ (N C : V → Finset V) (src dst : U → V) (ix : U → Cell h) (edge : ∀ i, dst i ∈ C (src i)), + (∀ v z, z ∈ N v → v ∈ N z) → (∀ v z, z ∈ C v → v ∈ C z) → + (∀ v, C v ⊆ N v) → (∀ v, (N v).card ≤ D) → (∀ v, (C v).card ≤ Δ) → + ∀ (l : V → Cell h → ℝ) (u B : ℝ), (∀ v x, 0 ≤ l v x ∧ l v x ≤ B) → + 0 < u → u ≤ B → (∀ v x, (coreDemands ix edge).incident u v x ≤ l v x) → + Nonempty (ResetResult F a N src dst ix l u ((2 : ℝ) ^ k * B) (resetWidth c w) + (resetPositions R Δ) (3 + terminalWidth D Y)) := by + let L := Detour.steps (terminalWidth Δ Y) + have hL : 0 < (L : ℝ) := by unfold L Detour.steps; positivity + obtain ⟨k, hk, ex⟩ := core_schedule Y w Δ (1 / L) hY hw hΔ (by positivity) enough + refine ⟨k, hk, ?_⟩ + intro F _ R hR V U _ _ h a D ha hD N C src dst ix edge ns cs sub ndeg cdeg l u B hl hu ub mass + let S := (2 : ℝ) ^ k * B + have hB : 0 < B := hu.trans_le ub + have hS : 0 < S := by unfold S; positivity + have hs : B / S = 1 / (2 : ℝ) ^ k := by unfold S; field_simp + have hl' v x : 0 ≤ l v x / S ∧ l v x / S ≤ 1 / (2 : ℝ) ^ k := + ⟨div_nonneg (hl v x).1 hS.le, (div_le_div_of_nonneg_right (hl v x).2 hS.le).trans_eq hs⟩ + have hi v x : (coreDemands ix edge).incident (u / S) v x ≤ l v x / S := by + unfold Demands.incident + rw [push_div] + exact div_le_div_of_nonneg_right (mass v x) hS.le + obtain ⟨Z, o, ⟨q⟩⟩ := ex V U h a D ha hD N C src dst ix edge ns cs sub ndeg cdeg + _ _ hl' (div_pos hu hS) ((div_le_div_of_nonneg_right ub hS.le).trans_eq hs) hi + have he : (L : ℝ) * (1 / L) ≤ 1 := by simp [hL.ne'] + let sw := Detour.switch (terminalNear (h := h - a) C Δ Y) + (terminal_symm cs _ _) (terminal_card _ _ _ hΔ cdeg) + let Q := Z.result q R hY hw hΔ hD ns cs sub ndeg sw.pin c hc hR he + exact ⟨Q.unscale hS⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Applying a reset to a core diagram + +All exterior ports, including tether ends, remain separately named. +Only crossing supplies survive, still bundled in the original unit. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.ResetResult + +open Finset + +variable {F V E : Type} [Field F] [Fintype V] [Fintype E] {x y : Wire} {a h u D H : ℕ} + {src dst : E → V} {ix : E → Cell h} {N : V → Finset V} {l : V → Cell h → ℝ} {B W : ℝ} + (q : ResetResult F a N src dst ix l u B W H D) + {G : Diagram F x y} (s : Bundles G src dst ix u) + +open Classical in +/-- Computes the assign by the application `q.owner (s.place v)`. -/ +def assign (_ : Unit) (v : G.V) := q.owner (s.place v) + +open Classical in +/-- The value specified by `(q.rule.bundle u).reindex s.bits`. -/ +abbrev raw := (q.rule.bundle u).reindex s.bits + +open Classical in +/-- The value specified by `(q.owner (src (s.bits e).1, ix (s.bits e).1), q.owner (dst (s.bits +e).1, ix (s.bits e).1))`. -/ +def demand (e : G.E) := + (q.owner (src (s.bits e).1, ix (s.bits e).1), q.owner (dst (s.bits e).1, ix (s.bits e).1)) + +open Classical in +theorem aligned : G.Aligned (q.assign s) (fun _ => id) (q.demand s) := by + intro _ e + exact ⟨congrArg q.owner (s.left e), congrArg q.owner (s.right e)⟩ + +open Classical in +/-- The indexed operation `G.replaced (q.raw s) (q.assign s) (fun _ => id) ()`. -/ +abbrev contract := G.replaced (q.raw s) (q.assign s) (fun _ => id) () + +open Classical in +theorem eval_contract (p : Val x) (r : Val y) : (q.contract s).eval p r = G.eval p r := by + simpa only [Fintype.sum_unique] using G.eval_replaced (q.raw s) (q.assign s) (fun _ => id) p r + +open Classical in +/-- The subtype of `e : q.wire` satisfying `(q.supply e).1 ≠ (q.supply e).2`. -/ +abbrev Survivors := {e : q.wire // (q.supply e).1 ≠ (q.supply e).2} + +open Classical in +/-- Uses `⟨(e.1.val, e.2), e.1.property⟩ invFun e := (⟨e.val.1, e.property⟩, e.val.2)` as the +representation. -/ +def crossingIndex : + q.Survivors × Fin u ≃ + Diagram.Cut (W := fun _ : Unit => fun z : q.wire × Fin u => q.supply z.1) (fun _ + => id) () where + toFun e := ⟨(e.1.val, e.2), e.1.property⟩ + invFun e := (⟨e.val.1, e.property⟩, e.val.2) + left_inv _ := rfl + right_inv _ := rfl + +open Classical in +/-- Reindexes `q.Survivors × Fin u` and `(q.contract s).E` by an equivalence. -/ +def remaining : q.Survivors × Fin u ≃ (q.contract s).E := + q.crossingIndex.trans (G.cutEdges (q.raw s) (q.assign s) (fun _ => id) (q.aligned s) ()) + +open Classical in +/-- The bundles used in the `ResetResult` construction. -/ +def bundles : Bundles (q.contract s) (fun e : q.Survivors => (q.supply e.val).1.2) + (fun e => (q.supply e.val).2.2) (fun e => (q.supply e.val).1.1) u where + place := Prod.swap + bits := (q.remaining s).symm + left e := by + obtain ⟨p, rfl⟩ := (q.remaining s).surjective e + rw [Equiv.symm_apply_apply] + rfl + right e := by + obtain ⟨p, rfl⟩ := (q.remaining s).surjective e + rw [Equiv.symm_apply_apply, (q.support _).1] + rfl + +open Classical in +theorem cost_contract : + (Fintype.card (q.contract s).E : ℝ) ≤ W * (Fintype.card V * (2 : ℝ) ^ a * B + ∑ v, ∑ x, l v x) + := by + rw [← Fintype.card_congr (q.remaining s), Fintype.card_prod, Fintype.card_fin, Nat.cast_mul] + exact (mul_le_mul_of_nonneg_right (Nat.cast_le.mpr (Fintype.card_subtype_le _)) + (Nat.cast_nonneg _)).trans q.cost + +open Classical in +theorem arity_contract (he : ∀ p, (exterior G s.place p : ℝ) ≤ l p.1 p.2) + (p : Cell a × q.vertex) : ((q.contract s).arity p : ℝ) ≤ 89 * B := by + have hb := G.arity_replaced (q.raw s) (q.assign s) (fun _ => id) (q.aligned s) () p + change (q.contract s).arity p ≤ exterior G (q.owner ∘ s.place) p + + degree (fun i : q.wire × Fin u => q.supply i.1) p at hb + rw [degree_bundle] at hb + refine (Nat.cast_le.mpr hb).trans (le_trans ?_ (q.load p)) + rw [Nat.cast_add, Nat.cast_mul, exterior_comp] + exact add_le_add_left (push_le_push q.owner he p) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.ResetResult +end + +/- # Degree reset on a common host with frozen tensors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet + +open Finset + +variable {F T : Type} [Field F] [Fintype T] {x y : Wire} {h u a : ℕ} + {L : Fringe x y T} (G : HostNet F L h u) + +section Transform +variable {B W : ℝ} {H D : ℕ} + (q : ResetResult F a G.N G.src G.dst G.ix G.load u B W H D) + +open scoped Classical in +theorem moved (p : slots x ⊕ slots y) : + (q.bundles G.units).place (portEnd (q.contract G.units) p) = + (q.owner (G.units.place (portEnd G.diagram p))).swap := by + cases p <;> rfl + +open scoped Classical in +/-- Builds `HostNet F L a u where diagram` with the specified `diagram`, `src`, `dst`, `ix`. -/ +def afterReset : HostNet F L a u where + diagram := q.contract G.units + V := q.vertex + E := q.Survivors + src e := (q.supply e.val).1.2 + dst e := (q.supply e.val).2.2 + ix e := (q.supply e.val).1.1 + units := q.bundles G.units + past := G.carried (Prod.swap ∘ q.owner) + park := Prod.swap ∘ q.owner ∘ G.park + frozen := G.frozen ∘ q.origin + N := q.full + C := q.core + ns := q.full_symm + cs := q.core_symm + sub := q.sub + kept t := by + dsimp only [Function.comp_apply, Prod.fst_swap] + rw [q.origin_owner] + exact G.kept t + core e := by + have hs t : ¬ G.frozen (q.origin (cond t (q.supply e.val).2 (q.supply e.val).1).2) := by + obtain ⟨i, he|he⟩ := q.active e.val t + · exact he ▸ (G.core i).1 + · exact he ▸ (G.core i).2 + exact ⟨hs false, hs true⟩ + edge e := (q.support e.val).2 + tether t := by + rw [G.moved q t] + let p := G.units.place (portEnd G.diagram t) + let z := G.park (L.tensor t) + change ¬G.frozen (q.origin (q.owner p).2) ∧ (q.owner p).1 = (q.owner z).1 ∧ + (q.owner z).2 ∈ q.full (q.owner p).2 + obtain ⟨hf, hi, he⟩ := G.tether t + change p.2 = z.2 at hi + rw [q.origin_owner, q.group, q.group, hi] + refine ⟨hf, rfl, ?_⟩ + have ht := q.tether p.1 z.1 he p.2 + rw [show (z.1, p.2) = z by rw [hi]] at ht + exact ht + +open scoped Classical in +theorem reset_load (v : q.vertex) (i : Cell a) : + (G.afterReset q).load v i ≤ 89 * B := by + let Q := G.afterReset q + let f := Prod.swap ∘ q.owner + have hm := G.reassign Q f rfl (G.moved q) rfl (v, i) + have hp : push f (Function.uncurry G.load) (v, i) = push q.owner (Function.uncurry G.load) (i, v) + := by + apply sum_congr rfl + intro j _ + simp [f, Prod.ext_iff, and_comm] + have hd : degree Q.pair (v, i) ≤ degree q.supply (i, v) := by + let e : Q.E ↪ q.wire := Function.Embedding.subtype _ + refine le_trans ?_ (degree_select q.supply e (i, v)) + rw [degree_sum, degree_sum] + apply sum_le_sum + intro t _ + have he := (q.support (e t)).1 + change arityCost (v, i) + (((q.supply (e t)).1.2, (q.supply (e t)).1.1), + ((q.supply (e t)).2.2, (q.supply (e t)).1.1)) ≤ arityCost (i, v) (q.supply (e t)) + simp [arityCost, Prod.ext_iff, and_comm, he] + exact hm.trans ((add_le_add hp.le (mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hd) + (Nat.cast_nonneg _))).trans (q.load (i, v))) + +open scoped Classical in +theorem afterReset_spec {σ : ℝ} (width : 0 ≤ W) + (slack : B * (Fintype.card G.V * 2 ^ a : ℕ) ≤ σ) : + (G.afterReset q).Bounded 3 D (89 * B) ∧ (G.afterReset q).X ≤ W * (σ + 2 * G.X + 2 * L.Z) ∧ + G.Preserves (G.afterReset q) ∧ (G.afterReset q).mass = G.mass + 2 * G.X ∧ + G.Tracks (G.afterReset q) (H + 1) := by + obtain ⟨S, _, β, hβ⟩ := q.uniform + refine ⟨⟨q.core_degree, q.full_degree, G.reset_load q⟩, ?_, + ⟨Prod.swap ∘ q.owner, rfl, G.moved q, ⟨(prefixMap q.le).comp q.mix.toLinearMap, + (prefixMap_onto q.le).comp q.mix.surjective, q.group⟩, + S, inferInstance, β, fun t => (hβ _).trans (q.origin_owner (G.park t))⟩, + G.carry_sum (Prod.swap ∘ q.owner), ?_⟩ + · have hs : (Fintype.card G.V : ℝ) * 2 ^ a * B ≤ σ := by + rwa [Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, mul_comm] at slack + change ((Fintype.card q.Survivors * u : ℕ) : ℝ) ≤ _ + rw [Nat.cast_mul] + refine (mul_le_mul_of_nonneg_right (Nat.cast_le.mpr (Fintype.card_subtype_le _)) + (Nat.cast_nonneg _)).trans (q.cost.trans ?_) + exact mul_le_mul_of_nonneg_left (by linarith only [hs, G.sum_load]) width + · have hpos : 0 < H + 1 := by omega + have ht : G.Tracks (G.afterReset q) (1 * (H + 1)) := by + refine tracks_of_slots β (fun v => {v}) (by simp [eq_comm]) (by simp) hpos + (q.positions.trans (by gcongr; omega)) ?_ + intro j + rw [mem_singleton] + exact (hβ _).trans ((congrArg (fun p => q.origin p.1) (G.moved q j)).trans + (q.origin_owner _)) + simpa only [one_mul] using ht + +end Transform + +open scoped Classical in +/-- Reset all groups using one choice of common links and a single rotor. -/ +theorem reset {Y w Δ : ℕ} (hY : 0 < Y) (hw : 0 < w) + (hΔ : 0 < Δ) (enough : 4 * coreBins Δ ≤ Y) + (c : ℝ) (hc : 0 ≤ c) : + ∃ k, ∀ (F : Type) [Field F] (R : Rotor F Y w), (Fintype.card R.E : ℝ) ≤ c * Y * w → + ∀ (T : Type) [Fintype T] (x y : Wire) (L : Fringe x y T) + (h a u D : ℕ) (B σ : ℝ) (G : HostNet F L h u), + a + k ≤ h → Δ ≤ D → G.Bounded Δ D B → 0 < u → u ≤ B → + (2 : ℝ) ^ k * B * (Fintype.card G.V * 2 ^ a : ℕ) ≤ σ → + ∃ Q : HostNet F L a u, + (∀ x y, Q.diagram.eval x y = G.diagram.eval x y) ∧ + Fintype.card Q.V ≤ resetPositions R Δ * 2 ^ (h - a) * Fintype.card G.V ∧ + Q.Bounded 3 (3 + terminalWidth D Y) (89 * (2 : ℝ) ^ k * B) ∧ + Q.X ≤ resetWidth c w * (σ + 2 * G.X + 2 * L.Z) ∧ G.Preserves Q ∧ + Q.mass = G.mass + 2 * G.X ∧ G.Tracks Q (resetPositions R Δ + 1) := by + obtain ⟨k, _, ex⟩ := reset_exists hY hw hΔ enough c hc + refine ⟨k, ?_⟩ + intro F _ R hR T _ x y L h a u D B σ G ha hD bounds hu hb slack + have load v i : (coreDemands G.ix G.edge).incident u v i ≤ G.load v i := by + unfold Demands.incident + rw [← degree_push] + exact (le_add_of_nonneg_left (Nat.cast_nonneg _)).trans (G.core_le_load v i) + obtain ⟨q⟩ := ex F R hR G.V G.E h a D ha hD G.N G.C G.src G.dst G.ix G.edge G.ns G.cs G.sub + bounds.2.1 bounds.1 _ _ _ (fun v i => ⟨G.load_nonneg v i, bounds.2.2 v i⟩) + (Nat.cast_pos.mpr hu) hb load + obtain ⟨bound, rest⟩ := G.afterReset_spec q (by unfold resetWidth; positivity) slack + exact ⟨G.afterReset q, q.eval_contract _, q.positions, + by simpa only [mul_assoc] using bound, rest⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Occupancy.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Occupancy.lean new file mode 100644 index 0000000000..c7c5215b1c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Occupancy.lean @@ -0,0 +1,408 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Field.ZMod +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Fintype.Pi +public import Mathlib.Data.Fin.Tuple.Basic +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Positivity +public import Mathlib.Tactic.Ring +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Algebra.BigOperators.Group.Finset.Basic +public import Mathlib.Data.Fintype.Card +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement + +/-! # Dyadic intervals indexed by binary prefixes -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +/-- The indexing data represented by `Fin j → ZMod 2`. -/ +abbrev Cell (j : ℕ) := Fin j → ZMod 2 + +/-- Evaluates `x (Fin.castLE h a)` at the input `a`. -/ +def ancestor {i j : ℕ} (h : i ≤ j) (x : Cell j) : Cell i := + fun a => x (Fin.castLE h a) + +@[simp] theorem ancestor_self {i : ℕ} (h : i ≤ i) (x : Cell i) : ancestor h x = x := rfl + +@[simp] theorem ancestor_ancestor {i j k : ℕ} (h : i ≤ j) (h' : j ≤ k) (x : Cell k) : + ancestor h (ancestor h' x) = ancestor (h.trans h') x := rfl + +theorem card_cell (j : ℕ) : Fintype.card (Cell j) = 2 ^ j := by simp [Cell] + +theorem card_prefix {i h : ℕ} (hi : i ≤ h) (c : Cell i) : + Fintype.card {x : Cell h // ancestor hi x = c} = 2 ^ (h - i) := by + obtain ⟨j, rfl⟩ := Nat.exists_eq_add_of_le hi + rw [Nat.add_sub_cancel_left, ← card_cell] + let suffix (x : {x : Cell (i + j) // ancestor hi x = c}) : Cell j := + fun a => x.1 (Fin.natAdd i a) + apply Fintype.card_congr (Equiv.ofBijective suffix ?_) + constructor + · intro x y e + apply Subtype.ext + funext a + induction a using Fin.addCases with + | left a => exact (congrFun x.2 a).trans (congrFun y.2 a).symm + | right a => exact congrFun e a + · intro z + exact ⟨⟨Fin.append c z, funext (Fin.append_left' c z)⟩, funext (Fin.append_right c z)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Second moments of loads at a dyadic depth + +Bounds on prefix collisions control both the variance and the contribution +from pairs of distinct blocks. These estimates serve the balanced +partitions and the reservations in the degree reset. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +variable {h : ℕ} (l : Cell h → ℝ) (π : Equiv.Perm (Cell h)) (i : ℕ) + +/-- Selects the appropriate branch of `if hi : i ≤ h then ∑ x, if ancestor hi (π x) = z then l x +else 0 else 0`. -/ +def load (z : Cell i) : ℝ := + if hi : i ≤ h then ∑ x, if ancestor hi (π x) = z then l x else 0 else 0 + +/-- The quantity computed by `(∑ x, l x) / (2 : ℝ) ^ i`. -/ +def mean := (∑ x, l x) / (2 : ℝ) ^ i + +/-- The sum of `(load l π i z - mean l i) ^ 2` indexed by `z : Cell i`. -/ +def variance := ∑ z : Cell i, (load l π i z - mean l i) ^ 2 + +/-- The quantity computed by `(load l π i z) ^ 2 - load (fun x => l x ^ 2) π i z`. -/ +def cross (z : Cell i) := (load l π i z) ^ 2 - load (fun x => l x ^ 2) π i z + +theorem load_nonneg (hl : ∀ x, 0 ≤ l x) (z : Cell i) : 0 ≤ load l π i z := by + unfold load + split_ifs + · exact Finset.sum_nonneg fun x _ => by split_ifs <;> first | exact hl _ | exact le_rfl + · exact le_rfl + +theorem sum_load (hi : i ≤ h) : (∑ z, load l π i z) = ∑ x, l x := by + simp only [load, dite_eq_left hi] + rw [Finset.sum_comm] + simp + +theorem sum_cross (hi : i ≤ h) : + (∑ z, cross l π i z) = (∑ z, (load l π i z) ^ 2) - ∑ x, l x ^ 2 := by + simp only [cross, Finset.sum_sub_distrib, sum_load _ _ _ hi] + +theorem variance_eq (hi : i ≤ h) : + variance l π i = (∑ z, (load l π i z) ^ 2) - (∑ x, l x) ^ 2 / (2 : ℝ) ^ i := by + simp only [variance, sub_sq, Finset.sum_add_distrib, Finset.sum_sub_distrib, ← Finset.sum_mul, + ← Finset.mul_sum, sum_load _ _ _ hi, Finset.sum_const, Finset.card_univ, card_cell, + nsmul_eq_mul, Nat.cast_pow, Nat.cast_ofNat, mean] + field_simp + ring + +theorem diagonal_le (z : Cell i) {c : ℝ} (hl : ∀ x, 0 ≤ l x ∧ l x ≤ c) : + load (fun x => l x ^ 2) π i z ≤ c * load l π i z := by + unfold load + split_ifs with hi + · rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro x _ + split_ifs + · exact (pow_two _).trans_le (mul_le_mul_of_nonneg_right (hl x).2 (hl x).1) + · simp + · simp + +theorem cross_nonneg (hl : ∀ x, 0 ≤ l x) (z : Cell i) : 0 ≤ cross l π i z := by + unfold cross load + split_ifs with hi + · let f (x : Cell h) := if ancestor hi (π x) = z then l x else 0 + have hf x : 0 ≤ f x := by unfold f; split_ifs <;> first | exact hl _ | exact le_rfl + apply sub_nonneg.mpr + rw [pow_two, Finset.mul_sum] + apply Finset.sum_le_sum + intro x _ + have hm := mul_le_mul_of_nonneg_right + (Finset.single_le_sum (fun y _ => hf y) (Finset.mem_univ x)) (hf x) + by_cases hx : ancestor hi (π x) = z + · simpa [hx, f, pow_two] using hm + · simp [hx] + · simp + +theorem square_load (hi : i ≤ h) : + (∑ z, (load l π i z) ^ 2) = + ∑ x, ∑ y, if ancestor hi (π x) = ancestor hi (π y) then l x * l y else 0 := by + simp only [load, dite_eq_left hi, pow_two, Finset.sum_mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro y _ + simp only [ite_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + simp [eq_comm, mul_ite] + +/-- A uniform family of prefix hash functions. -/ +def Mixes {M : Type} [Fintype M] (p : M → Equiv.Perm (Cell h)) : Prop := + ∀ (j : ℕ) (hj : j ≤ h) (x y : Cell h), x ≠ y → + (∑ m : M, if ancestor hj (p m x) = ancestor hj (p m y) then (1 : ℝ) else 0) ≤ + (Fintype.card M : ℝ) / (2 : ℝ) ^ j + +variable {M : Type} [Fintype M] {p : M → Equiv.Perm (Cell h)} + +private theorem moment_bound (hp : Mixes p) (hl : ∀ x, 0 ≤ l x) (hi : i ≤ h) : + (∑ m, ∑ z, (load l (p m) i z) ^ 2) ≤ + (Fintype.card M : ℝ) * ((∑ x, l x ^ 2) + (∑ x, l x) ^ 2 / (2 : ℝ) ^ i) := by + let C : ℝ := Fintype.card M + calc + _ ≤ ∑ x, ∑ y, ((if x = y then C * l x ^ 2 else 0) + C / 2 ^ i * (l x * l y)) := by + simp_rw [square_load l _ i hi] + rw [Finset.sum_comm] + apply Finset.sum_le_sum + intro x _ + rw [Finset.sum_comm] + apply Finset.sum_le_sum + intro y _ + by_cases he : x = y + · subst y + simp only [ite_true, ← pow_two, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + apply le_add_of_nonneg_right + unfold C + positivity + · have hb := mul_le_mul_of_nonneg_right (hp i hi x y he) (mul_nonneg (hl x) (hl y)) + rw [Finset.sum_mul] at hb + simpa [he, ite_mul, C] using hb + _ = _ := by + simp only [Finset.sum_add_distrib, Finset.sum_ite_eq, Finset.mem_univ, ite_true, + ← Finset.mul_sum, ← Finset.sum_mul] + unfold C + ring + +theorem variance_bound (hp : Mixes p) (hl : ∀ x, 0 ≤ l x) (hi : i ≤ h) : + (∑ m, variance l (p m) i) ≤ (Fintype.card M : ℝ) * ∑ x, l x ^ 2 := by + simp only [variance_eq _ _ _ hi, Finset.sum_sub_distrib, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul] + linarith [moment_bound l i hp hl hi] + +theorem cross_bound (hp : Mixes p) (hl : ∀ x, 0 ≤ l x) (hi : i ≤ h) : + (∑ m, ∑ z, cross l (p m) i z) ≤ (Fintype.card M : ℝ) * ((∑ x, l x) ^ 2 / (2 : ℝ) ^ i) := by + simp only [sum_cross _ _ _ hi, Finset.sum_sub_distrib, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul] + linarith [moment_bound l i hp hl hi] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Summing loads through successive assignments -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +variable {X Y Z : Type} [Fintype X] + +open scoped Classical in +/-- The sum of `if f x = y then l x else 0` indexed by `x`. -/ +def push (f : X → Y) (l : X → ℝ) (y : Y) := ∑ x, if f x = y then l x else 0 + +open scoped Classical in +theorem push_nonneg (f : X → Y) (l : X → ℝ) (hl : ∀ x, 0 ≤ l x) (y : Y) : + 0 ≤ push f l y := by + exact sum_nonneg fun x _ => by split_ifs <;> first | exact hl x | exact le_rfl + +open scoped Classical in +theorem push_le_push (f : X → Y) {l m : X → ℝ} (hl : ∀ x, l x ≤ m x) (y : Y) : + push f l y ≤ push f m y := by + exact sum_le_sum fun x _ => by split_ifs <;> first | exact hl x | exact le_rfl + +open scoped Classical in +theorem sum_push [Fintype Y] (f : X → Y) (l : X → ℝ) : + (∑ y, push f l y) = ∑ x, l x := by + unfold push + rw [sum_comm] + simp + +open scoped Classical in +theorem test_push [Fintype Y] (f : X → Y) (l : X → ℝ) (p : Y → Prop) [DecidablePred p] : + (∑ y, if p y then push f l y else 0) = ∑ x, if p (f x) then l x else 0 := by + rw [← sum_filter] + unfold push + rw [sum_comm] + simp + +open scoped Classical in +theorem push_comp [Fintype Y] (f : X → Y) (g : Y → Z) (l : X → ℝ) (z : Z) : + push g (push f l) z = push (g ∘ f) l z := + test_push f l (fun y => g y = z) + +open scoped Classical in +theorem push_div (f : X → Y) (l : X → ℝ) (r : ℝ) (y : Y) : + push f (fun x => l x / r) y = push f l y / r := by + simp only [push, div_eq_mul_inv, sum_mul, ite_mul, zero_mul] + +open scoped Classical in +theorem push_fst [Fintype Y] (l : X × Y → ℝ) (x : X) : + push Prod.fst l x = ∑ y, l (x, y) := by + unfold push + rw [Fintype.sum_prod_type, sum_comm] + simp + +open scoped Classical in +theorem push_at [Fintype Y] {W : X → Type} (f : (x : X) → Y → W x) + (l : X × Y → ℝ) (x : X) (w : W x) : + push (fun p => (⟨p.1, f p.1 p.2⟩ : Σ x, W x)) l ⟨x, w⟩ = + push (f x) (fun y => l (x, y)) w := by + unfold push + rw [Fintype.sum_prod_type, sum_eq_single x] + · simp + · intro y _ hy; simp [hy] + · simp + +open scoped Classical in +theorem push_prefix {h : ℕ} (base : X → ℕ) (hb : ∀ v, base v ≤ h) + (π : Equiv.Perm (Cell h)) (l : X → Cell h → ℝ) (v : X) (z : Cell (base v)) : + push (fun p => (⟨p.1, ancestor (hb p.1) (π p.2)⟩ : Σ x, Cell (base x))) + (Function.uncurry l) ⟨v, z⟩ = load (l v) π (base v) z := by + rw [push_at (fun v y => ancestor (hb v) (π y))] + simp only [load, dite_eq_left (hb v), push, Function.uncurry_apply_pair] + congr! 2 + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Counting both ends of a wire, including both incidences of a loop -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V E : Type} [Fintype E] + +open scoped Classical in +/-- The quantity computed by `Fintype.card {e // (pair e).1 = v} + Fintype.card {e // (pair e).2 += v}`. -/ +def degree (pair : E → V × V) (v : V) := + Fintype.card {e // (pair e).1 = v} + Fintype.card {e // (pair e).2 = v} + +open scoped Classical in +/-- The quantity computed by `(if p.1 = v then 1 else 0) + (if p.2 = v then 1 else 0)`. -/ +def arityCost (v : V) (p : V × V) : ℕ := + (if p.1 = v then 1 else 0) + (if p.2 = v then 1 else 0) + +open scoped Classical in +theorem degree_sum (pair : E → V × V) (v : V) : + degree pair v = ∑ e, arityCost v (pair e) := by + simp only [degree, Fintype.card_subtype, arityCost, sum_add_distrib, ← sum_filter, + ← card_eq_sum_ones] + +open scoped Classical in +theorem degree_map [Fintype V] {X : Type} (pair : E → V × V) (f : V → X) (z : X) : + degree (fun e => Prod.map f f (pair e)) z = + ∑ v, if f v = z then degree pair v else 0 := by + have aux (t : E → V) : Fintype.card {e // f (t e) = z} = + ∑ v ∈ univ.filter (fun v => f v = z), Fintype.card {e // t e = v} := by + simp only [Fintype.card_subtype] + rw [sum_card_fiberwise_eq_card_filter univ _ t] + simp + rw [← sum_filter] + simp only [degree, sum_add_distrib, ← aux] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Degree and load of a graph under a change of sites -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V W X U : Type} [Fintype U] + +open scoped Classical in +/-- Unused sites may coincide with active ones after projection. -/ +theorem push_max [Fintype V] (f : V → W) (p : V → Prop) (l : V → ℝ) (B : ℝ) + (hb : 0 ≤ B) (hs : ∀ v, l v ≤ B) (hz : ∀ v, ¬p v → l v = 0) + (hi : Set.InjOn f {v | p v}) (w : W) : push f l w ≤ B := by + unfold push + by_cases h : ∃ v, p v ∧ f v = w + · obtain ⟨v, hv, he⟩ := h + rw [sum_eq_single v] + · simpa only [he, ite_true] using hs v + · intro z _ hne + split_ifs with h + · exact hz z fun hp => hne (hi hp hv (h.trans he.symm)) + · rfl + · simp + · refine le_trans ?_ hb + refine (sum_eq_zero (fun v _ => ?_)).le + split_ifs with hv + · exact hz v fun hp => h ⟨v, hp, hv⟩ + · rfl + +open scoped Classical in +theorem degree_le_map [Finite V] (P : U → V × V) (f : V → W) (p : V → Prop) (u B : ℝ) + (hb : 0 ≤ B) (hs : ∀ v, degree P v * u ≤ B) (hz : ∀ v, ¬p v → degree P v = 0) + (hi : Set.InjOn f {v | p v}) (w : W) : + degree (fun i => Prod.map f f (P i)) w * u ≤ B := by + let : Fintype V := Fintype.ofFinite V + have := push_max f p (fun v => degree P v * u) B hb hs + (fun v hv => by simp [hz v hv]) hi w + simpa only [degree_map, Nat.cast_sum, sum_mul, Nat.cast_ite, Nat.cast_zero, + ite_mul, zero_mul, push] using this + +open scoped Classical in +theorem degree_partition [Fintype X] (f : U → V × V) (g : X → V × V) (v : V) : + degree (Sum.elim f g) v = degree f v + degree g v := by + simp only [degree_sum, Fintype.sum_sum_type, Sum.elim_inl, Sum.elim_inr] + +open scoped Classical in +theorem degree_select [Fintype X] (f : U → V × V) (e : X ↪ U) (v : V) : + degree (f ∘ e) v ≤ degree f v := by + simp only [degree_sum, Function.comp_apply] + rw [← sum_map univ e (fun x => arityCost v (f x))] + exact sum_le_sum_of_subset (subset_univ _) + +open scoped Classical in +theorem degree_push (f : U → Bool → V) (u : ℝ) (v : V) : + (degree (fun i => (f i false, f i true)) v : ℝ) * u = + push (Function.uncurry f) (fun _ => u) v := by + unfold push + rw [degree_sum, Nat.cast_sum, sum_mul, Fintype.sum_prod_type] + apply sum_congr rfl + intro i _ + by_cases hfalse : f i false = v <;> by_cases htrue : f i true = v <;> + simp [arityCost, Fintype.univ_bool, hfalse, htrue, two_mul, add_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +variable {V E F : Type} {a b : Wire} (G : Diagram F a b) {h : ℕ} + +/-- Placement of individual stations and partition of all core edges into +uniform bundles. Both ends of an edge are in the same block. -/ +structure Bundles (src dst : E → V) (ix : E → Cell h) (u : ℕ) where + /-- The `Bundles` component of type `G.V → V × Cell h`. -/ + place : G.V → V × Cell h + /-- Reindexes the data using `G.E ≃ E × Fin u`. -/ + bits : G.E ≃ E × Fin u + left : ∀ e, place (G.source e) = (src (bits e).1, ix (bits e).1) + right : ∀ e, place (G.target e) = (dst (bits e).1, ix (bits e).1) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Projection.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Projection.lean new file mode 100644 index 0000000000..0741c9f630 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Projection.lean @@ -0,0 +1,927 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Combinatorics.Hall.Finite +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.Linarith +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.CubeGadget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Packets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import Mathlib.Algebra.Order.Archimedean.Real.Basic +public import Mathlib.Algebra.Order.Floor.Semiring + +/-! +# Placing bundles on permutation layers + +A layer is a permutation of the terminals. To complete a matching we +allow a zero demand between a slack row and a slack column. Hall's +condition follows by counting either saturated rows or saturated columns. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {X : Type} [Fintype X] + +open scoped Classical in +private theorem saturated (a : X → X → ℕ) (n : ℕ) (hn : 0 < n) + (cols : ∀ j, ∑ i, a i j ≤ n) (s t : Finset X) + (full : ∀ i ∈ s, ∑ j, a i j = n) + (supp : ∀ i ∈ s, ∀ j ∉ t, a i j = 0) : s.card ≤ t.card := by + apply Nat.le_of_mul_le_mul_right _ hn + calc + s.card * n = ∑ i ∈ s, ∑ j ∈ t, a i j := by + rw [← Nat.nsmul_eq_mul, ← sum_const] + exact sum_congr rfl fun i hi => + ((sum_subset (subset_univ t) (fun j _ hj => supp i hi j hj)).trans (full i hi)).symm + _ ≤ ∑ j ∈ t, n := by + rw [sum_comm] + exact sum_le_sum fun j _ => (sum_le_sum_of_subset (subset_univ s)).trans (cols j) + _ = t.card * n := by simp + +open scoped Classical in +private theorem match_full (a : X → X → ℕ) (n : ℕ) (hn : 0 < n) + (rows : ∀ i, ∑ j, a i j ≤ n) (cols : ∀ j, ∑ i, a i j ≤ n) : + ∃ σ : Equiv.Perm X, ∀ i, + 0 < a i (σ i) ∨ (∑ j, a i j) < n ∧ (∑ k, a k (σ i)) < n := by + let f (i : X) := univ.filter fun j => 0 < a i j ∨ (∑ k, a i k) < n ∧ (∑ k, a k j) < n + have hall (s : Finset X) : s.card ≤ (s.biUnion f).card := by + let t := s.biUnion f + have no_edge i (hi : i ∈ s) j (hj : j ∉ t) : + a i j = 0 ∧ ((∑ k, a i k) < n → (∑ k, a k j) = n) := by + have h : j ∉ f i := fun e => hj (mem_biUnion.mpr ⟨i, hi, e⟩) + simp only [f, mem_filter, mem_univ, true_and] at h + have := cols j + omega + change s.card ≤ t.card + by_cases full : ∀ i ∈ s, ∑ j, a i j = n + · exact saturated a n hn cols s t full (fun i hi j hj => (no_edge i hi j hj).1) + · push Not at full + obtain ⟨i, hi, hdef⟩ := full + have hb := saturated (fun j k => a k j) n hn rows tᶜ sᶜ + (fun j hj => (no_edge i hi j (mem_compl.mp hj)).2 (lt_of_le_of_ne (rows i) hdef)) + (fun j hj k hk => (no_edge k (by simpa using hk) j (mem_compl.mp hj)).1) + rw [card_compl, card_compl] at hb + have := card_le_univ s + have := card_le_univ t + omega + obtain ⟨g, hg, hs⟩ := (all_card_le_biUnion_card_iff_existsInjective' f).mp hall + exact ⟨Equiv.ofBijective g (Finite.injective_iff_bijective.mp hg), + fun i => (mem_filter.mp (hs i)).2⟩ + +open scoped Classical in +/-- A nonnegative integral demand matrix with row and column sums at most +`n` is dominated entrywise by a sum of `n` permutation matrices. -/ +theorem permutation_layers (a : X → X → ℕ) (n : ℕ) + (rows : ∀ i, ∑ j, a i j ≤ n) (cols : ∀ j, ∑ i, a i j ≤ n) : + ∃ σ : Fin n → Equiv.Perm X, ∀ i j, a i j ≤ ∑ t, if σ t i = j then 1 else 0 := by + induction n generalizing a with + | zero => + refine ⟨Fin.elim0, fun i j => ?_⟩ + have h := (single_le_sum (fun k _ => Nat.zero_le (a i k)) (mem_univ j)).trans (rows i) + exact h.trans (Nat.zero_le _) + | succ n ih => + obtain ⟨τ, hτ⟩ := match_full a (n + 1) (by omega) rows cols + let b (i j : X) := a i j - if τ i = j then 1 else 0 + have cut (f g : X → ℕ) (x : X) (cap : ∑ i, f i ≤ n + 1) + (hfg : ∀ i, g i ≤ f i) (dec : g x = f x - 1) + (tight : 0 < f x ∨ ∑ i, f i < n + 1) : (∑ i, g i) ≤ n := by + rcases tight with hx | hs + · have := sum_lt_sum (fun i (_ : i ∈ univ) => hfg i) + ⟨x, mem_univ x, by omega⟩ + omega + · exact (sum_le_sum (fun i _ => hfg i)).trans (Nat.le_of_lt_succ hs) + have hr i : ∑ j, b i j ≤ n := + cut (a i) (b i) (τ i) (rows i) (fun _ => Nat.sub_le _ _) (by simp [b]) + ((hτ i).imp_right And.left) + have hc j : ∑ i, b i j ≤ n := by + refine cut (fun i => a i j) (fun i => b i j) (τ.symm j) (cols j) + (fun _ => Nat.sub_le _ _) (by simp [b]) ?_ + simpa only [Equiv.apply_symm_apply] using (hτ (τ.symm j)).imp_right And.right + obtain ⟨σ, hσ⟩ := ih b hr hc + refine ⟨Fin.cons τ σ, ?_⟩ + intro i j + rw [Fin.sum_univ_succ] + simp only [Fin.cons_zero, Fin.cons_succ] + have hi := hσ i j + unfold b at hi + omega + +open scoped Classical in +/-- Place each requested unit on a layer and port carrying its ordered +pair of terminals. Different pairs cannot collide at a terminal, since +each layer routes a permutation. -/ +theorem rotor_placement (a : X → X → ℕ) (U w : ℕ) (hw : 0 < w) + (rows : ∀ i, ∑ j, a i j ≤ U) (cols : ∀ j, ∑ i, a i j ≤ U) : + ∃ σ : Fin (U / w + Fintype.card X) → Equiv.Perm X, ∀ i j, + Nonempty (Fin (a i j) ↪ {t // σ t i = j} × Fin w) := by + have round (f : X → ℕ) (hf : ∑ i, f i ≤ U) : + (∑ i, (f i / w + 1)) ≤ U / w + Fintype.card X := by + rw [sum_add_distrib, sum_const, card_univ, Nat.nsmul_eq_mul, mul_one] + apply Nat.add_le_add_right + rw [Nat.le_div_iff_mul_le hw, sum_mul] + exact (sum_le_sum (fun i _ => Nat.div_mul_le_self (f i) w)).trans hf + obtain ⟨σ, hs⟩ := permutation_layers (fun i j => a i j / w + 1) _ + (fun i => round _ (rows i)) (fun j => round _ (cols j)) + refine ⟨σ, fun i j => Function.Embedding.nonempty_of_card_le ?_⟩ + rw [Fintype.card_fin, Fintype.card_prod, Fintype.card_fin, Fintype.card_subtype] + calc + _ ≤ (a i j / w + 1) * w := by + rw [add_mul, one_mul] + exact (Nat.lt_div_mul_add hw).le + _ ≤ _ := Nat.mul_le_mul_right _ (by simpa only [sum_boole, Nat.cast_id] using hs i j) + +open scoped Classical in +/-- Capacity in scalar bits, with `Y` terminals, unit size `u` and +budget `b = F B`. The rounding overhead costs at most one budget. -/ +theorem rotor_cost (U Y w : ℕ) (u b : ℝ) (hu : 0 ≤ u) + (hU : (U : ℝ) * Y * u ≤ 9 * b) (hw : (Y : ℝ) ^ 2 * w * u ≤ b) : + ((U / w + Y : ℕ) : ℝ) * Y * w * u ≤ 10 * b := by + have hr : ((U / w : ℕ) : ℝ) * w ≤ U := by exact_mod_cast Nat.div_mul_le_self U w + have hprod := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right hr (Nat.cast_nonneg Y)) hu + rw [Nat.cast_add] + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Common support after relocating the ends of a contact -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {X : Type} (N : X → Finset X) + +open scoped Classical in +/-- The indexed operation `(N p).biUnion fun q => (N q).biUnion N`. -/ +def cube (p : X) : Finset X := + (N p).biUnion fun q => (N q).biUnion N + +open scoped Classical in +theorem mem_cube (p q : X) : + q ∈ cube N p ↔ ∃ x ∈ N p, ∃ y ∈ N x, q ∈ N y := by + simp only [cube, mem_biUnion] + +open scoped Classical in +theorem cube_symm (sym : ∀ x y, y ∈ N x → x ∈ N y) (p q : X) (hq : q ∈ cube N p) : + p ∈ cube N q := by + obtain ⟨x, hx, y, hy, hz⟩ := (mem_cube _ _ _).mp hq + exact (mem_cube _ _ _).mpr ⟨y, sym _ _ hz, x, sym _ _ hy, sym _ _ hx⟩ + +open scoped Classical in +theorem cube_mono {C : X → Finset X} (sub : ∀ x, C x ⊆ N x) (p : X) : + cube C p ⊆ cube N p := by + intro q hq + obtain ⟨x, hx, y, hy, hz⟩ := (mem_cube _ _ _).mp hq + exact (mem_cube _ _ _).mpr ⟨x, sub _ hx, y, sub _ hy, sub _ hz⟩ + +open scoped Classical in +theorem cube_card {D : ℕ} (bound : ∀ p, (N p).card ≤ D) (p : X) : + (cube N p).card ≤ D ^ 3 := by + have step (T : X → Finset X) (L : ℕ) (ht : ∀ p, (T p).card ≤ L) (p : X) : + ((N p).biUnion T).card ≤ D * L := calc + _ ≤ ∑ x ∈ N p, (T x).card := card_biUnion_le + _ ≤ ∑ _x ∈ N p, L := sum_le_sum fun x _ => ht x + _ ≤ D * L := by simpa using Nat.mul_le_mul_right L (bound p) + simpa [cube, pow_succ, mul_assoc] using step _ _ (step N D bound) p + +namespace Grouping +variable {V E : Type} [Fintype V] {N C : V → Finset V} {Δ D h k : ℕ} + {B : ℝ} {l : V → Cell h → ℝ} (g : Grouping N C Δ D k B l) + {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + (cs : ∀ v w, w ∈ C v → v ∈ C w) (sub : ∀ v, C v ⊆ N v) + (hedge : ∀ e, dst e ∈ C (src e)) + +include cs sub hedge + +open scoped Classical in +theorem contact_core (col : Bool) {v w : V} (hw : w ∈ C v) (x : Cell h) : + g.route m col w x ∈ cube (near C Δ) (g.route m col v x) := + (mem_cube _ _ _).mpr ⟨_, near_symm cs _ _ _ (g.route_near m cs sub hedge col v x), + _, g.here_core cs sub hw x, g.route_near m cs sub hedge col w x⟩ + +open scoped Classical in +theorem contact_full (ns : ∀ v w, w ∈ N v → v ∈ N w) (le : Δ ≤ D) + (col : Bool) {v w : V} (hw : w ∈ N v) (x : Cell h) : + g.route m col w x ∈ cube (near N D) (g.route m col v x) := + (mem_cube _ _ _).mpr + ⟨_, near_mono sub le _ (near_symm cs _ _ _ (g.route_near m cs sub hedge col v x)), + _, g.here_full ns le hw x, near_mono sub le _ (g.route_near m cs sub hedge col w x)⟩ + +end Grouping +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Placing the six parties of each matched pair on the contracted host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Grouping + +open Spectral.Tensor + +variable {V E : Type} [Fintype V] {N C : V → Finset V} {Δ D h k : ℕ} + {B : ℝ} {l : V → Cell h → ℝ} (g : Grouping N C Δ D k B l) + {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + +/-- The last two parties charge their incidences to the indicated old endpoint. -/ +def rep (col : Bool) (e : m.items) : Fin 6 → V × Cell h := + let a := (src (m.mate e), ix (m.mate e)) + let b := (dst (m.mate e), ix (m.mate e)) + let c := (src e.val, ix e.val) + let d := (dst e.val, ix e.val) + ![a, b, c, d, if col then d else a, if col then b else d] + +/-- Computes the party by the application `g.route m col (g.rep m col e i).1 (g.rep m col e +i).2`. -/ +def party (col : Bool) (e : m.items) (i : Fin 6) : Site V h := + g.route m col (g.rep m col e i).1 (g.rep m col e i).2 + +private theorem join_source (col : Bool) (e : m.items) : + g.party m col e 2 = if col then g.party m col e 1 else g.party m col e 0 := by + have hx := (m.spec e).1 + change g.route m col (src e.val) (ix e.val) = + if col then g.route m col (dst (m.mate e)) (ix (m.mate e)) + else g.route m col (src (m.mate e)) (ix (m.mate e)) + rw [g.route_thin, g.route_thick m _ _ _ hx, g.route_thick m _ _ _ hx] + +/-- Each profile class is internal on its designated side. -/ +theorem party_closed (e : m.items) (t : Fin 8) : + let c := decide (4 ≤ t.val) + g.party m c e (sixPair t).1 = g.party m c e (sixPair t).2 := by + have r : g.party m false e 2 = g.party m false e 0 := g.join_source m false e + have c : g.party m true e 2 = g.party m true e 1 := g.join_source m true e + fin_cases t + · exact r.symm + · rfl + · exact r + · rfl + · exact c.symm + · rfl + · exact c + · rfl + +/-- Every replacement wire is internal in at least one layout. -/ +theorem party_internal (e : m.items) (t : Fin 8) : + g.party m false e (sixPair t).1 = g.party m false e (sixPair t).2 ∨ + g.party m true e (sixPair t).1 = g.party m true e (sixPair t).2 := by + have h := g.party_closed m e t + cases hc : decide (4 ≤ t.val) + · exact .inl (hc ▸ h) + · exact .inr (hc ▸ h) + +/-- All six parties lie among three sites on a path of length at most three. -/ +theorem party_near (cs : ∀ v w, w ∈ C v → v ∈ C w) (sub : ∀ v, C v ⊆ N v) + (hedge : ∀ e, dst e ∈ C (src e)) (col : Bool) (e : m.items) (i j : Fin 6) : + g.party m col e j ∈ cube (near C Δ) (g.party m col e i) := by + let a := g.here (src (m.mate e)) (ix (m.mate e)) + let b := g.here (dst (m.mate e)) (ix (m.mate e)) + let d := g.here (dst e.val) (ix e.val) + let y := g.route m col (dst e.val) (ix e.val) + have ab : b ∈ near C Δ a := g.here_core cs sub (hedge _) _ + have ad : d ∈ near C Δ a := by + have ha : a = g.here (src e.val) (ix e.val) := congrArg g.site (m.spec e).2.1 + rw [ha] + exact g.here_core cs sub (hedge _) _ + have dy : y ∈ near C Δ d := g.route_near m cs sub hedge _ _ _ + have anchor (i : Fin 6) : ∃ z, (z = a ∨ z = d) ∧ g.party m col e i ∈ near C Δ z := by + have h₀ : g.party m col e 0 ∈ near C Δ a := by + change g.route m col _ (ix (m.mate e)) ∈ _ + rw [g.route_thick m _ _ _ (m.spec e).1] + exact near_self _ _ _ + have h₁ : g.party m col e 1 ∈ near C Δ a := by + change g.route m col _ (ix (m.mate e)) ∈ _ + rw [g.route_thick m _ _ _ (m.spec e).1] + exact ab + have h₂ : g.party m col e 2 ∈ near C Δ a := by + rw [g.join_source]; split_ifs <;> assumption + have h₃ : g.party m col e 3 ∈ near C Δ d := dy + fin_cases i + · exact ⟨a, .inl rfl, h₀⟩ + · exact ⟨a, .inl rfl, h₁⟩ + · exact ⟨a, .inl rfl, h₂⟩ + · exact ⟨d, .inr rfl, h₃⟩ + · cases col + · exact ⟨a, .inl rfl, h₀⟩ + · exact ⟨d, .inr rfl, h₃⟩ + · cases col + · exact ⟨d, .inr rfl, h₃⟩ + · exact ⟨a, .inl rfl, h₁⟩ + obtain ⟨x, hx, hi⟩ := anchor i + obtain ⟨z, hz, hj⟩ := anchor j + refine (mem_cube _ _ _).mpr ⟨x, near_symm cs _ _ _ hi, z, ?_, hj⟩ + rcases hx with rfl | rfl <;> rcases hz with rfl | rfl + · exact near_self _ _ _ + · exact ad + · exact near_symm cs _ _ _ ad + · exact near_self _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Grouping +end + +/- # Splitting the original unit wires into matched pairs and untouched wires -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset Spectral.Tensor + +variable {V E P : Type} {h : ℕ} {ix : E → Cell h} + +namespace Matching +variable {src dst : E → P} (m : Matching src dst ix) + +open scoped Classical in +/-- Embeds `m.items × Fin 2` into `E where toFun p`. -/ +def pairEdge : m.items × Fin 2 ↪ E where + toFun p := if p.2 = 0 then m.mate p.1 else p.1.val + inj' := by + rintro ⟨x, i⟩ ⟨y, j⟩ he + have disjoint (a b : m.items) : m.mate a ≠ b.val := fun h => + m.thin _ _ b.property (h ▸ (m.spec a).1) + fin_cases i <;> fin_cases j + · exact Prod.ext (m.mate.injective he) rfl + · exact (disjoint _ _ he).elim + · exact (disjoint _ _ he.symm).elim + · exact Prod.ext (Subtype.ext he) rfl + +open scoped Classical in +/-- The subtype of `e` satisfying `e ∉ Set.range m.pairEdge`. -/ +abbrev unpaired := {e // e ∉ Set.range m.pairEdge} + +open scoped Classical in +/-- Reindexes `(m.items × Fin 2) ⊕ m.unpaired` and `E` by an equivalence. -/ +def partition [Fintype E] : (m.items × Fin 2) ⊕ m.unpaired ≃ E := + (m.pairEdge.toEquivRange.sumCongr (.refl _)).trans (Equiv.Set.sumCompl _) + +open scoped Classical in +/-- Indexes the replaced by the coordinates of `(Σ e : m.items, Σ j : Fin 8, Fin (f e j)) ⊕ +(m.unpaired × Fin b)`. -/ +abbrev replaced (b : ℕ) (f : m.items → Fin 8 → ℕ) := + (Σ e : m.items, Σ j : Fin 8, Fin (f e j)) ⊕ (m.unpaired × Fin b) + +variable [Fintype E] + +open scoped Classical in +theorem card_items : Fintype.card m.items = m.count := Fintype.card_subtype _ + +open scoped Classical in +theorem card_partition : 2 * m.count + Fintype.card m.unpaired = Fintype.card E := by + simpa [Fintype.card_sum, Fintype.card_prod, m.card_items, Nat.mul_comm] using + Fintype.card_congr m.partition + +end Matching + +namespace Grouping + +variable [Fintype V] {N C : V → Finset V} {Δ D k : ℕ} + {B : ℝ} {l : V → Cell h → ℝ} (g : Grouping N C Δ D k B l) + {src dst : E → V} (m : Matching (g.ends src ix) (g.ends dst ix) ix) + +open scoped Classical in +theorem rep_demand (col : Bool) (e : m.items) (j : Fin 2) : + Prod.map (g.rep m col e) (g.rep m col e) (sixDemandPair j) = + ((src (m.pairEdge (e, j)), ix (m.pairEdge (e, j))), + (dst (m.pairEdge (e, j)), ix (m.pairEdge (e, j)))) := by + fin_cases j <;> rfl + +variable {b : ℕ} {f : m.items → Fin 8 → ℕ} + +open scoped Classical in +/-- Endpoints before removing loops. A replacement edge has width +one `b`-th of an original unit. -/ +def contact (col : Bool) : m.replaced b f → Site V h × Site V h + | .inl ⟨e, j, _⟩ => Prod.map (g.party m col e) (g.party m col e) (sixPair j) + | .inr (e, _) => (g.route m col (src e.val) (ix e.val), g.route m col (dst e.val) (ix e.val)) + +open scoped Classical in +theorem contact_mem (cs : ∀ v w, w ∈ C v → v ∈ C w) (sub : ∀ v, C v ⊆ N v) + (hedge : ∀ e, dst e ∈ C (src e)) (col : Bool) (s : m.replaced b f) : + (g.contact m col s).2 ∈ cube (near C Δ) (g.contact m col s).1 := by + rcases s with ⟨e, j, t⟩ | ⟨e, t⟩ + · exact g.party_near m cs sub hedge col e _ _ + · exact g.contact_core m cs sub hedge col (hedge _) _ + +end Grouping +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Treating a group index as an extra host coordinate -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V : Type} {h : ℕ} + +open scoped Classical in +/-- The value specified by `N p.1 ×ˢ {p.2}`. -/ +def inGroup (a : ℕ) (N : V → Finset V) (p : V × Cell a) := N p.1 ×ˢ {p.2} + +open scoped Classical in +@[simp] theorem mem_inGroup (a : ℕ) (N : V → Finset V) (p q : V × Cell a) : + q ∈ inGroup a N p ↔ q.1 ∈ N p.1 ∧ q.2 = p.2 := by + simp only [inGroup, mem_product, mem_singleton] + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def splitCell (a : ℕ) (ha : a ≤ h) : Cell h ≃ Cell a × Cell (h - a) := + Equiv.ofBijective (fun x => (ancestor ha x, suffix a x)) (by + apply (Fintype.bijective_iff_injective_and_card _).mpr + refine ⟨?_, by rw [Fintype.card_prod, card_cell, card_cell, card_cell, ← pow_add, + Nat.add_sub_of_le ha]⟩ + intro x y e + obtain ⟨hp, hs⟩ := Prod.mk.inj e + funext i + by_cases hi : i.val < a + · exact congrFun hp ⟨i, hi⟩ + · have he := congrFun hs ⟨i.val - a, by have := i.isLt; omega⟩ + simpa [suffix, Nat.add_sub_of_le (Nat.le_of_not_gt hi)] using he) + +open scoped Classical in +/-- Reindexes `V × Cell h` and `(V × Cell a) × Cell (h - a)` by an equivalence. -/ +def splitAddr (V : Type) (a : ℕ) (ha : a ≤ h) : + V × Cell h ≃ (V × Cell a) × Cell (h - a) := + ((Equiv.refl V).prodCongr (splitCell a ha)).trans (Equiv.prodAssoc _ _ _).symm + +namespace HostNet + +variable {F T : Type} {x y : Wire} {u : ℕ} {L : Fringe x y T} + (G : HostNet F L h u) (a : ℕ) (ha : a ≤ h) + +open scoped Classical in +/-- Splits the address into a group prefix and an offset within that group. -/ +def regroup : HostNet F L (h - a) u where + diagram := G.diagram + V := G.V × Cell a + E := G.E + src e := (G.src e, ancestor ha (G.ix e)) + dst e := (G.dst e, ancestor ha (G.ix e)) + ix e := suffix a (G.ix e) + units := { + place := splitAddr G.V a ha ∘ G.units.place + bits := G.units.bits + left e := congrArg (splitAddr G.V a ha) (G.units.left e) + right e := congrArg (splitAddr G.V a ha) (G.units.right e) } + park := splitAddr G.V a ha ∘ G.park + past := G.past ∘ (splitAddr G.V a ha).symm + frozen v := G.frozen v.1 + N := inGroup a G.N + C := inGroup a G.C + ns v z he := by rw [mem_inGroup] at he ⊢; exact ⟨G.ns _ _ he.1, he.2.symm⟩ + cs v z he := by rw [mem_inGroup] at he ⊢; exact ⟨G.cs _ _ he.1, he.2.symm⟩ + sub v z he := by rw [mem_inGroup] at he ⊢; exact ⟨G.sub _ he.1, he.2⟩ + kept := G.kept + core := G.core + edge e := (mem_inGroup _ _ _ _).mpr ⟨G.edge e, rfl⟩ + tether q := by + obtain ⟨hp, hi, hz⟩ := G.tether q + exact ⟨hp, congrArg (suffix a) hi, (mem_inGroup _ _ _ _).mpr + ⟨hz, congrArg (ancestor ha) hi.symm⟩⟩ + +open scoped Classical in +@[simp] theorem regroup_X : (G.regroup a ha).X = G.X := rfl + +open scoped Classical in +@[simp] theorem regroup_mass : (G.regroup a ha).mass = G.mass := + (splitAddr G.V a ha).symm.sum_comp G.past + +open scoped Classical in +@[simp] theorem regroup_rate : (G.regroup a ha).rate = G.rate := by + rw [rate, rate, regroup_mass] + +variable [Fintype T] + +open scoped Classical in +theorem regroup_load (p : G.V × Cell h) : + (G.regroup a ha).load (splitAddr G.V a ha p).1 (splitAddr G.V a ha p).2 = + G.load p.1 p.2 := by + let e := splitAddr G.V a ha + have ex : (exterior G.diagram (e ∘ G.units.place) (e p) : ℝ) = G.tetherLoad p := by + rw [exterior_comp] + simp [push, tetherLoad] + have ed : degree (fun i => Prod.map e e (G.pair i)) (e p) = degree G.pair p := by + rw [degree_map] + simp + have ep : push (e ∘ G.park) L.charge (e p) = push G.park L.charge p := by + simp only [push, Function.comp_apply, Equiv.apply_eq_iff_eq] + congr! 2 + change (exterior G.diagram (e ∘ G.units.place) (e p) : ℝ) + + degree (fun i => Prod.map e e (G.pair i)) (e p) * (u : ℝ) + + L.scale * push (e ∘ G.park) L.charge (e p) + + (G.regroup a ha).rate * G.past (e.symm (e p)) = _ + rw [ex, ed, ep, regroup_rate, Equiv.symm_apply_apply] + rfl + +open scoped Classical in +theorem regroup_bounded {Δ D : ℕ} {B : ℝ} (h : G.Bounded Δ D B) : + (G.regroup a ha).Bounded Δ D B := by + refine ⟨fun p => ?_, fun p => ?_, fun v x => ?_⟩ + · change (inGroup a G.C p).card ≤ _ + simpa [inGroup] using h.1 p.1 + · change (inGroup a G.N p).card ≤ _ + simpa [inGroup] using h.2.1 p.1 + · obtain ⟨p, hp⟩ := (splitAddr G.V a ha).surjective (v, x) + have ht := (G.regroup_load a ha p).le.trans (h.2.2 _ _) + rwa [hp] at ht + +end HostNet +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Projecting simultaneous contractions onto a common host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V : Type} {a h : ℕ} + +open scoped Classical in +/-- Reindexes `Site (V × Cell a) h` and `Site V h × Cell a where toFun p` by an equivalence. -/ +def splitSite : Site (V × Cell a) h ≃ Site V h × Cell a where + toFun p := ((p.1.1, p.2), p.1.2) + invFun q := ((q.1.1, q.2), q.1.2) + left_inv _ := rfl + right_inv _ := rfl + +variable [Fintype V] + +open scoped Classical in +theorem split_near (N : V → Finset V) (D : ℕ) {p q : Site (V × Cell a) h} + (he : q ∈ near (inGroup a N) D p) : + (splitSite p).2 = (splitSite q).2 ∧ (splitSite q).1 ∈ near N D (splitSite p).1 := by + rcases (mem_near _ _ _ _).mp he with rfl | ⟨hn, hx, h₁, h₂⟩ + · exact ⟨rfl, near_self _ _ _⟩ + obtain ⟨hn, hi⟩ := (mem_inGroup _ _ _ _).mp hn + exact ⟨hi.symm, (mem_near _ _ _ _).mpr (.inr ⟨hn, hx, h₁, h₂⟩)⟩ + +open scoped Classical in +theorem split_cube (N : V → Finset V) (D : ℕ) {p q : Site (V × Cell a) h} + (he : q ∈ cube (near (inGroup a N) D) p) : + (splitSite p).2 = (splitSite q).2 ∧ (splitSite q).1 ∈ cube (near N D) (splitSite p).1 := by + obtain ⟨x, hx, y, hy, hz⟩ := (mem_cube _ _ _).mp he + obtain ⟨ix, hx⟩ := split_near N D hx + obtain ⟨iy, hy⟩ := split_near N D hy + obtain ⟨iz, hz⟩ := split_near N D hz + exact ⟨ix.trans (iy.trans iz), (mem_cube _ _ _).mpr ⟨_, hx, _, hy, hz⟩⟩ + +open scoped Classical in +theorem cube_near_card (N : V → Finset V) (D : ℕ) (hD : 0 < D) + (deg : ∀ v, (N v).card ≤ D) (p : Site V h) : + (cube (near N D) p).card ≤ (4 * D) ^ 900 := by + rw [show (900 : ℕ) = 300 * 3 by decide, pow_mul] + exact cube_card _ (near_card N D hD deg) p + +namespace HostNet + +variable {F T : Type} {x y : Wire} {u : ℕ} {L : Fringe x y T} + +open scoped Classical in +/-- Separate group labels from the slots of the common host. -/ +structure Projection (G : HostNet F L h u) (Δ D a : ℕ) where + /-- The `Projection` component of type `Type`. -/ + W : Type + [fw : Fintype W] + /-- Reindexes the data using `Site G.V h ≃ W × Cell a`. -/ + place : Site G.V h ≃ W × Cell a + /-- The `Projection` component of type `W → Finset W`. -/ + N : W → Finset W + /-- The `Projection` component of type `W → Finset W`. -/ + C : W → Finset W + ns : ∀ v z, z ∈ N v → v ∈ N z + cs : ∀ v z, z ∈ C v → v ∈ C z + sub : ∀ v, C v ⊆ N v + /-- The `Projection` component of type `W → Prop`. -/ + frozen : W → Prop + keep : ∀ p, frozen (place p).1 ↔ G.frozen p.1 + core : ∀ p q, q ∈ cube (near G.C Δ) p → (place p).2 = (place q).2 ∧ (place q).1 ∈ C (place p).1 + full : ∀ p q, q ∈ cube (near G.N D) p → (place p).2 = (place q).2 ∧ (place q).1 ∈ N (place p).1 + +attribute [instance] Projection.fw + +open scoped Classical in +/-- The quantity computed by `Site G.V (h - a) place := splitSite N := cube (near G.N D) C := +cube (near G.C Δ)`. -/ +def project (G : HostNet F L h u) (a : ℕ) (ha : a ≤ h) (Δ D : ℕ) (hle : Δ ≤ D) : + (G.regroup a ha).Projection Δ D a where + W := Site G.V (h - a) + place := splitSite + N := cube (near G.N D) + C := cube (near G.C Δ) + ns := cube_symm _ (near_symm G.ns _) + cs := cube_symm _ (near_symm G.cs _) + sub := cube_mono _ (near_mono G.sub hle) + frozen p := G.frozen p.1 + keep _ := Iff.rfl + core _ _ := split_cube G.C Δ + full _ _ := split_cube G.N D + +end HostNet +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Sums of networks sharing a fringe + +The budget `n` bounds the selector length in bits. Composition with +selector-dependent choices uses a dependent sum, so each term keeps its +multiplicity even when some of the resulting networks coincide. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet + +open Finset + +variable {F T : Type} {x y : Wire} {h u a z b w : ℕ} {L : Fringe x y T} + +/-- Counts the elements of `G.V * 2 ^ h`. -/ +def seats (G : HostNet F L h u) := Fintype.card G.V * 2 ^ h + +theorem seats_le (G : HostNet F L h u) (Q : HostNet F L a z) + (ha : a ≤ h) {K : ℕ} (hs : Fintype.card Q.V ≤ K * 2 ^ (h - a) * Fintype.card G.V) : + Q.seats ≤ K * G.seats := by + unfold seats + refine (Nat.mul_le_mul_right _ hs).trans_eq ?_ + have he : 2 ^ (h - a) * 2 ^ a = (2 : ℕ) ^ h := by rw [← pow_add, Nat.sub_add_cancel ha] + rw [← he] + ring + +variable [Field F] {G : HostNet F L h u} + +/-- The expands of type `Prop` for the given inputs. -/ +def Expands (G : HostNet F L h u) (n : ℕ) (P : HostNet F L a z → Prop) : Prop := + ∃ (I : Type) (_ : Fintype I) (q : I → HostNet F L a z), Fintype.card I ≤ 2 ^ n ∧ + (∀ x y, ∑ i, (q i).diagram.eval x y = G.diagram.eval x y) ∧ ∀ i, G.Preserves (q i) ∧ P (q i) + +variable {P P' : HostNet F L a z → Prop} {Q : HostNet F L b w → Prop} {n m : ℕ} + +theorem Expands.single (q : HostNet F L a z) (he : ∀ x y, q.diagram.eval x y = G.diagram.eval x y) + (hp : G.Preserves q) (hq : P q) : G.Expands n P := + ⟨Unit, inferInstance, fun _ => q, Nat.one_le_pow _ _ (by decide), + fun x y => by simpa using he x y, fun _ => ⟨hp, hq⟩⟩ + +theorem Expands.mono (h₁ : G.Expands n P) (hn : n ≤ m) (h₂ : ∀ q, P q → P' q) : + G.Expands m P' := by + obtain ⟨I, _, q, hi, he, h⟩ := h₁ + exact ⟨I, inferInstance, q, hi.trans (Nat.pow_le_pow_right (by decide) hn), he, + fun i => ⟨(h i).1, h₂ _ (h i).2⟩⟩ + +theorem Expands.bind (hf : G.Expands n P) (hg : ∀ q, P q → q.Expands m Q) : + G.Expands (n + m) Q := by + obtain ⟨I, _, q, hi, he, hp⟩ := hf + choose J hJ t ht he' hp' using fun i => hg (q i) (hp i).2 + let : ∀ i, Fintype (J i) := hJ + refine ⟨Σ i, J i, inferInstance, fun p => t p.1 p.2, ?_, ?_, ?_⟩ + · rw [Fintype.card_sigma, pow_add] + refine le_trans (sum_le_sum (s := univ) fun i _ => ht i) ?_ + simpa only [sum_const, card_univ, Nat.nsmul_eq_mul] using Nat.mul_le_mul_right (2 ^ m) hi + · intro x y + rw [Fintype.sum_sigma] + simp only [he', he] + · exact fun p => ⟨(hp p.1).1.trans (hp' p.1 p.2).1, (hp' p.1 p.2).2⟩ + +variable [Fintype T] + +omit [Field F] in +theorem Bounded.mono {G : HostNet F L h u} {Δ Δ' D D' : ℕ} {B B' : ℝ} + (hg : G.Bounded Δ D B) (hΔ : Δ ≤ Δ') (hD : D ≤ D') (hB : B ≤ B') : + G.Bounded Δ' D' B' := + ⟨fun v => (hg.1 v).trans hΔ, fun v => (hg.2.1 v).trans hD, + fun v i => (hg.2.2 v i).trans hB⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- +# Tether ends through a sequence of core contractions + +The set of possible source positions of a tether depends only on core +degrees, even when the full host has much larger degree. Counting +destinations also pays the ratio of block counts. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet + +open Finset + +variable {F T : Type} {x y : Wire} {L : Fringe x y T} {h a b u z w : ℕ} + (G : HostNet F L h u) (Q : HostNet F L a z) (R : HostNet F L b w) + +open scoped Classical in +/-- The value specified by `(G.units.place (portEnd G.diagram t)).1`. -/ +def tip (t : slots x ⊕ slots y) := (G.units.place (portEnd G.diagram t)).1 + +open scoped Classical in +/-- The indexed operation `(univ.filter fun t => G.tip t = v).image Q.tip`. -/ +def reach (v : G.V) : Finset Q.V := + (univ.filter fun t => G.tip t = v).image Q.tip + +open scoped Classical in +theorem mem_reach {v : G.V} {q : Q.V} : + q ∈ G.reach Q v ↔ ∃ t, G.tip t = v ∧ Q.tip t = q := by simp [reach] + +open scoped Classical in +theorem reach_self (t : slots x ⊕ slots y) : Q.tip t ∈ G.reach Q (G.tip t) := + (mem_reach _ _).mpr ⟨t, rfl, rfl⟩ + +open scoped Classical in +private theorem chain {K K' : ℕ} (hg : ∀ p, (G.reach Q p).card ≤ K) + (hq : ∀ p, (Q.reach R p).card ≤ K') (v : G.V) : (G.reach R v).card ≤ K * K' := by + have sub : G.reach R v ⊆ (G.reach Q v).biUnion (Q.reach R) := by + intro t ht + obtain ⟨i, rfl, rfl⟩ := (mem_reach _ _).mp ht + exact mem_biUnion.mpr ⟨Q.tip i, reach_self _ _ i, reach_self _ _ i⟩ + refine (card_le_card sub).trans (card_biUnion_le.trans ?_) + refine (sum_le_sum (fun t _ => hq t)).trans ?_ + simpa only [sum_const, Nat.nsmul_eq_mul] using Nat.mul_le_mul_right K' (hg v) + +open scoped Classical in +/-- Requires `(∀ v, (Q.reach G v).card ≤ K) ∧ (∀ v, (G.reach Q v).card ≤ K * 2 ^ (h - a))`. -/ +def Tracks (K : ℕ) : Prop := + (∀ v, (Q.reach G v).card ≤ K) ∧ (∀ v, (G.reach Q v).card ≤ K * 2 ^ (h - a)) + +variable {G Q R} {K H : ℕ} + +open scoped Classical in +theorem Tracks.mono (p : G.Tracks Q K) (h : K ≤ H) : G.Tracks Q H := + ⟨fun v => (p.1 v).trans h, fun v => (p.2 v).trans (Nat.mul_le_mul_right _ h)⟩ + +open scoped Classical in +theorem Tracks.trans (p : G.Tracks Q K) (q : Q.Tracks R H) (ha : a ≤ h) (hb : b ≤ a) : + G.Tracks R (H * K) := by + refine ⟨chain R Q G q.1 p.1, fun v => (chain G Q R p.2 q.2 v).trans_eq ?_⟩ + rw [show h - b = (h - a) + (a - b) by omega, pow_add] + ring + +open scoped Classical in +/-- Individual stations can move to a neighbor's slots. -/ +theorem tracks_of_slots {A : Type} [Finite A] (f : Q.V ≃ G.V × A) (N : G.V → Finset G.V) + (hN : ∀ u v, v ∈ N u → u ∈ N v) (hsize : ∀ v, (N v).card ≤ K) + (hpos : 0 < H) (seats : Fintype.card Q.V ≤ H * 2 ^ (h - a) * Fintype.card G.V) + (loc : ∀ t, (f (Q.tip t)).1 ∈ N (G.tip t)) : G.Tracks Q (K * H) := by + let : Fintype A := Fintype.ofFinite A + constructor + · intro q + refine (card_le_card (t := N (f q).1) ?_).trans ((hsize _).trans (Nat.le_mul_of_pos_right _ + hpos)) + intro v hv + obtain ⟨t, rfl, rfl⟩ := (mem_reach _ _).mp hv + exact hN _ _ (loc t) + intro v + have bound : Fintype.card A ≤ H * 2 ^ (h - a) := by + rw [Fintype.card_congr f, Fintype.card_prod, mul_comm (Fintype.card G.V)] at seats + exact Nat.le_of_mul_le_mul_right seats (Fintype.card_pos_iff.mpr ⟨v⟩) + have sub : (G.reach Q v).image f ⊆ (N v) ×ˢ univ := by + intro q hq + obtain ⟨z, hz, rfl⟩ := mem_image.mp hq + obtain ⟨t, rfl, rfl⟩ := (mem_reach _ _).mp hz + exact mem_product.mpr ⟨loc t, mem_univ _⟩ + have hc := card_le_card sub + rw [card_image_of_injective _ f.injective, card_product, card_univ] at hc + rw [mul_assoc] + exact hc.trans (Nat.mul_le_mul (hsize _) bound) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- +# Composing grouping steps + +The width estimate is affine in the old width and the sum of frozen +charge and slack. The other bounds are multiplicative. Counting seats +(host positions times blocks) makes the slack estimate independent of +how many blocks are grouped at a step. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open HostNet + +/-- A reduction with subdivision factor `b`, using `n` grouping steps, +full-degree exponent `e` and overhead `K`. The selector length is +bounded in units of the output width, even across composed reductions. -/ +structure Reduction (F : Type) [Field F] (Δ Δ' b n e K : ℕ) (ρ C : ℝ) : Prop where + unit : 0 < b + overhead : 0 < K + degree : ∀ D, Δ ≤ D → Δ' ≤ D ^ e + factor : 0 ≤ ρ + loss : 0 ≤ C + run : ∀ {T : Type} [Fintype T] {x y : Wire} {L : Fringe x y T} + {h u : ℕ} (G : HostNet F L h u) (z r a D M : ℕ) (B σ : ℝ), + 0 < z → u = b * z → u ≤ B → Δ ≤ D → G.Bounded Δ D B → 0 ≤ σ → + a + n * r ≤ h → K ≤ 2 ^ r → (K : ℝ) * B * G.seats ≤ σ * (2 : ℝ) ^ r → G.X + (L.Z + σ) + ≤ (M : ℝ) * z → + G.Expands (K * M) (fun Q : HostNet F L a z => + Q.seats ≤ K * G.seats ∧ Q.Bounded Δ' (D ^ e) (K * B) ∧ Q.X ≤ ρ * G.X + C * (L.Z + σ) ∧ + (Q.mass : ℝ) ≤ G.mass + 2 * (K : ℝ) * (G.X + (L.Z + σ)) ∧ G.Tracks Q K) + +namespace Reduction + +variable {F : Type} [Field F] {Δ Δ' Δ'' b b' n n' e e' K K' : ℕ} {ρ ρ' C C' : ℝ} + +/-- The quantity computed by `K + K * K + ⌈ρ + C + 1⌉₊`. -/ +def fee (K : ℕ) (ρ C : ℝ) := K + K * K + ⌈ρ + C + 1⌉₊ + +theorem comp (p : Reduction F Δ Δ' b n e K ρ C) (q : Reduction F Δ' Δ'' b' n' e' K' ρ' C') : + Reduction F Δ Δ'' (b * b') (n + n') (e * e') (fee K ρ C * K') (ρ' * ρ) (ρ' * C + C') := by + let s := ⌈ρ + C + 1⌉₊ + let H := fee K ρ C * K' + have hk := p.overhead + have hk' := q.overhead + have hf : K + K' * s ≤ H := by + calc + _ ≤ K * K' + K' * s := Nat.add_le_add_right (Nat.le_mul_of_pos_right _ hk') _ + _ = (K + s) * K' := by ring + _ ≤ _ := Nat.mul_le_mul_right _ (by unfold fee; omega) + have hm : K' * K * K ≤ H := by + rw [mul_assoc, mul_comm K'] + exact Nat.mul_le_mul_right _ (by unfold fee; omega) + have hprod : K' * K ≤ H := (Nat.le_mul_of_pos_right _ hk).trans hm + have hkH : K ≤ H := (Nat.le_add_right _ _).trans hf + have hkH' : K' ≤ H := (Nat.le_mul_of_pos_right _ hk).trans hprod + refine ⟨Nat.mul_pos p.unit q.unit, hk.trans_le hkH, ?_, mul_nonneg q.factor p.factor, + add_nonneg (mul_nonneg q.factor p.loss) q.loss, ?_⟩ + · intro D hd + rw [pow_mul] + exact q.degree _ (p.degree _ hd) + intro T _ x y L h u G z r a D M B σ hz hu huB hD hb hσ ha hr slack budget + let mid := a + n' * r + let U := b' * z + have hB : 0 ≤ B := (Nat.cast_nonneg u).trans huB + have hL : 0 ≤ L.Z + σ := add_nonneg L.total_nonneg hσ + have hu' : u = b * U := by unfold U; rw [hu, mul_assoc] + have hz' : 0 < U := Nat.mul_pos q.unit hz + have hU : U ≤ u := by rw [hu']; exact Nat.le_mul_of_pos_left _ p.unit + have hzu : z ≤ U := Nat.le_mul_of_pos_left _ q.unit + have hs : (K : ℝ) * B * G.seats ≤ σ * (2 : ℝ) ^ r := by + refine le_trans ?_ slack + gcongr + have hl := p.run G U r mid D M B σ hz' hu' huB hD hb hσ + (by unfold mid; rw [add_mul] at ha; omega) (hkH.trans hr) hs + (budget.trans (mul_le_mul_of_nonneg_left (Nat.cast_le.mpr hzu) (Nat.cast_nonneg _))) + have sel : K * M + K' * (s * M) ≤ H * M := by + rw [← mul_assoc, ← add_mul] + exact Nat.mul_le_mul_right _ hf + refine (hl.bind (m := K' * (s * M)) ?_).mono sel (fun _ h => h) + rintro Q ⟨hseat, hbound, hwidth, hist, track⟩ + have hub' : (U : ℝ) ≤ (K : ℝ) * B := calc + _ ≤ (u : ℝ) := Nat.cast_le.mpr hU + _ ≤ B := huB + _ ≤ _ := le_mul_of_one_le_left hB (by exact_mod_cast hk) + have hs' : (K' : ℝ) * (K * B) * Q.seats ≤ σ * 2 ^ r := calc + _ ≤ (K' : ℝ) * (K * B) * (K * G.seats) := by gcongr; exact_mod_cast hseat + _ = ((K' * K * K : ℕ) : ℝ) * B * G.seats := by push_cast; ring + _ ≤ (H : ℝ) * B * G.seats := by gcongr + _ ≤ _ := slack + have hQ : Q.X + (L.Z + σ) ≤ (s : ℝ) * (G.X + (L.Z + σ)) := calc + _ ≤ (ρ + C + 1) * (G.X + (L.Z + σ)) := by + nlinarith only [hwidth, mul_nonneg p.factor hL, + mul_nonneg p.loss (Nat.cast_nonneg (α := ℝ) G.X), Nat.cast_nonneg (α := ℝ) G.X] + _ ≤ _ := mul_le_mul_of_nonneg_right (Nat.le_ceil _) (by positivity) + have ht : Q.X + (L.Z + σ) ≤ ((s * M : ℕ) : ℝ) * z := by + rw [Nat.cast_mul, mul_assoc] + exact hQ.trans (mul_le_mul_of_nonneg_left budget (Nat.cast_nonneg _)) + have hh := q.run Q z r a (D ^ e) (s * M) _ σ hz rfl hub' (p.degree _ hD) hbound hσ + le_rfl (hkH'.trans hr) hs' ht + refine hh.mono le_rfl ?_ + rintro R ⟨hseat', hbound', hwidth', hist', track'⟩ + refine ⟨hseat'.trans ?_, hbound'.mono le_rfl (pow_mul _ _ _).ge ?_, ?_, ?_, + (track.trans track' (by + unfold mid + rw [add_mul] at ha + omega) (Nat.le_add_right _ _)).mono hprod⟩ + · exact (Nat.mul_le_mul_left _ hseat).trans (by + rw [← mul_assoc] + exact Nat.mul_le_mul_right _ hprod) + · rw [← mul_assoc, ← Nat.cast_mul] + exact mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hprod) hB + · have hw := mul_le_mul_of_nonneg_left hwidth q.factor + linarith + · calc + (R.mass : ℝ) ≤ Q.mass + 2 * (K' : ℝ) * (Q.X + (L.Z + σ)) := hist' + _ ≤ (G.mass + 2 * (K : ℝ) * (G.X + (L.Z + σ))) + + 2 * (K' : ℝ) * ((s : ℝ) * (G.X + (L.Z + σ))) := + add_le_add hist (mul_le_mul_of_nonneg_left hQ (by positivity)) + _ = G.mass + 2 * ((K + K' * s : ℕ) : ℝ) * (G.X + (L.Z + σ)) := by push_cast; ring + _ ≤ G.mass + 2 * (H : ℝ) * (G.X + (L.Z + σ)) := by gcongr + +end Reduction +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Reservations.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Reservations.lean new file mode 100644 index 0000000000..169053914d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Reservations.lean @@ -0,0 +1,610 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import Mathlib.Algebra.BigOperators.Field +public import Mathlib.Algebra.Order.Archimedean.Real.Basic +public import Mathlib.FieldTheory.Finite.GaloisField +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array + +/-! +# Summing the charges for propagated splits + +The propagation weight doubles every eight levels. Splits at depth `j` +below a base are paid for at rate `min (2^-k) (2^-j)`, where the minimum +base length is `F = 2^k`. The sum is at most `24 * 2^⌈k/8⌉ / 2^k`. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +/-- The quantity computed by `(2 : ℝ) ^ ((j + 7) / 8)`. -/ +def resetWeight (j : ℕ) := (2 : ℝ) ^ ((j + 7) / 8) + +private theorem weight_nonneg (j : ℕ) : 0 ≤ resetWeight j := by + unfold resetWeight + positivity + +private theorem weight_mono : Monotone resetWeight := by + intro i j hij + exact pow_le_pow_right₀ (by norm_num) (by omega) + +private theorem weight_add (j : ℕ) : resetWeight (j + 8) = 2 * resetWeight j := by + unfold resetWeight + rw [show (j + 8 + 7) / 8 = (j + 7) / 8 + 1 by omega, pow_succ'] + +private theorem prefix_bound (k : ℕ) : + ∑ j ∈ range k, resetWeight j ≤ 16 * resetWeight k := by + have h : 2 * ∑ j ∈ range k, resetWeight j ≤ ∑ j ∈ range (k + 8), resetWeight j := by + rw [Nat.add_comm k 8, sum_range_add] + simp only [Nat.add_comm 8, weight_add, ← mul_sum] + exact le_add_of_nonneg_left (sum_nonneg fun j _ => weight_nonneg j) + have ht : ∑ j ∈ range 8, resetWeight (k + j) ≤ 16 * resetWeight k := by + calc + _ ≤ ∑ _j ∈ range 8, resetWeight (k + 8) := sum_le_sum fun j hj => + weight_mono (Nat.add_le_add_left (mem_range.mp hj).le k) + _ = _ := by simp [weight_add]; ring + rw [sum_range_add] at h + linarith + +private theorem tail_bound (k n : ℕ) : + ∑ j ∈ range n, resetWeight (k + j) / (2 : ℝ) ^ (k + j) ≤ + (4 * resetWeight k + 2 * resetWeight (k + 1)) / (2 : ℝ) ^ k := by + induction n generalizing k with + | zero => + have := weight_nonneg k + have := weight_nonneg (k + 1) + simp only [range_zero, sum_empty] + positivity + | succ n ih => + rw [sum_range_succ'] + have he : (∑ j ∈ range n, resetWeight (k + (j + 1)) / (2 : ℝ) ^ (k + (j + 1))) = + ∑ j ∈ range n, resetWeight (k + 1 + j) / (2 : ℝ) ^ (k + 1 + j) := + sum_congr rfl (fun j _ => by rw [show k + (j + 1) = k + 1 + j by omega]) + rw [he, Nat.add_zero] + apply (add_le_add_left (ih (k + 1)) (resetWeight k / (2 : ℝ) ^ k)).trans + have hu := weight_mono (show k + 1 + 1 ≤ k + 8 by omega) + rw [weight_add] at hu + rw [pow_succ] + field_simp + linarith [weight_nonneg k] + +theorem resetWeight_bound (k n : ℕ) : + ∑ j ∈ range n, resetWeight j / (2 : ℝ) ^ (max k j) ≤ + 24 * resetWeight k / (2 : ℝ) ^ k := by + calc + _ ≤ ∑ j ∈ range (k + n), resetWeight j / (2 : ℝ) ^ (max k j) := + sum_le_sum_of_subset_of_nonneg (range_mono (by omega)) + (fun j _ _ => div_nonneg (weight_nonneg j) (by positivity)) + _ = (∑ j ∈ range k, resetWeight j) / (2 : ℝ) ^ k + + ∑ j ∈ range n, resetWeight (k + j) / (2 : ℝ) ^ (k + j) := by + rw [sum_range_add, sum_div] + congr 1 + · apply sum_congr rfl + intro j hj + rw [max_eq_left (mem_range.mp hj).le] + · simp only [max_eq_right (Nat.le_add_right k _)] + _ ≤ 16 * resetWeight k / (2 : ℝ) ^ k + + (4 * resetWeight k + 2 * resetWeight (k + 1)) / (2 : ℝ) ^ k := + add_le_add (div_le_div_of_nonneg_right (prefix_bound k) (by positivity)) (tail_bound k n) + _ ≤ _ := by + have hu := weight_mono (show k + 1 ≤ k + 8 by omega) + rw [weight_add] at hu + rw [← add_div] + exact div_le_div_of_nonneg_right (by linarith) (by positivity) + +/-- The required minimum base length depends only on the safety margin +and error tolerance, even with arbitrarily many tether neighbors. -/ +theorem small_resetWeight (g ε : ℝ) (hε : 0 < ε) (j : ℕ) : + ∃ k ≥ j, 144 * resetWeight k / (2 : ℝ) ^ k + 4 * g ^ 2 / (2 : ℝ) ^ k ≤ ε := by + obtain ⟨n, hn⟩ := exists_nat_gt ((144 + 4 * g ^ 2) / ε) + let r := max n j + have hN : (n : ℝ) ≤ (2 : ℝ) ^ r := by + exact_mod_cast (le_max_left n j).trans (Nat.lt_two_pow_self (n := r)).le + have h : 144 + 4 * g ^ 2 ≤ (2 : ℝ) ^ r * ε := (div_le_iff₀ hε).mp (hn.le.trans hN) + refine ⟨8 * r, by dsimp [r]; omega, ?_⟩ + rw [resetWeight, show (8 * r + 7) / 8 = r by omega, ← add_div, div_le_iff₀ (by positivity)] + have hr : 1 ≤ (2 : ℝ) ^ r := one_le_pow₀ (by norm_num) + calc + _ ≤ (144 + 4 * g ^ 2) * (2 : ℝ) ^ r := by + rw [add_mul] + exact add_le_add_right (le_mul_of_one_le_right (by positivity) hr) _ + _ ≤ ((2 : ℝ) ^ r * ε) * (2 : ℝ) ^ r := mul_le_mul_of_nonneg_right h (by positivity) + _ = ε * (2 : ℝ) ^ (r + r) := by rw [pow_add]; ring + _ ≤ _ := mul_le_mul_of_nonneg_left (pow_le_pow_right₀ (by norm_num) (by omega)) hε.le + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Excess loads in the degree reset + +Normalize by the capacity `FB`. Loads at most `1/F` with base mean +at most one obey two complementary bounds. The variance pays for near +overloads and the off-diagonal term for distant ones. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +variable {h : ℕ} (l : Cell h → ℝ) (π : Equiv.Perm (Cell h)) (i : ℕ) + +/-- The sum of `if 2 < load l π i z then load l π i z else 0` indexed by `z : Cell i`. -/ +def excess := ∑ z : Cell i, if 2 < load l π i z then load l π i z else 0 + +theorem overload_count : + 2 * (∑ z, if 2 < load l π i z then (1 : ℝ) else 0) ≤ excess l π i := by + rw [mul_sum] + apply sum_le_sum + intro z _ + split_ifs <;> linarith + +theorem excess_variance (hm : mean l i ≤ 1) : + excess l π i ≤ 2 * variance l π i := by + unfold variance + rw [mul_sum] + apply sum_le_sum + intro z _ + split_ifs with hz + · have := sq_nonneg (load l π i z - mean l i - 1) + nlinarith + · positivity + +theorem excess_cross (hl : ∀ x, 0 ≤ l x ∧ l x ≤ 1) : + excess l π i ≤ 2 * ∑ z, cross l π i z := by + rw [mul_sum] + apply sum_le_sum + intro z _ + split_ifs with hz + · unfold cross + nlinarith [diagonal_le l π i z hl] + · exact mul_nonneg (by norm_num) (cross_nonneg l π i (fun x => (hl x).1) z) + +variable {M : Type} [Fintype M] {p : M → Equiv.Perm (Cell h)} {k b : ℕ} + +private theorem small_variance (hp : Mixes p) (hi : i ≤ h) + (hl : ∀ x, 0 ≤ l x ∧ l x ≤ 1 / (2 : ℝ) ^ k) : + (∑ m, variance l (p m) i) ≤ (Fintype.card M : ℝ) * (∑ x, l x) / (2 : ℝ) ^ k := by + apply (variance_bound l i hp (fun x => (hl x).1) hi).trans + rw [mul_div_assoc, sum_div] + apply mul_le_mul_of_nonneg_left _ (Nat.cast_nonneg _) + apply sum_le_sum + intro x _ + simpa [pow_two, div_eq_mul_inv] using mul_le_mul_of_nonneg_left (hl x).2 (hl x).1 + +/-- Only quadratic moments in this estimator depend on the permutation. -/ +def estimate (k b j : ℕ) : ℝ := + if b + j ≤ h then + if j ≤ k then 2 * variance l π (b + j) else 2 * ∑ z, cross l π (b + j) z + else 0 + +theorem excess_le_estimate (hl : ∀ x, 0 ≤ l x ∧ l x ≤ 1 / (2 : ℝ) ^ k) + (hb : ∑ x, l x ≤ (2 : ℝ) ^ b) (j : ℕ) : excess l π (b + j) ≤ estimate l π k b j := by + unfold estimate + split_ifs with hd hj + · apply excess_variance + apply (div_le_one (by positivity : 0 < (2 : ℝ) ^ (b + j))).mpr + exact hb.trans (pow_le_pow_right₀ (by norm_num) (Nat.le_add_right _ _)) + · apply excess_cross + exact fun x => + ⟨(hl x).1, (hl x).2.trans ((div_le_one (by positivity)).mpr (one_le_pow₀ (by norm_num)))⟩ + · simp [excess, load, hd] + +theorem estimate_bound (hp : Mixes p) + (hl : ∀ x, 0 ≤ l x ∧ l x ≤ 1 / (2 : ℝ) ^ k) (hb : ∑ x, l x ≤ (2 : ℝ) ^ b) (j : ℕ) : + (∑ m, estimate l (p m) k b j) ≤ + 2 * (Fintype.card M : ℝ) * (∑ x, l x) / (2 : ℝ) ^ (max k j) := by + have hl₀ x := (hl x).1 + have hs : 0 ≤ ∑ x, l x := sum_nonneg fun x _ => hl₀ x + by_cases hd : b + j ≤ h + swap + · simp only [estimate, ite_eq_right hd, sum_const_zero] + positivity + by_cases hj : j ≤ k + · simp only [estimate, ite_eq_left hd, ite_eq_left hj] + rw [← mul_sum, max_eq_left hj, mul_assoc, mul_div_assoc] + exact mul_le_mul_of_nonneg_left (small_variance l _ hp hd hl) (by norm_num) + · simp only [estimate, ite_eq_left hd, ite_eq_right hj] + calc + _ ≤ 2 * ((Fintype.card M : ℝ) * ((∑ x, l x) ^ 2 / (2 : ℝ) ^ (b + j))) := by + rw [← mul_sum] + exact mul_le_mul_of_nonneg_left (cross_bound l _ hp hl₀ hd) (by norm_num) + _ ≤ _ := by + rw [max_eq_right (le_of_not_ge hj), pow_add] + field_simp + nlinarith [mul_nonneg (mul_nonneg (Nat.cast_nonneg (α := ℝ) (Fintype.card M)) hs) + (sub_nonneg.mpr hb)] + +/-- A bound for a single position, to be summed over positions and contacts. -/ +theorem weighted_estimate (hp : Mixes p) + (hl : ∀ x, 0 ≤ l x ∧ l x ≤ 1 / (2 : ℝ) ^ k) (hb : ∑ x, l x ≤ (2 : ℝ) ^ b) (n : ℕ) : + (∑ m, ∑ j ∈ range n, resetWeight j * estimate l (p m) k b j) ≤ + (Fintype.card M : ℝ) * (48 * resetWeight k / (2 : ℝ) ^ k) * ∑ x, l x := by + have hs : 0 ≤ ∑ x, l x := sum_nonneg fun x _ => (hl x).1 + calc + _ ≤ ∑ j ∈ range n, 2 * (Fintype.card M : ℝ) * (∑ x, l x) * + (resetWeight j / (2 : ℝ) ^ (max k j)) := by + rw [sum_comm] + apply sum_le_sum + intro j _ + rw [← mul_sum] + have he := mul_le_mul_of_nonneg_left (estimate_bound l hp hl hb j) + (show 0 ≤ resetWeight j by unfold resetWeight; positivity) + exact he.trans_eq (by ring) + _ ≤ _ := by + rw [← mul_sum] + have he := mul_le_mul_of_nonneg_left (resetWeight_bound k n) + (show 0 ≤ 2 * (Fintype.card M : ℝ) * (∑ x, l x) by positivity) + exact he.trans_eq (by ring) + +/-- A contact reserves its mean plus a fixed safety margin. -/ +def spills (g : ℝ) := ∑ z : Cell i, if mean l i + 1 / g < load l π i z then (1 : ℝ) else 0 + +theorem spills_variance {g : ℝ} (hg : 0 < g) : spills l π i g ≤ g ^ 2 * variance l π i := by + unfold variance + rw [mul_sum] + apply sum_le_sum + intro z _ + split_ifs with hz + · have hv : 1 ≤ g * (load l π i z - mean l i) := by + rw [mul_comm] + exact (div_le_iff₀ hg).mp (by linarith) + rw [← mul_pow] + exact one_le_pow₀ hv + · positivity + +theorem spill_estimate (hp : Mixes p) (hi : i ≤ h) + (hl : ∀ x, 0 ≤ l x ∧ l x ≤ 1 / (2 : ℝ) ^ k) (g : ℝ) : + (∑ m, g ^ 2 * variance l (p m) i) ≤ + (Fintype.card M : ℝ) * (g ^ 2 / (2 : ℝ) ^ k) * ∑ x, l x := by + rw [← mul_sum] + exact (mul_le_mul_of_nonneg_left (small_variance l i hp hi hl) (sq_nonneg g)).trans_eq + (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +section +/- +# Reservations between pairs of bases + +Two dyadic cells that intersect are nested. Thus each contact is indexed +by a cell at the finer of the two depths, with endpoints obtained by +taking prefixes. Its capacity is the mean over all such cells plus a +safety margin independent of the mixer. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +variable {V A : Type} (base : V → ℕ) (ends : A → Bool → V) + +open scoped Classical in +/-- The maximum of the quantities in `(base (ends c false)) (base (ends c true))`. -/ +def contactDepth (c : A) := max (base (ends c false)) (base (ends c true)) + +open scoped Classical in +theorem le_contactDepth (c : A) (t : Bool) : base (ends c t) ≤ contactDepth base ends c := by + cases t <;> simp [contactDepth] + +open scoped Classical in +/-- Uses `⟨ends w.1 t, ancestor (le_contactDepth base ends w.1 t) w.2⟩` as the representation. -/ +def contactEnd (w : Σ c, Cell (contactDepth base ends c)) (t : Bool) : Σ v, Cell (base v) := + ⟨ends w.1 t, ancestor (le_contactDepth base ends w.1 t) w.2⟩ + +open scoped Classical in +private theorem endpoint_sum (c : A) (t : Bool) (v : V) (z : Cell (base v)) (x : ℝ) : + (∑ w, if contactEnd base ends ⟨c, w⟩ t = ⟨v, z⟩ then x else 0) = + if ends c t = v then (2 : ℝ) ^ (contactDepth base ends c - base v) * x else 0 := by + by_cases he : ends c t = v + · subst v + simp only [contactEnd, Sigma.mk.inj_iff, heq_eq_eq, true_and, ite_true] + rw [← sum_filter, sum_const, nsmul_eq_mul, ← Fintype.card_subtype, + card_prefix (le_contactDepth base ends c t) z] + norm_cast + · have hn (w : Cell (contactDepth base ends c)) : + contactEnd base ends ⟨c, w⟩ t ≠ ⟨v, z⟩ := fun eq => he (congrArg Sigma.fst eq) + simp only [hn, he, ite_false, sum_const_zero] + +open scoped Classical in +theorem reservation_count [Fintype A] (v : V) (z : Cell (base v)) (s : ℕ) (D : ℝ) + (gap : ∀ c t, ends c t = v → contactDepth base ends c ≤ base v + s) + (degree : (∑ c, ∑ t : Bool, if ends c t = v then (1 : ℝ) else 0) ≤ D) : + (∑ c, ∑ t, ∑ w, if contactEnd base ends ⟨c, w⟩ t = ⟨v, z⟩ then (1 : ℝ) else 0) ≤ + D * (2 : ℝ) ^ s := by + refine le_trans ?_ (mul_le_mul_of_nonneg_right degree (by positivity)) + simp only [sum_mul, endpoint_sum, mul_one] + apply sum_le_sum + intro c _ + apply sum_le_sum + intro t _ + split_ifs with he + · rw [one_mul] + have := gap c t he + exact pow_le_pow_right₀ (by norm_num) (by omega) + · simp + +open scoped Classical in +/-- The reserved capacities at a base cost at most two normalized units. -/ +theorem reservation_bound [Fintype A] (y : A → ℝ) (v : V) (z : Cell (base v)) + (s : ℕ) (D : ℝ) (hD : 0 < D) + (gap : ∀ c t, ends c t = v → contactDepth base ends c ≤ base v + s) + (degree : (∑ c, ∑ t : Bool, if ends c t = v then (1 : ℝ) else 0) ≤ D) + (mass : (∑ c, ∑ t : Bool, if ends c t = v then y c else 0) ≤ (2 : ℝ) ^ (base v)) : + (∑ c, ∑ t, ∑ w, if contactEnd base ends ⟨c, w⟩ t = ⟨v, z⟩ then + y c / (2 : ℝ) ^ (contactDepth base ends c) + 1 / (D * (2 : ℝ) ^ s) else 0) ≤ 2 := by + calc + _ ≤ ∑ c, ∑ t : Bool, ((if ends c t = v then y c else 0) / (2 : ℝ) ^ (base v) + + (if ends c t = v then (1 : ℝ) else 0) / D) := by + apply sum_le_sum + intro c _ + apply sum_le_sum + intro t _ + rw [endpoint_sum] + by_cases hv : ends c t = v + swap + · simp [hv] + have lo : base v ≤ contactDepth base ends c := hv ▸ le_contactDepth base ends c t + have hi := gap c t hv + have hr : (2 : ℝ) ^ (contactDepth base ends c - base v) ≤ (2 : ℝ) ^ s := + pow_le_pow_right₀ (by norm_num) (by omega) + simp only [hv, ite_true, mul_add] + have he : (2 : ℝ) ^ (contactDepth base ends c) = + (2 : ℝ) ^ (contactDepth base ends c - base v) * (2 : ℝ) ^ (base v) := by + rw [← pow_add, Nat.sub_add_cancel lo] + rw [he] + apply add_le_add + · field_simp + exact le_rfl + · field_simp + exact hr + _ ≤ _ := by + simp only [sum_add_distrib, ← sum_div] + have := (div_le_one (by positivity : 0 < (2 : ℝ) ^ (base v))).mpr mass + have := (div_le_one hD).mpr degree + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +section +/- +# Mixing block indices by a field multiplier + +Identify binary block indices with a field of order `2 ^ h`. As the +multiplier ranges over units, the difference of any two distinct indices +visits each nonzero vector once. At most `2 ^ (h-i) - 1` of these vectors +have zero prefix of length `i`. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +/-- A single family of linear permutations works simultaneously at all depths. -/ +theorem mixer (h : ℕ) : + ∃ (M : Type) (_ : Fintype M) (_ : Nonempty M) (π : M → Equiv.Perm (Cell h)), + Fintype.card M ≤ 2 ^ h ∧ (∀ m, ∃ f : Cell h ≃ₗ[ZMod 2] Cell h, f.toEquiv = π m) ∧ + Mixes π := by + classical + by_cases hh : h = 0 + · subst h + refine ⟨Unit, inferInstance, inferInstance, fun _ => Equiv.refl _, by simp, + fun _ => ⟨LinearEquiv.refl _ _, rfl⟩, ?_⟩ + exact fun _ _ x y hxy => (hxy (Subsingleton.elim x y)).elim + let E := GaloisField 2 h + let : Fintype E := Fintype.ofFinite _ + let e : Cell h ≃ₗ[ZMod 2] E := + LinearEquiv.ofFinrankEq _ _ (by simp [E, GaloisField.finrank 2 hh]) + let f (m : Eˣ) : Cell h ≃ₗ[ZMod 2] Cell h := + e.trans (((LinearEquiv.smulOfUnit m : E ≃ₗ[E] E).restrictScalars (ZMod 2)).trans e.symm) + have hc : Fintype.card Eˣ + 1 = 2 ^ h := by + rw [Fintype.card_units, Nat.sub_add_cancel Fintype.card_pos, ← Fintype.card_congr e.toEquiv, + card_cell] + refine ⟨Eˣ, inferInstance, inferInstance, fun m => (f m).toEquiv, by omega, + fun m => ⟨f m, rfl⟩, fun i hi x y hxy => ?_⟩ + let B := {m : Eˣ // ancestor hi (f m x) = ancestor hi (f m y)} + let K := {x : Cell h // ancestor hi x = 0} + let g (m : B) : K := ⟨f m.1 (x - y), by + rw [map_sub] + change ancestor hi (f m.1 x) - ancestor hi (f m.1 y) = 0 + exact sub_eq_zero.mpr m.2⟩ + have inj : Function.Injective g := by + intro m n eq + have he : e.symm (m.1.val * e (x - y)) = e.symm (n.1.val * e (x - y)) := + congrArg Subtype.val eq + have hne : e (x - y) ≠ 0 := e.map_eq_zero_iff.not.mpr (sub_ne_zero.mpr hxy) + exact Subtype.ext (Units.ext (mul_right_cancel₀ hne (e.symm.injective he))) + have miss : (⟨0, rfl⟩ : K) ∉ Set.range g := by + rintro ⟨m, hm⟩ + have he : f m.1 (x - y) = 0 := congrArg Subtype.val hm + exact hxy (sub_eq_zero.mp ((f m.1).map_eq_zero_iff.mp he)) + have hsmall := (Fintype.card_lt_of_injective_of_notMem g inj miss).trans_eq (card_prefix hi 0) + have bound : Fintype.card B * 2 ^ i ≤ Fintype.card Eˣ := by + have := Nat.mul_lt_mul_of_pos_right hsmall (by positivity : 0 < 2 ^ i) + rw [← pow_add, Nat.sub_add_cancel hi] at this + omega + rw [Finset.sum_boole, ← Fintype.card_subtype, le_div_iff₀ (by positivity)] + exact_mod_cast bound + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +section +/- # Common reservations and term-specific layers for the core reset -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +variable {P U X W : Type} + (leaf : P → X) (point : U → Bool → P) (good : U → Prop) + (edge : U → W) (outLeaf : W → Bool → X) (cap : W → ℝ) (Y w : ℕ) + +/-- A reserved link has one slot at each end with the same index. -/ +abbrev Port (x : X) := + Σ q : {q : W × Bool // outLeaf q.1 q.2 = x}, Fin ⌈cap q.val.1 * Y / 8⌉₊ + +/-- The subtype of `q : {i` satisfying `good i} × Bool // leaf (point q.1.val q.2) = x`. -/ +abbrev GoodEnd (x : X) := + {q : {i // good i} × Bool // leaf (point q.1.val q.2) = x} + +/-- Uses `⟨⟨(edge q.val.1.val, q.val.2), (agree _ q.val.1.property _).symm.trans q.property⟩, +slot q.val.1⟩` as the representation. -/ +def portOf (agree : ∀ a, good a → ∀ t, leaf (point a t) = outLeaf (edge a) t) + (slot : ∀ a : {i // good i}, Fin ⌈cap (edge a.val) * Y / 8⌉₊) + {x : X} (q : GoodEnd leaf point good x) : Port outLeaf cap Y x := + ⟨⟨(edge q.val.1.val, q.val.2), (agree _ q.val.1.property _).symm.trans q.property⟩, slot q.val.1⟩ + +variable [Fintype P] + +/-- Attach whole input occurrences to terminals. At both ends of each good +unit, select a distinct port on a layer connecting to the reserved link. -/ +structure Delivery (out : ∀ x, Port outLeaf cap Y x ↪ Fin Y) (l : P → ℝ) (u : ℝ) where + agree : ∀ a, good a → ∀ t, leaf (point a t) = outLeaf (edge a) t + /-- The `Delivery` component of type `∀ a : {i // good i}, Fin ⌈cap (edge a.val) * Y / 8⌉₊`. -/ + slot : ∀ a : {i // good i}, Fin ⌈cap (edge a.val) * Y / 8⌉₊ + /-- The `Delivery` component of type `P → Fin Y`. -/ + terminal : P → Fin Y + /-- The `Delivery` component of type `X → ℕ`. -/ + layers : X → ℕ + /-- The `Delivery` component of type `∀ x, Fin (layers x) → Equiv.Perm (Fin Y)`. -/ + config : ∀ x, Fin (layers x) → Equiv.Perm (Fin Y) + /-- The `Delivery` component of type `∀ x, GoodEnd leaf point good x → Fin (layers x) × Fin + w`. -/ + lane : ∀ x, GoodEnd leaf point good x → Fin (layers x) × Fin w + load : ∀ x i, push (fun p => (leaf p, terminal p)) l (x, i) * Y ≤ 3 + cost : ∀ x, (layers x : ℝ) * Y * w * u ≤ 10 + empty : ∀ x, IsEmpty (GoodEnd leaf point good x) → layers x = 0 + routes : ∀ x q, config x (lane x q).1 (terminal (point q.val.1.val q.val.2)) = + out x (portOf leaf point good edge outLeaf cap Y agree slot q) + input : ∀ x, Function.Injective (fun q : GoodEnd leaf point good x => + (terminal (point q.val.1.val q.val.2), lane x q)) + output : ∀ x, Function.Injective (fun q : GoodEnd leaf point good x => + (out x (portOf leaf point good edge outLeaf cap Y agree slot q), lane x q)) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Programming a tagged verifier by fixing the output tags -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Tagged + +variable {a b : Wire} {k w : ℕ} {I : Type} + +open scoped Classical in +private def write (L : Layout a b I) (x : I → Val a) : Val b := + (bits b).symm fun j => bits a (x (L.positions.symm j).1) (L.positions.symm j).2 + +open scoped Classical in +private theorem bits_write (L : Layout a b I) (x : I → Val a) (i : I) (j : slots a) : + bits b (write L x) (L.positions (i, j)) = bits a (x i) j := by simp [write] + +open scoped Classical in +private theorem read_write (L : Layout a b I) (x : I → Val a) : + L.read (write L x) = x := by + funext i + simp [Layout.read, bits_write] + +open scoped Classical in +private theorem label_read (P : Layout a (tree k a) (Fin (2 ^ k))) + (hp : ∀ x, List.ofFn (P.read x) = flatten k x) + (R : Layout (row k a) (tree k (row k a)) (Fin (2 ^ k))) + (hr : ∀ x, List.ofFn (R.read x) = flatten k x) : + ∃ addr : Fin (2 ^ k) → Val (word k), Function.Injective addr ∧ + ∀ x i, R.read (label k x) i = (addr i, P.read x i) := by + obtain ⟨L, hL⟩ := Layout.exists_tree (word k) k + refine ⟨L.read (indices k), List.nodup_ofFn.mp ?_, fun x i => Prod.ext ?_ ?_⟩ + · rw [hL]; exact indices_nodup k + · have ht := label_tags k x + rw [← hr, ← hL, List.map_ofFn] at ht + exact congrFun (List.ofFn_injective ht) i + · have ht := congrArg (flatten k) (label_payloads k x) + rw [payloads, flatten_mapRows, ← hr, ← hp, List.map_ofFn] at ht + exact congrFun (List.ofFn_injective ht) i + +open scoped Classical in +private theorem perm_tagged {n : ℕ} {X Y : Type} (t : Fin n → X) (ht : Function.Injective t) + (x y : Fin n → Y) (σ : Equiv.Perm (Fin n)) : + (List.ofFn (fun i => (t (σ.symm i), y (σ.symm i)))).Perm + (List.ofFn (fun i => (t i, x i))) ↔ x = y := by + constructor + · intro hp + funext i + have hi : (t i, y i) ∈ List.ofFn (fun j => (t (σ.symm j), y (σ.symm j))) := + List.mem_ofFn.mpr ⟨σ i, by simp⟩ + obtain ⟨j, hj⟩ := List.mem_ofFn.mp (hp.subset hi) + obtain ⟨e, he⟩ := Prod.mk.inj hj + simpa only [ht e] using he + · rintro rfl + exact Equiv.Perm.ofFn_comp_perm σ.symm (fun i => (t i, x i)) + +open scoped Classical in +/-- Designate fixed, distinct input and output positions for the rotor. +Only the positional tags are programmed by the permutation. -/ +theorem tag_program (F : Type) [Field F] (k w : ℕ) : + ∃ port : Bool × (Fin (2 ^ k) × Fin w) ↪ slots (Tagged.inputs k (word w)), + ∀ σ : Equiv.Perm (Fin (2 ^ k)), + ∃ cfg : (Fin (2 ^ k) × Fin w → Bool) → (Fin (2 ^ k) × Fin w → Bool) → + Val (Tagged.inputs k (word w)), + (∀ (x y x' y' : Fin (2 ^ k) × Fin w → Bool) i, + (∀ j : Fin (2 ^ k) × Fin w, port (false, j) = i → x j = x' j) → + (∀ j : Fin (2 ^ k) × Fin w, port (true, σ j.1, j.2) = i → y j = y' j) → + bits (Tagged.inputs k (word w)) (cfg x y) i = + bits (Tagged.inputs k (word w)) (cfg x' y') i) ∧ + ∀ x y, tag F k (word w) (cfg x y) () = if x = y then 1 else 0 := by + obtain ⟨P, hp⟩ := Layout.exists_tree (word w) k + obtain ⟨R, hr⟩ := Layout.exists_tree (row k (word w)) k + obtain ⟨addr, ha, hl⟩ := label_read P hp R hr + let e : Fin w ≃ slots (word w) := Fintype.equivOfCardEq (by simp [wd_word]) + let g : Bool × (Fin (2 ^ k) × Fin w) → slots (Tagged.inputs k (word w)) + | (false, i, j) => .inl (P.positions (i, e j)) + | (true, i, j) => .inr (R.positions (i, .inr (e j))) + have hg : Function.Injective g := by + rintro ⟨b, i, j⟩ ⟨b', i', j'⟩ he + cases b <;> cases b' <;> + simp only [g, Sum.inl.injEq, Sum.inr.injEq, Equiv.apply_eq_iff_eq, + reduceCtorEq, Prod.mk.injEq, true_and] at he ⊢ <;> exact he + refine ⟨⟨g, hg⟩, fun σ => ?_⟩ + let payload (x : Fin (2 ^ k) × Fin w → Bool) (i : Fin (2 ^ k)) := + (bits (word w)).symm fun j => x (i, e.symm j) + have hinj : Function.Injective payload := by + intro x y eq + funext ⟨i, j⟩ + simpa [payload] using congrFun (congrArg (bits (word w)) (congrFun eq i)) (e j) + let cfg (x y : Fin (2 ^ k) × Fin w → Bool) : Val (Tagged.inputs k (word w)) := + (write P (payload x), write R (fun i => (addr (σ.symm i), payload y (σ.symm i)))) + refine ⟨cfg, ?_, ?_⟩ + · rintro x y x' y' (i | i) hx hy + · obtain ⟨⟨r, j⟩, rfl⟩ := P.positions.surjective i + change bits (tree k (word w)) (write P _) _ = bits (tree k (word w)) (write P _) _ + simp only [bits_write, payload, Equiv.apply_symm_apply] + exact hx (r, e.symm j) (by simp [g]) + · obtain ⟨⟨r, j⟩, rfl⟩ := R.positions.surjective i + change bits (tree k (row k (word w))) (write R _) _ + = bits (tree k (row k (word w))) (write R _) _ + rw [bits_write, bits_write] + cases j with + | inl j => rfl + | inr j => + change bits (word w) (payload y _) _ = bits (word w) (payload y' _) _ + simp only [payload, Equiv.apply_symm_apply] + exact hy (σ.symm r, e.symm j) (by simp [g]) + · intro x y + have he : R.read (label k (write P (payload x))) = fun i => (addr i, payload x i) := by + funext i + rw [hl, read_write] + simp only [cfg, tag, permuted, ← hr, he, read_write, perm_tagged addr ha, hinj.eq_iff] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/ResetLocation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/ResetLocation.lean new file mode 100644 index 0000000000..75ddb991f3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/ResetLocation.lean @@ -0,0 +1,942 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.BadBases +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Reservations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Delivery +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix + +/-! +# Selecting bases and a common mixer + +The total exceptional load can be made arbitrarily small. The length +parameter `k` is fixed before the group size, graph and loads. The +delay bound `s` is only imposed on core contacts. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +open scoped Classical in +/-- Quantitative bad-base estimate with loads normalized by `FB`. +The maximum base length is `2^(h-a)` and the minimum is `F = 2^k`. -/ +theorem reset_bases (j s : ℕ) (D ε : ℝ) (hD : 0 < D) (hε : 0 < ε) : + ∃ k ≥ j, ∀ (V A : Type) [Fintype V] [Fintype A] (h a : ℕ), a + k ≤ h → + ∀ (E : V → Finset V) (d : V → V → ℕ) (ends : A → Bool → V) + (l : V → Cell h → ℝ) (y : A → Cell h → ℝ), + (∀ u, ∑ v, (if u ∈ E v then 1 / (2 : ℝ) ^ (d v u) else 0) ≤ 1 / 2) → + (∀ c t, ends c (!t) ∈ E (ends c t) ∧ 8 * d (ends c t) (ends c (!t)) ≤ s) → + (∀ v, (∑ c, ∑ t : Bool, if ends c t = v then (1 : ℝ) else 0) ≤ D) → + (∀ v x, 0 ≤ l v x ∧ l v x ≤ 1 / (2 : ℝ) ^ k) → + (∀ c x, 0 ≤ y c x ∧ y c x ≤ 1 / (2 : ℝ) ^ k) → + (∀ v, (∑ c, ∑ t : Bool, if ends c t = v then ∑ x, y c x else 0) ≤ ∑ x, l v x) → + let g := D * (2 : ℝ) ^ s + ∃ (base : V → ℕ) (f : Cell h ≃ₗ[ZMod 2] Cell h), + (∀ v, a ≤ base v ∧ base v ≤ h - k ∧ (∑ x, l v x) ≤ (2 : ℝ) ^ (base v)) ∧ + (∀ v u, u ∈ E v → base u ≤ base v + 8 * d v u) ∧ + (∑ v, (2 : ℝ) ^ (base v)) ≤ 2 * Fintype.card V * (2 : ℝ) ^ a + 4 * (∑ v, ∑ x, l v x) ∧ + (∀ v (z : Cell (base v)), + (∑ c, ∑ t, ∑ w, if contactEnd base ends ⟨c, w⟩ t = ⟨v, z⟩ then (1 : ℝ) else 0) ≤ g ∧ + (∑ c, ∑ t, ∑ w, if contactEnd base ends ⟨c, w⟩ t = ⟨v, z⟩ + then mean (y c) (contactDepth base ends c) + 1 / g else 0) ≤ 2) ∧ + badLoad E d base (contactDepth base ends) (contactEnd base ends) l y g f.toEquiv ≤ + ε * (∑ v, ∑ x, l v x) := by + obtain ⟨k, hk, small⟩ := small_resetWeight (D * (2 : ℝ) ^ s) ε hε j + refine ⟨k, hk, ?_⟩ + intro V A _ _ h a ha E d ends l y budget hadj degree hl hy incident g + have hg : 0 < g := by unfold g; positivity + have mass v : 0 ≤ ∑ x, l v x := sum_nonneg fun x _ => (hl v x).1 + have lim v : (∑ x, l v x) ≤ (2 : ℝ) ^ (h - k) := calc + _ ≤ ∑ _x : Cell h, 1 / (2 : ℝ) ^ k := sum_le_sum (fun x _ => (hl v x).2) + _ = _ := by + simp only [sum_const, card_univ, card_cell, nsmul_eq_mul, Nat.cast_pow, Nat.cast_ofNat, + mul_one_div, div_eq_iff (by positivity : (2 : ℝ) ^ k ≠ 0), ← pow_add, + Nat.sub_add_cancel (by omega : k ≤ h)] + obtain ⟨base, hb, drop, count⟩ := choose_bases E d budget a (h - k) (by omega) + (fun v => ∑ x, l v x) (fun v => ⟨mass v, lim v⟩) + have hq c : contactDepth base ends c ≤ h := by + exact max_le ((hb _).2.1.trans (Nat.sub_le _ _)) ((hb _).2.1.trans (Nat.sub_le _ _)) + obtain ⟨f, hf⟩ := bad_bases E d base (contactDepth base ends) (contactEnd base ends) l y g + drop budget hl hy (fun v => (hb v).2.2) hq hg + refine ⟨base, f, hb, drop, count, ?_, hf.trans ?_⟩ + · intro v z + have gap c t (ht : ends c t = v) : contactDepth base ends c ≤ base v + s := by + subst v + obtain ⟨he, hs⟩ := hadj c t + have hdrop := (drop _ _ he).trans (Nat.add_le_add_left hs _) + cases t <;> simp_all only [Bool.not_false, Bool.not_true, contactDepth] <;> omega + exact ⟨reservation_count base ends v z s D gap (degree v), + reservation_bound base ends (fun c => ∑ x, y c x) v z s D hD gap (degree v) + ((incident v).trans (hb v).2.2)⟩ + · have total : (∑ c, ∑ x, y c x) ≤ ∑ v, ∑ x, l v x := by + apply le_trans _ (sum_le_sum (s := univ) fun v _ => incident v) + rw [sum_comm (s := (univ : Finset V))] + apply sum_le_sum + intro c _ + rw [sum_comm (s := (univ : Finset V))] + simp only [sum_ite_eq, mem_univ, ite_true] + exact single_le_sum (fun _ _ => sum_nonneg fun x _ => (hy c x).1) (mem_univ false) + refine le_trans ?_ (mul_le_mul_of_nonneg_right small (sum_nonneg fun v _ => mass v)) + rw [add_mul] + exact add_le_add_right (mul_le_mul_of_nonneg_left total (by positivity)) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Subdivision of reset bases + +Force all cells above each base to split. Below it, split only if the +load is above twice the normalized capacity or a neighbor forces the split. +Good bases survive unchanged. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +variable {V : Type} {h k : ℕ} +variable (E : V → Finset V) (d : V → V → ℕ) (base : V → ℕ) +variable (l : V → Cell h → ℝ) (π : Equiv.Perm (Cell h)) + +open scoped Classical in +/-- Requires `i < base v ∨ Spread E (fun v u => 8 * d v u) (fun v i z => 2 < load (l v) π i z) v +i z`. -/ +def ResetSplit (v : V) (i : ℕ) (z : Cell i) : Prop := + i < base v ∨ Spread E (fun v u => 8 * d v u) (fun v i z => 2 < load (l v) π i z) v i z + +open scoped Classical in +theorem reset_leaves (hk : k ≤ h) (hb : ∀ v, base v ≤ h - k) + (drop : ∀ v u, u ∈ E v → base u ≤ base v + 8 * d v u) + (hl : ∀ v x, l v x ≤ 1 / (2 : ℝ) ^ k) : + let M := ResetSplit E d base l π + (∀ v x, leafAt (M v) (π x) ∈ leaves (M v) h) ∧ + (∀ v c, c ∈ leaves (M v) h → + base v ≤ c.1 ∧ c.1 ≤ h - k ∧ (∃ hi : c.1 ≤ h, + ∀ x, leafAt (M v) (π x) = c ↔ ancestor hi (π x) = c.2) ∧ + 2 ^ k ≤ (univ.filter fun x => leafAt (M v) (π x) = c).card ∧ + (∑ x, if leafAt (M v) (π x) = c then l v x else 0) ≤ 2) ∧ + (∀ v u, u ∈ E v → ∀ x : Cell h, leafDepth (M u) x ≤ leafDepth (M v) x + 16 * d v u) := by + intro M + have high v i z (hm : 2 < load (l v) π i z) : i < h - k := by + unfold load at hm + split_ifs at hm with hi + · exact heavy.depth hk (hl v) ⟨hi, lt_trans (by norm_num) hm⟩ + · norm_num at hm + have small v i z (hm : M v i z) : i < h - k := by + rcases hm with hh | hh + · exact hh.trans_le (hb v) + · exact hh.depth high + have stop v x : ¬M v h x := fun hc => (Nat.sub_le h k).not_gt (small _ _ _ hc) + refine ⟨fun v x => leafAt_mem _ _ (stop v _), ?_, ?_⟩ + · rintro v ⟨i, z⟩ hc + obtain ⟨hi, reached, unmarked⟩ := (mem_leaves (M v) _).mp hc + have hj : i ≤ h - k := by + by_contra! bad + exact lt_irrefl _ (small _ _ _ (reached _ bad)) + have fiber (x : Cell h) : leafAt (M v) (π x) = ⟨i, z⟩ ↔ ancestor hi (π x) = z := + leafAt_eq_iff _ _ hi ⟨reached, unmarked⟩ + refine ⟨le_of_not_gt fun hh => unmarked (.inl hh), hj, ⟨hi, fiber⟩, ?_, ?_⟩ + · rw [card_leafAt _ _ hc] + exact Nat.pow_le_pow_right (by decide) (by omega : k ≤ h - i) + · have hload : load (l v) π i z ≤ 2 := + le_of_not_gt fun hh => unmarked (.inr (.start hh)) + simpa only [load, dite_eq_left hi, fiber] using hload + · intro v u hu x + rw [show 16 * d v u = 2 * (8 * d v u) by omega] + apply leafDepth_le_add + intro i _ c hc + rcases hc with hh | hh + · left + have := drop v u hu + omega + · exact .inr (.move (d := fun v u => 8 * d v u) (M := fun v i z => 2 + < load (l v) π i z) hu c hh) + +open scoped Classical in +theorem good_leaf {A : Type} (q : A → ℕ) (endpt : (Σ c, Cell (q c)) → Bool → Σ v, Cell (base v)) + (y : A → Cell h → ℝ) (g : ℝ) (v : V) (z : Cell (base v)) + (good : ¬BadBase E d base q endpt l y g π ⟨v, z⟩) : + Leaf (ResetSplit E d base l π v) (base v) z := by + refine ⟨fun _ hi => .inl hi, ?_⟩ + rintro (hh | hh) + · exact lt_irrefl _ hh + · exact good (.inl hh) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Packing one dyadic group + +Use the two host degree bounds separately. Only the core degree enters +the bound on the number of destinations of one source part. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V : Type} [Fintype V] {h k : ℕ} + +open scoped Classical in +/-- At depth `i`, at most `2 ^ s` destination parts meet a given +source part if they all have depth at most `i + s`. -/ +theorem neighbors_le (π : Cell h → Cell h) (a b : Cell h → Σ i, Cell i) + (c : Σ i, Cell i) (hc : c.1 ≤ h) + (ha : ∀ x, a x = c → ancestor hc (π x) = c.2) + (hb : ∀ x, ∃ hj : (b x).1 ≤ h, ∀ y, b y = b x ↔ ancestor hj (π y) = (b x).2) + (s : ℕ) (hd : ∀ x, a x = c → (b x).1 ≤ c.1 + s) : + ((univ.filter fun x => a x = c).image b).card ≤ 2 ^ s := by + let T := (univ.filter fun x => a x = c).image b + have rep (z : T) : ∃ x, a x = c ∧ b x = z.val := by + simpa only [T, mem_image, mem_filter, mem_univ, true_and] using z.property + choose p hp hq using rep + let code (z : T) : Cell s := fun j => + if hj : c.1 + j.val < h then π (p z) ⟨c.1 + j.val, hj⟩ else 0 + have inj : Function.Injective code := by + intro z w he + obtain ⟨hj, hf⟩ := hb (p w) + have hle := hd _ (hp w) + apply Subtype.ext + rw [← hq z, ← hq w, hf, ← (hf _).mp rfl] + funext j + by_cases hi : j.val < c.1 + · exact congrFun ((ha _ (hp z)).trans (ha _ (hp w)).symm) ⟨j.val, hi⟩ + · have hh : c.1 + (j.val - c.1) = j.val := by omega + have e := congrFun he ⟨j.val - c.1, by omega⟩ + simpa [code, hh, j.isLt.trans_le hj, ancestor, Fin.castLE] using e + simpa only [Fintype.card_coe, card_cell] using Fintype.card_le_of_injective code inj + +open scoped Classical in +private theorem weight_quarter (s : Finset V) (D m : ℕ) (hD : 0 < D) + (hs : s.card ≤ D) (hm : 2 ≤ m) : + (∑ v, if v ∈ s then 1 / (2 : ℝ) ^ (m * Nat.clog 2 (2 * D)) else 0) ≤ 1 / 4 := by + let n := Nat.clog 2 (2 * D) + have hn : 1 ≤ n := Nat.clog_pos (by decide) (by omega) + have hp : 4 * D ≤ 2 ^ (m * n) := calc + 4 * D = (2 * D) * 2 := by omega + _ ≤ (2 ^ n) * 2 := Nat.mul_le_mul_right _ (Nat.le_pow_clog (by decide) _) + _ ≤ 2 ^ (m * n) := Nat.pow_le_pow_right (by decide : 0 < 2) + ((show n + 1 ≤ 2 * n by omega).trans (Nat.mul_le_mul_right _ hm)) + have hc : (s.card : ℝ) * 4 ≤ (2 : ℝ) ^ (m * n) := by + exact_mod_cast (show s.card * 4 ≤ 2 ^ (m * n) by omega) + rw [sum_ite_mem, univ_inter, sum_const, nsmul_eq_mul, mul_one_div, + div_le_div_iff₀ (by positivity) (by norm_num), one_mul] + exact hc + +open scoped Classical in +/-- Each of the core and tether classes consumes at most a quarter of +the incoming weight budget. -/ +theorem edge_weight_sum (E C : V → Finset V) (Δ D m : ℕ) (hΔ : 0 < Δ) (hD : 0 < D) + (eSym : ∀ v u, u ∈ E v → v ∈ E u) (cSym : ∀ v u, u ∈ C v → v ∈ C u) + (eDeg : ∀ v, (E v).card ≤ D) (cDeg : ∀ v, (C v).card ≤ Δ) (hm : 2 ≤ m) (u : V) : + (∑ v, if u ∈ E v then + 1 / (2 : ℝ) ^ (m * Nat.clog 2 (2 * if u ∈ C v then Δ else D)) else 0) ≤ 1 / 2 := by + let w (n : ℕ) := 1 / (2 : ℝ) ^ (m * Nat.clog 2 (2 * n)) + have hw (n : ℕ) : 0 ≤ w n := by unfold w; positivity + calc + _ ≤ ∑ v, ((if v ∈ C u then w Δ else 0) + (if v ∈ E u then w D else 0)) := by + apply sum_le_sum + intro v _ + by_cases he : u ∈ E v + · by_cases hc : u ∈ C v + · simp [he, hc, cSym _ _ hc, eSym _ _ he, w] + · have hnc : v ∉ C u := fun hx => hc (cSym _ _ hx) + simp [he, hc, hnc, eSym _ _ he, w] + · rw [ite_eq_right he] + exact add_nonneg (ite_nonneg (hw _) le_rfl) (ite_nonneg (hw _) le_rfl) + _ ≤ 1 / 4 + 1 / 4 := by + rw [sum_add_distrib] + exact add_le_add (weight_quarter _ _ _ hΔ (cDeg u) hm) + (weight_quarter _ _ _ hD (eDeg u) hm) + _ = _ := by norm_num + +open scoped Classical in +/-- The quantity computed by `32 * Nat.clog 2 (2 * if u ∈ C v then Δ else D)`. -/ +def delay (C : V → Finset V) (Δ D : ℕ) (v u : V) := + 32 * Nat.clog 2 (2 * if u ∈ C v then Δ else D) + +open scoped Classical in +/-- The quantity computed by `l v x / ((2 : ℝ) ^ k * B)`. -/ +def relative (k : ℕ) (B : ℝ) (l : V → Cell h → ℝ) (v : V) (x : Cell h) := + l v x / ((2 : ℝ) ^ k * B) + +open scoped Classical in +/-- Use any minimizer of the total propagated split count. -/ +def groupBy (E C : V → Finset V) (Δ D : ℕ) (hΔ : 0 < Δ) (hD : 0 < D) + (eSym : ∀ v u, u ∈ E v → v ∈ E u) (cSym : ∀ v u, u ∈ C v → v ∈ C u) + (sub : ∀ v, C v ⊆ E v) (eDeg : ∀ v, (E v).card ≤ D) (cDeg : ∀ v, (C v).card ≤ Δ) + (hk : 1 ≤ k) (hkh : k ≤ h) (B : ℝ) (hB : 0 < B) + (l : V → Cell h → ℝ) (hl : ∀ v x, 0 ≤ l v x ∧ l v x ≤ B) + (pick : Fin (2 ^ h)) (opt : best E (delay C Δ D) (relative k B l) pick) : + Grouping E C Δ D k B l := by + let d (v u : V) := 32 * Nat.clog 2 (2 * if u ∈ C v then Δ else D) + have hd (v u : V) (_ : u ∈ E v) : 0 < d v u := by + apply Nat.mul_pos (by decide : 0 < 32) + apply Nat.clog_pos (by decide) + split_ifs <;> omega + let b := (2 : ℝ) ^ k * B + have hb : 0 < b := mul_pos (by positivity) hB + have hn v x : 0 ≤ l v x / b ∧ l v x / b ≤ 1 / (2 : ℝ) ^ k := by + refine ⟨div_nonneg (hl v x).1 hb.le, (div_le_iff₀ hb).mpr ?_⟩ + simpa [b, ← mul_assoc] using (hl v x).2 + let π := menu h pick + let M := marks E d (fun v x => l v x / b) pick + let parts v := leaves (M v) h + let label v x := leafAt (M v) (π x) + have ok := balanced_partition E d hd + (edge_weight_sum E C Δ D 32 hΔ hD eSym cSym eDeg cDeg (by decide)) hk hkh _ hn pick opt + have total := ok.1 + have mem := ok.2.1 + have part := ok.2.2.1 + have edge := ok.2.2.2 + have hedge v u (hu : u ∈ E v) x : (label u x).1 ≤ (label v x).1 + + 64 * Nat.clog 2 (2 * if u ∈ C v then Δ else D) := by + simpa only [d, ← mul_assoc, Nat.reduceMul] using edge v u hu x + refine ⟨π, parts, label, ?_, mem, ?_, hedge, ?_⟩ + · change (∑ v, ((parts v).card : ℝ)) ≤ _ at total + simpa only [div_eq_mul_inv, ← sum_mul, mul_assoc, b] using total + · intro v c hc + obtain ⟨hdepth, pref, hsize, hload⟩ := part v c hc + refine ⟨hdepth, pref, hsize, (div_le_one hb).mp ?_⟩ + change (∑ x, if label v x = c then l v x / b else 0) ≤ 1 at hload + simpa only [div_eq_mul_inv, sum_mul, ite_mul, zero_mul] using hload + · intro v c hc + obtain ⟨hi, hp⟩ := (part v c hc).2.1 + calc + _ ≤ ∑ _u ∈ C v, 2 ^ (64 * Nat.clog 2 (2 * Δ)) := by + refine sum_le_sum fun u hu => neighbors_le π _ _ c hi (fun x => (hp x).mp) + (fun x => (part u _ (mem u x)).2.1) _ ?_ + intro x hx + change label v x = c at hx + simpa only [ite_eq_left hu, hx] using hedge v u (sub v hu) x + _ ≤ _ := by + rw [sum_const, Nat.nsmul_eq_mul] + exact Nat.mul_le_mul_right _ (cDeg v) + +open scoped Classical in +theorem pack_group (E C : V → Finset V) (Δ D : ℕ) (hΔ : 0 < Δ) (hD : 0 < D) + (eSym : ∀ v u, u ∈ E v → v ∈ E u) (cSym : ∀ v u, u ∈ C v → v ∈ C u) + (sub : ∀ v, C v ⊆ E v) (eDeg : ∀ v, (E v).card ≤ D) (cDeg : ∀ v, (C v).card ≤ Δ) + (hk : 1 ≤ k) (hkh : k ≤ h) (B : ℝ) (hB : 0 < B) + (l : V → Cell h → ℝ) (hl : ∀ v x, 0 ≤ l v x ∧ l v x ≤ B) : + Nonempty (Grouping E C Δ D k B l) := by + obtain ⟨p, hp⟩ := best_exists E (delay C Δ D) (relative k B l) + exact ⟨groupBy E C Δ D hΔ hD eSym cSym sub eDeg cDeg hk hkh B hB l hl p hp⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Distributing indivisible core wire units + +A unit belongs to one block and one oriented contact. Both counts of the +same units are needed: load at a contact for reserving links and load +at the endpoint occurrences for packing whole tensors. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +variable {V A U : Type} {h : ℕ} + +open scoped Classical in +/-- The data for the demands construction, including `ends`, `contact`, `ix`. -/ +structure Demands (V A U : Type) (h : ℕ) where + /-- The two endpoints of a connection carried by `Demands`, with type `A → Bool → V`. -/ + ends : A → Bool → V + /-- The `Demands` component of type `U → A`. -/ + contact : U → A + /-- The `Demands` component of type `U → Cell h`. -/ + ix : U → Cell h + +namespace Demands + +variable (T : Demands V A U h) + +open scoped Classical in +/-- The value specified by `(T.ends (T.contact i) t, T.ix i)`. -/ +def point (i : U) (t : Bool) := (T.ends (T.contact i) t, T.ix i) + +open scoped Classical in +/-- The value specified by `(T.contact i, T.ix i)`. -/ +def edge (i : U) := (T.contact i, T.ix i) + +variable [Fintype U] + +open scoped Classical in +/-- The indexed operation `push T.edge (fun _ => u) (c, x)`. -/ +def amounts (u : ℝ) (c : A) (x : Cell h) := push T.edge (fun _ => u) (c, x) + +open scoped Classical in +/-- The indexed operation `push (Function.uncurry T.point) (fun _ => u) (v, x)`. -/ +def incident (u : ℝ) (v : V) (x : Cell h) := + push (Function.uncurry T.point) (fun _ => u) (v, x) + +open scoped Classical in +theorem incident_eq [Fintype A] (u : ℝ) (v : V) (x : Cell h) : + T.incident u v x = ∑ c, ∑ t, if T.ends c t = v then T.amounts u c x else 0 := by + unfold incident push + rw [Fintype.sum_prod_type, sum_comm, sum_comm (s := (univ : Finset A))] + apply sum_congr rfl + intro t _ + have he := test_push T.edge (fun _ => u) (fun q => T.ends q.1 t = v ∧ q.2 = x) + rw [Fintype.sum_prod_type] at he + change (∑ c, ∑ z, if T.ends c t = v ∧ z = x then T.amounts u c z else 0) = _ at he + simp only [ite_and, sum_ite_irrel, sum_const_zero, sum_ite_eq', mem_univ, ite_true] at he + refine (sum_congr rfl ?_).trans he.symm + intro i _ + simp only [Function.uncurry_apply_pair, point, edge, Prod.mk.injEq, ite_and] + congr! 2 + +open scoped Classical in +theorem amount_le [Finite A] (u : ℝ) (hu : 0 ≤ u) (c : A) (t : Bool) (x : Cell h) : + T.amounts u c x ≤ T.incident u (T.ends c t) x := by + let : Fintype A := Fintype.ofFinite A + let f c' t' := if T.ends c' t' = T.ends c t then T.amounts u c' x else 0 + have hf c' t' : 0 ≤ f c' t' := by + unfold f + split_ifs + · exact push_nonneg _ _ (fun _ => hu) _ + · exact le_rfl + rw [incident_eq] + change _ ≤ ∑ c', ∑ t', f c' t' + calc + _ = f c t := (ite_eq_left rfl).symm + _ ≤ ∑ t', f c t' := single_le_sum (fun t' _ => hf c t') (mem_univ t) + _ ≤ _ := single_le_sum (fun c' _ => sum_nonneg fun t' _ => hf c' t') (mem_univ c) + +open scoped Classical in +theorem sum_incident [Fintype A] (u : ℝ) (v : V) : + (∑ c, ∑ t : Bool, if T.ends c t = v then ∑ x, T.amounts u c x else 0) = + ∑ x, T.incident u v x := by + simp_rw [incident_eq] + rw [sum_comm (s := (univ : Finset (Cell h)))] + apply sum_congr rfl + intro c _ + rw [sum_comm (s := (univ : Finset (Cell h)))] + simp only [sum_ite_irrel, sum_const_zero] + +variable (base : V → ℕ) (hb : ∀ v, base v ≤ h) (π : Equiv.Perm (Cell h)) + +omit [Fintype U] in +include hb in +open scoped Classical in +theorem contact_le (c : A) : contactDepth base T.ends c ≤ h := max_le (hb _) (hb _) + +open scoped Classical in +/-- The value specified by `prefixSite _ (T.contact_le base hb) π (T.edge i)`. -/ +def link (i : U) : Link base T.ends := + prefixSite _ (T.contact_le base hb) π (T.edge i) + +omit [Fintype U] in +open scoped Classical in +theorem link_end (i : U) (t : Bool) : + contactEnd base T.ends (T.link base hb π i) t = prefixSite base hb π (T.point i t) := rfl + +open scoped Classical in +theorem link_load [Finite A] (u : ℝ) (z : Link base T.ends) : + push (T.link base hb π) (fun _ => u) z = + load (T.amounts u z.1) π (contactDepth base T.ends z.1) z.2 := by + let : Fintype A := Fintype.ofFinite A + change push (prefixSite _ (T.contact_le base hb) π ∘ T.edge) _ _ = _ + rw [← push_comp] + exact push_prefix _ (T.contact_le base hb) π (T.amounts u) z.1 z.2 + +end Demands +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# A reset schedule for individual wire units + +Transfer the exceptional load bound to actual demands. A contact between +good bases fits its predetermined capacity. Assign each old occurrence +to a leaf, preserving both endpoints of every such contact. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V A U : Type} {h a k : ℕ} [Fintype V] [Fintype U] + +open scoped Classical in +/-- The data for the schedule construction, including `base`, `π`, `lo`, `hi`, `mean`. -/ +structure Schedule (T : Demands V A U h) (E : V → Finset V) (d : V → V → ℕ) + (a k : ℕ) (l : V → Cell h → ℝ) (u g ε : ℝ) where + /-- The `Schedule` component of type `V → ℕ`. -/ + base : V → ℕ + /-- Reindexes the data using `Cell h ≃ₗ[ZMod 2] Cell h`. -/ + π : Cell h ≃ₗ[ZMod 2] Cell h + lo : ∀ v, a ≤ base v + hi : ∀ v, base v ≤ h - k + mean : ∀ v, (∑ x, l v x) ≤ (2 : ℝ) ^ (base v) + drop : ∀ v w, w ∈ E v → base w ≤ base v + 8 * d v w + count : (∑ v, (2 : ℝ) ^ (base v)) ≤ 2 * Fintype.card V * (2 : ℝ) ^ a + 4 * (∑ v, ∑ x, l v x) + bad : badLoad E d base (contactDepth base T.ends) (contactEnd base T.ends) + l (T.amounts u) g π.toEquiv ≤ ε * (∑ v, ∑ x, l v x) + sizes : ∀ v x, 0 ≤ l v x ∧ l v x ≤ 1 / (2 : ℝ) ^ k + mass : ∀ v x, T.incident u v x ≤ l v x + block : a + k ≤ h + width : 0 < u + margin : 0 < g + +namespace Schedule + +variable {T : Demands V A U h} {E : V → Finset V} {d : V → V → ℕ} +variable {l : V → Cell h → ℝ} {u g ε : ℝ} (Z : Schedule T E d a k l u g ε) + +open scoped Classical in +theorem depth (v : V) : Z.base v ≤ h := (Z.hi v).trans (Nat.sub_le _ _) + +open scoped Classical in +/-- Uses `prefixSite Z.base Z.depth Z.π.toEquiv` as the representation. -/ +abbrev baseOf := prefixSite Z.base Z.depth Z.π.toEquiv +open scoped Classical in +/-- Uses `T.link Z.base Z.depth Z.π.toEquiv` as the representation. -/ +abbrev link := T.link Z.base Z.depth Z.π.toEquiv +open scoped Classical in +/-- Uses `ResetSplit E d Z.base l Z.π.toEquiv` as the representation. -/ +abbrev mark := ResetSplit E d Z.base l Z.π.toEquiv +open scoped Classical in +/-- Uses `leafSite Z.mark Z.π.toEquiv` as the representation. -/ +abbrev leaf := leafSite Z.mark Z.π.toEquiv +open scoped Classical in +/-- Computes the outlet by the application `outLeaf Z.base T.ends Z.depth`. -/ +abbrev outlet := outLeaf Z.base T.ends Z.depth + +open scoped Classical in +/-- The quantity computed by `Packing.mean (T.amounts u c) (contactDepth Z.base T.ends c) + 1 / +g`. -/ +def capacity (c : A) := Packing.mean (T.amounts u c) (contactDepth Z.base T.ends c) + 1 / g +open scoped Classical in +/-- The value specified by `BadBase E d Z.base (contactDepth Z.base T.ends) (contactEnd Z.base +T.ends) l (T.amounts u) g Z.π.toEquiv`. -/ +def failed := BadBase E d Z.base (contactDepth Z.base T.ends) (contactEnd Z.base T.ends) + l (T.amounts u) g Z.π.toEquiv +open scoped Classical in +/-- The condition `∀ t : Bool, ¬Z.failed (Z.baseOf (T.point i t))` on the specified data. -/ +def good (i : U) := ∀ t : Bool, ¬Z.failed (Z.baseOf (T.point i t)) + +open scoped Classical in +theorem capacity_pos (c : A) : 0 < Z.capacity c := by + have hpos x : 0 ≤ T.amounts u c x := push_nonneg _ _ (fun _ => Z.width.le) _ + exact add_pos_of_nonneg_of_pos (div_nonneg (sum_nonneg fun x _ => hpos x) (by positivity)) + (one_div_pos.mpr Z.margin) + +open scoped Classical in +theorem routes (i : U) (hi : Z.good i) (t : Bool) : + Z.leaf (T.point i t) = Z.outlet (Z.link i) t := by + have hn := hi t + have he := good_leaf E d Z.base l Z.π.toEquiv _ _ (T.amounts u) g _ _ hn + exact leafSite_prefix _ _ _ _ _ he + +open scoped Classical in +theorem at_leaf (z : Site V h) : push Z.leaf (Function.uncurry l) z ≤ 2 := by + obtain ⟨hm, hl, _⟩ := reset_leaves E d Z.base l Z.π.toEquiv (by have := Z.block; omega) + Z.hi Z.drop (fun v x => (Z.sizes v x).2) + exact leafSite_mass _ _ _ hm (fun v c h => (hl v c h).2.2.2.2) z + +open scoped Classical in +theorem at_link [Finite A] (z : Link Z.base T.ends) : + push Z.link (fun i => if Z.good i then u else 0) z ≤ Z.capacity z.1 := by + let : Fintype A := Fintype.ofFinite A + by_cases hz : ∃ i, Z.link i = z ∧ Z.good i + · obtain ⟨i, rfl, hi⟩ := hz + refine (push_le_push _ (m := fun _ => u) (fun j + => by split_ifs <;> first | rfl | exact Z.width.le) _).trans ?_ + rw [show push Z.link _ _ = _ from T.link_load Z.base Z.depth Z.π.toEquiv u (Z.link i)] + exact le_of_not_gt fun over => hi false (.inr ⟨Z.link i, false, over, rfl⟩) + · have he : push Z.link (fun i => if Z.good i then u else 0) z = 0 := by + apply sum_eq_zero + intro i _ + dsimp only + split_ifs with h₁ h₂ + · exact (hz ⟨i, h₁, h₂⟩).elim + · rfl + · rfl + exact he.trans_le (Z.capacity_pos _).le + +open scoped Classical in +/-- Charge each unit using an exceptional route to at least one failed endpoint. -/ +theorem exceptional : + (∑ i, if Z.good i then 0 else u) ≤ ε * (∑ v, ∑ x, l v x) := by + let f := Z.baseOf ∘ Function.uncurry T.point + have hv (z : Σ v, Cell (Z.base v)) : push f (fun _ => u) z ≤ + load (l z.1) Z.π.toEquiv (Z.base z.1) z.2 := by + rw [show push f (fun _ => u) z = _ from (push_comp _ _ _ _).symm] + refine (push_le_push _ (m := Function.uncurry l) (fun x => Z.mass x.1 x.2) _).trans_eq ?_ + exact push_prefix Z.base Z.depth Z.π.toEquiv l z.1 z.2 + calc + _ ≤ ∑ q : U × Bool, if Z.failed (f q) then u else 0 := by + rw [Fintype.sum_prod_type] + apply sum_le_sum + intro i _ + have hp t : 0 ≤ if Z.failed (f (i, t)) then u else 0 := by + split_ifs <;> first | exact Z.width.le | rfl + split_ifs with hi + · exact sum_nonneg fun t _ => hp t + · unfold good at hi + push Not at hi + obtain ⟨t, ht⟩ := hi + have := single_le_sum (fun t _ => hp t) (mem_univ t) + exact (ite_eq_left ht).symm.trans_le this + _ ≤ badLoad E d Z.base _ _ l (T.amounts u) g Z.π.toEquiv := by + rw [← test_push f (fun _ => u)] + apply sum_le_sum + intro z _ + change (if Z.failed z then _ else 0) ≤ if Z.failed z then _ else 0 + split_ifs <;> first | exact hv z | rfl + _ ≤ _ := Z.bad + +end Schedule +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Reset routing over all groups at once + +Each old contact carries named units on specified blocks. Active terminals, +layers and the mixer are chosen using all blocks. The allowable links +between terminals use only the contact means and the relative addresses. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +namespace Schedule + +variable {V A U : Type} [Fintype V] [Fintype U] {h a k : ℕ} +variable {T : Demands V A U h} {E : V → Finset V} {d : V → V → ℕ} +variable {l : V → Cell h → ℝ} {u g ε : ℝ} (Z : Schedule T E d a k l u g ε) + +open scoped Classical in +/-- The condition `∀ x, Slots (relBase a Z.base) T.ends (relHi a Z.depth) Z.capacity Y x ↪ Fin +Y` on the specified data. -/ +abbrev Plugs (Y : ℕ) := + ∀ x, Slots (relBase a Z.base) T.ends (relHi a Z.depth) Z.capacity Y x ↪ Fin Y + +open scoped Classical in +/-- The indexed operation `Delivery Z.leaf T.point Z.good Z.link Z.outlet (fun z => Z.capacity +z.1) Y w (liftSlots a Z.lo o) (Function.uncurry l) u`. -/ +abbrev Dispatch {Y : ℕ} (o : Z.Plugs Y) (w : ℕ) := + Delivery Z.leaf T.point Z.good Z.link Z.outlet (fun z => Z.capacity z.1) + Y w (liftSlots a Z.lo o) (Function.uncurry l) u + +open scoped Classical in +theorem dispatch [Finite A] {Y w : ℕ} (o : Z.Plugs Y) (hY : 0 < Y) (hw : 0 < w) + (space : Y ^ 2 * w ≤ 2 ^ k) (unit : u ≤ 1 / (2 : ℝ) ^ k) : Nonempty (Z.Dispatch o w) := by + let : Fintype A := Fintype.ofFinite A + have hy : 1 ≤ (Y : ℝ) := by exact_mod_cast hY + have hw' : 1 ≤ (w : ℝ) := by exact_mod_cast hw + have space' : (Y : ℝ) ^ 2 * w ≤ (2 : ℝ) ^ k := by exact_mod_cast space + have uy : (Y : ℝ) ≤ (2 : ℝ) ^ k := by + apply le_trans _ space' + nlinarith [mul_nonneg (sq_nonneg (Y : ℝ)) (sub_nonneg.mpr hw')] + have overhead : (Y : ℝ) ^ 2 * w * u ≤ 1 := calc + _ ≤ (2 : ℝ) ^ k * u := mul_le_mul_of_nonneg_right space' Z.width.le + _ ≤ _ := by rw [mul_comm]; exact (le_div_iff₀ (by positivity)).mp unit + apply deliver _ _ _ _ _ _ _ _ _ _ _ hY hw Z.width overhead Z.routes Z.at_leaf + · rintro ⟨v, x⟩ + obtain ⟨hl, hh⟩ := Z.sizes v x + exact ⟨hl, (mul_le_mul_of_nonneg_left uy hl).trans ((le_div_iff₀ (by positivity)).mp hh)⟩ + · exact fun p => Z.mass p.1 p.2 + · exact Z.at_link + +end Schedule + +open scoped Classical in +/-- The only delay and degree assumptions on contacts are for the core. +Tether edges enter via the geometric budget, independent of their number. -/ +theorem reset_schedule (Y w s : ℕ) (D ε : ℝ) (hY : 0 < Y) (hw : 0 < w) + (hD : 0 < D) (hε : 0 < ε) (enough : 4 * (D * (2 : ℝ) ^ s) ≤ Y) : + ∃ k, Y ^ 2 * w ≤ 2 ^ k ∧ + ∀ (V A U : Type) [Fintype V] [Fintype A] [Fintype U] (h a : ℕ), a + k ≤ h → + ∀ (T : Demands V A U h) (E : V → Finset V) (d : V → V → ℕ) (l : V → Cell h → ℝ) (u : ℝ), + (∀ t, ∑ v, (if t ∈ E v then 1 / (2 : ℝ) ^ (d v t) else 0) ≤ 1 / 2) → + (∀ c t, T.ends c (!t) ∈ E (T.ends c t) ∧ 8 * d (T.ends c t) (T.ends c (!t)) ≤ s) → + (∀ v, (∑ c, ∑ t : Bool, if T.ends c t = v then (1 : ℝ) else 0) ≤ D) → + (∀ v x, 0 ≤ l v x ∧ l v x ≤ 1 / (2 : ℝ) ^ k) → + 0 < u → u ≤ 1 / (2 : ℝ) ^ k → (∀ v x, T.incident u v x ≤ l v x) → + ∃ (Z : Schedule T E d a k l u (D * (2 : ℝ) ^ s) ε) (o : Z.Plugs Y), + Nonempty (Z.Dispatch o w) := by + obtain ⟨k, hk, hex⟩ := reset_bases (Y ^ 2 * w) s D ε hD hε + have space : Y ^ 2 * w ≤ 2 ^ k := hk.trans Nat.lt_two_pow_self.le + refine ⟨k, space, ?_⟩ + intro V A U _ _ _ h a ha T E d l u budget adj degree hl hu hu' inc + have hy c x : 0 ≤ T.amounts u c x ∧ T.amounts u c x ≤ 1 / (2 : ℝ) ^ k := + ⟨push_nonneg _ _ (fun _ => hu.le) _, + ((T.amount_le u hu.le c false x).trans (inc _ x)).trans (hl _ x).2⟩ + have hm v : (∑ c, ∑ t : Bool, if T.ends c t = v then ∑ x, T.amounts u c x else 0) ≤ + ∑ x, l v x := by + rw [T.sum_incident] + exact sum_le_sum (fun x _ => inc v x) + obtain ⟨base, π, hb, drop, count, _, bad⟩ := + hex V A h a ha E d T.ends l (T.amounts u) budget adj degree hl hy hm + let Z : Schedule T E d a k l u (D * (2 : ℝ) ^ s) ε := + ⟨base, π, fun v => (hb v).1, fun v => (hb v).2.1, fun v => (hb v).2.2, drop, count, + bad, hl, inc, ha, hu, by positivity⟩ + have gap c t : contactDepth base T.ends c ≤ base (T.ends c t) + s := by + obtain ⟨he, hs⟩ := adj c t + have hx := (drop _ _ he).trans (Nat.add_le_add_left hs _) + cases t <;> simp_all only [Bool.not_false, Bool.not_true, contactDepth] <;> omega + let o : Z.Plugs Y := fun x => Classical.choice + (relative_slots base T.ends Z.depth s D hD (fun c => ∑ x, T.amounts u c x) + (fun c => sum_nonneg fun x _ => (hy c x).1) gap degree (fun v => (hm v).trans (hb v).2.2) + enough a Z.lo x) + exact ⟨Z, o, Z.dispatch o hY hw space hu'⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Applying the reset to a host graph + +Count each oriented core contact separately. This costs a factor of two +in the degree, absorbed by using the tighter base-depth difference. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V U : Type} {h : ℕ} + +open scoped Classical in +/-- The subtype of `p : V × V` satisfying `p.2 ∈ C p.1`. -/ +abbrev CoreContact (C : V → Finset V) := {p : V × V // p.2 ∈ C p.1} + +open scoped Classical in +/-- Returns `c.val.2` when `t` holds, and `c.val.1` otherwise. -/ +def unitEnds {C : V → Finset V} (c : CoreContact C) (t : Bool) := + if t then c.val.2 else c.val.1 + +open scoped Classical in +/-- Uses `⟨unitEnds, fun i => ⟨(src i, dst i), edge i⟩, ix⟩` as the representation. -/ +def coreDemands {src dst : U → V} (ix : U → Cell h) {C : V → Finset V} + (edge : ∀ i, dst i ∈ C (src i)) : Demands V (CoreContact C) U h := + ⟨unitEnds, fun i => ⟨(src i, dst i), edge i⟩, ix⟩ + +open scoped Classical in +/-- The quantity computed by `4 * Nat.clog 2 (2 * if z ∈ C v then Δ else D)`. -/ +def resetDelay (C : V → Finset V) (Δ D : ℕ) (v z : V) := + 4 * Nat.clog 2 (2 * if z ∈ C v then Δ else D) + +open scoped Classical in +/-- The quantity computed by `2 * (Δ : ℝ) * (2 : ℝ) ^ (32 * Nat.clog 2 (2 * Δ))`. -/ +def reserveCount (Δ : ℕ) := 2 * (Δ : ℝ) * (2 : ℝ) ^ (32 * Nat.clog 2 (2 * Δ)) + +open scoped Classical in +private theorem reserve_le (Δ : ℕ) (hΔ : 0 < Δ) : reserveCount Δ ≤ coreBins Δ := by + have : 1 ≤ Nat.clog 2 (2 * Δ) := Nat.clog_pos (by decide) (by omega) + unfold reserveCount coreBins + rw [Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, mul_comm 2 (Δ : ℝ), mul_assoc, ← pow_succ'] + exact mul_le_mul_of_nonneg_left (pow_le_pow_right₀ (by norm_num) (by omega)) (Nat.cast_nonneg _) + +open scoped Classical in +private theorem unitEnds_mem {C : V → Finset V} (cs : ∀ v w, w ∈ C v → v ∈ C w) + (c : CoreContact C) (t : Bool) : + unitEnds c (!t) ∈ C (unitEnds c t) := by + cases t + · exact c.2 + · exact cs _ _ c.2 + +open scoped Classical in +private theorem degree_core [Fintype V] (C : V → Finset V) + (cs : ∀ v w, w ∈ C v → v ∈ C w) (v : V) : + (∑ c : CoreContact C, ∑ t : Bool, if unitEnds c t = v then (1 : ℝ) else 0) ≤ + 2 * (C v).card := by + have one (t : Bool) : (∑ c : CoreContact C, if unitEnds c t = v then (1 : ℝ) else 0) ≤ + (C v).card := by + let f (c : {c : CoreContact C // unitEnds c t = v}) : C v := + ⟨unitEnds c.val (!t), by simpa only [c.2] using unitEnds_mem cs c.val t⟩ + have inj : Function.Injective f := by + intro c d he + have h₁ : unitEnds c.val (!t) = unitEnds d.val (!t) := congrArg Subtype.val he + have h₂ := c.2.trans d.2.symm + refine Subtype.ext (Subtype.ext ?_) + cases t + · exact Prod.ext h₂ h₁ + · exact Prod.ext h₁ h₂ + rw [sum_boole, ← Fintype.card_subtype, Nat.cast_le, ← Fintype.card_coe] + exact Fintype.card_le_of_injective f inj + rw [sum_comm] + simpa using sum_le_sum (s := univ) (fun t _ => one t) + +open scoped Classical in +theorem core_schedule (Y w Δ : ℕ) (ε : ℝ) (hY : 0 < Y) (hw : 0 < w) + (hΔ : 0 < Δ) (hε : 0 < ε) (enough : 4 * coreBins Δ ≤ Y) : + ∃ k, Y ^ 2 * w ≤ 2 ^ k ∧ + ∀ (V U : Type) [Fintype V] [Fintype U] (h a D : ℕ), a + k ≤ h → Δ ≤ D → + ∀ (N C : V → Finset V) (src dst : U → V) (ix : U → Cell h) (edge : ∀ i, dst i ∈ C (src i)), + (∀ v z, z ∈ N v → v ∈ N z) → (∀ v z, z ∈ C v → v ∈ C z) → + (∀ v, C v ⊆ N v) → (∀ v, (N v).card ≤ D) → (∀ v, (C v).card ≤ Δ) → + ∀ (l : V → Cell h → ℝ) (u : ℝ), (∀ v x, 0 ≤ l v x ∧ l v x ≤ 1 / (2 : ℝ) ^ k) → + 0 < u → u ≤ 1 / (2 : ℝ) ^ k → (∀ v x, (coreDemands ix edge).incident u v x ≤ l v x) → + ∃ (Z : Schedule (coreDemands ix edge) N (resetDelay C Δ D) a k l u (reserveCount Δ) ε) + (o : Z.Plugs Y), Nonempty (Z.Dispatch o w) := by + have en : 4 * reserveCount Δ ≤ (Y : ℝ) := + (mul_le_mul_of_nonneg_left (reserve_le Δ hΔ) (by norm_num)).trans (by exact_mod_cast enough) + obtain ⟨k, hk, exe⟩ := reset_schedule Y w (32 * Nat.clog 2 (2 * Δ)) (2 * Δ) ε + hY hw (by positivity) hε en + refine ⟨k, hk, ?_⟩ + intro V U _ _ h a D ha hD N C src dst ix edge ns cs sub ndeg cdeg l u hl hu hu' inc + refine exe V _ U h a ha (coreDemands ix edge) N (resetDelay C Δ D) l u + (edge_weight_sum N C Δ D 4 hΔ (hΔ.trans_le hD) ns cs ndeg cdeg (by decide)) ?_ ?_ hl hu hu' inc + · intro c t + have hm := unitEnds_mem cs c t + exact ⟨sub _ hm, by simp only [resetDelay, coreDemands, hm, ite_true]; omega⟩ + · exact fun v => (degree_core C cs v).trans + (mul_le_mul_of_nonneg_left (Nat.cast_le.mpr (cdeg v)) (by norm_num)) + +open scoped Classical in +/-- Every schedule with the stated margin admits relative reservations, +including the schedule elected by the integer controller. -/ +theorem Schedule.reserve {V U : Type} [Fintype V] [Fintype U] {h a k Δ D Y : ℕ} + {N C : V → Finset V} {src dst : U → V} {ix : U → Cell h} + {edge : ∀ i, dst i ∈ C (src i)} {l : V → Cell h → ℝ} {u g ε : ℝ} + (Z : Schedule (coreDemands ix edge) N (resetDelay C Δ D) a k l u g ε) + (cs : ∀ v z, z ∈ C v → v ∈ C z) (sub : ∀ v, C v ⊆ N v) + (hΔ : 0 < Δ) (deg : ∀ v, (C v).card ≤ Δ) (enough : 4 * coreBins Δ ≤ Y) + (margin : g = reserveCount Δ) (x : Site V (h - a)) : + Nonempty (Slots (relBase a Z.base) unitEnds (relHi a Z.depth) Z.capacity Y x ↪ Fin Y) := by + subst g + let s := 32 * Nat.clog 2 (2 * Δ) + let T := coreDemands ix edge + have gap c t : contactDepth Z.base T.ends c ≤ Z.base (T.ends c t) + s := by + have he := unitEnds_mem cs c t + have hx := Z.drop _ _ (sub _ he) + simp only [resetDelay, he, ite_true] at hx + cases t <;> simp only [Bool.not_false, Bool.not_true, contactDepth, T, coreDemands, s] at * + <;> omega + have mass v : (∑ c, ∑ t : Bool, if T.ends c t = v then ∑ x, T.amounts u c x else 0) ≤ + (2 : ℝ) ^ (Z.base v) := by + rw [T.sum_incident] + exact (sum_le_sum (fun x _ => Z.mass v x)).trans (Z.mean v) + have en : 4 * reserveCount Δ ≤ (Y : ℝ) := + (mul_le_mul_of_nonneg_left (reserve_le Δ hΔ) (by norm_num)).trans (by exact_mod_cast enough) + exact relative_slots Z.base T.ends Z.depth s (2 * Δ) (by positivity) (fun c => ∑ x, + T.amounts u c x) + (fun c => sum_nonneg fun x _ => push_nonneg _ _ (fun _ => Z.width.le) _) + gap (fun v => (degree_core C cs v).trans + (mul_le_mul_of_nonneg_left (Nat.cast_le.mpr (deg v)) (by norm_num))) mass en a Z.lo x + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Geometry of reset terminals + +An absolute leaf address splits into a group index and a site in the +common host. Contacts within a group respect the corresponding host +adjacencies, using the smaller bound on core contacts. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V : Type} {h : ℕ} + +open scoped Classical in +/-- Returns `ancestor ha p.2.2` when `ha : a ≤ p.depth` holds, and `0` otherwise. -/ +def Site.group (a : ℕ) (p : Site V h) : Cell a := + if ha : a ≤ p.depth then ancestor ha p.2.2 else 0 + +open scoped Classical in +theorem Site.group_drop {a : ℕ} {p q : Site V h} (hp : a ≤ p.depth) (hq : a ≤ q.depth) + (e : p.group a = q.group a) (d : p.drop a = q.drop a) : p = q := by + exact Site.drop_injective a hp hq (by simpa [Site.group, hp, hq] using e) d + +variable [Fintype V] {A U : Type} [Fintype U] {a k : ℕ} +variable {T : Demands V A U h} {N : V → Finset V} {d : V → V → ℕ} +variable {l : V → Cell h → ℝ} {u g ε : ℝ} + +namespace Schedule +variable (Z : Schedule T N d a k l u g ε) + +open scoped Classical in +theorem leaf_depth (p : V × Cell h) : a ≤ (Z.leaf p).depth := by + obtain ⟨mem, bound, _⟩ := reset_leaves N d Z.base l Z.π.toEquiv + (by have := Z.block; omega) Z.hi Z.drop (fun v x => (Z.sizes v x).2) + exact (Z.lo p.1).trans (bound _ _ (mem p.1 p.2)).1 + +open scoped Classical in +/-- The value specified by `ancestor (by have := Z.block; omega) (Z.π x)`. -/ +def group (x : Cell h) : Cell a := ancestor (by have := Z.block; omega) (Z.π x) + +open scoped Classical in +theorem leaf_group (p : V × Cell h) : (Z.leaf p).group a = Z.group p.2 := by + rw [Site.group, dite_eq_left (Z.leaf_depth p)] + rfl + +open scoped Classical in +theorem group_end (e : U) (t : Bool) : + (Z.leaf (T.point e t)).group a = Z.group (T.ix e) := Z.leaf_group _ + +open scoped Classical in +theorem leaf_gap {v z : V} (hz : z ∈ N v) (x : Cell h) : + (Z.leaf (z, x)).depth ≤ (Z.leaf (v, x)).depth + 16 * d v z := by + obtain ⟨_, _, gap⟩ := reset_leaves N d Z.base l Z.π.toEquiv + (by have := Z.block; omega) Z.hi Z.drop (fun v x => (Z.sizes v x).2) + exact gap v z hz (Z.π x) + +open scoped Classical in +theorem leaf_near {C : V → Finset V} {Δ D : ℕ} + (Z : Schedule T N (resetDelay C Δ D) a k l u g ε) + {P : V → Finset V} {L : ℕ} (sym : ∀ v z, z ∈ P v → v ∈ P z) + (sub : ∀ v, P v ⊆ N v) (bound : ∀ v z, z ∈ P v → (if z ∈ C v then Δ else D) ≤ L) + {v z : V} (hz : z ∈ P v) (x : Cell h) : + (Z.leaf (z, x)).drop a ∈ near P L ((Z.leaf (v, x)).drop a) := by + apply drop_near + have gap v z (he : z ∈ P v) : + (Z.leaf (z, x)).depth ≤ (Z.leaf (v, x)).depth + 64 * Nat.clog 2 (2 * L) := by + have hm := Z.leaf_gap (sub v he) x + have hs := Nat.clog_mono_right 2 (Nat.mul_le_mul_left 2 (bound v z he)) + refine hm.trans (Nat.add_le_add_left ?_ _) + unfold resetDelay + omega + exact (mem_near _ _ _ _).mpr (.inr ⟨hz, ⟨_, leafSite_contains _ _ _, leafSite_contains _ _ _⟩, + gap z v (sym _ _ hz), gap v z hz⟩) + +end Schedule + +open scoped Classical in +/-- All terminals of possible neighboring leaves are eligible. -/ +def terminalNear (P : V → Finset V) (L Y : ℕ) (x : Site V h × Fin Y) := + near P L x.1 ×ˢ (univ : Finset (Fin Y)) + +open scoped Classical in +theorem terminal_symm {P : V → Finset V} (sym : ∀ v z, z ∈ P v → v ∈ P z) + (L Y : ℕ) (x y : Site V h × Fin Y) (hy : y ∈ terminalNear P L Y x) : + x ∈ terminalNear P L Y y := + mem_product.mpr ⟨near_symm sym _ _ _ (mem_product.mp hy).1, mem_univ _⟩ + +open scoped Classical in +/-- The quantity computed by `(4 * L) ^ 300 * Y`. -/ +def terminalWidth (L Y : ℕ) := (4 * L) ^ 300 * Y + +open scoped Classical in +theorem terminal_card (P : V → Finset V) (L Y : ℕ) (hL : 0 < L) (deg : ∀ v, (P v).card ≤ L) + (x : Site V h × Fin Y) : (terminalNear P L Y x).card ≤ terminalWidth L Y := by + rw [terminalNear, card_product, card_univ, Fintype.card_fin] + exact Nat.mul_le_mul_right _ (near_card _ _ hL deg _) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/RestoreCost.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/RestoreCost.lean new file mode 100644 index 0000000000..a1c84eebac --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/RestoreCost.lean @@ -0,0 +1,1005 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.TetherHost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import Mathlib.Tactic.Linarith + +/-! +# Routing exceptional units through their two contact trees + +Descend to the tip assigned to the destination, cross its unique link, +then climb to the receiving terminal. The group label stays fixed. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Detour + +variable {w : ℕ} {X : Type} +local notation "L" => Nat.clog 2 w + +/-- The quantity computed by `2 * Nat.clog 2 w + 3`. -/ +def steps (w : ℕ) := 2 * Nat.clog 2 w + 3 + +/-- Returns `.inr (x, Tree.climb pin k)` when `k ≤ L` holds, and `.inl x` otherwise. -/ +def arm (x : X) (pin : Fin w) (k : ℕ) : Hub X w := + if k ≤ L then .inr (x, Tree.climb pin k) else .inl x + +private theorem owner_arm (x : X) (pin : Fin w) (k : ℕ) : owner (arm x pin k) = x := by + unfold arm + split_ifs <;> rfl + +private theorem arm_inj (x : X) (pin : Fin w) {i j : ℕ} (hi : i ≤ L + 1) (hj : j ≤ L + 1) + (he : arm x pin i = arm x pin j) : i = j := by + unfold arm at he + split_ifs at he with h h' + · have eq := (Prod.mk.inj (Sum.inr.inj he)).2 + exact congrArg Fin.val (Tree.climb_injective pin (a₁ := ⟨i, by omega⟩) + (a₂ := ⟨j, by omega⟩) eq) + · omega + +namespace Switch +variable (sw : Switch X w) {x y : X} + +private theorem arm_adj [Fintype X] (x : X) (pin : Fin w) {i : ℕ} (hi : i ≤ L) : + arm x pin (i + 1) ∈ sw.adj (arm x pin i) := by + rcases hi.eq_or_lt with rfl | hi + · apply sw.adj_symm + simp [arm] + · rw [arm, arm, ite_eq_left hi.le, ite_eq_left (by omega)] + exact sw.adj_inner _ (Tree.climb_adj _ hi) + +/-- Returns `arm x (sw.pin x ⟨y, hx⟩) (L + 1 - i)` when `i ≤ L + 1` holds, and `arm y (sw.pin y +⟨x, sw.sym _ _ hx⟩) (i - (L + 2))` otherwise. -/ +def path (hx : y ∈ sw.near x) (i : ℕ) : Hub X w := + if i ≤ L + 1 then arm x (sw.pin x ⟨y, hx⟩) (L + 1 - i) + else arm y (sw.pin y ⟨x, sw.sym _ _ hx⟩) (i - (L + 2)) + +@[simp] theorem path_zero (hx : y ∈ sw.near x) : sw.path hx 0 = .inl x := by simp [path, arm] + +@[simp] theorem path_last (hx : y ∈ sw.near x) : sw.path hx (steps w) = .inl y := by + unfold path steps arm + rw [ite_eq_right (by omega), ite_eq_right (by omega)] + +theorem path_adj [Fintype X] (hx : y ∈ sw.near x) {i : ℕ} (hi : i < steps w) : + sw.path hx (i + 1) ∈ sw.adj (sw.path hx i) := by + unfold steps at hi + simp only [path] + rcases lt_trichotomy i (L + 1) with h | rfl | h + · rw [ite_eq_left h.le, ite_eq_left (by omega), show L + 1 - i = L + 1 - (i + 1) + 1 by omega] + exact sw.adj_symm _ _ (sw.arm_adj _ _ (by omega)) + · simpa [arm] using sw.adj_bridge x y hx + · rw [ite_eq_right h.not_ge, ite_eq_right (by omega), show i + 1 - (L + 2) = i - (L + 2) + + 1 by omega] + exact sw.arm_adj _ _ (by omega) + +/-- The endpoint owning an intermediate station. -/ +def side (w i : ℕ) := decide (Nat.clog 2 w + 1 < i) + +theorem path_owner (hx : y ∈ sw.near x) (i : ℕ) : + owner (sw.path hx i) = if side w i then y else x := by + by_cases h : i ≤ L + 1 + · simp [path, owner_arm, side, h, not_lt.mpr h] + · simp [path, owner_arm, side, h, lt_of_not_ge h] + +theorem path_inj (hx : y ∈ sw.near x) {i j : ℕ} (hi : i ≤ steps w) (hj : j ≤ steps w) + (hs : side w i = side w j) (he : sw.path hx i = sw.path hx j) : i = j := by + unfold steps at hi hj + have iff : i ≤ L + 1 ↔ j ≤ L + 1 := by + have : L + 1 < i ↔ L + 1 < j := by simpa [side] using hs + omega + unfold path at he + by_cases h : i ≤ L + 1 + · rw [ite_eq_left h, ite_eq_left (iff.mp h)] at he + have := arm_inj _ _ (by omega) (by omega) he + omega + · rw [ite_eq_right h, ite_eq_right (mt iff.mpr h)] at he + have := arm_inj _ _ (by omega) (by omega) he + omega + +variable {U G : Type} (group : U → G) (ends : U → Bool → X) + (h : ∀ u, ends u true ∈ sw.near (ends u false)) + +/-- The quantity computed by `((group p.2, sw.path (h p.2) p.1.val), (group p.2, sw.path (h p.2) +(p.1.val + 1)))`. -/ +def route (p : Fin (steps w) × U) : (G × Hub X w) × (G × Hub X w) := + ((group p.2, sw.path (h p.2) p.1.val), (group p.2, sw.path (h p.2) (p.1.val + 1))) + +theorem route_adj [Fintype X] (p : Fin (steps w) × U) : + (sw.route group ends h p).1.1 = (sw.route group ends h p).2.1 ∧ + (sw.route group ends h p).2.2 ∈ sw.adj (sw.route group ends h p).1.2 := + ⟨rfl, sw.path_adj (h p.2) p.1.isLt⟩ + +/-- The indexed operation `(Spectral.Packet.Rule.path K (fun i u => (group u, sw.path (h u) i)) +(steps w)).congr (by simp only [path_zero, path_last]) rfl`. -/ +def rule [Fintype X] [Fintype U] [Fintype G] (K : Type) [Field K] : + Spectral.Packet.Rule K (fun u => ((group u, Sum.inl (ends u false)), (group u, + Sum.inl (ends u true)))) + (fun _ : Unit => sw.route group ends h) := + (Spectral.Packet.Rule.path K (fun i u => (group u, sw.path (h u) i)) (steps w)).congr + (by simp only [path_zero, path_last]) rfl + +theorem packet [Fintype X] [Fintype U] [Fintype G] (K : Type) [Field K] : + Spectral.Packet K (fun u => ((group u, Sum.inl (ends u false)), (group u, + Sum.inl (ends u true)))) + (fun _ : Unit => sw.route group ends h) := + (sw.rule group ends h K).packet + +open scoped Classical in +/-- Each station on an arm is visited at most once. Count both wire +incidences at a visit, even when both ends have the same owner. -/ +theorem route_degree [Fintype U] (z : G × Hub X w) : + degree (sw.route group ends h) z ≤ 2 * + degree (fun u => ((group u, ends u false), (group u, ends u true))) (z.1, owner z.2) := by + let v := (z.1, owner z.2) + let f (u : U) (s : Bool) := (group u, ends u s) + let k := degree (fun u => (f u false, f u true)) v + have each (n : ℕ) (hn : n ≤ 1) : + Fintype.card {p : Fin (steps w) × U // + (group p.2, sw.path (h p.2) (p.1.val + n)) = z} ≤ k := by + let S := {p : Fin (steps w) × U // (group p.2, sw.path (h p.2) (p.1.val + n)) = z} + let T := {s : U × Bool // f s.1 s.2 = v} + have hv (p : S) : f p.val.2 (side w (p.val.1.val + n)) = v := by + unfold v + refine Eq.trans ?_ (congrArg (fun a => (a.1, owner a.2)) p.property) + simp only [path_owner] + cases side w (p.val.1.val + n) <;> rfl + let index (p : S) : T := ⟨(p.val.2, side w (p.val.1.val + n)), hv p⟩ + have hi : Function.Injective index := by + rintro ⟨⟨i, u⟩, hu⟩ ⟨⟨j, u'⟩, hu'⟩ e + obtain ⟨he, hs⟩ := Prod.mk.inj (congrArg Subtype.val e) + change u = u' at he + subst u' + have t := congrArg Prod.snd (hu.trans hu'.symm) + have ht : i.val + n = j.val + n := sw.path_inj (h u) (by omega) (by omega) hs t + have : i = j := Fin.ext (by omega) + subst j + rfl + have hk : Fintype.card T = k := by + simp only [T, k, degree, Fintype.card_subtype, Finset.card_eq_sum_ones, Finset.sum_filter, + Fintype.sum_prod_type, Fintype.sum_bool, Finset.sum_add_distrib] + exact add_comm _ _ + exact (Fintype.card_le_of_injective index hi).trans_eq hk + rw [two_mul] + unfold degree + convert! Nat.add_le_add (each 0 (by decide)) (each 1 (by decide)) using 1 + congr! 3 + +end Switch +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Detour +end + +/- +# Routing tethers between frozen members and the core + +A short splitting tree may carry the whole frozen charge. The long +addressing trees carry only the load of a single outlet or core endpoint. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Tether +open Finset + +variable {V G I : Type} {r s w : ℕ} (sw : Detour.Switch (End V r s) w) + +open scoped Classical in +/-- Each tether bit has its own index, even when many bits take one route. -/ +structure Plan (G I : Type) where + /-- The `Plan` component of type `I → G`. -/ + group : I → G + /-- Assigns the destination of each connection. -/ + dst : I → V + /-- Assigns the source of each connection. -/ + src : I → V × Fin r + /-- The `Plan` component of type `I → Fin s`. -/ + pin : I → Fin s + ok : ∀ i, Sum.inr (src i, Tree.tip (pin i)) ∈ sw.near (.inl (dst i)) + +namespace Plan +variable {sw} (P : Plan sw G I) + +open scoped Classical in +/-- Indexes the wire by the coordinates of `(Fin (Detour.steps w) × I) ⊕ (Fin (Nat.clog 2 s) × +I)`. -/ +abbrev Wire (s w : ℕ) (I : Type) := (Fin (Detour.steps w) × I) ⊕ (Fin (Nat.clog 2 s) × I) + +open scoped Classical in +/-- Returns `.inr (P.src i, Tree.tip (P.pin i))` when `t` holds, and `.inl (P.dst i)` otherwise. -/ +def ends (i : I) (t : Bool) : End V r s := + if t then .inr (P.src i, Tree.tip (P.pin i)) else .inl (P.dst i) + +open scoped Classical in +/-- The value specified by `(P.group i, core (P.dst i))`. -/ +def terminal (i : I) : G × Host V r s w := (P.group i, core (P.dst i)) +open scoped Classical in +/-- The value specified by `(P.group i, member (P.src i))`. -/ +def frozen (i : I) : G × Host V r s w := (P.group i, member (P.src i)) +open scoped Classical in +/-- The value specified by `(P.group i, .inl (.inr (P.src i, Tree.climb (P.pin i) k)))`. -/ +def climb (k : ℕ) (i : I) : G × Host V r s w := + (P.group i, .inl (.inr (P.src i, Tree.climb (P.pin i) k))) + +open scoped Classical in +/-- Computes the cold by the application `sw.route P.group P.ends P.ok`. -/ +def cold := sw.route P.group P.ends P.ok +open scoped Classical in +/-- The quantity computed by `(P.climb q.1.val q.2, P.climb (q.1.val + 1) q.2)`. -/ +def hot (q : Fin (Nat.clog 2 s) × I) := (P.climb q.1.val q.2, P.climb (q.1.val + 1) q.2) +open scoped Classical in +/-- Computes the supply by the application `Sum.elim P.cold P.hot`. -/ +def supply := Sum.elim P.cold P.hot + +variable [Fintype V] + +open scoped Classical in +theorem support (C : V → Finset V) (e : Wire s w I) : + (P.supply e).1.1 = (P.supply e).2.1 ∧ (P.supply e).2.2 ∈ adj sw C (P.supply e).1.2 := by + cases e with + | inl e => exact ⟨rfl, mem_union_left _ (sw.route_adj P.group P.ends P.ok e).2⟩ + | inr e => exact ⟨rfl, branch_adj sw C (P.src e.2) (Tree.climb_adj (P.pin e.2) e.1.isLt)⟩ + +variable [Fintype I] [Fintype G] + +open scoped Classical in +theorem packet (F : Type) [Field F] : + Spectral.Packet F (fun i => (P.terminal i, P.frozen i)) (fun _ : Unit => P.supply) := by + have hc := sw.packet P.group P.ends P.ok F + have hh := Spectral.Packet.path F P.climb (Nat.clog 2 s) + have h : Spectral.Packet F (fun i => ((P.group i, Sum.inl (P.ends i true)), P.frozen i)) + (fun _ : Unit => P.hot) := by + unfold frozen member hot + simpa only [climb, ends, ite_true, Tree.climb_zero, Tree.climb_top] using hh + exact hc.series h + +open scoped Classical in +theorem cardinality : Fintype.card (Wire s w I) = + (Detour.steps w + Nat.clog 2 s) * Fintype.card I := by simp [Wire, add_mul] + +end Plan +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Tether +end + +/- # Squared arity on the short splitting trees -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V G I T : Type} [Fintype I] + +open scoped Classical in +private theorem sum_fiber_card [Fintype T] (f : I → T) : + ∑ i, Fintype.card {j // f j = f i} = ∑ t, (Fintype.card {j // f j = t}) ^ 2 := by + let n t := Fintype.card {j // f j = t} + change ∑ i, n (f i) = ∑ t, n t ^ 2 + rw [← Fintype.sum_fiberwise f] + apply sum_congr rfl + intro t _ + have he (i : {i // f i = t}) : n (f i.val) = n t := congrArg n i.property + simp only [he, sum_const, card_univ, Nat.nsmul_eq_mul, pow_two] + rfl + +namespace Tether.Plan +variable {r s w : ℕ} {sw : Detour.Switch (End V r s) w} + (P : Plan sw G I) (f : I → T) + (sep : ∀ i j, P.group i = P.group j → P.src i = P.src j → f i = f j) + +include sep + +open scoped Classical in +/-- All paths visiting a vertex of a splitting tree come from one +frozen tensor. Each contributes at most two incidences there. -/ +theorem hot_at (i : I) (k : ℕ) : + degree P.hot (P.climb k i) ≤ 2 * Fintype.card {j // f j = f i} := by + have once (n : ℕ) (hn : n ≤ 1) : + Fintype.card {e : Fin (Nat.clog 2 s) × I // P.climb (e.1.val + n) e.2 = P.climb k i} + ≤ Fintype.card {j // f j = f i} := by + let A := {e : Fin (Nat.clog 2 s) × I // P.climb (e.1.val + n) e.2 = P.climb k i} + have hlabel (a : A) : f a.val.2 = f i := by + have he := a.property + simp only [climb, Prod.mk.injEq, Sum.inl.injEq, Sum.inr.injEq] at he + exact sep _ _ he.1 he.2.1 + let send (a : A) : {j // f j = f i} := ⟨a.val.2, hlabel a⟩ + apply Fintype.card_le_of_injective send + rintro ⟨⟨a, j⟩, ha⟩ ⟨⟨b, l⟩, hb⟩ he + have eq : j = l := congrArg Subtype.val he + subst l + have hc := ha.trans hb.symm + simp only [climb, Prod.mk.injEq, Sum.inl.injEq, Sum.inr.injEq, true_and] at hc + have e := Tree.climb_injective (P.pin j) (a₁ := ⟨a.val + n, by omega⟩) + (a₂ := ⟨b.val + n, by omega⟩) hc + have : a = b := Fin.ext (Nat.add_right_cancel (congrArg Fin.val e)) + subst b + rfl + rw [two_mul] + unfold degree + convert! Nat.add_le_add (once 0 (by decide)) (once 1 le_rfl) using 1 + +variable [Fintype V] [Fintype G] [Fintype T] + +open scoped Classical in +/-- Only the short splitting-tree depth multiplies the frozen square +budget. It is independent of the full host degree. -/ +theorem hot_squares : + ∑ z, (degree P.hot z) ^ 2 ≤ 4 * Nat.clog 2 s * ∑ t, (Fintype.card {i // f i = t}) ^ 2 := by + simp_rw [pow_two (degree P.hot _)] + rw [weighted_degree, Fintype.sum_prod_type] + calc + _ ≤ ∑ _k : Fin (Nat.clog 2 s), ∑ i, 4 * Fintype.card {j // f j = f i} := by + refine sum_le_sum fun k _ => sum_le_sum fun i _ => ?_ + have := P.hot_at f sep i k.val + have := P.hot_at f sep i (k.val + 1) + change degree P.hot (P.climb k.val i) + degree P.hot (P.climb (k.val + 1) i) ≤ _ + omega + _ = _ := by rw [← mul_sum, sum_fiber_card]; simp [mul_assoc, mul_left_comm] + +omit [Fintype V] [Fintype G] [Fintype T] in +open scoped Classical in +theorem hot_max (B : ℝ) (hb : 0 ≤ B) (hB : ∀ t, Fintype.card {j // f j = t} ≤ B) + (z : G × Host V r s w) : degree P.hot z ≤ 2 * B := by + by_cases hz : ∃ i k, P.climb k i = z + · obtain ⟨i, k, rfl⟩ := hz + have hd : (degree P.hot (P.climb k i) : ℝ) ≤ 2 * Fintype.card {j // f j = f i} := by + exact_mod_cast P.hot_at f sep i k + exact hd.trans (mul_le_mul_of_nonneg_left (hB _) (by norm_num)) + · push Not at hz + simp [degree_sum, arityCost, hot, hz, hb] + +omit sep [Fintype V] [Fintype G] [Fintype T] in +open scoped Classical in +/-- A single outlet serves a single core destination. Thus both sides +of any cold route satisfy the same core load bound. -/ +theorem cold_max (B : ℝ) (hb : 0 ≤ B) + (dst : ∀ g v, Fintype.card {i // P.group i = g ∧ P.dst i = v} ≤ B) + (dest : ∀ i j, P.group i = P.group j → P.src i = P.src j → P.pin i = P.pin j → P.dst i + = P.dst j) + (z : G × Host V r s w) : degree P.cold z ≤ 2 * B := by + let a i := ((P.group i, P.ends i false), (P.group i, P.ends i true)) + have bound (g : G) (v : End V r s) : degree a (g, v) ≤ B := by + cases v with + | inl v => + simpa [degree_sum, arityCost, a, ends, sum_boole, Fintype.card_subtype] using dst g v + | inr v => + by_cases he : ∃ i, P.group i = g ∧ (P.src i, Tree.tip (P.pin i)) = v + · obtain ⟨i, hi, hv⟩ := he + have hd : degree a (g, .inr v) ≤ Fintype.card {j // P.group j = g ∧ P.dst j = P.dst i} := by + rw [degree_sum, Fintype.card_subtype, card_eq_sum_ones, sum_filter] + refine sum_le_sum fun j _ => ?_ + by_cases hj : P.group j = g ∧ (P.src j, Tree.tip (P.pin j)) = v + · obtain ⟨e, p⟩ := Prod.mk.inj (hj.2.trans hv.symm) + have := dest j i (hj.1.trans hi.symm) e (Tree.tip_injective p) + simp [arityCost, a, ends, hj.1, hj.2, this] + · simp [arityCost, a, ends, hj] + exact (Nat.cast_le.mpr hd).trans (dst _ _) + · have hn (i : I) : ¬(P.group i = g ∧ (P.src i, Tree.tip (P.pin i)) = v) := + fun h => he ⟨i, h⟩ + simp [degree_sum, arityCost, a, ends, hn, hb] + have h : (degree P.cold z : ℝ) ≤ 2 * degree a (z.1, Detour.owner z.2) := by + exact_mod_cast sw.route_degree P.group P.ends P.ok z + exact h.trans (mul_le_mul_of_nonneg_left (bound _ _) (by norm_num)) + +end Tether.Plan +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Indexing frozen members and tether outlets + +A positive load floor and a bound on the total load at a site give a +bound on the required slots. One outlet per distinct core destination +suffices. Thus a group of parallel bits is never split. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Tether +open Finset + +variable {I T V : Type} [Fintype I] + +open scoped Classical in +/-- Number the occupants of each location without conflicts. -/ +theorem number (loc : I → V) (l : I → ℝ) (b : ℝ) (hb : 0 < b) + (lo : ∀ i, b ≤ l i) (r : ℕ) (hi : ∀ v, push loc l v ≤ r * b) : + ∃ t : I → Fin r, Function.Injective (fun i => (loc i, t i)) := by + have slots (v : V) : Nonempty ({i // loc i = v} ↪ Fin r) := by + apply Function.Embedding.nonempty_of_card_le + rw [Fintype.card_fin, ← Nat.cast_le (α := ℝ)] + apply le_of_mul_le_mul_right _ hb + calc + _ = push loc (fun _ => b) v := by + rw [push, ← sum_filter, sum_const, nsmul_eq_mul, Fintype.card_subtype] + _ ≤ push loc l v := push_le_push loc lo v + _ ≤ _ := hi v + let p := fun v => Classical.choice (slots v) + let t i := p (loc i) ⟨i, rfl⟩ + have aux i v (he : loc i = v) : t i = p v ⟨i, he⟩ := by subst v; rfl + refine ⟨t, fun i j h => ?_⟩ + obtain ⟨e, h⟩ := Prod.mk.inj h + rw [aux i _ e, aux j _ rfl] at h + exact congrArg Subtype.val ((p _).injective h) + +open scoped Classical in +/-- Bits of a frozen member have the same outlet exactly when they +have the same core destination. -/ +theorem outlets (f : I → T) (v : I → V) (b : ℝ) (hb : 0 < b) + (lo : ∀ i, b ≤ Fintype.card {j // f j = f i ∧ v j = v i}) + (s : ℕ) (hi : ∀ t, Fintype.card {i // f i = t} ≤ s * b) : + ∃ pin : I → Fin s, ∀ i j, f i = f j → (pin i = pin j ↔ v i = v j) := by + let A := Set.range (fun i => (f i, v i)) + let e (i : I) : A := ⟨(f i, v i), i, rfl⟩ + let wt := push e (fun _ => 1) + let owner (p : A) := p.val.1 + have hw (p : A) : b ≤ wt p := by + obtain ⟨i, hi⟩ := p.property + have he : e i = p := Subtype.ext hi + rw [← he] + have eq (j : I) : e j = e i ↔ f j = f i ∧ v j = v i := by + rw [Subtype.ext_iff] + simp only [e, Prod.mk.injEq] + simpa only [wt, push, eq, sum_boole, Fintype.card_subtype] using lo i + have cap t : push owner wt t ≤ s * b := by + unfold wt + rw [push_comp] + change push f (fun _ => 1) t ≤ _ + simpa only [push, sum_boole, Fintype.card_subtype] using hi t + obtain ⟨p, hp⟩ := number owner wt b hb hw s cap + refine ⟨p ∘ e, fun i j he => ⟨fun h => ?_, fun h => congrArg p (Subtype.ext (Prod.ext he h))⟩⟩ + exact congrArg (fun z : A => z.val.2) (hp (show (owner (e i), p (e i)) = _ from Prod.ext he h)) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Tether +end + +/- # Restoring individual frozen members on the common host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +open Finset + +variable {F T : Type} {x y : Wire} {h u : ℕ} {L : Fringe x y T} (G : HostNet F L h u) + +open scoped Classical in +/-- Computes the far by the application `G.units.place (portEnd G.diagram i)`. -/ +def far (i : slots x ⊕ slots y) := G.units.place (portEnd G.diagram i) + +open scoped Classical in +/-- Parallel tether bits from one frozen tensor to a core occurrence. -/ +def parallelBits (i : slots x ⊕ slots y) := + letI : DecidableEq (G.V × Cell h) := Classical.typeDecidableEq _ + Fintype.card {j // L.tensor j = L.tensor i ∧ G.far j = G.far i} + +open scoped Classical in +theorem Preserves.parallelBits {h' u' : ℕ} {Q : HostNet F L h' u'} (hq : G.Preserves Q) + (i : slots x ⊕ slots y) : G.parallelBits i ≤ Q.parallelBits i := by + obtain ⟨o, _, ho, _⟩ := hq + simp only [HostNet.parallelBits, Fintype.card_subtype] + apply card_le_card + intro j hj + simp only [mem_filter, mem_univ, true_and] at hj ⊢ + exact ⟨hj.1, (ho j).trans ((congrArg o hj.2).trans (ho i).symm)⟩ + +open scoped Classical in +/-- The data for the restore construction, including `degree`, `slot`, `unique`, `pin`, +`outlet`. -/ +structure Restore (D r s : ℕ) where + degree : ∀ v, (G.N v).card ≤ D + /-- The `Restore` component of type `T → Fin r`. -/ + slot : T → Fin r + unique : Function.Injective (fun t => (G.park t, slot t)) + /-- The `Restore` component of type `slots x ⊕ slots y → Fin s`. -/ + pin : slots x ⊕ slots y → Fin s + outlet : ∀ i j, L.tensor i = L.tensor j → (pin i = pin j ↔ G.far i = G.far j) + /-- The bit positions of the representation. -/ + pins : ∀ x, ↥(Tether.near G.N r s x) ↪ Fin (Tether.width D r s) := + (Detour.switch (Tether.near G.N r s) (Tether.near_symm G.N G.ns) + (Tether.near_card G.N D degree)).pin + +open scoped Classical in +theorem restore [Fintype T] (D r s : ℕ) (B b : ℝ) (hb : 0 < b) + (host : G.Bounded 3 D B) (member_cap : B ≤ L.scale * (r * b)) + (charges : ∀ t, b ≤ L.charge t ∧ L.charge t ≤ s * b) + (contacts : ∀ i, b ≤ G.parallelBits i) : Nonempty (G.Restore D r s) := by + have upper (v : G.V × Cell h) : push G.park L.charge v ≤ r * b := by + apply le_of_mul_le_mul_left _ L.pos + refine le_trans ?_ ((host.2.2 v.1 v.2).trans member_cap) + change _ ≤ (G.tetherLoad v : ℝ) + degree G.pair v * (u : ℝ) + + L.scale * push G.park L.charge v + G.rate * G.past v + refine le_trans ?_ (le_add_of_nonneg_right (mul_nonneg G.rate_nonneg (Nat.cast_nonneg _))) + exact le_add_of_nonneg_left (by positivity) + obtain ⟨p, hp⟩ := Tether.number G.park L.charge b hb (fun t => (charges t).1) r upper + obtain ⟨pin, hit⟩ := Tether.outlets L.tensor G.far b hb contacts s + (fun t => (L.cover t).trans (charges t).2) + exact ⟨{ degree := host.2.1, slot := p, unique := hp, pin := pin, outlet := hit }⟩ + +namespace Restore +variable {G} {D r s : ℕ} (A : G.Restore D r s) +local notation "W" => Tether.width D r s + +open scoped Classical in +/-- Computes the space by the application `Tether.Host G.V r s W`. -/ +abbrev Space (_ : G.Restore D r s) := Tether.Host G.V r s W + +open scoped Classical in +/-- Uses `⟨Tether.near G.N r s, Tether.near_symm G.N G.ns, A.pins⟩` as the representation. -/ +def sw : Detour.Switch (Tether.End G.V r s) W := + ⟨Tether.near G.N r s, Tether.near_symm G.N G.ns, A.pins⟩ + +open scoped Classical in +/-- Builds `Tether.Plan A.sw (Cell h) (slots x ⊕ slots y) where group i` with the specified +`group`, `dst`, `src`, `pin`. -/ +def plan : Tether.Plan A.sw (Cell h) (slots x ⊕ slots y) where + group i := (G.far i).2 + dst i := (G.far i).1 + src i := ((G.park (L.tensor i)).1, A.slot (L.tensor i)) + pin := A.pin + ok i := mem_image_of_mem _ (mem_product.mpr + ⟨mem_product.mpr ⟨(G.tether i).2.2, mem_univ _⟩, mem_univ _⟩) + +open scoped Classical in +/-- The value specified by `(z.2, Tether.core z.1)`. -/ +def toCore (z : G.V × Cell h) : Cell h × A.Space := (z.2, Tether.core z.1) + +open scoped Classical in +theorem core_injective : Function.Injective A.toCore := by + intro p q he + simp only [toCore, Tether.core, Prod.mk.injEq, Sum.inl.injEq] at he + exact Prod.ext he.2 he.1 + +open scoped Classical in +/-- The value specified by `((G.park t).2, Tether.member ((G.park t).1, A.slot t))`. -/ +def toFrozen (t : T) : Cell h × A.Space := + ((G.park t).2, Tether.member ((G.park t).1, A.slot t)) + +open scoped Classical in +theorem frozen_injective : Function.Injective A.toFrozen := by + intro p q he + simp only [toFrozen, Tether.member, Prod.mk.injEq, Sum.inl.injEq, Sum.inr.injEq, and_true] at he + exact A.unique (Prod.ext (Prod.ext he.2.1 he.1) he.2.2) + +open scoped Classical in +theorem frozen_eq (i : slots x ⊕ slots y) : A.plan.frozen i = A.toFrozen (L.tensor i) := + Prod.ext (G.tether i).2.1 rfl + +open scoped Classical in +theorem sep (i j : slots x ⊕ slots y) (hg : A.plan.group i = A.plan.group j) + (hs : A.plan.src i = A.plan.src j) : L.tensor i = L.tensor j := by + apply A.frozen_injective + rw [← frozen_eq, ← frozen_eq, Tether.Plan.frozen, Tether.Plan.frozen, hg, hs] + +variable [Fintype T] + +omit [Fintype T] in +open scoped Classical in +theorem hot_max (B : ℝ) (hB : 0 ≤ B) (hc : ∀ t, L.charge t ≤ B) (z : Cell h × A.Space) : + Packing.degree A.plan.hot z ≤ 2 * B := + A.plan.hot_max L.tensor A.sep B hB (fun t => (L.cover t).trans (hc t)) z + +open scoped Classical in +theorem hot_squares : (∑ z, (Packing.degree A.plan.hot z : ℝ) ^ 2) ≤ + 4 * Nat.clog 2 s * ∑ t, (L.charge t) ^ 2 := by + have h := A.plan.hot_squares L.tensor A.sep + have h' : (∑ z, (Packing.degree A.plan.hot z : ℝ) ^ 2) ≤ + 4 * Nat.clog 2 s * ∑ t, (Fintype.card {i // L.tensor i = t} : ℝ) ^ 2 := by + exact_mod_cast h + exact h'.trans (mul_le_mul_of_nonneg_left (sum_le_sum fun t _ => + pow_le_pow_left₀ (Nat.cast_nonneg _) (L.cover t) 2) (by positivity)) + +open scoped Classical in +theorem cold_max (B : ℝ) (hb : 0 ≤ B) (host : G.Bounded 3 D B) (z : Cell h × A.Space) : + Packing.degree A.plan.cold z ≤ 2 * B := by + apply A.plan.cold_max B hb _ _ z + · intro i v + have ht : (G.tetherLoad (v, i) : ℝ) ≤ B := le_trans (le_add_of_nonneg_right (by positivity)) + ((G.core_le_load v i).trans (host.2.2 v i)) + rw [tetherLoad, port_load] at ht + simpa [plan, far, push, Prod.ext_iff, and_comm, sum_boole, Fintype.card_subtype] using ht + · intro i j hg hs hp + exact congrArg Prod.fst ((A.outlet i j (A.sep i j hg hs)).mp hp) + +end Restore +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet +end + +/- +# Restoring the frozen border and the degree-four support + +Keep the core wires and realize the tethers by one exact packet. +The orientation of each old incidence is retained. Exterior bits +are never identified, even when frozen members share a parking site. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet.Restore +open Spectral + +variable {F T : Type} {a b x y : Wire} {h u D r s : ℕ} + {L : Fringe x y T} {G : HostNet F L h u} (A : G.Restore D r s) + +open scoped Classical in +/-- Indexes the wires by the coordinates of `Tether.Plan.Wire s (Tether.width D r s) (slots x ⊕ +slots y) ⊕ G.diagram.E`. -/ +abbrev Wires (_ : G.Restore D r s) := + Tether.Plan.Wire s (Tether.width D r s) (slots x ⊕ slots y) ⊕ G.diagram.E + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def owner : G.diagram.V ⊕ T → Cell h × A.Space := + Sum.elim (A.toCore ∘ G.units.place) A.toFrozen + +open scoped Classical in +/-- The value specified by `(A.toCore (G.units.place (G.diagram.source e)), A.toCore +(G.units.place (G.diagram.target e)))`. -/ +def oldCore (e : G.diagram.E) := + (A.toCore (G.units.place (G.diagram.source e)), A.toCore (G.units.place (G.diagram.target e))) + +open scoped Classical in +/-- Computes the supply by the application `Sum.elim A.plan.supply A.oldCore`. -/ +def supply : A.Wires → (Cell h × A.Space) × (Cell h × A.Space) := + Sum.elim A.plan.supply A.oldCore + +open scoped Classical in +/-- Uses `Tether.adj A.sw G.C` as the representation. -/ +def adj : A.Space → Finset A.Space := Tether.adj A.sw G.C + +open scoped Classical in +theorem support (e : A.Wires) : + (A.supply e).1.1 = (A.supply e).2.1 ∧ (A.supply e).2.2 ∈ A.adj (A.supply e).1.2 := by + cases e with + | inl e => exact A.plan.support G.C e + | inr e => + simp only [supply, Sum.elim_inr, oldCore, G.units.left, G.units.right, toCore, true_and] + exact Tether.core_adj _ _ (G.edge _) + +variable [Fintype T] [Field F] (B : Border F T a b x y) (hB : L.tensor = B.tensor) + +open scoped Classical in +/-- The value specified by `(A.owner ((B.attach G.diagram).source e), A.owner ((B.attach +G.diagram).target e))`. -/ +def demands (e : (B.attach G.diagram).E) := + (A.owner ((B.attach G.diagram).source e), A.owner ((B.attach G.diagram).target e)) + +include hB in +open scoped Classical in +theorem packet : Packet F (A.demands B) (fun _ : Unit => A.supply) := by + let flip : slots x ⊕ slots y → Bool := Sum.elim (fun _ => false) (fun _ => true) + have ht := (A.plan.packet F).orient flip + have hp := ((ht.keep A.oldCore).place (Sum.elim id id)).reindex + (Equiv.sumComm G.diagram.E (slots x ⊕ slots y)) + convert hp using 1 + · funext e + rcases e with e | i | j + · rfl + · change (A.plan.terminal (.inl i), A.toFrozen (B.tensor (.inl i))) = + (A.plan.terminal (.inl i), A.plan.frozen (.inl i)) + rw [A.frozen_eq, hB] + · change (A.toFrozen (B.tensor (.inr j)), A.plan.terminal (.inr j)) = + (A.plan.frozen (.inr j), A.plan.terminal (.inr j)) + rw [A.frozen_eq, hB] + · funext _ e + cases e <;> rfl + +omit [Field F] in +open scoped Classical in +private theorem aligned : + (B.attach G.diagram).Aligned (fun _ : Unit => A.owner) (fun _ => id) (A.demands B) := + fun _ _ => ⟨rfl, rfl⟩ + +open scoped Classical in +/-- The indexed operation `(B.attach G.diagram).replaced (A.packet B hB).rule (fun _ => A.owner) +(fun _ => id) ()`. -/ +abbrev graph : Diagram F a b := + (B.attach G.diagram).replaced (A.packet B hB).rule (fun _ => A.owner) (fun _ => id) () + +open scoped Classical in +theorem eval : (A.graph B hB).eval = (B.attach G.diagram).eval := by + funext x y + simpa only [Fintype.sum_unique] using + (B.attach G.diagram).eval_replaced (A.packet B hB).rule (fun _ => A.owner) (fun _ => id) x y + +open scoped Classical in +theorem supported (e : (A.graph B hB).E) : + let p := (A.graph B hB).source e + let q := (A.graph B hB).target e + p.1 = q.1 ∧ q.2 ∈ A.adj p.2 := by + obtain ⟨i, rfl⟩ := ((B.attach G.diagram).cutEdges (A.packet B hB).rule + (fun _ => A.owner) (fun _ => id) (A.aligned B) ()).surjective e + exact A.support i.val + +open scoped Classical in +theorem arity (p : Cell h × A.Space) : + (A.graph B hB).arity p ≤ exterior (B.attach G.diagram) A.owner p + Packing.degree A.supply p := + (B.attach G.diagram).arity_replaced (A.packet B hB).rule (fun _ => A.owner) (fun _ => id) + (A.aligned B) () p + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.HostNet.Restore +end + +/- # Total load and squared load after restoring bounded degree -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V W : Type} [Fintype V] {f : V → W} + +open scoped Classical in +private theorem push_inj (hf : Function.Injective f) (l : V → ℝ) (v : V) : + push f l (f v) = l v := by simp [push, hf.eq_iff] + +open scoped Classical in +private theorem push_zero (l : V → ℝ) {w : W} (hw : w ∉ Set.range f) : + push f l w = 0 := by + have hn v : f v ≠ w := fun h => hw ⟨v, h⟩ + simp [push, hn] + +open scoped Classical in +private theorem push_sq (hf : Function.Injective f) (l : V → ℝ) (w : W) : + (push f l w) ^ 2 = push f (fun v => (l v) ^ 2) w := by + by_cases h : w ∈ Set.range f + · obtain ⟨v, rfl⟩ := h + rw [push_inj hf, push_inj hf] + · rw [push_zero _ h, push_zero _ h]; norm_num + +namespace HostNet.Restore + +variable {F T : Type} [Fintype T] {a b x y : Wire} {h u D r s : ℕ} + {L : Fringe x y T} {G : HostNet F L h u} (A : G.Restore D r s) + +open scoped Classical in +/-- Charge every parked member and all incident supply bits, also when +coarsening makes some of those bits internal to a site. -/ +def charge (p : Cell h × A.Space) := push A.toFrozen L.charge p + Packing.degree A.supply p + +open scoped Classical in +theorem charge_nonneg (p : Cell h × A.Space) : 0 ≤ A.charge p := + add_nonneg (push_nonneg _ _ L.nonneg _) (Nat.cast_nonneg _) + +open scoped Classical in +theorem exterior_covers (B : Border F T a b x y) + (cap : ∀ t, ((B.attach G.diagram).arity (.inr t) : ℝ) ≤ L.charge t) + (p : Cell h × A.Space) : exterior (B.attach G.diagram) A.owner p ≤ push A.toFrozen L.charge p + := by + let H := B.attach G.diagram + let f : slots a ⊕ slots b → T := + Sum.elim (fun i => (B.src.symm (.inl i)).1) (fun j => (B.dst.symm (.inl j)).1) + have hf : portEnd H = Sum.inr ∘ f := by funext q; cases q <;> rfl + have bound (t : T) : push f (fun _ => 1) t ≤ L.charge t := by + have hi := site_arity H id (.inr t) + rw [port_load, hf] at hi + have bit : push f (fun _ => 1) t ≤ (H.arity (.inr t) : ℝ) := by + rw [show (H.arity (.inr t) : ℝ) = push id (fun i => (H.arity i : ℝ)) (.inr t) + by exact (push_inj Function.injective_id (fun i => (H.arity i : ℝ)) (.inr t)).symm, hi] + have eq : push (id ∘ Sum.inr ∘ f) (fun _ => 1) (Sum.inr t : H.V) = + push f (fun _ => 1) t := by simp only [push, Function.comp_apply, id_eq, Sum.inr.injEq] + rw [eq] + exact le_add_of_nonneg_right (Nat.cast_nonneg _) + exact bit.trans (cap t) + change (exterior H A.owner p : ℝ) ≤ _ + rw [port_load, hf] + change push (A.toFrozen ∘ f) (fun _ => 1) p ≤ _ + rw [← push_comp] + exact push_le_push A.toFrozen bound p + +open scoped Classical in +theorem charge_covers [Field F] (B : Border F T a b x y) (he : L.tensor = B.tensor) + (cap : ∀ t, ((B.attach G.diagram).arity (.inr t) : ℝ) ≤ L.charge t) + (p : Cell h × A.Space) : (A.graph B he).arity p ≤ A.charge p := by + have outside := A.exterior_covers B cap p + have := Nat.cast_le (α := ℝ) |>.mpr (A.arity B he p) + rw [Nat.cast_add] at this + exact this.trans (add_le_add_left outside _) + +open scoped Classical in +theorem mass : + ∑ p, A.charge p ≤ 2 * G.X + + (1 + 2 * (Detour.steps (Tether.width D r s) + Nat.clog 2 s)) * L.Z := by + have hc : Fintype.card G.diagram.E = G.X := by + simp [X, Fintype.card_congr G.units.bits] + rw [show (∑ p, A.charge p) = ∑ t, L.charge t + 2 * Fintype.card A.Wires by + simp only [charge, sum_add_distrib, sum_push, ← Nat.cast_sum, sum_degree, Nat.cast_mul, + Nat.cast_ofNat]] + unfold Wires + rw [Fintype.card_sum, Tether.Plan.cardinality, hc, Nat.cast_add, Nat.cast_mul, Nat.cast_add] + have ht := mul_le_mul_of_nonneg_left L.tethers + (show (0 : ℝ) ≤ Detour.steps (Tether.width D r s) + Nat.clog 2 s by positivity) + have hp := L.reserve_nonneg + unfold Fringe.Z at * + linarith [L.reserve_nonneg] + +omit [Fintype T] in +open scoped Classical in +theorem core_degree (p : Cell h × A.Space) : + (Packing.degree A.oldCore p : ℝ) = push A.toCore (fun v => (Packing.degree G.pair v : ℝ) * u) p + := by + let pair (e : G.diagram.E) := (G.units.place (G.diagram.source e), + G.units.place (G.diagram.target e)) + have hh (z : G.V × Cell h) : Packing.degree pair z = Packing.degree G.pair z * u := by + rw [← degree_bundle G.pair u z, degree_sum, degree_sum] + exact Fintype.sum_equiv G.units.bits _ _ (fun e => + congrArg (arityCost z) (Prod.ext (G.units.left e) (G.units.right e))) + change (Packing.degree (fun e => Prod.map A.toCore A.toCore (pair e)) p : ℝ) = _ + simp only [degree_map, hh, Nat.cast_sum, Nat.cast_ite, Nat.cast_zero, Nat.cast_mul, push] + +open scoped Classical in +private def light (p : Cell h × A.Space) := + (Packing.degree A.oldCore p : ℝ) + Packing.degree A.plan.cold p + +open scoped Classical in +private theorem light_bound (B : ℝ) (hb : 0 ≤ B) (host : G.Bounded 3 D B) + (p : Cell h × A.Space) : A.light p ≤ 3 * B := by + have hc : (Packing.degree A.oldCore p : ℝ) ≤ B := by + rw [core_degree] + by_cases hx : p ∈ Set.range A.toCore + · obtain ⟨⟨v, i⟩, rfl⟩ := hx + rw [push_inj A.core_injective] + exact le_trans (le_add_of_nonneg_left (Nat.cast_nonneg _)) + ((G.core_le_load v i).trans (host.2.2 v i)) + · rw [push_zero _ hx]; exact hb + unfold light + linarith [A.cold_max B hb host p] + +open scoped Classical in +private theorem parts (p : Cell h × A.Space) : + A.charge p = push A.toFrozen L.charge p + Packing.degree A.plan.hot p + A.light p := by + simp only [charge, light, supply, Tether.Plan.supply, degree_partition, Nat.cast_add] + ring + +open scoped Classical in +theorem maximum (B Q : ℝ) (hb : 0 ≤ B) (hq : 0 ≤ Q) + (host : G.Bounded 3 D B) (hQ : ∀ t, L.charge t ≤ Q) (p : Cell h × A.Space) : + A.charge p ≤ 3 * (B + Q) := by + have hf : push A.toFrozen L.charge p ≤ Q := by + by_cases h : p ∈ Set.range A.toFrozen + · obtain ⟨t, rfl⟩ := h + rw [push_inj A.frozen_injective] + exact hQ _ + · rw [push_zero _ h]; exact hq + rw [parts] + linarith [A.hot_max Q hq hQ p, A.light_bound B hb host p] + +open scoped Classical in +/-- Full-degree routing contributes only a light-arity term. The large +frozen square budget is multiplied only by the short outlet depth. -/ +theorem squares (B : ℝ) (hb : 0 ≤ B) (host : G.Bounded 3 D B) : + ∑ p, (A.charge p) ^ 2 ≤ 3 * (1 + 4 * Nat.clog 2 s) * (∑ t, (L.charge t) ^ 2) + + 9 * B * ∑ p, A.charge p := by + have point (p : Cell h × A.Space) : (A.charge p) ^ 2 ≤ + 3 * ((push A.toFrozen L.charge p) ^ 2 + (Packing.degree A.plan.hot p : ℝ) ^ 2) + + 9 * B * A.charge p := by + let x := push A.toFrozen L.charge p + let y : ℝ := Packing.degree A.plan.hot p + let z := A.light p + have hx : 0 ≤ x := push_nonneg _ _ L.nonneg _ + have hy : 0 ≤ y := Nat.cast_nonneg _ + have hz : 0 ≤ z := by unfold z light; positivity + have he : A.charge p = x + y + z := A.parts p + have ht : z ≤ 3 * B := A.light_bound B hb host p + change (A.charge p) ^ 2 ≤ 3 * (x ^ 2 + y ^ 2) + 9 * B * A.charge p + rw [he] + nlinarith only [sq_nonneg (x - y), sq_nonneg (x - z), sq_nonneg (y - z), + mul_nonneg hb hx, mul_nonneg hb hy, mul_le_mul_of_nonneg_right ht hz] + have := sum_le_sum (fun p (_ : p ∈ univ) => point p) + simp only [sum_add_distrib, ← mul_sum, push_sq A.frozen_injective, sum_push] at this + linarith [A.hot_squares] + +omit [Fintype T] in +open scoped Classical in +private theorem repeated (b : ℝ) (units : b ≤ u) (contacts : ∀ i, b ≤ G.parallelBits i) + (e : A.Wires) : b ≤ Fintype.card {i // A.supply i = A.supply e} := by + let : DecidableEq (G.V × Cell h) := Classical.typeDecidableEq _ + rcases e with (⟨k, i⟩ | ⟨k, i⟩) | e + · refine (contacts i).trans (Nat.cast_le.mpr ?_) + unfold parallelBits + let t (j : {j // L.tensor j = L.tensor i ∧ G.far j = G.far i}) : + {e // A.supply e = A.supply (.inl (.inl (k, i)))} := ⟨.inl (.inl (k, j.val)), by + have hh := (A.outlet _ _ j.property.1).mpr j.property.2 + simp only [supply, Tether.Plan.supply, Sum.elim_inl, Tether.Plan.cold, Detour.Switch.route, + Tether.Plan.ends, plan, j.property.1, j.property.2, hh]⟩ + exact Fintype.card_le_of_injective t (by intro j l h; simpa [t, Subtype.ext_iff] using h) + · refine (contacts i).trans (Nat.cast_le.mpr ?_) + unfold parallelBits + let t (j : {j // L.tensor j = L.tensor i ∧ G.far j = G.far i}) : + {e // A.supply e = A.supply (.inl (.inr (k, i)))} := ⟨.inl (.inr (k, j.val)), by + have hh := (A.outlet _ _ j.property.1).mpr j.property.2 + simp only [supply, Tether.Plan.supply, Sum.elim_inl, Sum.elim_inr, Tether.Plan.hot, + Tether.Plan.climb, plan, j.property.1, j.property.2, hh]⟩ + exact Fintype.card_le_of_injective t (by intro j l h; simpa [t, Subtype.ext_iff] using h) + · let t (j : Fin u) : {i // A.supply i = A.supply (.inr e)} := + ⟨.inr (G.units.bits.symm ((G.units.bits e).1, j)), by + simp only [supply, Sum.elim_inr, oldCore, G.units.left, G.units.right, + Equiv.apply_symm_apply]⟩ + have hi : Function.Injective t := by intro j l he; simpa [t, Subtype.ext_iff] using he + refine units.trans (Nat.cast_le.mpr ?_) + simpa only [Fintype.card_fin] using Fintype.card_le_of_injective t hi + +open scoped Classical in +/-- Unoccupied sites have zero charge. Every other site carries at +least one whole original bundle or one surviving frozen member. -/ +theorem floor (b : ℝ) (units : b ≤ u) (contacts : ∀ i, b ≤ G.parallelBits i) + (frozen : ∀ t, b ≤ L.charge t) (p : Cell h × A.Space) : + A.charge p = 0 ∨ b ≤ A.charge p := by + unfold charge + by_cases hf : p ∈ Set.range A.toFrozen + · obtain ⟨t, rfl⟩ := hf + rw [push_inj A.frozen_injective] + exact .inr ((frozen t).trans (le_add_of_nonneg_right (Nat.cast_nonneg _))) + rw [push_zero _ hf, zero_add] + by_cases ha : ∃ e, (A.supply e).1 = p ∨ (A.supply e).2 = p + · obtain ⟨e, he⟩ := ha + refine .inr ((A.repeated b units contacts e).trans (Nat.cast_le.mpr ?_)) + rw [Fintype.card_subtype, card_eq_sum_ones, sum_filter, degree_sum] + refine sum_le_sum fun i _ => ?_ + by_cases h : A.supply i = A.supply e + · rcases he with he|he <;> simp [h, arityCost, he] + · simp [h] + · push Not at ha + left + simp [degree_sum, arityCost, (ha _).1, (ha _).2] + +end HostNet.Restore +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Original tether multiplicities are lower bounds after cutting -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Freeze + +variable {F : Type} {a b : Wire} {G : Diagram F a b} (Z : Freeze G) + +open scoped Classical in +private theorem parallel_tether (i : slots Z.x ⊕ slots Z.y) (e : G.E) + (hs : G.source e = G.source (Z.tether i)) (ht : G.target e = G.target (Z.tether i)) : + ∃ j, Z.tether j = e ∧ Z.border.tensor j = Z.border.tensor i ∧ + portEnd Z.core j = portEnd Z.core i := by + cases i with + | inl i => + have h : Z.frozen (G.target e) := ht.symm ▸ (Z.input i).property + obtain ⟨j, hj⟩ := Z.input.surjective ⟨e, h⟩ + have eq : Z.tether (.inl j) = e := congrArg Subtype.val hj + exact ⟨.inl j, eq, Subtype.ext ((congrArg G.target eq).trans ht), + Subtype.ext ((congrArg G.source eq).trans hs)⟩ + | inr i => + have h : Z.frozen (G.source e) := hs.symm ▸ (Z.output i).property + obtain ⟨j, hj⟩ := Z.output.surjective ⟨e, h⟩ + have eq : Z.tether (.inr j) = e := congrArg Subtype.val hj + exact ⟨.inr j, eq, Subtype.ext ((congrArg G.source eq).trans hs), + Subtype.ext ((congrArg G.target eq).trans ht)⟩ + +namespace Frame +variable {V : Type} [Fintype V] {h u : ℕ} {Z} + (H : Z.Frame V h) (hu : 0 < u) (hd : Z.Divisible u) + (L : Fringe Z.x Z.y Z.Fixed) (hL : L.tensor = Z.border.tensor) + +open scoped Classical in +theorem host_parallel + (hw : ∀ v w, u ∣ Fintype.card {e // G.source e = v ∧ G.target e = w}) + (i : slots Z.x ⊕ slots Z.y) : u ≤ (H.host hu hd L hL).parallelBits i := by + let Q := H.host hu hd L hL + let W := {e // G.source e = G.source (Z.tether i) ∧ G.target e = G.target (Z.tether i)} + have : Nonempty W := ⟨⟨Z.tether i, rfl, rfl⟩⟩ + have lower : u ≤ Fintype.card W := Nat.le_of_dvd Fintype.card_pos (hw _ _) + refine lower.trans ?_ + choose j he ht hc using fun e : W => Z.parallel_tether i e.val e.property.1 e.property.2 + have far (e : W) : Q.far (j e) = Q.far i := + congrArg (fun v : Z.Core => H.place v.val) (hc e) + let f (e : W) : {p // L.tensor p = L.tensor i ∧ Q.far p = Q.far i} := + ⟨j e, by rw [hL]; exact ht e, far e⟩ + have inj : Function.Injective f := by + intro e e' eq + exact Subtype.ext ((he e).symm.trans + ((congrArg (fun p => Z.tether p.val) eq).trans (he e'))) + unfold HostNet.parallelBits + convert! Fintype.card_le_of_injective f inj using 2 + +end Frame +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Freeze +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Suffix.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Suffix.lean new file mode 100644 index 0000000000..597b4d70cc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/Suffix.lean @@ -0,0 +1,961 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +public import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +public import Mathlib.Data.Finset.Max +public import Mathlib.Data.Fintype.Pi +public import Mathlib.Data.Fintype.Option +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import Mathlib.Algebra.Order.Chebyshev +public import Mathlib.Basic.Real.Basic +public import Mathlib.Algebra.Order.Archimedean.Real.Basic +public import Mathlib.Data.Nat.Log +public import Mathlib.Data.Fintype.Prod +public import Mathlib.Data.Fintype.Sigma +public import Mathlib.Algebra.BigOperators.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Reservations +public import Mathlib.Algebra.Module.Equiv.Defs +public import Mathlib.Algebra.Module.Pi + +/-! # Matching whole items to bins of given capacity -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {I D : Type} + +open scoped Classical in +theorem into_bins [Fintype I] [Fintype D] (size : I → ℕ) (cap : D → ℕ) (B : ℕ) (hsize : ∀ i, size i + ≤ B) : + ∃ p : I → Option D, (∀ i, (p i).isSome → 0 < size i) ∧ + (∀ d, (∑ i, if p i = some d then size i else 0) ≤ cap d) ∧ + min (∑ i, size i) (∑ d, cap d) ≤ (∑ i, if (p i).isSome then size i else 0) + + B * (univ.filter fun d => 0 < cap d).card := by + let used (p : I → Option D) d := ∑ i, if p i = some d then size i else 0 + let total (p : I → Option D) := ∑ i, if (p i).isSome then size i else 0 + let valid := univ.filter fun p : I → Option D => + (∀ i, (p i).isSome → 0 < size i) ∧ ∀ d, used p d ≤ cap d + obtain ⟨p, hp, hm⟩ := valid.exists_max_image total ⟨fun _ => none, by simp [valid, used]⟩ + obtain ⟨hpos, hcap⟩ := (mem_filter.mp hp).2 + refine ⟨p, hpos, hcap, ?_⟩ + by_cases hall : ∀ i, p i = none → size i = 0 + · apply le_trans (min_le_left _ _) + refine le_trans ?_ (Nat.le_add_right _ _) + apply sum_le_sum + intro i _ + cases he : p i with + | none => simp [hall i he] + | some d => simp + push Not at hall + obtain ⟨i, hi, hs⟩ := hall + have small (d : D) : cap d ≤ used p d + B := by + by_contra! big + let q := Function.update p i (some d) + have add (f : I → Option D → ℕ) (hz : f i none = 0) : + (∑ j, f j (q j)) = (∑ j, f j (p j)) + f i (some d) := by + rw [← sum_erase_add _ _ (mem_univ i), ← sum_erase_add _ (fun j => f j (p j)) (mem_univ i)] + simp only [q, Function.update_self, hi, hz, add_zero] + congr 1 + exact sum_congr rfl fun j hj => by rw [Function.update_of_ne (ne_of_mem_erase hj)] + have hq : q ∈ valid := by + refine mem_filter.mpr ⟨mem_univ _, ?_, ?_⟩ + · intro j hj + by_cases he : j = i + · simpa [he] using Nat.pos_of_ne_zero hs + · exact hpos j (by simpa [q, he] using hj) + · intro b + have he : used q b = used p b + if d = b then size i else 0 := by + simpa only [Option.some.injEq] using + add (fun j r => if r = some b then size j else 0) (by simp) + rw [he] + split_ifs with eq + · subst b + exact (Nat.add_le_add_left (hsize i) _).trans big.le + · simpa using hcap b + have ht : total q = total p + size i := + add (fun j r => if r.isSome then size j else 0) rfl + have := hm q hq + omega + have he : (∑ d, used p d) = total p := by + unfold used total + rw [sum_comm] + apply sum_congr rfl + intro j _ + cases p j <;> simp + calc + _ ≤ ∑ d, cap d := min_le_right _ _ + _ ≤ ∑ d, (used p d + if 0 < cap d then B else 0) := by + apply sum_le_sum + intro d _ + split_ifs <;> first | exact small d | omega + _ = _ := by rw [sum_add_distrib, he, ← sum_filter, sum_const, Nat.nsmul_eq_mul, mul_comm] + +open scoped Classical in +/-- Match each selected unit to a distinct unit of the specified bin. -/ +theorem match_units {E : Type} [Fintype E] (src : E → I) (plan : E → Option D) + (stock : I → D → Finset E) + (unique : ∀ i j d c e, e ∈ stock i d → e ∈ stock j c → i = j ∧ d = c) + (enough : ∀ i d, (univ.filter fun e => src e = i ∧ plan e = some d).card ≤ + (stock i d).card) : + ∃ mate : {e // (plan e).isSome} ↪ E, ∀ e, ∃ d, + plan e.val = some d ∧ mate e ∈ stock (src e.val) d := by + let items i d := univ.filter fun e => src e = i ∧ plan e = some d + have ex (i d) : ∃ f : E → E, (∀ e ∈ items i d, f e ∈ stock i d) ∧ + Set.InjOn f (items i d) := by + obtain ⟨g⟩ : Nonempty (items i d ↪ stock i d) := Function.Embedding.nonempty_of_card_le + (by simpa only [Fintype.card_coe] using enough i d) + let f e := if he : e ∈ items i d then (g ⟨e, he⟩).val else e + refine ⟨f, ?_, ?_⟩ + · intro e he; simp [f, he] + · intro a ha b hb he + simp only [mem_coe] at ha hb + simp only [f, dite_eq_left ha, dite_eq_left hb] at he + exact congrArg Subtype.val (g.injective (Subtype.ext he)) + choose f hm hi using ex + let D' := {e // (plan e).isSome} + let bin (e : D') := (plan e.val).get e.property + have hb (e : D') : plan e.val = some (bin e) := (Option.some_get _).symm + have he (e : D') : e.val ∈ items (src e.val) (bin e) := + mem_filter.mpr ⟨mem_univ _, rfl, hb e⟩ + let g (e : D') := f (src e.val) (bin e) e.val + have hg (e : D') : g e ∈ stock (src e.val) (bin e) := hm _ _ _ (he e) + have inj : Function.Injective g := by + intro x y h + obtain ⟨h₁, h₂⟩ := unique _ _ _ _ _ (hg x) (h.symm ▸ hg y) + have hx := he x + dsimp only [g] at h + rw [h₁, h₂] at h hx + exact Subtype.ext (hi _ _ hx (he y) h) + exact ⟨⟨g, inj⟩, fun e => ⟨bin e, hb e, hg e⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +section +/- +# Affine colorings of binary cells + +For two distinct cells, translating the color by an affine form that +vanishes at just one of them cancels their cross term in the second moment. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open scoped Classical in +/-- Indexes the color by the coordinates of `Cell h × ZMod 2`. -/ +abbrev Color (h : ℕ) := Cell h × ZMod 2 + +open scoped Classical in +/-- Requires `(∑ i, c.1 i * x i) + c.2 = 0`. -/ +def thick {h} (c : Color h) (x : Cell h) : Prop := + (∑ i, c.1 i * x i) + c.2 = 0 + +open scoped Classical in +private theorem thick_add {h} (c d : Color h) (x : Cell h) : + thick (c + d) x ↔ (thick c x ↔ thick d x) := by + have parity : ∀ u v : ZMod 2, u + v = 0 ↔ (u = 0 ↔ v = 0) := by decide + unfold thick + simp only [Prod.fst_add, Prod.snd_add, Pi.add_apply, add_mul, Finset.sum_add_distrib] + rw [add_add_add_comm, parity] + +open scoped Classical in +private noncomputable def signed {h} (w : Cell h → ℝ) (c : Color h) (x : Cell h) : ℝ := + if thick c x then w x else -w x + +open scoped Classical in +private theorem cross_term {h} (w : Cell h → ℝ) {x y : Cell h} (hxy : y ≠ x) : + ∑ c : Color h, signed w c x * signed w c y = 0 := by + obtain ⟨i, hi⟩ := Function.ne_iff.mp hxy + let d : Color h := (fun j => if j = i then 1 else 0, -x i) + have hd (z : Cell h) : thick d z ↔ z i = x i := by + simp only [thick, d, ite_mul, one_mul, zero_mul, Fintype.sum_ite_eq', ← sub_eq_add_neg, + sub_eq_zero] + have flip (c : Color h) : + signed w (c + d) x * signed w (c + d) y = -(signed w c x * signed w c y) := by + simp only [signed, thick_add, hd, hi, iff_true, iff_false] + by_cases hy : thick c y <;> simp [hy] + have he := Equiv.sum_comp (Equiv.addRight d) (fun c => signed w c x * signed w c y) + change (∑ c, signed w (c + d) x * signed w (c + d) y) = _ at he + simp_rw [flip, Finset.sum_neg_distrib] at he + exact eq_zero_of_neg_eq he + +open scoped Classical in +private theorem second_moment {h} (w : Cell h → ℝ) : + (∑ c : Color h, (∑ x, signed w c x) ^ 2) = ∑ _c : Color h, ∑ x, (w x) ^ 2 := by + simp_rw [pow_two, Finset.sum_mul_sum] + conv_rhs => rw [Finset.sum_comm] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + rw [Finset.sum_comm, Fintype.sum_eq_single x (fun y hy => cross_term w hy)] + apply Finset.sum_congr rfl + intro c _ + by_cases hx : thick c x <;> simp [signed, hx] + +open scoped Classical in +theorem coloring {P : Type} [Fintype P] {h : ℕ} (w : P → Cell h → ℝ) (B : ℝ) + (hw : ∀ p x, 0 ≤ w p x ∧ w p x ≤ B) : + ∃ c : Color h, (∑ p, |∑ x, if thick c x then w p x else -w p x|) ^ 2 ≤ + B * Fintype.card P * (∑ p, ∑ x, w p x) := by + have he : (∑ c : Color h, ∑ p, (∑ x, signed (w p) c x) ^ 2) = + ∑ _c : Color h, ∑ p, ∑ x, (w p x) ^ 2 := by + rw [Finset.sum_comm] + simp_rw [second_moment] + rw [Finset.sum_comm] + obtain ⟨c, _, hc⟩ := Finset.exists_le_of_sum_le Finset.univ_nonempty he.le + have hb : (∑ p, ∑ x, (w p x) ^ 2) ≤ B * ∑ p, ∑ x, w p x := by + simp_rw [Finset.mul_sum, pow_two] + exact Finset.sum_le_sum fun p _ => Finset.sum_le_sum fun x _ => + mul_le_mul_of_nonneg_right (hw p x).2 (hw p x).1 + refine ⟨c, ?_⟩ + calc + _ ≤ (Fintype.card P : ℝ) * ∑ p, |∑ x, signed (w p) c x|^2 := + sq_sum_le_card_mul_sum_sq + _ ≤ (Fintype.card P : ℝ) * (B * ∑ p, ∑ x, w p x) := by + simp_rw [sq_abs] + exact mul_le_mul_of_nonneg_left (hc.trans hb) (Nat.cast_nonneg _) + _ = _ := by ac_rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Matching core wire units within one dyadic group + +Treat a thin occurrence as one indivisible item. After the matching, +thin occurrences with the same destination can be gathered into one +pack. This gives at most one thin pack per bin plus an unmatched pack, +with total load bounded by the load of the colony. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open Finset + +variable {E P : Type} {h : ℕ} + +open scoped Classical in +/-- All outgoing units of an occurrence are either unmatched or paired +with distinct thick units from one source colony to one destination. -/ +structure Matching (src dst : E → P) (ix : E → Cell h) where + /-- The `Matching` component of type `Color h`. -/ + color : Color h + /-- The `Matching` component of type `P → Cell h → Option P`. -/ + plan : P → Cell h → Option P + thin : ∀ p x, (plan p x).isSome → ¬thick color x + used : ∀ p x, (plan p x).isSome → ∃ e, src e = p ∧ ix e = x + /-- Embeds the coordinates as `{e // (plan (src e) (ix e)).isSome} ↪ E`. -/ + mate : {e // (plan (src e) (ix e)).isSome} ↪ E + spec : ∀ e, thick color (ix (mate e)) ∧ src (mate e) = src e.val ∧ + plan (src e.val) (ix e.val) = some (dst (mate e)) + +open scoped Classical in +/-- The indexed operation `(univ.filter fun e => (m.plan (src e) (ix e)).isSome).card`. -/ +def Matching.count [Fintype E] {src dst : E → P} {ix : E → Cell h} (m : Matching src dst ix) := + (univ.filter fun e => (m.plan (src e) (ix e)).isSome).card + +open scoped Classical in +private theorem count_if {I : Type} [Fintype I] [DecidableEq I] + (s : Finset E) (f : E → I) (p : I → Prop) [DecidablePred p] : + (∑ i, if p i then (s.filter fun e => f e = i).card else 0) = + (s.filter fun e => p (f e)).card := by + rw [← sum_filter, sum_card_fiberwise_eq_card_filter s _ f] + simp + +open scoped Classical in +private theorem count_all {I : Type} [Fintype I] [DecidableEq I] (s : Finset E) (f : E → I) : + ∑ i, (s.filter fun e => f e = i).card = s.card := by + simpa using count_if s f (fun _ => True) + +variable [Fintype E] [Fintype P] (src dst : E → P) (ix : E → Cell h) + +open scoped Classical in +private def out (p : P) := univ.filter fun e => src e = p +open scoped Classical in +private def units (p : P) (x : Cell h) := ((out src p).filter fun e => ix e = x).card + +open scoped Classical in +private theorem match_color (b K : ℕ) (c : Color h) + (hs : ∀ p x, units src ix p x ≤ b) + (hd : ∀ p, ((out src p).image dst).card ≤ K) : + ∃ m : Matching src dst ix, (∑ p, + min (∑ x, if thick c x then 0 else units src ix p x) + (∑ x, if thick c x then units src ix p x else 0)) ≤ + m.count + b * K * Fintype.card P := by + let size p x := if thick c x then 0 else units src ix p x + let thickOut p := (out src p).filter fun e => thick c (ix e) + let stock p d := (thickOut p).filter fun e => dst e = d + let cap p d := (stock p d).card + have hsize p x : size p x ≤ b := by unfold size; split_ifs <;> simp [hs] + choose plan hpos hcap htotal using fun p => into_bins (size p) (cap p) b (hsize p) + have thin p x (hx : (plan p x).isSome) : ¬thick c x := by + intro h + simpa [size, h] using hpos p x hx + have used p x (hx : (plan p x).isSome) : ∃ e, src e = p ∧ ix e = x := by + have hn := hpos p x hx + simp only [size, ite_eq_right (thin p x hx), units, card_pos] at hn + obtain ⟨e, he⟩ := hn + exact ⟨e, by simpa [out] using he⟩ + let sel e := plan (src e) (ix e) + have count p (r : Option P → Prop) [DecidablePred r] (hr : ¬ r none) : + (∑ x, if r (plan p x) then size p x else 0) = + (univ.filter fun e => src e = p ∧ r (sel e)).card := by + trans ∑ x, if r (plan p x) then units src ix p x else 0 + · apply sum_congr rfl + intro x _ + cases ht : plan p x with + | none => simp [hr] + | some d => rw [show size p x = units src ix p x by simp [size, thin p x (by simp [ht])]] + · rw [show units src ix p = fun x => ((out src p).filter fun e => ix e = x).card from rfl, + count_if (out src p) ix (fun x => r (plan p x))] + congr 1 + ext e + simp only [out, sel, mem_filter, mem_univ, true_and] + by_cases hp : src e = p <;> simp [hp] + have mem p d e : e ∈ stock p d ↔ src e = p ∧ thick c (ix e) ∧ dst e = d := by + simp [stock, thickOut, out, and_assoc] + obtain ⟨mate, hm⟩ := match_units src sel stock + (fun i j d t e h h' => by + rw [mem] at h h' + exact ⟨h.1.symm.trans h'.1, h.2.2.symm.trans h'.2.2⟩) + (fun p d => by rw [← count p (· = some d) (by simp)]; exact hcap p d) + let m : Matching src dst ix := ⟨c, plan, thin, used, mate, fun e => by + obtain ⟨d, he, hf⟩ := hm e + rw [mem] at hf + exact ⟨hf.2.1, hf.1, hf.2.2.symm ▸ he⟩⟩ + refine ⟨m, ?_⟩ + let selected := univ.filter fun e => (sel e).isSome + have each (p : P) : + min (∑ x, size p x) (∑ x, if thick c x then units src ix p x else 0) ≤ + (selected.filter fun e => src e = p).card + b * K := by + have thickSum : (∑ x, if thick c x then units src ix p x else 0) = ∑ d, cap p d := + (count_if (out src p) ix (thick c)).trans (count_all (thickOut p) dst).symm + have bins : (univ.filter fun d => 0 < cap p d).card ≤ K := by + apply le_trans _ (hd p) + apply card_le_card + intro d hx + obtain ⟨e, he⟩ := card_pos.mp (mem_filter.mp hx).2 + exact mem_image.mpr ⟨e, (mem_filter.mp (mem_filter.mp he).1).1, (mem_filter.mp he).2⟩ + rw [thickSum] + apply (htotal p).trans + rw [count p (fun r => r.isSome) (by simp)] + simpa only [selected, filter_filter, and_comm] using + Nat.add_le_add_left (Nat.mul_le_mul_left b bins) (selected.filter fun e => src e = p).card + have all := sum_le_sum (s := univ) (fun p _ => each p) + rw [sum_add_distrib, count_all selected src, sum_const, card_univ, Nat.nsmul_eq_mul, + mul_comm (Fintype.card P)] at all + exact all + +omit [Fintype P] in +open scoped Classical in +private theorem color_counts (p : P) (c : Color h) : + min (∑ x, if thick c x then 0 else units src ix p x) + (∑ x, if thick c x then units src ix p x else 0) = + min (univ.filter fun e => src e = p ∧ ¬thick c (ix e)).card + (univ.filter fun e => src e = p ∧ thick c (ix e)).card := by + apply congrArg₂ min + · simpa only [ite_not, units, out, filter_filter] using + count_if (out src p) ix (fun x => ¬thick c x) + · simpa only [units, out, filter_filter] using count_if (out src p) ix (thick c) + +open scoped Classical in +/-- The width estimate preserves any property supplied by the matching construction. -/ +theorem subround_of_matching (u B : ℝ) (K : ℕ) (hu : 0 < u) (hB : 0 ≤ B) + (hs : ∀ p x, u * (univ.filter fun e => src e = p ∧ ix e = x).card ≤ B) + (good : Matching src dst ix → Prop) + (make : ∀ (c : Color h) (b : ℕ), + (∀ p x, (univ.filter fun e => src e = p ∧ ix e = x).card ≤ b) → + ∃ m : Matching src dst ix, good m ∧ + (∑ p, min (univ.filter fun e => src e = p ∧ ¬thick c (ix e)).card + (univ.filter fun e => src e = p ∧ thick c (ix e)).card) ≤ + m.count + b * K * Fintype.card P) : + ∃ m : Matching src dst ix, good m ∧ + u * Fintype.card E * (3 / 8) ≤ u * m.count + B * (K + 1) * Fintype.card P := by + let b := ⌊B / u⌋₊ + let w p x := u * (units src ix p x : ℝ) + have hw p x : 0 ≤ w p x ∧ w p x ≤ B := + ⟨mul_nonneg hu.le (Nat.cast_nonneg _), by simpa [w, units, out, filter_filter] using hs p x⟩ + have hb : u * b ≤ B := by + rw [mul_comm, ← le_div_iff₀ hu] + exact Nat.floor_le (div_nonneg hB hu.le) + have hb' p x : units src ix p x ≤ b := + Nat.le_floor ((le_div_iff₀ hu).mpr (by simpa only [mul_comm, w] using (hw p x).2)) + have htotal : (∑ p, ∑ x, w p x) = u * Fintype.card E := by + have h p : ∑ x, units src ix p x = (out src p).card := count_all _ _ + simp only [w, ← mul_sum, ← Nat.cast_sum, h, out] + exact congrArg (fun n : ℕ => u * (n : ℝ)) (count_all univ src) + obtain ⟨c, hc⟩ := coloring w B hw + obtain ⟨m, hg, hm⟩ := make c b (by simpa only [units, out, filter_filter] using hb') + simp_rw [← color_counts] at hm + let err p := ∑ x, if thick c x then w p x else -w p x + let left p := ∑ x, if thick c x then 0 else units src ix p x + let right p := ∑ x, if thick c x then units src ix p x else 0 + have he p : ∑ x, w p x ≤ 2 * u * (min (left p) (right p) : ℕ) + |err p| := by + have hh p : (∑ x, w p x) + err p = 2 * u * right p := by + simp only [err, right, Nat.cast_sum, ← sum_add_distrib, mul_sum] + apply sum_congr rfl + intro x _ + by_cases h : thick c x <;> simp [w, h] + ring + have hl p : (∑ x, w p x) - err p = 2 * u * left p := by + simp only [err, left, Nat.cast_sum, ← sum_sub_distrib, mul_sum] + apply sum_congr rfl + intro x _ + by_cases h : thick c x <;> simp [w, h] + ring + rcases le_total (left p) (right p) with h | h + · rw [min_eq_left h, ← hl] + linarith only [le_abs_self (err p)] + · rw [min_eq_right h, ← hh] + linarith only [neg_le_abs (err p)] + have he' := sum_le_sum (s := univ) fun p _ => he p + rw [htotal, sum_add_distrib, ← mul_sum, ← Nat.cast_sum] at he' + have hm' : ((∑ p, min (left p) (right p) : ℕ) : ℝ) ≤ + m.count + (b : ℝ) * K * Fintype.card P := by exact_mod_cast hm + have h' : (∑ p, |err p|) ≤ u * Fintype.card E / 4 + B * Fintype.card P := by + rw [htotal] at hc + change (∑ p, |err p|) ^ 2 ≤ _ at hc + apply le_of_sq_le_sq _ (by positivity) + nlinarith only [hc, sq_nonneg (u * Fintype.card E / 4 - B * Fintype.card P)] + refine ⟨m, hg, ?_⟩ + linarith only [he', h', mul_le_mul_of_nonneg_left hm' hu.le, + mul_le_mul_of_nonneg_right hb (show 0 ≤ (K : ℝ) * Fintype.card P by positivity), + show 0 ≤ B * Fintype.card P by positivity] + +open scoped Classical in +/-- Width bound with the imbalance absorbed by Young's inequality. +Here `E` indexes bundles of common positive width `u`. -/ +theorem subround (u B : ℝ) (K : ℕ) (hu : 0 < u) (hB : 0 ≤ B) + (hs : ∀ p x, u * (univ.filter fun e => src e = p ∧ ix e = x).card ≤ B) + (hd : ∀ p, ((univ.filter fun e => src e = p).image dst).card ≤ K) : + ∃ m : Matching src dst ix, + u * Fintype.card E * (3 / 8) ≤ u * m.count + B * (K + 1) * Fintype.card P := by + obtain ⟨m, _, hm⟩ := subround_of_matching src dst ix u B K hu hB hs (fun _ => True) (by + intro c b hb + obtain ⟨m, hm⟩ := match_color src dst ix b K c (by simpa only [units, out, filter_filter] + using hb) hd + simp_rw [color_counts] at hm + exact ⟨m, trivial, hm⟩) + exact ⟨m, hm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Common host for dyadic groups -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +open scoped Classical in +/-- Indexes the site by the coordinates of `V × (Σ d : Fin (h + 1), Cell d.val)`. -/ +abbrev Site (V : Type) (h : ℕ) := V × (Σ d : Fin (h + 1), Cell d.val) + +variable {V : Type} {h : ℕ} + +namespace Site + +open scoped Classical in +/-- Uses `p.2.1.val` as the representation. -/ +def depth (p : Site V h) := p.2.1.val + +open scoped Classical in +theorem depth_le (p : Site V h) : p.depth ≤ h := Nat.lt_succ_iff.mp p.2.1.isLt + +open scoped Classical in +/-- Requires `ancestor p.depth_le x = p.2.2`. -/ +def contains (p : Site V h) (x : Cell h) : Prop := ancestor p.depth_le x = p.2.2 + +end Site + +variable [Fintype V] + +open scoped Classical in +/-- Host contacts depend only on the original adjacency and depth limit, +independently of the chosen group, matching and contraction layout. -/ +def near (N : V → Finset V) (D : ℕ) (p : Site V h) : Finset (Site V h) := + insert p (univ.filter fun q => + q.1 ∈ N p.1 ∧ (∃ x, p.contains x ∧ q.contains x) ∧ + p.depth ≤ q.depth + 64 * Nat.clog 2 (2 * D) ∧ + q.depth ≤ p.depth + 64 * Nat.clog 2 (2 * D)) + +open scoped Classical in +theorem mem_near (N : V → Finset V) (D : ℕ) (p q : Site V h) : + q ∈ near N D p ↔ q = p ∨ + q.1 ∈ N p.1 ∧ (∃ x, p.contains x ∧ q.contains x) ∧ + p.depth ≤ q.depth + 64 * Nat.clog 2 (2 * D) ∧ + q.depth ≤ p.depth + 64 * Nat.clog 2 (2 * D) := by simp [near] + +open scoped Classical in +@[simp] theorem near_self (N : V → Finset V) (D : ℕ) (p : Site V h) : + p ∈ near N D p := (mem_near _ _ _ _).mpr (.inl rfl) + +open scoped Classical in +theorem near_symm {N : V → Finset V} (sym : ∀ v u, u ∈ N v → v ∈ N u) + (D : ℕ) (p q : Site V h) (hq : q ∈ near N D p) : p ∈ near N D q := by + rw [mem_near] at hq ⊢ + rcases hq with rfl | ⟨hn, ⟨x, hp, hq⟩, h₁, h₂⟩ + · exact .inl rfl + · exact .inr ⟨sym _ _ hn, ⟨x, hq, hp⟩, h₂, h₁⟩ + +open scoped Classical in +theorem near_mono {C N : V → Finset V} (sub : ∀ v, C v ⊆ N v) + {Δ D : ℕ} (hle : Δ ≤ D) (p : Site V h) : near C Δ p ⊆ near N D p := by + intro q hq + rw [mem_near] at hq ⊢ + rcases hq with rfl | ⟨hn, hp, h₁, h₂⟩ + · exact .inl rfl + · have hm := Nat.clog_mono_right 2 (Nat.mul_le_mul_left 2 hle) + exact .inr ⟨sub _ hn, hp, by omega, by omega⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Size and degree of the common dyadic host + +An overlapping interval at depth within `s` of a fixed site is determined +by its depth and at most `s` additional prefix bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +open scoped Classical in +theorem Site.card (V : Type) [Fintype V] (h : ℕ) : + Fintype.card (Site V h) ≤ 2 * 2 ^ h * Fintype.card V := by + have H (n : ℕ) : (∑ i : Fin n, 2 ^ i.val) < 2 ^ n := by + induction n with + | zero => simp + | succ n ih => + rw [Fin.sum_univ_castSucc, pow_succ] + simp only [Fin.val_castSucc, Fin.val_last] + omega + rw [Fintype.card_prod, Fintype.card_sigma, mul_comm (Fintype.card V)] + simp_rw [card_cell] + apply Nat.mul_le_mul_right + simpa only [pow_succ'] using (H (h + 1)).le + +variable {V : Type} [Fintype V] {h : ℕ} + +open scoped Classical in +private theorem near_card_raw (N : V → Finset V) (D : ℕ) (p : Site V h) : + let s := 64 * Nat.clog 2 (2 * D) + (near N D p).card ≤ ((N p.1).card + 1) * ((2 * s + 1) * 2 ^ s) := by + intro s + have facts (q : Site V h) (hq : q ∈ near N D p) : + q.1 ∈ insert p.1 (N p.1) ∧ p.depth ≤ q.depth + s ∧ q.depth ≤ p.depth + s ∧ + ∀ (i : Fin q.depth) (hi : i.val < p.depth), q.2.2 i = p.2.2 ⟨i.val, hi⟩ := by + rcases (mem_near N D p q).mp hq with rfl | ⟨hn, ⟨x, hp, hq⟩, h₁, h₂⟩ + · exact ⟨mem_insert_self _ _, by omega, by omega, fun _ _ => rfl⟩ + · exact ⟨mem_insert_of_mem hn, h₁, h₂, fun i hi => + (congrFun hq i).symm.trans (congrFun hp ⟨i.val, hi⟩)⟩ + let extra (q : Site V h) : Cell s := fun i => + if hi : p.depth + i.val < q.depth then q.2.2 ⟨p.depth + i.val, hi⟩ else 0 + let code (q : near N D p) : ↥(insert p.1 (N p.1)) × Fin (2 * s + 1) × Cell s := + (⟨q.val.1, (facts _ q.property).1⟩, ⟨q.val.depth + s - p.depth, by + have := (facts _ q.property).2.2.1 + omega⟩, extra q.val) + have inj : Function.Injective code := by + rintro ⟨⟨v, d, a⟩, ha⟩ ⟨⟨w, e, b⟩, hb⟩ he + have hv : v = w := congrArg (fun z => z.1.val) he + subst w + obtain ⟨_, ha₁, ha₂, ha₃⟩ := facts _ ha + obtain ⟨_, hb₁, _, hb₃⟩ := facts _ hb + change p.depth ≤ d.val + s at ha₁ + change p.depth ≤ e.val + s at hb₁ + change d.val ≤ p.depth + s at ha₂ + have hval : d.val + s - p.depth = e.val + s - p.depth := + congrArg (fun z => z.2.1.val) he + have heq : d = e := Fin.ext (by omega) + subst e + have hx : extra (v, ⟨d, a⟩) = extra (v, ⟨d, b⟩) := congrArg (fun z => z.2.2) he + have hab : a = b := by + funext i + by_cases hi : i.val < p.depth + · exact (ha₃ i hi).trans (hb₃ i hi).symm + · have hj : p.depth + (i.val - p.depth) = i.val := by omega + have hz := congrFun hx ⟨i.val - p.depth, by omega⟩ + unfold Site.depth at hj + simpa [extra, Site.depth, hj, i.isLt] using hz + subst b + rfl + have H := Fintype.card_le_of_injective code inj + simp only [Fintype.card_coe, Fintype.card_prod, Fintype.card_fin, card_cell] at H + exact H.trans (Nat.mul_le_mul_right _ (card_insert_le _ _)) + +open scoped Classical in +theorem near_card (N : V → Finset V) (D : ℕ) (hD : 0 < D) + (deg : ∀ v, (N v).card ≤ D) (p : Site V h) : + (near N D p).card ≤ (4 * D) ^ 300 := by + let n := Nat.clog 2 (2 * D) + let s := 64 * n + have hn : 1 ≤ n := Nat.clog_pos (by decide) (by omega) + have hpred : 2 ^ (n - 1) < 2 * D := Nat.pow_pred_clog_lt_self 2 (by omega) + have hpow : 2 ^ n ≤ 4 * D := by + rw [← Nat.sub_add_cancel hn, pow_succ] + omega + have hextra : 2 ^ s ≤ (4 * D) ^ 64 := by + rw [show s = n * 64 by exact Nat.mul_comm _ _, pow_mul] + exact Nat.pow_le_pow_left hpow _ + have hdepth : 2 * s + 1 ≤ (4 * D) ^ 128 := calc + _ ≤ 2 ^ (2 * s) := Nat.lt_pow_self (by decide) + _ = (2 ^ s) ^ 2 := by rw [Nat.mul_comm 2 s, pow_mul] + _ ≤ ((4 * D) ^ 64) ^ 2 := Nat.pow_le_pow_left hextra _ + _ = _ := by rw [← pow_mul] + have hbase : (N p.1).card + 1 ≤ 4 * D := by have := deg p.1; omega + calc + _ ≤ ((N p.1).card + 1) * ((2 * s + 1) * 2 ^ s) := near_card_raw N D p + _ ≤ 4 * D * ((4 * D) ^ 128 * (4 * D) ^ 64) := Nat.mul_le_mul hbase (Nat.mul_le_mul hdepth + hextra) + _ = (4 * D) ^ 193 := by rw [← pow_add, ← pow_succ'] + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +section +/- +# Relative addresses inside a group + +Forgetting a common prefix commutes with taking the endpoint of a contact. +The relative address and either absolute endpoint recover the whole address. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +variable {h : ℕ} {V A : Type} + +/-- Evaluates `x ⟨a + i, by have := i.isLt; omega⟩` at the input `i`. -/ +def suffix (a : ℕ) (x : Cell h) : Cell (h - a) := + fun i => x ⟨a + i, by have := i.isLt; omega⟩ + +/-- The quantity computed by `(p.1, ⟨⟨p.depth - a, by have := p.depth_le; omega⟩, suffix a +p.2.2⟩)`. -/ +def Site.drop (a : ℕ) (p : Site V h) : Site V (h - a) := + (p.1, ⟨⟨p.depth - a, by have := p.depth_le; omega⟩, suffix a p.2.2⟩) + +/-- The quantity computed by `base v - a`. -/ +def relBase (a : ℕ) (base : V → ℕ) (v : V) := base v - a + +theorem relHi (a : ℕ) {base : V → ℕ} (hb : ∀ v, base v ≤ h) (v : V) : + relBase a base v ≤ h - a := Nat.sub_le_sub_right (hb v) a + +theorem relDepth (a : ℕ) (base : V → ℕ) (ends : A → Bool → V) (c : A) : + contactDepth (relBase a base) ends c = contactDepth base ends c - a := by + unfold contactDepth relBase + omega + +variable {base : V → ℕ} {ends : A → Bool → V} + +/-- Uses `⟨z.1, fun i => suffix a z.2 (Fin.cast (relDepth a base ends z.1) i)⟩` as the +representation. -/ +def dropContact (a : ℕ) (z : Σ c, Cell (contactDepth base ends c)) : + Σ c, Cell (contactDepth (relBase a base) ends c) := + ⟨z.1, fun i => suffix a z.2 (Fin.cast (relDepth a base ends z.1) i)⟩ + +theorem dropContact_inj (a : ℕ) (lo : ∀ v, a ≤ base v) (t : Bool) + {x y : Σ c, Cell (contactDepth base ends c)} + (hr : dropContact a x = dropContact a y) + (he : contactEnd base ends x t = contactEnd base ends y t) : x = y := by + rcases x with ⟨b, x⟩ + rcases y with ⟨c, y⟩ + have eq : b = c := congrArg Sigma.fst hr + subst c + have hs := eq_of_heq (Sigma.mk.inj hr).2 + have hp := eq_of_heq (Sigma.mk.inj he).2 + congr 1 + funext i + by_cases hi : i.val < a + · exact congrFun hp ⟨i, hi.trans_le (lo _)⟩ + · have hd : i.val - a < contactDepth (relBase a base) ends b := by rw [relDepth]; omega + have ht := congrFun hs ⟨i.val - a, hd⟩ + simpa [suffix, Nat.add_sub_of_le (Nat.le_of_not_gt hi)] using ht + +theorem Site.drop_contains {p : Site V h} {x : Cell h} (a : ℕ) (hx : p.contains x) : + (p.drop a).contains (suffix a x) := + congrArg (suffix a) hx + +theorem drop_near [Fintype V] {N : V → Finset V} {D : ℕ} {p q : Site V h} + (a : ℕ) (hp : q ∈ near N D p) : q.drop a ∈ near N D (p.drop a) := by + rw [mem_near] at hp ⊢ + rcases hp with rfl | ⟨hn, ⟨x, hx, hy⟩, hp, hq⟩ + · exact .inl rfl + · have hd (s : Site V h) : (s.drop a).depth = s.depth - a := rfl + exact .inr ⟨hn, ⟨_, Site.drop_contains a hx, Site.drop_contains a hy⟩, + by rw [hd, hd]; omega, by rw [hd, hd]; omega⟩ + +theorem Site.drop_injective {p q : Site V h} (a : ℕ) (hp : a ≤ p.depth) (hq : a ≤ q.depth) + (e : ancestor hp p.2.2 = ancestor hq q.2.2) (hh : p.drop a = q.drop a) : p = q := by + have hv : p.1 = q.1 := congrArg (fun z : Site V (h - a) => z.1) hh + have hd : p.depth - a = q.depth - a := congrArg (fun z : Site V (h - a) => z.depth) hh + have hd' : p.depth = q.depth := by omega + obtain ⟨v, ⟨i, x⟩⟩ := p + obtain ⟨w, ⟨j, y⟩⟩ := q + have h₁ : v = w := hv + have h₂ : i = j := Fin.ext hd' + subst w j + have hs : suffix a x = suffix a y := eq_of_heq (Sigma.mk.inj (congrArg Prod.snd hh)).2 + suffices x = y by subst y; rfl + funext k + by_cases hk : k.val < a + · exact congrFun e ⟨k, hk⟩ + · have ht := congrFun hs ⟨k.val - a, by have := k.isLt; omega⟩ + simpa [suffix, Nat.add_sub_of_le (Nat.le_of_not_gt hk)] using ht + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Data and bounds for a dyadic grouping of blocks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {V : Type} [Fintype V] {h : ℕ} + +open scoped Classical in +/-- The bound on the number of core destinations per colony. -/ +def coreBins (Δ : ℕ) := Δ * 2 ^ (64 * Nat.clog 2 (2 * Δ)) + +open scoped Classical in +/-- The data for the grouping construction, including `π`, `parts`, `label`, `total`, `mem`. -/ +structure Grouping (N C : V → Finset V) (Δ D k : ℕ) (B : ℝ) (l : V → Cell h → ℝ) where + /-- Reindexes the data using `Cell h ≃ₗ[ZMod 2] Cell h`. -/ + π : Cell h ≃ₗ[ZMod 2] Cell h + /-- The `Grouping` component of type `V → Finset (Σ i, Cell i)`. -/ + parts : V → Finset (Σ i, Cell i) + /-- The label at each coordinate of type `V → Cell h → Σ i, Cell i`. -/ + label : V → Cell h → Σ i, Cell i + total : (∑ v, ((parts v).card : ℝ)) ≤ + Fintype.card V + 16 * (∑ v, ∑ x, l v x) / ((2 : ℝ) ^ k * B) + mem : ∀ v x, label v x ∈ parts v + part : ∀ v c, c ∈ parts v → + c.1 ≤ h - k ∧ (∃ hi : c.1 ≤ h, ∀ x, label v x = c ↔ ancestor hi (π x) = c.2) ∧ + 2 ^ k ≤ (univ.filter fun x => label v x = c).card ∧ + (∑ x, if label v x = c then l v x else 0) ≤ (2 : ℝ) ^ k * B + edge : ∀ v u, u ∈ N v → ∀ x, (label u x).1 ≤ (label v x).1 + + 64 * Nat.clog 2 (2 * if u ∈ C v then Δ else D) + bins : ∀ v c, c ∈ parts v → + (∑ u ∈ C v, ((univ.filter fun x => label v x = c).image (label u)).card) ≤ coreBins Δ + +namespace Grouping +variable {N C : V → Finset V} {Δ D k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) + +open scoped Classical in +/-- Indexes the colony by the coordinates of `Σ v, ↥(g.parts v)`. -/ +abbrev Colony := Σ v, ↥(g.parts v) + +open scoped Classical in +/-- Uses `⟨v, g.label v x, g.mem v x⟩` as the representation. -/ +def loc (v : V) (x : Cell h) : g.Colony := ⟨v, g.label v x, g.mem v x⟩ + +open scoped Classical in +/-- Computes the ends by the application `g.loc (src e) (ix e)`. -/ +def ends {E : Type} (src : E → V) (ix : E → Cell h) (e : E) : g.Colony := + g.loc (src e) (ix e) + +end Grouping +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# The two subround contractions on old occurrences + +Row contraction sends each occurrence to its own colony. Column contraction +moves precisely the matched thin source occurrences to the thick destination. +A whole occurrence has the same destination for all its outgoing units. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {E P V : Type} [Fintype V] {h : ℕ} + +open scoped Classical in +/-- The subtype of `e` satisfying `(m.plan (src e) (ix e)).isSome`. -/ +abbrev Matching.items {src dst : E → P} {ix : E → Cell h} (m : Matching src dst ix) := + {e // (m.plan (src e) (ix e)).isSome} + +namespace Grouping + +variable {N C : V → Finset V} {Δ D k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) + +open scoped Classical in +/-- The value specified by `(p.1, ⟨⟨p.2.val.1, by have := (g.part p.1 p.2.val p.2.property).1; +omega⟩, p.2.val.2⟩)`. -/ +def site (p : g.Colony) : Site V h := + (p.1, ⟨⟨p.2.val.1, by have := (g.part p.1 p.2.val p.2.property).1; omega⟩, p.2.val.2⟩) + +open scoped Classical in +theorem site_injective : Function.Injective g.site := by + rintro ⟨v, p⟩ ⟨w, q⟩ he + have : v = w := congrArg Prod.fst he + subst w + have : p.val = q.val := congrArg + (fun z : Site V h => (⟨z.2.1.val, z.2.2⟩ : Σ i, Cell i)) he + rw [Subtype.ext this] + +open scoped Classical in +/-- Computes the here by the application `g.site (g.loc v x)`. -/ +def here (v : V) (x : Cell h) := g.site (g.loc v x) + +open scoped Classical in +theorem here_contains (v : V) (x : Cell h) : (g.here v x).contains (g.π x) := by + obtain ⟨_, he⟩ := (g.part _ _ (g.mem v x)).2.1 + exact (he x).mp rfl + +open scoped Classical in +theorem here_core (cs : ∀ v w, w ∈ C v → v ∈ C w) (sub : ∀ v, C v ⊆ N v) + {v w : V} (hw : w ∈ C v) (x : Cell h) : g.here w x ∈ near C Δ (g.here v x) := by + have hv := cs _ _ hw + refine (mem_near _ _ _ _).mpr (.inr ⟨hw, ⟨_, g.here_contains v x, g.here_contains w x⟩, + ?_, ?_⟩) + · simpa only [ite_eq_left hv, here, site, loc, Site.depth] using g.edge w v (sub w hv) x + · simpa only [ite_eq_left hw, here, site, loc, Site.depth] using g.edge v w (sub v hw) x + +open scoped Classical in +theorem here_full (ns : ∀ v w, w ∈ N v → v ∈ N w) (le : Δ ≤ D) + {v w : V} (hw : w ∈ N v) (x : Cell h) : g.here w x ∈ near N D (g.here v x) := by + have edge (v w : V) (hw : w ∈ N v) : + (g.here w x).depth ≤ (g.here v x).depth + 64 * Nat.clog 2 (2 * D) := by + refine (g.edge v w hw x).trans (Nat.add_le_add_left (Nat.mul_le_mul_left _ ?_) _) + apply Nat.clog_mono_right + split_ifs <;> omega + exact (mem_near _ _ _ _).mpr (.inr ⟨hw, ⟨_, g.here_contains v x, g.here_contains w x⟩, + edge _ _ (ns _ _ hw), edge _ _ hw⟩) + +variable {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + +open scoped Classical in +/-- Returns `g.site ((m.plan (g.loc v x) x).getD (g.loc v x))` when `col` holds, and `g.here v +x` otherwise. -/ +def route (col : Bool) (v : V) (x : Cell h) : Site V h := + if col then g.site ((m.plan (g.loc v x) x).getD (g.loc v x)) else g.here v x + +open scoped Classical in +theorem route_thick (col : Bool) (v : V) (x : Cell h) (hx : thick m.color x) : + g.route m col v x = g.here v x := by + cases hp : m.plan (g.loc v x) x with + | none => simp [route, hp, here] + | some _ => exact (m.thin (g.loc v x) x (by simp [hp]) hx).elim + +open scoped Classical in +theorem route_thin (col : Bool) (e : m.items) : + g.route m col (src e.val) (ix e.val) = + if col then g.here (dst (m.mate e)) (ix (m.mate e)) + else g.here (src (m.mate e)) (ix (m.mate e)) := by + obtain ⟨_, hs, ht⟩ := m.spec e + cases col + · exact congrArg g.site hs.symm + · change g.site ((m.plan (g.ends src ix e.val) (ix e.val)).getD _) = _ + rw [ht] + rfl + +open scoped Classical in +/-- Only a source of core units can move, and it moves by at most one core hop. -/ +theorem route_cases (col : Bool) (v : V) (x : Cell h) : + g.route m col v x = g.here v x ∨ + ∃ e : m.items, src e.val = v ∧ ix e.val = x ∧ + g.here (src (m.mate e)) (ix (m.mate e)) = g.here v x ∧ + g.route m col v x = g.here (dst (m.mate e)) (ix (m.mate e)) := by + cases col + · exact .inl rfl + cases hp : m.plan (g.loc v x) x with + | none => exact .inl (by simp [route, hp, here]) + | some p => + have hh : (m.plan (g.loc v x) x).isSome := by simp [hp] + obtain ⟨e, he, hi⟩ := m.used _ _ hh + have hs : src e = v := congrArg Sigma.fst he + let i : m.items := ⟨e, by rw [he, hi]; exact hh⟩ + exact .inr ⟨i, hs, hi, congrArg g.site ((m.spec i).2.1.trans he), + by simpa [i, hs, hi] using g.route_thin m true i⟩ + +open scoped Classical in +theorem route_near (cs : ∀ v w, w ∈ C v → v ∈ C w) (sub : ∀ v, C v ⊆ N v) + (hedge : ∀ e, dst e ∈ C (src e)) (col : Bool) (v : V) (x : Cell h) : + g.route m col v x ∈ near C Δ (g.here v x) := by + rcases g.route_cases m col v x with he | ⟨e, _, _, hs, ht⟩ + · rw [he]; exact near_self _ _ _ + · rw [ht, ← hs]; exact g.here_core cs sub (hedge _) _ + +end Grouping +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- # Load of a site after row or column contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Grouping +open Finset + +variable {E V : Type} [Fintype V] {h : ℕ} + {N C : V → Finset V} {Δ D k : ℕ} {B : ℝ} {l : V → Cell h → ℝ} + (g : Grouping N C Δ D k B l) + +open scoped Classical in +theorem here_load (hB : 0 ≤ B) (z : Site V h) : + (∑ t : V × Cell h, if g.here t.1 t.2 = z then l t.1 t.2 else 0) ≤ (2 : ℝ) ^ k * B := by + by_cases hz : ∃ p, g.site p = z + · obtain ⟨⟨v, c, hc⟩, rfl⟩ := hz + rw [Fintype.sum_prod_type, Fintype.sum_eq_single v] + · have eq (x : Cell h) : g.here v x = g.site ⟨v, c, hc⟩ ↔ g.label v x = c := by + simp [here, g.site_injective.eq_iff, loc] + simp_rw [eq] + exact (g.part v c hc).2.2.2 + · intro w hw + apply sum_eq_zero + intro x _ + exact ite_eq_right (fun he => hw (congrArg Prod.fst he)) + · have hn (t : V × Cell h) : g.here t.1 t.2 ≠ z := fun he => hz ⟨g.loc _ _, he⟩ + simp_rw [ite_eq_right (hn _), sum_const_zero] + exact mul_nonneg (by positivity) hB + +variable {src dst : E → V} {ix : E → Cell h} + (m : Matching (g.ends src ix) (g.ends dst ix) ix) + +open scoped Classical in +/-- Each nearby colony contributes at most one full colony load. -/ +theorem route_load (cs : ∀ v w, w ∈ C v → v ∈ C w) (sub : ∀ v, C v ⊆ N v) + (hedge : ∀ e, dst e ∈ C (src e)) (hl : ∀ v x, 0 ≤ l v x) (hB : 0 ≤ B) + (col : Bool) (z : Site V h) : + (∑ t : V × Cell h, if g.route m col t.1 t.2 = z then l t.1 t.2 else 0) ≤ + (near C Δ z).card * ((2 : ℝ) ^ k * B) := by + calc + _ ≤ ∑ t : V × Cell h, ∑ a ∈ near C Δ z, if g.here t.1 t.2 = a then l t.1 t.2 else 0 := by + apply sum_le_sum + intro t _ + rw [sum_ite_eq] + by_cases he : g.route m col t.1 t.2 = z + · have hn := near_symm cs Δ _ _ (g.route_near m cs sub hedge col t.1 t.2) + rw [he] at hn + rw [ite_eq_left he, ite_eq_left hn] + · rw [ite_eq_right he] + split_ifs + · exact hl _ _ + · exact le_rfl + _ ≤ ∑ _a ∈ near C Δ z, (2 : ℝ) ^ k * B := by + rw [sum_comm] + exact sum_le_sum fun a _ => g.here_load hB a + _ = _ := by rw [sum_const, nsmul_eq_mul] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Grouping +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/TetherHost.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/TetherHost.lean new file mode 100644 index 0000000000..3b6b5d9f5c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Packing/TetherHost.lean @@ -0,0 +1,1053 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Nat.Log +public import Mathlib.Data.Fintype.Card +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Fintype.Prod +public import Mathlib.Data.Fintype.Sum +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Reservations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rule +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Present +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Delivery + +/-! +# Balanced binary trees gathering a fixed set of ports + +Heap position zero is unused. The root has room for an outside +connection and each leaf can connect to a port. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Tree +open Finset + +/-- The quantity computed by `Fin (2 ^ (Nat.clog 2 w + 1))`. -/ +abbrev Node (w : ℕ) := Fin (2 ^ (Nat.clog 2 w + 1)) + +variable {w : ℕ} + +/-- Uses `⟨1, by have := Nat.one_le_pow (Nat.clog 2 w) 2 (by decide) rw [Nat.pow_succ]; omega⟩` +as the representation. -/ +def root (w : ℕ) : Node w := ⟨1, by + have := Nat.one_le_pow (Nat.clog 2 w) 2 (by decide) + rw [Nat.pow_succ]; omega⟩ + +/-- The value specified by `⟨2 ^ Nat.clog 2 w + j.val, by have := Nat.le_pow_clog (by decide : 1 +< 2) w rw [Nat.pow_succ]; omega⟩`. -/ +def tip (j : Fin w) : Node w := ⟨2 ^ Nat.clog 2 w + j.val, by + have := Nat.le_pow_clog (by decide : 1 < 2) w + rw [Nat.pow_succ]; omega⟩ + +theorem tip_injective : Function.Injective (tip (w := w)) := by + intro i j h + exact Fin.ext (Nat.add_left_cancel (congrArg Fin.val h)) + +theorem size (hw : 0 < w) : Fintype.card (Node w) ≤ 4 * w := by + rw [Fintype.card_fin] + by_cases he : w = 1 + · subst w; decide + have h := Nat.pow_pred_clog_lt_self 2 (by omega : 1 < w) + rw [Nat.pred_eq_sub_one] at h + have hp := Nat.clog_pos (by decide : 1 < 2) (by omega : 1 < w) + rw [show Nat.clog 2 w + 1 = (Nat.clog 2 w - 1) + 1 + 1 by omega, Nat.pow_succ, Nat.pow_succ] + omega + +/-- The quantity computed by `⟨(tip j).val / 2 ^ k, (Nat.div_le_self _ _).trans_lt (tip +j).isLt⟩`. -/ +def climb (j : Fin w) (k : ℕ) : Node w := + ⟨(tip j).val / 2 ^ k, (Nat.div_le_self _ _).trans_lt (tip j).isLt⟩ + +@[simp] theorem climb_zero (j : Fin w) : climb j 0 = tip j := by ext; simp [climb] + +@[simp] theorem climb_top (j : Fin w) : climb j (Nat.clog 2 w) = root w := by + apply Fin.ext + have h := Nat.le_pow_clog (by decide : 1 < 2) w + unfold climb tip root + simp only + exact Nat.div_eq_of_lt_le (by omega) (by omega) + +private theorem climb_step (j : Fin w) (k : ℕ) : + (climb j (k + 1)).val = (climb j k).val / 2 := by + simp only [climb, Nat.pow_succ, Nat.div_div_eq_div_mul] + +private theorem below (j : Fin w) {k : ℕ} (hk : k < Nat.clog 2 w) : 1 < (climb j k).val := by + have h := Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.succ_le_of_lt hk) + rw [Nat.pow_succ] at h + apply (Nat.le_div_iff_mul_le (Nat.pow_pos (by decide : 0 < 2))).mpr + simp only [tip] + omega + +theorem climb_injective (j : Fin w) : + Function.Injective (fun k : Fin (Nat.clog 2 w + 1) => climb j k.val) := by + apply StrictAnti.injective + intro a b hab + have hh := below j (by omega : a.val < Nat.clog 2 w) + change (climb j b.val).val < (climb j a.val).val + refine lt_of_le_of_lt (b := (climb j (a.val + 1)).val) ?_ ?_ + · exact Nat.div_le_div_left (Nat.pow_le_pow_right (by decide) (by omega)) (Nat.pow_pos (by + decide)) + · rw [climb_step]; omega + +/-- Selects the elements of all indices satisfying `fun q => (1 < p.val ∧ q.val = p.val / 2) ∨ +(1 < q.val ∧ p.val = q.val / 2)`. -/ +def adj (p : Node w) : Finset (Node w) := univ.filter fun q => + (1 < p.val ∧ q.val = p.val / 2) ∨ (1 < q.val ∧ p.val = q.val / 2) + +theorem adj_symm {p q : Node w} (hq : q ∈ adj p) : p ∈ adj q := by + simpa only [adj, mem_filter, mem_univ, true_and, or_comm] using hq + +theorem climb_adj (j : Fin w) {k : ℕ} (hk : k < Nat.clog 2 w) : + climb j (k + 1) ∈ adj (climb j k) := by + exact mem_filter.mpr ⟨mem_univ _, .inl ⟨below j hk, climb_step j k⟩⟩ + +theorem degree (p : Node w) : + (adj p).card + (if p = root w then 1 else 0) + + (if 2 ^ Nat.clog 2 w ≤ p.val then 1 else 0) ≤ 3 := by + let parents : Finset ℕ := if p = root w then ∅ else {p.val / 2} + let children : Finset ℕ := if 2 ^ Nat.clog 2 w ≤ p.val then ∅ else {2 * p.val, 2 * p.val + 1} + have sub : (adj p).image Fin.val ⊆ parents ∪ children := by + rintro _ h + obtain ⟨q, hq, rfl⟩ := mem_image.mp h + rcases (mem_filter.mp hq).2 with ⟨hp, he⟩ | ⟨_, he⟩ + · have hn : p ≠ root w := by intro e; simp [e, root] at hp + exact mem_union_left _ (by simp [parents, hn, he]) + · have hb : q.val < 2 ^ Nat.clog 2 w * 2 := q.isLt + have hn : ¬2 ^ Nat.clog 2 w ≤ p.val := by omega + apply mem_union_right + simp only [children, ite_eq_right hn, mem_insert, mem_singleton] + omega + have hc := (card_le_card sub).trans (card_union_le parents children) + rw [card_image_of_injective _ Fin.val_injective] at hc + unfold parents children at hc + have hb : ({2 * p.val, 2 * p.val + 1} : Finset ℕ).card ≤ 2 := card_le_two + split_ifs at hc ⊢ <;> simp only [card_empty, card_singleton] at hc <;> omega + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Tree +end + +/- # A fixed contact tree at each terminal -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Detour +open Finset + +open scoped Classical in +/-- Indexes the hub by the coordinates of `X ⊕ (X × Tree.Node w)`. -/ +abbrev Hub (X : Type) (w : ℕ) := X ⊕ (X × Tree.Node w) + +open scoped Classical in +/-- The data for the switch construction, including `near`, `sym`, `pin`. -/ +structure Switch (X : Type) (w : ℕ) where + /-- The `Switch` component of type `X → Finset X`. -/ + near : X → Finset X + sym : ∀ x y, y ∈ near x → x ∈ near y + /-- Embeds the coordinates as `∀ x, ↥(near x) ↪ Fin w`. -/ + pin : ∀ x, ↥(near x) ↪ Fin w + +variable {X : Type} {w : ℕ} + +open scoped Classical in +/-- Computes the owner by the application `Sum.elim id Prod.fst`. -/ +def owner : Hub X w → X := Sum.elim id Prod.fst + +open scoped Classical in +/-- Builds `Switch X w where near` with the specified `near`, `sym`, `pin`. -/ +def switch (N : X → Finset X) (sym : ∀ x y, y ∈ N x → x ∈ N y) + (deg : ∀ x, (N x).card ≤ w) : Switch X w where + near := N + sym := sym + pin x := Classical.choice (Function.Embedding.nonempty_of_card_le (by simpa using deg x)) + +namespace Switch +variable [Fintype X] (sw : Switch X w) + +open scoped Classical in +/-- The indexed operation `univ.filter fun q => ∃ h : q.1 ∈ sw.near x, Tree.tip (sw.pin x ⟨q.1, +h⟩) = p ∧ Tree.tip (sw.pin q.1 ⟨x, sw.sym _ _ h⟩) = q.2`. -/ +def links (x : X) (p : Tree.Node w) : Finset (X × Tree.Node w) := + univ.filter fun q => ∃ h : q.1 ∈ sw.near x, + Tree.tip (sw.pin x ⟨q.1, h⟩) = p ∧ Tree.tip (sw.pin q.1 ⟨x, sw.sym _ _ h⟩) = q.2 + +open scoped Classical in +private theorem links_card (x : X) (p : Tree.Node w) : + (sw.links x p).card ≤ if 2 ^ Nat.clog 2 w ≤ p.val then 1 else 0 := by + split_ifs with h + · apply card_le_one.mpr + rintro ⟨y, q⟩ hy ⟨z, r⟩ hz + obtain ⟨_, h₁, h₂⟩ := (mem_filter.mp hy).2 + obtain ⟨_, h₃, h₄⟩ := (mem_filter.mp hz).2 + have he : y = z := congrArg Subtype.val ((sw.pin x).injective + (Tree.tip_injective (h₁.trans h₃.symm))) + subst z + exact Prod.ext rfl (h₂.symm.trans h₄) + · apply Nat.le_of_eq + rw [card_eq_zero] + apply eq_empty_iff_forall_notMem.mpr + intro q hq + obtain ⟨_, he, _⟩ := (mem_filter.mp hq).2 + apply h + rw [← he] + exact Nat.le_add_right _ _ + +open scoped Classical in +/-- In the case `.inl x`, this construction gives `{.inr (x, Tree.root w)}`. -/ +def adj : Hub X w → Finset (Hub X w) + | .inl x => {.inr (x, Tree.root w)} + | .inr (x, p) => + ((Tree.adj p).image (fun q => .inr (x, q)) ∪ if p = Tree.root w then {.inl x} else ∅) ∪ + (sw.links x p).image Sum.inr + +open scoped Classical in +@[simp] theorem adj_outer (x : X) : sw.adj (.inl x) = {.inr (x, Tree.root w)} := rfl + +open scoped Classical in +theorem adj_inner (x : X) {p q : Tree.Node w} (h : q ∈ Tree.adj p) : + Sum.inr (x, q) ∈ sw.adj (.inr (x, p)) := + mem_union_left _ (mem_union_left _ (mem_image_of_mem _ h)) + +open scoped Classical in +theorem adj_bridge (x y : X) (h : y ∈ sw.near x) : + Sum.inr (y, Tree.tip (sw.pin y ⟨x, sw.sym _ _ h⟩)) ∈ + sw.adj (.inr (x, Tree.tip (sw.pin x ⟨y, h⟩))) := + mem_union_right _ (mem_image_of_mem _ (mem_filter.mpr ⟨mem_univ _, h, rfl, rfl⟩)) + +open scoped Classical in +theorem adj_symm (p q : Hub X w) (hq : q ∈ sw.adj p) : p ∈ sw.adj q := by + rcases p with x | ⟨x, p⟩ + · have := mem_singleton.mp hq + subst q + simp [adj] + rcases mem_union.mp hq with h | h + · rcases mem_union.mp h with h | h + · obtain ⟨r, hr, rfl⟩ := mem_image.mp h + exact sw.adj_inner x (Tree.adj_symm hr) + · split_ifs at h with hp + · rw [mem_singleton.mp h, hp] + exact mem_singleton_self _ + · simp at h + · obtain ⟨⟨y, r⟩, hy, rfl⟩ := mem_image.mp h + obtain ⟨he, hp, hr⟩ := (mem_filter.mp hy).2 + change Tree.tip _ = r at hr + rw [← hp, ← hr] + exact sw.adj_bridge y x (sw.sym _ _ he) + +open scoped Classical in +theorem adj_degree (p : Hub X w) : (sw.adj p).card ≤ 3 := by + rcases p with x | ⟨x, p⟩ + · simp + refine le_trans ((card_union_le _ _).trans (Nat.add_le_add (card_union_le _ _) card_image_le)) + (le_trans ?_ (Tree.degree p)) + refine Nat.add_le_add (Nat.add_le_add card_image_le ?_) (sw.links_card _ _) + split_ifs <;> simp + +end Switch +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Detour +end + +/- +# Bounded-degree host for tether restoration + +Give each parked frozen member a private splitting tree. Its leaves +are outlets. The outlets and the old core use a common contact switch. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Tether +open Finset + +open scoped Classical in +/-- Indexes the end by the coordinates of `V ⊕ ((V × Fin r) × Tree.Node s)`. -/ +abbrev End (V : Type) (r s : ℕ) := V ⊕ ((V × Fin r) × Tree.Node s) +open scoped Classical in +/-- Computes the host by the application `Detour.Hub (End V r s) w`. -/ +abbrev Host (V : Type) (r s w : ℕ) := Detour.Hub (End V r s) w + +variable {V : Type} {r s w : ℕ} + +open scoped Classical in +/-- The value specified by `.inl (.inl v)`. -/ +def core (v : V) : Host V r s w := .inl (.inl v) +open scoped Classical in +/-- The value specified by `.inl (.inr (x, Tree.root s))`. -/ +def member (x : V × Fin r) : Host V r s w := .inl (.inr (x, Tree.root s)) + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `((N v ×ˢ univ) ×ˢ univ).image Sum.inr`. -/ +def near (N : V → Finset V) (r s : ℕ) : End V r s → Finset (End V r s) + | .inl v => ((N v ×ˢ univ) ×ˢ univ).image Sum.inr + | .inr p => (N p.1.1).image Sum.inl + +open scoped Classical in +theorem near_symm (N : V → Finset V) (hn : ∀ v u, u ∈ N v → v ∈ N u) + (v u : End V r s) (h : u ∈ near N r s v) : v ∈ near N r s u := by + rcases v with v | ⟨⟨v, i⟩, j⟩ <;> rcases u with u | ⟨⟨u, k⟩, l⟩ <;> + first + | solve | simp [near] at h + | simpa [near] using hn _ _ (by simpa [near] using h) + +open scoped Classical in +/-- The quantity computed by `D * (r + 1) * 2 ^ (Nat.clog 2 s + 1)`. -/ +def width (D r s : ℕ) := D * (r + 1) * 2 ^ (Nat.clog 2 s + 1) + +open scoped Classical in +theorem near_card (N : V → Finset V) (D : ℕ) (hd : ∀ v, (N v).card ≤ D) (v : End V r s) : + (near N r s v).card ≤ width D r s := by + cases v with + | inl v => + refine card_image_le.trans ?_ + simp only [card_product, card_univ, Fintype.card_fin, width] + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul (hd v) (Nat.le_succ r)) + | inr v => + refine card_image_le.trans ((hd v.1.1).trans ?_) + exact (Nat.le_mul_of_pos_right _ (Nat.succ_pos _)).trans + (Nat.le_mul_of_pos_right _ (Nat.pow_pos (by decide))) + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `(C v).image Sum.inl`. -/ +def branches (C : V → Finset V) : End V r s → Finset (End V r s) + | .inl v => (C v).image Sum.inl + | .inr (x, p) => (Tree.adj p).image fun q => .inr (x, q) + +open scoped Classical in +private theorem branches_symm (C : V → Finset V) (hs : ∀ v u, u ∈ C v → v ∈ C u) + (v u : End V r s) (he : u ∈ branches C v) : v ∈ branches C u := by + rcases v with v | ⟨x, p⟩ + · obtain ⟨u, hu, rfl⟩ := mem_image.mp he + exact mem_image_of_mem _ (hs _ _ hu) + · obtain ⟨q, hq, rfl⟩ := mem_image.mp he + exact mem_image_of_mem _ (Tree.adj_symm hq) + +variable [Fintype V] (sw : Detour.Switch (End V r s) w) (C : V → Finset V) + +open scoped Classical in +/-- The selected finite family `sw.adj z ∪ match z with | .inl x => (branches C x).image Sum.inl +| .inr _ => ∅`. -/ +def adj (z : Host V r s w) : Finset (Host V r s w) := + sw.adj z ∪ match z with + | .inl x => (branches C x).image Sum.inl + | .inr _ => ∅ + +open scoped Classical in +theorem adj_symm (hs : ∀ v u, u ∈ C v → v ∈ C u) (z z' : Host V r s w) + (h : z' ∈ adj sw C z) : z ∈ adj sw C z' := by + rcases mem_union.mp h with h | h + · exact mem_union_left _ (sw.adj_symm _ _ h) + cases z with + | inr _ => simp at h + | inl x => + obtain ⟨y, hy, rfl⟩ := mem_image.mp h + exact mem_union_right _ (mem_image_of_mem _ (branches_symm C hs _ _ hy)) + +open scoped Classical in +theorem adj_degree (hC : ∀ v, (C v).card ≤ 3) (z : Host V r s w) : + (adj sw C z).card ≤ 4 := by + cases z with + | inr v => + simpa only [adj, union_empty] using (sw.adj_degree (.inr v)).trans (by decide : 3 ≤ 4) + | inl x => + have h : (branches C x).card ≤ 3 := by + rcases x with v | ⟨u, p⟩ + · exact card_image_le.trans (hC v) + · have := Tree.degree p + exact card_image_le.trans (by omega) + exact (card_union_le _ _).trans (Nat.add_le_add (by simp) (card_image_le.trans h)) + +open scoped Classical in +theorem core_adj {v u : V} (hu : u ∈ C v) : core u ∈ adj sw C (core v) := + mem_union_right _ (mem_image_of_mem _ (mem_image_of_mem _ hu)) + +open scoped Classical in +theorem branch_adj (x : V × Fin r) {p q : Tree.Node s} (hq : q ∈ Tree.adj p) : + Sum.inl (.inr (x, q)) ∈ adj sw C (.inl (.inr (x, p))) := + mem_union_right _ (mem_image_of_mem _ (mem_image_of_mem _ hq)) + +open scoped Classical in +theorem size : Fintype.card (Host V r s w) = + Fintype.card V * (1 + r * 2 ^ (Nat.clog 2 s + 1)) * (1 + 2 ^ (Nat.clog 2 w + 1)) := by + simp only [Host, Detour.Hub, End, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + Nat.mul_add, Nat.mul_one, Nat.mul_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Tether +end + +/- # One programmable trivalent permutation network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +open scoped Classical in +/-- Exterior positions and the two ends of every internal edge. -/ +abbrev RotorEnd (Y w : ℕ) (E : Type) := (Bool × Fin Y × Fin w) ⊕ E ⊕ E + +open scoped Classical in +/-- The graph and port locations are independent of the permutation. -/ +structure Rotor (F : Type) [Field F] (Y w : ℕ) where + /-- The type of vertices. -/ + V : Type + /-- The type of edges. -/ + E : Type + [fv : Fintype V] + [fe : Fintype E] + /-- The `Rotor` component of type `RotorEnd Y w E → V`. -/ + pos : RotorEnd Y w E → V + degree : ∀ v, Fintype.card {q // pos q = v} ≤ 3 + packet : ∀ σ : Equiv.Perm (Fin Y), Spectral.Packet F + (fun p : Fin Y × Fin w => (pos (.inl (false, p)), pos (.inl (true, σ p.1, p.2)))) + (fun _ : Unit => fun e : E => (pos (.inr (.inl e)), pos (.inr (.inr e)))) + +attribute [instance] Rotor.fv Rotor.fe + +namespace Rotor +variable {F : Type} [Field F] {Y w : ℕ} (R : Rotor F Y w) + +open scoped Classical in +/-- The value specified by `R.pos (.inl (side, i, j))`. -/ +def port (side : Bool) (i : Fin Y) (j : Fin w) : R.V := R.pos (.inl (side, i, j)) + +open scoped Classical in +/-- The value specified by `(R.pos (.inr (.inl e)), R.pos (.inr (.inr e)))`. -/ +def edge (e : R.E) : R.V × R.V := (R.pos (.inr (.inl e)), R.pos (.inr (.inr e))) + +open scoped Classical in +/-- Fix the tags of a single permutation verifier, without adding vertices. -/ +theorem of_tag {k m : ℕ} + (h : Net F (Tagged.inputs k (word w)) .unit (Tagged.tag F k (word w)) m) : + ∃ R : Rotor F (2 ^ k) w, Fintype.card R.V = m ∧ 2 * Fintype.card R.E ≤ 3 * m := by + obtain ⟨G, eval, tri, size⟩ := h.diagram + obtain ⟨p, prog⟩ := tag_program F k w + let embed : RotorEnd (2 ^ k) w G.E → G.End + | .inl q => .inl (.inl (p q)) + | .inr (.inl e) => .inl (.inr e) + | .inr (.inr e) => .inr (.inr e) + have inj : Function.Injective embed := by + rintro (q | e | e) (z | f | f) he <;> + simp only [embed, Sum.inl.injEq, Sum.inr.injEq, reduceCtorEq, p.injective.eq_iff] + at he ⊢ <;> exact he + let pos := G.station ∘ embed + have degree (v : G.V) : Fintype.card {q // pos q = v} ≤ 3 := by + let f : {q // pos q = v} → {e // G.station e = v} := fun q => ⟨embed q.val, q.property⟩ + have hi : Function.Injective f := fun _ _ he => Subtype.ext (inj (congrArg Subtype.val he)) + exact (Fintype.card_le_of_injective f hi).trans ((G.degree v).le.trans (tri v)) + have packet (σ : Equiv.Perm (Fin (2 ^ k))) : Spectral.Packet F + (fun t : Fin (2 ^ k) × Fin w => (pos (.inl (false, t)), pos (.inl (true, σ t.1, t.2)))) + (fun _ : Unit => fun e : G.E => (pos (.inr (.inl e)), pos (.inr (.inr e)))) := by + obtain ⟨cfg, local_cfg, exact_cfg⟩ := prog σ + refine ⟨fun _ v x y z => G.vertex (cfg x y) () z v, ?_, ?_⟩ + · intro _ v x y z x' y' z' hx hy hz + apply G.local_weight + · rintro (i | e) hi + · exact local_cfg x y x' y' i (fun t ht => hx t (by simpa [pos, embed, ht, Diagram.station] + using hi)) + (fun t ht => hy t (by simpa [pos, embed, ht, Diagram.station] using hi)) + · exact hz e (.inl hi) + · rintro (i | e) hi + · exact i.elim + · exact hz e (.inr hi) + · intro x y + rw [Fintype.sum_unique] + change _ = G.eval (cfg x y) () + rw [eval, exact_cfg] + refine ⟨⟨G.V, G.E, pos, degree, packet⟩, size, ?_⟩ + have := G.cost_trivalent tri + rw [G.cost_eq, size] at this + change 2 * Fintype.card G.E ≤ 3 * m + omega + +end Rotor +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Deploying simultaneous permutation layers + +All copies use the same hardware. Each active port has +its own wire along the paths joining the terminals to the programmed +network. Both ends of unused port are pinned. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +open Spectral + +variable {F : Type} [Field F] {Y w n : ℕ} (R : Rotor F Y w) + +open scoped Classical in +/-- Indexes the hardware by the coordinates of `R.V ⊕ (Bool × Fin Y × Tree.Node w)`. -/ +abbrev Hardware := R.V ⊕ (Bool × Fin Y × Tree.Node w) + +open scoped Classical in +/-- The value specified by `.inr (t, i, Tree.root w)`. -/ +def root (t : Bool) (i : Fin Y) : R.Hardware := .inr (t, i, Tree.root w) + +open scoped Classical in +/-- Walk from a network port to its gathering-tree root. -/ +def walk (t : Bool) (i : Fin Y) (j : Fin w) : ℕ → R.Hardware + | 0 => .inl (R.port t i j) + | k + 1 => .inr (t, i, Tree.climb j k) + +open scoped Classical in +@[simp] theorem walk_top (t : Bool) (i : Fin Y) (j : Fin w) : + R.walk t i j (Nat.clog 2 w + 1) = R.root t i := by simp [walk, root] + +variable {A : Type} [Fintype A] + +open scoped Classical in +/-- Indexes the path edge by the coordinates of `Fin (Nat.clog 2 w + 1) × A`. -/ +abbrev PathEdge (w : ℕ) (A : Type) := Fin (Nat.clog 2 w + 1) × A +open scoped Classical in +/-- Indexes the layer edge by the coordinates of `Σ _ : Fin n, R.E`. -/ +abbrev LayerEdge (n : ℕ) := Σ _ : Fin n, R.E +open scoped Classical in +/-- Indexes the supply by the coordinates of `PathEdge w A ⊕ R.LayerEdge n ⊕ PathEdge w A`. -/ +abbrev Supply (A : Type) (n : ℕ) := PathEdge w A ⊕ R.LayerEdge n ⊕ PathEdge w A + +open scoped Classical in +/-- The path edge of type `R.Hardware × R.Hardware`, constructed using `R.walk t (p e.2) (lane +e.2).2`. -/ +def pathEdge (t : Bool) (p : A → Fin Y) (lane : A → Fin n × Fin w) + (e : PathEdge w A) : R.Hardware × R.Hardware := + let f := R.walk t (p e.2) (lane e.2).2 + (f e.1.val, f (e.1.val + 1)) + +open scoped Classical in +/-- The value specified by `(.inl (R.edge e.2).1, .inl (R.edge e.2).2)`. -/ +def layerEdge (e : R.LayerEdge n) : R.Hardware × R.Hardware := + (.inl (R.edge e.2).1, .inl (R.edge e.2).2) + +open scoped Classical in +/-- Computes the supply by the application `Sum.elim (R.pathEdge false p lane) (Sum.elim +R.layerEdge (R.pathEdge true q lane))`. -/ +def supply (p q : A → Fin Y) (lane : A → Fin n × Fin w) : + R.Supply A n → R.Hardware × R.Hardware := + Sum.elim (R.pathEdge false p lane) (Sum.elim R.layerEdge (R.pathEdge true q lane)) + +open scoped Classical in +/-- The construction uses `⟨(lane a).1, p a, (lane a).2⟩` for its intermediate `embed`. -/ +def layerRule (p q : A → Fin Y) (σ : Fin n → Equiv.Perm (Fin Y)) + (lane : A → Fin n × Fin w) + (inj : Function.Injective (fun a => (p a, lane a))) + (route : ∀ a, σ (lane a).1 (p a) = q a) : + Packet.Rule F (fun a : A => + (R.walk false (p a) (lane a).2 0, R.walk true (q a) (lane a).2 0)) + (fun _ : Unit => R.layerEdge (n := n)) := by + let embed (a : A) : Σ _ : Fin n, Fin Y × Fin w := + ⟨(lane a).1, p a, (lane a).2⟩ + have he : Function.Injective embed := by + intro a b hab + simp only [embed, Sigma.mk.inj_iff, heq_eq_eq, Prod.mk.injEq] at hab + exact inj (Prod.ext hab.2.1 (Prod.ext hab.1 hab.2.2)) + let h := Packet.Rule.parallelOne (fun t : Fin n => (R.packet (σ t)).rule) + have h' := (h.select ⟨embed, he⟩).place (fun t => (Sum.inl t.2 : R.Hardware)) + refine h'.congr ?_ rfl + funext i + simp only [Packet.parallelDemand, Function.Embedding.coeFn_mk, embed, route, walk, port] + +open scoped Classical in +/-- The tree rule of type `Packet.Rule F (fun a : A => (R.walk t (p a) (lane a).2 0, R.root t (p +a))) (fun _ : Unit => R.pathEdge t p lane)`, constructed using `Packet.Rule.path F (fun k (a +: A) => R.walk t (p a) (lane a).2 k)`. -/ +def treeRule (p : A → Fin Y) (lane : A → Fin n × Fin w) (t : Bool) : + Packet.Rule F (fun a : A => (R.walk t (p a) (lane a).2 0, R.root t (p a))) + (fun _ : Unit => R.pathEdge t p lane) := by + let hp := Packet.Rule.path F (fun k (a : A) => R.walk t (p a) (lane a).2 k) + (Nat.clog 2 w + 1) + exact hp.congr (by simp only [walk_top]) rfl + +open scoped Classical in +/-- Each named unit is carried from its input terminal to its assigned +output terminal by an exact one-term packet. -/ +def deployRule (p q : A → Fin Y) (σ : Fin n → Equiv.Perm (Fin Y)) + (lane : A → Fin n × Fin w) + (inj : Function.Injective (fun a => (p a, lane a))) + (route : ∀ a, σ (lane a).1 (p a) = q a) : + Packet.Rule F (fun a : A => (R.root false (p a), R.root true (q a))) + (fun _ : Unit => R.supply p q lane) := + (R.treeRule p lane false).reverse.series + ((R.layerRule p q σ lane inj route).series (R.treeRule q lane true)) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +end + +/- +# Common support of a rotor and its gathering trees + +The support leaves one free connection at every root. It does not +depend on the demand, layer count, port assignment or permutation. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +open Finset + +variable {F : Type} [Field F] {Y w n : ℕ} (R : Rotor F Y w) + +open scoped Classical in +/-- In the case `.inl (t, i, j)`, this construction gives `.inr (t, i, Tree.tip j)`. -/ +def opposite : RotorEnd Y w R.E → R.Hardware + | .inl (t, i, j) => .inr (t, i, Tree.tip j) + | .inr (.inl e) => .inl (R.edge e).2 + | .inr (.inr e) => .inl (R.edge e).1 + +open scoped Classical in +/-- The support used in the `Rotor` construction. -/ +def support : R.Hardware → Finset R.Hardware + | .inl v => (univ.filter fun e => R.pos e = v).image R.opposite + | .inr (t, i, p) => + ((Tree.adj p).image fun q => Sum.inr (t, i, q)) ∪ + ((univ.filter fun j => Tree.tip j = p).image fun j => Sum.inl (R.port t i j)) + +open scoped Classical in +private theorem neighbor (e : RotorEnd Y w R.E) : R.opposite e ∈ R.support (.inl (R.pos e)) := + mem_image.mpr ⟨e, mem_filter.mpr ⟨mem_univ _, rfl⟩, rfl⟩ + +open scoped Classical in +theorem support_symm {v u : R.Hardware} (hu : u ∈ R.support v) : v ∈ R.support u := by + rcases v with v | ⟨t, i, p⟩ + · obtain ⟨e, he, rfl⟩ := mem_image.mp hu + have h := (mem_filter.mp he).2 + subst v + rcases e with ⟨t, i, j⟩ | e | e + · exact mem_union_right _ (mem_image.mpr ⟨j, mem_filter.mpr ⟨mem_univ _, rfl⟩, rfl⟩) + · exact R.neighbor (.inr (.inr e)) + · exact R.neighbor (.inr (.inl e)) + · rcases mem_union.mp hu with h | h + · obtain ⟨q, hq, rfl⟩ := mem_image.mp h + exact mem_union_left _ (mem_image.mpr ⟨p, Tree.adj_symm hq, rfl⟩) + · obtain ⟨j, hj, rfl⟩ := mem_image.mp h + rw [← (mem_filter.mp hj).2] + exact R.neighbor (.inl (t, i, j)) + +open scoped Classical in +theorem support_degree (v : R.Hardware) : + (R.support v).card + (if ∃ t i, v = R.root t i then 1 else 0) ≤ 3 := by + rcases v with v | ⟨t, i, p⟩ + · have hn : ¬∃ t i, Sum.inl v = R.root t i := by simp [root] + rw [ite_eq_right hn, add_zero] + exact card_image_le.trans ((Fintype.card_subtype _).ge.trans (R.degree v)) + · have ht : (univ.filter fun j => Tree.tip j = p).card ≤ + if 2 ^ Nat.clog 2 w ≤ p.val then 1 else 0 := by + split_ifs with h + · exact card_le_one.mpr fun a ha b hb => + Tree.tip_injective ((mem_filter.mp ha).2.trans (mem_filter.mp hb).2.symm) + · have h' (j : Fin w) : Tree.tip j ≠ p := by + intro e + rw [← e] at h + exact h (Nat.le_add_right _ _) + simp [h'] + have hr : (∃ b j, Sum.inr (t, i, p) = R.root b j) ↔ p = Tree.root w := by simp [root] + have hc : (R.support (.inr (t, i, p))).card ≤ + (Tree.adj p).card + (univ.filter fun j => Tree.tip j = p).card := + (card_union_le _ _).trans (Nat.add_le_add card_image_le card_image_le) + simp only [hr] + have := Tree.degree p + omega + +open scoped Classical in +theorem size (hw : 0 < w) : Fintype.card R.Hardware ≤ Fintype.card R.V + 8 * Y * w := by + simp only [Hardware, Fintype.card_sum, Fintype.card_prod, Fintype.card_bool, Fintype.card_fin] + have h := Tree.size hw + rw [Fintype.card_fin] at h + have := Nat.mul_le_mul_left (2 * Y) h + nlinarith + +variable {A : Type} (p q : A → Fin Y) (lane : A → Fin n × Fin w) + +open scoped Classical in +private theorem path_mem (t : Bool) (e : PathEdge w A) : + (R.pathEdge t p lane e).2 ∈ R.support (R.pathEdge t p lane e).1 := by + obtain ⟨⟨k, hk⟩, a⟩ := e + cases k with + | zero => + simpa [pathEdge, walk, port, opposite] using R.neighbor (.inl (t, p a, (lane a).2)) + | succ k => + exact mem_union_left _ (mem_image.mpr ⟨_, Tree.climb_adj (lane a).2 (by omega), rfl⟩) + +open scoped Classical in +theorem supply_mem (e : R.Supply A n) : + (R.supply p q lane e).2 ∈ R.support (R.supply p q lane e).1 := by + rcases e with e | e | e + · exact R.path_mem p lane false e + · exact R.neighbor (.inr (.inl e.2)) + · exact R.path_mem q lane true e + +open scoped Classical in +theorem supply_card [Fintype A] : + Fintype.card (R.Supply A n) = + n * Fintype.card R.E + 2 * (Nat.clog 2 w + 1) * Fintype.card A := by + simp [Supply, LayerEdge, PathEdge, Fintype.card_sigma] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +end + +/- # Realizing the good contacts by permutation networks and direct links -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Delivery +open Spectral + +variable {P U X W F : Type} [Fintype P] [Field F] + {leaf : P → X} {point : U → Bool → P} {good : U → Prop} + {edge : U → W} {outLeaf : W → Bool → X} {cap : W → ℝ} {Y w : ℕ} + {out : ∀ x, Port outLeaf cap Y x ↪ Fin Y} {l : P → ℝ} {u : ℝ} + (d : Delivery leaf point good edge outLeaf cap Y w out l u) (R : Rotor F Y w) + +open scoped Classical in +/-- The value specified by `(leaf (point q.val t), R.root false (d.terminal (point q.val t)))`. -/ +def source (q : {i // good i}) (t : Bool) : X × R.Hardware := + (leaf (point q.val t), R.root false (d.terminal (point q.val t))) + +open scoped Classical in +/-- The value specified by `((d.plug q t).1, R.root true (d.plug q t).2)`. -/ +def target (q : {i // good i}) (t : Bool) : X × R.Hardware := + ((d.plug q t).1, R.root true (d.plug q t).2) + +open scoped Classical in +/-- Computes the input at by the application `d.terminal (point e.val.1.val e.val.2)`. -/ +def inputAt (x : X) (e : GoodEnd leaf point good x) := d.terminal (point e.val.1.val e.val.2) + +open scoped Classical in +/-- Computes the output at by the application `out x (portOf leaf point good edge outLeaf cap Y +d.agree d.slot e)`. -/ +def outputAt (x : X) (e : GoodEnd leaf point good x) := + out x (portOf leaf point good edge outLeaf cap Y d.agree d.slot e) + +open scoped Classical in +/-- Computes the local wires by the application `R.Supply (GoodEnd leaf point good x) (d.layers +x)`. -/ +abbrev LocalWires (x : X) := R.Supply (GoodEnd leaf point good x) (d.layers x) +open scoped Classical in +/-- Indexes the wires by the coordinates of `(Σ x, d.LocalWires R x) ⊕ {q // good q}`. -/ +abbrev Wires := (Σ x, d.LocalWires R x) ⊕ {q // good q} + +open scoped Classical in +/-- The inside of type `(X × R.Hardware) × (X × R.Hardware)`, constructed using `R.supply +(d.inputAt e.1) (d.outputAt e.1) (d.lane e.1) e.2`. -/ +def inside (e : Σ x, d.LocalWires R x) : (X × R.Hardware) × (X × R.Hardware) := + let z := R.supply (d.inputAt e.1) (d.outputAt e.1) (d.lane e.1) e.2 + ((e.1, z.1), (e.1, z.2)) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def supply : d.Wires R → (X × R.Hardware) × (X × R.Hardware) := + Sum.elim (d.inside R) (fun q => (d.target R q false, d.target R q true)) + +open scoped Classical in +/-- All hardware and direct links for a group stay in that group. -/ +theorem same_group {I : Type} (g : X → I) + (h : ∀ q, good q → g (leaf (point q false)) = g (leaf (point q true))) + (e : d.Wires R) : g (d.supply R e).1.1 = g (d.supply R e).2.1 := by + cases e with + | inl _ => rfl + | inr q => exact h q.val q.property + +variable [Fintype X] [Fintype U] + +open scoped Classical in +/-- The direct wire joins matching reserved outputs. Its internal bit +is summed exactly once, leaving equality on the two input terminals. -/ +def deployRule : + Packet.Rule F (fun q => (d.source R q false, d.source R q true)) + (fun _ : Unit => d.supply R) := by + have each (x : X) := + R.deployRule (d.inputAt x) (d.outputAt x) (d.config x) (d.lane x) (d.input x) (d.routes x) + let e : {q // good q} × Bool ≃ Σ x, GoodEnd leaf point good x := + (Equiv.sigmaFiberEquiv (fun q : {i // good i} × Bool => leaf (point q.1.val q.2))).symm + have hp := ((Packet.Rule.parallelOne each).place (fun q => (q.1, q.2))).select e.toEmbedding + have hq : Packet.Rule F (fun q : {i // good i} × Bool => (d.source R q.1 q.2, d.target R q.1 q.2)) + (fun _ : Unit => d.inside R) := hp + exact hq.joinOutputs + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Delivery +end + +/- # Degree-three support shared by all good contacts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing +open Finset + +variable {Z F : Type} [Field F] {Y w : ℕ} (R : Rotor F Y w) + +namespace Rotor + +open scoped Classical in +/-- Attach the predetermined cross-base links at output terminals. -/ +def net (p : Z × Fin Y → Z × Fin Y) (v : Z × R.Hardware) : Finset (Z × R.Hardware) := + ((R.support v.2).image (Prod.mk v.1)) ∪ + ((univ.filter (fun i => v.2 = R.root true i)).image (fun i => + ((p (v.1, i)).1, R.root true (p (v.1, i)).2))) + +open scoped Classical in +theorem mem_net (p : Z × Fin Y → Z × Fin Y) (v u : Z × R.Hardware) : + u ∈ R.net p v ↔ (u.1 = v.1 ∧ u.2 ∈ R.support v.2) ∨ + ∃ i, v.2 = R.root true i ∧ u = ((p (v.1, i)).1, R.root true (p (v.1, i)).2) := by + obtain ⟨z, a⟩ := u + simp only [net, mem_union, mem_image, mem_filter, mem_univ, true_and, Prod.mk.injEq] + aesop + +open scoped Classical in +theorem net_symm (p : Z × Fin Y → Z × Fin Y) (hp : Function.Involutive p) + {v u : Z × R.Hardware} (he : u ∈ R.net p v) : v ∈ R.net p u := by + rw [mem_net] at he ⊢ + rcases he with ⟨hs, he⟩ | ⟨i, hi, rfl⟩ + · exact .inl ⟨hs.symm, R.support_symm he⟩ + · refine .inr ⟨(p (v.1, i)).2, rfl, ?_⟩ + simp only [Prod.mk.eta, hp (v.1, i)] + exact Prod.ext rfl hi + +open scoped Classical in +/-- One connection at every input remains available for the exceptional +contacts, even if some outputs have no active good links. -/ +theorem net_degree (p : Z × Fin Y → Z × Fin Y) (v : Z × R.Hardware) : + (R.net p v).card + (if ∃ i, v.2 = R.root false i then 1 else 0) ≤ 3 := by + have hd := R.support_degree v.2 + have he : (R.net p v).card ≤ (R.support v.2).card + + (univ.filter fun i => v.2 = R.root true i).card := + (card_union_le _ _).trans (Nat.add_le_add card_image_le card_image_le) + by_cases h : ∃ t i, v.2 = R.root t i + · rw [ite_eq_left h] at hd + obtain ⟨t, i, hi⟩ := h + cases t <;> simp [hi, root, filter_eq] at he hd ⊢ <;> omega + · have hn t i : v.2 ≠ R.root t i := fun h' => h ⟨t, i, h'⟩ + simp only [hn, ge_iff_le, exists_false, ite_false, add_zero, + filter_false, card_empty] at he hd ⊢ + exact he.trans hd + +end Rotor + +variable {P U X W : Type} [Fintype P] + {leaf : P → X} {point : U → Bool → P} {good : U → Prop} + {edge : U → W} {outLeaf : W → Bool → X} {cap : W → ℝ} + {out : ∀ x, Port outLeaf cap Y x ↪ Fin Y} {l : P → ℝ} {u : ℝ} + (d : Delivery leaf point good edge outLeaf cap Y w out l u) + +open scoped Classical in +/-- Project the absolute group coordinates onto common hardware slots. -/ +theorem Delivery.supply_mem (g : X → Z) (p : Z × Fin Y → Z × Fin Y) + (links : ∀ q, p (Prod.map g id (d.plug q false)) = Prod.map g id (d.plug q true)) + (e : d.Wires R) : + Prod.map g id (d.supply R e).2 ∈ R.net p (Prod.map g id (d.supply R e).1) := by + rw [R.mem_net] + rcases e with ⟨x, e⟩ | q + · exact .inl ⟨rfl, R.supply_mem (d.inputAt x) (d.outputAt x) (d.lane x) e⟩ + · refine .inr ⟨(d.plug q false).2, rfl, ?_⟩ + exact congrArg (fun a : Z × Fin Y => (a.1, R.root true a.2)) (links q).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end + +/- +# Attaching the contact trees to the rotor + +Common core support consists of three parts. Each site has one rotor +and its gathering trees. Each output terminal has at most one direct +link, and each input terminal has one contact tree for exceptional traffic. +The full support adds tether connections at the input terminals. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +open Finset + +variable {F X : Type} [Field F] {Y w L : ℕ} (R : Rotor F Y w) + +open scoped Classical in +/-- Indexes the host by the coordinates of `(X × R.Hardware) ⊕ ((X × Fin Y) × Tree.Node L)`. -/ +abbrev Host (X : Type) (L : ℕ) := (X × R.Hardware) ⊕ ((X × Fin Y) × Tree.Node L) + +open scoped Classical in +/-- The value specified by `.inl (p.1, R.root false p.2)`. -/ +def input (p : X × Fin Y) : R.Host X L := .inl (p.1, R.root false p.2) + +open scoped Classical in +theorem input_injective : Function.Injective (R.input (X := X) (L := L)) := by + rintro ⟨x, i⟩ ⟨y, j⟩ he + simpa [input, root] using he + +open scoped Classical in +/-- Computes the hub by the application `Sum.elim R.input Sum.inr`. -/ +def hub : Detour.Hub (X × Fin Y) L → R.Host X L := Sum.elim R.input Sum.inr + +open scoped Classical in +theorem hub_injective : Function.Injective (R.hub (X := X) (L := L)) := by + rintro (p|p) (q|q) he + · exact congrArg Sum.inl (R.input_injective he) + · cases he + · cases he + · exact congrArg Sum.inr (Sum.inr.inj he) + +variable [Fintype X] (sw : Detour.Switch (X × Fin Y) L) (mate : X × Fin Y → X × Fin Y) + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `(R.net mate v).image Sum.inl ∪`. -/ +def links : R.Host X L → Finset (R.Host X L) + | .inl v => (R.net mate v).image Sum.inl ∪ + ((univ.filter fun i => v.2 = R.root false i).image + fun i => Sum.inr ((v.1, i), Tree.root L)) + | .inr v => (sw.adj (.inr v)).image R.hub + +open scoped Classical in +theorem links_net {v z : X × R.Hardware} (hz : z ∈ R.net mate v) : + .inl z ∈ R.links sw mate (.inl v) := mem_union_left _ (mem_image_of_mem _ hz) + +open scoped Classical in +theorem links_detour {v z : Detour.Hub (X × Fin Y) L} (hz : z ∈ sw.adj v) : + R.hub z ∈ R.links sw mate (R.hub v) := by + cases v with + | inl v => + have he := mem_singleton.mp hz + subst z + exact mem_union_right _ (mem_image.mpr ⟨v.2, mem_filter.mpr ⟨mem_univ _, rfl⟩, rfl⟩) + | inr v => exact mem_image_of_mem _ hz + +open scoped Classical in +theorem links_symm (hm : Function.Involutive mate) (v z : R.Host X L) + (hz : z ∈ R.links sw mate v) : v ∈ R.links sw mate z := by + cases v with + | inl v => + rcases mem_union.mp hz with hz | hz + · obtain ⟨q, hq, rfl⟩ := mem_image.mp hz + exact R.links_net sw mate (R.net_symm mate hm hq) + · obtain ⟨i, hi, rfl⟩ := mem_image.mp hz + have he : v = (v.1, R.root false i) := Prod.ext rfl (mem_filter.mp hi).2 + rw [he] + exact R.links_detour sw mate (sw.adj_symm (.inl (v.1, i)) (.inr ((v.1, i), Tree.root L)) + (mem_singleton_self _)) + | inr v => + obtain ⟨q, hq, rfl⟩ := mem_image.mp hz + exact R.links_detour sw mate (sw.adj_symm _ _ hq) + +open scoped Classical in +theorem links_degree (v : R.Host X L) : (R.links sw mate v).card ≤ 3 := by + cases v with + | inl v => + have ha : (R.links sw mate (.inl v)).card ≤ (R.net mate v).card + + (univ.filter fun i => v.2 = R.root false i).card := + (card_union_le _ _).trans (Nat.add_le_add card_image_le card_image_le) + have hb := R.net_degree mate v + by_cases hi : ∃ i, v.2 = R.root false i + · rw [ite_eq_left hi] at hb + obtain ⟨i, hi⟩ := hi + simp [hi, root, filter_eq] at ha + exact ha.trans hb + · have hn i : v.2 ≠ R.root false i := fun he => hi ⟨i, he⟩ + simp only [hn, exists_false, ite_false, add_zero, filter_false, card_empty] + at ha hb + exact ha.trans hb + | inr v => exact card_image_le.trans (sw.adj_degree _) + +variable (N : X × Fin Y → Finset (X × Fin Y)) + +open scoped Classical in +/-- The selected finite family `R.links sw mate v ∪ if hv : ∃ x, R.input x = v then (N +hv.choose).image R.input else ∅`. -/ +def full (v : R.Host X L) : Finset (R.Host X L) := + R.links sw mate v ∪ if hv : ∃ x, R.input x = v then (N hv.choose).image R.input else ∅ + +open scoped Classical in +theorem links_sub (v : R.Host X L) : R.links sw mate v ⊆ R.full sw mate N v := subset_union_left + +open scoped Classical in +theorem input_full {x y} (hy : y ∈ N x) : R.input y ∈ R.full sw mate N (R.input x) := by + have hv : ∃ z, R.input (L := L) z = R.input x := ⟨x, rfl⟩ + rw [full, dite_eq_left hv, R.input_injective hv.choose_spec] + exact mem_union_right _ (mem_image_of_mem _ hy) + +open scoped Classical in +theorem full_symm (hm : Function.Involutive mate) (sym : ∀ x y, y ∈ N x → x ∈ N y) + (v z : R.Host X L) (hz : z ∈ R.full sw mate N v) : v ∈ R.full sw mate N z := by + rcases mem_union.mp hz with hh | hh + · exact R.links_sub sw mate N z (R.links_symm sw mate hm _ _ hh) + · split_ifs at hh with hv + · obtain ⟨q, hq, rfl⟩ := mem_image.mp hh + exact hv.choose_spec ▸ R.input_full sw mate N (sym _ _ hq) + · simp at hh + +open scoped Classical in +theorem full_degree {D : ℕ} (bound : ∀ x, (N x).card ≤ D) (v : R.Host X L) : + (R.full sw mate N v).card ≤ 3 + D := by + apply (card_union_le _ _).trans (Nat.add_le_add (R.links_degree sw mate v) ?_) + split_ifs + · exact card_image_le.trans (bound _) + · simp + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Rotor +end + +/- # Wire cost of all permutation layers and their direct links -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing.Delivery +open Finset + +variable {P U X W F : Type} [Fintype P] [Fintype U] [Field F] + {leaf : P → X} {point : U → Bool → P} {good : U → Prop} + {edge : U → W} {outLeaf : W → Bool → X} {cap : W → ℝ} {Y w : ℕ} + {out : ∀ x, Port outLeaf cap Y x ↪ Fin Y} {l : P → ℝ} {u : ℝ} + (d : Delivery leaf point good edge outLeaf cap Y w out l u) (R : Rotor F Y w) + +open scoped Classical in +theorem card_ends (x : X) : Fintype.card (GoodEnd leaf point good x) ≤ d.layers x * Y * w := by + simpa [mul_assoc, mul_left_comm] using Fintype.card_le_of_injective _ (d.input x) + +variable [Fintype X] + +open scoped Classical in +/-- Charge a direct link to its first endpoint. Unused sites incur no +cost. All units are measured relative to the base budget. -/ +theorem width_le (c : ℝ) (hc : 0 ≤ c) (hu : 0 ≤ u) (hR : (Fintype.card R.E : ℝ) ≤ c * Y * w) + (s : Finset X) (hs : ∀ q, good q → ∀ t, leaf (point q t) ∈ s) : + (Fintype.card (d.Wires R) : ℝ) * u ≤ + 10 * (c + 2 * (Nat.clog 2 w + 1) + 1) * s.card := by + let A := GoodEnd leaf point good + let cost (x : X) := Fintype.card (d.LocalWires R x) + Fintype.card (A x) + have links : Fintype.card {q // good q} ≤ ∑ x, Fintype.card (A x) := by + let e := Equiv.sigmaFiberEquiv (fun q : {i // good i} × Bool => leaf (point q.1.val q.2)) + rw [← Fintype.card_sigma, Fintype.card_congr e, Fintype.card_prod, Fintype.card_bool] + omega + have total : Fintype.card (d.Wires R) ≤ ∑ x ∈ s, cost x := by + rw [sum_subset (subset_univ s)] + · simp only [Wires, Fintype.card_sum, Fintype.card_sigma, cost, sum_add_distrib] + exact Nat.add_le_add_left links _ + · intro x _ hx + have hempty : IsEmpty (A x) := ⟨fun q => hx (q.property ▸ hs q.val.1.val q.val.1.property + q.val.2)⟩ + have h0 : Fintype.card (A x) = 0 := Fintype.card_eq_zero + simp [cost, LocalWires, R.supply_card, d.empty x hempty, A] at h0 ⊢ + have localCost (x : X) : (cost x : ℝ) * u ≤ 10 * (c + 2 * (Nat.clog 2 w + 1) + 1) := by + have hA : (Fintype.card (A x) : ℝ) * u ≤ 10 := calc + _ ≤ (d.layers x : ℝ) * Y * w * u := by + apply mul_le_mul_of_nonneg_right _ hu + exact_mod_cast d.card_ends x + _ ≤ _ := d.cost x + have hE : (d.layers x : ℝ) * Fintype.card R.E * u ≤ c * 10 := calc + _ ≤ (d.layers x : ℝ) * (c * Y * w) * u := + mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hR (Nat.cast_nonneg _)) hu + _ = c * ((d.layers x : ℝ) * Y * w * u) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left (d.cost x) hc + have := mul_le_mul_of_nonneg_left hA (by positivity : (0 : ℝ) ≤ 2 * (Nat.clog 2 w + 1)) + simp only [cost, LocalWires, R.supply_card, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, + Nat.cast_one] + linarith + calc + _ ≤ (∑ x ∈ s, (cost x : ℝ)) * u := mul_le_mul_of_nonneg_right (by exact_mod_cast total) hu + _ ≤ _ := by + rw [sum_mul] + simpa only [sum_const, nsmul_eq_mul, mul_comm] using sum_le_sum (fun x (_ : x ∈ s) + => localCost x) + +end MatrixMultiplicationAllFields.MatrixExponent.Packing.Delivery +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Chord.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Chord.lean new file mode 100644 index 0000000000..ac11462b6c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Chord.lean @@ -0,0 +1,919 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Fields +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Finite +public import Mathlib.Algebra.BigOperators.Field +public import Mathlib.Data.Fin.VecNotation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.ScaleSlope +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryComparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryPrices +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.MovingForms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.WireRecovery + +/-! +# Compatible ordinary prices + +A single choice of prices on all finite placements permits comparing +tests that use different subsets of sites. Repeated marks are allowed. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices + +open Spectral + +/-- The atlas used in the `Prices` construction. -/ +structure Atlas (K : Type) (X : Type*) [Field K] [PseudoMetricSpace X] where + /-- Assigns a real-valued price to a tensor indexed by points of the atlas. -/ + price {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (v : S → X) : Tensor K S → ℝ + valid {S : Type} [Fintype S] [DecidableEq S] [Nontrivial S] (v : S → X) : + ∃ D, price v ∈ Tensor.ordinary K S D + wire {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (v : S → X) (i j : S) : + price v (Tensor.wire K i j 2) = dist (v i) (v j) + place {S T : Type} [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype T] [DecidableEq T] [Nonempty T] (v : T → X) (f : S → T) : + price (v ∘ f) = price v ∘ Tensor.place f + +namespace Atlas +variable {K S T : Type} [Field K] [Fintype S] [DecidableEq S] + +theorem sum_nontrivial (S T : Type) [Nonempty S] [Nonempty T] : Nontrivial (S ⊕ T) := + ⟨.inl (Classical.arbitrary S), .inr (Classical.arbitrary T), by simp⟩ + +section Pseudo +variable {X : Type*} [PseudoMetricSpace X] (A : Atlas K X) + +theorem bounded [Nontrivial S] (x : S → X) {E : ℝ} + (he : ∀ i j, dist (x i) (x j) ≤ E) : + A.price x ∈ Tensor.ordinary K S (E * Fintype.card S) := by + obtain ⟨D, hD⟩ := A.valid x + have h := Tensor.ordinary_restrict hD id (fun i j => (A.wire x i j).le.trans (he i j)) + simpa only [Function.comp_def, Tensor.place_id] using h + +theorem congr [Nonempty S] (x y : S → X) (h : ∀ i, dist (x i) (y i) = 0) : + A.price x = A.price y := by + let _ := sum_nontrivial S S + let z := Sum.elim x y + obtain ⟨D, d, hd, f, hf, he⟩ := A.valid z + change A.price (z ∘ Sum.inl) = A.price (z ∘ Sum.inr) + rw [A.place, A.place, he] + funext B + change Tensor.values d f (Tensor.place Sum.inl B) = Tensor.values d f (Tensor.place Sum.inr B) + by_cases hz : d = 0 + · simp [Tensor.values, hz] + have hh (i : S) : Tensor.dist f (.inl i) (.inr i) = 0 := by + have e := (A.wire z (.inl i) (.inr i)).trans (h i) + rw [he] at e + exact (mul_eq_zero.mp e).resolve_left hz + rw [Tensor.values, Tensor.values, Tensor.price_place_eq f hf Sum.inl Sum.inr hh] + +/-- Builds `Atlas K Y where price v` with the specified `price`, `valid`, `wire`, `place`. -/ +def pullback {Y : Type*} [PseudoMetricSpace Y] (f : Y → X) + (h : ∀ a b, dist (f a) (f b) = dist a b) : Atlas K Y where + price v := A.price (f ∘ v) + valid v := A.valid (f ∘ v) + wire v i j := (A.wire (f ∘ v) i j).trans (h _ _) + place v g := A.place (f ∘ v) g + +end Pseudo + +variable {X : Type*} [MetricSpace X] (A : Atlas K X) [Nonempty S] + +theorem realized (x : S → X) {D : ℝ} (hd : ∀ i j, dist (x i) (x j) ≤ D) : + Routing.Realized x (A.price x) D := by + refine ⟨hd, fun U _ _ _ y hy => ?_⟩ + let _ := sum_nontrivial S U + let z := Sum.elim x y + refine ⟨A.price z, A.bounded z hy, fun B => ?_, A.wire z⟩ + rw [← Tensor.place_inl] + exact congrFun (A.place z Sum.inl).symm B + +include A in +theorem space : Routing.SpectralSpace K X := + fun _ _ _ _ x => ⟨A.price x, A.wire x, fun _ _ h => A.realized x h⟩ + +theorem represents (x : S → X) : Routing.Represents K (A.price x) x := by + refine ⟨A.wire x, fun _ _ _ _ z _ _ h => ?_⟩ + rw [← A.place] + exact A.realized _ h + +end Atlas +end MatrixMultiplicationAllFields.MatrixExponent.Prices +end + +/- # A common limit for all finite placement prices -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas + +open Spectral Filter Topology +variable {K : Type} {X I : Type*} [Field K] [PseudoMetricSpace X] + +theorem of_limit (l : Ultrafilter I) + (P : ∀ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S], (S → X) → I → Tensor K S → ℝ) + (hv : ∀ {S : Type} [Fintype S] [DecidableEq S] [Nontrivial S] (x : S → X), + ∃ D, ∀ᶠ i in (l : Filter I), P x i ∈ Tensor.ordinary K S D) + (hw : ∀ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (x : S → X) (a b : S), + Tendsto (fun i => P x i (Tensor.wire K a b 2)) (l : Filter I) (𝓝 (dist (x a) (x b)))) + (hc : ∀ {S T : Type} [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype T] [DecidableEq T] [Nonempty T] (x : T → X) (y : S → T) (i : I), + P (x ∘ y) i = P x i ∘ Tensor.place y) : + ∃ A : Atlas K X, ∀ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (x : S → X), + Tendsto (P x) (l : Filter I) (𝓝 (A.price x)) := by + have lim {S : Type} [Fintype S] [DecidableEq S] [Nontrivial S] (x : S → X) : + ∃ D, ∃ Q ∈ Tensor.ordinary K S D, Tendsto (P x) (l : Filter I) (𝓝 Q) := by + obtain ⟨D, hD⟩ := hv x + exact ⟨D, (Tensor.compact_ordinary _).ultrafilter_le_nhds' (l.map (P x)) (Filter.mem_map.mpr + hD)⟩ + have existsQ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (x : S → X) : + ∃ Q, Tendsto (P x) (l : Filter I) (𝓝 Q) := by + let _ := sum_nontrivial S S + let z := Sum.elim x x + obtain ⟨_, Q, _, hQ⟩ := lim z + refine ⟨Q ∘ Tensor.place Sum.inl, tendsto_pi_nhds.mpr fun B => ?_⟩ + exact (tendsto_pi_nhds.mp hQ (Tensor.place Sum.inl B)).congr' + (Eventually.of_forall fun i => congrFun (hc z Sum.inl i).symm B) + let A : Atlas K X := + { price := fun x => (existsQ x).choose + valid := fun x => by + obtain ⟨D, Q, hQ, h⟩ := lim x + exact ⟨D, tendsto_nhds_unique h (existsQ x).choose_spec ▸ hQ⟩ + wire := fun x a b => tendsto_nhds_unique + (tendsto_pi_nhds.mp (existsQ x).choose_spec _) (hw x a b) + place := fun x y => by + funext B + apply tendsto_nhds_unique (tendsto_pi_nhds.mp (existsQ (x ∘ y)).choose_spec B) + exact (tendsto_pi_nhds.mp (existsQ x).choose_spec (Tensor.place y B)).congr' + (Eventually.of_forall fun i => congrFun (hc x y i).symm B) } + exact ⟨A, fun x => (existsQ x).choose_spec⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +end + +/- Compatible prices on a limit of rescaled finite placements. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +open Spectral Filter Topology +variable {K : Type} [Field K] {X I : Type*} [PseudoMetricSpace X] + +theorem scaled_limit (l : Ultrafilter I) (Y : I → Type*) [∀ i, PseudoMetricSpace (Y i)] + (A : ∀ i, Atlas K (Y i)) (w : ∀ i, X → Y i) (s : I → ℝ) (hs : ∀ i, 0 ≤ s i) + (hdist : ∀ a b, Tendsto (fun i => s i * dist (w i a) (w i b)) (l : Filter I) + (𝓝 (dist a b))) : + ∃ B : Atlas K X, ∀ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] + (x : S → X) (U : Tensor K S), + Tendsto (fun i => s i * (A i).price (fun s => w i (x s)) U) + (l : Filter I) (𝓝 (B.price x U)) := by + let P {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (x : S → X) (i : I) + (U : Tensor K S) := s i * (A i).price (fun s => w i (x s)) U + obtain ⟨B, hB⟩ := Atlas.of_limit l P (by + intro S _ _ _ x + obtain ⟨m, hm⟩ := (Set.finite_range (fun u : S × S => dist (x u.1) (x u.2))).bddAbove + have h : ∀ᶠ i in (l : Filter I), ∀ a b, s i * dist (w i (x a)) (w i (x b)) ≤ m + 1 := by + refine eventually_all.mpr fun a => eventually_all.mpr fun b => ?_ + exact (hdist _ _).eventually_le_const ((hm ⟨(a, b), rfl⟩).trans_lt (lt_add_one _)) + refine ⟨(m + 1) * Fintype.card S, h.mono fun i hi => ?_⟩ + obtain ⟨_, d, hd, f, hf, he⟩ := (A i).valid (fun s => w i (x s)) + have hv : P x i ∈ Tensor.ordinary K S (s i * d) := + ⟨_, ⟨mul_nonneg (hs i) hd.1, le_rfl⟩, f, hf, funext fun U => by + simp only [P, he, Tensor.values, mul_assoc]⟩ + have hw (a b) : P x i (Tensor.wire K a b 2) ≤ m + 1 := by + unfold P + rw [(A i).wire] + exact hi _ _ + simpa only [Function.comp_def, Tensor.place_id] using Tensor.ordinary_restrict hv id hw) (by + intro S _ _ _ x a b + simp only [P, Atlas.wire] + exact hdist _ _) (by + intro S T _ _ _ _ _ _ x y i + funext U + exact congrArg (s i * ·) (congrFun ((A i).place (fun s => w i (x s)) y) U)) + exact ⟨B, fun x U => tendsto_pi_nhds.mp (hB x) U⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +end + +/- +# Pointed limits of rescaled spectral spaces + +Points are represented by bounded sections. The pseudometric keeps +zero-distance representatives distinct. All prices agree on such points. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices +open Spectral Filter Topology + +/-- The data for the rescale construction, including `Y`, `[metric`, `o`, `d`, `hn`. -/ +structure Rescale (I : Type*) where + /-- The `Rescale` component of type `I → Type`. -/ + Y : I → Type + [metric : ∀ i, MetricSpace (Y i)] + /-- The `Rescale` component of type `∀ i, Y i`. -/ + o : ∀ i, Y i + /-- The `Rescale` component of type `I → ℝ`. -/ + d : I → ℝ + hn : ∀ i, 0 ≤ d i + /-- The `Rescale` component of type `Ultrafilter I`. -/ + l : Ultrafilter I + +attribute [instance] Rescale.metric + +namespace Rescale +variable {I : Type*} (R : Rescale I) + +/-- The subtype of `x : ∀ i, R.Y i` satisfying `∃ M : ℝ, ∀ᶠ i in (R.l : Filter I), R.d i * dist +(x i) (R.o i) ≤ M`. -/ +def Site := {x : ∀ i, R.Y i // ∃ M : ℝ, ∀ᶠ i in (R.l : Filter I), R.d i * dist (x i) (R.o i) ≤ M} + +theorem lim (x y : R.Site) : + ∃ v : ℝ, Tendsto (fun i => R.d i * dist (x.val i) (y.val i)) (R.l : Filter I) (𝓝 v) := by + obtain ⟨a, ha⟩ := x.property + obtain ⟨b, hb⟩ := y.property + let f := fun i => R.d i * dist (x.val i) (y.val i) + have h : ∀ᶠ i in (R.l : Filter I), f i ∈ Set.Icc 0 (a + b) := by + filter_upwards [ha, hb] with i hx hy + refine ⟨mul_nonneg (R.hn i) dist_nonneg, ?_⟩ + exact (mul_le_mul_of_nonneg_left (dist_triangle_right _ _ (R.o i)) (R.hn i)).trans + ((mul_add _ _ _).trans_le (add_le_add hx hy)) + obtain ⟨v, _, hv⟩ := isCompact_Icc.ultrafilter_le_nhds' (R.l.map f) (Filter.mem_map.mpr h) + exact ⟨v, hv⟩ + +instance : PseudoMetricSpace R.Site where + dist x y := (R.lim x y).choose + dist_self x := tendsto_nhds_unique (R.lim x x).choose_spec (by simp) + dist_comm x y := tendsto_nhds_unique (R.lim x y).choose_spec + ((R.lim y x).choose_spec.congr' (Eventually.of_forall (fun i => by rw [dist_comm]))) + dist_triangle x y z := le_of_tendsto_of_tendsto' (R.lim x z).choose_spec + ((R.lim x y).choose_spec.add (R.lim y z).choose_spec) + (fun i => by rw [← mul_add]; exact mul_le_mul_of_nonneg_left (dist_triangle _ _ _) (R.hn i)) + +theorem distance (x y : R.Site) : + Tendsto (fun i => R.d i * dist (x.val i) (y.val i)) (R.l : Filter I) (𝓝 (dist x y)) := + (R.lim x y).choose_spec + +variable (C : ∀ i, Routing.Comparison (R.Y i)) + +/-- The seg of type `R.Site`, constructed using `(C i).seg t (x.val i) (y.val i)`. -/ +def seg (t : Routing.Fraction) (x y : R.Site) : R.Site := by + refine ⟨fun i => (C i).seg t (x.val i) (y.val i), ?_⟩ + obtain ⟨a, ha⟩ := x.property + refine ⟨(dist x y + 1) + a, ?_⟩ + filter_upwards [ha, (R.distance x y).eventually_lt_const + (lt_add_one (dist x y))] with i hx hxy + let m := (C i).seg t (x.val i) (y.val i) + have h : dist m (x.val i) ≤ dist (x.val i) (y.val i) := by + rw [dist_comm, ((C i).along t _ _).start] + exact mul_le_of_le_one_left dist_nonneg t.2.2 + calc + R.d i * dist m (R.o i) ≤ R.d i * (dist m (x.val i) + dist (x.val i) (R.o i)) := + mul_le_mul_of_nonneg_left (dist_triangle _ _ _) (R.hn i) + _ ≤ _ := by + rw [mul_add] + exact add_le_add ((mul_le_mul_of_nonneg_left h (R.hn i)).trans hxy.le) hx + +theorem along (t : Routing.Fraction) (x y : R.Site) : Routing.Along t x y (R.seg C t x y) := by + intro z + apply le_of_tendsto_of_tendsto' ((R.distance _ _).pow 2) + ((((R.distance x z).pow 2).const_mul _ |>.add (((R.distance y z).pow 2).const_mul _)).sub + (((R.distance x y).pow 2).const_mul _)) + intro i + change (R.d i * dist ((C i).seg t _ _) _) ^ 2 ≤ _ + linarith only [mul_le_mul_of_nonneg_left ((C i).along t (x.val i) (y.val i) (z.val i)) + (sq_nonneg (R.d i))] + +variable {K : Type} [Field K] + +theorem atlas (A : ∀ i, Atlas K (R.Y i)) : + ∃ B : Atlas K R.Site, ∀ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] + (x : S → R.Site) (U : Tensor K S), + Tendsto (fun i => R.d i * (A i).price (fun s => (x s).val i) U) + (R.l : Filter I) (𝓝 (B.price x U)) := by + exact Atlas.scaled_limit R.l R.Y A (fun i (x : R.Site) => x.val i) R.d R.hn R.distance + +end Rescale +end MatrixMultiplicationAllFields.MatrixExponent.Prices +end + +/- # Passing compatible prices to the metric completion -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +open Filter Topology +variable {K X Y : Type} [Field K] [PseudoMetricSpace X] [MetricSpace Y] + +theorem dense (A : Atlas K X) (f : X → Y) (hf : Isometry f) (hd : DenseRange f) : + ∃ B : Atlas K Y, ∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (x : S → X), + B.price (f ∘ x) = A.price x := by + have appr (y : Y) : ∃ t : ℕ → X, Tendsto (fun n => f (t n)) atTop (𝓝 y) := by + obtain ⟨x, hx, he⟩ := mem_closure_iff_seq_limit.mp (hd y) + choose t ht using hx + exact ⟨t, by simpa only [ht] using he⟩ + choose t ht using appr + let e := Sum.elim f id + let _ : PseudoMetricSpace (X ⊕ Y) := PseudoMetricSpace.induced e inferInstance + let w (n : ℕ) := Sum.elim id (fun y => t y n) + let l := Ultrafilter.of (atTop : Filter ℕ) + have hw (x : X ⊕ Y) : Tendsto (fun n => f (w n x)) (l : Filter ℕ) (𝓝 (e x)) := by + cases x with + | inl x => exact tendsto_const_nhds + | inr y => exact (ht y).mono_left (Ultrafilter.of_le _) + obtain ⟨B, hB⟩ := scaled_limit l (fun _ => X) (fun _ => A) w (fun _ => 1) + (fun _ => zero_le_one) (fun a b => by + change Tendsto _ _ (𝓝 (dist (e a) (e b))) + simpa only [one_mul, hf.dist_eq] using (hw a).dist (hw b)) + refine ⟨B.pullback Sum.inr (fun _ _ => rfl), fun _ _ _ _ x => ?_⟩ + change B.price (Sum.inr ∘ f ∘ x) = _ + rw [B.congr (Sum.inr ∘ f ∘ x) (Sum.inl ∘ x) fun i => dist_self (f (x i))] + funext T + exact tendsto_nhds_unique (hB (Sum.inl ∘ x) T) (by simp [w]) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +end + +/- # Propagating submean estimates through geodesic constructions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +open Spectral + +variable {K S U : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype U] [DecidableEq U] [Nonempty U] {X J : Type*} [PseudoMetricSpace X] [Fintype J] + +/-- The condition `∀ B, A.price x B ≤ ∑ j, w j * A.price (y j) B` on the specified data. -/ +def Submean (A : Atlas K X) (w : J → ℝ) (x : S → X) (y : J → S → X) : Prop := + ∀ B, A.price x B ≤ ∑ j, w j * A.price (y j) B + +namespace Submean +variable {A : Atlas K X} {w : J → ℝ} {x : S → X} {y : J → S → X} + +theorem reindex (h : A.Submean w x y) (e : U → S) : + A.Submean w (x ∘ e) (fun j => y j ∘ e) := by + intro B + simp only [A.place, Function.comp_apply] + exact h (Tensor.place e B) + +theorem wire (h : A.Submean w x y) (a b : S) : + dist (x a) (x b) ≤ ∑ j, w j * dist (y j a) (y j b) := by + simpa only [A.wire] using h (Tensor.wire K a b 2) + +theorem extend (h : A.Submean w x y) (hw : ∀ j, 0 ≤ w j) + (p : U → X) (q : J → U → X) + (he : ∀ u, ∃ a b : S, ∃ t : ℝ, + dist (x a) (p u) = t * dist (x a) (x b) ∧ + dist (p u) (x b) = (1 - t) * dist (x a) (x b) ∧ + (∑ j, w j * dist (y j a) (q j u)) ≤ dist (x a) (p u) ∧ + (∑ j, w j * dist (q j u) (y j b)) ≤ dist (p u) (x b)) : + A.Submean w (Sum.elim x p) (fun j => Sum.elim (y j) (q j)) := by + let _ := sum_nontrivial S U + let z := Sum.elim x p + let v j := Sum.elim (y j) (q j) + obtain ⟨D, hP⟩ := A.valid z + let Q (B : Tensor K (S ⊕ U)) := ∑ j, w j * A.price (v j) B + have hc : Tensor.Cap Q := Tensor.Cap.weighted (fun j => + Tensor.cap_ordinary (A.valid (v j)).choose_spec) w hw + have init (y : S → X) (p : U → X) (B : Tensor K S) : + A.price (Sum.elim y p) (Tensor.pad U B) = A.price y B := by + rw [← Tensor.place_inl] + change (A.price (Sum.elim y p) ∘ Tensor.place Sum.inl) B = _ + rw [← A.place] + rfl + have hl (B : Tensor K S) : A.price z (Tensor.place Sum.inl B) ≤ Q (Tensor.pad U B) := by + simp only [Q, v, z, Tensor.place_inl, init] + exact h B + have hh := Tensor.Cap.geodesic_le hP hc Sum.inl Sum.inr hl (fun u => by + obtain ⟨a, b, t, h₁, h₂, h₃, h₄⟩ := he u + refine ⟨a, b, t, ?_, ?_, ?_⟩ + · simpa only [Tensor.AtFraction, Tensor.gap, A.wire, z, Sum.elim_inl, Sum.elim_inr] + using And.intro h₁ h₂ + · simpa only [Tensor.gap, Q, A.wire, z, v, Sum.elim_inl, Sum.elim_inr] using h₃ + · simpa only [Tensor.gap, Q, A.wire, z, v, Sum.elim_inl, Sum.elim_inr] using h₄) + have id' : Sum.elim Sum.inl Sum.inr = (id : S ⊕ U → S ⊕ U) := by funext i; cases i <;> rfl + intro B + simpa only [id', Tensor.place_id] using hh B + +end Submean +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +end + +/- Convexity and transport for compatible prices on a pseudometric space. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +open Spectral + +variable {K : Type} [Field K] {X : Type*} [PseudoMetricSpace X] (A : Atlas K X) + {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] + +theorem chord {x y z : S → X} {t : ℝ} (ht : 0 ≤ t) (ht' : t ≤ 1) + (h₁ : ∀ i, dist (x i) (z i) = t * dist (x i) (y i)) + (h₂ : ∀ i, dist (z i) (y i) = (1 - t) * dist (x i) (y i)) (T : Tensor K S) : + A.price z T ≤ (1 - t) * A.price x T + t * A.price y T := by + let w : Fin 2 → ℝ := ![1 - t, t] + let v := Sum.elim x y + let q : Fin 2 → S → X := ![x, y] + have h : A.Submean w v (fun _ => v) := by + intro T + simp [Fin.sum_univ_two, w, sub_mul] + have h' := h.extend (fun j => by fin_cases j <;> simp [w, ht, ht']) z q (fun i => by + refine ⟨.inl i, .inr i, t, h₁ i, h₂ i, ?_, ?_⟩ <;> simp [Fin.sum_univ_two, w, q, v, h₁, h₂]) + have he := h'.reindex (Sum.inr : S → (S ⊕ S) ⊕ S) T + simpa [Fin.sum_univ_two, w, q, Function.comp_def] using he + +theorem move_cost (T : Raw K S) (x y : S → X) : + |A.price x (Tensor.ofRaw T) - A.price y (Tensor.ofRaw T)| ≤ + ∑ i, dist (x i) (y i) * (Real.log (Fintype.card (T.leg i)) / Real.log 2) := by + let _ := sum_nontrivial S S + let z := Sum.elim x y + obtain ⟨D, d, hd, f, hf, he⟩ := A.valid z + change |A.price (z ∘ Sum.inl) _ - A.price (z ∘ Sum.inr) _| ≤ _ + rw [A.place, A.place, he] + have hw (i : S) : d * Tensor.dist f (.inl i) (.inr i) = dist (x i) (y i) := by + have h := A.wire z (.inl i) (.inr i) + rw [he] at h + exact h + have hl : 0 < Real.log 2 := Real.log_pos (by norm_num) + by_cases hT : Tensor.ofRaw T = 0 + · simp only [hT, Function.comp_apply, Tensor.place_zero, sub_self, abs_zero] + positivity + have h := Tensor.price_transport f hf T hT Sum.inl Sum.inr + have h' := div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left h hd.1) hl.le + simp only [Finset.mul_sum, ← mul_assoc, hw, Finset.sum_div, mul_div_assoc] at h' + simp only [Function.comp_apply, Tensor.values, ← mul_sub, ← sub_div, abs_mul, abs_of_nonneg hd.1, + abs_div, abs_of_pos hl] + exact h' + +theorem label_move (x y : S → X) : |A.price x 2 - A.price y 2| ≤ ∑ i, dist (x i) (y i) := by + have h := A.move_cost (Raw.shared K Finset.univ 2) x y + have hd (i : S) : Fintype.card ((Raw.shared K Finset.univ 2).leg i) = 2 := Fintype.card_fin _ + rw [show Tensor.ofRaw (Raw.shared K Finset.univ 2) = 2 from Tensor.shared_all K 2] at h + simpa [hd, (Real.log_pos (by norm_num : (1 : ℝ) < 2)).ne'] using h + +theorem nonnegative (x : S → X) (T : Tensor K S) : 0 ≤ A.price x T := by + let _ := sum_nontrivial S S + let v := Sum.elim x x + obtain ⟨D, d, hd, f, hf, he⟩ := A.valid v + change 0 ≤ A.price (v ∘ Sum.inl) T + rw [A.place, he] + exact Tensor.values_nonneg hd.1 hf _ + +theorem collapsed (x : S → X) (h : ∀ i j, dist (x i) (x j) = 0) (T : Tensor K S) : + A.price x T = 0 := by + let _ := sum_nontrivial S S + let v := Sum.elim x x + have hv (i j : S ⊕ S) : dist (v i) (v j) ≤ 0 := by + cases i <;> cases j <;> exact (h _ _).le + obtain ⟨d, hd, f, _, he⟩ := A.bounded v hv + change A.price (v ∘ Sum.inl) T = 0 + rw [A.place, he, show d = 0 by simpa using hd] + simp [Tensor.values] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +end + +/- +# Simultaneous finite approximations + +Approximate the completed placement by finite models. One common +ultrafilter records all finite lists of sites. Original markings +are included by name, even when two marks coincide in the completion. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.TermModel +open Spectral Filter Topology + +variable {K S Y : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [MetricSpace Y] {f : Tensor K S →+* ℝ} + +theorem approximate (hf : Monotone f) (d : ℝ) (p : Term S → Y) (hd : DenseRange p) + (he : ∀ (M : TermModel f) (a b), M.Valid a → M.Valid b → + dist (p a) (p b) = d * Tensor.dist M.g (M.point a) (M.point b)) : + ∃ (I : Type) (l : Ultrafilter I) (m : I → TermModel f) + (z : (i : I) → S ⊕ Y → (m i).Site), + (∀ i a, z i (.inl a) = (m i).point (.mark a)) ∧ + ∀ a b, Tendsto (fun i => d * Tensor.dist (m i).g (z i a) (z i b)) (l : Filter I) + (𝓝 (dist (Sum.elim (p ∘ Term.mark) id a) (Sum.elim (p ∘ Term.mark) id b))) := by + classical + have dense (y : Y) : ∃ t : ℕ → Term S, Tendsto (fun n => p (t n)) atTop (𝓝 y) := by + obtain ⟨x, hx, he⟩ := mem_closure_iff_seq_limit.mp (hd y) + choose t ht using hx + exact ⟨t, by simpa only [ht] using he⟩ + choose t ht using dense + let I := ℕ × Finset Y + let l := Ultrafilter.of (atTop : Filter I) + have hl : (l : Filter I) ≤ atTop := Ultrafilter.of_le _ + have hn : Tendsto (fun i : I => i.1) (l : Filter I) atTop := + tendsto_atTop.mpr fun n => hl (eventually_atTop.mpr ⟨(n, ∅), fun _ hi => hi.1⟩) + let A (i : I) := i.2.image (fun y => t y i.1) + choose m hm using fun i => exists_model hf (A i) + let w (i : I) := Sum.elim Term.mark (fun y => t y i.1) + have valid (a : S ⊕ Y) : ∀ᶠ i in (l : Filter I), (m i).Valid (w i a) := by + cases a with + | inl s => exact Eventually.of_forall (fun i => trivial) + | inr y => + apply hl + refine eventually_atTop.mpr ⟨(0, {y}), fun i hi => ?_⟩ + exact hm i _ (Finset.mem_image.mpr ⟨y, hi.2 (Finset.mem_singleton_self _), rfl⟩) + have lim (a : S ⊕ Y) : Tendsto (fun i => p (w i a)) (l : Filter I) + (𝓝 (Sum.elim (p ∘ Term.mark) id a)) := by + cases a with + | inl s => exact tendsto_const_nhds + | inr y => exact (ht y).comp hn + refine ⟨I, l, m, fun i a => (m i).point (w i a), fun _ _ => rfl, fun a b => ?_⟩ + apply ((lim a).dist (lim b)).congr' + filter_upwards [valid a, valid b] with i ha hb + exact he (m i) _ _ ha hb + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.TermModel +end + +/- +# Spectral realization + +Assuming squared-distance comparison on finite spectral placements, +complete the geodesic terms generated by the original marking. +Pointwise limits recover compatible ordinary prices for arbitrary +finite placements in the completed space. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Filter Topology + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + +variable (K S) in +omit [Nonempty S] in +theorem realize_zero : + ∃ (Y : Type) (_ : MetricSpace Y) (_ : CompleteSpace Y) (x : S → Y), + Comparison Y ∧ SpectralSpace K Y ∧ Represents K (0 : Tensor K S → ℝ) x := by + have eq0 (a b : Unit) : dist a b = 0 := dist_eq_zero.mpr (Subsingleton.elim _ _) + have H (T : Type) [Fintype T] [DecidableEq T] [Nonempty T] (y : T → Unit) + (D : ℝ) (hD : 0 < D) : Realized y (0 : Tensor K T → ℝ) D := by + refine ⟨fun i j => (eq0 _ _).le.trans hD.le, ?_⟩ + intro U _ _ _ z _ + let _ := Prices.Atlas.sum_nontrivial T U + exact ⟨0, Tensor.zero_ordinary (by positivity), fun _ => rfl, fun _ _ => (eq0 _ _).symm⟩ + refine ⟨Unit, inferInstance, inferInstance, fun _ => (), ?_, ?_, ?_⟩ + · intro a b t _ _ + exact ⟨(), by simp, by simp⟩ + · intro T _ _ _ x + exact ⟨0, fun _ _ => (eq0 _ _).symm, fun D hD _ => H T x D hD⟩ + · exact ⟨fun _ _ => (eq0 _ _).symm, fun T _ _ _ _ D hD _ => H T _ D hD⟩ + +theorem realize_atlas (hc : SpectralComparison K) {D : ℝ} {P : Tensor K S → ℝ} + (hp : P ∈ Tensor.ordinary K S D) : + ∃ (Y : Type) (_ : MetricSpace Y) (_ : CompleteSpace Y) (x : S → Y), + Comparison Y ∧ ∃ A : Prices.Atlas K Y, A.price x = P := by + classical + obtain ⟨d, ⟨hd, _⟩, f, hf, rfl⟩ := hp + obtain ⟨Y, _, _, p, C, hp, he⟩ := TermModel.complete hc hf d hd + obtain ⟨I, l, M, z, hz, hdist⟩ := TermModel.approximate hf d p hp he + let x := p ∘ Term.mark + let π := Sum.elim x id + let _ : PseudoMetricSpace (S ⊕ Y) := PseudoMetricSpace.induced π inferInstance + let Q {T : Type} [Fintype T] [DecidableEq T] [Nonempty T] (a : T → S ⊕ Y) (i : I) := + Tensor.values d (M i).g ∘ Tensor.place (z i ∘ a) + obtain ⟨A, hl⟩ := Prices.Atlas.of_limit l Q (by + intro T _ _ _ a + refine ⟨d * Fintype.card T, Eventually.of_forall fun i => ?_⟩ + have hm : Tensor.values d (M i).g ∈ Tensor.ordinary K (M i).Site d := + ⟨d, ⟨hd, le_rfl⟩, (M i).g, (M i).mono, rfl⟩ + refine Tensor.ordinary_restrict hm _ fun j k => ?_ + exact (mul_le_mul_of_nonneg_left (Tensor.dist_le_one _ (M i).mono _ _) hd).trans_eq (mul_one + d)) (by + intro T _ _ _ a j k + simp only [Q, Function.comp_apply, Tensor.place_wire] + exact hdist _ _) (by + intro T U _ _ _ _ _ _ a b i + funext B + simp only [Q, Function.comp_apply, ← Tensor.place_comp, Function.comp_assoc]) + refine ⟨Y, inferInstance, inferInstance, x, C, A.pullback Sum.inr (fun _ _ => rfl), ?_⟩ + change A.price (Sum.inr ∘ x) = _ + have eq : A.price (Sum.inr ∘ x) = A.price Sum.inl := + A.congr _ _ fun i => dist_self (x i) + rw [eq] + apply tendsto_nhds_unique (hl Sum.inl) + refine tendsto_const_nhds.congr' (Eventually.of_forall fun i => ?_) + funext B + have e : z i ∘ Sum.inl = (M i).point ∘ Term.mark := funext (hz i) + simp only [Q, Function.comp_apply, e, Tensor.values, (M i).initial] + +theorem realize (hc : SpectralComparison K) {D : ℝ} {P : Tensor K S → ℝ} + (hp : P ∈ Tensor.ordinary K S D) : + ∃ (Y : Type) (_ : MetricSpace Y) (_ : CompleteSpace Y) (x : S → Y), + Comparison Y ∧ SpectralSpace K Y ∧ Represents K P x := by + obtain ⟨Y, _, _, x, C, A, rfl⟩ := realize_atlas hc hp + exact ⟨Y, inferInstance, inferInstance, x, C, A.space, A.represents x⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Finite models for an invariant family of markings + +A model for a finite set of group elements realizes all its prices. +Two models containing the support of the same pair of terms agree +on their distance, even after translating the second support. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas + +open Routing +variable {G K : Type} [Group G] [Field K] [PseudoMetricSpace G] + +open scoped Classical in +/-- The condition `∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (x : S → G) (g : G), +A.price (fun i => g * x i) = A.price x` on the specified data. -/ +def Invariant (A : Atlas K G) : Prop := + ∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (x : S → G) (g : G), + A.price (fun i => g * x i) = A.price x + +open scoped Classical in +/-- The data for the model construction, including `Site`, `[metric`, `cmp`, `B`, `mark`. -/ +structure Model (A : Atlas K G) (s : Finset G) where + /-- The `Model` component of type `Type`. -/ + Site : Type + [metric : MetricSpace Site] + cmp : Comparison Site + /-- The `Model` component of type `Atlas K Site`. -/ + B : Atlas K Site + /-- The `Model` component of type `G → Site`. -/ + mark : G → Site + prices : ∀ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (x : S → G), + (∀ i, x i ∈ s) → B.price (mark ∘ x) = A.price x + +attribute [instance] Model.metric + +open scoped Classical in +theorem exists_model (A : Atlas K G) (s : Finset G) : Nonempty (Model A s) := by + let T := ↥s ⊕ Bool + have : Nontrivial T := ⟨Sum.inr false, Sum.inr true, fun e => Bool.false_ne_true (Sum.inr.inj e)⟩ + let z : T → G := Sum.elim Subtype.val (fun _ => 1) + let y (g : G) : T := if h : g ∈ s then .inl ⟨g, h⟩ else .inr false + obtain ⟨_, h⟩ := A.valid z + obtain ⟨Y, _, _, p, C, B, hB⟩ := realize_atlas (spectralComparison K) h + refine ⟨{ Site := Y, cmp := C, B := B, mark := p ∘ y, prices := ?_ }⟩ + intro S _ _ _ x hx + rw [Function.comp_assoc, B.place, hB, ← A.place] + have he : z ∘ y ∘ x = x := by funext i; simp [y, z, hx i] + rw [he] + +namespace Model +variable {A : Atlas K G} {s t : Finset G} (M : Model A s) + +open scoped Classical in +/-- Computes the sq by the application `dsq (a.eval M.cmp M.mark) (b.eval M.cmp M.mark)`. -/ +def sq (a b : Term G) := dsq (a.eval M.cmp M.mark) (b.eval M.cmp M.mark) + +omit [Group G] in +open scoped Classical in +theorem marked {x y : G} (hx : x ∈ s) (hy : y ∈ s) : + dist (M.mark x) (M.mark y) = dist x y := by + have h := M.prices ![x, y] (by intro i; fin_cases i <;> assumption) + simpa only [Atlas.wire, Function.comp_apply, Matrix.cons_val_zero, Matrix.cons_val_one] + using congrFun h (Spectral.Tensor.wire K 0 1 2) + +open scoped Classical in +private theorem coord {Y Z S : Type} [MetricSpace Y] [MetricSpace Z] + [Fintype S] [DecidableEq S] [Nonempty S] {x : S → Y} {y : S → Z} (C : Comparison Y) + (D : Comparison Z) (P : Atlas K Y) (Q : Atlas K Z) + (he : P.price x = Q.price y) (a b : Term S) : + dsq (a.eval C x) (b.eval C x) = dsq (a.eval D y) (b.eval D y) := by + obtain ⟨B, hB⟩ := (Set.finite_range (fun i : S × S => dist (x i.1) (x i.2))).bddAbove + have hx i j := hB ⟨(i, j), rfl⟩ + have hy (i j : S) : dist (y i) (y j) ≤ B := by rw [← Q.wire y, ← he, P.wire]; exact hx i j + apply sub_eq_zero.mp + apply abs_nonpos_iff.mp + refine le_of_forall_gt_imp_ge_of_dense fun ε hε => ?_ + obtain ⟨_, δ, hδ, h⟩ := finite_terms_tests K {a, b} B hε + exact h C D (P.realized _ hx) (Q.realized _ hy) (by simp [he, hδ.le]) a (by simp) b (by simp) + +open scoped Classical in +/-- The value specified by `insert 1 (a.support ∪ b.support)`. -/ +def names (a b : Term G) : Finset G := insert 1 (a.support ∪ b.support) + +open scoped Classical in +theorem invariant (N : Model A t) (H : A.Invariant) (g : G) (a b : Term G) + (hs : names a b ⊆ s) (ht : ∀ i ∈ names a b, g * i ∈ t) : + M.sq a b = N.sq (g • a) (g • b) := by + let W := names a b + let _ : Nonempty ↥W := ⟨⟨1, Finset.mem_insert_self _ _⟩⟩ + let lift (i : G) : W := if h : i ∈ W then ⟨i, h⟩ else Classical.arbitrary _ + let x (i : W) := i.val + let y (i : W) := g * i.val + have he : M.B.price (M.mark ∘ x) = N.B.price (N.mark ∘ y) := by + rw [M.prices _ (fun i => hs i.property), N.prices _ (fun i => ht _ i.property)] + exact (H _ x g).symm + have ev (u : Term G) (h : u.support ⊆ W) : + (u.map lift).eval M.cmp (M.mark ∘ x) = u.eval M.cmp M.mark ∧ + (u.map lift).eval N.cmp (N.mark ∘ y) = (g • u).eval N.cmp N.mark := by + change _ ∧ _ = (u.map (g * ·)).eval _ _ + simp only [Term.eval_map] + constructor <;> apply Term.eval_congr <;> intro i hi <;> simp [lift, x, y, h hi] + obtain ⟨ha, ha'⟩ := ev a (fun _ hi => Finset.mem_insert_of_mem (Finset.mem_union_left _ hi)) + obtain ⟨hb, hb'⟩ := ev b (fun _ hi => Finset.mem_insert_of_mem (Finset.mem_union_right _ hi)) + have h := coord M.cmp N.cmp M.B N.B he (a.map lift) (b.map lift) + rwa [ha, hb, ha', hb'] at h + +end Model +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +end + +/- +# Completing an invariant family of marked points + +On each pair of formal segments the distance stabilizes as soon as +the finite model contains all their marks. The resulting table gives +an isometric action on a completion. Take simultaneous limits of +prices to retain the marking on this completion. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas + +open Routing Filter Topology +variable {G F : Type} [Group G] [Field F] [PseudoMetricSpace G] {A : Atlas F G} + +open scoped Classical in +private theorem table (M : ∀ s, Model A s) (H : A.Invariant) : + ∃ R : Term G → Term G → ℝ, Table R ∧ (∀ (g : G) a b, R (g • a) (g • b) = R a b) ∧ + ∀ a b, ∀ᶠ s : Finset G in atTop, R a b = (M s).sq a b := by + let R (a b) := (M (Model.names a b)).sq a b + have inv (g : G) (a b) : ∀ᶠ s : Finset G in atTop, R a b = (M s).sq (g • a) (g • b) := by + filter_upwards [eventually_ge_atTop ((Model.names a b).image (g * ·))] with s hs + exact Model.invariant _ _ H g a b le_rfl fun i hi => hs (Finset.mem_image_of_mem _ hi) + have he (a b) : ∀ᶠ s : Finset G in atTop, R a b = (M s).sq a b := by simpa using inv 1 a b + refine ⟨R, ⟨fun _ _ => sq_nonneg _, fun a => ?_, fun a b => ?_, fun a b c => ?_, + fun t a b c => ?_⟩, fun g a b => ?_, he⟩ + · simp [R, Model.sq, dsq] + · obtain ⟨s, hs, ht⟩ := ((he a b).and (he b a)).exists + rw [hs, ht] + simp only [Model.sq, dsq, dist_comm] + · obtain ⟨s, h₁, h₂, h₃⟩ := ((he a c).and ((he a b).and (he b c))).exists + simp only [h₁, h₂, h₃, Model.sq, dsq, Real.sqrt_sq dist_nonneg] + exact dist_triangle _ _ _ + · obtain ⟨s, h₁, h₂, h₃, h₄⟩ := + ((he (.seg t a b) c).and ((he a c).and ((he b c).and (he a b)))).exists + rw [h₁, h₂, h₃, h₄] + exact (M s).cmp.along t _ _ _ + · obtain ⟨s, h₁, h₂⟩ := ((he (g • a) (g • b)).and (inv g a b)).exists + exact h₁.trans h₂.symm + +open scoped Classical in +theorem action_hull (A : Atlas F G) (hd : ∀ i j : G, dist i j ≤ 1) (hinv : A.Invariant) : + ∃ (Y : Type) (_ : MetricSpace Y) (_ : CompleteSpace Y) (_ : MulAction G Y) + (_ : IsIsometricSMul G Y) (C : Comparison Y) (B : Atlas F Y) (o : Y), + DenseRange (Term.eval C (fun g : G => g • o)) ∧ + (∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (x : S → G), + B.price (fun i => x i • o) = A.price x) ∧ ∀ x y : Y, dist x y ≤ 2 := by + let M := fun s => Classical.choice (A.exists_model s) + obtain ⟨R, hR, hg, he⟩ := table M hinv + obtain ⟨Y, _, _, _, _, C, f, hf, hseg, hr, hact⟩ := hR.realize hg + let _ : PseudoMetricSpace (Term G) := PseudoMetricSpace.induced f inferInstance + let l := Ultrafilter.of (atTop : Filter (Finset G)) + have hl : (l : Filter (Finset G)) ≤ atTop := Ultrafilter.of_le _ + let u (s : Finset G) := Term.eval (M s).cmp (M s).mark + obtain ⟨B, hB⟩ := scaled_limit l (fun s => (M s).Site) (fun s => (M s).B) u + (fun _ => 1) (fun _ => zero_le_one) (fun a b => by + apply tendsto_const_nhds.congr' + filter_upwards [hl (he a b)] with s hs + rw [one_mul] + exact (sq_eq_sq₀ dist_nonneg dist_nonneg).mp ((hr a b).trans hs)) + obtain ⟨D, hD⟩ := B.dense f (Isometry.of_dist_eq fun _ _ => rfl) hf + let o := f (.mark 1) + have ho (i : G) : i • o = f (.mark i) := by + rw [← hact] + change f (.mark (i * 1)) = _ + rw [mul_one] + have eval : Term.eval C (fun g : G => g • o) = f := by + funext a + induction a with + | mark i => exact ho i + | seg t a b ha hb => rw [Term.eval, ha, hb, hseg] + have hp (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (x : S → G) : + D.price (fun i => x i • o) = A.price x := by + simp only [ho] + change D.price (f ∘ Term.mark ∘ x) = _ + rw [hD] + funext T + refine tendsto_nhds_unique (hB (Term.mark ∘ x) T) ?_ + apply tendsto_const_nhds.congr' + filter_upwards [hl (eventually_ge_atTop (Finset.univ.image x))] with s hs + rw [one_mul] + exact congrFun ((M s).prices x (fun i => hs (Finset.mem_image_of_mem x (Finset.mem_univ + i)))).symm T + refine ⟨Y, inferInstance, inferInstance, inferInstance, inferInstance, C, D, o, eval.symm ▸ hf, + hp, ?_⟩ + have near (a : Term G) : dist (f a) o ^ 2 ≤ 1 := by + induction a with + | mark g => + have h := congrFun (hp _ ![g, 1]) (Spectral.Tensor.wire F 0 1 2) + simp only [Atlas.wire, Matrix.cons_val_zero, Matrix.cons_val_one, ho] at h + have hg : dist (f (.mark g)) o ≤ 1 := h.le.trans (hd g 1) + simpa using pow_le_pow_left₀ dist_nonneg hg 2 + | seg t a b ha hb => + rw [hseg] + have ht := t.2.1 + have ht' := sub_nonneg.mpr t.2.2 + refine ((C.along t (f a) (f b) o).trans (sub_le_self _ (by positivity))).trans ?_ + linarith only [mul_le_mul_of_nonneg_left ha ht', mul_le_mul_of_nonneg_left hb ht] + have radius (x : Y) : dist x o ≤ 1 := by + refine hf.induction_on (p := fun y => dist y o + ≤ 1) x (isClosed_le (by fun_prop) continuous_const) ?_ + exact fun a => (sq_le_sq₀ dist_nonneg zero_le_one).mp (by simpa using near a) + exact fun x y => by linarith only [dist_triangle_right x y o, radius x, radius y] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Atlas +end + +/- +# Optimizing the sphere price + +Transport makes the quadratic objective coercive. One-site controls +therefore apply to actual maximizers. Their increments and the completed +square bound determine the limiting normalized price and widths. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Sphere Spectral Filter Finset +open scoped Topology + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + {Y : Type*} [MetricSpace Y] {x : A → Y} {P : Tensor F A → ℝ} + +omit [DecidableEq A] in +private theorem unit_objective (z : A → F) (n : ℕ) (e : A → ℕ) : + Budget.value (spherePrice P z) (fun _ => 1) n e = objective P z n e := by + simp [Budget.value, objective] + +theorem saturation_of_controlled (h : Controlled F Y) : Saturation F Y := by + intro A _ _ _ x o ho z hz + obtain ⟨P, hP, htest⟩ := h x o ho z hz + let D := ∑ i, dist o (x i) ^ 2 + have hD : 0 ≤ D := sum_nonneg fun _ _ => sq_nonneg _ + let R := 4 * (D + 1) / entropy ^ 2 + have hR : 0 < R := div_pos (by positivity) (sq_pos_of_pos entropy_pos) + obtain ⟨C, hc⟩ := htest R hR + have transport (e : A → ℕ) : spherePrice P z e ≤ ∑ i, dist o (x i) * (1 * width (e i)) := by + simpa using hP.spherePrice_le z e o + choose e he using Budget.maximizer transport le_rfl zero_lt_one (fun _ => le_rfl) + z (hP.spherePrice_nonneg _ _) (fun _ ht => hP.spherePrice_zero ht) + simp only [unit_objective] at he + let w (n : ℕ) i := width (e n i) / n + let B (n : ℕ) := objective P z n (e n) + have hb (n : ℕ) (hn : 0 < n) (i : A) : w n i ≤ 2 * (D + 1) ∧ (e n i : ℝ) ≤ R * (n : ℝ) ^ 2 := by + have hh := Budget.bounds transport le_rfl zero_lt_one (fun _ => le_rfl) n hn (e n) + (by rw [unit_objective]; exact (he n hn).1) i + simpa only [one_mul] using hh + have hlim : (∀ i, Tendsto (fun n => w n i) atTop (𝓝 (dist o (x i)))) ∧ + Tendsto (fun n => B n / n) atTop (𝓝 (D / 2)) := by + apply optimizer_limits (C := C) (by positivity : 0 ≤ 2 * (D + 1)) + · filter_upwards [eventually_gt_atTop 0] with n hn + exact (he n hn).1 + · filter_upwards [eventually_gt_atTop 0] with n hn + exact fun i => ⟨div_nonneg (width_nonneg _) (by positivity), (hb n hn i).1⟩ + · filter_upwards [eventually_gt_atTop 0, hc] with n hn htest + obtain ⟨_, hne, hm⟩ := he n hn + obtain ⟨δ, hδ, hδ', hδ''⟩ := htest (e n) hm (fun i => (hb n hn i).2) hne + refine ⟨δ, hδ, hδ', fun i g hg => ?_⟩ + rw [mul_assoc, ← width] + unfold w + rw [div_mul_eq_mul_div] + exact hδ'' i g hg + · filter_upwards with n + simpa only [unit_objective, one_mul] using Budget.squares transport n (e n) + · filter_upwards [eventually_gt_atTop 0] with n hn + unfold w B + have hi := Budget.increment (μ := fun _ => 1) (p := spherePrice P z) (e n) n hn + simp only [unit_objective, one_mul] at hi + rw [hi] + gcongr + exact (he (n + 1) (by omega)).2.2 _ + refine ⟨P, hP, e, hlim.1, ?_⟩ + have hs : Tendsto (fun n => ∑ i, (w n i) ^ 2) atTop (𝓝 D) := + tendsto_finsetSum _ (fun i _ => (hlim.1 i).pow 2) + have ht := hlim.2.add (hs.div_const 2) + rw [add_halves] at ht + apply ht.congr' + filter_upwards with n + unfold w B + have hi := Budget.normalize (μ := fun _ => 1) (p := spherePrice P z) n (e n) + simp only [unit_objective, one_mul] at hi + rw [hi, sub_add_cancel] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Fields.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Fields.lean new file mode 100644 index 0000000000..6829da1de5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Fields.lean @@ -0,0 +1,463 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Extension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometrySector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport + +/-! +# Normalization after changing the marked sites + +Placement preserves products but may lose additivity. Its action on +full diagonals determines an exponent. Taking the inverse power restores +additivity, as the binomial expansion has only linearly many types. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S T : Type} [Field K] [Fintype S] [Fintype T] + +theorem ordinary_mono {D E : ℝ} (h : D ≤ E) : ordinary K S D ⊆ ordinary K S E := by + rintro P ⟨d, ⟨hd, hd'⟩, f, hf, rfl⟩ + exact ⟨d, ⟨hd, hd'.trans h⟩, f, hf, rfl⟩ + +private theorem linear_loss {a b : ℝ} (hb : 0 ≤ b) + (h : ∀ n : ℕ, a ^ n ≤ (n + 1 : ℝ) * b ^ n) : a ≤ b := + TensorSpectrum.le_of_pow_le_polynomial_mul_pow b a 1 1 hb zero_lt_one + (fun n _ => by simpa only [Real.rpow_one, one_mul] using h n) + +theorem normalize_hom {R : Type*} [CommSemiring R] [PartialOrder R] + (hadd : ∀ x y z : R, x ≤ y → x + z ≤ y + z) (hz0 : ∀ x : R, 0 ≤ x) + (g : R →* ℝ) + (hm : Monotone g) (hz : g 0 = 0) (ha : ∀ a b, g (a + b) ≤ g a + g b) + {p : ℝ} (hp : 0 < p) (hn : ∀ n : ℕ, g n = (n : ℝ) ^ p) : + ∃ f : R →+* ℝ, Monotone f ∧ ∀ a, f a = g a ^ p⁻¹ := by + have h0 (a) : 0 ≤ g a := hz ▸ hm (hz0 a) + let j : R →* ℝ := + { toFun := fun a => g a ^ p⁻¹ + map_one' := by rw [map_one, Real.one_rpow] + map_mul' := fun a b => by rw [g.map_mul, Real.mul_rpow (h0 a) (h0 b)] } + have j0 (a) : 0 ≤ j a := Real.rpow_nonneg (h0 a) _ + have jm : Monotone j := fun a _ h => + Real.rpow_le_rpow (h0 a) (hm h) (inv_nonneg.mpr hp.le) + have jn (n : ℕ) : j n = (n : ℝ) := by + change g n ^ p⁻¹ = _ + rw [hn, Real.rpow_rpow_inv (Nat.cast_nonneg _) hp.ne'] + have sum_le (U : Finset ℕ) (A : ℕ → R) : + g (∑ i ∈ U, A i) ≤ ∑ i ∈ U, g (A i) := by + induction U using Finset.induction_on with + | empty => simp [hz] + | insert i U hi ih => + rw [Finset.sum_insert hi, Finset.sum_insert hi] + exact (ha _ _).trans (add_le_add le_rfl ih) + have ja (x y : R) : j (x + y) = j x + j y := by + let A (n i : ℕ) := x ^ i * y ^ (n - i) * (n.choose i : R) + let U (n : ℕ) := Finset.range (n + 1) + have e (n : ℕ) : (x + y) ^ n = ∑ i ∈ U n, A n i := add_pow x y n + have e' (n : ℕ) : (j x + j y) ^ n = ∑ i ∈ U n, j (A n i) := by + simp only [A, U, j.map_mul, map_pow, jn, add_pow] + have hs := add_nonneg (j0 x) (j0 y) + apply le_antisymm + · apply (Real.rpow_inv_le_iff_of_pos (h0 _) hs hp).mpr + apply linear_loss (Real.rpow_nonneg hs _) + intro n + rw [← map_pow, e, Real.rpow_pow_comm hs] + refine (sum_le _ _).trans ?_ + have hl (i : ℕ) (hi : i ∈ U n) : g (A n i) ≤ ((j x + j y) ^ n) ^ p := by + apply (Real.rpow_inv_le_iff_of_pos (h0 _) (pow_nonneg hs n) hp).mp + change j (A n i) ≤ _ + rw [e'] + exact Finset.single_le_sum (fun i _ => j0 (A n i)) hi + simpa [U, nsmul_eq_mul] using Finset.sum_le_card_nsmul (U n) _ _ hl + · apply linear_loss (j0 _) + intro n + rw [e', ← map_pow, e] + have hl (i : ℕ) (hi : i ∈ U n) : j (A n i) ≤ j (∑ t ∈ U n, A n t) := by + apply jm + rw [← Finset.add_sum_erase (U n) (A n) hi, add_comm] + exact (zero_add _).symm.trans_le (hadd 0 _ (A n i) (hz0 _)) + simpa [U, nsmul_eq_mul] using Finset.sum_le_card_nsmul (U n) _ _ hl + exact ⟨{ j with map_add' := ja, map_zero' := by simpa using jn 0 }, jm, fun _ => rfl⟩ + +open scoped NNReal in +theorem zero_ordinary [Nontrivial S] {D : ℝ} (hD : 0 ≤ D) : + (0 : Tensor K S → ℝ) ∈ ordinary K S D := by + have h (a b : ℕ) (hab : (a : Tensor K S) ≤ b) : (a : ℝ≥0) ≤ b := + Nat.cast_le.mpr ((natCast_le_iff _ _).mp hab) + obtain ⟨g, hg, _⟩ := Spectrum.extension add_le_add_right mul_le_mul_left zero_le + one_le exists_bound (Nat.castRingHom (Tensor K S)) (Nat.castRingHom ℝ≥0) h + exact ⟨0, ⟨le_rfl, hD⟩, NNReal.toRealHom.comp g, hg, funext fun _ => (zero_mul _).symm⟩ + +variable [DecidableEq S] [DecidableEq T] + +private theorem diagonal_cost [Nonempty S] (x : S → T) (c : S) + (f : Tensor K T →+* ℝ) (hf : Monotone f) : + Real.log (f (place x (2 : Tensor K S))) / Real.log 2 ≤ ∑ i, dist f (x i) (x c) := by + let A := Raw.shared K (Finset.univ : Finset S) 2 + have e : ofRaw A = 2 := shared_all K 2 + have h : ofRaw A ≠ 0 := by + have hn := natCast_le (K := K) (S := S) (by decide : 1 ≤ 2) + rw [Nat.cast_one, Nat.cast_ofNat, ← e] at hn + exact fun hz => one_ne_zero (le_antisymm (hn.trans_eq hz) (zero_le _)) + let y := fun _ : S => x c + have hy : place y (ofRaw A) = 1 := by + change place y (shared K _ _) = _ + rw [place_shared, Finset.image_const Finset.univ_nonempty (x c)] + simpa [wire] using wire_self K (x c) (n := 2) (by decide) + have hd := (le_abs_self _).trans (price_transport f hf A h x y) + rw [hy, e, map_one, Real.log_one, sub_zero] at hd + have hc (s : S) : Fintype.card (A.leg s) = 2 := Fintype.card_fin 2 + rw [div_le_iff₀ (Real.log_pos (by norm_num)), Finset.sum_mul] + simpa only [hc, Nat.cast_ofNat, y] using hd + +variable [Nontrivial S] + +/-- The scale on the marked sites is bounded by the total cost of moving +each leg of their binary diagonal to one common site. -/ +theorem ordinary_restrict {D E : ℝ} {P : Tensor K T → ℝ} + (hP : P ∈ ordinary K T D) (x : S → T) + (he : ∀ i j, P (wire K (x i) (x j) 2) ≤ E) : + (P ∘ place x) ∈ ordinary K S (E * Fintype.card S) := by + obtain ⟨d, ⟨hd, _⟩, f, hf, rfl⟩ := hP + let g : Tensor K S →* ℝ := + { toFun := fun A => f (place x A) + map_one' := by rw [place_one, f.map_one] + map_mul' := fun A B => by rw [place_mul, f.map_mul] } + have hm : Monotone g := hf.comp (place_mono x) + have hz : g 0 = 0 := by change f (place x 0) = _; rw [place_zero, f.map_zero] + have ha (a b) : g (a + b) ≤ g a + g b := + (hf (place_add_le x a b)).trans_eq (f.map_add _ _) + have hu (n : ℕ) : g (n : Tensor K S) ≤ (n : ℝ) := by + induction n with + | zero => simp [hz] + | succ n ih => + rw [Nat.cast_succ, Nat.cast_succ] + exact (ha _ _).trans (add_le_add ih g.map_one.le) + obtain ⟨p, hp, _, hn⟩ := TensorSpectrum.exists_power_of_monotone_multiplicative + (fun n => g (n : Tensor K S)) + (fun _ _ _ _ => by rw [Nat.cast_mul, g.map_mul]) + (fun _ _ _ h => hm (natCast_le h)) + (fun n h => ⟨by simpa using hm (natCast_le h), hu n⟩) + have ep : Real.log (g 2) / Real.log 2 = p := by + have e := hn 2 (by decide) + simp only [Nat.cast_ofNat] at e + rw [e, Real.log_rpow (by norm_num), mul_div_cancel_right₀ _ (Real.log_pos (by norm_num)).ne'] + let c := Classical.arbitrary S + have hb : d * p ≤ E * Fintype.card S := calc + _ ≤ d * ∑ i, dist f (x i) (x c) := + mul_le_mul_of_nonneg_left (ep ▸ diagonal_cost x c f hf) hd + _ = ∑ i, d * dist f (x i) (x c) := Finset.mul_sum _ _ _ + _ ≤ ∑ _i : S, E := Finset.sum_le_sum fun i _ => he i c + _ = _ := by simp [mul_comm] + rcases hp.eq_or_lt with rfl | hp + · have ez : values d f ∘ place x = 0 := by + funext a + change d * (Real.log (g a) / Real.log 2) = 0 + by_cases h : a = 0 + · simp [h, hz] + obtain ⟨n, h'⟩ := exists_bound a + have hl : 1 ≤ g a := by simpa using hm (one_le a h) + have hh := hm (h'.trans (natCast_le (Nat.le_succ n))) + rw [hn (n + 1) (by omega), Real.rpow_zero] at hh + rw [le_antisymm hh hl, Real.log_one, zero_div, mul_zero] + rw [ez] + exact zero_ordinary (by simpa using hb) + · have hn' (n : ℕ) : g n = (n : ℝ) ^ p := by + cases n with + | zero => simp [hz, Real.zero_rpow hp.ne'] + | succ n => exact hn _ (by omega) + obtain ⟨j, hj, ej⟩ := normalize_hom add_le_add_right zero_le g hm hz ha hp hn' + refine ⟨d * p, ⟨mul_nonneg hd hp.le, hb⟩, j, hj, ?_⟩ + funext a + change d * (Real.log (g a) / Real.log 2) = d * p * (Real.log (j a) / Real.log 2) + by_cases h : a = 0 + · simp [h, hz] + have hg : 0 < g a := price_place_pos f hf x h + rw [ej, Real.log_rpow hg, mul_assoc, ← mul_div_assoc p, ← mul_assoc p, + mul_inv_cancel₀ hp.ne', one_mul] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- # Limits of spectral wire metrics -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Filter Topology + +/-- The wire models of type `Prop` for the given inputs. -/ +def WireModels (K Y : Type) [Field K] [PseudoMetricSpace Y] : Prop := + ∀ (B : Type) [Fintype B] [DecidableEq B] [Nonempty B] (z : B → Y) (D : ℝ), + 0 < D → (∀ i j, dist (z i) (z j) ≤ D) → + ∃ P : Tensor K B → ℝ, (P = 0 ∨ P ∈ Tensor.ordinary K B (D * Fintype.card B)) ∧ + ∀ i j, P (Tensor.wire K i j 2) = dist (z i) (z j) + +namespace WireModels +variable {K X Y B : Type} [Field K] [PseudoMetricSpace X] [PseudoMetricSpace Y] + +private theorem point [Fintype B] [DecidableEq B] [Nontrivial B] (h : WireModels K Y) (z : B → Y) : + ∃ d : ℝ, 0 ≤ d ∧ ∃ f : Tensor K B →+* ℝ, Monotone f ∧ + ∀ i j, dist (z i) (z j) = d * Tensor.dist f i j := by + obtain ⟨D, hD⟩ := (Set.finite_range (fun p : B × B => dist (z p.1) (z p.2))).bddAbove + have hb (i j : B) : dist (z i) (z j) ≤ max D 1 := (hD ⟨(i, j), rfl⟩).trans (le_max_left _ _) + obtain ⟨P, hP, he⟩ := h B z _ (zero_lt_one.trans_le (le_max_right _ _)) hb + have hp : P ∈ Tensor.ordinary K B (max D 1 * Fintype.card B) := by + rcases hP with rfl | hp + · exact Tensor.zero_ordinary (by positivity) + · exact hp + obtain ⟨d, hd, f, hf, rfl⟩ := hp + exact ⟨d, hd.1, f, hf, fun i j => (he i j).symm⟩ + +theorem busemann (h : WireModels K Y) : Busemann Y := by + intro t x y m a b n hx ha + let z := ![x, y, m, a, b, n] + obtain ⟨d, hd, f, hf, he⟩ := point h z + change Divides t (z 0) (z 1) (z 2) at hx + change Divides t (z 3) (z 4) (z 5) at ha + change dist (z 2) (z 5) ≤ (1 - t.val) * dist (z 0) (z 3) + t.val * dist (z 1) (z 4) + simp only [Divides, he] at hx ha ⊢ + rcases hd.eq_or_lt with rfl | hd + · simp + have cancel {u v w : ℝ} (h : d * u = w * (d * v)) : u = w * v := + mul_left_cancel₀ hd.ne' (h.trans (mul_left_comm _ _ _)) + have H := Tensor.busemann f hf (cancel hx.1) (cancel hx.2) (cancel ha.1) (cancel ha.2) + linarith only [mul_le_mul_of_nonneg_left H hd.le] + +theorem cuts (h : WireModels K Y) (hc : Sphere.ShiftedCrossing K) : CutBound (dist : Y → Y → ℝ) + := by + intro x x' y y' z z' w w' t u α β ht hu ha hb hq + let e := ![x, x', y, y', z, z', w, w'] + obtain ⟨d, hd, f, hf, he⟩ := point h e + have H := shifted_metric hc f hf 0 1 2 3 4 5 6 7 t u α β ht hu ha hb hq + rcases H with h | h + · left + change t * (dist (e 0) (e 1) - dist (e 0) (e 4) - dist (e 1) (e 5)) + + u * (dist (e 2) (e 3) - dist (e 2) (e 4) - dist (e 3) (e 5)) ≤ α * dist (e 4) (e 5) + simp only [he] + linarith only [mul_le_mul_of_nonneg_left h hd] + · right + change t * (dist (e 0) (e 1) - dist (e 0) (e 6) - dist (e 1) (e 7)) + + u * (dist (e 2) (e 3) - dist (e 2) (e 7) - dist (e 3) (e 6)) ≤ β * dist (e 6) (e 7) + simp only [he] + linarith only [mul_le_mul_of_nonneg_left h hd] + +/-- Finite models persist under pointwise limits of rescaled distances. -/ +theorem limit (h : WireModels K X) (u : Ultrafilter ℕ) (x : ℕ → Y → X) + (hh : ∀ a b, Tendsto (fun n : ℕ => ((n : ℝ) + 1) * dist (x n a) (x n b)) + (u : Filter ℕ) (𝓝 (dist a b))) : WireModels K Y := by + intro B _ _ _ z D _ hz + rcases subsingleton_or_nontrivial B with hB | hB + · refine ⟨0, Or.inl rfl, fun i j => ?_⟩ + rw [Subsingleton.elim i j, dist_self] + rfl + choose d hd f hf he using fun n => point h (x n ∘ z) + let P (n : ℕ) := Tensor.values (((n : ℝ) + 1) * d n) (f n) + have hp (n : ℕ) : P n ∈ Tensor.ordinary K B (((n : ℝ) + 1) * d n) := + ⟨_, ⟨mul_nonneg (by positivity) (hd n), le_rfl⟩, f n, hf n, rfl⟩ + have hw (i j : B) : Tendsto (fun n => P n (Tensor.wire K i j 2)) + (u : Filter ℕ) (𝓝 (dist (z i) (z j))) := by + refine (hh _ _).congr' (Eventually.of_forall fun n => ?_) + change ((n : ℝ) + 1) * dist ((x n ∘ z) i) ((x n ∘ z) j) = + ((n : ℝ) + 1) * d n * Tensor.dist (f n) i j + rw [he, mul_assoc] + have hb : ∀ᶠ n in (u : Filter ℕ), P n ∈ Tensor.ordinary K B ((D + 1) * Fintype.card B) := by + have hd : ∀ᶠ n in (u : Filter ℕ), ∀ i j, P n (Tensor.wire K i j 2) ≤ D + 1 := + eventually_all.mpr fun i => eventually_all.mpr fun j => + (hw i j).eventually (eventually_le_nhds ((hz i j).trans_lt (lt_add_one D))) + filter_upwards [hd] with n hn + simpa only [Function.comp_def, Tensor.place_id] using Tensor.ordinary_restrict (hp n) id hn + obtain ⟨Q, hQ, hq⟩ := (Tensor.compact_ordinary _).ultrafilter_le_nhds' + (u.map P) (Filter.mem_map.mpr hb) + have eq (i j : B) : Q (Tensor.wire K i j 2) = dist (z i) (z j) := + tendsto_nhds_unique (tendsto_pi_nhds.mp hq _) (hw i j) + refine ⟨Q, Or.inr ?_, eq⟩ + have h' := Tensor.ordinary_restrict hQ id fun i j => (eq i j).le.trans (hz i j) + simpa only [Function.comp_def, Tensor.place_id] using h' + +end WireModels +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Compatible prices from finite wire models + +For fixed marks, the possible compatible prices on them form a +directed family of compact sets as further names are prescribed. +Extension of scalars therefore only needs to preserve wire models. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +open scoped NNReal + +variable {K L S : Type} [Field K] [Field L] [Fintype S] [DecidableEq S] + +theorem map_wire (φ : K →+* L) (x y : S) (n : ℕ) : + map φ (wire K x y n) = wire L x y n := by + apply ofRaw_eq + refine Raw.relabel (Equiv.refl _) (fun _ => Equiv.refl _) fun i s j => ?_ + change Fin n at i j + change φ (if j = Raw.port {x, y} s i then 1 else 0) = if j = Raw.port {x, y} s i then 1 else 0 + split <;> simp + +omit [DecidableEq S] in +theorem extend_field_real [Nonempty S] [Algebra K L] (f : Tensor K S →+* ℝ) (hf : Monotone f) : + ∃ g : Tensor L S →+* ℝ, Monotone g ∧ ∀ A, g (map (algebraMap K L) A) = f A := by + have h (A : Tensor K S) : 0 ≤ f A := by simpa using hf (zero_le A) + let g : Tensor K S →+* ℝ≥0 := + { toFun := fun A => ⟨f A, h A⟩ + map_zero' := Subtype.ext (map_zero f) + map_one' := Subtype.ext (map_one f) + map_add' := fun a b => Subtype.ext (f.map_add a b) + map_mul' := fun a b => Subtype.ext (f.map_mul a b) } + obtain ⟨p, hp, he⟩ := extend_field L g hf + exact ⟨NNReal.toRealHom.comp p, hp, fun A => congrArg NNReal.toReal (he A)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Set + +variable {K S Y : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + +theorem WireModels.extend_field [PseudoMetricSpace Y] (h : WireModels K Y) + (L : Type) [Field L] [Algebra K L] : WireModels L Y := by + intro B _ _ _ z D hp hb + obtain ⟨P, h | ⟨d, hd, f, hf, rfl⟩, he⟩ := h B z D hp hb + · rw [h] at he + exact ⟨0, Or.inl rfl, he⟩ + · obtain ⟨g, hg, eg⟩ := Tensor.extend_field_real (L := L) f hf + refine ⟨Tensor.values d g, .inr ⟨d, hd, g, hg, rfl⟩, fun i j => ?_⟩ + rw [← he i j, Tensor.values, Tensor.values, ← eg, Tensor.map_wire] + +variable [MetricSpace Y] + +theorem SpectralSpace.wireModels (h : SpectralSpace K Y) : WireModels K Y := by + intro B _ _ _ x D hd hb + rcases subsingleton_or_nontrivial B with hB | hB + · exact ⟨0, .inl rfl, fun i j => by rw [Subsingleton.elim i j, dist_self]; rfl⟩ + obtain ⟨P, _, hp⟩ := h B x + have hz (i j : B) := (hb i j).trans (show D ≤ 2 * D by linarith) + obtain ⟨Q, hQ, _, eq⟩ := (hp D hd hb).2 B x (fun i j => by cases i <;> cases j <;> exact hz _ _) + have he (i j : B) : Q (Tensor.wire K (.inl i) (.inl j) 2) = dist (x i) (x j) := eq _ _ + exact ⟨Q ∘ Tensor.place Sum.inl, + .inr (Tensor.ordinary_restrict hQ Sum.inl fun i j => (he i j).le.trans (hb i j)), + fun i j => by rw [Function.comp_apply, Tensor.place_wire, he]⟩ + +private structure More (Y : Type) where + U : Type + [finiteSites : Fintype U] + [eqSites : DecidableEq U] + [inh : Nonempty U] + z : U → Y + +attribute [instance] More.finiteSites More.eqSites More.inh + +private instance (s : More Y) : Nontrivial (S ⊕ s.U) := + ⟨.inl (Classical.arbitrary _), .inr (Classical.arbitrary _), by simp⟩ + +private def feasible (x : S → Y) (s : More Y) : Set (Tensor K S → ℝ) := + {P | ∃ D Q, Q ∈ Tensor.ordinary K (S ⊕ s.U) D ∧ (∀ A, Q (Tensor.pad s.U A) = P A) ∧ + ∀ i j, Q (Tensor.wire K i j 2) = dist (Sum.elim x s.z i) (Sum.elim x s.z j)} + +private theorem feasible_bound (x : S → Y) (s : More Y) {P : Tensor K S → ℝ} + (h : P ∈ feasible x s) (E : ℝ) (he : ∀ i j, dist (Sum.elim x s.z i) (Sum.elim x s.z j) ≤ E) : + ∃ Q ∈ Tensor.ordinary K (S ⊕ s.U) (E * Fintype.card (S ⊕ s.U)), + (∀ A, Q (Tensor.pad s.U A) = P A) ∧ + ∀ i j, Q (Tensor.wire K i j 2) = dist (Sum.elim x s.z i) (Sum.elim x s.z j) := by + obtain ⟨_, Q, hQ, hp, hw⟩ := h + refine ⟨Q, ?_, hp, hw⟩ + have h' := Tensor.ordinary_restrict hQ id fun i j => (hw i j).le.trans (he i j) + simpa only [Function.comp_def, Tensor.place_id] using h' + +omit [DecidableEq S] [Nonempty S] in +omit [Fintype S] in +private theorem diameter_bound [Finite S] (z : S → Y) : ∃ D > 0, ∀ i j, dist (z i) (z j) ≤ D := by + let : Fintype S := Fintype.ofFinite S + obtain ⟨D, hD⟩ := (Set.finite_range (fun p : S × S => dist (z p.1) (z p.2))).bddAbove + exact ⟨max D 1, zero_lt_one.trans_le (le_max_right _ _), + fun i j => (hD ⟨(i, j), rfl⟩).trans (le_max_left _ _)⟩ + +private theorem feasible_compact (x : S → Y) (s : More Y) : IsCompact (feasible (K := K) x s) := by + let z := Sum.elim x s.z + obtain ⟨D, _, hd⟩ := diameter_bound z + let V := Tensor.ordinary K (S ⊕ s.U) (D * Fintype.card (S ⊕ s.U)) ∩ + {Q | ∀ i j, Q (Tensor.wire K i j 2) = dist (z i) (z j)} + have hc : IsCompact V := by + apply (Tensor.compact_ordinary _).inter_right + simp only [ofPred_forall] + exact isClosed_iInter fun i => isClosed_iInter fun j => + isClosed_eq (continuous_apply _) continuous_const + let p (Q : Tensor K (S ⊕ s.U) → ℝ) := Q ∘ Tensor.pad s.U + have hp : feasible x s = p '' V := by + ext P + constructor + · intro h + obtain ⟨Q, hQ, he, hw⟩ := feasible_bound x s h D hd + exact ⟨Q, ⟨hQ, hw⟩, funext he⟩ + · rintro ⟨Q, ⟨hQ, hw⟩, rfl⟩ + exact ⟨_, Q, hQ, fun _ => rfl, hw⟩ + rw [hp] + exact hc.image (continuous_pi fun _ => continuous_apply _) + +private theorem feasible_mono (x : S → Y) (s t : More Y) (e : s.U → t.U) + (he : ∀ i, t.z (e i) = s.z i) : feasible (K := K) x t ⊆ feasible x s := by + rintro P ⟨_, Q, hQ, hp, hw⟩ + let f := Sum.map (id : S → S) e + have hf (i) : Sum.elim x t.z (f i) = Sum.elim x s.z i := by + cases i with + | inl => rfl + | inr => exact he _ + have H (i j) : Q (Tensor.wire K (f i) (f j) 2) = dist (Sum.elim x s.z i) (Sum.elim x s.z j) := by + rw [hw, hf, hf] + obtain ⟨D, _, hd⟩ := diameter_bound (Sum.elim x s.z) + refine ⟨_, Q ∘ Tensor.place f, Tensor.ordinary_restrict hQ f (fun i j + => (H i j).le.trans (hd i j)), + fun A => ?_, fun i j => by rw [Function.comp_apply, Tensor.place_wire, H]⟩ + rw [Function.comp_apply, ← Tensor.place_inl, ← Tensor.place_comp, + show f ∘ Sum.inl = Sum.inl from rfl, Tensor.place_inl, hp] + +theorem WireModels.spectralSpace (h : WireModels K Y) : SpectralSpace K Y := by + intro S _ _ _ x + let V := feasible (K := K) x + let _ : Nonempty (More Y) := ⟨⟨S, x⟩⟩ + have hc (s) := feasible_compact (K := K) x s + have hn (s) : (V s).Nonempty := by + obtain ⟨D, hd, hb⟩ := diameter_bound (Sum.elim x s.z) + obtain ⟨Q, hQ, he⟩ := h _ _ D hd hb + have ho : Q ∈ Tensor.ordinary K (S ⊕ s.U) (D * Fintype.card (S ⊕ s.U)) := + hQ.elim (fun e => e.symm ▸ Tensor.zero_ordinary (by positivity)) id + exact ⟨Q ∘ Tensor.pad s.U, _, Q, ho, fun _ => rfl, he⟩ + have hd : Directed (· ⊇ ·) V := by + intro s t + let u : More Y := ⟨s.U ⊕ t.U, Sum.elim s.z t.z⟩ + exact ⟨u, feasible_mono x s u Sum.inl fun _ => rfl, feasible_mono x t u Sum.inr fun _ => rfl⟩ + obtain ⟨P, hP⟩ := IsCompact.nonempty_iInter_of_directed_nonempty_isCompact_isClosed + V hd hn hc (fun s => (hc s).isClosed) + have hp (s) := Set.mem_iInter.mp hP s + refine ⟨P, ?_, fun D _ hD => ⟨hD, ?_⟩⟩ + · obtain ⟨_, Q, _, e, w⟩ := hp ⟨S, x⟩ + intro a b + rw [← e, ← Tensor.place_inl, Tensor.place_wire] + exact w _ _ + · intro U _ _ _ z hz + exact feasible_bound x ⟨U, z⟩ (hp _) _ hz + +theorem SpectralSpace.extend_field (h : SpectralSpace K Y) (L : Type) [Field L] [Algebra K L] : + SpectralSpace L Y := + (h.wireModels.extend_field L).spectralSpace + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Finite.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Finite.lean new file mode 100644 index 0000000000..85451e4dc7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Finite.lean @@ -0,0 +1,507 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Extra +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport + +/-! +# Price determination at geodesic sites + +An extension adds duplicate sites with upper bounds on every evaluation. +The prescribed endpoint inequalities and Busemann convexity identify +these duplicates up to distance zero. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S T U V : Type} [Field K] + [Fintype S] [Fintype T] [Fintype U] [Fintype V] + [DecidableEq S] [DecidableEq T] [DecidableEq U] [DecidableEq V] + +private theorem place_prod {I : Type*} (f : S → T) (X : I → Tensor K S) (w : List I) : + place f (w.map X).prod = (w.map (fun i => place f (X i))).prod := by + induction w with + | nil => exact place_one f + | cons i w ih => rw [List.map_cons, List.prod_cons, place_mul, ih]; rfl + +variable [Nonempty S] + +/-- Additional old sites do not change closure tests on the marked ones. -/ +theorem enlarge_base {I : Type*} (f : Tensor K (S ⊕ V) →+* ℝ) (hf : Monotone f) + (X : I → Tensor K (S ⊕ U)) (p : I → ℝ) + (ht : ∀ w : List I, ∀ B, pad U B ≤ (w.map X).prod → f (pad V B) ≤ (w.map p).prod) : + ∃ g : Tensor K ((S ⊕ V) ⊕ U) →+* ℝ, Monotone g ∧ + (∀ B, g (pad U B) = f B) ∧ ∀ i, g (place (Sum.map Sum.inl id) (X i)) ≤ p i := by + apply (extension_iff f hf (fun i => place (Sum.map Sum.inl id) (X i)) p).mpr + intro w B hB + rw [← place_prod] at hB + obtain ⟨C, hC, hX⟩ := close_extra hB + exact (hf hC).trans (ht w C hX) + +theorem place_sum_inl (x : S → T) (z : U → T) (A : Tensor K S) : + place (Sum.elim x z) (pad U A) = place x A := by + rw [← place_inl, ← place_comp] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- # Geodesic determination on finite placements -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S T U V : Type} [Field K] + [Fintype S] [Fintype T] [Fintype U] [Fintype V] + [DecidableEq S] [DecidableEq T] [DecidableEq U] [DecidableEq V] + [Nonempty S] [Nonempty T] [Nonempty V] + +/-- Compare possibly repeated finite markings by their prices. -/ +def Agree (P : Tensor K V → ℝ) (Q : Tensor K T → ℝ) (x : S → V) (y : S → T) : Prop := + ∀ A, P (place x A) = Q (place y A) + +/-- Computes the gap by the application `P (wire K a b 2)`. -/ +def gap (P : Tensor K S → ℝ) (a b : S) : ℝ := P (wire K a b 2) + +/-- Requires `gap P a x = t * gap P a b ∧ gap P x b = (1 - t) * gap P a b`. -/ +def AtFraction (P : Tensor K S → ℝ) (a x b : S) (t : ℝ) : Prop := + gap P a x = t * gap P a b ∧ gap P x b = (1 - t) * gap P a b + +omit [Nonempty S] [Nonempty T] [Nonempty V] in +theorem Agree.gap {P : Tensor K V → ℝ} {Q : Tensor K T → ℝ} {x : S → V} {y : S → T} + (h : Agree P Q x y) (a b : S) : gap P (x a) (x b) = gap Q (y a) (y b) := by + simpa only [Tensor.gap, place_wire] using h (wire K a b 2) + +omit [Nonempty S] [Nonempty T] [Nonempty V] in +theorem Agree.comp {P : Tensor K V → ℝ} {Q : Tensor K T → ℝ} {x : S → V} {y : S → T} + (h : Agree P Q x y) (e : U → S) : Agree P Q (x ∘ e) (y ∘ e) := by + intro A + rw [place_comp, place_comp, h] + +/-- An upper bound on prices stable under products and restrictions. -/ +structure Cap (P : Tensor K S → ℝ) : Prop where + unit : P 1 = 0 + nonneg : ∀ A, 0 ≤ P A + mono : Monotone P + sub : ∀ A B, P (A * B) ≤ P A + P B + +omit [DecidableEq S] in +theorem cap_ordinary {P : Tensor K S → ℝ} {D : ℝ} (h : P ∈ ordinary K S D) : Cap P := by + obtain ⟨d, hd, f, hf, rfl⟩ := h + have hi := values_nonneg hd.1 hf + have hz : values d f 0 = 0 := by simp [values] + refine ⟨by simp [values], hi, ?_, ?_⟩ + · intro A B h + by_cases ha : A = 0 + · rw [ha, hz] + exact hi B + have hl := Real.log_le_log (zero_lt_one.trans_le (value_one_le hf ha)) (hf h) + exact mul_le_mul_of_nonneg_left (div_le_div_of_nonneg_right hl (Real.log_nonneg (by norm_num))) + hd.1 + · intro A B + by_cases ha : A = 0 + · rw [ha, zero_mul, hz, zero_add]; exact hi _ + by_cases hb : B = 0 + · rw [hb, mul_zero, hz, add_zero]; exact hi _ + unfold values + rw [map_mul, Real.log_mul (zero_lt_one.trans_le (value_one_le hf ha)).ne' + (zero_lt_one.trans_le (value_one_le hf hb)).ne', add_div, mul_add] + +omit [Nonempty S] [Nonempty T] in +theorem Cap.place {P : Tensor K T → ℝ} (h : Cap P) (x : S → T) : Cap (P ∘ Tensor.place x) where + unit := by rw [Function.comp_apply, place_one, h.unit] + nonneg _ := h.nonneg _ + mono := h.mono.comp (place_mono x) + sub A B := by simp only [Function.comp_apply, place_mul]; exact h.sub _ _ + +omit [DecidableEq S] [Nonempty S] in +theorem Cap.weighted {J : Type*} [Fintype J] {P : J → Tensor K S → ℝ} + (h : ∀ j, Cap (P j)) (w : J → ℝ) (hw : ∀ j, 0 ≤ w j) : + Cap (fun A => ∑ j, w j * P j A) where + unit := by simp [(h _).unit] + nonneg A := Finset.sum_nonneg fun j _ => mul_nonneg (hw j) ((h j).nonneg A) + mono := fun _ _ hab => Finset.sum_le_sum fun j _ + => mul_le_mul_of_nonneg_left ((h j).mono hab) (hw j) + sub A B := by + rw [← Finset.sum_add_distrib] + exact Finset.sum_le_sum fun j _ => (mul_le_mul_of_nonneg_left ((h j).sub A B) (hw j)).trans_eq + (mul_add _ _ _) + +omit [DecidableEq S] in +private theorem values_le {d : ℝ} (hd : 0 < d) {f : Tensor K S →+* ℝ} (hf : Monotone f) + (A : Tensor K S) {r : ℝ} (hr : 0 ≤ r) : values d f A ≤ r ↔ f A ≤ (2 : ℝ) ^ (r / d) := by + by_cases h : A = 0 + · simp [values, h, hr, Real.rpow_nonneg] + have hp := zero_lt_one.trans_le (value_one_le hf h) + have ht : 0 < (2 : ℝ) := by norm_num + rw [values, mul_comm d, ← le_div_iff₀ hd, div_le_iff₀ (Real.log_pos (by norm_num)), + ← Real.log_rpow ht, Real.log_le_log_iff hp (Real.rpow_pos_of_pos ht _)] + +/-- A submean inequality propagates whenever the two endpoint wire +bounds force the prescribed positions on their geodesics. -/ +theorem Cap.geodesic_le {D : ℝ} {P : Tensor K V → ℝ} (hP : P ∈ ordinary K V D) + {Q : Tensor K (S ⊕ U) → ℝ} (hQ : Cap Q) (x : S → V) (p : U → V) + (h : ∀ A, P (Tensor.place x A) ≤ Q (pad U A)) + (he : ∀ u, ∃ a b t, AtFraction P (x a) (p u) (x b) t ∧ + gap Q (.inl a) (.inr u) ≤ gap P (x a) (p u) ∧ + gap Q (.inr u) (.inl b) ≤ gap P (p u) (x b)) : + ∀ A, P (Tensor.place (Sum.elim x p) A) ≤ Q A := by + obtain ⟨d, hd, f, hf, rfl⟩ := hP + rcases hd.1.eq_or_lt with rfl | hd + · exact fun A => by simpa [values] using hQ.nonneg A + let e := Sum.elim x id + have es : Function.Surjective e := fun v => ⟨.inr v, rfl⟩ + let f' := f.comp (group e es) + have hf' : Monotone f' := hf.comp (group_mono e es) + let v (A : Tensor K (S ⊕ U)) := (2 : ℝ) ^ (Q A / d) + have prod (w : List (Tensor K (S ⊕ U))) : v w.prod ≤ (w.map v).prod := by + induction w with + | nil => simp [v, hQ.unit] + | cons A w ih => + rw [List.prod_cons, List.map_cons, List.prod_cons] + refine le_trans ?_ (mul_le_mul_of_nonneg_left ih (show 0 ≤ v A by unfold v; positivity)) + unfold v + rw [← Real.rpow_add (by norm_num), ← add_div] + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) + (div_le_div_of_nonneg_right (hQ.sub _ _) hd.le) + obtain ⟨k, hk, ek, hkp⟩ := enlarge_base f' hf' id v (fun w A ha => by + rw [List.map_id] at ha + change f (Tensor.place (Sum.elim x id) (pad V A)) ≤ _ + rw [place_sum_inl] + exact ((values_le hd hf _ (hQ.nonneg _)).mp ((h A).trans (hQ.mono ha))).trans (prod w)) + let L : S ⊕ U → (S ⊕ V) ⊕ U := Sum.inl ∘ Sum.map id p + let R : S ⊕ U → (S ⊕ V) ⊕ U := Sum.map Sum.inl id + have left (A : Tensor K (S ⊕ U)) : k (Tensor.place L A) = f (Tensor.place (Sum.elim x p) A) := by + rw [show L = Sum.inl ∘ Sum.map id p from rfl, place_comp, place_inl, ek] + change f (Tensor.place e (Tensor.place (Sum.map id p) A)) = _ + rw [← place_comp, show e ∘ Sum.map id p = Sum.elim x p by funext i; cases i <;> rfl] + have dl (i j) : dist k (L i) (L j) = dist f (Sum.elim x p i) (Sum.elim x p j) := by + unfold dist + rw [← place_wire L, left, place_wire] + have right (A : Tensor K (S ⊕ U)) : values d k (Tensor.place R A) ≤ Q A := + (values_le hd hk _ (hQ.nonneg _)).mpr (hkp A) + have dr (i j) : d * dist k (R i) (R j) ≤ gap Q i j := by + have H := right (wire K i j 2) + rw [place_wire] at H + exact H + have same : ∀ i, dist k (L i) (R i) = 0 := by + rintro (s | u) + · exact dist_self _ _ + obtain ⟨a, b, t, hp, hq, hq'⟩ := he u + have key {z w u : ℝ} (h : d * z = u * (d * w)) : z = u * w := by + rw [mul_left_comm u] at h + exact mul_left_cancel₀ hd.ne' h + have hm : Between f (x a) (p u) (x b) t := ⟨key hp.1, key hp.2⟩ + have hx : Between k (L (.inl a)) (L (.inr u)) (L (.inl b)) t := by + simpa only [Between, dl, Sum.elim_inl, Sum.elim_inr] using hm + have hy : Between k (L (.inl a)) (R (.inr u)) (L (.inl b)) t := by + apply between_of_le k hk + · rw [dl] + have hh : d * _ ≤ d * dist f (x a) (p u) := (dr (.inl a) (.inr u)).trans hq + exact (le_of_mul_le_mul_left hh hd).trans_eq hm.1 + · rw [dl] + have hh : d * _ ≤ d * dist f (p u) (x b) := (dr (.inr u) (.inl b)).trans hq' + exact (le_of_mul_le_mul_left hh hd).trans_eq hm.2 + have H := busemann k hk hx.1 hx.2 hy.1 hy.2 + rw [dist_self, dist_self, mul_zero, mul_zero, add_zero] at H + exact le_antisymm H (dist_nonneg _ hk _ _) + intro A + unfold values + rw [← left, price_place_eq k hk L R same] + exact right A + +private theorem determine_le {D E : ℝ} {P : Tensor K V → ℝ} {Q : Tensor K T → ℝ} + (hP : P ∈ ordinary K V D) (hQ : Q ∈ ordinary K T E) + {x : S → V} {y : S → T} (h : Agree P Q x y) + (p : U → V) (q : U → T) (a b : U → S) (t : U → ℝ) + (hp : ∀ i, AtFraction P (x (a i)) (p i) (x (b i)) (t i)) + (hq : ∀ i, AtFraction Q (y (a i)) (q i) (y (b i)) (t i)) + (A : Tensor K (S ⊕ U)) : P (place (Sum.elim x p) A) ≤ Q (place (Sum.elim y q) A) := by + apply Cap.geodesic_le hP ((cap_ordinary hQ).place (Sum.elim y q)) x p + · intro B + rw [Function.comp_apply, place_sum_inl, h] + · intro i + refine ⟨a i, b i, t i, hp i, ?_, ?_⟩ + · rw [gap, Function.comp_apply, place_wire] + exact ((hq i).1.trans ((congrArg _ (h.gap _ _).symm).trans (hp i).1.symm)).le + · rw [gap, Function.comp_apply, place_wire] + exact ((hq i).2.trans ((congrArg _ (h.gap _ _).symm).trans (hp i).2.symm)).le + +/-- The scales may differ, and the old sites need not exhaust either ambient +placement. Intermediate points can be added at different parameters. -/ +theorem Agree.extend {D E : ℝ} {P : Tensor K V → ℝ} {Q : Tensor K T → ℝ} + {x : S → V} {y : S → T} (h : Agree P Q x y) + (hP : P ∈ ordinary K V D) (hQ : Q ∈ ordinary K T E) + (p : U → V) (q : U → T) (a b : U → S) (t : U → ℝ) + (hp : ∀ i, AtFraction P (x (a i)) (p i) (x (b i)) (t i)) + (hq : ∀ i, AtFraction Q (y (a i)) (q i) (y (b i)) (t i)) : + Agree P Q (Sum.elim x p) (Sum.elim y q) := fun A => + le_antisymm (determine_le hP hQ h p q a b t hp hq A) + (determine_le hQ hP (fun B => (h B).symm) q p a b t hq hp A) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- # Evaluations of finite geodesic expressions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Tensor + +variable {K S T V : Type} [Field K] [Fintype T] [DecidableEq T] + +/-- A consistent evaluation at the sites named by e, restricted to one +term and all its subterms. -/ +def Fits (P : Tensor K T → ℝ) (e : Term S → T) : Term S → Prop + | .mark _ => True + | .seg u a b => Fits P e a ∧ Fits P e b ∧ AtFraction P (e a) (e (.seg u a b)) (e b) u + +theorem closed_fits (e : Term S → T) (a : Term S) : + IsClosed {P : Tensor K T → ℝ | Fits P e a} := by + induction a with + | mark => exact isClosed_univ + | seg u a b ha hb => + have h (i j : T) : Continuous (fun P : Tensor K T → ℝ => gap P i j) := + continuous_apply (wire K i j 2) + exact ha.inter (hb.inter ((isClosed_eq (h _ _) (continuous_const.mul (h _ _))).inter + (isClosed_eq (h _ _) (continuous_const.mul (h _ _))))) + +variable [Fintype V] [DecidableEq V] [Nonempty T] [Nonempty V] +variable {P : Tensor K T → ℝ} {Q : Tensor K V → ℝ} {D E : ℝ} + {p : Term S → T} {q : Term S → V} + +private def snoc {X Y : Type} (x : X → Y) (z : Y) : X ⊕ Unit → Y := Sum.elim x (fun _ => z) + +private theorem append_term (hP : P ∈ ordinary K T D) (hQ : Q ∈ ordinary K V E) + (a : Term S) (hp : Fits P p a) (hq : Fits Q q a) : + ∀ {X : Type} [Fintype X] [DecidableEq X] [Nonempty X] (x : X → T) (y : X → V) + (m : S → X), (∀ i, x (m i) = p (.mark i)) → (∀ i, y (m i) = q (.mark i)) → + Agree P Q x y → Agree P Q (snoc x (p a)) (snoc y (q a)) := by + induction a with + | mark i => + intro X _ _ _ x y m hx hy h + let e := snoc id (m i) + have he : x ∘ e = snoc x (p (.mark i)) := by + funext z; cases z + · rfl + · exact hx i + have he' : y ∘ e = snoc y (q (.mark i)) := by + funext z; cases z + · rfl + · exact hy i + rw [← he, ← he'] + exact h.comp e + | seg u a b ha hb => + intro X _ _ _ x y m hx hy h + have ha' := ha hp.1 hq.1 x y m hx hy h + have hb' := hb hp.2.1 hq.2.1 _ _ (Sum.inl ∘ m) hx hy ha' + have hc := hb'.extend hP hQ (fun _ : Unit => p (.seg u a b)) (fun _ => q (.seg u a b)) + (fun _ => .inl (.inr ())) (fun _ => .inr ()) (fun _ => u.val) + (fun _ => hp.2.2) (fun _ => hq.2.2) + let e : X ⊕ Unit → ((X ⊕ Unit) ⊕ Unit) ⊕ Unit := Sum.map (Sum.inl ∘ Sum.inl) id + have project {W : Type} (z : X → W) (a b c : W) : + snoc (snoc (snoc z a) b) c ∘ e = snoc z c := by funext i; cases i <;> rfl + have hc' := hc.comp e + change Agree P Q (snoc (snoc (snoc x (p a)) (p b)) _ ∘ e) + (snoc (snoc (snoc y (q a)) (q b)) _ ∘ e) at hc' + rwa [project, project] at hc' + +theorem terms_determine [Fintype S] [DecidableEq S] [Nonempty S] + (hP : P ∈ ordinary K T D) (hQ : Q ∈ ordinary K V E) (a b : Term S) + (hpa : Fits P p a) (hpb : Fits P p b) (hqa : Fits Q q a) (hqb : Fits Q q b) + (h : Agree P Q (p ∘ Term.mark) (q ∘ Term.mark)) : + gap P (p a) (p b) = gap Q (q a) (q b) := by + have ha := append_term hP hQ a hpa hqa _ _ id (fun _ => rfl) (fun _ => rfl) h + have hb := append_term hP hQ b hpb hqb _ _ Sum.inl (fun _ => rfl) (fun _ => rfl) ha + exact hb.gap (.inl (.inr ())) (.inr ()) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Uniform finite tests for geodesic distances + +On a compact set of enlarged prices, pairs with a prescribed discrepancy +in a term distance are compact. Some old tensor separates each such +pair, so finitely many old tensors suffice with positive tolerance. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Tensor Set + +private theorem finite_observations {X I J : Type*} [TopologicalSpace X] [Finite J] + {s : Set X} (hs : IsCompact s) (f : I → X → ℝ) (g : J → X → ℝ) + (hf : ∀ i, Continuous (f i)) (hg : ∀ j, Continuous (g j)) + (he : ∀ x ∈ s, ∀ y ∈ s, (∀ i, f i x = f i y) → ∀ j, g j x = g j y) + {ε : ℝ} (hε : 0 < ε) : + ∃ t : Finset I, ∃ δ : ℝ, 0 < δ ∧ ∀ x ∈ s, ∀ y ∈ s, + (∀ i ∈ t, |f i x - f i y| ≤ δ) → ∀ j, |g j x - g j y| ≤ ε := by + classical + let bad := s ×ˢ s ∩ {z : X × X | ∃ j, ε ≤ |g j z.1 - g j z.2|} + have hc : IsCompact bad := by + apply (hs.prod hs).inter_right + rw [ofPred_exists] + exact isClosed_iUnion_of_finite fun j => isClosed_le continuous_const + (((hg j).comp continuous_fst).sub ((hg j).comp continuous_snd)).abs + let U (i : I) := {z : X × X | f i z.1 ≠ f i z.2} + have hu (i : I) : IsOpen (U i) := + isOpen_ne_fun ((hf i).comp continuous_fst) ((hf i).comp continuous_snd) + have hcover : bad ⊆ ⋃ i, U i := by + rintro ⟨x, y⟩ ⟨⟨hx, hy⟩, j, h⟩ + apply mem_iUnion.mpr + exact not_forall.mp fun hxy => hε.not_ge (by simpa [he x hx y hy hxy j] using h) + obtain ⟨t, ht⟩ := hc.elim_finite_subcover U hu hcover + by_cases hn : bad.Nonempty + swap + · exact ⟨∅, 1, zero_lt_one, fun x hx y hy _ j => + le_of_not_gt fun h => hn ⟨(x, y), ⟨hx, hy⟩, j, h.le⟩⟩ + let d (z : X × X) := ∑ i ∈ t, |f i z.1 - f i z.2| + have hd : Continuous d := continuous_finsetSum _ fun i _ => + (((hf i).comp continuous_fst).sub ((hf i).comp continuous_snd)).abs + obtain ⟨z, hz, hmin⟩ := hc.exists_isMinOn hn hd.continuousOn + obtain ⟨i, hi, hneq⟩ := mem_iUnion₂.mp (ht hz) + have hd0 : 0 < d z := Finset.sum_pos' (fun _ _ => abs_nonneg _) ⟨i, hi, + abs_pos.mpr (sub_ne_zero.mpr hneq)⟩ + let δ := d z / ((t.card : ℝ) + 1) + have hδ : 0 < δ := div_pos hd0 (by positivity) + refine ⟨t, δ, hδ, fun x hx y hy hxy j => le_of_not_gt fun h => ?_⟩ + have h₁ : d z ≤ d (x, y) := hmin ⟨⟨hx, hy⟩, j, h.le⟩ + have h₂ : d (x, y) ≤ (t.card : ℝ) * δ := by + simpa [d, nsmul_eq_mul] using Finset.sum_le_sum hxy + have e : δ * ((t.card : ℝ) + 1) = d z := div_mul_cancel₀ _ (by positivity) + linarith + +variable {K S T : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype T] [DecidableEq T] [Nonempty T] + +private theorem finite_price_tests (w : Finset (Term S)) (e : Term S → T) (D : ℝ) + {ε : ℝ} (he : 0 < ε) : + ∃ s : Finset (Tensor K S), ∃ δ : ℝ, 0 < δ ∧ + ∀ P ∈ ordinary K T D, ∀ Q ∈ ordinary K T D, + (∀ a ∈ w, Fits P e a) → (∀ a ∈ w, Fits Q e a) → + (∀ A ∈ s, |P (place (e ∘ Term.mark) A) - Q (place (e ∘ Term.mark) A)| ≤ δ) → + ∀ a ∈ w, ∀ b ∈ w, |gap P (e a) (e b) ^ 2 - gap Q (e a) (e b) ^ 2| ≤ ε := by + let s := ordinary K T D ∩ {P | ∀ a ∈ w, Fits P e a} + have hs : IsCompact s := by + apply (compact_ordinary _).inter_right + simp only [ofPred_forall] + exact isClosed_iInter fun a => isClosed_iInter fun _ => closed_fits e a + let f (A : Tensor K S) (P : Tensor K T → ℝ) := P (place (e ∘ Term.mark) A) + let g (i : w × w) (P : Tensor K T → ℝ) := gap P (e i.1.val) (e i.2.val) ^ 2 + obtain ⟨q, δ, hδ, h⟩ := finite_observations hs f g + (fun A => continuous_apply _) (fun i => (continuous_apply _).pow 2) + (fun P hP Q hQ h (i : w × w) => congrArg (fun z : ℝ => z ^ 2) + (terms_determine hP.1 hQ.1 _ _ (hP.2 _ i.1.2) (hP.2 _ i.2.2) + (hQ.2 _ i.1.2) (hQ.2 _ i.2.2) h)) he + exact ⟨q, δ, hδ, fun P hP Q hQ h₁ h₂ h₃ a ha b hb => + h P ⟨hP, h₁⟩ Q ⟨hQ, h₂⟩ h₃ (⟨a, ha⟩, ⟨b, hb⟩)⟩ + +open Classical in +/-- In the case `.mark i`, this construction gives `{.mark i}`. -/ +def Term.subterms {G : Type} : Term G → Finset (Term G) + | .mark i => {.mark i} + | .seg u a b => insert (.seg u a b) (a.subterms ∪ b.subterms) + +theorem Term.mem_subterms {G : Type} (a : Term G) : a ∈ a.subterms := by + classical + cases a <;> simp [subterms] + +section Metric +variable {Y : Type*} [MetricSpace Y] (C : Comparison Y) (x : S → Y) + +omit [Fintype S] [DecidableEq S] [Nonempty S] in +private theorem eval_bound {D : ℝ} (hD : 0 ≤ D) (z : Y) (hx : ∀ i, dist (x i) z ≤ D) + (a : Term S) : dist (a.eval C x) z ≤ D := by + induction a with + | mark => exact hx _ + | seg u a b ha hb => + apply (sq_le_sq₀ _root_.dist_nonneg hD).mp + have h := C.along u (a.eval C x) (b.eval C x) z + have ht := sub_nonneg.mpr u.2.2 + have h₁ := mul_le_mul_of_nonneg_left ((sq_le_sq₀ _root_.dist_nonneg hD).mpr ha) ht + have h₂ := mul_le_mul_of_nonneg_left ((sq_le_sq₀ _root_.dist_nonneg hD).mpr hb) u.2.1 + have h₃ := mul_nonneg (mul_nonneg u.2.1 ht) (sq_nonneg (dist (a.eval C x) (b.eval C x))) + change dist (C.seg _ _ _) _ ^ 2 ≤ _ + linarith only [h, h₁, h₂, h₃] + +omit [Fintype S] [DecidableEq S] [Nonempty S] [Nonempty T] in +private theorem fits_of_eval (P : Tensor K T → ℝ) (e : Term S → T) (z : T → Y) + (hp : ∀ i j, gap P i j = dist (z i) (z j)) (a : Term S) + (he : ∀ b ∈ a.subterms, z (e b) = b.eval C x) : Fits P e a := by + classical + induction a with + | mark => trivial + | seg u a b ha hb => + have ha' (s) (h : s ∈ a.subterms) := he s (by simp [Term.subterms, h]) + have hb' (s) (h : s ∈ b.subterms) := he s (by simp [Term.subterms, h]) + refine ⟨ha ha', hb hb', ?_⟩ + simp only [AtFraction, hp, he _ (Term.mem_subterms _), ha' _ a.mem_subterms, + hb' _ b.mem_subterms, Term.eval] + have H := C.along u (a.eval C x) (b.eval C x) + refine ⟨H.start, ?_⟩ + rw [_root_.dist_comm, H.rev.start, _root_.dist_comm] + rfl +end Metric + +/-- Old tensor prices determine all distances among the indicated terms, +uniformly over complete realizations and repetitions of the markings. -/ +theorem finite_terms_tests (K : Type) [Field K] (w : Finset (Term S)) (D : ℝ) + {ε : ℝ} (he : 0 < ε) : + ∃ s : Finset (Tensor K S), ∃ δ : ℝ, 0 < δ ∧ + ∀ {Y Z : Type} [MetricSpace Y] [MetricSpace Z] (C : Comparison Y) (C' : Comparison Z) + {x : S → Y} {y : S → Z} {P Q : Tensor K S → ℝ}, + Realized x P D → Realized y Q D → (∀ A ∈ s, |P A - Q A| ≤ δ) → + ∀ a ∈ w, ∀ b ∈ w, |dist (a.eval C x) (b.eval C x) ^ 2 - dist (a.eval C' y) (b.eval C' y) ^ + 2| ≤ ε := by + classical + let i := Classical.arbitrary S + let W := insert (.mark i) (w.biUnion Term.subterms) + let _ : Nonempty ↥W := ⟨⟨.mark i, Finset.mem_insert_self _ _⟩⟩ + let e : Term S → S ⊕ ↥W + | .mark s => .inl s + | a@(.seg ..) => if h : a ∈ W then .inr ⟨a, h⟩ else .inl i + have em : e ∘ Term.mark = Sum.inl := rfl + let B := 2 * D * Fintype.card (S ⊕ ↥W) + have lift {Y : Type} [MetricSpace Y] (C : Comparison Y) (x : S → Y) + (P : Tensor K S → ℝ) (hx : Realized x P D) : + ∃ Q ∈ ordinary K (S ⊕ ↥W) B, (∀ A, Q (pad ↥W A) = P A) ∧ + (∀ a ∈ w, Fits Q e a) ∧ + ∀ a ∈ w, ∀ b ∈ w, gap Q (e a) (e b) = dist (a.eval C x) (b.eval C x) := by + let z (a : W) := a.val.eval C x + have hD := _root_.dist_nonneg.trans (hx.1 i i) + have hbound (j : S ⊕ ↥W) : dist (Sum.elim x z j) (x i) ≤ D := by + cases j with + | inl j => exact hx.1 j i + | inr j => exact eval_bound C x hD (x i) (fun s => hx.1 s i) j.val + have H (j k : S ⊕ ↥W) : dist (Sum.elim x z j) (Sum.elim x z k) ≤ 2 * D := by + rw [two_mul] + exact (_root_.dist_triangle_right _ _ _).trans (add_le_add (hbound j) (hbound k)) + obtain ⟨Q, hQ, he, hd⟩ := hx.2 _ z H + have hv (a) (ha : a ∈ w) (b) (hb : b ∈ a.subterms) : Sum.elim x z (e b) = b.eval C x := by + have h : b ∈ W := Finset.mem_insert_of_mem (Finset.mem_biUnion.mpr ⟨a, ha, hb⟩) + cases b <;> simp [e, h, z, Term.eval] + refine ⟨Q, hQ, he, fun a ha => fits_of_eval C x Q e _ hd a (hv a ha), ?_⟩ + intro a ha b hb + rw [gap, hd, hv a ha a a.mem_subterms, hv b hb b b.mem_subterms] + obtain ⟨s, δ, hδ, ht⟩ := finite_price_tests (K := K) w e B he + refine ⟨s, δ, hδ, ?_⟩ + intro Y Z _ _ C C' x y P Q hx hy hxy a ha b hb + obtain ⟨P', hP', eP, fP, dP⟩ := lift C x P hx + obtain ⟨Q', hQ', eQ, fQ, dQ⟩ := lift C' y Q hy + rw [← dP a ha b hb, ← dQ a ha b hb] + refine ht P' hP' Q' hQ' fP fQ ?_ a ha b hb + simpa only [em, place_inl, eP, eQ] using hxy + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/FourArms.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/FourArms.lean new file mode 100644 index 0000000000..a0f7dc9ecb --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/FourArms.lean @@ -0,0 +1,924 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.ScaleSlope +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryTerms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.TreePrice + +/-! +# First displacement in a decreasing filtration of isometric actions + +Orbit centers bound the change in distance to the fixed set. +The unique nearest fixed point inherits all symmetries of that set +fixing the original mark. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +open Routing Set +variable {X G : Type*} [MetricSpace X] [Group G] [MulAction G X] + +/-- The value specified by `⨆ g : H, dist x ((g : G) • x)`. -/ +def displacement (H : Subgroup G) (x : X) : ℝ := ⨆ g : H, dist x ((g : G) • x) + +/-- Uses `{x | ∀ g ∈ H, g • x = x}` as the representation. -/ +def fixed (H : Subgroup G) : Set X := {x | ∀ g ∈ H, g • x = x} + +variable {H : Subgroup G} {x : X} + +theorem displacement_le {r : ℝ} (h : ∀ g ∈ H, dist x (g • x) ≤ r) : + displacement H x ≤ r := ciSup_le fun g => h g g.property + +theorem le_displacement {M : ℝ} (h : ∀ g ∈ H, dist x (g • x) ≤ M) {g : G} (hg : g ∈ H) : + dist x (g • x) ≤ displacement H x := by + have hb : BddAbove (range fun g : H => dist x ((g : G) • x)) := by + refine ⟨M, ?_⟩ + rintro _ ⟨i, rfl⟩ + exact h i i.property + exact le_ciSup hb ⟨g, hg⟩ + +theorem displacement_eq {g : G} (hg : g ∈ H) (h : ∀ a ∈ H, dist x (a • x) ≤ dist x (g • x)) : + displacement H x = dist x (g • x) := + le_antisymm (displacement_le h) (le_displacement h hg) + +theorem displacement_fixed (h : x ∈ fixed H) : displacement H x = 0 := by + unfold displacement + have hz (g : H) : dist x ((g : G) • x) = 0 := by rw [h _ g.property, dist_self] + simp only [hz, ciSup_const] + +variable [CompleteSpace X] [IsIsometricSMul G X] (C : Comparison X) + +private theorem nearby (C : Comparison X) {M : ℝ} (h : ∀ g ∈ H, dist x (g • x) ≤ M) : + ∃ y ∈ fixed H, dist x y ≤ displacement H x := by + have h₀ := dist_nonneg.trans (le_displacement h H.one_mem) + obtain ⟨y, hy, hd⟩ := C.orbit H x (displacement H x ^ 2) + (fun _ hg => pow_le_pow_left₀ dist_nonneg (le_displacement h hg) 2) + exact ⟨y, hy, (sq_le_sq₀ dist_nonneg h₀).mp (by linarith [sq_nonneg (dist x y)])⟩ + +private theorem project (C : Comparison X) (H : Subgroup G) + (x : X) (hn : (fixed H : Set X).Nonempty) : + ∃ y ∈ fixed H, ∀ z ∈ fixed H, dist x y ^ 2 + dist y z ^ 2 ≤ dist x z ^ 2 := by + have closed : IsClosed (fixed H : Set X) := by + unfold fixed + simp only [ofPred_forall] + exact isClosed_iInter fun g => isClosed_iInter fun _ => isClosed_eq + (isometry_smul X g).continuous continuous_id + let Y := ↥(fixed H : Set X) + have : CompleteSpace Y := closed.completeSpace_coe + let F (_ : Unit) (z : Y) := dist x z.val ^ 2 + obtain ⟨z, hz⟩ := hn + obtain ⟨o, a, ha, ho⟩ := Routing.minimize F (fun _ => by unfold F; fun_prop) + (fun _ _ => sq_nonneg _) ⟨dist x z ^ 2, ⟨z, hz⟩, fun _ => le_rfl⟩ (by + intro p q t ht hu + let u : Fraction := ⟨t, ht, hu⟩ + let m := C.seg u p.val q.val + have hm := C.along u p.val q.val + have stable : m ∈ fixed H := by + intro g hg + apply Along.unique _ hm + intro v + have hd (a b : X) : dist a (g⁻¹ • b) = dist (g • a) b := by + rw [← dist_smul g, smul_inv_smul] + simpa only [hd, p.property g hg, q.property g hg] using hm (g⁻¹ • v) + refine ⟨⟨m, stable⟩, fun _ => ?_⟩ + change dist x m ^ 2 ≤ (1 - t) * dist x p.val ^ 2 + t * dist x q.val ^ 2 - + t * (1 - t) * dist p.val q.val ^ 2 + simpa only [dist_comm _ x] using hm x) + exact ⟨o.val, o.property, fun y hy => + (add_le_add_left (ha ()) _).trans (ho ⟨y, hy⟩ (dist x y ^ 2) fun _ => le_rfl)⟩ + +/-- The center at the critical radius is fixed by every symmetry fixing +the base mark and mapping the fixed set into itself. -/ +theorem motion_scale (C : Comparison X) (H : ℝ → Subgroup G) + (hm : AntitoneOn H (Ioi 0)) {M : ℝ} (hM : ∀ x y : X, dist x y ≤ M) + (hs : ∀ x : X, RationalSecants (fun r => displacement (H r) x)) + (o : X) (hmoved : ∃ a : ℝ, 0 < a ∧ o ∉ fixed (H a)) + (hsmall : ∀ ε : ℝ, 0 < ε → ∃ b, 0 < b ∧ displacement (H b) o < ε) : + ∃ (r : ℝ) (A : X) (k : ℝ), 0 < r ∧ 0 < k ∧ A ∈ fixed (H r) ∧ + (∀ φ : X → X, Isometry φ → φ o = o → MapsTo φ (fixed (H r)) (fixed (H r)) → φ A = A) ∧ + Kink (fun s => displacement (H s) A) r k := by + have bound (x : X) (r : ℝ) : ∀ g ∈ H r, dist x (g • x) ≤ M := fun _ _ => hM _ _ + have ne (r : ℝ) : (fixed (H r) : Set X).Nonempty := by + obtain ⟨x, hx, _⟩ := nearby C (bound o r) + exact ⟨x, hx⟩ + choose A hA hproj using fun r => project C (H r) o (ne r) + let f (r : ℝ) := dist o (A r) + have hmin (r : ℝ) (y : X) (hy : y ∈ fixed (H r)) : f r ≤ dist o y := + (sq_le_sq₀ dist_nonneg dist_nonneg).mp + ((le_add_of_nonneg_right (sq_nonneg _)).trans (hproj r y hy)) + have sub {s t : ℝ} (hs : 0 < s) (hst : s ≤ t) : (fixed (H s) : Set X) ⊆ fixed (H t) := + fun _ hx g hg => hx g (hm hs (hs.trans_le hst) hst hg) + have anti {s t : ℝ} (hs : 0 < s) (hst : s ≤ t) : f t ≤ f s := + hmin t (A s) (sub hs hst (hA s)) + obtain ⟨a, ha, hn⟩ := hmoved + have hfa : 0 < f a := dist_pos.mpr (fun he => hn (he.symm ▸ hA a)) + obtain ⟨b, hb, hb'⟩ := hsmall _ hfa + obtain ⟨z, hz, hz'⟩ := nearby C (bound o b) + have hf := ((hmin b z hz).trans hz').trans_lt hb' + have hab : a < b := lt_of_not_ge fun h => hf.not_ge (anti hb h) + obtain ⟨r, hr, k, hk, he⟩ := first_displacement ha hab hf + (fun t _ => hs (A t)) + (fun t _ x hx y hy hxy => displacement_le fun g hg => + le_displacement (bound _ x) (hm hx hy hxy hg)) + (fun t ht x htx => displacement_fixed (sub (ha.trans_le ht.1) htx (hA t))) + (fun t _ => displacement_le (bound _ (a / 2))) (by + intro s hs t _ hst + obtain ⟨y, hy, he⟩ := nearby C (bound (A t) s) + refine ⟨anti (ha.trans_le hs.1) hst, ?_⟩ + exact sub_le_iff_le_add'.mpr ((hmin s y hy).trans + ((dist_triangle o (A t) y).trans (add_le_add le_rfl he)))) + refine ⟨r, A r, k, ha.trans hr.1, hk, hA r, ?_, he⟩ + intro φ hi hφ hm + have hd := hproj r (φ (A r)) (hm (hA r)) + rw [show dist o (φ (A r)) = dist o (A r) by rw [← hφ, hi.dist_eq, hφ]] at hd + exact (dist_eq_zero.mp (by nlinarith : dist (A r) (φ (A r)) = 0)).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +section +/- # Zooming into the onset of displacement along rational radii -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +open Filter +open scoped Topology + +variable {R : ℝ → ℝ} {r k : ℝ} + +theorem Kink.slope (h : Kink R r k) {v z : ℕ → ℝ} {w : ℝ} + (hv : ∀ n, 0 < v n) (hv0 : Tendsto v atTop (𝓝 0)) (hz : Tendsto z atTop (𝓝 w)) : + Tendsto (fun n => R (r + v n * z n) / v n) atTop (𝓝 (k * max (-w) 0)) := by + have hu : Tendsto (fun n => k * max (-z n) 0) atTop (𝓝 (k * max (-w) 0)) := + (hz.neg.max tendsto_const_nhds).const_mul k + have ht : Tendsto (fun n => v n * z n) atTop (𝓝 0) := by simpa using hv0.mul hz + let M := |w| + 1 + have hM : 0 < M := by unfold M; positivity + have he : Tendsto (fun n => R (r + v n * z n) / v n - k * max (-z n) 0) atTop (𝓝 0) := by + apply Metric.tendsto_nhds.mpr + intro ε hε + obtain ⟨δ, hδ, H⟩ := h (ε / M) (div_pos hε hM) + filter_upwards [ht.abs.eventually_lt_const (by simpa using hδ), + hz.abs.eventually_lt_const (show |w| < M by unfold M; linarith)] with n hn hn' + have hd := H _ hn + have e : max (-(v n * z n)) 0 = v n * max (-z n) 0 := by + rw [mul_max_of_nonneg _ _ (hv n).le, mul_neg, mul_zero] + have a : R (r + v n * z n) / v n - k * max (-z n) 0 = + (R (r + v n * z n) - k * max (-(v n * z n)) 0) / v n := by + rw [e, sub_div, mul_left_comm k, mul_div_cancel_left₀ _ (hv n).ne'] + rw [Real.dist_eq, sub_zero, a, abs_div, abs_of_pos (hv n), div_lt_iff₀ (hv n)] + refine hd.trans_lt ?_ + rw [abs_mul, abs_of_pos (hv n), mul_comm (v n), ← mul_assoc] + apply mul_lt_mul_of_pos_right _ (hv n) + exact (mul_lt_mul_of_pos_left hn' (div_pos hε hM)).trans_eq (div_mul_cancel₀ _ hM.ne') + simpa only [zero_add, sub_add_cancel] using he.add hu + +/-- A single choice of rational dilation and origin works for all slopes. -/ +theorem Kink.zoom (h : Kink R r k) (hk : 0 < k) : + ∃ e t : ℕ → ℚ, (∀ n, 0 < e n) ∧ Tendsto (fun n => (e n : ℝ)) atTop (𝓝 0) ∧ + Tendsto (fun n => (t n : ℝ)) atTop (𝓝 r) ∧ ∀ u : ℚ, + Tendsto (fun n => (2 / (k * e n)) * R ↑(t n + e n * u)) atTop + (𝓝 (2 * max (1 - (u : ℝ)) 0)) := by + obtain ⟨e, _, he, he'⟩ := Real.exists_seq_rat_strictAnti_tendsto 0 + choose t hl hu using fun n => exists_rat_btwn (show r - e n < r - e n + (e n : ℝ) ^ 2 + from lt_add_of_pos_right _ (sq_pos_of_pos (he n))) + let s (n : ℕ) := ((t n : ℝ) - (r - e n)) / e n + have hs : Tendsto s atTop (𝓝 0) := by + refine squeeze_zero (fun n => div_nonneg (sub_nonneg.mpr (hl n).le) (he n).le) ?_ he' + intro n + exact (div_le_iff₀ (he n)).mpr (by linarith [hu n]) + have heq (n : ℕ) : (t n : ℝ) = r + e n * (s n - 1) := by + have h' : s n * e n = (t n : ℝ) - (r - e n) := div_mul_cancel₀ _ (he n).ne' + linarith + have ht : Tendsto (fun n => (t n : ℝ)) atTop (𝓝 r) := by + simp only [heq] + simpa using (he'.mul (hs.sub_const 1)).const_add r + refine ⟨e, t, fun n => by exact_mod_cast he n, he', ht, fun u => ?_⟩ + have H := (h.slope he he' ((hs.sub_const 1).add_const (u : ℝ))).const_mul (2 / k) + have ea (n : ℕ) : 2 / (k * e n) * R ↑(t n + e n * u) = + (2 / k) * (R (r + ↑(e n) * (s n - 1 + (u : ℝ))) / e n) := by + rw [Rat.cast_add, Rat.cast_mul, heq, mul_add, add_assoc] + ring + have ek : (2 / k) * (k * max (-(0 - 1 + (u : ℝ))) 0) = 2 * max (1 - (u : ℝ)) 0 := by + rw [show -(0 - 1 + (u : ℝ)) = 1 - (u : ℝ) by ring, ← mul_assoc, div_mul_cancel₀ _ hk.ne'] + simp only [ea] + rwa [ek] at H + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +section +/- +# Distances of individual leaves + +Use two inner arms and one outer arm, all of the same length. +Move the inward radius to the corner of the limiting profile. +The cost of the perturbation on the second inner arm then vanishes. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +open Filter +open scoped Topology + +/-- A scalar squeeze for the distance at a nongeneric parameter. -/ +theorem zoom_leaf {R : ℝ → ℝ} {r : ℝ} (hr : 0 < r) + {e t : ℕ → ℚ} {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) (he : ∀ n, 0 < e n) + (he0 : Tendsto (fun n => (e n : ℝ)) atTop (𝓝 0)) + (ht : Tendsto (fun n => (t n : ℝ)) atTop (𝓝 r)) + (hlim : ∀ u : ℚ, Tendsto (fun n => f n * R ↑(t n + e n * u)) atTop + (𝓝 (2 * max (1 - (u : ℝ)) 0))) + (u : ℚ) (d : ℕ → ℝ) + (hd : ∀ᶠ n in atTop, 0 ≤ d n ∧ d n ≤ R ↑(t n + e n * u) ∧ + ∀ s : ℚ, 0 < s → s < t n + e n * u → + 3 * R ↑(t n + e n * u) ≤ 2 * R ↑(t n + e n * u + s) + R ↑(t n + e n * u - s) + d n) : + Tendsto (fun n => f n * d n) atTop (𝓝 (2 * max (1 - (u : ℝ)) 0)) := by + have hu : ∀ᶠ n in atTop, f n * d n ≤ f n * R ↑(t n + e n * u) := + hd.mono fun n hn => mul_le_mul_of_nonneg_left hn.2.1 (hf n) + rcases le_or_gt 1 u with hge | hlt + · have h : (1 : ℝ) ≤ u := by exact_mod_cast hge + have hl := hlim u + rw [max_eq_right (sub_nonpos.mpr h), mul_zero] at hl ⊢ + exact squeeze_zero' (hd.mono fun n hn => mul_nonneg (hf n) hn.1) hu hl + let v := 2 * u - 1 + let w (a : ℚ) (n : ℕ) := f n * R ↑(t n + e n * a) + have hlow : Tendsto (fun n => 3 * w u n - 2 * w 1 n - w v n) atTop + (𝓝 (2 * max (1 - (u : ℝ)) 0)) := by + have h := (((hlim u).const_mul 3).sub ((hlim 1).const_mul 2)).sub (hlim v) + have hv : (v : ℝ) = 2 * u - 1 := by simp [v] + have hh : (u : ℝ) < 1 := by exact_mod_cast hlt + convert h using 1 + rw [hv, Rat.cast_one, sub_self, max_self, max_eq_left (by linarith : 0 ≤ 1 - (u : ℝ)), + max_eq_left (by linarith : 0 ≤ 1 - (2 * (u : ℝ) - 1))] + congr 1 + ring + have hrad : Tendsto (fun n => ((t n + e n * v : ℚ) : ℝ)) atTop (𝓝 r) := by + simpa only [Rat.cast_add, Rat.cast_mul, zero_mul, add_zero] using ht.add (he0.mul_const (v : ℝ)) + refine tendsto_of_tendsto_of_tendsto_of_le_of_le' hlow (hlim u) ?_ hu + filter_upwards [hd, hrad.eventually_const_lt hr] with n hn hv + let s := e n * (1 - u) + have h₁ : t n + e n * u + s = t n + e n * 1 := by unfold s; ring + have h₂ : t n + e n * u - s = t n + e n * v := by unfold s v; ring + have hpos : 0 < t n + e n * v := by exact_mod_cast hv + have h := hn.2.2 s (mul_pos (he n) (sub_pos.mpr hlt)) (sub_pos.mp (h₂.symm ▸ hpos)) + rw [h₁, h₂] at h + unfold w + linarith only [mul_le_mul_of_nonneg_left h (hf n)] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# The translation groups of valuation disks + +Use multiplicative notation for the additive group of the open +valuation disk to apply the metric group-action lemmas. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 + +open Filter +open scoped Topology + +/-- Builds `AddSubgroup (K0 E) where carrier` with the specified `carrier`, `zero_mem'`, +`add_mem'`, `neg_mem'`. -/ +def disk (E : Type*) [Field E] : AddSubgroup (K0 E) where + carrier := {z | 0 < val E z} + zero_mem' := by simp + add_mem' := (val E).map_lt_add + neg_mem' {z} h := by simpa using h + +/-- Computes the g by the application `Multiplicative (disk E)`. -/ +abbrev G (E : Type*) [Field E] := Multiplicative (disk E) + +variable {E : Type*} [Field E] + +/-- The value specified by `(Multiplicative.toAdd g : disk E).val`. -/ +def idx (g : G E) : K0 E := (Multiplicative.toAdd g : disk E).val + +/-- Returns `Multiplicative.ofAdd ⟨z, h⟩` when `h : 0 < val E z` holds, and `1` otherwise. -/ +def shift (z : K0 E) : G E := if h : 0 < val E z then Multiplicative.ofAdd ⟨z, h⟩ else 1 + +theorem idx_pos (g : G E) : 0 < val E (idx g) := (Multiplicative.toAdd g).property + +@[simp] theorem idx_one : idx (1 : G E) = 0 := rfl +@[simp] theorem idx_mul (g h : G E) : idx (g * h) = idx g + idx h := rfl +@[simp] theorem idx_inv (g : G E) : idx g⁻¹ = -idx g := rfl + +theorem idx_injective : Function.Injective (idx (E := E)) := by + intro a b h + exact Multiplicative.toAdd.injective (Subtype.ext h) + +@[simp] theorem idx_shift {z : K0 E} (h : 0 < val E z) : idx (shift z) = z := by + rw [shift, dite_eq_left h] + rfl + +@[simp] theorem shift_idx (g : G E) : shift (idx g) = g := + idx_injective (idx_shift (idx_pos g)) + +@[simp] theorem shift_zero : shift (0 : K0 E) = 1 := shift_idx 1 + +theorem shift_add {x y : K0 E} (hx : 0 < val E x) (hy : 0 < val E y) : + shift (x + y) = shift x * shift y := by + apply idx_injective + simp [idx_shift ((val E).map_lt_add hx hy), hx, hy] + +/-- Builds `Subgroup (G E) where carrier` with the specified `carrier`, `one_mem'`, `obtain`, +`exact`. -/ +def level (E : Type*) [Field E] (r : ℝ) : Subgroup (G E) where + carrier := {g | ∃ q : ℚ, r ≤ q ∧ ↑q ≤ val E (idx g)} + one_mem' := by + obtain ⟨q, hq⟩ := exists_rat_gt r + exact ⟨q, hq.le, by simp⟩ + inv_mem' := by + rintro g ⟨q, hq, hm⟩ + exact ⟨q, hq, by simpa using hm⟩ + mul_mem' := by + rintro a b ⟨p, hp, ha⟩ ⟨q, hq, hb⟩ + refine ⟨min p q, by rw [Rat.cast_min]; exact le_min hp hq, ?_⟩ + exact (val E).map_le_add ((WithTop.coe_le_coe.mpr (min_le_left _ _)).trans ha) + ((WithTop.coe_le_coe.mpr (min_le_right _ _)).trans hb) + +theorem level_anti : Antitone (level E) := by + rintro s t h g ⟨q, hq, hg⟩ + exact ⟨q, h.trans hq, hg⟩ + +theorem mem_level (q : ℚ) (g : G E) : g ∈ level E q ↔ ↑q ≤ val E (idx g) := by + constructor + · rintro ⟨r, hr, h⟩ + exact (WithTop.coe_le_coe.mpr (Rat.cast_le.mp hr)).trans h + · exact fun h => ⟨q, le_rfl, h⟩ + +/-- The quantity computed by `t t₀ * dilate e he z`. -/ +def zoom (e t₀ : ℚ) (he : 0 < e) (z : K0 E) : K0 E := t t₀ * dilate e he z + +theorem val_zoom (e t₀ : ℚ) (he : 0 < e) {z : K0 E} {s : ℚ} (hz : val E z = ↑s) : + val E (zoom e t₀ he z) = ↑(t₀ + e * s) := by + simp [zoom, val_dilate, hz] + +theorem zoom_pos {r : ℝ} (hr : 0 < r) {e t₀ : ℕ → ℚ} (he : ∀ n, 0 < e n) + (he0 : Tendsto (fun n => (e n : ℝ)) atTop (𝓝 0)) + (ht : Tendsto (fun n => (t₀ n : ℝ)) atTop (𝓝 r)) (z : K0 E) : + ∀ᶠ n in atTop, 0 < val E (zoom (e n) (t₀ n) (he n) z) := by + by_cases h : z = 0 + · simp [zoom, h] + obtain ⟨s, hs⟩ := WithTop.ne_top_iff_exists.mp ((val E).ne_top_iff.mpr h) + have H : Tendsto (fun n => ((t₀ n + e n * s : ℚ) : ℝ)) atTop (𝓝 r) := by + simpa only [Rat.cast_add, Rat.cast_mul, zero_mul, add_zero] using ht.add (he0.mul_const (s : ℝ)) + filter_upwards [H.eventually_const_lt hr] with n hn + rw [val_zoom _ _ _ hs.symm] + exact_mod_cast hn + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- +# Wire tests imply radial estimates + +Specialization permits using any integral parameter on the left. +There is no need to choose the same generic parameter in every test. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 + +variable {E X : Type*} [Field E] [MetricSpace X] [MulAction (G E) X] + +/-- The value specified by `dist A (shift z • A)`. -/ +def cost (A : X) (z : K0 E) : ℝ := dist A (shift z • A) +/-- Computes the profile by the application `displacement (level E q) A`. -/ +def profile (E : Type*) [Field E] [MulAction (G E) X] (A : X) (q : ℝ) : ℝ := + displacement (level E q) A + +/-- The one-inner-arm and equal-length two-inner-arm distance tests. -/ +structure RadialStars (E X : Type*) [Field E] [MetricSpace X] [MulAction (G E) X] : Prop where + secant : ∀ (A : X) (a b c : ℚ), 0 < a → a < b → b < c → ∀ w : K0 E, 0 ≤ val E w → + ∃ u : K0 E, 0 ≤ val E u ∧ + ((c : ℝ) - a) * cost A (t b * w) ≤ ((c : ℝ) - b) * cost A (t a * u) + + ((b : ℝ) - a) * cost A (t c * u) + branch : ∀ (A : X) (q s : ℚ), 0 < s → s < q → ∀ w v : K0 E, 0 ≤ val E w → val E v = 0 → + ∃ u : K0 E, 0 ≤ val E u ∧ 3 * cost A (t q * w) ≤ cost A (t (q + s) * u) + + cost A (t q * (v + t s * u)) + cost A (t (q - s) * u) + +theorem scaled_le (q : ℚ) {z : K0 E} (hz : 0 ≤ val E z) : + ↑q ≤ val E (t q * z) := by + rw [AddValuation.map_mul, val_t] + exact le_add_of_nonneg_right hz + +theorem scaled_pos {q : ℚ} (hq : 0 < q) {z : K0 E} (hz : 0 ≤ val E z) : + 0 < val E (t q * z) := + (WithTop.coe_pos.mpr hq).trans_le (scaled_le q hz) + +theorem unscale (q : ℚ) (z : K0 E) : t q * (t (-q) * z) = z := by + rw [← mul_assoc, ← t_add, add_neg_cancel, t_zero, one_mul] + +theorem le_unscale {q : ℚ} {z : K0 E} (hz : ↑q ≤ val E z) : + 0 ≤ val E (t (-q) * z) := by + rw [AddValuation.map_mul, val_t] + have h := add_le_add_right hz ((-q : ℚ) : WithTop ℚ) + rw [← WithTop.coe_add, neg_add_cancel, WithTop.coe_zero] at h + exact h + +theorem profile_le {A : X} {q : ℚ} {L : ℝ} + (h : ∀ u : K0 E, 0 ≤ val E u → cost A (t q * u) ≤ L) : profile E A q ≤ L := by + apply displacement_le + intro g hg + have h' := h _ (le_unscale ((mem_level q g).mp hg)) + simpa only [unscale, cost, shift_idx] using h' + +theorem cost_le {A : X} {q : ℚ} (hq : 0 < q) {z : K0 E} (hz : ↑q ≤ val E z) + {M : ℝ} (hM : ∀ x y : X, dist x y ≤ M) : cost A z ≤ profile E A q := by + apply le_displacement (fun _ _ => hM _ _) + rw [mem_level, idx_shift ((WithTop.coe_pos.mpr hq).trans_le hz)] + exact hz + +theorem RadialStars.secants (h : RadialStars E X) {M : ℝ} + (hM : ∀ x y : X, dist x y ≤ M) (A : X) : RationalSecants (profile E A) := by + intro a b c ha hab hbc + have h₁ : (a : ℝ) < b := Rat.cast_lt.mpr hab + have h₂ : (b : ℝ) < c := Rat.cast_lt.mpr hbc + rw [mul_comm, ← le_div_iff₀ (sub_pos.mpr (h₁.trans h₂))] + apply profile_le + intro w hw + obtain ⟨u, hu, hs⟩ := h.secant A a b c ha hab hbc w hw + rw [le_div_iff₀ (sub_pos.mpr (h₁.trans h₂)), mul_comm] + exact hs.trans (add_le_add + (mul_le_mul_of_nonneg_left (cost_le ha (scaled_le a hu) hM) (sub_nonneg.mpr h₂.le)) + (mul_le_mul_of_nonneg_left (cost_le (ha.trans (hab.trans hbc)) (scaled_le c hu) hM) + (sub_nonneg.mpr h₁.le))) + +variable [IsIsometricSMul (G E) X] + +theorem cost_add (A : X) {a b : K0 E} (ha : 0 < val E a) (hb : 0 < val E b) : + cost A (a + b) ≤ cost A a + cost A b := by + unfold cost + rw [shift_add ha hb, mul_smul] + simpa only [dist_smul] using dist_triangle A (shift a • A) (shift a • shift b • A) + +theorem RadialStars.star (h : RadialStars E X) {M : ℝ} (hM : ∀ x y : X, dist x y ≤ M) + (A : X) {q s : ℚ} (hs : 0 < s) (hsq : s < q) {z : K0 E} (hz : val E z = ↑q) : + 3 * profile E A q ≤ 2 * profile E A ↑(q + s) + profile E A ↑(q - s) + cost A z := by + have hq := hs.trans hsq + let v := t (-q) * z + have hv : val E v = 0 := by + unfold v + rw [AddValuation.map_mul, val_t, hz, ← WithTop.coe_add, neg_add_cancel, WithTop.coe_zero] + rw [mul_comm 3, ← le_div_iff₀ (by norm_num : (0 : ℝ) < 3)] + apply profile_le + intro w hw + obtain ⟨u, hu, h'⟩ := h.branch A q s hs hsq w v hw hv + have heq : t q * (v + t s * u) = z + t (q + s) * u := by + rw [mul_add, t_add, mul_assoc, show t q * v = z from unscale q z] + rw [heq] at h' + have he := cost_add A (hz.symm ▸ WithTop.coe_pos.mpr hq) (scaled_pos (add_pos hq hs) hu) + have hi := cost_le (A := A) (add_pos hq hs) (scaled_le (q + s) hu) hM + have ho := cost_le (A := A) (sub_pos.mpr hsq) (scaled_le (q - s) hu) hM + linarith only [h', he, hi, ho] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- The generic rate and comparisons along a single arm. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 + +variable {F : Type} [Field F] {E : Type*} [Field E] + +/-- The data for the branches construction, including `pos`, `integral`, `separate`. -/ +structure Branches (E : Type*) [Field E] where + /-- The `Branches` component of type `Four (K0 E)`. -/ + pos : Four (K0 E) + integral : ∀ i, 0 ≤ val E (pos i) + separate : ∀ i j, i ≠ j → val E (pos i - pos j) = 0 + +instance [Infinite E] : Nonempty (Branches E) := by + let e := Infinite.natEmbedding E + refine ⟨fun i => C (e i.val), fun i => ?_, fun i j h => ?_⟩ + · by_cases h : e i.val = 0 <;> simp [h] + · rw [← map_sub, val_C (sub_ne_zero.mpr (e.injective.ne (Fin.val_injective.ne h)))] + +namespace Branches + +variable (B : Branches E) (H : MotionTree F E) + +/-- Evaluates `if i = 3 then z else B.pos i` at the input `i`. -/ +def pts (z : K0 E) : Four (K0 E) := fun i => if i = 3 then z else B.pos i + +/-- The value specified by `H.rate (B.pts z) l`. -/ +def rate (z : K0 E) (l : Four ℚ) := H.rate (B.pts z) l + +theorem rate_nonneg (z : K0 E) (l : Four ℚ) (hl : ∀ i, l i ≤ 1) : + 0 ≤ B.rate H z l := H.nonneg _ _ hl + +theorem bound {z : K0 E} (h : 0 ≤ val E z) {l : ℚ} (hl : 0 ≤ l) (hl' : l ≤ 1) : + B.rate H z (fun _ => l) ≤ 6 * (l : ℝ) := by + have hi (i) : 0 ≤ val E (B.pts z i) := by + unfold pts + split <;> first | exact h | exact B.integral _ + have hb (i j) : diskGap (B.pts z i) (B.pts z j) l l ≤ 2 * l := by + have he := gap_bound hl hl zero_le_one + ((le_min (hi i) (hi j)).trans ((val E).map_sub _ _)) + linarith + refine (H.path _ _ (fun _ => hl') 0 1 2 3 (by decide)).trans ?_ + exact_mod_cast (show diskGap (B.pts z 0) (B.pts z 1) l l + + diskGap (B.pts z 1) (B.pts z 2) l l + diskGap (B.pts z 2) (B.pts z 3) l l ≤ 6 * l by + linarith only [hb 0 1, hb 1 2, hb 2 3]) + +/-- The supremum of `{r | ∃ z, 0 ≤ val E z ∧ B.rate H z (fun _ => l) = r}`. -/ +def generic (l : ℚ) := sSup {r | ∃ z, 0 ≤ val E z ∧ B.rate H z (fun _ => l) = r} + +theorem generic_le {l : ℚ} {D : ℝ} (h : ∀ z, 0 ≤ val E z → B.rate H z (fun _ => l) ≤ D) : + B.generic H l ≤ D := + csSup_le ⟨_, 0, by simp, rfl⟩ (by rintro _ ⟨z, hz, rfl⟩; exact h z hz) + +theorem le_generic {l : ℚ} (hl : 0 ≤ l) (hl' : l ≤ 1) {z : K0 E} (hz : 0 ≤ val E z) : + B.rate H z (fun _ => l) ≤ B.generic H l := + le_csSup ⟨_, by rintro _ ⟨z, hz, rfl⟩; exact B.bound H hz hl hl'⟩ ⟨z, hz, rfl⟩ + +/-- The quantity computed by `B.generic H l / (2 * (l : ℝ))`. -/ +def X (l : ℚ) := B.generic H l / (2 * (l : ℝ)) + +theorem generic_eq {l : ℚ} (hl : 0 < l) : B.generic H l = 2 * (l : ℝ) * B.X H l := by + unfold X + rw [mul_div_cancel₀ _ (by positivity)] + +private theorem radial {l L : ℚ} (hl : 0 < l) (h : l ≤ L) (hL : L ≤ 1) + {z : K0 E} (hz : 0 ≤ val E z) : + B.rate H z (fun _ => l) ≤ (l : ℝ) / L * B.rate H z (fun _ => L) := by + have hp := hl.trans_le h + have hch := H.chord (B.pts z) (B.pts z) (B.pts z) (fun _ => 0) (fun _ => L) (fun _ => l) + (fun _ => zero_le_one) (fun _ => hL) (fun _ => h.trans hL) (l / L) (by positivity) + ((div_le_one hp).mpr h) (fun i => by + rw [gap_same _ hl.le zero_le_one, gap_same _ hp.le zero_le_one, sub_zero, sub_zero, + div_mul_cancel₀ _ hp.ne']) (fun i => by + rw [gap_same _ h (h.trans hL), gap_same _ hp.le zero_le_one, sub_zero, sub_mul, one_mul, + div_mul_cancel₀ _ hp.ne']) + have hzero : H.rate (B.pts z) (fun _ => 0) = 0 := le_antisymm + (by simpa [rate] using B.bound H hz (l := 0) le_rfl zero_le_one) (H.nonneg _ _ fun _ + => zero_le_one) + simpa only [hzero, mul_zero, zero_add, Rat.cast_div, rate] using hch + +theorem monotone_X : MonotoneOn (B.X H) (Set.Ioc 0 1) := by + intro l hl L hL h + have hbound : B.generic H l ≤ (l : ℝ) / L * B.generic H L := by + refine B.generic_le H fun z hz => (B.radial H hl.1 h hL.2 hz).trans ?_ + exact mul_le_mul_of_nonneg_left (B.le_generic H hL.1.le hL.2 hz) + (div_nonneg (Rat.cast_nonneg.mpr hl.1.le) (Rat.cast_nonneg.mpr hL.1.le)) + rw [B.generic_eq H hl.1, B.generic_eq H hL.1] at hbound + have hpos : (0 : ℝ) < L := by exact_mod_cast hL.1 + have he : (l : ℝ) / L * (2 * L * B.X H L) = 2 * l * B.X H L := by field_simp + rw [he] at hbound + exact le_of_mul_le_mul_left hbound (mul_pos (by norm_num) (Rat.cast_pos.mpr hl.1)) + +theorem star {n : ℕ} (a b : K0 E) (c : Fin n → K0 E) + (hc : ∀ j, 0 ≤ val E (c j)) (hd : ∀ i j, i ≠ j → val E (c i - c j) = 0) + (r : Option (Fin n) → ℚ) (hr : ∀ j, 0 < r j) + (l : Four ℚ) (k : Option (Fin n) → Four ℚ) + (hl : ∀ i, l i ≤ 1) (hk : ∀ j i, k j i ≤ 1) + (harmonic : ∀ i, ∑ j, (k j i - l i) / r j = 0) (v : K0 E) (hv : 0 ≤ val E v) : + ∃ u : Option (Fin n) → K0 E, (∀ j, 0 ≤ val E (u j)) ∧ + 0 ≤ ∑ j, (B.rate H (a + b * armEnd c r (u j) j) (k j) - B.rate H (a + b * v) l) / (r j : ℝ) + := by + let w : Four (K0 E) := fun i => if i = 3 then b else 0 + have he (u : K0 E) : diskAffine (B.pts a) w u = B.pts (a + b * u) := by + funext i + by_cases hi : i = 3 <;> simp [hi, diskAffine, pts, w] + simpa only [he, rate] using H.star (B.pts a) w c hc hd r hr l k hl hk harmonic v hv + +theorem ray {a : K0 E} {r t₁ t₂ : ℚ} (h₁ : 0 < t₁) (h₂ : 0 < t₂) + (l k m : Four ℚ) (hl : ∀ i, l i ≤ 1) (hk : ∀ i, k i ≤ 1) (hm : ∀ i, m i ≤ 1) + (harmonic : ∀ i, (k i - l i) * t₂ + (m i - l i) * t₁ = 0) + {v : K0 E} (hv : 0 ≤ val E v) : + ∃ u w : K0 E, 0 ≤ val E u ∧ 0 ≤ val E w ∧ + ((t₁ : ℝ) + t₂) * B.rate H (a + t r * v) l ≤ + t₂ * B.rate H (a + t (r + t₁) * u) k + t₁ * B.rate H (a + t (r - t₂) * w) m := by + let s : Option (Fin 1) → ℚ := fun j => j.elim t₂ (fun _ => t₁) + let d : Option (Fin 1) → Four ℚ := fun j => j.elim m (fun _ => k) + have he i : ∑ j, (d j i - l i) / s j = 0 := by + simp only [Fintype.sum_option, Fin.sum_univ_one, s, d, Option.elim_none, Option.elim_some] + field_simp + linarith only [harmonic i] + obtain ⟨u, hu, hw⟩ := B.star H a (t r) (fun _ : Fin 1 => 0) (by simp) + (fun i j h => (h (Subsingleton.elim _ _)).elim) s (by rintro (_|j) <;> assumption) l d hl + (by rintro (_|j) <;> assumption) he v hv + refine ⟨u (some 0), u none, hu _, hu _, ?_⟩ + simp only [Fintype.sum_option, Fin.sum_univ_one, s, d, Option.elim_none, Option.elim_some, armEnd, + zero_add, ← mul_assoc, ← t_add, ← sub_eq_add_neg] at hw + have h₁' : (0 : ℝ) < t₁ := Rat.cast_pos.mpr h₁ + have h₂' : (0 : ℝ) < t₂ := Rat.cast_pos.mpr h₂ + field_simp at hw + linarith only [hw] + +end Branches +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- The three collision arms and their two-pair endpoints. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Branches + +open Spectral +variable {F : Type} [Field F] {E : Type*} [Field E] (B : Branches E) (H : MotionTree F E) + +/-- Evaluates `if i = j ∨ i = 3 then l + r / 2 else l - r / 2` at the input `i`. -/ +def depth (j : Fin 4) (l r : ℚ) : Four ℚ := + fun i => if i = j ∨ i = 3 then l + r / 2 else l - r / 2 + +theorem depth_le (j : Fin 4) {l r : ℚ} (hu : l ≤ 1 / 2) (h : r ∈ Set.Icc 0 (2 * l)) : + ∀ i, depth j l r i ≤ 1 := by + intro i + unfold depth + split <;> linarith [h.1, h.2] + +theorem merged (j : Fin 4) (hj : j ≠ 3) {l : ℚ} (hl : l ∈ Set.Ioc 0 (1 / 2)) + (u : K0 E) (hu : 0 ≤ val E u) : + B.rate H (B.pos j + t (2 * l) * u) (depth j l (2 * l)) ≤ 2 * (l : ℝ) := by + obtain ⟨a, b, ha, hb, ha', hb', he⟩ : + ∃ a b : Fin 4, a ≠ j ∧ b ≠ j ∧ a ≠ 3 ∧ b ≠ 3 ∧ ({a, b, j, 3} : Finset (Fin 4)) = Finset.univ + := by + fin_cases j + · exact ⟨1, 2, by decide⟩ + · exact ⟨0, 2, by decide⟩ + · exact ⟨0, 1, by decide⟩ + · exact (hj rfl).elim + let z := B.pos j + t (2 * l) * u + have hL : 2 * l ≤ 1 := by linarith [hl.2] + have hpos : 0 ≤ 2 * l := by linarith [hl.1] + have hab : diskGap (B.pos a) (B.pos b) 0 0 = 0 := by + rw [gap_of_le le_rfl ((le_min (B.integral a) (B.integral b)).trans ((val E).map_sub _ _)) + zero_le_one, sub_self] + have hbj : diskGap (B.pos b) (B.pos j) 0 (2 * l) = 2 * l := by + rw [gap_of_le hpos (by simp [B.separate b j hb]) zero_le_one, sub_zero] + have hjz : diskGap (B.pos j) z (2 * l) (2 * l) = 0 := by + rw [gap_symm, gap_of_le le_rfl (by simpa [z] using scaled_le (2 * l) hu) hL, sub_self] + have hp := H.path (B.pts z) (depth j l (2 * l)) (depth_le j hl.2 ⟨hpos, le_rfl⟩) a b j 3 he + simpa [pts, depth, ha, hb, ha', hb', hj, ← two_mul, hab, hbj, hjz, rate] using hp + +private theorem displacement (i j : Fin 4) (hij : i ≠ j) {r : ℚ} (hr : 0 < r) : + val E (B.pos i - (B.pos j + t r)) = 0 := by + rw [show B.pos i - (B.pos j + t r) = (B.pos i - B.pos j) + (-t r) by ring] + have h : val E (B.pos i - B.pos j) < val E (-t r) := by + rw [B.separate i j hij, AddValuation.map_neg, val_t] + exact WithTop.coe_pos.mpr hr + rw [AddValuation.map_add_of_distinct_val _ h.ne, min_eq_left h.le, B.separate i j hij] + +theorem collision_point {l h : ℚ} (hl : l ∈ Set.Ioc 0 (1 / 2)) (hh : h ∈ Set.Ioc 0 (2 * l)) : + ∃ z : K0 E, val E (B.pos 0 - z) = 0 ∧ val E (B.pos 1 - z) = 0 ∧ val E (B.pos 2 - z) + = ↑(2 * l - h) ∧ + B.rate H z (depth 2 l (2 * l - h)) ≤ 2 * (l : ℝ) + h * (B.X H l - 1) := by + let r := 2 * l - h + have hr : 0 ≤ r := sub_nonneg.mpr hh.2 + have hu : r ≤ 2 * l := sub_le_self _ hh.1.le + let k := depth 2 l r + have hk : ∀ i, k i ≤ 1 := depth_le _ hl.2 ⟨hr, hu⟩ + have hl' : l ≤ 1 := by linarith [hl.2] + change ∃ z, _ ∧ _ ∧ val E (B.pos 2 - z) = ↑r ∧ B.rate H z k ≤ _ + rcases hr.eq_or_lt with he | he + · have hk₀ : k = fun _ => l := by ext; simp [k, depth, ← he] + refine ⟨B.pos 3, B.separate _ _ (by decide), B.separate _ _ (by decide), + by simp [← he, B.separate 2 3 (by decide)], ?_⟩ + rw [hk₀, show h = 2 * l by unfold r at he; linarith] + have H' := B.le_generic H hl.1.le hl' (B.integral 3) + rw [B.generic_eq H hl.1] at H' + push_cast + linarith only [H'] + · refine ⟨B.pos 2 + t r, B.displacement 0 2 (by decide) he, B.displacement 1 2 (by decide) he, + by simp, ?_⟩ + obtain ⟨u, w, hu', hw, e⟩ := B.ray H (a := B.pos 2) (r := r) hh.1 he k (depth 2 l (2 * l)) + (fun _ => l) hk (depth_le _ hl.2 ⟨by linarith [hl.1], le_rfl⟩) (fun _ => hl') + (fun i => by unfold k depth; split <;> unfold r <;> ring) (v := 1) (by simp) + rw [show r + h = 2 * l by unfold r; ring, sub_self, t_zero, one_mul, mul_one] at e + have h₁ := B.merged H 2 (by decide) hl u hu' + have h₂ := B.le_generic H hl.1.le hl' ((le_min (B.integral 2) hw).trans ((val E).map_add _ _)) + rw [B.generic_eq H hl.1] at h₂ + have hi := e.trans (add_le_add (mul_le_mul_of_nonneg_left h₁ (Rat.cast_nonneg.mpr hr)) + (mul_le_mul_of_nonneg_left h₂ (Rat.cast_nonneg.mpr hh.1.le))) + refine le_of_mul_le_mul_left ?_ (show (0 : ℝ) + < 2 * l by exact_mod_cast (show 0 < 2 * l by linarith [hl.1])) + rw [show (r : ℝ) = 2 * l - h by simp [r]] at hi + linarith only [hi] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Branches +end + +/- A shrinking outer arm is controlled by a larger generic placement. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Branches + +variable {F : Type} [Field F] {E : Type*} [Field E] (B : Branches E) (H : MotionTree F E) + +/-- Evaluates `if i = 3 then l - 2 * r else l` at the input `i`. -/ +def outer (l r : ℚ) : Four ℚ := fun i => if i = 3 then l - 2 * r else l + +/-- The quantity computed by `B.rate H 0 (outer l l) / (2 * (l : ℝ))`. -/ +def Y (l : ℚ) := B.rate H 0 (outer l l) / (2 * (l : ℝ)) + +theorem outer_le {l r : ℚ} (hl : l ≤ 1) (hr : 0 ≤ r) : ∀ i, outer l r i ≤ 1 := by + intro i + unfold outer + split <;> linarith + +theorem outer_bound {l : ℚ} (hl : l ∈ Set.Ioc 0 1) : + B.rate H 0 (outer l l) ≤ 6 * (l : ℝ) := by + have hh (i j : Fin 4) : diskGap (B.pos i) (B.pos j) l l ≤ 2 * l := by + have e := gap_bound hl.1.le hl.1.le zero_le_one + ((le_min (B.integral i) (B.integral j)).trans ((val E).map_sub _ _)) + linarith + have h : diskGap (B.pos 2) 0 l (-l) ≤ 2 * l := by + have hv : ((-l : ℚ) : WithTop ℚ) ≤ val E (B.pos 2 - 0) := by + rw [sub_zero] + exact (WithTop.coe_le_coe.mpr (neg_nonpos.mpr hl.1.le)).trans (B.integral _) + have := gap_bound (by linarith [hl.1] : -l ≤ l) le_rfl (by linarith [hl.1]) hv + linarith + have hp := H.path (B.pts 0) (outer l l) (outer_le hl.2 hl.1.le) 0 1 2 3 (by decide) + change B.rate H 0 (outer l l) ≤ + (diskGap (B.pos 0) (B.pos 1) l l + diskGap (B.pos 1) (B.pos 2) l l + + diskGap (B.pos 2) 0 l (l - 2 * l) : ℚ) at hp + rw [show l - 2 * l = -l by ring] at hp + exact hp.trans (by exact_mod_cast (show _ ≤ 6 * l by linarith only [hh 0 1, hh 1 2, h])) + +theorem outer_merge {l : ℚ} (hl : l ∈ Set.Ioc 0 1) (u : K0 E) (hu : 0 ≤ val E u) : + B.rate H (t (-l) * u) (outer l l) ≤ B.rate H 0 (outer l l) := by + apply H.same _ _ _ (outer_le hl.2 hl.1.le) + intro i + by_cases hi : i = 3 + · simpa only [pts, outer, ite_eq_left hi, sub_zero, show l - 2 * l + = -l by ring] using scaled_le (-l) hu + · simp [pts, hi] + +private theorem outer_radial {l L : ℚ} (hl : 0 < l) (h : l < L) (hL : L ≤ 1) : + B.rate H 0 (outer l l) ≤ (l : ℝ) / L * B.rate H (t (-l)) (outer L l) := by + have hp := hl.trans h + have hl' := h.le.trans hL + have h₁ (i : Fin 4) : diskGap (B.pts 0 i) (B.pts 0 i) 0 (outer l l i) = l := by + by_cases hi : i = 3 + · rw [outer, ite_eq_left hi, gap_symm, gap_same _ (by linarith) (by linarith)] + ring + · rw [outer, ite_eq_right hi, gap_same _ hl.le zero_le_one, sub_zero] + have hv : val E (0 - t (-l)) = ↑(-l) := by rw [zero_sub, AddValuation.map_neg, val_t] + have h₂ (i : Fin 4) : diskGap (B.pts 0 i) (B.pts (t (-l)) i) 0 (outer L l i) = L := by + by_cases hi : i = 3 + · simp only [pts, outer, ite_eq_left hi] + rw [gap_branch (by linarith) (by linarith) hv] + ring + · simp only [pts, outer, ite_eq_right hi, gap_same _ hp.le zero_le_one, sub_zero] + have h₃ (i : Fin 4) : + diskGap (B.pts 0 i) (B.pts (t (-l)) i) (outer l l i) (outer L l i) = L - l := by + by_cases hi : i = 3 + · simp only [pts, outer, ite_eq_left hi] + rw [gap_branch (by linarith) (by linarith) hv] + ring + · simp only [pts, outer, ite_eq_right hi, gap_same _ h.le hl'] + have hch := H.chord (B.pts 0) (B.pts (t (-l))) (B.pts 0) (fun _ => 0) (outer L l) (outer l l) + (fun _ => zero_le_one) (outer_le hL hl.le) (outer_le hl' hl.le) (l / L) + (by positivity) ((div_le_one hp).mpr h.le) + (fun i => by rw [h₁, h₂, div_mul_cancel₀ _ hp.ne']) + (fun i => by rw [h₃, h₂, sub_mul, one_mul, div_mul_cancel₀ _ hp.ne']) + have he : H.rate (B.pts 0) (fun _ => 0) = 0 := le_antisymm + (by simpa [rate] using B.bound H (z := 0) (by simp) (l := 0) le_rfl zero_le_one) + (H.nonneg _ _ fun _ => zero_le_one) + simpa only [he, mul_zero, zero_add, Rat.cast_div, rate] using hch + +theorem negative_limit {L : ℚ} (hL : L ∈ Set.Ioc 0 1) (δ : ℝ) (hd : 0 < δ) : + ∃ r : ℚ, 0 < r ∧ ∀ l ∈ Set.Ioc 0 r, B.Y H l ≤ B.X H L + δ := by + have hpos : (0 : ℝ) < L := Rat.cast_pos.mpr hL.1 + obtain ⟨r, hr, hr'⟩ := exists_rat_btwn (lt_min hpos (by positivity : (0 : ℝ) < L * δ / 3)) + refine ⟨r, Rat.cast_pos.mp hr, fun l hl => ?_⟩ + have he := (Rat.cast_le.mpr hl.2 : (l : ℝ) ≤ r).trans_lt hr' + have h : l < L := Rat.cast_lt.mp (he.trans_le (min_le_left _ _)) + have hs : (l : ℝ) < L * δ / 3 := he.trans_le (min_le_right _ _) + have hp : (0 : ℝ) < l := Rat.cast_pos.mpr hl.1 + obtain ⟨u, v, hu, hv, hb⟩ := B.ray H (a := 0) (r := -l) hl.1 (sub_pos.mpr h) + (outer L l) (fun _ => L) (outer L L) (outer_le hL.2 hl.1.le) (fun _ => hL.2) + (outer_le hL.2 hL.1.le) (fun i => by unfold outer; split <;> ring) (v := 1) (by simp) + simp only [zero_add, mul_one, neg_add_cancel, t_zero, one_mul, show -l - (L - l) = -L by ring, + Rat.cast_sub, add_sub_cancel] at hb + have hi := B.le_generic H hL.1.le hL.2 hu + have hj := (B.outer_merge H hL v hv).trans (B.outer_bound H hL) + have hx : 0 ≤ B.generic H L := (B.rate_nonneg H _ _ (fun _ => hL.2)).trans hi + have hu' := mul_le_mul_of_nonneg_left hi (sub_nonneg.mpr (Rat.cast_le.mpr h.le : (l : ℝ) ≤ L)) + have hv' := mul_le_mul_of_nonneg_left hj hp.le + have hm : B.rate H (t (-l)) (outer L l) ≤ B.generic H L + 6 * l := by + refine le_of_mul_le_mul_left ?_ hpos + linarith only [hb, hu', hv', mul_nonneg hp.le hx] + have hb' := (B.outer_radial H hl.1 h hL.2).trans + (mul_le_mul_of_nonneg_left hm (div_nonneg hp.le hpos.le)) + rw [B.generic_eq H hL.1] at hb' + unfold Y + rw [div_le_iff₀ (by positivity)] + refine hb'.trans ?_ + rw [div_mul_eq_mul_div, div_le_iff₀ hpos] + linarith only [mul_le_mul_of_nonneg_left hs.le hp.le] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Branches +end + +/- Applying the submean test on the collision, unused, and outer arms. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 + +variable {F : Type} [Field F] {E : Type*} [Field E] + +namespace Branches + +variable (B : Branches E) (H : MotionTree F E) + +private def lengths (l : ℚ) : Option (Fin 4) → ℚ + | none => l + | some j => if j = 3 then l else 2 * l + +private def depths (l : ℚ) : Option (Fin 4) → Four ℚ + | none => outer l l + | some j => if j = 3 then fun _ => 3 * l / 2 else depth j l (2 * l) + +private theorem weights {l : ℚ} (hl : 0 < l) (i : Fin 4) : + ∑ j, (depths l j i - l) / lengths l j = 0 := by + rw [Fintype.sum_option, Fin.sum_univ_four] + fin_cases i <;> simp [depths, lengths, depth, outer] <;> field_simp <;> ring + +private theorem scalar_star {l a b c d e f : ℝ} (hl : 0 < l) + (h : 0 ≤ (b - a) / l + ((c - a) / (2 * l) + (d - a) / (2 * l) + (e - a) / (2 * l) + + (f - a) / l)) : + 7 * a ≤ 2 * b + c + d + e + 2 * f := by + field_simp at h + linarith only [h] + +theorem five_arms {l : ℚ} (hl : l ∈ Set.Ioc 0 (1 / 2)) : + 7 * B.X H l ≤ 3 + 2 * B.Y H l + 3 * B.X H (3 * l / 2) := by + have hl' : l ∈ Set.Ioc 0 1 := ⟨hl.1, by linarith [hl.2]⟩ + have hL : 3 * l / 2 ∈ Set.Ioc 0 1 := ⟨by linarith [hl.1], by linarith [hl.2]⟩ + have hp : (0 : ℝ) < l := Rat.cast_pos.mpr hl.1 + have hr : ∀ j, 0 < lengths l j := by + rintro (_|j) + · exact hl.1 + · simp only [lengths] + split <;> linarith [hl.1] + have hk : ∀ j i, depths l j i ≤ 1 := by + rintro (_|j) i + · exact outer_le hl'.2 hl.1.le _ + · simp only [depths] + split + · exact hL.2 + · exact depth_le _ hl.2 ⟨by linarith [hl.1], le_rfl⟩ _ + have h : B.generic H l ≤ (2 * B.rate H 0 (outer l l) + 6 * l + 2 * B.generic H (3 * l / 2)) / 7 + := by + apply B.generic_le H + intro v hv + obtain ⟨u, hu, he⟩ := B.star H 0 1 B.pos B.integral B.separate (lengths l) hr + (fun _ => l) (depths l) (fun _ => hl'.2) hk (weights hl.1) v hv + simp only [Fintype.sum_option, Fin.sum_univ_four, one_mul, zero_add, + armEnd, lengths, depths, Fin.reduceEq, ↓reduceIte, Rat.cast_mul, Rat.cast_ofNat] at he + have h₀ := B.merged H 0 (by decide) hl _ (hu (some 0)) + have h₁ := B.merged H 1 (by decide) hl _ (hu (some 1)) + have h₂ := B.merged H 2 (by decide) hl _ (hu (some 2)) + have h₃ := B.le_generic H hL.1.le hL.2 + ((le_min (B.integral 3) (scaled_pos hl.1 (hu (some 3))).le).trans ((val E).map_add _ _)) + have h₄ := B.outer_merge H hl' _ (hu none) + linarith only [scalar_star hp he, h₀, h₁, h₂, h₃, h₄] + rw [B.generic_eq H hl.1, B.generic_eq H hL.1, + show B.rate H 0 (outer l l) = 2 * (l : ℝ) * B.Y H l by + unfold Y; rw [mul_div_cancel₀ _ (by positivity)]] at h + push_cast at h + exact le_of_mul_le_mul_left (by linarith only [h]) hp + +/-- The common label near the branch point has normalized price at most +three halves in the limit. An infimum avoids any derivative assumptions. -/ +theorem small_X {ε : ℝ} (hε : 0 < ε) : + ∃ l ∈ Set.Ioc 0 (1 / 2 : ℚ), B.X H l ≤ 3 / 2 + ε := by + by_contra! lower + let S := B.X H '' Set.Ioc 0 (1 / 2 : ℚ) + have hs : S.Nonempty := ⟨_, 1 / 2, ⟨by norm_num, le_rfl⟩, rfl⟩ + have hb : 3 / 2 + ε ∈ lowerBounds S := by + rintro _ ⟨l, hl, rfl⟩ + exact (lower l hl).le + have he := le_csInf hs hb + obtain ⟨_, ⟨t, ht, rfl⟩, hsmall⟩ := exists_lt_of_csInf_lt hs + (show sInf S < sInf S + ε / 4 by linarith) + have ht' : t ∈ Set.Ioc 0 (1 : ℚ) := ⟨ht.1, by linarith [ht.2]⟩ + obtain ⟨r, hr, hr'⟩ := B.negative_limit H ht' (ε / 4) (by positivity) + let l := min (t / 3) r + have hl : 0 < l := lt_min (by linarith [ht.1]) hr + have hu : l ≤ t / 3 := min_le_left _ _ + have hlt : l ∈ Set.Ioc 0 (1 / 2 : ℚ) := ⟨hl, by linarith [ht.2]⟩ + have hi : sInf S ≤ B.X H l := csInf_le ⟨_, hb⟩ ⟨l, hlt, rfl⟩ + have hy := hr' l ⟨hl, min_le_right _ _⟩ + have hx := B.monotone_X H (show 3 * l / 2 ∈ Set.Ioc 0 (1 : ℚ) by + constructor <;> linarith [ht.2]) ht' + (show 3 * l / 2 ≤ t by linarith) + linarith only [B.five_arms H hlt, hy, hx, hi, he, hsmall, hε] + +end Branches + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/Rigidity.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/Rigidity.lean new file mode 100644 index 0000000000..b99334fed2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/Rigidity.lean @@ -0,0 +1,893 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Field +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.FourArms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.TreePrice +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Chord +public import Mathlib.Order.Filter.Cocardinal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.Zoom + +/-! # Submean tests on a valuation disk -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +open Filter +variable {F E : Type} [Field F] [Field E] {X : Type*} [PseudoMetricSpace X] + +/-- The quantity computed by `(r j : ℝ)⁻¹ / ∑ k, (r k : ℝ)⁻¹`. -/ +def weight {n : ℕ} (r : Option (Fin n) → ℚ) (j : Option (Fin n)) : ℝ := + (r j : ℝ)⁻¹ / ∑ k, (r k : ℝ)⁻¹ + +/-- The moving at of type `Prop` for the given inputs. -/ +def MovingAt (E : Type) [Field E] [MulAction (G E) X] (A : Atlas F X) (x : X) : Prop := + ∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] + (a b : S → K0 E) (v : K0 E), 0 ≤ val E v → + ∀ {n : ℕ} (c : Fin n → K0 E) (r : Option (Fin n) → ℚ), + (∀ j, 0 ≤ val E (c j)) → (∀ i j, i ≠ j → val E (c i - c j) = 0) → + (∀ j, 0 < r j) → (∀ i, 0 < val E (a i)) → (∀ i, 0 < val E (b i)) → + (∀ i, 0 < val E (t (-r none) * b i)) → + ∀ᶠ u : E in cocountable, A.Submean (weight r) + (fun i => shift (a i + b i * v) • x) + (fun j i => shift (a i + b i * armEnd c r (C u) j) • x) + +/-- The condition `∀ x, MovingAt E A x` on the specified data. -/ +def Moving (E : Type) [Field E] [MulAction (G E) X] (A : Atlas F X) : Prop := + ∀ x, MovingAt E A x + +/-- The leaf tests of type `Prop` for the given inputs. -/ +def LeafTests (A : Atlas F X) (L : K0 E → X) : Prop := + ∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (a b : S → K0 E) (v : K0 E), + 0 ≤ val E v → ∀ {n : ℕ} (c : Fin n → K0 E) (r : Option (Fin n) → ℚ), + (∀ j, 0 ≤ val E (c j)) → (∀ i j, i ≠ j → val E (c i - c j) = 0) → + (∀ j, 0 < r j) → + ∃ u : K0 E, 0 ≤ val E u ∧ A.Submean (weight r) + (fun i => L (a i + b i * v)) (fun j i => L (a i + b i * armEnd c r u j)) + +theorem cocountable_neBot (E : Type) [Uncountable E] : (cocountable (α := E)).NeBot := by + constructor + intro h + have he : (∅ : Set E) ∈ cocountable := by simp [h] + exact Set.not_countable_univ (by simpa using mem_cocountable.mp he) + +theorem cocountable_countable (E : Type) : CountableInterFilter (cocountable (α := E)) := + cardinalInterFilter_aleph_one_iff.mp inferInstance + +theorem integral_C (a : E) : 0 ≤ val E (C a) := by + rcases eq_or_ne a 0 with rfl | ha + · simp + · rw [val_C ha] + +variable {n : ℕ} {r : Option (Fin n) → ℚ} + +private theorem denominator_pos (h : ∀ j, 0 < r j) : 0 < ∑ j, (r j : ℝ)⁻¹ := + Finset.sum_pos (fun i _ => inv_pos.mpr (Rat.cast_pos.mpr (h i))) Finset.univ_nonempty + +theorem weight_pos (h : ∀ j, 0 < r j) (j) : 0 < weight r j := + div_pos (inv_pos.mpr (Rat.cast_pos.mpr (h j))) (denominator_pos h) + +theorem weight_sum (h : ∀ j, 0 < r j) : ∑ j, weight r j = 1 := by + unfold weight + rw [← Finset.sum_div, div_self (denominator_pos h).ne'] + +theorem weight_scale (e : ℚ) (he : 0 < e) : weight (fun j => e * r j) = weight r := by + funext j + simp only [weight, Rat.cast_mul, mul_inv_rev, ← Finset.sum_mul] + exact mul_div_mul_right _ _ (inv_ne_zero (Rat.cast_ne_zero.mpr he.ne')) + +theorem weight_iff (h : ∀ j, 0 < r j) (v : ℝ) (w : Option (Fin n) → ℝ) : + v ≤ ∑ j, weight r j * w j ↔ 0 ≤ ∑ j, (w j - v) / (r j : ℝ) := by + simp only [weight, div_mul_eq_mul_div, ← Finset.sum_div, le_div_iff₀ (denominator_pos h), + sub_div, Finset.sum_sub_distrib, sub_nonneg] + simp only [div_eq_mul_inv, Finset.mul_sum, mul_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- +# From leaves to points of the disk tree + +The leaf metric alone does not locate midpoints in the ambient space. +A three-arm test with a moving midpoint supplies the missing estimate. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +open Routing + +/-- The data for the leaves construction, including `A`, `L`, `along`, `gap`, `tests`. -/ +structure Leaves (F E X : Type) [Field F] [Field E] [PseudoMetricSpace X] where + /-- The `Leaves` component of type `Atlas F X`. -/ + A : Atlas F X + /-- The `Leaves` component of type `K0 E → X`. -/ + L : K0 E → X + along : ∀ (u : Fraction) (x y : X), ∃ m, Along u x y m + gap : ∀ x y, dist (L x) (L y) = (diskGap x y 1 1 : ℝ) + tests : LeafTests A L + +namespace Leaves +variable {F E X : Type} [Field F] [Field E] [PseudoMetricSpace X] (M : Leaves F E X) + +/-- The quantity computed by `(M.along ⟨1 / 2, by norm_num, by norm_num⟩ (M.L z) (M.L (z + t +l))).choose`. -/ +def pt (z : K0 E) (l : ℚ) := + (M.along ⟨1 / 2, by norm_num, by norm_num⟩ (M.L z) (M.L (z + t l))).choose + +theorem near_leaf {x y : K0 E} {r : ℚ} (hr : r ≤ 1) (h : ↑r ≤ val E (x - y)) : + dist (M.L x) (M.L y) ≤ 2 * (1 - (r : ℝ)) := by + rw [M.gap] + have hb := gap_bound hr hr hr h + exact_mod_cast (show diskGap x y 1 1 ≤ 2 * (1 - r) by linarith) + +theorem branch_leaf {x y : K0 E} {r : ℚ} (hr : r ≤ 1) (h : val E (x - y) = ↑r) : + dist (M.L x) (M.L y) = 2 * (1 - (r : ℝ)) := by + rw [M.gap, gap_branch hr hr h] + push_cast + ring + +theorem ends (z : K0 E) {l : ℚ} (hl : l ≤ 1) : + dist (M.L z) (M.L (z + t l)) = 2 * (1 - (l : ℝ)) := + M.branch_leaf hl (by rw [AddValuation.map_sub_swap, add_sub_cancel_left, val_t]) + +theorem midpoint (z : K0 E) {l : ℚ} (hl : l ≤ 1) : + dist (M.L z) (M.pt z l) = 1 - (l : ℝ) ∧ dist (M.pt z l) (M.L (z + t l)) = 1 - (l : ℝ) := by + have h := (M.along ⟨1 / 2, by norm_num, by norm_num⟩ (M.L z) (M.L (z + t l))).choose_spec + have h₁ := h.start + have h₂ := h.rev.start + rw [dist_comm (M.L (z + t l)) _, dist_comm (M.L (z + t l)) _] at h₂ + rw [M.ends z hl] at h₁ h₂ + change dist (M.L z) (M.pt z l) = (1 / 2) * _ at h₁ + change dist (M.pt z l) (M.L (z + t l)) = (1 - 1 / 2) * _ at h₂ + constructor <;> linarith + +private theorem test (z : K0 E) {l : ℚ} (hl : l ≤ 1) (b v : K0 E) (hv : 0 ≤ val E v) + {n : ℕ} (c : Fin n → K0 E) (r : Option (Fin n) → ℚ) + (hc : ∀ j, 0 ≤ val E (c j)) (hd : ∀ i j, i ≠ j → val E (c i - c j) = 0) + (hr : ∀ j, 0 < r j) (p : Option (Fin n) → X) + (hp : ∑ j, weight r j * dist (M.L z) (p j) ≤ 1 - (l : ℝ)) + (hq : ∑ j, weight r j * dist (p j) (M.L (z + t l)) ≤ 1 - (l : ℝ)) : + ∃ u : K0 E, 0 ≤ val E u ∧ + 0 ≤ ∑ j, (dist (p j) (M.L (z + b * armEnd c r u j)) - dist (M.pt z l) (M.L (z + + b * v))) / (r j : ℝ) := by + let a := ![z, z + t l, z] + let b' := ![0, 0, b] + obtain ⟨u, hu, h⟩ := M.tests (Fin 3) a b' v hv c r hc hd hr + refine ⟨u, hu, (weight_iff hr _ _).mp ?_⟩ + obtain ⟨h₁, h₂⟩ := M.midpoint z hl + have H := h.extend (fun j => (weight_pos hr j).le) (fun _ : Unit => M.pt z l) + (fun j _ => p j) (by + intro _ + refine ⟨0, 1, 1 / 2, ?_⟩ + simp only [a, b', Matrix.cons_val_zero, Matrix.cons_val_one, zero_mul, add_zero, h₁, h₂, + M.ends z hl] + exact ⟨by ring, by ring, hp, hq⟩) + exact H.wire (.inr ()) (.inl 2) + +private theorem outward (z : K0 E) {l a : ℚ} (hl : l ≤ 1) (ha : a ≤ l) + (w : K0 E) (hw : 0 ≤ val E w) : + dist (M.pt z l) (M.L (z + t a * w)) ≤ (1 - (l : ℝ)) + 2 * (1 - (a : ℝ)) := by + refine (dist_triangle _ (M.L z) _).trans ?_ + rw [dist_comm (M.pt z l) _, (M.midpoint z hl).1, dist_comm (M.L z) _] + refine add_le_add le_rfl (M.near_leaf (ha.trans hl) ?_) + rw [add_sub_cancel_left] + exact scaled_le a hw + +private theorem unlimited {a b : ℝ} (h : ∀ s : ℚ, 0 < s → (s : ℝ) * a ≤ b) : a ≤ 0 := by + by_contra! ha + obtain ⟨s, hs⟩ := exists_rat_gt (max 0 (b / a)) + exact (h s (Rat.cast_pos.mp ((le_max_left _ _).trans_lt hs))).not_gt + ((div_lt_iff₀ ha).mp ((le_max_right _ _).trans_lt hs)) + +/-- Points in the unit disk of the midpoint comparison. -/ +theorem inner (z : K0 E) {l : ℚ} (hl : l ≤ 1) (v : K0 E) (hv : 0 ≤ val E v) : + dist (M.pt z l) (M.L (z + t l * v)) ≤ 1 - (l : ℝ) := by + rcases hl.eq_or_lt with rfl | hl + · simpa using M.outward z le_rfl le_rfl v hv + let h := 1 - l + have hh : 0 < h := sub_pos.mpr hl + have hh' : (0 : ℝ) < h := Rat.cast_pos.mpr hh + have ee : (h : ℝ) = 1 - l := by simp [h] + let J := dist (M.pt z l) (M.L (z + t l * v)) + have I : 2 * (J - h) ≤ 0 := by + refine unlimited (b := (3 * (h : ℝ) - J) * h) fun s hs => ?_ + let r : Option (Fin 2) → ℚ := fun j => j.elim s (fun _ => h) + let c : Fin 2 → K0 E := ![0, 1] + let p : Option (Fin 2) → X := fun j => j.elim (M.pt z l) ![M.L z, M.L (z + t l)] + have hs' : (0 : ℝ) < s := Rat.cast_pos.mpr hs + have hr (j) : 0 < r j := by cases j <;> assumption + have hc (j) : 0 ≤ val E (c j) := by fin_cases j <;> simp [c] + have hd (i j) (hne : i ≠ j) : val E (c i - c j) = 0 := by + fin_cases i <;> fin_cases j <;> simp_all [c] + have e : weight r (some 0) = weight r (some 1) := rfl + have sum := weight_sum hr + rw [Fintype.sum_option, Fin.sum_univ_two, e] at sum + have es : (weight r none + (weight r (some 1) + weight r (some 1))) * (1 - (l : ℝ)) = 1 - l + := by + rw [sum, one_mul] + obtain ⟨u, hu, H⟩ := M.test z hl.le (t l) v hv c r hc hd hr p (by + simp only [Fintype.sum_option, Fin.sum_univ_two, p, Option.elim_none, Option.elim_some, + Matrix.cons_val_zero, Matrix.cons_val_one, dist_self, (M.midpoint z hl.le).1, + M.ends z hl.le] + linarith only [es]) (by + simp only [Fintype.sum_option, Fin.sum_univ_two, p, Option.elim_none, Option.elim_some, + Matrix.cons_val_zero, Matrix.cons_val_one, dist_self, (M.midpoint z hl.le).2, + M.ends z hl.le, e] + linarith only [es]) + simp only [Fintype.sum_option, Fin.sum_univ_two, p, c, r, armEnd, Option.elim_none, + Option.elim_some, + Matrix.cons_val_zero, Matrix.cons_val_one, mul_zero, zero_add, mul_add, mul_one, + ← mul_assoc, ← t_add, ← sub_eq_add_neg, show l + h = 1 by unfold h; ring] at H + have vanish (a : K0 E) : dist (M.L a) (M.L (a + t 1 * u)) = 0 := by + rw [dist_comm] + apply le_antisymm _ dist_nonneg + simpa using M.near_leaf (x := a + t 1 * u) (y := a) le_rfl + (by rw [add_sub_cancel_left]; exact scaled_le 1 hu) + rw [← add_assoc z (t l), vanish, vanish] at H + have hu' := M.outward z hl.le (show l - s ≤ l by linarith) u hu + rw [Rat.cast_sub] at hu' + change 0 ≤ (_ - J) / _ + ((0 - J) / _ + (0 - J) / _) at H + rw [← add_div, div_add_div _ _ hs'.ne' hh'.ne', le_div_iff₀ (mul_pos hs' hh')] at H + rw [ee] at H ⊢ + linarith only [H, mul_le_mul_of_nonneg_right hu' (ee ▸ hh'.le)] + linarith + +/-- Any distant leaf lies on an arm through the same midpoint. -/ +theorem outer (z : K0 E) {l a : ℚ} (hl : l ≤ 1) (ha : a ≤ l) (v : K0 E) (hv : 0 ≤ val E v) : + dist (M.pt z l) (M.L (z + t a * v)) ≤ 1 + (l : ℝ) - 2 * a := by + rcases ha.eq_or_lt with rfl | ha + · linarith only [M.inner z hl v hv] + let J := dist (M.pt z l) (M.L (z + t a * v)) + have e : J - (1 + (l : ℝ) - 2 * a) ≤ 0 := by + refine unlimited (b := (3 - (l : ℝ) - 2 * a - J) * (l - a)) fun s hs => ?_ + let r : Option (Fin 1) → ℚ := fun j => j.elim s (fun _ => l - a) + have hr : ∀ j, 0 < r j := by + intro j; cases j + · exact hs + · exact sub_pos.mpr ha + have hs' : (0 : ℝ) < s := Rat.cast_pos.mpr hs + have ha' : (0 : ℝ) < l - a := sub_pos.mpr (Rat.cast_lt.mpr ha) + obtain ⟨u, hu, H⟩ := M.test z hl (t a) v hv (fun _ => 0) r (by simp) + (fun i j h => (h (Subsingleton.elim _ _)).elim) hr (fun _ => M.pt z l) + (by simp only [← Finset.sum_mul, weight_sum hr, one_mul, (M.midpoint z hl).1, le_refl]) + (by simp only [← Finset.sum_mul, weight_sum hr, one_mul, (M.midpoint z hl).2, le_refl]) + simp only [Fintype.sum_option, Fin.sum_univ_one, r, armEnd, Option.elim_none, Option.elim_some, + zero_add, ← mul_assoc, ← t_add, ← sub_eq_add_neg, add_sub_cancel, Rat.cast_sub] at H + have hu' := M.outward z hl (show a - s ≤ l by linarith) u hu + rw [Rat.cast_sub] at hu' + change 0 ≤ (_ - J) / _ + (_ - J) / _ at H + rw [div_add_div _ _ hs'.ne' ha'.ne', le_div_iff₀ (mul_pos hs' ha')] at H + linarith only [H, mul_le_mul_of_nonneg_right hu' ha'.le, + mul_le_mul_of_nonneg_left (M.inner z hl u hu) hs'.le] + exact sub_nonpos.mp e + +end Leaves +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- # Distances between the chosen disk midpoints -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Leaves +open Routing +variable {F E X : Type} [Field F] [Field E] [PseudoMetricSpace X] (M : Leaves F E X) + +include M in +/-- Two ordered points on a common segment have distance equal to +the difference of their distances from the initial endpoint. -/ +private theorem ordered (a b x y : X) + (hx : dist a x + dist x b = dist a b) (hy : dist a y + dist y b = dist a b) + (hxy : dist a x ≤ dist a y) : dist x y = dist a y - dist a x := by + refine le_antisymm ?_ (by linarith [dist_triangle a x y]) + by_cases h : dist a b = 0 + · linarith [dist_nonneg (x := x) (y := b), dist_triangle_left x y a] + have hh : 0 < dist a b := lt_of_le_of_ne dist_nonneg (Ne.symm h) + let s : Fraction := ⟨dist a x / dist a b, div_nonneg dist_nonneg hh.le, + (div_le_one hh).mpr (by linarith [dist_nonneg (x := x) (y := b)])⟩ + obtain ⟨p, hp⟩ := M.along s a b + have e : s.val * dist a b = dist a x := div_mul_cancel₀ _ h + have bound (z : X) (hz : dist a z + dist z b = dist a b) : + dist p z ^ 2 ≤ (dist a z - dist a x) ^ 2 := by + refine (hp z).trans_eq ?_ + rw [dist_comm b z, show dist z b = dist a b - dist a z by linarith, ← e] + ring + have h₁ : dist p x = 0 := by nlinarith only [bound x hx] + have h₂ := (sq_le_sq₀ dist_nonneg (sub_nonneg.mpr hxy)).mp (bound y hy) + linarith [dist_triangle_left x y p] + +private theorem reached {z w : K0 E} {l a : ℚ} (hl : l ≤ 1) (ha : a ≤ l) + (h : ↑a ≤ val E (w - z)) : dist (M.pt z l) (M.L w) ≤ 1 + (l : ℝ) - 2 * a := by + have hb := M.outer z hl ha _ (le_unscale h) + rwa [unscale, add_sub_cancel] at hb + +theorem across {z w : K0 E} {l a : ℚ} (hl : l ≤ 1) (ha : a ≤ l) + (h : val E (w - z) = ↑a) : + dist (M.L z) (M.pt z l) + dist (M.pt z l) (M.L w) = dist (M.L z) (M.L w) := by + apply le_antisymm _ (dist_triangle _ _ _) + rw [(M.midpoint z hl).1, dist_comm (M.L z) (M.L w), M.branch_leaf (ha.trans hl) h] + linarith only [M.reached hl ha h.ge] + +private theorem nested {z w : K0 E} {l m : ℚ} (hl : l ≤ m) (hm : m ≤ 1) + (h : ↑l ≤ val E (w - z)) : dist (M.pt z l) (M.pt w m) = (m : ℝ) - l := by + have hl' := hl.trans hm + let u := w + t l + have hv : val E (u - w) = ↑l := by unfold u; rw [add_sub_cancel_left, val_t] + have hu : ↑l ≤ val E (u - z) := by + rw [show u - z = (u - w) + (w - z) by ring] + exact (val E).map_le_add hv.ge h + have hx := M.reached hl' le_rfl h + have hy := M.reached hl' le_rfl hu + rw [dist_comm] at hx + have hb : dist (M.L w) (M.L u) = 2 * (1 - (l : ℝ)) := M.ends w hl' + have H := dist_triangle (M.L w) (M.pt z l) (M.L u) + have h₁ : dist (M.L w) (M.pt z l) = 1 - (l : ℝ) := by linarith + have h₂ := (M.midpoint w hm).1 + rw [dist_comm, M.ordered (M.L w) (M.L u) _ _ (M.across hm hl hv) + (by linarith) (by rw [h₁, h₂]; exact sub_le_sub_left (Rat.cast_le.mpr hl) _), h₁, h₂] + ring + +private theorem separate {z w : K0 E} {l m r : ℚ} (hl : l ≤ 1) (hm : m ≤ 1) + (hr : r ≤ l) (hr' : r ≤ m) (h : val E (z - w) = ↑r) : + dist (M.pt z l) (M.pt w m) = (l : ℝ) + m - 2 * r := by + have hw := M.across hm hr' h + rw [dist_comm (M.L w) (M.L z), dist_comm (M.pt w m) (M.L z), + dist_comm (M.L w) (M.pt w m), add_comm] at hw + have hx := M.across hl hr ((val E).map_sub_swap w z |>.trans h) + have h₁ := (M.midpoint z hl).1 + have h₂ := (M.midpoint w hm).1 + rw [dist_comm] at h₂ + have hd := M.branch_leaf (hr.trans hl) h + have hr₁ : (r : ℝ) ≤ l := Rat.cast_le.mpr hr + have hr₂ : (r : ℝ) ≤ m := Rat.cast_le.mpr hr' + rw [M.ordered _ _ _ _ hx hw (by linarith)] + linarith + +theorem metric (z w : K0 E) {l m : ℚ} (hl : l ≤ 1) (hm : m ≤ 1) : + dist (M.pt z l) (M.pt w m) = (diskGap z w l m : ℝ) := by + wlog h : l ≤ m generalizing z w l m + · rw [dist_comm, gap_symm] + exact this w z hm hl (le_of_not_ge h) + rcases le_or_gt (l : WithTop ℚ) (val E (z - w)) with hle | hlt + · rw [gap_of_le h hle hl, Rat.cast_sub] + exact M.nested h hm (by rwa [AddValuation.map_sub_swap]) + obtain ⟨r, hr⟩ := WithTop.ne_top_iff_exists.mp (ne_top_of_lt hlt) + have hrl : r ≤ l := WithTop.coe_le_coe.mp (hr.trans_le hlt.le) + rw [gap_branch hrl (hrl.trans h) hr.symm, Rat.cast_sub, Rat.cast_add, Rat.cast_mul, + Rat.cast_ofNat] + exact M.separate hl hm hrl (hrl.trans h) hr.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Leaves +end + +/- +# Submean comparison on the branches of the disk tree + +For each moving leaf choose a distant endpoint whose distance +from that leaf is constant throughout the star. Harmonic depths +then give harmonic distances to both endpoints of the segment. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +variable {F E X : Type} [Field F] [Field E] [PseudoMetricSpace X] + +theorem arm_bound {n : ℕ} {c : Fin n → K0 E} (hc : ∀ j, 0 ≤ val E (c j)) + {r : Option (Fin n) → ℚ} (hr : ∀ j, 0 < r j) {u : K0 E} (hu : 0 ≤ val E u) + (j : Option (Fin n)) : ↑(-r none) ≤ val E (armEnd c r u j) := by + cases j with + | none => exact scaled_le _ hu + | some j => + exact (WithTop.coe_le_coe.mpr (neg_nonpos.mpr (hr _).le)).trans + ((val E).map_le_add (hc j) (scaled_pos (hr _) hu).le) + +private theorem far {n : ℕ} (a b : K0 E) (s l : ℚ) (k : Option (Fin n) → ℚ) : + ∃ (w : K0 E) (q : ℚ), q < 1 ∧ q ≤ l ∧ (∀ j, q ≤ k j) ∧ + ∀ v : K0 E, ↑(-s) ≤ val E v → val E (w - (a + b * v)) = ↑q := by + obtain ⟨d, hd⟩ := (Set.finite_range k).bddBelow + obtain ⟨e, he⟩ : ∃ e : ℚ, ↑e ≤ val E b := by + cases val E b + · exact ⟨0, le_top⟩ + · exact ⟨_, le_rfl⟩ + let q := min (min 0 (e - s - 1)) (min l d) + have hq : q < e - s := (min_le_left _ _).trans_lt ((min_le_right _ _).trans_lt (sub_one_lt _)) + refine ⟨a + t q, q, (min_le_left _ _).trans_lt ((min_le_left _ _).trans_lt zero_lt_one), + (min_le_right _ _).trans (min_le_left _ _), + fun j => ((min_le_right _ _).trans (min_le_right _ _)).trans (hd ⟨j, rfl⟩), fun v hv => ?_⟩ + have hval : val E (t q) < val E (-(b * v)) := by + rw [val_t, AddValuation.map_neg, AddValuation.map_mul] + refine (WithTop.coe_lt_coe.mpr hq).trans_le ?_ + rw [sub_eq_add_neg, WithTop.coe_add] + exact add_le_add he hv + rw [show a + t q - (a + b * v) = t q + -(b * v) by + ring, (val E).map_add_eq_of_lt_left hval, val_t] + +private theorem average {n : ℕ} (r : Option (Fin n) → ℚ) (hr : ∀ j, 0 < r j) + (l : ℚ) (k : Option (Fin n) → ℚ) (h : ∑ j, (k j - l) / r j = 0) : + ∑ j, weight r j * (k j : ℝ) = (l : ℝ) := by + have hz : ∑ j, ((k j : ℝ) - l) / r j = 0 := by + simpa only [Rat.cast_sum, Rat.cast_div, Rat.cast_sub, Rat.cast_zero] using + congrArg (fun t : ℚ => (t : ℝ)) h + apply le_antisymm _ ((weight_iff hr _ _).mpr hz.ge) + have ha : 0 ≤ ∑ j, (-(k j : ℝ)- -(l : ℝ)) / r j := by + simp only [neg_sub_neg, ← neg_sub (k _ : ℝ), neg_div, Finset.sum_neg_distrib, hz, neg_zero, + le_refl] + simpa using (weight_iff hr _ _).mpr ha + +theorem Leaves.harmonic (M : Leaves F E X) {n : ℕ} (a b : Four (K0 E)) (c : Fin n → K0 E) + (hc : ∀ j, 0 ≤ val E (c j)) (hd : ∀ i j, i ≠ j → val E (c i - c j) = 0) + (r : Option (Fin n) → ℚ) (hr : ∀ j, 0 < r j) + (l : Four ℚ) (k : Option (Fin n) → Four ℚ) + (hl : ∀ i, l i ≤ 1) (hk : ∀ j i, k j i ≤ 1) + (h : ∀ i, ∑ j, (k j i - l i) / r j = 0) (v : K0 E) (hv : 0 ≤ val E v) : + ∃ u : K0 E, 0 ≤ val E u ∧ M.A.Submean (weight r) + (fun i => M.pt (diskAffine a b v i) (l i)) + (fun j i => M.pt (diskAffine a b (armEnd c r u j) i) (k j i)) := by + choose w q hq hq₁ hq₂ hw using fun i => far (a i) (b i) (r none) (l i) (fun j => k j i) + let x (t : K0 E) := Sum.elim (fun i => M.L (diskAffine a b t i)) (fun i => M.L (w i)) + let p (t : K0 E) (d : Four ℚ) (i : Fin 4) := M.pt (diskAffine a b t i) (d i) + have H (u : K0 E) : + (fun i => M.L (Sum.elim a w i + Sum.elim b (fun _ => 0) i * u)) = x u := by + funext i + cases i <;> simp [x, diskAffine] + obtain ⟨u, hu, hh⟩ := M.tests _ (Sum.elim a w) (Sum.elim b (fun _ => 0)) v hv c r hc hd hr + rw [H v, show (fun j i => M.L (Sum.elim a w i + Sum.elim b (fun _ => 0) i * armEnd c r u j)) = + (fun j => x (armEnd c r u j)) from funext (fun j => H _)] at hh + let e := armEnd c r u + have he (i : Fin 4) (t : K0 E) (ht : ↑(-r none) ≤ val E t) + (d : Four ℚ) (hd : d i ≤ 1) (hqd : q i ≤ d i) : + dist (x t (.inl i)) (x t (.inr i)) = 2 * (1 - (q i : ℝ)) ∧ + dist (x t (.inl i)) (p t d i) = 1 - (d i : ℝ) ∧ + dist (p t d i) (x t (.inr i)) = (1 - 2 * (q i : ℝ)) + d i := by + have H := hw i t ht + change val E (w i - diskAffine a b t i) = _ at H + have h₁ := M.branch_leaf (hq i).le H + rw [dist_comm] at h₁ + have h₂ := (M.midpoint (diskAffine a b t i) hd).1 + have h₃ := M.across hd hqd H + exact ⟨h₁, h₂, by dsimp [x, p]; linarith only [h₁, h₂, h₃]⟩ + have hh' := hh.extend (fun j => (weight_pos hr j).le) (p v l) (fun j => p (e j) (k j)) (by + intro i + obtain ⟨hi, h₁, h₂⟩ := he i v ((WithTop.coe_le_coe.mpr (neg_nonpos.mpr (hr _).le)).trans hv) + l (hl i) (hq₁ i) + have hj (j) := he i (e j) (arm_bound hc hr hu j) (k j) (hk j i) (hq₂ i j) + have hd : 2 * (1 - (q i : ℝ)) ≠ 0 := by + have ht : (q i : ℝ) < 1 := by exact_mod_cast hq i + positivity + let t := (1 - (l i : ℝ)) / (2 * (1 - (q i : ℝ))) + have ht : t * (2 * (1 - (q i : ℝ))) = 1 - l i := div_mul_cancel₀ _ hd + refine ⟨.inl i, .inr i, t, ?_, ?_, ?_, ?_⟩ + · rw [hi, h₁, ht] + · rw [hi, h₂, sub_mul, ht] + ring + · change (∑ j, weight r j * dist (x (e j) (.inl i)) (p (e j) (k j) i)) ≤ _ + simp_rw [(hj _).2.1] + rw [h₁] + simp only [mul_sub, mul_one, Finset.sum_sub_distrib, weight_sum hr, + average r hr _ _ (h i), le_refl] + · change (∑ j, weight r j * dist (p (e j) (k j) i) (x (e j) (.inr i))) ≤ _ + simp_rw [(hj _).2.2] + rw [h₂] + simp only [mul_add, Finset.sum_add_distrib, ← Finset.sum_mul, weight_sum hr, one_mul, + average r hr _ _ (h i), le_refl]) + exact ⟨u, hu, hh'.reindex Sum.inr⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- +# Submean tests on the geodesic hull + +First allow a different orbit mark at every slot. Simultaneous +geodesic interpolation then gives the tests for terms. A countable +intersection and continuity in placement pass them to the closure. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices +open Spectral Filter Topology + +variable {F S : Type} [Field F] [Fintype S] [DecidableEq S] [Nonempty S] + {X : Type*} [PseudoMetricSpace X] (A : Atlas F X) + +theorem Atlas.transport (T : Raw F S) (ht : Tensor.ofRaw T ≠ 0) (x y : S → X) : + |A.price x (Tensor.ofRaw T) - A.price y (Tensor.ofRaw T)| ≤ + (∑ i, dist (x i) (y i) * Real.log (Fintype.card (T.leg i))) / Real.log 2 := by + let _ := sum_nontrivial S S + let z := Sum.elim x y + obtain ⟨D, d, hd, f, hf, he⟩ := A.valid z + have hw (i : S) : d * Tensor.dist f (.inl i) (.inr i) = dist (x i) (y i) := by + have h := A.wire z (.inl i) (.inr i) + rw [he] at h + exact h + change |A.price (z ∘ Sum.inl) _ - A.price (z ∘ Sum.inr) _| ≤ _ + rw [A.place, A.place, he] + simp only [Function.comp_apply, Tensor.values, ← mul_sub, ← sub_div, ← mul_div_assoc, + abs_div, abs_of_pos (Real.log_pos (show (1 : ℝ) < 2 by norm_num)), abs_mul, abs_of_nonneg hd.1] + have h := mul_le_mul_of_nonneg_left (Tensor.price_transport f hf T ht Sum.inl Sum.inr) hd.1 + rw [Finset.mul_sum] at h + simp only [← mul_assoc, hw] at h + exact div_le_div_of_nonneg_right h (Real.log_nonneg (by norm_num)) + +theorem Atlas.continuous_price (T : Tensor F S) : Continuous (fun x : S → X => A.price x T) := by + refine Quotient.inductionOn T fun t => ?_ + change Continuous (fun x : S → X => A.price x (Tensor.ofRaw t)) + by_cases ht : Tensor.ofRaw t = 0 + · have he (x : S → X) : A.price x 0 = 0 := by + let _ := sum_nontrivial S S + let z := Sum.elim x x + obtain ⟨D, d, _, f, _, he⟩ := A.valid z + change A.price (z ∘ Sum.inl) 0 = _ + rw [A.place, he] + simp [Tensor.place_zero, Tensor.values] + simp only [ht, he] + exact continuous_const + apply continuous_iff_continuousAt.mpr + intro x + let g (y : S → X) := (∑ i, dist (y i) (x i) * Real.log (Fintype.card (t.leg i))) / Real.log 2 + have hg : Continuous g := by unfold g; fun_prop + have hzero : g x = 0 := by simp [g] + refine tendsto_iff_dist_tendsto_zero.mpr (squeeze_zero (fun _ => dist_nonneg) (g := g) ?_ ?_) + · intro y + rw [Real.dist_eq] + exact A.transport t ht y x + · rw [← hzero] + exact hg.continuousAt + +end MatrixMultiplicationAllFields.MatrixExponent.Prices + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +open Filter Routing +open scoped Topology + +variable {E F : Type} [Field F] [Field E] {X : Type*} [MetricSpace X] + [MulAction (G E) X] [IsIsometricSMul (G E) X] {A : Atlas F X} {o : X} + +private def depth : Term (G E) → ℕ + | .mark _ => 0 + | .seg _ x y => max (depth x) (depth y) + 1 + +omit [IsIsometricSMul (G E) X] in +private theorem split_term (C : Comparison X) (o : X) {d : ℕ} (t : Term (G E)) (ht : depth t ≤ d + + 1) : + let ev := Term.eval C (fun g : G E => g • o) + ∃ l r : Term (G E), depth l ≤ d ∧ depth r ≤ d ∧ ∃ u : ℝ, + dist (ev l) (ev t) = u * dist (ev l) (ev r) ∧ + dist (ev t) (ev r) = (1 - u) * dist (ev l) (ev r) := by + cases t with + | mark g => exact ⟨.mark g, .mark g, Nat.zero_le _, Nat.zero_le _, 0, by simp, by simp⟩ + | seg u l r => + have h := C.along u (Term.eval C (fun g => g • o) l) (Term.eval C (fun g => g • o) r) + refine ⟨l, r, (le_max_left _ _).trans (Nat.le_of_succ_le_succ ht), + (le_max_right _ _).trans (Nat.le_of_succ_le_succ ht), u.val, h.start, ?_⟩ + have he := h.rev.start + rw [dist_comm, dist_comm (Term.eval C _ r) (Term.eval C _ l)] at he + exact he + +theorem MovingAt.term (ho : MovingAt E A o) (C' : Comparison X) (T : Term (G E)) : + MovingAt E A (T.eval C' (fun g => g • o)) := by + intro S _ _ _ a b v hv n c r hc hd hr ha hb he + let ev := Term.eval C' (fun g : G E => g • o) + let m (w : K0 E) (i : S) := a i + b i * w + let e (u : E) := armEnd c r (K0.C u) + have mulpos {x y : K0 E} (hx : 0 < val E x) (hy : 0 ≤ val E y) : 0 < val E (x * y) := by + rw [AddValuation.map_mul] + exact hx.trans_le (le_add_of_nonneg_right hy) + have hmv i : 0 < val E (m v i) := (val E).map_lt_add (ha i) (mulpos (hb i) hv) + have hme u j i : 0 < val E (m (e u j) i) := by + apply (val E).map_lt_add (ha i) + cases j with + | none => + rw [show e u none = t (-r none) * K0.C u from rfl, ← mul_assoc, mul_comm (b i)] + exact mulpos (he i) (integral_C u) + | some j => + apply mulpos (hb i) + apply (val E).map_le_add (hc j) + exact (mulpos (by rw [val_t]; exact WithTop.coe_pos.mpr (hr _)) (integral_C u)).le + let act {U : Type} (z : U → S) (f : U → Term (G E)) (w : K0 E) (i : U) := + shift (m w (z i)) • ev (f i) + have terms (d : ℕ) : ∀ (U : Type) [Fintype U] [DecidableEq U] [Nonempty U] + (z : U → S) (f : U → Term (G E)), (∀ i, depth (f i) ≤ d) → + ∀ᶠ u : E in cocountable, A.Submean (weight r) (act z f v) (fun j => act z f (e u j)) := by + induction d with + | zero => + intro U _ _ _ z f hf + have marks (i : U) : ∃ g, f i = .mark g := by + cases h : f i with + | mark g => exact ⟨g, rfl⟩ + | seg _ _ _ => have hw := hf i; simp [h, depth] at hw + choose g hg using marks + let a' i := a (z i) + idx (g i) + have hh := ho U a' (b ∘ z) v hv c r hc hd hr + (fun i => (val E).map_lt_add (ha _) (idx_pos _)) (fun i => hb _) (fun i => he _) + have eq (w : K0 E) (hw : ∀ i, 0 < val E (m w i)) : + act z f w = fun i => shift (a' i + b (z i) * w) • o := by + funext i + unfold act + rw [hg] + change shift (m w (z i)) • (g i • o) = _ + rw [show a' i + b (z i) * w = m w (z i) + idx (g i) from add_right_comm _ _ _, + shift_add (hw _) (idx_pos _), shift_idx, mul_smul] + filter_upwards [hh] with u hu + simp only [eq v hmv, eq _ (hme u _)] + exact hu + | succ d ih => + intro U _ _ _ z f hf + choose l r' hl hr' t ht₁ ht₂ using fun i => split_term C' o (f i) (hf i) + let z' := Sum.elim z z + let f' := Sum.elim l r' + have hf' (i : U ⊕ U) : depth (f' i) ≤ d := by cases i <;> first | exact hl _ | exact hr' _ + filter_upwards [ih (U ⊕ U) z' f' hf'] with u hu + have hh := hu.extend (fun j => (weight_pos hr j).le) (act z f v) + (fun j => act z f (e u j)) (fun i => by + refine ⟨.inl i, .inr i, t i, ?_, ?_, ?_, ?_⟩ + all_goals simp only [act, z', f', Sum.elim_inl, Sum.elim_inr, dist_smul] + · exact ht₁ i + · exact ht₂ i + · rw [← Finset.sum_mul, weight_sum hr, one_mul] + · rw [← Finset.sum_mul, weight_sum hr, one_mul]) + exact hh.reindex Sum.inr + exact terms (depth T) S id (fun _ => T) fun _ => le_rfl + +theorem Moving.of_dense (ho : MovingAt E A o) (C' : Comparison X) + (h : DenseRange (Term.eval C' (fun g : G E => g • o))) : Moving E A := by + intro x S _ _ _ a b v hv n c r hc hd hr ha hb he + obtain ⟨y, hy, hx⟩ := mem_closure_iff_seq_limit.mp (h x) + let m (w : K0 E) (x : X) (i : S) := shift (a i + b i * w) • x + let _ := cocountable_countable E + have hw : ∀ᶠ u : E in cocountable, ∀ k : ℕ, A.Submean (weight r) (m v (y k)) + (fun j => m (armEnd c r (K0.C u) j) (y k)) := by + apply eventually_countable_forall.mpr + intro k + obtain ⟨t, ht⟩ := hy k + rw [← ht] + exact ho.term C' t S a b v hv c r hc hd hr ha hb he + filter_upwards [hw] with u hu + intro B + have hp (w : K0 E) : Continuous (fun z => A.price (m w z) B) := + (A.continuous_price B).comp (continuous_pi fun i => (isometry_smul X (shift (a i + + b i * w))).continuous) + have ht : IsClosed {z | A.price (m v z) B ≤ + ∑ j, weight r j * A.price (m (armEnd c r (K0.C u) j) z) B} := + isClosed_le (hp v) (continuous_finsetSum _ fun j _ => continuous_const.mul (hp _)) + exact ht.mem_of_tendsto hx (Eventually.of_forall fun k => hu k B) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- # Restricting the submean comparison to a single wire -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +open Filter +variable {F E : Type} [Field F] [Field E] [Uncountable E] + {X : Type*} [MetricSpace X] [MulAction (G E) X] {A : Atlas F X} + +private theorem Moving.test (h : Moving E A) (x : X) {q : ℚ} (hq : 0 < q) + (w : K0 E) (hw : 0 ≤ val E w) {n : ℕ} (c : Fin n → K0 E) (r : Option (Fin n) → ℚ) + (hc : ∀ j, 0 ≤ val E (c j)) (hd : ∀ i j, i ≠ j → val E (c i - c j) = 0) + (hr : ∀ j, 0 < r j) (hr' : r none < q) : + ∃ u : K0 E, 0 ≤ val E u ∧ + 0 ≤ ∑ j, (cost x (t q * armEnd c r u j) - cost x (t q * w)) / (r j : ℝ) := by + have := cocountable_neBot E + let b : Fin 2 → K0 E := ![0, t q] + have hb : ∀ i, 0 < val E (b i) := by intro i; fin_cases i <;> simp [b, hq] + have ht : ∀ i, 0 < val E (t (-r none) * b i) := by + intro i + fin_cases i + · simp [b] + change 0 < val E (t (-r none) * t q) + rw [← t_add, val_t, WithTop.coe_pos] + linarith + obtain ⟨u, hu⟩ := (h x (Fin 2) (fun _ => 0) b w hw c r hc hd hr (by simp) hb ht).exists + refine ⟨C u, integral_C u, (weight_iff hr _ _).mp ?_⟩ + simpa [b, cost] using hu.wire 0 1 + +theorem Moving.radial (h : Moving E A) : RadialStars E X := by + constructor + · intro x a b c ha hab hbc w hw + let r : Option (Fin 1) → ℚ := fun j => if j = none then b - a else c - b + have hr : ∀ j, 0 < r j := by + intro j + unfold r + split <;> linarith + obtain ⟨u, hu, h'⟩ := h.test x (ha.trans hab) w hw (fun _ => 0) r (by simp) + (fun i j hij => (hij (Subsingleton.elim _ _)).elim) hr (by simp [r, ha]) + simp only [Fintype.sum_option, Fin.sum_univ_one, r, armEnd, zero_add, ite_true, + Option.some_ne_none, ite_false, ← mul_assoc, ← t_add, Rat.cast_sub] at h' + rw [show b + -(b - a) = a by ring, show b + (c - b) = c by ring] at h' + have h₁ : (a : ℝ) < b := Rat.cast_lt.mpr hab + have h₂ : (b : ℝ) < c := Rat.cast_lt.mpr hbc + refine ⟨u, hu, ?_⟩ + have he : (cost x (t b * w) - cost x (t a * u)) / ((b : ℝ) - a) ≤ + (cost x (t c * u) - cost x (t b * w)) / ((c : ℝ) - b) := by + rw [← neg_sub, neg_div] + linarith only [h'] + rw [div_le_div_iff₀ (sub_pos.mpr h₁) (sub_pos.mpr h₂)] at he + linarith only [he] + · intro x q s hs hq w v hw hv + let c : Fin 2 → K0 E := ![0, v] + have hc (j) : 0 ≤ val E (c j) := by fin_cases j <;> simp [c, hv] + have hd (i j) (hn : i ≠ j) : val E (c i - c j) = 0 := by + fin_cases i <;> fin_cases j <;> simp_all [c] + obtain ⟨u, hu, h'⟩ := h.test x (hs.trans hq) w hw c (fun _ => s) hc hd (fun _ => hs) hq + refine ⟨u, hu, ?_⟩ + rw [← Finset.sum_div, le_div_iff₀ (Rat.cast_pos.mpr hs), zero_mul, + Fintype.sum_option, Fin.sum_univ_two] at h' + simp only [armEnd, c, Matrix.cons_val_zero, Matrix.cons_val_one, zero_add, ← mul_assoc, + ← t_add, ← sub_eq_add_neg] at h' + linarith only [h'] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- +# Submean estimates survive the zoom + +Dilation of the coefficients multiplies the lengths of all arms by +the same positive number. A single residue outside countably many +exceptions works throughout the sequence of zooms. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +open Filter Topology Routing +variable {E F : Type} [Field E] [Field F] + +private theorem dilate_integral {x : K0 E} (hx : 0 ≤ val E x) {e : ℚ} (he : 0 < e) : + 0 ≤ val E (dilate e he x) := by + rw [val_dilate] + generalize val E x = v at * + cases v with + | top => simp + | coe v => + rw [WithTop.map_coe, WithTop.coe_nonneg] + exact mul_nonneg he.le (WithTop.coe_nonneg.mp hx) + +private theorem Dilation.affine (D : Dilation) (i : ℕ) (a b z : K0 E) : + D.index i (a + b * z) = D.index i a + D.index i b * dilate (D.e i) (D.pos i) z := by + simp only [index, zoom, map_add, map_mul, mul_add, mul_assoc] + +private theorem dilate_end {e : ℚ} (he : 0 < e) {n : ℕ} (c : Fin n → K0 E) + (r : Option (Fin n) → ℚ) (u : E) (j : Option (Fin n)) : + dilate e he (armEnd c r (C u) j) = + armEnd (dilate e he ∘ c) (fun k => e * r k) (C u) j := by + cases j <;> simp [armEnd] + +variable {X : Type} [MetricSpace X] [MulAction (G E) X] {A : Atlas F X} + +private theorem Moving.zoom [Uncountable E] (h : Moving E A) (D : Dilation) (x : X) + {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] + (a b : S → K0 E) (v : K0 E) (hv : 0 ≤ val E v) + {n : ℕ} (c : Fin n → K0 E) (r : Option (Fin n) → ℚ) + (hc : ∀ j, 0 ≤ val E (c j)) (hd : ∀ i j, i ≠ j → val E (c i - c j) = 0) + (hr : ∀ j, 0 < r j) : + ∃ u : E, ∀ᶠ i in atTop, A.Submean (weight r) + (fun j => D.point x i (a j + b j * v)) + (fun k j => D.point x i (a j + b j * armEnd c r (C u) k)) := by + let event (i : ℕ) := ∀ j, 0 < val E (D.index i (a j)) ∧ 0 < val E (D.index i (b j)) ∧ + 0 < val E (D.index i (t (-r none) * b j)) + have he : ∀ᶠ i in atTop, event i := eventually_all.mpr fun j => + (D.positive _).and ((D.positive _).and (D.positive _)) + have := cocountable_neBot E + have := cocountable_countable E + have aux : ∀ᶠ u : E in cocountable, ∀ i, event i → A.Submean (weight r) + (fun j => D.point x i (a j + b j * v)) + (fun k j => D.point x i (a j + b j * armEnd c r (C u) k)) := by + refine eventually_countable_forall.mpr fun i => ?_ + by_cases hi : event i + swap + · exact Eventually.of_forall (fun _ h => (hi h).elim) + let f := dilate (E := E) (D.e i) (D.pos i) + let t' (k) := D.e i * r k + have hd' (j k) (hj : j ≠ k) : val E ((f ∘ c) j - (f ∘ c) k) = 0 := by + rw [Function.comp_apply, Function.comp_apply, ← map_sub, val_dilate, hd j k hj] + simp + have hb' (j) : 0 < val E (t (-t' none) * D.index i (b j)) := by + have heq : D.index i (t (-r none) * b j) = t (-t' none) * D.index i (b j) := by + simp only [Dilation.index, K0.zoom, map_mul, dilate_t, mul_neg, t'] + rw [mul_left_comm] + rw [← heq] + exact (hi j).2.2 + have H := h x S (fun j => D.index i (a j)) (fun j => D.index i (b j)) (f v) + (dilate_integral hv _) (f ∘ c) t' (fun j => dilate_integral (hc j) _) hd' + (fun j => mul_pos (D.pos i) (hr j)) (fun j => (hi j).1) (fun j => (hi j).2.1) hb' + filter_upwards [H] with u hu _ + rw [show weight t' = weight r from weight_scale _ (D.pos i)] at hu + simpa only [Dilation.point, Dilation.affine, dilate_end] using hu + obtain ⟨u, hu⟩ := aux.exists + exact ⟨u, he.mono hu⟩ + +theorem Moving.limit [Uncountable E] [CompleteSpace X] [IsIsometricSMul (G E) X] + (h : Moving E A) (C : Comparison X) {M : ℝ} (hM : ∀ x y : X, dist x y ≤ M) + (o : X) (hm : ∃ a : ℝ, 0 < a ∧ o ∉ fixed (level E a)) + (hs : ∀ ε : ℝ, 0 < ε → ∃ b, 0 < b ∧ profile E o b < ε) : + ∃ (Y : Type) (_ : PseudoMetricSpace Y) (B : Atlas F Y) (L : K0 E → Y), + (∀ (u : Fraction) (x y : Y), ∃ m, Along u x y m) ∧ + (∀ x y, dist (L x) (L y) = (diskDist (leaf x) (leaf y) : ℝ)) ∧ LeafTests B L := by + obtain ⟨x, D, _, hw⟩ := h.radial.leaves C hM o hm hs + let R : Rescale ℕ := + { Y := fun _ => X, o := fun _ => x, d := D.factor + hn := fun i => (D.pos_factor i).le, l := Ultrafilter.of atTop } + have hl : (R.l : Filter ℕ) ≤ atTop := Ultrafilter.of_le _ + let L (z : K0 E) : R.Site := ⟨fun i => D.point x i z, by + have hd := (hw z 0).eventually_le_const (lt_add_one _) + refine ⟨(diskDist (leaf z) (leaf 0) : ℝ) + 1, hl ?_⟩ + have he (i : ℕ) : D.point x i (0 : K0 E) = x := by + simp [Dilation.point, Dilation.index, K0.zoom] + simp only [he] at hd + exact hd⟩ + obtain ⟨B, hB⟩ := R.atlas (fun _ => A) + refine ⟨R.Site, inferInstance, B, L, fun t x y => ⟨_, R.along (fun _ => C) t x y⟩, + fun z w => tendsto_nhds_unique (R.distance (L z) (L w)) ((hw z w).mono_left hl), ?_⟩ + intro S _ _ _ a b v hv n c r hc hd hr + obtain ⟨u, hu⟩ := h.zoom D x a b v hv c r hc hd hr + refine ⟨K0.C u, integral_C u, fun Z => ?_⟩ + apply le_of_tendsto_of_tendsto (hB _ Z) + (tendsto_finsetSum _ (fun j _ => (hB _ Z).const_mul (weight r j))) + filter_upwards [hl hu] with i hi + have hy := mul_le_mul_of_nonneg_left (hi Z) (D.pos_factor i).le + rw [Finset.mul_sum] at hy + exact hy.trans_eq (Finset.sum_congr rfl fun _ _ => mul_left_comm _ _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- +# Rigidity of analytic motion + +A nonconstant action with the disk tests and continuity at the origin +produces a configuration of leaves on the disk tree. Excluding +that configuration forces the action to fix the chosen mark. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +variable {F E X : Type} [Field F] [Field E] + +/-- Builds `MotionTree F E where rate x l` with the specified `rate`, `realized`, `let`, +`obtain`. -/ +def Leaves.tree [PseudoMetricSpace X] (M : Leaves F E X) : MotionTree F E where + rate x l := M.A.price (fun i => M.pt (x i) (l i)) 2 + realized x l hl := by + let p := fun i => M.pt (x i) (l i) + obtain ⟨D, hD⟩ := M.A.valid p + exact ⟨D, _, hD, rfl, fun i j => (M.A.wire p i j).trans (M.metric _ _ (hl i) (hl j))⟩ + chord x y z l m k hl hm hk θ h₀ h₁ left right := by + refine M.A.chord (Rat.cast_nonneg.mpr h₀) (by exact_mod_cast h₁) ?_ ?_ 2 + · intro i + rw [M.metric _ _ (hl i) (hk i), M.metric _ _ (hl i) (hm i), left i, Rat.cast_mul] + · intro i + rw [M.metric _ _ (hk i) (hm i), M.metric _ _ (hl i) (hm i), right i, + Rat.cast_mul, Rat.cast_sub, Rat.cast_one] + star a b c hc hd r hr l k hl hk he v hv := by + obtain ⟨u, hu, H⟩ := M.harmonic a b c hc hd r hr l k hl hk he v hv + exact ⟨fun _ => u, fun _ => hu, (weight_iff hr _ _).mp (H 2)⟩ + +variable [Uncountable E] [MetricSpace X] [CompleteSpace X] + [MulAction (G E) X] [IsIsometricSMul (G E) X] {A : Atlas F X} + +/-- Continuity need only hold at the chosen mark. -/ +theorem Moving.constantValue (h : Moving E A) (C : Routing.Comparison X) {M : ℝ} + (hM : ∀ x y : X, dist x y ≤ M) (o : X) + (hs : ∀ ε : ℝ, 0 < ε → ∃ b, 0 < b ∧ profile E o b < ε) + (hF : ∀ (Y : Type) [PseudoMetricSpace Y], Leaves F E Y → False) : ∀ g : G E, g • o = o := by + intro g + by_contra hn + have hz : idx g ≠ 0 := by + intro he + apply hn + rw [← shift_idx g, he, shift_zero, one_smul] + obtain ⟨s, hv⟩ := WithTop.ne_top_iff_exists.mp ((val E).ne_top_iff.mpr hz) + have hpos : 0 < s := WithTop.coe_pos.mp (hv.symm ▸ idx_pos g) + have moved : o ∉ fixed (level E s) := fun hy => hn (hy g ((mem_level _ _).mpr hv.le)) + obtain ⟨Y, _, B, L, ha, hw, ht⟩ := h.limit C hM o ⟨s, Rat.cast_pos.mpr hpos, moved⟩ hs + exact hF Y ⟨B, L, ha, hw, ht⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/ScaleSlope.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/ScaleSlope.lean new file mode 100644 index 0000000000..0f550373c3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/ScaleSlope.lean @@ -0,0 +1,480 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Partitions +public import Mathlib.Topology.Instances.Real.Lemmas +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Finite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Fields + +/-! +# A supporting slope for the displacement profile + +Minimize the distance to the fixed set plus a small linear tilt. This +gives a supporting line of strictly negative slope at the chosen +radius without differentiating the distance to the moving fixed set. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +open Filter Set +open scoped Topology + +/-- Convexity at rational triples is enough for decreasing profiles. -/ +def RationalSecants (R : ℝ → ℝ) : Prop := + ∀ a b c : ℚ, 0 < a → a < b → b < c → + ((c : ℝ) - a) * R b ≤ ((c : ℝ) - b) * R a + ((b : ℝ) - a) * R c + +theorem RationalSecants.real {R : ℝ → ℝ} (h : RationalSecants R) + (hm : AntitoneOn R (Ioi 0)) {a b c : ℝ} (ha : 0 < a) (hab : a < b) (hbc : b < c) : + (c - a) * R b ≤ (c - b) * R a + (b - a) * R c := by + obtain ⟨x, _, hx, lx⟩ := Real.exists_seq_rat_strictAnti_tendsto a + obtain ⟨y, _, hy, ly⟩ := Real.exists_seq_rat_strictMono_tendsto b + obtain ⟨z, _, hz, lz⟩ := Real.exists_seq_rat_strictAnti_tendsto c + apply le_of_tendsto_of_tendsto ((lz.sub lx).mul_const (R b)) + (((lz.sub ly).mul_const (R a)).add ((ly.sub lx).mul_const (R c))) + filter_upwards [lx.eventually_lt ly hab] with n hxy + have hyz := (hy n).trans (hbc.trans (hz n)) + have hx0 := ha.trans (hx n) + have hy0 := hx0.trans hxy + have hc0 := (ha.trans hab).trans hbc + have huv := h (x n) (y n) (z n) (by exact_mod_cast hx0) + (by exact_mod_cast hxy) (by exact_mod_cast hyz) + have h₁ := hm hy0 (ha.trans hab) (hy n).le + have h₂ := hm ha hx0 (hx n).le + have h₃ := hm hc0 (hc0.trans (hz n)) (hz n).le + exact (mul_le_mul_of_nonneg_left h₁ (sub_nonneg.mpr (hxy.trans hyz).le)).trans + (huv.trans (add_le_add (mul_le_mul_of_nonneg_left h₂ (sub_nonneg.mpr hyz.le)) + (mul_le_mul_of_nonneg_left h₃ (sub_nonneg.mpr hxy.le)))) + +/-- Uniform two-sided little-o estimate at the onset of displacement. -/ +def Kink (R : ℝ → ℝ) (r k : ℝ) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ δ : ℝ, 0 < δ ∧ ∀ h : ℝ, |h| < δ → + |R (r + h) - k * max (-h) 0| ≤ ε * |h| + +private theorem kink_of_support {R : ℝ → ℝ} (h : RationalSecants R) + (hm : AntitoneOn R (Ioi 0)) {a r c : ℝ} (ha : 0 < a) (har : a < r) (hc : 0 < c) + (hs : ∀ x ∈ Ico a r, c * (r - x) ≤ R x) (hz : ∀ x, r ≤ x → R x = 0) : + ∃ k, 0 < k ∧ Kink R r k := by + let q (x : ℝ) := R x / (r - x) + let S := q '' Ico a r + have hn : S.Nonempty := ⟨_, a, ⟨le_rfl, har⟩, rfl⟩ + have hb : c ∈ lowerBounds S := by + rintro _ ⟨x, hx, rfl⟩ + exact (le_div_iff₀ (sub_pos.mpr hx.2)).mpr (hs x hx) + let k := sInf S + refine ⟨k, hc.trans_le (le_csInf hn hb), fun ε hε => ?_⟩ + obtain ⟨_, ⟨x, hx, rfl⟩, he⟩ := exists_lt_of_csInf_lt hn (show k < k + ε by linarith) + refine ⟨r - x, sub_pos.mpr hx.2, fun v hv => ?_⟩ + rcases lt_or_ge v 0 with hv' | hv' + · have hl : x < r + v := by linarith [(abs_lt.mp hv).1] + have hu : r + v < r := by linarith + have hlow := csInf_le (show BddBelow S from ⟨c, hb⟩) + (show q (r + v) ∈ S from ⟨r + v, ⟨hx.1.trans hl.le, hu⟩, rfl⟩) + have hhi : q (r + v) ≤ q x := by + apply (div_le_div_iff₀ (sub_pos.mpr hu) (sub_pos.mpr hx.2)).mpr + have hd := h.real hm (ha.trans_le hx.1) hl hu + rw [hz r le_rfl] at hd + linarith only [hd] + have lo := (le_div_iff₀ (sub_pos.mpr hu)).mp hlow + have hi := (div_le_iff₀ (sub_pos.mpr hu)).mp (hhi.trans he.le) + rw [abs_of_neg hv', max_eq_left (neg_nonneg.mpr hv'.le), abs_of_nonneg (by linarith)] + linarith + · rw [hz _ (by linarith), max_eq_right (neg_nonpos.mpr hv'), mul_zero, sub_zero, abs_zero] + positivity + +/-- Each radius t selects a profile R t vanishing from that radius on. +Its earlier values bound the change in the projection distance f. -/ +theorem first_displacement {R : ℝ → ℝ → ℝ} {f : ℝ → ℝ} {a b M : ℝ} + (ha : 0 < a) (hab : a < b) (hf : f b < f a) + (hs : ∀ t ∈ Icc a b, RationalSecants (R t)) + (hm : ∀ t ∈ Icc a b, AntitoneOn (R t) (Ioi 0)) + (hz : ∀ t ∈ Icc a b, ∀ x, t ≤ x → R t x = 0) + (hM : ∀ t ∈ Icc a b, R t (a / 2) ≤ M) + (hp : ∀ s ∈ Icc a b, ∀ t ∈ Icc a b, s ≤ t → + f t ≤ f s ∧ f s - f t ≤ R t s) : + ∃ r ∈ Ioc a b, ∃ k : ℝ, 0 < k ∧ Kink (R r) r k := by + let L := (|M| + 1) / (a / 2) + have hL : 0 < L := by unfold L; positivity + have bound {s t : ℝ} (hs' : s ∈ Icc a b) (ht : t ∈ Icc a b) (hst : s ≤ t) : + f s - f t ≤ L * (t - s) := by + rcases hst.eq_or_lt with rfl | hst + · simp + have H := (hs t ht).real (hm t ht) (half_pos ha) (by linarith [hs'.1]) hst + rw [hz t ht t le_rfl, mul_zero, add_zero] at H + obtain ⟨h₁, h₂⟩ := hp s hs' t ht hst.le + have h₃ := mul_le_mul (show a / 2 ≤ t - a / 2 by linarith [ht.1]) h₂ + (sub_nonneg.mpr h₁) (show 0 ≤ t - a / 2 by linarith [ht.1]) + have h₄ := mul_le_mul_of_nonneg_left ((hM t ht).trans + ((le_abs_self M).trans (le_add_of_nonneg_right zero_le_one))) (sub_nonneg.mpr hst.le) + unfold L + rw [div_mul_eq_mul_div, le_div_iff₀ (half_pos ha)] + linarith only [H, h₃, h₄] + have cont : ContinuousOn f (Icc a b) := by + apply Metric.continuousOn_iff.mpr + intro t ht ε hε + refine ⟨ε / L, div_pos hε hL, fun s hs' hst => ?_⟩ + rw [Real.dist_eq, lt_div_iff₀ hL] at hst + rw [Real.dist_eq] + rcases le_total s t with h | h + · rw [abs_of_nonpos (sub_nonpos.mpr h)] at hst + rw [abs_of_nonneg (sub_nonneg.mpr (hp s hs' t ht h).1)] + linarith only [bound hs' ht h, hst] + · rw [abs_of_nonneg (sub_nonneg.mpr h)] at hst + rw [abs_of_nonpos (sub_nonpos.mpr (hp t ht s hs' h).1)] + linarith only [bound ht hs' h, hst] + let c := (f a - f b) / (2 * (b - a)) + have hc : 0 < c := div_pos (by linarith) (by linarith) + have he : c * (2 * (b - a)) = f a - f b := div_mul_cancel₀ _ (by linarith) + obtain ⟨r, hr, hr'⟩ := isCompact_Icc.exists_isMinOn (nonempty_Icc.mpr hab.le) + (show ContinuousOn (fun t => f t + c * t) _ from cont.add (continuousOn_const.mul + continuousOn_id)) + have har : a < r := by + rcases hr.1.eq_or_lt with rfl | h + · have h : f a + c * a ≤ f b + c * b := hr' ⟨hab.le, le_rfl⟩ + linarith + · exact h + refine ⟨r, ⟨har, hr.2⟩, kink_of_support (hs r hr) (hm r hr) ha har hc ?_ (hz r hr)⟩ + intro x hx + have hx' : x ∈ Icc a b := ⟨hx.1, hx.2.le.trans hr.2⟩ + have hl : f r + c * r ≤ f x + c * x := hr' hx' + linarith only [hl, (hp x hx' r hr hx.2.le).2] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# Finite realizations of geodesic expressions + +Every finite set of expressions can be realized at one spectral point. +When a missing expression is added, all previously correct expressions +keep their original sites and prices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Tensor + +/-- The spectral comparison of type `Prop` for the given inputs. -/ +def SpectralComparison (K : Type) [Field K] : Prop := + ∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (f : Tensor K S →+* ℝ), + Monotone f → ∀ (a m b : S) (u : Fraction), Between f a m b u → + ∀ z : S, Tensor.dist f m z ^ 2 ≤ (1 - u.val) * Tensor.dist f a z ^ 2 + + u.val * Tensor.dist f b z ^ 2 - u.val * (1 - u.val) * Tensor.dist f a b ^ 2 + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + +/-- The data for the term model construction, including `Site`, `[finiteSites`, `[decEq`, +`[inh`, `g`. -/ +structure TermModel (f : Tensor K S →+* ℝ) where + /-- The `TermModel` component of type `Type`. -/ + Site : Type + [finiteSites : Fintype Site] + [decEq : DecidableEq Site] + [inh : Nonempty Site] + /-- The `TermModel` component of type `Tensor K Site →+* ℝ`. -/ + g : Tensor K Site →+* ℝ + mono : Monotone g + /-- The `TermModel` component of type `Term S → Site`. -/ + point : Term S → Site + initial : ∀ A, g (place (point ∘ Term.mark) A) = f A + +attribute [instance] TermModel.finiteSites TermModel.decEq TermModel.inh + +namespace TermModel +variable {f : Tensor K S →+* ℝ} + +/-- Builds `TermModel f where Site` with the specified `Site`, `mono`, `point`. -/ +def start (hf : Monotone f) : TermModel f where + Site := S + g := f + mono := hf + point + | .mark i => i + | .seg .. => Classical.arbitrary S + initial A := congrArg f (place_id A) + +/-- Computes the valid by the application `Fits (values 1 M.g) M.point`. -/ +def Valid (M : TermModel f) : Term S → Prop := Fits (values 1 M.g) M.point + +omit [Nonempty S] in +theorem valid_iff (M : TermModel f) (t : Fraction) (a b : Term S) : + M.Valid (.seg t a b) ↔ M.Valid a ∧ M.Valid b ∧ + Between M.g (M.point a) (M.point (.seg t a b)) (M.point b) t := by + simp only [Valid, Fits, AtFraction, Between, gap, values, Tensor.dist, one_mul] + +omit [Nonempty S] in +private theorem append (M : TermModel f) (t : Fraction) (a b : Term S) + (ha : M.Valid a) (hb : M.Valid b) : + ∃ N : TermModel f, N.Valid (.seg t a b) ∧ ∀ c, M.Valid c → N.Valid c := by + classical + let d := Term.seg t a b + by_cases h : M.Valid d + · exact ⟨M, h, fun _ h => h⟩ + obtain ⟨g, hg, he, hd, _⟩ := geodesic M.g M.mono + (fun _ : Unit => M.point a) (fun _ => M.point b) t.2.1 t.2.2 + let p (c : Term S) : M.Site ⊕ Unit := if c = d then .inr () else .inl (M.point c) + have pm : p ∘ Term.mark = Sum.inl ∘ (M.point ∘ Term.mark) := by + funext i + simp [p, d] + let N : TermModel f := + { Site := M.Site ⊕ Unit, g := g, mono := hg, point := p + initial := fun A => by rw [pm, place_comp, place_inl, he, M.initial] } + have keep (c : Term S) (hc : M.Valid c) : N.point c = .inl (M.point c) := + ite_eq_right (fun hcd : c = d => h (hcd ▸ hc)) + have preserve (c : Term S) (hc : M.Valid c) : N.Valid c := by + induction c with + | mark => trivial + | seg v s r ih ik => + obtain ⟨hs, hr, hu⟩ := (M.valid_iff v s r).mp hc + refine (N.valid_iff v s r).mpr ⟨ih hs, ik hr, ?_⟩ + rw [keep _ hc, keep s hs, keep r hr] + change Between g _ _ _ _ + simpa only [Between, dist_pad he] using hu + refine ⟨N, (N.valid_iff t a b).mpr ⟨preserve a ha, preserve b hb, ?_⟩, preserve⟩ + rw [keep a ha, keep b hb] + have hp : N.point d = .inr () := ite_eq_left rfl + rw [hp] + exact hd () + +omit [Nonempty S] in +private theorem add_term (a : Term S) (M : TermModel f) : + ∃ N : TermModel f, N.Valid a ∧ ∀ b, M.Valid b → N.Valid b := by + induction a generalizing M with + | mark => exact ⟨M, trivial, fun _ h => h⟩ + | seg u a b ha hb => + obtain ⟨L, hL, hl⟩ := ha M + obtain ⟨N, hN, hn⟩ := hb L + obtain ⟨P, hp, keep⟩ := N.append u a b (hn a hL) hN + exact ⟨P, hp, fun i hi => keep i (hn i (hl i hi))⟩ + +theorem exists_model (hf : Monotone f) (w : Finset (Term S)) : + ∃ M : TermModel f, ∀ a ∈ w, M.Valid a := by + classical + induction w using Finset.induction_on with + | empty => exact ⟨start hf, by simp⟩ + | insert a w _ ih => + obtain ⟨M, hM⟩ := ih + obtain ⟨N, hN, hn⟩ := add_term a M + refine ⟨N, fun b hb => ?_⟩ + rcases Finset.mem_insert.mp hb with rfl | hb + · exact hN + · exact hn b (hM b hb) + +theorem same_distance (M N : TermModel f) {a b : Term S} + (ha : M.Valid a) (hb : M.Valid b) (ha' : N.Valid a) (hb' : N.Valid b) : + Tensor.dist M.g (M.point a) (M.point b) = Tensor.dist N.g (N.point a) (N.point b) := by + have h : Agree (values 1 M.g) (values 1 N.g) (M.point ∘ Term.mark) (N.point ∘ Term.mark) := + fun A => by rw [values, values, M.initial, N.initial] + have e := terms_determine (D := 1) (E := 1) + ⟨1, ⟨zero_le_one, le_rfl⟩, M.g, M.mono, rfl⟩ + ⟨1, ⟨zero_le_one, le_rfl⟩, N.g, N.mono, rfl⟩ a b ha hb ha' hb' h + simpa only [gap, values, one_mul, Tensor.dist] using e + +end TermModel +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Completing a spectral placement + +Pairwise distances of formal terms are independent of the finite model. +Use larger finite models to prove the triangle and comparison inequalities +for these distances, and pass to metric completion. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.TermModel +open Spectral UniformSpace + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + {f : Tensor K S →+* ℝ} + +open Classical in +/-- The length of type `ℝ`, constructed using `(exists_model hf {a, b}).choose`. -/ +def length (hf : Monotone f) (a b : Term S) : ℝ := + let M := (exists_model hf {a, b}).choose + Tensor.dist M.g (M.point a) (M.point b) + +theorem length_eq (hf : Monotone f) (M : TermModel f) {a b : Term S} + (ha : M.Valid a) (hb : M.Valid b) : length hf a b = Tensor.dist M.g (M.point a) (M.point b) + := by + classical + have h := (exists_model hf {a, b}).choose_spec + exact same_distance _ M (h a (by simp)) (h b (by simp)) ha hb + +/-- Builds `PseudoMetricSpace (Term S) where dist a b` with the specified `dist`, `dist_self`, +`classical`, `have`. -/ +abbrev termMetric (hf : Monotone f) (d : ℝ) (hd : 0 ≤ d) : PseudoMetricSpace (Term S) where + dist a b := d * length hf a b + dist_self a := by + classical + obtain ⟨M, hM⟩ := exists_model hf {a} + have ha := hM a (by simp) + rw [length_eq hf M ha ha, Tensor.dist_self, mul_zero] + dist_comm a b := by + classical + obtain ⟨M, hM⟩ := exists_model hf {a, b} + have ha := hM a (by simp) + have hb := hM b (by simp) + rw [length_eq hf M ha hb, length_eq hf M hb ha, Tensor.dist_comm] + dist_triangle a b c := by + classical + obtain ⟨M, hM⟩ := exists_model hf {a, b, c} + have ha := hM a (by simp) + have hb := hM b (by simp) + have hc := hM c (by simp) + rw [length_eq hf M ha hb, length_eq hf M hb hc, length_eq hf M ha hc, ← mul_add] + exact mul_le_mul_of_nonneg_left (Tensor.dist_triangle _ M.mono _ _ _) hd + +theorem complete (hc : SpectralComparison K) (hf : Monotone f) (d : ℝ) (hd : 0 ≤ d) : + ∃ (Y : Type) (_ : MetricSpace Y) (_ : CompleteSpace Y) (p : Term S → Y), + Comparison Y ∧ DenseRange p ∧ + ∀ (M : TermModel f) (a b), M.Valid a → M.Valid b → + dist (p a) (p b) = d * Tensor.dist M.g (M.point a) (M.point b) := by + classical + let _ := termMetric hf d hd + have e (M : TermModel f) (a b : Term S) (ha : M.Valid a) (hb : M.Valid b) : + dist a b = d * Tensor.dist M.g (M.point a) (M.point b) := + congrArg (d * ·) (length_eq hf M ha hb) + have hs (u : Fraction) (a b : Term S) : Along u a b (.seg u a b) := by + intro z + obtain ⟨M, hM⟩ := exists_model hf {Term.seg u a b, z} + have hw := hM (.seg u a b) (by simp) + have hz := hM z (by simp) + obtain ⟨ha, hb, hh⟩ := (M.valid_iff u a b).mp hw + have H := hc _ M.g M.mono _ _ _ u hh (M.point z) + rw [e M _ _ hw hz, e M _ _ ha hz, e M _ _ hb hz, e M _ _ ha hb] + linarith only [mul_le_mul_of_nonneg_left H (sq_nonneg d)] + have cmp : Comparison (Completion (Term S)) := by + intro a b t ht ht' + have h := completion_along (hs ⟨t, ht, ht'⟩) a b + exact ⟨_, h.start, h⟩ + exact ⟨_, inferInstance, inferInstance, Completion.coe', cmp, Completion.denseRange_coe, + fun M a b ha hb => (Completion.dist_eq a b).trans (e M a b ha hb)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.TermModel +end + +/- +# Finite prices on geodesic terms + +These constructions precede squared-distance comparison and metric +completion. In particular they can be used to establish comparison. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.TermModel +open Spectral + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + {f : Tensor K S →+* ℝ} (hf : Monotone f) + +theorem length_mark (a b : S) : + length hf (.mark a) (.mark b) = Tensor.dist f a b := + length_eq hf (start hf) trivial trivial + +theorem length_seg (u : Fraction) (a b : Term S) : + length hf a (.seg u a b) = u.val * length hf a b ∧ + length hf (.seg u a b) b = (1 - u.val) * length hf a b := by + classical + obtain ⟨M, hM⟩ := exists_model hf {Term.seg u a b} + have hz := hM (.seg u a b) (by simp) + obtain ⟨ha, hb, h⟩ := (M.valid_iff u a b).mp hz + rw [length_eq hf M ha hz, length_eq hf M hz hb, length_eq hf M ha hb] + exact h + +theorem length_ordinary (B : Type) [Fintype B] [DecidableEq B] + (z : B → Term S) (D : ℝ) (h : ∀ i j, length hf (z i) (z j) ≤ D) : + ∃ P : Tensor K B → ℝ, (P = 0 ∨ P ∈ Tensor.ordinary K B (D * Fintype.card B)) ∧ + ∀ i j, P (Tensor.wire K i j 2) = length hf (z i) (z j) := by + classical + obtain ⟨M, hM⟩ := exists_model hf (Finset.univ.image z) + have hv (i : B) := hM (z i) (Finset.mem_image_of_mem z (Finset.mem_univ i)) + have hd (i j : B) := length_eq hf M (hv i) (hv j) + rcases subsingleton_or_nontrivial B with hh | hh + · refine ⟨0, .inl rfl, fun i j => ?_⟩ + rw [hd, Subsingleton.elim i j, Tensor.dist_self] + rfl + · let Q := Tensor.values 1 M.g + let x := M.point ∘ z + have hQ : Q ∈ Tensor.ordinary K M.Site 1 := ⟨1, ⟨zero_le_one, le_rfl⟩, M.g, M.mono, rfl⟩ + have hw (i j) : Q (Tensor.wire K (x i) (x j) 2) = length hf (z i) (z j) := by + rw [hd] + exact one_mul _ + refine ⟨Q ∘ Tensor.place x, .inr (Tensor.ordinary_restrict hQ x fun i j + => (hw i j).le.trans (h i j)), + fun i j => ?_⟩ + rw [Function.comp_apply, Tensor.place_wire, hw] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.TermModel +end + +/- +# Rescaled limits of spectral wire metrics + +Take the ultralimit on sequences of bounded rescaled displacement. +Distance zero need not be quotiented out for wire tests or segments. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.WireModels +open Filter Topology + +theorem zoom {K X Y : Type} [Field K] [PseudoMetricSpace Y] (h : WireModels K Y) + (s : Segments Y) (o : Y) (f : ℕ → X → Y) + (hb : ∀ x, ∃ D : ℝ, ∀ n : ℕ, ((n : ℝ) + 1) * dist (f n x) o ≤ D) (v : Ultrafilter ℕ) : + ∃ (Z : Type) (_ : PseudoMetricSpace Z) (g : X → Z), + WireModels K Z ∧ Segments Z ∧ ∀ a b, Tendsto + (fun n : ℕ => ((n : ℝ) + 1) * dist (f n a) (f n b)) (v : Filter ℕ) (𝓝 (dist (g a) (g b))) + := by + let Z := {z : ℕ → Y // ∃ D : ℝ, ∀ n : ℕ, ((n : ℝ) + 1) * dist (z n) o ≤ D} + let q (x y : Z) (n : ℕ) := ((n : ℝ) + 1) * dist (x.val n) (y.val n) + have pos (n : ℕ) : 0 ≤ (n : ℝ) + 1 := by positivity + have lim (x y : Z) : ∃ d : ℝ, Tendsto (q x y) (v : Filter ℕ) (𝓝 d) := by + obtain ⟨A, hA⟩ := x.property + obtain ⟨B, hB⟩ := y.property + have hh (n : ℕ) : q x y n ∈ Set.Icc 0 (A + B) := by + refine ⟨mul_nonneg (pos n) dist_nonneg, ?_⟩ + exact (mul_le_mul_of_nonneg_left (dist_triangle_right _ _ o) (pos n)).trans + ((mul_add _ _ _).le.trans (add_le_add (hA n) (hB n))) + obtain ⟨d, _, hd⟩ := isCompact_Icc.ultrafilter_le_nhds' (v.map (q x y)) + (Filter.mem_map.mpr (Eventually.of_forall hh)) + exact ⟨d, hd⟩ + choose d hd using lim + let _ : PseudoMetricSpace Z := + { dist := d + dist_self := fun x => tendsto_nhds_unique (hd x x) (by simp [q]) + dist_comm := fun x y => tendsto_nhds_unique (hd x y) + ((hd y x).congr' (Eventually.of_forall fun n => by simp [q, dist_comm])) + dist_triangle := fun x y z => le_of_tendsto_of_tendsto (hd x z) ((hd x y).add (hd y z)) + (Eventually.of_forall fun n => + (mul_le_mul_of_nonneg_left (dist_triangle _ _ _) (pos n)).trans_eq (mul_add _ _ _)) } + let g (x : X) : Z := ⟨fun n => f n x, hb x⟩ + refine ⟨Z, inferInstance, g, h.limit v (fun n z => z.val n) hd, ?_, fun a b => hd (g a) (g b)⟩ + intro t x y + choose m hm using fun n => s t (x.val n) (y.val n) + obtain ⟨A, hA⟩ := x.property + obtain ⟨B, hB⟩ := y.property + have hm' (n : ℕ) : ((n : ℝ) + 1) * dist (m n) o ≤ (1 - t.val) * A + t.val * B := by + have e := h.busemann t _ _ _ _ _ _ (hm n) (Divides.same t o) + linarith only [mul_le_mul_of_nonneg_left e (pos n), + mul_le_mul_of_nonneg_left (hA n) (sub_nonneg.mpr t.2.2), + mul_le_mul_of_nonneg_left (hB n) t.2.1] + let z : Z := ⟨m, _, hm'⟩ + have aux (a b : Z) (u : ℝ) (hh : ∀ n, dist (a.val n) (b.val n) = u * dist (x.val n) (y.val n)) : + dist a b = u * dist x y := by + refine tendsto_nhds_unique (hd a b) ((tendsto_const_nhds.mul (hd x y)).congr' ?_) + exact Eventually.of_forall fun n => by unfold q; rw [hh, mul_left_comm] + exact ⟨z, aux x z _ (fun n => (hm n).1), aux z y _ (fun n => (hm n).2)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.WireModels +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/TreePrice.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/TreePrice.lean new file mode 100644 index 0000000000..4258c34b3a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/TreePrice.lean @@ -0,0 +1,990 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.LinearAlgebra.Matrix.Notation +public import Mathlib.InformationTheory.Hamming +public import Mathlib.Tactic.Linarith +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.RingTheory.HahnSeries.Summable +public import Mathlib.RingTheory.HahnSeries.Valuation +public import Mathlib.Algebra.Field.Subfield.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space + +/-! Sparse matrix approximation with an explicit factorization of the error. -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +open Finset + +variable {F X Y Z : Type} [Field F] + +open scoped Classical in +/-- The condition `∃ (I : Type) (_ : Fintype I), Fintype.card I ≤ b ∧ ∃ P : Matrix X I F, ∃ Q : +Matrix I Y F, M = P * Q` on the specified data. -/ +def Low (M : Matrix X Y F) (b : ℝ) : Prop := + ∃ (I : Type) (_ : Fintype I), Fintype.card I ≤ b ∧ + ∃ P : Matrix X I F, ∃ Q : Matrix I Y F, M = P * Q + +open scoped Classical in +theorem Low.zero : Low (0 : Matrix X Y F) 0 := + ⟨Empty, inferInstance, by simp, 0, 0, by simp⟩ + +open scoped Classical in +theorem Low.mono {M : Matrix X Y F} {b c : ℝ} (h : Low M b) (he : b ≤ c) : Low M c := by + obtain ⟨I, _, hb, H⟩ := h + exact ⟨I, inferInstance, hb.trans he, H⟩ + +open scoped Classical in +theorem Low.add {M N : Matrix X Y F} {b c : ℝ} (h : Low M b) (h' : Low N c) : + Low (M + N) (b + c) := by + obtain ⟨I, _, hi, P, Q, rfl⟩ := h + obtain ⟨J, _, hj, R, S, rfl⟩ := h' + refine ⟨I ⊕ J, inferInstance, by simpa using add_le_add hi hj, + fun x => Sum.elim (P x) (R x), Sum.elim Q S, ?_⟩ + ext x y + change (∑ i, P x i * Q i y) + (∑ j, R x j * S j y) = + ∑ k, Sum.elim (P x) (R x) k * (Sum.elim Q S k) y + rw [Fintype.sum_sum_type] + rfl + +open scoped Classical in +theorem Low.left [Fintype X] {M : Matrix X Y F} {b : ℝ} (h : Low M b) (N : Matrix Z X F) : + Low (N * M) b := by + obtain ⟨I, _, hi, P, Q, rfl⟩ := h + exact ⟨I, inferInstance, hi, N * P, Q, (Matrix.mul_assoc _ _ _).symm⟩ + +open scoped Classical in +theorem Low.right [Fintype Y] {M : Matrix X Y F} {b : ℝ} (h : Low M b) (N : Matrix Y Z F) : + Low (M * N) b := by + obtain ⟨I, _, hi, P, Q, rfl⟩ := h + exact ⟨I, inferInstance, hi, P, Q * N, Matrix.mul_assoc _ _ _⟩ + +open scoped Classical in +theorem Low.full [Fintype Y] (M : Matrix X Y F) : Low M (Fintype.card Y) := + ⟨Y, inferInstance, le_rfl, M, 1, by simp⟩ + +open scoped Classical in +theorem Low.sub {M N : Matrix X Y F} {r s : ℝ} (h : Low M r) (h' : Low N s) : + Low (M - N) (r + s) := by + obtain ⟨I, _, hi, P, Q, rfl⟩ := h' + rw [sub_eq_add_neg] + exact h.add ⟨I, inferInstance, hi, -P, Q, by simp⟩ + +open scoped Classical in +theorem approx_mul [Fintype X] {M N P Q : Matrix X X F} {r s : ℝ} + (hp : Low (M - P) r) (hq : Low (N - Q) s) : Low (M * N - P * Q) (r + s) := by + rw [show M * N - P * Q = (M - P) * N + P * (N - Q) by rw [sub_mul, mul_sub]; abel] + exact (hp.right _).add (hq.left _) + +open scoped Classical in +/-- Upper bound the coordinatewise displacement on all but the active +register. -/ +abbrev Bits (m : ℕ) := Fin m → Bool +open scoped Classical in +/-- The quantity computed by `Fin (n + 1) → Bits m`. -/ +abbrev Registers (n m : ℕ) := Fin (n + 1) → Bits m + +variable {n m : ℕ} + +open scoped Classical in +/-- The condition `∃ N, Low (M - N) b ∧ ∀ x y, N x y ≠ 0 → ∀ j ≠ 0, (hammingDist (x j) (y j) : +ℝ) ≤ t` on the specified data. -/ +def Near (M : Matrix (Registers n m) (Registers n m) F) (t b : ℝ) : Prop := + ∃ N, Low (M - N) b ∧ ∀ x y, N x y ≠ 0 → ∀ j ≠ 0, (hammingDist (x j) (y j) : ℝ) ≤ t + +variable {M N : Matrix (Registers n m) (Registers n m) F} {a b c d : ℝ} + +open scoped Classical in +theorem Near.exact (hM : ∀ x y, M x y ≠ 0 → ∀ j ≠ 0, x j = y j) : Near M 0 0 := + ⟨M, by rw [sub_self]; exact Low.zero, fun x y h j hj => by simp [hM x y h j hj]⟩ + +open scoped Classical in +theorem Near.mul (h : Near M a b) (h' : Near N c d) : Near (M * N) (a + c) (b + d) := by + obtain ⟨P, hp, hp'⟩ := h + obtain ⟨Q, hq, hq'⟩ := h' + refine ⟨P * Q, ?_, fun x y hxy j hj => ?_⟩ + · exact approx_mul hp hq + · obtain ⟨z, _, hz⟩ := exists_ne_zero_of_sum_ne_zero (show (∑ z, P x z * Q z y) ≠ 0 from hxy) + calc + _ ≤ (hammingDist (x j) (z j) : ℝ) + hammingDist (z j) (y j) := by + exact_mod_cast hammingDist_triangle (x j) (z j) (y j) + _ ≤ _ := add_le_add (hp' _ _ (left_ne_zero_of_mul hz) j hj) + (hq' _ _ (right_ne_zero_of_mul hz) j hj) + +open scoped Classical in +theorem Near.mono (h : Near M a b) (h₁ : a ≤ c) (h₂ : b ≤ d) : Near M c d := by + obtain ⟨P, hp, hp'⟩ := h + exact ⟨P, hp.mono h₂, fun x y h j hj => (hp' x y h j hj).trans h₁⟩ + +open scoped Classical in +theorem diag_low [DecidableEq X] (u : Finset X) : + Low (Matrix.diagonal (fun x : X => if x ∈ u then (1 : F) else 0)) u.card := by + refine ⟨↥u, inferInstance, by simp, fun x j => if x = j.val then 1 else 0, + fun j y => if y = j.val then 1 else 0, ?_⟩ + ext x y + change _ = ∑ j : u, (if x = j.val then (1 : F) else 0) * (if y = j.val then 1 else 0) + rw [sum_coe_sort u (fun j => (if x = j then (1 : F) else 0) * (if y = j then 1 else 0))] + by_cases h : x = y <;> simp [h] + +open scoped Classical in +/-- Delete rows and columns in an exceptional set. -/ +theorem Near.crop (u : Finset (Registers n m)) + (h : ∀ x ∉ u, ∀ y ∉ u, M x y ≠ 0 → ∀ j ≠ 0, (hammingDist (x j) (y j) : ℝ) ≤ a) : + Near M a (2 * u.card) := by + let P := Matrix.diagonal (fun x => if x ∈ u then (1 : F) else 0) + let Q := Matrix.diagonal (fun x => if x ∈ u then (0 : F) else 1) + have hq : P = 1 - Q := by + ext x y + by_cases he : x = y <;> by_cases hx : y ∈ u <;> simp [P, Q, he, hx] + refine ⟨Q * M * Q, ?_, fun x y hxy => ?_⟩ + · have hp : Low P u.card := diag_low u + rw [show M - Q * M * Q = P * M + Q * M * P by + rw [hq, sub_mul, mul_sub, one_mul, mul_one]; abel, two_mul] + exact (hp.right M).add (hp.left _) + · have hn : y ∉ u ∧ x ∉ u ∧ M x y ≠ 0 := by + simpa [Q, Matrix.mul_diagonal, Matrix.diagonal_mul, mul_ite, ite_mul] using hxy + exact h x hn.2.1 y hn.1 hn.2.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +section +/- +# Binary Hamming balls + +Weight each mismatch by a factor in `(0,1)`. The total mass factors by +coordinate. Two choices of the factor bound small balls and both tails +outside a fixed neighborhood of half the word length. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +open Finset Real + +private theorem mass {m : ℕ} (x : Fin m → Bool) (r : ℝ) : + ∑ y, r ^ hammingDist x y = (1 + r) ^ m := by + let f (i : Fin m) (b : Bool) := if x i ≠ b then r else 1 + have hy (y : Fin m → Bool) : r ^ hammingDist x y = ∏ i, f i (y i) := by + simp only [f, prod_ite, prod_const, one_pow, mul_one, hammingDist] + have hi (i : Fin m) : ∑ b, f i b = 1 + r := by + unfold f + cases x i <;> simp [add_comm] + simp_rw [hy] + rw [← Fintype.prod_sum f] + simp only [hi, prod_const, card_univ, Fintype.card_fin] + +private theorem weighted_ball {m : ℕ} (x : Fin m → Bool) {r a d : ℝ} + (hr : 0 < r) (hr' : r ≤ 1) (hd : log (1 + r) - a * log r ≤ d * log 2) : + (#{y | (hammingDist x y : ℝ) ≤ a * m} : ℝ) ≤ (2 : ℝ) ^ (d * m) := by + let S := (univ : Finset (Fin m → Bool)).filter fun y => (hammingDist x y : ℝ) ≤ a * m + apply (mul_le_mul_iff_left₀ (exp_pos (log r * (a * m)))).mp + calc + _ = ∑ _ ∈ S, exp (log r * (a * m)) := by simp [S] + _ ≤ ∑ y ∈ S, r ^ hammingDist x y := by + apply sum_le_sum + intro y hy + rw [← rpow_natCast, rpow_def_of_pos hr] + exact exp_le_exp.mpr (mul_le_mul_of_nonpos_left (mem_filter.mp hy).2 (log_nonpos hr.le hr')) + _ ≤ ∑ y, r ^ hammingDist x y := + sum_le_sum_of_subset_of_nonneg (subset_univ _) (fun _ _ _ => by positivity) + _ = (1 + r) ^ m := mass x r + _ ≤ _ := by + rw [← rpow_natCast, rpow_def_of_pos (by positivity), rpow_def_of_pos (by norm_num), ← exp_add] + apply exp_le_exp.mpr + linarith only [mul_le_mul_of_nonneg_right hd (Nat.cast_nonneg m)] + +theorem ball_bound {δ : ℝ} (hd : 0 < δ) : + ∃ t : ℝ, 0 < t ∧ ∀ m : ℕ, ∀ x : Fin m → Bool, + (#{y | (hammingDist x y : ℝ) ≤ t * m} : ℝ) ≤ (2 : ℝ) ^ (δ * m) := by + let b := δ * log 2 / 2 + have hb : 0 < b := by unfold b; positivity + let r := min b (1 / 2) + have hr : 0 < r := lt_min hb (by norm_num) + have hr' : r < 1 := (min_le_right _ _).trans_lt (by norm_num) + have hk : log r < 0 := log_neg hr hr' + refine ⟨-b / log r, div_pos_of_neg_of_neg (neg_neg_of_pos hb) hk, fun _ x + => weighted_ball x hr hr'.le ?_⟩ + rw [div_mul_cancel₀ _ hk.ne] + have he := log_le_sub_one_of_pos (show 0 < 1 + r by positivity) + have hl : r ≤ b := min_le_left _ _ + unfold b at hl ⊢ + linarith + +private theorem below_half {a : ℝ} (ha : 0 ≤ a) (ha' : a < 1 / 2) : + ∃ δ : ℝ, 0 < δ ∧ ∀ m : ℕ, ∀ x : Fin m → Bool, + (#{y | (hammingDist x y : ℝ) ≤ a * m} : ℝ) ≤ (2 : ℝ) ^ ((1 - δ) * m) := by + let r := a + 1 / 2 + have hr : 0 < r := by unfold r; linarith + have hr' : r < 1 := by unfold r; linarith + have h₁ := log_le_sub_one_of_pos (show 0 < (1 + r) / 2 by positivity) + rw [log_div (by positivity) (by norm_num)] at h₁ + have h₂ := mul_le_mul_of_nonneg_left (log_le_sub_one_of_pos (inv_pos.mpr hr)) hr.le + rw [log_inv, mul_sub, mul_inv_cancel₀ hr.ne', mul_one] at h₂ + have h₃ := mul_lt_mul_of_neg_right (show a < r / 2 by unfold r; linarith) (log_neg hr hr') + have hl : log (1 + r) - a * log r < log 2 := by linarith + have hp : 0 < log 2 := by positivity + refine ⟨1 - (log (1 + r) - a * log r) / log 2, + sub_pos.mpr ((div_lt_one hp).mpr hl), fun _ x => weighted_ball x hr hr'.le ?_⟩ + rw [sub_sub_cancel, div_mul_cancel₀ _ hp.ne'] + +private theorem opposite {m : ℕ} (x : Fin m → Bool) : + hammingDist (fun _ => false) x + hammingDist (fun _ => true) x = m := by + have he : (univ.filter (fun i => true ≠ x i)) = univ.filter (fun i => ¬false ≠ x i) := by + ext i + simp only [mem_filter, mem_univ, true_and] + cases x i <;> simp + rw [hammingDist, hammingDist, he, card_filter_add_card_filter_not] + simp + +theorem tail_bound {t : ℝ} (ht : 0 < t) : ∃ δ : ℝ, 0 < δ ∧ ∀ m : ℕ, + (#{x : Fin m → Bool | t * m < |(hammingDist (fun _ => false) x : ℝ) - (m : ℝ) / 2|} : ℝ) ≤ + 2 * (2 : ℝ) ^ ((1 - δ) * m) := by + let a := max 0 (1 / 2 - t) + obtain ⟨δ, hd, hb⟩ := below_half (le_max_left _ _) (show a + < 1 / 2 from max_lt (by norm_num) (by linarith)) + refine ⟨δ, hd, fun m => ?_⟩ + let S (b : Bool) := (univ : Finset (Fin m → Bool)).filter + fun x => (hammingDist (fun _ => b) x : ℝ) ≤ a * m + have h : ({x : Fin m → Bool | t * m < |(hammingDist (fun _ + => false) x : ℝ) - (m : ℝ) / 2|} : Finset _) ⊆ + S false ∪ S true := by + intro x hx + simp only [mem_filter, mem_univ, true_and, lt_abs] at hx + simp only [S, mem_union, mem_filter, mem_univ, true_and] + have he : (hammingDist (fun _ => false) x : ℝ) + hammingDist (fun _ => true) x = m := + by exact_mod_cast opposite x + have ha := mul_le_mul_of_nonneg_right (show 1 / 2 - t + ≤ a from le_max_right _ _) (Nat.cast_nonneg m) + rcases hx with hx | hx + · right; linarith + · left; linarith + have hh := (card_le_card h).trans (card_union_le _ _) + calc + _ ≤ ((S false).card : ℝ) + (S true).card := by exact_mod_cast hh + _ ≤ _ := by rw [two_mul]; exact add_le_add (hb m _) (hb m _) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# The field generated by rational powers of a parameter + +Taking a subfield of the Hahn field equips rational expressions with +their lowest-exponent valuation. Only finite expressions are admitted. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +/-- The value specified by `Subfield.closure {x | ∃ r : ℚ, ∃ a : E, HahnSeries.single r a = x}`. -/ +def seriesField (E : Type*) [Field E] : Subfield (HahnSeries ℚ E) := + Subfield.closure {x | ∃ r : ℚ, ∃ a : E, HahnSeries.single r a = x} + +/-- The value specified by `↥(seriesField E)`. -/ +abbrev K0 (E : Type*) [Field E] := ↥(seriesField E) + +namespace K0 + +variable {E L : Type*} [Field E] [Field L] + +theorem single_mem (r : ℚ) (a : E) : HahnSeries.single r a ∈ seriesField E := + Subfield.subset_closure ⟨r, a, rfl⟩ + +/-- Computes the c by the application `HahnSeries.C.codRestrict (seriesField E) (single_mem 0)`. -/ +def C : E →+* K0 E := HahnSeries.C.codRestrict (seriesField E) (single_mem 0) + +/-- Uses `⟨HahnSeries.single r 1, single_mem _ _⟩` as the representation. -/ +def t (r : ℚ) : K0 E := ⟨HahnSeries.single r 1, single_mem _ _⟩ + +@[simp] theorem t_zero : (t 0 : K0 E) = 1 := rfl + +@[simp] theorem t_ne_zero (r : ℚ) : (t r : K0 E) ≠ 0 := + fun he => HahnSeries.single_ne_zero one_ne_zero (congrArg Subtype.val he) + +theorem t_add (r s : ℚ) : (t (r + s) : K0 E) = t r * t s := by + apply Subtype.ext + change HahnSeries.single (r + s) 1 = HahnSeries.single r (1 : E) * HahnSeries.single s 1 + rw [HahnSeries.single_mul_single, mul_one] + +@[simp] theorem t_neg (r : ℚ) : (t (-r) : K0 E) = (t r)⁻¹ := by + apply eq_inv_of_mul_eq_one_left + rw [← t_add, neg_add_cancel, t_zero] + +theorem t_pow (r : ℚ) (n : ℕ) : (t r : K0 E) ^ n = t (n * r) := by + induction n with + | zero => simp + | succ n ih => rw [Nat.cast_succ, add_mul, one_mul, t_add, pow_succ, ih] + +theorem t_zpow (r : ℚ) (n : ℤ) : (t r : K0 E) ^ n = t (n * r) := by + cases n with + | ofNat n => simpa using t_pow (E := E) r n + | negSucc n => + rw [Int.negSucc_eq, zpow_neg, Int.cast_neg, neg_mul, t_neg] + rw [show (n : ℤ) + 1 = ↑(n + 1) by rfl, zpow_natCast] + simpa using congrArg Inv.inv (t_pow (E := E) r (n + 1)) + +/-- The value specified by `(HahnSeries.addVal ℚ E).comap (seriesField E).subtype`. -/ +def val (E : Type*) [Field E] : AddValuation (K0 E) (WithTop ℚ) := + (HahnSeries.addVal ℚ E).comap (seriesField E).subtype + +theorem val_def (x : K0 E) : val E x = (Subtype.val x).orderTop := HahnSeries.addVal_apply + +@[simp] theorem val_t (r : ℚ) : val E (t r) = ↑r := + (val_def _).trans (HahnSeries.orderTop_single one_ne_zero) + +@[simp] theorem val_C {a : E} (ha : a ≠ 0) : val E (C a) = 0 := + (val_def _).trans (HahnSeries.orderTop_single ha) + +theorem induction_on {P : K0 E → Prop} (x : K0 E) + (hc : ∀ a, P (C a)) (ht : ∀ r, P (t r)) + (ha : ∀ x y, P x → P y → P (x + y)) (hn : ∀ x, P x → P (-x)) + (hi : ∀ x, P x → P x⁻¹) (hm : ∀ x y, P x → P y → P (x * y)) : P x := by + obtain ⟨x, hx⟩ := x + induction hx using Subfield.closure_induction with + | mem x hx => + obtain ⟨r, a, rfl⟩ := hx + have he : (⟨HahnSeries.single r a, single_mem r a⟩ : K0 E) = t r * C a := by + apply Subtype.ext + change _ = HahnSeries.single r (1 : E) * HahnSeries.single 0 a + rw [HahnSeries.single_mul_single, one_mul, add_zero] + rw [he] + exact hm _ _ (ht r) (hc a) + | one => exact ht 0 + | add x y hx hy h k => exact ha ⟨x, hx⟩ ⟨y, hy⟩ h k + | neg x hx h => exact hn ⟨x, hx⟩ h + | inv x hx h => exact hi ⟨x, hx⟩ h + | mul x y hx hy h k => exact hm ⟨x, hx⟩ ⟨y, hy⟩ h k + +@[ext] theorem hom_ext {f g : K0 E →+* L} (hC : ∀ a, f (C a) = g (C a)) + (ht : ∀ r, f (t r) = g (t r)) : f = g := by + apply RingHom.ext + intro x + induction x using induction_on with + | hc a => exact hC a + | ht r => exact ht r + | ha _ _ h k => rw [map_add, map_add, h, k] + | hn _ h => rw [map_neg, map_neg, h] + | hi _ h => rw [map_inv₀, map_inv₀, h] + | hm _ _ h k => rw [map_mul, map_mul, h, k] + +end K0 +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- # The rational disk tree and its leaf metric -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +variable {E : Type*} [Field E] + +/-- The subtype of `l : ℚ` satisfying `l ≤ 1`. -/ +abbrev Depth := {l : ℚ // l ≤ 1} + +/-- Indexes the disk point by the coordinates of `K0 E × Depth`. -/ +abbrev diskPoint (E : Type*) [Field E] := K0 E × Depth + +/-- The value specified by `(z, ⟨1, le_rfl⟩)`. -/ +def leaf (z : K0 E) : diskPoint E := (z, ⟨1, le_rfl⟩) + +/-- The quantity computed by `a + b - 2 * min (min a b) ((val E (x - y)).untopD 1)`. -/ +def diskGap (x y : K0 E) (a b : ℚ) : ℚ := + a + b - 2 * min (min a b) ((val E (x - y)).untopD 1) + +/-- Computes the disk dist by the application `diskGap x.1 y.1 x.2.val y.2.val`. -/ +def diskDist (x y : diskPoint E) : ℚ := diskGap x.1 y.1 x.2.val y.2.val + +theorem diskDist_comm (x y : diskPoint E) : diskDist x y = diskDist y x := by + unfold diskDist diskGap + rw [add_comm, min_comm x.2.val, AddValuation.map_sub_swap] + +@[simp] theorem diskDist_self (x : diskPoint E) : diskDist x x = 0 := by + simp [diskDist, diskGap, min_eq_left x.2.property, two_mul] + +theorem leaf_dist {x y : K0 E} {r : ℚ} (h : val E (x - y) = ↑r) : + diskDist (leaf x) (leaf y) = 2 * max (1 - r) 0 := by + simp only [diskDist, diskGap, leaf, min_self, h, WithTop.untopD_coe] + rcases le_total 1 r with h | h + · rw [min_eq_left h, max_eq_right (sub_nonpos.mpr h)] + ring + · rw [min_eq_right h, max_eq_left (sub_nonneg.mpr h)] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- # Changes of coefficients and dilation of valuations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +variable {E L : Type*} [Field E] [Field L] + +/-- The restrict series of type `K0 E →+* K0 L` for the given inputs. -/ +def restrictSeries (f : HahnSeries ℚ E →+* HahnSeries ℚ L) + (h : ∀ r a, f (HahnSeries.single r a) ∈ seriesField L) : K0 E →+* K0 L := + (f.comp (seriesField E).subtype).codRestrict (seriesField L) fun x => by + have H : seriesField E ≤ (seriesField L).comap f := + Subfield.closure_le.mpr (by rintro _ ⟨r, a, rfl⟩; exact h r a) + exact H x.property + +/-- Builds `HahnSeries ℚ E →+* HahnSeries ℚ L where toFun x` with the specified `toFun`, +`map_add'`, `map_mul'`, `map_zero'`. -/ +def mapSeries (φ : E →+* L) : HahnSeries ℚ E →+* HahnSeries ℚ L where + toFun x := x.map φ + map_add' x y := by ext; simp + map_mul' _ _ := HahnSeries.map_mul φ.toNonUnitalRingHom + map_zero' := by ext; simp + map_one' := by ext i; simp [HahnSeries.coeff_one, apply_ite] + +theorem mapSeries_single (φ : E →+* L) (r : ℚ) (a : E) : + mapSeries φ (HahnSeries.single r a) = HahnSeries.single r (φ a) := by + ext i + change φ ((HahnSeries.single r a).coeff i) = _ + by_cases h : i = r <;> simp [h] + +/-- The indexed operation `restrictSeries (mapSeries φ) fun r a => by rw [mapSeries_single] +exact Subfield.subset_closure ⟨r, φ a, rfl⟩`. -/ +def map (φ : E →+* L) : K0 E →+* K0 L := + restrictSeries (mapSeries φ) fun r a => by + rw [mapSeries_single] + exact Subfield.subset_closure ⟨r, φ a, rfl⟩ + +@[simp] theorem map_C (φ : E →+* L) (a : E) : map φ (C a) = C (φ a) := + Subtype.ext (mapSeries_single φ 0 a) + +@[simp] theorem map_t (φ : E →+* L) (r : ℚ) : map φ (t r) = t r := + Subtype.ext ((mapSeries_single φ r 1).trans (congrArg _ φ.map_one)) + +@[simp] theorem val_map (φ : E →+* L) (x : K0 E) : val L (map φ x) = val E x := by + have e : (Subtype.val (map φ x)).support = (Subtype.val x).support := by + ext i + change φ ((Subtype.val x).coeff i) ≠ 0 ↔ (Subtype.val x).coeff i ≠ 0 + exact map_ne_zero φ + rw [val_def, val_def] + by_cases h : x = 0 + · simp [h] + have hu : Subtype.val x ≠ 0 := fun he => h (Subtype.ext he) + have hv : Subtype.val (map φ x) ≠ 0 := fun he => (map_ne_zero (map φ)).mpr h (Subtype.ext he) + simp only [HahnSeries.orderTop_of_ne_zero hu, HahnSeries.orderTop_of_ne_zero hv, e] + +/-- The indexed operation `HahnSeries.embDomainRingHom (AddMonoidHom.mulLeft d) (fun _ _ => +mul_left_cancel₀ hd.ne') (fun _ _ => mul_le_mul_iff_right₀ hd)`. -/ +def expand (d : ℚ) (hd : 0 < d) : HahnSeries ℚ E →+* HahnSeries ℚ E := + HahnSeries.embDomainRingHom (AddMonoidHom.mulLeft d) (fun _ _ => mul_left_cancel₀ hd.ne') + (fun _ _ => mul_le_mul_iff_right₀ hd) + +theorem expand_single (d : ℚ) (hd : 0 < d) (r : ℚ) (a : E) : + expand d hd (HahnSeries.single r a) = HahnSeries.single (d * r) a := + HahnSeries.embDomain_single + +/-- The indexed operation `restrictSeries (expand d hd) fun r a => by rw [expand_single] exact +Subfield.subset_closure ⟨d * r, a, rfl⟩`. -/ +def dilate (d : ℚ) (hd : 0 < d) : K0 E →+* K0 E := + restrictSeries (expand d hd) fun r a => by + rw [expand_single] + exact Subfield.subset_closure ⟨d * r, a, rfl⟩ + +@[simp] theorem dilate_C (d : ℚ) (hd : 0 < d) (a : E) : dilate d hd (C a) = C a := by + apply Subtype.ext + change expand d hd (HahnSeries.single 0 a) = HahnSeries.single 0 a + rw [expand_single, mul_zero] + +@[simp] theorem dilate_t (d : ℚ) (hd : 0 < d) (r : ℚ) : + dilate d hd (t r : K0 E) = t (d * r) := + Subtype.ext (expand_single d hd r 1) + +theorem val_dilate (d : ℚ) (hd : 0 < d) (x : K0 E) : + val E (dilate d hd x) = WithTop.map (fun r => d * r) (val E x) := by + rw [val_def, val_def] + exact HahnSeries.orderTop_embDomain + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- Binary register swap as three shears followed by a sign change. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +open Finset + +variable {F X I : Type} [Field F] [Fintype I] [DecidableEq I] [Fintype X] + +open scoped Classical in +/-- Evaluates `∏ i, M i (x i) (y i)` at the input `x y`. -/ +def matPower (M : I → Matrix X X F) : Matrix (I → X) (I → X) F := + fun x y => ∏ i, M i (x i) (y i) + +open scoped Classical in +theorem matPower_mul (M N : I → Matrix X X F) : + matPower (fun i => M i * N i) = matPower M * matPower N := by + ext x y + simp only [matPower, Matrix.mul_apply, Fintype.prod_sum, prod_mul_distrib] + +variable {n m : ℕ} + +open scoped Classical in +/-- The quantity computed by `Fin (n + 1) → Bool`. -/ +abbrev Col (n : ℕ) := Fin (n + 1) → Bool +open scoped Classical in +/-- Computes the op by the application `Matrix (Registers n m) (Registers n m) F`. -/ +abbrev Op (F : Type) (n m : ℕ) := Matrix (Registers n m) (Registers n m) F + +open scoped Classical in +/-- The value specified by `x ∘ Equiv.swap 0 i`. -/ +def swap (i : Fin (n + 1)) (x : Fin (n + 1) → X) := x ∘ Equiv.swap 0 i + +omit [Fintype X] in +open scoped Classical in +@[simp] theorem swap_swap (i : Fin (n + 1)) (x : Fin (n + 1) → X) : swap i (swap i x) = x := + funext fun _ => congrArg x (Equiv.swap_apply_self _ _ _) + +open scoped Classical in +/-- Evaluates `if y = swap i x then 1 else 0` at the input `x y`. -/ +def exchange (F X : Type) [Field F] [DecidableEq X] (i : Fin (n + 1)) : + Matrix (Fin (n + 1) → X) (Fin (n + 1) → X) F := fun x y => if y = swap i x then 1 else 0 + +open scoped Classical in +/-- Evaluates `x i b` at the input `i`. -/ +def column (x : Registers n m) (b : Fin m) : Col n := fun i => x i b + +open scoped Classical in +/-- Evaluates `∏ b, A (column x b) (column y b)` at the input `x y`. -/ +def parallel (m : ℕ) (A : Matrix (Col n) (Col n) F) : Op F n m := + fun x y => ∏ b, A (column x b) (column y b) + +open scoped Classical in +theorem parallel_mul (A B : Matrix (Col n) (Col n) F) : + parallel m (A * B) = parallel m A * parallel m B := by + ext x y + simp only [parallel, Matrix.mul_apply, Fintype.prod_sum, prod_mul_distrib] + let e := Equiv.piComm (fun (_ : Fin (n + 1)) (_ : Fin m) => Bool) + exact (e.sum_comp _).symm + +open scoped Classical in +theorem parallel_exchange (i : Fin (n + 1)) : + parallel m (exchange F Bool i) = exchange F (Bits m) i := by + ext x y + change (∏ b, if column y b = swap i (column x b) then (1 : F) else 0) = + if y = swap i x then 1 else 0 + by_cases h : y = swap i x + · rw [ite_eq_left h] + exact prod_eq_one (fun _ _ => ite_eq_left (by rw [h]; rfl)) + · rw [ite_eq_right h] + obtain ⟨a, b, he⟩ : ∃ a b, y a b ≠ swap i x a b := by simpa [funext_iff] using h + exact prod_eq_zero (mem_univ b) (ite_eq_right fun e => he (congrFun e a)) + +open scoped Classical in +/-- Requires `x 0 = b ∧ x i ≠ b`. -/ +def starts (i : Fin (n + 1)) (b : Bool) (x : Col n) : Prop := x 0 = b ∧ x i ≠ b + +open scoped Classical in +/-- The shear of type `Matrix (Col n) (Col n) F` for the given inputs. -/ +def shear (i : Fin (n + 1)) (b : Bool) (v : F) : Matrix (Col n) (Col n) F := + fun x y => (if y = x then 1 else 0) + + if starts i b x then (if y = swap i x then v else 0) else 0 + +open scoped Classical in +private theorem shear_mul (i : Fin (n + 1)) (b : Bool) (v : F) + (A : Matrix (Col n) (Col n) F) (x y : Col n) : + (shear i b v * A) x y = A x y + if starts i b x then v * A (swap i x) y else 0 := by + by_cases h : starts i b x <;> simp [Matrix.mul_apply, shear, h, add_mul, sum_add_distrib, ite_mul] + +open scoped Classical in +/-- The value specified by `Matrix.diagonal fun x => if starts i false x then -1 else 1`. -/ +def signs (F : Type) [Field F] (i : Fin (n + 1)) : Matrix (Col n) (Col n) F := + Matrix.diagonal fun x => if starts i false x then -1 else 1 + +open scoped Classical in +theorem exchange_shears (i : Fin (n + 1)) : + exchange F Bool i = shear i false 1 * (shear i true (-1) * (shear i false 1 * signs F i)) := by + ext x y + simp only [shear_mul, swap_swap, one_mul, neg_one_mul, exchange] + have h₁ : swap i x 0 = x i := by simp [swap] + have h₂ : swap i x i = x 0 := by simp [swap] + have hsame (h : x 0 = x i) : swap i x = x := by + funext a + simp only [swap, Function.comp_apply, Equiv.swap_apply_def] + split_ifs <;> simp_all + have hd (a : Col n) : signs F i a y = + if y = a then (if starts i false a then -1 else 1) else 0 := by + simp only [signs, Matrix.diagonal_apply, eq_comm (a := a)] + simp only [hd, starts, h₁, h₂] + by_cases h : x 0 = x i + · simp only [hsame h] + rcases Bool.dichotomy (x 0) with h₀ | h₀ <;> simp_all + · rcases Bool.dichotomy (x 0) with h₀ | h₀ <;> + rcases Bool.dichotomy (x i) with hi | hi <;> simp_all + split_ifs <;> simp + +open scoped Classical in +theorem near_signs (i : Fin (n + 1)) : Near (parallel m (signs F i)) 0 0 := by + apply Near.exact + intro x y h j _ + funext b + have hb := prod_ne_zero_iff.mp h b (mem_univ b) + by_contra he + exact hb (Matrix.diagonal_apply_ne _ (fun he' => he (congrFun he' j))) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# Restricting shear stages to typical words + +In a shear every changed bit moves the active register in the same +direction. If both endpoints have typical weight, few bits can change. +The exceptional rows and columns have exponentially small relative size. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +open Finset + +variable {F : Type} [Field F] {n m : ℕ} + +open scoped Classical in +private def weight (x : Registers n m) : ℝ := hammingDist (fun _ => false) (x 0) + +open scoped Classical in +private theorem count_dist (x y : Bits m) : + (hammingDist x y : ℝ) = ∑ b, if x b = y b then 0 else 1 := by + simp [hammingDist, sum_ite] + +open scoped Classical in +private theorem shear_dist (i : Fin (n + 1)) (b : Bool) (v : F) (x y : Registers n m) + (h : parallel m (shear i b v) x y ≠ 0) (j : Fin (n + 1)) : + (hammingDist (x j) (y j) : ℝ) ≤ |weight y - weight x| := by + let s : ℝ := if b then -1 else 1 + have step (u w : Col n) (h : shear i b v u w ≠ 0) : + (if u j = w j then (0 : ℝ) else 1) ≤ + s * ((if false = w 0 then 0 else 1) - (if false = u 0 then 0 else 1)) := by + by_cases he : w = u + · simp [he] + have hh : starts i b u ∧ w = swap i u := by + by_contra hh + by_cases h' : starts i b u <;> simp_all [shear] + have h₀ : u 0 = b := hh.1.1 + have h₁ : w 0 ≠ b := by simpa [hh.2, swap] using hh.1.2 + cases b <;> simp [s, h₀, h₁] <;> split_ifs <;> norm_num + have hs : (hammingDist (x j) (y j) : ℝ) ≤ s * (weight y - weight x) := by + simp only [weight, count_dist, ← sum_sub_distrib, mul_sum] + exact sum_le_sum fun k hk => step _ _ (prod_ne_zero_iff.mp h k hk) + cases b + · exact hs.trans (by simpa [s] using le_abs_self (weight y - weight x)) + · exact hs.trans (by simpa [s] using neg_le_abs (weight y - weight x)) + +open scoped Classical in +private def bad (n m : ℕ) (t : ℝ) : Finset (Registers n m) := + {x | t * m < |weight x - (m : ℝ) / 2|} + +open scoped Classical in +private theorem near_shear (i : Fin (n + 1)) (t : ℝ) (b : Bool) (v : F) : + Near (parallel m (shear i b v)) (2 * (t * m)) (2 * (bad n m t).card) := by + apply Near.crop + intro x hx y hy h j _ + simp only [bad, mem_filter, mem_univ, true_and, not_lt] at hx hy + refine (shear_dist i b v x y h j).trans ?_ + rw [abs_le] at hx hy ⊢ + constructor <;> linarith + +open scoped Classical in +private theorem bad_count (n m : ℕ) (t : ℝ) : + (bad n m t).card ≤ + #{x : Bits m | t * m < |(hammingDist (fun _ => false) x : ℝ) - (m : ℝ) / 2|} * 2 ^ (m * n) + := by + let S : Finset (Bits m) := + {x | t * m < |(hammingDist (fun _ => false) x : ℝ) - (m : ℝ) / 2|} + let e := (Fin.consEquiv (fun _ : Fin (n + 1) => Bits m)).symm + have h : (bad n m t).image e ⊆ S ×ˢ univ := by + intro x hx + obtain ⟨y, hy, rfl⟩ := mem_image.mp hx + exact mem_product.mpr ⟨mem_filter.mpr ⟨mem_univ _, (mem_filter.mp hy).2⟩, mem_univ _⟩ + simpa [card_image_of_injective _ e.injective, Bits, S, pow_mul] using card_le_card h + +open scoped Classical in +theorem near_exchange (n : ℕ) {t : ℝ} (ht : 0 < t) : + ∃ c : ℝ, 0 < c ∧ c ≤ 1 ∧ ∀ (m : ℕ) (i : Fin (n + 1)), + Near (exchange F (Bits m) i) (6 * (t * m)) (12 * (2 : ℝ) ^ (((n : ℝ) + 1 - c) * m)) := by + obtain ⟨δ, hδ, h⟩ := tail_bound ht + let c := min 1 δ + refine ⟨c, lt_min zero_lt_one hδ, min_le_left _ _, fun m i => ?_⟩ + have he : ((bad n m t).card : ℝ) ≤ 2 * (2 : ℝ) ^ (((n : ℝ) + 1 - c) * m) := calc + _ ≤ (#{x : Bits m | t * m < |(hammingDist (fun _ => false) x : ℝ) - (m : ℝ) / 2|} : ℝ) * + (2 : ℝ) ^ (m * n) := by exact_mod_cast bad_count n m t + _ ≤ 2 * (2 : ℝ) ^ ((1 - δ) * m) * (2 : ℝ) ^ (m * n) + := mul_le_mul_of_nonneg_right (h m) (by positivity) + _ ≤ _ := by + rw [mul_assoc, ← Real.rpow_natCast, ← Real.rpow_add (by norm_num : (0 : ℝ) < 2), Nat.cast_mul] + refine mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le (by norm_num) ?_) (by + norm_num) + nlinarith only [mul_le_mul_of_nonneg_right (show c + ≤ δ from min_le_right _ _) (Nat.cast_nonneg m)] + rw [← parallel_exchange, exchange_shears, parallel_mul, parallel_mul, parallel_mul] + have hf := near_shear (m := m) i t false (1 : F) + have hg := near_shear (m := m) i t true (-1 : F) + exact (hf.mul (hg.mul (hf.mul (near_signs i)))).mono (by linarith) (by linarith) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# One active register + +Conjugate the single-register matrix by a swap, so that all dense +operations act on register zero. Only a fixed number of approximate +swaps is needed, independently of the size of the base matrix. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +open Finset + +variable {F : Type} [Field F] {n m : ℕ} + +open scoped Classical in +private def applyAt (B : Matrix (Bits m) (Bits m) F) (i : Fin (n + 1)) : Op F n m := + matPower (fun j => if j = i then B else 1) + +open scoped Classical in +private theorem conjugate (B : Matrix (Bits m) (Bits m) F) (i : Fin (n + 1)) : + applyAt B i = exchange F (Bits m) i * applyAt B 0 * exchange F (Bits m) i := by + ext x y + have h (z : Registers n m) : y = swap i z ↔ z = swap i y := by + constructor <;> rintro rfl <;> simp + simp only [Matrix.mul_apply, exchange, h, ite_mul, mul_ite, one_mul, mul_one, zero_mul, mul_zero] + simp only [sum_ite_eq', mem_univ, ite_true] + unfold applyAt matPower + rw [← Equiv.prod_comp (Equiv.swap 0 i)] + refine prod_congr rfl fun j _ => ?_ + have hj : Equiv.swap 0 i j = i ↔ j = 0 := by + rw [← (Equiv.swap 0 i).injective.eq_iff (a := j), Equiv.swap_apply_left] + simp [swap, hj] + +open scoped Classical in +private theorem local_exact (B : Matrix (Bits m) (Bits m) F) : + Near (applyAt B (0 : Fin (n + 1))) 0 0 := by + apply Near.exact + intro x y h j hj + unfold applyAt matPower at h + have hn := prod_ne_zero_iff.mp h j (mem_univ _) + simpa [hj, Matrix.one_apply] using hn + +open scoped Classical in +private theorem parallel_near (B : Matrix (Bits m) (Bits m) F) {a b : ℝ} + (h : ∀ i : Fin (n + 1), Near (exchange F (Bits m) i) a b) : + Near (matPower (fun _ : Fin (n + 1) => B)) (2 * (n + 1) * a) (2 * (n + 1) * b) := by + let T (s : Finset (Fin (n + 1))) := matPower (fun i => if i ∈ s then B else 1) + have go (s : Finset (Fin (n + 1))) : Near (T s) (2 * s.card * a) (2 * s.card * b) := by + induction s using Finset.induction_on with + | empty => + simp only [card_empty, Nat.cast_zero, mul_zero, zero_mul] + apply Near.exact + intro x y h j _ + have hn := prod_ne_zero_iff.mp h j (mem_univ _) + simpa [Matrix.one_apply] using hn + | @insert i s hi ih => + have eq : T (insert i s) = applyAt B i * T s := by + unfold T applyAt + rw [← matPower_mul] + congr 1 + funext j + by_cases he : j = i <;> simp [he, hi] + rw [eq, conjugate, card_insert_of_notMem hi, Nat.cast_add, Nat.cast_one] + exact ((((h i).mul (local_exact B)).mul (h i)).mul ih).mono (by linarith) (by linarith) + simpa [T] using go univ + +open scoped Classical in +private theorem row_size (n m : ℕ) (x : Registers n m) (t : ℝ) + (S : Finset (Registers n m)) + (h : ∀ y ∈ S, ∀ i ≠ 0, (hammingDist (x i) (y i) : ℝ) ≤ t * m) + (hb : ∀ u : Bits m, (#{v | (hammingDist u v : ℝ) ≤ t * m} : ℝ) ≤ + (2 : ℝ) ^ ((1 / ((n : ℝ) + 1)) * m)) : S.card ≤ 2 ^ (2 * m) := by + let B (i : Fin (n + 1)) : Finset (Bits m) := + if i = 0 then univ else univ.filter fun v => (hammingDist (x i) v : ℝ) ≤ t * m + have hsub : S ⊆ Fintype.piFinset B := by + intro y hy + refine Fintype.mem_piFinset.mpr fun i => ?_ + by_cases hi : i = 0 + · simp [B, hi] + · simpa [B, hi] using h y hy i hi + have hcard := card_le_card hsub + rw [Fintype.card_piFinset, Fin.prod_univ_succ] at hcard + have hz : (B 0).card = 2 ^ m := by simp [B, Bits] + have htail : (∏ i : Fin n, ((B i.succ).card : ℝ)) ≤ (2 : ℝ) ^ m := calc + _ ≤ ∏ _i : Fin n, (2 : ℝ) ^ ((1 / ((n : ℝ) + 1)) * m) := by + refine prod_le_prod₀ (by intros; positivity) fun i _ => ?_ + simpa [B] using hb (x i.succ) + _ ≤ _ := by + simp only [prod_const, card_univ, Fintype.card_fin] + rw [← Real.rpow_natCast, ← Real.rpow_mul (by norm_num), ← Real.rpow_natCast] + apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + rw [show 1 / ((n : ℝ) + 1) * m * n = (m * n) / ((n : ℝ) + + 1) by ring, div_le_iff₀ (by positivity)] + nlinarith only [Nat.cast_nonneg (α := ℝ) m] + have ht : ∏ i : Fin n, (B i.succ).card ≤ 2 ^ m := by exact_mod_cast htail + rw [hz] at hcard + rw [two_mul, pow_add] + exact hcard.trans (Nat.mul_le_mul_left _ ht) + +open scoped Classical in +theorem sparse_power (n : ℕ) : ∃ c C : ℝ, 0 < c ∧ c ≤ 1 ∧ 0 ≤ C ∧ + ∀ m (B : Matrix (Bits m) (Bits m) F), ∃ D : Op F n m, + Low (matPower (fun _ : Fin (n + 1) => B) - D) (C * (2 : ℝ) ^ (((n : ℝ) + 1 - c) * m)) ∧ + ∀ x, #{y | D x y ≠ 0} ≤ 2 ^ (2 * m) := by + obtain ⟨t, ht, hb⟩ := ball_bound (by positivity : 0 < 1 / ((n : ℝ) + 1)) + let u := t / (12 * ((n : ℝ) + 1)) + obtain ⟨c, hc, hc', he⟩ := near_exchange (F := F) n (show 0 < u by positivity) + refine ⟨c, 24 * ((n : ℝ) + 1), hc, hc', by positivity, fun m B => ?_⟩ + obtain ⟨D, hd, hD⟩ := parallel_near B (he m) + refine ⟨D, hd.mono (by linarith), fun x => row_size n m x t _ ?_ (hb m)⟩ + intro y hy i hi + refine (hD x y (mem_filter.mp hy).2 i hi).trans_eq ?_ + unfold u + field_simp + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# Label rates on a tree of disks + +A star compares an arbitrary center value with some values at the +ends. No particular choice of a transcendental parameter is needed. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 + +open Spectral + +variable {E : Type*} [Field E] + +/-- The indexing data represented by `Fin 4 → α`. -/ +abbrev Four (α : Type*) := Fin 4 → α + +/-- Evaluates `a i + b i * u` at the input `i`. -/ +def diskAffine (a b : Four (K0 E)) (u : K0 E) : Four (K0 E) := fun i => a i + b i * u + +/-- In the case `none`, this construction gives `t (-r none) * u`. -/ +def armEnd {n : ℕ} (c : Fin n → K0 E) (r : Option (Fin n) → ℚ) (u : K0 E) : + Option (Fin n) → K0 E + | none => t (-r none) * u + | some j => c j + t (r (some j)) * u + +/-- The motion tree used in the `K0` construction. -/ +structure MotionTree (F : Type) [Field F] (E : Type*) [Field E] where + /-- The `MotionTree` field of type `Four (K0 E) → Four ℚ → ℝ`. -/ + rate : Four (K0 E) → Four ℚ → ℝ + realized (x : Four (K0 E)) (l : Four ℚ) (hl : ∀ i, l i ≤ 1) : + ∃ D : ℝ, ∃ P ∈ Tensor.ordinary F (Fin 4) D, P 2 = rate x l ∧ + ∀ i j, P (Tensor.wire F i j 2) = (diskGap (x i) (x j) (l i) (l j) : ℝ) + chord (x y z : Four (K0 E)) (l m k : Four ℚ) + (hl : ∀ i, l i ≤ 1) (hm : ∀ i, m i ≤ 1) (hk : ∀ i, k i ≤ 1) + (θ : ℚ) (h₀ : 0 ≤ θ) (h₁ : θ ≤ 1) + (left : ∀ i, diskGap (x i) (z i) (l i) (k i) = θ * diskGap (x i) (y i) (l i) (m i)) + (right : ∀ i, diskGap (z i) (y i) (k i) (m i) = (1 - θ) * diskGap (x i) (y i) (l i) (m i)) : + rate z k ≤ (1 - (θ : ℝ)) * rate x l + θ * rate y m + star {n : ℕ} (a b : Four (K0 E)) (c : Fin n → K0 E) + (hc : ∀ j, 0 ≤ val E (c j)) (hd : ∀ i j, i ≠ j → val E (c i - c j) = 0) + (r : Option (Fin n) → ℚ) (hr : ∀ j, 0 < r j) + (l : Four ℚ) (k : Option (Fin n) → Four ℚ) + (hl : ∀ i, l i ≤ 1) (hk : ∀ j i, k j i ≤ 1) + (harmonic : ∀ i, ∑ j, (k j i - l i) / r j = 0) (v : K0 E) (hv : 0 ≤ val E v) : + ∃ u : Option (Fin n) → K0 E, (∀ j, 0 ≤ val E (u j)) ∧ + 0 ≤ ∑ j, (rate (diskAffine a b (armEnd c r (u j) j)) (k j) - + rate (diskAffine a b v) l) / (r j : ℝ) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- Bounds on the diagonal cost from paths of three wires. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 + +open Spectral Finset + +variable {F : Type} [Field F] {E : Type*} [Field E] + +private theorem path_cost {D : ℝ} {P : Tensor F (Fin 4) → ℝ} + (h : P ∈ Tensor.ordinary F (Fin 4) D) (a b c d : Fin 4) + (ha : ({a, b, c, d} : Finset (Fin 4)) = univ) : + P 2 ≤ P (Tensor.wire F a b 2) + P (Tensor.wire F b c 2) + P (Tensor.wire F c d 2) := by + let W (a b : Fin 4) := Tensor.wire F a b 2 + have h₁ := Tensor.shared_join F (U := {a, b}) (V := {b, c, d}) (c := b) (by simp) (by simp) 2 + have h₂ := Tensor.shared_join F (U := {b, c}) (V := {c, d}) (c := c) (by simp) (by simp) 2 + rw [show ({a, b} : Finset (Fin 4)) ∪ {b, c, d} = univ by + rw [← ha]; ext; simp; tauto, Tensor.shared_all] at h₁ + rw [show ({b, c} : Finset (Fin 4)) ∪ {c, d} = {b, c, d} by simp] at h₂ + have h₃ : (2 : Tensor F (Fin 4)) ≤ W a b * (W b c * W c d) := + h₁.trans (Tensor.mul_le_mul_left _ _ _ h₂) + obtain ⟨s, hs, f, hf, rfl⟩ := h + have hpos (i j : Fin 4) : 0 < f (W i j) := by + rw [show f (W i j) = _ from Tensor.price_wire f hf _ _ (by decide : 0 < 2)] + positivity + have he := Real.log_le_log (show 0 < f 2 by rw [map_ofNat]; norm_num) (hf h₃) + rw [f.map_mul, f.map_mul, Real.log_mul (hpos _ _).ne' (mul_ne_zero (hpos _ _).ne' (hpos _ _).ne'), + Real.log_mul (hpos _ _).ne' (hpos _ _).ne'] at he + have he' := mul_le_mul_of_nonneg_left (div_le_div_of_nonneg_right he + (Real.log_nonneg (by norm_num : (1 : ℝ) ≤ 2))) hs.1 + simpa only [Tensor.values, W, add_div, mul_add, add_assoc] using he' + +namespace MotionTree +variable (H : MotionTree F E) + +theorem path (x : Four (K0 E)) (l : Four ℚ) (hl : ∀ i, l i ≤ 1) + (a b c d : Fin 4) (ha : ({a, b, c, d} : Finset (Fin 4)) = univ) : + H.rate x l ≤ (diskGap (x a) (x b) (l a) (l b) + diskGap (x b) (x c) (l b) (l c) + + diskGap (x c) (x d) (l c) (l d) : ℚ) := by + obtain ⟨D, P, hP, he, hw⟩ := H.realized x l hl + simpa only [he, hw, Rat.cast_add] using path_cost hP a b c d ha + +theorem nonneg (x : Four (K0 E)) (l : Four ℚ) (hl : ∀ i, l i ≤ 1) : 0 ≤ H.rate x l := by + obtain ⟨D, P, ⟨d, hd, f, hf, rfl⟩, he, _⟩ := H.realized x l hl + rw [← he] + exact Tensor.values_nonneg hd.1 hf _ + +end MotionTree + +theorem gap_bound {x y : K0 E} {a b r : ℚ} (ha : r ≤ a) (hb : r ≤ b) + (hr : r ≤ 1) (h : (r : WithTop ℚ) ≤ val E (x - y)) : diskGap x y a b ≤ a + b - 2 * r := by + have hm : r ≤ (val E (x - y)).untopD 1 := by + generalize val E (x - y) = t at * + cases t <;> simp_all + unfold diskGap + linarith only [le_min (le_min ha hb) hm] + +theorem gap_of_le {x y : K0 E} {a b : ℚ} (ha : a ≤ b) + (h : (a : WithTop ℚ) ≤ val E (x - y)) (ha' : a ≤ 1) : diskGap x y a b = b - a := by + have hu := gap_bound le_rfl ha ha' h + unfold diskGap at * + linarith [min_le_left (min a b) ((val E (x - y)).untopD 1), min_le_left a b] + +theorem gap_symm (x y : K0 E) (a b : ℚ) : diskGap x y a b = diskGap y x b a := by + rw [diskGap, diskGap, add_comm, min_comm a b, AddValuation.map_sub_swap] + +theorem gap_same (x : K0 E) {a b : ℚ} (hab : a ≤ b) (ha : a ≤ 1) : + diskGap x x a b = b - a := gap_of_le hab (by simp) ha + +theorem gap_branch {x y : K0 E} {a b r : ℚ} (ha : r ≤ a) (hb : r ≤ b) + (h : val E (x - y) = ↑r) : diskGap x y a b = a + b - 2 * r := by + rw [diskGap, h, WithTop.untopD_coe, min_eq_right (le_min ha hb)] + +theorem MotionTree.same (H : MotionTree F E) (x y : Four (K0 E)) (l : Four ℚ) + (hl : ∀ i, l i ≤ 1) (hh : ∀ i, (l i : WithTop ℚ) ≤ val E (x i - y i)) : + H.rate x l ≤ H.rate y l := by + have h i : diskGap (x i) (y i) (l i) (l i) = 0 := by rw [gap_of_le le_rfl (hh i) (hl i), sub_self] + have h' i : diskGap (x i) (x i) (l i) (l i) = 0 := by rw [gap_same _ le_rfl (hl i), sub_self] + simpa using H.chord x y x l l l hl hl hl 1 zero_le_one le_rfl (by simp [h, h']) (by simp [h]) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/Tripod.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/Tripod.lean new file mode 100644 index 0000000000..b55e0a3926 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/Tripod.lean @@ -0,0 +1,579 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.Zoom +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldExtension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.TreePrice +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Face.Contact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.Rigidity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Arms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Energy + +/-! +# Parameters for private products + +First fix the power count to amortize the two index strings per private +output. Then take the rank slack small compared with the sparse saving. +Rounding up to a binary length and the fixed multiplicative constant +each consume at most one further rank slack. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +open Real Filter + +private theorem natpower (x : ℝ) (hx : 0 < x) (k : ℕ) : + x ^ k = exp (log x * k) := by rw [← rpow_natCast, rpow_def_of_pos hx] + +theorem private_at_rate {F : Type} [Field F] (h : SparseApprox F) + {x ε : ℝ} (he : 0 < ε) + (hrank : ∀ δ : ℝ, 0 < δ → ∀ n : ℕ, ∃ s j r : ℕ, n ≤ s ∧ + (s : ℝ) ^ (x + ε) ≤ j ∧ (r : ℝ) ≤ (s : ℝ) ^ (2 + δ) ∧ Rectangle.RankLE F s s j r) : + ∃ δ : ℝ, 0 < δ ∧ ∀ m : ℕ, ∃ s j r p : ℕ, m ≤ s ∧ 0 < r ∧ 0 < p ∧ + (s : ℝ) ^ (x + δ) * p ≤ j ∧ (r : ℝ) ≤ (s : ℝ) ^ (2 - δ) ∧ j ≤ s ^ 3 ∧ + Decodes F s j r p := by + obtain ⟨n, hn⟩ := exists_nat_gt (12 / ε) + obtain ⟨c, C, hc, hc', hC, happrox⟩ := h n + let k := (n : ℝ) + 1 + have hk : 1 ≤ k := by unfold k; simp + have hek : 12 ≤ k * ε := by unfold k; rw [div_lt_iff₀ he] at hn; linarith + let δ := min (ε / 2) (c / (4 * k)) + have hd : 0 < δ := lt_min (half_pos he) (by positivity) + have hd' : δ ≤ ε / 2 := min_le_left _ _ + have hdc : δ * (4 * k) ≤ c := (le_div_iff₀ (by positivity)).mp (min_le_right _ _) + have hd₁ : δ ≤ 1 / 4 := by nlinarith + have hcost : δ + (k - c) * (2 + 2 * δ) ≤ k * (2 - δ) := by nlinarith + have hshort : k * (x + δ) + 2 * (2 + 2 * δ) ≤ k * (x + ε) := by nlinarith + have hlog₂ : 0 < log 2 := by positivity + obtain ⟨S, hS⟩ := eventually_atTop.mp ((tendsto_log_atTop.comp tendsto_natCast_atTop_atTop) + |>.eventually_ge_atTop ((max (log C) (log 2)) / δ)) + refine ⟨δ, hd, fun m => ?_⟩ + obtain ⟨s, j, r, hs, hj, hr, hdec⟩ := hrank δ hd (max 2 (max S m)) + have hs' : 1 ≤ (s : ℝ) := by exact_mod_cast (show 1 ≤ s by omega) + have hs₀ : 0 < (s : ℝ) := zero_lt_one.trans_le hs' + let L := log s + have hL : 0 ≤ L := log_nonneg hs' + have hbig : max (log C) (log 2) ≤ L * δ := (div_le_iff₀ hd).mp (hS s (by omega)) + let b := ⌈L * (2 + δ) / log 2⌉₊ + have hb₁ : L * (2 + δ) ≤ b * log 2 := (div_le_iff₀ hlog₂).mp (Nat.le_ceil _) + have hb₂ : (b : ℝ) * log 2 ≤ L * (2 + 2 * δ) := by + have ht := Nat.ceil_lt_add_one (show 0 ≤ L * (2 + δ) / log 2 by positivity) + have ht' := mul_lt_mul_of_pos_right ht hlog₂ + rw [add_mul, div_mul_cancel₀ _ hlog₂.ne', one_mul] at ht' + exact ht'.le.trans (by linarith [le_max_right (log C) (log 2)]) + have hcap : (s : ℝ) ^ (2 + δ) ≤ (2 : ℝ) ^ b := by + rw [rpow_def_of_pos hs₀, natpower _ (by norm_num), exp_le_exp, mul_comm (log 2)] + exact hb₁ + have hsq : (s : ℝ) * s ≤ (s : ℝ) ^ (2 + δ) := by + rw [← pow_two, ← rpow_two] + exact rpow_le_rpow_of_exponent_le hs' (by linarith) + obtain ⟨t, ht, hbound, hdecode⟩ := happrox s j r b (by exact_mod_cast hr.trans hcap) + (by exact_mod_cast hsq.trans hcap) hdec + refine ⟨s ^ (n + 1), j ^ (n + 1), t, 2 ^ (2 * b), (show m + ≤ s by omega).trans (Nat.le_self_pow (by omega) _), + ht, by positivity, ?_, ?_, ?_, hdecode⟩ + · push_cast + apply le_trans _ (pow_le_pow_left₀ (by positivity) hj (n + 1)) + rw [← rpow_natCast_mul hs₀.le, ← rpow_mul_natCast hs₀.le, rpow_def_of_pos hs₀, + rpow_def_of_pos hs₀, natpower _ (by norm_num), ← exp_add, exp_le_exp] + push_cast + unfold L at hb₂ hL + unfold k at hshort + linarith only [hb₂, mul_le_mul_of_nonneg_left hshort hL] + · have hC' : C ≤ exp (L * δ) := le_exp_of_log_le ((le_max_left _ _).trans hbig) + refine hbound.trans ((mul_le_mul_of_nonneg_right hC' (by positivity)).trans ?_) + rw [Nat.cast_pow, ← rpow_natCast_mul hs₀.le, rpow_def_of_pos hs₀, + rpow_def_of_pos (by norm_num : (0 : ℝ) < 2), ← exp_add, exp_le_exp] + push_cast + have h₁ := mul_le_mul_of_nonneg_left hcost hL + have h₂ := mul_le_mul_of_nonneg_left hb₂ (by linarith : 0 ≤ k - c) + unfold k L at h₁ h₂ + unfold L + linarith only [h₁, h₂] + · have hpos : 0 < s := by omega + have harea := hdec.cycle.area hpos + have hj' : j ≤ r := le_trans (by simpa using Nat.mul_le_mul_right j hpos) harea + have hpow : (r : ℝ) ≤ (s : ℝ) ^ (3 : ℕ) := by + rw [← rpow_natCast] + exact hr.trans (rpow_le_rpow_of_exponent_le hs' (by norm_num; linarith)) + rw [← pow_mul, mul_comm (n + 1), pow_mul] + exact Nat.pow_le_pow_left (hj'.trans (by exact_mod_cast hpow)) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# Short output sums from a strict dual threshold + +A sparse row is evaluated by a short list of products specific to that +output. Each rank-one summand in the error matrix contributes just one +common bilinear form. The two within-pair wires pay for the short lists, +so the four-site obstruction does not need one private product per output. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +open Finset + +variable {F X Y I : Type} [Field F] [Fintype I] {s j p : ℕ} + +open scoped Classical in +private theorem pad_sum (L : I → X → F) (R : I → Y → F) (h : Fintype.card I ≤ p) : + ∃ (U : Fin p → X → F) (V : Fin p → Y → F), ∀ x y, + ∑ i, L i x * R i y = ∑ t, U t x * V t y := by + let e : Fin p ≃ I ⊕ Fin (p - Fintype.card I) := Fintype.equivOfCardEq (by simp; omega) + let u := Sum.elim L (fun _ : Fin (p - Fintype.card I) => 0) + let v := Sum.elim R (fun _ : Fin (p - Fintype.card I) => 0) + refine ⟨u ∘ e, v ∘ e, fun x y => ?_⟩ + simp only [Function.comp_apply] + rw [e.sum_comp (fun i => u i x * v i y), Fintype.sum_sum_type] + simp [u, v] + +open scoped Classical in +private theorem decode {R : ℝ} (M D : Matrix I I F) (hl : Low (M - D) R) + (hs : ∀ x, #{y | D x y ≠ 0} ≤ p) + (row : Out s → I) (u v : I → Leg s j → F) + (he : ∀ e x y, entry F e x y = ∑ t, M (row e) t * (u t x * v t y)) : + ∃ t : ℕ, 0 < t ∧ (t : ℝ) ≤ R + 1 ∧ Decodes F s j t p := by + let T (e : Out s) : Finset I := {t | D (row e) t ≠ 0} + have hshort (e : Out s) : + ∃ a b : Fin p → Leg s j → F, ∀ x y, ∑ t, D (row e) t * (u t x * v t y) = + ∑ l, a l x * b l y := by + obtain ⟨a, b, h⟩ := pad_sum (fun (t : T e) x => D (row e) t * u t x) (fun (t : T e) => v t) + (show Fintype.card ↥(T e) ≤ p by rw [Fintype.card_coe]; exact hs _) + refine ⟨a, b, fun x y => ?_⟩ + rw [← h x y] + simp_rw [mul_assoc] + rw [sum_coe_sort (T e) (fun t => D (row e) t * (u t x * v t y))] + symm + apply sum_subset (subset_univ _) + intro k _ hk + have hz : D (row e) k = 0 := by simpa [T] using hk + simp [hz] + choose a b hab using hshort + obtain ⟨J, _, hJ, L, U, hLU⟩ := hl + let E (t : J) (x : Leg s j × Leg s j) := ∑ l, U t l * (u l x.1 * v l x.2) + obtain ⟨c, d, hcd⟩ := pad_sum (fun t e => L (row e) t) E (Nat.le_succ _) + refine ⟨Fintype.card J + 1, by omega, by simpa using add_le_add_left hJ 1, a, b, + fun e t => c t e, fun t x y => d t (x, y), fun e x y => ?_⟩ + have eqn (t : I) : M (row e) t = D (row e) t + ∑ k, L (row e) k * U k t := by + have h := congrArg (fun P : Matrix I I F => P (row e) t) hLU + exact sub_eq_iff_eq_add'.mp h + rw [he, short, ← hab, ← hcd e (x, y)] + simp only [eqn, add_mul, sum_add_distrib, sum_mul, E, mul_sum, mul_assoc] + rw [sum_comm] + +open scoped Classical in +theorem sparseApprox (F : Type) [Field F] : SparseApprox F := by + intro n + obtain ⟨c, C, hc, hc', hC, h⟩ := sparse_power (F := F) n + refine ⟨c, C + 1, hc, hc', by linarith, fun s j r m hr hs hk => ?_⟩ + obtain ⟨M, row, u, v, he⟩ := padded_power n hr hs hk + obtain ⟨D, hl, hD⟩ := h m M + obtain ⟨t, ht, hbound, hdec⟩ := decode _ D hl hD row u v he + refine ⟨t, ht, hbound.trans ?_, hdec⟩ + rw [add_mul, one_mul] + exact add_le_add_right (Real.one_le_rpow (by norm_num) (mul_nonneg (by linarith) (by + positivity))) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +section +/- +# Private products below the harmonic threshold + +The rectangular upper bound at inner width one half suffices. +Approaching that width from below leaves room for the power and +sparsification overheads without a strict dual improvement. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +private theorem threshold_rank (F : Type) [Field F] {δ : ℝ} (hδ : 0 < δ) (n : ℕ) : + ∃ s j r : ℕ, n ≤ s ∧ (s : ℝ) ^ (1 / 2 : ℝ) ≤ j ∧ + (r : ℝ) ≤ (s : ℝ) ^ (2 + δ) ∧ Rectangle.RankLE F s s j r := by + have h := Rectangle.upper_of_diagonal (Rectangle.support F) (Rectangle.diagonal F) + zero_lt_one zero_lt_one (by norm_num : (0 : ℝ) < 1 / 2) + norm_num [Rectangle.U, Rectangle.benchmark] at h + obtain ⟨m, r, hm, hr, hs⟩ := + (Rectangle.exponent_lt_iff_rank zero_le_one zero_le_one (by norm_num : (0 : ℝ) ≤ 1 / 2)).mp + (h.trans_lt (lt_add_of_pos_right 2 hδ)) + rw [Rectangle.side_one] at hr + refine ⟨m ^ n, (Rectangle.side m (1 / 2)) ^ n, r ^ n, (Nat.lt_pow_self (by omega : 1 < m)).le, + Nat.ceil_le.mp (Rectangle.side_pow (le_rfl : Rectangle.side m (1 / 2) ≤ _) n), ?_, hr.pow n⟩ + rw [Nat.cast_pow, Nat.cast_pow, ← Real.rpow_natCast_mul (by positivity), + mul_comm (n : ℝ), Real.rpow_mul_natCast (by positivity)] + exact pow_le_pow_left₀ (by positivity) hs.le _ + +theorem weak_private (F : Type) [Field F] (ε : ℝ) (hε : 0 < ε) : + ∃ δ : ℝ, 0 < δ ∧ ∀ n : ℕ, ∃ s j r p : ℕ, n ≤ s ∧ 0 < r ∧ 0 < p ∧ + (s : ℝ) ^ (1 / 2 - ε) * p ≤ j ∧ (r : ℝ) ≤ (s : ℝ) ^ (2 - δ) ∧ j ≤ s ^ 3 ∧ Decodes F s j r p + := by + obtain ⟨δ, hd, h⟩ := private_at_rate (x := 1 / 2 - ε) (sparseApprox F) hε + (fun δ hδ n => by rw [sub_add_cancel]; exact threshold_rank F hδ n) + refine ⟨δ, hd, fun n => ?_⟩ + obtain ⟨s, j, r, p, hs, hr, hp, he, hb, hj, hdec⟩ := h (max 1 n) + have hs' : (1 : ℝ) ≤ s := by exact_mod_cast (le_max_left 1 n).trans hs + refine ⟨s, j, r, p, (le_max_right _ _).trans hs, hr, hp, ?_, hb, hj, hdec⟩ + exact (mul_le_mul_of_nonneg_right + (Real.rpow_le_rpow_of_exponent_le hs' (le_add_of_nonneg_right hd.le)) + (Nat.cast_nonneg _)).trans he + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# Contact on three fixed rays + +Apply the one-sided short-sum bound at the two moving sites. Its two +labels have identical wire distances. The universal harmonic lower +bound on one of them therefore gives an upper bound on the other. +Crucially the latter only uses the three stationary disk centers. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +open Spectral + +variable {F E X : Type} [Field F] [Field E] [PseudoMetricSpace X] + +/-- The value specified by `![i, 0, 1]`. -/ +def indices (i : Fin 4) : Fin 3 → Fin 4 := ![i, 0, 1] + +theorem label_eq (A : Atlas F X) (x : Fin 4 → X) (i : Fin 4) : + A.price x (label F i 2) = A.price (x ∘ indices i) 2 := by + rw [A.place] + have h : Tensor.place (indices i) (2 : Tensor F (Fin 3)) = label F i 2 := by + rw [← (show Tensor.shared F (Finset.univ : Finset (Fin 3)) 2 = 2 from Tensor.shared_all F 2), + Tensor.place_shared, show (Finset.univ : Finset (Fin 3)) = {0, 1, 2} by decide] + simp [indices, label] + simp only [Function.comp_apply, h] + +private theorem lower (A : Atlas F X) (x : Fin 3 → X) {a h : ℝ} (hh : 0 < h) (ha : h ≤ a) + (h₁ : dist (x 0) (x 1) = a) (h₂ : dist (x 0) (x 2) = a) (h₃ : dist (x 1) (x 2) = h) : + a + h / 4 ≤ A.price x 2 := by + let d := A.price x 2 + obtain ⟨D, hD⟩ := A.valid x + let u := a - h / 2 + let v := h / 2 + have hu : 0 < u := by unfold u; linarith + have hv : 0 < v := by unfold v; linarith + obtain ⟨hd, hp⟩ := Rectangle.prices_of_ordinary (x := u) (y := v) (z := v) hD + (by rw [A.wire, h₁]; unfold u v; ring) (by rw [A.wire, h₂]; unfold u v; ring) + (by rw [A.wire, h₃]; unfold v; ring) (by positivity) + have hb := Rectangle.diagonal F _ _ _ hp + change 0 < d at hd + change Rectangle.dStar (u / d) (v / d) (v / d) ≤ 1 at hb + have he : Rectangle.dStar (u / d) (v / d) (v / d) = (u + 2 * v - u * v / (2 * u + v)) / d := by + unfold Rectangle.dStar + field_simp + ring + rw [he, div_le_one hd] at hb + have hc : u * v / (2 * u + v) ≤ v / 2 := by + rw [div_le_iff₀ (by positivity)] + nlinarith only [sq_nonneg v] + have hh : a + h / 4 = u + 2 * v - v / 2 := by unfold u v; ring + rw [hh] + exact (sub_le_sub_left hc _).trans hb + +namespace K0.Leaves + +variable (M : Leaves F E X) (B : Branches E) + +/-- Evaluates `M.pt (B.pos (indices 2 i)) (if i = 0 then a else b)` at the input `i`. -/ +def tripodMarks (a b : ℚ) : Fin 3 → X := + fun i => M.pt (B.pos (indices 2 i)) (if i = 0 then a else b) + +theorem three_rays (ε : ℝ) (hε : 0 < ε) : + ∃ δ : ℝ, 0 < δ ∧ ∀ l h : ℚ, l ∈ Set.Ioc 0 (1 / 2) → h ∈ Set.Ioc 0 (2 * l) → + 7 * (h : ℝ) < 2 * l * δ → B.X M.tree l ≤ 3 / 2 + ε → + M.A.price (M.tripodMarks B (2 * l - h / 2) (h / 2)) 2 ≤ 2 * (l : ℝ) + (1 / 4 + 3 * ε) * h + := by + obtain ⟨δ, hδ, hpriv⟩ := weak_private F ε hε + refine ⟨δ, hδ, fun l h hl hh hgap hx => ?_⟩ + obtain ⟨z, h₀, h₁, h₂, hu⟩ := B.collision_point M.tree hl hh + let a := 2 * l - h / 2 + let b := h / 2 + have ha : 0 ≤ a := by unfold a; linarith [hl.1, hh.2] + have hb : 0 ≤ b := by unfold b; linarith [hh.1] + have ha' : a ≤ 1 := by unfold a; linarith [hl.2, hh.1] + have hb' : b ≤ 1 := by unfold b; linarith [hl.2, hh.2] + let x : Fin 4 → X := ![M.pt (B.pos 0) b, M.pt (B.pos 1) b, M.pt (B.pos 2) a, M.pt z a] + have he : (fun i => M.pt (B.pts z i) (Branches.depth 2 l (2 * l - h) i)) = x := by + funext i + fin_cases i <;> simp [Branches.pts, Branches.depth, x, a, b] <;> congr 1 <;> ring + change M.A.price _ 2 ≤ _ at hu + rw [he] at hu + have cross (t w : K0 E) (hw : val E (t - w) = 0) : dist (M.pt t b) (M.pt w a) = 2 * (l : ℝ) := by + rw [M.metric t w hb' ha', gap_branch hb ha hw] + simp [a, b] + have h₀₂ : dist (x 0) (x 2) = 2 * (l : ℝ) := cross _ _ (B.separate 0 2 (by decide)) + have h₁₂ : dist (x 1) (x 2) = 2 * (l : ℝ) := cross _ _ (B.separate 1 2 (by decide)) + have h₀₃ : dist (x 0) (x 3) = 2 * (l : ℝ) := cross _ _ h₀ + have h₁₃ : dist (x 1) (x 3) = 2 * (l : ℝ) := cross _ _ h₁ + have h₀₁ : dist (x 0) (x 1) = (h : ℝ) := by + change dist (M.pt _ b) (M.pt _ b) = _ + rw [M.metric _ _ hb' hb', gap_branch hb hb (B.separate 0 1 (by decide))] + congr 1 + unfold b; ring + have h₂₃ : dist (x 2) (x 3) = (h : ℝ) := by + change dist (M.pt _ a) (M.pt _ a) = _ + have hc : 2 * l - h ≤ a := by unfold a; linarith [hh.1] + rw [M.metric _ _ ha' ha', gap_branch hc hc h₂] + congr 1 + unfold a; ring + have hp : (0 : ℝ) < h := Rat.cast_pos.mpr hh.1 + have hle : (h : ℝ) ≤ 2 * l := by exact_mod_cast hh.2 + have lo (i : Fin 4) (h₀ : dist (x 0) (x i) = 2 * (l : ℝ)) + (h₁ : dist (x 1) (x i) = 2 * (l : ℝ)) : + 2 * (l : ℝ) + h / 4 ≤ M.A.price x (label F i 2) := by + rw [label_eq] + exact lower _ _ hp hle ((dist_comm _ _).trans h₀) ((dist_comm _ _).trans h₁) h₀₁ + have ha₂ := lo 2 h₀₂ h₁₂ + have ha₃ := lo 3 h₀₃ h₁₃ + obtain ⟨D, hD⟩ := M.A.valid x + have hr := one_rate hpriv hD ((M.A.wire x _ _).trans h₀₂) ((M.A.wire x _ _).trans h₀₁) + ((M.A.wire x _ _).trans h₂₃) (hp.le.trans hle) hp.le hgap (by linarith only [ha₂, ha₃, hp]) + rw [label_eq M.A x 2, show x ∘ indices 2 = M.tripodMarks B a b by + funext i; fin_cases i <;> rfl] at hr + change M.A.price (M.tripodMarks B a b) 2 ≤ _ + linarith only [hu, hr, ha₃, mul_le_mul_of_nonneg_left hx hp.le] + +end K0.Leaves +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# A common limit for all three rays + +Approximate real radii by rational ones before taking the limit. +Integer radii are represented exactly, so the collision bounds survive +at each of the integer lengths used to approach the reciprocal face. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Leaves + +open Filter +open scoped Topology + +variable {F E X : Type} [Field F] [Field E] [PseudoMetricSpace X] +variable (M : Leaves F E X) (B : Branches E) + +/-- The quantity computed by `n + 1`. -/ +def zoom (n : ℕ) : ℚ := n + 1 + +theorem zoom_pos (n : ℕ) : 0 < zoom n := by unfold zoom; positivity + +theorem zoom_pos' (n : ℕ) : (0 : ℝ) < zoom n := Rat.cast_pos.mpr (zoom_pos n) + +/-- The quantity computed by `⌊(zoom n : ℝ) * r⌋₊ / zoom n`. -/ +def approx (r : ℝ) (n : ℕ) : ℚ := ⌊(zoom n : ℝ) * r⌋₊ / zoom n + +private theorem approx_nat (i n : ℕ) : approx (i : ℝ) n = i := by + unfold approx + rw [show (zoom n : ℝ) * i = ((n + 1) * i : ℕ) by simp [zoom], Nat.floor_natCast] + push_cast + exact mul_div_cancel_left₀ _ (zoom_pos n).ne' + +private theorem approx_limit {r : ℝ} (hr : 0 ≤ r) : + Tendsto (fun n => (approx r n : ℝ)) atTop (𝓝 r) := by + have hl : Tendsto (fun n => r - 1 / (zoom n : ℝ)) atTop (𝓝 r) := by + simpa [zoom] using (tendsto_one_div_add_atTop_nhds_zero_nat (𝕜 := ℝ)).const_sub r + refine tendsto_of_tendsto_of_tendsto_of_le_of_le' hl tendsto_const_nhds + (Eventually.of_forall fun n => ?_) (Eventually.of_forall fun n => ?_) + · have h := Nat.lt_floor_add_one ((zoom n : ℝ) * r) + simp only [approx, Rat.cast_div, Rat.cast_natCast] + rw [le_div_iff₀ (zoom_pos' n), sub_mul, div_mul_cancel₀ _ (zoom_pos' n).ne'] + linarith + · simp only [approx, Rat.cast_div, Rat.cast_natCast] + rw [div_le_iff₀ (zoom_pos' n), mul_comm r] + exact Nat.floor_le (mul_nonneg (zoom_pos' n).le hr) + +private theorem approx_fits (x : Rectangle.Twig) : + ∀ᶠ n in atTop, approx x.radius n / zoom n ∈ Set.Icc 0 1 := by + have h : Tendsto (fun n => (zoom n : ℝ)) atTop atTop := by + simpa [zoom] using (tendsto_natCast_atTop_atTop (R := ℝ)).atTop_add tendsto_const_nhds + filter_upwards [h.eventually_ge_atTop (x.radius + 1), + (approx_limit x.radius_nonneg).eventually_le_const (lt_add_one _)] with n hn hh + have hf := zoom_pos n + exact ⟨by unfold approx; positivity, (div_le_one hf).mpr (Rat.cast_le.mp (hh.trans hn))⟩ + +/-- The quantity computed by `M.pt (B.pos (indices 2 x.arm)) (approx x.radius n / zoom n)`. -/ +def toRay (n : ℕ) (x : Rectangle.Twig) := + M.pt (B.pos (indices 2 x.arm)) (approx x.radius n / zoom n) + +private theorem ray_limit (a b : Rectangle.Twig) : + Tendsto (fun n => (zoom n : ℝ) * dist (M.toRay B n a) (M.toRay B n b)) atTop (𝓝 (dist a b)) + := by + have ha := approx_limit a.radius_nonneg + have hb := approx_limit b.radius_nonneg + rw [Rectangle.Twig.dist_eq] + by_cases h : a.arm = b.arm + · rw [ite_eq_left h] + refine (ha.sub hb).abs.congr' ?_ + filter_upwards [approx_fits a, approx_fits b] with n hn hm + unfold toRay + rw [h, M.metric _ _ hn.2 hm.2] + have eq (z : K0 E) (t s : ℚ) (ht : t ≤ 1) (hs : s ≤ 1) : diskGap z z t s = |t - s| := by + rcases le_total t s with h|h + · rw [gap_same _ h ht, abs_of_nonpos (sub_nonpos.mpr h), neg_sub] + · rw [gap_symm, gap_same _ h hs, abs_of_nonneg (sub_nonneg.mpr h)] + rw [eq _ _ _ hn.2 hm.2, ← sub_div, abs_div, abs_of_pos (zoom_pos n)] + push_cast + rw [mul_div_cancel₀ _ (zoom_pos' n).ne'] + · rw [ite_eq_right h] + refine (ha.add hb).congr' ?_ + filter_upwards [approx_fits a, approx_fits b] with n hn hm + have hi : Function.Injective (indices 2) := by decide + unfold toRay + rw [M.metric _ _ hn.2 hm.2, gap_branch hn.1 hm.1 (B.separate _ _ (hi.ne h)), + mul_zero, sub_zero, ← add_div] + push_cast + rw [mul_div_cancel₀ _ (zoom_pos' n).ne'] + +theorem ray_integer (i n : ℕ) : + M.toRay B n ∘ Rectangle.Twig.mark ![(i : ℝ), 1, 1] = + M.tripodMarks B (i / zoom n) (1 / zoom n) := by + have he : approx 1 n = 1 := by simpa using approx_nat 1 n + funext j + fin_cases j <;> simp [toRay, tripodMarks, Rectangle.Twig.mark, Rectangle.Twig.radius, + approx_nat, he] + +/-- The same atlas works for every integer length. -/ +theorem ray_atlas : ∃ A : Atlas F Rectangle.Twig, Rectangle.Twig.Homogeneous A ∧ + ∀ (i : ℕ) (v : ℝ), + (∀ᶠ n in atTop, (zoom n : ℝ) * M.A.price (M.tripodMarks B (i / zoom n) (1 / zoom n)) 2 ≤ v) → + Rectangle.Twig.label A ![(i : ℝ), 1, 1] ≤ v := by + let l := Ultrafilter.of (atTop : Filter ℕ) + have hl : (l : Filter ℕ) ≤ atTop := Ultrafilter.of_le _ + obtain ⟨A, hA⟩ := Atlas.scaled_limit l (fun _ => X) (fun _ => M.A) (M.toRay B) + (fun n => zoom n) (fun n => (zoom_pos' n).le) (fun a b => (M.ray_limit B a b).mono_left hl) + obtain ⟨Q, hQ, hQA⟩ := Rectangle.Twig.tangent A + refine ⟨Q, hQ, fun i v h => (hQA _ _).trans (le_of_tendsto (hA _ _) ?_)⟩ + filter_upwards [h.filter_mono hl] with n hn + rw [← M.ray_integer B] at hn + exact hn + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Leaves +end + +/- +# A moving family forces contact at infinity + +For each large integer `i`, shrink collision placements with fixed +ratio of radii `i : 1 : 1`. The short-output estimate bounds the +three-terminal diagonal at all these ratios on one homogeneous +tripod. This gives a zero of the defect on the reciprocal face. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Leaves + +open Filter +open scoped Topology +variable {F E X : Type} [Field F] [Field E] [PseudoMetricSpace X] +variable (M : Leaves F E X) (B : Branches E) + +private theorem estimate (ε : ℝ) (hε : 0 < ε) : + ∀ᶠ i : ℕ in atTop, ∀ᶠ n : ℕ in atTop, + (zoom n : ℝ) * M.A.price (M.tripodMarks B (i / zoom n) (1 / zoom n)) 2 ≤ i + 3 / 2 + 6 * ε + := by + obtain ⟨δ, hδ, ht⟩ := M.three_rays B ε hε + obtain ⟨L, hL, hg⟩ := B.small_X M.tree hε + filter_upwards [eventually_ge_atTop 1, (tendsto_natCast_atTop_atTop (R := ℝ)).eventually_gt_atTop + (14 / δ)] with i hi hi' + have hi'' : (14 : ℝ) < (i + 1) * δ := by + rw [div_lt_iff₀ hδ] at hi' + linarith only [hi', hδ] + let scale := ((i : ℚ) + 1) / (2 * L) + obtain ⟨k, hk⟩ := exists_nat_ge scale + filter_upwards [eventually_ge_atTop k] with n hn + let l := ((i : ℚ) + 1) / (2 * zoom n) + let h := 2 / zoom n + have hz := zoom_pos n + have hz' := zoom_pos' n + have he : l ≤ L := by + have hkn : (k : ℚ) ≤ zoom n := by unfold zoom; exact_mod_cast (show k ≤ n + 1 by omega) + have hs : (i : ℚ) + 1 ≤ zoom n * (2 * L) := + (div_le_iff₀ (mul_pos (by norm_num) hL.1)).mp (hk.trans hkn) + unfold l + rw [div_le_iff₀ (by positivity)] + linarith only [hs] + have hl : l ∈ Set.Ioc 0 (1 / 2) := ⟨by unfold l; positivity, he.trans hL.2⟩ + have hh : h ∈ Set.Ioc 0 (2 * l) := by + have hq : (1 : ℚ) ≤ i := by exact_mod_cast hi + refine ⟨by unfold h; positivity, ?_⟩ + unfold l h + field_simp + linarith + have hm : B.X M.tree l ≤ 3 / 2 + ε := + (B.monotone_X M.tree ⟨hl.1, by linarith [hl.2]⟩ ⟨hL.1, by linarith [hL.2]⟩ he).trans hg + have hgap : 7 * (h : ℝ) < 2 * l * δ := by + unfold h l + push_cast + field_simp + linarith only [hi''] + have hc := ht l h hl hh hgap hm + rw [show 2 * l - h / 2 = (i : ℚ) / zoom n by unfold h l; ring, + show h / 2 = 1 / zoom n by unfold h; ring] at hc + refine (mul_le_mul_of_nonneg_left hc hz'.le).trans_eq ?_ + unfold h l + push_cast + field_simp + ring + +private theorem zero_of_integer {D : Rectangle.Minimum.Vec → ℝ} (h : Rectangle.StarTripod F D) + (hu : ∀ ε : ℝ, 0 < ε → ∀ᶠ n : ℕ in atTop, D ![(n : ℝ), 1, 1] ≤ n + 3 / 2 + ε) : + Rectangle.Face.limit D 1 1 = 0 := by + have ht := Rectangle.Face.tends h zero_lt_one zero_lt_one + have hp : 0 ≤ Rectangle.Face.limit D 1 1 := by + apply ge_of_tendsto ht + filter_upwards [self_mem_nhdsWithin] with r hr + exact h.toTripod.regular.nonneg _ (Rectangle.Face.positive hr zero_lt_one zero_lt_one) + apply le_antisymm _ hp + have hr : Tendsto (fun n : ℕ => (n : ℝ)⁻¹) atTop (𝓝[>] 0) := by + refine tendsto_nhdsWithin_iff.mpr ⟨?_, ?_⟩ + · exact tendsto_inv_atTop_zero.comp tendsto_natCast_atTop_atTop + · filter_upwards [eventually_gt_atTop 0] with n hn + change 0 < (n : ℝ)⁻¹ + positivity + refine le_of_forall_pos_le_add fun ε hε => le_of_tendsto (ht.comp hr) ?_ + filter_upwards [hu ε hε] with n hn + change Rectangle.defect D ![(n : ℝ)⁻¹, 1, 1] ≤ _ + have he : (![(n : ℝ)⁻¹, 1, 1] : Rectangle.Minimum.Vec)⁻¹ = ![(n : ℝ), 1, 1] := by + ext i + fin_cases i <;> simp + rw [Rectangle.defect, he] + simp only [Fin.sum_univ_three, Matrix.cons_val_zero, Matrix.cons_val_one, Matrix.cons_val_two, + Matrix.head_cons, Matrix.tail_cons, inv_one, inv_inv, zero_add] + have h₀ : 0 ≤ (n : ℝ)⁻¹ := by positivity + have h₁ : ((n : ℝ)⁻¹ + 1 + 1)⁻¹ ≤ (2 : ℝ)⁻¹ := inv_anti₀ (by positivity) (by linarith) + linarith only [hn, h₁] + +theorem tripod [Infinite E] (M : Leaves F E X) : + ∃ A : Atlas F Rectangle.Twig, Rectangle.Twig.Homogeneous A ∧ + Rectangle.Face.limit (Rectangle.Twig.label A) 1 1 = 0 := by + let B := Classical.arbitrary (Branches E) + obtain ⟨A, hA, h⟩ := M.ray_atlas B + refine ⟨A, hA, zero_of_integer hA.star (fun ε hε => ?_)⟩ + filter_upwards [M.estimate B (ε / 6) (by positivity)] with n hn + exact (h n _ hn).trans_eq (by ring) + +theorem contact [Infinite F] [Infinite E] (M : Leaves F E X) : + omega F = 9 / 4 ∧ Rectangle.Rigidity F := by + obtain ⟨A, h, hz⟩ := M.tripod + exact ⟨h.star.square_of_limit h.uniform hz, h.star.rigidity_of_limit h.uniform hz⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0.Leaves +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/Zoom.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/Zoom.lean new file mode 100644 index 0000000000..928e9adc36 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Motion/Zoom.lean @@ -0,0 +1,488 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.TreePrice +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.FourArms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Span +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space + +/-! # Realizing the leaf distances as limits of translated points -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 + +open Filter +open scoped Topology + +/-- The data for the dilation construction, including `e`, `origin`, `r`, `factor`, `pos`. -/ +structure Dilation where + /-- The `Dilation` component of type `ℕ → ℚ`. -/ + e : ℕ → ℚ + /-- The starting coordinate of type `ℕ → ℚ`. -/ + origin : ℕ → ℚ + /-- The `Dilation` field of type `ℝ`. -/ + r : ℝ + /-- The multiplicative factor of type `ℕ → ℝ`. -/ + factor : ℕ → ℝ + pos : ∀ n, 0 < e n + pos_r : 0 < r + pos_factor : ∀ n, 0 < factor n + he : Tendsto (fun n => (e n : ℝ)) atTop (𝓝 0) + ht : Tendsto (fun n => (origin n : ℝ)) atTop (𝓝 r) + +variable {E X : Type*} [Field E] + +/-- Computes the index by the application `zoom (D.e n) (D.origin n) (D.pos n) z`. -/ +def Dilation.index (D : Dilation) (n : ℕ) (z : K0 E) : K0 E := + zoom (D.e n) (D.origin n) (D.pos n) z + +@[simp] theorem Dilation.index_sub (D : Dilation) (n : ℕ) (z w : K0 E) : + D.index n (z - w) = D.index n z - D.index n w := by simp [index, zoom, mul_sub] + +theorem Dilation.positive (D : Dilation) (z : K0 E) : + ∀ᶠ n in atTop, 0 < val E (D.index n z) := zoom_pos D.pos_r D.pos D.he D.ht z + +variable [MetricSpace X] [MulAction (G E) X] [IsIsometricSMul (G E) X] + +/-- The value specified by `shift (D.index n z) • A`. -/ +def Dilation.point (D : Dilation) (A : X) (n : ℕ) (z : K0 E) : X := shift (D.index n z) • A + +theorem RadialStars.leaves [CompleteSpace X] (h : RadialStars E X) (C : Routing.Comparison X) + {M : ℝ} (hM : ∀ x y : X, dist x y ≤ M) (o : X) + (hm : ∃ a : ℝ, 0 < a ∧ o ∉ fixed (level E a)) + (hs : ∀ ε : ℝ, 0 < ε → ∃ b, 0 < b ∧ profile E o b < ε) : + ∃ (A : X) (D : Dilation), + (∀ φ : X → X, Isometry φ → φ o = o → + Set.MapsTo φ (fixed (level E D.r)) (fixed (level E D.r)) → φ A = A) ∧ + ∀ z w : K0 E, Tendsto (fun n => D.factor n * dist (D.point A n z) (D.point A n w)) + atTop (𝓝 (diskDist (leaf z) (leaf w) : ℝ)) := by + obtain ⟨r, A, k, hr, hk, _, hfix, hh⟩ := + motion_scale C (level E) (level_anti.antitoneOn _) hM (h.secants hM) o hm hs + obtain ⟨e, t₀, he, he0, ht, hlim⟩ := hh.zoom hk + let D : Dilation := ⟨e, t₀, r, fun n => 2 / (k * e n), he, hr, + fun n => div_pos (by norm_num) (mul_pos hk (Rat.cast_pos.mpr (he n))), he0, ht⟩ + refine ⟨A, D, hfix, fun z w => ?_⟩ + by_cases hz : z = w + · subst w + simp + obtain ⟨s, hv⟩ := WithTop.ne_top_iff_exists.mp ((val E).ne_top_iff.mpr (sub_ne_zero.mpr hz)) + rw [leaf_dist hv.symm, Rat.cast_mul, Rat.cast_max, Rat.cast_sub, Rat.cast_zero, + Rat.cast_one, Rat.cast_ofNat] + refine zoom_leaf (R := profile E A) hr (fun n => (D.pos_factor n).le) he he0 ht hlim s _ ?_ + filter_upwards [D.positive z, D.positive w, D.positive (z - w)] with n hn hm hd + have hval : val E (D.index n (z - w)) = ↑(t₀ n + e n * s) := val_zoom _ _ _ hv.symm + have hq : 0 < t₀ n + e n * s := WithTop.coe_pos.mp (hval ▸ hd) + have hshift : shift (D.index n z) = shift (D.index n w) * shift (D.index n (z - w)) := by + rw [← shift_add hm hd, D.index_sub, add_sub_cancel] + unfold Dilation.point + rw [hshift, mul_smul, dist_smul, dist_comm] + exact ⟨dist_nonneg, cost_le hq hval.ge hM, fun _ ha hb => h.star hM A ha hb hval⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion.K0 +end + +/- +# Sparse products with a common error space + +Each output of a rectangular multiplication uses private simple +products and a linear combination of common bilinear forms. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +open Spectral Finset + +open scoped Classical in +/-- Indexes the out by the coordinates of `Fin s × Fin s`. -/ +abbrev Out (s : ℕ) := Fin s × Fin s +open scoped Classical in +/-- Indexes the leg by the coordinates of `Fin s × Fin j`. -/ +abbrev Leg (s j : ℕ) := Fin s × Fin j + +variable {s j r p : ℕ} + +open scoped Classical in +/-- Returns `1` when `(x.1, y.1) = e ∧ x.2 = y.2` holds, and `0` otherwise. -/ +def entry (F : Type) [Field F] (e : Out s) (x y : Leg s j) : F := + if (x.1, y.1) = e ∧ x.2 = y.2 then 1 else 0 + +open scoped Classical in +/-- The sum of `u e t x * v e t y` indexed by `t`. -/ +def short (F : Type) [Field F] (u v : Out s → Fin p → Leg s j → F) (e : Out s) (x y : Leg s j) := + ∑ t, u e t x * v e t y + +open scoped Classical in +/-- The decodes of type `Prop` for the given inputs. -/ +def Decodes (F : Type) [Field F] (s j r p : ℕ) : Prop := + ∃ (u v : Out s → Fin p → Leg s j → F) (c : Out s → Fin r → F) + (b : Fin r → Leg s j → Leg s j → F), + ∀ e x y, entry F e x y = short F u v e x y + ∑ t, c e t * b t x y + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +/-- Sparse private products and shared error coordinates from a finite rank formula. -/ +def SparseApprox (F : Type) [Field F] : Prop := + ∀ n : ℕ, ∃ c C : ℝ, 0 < c ∧ c ≤ 1 ∧ 0 ≤ C ∧ ∀ s j r b : ℕ, + r ≤ 2 ^ b → s * s ≤ 2 ^ b → Rectangle.RankLE F s s j r → + ∃ t : ℕ, 0 < t ∧ (t : ℝ) ≤ C * (2 : ℝ) ^ (((n : ℝ) + 1 - c) * b) ∧ + Decodes F (s ^ (n + 1)) (j ^ (n + 1)) t (2 ^ (2 * b)) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# Binary padding of rectangular tensor powers + +Use zero for every unused column of the common factor matrix. The same +matrix on each register acts independently on each digit of every +matrix-product index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +open Finset + +variable {F : Type} [Field F] {s j r m : ℕ} + +open Classical in +private theorem padded (hr : r ≤ 2 ^ m) (hs : s * s ≤ 2 ^ m) (h : Rectangle.RankLE F s s j r) : + ∃ (M : Matrix (Bits m) (Bits m) F) (row : Out s → Bits m) + (u v : Bits m → Leg s j → F), ∀ e x y, + entry F e x y = ∑ t, M (row e) t * (u t x * v t y) := by + obtain ⟨a, b, c, h⟩ := h + let row : Out s ↪ Bits m := Classical.choice (Function.Embedding.nonempty_of_card_le (by simpa + [Out, Bits] using hs)) + let col : Fin r ↪ Bits m := Classical.choice (Function.Embedding.nonempty_of_card_le (by simpa + [Bits] using hr)) + let pad (z : Fin r → F) := Function.extend col z (fun _ => 0) + let M := Function.extend row (fun e => pad (fun t => c t e)) (fun _ _ => 0) + refine ⟨M, row, fun t x => pad (fun i => a i x) t, fun t y => pad (fun i => b i y.swap) t, + fun e x y => ?_⟩ + unfold M + rw [row.injective.extend_apply] + let f (t : Bits m) := pad (fun i => c i e) t * + (pad (fun i => a i x) t * pad (fun i => b i y.swap) t) + change entry F e x y = ∑ t, f t + calc + _ = ∑ i, a i x * b i y.swap * c i e := by + rw [h] + simp [entry, Prod.ext_iff, and_assoc, and_comm] + _ = ∑ t ∈ univ.image col, f t := by + rw [sum_image col.injective.injOn] + simp only [f, pad, col.injective.extend_apply, mul_comm] + _ = _ := by + apply sum_subset (subset_univ _) + intro t _ ht + have hn : ¬ ∃ i, col i = t := by simpa using ht + simp [f, pad, Function.extend, hn] + +open Classical in +private def digit (s k : ℕ) : Fin (s ^ k) ≃ (Fin k → Fin s) := + Fintype.equivOfCardEq (by simp) + +open Classical in +private def split {k : ℕ} (x : Leg (s ^ k) (j ^ k)) (i : Fin k) : Leg s j := + (digit s k x.1 i, digit j k x.2 i) + +open Classical in +private theorem entry_prod {k : ℕ} (e : Out (s ^ k)) (x y : Leg (s ^ k) (j ^ k)) : + entry F e x y = ∏ i, entry F (split e i) (split x i) (split y i) := by + unfold entry + by_cases h : (x.1, y.1) = e ∧ x.2 = y.2 + · obtain ⟨rfl, he⟩ := h + simp [split, he] + · rw [ite_eq_right h] + have hn : ∃ i, ¬ (((split x i).1, (split y i).1) = split e i ∧ + (split x i).2 = (split y i).2) := by + by_contra! h' + apply h + refine ⟨Prod.ext ?_ ?_, (digit j k).injective (funext fun i => (h' i).2)⟩ + · exact (digit s k).injective (funext fun i => congrArg Prod.fst (h' i).1) + · exact (digit s k).injective (funext fun i => congrArg Prod.snd (h' i).1) + obtain ⟨i, hi⟩ := hn + exact (prod_eq_zero (mem_univ i) (ite_eq_right hi)).symm + +open Classical in +theorem padded_power (n : ℕ) (hr : r ≤ 2 ^ m) (hs : s * s ≤ 2 ^ m) + (h : Rectangle.RankLE F s s j r) : + ∃ (M : Matrix (Bits m) (Bits m) F) (row : Out (s ^ (n + 1)) → Registers n m) + (u v : Registers n m → Leg (s ^ (n + 1)) (j ^ (n + 1)) → F), ∀ e x y, + entry F e x y = ∑ t, (matPower (fun _ : Fin (n + 1) => M)) (row e) t * (u t x * v t y) := by + obtain ⟨M, row, u, v, he⟩ := padded hr hs h + refine ⟨M, fun e i => row (split e i), fun t x => ∏ i, u (t i) (split x i), + fun t y => ∏ i, v (t i) (split y i), fun e x y => ?_⟩ + rw [entry_prod] + simp only [he, Fintype.prod_sum, prod_mul_distrib, matPower] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- +# One-sided short output sums + +Duplicate the output at sites 0 and 1 while the inputs are on 2 and 3. +The resulting tensor contains two overlapping three-site labels and +an inner wire. The error space is transmitted only once across the cut. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +open Spectral Finset + +variable {F : Type} [Field F] {s j r p : ℕ} + +open scoped Classical in +/-- Indexes the both by the coordinates of `Out s × Fin j`. -/ +abbrev Both (s j : ℕ) := Out s × Fin j + +open scoped Classical in +private def left (x : Both s j) : Leg s j := (x.1.1, x.2) +open scoped Classical in +private def right (x : Both s j) : Leg s j := (x.1.2, x.2) + +open scoped Classical in +private def oneSide (A : Out s → Leg s j → Leg s j → F) (x : Fin 4 → Both s j) := + if (x 0).1 = (x 1).1 then A (x 0).1 (left (x 2)) (right (x 3)) else 0 + +open scoped Classical in +/-- The value specified by `Tensor.shared F {i, 0, 1} n`. -/ +def label (F : Type) [Field F] (i : Fin 4) (n : ℕ) : Tensor F (Fin 4) := + Tensor.shared F {i, 0, 1} n +local notation "wire" => Tensor.wire (S := Fin 4) F + +open scoped Classical in +private theorem oneSide_lower [NeZero s] [NeZero j] : + label F 2 s * label F 3 s * wire 2 3 j ≤ + Tensor.array (oneSide (s := s) (j := j) (entry F)) := by + let a := Raw.port (n := s) ({2, 0, 1} : Finset (Fin 4)) + let b := Raw.port (n := s) ({3, 0, 1} : Finset (Fin 4)) + let c := Raw.port (n := j) ({2, 3} : Finset (Fin 4)) + let g (i : Fin 4) (t : Both s j) : Both s j := ((a i t.1.1, b i t.1.2), c i t.2) + have hg : Tensor.signals F g = label F 2 s * label F 3 s * wire 2 3 j := by + rw [show Tensor.signals F g = _ from + Tensor.signals_mul (fun i (t : Out s) => (a i t.1, b i t.2)) c, Tensor.signals_mul a b] + rfl + rw [← hg] + let P := Raw.ofTable (fun _ : Fin 4 => Both s j) (oneSide (entry F)) + let v (i : Fin 4) (t : Both s j) : F := if t = g i t then 1 else 0 + let L (i : Fin 4) (x y : Both s j) := if y = x then v i x else 0 + refine ⟨L, fun x => ?_⟩ + change Fin 4 → Both s j at x + change (∑ t : Both s j, ∏ i, if x i = g i t then (1 : F) else 0) = + ∑ t : P.term, ∏ i, ∑ y : Both s j, (if y = x i then v i (x i) else 0) * P.factor t i y + have hv (t : P.term) (i : Fin 4) : + (∑ y : Both s j, (if y = x i then v i (x i) else 0) * P.factor t i y) = + v i (x i) * P.factor t i (x i) := by + rw [Fintype.sum_eq_single (x i)] + · simp + · intro y h; simp [h] + simp only [hv, prod_mul_distrib, ← mul_sum] + rw [show (∑ t : P.term, ∏ i, P.factor t i (x i)) = _ from Raw.coeff_ofTable _ _ x] + rw [Fintype.sum_eq_single ((x 0).1, (x 2).2)] + · simp [oneSide, entry, left, right, v, g, a, b, c, Raw.port, Fin.prod_univ_four, Prod.ext_iff] + grind + · intro t ht + by_cases he : x 0 = g 0 t + · apply prod_eq_zero (mem_univ 2) + refine ite_eq_right fun h => ht (Prod.ext ?_ ?_) + · simpa [g, a, b, Raw.port] using (congrArg Prod.fst he).symm + · simpa [g, c, Raw.port] using (congrArg Prod.snd h).symm + · exact prod_eq_zero (mem_univ 0) (ite_eq_right he) + +open scoped Classical in +private theorem short_le (u v : Out s → Fin p → Leg s j → F) : + Tensor.array (oneSide (short F u v)) ≤ ((s * s : ℕ) : Tensor F (Fin 4)) * wire 2 3 p := by + let g (i : Fin 4) (y : Both s p) : Both s p := (y.1, Raw.port {2, 3} i y.2) + have hg : Tensor.signals F g = ((s * s : ℕ) : Tensor F (Fin 4)) * wire 2 3 p := by + rw [show Tensor.signals F g = _ from + Tensor.signals_mul (fun (_ : Fin 4) (e : Out s) => e) (Raw.port (n := p) {2, 3})] + change Tensor.ofRaw (Raw.diag F (Fin 4) (Out s)) * _ = _ + rw [Tensor.diag_eq_natCast, Fintype.card_prod, Fintype.card_fin] + rfl + rw [← hg] + let M (i : Fin 4) (x : Both s j) (y : Both s p) : F := + ![if x.1 = y.1 then 1 else 0, if x.1 = y.1 then 1 else 0, + u y.1 y.2 (left x), v y.1 y.2 (right x)] i + refine ⟨M, fun x => ?_⟩ + change Fin 4 → Both s j at x + rw [Raw.coeff_ofTable] + change oneSide _ _ = ∑ t : Both s p, ∏ i, ∑ y : Both s p, + M i (x i) y * if y = g i t then 1 else 0 + have delta (i) (t : Both s p) : + (∑ y : Both s p, M i (x i) y * if y = g i t then 1 else 0) = M i (x i) (g i t) := by + rw [Fintype.sum_eq_single (g i t)] + · simp + · intro y hy; simp [hy] + simp_rw [delta, Fin.prod_univ_four] + rw [Fintype.sum_prod_type, Fintype.sum_eq_single (x 0).1] + · by_cases h : (x 1).1 = (x 0).1 + · simp [oneSide, short, g, Raw.port, M, h] + · simp [oneSide, g, M, h, Ne.symm h] + · intro e he + simp [g, M, Ne.symm he] + +open scoped Classical in +theorem Decodes.one_side (h : Decodes F s j r p) (hs : 0 < s) (hj : 0 < j) : + label F 2 s * label F 3 s * wire 2 3 j ≤ + ((s * s : ℕ) : Tensor F (Fin 4)) * wire 2 3 p + + wire 0 2 r * wire 0 1 (s * s * j) * wire 2 3 (s * s * j) := by + have : NeZero s := ⟨hs.ne'⟩ + have : NeZero j := ⟨hj.ne'⟩ + obtain ⟨u, v, c, b, he⟩ := h + let L t (x : Fin 4 → Both s j) := if (x 0).1 = (x 1).1 then c (x 0).1 t else 0 + let R t (x : Fin 4 → Both s j) := b t (left (x 2)) (right (x 3)) + let err x := ∑ t, L t x * R t x + let g (i : Fin 4) : Fin 4 := if i.val < 2 then 0 else 2 + let E := Raw.ofTable (fun _ => Both s j) err + have hcut : Tensor.place g (Tensor.ofRaw E) ≤ wire 0 2 r := by + have h := Tensor.separated_le (fun _ => Both s j) err (fun i => i.val < 2) L R + (fun _ => rfl) (fun t x y h => by unfold L; rw [h 0 (by decide), h 1 (by decide)]) + (fun t x y h => by unfold R; rw [h 2 (by decide), h 3 (by decide)]) (0 : Fin 4) 2 + rwa [Fintype.card_fin] at h + have hg := Tensor.transport E g id + rw [Tensor.place_id, Fin.prod_univ_four] at hg + have hc (i : Fin 4) : Fintype.card (E.leg i) = s * s * j + := by change Fintype.card (Both s j) = _; simp + simp only [Fin.isValue, hc, show g 0 = 0 from rfl, show g 1 = 0 from rfl, + show g 2 = 2 from rfl, show g 3 = 2 from rfl, + id_eq, Tensor.wire_self F _ (by positivity : 0 < s * s * j), one_mul, mul_one] at hg + have herr : Tensor.array err ≤ wire 0 2 r * wire 0 1 (s * s * j) * wire 2 3 (s * s * j) := by + rw [mul_assoc] + apply hg.trans + rw [mul_comm (Tensor.place _ _), mul_comm (wire 0 2 r)] + exact Tensor.mul_le_mul_left _ _ _ hcut + refine oneSide_lower.trans ?_ + rw [show oneSide (entry F) = fun x => oneSide (short F u v) x + err x by + funext x + by_cases h : (x 0).1 = (x 1).1 <;> simp [oneSide, L, R, err, h, he]] + refine (Tensor.array_sum _ _).trans ((Tensor.add_le_add_right _ _ _ (short_le u v)).trans ?_) + rw [add_comm _ (Tensor.array err), add_comm _ (wire 0 2 r * wire 0 1 (s * s * j) * wire 2 3 (s * + s * j))] + exact Tensor.add_le_add_right _ _ _ herr + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end + +/- The one-sided test bounds the sum of two three-terminal label rates. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion + +open Spectral +variable {F : Type} [Field F] {a h ε δ : ℝ} +local notation "wire" => Tensor.wire (S := Fin 4) F + +private theorem label_rate (f : Tensor F (Fin 4) →+* ℝ) (hf : Monotone f) (i : Fin 4) + {n : ℕ} (hn : 0 < n) : + f (label F i n) = (n : ℝ) ^ Tensor.values 1 f (label F i 2) := by + have hm : Monotone (label F i) := fun _ _ h => Tensor.shared_mono F {i, 0, 1} (by simp) h + have hu (s : ℕ) (hs : 0 < s) : 1 ≤ f (label F i s) ∧ f (label F i s) ≤ (s : ℝ) := by + constructor + · simpa [label, Tensor.shared_one] using hf (hm hs) + · have he := Tensor.shared_subset F (Finset.subset_univ ({i, 0, 1} : Finset (Fin 4))) s + rw [Tensor.shared_all] at he + simpa [label] using hf he + obtain ⟨p, _, _, he⟩ := TensorSpectrum.exists_power_of_monotone_multiplicative (fun n + => f (label F i n)) + (fun _ _ _ _ => (congrArg f (Tensor.shared_mul F _ _ _)).trans (f.map_mul _ _)) + (fun _ _ _ h => hf (hm h)) hu + have hp : Tensor.values 1 f (label F i 2) = p := by + rw [Tensor.values, one_mul, he 2 (by decide), Nat.cast_ofNat, Real.log_rpow (by norm_num), + mul_div_cancel_right₀ _ (Real.log_pos (by norm_num : (1 : ℝ) < 2)).ne'] + rw [hp, he n hn] + +private theorem logs {L R E : ℝ} (hl : 0 < L) (hr : 0 < R) (he : 0 < E) (h : L ≤ R + E) : + Real.log L ≤ Real.log 2 + Real.log R ∨ Real.log L ≤ Real.log 2 + Real.log E := by + rcases le_total E R with h' | h' + · left + rw [← Real.log_mul (by norm_num) hr.ne'] + exact Real.log_le_log hl (by linarith) + · right + rw [← Real.log_mul (by norm_num) he.ne'] + exact Real.log_le_log hl (by linarith) + +private theorem finite_cost {s j r p : ℕ} (hs : 0 < s) (hj : 0 < j) (hr : 0 < r) (hp : 0 < p) + (H : Decodes F s j r p) {D : ℝ} {P : Tensor F (Fin 4) → ℝ} + (hP : P ∈ Tensor.ordinary F (Fin 4) D) (ha : P (wire 0 2 2) = a) + (hh : P (wire 0 1 2) = h) (hh' : P (wire 2 3 2) = h) : + let L := (P (label F 2 2) + P (label F 3 2)) * Real.log s + h * Real.log j + L ≤ P 2 * (Real.log 2 + 2 * Real.log s) + h * Real.log p ∨ + L ≤ P 2 * Real.log 2 + a * Real.log r + 2 * h * (2 * Real.log s + Real.log j) := by + obtain ⟨d, hd, f, hf, rfl⟩ := hP + have ht := hf (H.one_side hs hj) + rw [f.map_add, f.map_mul, f.map_mul, f.map_mul, f.map_mul, f.map_mul, map_natCast f] at ht + simp only [label_rate f hf _ hs, Tensor.price_wire f hf _ _ hj, + Tensor.price_wire f hf _ _ hp, Tensor.price_wire f hf _ _ hr, + Tensor.price_wire f hf _ _ (by positivity : 0 < s * s * j), Nat.cast_mul] at ht + have he := logs (by positivity) (by positivity) (by positivity) ht + simp (disch := positivity) only [Real.log_mul, Real.log_rpow] at he + have htwo : Tensor.values d f 2 = d := by + rw [Tensor.values, map_ofNat, div_self (Real.log_pos (by norm_num)).ne', mul_one] + change d * Tensor.dist f 0 2 = a at ha + change d * Tensor.dist f 0 1 = h at hh + change d * Tensor.dist f 2 3 = h at hh' + have hm (i : Fin 4) : d * Tensor.values 1 f (label F i 2) = Tensor.values d f (label F i 2) := by + simp [Tensor.values] + dsimp only + rw [htwo] + rcases he with he | he + all_goals + have he' := mul_le_mul_of_nonneg_left he hd.1 + simp only [mul_add, ← mul_assoc, hm, ha, hh, hh'] at he' + · exact .inl (by linarith only [he']) + · exact .inr (by linarith only [he']) + +theorem one_rate + (H : ∀ n : ℕ, ∃ s j r p : ℕ, n ≤ s ∧ 0 < r ∧ 0 < p ∧ (s : ℝ) ^ (1 / 2 - ε) * p ≤ j ∧ + (r : ℝ) ≤ (s : ℝ) ^ (2 - δ) ∧ j ≤ s ^ 3 ∧ Decodes F s j r p) + {D : ℝ} {P : Tensor F (Fin 4) → ℝ} (hP : P ∈ Tensor.ordinary F (Fin 4) D) + (ha : P (wire 0 2 2) = a) (hh : P (wire 0 1 2) = h) (hh' : P (wire 2 3 2) = h) + (ha' : 0 ≤ a) (hh₀ : 0 ≤ h) (hgap : 7 * h < a * δ) + (hlo : 2 * a ≤ P (label F 2 2) + P (label F 3 2)) : + P (label F 2 2) + P (label F 3 2) + (1 / 2 - ε) * h ≤ 2 * P 2 := by + by_contra! bad + let L := P (label F 2 2) + P (label F 3 2) + (1 / 2 - ε) * h - 2 * P 2 + have h₁ : 0 < L := sub_pos.mpr bad + have h₂ := sub_pos.mpr hgap + let B := P 2 * Real.log 2 + let M := max (B / L) (B / (a * δ - 7 * h)) + obtain ⟨n, hn⟩ := exists_nat_gt (Real.exp M) + obtain ⟨s, j, r, p, hs, hr, hp, hj, hr', hc, hd⟩ := H n + have hm := hn.trans_le (Nat.cast_le.mpr hs : (n : ℝ) ≤ s) + have hs' := (Real.exp_pos M).trans hm + have he : 0 < (s : ℝ) ^ (1 / 2 - ε) * p := by positivity + have hj' := he.trans_le hj + have hl := (Real.lt_log_iff_exp_lt hs').mpr hm + have hL := (div_lt_iff₀ h₁).mp ((le_max_left _ _).trans_lt hl) + have hR := (div_lt_iff₀ h₂).mp ((le_max_right _ _).trans_lt hl) + rcases finite_cost (Nat.cast_pos.mp hs') (Nat.cast_pos.mp hj') hr hp hd hP ha hh hh' with h | h + · have hv := Real.log_le_log he hj + rw [Real.log_mul (by positivity) (by positivity), Real.log_rpow hs'] at hv + unfold L B at hL + linarith only [h, hL, mul_le_mul_of_nonneg_left hv hh₀] + · have ht := Real.log_le_log (Nat.cast_pos.mpr hr) hr' + have hu := Real.log_le_log hj' (show (j : ℝ) ≤ (s : ℝ) ^ 3 by exact_mod_cast hc) + rw [Real.log_pow, Nat.cast_ofNat] at hu + rw [Real.log_rpow hs'] at ht + unfold B at hR + linarith only [h, hR, mul_le_mul_of_nonneg_left hu hh₀, mul_le_mul_of_nonneg_left ht ha', + mul_le_mul_of_nonneg_right hlo (show 0 ≤ Real.log (s : ℝ) by positivity)] + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.Motion +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/MovingForms.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/MovingForms.lean new file mode 100644 index 0000000000..150d684083 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/MovingForms.lean @@ -0,0 +1,921 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.WireRecovery +public import Mathlib.Algebra.BigOperators.Field +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Sync +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryJets + +/-! +# A center for prescribed widths + +Minimize a smoothed transport cost over ordinary one-site extensions. +Pointwise compactness gives a minimizer. The tangent inequality for +square root makes the same extension minimize a weighted variance. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Center +open Real Spectral Finset + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + +/-- Indexes the extended by the coordinates of `Tensor F (A ⊕ Unit)`. -/ +abbrev Extended (F A : Type) [Field F] [Fintype A] := Tensor F (A ⊕ Unit) + +/-- Computes the radius by the application `Tensor.dist g (.inl i) (.inr ())`. -/ +def radius (g : Extended F A →+* ℝ) (i : A) := Tensor.dist g (.inl i) (.inr ()) + +private theorem minimize (f : Tensor F A →+* ℝ) (hf : Monotone f) (a : A → ℝ) (τ : ℝ) : + ∃ g : Extended F A →+* ℝ, Monotone g ∧ (∀ T, g (Tensor.pad Unit T) = f T) ∧ + ∀ h : Extended F A →+* ℝ, Monotone h → (∀ T, h (Tensor.pad Unit T) = f T) → + (∑ i, a i * sqrt (radius g i ^ 2 + τ ^ 2)) ≤ ∑ i, a i * sqrt (radius h i ^ 2 + τ ^ 2) := by + let T := Extended F A + let S : Set (T → ℝ) := + {v | ∃ g : T →+* ℝ, Monotone g ∧ (∀ t, g (Tensor.pad Unit t) = f t) ∧ ⇑g = v} + have closed : IsClosed S := by + have eq : S = {v | v 0 = 0 ∧ v 1 = 1 ∧ (∀ x y, v (x + y) = v x + v y) ∧ + (∀ x y, v (x * y) = v x * v y) ∧ Monotone v ∧ (∀ t, v (Tensor.pad Unit t) = f t)} := by + ext v + constructor + · rintro ⟨g, hg, he, rfl⟩ + exact ⟨g.map_zero, g.map_one, g.map_add, g.map_mul, hg, he⟩ + · rintro ⟨h₀, h₁, ha, hm, hg, he⟩ + exact ⟨{toFun := v, map_zero' := h₀, map_one' := h₁, map_add' := ha, map_mul' := hm}, + hg, he, rfl⟩ + rw [eq] + simp only [Set.ofPred_and, Set.ofPred_forall] + refine (isClosed_eq (continuous_apply 0) continuous_const).inter <| + (isClosed_eq (continuous_apply 1) continuous_const).inter <| + IsClosed.inter ?_ (IsClosed.inter ?_ (isClosed_monotone.inter ?_)) + · exact isClosed_iInter fun _ => isClosed_iInter fun _ + => isClosed_eq (by fun_prop) (by fun_prop) + · exact isClosed_iInter fun _ => isClosed_iInter fun _ + => isClosed_eq (by fun_prop) (by fun_prop) + · exact isClosed_iInter fun _ => isClosed_eq (by fun_prop) continuous_const + have comp : IsCompact S := by + choose N hN using fun t : T => Tensor.exists_bound t + have hc : IsCompact {v : T → ℝ | ∀ t, v t ∈ Set.Icc 0 (N t : ℝ)} := + isCompact_pi_infinite fun _ => isCompact_Icc + refine hc.of_isClosed_subset closed ?_ + rintro v ⟨g, hg, _, rfl⟩ t + exact ⟨by simpa using hg (Tensor.zero_le t), by simpa using hg (hN t)⟩ + have ne : S.Nonempty := by + let y (_ : Unit) := Classical.arbitrary A + exact ⟨_, f.comp (Tensor.foldSites y), hf.comp (Tensor.foldSites_mono y), + fun t => congrArg f (Tensor.foldSites_pad y t), rfl⟩ + let wire (i : A) : T := Tensor.wire F (.inl i) (.inr ()) 2 + let J (v : T → ℝ) := ∑ i, a i * sqrt ((log (max 1 (v (wire i))) / log 2) ^ 2 + τ ^ 2) + have cont : Continuous J := by + apply continuous_finsetSum + intro i _ + have h : Continuous (fun v : T → ℝ => max 1 (v (wire i))) := by fun_prop + have hl := h.log (fun _ => (zero_lt_one.trans_le (le_max_left _ _)).ne') + exact continuous_const.mul (((hl.div_const _).pow 2).add continuous_const).sqrt + have eval (g : T →+* ℝ) (hg : Monotone g) : J g = ∑ i, a i * sqrt (radius g i ^ 2 + τ ^ 2) := by + apply sum_congr rfl + intro i _ + have hw : 1 ≤ g (wire i) := by + simpa using hg (Tensor.one_le_wire F (.inl i) (.inr ()) (by decide : 0 < 2)) + rw [max_eq_right hw] + rfl + obtain ⟨_, ⟨g, hg, he, rfl⟩, hm⟩ := comp.exists_isMinOn ne cont.continuousOn + refine ⟨g, hg, he, fun h hh he' => ?_⟩ + rw [← eval g hg, ← eval h hh] + exact hm ⟨h, hh, he', rfl⟩ + +private def smooth (τ d : ℝ) := sqrt (d ^ 2 + τ ^ 2) + +private theorem smooth_sq (τ d : ℝ) : smooth τ d ^ 2 = d ^ 2 + τ ^ 2 := sq_sqrt (by positivity) + +private theorem smooth_bounds {τ d : ℝ} (ht : 0 < τ) (ht' : τ ≤ 1) (hd : 0 ≤ d) (hd' : d ≤ 1) : + τ ≤ smooth τ d ∧ smooth τ d ≤ 2 ∧ d + τ ^ 2 / 3 ≤ smooth τ d := by + have hs : 0 ≤ smooth τ d := sqrt_nonneg _ + have h := smooth_sq τ d + have hu : smooth τ d ≤ 2 := by nlinarith + have hl : d ≤ smooth τ d := by nlinarith + refine ⟨by nlinarith, hu, ?_⟩ + nlinarith [mul_nonneg (sub_nonneg.mpr hl) (show 0 ≤ 3 - (smooth τ d + d) by linarith)] + +private theorem tangent {a τ d μ : ℝ} (hp : 0 < μ) (hμ : a * μ ^ 2 = smooth τ d) (x : ℝ) : + 2 * (a * smooth τ x - a * smooth τ d) ≤ (x / μ) ^ 2 - (d / μ) ^ 2 := by + rw [div_pow, div_pow, ← sub_div, le_div_iff₀ (sq_pos_of_pos hp)] + have he : 2 * (a * smooth τ x - a * smooth τ d) * μ ^ 2 = + 2 * smooth τ d * (smooth τ x - smooth τ d) := by rw [← hμ]; ring + rw [he] + nlinarith only [sq_nonneg (smooth τ x - smooth τ d), smooth_sq τ x, smooth_sq τ d] + +private theorem lower {a τ d μ : ℝ} (hp : 0 < μ) (hμ : a * μ ^ 2 = smooth τ d) + (ht : 0 < τ) (ht' : τ ≤ 1) (hd : 0 ≤ d) (hd' : d ≤ 1) : + a * d - τ * a ≤ (d / μ) ^ 2 := by + obtain ⟨h₁, _, h₂⟩ := smooth_bounds ht ht' hd hd' + have hs : d ≤ smooth τ d := by nlinarith + rw [div_pow, le_div_iff₀ (sq_pos_of_pos hp)] + have he : (a * d - τ * a) * μ ^ 2 = (d - τ) * smooth τ d := by rw [← hμ]; ring + rw [he] + nlinarith only [smooth_sq τ d, mul_le_mul_of_nonneg_left h₁ ht.le, + mul_le_mul_of_nonneg_right hs (ht.le.trans h₁)] + +/-- A common positive compact range of weights works for every +ordinary spectral point. -/ +theorem choose_weights (a : A → ℝ) (ha : ∀ i, 0 < a i) {τ : ℝ} (ht : 0 < τ) (ht' : τ ≤ 1) : + ∃ l U : ℝ, 0 < l ∧ 0 < U ∧ ∀ f : Tensor F A →+* ℝ, Monotone f → + ∃ g : Extended F A →+* ℝ, Monotone g ∧ (∀ t, g (Tensor.pad Unit t) = f t) ∧ + ∃ μ : A → ℝ, (∀ i, l ≤ μ i ∧ μ i ≤ U) ∧ + (∀ i, radius g i + τ ^ 2 / 3 ≤ a i * μ i ^ 2) ∧ + (∑ i, a i * radius g i) - τ * (∑ i, a i) ≤ ∑ i, (radius g i / μ i) ^ 2 ∧ + ∀ h : Extended F A →+* ℝ, Monotone h → (∀ t, h (Tensor.pad Unit t) = f t) → + (∑ i, (radius g i / μ i) ^ 2) ≤ ∑ i, (radius h i / μ i) ^ 2 := by + obtain ⟨j, _, hj⟩ := univ.exists_min_image a univ_nonempty + obtain ⟨k, _, hk⟩ := univ.exists_max_image a univ_nonempty + refine ⟨sqrt (τ / a k), sqrt (2 / a j), sqrt_pos.mpr (div_pos ht (ha k)), + sqrt_pos.mpr (div_pos (by norm_num) (ha j)), fun f hf => ?_⟩ + obtain ⟨g, hg, he, hm⟩ := minimize f hf a τ + let d := radius g + have h₀ (i : A) : 0 ≤ d i := Tensor.dist_nonneg g hg _ _ + have h₁ (i : A) : d i ≤ 1 := Tensor.dist_le_one g hg _ _ + have hs (i : A) := smooth_bounds ht ht' (h₀ i) (h₁ i) + let μ (i : A) := sqrt (smooth τ (d i) / a i) + have hp (i : A) : 0 < smooth τ (d i) / a i := div_pos (ht.trans_le (hs i).1) (ha i) + have hμ (i : A) : a i * μ i ^ 2 = smooth τ (d i) := by + unfold μ + rw [sq_sqrt (hp i).le, mul_div_cancel₀ _ (ha i).ne'] + refine ⟨g, hg, he, μ, fun i => ?_, fun i => ?_, ?_, fun h hh he' => ?_⟩ + · constructor + · exact sqrt_le_sqrt (div_le_div₀ (ht.le.trans (hs i).1) (hs i).1 (ha i) (hk i (mem_univ i))) + · exact sqrt_le_sqrt (div_le_div₀ (by norm_num) (hs i).2.1 (ha j) (hj i (mem_univ i))) + · rw [hμ] + exact (hs i).2.2 + · rw [mul_sum, ← sum_sub_distrib] + exact sum_le_sum fun i _ => lower (sqrt_pos.mpr (hp i)) (hμ i) ht ht' (h₀ i) (h₁ i) + · have hi := sum_le_sum (fun i (_ : i ∈ univ) => + tangent (sqrt_pos.mpr (hp i)) (hμ i) (radius h i)) + rw [← mul_sum, sum_sub_distrib, sum_sub_distrib] at hi + have hmin : (∑ i, a i * smooth τ (d i)) ≤ ∑ i, a i * smooth τ (radius h i) := hm h hh he' + exact sub_nonneg.mp ((mul_nonneg (by norm_num) (sub_nonneg.mpr hmin)).trans hi) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Center +end + +/- +# Weighted quadratic budgets + +A transport bound implies coercivity, hence a maximizing nonzero form at +every positive scale. The normalized deficit dominates the sum of squared +distances of the rescaled widths from their targets. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Budget +open Sphere Spectral Filter Finset + +variable {A F : Type} [Fintype A] [Field F] + +/-- The quantity computed by `p e - (∑ i, (μ i * Routing.width (e i)) ^ 2) / (2 * n)`. -/ +def value (p : (A → ℕ) → ℝ) (μ : A → ℝ) (n : ℕ) (e : A → ℕ) : ℝ := + p e - (∑ i, (μ i * Routing.width (e i)) ^ 2) / (2 * n) + +variable {p : (A → ℕ) → ℝ} {μ r : A → ℝ} + +theorem normalize (n : ℕ) (e : A → ℕ) : + value p μ n e / n = p e / n - (∑ i, (μ i * Routing.width (e i) / n) ^ 2) / 2 := by + unfold value + simp only [div_pow, ← sum_div] + ring + +theorem increment (e : A → ℕ) (n : ℕ) (hn : 0 < n) : + (∑ i, (μ i * Routing.width (e i) / n) ^ 2) * ((n : ℝ) / (n + 1)) = + 2 * (value p μ (n + 1) e - value p μ n e) := by + simp only [value, div_pow, ← sum_div, Nat.cast_add, Nat.cast_one] + have : (n : ℝ) ≠ 0 := by positivity + field_simp + ring + +variable (ht : ∀ e, p e ≤ ∑ i, r i * (μ i * Routing.width (e i))) +include ht + +theorem squares (n : ℕ) (e : A → ℕ) : + 2 * (value p μ n e / n) + ∑ i, (μ i * Routing.width (e i) / n - r i) ^ 2 ≤ ∑ i, r i ^ 2 := by + rw [normalize] + have hb : p e / n ≤ ∑ i, r i * (μ i * Routing.width (e i) / n) := by + simp only [← mul_div_assoc, ← sum_div] + exact div_le_div_of_nonneg_right (ht e) (by positivity) + have he : (∑ i, (μ i * Routing.width (e i) / n - r i) ^ 2) = + (∑ i, (μ i * Routing.width (e i) / n) ^ 2) - + 2 * (∑ i, r i * (μ i * Routing.width (e i) / n)) + ∑ i, r i ^ 2 := by + rw [mul_sum, ← sum_sub_distrib, ← sum_add_distrib] + apply sum_congr rfl + intro i _ + ring + linarith only [he, hb] + +variable {D l : ℝ} (hD : ∑ i, r i ^ 2 ≤ D) (hl : 0 < l) (hμ : ∀ i, l ≤ μ i) +include hD hl hμ + +theorem bounds (n : ℕ) (hn : 0 < n) (e : A → ℕ) (he : 0 ≤ value p μ n e) (i : A) : + μ i * Routing.width (e i) / n ≤ 2 * (D + 1) ∧ + (e i : ℝ) ≤ (4 * (D + 1) / (l * entropy) ^ 2) * (n : ℝ) ^ 2 := by + have hs := (squares ht n e).trans hD + have hp : 0 ≤ value p μ n e / n := div_nonneg he (by positivity) + have hd := (single_le_sum (fun j (_ : j ∈ univ) => sq_nonneg (r j)) (mem_univ i)).trans hD + have hw := single_le_sum (fun j (_ : j ∈ univ) => sq_nonneg (μ j * Routing.width (e j) / n - r j)) + (mem_univ i) + have hb : (μ i * Routing.width (e i) / (n : ℝ)) ^ 2 ≤ 4 * D := by + nlinarith only [hs, hp, hd, hw, sq_nonneg (μ i * Routing.width (e i) / n - 2 * r i)] + constructor + · nlinarith only [hb, sq_nonneg (μ i * Routing.width (e i) / n - 1)] + · rw [div_pow, mul_pow, width_sq, div_le_iff₀ (by positivity)] at hb + rw [div_mul_eq_mul_div, le_div_iff₀ (sq_pos_of_pos (mul_pos hl entropy_pos))] + have h := mul_le_mul_of_nonneg_right (pow_le_pow_left₀ hl.le (hμ i) 2) + (show 0 ≤ entropy ^ 2 * (e i : ℝ) by positivity) + nlinarith only [hb, h, sq_nonneg (n : ℝ)] + +theorem maximizer (z : A → F) (hp : 0 ≤ p (fun _ => 0)) + (hzero : ∀ e, sphereForm z e = 0 → p e = 0) (n : ℕ) : + ∃ e : A → ℕ, 0 < n → 0 ≤ value p μ n e ∧ sphereForm z e ≠ 0 ∧ + ∀ a, value p μ n a ≤ value p μ n e := by + by_cases hn : 0 < n + swap + · exact ⟨fun _ => 0, fun hh => (hn hh).elim⟩ + let N := ⌊(4 * (D + 1) / (l * entropy) ^ 2) * (n : ℝ) ^ 2⌋₊ + let S := {e | 0 ≤ value p μ n e ∧ sphereForm z e ≠ 0} + have hS : S.Finite := by + apply (Set.Finite.pi' (fun _ : A => Set.finite_Iic N)).subset + exact fun e he i => Nat.le_floor (bounds ht hD hl hμ n hn e he.1 i).2 + have he : S.Nonempty := by + refine ⟨fun _ => 0, ?_, sphereForm_vacuum z⟩ + simpa [value, Routing.width] using hp + obtain ⟨e, ⟨hpos, hne⟩, hmax⟩ := S.exists_max_image (value p μ n) hS he + refine ⟨e, fun _ => ⟨hpos, hne, fun a => ?_⟩⟩ + by_cases ha : 0 ≤ value p μ n a + swap + · exact (le_of_not_ge ha).trans hpos + by_cases hz : sphereForm z a = 0 + · refine le_trans ?_ hpos + rw [value, hzero a hz, zero_sub, neg_nonpos] + exact div_nonneg (sum_nonneg (fun _ _ => sq_nonneg _)) (by positivity) + · exact hmax _ ⟨ha, hz⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Budget +end + +/- +# Distance tests from a synchronized extension and wire recovery + +Use the same extended price for all site probes. A cubic energy cutoff +absorbs the bounded quadratic optimizer budgets. The logarithm of the +polynomial overhead in the recovered wire is then logarithmic in the +optimizer scale. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Sphere Spectral Real Filter Finset + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + {Y : Type*} [MetricSpace Y] + +theorem probe_cost (R : ℝ) (hR : 0 < R) {n a q : ℕ} (hn : 1 ≤ (n : ℝ)) + (ha : (a : ℝ) ≤ R * n ^ 2) (hq : q ≤ n) : + Sphere.width q a ≤ (sqrt R + 2) ^ 2 * (n : ℝ) ^ 2 ∧ + entropy ^ 2 * (Sphere.width q a + q - a) ≤ + 2 * width a * width q + entropy ^ 2 * (sqrt R + 3) * n := by + have hnq : (q : ℝ) ≤ n := by exact_mod_cast hq + have hs : sqrt (a : ℝ) ≤ sqrt R * n := + sqrt_le_iff.mpr ⟨by positivity, by rwa [mul_pow, sq_sqrt hR.le]⟩ + have ht : sqrt (q : ℝ) ≤ (n : ℝ) := sqrt_le_iff.mpr ⟨by positivity, by nlinarith⟩ + have hh := pow_le_pow_left₀ (show 0 ≤ sqrt (q : ℝ) + sqrt (a : ℝ) + 1 by positivity) + (show sqrt (q : ℝ) + sqrt (a : ℝ) + 1 ≤ (sqrt R + 2) * n by linarith) 2 + unfold Sphere.width + constructor + · nlinarith only [hh, sqrt_nonneg q, sqrt_nonneg a] + · have hk : (sqrt q + sqrt a) ^ 2 + (sqrt q + sqrt a) + q - a ≤ + 2 * sqrt a * sqrt q + (sqrt R + 3) * n := by + nlinarith only [sq_sqrt (Nat.cast_nonneg q), sq_sqrt (Nat.cast_nonneg a), hnq, hs, ht] + unfold width + linarith only [mul_le_mul_of_nonneg_left hk (sq_nonneg entropy)] + +omit [DecidableEq A] in +private theorem value_pos {f : Tensor F A →+* ℝ} (hf : Monotone f) {z : A → F} {e : A → ℕ} + (he : sphereForm z e ≠ 0) : 0 < f (sphereTensor z e) := by + refine zero_lt_one.trans_le (Tensor.value_one_le hf ?_) + intro ht + apply he + funext v + simpa using (Tensor.ofRaw_eq_zero _).mp ht v + +omit [DecidableEq A] in +private theorem objective_eq (f : Tensor F A →+* ℝ) (d : ℝ) (z : A → F) (n : ℕ) (e : A → ℕ) : + objective (Tensor.values d f) z n e = + d * log (f (sphereTensor z e)) - entropy ^ 2 / (2 * n) * ∑ i, (e i : ℝ) := by + simp only [objective, spherePrice, tablePrice, Tensor.values, width_sq, ← mul_sum] + rw [mul_assoc, div_mul_cancel₀ _ (log_pos (by norm_num : (1 : ℝ) < 2)).ne'] + unfold sphereTensor + ring + +omit [Nonempty A] in +private theorem sum_added (t : A ⊕ Unit → ℝ) (e : A → ℕ) (i : A) (h q : ℕ) : + ∑ j : A ⊕ Unit, t j * ((Sum.elim (Function.update e i h) (fun _ => q) j : ℕ) : ℝ) = + (∑ j, t (.inl j) * (e j : ℝ)) - t (.inl i) * e i + t (.inl i) * h + t (.inr ()) * q := by + rw [Fintype.sum_sum_type] + simp only [Sum.elim_inl, Sum.elim_inr, Fintype.sum_unique] + rw [← sum_erase_add _ _ (mem_univ i), ← sum_erase_add _ (fun j + => t (.inl j) * (e j : ℝ)) (mem_univ i)] + have he : ∑ j ∈ univ.erase i, t (.inl j) * ((Function.update e i h j : ℕ) : ℝ) + = ∑ j ∈ univ.erase i, t (.inl j) * (e j : ℝ) := + sum_congr rfl (fun j hj => by rw [Function.update_of_ne (mem_erase.mp hj).1]) + rw [he, Function.update_self, add_sub_cancel_right] + +theorem probe_log (hW : WireProbe F) {f : Tensor F A →+* ℝ} (hf : Monotone f) + {g : Tensor F (A ⊕ Unit) →+* ℝ} (hg : Monotone g) (hgf : ∀ T, g (Tensor.pad Unit T) = f T) + {z : A → F} (hz : Function.Injective z) (B : ℝ) (t : A ⊕ Unit → ℝ) (ht : ∀ i, 0 ≤ t i) (M : ℕ) + (hg' : ∀ s ∉ Set.range z, ∀ e : A ⊕ Unit → ℕ, (∀ j, e j ≤ M) → + g (sphereTensor (Sum.elim z (fun _ => s)) e) ≤ + ((M : ℝ) + 2) ^ (Fintype.card A + 8) * exp (B + ∑ j, t j * (e j : ℝ))) + (e : A → ℕ) (he : sphereForm z e ≠ 0) (i : A) (q : ℕ) + (hA : Fintype.card A ≤ M) (heM : ∀ j, e j ≤ M) + (hH : ⌊Sphere.width q (e i)⌋₊ ≤ M) (hq : q ≤ M) (hq' : 0 < Fintype.card (Level 1 q)) : + log (f (sphereTensor z e)) + Tensor.dist g (.inl i) (.inr ()) * log (Fintype.card (Level 1 q)) ≤ + (Fintype.card A + 12) * log (M + 2) + B + ((∑ j, t (.inl j) * (e j : ℝ)) - t (.inl i) * e i + + t (.inl i) * Sphere.width q (e i) + t (.inr ()) * q) := by + let H := ⌊Sphere.width q (e i)⌋₊ + let p := (M : ℝ) + 2 + let b := B + ((∑ j, t (.inl j) * (e j : ℝ)) - t (.inl i) * e i + + t (.inl i) * Sphere.width q (e i) + t (.inr ()) * q) + let D := Fintype.card A + 8 + have hp : 0 < p := by unfold p; positivity + obtain ⟨T, hT, hcard, hw⟩ := hW A z hz e i q + have hTC : (T.card : ℝ) ≤ p ^ 3 := by + have hs : (∑ j, e j) ≤ M * M := calc + _ ≤ Fintype.card A * M := by simpa using sum_le_card_nsmul univ e M (fun j _ => heM j) + _ ≤ M * M := Nat.mul_le_mul_right M hA + have hc : T.card ≤ (M + 2) ^ 3 := calc + _ ≤ 1 + M * (M * M + M + M) := hcard.trans (by gcongr) + _ ≤ _ := by ring_nf; omega + unfold p + exact_mod_cast hc + let X (h : ℕ) (s : F) : Tensor F (A ⊕ Unit) := sphereTensor (Sum.elim z (fun _ => s)) + (Sum.elim (Function.update e i h) (fun _ => q)) + have hs (h : ℕ) (hh : h ∈ range (H + 1)) (s : F) (hs : s ∈ T) : g (X h s) ≤ p ^ D * exp b := by + have hle := Nat.le_of_lt_succ (mem_range.mp hh) + have hle' : (h : ℝ) ≤ Sphere.width q (e i) := + (Nat.cast_le.mpr hle).trans (Nat.floor_le (by unfold Sphere.width; positivity)) + apply (hg' s (hT s hs) _ ?_).trans + · rw [sum_added] + unfold p D b + gcongr + exact ht _ + · rintro (j | _) + · change Function.update e i h j ≤ M + by_cases hji : j = i + · simpa [hji] using hle.trans hH + · simpa [hji] using heM j + · exact hq + have hh : (H : ℝ) + 1 ≤ p := by unfold p; exact_mod_cast (show H + 1 ≤ M + 2 by omega) + have hw' : f (sphereTensor z e) * (Fintype.card (Level 1 q) : ℝ) ^ Tensor.dist g (.inl i) (.inr + ()) ≤ + p ^ (D + 4) * exp b := by + calc + _ ≤ ∑ h ∈ range (H + 1), ∑ s ∈ T, g (X h s) := by + have hb := hg hw + rw [g.map_mul, hgf, Tensor.price_wire g hg _ _ hq'] at hb + simpa only [map_sum] using hb + _ ≤ ∑ _ ∈ range (H + 1), ∑ _ ∈ T, p ^ D * exp b := + sum_le_sum (fun h hh => sum_le_sum (hs h hh)) + _ = ((H : ℝ) + 1) * (T.card * (p ^ D * exp b)) := by simp + _ ≤ p * (p ^ 3 * (p ^ D * exp b)) := by gcongr + _ = _ := by rw [pow_add]; ring + have h₁ := value_pos hf he + have h₂ : (0 : ℝ) < Fintype.card (Level 1 q) := by exact_mod_cast hq' + have h := log_le_log (by positivity) hw' + rw [log_mul (by positivity) (by positivity), log_rpow h₂, log_mul (by positivity) (by positivity), + log_pow, log_exp] at h + unfold p D b at h + push_cast at h + linarith only [h] + +theorem probe_window (R : ℝ) (k : ℕ) : + ∀ᶠ n : ℕ in atTop, 1 ≤ (n : ℝ) ∧ 1 ≤ log n ∧ ∃ M : ℕ, n ≤ M ∧ k ≤ M ∧ + (sqrt R + 2) ^ 2 * (n : ℝ) ^ 2 ≤ M ∧ log ((M : ℝ) + 2) ≤ 4 * log n := by + filter_upwards [eventually_ge_atTop (k), eventually_ge_atTop 2, + tendsto_natCast_atTop_atTop.eventually_ge_atTop ((sqrt R + 2) ^ 2), + (tendsto_log_atTop.comp tendsto_natCast_atTop_atTop).eventually_ge_atTop 1] + with n hnA hn₂ hnR hnlog + have hn : 0 < (n : ℝ) := by positivity + have hn' : 2 ≤ (n : ℝ) := by exact_mod_cast hn₂ + let M := n ^ 3 + have hnM : n ≤ M := Nat.le_self_pow (by decide) _ + have hcap : (sqrt R + 2) ^ 2 * (n : ℝ) ^ 2 ≤ M := by + unfold M + push_cast + nlinarith only [mul_le_mul_of_nonneg_right hnR (sq_nonneg (n : ℝ))] + have hlog : log ((M : ℝ) + 2) ≤ 4 * log n := by + have h : (M : ℝ) + 2 ≤ (n : ℝ) ^ 4 := by + have := (Nat.cast_le (α := ℝ)).mpr hnM + unfold M at this ⊢ + push_cast at this ⊢ + nlinarith only [mul_le_mul_of_nonneg_right hn' (pow_nonneg hn.le 3), hn', this] + simpa using log_le_log (by positivity) h + exact ⟨by linarith, hnlog, M, hnM, hnA.trans hnM, hcap, hlog⟩ + +theorem controlled_of_probes (hV : VarianceTest F Y) (hE : BoundedExtension F) + (hW : WireProbe F) (hS : SpectralSpace F Y) : Controlled F Y := by + intro A _ _ _ x o ho z hz + by_cases hzero : (∑ i, dist o (x i) ^ 2) ≤ 0 + · obtain ⟨P, _, hp⟩ := hS A x + refine ⟨P, hp, fun _ _ => ⟨0, ?_⟩⟩ + filter_upwards with n + intro e _ _ _ + refine ⟨fun _ => 0, fun _ => le_rfl, by simpa using hzero, fun i g _ => ?_⟩ + simp only [zero_mul, add_zero] + exact div_nonneg (mul_nonneg (width_nonneg _) (width_nonneg _)) (by positivity) + let i₀ : A := Classical.arbitrary A + have : Nontrivial A := by + by_contra hn + have : Subsingleton A := not_nontrivial_iff_subsingleton.mp hn + have hx (i : A) : x i = x i₀ := congrArg x (Subsingleton.elim _ _) + have hy : dist o (x i₀) ^ 2 + dist o (x i₀) ^ 2 ≤ 0 := by + simpa [hx, Fintype.expect_const] using ho (x i₀) + have hd : dist o (x i₀) = 0 := by + nlinarith [dist_nonneg (x := o) (y := x i₀)] + exact hzero (by simp [hx, hd]) + obtain ⟨d, hd, f, hf, hP, hvar⟩ := hV A x o ho + have hd' : 0 < d := by + rcases hd.eq_or_lt with hd | hd + · let y (_ : Unit) := i₀ + have hh := hvar (f.comp (Tensor.foldSites y)) (hf.comp (Tensor.foldSites_mono y)) + (fun T => congrArg f (Tensor.foldSites_pad y T)) + exact (hzero (by simpa [← hd] using hh)).elim + · exact hd + refine ⟨Tensor.values d f, hP, fun R hR => ?_⟩ + let c := entropy ^ 2 * (sqrt R + 3) / 2 + let C := d * (Fintype.card A + 12) * 4 + c + have hc : 0 ≤ c := by unfold c; positivity + have hC : 0 ≤ C := by unfold C; positivity + refine ⟨C, ?_⟩ + filter_upwards [probe_window R (Fintype.card A)] with n hn + intro e he hbudget hne + obtain ⟨hn', hnlog, M, hnM, hA, hcap, hlog⟩ := hn + have hn : 0 < (n : ℝ) := zero_lt_one.trans_le hn' + have heM (i : A) : e i ≤ M := by + have h : R ≤ (sqrt R + 2) ^ 2 := by nlinarith [sq_sqrt hR.le, sqrt_nonneg R] + exact Nat.cast_le.mp ((hbudget i).trans ((mul_le_mul_of_nonneg_right h (sq_nonneg _)).trans + hcap)) + let B := objective (Tensor.values d f) z n e / d + let t := entropy ^ 2 / (2 * n) / d + have ht : 0 ≤ t := by unfold t; positivity + have hdt : d * t = entropy ^ 2 / (2 * n) := mul_div_cancel₀ _ hd'.ne' + have hB : d * B = objective (Tensor.values d f) z n e := mul_div_cancel₀ _ hd'.ne' + have hbase (a : A → ℕ) : f (sphereTensor z a) ≤ exp (B + ∑ i, t * (a i : ℝ)) := by + apply le_exp_of_log_le + apply (mul_le_mul_iff_right₀ hd').mp + rw [← mul_sum, mul_add, hB, ← mul_assoc, hdt] + have := he a + rw [objective_eq] at this + linarith only [this] + obtain ⟨g, hg, hgf, htest⟩ := hE A f hf z hz B t ht hbase M + refine ⟨fun i => d * Tensor.dist g (.inl i) (.inr ()), + fun i => mul_nonneg hd (Tensor.dist_nonneg g hg _ _), hvar g hg hgf, fun i q hq => ?_⟩ + by_cases hq' : 0 < Fintype.card (Level 1 q) + swap + · rw [Nat.eq_zero_of_not_pos hq', Nat.cast_zero, log_zero, mul_zero] + exact add_nonneg (div_nonneg (mul_nonneg (width_nonneg _) (width_nonneg _)) hn.le) + (mul_nonneg hC (zero_le_one.trans hnlog)) + obtain ⟨hlim, hw⟩ := probe_cost R hR (by linarith : 1 ≤ (n : ℝ)) (hbudget i) hq + have hH : ⌊Sphere.width q (e i)⌋₊ ≤ M := by + have hnonneg : 0 ≤ Sphere.width q (e i) := by + unfold Sphere.width + positivity + exact Nat.cast_le.mp ((Nat.floor_le hnonneg).trans (hlim.trans hcap)) + have hp := probe_log hW hf hg hgf hz B (fun _ => t) (fun _ => ht) M htest e hne i q hA heM hH + (hq.trans hnM) hq' + simp only [← mul_sum, ← mul_sub, ← mul_add] at hp + have hp' := mul_le_mul_of_nonneg_left hp hd + rw [mul_add, mul_add, mul_add, hB, objective_eq, ← mul_assoc d t, hdt] at hp' + have hh : entropy ^ 2 / (2 * n) * (Sphere.width q (e i) + q - e i) ≤ + width (e i) * width q / n + c := by + rw [div_mul_eq_mul_div, div_le_iff₀ (by positivity)] + unfold c + refine hw.trans_eq ?_ + field_simp + have hl := mul_le_mul_of_nonneg_left hlog (show 0 ≤ d * (Fintype.card A + 12) by positivity) + have he' := mul_le_mul_of_nonneg_left hnlog hc + unfold C + linarith only [hp', hh, hl, he'] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral + +/-- A price extension with a separate energy penalty at each site. -/ +def WeightedExtension (F : Type) [Field F] : Prop := + ∀ (A : Type) [Fintype A] [DecidableEq A] [Nonempty A] (f : Tensor F A →+* ℝ), + Monotone f → ∀ z : A → F, Function.Injective z → + ∀ (B : ℝ) (t : A ⊕ Unit → ℝ), (∀ i, 0 ≤ t i ∧ t i ≤ t (.inr ())) → + (∀ e, f (sphereTensor z e) ≤ Real.exp (B + ∑ i, t (.inl i) * (e i : ℝ))) → + ∀ M : ℕ, ∃ g : Tensor F (A ⊕ Unit) →+* ℝ, Monotone g ∧ + (∀ T, g (Tensor.pad Unit T) = f T) ∧ + ∀ (s : F), s ∉ Set.range z → ∀ e : A ⊕ Unit → ℕ, (∀ i, e i ≤ M) → + g (sphereTensor (Sum.elim z (fun _ => s)) e) ≤ + ((M : ℝ) + 2) ^ (Fintype.card A + 8) * Real.exp (B + ∑ i, t i * (e i : ℝ)) + +theorem WeightedExtension.uniform {F : Type} [Field F] (h : WeightedExtension F) : + BoundedExtension F := by + intro A _ _ _ f hf z hz B t ht + exact h A f hf z hz B (fun _ => t) (fun _ => ⟨ht, le_rfl⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Uniform distance tests for weighted budgets + +Penalties are squared rescaling factors. The new site pays the largest +allowed penalty. Since its probe energy is at most the optimizer scale, +this adds only a bounded term to the logarithmic error. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Center +open Spectral Real Filter Finset Sphere + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + +/-- Computes the price by the application `log (f (sphereTensor z e))`. -/ +def price (f : Tensor F A →+* ℝ) (z : A → F) (e : A → ℕ) := log (f (sphereTensor z e)) + +private def penalty (μ : A → ℝ) (U : ℝ) (n : ℕ) (i : A ⊕ Unit) := + (Sum.elim μ (fun _ => U) i) ^ 2 * entropy ^ 2 / (2 * n) + +omit [DecidableEq A] in +private theorem value_eq (f : Tensor F A →+* ℝ) (z : A → F) (μ : A → ℝ) + (U : ℝ) (n : ℕ) (e : A → ℕ) : + Budget.value (price f z) μ n e = + log (f (sphereTensor z e)) - ∑ i, penalty μ U n (.inl i) * (e i : ℝ) := by + unfold Budget.value price + rw [sum_div] + congr 1 + apply sum_congr rfl + intro i _ + simp only [penalty, Sum.elim_inl, mul_pow, width_sq] + ring + +private theorem weighted_cost (R U v : ℝ) (hR : 0 < R) (hv : 0 < v) (hU : v ≤ U) + {n a q : ℕ} (hn : 1 ≤ (n : ℝ)) (ha : (a : ℝ) ≤ R * n ^ 2) (hq : q ≤ n) : + v ^ 2 * entropy ^ 2 / (2 * n) * (Sphere.width q a - a) + U ^ 2 * entropy ^ 2 / (2 * n) * q ≤ + v ^ 2 * Routing.width a * Routing.width q / n + U ^ 2 * entropy ^ 2 * (sqrt R + 4) := by + have hc := (probe_cost R hR hn ha hq).2 + have hn' : 0 < (n : ℝ) := zero_lt_one.trans_le hn + have h₁ := mul_le_mul_of_nonneg_left hc (sq_nonneg v) + have h₂ := mul_le_mul_of_nonneg_right (pow_le_pow_left₀ hv.le hU 2) + (show 0 ≤ entropy ^ 2 * (sqrt R + 3) * n by positivity) + have h₃ := mul_le_mul_of_nonneg_left (show (q : ℝ) ≤ n by exact_mod_cast hq) + (show 0 ≤ U ^ 2 * entropy ^ 2 by positivity) + have h₄ : 0 ≤ v ^ 2 * entropy ^ 2 * q := by positivity + have h₅ : 0 ≤ U ^ 2 * entropy ^ 2 * (sqrt R + 4) * n := by positivity + field_simp + linarith only [h₁, h₂, h₃, h₄, h₅] + +theorem weighted_control (hE : WeightedExtension F) (hW : WireProbe F) + (z : A → F) (hz : Function.Injective z) {l U R : ℝ} (hl : 0 < l) (hR : 0 < R) : + ∃ C : ℝ, ∀ᶠ n : ℕ in atTop, ∀ (f : Tensor F A →+* ℝ), Monotone f → + ∀ μ : A → ℝ, (∀ i, l ≤ μ i ∧ μ i ≤ U) → ∀ e : A → ℕ, + (∀ a, Budget.value (price f z) μ n a ≤ Budget.value (price f z) μ n e) → + (∀ i, (e i : ℝ) ≤ R * (n : ℝ) ^ 2) → sphereForm z e ≠ 0 → + ∃ g : Extended F A →+* ℝ, Monotone g ∧ (∀ T, g (Tensor.pad Unit T) = f T) ∧ + ∀ i q, q ≤ n → radius g i / μ i * log (Fintype.card (Level 1 q)) ≤ + μ i * Routing.width (e i) / n * entropy * sqrt q + C * log n := by + let c := U ^ 2 * entropy ^ 2 * (sqrt R + 4) + let C := ((Fintype.card A + 12) * 4 + c) / l + have hc : 0 ≤ c := by unfold c; positivity + have hC : 0 ≤ C := by unfold C; positivity + refine ⟨C, ?_⟩ + filter_upwards [probe_window R (Fintype.card A)] with n hn + obtain ⟨hn, hnlog, M, hnM, hA, hcap, hlog⟩ := hn + intro f hf μ hμ e he hbudget hne + have hμpos i := hl.trans_le (hμ i).1 + let t := penalty μ U n + have ht (i) : 0 ≤ t i ∧ t i ≤ t (.inr ()) := by + refine ⟨by unfold t penalty; positivity, ?_⟩ + cases i with + | inr i => rfl + | inl i => + simp only [t, penalty, Sum.elim_inl, Sum.elim_inr] + have := hμpos i + gcongr + exact (hμ i).2 + let B := Budget.value (price f z) μ n e + have hbase (a : A → ℕ) : f (sphereTensor z a) ≤ exp (B + ∑ i, t (.inl i) * (a i : ℝ)) := by + apply le_exp_of_log_le + apply sub_le_iff_le_add.mp + rw [← value_eq f z μ U n a] + exact he a + obtain ⟨g, hg, hgf, htest⟩ := hE A f hf z hz B t ht hbase M + refine ⟨g, hg, hgf, fun i q hq => ?_⟩ + have hw := width_nonneg (e i) + have hm := hμpos i + have h₀ := entropy_pos + by_cases hq' : 0 < Fintype.card (Level 1 q) + swap + · rw [Nat.eq_zero_of_not_pos hq', Nat.cast_zero, log_zero, mul_zero] + positivity + have heM (j : A) : e j ≤ M := by + have h : R ≤ (sqrt R + 2) ^ 2 := by nlinarith [sq_sqrt hR.le, sqrt_nonneg R] + exact Nat.cast_le.mp ((hbudget j).trans ((mul_le_mul_of_nonneg_right h (sq_nonneg _)).trans + hcap)) + have hlim := (probe_cost R hR hn (hbudget i) hq).1 + have hH : ⌊Sphere.width q (e i)⌋₊ ≤ M := + Nat.cast_le.mp ((Nat.floor_le (by unfold Sphere.width; positivity)).trans (hlim.trans hcap)) + have hp := probe_log hW hf hg hgf hz B t (fun i => (ht i).1) M htest e hne i q hA heM hH + (hq.trans hnM) hq' + unfold B at hp + rw [value_eq f z μ U n e] at hp + have hh := weighted_cost R U (μ i) hR hm (hμ i).2 hn (hbudget i) hq + have hcoeff : (Fintype.card A + 12) * 4 + c ≤ μ i * C := + (mul_div_cancel₀ _ hl.ne').symm.le.trans (mul_le_mul_of_nonneg_right (hμ i).1 hC) + have hk := mul_le_mul_of_nonneg_right hcoeff (zero_le_one.trans hnlog) + have hcost := mul_le_mul_of_nonneg_left hlog (show 0 ≤ (Fintype.card A : ℝ) + 12 by positivity) + have herr := mul_le_mul_of_nonneg_left hnlog hc + rw [div_mul_eq_mul_div, div_le_iff₀ hm, mul_assoc _ entropy, ← Routing.width] + unfold radius + simp only [t, penalty, Sum.elim_inl, Sum.elim_inr] at hp + unfold c at herr hk + simp only [div_eq_mul_inv] at hp hh ⊢ + linarith only [hp, hh, hk, hcost, herr] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Center +end + +/- +# Uniform prescribed widths + +A smoothed minimizing extension sets the weights of the quadratic +optimization. Its strict slack absorbs the uniform error in the +optimizing widths. The price and width bounds use natural logarithms. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Sphere Spectral Filter Finset Center + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + +private theorem transport_bound (f : Tensor F A →+* ℝ) (g : Extended F A →+* ℝ) + (hg : Monotone g) (hgf : ∀ T, g (Tensor.pad Unit T) = f T) + (z : A → F) (μ : A → ℝ) (hμ : ∀ i, 0 < μ i) (e : A → ℕ) : + price f z e ≤ ∑ i, (radius g i / μ i) * (μ i * width (e i)) := by + have h := Tensor.preparation hg (Raw.ofTable (fun i => Level 1 (e i)) (sphereForm z e)) + rw [hgf] at h + apply h.trans + apply sum_le_sum + intro i _ + rw [← mul_assoc, div_mul_cancel₀ _ (hμ i).ne'] + exact mul_le_mul_of_nonneg_left (entropy_bound _) (Tensor.dist_nonneg g hg _ _) + +omit [DecidableEq A] in +private theorem cost_zero (f : Tensor F A →+* ℝ) (z : A → F) (e : A → ℕ) + (h : sphereForm z e = 0) : price f z e = 0 := by + have ht : sphereTensor z e = 0 := by + refine (Tensor.ofRaw_eq_zero _).mpr ?_ + change ∀ v : States 1 e, (Raw.ofTable (fun i => Level 1 (e i)) (sphereForm z e)).coeff v = 0 + simp [h] + simp [price, ht] + +/-- Uniformity in both the price and a compact range of penalties. -/ +private theorem profile (hE : WeightedExtension F) (hW : WireProbe F) (z : A → F) + (hz : Function.Injective z) {l U η : ℝ} (hl : 0 < l) (hη : 0 < η) : + ∀ᶠ n : ℕ in atTop, ∀ (f : Tensor F A →+* ℝ), Monotone f → + ∀ (g : Extended F A →+* ℝ), Monotone g → (∀ T, g (Tensor.pad Unit T) = f T) → + ∀ μ : A → ℝ, (∀ i, l ≤ μ i ∧ μ i ≤ U) → + (∀ h : Extended F A →+* ℝ, Monotone h → (∀ T, h (Tensor.pad Unit T) = f T) → + (∑ i, (radius g i / μ i) ^ 2) ≤ ∑ i, (radius h i / μ i) ^ 2) → + ∃ e : A → ℕ, (∀ i, μ i * width (e i) / n ≤ radius g i / μ i + η) ∧ + ∑ i, (radius g i / μ i) ^ 2 ≤ price f z e / n + η ^ 2 + Fintype.card A * (1 / l) * η := by + let D₀ := Fintype.card A * (1 / l) ^ 2 + have hD₀ : 0 ≤ D₀ := by unfold D₀; positivity + let R := 4 * (D₀ + 1) / (l * entropy) ^ 2 + have hR : 0 < R := div_pos (by positivity) (sq_pos_of_pos (mul_pos hl entropy_pos)) + obtain ⟨C, ht⟩ := weighted_control (U := U) hE hW z hz hl hR + obtain ⟨N, hN⟩ := eventually_atTop.mp ((eventually_gt_atTop 0).and ht) + filter_upwards [uniform_gap (I := A) D₀ (2 * (D₀ + + 1)) C (by positivity) N (η ^ 2) (by positivity)] + with n hn + intro f hf g hg hgf μ hμ hvar + let r i := radius g i / μ i + let D := ∑ i, r i ^ 2 + have hp i := hl.trans_le (hμ i).1 + have hr (i : A) : 0 ≤ r i ∧ r i ≤ 1 / l := + ⟨div_nonneg (Tensor.dist_nonneg g hg _ _) (hp i).le, + div_le_div₀ zero_le_one (Tensor.dist_le_one g hg _ _) hl (hμ i).1⟩ + have hD : D ≤ D₀ := by + simpa [D, D₀] using sum_le_card_nsmul univ (fun i => r i ^ 2) ((1 / l) ^ 2) + (fun i _ => pow_le_pow_left₀ (hr i).1 (hr i).2 2) + have hprice : 0 ≤ price f z (fun _ => 0) := by + unfold price + generalize sphereTensor z (fun _ => 0) = T + by_cases hT : T = 0 + · simp [hT] + exact Real.log_nonneg (Tensor.value_one_le hf hT) + have trans := transport_bound f g hg hgf z μ hp + choose e he using Budget.maximizer trans hD hl (fun i => (hμ i).1) z hprice (cost_zero f z) + let w (m : ℕ) i := μ i * width (e m i) / m + let B (m : ℕ) := Budget.value (price f z) μ m (e m) + have bound (m : ℕ) (hm : 0 < m) (i : A) : + w m i ≤ 2 * (D₀ + 1) ∧ (e m i : ℝ) ≤ R * (m : ℝ) ^ 2 := + Budget.bounds trans hD hl (fun j => (hμ j).1) m hm (e m) (he m hm).1 i + have hb : D < 2 * (B n / n) + η ^ 2 := by + refine hn D w B hD (fun m hm => (he m (hN m hm).1).1) ?_ ?_ ?_ + · intro m hm i + exact ⟨div_nonneg (mul_nonneg (hp i).le (width_nonneg _)) (by positivity), + (bound m (hN m hm).1 i).1⟩ + · intro m hm + obtain ⟨hpos, htest⟩ := hN m hm + obtain ⟨_, hne, hmax⟩ := he m hpos + obtain ⟨q, hq, hqf, hdist⟩ := htest f hf μ hμ (e m) hmax (fun i => (bound m hpos i).2) hne + exact ⟨fun i => radius q i / μ i, fun i => div_nonneg (Tensor.dist_nonneg q hq _ _) (hp i).le, + hvar q hq hqf, hdist⟩ + · intro m hm + unfold w B + rw [Budget.increment (p := price f z) _ _ (hN m hm).1] + gcongr + exact (he (m + 1) (by omega)).2.2 _ + have hs : 2 * (B n / n) + ∑ i, (w n i - r i) ^ 2 ≤ D := Budget.squares trans n (e n) + have hi (i : A) : w n i ≤ r i + η ∧ r i ≤ w n i + η := by + have := single_le_sum (fun j (_ : j ∈ univ) => sq_nonneg (w n j - r j)) (mem_univ i) + constructor <;> nlinarith only [this, hs, hb, hη] + refine ⟨e n, fun i => (hi i).1, ?_⟩ + have hi' (i : A) : r i ^ 2 ≤ w n i ^ 2 + 2 * (1 / l) * η := by + nlinarith only [mul_le_mul_of_nonneg_left (hi i).2 (hr i).1, + mul_le_mul_of_nonneg_right (hr i).2 hη.le, sq_nonneg (w n i - r i)] + have hh := sum_le_sum (fun i (_ : i ∈ univ) => hi' i) + simp only [sum_add_distrib, sum_const, card_univ, nsmul_eq_mul] at hh + have heq : B n / n = price f z (e n) / n - (∑ i, w n i ^ 2) / 2 := Budget.normalize n (e n) + change D ≤ _ + unfold D at hb ⊢ + linarith only [hh, heq, hb, sq_nonneg η] + +/-- At all sufficiently large scales, every spectral point admits a +sphere within the prescribed caps whose log price approaches the +transport cost of the caps at a single extended site. -/ +theorem prescribed_widths (hE : WeightedExtension F) (hW : WireProbe F) + (z : A → F) (hz : Function.Injective z) (a : A → ℝ) (ha : ∀ i, 0 < a i) + {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ n : ℕ in atTop, ∀ f : Tensor F A →+* ℝ, Monotone f → + ∃ g : Tensor F (A ⊕ Unit) →+* ℝ, Monotone g ∧ (∀ T, g (Tensor.pad Unit T) = f T) ∧ + ∃ e : A → ℕ, (∀ i, width (e i) ≤ n * a i) ∧ + n * ((∑ i, a i * Tensor.dist g (.inl i) (.inr ())) - ε) ≤ Real.log (f (sphereTensor z e)) + := by + let S := ∑ i, a i + have hS : 0 ≤ S := sum_nonneg fun i _ => (ha i).le + let τ := min 1 (ε / 2 / (S + 1)) + have ht : 0 < τ := lt_min zero_lt_one (by positivity) + have ht' : τ * S ≤ ε / 2 := by + have := (le_div_iff₀ (by positivity : 0 < S + 1)).mp (show τ ≤ ε / 2 / (S + + 1) from min_le_right _ _) + linarith + obtain ⟨l, U, hl, hU, weights⟩ := choose_weights (F := F) a ha ht (min_le_left _ _) + let B := Fintype.card A * (1 / l) + have hB : 0 ≤ B := by unfold B; positivity + let η := min 1 (min (τ ^ 2 / 3 / U) (ε / 2 / (B + 1))) + have hη : 0 < η := lt_min zero_lt_one (lt_min (by positivity) (by positivity)) + have hslack : η * U ≤ τ ^ 2 / 3 := + (le_div_iff₀ hU).mp ((min_le_right _ _).trans (min_le_left _ _)) + have herr : η ^ 2 + B * η ≤ ε / 2 := by + have hm : η ≤ 1 := min_le_left _ _ + have hh : η * (B + 1) ≤ ε / 2 := + (le_div_iff₀ (by positivity)).mp ((min_le_right _ _).trans (min_le_right _ _)) + nlinarith + filter_upwards [profile (U := U) hE hW z hz hl hη, eventually_gt_atTop 0] with n hp hn + intro f hf + obtain ⟨g, hg, he, μ, hμ, hs, hlow, hvar⟩ := weights f hf + obtain ⟨e, hw, hc⟩ := hp f hf g hg he μ hμ hvar + have hn' : 0 < (n : ℝ) := by positivity + refine ⟨g, hg, he, e, fun i => ?_, ?_⟩ + · have hm := hl.trans_le (hμ i).1 + have hi := mul_le_mul_of_nonneg_right (hw i) hm.le + rw [add_mul, div_mul_cancel₀ _ hm.ne'] at hi + rw [mul_comm, ← div_le_iff₀ hn'] + apply (mul_le_mul_iff_left₀ (sq_pos_of_pos hm)).mp + calc + _ = μ i * width (e i) / n * μ i := by ring + _ ≤ radius g i + η * μ i := hi + _ ≤ radius g i + τ ^ 2 / 3 := + add_le_add_right ((mul_le_mul_of_nonneg_left (hμ i).2 hη.le).trans hslack) _ + _ ≤ _ := hs i + · rw [mul_comm, ← le_div_iff₀ hn'] + change (∑ i, a i * radius g i) - ε ≤ price f z e / n + unfold S at ht' + unfold B at herr + linarith only [hc, hlow, ht', herr] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- Simultaneous price bounds for one moving sphere insertion. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral Sphere Finset Polynomial + +variable {A F : Type} [Field F] [Fintype A] + +open scoped Classical in +private theorem regular_denominator (a : A → Fin 2 → F) (s : F) + (h : Function.Injective (fun i => position (a i) s 1)) : + denominator (directions a) s 1 ≠ 0 := by + refine prod_ne_zero_iff.mpr fun d hd => ?_ + rcases mem_insert.mp hd with hnone | hm + · simp [linearFactor, hnone] + obtain ⟨_, hk, rfl⟩ := mem_image.mp hm + obtain ⟨⟨i, j⟩, hij, rfl⟩ := mem_image.mp hk + have hi := through_left (a i) (a j) + have hj := through_right (a i) (a j) + generalize through (a i) (a j) = k at * + obtain ⟨_ | d, t⟩ := k + · exact one_ne_zero + intro he + have hs : s = -d := by simpa [linearFactor, add_eq_zero_iff_eq_neg] using he + apply (mem_filter.mp hij).2 + apply h + simpa [projection, position, hs, sub_eq_add_neg, add_comm, mul_comm] using hi.trans hj.symm + +variable [Nonempty A] + +open scoped Classical in +private theorem scalar_le (X : A → Type) [∀ i, Fintype (X i)] + (T U : (∀ i, X i) → F) (c : F) (h : ∀ v, T v = c * U v) : + Tensor.ofRaw (Raw.ofTable X T) ≤ Tensor.ofRaw (Raw.ofTable X U) := by + simpa using Tensor.span_le X T (fun _ : Unit => U) (fun _ => c) (by simp [h]) + +omit [Nonempty A] in +open scoped Classical in +private theorem movingFamily (z : A → F) (hz : Function.Injective z) (e : A ⊕ Unit → ℕ) : + ∃ p : States 1 e → F[X], ∀ s ∉ Set.range z, + Prices.evalFamily (fun i => Level 1 (e i)) p s = sphereTensor (Sum.elim z (fun _ => s)) e + := by + let a : A ⊕ Unit → Fin 2 → F := Sum.elim (fun i => ![0, z i]) (fun _ => ![1, 0]) + refine ⟨fun v => correlatorPoly a (X : F[X]) 1 (inputs v), fun s hs => ?_⟩ + let t := Sum.elim z (fun _ : Unit => s) + have he (i) : position (a i) s 1 = t i := by cases i <;> simp [a, position, t] + have hi : Function.Injective t := by + rintro (i|⟨⟩) (j|⟨⟩) h + · exact congrArg Sum.inl (hz h) + · exact (hs ⟨i, h⟩).elim + · exact (hs ⟨j, h.symm⟩).elim + · rfl + have hd := regular_denominator a s (by simpa only [he] using hi) + let c := denominator (directions a) s 1 ^ ((∑ i, e i) / 2) + have hc : c ≠ 0 := pow_ne_zero _ hd + have eqn (v : States 1 e) : + (correlatorPoly a (X : F[X]) 1 (inputs v)).eval s = c * sphereForm t e v := by + have h := correlator_map (aeval s) a (X : F[X]) 1 (inputs v) + simp only [aeval_X, map_one, correlator_specialize _ _ _ hd, he, weight_inputs] at h + simpa [c, sphereForm] using h + refine le_antisymm (scalar_le _ _ _ c eqn) (scalar_le _ _ _ c⁻¹ fun v => ?_) + change sphereForm t e v = c⁻¹ * (correlatorPoly a (X : F[X]) 1 (inputs v)).eval s + rw [eqn, inv_mul_cancel_left₀ hc] + +open scoped Classical in +theorem BoundedForms.weighted (h : BoundedForms F) (sync : Prices.SharedPrice F) : + WeightedExtension F := by + intro A _ _ _ f hf z hz B t ht he M + let I := {e : A ⊕ Unit → ℕ // ∀ i, e i ≤ M} + let X (e : I) (i) := Level 1 (e.1 i) + let p (e : I) := ((M : ℝ) + 2) ^ (Fintype.card A + 8) * Real.exp (B + ∑ i, t i * (e.1 i : ℝ)) + choose P hP using fun i : I => movingFamily z hz i.1 + obtain ⟨g, hg, hext, hbound⟩ := sync A I f hf (univ.image z) X P p (by + intro s hs w T hT + have hs' : s ∉ Set.range z := by simpa using hs + have hh := h A f hf z hz B t ht he s hs' M + (w.map Subtype.val) (by + intro e he + obtain ⟨v, _, rfl⟩ := List.mem_map.mp he + exact v.2) T + simp only [List.map_map, Function.comp_def] at hh + apply hh + simpa only [X, hP _ s hs'] using hT) + refine ⟨g, hg, hext, fun s hs e he => ?_⟩ + have eq := hP ⟨e, he⟩ s hs + change Prices.evalFamily (X ⟨e, he⟩) (P ⟨e, he⟩) s = sphereTensor _ e at eq + rw [← eq] + exact hbound ⟨e, he⟩ s (by simpa using hs) + +open scoped Classical in +theorem BoundedForms.extension (h : BoundedForms F) (sync : Prices.SharedPrice F) : + BoundedExtension F := (h.weighted sync).uniform + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Padding.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Padding.lean new file mode 100644 index 0000000000..d3e1cbfcf7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Padding.lean @@ -0,0 +1,35 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Ring.Defs +public import Mathlib.Order.Basic + +/-! +# Restriction after adjoining trivial legs + +The embedding preserves products. A direct sum over the larger site +set gives each extra leg a block label. This costs an inequality in +one direction and permits independent closures in the other. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices + +/-- The data for the padding construction, including `zero`, `one`, `le_iff`, `mul`, `add_le`. -/ +structure Padding {S T : Type*} [CommSemiring S] [CommSemiring T] + [PartialOrder S] [PartialOrder T] (pad : S → T) : Prop where + zero : pad 0 = 0 + one : pad 1 = 1 + le_iff (s t) : pad s ≤ pad t ↔ s ≤ t + mul (s t) : pad (s * t) = pad s * pad t + add_le (s t) : pad (s + t) ≤ pad s + pad t + split {s x y} : pad s ≤ x + y → ∃ a b, pad a ≤ x ∧ pad b ≤ y ∧ s ≤ a + b + factor {s a x} : pad s ≤ pad a * x → ∃ b, pad b ≤ x ∧ s ≤ a * b + +end MatrixMultiplicationAllFields.MatrixExponent.Prices diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Space.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Space.lean new file mode 100644 index 0000000000..664c894a72 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Space.lean @@ -0,0 +1,240 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Comparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryTerms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Tensor + +/-! +# Compactness of ordinary prices of bounded scale + +We use base-two logarithms. A zero input is assigned a dummy value +of zero, common to every price. It therefore gives no information +in equality or continuity tests. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +open Set +open scoped NNReal + +variable {K S : Type} [Field K] [Fintype S] + +/-- The quantity computed by `d * (Real.log (f A) / Real.log 2)`. -/ +def values (d : ℝ) (f : Tensor K S →+* ℝ) (A : Tensor K S) : ℝ := + d * (Real.log (f A) / Real.log 2) + +variable (K S) in +/-- Uses `{P | ∃ d ∈ Icc 0 D, ∃ f : Tensor K S →+* ℝ, Monotone f ∧ P = values d f}` as the +representation. -/ +def ordinary (D : ℝ) : Set (Tensor K S → ℝ) := + {P | ∃ d ∈ Icc 0 D, ∃ f : Tensor K S →+* ℝ, Monotone f ∧ P = values d f} + +variable [Nonempty S] + +theorem value_one_le {f : Tensor K S →+* ℝ} (hf : Monotone f) {A : Tensor K S} + (h : A ≠ 0) : 1 ≤ f A := by + simpa using hf (one_le A h) + +theorem values_nonneg {d : ℝ} (hd : 0 ≤ d) {f : Tensor K S →+* ℝ} (hf : Monotone f) + (A : Tensor K S) : 0 ≤ values d f A := by + by_cases h : A = 0 + · simp [values, h] + exact mul_nonneg hd (div_nonneg (Real.log_nonneg (value_one_le hf h)) (Real.log_nonneg (by + norm_num))) + +theorem compact_ordinary (D : ℝ) : IsCompact (ordinary K S D) := by + let T := Tensor K S + let v (x : ℝ × (T → ℝ≥0)) (a : T) := x.1 * (Real.log (max 1 (x.2 a : ℝ)) / Real.log 2) + have hv : Continuous v := by + apply continuous_pi + intro a + have h : Continuous (fun x : ℝ × (T → ℝ≥0) => max 1 (x.2 a : ℝ)) := by fun_prop + exact continuous_fst.mul ((h.log (fun x => (zero_lt_one.trans_le (le_max_left _ + _)).ne')).div_const _) + have ev (d : ℝ) (g : T → ℝ≥0) (f : T →+* ℝ) (hf : Monotone f) (he : ∀ A, ↑(g A) = f A) : + v (d, g) = values d f := by + funext A + unfold v values + rw [he] + by_cases h : A = 0 + · simp [h] + · rw [max_eq_right (value_one_le hf h)] + have h : ordinary K S D = v '' (Icc 0 D ×ˢ Spectrum.points T) := by + ext P + constructor + · rintro ⟨d, hd, f, hf, rfl⟩ + have hn (A : T) : 0 ≤ f A := by simpa using hf (zero_le A) + let g : T →+* ℝ≥0 := + { toFun := fun A => ⟨f A, hn A⟩ + map_zero' := Subtype.ext (map_zero f) + map_one' := Subtype.ext (map_one f) + map_add' := fun a b => Subtype.ext (f.map_add a b) + map_mul' := fun a b => Subtype.ext (f.map_mul a b) } + exact ⟨(d, g), ⟨hd, g, hf, rfl⟩, ev d g f hf (fun _ => rfl)⟩ + · rintro ⟨⟨d, g⟩, ⟨hd, f, hf, he⟩, rfl⟩ + let f' := NNReal.toRealHom.comp f + have hf' : Monotone f' := hf + refine ⟨d, hd, f', hf', ev d g f' hf' ?_⟩ + intro A + exact congrArg NNReal.toReal (congrFun he A).symm + rw [h] + exact (isCompact_Icc.prod (Spectrum.compact_points exists_bound)).image hv + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +section +/- +# Compatible realizations of a finite price placement + +A witness on the enlarged marking can have a different scale. Its +scale bound comes from the diameter and the number of names. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral + +variable {K S T : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] +variable {Y : Type*} [MetricSpace Y] + +/-- The realized of type `Prop` for the given inputs. -/ +def Realized (x : S → Y) (P : Tensor K S → ℝ) (D : ℝ) : Prop := + (∀ a b, dist (x a) (x b) ≤ D) ∧ + ∀ (U : Type) [Fintype U] [DecidableEq U] [Nonempty U] (z : U → Y), + (∀ i j, dist (Sum.elim x z i) (Sum.elim x z j) ≤ 2 * D) → + ∃ Q ∈ Tensor.ordinary K (S ⊕ U) (2 * D * Fintype.card (S ⊕ U)), + (∀ A, Q (Tensor.pad U A) = P A) ∧ + ∀ i j, Q (Tensor.wire K i j 2) = dist (Sum.elim x z i) (Sum.elim x z j) + +theorem Realized.zero {x : S → Y} {P : Tensor K S → ℝ} {D : ℝ} (h : Realized x P D) : + P 0 = 0 := by + let i := Classical.arbitrary S + have hD : 0 ≤ D := dist_nonneg.trans (h.1 i i) + have hd (a b : S) : dist (x a) (x b) ≤ 2 * D := (h.1 a b).trans (by linarith) + obtain ⟨_, ⟨d, _, f, _, rfl⟩, he, _⟩ := h.2 S x (fun j k + => by cases j <;> cases k <;> exact hd _ _) + rw [← he, (Tensor.padding S).zero] + simp [Tensor.values] + +variable (K Y) in +/-- The spectral space of type `Prop` for the given inputs. -/ +def SpectralSpace : Prop := + ∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (x : S → Y), + ∃ P : Tensor K S → ℝ, (∀ a b, P (Tensor.wire K a b 2) = dist (x a) (x b)) ∧ + ∀ D : ℝ, 0 < D → (∀ a b, dist (x a) (x b) ≤ D) → Realized x P D + +variable (K) in +/-- The represents of type `Prop` for the given inputs. -/ +def Represents [Fintype T] [DecidableEq T] (P : Tensor K T → ℝ) (x : T → Y) : Prop := + (∀ a b, P (Tensor.wire K a b 2) = dist (x a) (x b)) ∧ + ∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (z : S → T) (D : ℝ), + 0 < D → (∀ a b, dist (x (z a)) (x (z b)) ≤ D) → + Realized (x ∘ z) (P ∘ Tensor.place z) D + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Preservation of shared labels and wire distances under extension -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + (U : Type) [Fintype U] [DecidableEq U] + +theorem pad_shared (V : Finset S) (n : ℕ) : + pad U (shared K V n) = shared K (V.image Sum.inl) n := by + rw [← place_inl, place_shared] + +theorem pad_wire (a b : S) (n : ℕ) : + pad U (wire K a b n) = wire K (.inl a) (.inl b) n := by + simp [wire, pad_shared] + +variable {U} + +theorem dist_pad {f : Tensor K S →+* ℝ} {g : Tensor K (S ⊕ U) →+* ℝ} + (h : ∀ B, g (pad U B) = f B) (a b : S) : + dist g (.inl a) (.inl b) = dist f a b := by + unfold dist + rw [← pad_wire, h] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- +# Simultaneous geodesic placement + +Fold all new sites onto the first and then the second endpoints. +One extension interpolates these evaluations from above. The triangle +inequality forces equality on each of the prescribed endpoint distances. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S U : Type} [Field K] [Fintype S] [DecidableEq S] + [Fintype U] [DecidableEq U] + +/-- The indexed operation `group (Sum.elim id a) (fun s => ⟨.inl s, rfl⟩)`. -/ +def foldSites (a : U → S) : Tensor K (S ⊕ U) →+* Tensor K S := + group (Sum.elim id a) (fun s => ⟨.inl s, rfl⟩) + +theorem foldSites_mono (a : U → S) : Monotone (foldSites (K := K) a) := group_mono _ _ + +theorem foldSites_wire (a : U → S) (x y : S ⊕ U) (n : ℕ) : + foldSites a (wire K x y n) = wire K (Sum.elim id a x) (Sum.elim id a y) n := + group_wire _ _ x y n + +theorem foldSites_pad [Nonempty S] (a : U → S) (B : Tensor K S) : + foldSites a (pad U B) = B := group_pad _ _ (fun _ => rfl) B + +/-- Two sharp distance bounds for a geodesic position at parameter t. -/ +def Between (f : Tensor K S →+* ℝ) (a x b : S) (t : ℝ) : Prop := + dist f a x = t * dist f a b ∧ dist f x b = (1 - t) * dist f a b + +theorem between_of_le (f : Tensor K S →+* ℝ) (hf : Monotone f) {a x b : S} {t : ℝ} + (ha : dist f a x ≤ t * dist f a b) (hb : dist f x b ≤ (1 - t) * dist f a b) : + Between f a x b t := by + have h := dist_triangle f hf a x b + constructor <;> linarith + +theorem geodesic [Nonempty S] (f : Tensor K S →+* ℝ) (hf : Monotone f) + (a b : U → S) {t : ℝ} (ht : 0 ≤ t) (ht' : t ≤ 1) : + ∃ g : Tensor K (S ⊕ U) →+* ℝ, Monotone g ∧ (∀ B, g (pad U B) = f B) ∧ + (∀ i, Between g (.inl (a i)) (.inr i) (.inl (b i)) t) ∧ + (∀ X, g X ≤ f (foldSites a X) ^ (1 - t) * f (foldSites b X) ^ t) := by + let v (c : U → S) := f.comp (foldSites c) + have hv (c : U → S) : Monotone (v c) := hf.comp (foldSites_mono c) + have he (c : U → S) (B : Tensor K S) : v c (pad U B) = f B := + congrArg f (foldSites_pad c B) + obtain ⟨g, hg, eg, h⟩ := interpolate f hf (v b) (v a) (hv b) (hv a) (he b) (he a) ht ht' + have hu (X : Tensor K (S ⊕ U)) : g X ≤ f (foldSites a X) ^ (1 - t) * f (foldSites b X) ^ t := + (h X).trans_eq (mul_comm _ _) + refine ⟨g, hg, eg, ?_, hu⟩ + have hd (x y : S ⊕ U) : dist g x y ≤ + (1 - t) * dist f (Sum.elim id a x) (Sum.elim id a y) + + t * dist f (Sum.elim id b x) (Sum.elim id b y) := by + have hxy := hu (wire K x y 2) + rw [foldSites_wire, foldSites_wire, price_wire g hg _ _ (by decide), + price_wire f hf _ _ (by decide), price_wire f hf _ _ (by decide)] at hxy + have hpos : 0 < (2 : ℝ) := by norm_num + simp only [Nat.cast_ofNat, ← Real.rpow_mul hpos.le, ← Real.rpow_add hpos] at hxy + have hd := (Real.rpow_le_rpow_left_iff (by norm_num : (1 : ℝ) < 2)).mp hxy + simpa only [mul_comm] using hd + intro i + apply between_of_le g hg + · simpa [dist_pad eg, dist_self] using hd (.inl (a i)) (.inr i) + · simpa [dist_pad eg, dist_self] using hd (.inr i) (.inl (b i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Sync.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Sync.lean new file mode 100644 index 0000000000..a8c926be72 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Sync.lean @@ -0,0 +1,64 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Tensor +public import Mathlib.Algebra.Polynomial.Eval.Defs + +/-! # Synchronizing one polynomial parameter at a single new site -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices +open Spectral + +variable {F S : Type} [Field F] [Fintype S] [Nonempty S] + +/-- The indexed operation `Tensor.ofRaw (Raw.ofTable X (fun b => (P b).eval z))`. -/ +def evalFamily (X : S → Type) [∀ s, Fintype (X s)] + (P : (∀ s, X s) → Polynomial F) (z : F) : Tensor F S := + Tensor.ofRaw (Raw.ofTable X (fun b => (P b).eval z)) + +/-- Every finite product is tested at a common parameter outside the given +finite exceptional set. A single ordinary extension must satisfy all the +bounds at once. -/ +def SharedPrice (F : Type) [Field F] : Prop := + ∀ (S I : Type) [Fintype S] [DecidableEq S] [Nonempty S] + (f : Tensor F S →+* ℝ), Monotone f → + ∀ (B : Finset F) (X : I → S ⊕ Unit → Type) [∀ i s, Fintype (X i s)] + (P : ∀ i, (∀ s, X i s) → Polynomial F) (p : I → ℝ), + (∀ s ∉ B, ∀ w : List I, ∀ T, Tensor.pad Unit T ≤ + (w.map (fun i => evalFamily (X i) (P i) s)).prod → f T ≤ (w.map p).prod) → + ∃ g : Tensor F (S ⊕ Unit) →+* ℝ, Monotone g ∧ (∀ T, g (Tensor.pad Unit T) = f T) ∧ + (∀ i s, s ∉ B → g (evalFamily (X i) (P i) s) ≤ p i) + +/-- A bound for all synchronized assisted costs also bounds the cost with +independently chosen parameters. -/ +def Synchronization (F : Type) [Field F] : Prop := + ∀ (S I : Type) [Fintype S] [DecidableEq S] [Nonempty S] + (f : Tensor F S →+* ℝ), Monotone f → + ∀ (B : Finset F) (X : I → S ⊕ Unit → Type) [∀ i s, Fintype (X i s)] + (P : ∀ i, (∀ s, X i s) → Polynomial F) + (w : List (I × {z // z ∉ B})) (r : ℝ), + (∀ s ∉ B, Tensor.assisted f (w.map (fun i => evalFamily (X i.1) (P i.1) s)).prod ≤ r) → + Tensor.assisted f (w.map (fun i => evalFamily (X i.1) (P i.1) i.2)).prod ≤ r + +theorem Synchronization.sharedPrice (hs : Synchronization F) : SharedPrice F := by + intro S I _ _ _ f hf B X _ P p h + let ev i z := evalFamily (X i) (P i) z + have ht (z : F) (hz : z ∉ B) : ∀ w : List I, + Tensor.assisted f (w.map (fun i => ev i z)).prod ≤ (w.map p).prod := + (Tensor.assisted_extension_iff f hf _ p).mp ((Tensor.extension_iff f hf _ p).mpr (h z hz)) + let J := I × {z // z ∉ B} + let E (i : J) := ev i.1 i.2 + obtain ⟨g, hg, he, ha⟩ := (Tensor.assisted_extension_iff f hf E (fun i => p i.1)).mpr + (fun w => hs S I f hf B X P w _ fun z hz => by + simpa only [List.map_map, Function.comp_def] using ht z hz (w.map Prod.fst)) + exact ⟨g, hg, he, fun i z hz => ha (i, ⟨z, hz⟩)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Tensor.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Tensor.lean new file mode 100644 index 0000000000..edf5e4cad5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/Tensor.lean @@ -0,0 +1,560 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecificLimits.Normed +public import Mathlib.Algebra.BigOperators.Group.List.Basic +public import Mathlib.Tactic.Ring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Padding +public import Mathlib.Algebra.Order.Archimedean.Real.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Constrained +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rank + +/-! +# Imposing one price bound + +For a target r strictly above the tested price of X, replace the +additive functional M(U) by the sum of M(X^n U) / r^n over n. +Shifting the index gives the desired inequality. All earlier linear +inequalities stable under multiplication are preserved. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices + +variable {T I : Type*} [CommSemiring T] [PartialOrder T] + +/-- The condition `∀ u, M (a * u) ≤ c * M (b * u)` on the specified data. -/ +def StableLE (M : T → ℝ) (a b : T) (c : ℝ) : Prop := + ∀ u, M (a * u) ≤ c * M (b * u) + +/-- The condition `∃ K : ℝ, ∀ w : List I, M (w.map X).prod ≤ K * (w.map p).prod` on the +specified data. -/ +def ProductBound (X : I → T) (p : I → ℝ) (M : T → ℝ) : Prop := + ∃ K : ℝ, ∀ w : List I, M (w.map X).prod ≤ K * (w.map p).prod + +theorem discount (hmul : ∀ a b c : T, a ≤ b → c * a ≤ c * b) + (hzero : ∀ a : T, 0 ≤ a) + {X : I → T} {p : I → ℝ} {M : T →+ ℝ} (hm : Monotone M) (hpos : 0 < M 1) + (hbound : ∀ x, ∃ c ≥ 0, StableLE M x 1 c) + (hb : ProductBound X p M) (i : I) {r : ℝ} (hi : 0 ≤ p i) (hr : p i < r) : + ∃ N : T →+ ℝ, Monotone N ∧ 0 < N 1 ∧ ProductBound X p N ∧ + StableLE N (X i) 1 r ∧ ∀ a b c, StableLE M a b c → StableLE N a b c := by + obtain ⟨K, hK⟩ := hb + have hr0 := hi.trans_lt hr + let q := p i / r + have hq : Summable (fun n : ℕ => q ^ n) := + summable_geometric_of_lt_one (div_nonneg hi hr0.le) ((div_lt_one hr0).mpr hr) + let t (u : T) (n : ℕ) := M (X i ^ n * u) / r ^ n + have ht (u : T) (n : ℕ) : 0 ≤ t u n := + div_nonneg (by rw [← map_zero M]; exact hm (hzero _)) (pow_nonneg hr0.le n) + have htest (w : List I) (n : ℕ) : + t (w.map X).prod n ≤ q ^ n * (K * (w.map p).prod) := by + have h := hK (List.replicate n i ++ w) + simp only [List.map_append, List.map_replicate, List.prod_append, List.prod_replicate] at h + calc + _ ≤ (K * (p i ^ n * (w.map p).prod)) / r ^ n := + div_le_div_of_nonneg_right h (pow_nonneg hr0.le n) + _ = _ := by unfold q; rw [div_pow]; ring + have hs (u : T) : Summable (t u) := by + obtain ⟨m, hm, hu⟩ := hbound u + refine Summable.of_nonneg_of_le (ht u) ?_ (hq.mul_right (K * m)) + intro n + have h := hu (X i ^ n) + rw [mul_comm u, one_mul] at h + have hn := htest [] n + simp only [List.map_nil, List.prod_nil, mul_one] at hn + calc + _ ≤ (m : ℝ) * M (X i ^ n) / r ^ n := + div_le_div_of_nonneg_right h (pow_nonneg hr0.le n) + _ = t 1 n * m := by unfold t; rw [mul_one]; ring + _ ≤ q ^ n * K * m := mul_le_mul_of_nonneg_right hn hm + _ = _ := mul_assoc _ _ _ + let N : T →+ ℝ := + { toFun := fun u => ∑' n, t u n + map_zero' := by simp [t] + map_add' := fun u v => by + rw [← (hs u).tsum_add (hs v)] + exact tsum_congr (fun n => by simp only [t, mul_add, map_add, add_div]) } + refine ⟨N, ?_, ?_, ?_, ?_, ?_⟩ + · intro u v h + refine Summable.tsum_le_tsum (fun n => ?_) (hs u) (hs v) + exact div_le_div_of_nonneg_right (hm (hmul _ _ _ h)) (pow_nonneg hr0.le n) + · have h := (hs 1).le_tsum 0 (fun n _ => ht 1 n) + exact hpos.trans_le (by simpa [N, t] using h) + · refine ⟨(∑' n : ℕ, q ^ n) * K, fun w => ?_⟩ + change (∑' n, t (w.map X).prod n) ≤ _ + rw [mul_assoc, ← tsum_mul_right] + exact Summable.tsum_le_tsum (htest w) (hs _) (hq.mul_right _) + · intro u + rw [one_mul, mul_comm r, ← div_le_iff₀ hr0] + change (∑' n, t (X i * u) n) / r ≤ ∑' n, t u n + rw [← tsum_div_const, (hs u).tsum_eq_zero_add] + have shift (n : ℕ) : t (X i * u) n / r = t u (n + 1) := by + simp only [t, pow_succ, div_div, mul_assoc] + simp only [shift] + exact le_add_of_nonneg_left (ht u 0) + · intro a b c h u + change (∑' n, t (a * u) n) ≤ c * ∑' n, t (b * u) n + rw [← tsum_mul_left] + refine Summable.tsum_le_tsum (fun n => ?_) (hs _) ((hs _).mul_left c) + unfold t + rw [mul_left_comm (X i ^ n) a, mul_left_comm (X i ^ n) b, ← mul_div_assoc] + exact div_le_div_of_nonneg_right (h _) (pow_nonneg hr0.le n) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices +end + +section +/- +# The additive closure envelope + +Take the supremum of the old spectral value over tensors obtained from +a restriction with trivial output legs at the added sites. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices + +variable {S T : Type*} [CommSemiring S] [CommSemiring T] + [PartialOrder S] [PartialOrder T] {pad : S → T} + +theorem Padding.envelope (hp : Padding pad) + (hadd : ∀ a b c : T, a ≤ b → a + c ≤ b + c) + (hmul : ∀ a b c : T, a ≤ b → c * a ≤ c * b) + (hzero : ∀ a : T, 0 ≤ a) (hbound : ∀ a : T, ∃ (s : S) (n : ℕ), a ≤ pad s * n) + (f : S →+* ℝ) (hf : Monotone f) : + ∃ M : T →+ ℝ, M 1 = 1 ∧ Monotone M ∧ + (∀ s x, M (pad s * x) = f s * M x) ∧ + (∀ x r, M x ≤ r ↔ ∀ s, pad s ≤ x → f s ≤ r) := by + let V (x : T) : Set ℝ := {r | ∃ s, pad s ≤ x ∧ f s = r} + let M (x : T) := sSup (V x) + have hn (x : T) : (V x).Nonempty := + ⟨f 0, 0, hp.zero.symm ▸ hzero x, rfl⟩ + have hb (n : ℕ) (s : S) (hs : pad s ≤ (n : T)) : f s ≤ n := by + induction n generalizing s with + | zero => + rw [Nat.cast_zero, ← hp.zero] at hs + simpa using hf ((hp.le_iff _ _).mp hs) + | succ n ih => + rw [Nat.cast_succ, ← hp.one] at hs + obtain ⟨a, b, ha, h1, hab⟩ := hp.split hs + have he := hf ((hp.le_iff _ _).mp h1) + rw [map_one] at he + rw [Nat.cast_succ] + exact (hf hab).trans (by rw [map_add]; exact add_le_add (ih a ha) he) + have hbd (x : T) : BddAbove (V x) := by + obtain ⟨a, n, h⟩ := hbound x + have ha : 0 ≤ f a := by + rw [← map_zero f] + exact hf ((hp.le_iff _ _).mp (hp.zero.symm ▸ hzero _)) + refine ⟨f a * n, ?_⟩ + rintro _ ⟨s, hs, rfl⟩ + obtain ⟨b, hh, h'⟩ := hp.factor (hs.trans h) + exact (hf h').trans (by rw [map_mul]; exact mul_le_mul_of_nonneg_left (hb n b hh) ha) + have lo (x : T) (s : S) (hs : pad s ≤ x) : f s ≤ M x := + le_csSup (hbd x) ⟨s, hs, rfl⟩ + have hi (x : T) (r : ℝ) : M x ≤ r ↔ ∀ s, pad s ≤ x → f s ≤ r := by + refine ⟨fun h s hs => (lo x s hs).trans h, fun h => csSup_le (hn x) ?_⟩ + rintro _ ⟨s, hs, rfl⟩ + exact h s hs + have mono : Monotone M := fun x y h => (hi x _).mpr fun s hs => lo y s (hs.trans h) + have old (s : S) : M (pad s) = f s := + le_antisymm ((hi _ _).mpr fun a ha => hf ((hp.le_iff _ _).mp ha)) (lo _ s le_rfl) + have zero : M 0 = 0 := by rw [← hp.zero, old, map_zero] + have one : M 1 = 1 := by rw [← hp.one, old, map_one] + have hsum (x y : T) : M (x + y) = M x + M y := by + apply le_antisymm + · refine (hi _ _).mpr fun s hs => ?_ + obtain ⟨a, b, ha, hb, h⟩ := hp.split hs + exact (hf h).trans (by rw [map_add]; exact add_le_add (lo x a ha) (lo y b hb)) + · apply le_sub_iff_add_le.mp + refine (hi x _).mpr fun a ha => ?_ + apply le_sub_comm.mp + refine (hi y _).mpr fun b hb => ?_ + rw [le_sub_iff_add_le', ← map_add] + apply lo + refine (hp.add_le _ _).trans ((hadd _ _ _ ha).trans ?_) + simpa only [add_comm] using hadd _ _ x hb + refine ⟨{ toFun := M, map_zero' := zero, map_add' := hsum }, one, mono, ?_, hi⟩ + intro s x + change M (pad s * x) = f s * M x + have hs : 0 ≤ f s := by rw [← old, ← zero]; exact mono (hzero _) + apply le_antisymm + · refine (hi _ _).mpr fun a ha => ?_ + obtain ⟨b, hb, hab⟩ := hp.factor ha + exact (hf hab).trans (by rw [map_mul]; exact mul_le_mul_of_nonneg_left (lo x b hb) hs) + · rcases hs.eq_or_lt with hz | hs + · rw [← hz, zero_mul, ← zero] + exact mono (hzero _) + · rw [mul_comm, ← le_div_iff₀ hs] + refine (hi x _).mpr fun b hb => ?_ + rw [le_div_iff₀ hs, mul_comm, ← map_mul] + exact lo _ _ (by rw [hp.mul]; exact hmul _ _ _ hb) + +end MatrixMultiplicationAllFields.MatrixExponent.Prices +end + +section +/- +# Simultaneous price extension + +We work with spectral values, i.e. exponentiated unit-scale prices. +The test runs through finite lists with repetitions. It therefore +includes closures that couple arbitrarily many copies. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices + +variable {S T I : Type*} [CommSemiring T] [PartialOrder T] + +/-- Turn the linear closure bounds into a single multiplicative evaluation. -/ +theorem character_of_products + (hmul : ∀ a b c : T, a ≤ b → c * a ≤ c * b) + (hzero : ∀ a : T, 0 ≤ a) + {X : I → T} {p : I → ℝ} (hp : ∀ i, 0 ≤ p i) + (M : T →+ ℝ) (hm : Monotone M) (hm1 : 0 < M 1) (hb : ProductBound X p M) + (hlower : ∀ x ≠ 0, ∃ c, StableLE M 1 x c) + (hupper : ∀ x, ∃ c ≥ 0, StableLE M x 1 c) : + ∃ g : T →+* ℝ, Monotone g ∧ (∀ i, g (X i) ≤ p i) ∧ + ∀ a b c, StableLE M a b c → g a ≤ c * g b := by + classical + let J := {t : T × T × ℝ // StableLE M t.1 t.2.1 t.2.2 ∨ + ∃ i, X i = t.1 ∧ 1 = t.2.1 ∧ p i < t.2.2} + let A (j : J) := j.val.1 + let B (j : J) := j.val.2.1 + let C (j : J) := j.val.2.2 + have step (s : Finset J) : + ∃ N : T →+ ℝ, Monotone N ∧ 0 < N 1 ∧ ProductBound X p N ∧ + (∀ a b c, StableLE M a b c → StableLE N a b c) ∧ + (∀ j ∈ s, StableLE N (A j) (B j) (C j)) := by + induction s using Finset.induction with + | empty => exact ⟨M, hm, hm1, hb, fun _ _ _ h => h, by simp⟩ + | @insert j s _ ih => + obtain ⟨N, hn, hn1, hN, keep, hs⟩ := ih + rcases j.property with h | ⟨i, ha, hb, hc⟩ + · refine ⟨N, hn, hn1, hN, keep, fun l hl => ?_⟩ + rcases Finset.mem_insert.mp hl with rfl | hl + · exact keep _ _ _ h + · exact hs _ hl + · obtain ⟨R, hr, hr1, hR, hj, preserve⟩ := + discount hmul hzero hn hn1 (fun x => by + obtain ⟨c, hc, h⟩ := hupper x + exact ⟨c, hc, keep _ _ _ h⟩) hN i (hp i) hc + refine ⟨R, hr, hr1, hR, fun a b c h => preserve a b c (keep a b c h), fun l hl => ?_⟩ + rcases Finset.mem_insert.mp hl with hl | hl + · subst l + simpa only [A, B, C, ← ha, ← hb] using hj + · exact preserve _ _ _ (hs l hl) + let fixed : Set J := {j | StableLE M (A j) (B j) (C j)} + have hl (x : T) (hx : x ≠ 0) : ∃ j ∈ fixed, A j = 1 ∧ B j = x := by + obtain ⟨c, hc⟩ := hlower x hx + exact ⟨⟨(1, x, c), Or.inl hc⟩, hc, rfl, rfl⟩ + have hu (x : T) : ∃ j ∈ fixed, A j = x ∧ B j = 1 := by + obtain ⟨c, _, hc⟩ := hupper x + exact ⟨⟨(x, 1, c), Or.inl hc⟩, hc, rfl, rfl⟩ + have norm (s : Finset J) : ∃ N : T →+ ℝ, N 1 = 1 ∧ Monotone N ∧ + ∀ j, j ∈ fixed ∨ j ∈ s → ∀ u, N (A j * u) ≤ C j * N (B j * u) := by + obtain ⟨N, hn, hn1, _, keep, hs⟩ := step s + let R : T →+ ℝ := + { toFun := fun x => N x / N 1 + map_zero' := by rw [map_zero, zero_div] + map_add' := fun x y => by rw [map_add, add_div] } + refine ⟨R, div_self hn1.ne', fun _ _ h => div_le_div_of_nonneg_right (hn h) hn1.le, ?_⟩ + intro j hj u + change N (A j * u) / N 1 ≤ C j * (N (B j * u) / N 1) + rw [← mul_div_assoc] + have h := hj.elim (fun h => keep _ _ _ h) (hs j) + exact div_le_div_of_nonneg_right (h u) hn1.le + obtain ⟨g, hg, h⟩ := Spectrum.constrained_character hmul hzero A B C fixed hl hu norm + refine ⟨g, hg, ?_, fun a b c hab => h ⟨(a, b, c), Or.inl hab⟩⟩ + intro i + refine le_of_forall_gt_imp_ge_of_dense fun r hr => ?_ + have hl := h ⟨(X i, 1, r), Or.inr ⟨i, rfl, rfl, hr⟩⟩ + simpa only [A, B, C, map_one, mul_one] using hl + +variable [CommSemiring S] [PartialOrder S] {pad : S → T} + +theorem Padding.weighted_extension (hp : Padding pad) + (hadd : ∀ a b c : T, a ≤ b → a + c ≤ b + c) + (hmul : ∀ a b c : T, a ≤ b → c * a ≤ c * b) + (hzero : ∀ a : T, 0 ≤ a) + (f : S →+* ℝ) (hf : Monotone f) + (hunit : ∀ x ≠ 0, ∃ s, pad s ≤ x ∧ 0 < f s) + (hbound : ∀ x, ∃ (s : S) (n : ℕ), x ≤ pad s * n) + (X : I → T) (p : I → ℝ) : + (∃ g : T →+* ℝ, Monotone g ∧ (∀ s, g (pad s) = f s) ∧ (∀ i, g (X i) ≤ p i)) ↔ + ∀ w : List I, ∀ s, pad s ≤ (w.map X).prod → f s ≤ (w.map p).prod := by + constructor + · rintro ⟨g, hg, he, hu⟩ w s h + have hn (x : T) : 0 ≤ g x := by rw [← map_zero g]; exact hg (hzero _) + have ht (w : List I) : g (w.map X).prod ≤ (w.map p).prod := by + induction w with + | nil => simp + | cons i w ih => + simp only [List.map_cons, List.prod_cons, map_mul] + exact mul_le_mul (hu i) ih (hn _) ((hn _).trans (hu i)) + rw [← he] + exact (hg h).trans (ht w) + · intro h + obtain ⟨M, h1, hm, he, hu⟩ := hp.envelope hadd hmul hzero hbound f hf + have hb : ProductBound X p M := + ⟨1, fun w => by rw [one_mul]; exact (hu _ _).mpr (h w)⟩ + have hn (i : I) : 0 ≤ p i := by + simpa using h [i] 0 (by rw [hp.zero]; exact hzero _) + have hlower (x : T) (hx : x ≠ 0) : ∃ c, StableLE M 1 x c := by + obtain ⟨s, h, hs⟩ := hunit x hx + refine ⟨(f s)⁻¹, fun u => ?_⟩ + rw [le_inv_mul_iff₀ hs, one_mul, ← he, mul_comm (pad s), mul_comm x] + exact hm (hmul _ _ _ h) + have hupper (x : T) : ∃ c ≥ 0, StableLE M x 1 c := by + obtain ⟨s, n, h⟩ := hbound x + have hs : 0 ≤ f s := by + rw [← map_zero f] + exact hf ((hp.le_iff _ _).mp (hp.zero.symm ▸ hzero _)) + refine ⟨f s * (n : ℝ), mul_nonneg hs (Nat.cast_nonneg _), fun u => ?_⟩ + rw [one_mul, mul_assoc, ← nsmul_eq_mul, ← map_nsmul, nsmul_eq_mul, + ← he, ← mul_assoc, mul_comm x, mul_comm (pad s * n)] + exact hm (hmul _ _ _ h) + obtain ⟨g, hg, hb, hs⟩ := + character_of_products hmul hzero hn M hm (by rw [h1]; exact zero_lt_one) hb hlower hupper + refine ⟨g, hg, ?_, hb⟩ + intro s + apply le_antisymm + · have hl := hs (pad s) 1 (f s) (fun u => by rw [one_mul, he]) + simpa using hl + · rcases le_or_gt (f s) 0 with h | h + · exact h.trans (by rw [← map_zero g]; exact hg (hzero _)) + · have hl := hs 1 (pad s) (f s)⁻¹ (fun u => by rw [one_mul, he, inv_mul_cancel_left₀ h.ne']) + rwa [map_one, le_inv_mul_iff₀ h, mul_one] at hl + +theorem Padding.extension (hp : Padding pad) + (hadd : ∀ a b c : T, a ≤ b → a + c ≤ b + c) + (hmul : ∀ a b c : T, a ≤ b → c * a ≤ c * b) + (hzero : ∀ a : T, 0 ≤ a) (hunit : ∀ a : T, a ≠ 0 → 1 ≤ a) + (hbound : ∀ a : T, ∃ n : ℕ, a ≤ (n : T)) + (f : S →+* ℝ) (hf : Monotone f) (X : I → T) (p : I → ℝ) : + (∃ g : T →+* ℝ, Monotone g ∧ (∀ s, g (pad s) = f s) ∧ (∀ i, g (X i) ≤ p i)) ↔ + ∀ w : List I, ∀ s, pad s ≤ (w.map X).prod → f s ≤ (w.map p).prod := by + refine hp.weighted_extension hadd hmul hzero f hf ?_ ?_ X p + · exact fun x hx => ⟨1, by rw [hp.one]; exact hunit x hx, by simp⟩ + · intro x + obtain ⟨n, hn⟩ := hbound x + exact ⟨1, n, by simpa only [hp.one, one_mul] using hn⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Prices +end + +/- # Assisted costs and simultaneous interpolation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices + +variable {S T : Type*} [CommSemiring S] [CommSemiring T] [PartialOrder S] [PartialOrder T] + +/-- Uniform hypotheses for ordinary and valued price extensions. -/ +structure ExtensionData (pad : S → T) (f : S →+* ℝ) : Prop where + padLaw : Padding pad + mono : Monotone f + add (a b c : T) : a ≤ b → a + c ≤ b + c + mul (a b c : T) : a ≤ b → c * a ≤ c * b + zero (a : T) : 0 ≤ a + lower : ∀ x ≠ 0, ∃ s, pad s ≤ x ∧ 0 < f s + upper : ∀ x, ∃ (s : S) (n : ℕ), x ≤ pad s * n + +/-- The exponentiated assisted cost. All positive powers and all restrictions +to a tensor with trivial legs at the added sites are tested. -/ +def assisted (pad : S → T) (f : S →+* ℝ) (A : T) : ℝ := + sSup {r | ∃ (m : ℕ) (B : S), 0 < m ∧ pad B ≤ A ^ m ∧ r = f B ^ (m : ℝ)⁻¹} + +namespace ExtensionData +variable {pad : S → T} {f : S →+* ℝ} (H : ExtensionData pad f) +include H + +theorem extension_iff {I : Type*} (X : I → T) (p : I → ℝ) : + (∃ g : T →+* ℝ, Monotone g ∧ (∀ B, g (pad B) = f B) ∧ (∀ i, g (X i) ≤ p i)) ↔ + ∀ w : List I, ∀ B, pad B ≤ (w.map X).prod → f B ≤ (w.map p).prod := + H.padLaw.weighted_extension H.add H.mul H.zero f H.mono H.lower H.upper X p + +theorem exists_extension : + ∃ g : T →+* ℝ, Monotone g ∧ ∀ B, g (pad B) = f B := by + obtain ⟨g, hg, he, _⟩ := (H.extension_iff (fun _ : Empty => 1) (fun _ => 1)).mpr + (by + intro w B h + cases w with + | nil => + change pad B ≤ 1 at h + rw [← H.padLaw.one] at h + simpa using H.mono ((H.padLaw.le_iff B 1).mp h) + | cons i _ => exact i.elim) + exact ⟨g, hg, he⟩ + +private theorem nonneg (A : S) : 0 ≤ f A := by + rw [← map_zero f] + exact H.mono ((H.padLaw.le_iff _ _).mp (H.padLaw.zero.symm ▸ H.zero _)) + +private theorem value_nonneg {g : T →+* ℝ} (hg : Monotone g) (B : T) : + 0 ≤ g B := by simpa using hg (H.zero B) + +theorem assisted_minimum (A : T) : + IsLeast {r | ∃ g : T →+* ℝ, + Monotone g ∧ (∀ B, g (pad B) = f B) ∧ g A = r} (assisted pad f A) := by + let V : Set ℝ := {r | ∃ (m : ℕ) (B : S), 0 < m ∧ pad B ≤ A ^ m ∧ + r = f B ^ (m : ℝ)⁻¹} + have hv : 0 ∈ V := + ⟨1, 0, by decide, by rw [H.padLaw.zero]; exact H.zero _, by simp⟩ + have upper (g : T →+* ℝ) (hg : Monotone g) (he : ∀ B, g (pad B) = f B) : + g A ∈ upperBounds V := by + rintro _ ⟨m, B, hm, hB, rfl⟩ + rw [Real.rpow_inv_le_iff_of_pos (H.nonneg _) (H.value_nonneg hg _) (Nat.cast_pos.mpr hm), + Real.rpow_natCast, ← map_pow, ← he] + exact hg hB + have lower (g : T →+* ℝ) (hg : Monotone g) (he : ∀ B, g (pad B) = f B) : + assisted pad f A ≤ g A := csSup_le ⟨0, hv⟩ (upper g hg he) + have hb : BddAbove V := by + obtain ⟨g, hg, he⟩ := H.exists_extension + exact ⟨g A, upper g hg he⟩ + have hp : 0 ≤ assisted pad f A := le_csSup hb hv + have test (m : ℕ) (B : S) (h : pad B ≤ A ^ m) : f B ≤ assisted pad f A ^ m := by + by_cases hm : m = 0 + · subst m + rw [pow_zero, ← H.padLaw.one] at h + simpa using H.mono ((H.padLaw.le_iff B 1).mp h) + · have hm' := Nat.pos_of_ne_zero hm + rw [← Real.rpow_natCast, ← Real.rpow_inv_le_iff_of_pos (H.nonneg _) hp + (Nat.cast_pos.mpr hm')] + exact le_csSup hb ⟨m, B, hm', h, rfl⟩ + obtain ⟨g, hg, he, hA⟩ := (H.extension_iff (fun _ : Unit => A) (fun _ => assisted pad f A)).mpr + (by + intro w B h + have hm : pad B ≤ (List.replicate w.length A).prod := by simpa using h + have hA := hm.trans_eq (List.prod_replicate w.length A) + simpa [List.prod_replicate] using test w.length B hA) + refine ⟨⟨g, hg, he, le_antisymm (hA ()) (lower g hg he)⟩, ?_⟩ + rintro _ ⟨g', hg', he', rfl⟩ + exact lower g' hg' he' + +/-- The product test in terms of assisted costs. -/ +theorem assisted_extension_iff {I : Type*} + (X : I → T) (p : I → ℝ) : + (∃ g : T →+* ℝ, Monotone g ∧ + (∀ B, g (pad B) = f B) ∧ (∀ i, g (X i) ≤ p i)) ↔ + ∀ w : List I, assisted pad f (w.map X).prod ≤ (w.map p).prod := by + constructor + · rintro ⟨g, hg, he, hu⟩ w + refine ((H.assisted_minimum _).2 ⟨g, hg, he, rfl⟩).trans ?_ + induction w with + | nil => simp + | cons i w ih => + simp only [List.map_cons, List.prod_cons] + refine (g.map_mul _ _).trans_le ?_ + exact mul_le_mul (hu i) ih (H.value_nonneg hg _) ((H.value_nonneg hg _).trans (hu i)) + · intro h + refine (H.extension_iff X p).mpr fun w B hB => ?_ + obtain ⟨g, hg, he, hA⟩ := (H.assisted_minimum (w.map X).prod).1 + exact ((he B).symm.trans_le (hg hB)).trans (hA.trans_le (h w)) + +/-- Interpolate all tensor evaluations at once, preserving the old price. -/ +theorem interpolate + (g h : T →+* ℝ) (hg : Monotone g) (hh : Monotone h) + (eg : ∀ B, g (pad B) = f B) (eh : ∀ B, h (pad B) = f B) + {t : ℝ} (ht : 0 ≤ t) (ht' : t ≤ 1) : + ∃ k : T →+* ℝ, Monotone k ∧ (∀ B, k (pad B) = f B) ∧ + ∀ A, k A ≤ g A ^ t * h A ^ (1 - t) := by + let p (A : T) := g A ^ t * h A ^ (1 - t) + have ep (w : List (T)) : p w.prod = (w.map p).prod := by + induction w with + | nil => simp [p] + | cons X w ih => + rw [List.prod_cons, List.map_cons, List.prod_cons, ← ih] + unfold p + rw [map_mul, map_mul, Real.mul_rpow (H.value_nonneg hg _) (H.value_nonneg hg _), + Real.mul_rpow (H.value_nonneg hh _) (H.value_nonneg hh _)] + exact mul_mul_mul_comm _ _ _ _ + apply (H.extension_iff id p).mpr + intro w B hB + rw [List.map_id] at hB + rw [← ep] + have hz := H.nonneg B + have ht1 := sub_nonneg.mpr ht' + have e : f B = f B ^ t * f B ^ (1 - t) := by + rw [← Real.rpow_add_of_nonneg hz ht ht1, add_sub_cancel, Real.rpow_one] + rw [e] + exact mul_le_mul (Real.rpow_le_rpow hz ((eg B).symm.trans_le (hg hB)) ht) + (Real.rpow_le_rpow hz ((eh B).symm.trans_le (hh hB)) ht1) + (Real.rpow_nonneg hz _) (Real.rpow_nonneg (H.value_nonneg hg _) _) + +end ExtensionData +end MatrixMultiplicationAllFields.MatrixExponent.Prices +end + +/- +# Extending an ordinary tensor price + +We use spectral values so that zero needs no infinite logarithm. +By `pad_le_ofRaw_iff`, testing `pad U B ≤ A` is equivalent (for +monotone prices) to testing every simultaneous closure of A at U. +Each functional has access to the entire local space of its site. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S U : Type} [Field K] [Fintype S] [Nonempty S] [Fintype U] + +private theorem data (f : Tensor K S →+* ℝ) (hf : Monotone f) : + Prices.ExtensionData (pad U) f := by + refine ⟨padding U, hf, add_le_add_right, mul_le_mul_left, zero_le, ?_, ?_⟩ + · intro x hx + exact ⟨1, by rw [(padding U).one]; exact one_le x hx, by simp⟩ + · intro x + obtain ⟨n, hn⟩ := exists_bound x + exact ⟨1, n, by rw [(padding U).one, one_mul]; exact hn⟩ + +theorem extension_iff {I : Type*} (f : Tensor K S →+* ℝ) (hf : Monotone f) + (X : I → Tensor K (S ⊕ U)) (p : I → ℝ) : + (∃ g : Tensor K (S ⊕ U) →+* ℝ, Monotone g ∧ + (∀ B, g (pad U B) = f B) ∧ (∀ i, g (X i) ≤ p i)) ↔ + ∀ w : List I, ∀ B, pad U B ≤ (w.map X).prod → f B ≤ (w.map p).prod := + (data (U := U) f hf).extension_iff X p + +theorem exists_extension (f : Tensor K S →+* ℝ) (hf : Monotone f) : + ∃ g : Tensor K (S ⊕ U) →+* ℝ, Monotone g ∧ ∀ B, g (pad U B) = f B := + (data (U := U) f hf).exists_extension + +/-- The exponentiated assisted cost. All positive powers and all restrictions +to a tensor with trivial legs at the added sites are tested. -/ +def assisted (f : Tensor K S →+* ℝ) (A : Tensor K (S ⊕ U)) : ℝ := + Prices.assisted (pad U) f A + +theorem assisted_minimum (f : Tensor K S →+* ℝ) (hf : Monotone f) (A : Tensor K (S ⊕ U)) : + IsLeast {r | ∃ g : Tensor K (S ⊕ U) →+* ℝ, + Monotone g ∧ (∀ B, g (pad U B) = f B) ∧ g A = r} (assisted f A) := + (data (U := U) f hf).assisted_minimum A + +/-- The product test in terms of assisted costs. -/ +theorem assisted_extension_iff {I : Type*} (f : Tensor K S →+* ℝ) (hf : Monotone f) + (X : I → Tensor K (S ⊕ U)) (p : I → ℝ) : + (∃ g : Tensor K (S ⊕ U) →+* ℝ, Monotone g ∧ + (∀ B, g (pad U B) = f B) ∧ (∀ i, g (X i) ≤ p i)) ↔ + ∀ w : List I, assisted f (w.map X).prod ≤ (w.map p).prod := + (data (U := U) f hf).assisted_extension_iff X p + +/-- Interpolate all tensor evaluations at once, preserving the old price. -/ +theorem interpolate (f : Tensor K S →+* ℝ) (hf : Monotone f) + (g h : Tensor K (S ⊕ U) →+* ℝ) (hg : Monotone g) (hh : Monotone h) + (eg : ∀ B, g (pad U B) = f B) (eh : ∀ B, h (pad U B) = f B) + {t : ℝ} (ht : 0 ≤ t) (ht' : t ≤ 1) : + ∃ k : Tensor K (S ⊕ U) →+* ℝ, Monotone k ∧ (∀ B, k (pad U B) = f B) ∧ + ∀ A, k A ≤ g A ^ t * h A ^ (1 - t) := + (data (U := U) f hf).interpolate g h hg hh eg eh ht ht' + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/WireRecovery.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/WireRecovery.lean new file mode 100644 index 0000000000..24f44d001e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Prices/WireRecovery.lean @@ -0,0 +1,919 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Span +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.TableMotion +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Width +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Coupled + +/-! +# From one-site distance tests to saturation + +A near-maximal level below energy `n` absorbs the logarithmic probe +error. Reusing the optimizing energies at scale `n+1` then gives a lower +bound on the increment of the unnormalized objective. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Sphere Real Filter Finset +open scoped Topology + +private theorem probe_bound (U C η : ℝ) (hU : 0 ≤ U) (hη : 0 < η) : + ∀ᶠ n : ℕ in atTop, ∀ w δ : ℝ, 0 ≤ w → w ≤ U → 0 ≤ δ → + (∀ g ≤ n, δ * log (Fintype.card (Level 1 g)) ≤ w * entropy * sqrt g + C * log n) → + δ ≤ w + η := by + have hc := entropy_pos + let b := entropy * η / 2 + have hb : 0 < b := by unfold b; positivity + let a := b / (U + η) + have ha : 0 < a := div_pos hb (by positivity) + have hprod : a * (U + η) = b := div_mul_cancel₀ _ (by positivity) + have ha' : a < entropy := by + apply (div_lt_iff₀ (show 0 < U + η by positivity)).mpr + unfold b + nlinarith + have hlev := (tendsto_sqrt_atTop.comp tendsto_natCast_atTop_atTop).eventually + (entropy_attained ha) + have herr := ((isLittleO_log_rpow_atTop (by norm_num : 0 + < (1 : ℝ) / 2)).const_mul_left C).bound hb + filter_upwards [hlev, tendsto_natCast_atTop_atTop.eventually herr, eventually_gt_atTop 0] + with n hn hl hn₀ + intro w δ hw hw' hd h + obtain ⟨g, hg, ht⟩ := hn + simp only [Function.comp_apply, sq_sqrt (Nat.cast_nonneg n), Nat.cast_le] at hg ht + have he : C * log n ≤ b * sqrt n := by + apply le_trans (le_abs_self _) + simpa only [norm_eq_abs, ← sqrt_eq_rpow, abs_of_nonneg (sqrt_nonneg _)] using hl + have hk : δ * (entropy - a) ≤ w * entropy + b := by + apply (mul_le_mul_iff_left₀ (show 0 < sqrt (n : ℝ) by positivity)).mp + calc + _ ≤ δ * log (Fintype.card (Level 1 g)) := by rw [mul_assoc]; gcongr + _ ≤ w * entropy * sqrt g + C * log n := h g hg + _ ≤ w * entropy * sqrt n + b * sqrt n := by gcongr + _ = _ := (add_mul _ _ _).symm + apply (mul_le_mul_iff_left₀ (sub_pos.mpr ha')).mp + have := mul_le_mul_of_nonneg_left hw' ha.le + unfold b at hprod hk + linarith + +variable {I : Type*} [Fintype I] + +/-- The threshold depends only on a bound on the variance, the width cap +and the probe error, independently of the underlying spectral point. -/ +theorem uniform_gap (D₀ U C : ℝ) (hU : 0 ≤ U) (N : ℕ) (ε : ℝ) (hε : 0 < ε) : + ∀ᶠ n : ℕ in atTop, ∀ (D : ℝ) (w : ℕ → I → ℝ) (B : ℕ → ℝ), D ≤ D₀ → + (∀ m ≥ N, 0 ≤ B m) → (∀ m ≥ N, ∀ i, 0 ≤ w m i ∧ w m i ≤ U) → + (∀ m ≥ N, ∃ δ : I → ℝ, (∀ i, 0 ≤ δ i) ∧ D ≤ ∑ i, δ i ^ 2 ∧ + ∀ i g, g ≤ m → δ i * log (Fintype.card (Level 1 g)) ≤ + w m i * entropy * sqrt g + C * log m) → + (∀ m ≥ N, (∑ i, w m i ^ 2) * ((m : ℝ) / (m + 1)) ≤ 2 * (B (m + 1) - B m)) → + D < 2 * (B n / n) + ε := by + let L := (Fintype.card I : ℝ) * (2 * U + 1) + have hL : 0 ≤ L := by unfold L; positivity + let η := min 1 ((ε / 4) / (L + 1)) + have hη : 0 < η := lt_min zero_lt_one (by positivity) + have hη' : η ≤ 1 := min_le_left _ _ + have hLη : L * η < ε / 4 := by + have := (le_div_iff₀ (by positivity : 0 < L + 1)).mp (show η ≤ _ from min_le_right _ _) + linarith + obtain ⟨M, hM⟩ := eventually_atTop.mp ((eventually_ge_atTop N).and + ((tendsto_natCast_atTop_atTop.eventually_ge_atTop (D₀ / (ε / 4))).and (probe_bound U C η hU + hη))) + filter_upwards [eventually_ge_atTop M, eventually_gt_atTop 0, + tendsto_natCast_atTop_atTop.eventually_gt_atTop (D₀ * M / (ε / 2))] with n hn hn₀ hlarge + intro D w B hD₀ hB hw ht hstep + have step (m : ℕ) (hm : M ≤ m) : D - ε / 2 ≤ 2 * (B (m + 1) - B m) := by + obtain ⟨hN, hm', hb⟩ := hM m hm + obtain ⟨δ, hδ, hD, hprobe⟩ := ht m hN + have hi (i : I) : δ i ^ 2 ≤ w m i ^ 2 + (2 * U + 1) * η := by + have hh := hb _ _ (hw m hN i).1 (hw m hN i).2 (hδ i) (hprobe i) + have := pow_le_pow_left₀ (hδ i) hh 2 + nlinarith only [this, mul_le_mul_of_nonneg_right (hw m hN i).2 hη.le, + mul_le_mul_of_nonneg_right hη' hη.le] + have hh := hD.trans (sum_le_sum (fun i _ => hi i)) + rw [sum_add_distrib, sum_const, card_univ, nsmul_eq_mul, ← mul_assoc] at hh + have hb' : D - ε / 4 ≤ ∑ i, w m i ^ 2 := by unfold L at hLη; linarith + refine le_trans ?_ (hstep m hN) + rw [← mul_div_assoc, le_div_iff₀ (by positivity)] + rw [div_le_iff₀ (by positivity : 0 < ε / 4)] at hm' + linarith only [mul_le_mul_of_nonneg_right hb' (Nat.cast_nonneg m), hε, hm', hD₀] + have accum (k : ℕ) (hk : M ≤ k) : (D - ε / 2) * (k : ℝ) - D₀ * M ≤ 2 * B k := by + induction k, hk using Nat.le_induction with + | base => + have := mul_le_mul_of_nonneg_right (show D - ε / 2 ≤ D₀ by linarith) (Nat.cast_nonneg M) + linarith only [this, hB M (hM M le_rfl).1] + | succ k hk ih => push_cast; linarith only [ih, step k hk] + rw [div_lt_iff₀ (half_pos hε)] at hlarge + rw [← mul_div_assoc, ← sub_lt_iff_lt_add, lt_div_iff₀ (by positivity)] + linarith only [hlarge, accum n hn] + +theorem optimizer_limits {D U C : ℝ} (hU : 0 ≤ U) (r : I → ℝ) + (w : ℕ → I → ℝ) (B : ℕ → ℝ) + (hpos : ∀ᶠ n in atTop, 0 ≤ B n) + (hw : ∀ᶠ n in atTop, ∀ i, 0 ≤ w n i ∧ w n i ≤ U) + (ht : ∀ᶠ n : ℕ in atTop, ∃ δ : I → ℝ, (∀ i, 0 ≤ δ i) ∧ D ≤ ∑ i, δ i ^ 2 ∧ + ∀ i g, g ≤ n → δ i * log (Fintype.card (Level 1 g)) ≤ + w n i * entropy * sqrt g + C * log n) + (hu : ∀ᶠ n : ℕ in atTop, 2 * (B n / n) + ∑ i, (w n i - r i) ^ 2 ≤ D) + (hl : ∀ᶠ n : ℕ in atTop, (∑ i, w n i ^ 2) * ((n : ℝ) / (n + 1)) ≤ 2 * (B (n + 1) - B n)) : + (∀ i, Tendsto (fun n => w n i) atTop (𝓝 (r i))) ∧ + Tendsto (fun n => B n / n) atTop (𝓝 (D / 2)) := by + have hB : Tendsto (fun n => B n / n) atTop (𝓝 (D / 2)) := by + apply tendsto_order.mpr + constructor + · intro a ha + obtain ⟨N, hN⟩ := eventually_atTop.mp (hpos.and (hw.and (ht.and hl))) + filter_upwards [uniform_gap (I := I) D U C hU N (D - 2 * a) (by linarith)] with n hn + have := hn D w B le_rfl (fun m hm => (hN m hm).1) (fun m hm => (hN m hm).2.1) + (fun m hm => (hN m hm).2.2.1) (fun m hm => (hN m hm).2.2.2) + linarith + · intro a ha + filter_upwards [hu] with n hn + have : 0 ≤ ∑ i, (w n i - r i) ^ 2 := sum_nonneg (fun _ _ => sq_nonneg _) + linarith + refine ⟨fun i => ?_, hB⟩ + have h₀ : Tendsto (fun n => D - 2 * (B n / n)) atTop (𝓝 0) := by + convert (hB.const_mul 2).const_sub D using 1 + congr 1; ring + have hsq : Tendsto (fun n => (w n i - r i) ^ 2) atTop (𝓝 0) := by + refine squeeze_zero' (Eventually.of_forall fun _ => sq_nonneg _) ?_ h₀ + filter_upwards [hu] with n hn + have := single_le_sum (fun j (_ : j ∈ univ) => sq_nonneg (w n j - r j)) (mem_univ i) + linarith + apply tendsto_sub_nhds_zero_iff.mp + apply tendsto_zero_iff_norm_tendsto_zero.mpr + simpa only [norm_eq_abs, sqrt_sq_eq_abs, sqrt_zero] using hsq.sqrt + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# The cost of a separated coefficient array and a linear combination + +Use natural logarithms for leg dimensions. Wire prices on binary legs +are distances, so the corresponding array prices are multiplied by +the natural logarithm of two. +-/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] +variable {Y : Type*} [MetricSpace Y] {x : A → Y} {P : Tensor F A → ℝ} + +open scoped Classical in +/-- The condition `∀ D : ℝ, 0 < D → (∀ a b, dist (x a) (x b) ≤ D) → Realized x P D` on the +specified data. -/ +def ExtendsAt (P : Tensor F A → ℝ) (x : A → Y) : Prop := + ∀ D : ℝ, 0 < D → (∀ a b, dist (x a) (x b) ≤ D) → Realized x P D + +open scoped Classical in +theorem ExtendsAt.prices (h : ExtendsAt P x) {U : Type} [Fintype U] + [DecidableEq U] [Nonempty U] (z : U → Y) : + ∃ d : ℝ, 0 ≤ d ∧ ∃ f : Tensor F (A ⊕ U) →+* ℝ, Monotone f ∧ + (∀ T, P T * Real.log 2 = d * Real.log (f (Tensor.pad U T))) ∧ + ∀ i j, d * Tensor.dist f i j = dist (Sum.elim x z i) (Sum.elim x z j) := by + let r (i : (A ⊕ U) × (A ⊕ U)) := dist (Sum.elim x z i.1) (Sum.elim x z i.2) + obtain ⟨B, hB⟩ := (Set.finite_range r).bddAbove + let D := max B 1 + have hd : 0 < D := lt_of_lt_of_le zero_lt_one (le_max_right _ _) + have hb (i j : A ⊕ U) : dist (Sum.elim x z i) (Sum.elim x z j) ≤ D := + (hB ⟨(i, j), rfl⟩).trans (le_max_left _ _) + have hh := h D hd (fun i j => hb (.inl i) (.inl j)) + obtain ⟨_, ⟨d, h₀, f, hf, rfl⟩, he, he'⟩ := hh.2 U z + (fun i j => (hb i j).trans (by linarith)) + refine ⟨d, h₀.1, f, hf, ?_, he'⟩ + intro T + rw [← he, Tensor.values, mul_assoc, div_mul_cancel₀ _ (Real.log_pos (by norm_num)).ne'] + +variable (X : A → Type) [∀ i, Fintype (X i)] + +open scoped Classical in +/-- The quantity computed by `P (Tensor.ofRaw (Raw.ofTable X T)) * Real.log 2`. -/ +def tablePrice (P : Tensor F A → ℝ) (T : (∀ i, X i) → F) : ℝ := + P (Tensor.ofRaw (Raw.ofTable X T)) * Real.log 2 + +open scoped Classical in +/-- Send the two groups from distinct sites with an intermediate leg +whose dimension is the number of separated summands. -/ +theorem ExtendsAt.cut (h : ExtendsAt P x) (T : (∀ i, X i) → F) (B : Finset A) + {J : Type} [Fintype J] (L R : J → (∀ i, X i) → F) + (hs : ∀ v, T v = ∑ j, L j v * R j v) + (hl : ∀ j v w, (∀ i ∈ B, v i = w i) → L j v = L j w) + (hr : ∀ j v w, (∀ i ∉ B, v i = w i) → R j v = R j w) (m o : Y) : + tablePrice X P T ≤ dist o m * Real.log (Fintype.card J) + + ∑ i, dist (if i ∈ B then m else o) (x i) * Real.log (Fintype.card (X i)) := by + let z (b : Bool) := if b then m else o + obtain ⟨d, hd, f, hf, he, hw⟩ := h.prices z + let U := Raw.ofTable X T + unfold tablePrice + rw [he] + by_cases hU : Tensor.ofRaw U = 0 + · rw [show Tensor.ofRaw (Raw.ofTable X T) = 0 from hU, (Tensor.padding Bool).zero, + map_zero, Real.log_zero, mul_zero] + positivity + have hJ : 0 < Fintype.card J := by + by_contra! hj + have : IsEmpty J := Fintype.card_eq_zero_iff.mp (by omega) + apply hU + refine (Tensor.ofRaw_eq_zero _).mpr ?_ + change ∀ v : (∀ i, X i), (Raw.ofTable X T).coeff v = 0 + simp [hs] + let a : A ⊕ Bool := .inr true + let b : A ⊕ Bool := .inr false + let p (i : A) := if i ∈ B then a else b + have hm : Tensor.place p (Tensor.ofRaw U) ≤ Tensor.wire F a b (Fintype.card J) := + Tensor.separated_le X T (· ∈ B) L R hs hl hr a b + have hcut := Real.log_le_log (Tensor.price_place_pos f hf p hU) (hf hm) + rw [Tensor.price_wire f hf _ _ hJ, Real.log_rpow (Nat.cast_pos.mpr hJ)] at hcut + have hc := mul_le_mul_of_nonneg_left hcut hd + rw [← mul_assoc, hw, show Sum.elim x z a = m from rfl, show Sum.elim x z b = o from rfl, + dist_comm m o] at hc + have ht := (abs_sub_le_iff.mp (Tensor.price_transport f hf U hU p Sum.inl)).2 + rw [Tensor.place_inl] at ht + have hh := mul_le_mul_of_nonneg_left ht hd + simp only [mul_sub, Finset.mul_sum, ← mul_assoc, hw, Sum.elim_inl] at hh + have hp (i : A) : Sum.elim x z (p i) = if i ∈ B then m else o := by + by_cases hi : i ∈ B <;> simp [p, hi, z, a, b] + simp only [hp] at hh + change _ ≤ ∑ i, dist (if i ∈ B then m else o) (x i) * Real.log (Fintype.card (X i)) at hh + change d * Real.log (f (Tensor.pad Bool (Tensor.ofRaw U))) ≤ _ + linarith only [hc, hh] + +open scoped Classical in +/-- In a finite span one summand has cost within the logarithm of the +number of summands, times a fixed scale, of the total cost. -/ +theorem ExtendsAt.span (h : ExtendsAt P x) : + ∃ d : ℝ, 0 ≤ d ∧ ∀ (X : A → Type) [∀ i, Fintype (X i)] + (T : (∀ i, X i) → F) (s : Finset ((∀ i, X i) → F)), + 0 < tablePrice X P T → T ∈ Submodule.span F (s : Set _) → + ∃ v ∈ s, tablePrice X P T ≤ tablePrice X P v + d * Real.log s.card := by + obtain ⟨d, hd, f, hf, he, _⟩ := h.prices x + refine ⟨d, hd, fun X _ T s hp ht => ?_⟩ + let V (v : (∀ i, X i) → F) := Tensor.ofRaw (Raw.ofTable X v) + let val (v : (∀ i, X i) → F) := f (Tensor.pad A (V v)) + have hprice (v) : tablePrice X P v = d * Real.log (val v) := he _ + have hpos : 0 < val T := by + have hn : 0 ≤ val T := by simpa using hf (Tensor.zero_le (Tensor.pad A (V T))) + refine lt_of_le_of_ne hn (fun hz => ?_) + simp [hprice, ← hz] at hp + obtain ⟨c, _, hc⟩ := Submodule.mem_span_finset.mp ht + have hrel : V T ≤ ∑ v ∈ s, V v := by + rw [← Finset.sum_coe_sort] + apply Tensor.span_le X T Subtype.val (fun v => c v.val) + intro z + have hh := congrFun hc z + rw [Finset.sum_coe_sort s (fun v => c v * v z)] + simpa [Finset.sum_apply] using hh.symm + have subadd (u : Finset ((∀ i, X i) → F)) : + f (Tensor.pad A (∑ v ∈ u, V v)) ≤ ∑ v ∈ u, val v := by + induction u using Finset.induction with + | empty => simp [(Tensor.padding A).zero] + | @insert v u hv ih => + rw [Finset.sum_insert hv, Finset.sum_insert hv] + have ha := hf ((Tensor.padding A).add_le (V v) (∑ w ∈ u, V w)) + rw [map_add] at ha + exact ha.trans (add_le_add_right ih _) + have hsum : val T ≤ ∑ v ∈ s, val v := + (hf (((Tensor.padding A).le_iff _ _).mpr hrel)).trans (subadd s) + have hne : s.Nonempty := Finset.nonempty_iff_ne_empty.mpr fun he => by + rw [he, Finset.sum_empty] at hsum + exact hpos.not_ge hsum + obtain ⟨v, hv, hm⟩ := Finset.exists_max_image s val hne + have hh : val T ≤ s.card * val v := calc + _ ≤ ∑ u ∈ s, val u := hsum + _ ≤ ∑ _u ∈ s, val v := Finset.sum_le_sum hm + _ = _ := by simp + have hsc : 0 < (s.card : ℝ) := Nat.cast_pos.mpr hne.card_pos + have hv' : 0 < val v := (mul_pos_iff_of_pos_left hsc).mp (hpos.trans_le hh) + have hl := Real.log_le_log hpos hh + rw [Real.log_mul hsc.ne' hv'.ne'] at hl + refine ⟨v, hv, ?_⟩ + rw [hprice, hprice, ← mul_add, add_comm] + exact mul_le_mul_of_nonneg_left hl hd + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- The unit-mass sphere price profile in doubled energy units. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Sphere Spectral Filter +open scoped Topology + +/-- The quantity computed by `Sphere.entropy * Real.sqrt e`. -/ +def width (e : ℕ) := Sphere.entropy * Real.sqrt e + +theorem width_nonneg (e : ℕ) : 0 ≤ width e := + mul_nonneg entropy_pos.le (Real.sqrt_nonneg _) + +theorem width_sq (e : ℕ) : width e ^ 2 = entropy ^ 2 * e := by + rw [width, mul_pow, Real.sq_sqrt (Nat.cast_nonneg _)] + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + +/-- The indexed operation `wick (fun i j => fieldKernel (z i.1, i.2) (z j.1, j.2)) (inputs x)`. -/ +def sphereForm (z : A → F) (e : A → ℕ) (x : States 1 e) : F := + wick (fun i j => fieldKernel (z i.1, i.2) (z j.1, j.2)) (inputs x) + +/-- The indexed operation `Tensor.ofRaw (Raw.ofTable (fun i => Level 1 (e i)) (sphereForm z +e))`. -/ +def sphereTensor (z : A → F) (e : A → ℕ) : Tensor F A := + Tensor.ofRaw (Raw.ofTable (fun i => Level 1 (e i)) (sphereForm z e)) + +/-- The indexed operation `tablePrice (fun i => Level 1 (e i)) P (sphereForm z e)`. -/ +def spherePrice (P : Tensor F A → ℝ) (z : A → F) (e : A → ℕ) : ℝ := + tablePrice (fun i => Level 1 (e i)) P (sphereForm z e) + +/-- Unit-mass saturation at the specified point placement and sphere +positions, with a price compatible with all auxiliary placements. -/ +def Saturation (F : Type) [Field F] (Y : Type*) [MetricSpace Y] : Prop := + ∀ {A : Type} [Fintype A] [DecidableEq A] [Nonempty A] (x : A → Y) (o : Y), Bary x o → + ∀ z : A → F, Function.Injective z → + ∃ P : Tensor F A → ℝ, ExtendsAt P x ∧ ∃ e : ℕ → A → ℕ, + (∀ i, Tendsto (fun n => width (e n i) / (n : ℝ)) atTop (𝓝 (dist o (x i)))) ∧ + Tendsto (fun n => spherePrice P z (e n) / (n : ℝ)) atTop (𝓝 (∑ i, dist o (x i) ^ 2)) + +variable {Y : Type*} [MetricSpace Y] {x : A → Y} {P : Tensor F A → ℝ} + +theorem ExtendsAt.spherePrice_nonneg (h : ExtendsAt P x) (z : A → F) (e : A → ℕ) : + 0 ≤ spherePrice P z e := by + obtain ⟨d, hd, f, hf, he, _⟩ := h.prices x + unfold spherePrice tablePrice + rw [he] + apply mul_nonneg hd + generalize Tensor.pad (K := F) (S := A) A _ = T + by_cases hT : T = 0 + · simp [hT] + exact Real.log_nonneg (Tensor.value_one_le hf hT) + +theorem ExtendsAt.spherePrice_le (h : ExtendsAt P x) (z : A → F) (e : A → ℕ) (o : Y) : + spherePrice P z e ≤ ∑ i, dist o (x i) * width (e i) := by + have hc := h.cut (fun i => Level 1 (e i)) (sphereForm z e) ∅ + (fun (_ : Unit) _ => 1) (fun _ v => sphereForm z e v) + (by simp) (by simp) (fun _ v w he => congrArg _ (funext (fun i => he i (by simp)))) o o + simp only [dist_self, zero_mul, zero_add, ite_self] at hc + exact hc.trans (Finset.sum_le_sum (fun i _ => mul_le_mul_of_nonneg_left (entropy_bound _) + dist_nonneg)) + +theorem ExtendsAt.spherePrice_zero (h : ExtendsAt P x) {z : A → F} {e : A → ℕ} + (he : sphereForm z e = 0) : spherePrice P z e = 0 := by + have ht : Tensor.ofRaw (Raw.ofTable (fun i => Level 1 (e i)) (sphereForm z e)) = 0 := by + refine (Tensor.ofRaw_eq_zero _).mpr ?_ + change ∀ v : States 1 e, (Raw.ofTable (fun i => Level 1 (e i)) (sphereForm z e)).coeff v = 0 + simp [he] + obtain ⟨d, hd, f, hf, hp, _⟩ := h.prices x + rw [spherePrice, tablePrice, ht, hp, (Tensor.padding A).zero, map_zero, Real.log_zero, mul_zero] + +omit [DecidableEq A] [Nonempty A] in +theorem sphereForm_vacuum (z : A → F) : sphereForm z (fun _ => 0) ≠ 0 := by + let w : States 1 (fun _ : A => 0) := fun _ => ⟨⟨[], by simp⟩, rfl⟩ + intro h + have he := congrFun h w + have hw : marksAt w = fun _ => [] := rfl + have hf (l : List A) : l.flatMap (marksAt w) = [] := by + induction l with + | nil => rfl + | cons j l ih => rw [List.flatMap_cons, ih, hw]; rfl + simp [sphereForm, inputs, hf] at he + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Quadratic objective and one-site probes for a maximizing sphere -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Sphere Spectral Filter + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + +/-- The quantity computed by `spherePrice P z e - (∑ i, width (e i) ^ 2) / (2 * n)`. -/ +def objective (P : Tensor F A → ℝ) (z : A → F) (n : ℕ) (e : A → ℕ) : ℝ := + spherePrice P z e - (∑ i, width (e i) ^ 2) / (2 * n) + +/-- The finite optimizer test uses only a single extra site and probes of +doubled energy at most `n`. -/ +def Controlled (F : Type) [Field F] (Y : Type*) [MetricSpace Y] : Prop := + ∀ {A : Type} [Fintype A] [DecidableEq A] [Nonempty A] (x : A → Y) (o : Y), Bary x o → + ∀ z : A → F, Function.Injective z → + ∃ P : Tensor F A → ℝ, ExtendsAt P x ∧ ∀ R : ℝ, 0 < R → ∃ C : ℝ, + ∀ᶠ n : ℕ in atTop, ∀ e : A → ℕ, (∀ h, objective P z n h ≤ objective P z n e) → + (∀ i, (e i : ℝ) ≤ R * (n : ℝ) ^ 2) → sphereForm z e ≠ 0 → + ∃ δ : A → ℝ, (∀ i, 0 ≤ δ i) ∧ (∑ i, dist o (x i) ^ 2) ≤ ∑ i, δ i ^ 2 ∧ + ∀ i g, g ≤ n → δ i * Real.log (Fintype.card (Level 1 g)) ≤ + width (e i) * width g / n + C * Real.log n + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- The product test for sphere forms with one shared moving insertion. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral + +/-- The bounded forms of type `Prop` for the given inputs. -/ +def BoundedForms (F : Type) [Field F] : Prop := + ∀ (A : Type) [Fintype A] [DecidableEq A] [Nonempty A] (f : Tensor F A →+* ℝ), + Monotone f → ∀ z : A → F, Function.Injective z → + ∀ (B : ℝ) (t : A ⊕ Unit → ℝ), (∀ i, 0 ≤ t i ∧ t i ≤ t (.inr ())) → + (∀ e, f (sphereTensor z e) ≤ Real.exp (B + ∑ i, t (.inl i) * (e i : ℝ))) → + ∀ s : F, s ∉ Set.range z → ∀ (M : ℕ) (w : List (A ⊕ Unit → ℕ)), + (∀ e ∈ w, ∀ i, e i ≤ M) → ∀ T, Tensor.pad Unit T ≤ + (w.map (sphereTensor (Sum.elim z (fun _ => s)))).prod → + f T ≤ (w.map (fun e => ((M : ℝ) + 2) ^ (Fintype.card A + 8) * + Real.exp (B + ∑ i, t i * (e i : ℝ)))).prod + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- One-site extension conditions for the sphere price argument. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral + +/-- The variance test of type `Prop` for the given inputs. -/ +def VarianceTest (F : Type) [Field F] (Y : Type*) [MetricSpace Y] : Prop := + ∀ (A : Type) [Fintype A] [DecidableEq A] [Nontrivial A] (x : A → Y) (o : Y), + Bary x o → ∃ d : ℝ, 0 ≤ d ∧ ∃ f : Tensor F A →+* ℝ, Monotone f ∧ + ExtendsAt (Tensor.values d f) x ∧ + ∀ g : Tensor F (A ⊕ Unit) →+* ℝ, Monotone g → + (∀ T, g (Tensor.pad Unit T) = f T) → + (∑ i, dist o (x i) ^ 2) ≤ ∑ i, (d * Tensor.dist g (.inl i) (.inr ())) ^ 2 + +/-- The bounded extension of type `Prop` for the given inputs. -/ +def BoundedExtension (F : Type) [Field F] : Prop := + ∀ (A : Type) [Fintype A] [DecidableEq A] [Nonempty A] (f : Tensor F A →+* ℝ), + Monotone f → ∀ z : A → F, Function.Injective z → + ∀ (B t : ℝ), 0 ≤ t → + (∀ e, f (sphereTensor z e) ≤ Real.exp (B + ∑ i, t * (e i : ℝ))) → + ∀ M : ℕ, ∃ g : Tensor F (A ⊕ Unit) →+* ℝ, Monotone g ∧ + (∀ T, g (Tensor.pad Unit T) = f T) ∧ + ∀ (s : F), s ∉ Set.range z → ∀ e : A ⊕ Unit → ℕ, (∀ i, e i ≤ M) → + g (sphereTensor (Sum.elim z (fun _ => s)) e) ≤ + ((M : ℝ) + 2) ^ (Fintype.card A + 8) * Real.exp (B + ∑ i, t * (e i : ℝ)) + +/-- The wire probe of type `Prop`, constructed using `⌊Sphere.width q (e i)⌋₊`. -/ +def WireProbe (F : Type) [Field F] : Prop := + ∀ (A : Type) [Fintype A] [DecidableEq A] [Nonempty A] (z : A → F), Function.Injective z → + ∀ (e : A → ℕ) (i : A) (q : ℕ), + let H := ⌊Sphere.width q (e i)⌋₊ + ∃ T : Finset F, (∀ s ∈ T, s ∉ Set.range z) ∧ + T.card ≤ 1 + Fintype.card A * ((∑ j, e j) + H + q) ∧ + Tensor.pad Unit (sphereTensor z e) * Tensor.wire F (.inl i) (.inr ()) + (Fintype.card (Sphere.Level 1 q)) ≤ + ∑ h ∈ Finset.range (H + 1), ∑ s ∈ T, + sphereTensor (Sum.elim z (fun _ => s)) (Sum.elim (Function.update e i h) (fun _ => q)) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Coordinates for a moving sphere insertion + +Site permutations contribute signs that are common to all basis +indices at the specified energies and all positions of the moving site. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Insertion + +open Finset Sphere Sphere.Motion + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] + +open scoped Classical in +/-- Computes the marks by the application `univ.image z`. -/ +def marks (z : A → F) : Finset F := univ.image z +open scoped Classical in +/-- Uses `⟨z i, mem_image_of_mem _ (mem_univ i)⟩` as the representation. -/ +def mark (z : A → F) (i : A) : ↥(marks z) := ⟨z i, mem_image_of_mem _ (mem_univ i)⟩ + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +abbrev energy (e : A → ℕ) (g : ℕ) : A ⊕ Unit → ℕ := Sum.elim e (fun _ => g) + +open scoped Classical in +/-- In the case `.inl i`, this construction gives `x i`. -/ +def add {e : A → ℕ} (x : States 1 e) {g : ℕ} (w : Level 1 g) : States 1 (energy e g) + | .inl i => x i + | .inr _ => w + +open scoped Classical in +/-- The indexed operation `fun j => ⟨Function.update (fun l => (x l).val) i w.val j, by by_cases +hj : j = i · subst j simpa using w.2 · simpa [hj] using (x j).2⟩`. -/ +def changeAt {e : A → ℕ} (i : A) (x : States 1 e) {h : ℕ} (w : Level 1 h) : + States 1 (Function.update e i h) := fun j => + ⟨Function.update (fun l => (x l).val) i w.val j, by + by_cases hj : j = i + · subst j + simpa using w.2 + · simpa [hj] using (x j).2⟩ + +omit [Fintype A] in +open scoped Classical in +@[simp] theorem changeAt_val {e : A → ℕ} (i : A) (x : States 1 e) {h : ℕ} (w : Level 1 h) (j : A) : + (changeAt i x w j).val = if j = i then w.val else (x j).val := by + simp [changeAt, Function.update_apply] + +open scoped Classical in +/-- Transforms the indexed data by `(univ.erase i).toList.flatMap (fun j => (x j).val.val.map +(mark z j, ·))`. -/ +def rest (z : A → F) (i : A) {e : A → ℕ} (x : States 1 e) : List (↥(marks z) × Mode 1) := + (univ.erase i).toList.flatMap (fun j => (x j).val.val.map (mark z j, ·)) + +omit [Field F] in +open scoped Classical in +theorem rest_avoids (z : A → F) (hz : Function.Injective z) (i : A) {e : A → ℕ} (x : States 1 e) : + ∀ y ∈ rest z i x, y.1 ≠ mark z i := by + intro y hy eq + obtain ⟨j, hj, hm⟩ := List.mem_flatMap.mp hy + obtain ⟨_, _, rfl⟩ := List.mem_map.mp hm + exact (mem_erase.mp (mem_toList.mp hj)).1 (hz (congrArg Subtype.val eq)) + +omit [Field F] in +open scoped Classical in +theorem weight_rest (z : A → F) (i : A) {e : A → ℕ} (x : States 1 e) : + weight (rest z i x) = ∑ j ∈ univ.erase i, e j := by + have h := weight_list x (univ.erase i).toList + rw [← List.sum_toFinset e (nodup_toList _), toList_toFinset] at h + rw [← h] + simp [weight, rest, List.map_flatMap, marksAt, Function.comp_def] + +omit [Field F] in +open scoped Classical in +@[simp] theorem rest_changeAt (z : A → F) (i : A) {e : A → ℕ} + (x : States 1 e) {h : ℕ} (w : Level 1 h) : rest z i (changeAt i x w) = rest z i x := by + apply List.flatMap_congr + intro j hj + rw [changeAt_val, ite_eq_right (mem_erase.mp (mem_toList.mp hj)).1] + +omit [DecidableEq A] in +open scoped Classical in +private theorem order (e : A → ℕ) (l : List A) (hl : univ.toList.Perm l) : + ∃ c : F, c ≠ 0 ∧ ∀ (z : A → F) (x : States 1 e), + sphereForm z e x = c * wick fieldKernel + (l.flatMap fun j => (x j).val.val.map (z j, ·)) := by + obtain ⟨n, hn⟩ := wick_perm_sites (R := F) (r := 1) e hl + refine ⟨(-1) ^ n, by simp, fun z x => ?_⟩ + let u (i : A × Mode 1) := (z i.1, i.2) + have h := hn (fun i j => fieldKernel (u i) (u j)) + (fun i j => fieldKernel_skew _ _) x [] + simp only [List.nil_append] at h + change sphereForm z e x = _ at h + rw [h, ← wick_map fieldKernel u] + simp [u, List.map_flatMap, marksAt, Function.comp_def] + +open scoped Classical in +theorem order_base (z : A → F) (i : A) (e : A → ℕ) : + ∃ c : F, c ≠ 0 ∧ ∀ x : States 1 e, sphereForm z e x = c * + wick fieldKernel ((x i).val.val.map (z i, ·) ++ spectators (rest z i x)) := by + have hp : univ.toList.Perm (i :: (univ.erase i).toList) := by + apply (List.perm_ext_iff_of_nodup (nodup_toList _) (by simp [nodup_toList])).mpr + simp [eq_or_ne] + obtain ⟨c, hc, h⟩ := order (F := F) e _ hp + refine ⟨c, hc, fun x => ?_⟩ + rw [h] + simp [spectators, rest, mark, List.map_flatMap, Function.comp_def] + +open scoped Classical in +private theorem added_perm (i : A) : + (univ : Finset (A ⊕ Unit)).toList.Perm (.inl i :: .inr () :: (univ.erase i).toList.map Sum.inl) + := by + let l : List (A ⊕ Unit) := .inl i :: .inr () :: (univ.erase i).toList.map Sum.inl + have hp : univ.toList.Perm l := by + have hn : l.Nodup := by + simp [l, nodup_toList, List.nodup_map_iff Sum.inl_injective] + apply (List.perm_ext_iff_of_nodup (nodup_toList _) hn).mpr + rintro (j | ⟨⟩) <;> simp [l, eq_or_ne] + exact hp + +open scoped Classical in +theorem order_added (z : A → F) (i : A) (e : A → ℕ) (g : ℕ) : + ∃ c : F, c ≠ 0 ∧ ∀ (s : F) (x : States 1 e) (w : Level 1 g), + sphereForm (Sum.elim z (fun _ => s)) (energy e g) (add x w) = c * + wick fieldKernel ((triple (mark z i) (x i).val.val w.val.val (rest z i x)).map (atPoint s)) + := by + let l : List (A ⊕ Unit) := .inl i :: .inr () :: (univ.erase i).toList.map Sum.inl + have hp : univ.toList.Perm l := added_perm i + obtain ⟨c, hc, h⟩ := order (F := F) (energy e g) _ hp + refine ⟨c, hc, fun s x w => ?_⟩ + rw [h] + simp [triple, rest, mark, List.map_flatMap, Function.comp_def, l, List.flatMap_map, add, atPoint] + +open scoped Classical in +/-- A common numerator in any of the pole orderings. -/ +theorem order_polynomial (z : A → F) (e : A ⊕ Unit → ℕ) : + ∃ P : States 1 e → Polynomial F, ∀ i : A, ∃ t : F, t ≠ 0 ∧ + ∀ x : States 1 e, P x = Polynomial.C t * numerator (marks z) + (triple (mark z i) (x (.inl i)).val.val (x (.inr ())).val.val + (rest z i (fun j => x (.inl j)))) := by + let u (x : (A ⊕ Unit) × Mode 1) : Option ↥(marks z) × Mode 1 := + (Sum.elim (fun i => some (mark z i)) (fun _ => none) x.1, x.2) + let k := polynomialKernel (r := 1) (trajectories (marks z)) (Polynomial.X : Polynomial F) 1 + refine ⟨fun x => wick (fun i j => k (u i) (u j)) (inputs x), fun i => ?_⟩ + let l : List (A ⊕ Unit) := .inl i :: .inr () :: (univ.erase i).toList.map Sum.inl + have hp : univ.toList.Perm l := added_perm i + obtain ⟨n, hn⟩ := wick_perm_sites (R := Polynomial F) (r := 1) e hp + refine ⟨(-1) ^ n, by simp, fun x => ?_⟩ + have h := hn (fun i j => k (u i) (u j)) (fun i j => polynomial_skew _ (u i) (u j)) x [] + simp only [List.nil_append] at h + change wick (fun i j => k (u i) (u j)) (univ.toList.flatMap (marksAt x)) = _ + rw [h, ← wick_map k u, map_pow, map_neg, map_one] + simp [numerator, correlatorPoly, k, triple, rest, marksAt, u, List.map_flatMap, + Function.comp_def, l, List.flatMap_map] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Insertion +end + +/- +# Recovering the entries of a wire at one site + +All coefficients of the interpolation and the matrix units are +independent of basis indices held at other sites. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Insertion + +open Finset Sphere Sphere.Motion + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] + +open scoped Classical in +private theorem units {q e : ℕ} (a : Level 1 q) (b : Level 1 e) : + ∃ v : Wedge 1 → F, ∀ (x : Level 1 q) (y : Level 1 e), + (∑ h ∈ range (⌊Sphere.width q e⌋₊ + 1), ∑ t : Level 1 h, + v t.val * fusion F t.val.val x.val.val y.val.val) = + if a = x ∧ b = y then 1 else 0 := by + obtain ⟨v, hv, he⟩ := fusion_width F a.val b.val + have hs (t : Wedge 1) (ht : t ∈ v.support) : + Sphere.energy t.val ∈ range (⌊Sphere.width q e⌋₊ + 1) := by + refine mem_range.mpr (Nat.lt_succ_of_le (Nat.le_floor ?_)) + simpa only [a.2, b.2] using hv t ht + refine ⟨v, fun x y => ?_⟩ + have hh := he x.val y.val (x.2.trans a.2.symm) (y.2.trans b.2.symm) + simp only [Finsupp.linearCombination_apply, Finsupp.sum, smul_eq_mul, ← Subtype.ext_iff] at hh + rw [← hh, ← sum_fiberwise_of_maps_to hs] + refine sum_congr rfl fun h _ => ?_ + symm + refine sum_bij_ne_zero (fun t ht _ => ⟨t, (mem_filter.mp ht).2⟩) + (fun _ _ _ => mem_univ _) (fun _ _ _ _ _ _ he => congrArg Subtype.val he) + ?_ (fun _ _ _ => rfl) + intro t _ ht + have hv' : t.val ∈ v.support := Finsupp.mem_support_iff.mpr (left_ne_zero_of_mul ht) + exact ⟨t.val, mem_filter.mpr ⟨hv', t.2⟩, ht, rfl⟩ + +variable (z : A → F) (i : A) (e : A → ℕ) (q : ℕ) + +open scoped Classical in +private theorem coefficient (hz : Function.Injective z) (T : Finset F) (hd : Disjoint T (marks z)) + (h : ℕ) (hT : (marks z).card * ((h + q + ∑ j ∈ univ.erase i, e j) / 2) < T.card) : + ∃ f : T → F, ∀ (x : States 1 e) (a : Level 1 h) (w : Level 1 q), + (∑ b : Level 1 (e i), fusion F a.val.val w.val.val b.val.val * + stationary (mark z i) b.val (rest z i x)) = + ∑ s : T, f s * sphereForm (Sum.elim z (fun _ => s.val)) + (energy (Function.update e i h) q) (add (changeAt i x a) w) := by + obtain ⟨f, hf⟩ := recover_level (r := 1) (mark z i) T hd h q (e i) _ hT + obtain ⟨c, hc, hc'⟩ := order_added z i (Function.update e i h) q + refine ⟨fun s => f s / c, fun x a w => ?_⟩ + rw [hf a w.val _ w.2 (rest_avoids z hz i x) (weight_rest _ _ _)] + refine sum_congr rfl fun s _ => ?_ + rw [hc', changeAt_val, ite_eq_left rfl, rest_changeAt, ← mul_assoc, div_mul_cancel₀ _ hc] + rfl + +open scoped Classical in +private theorem eval_units (q e : ℕ) (w : Level 1 q) (b : Level 1 e) + (f : Level 1 e → F) (v : Wedge 1 → F) + (hv : ∀ (t : Level 1 q) (y : Level 1 e), + (∑ h ∈ range (⌊Sphere.width q e⌋₊ + 1), ∑ a : Level 1 h, + v a.val * fusion F a.val.val t.val.val y.val.val) = + if w = t ∧ b = y then 1 else 0) (t : Level 1 q) : + (∑ h ∈ range (⌊Sphere.width q e⌋₊ + 1), ∑ a : Level 1 h, v a.val * + ∑ y, fusion F a.val.val t.val.val y.val.val * f y) = + if w = t then f b else 0 := by + have hh (h : ℕ) : + (∑ a : Level 1 h, v a.val * ∑ y, fusion F a.val.val t.val.val y.val.val * f y) = + ∑ y, (∑ a : Level 1 h, v a.val * fusion F a.val.val t.val.val y.val.val) * f y := by + simp only [mul_sum, sum_mul, mul_assoc] + rw [sum_comm] + simp_rw [hh] + rw [sum_comm] + simp_rw [← sum_mul, hv] + by_cases he : w = t <;> simp [he] + +open scoped Classical in +theorem recover_wire (hz : Function.Injective z) (T : Finset F) (hd : Disjoint T (marks z)) + (hT : Fintype.card A * ((∑ j, e j) + ⌊Sphere.width q (e i)⌋₊ + q) < T.card) : + ∃ k : ∀ h : ℕ, T → Level 1 h → Level 1 (e i) → Level 1 q → F, + ∀ (x : States 1 e) (w t : Level 1 q), + (if w = t then sphereForm z e x else 0) = + ∑ h ∈ range (⌊Sphere.width q (e i)⌋₊ + 1), ∑ s : T, ∑ a : Level 1 h, + k h s a (x i) w * sphereForm (Sum.elim z (fun _ => s.val)) + (energy (Function.update e i h) q) (add (changeAt i x a) t) := by + let H := ⌊Sphere.width q (e i)⌋₊ + have he (h : ℕ) (hh : h ∈ range (H + 1)) : + (marks z).card * ((h + q+∑ j ∈ univ.erase i, e j) / 2) < T.card := by + refine lt_of_le_of_lt (Nat.mul_le_mul card_image_le ?_) hT + have := mem_range.mp hh + have := sum_erase_add univ e (mem_univ i) + omega + choose! f hf using fun h hh => coefficient z i e q hz T hd h (he h hh) + choose v hv using fun (w : Level 1 q) (b : Level 1 (e i)) => units (F := F) w b + obtain ⟨c, _, hc⟩ := order_base z i e + refine ⟨fun h s a b w => c * v w b a.val * f h s, fun x w t => ?_⟩ + let g (y : Level 1 (e i)) := stationary (mark z i) y.val (rest z i x) + rw [show sphereForm z e x = c * g (x i) from hc x, show (if w = t then c * g (x i) else 0) + = c * (if w = t then g (x i) else 0) by simp] + rw [← eval_units _ _ w (x i) g (v w (x i)) (hv w (x i)) t, mul_sum] + refine sum_congr rfl fun h hh => ?_ + rw [sum_comm, mul_sum] + refine sum_congr rfl fun a _ => ?_ + dsimp only [g] + rw [hf h hh x a t, mul_sum, mul_sum] + exact sum_congr rfl (fun _ _ => by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Insertion +end + +/- Recovery of one full wire by a sum of local tensor restrictions. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral Sphere Finset + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] + +open scoped Classical in +omit [DecidableEq A] in +/-- A sum whose evaluation varies only at site `i` is one local map. -/ +private theorem mix_at {J : Type} [Fintype J] (U V : Raw F A) (i : A) + (k : J → V.leg i → F) (f : J → ∀ a, V.leg a → U.leg a) + (h : ∀ u v a, a ≠ i → f u a = f v a) (scale : ∀ a, V.leg a → F) : + ∃ M : Raw.Local U V, ∀ x, U.applyLocal M x = + (∏ a, scale a (x a)) * ∑ j, k j (x i) * U.coeff (fun a => f j a (x a)) := by + classical + let base : Raw.Local U V := if hJ : Nonempty J then + fun a x z => if z = f hJ.some a x then 1 else 0 else fun _ _ _ => 0 + let N := Function.update base i (fun x z => ∑ j, if z = f j i x then k j x else 0) + refine ⟨fun a x z => scale a x * N a x z, fun x => ?_⟩ + have hv (t : U.term) : + ∑ z, N i (x i) z * U.factor t i z = ∑ j, k j (x i) * U.factor t i (f j i (x i)) := by + simp only [N, Function.update_self, sum_mul] + rw [sum_comm] + simp [ite_mul] + have hu (t : U.term) (j : J) (a : A) (ha : a ∈ univ.erase i) : + ∑ z, N a (x a) z * U.factor t a z = U.factor t a (f j a (x a)) := by + have hai := (mem_erase.mp ha).1 + have hJ : Nonempty J := ⟨j⟩ + simp [N, hai, base, hJ, h hJ.some j a hai, ite_mul] + have step (t : U.term) : + (∏ a, ∑ z, N a (x a) z * U.factor t a z) = + ∑ j, k j (x i) * ∏ a, U.factor t a (f j a (x a)) := by + rw [← mul_prod_erase _ _ (mem_univ i), hv, sum_mul] + refine sum_congr rfl fun j _ => ?_ + rw [prod_congr rfl (hu t j), mul_assoc, mul_prod_erase _ (fun a + => U.factor t a (f j a (x a))) (mem_univ i)] + simp only [Raw.applyLocal, mul_assoc, ← mul_sum, prod_mul_distrib, step] + rw [sum_comm] + simp only [Raw.coeff, ← mul_sum] + +open scoped Classical in +private theorem wire_coeff (i : A) (n : ℕ) [NeZero n] (x : A ⊕ Unit → Fin n) : + (Raw.wire F (.inl i) (.inr ()) n).coeff x = + (∏ a, if a ∈ ({.inl i, .inr ()} : Finset (A ⊕ Unit)) ∨ x a = 0 then (1 : F) else 0) * + (if x (.inl i) = x (.inr ()) then 1 else 0) := by + let U : Finset (A ⊕ Unit) := {.inl i, .inr ()} + change (∑ j : Fin n, ∏ a, if x a = Raw.port U a j then (1 : F) else 0) = _ + rw [Fintype.sum_eq_single (x (.inr ()))] + · have eqn (a : A ⊕ Unit) : + (if x a = Raw.port U a (x (.inr ())) then (1 : F) else 0) = + (if a ∈ U ∨ x a = 0 then 1 else 0) * + (if a = .inl i then if x (.inl i) = x (.inr ()) then 1 else 0 else 1) := by + rcases a with j | ⟨⟩ + · by_cases h : j = i <;> simp [Raw.port, U, h] + · simp [Raw.port, U] + simp only [eqn, prod_mul_distrib] + simp [U] + · intro j hj + exact prod_eq_zero (mem_univ (.inr ())) (by simp [Raw.port, U, Ne.symm hj]) + +open Insertion + +variable [Nonempty A] + +open scoped Classical in +private def selectWord {e : A → ℕ} (i j : A) {h : ℕ} (v : Level 1 h) (w : Level 1 (e j)) : + Level 1 (Function.update e i h j) := + ⟨if j = i then v.val else w.val, by + by_cases hj : j = i + · simpa [hj] using v.2 + · simpa [hj] using w.2⟩ + +open scoped Classical in +private theorem probe (z : A → F) (hz : Function.Injective z) (e : A → ℕ) (i : A) (q : ℕ) + (T : Finset F) (hd : Disjoint T (Insertion.marks z)) + (hT : Fintype.card A * ((∑ j, e j) + ⌊Sphere.width q (e i)⌋₊ + q) < T.card) : + Tensor.pad Unit (sphereTensor z e) * Tensor.wire F (.inl i) (.inr ()) + (Fintype.card (Level 1 q)) ≤ + ∑ h ∈ range (⌊Sphere.width q (e i)⌋₊+1), ∑ s ∈ T, + sphereTensor (Sum.elim z (fun _ => s)) (Insertion.energy (Function.update e i h) q) := by + obtain ⟨k, hk⟩ := recover_wire z i e q hz T hd hT + let n := Fintype.card (Level 1 q) + let V₀ := Raw.ofTable (fun j => Level 1 (e j)) (sphereForm z e) + let V := V₀.pad Unit * Raw.wire F (.inl i) (.inr ()) n + let J := ℕ × ↥T + let E (h : ℕ) := Insertion.energy (Function.update e i h) q + let U (j : J) := Raw.ofTable (fun l => Level 1 (E j.1 l)) + (sphereForm (Sum.elim z (fun _ => j.2.val)) (E j.1)) + let D := range (⌊Sphere.width q (e i)⌋₊+1) + suffices h : Tensor.ofRaw V ≤ ∑ j ∈ D ×ˢ univ, Tensor.ofRaw (U j) by + rw [sum_product] at h + simp only [U, E] at h + refine h.trans_eq (sum_congr rfl fun j _ => ?_) + exact sum_coe_sort T (fun s => sphereTensor (Sum.elim z (fun _ => s)) (E j)) + apply (Raw.restriction_sum_iff U V _).mpr + by_cases h : n = 0 + · refine ⟨fun _ _ _ _ => 0, fun x => ?_⟩ + have hx := ((x (.inr ())).2 : Fin n).isLt + omega + have : NeZero n := ⟨h⟩ + let w : Fin n ≃ Level 1 q := (Fintype.equivFin _).symm + let α (l : A ⊕ Unit) (v : V.leg l) := + let t : Fin n := v.2 + if l ∈ ({.inl i, .inr ()} : Finset (A ⊕ Unit)) ∨ t = 0 then (1 : F) else 0 + let f (j : J) (t : Level 1 j.1) : ∀ l, V.leg l → (U j).leg l + | .inl a, v => selectWord i a t v.1 + | .inr _, v => w v.2 + have hf (j : J) (a b : Level 1 j.1) (l : A ⊕ Unit) (hl : l ≠ .inl i) : + f j a l = f j b l := by + cases l with + | inr _ => rfl + | inl l => + have hn : l ≠ i := fun h => hl (congrArg Sum.inl h) + funext v + apply Subtype.ext + simp [f, selectWord, hn] + let c (j : J) (t : Level 1 j.1) (v : V.leg (.inl i)) := k j.1 j.2 t v.1 (w v.2) + choose M hM using fun j => mix_at (U j) V (.inl i) (c j) (f j) (hf j) α + refine ⟨M, fun x => ?_⟩ + let v : States 1 e := fun j => (x (.inl j)).1 + let b : A ⊕ Unit → Fin n := fun j => (x j).2 + have hV : V.coeff x = (∏ l, α l (x l)) * + (if w (b (.inl i)) = w (b (.inr ())) then sphereForm z e v else 0) := by + rw [show V.coeff x = _ from Raw.coeff_mul _ _ x, Raw.pad_coeff] + change V₀.coeff v * (Raw.wire F (.inl i) (.inr ()) n).coeff b = _ + rw [show V₀.coeff v = _ from Raw.coeff_ofTable _ _ _, wire_coeff] + change sphereForm z e v * ((∏ l, α l (x l)) * _) = _ + simp only [w.injective.eq_iff, mul_ite, mul_one, mul_zero] + rw [mul_comm (sphereForm z e v)] + have hU (j : J) (t : Level 1 j.1) : + (U j).coeff (fun l => f j t l (x l)) = + sphereForm (Sum.elim z (fun _ => j.2.val)) (E j.1) + (Insertion.add (changeAt i v t) (w (b (.inr ())))) := by + have hl : (fun l => f j t l (x l)) = Insertion.add (changeAt i v t) (w (b (.inr ()))) := by + funext l + cases l with + | inr u => cases u; rfl + | inl a => + change selectWord i a t (v a) = changeAt i v t a + exact Subtype.ext (changeAt_val i v t a).symm + rw [hl] + exact Raw.coeff_ofTable _ _ _ + simp only [hM, hU, ← mul_sum] + rw [hV, hk, sum_product] + +open scoped Classical in +theorem wireProbe (F : Type) [Field F] [Infinite F] : WireProbe F := by + intro A _ _ _ z hz e i q H + let N := Fintype.card A * ((∑ j, e j) + H + q) + obtain ⟨T, ht, hcard⟩ := (Set.finite_range z).infinite_compl.exists_subset_card_eq (1 + N) + have hd : Disjoint T (Insertion.marks z) := by + refine disjoint_left.mpr fun s hs he => ht hs ?_ + simpa [Insertion.marks] using he + exact ⟨T, fun _ h => ht h, hcard.le, probe z hz e i q T hd (show N < T.card by omega)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/PrimeFields.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/PrimeFields.lean new file mode 100644 index 0000000000..b6130aaa86 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/PrimeFields.lean @@ -0,0 +1,54 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldExtension +public import Mathlib.Algebra.Algebra.ZMod +public import Mathlib.Algebra.Field.ZMod + +/-! +# Reduction to prime fields + +It suffices to rule out one finite system of coefficient equations at +a time. The threshold can be tested with integer arithmetic alone. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem prime_specialization {F : Type*} [Field F] {s : ℝ} (h : omega F < s) : + ∃ (p : ℕ) (_ : Fact p.Prime), omega (ZMod p) < s := by + obtain ⟨k, _, _, hk⟩ := finite_specialization h + let p := ringChar k + have : Fact p.Prime := ⟨CharP.char_is_prime k p⟩ + let : Algebra (ZMod p) k := ZMod.algebra k p + exact ⟨p, inferInstance, (omega_extension (ZMod p) k) ▸ hk⟩ + +/-- Lifting the upper bound from small fields to all universes. -/ +theorem upper_of_small {s : ℝ} (h : ∀ (k : Type) [Field k], omega k ≤ s) + (F : Type*) [Field F] : omega F ≤ s := by + obtain ⟨p, hp⟩ := CharP.exists F + rcases CharP.char_is_prime_or_zero F p with hprime | rfl + · have : Fact p.Prime := ⟨hprime⟩ + let : Algebra (ZMod p) F := ZMod.algebra F p + rw [omega_extension (ZMod p) F] + exact h _ + · let : CharZero F := CharP.charP_to_charZero F + rw [omega_extension ℚ F] + exact h _ + +theorem rank_threshold (n r : ℕ) : + (r : ℝ) < (n : ℝ) ^ (9 / 4 : ℝ) ↔ r ^ 4 < n ^ 9 := by + have he : ((n : ℝ) ^ (9 / 4 : ℝ)) ^ (4 : ℕ) = (n : ℝ) ^ (9 : ℕ) := by + rw [← Real.rpow_mul_natCast (Nat.cast_nonneg n)] + norm_num + rw [← pow_lt_pow_iff_left₀ (Nat.cast_nonneg (α := ℝ) r) + (Real.rpow_nonneg (Nat.cast_nonneg n) (9 / 4)) (by decide : (4 : ℕ) ≠ 0), he] + norm_cast + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/AddressSize.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/AddressSize.lean new file mode 100644 index 0000000000..1c0a0b9151 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/AddressSize.lean @@ -0,0 +1,671 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Skip +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.DispatchSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Capacity + +/-! +# Numbering encoded records + +A static partition names each record by a key and a row number. +The two endpoints and number of transmitted bits may depend on the +public report, but are shared by all rows with a given key. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal Finset +variable {R : ℕ} {E J : Type} {src dst : E → Fin R} {size : E → ℕ} + +open Classical in +/-- The data for the records construction, including `length`, `row`. -/ +structure Records (E J : Type) where + /-- The length of the indexed record carried by `Records`, with type `J → ℕ`. -/ + length : J → ℕ + /-- The row index of type `E ≃ (Σ j, Fin (length j))`. -/ + row : E ≃ (Σ j, Fin (length j)) + +namespace Records + +variable (p : Records E J) + +open Classical in +/-- The value specified by `(p.row e).1`. -/ +def key (e : E) := (p.row e).1 +open Classical in +/-- The value specified by `(p.row e).2.val`. -/ +def index (e : E) := (p.row e).2.val + +open Classical in +theorem index_lt (e : E) : p.index e < p.length (p.key e) := (p.row e).2.isLt + +open Classical in +private theorem unique {e e' : E} (h : p.key e = p.key e') (hi : p.index e = p.index e') : + e = e' := by + apply p.row.injective + unfold key at h + unfold index at hi + generalize p.row e = a, p.row e' = b at * + rcases a with ⟨a, i⟩ + rcases b with ⟨b, j⟩ + change a = b at h + subst b + rw [show i = j from Fin.ext hi] + +open Classical in +/-- The data for the routing construction, including `fromKey`, `toKey`, `bits`, `atSrc`, +`atDst`. -/ +structure Routing (src dst : E → Fin R) (size : E → ℕ) where + /-- The `Routing` component of type `J → Fin R`. -/ + fromKey : J → Fin R + /-- The `Routing` component of type `J → Fin R`. -/ + toKey : J → Fin R + /-- The `Routing` component of type `J → ℕ`. -/ + bits : J → ℕ + atSrc : ∀ e, fromKey (p.key e) = src e + atDst : ∀ e, toKey (p.key e) = dst e + atSize : ∀ e, bits (p.key e) = size e + +namespace Routing +variable {p} (s : p.Routing src dst size) + +open Classical in +/-- Returns `0` when `s.fromKey j = s.toKey j` holds, and `p.length j * s.bits j` otherwise. -/ +def width (j : J) := if s.fromKey j = s.toKey j then 0 else p.length j * s.bits j + +open Classical in +/-- The quantity computed by `p.index e.1.val * size e.1.val + e.2.val`. -/ +def digit (e : Encoded.Bits src dst size) := p.index e.1.val * size e.1.val + e.2.val + +open Classical in +/-- The label of type `Σ j, Fin (s.width j)` for the given inputs. -/ +def label (e : Encoded.Bits src dst size) : Σ j, Fin (s.width j) := + ⟨p.key e.1.val, ⟨digit (p := p) e, by + rw [width, s.atSrc, s.atDst, ite_eq_right e.1.property, s.atSize] + exact (Nat.add_lt_add_left e.2.isLt _).trans_le (by + rw [← Nat.succ_mul] + exact Nat.mul_le_mul_right _ (p.index_lt _))⟩⟩ + +open Classical in +private theorem digit_unique {u v a b w : ℕ} (ha : a < w) (hb : b < w) + (he : u * w + a = v * w + b) : u = v ∧ a = b := by + have h : a = b := by + have hh := congrArg (fun x => x % w) he + simpa [Nat.add_mod, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb] using hh + refine ⟨Nat.eq_of_mul_eq_mul_right (by omega : 0 < w) (by omega), h⟩ + +open Classical in +theorem label_injective : Function.Injective s.label := by + rintro ⟨⟨e, he⟩, i⟩ ⟨⟨f, hf⟩, j⟩ h + have hk := congrArg Sigma.fst h + change p.key e = p.key f at hk + have hw : size e = size f := by rw [← s.atSize, ← s.atSize, hk] + have hn := congrArg (fun z => z.2.val) h + change p.index e * size e + i.val = p.index f * size f + j.val at hn + obtain ⟨hl, hj⟩ := digit_unique i.isLt (j.isLt.trans_eq hw.symm) (by simpa only [hw] using hn) + have heq := p.unique hk hl + subst f + rw [show i = j from Fin.ext hj] + +variable [Fintype E] [Fintype J] + +open Classical in +theorem same_count : + Fintype.card (Encoded.Bits src dst size) = Fintype.card (Σ j, Fin (s.width j)) := by + simp only [Encoded.Bits, Fintype.card_sigma, Fintype.card_fin] + rw [← sum_subtype (univ.filter (fun i => src i ≠ dst i)) + (p := fun e => src e ≠ dst e) (by simp) size, sum_filter] + simp_rw [← s.atSrc, ← s.atDst, ← s.atSize] + rw [← p.row.symm.sum_comp, Fintype.sum_sigma] + unfold key + simp only [Equiv.apply_symm_apply] + apply sum_congr rfl + intro j _ + by_cases he : s.fromKey j = s.toKey j <;> simp [width, he] + +open Classical in +/-- Builds `Channels (Encoded.left src dst size) (Encoded.right src dst size) J where width` +with the specified `width`, `left`, `right`, `label`. -/ +def channels : Channels (Encoded.left src dst size) (Encoded.right src dst size) J where + width := s.width + left := s.fromKey + right := s.toKey + label := Equiv.ofBijective s.label ((Fintype.bijective_iff_injective_and_card _).mpr + ⟨s.label_injective, s.same_count⟩) + src_eq _ := (s.atSrc _).symm + dst_eq _ := (s.atDst _).symm + +open Classical in +theorem channels_index (e : Encoded.Bits src dst size) : + (s.channels.label e).2.val = p.index e.1.val * size e.1.val + e.2.val := rfl + +open Classical in +theorem channels_key (e : Encoded.Bits src dst size) : + (s.channels.label e).1 = p.key e.1.val := rfl + +end Routing +end Records +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Computing group membership and channel lengths from the public report -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +open Processor Install Finset +variable {F : Type} [Field F] {n h r d : ℕ} (A : Expansion F n h) + +open Classical in +/-- The quantity computed by `A.cross z i + Nat.clog 2 (Fintype.card A.I)`. -/ +def chargeBits (i : Fin n) (z : A.I) := A.cross z i + Nat.clog 2 (Fintype.card A.I) + +open Classical in +/-- The value specified by `⟨fun z => 256 * ((if z.1.1 = g then A.chargeBits i z.2 else 0) + (if +z.1.2.1 = g then A.chargeBits i z.2 else 0)), 0⟩`. -/ +def mass (i : Fin n) (g : Fin r) : Form (Class r × A.I) := + ⟨fun z => 256 * ((if z.1.1 = g then A.chargeBits i z.2 else 0) + + (if z.1.2.1 = g then A.chargeBits i z.2 else 0)), 0⟩ + +open Classical in +/-- Tests whether `N < (A.mass i g).value x` holds. -/ +def groupFlags (N : ℕ) (i : Fin n) (x : A.CountBit r d → Bool) (g : Fin r) := + decide (N < (A.mass i g).value x) + +open Classical in +theorem groupFlags_report (N : ℕ) (R : A.Report r d) (g : Fin r) : + A.groupFlags N R.1 (A.countBits R) g = true ↔ g ∈ A.reportGroups N R := by + have he (z : Class r × A.I) : number (fun i => A.countBits R (z, i)) = (R.2 z).val := + A.cnt_countBits R z + simp only [groupFlags, decide_eq_true_eq, mass, Form.value, linear, add_zero, he, + reportGroups, mem_filter, mem_univ, true_and, total, chargeBits, mul_sum, mul_left_comm] + +open Classical in +/-- Uses `⟨fun z => if z.1 = c then A.chargeBits i z.2 else 0, 0⟩` as the representation. -/ +def classForm (i : Fin n) (c : Class r) : Form (Class r × A.I) := + ⟨fun z => if z.1 = c then A.chargeBits i z.2 else 0, 0⟩ + +open Classical in +theorem classForm_report (R : A.Report r d) (c : Class r) : + (A.classForm R.1 c).value (A.countBits R) = A.classWidth R c := by + have he (z : Class r × A.I) : number (fun i => A.countBits R (z, i)) = (R.2 z).val := + A.cnt_countBits R z + simp only [classForm, Form.value, linear, add_zero, he] + rw [Fintype.sum_prod_type, sum_comm] + simp only [mul_ite, mul_zero, sum_ite_eq', mem_univ, ite_true, chargeBits, classWidth] + +open Classical in +/-- The quantity computed by `(1 + r) * 100000 * (1 + Fintype.card (A.CountBit r d)) * (1 + w)`. -/ +def flagCost (r d w : ℕ) := (1 + r) * 100000 * (1 + Fintype.card (A.CountBit r d)) * (1 + w) + +open Classical in +theorem groupFlags_net {N w M : ℕ} (i : Fin n) + (hc : ∀ z, A.chargeBits i z ≤ M) (hN : N < 2 ^ w) + (hv : Fintype.card (Class r × A.I) * (2 ^ registerWidth n r d * (512 * M)) < 2 ^ w) : + BNet F (A.groupFlags (d := d) (r := r) N i) (A.flagCost r d w) := by + let n₀ : Form (Class r × A.I) := ⟨fun _ => 0, N⟩ + have hn (x : A.CountBit r d → Bool) : n₀.value x = N := by simp [n₀, Form.value, linear] + have hm (g : Fin r) (x : A.CountBit r d → Bool) : (A.mass i g).value x < 2 ^ w := by + apply lt_of_le_of_lt _ hv + apply linear_le + intro z + have h := hc z.2 + simp only [mass] + split_ifs <;> omega + let k := 90000 * (1 + Fintype.card (A.CountBit r d)) * (1 + w) + have hg (g : Fin r) : BNet F (fun (x : A.CountBit r d → Bool) (_ : Unit) => + A.groupFlags N i x g) k := by + have he := n₀.compare F (A.mass i g) w (registerWidth n r d) (fun x => by rwa [hn]) (hm g) + simp only [hn] at he + unfold k + rw [Fintype.card_prod, Fintype.card_fin] + exact he + have hp := (BNet.collect _ hg).rename (.refl _) (Equiv.prodUnique _ Unit) + apply hp.mono + rw [Fintype.card_fin] + unfold k flagCost + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +/- +# Fixed classes of processor symbols + +The only classes with variable-length rows are the singleton selector +classes. Literal rows use a numbering that is independent of the +processor. Slot rows use the packet repetition and bit index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal Spectral +namespace Records + +variable {A B I J : Type} + +open Classical in +/-- Builds `Records A I where length i` with the specified `length`, `row`. -/ +def partition [Fintype A] [DecidableEq I] (f : A → I) : Records A I where + length i := multiplicity f i + row := (Equiv.sigmaFiberEquiv f).symm.trans (Equiv.sigmaCongrRight (fun _ => Fintype.equivFin _)) + +open Classical in +/-- Builds `Records (J × A) (J × I) where length t` with the specified `length`, `row`. -/ +def indexed (p : Records A I) (J : Type) : Records (J × A) (J × I) where + length t := p.length t.2 + row := + ((Equiv.refl J).prodCongr p.row).trans + ⟨fun t => ⟨(t.1, t.2.1), t.2.2⟩, fun q => (q.1.1, ⟨q.1.2, q.2⟩), fun _ => rfl, fun _ => rfl⟩ + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def union (p : Records A I) (q : Records B J) : Records (A ⊕ B) (I ⊕ J) where + length := Sum.elim p.length q.length + row := (p.row.sumCongr q.row).trans + (Equiv.sumSigmaDistrib (fun k => Fin (Sum.elim p.length q.length k))).symm + +open Classical in +/-- Builds `Records A I where length _` with the specified `length`, `row`. -/ +def uniform {w : ℕ} (e : A ≃ I × Fin w) : Records A I where + length _ := w + row := e.trans (Equiv.sigmaEquivProd _ _).symm + +end Records + +open Classical in +/-- Indexes the name by the coordinates of `((Fin (3 * r) × Label n r) ⊕ Label n r) ⊕ (Template +n r × Cube n × Bool) ⊕ Class r`. -/ +abbrev Name (n r : ℕ) := ((Fin (3 * r) × Label n r) ⊕ Label n r) ⊕ + (Template n r × Cube n × Bool) ⊕ Class r + +variable {F : Type} [Field F] {N l n r h t : ℕ} + +open Classical in +/-- Reindexes `Position n r t h × Bool` and `(Template n r × Cube n × Bool) × Fin (t * h) where +toFun a` by an equivalence. -/ +def slotRows : Position n r t h × Bool ≃ (Template n r × Cube n × Bool) × Fin (t * h) where + toFun a := ((a.1.1.1, a.1.2.1, a.2), finProdFinEquiv (a.1.1.2, a.1.2.2)) + invFun p := (((p.1.1, (finProdFinEquiv.symm p.2).1), p.1.2.1, (finProdFinEquiv.symm p.2).2), + p.1.2.2) + left_inv _ := by simp only [Equiv.symm_apply_apply] + right_inv _ := by simp only [Prod.mk.eta, Equiv.apply_symm_apply] + +variable (fa : Machine.Ports N l l → Label n r) + +open Classical in +/-- The records of type `Records (Pin N l l r ⊕ Expansion.Edge n r t h) (Name n r)`, constructed +using `(Records.partition (fun i => fa (.inl i))).indexed (Fin (3 * r))`. -/ +def records (h t : ℕ) : Records (Pin N l l r ⊕ Expansion.Edge n r t h) (Name n r) := + let lit := (Records.partition (fun i => fa (.inl i))).indexed (Fin (3 * r)) + let privatePins := Records.partition (fun q => fa (Pin.position (.inr q))) + let pos := Records.uniform (slotRows (n := n) (r := r) (t := t) (h := h)) + let sel := Records.uniform (Equiv.prodUnique (Class r) (Fin 1)).symm + (lit.union privatePins).union (pos.union sel) + +open Classical in +theorem name_card (n r : ℕ) : + Fintype.card (Name n r) = 3 * r * r ^ n + r ^ n + (r ^ n) ^ 2 * 2 ^ n * 2 + r ^ 3 := by + simp [Name] + ring + +open Classical in +/-- In the case `.inl (.inl (u, z))`, this construction gives `((Worker.index r).symm u, A.owner +hn N R z, 1)`. -/ +def descriptor (A : Expansion F n h) (hn : 2 ≤ n) (N : ℕ) (R : A.Report r t) : + Name n r → Worker r × Worker r × ℕ + | .inl (.inl (u, z)) => ((Worker.index r).symm u, A.owner hn N R z, 1) + | .inl (.inr z) => (A.owner hn N R z, A.owner hn N R z, 1) + | .inr (.inl (p, x, b)) => + let c := (group p R.1 false, group p R.1 true, group p (other hn R.1) false) + let v := A.owner hn N R (corner p (if b then Cube.flip Finset.univ x else x)) + (v, if A.shared N R c then v else .packet c.2.2, 1) + | .inr (.inr c) => (A.src hn N R (.inr c), A.dst hn N R (.inr c), A.classWidth R c) + +open Classical in +/-- Builds `let f` with the specified `let`, `fromKey`, `toKey`, `bits`. -/ +def grouping (A : Expansion F n h) (hn : 2 ≤ n) (R : A.Report r t) : + let f := A.owner hn N R ∘ fa + (records fa h t).Routing (A.extraSrc hn N R (Worker.index r) (Pin.src f)) + (A.extraDst hn N R (Worker.index r) (Pin.dst f)) (A.extraSize R) where + fromKey j := Worker.index r (descriptor A hn N R j).1 + toKey j := Worker.index r (descriptor A hn N R j).2.1 + bits j := (descriptor A hn N R j).2.2 + atSrc := by rintro ((⟨u, i⟩|q)|⟨p, x⟩|c) <;> rfl + atDst := by rintro ((⟨u, i⟩|q)|⟨p, x⟩|c) <;> rfl + atSize := by rintro ((⟨u, i⟩|q)|⟨p, x⟩|c) <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- # Endpoints from at most three group flags -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Install Diagonal Spectral +variable {n r : ℕ} (hn : 2 ≤ n) (i : Fin n) (mask : Fin r → Bool) + +/-- Returns `.station (z (other hn i))` when `mask (z i)` holds, and `.home (z i)` otherwise. -/ +def home (z : Label n r) : Worker r := + if mask (z i) then .station (z (other hn i)) else .home (z i) + +/-- In the case `.inl (.inl (u, z))`, this construction gives `((Worker.index r).symm u, home hn +i mask z)`. -/ +def pairOf : Name n r → Worker r × Worker r + | .inl (.inl (u, z)) => ((Worker.index r).symm u, home hn i mask z) + | .inl (.inr z) => (home hn i mask z, home hn i mask z) + | .inr (.inl (p, x, b)) => + let v := home hn i mask (corner p (if b then Cube.flip Finset.univ x else x)) + (v, if mask (p.1 i) = false ∧ mask (p.2 i) = false then v else .packet (p.1 (other hn i))) + | .inr (.inr c) => + if mask c.1 = false ∧ mask c.2.1 = false then (.home c.1, .home c.2.1) + else (.packet c.2.2, .packet c.2.2) + +theorem support (k : Name n r) : + ∃ S : Finset (Fin r), S.card ≤ 3 ∧ ∀ a b, + (∀ j ∈ S, a j = b j) → pairOf hn i a k = pairOf hn i b k := by + rcases k with (⟨u, z⟩|z)|⟨p, x, s⟩|c + · exact ⟨{z i}, by simp, fun a b h => by simp only [pairOf, home, h (z i) (by simp)]⟩ + · exact ⟨{z i}, by simp, fun a b h => by simp only [pairOf, home, h (z i) (by simp)]⟩ + · let t := corner p (if s then Cube.flip Finset.univ x else x) i + refine ⟨{t, p.1 i, p.2 i}, Finset.card_le_three, fun a b h => ?_⟩ + have ht := h t (by simp) + unfold t at ht + simp only [pairOf, home, ht, h (p.1 i) (by simp), h (p.2 i) (by simp)] + · exact ⟨{c.1, c.2.1}, Finset.card_le_two.trans (by decide), + fun a b h => by simp only [pairOf, h c.1 (by simp), h c.2.1 (by simp)]⟩ + +theorem endpoint_net (F : Type) [Field F] (k : Name n r) (f : Worker r × Worker r → Bool) : + BNet F (fun t (_ : Unit) => f (pairOf hn i t k)) (r + 134) := by + obtain ⟨S, hS, h⟩ := support hn i k + have hd : Depends (fun t (_ : Unit) => f (pairOf hn i t k)) 3 := + fun _ => ⟨S, hS, fun x y he => congrArg f (h x y he)⟩ + simpa [localCost] using hd.bnet F + +variable {F : Type} [Field F] {h d : ℕ} (A : Expansion F n h) (N : ℕ) + +theorem pairOf_report (R : A.Report r d) (j : Name n r) : + pairOf hn R.1 (A.groupFlags N R.1 (A.countBits R)) j = + ((descriptor A hn N R j).1, (descriptor A hn N R j).2.1) := by + have hf (g : Fin r) : A.groupFlags N R.1 (A.countBits R) g = false ↔ g ∉ A.reportGroups N R := by + rw [← A.groupFlags_report] + simp + rcases j with (⟨u, z⟩|z)|⟨p, x, b⟩|c + · simp only [pairOf, descriptor, home, Expansion.owner, A.groupFlags_report] + · simp only [pairOf, descriptor, home, Expansion.owner, A.groupFlags_report] + · simp only [pairOf, descriptor, home, Expansion.owner, A.groupFlags_report, hf, Expansion.shared, + decide_eq_true_eq, group, Bool.false_eq_true, ite_false, ite_true] + · simp only [pairOf, descriptor, Expansion.src, Expansion.dst, Expansion.shared, hf, + decide_eq_true_eq] + split <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Computing prefix lengths for the relay schedule -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal Install + +variable {F : Type} [Field F] {N l n h r d : ℕ} + (A : Expansion F n h) (hn : 2 ≤ n) (fa : Machine.Ports N l l → Label n r) + +open Classical in +/-- The construction uses `Worker.index r e.1` for its intermediate `a`. -/ +def selectLink (u v : Fin (3 * r)) (e : Worker r × Worker r) := + let a := Worker.index r e.1 + let b := Worker.index r e.2 + decide (a ≠ b ∧ (a = u ∧ b = v ∨ a = v ∧ b = u)) + +open Classical in +/-- In the case `.inr (.inr c)`, this construction gives `A.classForm i c`. -/ +def capacity (d : ℕ) (i : Fin n) (p : Name n r) : Form (Class r × A.I) := + match p with + | .inr (.inr c) => A.classForm i c + | _ => ⟨fun _ => 0, (records fa h d).length p⟩ + +open Classical in +/-- Returns `(capacity A fa d i p).value x` when `selectLink u v (pairOf hn i (A.groupFlags N i +x) p)` holds, and `0` otherwise. -/ +def bandwidth (i : Fin n) (p : Name n r) (u v : Fin (3 * r)) (x : A.CountBit r d → Bool) := + if selectLink u v (pairOf hn i (A.groupFlags N i x) p) + then (capacity A fa d i p).value x else 0 + +open Classical in +private theorem capacity_eq (p : Name n r) (R : A.Report r d) : + (capacity A fa d R.1 p).value (A.countBits R) = + (records fa h d).length p * (descriptor A hn N R p).2.2 := by + rcases p with (⟨u, z⟩|z)|⟨q, x, b⟩|c + all_goals simp only [capacity, descriptor] + · simp [Form.value, linear] + · simp [Form.value, linear] + · simp [Form.value, linear] + · change _ = 1 * A.classWidth R c + rw [one_mul, A.classForm_report] + +open Classical in +theorem bandwidth_eq (p : Name n r) (R : A.Report r d) (u v : Fin (3 * r)) : + bandwidth A hn fa R.1 p u v (A.countBits R) = (grouping fa A hn R).channels.widthAt u v p := by + rw [bandwidth, pairOf_report, capacity_eq A hn fa] + unfold Channels.widthAt selectLink + let s := grouping fa A hn R + let a := s.fromKey p + let b := s.toKey p + let W := (records fa h d).length p * s.bits p + change (if decide (a ≠ b ∧ (a = u ∧ b = v ∨ a = v ∧ b = u)) then W else 0) = + if a = u ∧ b = v ∨ a = v ∧ b = u then (if a = b then 0 else W) else 0 + by_cases he : a = b <;> simp [he] + +variable {A hn fa} {v w : ℕ} {i : Fin n} + +open Classical in +theorem bandwidth_net + (hg : BNet F (A.groupFlags (r := r) (d := d) N i) v) (p : Name n r) (x y : Fin (3 * r)) : + Register F w (bandwidth (d := d) A hn fa i p x y) + (v + r + 50000 * (1 + Fintype.card (A.CountBit r d)) * (1 + w)) := by + have he := hg.comp (endpoint_net hn i F p (selectLink x y)) + have hc := (capacity A fa d i p).net F w (Expansion.registerWidth n r d) + apply (Register.mask he hc).mono + have hw : Fintype.card (A.CountBit r d) = Fintype.card (Class r × A.I) * Expansion.registerWidth + n r d := + (Fintype.card_prod _ _).trans (congrArg _ (Fintype.card_fin _)) + rw [← hw] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Computing every total and every starting position in the channel numbering -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal Install Finset + +variable {F : Type} [Field F] {N l n h r d : ℕ} [ord : LinearOrder (Name n r)] + (A : Expansion F n h) (hn : 2 ≤ n) (fa : Machine.Ports N l l → Label n r) + +open Classical in +/-- Indexes the query by the coordinates of `Fin (3 * r) × Fin (3 * r) × Option (Name n r)`. -/ +abbrev Query (n r : ℕ) := Fin (3 * r) × Fin (3 * r) × Option (Name n r) + +open Classical in +/-- The value specified by `∑ j, if p.2.2.elim True (@LT.lt _ ord.toLT j) then bandwidth A hn fa +i j p.1 p.2.1 x else 0`. -/ +def addressSum (i : Fin n) (p : Query n r) (x : A.CountBit r d → Bool) := + ∑ j, if p.2.2.elim True (@LT.lt _ ord.toLT j) then bandwidth A hn fa i j p.1 p.2.1 x else 0 + +open Classical in +theorem addressSum_total (R : A.Report r d) (u v : Fin (3 * r)) : + addressSum A hn fa R.1 (u, v, none) (A.countBits R) = + ∑ j, (grouping fa A hn R).channels.widthAt u v j := by + simp only [addressSum, Option.elim_none, ite_true, bandwidth_eq] + +open Classical in +theorem addressSum_start (R : A.Report r d) (u v : Fin (3 * r)) (p : Name n r) : + addressSum A hn fa R.1 (u, v, some p) (A.countBits R) = + start ((grouping fa A hn R).channels.widthAt u v) p := by + simp only [addressSum, Option.elim_some, bandwidth_eq, start, sum_filter] + +open Classical in +/-- Computes the addresses by the application `digits w (addressSum A hn fa i j.1 x) j.2`. -/ +def addresses (w : ℕ) (i : Fin n) (x : A.CountBit r d → Bool) + (j : Query n r × slots (word w)) := digits w (addressSum A hn fa i j.1 x) j.2 + +open Classical in +/-- Counts the elements of `(A.CountBit r d) + Fintype.card (Query n r) *`. -/ +def addressCost (A : Expansion F n h) (r d w v : ℕ) := + Fintype.card (A.CountBit r d) + Fintype.card (Query n r) * + (2 * Fintype.card (A.CountBit r d) + (1 + Fintype.card (Name n r)) * + (v + r + 60000 * (1 + Fintype.card (A.CountBit r d)) * (1 + w))) + +variable {A hn fa} {v w : ℕ} {i : Fin n} + +open Classical in +theorem addresses_net (hg : BNet F (A.groupFlags (r := r) (d := d) N i) v) : + BNet F (addresses (d := d) A hn fa w i) (addressCost A r d w v) := by + let c := v + r + 50000 * (1 + Fintype.card (A.CountBit r d)) * (1 + w) + have ht (p : Query n r) (j : Name n r) : + Register F w (fun x => if p.2.2.elim True (@LT.lt _ ord.toLT j) then + bandwidth (d := d) A hn fa i j p.1 p.2.1 x else 0) c := by + by_cases he : p.2.2.elim True (@LT.lt _ ord.toLT j) + · simp only [ite_eq_left he] + exact bandwidth_net hg _ _ _ + · simp only [ite_eq_right he] + refine (Register.const 0).mono ?_ + unfold c + ring_nf + omega + have hp (p : Query n r) : Register F w (addressSum (d := d) A hn fa i p) + ((1 + Fintype.card (Name n r)) * (v + r + 60000 * (1 + Fintype.card (A.CountBit r d)) * (1 + + w))) := by + refine (Register.sum _ (ht p)).mono (Nat.mul_le_mul_left _ ?_) + unfold c + ring_nf + omega + exact BNet.collect _ hp + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- # Uniform size bounds for all pair lengths and channel offsets -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal Install + +variable {F : Type} [Field F] {N l n h r d w : ℕ} (A : Expansion F n h) + +private theorem address_bound (hn : 2 ≤ n) (hw : 100000000 ≤ w) + (hr : 0 < r) (hc : 2 ^ n ≤ w) (hI : Fintype.card A.I ≤ w) + (hd : Expansion.registerWidth n r d ≤ w * 8) : + addressCost A r d w (A.flagCost r d (w * 14)) ≤ r ^ (16 * n) * w ^ 48 := by + let T := r ^ (2 * n) * w ^ 6 + have hp (i : ℕ) (hi : i ≤ 2 * n) : r ^ i ≤ r ^ (2 * n) := Nat.pow_le_pow_right hr hi + have hrr : 1 ≤ r ^ (2 * n) := by simpa using hp 0 (by omega) + have ht : 4 ≤ T := le_trans (show 4 ≤ w ^ 6 from le_trans (by omega) (Nat.le_pow (by decide))) + (Nat.le_mul_of_pos_left _ hrr) + have hword : 1 + w ≤ T := by + apply le_trans _ (Nat.le_mul_of_pos_left _ hrr) + apply le_trans _ (Nat.pow_le_pow_right (by omega : 0 < w) (by decide : 2 ≤ 6)) + nlinarith + have hname : 1 + Fintype.card (Name n r) ≤ T := by + rw [name_card, ← pow_mul, show n * 2 = 2 * n by ring] + have h₁ : r * r ^ n ≤ r ^ (2 * n) := by rw [← pow_succ']; apply hp; omega + have h₂ := hp n (by omega) + have h₃ := hp 3 (by omega) + have h₄ := Nat.mul_le_mul_left (r ^ (2 * n)) hc + refine le_trans (b := r ^ (2 * n) * (6 + 2 * w)) (by nlinarith only [h₁, h₂, h₃, h₄, hrr]) ?_ + exact Nat.mul_le_mul_left _ (le_trans (by nlinarith) + (Nat.pow_le_pow_right (by omega : 0 < w) (by decide : 2 ≤ 6))) + have hinput : 1 + Fintype.card (A.CountBit r d) ≤ 9 * r ^ 3 * w ^ 2 := by + have he : Fintype.card (A.CountBit r d) = r ^ 3 * Fintype.card A.I * Expansion.registerWidth n + r d := by + simp only [Expansion.CountBit, Fintype.card_prod, Fintype.card_fin, Expansion.registerWidth] + ring + rw [he] + have hm := Nat.mul_le_mul (Nat.mul_le_mul_left (r ^ 3) hI) hd + have hz : 0 < r ^ 3 * w ^ 2 := by positivity + nlinarith only [hm, hz] + have hflag : A.flagCost r d (w * 14) ≤ T := by + unfold Expansion.flagCost + calc + _ ≤ (2 * r) * 100000 * (9 * r ^ 3 * w ^ 2) * (15 * w) := by gcongr <;> omega + _ = r ^ 4 * (27000000 * w ^ 3) := by ring + _ ≤ r ^ (2 * n) * w ^ 4 := by + apply Nat.mul_le_mul (hp 4 (by omega)) + rw [show w ^ 4 = w * w ^ 3 by ring] + gcongr + omega + _ ≤ T := Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) (by decide)) + have hdata : 1 + Fintype.card (A.CountBit r d) ≤ T := by + apply le_trans _ hflag + unfold Expansion.flagCost + exact (Nat.le_mul_of_pos_left _ (by positivity)).trans (Nat.le_mul_of_pos_right _ (by + positivity)) + have hpair : (3 * r) ^ 2 ≤ T := by + rw [show (3 * r) ^ 2 = r ^ 2 * 9 by ring] + exact Nat.mul_le_mul (hp 2 (by omega)) (le_trans (by omega) (Nat.le_pow (by decide))) + have hquery : Fintype.card (Query n r) ≤ T ^ 2 := by + rw [Fintype.card_prod, Fintype.card_prod, Fintype.card_option, Fintype.card_fin] + rw [← mul_assoc, ← pow_two, pow_two T] + exact Nat.mul_le_mul hpair (by omega) + have hs : r ≤ T := by nlinarith only [hpair] + have hk : 60000 ≤ T := by omega + unfold addressCost + calc + _ ≤ T + T ^ 2 * (T * T + T * (T + T + T * T * T)) := by gcongr <;> omega + _ ≤ T ^ 8 := by + have hv (i : ℕ) (hi : i ≤ 6) : T ^ i ≤ T ^ 6 := Nat.pow_le_pow_right (by omega) hi + have hb : 6 * T ^ 6 ≤ T ^ 8 := by rw [show T ^ 8 = T ^ 2 * T ^ 6 by ring]; gcongr; nlinarith + nlinarith only [hv 1 (by decide), hv 4 (by decide), hb] + _ = _ := by unfold T; rw [mul_pow, ← pow_mul, ← pow_mul]; congr 2; ring + +variable [LinearOrder (Name n r)] + +theorem addresses_size (hn : 2 ≤ n) (fa : Machine.Ports N l l → Label n r) (i : Fin n) + (hw : 100000000 ≤ w) (hN : N ≤ 2 ^ w) (hr : 0 < r) (hrN : r ^ (16 * n) ≤ 2 ^ w) + (hc : 2 ^ n ≤ w) (hI : Fintype.card A.I ≤ w) (he : ∀ z, 512 * A.chargeBits i z ≤ w) + (hp : Fintype.card (Packet n r d) < (2 ^ w) ^ 8) : + BNet F (addresses (d := d) A hn fa w i) (2 ^ w * w ^ 48) ∧ + BNet F (A.groupFlags (r := r) (d := d) N i) (2 ^ w * w ^ 48) := by + have hwN : w < 2 ^ w := Nat.lt_two_pow_self + have hb : Expansion.registerWidth n r d ≤ w * 8 := by + apply Nat.clog_le_of_le_pow + rw [pow_mul] + exact hp + have hrow : Fintype.card (Class r × A.I) ≤ (2 ^ w) ^ 2 := by + rw [Fintype.card_prod, show Fintype.card (Class r) = r ^ 3 by simp [Class]; ring, pow_two] + exact Nat.mul_le_mul ((Nat.pow_le_pow_right hr (by omega)).trans hrN) (by omega) + have hg := A.groupFlags_net (r := r) (d := d) (w := w * 14) (N := N) (M := w / 512) i + (fun z => by have := he z; omega) + (hN.trans_lt (Nat.pow_lt_pow_right (by decide) (by omega))) + (by + calc + _ ≤ (2 ^ w) ^ 2 * (2 ^ (w * 8) * 2 ^ w) := by gcongr; omega + _ = 2 ^ (w * 11) := by rw [pow_mul, pow_mul]; ring + _ < 2 ^ (w * 14) := Nat.pow_lt_pow_right (by decide) (by omega)) + have hsize := (address_bound A hn hw hr hc hI hb).trans (Nat.mul_le_mul_right _ hrN) + refine ⟨(addresses_net hg).mono hsize, hg.mono (le_trans ?_ hsize)⟩ + have : Nonempty (Fin (3 * r)) := ⟨⟨0, by omega⟩⟩ + unfold addressCost + calc + _ ≤ 0 + 1 * (0 + 1 * (A.flagCost r d (w * 14) + 0 + 0)) := by simp + _ ≤ _ := by gcongr <;> first | exact Fintype.card_pos | omega + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Capacity.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Capacity.lean new file mode 100644 index 0000000000..2314f2d6fa --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Capacity.lean @@ -0,0 +1,1038 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Replay +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.TemplateSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Broadcast + +/-! +# A fixed template for one copy of the original stations + +The label bits select which of the possible labels belong to a worker. +The remaining bits are one pair of blocks per packet, and the exterior +bits of the copies. This format exposes no table values to the controls. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout + +open Processor +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {n r h : ℕ} (L : Layout G n r h) + +open Classical in +/-- Indexes the tape by the coordinates of `Label n r ⊕ (Position n r L.d h × Bool) ⊕ slots a ⊕ +slots b`. -/ +abbrev Tape := Label n r ⊕ (Position n r L.d h × Bool) ⊕ slots a ⊕ slots b +open Classical in +/-- Indexes the gate by the coordinates of `G.normalized.V ⊕ Position n r L.d h`. -/ +abbrev Gate := G.normalized.V ⊕ Position n r L.d h + +open Classical in +/-- In the case `.inl z`, this construction gives `z`. -/ +def which : L.Tape → Label n r + | .inl z => z + | .inr (.inl (p, s)) => Expansion.endpoint p s + | .inr (.inr (.inl i)) => L.color (.inr (.inl i)) + | .inr (.inr (.inr j)) => L.color (.inr (.inr (.inl j))) + +open Classical in +/-- In the case `.inl v`, this construction gives `L.color v`. -/ +def whereAt : L.Gate → Label n r + | .inl v => L.color v + | .inr p => Expansion.endpoint p false + +open Classical in +/-- In the case `.inl v`, this construction gives `G.normalized.table v`. -/ +def op : L.Gate → Table F + | .inl v => G.normalized.table v + | .inr p => ⟨.bit, .unit, fun x _ => if x = false ∨ ∃ e, L.assign e = p then 1 else 0⟩ + +open Classical in +/-- The value specified by `.inr (.inl (L.assign e, s))`. -/ +def fromPort (s : Bool) (e : G.End) : L.Tape := .inr (.inl (L.assign e, s)) + +open Classical in +/-- In the case `.inl (.inl v), i`, this construction gives `L.fromPort false (G.portEquiv ⟨v, +i⟩)`. -/ +def arg : (g : L.Gate) → PortsOf (L.op g) → L.Tape + | .inl (.inl v), i => L.fromPort false (G.portEquiv ⟨v, i⟩) + | .inl (.inr (.inl i)), .inl _ => .inr (.inr (.inl i)) + | .inl (.inr (.inl i)), .inr _ => L.fromPort true (.inl (.inl i)) + | .inl (.inr (.inr (.inl j))), .inl _ => L.fromPort true (.inr (.inl j)) + | .inl (.inr (.inr (.inl j))), .inr _ => .inr (.inr (.inr j)) + | .inl (.inr (.inr (.inr e))), .inl _ => L.fromPort true (.inr (.inr e)) + | .inl (.inr (.inr (.inr e))), .inr _ => L.fromPort true (.inl (.inr e)) + | .inr p, _ => .inr (.inl (p, false)) + +open Classical in +private theorem which_station (e : G.End) : + L.which (L.fromPort false e) = L.color (.inl (G.station e)) := + congrArg Prod.fst (L.follows e) + +open Classical in +private theorem which_joint (e : G.End) : + L.which (L.fromPort true e) = L.color (.inr (G.junction e)) := + congrArg Prod.snd (L.follows e) + +open Classical in +theorem arg_local (v : L.Gate) (i : PortsOf (L.op v)) : L.which (L.arg v i) = L.whereAt v := by + rcases v with (v | p | q | e) | p + · exact (L.which_station _).trans (congrArg (fun j => L.color (.inl j)) (G.station_port _)) + · cases i + · rfl + · exact L.which_joint _ + · cases i + · exact L.which_joint _ + · rfl + · cases i <;> exact L.which_joint _ + · rfl + +open Classical in +/-- The subtype of `p : L.Tape` satisfying `L.which p i = g`. -/ +abbrev LocalTape (i : Fin n) (g : Fin r) := {p : L.Tape // L.which p i = g} +open Classical in +/-- The subtype of `p : L.Gate` satisfying `L.whereAt p i = g`. -/ +abbrev LocalGate (i : Fin n) (g : Fin r) := {p : L.Gate // L.whereAt p i = g} + +open Classical in +/-- In the case `.inl _`, this construction gives `⟨.inl (L.whereAt v.1), v.2⟩`. -/ +def route (i : Fin n) (g : Fin r) (v : L.LocalGate i g) : + Unit ⊕ PortsOf (L.op v.1) → L.LocalTape i g + | .inl _ => ⟨.inl (L.whereAt v.1), v.2⟩ + | .inr p => ⟨L.arg v.1 p, by rw [L.arg_local]; exact v.2⟩ + +open Classical in +/-- Returns `weight T (x ∘ Sum.inr)` when `x (.inl ())` holds, and `1` otherwise. -/ +def enabled (T : Table F) (x : Unit ⊕ PortsOf T → Bool) := + if x (.inl ()) then weight T (x ∘ Sum.inr) else 1 + +open Classical in +/-- The product of `enabled (L.op v.1) (x ∘ L.route i g v)` indexed by `v : L.LocalGate i g`. -/ +def kernel (i : Fin n) (g : Fin r) (x : L.LocalTape i g → Bool) : F := + ∏ v : L.LocalGate i g, enabled (L.op v.1) (x ∘ L.route i g v) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +section +/- +# Input and gate bounds for a worker template + +Count all candidate gates in one label coordinate, before the +report specifies which ones to enable. The original stations are +charged by incident ends. Junctions are binary and padding pins unary. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +open Finset +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {n r d h M : ℕ} (L : Layout G n r h) + +private theorem sum_at {X : Type} [Fintype X] (f : X → Fin r) (g : Fin r) (k : X → ℕ) : + (∑ p : {v // f v = g}, k p.val) = ∑ v, if f v = g then k v else 0 := by + rw [← sum_filter] + exact (sum_subtype _ (by simp) _).symm + +private theorem sum_count {X : Type} [Fintype X] (f : X → Fin r) (g : Fin r) (k : ℕ) : + (∑ v, if f v = g then k else 0) = multiplicity f g * k := by + rw [← sum_at f g (fun _ => k)] + simp [multiplicity] + +private theorem both_endpoints (i : Fin n) (g : Fin r) : + multiplicity (fun x : Position n r d h × Bool => Expansion.endpoint x.1 x.2 i) g * r = + 2 * Fintype.card (Position n r d h) := by + let f (x : Position n r d h × Bool) := Expansion.endpoint x.1 x.2 i + have he := sum_count f g 1 + rw [mul_one, Fintype.sum_prod_type, sum_comm] at he + change multiplicity f g * r = _ + rw [← he, sum_mul] + have e (s : Bool) : (∑ p, if f (p, s) = g then 1 else 0) * r = + Fintype.card (Position n r d h) := by + rw [sum_count (fun p => f (p, s)), mul_one] + exact endpoint_uniform s i g + simp only [e, sum_const, card_univ, Fintype.card_bool, nsmul_eq_mul, Nat.cast_id] + +variable (hv : ∀ z, multiplicity L.color z * r ^ n ≤ 16 * M) + (hp : Fintype.card (Position n r L.d h) ≤ 13 * M) + +include hv hp in +theorem tape_bound (hl : r ^ n ≤ M) (i : Fin n) (g : Fin r) : + Fintype.card (L.LocalTape i g) * r ≤ 100 * M := by + let f := fun v => L.color v i + let ext : slots a ⊕ slots b → G.normalized.V := Sum.elim + (fun p => .inr (.inl p)) (fun p => .inr (.inr (.inl p))) + have hi : Function.Injective ext := by rintro (x|x) (y|y) <;> simp [ext] + have hE : multiplicity (f ∘ ext) g ≤ multiplicity f g := by + let lift : {v // (f ∘ ext) v = g} → {v // f v = g} := fun v => ⟨ext v.1, v.2⟩ + exact Fintype.card_le_of_injective lift (fun _ _ h => Subtype.ext (hi (congrArg Subtype.val h))) + have hE' := (Nat.mul_le_mul_right r hE).trans (L.vertex_bound hv i g) + have he : (fun p : slots a ⊕ slots b => L.which (.inr (.inr p)) i) = f ∘ ext := by + funext p; cases p <;> rfl + change multiplicity (fun v => L.which v i) g * r ≤ _ + rw [multiplicity_sum, multiplicity_sum] + change (multiplicity (fun z : Label n r => z i) g + + (multiplicity (fun x : Position n r L.d h × Bool => Expansion.endpoint x.1 x.2 i) g + + multiplicity (fun p : slots a ⊕ slots b => L.which (.inr (.inr p)) i) g)) * r ≤ _ + rw [add_mul, add_mul, he, label_uniform, both_endpoints] + omega + +omit [Field F] in +private theorem station_cost (f : G.V → Fin r) (g : Fin r) : + (∑ v, if f v = g then 1 + G.arity v else 0) = + multiplicity f g + multiplicity (f ∘ G.station) g := by + have count {X : Type} [Fintype X] (k : X → Fin r) : + multiplicity k g = ∑ v, if k v = g then 1 else 0 := by + rw [sum_count, mul_one] + rw [count f, count (f ∘ G.station), ← G.portEquiv.sum_comp, Fintype.sum_sigma, + ← sum_add_distrib] + apply sum_congr rfl + intro v _ + simp only [Function.comp_apply, G.station_port] + by_cases he : f v = g <;> simp [he, Diagram.Port, Diagram.arity] + +include hv hp in +theorem gate_bound (i : Fin n) (g : Fin r) : + (∑ v : L.LocalGate i g, (1 + Processor.arity (L.op v.val))) * r ≤ 100 * M := by + let f := fun v => L.color v i + let fs := f ∘ Sum.inl + let fj := f ∘ Sum.inr + let fp := fun p : Position n r L.d h => Expansion.endpoint p false i + have h₁ : (multiplicity fs g + multiplicity fj g) * r ≤ 16 * M := by + rw [← multiplicity_sum f] + exact L.vertex_bound hv i g + have h₂ : multiplicity (fs ∘ G.station) g * r ≤ 26 * M := + (Nat.mul_le_mul_right _ (Nat.le_add_right _ _)).trans (L.end_bound hp i g) + have h₃ : multiplicity fp g * r ≤ 13 * M := (endpoint_uniform false i g).le.trans hp + rw [sum_at (fun v => L.whereAt v i) g (fun v => 1 + Processor.arity (L.op v)), + Fintype.sum_sum_type, Fintype.sum_sum_type] + change ((∑ v, if fs v = g then 1 + G.arity v else 0) + + (∑ v, if fj v = g then 3 else 0) + (∑ v, if fp v = g then 2 else 0)) * r ≤ 100 * M + rw [station_cost fs g, sum_count fj, sum_count fp] + nlinarith only [h₁, h₂, h₃, Nat.zero_le (multiplicity fs g * r)] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +/- # Feeding a station template from one batch of physical assignments -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout + +open Processor +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {n r h B : ℕ} (L : Layout G n r h) + +open Classical in +/-- Reindexes `Fin B × Position n r L.d h` and `Position n r (B * L.d) h where toFun t` by an +equivalence. -/ +def batches (B : ℕ) : Fin B × Position n r L.d h ≃ Position n r (B * L.d) h where + toFun t := ((t.2.1.1, finProdFinEquiv (t.1, t.2.1.2)), t.2.2) + invFun t := ((finProdFinEquiv.symm t.1.2).1, (t.1.1, (finProdFinEquiv.symm t.1.2).2), t.2) + left_inv _ := by simp only [Equiv.symm_apply_apply] + right_inv _ := by simp only [Prod.mk.eta, Equiv.apply_symm_apply] + +open Classical in +theorem pos_batches (t : Fin B) (e : G.End) : L.pos t e = L.batches B (t, L.assign e) := rfl + +open Classical in +/-- In the case `.inl z`, this construction gives `mask z`. -/ +def values (mask : Label n r → Bool) (x : Fin B → Val a) (y : Fin B → Val b) + (s : Bool → L.Slots B) (j : Fin B) : L.Tape → Bool + | .inl z => mask z + | .inr (.inl (p, u)) => (s u) (L.batches B (j, p)).1 (L.batches B (j, p)).2 + | .inr (.inr (.inl i)) => bits a (x j) i + | .inr (.inr (.inr i)) => bits b (y j) i + +variable (mask : Label n r → Bool) (x : Fin B → Val a) (y : Fin B → Val b) + (s : Bool → L.Slots B) (j : Fin B) + +open Classical in +theorem weight_vertex (v : G.normalized.V) : + weight (L.op (.inl v)) (L.values mask x y s j ∘ L.arg (.inl v)) = + G.normalized.vertex (x j) (y j) (L.read (s v.isRight) j) v := by + rcases v with v | i | p | e <;> rfl + +open Classical in +theorem weight_pin (p : Position n r L.d h) : + weight (L.op (.inr p)) (L.values mask x y s j ∘ L.arg (.inr p)) = + L.pin (s false) (L.batches B (j, p)) := by + have he : (∃ (k : Fin B) (e : G.End), L.pos k e = L.batches B (j, p)) ↔ ∃ e, L.assign e = p := by + simp only [pos_batches, (L.batches B).injective.eq_iff, Prod.mk.injEq] + simp + unfold pin + simp only [he] + rfl + +open Classical in +/-- Restrict to the potentially active gates before taking their product. -/ +theorem kernel_values (i : Fin n) (g : Fin r) (hm : ∀ z, mask z = true → z i = g) : + L.kernel i g (fun t => L.values mask x y s j t.1) = + ∏ v : L.Gate, if mask (L.whereAt v) then + weight (L.op v) (L.values mask x y s j ∘ L.arg v) else 1 := by + let f (v : L.Gate) := if mask (L.whereAt v) then + weight (L.op v) (L.values mask x y s j ∘ L.arg v) else 1 + change (∏ v : L.LocalGate i g, f v.1) = ∏ v, f v + rw [← Finset.prod_subtype (Finset.univ.filter (fun v => L.whereAt v i = g)) + (p := fun v => L.whereAt v i = g) (by simp) f] + apply Finset.prod_subset (Finset.subset_univ _) + intro v _ hv + exact ite_eq_right (fun h => hv (Finset.mem_filter.mpr ⟨Finset.mem_univ v, hm _ h⟩)) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +/- # Cost of one worker's station template -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout + +open Processor Install +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {n r h : ℕ} (L : Layout G n r h) {K q D : ℕ} + +omit [Field F] in +open Classical in +private theorem card_ports (T : Table F) : Fintype.card (PortsOf T) = arity T := by + simp [PortsOf, arity] + +open Classical in +private theorem enabled_net (hG : G.Admits D (Cheap F K q)) (v : L.Gate) : + Weight F (enabled (L.op v)) + ((1 + arity (L.op v)) * (1000 * (rate K q (D + 2) + 1))) := by + have hd : arity (L.op v) ≤ D + 2 ∧ (arity (L.op v) ≤ 3 ∨ L.op v ∈ Cheap F K q) := by + rcases v with (v|v)|v + · exact ⟨(hG v).1.trans (Nat.le_add_right _ _), (hG v).2⟩ + · change 2 ≤ D + 2 ∧ (2 ≤ 3 ∨ _) + exact ⟨by omega, .inl (by decide)⟩ + · change 1 ≤ D + 2 ∧ (1 ≤ 3 ∨ _) + exact ⟨by omega, .inl (by decide)⟩ + apply (weight_cheap hd.1 hd.2).branch.mono + rw [card_ports] + exact le_of_eq (by ring) + +open Classical in +/-- The sum of `(1 + arity (L.op v.val))` indexed by `v : L.LocalGate i g`. -/ +def instructions (i : Fin n) (g : Fin r) := + ∑ v : L.LocalGate i g, (1 + arity (L.op v.val)) + +open Classical in +/-- The quantity computed by `Fintype.card (L.LocalTape i g) + L.instructions i g * (1002 + 1000 +* rate K q (D + 2))`. -/ +def bill (i : Fin n) (g : Fin r) (K q D : ℕ) := + Fintype.card (L.LocalTape i g) + L.instructions i g * (1002 + 1000 * rate K q (D + 2)) + +open Classical in +theorem kernel_net (hG : G.Admits D (Cheap F K q)) (i : Fin n) (g : Fin r) : + Weight F (L.kernel i g) (L.bill i g K q D) := by + let I (v : L.LocalGate i g) := Unit ⊕ PortsOf (L.op v.val) + have hp := Weight.sigma_prod (I := I) (fun v => enabled (L.op v.val)) + (fun v => L.enabled_net hG v.val) + have hp' := hp.pull (fun p : Σ v, I v => L.route i g p.1 p.2) + refine hp'.mono ?_ + have hsize : Fintype.card (Σ v, I v) = L.instructions i g := by + rw [Fintype.card_sigma] + apply Finset.sum_congr rfl + intro v _ + change Fintype.card (Unit ⊕ PortsOf (L.op v.val)) = _ + rw [Fintype.card_sum, Fintype.card_unit, card_ports] + rw [hsize, ← Finset.sum_mul] + change Fintype.card (L.LocalTape i g) + 2 * L.instructions i g + + L.instructions i g * (1000 * (rate K q (D + 2) + 1)) ≤ L.bill i g K q D + unfold bill + exact le_of_eq (by ring) + +open Classical in +/-- The same binary script works on arbitrary input data for every +repetition, including arbitrary label activation flags. -/ +theorem kernel_script [Fintype F] (hG : G.Admits D (Cheap F K q)) (i : Fin n) (g : Fin r) + {w : ℕ} (hw : 2 * L.bill i g K q D ≤ 2 ^ w) (idx : L.LocalTape i g → Fin (2 ^ w)) : + ∃ code, ∀ x, template F w (Sum.elim x code) = L.kernel i g (x ∘ idx) := + weight_program (L.kernel_net hG i g) hw idx + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +/- +# A fixed bank of programmable network templates + +Rows can have different template sizes and repetition counts. A single +script is supplied for each row and is reused on all its inputs. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Install + +open Classical in +/-- The data for the bank construction, including `width`, `repetitions`. -/ +structure Bank (I : Type) where + /-- The width parameter carried by `Bank`, with type `I → ℕ`. -/ + width : I → ℕ + /-- The repeat count of type `I → ℕ`. -/ + repetitions : I → ℕ + +namespace Bank +variable {I : Type} [Fintype I] (b : Bank I) (F : Type) [Field F] [Fintype F] + +open Classical in +/-- Indexes the data by the coordinates of `Σ i, Fin (2 ^ b.repetitions i) × Fin (2 ^ b.width +i)`. -/ +abbrev Data := Σ i, Fin (2 ^ b.repetitions i) × Fin (2 ^ b.width i) +open Classical in +/-- Indexes the bits by the coordinates of `Σ i, Script F (b.width i + 1)`. -/ +abbrev Bits := Σ i, Script F (b.width i + 1) + +open Classical in +/-- The indexed operation `∏ i, repeated F (b.width i) (b.repetitions i) (Sum.elim (fun p => s +(.inl ⟨i, p⟩)) (fun j => s (.inr ⟨i, j⟩)))`. -/ +def result (s : b.Data ⊕ b.Bits F → Bool) : F := + ∏ i, repeated F (b.width i) (b.repetitions i) + (Sum.elim (fun p => s (.inl ⟨i, p⟩)) (fun j => s (.inr ⟨i, j⟩))) + +open Classical in +/-- The quantity computed by `∑ i, templateCost F * 2 ^ (b.repetitions i) * 2 ^ (b.width i) * +(b.width i + 2) ^ 3`. -/ +def budget : ℕ := ∑ i, templateCost F * 2 ^ (b.repetitions i) * 2 ^ (b.width i) * (b.width i + + 2) ^ 3 + +open Classical in +theorem net : Weight F (b.result F) (b.budget F) := by + have t := Weight.sigma_prod (fun i => repeated F (b.width i) (b.repetitions i)) + (fun i => repeated_net F (b.width i) (b.repetitions i)) + let e := Equiv.sigmaSumDistrib (fun i => Fin (2 ^ b.repetitions i) × Fin (2 ^ b.width i)) + (fun i => Script F (b.width i + 1)) + unfold budget + convert t.rename e using 1 + funext s + apply Finset.prod_congr rfl + intro i _ + apply congrArg (repeated F _ _) + funext j + cases j <;> rfl + +open Classical in +/-- The choice of the functions and their wiring affects only the scripts. -/ +theorem programs {X : I → Type} [∀ i, Finite (X i)] (f : (i : I) → (X i → Bool) → F) + (m : I → ℕ) (hf : ∀ i, Weight F (f i) (m i)) (hm : ∀ i, 2 * m i ≤ 2 ^ b.width i) + (src : ∀ i, X i → Fin (2 ^ b.width i)) : + ∃ c : b.Bits F → Bool, ∀ s : b.Data → Bool, b.result F (Sum.elim s c) = + ∏ i, ∏ j : Fin (2 ^ b.repetitions i), f i (fun k => s ⟨i, j, src i k⟩) := by + choose code hcode using fun i => weight_program (hf i) (hm i) (src i) + refine ⟨fun z => code z.1 z.2, fun s => ?_⟩ + apply Finset.prod_congr rfl + intro i _ + apply Finset.prod_congr rfl + intro j _ + exact hcode i (fun k => s ⟨i, j, k⟩) + +end Bank +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- +# Literal bits for a bank of templates + +The zero string marks padding. A program starts with a set bit, then +one bit per worker identifying the active worker, then the script. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Bank + +variable {n : ℕ} (b : Bank (Fin n)) (F : Type) [Fintype F] (l r : ℕ) + (hl : 1 + 3 * r + Fintype.card (b.Bits F) ≤ l) + +/-- Indexes the literal slot by the coordinates of `Unit ⊕ Fin (3 * r) ⊕ b.Bits F`. -/ +abbrev LiteralSlot := Unit ⊕ Fin (3 * r) ⊕ b.Bits F + +/-- Embeds `b.LiteralSlot F r` into `Fin l`. -/ +def literalPort : b.LiteralSlot F r ↪ Fin l := by + let row := ((Equiv.refl (Fin (3 * r))).sumCongr (Fintype.equivFin (b.Bits F))).trans + finSumFinEquiv + let head := ((Equiv.ofUnique Unit (Fin 1)).sumCongr row).trans finSumFinEquiv + exact head.toEmbedding.trans (Fin.castLEEmb (by omega)) + +@[simp] theorem literalPort_zero : (b.literalPort F l r hl (.inl ())).val = 0 := rfl + +/-- Indexes the literal by the coordinates of `Option (Fin (3 * r) × (b.Bits F → Bool))`. -/ +abbrev Literal := Option (Fin (3 * r) × (b.Bits F → Bool)) + +/-- In the case `none, _`, this construction gives `false`. -/ +def fields : b.Literal F r → b.LiteralSlot F r → Bool + | none, _ => false + | some _, .inl _ => true + | some p, .inr (.inl j) => decide (p.1 = j) + | some p, .inr (.inr j) => p.2 j + +omit [Fintype F] in +theorem fields_inj : Function.Injective (b.fields F r) := by + rintro (_|p) (_|q) he + · rfl + · exact (Bool.false_ne_true (congrFun he (.inl ()))).elim + · exact (Bool.false_ne_true (congrFun he (.inl ())).symm).elim + · apply congrArg some + apply Prod.ext + · simpa [fields] using congrFun he (.inr (.inl q.1)) + · exact funext fun j => congrFun he (.inr (.inr j)) + +/-- Embeds `b.Literal F r` into `(Fin l → Bool)`. -/ +def literalCode : b.Literal F r ↪ (Fin l → Bool) := by + let e := b.literalPort F l r hl + refine ⟨fun p => Function.extend e (b.fields F r p) (fun _ => false), ?_⟩ + intro p q he + apply b.fields_inj F r + funext i + exact ((e.injective.extend_apply _ _ i).symm.trans (congrFun he (e i))).trans + (e.injective.extend_apply _ _ i) + +private theorem literalCode_at (p : b.Literal F r) (i : b.LiteralSlot F r) : + b.literalCode F l r hl p (b.literalPort F l r hl i) = b.fields F r p i := + (b.literalPort F l r hl).injective.extend_apply (b.fields F r p) (fun _ => false) i + +theorem literalCode_pad (p : b.Literal F r) (i : Fin l) + (hi : i ∉ Set.range (b.literalPort F l r hl)) : + b.literalCode F l r hl p i = false := + Function.extend_apply' (b.fields F r p) (fun _ => false) i hi + +@[simp] theorem literalCode_none (i : Fin l) : b.literalCode F l r hl none i = false := by + by_cases hi : i ∈ Set.range (b.literalPort F l r hl) + · obtain ⟨j, rfl⟩ := hi + exact b.literalCode_at F l r hl none j + · exact b.literalCode_pad F l r hl none i hi + +variable (p : Fin (3 * r) × (b.Bits F → Bool)) + +@[simp] theorem literalCode_flag : + b.literalCode F l r hl (some p) (b.literalPort F l r hl (.inl ())) = true := + b.literalCode_at F l r hl (some p) (.inl ()) + +@[simp] theorem literalCode_worker (j : Fin (3 * r)) : + b.literalCode F l r hl (some p) (b.literalPort F l r hl (.inr (.inl j))) = decide (p.1 = j) := + b.literalCode_at F l r hl (some p) (.inr (.inl j)) + +@[simp] theorem literalCode_script (j : b.Bits F) : + b.literalCode F l r hl (some p) (b.literalPort F l r hl (.inr (.inr j))) = p.2 j := + b.literalCode_at F l r hl (some p) (.inr (.inr j)) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Bank +end + +/- # Reusing one station script in all copies at a site -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout + +open Processor +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {n r h B : ℕ} (L : Layout G n r h) (A : Expansion F n h) + {hn : 2 ≤ n} {N : ℕ} {R : A.Report r (B * L.d)} + +open Classical in +/-- Tests whether `A.owner hn N R z = u` holds. -/ +def siteMask (u : Worker r) (z : Label n r) : Bool := decide (A.owner hn N R z = u) + +open Classical in +theorem base_kernel (u : Worker r) (i : Fin n) (g : Fin r) + (ho : ∀ z, A.owner hn N R z = u → z i = g) + (x : Fin B → Val a) (y : Fin B → Val b) (s : A.Assignment hn N R) : + L.base A x y s u = ∏ j, L.kernel i g + (fun t => L.values (siteMask L A (hn := hn) (N := N) (R := R) u) x y (A.rows s) j t.1) := by + let f := siteMask L A (hn := hn) (N := N) (R := R) u + have hf : ∀ z, f z = true → z i = g := fun z h => ho _ (of_decide_eq_true h) + let v (j : Fin B) (q : G.normalized.V) := + if A.owner hn N R (L.color q) = u then + G.normalized.vertex (x j) (y j) (L.read (A.rows s q.isRight) j) q else 1 + let p (t : Position n r (B * L.d) h) := + if A.owner hn N R (Expansion.endpoint t false) = u then L.pin (A.rows s false) t else 1 + have hw (j : Fin B) : L.kernel i g (fun t => L.values f x y (A.rows s) j t.1) = + (∏ q, v j q) * (∏ t, p (L.batches B (j, t))) := by + rw [kernel_values _ _ _ _ _ _ _ _ hf, Fintype.prod_sum_type] + apply congrArg₂ (· * ·) + · apply Finset.prod_congr rfl + intro q _ + rw [L.weight_vertex f x y (A.rows s) j q] + simp only [f, siteMask, decide_eq_true_eq, whereAt, v] + · apply Finset.prod_congr rfl + intro t _ + rw [L.weight_pin f x y (A.rows s) j t] + simp only [f, siteMask, decide_eq_true_eq, whereAt] + rfl + change L.base A x y s u = ∏ j, L.kernel i g (fun t => L.values f x y (A.rows s) j t.1) + simp_rw [hw] + rw [Finset.prod_mul_distrib, base, Fintype.prod_sum_type, Fintype.prod_prod_type] + apply congrArg₂ (· * ·) + · apply Finset.prod_congr rfl + intro j _ + apply Finset.prod_congr rfl + rintro (q|q) _ <;> rfl + · change (∏ t, p t) = _ + rw [← (L.batches B).prod_comp p, Fintype.prod_prod_type] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +/- # Selecting a worker's active labels and batch copies -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout + +open Processor Finset +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {n r h B : ℕ} (L : Layout G n r h) + +open Classical in +/-- Inactive data can be replaced by zero instead of being read remotely. -/ +def active (mask : Label n r → Bool) (y : L.Tape → Bool) (t : L.Tape) : Bool := + if mask (L.which t) then y t else false + +open Classical in +theorem kernel_zero (i : Fin n) (g : Fin r) : L.kernel i g (fun _ => false) = 1 := by + unfold kernel + apply prod_eq_one + intro v _ + rfl + +open Classical in +private theorem kernel_active (i : Fin n) (g : Fin r) (mask : Label n r → Bool) + (x : Fin B → Val a) (y : Fin B → Val b) (s : Bool → L.Slots B) (j : Fin B) : + L.kernel i g (fun t => L.active mask (L.values mask x y s j) t.val) = + L.kernel i g (fun t => L.values mask x y s j t.val) := by + unfold kernel + apply prod_congr rfl + intro v _ + by_cases hv : mask (L.whereAt v.val) = true + · apply congrArg (enabled (L.op v.val)) + funext q + cases q with + | inl k => exact ite_eq_left hv + | inr k => exact ite_eq_left ((congrArg mask (L.arg_local v.val k)).trans hv) + · have he : mask (L.whereAt v.val) = false := Bool.eq_false_of_not_eq_true hv + simp [enabled, route, active, which, values, he] + +variable (A : Expansion F n h) {hn : 2 ≤ n} {N : ℕ} {R : A.Report r (B * L.d)} + +open Classical in +/-- In the case `.home g | .station g | .packet g`, this construction gives `g`. -/ +def symbol : Worker r → Fin r + | .home g | .station g | .packet g => g + +open Classical in +/-- In the case `.home _ | .packet _`, this construction gives `i`. -/ +def axis (hn : 2 ≤ n) (i : Fin n) : Worker r → Fin n + | .home _ | .packet _ => i + | .station _ => other hn i + +open Classical in +private theorem owner_here (u : Worker r) (z : Label n r) + (he : A.owner hn N R z = u) : z (axis hn R.1 u) = symbol u := by + subst u + unfold Expansion.owner + split <;> rfl + +open Classical in +/-- Contents of a named bit in one row of the worker's data. -/ +def entry (u : Worker r) (x : Fin B → Val a) (y : Fin B → Val b) + (s : A.Assignment hn N R) (i : Fin n) (j : ℕ) (t : L.LocalTape i (symbol u)) : Bool := + if hj : j < B ∧ i = axis hn R.1 u then + let mask := L.siteMask A (hn := hn) (N := N) (R := R) u + L.active mask (L.values mask x y (A.rows s) ⟨j, hj.1⟩) t.1 + else false + +open Classical in +theorem base_entries (u : Worker r) (x : Fin B → Val a) (y : Fin B → Val b) + (s : A.Assignment hn N R) (len : Fin n → ℕ) (hl : ∀ i, B ≤ len i) : + L.base A x y s u = + ∏ i, ∏ j : Fin (len i), L.kernel i (symbol u) (L.entry A u x y s i j.val) := by + let i := axis hn R.1 u + rw [Fintype.prod_eq_single i] + · rw [L.base_kernel A u i (symbol u) (L.owner_here A u) x y s] + symm + rw [prod_padded (Fin.castLEEmb (hl i))] + · refine prod_congr rfl (fun t _ => ?_) + have he : (Fin.castLEEmb (hl i) t).val < B ∧ i = axis hn R.1 u := ⟨t.2, rfl⟩ + unfold entry + simp only [dite_eq_left he] + exact L.kernel_active _ _ _ _ _ _ _ + · intro j hj + have he : ¬ (j.val < B ∧ i = axis hn R.1 u) := fun h => hj ⟨⟨j, h.1⟩, rfl⟩ + unfold entry + simp only [dite_eq_right he, kernel_zero] + · intro k hk + apply prod_eq_one + intro j _ + have he : ¬ (j.val < B ∧ k = axis hn R.1 u) := fun h => hk h.2 + unfold entry + simp only [dite_eq_right he, kernel_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +/- # One set of scripts for all reports and all copies -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout + +open Processor +variable {F : Type} [Field F] [Fintype F] {a b : Wire} {G : Diagram F a b} + {n r h B K q D : ℕ} (L : Layout G n r h) + (M : Bank (Fin n)) (u : Worker r) + +open Classical in +/-- The choice of addresses is part of the script. It need not preserve +order, and can be chosen to match the controller's data layout. -/ +abbrev Index := (i : Fin n) → L.LocalTape i (symbol u) → Fin (2 ^ M.width i) + +open Classical in +theorem station_scripts (hG : G.Admits D (Cheap F K q)) + (hw : ∀ i, 2 * L.bill i (symbol u) K q D ≤ 2 ^ M.width i) + (hl : ∀ i, B ≤ 2 ^ M.repetitions i) (idx : L.Index M u) : + ∃ c : M.Bits F → Bool, ∀ (A : Expansion F n h) (hn : 2 ≤ n) (N : ℕ) + (R : A.Report r (B * L.d)) (x : Fin B → Val a) (y : Fin B → Val b) + (s : A.Assignment hn N R) (z : M.Data → Bool), + (∀ i j v, z ⟨i, j, idx i v⟩ = L.entry A u x y s i j.val v) → + M.result F (Sum.elim z c) = L.base A x y s u := by + obtain ⟨c, hc⟩ := M.programs F (fun i => L.kernel i (symbol u)) _ + (fun i => L.kernel_net hG i (symbol u)) hw idx + refine ⟨c, fun A hn N R x y s z hz => ?_⟩ + rw [hc, L.base_entries A u x y s _ hl] + simp only [hz] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Layout +end + +/- +# Public data independent of the replacement graph + +A processor needs to know the exterior coloring and the number of +packets. The assignment to interior vertices and their tables is +entirely encoded by its station script. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal +variable {F : Type} [Field F] {N l d B n r h : ℕ} + +open Classical in +/-- Indexes the tape by the coordinates of `Label n r ⊕ (Position n r t h × Bool) ⊕ slots +(copies (Machine.tape N l l) d) ⊕ slots (copies .unit d)`. -/ +abbrev Tape (N l d n r h t : ℕ) := + Label n r ⊕ (Position n r t h × Bool) ⊕ slots (copies (Machine.tape N l l) d) ⊕ slots (copies + .unit d) + +open Classical in +/-- The data for the format construction, including `count`, `colors`, `which`. -/ +structure Format (N l d n r h : ℕ) where + /-- The number of entries. -/ + count : ℕ + /-- The `Format` component of type `Machine.Ports N l l → Label n r`. -/ + colors : Machine.Ports N l l → Label n r + /-- The `Format` component of type `Tape N l d n r h count → Label n r`. -/ + which : Tape N l d n r h count → Label n r + +namespace Format + +open Classical in +/-- Uses `⟨S.layout.d, S.colors, S.layout.which⟩` as the representation. -/ +def ofScheme {G : MachineDiagram F N l l d} {A : Expansion F n h} {hn : 2 ≤ n} + (S : Scheme A hn G r B) : Format N l d n r h := + ⟨S.layout.d, S.colors, S.layout.which⟩ + +open Classical in +/-- Builds `Format N l d n r h where count` with the specified `count`, `colors`. -/ +def prescribed (d h t : ℕ) (fa : Machine.Ports N l l → Label n r) : Format N l d n r h where + count := t + colors := fa + which + | .inl z => z + | .inr (.inl (p, s)) => Expansion.endpoint p s + | .inr (.inr (.inl i)) => fa (Machine.address N l l (port (Machine.tape N l l) d i).2) + | .inr (.inr (.inr i)) => (port .unit d i).2.elim + +open Classical in +theorem ofScheme_eq {G : MachineDiagram F N l l d} {A : Expansion F n h} {hn : 2 ≤ n} + (S : Scheme A hn G r B) {fa : Machine.Ports N l l → Label n r} {t : ℕ} + (hf : S.colors = fa) (ht : S.layout.d = t) : ofScheme S = prescribed d h t fa := by + subst fa t + unfold ofScheme prescribed + congr 1 + funext u + rcases u with z | ⟨p, s⟩ | i | i + · rfl + · rfl + · exact S.exterior i + · exact (port .unit d i).2.elim + +variable (P : Format N l d n r h) (M : Bank (Fin n)) + +open Classical in +/-- The subtype of `u : Tape N l d n r h P.count` satisfying `P.which u i = g`. -/ +abbrev LocalTape (i : Fin n) (g : Fin r) := {u : Tape N l d n r h P.count // P.which u i = g} +open Classical in +/-- The quantity computed by `(i : Fin n) → (g : Fin r) → P.LocalTape i g ↪ Fin (2 ^ M.width +i)`. -/ +abbrev Index := (i : Fin n) → (g : Fin r) → P.LocalTape i g ↪ Fin (2 ^ M.width i) + +variable (A : Expansion F n h) (hn : 2 ≤ n) (B : ℕ) + +open Classical in +/-- The quantity computed by `A.Accepted (r := r) (d := B * P.count) hn (A.budget hn N)`. -/ +abbrev Reports := A.Accepted (r := r) (d := B * P.count) hn (A.budget hn N) + +open Classical in +/-- The value specified by `A.owner hn N R.val ∘ P.colors`. -/ +def route (R : P.Reports A hn B) := A.owner hn N R.val ∘ P.colors + +open Classical in +/-- Computes the serial by the application `A.ExtraSerial hn N R.val (Worker.index r) (Pin.src +(P.route A hn B R)) (Pin.dst (P.route A hn B R))`. -/ +abbrev Serial (R : P.Reports A hn B) := A.ExtraSerial hn N R.val (Worker.index r) + (Pin.src (P.route A hn B R)) (Pin.dst (P.route A hn B R)) + +variable (R : P.Reports A hn B) (s : A.Assignment hn N R.val) + (x : Fin B → Val (copies (Machine.tape N l l) d)) (u : Worker r) + +open Classical in +/-- In the case `.inl z`, this construction gives `decide (A.owner hn N R.val z = u)`. -/ +def raw (j : Fin B) : Tape N l d n r h P.count → Bool + | .inl z => decide (A.owner hn N R.val z = u) + | .inr (.inl (p, v)) => A.rows s v (p.1.1, finProdFinEquiv (j, p.1.2)) p.2 + | .inr (.inr (.inl i)) => bits (copies (Machine.tape N l l) d) (x j) i + | .inr (.inr (.inr i)) => bits (copies .unit d) (unitCopies d) i + +open Classical in +/-- The fill of type `Bool` for the given inputs. -/ +def fill (idx : P.Index M) (z : M.Data) : Bool := + if hv : z.2.1.val < B ∧ z.1 = Layout.axis hn R.val.1 u then + Function.extend (idx z.1 (Layout.symbol u)) (fun t => + if A.owner hn N R.val (P.which t.1) = u then P.raw A hn B R s x u ⟨z.2.1.val, hv.1⟩ t.1 + else false) (fun _ => false) z.2.2 + else false + +end Format +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Reading a site-independent address format at a program site -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Format + +open Diagonal +variable {F : Type} [Field F] {N l d B n r h : ℕ} + {G : MachineDiagram F N l l d} {A : Expansion F n h} {hn : 2 ≤ n} + (S : Scheme A hn G r B) (M : Bank (Fin n)) (idx : (ofScheme S).Index M) + (R : S.Report) (s : A.Assignment hn N R.val) + (x : Fin B → Val (copies (Machine.tape N l l) d)) (u : Worker r) + +open Classical in +private theorem raw_eq (j : Fin B) (p : S.layout.Tape) : + (ofScheme S).raw A hn B R s x u j p = S.layout.values + (S.layout.siteMask A (hn := hn) (N := N) (R := R.val) u) x (fun _ + => unitCopies d) (A.rows s) j p := by + rcases p with z|⟨p, b⟩|i|j <;> rfl + +open Classical in +theorem fill_entry (i : Fin n) (j : Fin (2 ^ M.repetitions i)) + (p : S.layout.LocalTape i (Layout.symbol u)) : + (ofScheme S).fill M A hn B R s x u idx ⟨i, j, idx i (Layout.symbol u) p⟩ = + S.layout.entry A u x (fun _ => unitCopies d) s i j.val p := by + unfold fill Layout.entry + by_cases hv : j.val < B ∧ i = Layout.axis hn R.val.1 u + · simp only [dite_eq_left hv] + let g (t : (ofScheme S).LocalTape i (Layout.symbol u)) := + if A.owner hn N R.val ((ofScheme S).which t.1) + = u then (ofScheme S).raw A hn B R s x u ⟨j.val, hv.1⟩ t.1 else false + refine ((idx i (Layout.symbol u)).injective.extend_apply g (fun _ => false) p).trans ?_ + unfold Layout.active Layout.siteMask + simp only [decide_eq_true_eq] + exact congrArg (fun t => if A.owner hn N R.val (S.layout.which p.1) = u then t else false) + (raw_eq S R s x u _ p.1) + · simp only [dite_eq_right hv] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Format +end + +/- +# An interpreter independent of the interior of the graph + +The only graph-specific input is the literal, consisting of a processor +number and one bank of scripts. Wire numbering may depend on the public +report. The bit lengths are fixed before any compressed diagram is given. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal Machine +variable {F : Type} [Field F] [Fintype F] {N l d B n r h : ℕ} + +open Classical in +/-- The data for the controller construction, including `index`, `number`, `links`, `packets`, +`pins`. -/ +structure Controller (P : Format N l d n r h) (A : Expansion F n h) + (hn : 2 ≤ n) (M : Bank (Fin n)) (B : ℕ) where + /-- The identification of the indices of type `P.Index M`. -/ + index : P.Index M + /-- The `Controller` component of type `(R : P.Reports A hn B) → P.Serial A hn B R`. -/ + number : (R : P.Reports A hn B) → P.Serial A hn B R + links : 64 * (3 * r) ^ 2 ≤ N + packets : ∀ s : Packet n r (B * P.count) → A.I, A.budget hn N (A.report hn s) + pins : ∀ (R : A.Report r (B * P.count)) (u : Worker r), + let f := A.owner hn N R ∘ P.colors + 128 * Fintype.card {e : Pin N l l r // Pin.src f e ≠ Pin.dst f e ∧ + (Pin.src f e = u ∨ Pin.dst f e = u)} ≤ N + fits : Nat.clog 2 n + r ^ 3 * Fintype.card A.I * Nat.clog 2 (Fintype.card (Packet n r (B * + P.count)) + 1) + + 1 ≤ l + literal : 1 + 3 * r + Fintype.card (M.Bits F) ≤ l + +namespace Controller + +variable {P : Format N l d n r h} {A : Expansion F n h} {hn : 2 ≤ n} {M : Bank (Fin n)} + (C : Controller P A hn M B) + +open Classical in +/-- Computes the code by the application `M.literalCode F l r C.literal`. -/ +abbrev code := M.literalCode F l r C.literal + +open Classical in +/-- The indexed operation `feed (C.code none) (fun _ => false) (fun _ => false)`. -/ +def pad : Val (tape N l l) := feed (C.code none) (fun _ => false) (fun _ => false) + +open Classical in +/-- The private assignment supplies both the old exterior values and +the packet slots required by the original stations. -/ +def joint (R : P.Reports A hn B) (c : M.Bits F → Bool) (ξ : Fin l → Bool) (u : Worker r) + (y : Pin N l l r → Bool) (s : A.Assignment hn N R.1) : F := + let x := P.fill M A hn B R s (Pin.input C.pad y) u C.index + Pin.mask F u ξ y * (M.result F (Sum.elim x c) * A.factor s u) + +open Classical in +/-- The site used in the `Controller` construction. -/ +def site (i : Fin (3 * r)) (c : M.Bits F → Bool) (R : P.Reports A hn B) (y : Fin (N / 4) → Bool) := + A.extraProcessor hn N R.1 (Worker.index r) R.2.2 C.links + (Pin.src (P.route A hn B R)) (Pin.dst (P.route A hn B R)) (C.pins R.1) + (C.joint R c (C.code (some (i, c)))) (C.number R) i y + +open Classical in +/-- The contents of an interpreter table at a valid script literal. -/ +def run (i : Fin (3 * r)) (c : M.Bits F → Bool) (z : Fin l → Bool) (y : Fin (N / 4) → Bool) := + branch (A.encodeReport hn N r (B * P.count) l C.fits) (C.site i c) z y + +open Classical in +/-- Requires `U C.pad () = 1 ∧ ∀ i c z y, U (feed (C.code (some (i, c))) z y) () = C.run i c z +y`. -/ +def Agrees (U : Val (tape N l l) → Val .unit → F) : Prop := + U C.pad () = 1 ∧ ∀ i c z y, U (feed (C.code (some (i, c))) z y) () = C.run i c z y + +end Controller +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Programming a replacement with its local station scripts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal Machine + +variable {F : Type} [Field F] [Fintype F] {N l d B n r h K q D : ℕ} + {G : MachineDiagram F N l l d} {A : Expansion F n h} {hn : 2 ≤ n} + {P : Format N l d n r h} {M : Bank (Fin n)} (C : Controller P A hn M B) + (S : Scheme A hn G r B) (hP : Format.ofScheme S = P) + (hG : G.Admits D (Cheap F K q)) + (hw : ∀ i g, 2 * S.layout.bill i g K q D ≤ 2 ^ M.width i) + (hl : ∀ i, B ≤ 2 ^ M.repetitions i) + +include hP hG hw hl in +open Classical in +/-- The graph-specific script is short and fixed before any report, +input assignment or physical-link value is known. -/ +theorem programs (hf : S.fits) (U : Val (tape N l l) → Val .unit → F) (hu : C.Agrees U) : + S.Programs C.pad U (S.encodeReport hf) := by + subst P + refine ⟨C.number, fun u => ?_⟩ + let v := (Worker.index r).symm u + obtain ⟨c, hc⟩ := S.layout.station_scripts M v hG (fun i => hw i _) hl + (fun i => C.index i (Layout.symbol v)) + let ξ := C.code (some (u, c)) + refine ⟨ξ, fun z y => ?_⟩ + have he (R : S.Report) : C.joint R c ξ v = S.joint C.pad R ξ v := by + funext p a + unfold joint Scheme.joint Layout.localWeight + refine congrArg (fun x => Pin.mask F v ξ p * (x * A.factor a v)) ?_ + apply hc A hn N R.1 (Pin.input C.pad p) (fun _ => unitCopies d) a + exact Format.fill_entry S M C.index R a _ v + have ht : C.site u c = fun R => S.simulate C.pad R (C.number R) u ξ := by + funext R + exact A.extraProcessor_congr hn N R.1 (Worker.index r) R.2.2 C.links _ _ (C.pins R.1) + (C.number R) u (he R) + rw [hu.2 u c z y, run, ht] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- # Script and data capacity at a fixed scale -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal +variable {F : Type} [Field F] [Fintype F] {N l d B n r h K q D C : ℕ} + {G : MachineDiagram F N l l d} {A : Expansion F n h} {hn : 2 ≤ n} + (S : Scheme A hn G r B) (M : Bank (Fin n)) + +omit [Fintype F] in +open Classical in +theorem bill_bound (hc : S.compact C) (hd : D ^ 2 ≤ N) (hr : 0 < r) (hm : r ^ n ≤ C * N * d) + (hw : ∀ i, 1000000 * C * N * d * rate K q (N + 2) + ≤ 2 ^ (M.width i) * r) (i : Fin n) (g : Fin r) : + 2 * S.layout.bill i g K q D ≤ 2 ^ (M.width i) := by + let t := C * N * d + have hp : Fintype.card (Position n r S.layout.d h) ≤ 13 * t := by simpa [t, mul_assoc] using hc.1 + have hv : ∀ z, multiplicity S.layout.color z * r ^ n ≤ 16 * t + := by simpa [t, mul_assoc] using hc.2 + have hT := S.layout.tape_bound hv hp hm i g + have hG : S.layout.instructions i g * r ≤ 100 * t := S.layout.gate_bound hv hp i g + have hD : D ≤ N := (Nat.le_pow (by decide : 0 < 2)).trans hd + let R := rate K q (N + 2) + have hr' : 2 ≤ R := Nat.le_add_right _ _ + have hh : rate K q (D + 2) ≤ R := by unfold R rate; gcongr + apply (Nat.mul_le_mul_right_iff hr).1 + refine le_trans ?_ (hw i) + calc + _ = 2 * (Fintype.card (S.layout.LocalTape i g) * r + + (S.layout.instructions i g * r) * (1002 + 1000 * rate K q (D + 2))) + := by unfold Layout.bill; ring + _ ≤ 2 * (100 * t + 100 * t * (1002 + 1000 * R)) := by gcongr + _ = t * (200 + 200 * (1002 + 1000 * R)) := by ring + _ ≤ t * (1000000 * R) := by gcongr; omega + _ = _ := by unfold t R; ring + +open Classical in +theorem controller_exists (hf : S.fits) (hl : 1 + 3 * r + Fintype.card (M.Bits F) ≤ l) + (hw : ∀ i g, 2 * S.layout.bill i g K q D ≤ 2 ^ M.width i) : + Nonempty (Controller (Format.ofScheme S) A hn M B) := by + have h (i : Fin n) (g : Fin r) : + Nonempty (S.layout.LocalTape i g ↪ Fin (2 ^ M.width i)) := by + apply Function.Embedding.nonempty_of_card_le + rw [Fintype.card_fin] + have := hw i g + unfold Layout.bill at this + omega + exact ⟨⟨fun i g => (h i g).some, fun _ _ _ => (Fintype.equivFin _).symm, + S.links, S.packets, S.pins, hf, hl⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/DispatchSize.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/DispatchSize.lean new file mode 100644 index 0000000000..b473851485 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/DispatchSize.lean @@ -0,0 +1,963 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Physical +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Capacity +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.ControlWeight + +/-! +# Reading encoded symbols at a worker + +Nonloop bits have no private assignments. For each such bit invert +the numbering of its unordered endpoint pair. Read the leg starting +at the worker, unless the worker is the relay, in which case the +other endpoint supplies the unique leg. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +variable {R n : ℕ} {M : Type} [Fintype M] (src dst : M → Fin R) + (serial : Numbering src dst) + +/-- The token of type `Virtual (count src dst)` for the given inputs. -/ +def token (e : M) (he : src e ≠ dst e) : Virtual (count src dst) := + if h : src e < dst e then + ⟨⟨(src e, dst e), h⟩, (serial _ _).symm ⟨e, .inl ⟨rfl, rfl⟩⟩⟩ + else + ⟨⟨(dst e, src e), lt_of_le_of_ne (le_of_not_gt h) he.symm⟩, + (serial _ _).symm ⟨e, .inr ⟨rfl, rfl⟩⟩⟩ + +private theorem port_token (e : M) (he : src e ≠ dst e) : + ports src dst serial (.inl (token src dst serial e he)) = e := by + change edge src dst serial (.inl (token src dst serial e he)) = _ + unfold token + split <;> simp [edge] + +theorem sees_token (e : M) (he : src e ≠ dst e) (u : Fin R) (hu : src e = u ∨ dst e = u) : + sees u (token src dst serial e he).1 := by + unfold token + split <;> simp only [sees] <;> grind + +variable {q : Fin R → Fin R → ℕ} + +/-- The endpoint leg of type `Leg q` for the given inputs. -/ +def endpointLeg (b : Virtual q) (u : Fin R) (h : sees u b.1) : Leg q := + if hv : u ≠ via b then ⟨b, u, h, hv⟩ + else if hu : u = b.1.val.1 then ⟨b, b.1.val.2, .inr rfl, by grind [sees]⟩ + else ⟨b, b.1.val.1, .inl rfl, by grind⟩ + +private theorem at_endpoint_eq (b : Virtual q) (u : Fin R) (h : sees u b.1) : + (at_endpoint b u h).choose = endpointLeg b u h := by + have aux (l : Leg q) (hl : l.1 = b) (hi : sees u (link l)) : + l = endpointLeg b u h := by + have hi' := (incident l u).mp hi + rcases l with ⟨c, v, hv, hne⟩ + change c = b at hl + subst c + change u = v ∨ u = via b at hi' + unfold endpointLeg + split_ifs <;> congr 2 <;> grind [sees] + exact aux _ (at_endpoint b u h).choose_spec.1 (at_endpoint b u h).choose_spec.2 + +variable (hq : ∀ u, ∑ v, count src dst u v ≤ n / 64) (hn : 64 * R ^ 2 ≤ n) + +/-- Computes the location by the application `address (slot (count_symm src dst) hq hn +(endpointLeg (token src dst serial e he) u (sees_token src dst serial e he u hu)))`. -/ +def location (u : Fin R) (e : M) (he : src e ≠ dst e) (hu : src e = u ∨ dst e = u) : Fin (n / 4) := + address (slot (count_symm src dst) hq hn + (endpointLeg (token src dst serial e he) u (sees_token src dst serial e he u hu))) + +theorem read_location (u : Fin R) (t : Fin (n / 4) → Bool) (x : ∀ v, Private src dst v → Bool) + (e : M) (he : src e ≠ dst e) (hu : src e = u ∨ dst e = u) : + assignments src dst serial (receive (count_symm src dst) hq hn u t, x) e = + t (location src dst serial hq hn u e he hu) := by + have hp := (ports src dst serial).symm_apply_eq.mpr (port_token src dst serial e he).symm + unfold assignments + simp only [Equiv.trans_apply, Equiv.arrowCongr_apply, Function.comp_apply, Equiv.refl_apply, hp] + change receive (count_symm src dst) hq hn u t (token src dst serial e he) = _ + rw [receive, dite_eq_left (sees_token src dst serial e he u hu), at_endpoint_eq] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Encoded +variable {R n : ℕ} {M : Type} [Fintype M] (src dst : M → Fin R) + (alph : M → Type) (w : M → ℕ) (code : ∀ e, alph e ↪ (Fin (w e) → Bool)) + +local notation "S" => left src dst w +local notation "D" => right src dst w + +open Classical in +theorem private_empty (u : Fin R) : IsEmpty (Links.Private S D u) := by + have : IsEmpty (Links.Between S D u u) := by + refine ⟨fun ⟨b, h⟩ => b.1.2 ?_⟩ + rcases h with h | h <;> exact h.1.trans h.2.symm + rw [Links.Private, Links.count, Fintype.card_eq_zero] + infer_instance + +variable (hd : ∀ u, ∑ e ∈ Finset.univ.filter + (fun e => src e ≠ dst e ∧ (src e = u ∨ dst e = u)), w e ≤ n / 64) (hn : 64 * R ^ 2 ≤ n) + (serial : Links.Numbering (left src dst w) (right src dst w)) + +include hd in +open Classical in +theorem count_bound (u : Fin R) : ∑ v, Links.count S D u v ≤ n / 64 := + (Links.count_le S D u).trans ((load src dst w u).le.trans (hd u)) + +open Classical in +/-- The location of type `Fin (n / 4)` for the given inputs. -/ +def location (u : Fin R) (b : Bits src dst w) (hu : S b = u ∨ D b = u) : Fin (n / 4) := by + have he : S b ≠ D b := b.1.property + exact Links.location S D serial (count_bound src dst w hd) hn u b he hu + +open Classical in +/-- Compare every bit of a shared symbol with its physical input address. -/ +def receives (u : Fin R) (t : Fin (n / 4) → Bool) (z : Local src dst alph u) : Prop := + ∀ (e : Shared src dst) (he : src e.val = u ∨ dst e.val = u) (j : Fin (w e.val)), + code e.val (z ⟨e.val, he⟩) j = + t (location src dst w hd hn serial u ⟨e, j⟩ he) + +variable [DecidableEq M] [∀ e, Fintype (alph e)] {F : Type} [Field F] + +open Classical in +/-- Once relay equality and unused-wire pins have been checked, +only the local symbols remain to be summed. -/ +theorem worker_eq (g : Fin R → (∀ e, alph e) → F) (u : Fin R) (t : Fin (n / 4) → Bool) : + worker src dst alph w code hd hn g serial u t = + if Links.valid (Links.count_symm S D) (count_bound src dst w hd) hn u t then + ∑ z : Local src dst alph u, + if receives src dst alph w code hd hn serial u t z then localize src dst alph g u z else 0 + else 0 := by + have := private_empty src dst w u + have he (x : ∀ v, Links.Private S D v → Bool) (z : Local src dst alph u) : + agrees src dst alph w code u + (Links.assignments S D serial + (Links.receive (Links.count_symm S D) (count_bound src dst w hd) hn u t, x)) z ↔ + receives src dst alph w code hd hn serial u t z := by + unfold agrees receives location + apply forall_congr' + intro e + apply forall_congr' + intro h + apply forall_congr' + intro j + rw [Links.read_location S D serial _ hn u t x (⟨e, j⟩ : Bits src dst w) e.property h] + unfold worker Links.worker Links.site Links.tally + rw [Fintype.sum_unique] + simp only [bitSite, he] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Encoded +end + +/- +# Realizing the public report checks + +A class total needs two inequalities and comparing against each +candidate cut needs one. The offsets resolve ties by the first index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Processor Finset +variable {F : Type} [Field F] {n h r d v : ℕ} (A : Expansion F n h) (hn : 2 ≤ n) + +open Classical in +private theorem first_iff (s : Fin n → ℕ) (i : Fin n) : + i = first hn s ↔ ∀ j, s i < s j + if i ≤ j then 1 else 0 := by + constructor + · rintro rfl j + have := first_spec hn s j + split_ifs <;> omega + · intro h + have h₁ := h (first hn s) + have h₂ := first_spec hn s i + split_ifs at h₁ <;> omega + +open Classical in +/-- Indexes the tests by the coordinates of `Fin n ⊕ Class r × Bool`. -/ +abbrev Tests (n r : ℕ) := Fin n ⊕ Class r × Bool + +open Classical in +private def limit (d : ℕ) (i : Fin n) (c : Class r) := + Fintype.card {p : Packet n r d // packetClass hn i p = c} + +open Classical in +private def sides (d : ℕ) (i : Fin n) (side : Bool) : + Tests n r → Form (Class r × A.I) + | .inl j => + if side then ⟨fun z => A.cross z.2 j, if i ≤ j then 1 else 0⟩ + else ⟨fun z => A.cross z.2 i, 0⟩ + | .inr (c, t) => + if t = side then ⟨fun z => if z.1 = c then 1 else 0, side.toNat⟩ + else ⟨fun _ => 0, limit hn d i c + side.toNat⟩ + +open Classical in +private theorem class_total (x : A.CountBit r d → Bool) (c : Class r) : + linear (fun z => if z.1 = c then 1 else 0) x = ∑ j, A.cnt x (c, j) := by + unfold linear + rw [Fintype.sum_prod_type, sum_comm] + simp only [mul_ite, mul_one, mul_zero, sum_ite_eq', mem_univ, ite_true, cnt] + +open Classical in +private theorem guard_tests (i : Fin n) (x : A.CountBit r d → Bool) : + A.guard hn i x ↔ ∀ u : Tests n r, + (A.sides hn d i false u).value x < (A.sides hn d i true u).value x := by + let s (i : Fin n) := ∑ z, A.cnt x z * A.cross z.2 i + let t (c : Class r) := ∑ z, A.cnt x (c, z) + let test (u : Tests n r) := (A.sides hn d i false u).value x < (A.sides hn d i true u).value x + have h₀ : linear (fun _ => 0) x = 0 := by simp [linear] + have h₁ (j : Fin n) : test (.inl j) ↔ s i < s j + if i ≤ j then 1 else 0 := Iff.rfl + have h₂ (c : Class r) : test (.inr (c, false)) ↔ t c ≤ limit hn d i c := by + simp [test, sides, Form.value, class_total, h₀, t] + have h₃ (c : Class r) : test (.inr (c, true)) ↔ limit hn d i c ≤ t c := by + simp [test, sides, Form.value, class_total, h₀, t] + change (∀ c, t c = limit hn d i c) ∧ i = first hn s ↔ ∀ u, test u + rw [first_iff] + constructor + · rintro ⟨ht, hs⟩ (j|⟨c, _|_⟩) + · exact (h₁ j).2 (hs j) + · exact (h₂ c).2 (ht c).le + · exact (h₃ c).2 (ht c).ge + · intro h + exact ⟨fun c => le_antisymm ((h₂ c).mp (h _)) ((h₃ c).mp (h _)), fun j => (h₁ j).mp (h _)⟩ + +open Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev registerWidth (n r d : ℕ) := Nat.clog 2 (Fintype.card (Packet n r d) + 1) + +open Classical in +private theorem sides_lt {M : ℕ} (hM : 1 ≤ M) (hc : ∀ s j, A.cross s j ≤ M) + (hv : Fintype.card (Class r × A.I) * (2 ^ registerWidth n r d * M) + + Fintype.card (Packet n r d) + 1 < 2 ^ v) + (i : Fin n) (b : Bool) (u : Tests n r) (x : A.CountBit r d → Bool) : + (A.sides hn d i b u).value x < 2 ^ v := by + have hh : ∀ j, (A.sides hn d i b u).factors j ≤ M := by + intro j + rcases u with k|⟨t, y⟩ + · cases b <;> exact hc _ _ + · by_cases hy : y = b <;> by_cases ht : j.1 = t <;> simp [sides, hy, ht, hM] + have ho : (A.sides hn d i b u).offset ≤ Fintype.card (Packet n r d) + 1 := by + rcases u with k|⟨t, y⟩ + · cases b <;> by_cases hi : i ≤ k <;> simp [sides, hi] + · have : limit hn d i t ≤ Fintype.card (Packet n r d) := Fintype.card_subtype_le _ + have : b.toNat ≤ 1 := by cases b <;> decide + by_cases hy : y = b <;> simp only [sides, hy, ite_true, ite_false] <;> omega + exact lt_of_le_of_lt (Nat.add_le_add (linear_le hh x) ho) (by rw [add_assoc] at hv; exact hv) + +open Classical in +/-- Indexes the guard cost by the coordinates of `100000 * (1 + Fintype.card (Tests n r)) * (1 + +Fintype.card (Class r × A.I) * registerWidth n r d) * (1 + v)`. -/ +def guardCost (r d v : ℕ) := + 100000 * (1 + Fintype.card (Tests n r)) * + (1 + Fintype.card (Class r × A.I) * registerWidth n r d) * (1 + v) + +open Classical in +theorem guard_net {M : ℕ} (hM : 1 ≤ M) (hc : ∀ s j, A.cross s j ≤ M) + (hv : Fintype.card (Class r × A.I) * (2 ^ registerWidth n r d * M) + + Fintype.card (Packet n r d) + 1 < 2 ^ v) (i : Fin n) : + Install.Weight F (fun x : A.CountBit r d → Bool => if A.guard hn i x then 1 else 0) + (A.guardCost r d v) := by + simp only [guard_tests] + exact checks_net F (A.sides hn d i false) (A.sides hn d i true) v _ + (A.sides_lt hn hM hc hv i false) (A.sides_lt hn hM hc hv i true) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +section +/- # Register and circuit size bounds for the report checks -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +variable {F : Type} [Field F] {n r d h : ℕ} (A : Expansion F n h) + +open Classical in +private theorem class_card (r : ℕ) : Fintype.card (Class r) = r ^ 3 := by simp [Class]; ring + +open Classical in +theorem guard_size (hn : 2 ≤ n) (w : ℕ) + (hw : 100000000 ≤ w) (hnw : n ≤ w) (hI : Fintype.card A.I ≤ w) + (hc : ∀ s i, A.cross s i ≤ w) (hr : 0 < r) (hrw : r ^ 6 ≤ 2 ^ w) + (hpc : Fintype.card (Packet n r d) < (2 ^ w) ^ 8) (i : Fin n) : + Install.Weight F (fun x : A.CountBit r d → Bool => if A.guard hn i x then 1 else 0) + (2 ^ w * w ^ 5) := by + let N := 2 ^ w + have hwN : w < N := Nat.lt_two_pow_self + have hN : 2 ≤ N := by omega + have hw' : 1 ≤ w := by omega + have hword : registerWidth n r d ≤ w * 8 := by + apply Nat.clog_le_of_le_pow + rwa [pow_mul] + have hr' : 1 ≤ r ^ 3 := Nat.one_le_pow _ _ hr + have hrN : r ^ 3 ≤ N := (Nat.pow_le_pow_right hr (by decide : 3 ≤ 6)).trans hrw + have hrows : Fintype.card (Class r × A.I) ≤ r ^ 3 * w := by + rw [Fintype.card_prod, class_card] + gcongr + have htests : Fintype.card (Tests n r) ≤ n + 2 * r ^ 3 := by + simp only [Tests, Fintype.card_sum, Fintype.card_fin, Fintype.card_prod, Fintype.card_bool] + exact le_of_eq (by ring) + have hupper : Fintype.card (Class r × A.I) * (2 ^ registerWidth n r d * w) + + Fintype.card (Packet n r d) + 1 < 2 ^ (w * 13) := by + calc + _ ≤ (r ^ 3 * w) * (2 ^ (w * 8) * w) + N ^ 8 := by + rw [add_assoc] + exact Nat.add_le_add (Nat.mul_le_mul hrows (by gcongr)) hpc + _ ≤ (N * N) * (N ^ 8 * N) + N ^ 8 := by rw [pow_mul]; gcongr + _ = N ^ 11 + N ^ 8 := by ring + _ ≤ 2 * N ^ 11 := by rw [two_mul]; gcongr; omega + _ < N ^ 2 * N ^ 11 := by gcongr; nlinarith + _ = 2 ^ (w * 13) := by unfold N; rw [← pow_add, pow_mul] + apply (A.guard_net hn hw' hc hupper i).mono + unfold guardCost + have h₁ : 1 + Fintype.card (Tests n r) ≤ 4 * r ^ 3 * w := by + nlinarith only [htests, hnw, hr', hw', Nat.le_mul_of_pos_left w hr', + Nat.le_mul_of_pos_right (r ^ 3) hw'] + have h₂ : 1 + Fintype.card (Class r × A.I) * registerWidth n r d ≤ 9 * r ^ 3 * w ^ 2 := by + have ht := Nat.mul_le_mul hrows hword + have : 0 < r ^ 3 * w ^ 2 := by positivity + nlinarith only [ht, this] + calc + _ ≤ 100000 * (4 * r ^ 3 * w) * (9 * r ^ 3 * w ^ 2) * (14 * w) := by gcongr; omega + _ = r ^ 6 * 50400000 * w ^ 4 := by ring + _ ≤ 2 ^ w * w * w ^ 4 := by gcongr; omega + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +section +/- +# A bank fixed before the diagram is known + +Use one template per cube coordinate. A small power of the processor +length covers every polylogarithmic factor in the individual scripts. +The same scripts can be reused in many copies. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Filter + +theorem poly_bound (q k : ℕ) (hk : 0 < k) : + ∀ᶠ w : ℕ in atTop, w ^ q ≤ 2 ^ (w / k) := by + have ht : Tendsto (fun w : ℕ => (w : ℝ)) atTop atTop := tendsto_natCast_atTop_atTop + have hp := isLittleO_pow_exp_pos_mul_atTop q (by positivity : 0 < Real.log 2 / (2 * k)) + filter_upwards [eventually_ge_atTop k, ht.eventually hp.eventuallyLE] with w hw he + have hw' : w ≤ (2 * k) * (w / k) := by + have := Nat.mod_add_div w k + have := Nat.mod_lt w hk + have := Nat.le_mul_of_pos_right k (Nat.div_pos hw hk) + rw [mul_assoc] + omega + have hj : (w : ℝ) / (2 * k) ≤ (w / k : ℕ) := by + rw [div_le_iff₀ (by positivity), mul_comm] + exact_mod_cast hw' + have h : (w : ℝ) ^ q ≤ (2 : ℝ) ^ (w / k) := by + calc + _ ≤ Real.exp (Real.log 2 / (2 * k) * w) := by + simpa only [Real.norm_of_nonneg (by positivity : 0 ≤ (w : ℝ) ^ q), + Real.norm_of_nonneg (Real.exp_nonneg _)] using he + _ = (2 : ℝ) ^ ((w : ℝ) / (2 * k)) := by + rw [Real.rpow_def_of_pos (by positivity)] + congr 1 + ring + _ ≤ _ := by rw [← Real.rpow_natCast]; exact Real.rpow_le_rpow_of_exponent_le (by norm_num) hj + exact_mod_cast h + +private theorem log_rate (C K q w : ℕ) (hw : 2 ≤ w) (hc : C * (2 + K * 2 ^ q) ≤ w) : + C * (2 + K * (1 + Nat.clog 2 (2 ^ w + 3)) ^ q) ≤ w ^ (q + 1) := by + have hg : Nat.clog 2 (2 ^ w + 3) ≤ w + 1 := by + apply Nat.clog_le_of_le_pow + have h : 2 ^ 2 ≤ 2 ^ w := Nat.pow_le_pow_right (by decide : 0 < 2) hw + rw [pow_succ] + omega + calc + _ ≤ C * (2 * w ^ q + K * (2 * w) ^ q) := by + gcongr + · exact Nat.le_mul_of_pos_right _ (by positivity) + · omega + _ = C * (2 + K * 2 ^ q) * w ^ q := by rw [mul_pow]; ring + _ ≤ w * w ^ q := Nat.mul_le_mul_right _ hc + _ = _ := (pow_succ' _ _).symm + +private theorem card_bits (F : Type) [Fintype F] {n : ℕ} (b : Bank (Fin n)) : + Fintype.card (b.Bits F) = + ∑ i, 2 ^ (b.width i + 1) * (4 * (b.width i + 1) + 16 * Fintype.card F) := by + simp only [Bank.Bits, Fintype.card_sigma] + exact Finset.sum_congr rfl (fun i _ => card_script F (b.width i + 1)) + +theorem scales (F : Type) [Fintype F] (n C K q : ℕ) (hn : 2 ≤ n) : + ∀ᶠ w : ℕ in atTop, + let N := 2 ^ w + let r := 2 ^ (w / (16 * n)) + let d := 2 ^ (w / (32 * n)) + ∃ b : Bank (Fin n), b.budget F ≤ N * w ^ (q + 8) ∧ + Fintype.card (b.Bits F) ≤ N / 2048 / 2 ∧ + ∀ i : Fin n, C * N * d * (2 + K * (1 + Nat.clog 2 (N + 3)) ^ q) ≤ 2 ^ (b.width i) * r ∧ + 4 * r ≤ d * 2 ^ (b.repetitions i) := by + let T := 2 + C * (2 + K * 2 ^ q) + 64 * n * templateCost F + 8192 * n * (8 + 16 * Fintype.card F) + filter_upwards [eventually_ge_atTop T, poly_bound (q + 4) (32 * n) (by omega)] with w hT he + intro N r d + have hw : 2 ≤ w := by omega + let j := w / (32 * n) + have hj : j ≤ w := Nat.div_le_self _ _ + have hr : w / (16 * n) / 2 = j := by + rw [Nat.div_div_eq_div_mul, show 16 * n * 2 = 32 * n by ring] + have hr₀ : d * d ≤ r := by + change 2 ^ j * 2 ^ j ≤ 2 ^ (w / (16 * n)) + rw [← pow_add] + exact Nat.pow_le_pow_right (by decide) (by omega) + have hr₁ : r ≤ d * d * 2 := by + change 2 ^ (w / (16 * n)) ≤ 2 ^ j * 2 ^ j * 2 + rw [← pow_add, ← pow_succ] + exact Nat.pow_le_pow_right (by decide) (by omega) + let L := Nat.log 2 (w ^ (q + 1)) + 1 + have hlo : w ^ (q + 1) ≤ 2 ^ L := (Nat.lt_pow_succ_log_self (by decide) _).le + have hhi : 2 ^ L ≤ w ^ (q + 2) := by + dsimp only [L] + rw [pow_succ, show q + 2 = (q + 1) + 1 by omega, pow_succ w (q + 1)] + exact Nat.mul_le_mul (Nat.pow_log_le_self 2 (by positivity)) hw + have hL : L ≤ j := by + have h := hhi.trans ((Nat.pow_le_pow_right (by omega : 0 < w) (by omega : q + 2 ≤ q + + 4)).trans he) + exact (pow_le_pow_iff_right₀ (by decide : 1 < (2 : ℕ))).mp h + let u := w - j + L + have hu : u ≤ w := by omega + have hd : 2 ^ (w - j) * d = N := by + change 2 ^ (w - j) * 2 ^ j = 2 ^ w + rw [← pow_add, Nat.sub_add_cancel hj] + have hu' : 2 ^ u = 2 ^ (w - j) * 2 ^ L := pow_add _ _ _ + have hd' : 2 ^ (j + 3) = 8 * d := by rw [pow_add, mul_comm]; rfl + let b : Bank (Fin n) := ⟨fun _ => u, fun _ => j + 3⟩ + refine ⟨b, ?_, ?_, fun i => ⟨?_, ?_⟩⟩ + · simp only [Bank.budget, b, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + nsmul_eq_mul, Nat.cast_id, hd', hu'] + calc + _ = n * templateCost F * 8 * N * 2 ^ L * (u + 2) ^ 3 := by rw [← hd]; ring + _ ≤ n * templateCost F * 8 * N * w ^ (q + 2) * (2 * w) ^ 3 := by gcongr; omega + _ = N * (64 * n * templateCost F) * w ^ (q + 5) + := by rw [show q + 5 = (q + 2) + 3 by omega, pow_add w (q + 2)]; ring + _ ≤ N * w * w ^ (q + 5) := by gcongr; omega + _ ≤ _ := by + rw [mul_assoc, ← pow_succ'] + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) (by omega)) + · apply (Nat.le_div_iff_mul_le (by decide)).mpr + apply (Nat.le_div_iff_mul_le (by decide)).mpr + rw [card_bits] + simp only [b, Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul, Nat.cast_id] + have ht : 4 * (u + 1) + 16 * Fintype.card F ≤ (8 + 16 * Fintype.card F) * w := by + have := Nat.le_mul_of_pos_right (Fintype.card F) (by omega : 0 < w) + nlinarith + calc + _ ≤ n * (2 ^ (u + 1) * ((8 + 16 * Fintype.card F) * w)) * 2 * 2048 := by gcongr + _ = 2 ^ (w - j) * (8192 * n * (8 + 16 * Fintype.card F) * 2 ^ L * w) + := by rw [pow_succ, hu']; ring + _ ≤ 2 ^ (w - j) * (w * w ^ (q + 2) * w) := by gcongr; omega + _ = 2 ^ (w - j) * w ^ (q + 4) := by rw [← pow_succ', ← pow_succ] + _ ≤ N := by rw [← hd]; exact Nat.mul_le_mul_left _ he + · have h := (log_rate C K q w hw (by omega)).trans hlo + calc + _ = N * d * (C * (2 + K * (1 + Nat.clog 2 (N + 3)) ^ q)) := by ring + _ ≤ N * d * 2 ^ L := Nat.mul_le_mul_left _ h + _ = 2 ^ u * (d * d) := by rw [hu', ← hd]; ring + _ ≤ _ := Nat.mul_le_mul_left _ hr₀ + · change 4 * r ≤ d * 2 ^ (j + 3) + rw [hd'] + nlinarith only [hr₁] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- +# Which broadcast strings can contribute + +An ordinary branch requires a feasible report. An infeasible count +table has an empty symbol space, hence zero weight at every site. +The extra branch uses the all-zero broadcast. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +variable {F : Type} [Field F] {n h : ℕ} (A : Expansion F n h) (hn : 2 ≤ n) + (N r d b : ℕ) (hb : Nat.clog 2 n + r ^ 3 * Fintype.card A.I * + Nat.clog 2 (Fintype.card (Packet n r d) + 1) + 1 ≤ b) + +/-- The stamp of type `Prop` for the given inputs. -/ +def stamp (i : Fin n) (z : Fin b → Bool) : Prop := + z (A.reportPort r d b hb (.inl ())) = true ∧ + (∀ j, z (A.reportPort r d b hb (.inr (.inl j))) = i.val.testBit j.val) ∧ + ∀ k ∉ Set.range (A.reportPort r d b hb), z k = false + +/-- Computes the read counts by the application `z (A.reportPort r d b hb (.inr (.inr p)))`. -/ +def readCounts (z : Fin b → Bool) (p : A.CountBit r d) : Bool := + z (A.reportPort r d b hb (.inr (.inr p))) + +@[simp] theorem readCounts_encodeReport (R : A.Accepted (r := r) (d := d) hn (A.budget hn N)) : + A.readCounts r d b hb (A.encodeReport hn N r d b hb (some R)) = A.countBits R.val := + funext (A.encodeReport_count hn N r d b hb R) + +theorem guard_broadcast (hbudget : ∀ s : Packet n r d → A.I, A.budget hn N (A.report hn s)) + (i : Fin n) (z : Fin b → Bool) : + A.stamp r d b hb i z ∧ A.guard hn i (A.readCounts r d b hb z) ↔ + ∃ R : A.Accepted (r := r) (d := d) hn (A.budget hn N), + A.feasible hn R.val ∧ R.val.1 = i ∧ A.encodeReport hn N r d b hb (some R) = z := by + rw [A.guard_iff hn N hbudget] + constructor + · rintro ⟨⟨hflag, hcut, hpad⟩, R, hf, hi, hcount⟩ + refine ⟨R, hf, hi, funext fun j => ?_⟩ + by_cases hj : j ∈ Set.range (A.reportPort r d b hb) + · obtain ⟨_|k|p, rfl⟩ := hj + · exact (A.encodeReport_flag hn N r d b hb R).trans hflag.symm + · rw [encodeReport_cut, hi, hcut] + · rw [encodeReport_count, hcount] + rfl + · exact (A.encodeReport_pad hn N r d b hb (some R) j hj).trans (hpad j hj).symm + · rintro ⟨R, hf, rfl, rfl⟩ + exact ⟨⟨A.encodeReport_flag hn N r d b hb R, A.encodeReport_cut hn N r d b hb R, + A.encodeReport_pad hn N r d b hb (some R)⟩, R, hf, rfl, + (A.readCounts_encodeReport hn N r d b hb R).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal +variable {F : Type} [Field F] [Fintype F] {N l d B n r h : ℕ} + {P : Format N l d n r h} {A : Expansion F n h} {hn : 2 ≤ n} {M : Bank (Fin n)} + (C : Controller P A hn M B) (i : Fin (3 * r)) (c : M.Bits F → Bool) + +theorem site_infeasible (R : P.Reports A hn B) (y : Fin (N / 4) → Bool) + (hf : ¬ A.feasible hn R.val) : C.site i c R y = 0 := by + classical + have he := mt (A.feasible_symbols hn R.val N (T := Pin N l l r)).mpr hf + unfold site Expansion.extraProcessor + rw [Encoded.worker_eq] + simp only [Encoded.localize, he, dite_false, ite_self, Finset.sum_const_zero] + +theorem run_invalid (z : Fin l → Bool) (y : Fin (N / 4) → Bool) (hz : z ≠ fun _ => false) + (hr : ∀ R : P.Reports A hn B, A.feasible hn R.val → + A.encodeReport hn N r (B * P.count) l C.fits (some R) ≠ z) : + C.run i c z y = 0 := by + classical + let e := A.encodeReport hn N r (B * P.count) l C.fits + by_cases h : z ∈ Set.range e + · obtain ⟨_|R, rfl⟩ := h + · exact (hz (funext (A.encodeReport_none hn N r (B * P.count) l C.fits))).elim + · unfold run Machine.branch + rw [e.injective.extend_apply] + exact C.site_infeasible i c R y (fun hf => hr R hf rfl) + · unfold run Machine.branch + exact Function.extend_apply' _ _ _ h + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- +# Dispatching the processor by its broadcast header + +One control bit and the cut select a fixed-cut implementation. The +remaining checks impose the class counts and pin the unused bits. +A separate all-zero case realizes the unit branch. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal Install +variable {F : Type} [Field F] + +open Classical in +private theorem pin_net {I J : Type} [Fintype I] [Fintype J] (a : J → I) : + Weight F (fun x => if ∀ j, x (a j) = false then 1 else 0) + (Fintype.card I + 4 * Fintype.card J + 17) := by + have h := ((BNet.any F J).pull a).weight + (Weight.dense F Unit (fun x => if x () then 0 else 1)) + convert h using 1 + · funext x + simp only [Function.comp_apply, decide_eq_true_eq, ← Bool.not_eq_true, ← not_exists, ite_not] + · simp; omega + +variable [Fintype F] {N l d B n r h g m : ℕ} + {P : Format N l d n r h} {A : Expansion F n h} {hn : 2 ≤ n} {M : Bank (Fin n)} + (C : Controller P A hn M B) + +open Classical in +private abbrev Input (N l : ℕ) := Machine.Ports N l l → Bool +open Classical in +private abbrev Header (n : ℕ) := Unit ⊕ Fin (Nat.clog 2 n) +open Classical in +private abbrev port := A.reportPort r (B * P.count) l C.fits +open Classical in +/-- The quantity computed by `A.encodeReport hn N r (B * P.count) l C.fits`. -/ +abbrev reportCode := A.encodeReport hn N r (B * P.count) l C.fits + +open Classical in +/-- Correctness on the literals and reports used by the diagonal contraction. -/ +def Handles (k : Fin n) (f : (Machine.Ports N l l → Bool) → F) : Prop := + ∀ i c (R : P.Reports A hn B) y, R.val.1 = k → A.feasible hn R.val → + f (Sum.elim (C.code (some (i, c))) (Sum.elim (C.reportCode (some R)) y)) = C.site i c R y + +open Classical in +private def head : Header n → Fin l + | .inl _ => C.port (.inl ()) + | .inr j => C.port (.inr (.inl j)) + +open Classical in +private def parse (x : Header n → Bool) : Option (Fin n) := + if h : x (.inl ()) = true ∧ Processor.number (x ∘ Sum.inr) < n then + some ⟨Processor.number (x ∘ Sum.inr), h.2⟩ else none + +open Classical in +private theorem parse_report (R : P.Reports A hn B) : + parse (C.reportCode (some R) ∘ C.head) = some R.val.1 := by + have ht : Processor.number ((C.reportCode (some R) ∘ C.head) ∘ Sum.inr) = R.val.1.val := by + simp only [Function.comp_def, head, reportCode, port, Expansion.encodeReport_cut] + exact number_test _ (R.val.1.isLt.trans_le (Nat.le_pow_clog (by decide) _)) + unfold parse + simp only [ht, Function.comp_apply, head, port, reportCode, Expansion.encodeReport_flag, + R.val.1.isLt, and_self, dite_eq_left] + +open Classical in +private abbrev Pad := {i : Fin l // i ∉ Set.range C.port} + +open Classical in +private def good (k : Fin n) (z : Fin l → Bool) : Prop := + (∀ j : C.Pad, z j.val = false) ∧ A.guard hn k (A.readCounts r (B * P.count) l C.fits z) + +open Classical in +private theorem good_iff (z : Fin l → Bool) (k : Fin n) (hk : parse (z ∘ C.head) = some k) : + C.good k z ↔ ∃ R : P.Reports A hn B, + A.feasible hn R.val ∧ R.val.1 = k ∧ C.reportCode (some R) = z := by + rw [← A.guard_broadcast hn N r (B * P.count) l C.fits C.packets k z] + unfold good + apply and_congr_left' + unfold parse at hk + split at hk + · rename_i h + have he : Processor.number ((z ∘ C.head) ∘ Sum.inr) = k.val + := congrArg Fin.val (Option.some.inj hk) + have ht (j : Fin (Nat.clog 2 n)) : z (C.port (.inr (.inl j))) = k.val.testBit j.val := by + rw [← he, test_number] + rfl + exact ⟨fun hb => ⟨h.1, ht, fun j hj => hb ⟨j, hj⟩⟩, fun hb j => hb.2.2 j.val j.property⟩ + · contradiction + +open Classical in +private def broadcast (x : Input N l) : Fin l → Bool := fun j => x (.inr (.inl j)) + +open Classical in +private def step (f : Fin n → Input N l → F) : Option (Fin n) → Input N l → F + | none, x => if ∀ j, x (.inr j) = false then 1 else 0 + | some k, x => if C.good k (broadcast x) then f k x else 0 + +open Classical in +private def runAt (f : Fin n → Input N l → F) (x : Input N l) : F := + C.step f (parse (broadcast x ∘ C.head)) x + +open Classical in +private theorem runAt_zero (f : Fin n → Input N l → F) (ξ : Fin l → Bool) (y : Fin (N / 4) → Bool) : + C.runAt f (Sum.elim ξ (Sum.elim (fun _ => false) y)) = + if y = (fun _ => false) then 1 else 0 := by + simp [runAt, broadcast, parse, step, funext_iff] + +open Classical in +private theorem runAt_eq (f : Fin n → Input N l → F) (hf : ∀ k, C.Handles k (f k)) + (i : Fin (3 * r)) (c : M.Bits F → Bool) (z : Fin l → Bool) (y : Fin (N / 4) → Bool) : + C.runAt f (Sum.elim (C.code (some (i, c))) (Sum.elim z y)) = C.run i c z y := by + by_cases hz : z = fun _ => false + · have he : C.reportCode none = z := + (funext (A.encodeReport_none hn N r _ l C.fits)).trans hz.symm + rw [hz, runAt_zero, ← hz, ← he, run, Machine.branch, C.reportCode.injective.extend_apply] + rfl + change C.step f (parse (z ∘ C.head)) _ = _ + by_cases hvalid : ∃ R : P.Reports A hn B, A.feasible hn R.val ∧ C.reportCode (some R) = z + · obtain ⟨R, hR, rfl⟩ := hvalid + have hp := C.parse_report R + have hg := (C.good_iff _ _ hp).mpr ⟨R, hR, rfl, rfl⟩ + rw [hp, run, Machine.branch, C.reportCode.injective.extend_apply] + change (if C.good R.val.1 (C.reportCode (some R)) then _ else _) = C.site i c R y + rw [ite_eq_left hg] + exact hf _ i c R y rfl hR + · rw [C.run_invalid i c z y hz (fun R h he => hvalid ⟨R, h, he⟩)] + cases hp : parse (z ∘ C.head) with + | none => + unfold step + exact ite_eq_right (fun h => hz (funext (fun j => h (.inl j)))) + | some k => + have hh : ¬ C.good k z := by + rintro h + obtain ⟨R, hR, _, he⟩ := (C.good_iff z k hp).mp h + exact hvalid ⟨R, hR, he⟩ + exact ite_eq_right hh + +open Classical in +private theorem step_net (f : Fin n → Input N l → F) + (hg : ∀ k, Weight F (fun x : A.CountBit r (B * P.count) → Bool + => if A.guard hn k x then 1 else 0) g) + (hf : ∀ k, Weight F (f k) m) (s : Option (Fin n)) : + Weight F (C.step f s) (g + m + 50 * (l + l + N / 4 + 1)) := by + let I := Machine.Ports N l l + have hI : Fintype.card I = l + l + N / 4 := by simp [I, Machine.Ports, Nat.add_assoc] + cases s with + | none => + have h := pin_net (F := F) (Sum.inr : Fin l ⊕ Fin (N / 4) → I) + apply h.mono + rw [hI, Fintype.card_sum, Fintype.card_fin, Fintype.card_fin] + omega + | some k => + let pads : C.Pad → I := fun j => .inr (.inl j.val) + let counts : A.CountBit r (B * P.count) → I := fun j => .inr (.inl (C.port (.inr (.inr j)))) + have hp : Fintype.card C.Pad ≤ l := by + exact (Fintype.card_subtype_le _).trans_eq (Fintype.card_fin l) + have hc : Fintype.card (A.CountBit r (B * P.count)) ≤ Fintype.card I := by + apply Fintype.card_le_of_injective counts + intro i j he + exact Sum.inr.inj (Sum.inr.inj (C.port.injective (Sum.inl.inj (Sum.inr.inj he)))) + have hw := (pin_net (F := F) pads).mul (((hg k).pull counts).mul (hf k)) + convert hw.mono (n := g + m + 50 * (l + l + N / 4 + 1)) (by rw [hI] at hc ⊢; omega) using 1 + funext x + simp only [step, good, ite_mul, one_mul, zero_mul, broadcast, pads] + by_cases hpad : ∀ j : C.Pad, x (.inr (.inl j.val)) = false + · simp only [hpad, implies_true, true_and, ite_true]; rfl + · simp only [hpad, false_and, ite_false] + +open Classical in +/-- The quantity computed by `100 * (1 + Weight.switchCost (1 + Nat.clog 2 n))`. -/ +def dispatchCost (n : ℕ) := 100 * (1 + Weight.switchCost (1 + Nat.clog 2 n)) + +open Classical in +/-- Only the fixed-cut site computations and the count guard need their +own cost estimates. The other control and pin tests are linear. -/ +theorem dispatch + (hg : ∀ k, Weight F (fun x : A.CountBit r (B * P.count) → Bool + => if A.guard hn k x then 1 else 0) g) + (hf : ∀ k, ∃ f, Weight F f m ∧ C.Handles k f) : + ∃ U v, C.Agrees U ∧ Net F (Machine.tape N l l) .unit U v ∧ + v ≤ dispatchCost n * (g + m + (l + l + N / 4) + 1) := by + choose f hm hsite using hf + let I := Machine.Ports N l l + let addr : Header n ⊕ I → I := Sum.elim (fun i => .inr (.inl (C.head i))) id + have hs := Weight.switch (fun s => C.step f (parse s)) (fun s => C.step_net f hg hm (parse s)) + have hrun : Weight F (C.runAt f) (dispatchCost n * (g + m + (l + l + N / 4) + 1)) := by + apply (hs.pull addr).mono + have hi : Fintype.card I = l + l + N / 4 := by simp [I, Machine.Ports, Nat.add_assoc] + have hh : 1 + Nat.clog 2 n ≤ l := by have := C.fits; omega + simp only [Header, Fintype.card_sum, Fintype.card_unit, Fintype.card_fin] + unfold dispatchCost + ring_nf + omega + obtain ⟨v, hv, net⟩ := hrun (Machine.tape N l l) (Machine.address N l l).symm + refine ⟨_, v, ?_, net, hv⟩ + have he (ξ z : Fin l → Bool) (y : Fin (N / 4) → Bool) : + bits (Machine.tape N l l) (Machine.feed ξ z y) ∘ (Machine.address N l l).symm = + Sum.elim ξ (Sum.elim z y) := by + funext j + rw [Function.comp_apply, Machine.bits_feed, Equiv.apply_symm_apply] + constructor + · simp only [pad, he, runAt_zero, ite_true] + · intro i c z y + simpa only [he] using C.runAt_eq f hsite i c z y + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +section +/- +# Separating the controller estimate from the network being simulated + +After fixing the input length the controller has no diagram, network +or vertex tables as parameters. This file reduces implementation of +the diagonal processor to a size estimate for that controller. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal Machine Filter + +variable {F : Type} [Field F] [Fintype F] + +/-- The controller carries out the report and wiring operations around +a fixed-size bank of template interpreters. -/ +def ControlBound (F : Type) [Field F] [Fintype F] : Prop := + ∀ n h C Q : ℕ, ∀ hn : 2 ≤ n, 0 < h → 4 ≤ C → ∀ A : Expansion F n h, + ∃ k : ℕ, ∀ᶠ w : ℕ in atTop, + let N := 2 ^ w + let r := 2 ^ (w / (16 * n)) + let d := 2 ^ (w / (32 * n)) + let l := N / 2048 + let B := (3 * r + d - 1) / d + ∀ fa : Machine.Ports N l l → Label n r, + (∀ z, multiplicity fa z * r ^ n ≤ 4 * N) → + (∀ i g, multiplicity (fun t : Fin l => fa (.inl t) i) g * r ≤ 2 * l) → + let P := Format.prescribed d h (rounds n r h (12 * (C * N * d))) fa + ∀ M : Bank (Fin n), M.budget F ≤ N * w ^ Q → r ^ n ≤ C * N * d → + (∀ i, 100 * C * N * d ≤ 2 ^ M.width i * r) → + Nonempty (Controller P A hn M B) → + ∃ (S : Controller P A hn M B) (U : Val (tape N l l) → Val .unit → F) (v : ℕ), + S.Agrees U ∧ Net F (tape N l l) .unit U v ∧ v ≤ N * w ^ k + +theorem programmable_of_control (hctrl : ControlBound F) (K q : ℕ) : + Programmable F (Cheap F K q) := by + intro C hC n h hn hh A + obtain ⟨k, hk⟩ := hctrl n h C (q + 8) hn hh hC A + obtain ⟨δ, _, hs⟩ := Diagonal.scales C n h (Fintype.card A.I) hC hn + refine ⟨k, ?_⟩ + filter_upwards [hk, hs, scales F n (1000000 * C) K q hn, eventually_ge_atTop (64 * n)] + with w ctrl sc hb hw + let N := 2 ^ w + let r := 2 ^ (w / (16 * n)) + let d := 2 ^ (w / (32 * n)) + let l := N / 2048 + let B := (3 * r + d - 1) / d + have ⟨hd, hd', _⟩ := batch_floor w n + have s : Diagonal.Scales C n h (Fintype.card A.I) N r l l d 0 B := + sc.2 d 0 hd hd' (by simp) + have hr : 16 ≤ r := by + have ht : 4 ≤ w / (16 * n) := (Nat.le_div_iff_mul_le (by omega)).mpr (by omega) + exact Nat.pow_le_pow_right (n := 2) (by decide) ht + obtain ⟨M, hm, hbit, hspec⟩ := hb + have hl : 1 + 3 * r + Fintype.card (M.Bits F) ≤ l := by + have hsq : r ^ 2 ≤ l := (Nat.pow_le_pow_right (by omega) hn).trans s.labels + have hlin : 2 * (1 + 3 * r) ≤ l := by nlinarith + change Fintype.card (M.Bits F) ≤ l / 2 at hbit + omega + have hsize : r ^ n ≤ C * N * d := + s.labels.trans ((by omega : l ≤ N).trans + ((Nat.le_mul_of_pos_left N (by omega : 0 < C)).trans (Nat.le_mul_of_pos_right _ hd))) + have hwidth : ∀ i, 1000000 * C * N * d * rate K q (N + 2) ≤ 2 ^ M.width i * r := by + intro i + rw [rate, show 1 + (N + 2) = N + 3 by omega] + exact (hspec i).1 + have hrepeat (i : Fin n) : B ≤ 2 ^ M.repetitions i := + (Nat.mul_le_mul_right_iff hd).mp (s.copies.trans (by rw [mul_comm _ d]; exact (hspec i).2)) + intro fa hf hf' + let P := Format.prescribed d h (rounds n r h (12 * (C * N * d))) fa + by_cases hex : Nonempty (Controller P A hn M B) + · have hroom (i : Fin n) : 100 * C * N * d ≤ 2 ^ M.width i * r := by + calc + _ ≤ 1000000 * C * N * d := by gcongr; decide + _ ≤ 1000000 * C * N * d * rate K q (N + 2) := by + apply Nat.le_mul_of_pos_right + unfold rate + omega + _ ≤ _ := hwidth i + obtain ⟨S, U, v, hu, hnet, hv⟩ := ctrl fa hf hf' M hm hsize hroom hex + refine ⟨U, S.pad, v, hu.1, hnet, hv, ?_⟩ + intro _ D hD G _ had T hcol ht hc hcode + exact S.programs T (Format.ofScheme_eq T hcol ht) had + (bill_bound T M hc hD s.pos hsize hwidth) hrepeat hcode U hu + · obtain ⟨v, hv, hnet⟩ := DNet.discard F (tape N l l) + let pad := (bits (tape N l l)).symm (fun _ => false) + refine ⟨fun _ _ => 1, pad, v, rfl, hnet, ?_, ?_⟩ + · rw [wd_word] at hv + exact (hv.trans s.tape).trans (Nat.le_mul_of_pos_right _ (pow_pos (by omega : 0 < w) _)) + · intro _ D hD G _ _ T hcol ht hc hcode + have he := controller_exists T M hcode hl (bill_bound T M hc hD s.pos hsize hwidth) + rw [Format.ofScheme_eq T hcol ht] at he + exact (hex he).elim + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- +# Bounding the overhead of dispatch at the diagonal scale + +Only feasible broadcasts at one fixed cut have to be supplied by +the site implementation. The dispatcher checks all public conditions +and handles malformed broadcasts and the separate unit branch. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal Filter +variable {F : Type} [Field F] [Fintype F] {n h : ℕ} + +private theorem packet_count (w n C h : ℕ) (hn : 2 ≤ n) (hw : 12 * C + 8 ≤ w) : + let N := 2 ^ w + let r := 2 ^ (w / (16 * n)) + let d := 2 ^ (w / (32 * n)) + let B := (3 * r + d - 1) / d + r ^ 6 ≤ N ∧ Fintype.card (Packet n r (B * rounds n r h (12 * (C * N * d)))) < N ^ 8 := by + intro N r d B + have hw' : w < N := Nat.lt_two_pow_self + have ht (j : ℕ) (hj : j ≤ 16 * n) : r ^ j ≤ N := by + unfold r N + rw [← pow_mul] + exact Nat.pow_le_pow_right (by decide) + ((Nat.mul_le_mul_left _ hj).trans (Nat.div_mul_le_self w _)) + have hrN : r ≤ N := by simpa using ht 1 (by omega) + have hdN : d ≤ N := Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.div_le_self w _) + have hb : B ≤ N ^ 2 := by + have hb' : B ≤ 3 * r + d := (Nat.div_le_self _ _).trans (Nat.sub_le _ _) + nlinarith + have hg : rounds n r h (12 * (C * N * d)) ≤ N ^ 3 := by + unfold rounds + calc + _ ≤ (12 * C) * N * d + 1 := by + rw [← mul_assoc, ← mul_assoc] + exact Nat.add_le_add_right (Nat.div_le_self _ _) 1 + _ ≤ (12 * C) * N * N + N * N := by gcongr; nlinarith + _ = (12 * C + 1) * N * N := by ring + _ ≤ N ^ 3 := by rw [pow_succ, pow_two]; gcongr; omega + refine ⟨ht 6 (by omega), ?_⟩ + simp only [Packet, Template, Label, Fintype.card_prod, Fintype.card_fun, Fintype.card_fin] + calc + _ ≤ N * N * (N ^ 2 * N ^ 3) := by have := ht n (by omega); gcongr + _ = N ^ 7 := by ring + _ < N ^ 8 := Nat.pow_lt_pow_right (by omega) (by decide) + +theorem dispatch_scale (A : Expansion F n h) (hn : 2 ≤ n) (C k : ℕ) : + ∀ᶠ w : ℕ in atTop, + let N := 2 ^ w + let r := 2 ^ (w / (16 * n)) + let d := 2 ^ (w / (32 * n)) + let l := N / 2048 + let B := (3 * r + d - 1) / d + ∀ (fa : Machine.Ports N l l → Label n r) (M : Bank (Fin n)), + let P := Format.prescribed d h (rounds n r h (12 * (C * N * d))) fa + ∀ S : Controller P A hn M B, + (∀ i, ∃ f, Install.Weight F f (N * w ^ k) ∧ S.Handles i f) → + ∃ (U : Val (Machine.tape N l l) → Val .unit → F) (v : ℕ), + S.Agrees U ∧ Net F (Machine.tape N l l) .unit U v ∧ v ≤ N * w ^ (max k 5 + 1) := by + classical + let c := Controller.dispatchCost n + let t := ∑ s, ∑ i, A.cross s i + filter_upwards [eventually_ge_atTop (100000000 + n + 12 * C + 8 + Fintype.card A.I + t + 6 * c)] + with w hw + intro N r d l B fa M P S hsite + have hc (s) (i) : A.cross s i ≤ w := by + have he : A.cross s i ≤ t := le_trans + (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ i)) + (Finset.single_le_sum (f := fun s => ∑ i, A.cross s i) (fun _ _ + => Nat.zero_le _) (Finset.mem_univ s)) + omega + have ⟨hr, hcount⟩ := packet_count w n C h hn (by omega) + obtain ⟨U, v, hu, hnet, hv⟩ := S.dispatch + (A.guard_size hn w (by omega) (by omega) (by omega) hc (by positivity) hr hcount) hsite + refine ⟨U, v, hu, hnet, hv.trans ?_⟩ + have hw' : 0 < w := by omega + let m := N * w ^ (max k 5) + have hb (i : ℕ) (hi : i ≤ max k 5) : N * w ^ i ≤ m := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_right hw' hi) + have h₁ := hb 5 (le_max_right k 5) + have h₂ := hb k (le_max_left k 5) + have h₃ : N ≤ m := Nat.le_mul_of_pos_right _ (by positivity) + have : 0 < N := by unfold N; positivity + calc + _ ≤ c * (6 * m) := by apply Nat.mul_le_mul_left; change N * w ^ 5 + _ + _ + _ ≤ _; omega + _ = (6 * c) * m := by ring + _ ≤ w * m := Nat.mul_le_mul_right _ (by omega) + _ = _ := by unfold m; rw [pow_succ]; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/FetchSlot.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/FetchSlot.lean new file mode 100644 index 0000000000..8593ebf023 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/FetchSlot.lean @@ -0,0 +1,946 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.PinIndexRead +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Slots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Vector.Cases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.LocalBank + +/-! # Reading old physical bits at either endpoint -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex + +open Diagonal +variable {N l r : ℕ} + +/-- Computes the value by the application `Sum.elim (Pin.literal y u) (Sum.elim (Pin.broadcast +y) (Links.view u (Pin.link y)))`. -/ +def value (y : Pin N l l r → Bool) (u : Fin (3 * r)) : Machine.Ports N l l → Bool := + Sum.elim (Pin.literal y u) (Sum.elim (Pin.broadcast y) (Links.view u (Pin.link y))) + +/-- Matching `a` pairs `u` with `a-u`, except for a missing self-link. -/ +def number (k : Kind r) (u : Fin (3 * r)) : Option (Fin (3 * r)) := + match k with + | .empty => none + | .literal => some u + | .broadcast => some ⟨0, u.pos⟩ + | .link a => if u = a - u then none else some (min u (a - u)) + +private theorem match_of_address (e : Links.Slot (3 * r) N) (h : Fin (N / 4)) + (he : Links.address e = h) : kind (r := r) (l := l) (some (.inr (.inr h))) = + .link (e.1.val.1 + e.1.val.2) := by + subst h + let k := finProdFinEquiv (e.1.val.1 + e.1.val.2, e.2) + have hp : (Links.address e).val < 3 * r * (N / (4 * (3 * r))) := k.isLt + have hk : (⟨(Links.address e).val, hp⟩ : Fin _) = k := rfl + simp [kind, hp, hk, k] + +private theorem covered (u : Fin (3 * r)) (e : Links.Slot (3 * r) N) (he : Links.sees u e.1) : + number (kind (l := l) (some (.inr (.inr (Links.address e))))) u = some e.1.val.1 := by + let _ : NeZero (3 * r) := ⟨u.pos.ne'⟩ + rw [match_of_address e _ rfl] + have h := e.1.property + rcases he with rfl | rfl <;> simp [number, h.ne, h.ne', min_eq_left h.le, min_eq_right h.le] + +private theorem has_position (u j : Fin (3 * r)) (p : Fin (N / 4)) + (he : number (kind (l := l) (some (.inr (.inr p)))) u = some j) : + ∃ e : Links.Slot (3 * r) N, Links.sees u e.1 ∧ Links.address e = p ∧ e.1.val.1 = j := by + let _ : NeZero (3 * r) := ⟨u.pos.ne'⟩ + by_cases hp : p.val < 3 * r * (N / (4 * (3 * r))) + swap; · simp [kind, hp, number] at he + let z := finProdFinEquiv.symm (⟨p.val, hp⟩ : Fin (3 * r * (N / (4 * (3 * r))))) + let v := z.1 - u + simp only [kind, dite_eq_left hp, number] at he + change (if u = v then none else some (min u v)) = some j at he + have hn : u ≠ v := by intro h; rw [ite_eq_left h] at he; contradiction + rw [ite_eq_right hn, Option.some.injEq] at he + have hi : min u v < max u v := by grind + let e : Links.Slot (3 * r) N := (⟨(min u v, max u v), hi⟩, z.2) + refine ⟨e, ?_, Fin.ext ?_, he⟩ + · change u = min u v ∨ u = max u v + grind + · change (finProdFinEquiv (min u v + max u v, z.2)).val = p.val + rw [min_add_max, show u + v = z.1 by simp [v]] + exact congrArg Fin.val (finProdFinEquiv.apply_symm_apply _) + +theorem number_spec (y : Pin N l l r → Bool) (u : Fin (3 * r)) (p : Machine.Ports N l l) : + match number (kind (some p)) u with + | none => value y u p = false + | some j => ∃ q, prior p j = some q ∧ value y u p = y q := by + rcases p with k | k | k + · exact ⟨.inl (u, k), rfl, rfl⟩ + · exact ⟨.inr (.inl k), rfl, rfl⟩ + · cases he : number (kind (l := l) (some (.inr (.inr k)))) u with + | some j => + obtain ⟨e, hu, rfl, rfl⟩ := has_position u j k he + exact ⟨.inr (.inr e), prior_old (l := l) (.inr (.inr e)) _ rfl, + Links.view_address u (Pin.link y) e hu⟩ + | none => + have hh : ¬∃ s : {s : Links.Slot (3 * r) N // Links.sees u s.1}, Links.address s.val = k := by + rintro ⟨s, rfl⟩ + rw [covered u s.val s.property] at he + contradiction + change Links.view u (Pin.link y) k = false + exact Function.extend_apply' (fun s => Pin.link y s.val) (fun _ => false) _ hh + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex +end + +/- # Cost of testing and receiving compactly indexed pins -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex + +open Controller Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) (hb : 100 * N ≤ 2 ^ w) + [NeZero r] [NeZero (3 * r)] [NeZero (N / 4)] [LinearOrder (Name n r)] + (idx : Name n r ↪ Coloring.B w) (cell : Coloring.B w → Domain N l r) + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +include hw hi hb idx in +open Classical in +theorem packed_pins : + packed (U := raw _) F C.input (fun (s : X) j => (decode s (cell j)).isSome.toNat) 512 ∧ + packed (U := raw _) F C.input (fun (s : X) j => (shared s (cell j)).toNat) 512 ∧ + packed (U := raw _) F C.input (fun (s : X) j => (expected C s (cell j)).toNat) 512 := by + let k (s : X) j := query s (cell j) + let off (s : X) j := placeInClass P.colors (cellPort s (cell j)) + have hk := packed_query (i := i) C hw hi hb cell idx + have ho := packed_port (i := i) C hw hi hb cell (placeInClass P.colors) + have hget := C.packed_get hw hi k idx off hk (ho.mono (by decide)) + have hstatus : packed (U := raw _) F C.input (fun (s : X) j => status s (cell j)) 188 := + C.packed_pair hw hi k idx hk state + have hm := packed_mark (i := i) C hw hi hb cell + have hw' : 12 ≤ 2 ^ w := by have := hw.large; have := Nat.lt_two_pow_self (n := w); omega + have hmark (s : X) j : mark s (cell j) < 4 := by + unfold mark + rw [mode_spec] + split + · decide + · unfold tag; split <;> decide + have hstate (s : X) j : status s (cell j) < 3 := by + simp only [status, state] + split_ifs <;> decide + have H := packed.binary activity (m := 4) (n := 3) hw' hm hstatus hmark hstate + have val (s : X) j : activity (mark s (cell j)) (status s (cell j)) < 3 := by + rw [activity_eq] + split_ifs <;> decide + have hfit : fits (fun (s : X) j => activity (mark s (cell j)) (status s (cell j))) := + fun s j => (val s j).trans_le (by omega) + have hs (s : X) j : (decode s (cell j)).isSome = false → shared s (cell j) = false := by + unfold shared + cases decode s (cell j) <;> simp + refine ⟨?_, ?_, ?_⟩ + · convert (H.unary hfit (fun k => if k = 0 then 0 else 1)).mono (n := 512) (by decide) using 1 + funext s j + rw [activity_eq] + cases (decode s (cell j)).isSome <;> cases shared s (cell j) <;> rfl + · convert (H.unary hfit (fun k => if k = 2 then 1 else 0)).mono (n := 512) (by decide) using 1 + funext s j + rw [activity_eq] + cases he : (decode s (cell j)).isSome + · rw [hs s j he]; rfl + · cases shared s (cell j) <;> rfl + · have hl := packed.binary (fun k x => if k = 2 then x else 0) (m := 3) (n := 2) + (by omega) H hget val (fun s j => by cases get w s (k s j) (off s j) <;> decide) + convert hl.mono (n := 512) (by decide) using 1 + funext s j + rw [expected_eq s C hw.bits, activity_eq] + cases he : (decode s (cell j)).isSome + · rw [hs s j he]; rfl + · cases shared s (cell j) <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex +end + +/- # The activity and transfer checks for candidate slot bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.SlotKey +open Diagonal Controller MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i +local notation "D" => SlotKey.Domain n r (B * P.count) h + +open Classical in +/-- The value specified by `.inr (.inl (expand hn i (workerAt s) t))`. -/ +def edge (s : X) (t : D) : Edge P B := .inr (.inl (expand hn i (workerAt s) t)) + +open Classical in +/-- Tests whether `incident s (edge s t)` holds. -/ +def active (s : X) (t : D) := decide (incident s (edge s t)) + +open Classical in +/-- Tests whether `incident s (edge s t) ∧ source s (edge s t) ≠ target s (edge s t)` holds. -/ +def shared (s : X) (t : D) := decide (incident s (edge s t) + ∧ source s (edge s t) ≠ target s (edge s t)) + +variable [LinearOrder (Name n r)] [NeZero (N / 4)] [NeZero (3 * r)] + +open Classical in +/-- The quantity computed by `Controller.get w s (Controller.key P B (edge s t)) (t.2.2.val + h +* t.2.1.val)`. -/ +def expected (w : ℕ) (s : X) (t : D) : Bool := + Controller.get w s (Controller.key P B (edge s t)) (t.2.2.val + h * t.2.1.val) + +omit [NeZero (3 * r)] in +open Classical in +theorem expected_eq (hw : N ≤ 2 ^ w) (s : X) (t : D) (hs : shared s t = true) : + expected w s t = C.numberInOrder.physicalBit s (edge s t) 0 := by + obtain ⟨hi, hn⟩ := of_decide_eq_true hs + have he : width s (edge s t) = 1 := rfl + have hf : source s (edge s t) ≠ target s (edge s t) ∧ incident s (edge s t) ∧ 0 + < width s (edge s t) := + ⟨hn, hi, he.ge⟩ + rw [physicalBit, dite_eq_left hf, C.get_eq hw] + simp only [he, mul_one, add_zero] + rfl + +open Classical in +theorem packed_slots (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) (hc : 3 * r * Fintype.card (Name n r) ≤ 2 ^ w) + (idx : Name n r ↪ Coloring.B w) (cell : Coloring.B w → D) : + packed (U := raw _) F (C.input (i := i)) (fun s j => (active s (cell j)).toNat) 129 ∧ + packed (U := raw _) F (C.input (i := i)) (fun s j => (shared s (cell j)).toNat) 129 ∧ + packed (U := raw _) F (C.input (i := i)) (fun s j => (expected w s (cell j)).toNat) (37 + 250) + := by + let keys (s : X) (j : Coloring.B w) := Controller.key P B (edge s (cell j)) + have hsize : 3 * r * Fintype.card (Fin (count n r)) ≤ 2 ^ w := by + apply le_trans _ hc + apply Nat.mul_le_mul_left + rw [Fintype.card_fin] + refine (Nat.div_le_self _ _).trans ?_ + exact Fintype.card_le_of_injective (fun k : SlotKey n r => (Sum.inr (.inl k) : Name n r)) + (fun _ _ h => Sum.inl.inj (Sum.inr.inj h)) + have hk : packed (U := raw _) F (C.input (i := i)) (fun s j => (idx (keys s j)).val) 37 := + C.workerTable hw hi (fun j => (cell j).1) hsize + (fun u t => (idx (.inr (.inl (enumerate hn i ((Worker.index r).symm u) t).val))).val) + have ht := C.packed_pair hw hi keys idx hk + have ha := ht (fun u x y => (decide (x = u ∨ y = u)).toNat) + have hs := ht (fun u x y => (decide ((x = u ∨ y = u) ∧ x ≠ y)).toNat) + simp only [keys, ends_eq] at ha hs + refine ⟨ha, hs, ?_⟩ + have he := packed.const (U := raw _) F (C.input (i := i)) (fun j => (cell j).2.2.val + + h * (cell j).2.1.val) + (m := 0) (by rw [pow_zero, mul_one]; exact hi) + exact C.packed_get hw hi keys idx _ hk (he.mono (by decide)) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.SlotKey +end + +/- # A fixed private tape shared by all workers and feasible reports -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w k : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +open Classical in +/-- Indexes the guess by the coordinates of `PinIndex.Domain N l r ⊕ SlotKey.Domain n r (B * +P.count) h`. -/ +abbrev Guess (P : Format N l d n r h) (B : ℕ) := + PinIndex.Domain N l r ⊕ SlotKey.Domain n r (B * P.count) h + +open Classical in +/-- Indexes the xin by the coordinates of `Machine.Ports N l l ⊕ Guess P B`. -/ +abbrev XIn (P : Format N l d n r h) (B : ℕ) := Machine.Ports N l l ⊕ Guess P B + +open Classical in +/-- Indexes the with guess by the coordinates of `Invocation (P := P) (A := A) (hn := hn) (M := +M) (B := B) i × (Guess P B → Bool)`. -/ +abbrev WithGuess (P : Format N l d n r h) (A : Expansion F n h) (hn : 2 ≤ n) + (M : Bank (Fin n)) (B : ℕ) (i : Fin n) := + Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i × (Guess P B → Bool) + +open Classical in +/-- Computes the tape in by the application `Sum.elim (C.input z.1) z.2`. -/ +def tapeIn (z : WithGuess P A hn M B i) : XIn P B → Bool := Sum.elim (C.input z.1) z.2 + +open Classical in +theorem lift (hx : Fintype.card (XIn P B) ≤ 2 ^ w) {f : Array X w} + (hf : packed (U := raw _) F C.input f k) : + packed (U := raw _) F C.tapeIn (fun z => f z.1) (k + 2) := + hf.lift C.tapeIn Prod.fst Sum.inl hx (fun _ => rfl) + +open Classical in +/-- The equivalence obtained by `Equiv.subtypeSum.toEmbedding.trans (p.sumMap (SlotKey.encode +s))`. -/ +def collect (s : X) (p : {e : Pin N l l r // incident s (.inl e)} ↪ PinIndex.Domain N l r) : + LocalBit s ↪ Guess P B := + Equiv.subtypeSum.toEmbedding.trans (p.sumMap (SlotKey.encode s)) + +open Classical in +/-- Computes the gather by the application `collect s (PinIndex.encode hfa s)`. -/ +abbrev gather (hfa : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) (s : X) : LocalBit s ↪ Guess P B + := + collect s (PinIndex.encode hfa s) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- # Checking a fixed private tape in place of a variable set of local bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal Finset + +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} + +variable (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) + (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def used : Guess P B → Bool := Sum.elim (fun j => (PinIndex.decode s j).isSome) (SlotKey.active s) + +open Classical in +/-- Computes the sent by the application `Sum.elim (PinIndex.shared s) (SlotKey.shared s)`. -/ +def sent : Guess P B → Bool := Sum.elim (PinIndex.shared s) (SlotKey.shared s) + +omit [Fintype F] in +open Classical in +theorem used_iff (j : Guess P B) : used s j = true ↔ ∃ e, gather hf s e = j := by + constructor + · intro hu + cases j with + | inl j => + obtain ⟨q, h⟩ := Option.isSome_iff_exists.mp hu + obtain ⟨hq, he⟩ := (PinIndex.decode_eq hf s j q).mp h + exact ⟨⟨.inl q, hq⟩, congrArg Sum.inl he⟩ + | inr j => + obtain ⟨q, he⟩ := (SlotKey.range_encode s j).mpr (of_decide_eq_true hu) + exact ⟨⟨.inr q.1, q.2⟩, congrArg Sum.inr he⟩ + · rintro ⟨⟨q|q, h⟩, rfl⟩ + · change (PinIndex.decode s (PinIndex.encode hf s ⟨q, h⟩)).isSome = true + rw [PinIndex.decode_encode]; rfl + · change decide (incident s (.inr (.inl (SlotKey.expand hn i (workerAt s) + (SlotKey.encode s ⟨q, h⟩))))) = true + rw [SlotKey.expand_encode, decide_eq_true_eq] + exact h + +omit [Fintype F] in +open Classical in +theorem sent_iff (e : LocalBit s) : + sent s (gather hf s e) = true ↔ source s (wrap e.1) ≠ target s (wrap e.1) := by + rcases e with ⟨q|q, h⟩ + · change PinIndex.shared s (PinIndex.encode hf s ⟨q, h⟩) = true ↔ _ + simp only [PinIndex.shared, PinIndex.decode_encode, Option.any_some, decide_eq_true_eq, wrap] + · change SlotKey.shared s (SlotKey.encode s ⟨q, h⟩) = true ↔ _ + have he : incident s (.inr (.inl q)) := h + simp only [SlotKey.shared, SlotKey.edge, SlotKey.expand_encode, decide_eq_true_eq, he, + true_and, wrap] + +omit [Fintype F] in +open Classical in +theorem literal_eq (x : Guess P B → Bool) : + Pin.literal (localPins s (x ∘ gather hf s)) s.site = fun j => x (.inl (.inl j)) := by + funext j + obtain ⟨he, hv⟩ := (PinIndex.decode_eq hf s _ _).mp (PinIndex.decode_left s j) + change fullBit s _ (.inl (.inl (s.site, j))) = _ + have ht : incident s (wrap (.inl (.inl (s.site, j)))) := he + rw [fullBit, dite_eq_left ht] + exact congrArg (fun i => x (.inl i)) hv + +variable [LinearOrder (Name n r)] [NeZero (N / 4)] + +open Classical in +/-- Computes the expected by the application `Sum.elim (PinIndex.expected C s) (SlotKey.expected +w s)`. -/ +def expected (w : ℕ) : Guess P B → Bool := Sum.elim (PinIndex.expected C s) (SlotKey.expected w s) + +open Classical in +private theorem assigned (hw : N ≤ 2 ^ w) (e : LocalBit s) (he : sent s (gather hf s e) = true) : + C.expected s w (gather hf s e) = C.numberInOrder.physicalBit s (wrap e.1) 0 := by + rcases e with ⟨q|q, h⟩ + · change PinIndex.expected C s (PinIndex.encode hf s ⟨q, h⟩) = _ + simp only [PinIndex.expected, PinIndex.decode_encode, Option.any_some, wrap] + · let v : SlotKey.Here s := ⟨q, h⟩ + exact (SlotKey.expected_eq C hw s (SlotKey.encode s v) he).trans + (congrArg (fun t => C.numberInOrder.physicalBit s (.inr (.inl t)) 0) + (SlotKey.expand_encode s v)) + +open Classical in +/-- Returns `(!sent || (expected == bit))` when `used` holds, and `!bit` otherwise. -/ +def accept (used sent expected bit : Bool) : Bool := + if used then (!sent || (expected == bit)) else !bit + +open Classical in +/-- The condition `∀ j, accept (used s j) (sent s j) (C.expected s w j) (x j) = true` on the +specified data. -/ +def pass (w : ℕ) (x : Guess P B → Bool) : Prop := + ∀ j, accept (used s j) (sent s j) (C.expected s w j) (x j) = true + +open Classical in +private theorem pass_iff (hw : N ≤ 2 ^ w) (x : Guess P B → Bool) : + C.pass s w x ↔ C.numberInOrder.Matches s (x ∘ gather hf s) ∧ + ∀ j, x j = false ∨ ∃ e, gather hf s e = j := by + have h₁ (e : LocalBit s) := (used_iff hf s _).mpr ⟨e, rfl⟩ + constructor + · intro hp + constructor + · intro e he + have he' := (sent_iff hf s e).mpr he + have ht := hp (gather hf s e) + simp only [accept, h₁, he', ite_true, Bool.not_true, Bool.false_or, beq_iff_eq] at ht + exact ht.symm.trans (C.assigned hf s hw e he') + · intro j + by_cases h : used s j = true + · exact .inr ((used_iff hf s j).mp h) + · left + simpa [accept, h] using hp j + · rintro ⟨hm, hx⟩ j + by_cases h : used s j = true + · obtain ⟨e, rfl⟩ := (used_iff hf s j).mp h + by_cases hp : sent s (gather hf s e) = true + · have he := hm e ((sent_iff hf s e).mp hp) + simp [accept, h, hp, C.assigned hf s hw e hp, ←he] + · simp [accept, h, hp] + · have he := (hx j).resolve_right (mt (used_iff hf s j).mpr h) + simp [accept, h, he] + +open Classical in +theorem sum_pass (hw : N ≤ 2 ^ w) (f : (LocalBit s → Bool) → F) : + (∑ x : Guess P B → Bool, if C.pass s w x then f (x ∘ gather hf s) else 0) = + ∑ x, if C.numberInOrder.Matches s x then f x else 0 := by + rw [← sum_padded (gather hf s) (fun x => if C.numberInOrder.Matches s x then f x else 0)] + apply sum_congr rfl + intro x _ + simp only [C.pass_iff hf s hw, unused, prod_ite_zero, prod_const_one, mem_univ, forall_const, + ite_and, mul_ite, mul_one, mul_zero] + split_ifs <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- +# Checking the fixed private tape + +Unused cells are pinned to zero, shared cells must match their routed +bits, and every worker checks its own literal. The circuit treats the +worker identifier and the report as inputs. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal Install MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] {w : ℕ} + +open Classical in +private theorem bit_lt (b : Bool) : b.toNat < 2 := by cases b <;> decide + +open Classical in +private theorem packed_accept {S I : Type} [Fintype I] {inp : S → I → Bool} + {a b c d : S → Coloring.B w → Bool} {k : ℕ} (hw : 16 ≤ 2 ^ w) + (ha : packed (U := raw _) F inp (fun s j => (a s j).toNat) k) + (hb : packed (U := raw _) F inp (fun s j => (b s j).toNat) k) + (hc : packed (U := raw _) F inp (fun s j => (c s j).toNat) k) + (hd : packed (U := raw _) F inp (fun s j => (d s j).toNat) k) : + packed (U := raw _) F inp + (fun s j => (accept (a s j) (b s j) (c s j) (d s j)).toNat) (k + 64) := by + let pair (x y : ℕ) := 2 * x + y + have h (x y : Bool) : pair x.toNat y.toNat < 4 := by cases x <;> cases y <;> decide + have h₁ := packed.binary pair (m := 2) (n := 2) (by omega) ha hb + (fun _ _ => bit_lt _) (fun _ _ => bit_lt _) + have h₂ := packed.binary pair (m := 2) (n := 2) (by omega) hc hd + (fun _ _ => bit_lt _) (fun _ _ => bit_lt _) + let join (x y : ℕ) := (accept (x / 2 == 1) (x % 2 == 1) (y / 2 == 1) (y % 2 == 1)).toNat + have H := packed.binary join (m := 4) (n := 4) hw h₁ h₂ (fun _ _ => h _ _) (fun _ _ => h _ _) + convert H.mono (n := k + 64) (by omega) using 1 + funext s j + cases a s j <;> cases b s j <;> cases c s j <;> cases d s j <;> simp [join, pair, accept] + +variable [Fintype F] {N l d B n r h : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} + [NeZero r] [NeZero (3 * r)] [NeZero (N / 4)] [LinearOrder (Name n r)] + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i +local notation "Y" => WithGuess P A hn M B i + +open Classical in +private abbrev Test (P : Format N l d n r h) (B : ℕ) := Guess P B ⊕ Fin l + +open Classical in +private def checkCell (w : ℕ) (z : Y) : Test P B → Bool + | .inl q => accept (used z.1 q) (sent z.1 q) (C.expected z.1 w q) (z.2 q) + | .inr j => z.2 (.inl (.inl j)) == C.code (some (z.1.site, z.1.script)) j + +variable (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) (hb : 100 * N ≤ 2 ^ w) + (hx : Fintype.card (XIn P B) ≤ 2 ^ w) (hc : 3 * r * Fintype.card (Name n r) ≤ 2 ^ w) + (idx : Name n r ↪ Coloring.B w) (hf : ∀ z, Diagonal.multiplicity P.colors z * r ^ n ≤ 4 * N) + +include hw hi hb hx hc idx in +open Classical in +private theorem packed_cells (p : Coloring.B w → Test P B) : + packed (U := raw _) F C.tapeIn (fun (z : Y) j => (C.checkCell w z (p j)).toNat) 606 := by + have hw' : 16 ≤ 2 ^ w := by have := hw.large; have := Nat.lt_two_pow_self (n := w); omega + have hw1 : 1 ≤ w := by have := hw.large; omega + have read (f : Coloring.B w → XIn P B) : + packed (U := raw _) F C.tapeIn (fun (z : Y) j => (C.tapeIn z (f j)).toNat) 514 := + (packed.named F C.tapeIn f (c := 0) (by rwa [pow_zero, mul_one])).mono (by decide) + have H (p : Coloring.B w → Guess P B) + (hu : packed (U := raw _) F C.input (fun (s : X) j => (used s (p j)).toNat) 512) + (hs : packed (U := raw _) F C.input (fun (s : X) j => (sent s (p j)).toNat) 512) + (he : packed (U := raw _) F C.input (fun (s : X) j => (C.expected s w (p j)).toNat) 512) : + packed (U := raw _) F C.tapeIn (fun (z : Y) j => (C.checkCell w z (.inl (p j))).toNat) 578 := + packed_accept hw' (C.lift hx hu) (C.lift hx hs) (C.lift hx he) (read (Sum.inr ∘ p)) + apply packed.casesOn (c := 592) hw1 (fun z (_ : Unit) j => (C.checkCell w z j).toNat) + (fun _ => ()) p + · intro f + apply packed.casesOn (c := 578) hw1 (fun z (_ : Unit) j => (C.checkCell w z (.inl j)).toNat) + (fun _ => ()) f + · intro a + obtain ⟨hu, hs, he⟩ := PinIndex.packed_pins (i := i) C hw hi hb idx a + exact H (Sum.inl ∘ a) hu hs he + · intro a + obtain ⟨hu, hs, he⟩ := SlotKey.packed_slots (i := i) C hw hi hc idx a + exact H (Sum.inr ∘ a) (hu.mono (by decide)) (hs.mono (by decide)) (he.mono (by decide)) + · intro a + have h₁ := read (fun j => .inr (.inl (.inl (a j)))) + have h₂ := read (fun j => .inl (.inl (a j))) + have hsame := packed.binary (fun x y => (x == y).toNat) (m := 2) (n := 2) (by omega) + h₁ h₂ (fun _ _ => bit_lt _) (fun _ _ => bit_lt _) + convert hsame.mono (n := 592) (by decide) using 1 + funext z j + change (_ == _).toNat = ((z.2 (.inl (.inl (a j)))).toNat == + (C.code (some (z.1.site, z.1.script)) (a j)).toNat).toNat + cases z.2 (.inl (.inl (a j))) <;> cases C.code (some (z.1.site, z.1.script)) (a j) <;> rfl + +include hw hi hb hx hc idx in +open Classical in +theorem private_net : + ∃ f, Weight F f (2 ^ w * (100 + w) ^ 650) ∧ ∀ z : Y, f (C.tapeIn z) = + if C.pass z.1 w z.2 then Pin.mask F (workerAt z.1) (C.code (some (z.1.site, z.1.script))) + (localPins z.1 (z.2 ∘ gather hf z.1)) else 0 := by + have hl : 0 < l := by have := C.literal; omega + let _ : Nonempty (Test P B) := ⟨.inr ⟨0, hl⟩⟩ + obtain ⟨e⟩ : Nonempty (Test P B ↪ Coloring.B w) := Function.Embedding.nonempty_of_card_le (by + rw [Fintype.card_fin] + apply le_trans _ hx + simp only [Test, XIn, Machine.Ports, Fintype.card_sum, Fintype.card_fin] + omega) + let p := Function.invFun e + have hp : Function.Surjective p := (Function.leftInverse_invFun e.injective).surjective + have hw' : 16 ≤ 2 ^ w := by have := hw.large; have := Nat.lt_two_pow_self (n := w); omega + have h := C.packed_cells (i := i) hw hi hb hx hc idx p + obtain ⟨b, hb, he⟩ := packed.conjunction (by have := hw.large; omega) h + (fun _ _ => (bit_lt _).trans_le (by omega)) + have hout := hb.weight (Weight.dense F Unit (fun x => if x () then 1 else 0)) + refine ⟨_, hout.mono ?_, fun z => ?_⟩ + · rw [Fintype.card_unit] + let T := 2 ^ w * (100 + w) ^ 608 + have ht : 16 ≤ T := hw'.trans (Nat.le_mul_of_pos_right _ (by positivity)) + calc + _ ≤ T * 2 := by + rw [show 606 + 2 = 608 by decide, show (8 : ℕ) * 2 ^ 1 = 16 by decide] + exact (Nat.add_le_add_left ht T).trans_eq (mul_two T).symm + _ ≤ T * (100 + w) := Nat.mul_le_mul_left _ (by omega) + _ = 2 ^ w * (100 + w) ^ 609 := by unfold T; rw [mul_assoc, ← pow_succ] + _ ≤ _ := by gcongr; omega + · have ht : (∀ j, (C.checkCell w z (p j)).toNat = 1) ↔ + C.pass z.1 w z.2 ∧ (fun j => z.2 (.inl (.inl j))) = C.code (some (z.1.site, z.1.script)) + := by + have hu : (∀ j, (C.checkCell w z (p j)).toNat = 1) ↔ + ∀ t, C.checkCell w z t = true := by + simp only [Bool.toNat_eq_one] + constructor + · intro h t; obtain ⟨j, rfl⟩ := hp t; exact h j + · exact fun h _ => h _ + rw [hu, Sum.forall] + simp only [checkCell, beq_iff_eq, pass, funext_iff] + simp only [Function.comp_apply, he, decide_eq_true_eq, ht, Pin.mask, workerAt, + Equiv.apply_symm_apply, literal_eq, ite_and] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- # Reading a colored processor input from the compact array -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex + +open Controller Diagonal +variable {F : Type} [Field F] {N l d B n r h : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} {i : Fin n} + (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i +local notation "Y" => WithGuess P A hn M B i + +open Classical in +/-- The read of type `Bool` for the given inputs. -/ +def read (z : Y) (j u : ℕ) : Bool := + if hj : j < Fintype.card (Selected P.colors (axis z.1) (symbol z.1)) then + if hu : u < 3 * r then + let p := ((Fintype.equivFin (Selected P.colors (axis z.1) (symbol z.1))).symm ⟨j, hj⟩).val + if A.owner hn N z.1.report.val (P.colors p) = workerAt z.1 then + value (localPins z.1 (z.2 ∘ gather hf z.1)) ⟨u, hu⟩ p else false + else false + else false + +open Classical in +private theorem pin_read (z : Y) (e : Domain N l r) {q : Pin N l l r} + (he : decode z.1 e = some q) : + localPins z.1 (z.2 ∘ gather hf z.1) q = z.2 (.inl e) := by + obtain ⟨hq, rfl⟩ := (decode_eq hf z.1 e q).mp he + change fullBit z.1 _ (.inl q) = _ + rw [fullBit_at _ _ _ hq] + rfl + +open Classical in +/-- In the case `some (.inl k)`, this construction gives `some (.inl k)`. -/ +def direct : Option (Machine.Ports N l l) → Option (Domain N l r) + | some (.inl k) => some (.inl k) + | _ => none + +variable [NeZero r] + +open Classical in +/-- The access of type `Option (Domain N l r)`, constructed using `.inr (k, u)`. -/ +def access (s : X) (k : Fin (4 * N / r)) (u : Fin (3 * r)) : Option (Domain N l r) := + let e := .inr (k, u) + let p := cellPort s e + let st := status s e + if st = 0 then none else + if st = 1 ∧ (direct (r := r) p).isSome then direct p else + (number (kind p) u).map (fun j => .inr (k, j)) + +open Classical in +private theorem status_port (s : X) (k : Fin (4 * N / r)) (u : Fin (3 * r)) (p : Machine.Ports N l + l) + (hp : cellPort s (.inr (k, u)) = some p) : + status s (.inr (k, u)) = state s.site u (Worker.index r (A.owner hn N s.report.val (P.colors + p))) := by + unfold status query + rw [hp] + change state _ ((Worker.index r) ((Worker.index r).symm _)) _ = _ + rw [Equiv.apply_symm_apply] + rfl + +open Classical in +theorem read_access (z : Y) (k : Fin (4 * N / r)) (u : Fin (3 * r)) : + read hf z k.val u.val = (access z.1 k u).any (fun e => z.2 (.inl e)) := by + let s := z.1 + let t := Selected P.colors (axis s) (symbol s) + let y := localPins s (z.2 ∘ gather hf s) + unfold read + by_cases hk : k.val < Fintype.card t + swap + · have he : cellPort s (.inr (k, u)) = none := dite_eq_right hk + rw [dite_eq_right hk] + simp [access, show cellPort z.1 (.inr (k, u)) = none from he, direct, kind, number] + rw [dite_eq_left hk, dite_eq_left u.isLt] + let p := ((Fintype.equivFin t).symm ⟨k.val, hk⟩).val + let dest := A.owner hn N s.report.val (P.colors p) + change (if dest = workerAt s then value y u p else false) = + (access s k u).any _ + have hp : cellPort s (.inr (k, u)) = some p := dite_eq_left hk + have hs : status s (.inr (k, u)) = state s.site u (Worker.index r dest) := + status_port s k u p hp + unfold access + dsimp only + rw [hs, hp] + by_cases hd : dest = workerAt s + swap + · have he : s.site ≠ Worker.index r dest := + fun h => hd ((Worker.index r).eq_symm_apply.mpr h.symm) + simp [hd, state, he] + have he : s.site = Worker.index r dest := ((Worker.index r).eq_symm_apply.mp hd).symm + rw [ite_eq_left hd, state, ite_eq_left he] + have dir : (direct (r := r) (some p)).isSome = true ↔ ∃ j, p = .inl j := by + rcases p with j|j <;> simp [direct] + by_cases own : s.site = u ∧ (direct (r := r) (some p)).isSome + · obtain ⟨u', hj⟩ := dir.mp own.2 + rw [ite_eq_left own.1, hj] + simp only [direct, Option.isSome_some, and_self, ite_true, one_ne_zero, ite_false, + Option.any_some] + rw [← own.1] + exact pin_read hf z _ (decode_left s _) + have hn' : (if s.site = u then 1 else 2) ≠ 0 := by split <;> decide + have hd' : ¬ ((if s.site = u then 1 else 2) = 1 ∧ (direct (r := r) (some p)).isSome) := by + split <;> grind + rw [ite_eq_right hn', ite_eq_right hd'] + have ht := number_spec y u p + cases hnum : number (kind (some p)) u with + | none => rwa [hnum] at ht + | some j => + rw [hnum] at ht + obtain ⟨q, hq, hv⟩ := ht + obtain ⟨hq', hj⟩ := prior_spec hq + have hi : target s (.inl q) = s.site := by + change Worker.index r (A.owner hn N s.report.val (P.colors q.position)) = _ + rw [hq']; exact he.symm + have ho : ¬ PinIndex.own s q := by + rintro ⟨x, rfl⟩ + have hx : p = .inl x := hq'.symm + rw [hx] at hnum + have hu : u = j := Option.some.inj hnum + exact own ⟨(Fin.ext hj).trans hu.symm, dir.mpr ⟨x, hx⟩⟩ + have hi' := (decode_right s k j q).mpr ⟨hq' ▸ hp, hj, hi, ho⟩ + exact hv.trans (pin_read hf z _ hi') + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex +end + +/- # Collecting original tape bits by parallel reads -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex + +open Controller Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) (hb : 100 * N ≤ 2 ^ w) + (hx : Fintype.card (XIn P B) ≤ 2 ^ w) [NeZero r] [LinearOrder (Name n r)] + (idx : Name n r ↪ Coloring.B w) (hf : ∀ z, Diagonal.multiplicity P.colors z * r ^ n ≤ 4 * N) + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i +local notation "Y" => WithGuess P A hn M B i + +include hw hi hb idx in +open Classical in +private theorem packed_access (k : Coloring.B w → Fin (4 * N / r)) (u : Coloring.B w → Fin (3 * r)) + (fn : Option (Domain N l r) → ℕ) : + packed (U := raw _) F C.input (fun (s : X) j => fn (access s (k j) (u j))) 300 := by + let cell (j : Coloring.B w) : Domain N l r := .inr (k j, u j) + let f (s : X) j := number (kind (cellPort s (cell j))) (u j) + let e := Fintype.equivFin (Option (Fin (3 * r))) + have hf : packed (U := raw _) F C.input (fun s j => (e (f s j)).val) 96 := + packed_kind C hw hi hb cell (fun a b => (e (number a b)).val) + have hcap : Fintype.card (Option (Fin (3 * r))) * Fintype.card (Fin (4 * N / r)) ≤ 2 ^ w := by + rw [Fintype.card_option, Fintype.card_fin, Fintype.card_fin] + have := Nat.mul_div_le (4 * N) r + have := Nat.div_le_self (4 * N) r + nlinarith + have H (v : Coloring.B w → ℕ) : packed (U := raw _) F (C.input (i := i)) (fun _ => v) 2 := + packed.const (U := raw _) F _ _ (m := 0) (by rw [pow_zero, mul_one]; exact hi) + let _ : Nonempty (Fin (4 * N / r)) := ⟨k 0⟩ + let e' := Fintype.equivFin (Fin (4 * N / r)) + let g (v : Option (Fin (3 * r))) (j : Fin (4 * N / r)) := fn (v.map (fun x => .inr (j, x))) + have right := packed.named_table g hcap f (fun _ j => k j) e e' hf (H (fun j => (e' (k j)).val)) + have left := packed_port (i := i) C hw hi hb cell (fun p => fn (direct p)) + have lit := packed_port (i := i) C hw hi hb cell (fun p => (direct (r := r) p).isSome.toNat) + have hstat : packed (U := raw _) F C.input (fun (s : X) j => status s (cell j)) 188 := + C.packed_pair hw hi _ idx (packed_query C hw hi hb cell idx) state + have h2 : 2 < 2 ^ w := by have := hw.large; have := Nat.lt_two_pow_self (n := w); omega + have ht : fits (fun (s : X) j => status s (cell j)) := by + intro s j + simp only [status, state] + split_ifs <;> omega + have hl : fits (fun (s : X) j => (direct (r := r) (cellPort s (cell j))).isSome.toNat) := by + intro s j + dsimp only + cases (direct (r := r) (cellPort s (cell j))).isSome <;> simp only [Bool.toNat_false, + Bool.toNat_true] <;> omega + have hone : fits (fun (_ : X) (_ : Coloring.B w) => 1) := fun _ _ => (by omega : 1 < 2 ^ w) + have a := lit.choose_eq (H (fun _ => 1)) left right hl hone + have b := hstat.choose_eq (H (fun _ => 1)) a right ht hone + have c := hstat.choose_eq (H (fun _ => 0)) (H (fun _ => fn none)) b ht + (fun _ _ => Nat.two_pow_pos w) + convert c.mono (n := 300) (by decide) using 1 + funext s j + unfold access f g + change fn (if status s (cell j) = 0 then none else + if status s (cell j) = 1 ∧ (direct (r := r) (cellPort s (cell j))).isSome + then _ else _) = _ + cases (direct (r := r) (cellPort s (cell j))).isSome <;> + simp only [Bool.false_eq_true, and_false, and_true, ite_false, Bool.toNat_true, + Bool.toNat_false] <;> + split_ifs <;> first | rfl | contradiction + +include hw hi hb hx idx in +open Classical in +private theorem bounded_read (k : Coloring.B w → Fin (4 * N / r)) (u : Coloring.B w → Fin (3 * r)) : + packed (U := raw _) F C.tapeIn (fun (z : Y) j => (read hf z (k j).val (u j).val).toNat) 400 + := by + let D := Domain N l r + let o : D := .inr (k 0, u 0) + let _ : Nonempty D := ⟨o⟩ + have hcard : Fintype.card D ≤ Fintype.card (Coloring.B w) := by + rw [Fintype.card_fin] + apply le_trans _ hx + exact Fintype.card_le_of_injective (fun j : D => (Sum.inr (.inl j) : XIn P B)) + (fun _ _ he => Sum.inl.inj (Sum.inr.inj he)) + obtain ⟨e⟩ := Function.Embedding.nonempty_of_card_le hcard + let choice (z : Y) j := access z.1 (k j) (u j) + have H (f : Option D → ℕ) : packed (U := raw _) F C.tapeIn (fun z j => f (choice z j)) 302 := + C.lift hx (packed_access C hw hi hb idx k u f) + have named (p : Coloring.B w → D) : + packed (U := raw _) F C.tapeIn (fun (z : Y) j => (z.2 (.inl (p j))).toNat) 2 := + packed.named F (C.tapeIn (i := i)) (fun j => .inr (.inl (p j))) (c := 0) + (by rw [pow_zero, mul_one]; exact hx) + have hget := packed.fetch (fun z j => (choice z j).getD o) e + (fun z t => (z.2 (.inl t)).toNat) (H (fun p => (e (p.getD o)).val)) named + have hk := H (fun p => p.isSome.toNat) + have hbool (b : Bool) : b.toNat < 2 := by cases b <;> decide + have ht := packed.binary (fun k x => if k = 1 then x else 0) (m := 2) (n := 2) + (by have := hw.large; have := Nat.lt_two_pow_self (n := w); omega) hk hget + (fun _ _ => hbool _) (fun _ _ => hbool _) + convert ht.mono (n := 400) (by decide) using 1 + funext z j + rw [read_access] + unfold choice + cases access z.1 (k j) (u j) <;> rfl + +include hw hi hb hx idx in +open Classical in +theorem packed_read (j u : Coloring.B w → ℕ) : + packed (U := raw _) F C.tapeIn (fun (z : Y) t => (read hf z (j t) (u t)).toNat) 512 := by + have hR := hw.pos + have hN := C.links + let _ : NeZero (3 * r) := ⟨by omega⟩ + let _ : NeZero (4 * N / r) := ⟨(Nat.div_pos (by nlinarith) hR).ne'⟩ + have h := bounded_read (i := i) C hw hi hb hx idx hf (fun t => Fin.ofNat _ (j t)) + (fun t => Fin.ofNat _ (u t)) + let ok (t : Coloring.B w) := j t < 4 * N / r ∧ u t < 3 * r + have hv := packed.const (U := raw _) F (C.tapeIn (i := i)) (fun t => if ok t then 1 else 0) + (m := 0) (by rw [pow_zero, mul_one]; exact hx) + have ht := packed.binary (fun k x => if k = 1 then x else 0) (m := 2) (n := 2) + (by have := hw.large; have := Nat.lt_two_pow_self (n := w); omega) hv h + (by intro z t; split <;> decide) + (fun _ _ => (show ∀ b : Bool, b.toNat < 2 from fun b => by cases b <;> decide) _) + convert ht.mono (n := 512) (by decide) using 1 + funext z t + by_cases H : ok t + · simp only [ite_eq_left H, ite_true, Fin.val_ofNat, Nat.mod_eq_of_lt H.1, Nat.mod_eq_of_lt H.2] + · rw [ite_eq_right H, ite_eq_right (by decide : 0 ≠ 1)] + have hp : Fintype.card (Selected P.colors (axis z.1) (symbol z.1)) ≤ 4 * N / r := + (Nat.le_div_iff_mul_le hR).mpr (project_bound _ hf _ _) + unfold read + split + · rename_i hj + rw [dite_eq_right (fun ht => H ⟨hj.trans_le hp, ht⟩)] + rfl + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex +end + +/- # Fetching slot bits from the private tape at variable template names -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w c : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i +local notation "Slot" => Position n r (B * P.count) h × Bool +local notation "Dom" => SlotKey.Domain n r (B * P.count) h + +open Classical in +private def colNumber (hn : 2 ≤ n) (i : Fin n) (u : Worker r) : Name n r → ℕ + | .inr (.inl k) => + if he : SlotKey.focus hn i u k = Layout.symbol u then + ((SlotKey.enumerate hn i u).symm ⟨k, he⟩).val + else 0 + | _ => 0 + +omit [Fintype F] in +open Classical in +private theorem encode_col (s : X) (e : SlotKey.Here s) : + (SlotKey.encode s e).1.val = colNumber hn i (workerAt s) (key P B (.inr (.inl e.val))) := by + rw [← SlotKey.expand_encode s e] + let k := SlotKey.enumerate hn i (workerAt s) (SlotKey.encode s e).1 + change _ = colNumber hn i (workerAt s) (.inr (.inl k.val)) + rw [colNumber, dite_eq_left k.property] + exact congrArg Fin.val ((SlotKey.enumerate hn i (workerAt s)).symm_apply_apply _).symm + +open Classical in +private def slotCode (hc : Fintype.card Dom ≤ 2 ^ w) : Dom ↪ Coloring.B w := + ((Equiv.prodCongr (Equiv.refl _) finProdFinEquiv).trans finProdFinEquiv).toEmbedding.trans + (Fin.castLEEmb (by simpa [SlotKey.Domain] using hc)) + +omit [Fintype F] in +open Classical in +private theorem encode_offset (hc : Fintype.card Dom ≤ 2 ^ w) (s : X) (e : SlotKey.Here s) : + (slotCode hc (SlotKey.encode s e)).val = + e.val.1.2.2.val + h * e.val.1.1.2.val + + (B * P.count * h) * colNumber hn i (workerAt s) (key P B (.inr (.inl e.val))) := by + rw [← encode_col] + rfl + +variable [LinearOrder (Name n r)] + +open Classical in +theorem packed_slot (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (XIn P B) ≤ 2 ^ w) (hc : 3 * r * Fintype.card (Name n r) ≤ 2 ^ w) + (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) + (slot : X → Coloring.B w → Slot) (idx : Name n r ↪ Coloring.B w) + (hk : packed (U := raw _) F C.input (fun s j => (idx (key P B (.inr (.inl (slot s j))))).val) c) + (low : Coloring.B w → ℕ) + (hlow : ∀ s j, (slot s j).1.2.2.val + h * (slot s j).1.1.2.val = low j) : + packed (U := raw _) F C.tapeIn + (fun z j => (fullBit z.1 (z.2 ∘ gather hf z.1) (.inr (slot z.1 j))).toNat) (c + 128) := by + have : Nonempty (Name n r) := ⟨.inl (.inr (fun _ => ⟨0, hw.pos⟩))⟩ + have hI : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w := by + rw [Fintype.card_sum] at hi + omega + have hD : Fintype.card Dom ≤ 2 ^ w := by + rw [Fintype.card_sum, Fintype.card_sum (α := PinIndex.Domain N l r)] at hi + omega + let keys (s : X) j := key P B (.inr (.inl (slot s j))) + let K (s : X) j := low j + (B * P.count * h) * colNumber hn i (workerAt s) (keys s j) + have hb := C.packed_workerLookup hw hI hc keys idx hk (fun u k + => (B * P.count * h) * colNumber hn i u k) + have ha := packed.const (U := raw _) F (C.input (i := i)) low (m := 0) (by + rw [pow_zero, mul_one] + exact hI) + have hK : packed (U := raw _) F C.input K (c + 51) := (ha.add hb).mono (by omega) + let p : Coloring.B w → XIn P B := Function.extend (slotCode hD) + (fun j => .inr (.inr j)) (fun _ => .inl (.inl ⟨0, by have := C.literal; omega⟩)) + have hv := packed.named F (C.tapeIn (i := i)) p (c := 0) (by rw [pow_zero, mul_one]; exact hi) + have hget := hv.lookup (C.lift hi hK) + let f (s : X) (j : Coloring.B w) := if incident s (.inr (.inl (slot s j))) then 1 else 0 + have hflag : packed (U := raw _) F C.input f (c + 92) := by + have h := C.packed_pair hw hI keys idx hk (fun u a b => if a = u ∨ b = u then 1 else 0) + simpa only [keys, ends_eq] using h + have z0 := packed.const (U := raw _) F (C.tapeIn (i := i)) (fun _ : Coloring.B w => 0) + (m := 0) (by rw [pow_zero, mul_one]; exact hi) + have hsize : 1 < 2 ^ w := Nat.one_lt_pow (by have := hw.large; omega) (by decide) + have H := z0.select (C.lift hi hflag) hget z0 + (fun _ _ => pow_pos (by decide) _) (fun _ _ => by unfold f; split <;> omega) + convert H.mono (n := c + 128) (by omega) using 1 + funext z j + by_cases he : incident z.1 (.inr (.inl (slot z.1 j))) + · let e : SlotKey.Here z.1 := ⟨slot z.1 j, he⟩ + have eq : Fin.ofNat (2 ^ w) (K z.1 j) = slotCode hD (SlotKey.encode z.1 e) := by + have ho := encode_offset hD z.1 e + have ho' : (slotCode hD (SlotKey.encode z.1 e)).val = K z.1 j := by + simpa only [e, hlow, K, keys] using ho + rw [← ho'] + exact Fin.ext (Nat.mod_eq_of_lt (Fin.isLt _)) + have ht : incident z.1 (wrap (.inr (slot z.1 j))) := he + unfold fullBit + rw [dite_eq_left ht] + simp only [f, he, ite_true, zero_lt_one, eq, p, (slotCode hD).injective.extend_apply] + rfl + · simp [f, he, fullBit, wrap] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Guard.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Guard.lean new file mode 100644 index 0000000000..ed17509c57 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Guard.lean @@ -0,0 +1,822 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.GroupWithZero.Finset +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Algebra.Field.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Replay +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Broadcast +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Named +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Present + +/-! # Padding finite tables and private bit assignments -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Finset +variable {F A B : Type} [Field F] (e : A ↪ B) + +open Classical in +/-- An unused position must contain zero. -/ +def unused (j : B) (x : Bool) : F := + if x = false ∨ ∃ i, e i = j then 1 else 0 + +variable [Fintype A] [Fintype B] + +open Classical in +theorem prod_padded (g : B → F) (hone : ∀ j, (¬∃ i, e i = j) → g j = 1) : + (∏ j, g j) = ∏ i, g (e i) := by + rw [← prod_map univ e g] + symm + exact prod_subset (subset_univ _) (fun j _ hj => hone j (by simpa using hj)) + +open Classical in +/-- Each assignment on the active bits has exactly one extension with +nonzero padding weight, even in characteristic two. -/ +theorem sum_padded [DecidableEq A] [DecidableEq B] (f : (A → Bool) → F) : + (∑ y : B → Bool, f (y ∘ e) * ∏ j, unused e j (y j)) = ∑ x, f x := by + let pad (x : A → Bool) := Function.extend e x (fun _ => false) + have hp (x) : pad x ∘ e = x := funext fun i => e.injective.extend_apply x (fun _ => false) i + have hi : Function.Injective pad := fun x y h => by rw [← hp x, h, hp] + let S := univ.image pad + have hz (y : B → Bool) (hy : y ∉ S) : (∏ j, unused e j (y j)) = (0 : F) := by + have hne : pad (y ∘ e) ≠ y := fun h => hy (mem_image.mpr ⟨_, mem_univ _, h⟩) + obtain ⟨j, hj⟩ := Function.ne_iff.mp hne + apply prod_eq_zero (mem_univ j) + have hn : ¬ ∃ i, e i = j := by + rintro ⟨i, rfl⟩ + exact hj (congrFun (hp (y ∘ e)) i) + have : y j ≠ false := fun h => hj ((Function.extend_apply' _ _ _ hn).trans h.symm) + exact ite_eq_right (not_or.mpr ⟨this, hn⟩) + calc + _ = ∑ y ∈ S, f (y ∘ e) * ∏ j, unused e j (y j) := + (sum_subset (subset_univ _) (fun y _ hy => by rw [hz y hy, mul_zero])).symm + _ = _ := by + unfold S + rw [sum_image hi.injOn] + apply sum_congr rfl + intro x _ + have h (j : B) : unused e j (pad x j) = (1 : F) := by + by_cases hj : ∃ i, e i = j + · exact ite_eq_left (.inr hj) + · exact ite_eq_left (.inl (Function.extend_apply' _ _ _ hj)) + simp only [hp, h, prod_const_one, mul_one] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- # Summing private bits in a scalar network -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install.Weight + +variable {F I J : Type} [Field F] + +private theorem free (b : Wire) : Net F .unit b (fun _ _ => 1) (wd b) := by + induction b with + | unit => exact .empty + | bit => exact .table .unit .bit _ (by decide) + | pair a b ha hb => simpa only [one_mul, wd] using (ha.par hb).pre (.unit' .unit) + +private theorem sum_layout [Fintype J] [DecidableEq J] (a b : Wire) + (i : I ≃ slots a) (j : J ≃ slots b) (f : (I ⊕ J → Bool) → F) (x : Val a) : + (∑ y, f (Sum.elim (bits a x ∘ i) y)) = + ∑ z : Val b, f (bits (.pair a b) (x, z) ∘ i.sumCongr j) * 1 := by + let e := (bits b).trans (j.symm.arrowCongr (Equiv.refl Bool)) + rw [← e.sum_comp] + apply Finset.sum_congr rfl + intro z _ + rw [mul_one] + congr 1 + funext t + cases t <;> rfl + +/-- Trace the named private bits against unary tables of weight one. +Every assignment contributes once, with no division by the alphabet size. -/ +theorem sum_right [Fintype J] [DecidableEq J] {m : ℕ} {f : (I ⊕ J → Bool) → F} + (h : Weight F f m) : + Weight F (fun x => ∑ y : J → Bool, f (Sum.elim x y)) (m + Fintype.card J) := by + intro a i + let b := word (Fintype.card J) + let j : J ≃ slots (word (Fintype.card J)) := Fintype.equivOfCardEq (by simp) + obtain ⟨v, hv, h⟩ := h (.pair a b) (i.sumCongr j) + have k := ((h.par (free b)).pre (.unit' _)).trace + refine ⟨v + wd b, by simpa [b] using Nat.add_le_add_right hv (Fintype.card J), ?_⟩ + convert k using 1 + funext x y + exact sum_layout a b i j f x + +end MatrixMultiplicationAllFields.MatrixExponent.Install.Weight +end + +section +/- # Class counts as linear combinations of broadcast bits -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Finset +variable {w : ℕ} + +/-- The sum of `if x i then 2 ^ i.val else 0` indexed by `i`. -/ +def number (x : Fin w → Bool) := ∑ i, if x i then 2 ^ i.val else 0 + +theorem number_succ (x : Fin (w + 1) → Bool) : + number x = (if x 0 then 1 else 0) + number (x ∘ Fin.succ) * 2 := by + rw [number, Fin.sum_univ_succ] + simp only [number, Fin.val_zero, pow_zero, Fin.val_succ, pow_succ, sum_mul, + Function.comp_apply, ite_mul, zero_mul] + +theorem number_test (x : ℕ) (hx : x < 2 ^ w) : + number (fun i : Fin w => x.testBit i.val) = x := by + induction w generalizing x with + | zero => simp [number]; omega + | succ w ih => + have h : x / 2 < 2 ^ w := (Nat.div_lt_iff_lt_mul (by decide)).mpr (by rwa [pow_succ] at hx) + rw [number_succ] + simp only [Function.comp_def, Fin.val_succ, Nat.testBit_add_one, Fin.val_zero, + Nat.testBit_zero, decide_eq_true_eq, ih _ h] + split_ifs <;> omega + +private theorem exists_number (x : Fin w → Bool) : + ∃ k : Fin (2 ^ w), (fun i : Fin w => k.val.testBit i.val) = x := by + let f (k : Fin (2 ^ w)) (i : Fin w) := k.val.testBit i.val + have hi : Function.Injective f := fun a b he => Fin.ext <| + (number_test a.val a.isLt).symm.trans ((congrArg number he).trans (number_test b.val b.isLt)) + exact ((Fintype.bijective_iff_injective_and_card f).2 ⟨hi, by simp⟩).2 x + +theorem number_lt (x : Fin w → Bool) : number x < 2 ^ w := by + obtain ⟨k, rfl⟩ := exists_number x + rw [number_test k.val k.isLt] + exact k.isLt + +theorem test_number (x : Fin w → Bool) (i : Fin w) : (number x).testBit i.val = x i := by + obtain ⟨k, rfl⟩ := exists_number x + rw [number_test k.val k.isLt] + +variable {I : Type} [Fintype I] + +/-- The quantity computed by `∑ j, number (fun i => x (j, i)) * a j`. -/ +def linear (a : I → ℕ) (x : I × Fin w → Bool) := ∑ j, number (fun i => x (j, i)) * a j + +theorem linear_register (F : Type) [Field F] (a : I → ℕ) (v w : ℕ) : + Register F v (linear (w := w) a) (20000 * (1 + Fintype.card I * w) * (1 + v)) := by + have h := Register.weighted F v (fun j : I × Fin w => 2 ^ j.2.val * a j.1) + rw [Fintype.card_prod, Fintype.card_fin] at h + convert h using 1 + funext x + rw [Fintype.sum_prod_type] + simp only [linear, number, sum_mul, ite_mul, zero_mul] + +theorem linear_le {a : I → ℕ} {M : ℕ} (ha : ∀ i, a i ≤ M) (x : I × Fin w → Bool) : + linear a x ≤ Fintype.card I * (2 ^ w * M) := by + unfold linear + calc + _ ≤ ∑ _ : I, 2 ^ w * M := sum_le_sum (fun i _ => Nat.mul_le_mul (number_lt _).le (ha i)) + _ = _ := by simp + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- # Scalar checks of bounded linear inequalities -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Install Coloring +variable {F I J : Type} [Field F] [Fintype I] {m v w : ℕ} + +omit [Fintype I] in +theorem Register.offset [Finite I] {f : (I → Bool) → ℕ} (h : Register F v f m) (n : ℕ) : + Register F v (fun x => f x + n) (m + 10100 * (1 + v)) := by + let : Fintype I := Fintype.ofFinite I + have hp := (h.add_disjoint (Register.const (I := Empty) n)).rename (Equiv.sumEmpty I Empty) + exact hp.mono (by simp; omega) + +/-- The data for the form construction, including `factors`, `offset`. -/ +structure Form (I : Type) where + /-- The `Form` component of type `I → ℕ`. -/ + factors : I → ℕ + /-- Stores the offset associated with this `Form`. -/ + offset : ℕ + +/-- The quantity computed by `linear f.factors x + f.offset`. -/ +def Form.value (f : Form I) (x : I × Fin w → Bool) := linear f.factors x + f.offset + +theorem Form.net (F : Type) [Field F] (f : Form I) (v w : ℕ) : + Register F v (f.value (w := w)) (40000 * (1 + Fintype.card I * w) * (1 + v)) := by + apply ((linear_register F f.factors v w).offset f.offset).mono + ring_nf + omega + +theorem Form.compare (F : Type) [Field F] (f g : Form I) (v w : ℕ) + (hf : ∀ x : I × Fin w → Bool, f.value x < 2 ^ v) + (hg : ∀ x : I × Fin w → Bool, g.value x < 2 ^ v) : + BNet F (fun x : I × Fin w → Bool => fun _ : Unit => decide (f.value x < g.value x)) + (90000 * (1 + Fintype.card I * w) * (1 + v)) := by + apply ((f.net F v w).less (g.net F v w) hf hg).mono + rw [Fintype.card_prod, Fintype.card_fin] + ring_nf + omega + +/-- Each input count field has `w` bits. The register width `v` is +chosen to rule out overflow even on malformed inputs. -/ +theorem checks_net (F : Type) [Field F] [Fintype J] (f g : J → Form I) (v w : ℕ) + (hf : ∀ j (x : I × Fin w → Bool), (f j).value x < 2 ^ v) + (hg : ∀ j (x : I × Fin w → Bool), (g j).value x < 2 ^ v) : + Weight F (fun x : I × Fin w → Bool => if ∀ j, (f j).value x < (g j).value x then 1 else 0) + (100000 * (1 + Fintype.card J) * (1 + Fintype.card I * w) * (1 + v)) := by + classical + let p (j : J) (x : I × Fin w → Bool) : F := if (f j).value x < (g j).value x then 1 else 0 + have hp (j : J) : Weight F (p j) (90000 * (1 + Fintype.card I * w) * (1 + v) + 16) := by + have act := Weight.dense F Unit (fun x => if x () then 1 else 0) + have h := ((f j).compare F (g j) v w (hf j) (hg j)).weight act + simpa only [Function.comp_def, decide_eq_true_eq, Fintype.card_unit, pow_one, p] using h + have k := Weight.finite_product p hp + simp only [p, Finset.prod_ite_zero, Finset.prod_const_one, Finset.mem_univ, forall_const] at k + apply k.mono + rw [Fintype.card_prod, Fintype.card_fin] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- # Masked sums of bounded registers -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Register + +open Coloring Install Finset +variable {F I J : Type} [Field F] [Fintype I] {m n w : ℕ} + {f g : (I → Bool) → ℕ} + +theorem add (h : Register F w f m) (k : Register F w g n) : + Register F w (fun x => f x + g x) (5 * Fintype.card I + m + n + 10000 * (1 + w)) := by + have t := (BNet.pull (h.add_disjoint k) (Sum.elim id id)) + exact t.mono (by rw [Fintype.card_sum]; omega) + +theorem sum [Fintype J] (f : J → (I → Bool) → ℕ) (h : ∀ j, Register F w (f j) m) : + Register F w (fun x => ∑ j, f j x) + ((1 + Fintype.card J) * (m + 10000 * (Fintype.card I + w + 1))) := by + classical + let M := m + 10000 * (Fintype.card I + w + 1) + suffices ∀ S : Finset J, Register F w (fun x => ∑ j ∈ S, f j x) ((1 + S.card) * M) from this univ + intro S + induction S using Finset.induction_on with + | empty => simpa using (const (F := F) (I := I) (w := w) 0).mono (n := M) (by unfold M; omega) + | insert a S ha ih => + simp only [sum_insert ha, card_insert_of_notMem ha, ← add_assoc, add_mul, one_mul] + refine ((h a).add ih).mono ?_ + rw [add_mul, one_mul] + omega + +theorem mask {p : (I → Bool) → Bool} (hp : BNet F (fun x (_ : Unit) => p x) n) + (h : Register F w f m) : + Register F w (fun x => if p x then f x else 0) + (5 * Fintype.card I + n + m + 100 * (w + 1)) := by + let a (x : Unit ⊕ slots (word w) → Bool) (i : slots (word w)) := + if x (.inl ()) then x (.inr i) else digits w 0 i + have ha : Depends a 2 := by + intro i + refine ⟨{.inl (), .inr i}, by simp, fun x y he => ?_⟩ + simp only [a, he (.inl ()) (by simp), he (.inr i) (by simp)] + have t := (hp.pair h).comp (ha.bnet F) + have he : (a ∘ (fun x => Sum.elim (fun _ : Unit => p x) (digits w (f x)))) = + (fun x => digits w (if p x then f x else 0)) := by + funext x i + cases hc : p x <;> simp [a, hc] + rw [he] at t + apply t.mono + simp only [Fintype.card_sum, Fintype.card_unit, card_slots, wd_word, localCost] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Register +end + +/- +# Programming a vertex by a constant-size truth table + +The fourth address is spare for trivalent vertices. Reading four +addresses per instruction makes the parallel reader a binary tree. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +/-- The data for the rule construction, including `args`, `weight`. -/ +structure Rule (F I : Type) where + /-- The `Rule` component of type `Fin 4 → I`. -/ + args : Fin 4 → I + /-- The weight function carried by `Rule`, with type `(Fin 4 → Bool) → F`. -/ + weight : (Fin 4 → Bool) → F + +namespace Rule + +variable {F I J : Type} + +open Classical in +/-- The value specified by `p.weight (x ∘ p.args)`. -/ +def eval (p : Rule F I) (x : I → Bool) : F := p.weight (x ∘ p.args) + +open Classical in +/-- Uses `⟨a ∘ p.args, p.weight⟩` as the representation. -/ +def reindex (p : Rule F I) (a : I → J) : Rule F J := ⟨a ∘ p.args, p.weight⟩ + +open Classical in +theorem of_local [Fintype J] [Nonempty I] (a : J → I) (h : Fintype.card J ≤ 4) + (k : (J → Bool) → F) : + ∃ p : Rule F I, ∀ x, p.eval x = k (x ∘ a) := by + obtain ⟨e⟩ : Nonempty (J ↪ Fin 4) := Function.Embedding.nonempty_of_card_le (by simpa using h) + let spare := fun _ : Fin 4 => Classical.choice (inferInstance : Nonempty I) + refine ⟨⟨Function.extend e a spare, fun y => k (y ∘ e)⟩, fun x => ?_⟩ + unfold eval + apply congrArg k + funext t + exact congrArg x (e.injective.extend_apply a spare t) + +end Rule + +variable {F I : Type} {a b : Wire} (G : Diagram F a b) + +open Classical in +/-- The addresses of a gate may coincide, even across its two sides. -/ +theorem vertex_rule [Nonempty I] (h : G.Trivalent) + (input : slots a → I) (output : slots b → I) (edge : G.E → I) (v : G.V) : + ∃ p : Rule F I, ∀ x, p.eval x = + G.vertex ((bits a).symm (x ∘ input)) ((bits b).symm (x ∘ output)) (x ∘ edge) v := by + let f : G.Port v → I := + Sum.elim (fun i => Sum.elim input edge (G.src ⟨v, i⟩)) + (fun i => Sum.elim output edge (G.dst ⟨v, i⟩)) + let k (x : G.Port v → Bool) := (G.table v).2.2 + ((bits (G.table v).1).symm (x ∘ Sum.inl)) ((bits (G.table v).2.1).symm (x ∘ Sum.inr)) + have hc : Fintype.card (G.Port v) ≤ 4 := by + rw [Fintype.card_sum, card_slots, card_slots] + exact (h v).trans (by decide) + obtain ⟨p, hp⟩ := Rule.of_local f hc k + refine ⟨p, fun x => ?_⟩ + rw [hp, Diagram.vertex, Equiv.apply_symm_apply, Equiv.apply_symm_apply] + unfold k f + apply congrArg₂ (G.table v).2.2 + · apply congrArg (bits (G.table v).1).symm + funext i + simp only [Function.comp_apply, Sum.elim_inl] + cases G.src ⟨v, i⟩ <;> rfl + · apply congrArg (bits (G.table v).2.1).symm + funext i + simp only [Function.comp_apply, Sum.elim_inr] + cases G.dst ⟨v, i⟩ <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Trivalent diagrams as lists of local instructions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Finset +variable {F J A B : Type} [Field F] [Fintype A] [Fintype B] + +open Classical in +private theorem extra_rules [Nonempty J] (p : A → Rule F J) (h : Fintype.card A ≤ Fintype.card B) : + ∃ q : B → Rule F J, ∀ x, ∏ i, (q i).eval x = ∏ i, (p i).eval x := by + obtain ⟨e⟩ := Function.Embedding.nonempty_of_card_le h + let one : Rule F J := ⟨fun _ => choice inferInstance, fun _ => 1⟩ + let q := Function.extend e p (fun _ => one) + refine ⟨q, fun x => ?_⟩ + rw [prod_padded e _ (fun j hj => by + rw [show q j = one from Function.extend_apply' _ _ _ hj] + rfl)] + simp only [q, e.injective.extend_apply] + +open Classical in +/-- One half of the instructions represents vertices. The other half +pins private bits beyond the last internal edge. Both sets of external +slots may refer to any visible data positions. -/ +theorem compile {a b : Wire} (G : Diagram F a b) (h : G.Trivalent) + [DecidableEq B] [Nonempty B] (src : slots a → B) (dst : slots b → B) + (hv : Fintype.card G.V ≤ Fintype.card B) (he : Fintype.card G.E ≤ Fintype.card B) : + ∃ p : B ⊕ B → Rule F (B ⊕ B), ∀ x : B → Bool, + (∑ y : B → Bool, ∏ i, (p i).eval (Sum.elim x y)) = + G.eval ((bits a).symm (x ∘ src)) ((bits b).symm (x ∘ dst)) := by + obtain ⟨e⟩ := Function.Embedding.nonempty_of_card_le he + choose p hp using vertex_rule (I := B ⊕ B) G h (Sum.inl ∘ src) (Sum.inl ∘ dst) (Sum.inr ∘ e) + obtain ⟨q, hq⟩ := extra_rules p hv + let pin (j : B) : Rule F (B ⊕ B) := ⟨fun _ => .inr j, fun v => unused e j (v 0)⟩ + refine ⟨Sum.elim q pin, fun x => ?_⟩ + have ht (y : B → Bool) : + (∏ i, ((Sum.elim q pin) i).eval (Sum.elim x y)) = + (∏ i, G.vertex ((bits a).symm (x ∘ src)) ((bits b).symm (x ∘ dst)) (y ∘ e) i) * + ∏ j, unused e j (y j) := by + rw [Fintype.prod_sum_type] + simp only [Sum.elim_inl, Sum.elim_inr, hq, hp] + rfl + simp_rw [ht] + exact sum_padded e (fun z => ∏ i, G.vertex ((bits a).symm (x ∘ src)) ((bits b).symm (x ∘ dst)) z + i) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- +# Feasibility of reported selector counts + +A class can realize prescribed multiplicities exactly when their sum +equals the size of the class. Combining the classes and checking the +choice of cut then characterizes the reports of actual assignments. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Classical in +private theorem prescribe {P I : Type} [Fintype P] [Fintype I] [DecidableEq I] (m : I → ℕ) : + (∑ i, m i) = Fintype.card P ↔ ∃ s : P → I, ∀ i, multiplicity s i = m i := by + constructor + · intro h + let e : P ≃ (Σ i, Fin (m i)) := Fintype.equivOfCardEq (by simp [h]) + refine ⟨fun p => (e p).1, fun i => ?_⟩ + let f : {v : (Σ i, Fin (m i)) // v.1 = i} ≃ Fin (m i) := + { toFun := fun v => v.property ▸ v.val.2 + invFun := fun j => ⟨⟨i, j⟩, rfl⟩ + left_inv := by rintro ⟨⟨j, x⟩, rfl⟩; rfl + right_inv := fun _ => rfl } + let e' : {p // (e p).1 = i} ≃ Fin (m i) := + (e.subtypeEquiv (fun _ => Iff.rfl)).trans f + exact (Fintype.card_congr e').trans (Fintype.card_fin _) + · rintro ⟨s, hs⟩ + simp only [← hs, multiplicity, ← Fintype.card_sigma] + exact Fintype.card_congr (Equiv.sigmaFiberEquiv s) + +variable {F : Type} [Field F] {n h d r : ℕ} (A : Expansion F n h) + (hn : 2 ≤ n) (R : A.Report r d) + +open Classical in +/-- The condition `∀ c, ∑ i, (R.2 (c, i)).val = Fintype.card (A.Members hn R c)` on the +specified data. -/ +def feasible : Prop := + ∀ c, ∑ i, (R.2 (c, i)).val = Fintype.card (A.Members hn R c) + +open Classical in +theorem feasible_selectors : + A.feasible hn R ↔ ∀ c, Nonempty (A.Selectors hn R c) := by + unfold feasible + apply forall_congr' + intro c + rw [prescribe] + exact ⟨fun ⟨s, hs⟩ => ⟨⟨s, hs⟩⟩, fun ⟨s⟩ => ⟨s.val, s.property⟩⟩ + +open Classical in +theorem feasible_valid : A.feasible hn R ∧ A.valid hn R ↔ ∃ s, R = A.report hn s := by + rw [A.feasible_selectors] + constructor + · rintro ⟨hf, hv⟩ + let t := fun c => (hf c).some + let e := ((Equiv.sigmaFiberEquiv (packetClass (d := d) (r := r) hn R.1)).symm.arrowCongr + (Equiv.refl A.I)).trans (Equiv.piCurry (fun _ _ => A.I)) + obtain ⟨s, hs⟩ := e.surjective (fun c => (t c).val) + refine ⟨s, (A.checks_iff hn R s).mp ⟨hv, (A.counts_match hn R s).mp ?_⟩⟩ + intro c z + change multiplicity (e s c) z = _ + rw [hs] + exact (t c).property z + · rintro ⟨s, hs⟩ + obtain ⟨hv, hc⟩ := (A.checks_iff hn R s).mpr hs + exact ⟨fun c => ⟨⟨fun p => s p.1, (A.counts_match hn R s).mpr hc c⟩⟩, hv⟩ + +open Classical in +theorem feasible_symbols (N : ℕ) {T : Type} : + A.feasible hn R ↔ Nonempty ((e : T ⊕ Edge n r d h) → A.ExtraSymbol hn N R e) := by + rw [A.feasible_selectors] + constructor + · intro hs + refine ⟨?_⟩ + rintro (p|p|c) + · exact false + · exact false + · exact ⟨(hs c).some, fun _ _ => false⟩ + · rintro ⟨x⟩ c + exact ⟨(x (.inr (.inr c))).1⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +/- +# Checking a public report from its binary counts + +Check the class sizes and the minimizing coordinate. These checks force +the counts into range and identify an actual report, so the budget +follows from the bound for genuine assignments. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Finset +variable {F : Type} [Field F] {n h r d : ℕ} (A : Expansion F n h) (hn : 2 ≤ n) + +/-- The indexed operation `Processor.number (fun j => x (z, j))`. -/ +def cnt (x : A.CountBit r d → Bool) (z : Class r × A.I) := + Processor.number (fun j => x (z, j)) + +/-- The defining condition `(∀ c, ∑ z, A.cnt x (c, z) = Fintype.card {p : Packet n r d // +packetClass hn i p = c}) ∧ i = first hn (fun j => ∑ z, A.cnt x z * A.cross z.2 j)`. -/ +def guard (i : Fin n) (x : A.CountBit r d → Bool) : Prop := + (∀ c, ∑ z, A.cnt x (c, z) = Fintype.card {p : Packet n r d // packetClass hn i p = c}) ∧ + i = first hn (fun j => ∑ z, A.cnt x z * A.cross z.2 j) + +@[simp] theorem cnt_countBits (R : A.Report r d) (z : Class r × A.I) : + A.cnt (A.countBits R) z = (R.2 z).val := + Processor.number_test _ ((R.2 z).isLt.trans_le (Nat.le_pow_clog (by decide) _)) + +private theorem guard_report (R : A.Report r d) : + A.guard hn R.1 (A.countBits R) ↔ A.feasible hn R ∧ A.valid hn R := by + simp only [guard, cnt_countBits, feasible, valid, total, Members] + +theorem guard_iff (N : ℕ) + (hbudget : ∀ s : Packet n r d → A.I, A.budget hn N (A.report hn s)) + (i : Fin n) (x : A.CountBit r d → Bool) : + A.guard hn i x ↔ ∃ R : A.Accepted (r := r) (d := d) hn (A.budget hn N), + A.feasible hn R.val ∧ R.val.1 = i ∧ A.countBits R.val = x := by + constructor + · intro hx + have small (z : Class r × A.I) : A.cnt x z < Fintype.card (Packet n r d) + 1 := by + apply Nat.lt_succ_of_le + calc + A.cnt x z ≤ ∑ j, A.cnt x (z.1, j) := + single_le_sum (f := fun j => A.cnt x (z.1, j)) (fun _ _ => Nat.zero_le _) (mem_univ z.2) + _ = _ := hx.1 z.1 + _ ≤ _ := Fintype.card_subtype_le _ + let R : A.Report r d := (i, fun z => ⟨A.cnt x z, small z⟩) + have he : A.countBits R = x := by + funext ⟨z, j⟩ + exact Processor.test_number (fun k => x (z, k)) j + have hh := (A.guard_report hn R).mp (he.symm ▸ hx) + obtain ⟨s, hs⟩ := (A.feasible_valid hn R).mp hh + exact ⟨⟨R, hh.2, hs.symm ▸ hbudget s⟩, hh.1, rfl, he⟩ + · rintro ⟨R, hf, rfl, rfl⟩ + exact (A.guard_report hn R.val).mpr ⟨hf, R.property.1⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +section +/- +# A programmable product of local weights + +A common array stores the data bits. Each row supplies a descriptor and +four addresses in the array. Four batches of indirect reads deliver +the arguments to independent copies of the local table. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Install +variable {F C : Type} [Field F] + +/-- Indexes the ports by the coordinates of `Fin (2 ^ w) ⊕ (Fin 4 × Fin (2 ^ w) × slots (word +w)) ⊕ (Fin (2 ^ w) × C)`. -/ +abbrev Ports (C : Type) (w : ℕ) := + Fin (2 ^ w) ⊕ (Fin 4 × Fin (2 ^ w) × slots (word w)) ⊕ (Fin (2 ^ w) × C) + +/-- The indexed operation `∏ i : Fin (2 ^ w), g (fun c => x (.inr (.inr (i, c)))) (fun k => x +(.inl (Control.decode w (fun j => x (.inr (.inl (k, i, j)))))))`. -/ +def evaluate (g : (C → Bool) → (Fin 4 → Bool) → F) (w : ℕ) (x : Ports C w → Bool) : F := + ∏ i : Fin (2 ^ w), g (fun c => x (.inr (.inr (i, c)))) + (fun k => x (.inl (Control.decode w (fun j => x (.inr (.inl (k, i, j))))))) + +/-- The quantity computed by `50000 + 4 * Fintype.card C + 8 * 2 ^ (4 + Fintype.card C)`. -/ +def cost (C : Type) [Fintype C] := 50000 + 4 * Fintype.card C + 8 * 2 ^ (4 + Fintype.card C) + +theorem evaluate_net [Fintype C] (g : (C → Bool) → (Fin 4 → Bool) → F) (w : ℕ) : + Weight F (evaluate g w) (cost C * 2 ^ w * (w + 1) ^ 3) := by + let I := Fin (2 ^ w) + have reads := BNet.family 2 (fun _ => Control.read w) (fun _ => Control.read_net F w) + let dup : (Fin 4 × (I ⊕ I × slots (word w))) ⊕ (I × C) → Ports C w + | .inl (_, .inl i) => .inl i + | .inl (k, .inr p) => .inr (.inl (k, p)) + | .inr p => .inr (.inr p) + have gather := (reads.parallel (BNet.id F (I × C))).pull dup + have table := Weight.dense F (Fin 4 ⊕ C) (fun x => g (x ∘ Sum.inr) (x ∘ Sum.inl)) + let e := (Equiv.prodSumDistrib I (Fin 4) C).trans + ((Equiv.prodComm I (Fin 4)).sumCongr (.refl _)) + apply (gather.weight ((table.prod w).rename e)).mono + simp only [I, Ports, cost, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + card_slots, wd_word] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- +# A binary program for a finite-field table network + +For each of the sixteen possible argument strings a descriptor has one +bit per field element. A valid program sets just the bit corresponding +to the desired weight. Even arbitrary descriptor bits have a well-defined +interpretation, the sum of the selected field elements. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +/-- Indexes the descriptor by the coordinates of `(Fin 4 → Bool) × F`. -/ +abbrev Descriptor (F : Type) := (Fin 4 → Bool) × F + +/-- Indexes the script by the coordinates of `(Fin 4 × Fin (2 ^ w) × slots (word w)) ⊕ (Fin (2 ^ +w) × Descriptor F)`. -/ +abbrev Script (F : Type) (w : ℕ) := + (Fin 4 × Fin (2 ^ w) × slots (word w)) ⊕ (Fin (2 ^ w) × Descriptor F) + +theorem card_script (F : Type) [Fintype F] (w : ℕ) : + Fintype.card (Script F w) = 2 ^ w * (4 * w + 16 * Fintype.card F) := by + simp [Script, Descriptor] + ring + +/-- In the case `.inl (k, i, j)`, this construction gives `(Control.decode w).symm ((P i).args +k) j`. -/ +def program (F : Type) [DecidableEq F] (w : ℕ) (P : Fin (2 ^ w) → Rule F (Fin (2 ^ w))) : + Script F w → Bool + | .inl (k, i, j) => (Control.decode w).symm ((P i).args k) j + | .inr (i, t, z) => decide ((P i).weight t = z) + +/-- The indexing data represented by `evaluate (fun (d : Descriptor F → Bool) t => ∑ z, if d (t, +z) then z else 0) w`. -/ +def run (F : Type) [Field F] [Fintype F] (w : ℕ) : (Fin (2 ^ w) ⊕ Script F w → Bool) → F := + evaluate (fun (d : Descriptor F → Bool) t => ∑ z, if d (t, z) then z else 0) w + +theorem run_program {F : Type} [Field F] [Fintype F] [DecidableEq F] {w : ℕ} + (P : Fin (2 ^ w) → Rule F (Fin (2 ^ w))) (x : Fin (2 ^ w) → Bool) : + run F w (Sum.elim x (program F w P)) = ∏ j, (P j).eval x := by + simp only [run, evaluate, Sum.elim_inl, Sum.elim_inr, program, Equiv.apply_symm_apply, + decide_eq_true_eq, Finset.sum_ite_eq, Finset.mem_univ, ite_true, Rule.eval, Function.comp_def] + +theorem run_net (F : Type) [Field F] [Fintype F] (w : ℕ) : + Install.Weight F (run F w) (cost (Descriptor F) * 2 ^ w * (w + 1) ^ 3) := + evaluate_net _ w + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- +# Repeated programmable contractions + +The two halves of a data array hold exterior and private bits. Each +copy sums its private bits independently. The script is shared. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Install + +/-- Reindexes `Fin (2 ^ w) ⊕ Fin (2 ^ w)` and `Fin (2 ^ (w + 1))` by an equivalence. -/ +def dataSlots (w : ℕ) : Fin (2 ^ w) ⊕ Fin (2 ^ w) ≃ Fin (2 ^ (w + 1)) := + finSumFinEquiv.trans (finCongr (by rw [pow_succ, mul_two])) + +/-- Chooses the operation for the left or right summand. -/ +def data (w : ℕ) (x y : Fin (2 ^ w) → Bool) : Fin (2 ^ (w + 1)) → Bool := + Sum.elim x y ∘ (dataSlots w).symm + +variable (F : Type) [Field F] [Fintype F] + +/-- The sum of `run F (w + 1) (Sum.elim (data w (s ∘ Sum.inl) t) (s ∘ Sum.inr))` indexed by `t : +Fin (2 ^ w) → Bool`. -/ +def template (w : ℕ) (s : Fin (2 ^ w) ⊕ Script F (w + 1) → Bool) : F := + ∑ t : Fin (2 ^ w) → Bool, run F (w + 1) (Sum.elim (data w (s ∘ Sum.inl) t) (s ∘ Sum.inr)) + +private def reorder (X Y : Type) : (X ⊕ X) ⊕ Y ≃ (X ⊕ Y) ⊕ X := + (Equiv.sumAssoc _ _ _).trans + (((Equiv.refl X).sumCongr (Equiv.sumComm _ _)).trans (Equiv.sumAssoc _ _ _).symm) + +theorem template_net (w : ℕ) : + Weight F (template F w) (cost (Descriptor F) * 2 ^ (w + 1) * (w + 2) ^ 3 + 2 ^ w) := by + let e := ((dataSlots w).symm.sumCongr (.refl (Script F (w + 1)))).trans (reorder _ _) + have h := ((run_net F (w + 1)).rename e).sum_right + rw [Fintype.card_fin] at h + convert h using 1 + funext s + apply Finset.sum_congr rfl + intro t _ + apply congrArg + funext k + rcases k with i | i + · change Sum.elim (s ∘ Sum.inl) t ((dataSlots w).symm i) = + Sum.elim s t (reorder _ _ (.inl ((dataSlots w).symm i))) + cases (dataSlots w).symm i <;> rfl + · rfl + +/-- The indexed operation `∏ i, template F w (Sum.elim (fun k => x (.inl (i, k))) (x ∘ +Sum.inr))`. -/ +def repeated (w j : ℕ) (x : (Fin (2 ^ j) × Fin (2 ^ w)) ⊕ Script F (w + 1) → Bool) : F := + ∏ i, template F w (Sum.elim (fun k => x (.inl (i, k))) (x ∘ Sum.inr)) + +/-- The quantity computed by `2 * cost (Descriptor F) + 128 * (1 + Fintype.card F)`. -/ +def templateCost := 2 * cost (Descriptor F) + 128 * (1 + Fintype.card F) + +theorem repeated_net (w j : ℕ) : + Weight F (repeated F w j) (templateCost F * 2 ^ j * 2 ^ w * (w + 2) ^ 3) := by + let A := Fin (2 ^ j) + let X := Fin (2 ^ w) + let Y := Script F (w + 1) + let addr : A × (X ⊕ Y) → (A × X) ⊕ Y + | (i, .inl k) => .inl (i, k) + | (_, .inr k) => .inr k + have h := ((template_net F w).prod j).pull addr + have he (x : (A × X) ⊕ Y → Bool) (i : A) : + (fun k => (x ∘ addr) (i, k)) = Sum.elim (fun k => x (.inl (i, k))) (x ∘ Sum.inr) := by + funext k + cases k <;> rfl + rw [show repeated F w j = (fun x => ∏ i, template F w (fun k => (x ∘ addr) (i, k))) from + funext fun x => Finset.prod_congr rfl (fun i _ => congrArg _ (he x i).symm)] + apply h.mono + dsimp only [A, X, Y] + rw [Fintype.card_sum, Fintype.card_prod, card_script, Fintype.card_prod, Fintype.card_sum, + card_script, Fintype.card_fin, Fintype.card_fin] + have hp : 1 ≤ 2 ^ j := Nat.one_le_pow _ _ (by decide) + let S := 2 ^ (w + 1) * (4 * (w + 1) + 16 * Fintype.card F) + calc + _ ≤ 3 * 2 ^ j * (2 ^ w + S) + 2 ^ j * (cost (Descriptor F) * 2 ^ (w + 1) * (w + 2) ^ 3 + 2 ^ w) + := by + have hs := Nat.le_mul_of_pos_left S hp + unfold S at hs ⊢ + nlinarith only [hs] + _ = (2 ^ j * 2 ^ w) * (4 + 24 * (w + 1) + 96 * Fintype.card F + 2 * cost (Descriptor F) * (w + + 2) ^ 3) := by + unfold S + rw [pow_succ] + ring + _ ≤ (2 ^ j * 2 ^ w) * (templateCost F * (w + 2) ^ 3) := by + apply Nat.mul_le_mul_left + unfold templateCost + have hw : w + 2 ≤ (w + 2) ^ 3 := Nat.le_pow (by decide) + have hf := Nat.mul_le_mul_left (Fintype.card F) (by omega : 1 ≤ (w + 2) ^ 3) + nlinarith only [hw, hf] + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- +# Programming a network template + +One script records the wiring and coefficients of a trivalent network. +The script is independent of the values at all visible positions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Finset +variable {F : Type} [Field F] [Fintype F] {a b : Wire} {w m : ℕ} + +open Classical in +theorem template_program {k : Val a → Val b → F} (h : Net F a b k m) + (hm : 2 * m ≤ 2 ^ w) (src : slots a → Fin (2 ^ w)) (dst : slots b → Fin (2 ^ w)) : + ∃ code, ∀ x : Fin (2 ^ w) → Bool, + template F w (Sum.elim x code) = k ((bits a).symm (x ∘ src)) ((bits b).symm (x ∘ dst)) := by + obtain ⟨G, rfl, ht, hcard⟩ := h.diagram + have hc := G.cost_trivalent ht + rw [Diagram.cost_eq, hcard] at hc + obtain ⟨p, hp⟩ := compile G ht src dst (by rw [Fintype.card_fin]; omega) + (by rw [Fintype.card_fin]; omega) + let e := dataSlots w + let q i := (p (e.symm i)).reindex e + refine ⟨program F (w + 1) q, fun x => ?_⟩ + rw [← hp] + unfold template + apply sum_congr rfl + intro y _ + change run F (w + 1) (Sum.elim (data w x y) (program F (w + 1) q)) = _ + rw [run_program, ← e.prod_comp] + apply prod_congr rfl + intro i _ + simp only [q, Rule.reindex, Rule.eval, data, e, Function.comp_def, Equiv.symm_apply_apply] + +open Classical in +/-- In particular any bounded weighted circuit on named input bits can +be evaluated repeatedly without duplicating its program input. -/ +theorem weight_program {I : Type} [Finite I] {f : (I → Bool) → F} + (hf : Install.Weight F f m) (hm : 2 * m ≤ 2 ^ w) (src : I → Fin (2 ^ w)) : + ∃ code, ∀ x : Fin (2 ^ w) → Bool, template F w (Sum.elim x code) = f (x ∘ src) := by + let : Fintype I := Fintype.ofFinite I + let e : I ≃ slots (word (Fintype.card I)) := Fintype.equivOfCardEq (by simp) + obtain ⟨v, hv, net⟩ := hf _ e + obtain ⟨code, hcode⟩ := template_program net ((Nat.mul_le_mul_left 2 hv).trans hm) + (src ∘ e.symm) Empty.elim + refine ⟨code, fun x => ?_⟩ + simpa only [Function.comp_def, Equiv.apply_symm_apply, Equiv.symm_apply_apply] using hcode x + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Handle.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Handle.lean new file mode 100644 index 0000000000..32f377d85e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Handle.lean @@ -0,0 +1,960 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.LocalBank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.FetchSlot +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Capacity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.PinIndexRead +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Slots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Vector.Cases + +/-! # A worker as a sum over local bits and independent class kernels -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal +variable {F : Type} [Field F] [Fintype F] {N l n d r h B : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) + +open Classical in +private def localCoeff (v : Local s) := + Encoded.localize (source s) (target s) (A.ExtraSymbol hn N s.report.1) + (fun j x => C.joint s.report s.script (C.code (some (s.site, + s.script))) ((Worker.index r).symm j) + (fun e => x (.inl e)) (fun e => x (.inr e))) s.site v + +open Classical in +private theorem localCoeff_eq (hw : P.which = (Format.prescribed d h P.count P.colors).which) + (x : LocalBit s → Bool) (z : Symbols s) : + C.localCoeff s (localEquiv s (x, z)) = + Pin.mask F (workerAt s) (C.code (some (s.site, s.script))) (localPins s x) * + (M.result F (Sum.elim (C.bankData s x) s.script) * A.factor (localAssignment s x z) + (workerAt s)) := by + unfold localCoeff Encoded.localize + rw [dite_eq_left (symbols_exist s)] + exact C.joint_eq s hw x z + +open Classical in +private theorem site_local : + C.site s.site s.script s.report s.physical = + if C.relay s then ∑ v : Local s, if C.Received s v then C.localCoeff s v else 0 else 0 := by + unfold site Expansion.extraProcessor + rw [Encoded.worker_eq] + apply if_congr + · exact Iff.rfl + · refine Finset.sum_congr ?_ ?_ + · ext; simp + intro z _ + exact if_congr Iff.rfl rfl rfl + · rfl + +open Classical in +/-- After the relay check, sum over just the incident bit symbols. The +packet batch includes the private sums for all incident class symbols. -/ +theorem site_eq (hw : P.which = (Format.prescribed d h P.count P.colors).which) : + C.site s.site s.script s.report s.physical = + if C.relay s then ∑ x : LocalBit s → Bool, if C.Matches s x then + Pin.mask F (workerAt s) (C.code (some (s.site, s.script))) (localPins s x) * + (M.result F (Sum.elim (C.bankData s x) s.script) * PacketKernel.batch A i (C.frames s x)) + else 0 else 0 := by + rw [C.site_local s] + split_ifs + · rw [← (localEquiv s).sum_comp, Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro x _ + simp only [C.received_split, C.localCoeff_eq s hw, C.batch_frames] + by_cases he : C.Matches s x + · simp only [he, true_and, ite_true, Finset.mul_sum, mul_ite, mul_zero] + · simp only [he, false_and, ite_false, Finset.sum_const_zero] + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- +# Fixed station data cells + +Every potential cell has the same address at all workers. At the end +of the array, reserve the full exterior color-slice capacity, so a +worker with fewer exterior ports simply leaves more cells unused. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells + +open Diagonal +variable {N l n d r h : ℕ} (P : Format N l d n r h) + (hn : 2 ≤ n) (i : Fin n) (g : Fin r) + +open Classical in +/-- Indexes the domain by the coordinates of `Fin (r ^ n / r) ⊕ SlotKey.Domain n r P.count h ⊕ +(Fin (4 * N / r) × Fin d)`. -/ +abbrev Domain := Fin (r ^ n / r) ⊕ SlotKey.Domain n r P.count h ⊕ (Fin (4 * N / r) × Fin d) + +open Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def labels : Fin (r ^ n / r) ≃ {z : Label n r // z i = g} := + Fintype.equivOfCardEq (by + rw [Fintype.card_fin, ← label_uniform i g, Nat.mul_div_cancel _ g.pos] + rfl) + +open Classical in +/-- Resolve a template address before applying the activation mask. -/ +def read : Domain P → Option (Tape N l d n r h P.count) + | .inl s => some (.inl (labels i g s).val) + | .inr (.inl s) => some (.inr (.inl (SlotKey.expand hn i (.home g) s))) + | .inr (.inr (j, k)) => (PinIndex.readPort P.colors i g j).map (fun t => + .inr (.inr (.inl ((port (Machine.tape N l l) d).symm (k, (Machine.address N l l).symm t))))) + +variable (he : P.which = (Format.prescribed d h P.count P.colors).which) + (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) + +open Classical in +/-- In the case `⟨.inl z, hz⟩`, this construction gives `.inl ((labels i g).symm ⟨z, by rw [he] +at hz; exact hz⟩)`. -/ +def write : P.LocalTape i g → Domain P + | ⟨.inl z, hz⟩ => .inl ((labels i g).symm ⟨z, by rw [he] at hz; exact hz⟩) + | ⟨.inr (.inl s), hs⟩ => + let k : SlotKey.Visible hn i (.home g) := ⟨SlotKey.key s, by rw [he] at hs; exact hs⟩ + .inr (.inl ((SlotKey.enumerate hn i (.home g)).symm k, s.1.1.2, s.1.2.2)) + | ⟨.inr (.inr (.inl j)), hj⟩ => + let p := port (Machine.tape N l l) d j + let t : PinIndex.Selected P.colors i g := ⟨Machine.address N l l p.2, + by rw [he] at hj; exact hj⟩ + .inr (.inr (PinIndex.portIndex _ hf i g t, p.1)) + | ⟨.inr (.inr (.inr j)), _⟩ => (port .unit d j).2.elim + +open Classical in +theorem read_write (t : P.LocalTape i g) : + read P hn i g (write P hn i g he hf t) = some t.val := by + rcases t with ⟨z|⟨p, b⟩|j|j, ht⟩ + · simp only [read, write, Equiv.apply_symm_apply] + · simp only [read, write, SlotKey.expand, Equiv.apply_symm_apply] + rfl + · simp only [read, write, PinIndex.readPort_index, Option.map_some, Equiv.symm_apply_apply, + Prod.mk.eta] + · exact (port .unit d j).2.elim + +open Classical in +/-- Embeds `P.LocalTape i g` into `Domain P`. -/ +def encode : P.LocalTape i g ↪ Domain P := + ⟨write P hn i g he hf, fun x y h => Subtype.ext <| Option.some.inj <| + (read_write P hn i g he hf x).symm.trans ((congrArg (read P hn i g) h).trans + (read_write P hn i g he hf y))⟩ + +open Classical in +theorem read_hit (q : Domain P) {t} (ht : read P hn i g q = some t) : + ∃ v, (encode P hn i g he hf v = q) ∧ v.1 = t := by + rcases q with s | k | ⟨j, k⟩ + · obtain rfl := Option.some.inj ht + refine ⟨⟨_, by rw [he]; exact (labels i g s).2⟩, ?_, rfl⟩ + change Sum.inl ((labels i g).symm (labels i g s)) = _ + rw [Equiv.symm_apply_apply] + · obtain rfl := Option.some.inj ht + refine ⟨⟨_, by rw [he]; exact (SlotKey.enumerate hn i (.home g) k.1).2⟩, ?_, rfl⟩ + change Sum.inr (Sum.inl (((SlotKey.enumerate hn i (.home g)).symm + (SlotKey.enumerate hn i (.home g) k.1)), k.2)) = _ + rw [Equiv.symm_apply_apply] + · obtain ⟨p, hp, rfl⟩ := Option.map_eq_some_iff.mp ht + have hh : P.colors p i = g := by + unfold PinIndex.readPort at hp + split at hp + · rw [← Option.some.inj hp] + rename_i hj + exact ((Fintype.equivFin (PinIndex.Selected P.colors i g)).symm ⟨j.val, hj⟩).2 + · contradiction + have hi := PinIndex.index_readPort P.colors hf i g ⟨p, hh⟩ j hp + let v : P.LocalTape i g := ⟨.inr (.inr (.inl + ((port (Machine.tape N l l) d).symm (k, (Machine.address N l l).symm p)))), by + rw [he] + simpa only [Format.prescribed, Equiv.apply_symm_apply] using hh⟩ + have hv : write P hn i g he hf v = .inr (.inr (j, k)) := by + simp only [v, write, Equiv.apply_symm_apply, hi] + exact ⟨v, hv, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +end + +/- # Decoding template addresses into the common cell format -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +open Diagonal + +variable {N l n d r h : ℕ} {P : Format N l d n r h} {M : Bank (Fin n)} + +open Classical in +/-- The condition `∀ i, Domain P ↪ Fin (2 ^ M.width i)` on the specified data. -/ +abbrev Address (P : Format N l d n r h) (M : Bank (Fin n)) := + ∀ i, Domain P ↪ Fin (2 ^ M.width i) + +variable (hn : 2 ≤ n) (he : P.which = (Format.prescribed d h P.count P.colors).which) + (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) (addr : Address P M) + +open Classical in +/-- Maps the coordinate `i g` to `(encode P hn i g he hf).trans (addr i)`. -/ +def index : P.Index M := fun i g => (encode P hn i g he hf).trans (addr i) + +open Classical in +/-- Unused bank addresses have no corresponding input cell. -/ +def lookup (i : Fin n) := Function.extend (addr i) some (fun _ => none) + +open Classical in +private theorem expand (i : Fin n) (g : Fin r) (k : Fin (2 ^ M.width i)) + (f : Tape N l d n r h P.count → Bool) : + Function.extend (index hn he hf addr i g) (fun t => f t.val) (fun _ => false) k = + ((lookup addr i k).bind (read P hn i g)).any f := by + by_cases hq : ∃ q, addr i q = k + · obtain ⟨q, rfl⟩ := hq + rw [lookup, (addr i).injective.extend_apply, Option.bind_some] + cases hq : read P hn i g q with + | none => + apply Function.extend_apply' + rintro ⟨v, hv⟩ + have ht := (addr i).injective hv + change write P hn i g he hf v = q at ht + rw [← ht, read_write] at hq + contradiction + | some t => + obtain ⟨v, rfl, rfl⟩ := read_hit P hn i g he hf q hq + exact (index hn he hf addr i g).injective.extend_apply (fun x => f x.val) (fun _ => false) v + · rw [lookup, Function.extend_apply' _ _ _ hq, Option.bind_none] + apply Function.extend_apply' + exact fun ⟨v, hv⟩ => hq ⟨_, hv⟩ + +variable {F : Type} [Field F] [Fintype F] {A : Expansion F n h} {B : ℕ} + (C : Controller P A hn M B) + +open Classical in +/-- Uses `{ C with index := index hn he hf addr }` as the representation. -/ +def install : Controller P A hn M B := { C with index := index hn he hf addr } + +open Controller +variable {i : Fin n} (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) + (x : LocalBit s → Bool) + +open Classical in +/-- The probe used in the `Cells` construction. -/ +def probe (j : Fin B) (v : Domain P) := + (read P hn (PinIndex.axis s) (PinIndex.symbol s) v).any (fun t => + if A.owner hn N s.report.val (P.which t) = workerAt s then + P.raw A hn B s.report (localRows s x) (Pin.input C.pad (localPins s x)) (workerAt s) j t + else false) + +open Classical in +theorem bank_read (hc : C.index = index hn he hf addr) (k : M.Data) : + C.bankData s x k = if hv : k.2.1.val < B ∧ k.1 = PinIndex.axis s then + (lookup addr k.1 k.2.2).any (probe hn C s x ⟨k.2.1.val, hv.1⟩) + else false := by + unfold bankData Format.fill + have hax : Layout.axis hn s.report.val.1 (workerAt s) = PinIndex.axis s := + congrArg (fun i => Layout.axis hn i (workerAt s)) s.cut + simp only [hc, hax] + by_cases hv : k.2.1.val < B ∧ k.1 = PinIndex.axis s + · rw [dite_eq_left hv, dite_eq_left hv] + let f t := if A.owner hn N s.report.val (P.which t) = workerAt s then + P.raw A hn B s.report (localRows s x) (Pin.input C.pad (localPins s x)) + (workerAt s) ⟨k.2.1.val, hv.1⟩ t else false + refine (expand hn he hf addr k.1 (PinIndex.symbol s) k.2.2 f).trans ?_ + cases lookup addr k.1 k.2.2 with + | none => rfl + | some v => + exact congrArg (fun t => (read P hn t (PinIndex.symbol s) v).any f) hv.2 + · rw [dite_eq_right hv, dite_eq_right hv] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +end + +/- # Resolving the three kinds of bank input cells -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells + +open Diagonal Controller +variable {F : Type} [Field F] [Fintype F] {N l d B n r h : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} + (he : P.which = (Format.prescribed d h P.count P.colors).which) + (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i +local notation "Y" => WithGuess P A hn M B i + +open Classical in +/-- Tests whether `A.owner hn N s.report.1 z = workerAt s` holds. -/ +def owns (s : X) (z : Label n r) := decide (A.owner hn N s.report.1 z = workerAt s) + +open Classical in +/-- The slot of type `Position n r (B * P.count) h × Bool` for the given inputs. -/ +def slot (s : X) (j : Fin B) (p : SlotKey.Domain n r P.count h) : Position n r (B * P.count) h × + Bool := + let k := SlotKey.enumerate hn (PinIndex.axis s) (.home (PinIndex.symbol s)) p.1 + SlotKey.atRow k.val (finProdFinEquiv (j, p.2.1)) p.2.2 + +open Classical in +/-- In the case `.inl k`, this construction gives `owns z.1 (labels (PinIndex.axis z.1) +(PinIndex.symbol z.1) k).val`. -/ +def value (z : Y) (j : Fin B) : Domain P → Bool + | .inl k => owns z.1 (labels (PinIndex.axis z.1) (PinIndex.symbol z.1) k).val + | .inr (.inl v) => + let t := slot z.1 j v + if owns z.1 (Expansion.endpoint t.1 t.2) then + fullBit z.1 (z.2 ∘ gather hf z.1) (.inr t) else false + | .inr (.inr (k, t)) => PinIndex.read hf z k.val (finProdFinEquiv (j, t)).val + +open Classical in +private theorem pad_zero (k : slots (Machine.tape N l l)) : + bits (Machine.tape N l l) C.pad k = false := by + rw [Controller.pad, Machine.bits_feed] + rcases Machine.address N l l k with s|s|s <;> simp [Controller.code] + +include he in +open Classical in +theorem probe_value (z : Y) (j : Fin B) (v : Domain P) : + probe hn C z.1 (z.2 ∘ gather hf z.1) j v = value hf z j v := by + unfold probe + rw [he] + rcases v with k | q | ⟨k, t⟩ + · simp only [value, read, Option.any_some, Format.prescribed, Format.raw, owns] + have ha (p : Prop) [Decidable p] : (if p then decide p else false) = decide p + := by by_cases hp : p <;> simp [hp] + exact ha _ + · simp only [value, read, Option.any_some, Format.prescribed, Format.raw, owns, decide_eq_true_eq] + rfl + · simp only [value, read, PinIndex.read, PinIndex.readPort] + split + · rename_i hk + simp only [Option.map_some, Option.any_some, Format.prescribed, Equiv.apply_symm_apply, + Format.raw] + simp only [Pin.input, Machine.inputs, bits_bundle, Equiv.apply_symm_apply, Machine.padded] + split_ifs with h₁ h₂ + all_goals + first + | rfl + | solve | simp only [Machine.bits_feed, Equiv.apply_symm_apply, PinIndex.value] + | exact pad_zero C _ + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +end + +/- # Reading the fixed array of packet inputs at a selected class -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l n d r h B w : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +open Classical in +private abbrev Col (n r : ℕ) := + PacketKernel.Spot r × Fin (PacketKernel.templates n r) × Spectral.Cube n × Bool + +open Classical in +private theorem col_card (hr : 3 ≤ r) : Fintype.card (Col n r) ≤ Fintype.card (Name n r) := by + have h : PacketKernel.templates n r * r ^ 3 ≤ (r ^ n) ^ 2 := Nat.div_mul_le_self _ _ + rw [name_card] + have he : Fintype.card (Col n r) = (3 * r ^ 2 * PacketKernel.templates n r) * (2 ^ n * 2) := by + simp [Col, PacketKernel.Spot, Spectral.Cube]; ring + rw [he] + have hu : 3 * r ^ 2 * PacketKernel.templates n r ≤ (r ^ n) ^ 2 := + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ hr)).trans (by + simpa only [← pow_succ', mul_comm] using h) + have hv := Nat.mul_le_mul_right (2 ^ n * 2) hu + rw [mul_assoc ((r ^ n) ^ 2)] + omega + +open Classical in +/-- Indexes the row slot by the coordinates of `Fin (packetRows P B) × Bool × Spectral.Cube n × +Fin h`. -/ +abbrev RowSlot (P : Format N l d n r h) (B : ℕ) := + Fin (packetRows P B) × Bool × Spectral.Cube n × Fin h + +open Classical in +/-- The value specified by `(((PacketKernel.memberIndex A hn s.report.1 (chosen s j) b.1).val, +b.2.2), b.2.1)`. -/ +def frameSlot (s : X) (j : PacketKernel.Spot r) (b : RowSlot P B) : Position n r (B * P.count) h × + Bool := + (((PacketKernel.memberIndex A hn s.report.1 (chosen s j) b.1).val, b.2.2), b.2.1) + +open Classical in +theorem packed_frame_slot [LinearOrder (Name n r)] (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (XIn P B) ≤ 2 ^ w) (hc : 3 * r * Fintype.card (Name n r) ≤ 2 ^ w) + (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) (hr : 3 ≤ r) + (idx : Name n r ↪ Coloring.B w) (a : Coloring.B w → PacketKernel.Spot r) + (b : Coloring.B w → RowSlot P B) : + packed (U := raw _) F (C.tapeIn (i := i)) (fun z j => + (fullBit z.1 (z.2 ∘ gather hf z.1) (.inr (frameSlot z.1 (a j) (b j)))).toNat) 165 := by + let col (j) : Col n r := (a j, (b j).1.divNat, (b j).2.2.1, (b j).2.1) + let k (u : Fin (3 * r)) (c : Col n r) : Name n r := + .inr (.inl ((PacketKernel.templateIndex hn i (PacketKernel.candidate ((Worker.index r).symm u) + c.1) c.2.1).val, c.2.2)) + have hI : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w := by rw [Fintype.card_sum] at hi; omega + have hb := C.workerTable (i := i) hw hI col ((Nat.mul_le_mul_left _ (col_card hr)).trans hc) + (fun u c => (idx (k u c)).val) + let slot (s : X) (j : Coloring.B w) := frameSlot s (a j) (b j) + have he (s : X) (j) : key P B (.inr (.inl (slot s j))) = k s.site (col j) := by + let name (v : Fin n) : Name n r := .inr (.inl + ((PacketKernel.templateIndex hn v (chosen s (a j)) (b j).1.divNat).val, (b j).2.2.1, + (b j).2.1)) + exact congrArg name s.cut + have hk : packed (U := raw _) F C.input (fun s j + => (idx (key P B (.inr (.inl (slot s j))))).val) 37 := by + simpa only [he] using hb + exact C.packed_slot hw hi hc hf slot idx hk + (fun j => (b j).2.2.2.val + h * (b j).1.modNat.val) (fun _ _ => rfl) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- # Wiring the entire batch of packet-class kernels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l n d r h B w : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + +open Classical in +theorem packed_frames [LinearOrder (Name n r)] [NeZero (N / 4)] + (hw : Limits A N r (B * P.count) w) (hi : Fintype.card (XIn P B) ≤ 2 ^ w) + (hc : 3 * r * Fintype.card (Name n r) ≤ 2 ^ w) (hf : ∀ z, multiplicity P.colors z * r ^ n + ≤ 4 * N) + (hr : 3 ≤ r) (hn' : 9 * Fintype.card (A.CountBit r (B * P.count)) ≤ 2 ^ w) + (ht : 2 ^ PacketKernel.height A (packetRows P B) + < 2 ^ w) (idx : Coloring.B w → FrameSlot P A B) : + packed (U := raw _) F (C.tapeIn (i := i)) (fun z j => + (C.numberInOrder.frames z.1 (z.2 ∘ gather hf z.1) (idx j)).toNat) 400 := by + have hI : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w := by rw [Fintype.card_sum] at hi; omega + obtain ⟨e⟩ : Nonempty (Name n r ↪ Coloring.B w) := Function.Embedding.nonempty_of_card_le + (by rw [Fintype.card_fin]; exact (Nat.le_mul_of_pos_left _ (by omega)).trans hc) + have hpos : 1 ≤ w := by have := hw.large; omega + let a := fun j => (idx j).1 + let b := fun j => (idx j).2 + let f (z : WithGuess P A hn M B i) (u : PacketKernel.Spot r) + (v : PacketKernel.Frame A (packetRows P B) (countWidth P B)) := + (C.numberInOrder.frames z.1 (z.2 ∘ gather hf z.1) (u, v)).toNat + apply packed.casesOn (c := 386) hpos f a b + · intro j + exact (C.lift hi (C.packed_enabled hw hI e a)).mono (by decide) + intro j + apply packed.casesOn (c := 372) hpos (fun z u v => f z u (.inr v)) a j + · intro j + exact (C.lift hi (C.packed_mode hw hI e a j)).mono (by decide) + intro j + apply packed.casesOn (c := 358) hpos (fun z u v => f z u (.inr (.inr v))) a j + · intro j + exact (C.packed_frame_slot hw hi hc hf hr e a j).mono (by decide) + intro j + apply packed.casesOn (c := 344) hpos (fun z u v => f z u (.inr (.inr (.inr v)))) a j + · intro j + exact (C.lift hi (C.packed_counts_frame hw hI a hn' j)).mono (by decide) + · intro j + exact (C.lift hi (C.packed_frame_stream hw hI ht e a j)).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +section +/- # Space for padded template addresses -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +open Diagonal + +variable {N l n d r h : ℕ} (P : Format N l d n r h) + +theorem domain_size {C : ℕ} (hl : r ^ n ≤ C * N * d) (hc : 1 ≤ C) + (hp : Fintype.card (Position n r P.count h) ≤ 13 * C * N * d) : + Fintype.card (Domain P) * r ≤ 100 * C * N * d := by + have h₁ : (r ^ n / r) * r ≤ C * N * d := (Nat.div_mul_le_self ..).trans hl + have h₂ : (SlotKey.count n r) * (P.count * h) * r ≤ 2 * (13 * C * N * d) := by + calc + _ = (SlotKey.count n r * r) * (P.count * h) := by ring + _ ≤ Fintype.card (SlotKey n r) * (P.count * h) + := Nat.mul_le_mul_right _ (Nat.div_mul_le_self ..) + _ = 2 * Fintype.card (Position n r P.count h) := by + simp only [SlotKey, Position, Packet, Fintype.card_prod, Fintype.card_bool, + Fintype.card_fin] + ring + _ ≤ _ := Nat.mul_le_mul_left _ hp + have h₃ : (4 * N / r) * d * r ≤ 4 * (C * N * d) := by + calc + _ = ((4 * N / r) * r) * d := by ring + _ ≤ 4 * N * d := Nat.mul_le_mul_right _ (Nat.div_mul_le_self ..) + _ ≤ 4 * (C * N * d) := by + rw [mul_assoc, mul_assoc C] + exact Nat.mul_le_mul_left 4 (Nat.le_mul_of_pos_left _ hc) + simp only [Domain, SlotKey.Domain, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + nlinarith only [h₁, h₂, h₃, Nat.zero_le (C * N * d)] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +end + +section +/- # Bounds shared by the worker circuits -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal Controller +variable {F : Type} [Field F] [Fintype F] {N l d n r h : ℕ} + +/-- The workspace has `2^W` lanes, each containing a `W`-bit register. -/ +structure Window (P : Format N l d n r h) (A : Expansion F n h) + (M : Bank (Fin n)) (B C Q w W : ℕ) : Prop where + small : W ≤ 2 * w + cost : 2 ^ W ≤ N * w ^ (Q + 10) + limits : Limits A N r (B * P.count) W + three : 3 ≤ r + big : 100 * N ≤ 2 ^ W + names : 3 * r * Fintype.card (Name n r) ≤ 2 ^ W + counts : 9 * Fintype.card (A.CountBit r (B * P.count)) ≤ 2 ^ W + stream : 2 ^ PacketKernel.height A (packetRows P B) < 2 ^ W + frames : Fintype.card (FrameSlot P A B) ≤ 2 ^ W + guess : Fintype.card (XIn P B) ≤ 2 ^ W + data : Fintype.card M.Data ≤ 2 ^ W + bits : Fintype.card (M.Bits F) ≤ 2 ^ W + axes : 3 * r * n ≤ 2 ^ W + rate : PacketKernel.rate A + PacketKernel.batchRate A ≤ W + positions : Fintype.card (Position n r P.count h) ≤ 13 * C * N * d + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Testing activation and fetching a slot in the worker template -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +open Diagonal Controller MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector + +variable {F : Type} [Field F] [Fintype F] {N l n d r h B c Q w W : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) [LinearOrder (Name n r)] {i : Fin n} + (H : Window P A M B c Q w W) (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i +local notation "Y" => WithGuess P A hn M B i + +omit [LinearOrder (Name n r)] in +open Classical in +theorem input_le (H : Window P A M B c Q w W) : + Fintype.card (Machine.Ports N l l) ≤ 2 ^ W := by + have hx := H.guess + rw [Fintype.card_sum] at hx + omega + +omit [LinearOrder (Name n r)] in +open Classical in +theorem name_le (H : Window P A M B c Q w W) : Nonempty (Name n r ↪ Coloring.B W) := + Function.Embedding.nonempty_of_card_le (by + rw [Fintype.card_fin] + exact (Nat.le_mul_of_pos_left _ (by have := H.three; omega)).trans H.names) + +include H in +open Classical in +private theorem packed_owns {J : Type} [Fintype J] (hJ : Fintype.card J ≤ Fintype.card (Name n r)) + (j : Coloring.B W → J) (z : Worker r → J → Label n r) : + packed (U := raw _) F (C.tapeIn (i := i)) + (fun s p => (owns s.1 (z (workerAt s.1) (j p))).toNat) 131 := by + obtain ⟨idx⟩ := name_le H + let key (s : X) (p : Coloring.B W) : Name n r := .inl (.inr (z (workerAt s) (j p))) + have hk : packed (U := raw _) F (C.input (i := i)) (fun s p => (idx (key s p)).val) 37 := + C.workerTable H.limits (input_le H) j ((Nat.mul_le_mul_left _ hJ).trans H.names) + (fun u t => (idx (.inl (.inr (z ((Worker.index r).symm u) t)))).val) + have hh := C.packed_pair H.limits (input_le H) key idx hk (fun u x _ => (decide (x = u)).toNat) + simp only [key, request, descriptor, ← Equiv.eq_symm_apply] at hh + exact C.lift H.guess hh + +include H in +open Classical in +theorem packed_label (j : Coloring.B W → Fin B) (g : Coloring.B W → Fin (r ^ n / r)) : + packed (U := raw _) F (C.tapeIn (i := i)) (fun z p + => (value hf z (j p) (.inl (g p))).toNat) 131 := by + have hs : Fintype.card (Fin (r ^ n / r)) ≤ Fintype.card (Name n r) := by + rw [Fintype.card_fin, name_card] + have := Nat.div_le_self (r ^ n) r + omega + exact packed_owns C H hs g (fun u t => (labels (Layout.axis hn i u) (Layout.symbol u) t).val) + +include H in +open Classical in +theorem packed_position (j : Coloring.B W → Fin B) + (g : Coloring.B W → SlotKey.Domain n r P.count h) : + packed (U := raw _) F (C.tapeIn (i := i)) + (fun z p => (value hf z (j p) (.inr (.inl (g p)))).toNat) 180 := by + have hs : Fintype.card (Fin (SlotKey.count n r)) ≤ Fintype.card (Name n r) := by + rw [Fintype.card_fin] + refine (Nat.div_le_self _ _).trans ?_ + exact Fintype.card_le_of_injective (fun k : SlotKey n r => (Sum.inr (.inl k) : Name n r)) + (fun _ _ h => Sum.inl.inj (Sum.inr.inj h)) + let arg (s : X) (p : Coloring.B W) := slot s (j p) (g p) + let num (u : Worker r) (q : Fin (SlotKey.count n r)) := + (SlotKey.enumerate hn (Layout.axis hn i u) (.home (Layout.symbol u)) q).val + let lab (u : Worker r) (q : Fin (SlotKey.count n r)) := (num u q).label + let active (s : Y) p := owns s.1 (lab (workerAt s.1) (g p).1) + have ha : packed (U := raw _) F C.tapeIn (fun s p => (active s p).toNat) 131 := + packed_owns C H hs (fun p => (g p).1) lab + obtain ⟨idx⟩ := name_le H + have hk : packed (U := raw _) F C.input (fun s p + => (idx (key P B (.inr (.inl (arg s p))))).val) 37 := + C.workerTable H.limits (input_le H) (fun p => (g p).1) + ((Nat.mul_le_mul_left _ hs).trans H.names) + (fun u t => (idx (.inr (.inl (num ((Worker.index r).symm u) t)))).val) + let off p := (g p).2.2.val + h * (finProdFinEquiv (j p, (g p).2.1)).val + have hd := C.packed_slot H.limits H.guess H.names hf arg idx hk off (fun _ _ => rfl) + have hb := packed.const (U := raw _) F (C.tapeIn (i := i)) (fun _ : Coloring.B W => 0) + (m := 0) (by rw [pow_zero, mul_one]; exact H.guess) + have h1 : 1 < 2 ^ W := Nat.one_lt_pow (by have := H.limits.large; omega) (by decide) + have ht := hb.select ha hd hb (fun _ _ => pow_pos (by decide) _) + (fun s p => by cases active s p <;> simp [h1]) + convert ht.mono (n := 180) (by decide) using 1 + funext z p + change (if active z p then fullBit z.1 (z.2 ∘ gather hf z.1) (.inr (arg z.1 p)) else false).toNat + = _ + cases active z p <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +end + +/- # Computing every input bit of the station bank -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +open Diagonal Controller MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector + +variable {F : Type} [Field F] [Fintype F] {N l n d r h B c Q w W : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) [LinearOrder (Name n r)] [NeZero r] + {i : Fin n} (H : Window P A M B c Q w W) (he : P.which + = (Format.prescribed d h P.count P.colors).which) + (hf : ∀ z, Diagonal.multiplicity P.colors z * r ^ n ≤ 4 * N) + +local notation "Y" => WithGuess P A hn M B i + +include H in +open Classical in +private theorem packed_value (j : Coloring.B W → Fin B) (t : Coloring.B W → Domain P) : + packed (U := raw _) F (C.tapeIn (i := i)) (fun z p => (value hf z (j p) (t p)).toNat) 540 := by + have hw : 1 ≤ W := by have := H.limits.large; omega + apply packed.casesOn (c := 526) hw (fun (z : Y) j t => (value hf z j t).toNat) j t + · exact fun g => (packed_label C H hf j g).mono (by decide) + · intro g + apply packed.casesOn (c := 512) hw (fun (z : Y) j t => (value hf z j (.inr t)).toNat) j g + · exact fun t => (packed_position C H hf j t).mono (by decide) + · intro t + obtain ⟨idx⟩ := name_le H + exact PinIndex.packed_read C H.limits (input_le H) H.big H.guess idx hf + (fun p => (t p).1.val) (fun p => (finProdFinEquiv (j p, (t p).2)).val) + +open Classical in +private def findCell (addr : Address P M) (k : M.Data) : Unit ⊕ (Fin B × Domain P) := + if hj : k.2.1.val < B then + match lookup addr k.1 k.2.2 with + | some p => .inr (⟨k.2.1.val, hj⟩, p) + | none => .inl () + else .inl () + +open Classical in +private def found (z : Y) : Unit ⊕ (Fin B × Domain P) → Bool + | .inl _ => false + | .inr t => value hf z t.1 t.2 + +variable (addr : Address P M) (hidx : C.index = index hn he hf addr) + +omit [LinearOrder (Name n r)] [NeZero r] in +include hidx in +open Classical in +private theorem active_cell (z : Y) (k : M.Data) : + C.bankData z.1 (z.2 ∘ gather hf z.1) k = + if k.1 = PinIndex.axis z.1 then found hf z (findCell addr k) else false := by + rw [bank_read hn he hf addr C _ _ hidx] + by_cases haxis : k.1 = PinIndex.axis z.1 + · rw [ite_eq_left haxis] + unfold findCell + by_cases hj : k.2.1.val < B + · rw [dite_eq_left ⟨hj, haxis⟩, dite_eq_left hj] + cases lookup addr k.1 k.2.2 + · rfl + · exact probe_value C he hf _ _ _ + · rw [dite_eq_right (fun h => hj h.1), dite_eq_right hj]; rfl + · rw [dite_eq_right (fun h => haxis h.2), ite_eq_right haxis] + +include H hidx in +open Classical in +theorem packed_bank (k : Coloring.B W → M.Data) : + packed (U := raw _) F (C.tapeIn (i := i)) (fun z j => + (C.bankData z.1 (z.2 ∘ gather hf z.1) (k j)).toNat) 570 := by + have hw : 1 ≤ W := by have := H.limits.large; omega + have z0 := packed.const (U := raw _) F (C.tapeIn (i := i)) (fun _ : Coloring.B W => 0) + (m := 0) (by rw [pow_zero, mul_one]; exact H.guess) + have ht : packed (U := raw _) F (C.tapeIn (i := i)) + (fun z j => (found hf z (findCell addr (k j))).toNat) 554 := by + apply packed.casesOn (c := 540) hw (fun (z : Y) (_ : Unit) t => (found hf z t).toNat) + (fun _ => ()) (fun j => findCell addr (k j)) + · exact fun _ => z0.mono (by decide) + · exact fun t => packed_value C H hf (fun j => (t j).1) (fun j => (t j).2) + let m (z : Y) j := if (k j).1 = PinIndex.axis z.1 then 1 else 0 + have hm : packed (U := raw _) F (C.tapeIn (i := i)) m 39 := + C.lift H.guess (C.workerTable H.limits (input_le H) (fun j => (k j).1) + (by rw [Fintype.card_fin]; exact H.axes) + (fun u j => if j = Layout.axis hn i ((Worker.index r).symm u) then 1 else 0)) + have h1 : 1 < 2 ^ W := Nat.one_lt_pow (by omega) (by decide) + have hg := z0.select hm ht z0 + (fun _ _ => pow_pos (by decide) _) (fun _ _ => by unfold m; split <;> omega) + convert hg.mono (n := 570) (by decide) using 1 + funext z j + rw [active_cell C he hf addr hidx] + by_cases hv : (k j).1 = PinIndex.axis z.1 <;> simp [m, hv] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Cells +end + +section +/- # Cost of the packet contribution at a processor -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal Controller Install +variable {F : Type} [Field F] [Fintype F] {N l n d r h B K Q w W : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} {hn : 2 ≤ n} + +private theorem rows_fit : packetRows P B < 2 ^ countWidth P B := by + apply lt_of_lt_of_le _ (Nat.le_pow_clog (by decide : 1 < 2) _) + apply Nat.lt_succ_of_le + calc + _ ≤ (r ^ n) ^ 2 * (B * P.count) := Nat.mul_le_mul_right _ (Nat.div_le_self _ _) + _ = _ := by simp [Packet, Template, Label, pow_two] + +private theorem Window.batch (H : Window P A M B K Q w W) (i : Fin n) : + Weight F (PacketKernel.batch (p := packetRows P B) (w := countWidth P B) (r := r) A i) + (2 ^ W * (100 + W) ^ 7) := by + let p := packetRows P B + have hb : countWidth P B ≤ W * 8 := by + apply Nat.clog_le_of_le_pow + rw [pow_mul] + exact H.limits.packets + have hn : 1 + p ≤ 2 ^ PacketKernel.height A p := by + rw [add_comm] + exact (Nat.le_mul_of_pos_right _ (by unfold PacketKernel.rowSize; omega)).trans + (PacketKernel.height_bounds A p).1 + have hframe : 1 + p ≤ Fintype.card (PacketKernel.Frame A p (countWidth P B)) := by + apply hn.trans + simp only [PacketKernel.Frame, PacketKernel.Given, Fintype.card_sum, PackCode.Index, + Fintype.card_fin] + omega + have hdim : r ^ 2 * (1 + p) ≤ 2 ^ W := by + refine le_trans ?_ H.frames + rw [Fintype.card_prod, PacketKernel.card_spot] + exact Nat.mul_le_mul (by omega) hframe + have hr : PacketKernel.batchRate A ≤ 100 + W := by have := H.rate; omega + have hw : 1 + countWidth P B ≤ (100 + W) ^ 2 := by nlinarith + refine (PacketKernel.batch_net A i (rows_fit (P := P) (B := B))).mono ?_ + calc + _ = (r ^ 2 * (1 + p)) * PacketKernel.batchRate A * (1 + countWidth P B) ^ 3 := by unfold p; ring + _ ≤ 2 ^ W * (100 + W) * ((100 + W) ^ 2) ^ 3 := by gcongr + _ = _ := by ring + +private theorem frame_budget {a b c W : ℕ} (h : b ≤ a) (hc : a < c) : + 2 ^ W * (100 + W) ^ a + 2 ^ W * (100 + W) ^ b ≤ 2 ^ W * (100 + W) ^ c := by + rw [← mul_add] + apply Nat.mul_le_mul_left + calc + _ ≤ (100 + W) ^ a * 2 := by rw [mul_two]; gcongr + _ ≤ (100 + W) ^ (a + 1) := by rw [pow_succ]; gcongr; omega + _ ≤ _ := Nat.pow_le_pow_right (by omega) hc + +namespace Controller +open MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable (C : Controller P A hn M B) [LinearOrder (Name n r)] [NeZero (N / 4)] + +theorem frame_cost (H : Window P A M B K Q w W) (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) + (i : Fin n) : + ∃ f, Weight F f (2 ^ W * (100 + W) ^ 403) ∧ ∀ z : WithGuess P A hn M B i, + f (C.tapeIn z) = PacketKernel.batch A i (C.numberInOrder.frames z.1 (z.2 ∘ gather hf z.1)) + := by + have hW : 1 ≤ W := by have := H.limits.large; omega + obtain ⟨f, hnet, he⟩ := packed.output hW H.guess H.frames + (fun z : WithGuess P A hn M B i => C.numberInOrder.frames z.1 (z.2 ∘ gather hf z.1)) + (C.packed_frames H.limits H.guess H.names hf H.three H.counts H.stream) + refine ⟨_, (hnet.weight (H.batch i)).mono ?_, fun z => congrArg (PacketKernel.batch A i) (he z)⟩ + exact frame_budget (by decide) (by decide) + +end Controller +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # An exact scalar network for the programmed station bank -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal Install MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l n d r h B c Q w W : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) [LinearOrder (Name n r)] [NeZero r] + +open Classical in +private theorem bank_bound {D X Y Z p : ℕ} (hx : X ≤ 2 ^ D) (hy : Y ≤ 2 ^ D) + (hb : Z ≤ 2 ^ D * (100 + D) ^ Q) (hp : p < 650) : + 5 * X + 2 ^ D * (100 + D) ^ p + (X + 2 * Y + Y) + Z ≤ 2 ^ D * (100 + D) ^ (Q + 650) := by + let K := 2 ^ D * (100 + D) ^ (Q + 649) + have ht (j : ℕ) (hj : j ≤ Q + 649) : 2 ^ D * (100 + D) ^ j ≤ K := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) hj) + have h₁ : 2 ^ D ≤ K := by simpa only [pow_zero, mul_one] using ht 0 (by omega) + have h₂ := ht p (by omega) + have h₃ := ht Q (by omega) + calc + _ ≤ K * 11 := by omega + _ ≤ K * (100 + D) := Nat.mul_le_mul_left _ (by omega) + _ = _ := by unfold K; rw [mul_assoc, ←pow_succ] + +open Classical in +theorem bank_net (H : Window P A M B c Q w W) + (he : P.which = (Format.prescribed d h P.count P.colors).which) + (hf : ∀ z, Diagonal.multiplicity P.colors z * r ^ n ≤ 4 * N) + (addr : Cells.Address P M) (hidx : C.index = Cells.index hn he hf addr) + (hM : M.budget F ≤ 2 ^ W * (100 + W) ^ Q) (i : Fin n) : + ∃ g, Weight F g (2 ^ W * (100 + W) ^ (Q + 650)) ∧ ∀ z : WithGuess P A hn M B i, + g (C.tapeIn z) = M.result F (Sum.elim (C.bankData z.1 (z.2 ∘ gather hf z.1)) z.1.script) := by + let f (z : WithGuess P A hn M B i) := C.bankData z.1 (z.2 ∘ gather hf z.1) + obtain ⟨g, hg, heq⟩ := packed.output (by have := H.limits.large; omega) H.guess H.data f + (Cells.packed_bank C H he hf addr hidx) + let p (j : M.Bits F) : XIn P B := .inl (.inl (M.literalPort F l r C.literal (.inr (.inr j)))) + have hv := (hg.pair ((BNet.id F _).pull p)).weight (M.net F) + refine ⟨_, hv.mono (bank_bound H.guess H.bits hM (by decide)), fun z => ?_⟩ + have hs : C.tapeIn z ∘ p = z.1.script := by + funext j + exact M.literalCode_script F l r C.literal _ j + change M.result F (Sum.elim (g (C.tapeIn z)) (C.tapeIn z ∘ p)) = _ + rw [hs, heq] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- +# Assembling one fixed-cut worker + +The sum over the fixed tape of guesses is exact. The private check +forces inactive cells to zero and enforces the delivered bits. The +public relay check needs only the processor inputs. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal Install Finset +variable {F : Type} [Field F] [Fintype F] {N l n d r h B K Q w W : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) [LinearOrder (Name n r)] [NeZero (N / 4)] + [NeZero (3 * r)] + (hf : ∀ z, Diagonal.multiplicity P.colors z * r ^ n ≤ 4 * N) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i +local notation "Y" => WithGuess P A hn M B i + +open Classical in +/-- Selects the appropriate branch of `if C.pass z.1 W z.2 then Pin.mask F (workerAt z.1) +(C.code (some (z.1.site, z.1.script))) (localPins z.1 (z.2 ∘ gather hf z.1)) else 0`. -/ +def checked (W : ℕ) (z : Y) : F := + if C.pass z.1 W z.2 then + Pin.mask F (workerAt z.1) (C.code (some (z.1.site, + z.1.script))) (localPins z.1 (z.2 ∘ gather hf z.1)) + else 0 + +open Classical in +/-- The value specified by `M.result F (Sum.elim (C.bankData z.1 (z.2 ∘ gather hf z.1)) +z.1.script)`. -/ +def bankValue (z : Y) : F := + M.result F (Sum.elim (C.bankData z.1 (z.2 ∘ gather hf z.1)) z.1.script) + +open Classical in +private def packetValue (z : Y) : F := + PacketKernel.batch A i (C.numberInOrder.frames z.1 (z.2 ∘ gather hf z.1)) + +omit [NeZero (3 * r)] in +open Classical in +private theorem expanded (hw : N ≤ 2 ^ W) + (hP : P.which = (Format.prescribed d h P.count P.colors).which) (s : X) : + (if C.relay s then 1 else 0) * (∑ x : Guess P B → Bool, + C.checked hf W (s, x) * (C.bankValue hf (s, x) * C.packetValue hf (s, x))) = + C.numberInOrder.site s.site s.script s.report s.physical := by + rw [C.numberInOrder.site_eq s hP] + have he : C.numberInOrder.relay s ↔ C.relay s := Iff.rfl + simp only [he, ite_mul, one_mul, zero_mul] + apply if_congr Iff.rfl _ rfl + rw [← C.sum_pass hf s hw] + apply sum_congr rfl + intro x _ + simp only [checked, ite_mul, zero_mul] + rfl + +open Classical in +private theorem combined_budget {x y z a b c t e : ℕ} (hx : x ≤ 2 ^ W) (hy : y ≤ 2 ^ W) + (hz : z ≤ 2 ^ W) (ha : a ≤ t) (hb : b ≤ t) (hc : c ≤ t) (he : t < e) : + 5 * x + (2 ^ W * (100 + W) ^ a + 16) + + (5 * y + 2 ^ W * (100 + W) ^ b + (5 * y + 2 ^ W * (100 + W) ^ t + 2 ^ W * (100 + W) ^ c) + z) + ≤ + 2 ^ W * (100 + W) ^ e := by + let m := 2 ^ W * (100 + W) ^ t + have hm : 0 < m := by unfold m; positivity + have hh : 2 ^ W ≤ m := Nat.le_mul_of_pos_right _ (by positivity) + have h (j : ℕ) (hj : j ≤ t) : 2 ^ W * (100 + W) ^ j ≤ m := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) hj) + have := h _ ha + have := h _ hb + have := h _ hc + calc + _ ≤ m * 100 := by omega + _ ≤ m * (100 + W) := Nat.mul_le_mul_left _ (by omega) + _ = 2 ^ W * (100 + W) ^ (t + 1) := by rw [pow_succ, ← mul_assoc] + _ ≤ _ := Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) he) + +open Classical in +/-- One scalar circuit suffices for every worker, script and feasible +report at the prescribed cut. -/ +theorem handles [NeZero r] (H : Window P A M B K Q w W) + (he : P.which = (Format.prescribed d h P.count P.colors).which) + (hf : ∀ z, Diagonal.multiplicity P.colors z * r ^ n ≤ 4 * N) + (addr : Cells.Address P M) (hidx : C.index = Cells.index hn he hf addr) + (hM : M.budget F ≤ 2 ^ W * (100 + W) ^ Q) (i : Fin n) : + ∃ g, Weight F g (2 ^ W * (100 + W) ^ (Q + 660)) ∧ C.numberInOrder.Handles i g := by + have hi := H.guess + rw [Fintype.card_sum] at hi + have hi' : Fintype.card (Machine.Ports N l l) ≤ 2 ^ W := by omega + have hu : Fintype.card (Guess P B) ≤ 2 ^ W := by omega + obtain ⟨idx⟩ : Nonempty (Name n r ↪ Coloring.B W) := + Function.Embedding.nonempty_of_card_le (by + rw [Fintype.card_fin] + exact (Nat.le_mul_of_pos_left _ (by have := H.three; omega)).trans H.names) + obtain ⟨g, hg, hg'⟩ := C.relay_net H.limits hi' i + obtain ⟨a, ha, ha'⟩ := C.private_net (i := i) H.limits hi' H.big H.guess H.names idx hf + obtain ⟨b, hb, hb'⟩ := C.bank_net H he hf addr hidx hM i + obtain ⟨c, hc, hc'⟩ := C.frame_cost H hf i + have hpublic := hg.weight (Weight.dense F Unit (fun x => if x () then 1 else 0)) + have htotal := hpublic.mul (ha.mul (hb.mul hc)).sum_right + refine ⟨_, htotal.mono ?_, ?_⟩ + · rw [Fintype.card_unit] + exact combined_budget hi' H.guess hu (by omega) (by omega) (by omega) (by omega) + · intro j script R y hcut hfeas + let s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i := + ⟨j, script, R, y, hcut, hfeas⟩ + change (if g (C.input s) () then 1 else 0) * + (∑ x : Guess P B → Bool, a (C.tapeIn (s, x)) * (b (C.tapeIn (s, x)) * c (C.tapeIn (s, x)))) = + C.numberInOrder.site s.site s.script s.report s.physical + simp only [hg', decide_eq_true_eq, ha', hb', hc'] + exact C.expanded hf H.limits.bits he s + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Labels.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Labels.lean new file mode 100644 index 0000000000..55caa121e3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Labels.lean @@ -0,0 +1,346 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.ControlWeight +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortBack +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Wide +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Add +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.AlphabetCode + +/-! # Products of weights on disjoint sets of named bits -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install + +private def optionSlots {V : Type} (I : Option V → Type) : + I none ⊕ (Σ v : V, I (some v)) ≃ (Σ v, I v) where + toFun := Sum.elim (Sigma.mk none) (fun p => ⟨some p.1, p.2⟩) + invFun + | ⟨none, i⟩ => .inl i + | ⟨some v, i⟩ => .inr ⟨v, i⟩ + left_inv := by rintro (i|⟨v, i⟩) <;> rfl + right_inv := by rintro ⟨_|v, i⟩ <;> rfl + +/-- Parallel deterministic circuits with disjoint local inputs. -/ +theorem BNet.sigma {F : Type} [Field F] {V : Type} [Fintype V] + {I J : V → Type} [∀ v, Finite (I v)] [∀ v, Finite (J v)] + (f : ∀ v, (I v → Bool) → J v → Bool) {m : V → ℕ} (h : ∀ v, BNet F (f v) (m v)) : + BNet F (fun (x : (Σ v, I v) → Bool) (j : Σ v, J v) => + f j.1 (fun i => x ⟨j.1, i⟩) j.2) (∑ v, m v) := by + classical + revert V + apply Fintype.induction_empty_option + · intro A B _ e ih I J _ _ f m h + let := Fintype.ofEquiv B e.symm + have k := ih (fun v => f (e v)) (fun v => h (e v)) + rw [← e.sum_comp m] + let p := Equiv.sigmaCongrLeft (β := J) e + convert k.rename (Equiv.sigmaCongrLeft e) p using 1 + funext x j + obtain ⟨y, rfl⟩ := p.surjective j + let g (z : Σ v, J (e v)) := f (e z.1) (fun i => x ⟨e z.1, i⟩) z.2 + exact congrArg g (p.symm_apply_apply y).symm + · intro I J _ _ f m h + let : IsEmpty (Σ v, I v) := ⟨fun p => p.1.elim⟩ + let : IsEmpty (Σ v, J v) := ⟨fun p => p.1.elim⟩ + apply BNet.of_layout (a := .unit) (b := .unit) (Equiv.equivEmpty _) (Equiv.equivEmpty _) + rw [Fintype.sum_empty] + exact DNet.id F .unit + · intro V _ ih I J _ _ f m h + have k := ih (fun v => f (some v)) (fun v => h (some v)) + rw [Fintype.sum_option] + convert ((h none).parallel k).rename (optionSlots I) (optionSlots J) using 1 + funext x j + rcases j with ⟨_|v, j⟩ <;> rfl + +/-- Read a common input into an arbitrary finite collection of circuits. -/ +theorem BNet.collect {F I J V : Type} [Field F] [Fintype I] [Finite J] [Fintype V] + (f : V → (I → Bool) → J → Bool) {m : ℕ} (h : ∀ v, BNet F (f v) m) : + BNet F (fun x (t : V × J) => f t.1 x t.2) + (Fintype.card I + Fintype.card V * (2 * Fintype.card I + m)) := by + have k := ((BNet.sigma f h).pull (fun p => p.2)).rename (Equiv.refl I) (Equiv.sigmaEquivProd V J) + apply k.mono + simp only [Fintype.card_sigma, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, Nat.cast_id] + exact le_of_eq (by ring) + +namespace Weight + +/-- The cost of a disjoint product is at most the sum of local costs, +even if each factor uses its own set of coordinates. -/ +theorem sigma_prod {F : Type} [Field F] {V : Type} [Fintype V] + {I : V → Type} [∀ v, Finite (I v)] + (f : ∀ v, (I v → Bool) → F) {m : V → ℕ} (h : ∀ v, Weight F (f v) (m v)) : + Weight F (fun x : (Σ v, I v) → Bool => ∏ v, f v (fun i => x ⟨v, i⟩)) (∑ v, m v) := by + classical + revert V + apply Fintype.induction_empty_option + · intro A B _ e ih I _ f m h + let := Fintype.ofEquiv B e.symm + have k := ih (fun v => f (e v)) (fun v => h (e v)) + rw [← e.sum_comp m] + convert k.rename (Equiv.sigmaCongrLeft e) using 1 + funext x + rw [← e.prod_comp] + rfl + · intro I _ f m h + have : IsEmpty (Σ v, I v) := ⟨fun p => p.1.elim⟩ + apply of_layout (a := .unit) (Equiv.equivEmpty _) + exact ⟨0, Nat.zero_le _, by simpa using (Net.empty (F := F))⟩ + · intro V _ ih I _ f m h + have k := ih (fun v => f (some v)) (fun v => h (some v)) + rw [Fintype.sum_option] + convert ((h none).parallel k).rename (optionSlots I) using 1 + funext x + rw [Fintype.prod_option] + rfl + +/-- Enable a factor with one control bit. On the inactive branch its +weight is one, independently of its private assignments. -/ +theorem branch {F I : Type} [Field F] [Fintype I] {f : (I → Bool) → F} {m : ℕ} + (h : Weight F f m) : + Weight F (fun x : Unit ⊕ I → Bool => if x (.inl ()) then f (x ∘ Sum.inr) else 1) + (1000 * (m + Fintype.card I + 1)) := by + have hf (b : Unit → Bool) : + Weight F (fun x => if b () then f x else 1) (m + Fintype.card I) := by + by_cases hb : b () = true + · simpa [hb] using h.mono (Nat.le_add_right m (Fintype.card I)) + · intro a i + obtain ⟨v, hv, hs⟩ := DNet.discard F a + refine ⟨v, ?_, ?_⟩ + · rw [Fintype.card_congr i, card_slots] + omega + · simpa [hb] using hs + apply (switch _ hf).mono + simp [switchCost, localCost] + omega + +end Weight +end MatrixMultiplicationAllFields.MatrixExponent.Install +end + +section +/- +# Efficient high-arity tables + +A diagram may use a high-arity table if its scalar entries have a +trivalent realization of size quasilinear in its arity. The processor +needs only a circuit description for this table. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Install +variable {F : Type} [Field F] {a b : Wire} + +/-- The quantity computed by `wd T.1 + wd T.2.1`. -/ +def arity (T : Table F) : ℕ := wd T.1 + wd T.2.1 + +/-- The quantity computed by `{T | ∃ m ≤ (1 + arity T) * K * (1 + Nat.clog 2 (1 + arity T)) ^ q, +Net F T.1 T.2.1 T.2.2 m}`. -/ +def Cheap (F : Type) [Field F] (K q : ℕ) : Set (Table F) := + {T | ∃ m ≤ (1 + arity T) * K * (1 + Nat.clog 2 (1 + arity T)) ^ q, Net F T.1 T.2.1 T.2.2 m} + +/-- Indexes the ports of by the coordinates of `slots T.1 ⊕ slots T.2.1`. -/ +abbrev PortsOf (T : Table F) := slots T.1 ⊕ slots T.2.1 + +/-- The value specified by `T.2.2 ((bits T.1).symm (s ∘ Sum.inl)) ((bits T.2.1).symm (s ∘ +Sum.inr))`. -/ +def weight (T : Table F) (s : PortsOf T → Bool) : F := + T.2.2 ((bits T.1).symm (s ∘ Sum.inl)) ((bits T.2.1).symm (s ∘ Sum.inr)) + +private theorem of_net {k : Val a → Val b → F} {m : ℕ} (h : Net F a b k m) : + Weight F (weight ⟨a, b, k⟩) (m + wd b) := by + have t := ((h.par (Tagged.cap b)).pre (.assoc a b b)).post (.swap _ _) + apply Weight.of_layout (a := .pair a b) (.refl _) + refine ⟨m + wd b, le_rfl, ?_⟩ + convert t.trace using 1 + funext x y + simp only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + change k ((bits a).symm (bits a x.1)) ((bits b).symm (bits b x.2)) = _ + rw [Equiv.symm_apply_apply, Equiv.symm_apply_apply] + +/-- A common overhead bound for each argument and vertex. -/ +def rate (K q D : ℕ) := 2 + K * (1 + Nat.clog 2 (1 + D)) ^ q + +theorem weight_cheap {T : Table F} {K q D : ℕ} (hd : arity T ≤ D) + (ht : arity T ≤ 3 ∨ T ∈ Cheap F K q) : + Weight F (weight T) ((1 + arity T) * rate K q D) := by + have hi : wd T.2.1 ≤ arity T := Nat.le_add_left _ _ + rcases ht with ht | ⟨m, hm, hn⟩ + · refine (of_net (Net.table _ _ T.2.2 ht)).mono ?_ + unfold rate + exact (Nat.add_le_add_left hi 1).trans (Nat.le_mul_of_pos_right _ (by omega)) + · refine (of_net hn).mono ?_ + calc + _ ≤ (1 + arity T) * K * (1 + Nat.clog 2 (1 + arity T)) ^ q + arity T := Nat.add_le_add hm hi + _ ≤ (1 + arity T) * K * (1 + Nat.clog 2 (1 + D)) ^ q + arity T := by gcongr + _ ≤ _ := by unfold rate; ring_nf; omega + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- +# Arithmetic on count fields in public reports + +A fixed nonnegative linear combination of input bits requires only +linear work times the register width. The output is modulo the size +of the register. Comparisons below require explicit no-overflow bounds. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Install Coloring +variable {F I J : Type} [Field F] {w m n : ℕ} + +/-- The quantity computed by `(Control.decode w).symm (Fin.ofNat (2 ^ w) k)`. -/ +def digits (w k : ℕ) : slots (word w) → Bool := (Control.decode w).symm (Fin.ofNat (2 ^ w) k) + +/-- The indexed operation `BNet F (fun x => digits w (f x)) m`. -/ +def Register (F : Type) [Field F] (w : ℕ) (f : (I → Bool) → ℕ) (m : ℕ) := + BNet F (fun x => digits w (f x)) m + +namespace Register + +variable {f : (I → Bool) → ℕ} + +theorem mono (h : Register F w f m) (le : m ≤ n) : Register F w f n := BNet.mono h le + +theorem rename (h : Register F w f m) (e : I ≃ J) : + Register F w (fun x => f (x ∘ e)) m := BNet.rename h e (.refl _) + +theorem const [Fintype I] (k : ℕ) : + Register F w (fun _ : I → Bool => k) (Fintype.card I + 16 * w) := by + have h : Depends (fun _ : I → Bool => digits w k) 0 := + fun _ => ⟨∅, by simp, fun _ _ _ => rfl⟩ + simpa [Register, localCost] using h.bnet F + +private theorem of_bit (k : ℕ) : + Register F w (fun x : Unit → Bool => if x () then k else 0) (1 + 34 * w) := by + have h : Depends (fun x : Unit → Bool => digits w (if x () then k else 0)) 1 := by + intro i + exact ⟨{()}, by simp, fun x y h => by simp only [h () (by simp)]⟩ + simpa [Register, localCost] using h.bnet F + +theorem add_disjoint [Finite I] [Finite J] {g : (J → Bool) → ℕ} + (h : Register F w f m) (k : Register F w g n) : + Register F w (fun x => f (x ∘ Sum.inl) + g (x ∘ Sum.inr)) (m + n + 10000 * (1 + w)) := by + let : Fintype I := Fintype.ofFinite I + let : Fintype J := Fintype.ofFinite J + have hb := (BNet.parallel h k).comp (numeric_add F w) + unfold Register + convert hb using 1 + funext x + let i := f (x ∘ Sum.inl) + let j := g (x ∘ Sum.inr) + change digits w (i + j) = (Control.decode w).symm + (Control.decode w (digits w i) + Control.decode w (digits w j)) + simp only [digits, Equiv.apply_symm_apply] + exact congrArg _ (Fin.ext (Nat.add_mod i j (2 ^ w))) + +private def optionEquiv (I : Type) : Unit ⊕ I ≃ Option I := + ⟨Sum.elim (fun _ => none) some, fun x => x.elim (.inl ()) Sum.inr, + by rintro (_|_) <;> rfl, by rintro (_|_) <;> rfl⟩ + +theorem weighted [Fintype I] (F : Type) [Field F] (w : ℕ) (k : I → ℕ) : + Register F w (fun x => ∑ i, if x i then k i else 0) + (20000 * (1 + Fintype.card I) * (1 + w)) := by + classical + revert I + apply Fintype.induction_empty_option + · intro A B _ e ih k + let _ := Fintype.ofEquiv B e.symm + rw [← Fintype.card_congr e] + convert (ih (k ∘ e)).rename e using 1 + funext x + rw [← e.sum_comp] + rfl + · intro k + simp only [Fintype.sum_empty] + exact (const 0).mono (by simp; omega) + · intro I _ ih k + have h := ((of_bit (F := F) (w := w) (k none)).add_disjoint (ih (k ∘ some))).rename + (optionEquiv I) + simp_rw [Fintype.sum_option] + apply h.mono + rw [Fintype.card_option] + ring_nf + omega + +theorem less [Fintype I] {g : (I → Bool) → ℕ} + (h : Register F w f m) (k : Register F w g n) + (hf : ∀ x, f x < 2 ^ w) (hg : ∀ x, g x < 2 ^ w) : + BNet F (fun x (_ : Unit) => decide (f x < g x)) (5 * Fintype.card I + m + n + 1000 * (1 + w)) + := by + have hb := (BNet.pair h k).comp (numeric_lt F w) + convert hb using 1 + funext x i + change _ = decide (Control.decode w (digits w (f x)) < Control.decode w (digits w (g x))) + simp only [digits, Equiv.apply_symm_apply] + change _ = decide (f x % 2 ^ w < g x % 2 ^ w) + rw [Nat.mod_eq_of_lt (hf x), Nat.mod_eq_of_lt (hg x)] + +end Register +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- # Addresses in a concatenation of variable-width records -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Finset +variable {J : Type} [Fintype J] [LinearOrder J] (w : J → ℕ) + +/-- Zero-based start position in the concatenation. -/ +def start (j : J) := ∑ i ∈ univ.filter (fun i => i < j), w i + +theorem start_le (j : J) (s : Finset J) (h : ∀ i ≤ j, i ∈ s) : + start w j + w j ≤ ∑ i ∈ s, w i := by + let t := univ.filter (fun i => i < j) + have ht : insert j t ⊆ s := by + intro i hi + rcases mem_insert.mp hi with rfl | hi + · exact h _ le_rfl + · exact h i (mem_filter.mp hi).2.le + have hh := sum_le_sum_of_subset (f := w) ht + rw [sum_insert (by simp [t])] at hh + exact (Nat.add_comm _ _).le.trans hh + +theorem start_left (i j : J) (h : i < j) : start w i + w i ≤ start w j := + start_le w i _ (fun _ hk => mem_filter.mpr ⟨mem_univ _, hk.trans_lt h⟩) + +theorem serial_rank {t : ℕ} (ht : Fintype.card (Lex (Σ i, Fin (w i))) = t) + (s : Lex (Σ i, Fin (w i))) : + ((Fintype.orderIsoFinOfCardEq _ ht).symm s).val = start w s.1 + s.2.val := by + let f (p : Lex (Σ i, Fin (w i))) : Fin t := ⟨start w p.1 + p.2.val, by + have h := start_le w p.1 univ (fun _ _ => mem_univ _) + have he : ∑ i, w i = t := by simpa using ht + exact (Nat.add_lt_add_left p.2.isLt _).trans_le (h.trans_eq he)⟩ + have hm : StrictMono f := by + intro p q hp + rcases Sigma.Lex.lt_def.mp hp with hl|⟨he, hl⟩ + · exact ((Nat.add_lt_add_left p.2.isLt _).trans_le (start_left w _ _ hl)).trans_le + (Nat.le_add_right _ _) + · obtain ⟨i, u⟩ := p + obtain ⟨j, v⟩ := q + change i = j at he + subst j + exact Nat.add_lt_add_left hl _ + have hs := (Fintype.bijective_iff_injective_and_card f).2 ⟨hm.injective, by simpa using ht⟩ + rw [Subsingleton.elim (Fintype.orderIsoFinOfCardEq _ ht).symm + (StrictMono.orderIsoOfSurjective f hm hs.2)] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/LocalBank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/LocalBank.lean new file mode 100644 index 0000000000..495a56d9d4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/LocalBank.lean @@ -0,0 +1,643 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.PacketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.LocalReceive +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Capacity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Vector.Cases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Skip + +/-! +# Uniform classes and their member order + +The three labels use distinct keys. Once these are specified, all +other keys and the repetition index are unrestricted. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +open Diagonal +variable {F : Type} [Field F] {n h r d : ℕ} + +open Classical in +/-- Indexes the ordered template by the coordinates of `Lex (Lex (Label n r) × Lex (Label n +r))`. -/ +abbrev OrderedTemplate (n r : ℕ) := Lex (Lex (Label n r) × Lex (Label n r)) + +open Classical in +/-- The value specified by `(group p i false, group p i true, group p (other hn i) false)`. -/ +def templateClass (hn : 2 ≤ n) (i : Fin n) (p : Template n r) : Class r := + (group p i false, group p i true, group p (other hn i) false) + +open Classical in +/-- The subtype of `s : OrderedTemplate n r` satisfying `templateClass hn i s = c`. -/ +abbrev Templates (hn : 2 ≤ n) (i : Fin n) (c : Class r) := + {s : OrderedTemplate n r // templateClass hn i s = c} + +open Classical in +/-- The quantity computed by `(r ^ n) ^ 2 / r ^ 3`. -/ +def templates (n r : ℕ) := (r ^ n) ^ 2 / r ^ 3 + +open Classical in +theorem templates_uniform (hn : 2 ≤ n) (i : Fin n) (c : Class r) : + Fintype.card (Templates hn i c) * r ^ 3 = (r ^ n) ^ 2 := by + let a : Key n := (i, false) + let b : {j // j ≠ a} := ⟨(i, true), by simp [a]⟩ + let z : {j // j ≠ b} := ⟨⟨(other hn i, false), by simp [a, (other_ne hn i).symm]⟩, + by intro he; have := congrArg (fun j => j.val.2) he; contradiction⟩ + let Z := {j // j ≠ z} → Fin r + let e₁ := (symbols n r).trans (Equiv.funSplitAt a (Fin r)) + let e₂ := ((Equiv.funSplitAt b (Fin r)).trans + ((Equiv.refl _).prodCongr (Equiv.funSplitAt z (Fin r)))).trans (Equiv.prodAssoc _ _ _).symm + let e : Template n r ≃ Class r × Z := + (e₁.trans ((Equiv.refl _).prodCongr e₂)).trans (Equiv.prodAssoc _ _ _).symm + have he (t) : (e t).1 = templateClass hn i t := rfl + let f : Templates hn i c ≃ Z := + { toFun := fun t => (e t.val).2 + invFun := fun j => ⟨e.symm (c, j), by rw [← he, e.apply_symm_apply]⟩ + left_inv := fun t => Subtype.ext (e.symm_apply_eq.mpr (Prod.ext t.2.symm rfl)) + right_inv := fun j => congrArg Prod.snd (e.apply_symm_apply (c, j)) } + rw [Fintype.card_congr f] + have hc : Fintype.card (Class r) = r ^ 3 := by simp [Class]; ring + have ht : Fintype.card (Template n r) = (r ^ n) ^ 2 := by simp [Template, Label, pow_two] + rw [← ht, Fintype.card_congr e, Fintype.card_prod, hc, mul_comm] + +open Classical in +theorem card_templates (hn : 2 ≤ n) (i : Fin n) (c : Class r) : + Fintype.card (Templates hn i c) = templates n r := + Nat.eq_div_of_mul_eq_left (pow_ne_zero _ c.1.pos.ne') (templates_uniform hn i c) + +open Classical in +/-- Computes the template index by the application `Fintype.orderIsoFinOfCardEq _ +(card_templates hn i c)`. -/ +def templateIndex (hn : 2 ≤ n) (i : Fin n) (c : Class r) : + Fin (templates n r) ≃o Templates hn i c := + Fintype.orderIsoFinOfCardEq _ (card_templates hn i c) + +variable (A : Expansion F n h) (hn : 2 ≤ n) (R : A.Report r d) (c : Class r) + +open Classical in +/-- Reindexes `A.Members hn R c` and `Templates hn R.1 c × Fin d where toFun p` by an +equivalence. -/ +def separate : A.Members hn R c ≃ Templates hn R.1 c × Fin d where + toFun p := (⟨p.1.1, p.2⟩, p.1.2) + invFun p := ⟨(p.1.val, p.2), p.1.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +open Classical in +theorem member_count : Fintype.card (A.Members hn R c) = templates n r * d := by + rw [Fintype.card_congr (separate A hn R c), Fintype.card_prod, card_templates, Fintype.card_fin] + +open Classical in +theorem members_uniform : + Fintype.card (A.Members hn R c) * r ^ 3 = Fintype.card (Packet n r d) := by + rw [member_count, ← card_templates hn R.1 c, mul_right_comm, templates_uniform hn R.1 c] + simp [Packet, Template, Label, pow_two] + +open Classical in +theorem row_major_le {k : ℕ} (x y : Fin k) (i j : Fin d) : + finProdFinEquiv (x, i) ≤ finProdFinEquiv (y, j) ↔ x < y ∨ x = y ∧ i ≤ j := by + have lt (x y : Fin k) (i j : Fin d) (h : x < y) : + finProdFinEquiv (x, i) < finProdFinEquiv (y, j) := by + change i.val + d * x.val < j.val + d * y.val + have := Nat.mul_le_mul_left d (show x.val + 1 ≤ y.val from h) + rw [mul_add, mul_one] at this + omega + rcases lt_trichotomy x y with h | rfl | h + · exact iff_of_true (lt _ _ _ _ h).le (.inl h) + · simp only [lt_self_iff_false, true_and, false_or, Fin.le_iff_val_le_val, + finProdFinEquiv_apply_val, add_le_add_iff_right] + · exact iff_of_false (lt _ _ _ _ h).not_ge (by omega) + +open Classical in +/-- Enumerate templates in order and vary the repetition index fastest. -/ +def memberIndex : MemberOrder A hn R c (templates n r * d) where + toEquiv := (finProdFinEquiv.symm.trans ((templateIndex hn R.1 c).toEquiv.prodCongr (.refl + _))).trans + (separate A hn R c).symm + map_rel_iff' := by + intro a b + obtain ⟨⟨x, i⟩, rfl⟩ := finProdFinEquiv.surjective a + obtain ⟨⟨y, j⟩, rfl⟩ := finProdFinEquiv.surjective b + simp only [Equiv.trans_apply, Equiv.symm_apply_apply] + let e := templateIndex hn R.1 c + change toLex ((e x).val, i) ≤ toLex ((e y).val, j) ↔ _ + rw [Prod.Lex.toLex_le_toLex, row_major_le] + have hh : (e x).val < (e y).val ↔ x < y := e.lt_iff_lt + simp only [hh, Subtype.val_inj, e.injective.eq_iff] + +open Classical in +theorem memberIndex_div_mod (j : Fin (templates n r * d)) : + (memberIndex A hn R c j).val = + ((templateIndex hn R.1 c j.divNat).val, j.modNat) := rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +section +/- +# Reserving a quadratic number of packet classes + +An incident class contains the worker's label in at least one of +its three coordinates. Use the first match to break ties. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +open Diagonal + +/-- Indexes the spot by the coordinates of `Fin 3 × Fin r × Fin r`. -/ +abbrev Spot (r : ℕ) := Fin 3 × Fin r × Fin r + +theorem card_spot (r : ℕ) : Fintype.card (Spot r) = 3 * r ^ 2 := by simp [Spot, pow_two] + +variable {r : ℕ} + +/-- Selects the appropriate branch of `if j.1 = 0 then (Layout.symbol u, j.2) else if j.1 = 1 +then (j.2.1, Layout.symbol u, j.2.2) else (j.2.1, j.2.2, Layout.symbol u)`. -/ +def candidate (u : Worker r) (j : Spot r) : Class r := + if j.1 = 0 then (Layout.symbol u, j.2) else + if j.1 = 1 then (j.2.1, Layout.symbol u, j.2.2) else (j.2.1, j.2.2, Layout.symbol u) + +/-- Selects the appropriate branch of `if c.1 = Layout.symbol u then (0, c.2) else if c.2.1 = +Layout.symbol u then (1, c.1, c.2.2) else (2, c.1, c.2.1)`. -/ +def locate (u : Worker r) (c : Class r) : Spot r := + if c.1 = Layout.symbol u then (0, c.2) else + if c.2.1 = Layout.symbol u then (1, c.1, c.2.2) else (2, c.1, c.2.1) + +variable {F : Type} [Field F] {n h d : ℕ} + (A : Expansion F n h) (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) (u : Worker r) + +theorem candidate_locate (c : Incident A hn N R u) : + candidate u (locate u c.val) = c.val := by + obtain ⟨⟨x, y, z⟩, he⟩ := c + have h : x = Layout.symbol u ∨ y = Layout.symbol u ∨ z = Layout.symbol u := by + simp only [Expansion.src, Expansion.dst] at he + split_ifs at he <;> rcases he with rfl | rfl <;> simp [Layout.symbol] + unfold locate + split_ifs <;> simp_all [candidate] + +/-- Embeds `Incident A hn N R u` into `Spot r where toFun`. -/ +def index : Incident A hn N R u ↪ Spot r where + toFun := fun c => locate u c.val + inj' := fun c d h => Subtype.ext <| + (candidate_locate A hn N R u c).symm.trans + ((congrArg (candidate u) h).trans (candidate_locate A hn N R u d)) + +@[simp] theorem candidate_index (c : Incident A hn N R u) : + candidate u (index A hn N R u c) = c.val := + candidate_locate A hn N R u c + +/-- Requires `let c := candidate u j (A.src hn N R (.inr c) = u ∨ A.dst hn N R (.inr c) = u) ∧ +locate u c = j`. -/ +def active (j : Spot r) : Prop := + let c := candidate u j + (A.src hn N R (.inr c) = u ∨ A.dst hn N R (.inr c) = u) ∧ locate u c = j + +theorem active_iff (j : Spot r) : + active A hn N R u j ↔ ∃ c, index A hn N R u c = j := by + constructor + · rintro ⟨hc, hj⟩ + exact ⟨⟨candidate u j, hc⟩, hj⟩ + · rintro ⟨c, rfl⟩ + unfold active + rw [candidate_index] + exact ⟨c.property, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +/- +# A fixed batch of class kernels at each worker + +A worker reserves three grids indexed by two group names. An enabled +slot computes the kernel for its class. Disabled slots return one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +open Diagonal Install Finset + +open Classical in +/-- Returns `s.share` when `j = 0` holds, and `match s with | .side x => x | .both => true | +.joint => false` otherwise. -/ +def Mode.bits (s : Mode) (j : Fin 2) : Bool := + if j = 0 then s.share else match s with + | .side x => x + | .both => true + | .joint => false + +open Classical in +/-- Computes the read by the application `if x 0 then .side (x 1) else if x 1 then .both else +.joint`. -/ +def Mode.read (x : Fin 2 → Bool) : Mode := + if x 0 then .side (x 1) else if x 1 then .both else .joint + +open Classical in +@[simp] theorem Mode.read_bits (s : Mode) : Mode.read s.bits = s := by + cases s <;> rfl + +variable {F : Type} [Field F] {n h p w r d N : ℕ} (A : Expansion F n h) + +open Classical in +/-- Indexes the frame by the coordinates of `Unit ⊕ Fin 2 ⊕ Given A p w (height A p)`. -/ +abbrev Frame (p w : ℕ) := Unit ⊕ Fin 2 ⊕ Given A p w (height A p) + +open Classical in +/-- Selects the appropriate branch of `if x (.inl ()) then closed A i (Mode.read (fun j => x +(.inr (.inl j)))) (fun j => x (.inr (.inr j))) else 1`. -/ +def frame (i : Fin n) (x : Frame A p w → Bool) := + if x (.inl ()) then closed A i (Mode.read (fun j => x (.inr (.inl j)))) + (fun j => x (.inr (.inr j))) else 1 + +open Classical in +/-- The indexed operation `∏ j, frame A i (fun k => x (j, k))`. -/ +def batch (i : Fin n) (x : Spot r × Frame A p w → Bool) := + ∏ j, frame A i (fun k => x (j, k)) + +open Classical in +/-- Indexes the frame rate by the coordinates of `4 + Fintype.card (Bool × Spectral.Cube n × Fin +h) + Fintype.card A.I + 2 * rowSize A`. -/ +def frameRate := 4 + Fintype.card (Bool × Spectral.Cube n × Fin h) + + Fintype.card A.I + 2 * rowSize A + +open Classical in +theorem frame_width : Fintype.card (Frame A p w) ≤ frameRate A * (1 + p) * (1 + w) := by + have hh := (height_bounds A p).2 + simp only [Frame, Given, PackCode.Index, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + Fintype.card_unit, frameRate] + ring_nf at hh ⊢ + omega + +open Classical in +/-- The quantity computed by `3000 * (rate A + Fintype.card (Code A) + frameRate A)`. -/ +def batchRate := 3000 * (rate A + Fintype.card (Code A) + frameRate A) + +open Classical in +theorem batch_net (i : Fin n) (hp : p < 2 ^ w) : + Weight F (batch (p := p) (w := w) (r := r) A i) + (batchRate A * r ^ 2 * (1 + p) * (1 + w) ^ 3) := by + have k := (closed_net A i Mode.read hp).branch + have hf : Weight F (frame (p := p) (w := w) A i) + (1000 * (rate A + Fintype.card (Code A) + frameRate A) * (1 + p) * (1 + w) ^ 3) := by + apply k.mono + have hh := frame_width (p := p) (w := w) A + rw [Fintype.card_sum, Fintype.card_unit] at hh + ring_nf at hh ⊢ + omega + have ht := Weight.sigma_prod (fun _ : Spot r => frame A i) (fun _ => hf) + convert ht.rename (Equiv.sigmaEquivProd _ _) using 1 <;> try rfl + simp only [sum_const, card_univ, nsmul_eq_mul, Nat.cast_id, card_spot, batchRate] + ring + +open Classical in +/-- The active slots are exactly the incident classes, each represented once. -/ +theorem batch_eq (hn : 2 ≤ n) (R : A.Report r d) (u : Worker r) + (x : Spot r × Frame A p w → Bool) + (ha : ∀ j, x (j, .inl ()) = true ↔ active A hn N R u j) + (hm : ∀ c, Mode.read (fun j => x (index A hn N R u c, .inr (.inl j))) = + modeAt A hn N R u c.val) : + batch A R.1 x = ∏ c : Incident A hn N R u, + closed A R.1 (modeAt A hn N R u c.val) (fun j => x (index A hn N R u c, .inr (.inr j))) := by + let idx := index A hn N R u + have h₀ (j : Spot r) (hj : ¬∃ c, idx c = j) : frame A R.1 (fun k => x (j, k)) = 1 := by + have h : x (j, .inl ()) ≠ true := fun h => hj ((active_iff A hn N R u j).mp ((ha j).mp h)) + exact ite_eq_right h + unfold batch + rw [prod_padded idx _ h₀] + apply prod_congr rfl + intro c _ + have h := (ha (idx c)).mpr ((active_iff A hn N R u _).mpr ⟨c, rfl⟩) + simp only [frame, h, ite_true, idx, hm] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +/- +# Random access to the scheduled channels + +Compute the endpoints and the starting position of every requested +channel. The requests themselves can depend on the input. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal Coloring +variable {F S I : Type} [Field F] [Fintype I] {N l n h r d w c : ℕ} + [LinearOrder (Name n r)] (A : Expansion F n h) (hn : 2 ≤ n) + (fa : Machine.Ports N l l → Label n r) + +open Classical in +/-- The value specified by `(Worker.index r (descriptor A hn N R j).1, Worker.index r +(descriptor A hn N R j).2.1, some j)`. -/ +def request (N : ℕ) (R : A.Report r d) (j : Name n r) : Query n r := + (Worker.index r (descriptor A hn N R j).1, Worker.index r (descriptor A hn N R j).2.1, some j) + +open Classical in +/-- Computes the base address by the application `addressSum A hn fa R.1 (request A hn N R j) +(A.countBits R)`. -/ +def baseAddress (R : A.Report r d) (j : Name n r) : ℕ := + addressSum A hn fa R.1 (request A hn N R j) (A.countBits R) + +variable (hw : Limits A N r d w) (hi : Fintype.card I ≤ 2 ^ w) + (inp : S → I → Bool) (idx : A.CountBit r d → I) (rep : S → A.Report r d) (i : Fin n) + (hc : ∀ s, (rep s).1 = i) (he : ∀ s, inp s ∘ idx = A.countBits (rep s)) + (keys : S → B w → Name n r) (row : Name n r ↪ B w) + (hk : Vector.packed (U := Vector.raw I) F inp (fun s j => (row (keys s j)).val) c) + +include hw hi hc he hk fa in +open Classical in +theorem packed_request (f : Query n r → ℕ) : + Vector.packed (U := Vector.raw I) F inp + (fun s j => f (request A hn N (rep s) (keys s j))) (max 49 c + 10) := by + have : Nonempty (Fin r) := ⟨⟨0, hw.pos⟩⟩ + have : Nonempty (Name n r) := ⟨.inl (.inr (fun _ => ⟨0, hw.pos⟩))⟩ + apply Vector.packed.fetch keys row (fun s j => f (request A hn N (rep s) j)) hk + intro t + exact packed_observe A hn fa hw hi inp idx rep i hc he t + (fun j u v => f (Worker.index r u, Worker.index r v, some (t j))) + +include hw hi hc he hk in +open Classical in +theorem packed_base : + Vector.packed (U := Vector.raw I) F inp + (fun s j => baseAddress A hn fa (rep s) (keys s j)) (max 49 c + 20) := by + have : Nonempty (Fin (3 * r)) := ⟨⟨0, Nat.mul_pos (by decide) hw.pos⟩⟩ + obtain ⟨a⟩ : Nonempty (Query n r ↪ B w) := + Function.Embedding.nonempty_of_card_le (by rw [Fintype.card_fin]; exact hw.queries) + have hq := packed_request A hn fa hw hi inp idx rep i hc he keys row hk (fun j => (a j).val) + have hb := Vector.packed.fetch (fun s j => request A hn N (rep s) (keys s j)) a + (fun s j => addressSum A hn fa (rep s).1 j (A.countBits (rep s))) hq + (packed_lengths A hn fa hw hi inp idx rep i hc he) + exact hb.mono (by omega) + +open Classical in +theorem grouping_address (R : A.Report r d) + (z : Encoded.Bits (A.extraSrc hn N R (Worker.index r) (Pin.src (A.owner hn N R ∘ fa))) + (A.extraDst hn N R (Worker.index r) (Pin.dst (A.owner hn N R ∘ fa))) (A.extraSize R)) : + (grouping fa A hn R).channels.address z = + baseAddress A hn fa R ((records fa h d).key z.1.val) + + ((records fa h d).index z.1.val * A.extraSize R z.1.val + z.2.val) := by + let p := grouping fa A hn R + unfold Channels.address baseAddress request + rw [addressSum_start, Records.Routing.channels_index, Records.Routing.channels_key] + change start _ _ + _ = start (p.channels.widthAt (p.fromKey _) (p.toKey _)) _ + _ + rw [p.atSrc, p.atDst] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # The class frames read the reported counts and the incident bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal +variable {F : Type} [Field F] [Fintype F] {N l n d r h B : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) + +open PacketKernel + +open Classical in +/-- The quantity computed by `templates n r * (B * P.count)`. -/ +abbrev packetRows (P : Format N l d n r h) (B : ℕ) := templates n r * (B * P.count) +open Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev countWidth (P : Format N l d n r h) (B : ℕ) + := Nat.clog 2 (Fintype.card (Packet n r (B * P.count)) + 1) +open Classical in +/-- Indexes the frame slot by the coordinates of `Spot r × Frame A (packetRows P B) (countWidth +P B)`. -/ +abbrev FrameSlot (P : Format N l d n r h) (A : Expansion F n h) (B : ℕ) := + Spot r × Frame A (packetRows P B) (countWidth P B) + +open Classical in +/-- In the case `.inl (j, b, k)`, this construction gives `fullBit s x (.inr (((memberIndex A hn +s.report.val c j).val, k), b))`. -/ +def given (x : LocalBit s → Bool) (c : Class r) : + Given A (packetRows P B) (countWidth P B) (height A (packetRows P B)) → Bool + | .inl (j, b, k) => fullBit s x (.inr (((memberIndex A hn s.report.val c j).val, k), b)) + | .inr (.inl (a, j)) => A.countBits s.report.val ((c, a), j) + | .inr (.inr j) => C.physicalBit s (.inr (.inr c)) j.val + +open Classical in +/-- In the case `.inl _`, this construction gives `decide (active A hn N s.report.val (workerAt +s) z.1)`. -/ +def frames (x : LocalBit s → Bool) (z : FrameSlot P A B) : Bool := + let c := candidate (workerAt s) z.1 + match z.2 with + | .inl _ => decide (active A hn N s.report.val (workerAt s) z.1) + | .inr (.inl j) => (modeAt A hn N s.report.val (workerAt s) c).bits j + | .inr (.inr j) => C.given s x c j + +open Classical in +private theorem supplied_given (x : LocalBit s → Bool) (z : Symbols s) (c : Classes s) : + supplied A hn N s.report.val (workerAt s) (localAssignment s x z) c.val + (memberIndex A hn s.report.val c.val) (C.given s x c.val) := by + intro j b k hj + let p := (((memberIndex A hn s.report.val c.val j).val, k), b) + have ht : target s (.inr (.inl p)) = s.site := (Worker.index r).eq_symm_apply.mp hj + exact (assigned_row s x z p (.inr ht)).symm + +open Classical in +theorem batch_frames (x : LocalBit s → Bool) : + batch A i (C.frames s x) = + ∑ z : Symbols s, if C.streams s z then A.factor (localAssignment s x z) (workerAt s) else 0 + := by + let R := s.report.val + let u := workerAt s + let e (c : Classes s) := memberIndex A hn R c.val + let f (c : Classes s) := C.given s x c.val + have ha (j) : C.frames s x (j, .inl ()) = true ↔ active A hn N R u j := by + simp only [frames, decide_eq_true_eq]; rfl + have hm (c : Classes s) : + Mode.read (fun j => C.frames s x (PacketKernel.index A hn N R u c, .inr (.inl j))) = + modeAt A hn N R u c.val := by + simp only [frames, R, u, candidate_index, Mode.read_bits] + have hb := batch_eq A hn R u (C.frames s x) ha hm + have h₁ : batch A i (C.frames s x) = ∏ c, closed A R.1 (modeAt A hn N R u c.val) (f c) := by + simpa only [frames, R, u, candidate_index, f, s.cut] using hb + have hs (z : Symbols s) : (∀ c, stream A (modeAt A hn N R u c.val) + (fun j => f c (.inr (.inr j))) (z c)) ↔ C.streams s z := by + unfold streams + apply forall_congr' + intro c + unfold stream + rw [modeAt_share] + have hlen := (symbol_width A (e c) (z c)).trans (PacketKernel.capacity A (packetRows P B)) + have hmod (j : Fin (A.classWidth R c.val)) : (Fin.ofNat (2 ^ height A (packetRows P B)) + j.val).val = j.val := + Nat.mod_eq_of_lt (j.isLt.trans_le hlen) + simp only [f, given, hmod]; rfl + rw [h₁, product_eq A hn N R u e f (localAssignment s x) (PacketKernel.capacity A _) (fun c z => + A.cnt_countBits R (c.val, z)) (assigned_class s x) (C.supplied_given s x)] + apply Finset.sum_congr rfl + intro z _ + exact if_congr (hs z) rfl rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- # The bank reads only incident input bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal +variable {F : Type} [Field F] [Fintype F] {N l n d r h B : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) + +open Classical in +/-- The value specified by `fullBit s x ∘ Sum.inl`. -/ +def localPins (x : LocalBit s → Bool) : Pin N l l r → Bool := fullBit s x ∘ Sum.inl + +open Classical in +/-- In the case `.inl p`, this construction gives `fullBit s x (.inr p)`. -/ +def localRows (x : LocalBit s → Bool) : A.Assignment hn N s.report.1 + | .inl p => fullBit s x (.inr p) + | .inr c => (choice (symbols_exist s)) (.inr (.inr c)) + +open Classical in +/-- Computes the bank data by the application `P.fill M A hn B s.report (localRows s x) +(Pin.input C.pad (localPins s x)) (workerAt s) C.index`. -/ +def bankData (x : LocalBit s → Bool) : M.Data → Bool := + P.fill M A hn B s.report (localRows s x) (Pin.input C.pad (localPins s x)) (workerAt s) C.index + +omit [Fintype F] in +open Classical in +private theorem pin_eq (x : LocalBit s → Bool) (z : Symbols s) (e : Pin N l l r) + (he : incident s (.inl e)) : extendLocal s x z (.inl e) = localPins s x e := by + unfold extendLocal localPins + rw [dite_eq_left he, Function.comp_apply, fullBit_at s x (.inl e) he] + rfl + +open Classical in +private theorem bankData_eq (hw : P.which = (Format.prescribed d h P.count P.colors).which) + (x : LocalBit s → Bool) (z : Symbols s) : + P.fill M A hn B s.report (localAssignment s x z) + (Pin.input C.pad (fun e => extendLocal s x z (.inl e))) (workerAt s) C.index = C.bankData s x + := by + funext j + unfold bankData Format.fill + split_ifs with h + · apply congrArg (fun f => Function.extend (C.index j.1 (Layout.symbol (workerAt s))) f + (fun _ => false) j.2.2) + funext k + split_ifs with hk + · rw [congrFun hw k.val] at hk + rcases k with ⟨v|⟨p, b⟩|e|e, hk'⟩ + · rfl + · apply assigned_row + left + exact (Worker.index r).eq_symm_apply.mp hk + · apply Pin.input_local + intro q hq + apply pin_eq + right + apply (Worker.index r).eq_symm_apply.mp + change A.owner hn N s.report.val (P.colors q.position) = workerAt s + rw [hq] + exact hk + · rfl + · rfl + · rfl + +open Classical in +theorem joint_eq (hw : P.which = (Format.prescribed d h P.count P.colors).which) + (x : LocalBit s → Bool) (z : Symbols s) : + C.joint s.report s.script (C.code (some (s.site, s.script))) (workerAt s) + (fun e => extendLocal s x z (.inl e)) (localAssignment s x z) = + Pin.mask F (workerAt s) (C.code (some (s.site, s.script))) (localPins s x) * + (M.result F (Sum.elim (C.bankData s x) s.script) * A.factor (localAssignment s x z) + (workerAt s)) := by + unfold joint + rw [C.bankData_eq s hw] + apply congrArg (· * _) + apply Pin.mask_local _ _ _ _ (P.route A hn B s.report) + intro e he + exact pin_eq s x z e (.inl ((Worker.index r).eq_symm_apply.mp he)) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- +# Batched reads on the physical communication tape + +Channel keys are numbered statically. A request specifies a key and a +bit position within that channel. Reduction of addresses modulo the +lane count is harmless on the actual wire positions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l n d r h B w c : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) [LinearOrder (Name n r)] + +open Classical in +/-- The value specified by `(grouping P.colors A hn R.1).channels`. -/ +abbrev channels (R : P.Reports A hn B) := (grouping P.colors A hn R.1).channels + +open Classical in +/-- Uses `{ C with number := fun R => (channels R).serial }` as the representation. -/ +def numberInOrder : Controller P A hn M B := + { C with number := fun R => (channels R).serial } + +variable {i : Fin n} +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +variable [NeZero (N / 4)] [NeZero (3 * r)] + +open Classical in +/-- The get of type `Bool`, constructed using `request A hn N s.report.1 j`. -/ +def get (w : ℕ) (s : X) (j : Name n r) (k : ℕ) : Bool := + let q := request A hn N s.report.1 j + let x := (baseAddress A hn P.colors s.report.1 j + k) % 2 ^ w + s.physical (Fin.ofNat (N / 4) (routeAddress N (pairCount s.report) s.site q.1 q.2.1 x % 2 ^ w)) + +open Classical in +theorem packed_get (hw : Limits A N r (B * P.count) w) (hi : Fintype.card (Machine.Ports N l l) + ≤ 2 ^ w) + (key : X → Coloring.B w → Name n r) (idx : Name n r ↪ Coloring.B w) (k : Vector.Array X w) + (hp : packed (U := raw _) F C.input (fun s j => (idx (key s j)).val) c) + (hk : packed (U := raw _) F C.input k c) : + packed (U := raw _) F C.input (fun s j => (get w s (key s j) (k s j)).toNat) (c + 250) := by + let rep (s : X) := s.report.1 + have hg := packed_request A hn P.colors hw hi C.input C.countPort rep i Invocation.cut + C.counts_eq key idx hp + have hb := packed_base A hn P.colors hw hi C.input C.countPort rep i Invocation.cut + C.counts_eq key idx hp + have hh := C.packed_skip hw hi C.input C.countPort (fun s : X + => s.report) i Invocation.cut C.counts_eq + have hu := C.worker_net (i := i) hi ((Nat.le_pow (by decide : 0 < 5)).trans hw.pairs) + let physical (p : Coloring.B w) : Machine.Ports N l l := .inr (.inr (Fin.ofNat (N / 4) p.val)) + have hread := packed.named F (C.input (i := i)) physical (c := 0) (by simpa using hi) + have hr := hw.pos + have hcap := (Nat.pow_le_pow_right (NeZero.pos (3 * r)) (by decide : 2 ≤ 5)).trans hw.pairs + let q (s : X) (j : Coloring.B w) := request A hn N (rep s) (key s j) + apply packed.read_channel (N := N) (c := c + 82) (a := fun s j => (q s j).1) + (b := fun s j => (q s j).2.1) (u := fun s _ => s.site) (by omega) hcap + (hh.mono (by omega)) (hu.mono (by omega)) + ((hg (fun a => a.1.val)).mono (by omega)) ((hg (fun a => a.2.1.val)).mono (by omega)) + ((hb.add hk).reduce.mono (by omega)) (hread.mono (by omega)) + · intro s u v + exact (Links.skip_lt_of_load (C.pairSum s.report) C.links u v).trans_le hw.bits + · exact fun _ _ => Nat.mod_lt _ (pow_pos (by decide) _) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/LocalReceive.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/LocalReceive.lean new file mode 100644 index 0000000000..866eeed5e8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/LocalReceive.lean @@ -0,0 +1,1059 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.PacketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Replay +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Skip +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Vector.Cases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.AddressSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.DispatchSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.TemplateSize + +/-! # Exact semantics of the worker's packet kernel -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel + +open Diagonal Finset +variable {F : Type} [Field F] {n h p w t r N d : ℕ} (A : Expansion F n h) + {hn : 2 ≤ n} {R : A.Report r d} {c : Class r} + +open Classical in +/-- Requires `symbol A e z = raw A x ∧ (mode.share = true → ∀ j, A.alphabetCode hn N R c z j = +compact A x (Fin.ofNat (2 ^ t) j.val))`. -/ +def agrees (e : MemberOrder A hn R c p) (mode : Mode) (x : Inputs A p w t → Bool) + (z : A.Alphabet hn N R c) : Prop := + symbol A e z = raw A x ∧ (mode.share = true → + ∀ j, A.alphabetCode hn N R c z j = compact A x (Fin.ofNat (2 ^ t) j.val)) + +open Classical in +/-- The product of type `F` for the given inputs. -/ +def product (e : MemberOrder A hn R c p) (mode : Mode) (x : Inputs A p w t → Bool) + (z : A.Alphabet hn N R c) : F := + ∏ j, modeValue A mode (z.1.val (e j)) R.1 (fun s => row A x j (.inl (false, s))) + (fun s => row A x j (.inl (true, s))) (A.shared N R c) (z.2 (e j)) + +open Classical in +private theorem check_iff (e : MemberOrder A hn R c p) (mode : Mode) (x : Inputs A p w t → Bool) + (z : A.Alphabet hn N R c) (hz : symbol A e z = raw A x) + (hcut : mode.cut = A.shared N R c) (hcap : p * (prefixSize A + reserve A) ≤ 2 ^ t) : + (mode.share = true → PackCode.Matches t (valueAt A x) (markAt A R.1 mode x) (compact A x)) ↔ + agrees A e mode x z := by + simp only [agrees, hz, true_and] + by_cases hm : mode.share = true + · have hh : A.shared N R c = true := by + rw [← hcut] + cases mode <;> simp_all [Mode.share, Mode.cut] + have h := (symbol_width A e z).trans hcap + have he (j : Fin (A.classWidth R c)) : Fin.ofNat (2 ^ t) j.val = Fin.castLE h j := + Fin.ext (Nat.mod_eq_of_lt (j.isLt.trans_le h)) + simp only [hm, true_implies, match_code A e z mode x hz hcut hh hcap, funext_iff, + Function.comp_apply, he] + · simp [hm] + +open Classical in +/-- Each private code string represents at most one class symbol. +Ill-formed code strings contribute zero. -/ +theorem kernel_eq (e : MemberOrder A hn R c p) (mode : Mode) (x : Inputs A p w t → Bool) + (hcut : mode.cut = A.shared N R c) (hcap : p * (prefixSize A + reserve A) ≤ 2 ^ t) + (he : ∀ s, expected A x s = (R.2 (c, s)).val) : + kernel A R.1 mode x = ∑ z : A.Alphabet hn N R c, + if agrees A e mode x z then product A e mode x z else 0 := by + by_cases ht : ∃ z : A.Alphabet hn N R c, symbol A e z = raw A x + · have hc := ((symbol_iff A e x).mpr ht).2 + obtain ⟨z, hz⟩ := ht + rw [Fintype.sum_eq_single z] + · simp only [kernel, he, hc, implies_true, true_and, check_iff A e mode x z hz hcut hcap] + congr 1 + exact prod_congr rfl fun j _ => entry_encode A R.1 mode _ hcut _ _ _ (congrFun hz j).symm + · intro z' hn + exact ite_eq_right fun h => hn (symbol_injective A e (h.1.trans hz.symm)) + · have hall (z : A.Alphabet hn N R c) : ¬ agrees A e mode x z := fun hz => ht ⟨z, hz.1⟩ + simp only [hall, ite_false, sum_const_zero, kernel] + split_ifs with hk + · have hb : ¬∀ j, ok A R.1 mode.cut (raw A x j) := by + intro hv + apply ht + apply (symbol_iff A e x).mp + exact ⟨hcut ▸ hv, fun s => (hk.1 s).trans (he s)⟩ + obtain ⟨j, hj⟩ := not_forall.mp hb + apply prod_eq_zero (mem_univ j) + exact ite_eq_right hj + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +/- +# Summing the private records of a packet class + +The external positions supply the packet data, the reported counts, +and the compacted stream. Each contributing symbol has exactly one +fixed-width encoding in the private positions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel + +open Diagonal Install +variable {F : Type} [Field F] {n h r d N p w t : ℕ} (A : Expansion F n h) + {hn : 2 ≤ n} {R : A.Report r d} {c : Class r} + +open Classical in +/-- Indexes the given by the coordinates of `(Fin p × Bool × Spectral.Cube n × Fin h) ⊕ (A.I × +Fin w) ⊕ PackCode.Index t`. -/ +abbrev Given (p w t : ℕ) := + (Fin p × Bool × Spectral.Cube n × Fin h) ⊕ (A.I × Fin w) ⊕ PackCode.Index t +open Classical in +/-- Indexes the private by the coordinates of `Fin p × Code A`. -/ +abbrev Private (p : ℕ) := Fin p × Code A + +open Classical in +/-- Reindexes `Inputs A p w t` and `Given A p w t ⊕ Private A p` by an equivalence. -/ +def layout : Inputs A p w t ≃ Given A p w t ⊕ Private A p := + ((Equiv.prodSumDistrib _ _ _).sumCongr (.refl _)).trans + ((Equiv.sumAssoc _ _ _).trans + (((Equiv.refl _).sumCongr (Equiv.sumComm _ _)).trans (Equiv.sumAssoc _ _ _).symm)) + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def assemble (x : Given A p w t → Bool) (y : Private A p → Bool) : Inputs A p w t → Bool := + Sum.elim x y ∘ layout A + +open Classical in +/-- The sum of `kernel A i mode (assemble A x y)` indexed by `y`. -/ +def closed (i : Fin n) (mode : Mode) (x : Given A p w t → Bool) : F := + ∑ y, kernel A i mode (assemble A x y) + +open Classical in +theorem closed_net (i : Fin n) (pick : (Fin 2 → Bool) → Mode) (hp : p < 2 ^ w) : + Weight F (fun x : Fin 2 ⊕ Given A p w (height A p) → Bool => + closed A i (pick (x ∘ Sum.inl)) (x ∘ Sum.inr)) + (rate A * (1 + p) * (1 + w) ^ 3 + p * Fintype.card (Code A)) := by + let e := ((Equiv.refl (Fin 2)).sumCongr (layout (p := p) (w := w) (t := height A p) A)).trans + (Equiv.sumAssoc _ _ _).symm + have h := ((switched_net A i pick hp).rename e).sum_right + rw [Fintype.card_prod, Fintype.card_fin] at h + convert h using 1 + funext x + unfold closed + apply Finset.sum_congr rfl + intro y _ + apply congrArg + funext j + change Sum.elim (x ∘ Sum.inr) y (layout A j) = Sum.elim x y ((Equiv.sumAssoc _ _ _).symm (.inr + (layout A j))) + cases layout A j <;> rfl + +open Classical in +/-- Requires `mode.share = true → ∀ j, A.alphabetCode hn N R c z j = data (Fin.ofNat (2 ^ t) +j.val)`. -/ +def stream (mode : Mode) (data : PackCode.Index t → Bool) (z : A.Alphabet hn N R c) : Prop := + mode.share = true → ∀ j, A.alphabetCode hn N R c z j = data (Fin.ofNat (2 ^ t) j.val) + +open Classical in +/-- The term of type `F` for the given inputs. -/ +def term (e : MemberOrder A hn R c p) (mode : Mode) (x : Given A p w t → Bool) + (z : A.Alphabet hn N R c) : F := + ∏ j, modeValue A mode (z.1.val (e j)) R.1 (fun k => x (.inl (j, false, k))) + (fun k => x (.inl (j, true, k))) (A.shared N R c) (z.2 (e j)) + +open Classical in +theorem closed_eq (e : MemberOrder A hn R c p) (mode : Mode) (x : Given A p w t → Bool) + (hcut : mode.cut = A.shared N R c) (hcap : p * (prefixSize A + reserve A) ≤ 2 ^ t) + (he : ∀ s, number (fun j => x (.inr (.inl (s, j)))) = (R.2 (c, s)).val) : + closed A R.1 mode x = ∑ z : A.Alphabet hn N R c, + if stream A mode (fun j => x (.inr (.inr j))) z then term A e mode x z else 0 := by + have hh (y) := kernel_eq A e mode (assemble A x y) hcut hcap he + unfold closed + simp_rw [hh] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro z _ + rw [Fintype.sum_eq_single (Function.uncurry (symbol A e z))] + · have hs : symbol A e z = raw A (assemble A x (Function.uncurry (symbol A e z))) := rfl + have he : agrees A e mode (assemble A x (Function.uncurry (symbol A e z))) z ↔ + stream A mode (fun j => x (.inr (.inr j))) z := by + simp only [agrees, ← hs, true_and] + rfl + simp only [he] + rfl + · intro y hy + apply ite_eq_right + intro h + exact hy (congrArg Function.uncurry h.1.symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +/- +# The packet contribution at one worker + +Only data delivered to the worker can affect its factor. In particular +the remaining rows of the fixed layout may be filled with zeros. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel + +open Finset Diagonal +variable {F : Type} [Field F] {n h r d p w t : ℕ} (A : Expansion F n h) + (hn : 2 ≤ n) (N : ℕ) (R : A.Report r d) (u : Worker r) + +open Classical in +/-- The subtype of `c : Class r` satisfying `A.src hn N R (.inr c) = u ∨ A.dst hn N R (.inr c) = +u`. -/ +abbrev Incident := + {c : Class r // A.src hn N R (.inr c) = u ∨ A.dst hn N R (.inr c) = u} + +open Classical in +/-- Selects the appropriate branch of `if l then if left = right then .both else .side (decide +(right = u)) else .joint`. -/ +def chooseMode (l : Bool) (left right u : Worker r) : Mode := + if l then if left = right then .both else .side (decide (right = u)) else .joint + +open Classical in +/-- Computes the mode at by the application `chooseMode (A.shared N R c) (A.src hn N R (.inr c)) +(A.dst hn N R (.inr c)) u`. -/ +def modeAt (c : Class r) : Mode := + chooseMode (A.shared N R c) (A.src hn N R (.inr c)) (A.dst hn N R (.inr c)) u + +open Classical in +theorem modeAt_cut (c : Class r) : (modeAt A hn N R u c).cut = A.shared N R c := by + unfold modeAt chooseMode + split_ifs <;> simp_all [Mode.cut] + +open Classical in +theorem modeAt_share (c : Class r) : + (modeAt A hn N R u c).share = true ↔ A.src hn N R (.inr c) ≠ A.dst hn N R (.inr c) := by + unfold modeAt chooseMode + split_ifs <;> simp_all [Mode.share, Expansion.src, Expansion.dst] + +open Classical in +private theorem pieces (s : A.I) (i : Fin n) (x y : Block n h) (l : Bool) + (v : Fin (A.width s i l) → Bool) (left right : Worker r) + (hl : l = false → left = right) (hu : left = u ∨ right = u) : + (∏ b : Bool, if (if b then right else left) = u then A.piece s i x y b l v else 1) = + modeValue A (chooseMode l left right u) s i x y l v := by + cases l + · obtain rfl := hl rfl + have h := hu.elim id id + simp [h, Expansion.piece, modeValue] + · by_cases he : left = right + · subst right + have h := hu.elim id id + simp [chooseMode, h, Expansion.piece, modeValue, Expansion.value, mul_comm] + · rcases hu with rfl | rfl <;> simp [chooseMode, he, Ne.symm he, Expansion.piece, modeValue] + +open Classical in +private def contribution (a : A.Assignment hn N R) (c : Class r) : F := + ∏ b, if A.worker hn N R c b = u then A.half a c b else 1 + +open Classical in +/-- The condition `∀ j b k, A.dst hn N R (.inl (((e j).val, k), b)) = u → x (.inl (j, b, k)) = +A.rows a b (e j).val k` on the specified data. -/ +def supplied (a : A.Assignment hn N R) (c : Class r) (e : MemberOrder A hn R c p) + (x : Given A p w t → Bool) : Prop := + ∀ j b k, A.dst hn N R (.inl (((e j).val, k), b)) = u → + x (.inl (j, b, k)) = A.rows a b (e j).val k + +open Classical in +private theorem term_eq (a : A.Assignment hn N R) (c : Incident A hn N R u) + (e : MemberOrder A hn R c.val p) (x : Given A p w t → Bool) + (hx : supplied A hn N R u a c.val e x) : + contribution A hn N R u a c.val = term A e (modeAt A hn N R u c.val) x (a (.inr c.val)) := by + let z := a (.inr c.val) + let f (b : Bool) (j : Fin p) := + A.piece (z.1.val (e j)) R.1 (fun k => x (.inl (j, false, k))) (fun k => x (.inl (j, true, k))) b + (A.shared N R c.val) (z.2 (e j)) + have hb (b : Bool) : (if A.worker hn N R c.val b = u then A.half a c.val b else 1) = + ∏ j, if A.worker hn N R c.val b = u then f b j else 1 := by + by_cases he : A.worker hn N R c.val b = u + · simp only [he, ite_true, Expansion.half] + rw [← e.toEquiv.prod_comp] + apply prod_congr rfl + intro j _ + apply A.piece_local + · intro k hk + exact (hx j false k ((A.row_dst hn N R c.val (e j) k false b hk).trans he)).symm + · intro k hk + have ht : A.shared N R c.val = true → (!(k.1 R.1)) = b := fun h => + (show ∀ x y : Bool, x ≠ y → (!x) = y by decide) _ _ (hk h) + exact (hx j true k ((A.row_dst hn N R c.val (e j) k true b ht).trans he)).symm + · simp [he] + unfold contribution term + simp only [hb] + rw [prod_comm] + apply prod_congr rfl + intro j _ + apply pieces + · intro hs + simp [Expansion.src, Expansion.dst, hs] + · exact c.property + +open Classical in +private theorem product_contribution (a : A.Assignment hn N R) : + A.factor a u = ∏ c : Incident A hn N R u, contribution A hn N R u a c.val := by + let s := univ.filter (fun c => A.src hn N R (.inr c) = u ∨ A.dst hn N R (.inr c) = u) + rw [← prod_subtype s (by simp [s])] + symm + apply prod_subset (subset_univ _) + intro c _ hc + simp only [s, mem_filter, mem_univ, true_and, not_or] at hc + unfold contribution + apply prod_eq_one + intro b _ + cases b <;> simp [Expansion.worker, hc] + +open Classical in +/-- The indexing data represented by `(c : Incident A hn N R u) → A.Alphabet hn N R c.val`. -/ +abbrev Family := (c : Incident A hn N R u) → A.Alphabet hn N R c.val + +open Classical in +/-- Private summation in the class kernels computes exactly the worker's +sum over incident symbols, constrained by the received physical bits. +Slots whose destination is another worker are unrestricted. -/ +theorem product_eq + (e : (c : Incident A hn N R u) → MemberOrder A hn R c.val p) + (x : Incident A hn N R u → Given A p w t → Bool) + (a : Family A hn N R u → A.Assignment hn N R) + (hcap : p * (prefixSize A + reserve A) ≤ 2 ^ t) + (he : ∀ c s, number (fun j => x c (.inr (.inl (s, j)))) = (R.2 (c.val, s)).val) + (ha : ∀ z c, a z (.inr c.val) = z c) + (hx : ∀ z c, supplied A hn N R u (a z) c.val (e c) (x c)) : + (∏ c, closed A R.1 (modeAt A hn N R u c.val) (x c)) = + ∑ z : Family A hn N R u, + if ∀ c, stream A (modeAt A hn N R u c.val) (fun j => x c (.inr (.inr j))) (z c) + then A.factor (a z) u else 0 := by + have hh (c) := closed_eq A (e c) (modeAt A hn N R u c.val) (x c) + (modeAt_cut A hn N R u c.val) hcap (he c) + simp_rw [hh] + rw [Fintype.prod_sum] + apply sum_congr rfl + intro z _ + have hf : A.factor (a z) u = ∏ c, term A (e c) (modeAt A hn N R u c.val) (x c) (z c) := by + rw [product_contribution] + apply prod_congr rfl + intro c _ + rw [term_eq A hn N R u (a z) c _ _ (hx z c), ha] + simp only [prod_ite_zero, mem_univ, forall_const, hf] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +section +/- # Network cost of checking the physical link schedule -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed + +open Coloring Diagonal.Links +variable {F S I : Type} [Field F] [Fintype I] {w R N c : ℕ} {inp : S → I → Bool} + +private def test (u low sender relay mate idx limit here there : ℕ) := + let off := if u = low then (if here = 0 then 1 else 0) else 1 + let on := if relay = u then (if mate = u then 1 else (if here = there then 1 else 0)) else 1 + if sender = mate then off else if idx < limit then on else off + +private theorem test_le (u l a v b k q x y : ℕ) : test u l a v b k q x y ≤ 1 := by + simp only [test] + split_ifs <;> decide + +private theorem test_eq (u : Fin R) (q : Fin R → Fin R → ℕ) (t : ℕ → Bool) (p : Slot R N) : + test u.val p.1.val.1.val (sender p).val (relay p).val (mate q p).val + (Diagonal.Links.index q p) (q (sender p) (mate q p)) (t (address p).val).toNat + (t (peer q p)).toNat = 1 ↔ relayCheck q u t p := by + simp only [test, relayCheck, active, ← Fin.ext_iff] + cases t (address p).val <;> cases t (peer q p) <;> simp <;> grind + +private theorem test_net {u l a v b k q x y : Array S w} + (hu : packed (U := raw I) F inp u c) (hl : packed (U := raw I) F inp l c) + (ha : packed (U := raw I) F inp a c) (hv : packed (U := raw I) F inp v c) + (hb : packed (U := raw I) F inp b c) (hk : packed (U := raw I) F inp k c) + (hq : packed (U := raw I) F inp q c) (hx : packed (U := raw I) F inp x c) + (hy : packed (U := raw I) F inp y c) (hu' : fits u) (hl' : fits l) (ha' : fits a) + (hv' : fits v) (hb' : fits b) (hk' : fits k) (hq' : fits q) (hx' : fits x) (hy' : fits y) : + packed (U := raw I) F inp (fun s i => + test (u s i) (l s i) (a s i) (v s i) (b s i) (k s i) (q s i) (x s i) (y s i)) (c + 114) := by + have c0 := const (U := raw I) F inp (fun _ => 0) hu.width + have c1 := const (U := raw I) F inp (fun _ => 1) hu.width + have off := hu.choose_eq hl (hx.choose_eq c0 c1 c0 hx' (fun _ _ => Nat.two_pow_pos _)) c1 hu' hl' + have on := hv.choose_eq hu (hb.choose_eq hu c1 (hx.choose_eq hy c1 c0 hx' hy') hb' hu') c1 hv' hu' + exact (ha.choose_eq hb off (hk.select hq on off hk' hq') ha' hb').mono (by omega) + +open Classical in +/-- A single circuit checks all unused-slot pins and relay equalities. +The pair counts, skip offsets and current processor may vary with the +input. The link tape is selected by a fixed list of bit names. -/ +theorem valid [NeZero R] {q : S → Fin R → Fin R → ℕ} {u : S → Fin R} + (hr : 2 ≤ R) (hn : 64 * R ^ 2 ≤ N) (hw : N ≤ 2 ^ w) + (hs : ∀ s a b, q s a b = q s b a) (hq : ∀ s a, ∑ b, q s a b ≤ N / 64) + (hcount : packed (U := raw I) F inp (matrix w q) c) + (hskip : packed (U := raw I) F inp (matrix w (fun s => Diagonal.Links.skip (q s))) c) + (hu : packed (U := raw I) F inp (fun s (_ : B w) => (u s).val) c) + (t : Fin (N / 4) → I) : + ∃ b : (I → Bool) → Unit → Bool, Install.BNet F b (2 ^ w * (100 + w) ^ (c + 416)) ∧ + ∀ s, b (inp s) () = decide (Diagonal.Links.valid (hs s) (hq s) hn (u s) (inp s ∘ t)) := by + have hr' : R ≤ R ^ 2 := Nat.le_pow (by decide) + have h2 : 1 < 2 ^ w := by omega + have h1 : 1 ≤ w := Nat.one_le_iff_ne_zero.mpr (fun h => by simp [h] at h2) + let _ : NeZero (N / 4) := ⟨by omega⟩ + let ix (j : B w) := t (Fin.ofNat (N / 4) j.val) + let tape (s : S) (j : ℕ) := inp s (ix (Fin.ofNat (2 ^ w) j)) + have ht (s : S) : (fun i : Fin (N / 4) => tape s i.val) = inp s ∘ t := by + funext i + have hi : i.val < 2 ^ w := by omega + have he : Fin.ofNat (N / 4) (Fin.ofNat (2 ^ w) i.val).val = i := + Fin.ext (by simp only [Fin.val_ofNat, Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt i.isLt]) + simp only [tape, ix, he, Function.comp_apply] + obtain ⟨p, hp, hcover, ha, hrelay, hj, hlo, haddr⟩ := relay_lanes hr hn hw hu + obtain ⟨hm, hk, hlen, hpeer⟩ := + decode_slot hn hw hq (hcount.mono (by omega)) (hskip.mono (by omega)) ha hrelay hj + have hbit := named F inp ix hu.width + have hx := hbit.lookup haddr + have hy := hbit.lookup hpeer + have fit (a : S → B w → Fin R) : fits (fun s i => (a s i).val) := + fun s i => (a s i).isLt.trans_le (by omega) + have hkey : fits (fun s i => Diagonal.Links.index (q s) (p s i)) := + fun _ _ => (index_lt_of_size _).trans_le hw + have hq' (s) (a b : Fin R) : q s a b < 2 ^ w := by + have hg := (Finset.single_le_sum (fun i _ => Nat.zero_le (q s a i)) (Finset.mem_univ b)).trans + (hq s a) + omega + have hb (b : Bool) : b.toNat < 2 ^ w := by cases b <;> simp [h2] + let f (s : S) (i : B w) := + let j := p s i + test (u s).val j.1.val.1.val (sender j).val (relay j).val (mate (q s) j).val + (Diagonal.Links.index (q s) j) (q s (sender j) (mate (q s) j)) (tape s (address j).val).toNat + (tape s (peer (q s) j)).toNat + have hf : packed (U := raw I) F inp f (c + 300 + 114) := + test_net (hu.mono (by omega)) (hlo.mono (by omega)) (ha.mono (by omega)) + (hrelay.mono (by omega)) (hm.mono (by omega)) (hk.mono (by omega)) + (hlen.mono (by omega)) (hx.mono (by omega)) (hy.mono (by omega)) + (fit _) (fit _) (fit _) (fit _) (fit _) hkey (fun s _ => hq' s _ _) + (fun _ _ => hb _) (fun _ _ => hb _) + obtain ⟨b, hb, he⟩ := conjunction h1 hf (fun s i => (test_le ..).trans_lt h2) + refine ⟨b, hb, fun s => ?_⟩ + rw [he, decide_eq_decide, ← ht, valid_iff_check] + constructor + · intro h p' hp' + obtain ⟨i, rfl⟩ := hcover s p' hp' + exact (test_eq ..).mp (h i) + · intro h i + exact (test_eq ..).mpr (h _ (hp s i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +/- +# Pair lengths and processor offsets for accepted reports + +The register bound need only hold at the guaranteed input reports. +All circuit statements still involve a single computation independent +of the report. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal Install Coloring +variable {F S I : Type} [Field F] [Fintype I] {N l n h r d w : ℕ} + [LinearOrder (Name n r)] (A : Expansion F n h) (hn : 2 ≤ n) + (fa : Machine.Ports N l l → Label n r) + +open Classical in +/-- Bounds with slack so all addresses in the table fit in a register. -/ +structure Limits (A : Expansion F n h) (N r d w : ℕ) : Prop where + large : 100000000 ≤ w + cube : 2 ^ n ≤ w + bits : N ≤ 2 ^ w + pos : 0 < r + power : r ^ (16 * n) ≤ 2 ^ w + pairs : (3 * r) ^ 5 ≤ 2 ^ w + selectors : Fintype.card A.I ≤ w + charge : ∀ i z, 512 * A.chargeBits i z ≤ w + packets : Fintype.card (Packet n r d) < (2 ^ w) ^ 8 + queries : Fintype.card (Query n r) ≤ 2 ^ w + counts : Fintype.card (A.CountBit r d) ≤ 2 ^ w + +open Classical in +private theorem capacity_bound {X Y Z w : ℕ} (hX : X ≤ 2 ^ w) (hY : Y ≤ 2 ^ w) (hZ : Z ≤ 2 ^ w) : + X + 4 * 2 ^ w * w + Z * w + (X + 2 * Y + 2 ^ w * w ^ 48) ≤ 2 ^ w * (100 + w) ^ 49 := by + have he : 1 + w ≤ (100 + w) ^ 48 := + (by omega : 1 + w ≤ 100 + w) |>.trans (Nat.le_pow (by decide : 0 < 48)) + have hp : w ^ 48 ≤ (100 + w) ^ 48 := by gcongr; omega + calc + _ ≤ 2 ^ w + 4 * 2 ^ w * w + 2 ^ w * w + (2 ^ w + 2 * 2 ^ w + 2 ^ w * w ^ 48) := by gcongr + _ = 2 ^ w * (4 + 5 * w + w ^ 48) := by ring + _ ≤ 2 ^ w * ((100 + w) ^ 48 * 6) := by apply Nat.mul_le_mul_left; omega + _ ≤ _ := by + rw [show (100 + w) ^ 49 = (100 + w) ^ 48 * (100 + w) from pow_succ ..]; gcongr; omega + +open Classical in +theorem packed_lengths (hw : Limits A N r d w) (hi : Fintype.card I ≤ 2 ^ w) + (inp : S → I → Bool) (idx : A.CountBit r d → I) (rep : S → A.Report r d) (i : Fin n) + (hc : ∀ s, (rep s).1 = i) (he : ∀ s, inp s ∘ idx = A.countBits (rep s)) + (q : B w → Query n r) : + Vector.packed (U := Vector.raw I) F inp + (fun s j => addressSum A hn fa (rep s).1 (q j) (A.countBits (rep s))) 49 := by + have hg := (addresses_size A hn fa i hw.large hw.bits hw.pos hw.power hw.cube hw.selectors + (hw.charge i) hw.packets).1.pull idx + refine Vector.packed.reshape _ q hg (capacity_bound hi hw.counts hw.queries) ?_ + intro s j b + rw [he, hc] + rfl + +variable [Fintype F] {t B : ℕ} {P : Processor.Format N l t n r h} + {M : Bank (Fin n)} {A hn} (C : Controller P A hn M B) + +namespace Controller + +open Classical in +/-- The pair count of type `Fin (3 * r) → Fin (3 * r) → ℕ` for the given inputs. -/ +def pairCount (R : P.Reports A hn B) : Fin (3 * r) → Fin (3 * r) → ℕ := + Links.count (Encoded.left (A.extraSrc hn N R.1 (Worker.index r) (Pin.src (P.route A hn B R))) + (A.extraDst hn N R.1 (Worker.index r) (Pin.dst (P.route A hn B R))) (A.extraSize R.1)) + (Encoded.right (A.extraSrc hn N R.1 (Worker.index r) (Pin.src (P.route A hn B R))) + (A.extraDst hn N R.1 (Worker.index r) (Pin.dst (P.route A hn B R))) (A.extraSize R.1)) + +omit [LinearOrder (Name n r)] in +include C in +open Classical in +theorem pairSum (R : P.Reports A hn B) (u : Fin (3 * r)) : + ∑ v, pairCount R u v ≤ N / 64 := + Encoded.count_bound _ _ _ + (A.extra_bound hn N R.1 (Worker.index r) R.2.2 _ _ (C.pins R.1)) u + +variable [NeZero (3 * r)] (hw : Limits A N r (B * P.count) w) (hi : Fintype.card I ≤ 2 ^ w) + (inp : S → I → Bool) (idx : A.CountBit r (B * P.count) → I) + (rep : S → P.Reports A hn B) (i : Fin n) + (hc : ∀ s, (rep s).1.1 = i) (he : ∀ s, inp s ∘ idx = A.countBits (rep s).1) + +omit [Fintype F] in +include hw hi hc he in +open Classical in +theorem packed_count : + Vector.packed (U := Vector.raw I) F inp (Vector.matrix w (fun s => pairCount (rep s))) 49 := by + let get (u : Coloring.B w) : Query n r := + ((Vector.atPair (3 * r) u).1, (Vector.atPair (3 * r) u).2, none) + have hp := packed_lengths A hn P.colors hw hi inp idx (fun s => (rep s).1) i hc he get + convert hp using 1 + funext s j + unfold Vector.matrix get + rw [addressSum_total] + exact (grouping P.colors A hn (rep s).1).channels.count _ _ + +include C hw hi hc he in +open Classical in +theorem packed_skip : + Vector.packed (U := Vector.raw I) F inp (Vector.matrix w (fun s + => Links.skip (pairCount (rep s)))) 62 := by + apply (packed_count hw hi inp idx rep i hc he).skip hw.pairs + intro s u v + have ht : pairCount (rep s) u v ≤ N / 64 := + (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ v)).trans (C.pairSum _ u) + have := Nat.lt_two_pow_self (n := w) + have := hw.large + have := hw.bits + omega + +end Controller +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Inspecting arbitrary endpoint metadata in parallel -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal Install + +variable {F S I : Type} [Field F] [Fintype I] {N l n h r d w : ℕ} + [LinearOrder (Name n r)] (A : Expansion F n h) (hn : 2 ≤ n) + (fa : Machine.Ports N l l → Label n r) + +include fa in +open Classical in +theorem packed_observe (hw : Limits A N r d w) (hi : Fintype.card I ≤ 2 ^ w) + (inp : S → I → Bool) (idx : A.CountBit r d → I) (rep : S → A.Report r d) (i : Fin n) + (hc : ∀ s, (rep s).1 = i) (he : ∀ s, inp s ∘ idx = A.countBits (rep s)) + (keys : Coloring.B w → Name n r) (f : Coloring.B w → Worker r → Worker r → ℕ) : + Vector.packed (U := Vector.raw I) F inp (fun s j => + f j (descriptor A hn N (rep s) (keys j)).1 (descriptor A hn N (rep s) (keys j)).2.1) 49 := by + let read (t : Fin r → Bool) (p : Coloring.B w × slots (word w)) := + let q := pairOf hn i t (keys p.1) + digits w (f p.1 q.1 q.2) p.2 + have hr : Depends read 3 := by + intro p + obtain ⟨T, hT, h⟩ := support hn i (keys p.1) + exact ⟨T, hT, fun x y he => by unfold read; rw [h x y he]⟩ + have hg := (addresses_size A hn fa i hw.large hw.bits hw.pos hw.power hw.cube hw.selectors + (hw.charge i) hw.packets).2.pull idx + apply Vector.packed.of_net _ (hg.comp (hr.bnet F)) + · have h₁ : r ≤ 2 ^ w := (Nat.le_pow (by omega : 0 < 16 * n)).trans hw.power + have h₂ : 5 + 135 * w ≤ (100 + w) ^ 48 := by + refine le_trans ?_ (Nat.pow_le_pow_right (by omega) (by decide : 2 ≤ 48)) + ring_nf + omega + have h₃ : w ^ 48 ≤ (100 + w) ^ 48 := by gcongr; omega + simp only [Fintype.card_prod (Coloring.B w), Fintype.card_fin, card_slots, wd_word] + calc + _ ≤ 2 ^ w + 2 ^ w * w + (2 ^ w + 2 * 2 ^ w + 2 ^ w * w ^ 48 + (2 ^ w + 134 * (2 ^ w * w))) + := by + change _ + _ + (_ + 2 * Fintype.card (A.CountBit r d) + _ + (_ + 134 * _)) ≤ _ + have := hw.counts + gcongr + _ = 2 ^ w * (5 + 135 * w + w ^ 48) := by ring + _ ≤ 2 ^ w * ((100 + w) ^ 48 * 2) := by apply Nat.mul_le_mul_left; omega + _ ≤ _ := by rw [pow_succ (100 + w) 48]; gcongr; omega + · intro s j k + change read (A.groupFlags N i (inp s ∘ idx)) (j, k) = _ + simp only [read, he, ← hc s, pairOf_report] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Checking relay consistency directly from the public input bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal Install MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) + +open Classical in +/-- The data for the invocation construction, including `site`, `script`, `report`, `physical`, +`cut`. -/ +structure Invocation (i : Fin n) where + /-- The `Invocation` component of type `Fin (3 * r)`. -/ + site : Fin (3 * r) + /-- The `Invocation` component of type `M.Bits F → Bool`. -/ + script : M.Bits F → Bool + /-- The `Invocation` component of type `P.Reports A hn B`. -/ + report : P.Reports A hn B + /-- The `Invocation` component of type `Fin (N / 4) → Bool`. -/ + physical : Fin (N / 4) → Bool + cut : report.val.1 = i + feasible : A.feasible hn report.val + +variable {i : Fin n} + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def input (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) : + Machine.Ports N l l → Bool := + Sum.elim (C.code (some (s.site, s.script))) + (Sum.elim (A.encodeReport hn N r (B * P.count) l C.fits (some s.report)) s.physical) + +open Classical in +/-- The value specified by `.inr (.inl (A.reportPort _ _ _ C.fits (.inr (.inr c))))`. -/ +def countPort (c : A.CountBit r (B * P.count)) : Machine.Ports N l l := + .inr (.inl (A.reportPort _ _ _ C.fits (.inr (.inr c)))) + +open Classical in +theorem counts_eq (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) : + C.input s ∘ C.countPort = A.countBits s.report.val := + funext fun j => A.encodeReport_count _ _ _ _ _ _ _ j + +open Classical in +theorem worker_net (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) + (hr : 3 * r ≤ 2 ^ w) : + packed (U := raw _) F (C.input (i := i)) (fun s (_ : Coloring.B w) => s.site.val) 5 := by + let read : Fin (3 * r) → Machine.Ports N l l := + fun j => .inl (M.literalPort F l r C.literal (.inr (.inl j))) + let f (x : Machine.Ports N l l → Bool) (t : Unit × slots (word w)) := + digits w (∑ j, if x (read j) then j.val else 0) t.2 + have hn := (BNet.pull (Register.weighted F w (fun j : Fin (3 * r) => j.val)) read).rename + (.refl _) (Equiv.uniqueProd _ Unit).symm + apply packed.reshape f (fun _ => ()) hn + · simp only [Fintype.card_unit, Fintype.card_fin] + have he : 1 ≤ 2 ^ w := Nat.one_le_pow _ _ (by decide) + have hs : 50000 * (w + 1) ≤ (100 + w) ^ 5 := by ring_nf; omega + have hc := Nat.mul_le_mul_left (2 ^ w) hs + nlinarith only [hc, hr, hi, he, Nat.mul_le_mul_right w hr, Nat.mul_le_mul_right w he] + · intro s j b + simp only [f, input, read, Sum.elim_inl, code, Bank.literalCode_worker, decide_eq_true_eq, + Finset.sum_ite_eq, Finset.mem_univ, ite_true] + +omit [Fintype F] in +open Classical in +theorem pairSymm (R : P.Reports A hn B) (u v : Fin (3 * r)) : pairCount R u v = pairCount R v u := + Links.count_symm _ _ _ _ + +variable [NeZero (3 * r)] [LinearOrder (Name n r)] + +open Classical in +/-- The value specified by `Links.valid (pairSymm s.report) (C.pairSum s.report) C.links s.site +s.physical`. -/ +def relay (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) := + Links.valid (pairSymm s.report) (C.pairSum s.report) C.links s.site s.physical + +open Classical in +/-- One circuit works for all feasible reports, processor identifiers +and scripts at this cut. It pins unused slots and checks every relay. -/ +theorem relay_net (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) (i : Fin n) : + ∃ t : (Machine.Ports N l l → Bool) → Unit → Bool, + BNet F t (2 ^ w * (100 + w) ^ (62 + 416)) ∧ ∀ s, t (C.input (i := i) s) () + = decide (C.relay s) := by + let X := Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + have hg := packed_count hw hi C.input C.countPort (fun s : X + => s.report) i Invocation.cut (C.counts_eq) + have hs := C.packed_skip hw hi C.input C.countPort (fun s : X + => s.report) i Invocation.cut (C.counts_eq) + have hr := hw.pos + have he := C.worker_net (i := i) hi ((Nat.le_pow (by decide : 0 < 5)).trans hw.pairs) + obtain ⟨f, hf, hf'⟩ := packed.valid (u := fun s : X => s.site) (c := 62) (by omega) + C.links hw.bits (fun s : X => pairSymm s.report) (fun s : X => C.pairSum s.report) + (hg.mono (by decide)) hs (he.mono (by decide)) (fun j => .inr (.inr j)) + exact ⟨f, hf, fun s => hf' s⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- +# Separating bit and class symbols at one worker + +A shared bit has exactly one specified physical address. Private +bits and class symbols remain independent summation variables. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal +variable {F : Type} [Field F] [Fintype F] {N l n d r h B : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +open Classical in +/-- Indexes the bit by the coordinates of `Pin N l l r ⊕ (Position n r (B * P.count) h × Bool)`. -/ +abbrev Bit (P : Format N l d n r h) (B : ℕ) := Pin N l l r ⊕ (Position n r (B * P.count) h × Bool) +open Classical in +/-- Indexes the edge by the coordinates of `Pin N l l r ⊕ Expansion.Edge n r (B * P.count) h`. -/ +abbrev Edge (P : Format N l d n r h) (B : ℕ) := Pin N l l r ⊕ Expansion.Edge n r (B * P.count) h + +open Classical in +/-- In the case `.inl q`, this construction gives `.inl q`. -/ +def wrap : Bit P B → Edge P B + | .inl q => .inl q + | .inr q => .inr (.inl q) + +open Classical in +/-- Computes the source by the application `A.extraSrc hn N s.report.1 (Worker.index r) (Pin.src +(P.route A hn B s.report))`. -/ +abbrev source (s : X) := A.extraSrc hn N s.report.1 (Worker.index r) (Pin.src (P.route A hn B + s.report)) +open Classical in +/-- Computes the target by the application `A.extraDst hn N s.report.1 (Worker.index r) (Pin.dst +(P.route A hn B s.report))`. -/ +abbrev target (s : X) := A.extraDst hn N s.report.1 (Worker.index r) (Pin.dst (P.route A hn B + s.report)) +open Classical in +/-- Computes the width by the application `A.extraSize s.report.1`. -/ +abbrev width (s : X) : Edge P B → ℕ := A.extraSize s.report.1 +open Classical in +/-- The value specified by `(Worker.index r).symm s.site`. -/ +abbrev workerAt (s : X) := (Worker.index r).symm s.site +open Classical in +/-- The value specified by `source s e = s.site ∨ target s e = s.site`. -/ +abbrev incident (s : X) (e : Edge P B) := source s e = s.site ∨ target s e = s.site + +open Classical in +/-- The receive used in the `Controller` construction. -/ +def receive (s : X) (z : Encoded.Bits (source s) (target s) (width s)) (he : incident s z.1.val) := + s.physical (Encoded.location (source s) (target s) (width s) + (A.extra_bound hn N s.report.1 (Worker.index r) s.report.2.2 _ _ (C.pins s.report.1)) + C.links (C.number s.report) s.site z he) + +open Classical in +/-- Returns `C.receive s ⟨⟨e, h.1⟩, ⟨j, h.2.2⟩⟩ h.2.1` when `h : source s e ≠ target s e ∧ +incident s e ∧ j < width s e` holds, and `false` otherwise. -/ +def physicalBit (s : X) (e : Edge P B) (j : ℕ) : Bool := + if h : source s e ≠ target s e ∧ incident s e ∧ j < width s e then + C.receive s ⟨⟨e, h.1⟩, ⟨j, h.2.2⟩⟩ h.2.1 else false + +open Classical in +/-- The subtype of `q : Bit P B` satisfying `incident s (wrap q)`. -/ +abbrev LocalBit (s : X) := {q : Bit P B // incident s (wrap q)} + +open Classical in +/-- Returns `x ⟨q, h⟩` when `h : incident s (wrap q)` holds, and `false` otherwise. -/ +def fullBit (s : X) (x : LocalBit s → Bool) (q : Bit P B) := + if h : incident s (wrap q) then x ⟨q, h⟩ else false + +open Classical in +/-- The condition `∀ q, source s (wrap q.val) ≠ target s (wrap q.val) → x q = C.physicalBit s +(wrap q.val) 0` on the specified data. -/ +def Matches (s : X) (x : LocalBit s → Bool) : Prop := + ∀ q, source s (wrap q.val) ≠ target s (wrap q.val) → x q = C.physicalBit s (wrap q.val) 0 + +open Classical in +/-- Computes the classes by the application `PacketKernel.Incident A hn N s.report.1 (workerAt +s)`. -/ +abbrev Classes (s : X) := PacketKernel.Incident A hn N s.report.1 (workerAt s) +open Classical in +/-- Computes the symbols by the application `PacketKernel.Family A hn N s.report.1 (workerAt +s)`. -/ +abbrev Symbols (s : X) := PacketKernel.Family A hn N s.report.1 (workerAt s) +open Classical in +/-- The value specified by `Encoded.Local (source s) (target s) (A.ExtraSymbol hn N s.report.1) +s.site`. -/ +abbrev Local (s : X) := + Encoded.Local (source s) (target s) (A.ExtraSymbol hn N s.report.1) s.site + +omit [Fintype F] in +open Classical in +theorem class_here (s : X) (c : Class r) : incident s (.inr (.inr c)) ↔ + A.src hn N s.report.1 (.inr c) = workerAt s ∨ A.dst hn N s.report.1 (.inr c) = workerAt s := by + simp only [workerAt, incident, source, target, Expansion.extraSrc, Expansion.extraDst, + Function.comp_apply, Sum.elim_inr, Equiv.eq_symm_apply] + +open Classical in +/-- In the case `⟨.inl j, h⟩`, this construction gives `y.1 ⟨.inl j, h⟩`. -/ +def localEquiv (s : X) : (LocalBit s → Bool) × Symbols s ≃ Local s where + toFun y + | ⟨.inl j, h⟩ => y.1 ⟨.inl j, h⟩ + | ⟨.inr (.inl j), h⟩ => y.1 ⟨.inr j, h⟩ + | ⟨.inr (.inr c), h⟩ => y.2 ⟨c, (class_here s c).mp h⟩ + invFun x := (fun + | ⟨.inl j, h⟩ => x ⟨.inl j, h⟩ + | ⟨.inr j, h⟩ => x ⟨.inr (.inl j), h⟩, + fun c => x ⟨.inr (.inr c.val), (class_here s _).mpr c.property⟩) + left_inv y := by + apply Prod.ext + · funext k; rcases k with ⟨j|j, h⟩ <;> rfl + · rfl + right_inv x := by funext k; rcases k with ⟨j|j|j, h⟩ <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- +# A fixed-size table of potentially incident slot keys + +A home or station worker uses just its coordinate slice of the +possible endpoints. A packet worker instead uses the auxiliary +coordinate of the first template label. The size is the same for +all three roles, regardless of the heavy set. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal Spectral Finset +open Classical in +/-- Indexes the slot key by the coordinates of `Template n r × Cube n × Bool`. -/ +abbrev SlotKey (n r : ℕ) := Template n r × Cube n × Bool + +namespace SlotKey +variable {n r h t : ℕ} + +open Classical in +/-- The value specified by `(p.1.1.1, p.1.2.1, p.2)`. -/ +def key (p : Position n r t h × Bool) : SlotKey n r := (p.1.1.1, p.1.2.1, p.2) +open Classical in +/-- The value specified by `(((k.1, i), k.2.1, j), k.2.2)`. -/ +def atRow (k : SlotKey n r) (i : Fin t) (j : Fin h) : Position n r t h × Bool := + (((k.1, i), k.2.1, j), k.2.2) + +open Classical in +/-- Computes the label by the application `corner k.1 (if k.2.2 then Cube.flip univ k.2.1 else +k.2.1)`. -/ +def label (k : SlotKey n r) := corner k.1 (if k.2.2 then Cube.flip univ k.2.1 else k.2.1) + +variable (hn : 2 ≤ n) (i : Fin n) + +open Classical in +/-- In the case `.home _`, this construction gives `k.label i`. -/ +def focus (u : Worker r) (k : SlotKey n r) : Fin r := + match u with + | .home _ => k.label i + | .station _ => k.label (other hn i) + | .packet _ => k.1.1 (other hn i) + +open Classical in +/-- The subtype of `k : SlotKey n r` satisfying `focus hn i u k = Layout.symbol u`. -/ +abbrev Visible (u : Worker r) := {k : SlotKey n r // focus hn i u k = Layout.symbol u} + +open Classical in +private theorem template_uniform (j : Fin n) (b : Bool) (g : Fin r) : + multiplicity (fun t : Template n r => group t j b) g * r = Fintype.card (Template n r) := by + have h := group_uniform (d := 1) j b g + let e := Equiv.prodUnique (Template n r) (Fin 1) + have hf : multiplicity (fun t : Packet n r 1 => group t.1 j b) g = + multiplicity (fun t : Template n r => group t j b) g := + Fintype.card_congr (e.subtypeEquiv (fun _ => Iff.rfl)) + rwa [hf, Fintype.card_congr e] at h + +open Classical in +theorem visible_uniform (u : Worker r) : + Fintype.card (Visible hn i u) * r = Fintype.card (SlotKey n r) := by + have h (x : Cube n × Bool) : + multiplicity (fun t : Template n r => focus hn i u (t, x)) (Layout.symbol u) * r = + Fintype.card (Template n r) := by + cases u with + | home g => exact template_uniform i ((if x.2 then Cube.flip univ x.1 else x.1) i) g + | station g => + exact template_uniform (other hn i) + ((if x.2 then Cube.flip univ x.1 else x.1) (other hn i)) g + | packet g => exact template_uniform (other hn i) false g + have he : Fintype.card (Visible hn i u) = + ∑ x : Cube n × Bool, multiplicity (fun t : Template n r => focus hn i u (t, + x)) (Layout.symbol u) := by + simp only [Visible, Diagonal.multiplicity, Fintype.card_subtype] + have hw (p : SlotKey n r → Prop) [DecidablePred p] : + (univ.filter p).card = ∑ x, if p x then 1 else 0 := by simp + rw [hw, Fintype.sum_prod_type, sum_comm] + simp + rw [he, sum_mul] + simp only [h, sum_const, card_univ, nsmul_eq_mul, Nat.cast_id] + rw [Fintype.card_prod (Template n r), mul_comm] + +open Classical in +/-- Counts the elements of `(SlotKey n r) / r`. -/ +def count (n r : ℕ) := Fintype.card (SlotKey n r) / r + +open Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def enumerate (u : Worker r) : Fin (count n r) ≃ Visible hn i u := + Fintype.equivOfCardEq (by + rw [Fintype.card_fin, count, ← visible_uniform hn i u] + exact Nat.mul_div_cancel _ (Layout.symbol u).pos) + +variable {F : Type} [Field F] (A : Expansion F n h) (N : ℕ) (R : A.Report r t) + +open Classical in +theorem visible_src (q : Position n r t h × Bool) : + let u := A.src hn N R (.inl q) + focus hn R.1 u (key q) = Layout.symbol u := by + rcases q with ⟨p, b⟩ + simp only [Expansion.src, Expansion.owner] + split <;> rfl + +open Classical in +theorem visible_dst (q : Position n r t h × Bool) : + let u := A.dst hn N R (.inl q) + focus hn R.1 u (key q) = Layout.symbol u := by + rcases q with ⟨p, b⟩ + simp only [Expansion.dst] + split + · exact visible_src hn A N R (p, b) + · rfl + +end SlotKey +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +/- # Separating the bit and class checks in the physical input -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal +variable {F : Type} [Field F] [Fintype F] {N l n d r h B : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) + +open Classical in +/-- The received used in the `Controller` construction. -/ +abbrev Received (v : Local s) := + Encoded.receives (source s) (target s) (A.ExtraSymbol hn N s.report.1) (width s) + (A.extraCode hn N s.report.1) + (A.extra_bound hn N s.report.1 (Worker.index r) s.report.2.2 _ _ (C.pins s.report.1)) + C.links (C.number s.report) s.site s.physical v + +open Classical in +private theorem received_iff (v : Local s) : + C.Received s v ↔ ∀ (e : Edge P B) (he : incident s e), source s e ≠ target s e → + ∀ j, A.extraCode hn N s.report.1 e (v ⟨e, he⟩) j = C.physicalBit s e j.val := by + have atBit (e : Edge P B) (hi : incident s e) (he : source s e ≠ target s e) + (j : Fin (width s e)) : C.physicalBit s e j.val = C.receive s ⟨⟨e, he⟩, j⟩ hi := by + rw [physicalBit, dite_eq_left ⟨he, hi, j.isLt⟩] + constructor + · intro h e hi he j + rw [atBit e hi he j] + exact h ⟨e, he⟩ hi j + · rintro h ⟨e, he⟩ hi j + exact (h e hi he j).trans (atBit e hi he j) + +open Classical in +/-- The streams of type `Prop` for the given inputs. -/ +def streams (z : Symbols s) : Prop := + ∀ c : Classes s, A.src hn N s.report.1 (.inr c.val) ≠ A.dst hn N s.report.1 (.inr c.val) → + ∀ j, A.alphabetCode hn N s.report.1 c.val (z c) j = C.physicalBit s (.inr (.inr c.val)) j.val + +open Classical in +theorem received_split (x : LocalBit s → Bool) (z : Symbols s) : + C.Received s (localEquiv s (x, z)) ↔ C.Matches s x ∧ C.streams s z := by + rw [received_iff] + constructor + · intro h + constructor + · rintro ⟨e|e, hi⟩ he + · exact h (.inl e) hi he (0 : Fin 1) + · exact h (.inr (.inl e)) hi he (0 : Fin 1) + · intro c he j + exact h (.inr (.inr c.val)) ((class_here s _).mpr c.2) ((Worker.index r).injective.ne he) j + · rintro ⟨hx, hz⟩ (e|e|c) hi he j + · change Fin 1 at j + rw [Fin.eq_zero j] + exact hx ⟨.inl e, hi⟩ he + · change Fin 1 at j + rw [Fin.eq_zero j] + exact hx ⟨.inr e, hi⟩ he + · exact hz ⟨c, (class_here s c).mp hi⟩ (fun h => he (congrArg (Worker.index r) h)) j + +omit [Fintype F] in +open Classical in +theorem symbols_exist : + Nonempty ((e : Edge P B) → A.ExtraSymbol hn N s.report.1 e) := + (A.feasible_symbols hn s.report.1 N).mp s.feasible + +open Classical in +/-- This is the extension in the localization of a vertex table. -/ +def extendLocal (x : LocalBit s → Bool) (z : Symbols s) (e : Edge P B) : + A.ExtraSymbol hn N s.report.1 e := + if he : incident s e then localEquiv s (x, z) ⟨e, he⟩ else (choice (symbols_exist s)) e + +open Classical in +/-- Evaluates `extendLocal s x z (.inr e)` at the input `e`. -/ +def localAssignment (x : LocalBit s → Bool) (z : Symbols s) : A.Assignment hn N s.report.1 := + fun e => extendLocal s x z (.inr e) + +omit [Fintype F] in +open Classical in +theorem assigned_class (x : LocalBit s → Bool) (z : Symbols s) (c : Classes s) : + localAssignment s x z (.inr c.val) = z c := by + unfold localAssignment extendLocal + rw [dite_eq_left ((class_here s c.val).mpr c.2)] + rfl + +omit [Fintype F] in +open Classical in +theorem fullBit_at (x : LocalBit s → Bool) (q : Bit P B) (he : incident s (wrap q)) : + fullBit s x q = x ⟨q, he⟩ := by rw [fullBit, dite_eq_left he] + +omit [Fintype F] in +open Classical in +theorem assigned_row (x : LocalBit s → Bool) (z : Symbols s) (p : Position n r (B * P.count) h × + Bool) + (hp : incident s (.inr (.inl p))) : + localAssignment s x z (.inl p) = fullBit s x (.inr p) := by + unfold localAssignment extendLocal + rw [dite_eq_left hp, fullBit_at s x (.inr p) hp] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/PacketNet.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/PacketNet.lean new file mode 100644 index 0000000000..be71b3bad4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/PacketNet.lean @@ -0,0 +1,972 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Named +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.AlphabetCode +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels + +/-! +# Reading a compact sequence at the marked slots + +The prefix counter and the indirect reader use the same address +width. Doubling the array avoids truncating the extra counter bit. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PackCode + +open Install Control +/-- The quantity computed by `Fin (2 ^ w)`. -/ +abbrev Index (w : ℕ) := Fin (2 ^ w) + +/-- The quantity computed by `x (.inr (Fin.ofNat (2 ^ w) (histogram (x ∘ Sum.inl) true (some +i))))`. -/ +def scatter (w : ℕ) (x : Index w ⊕ Index w → Bool) (i : Index w) : Bool := + x (.inr (Fin.ofNat (2 ^ w) (histogram (x ∘ Sum.inl) true (some i)))) + +private def low (w : ℕ) (i : Index (w + 1)) : Index w := Fin.ofNat (2 ^ w) i.val + +private def high (w : ℕ) (i : Index w) : Index (w + 1) := + i.castLE (by rw [pow_succ]; omega) + +@[simp] private theorem low_high (w : ℕ) (i : Index w) : low w (high w i) = i := + Fin.ext (Nat.mod_eq_of_lt i.isLt) + +private theorem decode_bits (w u : ℕ) (hu : u < 2 ^ w) : + decode w (bits (word w) (Lookup.bits w u)) = ⟨u, hu⟩ := + (decode w).apply_symm_apply ⟨u, hu⟩ + +theorem scatter_net (F : Type) [Field F] (w : ℕ) : + BNet F (scatter w) (200000 * 2 ^ w * (w + 1) ^ 3) := by + let A := Option (Index w) × slots (word (w + 1)) + have counts := (prefix_bnet F w).parallel (BNet.id F (Index w)) + let addr : Index (w + 1) ⊕ Index (w + 1) × slots (word (w + 1)) → A ⊕ Index w + | .inl i => .inr (low w i) + | .inr (i, j) => .inl (some (low w i), j) + have h := (counts.comp ((read_net F (w + 1)).pull addr)).comp + ((BNet.id F (Index w)).pull (high w)) + convert h.mono (n := 200000 * 2 ^ w * (w + 1) ^ 3) (by + simp only [A, Index, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + Fintype.card_option, card_slots, wd_word, Fintype.card_unit, slots] + have hp : 1 ≤ 2 ^ w := Nat.one_le_pow _ _ (by decide) + have := Nat.le_mul_of_pos_right w hp + ring_nf + omega) using 1 + funext x i + have hu : histogram (x ∘ Sum.inl) true (some i) < 2 ^ (w + 1) := by + have := histogram_le (x ∘ Sum.inl) true (some i) + have := Nat.one_le_pow w 2 (by decide) + rw [pow_succ] + omega + change scatter w x i = x (.inr (low w (decode (w + 1) + (bits (word (w + 1)) (Lookup.bits (w + 1) (histogram (x ∘ Sum.inl) true (some (low w (high w + i))))))))) + rw [low_high, decode_bits _ _ hu] + rfl + +/-- The condition `∀ i, marks i = true → v i = scatter w (Sum.elim marks data) i` on the +specified data. -/ +def Matches (w : ℕ) (v marks data : Index w → Bool) : Prop := + ∀ i, marks i = true → v i = scatter w (Sum.elim marks data) i + +open Classical in +theorem matches_net (F : Type) [Field F] (w : ℕ) : + Weight F (fun x : Index w ⊕ Index w ⊕ Index w → Bool => + if Matches w (x ∘ Sum.inl) (fun j => x (.inr (.inl j))) (fun j => x (.inr (.inr j))) + then 1 else 0) (210000 * 2 ^ w * (w + 1) ^ 3) := by + let I := Index w ⊕ Index w ⊕ Index w + have gather := (BNet.id F I).pair ((scatter_net F w).pull (Sum.inr : Index w ⊕ Index w → I)) + let row (x : Fin 3 → Bool) : F := if x 0 = true → x 1 = x 2 then 1 else 0 + let addr (p : Index w × Fin 3) : I ⊕ Index w := + if p.2 = 0 then .inl (.inr (.inl p.1)) else if p.2 = 1 then .inl (.inl p.1) else .inr p.1 + have h := gather.weight (((Weight.dense F (Fin 3) row).prod w).pull addr) + convert h.mono (n := 210000 * 2 ^ w * (w + 1) ^ 3) (by + simp only [I, Index, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + ring_nf + omega) using 1 + funext x + have he : Sum.elim (fun j => x (.inr (.inl j))) (fun j => x (.inr (.inr j))) = + x ∘ Sum.inr := by funext j; cases j <;> rfl + simp only [Matches, he] + change _ = ∏ i, if x (.inr (.inl i)) = true → x (.inl i) = scatter w (x ∘ Sum.inr) i + then 1 else 0 + simp only [Finset.prod_ite_zero, Finset.mem_univ, forall_const, Finset.prod_const_one, + Function.comp_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PackCode +end + +section +/- # Relating marked positions to ordered block concatenation -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PackCode + +open Finset Diagonal.Expansion +variable {w l : ℕ} {marks values data : Index w → Bool} + +/-- The rank at a marked position is its index in the list of marks. -/ +theorem rank_image {f : Fin l → Index w} (hf : StrictMono f) + (hm : ∀ i, marks i = true ↔ ∃ j, f j = i) (j : Fin l) : + Control.histogram marks true (some (f j)) = j.val := by + rw [Control.histogram_some] + have h : (univ.filter fun i => marks i = true ∧ i < f j) = (Iio j).image f := by + ext i + simp only [mem_filter, mem_univ, true_and, mem_image, mem_Iio, hm] + constructor + · rintro ⟨⟨k, rfl⟩, hk⟩ + exact ⟨k, hf.lt_iff_lt.mp hk, rfl⟩ + · rintro ⟨k, hk, rfl⟩ + exact ⟨⟨k, rfl⟩, hf hk⟩ + rw [h, card_image_of_injective _ hf.injective, Fin.card_Iio] + +theorem matches_image {f : Fin l → Index w} (hf : StrictMono f) + (hm : ∀ i, marks i = true ↔ ∃ j, f j = i) (hl : l ≤ 2 ^ w) : + Matches w values marks data ↔ ∀ j, values (f j) = data (Fin.castLE hl j) := by + have h (j : Fin l) : scatter w (Sum.elim marks data) (f j) = data (Fin.castLE hl j) := by + change data (Fin.ofNat _ (Control.histogram marks true (some (f j)))) = _ + rw [rank_image hf hm] + exact congrArg data (Fin.ext (Nat.mod_eq_of_lt (j.isLt.trans_le hl))) + constructor + · exact fun hs j => (hs _ ((hm _).mpr ⟨j, rfl⟩)).trans (h j) + · intro hs i hi + obtain ⟨j, rfl⟩ := (hm i).mp hi + exact (hs j).trans (h j).symm + +/-- Any order-preserving placement of the active cells works. Slots +between them, and compact-array positions past the last cell, are ignored. -/ +theorem matches_pack {P : Type} [LinearOrder P] [Fintype P] (f : P → ℕ) + (x : (p : P) → Fin (f p) → Bool) (hl : ∑ p, f p = l) (hw : l ≤ 2 ^ w) + (addr : Lex (Σ p, Fin (f p)) → Index w) (ha : StrictMono addr) + (hm : ∀ i, marks i = true ↔ ∃ z, addr z = i) + (hx : ∀ z, values (addr z) = x z.1 z.2) : + Matches w values marks data ↔ pack f hl.le x = data ∘ Fin.castLE hw := by + subst l + let e := packOrder f + have h : ∀ i, marks i = true ↔ ∃ j, (addr ∘ e) j = i := by + intro i + rw [hm] + exact ⟨fun ⟨z, hz⟩ => ⟨e.symm z, by simpa using hz⟩, fun ⟨j, hj⟩ => ⟨e j, hj⟩⟩ + rw [matches_image (ha.comp e.strictMono) h hw, funext_iff] + apply forall_congr' + intro j + have he := pack_at f le_rfl x (e j) + change pack f le_rfl x (e.symm (e j)) = _ at he + rw [e.symm_apply_apply] at he + simp only [Function.comp_apply, hx, he] + +variable {P : Type} [LinearOrder P] [Fintype P] {s : ℕ} + +/-- Absolute positions in the uncompressed array. Its first `s` +bits are reserved for the fixed-length selector prefix. -/ +noncomputable def grid (cap : P → ℕ) (hc : s + ∑ p, cap p ≤ 2 ^ w) (p : P) (j : Fin (cap p)) : + Index w := + Fin.castLE hc (Fin.natAdd s ((packOrder cap).symm ⟨p, j⟩)) + +private theorem grid_mono {f cap : P → ℕ} (hf : ∀ p, f p ≤ cap p) + (hc : s + ∑ p, cap p ≤ 2 ^ w) : + StrictMono (fun z : Lex (Σ p, Fin (f p)) => grid cap hc z.1 (Fin.castLE (hf _) z.2)) := by + intro x y h + change s + _ < s + _ + apply Nat.add_lt_add_left + apply (packOrder cap).symm.strictMono + rcases Sigma.Lex.lt_def.mp h with h | ⟨he, h⟩ + · exact Sigma.Lex.lt_def.mpr (.inl h) + · obtain ⟨p, i⟩ := x + obtain ⟨q, j⟩ := y + change p = q at he + subst q + exact Sigma.Lex.lt_def.mpr (.inr ⟨rfl, h⟩) + +private theorem mono_append {m : ℕ} (hs : s ≤ 2 ^ w) + (g : Fin m → Index w) (hg : StrictMono g) (hstart : ∀ i, s ≤ (g i).val) : + StrictMono (Fin.append (Fin.castLE hs) g) := by + intro i j h + induction i using Fin.addCases <;> induction j using Fin.addCases + all_goals simp only [Fin.append_left, Fin.append_right] + · exact h + · exact (Fin.isLt (n := s) _).trans_le (hstart _) + · simp only [Fin.lt_def, Fin.val_natAdd, Fin.val_castAdd] at h + omega + · apply hg + simpa only [Fin.lt_def, Fin.val_natAdd, add_lt_add_iff_left] using h + +/-- Mark the entire fixed prefix and the initial `f p` slots of each +reserved block. The comparison checks the prefix and packed blocks. -/ +theorem matches_grid {f cap : P → ℕ} (hf : ∀ p, f p ≤ cap p) + (hl : ∑ p, f p = l) (hc : s + ∑ p, cap p ≤ 2 ^ w) (hw : s + l ≤ 2 ^ w) + (head : Fin s → Bool) (x : (p : P) → Fin (f p) → Bool) + (hm : ∀ i, marks i = true ↔ i.val < s ∨ + ∃ (p : P) (j : Fin (cap p)), j.val < f p ∧ grid cap hc p j = i) + (hhead : ∀ (i : Fin s), values (Fin.castLE (by omega) i) = head i) + (htail : ∀ (p : P) (j : Fin (f p)), values (grid cap hc p (j.castLE (hf p))) = x p j) : + Matches w values marks data ↔ Fin.append head (pack f hl.le x) = data ∘ Fin.castLE hw := by + subst l + have hs : s ≤ 2 ^ w := by omega + let addr (z : Lex (Σ p, Fin (f p))) := grid cap hc z.1 (Fin.castLE (hf _) z.2) + let e := packOrder f + let loc := Fin.append (Fin.castLE hs) (addr ∘ e) + have hmono : StrictMono loc := mono_append hs _ ((grid_mono hf hc).comp e.strictMono) + (fun i => Nat.le_add_right _ _) + have hmark (i) : marks i = true ↔ ∃ j, loc j = i := by + rw [hm] + constructor + · rintro (hi | ⟨p, j, hj, rfl⟩) + · exact ⟨Fin.castAdd _ ⟨i, hi⟩, by dsimp only [loc]; rw [Fin.append_left]; rfl⟩ + · refine ⟨Fin.natAdd s (e.symm (toLex ⟨p, ⟨j, hj⟩⟩)), ?_⟩ + dsimp only [loc]; rw [Fin.append_right, Function.comp_apply, e.apply_symm_apply] + rfl + · rintro ⟨j, rfl⟩ + induction j using Fin.addCases with + | left i => dsimp only [loc]; rw [Fin.append_left]; exact .inl i.isLt + | right i => + dsimp only [loc]; rw [Fin.append_right] + exact .inr ⟨(e i).1, Fin.castLE (hf _) (e i).2, (e i).2.isLt, rfl⟩ + rw [matches_image hmono hmark hw, funext_iff] + apply forall_congr' + intro i + induction i using Fin.addCases with + | left j => simp only [loc, Fin.append_left, Function.comp_apply, hhead] + | right j => + have he := pack_at f le_rfl x (e j) + change pack f le_rfl x (e.symm (e j)) = _ at he + rw [e.symm_apply_apply] at he + simp only [loc, Fin.append_right, Function.comp_apply, he, addr, htail] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PackCode + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion + +open Processor.PackCode +attribute [local instance] memberOrder + +variable {F : Type} [Field F] {n r d h N w : ℕ} (A : Expansion F n h) + {hn : 2 ≤ n} {R : A.Report r d} {c : Class r} {marks values data : Index w → Bool} + +/-- Computes the cross len by the application `A.width (z.1.val p) R.1 (A.shared N R c)`. -/ +abbrev crossLen (z : A.Alphabet hn N R c) (p : A.Members hn R c) := + A.width (z.1.val p) R.1 (A.shared N R c) + +/-- A shared class uses all the bits charged by its report. A single +prefix-count check therefore verifies its entire symbol. -/ +theorem matches_alphabet (z : A.Alphabet hn N R c) (hsh : A.shared N R c = true) + (cap : A.Members hn R c → ℕ) (hf : ∀ p, A.crossLen z p ≤ cap p) + (hc : A.selectorWidth hn R c + ∑ p, cap p ≤ 2 ^ w) (hw : A.classWidth R c ≤ 2 ^ w) + (hm : ∀ i, marks i = true ↔ i.val < A.selectorWidth hn R c ∨ + ∃ (p : A.Members hn R c) (j : Fin (cap p)), + j.val < A.crossLen z p ∧ grid cap hc p j = i) + (hhead : ∀ i : Fin (A.selectorWidth hn R c), + values (Fin.castLE (by omega) i) = A.selectorPrefix z.1 i) + (htail : ∀ (p : A.Members hn R c) (j : Fin (A.crossLen z p)), + values (grid cap hc p (j.castLE (hf p))) = z.2 p j) : + Matches w values marks data ↔ A.alphabetCode hn N R c z = data ∘ Fin.castLE hw := by + have hlen : A.classWidth R c = A.selectorWidth hn R c + ∑ p, A.crossLen z p := by + simpa only [crossLen, width, hsh, ite_true] using A.classWidth_split z.1 + have hl : ∑ p, A.crossLen z p = A.classWidth R c - A.selectorWidth hn R c := by omega + have hw' : A.selectorWidth hn R c + (A.classWidth R c - A.selectorWidth hn R c) ≤ 2 ^ w + := by omega + rw [matches_grid hf hl hc hw' (A.selectorPrefix z.1) z.2 hm hhead htail] + constructor + · intro h + funext j + exact congrFun h (A.codeSplit z.1 j) + · intro h + funext j + exact congrFun h ((A.codeSplit z.1).symm j) + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Expansion +end + +/- +# Fixed-width private packet records + +The selector and its crossing bits fit in one record of constant size +for a fixed cube identity. Out-of-range selector codes and nonzero +padding bits carry zero weight. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel + +open Diagonal Finset +variable {F : Type} [Field F] {n h p w t : ℕ} (A : Expansion F n h) + +open Classical in +/-- The mode used in the `PacketKernel` construction. -/ +inductive Mode where + | joint + | both + | side (b : Bool) + +open Classical in +/-- In the case `.joint`, this construction gives `false`. -/ +def Mode.cut : Mode → Bool + | .joint => false + | _ => true + +open Classical in +/-- In the case `.side _`, this construction gives `true`. -/ +def Mode.share : Mode → Bool + | .side _ => true + | _ => false + +open Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev prefixSize := Nat.clog 2 (Fintype.card A.I) +open Classical in +/-- The value specified by `∑ s, ∑ i, A.cross s i`. -/ +def reserve := ∑ s, ∑ i, A.cross s i + +open Classical in +theorem width_le (s : A.I) (i : Fin n) (b : Bool) : A.width s i b ≤ reserve A := by + cases b + · exact Nat.zero_le _ + · exact (single_le_sum (f := A.cross s) (fun _ _ => Nat.zero_le _) (mem_univ i)).trans + (single_le_sum (f := fun z => ∑ j, A.cross z j) (fun _ _ => Nat.zero_le _) (mem_univ s)) + +open Classical in +/-- Indexes the code by the coordinates of `Fin (prefixSize A) ⊕ Fin (reserve A)`. -/ +abbrev Code := Fin (prefixSize A) ⊕ Fin (reserve A) +open Classical in +/-- Indexes the row by the coordinates of `(Bool × Spectral.Cube n × Fin h) ⊕ Code A`. -/ +abbrev Row := (Bool × Spectral.Cube n × Fin h) ⊕ Code A +open Classical in +/-- Indexes the inputs by the coordinates of `(Fin p × Row A) ⊕ (A.I × Fin w) ⊕ PackCode.Index +t`. -/ +abbrev Inputs (p w t : ℕ) := (Fin p × Row A) ⊕ (A.I × Fin w) ⊕ PackCode.Index t + +open Classical in +theorem inhabited : Nonempty A.I := by + by_contra hempty + have : IsEmpty A.I := not_nonempty_iff.mp hempty + have := A.full (fun _ => false) (fun _ => false) + simp at this + +open Classical in +/-- The value specified by `letI := inhabited A Function.invFun A.selectorCode (z ∘ Sum.inl)`. -/ +def selector (z : Code A → Bool) : A.I := + letI := inhabited A + Function.invFun A.selectorCode (z ∘ Sum.inl) + +open Classical in +/-- Computes the used by the application `A.width (selector A z) i b`. -/ +def used (i : Fin n) (b : Bool) (z : Code A → Bool) := A.width (selector A z) i b + +open Classical in +/-- Computes the crossing by the application `z (.inr (j.castLE (width_le A _ _ _)))`. -/ +def crossing (i : Fin n) (b : Bool) (z : Code A → Bool) (j : Fin (used A i b z)) := + z (.inr (j.castLE (width_le A _ _ _))) + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def encode (i : Fin n) (b : Bool) (s : A.I) (v : Fin (A.width s i b) → Bool) : Code A → Bool := + Sum.elim (A.selectorCode s) (fun j => if hj : j.val < A.width s i b then v ⟨j, hj⟩ else false) + +open Classical in +@[simp] theorem selector_encode (i : Fin n) (b : Bool) (s : A.I) (v : Fin (A.width s i b) → Bool) : + selector A (encode A i b s v) = s := by + have := inhabited A + exact Function.leftInverse_invFun A.selectorCode.injective s + +open Classical in +/-- Requires `encode A i b (selector A z) (crossing A i b z) = z`. -/ +def ok (i : Fin n) (b : Bool) (z : Code A → Bool) : Prop := + encode A i b (selector A z) (crossing A i b z) = z + +open Classical in +private theorem apply_encode {X : Type} (i : Fin n) (b : Bool) + (s : A.I) (v : Fin (A.width s i b) → Bool) + (g : (t : A.I) → (Fin (A.width t i b) → Bool) → X) : + g (selector A (encode A i b s v)) (crossing A i b (encode A i b s v)) = g s v := by + let k (t : A.I) (j : Fin (A.width t i b)) := encode A i b s v (.inr (j.castLE (width_le A t i b))) + change g _ (k _) = _ + rw [selector_encode] + apply congrArg (g s) + funext j + simp [k, encode, j.isLt] + +open Classical in +@[simp] theorem ok_encode (i : Fin n) (b : Bool) (s : A.I) (v : Fin (A.width s i b) → Bool) : + ok A i b (encode A i b s v) := + apply_encode A i b s v (encode A i b) + +open Classical in +/-- In the case `false, _`, this construction gives `A.weight s x y`. -/ +def modeValue (mode : Mode) (s : A.I) (i : Fin n) (x y : Block n h) : + (cut : Bool) → (Fin (A.width s i cut) → Bool) → F + | false, _ => A.weight s x y + | true, z => match mode with + | .side b => A.side s i b x y z + | _ => A.value s i x y true z + +open Classical in +/-- The entry of type `F`, constructed using `u ∘ Sum.inr`. -/ +def entry (i : Fin n) (mode : Mode) (u : Row A → Bool) : F := + let z := u ∘ Sum.inr + if ok A i mode.cut z then + modeValue A mode (selector A z) i (fun j => u (.inl (false, j))) (fun j => u (.inl (true, j))) + mode.cut (crossing A i mode.cut z) + else 0 + +open Classical in +theorem entry_encode (i : Fin n) (mode : Mode) (b : Bool) (hb : mode.cut = b) + (s : A.I) (v : Fin (A.width s i b) → Bool) (u : Row A → Bool) + (hu : u ∘ Sum.inr = encode A i b s v) : + entry A i mode u = + modeValue A mode s i (fun j => u (.inl (false, j))) (fun j => u (.inl (true, j))) b v := by + unfold entry + dsimp only + rw [hu, hb, ite_eq_left (ok_encode A i b s v)] + exact apply_encode A i b s v (fun t v => + modeValue A mode t i (fun j => u (.inl (false, j))) (fun j => u (.inl (true, j))) b v) + +open Classical in +/-- The value specified by `x (.inl (j, u))`. -/ +def row (x : Inputs A p w t → Bool) (j : Fin p) (u : Row A) := x (.inl (j, u)) +open Classical in +/-- The value specified by `row A x j ∘ Sum.inr`. -/ +def raw (x : Inputs A p w t → Bool) (j : Fin p) := row A x j ∘ Sum.inr +open Classical in +/-- The indexed operation `number (fun j => x (.inr (.inl (s, j))))`. -/ +def expected (x : Inputs A p w t → Bool) (s : A.I) := number (fun j => x (.inr (.inl (s, j)))) +open Classical in +/-- Computes the compact by the application `x (.inr (.inr j))`. -/ +def compact (x : Inputs A p w t → Bool) (j : PackCode.Index t) := x (.inr (.inr j)) + +open Classical in +/-- The value specified by `multiplicity (selector A ∘ raw A x) s`. -/ +def tally (x : Inputs A p w t → Bool) (s : A.I) := multiplicity (selector A ∘ raw A x) s + +open Classical in +/-- Uncompressed addresses reserve the full selector prefix and a +fixed crossing capacity for every packet in order. -/ +def address (p : ℕ) : Fin p × Code A ≃ Fin (p * prefixSize A + p * reserve A) := + (Equiv.prodSumDistrib _ _ _).trans ((finProdFinEquiv.sumCongr finProdFinEquiv).trans + finSumFinEquiv) + +open Classical in +/-- The value specified by `(address A p z).val`. -/ +def position (p : ℕ) (z : Fin p × Code A) := (address A p z).val + +open Classical in +theorem position_inj (p : ℕ) : Function.Injective (position A p) := + Fin.val_injective.comp (address A p).injective + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def valueAt (x : Inputs A p w t → Bool) (k : PackCode.Index t) : Bool := + Function.extend (position A p) (fun z => raw A x z.1 z.2) (fun _ => false) k.val + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def markAt (i : Fin n) (mode : Mode) (x : Inputs A p w t → Bool) (k : PackCode.Index t) : Bool := + Function.extend (position A p) (fun z => Sum.elim (fun _ => true) + (fun j => decide (j.val < used A i mode.cut (raw A x z.1))) z.2) (fun _ => false) k.val + +open Classical in +/-- The kernel of type `F` for the given inputs. -/ +def kernel (i : Fin n) (mode : Mode) (x : Inputs A p w t → Bool) : F := + if (∀ s, tally A x s = expected A x s) ∧ + (mode.share = true → PackCode.Matches t (valueAt A x) (markAt A i mode x) (compact A x)) then + ∏ j, entry A i mode (row A x j) + else 0 + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +/- # An exact count check on fixed-width packet records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +open Install Diagonal Finset +variable {F : Type} [Field F] {n h p w t v : ℕ} (A : Expansion F n h) + +open Classical in +private theorem register_eq {I : Type} [Fintype I] {f g : (I → Bool) → ℕ} {a b : ℕ} + (hf : Register F v f a) (hg : Register F v g b) + (h₁ : ∀ x, f x < 2 ^ v) (h₂ : ∀ x, g x < 2 ^ v) : + Weight F (fun x => if f x = g x then 1 else 0) + (15 * Fintype.card I + 2 * a + 2 * b + 2100 * (1 + v)) := by + have h := (hf.less hg h₁ h₂).pair (hg.less hf h₂ h₁) + have k := h.weight (Weight.dense F (Unit ⊕ Unit) + (fun x => if x (.inl ()) = false ∧ x (.inr ()) = false then 1 else 0)) + convert k.mono (n := 15 * Fintype.card I + 2 * a + 2 * b + 2100 * (1 + v)) (by + simp + omega) using 1 + funext x + simp only [Function.comp_apply, Sum.elim_inl, Sum.elim_inr, decide_eq_false_iff_not, not_lt, + ← le_antisymm_iff] + simp only [eq_comm] + +open Classical in +theorem raw_support (j : Fin p) : + ∃ S : Finset (Inputs A p w t), S.card ≤ Fintype.card (Code A) ∧ + ∀ x y, (∀ u ∈ S, x u = y u) → raw A x j = raw A y j := by + let k : Code A → Inputs A p w t := fun u => .inl (j, .inr u) + exact ⟨univ.image k, card_image_le, + fun x y he => funext (fun i => he _ (mem_image_of_mem k (mem_univ i)))⟩ + +open Classical in +private theorem tally_net (s : A.I) (v : ℕ) : + Register F v (fun x : Inputs A p w t → Bool => tally A x s) + (Fintype.card (Inputs A p w t) + localCost (Fintype.card (Code A)) * p + + 20000 * (1 + p) * (1 + v)) := by + let f (x : Inputs A p w t → Bool) (j : Fin p) := decide (selector A (raw A x j) = s) + have dep : Depends f (Fintype.card (Code A)) := by + intro j + obtain ⟨S, hS, h⟩ := raw_support A (w := w) (t := t) j + exact ⟨S, hS, fun x y he => by simp only [f, h x y he]⟩ + have hh := (dep.bnet F).comp (Register.weighted F v (fun _ : Fin p => 1)) + rw [Fintype.card_fin] at hh + unfold Register + convert hh using 1 + funext x + congr 1 + simp [f, tally, Diagonal.multiplicity, Fintype.card_subtype] + +open Classical in +private theorem expected_net (s : A.I) (v : ℕ) : + Register F v (fun x : Inputs A p w t → Bool => expected A x s) + (Fintype.card (Inputs A p w t) + 2 * w + 20000 * (1 + w) * (1 + v)) := by + have h := BNet.pull (Register.weighted F v (fun j : Fin w => 2 ^ j.val)) + (fun j => (.inr (.inl (s, j)) : Inputs A p w t)) + rw [Fintype.card_fin] at h + exact h + +open Classical in +/-- The bound obtained by adding the component charges `30 * Fintype.card (Inputs A p w t) + 2 * +localCost (Fintype.card (Code A)) * p + 100000 * (1 + p + w) * (2 + t + w)`. -/ +def countCost (p w t : ℕ) := + 30 * Fintype.card (Inputs A p w t) + 2 * localCost (Fintype.card (Code A)) * p + + 100000 * (1 + p + w) * (2 + t + w) + +open Classical in +theorem checked_counts (hp : p ≤ 2 ^ t) : + Weight F (fun x : Inputs A p w t → Bool => if ∀ s, tally A x s = expected A x s then 1 else 0) + ((1 + Fintype.card A.I) * countCost A p w t) := by + let v := 1 + t + w + let I := Inputs A p w t + let test (s : A.I) (x : I → Bool) := if tally A x s = expected A x s then (1 : F) else 0 + have hh (s : A.I) : Weight F (test s) (countCost A p w t - 5 * Fintype.card I) := by + have ht (x : I → Bool) : tally A x s < 2 ^ v := calc + tally A x s ≤ Fintype.card (Fin p) := Fintype.card_subtype_le (fun j + => selector A (raw A x j) = s) + _ ≤ 2 ^ t := by simpa using hp + _ < 2 ^ v := Nat.pow_lt_pow_right (by decide) (by omega) + have he (x : I → Bool) : expected A x s < 2 ^ v := + (number_lt _).trans_le (Nat.pow_le_pow_right (by decide) (by omega)) + apply (register_eq (tally_net A s v) (expected_net A s v) ht he).mono + unfold countCost I v + ring_nf + omega + have net := Weight.finite_product test hh + simp only [test, prod_ite_zero, mem_univ, forall_const, prod_const_one] at net + apply net.mono + have ht : 5 * Fintype.card I ≤ countCost A p w t := by unfold countCost I; omega + rw [Nat.add_sub_of_le ht, add_mul, one_mul] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +/- +# A trivalent network for one packet class + +Prepare marks and values with bounded input dependence. The remaining +work is one batched read, histogram comparisons, and independent +constant-arity weights. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel + +open Install Diagonal Finset PackCode +variable {F : Type} [Field F] {n h p w t : ℕ} (A : Expansion F n h) (i : Fin n) (mode : Mode) + +open Classical in +private def requests (x : Inputs A p w t → Bool) : Index t ⊕ Index t ⊕ Index t → Bool := + Sum.elim (valueAt A x) (Sum.elim (fun j => mode.share && markAt A i mode x j) (compact A x)) + +open Classical in +private theorem request_dep : + Depends (requests (p := p) (w := w) (t := t) A i mode) (1 + Fintype.card (Code A)) := by + have both (j : Index t) : + ∃ S : Finset (Inputs A p w t), S.card ≤ 1 + Fintype.card (Code A) ∧ + ∀ x y, (∀ u ∈ S, x u = y u) → + valueAt A x j = valueAt A y j ∧ markAt A i mode x j = markAt A i mode y j := by + by_cases hj : ∃ k, position A p k = j.val + · obtain ⟨⟨u, k⟩, he⟩ := hj + obtain ⟨S, hS, hs⟩ := raw_support A (w := w) (t := t) u + refine ⟨S, by omega, fun x y h => ?_⟩ + simp only [valueAt, markAt, ← he, (position_inj A p).extend_apply, hs x y h, and_self] + · refine ⟨∅, by simp, fun x y _ => ?_⟩ + simp only [valueAt, markAt, Function.extend_apply' _ _ _ hj, and_self] + rintro (j|j|j) + · obtain ⟨S, hS, he⟩ := both j + exact ⟨S, hS, fun x y h => (he x y h).1⟩ + · obtain ⟨S, hS, he⟩ := both j + exact ⟨S, hS, fun x y h => congrArg (mode.share && ·) (he x y h).2⟩ + · exact ⟨{.inr (.inr j)}, by simp, fun x y h => h _ (mem_singleton_self _)⟩ + +open Classical in +private theorem checked_stream : + Weight F (fun x : Inputs A p w t → Bool => + if mode.share = true → Matches t (valueAt A x) (markAt A i mode x) (compact A x) then 1 else + 0) + (Fintype.card (Inputs A p w t) + localCost (1 + Fintype.card (Code A)) * (3 * 2 ^ t) + + 210000 * 2 ^ t * (t + 1) ^ 3) := by + have hr := (request_dep (p := p) (w := w) (t := t) A i mode).bnet F + have hs := hr.weight (matches_net F t) + convert hs using 1 + · funext x + cases he : mode.share <;> simp [requests, Matches, he] + · simp only [Fintype.card_sum, Fintype.card_fin, Index] + ring + +open Classical in +private theorem entries_net : + Weight F (fun x : Inputs A p w t → Bool => ∏ j, entry A i mode (row A x j)) + (Fintype.card (Inputs A p w t) + 2 * (p * Fintype.card (Row A)) + + p * (8 * 2 ^ Fintype.card (Row A))) := by + have h := Weight.sigma_prod (fun _ : Fin p => entry A i mode) + (fun _ => Weight.dense F (Row A) (entry A i mode)) + let addr (z : Σ _ : Fin p, Row A) : Inputs A p w t := .inl (z.1, z.2) + convert h.pull addr using 1 <;> try rfl + simp only [Fintype.card_sigma, sum_const, card_univ, nsmul_eq_mul, Nat.cast_id, Fintype.card_fin] + +open Classical in +private def rawCost (p w t : ℕ) := + 12 * Fintype.card (Inputs A p w t) + (1 + Fintype.card A.I) * countCost A p w t + + localCost (1 + Fintype.card (Code A)) * (3 * 2 ^ t) + 210000 * 2 ^ t * (t + 1) ^ 3 + + 2 * (p * Fintype.card (Row A)) + p * (8 * 2 ^ Fintype.card (Row A)) + +open Classical in +private theorem raw_net (hp : p ≤ 2 ^ t) : + Weight F (kernel (p := p) (w := w) (t := t) A i mode) (rawCost A p w t) := by + have h := (checked_counts (w := w) A hp).mul ((checked_stream A i mode).mul (entries_net A i + mode)) + convert h using 1 + · funext x + simp only [kernel, ite_and, ite_mul, one_mul, zero_mul] + · unfold rawCost + ring + +open Classical in +/-- The construction uses `1 + Fintype.card (Row A) + Fintype.card A.I` for its intermediate +`M`. -/ +def cost := + let M := 1 + Fintype.card (Row A) + Fintype.card A.I + 12 * M + (1 + Fintype.card A.I) * (30 * M + 2 * localCost (Fintype.card (Code A)) + 400000) + + 3 * localCost (1 + Fintype.card (Code A)) + 210000 + + 2 * Fintype.card (Row A) + 8 * 2 ^ Fintype.card (Row A) + +open Classical in +theorem kernel_net (hp : p ≤ 2 ^ t) : + Weight F (kernel (p := p) (w := w) (t := t) A i mode) (cost A * 2 ^ t * (1 + w + t) ^ 3) := by + apply (raw_net A i mode hp).mono + let M := 1 + Fintype.card (Row A) + Fintype.card A.I + let v := 1 + w + t + let U := 2 ^ t * v ^ 3 + have hB : 0 < 2 ^ t := by positivity + have hv : 0 < v := by omega + have ht : 2 ^ t ≤ U := Nat.le_mul_of_pos_right _ (by positivity) + have hp' := hp.trans ht + have hv' : v ≤ U := (Nat.le_pow (by decide : 0 < 3)).trans (Nat.le_mul_of_pos_left _ hB) + have hi : Fintype.card (Inputs A p w t) ≤ M * U := by + rw [Fintype.card_sum, Fintype.card_sum (α := A.I × Fin w), + Fintype.card_prod (Fin p) (Row A), Fintype.card_prod A.I (Fin w), + Fintype.card_fin, Fintype.card_fin, Fintype.card_fin] + calc + _ ≤ U * Fintype.card (Row A) + (Fintype.card A.I * U + U) := by gcongr; omega + _ = _ := by unfold M; ring + have hw : (1 + p + w) * (2 + t + w) ≤ 4 * U := by + calc + _ ≤ (2 ^ t + v) * (2 * v) := Nat.mul_le_mul (by omega) (by omega) + _ ≤ (2 ^ t * v + 2 ^ t * v) * (2 * v) := by + gcongr + · exact Nat.le_mul_of_pos_right _ hv + · exact Nat.le_mul_of_pos_left _ hB + _ = 4 * 2 ^ t * v ^ 2 := by ring + _ ≤ _ := by unfold U; rw [← mul_assoc]; gcongr; decide + have hh : countCost A p w t ≤ (30 * M + 2 * localCost (Fintype.card (Code A)) + 400000) * U := by + unfold countCost + rw [mul_assoc 100000] + calc + _ ≤ 30 * (M * U) + 2 * localCost (Fintype.card (Code A)) * U + 100000 * (4 * U) := by gcongr + _ = _ := by ring + have hh' : 210000 * 2 ^ t * (t + 1) ^ 3 ≤ 210000 * U + := by unfold U; rw [← mul_assoc]; gcongr; omega + unfold rawCost + calc + _ ≤ 12 * (M * U) + (1 + Fintype.card A.I) * ((30 * M + 2 * localCost (Fintype.card (Code A)) + + 400000) * U) + + localCost (1 + Fintype.card (Code A)) * (3 * U) + 210000 * U + + 2 * (U * Fintype.card (Row A)) + U * (8 * 2 ^ Fintype.card (Row A)) := by gcongr + _ = cost A * U := by unfold cost; dsimp only [M]; ring + _ = _ := by rw [mul_assoc] + +open Classical in +/-- The quantity computed by `prefixSize A + reserve A + 1`. -/ +def rowSize := prefixSize A + reserve A + 1 +open Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def height (p : ℕ) := Nat.clog 2 ((p + 1) * rowSize A) + +open Classical in +theorem height_bounds (p : ℕ) : + (p + 1) * rowSize A ≤ 2 ^ height A p ∧ 2 ^ height A p ≤ 2 * ((p + 1) * rowSize A) := by + let k := (p + 1) * rowSize A + have hk : 0 < k := by unfold k rowSize; positivity + refine ⟨Nat.le_pow_clog (by decide) _, ?_⟩ + have hu : height A p ≤ Nat.log 2 k + 1 := + Nat.clog_le_of_le_pow (Nat.lt_pow_succ_log_self (by decide : 1 < 2) k).le + calc + _ ≤ 2 ^ (Nat.log 2 k + 1) := Nat.pow_le_pow_right (by decide) hu + _ ≤ 2 * k := by rw [pow_succ']; exact Nat.mul_le_mul_left _ (Nat.pow_log_le_self _ hk.ne') + +open Classical in +theorem capacity (p : ℕ) : p * (prefixSize A + reserve A) ≤ 2 ^ height A p := + (Nat.mul_le_mul (Nat.le_succ p) (Nat.le_succ _)).trans (height_bounds A p).1 + +open Classical in +/-- The rate used in the `PacketKernel` construction. -/ +def rate := + Weight.switchCost 2 * (Fintype.card (Row A) + Fintype.card A.I + 2 * rowSize A + + cost A * (2 * rowSize A) * (2 + Nat.clog 2 (rowSize A)) ^ 3 + 1) + +open Classical in +/-- A two-bit mode can vary with the report. The cost per member is +polynomial in the width of the count fields and independent of the cut. -/ +theorem switched_net (pick : (Fin 2 → Bool) → Mode) (hp : p < 2 ^ w) : + Weight F (fun x : Fin 2 ⊕ Inputs A p w (height A p) → Bool => + kernel A i (pick (x ∘ Sum.inl)) (x ∘ Sum.inr)) (rate A * (1 + p) * (1 + w) ^ 3) := by + let t := height A p + have hs : 0 < rowSize A := by unfold rowSize; omega + obtain ⟨hlo, hhi⟩ := height_bounds A p + have hpt : p ≤ 2 ^ t := ((Nat.le_succ p).trans (Nat.le_mul_of_pos_right _ hs)).trans hlo + have ht : t ≤ w + Nat.clog 2 (rowSize A) := by + apply Nat.clog_le_of_le_pow + rw [pow_add] + exact Nat.mul_le_mul hp (Nat.le_pow_clog (by decide) _) + let v := 2 + Nat.clog 2 (rowSize A) + have hlen : 1 + w + t ≤ v * (1 + w) := by unfold v; ring_nf; omega + have hc : Fintype.card (Inputs A p w t) ≤ + p * Fintype.card (Row A) + Fintype.card A.I * w + 2 * ((p + 1) * rowSize A) := by + rw [Fintype.card_sum, Fintype.card_sum (α := A.I × Fin w), + Fintype.card_prod (Fin p) (Row A), Fintype.card_prod A.I (Fin w), + Fintype.card_fin, Fintype.card_fin, Fintype.card_fin, ← add_assoc] + exact Nat.add_le_add_left hhi _ + apply (Weight.switch _ (fun z => kernel_net A i (pick z) (w := w) hpt)).mono + rw [Fintype.card_fin, rate, mul_assoc _ (1 + p), mul_assoc (Weight.switchCost 2)] + apply Nat.mul_le_mul_left + calc + _ ≤ p * Fintype.card (Row A) + Fintype.card A.I * w + 2 * ((p + 1) * rowSize A) + + cost A * (2 * ((p + 1) * rowSize A)) * (v * (1 + w)) ^ 3 + 1 := by gcongr + _ ≤ _ := by rw [show 2 + Nat.clog 2 (rowSize A) = v from rfl]; ring_nf; omega + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +/- # Private assignments for a fixed class and public report -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel + +open Diagonal +variable {F : Type} [Field F] {n h p w t r N d : ℕ} (A : Expansion F n h) + {hn : 2 ≤ n} {R : A.Report r d} {c : Class r} + +attribute [local instance] Expansion.memberOrder + +open Classical in +/-- The non-strict comparison associated with the packet membership order. -/ +private abbrev memberLE : LE (A.Members hn R c) := (A.memberOrder hn R c).toLE +open Classical in +/-- The strict comparison associated with the packet membership order. -/ +private abbrev memberLT : LT (A.Members hn R c) := (A.memberOrder hn R c).toLT + +attribute [local instance] memberLE memberLT + +open Classical in +/-- The value specified by `@OrderIso (Fin p) (A.Members hn R c) _ (A.memberOrder hn R c).toLE`. -/ +abbrev MemberOrder (hn : 2 ≤ n) (R : A.Report r d) (c : Class r) (p : ℕ) := + @OrderIso (Fin p) (A.Members hn R c) _ (A.memberOrder hn R c).toLE + +open Classical in +/-- Computes the symbol by the application `encode A R.1 (A.shared N R c) (z.1.val (e j)) (z.2 +(e j))`. -/ +def symbol (e : MemberOrder A hn R c p) (z : A.Alphabet hn N R c) (j : Fin p) : Code A → Bool := + encode A R.1 (A.shared N R c) (z.1.val (e j)) (z.2 (e j)) + +open Classical in +theorem symbol_injective (e : MemberOrder A hn R c p) : + Function.Injective (symbol A (N := N) e) := by + rintro ⟨s, x⟩ ⟨s', y⟩ he + have hs : s = s' := by + apply Subtype.ext + funext j + obtain ⟨k, rfl⟩ := e.surjective j + simpa only [symbol, selector_encode] using congrArg (selector A) (congrFun he k) + subst s' + congr 1 + funext j k + obtain ⟨l, rfl⟩ := e.surjective j + have h' := congrFun (congrFun he l) (.inr (k.castLE (width_le A _ _ _))) + simpa [symbol, encode, k.isLt] using h' + +open Classical in +private theorem multiplicity_equiv {I J Z : Type} [Fintype I] [Fintype J] [DecidableEq Z] + (e : I ≃ J) (f : J → Z) (z : Z) : multiplicity (f ∘ e) z = multiplicity f z := + Fintype.card_congr (e.subtypeEquiv (fun _ => Iff.rfl)) + +open Classical in +theorem symbol_iff (e : MemberOrder A hn R c p) (x : Inputs A p w t → Bool) : + (∀ j, ok A R.1 (A.shared N R c) (raw A x j)) ∧ + (∀ s, tally A x s = (R.2 (c, s)).val) ↔ ∃ z : A.Alphabet hn N R c, symbol A e z = raw A x + := by + constructor + · rintro ⟨hraw, ht⟩ + let f := selector A ∘ raw A x + let s : A.Selectors hn R c := + ⟨f ∘ e.symm, fun k => (multiplicity_equiv e.symm.toEquiv f k).trans (ht k)⟩ + let z : A.Alphabet hn N R c := + ⟨s, fun j => crossing A R.1 (A.shared N R c) (raw A x (e.symm j))⟩ + refine ⟨z, funext fun j => ?_⟩ + exact (hraw (e.symm (e j))).trans (by rw [e.symm_apply_apply]) + · rintro ⟨z, hz⟩ + constructor + · rw [← hz] + exact fun j => ok_encode A _ _ _ _ + · intro s + have hf : selector A ∘ raw A x = z.1.val ∘ e := by + funext j + rw [← hz] + exact selector_encode A _ _ _ _ + rw [tally, hf] + exact (multiplicity_equiv e.toEquiv _ _).trans (z.1.2 s) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end + +/- # Checking a packed shared symbol in a fixed rectangular layout -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel + +open Finset Diagonal Diagonal.Expansion PackCode +variable {F : Type} [Field F] {n h p w t r N d : ℕ} (A : Expansion F n h) + {hn : 2 ≤ n} {R : A.Report r d} {c : Class r} + +attribute [local instance] memberOrder memberLE memberLT + +private theorem fixed_rank {P : Type} [LinearOrder P] [Fintype P] (e : Fin p ≃o P) + (D : ℕ) (j : Fin p) (k : Fin D) : + ((packOrder (fun _ : P => D)).symm (toLex ⟨e j, k⟩)).val = (finProdFinEquiv (j, k)).val := by + rw [packOrder, serial_rank] + change start (fun _ => D) (e j) + k.val = k.val + D * j.val + rw [start, sum_filter, ← e.toEquiv.sum_comp] + change (∑ i, if e i < e j then D else 0) + k.val = _ + simp only [e.lt_iff_lt, ← sum_filter] + rw [show univ.filter (fun i => i < j) = Iio j by ext; simp] + simp [Fin.card_Iio, mul_comm, add_comm] + +theorem symbol_width (e : MemberOrder A hn R c p) (z : A.Alphabet hn N R c) : + A.classWidth R c ≤ p * (prefixSize A + reserve A) := by + have hp : Fintype.card (A.Members hn R c) = p := (Fintype.card_congr e.symm.toEquiv).trans + (Fintype.card_fin _) + rw [A.classWidth_spec z.1] + calc + _ ≤ ∑ _ : A.Members hn R c, (prefixSize A + reserve A) := by + apply sum_le_sum + intro j _ + rw [add_comm] + exact Nat.add_le_add_left (width_le A _ _ true) _ + _ = _ := by simp only [sum_const, card_univ, hp, nsmul_eq_mul, Nat.cast_id] + +private theorem value_at (x : Inputs A p w t → Bool) (j : Fin p) (k : Code A) + (i : Index t) (hi : position A p (j, k) = i.val) : + valueAt A x i = raw A x j k := by + unfold valueAt + rw [← hi, (position_inj A p).extend_apply] + +private theorem mark_at (i : Fin n) (mode : Mode) (x : Inputs A p w t → Bool) (j : Fin p) + (k : Code A) (u : Index t) (hu : position A p (j, k) = u.val) : + markAt A i mode x u = Sum.elim (fun _ => true) + (fun b => decide (b.val < used A i mode.cut (raw A x j))) k := by + unfold markAt + rw [← hu, (position_inj A p).extend_apply] + +theorem match_code (e : MemberOrder A hn R c p) (z : A.Alphabet hn N R c) (mode : Mode) + (x : Inputs A p w t → Bool) (hz : symbol A e z = raw A x) + (hcut : mode.cut = A.shared N R c) (hsh : A.shared N R c = true) + (hcap : p * (prefixSize A + reserve A) ≤ 2 ^ t) : + Matches t (valueAt A x) (markAt A R.1 mode x) (compact A x) ↔ + A.alphabetCode hn N R c z = compact A x ∘ Fin.castLE ((symbol_width A e z).trans hcap) := by + let P := A.Members hn R c + let : LT P := (A.memberOrder hn R c).toLT + let D := fun _ : P => reserve A + let H := fun _ : P => prefixSize A + have hp : Fintype.card P = p := (Fintype.card_congr e.symm.toEquiv).trans (Fintype.card_fin _) + have hs : A.selectorWidth hn R c = p * prefixSize A := by + change (∑ _j : P, prefixSize A) = _ + simp only [sum_const, card_univ, nsmul_eq_mul, Nat.cast_id, hp] + have hc : A.selectorWidth hn R c + ∑ j, D j ≤ 2 ^ t := by + simpa only [D, sum_const, card_univ, nsmul_eq_mul, Nat.cast_id, hp, hs, ← mul_add] using hcap + have hu (j) : used A R.1 mode.cut (raw A x j) = A.crossLen z (e j) := by + simp only [← hz, used, symbol, selector_encode, hcut, crossLen] + have hpos (j : Fin p) (k : Fin (reserve A)) : + position A p (j, .inr k) = (grid D hc (e j) k).val := by + change p * prefixSize A + (finProdFinEquiv (j, k)).val = + A.selectorWidth hn R c + ((packOrder D).symm (toLex ⟨e j, k⟩)).val + rw [hs] + exact congrArg _ (fixed_rank e (reserve A) j k).symm + refine A.matches_alphabet z hsh D (fun _ => width_le A _ _ _) hc _ ?_ ?_ ?_ + · intro i + constructor + · intro hm + have hex : ∃ y, position A p y = i.val := by + by_contra! hh + unfold markAt at hm + rw [Function.extend_apply' _ _ _ (not_exists.mpr hh)] at hm + contradiction + obtain ⟨⟨j, k|k⟩, he⟩ := hex + · left + rw [hs, ← he] + exact (finProdFinEquiv (j, k)).isLt + · right + rw [mark_at A R.1 mode x j (.inr k) i he] at hm + refine ⟨e j, k, ?_, Fin.ext ((hpos j k).symm.trans he)⟩ + simpa only [Sum.elim_inr, decide_eq_true_eq, hu] using hm + · rintro (hi | ⟨j, k, hk, rfl⟩) + · rw [hs] at hi + obtain ⟨⟨j, k⟩, hh⟩ := finProdFinEquiv.surjective (⟨i.val, hi⟩ : Fin (p * prefixSize A)) + exact mark_at A R.1 mode x j (.inl k) i (congrArg Fin.val hh) + · obtain ⟨u, rfl⟩ := e.surjective j + rw [mark_at A R.1 mode x u (.inr k) _ (hpos u k)] + simp only [Sum.elim_inr, decide_eq_true_eq, hu, hk] + · intro i + obtain ⟨⟨j, k⟩, rfl⟩ := (packOrder H).symm.surjective i + obtain ⟨u, rfl⟩ := e.surjective j + have hh := pack_at H le_rfl (fun j => A.selectorCode (z.1.val j)) (toLex ⟨e u, k⟩) + calc + _ = raw A x u (.inl k) := by + apply value_at + exact (fixed_rank e (prefixSize A) u k).symm + _ = _ := by rw [← hz]; exact hh.symm + · intro j k + obtain ⟨u, rfl⟩ := e.surjective j + rw [value_at A x u (.inr _) _ (hpos u _), ← hz] + simp [symbol, encode, k.isLt] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PacketKernel +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/PinIndexRead.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/PinIndexRead.lean new file mode 100644 index 0000000000..0a3c4a47b5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/PinIndexRead.lean @@ -0,0 +1,993 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.LocalReceive +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.TemplateSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.LocalBank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Vector.Cases + +/-! +# A compact index for the old processor inputs + +An old physical bit is determined by its tape position and the lower +endpoint of its link. The quotient of the address by the link width +gives the sum of the endpoints modulo the number of processors. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex + +open Diagonal +variable {R N l r n : ℕ} + +/-- Indexes the domain by the coordinates of `Fin l ⊕ (Fin (4 * N / r) × Fin (3 * r))`. -/ +abbrev Domain (N l r : ℕ) := Fin l ⊕ (Fin (4 * N / r) × Fin (3 * r)) + +/-- In the case `.inl t`, this construction gives `t.1.val`. -/ +def old : Pin N l l r → ℕ + | .inl t => t.1.val + | .inr (.inl _) => 0 + | .inr (.inr t) => t.1.val.1.val + +theorem old_lt (q : Pin N l l r) (hr : 0 < 3 * r) : old q < 3 * r := by + rcases q with q | q | q + · exact q.1.isLt + · exact hr + · exact q.1.val.1.isLt + +/-- The physical of type `Option (Links.Slot R N)`, constructed using `finProdFinEquiv.symm +⟨p.val, h⟩`. -/ +def physical (p : Fin (N / 4)) (u : Fin R) : Option (Links.Slot R N) := + if h : p.val < R * (N / (4 * R)) then + let z := finProdFinEquiv.symm ⟨p.val, h⟩ + let v := z.1 - u + if k : u < v then some (⟨(u, v), k⟩, z.2) else none + else none + +theorem physical_address (e : Links.Slot R N) : + physical (Links.address e) e.1.val.1 = some e := by + let z := (e.1.val.1 + e.1.val.2, e.2) + have h : (Links.address e).val < R * (N / (4 * R)) := (finProdFinEquiv z).isLt + have he : (⟨(Links.address e).val, h⟩ : Fin (R * (N / (4 * R)))) = finProdFinEquiv z := rfl + let _ : NeZero R := ⟨e.1.val.1.pos.ne'⟩ + simp [physical, h, he, z, e.1.property] + +theorem physical_spec {p : Fin (N / 4)} {u : Fin R} {e : Links.Slot R N} + (h : physical p u = some e) : Links.address e = p ∧ e.1.val.1 = u := by + let _ : NeZero R := ⟨u.pos.ne'⟩ + unfold physical at h + split at h <;> try contradiction + rename_i hp + let z := finProdFinEquiv.symm (⟨p.val, hp⟩ : Fin (R * (N / (4 * R)))) + dsimp only at h + split at h <;> try contradiction + cases Option.some.inj h + refine ⟨Fin.ext ?_, rfl⟩ + change (finProdFinEquiv (u + (z.1 - u), z.2)).val = p.val + rw [add_sub_cancel] + exact congrArg Fin.val (finProdFinEquiv.apply_symm_apply ⟨p.val, hp⟩) + +/-- In the case `.inl x`, this construction gives `some (.inl (j, x))`. -/ +def prior (p : Machine.Ports N l l) (j : Fin (3 * r)) : Option (Pin N l l r) := + match p with + | .inl x => some (.inl (j, x)) + | .inr (.inl x) => if j.val = 0 then some (.inr (.inl x)) else none + | .inr (.inr x) => (physical x j).map (fun t => .inr (.inr t)) + +theorem prior_old (q : Pin N l l r) (j : Fin (3 * r)) (h : old q = j.val) : + prior q.position j = some q := by + rcases q with ⟨u, v⟩ | q | q + · rw [← (show u = j from Fin.ext h)]; rfl + · change 0 = j.val at h + simp [Pin.position, prior, h.symm] + · rw [← (show q.1.val.1 = j from Fin.ext h)] + simp [Pin.position, prior, physical_address] + +theorem prior_spec {p : Machine.Ports N l l} {j : Fin (3 * r)} {q : Pin N l l r} + (h : prior p j = some q) : q.position = p ∧ old q = j.val := by + rcases p with p | p | p + · cases Option.some.inj h; exact ⟨rfl, rfl⟩ + · simp only [prior] at h + split at h <;> try contradiction + cases Option.some.inj h + exact ⟨rfl, by symm; assumption⟩ + · obtain ⟨e, he, rfl⟩ := Option.map_eq_some_iff.mp h + obtain ⟨hp, hj⟩ := physical_spec he + simp [Pin.position, old, hp, hj] + +variable (fa : Machine.Ports N l l → Label n r) (hfa : ∀ z, multiplicity fa z * r ^ n ≤ 4 * N) + (i : Fin n) (g : Fin r) + +/-- The subtype of `p` satisfying `fa p i = g`. -/ +abbrev Selected := {p // fa p i = g} + +/-- The numbering depends only on the coordinate and symbol, not on +the worker role or current report. -/ +def portIndex : Selected fa i g ↪ Fin (4 * N / r) := + (Fintype.equivFin _).toEmbedding.trans + (Fin.castLEEmb ((Nat.le_div_iff_mul_le g.pos).mpr (project_bound fa hfa i g))) + +/-- Returns `some ((Fintype.equivFin (Selected fa i g)).symm ⟨j.val, h⟩).val` when `h : j.val < +Fintype.card (Selected fa i g)` holds, and `none` otherwise. -/ +def readPort (j : Fin (4 * N / r)) : Option (Machine.Ports N l l) := + if h : j.val < Fintype.card (Selected fa i g) then + some ((Fintype.equivFin (Selected fa i g)).symm ⟨j.val, h⟩).val else none + +theorem readPort_index (p : Selected fa i g) : + readPort fa i g (portIndex fa hfa i g p) = some p.val := by + have he : (portIndex fa hfa i g p).val = (Fintype.equivFin _ p).val := rfl + simp [readPort, he] + +theorem index_readPort (p : Selected fa i g) (j : Fin (4 * N / r)) + (he : readPort fa i g j = some p.val) : portIndex fa hfa i g p = j := by + unfold readPort at he + split at he <;> try contradiction + rename_i hj + have h : (Fintype.equivFin (Selected fa i g)).symm ⟨j.val, hj⟩ = p := + Subtype.ext (Option.some.inj he) + apply Fin.ext + change (Fintype.equivFin _ p).val = j.val + rw [← h, Equiv.apply_symm_apply] + +open Controller +variable {F : Type} [Field F] {d h B : ℕ} {i} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} {hn : 2 ≤ n} + (hf : ∀ z, multiplicity P.colors z * r ^ n ≤ 4 * N) + +variable (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) + +open Classical in +/-- The subtype of `q : Pin N l l r` satisfying `incident s (.inl q)`. -/ +abbrev Here := {q : Pin N l l r // incident s (.inl q)} + +open Classical in +/-- The condition `∃ j, q = .inl (s.site, j)` on the specified data. -/ +def own (q : Pin N l l r) := ∃ j, q = .inl (s.site, j) + +open Classical in +theorem here_iff (q : Pin N l l r) : + incident s (.inl q) ↔ own s q ∨ target s (.inl q) = s.site := by + rcases q with ⟨u, j⟩ | q + · simp [incident, own, source, Expansion.extraSrc, Pin.src] + · simp [incident, own, source, target, Expansion.extraSrc, Expansion.extraDst, Pin.src] + +open Classical in +/-- The value specified by `Layout.axis hn i (workerAt s)`. -/ +def axis := Layout.axis hn i (workerAt s) +open Classical in +/-- The value specified by `Layout.symbol (workerAt s)`. -/ +def symbol := Layout.symbol (workerAt s) + +open Classical in +theorem selected (q : Pin N l l r) (ht : target s (.inl q) = s.site) : + P.colors q.position (axis s) = symbol s := by + have h : A.owner hn N s.report.val (P.colors q.position) = workerAt s := + (Worker.index r).eq_symm_apply.mpr ht + unfold axis symbol + rw [← h, ← congrArg (Layout.axis (r := r) hn) s.cut] + unfold Expansion.owner + split <;> rfl + +open Classical in +/-- In the case `.inl j`, this construction gives `some (.inl j)`. -/ +def cellPort : Domain N l r → Option (Machine.Ports N l l) + | .inl j => some (.inl j) + | .inr p => readPort P.colors (axis s) (symbol s) p.1 + +open Classical in +/-- In the case `.inl _`, this construction gives `s.site`. -/ +def cellWorker : Domain N l r → Fin (3 * r) + | .inl _ => s.site + | .inr p => p.2 + +open Classical in +/-- The indexed operation `(cellPort s e).bind fun p => prior p (cellWorker s e)`. -/ +def candidate (e : Domain N l r) : Option (Pin N l l r) := + (cellPort s e).bind fun p => prior p (cellWorker s e) + +open Classical in +/-- A literal emitted at this site always uses its own direct cell. +The second copy is suppressed even for a local literal. -/ +def decode (e : Domain N l r) : Option (Pin N l l r) := + (candidate s e).bind (fun q => + if e.isLeft ∨ target s (.inl q) = s.site ∧ ¬ own s q then some q else none) + +open Classical in +theorem decode_left (j : Fin l) : decode s (.inl j) = some (.inl (s.site, j)) := by + simp [decode, candidate, cellPort, cellWorker, prior] + +open Classical in +theorem decode_right (k : Fin (4 * N / r)) (u : Fin (3 * r)) (q : Pin N l l r) : + decode s (.inr (k, u)) = some q ↔ + readPort P.colors (axis s) (symbol s) k = some q.position ∧ + old q = u.val ∧ target s (.inl q) = s.site ∧ ¬own s q := by + unfold decode candidate cellPort cellWorker + simp only [Sum.isLeft_inr, Bool.false_eq_true, false_or, Option.bind_eq_some_iff] + constructor + · rintro ⟨q', ⟨p, hp, hp'⟩, h⟩ + split at h <;> try contradiction + cases Option.some.inj h + obtain ⟨rfl, he⟩ := prior_spec hp' + exact ⟨hp, he, by assumption⟩ + · rintro ⟨hp, he, h⟩ + exact ⟨q, ⟨q.position, hp, prior_old q u he⟩, ite_eq_left h⟩ + +open Classical in +/-- The place of type `Domain N l r` for the given inputs. -/ +def place (q : Here s) : Domain N l r := + if h : own s q.val then .inl h.choose else + .inr (portIndex _ hf _ _ ⟨q.val.position, selected s q.val ((here_iff s _).mp q.2 + |>.resolve_left h)⟩, + ⟨old q.val, old_lt _ s.site.pos⟩) + +open Classical in +theorem decode_place (q : Here s) : decode s (place hf s q) = some q.val := by + unfold place + split + · rename_i h + exact (decode_left s _).trans (congrArg some h.choose_spec.symm) + · rename_i h + exact (decode_right ..).mpr ⟨readPort_index .., rfl, ((here_iff s _).mp q.2).resolve_left h, h⟩ + +open Classical in +/-- Embeds `Here s` into `Domain N l r`. -/ +def encode : Here s ↪ Domain N l r := + ⟨place hf s, fun x y h => Subtype.ext (Option.some.inj + ((decode_place hf s x).symm.trans ((congrArg (decode s) h).trans (decode_place hf s y))))⟩ + +open Classical in +theorem decode_encode (q : Here s) : decode s (encode hf s q) = some q.val := decode_place hf s q + +open Classical in +theorem decode_eq (e : Domain N l r) (q : Pin N l l r) : + decode s e = some q ↔ ∃ hq, encode hf s ⟨q, hq⟩ = e := by + constructor + · intro he + rcases e with j | ⟨k, u⟩ + · rw [decode_left, Option.some.injEq] at he + have h : own s q := ⟨j, he.symm⟩ + refine ⟨(here_iff s q).mpr (.inl h), ?_⟩ + change place hf s _ = _ + simp only [place, dite_eq_left h, Sum.inl.injEq] + exact congrArg Prod.snd (Sum.inl.inj (h.choose_spec.symm.trans he.symm)) + · obtain ⟨hp, hu, ht, h⟩ := (decode_right ..).mp he + refine ⟨.inr ht, ?_⟩ + change place hf s _ = _ + simp only [place, dite_eq_right h, Sum.inr.injEq] + exact Prod.ext (index_readPort _ hf _ _ _ _ hp) (Fin.ext hu) + · rintro ⟨hq, rfl⟩ + exact decode_encode hf s ⟨q, hq⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex +end + +section +/- # Agreement of batched reads with the message decoder -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller + +open Diagonal +variable {F : Type} [Field F] [Fintype F] {N l n d r h B w : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) [LinearOrder (Name n r)] + {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +/-- The quantity computed by `(records P.colors h (B * P.count)).key e`. -/ +noncomputable def key (P : Format N l d n r h) (B : ℕ) (e : Edge P B) : Name n r := + (records P.colors h (B * P.count)).key e + +/-- The quantity computed by `(records P.colors h (B * P.count)).index e`. -/ +noncomputable def offset (P : Format N l d n r h) (B : ℕ) (e : Edge P B) : ℕ := + (records P.colors h (B * P.count)).index e + +omit [LinearOrder (Name n r)] [Fintype F] in +theorem ends_eq (s : X) (e : Edge P B) : + request A hn N s.report.val (key P B e) = (source s e, target s e, some (key P B e)) := by + let t := grouping P.colors A hn s.report.1 + exact Prod.ext (t.atSrc e) (Prod.ext (t.atDst e) rfl) + +variable [NeZero (N / 4)] + +theorem get_eq (hw : N ≤ 2 ^ w) (s : X) (z : Encoded.Bits (source s) (target s) (width s)) + (he : incident s z.1.val) : + C.numberInOrder.receive s z he = + get w s (key P B z.1.val) (offset P B z.1.val * width s z.1.val + z.2.val) := by + let c := channels s.report + have hq := C.pairSum s.report + let v := Links.token _ _ c.serial z z.1.2 + have hv : v.2.val < N := + v.2.isLt.trans_le ((Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ _)).trans + ((hq _).trans (Nat.div_le_self ..))) + have haddr : c.address z < 2 ^ w := by rw [← c.token_address z z.1.2]; exact hv.trans_le hw + let loc := Links.location _ _ c.serial hq C.links s.site z z.1.2 he + have hx : loc.val = routeAddress N (pairCount s.report) s.site (source s z.1.val) + (target s z.1.val) (c.address z) := c.location_eq _ _ _ _ _ _ + unfold get + rw [ends_eq] + change s.physical loc = s.physical (Fin.ofNat (N / 4) (routeAddress N (pairCount s.report) s.site + (source s z.1.val) (target s z.1.val) + ((baseAddress A hn P.colors s.report.val (key P B z.1.val) + + (offset P B z.1.val * width s z.1.val + z.2.val)) % 2 ^ w) % 2 ^ w)) + have ha := grouping_address A hn P.colors s.report.val z + change c.address z = baseAddress A hn P.colors s.report.val (key P B z.1.val) + + (offset P B z.1.val * width s z.1.val + z.2.val) at ha + rw [← ha, Nat.mod_eq_of_lt haddr, ← hx, Nat.mod_eq_of_lt (loc.isLt.trans_le ((Nat.div_le_self + ..).trans hw))] + exact congrArg s.physical (Fin.ext (Nat.mod_eq_of_lt loc.isLt).symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- +# Metadata for a candidate pin + +The tape position determines the label and literal offset. To decide +whether an old physical bit exists, only its matching number and +the proposed lower processor index are needed. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex + +open Controller Diagonal +variable {N l r n : ℕ} + +open Classical in +/-- The kind used in the `PinIndex` construction. -/ +inductive Kind (r : ℕ) where + | empty + | literal + | broadcast + | link (j : Fin (3 * r)) + deriving Fintype + +open Classical in +theorem card_kind (r : ℕ) : Fintype.card (Kind r) = 3 * r + 3 := by + let e : Kind r ≃ Option (Option (Option (Fin (3 * r)))) := { + toFun + | .empty => none + | .literal => some none + | .broadcast => some (some none) + | .link j => some (some (some j)) + invFun + | none => .empty + | some none => .literal + | some (some none) => .broadcast + | some (some (some j)) => .link j + left_inv x := by cases x <;> rfl + right_inv x := by rcases x with _ | (_ | (_ | _)) <;> rfl + } + rw [Fintype.card_congr e] + simp + +open Classical in +/-- In the case `none`, this construction gives `.empty`. -/ +def kind : Option (Machine.Ports N l l) → Kind r + | none => .empty + | some (.inl _) => .literal + | some (.inr (.inl _)) => .broadcast + | some (.inr (.inr p)) => + if hp : p.val < 3 * r * (N / (4 * (3 * r))) then .link (finProdFinEquiv.symm ⟨p.val, hp⟩).1 + else .empty + +open Classical in +/-- Zero means absent, one means literal, and two means a private pin. -/ +def mode (k : Kind r) (j : Fin (3 * r)) : ℕ := + match k with + | .empty => 0 + | .literal => 1 + | .broadcast => if j.val = 0 then 2 else 0 + | .link a => if j < a - j then 2 else 0 + +open Classical in +/-- In the case `none`, this construction gives `0`. -/ +def tag : Option (Pin N l l r) → ℕ + | none => 0 + | some (.inl _) => 1 + | some (.inr _) => 2 + +open Classical in +theorem mode_spec (p : Option (Machine.Ports N l l)) (j : Fin (3 * r)) : + mode (kind p) j = tag (p.bind fun t => prior t j) := by + rcases p with _ | (x|x|x) + · rfl + · rfl + · simp only [kind, mode, Option.bind_some, prior] + split <;> rfl + · simp only [kind, Option.bind_some, prior, physical] + split + · unfold mode + dsimp only + split <;> rfl + · rfl + +variable {F : Type} [Field F] {d h B w : ℕ} {i : Fin n} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} {hn : 2 ≤ n} + (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) + +open Classical in +/-- The indexed operation `(decode s e).any (fun q => decide (source s (.inl q) ≠ target s (.inl +q)))`. -/ +def shared (e : Domain N l r) := (decode s e).any (fun q + => decide (source s (.inl q) ≠ target s (.inl q))) + +open Classical in +/-- Transforms the indexed data by `(p.map fa).getD (fun _ => 0)`. -/ +def label [NeZero r] (fa : Machine.Ports N l l → Label n r) (p : Option (Machine.Ports N l l)) := + (p.map fa).getD (fun _ => 0) + +open Classical in +/-- Using a literal key even for a private pin gives the correct +destination, the only endpoint needed for that case. -/ +def query [NeZero r] (e : Domain N l r) : Name n r := + .inl (.inl (cellWorker s e, label P.colors (cellPort s e))) + +open Classical in +/-- The place in class of type `Option (Machine.Ports N l l) → ℕ | some (.inl j) => +(Records.partition (fun t => fa (.inl t))).index j | _ => 0` for the given inputs. -/ +def placeInClass (fa : Machine.Ports N l l → Label n r) : Option (Machine.Ports N l l) → ℕ + | some (.inl j) => (Records.partition (fun t => fa (.inl t))).index j + | _ => 0 + +open Classical in +/-- Selects the appropriate branch of `if u = b then (if u = a then 1 else 2) else 0`. -/ +def state (u a b : Fin (3 * r)) : ℕ := if u = b then (if u = a then 1 else 2) else 0 + +open Classical in +/-- The construction uses `request A hn N s.report.val (query s e)` for its intermediate `k`. -/ +def status [NeZero r] (e : Domain N l r) := + let k := request A hn N s.report.val (query s e) + state s.site k.1 k.2.1 + +open Classical in +private theorem occupied {e : Domain N l r} {q : Pin N l l r} (he : candidate s e = some q) : + cellPort s e = some q.position ∧ (cellWorker s e).val = old q := by + obtain ⟨p, hp, hp'⟩ := Option.bind_eq_some_iff.mp he + obtain ⟨rfl, ho⟩ := prior_spec hp' + exact ⟨hp, ho.symm⟩ + +variable [NeZero r] + +open Classical in +private theorem literal_key {e : Domain N l r} {u : Fin (3 * r)} {j : Fin l} + (he : candidate s e = some (.inl (u, j))) : + query s e = key P B (.inl (.inl (u, j))) ∧ + placeInClass P.colors (cellPort s e) = offset P B (.inl (.inl (u, j))) := by + obtain ⟨hp, ho⟩ := occupied s he + rw [query, hp, show cellWorker s e = u from Fin.ext ho] + exact ⟨rfl, rfl⟩ + +open Classical in +private theorem status_eq {e : Domain N l r} {q : Pin N l l r} (he : candidate s e = some q) : + status s e = state s.site (cellWorker s e) (target s (.inl q)) := by + unfold status query + rw [(occupied s he).1] + change state _ ((Worker.index r) ((Worker.index r).symm _)) _ = _ + rw [Equiv.apply_symm_apply] + rfl + +open Classical in +/-- Returns `3` when `e.isLeft` holds, and `mode (kind (cellPort s e)) (cellWorker s e)` +otherwise. -/ +def mark (e : Domain N l r) := + if e.isLeft then 3 else mode (kind (cellPort s e)) (cellWorker s e) + +open Classical in +/-- Zero for absent cells, one for private cells and two for shared cells. -/ +def activity (mark status : ℕ) : ℕ := + if mark = 3 then (if status = 0 then 2 else 1) else + if mark = 2 then (if status = 0 then 0 else 1) else + if mark = 1 ∧ status = 2 then 2 else 0 + +omit [NeZero r] in +open Classical in +private theorem literal_src (u : Fin (3 * r)) (j : Fin l) : + source s (.inl (.inl (u, j))) = u := (Worker.index r).apply_symm_apply u + +open Classical in +theorem activity_eq (e : Domain N l r) : + activity (mark s e) (status s e) = + if (decode s e).isSome then if shared s e then 2 else 1 else 0 := by + unfold mark + rw [mode_spec] + change activity (if e.isLeft then 3 else tag (candidate s e)) _ = _ + unfold shared + cases e with + | inl j => + have h : candidate s (.inl j) = some (.inl (s.site, j)) := rfl + rw [decode_left, status_eq s h] + simp [cellWorker, activity, literal_src, state] + | inr t => + cases h : candidate s (.inr t) with + | none => simp [decode, h, activity, tag] + | some q => + rw [status_eq s h] + rcases q with ⟨u, j⟩ | q + · have he : cellWorker s (.inr t) = u := Fin.ext (occupied s h).2 + rw [he] + by_cases hh : target s (.inl (.inl (u, j))) = s.site ∧ ¬own s (.inl (u, j)) + · simp only [decode, h, Option.bind_some, Sum.isLeft_inr, Bool.false_eq_true, false_or, + ite_eq_left hh, Option.any_some, literal_src] + simp [own] at hh + simp [tag, activity, state, hh.1, hh.2, Ne.symm hh.2] + · simp only [decode, h, Option.bind_some, Sum.isLeft_inr, Bool.false_eq_true, false_or, + ite_eq_right hh] + simp [own] at hh + simp [tag, activity, state] + grind + · have he : source s (.inl (.inr q)) = target s (.inl (.inr q)) := rfl + simp [decode, h, tag, activity, own, state] + grind + +variable [Fintype F] [LinearOrder (Name n r)] (C : Controller P A hn M B) + +open Classical in +/-- The value specified by `(decode s e).any fun q => C.numberInOrder.physicalBit s (.inl q) 0`. -/ +def expected (C : Controller P A hn M B) + (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) (e : Domain N l r) + := (decode s e).any fun q => C.numberInOrder.physicalBit s (.inl q) 0 + +open Classical in +theorem expected_eq [NeZero (N / 4)] (hw : N ≤ 2 ^ w) (e : Domain N l r) : + expected C s e = + if shared s e then get w s (query s e) (placeInClass P.colors (cellPort s e)) else false := by + unfold expected shared + cases he : decode s e with + | none => rfl + | some q => + obtain ⟨q', hc, hc'⟩ := Option.bind_eq_some_iff.mp he + split at hc' <;> try contradiction + cases Option.some.inj hc' + have hi : incident s (.inl q) := by + rcases e with j | ⟨k, u⟩ + · rw [decode_left, Option.some.injEq] at he + rw [← he] + exact .inl (literal_src ..) + · exact .inr ((decode_right ..).mp he).2.2.1 + by_cases hne : source s (.inl q) ≠ target s (.inl q) + · rcases q with ⟨u, j⟩ | q + · obtain ⟨hk, ho⟩ := literal_key s hc + simp only [Option.any_some, decide_eq_true_eq, ite_eq_left hne, hk, ho] + have h : width s (.inl (.inl (u, j))) = 1 := rfl + unfold physicalBit + rw [dite_eq_left ⟨hne, hi, by omega⟩, C.get_eq hw] + simp only [h, mul_one, add_zero] + · exact (hne rfl).elim + · simp [physicalBit, hne] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex +end + +/- # Batched reads of static metadata depending on the worker identifier -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) + +include hi hw in +open Classical in +theorem workerTable {J : Type} [Fintype J] (col : Coloring.B w → J) + (hc : 3 * r * Fintype.card J ≤ 2 ^ w) (f : Fin (3 * r) → J → ℕ) : + packed (U := raw _) F (C.input (i := i)) (fun s j => f s.site (col j)) 37 := by + have : Nonempty J := ⟨col 0⟩ + have : Nonempty (Fin (3 * r)) := ⟨⟨0, Nat.mul_pos (by decide) hw.pos⟩⟩ + let a : Fin (3 * r) ≃ Fin (Fintype.card (Fin (3 * r))) := finCongr (Fintype.card_fin _).symm + let b := Fintype.equivFin J + have ht := packed.const (U := raw _) F (C.input (i := i)) (fun j => (b (col j)).val) + (m := 0) (by rw [pow_zero, mul_one]; exact hi) + have hu := C.worker_net (i := i) hi ((Nat.le_pow (by decide : 0 < 5)).trans hw.pairs) + exact packed.named_table (U := raw _) (inp := C.input (i := i)) (c := 5) (d := 0 + + 2) f (by rwa [Fintype.card_fin]) (fun s (_ : Coloring.B w) => s.site) (fun _ j => col j) + a b hu ht + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +open Classical in +/-- The reachability tests on source, destination and current site +form an arbitrary static table of at most `(3*r)^3` entries. -/ +theorem packed_pair [LinearOrder (Name n r)] {c : ℕ} (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) + (key : X → Coloring.B w → Name n r) (idx : Name n r ↪ Coloring.B w) + (hk : packed (U := raw _) F C.input (fun s j => (idx (key s j)).val) c) + (f : Fin (3 * r) → Fin (3 * r) → Fin (3 * r) → ℕ) : + packed (U := raw _) F C.input (fun s j => + let e := request A hn N s.report.val (key s j) + f s.site e.1 e.2.1) (c + 92) := by + have hr : 0 < 3 * r := Nat.mul_pos (by decide) hw.pos + let _ : NeZero (3 * r) := ⟨Nat.ne_of_gt hr⟩ + let fwd : Query n r → Fin ((3 * r) * (3 * r)) := fun e => finProdFinEquiv (e.1, e.2.1) + have hp := packed_request A hn P.colors hw hi C.input C.countPort (fun s : X => s.report.val) i + Invocation.cut C.counts_eq key idx hk (fun j => (fwd j).val) + have hu := C.worker_net (i := i) hi ((Nat.le_pow (by decide : 0 < 5)).trans hw.pairs) + have hcap : 3 * r * ((3 * r) * (3 * r)) ≤ 2 ^ w := by + rw [show 3 * r * ((3 * r) * (3 * r)) = (3 * r) ^ 3 by ring] + exact (Nat.pow_le_pow_right hr (by decide : 3 ≤ 5)).trans hw.pairs + let k (u v : ℕ) := + let p := finProdFinEquiv.symm (Fin.ofNat ((3 * r) * (3 * r)) v) + f (Fin.ofNat (3 * r) u) p.1 p.2 + have H := packed.binary k hcap hu hp (fun _ _ => Fin.isLt _) (fun _ _ => Fin.isLt _) + convert H.mono (n := c + 92) (by omega) using 1 + funext s j + have e {a : ℕ} [NeZero a] (v : Fin a) : Fin.ofNat a v.val = v := Fin.ext (Nat.mod_eq_of_lt v.isLt) + simp only [k, e, fwd, Equiv.symm_apply_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- # Reading worker-specific pin metadata from small fixed tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex + +open Controller Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) (hb : 100 * N ≤ 2 ^ w) + (cell : Coloring.B w → Domain N l r) + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +include hw hi in +open Classical in +private theorem left {f g : Vector.Array X w} {a b : ℕ} + (hf : packed (U := raw _) F C.input f a) (hg : packed (U := raw _) F C.input g b) : + packed (U := raw _) F C.input (fun s j => if (cell j).isLeft then f s j else g s j) + (max a b + 26) := by + have ht := packed.const (U := raw _) F (C.input (i := i)) + (fun j => if (cell j).isLeft then 0 else 1) (m := 0) (w := w) (by + rw [pow_zero, mul_one] + exact hi) + have hz := packed.const (U := raw _) F (C.input (i := i)) (fun _ => 0) (m := 0) (w + := w) (by rw [pow_zero, mul_one]; exact hi) + have h2 : 1 < 2 ^ w := Nat.one_lt_pow (by have := hw.large; omega) (by decide) + have h := ht.choose_eq hz hf hg (by intro s j; dsimp; split <;> omega) (fun _ _ + => Nat.two_pow_pos w) + convert h.mono (n := max a b + 26) (by omega) using 1 + funext s j + cases (cell j).isLeft <;> rfl + +include hw hi hb in +open Classical in +/-- Any function of the worker's selected port can be tabulated before +the old processor index is attached to each copy. -/ +theorem packed_port (f : Option (Machine.Ports N l l) → ℕ) : + packed (U := raw _) F C.input (fun (s : X) j => f (cellPort s (cell j))) 64 := by + let col : Coloring.B w → Option (Fin (4 * N / r)) := fun j => + Sum.elim (fun _ => none) (fun p => some p.1) (cell j) + have hsize : 3 * r * Fintype.card (Option (Fin (4 * N / r))) ≤ 2 ^ w := by + rw [Fintype.card_option, Fintype.card_fin] + have hg := Nat.mul_div_le (4 * N) r + have hr : 3 * r ≤ (3 * r) ^ 2 := Nat.le_pow (by decide) + have := C.links + nlinarith + let v (u : Fin (3 * r)) (k : Option (Fin (4 * N / r))) := + let a := (Worker.index r).symm u + f (k.bind (readPort P.colors (Layout.axis hn i a) (Layout.symbol a))) + have hp := C.workerTable (i := i) hw hi col hsize v + have hl := packed.const (U := raw _) F (C.input (i := i)) + (fun j => Sum.elim (fun x => f (some (.inl x))) (fun _ => 0) (cell j)) + (m := 0) (w := w) (by rw [pow_zero, mul_one]; exact hi) + convert (left C hw hi cell hl hp).mono (n := 64) (by decide) using 1 + funext s j + unfold col + cases cell j <;> rfl + +include hw hi in +open Classical in +theorem packed_worker : + packed (U := raw _) F C.input (fun (s : X) j => (cellWorker s (cell j)).val) 31 := by + have hp := C.worker_net (i := i) hi ((Nat.le_pow (by decide : 0 < 5)).trans hw.pairs) + have h := packed.const (U := raw _) F (C.input (i := i)) + (fun j => Sum.elim (fun _ => 0) (fun p => p.2.val) (cell j)) (m := 0) (w + := w) (by rw [pow_zero, mul_one]; exact hi) + convert (left C hw hi cell hp h).mono (n := 31) (by decide) using 1 + funext s j + cases cell j <;> rfl + +include hw hi hb in +open Classical in +private theorem packed_table {T : Type} [Fintype T] [Nonempty T] + (hsize : Fintype.card T * (3 * r) ≤ 2 ^ w) + (f : Option (Machine.Ports N l l) → T) (g : T → Fin (3 * r) → ℕ) : + packed (U := raw _) F C.input + (fun (s : X) j => g (f (cellPort s (cell j))) (cellWorker s (cell j))) 96 := by + let _ : Nonempty (Fin (3 * r)) := ⟨⟨0, by have := hw.pos; omega⟩⟩ + let e := Fintype.equivFin T + let v : Fin (3 * r) ≃ Fin (Fintype.card (Fin (3 * r))) := finCongr (Fintype.card_fin _).symm + have hv := packed_worker (i := i) C hw hi cell + have hp := packed_port (i := i) C hw hi hb cell (fun k => (e (f k)).val) + have ht := packed.named_table g (by rwa [Fintype.card_fin]) + (fun (s : X) j => f (cellPort s (cell j))) (fun s j => cellWorker s (cell j)) e v hp hv + exact ht.mono (by decide) + +include hw hi hb in +open Classical in +theorem packed_query [NeZero r] (idx : Name n r ↪ Coloring.B w) : + packed (U := raw _) F C.input (fun (s : X) j => (idx (query s (cell j))).val) 96 := by + have hcap : Fintype.card (Label n r) * (3 * r) ≤ 2 ^ w := by + have := Fintype.card_le_of_injective idx idx.injective + rw [name_card, Fintype.card_fin] at this + rw [show Fintype.card (Label n r) = r ^ n by simp [Label], mul_comm] + omega + exact packed_table C hw hi hb cell hcap (label P.colors) (fun z u => (idx (.inl (.inl (u, + z)))).val) + +include hw hi hb in +open Classical in +theorem packed_kind (f : Kind r → Fin (3 * r) → ℕ) : + packed (U := raw _) F C.input + (fun (s : X) j => f (kind (cellPort s (cell j))) (cellWorker s (cell j))) 96 := by + let _ : Nonempty (Kind r) := ⟨.empty⟩ + have hcap : Fintype.card (Kind r) * (3 * r) ≤ 2 ^ w := by + rw [card_kind] + have := C.links + have := hw.pos + nlinarith + exact packed_table C hw hi hb cell hcap kind f + +include hw hi hb in +open Classical in +theorem packed_mark : + packed (U := raw _) F C.input (fun (s : X) j => mark s (cell j)) 122 := by + have hm := packed_kind (i := i) C hw hi hb cell mode + have h := packed.const (U := raw _) F (C.input (i := i)) (fun _ => 3) (m := 0) (w + := w) (by rw [pow_zero, mul_one]; exact hi) + exact (left C hw hi cell h hm).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.PinIndex +end + +/- # Reading class controls from the worker identifier and report -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l n d r h B w : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +open Classical in +/-- Computes the chosen by the application `PacketKernel.candidate (workerAt s) c`. -/ +def chosen (s : X) (c : PacketKernel.Spot r) := PacketKernel.candidate (workerAt s) c + +omit [Fintype F] in +open Classical in +theorem spot_fit (hw : Limits A N r (B * P.count) w) : + 3 * r * Fintype.card (PacketKernel.Spot r) ≤ 2 ^ w := by + have : 0 < 3 * r := Nat.mul_pos (by decide) hw.pos + rw [PacketKernel.card_spot] + calc + _ ≤ (3 * r) ^ 3 := by ring_nf; omega + _ ≤ _ := (Nat.pow_le_pow_right this (by decide)).trans hw.pairs + +variable [LinearOrder (Name n r)] (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) + (idx : Name n r ↪ Coloring.B w) (a : Coloring.B w → PacketKernel.Spot r) + +omit [LinearOrder (Name n r)] in +include hi hw in +open Classical in +theorem packed_chosen : + packed (U := raw _) F (C.input (i := i)) + (fun s j => (idx (.inr (.inr (chosen s (a j))))).val) 37 := + C.workerTable hw hi a (spot_fit hw) (fun u c => + (idx (.inr (.inr (PacketKernel.candidate ((Worker.index r).symm u) c)))).val) + +include hw hi idx in +open Classical in +theorem packed_class_pair (k : Worker r → Worker r → Worker r → ℕ) : + packed (U := raw _) F (C.input (i := i)) (fun s j => + k (workerAt s) (A.src hn N s.report.1 (.inr (chosen s (a j)))) + (A.dst hn N s.report.1 (.inr (chosen s (a j))))) 129 := by + let f (s : X) (j : Coloring.B w) : Name n r := .inr (.inr (chosen s (a j))) + have H := C.packed_pair hw hi f idx (C.packed_chosen hw hi idx a) + (fun u x y => k ((Worker.index r).symm u) ((Worker.index r).symm x) ((Worker.index r).symm y)) + simpa only [f, request, descriptor, Equiv.symm_apply_apply] using H + +include hw hi idx in +open Classical in +theorem packed_enabled : + packed (U := raw _) F (C.input (i := i)) (fun s j => + (decide (PacketKernel.active A hn N s.report.1 (workerAt s) (a j))).toNat) 150 := by + have h₁ := C.packed_class_pair (i := i) hw hi idx a (fun u x y => if x = u ∨ y = u then 1 else 0) + have h₂ := C.workerTable (i := i) hw hi a (spot_fit hw) (fun u j => + let v := (Worker.index r).symm u + if PacketKernel.locate v (PacketKernel.candidate v j) = j then 1 else 0) + have hz := packed.const (U := raw _) F (C.input (i := i)) (fun _ : Coloring.B w => 0) + (m := 0) (by rw [pow_zero, mul_one]; exact hi) + have hpow : 1 < 2 ^ w := Nat.one_lt_pow (by have := hw.large; omega) (by decide) + have hk := hz.select h₁ h₂ hz (fun _ _ => by positivity) (fun _ _ => by split <;> omega) + convert hk.mono (n := 150) (by decide) using 1 + funext s j + simp only [PacketKernel.active, chosen, workerAt] + split_ifs <;> simp_all [Bool.toNat] + +open Classical in +private def fromEnds (u x y : Worker r) : PacketKernel.Mode := + match x with + | .home _ => if x = y then .both else .side (decide (y = u)) + | _ => .joint + +omit [Fintype F] [LinearOrder (Name n r)] in +open Classical in +private theorem mode_ends (s : X) (c : Class r) : + PacketKernel.modeAt A hn N s.report.1 (workerAt s) c = + fromEnds (workerAt s) (A.src hn N s.report.1 (.inr c)) (A.dst hn N s.report.1 (.inr c)) := by + let u := workerAt s + let x := A.src hn N s.report.1 (.inr c) + let y := A.dst hn N s.report.1 (.inr c) + change (if A.shared N s.report.1 c then if x = y then PacketKernel.Mode.both + else .side (decide (y = u)) else .joint) = fromEnds u x y + unfold x + cases hh : A.shared N s.report.1 c <;> simp [fromEnds, Expansion.src, hh] + +include hw hi idx in +open Classical in +theorem packed_mode (b : Coloring.B w → Fin 2) : + packed (U := raw _) F (C.input (i := i)) (fun s j => + ((PacketKernel.modeAt A hn N s.report.1 (workerAt s) (chosen s (a j))).bits (b j)).toNat) 150 + := by + have H (v : Fin 2) := C.packed_class_pair (i := i) hw hi idx a + (fun u x y => ((fromEnds u x y).bits v).toNat) + have h := packed.const (U := raw _) F (C.input (i := i)) (fun j => (b j).val) + (m := 0) (by rw [pow_zero, mul_one]; exact hi) + have ho := packed.const (U := raw _) F (C.input (i := i)) (fun _ : Coloring.B w => 1) + (m := 0) (by rw [pow_zero, mul_one]; exact hi) + have hpow : 1 < 2 ^ w := Nat.one_lt_pow (by have := hw.large; omega) (by decide) + have hk := h.select ho (H 0) (H 1) (fun _ j => (b j).isLt.trans_le hpow) (fun _ _ => hpow) + convert hk.mono (n := 150) (by decide) using 1 + funext s j + rw [mode_ends] + generalize b j = k + fin_cases k <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- # Batched access to the counts and total widths of classes -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l n d r h B w : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +open Classical in +private theorem class_card : Fintype.card (Class r) = r ^ 3 := by simp [Class]; ring + +variable (hw : Limits A N r (B * P.count) w) (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) + (a : Coloring.B w → PacketKernel.Spot r) + +include hw hi in +open Classical in +theorem packed_counts_frame (hc : 9 * Fintype.card (A.CountBit r (B * P.count)) ≤ 2 ^ w) + (b : Coloring.B w → A.I × Fin (countWidth P B)) : + packed (U := raw _) F (C.input (i := i)) (fun s j => + (A.countBits s.report.val ((chosen s (a j), (b j).1), (b j).2)).toNat) 47 := by + let D := A.CountBit r (B * P.count) + let J := PacketKernel.Spot r × A.I × Fin (countWidth P B) + let f (u : Fin (3 * r)) (z : J) : D := + ((PacketKernel.candidate ((Worker.index r).symm u) z.1, z.2.1), z.2.2) + have cap : 3 * r * Fintype.card J ≤ 2 ^ w := by + calc + _ = 9 * Fintype.card D := by + simp only [J, D, Expansion.CountBit, PacketKernel.Spot, Class, Fintype.card_prod, + Fintype.card_fin, countWidth] + ring + _ ≤ _ := hc + have : Nonempty D := ⟨f ⟨0, by have := hw.pos; omega⟩ (a 0, b 0)⟩ + obtain ⟨e⟩ : Nonempty (D ↪ Coloring.B w) := + Function.Embedding.nonempty_of_card_le (by rw [Fintype.card_fin]; exact hw.counts) + have hk := C.workerTable (i := i) hw hi (fun j => (a j, b j)) cap (fun u j => (e (f u j)).val) + have ht (j : Coloring.B w → D) : packed (U := raw _) F (C.input (i := i)) + (fun s k => (A.countBits s.report.val (j k)).toNat) 2 := by + have h := packed.named F (C.input (i := i)) (C.countPort ∘ j) (c := 0) (by simpa using hi) + convert h using 1 + funext s k + exact congrArg Bool.toNat (congrFun (C.counts_eq s) (j k)).symm + have H := packed.fetch (fun (s : X) j => f s.site (a j, b j)) e + (fun s k => (A.countBits s.report.val k).toNat) hk ht + exact H.mono (by decide) + +include hw hi in +open Classical in +private theorem packed_all_widths (j : Coloring.B w → Class r) : + packed (U := raw _) F (C.input (i := i)) (fun s k => A.classWidth s.report.val (j k)) 7 := by + let v := countWidth P B + let f := A.chargeBits i + have hb := Install.BNet.copies (linear_register F f w v) (Class r) + let addr : Class r × (A.I × Fin v) → Machine.Ports N l l := + fun p => C.countPort ((p.1, p.2.1), p.2.2) + have h := hb.pull addr + apply packed.reshape _ j h + · have h₁ : Fintype.card (Class r) ≤ 2 ^ w := by + rw [class_card] + exact (Nat.pow_le_pow_right hw.pos (by omega)).trans hw.power + have h₂ : Fintype.card (Class r) * (Fintype.card A.I * v) ≤ 2 ^ w := by + simpa only [v, countWidth, Expansion.CountBit, Fintype.card_prod, Fintype.card_fin, + mul_assoc] using hw.counts + rw [Fintype.card_prod (Class r) (A.I × Fin v), Fintype.card_prod A.I (Fin v), Fintype.card_fin] + have h₃ : Fintype.card (Class r) * (20000 * (1 + Fintype.card A.I * v) * (1 + w)) ≤ + 40000 * 2 ^ w * (1 + w) := by + have hh := Nat.mul_le_mul_right (20000 * (1 + w)) (Nat.add_le_add h₁ h₂) + nlinarith only [hh] + have h₄ : 50000 * (1 + w) ≤ (100 + w) ^ 7 := by ring_nf; omega + nlinarith only [h₂, h₃, hi, Nat.mul_le_mul_right w h₁, Nat.mul_le_mul_left (2 ^ w) h₄] + · intro s k t + change digits w (linear f (fun y => C.input s (addr (j k, y)))) t = _ + have hh (z : A.I) : Processor.number (fun y => C.input s (addr (j k, (z, y)))) = + (s.report.val.2 (j k, z)).val := by + change Processor.number (fun y => (C.input s ∘ C.countPort) ((j k, z), y)) = _ + rw [C.counts_eq s] + exact A.cnt_countBits _ _ + simp only [linear, hh, Expansion.classWidth, f, Expansion.chargeBits, s.cut] + +include hw hi in +open Classical in +theorem packed_frame_width : + packed (U := raw _) F (C.input (i := i)) + (fun s j => A.classWidth s.report.val (chosen s (a j))) 47 := by + have : Nonempty (Fin r) := ⟨⟨0, hw.pos⟩⟩ + obtain ⟨idx⟩ : Nonempty (Class r ↪ Coloring.B w) := Function.Embedding.nonempty_of_card_le + (by + rw [class_card, Fintype.card_fin] + exact (Nat.pow_le_pow_right hw.pos (by omega)).trans hw.power) + have hk := C.workerTable (i := i) hw hi a (spot_fit hw) + (fun u c => (idx (PacketKernel.candidate ((Worker.index r).symm u) c)).val) + have H := packed.fetch (fun (s : X) j => chosen s (a j)) idx + (fun s c => A.classWidth s.report.1 c) hk (C.packed_all_widths hw hi) + exact H.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end + +/- # Static lookups on worker numbers and variable keys -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l d B n r h w c : ℕ} + {A : Expansion F n h} {hn : 2 ≤ n} {P : Format N l d n r h} {M : Bank (Fin n)} + (C : Controller P A hn M B) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +open Classical in +theorem packed_workerLookup (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) + {J : Type} [Fintype J] [Nonempty J] (hc : 3 * r * Fintype.card J ≤ 2 ^ w) + (col : X → Coloring.B w → J) (idx : J ↪ Coloring.B w) + (hk : packed (U := raw _) F C.input (fun s j => (idx (col s j)).val) c) + (f : Worker r → J → ℕ) : + packed (U := raw _) F C.input (fun s j => f (workerAt s) (col s j)) (c + 44) := by + have : Nonempty (Fin (3 * r)) := ⟨⟨0, Nat.mul_pos (by decide) hw.pos⟩⟩ + let a : Fin (3 * r) ≃ Fin (Fintype.card (Fin (3 * r))) := finCongr (Fintype.card_fin _).symm + let b := Fintype.equivFin J + have hu := C.worker_net (i := i) hi ((Nat.le_pow (by decide : 0 < 5)).trans hw.pairs) + have hslot := packed.remap col idx hk (fun j => (b j).val) + have hv := packed.named_table (U := raw _) (inp := C.input (i := i)) + (c := 5) (d := c + 12) (fun u j => f ((Worker.index r).symm u) j) + (by rwa [Fintype.card_fin]) (fun s (_ : Coloring.B w) => s.site) col a b hu hslot + exact hv.mono (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Resistance.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Resistance.lean new file mode 100644 index 0000000000..f62f16cb45 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Resistance.lean @@ -0,0 +1,84 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Handle +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.WindowSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Broadcast + +/-! +# Diagonal resistance over a finite field + +One processor works for every replacement of the prescribed size. +Its literal codes can then be chosen independently at the different +sites. The controller and its size bound require no complexity assumptions. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal Filter + +variable {F : Type} [Field F] [Fintype F] + +private theorem fit_window {N w W Q s : ℕ} (hs : W ≤ 2 * w) (hb : 2 ^ W ≤ N * w ^ (Q + 10)) + (hw : 200 ≤ w) : 2 ^ W * (100 + W) ^ (Q + s) ≤ N * w ^ ((Q + 10) + 2 * (Q + s)) := by + rw [pow_add w, pow_mul, ← mul_assoc] + exact Nat.mul_le_mul hb (Nat.pow_le_pow_left (by nlinarith : 100 + W ≤ w ^ 2) _) + +theorem control (F : Type) [Field F] [Fintype F] : ControlBound F := by + classical + intro n h K Q hn hh hK A + let t := (Q + 10) + 2 * (Q + 660) + refine ⟨max t 5 + 1, ?_⟩ + filter_upwards [window n h K Q hn hh hK A, dispatch_scale A hn K t, + eventually_ge_atTop 200] with w getW dispatch hw + intro N r d l B fa hf _ P M hm hlabel hroom hex + obtain ⟨W, H⟩ := getW fa M hm hex + have hr : 0 < r := lt_of_lt_of_le (by decide) H.three + let _ : NeZero r := ⟨hr.ne'⟩ + let _ : NeZero (3 * r) := ⟨by omega⟩ + have hn4 : 0 < N / 4 := by + have := hex.some.links + have := Nat.le_pow (a := 3 * r) (by decide : 0 < 2) + omega + let _ : NeZero (N / 4) := ⟨hn4.ne'⟩ + let e := Fintype.equivFin (Name n r) + let _ : LinearOrder (Name n r) := LinearOrder.lift' e e.injective + have he : P.which = (Format.prescribed d h P.count P.colors).which := rfl + have hg : ∀ z, Diagonal.multiplicity P.colors z * r ^ n ≤ 4 * N := hf + have hc (i) : Nonempty (Cells.Domain P ↪ Fin (2 ^ M.width i)) := by + apply Function.Embedding.nonempty_of_card_le + rw [Fintype.card_fin] + apply (Nat.mul_le_mul_right_iff hr).mp + exact (Cells.domain_size P hlabel (by omega) H.positions).trans (hroom i) + let a : Cells.Address P M := fun i => (hc i).some + let C := Cells.install hn he hg a hex.some + have hwW : w ≤ W := by + by_contra! hlt + have hh := Nat.pow_lt_pow_right (by decide : 1 < 2) hlt + exact hh.not_ge H.limits.bits + have hM : M.budget F ≤ 2 ^ W * (100 + W) ^ Q := + hm.trans (Nat.mul_le_mul H.limits.bits (Nat.pow_le_pow_left (by omega) _)) + refine ⟨C.numberInOrder, dispatch fa M C.numberInOrder ?_⟩ + intro i + obtain ⟨f, hf, he⟩ := C.handles H he hg a rfl hM i + exact ⟨f, hf.mono (fit_window H.small H.cost hw), he⟩ + +/-- A cheaply realizable family resists all sufficiently small +simultaneous implementations, even with quasilinear macro gates. -/ +theorem resists (F : Type) [Field F] [Finite F] (K q : ℕ) : + Diagonal.Resists F (Cheap F K q) := by + let _ := Fintype.ofFinite F + exact resists_of_programmable (programmable_of_control (control F) K q) + +theorem hard_of_descent {F : Type} [Field F] [Finite F] {K q : ℕ} + (h : Diagonal.Descent F (Cheap F K q)) : Tagged.Hard F := + hard_of_resists (resists F K q) h + +end MatrixMultiplicationAllFields.MatrixExponent.Processor diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Skip.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Skip.lean new file mode 100644 index 0000000000..1332d65c1b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Skip.lean @@ -0,0 +1,938 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.DispatchSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Vector.Cases + +/-! # Numbering a pair's virtual bits by whole channels -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor + +open Diagonal +variable {R : ℕ} {E J : Type} {src dst : E → Fin R} + +/-- The bits with any one key have identical endpoints. -/ +structure Channels (src dst : E → Fin R) (J : Type) where + /-- The width parameter carried by `Channels`, with type `J → ℕ`. -/ + width : J → ℕ + /-- The left-side data carried by `Channels`, with type `J → Fin R`. -/ + left : J → Fin R + /-- The right-side data carried by `Channels`, with type `J → Fin R`. -/ + right : J → Fin R + /-- The label at each coordinate of type `E ≃ (Σ j, Fin (width j))`. -/ + label : E ≃ (Σ j, Fin (width j)) + src_eq : ∀ e, src e = left (label e).1 + dst_eq : ∀ e, dst e = right (label e).1 + +namespace Channels + +variable [Fintype E] [Fintype J] [LinearOrder J] (c : Channels src dst J) + +/-- Returns `c.width j` when `c.left j = u ∧ c.right j = v ∨ c.left j = v ∧ c.right j = u` +holds, and `0` otherwise. -/ +def widthAt (u v : Fin R) (j : J) : ℕ := + if c.left j = u ∧ c.right j = v ∨ c.left j = v ∧ c.right j = u then c.width j else 0 + +/-- Indexes the block by the coordinates of `Lex (Σ j, Fin (c.widthAt u v j))`. -/ +abbrev Block (u v : Fin R) := Lex (Σ j, Fin (c.widthAt u v j)) + +/-- The send of type `c.Block u v` for the given inputs. -/ +def send {u v : Fin R} (i : Links.Between src dst u v) : c.Block u v := + ⟨(c.label i).1, ⟨(c.label i).2.val, by + have h := i.property + rw [c.src_eq, c.dst_eq] at h + rw [widthAt, ite_eq_left h] + exact (c.label i).2.isLt⟩⟩ + +omit [Fintype J] [LinearOrder J] in +theorem sigma_eq {w : J → ℕ} {x y : (Σ j, Fin (w j))} + (hf : x.1 = y.1) (hs : x.2.val = y.2.val) : x = y := by + rcases x with ⟨i, v⟩ + rcases y with ⟨j, u⟩ + change i = j at hf + subst j + rw [show v = u from Fin.ext hs] + +/-- Bundles the indexing function as an equivalence. -/ +def blockEquiv (u v : Fin R) : Links.Between src dst u v ≃ c.Block u v := + Equiv.ofBijective (c.send (u := u) (v := v)) ⟨by + intro x y h + apply Subtype.ext + apply c.label.injective + have ha := congrArg Sigma.fst h + have hb := congrArg (fun z => z.2.val) h + exact sigma_eq ha hb, by + intro t + let j := t.1 + have hl : t.2.val < c.widthAt u v j := t.2.isLt + unfold widthAt at hl + split at hl + · rename_i h + let e := c.label.symm ⟨j, ⟨t.2.val, hl⟩⟩ + have he : c.label e = ⟨j, ⟨t.2.val, hl⟩⟩ := c.label.apply_symm_apply _ + have hp : src e = u ∧ dst e = v ∨ src e = v ∧ dst e = u := by + rw [c.src_eq, c.dst_eq, he] + exact h + have ha := congrArg Sigma.fst he + have hb := congrArg (fun z => z.2.val) he + exact ⟨⟨e, hp⟩, sigma_eq ha hb⟩ + · omega⟩ + +theorem count (u v : Fin R) : Links.count src dst u v = ∑ j, c.widthAt u v j := by + rw [Links.count, Fintype.card_congr (c.blockEquiv u v)] + simp [Block] + +/-- The serial of type `Links.Numbering src dst` for the given inputs. -/ +def serial : Links.Numbering src dst := + fun u v => (Fintype.orderIsoFinOfCardEq (c.Block u v) + (Fintype.card_congr (c.blockEquiv u v).symm)).toEquiv.trans (c.blockEquiv u v).symm + +theorem serial_value {u v : Fin R} (x : Links.Between src dst u v) : + ((c.serial u v).symm x).val = + start (c.widthAt u v) (c.label x).1 + (c.label x).2.val := + serial_rank _ _ (c.blockEquiv u v x) + +end Channels +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- # Arithmetic form of the physical address at either end of a link -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +variable {R N : ℕ} + +/-- The sum of `(q u j / R + 1)` indexed by `j ∈ Finset.Iio v`. -/ +def skip (q : Fin R → Fin R → ℕ) (u v : Fin R) := ∑ j ∈ Finset.Iio v, (q u j / R + 1) + +/-- The parity bit identifies the endpoint and the position modulo +the processor count identifies the relay. -/ +def wireAddress (R N u k base : ℕ) := + 2 * base + 2 * (k / R) + (if u < k % R then 0 else 1) + (N / (4 * R)) * ((u + k % R) % R) + +variable {q : Fin R → Fin R → ℕ} (hs : ∀ u v, q u v = q v u) + (hq : ∀ u, ∑ v, q u v ≤ N / 64) (hn : 64 * R ^ 2 ≤ N) + +theorem address_leg (l : Leg q) : + (address (slot hs hq hn l)).val = + wireAddress R N l.2.val.val l.1.2.val (skip q l.2.val (other l)) := by + have he : (link l).val.1 + (link l).val.2 = l.2.val + via l.1 := by + unfold link + split + · rfl + · exact add_comm _ _ + change position l + N / (4 * R) * ((link l).val.1 + (link l).val.2).val = _ + rw [he] + unfold position wireAddress + rw [Nat.mul_add] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +open Coloring Diagonal.Links + +variable {F S : Type} [Field F] {w : ℕ} {U : Coloring.Format} + {inp : S → U.obj} {u k b : Array S w} {R N c : ℕ} + +theorem wire_address (hR : 0 < R) (hR' : 2 * R ≤ 2 ^ w) + (hu : packed F inp u c) (hk : packed F inp k c) (hb : packed F inp b c) + (hu' : ∀ s i, u s i < R) (hk' : fits k) (hb' : fits b) : + packed F inp (fun s i => wireAddress R N (u s i) (k s i) (b s i)) (c + 64) := by + let via (s : S) (i : B w) := k s i % R + have hv' : fits via := by intro s i; have := Nat.mod_lt (k s i) hR; unfold via; omega + have hu'' : fits u := by intro s i; have := hu' s i; omega + have hplus : fits (fun s i => u s i + via s i) := by + intro s i + have := hu' s i + have := Nat.mod_lt (k s i) hR + change u s i + k s i % R < _ + omega + have hv := hk.unary hk' (fun t => t % R) + have hh := ((hu.add hv).unary hplus (fun x => (N / (4 * R)) * (x % R))) + have ix := (hb.unary hb' (2*·)).add (hk.unary hk' (fun x => 2 * (x / R))) + have bit := hu.select hv (const F inp (fun _ => 0) hu.width) (const F inp (fun _ => 1) hu.width) + hu'' hv' + exact ((ix.add bit).add hh).mono (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +section +/- +# Inverting the physical link schedule + +Parity recovers the sending endpoint. Prefix intervals identify its +partner. The quotient inside the interval and the relay identify the +virtual bit. Unused positions, including holes at interval boundaries, +are rejected by the final index check. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +open Finset +variable {R N : ℕ} (q : Fin R → Fin R → ℕ) + +theorem skip_step (u : Fin R) {a b : Fin R} (hab : a < b) : + skip q u a + (q u a / R + 1) ≤ skip q u b := by + have h : insert a (Iio a) ⊆ Iio b := by + intro c hc + simp only [mem_insert, mem_Iio] at hc ⊢ + omega + have hh := sum_le_sum_of_subset (f := fun c => q u c / R + 1) h + rw [sum_insert (by simp)] at hh + exact (Nat.add_comm ..).le.trans hh + +theorem candidates (a : Fin R) (i : ℕ) : + (univ.filter (fun b => skip q a b ≤ i)).Nonempty := by + let b : Fin R := ⟨0, a.pos⟩ + have hb : Iio b = ∅ := by ext t; simp [b, Fin.lt_def] + exact ⟨b, mem_filter.mpr ⟨mem_univ _, by simp [skip, hb]⟩⟩ + +/-- The indexed operation `(univ.filter (fun b => skip q a b ≤ i)).max' (candidates q a i)`. -/ +def partner (a : Fin R) (i : ℕ) : Fin R := + (univ.filter (fun b => skip q a b ≤ i)).max' (candidates q a i) + +theorem partner_spec (a : Fin R) (i : ℕ) : + skip q a (partner q a i) ≤ i ∧ ∀ b, skip q a b ≤ i → b ≤ partner q a i := + ⟨(mem_filter.mp (max'_mem _ (candidates q a i))).2, + fun b h => le_max' _ b (mem_filter.mpr ⟨mem_univ _, h⟩)⟩ + +theorem le_partner (a b : Fin R) (i : ℕ) : b ≤ partner q a i ↔ skip q a b ≤ i := by + obtain ⟨hi, h⟩ := partner_spec q a i + refine ⟨fun hb => ?_, h b⟩ + rcases hb.eq_or_lt with rfl | hb + · exact hi + · exact (Nat.le_add_right ..).trans ((skip_step q a hb).trans hi) + +private theorem partner_at (a b : Fin R) (k : ℕ) (hk : k < q a b) : + partner q a (skip q a b + k / R) = b := by + obtain ⟨hi, h⟩ := partner_spec q a (skip q a b + k / R) + apply le_antisymm _ (h b (Nat.le_add_right ..)) + by_contra! h' + have := skip_step q a h' + have := Nat.div_le_div_right (c := R) hk.le + omega + +/-- Returns `p.1.val.1` when `p.2.val % 2 = 0` holds, and `p.1.val.2` otherwise. -/ +def sender (p : Slot R N) : Fin R := + if p.2.val % 2 = 0 then p.1.val.1 else p.1.val.2 + +/-- Returns `p.1.val.2` when `p.2.val % 2 = 0` holds, and `p.1.val.1` otherwise. -/ +def relay (p : Slot R N) : Fin R := + if p.2.val % 2 = 0 then p.1.val.2 else p.1.val.1 + +/-- The quantity computed by `partner q (sender p) (p.2.val / 2)`. -/ +def mate (p : Slot R N) : Fin R := partner q (sender p) (p.2.val / 2) + +/-- The quantity computed by `R * (p.2.val / 2 - skip q (sender p) (mate q p)) + (relay p).val`. -/ +def index (p : Slot R N) : ℕ := + R * (p.2.val / 2 - skip q (sender p) (mate q p)) + (relay p).val + +/-- Requires `sender p ≠ mate q p ∧ index q p < q (sender p) (mate q p)`. -/ +def active (p : Slot R N) : Prop := + sender p ≠ mate q p ∧ index q p < q (sender p) (mate q p) + +variable {q} (hs : ∀ u v, q u v = q v u) (hq : ∀ u, ∑ v, q u v ≤ N / 64) + (hn : 64 * R ^ 2 ≤ N) + +include hs in +private theorem key (l : Leg q) : l.2.val ≠ other l ∧ l.1.2.val < q l.2.val (other l) := by + have hp := l.1.1.property + unfold other + split + · rename_i he + rw [he] + exact ⟨hp.ne, l.1.2.isLt⟩ + · rename_i he + rw [l.2.property.1.resolve_left he] + exact ⟨hp.ne', l.1.2.isLt.trans_eq (hs _ _)⟩ + +theorem read_slot (l : Leg q) : + let p := slot hs hq hn l + sender p = l.2.val ∧ relay p = via l.1 ∧ mate q p = other l ∧ index q p = l.1.2.val := by + intro p + have hpair : sender p = l.2.val ∧ relay p = via l.1 := by + unfold sender relay p slot link position + split <;> simp_all + have hp : p.2.val / 2 = skip q l.2.val (other l) + l.1.2.val / R := by + change (2 * (skip q l.2.val (other l) + l.1.2.val / R) + _) / 2 = _ + split <;> omega + have hm : mate q p = other l := by + rw [mate, hpair.1, hp, partner_at q _ _ _ (key hs l).2] + refine ⟨hpair.1, hpair.2, hm, ?_⟩ + rw [index, hpair.1, hpair.2, hm, hp, Nat.add_sub_cancel_left] + exact (Nat.add_comm ..).trans (Nat.mod_add_div ..) + +private theorem sender_ne (p : Slot R N) : sender p ≠ relay p := by + unfold sender relay + split <;> have := p.1.property <;> omega + +theorem mod_index (p : Slot R N) : index q p % R = (relay p).val := by + simp [index, Nat.add_mod, Nat.mod_eq_of_lt (relay p).isLt] + +private theorem slot_ext {p t : Slot R N} (ha : sender p = sender t) (hb : relay p = relay t) + (hm : mate q p = mate q t) (hi : index q p = index q t) : p = t := by + have hv (z : Slot R N) : skip q (sender z) (mate q z) ≤ z.2.val / 2 := + (partner_spec q _ _).1 + have hd := hv p + have he := hv t + rw [index, index, ha, hb, hm] at hi + rw [ha, hm] at hd + have hhalf := Nat.eq_of_mul_eq_mul_left (sender p).pos (Nat.add_right_cancel hi) + have hp := p.1.property + have ht := t.1.property + unfold sender at ha + unfold relay at hb + split_ifs at ha hb <;> exact Prod.ext (Subtype.ext (Prod.ext (by omega) (by omega))) (by omega) + +include hs in +private theorem make_leg (a b : Fin R) (k : ℕ) + (hne : a ≠ b) (hk : k < q a b) (hv : a.val ≠ k % R) : + ∃ l : Leg q, l.2.val = a ∧ other l = b ∧ l.1.2.val = k := by + have hh (v : Virtual q) (he : v.2.val = k) : a ≠ via v := by + intro h + apply hv + exact (congrArg Fin.val h).trans (congrArg (· % R) he) + rcases lt_or_gt_of_ne hne with h | h + · let v : Virtual q := ⟨⟨(a, b), h⟩, ⟨k, hk⟩⟩ + let l : Leg q := ⟨v, a, .inl rfl, hh v rfl⟩ + exact ⟨l, rfl, by simp [l, v, other], rfl⟩ + · let v : Virtual q := ⟨⟨(b, a), h⟩, ⟨k, hk.trans_eq (hs a b)⟩⟩ + let l : Leg q := ⟨v, a, .inr rfl, hh v rfl⟩ + exact ⟨l, rfl, by simp [l, v, other, hne], rfl⟩ + +/-- An arithmetic decoder recognizes exactly the occupied slots. -/ +theorem active_iff (p : Slot R N) : active q p ↔ p ∈ Set.range (slot hs hq hn) := by + constructor + · intro h + have hv : (sender p).val ≠ index q p % R := by + rw [mod_index] + exact fun h => sender_ne p (Fin.ext h) + obtain ⟨l, ha, hb, hk⟩ := make_leg hs _ _ _ h.1 h.2 hv + obtain ⟨h₁, h₂, h₃, h₄⟩ := read_slot hs hq hn l + refine ⟨l, slot_ext (h₁.trans ha) ?_ (h₃.trans hb) (h₄.trans hk)⟩ + rw [h₂] + exact Fin.ext ((congrArg (· % R) hk).trans (mod_index p)) + · rintro ⟨l, rfl⟩ + obtain ⟨h₁, _, h₃, h₄⟩ := read_slot hs hq hn l + rw [active, h₁, h₃, h₄] + exact key hs l + +private theorem legs {l k : Leg q} (hl : l.1 = k.1) : + l = k ∨ other l = k.2.val ∧ other k = l.2.val := by + rcases l with ⟨v, a, ha, ha'⟩ + rcases k with ⟨w, b, hb, hb'⟩ + change v = w at hl + subst w + by_cases he : a = b + · left; subst b; rfl + · right + unfold other + dsimp only + grind + +private theorem opposite_leg (l : Leg q) (h : other l ≠ via l.1) : + ∃ k : Leg q, k.1 = l.1 ∧ k.2.val = other l ∧ other k = l.2.val := by + have he : other l = l.1.1.val.1 ∨ other l = l.1.1.val.2 := by + unfold other + split <;> simp + let k : Leg q := ⟨l.1, other l, he, h⟩ + rcases legs (l := l) (k := k) rfl with hh | hh + · have hh' : l.2.val = other l := congrArg (fun z : Leg q => z.2.val) hh + have := l.2.property.1 + have := l.1.1.property + unfold other at hh' + grind + · exact ⟨k, rfl, rfl, hh.2⟩ + +/-- At a relay the peer leg has the same bit index and reversed endpoints. -/ +def peer (q : Fin R → Fin R → ℕ) (p : Slot R N) := + wireAddress R N (mate q p).val (index q p) (skip q (mate q p) (sender p)) + +private theorem peer_leg {l k : Leg q} (hv : l.1 = k.1) + (ha : other l = k.2.val) (hb : other k = l.2.val) : + peer q (slot hs hq hn l) = (address (slot hs hq hn k)).val := by + obtain ⟨h₁, _, h₃, h₄⟩ := read_slot hs hq hn l + have hi := congrArg (fun b : Virtual q => b.2.val) hv + rw [peer, h₁, h₃, h₄, ha, ← hb, hi, address_leg] + +/-- The tape may be extended arbitrarily outside its valid addresses. +Only an active relay with a second leg reads the peer address. -/ +def relayCheck (q : Fin R → Fin R → ℕ) (u : Fin R) (t : ℕ → Bool) (p : Slot R N) : Prop := + (¬active q p → u = p.1.val.1 → t (address p).val = false) ∧ + (active q p → relay p = u → mate q p ≠ u → t (address p).val = t (peer q p)) + +theorem valid_iff_check (u : Fin R) (t : ℕ → Bool) : + valid hs hq hn u (fun i => t i.val) ↔ ∀ p : Slot R N, sees u p.1 → relayCheck q u t p := by + constructor + · intro h p _ + constructor + · intro he hu + exact h.2 p (fun hp => he ((active_iff hs hq hn p).mpr hp)) hu + · intro ha hr hm + obtain ⟨l, rfl⟩ := (active_iff hs hq hn p).mp ha + obtain ⟨_, hv, he, _⟩ := read_slot hs hq hn l + rw [hv] at hr + rw [he, ← hr] at hm + obtain ⟨k, hk, h₁, h₂⟩ := opposite_leg l hm + rw [peer_leg hs hq hn hk.symm h₁.symm h₂] + exact h.1 l k hk.symm hr + · intro h + constructor + · intro l k hv hu + rcases legs hv with rfl | ⟨ha, hb⟩ + · rfl + · let p := slot hs hq hn l + have hh := (h p ((incident l u).mpr (.inr hu.symm))).2 + have he := read_slot hs hq hn l + have hm : mate q p ≠ u := by rw [he.2.2.1, ha, ← hu, hv]; exact k.2.property.2 + have ht := hh ((active_iff hs hq hn p).mpr ⟨l, rfl⟩) (he.2.1.trans hu) hm + rwa [peer_leg hs hq hn hv ha hb] at ht + · intro p hp hu + exact (h p (.inl hu)).1 (fun h => hp ((active_iff hs hq hn p).mp h)) hu + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links +end + +section +/- # Batched binary search on prefix intervals -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed + +open Coloring Diagonal.Links +variable {F S : Type} [Field F] {w R : ℕ} {U : Coloring.Format} {inp : S → U.obj} + +private def state (inp : S → U.obj) (x : Array S w) (s : S) : (U.pair (Perm w)).obj := + (inp s, fun i => Fin.ofNat (2 ^ w) (x s i)) + +/-- Each step gets the unchanged input and the current vector. Track +actual gate counts to avoid raising the cost exponent at every step. -/ +private theorem evolve (z : ℕ → Array S w) {c : ℕ} (init : packed F inp (z 0) c) + (next : ∀ k < w, packed F (state inp (z k)) (z (k + 1)) c) : + packed F inp (z w) (c + 2) := by + let T := 2 ^ w * (100 + w) ^ c + have hi := init.width + have run (k : ℕ) (hk : k ≤ w) : ∃ g m, Circuit F U (Perm w) g m ∧ + U.width + (Perm w).width + m ≤ (1 + 7 * k) * T ∧ + ∀ s i, g (inp s) i = Fin.ofNat (2 ^ w) (z k s i) := by + induction k with + | zero => + obtain ⟨g, ⟨m, hg, hm⟩, he⟩ := init + exact ⟨g, m, hg, by simpa [T] using hm, he⟩ + | succ k ih => + obtain ⟨g, m, hg, hm, he⟩ := ih (by omega) + obtain ⟨f, ⟨n, hf, hn⟩, he'⟩ := next k (by omega) + refine ⟨_, _, ((Circuit.id F U).pair hg).comp hf, ?_, ?_⟩ + · rw [show (1 + 7 * (k + 1)) * T = (1 + 7 * k) * T + 7 * T by ring] + omega + · intro s i + change f (inp s, g (inp s)) i = _ + rw [funext (he s)] + exact he' s i + obtain ⟨g, m, hg, hm, he⟩ := run w le_rfl + refine ⟨g, ⟨m, hg, hm.trans ?_⟩, he⟩ + rw [mul_comm (1 + 7 * w), pow_add, ← mul_assoc (2 ^ w)] + apply Nat.mul_le_mul_left + nlinarith + +private theorem state_width {c : ℕ} (hi : U.width ≤ 2 ^ w * (100 + w) ^ c) : + (U.pair (Perm w)).width ≤ 2 ^ w * (100 + w) ^ (c + 2) := by + rw [Coloring.Format.width_pair, Coloring.Format.width_vec, Coloring.Format.width_addr] + have hp : 1 ≤ (100 + w) ^ c := Nat.one_le_pow _ _ (by omega) + calc + _ ≤ 2 ^ w * ((100 + w) ^ c + w) := by rw [mul_add]; omega + _ ≤ _ := by + rw [pow_add] + apply Nat.mul_le_mul_left + have he := Nat.mul_le_mul_right w hp + have hh := Nat.mul_le_mul_left ((100 + w) ^ c) (show 1 + w ≤ (100 + w) ^ 2 by nlinarith) + rw [mul_add] at hh + omega + +private theorem old {x y : Array S w} {c : ℕ} (hf : packed F inp x c) : + packed F (state inp y) x (c + 5) := by + have hp := (Cheap.id F (state_width hf.width)).fst + obtain ⟨g, hg, he⟩ := hf + exact ⟨_, (hp.comp hg).mono (by omega), he⟩ + +private theorem current (x : Array S w) {c : ℕ} (hi : U.width ≤ 2 ^ w * (100 + w) ^ c) : + packed F (state inp x) x (c + 5) := + ⟨_, (Cheap.id F (state_width hi)).snd.mono (by omega), fun _ _ => rfl⟩ + +variable [NeZero R] {a b : S → B w → Fin R} {q : S → Fin R → Fin R → ℕ} {c : ℕ} + +theorem entry (hw : R ^ 2 ≤ 2 ^ w) (hq : packed F inp (matrix w q) c) + (ha : packed F inp (fun s i => (a s i).val) c) + (hb : packed F inp (fun s i => (b s i).val) c) : + packed F inp (fun s i => q s (a s i) (b s i)) (c + 30) := by + have hf : fits (fun s i => (a s i).val) := + fun s i => (a s i).isLt.trans_le ((Nat.le_pow (by decide : 0 < 2)).trans hw) + have h := (hq.lookup ((ha.unary hf (· * R)).add hb)).mono (n := c + 30) (by omega) + simpa only [matrix_index hw] using h + +private def approx (w p : ℕ) : ℕ → ℕ + | 0 => 0 + | k + 1 => + let y := approx w p k + 2 ^ (w - (k + 1)) + if y ≤ p then y else approx w p k + +private theorem approx_le (w p k : ℕ) : approx w p k ≤ p := by + induction k with + | zero => exact Nat.zero_le _ + | succ k ih => simp only [approx]; split <;> assumption + +private theorem approx_eq {w p : ℕ} (hp : p < 2 ^ w) : approx w p w = p := by + have up (k : ℕ) (hk : k ≤ w) : p < approx w p k + 2 ^ (w - k) := by + induction k with + | zero => simpa [approx] using hp + | succ k ih => + have h := ih (by omega) + rw [show w - k = (w - (k + 1)) + 1 by omega, pow_succ] at h + simp only [approx] + split <;> omega + have := up w le_rfl + have := approx_le w p w + simp only [Nat.sub_self, pow_zero] at * + omega + +/-- Find the last prefix offset not exceeding each query. The circuit +tests one candidate per lane per bit of the partner index. -/ +theorem search {j : Array S w} (hw : R ^ 2 ≤ 2 ^ w) + (hskip : packed F inp (matrix w (fun s => skip (q s))) c) + (ha : packed F inp (fun s i => (a s i).val) c) (hj : packed F inp j c) + (hb : ∀ s u v, skip (q s) u v < 2 ^ w) (hfit : fits j) : + packed F inp (fun s i => (partner (q s) (a s i) (j s i)).val) (c + 64) := by + let p s i := partner (q s) (a s i) (j s i) + have hR : R ≤ 2 ^ w := (Nat.le_pow (by decide : 0 < 2)).trans hw + let z (k : ℕ) (s : S) (i : B w) := approx w (p s i).val k + have hz k s i : z k s i < R := (approx_le ..).trans_lt (p s i).isLt + have init : packed F inp (z 0) (c + 62) := + (const F inp (fun _ => 0) ha.width).mono (by omega) + have next (k : ℕ) (_ : k < w) : packed F (state inp (z k)) (z (k + 1)) (c + 62) := by + let f x := if x + 2 ^ (w - (k + 1)) < R then x + 2 ^ (w - (k + 1)) else x + let b (s : S) (i : B w) : Fin R := ⟨f (z k s i), by + unfold f + split + · assumption + · exact hz k _ _⟩ + have hcur := current (inp := inp) (F := F) (z k) ha.width + have hc : packed F (state inp (z k)) (fun s i => (b s i).val) (c + 17) := + hcur.unary (fun s i => (hz k s i).trans_le hR) f + have hcost := entry hw ((old hskip).mono (by omega)) ((old ha).mono (by omega)) hc + have hnew := (old hj).select hcost hcur hc hfit (fun s i => hb s _ _) + convert hnew.mono (n := c + 62) (by omega) using 1 + funext s i + have hi := le_partner (q s) (a s i) (b s i) (j s i) + change (b s i).val ≤ (p s i).val ↔ _ at hi + have hp := (p s i).isLt + change (if z k s i + 2 ^ (w - (k + 1)) ≤ (p s i).val then z k s i + 2 ^ (w - (k + 1)) + else z k s i) = _ + have he : (b s i).val = f (z k s i) := rfl + unfold f at he + split_ifs at he ⊢ <;> omega + have he : z w = (fun s i => (p s i).val) := + funext fun s => funext fun i => approx_eq ((p s i).isLt.trans_le hR) + have h := evolve z init next + rwa [he] at h + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +section +/- # Reading a link when a worker is itself the intermediate processor -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links +variable {R N : ℕ} {q : Fin R → Fin R → ℕ} + +/-- The construction uses `wireAddress R N a k x` for its intermediate `left`. -/ +def endAddress (R N u a b k x y : ℕ) := + let left := wireAddress R N a k x + let right := wireAddress R N b k y + if u = k % R then (if u = a then right else left) else (if u = a then left else right) + +theorem endpoint_address (hs : ∀ u v, q u v = q v u) + (hq : ∀ u, ∑ v, q u v ≤ N / 64) (hn : 64 * R ^ 2 ≤ N) + (z : Virtual q) (u : Fin R) (hu : sees u z.1) : + let a := z.1.val.1 + let b := z.1.val.2 + (address (slot hs hq hn (endpointLeg z u hu))).val = + endAddress R N u.val a.val b.val z.2.val (skip q a b) (skip q b a) := by + intro a b + rw [address_leg] + have hv (u : Fin R) : u.val = z.2.val % R ↔ u = via z := ⟨fun h => Fin.ext h, fun h + => by rw [h]; rfl⟩ + unfold endAddress + simp only [hv, ← Fin.ext_iff] + have hne : z.1.val.2 ≠ z.1.val.1 := z.1.property.ne' + unfold endpointLeg + by_cases h : u = via z + · rw [dite_eq_right (not_ne_iff.mpr h), ite_eq_left h] + rcases hu with rfl | rfl + · rw [dite_eq_left rfl]; simp [other, a, b, hne] + · rw [dite_eq_right hne]; simp [other, a, b, hne] + · rw [dite_eq_left h, ite_eq_right h] + rcases hu with rfl | rfl + · simp [other, a, b] + · simp [other, a, b, hne] + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +open Coloring Diagonal.Links +variable {F S : Type} [Field F] {w : ℕ} {U : Coloring.Format} + {inp : S → U.obj} {f g u a b k x y : Array S w} {R N c d e t : ℕ} + +theorem choose_eq (hf : packed F inp f c) (hg : packed F inp g d) + (hx : packed F inp x e) (hy : packed F inp y t) (hf' : fits f) (hg' : fits g) : + packed F inp (fun s i => if f s i = g s i then x s i else y s i) + (max (max c d) (max e t) + 24) := by + have h := hf.select hg hy (hg.select hf hy hx hg' hf') hf' hg' + convert h.mono (n := max (max c d) (max e t) + 24) (by omega) using 1 + funext s i + split_ifs <;> omega + +theorem end_address (hR : 0 < R) (hR' : 2 * R ≤ 2 ^ w) + (hu : packed F inp u c) (ha : packed F inp a c) (hb : packed F inp b c) + (hk : packed F inp k c) (hx : packed F inp x c) (hy : packed F inp y c) + (hu' : fits u) (ha' : ∀ s i, a s i < R) (hb' : ∀ s i, b s i < R) + (hk' : fits k) (hx' : fits x) (hy' : fits y) : + packed F inp (fun s i => endAddress R N (u s i) (a s i) (b s i) (k s i) (x s i) (y s i)) + (c + 128) := by + have ha'' : fits a := by intro s i; have := ha' s i; omega + have hm := hk.unary hk' (· % R) + have hm' : fits (fun s i => k s i % R) := by + intro s i + exact (Nat.mod_lt _ hR).trans_le (by omega) + have hl := wire_address (N := N) hR hR' ha hk hx ha' hk' hx' + have hr := wire_address (N := N) hR hR' hb hk hy hb' hk' hy' + exact (hu.choose_eq hm (hu.choose_eq ha hr hl hu' ha'') (hu.choose_eq ha hl hr hu' ha'') + hu' hm').mono (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +section +/- # Simultaneous decoding of occupied positions on physical links -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +variable {R N : ℕ} {q : Fin R → Fin R → ℕ} + +theorem skip_lt_of_load (hq : ∀ u, ∑ v, q u v ≤ N / 64) (hn : 64 * R ^ 2 ≤ N) (u v : Fin R) : + skip q u v < N := by + calc + _ ≤ ∑ z, (q u z / R + 1) := Finset.sum_le_sum_of_subset (Finset.subset_univ _) + _ ≤ ∑ z, (q u z + 1) := Finset.sum_le_sum (fun z _ + => Nat.add_le_add_right (Nat.div_le_self ..) 1) + _ ≤ N / 64 + R := by simp [Finset.sum_add_distrib, hq] + _ < N := by have := u.pos; have := Nat.le_pow (a := R) (by decide : 0 < 2); omega + +theorem index_lt_of_size (p : Slot R N) : index q p < N := by + have h := (Nat.mul_le_mul_left R p.2.isLt).trans (show R * (N / (4 * R)) ≤ N / 4 by + rw [← Nat.div_div_eq_div_mul] + exact Nat.mul_div_le _ _) + have h' := Nat.mul_le_mul_left R + (show p.2.val / 2 - skip q (sender p) (mate q p) ≤ p.2.val by omega) + rw [Nat.mul_succ] at h + unfold index + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Diagonal.Links + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed + +open Coloring Diagonal.Links +variable {F S : Type} [Field F] {w R N c : ℕ} {U : Coloring.Format} {inp : S → U.obj} + +/-- Subtract ordered operands by modular addition. -/ +theorem sub {f g : Array S w} {m n : ℕ} + (hf : packed F inp f m) (hg : packed F inp g n) (hfit : fits g) + (hle : ∀ s i, g s i ≤ f s i) : + packed F inp (fun s i => f s i - g s i) (max m n + 20) := by + obtain ⟨a, ha, he⟩ := hf.add (hg.unary hfit (fun k => 2 ^ w - k)) + refine ⟨a, ha.mono (by omega), fun s i => ?_⟩ + rw [he] + apply Fin.ext + change (f s i + (2 ^ w - g s i)) % 2 ^ w = (f s i - g s i) % 2 ^ w + have := hle s i + have := hfit s i + rw [show f s i + (2 ^ w - g s i) = f s i - g s i + 2 ^ w by omega, Nat.add_mod_right] + +variable [NeZero R] {q : S → Fin R → Fin R → ℕ} {p : S → B w → Slot R N} + +/-- Compute the partner, index, length and peer address for each lane. +A peer address is used only when the partner leg exists. -/ +theorem decode_slot (hn : 64 * R ^ 2 ≤ N) (hw : N ≤ 2 ^ w) + (hq : ∀ s u, ∑ v, q s u v ≤ N / 64) + (hcount : packed F inp (matrix w q) c) + (hskip : packed F inp (matrix w (fun s => skip (q s))) c) + (ha : packed F inp (fun s i => (sender (p s i)).val) c) + (hb : packed F inp (fun s i => (relay (p s i)).val) c) + (hj : packed F inp (fun s i => (p s i).2.val / 2) c) : + packed F inp (fun s i => (mate (q s) (p s i)).val) (c + 200) ∧ + packed F inp (fun s i => Diagonal.Links.index (q s) (p s i)) (c + 200) ∧ + packed F inp (fun s i => q s (sender (p s i)) (mate (q s) (p s i))) (c + 200) ∧ + packed F inp (fun s i => peer (q s) (p s i)) (c + 200) := by + have hr : R ^ 2 ≤ 2 ^ w := by omega + have hr' : 2 * R ≤ 2 ^ w := by have he : R ≤ R ^ 2 := Nat.le_pow (by decide); omega + have hfit (s) (u v : Fin R) : skip (q s) u v < 2 ^ w + := (skip_lt_of_load (hq s) hn u v).trans_le hw + have hj' : fits (fun s i => (p s i).2.val / 2) := by + intro s i + have := (p s i).2.isLt + have := Nat.div_le_self N (4 * R) + dsimp + omega + let b s i := mate (q s) (p s i) + let a s i := sender (p s i) + have hm : packed F inp (fun s i => (b s i).val) (c + 64) := search hr hskip ha hj hfit hj' + have askip := hskip.mono (n := c + 64) (by omega) + have asrc := ha.mono (n := c + 64) (by omega) + have hl := entry hr askip asrc hm + have hrgt := entry hr askip hm asrc + have hc := entry hr (hcount.mono (by omega)) asrc hm + have hk := hj.sub hl (fun s i => hfit s _ _) (fun s i => (partner_spec _ _ _).1) + have hk' : fits (fun s i => (p s i).2.val / 2 - skip (q s) (a s i) (b s i)) := + fun s i => (Nat.sub_le ..).trans_lt (hj' s i) + have hidx : packed F inp (fun s i => Diagonal.Links.index (q s) (p s i)) (c + 136) := + ((hk.unary hk' (R * ·)).add hb).mono (by omega) + exact ⟨hm.mono (by omega), hidx.mono (by omega), hc.mono (by omega), + wire_address (NeZero.pos R) hr' (hm.mono (by omega)) hidx (hrgt.mono (by omega)) + (fun s i => (b s i).isLt) (fun s i => (index_lt_of_size _).trans_le hw) (fun s i + => hfit s _ _)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +/- # Enumerating the incident links of one processor in parallel -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed + +open Coloring Diagonal.Links + +variable {F S : Type} [Field F] {w R N c : ℕ} {U : Coloring.Format} {inp : S → U.obj} + +/-- Repeated lanes are harmless in a conjunction. Assign the diagonal +of the processor-pair matrix to any existing link at the processor. -/ +private def fan (hr : 2 ≤ R) (u v : Fin R) : Link R := + if h : u < v then ⟨(u, v), h⟩ else if h : v < u then ⟨(v, u), h⟩ + else if h : u.val = 0 then ⟨(u, ⟨1, by omega⟩), by change u.val < 1; omega⟩ + else ⟨(⟨0, by omega⟩, u), by change 0 < u.val; omega⟩ + +private theorem fan_sees (hr : 2 ≤ R) (u v : Fin R) : sees u (fan hr u v) := by + unfold fan + split_ifs <;> simp [sees] + +private theorem fan_covers (hr : 2 ≤ R) (u : Fin R) (p : Link R) (hu : sees u p) : + ∃ v, fan hr u v = p := by + rcases hu with rfl|rfl + · exact ⟨p.val.2, by simp [fan, p.property]⟩ + · exact ⟨p.val.1, by simp [fan, p.property, p.property.not_gt]⟩ + +private theorem exists_lanes (hr : 2 ≤ R) (hn : 64 * R ^ 2 ≤ N) (hw : N ≤ 2 ^ w) : + ∃ f : B w → Fin R × Fin (N / (4 * R)), Function.Surjective f := by + have hc : R * (N / (4 * R)) ≤ 2 ^ w := by + rw [← Nat.div_div_eq_div_mul] + exact (Nat.mul_div_le ..).trans ((Nat.div_le_self ..).trans hw) + have h : 0 < N / (4 * R) := Nat.div_pos (by nlinarith) (by omega) + let _ : NeZero (R * (N / (4 * R))) := ⟨by positivity⟩ + refine ⟨fun i => finProdFinEquiv.symm (Fin.ofNat _ i.val), fun p => ?_⟩ + refine ⟨Fin.castLE hc (finProdFinEquiv p), ?_⟩ + apply finProdFinEquiv.injective + rw [Equiv.apply_symm_apply] + exact Fin.ext (Nat.mod_eq_of_lt (finProdFinEquiv p).isLt) + +/-- The fixed lane index specifies a peer and a byte. A small matrix +indexed by the worker and peer supplies link-specific metadata. -/ +theorem relay_lanes [NeZero R] {u : S → Fin R} (hr : 2 ≤ R) + (hn : 64 * R ^ 2 ≤ N) (hw : N ≤ 2 ^ w) (hu : packed F inp (fun s (_ : B w) => (u s).val) c) : + ∃ p : S → B w → Slot R N, + (∀ s i, sees (u s) (p s i).1) ∧ (∀ s t, sees (u s) t.1 → ∃ i, p s i = t) ∧ + packed F inp (fun s i => (sender (p s i)).val) (c + 64) ∧ + packed F inp (fun s i => (relay (p s i)).val) (c + 64) ∧ + packed F inp (fun s i => (p s i).2.val / 2) (c + 64) ∧ + packed F inp (fun s i => (p s i).1.val.1.val) (c + 64) ∧ + packed F inp (fun s i => (address (p s i)).val) (c + 64) := by + obtain ⟨f, hf⟩ := exists_lanes hr hn hw + let p (s : S) (i : B w) : Slot R N := (fan hr (u s) (f i).1, (f i).2) + have hmeta (g : Link R → ℕ) : packed F inp (fun s i => g (p s i).1) (c + 32) := by + have hg : packed F inp (matrix w (fun _ a b => g (fan hr a b))) (c + 2) := + const F inp (fun j => g (fan hr (atPair R j).1 (atPair R j).2)) hu.width + exact entry (by omega) hg (hu.mono (by omega)) (const F inp (fun j => (f j).1.val) hu.width) + have lo := hmeta (fun p => p.val.1.val) + have hi := hmeta (fun p => p.val.2.val) + have bit := const F inp (fun i => (f i).2.val % 2) hu.width + have zero := const F inp (fun _ => 0) hu.width + have hbit : fits (fun (_ : S) i => (f i).2.val % 2) := by + intro s i + have := Nat.le_pow (a := R) (by decide : 0 < 2) + dsimp; omega + have hz : fits (fun (_ : S) (_ : B w) => 0) := fun _ _ => Nat.two_pow_pos w + refine ⟨p, fun s i => fan_sees hr _ _, ?_, ?_, ?_, + (const F inp (fun i => (f i).2.val / 2) hu.width).mono (by omega), lo.mono (by omega), ?_⟩ + · intro s t ht + obtain ⟨v, hv⟩ := fan_covers hr _ _ ht + obtain ⟨i, he⟩ := hf (v, t.2) + exact ⟨i, by simp [p, he, hv]⟩ + · convert (bit.choose_eq zero lo hi hbit hz).mono (n := c + 64) (by omega) using 1 + funext s i + unfold sender p + split <;> rfl + · convert (bit.choose_eq zero hi lo hbit hz).mono (n := c + 64) (by omega) using 1 + funext s i + unfold relay p + split <;> rfl + · have hp := hmeta (fun p => N / (4 * R) * (p.val.1 + p.val.2).val) + exact ((const F inp (fun i => (f i).2.val) hu.width).add hp).mono (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +/- # Reading the incident bits of numbered channels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal +variable {R N : ℕ} + +/-- Computes the route address by the application `Links.endAddress R N u.val a.val b.val k +(Links.skip q a b) (Links.skip q b a)`. -/ +def routeAddress (N : ℕ) (q : Fin R → Fin R → ℕ) (u a b : Fin R) (k : ℕ) := + Links.endAddress R N u.val a.val b.val k (Links.skip q a b) (Links.skip q b a) + +private theorem symmetric (q : Fin R → Fin R → ℕ) (u a b : Fin R) (k : ℕ) + (hne : a ≠ b) (hu : a = u ∨ b = u) : + routeAddress N q u a b k = routeAddress N q u b a k := by + unfold routeAddress Links.endAddress + have hab : a.val ≠ b.val := fun h => hne (Fin.ext h) + rcases hu with rfl | rfl + · simp only [hab, ite_false, ite_true] + · simp only [hab.symm, ite_false, ite_true] + +namespace Channels + +variable {E J : Type} {src dst : E → Fin R} [Fintype E] [Fintype J] [LinearOrder J] + (c : Channels src dst J) + +omit [Fintype E] [Fintype J] [LinearOrder J] in +theorem widthAt_symm (u v : Fin R) : c.widthAt u v = c.widthAt v u := by + funext j + simp only [widthAt, or_comm] + +/-- The quantity computed by `start (c.widthAt (src e) (dst e)) (c.label e).1 + (c.label +e).2.val`. -/ +def address (e : E) := + start (c.widthAt (src e) (dst e)) (c.label e).1 + (c.label e).2.val + +theorem token_address (e : E) (he : src e ≠ dst e) : + (Links.token src dst c.serial e he).2.val = c.address e := by + unfold Links.token address + by_cases h : src e < dst e + · rw [dite_eq_left h] + exact c.serial_value _ + · rw [dite_eq_right h, widthAt_symm c (src e) (dst e)] + exact c.serial_value _ + +theorem location_eq (hq : ∀ u, ∑ v, Links.count src dst u v ≤ N / 64) + (hn : 64 * R ^ 2 ≤ N) (u : Fin R) (e : E) (he : src e ≠ dst e) (hu : src e = u ∨ dst e = u) : + (Links.location src dst c.serial hq hn u e he hu).val = + routeAddress N (Links.count src dst) u (src e) (dst e) (c.address e) := by + unfold Links.location + rw [Links.endpoint_address, token_address] + unfold Links.token + split + · rfl + · exact (symmetric _ u _ _ _ he hu).symm + +end Channels + +namespace Vector.packed + +open Coloring +variable {F S : Type} [Field F] {w c : ℕ} {U : Coloring.Format} [NeZero R] + {inp : S → U.obj} {q : S → Fin R → Fin R → ℕ} {u a b : S → B w → Fin R} + {k x : Array S w} + +theorem read_channel (hr : 2 ≤ R) (hw : R ^ 2 ≤ 2 ^ w) + (hs : packed F inp (matrix w (fun s => Links.skip (q s))) c) + (hu : packed F inp (fun s i => (u s i).val) c) + (ha : packed F inp (fun s i => (a s i).val) c) + (hb : packed F inp (fun s i => (b s i).val) c) + (hk : packed F inp k c) (hx : packed F inp x c) + (hf : ∀ s u v, Links.skip (q s) u v < 2 ^ w) (hfit : fits k) : + packed F inp (fun s i => x s (Fin.ofNat (2 ^ w) + (routeAddress N (q s) (u s i) (a s i) (b s i) (k s i)))) (c + 168) := by + have hle : 2 * R ≤ 2 ^ w := (by nlinarith : 2 * R ≤ R ^ 2) |>.trans hw + have hu' : fits (fun s i => (u s i).val) := fun s i => (u s i).isLt.trans_le (by omega) + have hm : c ≤ c + 30 := by omega + have ht := end_address (N := N) (NeZero.pos R) hle (hu.mono hm) (ha.mono hm) (hb.mono hm) + (hk.mono hm) (entry hw hs ha hb) (entry hw hs hb ha) + hu' (fun _ _ => Fin.isLt _) (fun _ _ => Fin.isLt _) hfit (fun _ _ => hf _ _ _) (fun _ _ + => hf _ _ _) + exact (hx.lookup ht).mono (by omega) + +end Vector.packed +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- # Prefix offsets in the physical relay schedule -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector + +open Install Diagonal.Links +variable {F S I : Type} [Field F] [Fintype I] {R w c : ℕ} [NeZero R] + {inp : S → I → Bool} {q : S → Fin R → Fin R → ℕ} + +private theorem size_bound (hw : R ^ 5 ≤ 2 ^ w) (hi : Fintype.card I ≤ 2 ^ w * (100 + w) ^ c) : + Fintype.card I + 4 * 2 ^ w * w + Fintype.card (Pair R) * w + + (2 ^ w * (100 + w) ^ (c + 12) + 3 * Fintype.card (Pair R) * w + 100000 * R ^ 5 * (w + 1)) ≤ + 2 ^ w * (100 + w) ^ (c + 13) := by + have hp : Fintype.card (Pair R) ≤ 2 ^ w := by + simp only [Fintype.card_prod, Fintype.card_fin, ← pow_two] + exact (Nat.pow_le_pow_right (NeZero.pos R) (by decide : 2 ≤ 5)).trans hw + have he (j : ℕ) (hj : j ≤ c + 12) : (100 + w) ^ j ≤ (100 + w) ^ (c + 12) := + Nat.pow_le_pow_right (by omega) hj + have h₁ := he c (by omega) + have h₂ : 100008 * (w + 1) ≤ (100 + w) ^ (c + 12) := + le_trans (by ring_nf; omega) (he 4 (by omega)) + calc + _ ≤ 2 ^ w * (100 + w) ^ c + 4 * 2 ^ w * w + 2 ^ w * w + + (2 ^ w * (100 + w) ^ (c + 12) + 3 * 2 ^ w * w + 100000 * 2 ^ w * (w + 1)) := by gcongr + _ ≤ 2 ^ w * ((100 + w) ^ c + (100 + w) ^ (c + 12) + 100008 * (w + 1)) := by ring_nf; omega + _ ≤ 2 ^ w * ((100 + w) ^ (c + 12) * 3) := by + have H (a b c : ℕ) (ha : a ≤ b) (hc : c ≤ b) : a + b + c ≤ b * 3 := by omega + exact Nat.mul_le_mul_left _ (H _ _ _ h₁ h₂) + _ ≤ _ := by rw [show c + 13 = (c + 12) + 1 by omega, pow_succ (100 + w) (c + 12)]; gcongr; omega + +theorem packed.skip (h : packed (U := raw I) F inp (matrix w q) c) + (hsize : R ^ 5 ≤ 2 ^ w) (hbound : ∀ s u v, q s u v + 1 < 2 ^ w) : + packed (U := raw I) F inp (matrix w (fun s => Diagonal.Links.skip (q s))) (c + 13) := by + have ht : R ^ 2 ≤ 2 ^ w := (Nat.pow_le_pow_right (NeZero.pos R) (by decide : 2 ≤ 5)).trans hsize + have hx : fits (matrix w q) := fun s _ => (Nat.lt_succ_self _).trans (hbound s _ _) + have hu := h.unary hx (fun k => k / R + 1) + obtain ⟨g, hg, he⟩ := hu.unpack (index (R := R) w) + have ho (s : S) (p : Pair R) (k) : g (inp s) (p, k) = digits w (q s p.1 p.2 / R + 1) k := by + simpa only [matrix, pair_index ht, raw, Equiv.refl_apply] using he s p k + have hv := hg.comp (prefixWords_net (F := F) (R := R) (w := w)) + apply packed.reshape _ (atPair R) hv (size_bound hsize h.width) + intro s j b + change digits w (prefixWords (g (inp s)) (atPair R j)) b = _ + rw [prefixWords_eq _ _ _ (ho s) (fun p => by + exact lt_of_le_of_lt (Nat.add_le_add_right (Nat.div_le_self _ _) 1) (hbound s p.1 p.2))] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Slots.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Slots.lean new file mode 100644 index 0000000000..edbb74f581 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Slots.lean @@ -0,0 +1,162 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.LocalReceive +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.PinIndexRead + +/-! +# Local slot numbers at a fixed cut + +The key number can depend on the worker. The two large indices +of a slot, its repetition number and bit index, are unchanged. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.SlotKey + +open Diagonal Controller +variable {F : Type} [Field F] {N l d B n r h : ℕ} + {P : Format N l d n r h} {A : Expansion F n h} {M : Bank (Fin n)} {hn : 2 ≤ n} {i : Fin n} + +/-- Indexes the domain by the coordinates of `Fin (count n r) × Fin t × Fin h`. -/ +abbrev Domain (n r t h : ℕ) := Fin (count n r) × Fin t × Fin h + +/-- Computes the expand by the application `atRow (enumerate hn i u x.1).val x.2.1 x.2.2`. -/ +def expand (hn : 2 ≤ n) (i : Fin n) (u : Worker r) {t : ℕ} (x : Domain n r t h) := + atRow (enumerate hn i u x.1).val x.2.1 x.2.2 + +theorem expand_injective (hn : 2 ≤ n) (i : Fin n) (u : Worker r) {t : ℕ} : + Function.Injective (expand (h := h) hn i u (t := t)) := by + intro a b he + have hk := congrArg SlotKey.key he + have ha := congrArg (fun p => (p.1.1.2, p.1.2.2)) he + exact Prod.ext ((enumerate hn i u).injective (Subtype.ext hk)) ha + +variable (s : Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i) + +/-- The subtype of `q : Position n r (B * P.count) h × Bool` satisfying `incident s (.inr (.inl +q))`. -/ +abbrev Here := {q : Position n r (B * P.count) h × Bool // incident s (.inr (.inl q))} + +theorem seen (q : Here s) : + focus hn i (workerAt s) (SlotKey.key q.1) = Layout.symbol (workerAt s) := by + have hq : A.src hn N s.report.1 (.inl q.val) = workerAt s ∨ + A.dst hn N s.report.1 (.inl q.val) = workerAt s := + q.2.imp (Worker.index r).eq_symm_apply.mpr (Worker.index r).eq_symm_apply.mpr + rcases hq with hq | hq + · simpa only [s.cut, hq] using visible_src hn A N s.report.1 q.val + · simpa only [s.cut, hq] using visible_dst hn A N s.report.1 q.val + +/-- The value specified by `((enumerate hn i (workerAt s)).symm ⟨SlotKey.key q.val, seen s q⟩, +q.val.1.1.2, q.val.1.2.2)`. -/ +def shrink (q : Here s) : Domain n r (B * P.count) h := + ((enumerate hn i (workerAt s)).symm ⟨SlotKey.key q.val, seen s q⟩, q.val.1.1.2, q.val.1.2.2) + +theorem expand_shrink (q : Here s) : expand hn i (workerAt s) (shrink s q) = q := by + simp only [expand, shrink, Equiv.apply_symm_apply] + rfl + +/-- Embeds `Here s` into `Domain n r (B * P.count) h`. -/ +def encode : Here s ↪ Domain n r (B * P.count) h := + ⟨shrink s, fun a b h => Subtype.ext ((expand_shrink s a).symm.trans + ((congrArg (expand hn i (workerAt s)) h).trans (expand_shrink s b)))⟩ + +theorem expand_encode (q : Here s) : expand hn i (workerAt s) (encode s q) = q := expand_shrink s q + +theorem range_encode (x : Domain n r (B * P.count) h) : + (∃ q, encode s q = x) ↔ incident s (.inr (.inl (expand hn i (workerAt s) x))) := by + constructor + · rintro ⟨q, rfl⟩ + rw [expand_encode] + exact q.property + · intro he + exact ⟨⟨_, he⟩, expand_injective hn i _ (expand_encode s _)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.SlotKey +end + +/- # Physical stream bits for each candidate class -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +open Diagonal MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +variable {F : Type} [Field F] [Fintype F] {N l n d r h B w : ℕ} + {P : Format N l d n r h} {M : Bank (Fin n)} {A : Expansion F n h} + {hn : 2 ≤ n} (C : Controller P A hn M B) {i : Fin n} + +local notation "X" => Invocation (P := P) (A := A) (hn := hn) (M := M) (B := B) i + +open Classical in +private def onLink (u x y : Worker r) := if x ≠ y ∧ (x = u ∨ y = u) then 1 else 0 + +open Classical in +private def gate (s : X) (c : Class r) := + onLink (workerAt s) (A.src hn N s.report.val (.inr c)) (A.dst hn N s.report.val (.inr c)) + +variable [LinearOrder (Name n r)] [NeZero (N / 4)] + +open Classical in +private theorem stream_eq (hw : N ≤ 2 ^ w) (s : X) (c : Class r) (j : ℕ) : + (C.numberInOrder.physicalBit s (.inr (.inr c)) j).toNat = + if 0 < gate s c then + if j < A.classWidth s.report.val c then (get w s (.inr (.inr c)) j).toNat else 0 + else 0 := by + let e : Edge P B := .inr (.inr c) + have he : 0 < gate s c ↔ source s e ≠ target s e ∧ incident s e := by + unfold gate onLink + simp only [e, class_here, source, target, Expansion.extraSrc, Expansion.extraDst, + Function.comp_apply, Sum.elim_inr, ne_eq, Equiv.apply_eq_iff_eq] + split_ifs <;> simp_all + change (C.numberInOrder.physicalBit s e j).toNat = _ + simp only [← ite_and, he, and_assoc] + change (C.numberInOrder.physicalBit s e j).toNat = + if source s e ≠ target s e ∧ incident s e ∧ j < width s e then _ else _ + unfold physicalBit + split_ifs with hh + · rw [C.get_eq hw] + have hkey : key P B e = .inr (.inr c) := rfl + have hoff : offset P B e = 0 := rfl + simp only [hoff, hkey, zero_mul, zero_add] + · rfl + +open Classical in +theorem packed_frame_stream (hw : Limits A N r (B * P.count) w) + (hi : Fintype.card (Machine.Ports N l l) ≤ 2 ^ w) + (ht : 2 ^ PacketKernel.height A (packetRows P B) < 2 ^ w) + (idx : Name n r ↪ Coloring.B w) (a : Coloring.B w → PacketKernel.Spot r) + (b : Coloring.B w → PackCode.Index (PacketKernel.height A (packetRows P B))) : + packed (U := raw _) F (C.input (i := i)) (fun s j => + (C.numberInOrder.physicalBit s (.inr (.inr (chosen s (a j)))) (b j).val).toNat) 315 := by + have : NeZero (3 * r) := ⟨by have := hw.pos; omega⟩ + let k (s : X) (j : Coloring.B w) : Name n r := .inr (.inr (chosen s (a j))) + have hkey := C.packed_chosen (i := i) hw hi idx a + have hindex := packed.const (U := raw _) F (C.input (i := i)) (fun j => (b j).val) + (m := 0) (by rw [pow_zero, mul_one]; exact hi) + have hz := packed.const (U := raw _) F (C.input (i := i)) (fun _ : Coloring.B w => 0) + (m := 0) (by rw [pow_zero, mul_one]; exact hi) + have hg := C.packed_get hw hi k idx _ hkey (hindex.mono (by decide)) + have hf := C.packed_frame_width (i := i) hw hi a + have hl (s : X) (j : Coloring.B w) : A.classWidth s.report.val (chosen s (a j)) < 2 ^ w := by + let c := chosen s (a j) + let z : A.Alphabet hn N s.report.val c := (choice (symbols_exist s)) (.inr (.inr c)) + exact ((PacketKernel.symbol_width A (PacketKernel.memberIndex A hn _ c) z).trans + (PacketKernel.capacity A _)).trans_lt ht + have ok := hindex.select hf hg hz (fun _ j => (b j).isLt.trans ht) hl + have hm := C.packed_class_pair (i := i) hw hi idx a onLink + have hh : 1 < 2 ^ w := Nat.one_lt_pow (by have := hw.large; omega) (by decide) + have hv := hz.select hm ok hz (fun _ _ => by positivity) (fun _ _ => by + unfold onLink + split <;> omega) + convert hv.mono (n := 315) (by decide) using 1 + funext s j + exact C.stream_eq hw.bits s (chosen s (a j)) (b j).val + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Controller +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Vector/Cases.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Vector/Cases.lean new file mode 100644 index 0000000000..b55f978313 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/Vector/Cases.lean @@ -0,0 +1,574 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Add +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Guard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet + +/-! +# Simultaneous arithmetic on valid inputs + +The same circuit handles every setting in the indicated domain. +Registers are interpreted modulo their capacity. Only comparisons and +indirect reads need hypotheses about the sizes of their operands. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +open Coloring +variable {F S : Type} [Field F] {w : ℕ} {U : Coloring.Format} + +/-- The indexing data represented by `S → B w → ℕ`. -/ +abbrev Array (S : Type) (w : ℕ) := S → B w → ℕ + +/-- The condition `∀ s i, f s i < 2 ^ w` on the specified data. -/ +def fits (f : Array S w) := ∀ s i, f s i < 2 ^ w + +/-- The condition `∃ g, Coloring.Cheap F w w U (Perm w) g c ∧ ∀ s i, g (inp s) i = Fin.ofNat (2 +^ w) (f s i)` on the specified data. -/ +def packed (F : Type) [Field F] (inp : S → U.obj) (f : Array S w) (c : ℕ) : Prop := + ∃ g, Coloring.Cheap F w w U (Perm w) g c ∧ ∀ s i, g (inp s) i = Fin.ofNat (2 ^ w) (f s i) + +namespace packed + +variable {inp : S → U.obj} {f g : Array S w} {m n : ℕ} + +theorem mono (h : packed F inp f m) (le : m ≤ n) : packed F inp f n := by + obtain ⟨a, ha, he⟩ := h + exact ⟨a, ha.mono le, he⟩ + +theorem const (F : Type) [Field F] (inp : S → U.obj) (f : B w → ℕ) + (hw : U.width ≤ 2 ^ w * (100 + w) ^ m) : packed F inp (fun _ => f) (m + 2) := by + have h₁ : U.width ≤ 2 ^ w * (100 + w) ^ (m + 1) := hw.trans (by gcongr; omega) + have h₂ : (Perm w).width ≤ 2 ^ w * (100 + w) ^ (m + 1) := by + rw [Format.width_vec, Format.width_addr] + exact Nat.mul_le_mul_left _ ((Nat.le_add_left _ _).trans (Nat.le_pow (by omega))) + exact ⟨_, Cheap.const F h₁ h₂ (fun i => Fin.ofNat (2 ^ w) (f i)), fun _ _ => rfl⟩ + +theorem width (hf : packed F inp f m) : U.width ≤ 2 ^ w * (100 + w) ^ m := by + obtain ⟨_, ⟨v, _, hv⟩, _⟩ := hf + omega + +theorem lookup (hf : packed F inp f m) (hg : packed F inp g n) : + packed F inp (fun s i => f s (Fin.ofNat (2 ^ w) (g s i))) (max m n + 10) := by + obtain ⟨a, ha, he⟩ := hf + obtain ⟨b, hb, hi⟩ := hg + have h := (ha.pair hb).comp (Cheap.lookup F w w (.addr w) le_rfl (by simp)) + exact ⟨_, h.mono (by omega), fun s i => by simp only [Function.comp_apply, hi, he]⟩ + +/-- A fixed unary table may be evaluated on every register at once. -/ +theorem unary (hf : packed F inp f m) (h : fits f) (t : ℕ → ℕ) : + packed F inp (fun s i => t (f s i)) (m + 12) := by + have he := ((const F inp (fun i : B w => t i.val) hf.width).lookup hf).mono + (n := m + 12) (by omega) + convert he using 1 + funext s i + exact congrArg t (Nat.mod_eq_of_lt (h s i)).symm + +theorem add (hf : packed F inp f m) (hg : packed F inp g n) : + packed F inp (fun s i => f s i + g s i) (max m n + 7) := by + obtain ⟨a, ha, he⟩ := hf + obtain ⟨b, hb, hi⟩ := hg + have h : Coloring.Cheap F 0 w (.pair (.addr w) (.addr w)) (.addr w) (fun x => x.1 + x.2) 4 := + ⟨_, numeric_add F w, by simp only [Format.width_pair, Format.width_addr]; ring_nf; omega⟩ + refine ⟨_, (((ha.pair hb).zip).comp (Coloring.Cheap.map _ (fun _ => h))).mono (by omega), ?_⟩ + intro s i + change a (inp s) i + b (inp s) i = _ + rw [he, hi] + exact Fin.ext (Nat.add_mod _ _ _).symm + +theorem select {t u : Array S w} {a b : ℕ} + (hf : packed F inp f m) (hg : packed F inp g n) + (ht : packed F inp t a) (hu : packed F inp u b) (h : fits f) (k : fits g) : + packed F inp (fun s i => if f s i < g s i then t s i else u s i) + (max (max m n) (max a b) + 12) := by + obtain ⟨x, hx, hx'⟩ := hf + obtain ⟨y, hy, hy'⟩ := hg + obtain ⟨z, hz, hz'⟩ := ht + obtain ⟨v, hv, hv'⟩ := hu + have cmp : Coloring.Cheap F 0 w (.pair (.addr w) (.addr w)) .bit (fun x => decide (x.1 < x.2)) 3 + := ⟨_, numeric_lt F w, by + simp only [Format.width_pair, Format.width_addr] + rw [Format.width_bit] + ring_nf + omega⟩ + have bit := ((hx.pair hy).zip).comp (Coloring.Cheap.map _ (fun _ => cmp)) + have step := (((hz.pair hv).zip.pair bit).zip).comp (Coloring.Cheap.map _ (fun _ + => cheap_select F w)) + refine ⟨_, step.mono (by omega), ?_⟩ + intro s i + simp only [Function.comp_apply, hx', hy', hz', hv', decide_eq_true_eq] + change (if f s i % 2 ^ w < g s i % 2 ^ w then _ else _) = _ + rw [Nat.mod_eq_of_lt (h s i), Nat.mod_eq_of_lt (k s i)] + split <;> rfl + +end packed +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +end + +section +/- # Routing lanes to one of two computations by a fixed partition -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +open Coloring + +variable {F S I J K : Type} [Field F] {w c : ℕ} {U : Coloring.Format} {inp : S → U.obj} + +/-- Both stages may use every lane. Empty index sets need no dummy input. -/ +theorem casesOn (hw : 1 ≤ w) (f : S → K → I ⊕ J → ℕ) (idx : B w → K) (arg : B w → I ⊕ J) + (h₁ : ∀ a : B w → I, packed F inp (fun s j => f s (idx j) (.inl (a j))) c) + (h₂ : ∀ a : B w → J, packed F inp (fun s j => f s (idx j) (.inr (a j))) c) : + packed F inp (fun s j => f s (idx j) (arg j)) (c + 14) := by + classical + rcases isEmpty_or_nonempty I with he|hi + · let k := Sum.elim (isEmptyElim : I → J) id + have h (x : I ⊕ J) : Sum.inr (k x) = x := by + cases x + · exact isEmptyElim ‹I› + · rfl + simpa only [Function.comp_apply, h] using (h₂ (k ∘ arg)).mono (n := c + 14) (by omega) + rcases isEmpty_or_nonempty J with he|hj + · let k := Sum.elim id (isEmptyElim : J → I) + have h (x : I ⊕ J) : Sum.inl (k x) = x := by + cases x + · rfl + · exact isEmptyElim ‹J› + simpa only [Function.comp_apply, h] using (h₁ (k ∘ arg)).mono (n := c + 14) (by omega) + let l := Sum.elim id (fun _ : J => hi.some) + let r := Sum.elim (fun _ : I => hj.some) id + let mask := Sum.elim (fun _ : I => 0) (fun _ : J => 1) + have a := h₁ (l ∘ arg) + have b := h₂ (r ∘ arg) + have m := const F inp (mask ∘ arg) a.width + have n := const F inp (fun _ => 1) a.width + have hp : 1 < 2 ^ w := Nat.one_lt_pow (by omega) (by decide) + have hf := m.select n a b (fun _ j => by cases h : arg j <;> simp [mask, h, hp]) + (fun _ _ => hp) + convert hf.mono (n := c + 14) (by omega) using 1 + funext s j + cases h : arg j <;> simp [l, r, mask, h] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +section +/- # Indirect reads through fixed finite lookup tables -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +open Coloring + +variable {F S J : Type} [Field F] {w : ℕ} {U : Coloring.Format} + {inp : S → U.obj} {c d : ℕ} + +theorem reduce {f : Array S w} (h : packed F inp f c) : + packed F inp (fun s i => f s i % 2 ^ w) c := by + obtain ⟨t, ht, he⟩ := h + exact ⟨t, ht, fun s i => (he s i).trans (Fin.ext (Nat.mod_mod _ _).symm)⟩ + +/-- A fixed indexing of the possible requests suffices. It is not +necessary to compute an inverse table from the input data. -/ +theorem fetch [Nonempty J] (keys : S → B w → J) (idx : J ↪ B w) (f : S → J → ℕ) + (hk : packed F inp (fun s i => (idx (keys s i)).val) c) + (ht : ∀ key : B w → J, packed F inp (fun s i => f s (key i)) d) : + packed F inp (fun s i => f s (keys s i)) (max d c + 10) := by + classical + let j := Function.invFun idx + have hh := (ht j).lookup hk + have he (s : S) (i : B w) : Fin.ofNat (2 ^ w) (idx (keys s i)).val = idx (keys s i) := + Fin.ext (Nat.mod_eq_of_lt (Fin.isLt _)) + have hi (k : J) : j (idx k) = k := Function.leftInverse_invFun idx.injective _ + simpa only [he, hi] using hh + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +section +/- # Converting circuits on named bits into packed word arrays -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +open Install Coloring + +/-- The indexing data represented by `⟨I → Bool, I, .refl _⟩`. -/ +abbrev raw (I : Type) [Fintype I] : Coloring.Format := ⟨I → Bool, I, .refl _⟩ + +variable {F S I J : Type} [Field F] [Fintype I] [Fintype J] {w : ℕ} + {inp : S → I → Bool} {f : Array S w} {m c : ℕ} + +theorem packed.of_net (k : (I → Bool) → B w × slots (word w) → Bool) + (hk : BNet F k m) (hc : Fintype.card I + 2 ^ w * w + m ≤ 2 ^ w * (100 + w) ^ c) + (he : ∀ s j b, k (inp s) (j, b) = digits w (f s j) b) : + packed (U := raw I) F inp f c := by + refine ⟨(Perm w).code.symm ∘ k, ⟨m, ?_, ?_⟩, ?_⟩ + · simpa only [Circuit, Function.comp_def, Equiv.apply_symm_apply, raw, Equiv.refl_symm, + Equiv.refl_apply] using hk + · simpa [raw, Perm] using hc + · intro s i + change Control.decode w (fun t => k (inp s) (i, t)) = _ + simp only [he, digits, Equiv.apply_symm_apply] + +theorem packed.reshape (k : (I → Bool) → J × slots (word w) → Bool) (idx : B w → J) + (hk : BNet F k m) (hc : Fintype.card I + 4 * 2 ^ w * w + Fintype.card J * w + m ≤ 2 ^ w * (100 + + w) ^ c) + (he : ∀ s j b, k (inp s) (idx j, b) = digits w (f s j) b) : + packed (U := raw I) F inp f c := by + let e : B w × slots (word w) → J × slots (word w) := Prod.map idx id + have h := hk.comp ((BNet.id F _).pull e) + refine packed.of_net _ h ?_ he + simp only [Fintype.card_prod, Fintype.card_fin, card_slots, wd_word] + nlinarith only [hc] + +theorem packed.unpack {U : Coloring.Format} {inp : S → U.obj} + (h : packed F inp f c) (idx : J → B w) : + ∃ k : (U.pins → Bool) → (J × slots (word w)) → Bool, + BNet F k (2 ^ w * (100 + w) ^ c + 3 * Fintype.card J * w) ∧ + ∀ s j b, k (U.code (inp s)) (j, b) = digits w (f s (idx j)) b := by + obtain ⟨g, ⟨m, hg, hm⟩, he⟩ := h + let e : J × slots (word w) → B w × slots (word w) := Prod.map idx id + have t := BNet.comp hg ((BNet.id F _).pull e) + refine ⟨_, t.mono ?_, fun s j b => ?_⟩ + · simp only [Fintype.card_prod, Fintype.card_fin, card_slots, wd_word, Perm, Format.width_vec, + Format.width_addr] at hm ⊢ + nlinarith only [hm] + · simp only [Function.comp_apply, id_eq, Equiv.symm_apply_apply] + change (Control.decode w).symm (g (inp s) (idx j)) b = _ + rw [he] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +end + +section +/- # Row sums of small square arrays of channel lengths -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector + +open Coloring Install +variable {F S : Type} [Field F] {w R : ℕ} [NeZero R] + +/-- Indexes the pair by the coordinates of `Fin R × Fin R`. -/ +abbrev Pair (R : ℕ) := Fin R × Fin R + +/-- The quantity computed by `Fin.ofNat (2 ^ w) (p.1.val * R + p.2.val)`. -/ +def index (w : ℕ) (p : Pair R) : B w := Fin.ofNat (2 ^ w) (p.1.val * R + p.2.val) + +/-- The quantity computed by `finProdFinEquiv.symm (Fin.ofNat (R * R) i.val)`. -/ +def atPair (R : ℕ) [NeZero R] (i : B w) : Pair R := + finProdFinEquiv.symm (Fin.ofNat (R * R) i.val) + +theorem pair_index (hw : R ^ 2 ≤ 2 ^ w) (p : Pair R) : atPair R (index w p) = p := by + apply finProdFinEquiv.injective + simp only [atPair, Equiv.apply_symm_apply] + apply Fin.ext + have he : p.1.val * R + p.2.val = (finProdFinEquiv p).val := by + change _ = p.2.val + R * p.1.val + ring + change (p.1.val * R + p.2.val) % 2 ^ w % (R * R) = _ + rw [he, Nat.mod_eq_of_lt ((finProdFinEquiv p).isLt.trans_le (by rwa [pow_two] at hw)), + Nat.mod_eq_of_lt (finProdFinEquiv p).isLt] + +/-- Evaluates `f s (atPair R i).1 (atPair R i).2` at the input `s i`. -/ +def matrix (w : ℕ) (f : S → Fin R → Fin R → ℕ) : Array S w := + fun s i => f s (atPair R i).1 (atPair R i).2 + +theorem matrix_index (hw : R ^ 2 ≤ 2 ^ w) (f : S → Fin R → Fin R → ℕ) (s : S) (u v : Fin R) : + matrix w f s (Fin.ofNat (2 ^ w) (u.val * R + v.val)) = f s u v := by + change matrix w f s (index w (u, v)) = _ + rw [matrix, pair_index hw] + +/-- Indexes the cell by the coordinates of `Pair R × slots (word w)`. -/ +abbrev Cell (R w : ℕ) := Pair R × slots (word w) + +/-- The indexed operation `(Control.decode w (fun k => x (p, k))).val`. -/ +def decode (x : Cell R w → Bool) (p : Pair R) := (Control.decode w (fun k => x (p, k))).val + +omit [NeZero R] in +private theorem decoded (F : Type) [Field F] (p : Pair R) : + Register F w (fun x => decode (w := w) x p) (Fintype.card (Cell R w) + 3 * w) := by + have hp := (BNet.id F (slots (word w))).pull (fun i => (p, i)) + unfold Register + have he (x : Cell R w → Bool) : digits w (decode x p) = fun i => x (p, i) := by + unfold digits decode + rw [show Fin.ofNat (2 ^ w) (Control.decode w (fun k => x (p, k))).val = + Control.decode w (fun k => x (p, k)) from Fin.ext (Nat.mod_eq_of_lt (Fin.isLt _))] + exact (Control.decode w).symm_apply_apply _ + simp only [he] + exact hp.mono (by unfold Cell; rw [card_slots, wd_word]; omega) + +/-- The value specified by `∑ j : Fin R, if j < p.2 then decode x (p.1, j) else 0`. -/ +def prefixWords (x : Cell R w → Bool) (p : Pair R) := + ∑ j : Fin R, if j < p.2 then decode x (p.1, j) else 0 + +theorem prefixWords_net : + BNet F (fun (x : Cell R w → Bool) (q : Cell R w) => digits w (prefixWords x q.1) q.2) + (100000 * R ^ 5 * (w + 1)) := by + let T := Fintype.card (Cell R w) + have hj (p : Pair R) (j : Fin R) : + Register F w (fun x : Cell R w → Bool => if j < p.2 then decode x (p.1, j) else 0) + (T + 16 * w) := by + by_cases h : j < p.2 + · simp only [ite_eq_left h] + exact (decoded F _).mono (by omega) + · simp only [ite_eq_right h] + exact Register.const _ + have hp (p : Pair R) := Register.sum _ (hj p) + apply (BNet.collect _ hp).mono + have ht : Fintype.card (Cell R w) = R ^ 2 * w := by simp [Cell, Pair, pow_two] + have hr : 1 ≤ R := NeZero.pos R + have hR : R ^ 2 ≤ R ^ 5 := Nat.pow_le_pow_right hr (by decide) + have h₁ : 1 ≤ R ^ 2 := Nat.one_le_pow _ _ hr + have hh : w ≤ R ^ 2 * w := Nat.le_mul_of_pos_left _ h₁ + unfold T + rw [ht, show Fintype.card (Pair R) = R ^ 2 by simp [Pair, pow_two], Fintype.card_fin] + calc + _ ≤ R ^ 5 * w + R ^ 2 * (2 * (R ^ 2 * w) + (2 * R) * (40000 * R ^ 2 * (w + 1))) := by + gcongr + · omega + · nlinarith only [hh, h₁] + _ ≤ _ := by + have h : R ^ 4 * w ≤ R ^ 5 * w := Nat.mul_le_mul_right _ (Nat.pow_le_pow_right hr (by decide)) + nlinarith only [h, Nat.zero_le (R ^ 5 * w), Nat.zero_le (R ^ 5)] + +omit [NeZero R] in +theorem prefixWords_eq (x : Cell R w → Bool) (g : Pair R → ℕ) (p : Pair R) + (h : ∀ q k, x (q, k) = digits w (g q) k) (hb : ∀ q, g q < 2 ^ w) : + prefixWords x p = ∑ j ∈ Finset.Iio p.2, g (p.1, j) := by + unfold prefixWords decode + simp only [h, digits, Equiv.apply_symm_apply, Fin.val_ofNat, Nat.mod_eq_of_lt (hb _)] + rw [← Finset.sum_filter, show Finset.univ.filter (fun j : Fin R => j < p.2) = Finset.Iio p.2 by + ext; simp] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector +end + +section +/- # Loading bits into word lanes and checking simultaneous assertions -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed + +open Install Coloring +variable {F S I : Type} [Field F] [Fintype I] {w c : ℕ} + +private theorem slack (w c : ℕ) : + 2 * (2 ^ w * (100 + w) ^ c) + 35 * (2 ^ w * w) + 1 ≤ 2 ^ w * (100 + w) ^ (c + 2) := by + let T := 2 ^ w * (100 + w) ^ c + have hh : 2 ^ w ≤ T := Nat.le_mul_of_pos_right _ (by positivity) + have ht : 0 < T := by unfold T; positivity + rw [pow_add, ← mul_assoc (2 ^ w)] + calc + _ ≤ 2 * T + 35 * (T * w) + T := by gcongr; omega + _ = T * (3 + 35 * w) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ (by nlinarith) + +theorem named (F : Type) [Field F] (inp : S → I → Bool) (idx : B w → I) + (hi : Fintype.card I ≤ 2 ^ w * (100 + w) ^ c) : + packed (U := raw I) F inp (fun s i => (inp s (idx i)).toNat) (c + 2) := by + let k (x : I → Bool) (i : B w × slots (word w)) := digits w (x (idx i.1)).toNat i.2 + have hd : Depends k 1 := by + intro i + refine ⟨{idx i.1}, by simp, fun x y h => ?_⟩ + unfold k + rw [h _ (Finset.mem_singleton_self _)] + refine of_net k (hd.bnet F) ?_ (fun _ _ _ => rfl) + simp only [Fintype.card_prod, Fintype.card_fin, card_slots, wd_word] + rw [show localCost 1 = 34 by decide] + have := slack w c + omega + +open Classical in +private theorem equal (z : I → Bool) : + BNet F (fun x => fun _ : Unit => decide (x = z)) (10 * Fintype.card I + 1) := by + let a := word (Fintype.card I) + let e : I ≃ slots (word (Fintype.card I)) := Fintype.equivOfCardEq (by simp) + let r := (bits a).trans (e.symm.arrowCongr (.refl Bool)) + apply BNet.of_layout (a := a) (b := .bit) e (.refl Unit) + have h := Control.equal_net F a (r.symm z) + change DNet F a .bit (fun x => decide (r x = z)) _ + simpa only [r.eq_symm_apply, a, wd_word] using h + +theorem conjunction {inp : S → I → Bool} {f : Array S w} (hw : 1 ≤ w) + (h : packed (U := raw I) F inp f c) (hfit : fits f) : + ∃ b : (I → Bool) → Unit → Bool, BNet F b (2 ^ w * (100 + w) ^ (c + 2)) ∧ + ∀ s, b (inp s) () = decide (∀ i, f s i = 1) := by + classical + obtain ⟨k, hk, he⟩ := h.unpack id + let z (i : B w × slots (word w)) := digits w 1 i.2 + have H := hk.comp (equal (F := F) z) + refine ⟨_, H.mono ?_, fun s => ?_⟩ + · simp only [Fintype.card_prod, Fintype.card_fin, card_slots, wd_word] + rw [mul_assoc 3] + have := slack w c + omega + · simp only [Function.comp_apply, decide_eq_decide] + have hm : 1 < 2 ^ w := Nat.one_lt_pow (by omega) (by decide) + change k (inp s) = z ↔ _ + have hv (i j) : k (inp s) (i, j) = digits w (f s i) j := he s i j + constructor + · intro h i + have hd : digits w (f s i) = digits w 1 := funext fun j => + (hv i j).symm.trans (congrFun h (i, j)) + have := congrArg Fin.val ((Control.decode w).symm.injective hd) + simpa only [Fin.val_ofNat, Nat.mod_eq_of_lt (hfit s i), Nat.mod_eq_of_lt hm] using this + · intro h + funext ⟨i, j⟩ + rw [hv, h] + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +section +/- +# Static tables indexed by two smaller keys + +A worker number and a local record number can jointly index a table +even when the record is used many times. The product of the two key +ranges must fit in the shared array. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +open Coloring + +variable {F S : Type} [Field F] {w m n : ℕ} {U : Coloring.Format} + {inp : S → U.obj} {f g : Array S w} {c d : ℕ} + +theorem binary (a : ℕ → ℕ → ℕ) (hw : m * n ≤ 2 ^ w) + (hf : packed F inp f c) (hg : packed F inp g d) + (hm : ∀ s i, f s i < m) (hn : ∀ s i, g s i < n) : + packed F inp (fun s i => a (f s i) (g s i)) (max c d + 32) := by + have hw' : fits f := fun s i => (hm s i).trans_le + ((Nat.le_mul_of_pos_right _ (Nat.zero_lt_of_lt (hn s i))).trans hw) + have he : fits (fun s i => f s i * n + g s i) := by + intro s i + exact (Nat.add_lt_add_left (hn s i) _).trans_le + (by rw [← Nat.succ_mul]; exact (Nat.mul_le_mul_right _ (hm s i)).trans hw) + have ha := ((hf.unary hw' (·*n)).add hg).unary he (fun x => a (x / n) (x % n)) + convert ha.mono (n := max c d + 32) (by omega) using 1 + funext s i + have hpos : 0 < n := Nat.zero_lt_of_lt (hn s i) + rw [mul_comm (f s i), Nat.mul_add_div hpos, Nat.div_eq_of_lt (hn s i), add_zero, + Nat.mul_add_mod, Nat.mod_eq_of_lt (hn s i)] + +theorem named_table {A B : Type} [Fintype A] [Fintype B] [Nonempty A] [Nonempty B] + (a : A → B → ℕ) (ha : Fintype.card A * Fintype.card B ≤ 2 ^ w) + (x : S → Coloring.B w → A) (y : S → Coloring.B w → B) + (p : A ≃ Fin (Fintype.card A)) (q : B ≃ Fin (Fintype.card B)) + (hp : packed F inp (fun s i => (p (x s i)).val) c) + (hq : packed F inp (fun s i => (q (y s i)).val) d) : + packed F inp (fun s i => a (x s i) (y s i)) (max c d + 32) := by + let _ : NeZero (Fintype.card A) := ⟨Fintype.card_ne_zero⟩ + let _ : NeZero (Fintype.card B) := ⟨Fintype.card_ne_zero⟩ + have h := binary (fun u v => a (p.symm (Fin.ofNat _ u)) (q.symm (Fin.ofNat _ v))) + ha hp hq (fun _ _ => Fin.isLt _) (fun _ _ => Fin.isLt _) + have he {m : ℕ} [NeZero m] (i : Fin m) : Fin.ofNat m i.val = i := + Fin.ext (Nat.mod_eq_of_lt i.isLt) + simpa only [he, Equiv.symm_apply_apply] using h + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +section +/- # Changing the input and the lane indexing of a packed computation -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +open Coloring +variable {F S T I J : Type} [Field F] [Fintype I] [Fintype J] {w c : ℕ} + {inp : S → I → Bool} {f : Array S w} + +theorem lift (h : packed (U := raw I) F inp f c) + (inp' : T → J → Bool) (k : T → S) (p : I → J) (hi : Fintype.card J ≤ 2 ^ w) + (he : ∀ t, inp' t ∘ p = inp (k t)) : + packed (U := raw J) F inp' (fun t => f (k t)) (c + 2) := by + have hw : (raw J).width ≤ 2 ^ w * (100 + w) ^ c := + hi.trans (Nat.le_mul_of_pos_right _ (by positivity)) + have hp := Cheap.project F (f := fun (x : (raw J).obj) => (x ∘ p : (raw I).obj)) + hw h.width p (fun _ _ => rfl) + obtain ⟨a, ha, hf⟩ := h + refine ⟨_, (hp.comp ha).mono (by omega), ?_⟩ + intro t i + change a (inp' t ∘ p) i = _ + rw [he] + exact hf _ _ + +/-- Renumber a packed domain by any static function. -/ +theorem remap {D : Type} {U : Coloring.Format} {inp : S → U.obj} + (a : S → B w → D) (idx : D ↪ B w) (ha : packed F inp (fun s j => (idx (a s j)).val) c) + (fn : D → ℕ) : packed F inp (fun s j => fn (a s j)) (c + 12) := by + classical + let g (k : ℕ) := Function.extend idx fn (fun _ => 0) (Fin.ofNat (2 ^ w) k) + have h := ha.unary (fun _ _ => Fin.isLt _) g + have he (s : S) (j : B w) : g (idx (a s j)).val = fn (a s j) := by + unfold g + rw [show Fin.ofNat (2 ^ w) (idx (a s j)).val = idx (a s j) from + Fin.ext (Nat.mod_eq_of_lt (Fin.isLt _))] + exact idx.injective.extend_apply _ _ _ + simpa only [he] using h + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end + +section +/- # Returning named Boolean results from a packed calculation -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +open Coloring Install +variable {F S I J : Type} [Field F] [Fintype I] [Fintype J] {w c : ℕ} + {inp : S → I → Bool} + +private theorem read_flag (hw : 1 ≤ w) : + ∃ (k : slots (word w)) (t : Bool → Bool), ∀ b : Bool, t (digits w b.toNat k) = b := by + have hz : 1 < 2 ^ w := Nat.one_lt_pow (by omega) (by decide) + have hn : digits w 0 ≠ digits w 1 := by + intro he + have := congrArg Fin.val ((Control.decode w).symm.injective he) + simp only [Fin.val_ofNat, Nat.zero_mod, Nat.mod_eq_of_lt hz] at this + omega + obtain ⟨i, hi⟩ := Function.ne_iff.mp hn + exact ⟨i, fun a => decide (a = digits w 1 i), by rintro (_|_) <;> simp [hi]⟩ + +/-- If the register in each lane represents a bit, any fixed naming +of the requested bits can be used for the output of the circuit. -/ +theorem output (hw : 1 ≤ w) (hi : Fintype.card I ≤ 2 ^ w) (hj : Fintype.card J ≤ 2 ^ w) + (f : S → J → Bool) + (hf : ∀ ix : B w → J, packed (U := raw I) F inp (fun s j => (f s (ix j)).toNat) c) : + ∃ t, BNet F t (2 ^ w * (100 + w) ^ (c + 2)) ∧ ∀ s, t (inp s) = f s := by + classical + have hsize : 2 ^ w * (100 + w) ^ c + 4 * Fintype.card J * w + 34 * Fintype.card J ≤ 2 ^ w * (100 + + w) ^ (c + 2) := by + have hc : 1 ≤ (100 + w) ^ c := Nat.one_le_pow _ _ (by omega) + calc + _ ≤ 2 ^ w * (100 + w) ^ c + 4 * 2 ^ w * w + 34 * 2 ^ w := by gcongr + _ = 2 ^ w * ((100 + w) ^ c + (4 * w + 34)) := by ring + _ ≤ 2 ^ w * ((100 + w) ^ c * (1 + (4 * w + 34))) := by + rw [mul_add ((100 + w) ^ c), mul_one] + gcongr + exact Nat.le_mul_of_pos_left _ hc + _ ≤ _ := by rw [pow_add]; gcongr; nlinarith + cases isEmpty_or_nonempty J + · have hd : Depends (fun (_ : I → Bool) (_ : J) => false) 0 := + fun _ => ⟨∅, by simp, fun _ _ _ => rfl⟩ + refine ⟨_, (hd.bnet F).mono ?_, fun _ => Subsingleton.elim _ _⟩ + simpa only [Fintype.card_eq_zero, mul_zero, add_zero] using + hi.trans (Nat.le_mul_of_pos_right _ (by positivity : 0 < (100 + w) ^ (c + 2))) + · obtain ⟨idx⟩ : Nonempty (J ↪ B w) := Function.Embedding.nonempty_of_card_le (by simpa using hj) + obtain ⟨k, t, he⟩ := read_flag hw + obtain ⟨g, hg, hg'⟩ := (hf (Function.invFun idx)).unpack idx + let a (x : J × slots (word w) → Bool) (j : J) := t (x (j, k)) + have ha : Depends a 1 := fun j => ⟨{(j, k)}, by simp, fun x y h => congrArg t (h _ (by simp))⟩ + refine ⟨_, (hg.comp (ha.bnet F)).mono ?_, fun s => funext fun j => ?_⟩ + · rw [Fintype.card_prod, card_slots, wd_word] + rw [show localCost 1 = 34 by decide] + exact le_trans (le_of_eq (by ring)) hsize + · have h := hg' s j k + rw [Function.leftInverse_invFun idx.injective j] at h + exact (congrArg t h).trans (he _) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor.Vector.packed +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/WindowSize.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/WindowSize.lean new file mode 100644 index 0000000000..30ed6f05bb --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Processor/WindowSize.lean @@ -0,0 +1,282 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Handle +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.DispatchSize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagonal.Broadcast + +/-! # Finite size estimates before the working width is chosen -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal Controller +variable {F : Type} [Field F] [Fintype F] {N l d B n r h C : ℕ} + +theorem Bank.data_le_budget (M : Bank (Fin n)) (F : Type) [Field F] [Fintype F] : + Fintype.card M.Data ≤ M.budget F := by + simp only [Bank.Data, Fintype.card_sigma, Fintype.card_prod, Fintype.card_fin, Bank.budget] + apply Finset.sum_le_sum + intro i _ + have : 0 < templateCost F := by unfold templateCost; positivity + exact (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_left _ this)).trans + (Nat.le_mul_of_pos_right _ (by positivity)) + +namespace Window + +theorem position_card (n r a h : ℕ) : + Fintype.card (Position n r a h) = (r ^ n) ^ 2 * 2 ^ n * h * a := by + simp [Position, Packet, Template, Label, Spectral.Cube] + ring + +theorem position_bound (hp : (r ^ n) ^ 2 * 2 ^ n * h ≤ C * N * d) : + Fintype.card (Position n r (rounds n r h (12 * (C * N * d))) h) ≤ 13 * C * N * d := by + let M := (r ^ n) ^ 2 * 2 ^ n * h + rw [position_card] + have he : rounds n r h (12 * (C * N * d)) = 12 * (C * N * d) / M + 1 := by + simp [rounds, Label, Spectral.Cube, M] + rw [he] + change M * (12 * (C * N * d) / M + 1) ≤ _ + rw [mul_add, mul_one] + exact (Nat.add_le_add (Nat.mul_div_le _ _) hp).trans_eq (by ring) + +variable (P : Format N l d n r h) + +theorem total_positions (hpos : Fintype.card (Position n r P.count h) ≤ 13 * C * N * d) + (hB : B * d ≤ 4 * r) : Fintype.card (Position n r (B * P.count) h) ≤ 52 * C * N * r := by + calc + _ = B * Fintype.card (Position n r P.count h) := by rw [position_card, position_card]; ring + _ ≤ B * (13 * C * N * d) := Nat.mul_le_mul_left _ hpos + _ = 13 * C * N * (B * d) := by ring + _ ≤ 13 * C * N * (4 * r) := Nat.mul_le_mul_left _ hB + _ = _ := by ring + +variable (hp : Fintype.card (Position n r (B * P.count) h) ≤ 52 * C * N * r) + +include hp in +theorem packet_bound (hh : 0 < h) : Fintype.card (Packet n r (B * P.count)) ≤ 52 * C * N * r := by + refine le_trans ?_ hp + rw [Fintype.card_prod (Packet n r (B * P.count))] + have : Nonempty (Fin h) := ⟨⟨0, hh⟩⟩ + exact Nat.le_mul_of_pos_right _ Fintype.card_pos + +include hp in +theorem rows_bound (hh : 0 < h) (hr : 0 < r) : r ^ 2 * packetRows P B ≤ 52 * C * N := by + apply Nat.le_of_mul_le_mul_right _ hr + calc + _ = (PacketKernel.templates n r * r ^ 3) * (B * P.count) := by unfold packetRows; ring + _ ≤ (r ^ n) ^ 2 * (B * P.count) := Nat.mul_le_mul_right _ (Nat.div_mul_le_self _ _) + _ = Fintype.card (Packet n r (B * P.count)) := by simp [Packet, Template, Label, pow_two] + _ ≤ _ := packet_bound P hp hh + +include hp in +theorem guess_bound (hl : l ≤ N) (hr : 0 < r) : + Fintype.card (XIn P B) ≤ (16 + 104 * C) * N := by + have hs : Fintype.card (SlotKey.Domain n r (B * P.count) h) ≤ 104 * C * N := by + apply Nat.le_of_mul_le_mul_right _ hr + calc + _ = (Fintype.card (SlotKey n r) / r * r) * (B * P.count * h) := by + simp only [SlotKey.Domain, Fintype.card_prod, Fintype.card_fin, SlotKey.count] + ring + _ ≤ Fintype.card (SlotKey n r) * (B * P.count * h) + := Nat.mul_le_mul_right _ (Nat.div_mul_le_self _ _) + _ = 2 * Fintype.card (Position n r (B * P.count) h) := by + simp only [SlotKey, Position, Packet, Fintype.card_prod, Fintype.card_fin, + Fintype.card_bool] + ring + _ ≤ 2 * (52 * C * N * r) := Nat.mul_le_mul_left _ hp + _ = _ := by ring + have hi : Fintype.card (PinIndex.Domain N l r) ≤ l + 12 * N := by + simp only [PinIndex.Domain, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + rw [show 4 * N / r * (3 * r) = 3 * (4 * N / r * r) by ring] + have := Nat.div_mul_le_self (4 * N) r + omega + rw [Fintype.card_sum, Fintype.card_sum (α := PinIndex.Domain N l r), add_mul] + have ht : Fintype.card (Machine.Ports N l l) ≤ 3 * N := by simp [Machine.Ports]; omega + omega + +end Window +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end + +section +/- +# A single working width at each sufficiently large scale + +The number of lanes exceeds the length of the processor by a +polylogarithmic factor. Packet slots and private bits are counted +per worker, before any diagram is chosen. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Processor +open Diagonal Controller Filter +variable {F : Type} [Field F] [Fintype F] {N l d B n r h C Q w W : ℕ} + +private theorem rough_keys (hn : 2 ≤ n) (hr : 1 ≤ r) (hp : r ^ (16 * n) ≤ N) : + 3 * r * Fintype.card (Name n r) ≤ 9 * (6 + 2 * 2 ^ n) * N ∧ + Fintype.card (Query n r) ≤ 9 * (6 + 2 * 2 ^ n) * N := by + let T := (r ^ n) ^ 2 + have ht (j : ℕ) (hj : j ≤ n * 2) : r ^ j ≤ T := by + unfold T; rw [← pow_mul] + exact Nat.pow_le_pow_right hr hj + have h₁ : r * r ^ n ≤ T := by rw [← pow_succ']; exact ht _ (by omega) + have h₂ : r ^ n ≤ T := ht _ (by omega) + have h₃ : r ^ 3 ≤ T := ht _ (by omega) + have h₄ : 1 ≤ T := ht 0 (by omega) + have h₅ : r ^ 2 * T ≤ N := by + unfold T + rw [← pow_mul, ← pow_add] + exact (Nat.pow_le_pow_right hr (by omega)).trans hp + have ha : Fintype.card (Name n r) + 1 ≤ (6 + 2 * 2 ^ n) * T := by + rw [name_card] + change 3 * r * r ^ n + r ^ n + T * 2 ^ n * 2 + r ^ 3 + 1 ≤ _ + nlinarith only [h₁, h₂, h₃, h₄] + have hb : (3 * r) * (3 * r) * (Fintype.card (Name n r) + 1) ≤ 9 * (6 + 2 * 2 ^ n) * N := by + calc + _ ≤ (3 * r) * (3 * r) * ((6 + 2 * 2 ^ n) * T) := Nat.mul_le_mul_left _ ha + _ = 9 * (6 + 2 * 2 ^ n) * (r ^ 2 * T) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ h₅ + constructor + · exact (Nat.mul_le_mul (Nat.le_mul_of_pos_right _ (by omega)) (Nat.le_succ _)).trans hb + · rw [Fintype.card_prod, Fintype.card_prod, Fintype.card_option, Fintype.card_fin, ← mul_assoc] + exact hb + +private def threshold (A : Expansion F n h) (C : ℕ) := + 100000000 + 3 * n + 9 * (6 + 2 * 2 ^ n) + (16 + 104 * C) + + PacketKernel.rate A + PacketKernel.batchRate A + 512 * PacketKernel.rowSize A + + 36 * Fintype.card A.I + 15 * PacketKernel.frameRate A * (52 * C + 1) + + 2 * PacketKernel.rowSize A * (52 * C + 1) + +private theorem finite_window (P : Format N l d n r h) (A : Expansion F n h) (hn : 2 ≤ n) + (M : Bank (Fin n)) (S : Controller P A hn M B) (hh : 0 < h) + (hN : N = 2 ^ w) (hr : 3 ≤ r) (hp : r ^ (16 * n) ≤ N) (hl : l ≤ N) + (hpos : Fintype.card (Position n r P.count h) ≤ 13 * C * N * d) (hB : B * d ≤ 4 * r) + (hM : M.budget F ≤ N * w ^ Q) (hT : threshold A C ≤ w) + (hW : w ≤ W) (hs : W ≤ 2 * w) (hu : 2 ^ W ≤ N * w ^ (Q + 10)) (hd : N * w ^ (Q + 4) ≤ 2 ^ W) : + Window P A M B C Q w W := by + unfold threshold at hT + have hw : 100000000 ≤ w := by omega + have hNr : 0 < N := by rw [hN]; positivity + have hNw : w < N := by rw [hN]; exact Nat.lt_two_pow_self + have hr' : 0 < r := by omega + have hpow (j : ℕ) (hj : j ≤ 16 * n) : r ^ j ≤ N := (Nat.pow_le_pow_right hr' hj).trans hp + have hrN : r ≤ N := by simpa using hpow 1 (by omega) + have hr₂ := hpow 2 (by omega) + have hr₃ := hpow 3 (by omega) + have spaces (k : ℕ) (hk : k < Q + 4) : N * w ^ k < 2 ^ W := + (Nat.mul_lt_mul_of_pos_left (Nat.pow_lt_pow_right (by omega) hk) hNr).trans_le hd + have hcap : N * w < 2 ^ W := by simpa using spaces 1 (by omega) + have constantValue (k : ℕ) (hk : k ≤ w) : k * N ≤ 2 ^ W := + (Nat.mul_le_mul_right N hk).trans (by rw [mul_comm]; exact hcap.le) + have hNV : N ≤ 2 ^ W := by simpa using constantValue 1 (by omega) + have htot := Window.total_positions P hpos hB + have hpack := Window.packet_bound P htot hh + have hrow := Window.rows_bound P htot hh hr' + have hrow' : r ^ 2 * (1 + packetRows P B) ≤ (52 * C + 1) * N := by rw [mul_add, add_mul]; omega + have hpack' : Fintype.card (Packet n r (B * P.count)) < N ^ 3 := by + apply hpack.trans_lt + calc + _ ≤ 52 * C * N * N := Nat.mul_le_mul_left _ hrN + _ < N * N * N := by gcongr; omega + _ = _ := by ring + have hcnt : countWidth P B ≤ 3 * w := by + apply Nat.clog_le_of_le_pow + rw [mul_comm 3, pow_mul, ← hN] + exact hpack' + have hc : 9 * Fintype.card (A.CountBit r (B * P.count)) ≤ 2 ^ W := by + rw [Fintype.card_prod, Fintype.card_prod (Class r) A.I, Fintype.card_fin, + show Fintype.card (Class r) = r ^ 3 by simp [Class]; ring] + calc + _ ≤ 9 * (N * Fintype.card A.I * (3 * w)) := by gcongr + _ = (27 * Fintype.card A.I) * N * w := by ring + _ ≤ w * N * w := by gcongr; omega + _ ≤ _ := by rw [show w * N * w = N * w ^ 2 by ring]; exact (spaces 2 (by omega)).le + have hkeys := rough_keys hn (by omega) hp + have hkey := constantValue (9 * (6 + 2 * 2 ^ n)) (by omega) + refine ⟨hs, hu, ?_, hr, constantValue _ (by omega), hkeys.1.trans hkey, hc, + ?_, ?_, ?_, ?_, ?_, ?_, by omega, hpos⟩ + · refine ⟨by omega, by omega, hNV, hr', hp.trans hNV, ?_, by omega, ?_, ?_, hkeys.2.trans hkey, + by omega⟩ + · rw [mul_pow] + exact (Nat.mul_le_mul_left _ (hpow 5 (by omega))).trans (constantValue _ (by omega)) + · intro i z + have hz : A.cross z i ≤ PacketKernel.reserve A := PacketKernel.width_le A z i true + unfold Expansion.chargeBits PacketKernel.rowSize PacketKernel.prefixSize at * + omega + · exact hpack'.trans_le ((Nat.pow_le_pow_left hNV 3).trans + (Nat.pow_le_pow_right (by positivity) (by decide))) + · have hsl : 1 + packetRows P B ≤ (52 * C + 1) * N := + (Nat.le_mul_of_pos_left _ (by positivity)).trans hrow' + calc + _ ≤ 2 * ((packetRows P B + 1) * PacketKernel.rowSize A) := (PacketKernel.height_bounds A _).2 + _ ≤ 2 * (((52 * C + 1) * N) * PacketKernel.rowSize A) := by gcongr; omega + _ = N * (2 * PacketKernel.rowSize A * (52 * C + 1)) := by ring + _ ≤ N * w := by gcongr; omega + _ < _ := hcap + · rw [Fintype.card_prod, PacketKernel.card_spot] + calc + _ ≤ 3 * r ^ 2 * (PacketKernel.frameRate A * (1 + packetRows P B) * (1 + countWidth P B)) := + Nat.mul_le_mul_left _ (PacketKernel.frame_width A) + _ = 3 * PacketKernel.frameRate A * (r ^ 2 * (1 + packetRows P B)) * (1 + countWidth P B) + := by ring + _ ≤ 3 * PacketKernel.frameRate A * ((52 * C + 1) * N) * (5 * w) := by gcongr; omega + _ = (15 * PacketKernel.frameRate A * (52 * C + 1)) * N * w := by ring + _ ≤ w * N * w := by gcongr; omega + _ ≤ _ := by rw [show w * N * w = N * w ^ 2 by ring]; exact (spaces 2 (by omega)).le + · exact (Window.guess_bound P htot hl hr').trans (constantValue _ (by omega)) + · exact (M.data_le_budget F).trans (hM.trans (spaces Q (by omega)).le) + · have := S.literal + omega + · rw [mul_right_comm] + exact (Nat.mul_le_mul_left _ hrN).trans (constantValue _ (by omega)) + +theorem window (n h C Q : ℕ) (hn : 2 ≤ n) (hh : 0 < h) (hC : 4 ≤ C) + (A : Expansion F n h) : + ∀ᶠ w : ℕ in atTop, + let N := 2 ^ w + let r := 2 ^ (w / (16 * n)) + let d := 2 ^ (w / (32 * n)) + let l := N / 2048 + let B := (3 * r + d - 1) / d + ∀ fa : Machine.Ports N l l → Label n r, + let P := Format.prescribed d h (rounds n r h (12 * (C * N * d))) fa + ∀ M : Bank (Fin n), M.budget F ≤ N * w ^ Q → Nonempty (Controller P A hn M B) → + ∃ W, Window P A M B C Q w W := by + obtain ⟨δ, _, hs⟩ := Diagonal.scales C n h (Fintype.card A.I) hC hn + filter_upwards [hs, eventually_ge_atTop (threshold A C), eventually_ge_atTop (32 * n), + poly_bound (Q + 4) 1 (by decide)] with w hs hT hw he + intro N r d l B fa P M hM hS + obtain ⟨hd, hd', _⟩ := batch_floor w n + have sc : Scales C n h (Fintype.card A.I) N r l l d 0 B := + hs.2 d 0 hd hd' (by simp) + have hr : 3 ≤ r := by + have h₁ : 2 ≤ w / (16 * n) := (Nat.le_div_iff_mul_le (by omega)).mpr (by omega) + exact (show 3 ≤ 2 ^ 2 by decide).trans (Nat.pow_le_pow_right (by decide) h₁) + have hp : r ^ (16 * n) ≤ N := by + unfold r N + rw [← pow_mul] + exact Nat.pow_le_pow_right (by decide) (Nat.div_mul_le_self w (16 * n)) + have hw' : 2 ≤ w := by omega + let j := Nat.clog 2 (w ^ (Q + 4)) + have hj : j ≤ w := Nat.clog_le_of_le_pow (by simpa only [Nat.div_one] using he) + have hlog := Nat.clog_le_of_le_pow (Nat.lt_pow_succ_log_self (by decide : 1 < 2) (w ^ (Q + 4))).le + have hhigh : 2 ^ j ≤ w ^ (Q + 10) := calc + _ ≤ 2 ^ (Nat.log 2 (w ^ (Q + 4)) + 1) := Nat.pow_le_pow_right (by decide) hlog + _ ≤ w ^ (Q + 4) * w := by + rw [pow_succ] + exact Nat.mul_le_mul (Nat.pow_log_le_self _ (by positivity)) hw' + _ ≤ _ := by rw [← pow_succ]; exact Nat.pow_le_pow_right (by omega) (by omega) + refine ⟨w + j, finite_window P A hn M hS.some hh rfl hr hp (Nat.div_le_self _ _) + (Window.position_bound sc.padding) sc.copies hM hT (by omega) (by omega) ?_ ?_⟩ + · rw [pow_add]; exact Nat.mul_le_mul_left N hhigh + · rw [pow_add (2 : ℕ)]; exact Nat.mul_le_mul_left N (Nat.le_pow_clog (by decide) _) + +end MatrixMultiplicationAllFields.MatrixExponent.Processor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Alignment.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Alignment.lean new file mode 100644 index 0000000000..86da78cce2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Alignment.lean @@ -0,0 +1,1078 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Frame +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.SumOut +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Round + +/-! +# Named tensor requests + +Each slot belongs to one site. Relocating a presentation changes only +the owner map, retaining slot names and the underlying coefficients. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Classical in +/-- The data for the board construction, including `slot`, `[finiteSlot`, `owner`, `value`. -/ +structure Board (K S : Type) where + /-- The `Board` component of type `Type`. -/ + slot : Type + [finiteSlot : Fintype slot] + /-- The owner assigned to each element of type `slot → S`. -/ + owner : slot → S + /-- The evaluation map carried by `Board`, with type `(slot → Bool) → K`. -/ + value : (slot → Bool) → K + +attribute [instance] Board.finiteSlot + +namespace Board + +variable {K S T I : Type} (D : Board K S) + +open Classical in +/-- The subtype of `i : D.slot` satisfying `D.owner i = s`. -/ +abbrev localPort (s : S) := {i : D.slot // D.owner i = s} + +open Classical in +/-- Builds `Binary K S where port s` with the specified `port`, `value`. -/ +def binary : Binary K S where + port s := D.localPort s + value x := D.value (fun i => x (D.owner i) ⟨i, rfl⟩) + +open Classical in +/-- Builds `Board K T where slot` with the specified `slot`, `owner`, `value`. -/ +def move (f : S → T) : Board K T where + slot := D.slot + owner := f ∘ D.owner + value := D.value + +open Classical in +/-- Indexes the of binary by the coordinates of `Σ s, A.port s owner := Sigma.fst value x := +A.value (fun s i => x ⟨s, i⟩)`. -/ +def ofBinary [Fintype S] (A : Binary K S) : Board K S where + slot := Σ s, A.port s + owner := Sigma.fst + value x := A.value (fun s i => x ⟨s, i⟩) + +variable [Field K] + +open Classical in +/-- Uses `D.binary.tensor` as the representation. -/ +def tensor [Fintype S] [Nonempty S] : Spectral.Tensor K S := D.binary.tensor + +open Classical in +/-- Builds `Board K S where slot` with the specified `slot`, `owner`, `value`. -/ +def link (K : Type) [Field K] (a b : S) : Board K S where + slot := Bool + owner i := if i then b else a + value x := if x false = x true then 1 else 0 + +open Classical in +/-- Indexes the union by the coordinates of `Σ i, (A i).slot owner x := (A x.1).owner x.2 value +x := ∏ i, (A i).value (fun j => x ⟨i, j⟩)`. -/ +def union [Fintype I] (A : I → Board K S) : Board K S where + slot := Σ i, (A i).slot + owner x := (A x.1).owner x.2 + value x := ∏ i, (A i).value (fun j => x ⟨i, j⟩) + +open Classical in +/-- Indexes the orders by the coordinates of `union (fun i : Σ i, Fin (z i) => A i.1)`. -/ +def orders [Fintype I] (A : I → Board K S) (z : I → ℕ) : Board K S := + union (fun i : Σ i, Fin (z i) => A i.1) + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Local coordinates of orders indexed by kind and ordinal -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +variable {K S S' I I' : Type} + +/-- Indexes the pin by the coordinates of `Σ i, (T i).localPort s`. -/ +abbrev Pin (T : I → Board K S) (s : S) := Σ i, (T i).localPort s + +namespace Pin + +variable {T : I → Board K S} {T' : I' → Board K S'} {s : S} {s' : S'} + +/-- The condition `∀ i, z i.1 = z' (e i).1` on the specified data. -/ +def Same (e : Pin T s ≃ Pin T' s') (z : I → ℕ) (z' : I' → ℕ) : Prop := + ∀ i, z i.1 = z' (e i).1 + +variable [Field K] [Fintype I] [Fintype I'] {z : I → ℕ} {z' : I' → ℕ} + +/-- Uses `⟨⟨⟨i.1, j⟩, i.2.1⟩, i.2.2⟩` as the representation. -/ +def atCopy (i : Pin T s) (j : Fin (z i.1)) : (Board.orders T z).localPort s := + ⟨⟨⟨i.1, j⟩, i.2.1⟩, i.2.2⟩ + +/-- Reindexes `(Σ i : Pin T s, Fin (z i.1))` and `(Board.orders T z).localPort s where toFun x` +by an equivalence. -/ +def slots (T : I → Board K S) (s : S) (z : I → ℕ) : + (Σ i : Pin T s, Fin (z i.1)) ≃ (Board.orders T z).localPort s where + toFun x := atCopy x.1 x.2 + invFun p := ⟨⟨p.1.1.1, ⟨p.1.2, p.2⟩⟩, p.1.1.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +theorem exists_atCopy (p : (Board.orders T z).localPort s) : + ∃ (i : Pin T s) (j : Fin (z i.1)), atCopy i j = p := by + obtain ⟨⟨i, j⟩, h⟩ := (slots T s z).surjective p + exact ⟨i, j, h⟩ + +/-- Reindexes `(Board.orders T z).localPort s` and `(Board.orders T' z').localPort s'` by an +equivalence. -/ +def lift (e : Pin T s ≃ Pin T' s') (hz : Same e z z') : + (Board.orders T z).localPort s ≃ (Board.orders T' z').localPort s' := + (slots T s z).symm.trans ((Equiv.sigmaCongr e fun i => finCongr (hz i)).trans (slots T' s' z')) + +theorem lift_atCopy (e : Pin T s ≃ Pin T' s') (hz : Same e z z') + (i : Pin T s) (j : Fin (z i.1)) : + lift e hz (atCopy i j) = atCopy (e i) (Fin.cast (hz i) j) := rfl + +end Pin +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Fast local maps are stable under wiring, products, and contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Frame + +open Install Binary + +variable {K X Y Z U V I : Type} [Field K] [Fintype X] [Fintype Y] + [Fintype Z] [Fintype U] [Fintype V] [Fintype I] + +open Classical in +private theorem scale_ge (h : ℕ) : 2 ^ h ≤ scale h := + Nat.le_mul_of_pos_right _ (by positivity) + +open Classical in +omit [Fintype U] [Fintype V] [Fintype X] [Fintype Y] in +theorem Fast.pull [Finite U] [Finite V] [Finite X] [Finite Y] {f : Frame K X Y} + (hf : Fast f) (i : X → U) (j : Y → V) : + Fast (f.pull i j) := by + let : Fintype U := Fintype.ofFinite U + let : Fintype V := Fintype.ofFinite V + let : Fintype X := Fintype.ofFinite X + let : Fintype Y := Fintype.ofFinite Y + obtain ⟨c, hc⟩ := hf + refine ⟨Fintype.card (U ⊕ V) + 2 * Fintype.card (X ⊕ Y) + c, fun h => ?_⟩ + apply ((hc h).pull (Prod.map (Sum.map i j) id)).mono + simp only [Fintype.card_prod, Fintype.card_fin, add_mul, mul_assoc] + gcongr <;> exact scale_ge h + +open Classical in +omit [Fintype X] [Fintype Y] in +theorem Fast.product [Finite X] [Finite Y] {f : I → Frame K X Y} (hf : ∀ i, Fast (f i)) : + Fast (product f) := by + let : Fintype X := Fintype.ofFinite X + let : Fintype Y := Fintype.ofFinite Y + choose c hc using hf + let m := Finset.univ.sup c + refine ⟨Fintype.card (X ⊕ Y) + Fintype.card I * (5 * Fintype.card (X ⊕ Y) + m), fun h => ?_⟩ + have k (i) : Weight K (weight (f i) h) (m * scale h) := + (hc i h).mono (Nat.mul_le_mul_right _ (Finset.le_sup (Finset.mem_univ i))) + apply (Weight.finite_product _ k).mono + simp only [Fintype.card_prod, Fintype.card_fin, add_mul, mul_assoc] + gcongr <;> exact scale_ge h + +open Classical in +omit [Fintype X] [Fintype Y] in +theorem Fast.mul [Finite X] [Finite Y] {f g : Frame K X Y} (hf : Fast f) (hg : Fast g) : + Fast (fun h x y => f h x y * g h x y) := by + let : Fintype X := Fintype.ofFinite X + let : Fintype Y := Fintype.ofFinite Y + obtain ⟨c, hc⟩ := hf + obtain ⟨d, hd⟩ := hg + refine ⟨5 * Fintype.card (X ⊕ Y) + c + d, fun h => ?_⟩ + apply ((hc h).mul (hd h)).mono + simp only [Fintype.card_prod, Fintype.card_fin, add_mul, mul_assoc] + gcongr + exact scale_ge h + +open Classical in +omit [Fintype X] [Fintype Z] in +theorem Fast.compose [Finite X] [Finite Z] {f : Frame K X Y} {g : Frame K Y Z} + (hf : Fast f) (hg : Fast g) : + Fast (f.compose g) := by + let : Fintype X := Fintype.ofFinite X + let : Fintype Z := Fintype.ofFinite Z + obtain ⟨c, hc⟩ := hf + obtain ⟨d, hd⟩ := hg + refine ⟨10 * Fintype.card X + 12 * Fintype.card Y + 10 * Fintype.card Z + c + d, fun h => ?_⟩ + let N := Fin (2 ^ h) + let i : (X ⊕ Y) × N → (X ⊕ Z) × N ⊕ Y × N + | (.inl x, k) => .inl (.inl x, k) + | (.inr y, k) => .inr (y, k) + let j : (Y ⊕ Z) × N → (X ⊕ Z) × N ⊕ Y × N + | (.inl y, k) => .inr (y, k) + | (.inr z, k) => .inl (.inr z, k) + have H := (((hc h).pull i).mul ((hd h).pull j)).sum_out + let : DecidableEq (Y × N) := Classical.decEq _ + have e (x : (X ⊕ Z) × N → Bool) : + (∑ y : Y × N → Bool, weight f h (Sum.elim x y ∘ i) * weight g h (Sum.elim x y ∘ j)) = + weight (f.compose g) h x := + (Equiv.curry Y N Bool).sum_comp (fun y => + f h (fun j k => x (.inl j, k)) y * g h y (fun j k => x (.inr j, k))) + rw [← funext e] + apply H.mono + simp only [N, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + nlinarith only [Nat.mul_le_mul_left (10 * Fintype.card X + 12 * Fintype.card Y + + 10 * Fintype.card Z) + (scale_ge h)] + +open Classical in +omit [Fintype X] [Fintype Y] in +theorem fast_diagonal [Finite X] [Finite Y] (k : (X → Bool) → (Y → Bool) → K) : + Fast (diagonal k) := by + let : Fintype X := Fintype.ofFinite X + let : Fintype Y := Fintype.ofFinite Y + let f (x : X ⊕ Y → Bool) := k (x ∘ Sum.inl) (x ∘ Sum.inr) + refine ⟨8 * 2 ^ Fintype.card (X ⊕ Y), fun h => ?_⟩ + apply (((Weight.dense K _ f).prod h).rename (Equiv.prodComm _ _)).mono + rw [mul_comm (2 ^ h)] + exact Nat.mul_le_mul_left _ (scale_ge h) + +open Classical in +theorem fast_keep (K X : Type) [Field K] [Finite X] : Fast (keep K X) := by + let : Fintype X := Fintype.ofFinite X + let k (x y : X → Bool) := if x = y then (1 : K) else 0 + suffices keep K X = diagonal k by rw [this]; exact fast_diagonal k + funext h x y + by_cases e : x = y + · simp [keep, diagonal, k, e] + rw [keep, ite_eq_right e] + obtain ⟨i, hi⟩ := Function.ne_iff.mp e + obtain ⟨j, hj⟩ := Function.ne_iff.mp hi + symm + apply Finset.prod_eq_zero (Finset.mem_univ j) + exact ite_eq_right (fun he => hj (congrFun he i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Frame +end + +/- +# Exact local expansions of named boards + +An expansion exposes every local matrix. Its equation sums first +over the common choice and then over all independent supply slots. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board + +variable {K S I : Type} [Field K] [Fintype S] + (D V : Board K S) + +open Classical in +/-- The product of `D.value (fun j => x j i)` indexed by `i : Fin (2 ^ h)`. -/ +def eval (h : ℕ) (x : Lines h D.slot) : K := + ∏ i : Fin (2 ^ h), D.value (fun j => x j i) + +open Classical in +/-- The value specified by `x ∘ Subtype.val`. -/ +def view {h : ℕ} (s : S) (x : Lines h D.slot) : Lines h (D.localPort s) := + x ∘ Subtype.val + +open Classical in +/-- Reindexes `Lines h D.slot` and `((s : S) → Lines h (D.localPort s)) where toFun x s` by an +equivalence. -/ +def fibers (h : ℕ) : Lines h D.slot ≃ ((s : S) → Lines h (D.localPort s)) where + toFun x s := D.view s x + invFun x j := x (D.owner j) ⟨j, rfl⟩ + left_inv _ := rfl + right_inv x := by funext s ⟨j, hj⟩; subst s; rfl + +open Classical in +/-- The condition `∀ s, Frame K (D.localPort s) (V.localPort s)` on the specified data. -/ +abbrev Kernel := ∀ s, Frame K (D.localPort s) (V.localPort s) + +open Classical in +/-- The product of `k s h (D.view s x) (V.view s y)` indexed by `s`. -/ +def Kernel.prod (k : Kernel D V) (h : ℕ) (x : Lines h D.slot) (y : Lines h V.slot) := + ∏ s, k s h (D.view s x) (V.view s y) + +open Classical in +/-- The data for the expansion construction, including `kernel`, `fast`, `identity`. -/ +structure Expansion [Fintype I] (V : I → Board K S) where + /-- The `Expansion` component of type `∀ i, Kernel D (V i)`. -/ + kernel : ∀ i, Kernel D (V i) + fast : ∀ i s, Frame.Fast (kernel i s) + identity : ∀ h x, D.eval h x = ∑ i, ∑ y, Kernel.prod D (V i) (kernel i) h x y * (V i).eval h y + +open Classical in +/-- Reindexes `Lines h D.slot` and `(D.binary.batch (2 ^ h)).Assign where toFun x _ p` by an +equivalence. -/ +def binaryLines (h : ℕ) : Lines h D.slot ≃ (D.binary.batch (2 ^ h)).Assign where + toFun x _ p := x p.2.val p.1 + invFun y j i := y (D.owner j) (i, ⟨j, rfl⟩) + left_inv _ := rfl + right_inv y := by funext s ⟨i, j, hj⟩; subst s; rfl + +open Classical in +/-- Compile the selected scaler only for a fixed local shape. -/ +def realize [Fintype I] (V : I → Board K S) + (h : Binary.Scalable D.binary (fun i => (V i).binary)) : Expansion D V := by + let c := h.choose + let k (d : ℕ) := (h.choose_spec d).choose + have hk (d : ℕ) := (h.choose_spec d).choose_spec + let f (i : I) : Kernel D (V i) := fun s d x y => + k d i s (fun j => x j.2 j.1) (fun j => y j.2 j.1) + refine ⟨f, ?_, ?_⟩ + · intro i s + refine ⟨c, fun d => ?_⟩ + let e := (Equiv.prodSumDistrib (Fin (2 ^ d)) (D.localPort s) ((V i).localPort s)).symm.trans + (Equiv.prodComm _ _) + exact ((hk d).1 i s).rename e + · intro d x + have he := (hk d).2 (D.binaryLines d x) + refine he.trans (Finset.sum_congr rfl fun i _ => ?_) + unfold Binary.act + rw [← ((V i).binaryLines d).sum_comp] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board +end + +/- # Composing exact board expansions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board + +open Finset + +variable {K S I : Type} [Field K] [Fintype S] [Fintype I] + +section Sequential + +variable {D V W : Board K S} + +open Classical in +theorem compose_prod (f : Kernel D V) (g : Kernel V W) (h : ℕ) + (x : Lines h D.slot) (y : Lines h W.slot) : + Kernel.prod D W (fun s => Frame.compose (f s) (g s)) h x y = + ∑ z : Lines h V.slot, Kernel.prod D V f h x z * Kernel.prod V W g h z y := by + let L (s : S) (v : Lines h (V.localPort s)) := f s h (D.view s x) v * g s h v (W.view s y) + have eq : Kernel.prod D W (fun s => Frame.compose (f s) (g s)) h x y = ∏ s, ∑ v, L s v := by + apply prod_congr rfl + intro s _ + exact sum_congr (by ext; simp) fun _ _ => rfl + rw [eq, Fintype.prod_sum, ← (V.fibers h).sum_comp] + unfold Kernel.prod L + exact sum_congr rfl fun _ _ => prod_mul_distrib + +variable {J : I → Type} [∀ i, Fintype (J i)] + {P : I → Board K S} {Q : ∀ i, J i → Board K S} + +open Classical in +/-- Builds `Expansion D (fun j : Σ i, J i => Q j.1 j.2) where kernel j s` with the specified +`kernel`, `fast`, `identity`. -/ +def Expansion.comp (a : Expansion D P) (b : ∀ i, Expansion (P i) (Q i)) : + Expansion D (fun j : Σ i, J i => Q j.1 j.2) where + kernel j s := Frame.compose (a.kernel j.1 s) ((b j.1).kernel j.2 s) + fast j s := (a.fast j.1 s).compose ((b j.1).fast j.2 s) + identity h x := by + rw [a.identity, Fintype.sum_sigma] + apply sum_congr rfl + intro i _ + simp only [compose_prod, sum_mul, (b i).identity, mul_sum, mul_assoc] + rw [sum_comm] + exact sum_congr rfl fun j _ => sum_comm + +end Sequential + +section Parallel + +variable {A : I → Type} [∀ i, Fintype (A i)] + (D : I → Board K S) + +open Classical in +/-- Uses `⟨⟨i, j.1⟩, j.2⟩` as the representation. -/ +def component (s : S) (i : I) (j : (D i).localPort s) : (union D).localPort s := + ⟨⟨i, j.1⟩, j.2⟩ + +open Classical in +/-- Reindexes `Lines h (union D).slot` and `(∀ i, Lines h (D i).slot) where toFun x i j` by an +equivalence. -/ +def parts (h : ℕ) : Lines h (union D).slot ≃ (∀ i, Lines h (D i).slot) where + toFun x i j := x ⟨i, j⟩ + invFun x j := x j.1 j.2 + left_inv _ := rfl + right_inv _ := rfl + +omit [Fintype S] in +open Classical in +theorem eval_union (h : ℕ) (x : Lines h (union D).slot) : + (union D).eval h x = ∏ i, (D i).eval h (parts D h x i) := + prod_comm + +variable {D} {V : ∀ i, A i → Board K S} (a : ∀ i, Expansion (D i) (V i)) + +open Classical in +/-- Builds `Expansion (union D) (fun c : ∀ i, A i => union fun i => V i (c i)) where kernel c s` +with the specified `kernel`, `fast`, `identity`. -/ +def Expansion.parallel [DecidableEq I] : + Expansion (union D) (fun c : ∀ i, A i => union fun i => V i (c i)) where + kernel c s := Frame.product fun i => Frame.pull ((a i).kernel (c i) s) + (component D s i) (component (fun i => V i (c i)) s i) + fast c s := Frame.Fast.product (fun i => ((a i).fast (c i) s).pull _ _) + identity h x := by + rw [eval_union] + simp_rw [(a _).identity] + rw [Fintype.prod_sum] + apply sum_congr rfl + intro c _ + rw [Fintype.prod_sum, ← (parts (fun i => V i (c i)) h).sum_comp] + apply sum_congr rfl + intro y _ + rw [prod_mul_distrib, eval_union] + apply congrArg₂ (· * ·) _ rfl + unfold Kernel.prod Frame.product + exact prod_comm + +end Parallel +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board +end + +/- +# Port bijections for inventories of boards + +These bijections preserve the owner of every bit and the entire tensor +on those bits. They do not introduce local linear maps. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board + +open Routing + +variable {K S I J : Type} + +/-- Change only the names of the bit positions. -/ +structure Rename (D V : Board K S) where + /-- The equivalence reindexing the data of type `D.slot ≃ V.slot`. -/ + eqv : D.slot ≃ V.slot + owner_eq : ∀ i, V.owner (eqv i) = D.owner i + value_eq : ∀ x, D.value (x ∘ eqv) = V.value x + +/-- Indexes the join by the coordinates of `D.slot ⊕ V.slot owner := Sum.elim D.owner V.owner +value x := D.value (x ∘ Sum.inl) * V.value (x ∘ Sum.inr)`. -/ +def join [Field K] (D V : Board K S) : Board K S where + slot := D.slot ⊕ V.slot + owner := Sum.elim D.owner V.owner + value x := D.value (x ∘ Sum.inl) * V.value (x ∘ Sum.inr) + +namespace Rename + +variable {D V W X : Board K S} + +/-- Uses `⟨.refl _, fun _ => rfl, fun _ => rfl⟩` as the representation. -/ +def refl (D : Board K S) : Rename D D := ⟨.refl _, fun _ => rfl, fun _ => rfl⟩ + +/-- Builds `Rename D W where eqv` with the specified `eqv`, `owner_eq`, `value_eq`. -/ +def trans (h : Rename D V) (k : Rename V W) : Rename D W where + eqv := h.eqv.trans k.eqv + owner_eq i := (k.owner_eq _).trans (h.owner_eq i) + value_eq x := (h.value_eq (x ∘ k.eqv)).trans (k.value_eq x) + +/-- Builds `Rename V D where eqv` with the specified `eqv`, `owner_eq`, `value_eq`. -/ +def symm (h : Rename D V) : Rename V D where + eqv := h.eqv.symm + owner_eq i := by rw [← h.owner_eq, Equiv.apply_symm_apply] + value_eq x := by rw [← h.value_eq]; simp [Function.comp_def] + +variable [Field K] + +/-- Builds `Rename (D.join W) (V.join X) where eqv` with the specified `eqv`, `owner_eq`, +`rintro`. -/ +def join (h : Rename D V) (k : Rename W X) : Rename (D.join W) (V.join X) where + eqv := h.eqv.sumCongr k.eqv + owner_eq := by + rintro (i | j) + · exact h.owner_eq i + · exact k.owner_eq j + value_eq x := congrArg₂ (· * ·) (h.value_eq (x ∘ Sum.inl)) (k.value_eq (x ∘ Sum.inr)) + +/-- Reindexes each fiber of the dependent pair. -/ +def union [Fintype I] {D V : I → Board K S} (h : ∀ i, Rename (D i) (V i)) : + Rename (Board.union D) (Board.union V) where + eqv := Equiv.sigmaCongrRight (fun i => (h i).eqv) + owner_eq i := (h i.1).owner_eq i.2 + value_eq x := Finset.prod_congr rfl (fun i _ => (h i).value_eq (fun j => x ⟨i, j⟩)) + +end Rename + +variable [Field K] [Fintype I] [Fintype J] + +/-- Builds `Rename (union (D ∘ e)) (union D) where eqv` with the specified `eqv`, `owner_eq`, +`value_eq`. -/ +def unionEquiv (D : J → Board K S) (e : I ≃ J) : Rename (union (D ∘ e)) (union D) where + eqv := Equiv.sigmaCongrLeft (β := fun i => (D i).slot) e + owner_eq _ := rfl + value_eq x := e.prod_comp (fun i => (D i).value (fun j => x ⟨i, j⟩)) + +/-- Builds `Rename (union (fun j : Σ i, P i => D j.1 j.2)) (union (fun i => union (D i))) where +eqv` with the specified `eqv`, `owner_eq`, `value_eq`. -/ +def unionSigma {P : I → Type} [∀ i, Fintype (P i)] (D : (i : I) → P i → Board K S) : + Rename (union (fun j : Σ i, P i => D j.1 j.2)) (union (fun i => union (D i))) where + eqv := Equiv.sigmaAssoc (fun i j => (D i j).slot) + owner_eq _ := rfl + value_eq x := Fintype.prod_sigma (fun j : Σ i, P i => + (D j.1 j.2).value (fun k => x ⟨j.1, ⟨j.2, k⟩⟩)) + +/-- The equivalence obtained by `Equiv.sumSigmaDistrib (fun i => (D i).slot) owner_eq := by +rintro ⟨i | j, k⟩ <;> rfl value_eq x := Fintype.prod_sum_type _`. -/ +def unionSplit (D : I ⊕ J → Board K S) : + Rename (union D) ((union (D ∘ Sum.inl)).join (union (D ∘ Sum.inr))) where + eqv := Equiv.sumSigmaDistrib (fun i => (D i).slot) + owner_eq := by rintro ⟨i | j, k⟩ <;> rfl + value_eq x := Fintype.prod_sum_type _ + +/-- Builds `Rename (union (fun i => (D i).join (V i))) ((union D).join (union V)) where eqv` +with the specified `Rename`, `owner_eq`, `value_eq`. -/ +def unionJoin (D V : I → Board K S) : + Rename (union (fun i => (D i).join (V i))) ((union D).join (union V)) where + eqv := Equiv.sigmaSumDistrib (fun i => (D i).slot) (fun i => (V i).slot) + owner_eq := by rintro ⟨i, j | k⟩ <;> rfl + value_eq _ := Finset.prod_mul_distrib + +/-- Builds `Rename (union (fun i => union (D i))) (union (fun j => union (fun i => D i j))) +where eqv` with the specified `Rename`, `toFun`, `invFun`, `left_inv`. -/ +def unionSwap (D : I → J → Board K S) : + Rename (union (fun i => union (D i))) (union (fun j => union (fun i => D i j))) where + eqv := { + toFun := fun x => ⟨x.2.1, ⟨x.1, x.2.2⟩⟩ + invFun := fun x => ⟨x.2.1, ⟨x.1, x.2.2⟩⟩ + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + owner_eq _ := rfl + value_eq _ := Finset.prod_comm + +/-- The indexed operation `unionSigma (fun i (_ : Fin (z i)) => T i)`. -/ +def ordersUnion (T : I → Board K S) (z : I → ℕ) : + Rename (orders T z) (union (fun i => union (fun _ : Fin (z i) => T i))) := + unionSigma (fun i (_ : Fin (z i)) => T i) + +/-- The orders add of type `Rename (orders T (fun i => x i + y i)) ((orders T x).join (orders T +y))`, constructed using `T i`. -/ +def ordersAdd (T : I → Board K S) (x y : I → ℕ) : + Rename (orders T (fun i => x i + y i)) ((orders T x).join (orders T y)) := by + let D (i : I) (_ : Fin (x i) ⊕ Fin (y i)) := T i + let e i := (unionEquiv (D i) finSumFinEquiv.symm).trans (unionSplit (D i)) + exact (ordersUnion T _).trans <| (Rename.union e).trans <| + (unionJoin _ _).trans ((ordersUnion T x).symm.join (ordersUnion T y).symm) + +/-- The orders sum of type `Rename (orders T (fun i => ∑ j, z j i)) (union (fun j => orders T (z +j)))`, constructed using `(unionEquiv (fun _ => T i) (e i)).trans`. -/ +def ordersSum (T : I → Board K S) (z : J → I → ℕ) + (e : ∀ i, Fin (∑ j, z j i) ≃ Σ j, Fin (z j i)) : + Rename (orders T (fun i => ∑ j, z j i)) (union (fun j => orders T (z j))) := by + let r (i : I) := (unionEquiv (fun _ => T i) (e i)).trans + (unionSigma (fun j (_ : Fin (z j i)) => T i)) + exact (ordersUnion T _).trans <| (Rename.union r).trans <| + (unionSwap _).trans (Rename.union fun j => (ordersUnion T (z j)).symm) + +/-- The value specified by `(ordersUnion T z).trans <| (unionSplit _).trans ((ordersUnion _ +_).symm.join (ordersUnion _ _).symm)`. -/ +def ordersSplit (T : I ⊕ J → Board K S) (z : I ⊕ J → ℕ) : + Rename (orders T z) + ((orders (T ∘ Sum.inl) (z ∘ Sum.inl)).join (orders (T ∘ Sum.inr) (z ∘ Sum.inr))) := + (ordersUnion T z).trans <| (unionSplit _).trans + ((ordersUnion _ _).symm.join (ordersUnion _ _).symm) + +/-- Reindexes `(Σ j, Fin (z j))` and `Σ i, Fin (Stock.collect g z i)` by an equivalence. -/ +def collectEquiv [DecidableEq I] (g : J → I) (hg : Function.Injective g) (z : J → ℕ) : + (Σ j, Fin (z j)) ≃ Σ i, Fin (Stock.collect g z i) := by + let f (p : Σ j, Fin (z j)) : Σ i, Fin (Stock.collect g z i) := + ⟨g p.1, Fin.cast (Stock.collect_inj hg z p.1).symm p.2⟩ + refine Equiv.ofBijective f ⟨?_, ?_⟩ + · rintro ⟨j, a⟩ ⟨k, b⟩ h + have hj : j = k := hg (congrArg Sigma.fst h) + subst k + have hab : a = b := Fin.ext (congrArg (fun p => p.2.val) h) + rw [hab] + · rintro ⟨i, a⟩ + obtain ⟨j, rfl, _⟩ := Stock.collect_nonzero (Nat.ne_of_gt a.pos) + exact ⟨⟨j, Fin.cast (Stock.collect_inj hg z j) a⟩, rfl⟩ + +/-- Indexes the orders collect by the coordinates of `(unionEquiv (fun p : Σ i, Fin +(Stock.collect g z i) => T p.1) (collectEquiv g hg z)).symm`. -/ +def ordersCollect [DecidableEq I] (T : I → Board K S) (g : J → I) + (hg : Function.Injective g) (z : J → ℕ) : + Rename (orders T (Stock.collect g z)) (orders (T ∘ g) z) := + (unionEquiv (fun p : Σ i, Fin (Stock.collect g z i) => T p.1) (collectEquiv g hg z)).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board +end + +/- # Relocation, reindexing, and unchanged slots in local expansions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board + +variable {K S T I : Type} {D D' : Board K S} {V V' : I → Board K S} + +open Classical in +/-- Evaluates `⟨e.eqv i, (e.owner_eq i).trans i.property⟩` at the input `i`. -/ +def Rename.local (e : Rename D D') (s : S) : D.localPort s → D'.localPort s := + fun i => ⟨e.eqv i, (e.owner_eq i).trans i.property⟩ + +variable [Field K] + +open Classical in +theorem Rename.eval_eq (e : Rename D D') (n : ℕ) (x : Lines n D'.slot) : + D.eval n (x ∘ e.eqv) = D'.eval n x := + Finset.prod_congr rfl fun i _ => e.value_eq (fun j => x j i) + +variable [Fintype S] [Fintype I] + +open Classical in +/-- Builds `Expansion D' V' where kernel i s` with the specified `Expansion`, `fast`, +`identity`. -/ +def Expansion.rename (h : Expansion D V) (e : Rename D D') (g : ∀ i, Rename (V i) (V' i)) : + Expansion D' V' where + kernel i s := (h.kernel i s).pull (e.local s) ((g i).local s) + fast i s := (h.fast i s).pull _ _ + identity n x := by + rw [← e.eval_eq, h.identity] + refine Finset.sum_congr rfl fun i _ => ?_ + rw [← ((g i).eqv.symm.arrowCongr (Equiv.refl (Fin (2 ^ n) → Bool))).sum_comp] + exact Finset.sum_congr rfl fun y _ => congrArg _ ((g i).eval_eq n y) + +open Classical in +/-- Evaluates `⟨i.val, (congrArg f i.property).trans s.property⟩` at the input `i`. -/ +def movePort (D : Board K S) (f : S → T) {t : T} (s : {s // f s = t}) : + D.localPort s → (D.move f).localPort t := + fun i => ⟨i.val, (congrArg f i.property).trans s.property⟩ + +open Classical in +/-- Builds `Expansion (D.move f) (fun i => (V i).move f) where kernel i t` with the specified +`Expansion`, `fast`, `identity`. -/ +def Expansion.place [Fintype T] (h : Expansion D V) (f : S → T) : + Expansion (D.move f) (fun i => (V i).move f) where + kernel i t := Frame.product fun s : {s // f s = t} => + (h.kernel i s).pull (D.movePort f s) ((V i).movePort f s) + fast i t := Frame.Fast.product fun s => (h.fast i s).pull _ _ + identity n x := by + refine (h.identity n x).trans (Finset.sum_congr rfl fun i _ => + Finset.sum_congr rfl fun y _ => ?_) + exact congrArg (· * (V i).eval n y) + (Fintype.prod_fiberwise f (fun s => h.kernel i s n (D.view s x) ((V i).view s y))).symm + +open Classical in +/-- Evaluates `⟨.inl i.val, i.property⟩` at the input `i`. -/ +def joinLeft (D X : Board K S) (s : S) : D.localPort s → (D.join X).localPort s := + fun i => ⟨.inl i.val, i.property⟩ + +open Classical in +/-- Evaluates `⟨.inr i.val, i.property⟩` at the input `i`. -/ +def joinRight (D X : Board K S) (s : S) : X.localPort s → (D.join X).localPort s := + fun i => ⟨.inr i.val, i.property⟩ + +omit [Fintype S] in +open Classical in +theorem eval_join (D X : Board K S) (n : ℕ) (x : Lines n (D.join X).slot) : + (D.join X).eval n x = D.eval n (x ∘ Sum.inl) * X.eval n (x ∘ Sum.inr) := + Finset.prod_mul_distrib + +open Classical in +private theorem delta (X : Board K S) (n : ℕ) (x y : Lines n X.slot) : + (∏ s, Frame.keep K (X.localPort s) n (X.view s x) (X.view s y)) = + if x = y then 1 else 0 := by + by_cases e : x = y + · simp [Frame.keep, e] + obtain ⟨i, hi⟩ := Function.ne_iff.mp e + rw [ite_eq_right e] + apply Finset.prod_eq_zero (Finset.mem_univ (X.owner i)) + exact ite_eq_right (fun h => hi (congrFun h ⟨i, rfl⟩)) + +open Classical in +/-- The keep of type `Kernel (D.join X) (D'.join X)` for the given inputs. -/ +def Kernel.keep (k : Kernel D D') (X : Board K S) : Kernel (D.join X) (D'.join X) := + fun s n x y => k s n (x ∘ D.joinLeft X s) (y ∘ D'.joinLeft X s) * + Frame.keep K (X.localPort s) n (x ∘ D.joinRight X s) (y ∘ D'.joinRight X s) + +open Classical in +theorem Kernel.keep_prod (k : Kernel D D') (X : Board K S) + (n : ℕ) (x : Lines n (D.join X).slot) (y : Lines n D'.slot) (z : Lines n X.slot) : + Kernel.prod _ _ (k.keep X) n x (Sum.elim y z) = + Kernel.prod D D' k n (x ∘ Sum.inl) y * (if x ∘ Sum.inr = z then 1 else 0) := by + rw [← delta X] + exact Finset.prod_mul_distrib + +open Classical in +/-- Builds `Expansion (D.join X) (fun i => (V i).join X) where kernel i` with the specified +`Expansion`, `fast`, `identity`. -/ +def Expansion.keep (h : Expansion D V) (X : Board K S) : + Expansion (D.join X) (fun i => (V i).join X) where + kernel i := (h.kernel i).keep X + fast i s := ((h.fast i s).pull (D.joinLeft X s) ((V i).joinLeft X s)).mul + ((Frame.fast_keep K (X.localPort s)).pull (D.joinRight X s) ((V i).joinRight X s)) + identity n x := by + rw [eval_join, h.identity, Finset.sum_mul] + refine Finset.sum_congr rfl fun i _ => ?_ + let e : Lines n (V i).slot × Lines n X.slot ≃ Lines n ((V i).join X).slot := + (Equiv.sumArrowEquivProdArrow _ _ _).symm + rw [← e.sum_comp, Fintype.sum_prod_type, Finset.sum_mul] + refine Finset.sum_congr rfl fun y _ => ?_ + symm + calc + _ = ∑ z : Lines n X.slot, + (Kernel.prod D (V i) (h.kernel i) n (x ∘ Sum.inl) y * + (if x ∘ Sum.inr = z then 1 else 0)) * ((V i).eval n y * X.eval n z) := + Finset.sum_congr rfl fun z _ => congrArg₂ (· * ·) + ((h.kernel i).keep_prod X n x y z) (eval_join (V i) X n (Sum.elim y z)) + _ = _ := by simp [mul_ite, ite_mul, mul_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board +end + +/- # Local maps in different port coordinates -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +namespace Frame + +variable {K X X' Y Y' Z Z' U U' V V' : Type} + +open Classical in +/-- The condition `∀ h x y, f h (x ∘ e) (y ∘ g) = f' h x y` on the specified data. -/ +def Rel (e : X ≃ X') (g : Y ≃ Y') (f : Frame K X Y) (f' : Frame K X' Y') : Prop := + ∀ h x y, f h (x ∘ e) (y ∘ g) = f' h x y + +variable {e : X ≃ X'} {g : Y ≃ Y'} {f : Frame K X Y} {f' : Frame K X' Y'} + +open Classical in +theorem Rel.refl (f : Frame K X Y) : Rel (.refl X) (.refl Y) f f := fun _ _ _ => rfl + +open Classical in +theorem Rel.symm (hf : Rel e g f f') : Rel e.symm g.symm f' f := by + intro h x y + rw [← hf] + simp only [Function.comp_def, Equiv.symm_apply_apply] + +open Classical in +theorem Rel.trans {a : X' ≃ U} {b : Y' ≃ V} {l : Frame K U V} + (hf : Rel e g f f') (hl : Rel a b f' l) : Rel (e.trans a) (g.trans b) f l := + fun h x y => (hf h (x ∘ a) (y ∘ b)).trans (hl h x y) + +open Classical in +theorem Rel.pull (hf : Rel e g f f') {i : X → U} {j : Y → V} {i' : X' → U'} {j' : Y' → V'} + {a : U ≃ U'} {b : V ≃ V'} (hi : ∀ x, a (i x) = i' (e x)) (hj : ∀ y, b (j y) = j' (g y)) : + Rel a b (f.pull i j) (f'.pull i' j') := by + intro h x y + unfold Frame.pull + rw [← hf] + simp only [Function.comp_def, hi, hj] + +variable [Field K] + +open Classical in +theorem Rel.mul {k : Frame K X Y} {k' : Frame K X' Y'} + (hf : Rel e g f f') (hk : Rel e g k k') : + Rel e g (fun h x y => f h x y * k h x y) (fun h x y => f' h x y * k' h x y) := + fun h x y => congrArg₂ (· * ·) (hf h x y) (hk h x y) + +open Classical in +theorem Rel.product {I J : Type} [Fintype I] [Fintype J] (i : I ≃ J) + {k : I → Frame K X Y} {l : J → Frame K X' Y'} (hk : ∀ j, Rel e g (k j) (l (i j))) : + Rel e g (product k) (product l) := by + intro h x y + unfold Frame.product + rw [← i.prod_comp (fun j => l j h x y)] + exact Finset.prod_congr rfl fun j _ => hk j h x y + +open Classical in +theorem Rel.compose [Fintype Y] [Fintype Y'] {a : Z ≃ Z'} {k : Frame K Y Z} {k' : Frame K Y' Z'} + (hf : Rel e g f f') (hk : Rel g a k k') : Rel e a (f.compose k) (f'.compose k') := by + intro h x z + unfold Frame.compose + rw [← (g.symm.arrowCongr (Equiv.refl (Fin (2 ^ h) → Bool))).sum_comp] + exact Finset.sum_congr rfl fun y _ => congrArg₂ (· * ·) (hf h x y) (hk h y z) + +open Classical in +theorem keep_rel (e : X ≃ X') : Rel e e (keep K X) (keep K X') := by + intro h x y + have he : x ∘ e = y ∘ e ↔ x = y := (e.symm.arrowCongr (Equiv.refl (Fin (2 ^ h) → + Bool))).injective.eq_iff + simp only [keep, he] + +end Frame + +namespace Board + +variable {K S S' : Type} [Field K] {D V W : Board K S} {D' V' W' : Board K S'} {s : S} {s' : S'} + +open Classical in +/-- Computes the split join by the application `Sum.elim (D.joinLeft V s) (D.joinRight V s)`. -/ +def splitJoin (D V : Board K S) (s : S) : + (D.join V).localPort s ≃ D.localPort s ⊕ V.localPort s where + toFun + | ⟨.inl i, h⟩ => .inl ⟨i, h⟩ + | ⟨.inr i, h⟩ => .inr ⟨i, h⟩ + invFun := Sum.elim (D.joinLeft V s) (D.joinRight V s) + left_inv := by rintro ⟨i|i, h⟩ <;> rfl + right_inv := by rintro (i|i) <;> rfl + +open Classical in +/-- Reindexes `(D.join V).localPort s` and `(D'.join V').localPort s'` by an equivalence. -/ +def joinPorts (e : D.localPort s ≃ D'.localPort s') (g : V.localPort s ≃ V'.localPort s') : + (D.join V).localPort s ≃ (D'.join V').localPort s' := + (splitJoin D V s).trans ((e.sumCongr g).trans (splitJoin D' V' s').symm) + +open Classical in +@[simp] theorem joinPorts_left (e : D.localPort s ≃ D'.localPort s') + (g : V.localPort s ≃ V'.localPort s') (i : D.localPort s) : + joinPorts e g (D.joinLeft V s i) = D'.joinLeft V' s' (e i) := rfl + +open Classical in +@[simp] theorem joinPorts_right (e : D.localPort s ≃ D'.localPort s') + (g : V.localPort s ≃ V'.localPort s') (i : V.localPort s) : + joinPorts e g (D.joinRight V s i) = D'.joinRight V' s' (g i) := rfl + +open Classical in +theorem Kernel.keep_rel {k : Kernel D V} {k' : Kernel D' V'} + {e : D.localPort s ≃ D'.localPort s'} {g : V.localPort s ≃ V'.localPort s'} + (hk : Frame.Rel e g (k s) (k' s')) (w : W.localPort s ≃ W'.localPort s') : + Frame.Rel (joinPorts e w) (joinPorts g w) (k.keep W s) (k'.keep W' s') := + (hk.pull (joinPorts_left e w) (joinPorts_left g w)).mul + ((Frame.keep_rel w).pull (joinPorts_right e w) (joinPorts_right g w)) + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +section +/- # Assigning stock positions to concurrent interventions -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing + +/-- The control can choose its own local ordering of the centers. -/ +structure Allocation {I E J : Type} [Fintype J] [DecidableEq J] (q : J → Intervention I E) where + /-- Reindexes the data using `∀ i, Fin ((Intervention.parallel q).take i) ≃ Σ j, Fin ((q + j).take i)`. -/ + take : ∀ i, Fin ((Intervention.parallel q).take i) ≃ Σ j, Fin ((q j).take i) + /-- Reindexes the data using `∀ (h : (j : J) → (q j).choice) i, Fin ((Intervention.parallel + q).put h i) ≃ Σ j, Fin ((q j).put (h j) i)`. -/ + put : ∀ (h : (j : J) → (q j).choice) i, + Fin ((Intervention.parallel q).put h i) ≃ Σ j, Fin ((q j).put (h j) i) + /-- Reindexes the data using `∀ (h : (j : J) → (q j).choice) e, Fin ((Intervention.parallel + q).core h e) ≃ Σ j, Fin ((q j).core (h j) e)`. -/ + core : ∀ (h : (j : J) → (q j).choice) e, + Fin ((Intervention.parallel q).core h e) ≃ Σ j, Fin ((q j).core (h j) e) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Implementing a simultaneous stock intervention by local matrix kernels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Routing Board + +variable {K S I E J : Type} [Field K] + +/-- Builds `Rename ((D.join V).join W) ((W.join D).join V) where eqv` with the specified `eqv`, +`owner_eq`, `value_eq`. -/ +def Board.rotate (D V W : Board K S) : Rename ((D.join V).join W) ((W.join D).join V) where + eqv := (Equiv.sumComm _ _).trans (Equiv.sumAssoc _ _ _).symm + owner_eq := by rintro ((x|x)|x) <;> rfl + value_eq x := by + change (D.value (fun j => x (.inl (.inr j))) * V.value (fun j => x (.inr j))) * + W.value (fun j => x (.inl (.inl j))) = + (W.value (fun j => x (.inl (.inl j))) * D.value (fun j => x (.inl (.inr j)))) * + V.value (fun j => x (.inr j)) + ac_rfl + +/-- The equivalence obtained by `Equiv.sumComm _ _ owner_eq := by rintro (x|x) <;> rfl value_eq +_ := mul_comm _ _`. -/ +def Board.swap (D V : Board K S) : Rename (D.join V) (V.join D) where + eqv := Equiv.sumComm _ _ + owner_eq := by rintro (x|x) <;> rfl + value_eq _ := mul_comm _ _ + +variable [Fintype S] [Fintype I] [Fintype E] (T : I → Board K S) (V : E → Board K S) + +/-- The indexed operation `Expansion (orders T q.take) (fun u => (orders T (q.put u)).join +(orders V (q.core u)))`. -/ +abbrev Executes (q : Intervention I E) := + Expansion (orders T q.take) (fun u => (orders T (q.put u)).join (orders V (q.core u))) + +/-- Indexes the orders eq by the coordinates of `unionEquiv (fun j : Σ i, Fin (y i) => T j.1) +(Equiv.sigmaCongrRight fun i => finCongr (congrFun h i))`. -/ +def Board.ordersEq {x y : I → ℕ} (h : x = y) : Rename (orders T x) (orders T y) := + unionEquiv (fun j : Σ i, Fin (y i) => T j.1) (Equiv.sigmaCongrRight fun i + => finCongr (congrFun h i)) + +variable {T V} + +/-- The parallel of type `Executes T V (Intervention.parallel q)` for the given inputs. -/ +def Executes.parallel [Fintype J] [DecidableEq J] {q : J → Intervention I E} + (e : Allocation q) (r : ∀ j, Executes T V (q j)) : Executes T V (Intervention.parallel q) := + (Expansion.parallel r).rename (ordersSum T _ e.take).symm fun u => + (unionJoin _ _).trans ((ordersSum T _ (e.put u)).symm.join (ordersSum V _ (e.core u)).symm) + +/-- The take step of type `Expansion (orders T z) (fun j => (orders T (q.next z j)).join (orders +V (q.core j)))`, constructed using `fun i => z i - q.take i`. -/ +def Executes.takeStep {q : Intervention I E} (r : Executes T V q) (z : I → ℕ) (hz : q.take ≤ z) : + Expansion (orders T z) (fun j => (orders T (q.next z j)).join (orders V (q.core j))) := by + let w := fun i => z i - q.take i + have he : (fun i => q.take i + w i) = z := by + funext i + exact Nat.add_sub_of_le (hz i) + exact (r.keep (orders T w)).rename + ((ordersAdd T q.take w).symm.trans (ordersEq T he)) fun j => + (rotate _ _ _).trans ((ordersAdd T w (q.put j)).symm.join (.refl _)) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Coordinates of the inventory bijections + +Slots within each copy are unchanged. For a sum of inventories, +the copy ordinal is determined by the supplied allocation. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board + +variable {K S I J : Type} [Field K] [Fintype I] [Fintype J] + +private theorem inverse_slot {X Y Z : Type} (e : X ≃ Y) (j : Y) (s : Z) : + (Equiv.sigmaCongrLeft (β := fun _ => Z) e).symm ⟨j, s⟩ = ⟨e.symm j, s⟩ := by + apply (Equiv.sigmaCongrLeft (β := fun _ => Z) e).injective + rw [Equiv.apply_symm_apply] + change (⟨j, s⟩ : Σ _ : Y, Z) = ⟨e (e.symm j), s⟩ + rw [Equiv.apply_symm_apply] + +private def embedOrdinal (T : I → Board K S) (a : I → ℕ) (i : I) + (p : Σ _ : Fin (a i), (T i).slot) : (orders T a).slot := + ⟨⟨i, p.1⟩, p.2⟩ + +theorem orders_add_left (T : I → Board K S) (a b : I → ℕ) + (i : I) (r : Fin (a i)) (s : (T i).slot) : + (ordersAdd T a b).symm.eqv (.inl ⟨⟨i, r⟩, s⟩) = ⟨⟨i, Fin.castAdd (b i) r⟩, s⟩ := by + exact congrArg (embedOrdinal T (fun i => a i + b i) i) + (inverse_slot (finSumFinEquiv (m := a i) (n := b i)).symm (.inl r) s) + +theorem orders_add_right (T : I → Board K S) (a b : I → ℕ) + (i : I) (r : Fin (b i)) (s : (T i).slot) : + (ordersAdd T a b).symm.eqv (.inr ⟨⟨i, r⟩, s⟩) = ⟨⟨i, Fin.natAdd (a i) r⟩, s⟩ := by + exact congrArg (embedOrdinal T (fun i => a i + b i) i) + (inverse_slot (finSumFinEquiv (m := a i) (n := b i)).symm (.inr r) s) + +theorem orders_sum_slot (T : I → Board K S) (z : J → I → ℕ) + (e : ∀ i, Fin (∑ j, z j i) ≃ Σ j, Fin (z j i)) + (j : J) (i : I) (r : Fin (z j i)) (s : (T i).slot) : + (ordersSum T z e).symm.eqv ⟨j, ⟨⟨i, r⟩, s⟩⟩ = ⟨⟨i, (e i).symm ⟨j, r⟩⟩, s⟩ := by + exact congrArg (embedOrdinal T (fun i => ∑ j, z j i) i) (inverse_slot (e i) ⟨j, r⟩ s) + +theorem orders_split_left (T : I ⊕ J → Board K S) (z : I ⊕ J → ℕ) + (i : I) (r : Fin (z (.inl i))) (s : (T (.inl i)).slot) : + (ordersSplit T z).symm.eqv (.inl ⟨⟨i, r⟩, s⟩) = ⟨⟨.inl i, r⟩, s⟩ := rfl + +theorem orders_split_right (T : I ⊕ J → Board K S) (z : I ⊕ J → ℕ) + (j : J) (r : Fin (z (.inr j))) (s : (T (.inr j)).slot) : + (ordersSplit T z).symm.eqv (.inr ⟨⟨j, r⟩, s⟩) = ⟨⟨.inr j, r⟩, s⟩ := rfl + +theorem orders_collect_slot [DecidableEq I] (T : I → Board K S) (g : J → I) + (hg : Function.Injective g) (z : J → ℕ) (j : J) (r : Fin (z j)) (s : (T (g j)).slot) : + (ordersCollect T g hg z).symm.eqv ⟨⟨j, r⟩, s⟩ = + ⟨⟨g j, Fin.cast (Routing.Stock.collect_inj hg z j).symm r⟩, s⟩ := rfl + +theorem orders_eq_slot (T : I → Board K S) {a b : I → ℕ} (h : a = b) + (i : I) (r : Fin (a i)) (s : (T i).slot) : + (ordersEq T h).eqv ⟨⟨i, r⟩, s⟩ = ⟨⟨i, Fin.cast (congrFun h i) r⟩, s⟩ := rfl + +theorem union_join_left (T V : I → Board K S) (i : I) (s : (T i).slot) : + (unionJoin T V).eqv ⟨i, .inl s⟩ = .inl ⟨i, s⟩ := rfl + +theorem union_join_right (T V : I → Board K S) (i : I) (s : (V i).slot) : + (unionJoin T V).eqv ⟨i, .inr s⟩ = .inr ⟨i, s⟩ := rfl + +variable (D V W : Board K S) + +theorem swap_left (s : D.slot) : (swap D V).eqv (.inl s) = .inr s := rfl +theorem swap_right (s : V.slot) : (swap D V).eqv (.inr s) = .inl s := rfl + +theorem rotate_left (s : D.slot) : (rotate D V W).eqv (.inl (.inl s)) = .inl (.inr s) := rfl +theorem rotate_middle (s : V.slot) : (rotate D V W).eqv (.inl (.inr s)) = .inr s := rfl +theorem rotate_right (s : W.slot) : (rotate D V W).eqv (.inr s) = .inl (.inl s) := rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board +end + +/- # Tracking copy ordinals across concurrent expansions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Routing Board Finset + +variable {K S S' I I' E J J' : Type} [Field K] [Fintype I] [Fintype I'] [Fintype E] + [Fintype J] [Fintype J'] {T : I → Board K S} {T' : I' → Board K S'} + {V : E → Board K S} {s : S} {s' : S'} {u : Finset J} {u' : Finset J'} + +/-- A move is invisible at a site if it uses no incident slots and its local scalar is one. -/ +structure Silent [Fintype S] (s : S) {q : Intervention I E} (r : Executes T V q) + (t : q.choice) : Prop where + take : ∀ i : Pin T s, q.take i.1 = 0 + put : ∀ i : Pin T s, q.put t i.1 = 0 + core : ∀ i : Pin V s, q.core t i.1 = 0 + one : ∀ h x y, r.kernel t s h x y = 1 + +namespace Pin + +/-- The condition `∀ i, Fin (∑ j, z j i) ≃ Σ j, Fin (z j i)` on the specified data. -/ +abbrev Assignment (z : J → I → ℕ) := ∀ i, Fin (∑ j, z j i) ≃ Σ j, Fin (z j i) + +variable {z : J → I → ℕ} {z' : J' → I' → ℕ} + +/-- Corresponding copies are assigned the same ordinal in the aggregate stock. -/ +def Align (e : Pin T s ≃ Pin T' s') (g : ↥u ≃ ↥u') (a : Assignment z) (b : Assignment z') : + Prop := + ∀ (j : ↥u) (i : Pin T s) (r : Fin (z j i.1)) (r' : Fin (z' (g j) (e i).1)), + r.val = r'.val → ((a i.1).symm ⟨j, r⟩).val = ((b (e i).1).symm ⟨g j, r'⟩).val + +/-- The indexed operation `(ordersSum T z a).symm.local s ∘ component (fun j => orders T (z j)) +s j`. -/ +def assign (T : I → Board K S) (a : Assignment z) (j : J) (s : S) : + (orders T (z j)).localPort s → (orders T (fun i => ∑ j, z j i)).localPort s := + (ordersSum T z a).symm.local s ∘ component (fun j => orders T (z j)) s j + +theorem assign_atCopy (a : Assignment z) (j : J) (i : Pin T s) (r : Fin (z j i.1)) : + assign T a j s (atCopy i r) = atCopy i ((a i.1).symm ⟨j, r⟩) := + Subtype.ext (orders_sum_slot T z a j i.1 r i.2.val) + +theorem Align.assign {e : Pin T s ≃ Pin T' s'} {g : ↥u ≃ ↥u'} + {a : Assignment z} {b : Assignment z'} (h : Align e g a b) + (ht : Same e (fun i => ∑ j, z j i) (fun i => ∑ j, z' j i)) + (j : ↥u) (hj : Same e (z j) (z' (g j))) (x : (orders T (z j)).localPort s) : + lift e ht (Pin.assign T a j s x) = Pin.assign T' b (g j) s' (lift e hj x) := by + obtain ⟨i, r, rfl⟩ := exists_atCopy x + rw [assign_atCopy, lift_atCopy, lift_atCopy, assign_atCopy] + exact congrArg (atCopy (e i)) (Fin.ext (h j i r _ rfl)) + +end Pin + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Focus.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Focus.lean new file mode 100644 index 0000000000..e6745b59f7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Focus.lean @@ -0,0 +1,1009 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Frame +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.SumOut +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Alignment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Uniform.System +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Packets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Keys +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Fixed +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Wired + +/-! # Common binary local coordinates for finitely many tensor classes -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Binary + +open Spectral + +variable {K S : Type} [Field K] [Fintype S] [Nonempty S] + +open Classical in +private theorem representAt (R : Raw K S) (d : ℕ) + (h : ∀ s, Fintype.card (R.leg s) ≤ 2 ^ d) : + ∃ f : (S → Fin d → Bool) → K, (of f).tensor = Tensor.ofRaw R := by + by_cases e : ∀ s, Nonempty (R.leg s) + · let := e + have hem (s : S) : Nonempty (R.leg s ↪ (Fin d → Bool)) := + Function.Embedding.nonempty_of_card_le (by simpa using h s) + let enc s := Classical.choice (hem s) + let dec s := Function.invFun (enc s) + let f (x : S → Fin d → Bool) := R.coeff (fun s => dec s (x s)) + refine ⟨f, Tensor.ofRaw_eq ⟨?_, ?_⟩⟩ + · refine Raw.Restricts.pullback (fun s => enc s) fun x => ?_ + calc + _ = R.coeff (fun s => dec s (enc s (x s))) := + congrArg R.coeff (funext fun s => (Function.leftInverse_invFun (enc s).injective _).symm) + _ = _ := (raw_coeff (of f) (fun s => enc s (x s))).symm + · exact Raw.Restricts.pullback dec (raw_coeff (of f)) + · have z : Tensor.ofRaw R = 0 := + (Tensor.ofRaw_eq_zero _).mpr fun x => (e (fun s => ⟨x s⟩)).elim + refine ⟨fun _ => 0, ?_⟩ + rw [z] + exact (Tensor.ofRaw_eq_zero _).mpr (raw_coeff (of (fun _ : S → Fin d → Bool => (0 : K)))) + +open Classical in +/-- Choose a single register width accommodating every local coordinate in the family. -/ +theorem represent {I : Type} [Finite I] (T : I → Tensor K S) : + ∃ d : ℕ, ∃ A : I → (S → Fin d → Bool) → K, ∀ i, (of (A i)).tensor = T i := by + let : Fintype I := Fintype.ofFinite I + let R (i : I) : Raw K S := Quotient.out (T i) + let size (j : I × S) := Fintype.card ((R j.1).leg j.2) + let d := Finset.univ.sup size + have each (i : I) : ∃ f : (S → Fin d → Bool) → K, (of f).tensor = T i := by + have h (s : S) : Fintype.card ((R i).leg s) ≤ 2 ^ d := + (Finset.le_sup (f := size) (Finset.mem_univ (i, s))).trans Nat.lt_two_pow_self.le + obtain ⟨f, hf⟩ := representAt (R i) d h + exact ⟨f, hf.trans (Quotient.out_eq _)⟩ + choose A hA using each + exact ⟨d, A, hA⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Binary +end + +/- # Composition of restrictions with bounded local implementations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Binary + +open Spectral Install + +variable {K S : Type} [Field K] [Fintype S] {D V W : Binary K S} + +open Classical in +/-- Evaluates `∑ z, k s x z * l s z y` at the input `s x y`. -/ +def compose (k : Action D V) (l : Action V W) : Action D W := + fun s x y => ∑ z, k s x z * l s z y + +open Classical in +theorem compose_act (k : Action D V) (l : Action V W) (x : D.Assign) : + act D W (compose k l) x = ∑ z : V.Assign, (∏ s, k s (x s) (z s)) * act V W l z := by + simp only [act, compose, Fintype.prod_sum, Finset.sum_mul, Finset.prod_mul_distrib, + Finset.mul_sum] + rw [Finset.sum_comm] + simp only [mul_assoc] + +open Classical in +theorem Cheap.compose {k : Action D V} {l : Action V W} {b c : ℕ} + (hk : Cheap D V k b) (hl : Cheap V W l c) : + Cheap D W (compose k l) (12 * (D.size + V.size + W.size) + b + c) := by + intro s + let i : D.port s ⊕ V.port s → (D.port s ⊕ W.port s) ⊕ V.port s := + Sum.map Sum.inl id + let j : V.port s ⊕ W.port s → (D.port s ⊕ W.port s) ⊕ V.port s := + Sum.elim Sum.inr (Sum.inl ∘ Sum.inr) + have ht := (((hk s).pull i).mul ((hl s).pull j)).sum_out + refine ht.mono ?_ + simp only [Fintype.card_sum] + have := D.card_le s + have := V.card_le s + have := W.card_le s + omega + +open Classical in +theorem batch_size_le (D : Binary K S) (h : ℕ) : (batch (2 ^ h) D).size ≤ D.size * scale h := by + have hcard (s : S) : Fintype.card ((batch (2 ^ h) D).port s) = 2 ^ h * Fintype.card (D.port s) := + (Fintype.card_prod _ _).trans (by simp) + simp only [size, hcard, ← Finset.mul_sum] + rw [mul_comm (2 ^ h)] + unfold scale + exact Nat.mul_le_mul_left _ (Nat.le_mul_of_pos_right _ (by positivity)) + +open Classical in +theorem cheap_batch_compose {h b c : ℕ} {k : Action (batch (2 ^ h) D) (batch (2 ^ h) V)} + {l : Action (batch (2 ^ h) V) (batch (2 ^ h) W)} + (hk : Cheap _ _ k (b * scale h)) (hl : Cheap _ _ l (c * scale h)) : + Cheap _ _ (compose k l) ((12 * (D.size + V.size + W.size) + b + c) * scale h) := by + apply (hk.compose hl).mono + nlinarith only [batch_size_le D h, batch_size_le V h, batch_size_le W h] + +variable [Nonempty S] {A : Type} [Fintype A] {U : A → Binary K S} + +open Classical in +theorem Scalable.left (h : Scalable V U) (he : D.tensor ≤ V.tensor) : Scalable D U := by + obtain ⟨l, hl⟩ := (single_action D V).mp he + obtain ⟨c, h⟩ := h + let b := 8 * 2 ^ (D.size + V.size) + let size := ∑ i, (U i).size + refine ⟨12 * (D.size + V.size + size) + b + c, fun n => ?_⟩ + obtain ⟨k, hk, he⟩ := h n + let L := diagonalAction D V l (2 ^ n) + refine ⟨fun i => compose L (k i), fun i => ?_, fun x => ?_⟩ + · have hs : (U i).size ≤ size := + Finset.single_le_sum (f := fun i => (U i).size) (fun _ _ => Nat.zero_le _) (Finset.mem_univ i) + apply (cheap_batch_compose (diagonal_cheap D V l n) (hk i)).mono + apply Nat.mul_le_mul_right + unfold b + omega + · simp_rw [compose_act] + rw [Finset.sum_comm] + simp only [← Finset.mul_sum, ← he] + change _ = act _ _ L x + rw [show act _ _ L x = _ from diagonal_act D V l (2 ^ n) x] + change (∏ i, D.value (rows D (2 ^ n) x i)) = _ + exact Finset.prod_congr rfl fun i _ => hl (rows D (2 ^ n) x i) + +open Classical in +theorem Scalable.right {V : A → Binary K S} (h : Scalable D U) + (he : ∀ i, (U i).tensor ≤ (V i).tensor) : Scalable D V := by + choose l hl using fun i => (single_action _ _).mp (he i) + obtain ⟨b, h⟩ := h + let c i := 12 * (D.size + (U i).size + (V i).size) + b + 8 * 2 ^ ((U i).size + (V i).size) + refine ⟨∑ i, c i, fun n => ?_⟩ + obtain ⟨k, hk, he⟩ := h n + let L i := diagonalAction (U i) (V i) (l i) (2 ^ n) + refine ⟨fun i => compose (k i) (L i), fun i => ?_, fun x => ?_⟩ + · apply (cheap_batch_compose (hk i) (diagonal_cheap _ _ (l i) n)).mono + exact Nat.mul_le_mul_right _ (Finset.single_le_sum (f := c) (fun _ _ + => Nat.zero_le _) (Finset.mem_univ i)) + · rw [he] + apply Finset.sum_congr rfl + intro i _ + rw [compose_act] + apply Finset.sum_congr rfl + intro y _ + refine congrArg _ ?_ + rw [show act _ _ (L i) y = _ from diagonal_act _ _ (l i) (2 ^ n) y] + change (∏ j, (U i).value (rows (U i) (2 ^ n) y j)) = _ + exact Finset.prod_congr rfl fun j _ => hl i (rows (U i) (2 ^ n) y j) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Binary +end + +/- # Tensor classes of flat boards -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board + +open Spectral Routing + +variable {K S T I : Type} [Field K] [Fintype S] [Nonempty S] + +open Classical in +private def binPorts (A : Binary K S) (s : S) : + A.port s ≃ (ofBinary A).localPort s where + toFun i := ⟨⟨s, i⟩, rfl⟩ + invFun i := i.property ▸ i.val.2 + left_inv _ := rfl + right_inv := by rintro ⟨⟨t, i⟩, rfl⟩; rfl + +open Classical in +theorem tensor_ofBinary (A : Binary K S) : (ofBinary A).tensor = A.tensor := + Binary.tensor_relabel (binPorts A) (fun _ => rfl) + +open Classical in +private def unionPorts [Fintype I] (A : I → Board K S) (s : S) : + (Σ i, (A i).localPort s) ≃ (union A).localPort s where + toFun j := ⟨⟨j.1, j.2.1⟩, j.2.2⟩ + invFun j := ⟨j.val.1, ⟨j.val.2, j.property⟩⟩ + left_inv _ := rfl + right_inv _ := rfl + +open Classical in +theorem tensor_union [Fintype I] (A : I → Board K S) : + (union A).tensor = ∏ i, (A i).tensor := by + unfold tensor + rw [← Binary.tensor_of_product] + exact Binary.tensor_relabel (unionPorts A) (fun _ => rfl) + +open Classical in +theorem tensor_orders [Fintype I] (A : I → Board K S) (z : I → ℕ) : + (orders A z).tensor = Stock.bundle (fun i => (A i).tensor) z := by + rw [orders, tensor_union, Fintype.prod_sigma] + simp [Stock.bundle] + +open Classical in +theorem tensor_move [Fintype T] [Nonempty T] [DecidableEq S] [DecidableEq T] + (D : Board K S) (f : S → T) : + (D.move f).tensor = Tensor.place f D.tensor := by + apply Tensor.ofRaw_eq + constructor + · refine .pullback (fun t x i => x ⟨D.owner i.val, i.property⟩ ⟨i.val, rfl⟩) fun x => ?_ + erw [Raw.coeff_group, Binary.raw_coeff, Binary.raw_coeff] + rfl + · refine .pullback (fun t x s i => x ⟨i.val, (congrArg f i.property).trans s.property⟩) + fun x => ?_ + erw [Raw.coeff_group, Binary.raw_coeff, Binary.raw_coeff] + rfl + +open Classical in +private def baseLink (K : Type) [Field K] : Board K Bool where + slot := Bool + owner := id + value x := if x false = x true then 1 else 0 + +open Classical in +private def oneBit (K : Type) [Field K] (s : Bool) : + ((baseLink K).localPort s → Bool) ≃ Bool where + toFun x := x ⟨s, rfl⟩ + invFun b _ := b + left_inv x := by funext ⟨i, h⟩; change i = s at h; subst i; rfl + right_inv _ := rfl + +open Classical in +private theorem tensor_baseLink (K : Type) [Field K] : + (baseLink K).tensor = Tensor.wire K false true 2 := by + rw [Tensor.wire, show ({false, true} : Finset Bool) = Finset.univ by decide, + Tensor.shared_all, ← Fintype.card_bool, ← Tensor.diag_eq_natCast] + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (oneBit K) fun x => ?_ + rw [Binary.raw_coeff] + let v (s : Bool) := oneBit K s (x s) + change (if v false = v true then (1 : K) else 0) = + ∑ j : Bool, ∏ s : Bool, if v s = j then 1 else 0 + simp [mul_ite] + simp only [eq_comm (a := v true)] + +open Classical in +theorem tensor_link [DecidableEq S] (K : Type) [Field K] (a b : S) : + (link K a b).tensor = Tensor.wire K a b 2 := by + let f (i : Bool) := if i then b else a + change ((baseLink K).move f).tensor = _ + rw [tensor_move, tensor_baseLink, Tensor.place_wire] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board +end + +/- +# Repeating a single restriction by independent local maps +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +variable {K S : Type} [Field K] [Fintype S] [Nonempty S] + +open Classical in +theorem Binary.single_scalable (D V : Binary K S) (he : D.tensor ≤ V.tensor) : + D.Scalable (fun _ : Unit => V) := by + obtain ⟨k, hk⟩ := (Binary.single_action D V).mp he + refine ⟨8 * 2 ^ (D.size + V.size), fun h => + ⟨fun _ => Binary.diagonalAction D V k (2 ^ h), fun _ => D.diagonal_cheap V k h, fun x => ?_⟩⟩ + rw [Fintype.sum_unique, Binary.diagonal_act] + change (∏ i : Fin (2 ^ h), D.value (D.rows _ x i)) = ∏ i, D.act V k (D.rows _ x i) + exact Finset.prod_congr rfl fun i _ => hk (D.rows _ x i) + +open Classical in +/-- Computes the single by the application `Board.realize D _ (Binary.single_scalable D.binary +V.binary he)`. -/ +def Board.single (D V : Board K S) (he : D.tensor ≤ V.tensor) : + D.Expansion (fun _ : Unit => V) := + Board.realize D _ (Binary.single_scalable D.binary V.binary he) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Local and global bit presentations of the same commodities -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Spectral Routing + +variable {K S I : Type} [Field K] [Fintype S] [Nonempty S] {N : ℕ} + +open Classical in +/-- The indexed operation `Board.ofBinary (Binary.of ((Binary.represent (fun j => +(A.equivFin.symm j).val)).choose_spec.choose i))`. -/ +def commodity (A : Finset (Tensor K S)) (i : Fin A.card) : Board K S := + Board.ofBinary (Binary.of ((Binary.represent (fun j + => (A.equivFin.symm j).val)).choose_spec.choose i)) + +open Classical in +theorem tensor_commodity (A : Finset (Tensor K S)) (i : Fin A.card) : + (commodity A i).tensor = (A.equivFin.symm i).val := by + rw [commodity, Board.tensor_ofBinary] + exact (Binary.represent (fun j => (A.equivFin.symm j).val)).choose_spec.choose_spec i + +variable (s : Shape N) (b : Market I N) (A : Finset (Tensor K S)) + +open Classical in +/-- In the case `none`, this construction gives `Board.link K s.2.src s.2.dst`. -/ +def localRequest : s.Req A → Board K (Fin s.1.val) + | none => Board.link K s.2.src s.2.dst + | some (z, j) => (commodity A j).move z + +open Classical in +/-- Computes the local edge by the application `Board.link K e.val.1 e.val.2`. -/ +def localEdge (K : Type) [Field K] (s : Shape N) (e : s.2.edges) : Board K (Fin s.1.val) := + Board.link K e.val.1 e.val.2 + +open Classical in +/-- Computes the goods by the application `Sum.elim (localRequest s A) (localEdge K s)`. -/ +def goods : s.2.Goods A → Board K (Fin s.1.val) := + Sum.elim (localRequest s A) (localEdge K s) + +open Classical in +/-- In the case `.inl i`, this construction gives `Board.link K i (b.name i (b.shape i).dst)`. -/ +def request : b.Request A → Board K I + | .inl i => Board.link K i (b.name i (b.shape i).dst) + | .inr (z, j) => (commodity A j).move z.val + +open Classical in +/-- Computes the edge by the application `Board.link K (b.name e.1 e.2.val.1) (b.name e.1 +e.2.val.2)`. -/ +def edge (K : Type) [Field K] (b : Market I N) (e : b.Edge) : Board K I := + Board.link K (b.name e.1 e.2.val.1) (b.name e.1 e.2.val.2) + +open Classical in +/-- In the case `none`, this construction gives `refine ⟨Equiv.refl Bool, ?_, fun _ => rfl⟩`. -/ +def requestMove (i : I) (j : (b.code i).Req A) : + Board.Rename ((localRequest (b.code i) A j).move (b.name i)) (request b A (b.request A i j)) + := by + cases j with + | none => + refine ⟨Equiv.refl Bool, ?_, fun _ => rfl⟩ + intro x + cases x + · exact (b.origin i).symm + · rfl + | some z => exact .refl _ + +open Classical in +/-- Uses `⟨Equiv.refl Bool, by intro x; cases x <;> rfl, fun _ => rfl⟩` as the representation. -/ +def edgeMove (K : Type) [Field K] (b : Market I N) (i : I) (e : (b.shape i).edges) : + Board.Rename ((localEdge K (b.code i) e).move (b.name i)) (edge K b ⟨i, e⟩) := + ⟨Equiv.refl Bool, by intro x; cases x <;> rfl, fun _ => rfl⟩ + +variable [DecidableEq S] [Nonempty (Fin s.1.val)] + +open Classical in +theorem tensor_goods (j : s.2.Goods A) : (goods s A j).tensor = s.2.tensor A j := by + rcases j with (_ | ⟨z, i⟩) | e + · exact Board.tensor_link K _ _ + · change ((commodity A i).move z).tensor = _ + rw [Board.tensor_move, tensor_commodity] + rfl + · exact Board.tensor_link K _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Terminal kernels for fixed local routes + +Choose the implementing restriction on the bounded shape before +placing it at global labels. Placement preserves all port names. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Spectral Routing + +variable {K I S : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype I] [DecidableEq I] {N t : ℕ} (A : Finset (Tensor K S)) (d M : ℕ) + +open scoped Classical in +/-- The local supply of type `(localRequest s A x).Expansion (fun _ : Unit => Board.orders +(localEdge K s) (s.route A d M x))`, constructed using `⟨s.2.src⟩`. -/ +def localSupply (s : Shape N) (x : s.Req A) + (h : s.2.Direct K (s.2.tensor A (.inl x)) (s.priceCap A d M x)) : + (localRequest s A x).Expansion (fun _ : Unit => Board.orders (localEdge K s) (s.route A d M x)) + := by + let _ : Nonempty (Fin s.1.val) := ⟨s.2.src⟩ + apply Board.single + rw [Board.tensor_orders] + have he : (fun i => (localEdge K s i).tensor) = s.2.wire K := + funext fun i => tensor_goods s A (.inr i) + rw [he, show (localRequest s A x).tensor = s.2.tensor A (.inl x) from tensor_goods s A (.inl x)] + exact (s.route_spec A d M x h).2 + +variable (b : Market I N) (g : b.Ports t) (hr : b.ready A d) (hc : UniformCap N A M) + +open scoped Classical in +/-- The indexed operation `Stock.collect (fun e => ⟨u.1, e⟩) ((b.code u.1).route A d M u.2)`. -/ +def fromTally (u : b.Source A) : b.Edge → ℕ := + Stock.collect (fun e => ⟨u.1, e⟩) ((b.code u.1).route A d M u.2) + +include hr hc in +open scoped Classical in +/-- The supply from of type `(request b A x).Expansion (fun _ : Unit => Board.orders (edge K b) +(fromTally A d M b u))`, constructed using `(b.code u.1).route A d M u.2`. -/ +def supplyFrom (x : b.Request A) (u : b.Source A) (he : b.request A u.1 u.2 = x) : + (request b A x).Expansion (fun _ : Unit => Board.orders (edge K b) (fromTally A d M b u)) := by + let z := (b.code u.1).route A d M u.2 + let f (e : (b.shape u.1).edges) : b.Edge := ⟨u.1, e⟩ + have hf : Function.Injective f := fun _ _ e => eq_of_heq (Sigma.mk.inj e).2 + let v := localSupply A d M (b.code u.1) u.2 (b.local_route A d M hr hc _ _) + let h₁ : Board.Rename ((localRequest (b.code u.1) A u.2).move (b.name u.1)) (request b A x) := + he ▸ requestMove b A u.1 u.2 + let h₂ : Board.Rename ((Board.orders (localEdge K (b.code u.1)) z).move (b.name u.1)) + (Board.orders (edge K b ∘ f) z) := + Board.Rename.union fun p : Σ e, Fin (z e) => edgeMove K b u.1 p.1 + exact (v.place (b.name u.1)).rename h₁ fun _ => + h₂.trans (Board.ordersCollect (edge K b) f hf z).symm + +include hr hc in +open scoped Classical in +/-- Computes the supply at by the application `supplyFrom A d M b hr hc x (b.depot A g x) +(b.depot_spec A g x).1`. -/ +def supplyAt (x : b.Request A) : + (request b A x).Expansion (fun _ : Unit => Board.orders (edge K b) (b.tally A d M g x)) := + supplyFrom A d M b hr hc x (b.depot A g x) (b.depot_spec A g x).1 + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Supplying a full terminal inventory + +Copies using an edge are numbered by the local request at its depot +and the ordinal of the copy. The ordering therefore depends only +on data at that center. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Spectral Routing + +variable {K I S : Type} [Field K] [Fintype S] + +open scoped Classical in +/-- The singly of type `(Board.union D).Expansion (fun _ : Unit => Board.union V)`, constructed +using `Board.Expansion.parallel r`. -/ +def Board.Expansion.singly [Fintype I] {D V : I → Board K S} + (r : ∀ i, (D i).Expansion (fun _ : Unit => V i)) : + (Board.union D).Expansion (fun _ : Unit => Board.union V) := by + let a := Board.Expansion.parallel r + exact ⟨fun _ => a.kernel default, fun _ => a.fast default, fun h x => by + rw [a.identity] + simp only [Fintype.sum_unique]⟩ + +variable [DecidableEq S] [Nonempty S] [Fintype I] [DecidableEq I] {N t : ℕ} + (A : Finset (Tensor K S)) (d M : ℕ) (b : Market I N) (g : b.Ports t) + +open scoped Classical in +theorem tally_origin (x : b.Request A) (e : b.Edge) (h : b.tally A d M g x e ≠ 0) : + (b.depot A g x).1 = e.1 := by + obtain ⟨j, hj, _⟩ := Stock.collect_nonzero h + exact congrArg Sigma.fst hj + +open scoped Classical in +/-- The value specified by `(Fintype.equivFin ((b.code x.1).Req A) x.2).val`. -/ +def supplyIndex (x : b.Source A) := (Fintype.equivFin ((b.code x.1).Req A) x.2).val + +omit [Fintype I] [DecidableEq I] [Nonempty S] in +open scoped Classical in +private theorem supplyIndex_inj (x y : b.Source A) (he : x.1 = y.1) + (h : supplyIndex A b x = supplyIndex A b y) : x = y := by + rcases x with ⟨i, x⟩ + rcases y with ⟨j, y⟩ + change i = j at he + subst j + have e : x = y := (Fintype.equivFin ((b.code i).Req A)).injective (Fin.ext h) + rw [e] + +variable (z : b.Request A → ℕ) +open scoped Classical in +/-- Indexes the units by the coordinates of `Σ i, Fin (z i)`. -/ +abbrev Units := Σ i, Fin (z i) + +open scoped Classical in +/-- The value specified by `Encodable.encode (supplyIndex A b (b.depot A g x.1), x.2.val)`. -/ +def supplyKey (x : Units A b z) := + Encodable.encode (supplyIndex A b (b.depot A g x.1), x.2.val) + +open scoped Classical in +theorem supplyOrdered (e : b.Edge) : + Ordered (fun x : Units A b z => b.tally A d M g x.1 e) (supplyKey A b g z) := by + rintro ⟨x, i⟩ ⟨y, j⟩ hx hy hh + have h := Encodable.encode_injective hh + have hs := supplyIndex_inj A b _ _ + ((tally_origin A d M b g x e hx).trans (tally_origin A d M b g y e hy).symm) + (congrArg Prod.fst h) + have he : x = y := (b.depot_spec A g x).1.symm.trans + ((congrArg (b.requestOf A) hs).trans (b.depot_spec A g y).1) + subst y + have hij : i = j := Fin.ext (congrArg Prod.snd h) + rw [hij] + +open scoped Classical in +/-- The construction uses `b.tally A d M g i.1` for its intermediate `Y`. -/ +def terminal (hr : b.ready A d) (hc : UniformCap N A M) : + (Board.orders (request b A) z).Expansion + (fun _ : Unit => Board.orders (edge K b) (fun e => ∑ i, b.tally A d M g i e * z i)) := by + let Y (i : Units A b z) := b.tally A d M g i.1 + let r := Board.Expansion.singly (fun j : Units A b z => supplyAt A d M b g hr hc j.1) + let u := Board.ordersSum (edge K b) Y (fun e => (pack _ _ (supplyOrdered A d M b g z e)).symm) + have he : (fun e => ∑ j, Y j e) = (fun e => ∑ i, b.tally A d M g i e * z i) := by + funext e + simp only [Y, Units, Fintype.sum_sigma, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + nsmul_eq_mul, Nat.cast_id] + exact Finset.sum_congr rfl fun _ _ => mul_comm _ _ + exact r.rename (.refl _) fun _ => u.symm.trans (Board.ordersEq (edge K b) he) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Compiling an inventory schedule to local maps + +Reserve the remaining payload as part of the stock. Core edges of +each step precede the later ones in the final enumeration. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Board Routing + +variable {K S I E : Type} [Field K] [Fintype S] [Fintype I] [DecidableEq I] [Fintype E] + (T : I → Board K S) (V : E → Board K S) + (L : Finset I) (Q : (I → ℕ) → Intervention I E) (Y : I → E → ℕ) + +/-- The condition `∀ z : I → ℕ, Expansion (orders T z) (fun _ : Unit => orders V (fun e => ∑ i, +Y i e * z i))` on the specified data. -/ +abbrev Settlement := ∀ z : I → ℕ, Expansion (orders T z) + (fun _ : Unit => orders V (fun e => ∑ i, Y i e * z i)) + +variable (close : Settlement T V Y) (run : ∀ z, Executes T V (Q z)) + +/-- In the case `zero`, this construction gives `have he : z = z + Stock.copies L 0 := by ext i; +simp [Stock.copies]`. -/ +def execute {a : I → ℝ} {budget : ℝ} (k : ℕ) (z : I → ℕ) (v : ℝ) + (h : Runs L a Q budget k z v) : + Expansion (orders T (z + Stock.copies L k)) + (fun j : Branch L Q k z => orders V (edges L Q Y k z j)) := by + cases k with + | zero => + have he : z = z + Stock.copies L 0 := by ext i; simp [Stock.copies] + exact (close z).rename (ordersEq T he) (fun _ => .refl _) + | succ k => + let q := Q z + let Z := z + Stock.copies L (k + 1) + let z' j := q.next z j + Stock.copies L 1 + have hq : q.take ≤ Z := fun i => (h.1 i).trans (Nat.le_add_right _ _) + have he (j : q.choice) : z' j + Stock.copies L k = q.next Z j := by + funext i + have hh : q.take i ≤ z i := h.1 i + by_cases hi : i ∈ L <;> simp [Intervention.next, Stock.copies, z', Z, hi] + omega + let first := (run z).takeStep Z hq + let rest (j : q.choice) := execute k (z' j) (v + q.cost j) (h.2 j) + let finish (j : q.choice) : Expansion ((orders T (q.next Z j)).join (orders V (q.core j))) + (fun i : Branch L Q k (z' j) => orders V (q.core j + edges L Q Y k (z' j) i)) := + ((rest j).keep _).rename ((ordersEq T (he j)).join (.refl _)) fun i => + (swap _ _).trans (ordersAdd V _ _).symm + exact first.comp finish + +/-- The indexed operation `(execute T V L Q Y close run k 0 0 h).rename (ordersEq T (zero_add +_)) (fun _ => .refl _)`. -/ +def executeStart {a : I → ℝ} {budget : ℝ} {k : ℕ} (h : Runs L a Q budget k 0 0) : + Expansion (orders T (Stock.copies L k)) + (fun j : Branch L Q k 0 => orders V (edges L Q Y k 0 j)) := + (execute T V L Q Y close run k 0 0 h).rename (ordersEq T (zero_add _)) (fun _ => .refl _) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Scalable local substitutions + +The fixed alphabet of rounded histograms serves every scale. The supply +bundle pays separately for the common selector and the goods of each letter. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Spectral Routing Routing.Stock Finset + +variable {K S I : Type} [Field K] [Fintype S] [Nonempty S] [Fintype I] [DecidableEq I] + {T : I → Tensor K S} {H : ℝ} + +theorem flex_scalable + (q : Proposal T H) (u : Finset I) + (hu : (2 : Tensor K S) ≤ ∏ i ∈ u, T i) (hT : ∀ i, 1 ≤ T i) + (b : ℕ) (hb : Fintype.card q.move.letter ≤ 2 ^ b) (D : Binary K S) + (V : ↥(histograms q.move.letter (2 ^ b + Fintype.card q.move.letter)) → Binary K S) + (hd : D.tensor ≤ bundle T (Stock.copies q.demand (q.move.block * 2 ^ b))) + (hv : ∀ t, bundle T (q.output u (2 ^ b + Fintype.card q.move.letter) t.val) ≤ (V t).tensor) : + Binary.Scalable D V := by + classical + let : MulLeftMono (Tensor K S) := ⟨fun c a b h => Tensor.mul_le_mul_left _ _ _ h⟩ + have lo (s : Finset I) (n : ℕ) : 1 ≤ (∏ i ∈ s, T i) ^ n := by + exact one_le_pow_of_one_le' (one_le_prod fun i _ => hT i) _ + have hn : Nonempty q.move.letter := by + by_contra! h + have h₁ := (lo q.demand q.move.block).trans q.move.covers + rw [sum_of_isEmpty] at h₁ + exact one_ne_zero (le_antisymm h₁ (Tensor.zero_le _)) + obtain ⟨_, F, hF⟩ := Binary.represent (fun _ : Unit => (∏ i ∈ q.demand, T i) ^ q.move.block) + obtain ⟨_, G, hG⟩ := Binary.represent (fun j => bundle T (q.orders j)) + have cover : (Binary.of (F ())).tensor ≤ ∑ j, (Binary.of (G j)).tensor := by + simp only [hF, hG, Proposal.orders, bundle_collect] + exact q.move.covers + have goods (j) : 1 ≤ (Binary.of (G j)).tensor := by + rw [hG] + exact one_le_prod fun i _ => one_le_pow_of_one_le' (hT i) _ + have cost : (Fintype.card q.move.letter : Tensor K S) ≤ (∏ i ∈ u, T i) ^ q.move.bits := by + refine (Tensor.natCast_le q.move.fits).trans ?_ + rw [Nat.cast_pow, Nat.cast_ofNat] + exact pow_le_pow_left' hu _ + have h := word_scalable (F ()) G hn.some cover goods b hb + refine (h.left ?_).right fun t => (offer_bound G _ _).trans (le_trans ?_ (hv t)) + · rw [Binary.tensor_of_batch, hF, ← pow_mul, ← bundle_copies] + exact hd + · simp only [hG] + unfold Proposal.output + rw [bundle_add, bundle_copies, bundle_sum, pow_mul] + apply mul_le_mul_left + exact (pow_le_pow_left' cost _).trans + (pow_le_pow_right' (lo u q.move.bits) (Nat.le_add_right _ _)) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Local implementations for the finite menu of shapes + +Choose the scalable maps on the canonical shape. Moving to another +market changes only the site and slot names. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Spectral Routing Board Stock + +variable {K S I : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + {N : ℕ} (s : Shape N) (A : Finset (Tensor K S)) + +open Classical in +/-- This choice uses only the shape and move, independently of the +location or total number of sites in the ambient market. -/ +def localAction (q : s.Move A) (h : ℕ) (ha : 0 ∉ A) (hb : Fintype.card q.move.letter ≤ 2 ^ h) : + Expansion (orders (goods s A) (Stock.copies q.demand (q.move.block * 2 ^ h))) + (fun t : ↥(histograms q.move.letter (2 ^ h + Fintype.card q.move.letter)) => + orders (goods s A) (q.output (s.2.links A) (2 ^ h + Fintype.card q.move.letter) t.val)) + := by + let _ : Nonempty (Fin s.1.val) := ⟨s.2.src⟩ + apply Board.realize + have eq (z : s.2.Goods A → ℕ) : + (orders (goods s A) z).binary.tensor = bundle (s.2.tensor A) z := by + change (orders (goods s A) z).tensor = _ + rw [tensor_orders, show (fun i => (goods s A i).tensor) = s.2.tensor A from + funext (tensor_goods s A)] + exact flex_scalable q _ (s.2.broadcast A) (fun j => Tensor.one_le _ (s.2.nonzero A ha j)) + h hb _ _ (eq _).le (fun t => (eq _).ge) + +variable [Fintype I] [DecidableEq I] (b : Market I N) (i : I) + +open Classical in +/-- Computes the global board by the application `Sum.elim (request b A) (edge K b)`. -/ +def globalBoard : b.Good A → Board K I := Sum.elim (request b A) (edge K b) + +open Classical in +/-- In the case `.inl r`, this construction gives `requestMove b A i r`. -/ +def goodsMove (j : (b.shape i).Goods A) : + Rename ((goods (b.code i) A j).move (b.name i)) (globalBoard A b (b.assign A i j)) := + match j with + | .inl r => requestMove b A i r + | .inr e => edgeMove K b i e + +open Classical in +/-- Decides equality separately on valid requests and edge records. -/ +local instance : DecidableEq (b.Good A) := @instDecidableEqSum (b.Request A) b.Edge inferInstance + inferInstance + +open Classical in +/-- The post used in the `Protocol` construction. -/ +def post (z : (b.shape i).Goods A → ℕ) : + Rename ((orders (goods (b.code i) A) z).move (b.name i)) + ((orders (request b A) (collect (b.assign A i) z ∘ Sum.inl)).join + (orders (edge K b) (collect (b.assign A i) z ∘ Sum.inr))) := + (Rename.union (fun r : Σ j, Fin (z j) => goodsMove A b i r.1)).trans <| + (ordersCollect (globalBoard A b) (b.assign A i) (b.assign_injective A i) z).symm.trans + (ordersSplit (globalBoard A b) _) + +open Classical in +/-- The drop empty of type `Rename (D.join (orders V z)) D` for the given inputs. -/ +def Board.dropEmpty {E : Type} [Fintype E] (D : Board K I) (V : E → Board K I) + (z : E → ℕ) (hz : ∀ e, z e = 0) : Rename (D.join (orders V z)) D := by + letI : IsEmpty (Σ i, Fin (z i)) := ⟨fun p => Fin.elim0 (Fin.cast (hz _) p.2)⟩ + letI : IsEmpty (orders V z).slot := ⟨fun p => isEmptyElim p.1⟩ + refine ⟨Equiv.sumEmpty _ _, ?_, fun x => ?_⟩ + · rintro (j|j) + · rfl + · exact isEmptyElim j + · change D.value x * (∏ r : Σ j, Fin (z j), _) = _ + rw [Finset.prod_of_isEmpty, mul_one] + +open Classical in +/-- The apply move of type `Executes (request b A) (edge K b) (q.flex (b.assign A i) ((b.shape +i).links A) (2 ^ h))`, constructed using `(localAction (b.code i) A q h ha hb).place (b.name +i)`. -/ +def applyMove (q : (b.code i).Move A) (h : ℕ) (ha : 0 ∉ A) + (hb : Fintype.card q.move.letter ≤ 2 ^ h) + (hd : ∀ j ∈ q.demand, ∃ l, b.assign A i j = .inl l) : + Executes (request b A) (edge K b) (q.flex (b.assign A i) ((b.shape i).links A) (2 ^ h)) := by + let r := (localAction (b.code i) A q h ha hb).place (b.name i) + let d := Stock.copies q.demand (q.move.block * 2 ^ h) + let e := (post A b i d).trans (Board.dropEmpty _ _ _ (q.take_core (b.assign A i) (2 ^ h) hd)) + exact r.rename e (fun _ => post A b i _) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Identifying the initial payload requests with permutation wires -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Spectral Routing Board + +variable {F S : Type} [Field F] [Fintype S] [Nonempty S] [DecidableEq S] {h N : ℕ} + +open Classical in +/-- Decidable equality on transport sites for the focused protocol. -/ +local instance : DecidableEq (Transport.Site h) := Classical.decEq _ + +open Classical in +/-- The demand rename of type `Rename (orders (request b A) (Stock.copies (b.payload A) W)) +(Demand F σ W)`, constructed using `Stock.copies (b.payload A) W`. -/ +def demandRename (b : Market (Transport.Site h) N) (A : Finset (Tensor F S)) + (σ : Coloring.B h → Coloring.B h) (W : ℕ) + (hσ : ∀ i, b.name i (b.shape i).dst = inflate h σ i) : + Rename (orders (request b A) (Stock.copies (b.payload A) W)) (Demand F σ W) := by + let m := Stock.copies (b.payload A) W + have hl : m ∘ Sum.inl = fun _ : Transport.Site h => W := by + funext i + simp [m, Stock.copies, Market.payload] + have hr : ∀ i, (m ∘ Sum.inr) i = 0 := by + intro i + simp [m, Stock.copies, Market.payload] + let first := (ordersSplit (request b A) m).trans (dropEmpty _ _ _ hr) + let name (i : Transport.Site h) : Rename (request b A (.inl i)) (Board.link F i (inflate h σ i)) + := + ⟨Equiv.refl Bool, fun v => by cases v <;> first | rfl | exact (hσ i).symm, fun _ => rfl⟩ + exact (first.trans (ordersEq _ hl)).trans (Rename.union (fun j : Σ _ : Transport.Site h, Fin W => + name j.1)) + +open Classical in +theorem demandRename_apply (b : Market (Transport.Site h) N) (A : Finset (Tensor F S)) + (σ : Coloring.B h → Coloring.B h) (W : ℕ) + (hσ : ∀ i, b.name i (b.shape i).dst = inflate h σ i) + (i : Transport.Site h) (u : Fin (Stock.copies (b.payload A) W (.inl i))) + (j : Fin W) (he : u.val = j.val) (v : Bool) : + (demandRename b A σ W hσ).eqv ⟨⟨.inl i, u⟩, v⟩ = ⟨⟨i, j⟩, v⟩ := by + obtain ⟨u, hu⟩ := u + obtain ⟨j, hj⟩ := j + change u = j at he + subst j + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Implementing the protocol at all dyadic widths -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Spectral Routing + +variable {K I S : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + [Fintype I] [DecidableEq I] {N M t : ℕ} {ρ : ℝ} (b : Market I N) + {A : Finset (Tensor K S)} (a : Atlas N A M ρ) (g : b.Ports t) + (h : ℕ) (ha : 0 ∉ A) (hh : a.Room (2 ^ h)) + +open scoped Classical in +/-- The perform of type `Executes (request b A) (edge K b) (b.policy a p (2 ^ h))` for the given +inputs. -/ +def perform (p : b.Request A → ℝ) : + Executes (request b A) (edge K b) (b.policy a p (2 ^ h)) := + Executes.parallel (b.allocation a p (2 ^ h) g) fun i => + applyMove A b i (b.moveAt a p i) h ha (hh _ _ (b.moving a p i).1).1 (b.demand_slot a p i) + +variable (μ d W : ℕ) (hr : b.ready A d) (hc : UniformCap N A M) + (hw : Runs (b.payload A) (b.cap A d M) (b.decision a μ d (2 ^ h)) + (1203 * Fintype.card I * W) W 0 0) + +open scoped Classical in +/-- The program used in the `Protocol` construction. -/ +def program : + (Board.orders (request b A) (Stock.copies (b.payload A) W)).Expansion + (fun j : Branch (b.payload A) (b.decision a μ d (2 ^ h)) W 0 => + Board.orders (edge K b) + (edges (b.payload A) (b.decision a μ d (2 ^ h)) (b.tally A d M g) W 0 j)) := + executeStart _ _ _ _ _ (fun z => terminal A d M b g z hr hc) + (fun z => perform b a g h ha hh (fun i => price μ (b.cap A d M i) (z i))) hw + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Local comparison of two inventory protocols + +Only charts meeting the marked site can contribute nontrivial factors +there. Keep their shape and focus, and the identifications of all +incident commodity and core pins. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral + +variable {K S I I' : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + {N : ℕ} (A : Finset (Tensor K S)) + +open Classical in +/-- Indexes the near by the coordinates of `Σ i : I, {u : Fin (b.size i).val // b.name i u = +s}`. -/ +abbrev Near (b : Market I N) (s : I) := Σ i : I, {u : Fin (b.size i).val // b.name i u = s} + +open Classical in +/-- Uses `⟨b.request A j.1 l.1, (requestMove b A j.1 l.1).local s (Board.movePort _ (b.name j.1) +j.2 l.2)⟩` as the representation. -/ +def placeReq {b : Market I N} {s : I} (j : Near b s) + (l : Pin (localRequest (b.code j.1) A) j.2.1) : Pin (request b A) s := + ⟨b.request A j.1 l.1, (requestMove b A j.1 l.1).local s + (Board.movePort _ (b.name j.1) j.2 l.2)⟩ + +open Classical in +/-- Uses `⟨⟨j.1, l.1⟩, (edgeMove K b j.1 l.1).local s (Board.movePort _ (b.name j.1) j.2 l.2)⟩` +as the representation. -/ +def placeEdge (K : Type) [Field K] {b : Market I N} {s : I} (j : Near b s) + (l : Pin (localEdge K (b.code j.1)) j.2.1) : Pin (edge K b) s := + ⟨⟨j.1, l.1⟩, (edgeMove K b j.1 l.1).local s + (Board.movePort _ (b.name j.1) j.2 l.2)⟩ + +open Classical in +/-- The data for the match construction, including `req`, `core`, `near`, `same`, `focus`. -/ +structure Match (b : Market I N) (c : Market I' N) (s : I) (v : I') where + /-- Reindexes the data using `Pin (request b A) s ≃ Pin (request c A) v`. -/ + req : Pin (request b A) s ≃ Pin (request c A) v + /-- Reindexes the data using `Pin (edge K b) s ≃ Pin (edge K c) v`. -/ + core : Pin (edge K b) s ≃ Pin (edge K c) v + /-- Reindexes the data using `Near b s ≃ Near c v`. -/ + near : Near b s ≃ Near c v + same : ∀ j, b.code j.1 = c.code (near j).1 + focus : ∀ j, j.2.1.val = (near j).2.1.val + req_eq : ∀ j l l', HEq l l' → req (placeReq A j l) = placeReq A (near j) l' + core_eq : ∀ j l l', HEq l l' → core (placeEdge K j l) = placeEdge K (near j) l' + +variable [Fintype I] [Fintype I'] [DecidableEq I] [DecidableEq I'] + {A} {b : Market I N} {c : Market I' N} {s : I} {v : I'} + {t t' : ℕ} (r : Match A b c s v) (g : b.Ports t) (g' : c.Ports t') + +open Classical in +/-- The condition `∀ (j : Near b s) (x : Pin (request b A) s), g.key (b.home A x.1) j.1 = g'.key +(c.home A (r.req x).1) (r.near j).1` on the specified data. -/ +def Match.keys : Prop := + ∀ (j : Near b s) (x : Pin (request b A) s), + g.key (b.home A x.1) j.1 = g'.key (c.home A (r.req x).1) (r.near j).1 + +open Classical in +/-- The depots of type `Prop` for the given inputs. -/ +def Match.depots : Prop := + ∀ (j : Near b s) (x : (b.code j.1).Req A) (x' : (c.code (r.near j).1).Req A), + HEq x x' → + ((b.depot A g (b.request A j.1 x)).1 = j.1 ↔ + (c.depot A g' (c.request A (r.near j).1 x')).1 = (r.near j).1) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Transport of a local kernel and its individual pins -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral + +namespace Board + +variable {K S T I : Type} [Field K] [Fintype S] [Fintype T] [Fintype I] + {D : Board K S} {V : I → Board K S} (r : Expansion D V) (f : S ↪ T) {s : T} + +open Classical in +theorem Expansion.placed (j : {i // f i = s}) (t : I) : + (r.place f).kernel t s = (r.kernel t j.val).pull (movePort D f j) (movePort (V t) f j) := by + funext h x y + apply Fintype.prod_eq_single j + intro i hi + exact (hi (Subtype.ext (f.injective (i.property.trans j.property.symm)))).elim + +open Classical in +theorem Expansion.absent (hj : ∀ i, f i ≠ s) (t : I) : + (r.place f).kernel t s = (fun _ _ _ => 1) := by + funext h x y + exact Finset.prod_eq_one fun i _ => (hj i i.property).elim + +omit [Field K] [Fintype S] [Fintype T] in +open Classical in +theorem Rename.find_source {Q : Board K T} (e : Rename (D.move f) Q) (x : Q.localPort s) : + ∃ (i : {i // f i = s}) (p : D.localPort i.val), e.local s (movePort D f i p) = x := by + let y := e.symm.local s x + refine ⟨⟨D.owner y.val, y.property⟩, ⟨y.val, rfl⟩, ?_⟩ + exact Subtype.ext (e.eqv.apply_symm_apply x.val) + +end Board + +variable {K S I I' : Type} [Field K] [Fintype S] [Nonempty S] + {N : ℕ} {b : Market I N} {c : Market I' N} {s : I} {v : I'} {A : Finset (Tensor K S)} + +open Classical in +/-- Indexes the spot by the coordinates of `Σ x : Shape N, Fin x.1.val`. -/ +abbrev Spot (N : ℕ) := Σ x : Shape N, Fin x.1.val +open Classical in +/-- Uses `⟨b.code j.1, j.2.1⟩` as the representation. -/ +def spot (j : Near b s) : Spot N := ⟨b.code j.1, j.2.1⟩ + +open Classical in +theorem Match.spot_eq (r : Match A b c s v) (j : Near b s) : + spot j = spot (r.near j) := + Sigma.ext (r.same j) ((Fin.heq_ext_iff (congrArg (fun x : Shape N => x.1.val) (r.same j))).mpr + (r.focus j)) + +open Classical in +/-- Builds `Match A c b v s where req` with the specified `req`, `core`, `near`, `same`. -/ +def Match.symm (r : Match A b c s v) : Match A c b v s where + req := r.req.symm + core := r.core.symm + near := r.near.symm + same j := by simpa using (r.same (r.near.symm j)).symm + focus j := (congrArg (fun v : Near c _ => v.2.1.val) (r.near.apply_symm_apply j)).symm.trans + (r.focus (r.near.symm j)).symm + req_eq j x y he := by + apply r.req.symm_apply_eq.mpr + have h := r.req_eq (r.near.symm j) + rw [r.near.apply_symm_apply] at h + exact (h _ _ he.symm).symm + core_eq j x y he := by + apply r.core.symm_apply_eq.mpr + have h := r.core_eq (r.near.symm j) + rw [r.near.apply_symm_apply] at h + exact (h _ _ he.symm).symm + +open Classical in +theorem placeReq_surj (x : Pin (request b A) s) (i : I) (j : (b.code i).Req A) + (h : b.request A i j = x.1) : + ∃ (u : {u // b.name i u = s}) (p : (localRequest (b.code i) A j).localPort u.val), + placeReq A (⟨i, u⟩ : Near b s) ⟨j, p⟩ = x := by + obtain ⟨k, x⟩ := x + change _ = k at h + subst k + obtain ⟨u, p, hp⟩ := Board.Rename.find_source (b.name i) (requestMove b A i j) x + exact ⟨u, p, congrArg (Sigma.mk _) hp⟩ + +open Classical in +theorem placeEdge_surj (x : Pin (edge K b) s) (i : I) (j : (b.shape i).edges) + (h : ⟨i, j⟩ = x.1) : + ∃ (u : {u // b.name i u = s}) (p : (localEdge K (b.code i) j).localPort u.val), + placeEdge K (⟨i, u⟩ : Near b s) ⟨j, p⟩ = x := by + obtain ⟨k, x⟩ := x + change _ = k at h + subst k + obtain ⟨u, p, hp⟩ := Board.Rename.find_source (b.name i) (edgeMove K b i j) x + exact ⟨u, p, congrArg (Sigma.mk _) hp⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Frame.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Frame.lean new file mode 100644 index 0000000000..0ac60a1291 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Frame.lean @@ -0,0 +1,814 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryComparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Fixed + +/-! +# Binary presentations with named local ports + +The tensor semiring forgets local coordinates. A binary presentation +retains them, so the cost of a restriction can be counted. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Spectral + +/-- The data for the binary construction, including `port`, `[finitePort`, `value`. -/ +structure Binary (K S : Type) where + /-- The `Binary` component of type `S → Type`. -/ + port : S → Type + [finitePort : ∀ s, Fintype (port s)] + /-- The evaluation map carried by `Binary`, with type `(∀ s, port s → Bool) → K`. -/ + value : (∀ s, port s → Bool) → K + +attribute [instance] Binary.finitePort + +namespace Binary + +variable {K S : Type} [Field K] [Fintype S] [Nonempty S] + +open Classical in +/-- The condition `∀ s, D.port s → Bool` on the specified data. -/ +abbrev Assign (D : Binary K S) := ∀ s, D.port s → Bool + +open Classical in +/-- Computes the raw by the application `Raw.ofTable _ D.value`. -/ +def raw (D : Binary K S) : Raw K S := Raw.ofTable _ D.value + +open Classical in +/-- Computes the tensor by the application `Tensor.ofRaw D.raw`. -/ +def tensor (D : Binary K S) : Tensor K S := Tensor.ofRaw D.raw + +open Classical in +/-- Indexes the batch by the coordinates of `Fin n × D.port s value x := ∏ i, D.value (fun s j +=> x s (i, j))`. -/ +def batch (n : ℕ) (D : Binary K S) : Binary K S where + port s := Fin n × D.port s + value x := ∏ i, D.value (fun s j => x s (i, j)) + +open Classical in +/-- Indexes the product by the coordinates of `Σ i, (D i).port s value x := ∏ i, (D i).value +(fun s j => x s ⟨i, j⟩)`. -/ +def product {I : Type} [Fintype I] (D : I → Binary K S) : Binary K S where + port s := Σ i, (D i).port s + value x := ∏ i, (D i).value (fun s j => x s ⟨i, j⟩) + +open Classical in +/-- The condition `∀ s, (D.port s → Bool) → (V.port s → Bool) → K` on the specified data. -/ +abbrev Action (D V : Binary K S) := ∀ s, (D.port s → Bool) → (V.port s → Bool) → K + +open Classical in +/-- The quantity computed by `∑ y : V.Assign, (∏ s, k s (x s) (y s)) * V.value y`. -/ +def act (D V : Binary K S) (k : Action D V) (x : D.Assign) : K := + ∑ y : V.Assign, (∏ s, k s (x s) (y s)) * V.value y + +open Classical in +theorem applyLocal (D V : Binary K S) (k : Action D V) (x : D.Assign) : + Raw.applyLocal (B := D.raw) V.raw k x = act D V k x := by + refine (Raw.expand V.raw (fun s => k s (x s))).trans ?_ + apply Finset.sum_congr rfl + intro y _ + exact congrArg _ (Raw.coeff_ofTable _ V.value y) + +open Classical in +theorem sum_action {I : Type} [Fintype I] (D : Binary K S) (V : I → Binary K S) : + D.tensor ≤ ∑ i, (V i).tensor ↔ + ∃ k : ∀ i, Action D (V i), ∀ x, D.value x = ∑ i, act D (V i) (k i) x := by + unfold tensor + rw [Raw.restriction_sum_iff] + constructor + · rintro ⟨k, hk⟩ + refine ⟨k, fun x => (Raw.coeff_ofTable _ D.value x).symm.trans ((hk x).trans ?_)⟩ + exact Finset.sum_congr rfl fun i _ => applyLocal D (V i) (k i) x + · rintro ⟨k, hk⟩ + refine ⟨k, fun x => (Raw.coeff_ofTable _ D.value x).trans ((hk x).trans ?_)⟩ + exact Finset.sum_congr rfl fun i _ => (applyLocal D (V i) (k i) x).symm + +open Classical in +theorem single_action (D V : Binary K S) : + D.tensor ≤ V.tensor ↔ ∃ k : Action D V, ∀ x, D.value x = act D V k x := by + have h := sum_action D (fun _ : Unit => V) + simp only [Fintype.sum_unique] at h + exact h.trans ⟨fun ⟨k, hk⟩ => ⟨k (), hk⟩, fun ⟨k, hk⟩ => ⟨fun _ => k, hk⟩⟩ + +end Binary +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Implementing restrictions on bit arrays at all dyadic widths + +The constant may depend on the two presentations and the finite +branch alphabet. It does not depend on the dyadic width. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Binary + +open Spectral Install + +variable {K S A : Type} [Field K] [Fintype S] [Nonempty S] [Fintype A] + (D V : Binary K S) + +open Classical in +/-- Reindexes `(batch n D).Assign` and `(Fin n → D.Assign) where toFun x i s j` by an +equivalence. -/ +def rows (n : ℕ) : (batch n D).Assign ≃ (Fin n → D.Assign) where + toFun x i s j := x s (i, j) + invFun x s p := x p.1 s p.2 + left_inv _ := rfl + right_inv _ := rfl + +open Classical in +/-- Evaluates `∏ i, k s (fun j => x (i, j)) (fun j => y (i, j))` at the input `s x y`. -/ +def diagonalAction (k : Action D V) (n : ℕ) : Action (batch n D) (batch n V) := + fun s x y => ∏ i, k s (fun j => x (i, j)) (fun j => y (i, j)) + +omit [Nonempty S] in +open Classical in +theorem diagonal_act (k : Action D V) (n : ℕ) (x : (batch n D).Assign) : + act _ _ (diagonalAction D V k n) x = ∏ i, act D V k (rows D n x i) := by + unfold act + rw [Fintype.prod_sum, ← (rows V n).sum_comp] + apply Finset.sum_congr rfl + intro y _ + rw [Finset.prod_mul_distrib] + apply congrArg₂ (· * ·) _ rfl + unfold diagonalAction + exact Finset.prod_comm + +open Classical in +/-- The condition `∀ s, Weight K (fun x : D.port s ⊕ V.port s → Bool => k s (x ∘ Sum.inl) (x ∘ +Sum.inr)) c` on the specified data. -/ +def Cheap (k : Action D V) (c : ℕ) : Prop := + ∀ s, Weight K (fun x : D.port s ⊕ V.port s → Bool => k s (x ∘ Sum.inl) (x ∘ Sum.inr)) c + +open Classical in +/-- The quantity computed by `2 ^ h * (h + 1) ^ 3`. -/ +def scale (h : ℕ) : ℕ := 2 ^ h * (h + 1) ^ 3 + +open Classical in +/-- The scalable of type `Prop` for the given inputs. -/ +def Scalable (D : Binary K S) (V : A → Binary K S) : Prop := + ∃ c : ℕ, ∀ h : ℕ, ∃ k : ∀ i, Action (batch (2 ^ h) D) (batch (2 ^ h) (V i)), + (∀ i, Cheap _ _ (k i) (c * scale h)) ∧ + ∀ x, (batch (2 ^ h) D).value x = ∑ i, act _ _ (k i) x + +omit [Fintype S] [Nonempty S] in +open Classical in +theorem Cheap.mono {D V : Binary K S} {k : Action D V} {b c : ℕ} (hk : Cheap D V k b) (hc : b ≤ c) : + Cheap D V k c := fun s => (hk s).mono hc + +open Classical in +/-- The sum of `Fintype.card (D.port s)` indexed by `s`. -/ +def size (D : Binary K S) : ℕ := ∑ s, Fintype.card (D.port s) + +omit [Field K] [Nonempty S] in +open Classical in +theorem card_le (s : S) : Fintype.card (D.port s) ≤ size D := + Finset.single_le_sum (f := fun s => Fintype.card (D.port s)) (fun _ _ + => Nat.zero_le _) (Finset.mem_univ s) + +omit [Nonempty S] in +open Classical in +theorem diagonal_cheap (k : Action D V) (h : ℕ) : + Cheap _ _ (diagonalAction D V k (2 ^ h)) ((8 * 2 ^ (D.size + V.size)) * scale h) := by + intro s + let f := fun x : D.port s ⊕ V.port s → Bool => k s (x ∘ Sum.inl) (x ∘ Sum.inr) + have H := ((Weight.dense K _ f).prod h).rename + (Equiv.prodSumDistrib (Fin (2 ^ h)) (D.port s) (V.port s)) + refine H.mono ?_ + rw [Fintype.card_sum, mul_comm (2 ^ h)] + unfold scale + gcongr + · exact D.card_le s + · exact V.card_le s + · exact Nat.le_mul_of_pos_right _ (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Binary +end + +/- # Tensor products on disjoint families of named bit positions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Binary + +open Spectral + +variable {K S : Type} [Field K] [Fintype S] [Nonempty S] + +open Classical in +/-- Uses `⟨fun _ => X, f⟩` as the representation. -/ +def of {X : Type} [Fintype X] (f : (S → X → Bool) → K) : Binary K S := + ⟨fun _ => X, f⟩ + +open Classical in +/-- Indexes the join by the coordinates of `D.port s ⊕ V.port s value x := D.value (fun s j => x +s (.inl j)) * V.value (fun s j => x s (.inr j))`. -/ +def join (D V : Binary K S) : Binary K S where + port s := D.port s ⊕ V.port s + value x := D.value (fun s j => x s (.inl j)) * V.value (fun s j => x s (.inr j)) + +open Classical in +theorem raw_coeff (D : Binary K S) (x : ∀ s, D.raw.leg s) : D.raw.coeff x = D.value x := + Raw.coeff_ofTable _ D.value x + +open Classical in +theorem tensor_of_join (D V : Binary K S) : (D.join V).tensor = D.tensor * V.tensor := by + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (fun s => Equiv.sumArrowEquivProdArrow _ _ Bool) fun x => ?_ + rw [Raw.coeff_mul] + simp only [raw_coeff] + rfl + +open Classical in +theorem tensor_relabel {D V : Binary K S} (e : ∀ s, V.port s ≃ D.port s) + (h : ∀ x, D.value x = V.value (fun s j => x s (e s j))) : D.tensor = V.tensor := by + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (fun s => (e s).symm.arrowCongr (Equiv.refl Bool)) fun x => ?_ + simp only [raw_coeff] + exact h x + +open Classical in +private def splitPorts {I : Type} (P : Option I → Type) : + P none ⊕ (Σ i, P (some i)) ≃ Σ i, P i where + toFun := Sum.elim (fun j => ⟨none, j⟩) (fun z => ⟨some z.1, z.2⟩) + invFun + | ⟨none, j⟩ => .inl j + | ⟨some i, j⟩ => .inr ⟨i, j⟩ + left_inv := by rintro (x | ⟨i, x⟩) <;> rfl + right_inv := by rintro ⟨_ | i, x⟩ <;> rfl + +open Classical in +theorem tensor_of_product {I : Type} [Fintype I] (D : I → Binary K S) : + (product D).tensor = ∏ i, (D i).tensor := by + refine Fintype.induction_empty_option + (P := fun T => ∀ (D : T → Binary K S), (product D).tensor = ∏ i, (D i).tensor) + ?_ ?_ ?_ I D + · intro A B _ e ih V + let := Fintype.ofEquiv B e.symm + rw [← e.prod_comp (fun i => (V i).tensor), ← ih (fun i => V (e i))] + refine tensor_relabel (fun s => Equiv.sigmaCongrLeft (β := fun i => (V i).port s) e) ?_ + exact fun x => (e.prod_comp (fun i => (V i).value (fun s j => x s ⟨i, j⟩))).symm + · intro V + rw [Finset.prod_of_isEmpty] + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (fun s => + Equiv.ofUnique ((Σ i, (V i).port s) → Bool) Unit) fun x => ?_ + rw [raw_coeff] + change (∏ i, (V i).value (fun s j => x s ⟨i, j⟩)) = ∑ _ : Unit, ∏ _ : S, (1 : K) + simp + · intro A _ ih V + rw [Fintype.prod_option, ← ih (fun i => V (some i)), ← tensor_of_join] + refine tensor_relabel (fun s => splitPorts (fun i => (V i).port s)) ?_ + exact fun x => Fintype.prod_option (fun i => (V i).value (fun s j => x s ⟨i, j⟩)) + +open Classical in +theorem tensor_of_batch (D : Binary K S) (n : ℕ) : (D.batch n).tensor = D.tensor ^ n := by + calc + _ = (product (fun _ : Fin n => D)).tensor := + tensor_relabel (fun s => Equiv.sigmaEquivProd _ _) (fun _ => rfl) + _ = _ := by rw [tensor_of_product]; simp + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Binary +end + +/- # Local operators on bundles of dyadic width -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Classical in +/-- The quantity computed by `X → Fin (2 ^ h) → Bool`. -/ +abbrev Lines (h : ℕ) (X : Type) := X → Fin (2 ^ h) → Bool + +open Classical in +/-- The condition `∀ h, Lines h X → Lines h Y → K` on the specified data. -/ +abbrev Frame (K X Y : Type) := ∀ h, Lines h X → Lines h Y → K + +namespace Frame + +variable {K X Y Z U V I : Type} [Field K] + +open Classical in +/-- The indexed operation `f h (fun i k => x (.inl i, k)) (fun j k => x (.inr j, k))`. -/ +def weight (f : Frame K X Y) (h : ℕ) (x : (X ⊕ Y) × Fin (2 ^ h) → Bool) : K := + f h (fun i k => x (.inl i, k)) (fun j k => x (.inr j, k)) + +open Classical in +/-- The condition `∃ c : ℕ, ∀ h : ℕ, Install.Weight K (weight f h) (c * Binary.scale h)` on the +specified data. -/ +def Fast (f : Frame K X Y) : Prop := + ∃ c : ℕ, ∀ h : ℕ, Install.Weight K (weight f h) (c * Binary.scale h) + +open Classical in +/-- Evaluates `f h (x ∘ i) (y ∘ j)` at the input `h x y`. -/ +def pull (f : Frame K X Y) (i : X → U) (j : Y → V) : Frame K U V := + fun h x y => f h (x ∘ i) (y ∘ j) + +open Classical in +/-- Evaluates `∏ i, f i h x y` at the input `h x y`. -/ +def product [Fintype I] (f : I → Frame K X Y) : Frame K X Y := + fun h x y => ∏ i, f i h x y + +open Classical in +/-- Evaluates `∑ y, f h x y * g h y z` at the input `h x z`. -/ +def compose [Fintype Y] (f : Frame K X Y) (g : Frame K Y Z) : Frame K X Z := + fun h x z => ∑ y, f h x y * g h y z + +open Classical in +/-- Evaluates `∏ i, k (fun j => x j i) (fun j => y j i)` at the input `_h x y`. -/ +def diagonal (k : (X → Bool) → (Y → Bool) → K) : Frame K X Y := + fun _h x y => ∏ i, k (fun j => x j i) (fun j => y j i) + +open Classical in +/-- Evaluates `if x = y then 1 else 0` at the input `_ x y`. -/ +def keep (K X : Type) [Field K] : Frame K X X := + fun _ x y => if x = y then 1 else 0 + +end Frame +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Exact branch indices of a scheduled inventory reduction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Routing + +variable {I E : Type} [DecidableEq I] (L : Finset I) (Q : (I → ℕ) → Intervention I E) + +/-- In the case `0, _`, this construction gives `Unit`. -/ +abbrev Branch : ℕ → (I → ℕ) → Type + | 0, _ => Unit + | k + 1, z => Σ j : (Q z).choice, Branch k ((Q z).next z j + Stock.copies L 1) + +instance finiteBranch : (k : ℕ) → (z : I → ℕ) → Fintype (Branch L Q k z) + | 0, _ => inferInstanceAs (Fintype Unit) + | k + 1, z => + letI : ∀ j, Fintype (Branch L Q k ((Q z).next z j + Stock.copies L 1)) := fun _ + => finiteBranch k _ + inferInstanceAs (Fintype (Σ j : (Q z).choice, Branch L Q k ((Q z).next z j + Stock.copies L 1))) + +variable [Fintype I] (Y : I → E → ℕ) + +/-- Install the current round's core links before the remaining links. +The terminal supplies for each remaining request are paid separately. -/ +def edges : (k : ℕ) → (z : I → ℕ) → Branch L Q k z → E → ℕ + | 0, z, _ => fun e => ∑ i, Y i e * z i + | k + 1, z, p => (Q z).core p.1 + edges k ((Q z).next z p.1 + Stock.copies L 1) p.2 + +theorem edges_cost [Fintype E] {a : I → ℝ} (hc : ∀ i, (∑ e, Y i e : ℕ) ≤ a i) + {B v : ℝ} {k : ℕ} {z : I → ℕ} (h : Runs L a Q B k z v) (p : Branch L Q k z) : + v + (∑ e, edges L Q Y k z p e : ℕ) ≤ B := by + induction k generalizing v z with + | zero => + change v + Stock.total a z ≤ B at h + refine le_trans ?_ h + simp only [edges, Finset.sum_comm (s := (Finset.univ : Finset E)), ← Finset.sum_mul, + Nat.cast_sum, Nat.cast_mul, Stock.total] + apply add_le_add le_rfl + apply Finset.sum_le_sum + intro i _ + rw [mul_comm, ← Nat.cast_sum] + exact mul_le_mul_of_nonneg_left (hc i) (Nat.cast_nonneg _) + | succ k ih => + have hs := ih (h.2 p.1) p.2 + simpa only [edges, Pi.add_apply, Finset.sum_add_distrib, Nat.cast_add, Intervention.cost, + add_assoc] using hs + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Addressing the copies of a substitution -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Layout + +open Routing.WordSum + +variable {S A X Y : Type} {m z n : ℕ} + +/-- Reindexes `Fin z × Fin m` and `Fin n` by an equivalence. -/ +def row (hn : n = m * z) : Fin z × Fin m ≃ Fin n := + finProdFinEquiv.trans (finCongr (by rw [hn, Nat.mul_comm])) + +/-- Reindexes `Fin z × Address 1 t` and `Address z t where toFun p` by an equivalence. -/ +def addresses (t : A → ℕ) (z : ℕ) : Fin z × Address 1 t ≃ Address z t where + toFun p := ⟨p.2.1, row (by simp) (p.1, p.2.2)⟩ + invFun p := + let yz := (row (m := t p.1 * 1) (z := z) (by simp)).symm p.2 + (yz.1, ⟨p.1, yz.2⟩) + left_inv p := by obtain ⟨k, a, i⟩ := p; simp + right_inv p := by obtain ⟨a, i⟩ := p; simp + +variable (hn : n = m * z) (t : A → ℕ) + +/-- Indexes the in ports by the coordinates of `Fin z × (Fin m × X)`. -/ +abbrev InPorts (X : Type) (m z : ℕ) := Fin z × (Fin m × X) +/-- Indexes the out ports by the coordinates of `Fin z × ((Fin m × A) ⊕ (Σ _ : Address 1 t, +Y))`. -/ +abbrev OutPorts (Y : Type) (t : A → ℕ) (m z : ℕ) := + Fin z × ((Fin m × A) ⊕ (Σ _ : Address 1 t, Y)) + +/-- The value specified by `x (((row hn).symm i).1, ((row hn).symm i).2, j)`. -/ +def input (x : InPorts X m z → Bool) (i : Fin n) (j : X) := + x (((row hn).symm i).1, ((row hn).symm i).2, j) + +/-- The value specified by `x (((row hn).symm i).1, .inl (((row hn).symm i).2, j))`. -/ +def code (x : OutPorts Y t m z → Bool) (i : Fin n) (j : A) := + x (((row hn).symm i).1, .inl (((row hn).symm i).2, j)) + +/-- The value specified by `x (((addresses t z).symm i).1, .inr ⟨((addresses t z).symm i).2, +j⟩)`. -/ +def supply (x : OutPorts Y t m z → Bool) (i : Address z t) (j : Y) := + x (((addresses t z).symm i).1, .inr ⟨((addresses t z).symm i).2, j⟩) + +/-- Chooses the operation for the left or right summand. -/ +def assemble (u : Fin n → S → A → Bool) (v : Address z t → S → Y → Bool) + (s : S) (p : OutPorts Y t m z) : Bool := + Sum.elim (fun k => u (row hn (p.1, k.1)) s k.2) + (fun k => v (addresses t z (p.1, k.1)) s k.2) p.2 + +theorem code_assemble (u : Fin n → S → A → Bool) (v : Address z t → S → Y → Bool) (s : S) : + code hn t (assemble hn t u v s) = fun i => u i s := by + funext i j + simp [code, assemble] + +theorem supply_assemble (u : Fin n → S → A → Bool) (v : Address z t → S → Y → Bool) (s : S) : + supply t (assemble hn t u v s) = fun i => v i s := by + funext i j + simp [supply, assemble] + +/-- Reindexes `(Fin n → S → A → Bool) × (Address z t → S → Y → Bool)` and `(S → OutPorts Y t m z +→ Bool) where toFun p` by an equivalence. -/ +def joined : + (Fin n → S → A → Bool) × (Address z t → S → Y → Bool) ≃ (S → OutPorts Y t m z → Bool) where + toFun p := assemble hn t p.1 p.2 + invFun f := (fun i s => code hn t (f s) i, fun j s => supply t (f s) j) + left_inv p := by simp only [code_assemble, supply_assemble] + right_inv f := by + funext s ⟨k, p⟩ + rcases p with ⟨i, j⟩ | ⟨i, j⟩ <;> simp [assemble, code, supply] + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Layout +end + +/- +# Supplies for a fixed rounded histogram + +The selector is encoded by one indicator bit per letter. Its tensor +is still bounded by the size of the alphabet, since only valid words +occur and all sites see the same word. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Spectral Routing.WordSum Finset + +variable {K S A X Y : Type} [Field K] [Fintype S] [Nonempty S] + [Fintype A] [DecidableEq A] [Fintype X] [Fintype Y] + +open Classical in +/-- Tests whether `a = b` holds. -/ +def encode (a b : A) : Bool := decide (a = b) + +open Classical in +/-- Returns `h.choose` when `h : ∃ a, x a = true` holds, and `a₀` otherwise. -/ +def decode (a₀ : A) (x : A → Bool) : A := + if h : ∃ a, x a = true then h.choose else a₀ + +open Classical in +@[simp] theorem decode_encode (a₀ a : A) : decode a₀ (encode a) = a := by + have h : ∃ b, encode a b = true := ⟨a, by simp [encode]⟩ + rw [decode, dite_eq_left h] + exact (of_decide_eq_true h.choose_spec).symm + +open Classical in +private theorem prod_delta {I Z : Type} [Fintype I] [DecidableEq Z] (x y : I → Z) : + (∏ i, if x i = y i then (1 : K) else 0) = if x = y then 1 else 0 := by + by_cases h : x = y + · simp [h] + rw [ite_eq_right h] + obtain ⟨i, hi⟩ := Function.ne_iff.mp h + exact prod_eq_zero (mem_univ i) (ite_eq_right hi) + +open Classical in +/-- The indexing data represented by `Binary.of (fun x : S → A → Bool => ∑ a, if x = fun _ => +encode a then 1 else 0)`. -/ +def selector (K S A : Type) [Field K] [Fintype S] [Fintype A] [DecidableEq A] : Binary K S := + Binary.of (fun x : S → A → Bool => ∑ a, if x = fun _ => encode a then 1 else 0) + +open Classical in +theorem selector_bound : (selector K S A).tensor ≤ (Fintype.card A : Tensor K S) := by + rw [← Tensor.diag_eq_natCast A] + change (Raw.diag K S A).Restricts (selector K S A).raw + refine ⟨fun _ (x : A → Bool) (a : A) => if x = encode a then 1 else 0, fun x => ?_⟩ + change S → A → Bool at x + refine (Binary.raw_coeff (selector K S A) x).trans ?_ + change (∑ a, if x = fun _ => encode a then (1 : K) else 0) = + ∑ a : A, ∏ s, ∑ j : A, (if x s = encode j then 1 else 0) * if j = a then 1 else 0 + simp only [mul_ite, mul_one, mul_zero, sum_ite_eq', mem_univ, ite_true] + exact sum_congr rfl fun a _ => (prod_delta x (fun _ => encode a)).symm + +open Classical in +/-- The indexed operation `((selector K S A).batch m).join (Binary.product fun j : Address 1 t +=> Binary.of (P j.1))`. -/ +def offer (P : A → (S → Y → Bool) → K) (m : ℕ) (t : A → ℕ) : Binary K S := + ((selector K S A).batch m).join (Binary.product fun j : Address 1 t => Binary.of (P j.1)) + +open Classical in +theorem offer_bound (P : A → (S → Y → Bool) → K) (m : ℕ) (t : A → ℕ) : + (offer P m t).tensor ≤ (Fintype.card A : Tensor K S) ^ m * ∏ a, (Binary.of (P a)).tensor ^ t a + := by + let : MulLeftMono (Tensor K S) := ⟨fun c a b h => Tensor.mul_le_mul_left _ _ _ h⟩ + rw [offer, Binary.tensor_of_join, Binary.tensor_of_batch, Binary.tensor_of_product, + Fintype.prod_sigma] + simp only [prod_const, card_univ, Fintype.card_fin, mul_one] + exact mul_le_mul_left (pow_le_pow_left' selector_bound m) _ + +variable {m z n : ℕ} (hn : n = m * z) + +omit [Nonempty S] [Fintype S] in +open Classical in +theorem demand_value (T : (S → X → Bool) → K) (x : S → Layout.InPorts X m z → Bool) : + (((Binary.of T).batch m).batch z).value x = + ∏ i, T (fun s => Layout.input hn (x s) i) := by + rw [← (Layout.row hn).prod_comp, Fintype.prod_prod_type] + change (∏ i : Fin z, ∏ j : Fin m, T (fun s k => x s (i, j, k))) = _ + apply prod_congr rfl + intro i _ + apply prod_congr rfl + intro j _ + congr 1 + funext s k + simp [Layout.input] + +omit [Nonempty S] in +open Classical in +theorem offer_value (P : A → (S → Y → Bool) → K) (t : A → ℕ) + (u : Fin n → S → A → Bool) (v : Address z t → S → Y → Bool) : + ((offer P m t).batch z).value (Layout.assemble hn t u v) = + (∑ w : Fin n → A, if u = fun i _ => encode (w i) then (1 : K) else 0) * + ∏ j, P j.1 (v j) := by + have h : (∏ i : Fin n, (selector K S A).value (u i)) = + ∑ w : Fin n → A, if u = fun i _ => encode (w i) then (1 : K) else 0 := by + change (∏ i : Fin n, ∑ a, if u i = fun _ => encode a then (1 : K) else 0) = _ + rw [Fintype.prod_sum] + exact sum_congr rfl fun w _ => prod_delta u (fun i _ => encode (w i)) + rw [← h, ← (Layout.row hn).prod_comp, ← (Layout.addresses t z).prod_comp, + Fintype.prod_prod_type, Fintype.prod_prod_type, ← prod_mul_distrib] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Local implementation of a word of selectors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Routing.WordSum + +variable {K S A X Y : Type} [Field K] [Fintype S] [Nonempty S] + [Fintype A] [DecidableEq A] [Fintype X] [Fintype Y] {n m z : ℕ} + +variable (T : (S → X → Bool) → K) (P : A → (S → Y → Bool) → K) + (L : A → S → (X → Bool) → (Y → Bool) → K) (U : A → S → (Y → Bool) → K) + (a₀ : A) (hn : n = m * z) (t : A → ℕ) + +open Classical in +/-- The word action of type `Binary.Action (((Binary.of T).batch m).batch z) ((offer P m +t).batch z)`, constructed using `fun i => decode a₀ (Layout.code hn t y i)`. -/ +def wordAction : Binary.Action (((Binary.of T).batch m).batch z) ((offer P m t).batch z) := + fun s x y => + let w := fun i => decode a₀ (Layout.code hn t y i) + (if profile a₀ m z w = t then 1 else 0) * + factor L U z w t s (Layout.input hn x) (Layout.supply t y) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Coefficient identity for the scaled local maps -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Routing.WordSum Finset + +variable {K S A X Y : Type} [Field K] [Fintype S] [Nonempty S] + [Fintype A] [DecidableEq A] [Fintype X] [Fintype Y] {n m z : ℕ} + +open Classical in +private theorem sum_codes {I J W : Type} [Fintype I] [Fintype J] [Fintype W] [DecidableEq I] + (u : W → I) (f : I → J → K) (g : J → K) : + (∑ i, ∑ j, f i j * ((∑ w, if i = u w then 1 else 0) * g j)) = + ∑ w, ∑ j, f (u w) j * g j := by + rw [sum_comm, sum_comm (s := (univ : Finset W))] + apply sum_congr rfl + intro j _ + simp only [sum_mul, mul_sum, ite_mul, mul_ite, one_mul, zero_mul, mul_zero] + rw [sum_comm] + simp + +variable (T : (S → X → Bool) → K) (P : A → (S → Y → Bool) → K) + (L : A → S → (X → Bool) → (Y → Bool) → K) (U : A → S → (Y → Bool) → K) + (a₀ : A) (hn : n = m * z) (t : A → ℕ) + +open Classical in +private theorem word_act (x : S → Layout.InPorts X m z → Bool) : + Binary.act _ _ (wordAction T P L U a₀ hn t) x = + ∑ w : Fin n → A, if profile a₀ m z w = t then + ∑ y : Address z t → S → Y → Bool, + (∏ s, factor L U z w t s (Layout.input hn (x s)) (fun i => y i s)) * + ∏ i, P i.1 (y i) else 0 := by + let f (u : Fin n → S → A → Bool) (v : Address z t → S → Y → Bool) := + ∏ s, wordAction T P L U a₀ hn t s (x s) (Layout.assemble hn t u v s) + let g (v : Address z t → S → Y → Bool) := ∏ i, P i.1 (v i) + let code (w : Fin n → A) : Fin n → S → A → Bool := fun i _ => encode (w i) + have he : Binary.act _ _ (wordAction T P L U a₀ hn t) x = + ∑ u, ∑ v, f u v * ((∑ w, if u = code w then 1 else 0) * g v) := by + let e : _ ≃ ((offer P m t).batch z).Assign := Layout.joined hn t + unfold Binary.act + rw [← e.sum_comp, Fintype.sum_prod_type] + apply sum_congr rfl + intro u _ + apply sum_congr rfl + intro v _ + exact congrArg (f u v * ·) (offer_value hn P t u v) + rw [he, sum_codes] + apply sum_congr rfl + intro w _ + have key (v : Address z t → S → Y → Bool) (s : S) : + wordAction T P L U a₀ hn t s (x s) (Layout.assemble hn t (code w) v s) = + (if profile a₀ m z w = t then 1 else 0) * + factor L U z w t s (Layout.input hn (x s)) (fun i => v i s) := by + simp only [wordAction, Layout.code_assemble, Layout.supply_assemble, code, decode_encode] + by_cases hh : profile a₀ m z w = t + · rw [ite_eq_left hh] + apply sum_congr rfl + intro v _ + unfold f + simp only [key, ite_eq_left hh, one_mul, g] + · rw [ite_eq_right hh] + apply sum_eq_zero + intro v _ + have hv : f (code w) v = 0 := by + apply prod_eq_zero (mem_univ (Classical.arbitrary S)) + rw [key, ite_eq_right hh, zero_mul] + rw [hv, zero_mul] + +open Classical in +theorem word_exact (hz : 0 < z) + (hT : ∀ x, T x = ∑ a, ∑ y, (∏ s, L a s (x s) (y s)) * P a y) + (hU : ∀ a, ∑ y, (∏ s, U a s (y s)) * P a y = 1) + (x : (((Binary.of T).batch m).batch z).Assign) : + (((Binary.of T).batch m).batch z).value x = + ∑ t : ↥(histograms A (m + Fintype.card A)), + Binary.act _ _ (wordAction T P L U a₀ hn t.val) x := by + change S → Layout.InPorts X m z → Bool at x + refine (demand_value hn T x).trans ((expand P L U hU T hT a₀ hn hz _).trans ?_) + exact sum_congr rfl fun t _ => (word_act T P L U a₀ hn t.val x).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Uniform implementation cost of a scaled word action -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Install Routing Routing.WordSum + +variable {K S A X Y : Type} + +open Classical in +/-- The word input and the two protocol ports name the same bits. -/ +private def ports {k m z : ℕ} (hn : 2 ^ k = m * z) (t : A → ℕ) : + Input A X Y k z t ≃ Layout.InPorts X m z ⊕ Layout.OutPorts Y t m z where + toFun + | .inl (i, .inl a) => + let j := (Layout.row hn).symm i + .inr (j.1, .inl (j.2, a)) + | .inl (i, .inr x) => + let j := (Layout.row hn).symm i + .inl (j.1, j.2, x) + | .inr (i, y) => + let j := (Layout.addresses t z).symm i + .inr (j.1, .inr ⟨j.2, y⟩) + invFun + | .inl (j, i, x) => .inl (Layout.row hn (j, i), .inr x) + | .inr (j, .inl (i, a)) => .inl (Layout.row hn (j, i), .inl a) + | .inr (j, .inr ⟨i, y⟩) => .inr (Layout.addresses t z (j, i), y) + left_inv + | .inl (i, .inl a) => by simp + | .inl (i, .inr x) => by simp + | .inr (i, y) => by simp + right_inv + | .inl (j, i, x) => by simp + | .inr (j, .inl (i, a)) => by simp + | .inr (j, .inr ⟨i, y⟩) => by simp + +open Classical in +private theorem shift_scale (b h : ℕ) : scale (b + h) ≤ scale b * Binary.scale h := by + unfold scale Binary.scale + rw [pow_add, mul_mul_mul_comm, ← mul_pow] + gcongr + nlinarith + +variable [Field K] [Fintype S] [Fintype A] [DecidableEq A] [Fintype X] [Fintype Y] + (T : (S → X → Bool) → K) (P : A → (S → Y → Bool) → K) + (L : A → S → (X → Bool) → (Y → Bool) → K) (U : A → S → (Y → Bool) → K) (a₀ : A) + +open Classical in +/-- The constants may depend on the block and the alphabets. The same +bound holds for every additional dyadic power and rounded profile. -/ +theorem word_cheap (b : ℕ) (hb : Fintype.card A ≤ 2 ^ b) : + ∃ c : ℕ, ∀ h : ℕ, ∀ t : ↥(histograms A (2 ^ b + Fintype.card A)), + Binary.Cheap _ _ (wordAction T P L U a₀ (pow_add 2 b h) t.val) (c * Binary.scale h) := by + obtain ⟨M, hM⟩ := work_size (A := A) (R := A) (B := X) (C := Y) + obtain ⟨N, hN⟩ := factor_net L U (decode a₀) + obtain ⟨Q, hQ⟩ := check_net (K := K) a₀ (decode a₀) + let c := 6 * M + 2 * Fintype.card A + Q + N + refine ⟨c * scale b, fun h t s => ?_⟩ + let k := b + h + let z := 2 ^ h + have hn : 2 ^ k = 2 ^ b * z := pow_add 2 b h + have ht (a) : t.val a * z ≤ 2 ^ (k + 1) := by + have hta : t.val a ≤ 2 ^ b + Fintype.card A := + (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ a)).trans_eq + (mem_histograms.mp t.property) + rw [pow_succ, hn] + calc + _ ≤ (2 ^ b + 2 ^ b) * z := Nat.mul_le_mul_right z (hta.trans (Nat.add_le_add_left hb _)) + _ = _ := by ring + let I := Input A X Y k z t.val + let e (j : Row k × A) : I := .inl (j.1, .inl j.2) + have test := (hQ k (2 ^ b) z hn (by positivity) t).pull e + have net := (test.mul (hN k z t.val ht s)).rename (ports hn t.val) + refine net.mono (le_trans (b := c * scale k) ?_ ?_) + · have hi : Fintype.card I ≤ M * scale k := + (Fintype.card_le_of_injective Sum.inl Sum.inl_injective).trans (hM k z t.val ht) + change 5 * Fintype.card I + (Fintype.card I + 2 * Fintype.card (Row k × A) + + Q * 2 ^ k * (k + 1)) + N * 2 ^ k * (k + 1) ^ 3 ≤ c * scale k + rw [Fintype.card_prod, Fintype.card_fin] + unfold c + unfold scale at hi ⊢ + ring_nf at hi ⊢ + omega + · rw [mul_assoc] + exact Nat.mul_le_mul_left _ (shift_scale b h) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # A rounded substitution has a uniformly fast local implementation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Spectral Routing Finset + +variable {K S A X Y : Type} [Field K] [Fintype S] [Nonempty S] + [Fintype A] [DecidableEq A] [Fintype X] [Fintype Y] + +open Classical in +private theorem scalar (P : (S → Y → Bool) → K) (hP : 1 ≤ (Binary.of P).tensor) : + ∃ U : S → (Y → Bool) → K, ∑ y, (∏ s, U s (y s)) * P y = 1 := by + change (Binary.of P).raw.Restricts 1 at hP + obtain ⟨U, h⟩ := (Raw.restricts_iff _ _).mp hP + refine ⟨fun s => U s (), ?_⟩ + have he := h (fun _ => ()) + have h1 : (1 : Raw K S).coeff (fun _ => ()) = 1 := by + change (∑ _ : Unit, ∏ _ : S, (1 : K)) = 1 + simp + rw [h1] at he + refine (sum_congr rfl fun y _ => ?_).trans he.symm + exact congrArg _ (Binary.raw_coeff (Binary.of P) y).symm + +open Classical in +theorem word_scalable (T : (S → X → Bool) → K) (P : A → (S → Y → Bool) → K) (a₀ : A) + (hT : (Binary.of T).tensor ≤ ∑ a, (Binary.of (P a)).tensor) + (hP : ∀ a, 1 ≤ (Binary.of (P a)).tensor) (b : ℕ) (hb : Fintype.card A ≤ 2 ^ b) : + Binary.Scalable ((Binary.of T).batch (2 ^ b)) + (fun t : ↥(histograms A (2 ^ b + Fintype.card A)) => offer P (2 ^ b) t.val) := by + obtain ⟨L, hL⟩ := (Binary.sum_action (Binary.of T) (fun a => Binary.of (P a))).mp hT + choose U hU using fun a => scalar (P a) (hP a) + obtain ⟨c, hc⟩ := word_cheap T P L U a₀ b hb + exact ⟨c, fun h => ⟨fun t => wordAction T P L U a₀ (pow_add 2 b h) t.val, + hc h, word_exact T P L U a₀ (pow_add 2 b h) (by positivity) hL hU⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Replay.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Replay.lean new file mode 100644 index 0000000000..257946160d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Replay.lean @@ -0,0 +1,551 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Focus +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Alignment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Rig + +/-! +# Local enumeration of terminal supplies + +A request may be visible in several charts. Only its depot contributes +copies, including when the depot has no pins for that request at this site. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral Finset + +variable {K S I I' : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + [Fintype I] [DecidableEq I] [Fintype I'] [DecidableEq I'] {N t t' : ℕ} + {A : Finset (Tensor K S)} {b : Market I N} {c : Market I' N} {s : I} {v : I'} + {g : b.Ports t} {g' : c.Ports t'} {z : b.Request A → ℕ} {z' : c.Request A → ℕ} + +open Classical in +/-- The defining condition `∀ (j : Near b s) (x : (b.code j.1).Req A) (x' : (c.code (r.near +j).1).Req A), HEq x x' → z (b.request A j.1 x) = z' (c.request A (r.near j).1 x')`. -/ +def Match.Stocks (r : Match A b c s v) (z : b.Request A → ℕ) (z' : c.Request A → ℕ) : Prop := + ∀ (j : Near b s) (x : (b.code j.1).Req A) (x' : (c.code (r.near j).1).Req A), + HEq x x' → z (b.request A j.1 x) = z' (c.request A (r.near j).1 x') + +omit [DecidableEq S] in +open Classical in +/-- Returns `z (b.request A j.1 x)` when `(b.depot A g (b.request A j.1 x)).1 = j.1` holds, and +`0` otherwise. -/ +def assigned (g : b.Ports t) (z : b.Request A → ℕ) (j : Near b s) (x : (b.code j.1).Req A) := + if (b.depot A g (b.request A j.1 x)).1 = j.1 then z (b.request A j.1 x) else 0 + +omit [DecidableEq S] in +open Classical in +/-- Indexes the supply unit by the coordinates of `Σ j : Near b s, Σ x : (b.code j.1).Req A, Fin +(assigned g z j x)`. -/ +abbrev SupplyUnit (g : b.Ports t) (z : b.Request A → ℕ) (s : I) := + Σ j : Near b s, Σ x : (b.code j.1).Req A, Fin (assigned g z j x) + +namespace SupplyUnit + +variable (u : SupplyUnit g z s) + +omit [DecidableEq S] in +open Classical in +/-- Computes the req by the application `b.request A u.1.1 u.2.1`. -/ +def req := b.request A u.1.1 u.2.1 + +open Classical in +omit [DecidableEq S] in +theorem depot : b.depot A g u.req = ⟨u.1.1, u.2.1⟩ := by + classical + have ha := u.2.2.pos + unfold assigned at ha + split at ha + · rename_i he + have hh := (b.depot_spec A g u.req).1 + change (b.depot A g u.req).1 = _ at he + generalize b.depot A g u.req = w at * + rcases w with ⟨i, x⟩ + change i = _ at he + subst i + have h : b.assign A _ (.inl x) = b.assign A _ (.inl u.2.1) := congrArg Sum.inl hh + rw [Sum.inl.inj (b.assign_injective A _ h)] + · exact (Nat.lt_irrefl _ ha).elim + +open Classical in +/-- Computes the copy by the application `Fin.cast (ite_eq_left (congrArg Sigma.fst (depot u))) +u.2.2`. -/ +def copy : Fin (z u.req) := + Fin.cast (ite_eq_left (congrArg Sigma.fst (depot u))) u.2.2 + +open Classical in +/-- Uses `⟨u.req, u.copy⟩` as the representation. -/ +def unit : Units A b z := ⟨u.req, u.copy⟩ + +open Classical in +omit [DecidableEq S] in +omit [DecidableEq S] in +theorem injective : Function.Injective (unit : SupplyUnit g z s → Units A b z) := by + classical + rintro ⟨⟨i, a⟩, x, k⟩ ⟨⟨i', a'⟩, x', k'⟩ h + have he := congrArg (fun p : Units A b z => b.depot A g p.1) h + simp only [unit, depot] at he + have hi : i = i' := congrArg Sigma.fst he + subst i' + have ha : a = a' := Subtype.ext ((b.name i).injective (a.property.trans a'.property.symm)) + subst a' + have hx : x = x' := eq_of_heq (Sigma.mk.inj he).2 + subst x' + have hk : k = k' := Fin.ext (congrArg (fun p : Units A b z => p.2.val) h) + rw [hk] + +open Classical in +omit [DecidableEq S] in +omit [DecidableEq S] in +theorem exists_unit (w : Units A b z) (h : ∃ i, b.name (b.depot A g w.1).1 i = s) : + ∃ u : SupplyUnit g z s, u.unit = w := by + classical + have he := (b.depot_spec A g w.1).1 + generalize hd : b.depot A g w.1 = j at h he + rcases j with ⟨j, x⟩ + rcases w with ⟨w, k⟩ + change b.request A j x = w at he + subst w + obtain ⟨i, hi⟩ := h + let l : Near b s := ⟨j, ⟨i, hi⟩⟩ + have hk : assigned g z l x = z (b.request A j x) := ite_eq_left (congrArg Sigma.fst hd) + exact ⟨⟨l, x, Fin.cast hk.symm k⟩, rfl⟩ + +open Classical in +@[to_additive sum_units] +theorem prod_units {P : Type} [CommMonoid P] (f : Units A b z → P) + (hf : ∀ w, (∀ i, b.name (b.depot A g w.1).1 i ≠ s) → f w = 1) : + ∏ w, f w = ∏ u : SupplyUnit g z s, f u.unit := by + let e : SupplyUnit g z s ↪ Units A b z := ⟨unit, injective⟩ + change _ = ∏ u, f (e u) + rw [← prod_map] + symm + refine prod_subset (subset_univ _) fun w _ hw => hf w fun i hi => ?_ + obtain ⟨u, rfl⟩ := exists_unit w ⟨i, hi⟩ + exact hw (mem_map_of_mem e (mem_univ u)) + +end SupplyUnit + +variable (r : Match A b c s v) (hd : r.depots g g') (hz : r.Stocks z z') + +include hd hz in +open Classical in +omit [DecidableEq S] in +theorem Match.assigned_eq (j : Near b s) + (x : (b.code j.1).Req A) (x' : (c.code (r.near j).1).Req A) (he : HEq x x') : + assigned g z j x = assigned g' z' (r.near j) x' := by + classical + simp only [assigned, hd j x x' he, hz j x x' he] + +include hd hz in +open Classical in +/-- Reindexes `SupplyUnit g z s` and `SupplyUnit g' z' v` by an equivalence. -/ +def Match.supplyUnits : SupplyUnit g z s ≃ SupplyUnit g' z' v := + Equiv.sigmaCongr r.near fun j => + Equiv.sigmaCongr (Equiv.cast (congrArg (fun i : Shape N => i.Req A) (r.same j))) fun x => + finCongr (r.assigned_eq hd hz j x _ (cast_heq _ _).symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Local dependence of supply counts and copy positions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral Finset + +variable {K S I I' : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + [Fintype I] [DecidableEq I] [Fintype I'] [DecidableEq I'] {N t t' : ℕ} + {A : Finset (Tensor K S)} {b : Market I N} {c : Market I' N} {s : I} {v : I'} + {g : b.Ports t} {g' : c.Ports t'} {z : b.Request A → ℕ} {z' : c.Request A → ℕ} + +open Classical in +/-- Indexes the source spot by the coordinates of `Σ j : Spot N, j.1.Req A`. -/ +abbrev SourceSpot (A : Finset (Tensor K S)) (N : ℕ) := Σ j : Spot N, j.1.Req A + +open Classical in +/-- Uses `⟨Protocol.spot u.1, u.2.1⟩` as the representation. -/ +def SupplyUnit.spot (u : SupplyUnit g z s) : SourceSpot A N := ⟨Protocol.spot u.1, u.2.1⟩ + +variable (r : Match A b c s v) (hd : r.depots g g') (hz : r.Stocks z z') + (d M : ℕ) + +open Classical in +omit [DecidableEq S] in +theorem Match.supply_spot (u : SupplyUnit g z s) : + u.spot = (r.supplyUnits hd hz u).spot := + Sigma.ext (r.spot_eq u.1) (cast_heq _ _).symm + +open Classical in +private def indexSpot (a : SourceSpot A N) := (Fintype.equivFin (a.1.1.Req A) a.2).val + +open Classical in +private theorem SupplyUnit.key_eq (u : SupplyUnit g z s) : + supplyKey A b g z u.unit = Encodable.encode (indexSpot u.spot, u.copy.val) := by + unfold supplyKey SupplyUnit.unit + rw [u.depot] + rfl + +open Classical in +theorem Match.key_supply (u : SupplyUnit g z s) : + supplyKey A b g z u.unit = supplyKey A c g' z' (r.supplyUnits hd hz u).unit := by + rw [SupplyUnit.key_eq, SupplyUnit.key_eq, r.supply_spot hd hz u] + rfl + +open Classical in +/-- Computes the edge pins by the application `Pin (localEdge K p.1) p.2`. -/ +abbrev Spot.edgePins (p : Spot N) (K : Type) [Field K] := Pin (localEdge K p.1) p.2 + +open Classical in +theorem SupplyUnit.tally_at (u : SupplyUnit g z s) (x : (Protocol.spot u.1).edgePins K) : + b.tally A d M g u.req (placeEdge K u.1 x).1 = (b.code u.1.1).route A d M u.2.1 x.1 := by + unfold Market.tally + rw [u.depot] + let i := u.1.1 + let f (v : (b.shape i).edges) : b.Edge := ⟨i, v⟩ + exact Stock.collect_inj (g := f) (fun _ _ e => eq_of_heq (Sigma.mk.inj e).2) + ((b.code i).route A d M u.2.1) x.1 + +open Classical in +theorem SupplyUnit.tally_away (u : SupplyUnit g z s) (j : Near b s) + (hne : u.1 ≠ j) (x : (Protocol.spot j).edgePins K) : + b.tally A d M g u.req (placeEdge K j x).1 = 0 := by + by_contra h + have e := tally_origin A d M b g u.req _ h + rw [u.depot] at e + change u.1.1 = j.1 at e + rcases u with ⟨⟨i, p⟩, u⟩ + rcases j with ⟨j, q⟩ + change i = j at e + subst j + exact hne (congrArg (Sigma.mk i) (Subtype.ext ((b.name i).injective (p.property.trans + q.property.symm)))) + +open Classical in +theorem Match.tally_unit (u : SupplyUnit g z s) : + Pin.Same r.core (b.tally A d M g u.req) (c.tally A d M g' (r.supplyUnits hd hz u).req) := by + intro p + have hex : ∃ (j : Near b s) (x : (spot j).edgePins K), placeEdge K j x = p := by + obtain ⟨a, l, h⟩ := placeEdge_surj p p.1.1 p.1.2 rfl + exact ⟨⟨p.1.1, a⟩, ⟨p.1.2, l⟩, h⟩ + obtain ⟨j, x, rfl⟩ := hex + let y := cast (congrArg (fun i : Spot N => i.edgePins K) (r.spot_eq j)) x + rw [r.core_eq j x y (cast_heq _ _).symm] + by_cases h : u.1 = j + · subst j + let w := r.supplyUnits hd hz u + have he : (⟨u.spot, x⟩ : Σ p : SourceSpot A N, p.1.edgePins K) = ⟨w.spot, y⟩ := + Sigma.ext (r.supply_spot hd hz u) (cast_heq _ _).symm + exact (u.tally_at d M x).trans ((congrArg (fun p : Σ a : SourceSpot A N, a.1.edgePins K => + p.1.1.1.route A d M p.1.2 p.2.1) he).trans (w.tally_at d M y).symm) + · exact (u.tally_away d M j h x).trans ((r.supplyUnits hd hz u).tally_away d M (r.near j) + (r.near.injective.ne h) y).symm + +open Classical in +theorem tally_absent (u : Units A b z) (h : ∀ i, b.name (b.depot A g u.1).1 i ≠ s) + (p : Pin (edge K b) s) : b.tally A d M g u.1 p.1 = 0 := by + by_contra hn + have he := tally_origin A d M b g _ _ hn + obtain ⟨i, _, _⟩ := placeEdge_surj p p.1.1 p.1.2 rfl + rw [he] at h + exact h i i.property + +open Classical in +theorem Match.count_supply (p : Pin (edge K b) s) (P : ℕ → Prop) [DecidablePred P] + (hd : r.depots g g') (hz : r.Stocks z z') : + (∑ i : Units A b z, if P (supplyKey A b g z i) then b.tally A d M g i.1 p.1 else 0) = + ∑ i : Units A c z', if P (supplyKey A c g' z' i) then c.tally A d M g' i.1 (r.core p).1 else + 0 := by + rw [SupplyUnit.sum_units (g := g) (s := s) _ (by + intro i hi; rw [tally_absent d M i hi p, ite_self]), + SupplyUnit.sum_units (g := g') (s := v) _ (by + intro i hi; rw [tally_absent d M i hi (r.core p), ite_self]), + ← (r.supplyUnits hd hz).sum_comp] + refine sum_congr rfl fun i _ => ?_ + rw [r.key_supply hd hz] + exact congrArg (fun n => if P _ then n else 0) (r.tally_unit hd hz d M i p) + +open Classical in +theorem Match.total_supply (hd : r.depots g g') (hz : r.Stocks z z') : + Pin.Same r.core (fun e => ∑ i, b.tally A d M g i e * z i) + (fun e => ∑ i, c.tally A d M g' i e * z' i) := by + intro p + have h := r.count_supply d M p (fun _ => True) hd hz + simp only [ite_true, Units, Fintype.sum_sigma, Finset.sum_const, Finset.card_univ, + Fintype.card_fin, nsmul_eq_mul, Nat.cast_id] at h + exact (sum_congr rfl (fun _ _ => mul_comm _ _)).trans + (h.trans (sum_congr rfl (fun _ _ => mul_comm _ _))) + +open Classical in +theorem Match.offset_supply (u : SupplyUnit g z s) (p : Pin (edge K b) s) : + offset (fun i => b.tally A d M g i.1 p.1) (supplyKey A b g z) u.unit = + offset (fun i => c.tally A d M g' i.1 (r.core p).1) (supplyKey A c g' z') + (r.supplyUnits hd hz u).unit := by + simp only [offset, sum_filter, ← r.key_supply hd hz u] + exact r.count_supply d M p (· < supplyKey A b g z u.unit) hd hz + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Individual terminal factors and their port numbers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral Finset Board + +variable {K S I : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + [Fintype I] [DecidableEq I] {N t : ℕ} + {A : Finset (Tensor K S)} {b : Market I N} {s : I} + {g : b.Ports t} {z : b.Request A → ℕ} (d M : ℕ) + +open Classical in +/-- The sum of `b.tally A d M g i e * z i` indexed by `i`. -/ +abbrev totalTally (g : b.Ports t) (z : b.Request A → ℕ) (e : b.Edge) := + ∑ i, b.tally A d M g i e * z i + +open Classical in +theorem tally_sum (g : b.Ports t) (z : b.Request A → ℕ) : + (fun e => ∑ j : Units A b z, b.tally A d M g j.1 e) = totalTally d M g z := by + funext e + simp [Units, totalTally, Fintype.sum_sigma, mul_comm] + +open Classical in +/-- The indexed operation `(ordersEq (edge K b) (tally_sum d M g z)).local s ∘ Pin.assign (edge +K b) (fun e => (pack _ _ (supplyOrdered A d M b g z e)).symm) w s`. -/ +def supplyPort (g : b.Ports t) (w : Units A b z) (s : I) : + (orders (edge K b) (b.tally A d M g w.1)).localPort s → + (orders (edge K b) (totalTally d M g z)).localPort s := + (ordersEq (edge K b) (tally_sum d M g z)).local s ∘ + Pin.assign (edge K b) (fun e => (pack _ _ (supplyOrdered A d M b g z e)).symm) w s + +open Classical in +/-- Transports an index across an equality of bounds. -/ +def supplyNumber (g : b.Ports t) (w : Units A b z) (e : b.Edge) + (j : Fin (b.tally A d M g w.1 e)) : Fin (totalTally d M g z e) := + Fin.cast (congrFun (tally_sum d M g z) e) ((pack _ _ (supplyOrdered A d M b g z e)) ⟨w, j⟩) + +open Classical in +theorem supplyPort_copy (g : b.Ports t) (w : Units A b z) (i : Pin (edge K b) s) + (j : Fin (b.tally A d M g w.1 i.1)) : + supplyPort d M g w s (Pin.atCopy i j) = Pin.atCopy i (supplyNumber d M g w i.1 j) := by + unfold supplyPort + rw [Function.comp_apply, Pin.assign_atCopy] + rfl + +variable (hr : b.ready A d) (hc : UniformCap N A M) + +open Classical in +theorem supply_absent (x : b.Request A) (h : ∀ i, b.name (b.depot A g x).1 i ≠ s) : + (supplyAt A d M b g hr hc x).kernel () s = fun _ _ _ => 1 := by + simp only [supplyAt, supplyFrom, Expansion.rename, Expansion.absent _ _ h ()] + rfl + +open Classical in +/-- The indexed operation `Frame.pull ((supplyAt A d M b g hr hc w.1).kernel () s) (fun j => +Pin.atCopy ⟨w.1, j⟩ w.2) (supplyPort d M g w s)`. -/ +def supplyFactor (g : b.Ports t) (w : Units A b z) (s : I) : + Frame K ((orders (request b A) z).localPort s) + ((orders (edge K b) (totalTally d M g z)).localPort s) := + Frame.pull ((supplyAt A d M b g hr hc w.1).kernel () s) + (fun j => Pin.atCopy ⟨w.1, j⟩ w.2) (supplyPort d M g w s) + +open Classical in +theorem terminal_factors (g : b.Ports t) (z : b.Request A → ℕ) (s : I) : + (terminal A d M b g z hr hc).kernel () s = + Frame.product (fun u : SupplyUnit g z s => supplyFactor d M hr hc g u.unit s) := by + funext h x y + apply SupplyUnit.prod_units (g := g) (s := s) (fun w => supplyFactor d M hr hc g w s h x y) + intro w hw + rw [supplyFactor, supply_absent d M hr hc _ hw] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # A terminal factor reads only the pins and ordinals of its own local route -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral Finset Board + +variable {K S I : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + [Fintype I] [DecidableEq I] {N t : ℕ} + {A : Finset (Tensor K S)} {b : Market I N} {s : I} + {g : b.Ports t} {z : b.Request A → ℕ} (d M : ℕ) + +open Classical in +/-- Computes the req pins by the application `Pin (localRequest p.1 A) p.2`. -/ +abbrev Spot.reqPins (p : Spot N) (A : Finset (Tensor K S)) := Pin (localRequest p.1 A) p.2 + +open Classical in +/-- Feed a pin and copy number to a local program without any global names. -/ +def SourceSpot.run (p : SourceSpot A N) (h : ℕ) + (X : Lines h (p.1.reqPins A)) (Y : Lines h (p.1.edgePins K × ℕ)) : K := + if he : p.1.1.2.Direct K (p.1.1.2.tensor A (.inl p.2)) (p.1.1.priceCap A d M p.2) then + (localSupply A d M p.1.1 p.2 he).kernel () p.1.2 h (fun i => X ⟨p.2, i⟩) + (fun o => Y (⟨o.1.1.1, ⟨o.1.2, o.2⟩⟩, o.1.1.2.val)) + else 0 + +variable (hr : b.ready A d) (hc : UniformCap N A M) (u : SupplyUnit g z s) + +open Classical in +theorem SupplyUnit.local_value (h : ℕ) (X : Lines h (Pin (request b A) s)) + (Y : Lines h (Pin (edge K b) s × ℕ)) : + (supplyAt A d M b g hr hc u.req).kernel () s h (fun i => X ⟨u.req, i⟩) + (fun o => Y (⟨o.1.1.1, ⟨o.1.2, o.2⟩⟩, o.1.1.2.val)) = + u.spot.run d M h (fun l => X (placeReq A u.1 l)) + (fun p => Y (placeEdge K u.1 p.1, p.2)) := by + let F (w : b.Source A) (hw : b.request A w.1 w.2 = u.req) := + (supplyFrom A d M b hr hc u.req w hw).kernel () s h (fun i => X ⟨u.req, i⟩) + (fun o => Y (⟨o.1.1.1, ⟨o.1.2, o.2⟩⟩, o.1.1.2.val)) + change F (b.depot A g u.req) (b.depot_spec A g u.req).1 = _ + have key : F (b.depot A g u.req) (b.depot_spec A g u.req).1 = F ⟨u.1.1, u.2.1⟩ rfl := by + simp only [u.depot] + rw [key] + let v := localSupply A d M (b.code u.1.1) u.2.1 (b.local_route A d M hr hc _ _) + have he : u.spot.1.1.2.Direct K (u.spot.1.1.2.tensor A (.inl u.spot.2)) + (u.spot.1.1.priceCap A d M u.spot.2) := b.local_route A d M hr hc _ _ + rw [SourceSpot.run, dite_eq_left he] + unfold F supplyFrom Expansion.rename + dsimp only + rw [v.placed (b.name u.1.1) u.1.2 ()] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Matched charts give identical terminal kernels on corresponding pins -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral Finset Board + +namespace Pin + +variable {K S S' I I' : Type} [Field K] [Fintype I] [Fintype I'] + {T : I → Board K S} {T' : I' → Board K S'} {s : S} {s' : S'} + {z : I → ℕ} {z' : I' → ℕ} {h : ℕ} + +open Classical in +/-- Returns `x (atCopy p ⟨k, hk⟩)` when `hk : k < z p.1` holds, and `fun _ => false` otherwise. -/ +def read (x : Lines h ((orders T z).localPort s)) (p : Pin T s) (k : ℕ) : Fin (2 ^ h) → Bool := + if hk : k < z p.1 then x (atCopy p ⟨k, hk⟩) else fun _ => false + +open Classical in +theorem read_copy (x : Lines h ((orders T z).localPort s)) (p : Pin T s) (k : Fin (z p.1)) : + read x p k = x (atCopy p k) := dite_eq_left k.isLt + +open Classical in +theorem read_lift (e : Pin T s ≃ Pin T' s') (hz : Same e z z') + (x : Lines h ((orders T' z').localPort s')) (p : Pin T s) (k : ℕ) : + read (x ∘ lift e hz) p k = read x (e p) k := by + by_cases hk : k < z p.1 + · rw [read, read, dite_eq_left hk, dite_eq_left (lt_of_lt_of_eq hk (hz p))] + rfl + · have hk' : ¬ k < z' (e p).1 := by rw [← hz p]; exact hk + rw [read, read, dite_eq_right hk, dite_eq_right hk'] + +end Pin + +variable {K S I I' : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + [Fintype I] [DecidableEq I] [Fintype I'] [DecidableEq I'] {N t t' : ℕ} + {A : Finset (Tensor K S)} {b : Market I N} {c : Market I' N} {s : I} {v : I'} + {g : b.Ports t} {g' : c.Ports t'} {z : b.Request A → ℕ} {z' : c.Request A → ℕ} + (d M : ℕ) + +open Classical in +private def baseOffset (u : SupplyUnit g z s) (p : Pin (edge K b) s) := + offset (fun i => b.tally A d M g i.1 p.1) (supplyKey A b g z) u.unit + +open Classical in +private theorem packed_factor (hr : b.ready A d) (hc : UniformCap N A M) + (u : SupplyUnit g z s) (h : ℕ) (x : Lines h ((orders (request b A) z).localPort s)) + (y : Lines h ((orders (edge K b) (totalTally d M g z)).localPort s)) : + supplyFactor d M hr hc g u.unit s h x y = + u.spot.run d M h (fun p => Pin.read x (placeReq A u.1 p) u.copy.val) + (fun q => let p := placeEdge K u.1 q.1; Pin.read y p (baseOffset d M u p + q.2)) := by + let X := fun p => Pin.read x p u.copy.val + let Y := fun q : Pin (edge K b) s × ℕ => Pin.read y q.1 (baseOffset d M u q.1 + q.2) + refine Eq.trans ?_ (u.local_value d M hr hc h X Y) + apply congrArg₂ ((supplyAt A d M b g hr hc u.req).kernel () s h) + · exact funext fun j => (Pin.read_copy x ⟨u.req, j⟩ u.copy).symm + · funext o + obtain ⟨p, l, rfl⟩ := Pin.exists_atCopy o + change y (supplyPort d M g u.unit s (Pin.atCopy p l)) = _ + rw [supplyPort_copy] + refine (Pin.read_copy y p (supplyNumber d M g u.unit p.1 l)).symm.trans ?_ + change Pin.read y p (supplyNumber d M g u.unit p.1 l).val = + Pin.read y p (baseOffset d M u p + l.val) + congr 1 + +open Classical in +private theorem SourceSpot.run_eq {p q : SourceSpot A N} (he : p = q) (h : ℕ) + {x : Lines h (p.1.reqPins A)} {x' : Lines h (q.1.reqPins A)} + {y : Lines h (p.1.edgePins K × ℕ)} {y' : Lines h (q.1.edgePins K × ℕ)} + (hx : ∀ i j, HEq i j → x i = x' j) (hy : ∀ i j k, HEq i j → y (i, k) = y' (j, k)) : + p.run d M h x y = q.run d M h x' y' := by + subst q + exact congrArg₂ (p.run d M h) (funext fun i => hx i i .rfl) + (funext fun i => hy i.1 i.1 i.2 .rfl) + +open Classical in +theorem Match.terminal_rel (r : Match A b c s v) (hd : r.depots g g') (hz : r.Stocks z z') + (d M : ℕ) (hr : b.ready A d) (hr' : c.ready A d) (hc : UniformCap N A M) : + ∃ hw : Pin.Same r.core (totalTally d M g z) (totalTally d M g' z'), + ∀ he : Pin.Same r.req z z', Frame.Rel (Pin.lift r.req he) (Pin.lift r.core hw) + ((terminal A d M b g z hr hc).kernel () s) ((terminal A d M c g' z' hr' hc).kernel () v) + := by + refine ⟨r.total_supply d M hd hz, fun he => ?_⟩ + rw [terminal_factors, terminal_factors] + apply Frame.Rel.product (r.supplyUnits hd hz) + intro u h x y + rw [packed_factor, packed_factor] + apply SourceSpot.run_eq d M (r.supply_spot hd hz u) + · intro i j hij + rw [Pin.read_lift, r.req_eq u.1 i j hij] + rfl + · intro i j k hij + dsimp only + rw [Pin.read_lift] + unfold baseOffset + rw [r.offset_supply hd hz d M u (placeEdge K u.1 i), r.core_eq u.1 i j hij] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Matching local schedules +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Match +open Routing Spectral + +variable {K S I I' : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype I] [DecidableEq I] [Fintype I'] [DecidableEq I'] + {N M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} {b : Market I N} {c : Market I' N} + {s : I} {t : I'} (f : Match A b c s t) (a : Atlas N A M ρ) (μ d m : ℕ) + +open scoped Classical in +/-- In the case `0, z, y, _, _`, this construction gives `f.Stocks z y`. -/ +def Replay : (k : ℕ) → (z : b.Request A → ℕ) → (y : c.Request A → ℕ) → + b.Path a μ d m k z → c.Path a μ d m k y → Prop + | 0, z, y, _, _ => f.Stocks z y + | k + 1, z, y, u, v => + f.Stocks z y ∧ + (∀ j : Near b s, HEq (b.record a (b.stockPrice (M := M) μ d z) m u.1 j.1) + (c.record a (c.stockPrice (M := M) μ d y) m v.1 (f.near j).1)) ∧ + Replay k (b.after a μ d m z u.1) (c.after a μ d m y v.1) u.2 v.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Match +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/ReplayRel.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/ReplayRel.lean new file mode 100644 index 0000000000..a3bd6bb461 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/ReplayRel.lean @@ -0,0 +1,952 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Alignment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Focus +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Replay + +/-! # Commuting local reindexings of inventories -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board + +variable {K S T : Type} {s : S} {t : T} {D D' D'' : Board K S} {V V' V'' : Board K T} + +/-- The condition `∀ u, f (a.local s u) = b.local t (e u)` on the specified data. -/ +def Square (a : Rename D D') (b : Rename V V') + (e : D.localPort s ≃ V.localPort t) (f : D'.localPort s ≃ V'.localPort t) : Prop := + ∀ u, f (a.local s u) = b.local t (e u) + +namespace Square + +variable {a : Rename D D'} {b : Rename V V'} + {e : D.localPort s ≃ V.localPort t} {f : D'.localPort s ≃ V'.localPort t} + +theorem refl (e : D.localPort s ≃ V.localPort t) : Square (.refl D) (.refl V) e e := + fun _ => rfl + +theorem trans {a' : Rename D' D''} {b' : Rename V' V''} {g : D''.localPort s ≃ V''.localPort t} + (h : Square a b e f) (k : Square a' b' f g) : Square (a.trans a') (b.trans b') e g := + fun i => (k (a.local s i)).trans (congrArg (b'.local t) (h i)) + +theorem symm (h : Square a b e f) : Square a.symm b.symm f e := by + intro i + have he : a.local s (a.symm.local s i) = i := Subtype.ext (a.eqv.apply_symm_apply _) + have hh := h (a.symm.local s i) + rw [he] at hh + exact Subtype.ext (b.eqv.eq_symm_apply.mpr (congrArg Subtype.val hh.symm)) + +variable [Field K] + +theorem join {A A' : Board K S} {B B' : Board K T} + {c : Rename A A'} {d : Rename B B'} + {g : A.localPort s ≃ B.localPort t} {l : A'.localPort s ≃ B'.localPort t} + (h : Square a b e f) (k : Square c d g l) : + Square (a.join c) (b.join d) (joinPorts e g) (joinPorts f l) := by + rintro ⟨i | i, hi⟩ + · exact congrArg (V'.joinLeft B' t) (h ⟨i, hi⟩) + · exact congrArg (V'.joinRight B' t) (k ⟨i, hi⟩) + +theorem swap (e : D.localPort s ≃ V.localPort t) (f : D'.localPort s ≃ V'.localPort t) : + Square (D.swap D') (V.swap V') (joinPorts e f) (joinPorts f e) := by + rintro ⟨i | i, hi⟩ <;> rfl + +theorem rotate (e : D.localPort s ≃ V.localPort t) (f : D'.localPort s ≃ V'.localPort t) + (g : D''.localPort s ≃ V''.localPort t) : + Square (D.rotate D' D'') (V.rotate V' V'') (joinPorts (joinPorts e f) g) + (joinPorts (joinPorts g e) f) := by + rintro ⟨(i|i)|i, hi⟩ <;> rfl + +variable {I J : Type} [Fintype I] [Fintype J] {U : I → Board K S} {W : J → Board K T} + {z y : I → ℕ} {z' y' : J → ℕ} (p : Pin U s ≃ Pin W t) + +theorem orders_eq (h : z = y) (k : z' = y') (hz : Pin.Same p z z') (hy : Pin.Same p y y') : + Square (Board.ordersEq U h) (Board.ordersEq W k) (Pin.lift p hz) (Pin.lift p hy) := by + subst y + subst y' + rintro i + obtain ⟨j, a, rfl⟩ := Pin.exists_atCopy i + rfl + +private theorem add_left (i : Pin U s) (v : Fin (z i.1)) : + (Board.ordersAdd U z y).symm.local s ((orders U z).joinLeft (orders U y) s (i.atCopy v)) = + i.atCopy (z := z + y) (Fin.castAdd (y i.1) v) := by + apply Subtype.ext + exact orders_add_left U z y _ _ _ + +private theorem add_right (i : Pin U s) (v : Fin (y i.1)) : + (Board.ordersAdd U z y).symm.local s ((orders U z).joinRight (orders U y) s (i.atCopy v)) = + i.atCopy (z := z + y) (Fin.natAdd (z i.1) v) := by + apply Subtype.ext + exact orders_add_right U z y _ _ _ + +theorem orders_add (hz : Pin.Same p z z') (hy : Pin.Same p y y') : + Square (Board.ordersAdd U z y).symm (Board.ordersAdd W z' y').symm + (joinPorts (Pin.lift p hz) (Pin.lift p hy)) + (Pin.lift p (fun i => congrArg₂ (· + ·) (hz i) (hy i))) := by + intro u + have cases' : (∃ v, (orders U z).joinLeft (orders U y) s v = u) ∨ + (∃ v, (orders U z).joinRight (orders U y) s v = u) := by + obtain ⟨i | i, hi⟩ := u + · exact .inl ⟨⟨i, hi⟩, rfl⟩ + · exact .inr ⟨⟨i, hi⟩, rfl⟩ + rcases cases' with ⟨v, rfl⟩ | ⟨v, rfl⟩ <;> obtain ⟨j, a, rfl⟩ := Pin.exists_atCopy v + · rw [joinPorts_left, Pin.lift_atCopy, add_left, add_left] + rfl + · rw [joinPorts_right, Pin.lift_atCopy, add_right, add_right] + change Pin.atCopy (z := z' + y') (p j) (Fin.cast (congrArg₂ (· + + ·) (hz j) (hy j)) (Fin.natAdd (z j.1) a)) = _ + apply congrArg (Pin.atCopy (z := z' + y') (p j)) + exact Fin.ext (congrArg (· + a.val) (hz j)) + +end Square +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Board +end + +/- # Corresponding branches of two inventory schedules at one site -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing + +variable {K S S' I I' E E' : Type} [Field K] + [Fintype S] [Fintype S'] [Fintype I] [Fintype I'] [Fintype E] [Fintype E'] + {T : I → Board K S} {T' : I' → Board K S'} {V : E → Board K S} {V' : E' → Board K S'} + {s : S} {s' : S'} + +/-- The data for the move rel construction, including `take`, `put`, `core`, `rel`. -/ +structure MoveRel (e : Pin T s ≃ Pin T' s') (f : Pin V s ≃ Pin V' s') + {q : Intervention I E} {q' : Intervention I' E'} + (r : Executes T V q) (r' : Executes T' V' q') (j : q.choice) (j' : q'.choice) : Prop where + take : Pin.Same e q.take q'.take + put : Pin.Same e (q.put j) (q'.put j') + core : Pin.Same f (q.core j) (q'.core j') + rel : Frame.Rel (Pin.lift e take) (Board.joinPorts (Pin.lift e put) (Pin.lift f core)) + (r.kernel j s) (r'.kernel j' s') + +variable [DecidableEq I] [DecidableEq I'] + {Q : (I → ℕ) → Intervention I E} {Q' : (I' → ℕ) → Intervention I' E'} + {Y : I → E → ℕ} {Y' : I' → E' → ℕ} + +/-- In the case `0, z, z', p, p'`, this construction gives `∃ hw : Pin.Same f (edges L Q Y 0 z +p) (edges L' Q' Y' 0 z' p'),`. -/ +def RunRel (e : Pin T s ≃ Pin T' s') (f : Pin V s ≃ Pin V' s') + (close : Settlement T V Y) (close' : Settlement T' V' Y') + (run : ∀ z, Executes T V (Q z)) (run' : ∀ z, Executes T' V' (Q' z)) + {L : Finset I} {L' : Finset I'} : + (k : ℕ) → {z : I → ℕ} → {z' : I' → ℕ} → Branch L Q k z → Branch L' Q' k z' → Prop + | 0, z, z', p, p' => + ∃ hw : Pin.Same f (edges L Q Y 0 z p) (edges L' Q' Y' 0 z' p'), + ∀ hz : Pin.Same e z z', Frame.Rel (Pin.lift e hz) (Pin.lift f hw) + ((close z).kernel () s) ((close' z').kernel () s') + | k + 1, z, z', p, p' => + MoveRel e f (run z) (run' z') p.1 p'.1 ∧ + RunRel e f close close' run run' (L := L) (L' := L') k p.2 p'.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Transporting an execution between corresponding local coordinates + +The unchanged inventory and the newly installed links are reindexed +separately. Every local ordinal is preserved, even when the global +sets of labels, sites and possible branches differ. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Board + +variable {K S S' I I' E E' : Type} [Field K] + [Fintype S] [Fintype S'] [Fintype I] [Fintype I'] [Fintype E] [Fintype E'] + {T : I → Board K S} {T' : I' → Board K S'} {V : E → Board K S} {V' : E' → Board K S'} + {s : S} {s' : S'} {e : Pin T s ≃ Pin T' s'} {f : Pin V s ≃ Pin V' s'} + {q : Intervention I E} {q' : Intervention I' E'} + {r : Executes T V q} {r' : Executes T' V' q'} {j : q.choice} {j' : q'.choice} + {z : I → ℕ} {z' : I' → ℕ} + +omit [Field K] [Fintype S] [Fintype S'] [Fintype I] [Fintype I'] in +theorem Pin.Same.add {u : I → ℕ} {u' : I' → ℕ} + (h : Pin.Same e z z') (k : Pin.Same e u u') : Pin.Same e (z + u) (z' + u') := + fun i => congrArg₂ (· + ·) (h i) (k i) + +theorem MoveRel.next (h : MoveRel e f r r' j j') (hz : Pin.Same e z z') : + Pin.Same e (q.next z j) (q'.next z' j') := + fun i => congrArg₂ (· + ·) (congrArg₂ (· - ·) (hz i) (h.take i)) (h.put i) + +theorem MoveRel.takeStep (h : MoveRel e f r r' j j') (hz : Pin.Same e z z') + (ht : q.take ≤ z) (ht' : q'.take ≤ z') : + Frame.Rel (Pin.lift e hz) (joinPorts (Pin.lift e (h.next hz)) (Pin.lift f h.core)) + ((r.takeStep z ht).kernel j s) ((r'.takeStep z' ht').kernel j' s') := by + let w := z - q.take + let w' := z' - q'.take + have hw : Pin.Same e w w' := fun i => congrArg₂ (· - ·) (hz i) (h.take i) + have h₁ : q.take + w = z := funext fun i => Nat.add_sub_of_le (ht i) + have h₂ : q'.take + w' = z' := funext fun i => Nat.add_sub_of_le (ht' i) + have inp := (Square.orders_add e h.take hw).trans (Square.orders_eq e h₁ h₂ (h.take.add hw) hz) + have out := (Square.rotate (Pin.lift e h.put) (Pin.lift f h.core) (Pin.lift e hw)).trans + ((Square.orders_add e hw h.put).join (Square.refl (Pin.lift f h.core))) + exact (Kernel.keep_rel h.rel (Pin.lift e hw)).pull inp out + +variable [DecidableEq I] [DecidableEq I'] + {Q : (I → ℕ) → Intervention I E} {Q' : (I' → ℕ) → Intervention I' E'} + {Y : I → E → ℕ} {Y' : I' → E' → ℕ} + {L : Finset I} {L' : Finset I'} + {close : Settlement T V Y} {close' : Settlement T' V' Y'} + {run : ∀ z, Executes T V (Q z)} {run' : ∀ z, Executes T' V' (Q' z)} + {a : I → ℝ} {a' : I' → ℝ} {w w' v v' : ℝ} {k : ℕ} + +omit [Fintype I] [Fintype E] in +private theorem carry (q : Intervention I E) (ht : q.take + ≤ z) (j : q.choice) (L : Finset I) (k : ℕ) : + q.next z j + Stock.copies L 1 + Stock.copies L k = q.next (z + Stock.copies L (k + 1)) j := by + funext i + have hh : q.take i ≤ z i := ht i + by_cases h : i ∈ L <;> simp [Intervention.next, Stock.copies, h] + omega + +theorem execute_rel (h : Runs L a Q w k z v) (h' : Runs L' a' Q' w' k z' v') + (hL : ∀ n, Pin.Same e (Stock.copies L n) (Stock.copies L' n)) (hz : Pin.Same e z z') + {p : Branch L Q k z} {p' : Branch L' Q' k z'} + (hr : RunRel e f close close' run run' k p p') : + ∃ hw : Pin.Same f (edges L Q Y k z p) (edges L' Q' Y' k z' p'), + Frame.Rel (Pin.lift e (hz.add (hL k))) (Pin.lift f hw) + ((execute T V L Q Y close run k z v h).kernel p s) + ((execute T' V' L' Q' Y' close' run' k z' v' h').kernel p' s') := by + induction k generalizing z z' v v' with + | zero => + obtain ⟨hw, hk⟩ := hr + have ha : z = z + Stock.copies L 0 := by ext; simp [Stock.copies] + have hb : z' = z' + Stock.copies L' 0 := by ext; simp [Stock.copies] + refine ⟨hw, ?_⟩ + rw [execute, execute] + exact (hk hz).pull (Square.orders_eq e ha hb hz (hz.add (hL 0))) (Square.refl (Pin.lift f hw)) + | succ k ih => + obtain ⟨hs, hrest⟩ := hr + have hn := (hs.next hz).add (hL 1) + obtain ⟨hw, hk⟩ := ih (h.2 p.1) (h'.2 p'.1) hn hrest + have first := hs.takeStep (hz.add (hL (k + 1))) + (fun i => (h.1 i).trans (Nat.le_add_right ..)) + (fun i => (h'.1 i).trans (Nat.le_add_right ..)) + have hkeep := Kernel.keep_rel hk (Pin.lift f hs.core) + have inp := (Square.orders_eq e (carry _ h.1 p.1 L k) (carry _ h'.1 p'.1 L' k) + (hn.add (hL k)) (hs.next (hz.add (hL (k + 1))))).join (Square.refl (Pin.lift f hs.core)) + have out := (Square.swap (Pin.lift f hw) (Pin.lift f hs.core)).trans + (Square.orders_add f hs.core hw) + refine ⟨hs.core.add hw, ?_⟩ + classical + rw [execute, execute] + exact first.compose (hkeep.pull inp out) + +theorem execute_start_rel (h : Runs L a Q w k 0 0) (h' : Runs L' a' Q' w' k 0 0) + (hL : ∀ n, Pin.Same e (Stock.copies L n) (Stock.copies L' n)) + {p : Branch L Q k 0} {p' : Branch L' Q' k 0} + (hr : RunRel e f close close' run run' k p p') : + ∃ hw : Pin.Same f (edges L Q Y k 0 p) (edges L' Q' Y' k 0 p'), + Frame.Rel (Pin.lift e (hL k)) (Pin.lift f hw) + ((executeStart T V L Q Y close run h).kernel p s) + ((executeStart T' V' L' Q' Y' close' run' h').kernel p' s') := by + have hz : Pin.Same e 0 0 := fun _ => rfl + obtain ⟨hw, hk⟩ := execute_rel h h' hL hz hr + exact ⟨hw, hk.pull (Square.orders_eq e (zero_add _) (zero_add _) (hz.add (hL k)) (hL k)) + (Square.refl (Pin.lift f hw))⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Locality of simultaneous inventory moves + +Only the participants incident at the chosen site need to correspond. +Inactive participants add no stock and contribute the scalar one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Routing Board Finset + +variable {K S S' I I' E E' J J' : Type} [Field K] + [Fintype I] [Fintype I'] [Fintype E] [Fintype E'] [Fintype J] [Fintype J'] + {s : S} {s' : S'} {u : Finset J} {u' : Finset J'} + +@[to_additive] +theorem prod_match {M : Type} [CommMonoid M] {v : J → M} {w : J' → M} + (g : ↥u ≃ ↥u') (he : ∀ j : ↥u, v j = w (g j)) + (hv : ∀ j ∉ u, v j = 1) (hw : ∀ j ∉ u', w j = 1) : ∏ j, v j = ∏ j, w j := by + rw [← prod_subset (subset_univ u) (fun j _ hj => hv j hj), + ← prod_subset (subset_univ u') (fun j _ hj => hw j hj), + ← prod_coe_sort u v, ← prod_coe_sort u' w, ← g.prod_comp] + exact prod_congr rfl fun j _ => he j + +private def outputSlot (T : I → Board K S) (V : E → Board K S) + {p : J → I → ℕ} {c : J → E → ℕ} (a : Pin.Assignment p) (b : Pin.Assignment c) + (j : J) (s : S) : + ((orders T (p j)).join (orders V (c j))).localPort s → + ((orders T (fun i => ∑ j, p j i)).join (orders V (fun i => ∑ j, c j i))).localPort s := + ((unionJoin _ _).trans ((ordersSum T p a).symm.join (ordersSum V c b).symm)).local s ∘ + component (fun i => (orders T (p i)).join (orders V (c i))) s j + +variable {T : I → Board K S} {T' : I' → Board K S'} {V : E → Board K S} {V' : E' → Board K S'} + {e : Pin T s ≃ Pin T' s'} {f : Pin V s ≃ Pin V' s'} + +private theorem output_match {g : ↥u ≃ ↥u'} {p : J → I → ℕ} {c : J → E → ℕ} + {p' : J' → I' → ℕ} {c' : J' → E' → ℕ} + {a : Pin.Assignment p} {b : Pin.Assignment c} {a' : Pin.Assignment p'} {b' : Pin.Assignment c'} + (ha : Pin.Align e g a a') (hb : Pin.Align f g b b') + (hp : Pin.Same e (fun i => ∑ j, p j i) (fun i => ∑ j, p' j i)) + (hc : Pin.Same f (fun i => ∑ j, c j i) (fun i => ∑ j, c' j i)) + (j : ↥u) (hpj : Pin.Same e (p j) (p' (g j))) (hcj : Pin.Same f (c j) (c' (g j))) + (x : ((orders T (p j)).join (orders V (c j))).localPort s) : + joinPorts (Pin.lift e hp) (Pin.lift f hc) (outputSlot T V a b j s x) = + outputSlot T' V' a' b' (g j) s' (joinPorts (Pin.lift e hpj) (Pin.lift f hcj) x) := by + rcases x with ⟨x|x, hx⟩ + · exact congrArg (joinLeft _ (orders V' (fun i => ∑ j, c' j i)) s') (ha.assign hp j hpj ⟨x, hx⟩) + · exact congrArg (joinRight (orders T' (fun i => ∑ j, p' j i)) _ s') (hb.assign hc j hcj ⟨x, hx⟩) + +variable [Fintype S] [Fintype S'] [DecidableEq J] [DecidableEq J'] + {q : J → Intervention I E} {q' : J' → Intervention I' E'} + {r : ∀ j, Executes T V (q j)} {r' : ∀ j, Executes T' V' (q' j)} + {t : ∀ j, (q j).choice} {t' : ∀ j, (q' j).choice} + +theorem MoveRel.parallel (a : Allocation q) (b : Allocation q') (g : ↥u ≃ ↥u') + (hr : ∀ j : ↥u, MoveRel e f (r j) (r' (g j)) (t j) (t' (g j))) + (hs : ∀ j ∉ u, Silent s (r j) (t j)) (hs' : ∀ j ∉ u', Silent s' (r' j) (t' j)) + (h₁ : Pin.Align e g a.take b.take) (h₂ : Pin.Align e g (a.put t) (b.put t')) + (h₃ : Pin.Align f g (a.core t) (b.core t')) : + MoveRel e f (Executes.parallel a r) (Executes.parallel b r') t t' := by + have ht : Pin.Same e (Intervention.parallel q).take (Intervention.parallel q').take := + fun i => sum_match g (fun j => (hr j).take i) + (fun j h => (hs j h).take i) (fun j h => (hs' j h).take (e i)) + have hp : Pin.Same e ((Intervention.parallel q).put t) ((Intervention.parallel q').put t') := + fun i => sum_match g (fun j => (hr j).put i) + (fun j h => (hs j h).put i) (fun j h => (hs' j h).put (e i)) + have hc : Pin.Same f ((Intervention.parallel q).core t) ((Intervention.parallel q').core t') := + fun i => sum_match g (fun j => (hr j).core i) + (fun j h => (hs j h).core i) (fun j h => (hs' j h).core (f i)) + refine ⟨ht, hp, hc, fun h x y => ?_⟩ + apply prod_match g + · intro j + exact ((hr j).rel.pull (h₁.assign ht j (hr j).take) + (output_match h₂ h₃ hp hc j (hr j).put (hr j).core)) h x y + · exact fun j hj => (hs j hj).one _ _ _ + · exact fun j hj => (hs' j hj).one _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Naming the visible pins of a chart -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral + +variable {K S I J : Type} + +theorem Pin.eq_iff {T : J → Board K I} {v : I} (p q : Pin T v) : + p = q ↔ p.1 = q.1 ∧ HEq p.2.val q.2.val := by + constructor + · rintro rfl; exact ⟨rfl, HEq.rfl⟩ + · obtain ⟨i, x⟩ := p + obtain ⟨j, y⟩ := q + rintro ⟨rfl, h⟩ + exact congrArg (Sigma.mk _) (Subtype.ext (eq_of_heq h)) + +variable [Field K] [Fintype S] [Nonempty S] {N : ℕ} {b : Market I N} {s : I} + (A : Finset (Tensor K S)) + +theorem Near.eq_of_fst_eq {i j : Near b s} (h : i.1 = j.1) : i = j := by + obtain ⟨i, u⟩ := i + obtain ⟨j, v⟩ := j + change i = j at h + subst j + exact congrArg (Sigma.mk i) (Subtype.ext ((b.name i).injective (u.property.trans + v.property.symm))) + +theorem placeReq_slot (j : Near b s) (l : Pin (localRequest (b.code j.1) A) j.2.1) : + HEq (placeReq A j l).2.val l.2.val := by + obtain ⟨k, x⟩ := l + cases k <;> exact HEq.rfl + +theorem placeReq_eq_iff (i j : Near b s) + (l : Pin (localRequest (b.code i.1) A) i.2.1) + (r : Pin (localRequest (b.code j.1) A) j.2.1) : + placeReq A i l = placeReq A j r ↔ + b.request A i.1 l.1 = b.request A j.1 r.1 ∧ HEq l.2.val r.2.val := by + rw [Pin.eq_iff] + exact and_congr Iff.rfl ⟨fun h => (placeReq_slot A i l).symm.trans (h.trans (placeReq_slot A j + r)), + fun h => (placeReq_slot A i l).trans (h.trans (placeReq_slot A j r).symm)⟩ + +theorem placeEdge_injective : + Function.Injective (fun p : Σ j : Near b s, Pin (localEdge K (b.code j.1)) j.2.1 => + placeEdge K p.1 p.2) := by + rintro ⟨i, x⟩ ⟨j, y⟩ h + have he : i = j := Near.eq_of_fst_eq (congrArg (fun p => p.1.1) h) + subst j + have hg := congrArg (fun p => p.1) h + have hl : x.1 = y.1 := eq_of_heq (Sigma.mk.inj hg).2 + have hv : (x.2.val : Bool) = (y.2.val : Bool) := + congrArg (fun p : Pin (edge K b) s => (p.2.val : Bool)) h + exact congrArg (Sigma.mk i) ((Pin.eq_iff _ _).mpr ⟨hl, heq_of_eq hv⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Moving a count from a local chart to an incident global pin -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral + +variable {K S I I' : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + [DecidableEq I] [DecidableEq I'] {N : ℕ} (A : Finset (Tensor K S)) + {b : Market I N} {c : Market I' N} {s : I} {v : I'} + +open Classical in +/-- Computes the inputs by the application `Pin (localRequest u.1 A) u.2`. -/ +abbrev Inputs (u : Spot N) := Pin (localRequest u.1 A) u.2 +open Classical in +/-- Computes the links at by the application `Pin (localEdge K u.1) u.2`. -/ +abbrev LinksAt (K : Type) [Field K] (u : Spot N) := Pin (localEdge K u.1) u.2 + +open Classical in +/-- Decides equality of requests and edges in the replay relation. -/ +local instance : DecidableEq (b.Good A) := @instDecidableEqSum (b.Request A) b.Edge inferInstance + inferInstance + +open Classical in +/-- The value specified by `@Stock.collect _ _ _ (@instDecidableEqSum (b.Request A) b.Edge +inferInstance inferInstance) (b.assign A i) z`. -/ +def counts (b : Market I N) (i : I) (z : (b.shape i).Goods A → ℕ) : b.Request A ⊕ b.Edge → ℕ := + @Stock.collect _ _ _ (@instDecidableEqSum (b.Request A) b.Edge inferInstance inferInstance) + (b.assign A i) z + +open Classical in +theorem counts_req (j : Near b s) (z : (b.shape j.1).Goods A → ℕ) (p : Inputs A (spot j)) : + counts A b j.1 z (.inl (placeReq A j p).1) = z (.inl p.1) := + Stock.collect_inj (b.assign_injective A j.1) z (.inl p.1) + +omit [Nonempty S] in +open Classical in +theorem counts_edge (j : Near b s) (z : (b.shape j.1).Goods A → ℕ) (p : LinksAt K (spot j)) : + counts A b j.1 z (.inr (placeEdge K j p).1) = z (.inr p.1) := + Stock.collect_inj (b.assign_injective A j.1) z (.inr p.1) + +open Classical in +theorem req_source (i : I) {z : (b.shape i).Goods A → ℕ} (p : Pin (request b A) s) + (h : counts A b i z (.inl p.1) ≠ 0) : + ∃ (u : {u // b.name i u = s}) (l : Inputs A (spot (⟨i, u⟩ : Near b s))), + placeReq A ⟨i, u⟩ l = p := by + obtain ⟨k, hk, _⟩ := Stock.collect_nonzero h + rcases k with k | k + · obtain ⟨u, x, hx⟩ := placeReq_surj p i k (Sum.inl.inj hk) + exact ⟨u, ⟨k, x⟩, hx⟩ + · contradiction + +omit [Nonempty S] in +open Classical in +theorem edge_source (i : I) {z : (b.shape i).Goods A → ℕ} (p : Pin (edge K b) s) + (h : counts A b i z (.inr p.1) ≠ 0) : + ∃ (u : {u // b.name i u = s}) (l : LinksAt K (spot (⟨i, u⟩ : Near b s))), + placeEdge K ⟨i, u⟩ l = p := by + obtain ⟨k, hk, _⟩ := Stock.collect_nonzero h + rcases k with k | k + · contradiction + · obtain ⟨u, x, hx⟩ := placeEdge_surj p i k (Sum.inr.inj hk) + exact ⟨u, ⟨k, x⟩, hx⟩ + +open Classical in +private theorem values {P : Type*} {Z Y : P → Type} {a b : P} (h : a = b) + (f : ∀ u, Z u → Y u → ℕ) {z : Z a} {z' : Z b} (hz : HEq z z') + {x : Y a} {y : Y b} (hx : HEq x y) : f a z x = f b z' y := by + subst b + rw [eq_of_heq hz, eq_of_heq hx] + +variable {A} (r : Match A b c s v) (j : Near b s) + {z : (b.shape j.1).Goods A → ℕ} {y : (c.shape (r.near j).1).Goods A → ℕ} + +open Classical in +private theorem along {X Y U V : Type} (e : X ≃ Y) (f : U ≃ V) + (a : U → X) (b : V → Y) (x : X → ℕ) (y : Y → ℕ) + (h : ∀ i, e (a i) = b (f i)) (he : ∀ i, x (a i) = y (b (f i))) + (hx : ∀ i, x i ≠ 0 → ∃ j, a j = i) (hy : ∀ i, y i ≠ 0 → ∃ j, b j = i) : + ∀ i, x i = y (e i) := by + intro i + by_cases hi : ∃ j, a j = i + · obtain ⟨j, rfl⟩ := hi + rw [he, h] + have zero : x i = 0 := Classical.byContradiction (fun h => hi (hx _ h)) + rw [zero] + by_contra! hn + obtain ⟨u, hu⟩ := hy _ hn.symm + exact hi ⟨f.symm u, e.injective (by rw [h, f.apply_symm_apply, hu])⟩ + +open Classical in +theorem Match.same_req (hz : HEq z y) : + Pin.Same r.req (counts A b j.1 z ∘ Sum.inl) (counts A c (r.near j).1 y ∘ Sum.inl) := by + let g := Equiv.cast (congrArg (Inputs A) (r.spot_eq j)) + refine along r.req g (placeReq A j) (placeReq A (r.near j)) (fun p => counts A b j.1 z (.inl p.1)) + (fun p => counts A c (r.near j).1 y (.inl p.1)) ?_ ?_ ?_ ?_ + · exact fun i => r.req_eq j i (g i) (cast_heq _ _).symm + · intro i + rw [counts_req, counts_req] + exact values (r.spot_eq j) + (fun u (z : u.1.2.Goods A → ℕ) (i : Inputs A u) => z (.inl i.1)) hz (cast_heq _ _).symm + · intro i hi + obtain ⟨u, l, hl⟩ := req_source A _ i hi + have he : u = j.2 := Subtype.ext ((b.name _).injective (u.property.trans j.2.property.symm)) + subst u + exact ⟨l, hl⟩ + · intro i hi + obtain ⟨u, l, hl⟩ := req_source A _ i hi + have he : u = (r.near j).2 := + Subtype.ext ((c.name _).injective (u.property.trans (r.near j).2.property.symm)) + subst u + exact ⟨l, hl⟩ + +open Classical in +theorem Match.same_core (hz : HEq z y) : + Pin.Same r.core (counts A b j.1 z ∘ Sum.inr) (counts A c (r.near j).1 y ∘ Sum.inr) := by + let g := Equiv.cast (congrArg (LinksAt K) (r.spot_eq j)) + refine along r.core g (placeEdge K j) (placeEdge K (r.near j)) (fun p + => counts A b j.1 z (.inr p.1)) + (fun p => counts A c (r.near j).1 y (.inr p.1)) ?_ ?_ ?_ ?_ + · exact fun i => r.core_eq j i (g i) (cast_heq _ _).symm + · intro i + rw [counts_edge, counts_edge] + exact values (r.spot_eq j) + (fun u (z : u.1.2.Goods A → ℕ) (i : LinksAt K u) => z (.inr i.1)) hz (cast_heq _ _).symm + · intro i hi + obtain ⟨u, l, hl⟩ := edge_source A _ i hi + have he : u = j.2 := Subtype.ext ((b.name _).injective (u.property.trans j.2.property.symm)) + subst u + exact ⟨l, hl⟩ + · intro i hi + obtain ⟨u, l, hl⟩ := edge_source A _ i hi + have he : u = (r.near j).2 := + Subtype.ext ((c.name _).injective (u.property.trans (r.near j).2.property.symm)) + subst u + exact ⟨l, hl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # The local factor of a market move in canonical coordinates -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol + +open Spectral Routing Board + +variable {K S I G : Type} [Field K] {n : ℕ} + +open Classical in +/-- The value specified by `x (⟨p.1.1.1, ⟨p.1.2, p.2⟩⟩, p.1.1.2.val)`. -/ +def feed [Fintype G] {T : G → Board K I} {s : I} {z : G → ℕ} + (x : Lines n (Pin T s × ℕ)) (p : (orders T z).localPort s) : Fin (2 ^ n) → Bool := + x (⟨p.1.1.1, ⟨p.1.2, p.2⟩⟩, p.1.1.2.val) + +open Classical in +/-- In the case `⟨.inl i, h⟩`, this construction gives `x ⟨i, h⟩`. -/ +def both {D V : Board K I} {s : I} (x : Lines n (D.localPort s)) (y : Lines n (V.localPort s)) : + Lines n ((D.join V).localPort s) + | ⟨.inl i, h⟩ => x ⟨i, h⟩ + | ⟨.inr i, h⟩ => y ⟨i, h⟩ + +open Classical in +private theorem placed_value [Fintype G] [Fintype S] [Fintype I] + {D : Board K S} {V : G → Board K S} {D' : Board K I} {V' : G → Board K I} + (v : Expansion D V) (f : S ↪ I) (e : Rename (D.move f) D') + (g : ∀ i, Rename ((V i).move f) (V' i)) {s : I} (j : {u // f u = s}) (t : G) + (x : Lines n (D'.localPort s)) (y : Lines n ((V' t).localPort s)) : + ((v.place f).rename e g).kernel t s n x y = v.kernel t j.val n + ((x ∘ e.local s) ∘ D.movePort f j) ((y ∘ (g t).local s) ∘ (V t).movePort f j) := by + unfold Expansion.rename + dsimp only + rw [v.placed f j t] + rfl + +variable [Fintype S] [Nonempty S] [DecidableEq S] {N h : ℕ} {A : Finset (Tensor K S)} + +open Classical in +/-- Indexes the ticket by the coordinates of `Σ p : Spot N, Σ q : p.1.Move A, ↥(histograms +q.move.letter (2 ^ h + Fintype.card q.move.letter))`. -/ +abbrev Ticket (A : Finset (Tensor K S)) (N h : ℕ) := + Σ p : Spot N, Σ q : p.1.Move A, ↥(histograms q.move.letter (2 ^ h + Fintype.card q.move.letter)) + +open Classical in +/-- In the case `(⟨.inl i, j⟩, k)`, this construction gives `x (⟨i, j⟩, k)`. -/ +def gather (p : Spot N) (x : Lines n (Inputs A p × ℕ)) (y : Lines n (LinksAt K p × ℕ)) : + Lines n (Pin (goods p.1 A) p.2 × ℕ) + | (⟨.inl i, j⟩, k) => x (⟨i, j⟩, k) + | (⟨.inr i, j⟩, k) => y (⟨i, j⟩, k) + +open Classical in +/-- The run of type `K` for the given inputs. -/ +def Ticket.run (p : Ticket A N h) (ha : 0 ∉ A) + (x y : Lines n (Inputs A p.1 × ℕ)) (z : Lines n (LinksAt K p.1 × ℕ)) : K := + if hb : Fintype.card p.2.1.move.letter ≤ 2 ^ h then + (localAction p.1.1 A p.2.1 h ha hb).kernel p.2.2 p.1.2 n + (feed (gather p.1 x (fun _ _ => false))) (feed (gather p.1 y z)) + else 0 + +variable [Fintype I] [DecidableEq I] {b : Market I N} {s : I} (j : Near b s) + (q : (b.code j.1).Move A) (ha : 0 ∉ A) (hb : Fintype.card q.move.letter ≤ 2 ^ h) + (hd : ∀ u ∈ q.demand, ∃ i, b.assign A j.1 u = .inl i) + (u : ↥(histograms q.move.letter (2 ^ h + Fintype.card q.move.letter))) + +open Classical in +/-- Uses `⟨spot j, q, u⟩` as the representation. -/ +def ticket : Ticket A N h := ⟨spot j, q, u⟩ + +open Classical in +private theorem post_read (d : (b.shape j.1).Goods A → ℕ) + (y : Lines n (Pin (request b A) s × ℕ)) (z : Lines n (Pin (edge K b) s × ℕ)) : + (both (feed y) (feed z) ∘ (post A b j.1 d).local s) ∘ + movePort (orders (goods (b.code j.1) A) d) (b.name j.1) j.2 = + feed (gather (spot j) (fun p => y (placeReq A j p.1, p.2)) (fun p => z (placeEdge K j p.1, + p.2))) := by + funext ⟨⟨⟨i, k⟩, l⟩, hl⟩ + cases i <;> rfl + +omit [Fintype I] [DecidableEq I] in +open Classical in +private theorem drop_feed {E : Type} [Fintype E] (D : Board K I) (V : E → Board K I) + (z : E → ℕ) (hz : ∀ e, z e = 0) (x : Lines n (D.localPort s)) : + x ∘ (dropEmpty D V z hz).local s = both x (feed (fun _ _ => false)) := by + funext o + rcases o with ⟨i|⟨⟨i, k⟩, l⟩, hl⟩ + · rfl + · exact Fin.elim0 (Fin.cast (hz i) k) + +open Classical in +theorem applyMove_value (x y : Lines n (Pin (request b A) s × ℕ)) + (z : Lines n (Pin (edge K b) s × ℕ)) : + (applyMove A b j.1 q h ha hb hd).kernel u s n (feed x) (both (feed y) (feed z)) = + (ticket j q u).run ha (fun p => x (placeReq A j p.1, p.2)) + (fun p => y (placeReq A j p.1, p.2)) (fun p => z (placeEdge K j p.1, p.2)) := by + let v := localAction (b.code j.1) A q h ha hb + unfold Ticket.run ticket + dsimp only + rw [dite_eq_left hb] + let d := Stock.copies q.demand (q.move.block * 2 ^ h) + let e := (post A b j.1 d).trans (dropEmpty _ _ _ (q.take_core (b.assign A j.1) (2 ^ h) hd)) + let g := fun t : ↥(histograms q.move.letter (2 ^ h + Fintype.card q.move.letter)) => + post A b j.1 (q.output ((b.shape j.1).links A) (2 ^ h + Fintype.card q.move.letter) t.val) + refine (placed_value v (b.name j.1) e g j.2 u (feed x) (both (feed y) (feed z))).trans ?_ + refine congrArg₂ (v.kernel u j.2.val n) ?_ (post_read j _ y z) + refine Eq.trans ?_ (post_read j d x (fun _ _ => false)) + have hx := drop_feed (orders (request b A) (counts A b j.1 d ∘ Sum.inl)) + (edge K b) (counts A b j.1 d ∘ Sum.inr) (q.take_core (b.assign A j.1) (2 ^ h) hd) (feed x) + exact congrArg (fun f => (f ∘ (post A b j.1 d).local s) ∘ + movePort (orders (goods (b.code j.1) A) d) (b.name j.1) j.2) hx + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Interventions outside the marked site's neighborhood -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral Board + +variable {K S I : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] [Fintype I] + [DecidableEq I] {N M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} (b : Market I N) + (a : Atlas N A M ρ) (h : ℕ) (ha : 0 ∉ A) (hh : a.Room (2 ^ h)) (p : b.Request A → ℝ) + +open Classical in +/-- Computes the worker by the application `applyMove A b i (b.moveAt a p i) h ha (hh _ _ +(b.moving a p i).1).1 (b.demand_slot a p i)`. -/ +abbrev worker (i : b.active a p) : Executes (request b A) (edge K b) (b.localMove a p (2 ^ h) i) := + applyMove A b i (b.moveAt a p i) h ha (hh _ _ (b.moving a p i).1).1 (b.demand_slot a p i) + +open Classical in +theorem silent_move (u : (b.policy a p (2 ^ h)).choice) (j : b.active a p) + {s : I} (hoff : ∀ l, b.name j l ≠ s) : Silent s (worker b a h ha hh p j) (u j) := by + let q := b.moveAt a p j + let d := Stock.copies q.demand (q.move.block * 2 ^ h) + let r := q.output ((b.shape j).links A) (2 ^ h + Fintype.card q.move.letter) (u j).val + have req (z : (b.shape j).Goods A → ℕ) (x : Pin (request b A) s) : + counts A b j z (.inl x.1) = 0 := by + by_contra he + obtain ⟨t, _⟩ := req_source A _ x he + exact hoff _ t.property + have core (x : Pin (edge K b) s) : counts A b j r (.inr x.1) = 0 := by + by_contra he + obtain ⟨t, _⟩ := edge_source A _ x he + exact hoff _ t.property + refine ⟨req d, req r, core, fun t x y => ?_⟩ + let v := localAction (b.code j) A q h ha (hh _ _ (b.moving a p j).1).1 + unfold worker applyMove Expansion.rename + dsimp only + rw [v.absent (b.name j) hoff (u j)] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Matched moves have identical local maps -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Spectral Routing Board + +variable {K S I I' : Type} [Field K] [Fintype S] [Nonempty S] [DecidableEq S] + {N M h : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} + +open Classical in +private theorem Ticket.run_congr {a b : Ticket A N h} (hab : a = b) (ha : 0 ∉ A) {n : ℕ} + {x y : Lines n (Inputs A a.1 × ℕ)} {z : Lines n (LinksAt K a.1 × ℕ)} + {x' y' : Lines n (Inputs A b.1 × ℕ)} {z' : Lines n (LinksAt K b.1 × ℕ)} + (hx : ∀ i j k, HEq i j → x (i, k) = x' (j, k)) + (hy : ∀ i j k, HEq i j → y (i, k) = y' (j, k)) + (hz : ∀ i j k, HEq i j → z (i, k) = z' (j, k)) : + a.run ha x y z = b.run ha x' y' z' := by + subst b + have he : x = x' := funext fun i => hx i.1 i.1 i.2 .rfl + have hf : y = y' := funext fun i => hy i.1 i.1 i.2 .rfl + have hg : z = z' := funext fun i => hz i.1 i.1 i.2 .rfl + rw [he, hf, hg] + +open Classical in +private def Ticket.amount (q : Ticket A N h) (put : Bool) : q.1.1.2.Goods A → ℕ := + if put then q.2.1.output (q.1.1.2.links A) (2 ^ h + Fintype.card q.2.1.move.letter) q.2.2.val + else Stock.copies q.2.1.demand (q.2.1.move.block * 2 ^ h) + +omit [Nonempty S] in +open Classical in +private theorem Ticket.amount_congr {a b : Ticket A N h} (hab : a = b) (put : Bool) : + HEq (a.amount put) (b.amount put) := by subst b; rfl + +omit [Nonempty S] in +open Classical in +private theorem recorded {a : Atlas N A M ρ} {s t : Spot N} (he : s = t) + (q : a.menu s.1) (r : a.menu t.1) (u : a.Branch s.1 (2 ^ h) q) (v : a.Branch t.1 (2 ^ h) r) + (hu : HEq (some ⟨q, u⟩ : a.Record s.1 (2 ^ h)) (some ⟨r, v⟩ : a.Record t.1 (2 ^ h))) : + (⟨s, q.val, u⟩ : Ticket A N h) = ⟨t, r.val, v⟩ := by + subst t + have he := Option.some.inj (eq_of_heq hu) + obtain ⟨rfl, hv⟩ := Sigma.mk.inj he + rw [eq_of_heq hv] + +variable [Fintype I] [DecidableEq I] [Fintype I'] [DecidableEq I'] + {b : Market I N} {c : Market I' N} {s : I} {v : I'} + (r : Match A b c s v) (a : Atlas N A M ρ) (h : ℕ) (ha : 0 ∉ A) (hh : a.Room (2 ^ h)) + (p : b.Request A → ℝ) (p' : c.Request A → ℝ) + (u : (b.policy a p (2 ^ h)).choice) (u' : (c.policy a p' (2 ^ h)).choice) + (j : Near b s) (hj : j.1 ∈ b.active a p) (hj' : (r.near j).1 ∈ c.active a p') + +open Classical in +private theorem packed (n : ℕ) : + let i : b.active a p := ⟨j.1, hj⟩ + let q := b.localMove a p (2 ^ h) i + let Y := orders (request b A) (q.put (u i)) + let Z := orders (edge K b) (q.core (u i)) + ∀ x y, (worker b a h ha hh p i).kernel (u i) s n x y = + (ticket j (b.moveAt a p i) (u i)).run ha + (fun t => Pin.read x (placeReq A j t.1) t.2) + (fun t => Pin.read (y ∘ Y.joinLeft Z s) (placeReq A j t.1) t.2) + (fun t => Pin.read (y ∘ Y.joinRight Z s) (placeEdge K j t.1) t.2) := by + intro i q Y Z x y + let X := fun t : Pin (request b A) s × ℕ => Pin.read x t.1 t.2 + let U := fun t : Pin (request b A) s × ℕ => Pin.read (y ∘ Y.joinLeft Z s) t.1 t.2 + let V := fun t : Pin (edge K b) s × ℕ => Pin.read (y ∘ Y.joinRight Z s) t.1 t.2 + refine Eq.trans ?_ (applyMove_value j _ ha (hh _ _ (b.moving a p i).1).1 (b.demand_slot a p i) (u + i) X U V) + apply congrArg₂ ((worker b a h ha hh p i).kernel (u i) s n) + · funext l + obtain ⟨l, k, rfl⟩ := Pin.exists_atCopy l + exact (Pin.read_copy x l k).symm + · funext l + rcases l with ⟨l|l, hl⟩ + · exact (Pin.read_copy (y ∘ Y.joinLeft Z s) ⟨l.1.1, ⟨l.2, hl⟩⟩ l.1.2).symm + · exact (Pin.read_copy (y ∘ Y.joinRight Z s) ⟨l.1.1, ⟨l.2, hl⟩⟩ l.1.2).symm + +open Classical in +theorem Match.local_rel + (hrec : HEq (b.record a p (2 ^ h) u j.1) (c.record a p' (2 ^ h) u' (r.near j).1)) : + MoveRel r.req r.core (worker b a h ha hh p ⟨j.1, hj⟩) + (worker c a h ha hh p' ⟨(r.near j).1, hj'⟩) (u ⟨j.1, hj⟩) (u' ⟨(r.near j).1, hj'⟩) := by + let i : b.active a p := ⟨j.1, hj⟩ + let i' : c.active a p' := ⟨(r.near j).1, hj'⟩ + have ht : ticket j (b.moveAt a p i) (u i) = ticket (r.near j) (c.moveAt a p' i') (u' i') := by + change HEq (b.record a p (2 ^ h) u i) (c.record a p' (2 ^ h) u' i') at hrec + rw [b.record_active, c.record_active] at hrec + exact recorded (r.spot_eq j) (b.live a p i) (c.live a p' i') _ _ hrec + let q := b.localMove a p (2 ^ h) i + let q' := c.localMove a p' (2 ^ h) i' + have htake : Pin.Same r.req q.take q'.take := r.same_req j (Ticket.amount_congr ht false) + have hput : Pin.Same r.req (q.put (u i)) (q'.put (u' i')) := + r.same_req j (Ticket.amount_congr ht true) + have hcore : Pin.Same r.core (q.core (u i)) (q'.core (u' i')) := + r.same_core j (Ticket.amount_congr ht true) + refine ⟨htake, hput, hcore, fun n x y => ?_⟩ + rw [packed a h ha hh p u j hj n, packed a h ha hh p' u' (r.near j) hj' n] + let Y := orders (request c A) (q'.put (u' i')) + let Z := orders (edge K c) (q'.core (u' i')) + apply Ticket.run_congr ht + · intro l l' k he + rw [Pin.read_lift, r.req_eq j l l' he] + · intro l l' k he + change Pin.read ((y ∘ Y.joinLeft Z v) ∘ Pin.lift r.req hput) (placeReq A j l) k = _ + rw [Pin.read_lift, r.req_eq j l l' he] + · intro l l' k he + change Pin.read ((y ∘ Y.joinRight Z v) ∘ Pin.lift r.core hcore) (placeEdge K j l) k = _ + rw [Pin.read_lift, r.core_eq j l l' he] + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# Assembling corresponding interventions at a site + +Match only the active centers meeting this site. All other centers +are silent there. Local ordering keys give equal offsets to matching +copies, independently of the order of the other centers. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Routing Spectral Finset + +variable {K S I I' : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype I] [DecidableEq I] [Fintype I'] [DecidableEq I'] + {N M t t' : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} {b : Market I N} {c : Market I' N} + {s : I} {v : I'} + +open scoped Classical in +private def onSite (b : Market I N) (s : I) (U : Finset I) : Finset U := + univ.filter (fun i : U => ∃ j, b.name i.val j = s) + +open scoped Classical in +private def incident (b : Market I N) (s : I) (U : Finset I) : + ↥(onSite b s U) ≃ {j : Near b s // j.1 ∈ U} where + toFun i := + let h := (mem_filter.mp i.property).2 + ⟨⟨i.val.val, ⟨h.choose, h.choose_spec⟩⟩, i.val.property⟩ + invFun j := ⟨⟨j.val.1, j.property⟩, + mem_filter.mpr ⟨mem_univ _, ⟨j.val.2.val, j.val.2.property⟩⟩⟩ + left_inv _ := rfl + right_inv _ := Subtype.ext (Near.eq_of_fst_eq rfl) + +omit [Fintype I] in +open scoped Classical in +private theorem offSite {U : Finset I} {j : U} (hj : j ∉ onSite b s U) : + ∀ l, b.name j l ≠ s := fun l hl => hj (mem_filter.mpr ⟨mem_univ _, l, hl⟩) + +omit [Nonempty S] in +open scoped Classical in +private theorem record_live (b : Market I N) (a : Atlas N A M ρ) (p : b.Request A → ℝ) + (n : ℕ) (u : (b.policy a p n).choice) (i : I) : + (b.record a p n u i).isSome = true ↔ i ∈ b.active a p := by + unfold Market.record + split <;> simp_all + +open scoped Classical in +private theorem Match.live_iff (r : Match A b c s v) (a : Atlas N A M ρ) + (p : b.Request A → ℝ) (p' : c.Request A → ℝ) (n : ℕ) + (u : (b.policy a p n).choice) (u' : (c.policy a p' n).choice) + (j : Near b s) (hr : HEq (b.record a p n u j.1) (c.record a p' n u' (r.near j).1)) : + j.1 ∈ b.active a p ↔ (r.near j).1 ∈ c.active a p' := by + have h : (⟨_, b.record a p n u j.1⟩ : Σ i, a.Record i n) = + ⟨_, c.record a p' n u' (r.near j).1⟩ := Sigma.ext (r.same j) hr + have he := congrArg (fun x : Σ i, a.Record i n => x.2.isSome) h + rw [← record_live b a p n u, ← record_live c a p' n u', he] + +open scoped Classical in +private theorem pack_agree {J J' : Type} [Fintype J] [Fintype J'] {U : Finset J} {U' : Finset J'} + (e : ↥U ≃ ↥U') {z key : J → ℕ} {z' key' : J' → ℕ} + (hkey : ∀ j : ↥U, key j = key' (e j)) (heq : ∀ j : ↥U, z j = z' (e j)) + (h₀ : ∀ j ∉ U, z j = 0) (h₀' : ∀ j ∉ U', z' j = 0) + (i : ↥U) (k : Fin (z i)) (l : Fin (z' (e i))) (h : k.val = l.val) : + offset z key i + k.val = offset z' key' (e i) + l.val := by + rw [h] + unfold offset + simp only [sum_filter] + apply congrArg (· + l.val) + apply sum_match e + · intro j + rw [hkey i, hkey j, heq] + · intro j hj; rw [h₀ j hj, ite_self] + · intro j hj; rw [h₀' j hj, ite_self] + +open scoped Classical in +theorem Match.perform_rel (r : Match A b c s v) (a : Atlas N A M ρ) + (g : b.Ports t) (g' : c.Ports t') (hkeys : r.keys g g') + (h : ℕ) (ha : 0 ∉ A) (hh : a.Room (2 ^ h)) + (p : b.Request A → ℝ) (p' : c.Request A → ℝ) + (u : (b.policy a p (2 ^ h)).choice) (u' : (c.policy a p' (2 ^ h)).choice) + (hrec : ∀ j : Near b s, HEq (b.record a p (2 ^ h) u j.1) (c.record a p' (2 ^ h) u' (r.near + j).1)) : + MoveRel r.req r.core (perform b a g h ha hh p) (perform c a g' h ha hh p') u u' := by + let U := onSite b s (b.active a p) + let U' := onSite c v (c.active a p') + let l := incident b s (b.active a p) + let l' := incident c v (c.active a p') + have eq (j) := r.live_iff a p p' (2 ^ h) u u' j (hrec j) + let e : ↥U ≃ ↥U' := l.trans ((r.near.subtypeEquiv eq).trans l'.symm) + have yes (i : ↥U) : MoveRel r.req r.core (worker b a h ha hh p i.val) + (worker c a h ha hh p' (e i).val) (u i.val) (u' (e i).val) := + r.local_rel a h ha hh p p' u u' (l i).val (l i).property ((eq _).mp (l i).property) (hrec _) + have no (i) (hi : i ∉ U) := silent_move b a h ha hh p u i (offSite hi) + have no' (i) (hi : i ∉ U') := silent_move c a h ha hh p' u' i (offSite hi) + have key (x : Pin (request b A) s) (i : ↥U) : + b.position a p g x.1 i.val = c.position a p' g' (r.req x).1 (e i).val := hkeys (l i).val x + refine MoveRel.parallel (b.allocation a p (2 ^ h) g) (c.allocation a p' (2 ^ h) g') e yes no no' + ?_ ?_ ?_ + · intro j i k k' he + exact pack_agree e (key i) (fun w => (yes w).take i) (fun w hw => (no w hw).take i) + (fun w hw => (no' w hw).take (r.req i)) j k k' he + · intro j i k k' he + exact pack_agree e (key i) (fun w => (yes w).put i) (fun w hw => (no w hw).put i) + (fun w hw => (no' w hw).put (r.req i)) j k k' he + · intro j i k k' he + exact pack_agree e (key := fun _ => 0) (key' := fun _ => 0) (fun _ => rfl) (fun w + => (yes w).core i) (fun w hw => (no w hw).core i) + (fun w hw => (no' w hw).core (r.core i)) j k k' he + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- +# A matched replay identifies the local operator at every scale +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol.Match + +open Spectral Routing + +variable {K S I I' : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype I] [DecidableEq I] [Fintype I'] [DecidableEq I'] + {N M t t' : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} {b : Market I N} {c : Market I' N} + {s : I} {v : I'} (f : Match A b c s v) (a : Atlas N A M ρ) + (g : b.Ports t) (g' : c.Ports t') (h : ℕ) (ha : 0 ∉ A) (hh : a.Room (2 ^ h)) (μ d : ℕ) + +open scoped Classical in +theorem replay_rel (hs : f.keys g g') + (hd : f.depots g g') (hr : b.ready A d) (hr' : c.ready A d) (hc : UniformCap N A M) + {k : ℕ} {z : b.Request A → ℕ} {y : c.Request A → ℕ} + {u : b.Path a μ d (2 ^ h) k z} {w : c.Path a μ d (2 ^ h) k y} + (he : f.Replay a μ d (2 ^ h) k z y u w) : + RunRel f.req f.core (fun z => terminal A d M b g z hr hc) + (fun z => terminal A d M c g' z hr' hc) + (Q := b.decision a μ d (2 ^ h)) (Q' := c.decision a μ d (2 ^ h)) + (fun z => perform b a g h ha hh (b.stockPrice (M := M) μ d z)) + (fun z => perform c a g' h ha hh (c.stockPrice (M := M) μ d z)) + (L := b.payload A) (L' := c.payload A) k u w := by + induction k generalizing z y with + | zero => exact f.terminal_rel hd he d M hr hr' hc + | succ k ih => exact ⟨f.perform_rel a g g' hs h ha hh _ _ u.1 w.1 he.2.1, ih he.2.2⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol.Match +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Wired.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Wired.lean new file mode 100644 index 0000000000..bce7bdbcdb --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Protocol/Wired.lean @@ -0,0 +1,283 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Alignment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.System + +/-! +# Wiring a local board expansion into transport banks + +The branch selector and every enabled endpoint are embedded injectively. +Invalid codes and nonzero padding must have zero weight. This makes +the two changes of summation indices exact over any field. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Transport + +variable {F E : Type} [Field F] {h p W z : ℕ} + +open Classical in +/-- Indexes the end by the coordinates of `Σ _ : (Σ e, Fin (m e)), Bool`. -/ +abbrev End (m : E → ℕ) := Σ _ : (Σ e, Fin (m e)), Bool + +open Classical in +/-- The indexed operation `Board.orders (fun e => Board.link F (src e) (dst e)) m`. -/ +abbrev Links (F : Type) [Field F] [Fintype E] (src dst : E → Site h) (m : E → ℕ) := + Board.orders (fun e => Board.link F (src e) (dst e)) m + +open Classical in +/-- The indexed operation `Links F id (Routing.inflate h σ) (fun _ => W)`. -/ +abbrev Demand (F : Type) [Field F] (σ : Coloring.B h → Coloring.B h) (W : ℕ) := + Links F id (Routing.inflate h σ) (fun _ => W) + +open Classical in +/-- Uses `⟨i.1, !i.2⟩` as the representation. -/ +def opposite {m : E → ℕ} (i : End m) : End m := ⟨i.1, !i.2⟩ + +open Classical in +/-- The data for the placement construction, including `embed`, `owner`, `cmd`, `cover`, +`group`. -/ +structure Placement (src dst : E → Site h) (m : E → ℕ) + (g : Port h p → ℕ) (a : Orders h p) where + /-- Embeds the coordinates as `End m ↪ Port h p`. -/ + embed : End m ↪ Port h p + owner : ∀ i, (embed i).1 = if i.2 then dst i.1.1 else src i.1.1 + cmd : ∀ i, a (embed i) = (true, i.2, embed (opposite i)) + cover : ∀ i ∈ Enabled a, ∃ j, embed j = i + group : ∀ i, g (embed (opposite i)) = g (embed i) + +open Classical in +/-- The condition `∀ i ∉ Enabled a, ∀ t, c i.1 (i.2, t) = false` on the specified data. -/ +def Padded (a : Orders h p) (c : Site h → Channels p (2 ^ z)) : Prop := + ∀ i ∉ Enabled a, ∀ t, c i.1 (i.2, t) = false + +open Classical in +/-- Evaluates `if i.2 then y (Routing.inflate h σ i.1.1) (i.1.2, t) else x i.1.1 (i.1.2, t)` at +the input `i t`. -/ +def outside (σ : Coloring.B h → Coloring.B h) (W : ℕ) (x y : Site h → Data W (2 ^ z)) : + Lines z (End (fun _ : Site h => W)) := + fun i t => if i.2 then y (Routing.inflate h σ i.1.1) (i.1.2, t) else x i.1.1 (i.1.2, t) + +open Classical in +/-- Evaluates `c (P.embed i).1 ((P.embed i).2, t)` at the input `i t`. -/ +def Placement.inside {src dst : E → Site h} {m : E → ℕ} {g : Port h p → ℕ} {a : Orders h p} + (P : Placement src dst m g a) (c : Site h → Channels p (2 ^ z)) : Lines z (End m) := + fun i t => c (P.embed i).1 ((P.embed i).2, t) + +open Classical in +/-- The data for the wiring construction, including `E`, `I`, `[finiteE`, `[finiteI`, `src`. -/ +structure Wiring (S : System F h p W (2 ^ z)) (C : ℕ) (σ : Equiv.Perm (Coloring.B h)) where + /-- The type of edges. -/ + E : Type + /-- The `Wiring` component of type `Type`. -/ + I : Type + [finiteE : Fintype E] + [finiteI : Fintype I] + /-- Assigns the source of each connection. -/ + src : E → Site h + /-- Assigns the destination of each connection. -/ + dst : E → Site h + /-- The `Wiring` component of type `I → E → ℕ`. -/ + m : I → E → ℕ + /-- The `Wiring` component of type `(Demand F σ W).Expansion (fun j => Links F src dst (m + j))`. -/ + proc : (Demand F σ W).Expansion (fun j => Links F src dst (m j)) + /-- Embeds the coordinates as `I ↪ S.selector.obj`. -/ + choose : I ↪ S.selector.obj + /-- The `Wiring` component of type `∀ j, Placement src dst (m j) S.group (commands (S.dispatch + (σ, choose j)))`. -/ + place : ∀ j, Placement src dst (m j) S.group (commands (S.dispatch (σ, choose j))) + cost : ∀ j, 2 * (∑ e, m j e) ≤ C * W * 2 ^ h + agrees : ∀ j x y c, Padded (commands (S.dispatch (σ, choose j))) c → ∀ i, + S.kernel ((S.dispatch (σ, choose j)) i).1 (x i) (y i) (c i) = + proc.kernel j i z ((Demand F σ W).view i (outside σ W x y)) + ((Links F src dst (m j)).view i ((place j).inside c)) + invalid : ∀ t x y c, S.value (S.dispatch (σ, t)) x y c ≠ 0 → + (∃ j, choose j = t) ∧ Padded (commands (S.dispatch (σ, t))) c + +attribute [instance] Wiring.finiteE Wiring.finiteI + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end + +/- # Summing over padded banks and selectors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Protocol +open Transport + +variable {F E : Type} [Field F] {h p z W C : ℕ} {src dst : E → Site h} {m : E → ℕ} +variable {g : Port h p → ℕ} {a : Orders h p} + +open Classical in +private theorem sum_embed {I J : Type} [Fintype I] [Fintype J] (e : I ↪ J) (f : J → F) + (he : ∀ j, f j ≠ 0 → ∃ i, e i = j) : ∑ j, f j = ∑ i, f (e i) := by + rw [← Finset.sum_map] + symm + refine Finset.sum_subset (Finset.subset_univ _) (fun j _ hj => ?_) + by_contra h + obtain ⟨i, rfl⟩ := he j h + exact hj (Finset.mem_map_of_mem _ (Finset.mem_univ _)) + +open Classical in +private theorem links_eval [Fintype E] (x : Lines z (End m)) : + (Links F src dst m).eval z x = + if ∀ j, x ⟨j, false⟩ = x ⟨j, true⟩ then 1 else 0 := by + change (∏ t, ∏ j : Σ e, Fin (m e), if x ⟨j, false⟩ t = x ⟨j, true⟩ t then 1 else 0) = _ + simp only [Finset.prod_boole, Finset.mem_univ, forall_const] + congr 1 + exact propext ⟨fun e j => funext (fun t => e t j), fun e t j => congrFun (e j) t⟩ + +open Classical in +private theorem demand_eval (σ : Coloring.B h → Coloring.B h) (x y : Site h → Data W (2 ^ z)) : + (Demand F σ W).eval z (outside σ W x y) = + if ∀ i, x i = y (Routing.inflate h σ i) then 1 else 0 := by + rw [links_eval] + congr 1 + apply propext + constructor + · intro he i + funext ⟨j, t⟩ + exact congrFun (he ⟨i, j⟩) t + · intro he j + funext t + exact congrFun (he j.1) (j.2, t) + +namespace Placement + +variable (P : Placement src dst m g a) + +open Classical in +private theorem enabled (i : End m) : P.embed i ∈ Enabled a := by simp [Enabled, P.cmd] + +open Classical in +theorem valid (P : Placement src dst m g a) : Valid g a := by + intro j hj + obtain ⟨i, rfl⟩ := P.cover j hj + have he : opposite (opposite i) = i := by rcases i with ⟨k, b⟩; simp [opposite] + simp only [P.cmd, he] + exact ⟨P.enabled _, trivial, rfl, P.group i⟩ + +open Classical in +theorem count [Fintype E] (P : Placement src dst m g a) : + (Enabled a).card = 2 * (∑ e, m e) := by + have he : Enabled a = Finset.univ.map P.embed := by + ext i + simp only [Finset.mem_map, Finset.mem_univ, true_and] + exact ⟨P.cover i, by rintro ⟨k, rfl⟩; exact P.enabled k⟩ + rw [he, Finset.card_map, Finset.card_univ] + simp [End, Fintype.card_sigma, mul_comm] + +open Classical in +private theorem agrees [Fintype E] (c : Site h → Channels p (2 ^ z)) : + (Links F src dst m).eval z (P.inside c) = if Joins a c then 1 else 0 := by + rw [links_eval] + congr 1 + apply propext + constructor + · intro he j hj + obtain ⟨⟨k, b⟩, rfl⟩ := P.cover j hj + rw [P.cmd] + cases b + · exact congrFun (he k) + · exact congrFun (he k).symm + · intro he j + have h := he _ (P.enabled ⟨j, false⟩) + rw [P.cmd] at h + exact funext h + +open Classical in +private def fill (u : Lines z (End m)) : Site h → Channels p (2 ^ z) := + fun i ⟨k, t⟩ => if hi : (i, k) ∈ Enabled a then u (P.cover _ hi).choose t else false + +open Classical in +private theorem fill_padded (u : Lines z (End m)) : Padded a (P.fill u) := by + rintro ⟨i, k⟩ hi t + simp [fill, hi] + +open Classical in +private theorem inside_fill : Function.LeftInverse (P.inside (z := z)) P.fill := by + intro u + funext i t + have hi := P.enabled i + simp only [inside, fill, Prod.mk.eta, dite_eq_left hi] + rw [P.embed.injective (P.cover _ hi).choose_spec] + +open Classical in +private theorem fill_inside (c : Site h → Channels p (2 ^ z)) (hc : Padded a c) : + P.fill (P.inside c) = c := by + funext i ⟨k, t⟩ + unfold fill + dsimp only + split + · rename_i hi + unfold inside + rw [(P.cover _ hi).choose_spec] + · rename_i hi + exact (hc (i, k) hi t).symm + +end Placement + +variable {S : System F h p W (2 ^ z)} {σ : Equiv.Perm (Coloring.B h)} + +open Classical in +private theorem Wiring.term (q : Wiring S C σ) (j : q.I) (x y : Site h → Data W (2 ^ z)) : + let v := S.dispatch (σ, q.choose j) + let V := Links F q.src q.dst (q.m j) + (∑ c : Site h → Channels p (2 ^ z), S.value v x y c * (if Joins (commands v) c then 1 else 0)) = + ∑ u, Board.Kernel.prod (Demand F σ W) V (q.proc.kernel j) z (outside σ W x y) u * V.eval z u + := by + let P := q.place j + let e : Lines z (Links F q.src q.dst (q.m j)).slot ↪ (Site h → Channels p (2 ^ z)) := + ⟨P.fill, P.inside_fill.injective⟩ + dsimp only + rw [sum_embed e] + · apply Finset.sum_congr rfl + intro u _ + have hp := P.fill_padded (z := z) u + change S.value _ x y (P.fill u) * (if Joins _ (P.fill u) then 1 else 0) = _ + rw [← P.agrees (F := F), P.inside_fill u] + congr 1 + unfold System.value Board.Kernel.prod + apply Finset.prod_congr rfl + intro i _ + rw [q.agrees j x y _ hp, P.inside_fill u] + · intro c hc + have hp := (q.invalid (q.choose j) x y c (left_ne_zero_of_mul hc)).2 + exact ⟨P.inside c, P.fill_inside c hp⟩ + +open Classical in +theorem system_correct (hw : ∀ σ, Nonempty (Wiring S C σ)) : S.Correct C := by + intro σ x y + obtain ⟨q⟩ := hw σ + constructor + · intro t c _ hn + obtain ⟨⟨j, rfl⟩, _⟩ := q.invalid t x y c hn + exact ⟨(q.place j).valid, (q.place j).count.le.trans (q.cost j)⟩ + let e := q.choose.trans S.selector.code.toEmbedding + rw [← demand_eval (F := F) σ x y, q.proc.identity z (outside σ W x y)] + symm + rw [sum_embed e] + · apply Finset.sum_congr rfl + intro j _ + change (∑ c : Site h → Channels p (2 ^ z), + let v := S.dispatch (σ, S.selector.code.symm (S.selector.code (q.choose j))) + S.value v x y c * (if Joins (commands v) c then 1 else 0)) = _ + rw [Equiv.symm_apply_apply] + exact q.term j x y + · intro t ht + obtain ⟨c, _, hc⟩ := Finset.exists_ne_zero_of_sum_ne_zero ht + obtain ⟨⟨j, hj⟩, _⟩ := q.invalid _ x y c (left_ne_zero_of_mul hc) + exact ⟨j, S.selector.code.eq_symm_apply.mp hj⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Protocol +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Budget.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Budget.lean new file mode 100644 index 0000000000..4561960290 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Budget.lean @@ -0,0 +1,908 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortOne +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Scan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.WideTag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Short + +/-! +# Packing a stable local sort + +The ordered prefix consists, for each digit, of its real rows followed by a +full pack of blanks. Thus even an unaligned pack contains at most one real +digit. At most one live pack extends past this prefix. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +section Grouping +variable {α β : Type} [LinearOrder β] [DecidableEq β] + +private theorem split_first (f : α → β) (k : β) (xs : List α) + (ho : xs.Pairwise (fun x y => f x ≤ f y)) (hle : ∀ x ∈ xs, k ≤ f x) : + xs = xs.filter (fun x => f x = k) ++ xs.filter (fun x => f x ≠ k) := by + induction xs with + | nil => rfl + | cons x xs ih => + obtain ⟨h, hs⟩ := List.pairwise_cons.mp ho + by_cases hx : f x = k + · simpa [hx] using ih hs (fun y hy => hle y (by simp [hy])) + · have hne : ∀ y ∈ x :: xs, f y ≠ k := by + intro y hy + rcases List.mem_cons.mp hy with rfl | hy + · exact hx + · exact ((lt_of_le_of_ne (hle x (by simp)) (Ne.symm hx)).trans_le (h y hy)).ne' + rw [List.filter_eq_nil_iff.mpr (by simpa using hne), List.nil_append, + List.filter_eq_self.mpr (by simpa using hne)] + +/-- Read the least keys one at a time, leaving all larger keys as a tail. -/ +private theorem group_prefix (f : α → β) (tail : α → Bool) (ks : List β) + (hk : ks.Pairwise (· < ·)) (ht : ∀ k ∈ ks, ∀ x, tail x = true → k < f x) + (xs : List α) (ho : xs.Pairwise (fun x y => f x ≤ f y)) + (hc : ∀ x ∈ xs, f x ∈ ks ∨ tail x = true) : + xs = ks.flatMap (fun k => xs.filter (fun x => f x = k)) ++ xs.filter tail := by + induction ks generalizing xs with + | nil => simpa using (List.filter_eq_self.mpr (by simpa using hc)).symm + | cons k ks ih => + obtain ⟨hmin, hk⟩ := List.pairwise_cons.mp hk + have hle (x : α) (hx : x ∈ xs) : k ≤ f x := by + rcases hc x hx with he | h + · rcases List.mem_cons.mp he with h | h + · exact h.ge + · exact (hmin _ h).le + · exact (ht k (by simp) x h).le + let zs := xs.filter (fun x => f x ≠ k) + have hc' : ∀ x ∈ zs, f x ∈ ks ∨ tail x = true := by + intro x hx + obtain ⟨hx, hne⟩ := List.mem_filter.mp hx + simpa [of_decide_eq_true hne] using hc x hx + have keep (p : α → Bool) (h : ∀ x, p x = true → f x ≠ k) : + zs.filter p = xs.filter p := by + unfold zs + rw [List.filter_filter] + apply List.filter_congr + intro x _ + cases hx : p x + · simp + · simp [h x hx] + have hh := ih hk (fun i hi => ht i (by simp [hi])) zs (ho.filter _) hc' + rw [keep tail (fun x hx => (ht k (by simp) x hx).ne')] at hh + have he : ks.flatMap (fun j => zs.filter (fun x => f x = j)) = + ks.flatMap (fun j => xs.filter (fun x => f x = j)) := by + apply List.flatMap_congr + intro j hj + exact keep _ (fun _ he => (of_decide_eq_true he) ▸ (hmin j hj).ne') + rw [he] at hh + rw [List.flatMap_cons, List.append_assoc, ← hh] + exact split_first f k xs ho hle + +end Grouping + +private theorem filter_groups {α β : Type} [DecidableEq β] (f : α → β) (g : β → List α) + (h : ∀ k x, x ∈ g k → f x = k) (ks : List β) (hn : ks.Nodup) (k : β) : + (ks.flatMap g).filter (fun x => f x = k) = if k ∈ ks then g k else [] := by + induction ks with + | nil => simp + | cons i ks ih => + rw [List.flatMap_cons, List.filter_append, ih hn.of_cons] + by_cases he : i = k + · subst i + rw [List.filter_eq_self.mpr (by simpa using h k)] + simp [(List.nodup_cons.mp hn).1] + · rw [List.filter_eq_nil_iff.mpr (by + intro x hx + simp [h i x hx, he])] + simp [Ne.symm he] + +variable {α : Type} {s : ℕ} (d : α → Val (word s)) + +private theorem real_subset {xs ys : List (Bool × α)} (h : xs.Sublist ys) : + (real xs).Sublist (real ys) := (h.filter _).map _ + +private def Windows (P : ℕ) (xs : List (Bool × α)) : Prop := + ∀ i r, r ≤ P → homogeneous d (real ((xs.drop i).take r)) + +private theorem windows_blank {P : ℕ} {xs : List (Bool × α)} (hx : real xs = []) : + Windows d P xs := by + intro i r _ + have h := real_subset ((xs.drop i).take_sublist r |>.trans (xs.drop_sublist i)) + simp only [hx, List.sublist_nil] at h + simp [h, homogeneous] + +private theorem windows_cons {P : ℕ} {xs : List (Bool × α)} (junk : α) + (h : Windows d P xs) : Windows d P ((true, junk) :: xs) := by + rintro (_ | i) (_ | r) hr + · simp [real, homogeneous] + · simpa [real] using h 0 r (by omega) + · simp [real, homogeneous] + · exact h i (r + 1) hr + +private theorem windows_group {P : ℕ} {xs : List (Bool × α)} (h : Windows d P xs) + (junk : α) (ys : List (Bool × α)) (hy : homogeneous d (real ys)) : + Windows d P (ys ++ List.replicate P (true, junk) ++ xs) := by + induction ys with + | nil => + have pad (n : ℕ) : Windows d P (List.replicate n (true, junk) ++ xs) := by + induction n with + | zero => exact h + | succ n ih => simpa only [List.replicate_succ, List.cons_append] using windows_cons d junk ih + exact pad P + | cons y ys ih => + rintro (_ | i) r hr + · let buf := (y :: ys) ++ List.replicate P (true, junk) + change homogeneous d (real ((buf ++ xs).take r)) + rw [List.take_append_of_le_length (by simp [buf]; omega)] + have hs := (real_subset (List.take_sublist r buf)).subset + have hb : real buf = real (y :: ys) := by unfold buf; rw [real_append]; simp [real] + rw [hb] at hs + exact fun _ hu _ hv => hy _ (hs hu) _ (hs hv) + · have hs := (real_subset (List.sublist_cons_self y ys)).subset + exact ih (fun _ hu _ hv => hy _ (hs hu) _ (hs hv)) i r hr + +private theorem windows_chunk {P : ℕ} {bs : List (List (Bool × α))} + (h : Windows d P bs.flatten) (b : List (Bool × α)) (hb : b ∈ bs) (hl : b.length = P) : + homogeneous d (real b) := by + obtain ⟨l, r, rfl⟩ := List.mem_iff_append.mp hb + simpa only [List.flatten_append, List.flatten_cons, List.drop_left, List.take_left] using + h l.flatten.length b.length hl.le + +private theorem no_live {bs : List (List (Bool × α))} (h : real bs.flatten = []) : + bs.filter live = [] := by + induction bs with + | nil => rfl + | cons b bs ih => + simp only [List.flatten_cons, real_append, List.append_eq_nil_iff] at h + simp [live, h.1, ih h.2] + +private theorem live_bound {P : ℕ} (bs : List (List (Bool × α))) + (hl : ∀ b ∈ bs, b.length = P) (xs zs : List (Bool × α)) + (hz : real zs = []) (he : bs.flatten = xs ++ zs) : + (bs.filter live).length * P ≤ xs.length + P := by + induction bs generalizing xs with + | nil => simp + | cons b bs ih => + obtain ⟨hb, hl⟩ := List.forall_mem_cons.mp hl + have hh : bs.flatten = (xs ++ zs).drop P := by + rw [← he, List.flatten_cons, ← hb, List.drop_left] + have ht : (bs.filter live).length * P ≤ xs.length := by + by_cases hp : P ≤ xs.length + · rw [List.drop_append_of_le_length hp] at hh + simpa [Nat.sub_add_cancel hp] using ih hl _ hh + · rw [List.drop_append, List.drop_eq_nil_of_le (by omega), List.nil_append] at hh + have hs := real_subset (List.drop_sublist (P - xs.length) zs) + rw [← hh, hz, List.sublist_nil] at hs + simp [no_live hs] + rw [List.filter_cons] + split + · rw [List.length_cons, Nat.succ_mul]; omega + · omega + +private def digitBlock (xs : List α) (junk : α) (P : ℕ) (k : Val (word s)) : + List (Bool × α) := + (xs.filter (fun x => d x = k)).map (false, ·) ++ List.replicate P (true, junk) + +private theorem real_mark (xs : List α) : real (xs.map (false, ·)) = xs := by + simp [real, List.filter_map, Function.comp_def] + +private theorem real_pad (junk : α) (P : ℕ) : + real (List.replicate P (true, junk)) = [] := by simp [real] + +private theorem block_bounds (xs : List α) (junk : α) (P : ℕ) (ks : List (Val (word s))) + (tail : List (Bool × α)) (ht : real tail = []) : + let body := ks.flatMap (digitBlock d xs junk P) + Windows d P (body ++ tail) ∧ body.length = (real body).length + ks.length * P ∧ + real body = ks.flatMap (fun k => xs.filter (fun x => d x = k)) := by + induction ks with + | nil => simpa [real] using windows_blank d ht + | cons k ks ih => + obtain ⟨hh, hl, hr⟩ := ih + simp only [List.flatMap_cons, List.append_assoc, digitBlock, real_append, real_mark, real_pad, + List.length_append, List.length_cons, List.length_map, List.length_replicate, + Nat.succ_mul, List.nil_append] + refine ⟨?_, by omega, by rw [hr]⟩ + rw [← List.append_assoc] + apply windows_group d hh junk + rw [real_mark] + intro x hx y hy + exact (of_decide_eq_true (List.mem_filter.mp hx).2).trans + (of_decide_eq_true (List.mem_filter.mp hy).2).symm + +private abbrev Row (s : ℕ) (α : Type) := Val (word (s + 1)) × (Bool × α) + +private theorem filter_decorate (xs : List (Bool × α)) (k : Val (word s)) : + ((xs.map (decorate d)).filter (fun x => x.1 = (false, k))).map Prod.snd = + ((real xs).filter (fun x => d x = k)).map (false, ·) := by + induction xs with + | nil => rfl + | cons x xs ih => + obtain ⟨f, x⟩ := x + cases f <;> by_cases h : d x = k <;> simp_all [decorate, real] + +private theorem filter_filler (junk : α) (keys : List (Val (word s))) (hn : keys.Nodup) + (P e : ℕ) (k : Val (word s)) (hk : k ∈ keys) : + ((filler junk keys P e).filter (fun x => x.1 = (false, k))).map Prod.snd = + List.replicate P (true, junk) := by + let mark (i : Val (word s)) : Val (word (s + 1)) := (false, i) + have hm : Function.Injective mark := fun _ _ h => congrArg Prod.snd h + let pads (i : Val (word (s + 1))) := List.replicate P (i, true, junk) + have hx := filter_groups Prod.fst pads (by simp [pads]) (keys.map mark) + (hn.map hm) (mark k) + rw [ite_eq_left (List.mem_map.mpr ⟨k, hk, rfl⟩)] at hx + simp only [List.flatMap_map, mark, pads] at hx + simp [filler, hx] + +private theorem blank_tail (ys : List (Row s α)) (xs : List (Bool × α)) (junk : α) + (keys : List (Val (word s))) (P e : ℕ) + (h : ys.Perm (xs.map (decorate d) ++ filler junk keys P e)) : + real ((ys.filter (fun y => y.1.1)).map Prod.snd) = [] := by + unfold real + rw [List.map_eq_nil_iff, List.filter_eq_nil_iff] + intro x hx + obtain ⟨y, hy, rfl⟩ := List.mem_map.mp hx + obtain ⟨hy, ht⟩ := List.mem_filter.mp hy + rcases List.mem_append.mp (h.mem_iff.mp hy) with hy | hy + · obtain ⟨z, _, rfl⟩ := List.mem_map.mp hy + simpa [decorate] using ht + · simp [filler] at hy + grind + +private theorem real_perm (ys : List (Row s α)) (xs : List (Bool × α)) (junk : α) + (keys : List (Val (word s))) (P e : ℕ) + (h : ys.Perm (xs.map (decorate d) ++ filler junk keys P e)) : + (real (ys.map Prod.snd)).Perm (real xs) := by + have he : real ((filler junk keys P e).map Prod.snd) = [] := by + simp [filler, real, List.filter_flatMap, List.map_flatMap] + have hp : (real (ys.map Prod.snd)).Perm + (real ((xs.map (decorate d) ++ filler junk keys P e).map Prod.snd)) := + ((h.map _).filter _).map _ + simpa [real_append, he, decorate, Function.comp_def] using hp + +private theorem layout (xs : List (Bool × α)) (junk : α) + (keys ks : List (Val (word s))) (hn : keys.Nodup) (ha : ∀ k, k ∈ keys) + (hk : ks.Pairwise (· < ·)) (hall : ∀ k, k ∈ ks) (P e : ℕ) (ys : List (Row s α)) + (hs : Stable (s := s + 1) Prod.fst (xs.map (decorate d) ++ filler junk keys P e) ys) : + ys.map Prod.snd = ks.flatMap (digitBlock d (real xs) junk P) ++ + (ys.filter (fun y => y.1.1)).map Prod.snd := by + let mark (k : Val (word s)) : Val (word (s + 1)) := (false, k) + have ho : (ks.map mark).Pairwise (wordOrder (s + 1)).lt := by + apply List.pairwise_map.mpr + refine hk.imp fun {a b} h => ?_ + exact Prod.Lex.toLex_lt_toLex.mpr (.inr ⟨rfl, h⟩) + have ht (k) (hm : k ∈ ks.map mark) (x : Row s α) (hx : x.1.1 = true) : + (wordOrder (s + 1)).lt k x.1 := by + obtain ⟨i, _, rfl⟩ := List.mem_map.mp hm + exact Prod.Lex.toLex_lt_toLex.mpr (.inl (by simp [hx])) + have hc (x : Row s α) (_ : x ∈ ys) : x.1 ∈ ks.map mark ∨ x.1.1 = true := by + obtain ⟨⟨_ | _, k⟩, _⟩ := x + · exact .inl (List.mem_map.mpr ⟨k, hall k, rfl⟩) + · exact .inr rfl + have eq := @group_prefix _ _ (wordOrder (s + 1)) (valDecidableEq _) Prod.fst + (fun y : Row s α => y.1.1) (ks.map mark) ho ht ys hs.2.1 hc + conv_lhs => rw [eq] + rw [List.map_append, List.flatMap_map, List.map_flatMap] + congr 1 + apply List.flatMap_congr + intro k _ + rw [hs.2.2 (mark k), List.filter_append, List.map_append] + exact congrArg₂ (· ++ ·) (filter_decorate d xs k) (filter_filler junk keys hn P e k (ha k)) + +private theorem ordered_groups (xs : List α) (ks : List (Val (word s))) + (hk : ks.Pairwise (· < ·)) : + (ks.flatMap (fun k => xs.filter (fun x => d x = k))).Pairwise (fun x y => d x ≤ d y) := by + apply List.pairwise_flatMap.mpr + constructor + · intro i _ + refine List.pairwise_iff_get.mpr fun x y _ => ?_ + have he (j) : d ((xs.filter (fun x => d x = i)).get j) = i := + of_decide_eq_true (List.mem_filter.mp (List.get_mem _ j)).2 + rw [he, he] + · refine hk.imp fun h x hx y hy => ?_ + rw [of_decide_eq_true (List.mem_filter.mp hx).2, of_decide_eq_true (List.mem_filter.mp hy).2] + exact h.le + +/-- Local stable sorting with P delimiters per digit isolates all digits in +the output packs. Only packs overlapping the real-key prefix can be live. -/ +theorem packing (xs : List (Bool × α)) (junk : α) (keys : List (Val (word s))) + (hn : keys.Nodup) (ha : ∀ k, k ∈ keys) (P e : ℕ) + (ys : List (Val (word (s + 1)) × (Bool × α))) + (hs : Stable (s := s + 1) Prod.fst (xs.map (decorate d) ++ filler junk keys P e) ys) + (bs : List (List (Bool × α))) (hl : ∀ b ∈ bs, b.length = P) (hf : bs.flatten + = ys.map Prod.snd) : + (∀ b ∈ bs, homogeneous d (real b)) ∧ + (bs.filter live).length * P ≤ (real xs).length + (keys.length + 1) * P ∧ + Stable d (real xs) (real bs.flatten) := by + let ks := keys.insertionSort (· ≤ ·) + have hk : ks.Perm keys := List.perm_insertionSort _ _ + have hall := fun k => hk.mem_iff.mpr (ha k) + have hnodup := hk.nodup_iff.mpr hn + have hord : ks.Pairwise (· < ·) := + ((List.pairwise_insertionSort (· ≤ ·) keys).and hnodup).imp (fun h => lt_of_le_of_ne h.1 h.2) + let body := ks.flatMap (digitBlock d (real xs) junk P) + let tail := (ys.filter (fun y => y.1.1)).map Prod.snd + have hey : bs.flatten = body ++ tail := + hf.trans (layout d xs junk keys ks hn ha hord hall P e ys hs) + have ht : real tail = [] := blank_tail d ys xs junk keys P e hs.1 + obtain ⟨hw, hm, hg⟩ := block_bounds d (real xs) junk P ks tail ht + have hp : (real bs.flatten).Perm (real xs) := by + rw [hf] + exact real_perm d ys xs junk keys P e hs.1 + have hr : real bs.flatten = real body := by rw [hey, real_append, ht, List.append_nil] + refine ⟨(fun b hb => windows_chunk d (hey ▸ hw) b hb (hl b hb)), ?_, hp, ?_, ?_⟩ + · calc + _ ≤ body.length + P := live_bound bs hl body tail ht hey + _ = _ := by rw [hm, ← hr, hp.length_eq, hk.length_eq, Nat.succ_mul, Nat.add_assoc] + · rw [hr, hg] + exact ordered_groups d (real xs) ks hord + · intro k + rw [hr, hg, filter_groups d _ (by simp) _ hnodup, ite_eq_left (hall k)] + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- +# Stable sorting with tagged permutations + +Label each record by its input position. Compare by digit, then by +position. A final comparison by record makes the order total even +outside the set of correctly labelled records. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix +open Tagged + +variable {a : Wire} {s w : ℕ} + +theorem indices_sorted (w : ℕ) : (flatten w (indices w)).Pairwise (· < ·) := by + induction w with + | zero => simp [flatten] + | succ w ih => + simp only [indices, flatten, flatten_mapRows, List.pairwise_append, List.pairwise_map] + refine ⟨?_, ?_, ?_⟩ + · refine ih.imp fun h => ?_ + exact Prod.Lex.toLex_lt_toLex.mpr (.inr ⟨rfl, h⟩) + · refine ih.imp fun h => ?_ + exact Prod.Lex.toLex_lt_toLex.mpr (.inr ⟨rfl, h⟩) + · intro x hx y hy + obtain ⟨i, _, rfl⟩ := List.mem_map.mp hx + obtain ⟨j, _, rfl⟩ := List.mem_map.mp hy + exact Prod.Lex.toLex_lt_toLex.mpr (.inl (show false < true by decide)) + +private theorem label_values (w : ℕ) (x : Val (tree w a)) : + (flatten w (label w x)).map Prod.snd = flatten w x := by + have h (n : ℕ) (y : Val (tree n a)) (i : Val (tree n (word w))) : + (flatten n (zipRows (c := row w a) (fun u v => (v, u)) n y i)).map Prod.snd = + flatten n y := by + induction n with + | zero => rfl + | succ n ih => simp only [flatten, zipRows, List.map_append, ih] + exact h w x (indices w) + +private abbrev priority [LinearOrder (Val a)] (d : Val a → Val (word s)) (w : ℕ) : + LinearOrder (Val (row w a)) := + LinearOrder.lift' (fun z : Val (row w a) => toLex (d z.2, toLex z)) + (fun _ _ h => congrArg Prod.snd h) + +private theorem stable_label [LinearOrder (Val a)] (d : Val a → Val (word s)) + (x : Val (tree w a)) (ys : List (Val (row w a))) + (hp : ys.Perm (flatten w (label w x))) (hs : ys.Pairwise (priority d w).le) : + Stable d (flatten w x) (ys.map Prod.snd) := by + rw [← label_values w x] + refine ⟨hp.map _, List.pairwise_map.mpr ?_, ?_⟩ + · refine hs.imp fun {i j} h => ?_ + rcases (Prod.Lex.toLex_le_toLex (x := (d i.2, toLex i)) (y := (d j.2, toLex j))).mp h with h | h + · exact h.le + · exact h.1.le + · intro k + let p : Val (row w a) → Bool := fun i => decide (d i.2 = k) + have hi : (flatten w (label w x)).Pairwise (fun i j => i.1 < j.1) := + List.pairwise_map.mp (by rw [label_tags]; exact indices_sorted w) + have hx : ((flatten w (label w x)).filter p).Pairwise (priority d w).le := by + refine List.pairwise_filter.mpr (hi.imp fun {i j} h h₁ h₂ => ?_) + exact Prod.Lex.toLex_le_toLex.mpr (.inr ⟨(of_decide_eq_true h₁).trans (of_decide_eq_true + h₂).symm, + Prod.Lex.toLex_le_toLex.mpr (.inl h)⟩) + let _ := priority d w + have he := List.Perm.eq_of_pairwise' (hs.filter p) hx (hp.filter p) + rw [List.filter_map, List.filter_map] + exact congrArg (List.map Prod.snd) he + +variable {F : Type} [Field F] {W m c : ℕ} + +theorem stable_net {digit : Val a → Val (word s)} (hd : DNet F a (word s) digit c) + (hW : 1 + w + wd a + s ≤ W) (h : Net F (Tagged.inputs w (word W)) .unit (tag F w (word W)) m) : + ∃ f : Val (tree w a) → Val (tree w a), + DNet F (tree w a) (tree w a) f (4 * m + 1000000 * 2 ^ w * (W + c)) ∧ + ∀ x, Stable digit (flatten w x) (flatten w (f x)) := by + obtain ⟨encode, he, hi⟩ := Rewire.exists_of_width (wd_word (wd a)).symm + let _ : LinearOrder (Val a) := LinearOrder.lift' encode hi + have acmp : DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) (100 * (wd a + 1)) := + (compare_lt F (wd a)).pre (he.par he) + have cmp : letI := priority digit w + letI : LT (Val (row w a)) := (priority digit w).toLT + DNet F (.pair (row w a) (row w a)) .bit (fun x => decide (x.1 < x.2)) (800 * W + 2 * c) := by + let _ : LinearOrder (Val (row w a)) := + @Prod.Lex.instLinearOrder _ _ (wordOrder w) inferInstance + have key := ((DNet.snd F (word w) a).comp hd).pair (DNet.id F (row w a)) + have pos := lex_compare (compare_lt F w) acmp + have all := (key.par key).comp (lex_compare (compare_lt F s) pos) + exact all.mono (n := 800 * W + 2 * c) (by simp only [wd, wd_word]; omega) + let _ := priority digit w + have ha := tag_slices (b := row w a) (Batch.of_net h 1) 0 + (by simp only [wd, wd_word]; omega) + have hs := sort_of_tag ha cmp + have net := ((label_net F w a).comp ((hs.pre (.unit' _)).post (.unit _))).comp + (mapRows_net (DNet.snd F (word w) a) w) + refine ⟨_, net.mono ?_, ?_⟩ + · simp only [wd, wd_word] + have hm := Nat.mul_le_mul_left (2 ^ w) hW + ring_nf at hm ⊢ + omega + · intro x + rw [flatten_mapRows] + exact stable_label digit x _ (sortTree_perm ..) (sortTree_sorted ..) + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- +# Sorting packs and discarding the empty tail + +All records in a nonempty pack agree on their digit. Stability on packs +therefore preserves order within each digit at the level of records. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +variable {α β : Type} {s : ℕ} (d : α → Val (word s)) + (key : β → Val (word (s + 1))) (load : β → List α) + +/-- Requires `((key b).1 = true ↔ load b = []) ∧ ∀ x ∈ load b, key b = (false, d x)`. -/ +def packSpec (b : β) : Prop := + ((key b).1 = true ↔ load b = []) ∧ ∀ x ∈ load b, key b = (false, d x) + +private theorem filter_load (z : Val (word s)) (bs : List β) + (hm : ∀ b ∈ bs, packSpec d key load b) : + (bs.flatMap load).filter (fun x => d x = z) = + (bs.filter (fun b => key b = (false, z))).flatMap load := by + induction bs with + | nil => rfl + | cons b bs ih => + have hb := (hm b (by simp)).2 + have he := ih (fun i hi => hm i (by simp [hi])) + by_cases h : key b = (false, z) + · have hs : (load b).filter (fun x => d x = z) = load b := + List.filter_eq_self.mpr fun x hx => by + simp only [decide_eq_true_eq] + exact congrArg Prod.snd ((hb x hx).symm.trans h) + simp [h, he, hs] + · have hs : (load b).filter (fun x => d x = z) = [] := + List.filter_eq_nil_iff.mpr fun x hx => by + simp only [decide_eq_true_eq] + exact fun e => h (by rw [hb x hx, e]) + simp [h, he, hs] + +private theorem unpack_order (xs : List β) (hm : ∀ b ∈ xs, packSpec d key load b) + (hs : xs.Pairwise (fun b c => (wordOrder (s + 1)).le (key b) (key c))) : + (xs.flatMap load).Pairwise (fun x y => d x ≤ d y) := by + have transfer (b c : β) (hb : b ∈ xs) (hc : c ∈ xs) + (he : (wordOrder (s + 1)).le (key b) (key c)) (x : α) (hx : x ∈ load b) + (y : α) (hy : y ∈ load c) : d x ≤ d y := by + rw [(hm b hb).2 x hx, (hm c hc).2 y hy] at he + exact ((Prod.Lex.toLex_le_toLex.mp he).resolve_left (lt_irrefl false)).2 + apply List.pairwise_flatMap.mpr + refine ⟨?_, hs.imp_of_mem (fun hb hc he => transfer _ _ hb hc he)⟩ + intro b hb + exact List.pairwise_iff_getElem.mpr fun _ _ _ _ _ => + transfer _ _ hb hb ((wordOrder (s + 1)).le_refl _) _ (List.getElem_mem _) _ (List.getElem_mem _) + +theorem sort_packs (xs ys zs : List β) (hm : ∀ b ∈ xs, packSpec d key load b) + (hs : Stable (s := s + 1) key xs (ys ++ zs)) + (hcap : (xs.filter (fun b => !(load b).isEmpty)).length ≤ ys.length) : + Stable d (xs.flatMap load) (ys.flatMap load) := by + obtain ⟨hp, ho, hf⟩ := hs + have ht : ∀ b ∈ ys ++ zs, packSpec d key load b := fun b hb => hm b (hp.subset hb) + have hz : zs.flatMap load = [] := by + apply List.flatMap_eq_nil_iff.mpr + intro z hz + by_contra hload + have hkey := (ht z (List.mem_append_right _ hz)).1 + have hz' : (key z).1 = false := Bool.eq_false_iff.mpr (mt hkey.mp hload) + have hy : ys.filter (fun b => !(load b).isEmpty) = ys := by + apply List.filter_eq_self.mpr + intro y hy + have hc := (List.pairwise_append.mp ho).2.2 y hy z hz + have hx := (ht y (List.mem_append_left _ hy)).1 + have hl : load y ≠ [] := by + intro e + have hlt : true < false := by + simpa [hx.mpr e, hz'] using Prod.Lex.toLex_le_toLex.mp hc + exact (by decide : ¬ (true < false)) hlt + simp [hl] + have hp' := (hp.filter (fun b => !(load b).isEmpty)).length_eq + rw [List.filter_append, hy, List.length_append] at hp' + have hv : z ∈ zs.filter (fun b => !(load b).isEmpty) := by simp [hz, hload] + have := List.length_pos_of_mem hv + omega + have he : (ys ++ zs).flatMap load = ys.flatMap load := by simp [hz] + rw [← he] + refine ⟨hp.flatMap (fun _ _ => .refl _), unpack_order d key load _ ht ho, fun z => ?_⟩ + rw [filter_load d key load z _ ht, filter_load d key load z _ hm, hf] + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- # Reading the digit of a pack in linear time -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +variable {a : Wire} {s : ℕ} (d : Val a → Val (word s)) + +/-- Computes the pack by the application `tree q (slot a)`. -/ +abbrev pack (q : ℕ) (a : Wire) := tree q (slot a) + +/-- Computes the content by the application `real (flatten q x)`. -/ +def content (q : ℕ) (x : Val (pack q a)) : List (Val a) := + real (flatten q x) + +/-- Returns `k` when `x.1` holds, and `(false, d x.2)` otherwise. -/ +def readDigit (k : Val (word (s + 1))) (x : Val (slot a)) : Val (word (s + 1)) := + if x.1 then k else (false, d x.2) + +/-- The value specified by `(flatten q x).foldl (readDigit d) (true, Lookup.zero s)`. -/ +def packKey (q : ℕ) (x : Val (pack q a)) : Val (word (s + 1)) := + (flatten q x).foldl (readDigit d) (true, Lookup.zero s) + +private theorem scan_key (xs : List (Val (slot a))) (k : Val (word (s + 1))) : + (real xs = [] ∧ xs.foldl (readDigit d) k = k) ∨ + ∃ x ∈ real xs, xs.foldl (readDigit d) k = (false, d x) := by + induction xs generalizing k with + | nil => exact .inl ⟨rfl, rfl⟩ + | cons x xs ih => + rcases x with ⟨_ | _, x⟩ + · right + change ∃ y ∈ x :: real xs, xs.foldl (readDigit d) (false, d x) = (false, d y) + rcases ih (false, d x) with ⟨_, he⟩ | ⟨y, hy, he⟩ + · exact ⟨x, .head _, he⟩ + · exact ⟨y, .tail _ hy, he⟩ + · exact ih k + +theorem packKey_spec (q : ℕ) (x : Val (pack q a)) (h : homogeneous d (content q x)) : + packSpec d (packKey d q) (content q) x := by + rcases scan_key d (flatten q x) (true, Lookup.zero s) with ⟨hx, he⟩ | ⟨y, hy, he⟩ + · simp [packSpec, packKey, he, content, hx] + · have hk : packKey d q x = (false, d y) := he + have hl : content q x ≠ [] := List.ne_nil_of_mem hy + refine ⟨by simp [hk, hl], fun z hz => ?_⟩ + rw [hk, h _ hy _ hz] + +variable {F : Type} [Field F] {d} + +theorem packKey_net (hd : DNet F a (word s) d (100 * (1 + wd a + s))) (q : ℕ) : + DNet F (pack q a) (word (s + 1)) (packKey d q) (1000 * 2 ^ q * (1 + wd a + s)) := by + let k := word (s + 1) + have old := DNet.fst F k (slot a) + have slotNet := DNet.snd F k (slot a) + have flag := slotNet.comp (DNet.fst F .bit a) + have get := (slotNet.comp (DNet.snd F .bit a)).comp hd + have key := ((Lookup.const_net F .bit false).par get).pre ((Rewire.unit' _).comp (.swap _ _)) + have step : DNet F (.pair k (slot a)) k (fun x => readDigit d x.1 x.2) + (500 * (1 + wd a + s)) := + (((old.pair key).pair flag).comp (selectWord F (s + 1))).mono + (by simp only [wd, k, wd_word]; omega) + have start := Lookup.const_net F k (true, Lookup.zero s) + have seed := (start.par (DNet.id F (pack q a))).pre ((Rewire.unit' _).comp (.swap _ _)) + apply (seed.comp (Lookup.fold_net F step q)).mono + simp only [k, wd, wd_tree, wd_word] + have h := Nat.one_le_pow q 2 (by decide) + nlinarith [Nat.mul_le_mul_right s h] + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- # Crossing a block boundary without permuting the records -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +variable {a : Wire} {s : ℕ} + +/-- In the case `0, x`, this construction gives `x`. -/ +def gather (q : ℕ) : (b : ℕ) → Val (tree (q + b) a) → Val (tree b (tree q a)) + | 0, x => x + | b + 1, x => (gather q b x.1, gather q b x.2) + +/-- In the case `0, x`, this construction gives `x`. -/ +def scatter (q : ℕ) : (b : ℕ) → Val (tree b (tree q a)) → Val (tree (q + b) a) + | 0, x => x + | b + 1, x => (scatter q b x.1, scatter q b x.2) + +theorem gather_wire (q b : ℕ) : Rewire (tree (q + b) a) (tree b (tree q a)) (gather q b) := by + induction b with + | zero => exact .id _ + | succ b ih => exact ih.par ih + +theorem scatter_wire (q b : ℕ) : Rewire (tree b (tree q a)) (tree (q + b) a) (scatter q b) := by + induction b with + | zero => exact .id _ + | succ b ih => exact ih.par ih + +theorem flatten_gather (q b : ℕ) (x : Val (tree (q + b) a)) : + (flatten b (gather q b x)).flatMap (flatten q) = flatten (q + b) x := by + induction b with + | zero => simp [gather, flatten] + | succ b ih => + change (flatten b (gather q b x.1) ++ flatten b (gather q b x.2)).flatMap (flatten q) + = flatten (q + b) x.1 ++ flatten (q + b) x.2 + exact List.flatMap_append.trans (congrArg₂ (· ++ ·) (ih x.1) (ih x.2)) + +theorem scatter_content (q b : ℕ) (x : Val (tree b (pack q a))) : + real (flatten (q + b) (scatter q b x)) = (flatten b x).flatMap (content q) := by + induction b with + | zero => simp [scatter, flatten, content] + | succ b ih => + change real (flatten (q + b) (scatter q b x.1) ++ flatten (q + b) (scatter q b x.2)) = + (flatten b x.1 ++ flatten b x.2).flatMap (content q) + rw [real_append, List.flatMap_append, ih, ih] + +/-- A partial pass before sorting the packs. The additional space for +separators is charged once per input block. -/ +structure Blocked (d : Val a → Val (word s)) (q k : ℕ) + (xs : List (Val a)) (bs : List (Val (pack q a))) : Prop where + homo : ∀ b ∈ bs, homogeneous d (content q b) + bound : (bs.filter (fun b => !(content q b).isEmpty)).length * 2 ^ q ≤ + xs.length + 2 ^ k * ((2 ^ s + 1) * 2 ^ q) + perm : (bs.flatMap (content q)).Perm xs + keep : ∀ z, (bs.flatMap (content q)).filter (fun x => d x = z) = xs.filter (fun x => d x = z) + +variable {q k : ℕ} {d : Val a → Val (word s)} + +theorem Blocked.append {xs ys : List (Val a)} {bs cs : List (Val (pack q a))} + (h : Blocked d q k xs bs) (g : Blocked d q k ys cs) : + Blocked d q (k + 1) (xs ++ ys) (bs ++ cs) where + homo b hb := (List.mem_append.mp hb).elim (h.homo b) (g.homo b) + bound := by + rw [List.filter_append, List.length_append, List.length_append, add_mul, pow_succ, mul_two, + add_mul] + exact (Nat.add_le_add h.bound g.bound).trans_eq (by omega) + perm := by rw [List.flatMap_append]; exact h.perm.append g.perm + keep z := by rw [List.flatMap_append, List.filter_append, List.filter_append, h.keep, g.keep] + +theorem Blocked.finish {xs : List (Val a)} {bs cs es : List (Val (pack q a))} + (h : Blocked d q k xs bs) + (hg : Stable (packKey d q) bs (cs ++ es)) + (hc : xs.length + 2 ^ k * ((2 ^ s + 1) * 2 ^ q) ≤ cs.length * 2 ^ q) : + Stable d xs (cs.flatMap (content q)) := by + have hm := fun i hi => packKey_spec d q i (h.homo i hi) + have hb := Nat.le_of_mul_le_mul_right (h.bound.trans hc) (pow_pos (by decide) q) + obtain ⟨hp, ho, he⟩ := sort_packs d (packKey d q) (content q) bs cs es hm hg hb + exact ⟨hp.trans h.perm, ho, fun z => (he z).trans (h.keep z)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- +# A local radix pass + +Double the number of slots and fill the new half with separators. +Stable sorting by the augmented key leaves enough empty slots between +digits to make each pack homogeneous. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +variable {F : Type} [Field F] {a : Wire} {s q b U x : ℕ} {d : Val a → Val (word s)} + +private theorem filler_length (junk : Val a) (keys : List (Val (word s))) (P e : ℕ) : + (filler junk keys P e).length = keys.length * P + e := by + simp [filler, List.length_flatMap] + +private theorem packs_content (bs : List (Val (pack q a))) : + real (bs.map (flatten q)).flatten = bs.flatMap (content q) := by + induction bs with + | nil => rfl + | cons b bs ih => simp only [List.map_cons, List.flatten_cons, real_append, ih, + List.flatMap_cons, content] + +private theorem blocked_of_packing (xs : List (Val (slot a))) (junk : Val a) + (keys : List (Val (word s))) (hn : keys.Nodup) (ha : ∀ k, k ∈ keys) (hk : keys.length = 2 ^ s) + (e : ℕ) (ys : List (Val (aug s a))) + (hs : Stable (s := s + 1) Prod.fst (xs.map (decorate d) ++ filler junk keys (2 ^ q) e) ys) + (bs : List (Val (pack q a))) (hf : bs.flatMap (flatten q) = ys.map Prod.snd) : + Blocked d q 0 (real xs) bs := by + have hl : ∀ b ∈ bs.map (flatten q), b.length = 2 ^ q := by + intro b hb + obtain ⟨z, _, rfl⟩ := List.mem_map.mp hb + exact Tagged.length_flatten q z + obtain ⟨hh, hb, ho⟩ := packing d xs junk keys hn ha (2 ^ q) e ys hs + (bs.map (flatten (a := slot a) q)) hl hf + rw [packs_content] at ho + refine ⟨fun z hz => hh _ (List.mem_map.mpr ⟨z, hz, rfl⟩), ?_, ho.1, ho.2.2⟩ + simpa only [List.filter_map, List.length_map, Function.comp_def, live, content, hk, pow_zero, + one_mul] using hb + +theorem local_net (hd : DNet F a (word s) d (100 * (1 + wd a + s))) + (hb : s + 2 ≤ b) (hU : 6 + q + b + wd a + 2 * s ≤ U) (hT : Tag F (q + b + 1) U x) : + ∃ f, DNet F (tree (q + b) (slot a)) (tree (b + 1) (pack q a)) f + (4 * x + 10000000 * 2 ^ (q + b + 1) * U) ∧ + ∀ y, Blocked d q 0 (real (flatten (q + b) y)) (flatten (b + 1) (f y)) := by + obtain ⟨z, hn, ha, _⟩ := Lookup.ordered_keys (word s) + let keys := flatten (wd (word s)) z + have hk : keys.length = 2 ^ s := by simp [keys, Tagged.length_flatten] + let junk := (bits a).symm (fun _ => false) + let e := 2 ^ (q + b) - 2 ^ s * 2 ^ q + have hlen : (filler junk keys (2 ^ q) e).length = 2 ^ (q + b) := by + rw [filler_length, hk, Nat.add_sub_of_le] + rw [← pow_add] + exact Nat.pow_le_pow_right (by decide) (by omega) + obtain ⟨pad, hp⟩ := Lookup.as_tree (a := aug s a) (q + b) _ hlen + have hx : DNet F (slot a) (aug s a) (decorate d) (200 * U) := + (((DNet.id F .bit).par hd).pair (DNet.id F (slot a))).mono (by simp only [wd]; omega) + have prepared := ((Tagged.mapRows_net hx (q + b)).par (Tagged.literal_net F _ pad)).pre (.unit' _) + obtain ⟨sort, hsort, ok⟩ := stable_net (s := s + 1) (DNet.fst F (word (s + 1)) (slot a)) + (by simp only [wd, wd_word]; omega) hT + have proj := Tagged.mapRows_net (DNet.snd F (word (s + 1)) (slot a)) (q + b + 1) + have net := ((prepared.comp hsort).comp proj).post (gather_wire q (b + 1)) + refine ⟨_, net.mono ?_, fun y => ?_⟩ + · simp only [wd_tree, wd, wd_word, pow_succ] + have he := Nat.mul_le_mul_left (2 ^ (q + b)) hU + ring_nf at he ⊢ + omega + · have hs := ok (Tagged.mapRows (a := slot a) (b := aug s a) (decorate d) (q + b) y, pad) + change Stable (s := s + 1) Prod.fst + (flatten (q + b) (Tagged.mapRows (a := slot a) (b := aug s a) (decorate d) (q + b) y) ++ + flatten (q + b) pad) _ at hs + rw [Tagged.flatten_mapRows, hp] at hs + apply blocked_of_packing _ junk keys hn ha hk e _ hs + rw [flatten_gather] + exact Tagged.flatten_mapRows (a := aug s a) (b := slot a) Prod.snd (q + b + 1) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- # Cost allowances for a radix pass and all passes combined -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +/-- The quantity computed by `2 ^ k * (4 * x + 10000000 * 2 ^ (q + b + 1) * U) + (4 * y + +2000000000 * 2 ^ (b + k + 1) * V)`. -/ +def passCost (q b k U V x y : ℕ) : ℕ := + 2 ^ k * (4 * x + 10000000 * 2 ^ (q + b + 1) * U) + (4 * y + 2000000000 * 2 ^ (b + k + 1) * V) + +/-- The quantity computed by `(2 * w / s + 1) * passCost q b k U V x y + 200000 * 2 ^ w * (w + +1)`. -/ +def budget (w s q b k U V x y : ℕ) : ℕ := + (2 * w / s + 1) * passCost q b k U V x y + 200000 * 2 ^ w * (w + 1) + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- +# A radix pass at fixed capacity + +Half the slots are reserved for padding. All blocks are processed +independently, then a single stable sort reorders their packs. If the +number of packs per block is at least four times the digit alphabet +size, the trailing half is entirely empty and can be discarded. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +private theorem blocks_net {F : Type} [Field F] {a : Wire} {q b s m : ℕ} + {d : Val a → Val (word s)} (k : ℕ) + (h : ∃ f, DNet F (tree (q + b) (slot a)) (tree (b + 1) (pack q a)) f m ∧ + ∀ y, Blocked d q 0 (real (flatten (q + b) y)) (flatten (b + 1) (f y))) : + ∃ f, DNet F (tree (q + (b + k)) (slot a)) (tree (b + k + 1) (pack q a)) f (2 ^ k * m) ∧ + ∀ y, Blocked d q k (real (flatten (q + (b + k)) y)) (flatten (b + k + 1) (f y)) := by + induction k with + | zero => simpa using h + | succ k ih => + obtain ⟨f, hf, he⟩ := ih + rw [pow_succ, mul_two, add_mul] + refine ⟨fun y => (f y.1, f y.2), hf.par hf, fun y => ?_⟩ + change Blocked _ _ _ (real (flatten (q + (b + k)) y.1 ++ flatten (q + (b + k)) y.2)) + (flatten (b + k + 1) (f y.1) ++ flatten (b + k + 1) (f y.2)) + rw [real_append] + exact (he y.1).append (he y.2) + +private theorem capacity {s q b k n : ℕ} (hb : s + 2 ≤ b) (hn : 2 * n ≤ 2 ^ (q + (b + k))) : + n + 2 ^ k * ((2 ^ s + 1) * 2 ^ q) ≤ 2 ^ (b + k) * 2 ^ q := by + have h : 2 * (2 ^ s + 1) ≤ 2 ^ b := by + have := Nat.pow_le_pow_right (by decide : 0 < 2) hb + have := (pow_pos (by decide : 0 < 2) s) + rw [pow_add] at * + omega + have h' := Nat.mul_le_mul_right (2 ^ k * 2 ^ q) h + simp only [pow_add] at hn ⊢ + ring_nf at hn h' ⊢ + omega + +private theorem finish_net {F : Type} [Field F] {a : Wire} {q b k s V y : ℕ} + {d : Val a → Val (word s)} (hd : DNet F a (word s) d (100 * (1 + wd a + s))) + (hV : (4 + b + k + s + wd a) * 2 ^ q ≤ V) (hT : Tag F (b + k + 1) V y) (hb : s + 2 ≤ b) : + ∃ f, DNet F (tree (b + k + 1) (pack q a)) (tree (q + (b + k)) (slot a)) f + (4 * y + 2000000000 * 2 ^ (b + k + 1) * V) ∧ + ∀ z xs, 2 * xs.length ≤ 2 ^ (q + (b + k)) → Blocked d q k xs (flatten (b + k + 1) z) → + Stable d xs (real (flatten (q + (b + k)) (f z))) := by + have hw : 1 + (b + k + 1) + wd (pack q a) + (s + 1) ≤ V := by + have h := Nat.mul_le_mul_left (3 + b + k + s) (Nat.one_le_pow q 2 (by decide)) + simp only [wd_tree, wd] + nlinarith only [hV, h] + obtain ⟨f, hf, he⟩ := stable_net (packKey_net hd q) hw hT + let half := tree (b + k) (pack q a) + have net := ((hf.comp (DNet.fst F half half)).post (scatter_wire q (b + k))) + refine ⟨_, net.mono ?_, fun z xs hn hz => ?_⟩ + · have h := Nat.mul_le_mul_left (2 ^ (b + k + 1)) hV + simp only [wd, wd_tree, half, pow_succ] at h ⊢ + ring_nf at h ⊢ + omega + · rw [scatter_content] + exact hz.finish (es := flatten (b + k) (f z).2) (he z) + (by rw [Tagged.length_flatten]; exact capacity hb hn) + +theorem one_pass (F : Type) [Field F] (w s q b k U V x y : ℕ) + (hb : s + 2 ≤ b) (he : q + (b + k) = w + 2) + (hU : 10 * (w + 2) ≤ U) (hV : 10 * (w + 2) * 2 ^ q ≤ V) + (h1 : Tag F (q + b + 1) U x) (h2 : Tag F (b + k + 1) V y) + (a : Wire) (ha : wd a ≤ 2 * w + 1) (d : Val a → Val (word s)) + (hd : DNet F a (word s) d (100 * (1 + wd a + s))) : + ∃ f, DNet F (tree (w + 2) (slot a)) (tree (w + 2) (slot a)) f (passCost q b k U V x y) ∧ + ∀ z, 2 * (real (flatten (w + 2) z)).length ≤ 2 ^ (w + 2) → + Stable d (real (flatten (w + 2) z)) (real (flatten (w + 2) (f z))) := by + rw [← he] + have hu : 6 + q + b + wd a + 2 * s ≤ U := by omega + have hv : (4 + b + k + s + wd a) * 2 ^ q ≤ V := + (Nat.mul_le_mul_right _ (by omega)).trans hV + obtain ⟨f, hf, ef⟩ := blocks_net k (local_net hd hb hu h1) + obtain ⟨g, hg, eg⟩ := finish_net hd hv h2 hb + exact ⟨_, hf.comp hg, fun z hz => eg (f z) _ hz (ef z)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- # Cost of verifying an ordinary tagged permutation by radix sorting -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +theorem tag_exists (F : Type) [Field F] (w : ℕ) : ∃ v, Tag F w w v := by + obtain ⟨v, hv, _⟩ := Net.dense _ _ (Tagged.tag F w (word w)) + exact ⟨v, hv⟩ + +theorem budget_net (F : Type) [Field F] (w s q b k U V x y : ℕ) + (hs : 1 ≤ s) (hb : s + 2 ≤ b) (he : q + (b + k) = w + 2) + (hU : 10 * (w + 2) ≤ U) (hV : 10 * (w + 2) * 2 ^ q ≤ V) + (h1 : Tag F (q + b + 1) U x) (h2 : Tag F (b + k + 1) V y) : + ∃ v ≤ budget w s q b k U V x y, Tag F w w v := by + have one := one_pass F w s q b k U V x y hb he hU hV h1 h2 + let a := word (2 * w + 1) + have ha : wd a = 2 * w + 1 := wd_word _ + obtain ⟨f, hf, hsort⟩ := radix F a (w + 2) s _ hs (one a ha.le) + (show 2 * w ≤ wd a by omega) Prod.snd (DNet.snd F .bit (word (2 * w))) + obtain ⟨v, hv, net⟩ := tag_of_sort hf (fun z hz => + hsort z (show 2 * (real (flatten (w + 2) z)).length ≤ 2 ^ (w + 2) by rw [pow_succ]; omega)) + refine ⟨v, hv.trans ?_, net⟩ + rw [ha, budget, pow_add] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Defs.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Defs.lean new file mode 100644 index 0000000000..54416662b5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Defs.lean @@ -0,0 +1,60 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange + +/-! +# Stable radix passes with spare slots + +A set presence flag denotes an empty slot. Each block receives a +pack's worth of separators for every digit. Stability places these +after the real rows of that digit. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +/-- Requires `ys.Perm xs ∧ ys.Pairwise (fun i j => d i ≤ d j) ∧ ∀ k, ys.filter (fun x => d x = +k) = xs.filter (fun x => d x = k)`. -/ +def Stable {α : Type} {s : ℕ} (d : α → Val (word s)) (xs ys : List α) : Prop := + ys.Perm xs ∧ ys.Pairwise (fun i j => d i ≤ d j) ∧ + ∀ k, ys.filter (fun x => d x = k) = xs.filter (fun x => d x = k) + +/-- Computes the slot by the application `Wire.pair .bit a`. -/ +abbrev slot (a : Wire) := Wire.pair .bit a +/-- The quantity computed by `Wire.pair (word (s + 1)) (slot a)`. -/ +abbrev aug (s : ℕ) (a : Wire) := Wire.pair (word (s + 1)) (slot a) + +/-- Transforms the indexed data by `(xs.filter (fun r => !r.1)).map Prod.snd`. -/ +def real {α : Type} (xs : List (Bool × α)) : List α := + (xs.filter (fun r => !r.1)).map Prod.snd + +theorem real_append {α : Type} (xs ys : List (Bool × α)) : + real (xs ++ ys) = real xs ++ real ys := by simp [real] + +/-- The value specified by `((x.1, d x.2), x)`. -/ +def decorate {α : Type} {s : ℕ} (d : α → Val (word s)) (x : Bool × α) : + Val (word (s + 1)) × (Bool × α) := ((x.1, d x.2), x) + +/-- The indexed operation `keys.flatMap (fun k => List.replicate P ((false, k), true, junk)) ++ +List.replicate e ((true, Lookup.zero s), true, junk)`. -/ +def filler {α : Type} {s : ℕ} (junk : α) (keys : List (Val (word s))) (P e : ℕ) : + List (Val (word (s + 1)) × (Bool × α)) := + keys.flatMap (fun k => List.replicate P ((false, k), true, junk)) ++ + List.replicate e ((true, Lookup.zero s), true, junk) + +/-- The condition `∀ x ∈ xs, ∀ y ∈ xs, d x = d y` on the specified data. -/ +def homogeneous {α : Type} {s : ℕ} (d : α → Val (word s)) (xs : List α) : Prop := + ∀ x ∈ xs, ∀ y ∈ xs, d x = d y + +/-- The value specified by `!(real b).isEmpty`. -/ +def live {α : Type} (b : List (Bool × α)) : Bool := !(real b).isEmpty + +end MatrixMultiplicationAllFields.MatrixExponent.Radix diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Estimate.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Estimate.lean new file mode 100644 index 0000000000..f6f21bea6a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Estimate.lean @@ -0,0 +1,208 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Budget +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics + +/-! +# From wide records to logarithmic-width tagged permutations + +If the wide-record threshold at overhead exponent 1/2 is w^A, set +t = 1/A. Use s = floor(w^t) bits per digit and 2^s records per pack. +Each local call has height 2s+3 and each global call has width at +least 2^s. Both calls cost at most O(w^(t/2)) per payload bit. There +are O(w^(1-t)) passes, yielding the exponent 2-t/2. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix +open Filter + +private theorem scales {t : ℝ} (ht : 0 < t) (ht' : t < 1) (B : ℕ) : + ∀ᶠ w : ℕ in atTop, ∃ s : ℕ, 3 ≤ s ∧ 2 * s ≤ w ∧ + (s : ℝ) ≤ (w : ℝ) ^ t ∧ (w : ℝ) ^ t ≤ 2 * s ∧ w ^ B ≤ 2 ^ s := by + have hn : Tendsto (fun w : ℕ => (w : ℝ)) atTop atTop := tendsto_natCast_atTop_atTop + have hr := (tendsto_rpow_atTop ht).comp hn + have he := isLittleO_rpow_exp_pos_mul_atTop ((B : ℝ) / t) + (by positivity : 0 < Real.log 2 / 2) + filter_upwards [eventually_ge_atTop 1, hr.eventually_ge_atTop 4, + ((tendsto_rpow_atTop (sub_pos.mpr ht')).comp hn).eventually_ge_atTop 2, + hr.eventually he.eventuallyLE] with w hw hl hu hx + change 4 ≤ (w : ℝ) ^ t at hl + change 2 ≤ (w : ℝ) ^ (1 - t) at hu + have hw' : 0 < (w : ℝ) := by exact_mod_cast hw + let s := ⌊(w : ℝ) ^ t⌋₊ + have hs : (s : ℝ) ≤ (w : ℝ) ^ t := Nat.floor_le (by positivity) + have hh : (w : ℝ) ^ t < (s : ℝ) + 1 := Nat.lt_floor_add_one _ + have htwo : (w : ℝ) ^ t ≤ 2 * s := by linarith + refine ⟨s, by exact_mod_cast (show 3 ≤ (s : ℝ) by linarith), ?_, hs, htwo, ?_⟩ + · have h : 2 * (s : ℝ) ≤ w := calc + _ ≤ (w : ℝ) ^ (1 - t) * (w : ℝ) ^ t := mul_le_mul hu hs (by positivity) (by positivity) + _ = w := by rw [← Real.rpow_add hw', sub_add_cancel, Real.rpow_one] + exact_mod_cast h + · have h : (w : ℝ) ^ B ≤ (2 : ℝ) ^ s := calc + _ = ((w : ℝ) ^ t) ^ ((B : ℝ) / t) := by + rw [← Real.rpow_mul hw'.le, mul_div_cancel₀ _ ht.ne', Real.rpow_natCast] + _ ≤ Real.exp (Real.log 2 / 2 * (w : ℝ) ^ t) := by + simpa only [Function.comp_apply, Real.norm_of_nonneg + (by positivity : 0 ≤ ((w : ℝ) ^ t) ^ ((B : ℝ) / t)), + Real.norm_of_nonneg (Real.exp_nonneg _)] using hx + _ ≤ Real.exp (s * Real.log 2) := Real.exp_le_exp.mpr (by + linarith [mul_le_mul_of_nonneg_left htwo (by positivity : 0 ≤ Real.log 2)]) + _ = _ := by rw [Real.exp_nat_mul, Real.exp_log (by norm_num)] + exact_mod_cast h + +private theorem local_width {s w A : ℕ} {t : ℝ} + (ht : t * (A : ℝ) = 1) (hs : 3 ≤ s) (hu : (s : ℝ) ≤ (w : ℝ) ^ t) : + (s + (s + 2) + 1) ^ A ≤ 3 ^ A * w ∧ + ((s + (s + 2) + 1 : ℕ) : ℝ) ^ (1 / 2 : ℝ) ≤ 3 * (w : ℝ) ^ (t / 2) := by + have hl : ((s + (s + 2) + 1 : ℕ) : ℝ) ≤ 3 * (w : ℝ) ^ t := by + have : (3 : ℝ) ≤ s := by exact_mod_cast hs + push_cast + linarith + constructor + · have hh := pow_le_pow_left₀ (by positivity) hl A + rw [mul_pow, ← Real.rpow_mul_natCast (by positivity), ht, Real.rpow_one] at hh + exact_mod_cast hh + · calc + _ ≤ (3 * (w : ℝ) ^ t) ^ (1 / 2 : ℝ) := Real.rpow_le_rpow (by positivity) hl (by norm_num) + _ = (3 : ℝ) ^ (1 / 2 : ℝ) * (w : ℝ) ^ (t / 2) := by + rw [Real.mul_rpow (by positivity) (by positivity), + ← Real.rpow_mul (by positivity), mul_one_div] + _ ≤ _ := mul_le_mul_of_nonneg_right + (Real.rpow_le_self_of_one_le (by norm_num) (by norm_num)) (by positivity) + +private theorem pass_bound {q b k w U x y : ℕ} {L : ℝ} (he : q + (b + k) = w + 2) + (hL : 1 ≤ L) (hx : (x : ℝ) ≤ L * (2 : ℝ) ^ (q + b + 1) * U) + (hy : (y : ℝ) ≤ L * (2 : ℝ) ^ (b + k + 1) * ((U : ℝ) * 2 ^ q)) : + (passCost q b k U (U * 2 ^ q) x y : ℝ) ≤ 20000000000 * L * (2 : ℝ) ^ w * U := by + have h₁ : (2 : ℝ) ^ k * 2 ^ (q + b + 1) = 8 * 2 ^ w := by + rw [← pow_add, show k + (q + b + 1) = 3 + w by omega, pow_add]; norm_num + have h₂ : (2 : ℝ) ^ (b + k + 1) * 2 ^ q = 8 * 2 ^ w := by + rw [← pow_add, show b + k + 1 + q = 3 + w by omega, pow_add]; norm_num + unfold passCost + push_cast + calc + _ ≤ (2 : ℝ) ^ k * (4 * (L * 2 ^ (q + b + 1) * U) + 10000000 * 2 ^ (q + b + 1) * U) + + (4 * (L * 2 ^ (b + k + 1) * (U * 2 ^ q)) + 2000000000 * 2 ^ (b + k + 1) * (U * 2 ^ q)) + := by gcongr + _ = (2 ^ k * 2 ^ (q + b + 1)) * (4 * L + 10000000) * U + + (2 ^ (b + k + 1) * 2 ^ q) * (4 * L + 2000000000) * U := by ring + _ = 8 * (8 * L + 2010000000) * (2 : ℝ) ^ w * U := by rw [h₁, h₂]; ring + _ ≤ _ := by + have : 8 * (8 * L + 2010000000) ≤ 20000000000 * L := by linarith + gcongr + +private theorem budget_bound {w s q b k U V x y : ℕ} {D t : ℝ} + (hw : 1 ≤ w) (ht : t < 1) (hs : (w : ℝ) ^ t ≤ 2 * s) + (hp : (passCost q b k U V x y : ℝ) ≤ D * (2 : ℝ) ^ w * w * (w : ℝ) ^ (t / 2)) : + (budget w s q b k U V x y : ℝ) ≤ (5 * D + 400000) * (2 : ℝ) ^ w * (w : ℝ) ^ (2 - t / 2) := by + have hw' : 1 ≤ (w : ℝ) := by exact_mod_cast hw + have hw0 : 0 < (w : ℝ) := zero_lt_one.trans_le hw' + have hdiv : ((2 * w / s : ℕ) : ℝ) * s ≤ 2 * w := by exact_mod_cast Nat.div_mul_le_self (2 * w) s + have hcnt : ((2 * w / s + 1 : ℕ) : ℝ) ≤ 5 * (w : ℝ) ^ (1 - t) := by + apply le_of_mul_le_mul_right _ (Real.rpow_pos_of_pos hw0 t) + rw [mul_assoc, ← Real.rpow_add hw0, sub_add_cancel, Real.rpow_one, Nat.cast_add, Nat.cast_one] + linarith [mul_le_mul_of_nonneg_left hs (Nat.cast_nonneg (α := ℝ) (2 * w / s)), + Real.rpow_le_self_of_one_le hw' ht.le] + have hsum : (w : ℝ) ^ (1 - t) * w * (w : ℝ) ^ (t / 2) = (w : ℝ) ^ (2 - t / 2) := by + rw [show (2 : ℝ) - t / 2 = (1 - t + 1) + t / 2 by + ring, Real.rpow_add hw0, Real.rpow_add hw0, Real.rpow_one] + have hl : (w : ℝ) + 1 ≤ 2 * (w : ℝ) ^ (2 - t / 2) := by + have hh := Real.rpow_le_rpow_of_exponent_le hw' (show 1 ≤ 2 - t / 2 by linarith) + rw [Real.rpow_one] at hh + linarith + unfold budget + rw [Nat.cast_add, Nat.cast_mul] + calc + _ ≤ 5 * (w : ℝ) ^ (1 - t) * (D * (2 : ℝ) ^ w * w * (w : ℝ) ^ (t / 2)) + + 200000 * (2 : ℝ) ^ w * (2 * (w : ℝ) ^ (2 - t / 2)) := by + apply add_le_add (mul_le_mul hcnt hp (by positivity) (by positivity)) + push_cast + gcongr + _ = _ := by rw [← hsum]; ring + +private theorem extend_bound {F : Type} [Field F] {C p : ℝ} (hp : 0 ≤ p) + (h : ∀ᶠ w : ℕ in atTop, ∃ v, Tag F w w v ∧ (v : ℝ) ≤ C * (2 : ℝ) ^ w * (w : ℝ) ^ p) : + Lookup.ShortTag F p := by + obtain ⟨N, hN⟩ := eventually_atTop.mp h + choose v hv using tag_exists F + let D := max C (∑ i ∈ Finset.range N, (v i : ℝ)) + refine ⟨D, fun w hw => ?_⟩ + by_cases h : N ≤ w + · obtain ⟨m, hm, hm'⟩ := hN w h + exact ⟨m, hm, hm'.trans (by gcongr; exact le_max_left _ _)⟩ + have hh : (v w : ℝ) ≤ D := + (Finset.single_le_sum (f := fun i => (v i : ℝ)) (fun i _ => by positivity) + (Finset.mem_range.mpr (lt_of_not_ge h))).trans (le_max_right _ _) + refine ⟨_, hv w, ?_⟩ + have hD : 0 ≤ D := (Nat.cast_nonneg _).trans hh + calc + (v w : ℝ) ≤ D * 1 * 1 := by simpa using hh + _ ≤ D * (2 : ℝ) ^ w * (w : ℝ) ^ p := + mul_le_mul (mul_le_mul_of_nonneg_left (one_le_pow₀ (by norm_num)) hD) + (Real.one_le_rpow (by exact_mod_cast hw) hp) (by norm_num) (by positivity) + +theorem short_of_wide {F : Type} [Field F] + (wide : WideTag F) : ∃ p : ℝ, 1 < p ∧ p < 2 ∧ Lookup.ShortTag F p := by + obtain ⟨A, hA, C, hC⟩ := wide (1 / 2) (by norm_num) + have hA' : 1 < (A : ℝ) := by exact_mod_cast hA + let t := 1 / (A : ℝ) + have ht : 0 < t := by unfold t; positivity + have ht' : t < 1 := (div_lt_one (by linarith)).mpr hA' + have htA : t * (A : ℝ) = 1 := div_mul_cancel₀ _ (by linarith) + obtain ⟨B, _, E, hE⟩ := wide (t / 2) (by linarith) + let D := max 1 (max C E) + have hD : 1 ≤ D := le_max_left _ _ + have hCD : C ≤ D := (le_max_left _ _).trans (le_max_right _ _) + have hED : E ≤ D := (le_max_right _ _).trans (le_max_right _ _) + let T : ℕ := 30 * 3 ^ A + let R : ℝ := 20000000000 * 3 * D * T + refine ⟨2 - t / 2, by linarith, by linarith, ?_⟩ + apply extend_bound (C := 5 * R + 400000) (by linarith) + filter_upwards [scales ht ht' B] with w h + obtain ⟨s, hs, hs2, hsu, hsl, hexp⟩ := h + let b := s + 2 + let k := w - 2 * s + let U := T * w + have he : s + (b + k) = w + 2 := by omega + have hg : b + k + 1 ≤ w := by omega + have hw : 1 ≤ w := by omega + have hU : 10 * (w + 2) ≤ U := calc + _ ≤ 30 * w := by omega + _ ≤ (30 * 3 ^ A) * w := Nat.mul_le_mul_right w (Nat.le_mul_of_pos_right 30 (by positivity)) + obtain ⟨hwidth, hlocal⟩ := local_width htA hs hsu + obtain ⟨x, hx, hx'⟩ := hC (s + b + 1) U (by omega) + (hwidth.trans (Nat.mul_le_mul_right w (Nat.le_mul_of_pos_left _ (by decide)))) + obtain ⟨y, hy, hy'⟩ := hE (b + k + 1) (U * 2 ^ s) (by omega) + ((Nat.pow_le_pow_left hg B).trans (hexp.trans (Nat.le_mul_of_pos_left _ (by omega)))) + obtain ⟨v, hv, hv'⟩ := budget_net F w s s b k U (U * 2 ^ s) x y (by omega) le_rfl he hU + (Nat.mul_le_mul_right _ hU) hx hy + refine ⟨v, hv', (Nat.cast_le.mpr hv).trans (budget_bound hw ht' hsl ?_)⟩ + have hρ : 1 ≤ (w : ℝ) ^ (t / 2) := Real.one_le_rpow (by exact_mod_cast hw) (by linarith) + have hglobal : ((b + k + 1 : ℕ) : ℝ) ^ (t / 2) ≤ 3 * (w : ℝ) ^ (t / 2) := by + have hh : ((b + k + 1 : ℕ) : ℝ) ^ (t / 2) ≤ (w : ℝ) ^ (t / 2) := + Real.rpow_le_rpow (by positivity) (by exact_mod_cast hg) (by linarith) + linarith + let L := 3 * D * (w : ℝ) ^ (t / 2) + have hL : 1 ≤ L := by unfold L; nlinarith + have hx'' : (x : ℝ) ≤ L * (2 : ℝ) ^ (s + b + 1) * U := calc + _ ≤ _ := hx' + _ ≤ D * (2 : ℝ) ^ (s + b + 1) * U * (3 * (w : ℝ) ^ (t / 2)) := by gcongr + _ = _ := by unfold L; ring + have hy'' : (y : ℝ) ≤ L * (2 : ℝ) ^ (b + k + 1) * ((U : ℝ) * 2 ^ s) := calc + _ ≤ _ := hy' + _ ≤ D * (2 : ℝ) ^ (b + k + 1) * (U * 2 ^ s : ℕ) * (3 * (w : ℝ) ^ (t / 2)) := by gcongr + _ = _ := by unfold L; push_cast; ring + refine (pass_bound he hL hx'' hy'').trans_eq ?_ + unfold L U R + rw [Nat.cast_mul] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Radix diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Protocol.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Protocol.lean new file mode 100644 index 0000000000..8d44373a13 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Protocol.lean @@ -0,0 +1,28 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.WideTag + +/-! # Cost of installing the smaller tagged-permutation calls -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +/-- One layer of the routing protocol, restricted to payloads of length +`h^A`. The inductive cost is that of `L` copies of a shorter verifier. +The constant on the total payload stays bounded as the height ratio shrinks. -/ +def Protocol (F : Type) [Field F] : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ τ : ℝ, 0 < τ → ∃ Y : ℝ, 0 < Y ∧ ∃ J : ℕ, + ∀ A : ℕ, J ≤ A → ∀ ζ : ℝ, 0 < ζ → ∀ᶠ h : ℕ in Filter.atTop, + ∃ l v M L : ℕ, 1 ≤ l ∧ (l : ℝ) ≤ τ * h ∧ Y * (h : ℝ) ^ A ≤ v ∧ + (L : ℝ) * (2 : ℝ) ^ l * v ≤ C * (2 : ℝ) ^ h * (h : ℝ) ^ A ∧ + (M : ℝ) ≤ (2 : ℝ) ^ h * (h : ℝ) ^ A * (h : ℝ) ^ ζ ∧ + ∀ s, Tag F l v s → ∃ m ≤ M + L * s, Tag F h (h ^ A) m + +end MatrixMultiplicationAllFields.MatrixExponent.Radix diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Short.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Short.lean new file mode 100644 index 0000000000..beb892b820 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/Short.lean @@ -0,0 +1,605 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Scan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.WideTag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortOne +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Protocol +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Dense + +/-! +# Checking a tagged permutation by sorting + +Mark the labelled inputs and the proposed outputs with opposite bits. +Sort by the common address and payload, ignoring empty slots. Since +input labels are distinct, a permutation is characterized by consecutive +pairs with equal keys and opposite marks. Their order within a pair is free. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +private def side {α : Type} (b : Bool) (xs : List (Bool × α)) : List α := + (xs.filter (fun r => r.1 == b)).map Prod.snd + +private def paired {α : Type} : List (Bool × α) → Prop + | [] => True + | [_] => False + | x :: y :: xs => x.1 ≠ y.1 ∧ x.2 = y.2 ∧ paired xs + +private theorem side_pair {α : Type} (x y : Bool × α) (xs : List (Bool × α)) + (marks : x.1 ≠ y.1) (same : x.2 = y.2) (b : Bool) : + side b (x :: y :: xs) = x.2 :: side b xs := by + obtain ⟨p, u⟩ := x + obtain ⟨q, v⟩ := y + cases p <;> cases q <;> cases b <;> simp_all [side] + +private theorem paired_iff {α : Type} [LinearOrder α] (xs : List (Bool × α)) + (hs : xs.Pairwise (fun i j => i.2 ≤ j.2)) (hn : (side false xs).Nodup) : + paired xs ↔ (side false xs).Perm (side true xs) := by + induction xs using List.twoStepInduction with + | nil => simp [paired, side] + | singleton x => obtain ⟨_ | _, _⟩ := x <;> simp [paired, side] + | cons_cons x y xs ih _ => + obtain ⟨hx, hys⟩ := List.pairwise_cons.mp hs + obtain ⟨hy, hxs⟩ := List.pairwise_cons.mp hys + have mate (h : (side false (x::y::xs)).Perm (side true (x::y::xs))) : + x.1 ≠ y.1 ∧ x.2 = y.2 := by + have hn' : (side x.1 (x::y::xs)).Nodup := by + cases x.1 + · exact hn + · exact h.nodup hn + have hp : (side x.1 (x::y::xs)).Perm (side (!x.1) (x::y::xs)) := by + cases x.1 + · exact h + · exact h.symm + have hm := hp.subset (show x.2 ∈ side x.1 (x::y::xs) by simp [side]) + have hmy : x.2 ∈ side (!x.1) (y::xs) := by simpa [side] using hm + obtain ⟨z, hz, he⟩ := List.mem_map.mp hmy + have ey : x.2 = y.2 := by + apply le_antisymm (hx y (by simp)) + rw [← he] + rcases List.mem_cons.mp (List.mem_filter.mp hz).1 with rfl | h + · exact le_rfl + · exact hy _ h + refine ⟨fun e => ?_, ey⟩ + simp [side, e, ey] at hn' + by_cases good : x.1 ≠ y.1 ∧ x.2 = y.2 + · have drop := side_pair x y xs good.1 good.2 + rw [drop] at hn + simp only [paired, good.1, good.2, ne_eq, not_false_eq_true, true_and, drop, List.perm_cons] + exact ih hxs (List.nodup_cons.mp hn).2 + · exact iff_of_false (fun h => good ⟨h.1, h.2.1⟩) (fun h => good (mate h)) + +private abbrev recWire (n : ℕ) := word (n + 1) +private abbrev pairState (n : ℕ) := word (n + 3) + +private def pairStep (n : ℕ) (s : Val (pairState n)) (r : Val (recWire n)) : + Val (pairState n) := + (s.1 && (!s.2.1 || (decide (s.2.2.1 ≠ r.1) && decide (s.2.2.2 = r.2))), !s.2.1, r) + +private def slotStep (n : ℕ) (s : Val (pairState n)) (r : Val (slot (recWire n))) : + Val (pairState n) := if r.1 then s else pairStep n s r.2 + +private def finish (n : ℕ) (s : Val (pairState n)) : Bool := s.1 && !s.2.1 + +private theorem skip_empty (n : ℕ) (xs : List (Val (slot (recWire n)))) (s : Val (pairState n)) : + xs.foldl (slotStep n) s = (real xs).foldl (pairStep n) s := by + induction xs generalizing s with + | nil => rfl + | cons x xs ih => + obtain ⟨b, r⟩ := x + cases b <;> simp [slotStep, real, ih] + +private theorem check_pairs (n : ℕ) (xs : List (Val (recWire n))) (ok : Bool) + (last : Val (recWire n)) : + finish n (xs.foldl (pairStep n) (ok, false, last)) = true ↔ ok = true ∧ paired xs := by + induction xs using List.twoStepInduction generalizing ok last with + | nil => simp [finish, paired] + | singleton x => simp [finish, pairStep, paired] + | cons_cons x y xs ih _ => + simp [pairStep, paired, Bool.and_eq_true, ih, and_assoc] + +variable (F : Type) [Field F] + +private theorem slot_net (n : ℕ) : + DNet F (.pair (pairState n) (slot (recWire n))) (pairState n) + (fun x => slotStep n x.1 x.2) (500 * (n + 1)) := by + have old := DNet.fst F (pairState n) (slot (recWire n)) + have next := DNet.snd F (pairState n) (slot (recWire n)) + have ok := old.comp (DNet.fst F .bit (word (n + 2))) + have prev := old.comp (DNet.snd F .bit (word (n + 2))) + have wait := (prev.comp (DNet.fst F .bit (recWire n))).comp + (DNet.table F .bit .bit (fun b => !b) (by decide)) + have blank := next.comp (DNet.fst F .bit (recWire n)) + have x := prev.comp (DNet.snd F .bit (recWire n)) + have y := next.comp (DNet.snd F .bit (recWire n)) + have both := DNet.table F (.pair .bit .bit) .bit (fun p => p.1 && p.2) (by decide) + have either := DNet.table F (.pair .bit .bit) .bit (fun p => p.1 || p.2) (by decide) + have diff := DNet.table F (.pair .bit .bit) .bit (fun p => decide (p.1 ≠ p.2)) (by decide) + have test := (((diff.par (Lookup.eq_net F n)).pre (.middle .bit (word n) .bit (word n))).comp + both) + have matchRow := (x.pair y).comp test + have step := ((ok.pair ((wait.pair matchRow).comp either)).comp both).pair (wait.pair y) + have h := ((old.pair step).pair blank).comp (selectWord F (n + 3)) + exact h.mono (by simp only [wd, wd_word]; omega) + +private def checked (n l : ℕ) (x : Val (tree l (slot (recWire n)))) : Bool := + finish n ((flatten l x).foldl (slotStep n) (true, false, Lookup.zero _)) + +private theorem check_net (n l : ℕ) : + DNet F (tree l (slot (recWire n))) .bit (checked n l) (1000 * 2 ^ l * (n + 1)) := by + have seed := ((Lookup.const_net F (pairState n) (true, false, Lookup.zero _)).par + (DNet.id F (tree l (slot (recWire n))))).pre ((Rewire.unit' _).comp (.swap _ _)) + have done := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 && !x.2) (by decide) + have readout := ((DNet.id F .bit).par (DNet.fst F .bit (recWire n))).comp done + have net := (seed.comp (Lookup.fold_net F (slot_net F n) l)).comp readout + apply net.mono + simp only [wd_tree, wd, wd_word] + have h : 1 ≤ 2 ^ l := Nat.one_le_pow _ _ (by decide) + nlinarith [Nat.mul_le_mul_right n h] + +private def blanks (n : ℕ) : (l : ℕ) → Val (tree l (slot (recWire n))) + | 0 => (true, Lookup.zero _) + | l + 1 => (blanks n l, blanks n l) + +private theorem blanks_empty (n l : ℕ) : real (flatten l (blanks n l)) = [] := by + induction l with + | zero => rfl + | succ l ih => + simp only [blanks, flatten, real, List.filter_append, List.map_append] at * + rw [ih, List.nil_append] + +private def mark {a : Wire} {n : ℕ} (e : Val a → Val (word n)) (b : Bool) (x : Val a) : + Val (slot (recWire n)) := (false, b, e x) + +private abbrev addr (w : ℕ) := Tagged.row w (word w) + +private def prepare (w : ℕ) (e : Val (addr w) → Val (word (2 * w))) + (x : Val (Tagged.inputs w (word w))) : Val (tree (w + 2) (slot (recWire (2 * w)))) := + ((Tagged.mapRows (mark e false) w (Tagged.label w x.1), Tagged.mapRows (mark e true) w x.2), + blanks _ _) + +private theorem prepared {w : ℕ} (e : Val (addr w) → Val (word (2 * w))) + (x : Val (Tagged.inputs w (word w))) : + real (flatten (w + 2) (prepare w e x)) = + (flatten w (Tagged.label w x.1)).map (fun u => (false, e u)) ++ + (flatten w x.2).map (fun u => (true, e u)) := by + have hm (b : Bool) (xs : List (Val (addr w))) : + real (xs.map (mark e b)) = xs.map (fun u => (b, e u)) := by + induction xs with + | nil => rfl + | cons y ys ih => simpa [real, mark] using congrArg (List.cons (b, e y)) ih + have ha (xs ys : List (Val (slot (recWire (2 * w))))) : + real (xs ++ ys) = real xs ++ real ys := by simp [real] + simp only [prepare, blanks, flatten, Tagged.flatten_mapRows, ha, hm] + rw [blanks_empty (2 * w) w, List.nil_append, List.append_nil] + +private theorem prepare_net {w : ℕ} {e : Val (addr w) → Val (word (2 * w))} + (he : Rewire (addr w) (word (2 * w)) e) : + DNet F (Tagged.inputs w (word w)) (tree (w + 2) (slot (recWire (2 * w)))) + (prepare w e) (100 * 2 ^ w * (w + 1)) := by + have hm (b : Bool) : DNet F (addr w) (slot (recWire (2 * w))) (mark e b) + (2 + wd (addr w)) := by + have flag := Lookup.const_net F (.pair .bit .bit) (false, b) + exact (((flag.par ((DNet.id F _).post he)).pre + ((Rewire.unit' _).comp (.swap _ _))).post (.assoc _ _ _)) + have h₁ := (Tagged.label_net F w (word w)).comp (Tagged.mapRows_net (hm false) w) + have h₂ := Tagged.mapRows_net (hm true) w + have padding := Lookup.const_net F _ (blanks (2 * w) (w + 1)) + apply (((h₁.par h₂).par padding).pre (.unit' _)).mono + simp only [wd_tree, wd_word, wd] + ring_nf + omega + +private theorem check_spec {w : ℕ} {e : Val (addr w) → Val (word (2 * w))} + (he : Function.Injective e) (x : Val (Tagged.inputs w (word w))) + (y : Val (tree (w + 2) (slot (recWire (2 * w))))) + (hp : (real (flatten (w + 2) y)).Perm (real (flatten (w + 2) (prepare w e x)))) + (hs : (real (flatten (w + 2) y)).Pairwise (fun i j => (wordOrder (2 * w)).le i.2 j.2)) : + checked (2 * w) (w + 2) y = true ↔ (flatten w x.2).Perm (flatten w (Tagged.label w x.1)) := by + let ys := real (flatten (w + 2) y) + have hm (b : Bool) : (side b ys).Perm (side b (real (flatten (w + 2) (prepare w e x)))) := + (hp.filter _).map _ + rw [prepared e x] at hm + have hl : (side false ys).Perm ((flatten w (Tagged.label w x.1)).map e) := by + simpa [side, List.filter_map, Function.comp_def] using hm false + have hr : (side true ys).Perm ((flatten w x.2).map e) := by + simpa [side, List.filter_map, Function.comp_def] using hm true + have hn := hl.symm.nodup ((Tagged.label_nodup w x.1).map he) + rw [checked, skip_empty, check_pairs, eq_self_iff_true, true_and, paired_iff _ hs hn] + exact ⟨fun h => (List.map_perm_map_iff he).mp (hr.symm.trans (h.symm.trans hl)), + fun h => hl.trans ((h.symm.map e).trans hr.symm)⟩ + +/-- One sort of the marked union suffices. It uses twice the number of +live rows as payloads, leaving half of its slots empty. -/ +theorem tag_of_sort {F : Type} [Field F] {w m : ℕ} + {sort : Val (tree (w + 2) (slot (word (2 * w + 1)))) → Val (tree (w + 2) (slot (word (2 * w + + 1))))} + (h : DNet F (tree (w + 2) (slot (word (2 * w + 1)))) (tree (w + 2) (slot (word (2 * w + + 1)))) sort m) + (hs : ∀ x, (real (flatten (w + 2) x)).length ≤ 2 ^ (w + 1) → + (real (flatten (w + 2) (sort x))).Perm (real (flatten (w + 2) x)) ∧ + (real (flatten (w + 2) (sort x))).Pairwise (fun i j => (wordOrder (2 * w)).le i.2 j.2)) : + ∃ v ≤ m + 100000 * 2 ^ w * (w + 1), Net F (Tagged.inputs w (word w)) .unit + (Tagged.tag F w (word w)) v := by + obtain ⟨e, he, hinj⟩ := Rewire.exists_of_width (a := addr w) (b := word (2 * w)) + (by simp [wd, two_mul]) + have good (x : Val (Tagged.inputs w (word w))) : + checked (2 * w) (w + 2) (sort (prepare w e x)) = true ↔ + (flatten w x.2).Perm (flatten w (Tagged.label w x.1)) := by + obtain ⟨hp, ho⟩ := hs (prepare w e x) (by + rw [prepared e x] + rw [List.length_append, List.length_map, List.length_map, Tagged.length_flatten, + Tagged.length_flatten, pow_succ] + omega) + exact check_spec hinj x _ hp ho + obtain ⟨v, hv, net⟩ := ((prepare_net F he).comp h).comp (check_net F (2 * w) (w + 2)) + have pin := Net.table (F := F) .bit .unit (fun b _ => if b then 1 else 0) (by decide) + refine ⟨v + 1, ?_, ?_⟩ + · have hpos : 0 < 2 ^ w := by positivity + rw [pow_add] at hv + ring_nf at hv ⊢ + omega + · convert net.comp pin using 1 + funext x _ + simp only [Tagged.tag, Tagged.permuted, ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, + Finset.mem_univ, ite_true, good] + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- +# Sorting a long key by stable digit passes + +The last digits are sorted first. When an earlier digit is processed, each +sublist with that digit retains its order. A rewiring keeps the unused key +prefix attached to the suffix during the construction of each digit circuit. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +private theorem split_word (n s : ℕ) : + ∃ f : Val (word (n + s)) → Val (.pair (word s) (word n)), + Rewire (word (n + s)) (.pair (word s) (word n)) f ∧ + ∀ x y, x ≤ y ↔ (f x).1 < (f y).1 ∨ (f x).1 = (f y).1 ∧ (f x).2 ≤ (f y).2 := by + induction s with + | zero => + refine ⟨_, (Rewire.unit' _).comp (.swap _ _), ?_⟩ + intro x y + simp + | succ s ih => + obtain ⟨f, hf, ho⟩ := ih + refine ⟨_, ((Rewire.id .bit).par hf).comp (.assoc' _ _ _), ?_⟩ + rintro ⟨b, x⟩ ⟨c, y⟩ + change toLex (b, x) ≤ toLex (c, y) ↔ + toLex (b, (f x).1) < toLex (c, (f y).1) ∨ + (b, (f x).1) = (c, (f y).1) ∧ (f x).2 ≤ (f y).2 + rw [Prod.Lex.toLex_le_toLex, Prod.Lex.toLex_lt_toLex, Prod.mk.injEq, ho] + tauto + +private theorem combine {α : Type} {s n : ℕ} {d : α → Val (word s)} + {low : α → Val (word n)} {xs ys : List α} (hs : Stable d xs ys) + (hl : xs.Pairwise (fun x y => low x ≤ low y)) : + ys.Pairwise (fun x y => d x < d y ∨ d x = d y ∧ low x ≤ low y) := by + apply List.pairwise_iff_getElem.mpr + intro i j hi hj hij + rcases (List.pairwise_iff_getElem.mp hs.2.1 i j hi hj hij).lt_or_eq with h | h + · exact .inl h + · refine .inr ⟨h, ?_⟩ + have hk := hl.filter (fun x => d x = d ys[j]) + rw [← hs.2.2] at hk + exact List.pairwise_iff_getElem.mp (List.pairwise_filter.mp hk) i j hi hj hij + (decide_eq_true h) (decide_eq_true rfl) + +variable {F : Type} [Field F] {a : Wire} {n s : ℕ} + +private theorem pad_key {p : ℕ} (hp : n ≤ p) (f : Val a → Val (word n)) + (hf : DNet F a (word n) f (wd a)) : + ∃ g : Val a → Val (word p), DNet F a (word p) g (wd a + p) ∧ + ∀ x y, g x ≤ g y → f x ≤ f y := by + obtain ⟨j, rfl⟩ := Nat.exists_eq_add_of_le hp + obtain ⟨u, hu, ho⟩ := split_word n j + obtain ⟨v, hv, hi⟩ := hu.inverse + have hz := Tagged.literal_net F (word j) (Lookup.zero j) + have net := ((hz.par hf).pre ((Rewire.unit' a).comp (.swap _ _))).post hv + refine ⟨_, net.mono (by simp only [wd_word]; omega), ?_⟩ + intro x y h + have huv (z) : u (v z) = z := (hi _ _).mpr rfl + rw [ho, huv, huv] at h + exact (h.resolve_left (lt_irrefl _)).2 + +/-- A pass can rearrange empty slots freely. Only its action on the real +records matters, and the occupancy bound is preserved by permutation. -/ +theorem radix (F : Type) [Field F] (a : Wire) (h s M : ℕ) (hs : 0 < s) + (H : ∀ d : Val a → Val (word s), DNet F a (word s) d (100 * (1 + wd a + s)) → + ∃ f, DNet F (tree h (slot a)) (tree h (slot a)) f M ∧ + ∀ x, 2 * (real (flatten h x)).length ≤ 2 ^ h → + Stable d (real (flatten h x)) (real (flatten h (f x)))) + {n : ℕ} (hn : n ≤ wd a) (f : Val a → Val (word n)) (hf : DNet F a (word n) f (wd a)) : + ∃ g, DNet F (tree h (slot a)) (tree h (slot a)) g ((n / s + 1) * M + 2 ^ h * (1 + wd a)) ∧ + ∀ x, 2 * (real (flatten h x)).length ≤ 2 ^ h → + (real (flatten h (g x))).Perm (real (flatten h x)) ∧ + (real (flatten h (g x))).Pairwise (fun i j => (wordOrder n).le (f i) (f j)) := by + let A := tree h (slot a) + have aux (k : ℕ) (b : Wire) (hw : wd b + s * k ≤ wd a + s) + (q : Val a → Val (.pair b (word (s * k)))) + (hq : DNet F a (.pair b (word (s * k))) q (2 * wd a + s)) : + ∃ g, DNet F A A g (k * M + wd A) ∧ + ∀ x, 2 * (real (flatten h x)).length ≤ 2 ^ h → + (real (flatten h (g x))).Perm (real (flatten h x)) ∧ + (real (flatten h (g x))).Pairwise (fun i j => (q i).2 ≤ (q j).2) := by + induction k generalizing b with + | zero => + refine ⟨_, (DNet.id F A).mono (by simp), fun x _ => ⟨.refl _, ?_⟩⟩ + exact List.pairwise_iff_getElem.mpr fun _ _ _ _ _ => (wordOrder 0).le_refl () + | succ k ih => + obtain ⟨u, hu, ho⟩ := split_word (s * k) s + have key := hq.post ((Rewire.id b).par hu) + have low := key.post (.assoc' _ _ _) + obtain ⟨g, hg, ok⟩ := ih (.pair b (word s)) + (by simp only [wd, wd_word, Nat.mul_succ] at hw ⊢; omega) _ low + have high := (key.comp (DNet.snd F b _)).comp (DNet.fst F (word s) (word (s * k))) + obtain ⟨z, hz, ok'⟩ := H (fun x => (u (q x).2).1) + (high.mono (by simp only [wd, wd_word, Nat.mul_succ] at hw ⊢; omega)) + refine ⟨_, (hg.comp hz).mono (by rw [Nat.succ_mul]; omega), fun x hx => ?_⟩ + obtain ⟨hp, hl⟩ := ok x hx + have hst := ok' (g x) (by rwa [hp.length_eq]) + refine ⟨hst.1.trans hp, ?_⟩ + exact (combine hst hl).imp fun e => (ho _ _).mpr e + have hw : s * (n / s + 1) ≤ wd a + s := by + rw [Nat.mul_succ, Nat.mul_comm s] + exact Nat.add_le_add_right ((Nat.div_mul_le_self n s).trans hn) s + obtain ⟨key, hkey, ho⟩ := pad_key (Nat.lt_mul_div_succ n hs).le f hf + have net := hkey.post ((Rewire.unit' _).comp (.swap _ _)) + obtain ⟨g, hg, ok⟩ := aux (n / s + 1) .unit (by simpa [wd] using hw) _ (net.mono (by omega)) + refine ⟨g, by simpa only [A, wd_tree, wd] using hg, fun x hx => ?_⟩ + obtain ⟨hp, hl⟩ := ok x hx + exact ⟨hp, hl.imp (fun e => ho _ _ e)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- +# Wider payloads at linear cost + +Duplicate only the position tags when joining two verifiers. Payloads +go directly to the two networks, so recursive doubling incurs no +logarithmic factor in their total width. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix +open Tagged + +variable {F : Type} [Field F] {a b c : Wire} {m w : ℕ} + +private theorem common_input {k : Val (.pair a b) → Val .unit → F} + (h : Net F (.pair a b) .unit k m) : + ∃ v ≤ wd a + 2 * m, Net F (.pair a (.pair b b)) .unit + (fun x z => k (x.1, x.2.1) z * k (x.1, x.2.2) z) v := by + obtain ⟨u, hu, dup⟩ := DNet.dup F a + have both := ((h.par h).pre (.middle a a b b)).post (.unit' _) + have rin := (Rewire.assoc a (.pair b b) (.pair a a)).comp + ((Rewire.id a).par (.swap _ _)) + have net := (((dup.par both).pre rin).post (.swap _ _)).trace + refine ⟨u + (m + m), by omega, ?_⟩ + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] using net + +private theorem map_map (f : Val a → Val b) (g : Val b → Val c) (w : ℕ) + (x : Val (tree w a)) : mapRows g w (mapRows f w x) = mapRows (fun y => g (f y)) w x := by + induction w with + | zero => rfl + | succ w ih => exact Prod.ext (ih _) (ih _) + +private theorem separate (w : ℕ) (a b : Wire) : + Rewire (tree w (.pair a b)) (.pair (tree w a) (tree w b)) + (fun x => (mapRows (a := .pair a b) Prod.fst w x, mapRows (a := .pair a b) Prod.snd w x)) + := by + induction w with + | zero => exact .id _ + | succ w ih => exact (ih.par ih).comp (.middle _ _ _ _) + +private abbrev data (w : ℕ) (a : Wire) := Wire.pair (tree w a) (tree w a) +private abbrev tags (w : ℕ) := tree w (word w) + +private def extract (w : ℕ) (a : Wire) (x : Val (Tagged.inputs w a)) : + Val (.pair (tags w) (data w a)) := + (mapRows (a := row w a) Prod.fst w x.2, x.1, mapRows (a := row w a) Prod.snd w x.2) + +private theorem extract_wire (w : ℕ) (a : Wire) : + Rewire (Tagged.inputs w a) (.pair (tags w) (data w a)) (extract w a) := + ((Rewire.id _).par (separate w (word w) a)).comp <| + (Rewire.assoc' _ _ _).comp <| ((Rewire.swap _ _).par (.id _)).comp (.assoc _ _ _) + +private theorem extract_project (f : Val a → Val b) (w : ℕ) (x : Val (Tagged.inputs w a)) : + extract w b (project w f x) = + ((extract w a x).1, mapRows f w (extract w a x).2.1, mapRows f w (extract w a x).2.2) := by + simp only [extract, project, map_map, Prod.map, id_eq] + +private theorem double (h : Net F (Tagged.inputs w a) .unit (tag F w a) m) : + ∃ v ≤ 2 ^ w * w + 2 * m, Net F (Tagged.inputs w (.pair a a)) .unit (tag F w (.pair a a)) v := by + obtain ⟨join, hj, he⟩ := (extract_wire w a).inverse + obtain ⟨v, hv, net⟩ := common_input (h.pre hj) + have sep := separate w a a + have split := (sep.par sep).comp (.middle _ _ _ _) + have hn := net.pre ((extract_wire w (.pair a a)).comp ((Rewire.id _).par split)) + refine ⟨v, by simpa [tags, wd_tree] using hv, ?_⟩ + convert hn using 1 + funext x y + rw [tag_pair] + congr 2 <;> exact (he _ _).mp (extract_project _ w x) + +private theorem double_iter (h : Net F (Tagged.inputs w a) .unit (tag F w a) m) (k : ℕ) : + ∃ n, Net F (Tagged.inputs w (tree k a)) .unit (tag F w (tree k a)) n ∧ + n + 2 ^ w * w ≤ 2 ^ k * (m + 2 ^ w * w) := by + induction k with + | zero => exact ⟨m, h, by simp⟩ + | succ k ih => + obtain ⟨v, hv, hc⟩ := ih + obtain ⟨n, hn, g⟩ := double hv + refine ⟨n, g, ?_⟩ + rw [pow_succ, mul_right_comm] + exact (show n + 2 ^ w * w ≤ (v + 2 ^ w * w) * 2 by omega).trans + (Nat.mul_le_mul_right 2 hc) + +private theorem dyadic_cover {u v : ℕ} (hu : 1 ≤ u) (hv : u ≤ v) : + ∃ k : ℕ, v ≤ 2 ^ k * u ∧ 2 ^ k * u ≤ 2 * v := by + have hex : ∃ k : ℕ, v ≤ 2 ^ k * u := + ⟨v, (Nat.lt_two_pow_self.le).trans (by simpa using Nat.mul_le_mul_left (2 ^ v) hu)⟩ + refine ⟨Nat.find hex, Nat.find_spec hex, ?_⟩ + cases he : Nat.find hex with + | zero => simpa using (show u ≤ 2 * v by omega) + | succ k => + have h := Nat.find_min hex (show k < Nat.find hex by omega) + rw [pow_succ, mul_two, add_mul] + omega + +/-- Split the payload into a dyadic number of slices and pad the last +slice. The overhead is uniform in the ratio of the two widths. -/ +theorem widen {u v : ℕ} (hw : 1 ≤ w) (hu : w ≤ u) (hv : u ≤ v) (ht : Tag F w u m) : + ∃ n, Tag F w v n ∧ n * u ≤ 2 * v * m + 100 * 2 ^ w * v * u := by + obtain ⟨k, h₁, h₂⟩ := dyadic_cover (hw.trans hu) hv + obtain ⟨l, hl, hc⟩ := double_iter ht k + obtain ⟨n, hn, net⟩ := tag_shrink (F := F) (b := word v) (Batch.of_net hl 1) + (by simpa only [wd_tree, wd_word] using h₁) + refine ⟨n, ?_, ?_⟩ + · simpa only [power, mul_one, Tag] using (net.pre (.unit' _)).post (.unit' _) + · simp only [wd_tree, wd_word, one_mul] at hn + have hb : n ≤ 2 ^ k * m + 3 * 2 ^ w * (2 ^ k * u) := by + have hw' := Nat.mul_le_mul_left (2 ^ k * 2 ^ w) hu + ring_nf at hw' hn hc ⊢ + omega + calc + n * u ≤ (2 ^ k * m + 3 * 2 ^ w * (2 ^ k * u)) * u := Nat.mul_le_mul_right _ hb + _ = (2 ^ k * u) * m + 3 * 2 ^ w * (2 ^ k * u) * u := by ring + _ ≤ (2 * v) * m + 3 * 2 ^ w * (2 * v) * u := by gcongr + _ ≤ _ := by ring_nf; omega + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end + +section +/- +# The wide-record recursion + +It is enough to install calls at the threshold width. Once the height +ratio `τ` and width ratio `Y` are fixed, take the threshold exponent +`A` large enough that `τ^A ≤ Y`. Every recursive call then still +meets the wide-record threshold. Slicing handles widths above it. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +variable {F : Type} [Field F] + +private theorem bounded_heights (A N : ℕ) : + ∃ B : ℕ, ∀ h < N, ∃ m ≤ B, Tag F h (h ^ A) m := by + induction N with + | zero => exact ⟨0, by simp⟩ + | succ N ih => + obtain ⟨B, hB⟩ := ih + obtain ⟨m, hm, _⟩ := Net.dense _ _ (Tagged.tag F N (word (N ^ A))) + refine ⟨B + m, fun h hh => ?_⟩ + rcases (Nat.lt_succ_iff.mp hh).eq_or_lt with rfl | hn + · exact ⟨m, by omega, hm⟩ + · obtain ⟨k, hk, ht⟩ := hB h hn + exact ⟨k, by omega, ht⟩ + +private theorem widen_bound {D ζ : ℝ} (hD : 204 ≤ D) (hζ : 0 < ζ) + {h u v m : ℕ} (hh : 1 ≤ h) (hu : h ≤ u) (hv : u ≤ v) (ht : Tag F h u m) + (hm : (m : ℝ) ≤ (1 + D / 4) * (2 : ℝ) ^ h * u * (h : ℝ) ^ ζ) : + ∃ n, Tag F h v n ∧ (n : ℝ) ≤ D * (2 : ℝ) ^ h * v * (h : ℝ) ^ ζ := by + obtain ⟨n, hn, hc⟩ := widen hh hu hv ht + refine ⟨n, hn, le_of_mul_le_mul_right (a := (u : ℝ)) ?_ (by exact_mod_cast (show 0 < u by omega))⟩ + have hr := Real.one_le_rpow (by exact_mod_cast hh : 1 ≤ (h : ℝ)) hζ.le + calc + (n : ℝ) * u ≤ 2 * v * m + 100 * (2 : ℝ) ^ h * v * u := by exact_mod_cast hc + _ ≤ 2 * v * ((1 + D / 4) * (2 : ℝ) ^ h * u * (h : ℝ) ^ ζ) + + 100 * (2 : ℝ) ^ h * v * u * (h : ℝ) ^ ζ := + add_le_add (mul_le_mul_of_nonneg_left hm (by positivity)) + (le_mul_of_one_le_right (by positivity) hr) + _ = (102 + D / 2) * ((2 : ℝ) ^ h * v * (h : ℝ) ^ ζ * u) := by ring + _ ≤ D * ((2 : ℝ) ^ h * v * (h : ℝ) ^ ζ * u) := by gcongr; linarith + _ = _ := by ring + +theorem wide_of_protocol (prot : Protocol F) : WideTag F := by + intro ζ hζ + obtain ⟨C, hC, prop⟩ := prot + let τ := ((4 * C)⁻¹) ^ ζ⁻¹ + have ht : 0 < τ := by unfold τ; positivity + have ht' : τ < 1 := Real.rpow_lt_one (by positivity) (inv_lt_one_of_one_lt₀ (by linarith)) + (inv_pos.mpr hζ) + have hct : C * τ ^ ζ = 1 / 4 := by + unfold τ + rw [Real.rpow_inv_rpow (by positivity) hζ.ne'] + field_simp + obtain ⟨Y, hY, J, rec⟩ := prop τ ht + obtain ⟨a, ha⟩ := exists_pow_lt_of_lt_one hY ht' + let A := a + J + 2 + have hA : 2 ≤ A := by omega + have hratio : τ ^ A ≤ Y := (pow_le_pow_of_le_one ht.le ht'.le (show a ≤ A by omega)).trans ha.le + obtain ⟨N, hN⟩ := Filter.eventually_atTop.mp (rec A (by omega) ζ hζ) + obtain ⟨B, hB⟩ := bounded_heights (F := F) A N + let D : ℝ := 204 + 4 * B + have hD : 204 ≤ D := by unfold D; linarith + refine ⟨A, hA, D, ?_⟩ + intro h + induction h using Nat.strong_induction_on with + | ind h ih => + intro v hh hv + have hh' : 1 ≤ (h : ℝ) := by exact_mod_cast hh + have base : ∃ m, Tag F h (h ^ A) m ∧ (m : ℝ) ≤ (1 + + D / 4) * (2 : ℝ) ^ h * (h : ℝ) ^ A * (h : ℝ) ^ ζ := by + by_cases hsmall : h < N + · obtain ⟨m, hm, hs⟩ := hB h hsmall + refine ⟨m, hs, ?_⟩ + calc + (m : ℝ) ≤ B := by exact_mod_cast hm + _ ≤ (1 + D / 4) * 1 * 1 * 1 := by unfold D; linarith + _ ≤ _ := by + gcongr + · exact one_le_pow₀ (by norm_num) + · exact one_le_pow₀ hh' + · exact Real.one_le_rpow hh' hζ.le + obtain ⟨l, u, M, L, hl, hlt, hu, hsize, hM, make⟩ := hN h (le_of_not_gt hsmall) + have hle : l < h := by + exact_mod_cast hlt.trans_lt (mul_lt_of_lt_one_left (by linarith) ht') + have hwide : l ^ A ≤ u := by + have hp := pow_le_pow_left₀ (Nat.cast_nonneg (α := ℝ) l) hlt A + rw [mul_pow] at hp + exact_mod_cast hp.trans ((mul_le_mul_of_nonneg_right hratio (by positivity)).trans hu) + obtain ⟨s, hs, hc⟩ := ih l hle u hl hwide + obtain ⟨m, hm, htag⟩ := make s hs + have hr : (l : ℝ) ^ ζ ≤ τ ^ ζ * (h : ℝ) ^ ζ := by + rw [← Real.mul_rpow ht.le (by positivity)] + exact Real.rpow_le_rpow (by positivity) hlt hζ.le + have hcost : (L : ℝ) * s ≤ (D / 4) * (2 : ℝ) ^ h * (h : ℝ) ^ A * (h : ℝ) ^ ζ := by + calc + (L : ℝ) * s ≤ L * (D * (2 : ℝ) ^ l * u * (l : ℝ) ^ ζ) + := mul_le_mul_of_nonneg_left hc (by positivity) + _ = D * (L * (2 : ℝ) ^ l * u) * (l : ℝ) ^ ζ := by ring + _ ≤ D * (C * (2 : ℝ) ^ h * (h : ℝ) ^ A) * (τ ^ ζ * (h : ℝ) ^ ζ) := by gcongr + _ = D * (C * τ ^ ζ) * (2 : ℝ) ^ h * (h : ℝ) ^ A * (h : ℝ) ^ ζ := by ring + _ = _ := by rw [hct]; ring + refine ⟨m, htag, ?_⟩ + calc + (m : ℝ) ≤ M + (L : ℝ) * s := by exact_mod_cast hm + _ ≤ _ := by linarith only [hM, hcost] + obtain ⟨m, htag, hm⟩ := base + exact widen_bound hD hζ hh (Nat.le_pow (by omega)) hv htag (by simpa using hm) + +end MatrixMultiplicationAllFields.MatrixExponent.Radix +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/WideTag.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/WideTag.lean new file mode 100644 index 0000000000..4f6154bead --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Radix/WideTag.lean @@ -0,0 +1,27 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.ShortTag + +/-! # Tagged permutation estimates with wider keys -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Radix + +/-- Computes the tag by the application `Net F (Tagged.inputs w (word v)) .unit (Tagged.tag F w +(word v)) m`. -/ +def Tag (F : Type) [Field F] (w v m : ℕ) : Prop := + Net F (Tagged.inputs w (word v)) .unit (Tagged.tag F w (word v)) m + +/-- The wide-record estimate in the conditional stable sorting theorem. -/ +def WideTag (F : Type) [Field F] : Prop := + ∀ ζ : ℝ, 0 < ζ → ∃ A : ℕ, 2 ≤ A ∧ ∃ C : ℝ, ∀ w v : ℕ, 1 ≤ w → w ^ A ≤ v → + ∃ m : ℕ, Tag F w v m ∧ (m : ℝ) ≤ C * (2 : ℝ) ^ w * v * (w : ℝ) ^ ζ + +end MatrixMultiplicationAllFields.MatrixExponent.Radix diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/RankCriterion.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/RankCriterion.lean new file mode 100644 index 0000000000..c641fb4049 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/RankCriterion.lean @@ -0,0 +1,88 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Bilinearize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Flattening +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Growth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Specialization +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics + +/-! +# Strict savings and finite specialization + +The factor two in bilinearization is absorbed before changing fields. +Only one finite decomposition needs to be specialized. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent +open Filter + +variable {F : Type*} [Field F] {a b : ℝ} {n r : ℕ} + +private theorem small_rank (h : Admissible F a) (hab : a < b) : + ∃ n r : ℕ, 2 ≤ n ∧ RankLE (Rat F n) n r ∧ (r : ℝ) < (n : ℝ) ^ b := by + let ε := (b - a) / 2 + have hε : 0 < ε := by dsimp [ε]; linarith + obtain ⟨C, _, hC⟩ := h ε hε + have ht : Tendsto (fun n : ℕ => (n : ℝ) ^ ε) atTop atTop := + (tendsto_rpow_atTop hε).comp tendsto_natCast_atTop_atTop + obtain ⟨n, hn, hp⟩ := ((eventually_ge_atTop 2).and (ht.eventually_gt_atTop (2 * C))).exists + obtain ⟨m, hm, hcost⟩ := hC n (by omega) + refine ⟨n, 2 * m, hn, bilinearize hm, ?_⟩ + have hn0 : 0 < (n : ℝ) := by exact_mod_cast (show 0 < n by omega) + calc + ((2 * m : ℕ) : ℝ) ≤ (2 * C) * (n : ℝ) ^ (a + ε) := by push_cast; linarith + _ < (n : ℝ) ^ ε * (n : ℝ) ^ (a + ε) := + mul_lt_mul_of_pos_right hp (Real.rpow_pos_of_pos hn0 _) + _ = (n : ℝ) ^ b := by rw [← Real.rpow_add hn0, show ε + (a + ε) = b by dsimp [ε]; ring] + +private theorem rank_area (hr : RankLE F n r) : (n : ℝ) ^ (2 : ℝ) ≤ (r : ℝ) := by + rw [Real.rpow_two] + exact_mod_cast rank_lower hr + +theorem two_le_admissible (h : Admissible F a) : 2 ≤ a := by + by_contra! hlt + obtain ⟨n, r, _, hr, hp⟩ := small_rank h hlt + exact (rank_area hr).not_gt hp + +theorem two_le_omega (F : Type*) [Field F] : 2 ≤ omega F := + le_csInf ⟨3, admissible_three F⟩ (fun _ h => two_le_admissible h) + +theorem omega_le_of_admissible (h : Admissible F a) : omega F ≤ a := + csInf_le ⟨2, fun _ h' => two_le_admissible h'⟩ h + +theorem omega_le_of_rank {s : ℝ} (hn : 2 ≤ n) (hr : RankLE F n r) + (hrs : (r : ℝ) ≤ (n : ℝ) ^ s) : omega F ≤ s := + omega_le_of_admissible (admissible_of_rank hn hr hrs) + +theorem omega_lt_of_rank (hn : 2 ≤ n) (hr : RankLE F n r) + (hrs : (r : ℝ) < (n : ℝ) ^ b) : omega F < b := by + have hn1 : 1 < (n : ℝ) := by exact_mod_cast hn + have hr0 : 0 < (r : ℝ) := (Real.rpow_pos_of_pos (by linarith) _).trans_le (rank_area hr) + let s := Real.log (r : ℝ) / Real.log (n : ℝ) + have hs : (n : ℝ) ^ s = r := by + rw [Real.rpow_def_of_pos (by linarith), show Real.log (n : ℝ) * s = Real.log (r : ℝ) by + dsimp [s]; exact mul_div_cancel₀ _ (Real.log_pos hn1).ne', Real.exp_log hr0] + exact (omega_le_of_rank hn hr hs.ge).trans_lt ((Real.rpow_lt_rpow_left_iff hn1).mp + (hs.trans_lt hrs)) + +theorem rank_of_omega_lt (h : omega F < b) : + ∃ n r : ℕ, 2 ≤ n ∧ RankLE (Rat F n) n r ∧ (r : ℝ) < (n : ℝ) ^ b := by + obtain ⟨a, ha, hab⟩ := exists_lt_of_csInf_lt ⟨3, admissible_three F⟩ h + exact small_rank ha hab + +/-- Specialize a strict asymptotic rank bound to a finite field. -/ +theorem finite_specialization (h : omega F < b) : + ∃ (k : Type) (_ : Field k) (_ : Finite k), omega k < b := by + obtain ⟨n, r, hn, hr, hrs⟩ := rank_of_omega_lt h + obtain ⟨k, hk, hf, hkr⟩ := specializeRank hr + exact ⟨k, hk, hf, omega_lt_of_rank hn hkr hrs⟩ + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/RankPower.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/RankPower.lean new file mode 100644 index 0000000000..12f947c850 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/RankPower.lean @@ -0,0 +1,28 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law + +/-! Square specializations of the rectangular rank constructions. -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {F K : Type*} [Field F] [Field K] {n m r s : ℕ} + +theorem rank_map (f : F →+* K) (h : RankLE F n r) : RankLE K n r := + Rectangle.RankLE.map h f + +theorem rank_mul (h : RankLE F n r) (h' : RankLE F m s) : RankLE F (n * m) (r * s) := + Rectangle.RankLE.tensor h h' + +theorem rank_pow (h : RankLE F n r) (k : ℕ) : RankLE F (n ^ k) (r ^ k) := + Rectangle.RankLE.pow h k + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/RationalCircuits.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/RationalCircuits.lean new file mode 100644 index 0000000000..1283c9e325 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/RationalCircuits.lean @@ -0,0 +1,74 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.MatrixRank +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Algebra.MvPolynomial.Basic +public import Mathlib.RingTheory.Localization.FractionRing + +/-! +# Formal arithmetic complexity of square matrix multiplication + +A straight-line computation records the set of available wire values. All +inputs and field constants are initially available. One step adds the value +of one binary gate, with unrestricted reuse. The division rule tests the +denominator in the rational function field, even in positive characteristic. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- Indexes the pos by the coordinates of `Fin n × Fin n`. -/ +abbrev Pos (n : ℕ) := Fin n × Fin n +/-- Indexes the var by the coordinates of `Pos n ⊕ Pos n`. -/ +abbrev Var (n : ℕ) := Pos n ⊕ Pos n +/-- Computes the rat by the application `FractionRing (MvPolynomial (Var n) F)`. -/ +abbrev Rat (F : Type*) [Field F] (n : ℕ) := FractionRing (MvPolynomial (Var n) F) + +/-- Computes the input by the application `algebraMap (MvPolynomial (Var n) F) (Rat F n) +(MvPolynomial.X i)`. -/ +def input (F : Type*) [Field F] {n : ℕ} (i : Var n) : Rat F n := + algebraMap (MvPolynomial (Var n) F) (Rat F n) (MvPolynomial.X i) + +/-- The set of values attained by `(algebraMap F (Rat F n)) ∪ Set.range (input F)`. -/ +def initial (F : Type*) [Field F] (n : ℕ) : Set (Rat F n) := + Set.range (algebraMap F (Rat F n)) ∪ Set.range (input F) + +/-- The quantity computed by `∑ k : Fin n, input F (.inl (p.1, k)) * input F (.inr (k, p.2))`. -/ +def output (F : Type*) [Field F] {n : ℕ} (p : Pos n) : Rat F n := + ∑ k : Fin n, input F (.inl (p.1, k)) * input F (.inr (k, p.2)) + +/-- The build used in the `MatrixExponent` construction. -/ +inductive Build {K : Type*} [Field K] (S : Set K) : ℕ → Set K → Prop + | nil : Build S 0 S + | add {m T x y} : Build S m T → x ∈ T → y ∈ T → Build S (m + 1) (insert (x + y) T) + | sub {m T x y} : Build S m T → x ∈ T → y ∈ T → Build S (m + 1) (insert (x - y) T) + | mul {m T x y} : Build S m T → x ∈ T → y ∈ T → Build S (m + 1) (insert (x * y) T) + | div {m T x y} : Build S m T → x ∈ T → y ∈ T → y ≠ 0 → Build S (m + 1) (insert (x / y) T) + +/-- The condition `∃ T, Build (initial F n) m T ∧ ∀ p : Pos n, output F p ∈ T` on the specified +data. -/ +def Computes (F : Type*) [Field F] (n m : ℕ) : Prop := + ∃ T, Build (initial F n) m T ∧ ∀ p : Pos n, output F p ∈ T + +/-- The condition `∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ n : ℕ, 0 < n → ∃ m : ℕ, Computes F n m ∧ +(m : ℝ) ≤ C * (n : ℝ) ^ (s + ε)` on the specified data. -/ +def Admissible (F : Type*) [Field F] (s : ℝ) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ n : ℕ, 0 < n → + ∃ m : ℕ, Computes F n m ∧ (m : ℝ) ≤ C * (n : ℝ) ^ (s + ε) + +/-- The infimum of `{s | Admissible F s}`. -/ +def omega (F : Type*) [Field F] : ℝ := sInf {s | Admissible F s} + +/-- Coefficient rank for square matrix multiplication. -/ +abbrev RankLE (F : Type*) [CommSemiring F] (n r : ℕ) : Prop := + TensorSpectrum.MatrixRank F n n n r + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Realization.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Realization.lean new file mode 100644 index 0000000000..813c3ebf17 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Realization.lean @@ -0,0 +1,32 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Obstruction +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Hard +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Install + +/-! +# Reduction to the compression installation + +Exact many-list hardness holds over all finite fields. The arithmetic +equality and the rectangular rigidity therefore reduce to the +compression construction over prime fields under shared prices. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem contact_of_installations + (rounds : ∀ (p : ℕ) [Fact p.Prime], Prices.SharedPrice (AlgebraicClosure (ZMod p)) → + Rounds.Installable (ZMod p)) + (F : Type*) [Field F] : omega F = 9 / 4 ∧ Rectangle.Rigidity F := + contact_of_network_estimates (fun p _ => BatchDescent.hard (ZMod p)) + (fun p _ h => (rounds p h).reduction) F + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle.lean new file mode 100644 index 0000000000..541fe90ff5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle.lean @@ -0,0 +1,108 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Face.Contact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Dual + +/-! +# Rectangular matrix multiplication over arbitrary fields + +The upper bound and the entire region below the harmonic threshold +are unconditional. Propagation of positive contact is the remaining +spectral input for the rigidity dichotomy. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {a b c : ℝ} + +theorem upper (F : Type*) [Field F] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + exponent F a b c ≤ U a b c := by + by_cases h : a = 0 ∨ b = 0 ∨ c = 0 + · rw [coordinate_plane F ha hb hc h, U_plane ha hb hc h] + push Not at h + obtain ⟨K, _, ⟨alg⟩⟩ := small_field F + rw [exponent_extension K F ha hb hc] + exact upper_of_diagonal (support K) (diagonal K) + (ha.lt_of_ne' h.1) (hb.lt_of_ne' h.2.1) (hc.lt_of_ne' h.2.2) + +/-- The full benchmark upper bound includes arbitrary positive slack +in the cost of the formal arithmetic circuits. -/ +theorem arithmetic_upper (F : Type*) [Field F] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + Admissible F a b c (U a b c) := by + intro ε hε + have h := lt_add_of_le_of_pos (upper F ha hb hc) hε + obtain ⟨s, hs, hlt⟩ := exists_lt_of_csInf_lt ⟨_, volume_admissible F ha hb hc⟩ h + obtain ⟨C, hC, hprog⟩ := hs (U a b c + ε - s) (sub_pos.mpr hlt) + refine ⟨C, hC, ?_⟩ + simpa only [show s + (U a b c + ε - s) = U a b c + ε by ring] using hprog + +theorem flat (F : Type*) [Field F] (ha : 0 < a) (hb : 0 < b) (hc : 0 ≤ c) + (hc' : c ≤ a * b / (a + b)) : exponent F a b c = a + b := by + have h : (a + b) * c ≤ a * b := by + rw [mul_comm]; exact (le_div_iff₀ (add_pos ha hb)).mp hc' + have hmin : c ≤ min a b := by apply le_min <;> nlinarith + have hu := upper F ha.le hb.le hc + simp only [U, ite_eq_left hmin, benchmark, max_eq_right (sub_nonpos.mpr h), zero_pow + (by decide : 2 ≠ 0), zero_div, add_zero] at hu + exact le_antisymm hu ((le_max_left _ _).trans (bounds F ha.le hb.le hc).1) + +theorem dual_lower (F : Type*) [Field F] (ha : 0 < a) (hb : 0 < b) : + a * b / (a + b) ≤ dual F a b := by + have h : 0 ≤ a * b / (a + b) := by positivity + have h' : a * b / (a + b) ≤ min a b := by + apply le_min <;> rw [div_le_iff₀ (add_pos ha hb)] <;> nlinarith + exact le_csSup ⟨min a b, fun _ hc => hc.1.2⟩ ⟨⟨h, h'⟩, flat F ha hb h le_rfl⟩ + +theorem rigidity (h : ∀ (K : Type) [Field K], Propagation (Prices K)) + (F : Type*) [Field F] : Rigidity F := by + obtain ⟨K, _, ⟨alg⟩⟩ := small_field F + rcases rigidity_of_contact (support K) (diagonal K) (h K) with hK | hK + · left + intro a b c ha hb hc + rw [exponent_extension K F ha.le hb.le hc.le] + exact hK a b c ha hb hc + · right + intro a b c ha hb hc hactive + rw [exponent_extension K F ha.le hb.le hc.le] + exact hK a b c ha hb hc hactive + +/-- A strict saving at any fixed shape is witnessed in some prime field. -/ +theorem prime_specialization {F : Type*} [Field F] {s : ℝ} + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) (h : exponent F a b c < s) : + ∃ (p : ℕ) (_ : Fact p.Prime), exponent (ZMod p) a b c < s := by + obtain ⟨n, r, hn, hr, hs⟩ := (exponent_lt_iff_rank ha hb hc).mp h + obtain ⟨K, _, _, hK⟩ := specializeRank hr + let p := ringChar K + have : Fact p.Prime := ⟨CharP.char_is_prime K p⟩ + let _ : Algebra (ZMod p) K := ZMod.algebra K p + refine ⟨p, inferInstance, ?_⟩ + rw [← exponent_extension (ZMod p) K ha hb hc] + exact exponent_lt_of_rank ha hb hc hn hK hs + +theorem of_prime_fields + (h : ∀ (p : ℕ) [Fact p.Prime], MatrixExponent.omega (ZMod p) = 9 / 4 ∧ Rigidity (ZMod p)) + (F : Type*) [Field F] : MatrixExponent.omega F = 9 / 4 ∧ Rigidity F := by + have he (a b c : ℝ) (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : + exponent F a b c = U a b c := by + refine le_antisymm (upper F ha.le hb.le hc.le) ?_ + by_contra! hlt + obtain ⟨p, _, hp⟩ := prime_specialization ha.le hb.le hc.le hlt + exact hp.ne (positive_shapes (h p).2 (h p).1 ha hb hc) + have hs := he 1 1 1 zero_lt_one zero_lt_one zero_lt_one + norm_num [square, U, benchmark] at hs + exact ⟨hs, Or.inl he⟩ + +theorem of_finite_fields + (h : ∀ (K : Type) [Field K] [Finite K], MatrixExponent.omega K = 9 / 4 ∧ Rigidity K) + (F : Type*) [Field F] : MatrixExponent.omega F = 9 / 4 ∧ Rigidity F := + of_prime_fields (fun p _ => h (ZMod p)) F + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/Model.lean new file mode 100644 index 0000000000..03e110a4b5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/Model.lean @@ -0,0 +1,47 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights +public import Mathlib.Algebra.MvPolynomial.Eval +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure + +/-! # Geometric closure of the rank locus in the full coefficient space -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} [Field F] {i j k : ℕ} + +/-- The condition `∀ p : MvPolynomial ι F, (∀ y ∈ s, MvPolynomial.eval y p = 0) → +MvPolynomial.eval x p = 0` on the specified data. -/ +def ZClosure {ι : Type} (s : Set (ι → F)) (x : ι → F) : Prop := + ∀ p : MvPolynomial ι F, + (∀ y ∈ s, MvPolynomial.eval y p = 0) → MvPolynomial.eval x p = 0 + +/-- Indexes the coordinates by the coordinates of `Pos i k × Pos k j × Pos i j`. -/ +abbrev Coordinates (i j k : ℕ) := Pos i k × Pos k j × Pos i j + +/-- Evaluates `if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then w x.1 y.2 x.2 else 0` at the input `(x, +y, z)`. -/ +def coefficients (w : Fin i → Fin j → Fin k → F) : Coordinates i j k → F := + fun (x, y, z) => if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then w x.1 y.2 x.2 else 0 + +/-- The rank set of type `Set (Coordinates i j k → F)` for the given inputs. -/ +def rankSet (F : Type*) [Field F] (i j k r : ℕ) : Set (Coordinates i j k → F) := + {v | ∃ (a : Fin r → Pos i k → F) (b : Fin r → Pos k j → F) (c : Fin r → Pos i j → F), + ∀ x y z, ∑ l : Fin r, a l x * b l y * c l z = v (x, y, z)} + +/-- The defining condition `ZClosure (rankSet (AlgebraicClosure F) i j k r) (coefficients (fun x +y z => algebraMap F (AlgebraicClosure F) (w x y z)))`. -/ +def BorderRankLE (w : Fin i → Fin j → Fin k → F) (r : ℕ) : Prop := + ZClosure (rankSet (AlgebraicClosure F) i j k r) + (coefficients (fun x y z => algebraMap F (AlgebraicClosure F) (w x y z))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/Price.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/Price.lean new file mode 100644 index 0000000000..92711d67c8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/Price.lean @@ -0,0 +1,811 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.MvPolynomial.Eval +public import Mathlib.RingTheory.Valuation.LocalSubring +public import Mathlib.RingTheory.LocalRing.ResidueField.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Comparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Model +public import Mathlib.Algebra.MvPolynomial.Funext +public import Mathlib.Algebra.MvPolynomial.Monad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Mask +public import Mathlib.Algebra.Polynomial.Roots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Span +public import Mathlib.Algebra.BigOperators.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.WeightedModel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law + +/-! +# Specialization by a valuation + +If every polynomial identity of a tuple holds at another tuple, one +valuation subring contains the first tuple and specializes it to the +second. The coefficients are fixed under specialization. +-/ + +universe u + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open MvPolynomial IsLocalRing + +variable {K E : Type*} [Field K] [Field E] {ι : Type} + +theorem valuation_place (φ : K →+* E) (v : ι → E) (x : ι → K) + (h : ∀ p : MvPolynomial ι K, eval₂ φ v p = 0 → eval x p = 0) : + ∃ (V : ValuationSubring E) (f : K →+* V) (u : ι → V), + (∀ a, (f a : E) = φ a) ∧ (∀ i, (u i : E) = v i) ∧ + (∀ i, residue V (u i) = residue V (f (x i))) := by + let e := eval₂Hom φ v + let I := Ideal.map e.rangeRestrict (RingHom.ker (eval x)) + have hI : I ≠ ⊤ := by + intro he + have h₁ : (1 : e.range) ∈ I := by rw [he]; exact Submodule.mem_top + obtain ⟨p, hp, hp'⟩ := (Ideal.mem_map_iff_of_surjective _ e.rangeRestrict_surjective).mp h₁ + change eval x p = 0 at hp + have he' : e p = 1 := congrArg Subtype.val hp' + have hz := h (p - 1) (by change e (p - 1) = 0; rw [map_sub, map_one, he', sub_self]) + simp [hp] at hz + obtain ⟨V, hV, hnon⟩ := I.image_subset_nonunits_valuationSubring hI + let ev : MvPolynomial ι K →+* V := (Subring.inclusion hV).comp e.rangeRestrict + refine ⟨V, ev.comp C, fun i => ev (X i), ?_, ?_, ?_⟩ + · intro a + change eval₂ φ v (C a) = _ + simp + · intro i + change eval₂ φ v (X i) = _ + simp + · intro i + let p := X i - C (x i) + have hp : p ∈ RingHom.ker (eval x) := by simp [p] + have hz : (ev p : E) ∈ (V.nonunits : Set E) := hnon ⟨e.rangeRestrict p, + Ideal.mem_map_of_mem _ hp, rfl⟩ + rw [← V.image_maximalIdeal] at hz + obtain ⟨z, hz, he⟩ := hz + have hz' : residue V (ev p) = 0 := by + rw [← Subtype.ext he] + exact (residue_eq_zero_iff _).mpr hz + simpa only [p, map_sub, sub_eq_zero, RingHom.comp_apply] using hz' + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# A simultaneous spectral maximizer + +Testing the weighted tensor tensored with many ordinary copies +finds a point attaining the ordinary maximum while retaining +the weighted lower bound. Only two observables of the compact +spectrum are needed. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral Set +open scoped NNReal + +variable {F : Type} [Field F] {A B : Tensor F (Fin 3)} {a b : ℝ} + +private theorem large_power {u v : ℝ} (hu : 0 < u) (hv : u < v) (C : ℝ) : + ∃ n : ℕ, C * u ^ n < v ^ n := by + obtain ⟨n, hn⟩ := pow_unbounded_of_one_lt C ((one_lt_div hu).mpr hv) + rw [div_pow, lt_div_iff₀ (pow_pos hu _)] at hn + exact ⟨n, hn⟩ + +private theorem compact_max {P : Set (Tensor F (Fin 3) → ℝ≥0)} + (hc : IsCompact P) (hn : P.Nonempty) (hs : P ⊆ Spectrum.points (Tensor F (Fin 3))) + (A : Tensor F (Fin 3)) : + ∃ f : Point F, Monotone f ∧ ⇑f ∈ P ∧ ∀ g : Point F, ⇑g ∈ P → (g A : ℝ) ≤ f A := by + obtain ⟨u, hu, hh⟩ := hc.exists_isMaxOn hn (continuous_apply A).continuousOn + obtain ⟨f, hf, rfl⟩ := hs hu + exact ⟨f, hf, hu, fun g hg => NNReal.coe_le_coe.mpr (hh hg)⟩ + +/-- Exact lower bounds at all powers are detected by a single spectral point. -/ +theorem detector (ha : 0 < a) (hl : ∀ n r : ℕ, A ^ n ≤ (r : Tensor F (Fin 3)) → a ^ n ≤ r) : + ∃ f : Point F, Monotone f ∧ a ≤ (f A : ℝ) := by + obtain ⟨g, hg, _⟩ := maximum_score F 0 0 0 + obtain ⟨f, hf, _, hmax⟩ := compact_max (Spectrum.compact_points Tensor.exists_bound) + ⟨g, g, hg, rfl⟩ Set.Subset.rfl A + have hA : A ≠ 0 := by + intro he + have := hl 1 0 (by simp [he]) + simp at this + linarith + have hf₁ : 1 ≤ (f A : ℝ) := by + have he := hf (Tensor.one_le A hA) + rw [map_one] at he + exact_mod_cast he + refine ⟨f, hf, ?_⟩ + by_contra! hlt + obtain ⟨n, hn⟩ := large_power (zero_lt_one.trans_le hf₁) hlt 3 + let r := ⌈2 * (f A : ℝ) ^ n⌉₊ + have hrr := one_le_pow₀ (n := n) hf₁ + have hlo : (f A : ℝ) ^ n < r := lt_of_lt_of_le (by linarith) (Nat.le_ceil _) + have hhi : (r : ℝ) < a ^ n := lt_trans (Nat.ceil_lt_add_one (by positivity)) (by linarith) + have hr : 0 < (r : ℝ) := (by positivity : 0 ≤ (f A : ℝ) ^ n).trans_lt hlo + have hne : (r : Tensor F (Fin 3)) ≠ 0 := by + intro he + have hh : r ≤ 0 := (Tensor.natCast_le_iff (K := F) (S := Fin 3) r 0).mp (by simp [he]) + exact hr.not_ge (by exact_mod_cast hh) + have hp (g : Point F) (hg : Monotone g) : g (A ^ n) < g (r : Tensor F (Fin 3)) := by + rw [map_pow, map_natCast] + exact_mod_cast (pow_le_pow_left₀ (NNReal.coe_nonneg _) (hmax g ⟨g, hg, rfl⟩) n).trans_lt hlo + obtain ⟨C, hC⟩ := Spectrum.strictComparison Tensor.add_le_add_right Tensor.mul_le_mul_left + Tensor.zero_le Tensor.one_le Tensor.exists_bound hne hp + obtain ⟨m, hm⟩ := large_power hr hhi C + have he := hl (n * m) (C * r ^ m) (by rw [pow_mul, Nat.cast_mul, Nat.cast_pow]; exact hC m) + rw [pow_mul, Nat.cast_mul, Nat.cast_pow] at he + exact hm.not_ge he + +theorem simultaneous (ha : 0 < a) (hb : 0 < b) + (hmax : ∀ f : Point F, Monotone f → (f B : ℝ) ≤ b) + (hl : ∀ m n r : ℕ, (A * B ^ m) ^ n ≤ (r : Tensor F (Fin 3)) → (a * b ^ m) ^ n ≤ r) : + ∃ f : Point F, Monotone f ∧ a ≤ (f A : ℝ) ∧ (f B : ℝ) = b := by + have hpoint (m : ℕ) : ∃ f : Point F, Monotone f ∧ a ≤ (f A : ℝ) ∧ + a * b ^ m ≤ (f A : ℝ) * (f B : ℝ) ^ m := by + obtain ⟨f, hf, he⟩ := detector (by positivity) (hl m) + simp only [f.map_mul, map_pow, NNReal.coe_mul, NNReal.coe_pow] at he + refine ⟨f, hf, ?_, he⟩ + apply le_of_mul_le_mul_right _ (pow_pos hb m) + exact he.trans (mul_le_mul_of_nonneg_left + (pow_le_pow_left₀ (by positivity) (hmax f hf) _) (by positivity)) + let P := Spectrum.points (Tensor F (Fin 3)) ∩ {g | a ≤ (g A : ℝ)} + have hc : IsCompact P := (Spectrum.compact_points Tensor.exists_bound).inter_right + (isClosed_le continuous_const (by fun_prop)) + obtain ⟨g, hg, hg', he⟩ := hpoint 1 + obtain ⟨f, hf, hf', hm⟩ := compact_max hc ⟨g, ⟨g, hg, rfl⟩, hg'⟩ inter_subset_left B + refine ⟨f, hf, hf'.2, le_antisymm (hmax _ hf) ?_⟩ + by_contra! hlt + have hpos : 0 < (f B : ℝ) := by + have hh : 0 < (g A : ℝ) * (g B : ℝ) := by + rw [pow_one, pow_one] at he + exact (mul_pos ha hb).trans_le he + exact (pos_of_mul_pos_right hh (by positivity)).trans_le (hm g ⟨⟨g, hg, rfl⟩, hg'⟩) + obtain ⟨R, hR⟩ := Tensor.exists_bound A + obtain ⟨m, hh⟩ := large_power hpos hlt (R / a) + obtain ⟨g, hg, hg', he⟩ := hpoint m + have hg₁ : (g A : ℝ) ≤ R := by exact_mod_cast (show g A ≤ R by simpa using hg hR) + have hg₂ := hm g ⟨⟨g, hg, rfl⟩, hg'⟩ + rw [div_mul_eq_mul_div, div_lt_iff₀ ha, mul_comm (b ^ m)] at hh + exact hh.not_ge (he.trans (mul_le_mul hg₁ (pow_le_pow_left₀ (by positivity) hg₂ _) (by positivity) + (by positivity))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# Generic rank decompositions + +Over an infinite field the identities of rank-bounded tensors are +exactly the polynomial identities of the generic decomposition. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Border +open MvPolynomial IsLocalRing + +variable {K : Type u} {E : Type*} [Field K] [Field E] {i j k r : ℕ} + +private abbrev Param (i j k r : ℕ) := Fin r × (Pos i k ⊕ Pos k j ⊕ Pos i j) + +private def generic (K : Type*) [Field K] (i j k r : ℕ) : + Coordinates i j k → MvPolynomial (Param i j k r) K := fun t => + ∑ l, X (l, .inl t.1) * X (l, .inr (.inl t.2.1)) * X (l, .inr (.inr t.2.2)) + +private theorem generic_mem (g : MvPolynomial (Param i j k r) K →+* E) : + (fun t => g (generic K i j k r t)) ∈ rankSet E i j k r := by + refine ⟨fun l x => g (X (l, .inl x)), fun l y => g (X (l, .inr (.inl y))), + fun l z => g (X (l, .inr (.inr z))), fun x y z => ?_⟩ + simp only [generic, map_sum, map_mul] + +private theorem generic_identity {p : MvPolynomial (Coordinates i j k) K} + (hp : eval₂ C (generic K i j k r) p = 0) + (φ : K →+* E) {v : Coordinates i j k → E} (hv : v ∈ rankSet E i j k r) : + eval₂ φ v p = 0 := by + obtain ⟨a, b, c, h⟩ := hv + let g := eval₂Hom φ (fun t : Param i j k r => Sum.elim (a t.1) (Sum.elim (b t.1) (c t.1)) t.2) + have hg : (fun t => g (generic K i j k r t)) = v := by + funext t + simpa [generic, g] using h t.1 t.2.1 t.2.2 + have he := congrArg g hp + rwa [hom_eval₂, hg, show g.comp C = φ from eval₂Hom_comp_C _ _, map_zero] at he + +/-- Base-field equations of a rank locus apply also to extension-field witnesses. -/ +theorem identity_of_rank [Infinite K] {p : MvPolynomial (Coordinates i j k) K} + (hp : ∀ v ∈ rankSet K i j k r, eval v p = 0) + (φ : K →+* E) {v : Coordinates i j k → E} (hv : v ∈ rankSet E i j k r) : + eval₂ φ v p = 0 := by + apply generic_identity _ φ hv + apply MvPolynomial.funext + intro x + rw [map_zero, hom_eval₂, show (eval x).comp C = RingHom.id K from eval₂Hom_comp_C _ _] + exact hp _ (generic_mem (eval x)) + +/-- Only the tensor entries have to be integral at the place. +The summands of the generic decomposition may have poles. -/ +theorem integral_model {x : Coordinates i j k → K} (hx : ZClosure (rankSet K i j k r) x) : + ∃ (L : Type u) (_ : Field L) (V : ValuationSubring L) (f : K →+* V) + (v : Coordinates i j k → V), + (fun t => (v t : L)) ∈ rankSet L i j k r ∧ ∀ t, residue V (v t) = residue V (f (x t)) := by + let S := MvPolynomial (Param i j k r) K + let L := FractionRing S + let g := algebraMap S L + let y t := g (generic K i j k r t) + have he (p) (hp : eval₂ (g.comp C) y p = 0) : eval x p = 0 := by + apply hx + have hg : eval₂ C (generic K i j k r) p = 0 := by + apply IsFractionRing.injective S L + rw [map_zero, hom_eval₂] + exact hp + exact fun _ hv => generic_identity hg (RingHom.id K) hv + obtain ⟨V, f, v, _, hv, hv'⟩ := valuation_place (g.comp C) y x he + exact ⟨L, inferInstance, V, f, v, by simpa only [hv] using generic_mem g, hv'⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Border +end + +/- +# One pivot for a border-rank decomposition + +Choose a live output of maximal valuation in the first summand. Its +multiples cancel that summand on every live output, with the multipliers +integral at the chosen place. All other outputs are projected to zero. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Border +open IsLocalRing MvPolynomial + +variable {i j k r : ℕ} + +/-- Evaluates `if z ∈ u then a x.1 * b y.2 * c z * (v (x, y, z) - d z * v (x, y, o)) else 0` at +the input `(x, y, z)`. -/ +def shear {R : Type*} [CommRing R] (u : Finset (Pos i j)) (o : Pos i j) + (d : Pos i j → R) (v : Coordinates i j k → R) + (a : Fin i → R) (b : Fin j → R) (c : Pos i j → R) : Coordinates i j k → R := + fun (x, y, z) => if z ∈ u then a x.1 * b y.2 * c z * (v (x, y, z) - d z * v (x, y, o)) else 0 + +private theorem map_shear {R S : Type*} [CommRing R] [CommRing S] (φ : R →+* S) + (u : Finset (Pos i j)) (o : Pos i j) (d : Pos i j → R) (v : Coordinates i j k → R) + (a : Fin i → R) (b : Fin j → R) (c : Pos i j → R) : + φ ∘ shear u o d v a b c = shear u o (φ ∘ d) (φ ∘ v) (φ ∘ a) (φ ∘ b) (φ ∘ c) := by + funext t + simp only [shear, Function.comp_apply, apply_ite φ, map_mul, map_sub, map_zero] + +variable {K : Type u} [Field K] {L : Type*} [Field L] {u : Finset (Pos i j)} + +private theorem pivot (V : ValuationSubring L) (hu : u.Nonempty) + {v : Coordinates i j k → L} (hv : v ∈ rankSet L i j k (r + 1)) : + ∃ o ∈ u, ∃ d : Pos i j → V, d o = 1 ∧ ∀ a b c, + shear u o (fun z => (d z : L)) v a b c ∈ rankSet L i j k r := by + classical + obtain ⟨A, B, C, h⟩ := hv + obtain ⟨o, ho, hmax⟩ := u.exists_max_image (fun z => V.valuation (C 0 z)) hu + have hd (z : Pos i j) : ∃ e : V, (z = o → e = 1) ∧ (z ∈ u → (e : L) * C 0 o = C 0 z) := by + by_cases he : z = o + · exact ⟨1, fun _ => rfl, fun _ => by simp [he]⟩ + by_cases hz : z ∈ u + · obtain ⟨e, h'⟩ := (V.valuation_le_iff _ _).mp (hmax z hz) + exact ⟨e, fun h => (he h).elim, fun _ => h'⟩ + · exact ⟨0, fun h => (he h).elim, fun h => (hz h).elim⟩ + choose d h₁ h₂ using hd + refine ⟨o, ho, d, h₁ o rfl, fun a b c => ?_⟩ + let C' l z := if z ∈ u then c z * (C l z - (d z : L) * C l o) else 0 + refine ⟨fun l x => a x.1 * A l.succ x, fun l y => b y.2 * B l.succ y, + fun l z => C' l.succ z, fun x y z => ?_⟩ + by_cases hz : z ∈ u + swap; · simp [C', shear, hz] + let f l := a x.1 * A l x * (b y.2 * B l y) * C' l z + have hf : f 0 = 0 := by simp [f, C', hz, h₂ z hz] + change ∑ l : Fin r, f l.succ = _ + rw [← zero_add (∑ l : Fin r, f l.succ), ← hf, ← Fin.sum_univ_succ] + simp only [shear, hz, ↓reduceIte, ← h, Finset.mul_sum, ← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro l _ + simp only [f, C', hz, ↓reduceIte] + ring + +/-- A residue-field pivot works simultaneously for every diagonal rescaling +over the ground field and every polynomial identity of rank at most `r`. -/ +theorem shear_identity [Infinite K] {v : Coordinates i j k → K} + (hv : ZClosure (rankSet K i j k (r + 1)) v) (hu : u.Nonempty) : + ∃ o ∈ u, ∃ (E : Type u) (_ : Field E) (φ : K →+* E) (d : Pos i j → E), d o = 1 ∧ + ∀ (a : Fin i → K) (b : Fin j → K) (c : Pos i j → K) (p : MvPolynomial (Coordinates i j k) K), + (∀ x ∈ rankSet K i j k r, eval x p = 0) → + eval₂ φ (shear u o d (φ ∘ v) (φ ∘ a) (φ ∘ b) (φ ∘ c)) p = 0 := by + obtain ⟨L, _, V, g, w, hw, he⟩ := integral_model hv + obtain ⟨o, ho, d, hd, h⟩ := pivot V hu hw + let π := residue V + let e : V →+* L := V.toSubring.subtype + refine ⟨o, ho, ResidueField V, inferInstance, π.comp g, π ∘ d, by simp [hd], ?_⟩ + intro a b c p hp + let y := shear u o d w (g ∘ a) (g ∘ b) (g ∘ c) + have hy : eval₂ g y p = 0 := by + apply Subtype.ext + change e (eval₂ g y p) = e 0 + rw [map_zero, eval₂_comp_left] + apply identity_of_rank hp + unfold y + rw [map_shear] + exact h _ _ _ + have hπ := congrArg π hy + rw [map_zero, eval₂_comp_left] at hπ + unfold y at hπ + rw [map_shear, show π ∘ w = (π.comp g) ∘ v from funext he] at hπ + exact hπ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Border +end + +/- +# Isolating an output cell + +Independent scalings of rows and columns preserve the weighted product. +Scale every row and column other than the pivot's by a parameter. On the +sheared tensor this gives a polynomial path whose value at zero simply +erases the pivot. Polynomial identities persist at zero. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Border +open MvPolynomial + +variable {i j k r : ℕ} {K E : Type*} [Field K] [Field E] + +private def scale {R : Type*} [One R] {n : ℕ} (o : Fin n) (t : R) (x : Fin n) : R := + if x = o then 1 else t + +private def factor {R : Type*} [Monoid R] (o : Pos i j) (t : R) (x : Pos i j) : R := + scale o.1 t x.1 * scale o.2 t x.2 + +private def path {R : Type*} [CommRing R] (u : Finset (Pos i j)) (o : Pos i j) + (d : Pos i j → R) (v : Coordinates i j k → R) (t : R) : Coordinates i j k → R := + fun (x, y, z) => if z ∈ u then v (x, y, z) - factor o t z * d z * v (x, y, o) else 0 + +private theorem shear_path (φ : K →+* E) (w : Fin i → Fin j → Fin k → K) + (u : Finset (Pos i j)) (o : Pos i j) (d : Pos i j → E) {t : K} (ht : t ≠ 0) : + shear u o d (φ ∘ coefficients w) (φ ∘ scale o.1 t⁻¹) (φ ∘ scale o.2 t⁻¹) + (φ ∘ factor o t) = path u o d (φ ∘ coefficients w) (φ t) := by + funext ⟨x, y, z⟩ + have hmap (p : Pos i j) : factor o (φ t) p = φ (factor o t p) := by + simp only [factor, scale, map_mul, apply_ite φ, map_one] + have he (p : Pos i j) : + scale o.1 t⁻¹ x.1 * scale o.2 t⁻¹ y.2 * factor o t p * coefficients w (x, y, p) = + coefficients w (x, y, p) := by + by_cases h : x.1 = p.1 ∧ x.2 = y.1 ∧ y.2 = p.2 + · rw [h.1, h.2.2, factor, mul_mul_mul_comm] + have hcancel {n : ℕ} (a b : Fin n) : scale a t⁻¹ b * scale a t b = 1 := by + unfold scale + split <;> simp [ht] + rw [hcancel, hcancel, one_mul, one_mul] + · simp [coefficients, h] + have hz := congrArg φ (he z) + have ho := congrArg φ (he o) + simp only [show factor o t o = 1 by simp [factor, scale], mul_one, map_mul] at ho + simp only [map_mul] at hz + by_cases h : z ∈ u + · simp only [shear, path, h, ↓reduceIte, Function.comp_apply, hmap] + linear_combination hz - φ (factor o t z) * d z * ho + · simp [shear, path, h] + +private theorem path_zero (φ : K →+* E) (w : Fin i → Fin j → Fin k → K) + (u : Finset (Pos i j)) (o : Pos i j) (d : Pos i j → E) (hd : d o = 1) : + path u o d (φ ∘ coefficients w) 0 = φ ∘ coefficients (mask w (u.erase o)) := by + funext ⟨x, y, z⟩ + have hscale : factor o (0 : E) z = if z = o then 1 else 0 := by + simp only [factor, scale, Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul] + have hmask : coefficients (mask w (u.erase o)) (x, y, z) = + if z ∈ u.erase o then coefficients w (x, y, z) else 0 := by + by_cases h : x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 + · simp [coefficients, mask, h.1, h.2.1, h.2.2] + · simp [coefficients, h] + simp only [path, Function.comp_apply, hscale, hmask, Finset.mem_erase] + by_cases he : z = o + · simp [he, hd] + · simp [he, apply_ite φ] + +private theorem path_identity [Infinite K] (φ : K →+* E) (v : Coordinates i j k → E) + (u : Finset (Pos i j)) (o : Pos i j) (d : Pos i j → E) (p : MvPolynomial (Coordinates i j k) K) + (h : ∀ t : K, t ≠ 0 → eval₂ φ (path u o d v (φ t)) p = 0) : + eval₂ φ (path u o d v 0) p = 0 := by + let Q := eval₂ (Polynomial.C.comp φ) (path u o (Polynomial.C ∘ d) (Polynomial.C ∘ v) + Polynomial.X) p + have he (t : E) : Q.eval t = eval₂ φ (path u o d v t) p := by + let ev := Polynomial.evalRingHom t + change ev Q = _ + unfold Q + rw [eval₂_comp_left] + have hc : ev.comp (Polynomial.C.comp φ) = φ := by ext a; simp [ev] + rw [hc] + congr 1 + funext a + simp only [Function.comp_apply, path, factor, scale, apply_ite ev, map_mul, map_one, map_sub, + map_zero] + simp [ev] + have hz : Q = 0 := by + apply Polynomial.eq_zero_of_infinite_isRoot + apply ((Set.infinite_range_of_injective φ.injective).sdiff (Set.finite_singleton 0)).mono + rintro _ ⟨⟨t, rfl⟩, ht⟩ + change Q.eval (φ t) = 0 + rw [he] + exact h t (fun he => ht (by simp [he])) + rw [← he, hz, Polynomial.eval_zero] + +/-- Erase one cell of a nonempty set, dropping the border rank budget by one. -/ +theorem erase [Infinite K] (w : Fin i → Fin j → Fin k → K) (u : Finset (Pos i j)) + (hu : u.Nonempty) (h : ZClosure (rankSet K i j k (r + 1)) (coefficients w)) : + ∃ o ∈ u, ZClosure (rankSet K i j k r) (coefficients (mask w (u.erase o))) := by + obtain ⟨o, ho, E, _, φ, d, hd, he⟩ := shear_identity h hu + refine ⟨o, ho, fun p hp => ?_⟩ + apply φ.injective + rw [map_zero, eval₂_comp, ← path_zero φ w u o d hd] + apply path_identity + intro t ht + rw [← shear_path φ w u o d ht] + exact he _ _ _ p hp + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Border +end + +section +/- # Coordinate deletion in geometric border rank -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open MvPolynomial + +variable {F : Type*} [Field F] {i j k r : ℕ} {w : Fin i → Fin j → Fin k → F} + +private theorem BorderRankLE.zero (h : BorderRankLE w 0) (a : Fin i) (b : Fin j) (c : Fin k) : + w a b c = 0 := by + let t : Coordinates i j k := ((a, c), (c, b), (a, b)) + have he := h (X t) (by + rintro v ⟨A, B, C, hv⟩ + rw [eval_X] + simpa [t] using (hv (a, c) (c, b) (a, b)).symm) + simpa [t, coefficients] using he + +private theorem BorderRankLE.erase {u : Finset (Pos i j)} (hu : u.Nonempty) + (h : BorderRankLE (mask w u) (r + 1)) : + ∃ o ∈ u, BorderRankLE (mask w (u.erase o)) r := by + let φ := algebraMap F (AlgebraicClosure F) + obtain ⟨o, ho, hr⟩ := Border.erase (fun x y z => φ (mask w u x y z)) u hu h + refine ⟨o, ho, ?_⟩ + have he : (fun x y z => φ (mask w (u.erase o) x y z)) = + mask (fun x y z => φ (mask w u x y z)) (u.erase o) := by + funext x y z + by_cases h' : (x, y) ∈ u.erase o + · simp only [mask, h', Finset.mem_of_mem_erase h', ↓reduceIte] + · simp only [mask, h', ↓reduceIte, map_zero] + rwa [← he] at hr + +private theorem delete_mask (hw : ∀ x y z, w x y z ≠ 0) (hk : 0 < k) + (u : Finset (Pos i j)) (hr : BorderRankLE (mask w u) r) : + u.card ≤ r ∧ ∀ q ≤ u.card, ∃ v : Finset (Pos i j), + v.card = q ∧ BorderRankLE (mask w v) (r - (u.card - q)) := by + induction r generalizing u with + | zero => + have he : u.card = 0 := by + by_contra hne + obtain ⟨⟨a, b⟩, hab⟩ := Finset.card_pos.mp (Nat.pos_of_ne_zero hne) + have h' := hr.zero a b ⟨0, hk⟩ + simp [mask, hab, hw] at h' + exact ⟨he.le, fun q hq => ⟨u, by omega, by simpa using hr⟩⟩ + | succ r ih => + by_cases he : u.Nonempty + · obtain ⟨o, ho, he'⟩ := BorderRankLE.erase he hr + obtain ⟨hle, hd⟩ := ih (u.erase o) he' + have hcard := Finset.card_erase_add_one ho + refine ⟨by omega, fun q hq => ?_⟩ + rcases eq_or_lt_of_le hq with rfl | hlt + · exact ⟨u, rfl, by simpa using hr⟩ + · rw [show r + 1 - (u.card - q) = r - ((u.erase o).card - q) by omega] + exact hd q (by omega) + · have he' := Finset.not_nonempty_iff_eq_empty.mp he + subst u + simp only [Finset.card_empty, zero_le, true_and, Nat.le_zero, Nat.zero_sub, Nat.sub_zero] + exact fun q hq => ⟨∅, by simp [hq], hr⟩ + +/-- Retaining some set of exactly `q` output cells lowers the geometric +border-rank budget by the number deleted. No hypothesis on the field or +on the rank of the retained set is required. -/ +theorem BorderRankLE.delete (h : BorderRankLE w r) (hw : ∀ x y z, w x y z ≠ 0) + (hk : 0 < k) {q : ℕ} (hq : q ≤ i * j) : + i * j ≤ r ∧ ∃ u : Finset (Pos i j), u.card = q ∧ BorderRankLE (mask w u) (r - (i * j - q)) := by + have he : mask w Finset.univ = w := by funext a b c; simp [mask] + have h' := delete_mask hw hk Finset.univ (he.symm ▸ h) + simp only [Finset.card_univ, Pos, Fintype.card_prod, Fintype.card_fin] at h' + exact ⟨h'.1, h'.2 q hq⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# Spectral sublevels are Zariski closed + +The rank interpolation argument works for any spectral point because +a linear combination costs at most the sum of its constituent prices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral +open scoped NNReal + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + {X : S → Type} [∀ s, Fintype (X s)] {A : Set ((∀ s, X s) → K)} {T : (∀ s, X s) → K} + +/-- The product of `T (fun s => x s l)` indexed by `l`. -/ +def copyTable (T : (∀ s, X s) → K) (n : ℕ) (x : ∀ s, Fin n → X s) : K := + ∏ l, T (fun s => x s l) + +omit [DecidableEq S] in +theorem table_pow (T : (∀ s, X s) → K) (n : ℕ) : + Tensor.ofRaw (Raw.ofTable (fun s => Fin n → X s) (copyTable T n)) = + (Tensor.ofRaw (Raw.ofTable X T)) ^ n := by + classical + induction n with + | zero => + rw [pow_zero] + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (fun s => Equiv.ofUnique (Fin 0 → X s) Unit) fun x => ?_ + change (∀ s, Fin 0 → X s) at x + change _ = (1 : Raw K S).coeff (fun _ => ()) + rw [Raw.coeff_ofTable] + change copyTable T 0 x = ∑ _ : Unit, ∏ _ : S, (1 : K) + simp [copyTable] + | succ n ih => + rw [pow_succ', ← ih, ← Tensor.ofRaw_mul] + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (fun s => (Fin.consEquiv (fun _ => X s)).symm) fun x => ?_ + change (∀ s, Fin (n + 1) → X s) at x + change _ = (Raw.ofTable X T * Raw.ofTable (fun s => Fin n → X s) + (copyTable T n)).coeff (fun s => (x s 0, fun l => x s l.succ)) + rw [Raw.coeff_ofTable, Raw.coeff_mul] + change _ = (Raw.ofTable X T).coeff (fun s => x s 0) * + (Raw.ofTable (fun s => Fin n → X s) (copyTable T n)).coeff (fun s l => x s l.succ) + rw [Raw.coeff_ofTable X T (fun s => x s 0), + Raw.coeff_ofTable _ (copyTable T n) (fun s l => x s l.succ)] + unfold copyTable + rw [Fin.prod_univ_succ] + +omit [DecidableEq S] in +theorem ZClosure.price (h : ZClosure A T) (f : Tensor K S →+* ℝ≥0) (hf : Monotone f) + {B : ℝ} (hB : 0 ≤ B) (hprice : ∀ t ∈ A, (f (Tensor.ofRaw (Raw.ofTable X t)) : ℝ) ≤ B) : + (f (Tensor.ofRaw (Raw.ofTable X T)) : ℝ) ≤ B := by + classical + apply TensorSpectrum.le_of_pow_le_polynomial_mul_pow _ _ 1 (Fintype.card (∀ s, X s)) + hB (by norm_num) + intro n _ + obtain ⟨d, hd, y, c, hy, he⟩ := h.power n + have hs := hf (Tensor.span_le (fun s => Fin n → X s) (copyTable T n) + (fun i => copyTable (y i) n) c (fun t => he (fun l s => t s l))) + simp only [table_pow, map_pow, map_sum] at hs + rw [one_mul, Real.rpow_natCast] + calc + _ ≤ ∑ t : Fin d, (f (Tensor.ofRaw (Raw.ofTable X (y t))) : ℝ) ^ n := by exact_mod_cast hs + _ ≤ ∑ _ : Fin d, B ^ n := Finset.sum_le_sum fun t _ => + pow_le_pow_left₀ (by positivity) (hprice _ (hy t)) _ + _ = d * B ^ n := by simp + _ ≤ _ := mul_le_mul_of_nonneg_right (by exact_mod_cast hd) (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- # Weighted products as three-site spectral tensors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral + +variable {F : Type} [Field F] {i j k r : ℕ} + +theorem legs_card (i j k : ℕ) (s : Fin 3) : + Fintype.card (legs i j k s) ≤ max (i * j) (max (i * k) (j * k)) := by + fin_cases s + · change Fintype.card (Pos i j) ≤ _ + simp only [Pos, Fintype.card_prod, Fintype.card_fin] + exact le_max_left _ _ + · change Fintype.card (Pos i k) ≤ _ + simp only [Pos, Fintype.card_prod, Fintype.card_fin] + exact (le_max_left _ _).trans (le_max_right _ _) + · change Fintype.card (Pos k j) ≤ _ + simp only [Pos, Fintype.card_prod, Fintype.card_fin, mul_comm k j] + exact (le_max_right _ _).trans (le_max_right _ _) + +theorem wtensor_le_iff (T : Coordinates i j k → F) : + wtensor T ≤ (r : Tensor F (Fin 3)) ↔ T ∈ rankSet F i j k r := by + constructor + · intro h + obtain ⟨A, he⟩ := Speedup.exists_form h + refine ⟨fun l => A l 1, fun l => A l 2, fun l => A l 0, fun x y z => ?_⟩ + have hh := congrFun he (tripleLeg (α := legs i j k) z x y) + simp only [Speedup.form, Fin.prod_univ_three] at hh + change T (x, y, z) = ∑ l, A l 0 z * A l 1 x * A l 2 y at hh + simpa only [mul_comm, mul_left_comm, mul_assoc] using hh.symm + · rintro ⟨a, b, c, h⟩ + let A : Speedup.Family F (legs i j k) r := fun l => tripleLeg (c l) (a l) (b l) + have he : T ∘ ungroup = Speedup.form A := by + funext x + simp only [Speedup.form, Fin.prod_univ_three] + change T (x 1, x 2, x 0) = ∑ l, c l (x 0) * a l (x 1) * b l (x 2) + simpa only [mul_comm, mul_left_comm, mul_assoc] using (h (x 1) (x 2) (x 0)).symm + rw [wtensor, he] + exact Speedup.form_le A + +theorem ordinary_le_tensor (F : Type) [Field F] (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + weightedTensor (fun (_ : Fin i) (_ : Fin j) (_ : Fin k) => (1 : F)) ≤ tensor F i j k := by + let proj : (s : Fin 3) → legs i j k s → (Fin i × Fin j) × Fin k := + tripleLeg (fun z => (z, ⟨0, hk⟩)) (fun x => ((x.1, ⟨0, hj⟩), x.2)) + (fun y => ((⟨0, hi⟩, y.2), y.1)) + refine Raw.Restricts.pullback proj fun x => ?_ + change (∀ s, legs i j k s) at x + rw [Raw.coeff_ofTable, coeff_wires (fun s => proj s (x s))] + rfl + +variable {i' j' k' I J K : ℕ} + +private def split {n m N p q P : ℕ} (f : Fin N ≃ Pos n m) (g : Fin P ≃ Pos p q) (v : Pos N P) := + (((f v.1).1, (g v.2).1), ((f v.1).2, (g v.2).2)) + +private theorem product_le {w : Fin i → Fin j → Fin k → F} {v : Fin i' → Fin j' → Fin k' → F} + {u : Fin I → Fin J → Fin K → F} (x : Fin I ≃ Pos i i') (y : Fin J ≃ Pos j j') + (z : Fin K ≃ Pos k k') + (h : ∀ (X : Pos I K) (Y : Pos K J) (Z : Pos I J), + coefficients u (X, Y, Z) = + coefficients w ((split x z X).1, (split z y Y).1, (split x y Z).1) * + coefficients v ((split x z X).2, (split z y Y).2, (split x y Z).2)) : + weightedTensor u ≤ weightedTensor w * weightedTensor v := by + let proj : (s : Fin 3) → legs I J K s → legs i j k s × legs i' j' k' s := + tripleLeg (split x y) (split x z) (split z y) + refine Raw.Restricts.pullback proj fun t => ?_ + change (∀ s, legs I J K s) at t + rw [Raw.coeff_ofTable] + let A := Raw.ofTable (legs i j k) (coefficients w ∘ ungroup) + let B := Raw.ofTable (legs i' j' k') (coefficients v ∘ ungroup) + change _ = (A * B).coeff (fun s => proj s (t s)) + rw [Raw.coeff_mul A B (fun s => proj s (t s))] + unfold A B + rw [Raw.coeff_ofTable _ _ (fun s => (proj s (t s)).1), + Raw.coeff_ofTable _ _ (fun s => (proj s (t s)).2)] + exact h (t 1) (t 2) (t 0) + +private theorem product_full {w : Fin i → Fin j → Fin k → F} {v : Fin i' → Fin j' → Fin k' → F} + (hw : ∀ a b c, w a b c ≠ 0) (hv : ∀ a b c, v a b c ≠ 0) + (x : Fin I ≃ Pos i i') (y : Fin J ≃ Pos j j') (z : Fin K ≃ Pos k k') : + ∃ u : Fin I → Fin J → Fin K → F, (∀ a b c, u a b c ≠ 0) ∧ + weightedTensor u ≤ weightedTensor w * weightedTensor v := by + let u a b c := w (x a).1 (y b).1 (z c).1 * v (x a).2 (y b).2 (z c).2 + refine ⟨u, fun _ _ _ => mul_ne_zero (hw _ _ _) (hv _ _ _), ?_⟩ + apply product_le x y z + have he {n m N : ℕ} (f : Fin N ≃ Pos n m) (a b : Fin N) : + a = b ↔ (f a).1 = (f b).1 ∧ (f a).2 = (f b).2 := + f.injective.eq_iff.symm.trans Prod.ext_iff + intro X Y Z + simp only [coefficients, split, u, ite_mul, mul_ite, zero_mul, mul_zero, ← ite_and, + he x X.1 Z.1, he z X.2 Y.1, he y Y.2 Z.2, and_comm, and_left_comm, and_assoc] + +/-- Tensor products retain a full-support weighting after pairing the +indices on each side. -/ +theorem tensor_full {w : Fin i → Fin j → Fin k → F} {v : Fin i' → Fin j' → Fin k' → F} + (hw : ∀ a b c, w a b c ≠ 0) (hv : ∀ a b c, v a b c ≠ 0) + (hi : I = i * i') (hj : J = j * j') (hk : K = k * k') : + ∃ u : Fin I → Fin J → Fin K → F, (∀ a b c, u a b c ≠ 0) ∧ + weightedTensor u ≤ weightedTensor w * weightedTensor v := by + let x := (finCongr hi).trans finProdFinEquiv.symm + let y := (finCongr hj).trans finProdFinEquiv.symm + let z := (finCongr hk).trans finProdFinEquiv.symm + exact product_full hw hv x y z + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# Powers and field transfer for geometric border rank + +Powering is a polynomial map of coefficient spaces, so exact +decompositions suffice to verify its action on the closure. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} [Field F] {i j k r : ℕ} {w : Fin i → Fin j → Fin k → F} + +namespace Border + +/-- The value specified by `(finFunctionFinEquiv.symm x.1 l, finFunctionFinEquiv.symm x.2 l)`. -/ +def digit {i j n : ℕ} (x : Pos (i ^ n) (j ^ n)) (l : Fin n) : Pos i j := + (finFunctionFinEquiv.symm x.1 l, finFunctionFinEquiv.symm x.2 l) + +theorem coefficients_pow (w : Fin i → Fin j → Fin k → F) (n : ℕ) + (x : Pos (i ^ n) (k ^ n)) (y : Pos (k ^ n) (j ^ n)) (z : Pos (i ^ n) (j ^ n)) : + (∏ l, coefficients w (digit x l, digit y l, digit z l)) = + coefficients (WPower w n) (x, y, z) := by + classical + unfold coefficients digit WPower + simp only [Fintype.prod_ite_zero, forall_and, ← funext_iff, Equiv.symm_apply_eq, + Equiv.apply_symm_apply] + +/-- Evaluates `∏ l, v (digit x l, digit y l, digit z l)` at the input `(x, y, z)`. -/ +def powerTable {R : Type*} [CommMonoid R] (v : Coordinates i j k → R) (n : ℕ) : + Coordinates (i ^ n) (j ^ n) (k ^ n) → R := + fun (x, y, z) => ∏ l, v (digit x l, digit y l, digit z l) + +theorem rankSet_power {v : Coordinates i j k → F} (hv : v ∈ rankSet F i j k r) (n : ℕ) : + powerTable v n ∈ rankSet F (i ^ n) (j ^ n) (k ^ n) (r ^ n) := by + obtain ⟨A, B, C, h⟩ := hv + refine ⟨fun t x => ∏ l, A (finFunctionFinEquiv.symm t l) (digit x l), + fun t y => ∏ l, B (finFunctionFinEquiv.symm t l) (digit y l), + fun t z => ∏ l, C (finFunctionFinEquiv.symm t l) (digit z l), fun x y z => ?_⟩ + rw [← finFunctionFinEquiv.sum_comp] + simp only [powerTable, ← h, Equiv.symm_apply_apply, Fintype.prod_sum, + Finset.prod_mul_distrib] + +end Border + +open Border MvPolynomial + +theorem BorderRankLE.pow (h : BorderRankLE w r) (n : ℕ) : BorderRankLE (WPower w n) (r ^ n) := by + let K := AlgebraicClosure F + let v x y z := algebraMap F K (w x y z) + have hv : (fun x y z => algebraMap F K (WPower w n x y z)) = WPower v n := by + funext x y z + simp only [WPower, map_prod, v] + unfold BorderRankLE + rw [hv, show coefficients (WPower v n) = powerTable (coefficients v) n from + funext fun ⟨x, y, z⟩ => (coefficients_pow v n x y z).symm] + intro p hp + let q := eval₂ C (powerTable X n) p + have he (z : Coordinates i j k → K) : eval z q = eval (powerTable z n) p := by + unfold q + rw [hom_eval₂, show (eval z).comp C = RingHom.id K from eval₂Hom_comp_C _ _] + have hh : (fun t => eval z (powerTable X n t)) = powerTable z n := by + funext t + simp only [powerTable, map_prod, eval_X] + rw [hh] + rfl + rw [← he] + exact h q (fun z hz => (he z).trans (hp _ (rankSet_power hz n))) + +/-- Adjoin the weights together with countably many distinct elements +of the algebraic closure. Infinitude ensures rank-locus identities +over this smaller field apply over the entire closure. -/ +theorem BorderRankLE.small (h : BorderRankLE w r) : + ∃ (K : Type) (_ : Field K) (_ : Infinite K) (_ : Algebra K (AlgebraicClosure F)) + (u : Fin i → Fin j → Fin k → K), + (∀ x y z, u x y z = 0 ↔ w x y z = 0) ∧ ZClosure (rankSet K i j k r) (coefficients u) := by + let L := AlgebraicClosure F + let a := algebraMap F L + let e := Infinite.natEmbedding L + let data : (Fin i × Fin j × Fin k) ⊕ ℕ → L := + Sum.elim (fun p => a (w p.1 p.2.1 p.2.2)) e + obtain ⟨K, _, φ, v, hv⟩ := small_coefficients data + have : Infinite K := Infinite.of_injective (fun n : ℕ => v (.inr n)) (by + intro n m he + apply e.injective + exact (hv (.inr n)).symm.trans ((congrArg φ he).trans (hv (.inr m)))) + let u x y z := v (.inl (x, y, z)) + have hu x y z : φ (u x y z) = a (w x y z) := hv (.inl (x, y, z)) + refine ⟨K, inferInstance, inferInstance, φ.toAlgebra, u, ?_, fun p hp => ?_⟩ + · intro x y z + rw [← φ.injective.eq_iff, hu, map_zero, ← map_zero a, a.injective.eq_iff] + have he : φ ∘ coefficients u = coefficients (fun x y z => a (w x y z)) := by + funext t + simp only [Function.comp_apply, coefficients, apply_ite φ, map_zero, hu] + apply φ.injective + rw [map_zero, eval₂_comp, he, ← eval_map] + exact h _ fun z hz => by rw [eval_map]; exact identity_of_rank hp φ hz + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/Surplus.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/Surplus.lean new file mode 100644 index 0000000000..0b7d2acbbe --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/Surplus.lean @@ -0,0 +1,272 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Mask + +/-! +# Geometric border rank + +Take Zariski closure in the space of all three-tensor coefficients over +the algebraic closure, including the coefficients outside the multiplication +support. The Veronese span bound gives an exact decomposition of every +power at polynomial overhead. This overhead disappears in the limit. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} [Field F] {i j k r : ℕ} + +variable {w : Fin i → Fin j → Fin k → F} + +theorem WeightedRankLE.border (hr : WeightedRankLE w r) : BorderRankLE w r := + fun _ h => h _ (hr.map (algebraMap F (AlgebraicClosure F))) + +open Border in +private theorem closure_pow (h : ZClosure (rankSet F i j k r) (coefficients w)) (n : ℕ) : + rankW (WPower w n) ≤ (n + 1) ^ Fintype.card (Coordinates i j k) * r ^ n := by + obtain ⟨d, hd, y, c, hy, he⟩ := h.power n + choose A B C hABC using fun t => rankSet_power (hy t) n + have hr : WeightedRankLE (WPower w n) (d * r ^ n) := by + let e : Fin (d * r ^ n) ≃ Fin d × Fin (r ^ n) := finProdFinEquiv.symm + refine ⟨fun t x => c (e t).1 * A (e t).1 (e t).2 x, + fun t y => B (e t).1 (e t).2 y, fun t z => C (e t).1 (e t).2 z, ?_⟩ + intro x y' z + change _ = coefficients (WPower w n) (x, y', z) + rw [← coefficients_pow, he, ← e.symm.sum_comp, Fintype.sum_prod_type] + simp only [Equiv.apply_symm_apply] + apply Finset.sum_congr rfl + intro t _ + change _ = c t * powerTable (y t) n (x, y', z) + rw [← hABC, Finset.mul_sum] + simp only [mul_assoc] + exact (rankW_le hr).trans (Nat.mul_le_mul_right _ hd) + +/-- In geometric border rank the decompositions can use the algebraic +closure. Specialization and field descent remove that scalar extension. -/ +theorem BorderRankLE.asymptotic (h : BorderRankLE w r) (hi : 0 < i) (hj : 0 < j) + (hk : 0 < k) : asymptoticRank w ≤ r := by + rcases (supportSize w).eq_zero_or_pos with he | he + · rw [asymptotic_zero he]; positivity + have hw : 0 < Rectangle.density w := by unfold Rectangle.density; positivity + have hp : 0 < asymptoticRank w := lt_of_lt_of_le (by positivity) (asymptotic_density hi hj hk hw) + apply TensorSpectrum.le_of_pow_le_polynomial_mul_pow _ _ 1 (Fintype.card (Coordinates i j k)) + (by positivity) (by norm_num) + intro n hn + have hr := rankW_spec (WPower (extend (AlgebraicClosure F) w) n) + rw [one_mul, Real.rpow_natCast] + exact (extension_lower hr hi hj hk hw hn).trans (by exact_mod_cast closure_pow h n) + +theorem BorderRankLE.density (h : BorderRankLE w r) (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + Rectangle.density w * Real.exp (exponent F (Real.log i) (Real.log j) (Real.log k)) ≤ r := by + rcases le_or_gt (Rectangle.density w) 0 with hw | hw + · exact (mul_nonpos_of_nonpos_of_nonneg hw (Real.exp_nonneg _)).trans (by positivity) + · exact (asymptotic_density hi hj hk hw).trans (h.asymptotic hi hj hk) + +theorem BorderRankLE.full (h : BorderRankLE w r) (hw : ∀ a b c, w a b c ≠ 0) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + Real.exp (exponent F (Real.log i) (Real.log j) (Real.log k)) ≤ r := by + have hd := h.density hi hj hk + rwa [Rectangle.density, full_size hw, Nat.cast_mul, Nat.cast_mul, + div_self (by positivity), one_mul] at hd + +theorem cell_bound (F : Type*) [Field F] : CellBound F := + cells_of_closed (fun K _ _ => (closed_fulfills K).cells) F + +/-- The product on any set of whole output cells pays at least for the +most nearly square rectangle of the same area. -/ +theorem ZClosure.cells (h : ZClosure (rankSet F i j k r) (coefficients w)) {u : Finset (Pos i j)} + (hu : u.Nonempty) (hw : ∀ x y z, w x y z ≠ 0 ↔ (x, y) ∈ u) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + Real.exp (exponent F (short i j u.card) (Real.log u.card - short i j u.card) + (Real.log k)) ≤ r := by + obtain ⟨ha, hb⟩ := short_bounds hi hj hu.card_pos + have hc : 0 ≤ Real.log k := Real.log_nonneg (by exact_mod_cast hk) + apply TensorSpectrum.le_of_pow_le_polynomial_mul_pow _ _ 1 (Fintype.card (Coordinates i j k)) + (by positivity) (by norm_num) + intro n _ + obtain ⟨s, hs, hs'⟩ := power_cells hw hk n + have hs₀ : s.Nonempty := Finset.card_pos.mp (hs.symm ▸ pow_pos hu.card_pos n) + have hh := cell_bound F _ _ _ _ (pow_pos hi n) (pow_pos hj n) (pow_pos hk n) _ s hs₀ hs' + (rankW_spec (WPower w n)) + simp only [hs, short_pow, Nat.cast_pow, Real.log_pow, ← mul_sub] at hh + rw [homogeneous F ha (sub_nonneg.mpr hb) hc (Nat.cast_nonneg _), Real.exp_nat_mul] at hh + rw [one_mul, Real.rpow_natCast] + exact hh.trans (by exact_mod_cast closure_pow h n) + +theorem BorderRankLE.cells (h : BorderRankLE w r) {u : Finset (Pos i j)} + (hu : u.Nonempty) (hw : ∀ x y z, w x y z ≠ 0 ↔ (x, y) ∈ u) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + Real.exp (exponent F (short i j u.card) (Real.log u.card - short i j u.card) + (Real.log k)) ≤ r := by + let K := AlgebraicClosure F + let v x y z := algebraMap F K (w x y z) + have hv (x y z) : v x y z ≠ 0 ↔ (x, y) ∈ u := by simpa [v] using hw x y z + obtain ⟨ha, hb⟩ := short_bounds hi hj hu.card_pos + have hc : 0 ≤ Real.log k := Real.log_nonneg (by exact_mod_cast hk) + rw [← exponent_extension F K ha (sub_nonneg.mpr hb) hc] + exact ZClosure.cells h hu hv hi hj hk + +theorem BorderRankLE.surplus (h : BorderRankLE w r) (hw : ∀ a b c, w a b c ≠ 0) + {q : ℕ} (hq : 0 < q) (hk : 0 < k) (hq' : q ≤ i * j) : + Real.exp (exponent F (short i j q) (Real.log q - short i j q) (Real.log k)) - q ≤ + (r : ℝ) - (i : ℝ) * j := by + have hi : 0 < i := Nat.pos_of_ne_zero (by rintro rfl; simp at hq'; omega) + have hj : 0 < j := Nat.pos_of_ne_zero (by rintro rfl; simp at hq'; omega) + obtain ⟨harea, u, he, hcut⟩ := h.delete hw hk hq' + have hu : u.Nonempty := Finset.card_pos.mp (he.symm ▸ hq) + have hm (x y z) : mask w u x y z ≠ 0 ↔ (x, y) ∈ u := by simp [mask, hw] + have hl := hcut.cells hu hm hi hj hk + rw [he, Nat.cast_sub ((Nat.sub_le _ _).trans harea), Nat.cast_sub hq', Nat.cast_mul] at hl + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Geometric border rank at the harmonic threshold + +Choose the retained area as a product of rounded side lengths. +Trimming the longer side, or both sides equally at a square, makes +these the most nearly square lengths that fit at that area. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +private theorem short_left {i j a b : ℕ} (ha : 0 < a) (hab : a ≤ b) (hi : a ≤ i) (hj : b ≤ j) + (he : a = i ∨ a = b) : short i j (a * b) = Real.log a := by + have hb := ha.trans_le hab + have hlog {s t : ℕ} (hs : 0 < s) (h : s ≤ t) : Real.log s ≤ Real.log t := + Real.log_le_log (by positivity) (by exact_mod_cast h) + rw [short, Nat.cast_mul, Real.log_mul (by positivity) (by positivity)] + apply le_antisymm _ (le_min (le_min (hlog ha hi) (hlog ha (hab.trans hj))) + (by linarith [hlog ha hab])) + rcases he with he | he + · exact (min_le_left _ _).trans ((min_le_left _ _).trans_eq (by rw [he])) + · exact (min_le_right _ _).trans_eq (by rw [he]; ring) + +private theorem trim_longer (u : ℝ) {x y : ℝ} (hxy : x < y) : + ∀ᶠ n : ℕ in atTop, side n x ≤ trimmed n y u := by + have h := (tendsto_rpow_atTop (sub_pos.mpr hxy)).comp tendsto_natCast_atTop_atTop + filter_upwards [eventually_gt_atTop 0, h.eventually_ge_atTop (Real.exp u)] with n hn he + apply Nat.ceil_mono + rw [Real.exp_neg, le_inv_mul_iff₀ (Real.exp_pos _)] + change Real.exp u ≤ (n : ℝ) ^ (y - x) at he + rwa [Real.rpow_sub (by positivity), le_div_iff₀ (by positivity)] at he + +private theorem exponent_short (F : Type*) [Field F] {i j a b k : ℕ} + (ha : 0 < a) (hb : 0 < b) (hk : 0 < k) + (h : short i j (a * b) = Real.log a ∨ short i j (a * b) = Real.log b) : + exponent F (short i j (a * b)) (Real.log (a * b : ℕ) - short i j (a * b)) (Real.log k) = + exponent F (Real.log a) (Real.log b) (Real.log k) := by + rw [Nat.cast_mul, Real.log_mul (by positivity) (by positivity)] + rcases h with h | h + · rw [h, add_sub_cancel_left] + · rw [h, add_sub_cancel_right] + exact transpose _ (Real.log_nonneg (by exact_mod_cast hb)) + (Real.log_nonneg (by exact_mod_cast ha)) (Real.log_nonneg (by exact_mod_cast hk)) + +private theorem border_shift {K : ℕ → Type*} [∀ n, Field (K n)] {x y : ℝ} + (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hrig : ∀ n, Rigidity (K n)) (hsq : ∀ n, MatrixExponent.omega (K n) = 9 / 4) + {b : ℝ} {a : ℕ → ℕ} (ha : ∀ n, 0 < n → 0 < a n) + (hlog : Tendsto (fun n => Real.log (a n) - x * y * Real.log n) atTop (nhds (b * (x * y)))) + (w : ∀ n, Fin (side n x) → Fin (side n y) → Fin (a n) → K n) + (hw : ∀ n a b c, w n a b c ≠ 0) (r : ℕ → ℕ) (hr : ∀ n, BorderRankLE (w n) (r n)) + {L : ℝ} (hL : L < Threshold.optimum b (min (x / y) (y / x))) : + ∀ᶠ n in atTop, L < normalized x y r n := by + have hl (s t : ℝ) (hs : 0 ≤ s) (ht : 0 ≤ t) + (h : L < Real.exp (-s - t) * (max (b + (y / x) * s + (x / y) * t) 0) ^ 2 / 4) + (hfit : ∀ᶠ n : ℕ in atTop, + let a := trimmed n x s + let b := trimmed n y t + let z := short (side n x) (side n y) (a * b) + z = Real.log a ∨ z = Real.log b) : + ∀ᶠ n in atTop, L < normalized x y r n := by + filter_upwards [eventually_gt_atTop 0, (trimmed_shifted_surplus_limit hx hy hxy hlog s + t).eventually + (lt_mem_nhds h), hfit] with n hn hn' hfit' + have hi := trimmed_pos hn x s + have hj := trimmed_pos hn y t + have hk := ha n hn + have hd := (hr n).surplus (hw n) (Nat.mul_pos hi hj) hk + (Nat.mul_le_mul (trimmed_le n x hs) (trimmed_le n y ht)) + have hlog {i : ℕ} (h : 0 < i) : 0 ≤ Real.log (i : ℝ) := + Real.log_nonneg (by exact_mod_cast h) + rw [exponent_short _ hi hj hk hfit', Nat.cast_mul, + all_shapes (hrig n) (hsq n) (hlog hi) (hlog hj) (hlog hk)] at hd + have hA : 1 ≤ (side n x : ℝ) * side n y := by + exact_mod_cast Nat.mul_pos (side_pos hn x) (side_pos hn y) + exact hn'.trans_le (div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_right hd + (Real.log_nonneg hA)) (by positivity)) + let C := min (x / y) (y / x) + have hC : 0 < C := by unfold C; positivity + obtain ⟨u, hu, he⟩ := (Threshold.maximum b hC).2.1 + have hbound : L < Threshold.gain b C u := he.symm ▸ hL + unfold Threshold.gain C at hbound + rcases lt_trichotomy x y with h | rfl | h + · apply hl 0 u le_rfl hu + · have hh : x / y ≤ y / x := by gcongr + simpa [min_eq_left hh] using hbound + · filter_upwards [eventually_gt_atTop 0, trim_longer u h] with n hn he + left + rw [trimmed_zero] + exact short_left (side_pos hn x) he le_rfl (trimmed_le n y hu) (.inl rfl) + · apply hl (u / 2) (u / 2) (by positivity) (by positivity) + · simpa [show -(u / 2) - u / 2 = -u by ring, div_self hx.ne', add_assoc] using hbound + · filter_upwards [eventually_gt_atTop 0] with n hn + left + have h' := trimmed_le n x (show 0 ≤ u / 2 by positivity) + exact short_left (trimmed_pos hn x _) le_rfl h' h' (.inr rfl) + · apply hl u 0 hu le_rfl + · have hh : y / x ≤ x / y := by gcongr + simpa [min_eq_right hh] using hbound + · filter_upwards [eventually_gt_atTop 0, trim_longer u h] with n hn he + right + rw [trimmed_zero] + rw [show short (side n x) (side n y) (trimmed n x u * side n y) = + short (side n y) (side n x) (side n y * trimmed n x u) by simp [short, min_comm, mul_comm]] + exact short_left (side_pos hn y) he le_rfl (trimmed_le n x hu) (.inl rfl) + +theorem scaled_border_surplus {K : ℕ → Type*} [∀ n, Field (K n)] {x y a : ℝ} + (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) (ha : 0 < a) + (hrig : ∀ n, Rigidity (K n)) (hsq : ∀ n, MatrixExponent.omega (K n) = 9 / 4) + (w : ∀ n, Fin (side n x) → Fin (side n y) → Fin (Threshold.width n x y a) → K n) + (hw : ∀ n a b c, w n a b c ≠ 0) (r : ℕ → ℕ) (hr : ∀ n, BorderRankLE (w n) (r n)) + {L : ℝ} (hL : L < Threshold.optimum (Real.log a / (x * y)) (min (x / y) (y / x))) : + ∀ᶠ n in atTop, L < normalized x y r n := by + apply border_shift hx hy hxy hrig hsq _ (Threshold.log_width hx hy ha) w hw r hr hL + intro n hn + exact Nat.ceil_pos.mpr (by positivity) + +/-- The border-rank half of the harmonic threshold corollary. -/ +theorem border_surplus {K : ℕ → Type*} [∀ n, Field (K n)] {x y : ℝ} + (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hrig : ∀ n, Rigidity (K n)) (hsq : ∀ n, MatrixExponent.omega (K n) = 9 / 4) + (w : ∀ n, Fin (side n x) → Fin (side n y) → Fin (side n (x * y)) → K n) + (hw : ∀ n a b c, w n a b c ≠ 0) (r : ℕ → ℕ) (hr : ∀ n, BorderRankLE (w n) (r n)) + {L : ℝ} (hL : L < Real.exp (-2) * min ((x / y) ^ 2) ((y / x) ^ 2)) : + ∀ᶠ n in atTop, L < normalized x y r n := by + refine border_shift hx hy hxy hrig hsq (b := 0) (fun n hn => side_pos hn (x * y)) + (by simpa using log_side (mul_pos hx hy)) w hw r hr ?_ + rw [Threshold.optimum, ite_eq_left (by positivity), zero_div, zero_sub, mul_comm] + rcases le_total (x / y) (y / x) with h | h + · simpa only [min_eq_left h, min_eq_left (pow_le_pow_left₀ (by positivity) h 2)] using hL + · simpa only [min_eq_right h, min_eq_right (pow_le_pow_left₀ (by positivity) h 2)] using hL + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/WeightedModel.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/WeightedModel.lean new file mode 100644 index 0000000000..677559a9e5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Border/WeightedModel.lean @@ -0,0 +1,43 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Semiring + +/-! # The three tensor legs of a weighted product -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral + +variable {F : Type} [Field F] {i j k : ℕ} + +/-- The indexed operation `Fin.cases a (Fin.cases b (Fin.cases c fun t => Fin.elim0 t))`. -/ +def tripleLeg {α : Fin 3 → Sort*} (a : α 0) (b : α 1) (c : α 2) : ∀ t, α t := + Fin.cases a (Fin.cases b (Fin.cases c fun t => Fin.elim0 t)) + +/-- The value specified by `![Pos i j, Pos i k, Pos k j]`. -/ +abbrev legs (i j k : ℕ) : Fin 3 → Type := ![Pos i j, Pos i k, Pos k j] + +instance legFintype (i j k : ℕ) : ∀ s, Fintype (legs i j k s) := + tripleLeg (inferInstanceAs (Fintype (Pos i j))) (inferInstanceAs (Fintype (Pos i k))) + (inferInstanceAs (Fintype (Pos k j))) + +/-- The value specified by `(x 1, x 2, x 0)`. -/ +def ungroup (x : ∀ s, legs i j k s) : Coordinates i j k := (x 1, x 2, x 0) + +/-- The value specified by `Tensor.ofRaw (Raw.ofTable (legs i j k) (T ∘ ungroup))`. -/ +def wtensor (T : Coordinates i j k → F) : Tensor F (Fin 3) := + Tensor.ofRaw (Raw.ofTable (legs i j k) (T ∘ ungroup)) + +/-- Computes the weighted tensor by the application `wtensor (coefficients w)`. -/ +def weightedTensor (w : Fin i → Fin j → Fin k → F) := wtensor (coefficients w) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Bounds.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Bounds.lean new file mode 100644 index 0000000000..043b878722 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Bounds.lean @@ -0,0 +1,134 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Nodes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CircuitCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Bilinearize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics + +/-! # Universal arithmetic bounds and the coordinate planes -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +variable {F : Type*} [Field F] {a b c s : ℝ} + +@[simp] theorem side_one (n : ℕ) : side n 1 = n := by simp [side] + +theorem square (F : Type*) [Field F] : exponent F 1 1 1 = MatrixExponent.omega F := by + unfold exponent MatrixExponent.omega Admissible MatrixExponent.Admissible + simp only [side_one] + rfl + +theorem side_pos {n : ℕ} (hn : 0 < n) (a : ℝ) : 0 < side n a := + Nat.ceil_pos.mpr (by positivity) + +theorem side_le {n : ℕ} (hn : 0 < n) (ha : 0 ≤ a) : + (side n a : ℝ) ≤ 2 * (n : ℝ) ^ a := by + have h : 1 ≤ (n : ℝ) ^ a := Real.one_le_rpow (by exact_mod_cast hn) ha + exact (Nat.ceil_lt_add_one (by positivity)).le.trans (by linarith) + +/-- Raise a rounded side length to a power between zero and one. -/ +theorem rounded_dot {n : ℕ} (hn : 0 < n) {a p : ℝ} (ha : 0 ≤ a) + (hp : 0 ≤ p) (hp' : p ≤ 1) : + (side n a : ℝ) ^ p ≤ 2 * (n : ℝ) ^ (a * p) := by + calc + _ ≤ (2 * (n : ℝ) ^ a) ^ p := + Real.rpow_le_rpow (by positivity) (side_le hn ha) hp + _ = (2 : ℝ) ^ p * (n : ℝ) ^ (a * p) := by + rw [Real.mul_rpow (by norm_num) (by positivity), ← Real.rpow_mul (by positivity)] + _ ≤ _ := by + apply mul_le_mul_of_nonneg_right _ (by positivity) + simpa using Real.rpow_le_rpow_of_exponent_le (by norm_num : (1 : ℝ) ≤ 2) hp' + +/-- Taking a positive real root preserves a power inequality. -/ +theorem root_le {a b p : ℝ} (hp : 0 < p) (ha : 0 ≤ a) (h : a ^ p ≤ b) : + a ≤ b ^ (1 / p) := by + simpa only [one_div] using + (Real.le_rpow_inv_iff_of_pos ha ((Real.rpow_nonneg ha p).trans h) hp).2 h + +private theorem naive (F : Type*) [Field F] (i j k : ℕ) : + ∃ m : ℕ, Computes F i j k m ∧ m ≤ i * j * (k * 2) := by + have h (p : Pos i j) : + CanMake (initial F i j k) (Fintype.card (Fin k) * 2) {output F p} := + CanMake.linear (Or.inl ⟨0, map_zero _⟩) (fun _ => Or.inr ⟨_, rfl⟩) + (fun _ => Or.inr ⟨_, rfl⟩) + obtain ⟨m, hm, T, hT, ho⟩ := CanMake.range h + exact ⟨m, ⟨T, hT.embed, fun p => ho ⟨p, rfl⟩⟩, by simpa [Pos] using hm⟩ + +theorem volume_admissible (F : Type*) [Field F] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + Admissible F a b c (a + b + c) := by + intro ε hε + refine ⟨16, by norm_num, ?_⟩ + intro n hn + have hn₀ : 0 < (n : ℝ) := by positivity + have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast hn + obtain ⟨m, hm, hcost⟩ := naive F (side n a) (side n b) (side n c) + refine ⟨m, hm, ?_⟩ + calc + (m : ℝ) ≤ (side n a : ℝ) * side n b * (side n c * 2) := by exact_mod_cast hcost + _ ≤ (2 * (n : ℝ) ^ a) * (2 * (n : ℝ) ^ b) * (2 * (n : ℝ) ^ c * 2) := by + gcongr <;> apply side_le <;> assumption + _ = 16 * (n : ℝ) ^ (a + b + c) := by rw [Real.rpow_add hn₀, Real.rpow_add hn₀]; ring + _ ≤ _ := mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hn₁ (by linarith)) (by + norm_num) + +/-- Any uniform polynomial lower bound on twice the circuit cost transfers +to every admissible exponent. -/ +theorem le_admissible_of_cost (hs : Admissible F a b c s) {t : ℝ} + (hl : ∀ n m : ℕ, 2 ≤ n → Computes F (side n a) (side n b) (side n c) m → + (n : ℝ) ^ t ≤ 2 * m) : t ≤ s := by + by_contra! hlt + let ε := (t - s) / 2 + have hε : 0 < ε := by dsimp [ε]; linarith + obtain ⟨C, _, hC⟩ := hs ε hε + have ht : Tendsto (fun n : ℕ => (n : ℝ) ^ ε) atTop atTop := + (tendsto_rpow_atTop hε).comp tendsto_natCast_atTop_atTop + obtain ⟨n, hn, hp⟩ := ((eventually_ge_atTop 2).and (ht.eventually_gt_atTop (2 * C))).exists + obtain ⟨m, hm, hcost⟩ := hC n (by omega) + have hn₀ : 0 < (n : ℝ) := by exact_mod_cast (show 0 < n by omega) + apply (hl n m hn hm).not_gt + calc + 2 * (m : ℝ) ≤ (2 * C) * (n : ℝ) ^ (s + ε) := by linarith + _ < (n : ℝ) ^ ε * (n : ℝ) ^ (s + ε) := mul_lt_mul_of_pos_right hp (by positivity) + _ = (n : ℝ) ^ t := by rw [← Real.rpow_add hn₀, show ε + (s + ε) = t by dsimp [ε]; ring] + +private theorem area_cost {n m : ℕ} (hn : 0 < n) + (h : side n a * side n b ≤ 2 * m) : (n : ℝ) ^ (a + b) ≤ 2 * m := by + rw [Real.rpow_add (by positivity)] + calc + _ ≤ (side n a : ℝ) * side n b := + mul_le_mul (Nat.le_ceil _) (Nat.le_ceil _) (by positivity) (by positivity) + _ ≤ _ := by exact_mod_cast h + +theorem areas_le_admissible (h : Admissible F a b c s) : + max (a + b) (max (a + c) (b + c)) ≤ s := by + refine max_le ?_ (max_le ?_ ?_) <;> apply le_admissible_of_cost h <;> intro n m hn hm + · exact area_cost (by omega) ((bilinearize hm).area (side_pos (by omega) c)) + · rw [add_comm a c] + exact area_cost (by omega) ((bilinearize hm).cycle.cycle.area (side_pos (by omega) b)) + · exact area_cost (by omega) ((bilinearize hm).cycle.area (side_pos (by omega) a)) + +theorem bounds (F : Type*) [Field F] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + max (a + b) (max (a + c) (b + c)) ≤ exponent F a b c ∧ + exponent F a b c ≤ a + b + c := by + have h := volume_admissible F ha hb hc + exact ⟨le_csInf ⟨_, h⟩ (fun _ ht => areas_le_admissible ht), + csInf_le ⟨_, fun _ ht => areas_le_admissible ht⟩ h⟩ + +theorem coordinate_plane (F : Type*) [Field F] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (h : a = 0 ∨ b = 0 ∨ c = 0) : exponent F a b c = a + b + c := by + obtain ⟨hl, hu⟩ := bounds F ha hb hc + refine le_antisymm hu ?_ + rw [max_le_iff, max_le_iff] at hl + rcases h with h | h | h <;> linarith [hl.1, hl.2.1, hl.2.2] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/CharacterRank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/CharacterRank.lean new file mode 100644 index 0000000000..797306fdf5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/CharacterRank.lean @@ -0,0 +1,83 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Support +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.DotsPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.FlatteningOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.RectangularRank + +/-! +# From the character estimate to rectangular algorithms + +Each pairing belongs to the two legs other than its named leg. Reading +the first two legs as inputs and the third as output gives a rank bound +on the formal product. Ceiling costs at most a factor of two per pairing. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Upper Upper.TensorClass + +private abbrev dots := TensorSpectrum.TensorClass.dots (K := Coeff) + +private theorem dots_power (i j k t : ℕ) : + dots (i ^ t) (j ^ t) (k ^ t) = (dots i j k) ^ t := + TensorSpectrum.TensorClass.dots_power i j k t + +private theorem rank_of_dots {i j k r : ℕ} (h : dots i j k ≤ (r : TensorClass)) : + RankLE Coeff i j k r := + TensorSpectrum.TensorClass.rank_of_dots h + +private theorem price_dots (f : Character) {n : ℕ} (hn : 0 < n) {a b c : ℝ} + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + (f (dots (side n a) (side n b) (side n c)) : ℝ) ≤ + 8 * (n : ℝ) ^ (b * f.pX + a * f.pY + c * f.pZ) := + TensorSpectrum.TensorClass.price_dots f hn ha hb hc + +theorem exponent_le_of_characters {a b c s : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) + (hc : 0 ≤ c) (hs : 0 ≤ s) + (h : ∀ f : Character, b * f.pX + a * f.pY + c * f.pZ ≤ s) : + exponent Coeff a b c ≤ s := by + refine exponent_le_of_rank_powers ha hb hc hs ?_ + intro n r hn hlo hr + have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast (show 1 ≤ n by omega) + have hne : (r : TensorClass) ≠ 0 := by + intro he + have he' := (rank_eq_zero_iff _).mpr he + rw [rank_natCast] at he' + exact hr.ne' (by exact_mod_cast he') + let M := dots (side n a) (side n b) (side n c) + have hp (g : TensorClass →+* NNReal) (hg : Monotone g) : g M < g (r : TensorClass) := by + let f : Character := ⟨g, hg⟩ + rw [map_natCast] + apply NNReal.coe_lt_coe.mp + calc + (g M : ℝ) ≤ 8 * (n : ℝ) ^ (b * f.pX + a * f.pY + c * f.pZ) := + price_dots f (by omega) ha hb hc + _ ≤ 8 * (n : ℝ) ^ s := + mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hn₁ (h f)) (by norm_num) + _ < (r : ℝ) := hlo + obtain ⟨C, hC⟩ := Spectrum.strictComparison + (fun _ _ _ h => add_mono h le_rfl) (fun _ _ _ h => mul_mono le_rfl h) + TensorClass.zero_le (fun _ => one_le_of_ne_zero) (fun A => ⟨rank A, le_rank_natCast A⟩) hne hp + refine ⟨C, fun p => rank_of_dots ?_⟩ + rw [dots_power, Nat.cast_mul, Nat.cast_pow, mul_comm] + exact hC p + +theorem coeff_discrete + (h : ∀ (f : Character) (A B C : ℕ), 0 < A → 0 < B → 0 < C → + 4 * (f.pX * B * C + f.pY * A * C + f.pZ * A * B) ≤ ((A : ℝ) + B + C) ^ 2) : + DiscreteBound Coeff := by + intro A B C hA hB hC + apply exponent_le_of_characters (by positivity) (by positivity) (by positivity) (by positivity) + intro f + linarith only [h f B C A hB hC hA] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Dual.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Dual.lean new file mode 100644 index 0000000000..5469aa2f8b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Dual.lean @@ -0,0 +1,726 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights +public import Mathlib.LinearAlgebra.Matrix.Rank +public import Mathlib.LinearAlgebra.Finsupp.LinearCombination +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Bounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldExtension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.FiniteModel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.UpperBound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Threshold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Support +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law +public import Mathlib.Analysis.Subadditive +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth + +/-! +# Deleting output rows and columns in exact bilinear rank + +The output coefficients of a full-support product are independent. The +discarded outputs therefore give independent kernel vectors for the matrix of +restricted rank-one products. A column basis consists of rank-one products +and still spans every retained output. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} [Field F] {i j k i' j' r s : ℕ} + +variable {w : Fin i → Fin j → Fin k → F} + +private theorem WeightedRankLE.mono (h : WeightedRankLE w r) (hrs : r ≤ s) : + WeightedRankLE w s := by + induction s, hrs using Nat.le_induction with + | base => exact h + | succ s _ ih => + obtain ⟨a, b, c, hc⟩ := ih + refine ⟨Fin.cons 0 a, Fin.cons 0 b, Fin.cons 0 c, fun x y z => ?_⟩ + simpa [Fin.sum_univ_succ] using hc x y z + +private def products (a : Fin r → Pos i k → F) (b : Fin r → Pos k j → F) : + Matrix (Pos i k × Pos k j) (Fin r) F := fun p l => a l p.1 * b l p.2 + +private theorem compress_products (a : Fin r → Pos i k → F) (b : Fin r → Pos k j → F) + (c : Fin r → Pos i j → F) : + let d := (products a b).rank + ∃ (e : Fin d → Fin r) (c' : Fin d → Pos i j → F), ∀ x y z, + ∑ l, a (e l) x * b (e l) y * c' l z = ∑ l, a l x * b l y * c l z := by + classical + let M := products a b + rw [Matrix.rank_eq_finrank_span_cols] + obtain ⟨v, hv, heq, _⟩ := Submodule.exists_fun_fin_finrank_span_eq F (Set.range M.col) + choose e he using hv + have hmem (z : Pos i j) : ∑ l, c l z • M.col l ∈ Submodule.span F (Set.range v) := by + rw [heq] + exact (Submodule.mem_span_range_iff_exists_fun _).mpr ⟨fun l => c l z, rfl⟩ + choose c' hc' using fun z => (Submodule.mem_span_range_iff_exists_fun _).mp (hmem z) + refine ⟨e, fun l z => c' z l, fun x y z => ?_⟩ + have hz := congrFun (hc' z) (x, y) + simp only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul, ← he] at hz + simpa only [Matrix.col_apply, M, products, mul_comm] using hz + +theorem WeightedRankLE.delete (h : WeightedRankLE w r) (hw : ∀ x y z, w x y z ≠ 0) + (hk : 0 < k) (hi : i' ≤ i) (hj : j' ≤ j) : + i * j ≤ r ∧ WeightedRankLE (fun x y z => w (Fin.castLE hi x) (Fin.castLE hj y) z) + (r - (i * j - i' * j')) := by + classical + obtain ⟨a, b, c, hc⟩ := h + let v : Fin k := ⟨0, hk⟩ + let B {α : Type} (z : α → Pos i j) : Matrix (Fin r) α F := fun l t => c l (z t) + have hind {α : Type} [Fintype α] (z : α → Pos i j) (hinj : Function.Injective z) : + Fintype.card α ≤ (B z).rank := by + let A : Matrix α (Fin r) F := fun t l => + (w (z t).1 (z t).2 v)⁻¹ * (a l ((z t).1, v) * b l (v, (z t).2)) + have he : A * B z = 1 := by + ext t u + rw [Matrix.mul_apply, Matrix.one_apply] + simp only [A, B, mul_assoc ((w _ _ _)⁻¹), ← Finset.mul_sum, hc, + true_and, ← Prod.ext_iff, hinj.eq_iff, mul_ite, mul_zero, inv_mul_cancel₀ (hw _ _ _)] + simpa only [he, Matrix.rank_one] using Matrix.rank_mul_le_right A (B z) + constructor + · simpa [Pos] using (hind id Function.injective_id).trans (B id).rank_le_card_height + let X (x : Pos i' k) : Pos i k := (Fin.castLE hi x.1, x.2) + let Y (y : Pos k j') : Pos k j := (y.1, Fin.castLE hj y.2) + let Z (z : Pos i' j') : Pos i j := (Fin.castLE hi z.1, Fin.castLE hj z.2) + let a' l x := a l (X x) + let b' l y := b l (Y y) + let M := products a' b' + let D := (Set.range Z)ᶜ + let z : D → Pos i j := Subtype.val + have hzero : M * B z = 0 := by + ext p t + rw [Matrix.mul_apply, Matrix.zero_apply] + change ∑ l, a l (X p.1) * b l (Y p.2) * c l (z t) = 0 + rw [hc, ite_eq_right] + rintro ⟨h₁, _, h₂⟩ + exact t.property ⟨(p.1.1, p.2.2), Prod.ext h₁ h₂⟩ + have hcard : i * j - i' * j' ≤ Fintype.card D := by + unfold D + rw [Fintype.card_compl_set] + simpa [Pos] using Nat.sub_le_sub_left (Fintype.card_range_le Z) (i * j) + have hbound : M.rank ≤ r - (i * j - i' * j') := by + have := Matrix.rank_add_rank_le_card_of_mul_eq_zero hzero + rw [Fintype.card_fin] at this + have := hind z Subtype.val_injective + omega + apply WeightedRankLE.mono _ hbound + obtain ⟨e, c', he⟩ := compress_products a' b' (fun l p => c l (Z p)) + refine ⟨fun l => a' (e l), fun l => b' (e l), c', fun x y z => ?_⟩ + refine (he x y z).trans ?_ + simpa [a', b', X, Y, Z, Fin.ext_iff] using hc (X x) (Y y) (Z z) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- # Rectangular shapes and dual exponents from square equality and rigidity -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} [Field F] {a b c : ℝ} + +/-- The square is active, so square equality excludes the strict branch. -/ +theorem positive_shapes (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : exponent F a b c = U a b c := by + rcases hr with h | h + · exact h a b c ha hb hc + · have h' := h 1 1 1 (by norm_num) (by norm_num) (by norm_num) + (by norm_num [U, benchmark]) + rw [square, hs] at h' + norm_num [U, benchmark] at h' + +theorem U_plane (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (h : a = 0 ∨ b = 0 ∨ c = 0) : U a b c = a + b + c := by + unfold U + split_ifs with h₁ h₂ + · have : c = 0 := by + rw [le_min_iff] at h₁ + rcases h with h | h | h <;> linarith [h₁.1, h₁.2] + simp [this, benchmark] + · rw [min_eq_left h₂] at h₁ + have : a = 0 := by rcases h with h | h | h <;> linarith + simp [this, benchmark] + · rw [min_eq_right (le_of_not_ge h₂)] at h₁ + have : b = 0 := by rcases h with h | h | h <;> linarith + simp [this, benchmark, add_comm] + +theorem all_shapes (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : exponent F a b c = U a b c := by + by_cases h : a = 0 ∨ b = 0 ∨ c = 0 + · rw [coordinate_plane F ha hb hc h, U_plane ha hb hc h] + push Not at h + exact positive_shapes hr hs (ha.lt_of_ne' h.1) (hb.lt_of_ne' h.2.1) (hc.lt_of_ne' h.2.2) + +theorem ordered_formula (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + (hc : 0 < c) (h : c ≤ min a b) : + exponent F a b c = a + b + (max ((a + b) * c - a * b) 0) ^ 2 / (4 * a * b * c) := by + rw [positive_shapes hr hs (hc.trans_le (le_min_iff.mp h).1) (hc.trans_le (le_min_iff.mp h).2) hc, + U, ite_eq_left h, benchmark] + +theorem threshold (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + (ha : 0 < a) (hb : 0 < b) (hc : 0 ≤ c) (hc' : c ≤ min a b) : + exponent F a b c = a + b ↔ c ≤ a * b / (a + b) := by + rcases eq_or_lt_of_le hc with rfl | hc + · rw [coordinate_plane F ha.le hb.le le_rfl (Or.inr (Or.inr rfl)), add_zero] + simp [le_of_lt (div_pos (mul_pos ha hb) (add_pos ha hb))] + rw [ordered_formula hr hs hc hc', add_eq_left, div_eq_zero_iff, sq_eq_zero_iff, + or_iff_left (by positivity : 4 * a * b * c ≠ 0), max_eq_right_iff, sub_nonpos, + le_div_iff₀ (add_pos ha hb), mul_comm c] + +/-- The dual exponent is attained, including for nonsquare output. -/ +theorem greatest (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + (ha : 0 < a) (hb : 0 < b) : + IsGreatest {c ∈ Set.Icc 0 (min a b) | exponent F a b c = a + b} (a * b / (a + b)) := by + have h : 0 ≤ a * b / (a + b) := by positivity + have h' : a * b / (a + b) ≤ min a b := by + apply le_min <;> rw [div_le_iff₀ (add_pos ha hb)] <;> nlinarith + exact ⟨⟨⟨h, h'⟩, (threshold hr hs ha hb h h').mpr le_rfl⟩, + fun _ hc => (threshold hr hs ha hb hc.1.1 hc.1.2).mp hc.2⟩ + +theorem dual_eq (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + (ha : 0 < a) (hb : 0 < b) : dual F a b = a * b / (a + b) := + (greatest hr hs ha hb).csSup_eq + +theorem dual_square (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) : dual F 1 1 = 1 / 2 + := by + rw [dual_eq hr hs zero_lt_one zero_lt_one] + norm_num + +theorem square_output (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + (hc : 0 ≤ c) (hc' : c ≤ 1) : + exponent F 1 1 c = if c ≤ 1 / 2 then 2 else 2 + (c - 1 / 2) ^ 2 / c := by + split_ifs with h + · have := (threshold hr hs zero_lt_one zero_lt_one hc (le_min hc' hc')).mpr (by linarith) + linarith + · rw [ordered_formula hr hs (by linarith) (le_min hc' hc'), max_eq_left (by linarith)] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- Cyclic symmetrization transfers a square lower bound to every shape. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} [Field F] {i j k r : ℕ} {a b c : ℝ} + +theorem RankLE.volume_lower (hr : RankLE F i j k r) (hω : 9 / 4 ≤ omega F) : + ((i : ℝ) * j * k) ^ (3 / 4 : ℝ) ≤ r := by + have hs := hr.symmetrize + rw [← Nat.cast_mul, ← Nat.cast_mul] + let N := i * j * k + change MatrixExponent.RankLE F N (r ^ 3) at hs + change (N : ℝ) ^ (3 / 4 : ℝ) ≤ r + by_cases hN : 2 ≤ N + · by_contra! hlt + apply hω.not_gt + apply omega_lt_of_rank hN hs + rw [Nat.cast_pow] + calc + (r : ℝ) ^ 3 < ((N : ℝ) ^ (3 / 4 : ℝ)) ^ (3 : ℕ) := + pow_lt_pow_left₀ hlt (by positivity) (by decide) + _ = (N : ℝ) ^ (9 / 4 : ℝ) := by + rw [← Real.rpow_mul_natCast (Nat.cast_nonneg N)] + norm_num + · have hl := rank_lower hs + rcases (show N = 0 ∨ N = 1 by omega) with h | h + · norm_num [h] + · have hr0 : r ≠ 0 := by rintro rfl; simp [h] at hl + simpa [h] using (show 1 ≤ (r : ℝ) by exact_mod_cast Nat.one_le_iff_ne_zero.mpr hr0) + +/-- The mixed derivatives give a rectangular decomposition over a rational +function field. The square exponent is unchanged by this extension. -/ +theorem volume_lower (hω : 9 / 4 ≤ omega F) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + 3 / 4 * (a + b + c) ≤ exponent F a b c := by + refine le_csInf ⟨_, volume_admissible F ha hb hc⟩ fun s hs => ?_ + apply le_admissible_of_cost hs + intro n m hn hm + have hn₀ : 0 < (n : ℝ) := by exact_mod_cast (show 0 < n by omega) + have hr := (bilinearize hm).volume_lower (by rw [omega_extension F]; exact hω) + calc + (n : ℝ) ^ (3 / 4 * (a + b + c)) = + ((n : ℝ) ^ a * (n : ℝ) ^ b * (n : ℝ) ^ c) ^ (3 / 4 : ℝ) := by + rw [mul_comm, Real.rpow_mul hn₀.le, Real.rpow_add hn₀, Real.rpow_add hn₀] + _ ≤ ((side n a : ℝ) * side n b * side n c) ^ (3 / 4 : ℝ) := by + gcongr <;> exact Nat.le_ceil _ + _ ≤ 2 * m := by simpa using hr + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- # From arbitrary block sides to powers of one fixed format -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +private theorem pad_fixed {n p q i : ℕ} (hn : 2 ≤ n) (hi : 0 < i) + (hp : (p : ℝ) ≤ q * Real.log n) : i ^ p ≤ (side n (Real.log i)) ^ q := by + have hn' : 0 < (n : ℝ) := by exact_mod_cast (show 0 < n by omega) + have hi' : 1 ≤ (i : ℝ) := by exact_mod_cast hi + have h := Real.exp_le_exp.mpr (mul_le_mul_of_nonneg_right hp (Real.log_nonneg hi')) + rw [mul_assoc, Real.exp_nat_mul, Real.exp_nat_mul, Real.exp_log (by positivity), + ← Real.rpow_def_of_pos hn'] at h + have h' := pow_le_pow_left₀ (Real.rpow_nonneg hn'.le (Real.log i)) + (Nat.le_ceil ((n : ℝ) ^ Real.log i)) q + exact_mod_cast h.trans h' + +/-- Every strict bound on the exponent at the logarithmic shape can +be met by the log rank per copy of an actual finite tensor power. -/ +theorem fixed_rank {F : Type*} [Field F] {i j k : ℕ} (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) + {s : ℝ} (h : exponent F (Real.log i) (Real.log j) (Real.log k) < s) : + ∃ p r : ℕ, 0 < p ∧ RankLE F (i ^ p) (j ^ p) (k ^ p) r ∧ Real.log r / p < s := by + have hlog {i : ℕ} (hi : 0 < i) : 0 ≤ Real.log (i : ℝ) := + Real.log_nonneg (by exact_mod_cast hi) + obtain ⟨t, ht, ht'⟩ := exists_between h + obtain ⟨n, r, hn, hr, hrs⟩ := (exponent_lt_iff_rank (hlog hi) (hlog hj) (hlog hk)).mp ht + have hn₀ : 0 < n := by omega + have hr₀ : 0 < r := (Nat.mul_pos (side_pos hn₀ _) (side_pos hn₀ _)).trans_le + (hr.area (side_pos hn₀ _)) + have hnlog : 0 < Real.log (n : ℝ) := Real.log_pos (by exact_mod_cast hn) + have hprice : Real.log r < t * Real.log n := by + simpa only [Real.log_rpow (by positivity : 0 < (n : ℝ))] using + Real.log_lt_log (by positivity) hrs + have ht₀ : 0 < t := pos_of_mul_pos_left ((hlog hr₀).trans_lt hprice) hnlog.le + obtain ⟨p, hp⟩ := exists_nat_gt (t * Real.log n / (s - t)) + have hp' : 0 < (p : ℝ) := (by positivity : 0 < t * Real.log n / (s - t)).trans hp + let q := ⌈(p : ℝ) / Real.log n⌉₊ + have hlo : (p : ℝ) ≤ q * Real.log n := (div_le_iff₀ hnlog).mp (Nat.le_ceil _) + have hhi : (q : ℝ) * Real.log n < p + Real.log n := by + apply (lt_div_iff₀ hnlog).mp + rw [add_div, div_self hnlog.ne'] + exact Nat.ceil_lt_add_one (by positivity) + refine ⟨p, r ^ q, by exact_mod_cast hp', (hr.pow q).cut (pad_fixed hn hi hlo) + (pad_fixed hn hj hlo) (pad_fixed hn hk hlo), ?_⟩ + rw [Nat.cast_pow, Real.log_pow, div_lt_iff₀ hp'] + linarith only [(div_lt_iff₀ (sub_pos.mpr ht')).mp hp, + mul_lt_mul_of_pos_left hhi ht₀, mul_le_mul_of_nonneg_left hprice.le (Nat.cast_nonneg q)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Exact rank surplus at the harmonic threshold + +The field and the full-support coefficients may change at every size. +The lower limit statement uses eventual inequalities against every +strictly smaller real constant, so also covers infinite lower limits. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +theorem density_bound (F : Type*) [Field F] : DensityBound F := + density_of_closed (fun K _ _ => (closed_fulfills K).density) F + +variable {F : Type*} [Field F] {i j k r : ℕ} {w : Fin i → Fin j → Fin k → F} + +theorem full_size (hw : ∀ a b c, w a b c ≠ 0) : supportSize w = i * j * k := by + simp [supportSize, hw, mul_comm, mul_left_comm] + +theorem WeightedRankLE.full (h : WeightedRankLE w r) (hw : ∀ a b c, w a b c ≠ 0) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + Real.exp (exponent F (Real.log i) (Real.log j) (Real.log k)) ≤ r := by + have he := density_bound F i j k r hi hj hk w h + rw [full_size hw, Nat.cast_mul, Nat.cast_mul] at he + exact le_of_mul_le_mul_left he (by positivity) + +theorem WeightedRankLE.surplus (h : WeightedRankLE w r) (hw : ∀ a b c, w a b c ≠ 0) + {a b : ℕ} (ha : 0 < a) (hb : 0 < b) (hk : 0 < k) (hi : a ≤ i) (hj : b ≤ j) : + Real.exp (exponent F (Real.log a) (Real.log b) (Real.log k)) - (a : ℝ) * b ≤ + (r : ℝ) - (i : ℝ) * j := by + obtain ⟨harea, hcut⟩ := h.delete hw hk hi hj + have he := hcut.full (fun _ _ _ => hw _ _ _) ha hb hk + rw [Nat.cast_sub ((Nat.sub_le _ _).trans harea), Nat.cast_sub (Nat.mul_le_mul hi hj), + Nat.cast_mul, Nat.cast_mul] at he + linarith + +private theorem exact_shift {K : ℕ → Type*} [∀ n, Field (K n)] {x y : ℝ} + (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hrig : ∀ n, Rigidity (K n)) (hsq : ∀ n, MatrixExponent.omega (K n) = 9 / 4) + {b : ℝ} {a : ℕ → ℕ} (ha : ∀ n, 0 < n → 0 < a n) + (hlog : Tendsto (fun n => Real.log (a n) - x * y * Real.log n) atTop (nhds (b * (x * y)))) + (w : ∀ n, Fin (side n x) → Fin (side n y) → Fin (a n) → K n) + (hw : ∀ n a b c, w n a b c ≠ 0) (r : ℕ → ℕ) (hr : ∀ n, WeightedRankLE (w n) (r n)) + {L : ℝ} (hL : L < Threshold.optimum b (max (x / y) (y / x))) : + ∀ᶠ n in atTop, L < normalized x y r n := by + have hl (s t : ℝ) (hs : 0 ≤ s) (ht : 0 ≤ t) + (h : L < Real.exp (-s - t) * (max (b + (y / x) * s + (x / y) * t) 0) ^ 2 / 4) : + ∀ᶠ n in atTop, L < normalized x y r n := by + filter_upwards [eventually_gt_atTop 0, (trimmed_shifted_surplus_limit hx hy hxy hlog s + t).eventually + (lt_mem_nhds h)] with n hn hn' + have hi := trimmed_pos hn x s + have hj := trimmed_pos hn y t + have hk := ha n hn + have hd := (hr n).surplus (hw n) hi hj hk (trimmed_le n x hs) (trimmed_le n y ht) + have hlog {i : ℕ} (h : 0 < i) : 0 ≤ Real.log (i : ℝ) := + Real.log_nonneg (by exact_mod_cast h) + rw [all_shapes (hrig n) (hsq n) (hlog hi) (hlog hj) (hlog hk)] at hd + have hA : 1 ≤ (side n x : ℝ) * side n y := by + exact_mod_cast Nat.mul_pos (side_pos hn x) (side_pos hn y) + exact hn'.trans_le (div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_right hd + (Real.log_nonneg hA)) (by positivity)) + let C := max (x / y) (y / x) + have hC : 0 < C := by unfold C; positivity + obtain ⟨u, hu, he⟩ := (Threshold.maximum b hC).2.1 + have hbound : L < Threshold.gain b C u := he.symm ▸ hL + unfold Threshold.gain C at hbound + rcases le_total (x / y) (y / x) with h | h + · apply hl u 0 hu le_rfl + simpa [max_eq_right h] using hbound + · apply hl 0 u le_rfl hu + simpa [max_eq_left h] using hbound + +theorem scaled_exact_surplus {K : ℕ → Type*} [∀ n, Field (K n)] {x y a : ℝ} + (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) (ha : 0 < a) + (hrig : ∀ n, Rigidity (K n)) (hsq : ∀ n, MatrixExponent.omega (K n) = 9 / 4) + (w : ∀ n, Fin (side n x) → Fin (side n y) → Fin (Threshold.width n x y a) → K n) + (hw : ∀ n a b c, w n a b c ≠ 0) (r : ℕ → ℕ) (hr : ∀ n, WeightedRankLE (w n) (r n)) + {L : ℝ} (hL : L < Threshold.optimum (Real.log a / (x * y)) (max (x / y) (y / x))) : + ∀ᶠ n in atTop, L < normalized x y r n := by + apply exact_shift hx hy hxy hrig hsq _ (Threshold.log_width hx hy ha) w hw r hr hL + intro n hn + exact Nat.ceil_pos.mpr (by positivity) + +/-- The exact-rank half of the harmonic threshold corollary. -/ +theorem exact_surplus {K : ℕ → Type*} [∀ n, Field (K n)] {x y : ℝ} + (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hrig : ∀ n, Rigidity (K n)) (hsq : ∀ n, MatrixExponent.omega (K n) = 9 / 4) + (w : ∀ n, Fin (side n x) → Fin (side n y) → Fin (side n (x * y)) → K n) + (hw : ∀ n a b c, w n a b c ≠ 0) (r : ℕ → ℕ) (hr : ∀ n, WeightedRankLE (w n) (r n)) + {L : ℝ} (hL : L < Real.exp (-2) * max ((x / y) ^ 2) ((y / x) ^ 2)) : + ∀ᶠ n in atTop, L < normalized x y r n := by + refine exact_shift hx hy hxy hrig hsq (b := 0) (fun n hn => side_pos hn (x * y)) + (by simpa using log_side (mul_pos hx hy)) w hw r hr ?_ + rw [Threshold.optimum, ite_eq_left (by positivity), zero_div, zero_sub, mul_comm] + rcases le_total (x / y) (y / x) with h | h + · simpa only [max_eq_right h, max_eq_right (pow_le_pow_left₀ (by positivity) h 2)] using hL + · simpa only [max_eq_left h, max_eq_left (pow_le_pow_left₀ (by positivity) h 2)] using hL + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- # Homogeneity for the actual arithmetic exponent -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +theorem homogeneous (F : Type*) [Field F] {a b c s : ℝ} + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) (hs : 0 ≤ s) : + exponent F (s * a) (s * b) (s * c) = s * exponent F a b c := by + obtain ⟨K, _, ⟨alg⟩⟩ := small_field F + have ha' := mul_nonneg hs ha + have hb' := mul_nonneg hs hb + have hc' := mul_nonneg hs hc + rw [exponent_extension K F ha hb hc, exponent_extension K F ha' hb' hc'] + have he (x y z : ℝ) : load (s * a) (s * b) (s * c) x y z = s * load a b c x y z := by + unfold load + ring + have hp := support K + apply le_antisymm + · obtain ⟨x, y, z, h, heq⟩ := hp.attains ha' hb' hc' + rw [← heq, he] + exact mul_le_mul_of_nonneg_left (hp.bound ha hb hc h) hs + · obtain ⟨x, y, z, h, heq⟩ := hp.attains ha hb hc + rw [← heq, ← he] + exact hp.bound ha' hb' hc' h + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# Minimum asymptotic rank over coefficients + +The powers have separate row, column and inner indices for every copy. +The density bound holds on every power. Fekete's lemma supplies the +limit, and padding a strict rank witness gives the opposite inequality +for the all-ones weighting. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter +open scoped Topology + +variable {F : Type*} [Field F] {i j k : ℕ} + +theorem rank_rate {r : ℕ → ℕ} (hr : ∀ n, 0 < r n) + (hadd : ∀ n m, r (n + m) ≤ r n * r m) : + ∃ L : ℝ, Tendsto (fun n : ℕ => (r n : ℝ) ^ (n : ℝ)⁻¹) atTop (𝓝 L) ∧ + ∀ n : ℕ, 0 < n → L ≤ Real.exp (Real.log (r n) / n) := by + have hp (n) : 0 < (r n : ℝ) := Nat.cast_pos.mpr (hr n) + let u n := Real.log (r n : ℝ) + have hs : Subadditive u := by + intro n m + unfold u + rw [← Real.log_mul (hp n).ne' (hp m).ne'] + exact Real.log_le_log (hp _) (by exact_mod_cast hadd n m) + have hb : BddBelow (Set.range fun n => u n / n) := by + refine ⟨0, ?_⟩ + rintro _ ⟨n, rfl⟩ + exact div_nonneg (Real.log_nonneg (by exact_mod_cast hr n)) (by positivity) + refine ⟨Real.exp hs.lim, ?_, fun n hn => Real.exp_le_exp.mpr (hs.lim_le_div hb hn.ne')⟩ + simpa only [u, Real.rpow_def_of_pos (hp _), div_eq_mul_inv] using (hs.tendsto_lim hb).rexp + +variable {w : Fin i → Fin j → Fin k → F} + +private theorem full_density (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) + (hw : ∀ a b c, w a b c ≠ 0) : density w = 1 := by + rw [density, full_size hw, Nat.cast_mul, Nat.cast_mul, div_self (by positivity)] + +/-- There is no loss in the density estimate for a power other than +raising the density itself to that power. -/ +theorem density_power_lower (w : Fin i → Fin j → Fin k → F) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) (n : ℕ) : + (density w * Real.exp (exponent F (Real.log i) (Real.log j) (Real.log k))) ^ n ≤ + rankW (WPower w n) := by + have hd := density_bound F _ _ _ _ (pow_pos hi n) (pow_pos hj n) (pow_pos hk n) _ + (rankW_spec (WPower w n)) + have hlog {i : ℕ} (hi : 0 < i) : 0 ≤ Real.log (i : ℝ) := + Real.log_nonneg (by exact_mod_cast hi) + rw [supportSize_power] at hd + simp only [Nat.cast_pow, Real.log_pow] at hd + rw [homogeneous F (hlog hi) (hlog hj) (hlog hk) (Nat.cast_nonneg _), Real.exp_nat_mul] at hd + rw [density, mul_pow, div_pow, div_mul_eq_mul_div, div_le_iff₀ (by positivity), + mul_pow, mul_pow, mul_comm (rankW _ : ℝ)] + exact hd + +private theorem rate_spec (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) (hw : 0 < density w) : + Tendsto (fun n : ℕ => (rankW (WPower w n) : ℝ) ^ (n : ℝ)⁻¹) atTop (𝓝 (asymptoticRank w)) ∧ + ∀ n : ℕ, 0 < n → asymptoticRank w ≤ Real.exp (Real.log (rankW (WPower w n)) / n) := by + have hp (n : ℕ) : 0 < rankW (WPower w n) := + Nat.cast_pos.mp (lt_of_lt_of_le (by positivity) (density_power_lower w hi hj hk n)) + obtain ⟨L, hl, hb⟩ := rank_rate hp (rankW_add w) + rw [asymptoticRank, hl.limUnder_eq] + exact ⟨hl, hb⟩ + +theorem tendsto_asymptoticRank (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) (hw : 0 < density w) : + Tendsto (fun n : ℕ => (rankW (WPower w n) : ℝ) ^ (n : ℝ)⁻¹) atTop (𝓝 (asymptoticRank w)) := + (rate_spec hi hj hk hw).1 + +private theorem zero_limit (hs : supportSize w = 0) : + Tendsto (fun n : ℕ => (rankW (WPower w n) : ℝ) ^ (n : ℝ)⁻¹) atTop (nhds 0) := by + classical + have hw : ∀ b a c, w a b c = 0 := by + simpa [supportSize, Finset.sum_eq_zero_iff] using hs + refine tendsto_const_nhds.congr' ?_ + filter_upwards [eventually_gt_atTop 0] with n hn + have h : WeightedRankLE (WPower w n) 0 := by + refine ⟨0, 0, 0, fun x y z => ?_⟩ + simp [WPower, hw, hn.ne'] + rw [Nat.eq_zero_of_le_zero (rankW_le h), Nat.cast_zero, Real.zero_rpow (by positivity)] + +theorem asymptotic_zero (hs : supportSize w = 0) : asymptoticRank w = 0 := + (zero_limit hs).limUnder_eq + +theorem asymptotic_converges (w : Fin i → Fin j → Fin k → F) (hi : 0 < i) (hj : 0 < j) (hk : 0 + < k) : + Tendsto (fun n : ℕ => (rankW (WPower w n) : ℝ) ^ (n : ℝ)⁻¹) atTop (nhds (asymptoticRank w)) + := by + rcases (supportSize w).eq_zero_or_pos with h | h + · rw [asymptotic_zero h] + exact zero_limit h + exact tendsto_asymptoticRank hi hj hk (by unfold density; positivity) + +theorem asymptotic_density (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) (hw : 0 < density w) : + density w * Real.exp (exponent F (Real.log i) (Real.log j) (Real.log k)) ≤ asymptoticRank w + := by + apply ge_of_tendsto (tendsto_asymptoticRank hi hj hk hw) + filter_upwards [eventually_gt_atTop 0] with n hn + have h := Real.rpow_le_rpow (by positivity) (density_power_lower w hi hj hk n) + (by positivity : 0 ≤ (n : ℝ)⁻¹) + rwa [Real.pow_rpow_inv_natCast (by positivity) hn.ne'] at h + +theorem asymptotic_le_power (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) (hw : 0 < density w) + {n : ℕ} (hn : 0 < n) : asymptoticRank w ^ n ≤ (rankW (WPower w n) : ℝ) := by + have h := (rate_spec hi hj hk hw).2 n hn + have hp : 0 < (rankW (WPower w n) : ℝ) := + lt_of_lt_of_le (by positivity) (density_power_lower w hi hj hk n) + have hpos : 0 < asymptoticRank w := lt_of_lt_of_le (by positivity) (asymptotic_density hi hj hk + hw) + rw [div_eq_mul_inv, ← Real.rpow_def_of_pos hp] at h + have hh := pow_le_pow_left₀ hpos.le h n + rwa [Real.rpow_inv_natCast_pow hp.le hn.ne'] at hh + +theorem ordinary_rank (F : Type*) [Field F] (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + asymptoticRank (ordinary F i j k) = + Real.exp (exponent F (Real.log i) (Real.log j) (Real.log k)) := by + let w := ordinary F i j k + have hd : density w = 1 := full_density hi hj hk (fun _ _ _ => one_ne_zero) + have hw : 0 < density w := hd.symm ▸ zero_lt_one + have hlo := asymptotic_density hi hj hk hw + rw [hd, one_mul] at hlo + refine le_antisymm ?_ hlo + by_contra! hlt + have hpos : 0 < asymptoticRank w := (Real.exp_pos _).trans_le hlo + obtain ⟨n, r, hn, hr, he⟩ := fixed_rank hi hj hk ((Real.lt_log_iff_exp_lt hpos).mpr hlt) + have hR : rankW (WPower w n) ≤ r := by + apply rankW_le + rw [show WPower w n = (fun _ _ _ => 1) from WPower_one n] + exact hr + have hp : 0 < (rankW (WPower w n) : ℝ) := + lt_of_lt_of_le (by positivity) (density_power_lower w hi hj hk n) + have hh := (rate_spec hi hj hk hw).2 n hn + apply (lt_irrefl (asymptoticRank w)) + calc + _ ≤ Real.exp (Real.log (rankW (WPower w n)) / n) := hh + _ ≤ Real.exp (Real.log r / n) := by gcongr + _ < _ := (Real.lt_log_iff_exp_lt hpos).mp he + +/-- At every fixed positive format, the ordinary product attains the +minimum over all full-support weightings. -/ +theorem minimum_rank (F : Type*) [Field F] (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + IsLeast {s | ∃ w : Fin i → Fin j → Fin k → F, + (∀ a b c, w a b c ≠ 0) ∧ asymptoticRank w = s} + (Real.exp (exponent F (Real.log i) (Real.log j) (Real.log k))) := by + refine ⟨⟨ordinary F i j k, fun _ _ _ => one_ne_zero, ordinary_rank F hi hj hk⟩, ?_⟩ + rintro _ ⟨w, hw, rfl⟩ + have hd := full_density hi hj hk hw + have h := asymptotic_density (w := w) hi hj hk (hd.symm ▸ zero_lt_one) + rwa [hd, one_mul] at h + +/-- The ordinary multiplication tensor has minimum asymptotic rank among full-support weights. -/ +theorem minimum_eq_benchmark (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + asymptoticRank (ordinary F i j k) = Real.exp (U (Real.log i) (Real.log j) (Real.log k)) ∧ + IsLeast {s | ∃ w : Fin i → Fin j → Fin k → F, + (∀ a b c, w a b c ≠ 0) ∧ asymptoticRank w = s} + (Real.exp (U (Real.log i) (Real.log j) (Real.log k))) := by + rw [← all_shapes hr hs (Real.log_nonneg (by exact_mod_cast hi)) + (Real.log_nonneg (by exact_mod_cast hj)) (Real.log_nonneg (by exact_mod_cast hk))] + exact ⟨ordinary_rank F hi hj hk, minimum_rank F hi hj hk⟩ + +theorem ordinary_square (F : Type*) [Field F] (hi : 0 < i) : + asymptoticRank (ordinary F i i i) = (i : ℝ) ^ MatrixExponent.omega F := by + have h := homogeneous F zero_le_one zero_le_one zero_le_one + (Real.log_nonneg (by exact_mod_cast hi : 1 ≤ (i : ℝ))) + rw [mul_one, square] at h + rw [ordinary_rank F hi hi hi, h, Real.rpow_def_of_pos (by positivity)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# Asymptotic rank under extension of the coefficient field + +Specialization fixes the weighting in the base field. The finite +extension may depend on the chosen power, so we take further powers +*after* specialization to pay its degree cost only once. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +variable {F K : Type*} [Field F] [Field K] [Algebra F K] + {i j k r n : ℕ} {w : Fin i → Fin j → Fin k → F} + +/-- Computes the extend by the application `algebraMap F K (w x y z)`. -/ +def extend (K : Type*) [Field K] [Algebra F K] (w : Fin i → Fin j → Fin k → F) + (x : Fin i) (y : Fin j) (z : Fin k) := algebraMap F K (w x y z) + +theorem WPower_extend (w : Fin i → Fin j → Fin k → F) (n : ℕ) : + WPower (extend K w) n = extend K (WPower w n) := by + funext x y z + simp only [WPower, extend, map_prod] + +theorem density_extend (w : Fin i → Fin j → Fin k → F) : density (extend K w) = density w := by + unfold density extend + rw [supportSize_map] + +theorem extension_lower (h : WeightedRankLE (WPower (extend K w) n) r) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) (hw : 0 < density w) (hn : 0 < n) : + asymptoticRank w ^ n ≤ r := by + rw [WPower_extend] at h + obtain ⟨L, _, _, _, hL⟩ := finiteTypeWeighted (algebraMap F K) (WPower w n) h + have : Module.Finite F L := finite_of_finite_type_of_isJacobsonRing F L + change WeightedRankLE (extend L (WPower w n)) r at hL + rw [← WPower_extend] at hL + let D := Module.finrank F L ^ 2 + have hp : 0 < asymptoticRank w := lt_of_lt_of_le (by positivity) (asymptotic_density hi hj hk hw) + apply TensorSpectrum.le_of_pow_le_polynomial_mul_pow _ _ (D + 1) 0 + (by positivity) (by positivity) + intro m hm + let t := rankW (WPower (extend L w) (n * m)) + have ht : t ≤ r ^ m := (rankW_mul (extend L w) n m hm).trans (Nat.pow_le_pow_left (rankW_le hL) _) + have ht' : WeightedRankLE (extend L (WPower w (n * m))) t := by + rw [← WPower_extend] + exact rankW_spec _ + have hd := rankW_le (descendWeighted (F := F) ht') + rw [← pow_mul, Real.rpow_zero, mul_one] + calc + _ ≤ (rankW (WPower w (n * m)) : ℝ) := asymptotic_le_power hi hj hk hw (Nat.mul_pos hn hm) + _ ≤ (t : ℝ) * D := by exact_mod_cast hd + _ ≤ (r : ℝ) ^ m * (D + 1) := by + gcongr + · exact_mod_cast ht + · linarith + _ = _ := mul_comm _ _ + +theorem asymptotic_extension (K : Type*) [Field K] [Algebra F K] + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + asymptoticRank (extend K w) = asymptoticRank w := by + rcases (supportSize w).eq_zero_or_pos with h | h + · have he : supportSize (extend K w) = 0 := (supportSize_map _ _).trans h + rw [asymptotic_zero he, asymptotic_zero h] + have hw : 0 < density w := by unfold density; positivity + have h := tendsto_asymptoticRank hi hj hk hw + have hw' : 0 < density (extend K w) := by rwa [density_extend] + have h' := tendsto_asymptoticRank hi hj hk hw' + apply le_antisymm + · apply le_of_tendsto_of_tendsto h' h + filter_upwards [] with n + apply Real.rpow_le_rpow (by positivity) _ (by positivity) + rw [WPower_extend] + exact_mod_cast rankW_le ((rankW_spec (WPower w n)).map (algebraMap F K)) + · have hp : 0 < asymptoticRank w := lt_of_lt_of_le (by positivity) (asymptotic_density hi hj hk + hw) + apply ge_of_tendsto h' + filter_upwards [eventually_gt_atTop 0] with n hn + rw [← Real.pow_rpow_inv_natCast hp.le hn.ne'] + exact Real.rpow_le_rpow (by positivity) + (extension_lower (rankW_spec (WPower (extend K w) n)) hi hj hk hw hn) (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- # Large low-rank rectangles from a strict dual saving -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +theorem rank_of_dual {F : Type*} [Field F] (h : 1 / 2 < dual F 1 1) : + ∃ ε : ℝ, 0 < ε ∧ ∀ δ : ℝ, 0 < δ → ∀ n : ℕ, ∃ s j r : ℕ, n ≤ s ∧ + (s : ℝ) ^ (1 / 2 + ε) ≤ j ∧ (r : ℝ) ≤ (s : ℝ) ^ (2 + δ) ∧ RankLE F s s j r := by + have hz := coordinate_plane F zero_le_one zero_le_one (le_rfl : (0 : ℝ) ≤ 0) + (Or.inr (Or.inr rfl)) + obtain ⟨c, ⟨⟨hc, _⟩, he⟩, hlt⟩ := exists_lt_of_lt_csSup + (show {c ∈ Set.Icc 0 (min 1 1) | exponent F 1 1 c = 1 + 1}.Nonempty from + ⟨0, by simp [hz]⟩) h + refine ⟨c - 1 / 2, by linarith, ?_⟩ + intro δ hδ n + obtain ⟨m, r, hm, hr, hrs⟩ := (exponent_lt_iff_rank zero_le_one zero_le_one hc).mp + (show exponent F 1 1 c < 2 + δ by linarith) + rw [side_one] at hr + refine ⟨m ^ n, (side m c) ^ n, r ^ n, (Nat.lt_pow_self (by omega : 1 < m)).le, ?_, ?_, hr.pow n⟩ + · rw [show 1 / 2 + (c - 1 / 2) = c by ring] + exact Nat.ceil_le.mp (side_pow (le_rfl : side m c ≤ _) n) + · rw [Nat.cast_pow, Nat.cast_pow, ← Real.rpow_natCast_mul (by positivity), + mul_comm (n : ℝ), Real.rpow_mul_natCast (by positivity)] + exact pow_le_pow_left₀ (by positivity) hrs.le _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Face/Contact.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Face/Contact.lean new file mode 100644 index 0000000000..4fff17ba18 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Face/Contact.lean @@ -0,0 +1,862 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Support +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.UpperBound +public import Mathlib.Analysis.Convex.Continuous +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Minimum.FaceZero +public import Mathlib.Topology.Order.Monotone + +/-! +# The diagonal inequality from integer rectangular bounds + +The homogeneous quadratic inequalities extend from positive integer +weights to positive real weights by a common rescaling and a limit. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +variable {F : Type} [Field F] {x y z a b c : ℝ} + +private theorem real_weights (h : DiscreteBound F) (hp : Prices F x y z) + (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : + 4 * ((x + y) * a * b + (x + z) * a * c + (y + z) * b * c) ≤ (a + b + c) ^ 2 := by + have ha' := tendsto_nat_ceil_mul_div_atTop ha.le + have hb' := tendsto_nat_ceil_mul_div_atTop hb.le + have hc' := tendsto_nat_ceil_mul_div_atTop hc.le + have h₁ := (ha'.const_mul (x + y)).mul hb' + have h₂ := (ha'.const_mul (x + z)).mul hc' + have h₃ := (hb'.const_mul (y + z)).mul hc' + apply le_of_tendsto_of_tendsto (((h₁.add h₂).add h₃).const_mul 4) (((ha'.add hb').add hc').pow 2) + filter_upwards [eventually_gt_atTop (0 : ℝ)] with t ht + have hd := h ⌈a * t⌉₊ ⌈b * t⌉₊ ⌈c * t⌉₊ (by positivity) (by positivity) (by positivity) + have hl := ((support F).bound (by positivity) (by positivity) (by positivity) hp).trans hd + unfold load at hl + generalize ⌈a * t⌉₊ = A, ⌈b * t⌉₊ = B, ⌈c * t⌉₊ = C at hl ⊢ + field_simp + linarith only [hl] + +theorem diagonal_of_discrete (h : DiscreteBound F) : DiagonalBound (Prices F) := by + intro x y z hp + obtain ⟨hx, hy, hz⟩ := hp.nonneg + by_cases hb : x = 0 ∨ y = 0 ∨ z = 0 + · obtain ⟨f, hf, hxy, hxz, hyz⟩ := hp + rcases hb with rfl | rfl | rfl + · simpa [dStar, hyz] using (dist_bounds hf 1 2).2 + · simpa [dStar, hxz] using (dist_bounds hf 0 2).2 + · simpa [dStar, hxy] using (dist_bounds hf 0 1).2 + push Not at hb + have hx' := hx.lt_of_ne' hb.1 + have hy' := hy.lt_of_ne' hb.2.1 + have hz' := hz.lt_of_ne' hb.2.2 + have hd := real_weights h hp (by positivity : 0 < x * (y + z)) + (by positivity : 0 < y * (x + z)) (by positivity : 0 < z * (x + y)) + let p := x * y + y * z + z * x + have hpos : 0 < p := by unfold p; positivity + have he : (x + y) * (x + z) * (y + z) ≤ p := by + apply le_of_mul_le_mul_right _ hpos + unfold p + linarith only [hd] + unfold dStar + rw [sub_le_iff_le_add, ← sub_le_iff_le_add', le_div_iff₀ hpos] + unfold p at he + linarith only [he] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- # The unique contact price at the square -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +private theorem symmetric_maximizer {x y z : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) + (h : load 1 1 1 x y z = 9 / 4) (hD : dStar x y z ≤ 1) : + x = 3 / 8 ∧ y = 3 / 8 ∧ z = 3 / 8 := by + have hsum : x + y + z = 9 / 8 := by unfold load at h; linarith + have hH : 1 / 8 ≤ x * y * z / (x * y + y * z + z * x) := by + unfold dStar at hD + linarith + have hx' : 0 < x := hx.lt_of_ne (by rintro rfl; norm_num at hH) + have hy' : 0 < y := hy.lt_of_ne (by rintro rfl; norm_num at hH) + have hz' : 0 < z := hz.lt_of_ne (by rintro rfl; norm_num at hH) + rw [le_div_iff₀ (by positivity)] at hH + have he : z * (x - y) ^ 2 + y * (x - z) ^ 2 + x * (y - z) ^ 2 ≤ 0 := by + calc + _ = (x + y + z) * (x * y + y * z + z * x) - 9 * x * y * z := by ring + _ ≤ 0 := by rw [hsum]; linarith + have h₁ : 0 ≤ z * (x - y) ^ 2 := by positivity + have h₂ : 0 ≤ y * (x - z) ^ 2 := by positivity + have h₃ : 0 ≤ x * (y - z) ^ 2 := by positivity + have hxy : x = y := + sub_eq_zero.mp (sq_eq_zero_iff.mp ((mul_eq_zero.mp (le_antisymm (by linarith) h₁)).resolve_left + hz'.ne')) + have hxz : x = z := + sub_eq_zero.mp (sq_eq_zero_iff.mp ((mul_eq_zero.mp (le_antisymm (by linarith) h₂)).resolve_left + hy'.ne')) + exact ⟨by linarith, by linarith, by linarith⟩ + +theorem diagonal (F : Type) [Field F] : DiagonalBound (Prices F) := + diagonal_of_discrete (discrete_bound F) + +theorem square_iff_contact (F : Type) [Field F] : + MatrixExponent.omega F = 9 / 4 ↔ Prices F (3 / 8) (3 / 8) (3 / 8) := by + have hD := diagonal F + have h := support F + rw [← square] + constructor + · intro hω + obtain ⟨x, y, z, hp, he⟩ := h.attains zero_le_one zero_le_one zero_le_one + obtain ⟨hx, hy, hz⟩ := hp.nonneg + obtain ⟨rfl, rfl, rfl⟩ := symmetric_maximizer hx hy hz (he.trans hω) (hD _ _ _ hp) + exact hp + · intro hp + have hl := h.bound zero_le_one zero_le_one zero_le_one hp + have hu := upper_of_diagonal h hD zero_lt_one zero_lt_one zero_lt_one + norm_num [U, benchmark] at hu + norm_num [load] at hl + exact le_antisymm hu hl + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# Positive spectral contact on a homogeneous tripod + +Lengths on the three arms determine three wire distances. The common-label +rate is homogeneous and convex along each arm, with transport cost at +most one per unit distance. In reciprocal coordinates its excess over +the harmonic benchmark satisfies the regularity hypotheses of the +strong minimum principle. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Minimum Set + +/-- The properties of common-label rates on a homogeneous spectral tripod +used for propagation. -/ +structure Tripod (F : Type) [Field F] (D : Vec → ℝ) : Prop where + pos : ∀ a, Positive a → 0 < D a + prices : ∀ a, Positive a → Prices F (a 0 / D a) (a 1 / D a) (a 2 / D a) + scale : ∀ a, Positive a → ∀ s : ℝ, 0 < s → D (s • a) = s * D a + convex : ∀ a, Positive a → ∀ i, ConvexOn ℝ (Ioi 0) (fun t => D (Function.update a i t)) + transport : ∀ a, Positive a → ∀ i, MonotoneOn (fun t => D (Function.update a i t) + t) (Ioi 0) + +/-- The quantity computed by `D v⁻¹ - ∑ i, (v i)⁻¹ + (∑ i, v i)⁻¹`. -/ +def defect (D : Vec → ℝ) (v : Vec) : ℝ := + D v⁻¹ - ∑ i, (v i)⁻¹ + (∑ i, v i)⁻¹ + +variable {F : Type} [Field F] {D : Vec → ℝ} {v a : Vec} + +private theorem inv_positive (hv : Positive v) : Positive v⁻¹ := fun i => inv_pos.mpr (hv i) + +private theorem total_pos (hv : Positive v) : 0 < ∑ i, v i := + Finset.sum_pos (fun i _ => hv i) Finset.univ_nonempty + +theorem defect_inv (D : Vec → ℝ) (ha : Positive a) : + defect D a⁻¹ = D a - dStar (a 0) (a 1) (a 2) := by + have hx := ha 0 + have hy := ha 1 + have hz := ha 2 + simp only [defect, dStar, Fin.sum_univ_three, Pi.inv_apply, inv_inv] + field_simp + ring + +private theorem Tripod.lower (h : Tripod F D) (ha : Positive a) : + dStar (a 0) (a 1) (a 2) ≤ D a := by + have hD := h.pos _ ha + have hx := ha 0 + have hy := ha 1 + have hz := ha 2 + have he : dStar (a 0 / D a) (a 1 / D a) (a 2 / D a) = + dStar (a 0) (a 1) (a 2) / D a := by + unfold dStar + field_simp + have hd := diagonal F _ _ _ (h.prices _ ha) + rwa [he, div_le_one hD] at hd + +private theorem Tripod.defect_scale (h : Tripod F D) (hv : Positive v) {s : ℝ} (hs : 0 < s) : + defect D (s • v) = defect D v / s := by + have he : (s • v)⁻¹ = s⁻¹ • v⁻¹ := by ext; simp [mul_comm] + rw [defect, he, h.scale _ (inv_positive hv) _ (inv_pos.mpr hs), defect] + simp only [Pi.smul_apply, smul_eq_mul, mul_inv_rev, ← Finset.sum_mul, ← Finset.mul_sum] + ring + +theorem ray_defect (D : Vec → ℝ) (v : Vec) (i : Fin 3) : + ray (defect D) v i = fun t => + D (Function.update v⁻¹ i (1 / (v i + t))) - 1 / (v i + t) + 1 / ((∑ j, v j) + t) - + ∑ j ∈ Finset.univ.erase i, (v j)⁻¹ := by + funext t + have he : (move v i t)⁻¹ = Function.update v⁻¹ i (1 / (v i + t)) := by + ext j + by_cases h : j = i <;> simp [move, h] + have hs (f : ℝ → ℝ) : ∑ j, f (move v i t j) = f (v i + t) + ∑ j ∈ Finset.univ.erase i, f (v j) + := by + rw [← Finset.add_sum_erase _ _ (Finset.mem_univ i)] + simp only [move, Function.update_self] + congr 1 + apply Finset.sum_congr rfl + intro j hj + rw [Function.update_of_ne (Finset.mem_erase.mp hj).1] + have ht : (∑ j, move v i t j) = (∑ j, v j) + t := by + have := hs (fun x => x) + rw [← Finset.add_sum_erase _ v (Finset.mem_univ i)] + linarith + rw [ray, defect, he, ht, hs (fun x => x⁻¹)] + ring + +theorem Tripod.regular (h : Tripod F D) : Regular (defect D) := by + refine ⟨?_, fun v hv s hs => h.defect_scale hv hs, ?_, ?_⟩ + · intro v hv + have hi := inv_positive hv + have he := defect_inv D hi + rw [inv_inv] at he + rw [he] + exact sub_nonneg.mpr (h.lower hi) + · intro v hv i + rw [ray_defect] + have hf := (h.convex _ (inv_positive hv) i).continuousOn isOpen_Ioi + have hinv {a : ℝ} (ha : 0 < a) : ContinuousOn (fun t : ℝ => 1 / (a + t)) (Ici 0) := + continuousOn_const.div (continuousOn_const.add continuousOn_id) + (fun _ ht => (add_pos_of_pos_of_nonneg ha ht).ne') + exact (((hf.comp (hinv (hv i)) (fun t ht => one_div_pos.mpr + (add_pos_of_pos_of_nonneg (hv i) ht))).sub (hinv (hv i))).add + (hinv (total_pos hv))).sub continuousOn_const + · intro v hv + let C := ∑ i, 2 / (v i) ^ 3 + have hn (i) : 0 ≤ 2 / (v i) ^ 3 := div_nonneg (by norm_num) (pow_nonneg (hv i).le _) + refine ⟨C, Finset.sum_nonneg fun i _ => hn i, ?_⟩ + intro w hw i + have hw' : Positive w := fun j => (hv j).trans_le (hw.1 j) + have hC : 2 / (w i) ^ 3 ≤ C := calc + _ ≤ 2 / (v i) ^ 3 := by have := hv i; gcongr; exact hw.1 i + _ ≤ _ := Finset.single_le_sum (fun j _ => hn j) (Finset.mem_univ i) + rw [ray_defect] + exact reciprocal_semiconvex (h.convex _ (inv_positive hw') i) + (h.transport _ (inv_positive hw') i) (hw' i) (total_pos hw') hC + +/-- At one contact there is no defect. The directional comparison then +forces the full positive polar boundary into the spectrum. -/ +theorem Tripod.boundary (h : Tripod F D) (hc : Comparison (defect D)) + (ha : Positive a) (he : D a = dStar (a 0) (a 1) (a 2)) (x y z : ℝ) + (hx : 0 < x) (hy : 0 < y) (hz : 0 < z) : + Prices F (x / dStar x y z) (y / dStar x y z) (z / dStar x y z) := by + let b : Vec := ![x, y, z] + have hb : Positive b := by intro i; fin_cases i <;> assumption + have hh := vanishes h.regular hc (inv_positive ha) (by rw [defect_inv D ha, he, sub_self]) + (inv_positive hb) + rw [defect_inv D hb, sub_eq_zero] at hh + have hp := h.prices _ hb + rw [hh] at hp + exact hp + +/-- It is enough to realize the initial contact in one tripod where +the directional identity holds locally. -/ +theorem propagation_of_tripod + (h : ∀ x y z, 0 < x → 0 < y → 0 < z → Prices F x y z → dStar x y z = 1 → + ∃ D, Tripod F D ∧ D ![x, y, z] = 1 ∧ Comparison (defect D)) : + Propagation (Prices F) := by + rintro ⟨x, y, z, hx, hy, hz, hp, he⟩ + obtain ⟨D, hD, h₁, h₂⟩ := h x y z hx hy hz hp he + have ha : Positive ![x, y, z] := by intro i; fin_cases i <;> assumption + exact hD.boundary h₂ ha (h₁.trans he.symm) + +theorem propagation_of_potential + (h : ∀ x y z, 0 < x → 0 < y → 0 < z → Prices F x y z → dStar x y z = 1 → + ∃ D, Tripod F D ∧ D ![x, y, z] = 1 ∧ HasPotential (defect D)) : + Propagation (Prices F) := by + apply propagation_of_tripod + intro x y z hx hy hz hp he + obtain ⟨D, hD, h₁, h₂⟩ := h x y z hx hy hz hp he + exact ⟨D, hD, h₁, comparison_of_potential hD.regular h₂⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Contact at infinity from a sharp dual threshold + +Normalize the sum of the two short arms to two. Testing the spectral +formula just above inner exponent one half forces these arms to converge +to one, the long arm to escape, and the *absolute* diagonal defect to vanish. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +/-- Contact in the limit as one arm escapes to infinity. -/ +def Escapes (F : Type) [Field F] : Prop := + ∀ ε M : ℝ, 0 < ε → 0 ≤ M → ∃ x y z D : ℝ, + M < x ∧ 0 < y ∧ 0 < z ∧ 0 < D ∧ y + z = 2 ∧ + |y - 1| < ε ∧ |z - 1| < ε ∧ 0 ≤ D - dStar x y z ∧ D - dStar x y z < ε ∧ + Prices F (x / D) (y / D) (z / D) + +variable {F : Type} [Field F] {x y z d : ℝ} + +private theorem exceed (hd : dual F 1 1 ≤ 1 / 2) (h : 0 < d) (h' : d ≤ 1 / 2) : + 2 < exponent F 1 1 (1 / 2 + d) := by + have hl := (bounds F zero_le_one zero_le_one (by linarith : 0 ≤ 1 / 2 + d)).1 + by_contra! hu + have he : exponent F 1 1 (1 / 2 + d) = 1 + 1 := by + rw [max_le_iff] at hl + linarith [hl.1] + have hh : 1 / 2 + d ≤ dual F 1 1 := + le_csSup ⟨_, fun _ hx => hx.1.2⟩ ⟨⟨by linarith, by simp; linarith⟩, he⟩ + linarith + +private theorem positive_arms (hp : Prices F x y z) (h : d ≤ 1 / 2) + (hl : 2 < load 1 1 (1 / 2 + d) x y z) : 0 < x ∧ 0 < y ∧ 0 < z := by + obtain ⟨hx, hy, hz⟩ := hp.nonneg + have hs : 1 < x + y + z := by + unfold load at hl + linarith [mul_nonneg (by linarith : 0 ≤ 1 / 2 - d) (add_nonneg hy hz)] + have hh := diagonal F _ _ _ hp + refine ⟨hx.lt_of_ne ?_, hy.lt_of_ne ?_, hz.lt_of_ne ?_⟩ <;> + rintro rfl <;> simp [dStar] at hh <;> linarith + +/-- Completing the square separates three nonnegative losses. -/ +private theorem losses (hx : 0 < x) (hy : 0 < y) (hz : 0 < z) (he : y + z = 2) : + let g := y * z / 2 + g ^ 2 / (x + g) + (y - 1) ^ 2 / 2 = dStar x y z - x - 3 / 2 := by + dsimp only + unfold dStar + field_simp + rw [show z = 2 - y by linarith] + ring + +private theorem near_contact (hd : dual F 1 1 ≤ 1 / 2) (h : 0 < d) (h' : d ≤ 1 / 2) : + ∃ x y z D : ℝ, 0 < x ∧ 0 < y ∧ 0 < z ∧ 0 < D ∧ y + z = 2 ∧ + Prices F (x / D) (y / D) (z / D) ∧ 0 ≤ D - dStar x y z ∧ + D - dStar x y z + ((y * z / 2) ^ 2 / (x + y * z / 2) + (y - 1) ^ 2 / 2) < d := by + obtain ⟨a, b, c, hp, he⟩ := (support F).attains zero_le_one zero_le_one + (by linarith : 0 ≤ 1 / 2 + d) + have hl := (exceed hd h h').trans_eq he.symm + obtain ⟨ha, hb, hc⟩ := positive_arms hp h' hl + let D := 2 / (b + c) + have hD : 0 < D := by unfold D; positivity + let x := a * D + let y := b * D + let z := c * D + have hx : 0 < x := mul_pos ha hD + have hy : 0 < y := mul_pos hb hD + have hz : 0 < z := mul_pos hc hD + have hsum : y + z = 2 := by unfold y z D; field_simp + have hs : dStar x y z = dStar a b c * D := by + unfold x y z dStar + field_simp + have h' := mul_le_mul_of_nonneg_right (diagonal F _ _ _ hp) hD.le + refine ⟨x, y, z, D, hx, hy, hz, hD, hsum, ?_, by rw [hs]; linarith, ?_⟩ + · simpa only [x, y, z, mul_div_cancel_right₀ _ hD.ne'] using hp + rw [losses hx hy hz hsum] + have he' : load 1 1 (1 / 2 + d) a b c * D = 2 * x + (3 / 2 + d) * (y + z) := by + unfold load x y z + ring + have hh := mul_lt_mul_of_pos_right hl hD + rw [he', hsum] at hh + linarith + +theorem escapes_of_dual (hd : dual F 1 1 ≤ 1 / 2) : Escapes F := by + intro ε M hε hM + let d := min (min ε (ε ^ 2 / 2)) (min (1 / 16) (1 / (16 * (M + 1)))) + have hd' : 0 < d := by unfold d; positivity + have hd₁ : d ≤ ε := (min_le_left _ _).trans (min_le_left _ _) + have hd₂ : d ≤ ε ^ 2 / 2 := (min_le_left _ _).trans (min_le_right _ _) + have hd₃ : d ≤ 1 / 16 := (min_le_right _ _).trans (min_le_left _ _) + have hd₄ : d ≤ 1 / (16 * (M + 1)) := (min_le_right _ _).trans (min_le_right _ _) + obtain ⟨x, y, z, D, hx, hy, hz, hD, hs, hp, hl, hu⟩ := near_contact hd hd' (by linarith) + let g := y * z / 2 + change D - dStar x y z + (g ^ 2 / (x + g) + (y - 1) ^ 2 / 2) < d at hu + have h₁ : 0 ≤ g ^ 2 / (x + g) := by positivity + have h₂ : 0 ≤ (y - 1) ^ 2 / 2 := by positivity + have hsmall : (y - 1) ^ 2 < ε ^ 2 := by linarith + have hy' : |y - 1| < ε := by + rw [abs_lt] + constructor <;> nlinarith only [hsmall, hε] + have hz' : |z - 1| < ε := by rwa [show z - 1 = -(y - 1) by linarith, abs_neg] + refine ⟨x, y, z, D, ?_, hy, hz, hD, hs, hy', hz', hl, by linarith, hp⟩ + have he : g = (1 - (y - 1) ^ 2) / 2 := by unfold g; rw [show z = 2 - y by linarith]; ring + have hgle : g ≤ 1 := by linarith + have hgge : 1 / 4 ≤ g := by linarith + have h₃ : g ^ 2 < d * (x + g) := (div_lt_iff₀ (by positivity)).mp (by linarith) + have h₄ := (le_div_iff₀ (by positivity : 0 < 16 * (M + 1))).mp hd₄ + by_contra! hh + nlinarith only [h₃, h₄, hgge, mul_le_mul_of_nonneg_left (add_le_add hh hgle) hd'.le] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# Approaching a reciprocal face + +The star bound and convexity along an unbounded arm make the +diagonal rate minus the length nonincreasing along that arm. +In reciprocal coordinates this gives a limit at the open face. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Minimum Set Filter +open scoped Topology + +/-- A tripod whose common-label rate satisfies the star spanning-tree bound. -/ +structure StarTripod (F : Type) [Field F] (D : Vec → ℝ) : Prop extends Tripod F D where + star : ∀ a, Positive a → D a ≤ ∑ i, a i + +variable {F : Type} [Field F] {D : Vec → ℝ} {v : Vec} + +private theorem growth_linear {f : ℝ → ℝ} (h : ConvexOn ℝ (Ioi 0) f) + {L : ℝ} (hL : ∀ x, 0 < x → f x ≤ x + L) : AntitoneOn (fun x => f x - x) (Ioi 0) := by + intro a ha b hb hab + rcases eq_or_lt_of_le hab with rfl | hab + · rfl + by_contra! hbad + let c := (f b - f a) / (b - a) + have hc : 1 < c := (lt_div_iff₀ (sub_pos.mpr hab)).2 (by linarith) + obtain ⟨t, ht⟩ := exists_gt (max b ((c * b + L - f b) / (c - 1))) + obtain ⟨ht₁, ht₂⟩ := max_lt_iff.mp ht + have ht : 0 < t := hb.trans ht₁ + have ht' := h.slope_mono_adjacent ha ht hab ht₁ + change c ≤ (f t - f b) / (t - b) at ht' + rw [le_div_iff₀ (sub_pos.mpr ht₁)] at ht' + rw [div_lt_iff₀ (sub_pos.mpr hc)] at ht₂ + linarith only [ht', ht₂, hL t ht] + +theorem StarTripod.anti (h : StarTripod F D) (hv : Positive v) (i : Fin 3) : + AntitoneOn (fun t => D (Function.update v i t) - t) (Ioi 0) := by + apply growth_linear (h.convex _ hv i) (L := ∑ j ∈ Finset.univ \ {i}, v j) + intro x hx + have hp : Positive (Function.update v i x) := by + intro j + by_cases he : j = i + · simpa [he] using hx + · simpa [he] using hv j + have ht := h.star _ hp + rwa [Finset.sum_update_of_mem (Finset.mem_univ i)] at ht + +theorem StarTripod.cap (h : StarTripod F D) (hv : Positive v) : + defect D v ≤ (∑ i, v i)⁻¹ := by + have he := h.star v⁻¹ (fun i => inv_pos.mpr (hv i)) + unfold defect + simp only [Pi.inv_apply] at he + linarith + +namespace Face + +theorem positive {x y z : ℝ} (hx : 0 < x) (hy : 0 < y) (hz : 0 < z) : Positive ![x, y, z] := by + intro i; fin_cases i <;> assumption + +private theorem update_inv (x y z : ℝ) : + (![x, y, z] : Vec)⁻¹ = Function.update ![1, y⁻¹, z⁻¹] 0 x⁻¹ := by + ext i; fin_cases i <;> simp + +variable (h : StarTripod F D) {x y z : ℝ} +include h + +theorem monotone (hy : 0 < y) (hz : 0 < z) : + MonotoneOn (fun x => defect D ![x, y, z] - (x + y + z)⁻¹) (Ioi 0) := by + intro a ha b hb hab + have he := h.anti (positive zero_lt_one (inv_pos.mpr hy) (inv_pos.mpr hz)) 0 + (show 0 < b⁻¹ from inv_pos.mpr hb) (show 0 < a⁻¹ from inv_pos.mpr ha) (inv_anti₀ ha hab) + change D _ - _ ≤ D _ - _ at he + simp only [defect, Fin.sum_univ_three, Matrix.cons_val_zero, Matrix.cons_val_one, + Matrix.cons_val_two, Matrix.head_cons, Matrix.tail_cons, update_inv] + linarith + +/-- The indexed operation `limUnder (𝓝[>] 0) fun x => defect D ![x, y, z]`. -/ +def limit (D : Vec → ℝ) (y z : ℝ) : ℝ := + limUnder (𝓝[>] 0) fun x => defect D ![x, y, z] + +theorem tends (hy : 0 < y) (hz : 0 < z) : + Tendsto (fun x => defect D ![x, y, z]) (𝓝[>] 0) (𝓝 (limit D y z)) := by + let f x := defect D ![x, y, z] - (x + y + z)⁻¹ + have hb : BddBelow (f '' Ioi 0) := by + refine ⟨-(y + z)⁻¹, ?_⟩ + rintro _ ⟨x, hx, rfl⟩ + have hd := h.toTripod.regular.nonneg _ (positive hx hy hz) + have hi : (x + y + z)⁻¹ ≤ (y + z)⁻¹ := inv_anti₀ (by positivity) (by linarith [show 0 + < x from hx]) + unfold f; linarith + have ht := (monotone h hy hz).tendsto_nhdsGT hb + have hi : ContinuousAt (fun x : ℝ => (x + y + z)⁻¹) 0 := by fun_prop (disch := positivity) + apply tendsto_nhds_limUnder + refine ⟨sInf (f '' Ioi 0) + (0 + y + z)⁻¹, ?_⟩ + simpa only [sub_add_cancel] using ht.add hi.continuousWithinAt + +end Face +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- # Uniform estimates tangential to a reciprocal face -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Minimum Set + +variable {F : Type} [Field F] {D : Vec → ℝ} {v : Vec} + +private theorem inv_step {a s t : ℝ} (ha : 0 < a) (hs : 0 ≤ s) (ht : s ≤ t) : + 0 ≤ 1 / (a + s) - 1 / (a + t) ∧ 1 / (a + s) - 1 / (a + t) ≤ (t - s) / a ^ 2 := by + have h₁ : 0 < a + s := by linarith + have h₂ : 0 < a + t := by linarith + rw [show 1 / (a + s) - 1 / (a + t) = (t - s) / ((a + s) * (a + t)) by field_simp; ring] + have h : a ^ 2 ≤ (a + s) * (a + t) := by rw [pow_two]; gcongr <;> linarith + exact ⟨div_nonneg (sub_nonneg.mpr ht) (by positivity), + div_le_div_of_nonneg_left (sub_nonneg.mpr ht) (by positivity) h⟩ + +theorem StarTripod.step (h : StarTripod F D) (hv : Positive v) (i : Fin 3) + {s t : ℝ} (hs : 0 ≤ s) (ht : s ≤ t) : + ray (defect D) v i s - ray (defect D) v i t ≤ (t - s) / (∑ j, v j) ^ 2 ∧ + ray (defect D) v i t - ray (defect D) v i s ≤ 2 * ((t - s) / (v i) ^ 2) := by + have h₁ : 0 < v i := hv i + have h₂ : 0 < ∑ j, v j := Finset.sum_pos (fun j _ => hv j) Finset.univ_nonempty + have hi : Positive v⁻¹ := fun j => inv_pos.mpr (hv j) + have ht' := hs.trans ht + have hs₀ : 1 / (v i + s) ∈ Ioi (0 : ℝ) := by apply mem_Ioi.mpr; positivity + have ht₀ : 1 / (v i + t) ∈ Ioi (0 : ℝ) := by apply mem_Ioi.mpr; positivity + obtain ⟨hi₁, hi₂⟩ := inv_step h₁ hs ht + obtain ⟨hv₁, hv₂⟩ := inv_step h₂ hs ht + have hinc := h.transport _ hi i ht₀ hs₀ (sub_nonneg.mp hi₁) + have hdec := h.anti hi i ht₀ hs₀ (sub_nonneg.mp hi₁) + rw [ray_defect] + dsimp only at hinc hdec ⊢ + constructor <;> linarith + +theorem StarTripod.ray_bound (h : StarTripod F D) (hv : Positive v) (i : Fin 3) + {s t : ℝ} (hs : 0 ≤ s) (ht : 0 ≤ t) : + |ray (defect D) v i t - ray (defect D) v i s| ≤ (2 / (v i) ^ 2) * |t - s| := by + wlog hst : s ≤ t generalizing s t + · rw [abs_sub_comm, abs_sub_comm t] + exact this ht hs (le_of_not_ge hst) + have hi : v i ≤ ∑ j, v j := Finset.single_le_sum (fun j _ => (hv j).le) (Finset.mem_univ i) + obtain ⟨h₁, h₂⟩ := h.step hv i hs hst + have hp := hv i + have he : (t - s) / (∑ j, v j) ^ 2 ≤ (t - s) / (v i) ^ 2 := by gcongr + have he' : 0 ≤ (t - s) / (v i) ^ 2 := by positivity + rw [abs_of_nonneg (sub_nonneg.mpr hst), abs_sub_le_iff] + simp only [div_eq_mul_inv] at he he' h₁ h₂ ⊢ + constructor <;> linarith + +theorem StarTripod.tail (h : StarTripod F D) (hv : Positive v) (i : Fin 3) + {t : ℝ} (ht : 0 < t) : ray (defect D) v i t ≤ 1 / t := by + have hp := hv.move i ht.le + refine (h.cap hp).trans ?_ + rw [one_div] + apply inv_anti₀ ht + refine le_trans ?_ (Finset.single_le_sum (fun j _ => (hp j).le) (Finset.mem_univ i)) + simp [move, (hv i).le] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# The positive face as a three-coordinate defect + +Splitting one tangential coordinate into two equal-role coordinates +allows the interior strong minimum principle to be used unchanged. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Face +open Minimum Set Filter +open scoped Topology + +/-- The quantity computed by `![t, v 0, v 1 + v 2]`. -/ +def atDepth (t : ℝ) (v : Vec) : Vec := ![t, v 0, v 1 + v 2] + +/-- The quantity computed by `limit D (v 0) (v 1 + v 2)`. -/ +def lifted (D : Vec → ℝ) (v : Vec) : ℝ := limit D (v 0) (v 1 + v 2) + +/-- Returns `1` when `i = 0` holds, and `2` otherwise. -/ +def tangent (i : Fin 3) : Fin 3 := if i = 0 then 1 else 2 + +variable {v w : Vec} {t : ℝ} + +theorem depth_positive (hv : Positive v) (ht : 0 < t) : Positive (atDepth t v) := + positive ht (hv 0) (add_pos (hv 1) (hv 2)) + +theorem tangent_le (hv : Positive v) (t : ℝ) (i : Fin 3) : v i ≤ atDepth t v (tangent i) := by + fin_cases i <;> simp [tangent, atDepth, (hv 1).le, (hv 2).le] + +theorem along (r : ℝ) (v : Vec) (i : Fin 3) (t : ℝ) : + move (atDepth r v) (tangent i) t = atDepth r (move v i t) := by + ext j + fin_cases i <;> fin_cases j <;> simp [atDepth, move, tangent, add_comm, add_left_comm, add_assoc] + +variable {F : Type} [Field F] {D : Vec → ℝ} (h : StarTripod F D) +include h + +theorem lifted_limit (hv : Positive v) : + Tendsto (fun r => defect D (atDepth r v)) (𝓝[>] 0) (𝓝 (lifted D v)) := + tends h (hv 0) (add_pos (hv 1) (hv 2)) + +theorem ray_limit (hv : Positive v) (i : Fin 3) (ht : 0 ≤ t) : + Tendsto (fun r => ray (defect D) (atDepth r v) (tangent i) t) (𝓝[>] 0) + (𝓝 (ray (lifted D) v i t)) := by + simpa only [ray, along] using lifted_limit h (hv.move i ht) + +private theorem lifted_scale (hv : Positive v) {s : ℝ} (hs : 0 < s) : + lifted D (s • v) = lifted D v / s := by + have hv' : Positive (s • v) := fun i => mul_pos hs (hv i) + have he (r : ℝ) : atDepth (s * r) (s • v) = s • atDepth r v := by + ext i; fin_cases i <;> simp [atDepth, mul_add] + have ht : Tendsto (fun r : ℝ => s * r) (𝓝[>] 0) (𝓝[>] 0) := by + refine tendsto_nhdsWithin_iff.mpr ⟨?_, ?_⟩ + · simpa using (tendsto_id.mono_left nhdsWithin_le_nhds : + Tendsto (fun x : ℝ => x) (𝓝[>] 0) (𝓝 0)).const_mul s + · filter_upwards [self_mem_nhdsWithin] with r hr + exact mul_pos hs hr + refine tendsto_nhds_unique ((lifted_limit h hv').comp ht) ?_ + refine ((lifted_limit h hv).div_const s).congr' ?_ + filter_upwards [self_mem_nhdsWithin] with r hr + simp only [Function.comp_apply, he, h.toTripod.regular.homogeneous _ (depth_positive hv hr) _ hs] + +theorem ray_bound (hv : Positive v) (i : Fin 3) {r s t : ℝ} (hr : 0 < r) + (hs : 0 ≤ s) (ht : 0 ≤ t) : + |ray (defect D) (atDepth r v) (tangent i) t - ray (defect D) (atDepth r v) (tangent i) s| ≤ + 2 / (v i) ^ 2 * |t - s| := by + apply (h.ray_bound (depth_positive hv hr) (tangent i) hs ht).trans + have hp := hv i + gcongr + exact tangent_le hv r i + +private theorem ray_continuous (hv : Positive v) (i : Fin 3) : + ContinuousOn (ray (lifted D) v i) (Ici 0) := by + let C : NNReal := ⟨2 / (v i) ^ 2, by positivity⟩ + apply LipschitzOnWith.continuousOn (K := C) + apply LipschitzOnWith.of_dist_le_mul + intro t ht s hs + simp only [Real.dist_eq] + apply le_of_tendsto ((ray_limit h hv i ht).sub (ray_limit h hv i hs)).abs + filter_upwards [self_mem_nhdsWithin] with r hr + exact ray_bound h hv i hr hs ht + +private theorem ray_convex (hv : Positive v) (i : Fin 3) {C : ℝ} (hC : 2 / (v i) ^ 3 ≤ C) : + Semiconvex (ray (lifted D) v i) C := by + have hc (r : ℝ) (hr : 0 < r) : Semiconvex (ray (defect D) (atDepth r v) (tangent i)) C := by + have hp := depth_positive hv hr + have hi : Positive (atDepth r v)⁻¹ := fun j => inv_pos.mpr (hp j) + have hsum : 0 < ∑ j, atDepth r v j := Finset.sum_pos (fun j _ => hp j) Finset.univ_nonempty + rw [ray_defect] + apply reciprocal_semiconvex (h.convex _ hi (tangent i)) + (h.transport _ hi (tangent i)) (hp _) hsum + apply le_trans _ hC + have he := hv i + gcongr + exact tangent_le hv r i + refine ⟨convex_Ici _, ?_⟩ + intro x hx y hy a b ha hb hab + simp only [smul_eq_mul] + have hf (t) (ht : 0 ≤ t) := (ray_limit h hv i ht).add_const (C * t ^ 2) + apply le_of_tendsto_of_tendsto (hf _ (add_nonneg (mul_nonneg ha hx) (mul_nonneg hb hy))) + (((hf x hx).const_mul a).add ((hf y hy).const_mul b)) + filter_upwards [self_mem_nhdsWithin] with r hr + exact (hc r hr).2 hx hy ha hb hab + +theorem regular : Regular (lifted D) := by + refine ⟨?_, fun _ hv _ hs => lifted_scale h hv hs, fun _ hv => ray_continuous h hv, ?_⟩ + · intro v hv + apply ge_of_tendsto (lifted_limit h hv) + filter_upwards [self_mem_nhdsWithin] with r hr + exact h.toTripod.regular.nonneg _ (depth_positive hv hr) + · intro v hv + let C := ∑ i, 2 / (v i) ^ 3 + have hp i : 0 ≤ 2 / (v i) ^ 3 := div_nonneg (by norm_num) (pow_nonneg (hv i).le _) + refine ⟨C, Finset.sum_nonneg (fun i _ => hp i), ?_⟩ + intro w hw i + apply ray_convex h (fun j => (hv j).trans_le (hw.1 j)) i + apply le_trans _ (Finset.single_le_sum (fun j _ => hp j) (Finset.mem_univ i)) + have h' := hv i + gcongr + exact hw.1 i + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Face +end + +section +/- # Passing the directional integral comparison to a face -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Face +open Minimum Set Filter +open scoped Topology + +/-- The constant stays bounded as the first reciprocal length tends to +zero while the other two range over a compact positive box. -/ +def Uniform (D : Vec → ℝ) : Prop := + ∀ v, Positive v → ∃ E : ℝ, 0 ≤ E ∧ ∀ w, Positive w → w ≤ (2 : ℝ) • v → + v 1 ≤ w 1 → v 2 ≤ w 2 → ∀ i j, ∀ ζ : ℝ, 0 < ζ → + ∀ᶠ T : ℝ in atTop, J D w i T - J D w j T ≤ E * D w + ζ + +variable {F : Type} [Field F] {D : Vec → ℝ} + +theorem Uniform.interior (h : Uniform D) : Comparison D := by + intro v hv + obtain ⟨E, hE, hc⟩ := h v hv + exact ⟨E, hE, fun w hw => hc w (fun i => (hv i).trans_le (hw.1 i)) hw.2 (hw.1 1) (hw.1 2)⟩ + +theorem comparison (h : StarTripod F D) (hc : Uniform (defect D)) : + Comparison (lifted D) := by + intro v hv + obtain ⟨E, hE, he⟩ := hc (atDepth 1 v) (depth_positive hv zero_lt_one) + refine ⟨E, hE, ?_⟩ + intro w hw i j ζ hζ + have hw' : Positive w := fun i => (hv i).trans_le (hw.1 i) + let f (i : Fin 3) (r : ℝ) := ray (defect D) (atDepth r w) (tangent i) + have hp r (hr : r ∈ Ioc (0 : ℝ) 1) := depth_positive hw' hr.1 + let C := 2 / (w i) ^ 2 + 2 / (w j) ^ 2 + have hC : 0 ≤ C := by unfold C; positivity + have hnear (r) (hr : r ∈ Ioc (0 : ℝ) 1) (t : ℝ) (ht : 0 < t) : + -(C * t) ≤ f i r t - f j r t := by + have h₁ := ray_bound h hw' i hr.1 le_rfl ht.le + have h₂ := ray_bound h hw' j hr.1 le_rfl ht.le + simp only [sub_zero, abs_of_pos ht, ray_zero, abs_le] at h₁ h₂ + unfold C f + linarith only [h₁.1, h₂.2] + have hr := h.toTripod.regular + have hcon i r (hp : Positive (atDepth r w)) := hr.continuous _ hp (tangent i) + have hnon i r (hp : Positive (atDepth r w)) t (ht : 0 ≤ t) : 0 ≤ f i r t := + hr.nonneg _ (hp.move _ ht) + apply compare_limit (f := f i) (g := f j) hC + (fun r h' => ⟨hcon _ _ (hp r h'), hcon _ _ (hp r h')⟩) + (fun r h' t ht => ⟨hnon _ _ (hp r h') t ht, hnon _ _ (hp r h') t ht⟩) + (fun r h' t ht => ⟨h.tail (hp r h') _ ht, h.tail (hp r h') _ ht⟩) hnear + (fun t ht => ⟨ray_limit h hw' i ht.le, ray_limit h hw' j ht.le⟩) + ((lifted_limit h hw').const_mul E) ?_ hζ + intro r h' + have hu : atDepth r w ≤ (2 : ℝ) • atDepth 1 v := by + have he (k : Fin 3) : w k ≤ 2 * v k := hw.2 k + intro k + fin_cases k <;> simp [atDepth] <;> linarith [h'.2, he 0, he 1, he 2] + exact he _ (hp r h') hu (hw.1 0) (add_le_add (hw.1 1) (hw.1 2)) (tangent i) (tangent j) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Face +end + +section +/- +# Spectral contact at infinity + +The localized rate estimate gives a zero at one point of a reciprocal +face. The strong minimum principle first propagates it tangentially; +normal comparison then gives a finite contact on the tripod. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Minimum Face Set Filter +open scoped Topology + +variable {F : Type} [Field F] {D : Vec → ℝ} + +private theorem StarTripod.face_zero (h : StarTripod F D) + (hc : Uniform (defect D)) (hz : limit D 1 1 = 0) : + ∃ v, Positive v ∧ defect D v = 0 := by + have hl (y : ℝ) (hy : 0 < y) : Tendsto (fun r => defect D ![r, y, 1]) (𝓝[>] 0) (𝓝 0) := by + have hhalf : (0 : ℝ) < 1 / 2 := by norm_num + have he := vanishes (regular h) (comparison h hc) (positive zero_lt_one hhalf hhalf) + (by norm_num [lifted, Matrix.cons_val_two, hz]) (positive hy hhalf hhalf) + norm_num [lifted, Matrix.cons_val_two] at he + have hh := tends h hy zero_lt_one + rwa [he] at hh + have h₀ (r t : ℝ) : ray (defect D) ![r, 1, 1] 0 t = defect D ![r + t, 1, 1] := by + unfold ray + congr 1 + ext i; fin_cases i <;> simp [move] + have h₁ (r t : ℝ) : ray (defect D) ![r, 1, 1] 1 t = defect D ![r, 1 + t, 1] := by + unfold ray + congr 1 + ext i; fin_cases i <;> simp [move] + obtain ⟨E, _, he⟩ := hc _ (positive zero_lt_one zero_lt_one zero_lt_one) + apply Minimum.face_zero h.toTripod.regular (E := E) (by norm_num : (0 : ℝ) ≤ 2) hl + · intro r hr t ht + have hh := (h.step (positive hr.1 zero_lt_one zero_lt_one) 0 le_rfl ht).1 + rw [ray_zero, h₀, Fin.sum_univ_three] at hh + simp only [Matrix.cons_val_zero, Matrix.cons_val_one, Matrix.cons_val_two, + Matrix.head_cons, Matrix.tail_cons, sub_zero] at hh + have hd : t / (r + 1 + 1) ^ 2 ≤ t := div_le_self ht (by nlinarith [hr.1]) + linarith + · intro r hr t ht + have hh := (h.step (positive hr.1 zero_lt_one zero_lt_one) 1 le_rfl ht).2 + rw [ray_zero, h₁] at hh + simp only [Matrix.cons_val_one, Matrix.cons_val_zero, sub_zero, one_pow, div_one] at hh + linarith + · intro r hr t ht + rw [← h₁] + exact h.tail (positive hr.1 zero_lt_one zero_lt_one) 1 ht + · intro r hr + refine he _ (positive hr.1 zero_lt_one zero_lt_one) ?_ le_rfl le_rfl 0 1 + intro i + fin_cases i <;> simp; linarith [hr.2] + +/-- Truncation of the long arm at length `x`, with short arms of +unit length. -/ +def Localized (D : Vec → ℝ) : Prop := + ∀ x : ℝ, 1 < x → D ![x, 1, 1] ≤ x + 3 / 2 + 1 / (2 * x) + +theorem StarTripod.localized_zero (h : StarTripod F D) (hl : Localized D) : limit D 1 1 = 0 := by + have ht := tends h zero_lt_one zero_lt_one + have hpos : 0 ≤ limit D 1 1 := by + apply ge_of_tendsto ht + filter_upwards [self_mem_nhdsWithin] with r hr + exact h.toTripod.regular.nonneg _ (positive hr zero_lt_one zero_lt_one) + refine le_antisymm ?_ hpos + apply le_of_tendsto_of_tendsto ht (tendsto_id.mono_left nhdsWithin_le_nhds) + filter_upwards [Ioo_mem_nhdsGT zero_lt_one] with r hr + obtain ⟨hr, hr'⟩ := hr + have hu := hl r⁻¹ ((one_lt_inv₀ hr).mpr hr') + have he : (![r, 1, 1] : Vec)⁻¹ = ![r⁻¹, 1, 1] := by ext i; fin_cases i <;> simp + rw [defect, he] + simp only [Fin.sum_univ_three, Matrix.cons_val_zero, Matrix.cons_val_one, Matrix.cons_val_two, + Matrix.head_cons, Matrix.tail_cons, inv_one, id_eq] + have h₁ : (r + 1 + 1)⁻¹ ≤ (2 : ℝ)⁻¹ := inv_anti₀ (by norm_num) (by linarith) + have h₂ : 1 / (2 * r⁻¹) = r / 2 := by field_simp + rw [h₂] at hu + linarith + +/-- A zero at infinity on a homogeneous tripod realizes the entire +positive polar boundary in the space of spectral prices. -/ +theorem StarTripod.boundary_of_limit (h : StarTripod F D) (hc : Uniform (defect D)) + (hz : limit D 1 1 = 0) (x y z : ℝ) (hx : 0 < x) (hy : 0 < y) (hz' : 0 < z) : + Prices F (x / dStar x y z) (y / dStar x y z) (z / dStar x y z) := by + obtain ⟨v, hv, hz⟩ := h.face_zero hc hz + have ha : Positive v⁻¹ := fun i => inv_pos.mpr (hv i) + have he := defect_inv D ha + rw [inv_inv, hz, eq_comm, sub_eq_zero] at he + exact h.toTripod.boundary hc.interior ha he x y z hx hy hz' + +theorem StarTripod.rigidity_of_limit (h : StarTripod F D) (hc : Uniform (defect D)) + (hz : limit D 1 1 = 0) : Rigidity F := + rigidity_of_contact (support F) (diagonal F) (fun _ => h.boundary_of_limit hc hz) + +theorem StarTripod.square_of_limit (h : StarTripod F D) (hc : Uniform (defect D)) + (hz : limit D 1 1 = 0) : MatrixExponent.omega F = 9 / 4 := by + have hp := h.boundary_of_limit hc hz 1 1 1 zero_lt_one zero_lt_one zero_lt_one + norm_num [dStar] at hp + exact (square_iff_contact F).mpr hp + +theorem StarTripod.square (h : StarTripod F D) (hc : Uniform (defect D)) (hl : Localized D) : + MatrixExponent.omega F = 9 / 4 := + h.square_of_limit hc (h.localized_zero hl) + +/-- A localized tripod with uniform comparison is the remaining +geometric input for the strict dual saving. -/ +theorem dual_of_localization (h : Escapes F → ∃ D, + StarTripod F D ∧ Uniform (defect D) ∧ Localized D) + (hs : MatrixExponent.omega F < 9 / 4) : 1 / 2 < dual F 1 1 := by + by_contra! he + obtain ⟨D, hD, hc, hl⟩ := h (escapes_of_dual he) + exact hs.ne (hD.square hc hl) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/FiniteModel.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/FiniteModel.lean new file mode 100644 index 0000000000..f35b175ea6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/FiniteModel.lean @@ -0,0 +1,54 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights +public import Mathlib.Data.Fintype.BigOperators + +/-! +# Exact ranks of powers and their asymptotic rate + +Each side of a power has one independent digit per copy. Convergence +to the stated limit is proved for positive support density. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +variable {F : Type*} {i j k : ℕ} + +/-- The indexed operation `fun a b c => ∏ l : Fin n, w (finFunctionFinEquiv.symm a l) +(finFunctionFinEquiv.symm b l) (finFunctionFinEquiv.symm c l)`. -/ +def WPower [CommMonoid F] (w : Fin i → Fin j → Fin k → F) (n : ℕ) : + Fin (i ^ n) → Fin (j ^ n) → Fin (k ^ n) → F := fun a b c => + ∏ l : Fin n, w (finFunctionFinEquiv.symm a l) + (finFunctionFinEquiv.symm b l) (finFunctionFinEquiv.symm c l) + +/-- The infimum of `{r : ℕ | WeightedRankLE w r}`. -/ +def rankW [CommSemiring F] (w : Fin i → Fin j → Fin k → F) : ℕ := + sInf {r : ℕ | WeightedRankLE w r} + +/-- The quantity computed by `limUnder atTop fun n : ℕ => (rankW (WPower w n) : ℝ) ^ (n : ℝ)⁻¹`. -/ +def asymptoticRank [CommSemiring F] (w : Fin i → Fin j → Fin k → F) : ℝ := + limUnder atTop fun n : ℕ => (rankW (WPower w n) : ℝ) ^ (n : ℝ)⁻¹ + +/-- Evaluates `1` at the input `_ _ _`. -/ +def ordinary (F : Type*) [One F] (i j k : ℕ) : Fin i → Fin j → Fin k → F := + fun _ _ _ => 1 + +/-- The quantity computed by `supportSize w / ((i : ℝ) * j * k)`. -/ +def density [Zero F] (w : Fin i → Fin j → Fin k → F) : ℝ := supportSize w / ((i : ℝ) * j * k) + +/-- Normalize the surplus by the output area divided by its natural logarithm. -/ +noncomputable def normalized (x y : ℝ) (r : ℕ → ℕ) (n : ℕ) : ℝ := + let A := (side n x : ℝ) * side n y + ((r n : ℝ) - A) * Real.log A / A + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Folding/Swap.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Folding/Swap.lean new file mode 100644 index 0000000000..f93ce4dbd1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Folding/Swap.lean @@ -0,0 +1,786 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Folding.Transfer +public import Mathlib.Data.Fintype.EquivFin + +/-! +# Graded actions on nested blocks + +The distance counts all blocks on which two words differ, including +individual positions. This gives an edit bound without a logarithmic +charge per changed position. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Prices.Motion + +open scoped Classical in +/-- In the case `0, X`, this construction gives `X`. -/ +abbrev Tree : ℕ → Type → Type + | 0, X => X + | j + 1, X => Tree j (Block X) + +open scoped Classical in +instance treeFinite : (j : ℕ) → (X : Type) → [Fintype X] → Fintype (Tree j X) + | 0, _, h => h + | j + 1, X, _ => treeFinite j (Block X) + +variable {X Y F : Type} [Field F] + +open scoped Classical in +/-- In the case `0, _, o`, this construction gives `o`. -/ +def treeOrder : (j : ℕ) → {X : Type} → Order X → Order (Tree j X) + | 0, _, o => o + | j + 1, _, o => treeOrder j o.block + +open scoped Classical in +/-- In the case `0, _, A`, this construction gives `A`. -/ +def action : (j : ℕ) → {X : Type} → Matrix X X F → Matrix (Tree j X) (Tree j X) F + | 0, _, A => A + | j + 1, _, A => action j (matPower (fun _ : Fin 100 => A)) + +open scoped Classical in +theorem action_mul [Fintype X] (j : ℕ) (A B : Matrix X X F) : + action j (A * B) = action j A * action j B := by + induction j generalizing X with + | zero => rfl + | succ j ih => + simp only [action] + rw [matPower_mul, ih] + +open scoped Classical in +theorem tree_mono (j : ℕ) {p o : Order X} (h : ∀ x y, p.rel x y → o.rel x y) (x y : Tree j X) + (he : (treeOrder j p).rel x y) : (treeOrder j o).rel x y := by + induction j generalizing X with + | zero => exact h x y he + | succ j ih => exact ih (p := p.block) (o := o.block) (fun _ _ e i => h _ _ (e i)) x y he + +open scoped Classical in +theorem tree_focus [Fintype X] (j : ℕ) (o : Order X) {K : ℝ} (h : Focus o.grade K) : + Focus (treeOrder j o).grade (10 ^ j * K) := by + induction j generalizing X K with + | zero => simpa [treeOrder] using h + | succ j ih => + rw [pow_succ, mul_assoc] + exact ih o.block h.block + +open scoped Classical in +theorem card_tree [Fintype X] (j : ℕ) : Fintype.card (Tree j X) = Fintype.card X ^ (100 ^ j) := by + induction j generalizing X with + | zero => simp [Tree] + | succ j ih => + change Fintype.card (Tree j (Block X)) = _ + rw [ih, Fintype.card_fun, Fintype.card_fin, ← pow_mul, pow_succ'] + +open scoped Classical in +/-- Returns `0` when `x = y` holds, and `1` otherwise. -/ +def mismatch (x y : X) : ℝ := if x = y then 0 else 1 + +open scoped Classical in +/-- The quantity computed by `mismatch x y + ∑ i, c (x i) (y i)`. -/ +def next (c : X → X → ℝ) (x y : Block X) := mismatch x y + ∑ i, c (x i) (y i) + +open scoped Classical in +/-- In the case `0, _, c`, this construction gives `c`. -/ +def fee : (j : ℕ) → {X : Type} → (X → X → ℝ) → Tree j X → Tree j X → ℝ + | 0, _, c => c + | j + 1, _, c => fee j (next c) + +open scoped Classical in +theorem fee_refl (j : ℕ) {c : X → X → ℝ} (h : ∀ x, c x x = 0) (x : Tree j X) : + fee j c x x = 0 := by + induction j generalizing X with + | zero => exact h x + | succ j ih => exact ih (c := next c) (by intro y; simp [next, mismatch, h]) x + +open scoped Classical in +theorem fee_nonneg (j : ℕ) {c : X → X → ℝ} (h : ∀ x y, 0 ≤ c x y) (x y : Tree j X) : + 0 ≤ fee j c x y := by + induction j generalizing X with + | zero => exact h x y + | succ j ih => + apply ih (c := next c) _ x y + intro u v + exact add_nonneg (by unfold mismatch; positivity) (sum_nonneg (fun _ _ => h _ _)) + +open scoped Classical in +theorem mismatch_triangle (x y z : X) : mismatch x z ≤ mismatch x y + mismatch y z := by + unfold mismatch + grind + +open scoped Classical in +theorem fee_triangle (j : ℕ) {c : X → X → ℝ} (h : ∀ x y z, c x z ≤ c x y + c y z) + (x y z : Tree j X) : fee j c x z ≤ fee j c x y + fee j c y z := by + induction j generalizing X with + | zero => exact h _ _ _ + | succ j ih => + apply ih (c := next c) _ x y z + intro u v w + have hh := sum_le_sum (s := univ) fun i _ => h (u i) (v i) (w i) + rw [sum_add_distrib] at hh + unfold next + linarith only [hh, mismatch_triangle u v w] + +open scoped Classical in +theorem mismatch_grade (o : Order X) {x y : X} (hr : o.rel x y) : + mismatch x y ≤ (o.grade y : ℝ) - o.grade x := by + unfold mismatch + split_ifs with h + · simp [h] + have he : (o.grade x : ℝ) + 1 ≤ o.grade y := by exact_mod_cast o.inc hr h + linarith + +open scoped Classical in +private theorem fee_grade (j : ℕ) (o : Order X) (d e : X → X → ℝ) + (h : ∀ x y, o.rel x y → d x y ≤ e x y + ((o.grade y : ℝ) - o.grade x)) + (x y : Tree j X) (hr : (treeOrder j o).rel x y) : + fee j d x y ≤ fee j e x y + (((treeOrder j o).grade y : ℝ) - (treeOrder j o).grade x) := by + induction j generalizing X with + | zero => exact h _ _ hr + | succ j ih => + apply ih o.block (next d) (next e) _ x y hr + intro u v h' + have hh := sum_le_sum (s := univ) fun i _ => h (u i) (v i) (h' i) + rw [sum_add_distrib, sum_sub_distrib] at hh + simp only [next, Order.block, blockGrade, Nat.cast_sum] + linarith only [hh] + +open scoped Classical in +theorem refine_fee (j : ℕ) (o : Order X) (x y : Tree j (Block X)) + (hr : (treeOrder j o.block).rel x y) : + fee (j + 1) (@mismatch X) x y ≤ fee j (@mismatch (Block X)) x y + + (((treeOrder j o.block).grade y : ℝ) - (treeOrder j o.block).grade x) := by + apply fee_grade j o.block (next mismatch) mismatch _ x y hr + intro u v h + simp only [next, Order.block, blockGrade, Nat.cast_sum, ← sum_sub_distrib] + exact add_le_add_right (sum_le_sum (fun i _ => mismatch_grade o (h i))) _ + +open scoped Classical in +/-- The indexing data represented by `Fin m → Tree j X`. -/ +abbrev Word (m j : ℕ) (X : Type) := Fin m → Tree j X + +open scoped Classical in +/-- The quantity computed by `m * 100 ^ j`. -/ +def bits (m j : ℕ) := m * 100 ^ j + +open scoped Classical in +theorem card_word [Fintype X] (m j : ℕ) : Fintype.card (Word m j X) = Fintype.card X ^ bits m j + := by + rw [Fintype.card_fun, Fintype.card_fin, card_tree, ← pow_mul, mul_comm, bits] + +open scoped Classical in +/-- The sum of `fee j (@mismatch X) (x i) (y i)` indexed by `i`. -/ +def edits (m j : ℕ) (X : Type) (x y : Word m j X) := ∑ i, fee j (@mismatch X) (x i) (y i) + +open scoped Classical in +theorem edits_refl (m j : ℕ) (X : Type) (x : Word m j X) : edits m j X x x = 0 := + sum_eq_zero fun _ _ => fee_refl _ (fun _ => by simp [mismatch]) _ + +open scoped Classical in +theorem edits_triangle (m j : ℕ) (X : Type) (x y z : Word m j X) : + edits m j X x z ≤ edits m j X x y + edits m j X y z := by + unfold edits; rw [← sum_add_distrib] + exact sum_le_sum (fun _ _ => fee_triangle _ mismatch_triangle _ _ _) + +open scoped Classical in +/-- The indexed operation `matPower (fun _ => action j A)`. -/ +def run (m j : ℕ) (A : Matrix X X F) : Matrix (Word m j X) (Word m j X) F := + matPower (fun _ => action j A) + +open scoped Classical in +theorem run_mul [Fintype X] (m j : ℕ) (A B : Matrix X X F) : + run m j (A * B) = run m j A * run m j B := by + unfold run; rw [action_mul, matPower_mul] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Counting words by the blocks on which they differ -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Real + +variable {X : Type} [Fintype X] + +open scoped Classical in +/-- The condition `∀ x, ∑ y, exp (-100 * c x y) ≤ 2` on the specified data. -/ +def Mass (c : X → X → ℝ) : Prop := ∀ x, ∑ y, exp (-100 * c x y) ≤ 2 + +open scoped Classical in +private theorem Mass.parallel {c : X → X → ℝ} (h : Mass c) {m : ℕ} (x : Fin m → X) : + ∑ y : Fin m → X, exp (-100*∑ i, c (x i) (y i)) ≤ 2 ^ m := by + simp_rw [mul_sum, exp_sum] + rw [← Fintype.prod_sum (fun i t => exp (-100 * c (x i) t))] + simpa using prod_le_prod₀ (s := univ) (fun i _ => by positivity) (fun i _ => h (x i)) + +open scoped Classical in +theorem Mass.block {c : X → X → ℝ} (h : Mass c) (hr : ∀ x, c x x = 0) : Mass (next c) := by + intro x + have he : (2 : ℝ) ^ 100 ≤ exp 100 := by + have hh := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 2) + (show (2 : ℝ) ≤ exp 1 by linarith [add_one_le_exp 1]) 100 + simpa only [← exp_nat_mul, Nat.cast_ofNat, mul_one] using hh + calc + _ ≤ ∑ y : Block X, ((if x = y then 1 else 0) + exp (-100) * exp (-100*∑ i, c (x i) (y i))) := by + apply sum_le_sum + intro y _ + unfold next mismatch + by_cases hy : x = y + · subst y; simp [hr, (exp_pos _).le] + · simp [hy, mul_add, exp_add] + _ ≤ 1 + exp (-100) * 2 ^ 100 := by + rw [sum_add_distrib, ← mul_sum, Fintype.sum_ite_eq] + exact add_le_add_right (mul_le_mul_of_nonneg_left (h.parallel x) (exp_nonneg _)) _ + _ ≤ 2 := by + rw [exp_neg] + linarith [(inv_mul_le_one₀ (exp_pos 100)).mpr he] + +open scoped Classical in +private theorem Mass.tree {c : X → X → ℝ} (h : Mass c) (hr : ∀ x, c x x = 0) (j : ℕ) : + Mass (fee j c) := by + induction j generalizing X with + | zero => exact h + | succ j ih => exact ih (h.block hr) (fun x => by simp [next, mismatch, hr]) + +open scoped Classical in +theorem edits_mass (m j : ℕ) (x : Word m j Bool) : + ∑ y, exp (-100 * edits m j Bool x y) ≤ 2 ^ m := by + have h : Mass (@mismatch Bool) := by + intro x + simpa using sum_le_sum (s := univ) (fun y _ => show exp (-100 * mismatch x y) ≤ 1 from + exp_le_one_iff.mpr (by unfold mismatch; split <;> norm_num)) + exact (h.tree (fun _ => by simp [mismatch]) j).parallel x + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Pairing the corresponding bits of two registers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Prices.Motion Finset + +variable {X Y F : Type} [Field F] + +open scoped Classical in +/-- In the case `0, _, _, f`, this construction gives `f`. -/ +def liftPair : (j : ℕ) → {X Y : Type} → (X → X → Y) → Tree j X → Tree j X → Tree j Y + | 0, _, _, f => f + | j + 1, _, _, f => liftPair j (fun x y i => f (x i) (y i)) + +open scoped Classical in +/-- Evaluates `liftPair j (fun a b => ![a, b]) (x.1 i) (x.2 i)` at the input `i`. -/ +def paired (m j : ℕ) (x : Word m j Bool × Word m j Bool) : Word m j (Col 1) := + fun i => liftPair j (fun a b => ![a, b]) (x.1 i) (x.2 i) + +open scoped Classical in +private theorem pair_cost (j : ℕ) (f : X → X → Y) (d : X → X → ℝ) (e : Y → Y → ℝ) + (h : ∀ a b x y, f a b = f x y → a = x) + (hle : ∀ a b x y, d a x ≤ e (f a b) (f x y)) (a b x y : Tree j X) : + fee j d a x ≤ fee j e (liftPair j f a b) (liftPair j f x y) := by + induction j generalizing X Y with + | zero => exact hle _ _ _ _ + | succ j ih => + let g (u v : Block X) : Block Y := fun i => f (u i) (v i) + have hg (u v r s : Block X) (he : g u v = g r s) : u = r := + funext fun i => h _ _ _ _ (congrFun he i) + apply ih g (next d) (next e) hg _ a b x y + intro u v r s + apply add_le_add _ (sum_le_sum (fun i _ => hle (u i) (v i) (r i) (s i))) + change mismatch u r ≤ mismatch (g u v) (g r s) + by_cases he : g u v = g r s + · rw [he, hg _ _ _ _ he]; simp [mismatch] + · simp only [mismatch, ite_eq_right he]; split <;> norm_num + +open scoped Classical in +theorem paired_cost (m j : ℕ) (x y : Word m j Bool × Word m j Bool) : + edits m j Bool x.1 y.1 ≤ edits m j (Col 1) (paired m j x) (paired m j y) := by + have h (a b x y : Bool) (he : ![a, b] = ![x, y]) : a = x := congrFun he 0 + have hle (a b x y : Bool) : mismatch a x ≤ mismatch ![a, b] ![x, y] := by + unfold mismatch + split_ifs with h₁ h₂ <;> grind + exact sum_le_sum (fun _ _ => pair_cost j _ _ _ h hle _ _ _ _) + +open scoped Classical in +private theorem pair_swap (j : ℕ) (f : X → X → Y) (A : Matrix Y Y F) + (h : ∀ a b x y, A (f a b) (f x y) = if a = y ∧ b = x then 1 else 0) + (a b x y : Tree j X) : + action j A (liftPair j f a b) (liftPair j f x y) = if a = y ∧ b = x then 1 else 0 := by + induction j generalizing X Y with + | zero => exact h _ _ _ _ + | succ j ih => + let g (a b : Block X) : Block Y := fun i => f (a i) (b i) + apply ih g (matPower (fun _ : Fin 100 => A)) _ a b x y + intro a b x y + simp only [matPower, g, h, Fintype.prod_ite_zero, prod_const_one, forall_and, ← funext_iff] + split_ifs <;> rfl + +open scoped Classical in +theorem paired_swap (m j : ℕ) (x y : Word m j Bool × Word m j Bool) : + run m j (exchange F Bool (1 : Fin 2)) (paired m j x) (paired m j y) = + if x = (y.2, y.1) then 1 else 0 := by + have h (a b x y : Bool) : + exchange F Bool (1 : Fin 2) ![a, b] ![x, y] = if a = y ∧ b = x then 1 else 0 := by + simp [exchange, swap, funext_iff, Fin.forall_fin_succ, eq_comm, and_comm] + have he := pair_swap j (fun a b : Bool => ![a, b]) (exchange F Bool (1 : Fin 2)) + (by intro a b x y; rw [h]; split_ifs <;> rfl) + simp only [run, matPower, paired, he, Fintype.prod_ite_zero, prod_const_one, + forall_and, ← funext_iff, Prod.ext_iff] + +open scoped Classical in +theorem run_diagonal (m j : ℕ) (A : Matrix X X F) (h : ∀ x y, A x y ≠ 0 → x = y) + (x y : Word m j X) (he : run m j A x y ≠ 0) : x = y := by + induction j generalizing X with + | zero => + change (∏ i, A (x i) (y i)) ≠ 0 at he + exact funext fun i => h _ _ (prod_ne_zero_iff.mp he i (mem_univ _)) + | succ j ih => + apply ih (matPower (fun _ : Fin 100 => A)) _ x y he + exact fun _ _ he => funext fun i => h _ _ (prod_ne_zero_iff.mp he i (mem_univ _)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Composing ordered approximations and cutting off exceptional grades -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Prices.Motion + +variable {X F : Type} [Field F] [Fintype X] + +open scoped Classical in +omit [Fintype X] in +/-- Discarding all transitions with either endpoint in an exceptional +set increases the rank loss by at most twice the size of the set. -/ +theorem trim [Finite X] {A B : Matrix X X F} {b : ℝ} (h : Low (A - B) b) (S : Finset X) : + ∃ C, Low (A - C) (b + 2 * S.card) ∧ ∀ x y, C x y ≠ 0 → x ∉ S ∧ y ∉ S ∧ B x y ≠ 0 := by + let : Fintype X := Fintype.ofFinite X + let P := Matrix.diagonal (fun x : X => if x ∈ S then (1 : F) else 0) + let Q := Matrix.diagonal (fun x : X => if x ∈ S then (0 : F) else 1) + have hq : P = 1 - Q := by + ext x y + by_cases he : x = y + · subst y; by_cases hx : x ∈ S <;> simp [P, Q, hx] + · simp [P, Q, he] + refine ⟨Q * B * Q, ?_, ?_⟩ + · have hp : Low P S.card := diag_low S + rw [show A - Q * B * Q = (A - B) + (P * B + Q * B * P) by + rw [hq, sub_mul, mul_sub, one_mul, mul_one]; abel, + two_mul] + exact h.add ((hp.right B).add (hp.left _)) + · intro x y hxy + simpa [Q, Matrix.mul_diagonal, Matrix.diagonal_mul, mul_ite, ite_mul, and_comm, and_left_comm] + using hxy + +open scoped Classical in +/-- The retained paths respect the order at every site. This controls +the finer blocks after the three parity factors are multiplied. -/ +def Plan (j : ℕ) (o : Order X) (A : Matrix X X F) (K : ℝ) : Prop := + ∃ C : ℝ, 0 ≤ C ∧ ∀ (m : ℕ) (t : ℝ), 0 < t → + ∃ B : Matrix (Word m j X) (Word m j X) F, + Low (run m j A - B) (C * Fintype.card (Word m j X) * Real.exp (-t ^ 2 * bits m j)) ∧ + ∀ x y, B x y ≠ 0 → + (∀ i, (treeOrder j o).rel (x i) (y i)) ∧ edits m j X x y ≤ K * t * bits m j + +variable {j : ℕ} {o p : Order X} {A B : Matrix X X F} {K L : ℝ} + +open scoped Classical in +theorem Plan.of_order (h : Plan j o A K) (hp : ∀ x y, o.rel x y → p.rel x y) : + Plan j p A K := by + obtain ⟨C, hC, h⟩ := h + refine ⟨C, hC, fun m t ht => ?_⟩ + obtain ⟨P, hP, hs⟩ := h m t ht + refine ⟨P, hP, fun x y he => ?_⟩ + exact ⟨fun i => tree_mono _ hp _ _ ((hs x y he).1 i), (hs x y he).2⟩ + +open scoped Classical in +theorem Plan.mul (h : Plan j o A K) (h' : Plan j o B L) : Plan j o (A * B) (K + L) := by + obtain ⟨C, hC, h⟩ := h + obtain ⟨D, hD, h'⟩ := h' + refine ⟨C + D, add_nonneg hC hD, fun m t ht => ?_⟩ + obtain ⟨P, hP, hs⟩ := h m t ht + obtain ⟨Q, hQ, hs'⟩ := h' m t ht + refine ⟨P * Q, ?_, fun x y he => ?_⟩ + · rw [run_mul, add_mul, add_mul] + exact approx_mul hP hQ + · obtain ⟨z, _, hz⟩ := exists_ne_zero_of_sum_ne_zero he + obtain ⟨hr, hd⟩ := hs x z (left_ne_zero_of_mul hz) + obtain ⟨hr', hd'⟩ := hs' z y (right_ne_zero_of_mul hz) + refine ⟨fun i => (treeOrder j o).trans (hr i) (hr' i), ?_⟩ + rw [add_mul, add_mul] + exact (edits_triangle _ _ _ x z y).trans (add_le_add hd hd') + +open scoped Classical in +/-- Rescale the test on the coarse alphabet to the original word length. -/ +theorem Focus.test (h : Focus o.grade K) (j : ℕ) : + ∃ C : ℝ, 0 ≤ C ∧ ∀ m (t : ℝ), 0 < t → + ∃ S : Finset (Word m j X), (S.card : ℝ) ≤ + C * Fintype.card (Word m j X) * Real.exp (-t ^ 2 * bits m j) ∧ + ∀ x ∉ S, ∀ y ∉ S, height (treeOrder j o).grade y - height (treeOrder j o).grade x ≤ + K * t * bits m j := by + obtain ⟨C, hC, h⟩ := tree_focus j o h + refine ⟨C, hC, fun m t ht => ?_⟩ + obtain ⟨S, hS, hs⟩ := h (Fin m) (10 ^ j * t) (by positivity) + have hb : (bits m j : ℝ) = m * ((10 : ℝ) ^ j) ^ 2 := by + rw [bits, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, ← pow_mul, mul_comm j 2, pow_mul] + norm_num + simp only [Fintype.card_fin] at hS hs + refine ⟨S, ?_, fun x hx y hy => (hs x hx y hy).trans_eq ?_⟩ + · rw [hb, show -t ^ 2 * (m * ((10 : ℝ) ^ j) ^ 2) = -(10 ^ j * t) ^ 2 * m by ring] + exact hS + · rw [hb]; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- +# Hierarchical elimination + +Grouping a hundred blocks multiplies a grade's deviation coefficient +by ten. After parity elimination the middle coefficient is at most +`5K+2`, and the two outer coefficients are four each. Since +`5K+10 ≤ 7.5K`, there is room to charge one more level of edits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Prices.Motion + +variable {X F : Type} [Field F] [Fintype X] {o : Order X} {A : Matrix X X F} {K L : ℝ} + +open scoped Classical in +private theorem base (h : o.Unitriangular A) (hk : Focus o.grade K) (hK : 0 ≤ K) : + Plan 0 o A (4 * K) := by + obtain ⟨C, hC, hF⟩ := hk.test 0 + refine ⟨2 * C, by positivity, fun m t ht => ?_⟩ + obtain ⟨S, hS, hs⟩ := hF m t ht + have hp : Low (run m 0 A - run m 0 A) 0 := by rw [sub_self]; exact Low.zero + obtain ⟨P, hP, hp⟩ := trim hp S + refine ⟨P, hP.mono (by linarith only [hS]), fun x y he => ?_⟩ + obtain ⟨hx, hy, hxy⟩ := hp x y he + change (∏ i, A (x i) (y i)) ≠ 0 at hxy + have hr i : o.rel (x i) (y i) := h.2 _ _ (prod_ne_zero_iff.mp hxy i (mem_univ _)) + refine ⟨hr, ?_⟩ + have hd := sum_le_sum (s := univ) fun i _ => mismatch_grade o (hr i) + rw [sum_sub_distrib] at hd + exact (hd.trans (hs x hx y hy)).trans (by gcongr; linarith) + +open scoped Classical in +private theorem refine_plan {j : ℕ} (hk : Focus o.grade K) (hL : L ≤ 30 * K) + (hp : Plan j o.block (matPower (fun _ : Fin 100 => A)) L) : Plan (j + 1) o A (4 * K) := by + obtain ⟨C, hC, hF⟩ := hk.test (j + 1) + obtain ⟨D, hD, hP⟩ := hp + refine ⟨D + 2 * C, by positivity, fun m t ht => ?_⟩ + have hb : (bits m (j + 1) : ℝ) = 100 * (bits m j : ℝ) := by + simp only [bits, pow_succ, Nat.cast_mul, Nat.cast_ofNat]; ring + obtain ⟨S, hS, hs⟩ := hF m t ht + obtain ⟨P, hP, hp⟩ := hP m (10 * t) (by positivity) + have he : -(10 * t) ^ 2 * bits m j = -t ^ 2 * bits m (j + 1) := by rw [hb]; ring + rw [he] at hP + change Low (run m (j + 1) A - P) + (D * Fintype.card (Word m (j + 1) X) * Real.exp (-t ^ 2 * bits m (j + 1))) at hP + obtain ⟨Q, hQ, hq⟩ := trim hP S + refine ⟨Q, hQ.mono (by linarith only [hS]), fun x y he => ?_⟩ + obtain ⟨hx, hy, hxy⟩ := hq x y he + obtain ⟨hr, hd⟩ := hp x y hxy + refine ⟨hr, ?_⟩ + have hu := sum_le_sum (s := univ) fun i _ => refine_fee j o (x i) (y i) (hr i) + rw [sum_add_distrib, sum_sub_distrib] at hu + have hg := hs x hx y hy + have hcost : L * (10 * t) * bits m j ≤ 3 * K * t * bits m (j + 1) := by + rw [hb] + linarith only [mul_le_mul_of_nonneg_right hL (by positivity : 0 ≤ t * bits m j)] + exact (hu.trans (add_le_add (hd.trans hcost) hg)).trans_eq (by ring) + +open scoped Classical in +theorem elimination [Nonempty X] (j : ℕ) (h : o.Unitriangular A) (hk : Focus o.grade K) + (hK : 4 ≤ K) : Plan j o A (4 * K) := by + induction j generalizing X K with + | zero => exact base h hk (by linarith) + | succ j ih => + obtain ⟨P, Q, R, hP, hQ, hR, he⟩ := Order.factor (o.block_unit h) + have hb (a : ℕ) : Focus (o.block.outer a).grade 4 := + binary_focus _ fun x => by unfold Order.outer; dsimp; split <;> omega + have hm : Focus o.block.middle.grade ((10 * K + 4) / 2) := hk.block.half + have h₁ : Plan j o.block P (4 * 4) := (ih hP (hb 1) le_rfl).of_order fun _ _ h => h.1 + have h₂ : Plan j o.block Q (4 * ((10 * K + 4) / 2)) := + (ih hQ hm (by linarith)).of_order fun _ _ h => h.1 + have h₃ : Plan j o.block R (4 * 4) := (ih hR (hb 0) le_rfl).of_order fun _ _ h => h.1 + exact refine_plan hk (by linarith) (he.symm ▸ (h₁.mul h₂).mul h₃) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # The dimension-independent swap estimate over an arbitrary field -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Prices.Motion Finset + +open scoped Classical in +private def shearOrder (b : Bool) : Order (Col 1) where + rel x y := x = y ∨ x 0 = b ∧ y 0 ≠ b + grade x := if x 0 = b then 0 else 1 + refl _ := Or.inl rfl + trans h k := by grind + inc h he := by obtain ⟨hx, hy⟩ := h.resolve_left he; simp [hx, hy] + +variable {F : Type} [Field F] + +open scoped Classical in +private theorem triangular (b : Bool) (v : F) : + (shearOrder b).Unitriangular (shear (1 : Fin 2) b v) := by + have h (x : Col 1) (hx : starts 1 b x) : swap 1 x 0 ≠ b := by simpa [swap] using hx.2 + constructor + · intro x + by_cases hx : starts 1 b x + · have he : x ≠ swap 1 x := fun he => h x hx ((congrFun he.symm 0).trans hx.1) + simp [shear, hx, he] + · simp [shear, hx] + · intro x y he + by_cases hxy : x = y + · exact Or.inl hxy + have hh : starts 1 b x ∧ y = swap 1 x := by + by_contra h' + by_cases hx : starts 1 b x + · have hy : y ≠ swap 1 x := fun e => h' ⟨hx, e⟩ + simp [shear, hx, hy, Ne.symm hxy] at he + · simp [shear, hx, Ne.symm hxy] at he + exact Or.inr ⟨hh.1.1, hh.2 ▸ h x hh.1⟩ + +open scoped Classical in +private theorem shear_plan (j : ℕ) (b : Bool) (v : F) : + ∃ C : ℝ, 0 ≤ C ∧ ∀ m (t : ℝ), 0 < t → + Within (edits m j (Col 1)) (run m j (shear (1 : Fin 2) b v)) + (C * Fintype.card (Word m j (Col 1)) * Real.exp (-t ^ 2 * bits m j)) (16 * t * bits m j) + := by + have hu : Focus (shearOrder b).grade 4 := + binary_focus _ fun x => by unfold shearOrder; dsimp; split <;> omega + obtain ⟨C, hC, h⟩ := elimination j (triangular b v) hu le_rfl + refine ⟨C, hC, fun m t ht => ?_⟩ + obtain ⟨B, hB, hp⟩ := h m t ht + refine ⟨B, hB, fun x y h => ?_⟩ + simpa only [show (4 : ℝ) * 4 = 16 by norm_num] using (hp x y h).2 + +open scoped Classical in +theorem swap_bound (F : Type) [Field F] (j : ℕ) : + ∃ C : ℝ, 0 ≤ C ∧ ∀ m : ℕ, SwapBound F (Word m j Bool) (edits m j Bool) (bits m j) C := by + obtain ⟨C, hC, h⟩ := shear_plan j false (1 : F) + obtain ⟨D, hD, h'⟩ := shear_plan j true (-1 : F) + refine ⟨2 * C + D, by positivity, fun m t ht => ?_⟩ + have hd : Within (edits m j (Col 1)) (run m j (signs F (1 : Fin 2))) 0 0 := by + apply Within.exact + intro x y he + have hh : x = y := run_diagonal m j _ (by + intro u v hu + by_contra hne + simp [signs, hne] at hu) x y he + rw [hh, edits_refl] + have hs := h m t ht + have hs' := h' m t ht + have tri := edits_triangle m j (Col 1) + have he := hs.mul (hs'.mul (hs.mul hd tri) tri) tri + rw [← run_mul, ← run_mul, ← run_mul, ← exchange_shears] at he + have hcard : (Fintype.card (Word m j (Col 1)) : ℝ) = (Fintype.card (Word m j Bool) : ℝ) ^ 2 := by + rw [card_word, card_word] + simp only [Col, Fintype.card_fun, Fintype.card_fin, Nat.reduceAdd, Nat.cast_pow] + rw [← pow_mul, ← pow_mul, mul_comm] + have hm : (run m j (exchange F Bool (1 : Fin 2))).submatrix (paired m j) (paired m j) = + swapMatrix F (Word m j Bool) := by + ext x y + simp only [Matrix.submatrix_apply, paired_swap, swapMatrix] + split_ifs <;> rfl + obtain ⟨B, hB, hp⟩ := he.pull (paired m j) + rw [hm, hcard] at hB + refine ⟨B, hB.mono (by linarith), fun x y hxy => (paired_cost m j x y).trans ?_⟩ + linarith only [hp x y hxy] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # From displacement to row support on a binary alphabet -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Prices.Motion Interior Real + +variable {F W : Type} [Field F] [Fintype W] + +open scoped Classical in +private theorem volume {n : ℕ} [NeZero n] (d : W → W → ℝ) {V p : ℝ} + (hV : 1 ≤ V) (hm : ∀ x, ∑ y, exp (-100 * d x y) ≤ V) + {M : Matrix (Fin n → W) (Fin n → W) F} + (h : ∀ x y, M x y ≠ 0 → ∑ i ∈ univ.erase 0, d (x i) (y i) ≤ p) : + Rows M (Fintype.card W * V ^ n * exp (100 * p)) := by + intro x + let S : Finset (Fin n → W) := {y | M x y ≠ 0} + let f (i : Fin n) (z : W) := if i = 0 then 1 else exp (-100 * d (x i) z) + have hf i z : 0 ≤ f i z := by unfold f; split <;> positivity + have hl (y) (hy : y ∈ S) : exp (-(100 * p)) ≤ ∏ i, f i (y i) := by + rw [← prod_erase_mul _ _ (mem_univ 0), show f 0 (y 0) = 1 by simp [f], mul_one] + have he : ∏ i ∈ univ.erase 0, f i (y i) = exp (-100*∑ i ∈ univ.erase 0, d (x i) (y i)) := by + rw [mul_sum, exp_sum] + exact prod_congr rfl (fun i hi => ite_eq_right (mem_erase.mp hi).1) + rw [he, exp_le_exp] + linarith [h x y (mem_filter.mp hy).2] + have hr : ∏ i ∈ univ.erase (0 : Fin n), (∑ y, f i y) ≤ V ^ n := by + apply le_trans (b := ∏ _i ∈ univ.erase (0 : Fin n), V) + · apply prod_le_prod₀ (fun i _ => sum_nonneg fun y _ => hf i y) + intro i hi + simpa only [f, ite_eq_right (mem_erase.mp hi).1] using hm (x i) + · rw [prod_const] + exact pow_le_pow_right₀ hV (by simp) + have hh : (S.card : ℝ) * exp (-(100 * p)) ≤ Fintype.card W * V ^ n := calc + _ = ∑ _y ∈ S, exp (-(100 * p)) := by simp + _ ≤ ∑ y ∈ S, ∏ i, f i (y i) := sum_le_sum hl + _ ≤ ∑ y : Fin n → W, ∏ i, f i (y i) := + sum_le_sum_of_subset_of_nonneg (subset_univ _) (fun y _ _ => prod_nonneg (fun i _ => hf _ _)) + _ ≤ _ := by + rw [← Fintype.prod_sum, ← mul_prod_erase _ _ (mem_univ 0)] + rw [show ∑ y, f 0 y = (Fintype.card W : ℝ) by simp [f]] + exact mul_le_mul_of_nonneg_left hr (by positivity) + rwa [exp_neg, ← div_eq_mul_inv, div_le_iff₀ (exp_pos _)] at hh + +open scoped Classical in +/-- The quantity computed by `100000 / log 2`. -/ +def coefficient : ℝ := 100000 / log 2 + +open scoped Classical in +theorem one_le_coefficient : 1 ≤ coefficient := by + rw [coefficient, le_div_iff₀ (log_pos (by norm_num))] + linarith [log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2)] + +open scoped Classical in +theorem binary_power (k : ℕ) {C η : ℝ} (hC : 0 ≤ C) (hη : 0 < η) + (h : ∀ m, SwapBound F (Word m k Bool) (edits m k Bool) (bits m k) C) : + ∃ H : ℝ, 0 ≤ H ∧ ∀ (m : ℕ) (M : Matrix (Word m k Bool) (Word m k Bool) F), ∃ N, + Low (matPower (fun _ : Fin (2 ^ k) => M) - N) (H * ((2 : ℝ) ^ bits m k) ^ ((2 : ℝ) ^ k - 2 * + η ^ 2)) ∧ + Rows N (((2 : ℝ) ^ bits m k) ^ (2 + coefficient * η * Real.sqrt ((2 : ℝ) ^ k))) := by + obtain ⟨H, hH, hf⟩ := fold k hC (mul_pos (by norm_num : (0 : ℝ) < 2) hη) + refine ⟨H, hH, fun m M => ?_⟩ + let b := bits m k + let R := (2 : ℝ) ^ b + have hR : 0 < R := by unfold R; positivity + obtain ⟨N, hN, hcost⟩ := hf F _ _ b (edits_refl _ _ _) (edits_triangle _ _ _) (h m) M + have hcard : (Fintype.card (Word m k Bool) : ℝ) = R := by rw [card_word]; simp [R, b] + have hs := volume (edits m k Bool) (one_le_pow₀ (by norm_num)) (edits_mass _ _) hcost + rw [hcard] at hN hs + have he (x : ℝ) : R ^ x = exp (b * log 2 * x) := by + rw [rpow_def_of_pos hR, show log R = b * log 2 from log_pow _ _] + refine ⟨N, hN.mono ?_, hs.mono ?_⟩ + · change _ ≤ H * R ^ ((2 : ℝ) ^ k - 2 * η ^ 2) + have hu : exp (-(2 * η) ^ 2 * b) ≤ R ^ (-(2 * η ^ 2)) := by + rw [he, exp_le_exp] + have hlog : log 2 ≤ 2 := (log_le_sub_one_of_pos (by norm_num)).trans (by norm_num) + linarith only [mul_le_mul_of_nonneg_right hlog (show 0 ≤ 2 * η ^ 2 * b by positivity)] + rw [sub_eq_add_neg, rpow_add hR, show (2 : ℝ) ^ k + = ((2 ^ k : ℕ) : ℝ) by norm_cast, rpow_natCast, ← mul_assoc] + exact mul_le_mul_of_nonneg_left hu (by positivity) + · change _ ≤ R ^ (2 + coefficient * η * Real.sqrt ((2 : ℝ) ^ k)) + have hn : ((2 : ℝ) ^ m) ^ (2 ^ k : ℕ) ≤ R := by + rw [← pow_mul] + apply pow_le_pow_right₀ (by norm_num) + exact Nat.mul_le_mul_left m (Nat.pow_le_pow_left (by norm_num : 2 ≤ 100) _) + rw [rpow_add hR, rpow_two, pow_two, he] + apply mul_le_mul (mul_le_mul_of_nonneg_left hn hR.le) _ (by positivity) (by positivity) + apply le_of_eq + congr 1 + unfold coefficient + field_simp + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Restricting from the next geometric alphabet size -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Prices.Motion Interior Filter + +variable {F W : Type} [Field F] [Fintype W] + +open scoped Classical in +private theorem restrict_power (n d : ℕ) (hd : 0 < d) (hd' : d ≤ Fintype.card W) + {r p : ℝ} (h : ∀ M : Matrix W W F, ∃ N, Low (matPower (fun _ : Fin n => M) - N) r ∧ Rows N p) + (B : Matrix (Fin d) (Fin d) F) : ∃ A, Low (matPower (fun _ : Fin n => B) - A) r ∧ Rows A p := by + have : Nonempty (Fin d) := Fin.pos_iff_nonempty.mp hd + let e : Fin d ↪ W := (Fin.castLEEmb hd').trans (Fintype.equivFin W).symm.toEmbedding + let f (x : Fin n → Fin d) := e ∘ x + have hf : Function.Injective f := fun _ _ he => funext fun i => e.injective (congrFun he i) + let M := B.submatrix (Function.invFun e) (Function.invFun e) + have he (x) := Function.leftInverse_invFun e.injective x + obtain ⟨N, hr, hp⟩ := h M + refine ⟨N.submatrix f f, ?_, fun x => ?_⟩ + · convert low_pull hr f using 1 + ext x y + simp only [Matrix.submatrix_apply, Matrix.sub_apply, M, f, matPower, Function.comp_apply, he] + · apply le_trans _ (hp (f x)) + apply Nat.cast_le.mpr + rw [← card_image_of_injective _ hf] + apply card_le_card + rintro y hy + obtain ⟨z, hz, rfl⟩ := mem_image.mp hy + exact mem_filter.mpr ⟨mem_univ _, (mem_filter.mp hz).2⟩ + +open scoped Classical in +private theorem upper_size (k d : ℕ) (hd : 1 ≤ d) : ∃ m : ℕ, d ≤ Fintype.card (Word m k Bool) ∧ + (2 : ℝ) ^ bits m k ≤ (2 : ℝ) ^ (100 ^ k : ℕ) * d := by + let b := (2 : ℝ) ^ (100 ^ k : ℕ) + have hb : 1 < b := one_lt_pow₀ (by norm_num) (by positivity) + obtain ⟨j, hlo, hhi⟩ := exists_nat_pow_near (by exact_mod_cast hd : 1 ≤ (d : ℝ)) hb + have he (m : ℕ) : (2 : ℝ) ^ bits m k = b ^ m := by rw [bits, mul_comm, pow_mul] + refine ⟨j + 1, ?_, ?_⟩ + · rw [card_word, Fintype.card_bool] + rw [← he] at hhi + exact_mod_cast hhi.le + · rw [he, pow_succ'] + exact mul_le_mul_of_nonneg_left hlo (by positivity) + +open scoped Classical in +/-- Constant-factor padding and the fixed interpolation cost are +absorbed by an arbitrarily small positive exponent. -/ +private theorem absorb (k : ℕ) {H a b : ℝ} (hH : 0 ≤ H) (ha : 0 ≤ a) (hb : a < b) : + ∀ᶠ d : ℕ in atTop, ∀ R : ℝ, 0 ≤ R → R ≤ (2 : ℝ) ^ (100 ^ k : ℕ) * d → + H * R ^ a ≤ (d : ℝ) ^ b := by + let U := (2 : ℝ) ^ (100 ^ k : ℕ) + have hg := (tendsto_rpow_atTop (sub_pos.mpr hb)).comp tendsto_natCast_atTop_atTop + filter_upwards [eventually_ge_atTop 1, hg.eventually_ge_atTop (H * U ^ a)] with d hd hh R hR hR' + calc + _ ≤ H * (U * d) ^ a := mul_le_mul_of_nonneg_left (Real.rpow_le_rpow hR hR' ha) hH + _ = (H * U ^ a) * (d : ℝ) ^ a := by + rw [Real.mul_rpow (by positivity) (by positivity), mul_assoc] + _ ≤ (d : ℝ) ^ (b - a) * (d : ℝ) ^ a := mul_le_mul_of_nonneg_right hh (by positivity) + _ = _ := by rw [← Real.rpow_add (by positivity), sub_add_cancel] + +open scoped Classical in +theorem of_swap (h : ∀ (F : Type) [Field F] (k : ℕ), ∃ C : ℝ, 0 ≤ C ∧ + ∀ m : ℕ, SwapBound F (Word m k Bool) (edits m k Bool) (bits m k) C) : Folds coefficient := by + intro F _ k η hη he + obtain ⟨C, hC, hs⟩ := h F k + obtain ⟨H, hH, hh⟩ := binary_power k hC hη hs + let p := coefficient * η * Real.sqrt ((2 : ℝ) ^ k) + have hp : 0 ≤ p := by have := one_le_coefficient; unfold p; positivity + have hr := absorb k hH (show 0 ≤ (2 : ℝ) ^ k - 2 * η ^ 2 by linarith) + (show (2 : ℝ) ^ k - 2 * η ^ 2 < (2 : ℝ) ^ k - η ^ 2 by nlinarith) + have hm := absorb k zero_le_one (show 0 ≤ 2 + p by linarith) (show 2 + p < 3 + p by linarith) + filter_upwards [eventually_ge_atTop 1, hr, hm] with d hd h₁ h₂ B + obtain ⟨m, hlo, hhi⟩ := upper_size k d hd + obtain ⟨A, ha, hb⟩ := restrict_power _ _ (by omega) hlo (hh m) B + refine ⟨A, ha.mono (h₁ _ (by positivity) hhi), hb.mono ?_⟩ + simpa only [one_mul] using h₂ _ (by positivity) hhi + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Folding/Transfer.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Folding/Transfer.lean new file mode 100644 index 0000000000..fabd351246 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Folding/Transfer.lean @@ -0,0 +1,923 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.Convex.SpecificFunctions.Basic +public import Mathlib.Analysis.SpecialFunctions.Trigonometric.Series +public import Mathlib.Data.Fintype.BigOperators +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.TreePrice +public import Mathlib.Analysis.SpecialFunctions.Exp +public import Mathlib.LinearAlgebra.Matrix.Kronecker +public import Mathlib.Analysis.Real.Sqrt +public import Mathlib.Algebra.BigOperators.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Dense +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics + +/-! # Concentration of additive grades on finite words -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Real + +variable {X I : Type} [Fintype X] [Fintype I] [DecidableEq I] + +/-- The sum of `(g (x i) : ℝ)` indexed by `i`. -/ +def height (g : X → ℕ) (x : I → X) : ℝ := ∑ i, (g (x i) : ℝ) + +/-- The prefactor in the tail bound is fixed before taking word powers. -/ +def Focus (g : X → ℕ) (K : ℝ) : Prop := + ∃ C : ℝ, 0 ≤ C ∧ ∀ (I : Type) [Fintype I] [DecidableEq I] (t : ℝ), 0 < t → + ∃ S : Finset (I → X), (S.card : ℝ) ≤ C * Fintype.card (I → X) * exp (-t ^ 2 * Fintype.card I) ∧ + ∀ x ∉ S, ∀ y ∉ S, height g y - height g x ≤ K * t * Fintype.card I + +private theorem moment (f : X → ℝ) (hf : ∀ x, |f x| ≤ 1) (hz : ∑ x, f x = 0) (t : ℝ) : + ∑ x, exp (t * f x) ≤ Fintype.card X * exp (t ^ 2) := by + have h (x) : exp (t * f x) ≤ cosh t + f x * ((exp t - exp (-t)) / 2) := by + obtain ⟨hl, hr⟩ := abs_le.mp (hf x) + have he := convexOn_exp.2 (Set.mem_univ t) (Set.mem_univ (-t)) + (show 0 ≤ (1 + f x) / 2 by linarith) (show 0 ≤ (1 - f x) / 2 by linarith) + (by ring : (1 + f x) / 2 + (1 - f x) / 2 = 1) + simp only [smul_eq_mul, show (1 + f x) / 2 * t + (1 - f x) / 2 * (-t) = t * f x by ring] at he + rw [cosh_eq] + linarith only [he] + have he := sum_le_sum (s := univ) fun x _ => h x + rw [sum_add_distrib, ← sum_mul, hz, zero_mul, add_zero, sum_const, nsmul_eq_mul, card_univ] at he + exact he.trans (mul_le_mul_of_nonneg_left + ((cosh_le_exp_half_sq t).trans (exp_le_exp.mpr (by nlinarith [sq_nonneg t]))) (by positivity)) + +open Classical in +private theorem tail (f : X → ℝ) (hf : ∀ x, |f x| ≤ 1) (hz : ∑ x, f x = 0) {t : ℝ} (ht : 0 < t) : + (#{x : I → X | 2 * t * Fintype.card I < ∑ i, f (x i)} : ℝ) ≤ + Fintype.card (I → X) * exp (-t ^ 2 * Fintype.card I) := by + let n := Fintype.card I + let S : Finset (I → X) := {x | 2 * t * n < ∑ i, f (x i)} + apply le_of_mul_le_mul_right _ (exp_pos (t * (2 * t * n))) + calc + _ = ∑ _ ∈ S, exp (t * (2 * t * n)) := by simp [S, n] + _ ≤ ∑ x ∈ S, exp (t * ∑ i, f (x i)) := sum_le_sum fun x hx => + exp_le_exp.mpr (mul_le_mul_of_nonneg_left (mem_filter.mp hx).2.le ht.le) + _ ≤ ∑ x : I → X, exp (t * ∑ i, f (x i)) := + sum_le_sum_of_subset_of_nonneg (subset_univ _) (by intros; positivity) + _ = (∑ x, exp (t * f x)) ^ n := by + simp_rw [mul_sum, exp_sum] + rw [← Fintype.prod_sum (fun (_ : I) (x : X) => exp (t * f x)), prod_const, card_univ] + _ ≤ (Fintype.card X * exp (t ^ 2)) ^ n := + pow_le_pow_left₀ (by positivity) (moment f hf hz t) _ + _ = _ := by + rw [Fintype.card_fun, Nat.cast_pow, mul_pow, ← exp_nat_mul, mul_assoc, ← exp_add] + unfold n + ring_nf + +theorem binary_focus [Nonempty X] (g : X → ℕ) (hg : ∀ x, g x ≤ 1) : Focus g 4 := by + classical + let a := (∑ x, (g x : ℝ)) / Fintype.card X + have hc : 0 < (Fintype.card X : ℝ) := by positivity + have he : a * Fintype.card X = ∑ x, (g x : ℝ) := div_mul_cancel₀ _ hc.ne' + have ha : 0 ≤ a := by unfold a; positivity + have hle (x) : (g x : ℝ) ≤ 1 := by exact_mod_cast hg x + have ha' : a ≤ 1 := (div_le_one hc).mpr (by simpa using sum_le_sum (s := univ) fun x _ => hle x) + let f x := (g x : ℝ) - a + have hz : ∑ x, f x = 0 := by simp [f, sum_sub_distrib, ← he, mul_comm] + have hf (x) : |f x| ≤ 1 := by unfold f; rw [abs_le]; constructor <;> linarith [hle x] + refine ⟨2, by norm_num, ?_⟩ + intro I _ _ t ht + let S (h : X → ℝ) : Finset (I → X) := {x | 2 * t * Fintype.card I < ∑ i, h (x i)} + have h₁ := tail (I := I) f hf hz ht + have h₂ := tail (I := I) (-f) (by simpa using hf) (by simp [hz]) ht + refine ⟨S f ∪ S (-f), ?_, ?_⟩ + · have he : ((S f ∪ S (-f)).card : ℝ) ≤ (S f).card + (S (-f)).card := by + exact_mod_cast card_union_le (S f) (S (-f)) + unfold S at he ⊢ + linarith only [he, h₁, h₂] + · intro x hx y hy + have hx' := (notMem_union.mp hx).2 + have hy' := (notMem_union.mp hy).1 + simp only [S, mem_filter, mem_univ, true_and, not_lt, Pi.neg_apply, sum_neg_distrib, + f, sum_sub_distrib] at hx' hy' + unfold height + linarith only [hx', hy'] + +/-- The indexing data represented by `Fin 100 → X`. -/ +abbrev Block (X : Type) := Fin 100 → X + +/-- The sum of `g (x i)` indexed by `i`. -/ +def blockGrade (g : X → ℕ) (x : Block X) := ∑ i, g (x i) + +theorem Focus.block {g : X → ℕ} {K : ℝ} (h : Focus g K) : Focus (blockGrade g) (10 * K) := by + classical + obtain ⟨C, hC, h⟩ := h + refine ⟨C, hC, ?_⟩ + intro I _ _ t ht + let e := Equiv.curry I (Fin 100) X + have hc : (Fintype.card (I × Fin 100) : ℝ) = Fintype.card I * 100 := by simp + have he (x : I → Block X) : height (blockGrade g) x = height g (e.symm x) := by + simp only [height, blockGrade, Nat.cast_sum, Fintype.sum_prod_type] + rfl + obtain ⟨S, hS, hd⟩ := h (I × Fin 100) (t / 10) (by positivity) + refine ⟨S.map e.toEmbedding, ?_, ?_⟩ + · rw [card_map] + rw [Fintype.card_congr e, hc, show -(t / 10) ^ 2 * (Fintype.card I * 100) + = -t ^ 2 * Fintype.card I by ring] at hS + exact hS + · intro x hx y hy + rw [he, he] + rw [mem_map_equiv] at hx hy + have hh := hd _ hx _ hy + rw [hc] at hh + linarith only [hh] + +theorem Focus.half [Nonempty X] {g : X → ℕ} {K : ℝ} (h : Focus g K) : + Focus (fun x => g x / 2) ((K + 4) / 2) := by + classical + obtain ⟨C, hC, h⟩ := h + obtain ⟨D, hD, h'⟩ := binary_focus (fun x => g x % 2) (fun _ => by omega) + refine ⟨C + D, add_nonneg hC hD, ?_⟩ + intro I _ _ t ht + obtain ⟨S, hS, hs⟩ := h I t ht + obtain ⟨T, hT, ht'⟩ := h' I t ht + refine ⟨S ∪ T, ?_, ?_⟩ + · have hh : ((S ∪ T).card : ℝ) ≤ S.card + T.card := by exact_mod_cast card_union_le S T + linarith only [hh, hS, hT] + · intro x hx y hy + have he (v : I → X) : 2 * height (fun u => g u / 2) v + height (fun u => g u % 2) v + = height g v := by + simp only [height, mul_sum, ← sum_add_distrib] + apply sum_congr rfl + intro i _ + exact_mod_cast (show 2 * (g (v i) / 2) + g (v i) % 2 = g (v i) by omega) + obtain ⟨hx, hx'⟩ := notMem_union.mp hx + obtain ⟨hy, hy'⟩ := notMem_union.mp hy + linarith only [he x, he y, hs x hx y hy, ht' y hy' x hx'] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # A quantitative one-register approximation to a swap -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Prices.Motion + +open scoped Classical in +/-- Evaluates `if x = (y.2, y.1) then 1 else 0` at the input `x y`. -/ +def swapMatrix (F W : Type) [Field F] : Matrix (W × W) (W × W) F := + fun x y => if x = (y.2, y.1) then 1 else 0 + +open scoped Classical in +/-- The swap bound of type `Prop` for the given inputs. -/ +def SwapBound (F W : Type) [Field F] [Fintype W] (dist : W → W → ℝ) (B : ℕ) (C : ℝ) : Prop := + ∀ t : ℝ, 0 < t → ∃ N : Matrix (W × W) (W × W) F, + Low (swapMatrix F W - N) (C * (Fintype.card W : ℝ) ^ 2 * Real.exp (-t ^ 2 * B)) ∧ + ∀ x y, N x y ≠ 0 → dist x.1 y.1 ≤ 48 * t * B + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Matrix approximation with a bound on displacement -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Prices.Motion +open scoped Kronecker + +variable {X Y F : Type} [Field F] {D : X → X → ℝ} {M N : Matrix X X F} + {a b r s : ℝ} + +open scoped Classical in +theorem low_pull (h : Low M r) (f : Y → X) : Low (M.submatrix f f) r := by + obtain ⟨I, _, hi, P, Q, rfl⟩ := h + exact ⟨I, inferInstance, hi, P.submatrix f id, Q.submatrix id f, rfl⟩ + +open scoped Classical in +theorem low_kron {N : Matrix Y Y F} (h : Low M r) (h' : Low N s) : Low (M ⊗ₖ N) (r * s) := by + obtain ⟨I, _, hi, P, Q, rfl⟩ := h + obtain ⟨J, _, hj, S, T, rfl⟩ := h' + refine ⟨I × J, inferInstance, ?_, P ⊗ₖ S, Q ⊗ₖ T, Matrix.mul_kronecker_mul _ _ _ _⟩ + rw [Fintype.card_prod, Nat.cast_mul] + exact mul_le_mul hi hj (by positivity) ((by positivity : 0 ≤ (Fintype.card I : ℝ)).trans hi) + +open scoped Classical in +/-- The condition `∀ x y, M x y ≠ 0 → D x y ≤ p` on the specified data. -/ +def Bounded (D : X → X → ℝ) (M : Matrix X X F) (p : ℝ) : Prop := + ∀ x y, M x y ≠ 0 → D x y ≤ p + +open scoped Classical in +/-- The condition `∃ N, Low (M - N) r ∧ Bounded D N p` on the specified data. -/ +def Within (D : X → X → ℝ) (M : Matrix X X F) (r p : ℝ) : Prop := + ∃ N, Low (M - N) r ∧ Bounded D N p + +open scoped Classical in +theorem Bounded.mono (h : Bounded D M a) (hab : a ≤ b) : Bounded D M b := + fun x y hxy => (h x y hxy).trans hab + +open scoped Classical in +theorem Bounded.sub (h : Bounded D M a) (h' : Bounded D N a) : Bounded D (M - N) a := by + intro x y he + by_cases hx : M x y = 0 + · exact h' _ _ (by simpa [hx] using he) + · exact h _ _ hx + +open scoped Classical in +theorem Within.exact (h : Bounded D M a) : Within D M 0 a := + ⟨M, by rw [sub_self]; exact Low.zero, h⟩ + +open scoped Classical in +theorem Within.low (h : Low M r) (a : ℝ) : Within D M r a := ⟨0, by simpa, by simp [Bounded]⟩ + +open scoped Classical in +theorem Within.mono (h : Within D M r a) (hr : r ≤ s) (ha : a ≤ b) : Within D M s b := by + obtain ⟨P, hp, hp'⟩ := h + exact ⟨P, hp.mono hr, hp'.mono ha⟩ + +open scoped Classical in +theorem Within.pull (h : Within D M r a) (f : Y → X) : + Within (fun x y => D (f x) (f y)) (M.submatrix f f) r a := by + obtain ⟨P, hp, hp'⟩ := h + exact ⟨P.submatrix f f, low_pull hp f, fun x y => hp' (f x) (f y)⟩ + +open scoped Classical in +theorem Within.add (h : Within D M r a) (h' : Within D N s a) : Within D (M + N) (r + s) a := by + obtain ⟨P, hp, hp'⟩ := h + obtain ⟨Q, hq, hq'⟩ := h' + refine ⟨P + Q, by rw [add_sub_add_comm]; exact hp.add hq, fun x y he => ?_⟩ + by_cases hx : P x y = 0 + · exact hq' _ _ (by simpa [hx] using he) + · exact hp' _ _ hx + +open scoped Classical in +theorem Within.mul [Fintype X] (h : Within D M r a) (h' : Within D N s b) + (ht : ∀ x y z, D x z ≤ D x y + D y z) : Within D (M * N) (r + s) (a + b) := by + obtain ⟨P, hp, hp'⟩ := h + obtain ⟨Q, hq, hq'⟩ := h' + refine ⟨P * Q, ?_, fun x y hxy => ?_⟩ + · exact approx_mul hp hq + · obtain ⟨z, _, hz⟩ := exists_ne_zero_of_sum_ne_zero (show (∑ z, P x z * Q z y) ≠ 0 from hxy) + exact (ht _ _ _).trans (add_le_add (hp' _ _ (left_ne_zero_of_mul hz)) + (hq' _ _ (right_ne_zero_of_mul hz))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Freeing an active register in a pair of groups -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Prices.Motion +open scoped Kronecker + +variable {W T F : Type} [Field F] {d : W → W → ℝ} {D : T → T → ℝ} + +open scoped Classical in +/-- Indexes the pair by the coordinates of `(W × T) × (W × T)`. -/ +abbrev Pair (W T : Type) := (W × T) × (W × T) + +open scoped Classical in +/-- The quantity computed by `D x.1.2 y.1.2 + d x.2.1 y.2.1 + D x.2.2 y.2.2`. -/ +def cost (d : W → W → ℝ) (D : T → T → ℝ) (x y : Pair W T) : ℝ := + D x.1.2 y.1.2 + d x.2.1 y.2.1 + D x.2.2 y.2.2 + +open scoped Classical in +private def sw (x : Pair W T) : Pair W T := ((x.2.1, x.1.2), (x.1.1, x.2.2)) + +open scoped Classical in +@[simp] private theorem sw_sw (x : Pair W T) : sw (sw x) = x := rfl + +open scoped Classical in +private def exch (F W T : Type) [Field F] : Matrix (Pair W T) (Pair W T) F := + fun x y => if x = sw y then 1 else 0 + +variable [Fintype W] [Fintype T] {C t : ℝ} {B : ℕ} + +open scoped Classical in +private theorem conjugate (M : Matrix (Pair W T) (Pair W T) F) : + exch F W T * M.submatrix sw sw * exch F W T = M := by + ext x y + have h (z) : x = sw z ↔ z = sw x := by constructor <;> rintro rfl <;> simp + simp [Matrix.mul_apply, exch, h, ite_mul, mul_ite] + +open scoped Classical in +private theorem exchange_cost (hD : ∀ x, D x x = 0) (h : SwapBound F W d B C) (ht : 0 < t) : + Within (cost d D) (exch F W T) + (C * (Fintype.card (W × T) : ℝ) ^ 2 * Real.exp (-t ^ 2 * B)) (48 * t * B) := by + obtain ⟨N, hr, hn⟩ := h t ht + let π (x : Pair W T) := ((x.2.1, x.1.1), (x.1.2, x.2.2)) + let I : Matrix (T × T) (T × T) F := 1 + refine ⟨(N ⊗ₖ I).submatrix π π, ?_, ?_⟩ + · have he : exch F W T - (N ⊗ₖ I).submatrix π π = + ((swapMatrix F W - N) ⊗ₖ I).submatrix π π := by + ext x y + simp only [Matrix.sub_apply, Matrix.submatrix_apply, Matrix.kroneckerMap_apply, sub_mul] + congr 1 + simp only [I, π, exch, sw, swapMatrix, Matrix.one_apply, Prod.ext_iff, ite_mul, one_mul, + zero_mul, + ← ite_and] + congr 1 + exact propext (by tauto) + rw [he] + apply (low_pull (low_kron hr (Low.full I)) π).mono + simp only [Fintype.card_prod, Nat.cast_mul] + exact le_of_eq (by ring) + · intro x y hxy + change N (x.2.1, x.1.1) (y.2.1, y.1.1) * I (x.1.2, x.2.2) (y.1.2, y.2.2) ≠ 0 at hxy + have he : x.1.2 = y.1.2 ∧ x.2.2 = y.2.2 := by + simpa [I, Matrix.one_apply] using right_ne_zero_of_mul hxy + simpa [cost, he.1, he.2, hD] using hn _ _ (left_ne_zero_of_mul hxy) + +open scoped Classical in +/-- Apply the second operation with the active registers exchanged. Its +uncontrolled movement then stays on the first register. -/ +theorem free_register (hd : ∀ x, d x x = 0) (hd' : ∀ x y z, d x z ≤ d x y + d y z) + (hD : ∀ x, D x x = 0) (hD' : ∀ x y z, D x z ≤ D x y + D y z) + (h : SwapBound F W d B C) (ht : 0 < t) {P Q : Matrix (W × T) (W × T) F} {a b : ℝ} + (hP : Bounded (fun x y => D x.2 y.2) P a) (hQ : Bounded (fun x y => D x.2 y.2) Q b) : + Within (cost d D) (P ⊗ₖ Q) (2 * C * (Fintype.card (W × T) : ℝ) ^ 2 * Real.exp (-t ^ 2 * B)) (a + + b + 96 * t * B) := by + have tri (x y z : Pair W T) : cost d D x z ≤ cost d D x y + cost d D y z := by + unfold cost + linarith only [hD' x.1.2 y.1.2 z.1.2, hd' x.2.1 y.2.1 z.2.1, hD' x.2.2 y.2.2 z.2.2] + let I : Matrix (W × T) (W × T) F := 1 + have hl : Within (cost d D) (P ⊗ₖ I) 0 a := by + apply Within.exact + intro x y hh + change P x.1 y.1 * I x.2 y.2 ≠ 0 at hh + have he : x.2 = y.2 := by simpa [I, Matrix.one_apply] using right_ne_zero_of_mul hh + simpa [cost, he, hD, hd] using hP _ _ (left_ne_zero_of_mul hh) + have hr : Within (cost d D) ((I ⊗ₖ Q).submatrix sw sw) 0 b := by + apply Within.exact + intro x y hh + change I (x.2.1, x.1.2) (y.2.1, y.1.2) * Q (x.1.1, x.2.2) (y.1.1, y.2.2) ≠ 0 at hh + have he : x.2.1 = y.2.1 ∧ x.1.2 = y.1.2 := by + simpa [I, Matrix.one_apply] using left_ne_zero_of_mul hh + simpa [cost, he.1, he.2, hD, hd] using hQ _ _ (right_ne_zero_of_mul hh) + have he := exchange_cost hD h ht + have hh := hl.mul ((he.mul hr tri).mul he tri) tri + rw [conjugate, ← Matrix.mul_kronecker_mul, show I = 1 from rfl, mul_one, one_mul] at hh + exact hh.mono (by linarith) (by linarith) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- +# Interpolating approximations of two groups + +The j-th difference on the left is paired with the approximation +at the complementary index on the right. The two rank savings +multiply, so each remainder gets the full target saving. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Prices.Motion +open scoped Kronecker + +variable {X F : Type} [Field F] [Fintype X] {D : X → X → ℝ} + {E : X × X → X × X → ℝ} {M : Matrix X X F} {b : ℕ → ℝ} {q : ℕ} {R H u L : ℝ} + +open scoped Classical in +theorem interpolate (hu : 0 ≤ u) (hu' : u ≤ 1) (hR : (Fintype.card X : ℝ) ≤ R) (hb : Monotone b) + (h : ∀ j : ℕ, 0 < j → Within D M (R * u ^ j) (b j)) + (hh : ∀ j < q, ∀ P Q : Matrix X X F, Bounded D P (b (j + 1)) → Bounded D Q (b (q - j)) → + Within E (P ⊗ₖ Q) (H * u ^ q) L) : + Within E (M ⊗ₖ M) (((q : ℝ) * (2 * R ^ 2 + H) + R ^ 2) * u ^ q) L := by + have hM := (Low.full M).mono hR + have hR' : 0 ≤ R := (by positivity : 0 ≤ (Fintype.card X : ℝ)).trans hR + have he (j : ℕ) : ∃ N, (j = 0 → N = 0) ∧ Low (M - N) (R * u ^ j) ∧ Bounded D N (b j) := by + by_cases hj : j = 0 + · exact ⟨0, fun _ => rfl, by simpa [hj] using hM, by simp [Bounded]⟩ + · obtain ⟨N, hN, hN'⟩ := h j (by omega) + exact ⟨N, by omega, hN, hN'⟩ + choose A hz hr hp using he + have step (j : ℕ) (hj : j < q) : + Within E ((A (j + 1) - A j) ⊗ₖ M) ((2 * R ^ 2 + H) * u ^ q) L := by + let P := A (j + 1) - A j + have hs : Low P (2 * R * u ^ j) := by + rw [show P = (M - A j) - (M - A (j + 1)) by unfold P; abel] + refine ((hr j).sub (hr (j + 1))).mono ?_ + rw [pow_succ] + linarith [mul_le_mul_of_nonneg_left hu' (show 0 ≤ R * u ^ j by positivity)] + have hf := hh j hj P (A (q - j)) ((hp (j + 1)).sub ((hp j).mono (hb (Nat.le_succ _)))) (hp _) + have hl := low_kron hs (hr (q - j)) + have heq : u ^ j * u ^ (q - j) = u ^ q := by rw [← pow_add, Nat.add_sub_of_le hj.le] + change Within E (P ⊗ₖ M) _ _ + rw [show P ⊗ₖ M = (P ⊗ₖ (M - A (q - j))) + (P ⊗ₖ A (q - j)) by + rw [← Matrix.kronecker_add, sub_add_cancel]] + refine ((Within.low hl L).add hf).mono ?_ le_rfl + apply le_of_eq + rw [← heq] + ring + have go (i : ℕ) (hi : i ≤ q) : Within E (A i ⊗ₖ M) (i * ((2 * R ^ 2 + H) * u ^ q)) L := by + induction i with + | zero => + rw [hz _ rfl, Matrix.zero_kronecker, Nat.cast_zero, zero_mul] + exact Within.low Low.zero L + | succ i ih => + rw [Nat.cast_succ, add_mul, one_mul] + have hh := (ih (by omega)).add (step i (by omega)) + rwa [← Matrix.add_kronecker, add_sub_cancel] at hh + have ht := (go q le_rfl).add (Within.low (low_kron (hr q) hM) L) + rw [← Matrix.add_kronecker, add_sub_cancel] at ht + exact ht.mono (le_of_eq (by ring)) le_rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Summing the displacement costs on a dyadic tree -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding + +/-- The additive reserve covers the cost of two exchanges and rounding +to a finite interpolation grid. -/ +def radius (k : ℕ) := 500 * Real.sqrt ((2 : ℝ) ^ k) - 400 + +theorem radius_pos (k : ℕ) : 0 < radius k := by + have hh : (1 : ℝ) ≤ Real.sqrt ((2 : ℝ) ^ k) := + Real.one_le_sqrt.mpr (one_le_pow₀ (by norm_num)) + unfold radius + linarith + +private theorem sqrt_tangent {a : ℝ} (ha : 0 ≤ a) : + Real.sqrt a * Real.sqrt 2 ≤ a + 1 / 2 := by + nlinarith [Real.sq_sqrt ha, Real.sq_sqrt (by norm_num : (0 : ℝ) ≤ 2), + sq_nonneg (Real.sqrt a - Real.sqrt 2 / 2)] + +theorem grid_choice (k : ℕ) : ∃ q : ℕ, 0 < q ∧ ∀ j < q, + radius k * (Real.sqrt (((j : ℝ) + 1) / q) + Real.sqrt (((q : ℝ) - j) / q)) + 96 ≤ radius (k + + 1) := by + obtain ⟨q, hq⟩ := exists_nat_gt (radius k) + have hq' := (radius_pos k).trans hq + have hs : (5 / 4 : ℝ) ≤ Real.sqrt 2 := by rw [Real.le_sqrt] <;> norm_num + have ht := Real.sq_sqrt (by norm_num : (0 : ℝ) ≤ 2) + refine ⟨q, Nat.cast_pos.mp hq', fun j hj => ?_⟩ + have hj' : (j : ℝ) ≤ q := Nat.cast_le.mpr hj.le + let a := ((j : ℝ) + 1) / q + let b := ((q : ℝ) - j) / q + have ha : 0 ≤ a := by unfold a; positivity + have hb : 0 ≤ b := by unfold b; positivity + have hab : a + b = 1 + 1 / q := by unfold a b; field_simp; ring + have hm : Real.sqrt a + Real.sqrt b ≤ Real.sqrt 2 + 1 / q := by + apply le_of_mul_le_mul_right _ (show 0 < Real.sqrt 2 by positivity) + have h := le_mul_of_one_le_right (show (0 : ℝ) + ≤ 1 / q by positivity) (show 1 ≤ Real.sqrt 2 by linarith) + linarith [sqrt_tangent ha, sqrt_tangent hb] + calc + _ ≤ radius k * (Real.sqrt 2 + 1 / q) + 96 := by + exact add_le_add_left (mul_le_mul_of_nonneg_left hm (radius_pos k).le) _ + _ ≤ radius k * Real.sqrt 2 + 97 := by + have h := (div_le_one hq').mpr hq.le + rw [mul_add, mul_one_div] + linarith + _ ≤ _ := by + unfold radius + rw [pow_succ, Real.sqrt_mul (by positivity)] + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # A doubling step with a uniform constant at every target rate -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Prices.Motion +open scoped Kronecker + +open scoped Classical in +theorem double (k : ℕ) {C K : ℝ} (hC : 0 ≤ C) (hK : 1 ≤ K) : + ∃ H : ℝ, 1 ≤ H ∧ ∀ (F W T : Type) [Field F] [Fintype W] [Fintype T] + (d : W → W → ℝ) (D : T → T → ℝ) (B : ℕ), + (∀ x, d x x = 0) → (∀ x y z, d x z ≤ d x y + d y z) → + (∀ x, D x x = 0) → (∀ x y z, D x z ≤ D x y + D y z) → + SwapBound F W d B C → ∀ M : Matrix (W × T) (W × T) F, + (∀ t : ℝ, 0 < t → Within (fun x y => D x.2 y.2) M + (K * (Fintype.card (W × T) : ℝ) * Real.exp (-t ^ 2 * B)) (radius k * t * B)) → + ∀ t : ℝ, 0 < t → Within (cost d D) (M ⊗ₖ M) + (H * (Fintype.card (W × T) : ℝ) ^ 2 * Real.exp (-t ^ 2 * B)) (radius (k + 1) * t * B) := by + obtain ⟨q, hq, hr⟩ := grid_choice k + have hq' : 0 < (q : ℝ) := by positivity + refine ⟨q * (2 * K ^ 2 + 2 * C) + K ^ 2, ?_, ?_⟩ + · exact (one_le_pow₀ hK).trans (le_add_of_nonneg_left (by positivity)) + intro F W T _ _ _ d D B hd hd' hD hD' hs M hm t ht + let u := Real.exp (-t ^ 2 * B / q) + let s (j : ℕ) := t * Real.sqrt ((j : ℝ) / q) + let b (j : ℕ) := radius k * s j * B + let N : ℝ := Fintype.card (W × T) + have hb : Monotone b := by + intro i j hij + have hk := radius_pos k + unfold b s + gcongr + have he (j : ℕ) : u ^ j = Real.exp (-(s j) ^ 2 * B) := by + simp only [u, s, ← Real.exp_nat_mul, mul_pow, Real.sq_sqrt (show 0 ≤ (j : ℝ) / q by positivity)] + congr 1 + ring + have heq : u ^ q = Real.exp (-t ^ 2 * B) := by simp [he, s, hq'.ne'] + have hp (j : ℕ) (hj : 0 < j) : Within (fun x y => D x.2 y.2) M (K * N * u ^ j) (b j) := by + rw [he] + exact hm (s j) (by unfold s; positivity) + have hpq (j : ℕ) (hj : j < q) (P Q : Matrix (W × T) (W × T) F) + (hP : Bounded (fun x y => D x.2 y.2) P (b (j + 1))) + (hQ : Bounded (fun x y => D x.2 y.2) Q (b (q - j))) : + Within (cost d D) (P ⊗ₖ Q) (2 * C * N ^ 2 * u ^ q) (radius (k + 1) * t * B) := by + rw [heq] + refine (free_register hd hd' hD hD' hs ht hP hQ).mono le_rfl ?_ + simp only [b, s, Nat.cast_add, Nat.cast_one, Nat.cast_sub hj.le] + linarith only [mul_le_mul_of_nonneg_right (hr j hj) (show 0 ≤ t * B by positivity)] + have hu : u ≤ 1 := Real.exp_le_one_iff.mpr (div_nonpos_of_nonpos_of_nonneg + (mul_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (sq_nonneg _)) (by positivity)) hq'.le) + have hi := interpolate (Real.exp_pos _).le hu + (le_mul_of_one_le_left (show 0 ≤ N by unfold N; positivity) hK) hb hp hpq + rw [heq] at hi + exact hi.mono (le_of_eq (by unfold N; ring)) le_rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Folding a dyadic power down to one unrestricted register -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Prices.Motion +open scoped Kronecker + +variable {W F : Type} [Field F] [Fintype W] + +open scoped Classical in +private def inactive (d : W → W → ℝ) {n : ℕ} (x y : Fin n → W) := + ∑ i, if i.val = 0 then 0 else d (x i) (y i) + +open scoped Classical in +private def Works (k n : ℕ) (K C : ℝ) : Prop := + ∀ (F W : Type) [Field F] [Fintype W] (d : W → W → ℝ) (B : ℕ), + (∀ x, d x x = 0) → (∀ x y z, d x z ≤ d x y + d y z) → SwapBound F W d B C → + ∀ (M : Matrix W W F) (t : ℝ), 0 < t → + Within (inactive d) (matPower (fun _ : Fin n => M)) + (K * (Fintype.card W : ℝ) ^ n * Real.exp (-t ^ 2 * B)) (radius k * t * B) + +open scoped Classical in +private theorem works_double {k n : ℕ} {K C : ℝ} (hn : 0 < n) (hK : 1 ≤ K) (hC : 0 ≤ C) + (h : Works k n K C) : ∃ H : ℝ, 1 ≤ H ∧ Works (k + 1) (n + n) H C := by + cases n with + | zero => omega + | succ n => + obtain ⟨H, hH, hh⟩ := double k hC hK + refine ⟨H, hH, ?_⟩ + intro F W _ _ d B hd hd' hs M t ht + let T := Fin n → W + let D (x y : T) := ∑ i, d (x i) (y i) + have hD x : D x x = 0 := by simp [D, hd] + have hD' x y z : D x z ≤ D x y + D y z := by + unfold D + rw [← sum_add_distrib] + exact sum_le_sum (fun i _ => hd' _ _ _) + let join (x : W × T) : Fin (n + 1) → W := Fin.cons x.1 x.2 + let split (x : Fin (n + 1) → W) : W × T := (x 0, Fin.tail x) + let A := (matPower (fun _ : Fin (n + 1) => M)).submatrix join join + have card : (Fintype.card (W × T) : ℝ) = (Fintype.card W : ℝ) ^ (n + 1) := by + simp [T, pow_succ'] + have hj : (fun x y => inactive d (join x) (join y)) = (fun x y => D x.2 y.2) := by + funext x y + simp [inactive, Fin.sum_univ_succ, join, D] + have hA (u : ℝ) (hu : 0 < u) := (h F W d B hd hd' hs M u hu).pull join + rw [hj, ← card] at hA + have he := hh F W T d D B hd hd' hD hD' hs A hA t ht + let left (x : Fin ((n + 1) + (n + 1)) → W) := x ∘ Fin.castAdd (n + 1) + let right (x : Fin ((n + 1) + (n + 1)) → W) := x ∘ Fin.natAdd (n + 1) + let pair x := (split (left x), split (right x)) + have hw := he.pull pair + have hM : (A ⊗ₖ A).submatrix pair pair = matPower (fun _ : Fin ((n + 1) + (n + 1)) => M) := by + ext x y + simp only [A, Matrix.submatrix_apply, Matrix.kroneckerMap_apply, pair, join, split, + Fin.cons_self_tail, + matPower] + exact (Fin.prod_univ_add (fun i => M (x i) (y i))).symm + have hdist : (fun x y => cost d D (pair x) (pair y)) = inactive d := by + funext x y + unfold inactive + rw [Fin.sum_univ_add] + simp [Fin.sum_univ_succ, cost, D, pair, split, left, right, Fin.tail, add_assoc] + rw [hM, hdist, card, pow_two, ← pow_add] at hw + exact hw + +open scoped Classical in +private theorem works (k : ℕ) {C : ℝ} (hC : 0 ≤ C) : ∃ K : ℝ, 1 ≤ K ∧ Works k (2 ^ k) K C := by + induction k with + | zero => + refine ⟨1, le_rfl, ?_⟩ + intro F W _ _ d B hd hd' hs M t ht + have hp : Bounded (inactive d) (matPower (fun _ : Fin 1 => M)) 0 := by simp [Bounded, inactive] + have hk := radius_pos 0 + exact (Within.exact hp).mono (by positivity) (by positivity) + | succ k ih => + obtain ⟨K, hK, hw⟩ := ih + rw [pow_succ, mul_two] + exact works_double (by positivity) hK hC hw + +open scoped Classical in +theorem fold (k : ℕ) {C t : ℝ} (hC : 0 ≤ C) (ht : 0 < t) : + ∃ H : ℝ, 0 ≤ H ∧ ∀ (F W : Type) [Field F] [Fintype W] (dist : W → W → ℝ) (B : ℕ), + (∀ x, dist x x = 0) → (∀ x y z, dist x z ≤ dist x y + dist y z) → SwapBound F W dist B C → + ∀ M : Matrix W W F, ∃ N, Low (matPower (fun _ : Fin (2 ^ k) => M) - N) + (H * (Fintype.card W : ℝ) ^ (2 ^ k : ℕ) * Real.exp (-t ^ 2 * B)) ∧ + ∀ x y, N x y ≠ 0 → ∑ i ∈ univ.erase 0, dist (x i) (y i) + ≤ 500 * t * Real.sqrt ((2 : ℝ) ^ k) * B := by + obtain ⟨H, hH, h⟩ := works k hC + refine ⟨H, by linarith, ?_⟩ + intro F W _ _ d B hd hd' hs M + obtain ⟨N, he, hb⟩ := h F W d B hd hd' hs M t ht + refine ⟨N, he, fun x y hh => ?_⟩ + have eqn : inactive d x y = ∑ i ∈ univ.erase 0, d (x i) (y i) := by + unfold inactive + rw [← sum_erase_add _ _ (mem_univ 0)] + simp only [Fin.val_zero, ↓reduceIte, add_zero] + exact sum_congr rfl (fun i hi => ite_eq_right (fun h => (mem_erase.mp hi).1 (Fin.ext h))) + rw [← eqn] + refine (hb x y hh).trans ?_ + unfold radius + linarith only [show 0 ≤ t * B by positivity] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Dyadic folding and the quadratic tradeoff on a finite grid -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Filter Prices.Motion Interior + +/-- Approximation on a fixed number of registers, uniformly for every +sufficiently large alphabet and every decoder. -/ +def Folds (K : ℝ) : Prop := + ∀ (F : Type) [Field F] (k : ℕ) (η : ℝ), 0 < η → η ^ 2 < (2 : ℝ) ^ k / 2 → + ∀ᶠ N : ℕ in atTop, ∀ B : Matrix (Fin N) (Fin N) F, ∃ A, + Low (matPower (fun _ : Fin (2 ^ k) => B) - A) ((N : ℝ) ^ ((2 : ℝ) ^ k - η ^ 2)) ∧ + Rows A ((N : ℝ) ^ (3 + K * η * Real.sqrt ((2 : ℝ) ^ k))) + +variable {K : ℝ} {F : Type} [Field F] + +/-- With at least the reciprocal of the loss in registers, the constant +cost of the last free register fits in the square-root envelope. -/ +theorem Folds.grid (h : Folds K) (hK : 1 ≤ K) (k : ℕ) {r : ℝ} + (hr : 0 < r) (hr' : r ≤ 1) (hk : 1 ≤ r * (2 : ℝ) ^ k) : + ∀ᶠ d : ℕ in atTop, ∀ M : Matrix (Fin d) (Fin d) F, ∃ A, + Low (matPower (fun _ : Fin (2 ^ k) => M) - A) (((d : ℝ) ^ (2 ^ k : ℕ)) ^ (1 - r)) ∧ + Rows A (((d : ℝ) ^ (2 ^ k : ℕ)) ^ ((K + 4) * Real.sqrt r)) := by + let m := (2 : ℝ) ^ k + have hm : 0 < m := by unfold m; positivity + have hs : r ≤ Real.sqrt r := (Real.le_sqrt hr.le hr.le).mpr (by nlinarith) + by_cases hlarge : 1 / 2 ≤ r + · filter_upwards [eventually_ge_atTop 1] with d hd M + have hd' : 1 ≤ (d : ℝ) := by exact_mod_cast hd + let P := matPower (fun _ : Fin (2 ^ k) => M) + refine ⟨P, ?_, (Rows.bound P).mono ?_⟩ + · unfold P + rw [sub_self] + exact Low.zero.mono (by positivity) + · simp only [Fintype.card_fun, Fintype.card_fin, Nat.cast_pow] + exact Real.self_le_rpow_of_one_le (one_le_pow₀ hd') (by nlinarith) + let η := Real.sqrt (r * m) + have ht : η ^ 2 = r * m := Real.sq_sqrt (by positivity) + have he : η * Real.sqrt m = Real.sqrt r * m := by + rw [show η = Real.sqrt r * Real.sqrt m from Real.sqrt_mul hr.le _, mul_assoc, + Real.mul_self_sqrt hm.le] + have hsmall : η ^ 2 < m / 2 := by rw [ht]; nlinarith + filter_upwards [eventually_ge_atTop 1, h F k η (by unfold η; positivity) hsmall] with d hd hh M + have hd' : 1 ≤ (d : ℝ) := by exact_mod_cast hd + obtain ⟨A, hA, hB⟩ := hh M + have hc (z : ℝ) : ((d : ℝ) ^ (2 ^ k : ℕ)) ^ z = (d : ℝ) ^ (m * z) := by + rw [← Real.rpow_natCast_mul (by positivity), Nat.cast_pow, Nat.cast_ofNat] + refine ⟨A, ?_, hB.mono ?_⟩ + · rw [hc, show m * (1 - r) = m - η ^ 2 by rw [ht]; ring] + exact hA + · rw [hc] + apply Real.rpow_le_rpow_of_exponent_le hd' + change 3 + K * η * Real.sqrt m ≤ m * ((K + 4) * Real.sqrt r) + rw [mul_assoc, he] + have hb : 1 ≤ Real.sqrt r * m := hk.trans (mul_le_mul_of_nonneg_right hs hm.le) + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end + +/- # Parity elimination on graded finite partially ordered sets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +open Finset Prices.Motion + +open scoped Classical in +/-- The data for the order construction, including `rel`, `grade`, `refl`, `trans`, `inc`. -/ +structure Order (X : Type) where + /-- The `Order` component of type `X → X → Prop`. -/ + rel : X → X → Prop + /-- The `Order` component of type `X → ℕ`. -/ + grade : X → ℕ + refl : ∀ x, rel x x + trans : ∀ {x y z}, rel x y → rel y z → rel x z + inc : ∀ {x y}, rel x y → x ≠ y → grade x < grade y + +namespace Order +variable {X F : Type} [Field F] (o : Order X) + +open scoped Classical in +/-- Requires `(∀ x, A x x = 1) ∧ ∀ x y, A x y ≠ 0 → o.rel x y`. -/ +def Unitriangular (A : Matrix X X F) : Prop := + (∀ x, A x x = 1) ∧ ∀ x y, A x y ≠ 0 → o.rel x y + +open scoped Classical in +/-- Builds `Order (Block X) where rel x y` with the specified `rel`, `grade`, `refl`, `trans`. -/ +def block : Order (Block X) where + rel x y := ∀ i, o.rel (x i) (y i) + grade := blockGrade o.grade + refl _ _ := o.refl _ + trans h k i := o.trans (h i) (k i) + inc {x y} h h' := by + apply sum_lt_sum + · intro i _ + by_cases he : x i = y i + · rw [he] + · exact (o.inc (h i) he).le + · obtain ⟨i, hi⟩ := Function.ne_iff.mp h' + exact ⟨i, mem_univ _, o.inc (h i) hi⟩ + +open scoped Classical in +theorem block_unit {A : Matrix X X F} (h : o.Unitriangular A) : + o.block.Unitriangular (matPower (fun _ : Fin 100 => A)) := by + refine ⟨fun x => prod_eq_one (fun _ _ => h.1 _), fun x y hxy i => ?_⟩ + exact h.2 _ _ (prod_ne_zero_iff.mp hxy i (mem_univ _)) + +open scoped Classical in +/-- The value specified by `o.grade x % 2`. -/ +def parity (x : X) := o.grade x % 2 + +open scoped Classical in +/-- Builds `Order X where rel x y` with the specified `rel`, `grade`, `refl`, `trans`. -/ +def middle : Order X where + rel x y := o.rel x y ∧ o.parity x = o.parity y + grade x := o.grade x / 2 + refl x := ⟨o.refl x, rfl⟩ + trans h k := ⟨o.trans h.1 k.1, h.2.trans k.2⟩ + inc h he := by have := o.inc h.1 he; unfold parity at h; omega + +open scoped Classical in +/-- Builds `Order X where rel x y` with the specified `rel`, `grade`, `refl`, `trans`. -/ +def outer (a : ℕ) : Order X where + rel x y := o.rel x y ∧ (x = y ∨ o.parity x = a ∧ o.parity y ≠ a) + grade x := if o.parity x = a then 0 else 1 + refl x := ⟨o.refl x, Or.inl rfl⟩ + trans h k := ⟨o.trans h.1 k.1, by grind⟩ + inc h he := by obtain ⟨h₁, h₂⟩ := h.2.resolve_left he; simp [h₁, h₂] + +open scoped Classical in +private def Piece (a b : ℕ) (P : Matrix X X F) : Prop := + ∀ x y, P x y ≠ 0 → o.rel x y ∧ o.grade x < o.grade y ∧ o.parity x = a ∧ o.parity y = b + +variable {o} {a b c e : ℕ} {P Q : Matrix X X F} + +open scoped Classical in +private theorem Piece.zero : o.Piece a b (0 : Matrix X X F) := by simp [Piece] + +open scoped Classical in +private theorem Piece.sub (h : o.Piece a b P) (k : o.Piece a b Q) : o.Piece a b (P - Q) := by + intro x y hn + by_cases he : P x y = 0 + · exact k x y (by simpa [he] using hn) + · exact h x y he + +open scoped Classical in +private theorem Piece.diag (h : o.Piece a b P) (x : X) : P x x = 0 := by + by_contra he; exact (h x x he).2.1.false + +open scoped Classical in +private theorem Piece.out (h : o.Piece a b P) (hab : b ≠ a) : + (o.outer a).Unitriangular (1 + P) := by + refine ⟨fun x => by simp [h.diag], ?_⟩ + intro x y hh + by_cases he : x = y + · subst y; exact (o.outer a).refl _ + obtain ⟨hr, _, ha, hb⟩ := h x y (by simpa [he] using hh) + exact ⟨hr, Or.inr ⟨ha, hb.trans_ne hab⟩⟩ + +variable [Fintype X] + +open scoped Classical in +private theorem Piece.mul (h : o.Piece a b P) (k : o.Piece b c Q) : o.Piece a c (P * Q) := by + intro x y hn + obtain ⟨z, _, hz⟩ := exists_ne_zero_of_sum_ne_zero hn + obtain ⟨h₁, h₂, h₃, _⟩ := h x z (left_ne_zero_of_mul hz) + obtain ⟨k₁, k₂, _, k₃⟩ := k z y (right_ne_zero_of_mul hz) + exact ⟨o.trans h₁ k₁, h₂.trans k₂, h₃, k₃⟩ + +open scoped Classical in +private theorem Piece.mul_mismatch (h : o.Piece a b P) (k : o.Piece c e Q) (hne : b ≠ c) : + P * Q = 0 := by + ext x y + by_contra hn + obtain ⟨z, _, hz⟩ := exists_ne_zero_of_sum_ne_zero hn + exact hne ((h x z (left_ne_zero_of_mul hz)).2.2.2.symm.trans (k z y (right_ne_zero_of_mul + hz)).2.2.1) + +open scoped Classical in +private theorem Piece.nil (h : o.Piece a a P) : ∃ n : ℕ, P ^ n = 0 := by + have hh (n : ℕ) (x y : X) (hn : (P ^ n) x y ≠ 0) : o.grade x + n ≤ o.grade y := by + induction n generalizing y with + | zero => + have : x = y := by simpa [Matrix.one_apply] using hn + simp [this] + | succ n ih => + rw [pow_succ, Matrix.mul_apply] at hn + obtain ⟨z, _, hz⟩ := exists_ne_zero_of_sum_ne_zero hn + exact Nat.succ_le_of_lt ((ih z (left_ne_zero_of_mul hz)).trans_lt (h z y + (right_ne_zero_of_mul hz)).2.1) + refine ⟨univ.sup o.grade + 1, ?_⟩ + ext x y + by_contra he + have := hh _ x y he + have := Finset.le_sup (f := o.grade) (mem_univ y) + omega + +open scoped Classical in +private theorem Piece.solve_right (h : o.Piece a a P) (k : o.Piece b a Q) : + ∃ T, o.Piece b a T ∧ T + T * P = Q := by + obtain ⟨n, hn⟩ := h.nil + have he : Q * P ^ n = 0 := by rw [hn, mul_zero] + clear hn + induction n generalizing Q with + | zero => + rw [pow_zero, mul_one] at he + exact ⟨0, Piece.zero, by simp [he]⟩ + | succ n ih => + rw [pow_succ', ← mul_assoc] at he + obtain ⟨T, hT, ht⟩ := ih (k.mul h) he + exact ⟨Q - T, k.sub hT, by rw [sub_mul, ← ht]; abel⟩ + +open scoped Classical in +private theorem Piece.solve_left (h : o.Piece a a P) (k : o.Piece a b Q) : + ∃ T, o.Piece a b T ∧ T + P * T = Q := by + obtain ⟨n, hn⟩ := h.nil + have he : P ^ n * Q = 0 := by rw [hn, zero_mul] + clear hn + induction n generalizing Q with + | zero => + rw [pow_zero, one_mul] at he + exact ⟨0, Piece.zero, by simp [he]⟩ + | succ n ih => + rw [pow_succ, mul_assoc] at he + obtain ⟨T, hT, ht⟩ := ih (h.mul k) he + exact ⟨Q - T, k.sub hT, by rw [mul_sub, ← ht]; abel⟩ + +open scoped Classical in +/-- Even–odd elimination. The off-diagonal factors have binary +grades and the remaining factor halves the original grade. -/ +theorem factor {A : Matrix X X F} (h : o.Unitriangular A) : + ∃ L M R : Matrix X X F, (o.outer 1).Unitriangular L ∧ o.middle.Unitriangular M ∧ + (o.outer 0).Unitriangular R ∧ A = L * M * R := by + let B (a b : ℕ) : Matrix X X F := fun x y => + if x ≠ y ∧ o.parity x = a ∧ o.parity y = b then A x y else 0 + have hp a b : o.Piece a b (B a b) := by + intro x y hn + unfold B at hn + split at hn + · rename_i he + have hr := h.2 x y hn + exact ⟨hr, o.inc hr he.1, he.2⟩ + · contradiction + have he : A = 1 + B 0 0 + B 1 1 + B 1 0 + B 0 1 := by + have par (x : X) : o.parity x = 0 ∨ o.parity x = 1 := by unfold parity; omega + ext x y + simp only [Matrix.add_apply, Matrix.one_apply] + by_cases hh : x = y + · subst y; simp [B, h.1] + rcases par x with hx|hx <;> rcases par y with hy|hy <;> simp [B, hx, hy, hh] + obtain ⟨L, hL, hL'⟩ := (hp 0 0).solve_right (hp 1 0) + obtain ⟨R, hR, hR'⟩ := (hp 0 0).solve_left (hp 0 1) + let Z := B 1 1 - L * B 0 1 + have hZ : o.Piece 1 1 Z := (hp 1 1).sub (hL.mul (hp 0 1)) + refine ⟨1 + L, 1 + B 0 0 + Z, 1 + R, hL.out (by decide), ?_, hR.out (by decide), ?_⟩ + · refine ⟨fun x => by simp [(hp 0 0).diag, hZ.diag], ?_⟩ + intro x y hn + by_cases hh : x = y + · subst y; exact o.middle.refl _ + by_cases hz : Z x y = 0 + · obtain ⟨hr, _, ha, hb⟩ := hp 0 0 x y (by simpa [hh, hz] using hn) + exact ⟨hr, ha.trans hb.symm⟩ + · obtain ⟨hr, _, ha, hb⟩ := hZ x y hz + exact ⟨hr, ha.trans hb.symm⟩ + · have h₁ := hL.mul_mismatch hZ (by decide) + have h₂ := hZ.mul_mismatch hR (by decide) + calc + A = 1 + B 0 0 + Z + (L + L * B 0 0) + (R + B 0 0 * R) + L * (R + B 0 0 * R) := by + rw [hL', hR', he]; unfold Z; abel + _ = (1 + L) * (1 + B 0 0 + Z) * (1 + R) := by + simp only [add_mul, mul_add, mul_one, one_mul, h₁, h₂, add_zero, mul_assoc] + abel + +end Order +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Folding +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Interior/Convert.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Interior/Convert.lean new file mode 100644 index 0000000000..7f9b8f1566 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Interior/Convert.lean @@ -0,0 +1,484 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Folding.Transfer +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Interior.Fill +public import Mathlib.FieldTheory.Finite.Basic +public import Mathlib.Tactic.NormNum.Prime +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Bounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sums.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Strict +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagWords +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth +public import Mathlib.Analysis.Convex.StdSimplex + +/-! # Quadratic nonrigidity of decoder powers -/ + +universe u + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Filter Prices.Motion + +variable {F : Type} [Field F] {q : ℕ} {K l : ℝ} + +theorem pack (h : Folding.Folds K) (hK : 1 ≤ K) (hl : 1 ≤ l) (hq : (q : ℝ) = l * l) : + ∀ᶠ d : ℕ in atTop, ∀ M : Matrix (Fin d) (Fin d) F, + Packed (matPower (fun _ : Fin q => matPower (fun _ : Fin (2 ^ q) => M))) + (((d : ℝ) ^ (2 ^ q : ℕ)) ^ ((q : ℝ) - 1 / 2)) (((d : ℝ) ^ (2 ^ q : ℕ)) ^ (4 * (K + 4) * l)) + := by + let C := K + 4 + have hC : 1 ≤ C := by unfold C; linarith + have hq' : 0 < (q : ℝ) := by rw [hq]; positivity + have ht : (q : ℝ) ≤ (2 : ℝ) ^ q := by + exact_mod_cast (Nat.lt_pow_self (by decide : 1 < 2) (n := q)).le + have hs (i : Fin q) := h.grid (F := F) hK q (r := (i.val + 1 : ℕ) / (q : ℝ)) (by positivity) + ((div_le_one hq').mpr (by exact_mod_cast i.isLt)) (by + rw [div_mul_eq_mul_div, le_div_iff₀ hq', one_mul] + exact ht.trans (le_mul_of_one_le_left (by positivity) (by exact_mod_cast Nat.succ_pos i.val))) + have hg := (tendsto_rpow_atTop (by norm_num : (0 : ℝ) < 1 / 2)).comp tendsto_natCast_atTop_atTop + filter_upwards [eventually_ge_atTop 1, eventually_all.mpr hs, + hg.eventually_ge_atTop ((2 * ((q : ℝ) + 1)) ^ q)] with d hd hn hn' M + let n := 2 ^ q + let D := (d : ℝ) ^ n + have hd' : 1 ≤ (d : ℝ) := by exact_mod_cast hd + have hD : 1 ≤ D := one_le_pow₀ hd' + have hfactor : (2 * ((q : ℝ) + 1)) ^ q ≤ D ^ (1 / 2 : ℝ) := by + have hpos : n ≠ 0 := by + unfold n + positivity + exact hn'.trans (Real.rpow_le_rpow (by positivity) (le_self_pow₀ hd' hpos) (by norm_num)) + have H := collect (M := matPower (fun _ : Fin n => M)) + hD (by simp [D]) hl hq hC (fun j hj hj' => by + simpa only [Nat.sub_add_cancel hj] using hn ⟨j - 1, by omega⟩ M) + have hh {a b : ℝ} (hab : 1 / 2 + a ≤ b) : (2 * ((q : ℝ) + 1)) ^ q * D ^ a ≤ D ^ b := by + apply le_trans (mul_le_mul_of_nonneg_right hfactor (by positivity)) + change D ^ (1 / 2 : ℝ) * D ^ a ≤ D ^ b + rw [← Real.rpow_add (by linarith)] + exact Real.rpow_le_rpow_of_exponent_le hD hab + obtain ⟨A, B, he, ha, hb⟩ := H + have hp : (2 * ((q : ℝ) + 1)) ^ q * D ^ (3 * C * l) ≤ D ^ (4 * C * l) := hh (by nlinarith) + exact ⟨A, B, he, ha.mono hp, hb.mono (hh (by linarith)) hp⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +section +/- +# A thin product with one private multiplication per output + +The seed is integral, with the auxiliary field used only to index +zero-one coefficients. The number of independent products is a +square, so the whole batch tiles one larger output with no padding. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior + +private theorem tile_seed {F : Type*} [Field F] {G A H E C : Type} + [Fintype G] [Fintype A] [Fintype H] [Fintype E] [Fintype C] + (S : Seed F G A H E C) {b a g n : ℕ} + (hg : Fintype.card G = g * g) (ha : Fintype.card A = a) + (hb : 0 < b) (hn : 0 < n) + (hgap : 2 ^ b * Fintype.card G * Fintype.card H * 2 < Fintype.card H ^ b) + (herr : 2 ^ (b + 1) * Fintype.card E ≤ Fintype.card (Out G A)) : + let q := (g * a) ^ b + ∃ r, 2 ^ n * r ≤ q ^ n * q ^ n ∧ PrivateProducts F (q ^ n) (q ^ n) (2 ^ n) r := by + classical + intro q + obtain ⟨r, hsize, hpriv⟩ := S.amplify hb hgap herr hn + let m := b * n + have he : q ^ n = g ^ m * a ^ m := by unfold q m; rw [← pow_mul, mul_pow] + have hG : Fintype.card (Pos (g ^ m) (g ^ m)) = Fintype.card (Fin (b * n) → G) := by + simp [Pos, hg, m, mul_pow] + have hA : Fintype.card (Fin (a ^ m)) = Fintype.card (Fin (b * n) → A) := by simp [ha, m] + rw [he] + refine ⟨r, hsize.trans_eq ?_, tile (Fintype.equivOfCardEq hG) (Fintype.equivOfCardEq hA) + (Equiv.refl _) hpriv⟩ + simp only [Out, Fintype.card_prod, hg, ha, mul_pow, m] + ring + +/-- A fixed geometric sequence suffices for converting short signals +into private products. -/ +theorem thin : ∃ S : ℕ, 2 ≤ S ∧ ∀ (F : Type u) [Field F] (n : ℕ), 0 < n → + ∃ r : ℕ, 2 ^ n * r ≤ S ^ n * S ^ n ∧ PrivateProducts F (S ^ n) (S ^ n) (2 ^ n) r := by + classical + obtain ⟨l, hl⟩ : ∃ l : ℕ, l + 1 = 1024 * 1024 := ⟨1048575, by norm_num⟩ + have : Fact (Nat.Prime 17) := ⟨by norm_num⟩ + let K := ZMod 17 + have hK : Fintype.card K = 17 := ZMod.card _ + have hH : Fintype.card Kˣ = 16 := by rw [Fintype.card_units, hK] + let a := 17 ^ l + have ha : 0 < a := by unfold a; positivity + let S := (1024 * a) ^ 10 + have hS : 2 ≤ S := by + apply le_trans (b := 1024 * a) (by omega) + exact Nat.le_self_pow (by decide) _ + refine ⟨S, hS, ?_⟩ + intro F _ n hn + apply tile_seed (blockSeed F K l) (b := 10) (g := 1024) (a := a) + (by simpa using hl) (by simp [hK, a]) (by decide) hn + · rw [Fintype.card_fin, hH, hl] + norm_num + · simp only [Out, Fintype.card_prod, Fintype.card_fun, Fintype.card_fin, hK] + rw [pow_succ (17 * 17), mul_pow, hl] + have h : 2 ^ 11 * (17 * 17) ≤ 1024 * 1024 := by norm_num + rw [mul_comm (17 ^ l * 17 ^ l), ← mul_assoc] + exact Nat.mul_le_mul_right _ h + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- # From a packed decoder to short sums of products -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset Prices.Motion Border + +variable {F T : Type} [Field F] [Fintype T] {M : Matrix T T F} {i j k d : ℕ} + +open scoped Classical in +/-- The defining condition `∃ (row : Pos i j → T) (P : T → Product F (Pos i k) (Pos k j)), ∀ z x +y, matrix F i j k z x y = ∑ t, M (row z) t * (P t).apply x y`. -/ +def Decoded (M : Matrix T T F) (i j k : ℕ) : Prop := + ∃ (row : Pos i j → T) (P : T → Product F (Pos i k) (Pos k j)), + ∀ z x y, matrix F i j k z x y = ∑ t, M (row z) t * (P t).apply x y + +open scoped Classical in +theorem decoder (h : RankLE F i j k d) (ha : i * j ≤ d) : + ∃ M : Matrix (Fin d) (Fin d) F, Decoded M i j k := by + obtain ⟨a, b, c, he⟩ := h + let row : Pos i j ↪ Fin d := finProdFinEquiv.toEmbedding.trans (Fin.castLEEmb ha) + let M := Function.extend row (fun z t => c t z) (fun _ _ => 0) + refine ⟨M, row, fun t => ⟨a t, b t⟩, fun z x y => ?_⟩ + simpa only [matrix, Product.apply, M, row.injective.extend_apply, mul_comm] using (he x y z).symm + +open scoped Classical in +theorem Decoded.pow (h : Decoded M i j k) (n : ℕ) : + Decoded (matPower (fun _ : Fin n => M)) (i ^ n) (j ^ n) (k ^ n) := by + obtain ⟨row, P, he⟩ := h + refine ⟨fun z l => row (digit z l), fun t => ⟨fun x => ∏ l, (P (t l)).left (digit x l), + fun y => ∏ l, (P (t l)).right (digit y l)⟩, fun z x y => ?_⟩ + have hm : matrix F (i ^ n) (j ^ n) (k ^ n) z x y = + ∏ l, matrix F i j k (digit z l) (digit x l) (digit y l) := by + simpa only [coefficients, WPower, prod_const_one, matrix] using + (coefficients_pow (fun _ _ _ => (1 : F)) n x y z).symm + rw [hm] + simp only [he, matPower, Product.apply, Fintype.prod_sum, prod_mul_distrib] + +open scoped Classical in +private theorem Rows.short {Z X Y : Type} {A : Matrix Z T F} {p : ℝ} (h : Rows A p) + (P : T → Product F X Y) (z : Z) : ∃ a : Fin ⌊p⌋₊ → Product F X Y, ∀ x y, + ∑ t, A z t * (P t).apply x y = ∑ l, (a l).apply x y := by + let s : Finset T := {t | A z t ≠ 0} + have hs : s.card ≤ ⌊p⌋₊ := Nat.le_floor (h z) + let e : Fin ⌊p⌋₊ ≃ ↥s ⊕ Fin (⌊p⌋₊-s.card) := Fintype.equivOfCardEq (by simp; omega) + let Q : ↥s ⊕ Fin (⌊p⌋₊-s.card) → Product F X Y := + Sum.elim (fun t => ⟨fun x => A z t * (P t).left x, (P t).right⟩) (fun _ => ⟨0, 0⟩) + refine ⟨Q ∘ e, fun x y => ?_⟩ + simp only [Function.comp_apply] + rw [e.sum_comp (fun t => (Q t).apply x y), Fintype.sum_sum_type] + simp only [Q, Sum.elim_inl, Sum.elim_inr, Product.apply, Pi.zero_apply, zero_mul, sum_const_zero, + add_zero, mul_assoc] + rw [sum_coe_sort s (fun t => A z t * ((P t).left x * (P t).right y))] + symm + apply sum_subset (subset_univ _) + intro t _ ht + have hz : A z t = 0 := by simpa [s] using ht + simp [hz] + +open scoped Classical in +theorem Decoded.slots {r p : ℝ} (h : Decoded M i j k) (hp : Packed M r p) : + ∃ e : ℕ, (e : ℝ) ≤ r ∧ Slots (matrix F i j k) e ⌊p⌋₊ := by + obtain ⟨row, P, he⟩ := h + obtain ⟨A, B, hM, ha, e, he', L, R, hB, hR⟩ := hp + choose a h₁ using ha.short P + choose b h₂ using hR.short P + refine ⟨e, he', Sum.elim (a ∘ row) b, fun z => L (row z), fun z x y => ?_⟩ + rw [he, hM, hB] + simp only [Sum.elim_inl, Sum.elim_inr, Function.comp_apply, ← h₁, ← h₂, Matrix.add_apply, + Matrix.mul_apply, add_mul, sum_add_distrib, sum_mul, mul_sum, mul_assoc] + rw [sum_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sums +open Spectral Filter +open scoped Topology + +variable {F : Type} [Field F] {A B : Three F} + +theorem rank_spec (A : Three F) : A ≤ (rank A : Three F) := + Nat.sInf_mem (s := {n : ℕ | A ≤ (n : Three F)}) (Tensor.exists_bound A) + +private theorem rank_le {r : ℕ} (h : A ≤ (r : Three F)) : rank A ≤ r := Nat.sInf_le h + +private theorem rank_mul (A B : Three F) : rank (A * B) ≤ rank A * rank B := by + apply rank_le + rw [Nat.cast_mul] + refine (Tensor.mul_le_mul_left _ _ A (rank_spec B)).trans ?_ + rw [mul_comm A, mul_comm (rank A : Three F)] + exact Tensor.mul_le_mul_left _ _ _ (rank_spec A) + +private theorem rank_pos (hA : A ≠ 0) (n : ℕ) : 0 < rank (A ^ n) := by + obtain ⟨f, hf, _⟩ := maximum_score F 0 0 0 + have hf₁ : 1 ≤ f A := by simpa using hf (Tensor.one_le A hA) + have hh := hf (rank_spec (A ^ n)) + rw [map_pow, map_natCast] at hh + exact_mod_cast (pow_pos (zero_lt_one.trans_le hf₁) n).trans_le hh + +theorem rate_spec (hA : A ≠ 0) : + Tendsto (fun n : ℕ => (rank (A ^ n) : ℝ) ^ (n : ℝ)⁻¹) atTop (𝓝 (asymptotic A)) ∧ + ∀ n : ℕ, 0 < n → asymptotic A ≤ Real.exp (Real.log (rank (A ^ n)) / n) := by + have hm (n m : ℕ) : rank (A ^ (n + m)) ≤ rank (A ^ n) * rank (A ^ m) + := by rw [pow_add]; apply rank_mul + obtain ⟨L, hl, hb⟩ := rank_rate (rank_pos hA) hm + rw [asymptotic, hl.limUnder_eq] + exact ⟨hl, hb⟩ + +theorem price_le {f : Point F} (hf : Monotone f) (hA : A ≠ 0) : (f A : ℝ) ≤ asymptotic A := by + apply ge_of_tendsto (rate_spec hA).1 + filter_upwards [eventually_gt_atTop 0] with n hn + have hh := hf (rank_spec (A ^ n)) + rw [map_pow, map_natCast] at hh + rw [← Real.pow_rpow_inv_natCast (NNReal.coe_nonneg (f A)) hn.ne'] + exact Real.rpow_le_rpow (by positivity) (by exact_mod_cast hh) (by positivity) + +theorem asymptotic_pos (hA : A ≠ 0) : 0 < asymptotic A := by + obtain ⟨f, hf, _⟩ := maximum_score F 0 0 0 + have hf₁ : 1 ≤ f A := by simpa using hf (Tensor.one_le A hA) + exact (by positivity : 0 < (f A : ℝ)).trans_le (price_le hf hA) + +theorem detected (hA : A ≠ 0) : + ∃ f : Point F, Monotone f ∧ (f A : ℝ) = asymptotic A := by + have h := asymptotic_pos hA + obtain ⟨f, hf, hf'⟩ := detector (A := A) h (by + intro n r hr + rcases n.eq_zero_or_pos with rfl | hn + · rw [pow_zero, ← Nat.cast_one] at hr + rw [pow_zero] + exact_mod_cast (Tensor.natCast_le_iff _ _).mp hr + have he := (rate_spec hA).2 _ hn + have hp : 0 < (rank (A ^ n) : ℝ) := by exact_mod_cast rank_pos hA n + rw [div_eq_mul_inv, ← Real.rpow_def_of_pos hp] at he + have hh := pow_le_pow_left₀ h.le he n + rw [Real.rpow_inv_natCast_pow hp.le hn.ne'] at hh + exact hh.trans (by exact_mod_cast rank_le hr)) + exact ⟨f, hf, le_antisymm (price_le hf hA) hf'⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sums +end + +/- +# Minimum price of a sum + +For each mixed product use a point detecting a full-support weighting. +The point may depend on the multiplicities of the summands. Grouping +words by multiplicity loses only a polynomial factor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sums +open Spectral MatrixMultiplicationAllFields.TensorSpectrum.TagWords + +variable {F : Type} [Field F] {n : ℕ} {A B : Three F} + +private theorem products {A B : Fin n → Three F} (hn : 0 < n) (h : ∀ i, Dominates (A i) (B i)) + (t : Fin n → ℕ) : Dominates (∏ i, A i ^ t i) (∏ i, B i ^ t i) := by + suffices ∀ s : Finset (Fin n), Dominates (∏ i ∈ s, A i ^ t i) (∏ i ∈ s, B i ^ t i) from this _ + intro s + induction s using Finset.induction_on with + | empty => simpa using (h ⟨0, hn⟩).pow 0 + | insert i s hi ih => + rw [Finset.prod_insert hi, Finset.prod_insert hi] + exact ((h i).pow _).mul ih + +private theorem majorize {A B : Fin n → Three F} (hn : 0 < n) (h : ∀ i, Dominates (A i) (B i)) + (hA : (∑ i, A i) ≠ 0) (f : Point F) (hf : Monotone f) : + ∑ i, (f (B i) : ℝ) ≤ asymptotic (∑ i, A i) := by + let b i := (f (B i) : ℝ) + apply TensorSpectrum.le_of_pow_le_polynomial_mul_pow _ _ 1 n (asymptotic_pos hA).le + zero_lt_one + intro N _ + obtain ⟨t, ht⟩ := exists_fiberMass_ge_average (N := N) b + obtain ⟨g, hg, hv⟩ := (products hn h fun i => (t i).val).price hf + let a i := (g (A i) : ℝ) + have hh : countWeight b t ≤ countWeight a t := by + simpa only [countWeight, map_prod, map_pow, NNReal.coe_prod, NNReal.coe_pow] using hv + have hmass : fiberMass b t ≤ fiberMass a t := mul_le_mul_of_nonneg_left hh (by positivity) + have hm : fiberMass a t ≤ (∑ i, a i) ^ N := by + rw [← sum_fiberMass] + apply Finset.single_le_sum _ (Finset.mem_univ t) + intro i _ + unfold fiberMass countWeight a + positivity + have he : ∑ i, a i ≤ asymptotic (∑ i, A i) := by + simpa only [a, map_sum, NNReal.coe_sum] using price_le hg hA + rw [one_mul, Real.rpow_natCast, mul_comm] + apply (div_le_iff₀ (by positivity)).mp + exact ht.trans (hmass.trans (hm.trans (pow_le_pow_left₀ (by unfold a; positivity) he N))) + +variable {v : Fin n → Shape} {w : ∀ t, Weights F (v t)} + +theorem blocks_ne_zero (hn : 0 < n) (hw : ∀ t a b c, w t a b c ≠ 0) : blocks v w ≠ 0 := by + let t : Fin n := ⟨0, hn⟩ + obtain ⟨f, _, h, _⟩ := weighted_maximizer (hw t) (v t).hi (v t).hj (v t).hk + intro he + have hh : f (weightedTensor (w t)) ≤ f (blocks v w) := by + rw [blocks, map_sum] + exact Finset.single_le_sum (fun i _ => (show 0 + ≤ f (weightedTensor (w i)) from zero_le)) (Finset.mem_univ t) + rw [he, map_zero] at hh + exact (Real.exp_pos _).not_ge (h.trans (NNReal.coe_le_coe.mpr hh)) + +/-- Computes the price by the application `Real.exp (score f (Real.log v.i) (Real.log v.j) +(Real.log v.k))`. -/ +def price (f : Point F) (v : Shape) := Real.exp (score f (Real.log v.i) (Real.log v.j) (Real.log + v.k)) + +theorem price_lower (hn : 0 < n) (hw : ∀ t a b c, w t a b c ≠ 0) (f : Point F) (hf : Monotone f) : + ∑ i, price f (v i) ≤ asymptotic (blocks v w) := by + have h (t) : Dominates (weightedTensor (w t)) (tensor F (v t).i (v t).j (v t).k) := + ⟨_, _, _, (v t).hi, (v t).hj, (v t).hk, ⟨w t, hw t, le_rfl⟩, rfl⟩ + have he := majorize hn h (blocks_ne_zero hn hw) f hf + simp_rw [tensor_price hf (v _).hi (v _).hj (v _).hk] at he + exact he + +theorem price_upper (F : Type) [Field F] (v : Fin n → Shape) (hn : 0 < n) : + ∃ f : Point F, Monotone f ∧ asymptotic (blocks v (unweighted F v)) ≤ ∑ t, price f (v t) := by + have h : blocks v (unweighted F v) ≠ 0 := blocks_ne_zero hn fun _ _ _ _ => one_ne_zero + obtain ⟨f, hf, he⟩ := detected h + refine ⟨f, hf, ?_⟩ + rw [← he, blocks, map_sum, NNReal.coe_sum] + apply Finset.sum_le_sum + intro t _ + rw [price, ← tensor_price hf (v t).hi (v t).hj (v t).hk] + exact NNReal.coe_le_coe.mpr (hf (ordinary_le_tensor F (v t).hi (v t).hj (v t).hk)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sums +end + +/- # Variational formula for independent products of different shapes -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sums +open Set Filter +open scoped Topology + +variable {F : Type} [Field F] {n : ℕ} (v : Fin n → Shape) + +/-- Uses `{p | (∀ i, 0 ≤ p i) ∧ ∑ i, p i = 1}` as the representation. -/ +def simplex (n : ℕ) : Set (Fin n → ℝ) := + {p | (∀ i, 0 ≤ p i) ∧ ∑ i, p i = 1} + +private theorem log_sum (hn : 0 < n) (t : Fin n → ℝ) : + IsGreatest ((fun p => entropy p + ∑ i, p i * t i) '' simplex n) + (Real.log (∑ i, Real.exp (t i))) := by + let S := ∑ i, Real.exp (t i) + have hS : 0 < S := Finset.sum_pos (fun i _ => Real.exp_pos _) ⟨⟨0, hn⟩, Finset.mem_univ _⟩ + let p i := Real.exp (t i) / S + have hp i : 0 < p i := div_pos (Real.exp_pos _) hS + have hs : ∑ i, p i = 1 := by + unfold p + rw [← Finset.sum_div, div_self hS.ne'] + have he (i) : Real.log (p i) = t i - Real.log S := by + rw [show p i = _ from rfl, Real.log_div (Real.exp_ne_zero _) hS.ne', Real.log_exp] + have hid (q) (hq : q ∈ simplex n) : + entropy q + ∑ i, q i * t i = Real.log S + ∑ i, q i * (Real.log (p i) - Real.log (q i)) := by + simp only [he, entropy, mul_sub, Finset.sum_sub_distrib, ← Finset.sum_mul, hq.2, one_mul] + ring + have hp' : p ∈ simplex n := ⟨fun i => (hp i).le, hs⟩ + constructor + · refine ⟨p, hp', ?_⟩ + change entropy p + _ = Real.log S + rw [hid p hp'] + simp + · rintro _ ⟨q, hq, rfl⟩ + have hh := gibbs hq.1 hq.2 (fun i => (hp i).le) hs.le (fun i _ => hp i) + change entropy q + _ ≤ Real.log S + rw [hid q hq] + linarith + +private theorem mean_nonneg {p : Fin n → ℝ} (hp : p ∈ simplex n) + (q : Shape → ℕ) (hq : ∀ v, 0 < q v) : 0 ≤ mean v p q := + Finset.sum_nonneg fun i _ => mul_nonneg (hp.1 i) (Real.log_nonneg (by exact_mod_cast hq (v i))) + +private theorem mean_score (p : Fin n → ℝ) (f : Point F) : + score f (mean v p Shape.i) (mean v p Shape.j) (mean v p Shape.k) = + ∑ i, p i * score f (Real.log (v i).i) (Real.log (v i).j) (Real.log (v i).k) := by + unfold score mean + simp only [Finset.sum_mul, ← Finset.sum_add_distrib] + exact Finset.sum_congr rfl fun _ _ => by ring + +theorem blocks_limit (hn : 0 < n) (w : ∀ i, Weights F (v i)) (hw : ∀ t a b c, w t a b c ≠ 0) : + Tendsto (fun m : ℕ => (rank ((blocks v w) ^ m) : ℝ) ^ (m : ℝ)⁻¹) atTop + (𝓝 (asymptotic (blocks v w))) := + (rate_spec (blocks_ne_zero hn hw)).1 + +private theorem maximum_le (hn : 0 < n) (w : ∀ i, Weights F (v i)) (hw : ∀ t a b c, w t a b c ≠ 0) + {p : Fin n → ℝ} (hp : p ∈ simplex n) : + objective (exponent F) v p ≤ Real.log (asymptotic (blocks v w)) := by + obtain ⟨x, y, z, hP, he⟩ := (support F).attains (mean_nonneg v hp _ Shape.hi) + (mean_nonneg v hp _ Shape.hj) (mean_nonneg v hp _ Shape.hk) + obtain ⟨f, hf, hval⟩ := hP.score (a := mean v p Shape.i) (b := mean v p Shape.j) (c + := mean v p Shape.k) + have hl := (log_sum hn (fun i => score f (Real.log (v i).i) (Real.log (v i).j) (Real.log (v + i).k))).2 + ⟨p, hp, rfl⟩ + unfold objective + rw [← he, hval, mean_score] + refine hl.trans (Real.log_le_log ?_ (price_lower hn hw f hf)) + exact Finset.sum_pos (fun _ _ => Real.exp_pos _) ⟨⟨0, hn⟩, Finset.mem_univ _⟩ + +theorem minimum (F : Type) [Field F] (v : Fin n → Shape) (hn : 0 < n) : + IsLeast {s | ∃ w : ∀ t, Weights F (v t), (∀ t a b c, w t a b c ≠ 0) ∧ + asymptotic (blocks v w) = s} (asymptotic (blocks v (unweighted F v))) ∧ + IsGreatest (objective (exponent F) v '' simplex n) + (Real.log (asymptotic (blocks v (unweighted F v)))) := by + let w := unweighted F v + have hw : ∀ t a b c, w t a b c ≠ 0 := fun _ _ _ _ => one_ne_zero + obtain ⟨f, hf, hh⟩ := price_upper F v hn + constructor + · refine ⟨⟨w, hw, rfl⟩, ?_⟩ + rintro _ ⟨v', hv', rfl⟩ + exact hh.trans (price_lower hn hv' f hf) + have hpos := asymptotic_pos (blocks_ne_zero hn hw) + have he := Real.log_le_log hpos hh + obtain ⟨p, hp, heq⟩ := + (log_sum hn (fun i => score f (Real.log (v i).i) (Real.log (v i).j) (Real.log (v i).k))).1 + have hscore := score_le_exponent hf (mean_nonneg v hp _ Shape.hi) + (mean_nonneg v hp _ Shape.hj) (mean_nonneg v hp _ Shape.hk) + rw [mean_score] at hscore + have hle : Real.log (asymptotic (blocks v w)) ≤ objective (exponent F) v p := + he.trans (heq.ge.trans (add_le_add_right hscore _)) + refine ⟨⟨p, hp, le_antisymm (maximum_le v hn w hw hp) hle⟩, ?_⟩ + rintro _ ⟨q, hq, rfl⟩ + exact maximum_le v hn w hw hq + +/-- The rectangular law evaluates the maximum for heterogeneous direct sums. -/ +theorem benchmark_maximum (v : Fin n → Shape) (hn : 0 < n) + (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) : + IsGreatest (objective U v '' simplex n) + (Real.log (asymptotic (blocks v (unweighted F v)))) := by + have he : objective U v '' simplex n = objective (exponent F) v '' simplex n := by + apply Set.image_congr + intro p hp + unfold objective + rw [all_shapes hr hs (mean_nonneg v hp _ Shape.hi) + (mean_nonneg v hp _ Shape.hj) (mean_nonneg v hp _ Shape.hk)] + rw [he] + exact (minimum F v hn).2 + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sums +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Interior/Fill.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Interior/Fill.lean new file mode 100644 index 0000000000..352bc91a8e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Interior/Fill.lean @@ -0,0 +1,948 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Interior.Model +public import Mathlib.LinearAlgebra.Finsupp.LinearCombination +public import Mathlib.Algebra.BigOperators.Field +public import Mathlib.Algebra.Field.Basic +public import Mathlib.Data.Fintype.Prod +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.Ring +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Data.Fin.Tuple.Basic +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Dense + +/-! # Private formulas and shared measurements -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior + +variable {F : Type*} [Field F] {X Y Z E : Type} [Fintype E] + +theorem private_of_span (M : Z → X → Y → F) (a : Z → Product F X Y) (b : E → Product F X Y) + (h : ∀ z, M z - (a z).apply ∈ Submodule.span F (Set.range (fun l => (b l).apply))) : + Private M (Fintype.card E) := by + have hi (z) := (Submodule.mem_span_range_iff_exists_fun _).mp (h z) + choose c hc using hi + let e := (Fintype.equivFin E).symm + refine ⟨a, b ∘ e, fun z l => c z (e l), fun z x y => ?_⟩ + have he := congrFun (congrFun (hc z) x) y + simp only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul, Pi.sub_apply] at he + simp only [Function.comp_apply, e.sum_comp (fun t => c z t * (b t).apply x y)] + rw [he, add_sub_cancel] + +/-- A batch of independent products, indexed by the group and two +outer indices. The right input has column before inner index. -/ +abbrev Port (G A H : Type) := G × A × H +/-- Indexes the out by the coordinates of `G × A × A`. -/ +abbrev Out (G A : Type) := G × A × A + +open Classical in +/-- Selects the appropriate branch of `if x.1 = z.1 ∧ y.1 = z.1 ∧ x.2.1 = z.2.1 ∧ y.2.1 = z.2.2 +∧ x.2.2 = y.2.2 then 1 else 0`. -/ +def batch (F : Type*) [Field F] (G A H : Type) (z : Out G A) (x y : Port G A H) : F := + if x.1 = z.1 ∧ y.1 = z.1 ∧ x.2.1 = z.2.1 ∧ y.2.1 = z.2.2 ∧ x.2.2 = y.2.2 then 1 else 0 + +/-- Common measurements in this seed vanish whenever the two inputs +belong to the same group and the same summation index. -/ +structure Seed (F : Type*) [Field F] (G A H E C : Type) [Fintype C] where + /-- The `Seed` component of type `Out G A → Product F (Port G A H) (Port G A H)`. -/ + main : Out G A → Product F (Port G A H) (Port G A H) + /-- The `Seed` component of type `E → Product F (Port G A H) (Port G A H)`. -/ + extra : E → Product F (Port G A H) (Port G A H) + /-- The encoding map carried by `Seed`, with type `Out G A → C → E`. -/ + code : Out G A → C → E + eqn : ∀ z x y, batch F G A H z x y = + (main z).apply x y - ∑ t, (extra (code z t)).apply x y + aligned : ∀ t x y, x.1 = y.1 → x.2.2 = y.2.2 → (extra t).apply x y = 0 + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- +# A joint outer-product and dot-product identity + +Use two affine lines of each nonzero slope in a finite auxiliary field. +Each pair of a left and a right line intersects exactly once, except +parallel lines of the same slope. Subtracting the product at every grid +point from the unrestricted product leaves the dot product of equal +slopes. All encoder entries are zero or one over the target field. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior + +open scoped Classical in +/-- Indexes the letter by the coordinates of `K ⊕ Kˣ`. -/ +abbrev Letter (K : Type) [Field K] := K ⊕ Kˣ + +variable {K : Type} [Field K] + +open scoped Classical in +/-- The two cases impose `p.1 = i` and `p.1 = h * p.2`, respectively. -/ +def left : Letter K → K × K → Prop + | .inl i, p => p.1 = i + | .inr h, p => p.1 = h * p.2 + +open scoped Classical in +/-- The two cases impose `p.2 = j` and `p.1 = h * p.2 + 1`, respectively. -/ +def right : Letter K → K × K → Prop + | .inl j, p => p.2 = j + | .inr h, p => p.1 = h * p.2 + 1 + +open scoped Classical in +private theorem parallel (a : Kˣ) (p : K × K) : ¬ (left (.inr a) p ∧ right (.inr a) p) := by + simp [left, right] + grind + +open scoped Classical in +private theorem meet (x y : Letter K) (h : ¬ ∃ a, x = .inr a ∧ y = .inr a) : + ∃! p, left x p ∧ right y p := by + rcases x with i | a <;> rcases y with j | b + · exact ⟨(i, j), ⟨rfl, rfl⟩, fun p hp => Prod.ext hp.1 hp.2⟩ + · refine ⟨(i, (i - 1) / b), ⟨rfl, ?_⟩, ?_⟩ + · change i = (b : K) * ((i - 1) / b) + 1 + rw [mul_div_cancel₀ _ b.ne_zero, sub_add_cancel] + · rintro ⟨u, v⟩ ⟨hu, hv⟩ + change u = i at hu + change u = (b : K) * v + 1 at hv + subst u + refine Prod.ext rfl ((eq_div_iff b.ne_zero).mpr ?_) + rw [hv] + ring + · refine ⟨(a * j, j), ⟨rfl, rfl⟩, ?_⟩ + intro p hp + exact Prod.ext (hp.1.trans (congrArg ((a : K) * ·) hp.2)) hp.2 + · have hab : (a : K) ≠ b := by + intro he + exact h ⟨a, rfl, by rw [Units.ext he]⟩ + let z := ((a : K) - b)⁻¹ + have he : ((a : K) - b) * z = 1 := mul_inv_cancel₀ (sub_ne_zero.mpr hab) + refine ⟨(a * z, z), ⟨rfl, ?_⟩, ?_⟩ + · change (a : K) * z = b * z + 1 + rw [← he]; ring + · rintro ⟨u, v⟩ ⟨hu, hv⟩ + change u = (a : K) * v at hu + change u = (b : K) * v + 1 at hv + have hh : ((a : K) - b) * v = 1 := by rw [sub_mul, ← hu, hv]; ring + have hz : v = z := mul_left_cancel₀ (sub_ne_zero.mpr hab) (hh.trans he.symm) + exact Prod.ext (hu.trans (congrArg ((a : K) * ·) hz)) hz + +variable (F : Type*) [Field F] + +open scoped Classical in +/-- Returns `1` when `left x p` holds, and `0` otherwise. -/ +def encoderL (p : K × K) (x : Letter K) : F := if left x p then 1 else 0 +open scoped Classical in +/-- Returns `1` when `right x p` holds, and `0` otherwise. -/ +def encoderR (p : K × K) (x : Letter K) : F := if right x p then 1 else 0 + +open scoped Classical in +theorem ordinary_entry (p : K × K) (i j : K) : + encoderL F p (.inl i) * encoderR F p (.inl j) = if p = (i, j) then 1 else 0 := by + by_cases h : p.1 = i <;> by_cases h' : p.2 = j <;> + simp [encoderL, encoderR, left, right, Prod.ext_iff, h, h'] + +open scoped Classical in +theorem equal_entry (p : K × K) (a : Kˣ) : + encoderL F p (.inr a) * encoderR F p (.inr a) = 0 := by + have h := parallel a p + grind [encoderL, encoderR] + +open scoped Classical in +theorem dot_entry [Fintype K] (x y : Letter K) : + 1 - ∑ p, encoderL F p x * encoderR F p y = + if ∃ a, x = .inr a ∧ y = .inr a then 1 else 0 := by + split_ifs with h + · obtain ⟨a, rfl, rfl⟩ := h + simp [equal_entry] + obtain ⟨p, hp, hu⟩ := meet x y h + rw [Fintype.sum_eq_single p] + · simp [encoderL, encoderR, hp.1, hp.2] + · intro t ht + have he : ¬ (left x t ∧ right y t) := fun he => ht (hu t he) + grind [encoderL, encoderR] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- +# One distinguished position per block + +Use a line slope in one position, and ordinary indices in the +others. Reading the dot-product identity at the distinguished +position gives independent products, all with the same correction +dictionary indexed by words of ordinary grid points. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior + +variable (F : Type*) [Field F] {K : Type} [Field K] {n : ℕ} + +open scoped Classical in +/-- The quantity computed by `Port (Fin (n + 1)) (Fin n → K) Kˣ`. -/ +abbrev InFromBlock (K : Type) [Field K] (n : ℕ) := Port (Fin (n + 1)) (Fin n → K) Kˣ +open scoped Classical in +/-- The quantity computed by `Out (Fin (n + 1)) (Fin n → K)`. -/ +abbrev OutputFromBlock (K : Type) (n : ℕ) := Out (Fin (n + 1)) (Fin n → K) + +open scoped Classical in +/-- The indexed operation `x.1.insertNth (.inr x.2.2) (fun l => .inl (x.2.1 l))`. -/ +def encode (x : InFromBlock K n) : Fin (n + 1) → Letter K := + x.1.insertNth (.inr x.2.2) (fun l => .inl (x.2.1 l)) + +open scoped Classical in +theorem encode_slope (x : InFromBlock K n) (i : Fin (n + 1)) (a : Kˣ) : + encode x i = .inr a ↔ x.1 = i ∧ x.2.2 = a := by + by_cases h : x.1 = i + · subst i; simp [encode] + obtain ⟨l, rfl⟩ := Fin.exists_succAbove_eq (Ne.symm h) + simp [encode, h] + +open scoped Classical in +/-- The value specified by `(z.2.1 l, z.2.2 l)`. -/ +def point (z : OutputFromBlock K n) (l : Fin n) : K × K := (z.2.1 l, z.2.2 l) + +open scoped Classical in +/-- The indexed operation `⟨fun x => ∏ l, encoderL F (point z l) (encode x (z.1.succAbove l)), +fun y => ∏ l, encoderR F (point z l) (encode y (z.1.succAbove l))⟩`. -/ +def primary (z : OutputFromBlock K n) : Product F (InFromBlock K n) (InFromBlock K n) := + ⟨fun x => ∏ l, encoderL F (point z l) (encode x (z.1.succAbove l)), + fun y => ∏ l, encoderR F (point z l) (encode y (z.1.succAbove l))⟩ + +open scoped Classical in +/-- Uses `⟨fun x => ∏ l, encoderL F (q l) (encode x l), fun y => ∏ l, encoderR F (q l) (encode y +l)⟩` as the representation. -/ +def ordinaryBlock (q : Fin (n + 1) → K × K) : Product F (InFromBlock K n) (InFromBlock K n) + := + ⟨fun x => ∏ l, encoderL F (q l) (encode x l), fun y => ∏ l, encoderR F (q l) (encode y l)⟩ + +open scoped Classical in +theorem expand (z : OutputFromBlock K n) (x y : InFromBlock K n) (a : K × K) : + (ordinaryBlock F (z.1.insertNth a (point z))).apply x y = + encoderL F a (encode x z.1) * encoderR F a (encode y z.1) * (primary F z).apply x y := by + unfold Product.apply ordinaryBlock primary + simp only [← Finset.prod_mul_distrib] + rw [Fin.prod_univ_succAbove _ z.1] + simp + +open scoped Classical in +theorem primary_eq (g : Fin (n + 1)) (x y u v : Fin n → K) (a : Kˣ) : + (primary F (g, u, v)).apply (g, x, a) (g, y, a) = if x = u ∧ y = v then 1 else 0 := by + simp only [Product.apply, primary, point, encode, Fin.insertNth_apply_succAbove, + ← Finset.prod_mul_distrib, + ordinary_entry, Fintype.prod_ite_zero, Finset.prod_const_one, Prod.mk.injEq, forall_and, + ← funext_iff] + congr 1 + exact propext (and_congr eq_comm eq_comm) + +open scoped Classical in +/-- The auxiliary field indexes zero-one coefficients over `F`. -/ +def blockSeed (K : Type) [Field K] [Fintype K] (n : ℕ) : + Seed F (Fin (n + 1)) (Fin n → K) Kˣ (Fin (n + 1) → K × K) (K × K) where + main := primary F + extra := ordinaryBlock F + code z a := z.1.insertNth a (point z) + eqn z x y := by + simp only [expand, ← Finset.sum_mul, ← one_sub_mul, dot_entry] + simp_rw [encode_slope] + by_cases he : x.1 = z.1 ∧ y.1 = z.1 ∧ x.2.2 = y.2.2 + · rcases z with ⟨g, u, v⟩ + rcases x with ⟨g', x, a⟩ + rcases y with ⟨g'', y, b⟩ + change g' = g ∧ g'' = g ∧ a = b at he + obtain ⟨rfl, rfl, rfl⟩ := he + simp [batch, primary_eq] + · unfold batch + grind + aligned q x y hg ha := by + simp only [ordinaryBlock, Product.apply, ← Finset.prod_mul_distrib] + apply Finset.prod_eq_zero (Finset.mem_univ x.1) + rw [(encode_slope x _ _).2 ⟨rfl, rfl⟩, (encode_slope y _ _).2 ⟨hg.symm, ha.symm⟩] + exact equal_entry F _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +section +/- # Choosing the grid to retain a quadratic saving -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior + +/-- The width overhead grows linearly in the mesh parameter while +the block length grows quadratically. A mesh parameter proportional +to the inverse gap leaves room on both output sides. -/ +theorem parameters {x y z a : ℝ} (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hz : 0 ≤ z) (hz' : z < x * y) (ha : 1 ≤ a) : + ∃ (q : ℕ) (l θ φ : ℝ), 1 ≤ l ∧ (q : ℝ) = l * l ∧ 0 < θ ∧ θ < φ ∧ + φ * (x * q + a * l) ≤ x ∧ φ * (y * q + a * l) ≤ y ∧ z ≤ θ * (x * y * q) ∧ + (1 / (16 * (4 * a + 1) ^ 2)) * (x * y - z) ^ 2 ≤ θ / 4 := by + let g := x * y - z + have hg : 0 < g := sub_pos.mpr hz' + have hg' : g ≤ 1 := by unfold g; nlinarith + let t := g / (x * y) + have ht : 0 < t := by unfold t; positivity + have ht' : t ≤ 1 := (div_le_one (by positivity)).mpr (sub_le_self _ hz) + have ht₀ : t * (x * y) = g := div_mul_cancel₀ _ (by positivity) + let m := ⌈4 * a / g⌉₊ + let l : ℝ := m + have hl : 1 ≤ l := Nat.one_le_cast.mpr (Nat.ceil_pos.mpr (by positivity)) + have hlo : 4 * a ≤ l * g := (div_le_iff₀ hg).mp (Nat.le_ceil _) + have hhi : l * g ≤ 4 * a + 1 := by + calc + _ ≤ (4 * a / g + 1) * g := mul_le_mul_of_nonneg_right (Nat.ceil_lt_add_one (by + positivity)).le hg.le + _ = 4 * a + g := by rw [add_mul, div_mul_cancel₀ _ hg.ne', one_mul] + _ ≤ _ := by linarith + let q := m * m + have hq : (q : ℝ) = l * l := Nat.cast_mul _ _ + have hq' : 0 < (q : ℝ) := by rw [hq]; positivity + let θ := (1 - 3 * t / 4) / q + let φ := (1 - t / 2) / q + have he : θ * q = 1 - 3 * t / 4 := div_mul_cancel₀ _ hq'.ne' + have hf : φ * q = 1 - t / 2 := div_mul_cancel₀ _ hq'.ne' + have hθ : 0 < θ := div_pos (by linarith) hq' + have hφ : θ < φ := div_lt_div_of_pos_right (by linarith) hq' + have hcost : a * l ≤ q * g / 4 := by + rw [hq] + linarith [mul_le_mul_of_nonneg_right hlo (by linarith : 0 ≤ l)] + have outer (b : ℝ) (hb : x * y ≤ b) : φ * (b * q + a * l) ≤ b := by + calc + _ ≤ φ * (b * q + q * g / 4) := by gcongr; linarith + _ = (φ * q) * (b + g / 4) := by ring + _ ≤ b := by + rw [hf] + linarith [mul_le_mul_of_nonneg_left hb ht.le, mul_nonneg ht.le hg.le] + refine ⟨q, l, θ, φ, hl, hq, hθ, hφ, outer x (by nlinarith), outer y (by nlinarith), ?_, ?_⟩ + · rw [show θ * (x * y * q) = (θ * q) * (x * y) by ring, he] + change t * (x * y) = x * y - z at ht₀ + linarith + · have hsq : (q : ℝ) * g ^ 2 ≤ (4 * a + 1) ^ 2 := by + rw [hq, show l * l * g ^ 2 = (l * g) ^ 2 by ring] + gcongr + change (1 / (16 * (4 * a + 1) ^ 2)) * g ^ 2 ≤ θ / 4 + rw [one_div_mul_eq_div, div_le_iff₀ (by positivity)] + calc + _ ≤ (4 * θ * q) * g ^ 2 := le_mul_of_one_le_left (by positivity) (by linarith) + _ = (4 * θ) * (q * g ^ 2) := by ring + _ ≤ (4 * θ) * (4 * a + 1) ^ 2 := by gcongr + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- # Tiling output rectangles while retaining private products -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset + +variable {F : Type*} [Field F] {X Y Z X' Y' Z' U V : Type} {M : Z → X → Y → F} {r : ℕ} + +theorem Private.pull (h : Private M r) (a : X' → X) (b : Y' → Y) (c : Z' → Z) : + Private (fun z x y => M (c z) (a x) (b y)) r := by + obtain ⟨p, q, d, he⟩ := h + let map (t : Product F X Y) : Product F X' Y' := ⟨t.left ∘ a, t.right ∘ b⟩ + exact ⟨fun z => map (p (c z)), fun l => map (q l), d ∘ c, fun z x y => he _ _ _⟩ + +theorem Private.collect [Fintype U] [Fintype V] (h : Private M r) + (a : X' → U → X) (b : Y' → V → Y) (c : Z' → Z) : + Private (fun z x y => ∑ i, ∑ j, M (c z) (a x i) (b y j)) r := by + obtain ⟨p, q, d, he⟩ := h + let map (t : Product F X Y) : Product F X' Y' := + ⟨fun x => ∑ i, t.left (a x i), fun y => ∑ j, t.right (b y j)⟩ + have hv (t : Product F X Y) (x y) : + (map t).apply x y = ∑ i, ∑ j, t.apply (a x i) (b y j) := by + simp only [map, Product.apply, sum_mul, mul_sum] + rw [sum_comm] + refine ⟨fun z => map (p (c z)), fun l => map (q l), d ∘ c, ?_⟩ + intro z x y + simp only [he, hv, Function.comp_apply, sum_add_distrib, mul_sum] + congr 1 + simp_rw [sum_comm (s := (univ : Finset V)) (t := (univ : Finset (Fin r)))] + rw [sum_comm] + +variable {i j k i' j' k' : ℕ} + +theorem PrivateProducts.cut (h : PrivateProducts F i j k r) (hi : i' ≤ i) (hj : j' ≤ j) + (hk : k' ≤ k) : PrivateProducts F i' j' k' r := by + let lift {a b a' b'} (ha : a' ≤ a) (hb : b' ≤ b) (x : Pos a' b') : Pos a b := + (Fin.castLE ha x.1, Fin.castLE hb x.2) + have he := Private.pull h (lift hi hk) (lift hk hj) (lift hi hj) + simpa only [PrivateProducts, lift, Fin.castLE_inj] using he + +theorem PrivateProducts.rank (h : PrivateProducts F i j k r) : RankLE F i j k (i * j + r) := by + obtain ⟨p, q, d, he⟩ := h + let e : (Pos i j ⊕ Fin r) ≃ Fin (i * j + r) := + (Equiv.sumCongr finProdFinEquiv (Equiv.refl _)).trans finSumFinEquiv + let s l := (e.symm l).elim p q + refine ⟨fun l => (s l).left, fun l => (s l).right, + fun l z => (e.symm l).elim (fun t => if t = z then 1 else 0) (d z), ?_⟩ + intro x y z + rw [← e.sum_comp, Fintype.sum_sum_type] + simp only [s, Equiv.symm_apply_apply, Sum.elim_inl, Sum.elim_inr, mul_ite, mul_one, mul_zero, + Fintype.sum_ite_eq'] + simpa only [Product.apply, mul_comm] using (he z x y).symm + +/-- Glue independent square tiles by identifying the inputs they share. -/ +theorem tile {G A H : Type} {s a k : ℕ} (g : Pos s s ≃ G) (u : Fin a ≃ A) (v : Fin k ≃ H) + (h : Private (batch F G A H) r) : PrivateProducts F (s * a) (s * a) k r := by + classical + let e : Fin (s * a) ≃ Pos s a := finProdFinEquiv.symm + let X (x : Pos (s * a) k) (j : Fin s) : Port G A H := (g ((e x.1).1, j), u (e x.1).2, v x.2) + let Y (y : Pos k (s * a)) (i : Fin s) : Port G A H := (g (i, (e y.2).1), u (e y.2).2, v y.1) + let Z (z : Pos (s * a) (s * a)) : Out G A := + (g ((e z.1).1, (e z.2).1), u (e z.1).2, u (e z.2).2) + have hh := h.collect X Y Z + unfold PrivateProducts + convert hh using 1 + funext z x y + have hx (j i) : batch F G A H (Z z) (X x j) (Y y i) = + if j = (e z.2).1 ∧ i = (e z.1).1 then + if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then 1 else 0 else 0 := by + have he (x y : Fin (s * a)) : x = y ↔ (e x).1 = (e y).1 ∧ (e x).2 = (e y).2 := + e.injective.eq_iff.symm.trans Prod.ext_iff + simp only [batch, X, Y, Z, Equiv.apply_eq_iff_eq, Prod.mk.injEq, he x.1 z.1, he y.2 z.2, + ← ite_and] + congr 1 + exact propext (by tauto) + simp [hx, ite_and] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- +# Converting short sums to private products + +Across a square array of groups, a short sum of separable forms is +itself a thin matrix product. Only the private terms of distinguished +sums remain private. All products for other sums are shared. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset + +variable {F : Type*} [Field F] {X Y Z O : Type} {m n r : ℕ} + +/-- The slots of type `Prop` for the given inputs. -/ +def Slots (M : Z → X → Y → F) (r m : ℕ) : Prop := + ∃ (a : Z ⊕ Fin r → Fin m → Product F X Y) (c : Z → Fin r → F), ∀ z x y, + M z x y = (∑ j, (a (.inl z) j).apply x y) + ∑ l, c z l * ∑ j, (a (.inr l) j).apply x y + +/-- Returns `(1 : F)` when `x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2` holds, and `0` otherwise. -/ +def matrix (F : Type*) [Field F] (i j k : ℕ) (z : Pos i j) (x : Pos i k) (y : Pos k j) := + if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then (1 : F) else 0 + +/-- Returns `∑ j, (a j).apply x.2 y.2` when `x.1 = z.1 ∧ y.1 = z.2` holds, and `0` otherwise. -/ +def signal (a : Fin m → Product F X Y) (z : Pos n n) (x : Fin n × X) (y : Fin n × Y) : F := + if x.1 = z.1 ∧ y.1 = z.2 then ∑ j, (a j).apply x.2 y.2 else 0 + +private theorem signal_private (a : Fin m → Product F X Y) (h : PrivateProducts F n n m r) : + Private (signal (n := n) a) r := by + obtain ⟨p, q, c, he⟩ := h + let lift (b : Product F (Pos n m) (Pos m n)) : Product F (Fin n × X) (Fin n × Y) := + ⟨fun x => ∑ i, (a i).left x.2 * b.left (x.1, i), + fun y => ∑ j, (a j).right y.2 * b.right (j, y.1)⟩ + have eqn (b) (x y) : (lift b).apply x y = + ∑ i, ∑ j, (a i).left x.2 * (a j).right y.2 * b.apply (x.1, i) (j, y.1) := by + simp only [Product.apply, lift, sum_mul, mul_sum] + rw [sum_comm] + exact sum_congr rfl fun _ _ => sum_congr rfl fun _ _ => by ring + refine ⟨lift ∘ p, lift ∘ q, c, fun z x y => ?_⟩ + have target : signal a z x y = ∑ i, ∑ j, (a i).left x.2 * (a j).right y.2 * + matrix F n n m z (x.1, i) (j, y.1) := by + by_cases h₁ : x.1 = z.1 <;> by_cases h₂ : y.1 = z.2 <;> + simp [signal, matrix, h₁, h₂, mul_ite, Product.apply] + change ∀ z x y, matrix F n n m z x y = _ at he + rw [target] + simp only [Function.comp_apply, eqn, he, mul_add, sum_add_distrib, mul_sum] + congr 1 + rw [sum_comm (s := (univ : Finset (Fin r)))] + apply sum_congr rfl + intro i _ + rw [sum_comm (s := (univ : Finset (Fin r)))] + exact sum_congr rfl fun _ _ => sum_congr rfl fun _ _ => by ring + +/-- Charge all corrections at each slot and all private products of +the common slots. -/ +private theorem shared [Fintype Z] [Fintype O] + (T : Z ⊕ Fin r → O → X → Y → F) (c : Z → Fin r → F) (h : ∀ i, Private (T i) m) : + Private (fun (p : Z × O) x y => T (.inl p.1) p.2 x y + ∑ j, c p.1 j * T (.inr j) p.2 x y) + ((Fintype.card Z + r) * m + r * Fintype.card O) := by + choose a b d he using h + let E := ((Z ⊕ Fin r) × Fin m) ⊕ (Fin r × O) + let B : E → Product F X Y := Sum.elim (fun p => b p.1 p.2) (fun p => a (.inr p.1) p.2) + let W := Submodule.span F (Set.range fun l => (B l).apply) + have hb i z : T i z - (a i z).apply ∈ W := by + have h' : T i z - (a i z).apply = ∑ l, d i z l • (b i l).apply := by + funext x y + simp only [Finset.sum_apply, Pi.smul_apply, Pi.sub_apply, smul_eq_mul, he, + add_sub_cancel_left] + rw [h'] + exact W.sum_mem fun l _ => W.smul_mem _ (Submodule.subset_span ⟨.inl (i, l), rfl⟩) + have ha i z : T (.inr i) z ∈ W := by + have hh : (a (.inr i) z).apply ∈ W := Submodule.subset_span ⟨.inr (i, z), rfl⟩ + simpa using W.add_mem (hb (.inr i) z) hh + rw [show (Fintype.card Z + r) * m + r * Fintype.card O = Fintype.card E by simp [E]] + refine private_of_span _ (fun z => a (.inl z.1) z.2) B ?_ + intro z + have hs : (∑ j, c z.1 j • T (.inr j) z.2) ∈ W := W.sum_mem fun j _ => W.smul_mem _ (ha j z.2) + convert W.add_mem (hb (.inl z.1) z.2) hs using 1 + funext x y + simp only [Pi.sub_apply, Pi.add_apply, Finset.sum_apply, Pi.smul_apply, smul_eq_mul] + ring + +theorem Slots.enlarge {i j k p b e : ℕ} (h : Slots (matrix F i j k) e p) + (hb : PrivateProducts F b b p r) : + PrivateProducts F (i * b) (j * b) k ((i * j + e) * r + e * (b * b)) := by + obtain ⟨a, c, he⟩ := h + have hs := shared (fun t => signal (n := b) (a t)) c (fun t => signal_private (a t) hb) + let I : Fin (i * b) ≃ Pos i b := finProdFinEquiv.symm + let J : Fin (j * b) ≃ Pos j b := finProdFinEquiv.symm + let x (p : Pos (i * b) k) := ((I p.1).2, (I p.1).1, p.2) + let y (p : Pos k (j * b)) := ((J p.2).2, p.1, (J p.2).1) + let z (p : Pos (i * b) (j * b)) := (((I p.1).1, (J p.2).1), ((I p.1).2, (J p.2).2)) + have hh := hs.pull x y z + simp only [Pos, Fintype.card_prod, Fintype.card_fin] at hh + unfold PrivateProducts + convert hh using 1 + funext w u v + have hi (p q : Fin (i * b)) := (I.injective.eq_iff (a := p) (b := q)).symm.trans Prod.ext_iff + have hj (p q : Fin (j * b)) := (J.injective.eq_iff (a := p) (b := q)).symm.trans Prod.ext_iff + simp only [signal, x, y, z, hi u.1 w.1, hj v.2 w.2] + by_cases ht : (I u.1).2 = (I w.1).2 ∧ (J v.2).2 = (J w.2).2 + · simp only [ht.1, ht.2, and_true, ↓reduceIte] + exact he ((I w.1).1, (J w.2).1) ((I u.1).1, u.2) (v.1, (J v.2).1) + · simp only [ite_eq_right ht, mul_zero, sum_const_zero, add_zero] + apply ite_eq_right + tauto + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +section +/- # Replicating private rectangles and cutting off the boundary -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior + +variable {F : Type*} [Field F] {i j k r : ℕ} + +open scoped Classical in +theorem PrivateProducts.repeat (h : PrivateProducts F i j k r) (a b : ℕ) : + PrivateProducts F (a * i) (b * j) k (a * b * r) := by + obtain ⟨p, q, c, he⟩ := h + let I : Fin (a * i) ≃ Pos a i := finProdFinEquiv.symm + let J : Fin (b * j) ≃ Pos b j := finProdFinEquiv.symm + let z (p : Pos (a * i) (b * j)) := ((I p.1).2, (J p.2).2) + let g (p : Pos (a * i) (b * j)) := ((I p.1).1, (J p.2).1) + let x (p : Pos (a * i) k) := ((I p.1).2, p.2) + let y (p : Pos k (b * j)) := (p.1, (J p.2).2) + let lift (s : Pos a b) (t : Product F (Pos i k) (Pos k j)) : Product F (Pos (a * i) k) (Pos k (b + * j)) := + ⟨fun u => if (I u.1).1 = s.1 then t.left (x u) else 0, + fun v => if (J v.2).1 = s.2 then t.right (y v) else 0⟩ + let E := Pos a b × Fin r + let e := (Equiv.prodCongr (finProdFinEquiv (m := a) (n := b)) (Equiv.refl (Fin r))).trans + finProdFinEquiv + refine ⟨fun w => lift (g w) (p (z w)), fun l => lift (e.symm l).1 (q (e.symm l).2), + fun w l => if (e.symm l).1 = g w then c (z w) (e.symm l).2 else 0, ?_⟩ + intro w u v + rw [← e.sum_comp, Fintype.sum_prod_type, Finset.sum_comm] + simp only [Equiv.symm_apply_apply, ite_mul, zero_mul, Fintype.sum_ite_eq'] + have hi (p q : Fin (a * i)) := (I.injective.eq_iff (a := p) (b := q)).symm.trans Prod.ext_iff + have hj (p q : Fin (b * j)) := (J.injective.eq_iff (a := p) (b := q)).symm.trans Prod.ext_iff + simp only [hi u.1 w.1, hj v.2 w.2] + by_cases hu : (I u.1).1 = (I w.1).1 + · by_cases hv : (J v.2).1 = (J w.2).1 + · simpa only [lift, g, x, y, z, Product.apply, hu, hv, true_and, ↓reduceIte] + using he (z w) (x u) (y v) + · simp [lift, g, Product.apply, hv] + · simp [lift, g, Product.apply, hu] + +open scoped Classical in +theorem PrivateProducts.cover (h : PrivateProducts F i j k r) {I J K : ℕ} + (hi : 0 < i) (hi' : i ≤ I) (hj : 0 < j) (hj' : j ≤ J) (hk : K ≤ k) : + ∃ R, PrivateProducts F I J K R ∧ R * (i * j) ≤ 4 * (I * J) * r := by + have round (i I : ℕ) (hi : 0 < i) (hi' : i ≤ I) : + ∃ m, I ≤ m * i ∧ m * i ≤ 2 * I := by + refine ⟨I / i + 1, ?_, ?_⟩ + · rw [Nat.add_mul, Nat.one_mul] + have := Nat.mod_lt I hi + have := Nat.mod_add_div' I i + omega + · rw [Nat.add_mul, Nat.one_mul] + have := Nat.div_mul_le_self I i + omega + obtain ⟨a, ha, ha'⟩ := round i I hi hi' + obtain ⟨b, hb, hb'⟩ := round j J hj hj' + refine ⟨a * b * r, (h.repeat a b).cut ha hb hk, ?_⟩ + calc + _ = (a * i) * (b * j) * r := by ring + _ ≤ (2 * I) * (2 * J) * r := by gcongr + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- # Filling arbitrary output rectangles from a geometric sequence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Filter + +variable {F : Type*} [Field F] {x y z b : ℝ} + +theorem PrivateProducts.map {K : Type*} [Field K] (f : K →+* F) {i j k r : ℕ} + (h : PrivateProducts K i j k r) : PrivateProducts F i j k r := by + obtain ⟨p, q, c, he⟩ := h + let lift (a : Product K (Pos i k) (Pos k j)) : Product F _ _ := ⟨f ∘ a.left, f ∘ a.right⟩ + refine ⟨lift ∘ p, lift ∘ q, fun t u => f (c t u), fun t u v => ?_⟩ + simpa only [Function.comp_apply, lift, Product.apply, apply_ite f, map_zero, map_one, + map_add, map_mul, map_sum] using congrArg f (he t u v) + +private theorem between {θ φ : ℝ} (hb : 1 < b) (hθ : 0 < θ) (hφ : θ < φ) (n₀ : ℕ) : + ∀ᶠ m : ℕ in atTop, ∃ n ≥ n₀, (m : ℝ) ^ θ ≤ b ^ n ∧ b ^ n ≤ (m : ℝ) ^ φ := by + have h₁ := (tendsto_rpow_atTop hθ).comp tendsto_natCast_atTop_atTop + have h₂ := (tendsto_rpow_atTop (sub_pos.mpr hφ)).comp tendsto_natCast_atTop_atTop + filter_upwards [eventually_ge_atTop 1, h₁.eventually_ge_atTop (b ^ n₀), + h₂.eventually_ge_atTop b] with m hm hmn hmg + have hm' : 1 ≤ (m : ℝ) := by exact_mod_cast hm + obtain ⟨n, hn, hn'⟩ := exists_nat_pow_near (Real.one_le_rpow hm' hθ.le) hb + refine ⟨n + 1, ?_, hn'.le, ?_⟩ + · by_contra! hlt + exact hn'.not_ge ((pow_le_pow_right₀ hb.le hlt.le).trans hmn) + · rw [pow_succ, show φ = θ + (φ - θ) by ring, Real.rpow_add (by positivity)] + exact mul_le_mul hn hmg (by positivity) (by positivity) + +theorem fill {X Y Z θ φ δ : ℝ} (hb : 1 < b) (hθ : 0 < θ) (hφ : θ < φ) + (hX : 0 ≤ X) (hY : 0 ≤ Y) (hZ : 0 ≤ Z) + (hx : φ * X ≤ x) (hy : φ * Y ≤ y) (hz : z ≤ θ * Z) (hδ : δ ≤ θ / 4) + (h : ∀ᶠ n : ℕ in atTop, ∃ i j k r : ℕ, 0 < i ∧ 0 < j ∧ (i : ℝ) ≤ (b ^ n) ^ X ∧ + (j : ℝ) ≤ (b ^ n) ^ Y ∧ (b ^ n) ^ Z ≤ k ∧ (r : ℝ) * (b ^ n) ^ (1 / 4 : ℝ) ≤ 3 * i * j + ∧ PrivateProducts F i j k r) : + ∀ᶠ m : ℕ in atTop, ∃ r : ℕ, PrivateProducts F (side m x) (side m y) (side m z) r ∧ + (r : ℝ) ≤ 12 * side m x * side m y * (m : ℝ) ^ (-δ) := by + obtain ⟨n₀, hn⟩ := eventually_atTop.mp h + filter_upwards [eventually_ge_atTop 1, between hb hθ hφ n₀] with m hm hseq + have hm' : 1 ≤ (m : ℝ) := by exact_mod_cast hm + obtain ⟨n, h₀, hlo, hhi⟩ := hseq + obtain ⟨i, j, k, r, hi, hj, hI, hJ, hK, hr, hp⟩ := hn n h₀ + have outer {i : ℕ} {a A : ℝ} (ha : 0 ≤ A) (ha' : φ * A ≤ a) (hs : (i : ℝ) ≤ (b ^ n) ^ A) : + i ≤ side m a := by + apply (Nat.cast_le (α := ℝ)).mp + calc + (i : ℝ) ≤ ((m : ℝ) ^ φ) ^ A := hs.trans (Real.rpow_le_rpow (by positivity) hhi ha) + _ ≤ (m : ℝ) ^ a := by rw [← Real.rpow_mul (by positivity)]; gcongr + _ ≤ _ := Nat.le_ceil _ + have inner {a A : ℝ} (ha : 0 ≤ A) (ha' : a ≤ θ * A) : (m : ℝ) ^ a ≤ (b ^ n) ^ A := by + apply le_trans (Real.rpow_le_rpow_of_exponent_le hm' ha') + rw [Real.rpow_mul (by positivity)] + exact Real.rpow_le_rpow (by positivity) hlo ha + have hk : side m z ≤ k := Nat.ceil_le.mpr ((inner hZ hz).trans hK) + obtain ⟨R, hR, he⟩ := hp.cover hi (outer hX hx hI) hj (outer hY hy hJ) hk + refine ⟨R, hR, ?_⟩ + rw [Real.rpow_neg (by positivity), ← div_eq_mul_inv, le_div_iff₀ (by positivity)] + apply le_of_mul_le_mul_right _ (show 0 < (i : ℝ) * j by positivity) + have he' : (R : ℝ) * ((i : ℝ) * j) ≤ 4 * ((side m x : ℝ) * side m y) * r := by exact_mod_cast he + have ht : (m : ℝ) ^ δ ≤ (b ^ n) ^ (1 / 4 : ℝ) := inner (by norm_num) (by linarith) + calc + _ = (R : ℝ) * ((i : ℝ) * j) * (m : ℝ) ^ δ := by ring + _ ≤ (4 * ((side m x : ℝ) * side m y) * r) * (b ^ n) ^ (1 / 4 : ℝ) := by gcongr + _ ≤ 4 * ((side m x : ℝ) * side m y) * (3 * i * j) := by rw [mul_assoc]; gcongr + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- +# Cost of words with many corrections + +Give each correction letter weight `2^(b+1)`. If even the weighted +correction alphabet is no larger than the output alphabet, the +high-correction words are at most a fraction `2⁻ⁿ` of the output +words after `b n` positions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset + +variable {O E : Type} {m n : ℕ} + +open scoped Classical in +/-- The value specified by `#{i | (p i).isRight}`. -/ +def changes (p : Fin m → O ⊕ E) : ℕ := #{i | (p i).isRight} + +open scoped Classical in +/-- The subtype of `p : Fin m → O ⊕ E` satisfying `n ≤ changes p`. -/ +abbrev Errors (O E : Type) (m n : ℕ) := {p : Fin m → O ⊕ E // n ≤ changes p} + +variable [Fintype O] [Fintype E] + +open scoped Classical in +theorem error_count (b n : ℕ) (h : 2 ^ (b + 1) * Fintype.card E ≤ Fintype.card O) : + 2 ^ n * Fintype.card (Errors O E (b * n) n) ≤ Fintype.card O ^ (b * n) := by + let q := 2 ^ (b + 1) + let w (p : O ⊕ E) := if p.isRight then q else 1 + have hw (p : Fin (b * n) → O ⊕ E) : q ^ changes p = ∏ i, w (p i) := by + simp [w, changes, prod_ite] + have hs : ∑ p, w p ≤ 2 * Fintype.card O := by + rw [Fintype.sum_sum_type] + change q * Fintype.card E ≤ Fintype.card O at h + rw [Nat.mul_comm q] at h + have hsum := Nat.add_le_add_left h (Fintype.card O) + simpa only [w, Sum.isRight_inl, Sum.isRight_inr, Bool.false_eq_true, ite_false, ite_true, + Finset.sum_const, Finset.card_univ, nsmul_eq_mul, Nat.cast_id, mul_one, two_mul] + using hsum + have he : Fintype.card (Errors O E (b * n) n) * q ^ n ≤ (2 * Fintype.card O) ^ (b * n) := by + rw [Fintype.card_subtype] + calc + _ = ∑ _ ∈ (univ : Finset (Fin (b * n) → O ⊕ E)).filter (fun p => n ≤ changes p), q ^ n + := by simp + _ ≤ ∑ p ∈ univ.filter (fun p : Fin (b * n) → O ⊕ E => n ≤ changes p), ∏ i, w (p i) := by + apply sum_le_sum + intro p hp + rw [← hw] + exact pow_le_pow_right₀ (one_le_pow₀ (by decide)) (mem_filter.mp hp).2 + _ ≤ ∑ p : Fin (b * n) → O ⊕ E, ∏ i, w (p i) := + sum_le_sum_of_subset_of_nonneg (filter_subset _ _) (by intros; positivity) + _ = (∑ p, w p) ^ (b * n) := (Fintype.sum_pow _ _).symm + _ ≤ _ := Nat.pow_le_pow_left hs _ + apply Nat.le_of_mul_le_mul_left (c := 2 ^ (b * n)) _ (by positivity) + simp only [q, pow_succ, mul_pow, ← pow_mul] at he + simpa only [mul_comm, mul_left_comm, mul_assoc] using he + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- +# Removing the middle layers of a product expansion + +If the corrected coordinates vanish at intermediate error counts, +the discrepancy of the private product lies in the span of the raw +words with many errors. This uses distributivity over the ground field. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset + +variable (F : Type*) [Field F] {V : Type*} [CommRing V] [Algebra F V] + {O E C : Type} [Fintype C] {m n : ℕ} + (f : Fin m → O ⊕ E → V) (o : Fin m → O) (e : Fin m → C → E) + +open scoped Classical in +/-- The product of `f i (p i)` indexed by `i`. -/ +def raw (p : Fin m → O ⊕ E) := ∏ i, f i (p i) + +open scoped Classical in +/-- The sum of `f i (.inr (e i j))` indexed by `j`. -/ +def errors (i : Fin m) := ∑ j, f i (.inr (e i j)) + +open scoped Classical in +/-- The product of `if i ∈ s then errors f e i else f i (.inl (o i)) - errors f e i` indexed by +`i`. -/ +def layer (s : Finset (Fin m)) := + ∏ i, if i ∈ s then errors f e i else f i (.inl (o i)) - errors f e i + +open scoped Classical in +private theorem layer_high (s : Finset (Fin m)) (hs : n ≤ s.card) : + layer f o e s ∈ Submodule.span F (Set.range fun p : Errors O E m n => raw f p.val) := by + let W := Submodule.span F (Set.range fun p : Errors O E m n => raw f p.val) + let t (i : Fin m) (c : Option C) : O ⊕ E := c.elim (.inl (o i)) (fun j => .inr (e i j)) + let a (i : Fin m) (c : Option C) : F := + if i ∈ s then if c.isSome then 1 else 0 else if c.isSome then -1 else 1 + have he (i) : (if i ∈ s then errors f e i else f i (.inl (o i)) - errors f e i) = + ∑ c, a i c • f i (t i c) := by + by_cases h : i ∈ s <;> simp [a, t, h, Fintype.sum_option, errors, sub_eq_add_neg] + unfold layer + simp_rw [he] + rw [Fintype.prod_sum] + apply Submodule.sum_mem + intro p _ + have he : (∏ i, a i (p i) • f i (t i (p i))) = + (∏ i, a i (p i)) • raw f (fun i => t i (p i)) := by + simp only [Algebra.smul_def, prod_mul_distrib, map_prod, raw] + rw [he] + by_cases h : ∏ i, a i (p i) = 0 + · simp [h] + have hp : n ≤ changes (fun i => t i (p i)) := by + refine hs.trans (card_le_card ?_) + intro i hi + have hv := prod_ne_zero_iff.mp h i (mem_univ _) + cases hh : p i + · simp [a, hi, hh] at hv + · simp [t, hh] + exact W.smul_mem _ (Submodule.subset_span ⟨⟨_, hp⟩, rfl⟩) + +open scoped Classical in +theorem middle_layers (hz : ∀ s : Finset (Fin m), s.Nonempty → s.card < n → layer f o e s = 0) : + layer f o e ∅ - raw f (fun i => .inl (o i)) ∈ + Submodule.span F (Set.range fun p : Errors O E m n => raw f p.val) := by + let W := Submodule.span F (Set.range fun p : Errors O E m n => raw f p.val) + have he : raw f (fun i => .inl (o i)) = ∑ s, layer f o e s := by + rw [show raw f (fun i => .inl (o i)) = + ∏ i, (errors f e i + (f i (.inl (o i)) - errors f e i)) by simp [raw]] + rw [Fintype.prod_add] + apply sum_congr rfl + intro s _ + simp [layer, prod_ite, compl_eq_univ_sdiff, sdiff_eq_filter] + rw [he, ← add_sum_erase _ _ (mem_univ ∅), sub_add_cancel_left] + apply W.neg_mem + apply W.sum_mem + intro s hs + rcases lt_or_ge s.card n with h | h + · rw [hz s (nonempty_iff_ne_empty.mpr (mem_erase.mp hs).1) h] + exact W.zero_mem + · exact layer_high F f o e s h + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- +# Amplifying a private seed with an agreement code + +The code forces either exact agreement at all slots, annihilating +each common term, or disagreement at many slots, annihilating +all intermediate layers of the corrected expansion. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset + +variable {G A H E C : Type} {F : Type*} [Field F] [Fintype C] {m n k : ℕ} + +open scoped Classical in +private abbrev InFromShell (G A : Type) (m k : ℕ) := Port (Fin m → G) (Fin m → A) (Fin k) +open scoped Classical in +private abbrev OutputFromShell (G A : Type) (m : ℕ) := Out (Fin m → G) (Fin m → A) + +open scoped Classical in +private def out (z : OutputFromShell G A m) (i : Fin m) : Out G A := (z.1 i, z.2.1 i, z.2.2 i) + +variable (c : (Fin m → G) → Fin k → Fin m → H) + +open scoped Classical in +private def read (x : InFromShell G A m k) (i : Fin m) : Port G A H := + (x.1 i, x.2.1 i, c x.1 x.2.2 i) + +open scoped Classical in +private def Separates := ∀ x a y d, (x, a) ≠ (y, d) → + n ≤ hammingDist (fun i => (x i, c x a i)) (fun i => (y i, c y d i)) + +open scoped Classical in +private theorem agreement (h : Separates (n := n) c) {x y : InFromShell G A m k} {s : Finset (Fin + m)} + (hs : s.card < n) (he : ∀ i ∉ s, (read c x i).1 = (read c y i).1 ∧ + (read c x i).2.2 = (read c y i).2.2) : x.1 = y.1 ∧ x.2.2 = y.2.2 := by + apply Prod.mk.inj + by_contra hne + apply hs.not_ge + refine (h _ _ _ _ hne).trans (card_le_card ?_) + intro i hi + by_contra hn + exact (mem_filter.mp hi).2 (Prod.ext (he i hn).1 (he i hn).2) + +variable (S : Seed F G A H E C) + +open scoped Classical in +private def one (t : Out G A ⊕ E) := t.elim S.main S.extra + +open scoped Classical in +private def signalFromShell (i : Fin m) (t : Out G A ⊕ E) (x y : InFromShell G A m k) := + (one S t).apply (read c x i) (read c y i) + +open scoped Classical in +private def wordProduct (t : Fin m → Out G A ⊕ E) : Product F (InFromShell G A m k) (InFromShell G + A m k) := + ⟨fun x => ∏ i, (one S (t i)).left (read c x i), fun y => ∏ i, (one S (t i)).right (read c y i)⟩ + +open scoped Classical in +private theorem word_apply (t) : (wordProduct c S t).apply = raw (signalFromShell c S) t := by + funext x y + simp only [Product.apply, wordProduct, raw, Finset.prod_apply, signalFromShell, prod_mul_distrib] + +open scoped Classical in +private def fixups (z : OutputFromShell G A m) := fun i => S.code (out z i) + +open scoped Classical in +private theorem layer_eq (s : Finset (Fin m)) (z : OutputFromShell G A m) (x y : InFromShell G A m + k) : + layer (signalFromShell c S) (out z) (fixups S z) s x y = + ∏ i, if i ∈ s then ∑ t, (S.extra (fixups S z i t)).apply (read c x i) (read c y i) + else batch F G A H (out z i) (read c x i) (read c y i) := by + simp only [layer, Finset.prod_apply] + apply prod_congr rfl + intro i _ + by_cases he : i ∈ s <;> simp [he, errors, Finset.sum_apply, signalFromShell, one, fixups, S.eqn] + +open scoped Classical in +private theorem middle_zero (h : Separates (n := n) c) (z : OutputFromShell G A m) (s : Finset (Fin + m)) + (hs : s.Nonempty) (hs' : s.card < n) : layer (signalFromShell c S) (out z) (fixups S z) s = 0 + := by + funext x y + simp only [Pi.zero_apply, layer_eq] + by_contra hn + have hv i := prod_ne_zero_iff.mp hn i (mem_univ _) + obtain ⟨hg, hk⟩ := agreement c h (x := x) (y := y) hs' (by + intro i hi + have ht := hv i + simp only [ite_eq_right hi, batch, ne_eq, ite_eq_right_iff, one_ne_zero, imp_false, not_not] + at ht + exact ⟨ht.1.trans ht.2.1.symm, ht.2.2.2.2⟩) + obtain ⟨i, hi⟩ := hs + have he := hv i + rw [ite_eq_left hi] at he + apply he + apply sum_eq_zero + intro t _ + apply S.aligned + · simp [read, hg] + · simp [read, hg, hk] + +open scoped Classical in +private theorem empty_layer (hn : 0 < n) (h : Separates (n := n) c) (z : OutputFromShell G A m) : + layer (signalFromShell c S) (out z) (fixups S z) ∅ = batch F (Fin m → G) (Fin m → A) (Fin k) z + := by + funext x y + simp only [layer_eq, notMem_empty, ↓reduceIte, batch, Fintype.prod_ite_zero, prod_const_one] + congr 1 + apply propext + constructor + · intro he + have hg := agreement c h (x := x) (y := y) (s := ∅) hn (fun i _ => + ⟨(he i).1.trans (he i).2.1.symm, (he i).2.2.2.2⟩) + exact ⟨funext fun i => (he i).1, funext fun i => (he i).2.1, funext fun i => (he i).2.2.1, + funext fun i => (he i).2.2.2.1, hg.2⟩ + · rintro ⟨hg, hg', ha, ha', hk⟩ i + simp [read, out, hg, hg', ha, ha', hk] + +open scoped Classical in +theorem Seed.amplify [Fintype G] [Fintype A] [Fintype E] [Fintype H] {b k n : ℕ} + (S : Seed F G A H E C) (hb : 0 < b) + (hgap : 2 ^ b * Fintype.card G * Fintype.card H * k < Fintype.card H ^ b) + (herr : 2 ^ (b + 1) * Fintype.card E ≤ Fintype.card (Out G A)) (hn : 0 < n) : + ∃ r, 2 ^ n * r ≤ Fintype.card (Out G A) ^ (b * n) ∧ + Private (batch F (Fin (b * n) → G) (Fin (b * n) → A) (Fin (k ^ n))) r := by + obtain ⟨c, hc⟩ := Interior.code hb hgap hn + refine ⟨_, error_count _ _ herr, ?_⟩ + refine private_of_span _ (fun z => wordProduct c S (fun i => .inl (out z i))) + (fun t : Errors (Out G A) E (b * n) n => wordProduct c S t.val) ?_ + intro z + simp_rw [word_apply, ← empty_layer c S hn hc z] + exact middle_layers F _ _ _ (middle_zero c S hc z) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Interior/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Interior/Model.lean new file mode 100644 index 0000000000..c8bdc7720f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Interior/Model.lean @@ -0,0 +1,40 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Model + +/-! # Bilinear formulas with a private product for each output -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior + +/-- Coefficients of a decomposable bilinear form. -/ +structure Product (F : Type*) (X Y : Type) where + /-- The left-side data carried by `Product`, with type `X → F`. -/ + left : X → F + /-- The right-side data carried by `Product`, with type `Y → F`. -/ + right : Y → F + +/-- The quantity computed by `p.left x * p.right y`. -/ +def Product.apply {F : Type*} [Mul F] {X Y : Type} (p : Product F X Y) (x : X) (y : Y) := + p.left x * p.right y + +/-- Each output reads its own product and a linear combination of +common products. No other output reads the private product. -/ +def Private {F : Type*} [Field F] {X Y Z : Type} (M : Z → X → Y → F) (r : ℕ) : Prop := + ∃ (a : Z → Product F X Y) (b : Fin r → Product F X Y) (c : Z → Fin r → F), + ∀ z x y, M z x y = (a z).apply x y + ∑ l, c z l * (b l).apply x y + +/-- Requires `Private (fun (z : Pos i j) (x : Pos i k) (y : Pos k j) => if x.1 = z.1 ∧ x.2 = y.1 +∧ y.2 = z.2 then (1 : F) else 0) r`. -/ +def PrivateProducts (F : Type*) [Field F] (i j k r : ℕ) : Prop := + Private (fun (z : Pos i j) (x : Pos i k) (y : Pos k j) => + if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then (1 : F) else 0) r + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Mask.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Mask.lean new file mode 100644 index 0000000000..3018e8f672 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Mask.lean @@ -0,0 +1,42 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights + +/-! # Output-cell restrictions of a weighted product -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} {i j k : ℕ} + +/-- Returns `w x y z` when `(x, y) ∈ u` holds, and `0` otherwise. -/ +def mask [Zero F] (w : Fin i → Fin j → Fin k → F) (u : Finset (Pos i j)) + (x : Fin i) (y : Fin j) (z : Fin k) : F := if (x, y) ∈ u then w x y z else 0 + +/-- Logarithm of the short side of the most nearly square rectangle +of area `q` fitting in the original format. -/ +noncomputable def short (i j q : ℕ) : ℝ := + min (min (Real.log i) (Real.log j)) (Real.log q / 2) + +/-- The cell bound of type `Prop` for the given inputs. -/ +def CellBound (F : Type*) [Field F] : Prop := + ∀ i j k r : ℕ, 0 < i → 0 < j → 0 < k → + ∀ (w : Fin i → Fin j → Fin k → F) (u : Finset (Pos i j)), + u.Nonempty → (∀ x y z, w x y z ≠ 0 ↔ (x, y) ∈ u) → WeightedRankLE w r → + Real.exp (exponent F (short i j u.card) + (Real.log u.card - short i j u.card) (Real.log k)) ≤ r + +theorem short_bounds {i j q : ℕ} (hi : 0 < i) (hj : 0 < j) (hq : 0 < q) : + 0 ≤ short i j q ∧ short i j q ≤ Real.log q := by + have hlog {n : ℕ} (hn : 0 < n) : 0 ≤ Real.log (n : ℝ) := Real.log_nonneg (by exact_mod_cast hn) + exact ⟨le_min (le_min (hlog hi) (hlog hj)) (by linarith [hlog hq]), + (min_le_right _ _).trans (by linarith [hlog hq])⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Minimum/FaceZero.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Minimum/FaceZero.lean new file mode 100644 index 0000000000..0f26865eed --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Minimum/FaceZero.lean @@ -0,0 +1,884 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.Convex.Slope +public import Mathlib.Basic.Real.Basic +public import Mathlib.Analysis.SpecialFunctions.Integrals.Basic +public import Mathlib.MeasureTheory.Integral.DominatedConvergence + +/-! # Finite secants of a semiconvex defect along one ray -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open Set + +/-- Requires `ConvexOn ℝ (Ici 0) (fun t => g t + C * t ^ 2)`. -/ +def Semiconvex (g : ℝ → ℝ) (C : ℝ) : Prop := + ConvexOn ℝ (Ici 0) (fun t => g t + C * t ^ 2) + +variable {g : ℝ → ℝ} {C a t r : ℝ} + +theorem Semiconvex.slope (h : Semiconvex g C) (ha : 0 < a) (ht : a ≤ t) : + (g a + C * a ^ 2 - g 0) / a ≤ (g t + C * t ^ 2 - g 0) / t := by + simpa using h.secant_mono (show (0 : ℝ) ∈ Ici 0 from Set.mem_Ici.mpr le_rfl) ha.le (ha.trans_le + ht).le + ha.ne' (ha.trans_le ht).ne' ht + +/-- Before subtracting the value at zero, the translated increment may +be negative. The subtracted increment is bounded below by a linear error. -/ +theorem Semiconvex.shift (h : Semiconvex g C) (ha : 0 < a) (ht : 0 < t) : + g a - g 0 - 2 * C * a * t ≤ g (t + a) - g t := by + have h₁ := (div_le_iff₀ ha).mp (h.slope ha (le_add_of_nonneg_left ht.le)) + have h₂ := (div_le_iff₀ ht).mp (h.slope ht (le_add_of_nonneg_right ha.le)) + have he := div_mul_cancel₀ (g (t + a) + C * (t + a) ^ 2 - g 0) (add_pos ht ha).ne' + linarith only [h₁, h₂, he] + +/-- One number controls the change near zero and gives a lower bound at +all larger arguments. No derivative at zero is needed. -/ +theorem Semiconvex.envelope (h : Semiconvex g C) (hC : 0 ≤ C) + (hn : ∀ t, 0 ≤ t → 0 ≤ g t) (hr : 0 < r) : + ∃ S : ℝ, 0 ≤ S ∧ + (∀ t, 0 < t → t ≤ 2 * r → g t - g 0 ≤ t * S) ∧ + (∀ t, 2 * r ≤ t → t * (S - g 0 / (2 * r)) - C * t ^ 2 ≤ g t) := by + let S := (g (2 * r) + C * (2 * r) ^ 2) / (2 * r) + have hz := hn 0 le_rfl + have hr' : 0 < 2 * r := by positivity + have he : (g (2 * r) + C * (2 * r) ^ 2 - g 0) / (2 * r) = S - g 0 / (2 * r) := sub_div _ _ _ + refine ⟨S, div_nonneg (add_nonneg (hn _ hr'.le) (by positivity)) hr'.le, ?_, ?_⟩ + · intro t ht ht' + have hh := (div_le_iff₀ ht).mp (h.slope ht ht') + rw [he] at hh + have hz' : 0 ≤ g 0 / (2 * r) * t := by positivity + have hCt : 0 ≤ C * t ^ 2 := by positivity + linarith + · intro t ht + have hh := (le_div_iff₀ (hr'.trans_le ht)).mp (h.slope hr' ht) + rw [he] at hh + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +section +/- +# Semiconvexity in reciprocal coordinates + +Convexity and the one-sided transport bound make `D(r) + r` convex +and nondecreasing. A quadratic correction then absorbs the negative +reciprocal term left over after composition. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open Set + +/-- The difference of successive slopes has the sign of +`C * (a+x) * (a+y) * (a+z) + K`. -/ +private theorem convex_quadratic_reciprocal {a C K : ℝ} (ha : 0 < a) + (hC : 0 ≤ C) (hK : 0 ≤ C * a ^ 3 + K) : + ConvexOn ℝ (Ici 0) (fun t => C * t ^ 2 + K / (a + t)) := by + apply convexOn_of_slope_mono_adjacent (convex_Ici 0) + intro x y z hx hz hxy hyz + change 0 ≤ x at hx + change 0 ≤ z at hz + have hy := (hx.trans_lt hxy).le + have h₁ := sub_pos.mpr hxy + have h₂ := sub_pos.mpr hyz + have h₃ := sub_pos.mpr (hxy.trans hyz) + let P := (a + x) * (a + y) * (a + z) + have hP : 0 < P := by unfold P; positivity + have hP' : a ^ 3 ≤ P := by + rw [show a ^ 3 = a * a * a by ring] + unfold P + gcongr <;> linarith + have hsign : 0 ≤ C * P + K := hK.trans (by gcongr) + apply sub_nonneg.mp + calc + 0 ≤ (z - x) * (C * P + K) / P := by positivity + _ = _ := by unfold P; field_simp; ring + +private theorem convex_reciprocal {a : ℝ} (ha : 0 < a) : + ConvexOn ℝ (Ici 0) (fun t => 1 / (a + t)) := by + simpa only [zero_mul, zero_add] using + (convex_quadratic_reciprocal (C := 0) (K := 1) ha le_rfl (by simp)) + +theorem reciprocal_semiconvex {D : ℝ → ℝ} (h : ConvexOn ℝ (Ioi 0) D) + (hmono : MonotoneOn (fun r => D r + r) (Ioi 0)) {a b c C : ℝ} + (ha : 0 < a) (hb : 0 < b) (hC : 2 / a ^ 3 ≤ C) : + Semiconvex (fun t => D (1 / (a + t)) - 1 / (a + t) + 1 / (b + t) - c) C := by + have hD : ConvexOn ℝ (Ioi 0) (fun r => D r + r) := h.add (convexOn_id h.1) + have hr := convex_reciprocal ha + have hpos {x : ℝ} (hx : x ∈ Ici 0) : 1 / (a + x) ∈ Ioi 0 := + one_div_pos.mpr (add_pos_of_pos_of_nonneg ha hx) + have hf : ConvexOn ℝ (Ici 0) (fun t => D (1 / (a + t)) + 1 / (a + t)) := by + refine ⟨hr.1, ?_⟩ + intro x hx y hy s t hs ht hst + exact (hmono (hpos (hr.1 hx hy hs ht hst)) (hD.1 (hpos hx) (hpos hy) hs ht hst) + (hr.2 hx hy hs ht hst)).trans (hD.2 (hpos hx) (hpos hy) hs ht hst) + have hquadratic : 2 ≤ C * a ^ 3 := (div_le_iff₀ (pow_pos ha 3)).mp hC + have hq := convex_quadratic_reciprocal (K := -2) ha + ((by positivity : (0 : ℝ) ≤ 2 / a ^ 3).trans hC) (by linarith) + refine (((hf.add hq).add (convex_reciprocal hb)).add_const (-c)).congr ?_ + intro t _ + simp only [Pi.add_apply] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +/- +# Translation of a truncated directional integral + +After shifting the variable the interval loses a short prefix but gains a +nonnegative tail. On the overlap, the gain in the kernel is at least +`a / t^2`. A linear lower estimate for the defect thus gives a logarithmic gain. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open MeasureTheory Set + +/-- The quantity computed by `∫ t in u..T, g t / t`. -/ +def price (g : ℝ → ℝ) (u T : ℝ) := ∫ t in u..T, g t / t + +variable {g : ℝ → ℝ} {u T : ℝ} + +theorem price_integrable (hc : ContinuousOn g (Ici 0)) (hu : 0 < u) (hT : u ≤ T) : + IntervalIntegrable (fun t => g t / t) volume u T := by + apply ContinuousOn.intervalIntegrable_of_Icc hT + exact (hc.mono (fun t (ht : t ∈ Icc u T) => hu.le.trans ht.1)).div continuousOn_id + (fun _ ht => (hu.trans_le ht.1).ne') + +theorem price_nonneg (hn : ∀ t, 0 ≤ t → 0 ≤ g t) (hu : 0 ≤ u) (hT : u ≤ T) : + 0 ≤ price g u T := + intervalIntegral.integral_nonneg hT fun t ht => div_nonneg (hn t (hu.trans ht.1)) (hu.trans ht.1) + +private theorem gain {t a v S C : ℝ} (ha : 0 < a) (ht : a < t) (hv : 0 ≤ v) + (hS : t * S - C * t ^ 2 ≤ v) : a * (S * t⁻¹ - C) ≤ v / (t - a) - v / t := by + have ht₀ : 0 < t := ha.trans ht + have hta : 0 < t - a := sub_pos.mpr ht + calc + _ = a * (t * S - C * t ^ 2) / (t * t) := by field_simp + _ ≤ a * v / (t * t) := by gcongr + _ ≤ a * v / (t * (t - a)) := by gcongr; linarith + _ = _ := by field_simp; ring + +theorem integrate_gain {a S C : ℝ} (hu : 0 < u) (hT : u ≤ T) : + (∫ t in u..T, a * (S * t⁻¹ - C)) = a * (S * Real.log (T / u) - (T - u) * C) := by + have hi : IntervalIntegrable (fun t : ℝ => t⁻¹) volume u T := by + apply ContinuousOn.intervalIntegrable_of_Icc hT + exact continuousOn_id.inv₀ (fun _ ht => (hu.trans_le ht.1).ne') + rw [intervalIntegral.integral_const_mul, + intervalIntegral.integral_sub (hi.const_mul S) intervalIntegrable_const, + intervalIntegral.integral_const_mul, integral_inv_of_pos hu (hu.trans_le hT), + intervalIntegral.integral_const, smul_eq_mul] + +theorem translation (hc : ContinuousOn g (Ici 0)) (hn : ∀ t, 0 ≤ t → 0 ≤ g t) + {a r R T B S C : ℝ} (ha : 0 < a) (hr : a ≤ r) (hR : 2 * r ≤ R) (hT : R ≤ T) (hC : 0 ≤ C) + (hB : ∀ t, r ≤ t → t ≤ r + a → g t ≤ B * r) + (hS : ∀ t, 2 * r ≤ t → t ≤ R → t * S - C * t ^ 2 ≤ g t) : + a * (S * Real.log (R / (2 * r)) - C * R - B) ≤ price (fun t => g (t + a)) r T - price g r T + := by + have hr₀ := ha.trans_le hr + have hra : r + a ≤ 2 * r := by linarith + have hrT : r + a ≤ T := hra.trans (hR.trans hT) + let f (t : ℝ) := g t / (t - a) + have hf {u v : ℝ} (hu : r + a ≤ u) (hv : u ≤ v) : IntervalIntegrable f volume u v := by + apply ContinuousOn.intervalIntegrable_of_Icc hv + have hu₀ : 0 < u := by linarith + exact (hc.mono (fun t (ht : t ∈ Icc u v) => hu₀.le.trans ht.1)).div + (continuousOn_id.sub continuousOn_const) (fun t ht => by change t - a ≠ 0; linarith [ht.1]) + have hshift : price (fun t => g (t + a)) r T = ∫ t in r + a..T + a, f t := by + rw [← intervalIntegral.integral_comp_add_right f a] + simp only [price, f, add_sub_cancel_right] + have htail : 0 ≤ ∫ t in T..T + a, f t := by + apply intervalIntegral.integral_nonneg (by linarith) + intro t ht + exact div_nonneg (hn t (by linarith [ht.1])) (by linarith [ht.1]) + have hprefix : price g r (r + a) ≤ a * B := by + have hB₀ : 0 ≤ B := nonneg_of_mul_nonneg_left + ((hn r hr₀.le).trans (hB r le_rfl (by linarith))) hr₀ + calc + _ ≤ ∫ _ in r..r + a, B := by + apply intervalIntegral.integral_mono_on (by linarith) (price_integrable hc hr₀ (by + linarith)) + intervalIntegrable_const + intro t ht + exact (div_le_iff₀ (hr₀.trans_le ht.1)).mpr + ((hB t ht.1 ht.2).trans (mul_le_mul_of_nonneg_left ht.1 hB₀)) + _ = _ := by simp + let diff (t : ℝ) := f t - g t / t + have hdiff {u v : ℝ} (hu : r + a ≤ u) (hv : u ≤ v) : IntervalIntegrable diff volume u v := + (hf hu hv).sub (price_integrable hc (by linarith) hv) + have hmid : (∫ t in 2 * r..R, diff t) ≤ ∫ t in r + a..T, diff t := by + apply intervalIntegral.integral_mono_interval hra hR hT _ (hdiff le_rfl hrT) + filter_upwards [ae_restrict_mem measurableSet_Ioc] with t ht + exact sub_nonneg.mpr (div_le_div_of_nonneg_left (hn t (by linarith [ht.1])) + (by linarith [ht.1]) (by linarith)) + have hlo : a * (S * Real.log (R / (2 * r)) - (R - 2 * r) * C) ≤ ∫ t in 2 * r..R, diff t := by + rw [← integrate_gain (by positivity) hR] + apply intervalIntegral.integral_mono_on hR _ (hdiff hra hR) + · intro t ht + exact gain ha (by linarith [ht.1]) (hn t (by linarith [ht.1])) (hS t ht.1 ht.2) + · apply ContinuousOn.intervalIntegrable_of_Icc hR + exact continuousOn_const.mul ((continuousOn_const.mul + (continuousOn_id.inv₀ (fun t ht => by + change t ≠ 0 + linarith [ht.1]))).sub continuousOn_const) + have hfull := hlo.trans hmid + unfold diff at hfull + rw [intervalIntegral.integral_sub (hf le_rfl hrT) (price_integrable hc (by positivity) hrT)] + at hfull + rw [hshift, ← intervalIntegral.integral_add_adjacent_intervals (hf le_rfl hrT) (hf hrT (by + linarith))] + unfold price at hprefix ⊢ + rw [← intervalIntegral.integral_add_adjacent_intervals + (price_integrable hc hr₀ (show r ≤ r + a by linarith)) + (price_integrable hc (by positivity) hrT)] + linarith only [hfull, htail, hprefix, show 0 ≤ a * r * C by positivity] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +section +/- +# Dilation at a zero of the defect + +A fixed interval of positive mass forces a strict decrease under dilation. +Continuity at zero controls the mass added below the lower cutoff. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open MeasureTheory Set Filter + +variable {g : ℝ → ℝ} + +private theorem price_mono_interval (hc : ContinuousOn g (Ici 0)) (hn : ∀ t, 0 ≤ t → 0 ≤ g t) + {u a b T : ℝ} (hu : 0 < u) (hua : u ≤ a) (hab : a ≤ b) (hbT : b ≤ T) : + price g a b ≤ price g u T := by + apply intervalIntegral.integral_mono_interval hua hab hbT _ + (price_integrable hc hu (hua.trans (hab.trans hbT))) + filter_upwards [ae_restrict_mem measurableSet_Ioc] with t ht + exact div_nonneg (hn t (hu.trans ht.1).le) (hu.trans ht.1).le + +private theorem price_dilate {q u T : ℝ} (hq : 0 < q) : + price (fun t => g (t / q) / q) u T = price g (u / q) (T / q) / q := by + unfold price + calc + _ = ∫ t in u..T, (q ^ 2)⁻¹ * (g (t / q) / (t / q)) := by + apply intervalIntegral.integral_congr + intro t _ + by_cases ht : t = 0 + · simp [ht] + · field_simp + _ = _ := by + rw [intervalIntegral.integral_const_mul, + intervalIntegral.integral_comp_div (fun t => g t / t) hq.ne', smul_eq_mul] + field_simp + +theorem dilation (hc : ContinuousOn g (Ici 0)) (hn : ∀ t, 0 ≤ t → 0 ≤ g t) + (hg : g 0 = 0) (hw : ∃ t, 0 < t ∧ 0 < g t) : + ∃ D : ℝ, 0 < D ∧ ∀ ε : ℝ, 0 < ε → ε ≤ 1 → ∀ᶠ T : ℝ in atTop, + price (fun t => g (t / (1 + ε)) / (1 + ε)) (1 / T) T - price g (1 / T) T ≤ -ε * D := by + obtain ⟨t, ht, hgt⟩ := hw + let C := price g t (2 * t) + have hC : 0 < C := by + apply intervalIntegral.integral_pos (by linarith) + · exact (hc.mono (fun s (hs : s ∈ Icc t (2 * t)) => ht.le.trans hs.1)).div continuousOn_id + (fun _ hs => (ht.trans_le hs.1).ne') + · exact fun s hs => div_nonneg (hn s (ht.trans hs.1).le) (ht.trans hs.1).le + · exact ⟨t, ⟨le_rfl, by linarith⟩, div_pos hgt ht⟩ + obtain ⟨δ, hδ, hsmall⟩ := Metric.continuousWithinAt_iff.mp (hc 0 (by simp)) (C / 2) (by + positivity) + refine ⟨C / 4, by positivity, ?_⟩ + intro ε hε hε' + let q := 1 + ε + have hq : 0 < q := by unfold q; linarith + have hq' : 1 ≤ q := by unfold q; linarith + filter_upwards [eventually_ge_atTop (2 * t), eventually_gt_atTop (1 / t), + eventually_gt_atTop (1 / δ)] with T hT hTt hTδ + have hT₀ : 0 < T := by linarith + let u := 1 / T + have hu : 0 < u := by unfold u; positivity + have hut : u ≤ t := ((one_div_lt hT₀ ht).mpr hTt).le + have huδ : u < δ := (one_div_lt hT₀ hδ).mpr hTδ + have huT : u ≤ T := by linarith + have huq : 0 < u / q := div_pos hu hq + have huq' : u / q ≤ u := div_le_self hu.le hq' + have hmass : C ≤ price g u T := price_mono_interval hc hn hu hut (by linarith) hT + have hprefix : price g (u / q) u ≤ ε * (C / 2) := by + calc + _ ≤ ∫ _ in u / q..u, (C / 2) / (u / q) := by + apply intervalIntegral.integral_mono_on huq' (price_integrable hc huq huq') + intervalIntegrable_const + intro s hs + have hs₀ := huq.trans_le hs.1 + have hd := hsmall hs₀.le (by simpa [Real.dist_eq, abs_of_pos hs₀] using hs.2.trans_lt huδ) + have hg' : g s ≤ C / 2 := by + simpa [hg, Real.dist_eq, abs_of_nonneg (hn s hs₀.le)] using hd.le + exact div_le_div₀ (by positivity) hg' huq hs.1 + _ = _ := by + rw [intervalIntegral.integral_const, smul_eq_mul] + field_simp + unfold q + ring + have hbound : price g (u / q) (T / q) ≤ ε * (C / 2) + price g u T := calc + _ ≤ price g (u / q) T := price_mono_interval hc hn huq le_rfl + (div_le_div_of_nonneg_right huT hq.le) (div_le_self hT₀.le hq') + _ = price g (u / q) u + price g u T := + (intervalIntegral.integral_add_adjacent_intervals + (price_integrable hc huq huq') (price_integrable hc hu huT)).symm + _ ≤ _ := add_le_add_left hprefix _ + change price (fun s => g (s / q) / q) u T - price g u T ≤ _ + rw [price_dilate hq, sub_le_iff_le_add, div_le_iff₀ hq] + apply hbound.trans + unfold q + linarith only [mul_le_mul_of_nonneg_left hmass hε.le, + mul_le_mul_of_nonneg_left hε' (mul_nonneg hε.le hC.le)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +section +/- # The cost of translating a single coordinate -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open Set MeasureTheory + +variable {g : ℝ → ℝ} {C a u r R T : ℝ} + +private theorem continuous_shift (hc : ContinuousOn g (Ici 0)) (ha : 0 ≤ a) : + ContinuousOn (fun t => g (t + a)) (Ici 0) := + hc.comp (continuousOn_id.add continuousOn_const) (fun _ ht => add_nonneg ht ha) + +private theorem small_increment (hc : ContinuousOn g (Ici 0)) (h : Semiconvex g C) + (ha : 0 < a) (hu : 0 < u) (hr : u ≤ r) : + (g a - g 0) * Real.log (r / u) - (r - u) * (2 * C * a) ≤ + price (fun t => g (t + a)) u r - price g u r := by + have he := integrate_gain (a := 1) (S := g a - g 0) (C := 2 * C * a) hu hr + simp only [one_mul] at he + rw [← he, price, price, ← intervalIntegral.integral_sub + (price_integrable (continuous_shift hc ha.le) hu hr) (price_integrable hc hu hr)] + apply intervalIntegral.integral_mono_on hr + · apply ContinuousOn.intervalIntegrable_of_Icc hr + exact (continuousOn_const.mul (continuousOn_id.inv₀ + (fun t (ht : t ∈ Icc u r) => (hu.trans_le ht.1).ne'))).sub continuousOn_const + · exact (price_integrable (continuous_shift hc ha.le) hu hr).sub (price_integrable hc hu hr) + intro t ht + have ht₀ := hu.trans_le ht.1 + rw [← sub_div, le_div_iff₀ ht₀, sub_mul, mul_assoc, inv_mul_cancel₀ ht₀.ne', mul_one] + exact h.shift ha ht₀ + +/-- The logarithmic gain at intermediate distances pays for the possible +increase in the defect when the path switches coordinates. -/ +theorem increment (hc : ContinuousOn g (Ici 0)) (hn : ∀ t, 0 ≤ t → 0 ≤ g t) + (h : Semiconvex g C) (hC : 0 ≤ C) {L : ℝ} (hL : 2 ≤ L) + (ha : 0 < a) (har : a * (L + 2) ≤ r) (hR : 2 * r ≤ R) + (he : Real.log (R / (2 * r)) = L) (hu : 0 < u) (hur : u ≤ r) (hT : R ≤ T) : + (g a - g 0) * Real.log (r / u) + (L - 2) * max (g a - g 0) 0 - g 0 - 2 * C * a * R ≤ + price (fun t => g (t + a)) u T - price g u T := by + have hr : 0 < r := hu.trans_le hur + have ha' : a ≤ r := (le_mul_of_one_le_right ha.le (by linarith)).trans har + have hrT : r ≤ T := by linarith + have hz := hn 0 le_rfl + obtain ⟨S, hS, hl, hh⟩ := h.envelope hC hn hr + have hb : ∀ t, r ≤ t → t ≤ r + a → g t ≤ (g 0 / r + 2 * S) * r := by + intro t ht ht' + have ht'' : t ≤ 2 * r := by linarith + rw [add_mul, div_mul_cancel₀ _ hr.ne'] + linarith [hl t (hr.trans_le ht) ht'', mul_le_mul_of_nonneg_right ht'' hS] + have hlarge := translation hc hn ha ha' hR hT hC hb (fun t ht _ => hh t ht) + rw [he] at hlarge + have hsmall := small_increment hc h ha hu hur + have hgain : (L - 2) * max (g a - g 0) 0 ≤ (L - 2) * (a * S) := + mul_le_mul_of_nonneg_left (max_le (hl a ha (by linarith)) (by positivity)) (by linarith) + have hcost : a * (L * (g 0 / (2 * r)) + g 0 / r) ≤ g 0 := by + calc + _ = (a * (L + 2)) * (g 0 / (2 * r)) := by ring + _ ≤ r * (g 0 / (2 * r)) := mul_le_mul_of_nonneg_right har (by positivity) + _ = g 0 / 2 := by field_simp + _ ≤ _ := by linarith + have hcut : (r - u) * (2 * C * a) ≤ C * a * R := by + linarith [mul_le_mul_of_nonneg_left (by linarith : 2 * (r - u) ≤ R) (mul_nonneg hC ha.le)] + have join {g : ℝ → ℝ} (hg : ContinuousOn g (Ici 0)) : + price g u r + price g r T = price g u T := + intervalIntegral.integral_add_adjacent_intervals (price_integrable hg hu hur) + (price_integrable hg hr hrT) + rw [← join hc, ← join (continuous_shift hc ha.le)] + linarith only [hlarge, hsmall, hgain, hcost, hcut] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +/- +# Coordinate rays and radial paths in the positive orthant + +Only *differences* of truncated directional integrals are needed. +Thus the common singular subtraction in the directional identity +cancels, even when the defect is positive at an intermediate point. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open Filter Set + +/-- The indexing data represented by `Fin 3 → ℝ`. -/ +abbrev Vec := Fin 3 → ℝ + +/-- The condition `∀ i, 0 < v i` on the specified data. -/ +def Positive (v : Vec) : Prop := ∀ i, 0 < v i + +/-- Replaces the value at one index and retains all other entries. -/ +def move (v : Vec) (i : Fin 3) (t : ℝ) : Vec := Function.update v i (v i + t) + +/-- Computes the ray by the application `D (move v i t)`. -/ +def ray (D : Vec → ℝ) (v : Vec) (i : Fin 3) (t : ℝ) : ℝ := D (move v i t) + +/-- The quantity computed by `price (ray D v i) (1 / T) T`. -/ +def J (D : Vec → ℝ) (v : Vec) (i : Fin 3) (T : ℝ) : ℝ := price (ray D v i) (1 / T) T + +/-- The data for the regular construction, including `nonneg`, `homogeneous`, `continuous`, +`convex`. -/ +structure Regular (D : Vec → ℝ) : Prop where + nonneg : ∀ v, Positive v → 0 ≤ D v + homogeneous : ∀ v, Positive v → ∀ s : ℝ, 0 < s → D (s • v) = D v / s + continuous : ∀ v, Positive v → ∀ i, ContinuousOn (ray D v i) (Ici 0) + convex : ∀ v, Positive v → ∃ C : ℝ, 0 ≤ C ∧ + ∀ w ∈ Icc v ((2 : ℝ) • v), ∀ i, Semiconvex (ray D w i) C + +/-- The local directional comparison, in truncated form. -/ +def Comparison (D : Vec → ℝ) : Prop := + ∀ v, Positive v → ∃ E : ℝ, 0 ≤ E ∧ ∀ w ∈ Icc v ((2 : ℝ) • v), ∀ i j, + ∀ ζ : ℝ, 0 < ζ → ∀ᶠ T : ℝ in atTop, J D w i T - J D w j T ≤ E * D w + ζ + +variable {D : Vec → ℝ} {v w : Vec} {ε s t : ℝ} + +theorem Positive.move (h : Positive v) (i : Fin 3) (ht : 0 ≤ t) : Positive (move v i t) := by + intro j + by_cases h' : j = i + · subst j + simpa [Minimum.move] using add_pos_of_pos_of_nonneg (h i) ht + · simpa [Minimum.move, h'] using h j + +@[simp] theorem ray_zero (D : Vec → ℝ) (v : Vec) (i : Fin 3) : ray D v i 0 = D v := by + simp [ray, move] + +theorem ray_move (D : Vec → ℝ) (v : Vec) (i : Fin 3) (s : ℝ) : + ray D (move v i s) i = fun t => ray D v i (t + s) := by + funext t + unfold ray move + simp [add_comm, add_left_comm] + +theorem Regular.scale (h : Regular D) (hv : Positive v) (i : Fin 3) (hs : 0 < s) + (ht : 0 ≤ t) : ray D (s • v) i t = ray D v i (t / s) / s := by + have he : move (s • v) i t = s • move v i (t / s) := by + funext j + by_cases h' : j = i + · subst j; simp [move, mul_add, mul_div_cancel₀ t hs.ne'] + · simp [move, h'] + rw [ray, he, h.homogeneous _ (hv.move i (div_nonneg ht hs.le)) _ hs] + rfl + +/-- First enlarge coordinate 0, then 1, then 2. -/ +def path (v : Vec) (ε : ℝ) (n : ℕ) (i : Fin 3) : ℝ := + if i.val < n then (1 + ε) * v i else v i + +@[simp] theorem path_zero (v : Vec) (ε : ℝ) : path v ε 0 = v := by + funext i; simp [path] + +@[simp] theorem path_three (v : Vec) (ε : ℝ) : path v ε 3 = (1 + ε) • v := by + funext i; simp [path, i.isLt] + +theorem path_mem (hv : Positive v) (he : 0 ≤ ε) (he' : ε ≤ 1) (n : ℕ) : + path v ε n ∈ Icc v ((2 : ℝ) • v) := by + constructor <;> intro i <;> simp only [path, Pi.smul_apply, smul_eq_mul] + all_goals split_ifs <;> nlinarith [hv i] + +theorem path_succ (v : Vec) (ε : ℝ) (i : Fin 3) : + path v ε (i.val + 1) = move (path v ε i.val) i (ε * v i) := by + funext j + by_cases h : j = i + · subst j; simp [path, move, add_mul] + · have he : j.val < i.val + 1 ↔ j.val < i.val := by omega + simp only [move, Function.update_of_ne h, path, he] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +section +/- # Passing a directional comparison to a limiting face -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open Set Filter MeasureTheory +open scoped Topology + +private theorem tail_bound {g : ℝ → ℝ} (hc : ContinuousOn g (Ici 0)) + (hg : ∀ t, 0 < t → g t ≤ 1 / t) {B T : ℝ} (hB : 0 < B) (hT : B ≤ T) : + price g B T ≤ 1 / B := by + have hi : IntervalIntegrable (fun t : ℝ => 1 / t ^ 2) volume B T := by + apply ContinuousOn.intervalIntegrable_of_Icc hT + exact continuousOn_const.div (continuousOn_id.pow 2) (fun _ ht + => pow_ne_zero _ (hB.trans_le ht.1).ne') + have hd (t : ℝ) (ht : t ∈ uIcc B T) : HasDerivAt (fun t : ℝ => -1 / t) (1 / t ^ 2) t := by + rw [uIcc_of_le hT] at ht + simpa only [id_eq, zero_mul, zero_sub, mul_one, neg_neg] using! + (hasDerivAt_const t (-1 : ℝ)).div (hasDerivAt_id t) (hB.trans_le ht.1).ne' + calc + _ ≤ ∫ t in B..T, 1 / t ^ 2 := by + apply intervalIntegral.integral_mono_on hT (price_integrable hc hB hT) hi + intro t ht + rw [pow_two, ← div_div] + exact div_le_div_of_nonneg_right (hg t (hB.trans_le ht.1)) (hB.trans_le ht.1).le + _ = -1 / T - -1 / B := intervalIntegral.integral_eq_sub_of_hasDerivAt hd hi + _ ≤ _ := by rw [neg_div, neg_div]; linarith [one_div_pos.mpr (hB.trans_le hT)] + +theorem middle_bound {f g : ℝ → ℝ} (hf : ContinuousOn f (Ici 0)) (hg : ContinuousOn g (Ici 0)) + (hn : ∀ t, 0 ≤ t → 0 ≤ f t) {C B T : ℝ} (hC : 0 ≤ C) (hB : 2 ≤ B) (hT : B ≤ T) + (hnear : ∀ t, 0 < t → -(C * t) ≤ f t - g t) + (hfar : ∀ t, 0 < t → g t ≤ 1 / t) + : price f (1 / B) B - price g (1 / B) B ≤ + price f (1 / T) T - price g (1 / T) T + (C + 1) / B := by + have hB₀ : 0 < B := by linarith + have hT₀ : 0 < T := hB₀.trans_le hT + have hu : 0 < 1 / T := by positivity + have ha : 0 < 1 / B := by positivity + have hua := one_div_le_one_div_of_le hB₀ hT + have ha₁ : 1 / B ≤ 1 := div_le_self zero_le_one (by linarith) + have haB : 1 / B ≤ B := by linarith + have hsmall : -(C / B) ≤ price f (1 / T) (1 / B) - price g (1 / T) (1 / B) := by + have h₁ := price_integrable hf hu hua + have h₂ := price_integrable hg hu hua + unfold price + rw [← intervalIntegral.integral_sub h₁ h₂] + calc + _ ≤ ∫ _ in 1 / T..1 / B, -C := by + rw [intervalIntegral.integral_const, smul_eq_mul] + simp only [div_eq_mul_inv] + linarith [mul_nonneg (inv_nonneg.mpr hT₀.le) hC] + _ ≤ _ := by + apply intervalIntegral.integral_mono_on hua intervalIntegrable_const (h₁.sub h₂) + intro t ht + rw [← sub_div, le_div_iff₀ (hu.trans_le ht.1), neg_mul] + exact hnear t (hu.trans_le ht.1) + have hsplit (k : ℝ → ℝ) (hk : ContinuousOn k (Ici 0)) : + price k (1 / T) T = price k (1 / T) (1 / B) + price k (1 / B) B + price k B T := by + unfold price + rw [intervalIntegral.integral_add_adjacent_intervals (price_integrable hk hu hua) + (price_integrable hk ha haB), + intervalIntegral.integral_add_adjacent_intervals (price_integrable hk hu (hua.trans haB)) + (price_integrable hk hB₀ hT)] + rw [hsplit f hf, hsplit g hg, add_div] + linarith only [hsmall, price_nonneg hn hB₀.le hT, tail_bound hg hfar hB₀ hT] + +theorem compact_price {G : ℝ → ℝ} {g : ℝ → ℝ → ℝ} {A B : ℝ} (hA : 0 < A) (hB : A ≤ B) + (hc : ∀ r ∈ Ioc (0 : ℝ) 1, ContinuousOn (g r) (Ici 0)) + (hb : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ t, 0 < t → 0 ≤ g r t ∧ g r t ≤ 1 / t) + (hl : ∀ t, 0 < t → Tendsto (fun r => g r t) (𝓝[>] 0) (𝓝 (G t))) : + Tendsto (fun r => price (g r) A B) (𝓝[>] 0) (𝓝 (price G A B)) := by + have he : ∀ᶠ r in 𝓝[>] (0 : ℝ), r ∈ Ioc 0 1 := Ioc_mem_nhdsGT zero_lt_one + unfold price + apply intervalIntegral.tendsto_integral_filter_of_dominated_convergence (fun _ => 1 / A / A) + · filter_upwards [he] with r hr + exact (intervalIntegrable_iff.mp (price_integrable (hc r hr) hA hB)).aestronglyMeasurable + · filter_upwards [he] with r hr + filter_upwards [] with t ht + rw [uIoc_of_le hB] at ht + have ht' := hA.trans ht.1 + obtain ⟨hl, hu⟩ := hb r hr t ht' + rw [Real.norm_of_nonneg (div_nonneg hl ht'.le)] + exact div_le_div₀ (by positivity) (hu.trans (one_div_le_one_div_of_le hA ht.1.le)) hA ht.1.le + · exact intervalIntegrable_const + · filter_upwards [] with t ht + rw [uIoc_of_le hB] at ht + exact (hl t (hA.trans ht.1)).div_const t + +/-- A common estimate near zero and an inverse-square tail let the +limiting comparison pass to a reciprocal face. -/ +theorem compare_limit {f g : ℝ → ℝ → ℝ} {F G A : ℝ → ℝ} {C E : ℝ} (hC : 0 ≤ C) + (hc : ∀ r ∈ Ioc (0 : ℝ) 1, ContinuousOn (f r) (Ici 0) ∧ ContinuousOn (g r) (Ici 0)) + (hf : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ t, 0 ≤ t → 0 ≤ f r t ∧ 0 ≤ g r t) + (hu : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ t, 0 < t → f r t ≤ 1 / t ∧ g r t ≤ 1 / t) + (hnear : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ t, 0 < t → -(C * t) ≤ f r t - g r t) + (hl : ∀ t, 0 < t → Tendsto (fun r => f r t) (𝓝[>] 0) (𝓝 (F t)) ∧ + Tendsto (fun r => g r t) (𝓝[>] 0) (𝓝 (G t))) + (hA : Tendsto A (𝓝[>] 0) (𝓝 E)) + (he : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ ζ : ℝ, 0 < ζ → ∀ᶠ T : ℝ in atTop, + price (f r) (1 / T) T - price (g r) (1 / T) T ≤ A r + ζ) + {ζ : ℝ} (hζ : 0 < ζ) : + ∀ᶠ B : ℝ in atTop, price F (1 / B) B - price G (1 / B) B ≤ E + ζ := by + filter_upwards [eventually_ge_atTop 2, eventually_ge_atTop ((C + 1) / (ζ / 2))] with B hB hB' + have hB₀ : 0 < B := by linarith + have hb : 1 / B ≤ B := (div_le_self zero_le_one (by linarith)).trans (by linarith) + have hk : (C + 1) / B ≤ ζ / 2 := (div_le_iff₀ hB₀).2 (by + linarith [(div_le_iff₀ (half_pos hζ)).mp hB']) + have h₁ := compact_price (one_div_pos.mpr hB₀) hb (fun r hr => (hc r hr).1) + (fun r hr t ht => ⟨(hf r hr t ht.le).1, (hu r hr t ht).1⟩) (fun t ht => (hl t ht).1) + have h₂ := compact_price (one_div_pos.mpr hB₀) hb (fun r hr => (hc r hr).2) + (fun r hr t ht => ⟨(hf r hr t ht.le).2, (hu r hr t ht).2⟩) (fun t ht => (hl t ht).2) + apply le_of_tendsto_of_tendsto (h₁.sub h₂) (hA.add_const ζ) + filter_upwards [Ioc_mem_nhdsGT zero_lt_one] with r hr + obtain ⟨T, hT, ht⟩ := ((eventually_ge_atTop B).and (he r hr _ (half_pos hζ))).exists + have hh := middle_bound (hc r hr).1 (hc r hr).2 (fun t h => (hf r hr t h).1) + hC hB hT (hnear r hr) (fun t h => (hu r hr t h).2) + linarith only [ht, hh, hk] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +section +/- +# From a vanishing face to an interior zero + +Compare the normal and tangential ray integrals on the same truncated +interval. Near zero their difference is bounded below by transport. +At infinity the tangential kernel has an integrable inverse-square bound. +On any fixed interval away from zero its integral vanishes in the face limit. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open Set Filter MeasureTheory +open scoped Topology + +variable {D : Vec → ℝ} + +private theorem balance {f g : ℝ → ℝ} (hf : ContinuousOn f (Ici 0)) (hg : ContinuousOn g (Ici 0)) + (hn : ∀ t, 0 ≤ t → 0 ≤ f t) {C m B T : ℝ} (hC : 0 ≤ C) (hB : 2 ≤ B) (hT : B ≤ T) + (hnear : ∀ t, 0 < t → -(C * t) ≤ f t - g t) + (hfar : ∀ t, 0 < t → g t ≤ 1 / t) + (hm : ∀ t ∈ Icc (1 : ℝ) 2, m ≤ f t / t) : + m ≤ price f (1 / T) T - price g (1 / T) T + C / B + price g (1 / B) B + 1 / B := by + have hB₀ : 0 < B := by linarith + have ha : 0 < 1 / B := by positivity + have ha₁ : 1 / B ≤ 1 := div_le_self zero_le_one (by linarith) + have haB : 1 / B ≤ B := by linarith + have hmid : m ≤ price f (1 / B) B := calc + _ = ∫ _ in (1 : ℝ)..2, m := by norm_num + _ ≤ price f 1 2 := intervalIntegral.integral_mono_on (by norm_num) + intervalIntegrable_const (price_integrable hf (by norm_num) (by norm_num)) hm + _ ≤ _ := by + apply intervalIntegral.integral_mono_interval ha₁ (by norm_num) hB _ (price_integrable hf ha + haB) + filter_upwards [ae_restrict_mem measurableSet_Ioc] with t ht + exact div_nonneg (hn t (ha.trans ht.1).le) (ha.trans ht.1).le + have he := middle_bound hf hg hn hC hB hT hnear hfar + rw [add_div] at he + linarith only [hmid, he] + +private theorem compact_limit {g : ℝ → ℝ → ℝ} {A B : ℝ} (hA : 0 < A) (hB : A ≤ B) + (hc : ∀ r ∈ Ioc (0 : ℝ) 1, ContinuousOn (g r) (Ici 0)) + (hb : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ t, 0 < t → 0 ≤ g r t ∧ g r t ≤ 1 / t) + (hl : ∀ t, 0 < t → Tendsto (fun r => g r t) (𝓝[>] 0) (𝓝 0)) : + Tendsto (fun r => price (g r) A B) (𝓝[>] 0) (𝓝 0) := by + simpa [price] using compact_price (G := fun _ => 0) hA hB hc hb hl + +/-- A vanishing face and a uniform directional comparison up to that +face give a zero at a finite positive triple. -/ +theorem face_zero (h : Regular D) {C E : ℝ} (hc : 0 ≤ C) + (hlim : ∀ y : ℝ, 0 < y → Tendsto (fun r : ℝ => D ![r, y, 1]) (𝓝[>] 0) (𝓝 0)) + (hl : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ t : ℝ, 0 ≤ t → D ![r, 1, 1] ≤ D ![r + t, 1, 1] + C * t) + (hu : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ t : ℝ, 0 ≤ t → D ![r, 1 + t, 1] ≤ D ![r, 1, 1] + C * t) + (ht : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ t : ℝ, 0 < t → D ![r, 1 + t, 1] ≤ 1 / t) + (he : ∀ r ∈ Ioc (0 : ℝ) 1, ∀ ζ : ℝ, 0 < ζ → ∀ᶠ T : ℝ in atTop, + J D ![r, 1, 1] 0 T - J D ![r, 1, 1] 1 T ≤ E * D ![r, 1, 1] + ζ) : + ∃ v, Positive v ∧ D v = 0 := by + by_contra! hn + let v (r : ℝ) : Vec := ![r, 1, 1] + let f r := ray D (v r) 0 + let g r := ray D (v r) 1 + have hv {r} (hr : 0 < r) : Positive (v r) := by + intro i + fin_cases i <;> simp [v, hr] + have hf (r t) : f r t = D ![r + t, 1, 1] := by + unfold f ray + congr 1 + funext i + fin_cases i <;> simp [move, v] + have hg (r t) : g r t = D ![r, 1 + t, 1] := by + unfold g ray + congr 1 + funext i + fin_cases i <;> simp [move, v] + have hp {r} (hr : 0 < r) (i : Fin 3) {t} (ht : 0 ≤ t) : 0 < ray D (v r) i t := by + have h' := (hv hr).move i ht + exact (h.nonneg _ h').lt_of_ne' (hn _ h') + -- Without an interior zero the normal integral has a uniform positive mass. + have hf' : ContinuousOn (f 1) (Icc 0 2) := + (h.continuous _ (hv zero_lt_one) _).mono Icc_subset_Ici_self + obtain ⟨a, ha, hmin⟩ := isCompact_Icc.exists_isMinOn (nonempty_Icc.mpr (by norm_num)) hf' + let m := f 1 a / 2 + have hm : 0 < m := half_pos (hp zero_lt_one 0 ha.1) + have hmass {r} (hr : r ∈ Ioc (0 : ℝ) 1) {t} (ht : t ∈ Icc (1 : ℝ) 2) : m ≤ f r t / t := by + have hd := hmin (show r + t - 1 ∈ Icc (0 : ℝ) 2 by + constructor <;> linarith [hr.1, hr.2, ht.1, ht.2]) + have hEq : f 1 (r + t - 1) = f r t := by rw [hf, hf, show 1 + (r + t - 1) = r + t by ring] + change f 1 a ≤ f 1 (r + t - 1) at hd + rw [hEq] at hd + exact div_le_div₀ (hp hr.1 0 (by linarith [ht.1])).le hd (by linarith [ht.1]) ht.2 + have hnear {r} (hr : r ∈ Ioc (0 : ℝ) 1) (t) (ht : 0 < t) : -(2 * C * t) ≤ f r t - g r t := by + rw [hf, hg] + linarith only [hl r hr t ht.le, hu r hr t ht.le] + have hfar {r} (hr : r ∈ Ioc (0 : ℝ) 1) (t) (ht' : 0 < t) : g r t ≤ 1 / t := by + rw [hg] + exact ht r hr t ht' + have hcont (r) (hr : r ∈ Ioc (0 : ℝ) 1) : ContinuousOn (g r) (Ici 0) := h.continuous _ (hv hr.1) _ + have hzero (t) (ht' : 0 < t) : Tendsto (fun r => g r t) (𝓝[>] 0) (𝓝 0) := by + simp only [hg] + exact hlim _ (by linarith) + -- Keep the middle interval fixed while approaching the face. + have hbound (B : ℝ) (hB : 2 ≤ B) : m ≤ (2 * C + 2) / B := by + have hB' : 0 < B := by linarith + have hcut : 1 / B ≤ B := (div_le_self zero_le_one (by linarith)).trans (by linarith) + have hmiddle := compact_limit (by positivity : 0 < 1 / B) hcut hcont + (fun r hr t ht => ⟨(hp hr.1 1 ht.le).le, hfar hr t ht⟩) hzero + have hrate := (((hlim 1 zero_lt_one).const_mul E).add hmiddle).add_const ((2 * C + 2) / B) + simp only [mul_zero, zero_add] at hrate + apply ge_of_tendsto hrate + filter_upwards [Ioc_mem_nhdsGT (show (0 : ℝ) < 1 by norm_num)] with r hr + obtain ⟨T, hT, he'⟩ := ((eventually_ge_atTop B).and (he r hr (1 / B) (by positivity))).exists + change price (f r) (1 / T) T - price (g r) (1 / T) T ≤ _ at he' + have hh := balance (h.continuous _ (hv hr.1) 0) (hcont r hr) + (fun _ ht => (hp hr.1 0 ht).le) (by positivity) hB hT (hnear hr) (hfar hr) + (fun _ ht => hmass hr ht) + change m ≤ price (f r) (1 / T) T - price (g r) (1 / T) T + 2 * C / B + price (g r) (1 / B) B + + 1 / B at hh + simp only [div_eq_mul_inv] at hh he' ⊢ + linarith only [hh, he'] + have ht' : Tendsto (fun B : ℝ => (2 * C + 2) / B) atTop (𝓝 0) + := tendsto_const_nhds.div_atTop tendsto_id + exact hm.not_ge (ge_of_tendsto ht' ((eventually_ge_atTop 2).mono hbound)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +section +/- +# From directional potentials to price comparison + +The derivative along a ray from an axis gives the defect. Inverting the +ray parameter converts the derivative to the kernel of the truncated +integral. Differences of the primitives have limits at both endpoints. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open Set Filter +open scoped Topology + +/-- The comparison of axis limits is locally uniform in the +sense that one constant works throughout the positive box. -/ +def HasPotential (D : Vec → ℝ) : Prop := + ∀ v, Positive v → ∃ E : ℝ, 0 ≤ E ∧ ∀ w ∈ Icc v ((2 : ℝ) • v), + ∃ (G : Fin 3 → ℝ → ℝ) (b : Fin 3 → ℝ), + (∀ i t, 0 < t → HasDerivAt (G i) (-D (move (t • w) i 1)) t) ∧ + (∀ i, Tendsto (fun T : ℝ => G i (1 / T)) atTop (𝓝 (b i))) ∧ + (∀ i j, Tendsto (fun T : ℝ => G i T - G j T) atTop (𝓝 0)) ∧ + (∀ i j, b i - b j ≤ E * D w) + +variable {D : Vec → ℝ} + +theorem integral_potential (h : Regular D) {w : Vec} (hw : Positive w) + {i : Fin 3} {G : ℝ → ℝ} (hg : ∀ t : ℝ, 0 < t → HasDerivAt G (-D (move (t • w) i 1)) t) + {T : ℝ} (hT : 1 ≤ T) : J D w i T = G (1 / T) - G T := by + have hT₀ : 0 < T := zero_lt_one.trans_le hT + have hu : 0 < 1 / T := by positivity + have huT : 1 / T ≤ T := (div_le_self zero_le_one hT).trans hT + have hd (t : ℝ) (ht : t ∈ uIcc (1 / T) T) : + HasDerivAt (fun t => G (1 / t)) (ray D w i t / t) t := by + rw [uIcc_of_le huT] at ht + have ht₀ : 0 < t := hu.trans_le ht.1 + have hi : HasDerivAt (fun t : ℝ => 1 / t) (-1 / t ^ 2) t := by + simpa only [id_eq, zero_mul, zero_sub, one_mul] using! + (hasDerivAt_const t (1 : ℝ)).div (hasDerivAt_id t) ht₀.ne' + have he : -D (move ((1 / t) • w) i 1) * (-1 / t ^ 2) = ray D w i t / t := by + change -ray D ((1 / t) • w) i 1 * (-1 / t ^ 2) = _ + rw [h.scale hw i (by positivity) zero_le_one, one_div_one_div] + field_simp + rw [← he] + exact (hg _ (by positivity)).comp t hi + simpa only [J, price, one_div_one_div] using + intervalIntegral.integral_eq_sub_of_hasDerivAt hd (price_integrable (h.continuous _ hw i) hu + huT) + +theorem comparison_of_potential (h : Regular D) (hg : HasPotential D) : Comparison D := by + intro v hv + obtain ⟨E, hE, hG⟩ := hg v hv + refine ⟨E, hE, fun w hw i j ζ hζ => ?_⟩ + obtain ⟨G, b, hd, hb, hinf, he⟩ := hG w hw + have hp : Positive w := fun k => (hv k).trans_le (hw.1 k) + have ht := ((hb i).sub (hb j)).sub (hinf i j) + rw [sub_zero] at ht + have hlt := (he i j).trans_lt (lt_add_of_pos_right _ hζ) + filter_upwards [eventually_ge_atTop (1 : ℝ), ht.eventually_lt_const hlt] with T hT ht' + rw [integral_potential h hp (hd i) hT, integral_potential h hp (hd j) hT] + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +section +/- # Comparing a radial dilation with three coordinate increments -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open Set Filter + +variable {D : Vec → ℝ} {v : Vec} {ε r R C E ζ : ℝ} + +theorem telescope (hg : Regular D) (hv : Positive v) (hz : D v = 0) + (hC : 0 ≤ C) (hE : 0 ≤ E) + (hc : ∀ w ∈ Icc v ((2 : ℝ) • v), ∀ i, Semiconvex (ray D w i) C) + (he : ∀ w ∈ Icc v ((2 : ℝ) • v), ∀ i j, + ∀ᶠ T : ℝ in atTop, J D w i T - J D w j T ≤ E * D w + ζ) + (hε : 0 < ε) (hε' : ε ≤ 1) (hr : 0 < r) (hR : 2 * r ≤ R) + (hlog : Real.log (R / (2 * r)) = 2 * E + 4) (hstep : ∀ i, ε * v i * (2 * E + 6) ≤ r) + (k : Fin 3) : + ∀ᶠ T in atTop, -2 * C * ε * (v 0 + v 1 + v 2) * R - 4 * ζ ≤ + J D ((1 + ε) • v) k T - J D v k T := by + let w := path v ε + have hw (n : ℕ) : w n ∈ Icc v ((2 : ℝ) • v) := path_mem hv hε.le hε' n + have hp (n : ℕ) : Positive (w n) := fun i => (hv i).trans_le ((hw n).1 i) + have h₀ : D (w 0) = 0 := by simp [w, hz] + have h₃ : D (w 3) = 0 := by + rw [show w 3 = _ from path_three _ _, hg.homogeneous v hv _ (by positivity), hz, zero_div] + filter_upwards [eventually_ge_atTop R, eventually_ge_atTop (1 / r), + he _ (hw 0) k 0, he _ (hw 1) 0 1, he _ (hw 2) 1 2, he _ (hw 3) 2 k] + with T hT hT' e₀ e₁ e₂ e₃ + have hu : 0 < 1 / T := one_div_pos.mpr ((one_div_pos.mpr hr).trans_le hT') + have hur : 1 / T ≤ r := by + simpa using one_div_le_one_div_of_le (one_div_pos.mpr hr) hT' + let l := Real.log (r / (1 / T)) + have step (i : Fin 3) : + (D (w (i.val + 1)) - D (w i.val)) * l + + (2 * E + 2) * max (D (w (i.val + 1)) - D (w i.val)) 0 - D (w i.val) - + 2 * C * (ε * v i) * R ≤ J D (w (i.val + 1)) i T - J D (w i.val) i T := by + let f := ray D (w i.val) i + have hf₀ : ∀ t, 0 ≤ t → 0 ≤ f t := fun t ht => hg.nonneg _ ((hp _).move i ht) + have heq : w (i.val + 1) = move (w i.val) i (ε * v i) := path_succ v ε i + have hs := increment (hg.continuous _ (hp i.val) i) hf₀ (hc _ (hw _) i) hC + (by linarith : 2 ≤ 2 * E + 4) (mul_pos hε (hv i)) (by linarith [hstep i]) hR hlog hu hur hT + rw [ray_zero, ← ray_move, ← heq, show 2 * E + 4 - 2 = 2 * E + 2 by ring] at hs + simpa only [J, ray, ← heq] using hs + have s₀ := step 0 + have s₁ := step 1 + have s₂ := step 2 + simp only [Fin.val_zero, Fin.val_one, show (2 : Fin 3).val = 2 from rfl, Nat.reduceAdd, h₀, h₃, + sub_zero, zero_sub] at s₀ s₁ s₂ + have hm : + D (w 1) + D (w 2) ≤ + 2 * (max (D (w 1)) 0 + max (D (w 2) - D (w 1)) 0 + max (-D (w 2)) 0) := by + linarith only [le_max_left (D (w 1)) 0, le_max_left (D (w 2) - D (w 1)) 0, + le_max_right (D (w 2) - D (w 1)) 0, le_max_right (-D (w 2)) 0] + have hm' := mul_le_mul_of_nonneg_left hm (by linarith : 0 ≤ E + 1) + rw [h₀] at e₀ + rw [h₃] at e₃ + have hres : -2 * C * ε * (v 0 + v 1 + v 2) * R - 4 * ζ ≤ J D (w 3) k T - J D (w 0) k T := by + linarith only [s₀, s₁, s₂, e₀, e₁, e₂, e₃, hm'] + simpa only [w, path_zero, path_three] using hres + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Model.lean new file mode 100644 index 0000000000..479b95bee1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Model.lean @@ -0,0 +1,87 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.RationalCircuits + +/-! +# The arithmetic exponent for rectangular products + +The side lengths are ordered as rows, columns, inner dimension. The +straight-line circuit rules are shared with the square model. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +/-- Indexes the pos by the coordinates of `Fin i × Fin j`. -/ +abbrev Pos (i j : ℕ) := Fin i × Fin j +/-- Indexes the var by the coordinates of `Pos i k ⊕ Pos k j`. -/ +abbrev Var (i j k : ℕ) := Pos i k ⊕ Pos k j +/-- Computes the rat by the application `FractionRing (MvPolynomial (Var i j k) F)`. -/ +abbrev Rat (F : Type*) [Field F] (i j k : ℕ) := FractionRing (MvPolynomial (Var i j k) F) + +/-- Computes the input by the application `algebraMap (MvPolynomial (Var i j k) F) (Rat F i j k) +(MvPolynomial.X x)`. -/ +def input (F : Type*) [Field F] {i j k : ℕ} (x : Var i j k) : Rat F i j k := + algebraMap (MvPolynomial (Var i j k) F) (Rat F i j k) (MvPolynomial.X x) + +/-- The set of values attained by `(algebraMap F (Rat F i j k)) ∪ Set.range (input F)`. -/ +def initial (F : Type*) [Field F] (i j k : ℕ) : Set (Rat F i j k) := + Set.range (algebraMap F (Rat F i j k)) ∪ Set.range (input F) + +/-- The quantity computed by `∑ l : Fin k, input F (.inl (p.1, l)) * input F (.inr (l, p.2))`. -/ +def output (F : Type*) [Field F] {i j k : ℕ} (p : Pos i j) : Rat F i j k := + ∑ l : Fin k, input F (.inl (p.1, l)) * input F (.inr (l, p.2)) + +/-- The condition `∃ T, Build (initial F i j k) m T ∧ ∀ p : Pos i j, output F p ∈ T` on the +specified data. -/ +def Computes (F : Type*) [Field F] (i j k m : ℕ) : Prop := + ∃ T, Build (initial F i j k) m T ∧ ∀ p : Pos i j, output F p ∈ T + +/-- The quantity computed by `⌈(n : ℝ) ^ a⌉₊`. -/ +def side (n : ℕ) (a : ℝ) : ℕ := ⌈(n : ℝ) ^ a⌉₊ + +/-- The defining condition `∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ n : ℕ, 0 < n → ∃ m : ℕ, Computes +F (side n a) (side n b) (side n c) m ∧ (m : ℝ) ≤ C * (n : ℝ) ^ (s + ε)`. -/ +def Admissible (F : Type*) [Field F] (a b c s : ℝ) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ n : ℕ, 0 < n → + ∃ m : ℕ, Computes F (side n a) (side n b) (side n c) m ∧ + (m : ℝ) ≤ C * (n : ℝ) ^ (s + ε) + +/-- The infimum of `{s | Admissible F a b c s}`. -/ +def exponent (F : Type*) [Field F] (a b c : ℝ) : ℝ := sInf {s | Admissible F a b c s} + +/-- The supremum of `{c ∈ Set.Icc 0 (min a b) | exponent F a b c = a + b}`. -/ +def dual (F : Type*) [Field F] (a b : ℝ) : ℝ := + sSup {c ∈ Set.Icc 0 (min a b) | exponent F a b c = a + b} + +/-- Coefficient rank for rectangular matrix multiplication over a commutative semiring. -/ +abbrev RankLE (F : Type*) [CommSemiring F] (i j k r : ℕ) : Prop := + TensorSpectrum.MatrixRank F i j k r + +/-- The benchmark on the cone where the last coordinate is smallest. -/ +def benchmark (a b c : ℝ) : ℝ := + a + b + (max ((a + b) * c - a * b) 0) ^ 2 / (4 * a * b * c) + +/-- Evaluate the benchmark with a smallest side placed last. Division by +zero in the real-valued formula returns zero on a coordinate plane. -/ +def U (a b c : ℝ) : ℝ := + if c ≤ min a b then benchmark a b c + else if a ≤ b then benchmark b c a + else benchmark c a b + +/-- The dichotomy between benchmark equality and strict savings at active shapes. +An active shape is one where the benchmark exceeds every pair sum. -/ +def Rigidity (F : Type*) [Field F] : Prop := + (∀ a b c : ℝ, 0 < a → 0 < b → 0 < c → exponent F a b c = U a b c) ∨ + (∀ a b c : ℝ, 0 < a → 0 < b → 0 < c → + max (a + b) (max (a + c) (b + c)) < U a b c → exponent F a b c < U a b c) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Multi/Count.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Multi/Count.lean new file mode 100644 index 0000000000..96ef3630a1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Multi/Count.lean @@ -0,0 +1,949 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.Asymptotics.SpecificAsymptotics +public import Mathlib.Analysis.SpecialFunctions.Log.Basic +public import Mathlib.Data.Fintype.Prod +public import Mathlib.Algebra.Order.Ring.Int +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Order.Preorder.Finite +public import Mathlib.Data.Fintype.Perm +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Pairing +public import Mathlib.Data.Sym.Card +public import Mathlib.Algebra.MonoidAlgebra.Basic +public import Mathlib.Basic.NNReal.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Chord + +/-! # The volume correction per variable -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Filter +open scoped Topology + +private def volume (n : ℕ) : ℝ := n * Real.log n - Real.log n.factorial + +/-- The quantity computed by `Real.log n - Real.log n.factorial / n`. -/ +def correction (n : ℕ) := Real.log n - Real.log n.factorial / n + +private theorem volume_step (n : ℕ) : + (n : ℝ) / (n + 1) ≤ volume (n + 1) - volume n ∧ volume (n + 1) - volume n ≤ 1 := by + rcases n.eq_zero_or_pos with rfl | hn + · norm_num [volume] + have h₀ : 0 < (n : ℝ) := by positivity + have h₁ : 0 < (n : ℝ) + 1 := by positivity + have he : volume (n + 1) - volume n = (n : ℝ) * (Real.log (n + 1) - Real.log n) := by + unfold volume + rw [Nat.factorial_succ, Nat.cast_mul, Nat.cast_add, Nat.cast_one, + Real.log_mul h₁.ne' (by positivity)] + ring + rw [he] + have hl := Real.log_le_sub_one_of_pos (div_pos h₀ h₁) + have hu := Real.log_le_sub_one_of_pos (div_pos h₁ h₀) + rw [Real.log_div h₀.ne' h₁.ne', show (n : ℝ) / (n + 1) - 1 = -1 / (n + + 1) by field_simp; ring, neg_div] at hl + rw [Real.log_div h₁.ne' h₀.ne', add_div, div_self h₀.ne', add_sub_cancel_left] at hu + constructor + · rw [div_eq_mul_inv] + exact mul_le_mul_of_nonneg_left (by rw [one_div] at hl; linarith) h₀.le + · rw [mul_comm, ← le_div_iff₀ h₀] + exact hu + +theorem correction_le (n : ℕ) : correction n ≤ 1 := by + have h (m : ℕ) : volume m ≤ m := by + induction m with + | zero => simp [volume] + | succ m ih => rw [Nat.cast_succ]; linarith [(volume_step m).2] + rcases n.eq_zero_or_pos with rfl | hn + · norm_num [correction] + have he := h n + unfold volume at he + unfold correction + field_simp + linarith + +theorem correction_limit : Tendsto correction atTop (𝓝 1) := by + have ht : Tendsto (fun n : ℕ => (n : ℝ) / (n + 1)) atTop (𝓝 1) := by + simpa using tendsto_natCast_div_add_atTop (1 : ℝ) + have h := (tendsto_of_tendsto_of_tendsto_of_le_of_le ht tendsto_const_nhds + (fun n => (volume_step n).1) (fun n => (volume_step n).2)).cesaro + apply h.congr' + filter_upwards [eventually_gt_atTop 0] with n hn + rw [Finset.sum_range_sub] + unfold volume correction + simp only [Nat.cast_zero, Nat.factorial_zero, Nat.cast_one, Real.log_one, zero_mul, sub_zero] + field_simp + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +section +/- The sum of all positive pair differences is subadditive. +For vectors with distinct entries equality forces a common ordering. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Finset + +variable {m : ℕ} {ι : Type} [Fintype ι] + +private def support (q : Equiv.Perm (Fin m)) (x : Fin m → ℤ) (p : Fin m × Fin m) := + if q p.1 < q p.2 then x p.2 - x p.1 else 0 + +/-- The sum of `max (x p.2 - x p.1) 0` indexed by `p : Fin m × Fin m`. -/ +def variation (x : Fin m → ℤ) := ∑ p : Fin m × Fin m, max (x p.2 - x p.1) 0 + +private theorem support_le (q : Equiv.Perm (Fin m)) (x : Fin m → ℤ) (p : Fin m × Fin m) : + support q x p ≤ max (x p.2 - x p.1) 0 := by + unfold support + split <;> simp + +private theorem support_eq (p q : Equiv.Perm (Fin m)) (x : Fin m → ℤ) + (hx : ∀ a b, x a < x b ↔ p a < p b) : + (∑ u, support q x u) = variation x ↔ p = q := by + rw [variation, sum_eq_sum_iff_of_le (fun u _ => support_le q x u)] + constructor + · intro he + have hm : StrictMono (fun i => q (p.symm i)) := by + intro a b hab + have h := he (p.symm a, p.symm b) (mem_univ _) + have h' : x (p.symm a) < x (p.symm b) := (hx _ _).mpr (by simpa using hab) + by_contra! hc + simp [support, not_lt.mpr hc] at h + omega + apply Equiv.ext + intro a + simpa using (congrFun hm.eq_id (p a)).symm + · rintro rfl u _ + simp only [support, ← hx] + split <;> omega + +theorem variation_rule (p : Option ι → Equiv.Perm (Fin m)) (x : Option ι → Fin m → ℤ) + (hx : ∀ s a b, x s a < x s b ↔ p s a < p s b) + (he : ∀ a, ∑ i, x (some i) a = x none a) : + variation (x none) ≤ ∑ i, variation (x (some i)) ∧ + (variation (x none) = ∑ i, variation (x (some i)) ↔ ∀ i, p (some i) = p none) := by + have hr : variation (x none) = ∑ i, ∑ u, support (p none) (x (some i)) u := by + rw [← (support_eq _ _ _ (hx none)).mpr rfl, sum_comm] + refine sum_congr rfl fun u _ => ?_ + unfold support + split <;> simp [*, sum_sub_distrib] + have hl i : (∑ u, support (p none) (x (some i)) u) ≤ variation (x (some i)) := + sum_le_sum fun u _ => support_le _ _ u + rw [hr] + refine ⟨sum_le_sum fun i _ => hl i, ?_⟩ + simp only [sum_eq_sum_iff_of_le (fun i _ => hl i), mem_univ, forall_true_left, + support_eq _ _ _ (hx _)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- Multivariate polynomial multiplication with total-degree budgets. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Finset + +/-- The subtype of `x : Fin m → ℕ` satisfying `∑ i, x i ≤ d`. -/ +abbrev Deg (m d : ℕ) := {x : Fin m → ℕ // ∑ i, x i ≤ d} + +instance (m d : ℕ) : Fintype (Deg m d) := by + classical + let f (x : Deg m d) (i : Fin m) : Fin (d + 1) := + ⟨x.val i, Nat.lt_succ_of_le ((single_le_sum (fun _ _ + => Nat.zero_le _) (mem_univ i)).trans x.property)⟩ + exact Fintype.ofInjective f (fun x y h => Subtype.ext (funext fun i + => congrArg Fin.val (congrFun h i))) + +variable {ι : Type} [Fintype ι] + +/-- Computes the leg by the application `Deg m (Profile.length L s)`. -/ +abbrev leg (m : ℕ) (L : ι → ℕ) (s : Option ι) := Deg m (Profile.length L s) + +variable (F : Type) [Field F] (m : ℕ) (L : ι → ℕ) + +/-- Returns `1` when `∑ i, (x (some i)).val = (x none).val` holds, and `0` otherwise. -/ +def entry (x : ∀ s, leg m L s) : F := if ∑ i, (x (some i)).val = (x none).val then 1 else 0 + +/-- Computes the simplex by the application `Tensor.ofRaw (Raw.ofTable (leg m L) (entry F m +L))`. -/ +def simplex : Tensor F (Option ι) := Tensor.ofRaw (Raw.ofTable (leg m L) (entry F m L)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- +# Homogeneous coordinates on a simplex + +A slack variable gives each monomial a prescribed total degree. +A pair of multiplications has one term for each pair of input tuples. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Finset + +/-- Computes the letter by the application `Option (Fin m)`. -/ +abbrev Letter (m : ℕ) := Option (Fin m) +/-- Computes the word by the application `Sym (Letter m) d`. -/ +abbrev Word (m d : ℕ) := Sym (Letter m) d + +variable {m d : ℕ} + +theorem size (t : Multiset (Letter m)) : + t.count none + ∑ i, t.count (some i) = t.card := by + rw [← Fintype.sum_option (fun i => t.count i), + Multiset.sum_count_eq_card (fun _ _ => mem_univ _)] + +theorem ext_word {t u : Multiset (Letter m)} (hd : t.card = u.card) : + t = u ↔ ∀ i, t.count (some i) = u.count (some i) := by + refine ⟨fun h => by rw [h]; simp, fun h => Multiset.ext.mpr ?_⟩ + rintro (_ | i) + · have ht := size t + have hu := size u + simp_rw [h] at ht + omega + · exact h i + +/-- Uses `⟨fun i => t.val.count (some i), (Nat.le_add_left _ _).trans_eq ((size t.val).trans +t.property)⟩` as the representation. -/ +def unpad (t : Word m d) : Deg m d := + ⟨fun i => t.val.count (some i), + (Nat.le_add_left _ _).trans_eq ((size t.val).trans t.property)⟩ + +/-- Bundles the indexing function as an equivalence. -/ +def coordinates (m d : ℕ) : Word m d ≃ Deg m d := Equiv.ofBijective unpad (by + constructor + · intro t u h + exact Subtype.ext ((ext_word (t.property.trans u.property.symm)).mpr + (fun i => congrFun (congrArg Subtype.val h) i)) + · intro x + let t := Multiset.replicate (d - ∑ i, x.val i) none + + ∑ i, Multiset.replicate (x.val i) (some i) + have he : t.card = d := by + simp only [t, Multiset.card_add, Multiset.card_sum, Multiset.card_replicate] + exact Nat.sub_add_cancel x.property + refine ⟨⟨t, he⟩, Subtype.ext (funext fun i => ?_)⟩ + simp [unpad, t, Multiset.count_replicate, Multiset.count_sum']) + +variable {ι : Type} [Fintype ι] (L R : ι → ℕ) + +/-- Uses `⟨∑ i, (x i).val, by rw [Multiset.card_sum]; exact sum_congr rfl fun i _ => (x +i).property⟩` as the representation. -/ +def merge (x : ∀ i, Word m (L i)) : Word m (∑ i, L i) := + ⟨∑ i, (x i).val, by rw [Multiset.card_sum]; exact sum_congr rfl fun i _ => (x i).property⟩ + +private theorem merge_eq (x : ∀ s, Word m (Profile.length L s)) : + merge L (fun i => x (some i)) = x none ↔ + ∑ i, (unpad (x (some i))).val = (unpad (x none)).val := by + erw [Subtype.ext_iff, ext_word ((merge L _).property.trans (x none).property.symm)] + simp only [merge, Multiset.count_sum', unpad, funext_iff, Finset.sum_apply] + +/-- Indexes the both by the coordinates of `Word m (Profile.length L s) × Word m (Profile.length +R s)`. -/ +abbrev Both (m : ℕ) (s : Option ι) := Word m (Profile.length L s) × Word m (Profile.length R s) +/-- The condition `∀ i, Both L R m (some i)` on the specified data. -/ +abbrev Inputs (m : ℕ) := ∀ i, Both L R m (some i) + +/-- In the case `some i`, this construction gives `x i`. -/ +def extend (x : Inputs L R m) : ∀ s, Both L R m s + | some i => x i + | none => (merge L (fun i => (x i).1), merge R (fun i => (x i).2)) + +variable (F : Type) [Field F] (m) [DecidableEq ι] + +/-- Uses `⟨Both L R m, Inputs L R m, fun x s y => if extend L R x s = y then 1 else 0⟩` as the +representation. -/ +def double : Raw F (Option ι) := + ⟨Both L R m, Inputs L R m, fun x s y => if extend L R x s = y then 1 else 0⟩ + +theorem double_coeff (x : ∀ s, Both L R m s) : + (double m L R F).coeff x = + if extend L R (fun i => x (some i)) none = x none then 1 else 0 := by + classical + change ∑ y : Inputs L R m, ∏ s, (if extend L R y s = x s then (1 : F) else 0) = _ + rw [Fintype.sum_eq_single (fun i => x (some i))] + · rw [Fintype.prod_option] + simp [extend] + · intro y hy + obtain ⟨i, hi⟩ := Function.ne_iff.mp hy + exact prod_eq_zero (mem_univ (some i)) (ite_eq_right hi) + +theorem double_eq : Tensor.ofRaw (double m L R F) = simplex F m L * simplex F m R := by + unfold simplex + rw [← Tensor.ofRaw_mul] + let e s := (coordinates m (Profile.length L s)).prodCongr (coordinates m (Profile.length R s)) + refine Tensor.ofRaw_eq (Raw.equiv_coeff e fun x => ?_) + change (∀ s, Both L R m s) at x + erw [double_coeff, Raw.coeff_mul, Raw.coeff_ofTable, Raw.coeff_ofTable] + change _ = entry F m L (fun s => unpad (x s).1) * entry F m R (fun s => unpad (x s).2) + simp only [entry, ite_mul, one_mul, zero_mul, ← ite_and] + congr 1 + exact propext (Prod.ext_iff.trans (and_congr (merge_eq L (fun s => (x s).1)) + (merge_eq R (fun s => (x s).2)))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +section +/- # Number of available cube translations in a degree simplex -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Finset + +theorem count_lower (m q : ℕ) : q ^ m ≤ m.factorial * Fintype.card (Deg m q) := by + have h := (Fintype.card_congr (coordinates m q)).le + change Fintype.card (Sym (Option (Fin m)) q) ≤ Fintype.card (Deg m q) at h + rw [Sym.card_sym_eq_choose, Fintype.card_option, Fintype.card_fin, + show m + 1 + q - 1 = q + m by omega, Nat.choose_symm_add] at h + calc + _ ≤ (q + 1) ^ m := Nat.pow_le_pow_left (by omega) _ + _ ≤ (q + 1).ascFactorial m := Nat.pow_succ_le_ascFactorial _ _ + _ = m.factorial * (q + m).choose m := Nat.ascFactorial_eq_factorial_mul_choose _ _ + _ ≤ _ := Nat.mul_le_mul_left _ h + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- +# Bihomogeneous substitution + +Expand `X^u (X+Y)^v` in powers of `X+Y` and `Y`. Its component of +highest Y-degree is `X^u Y^v`. Terms already containing too many Y's +cannot contribute to the chosen component. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Finset + +/-- Computes the mon by the application `Multiset (Letter m)`. -/ +abbrev Mon (m : ℕ) := Multiset (Letter m) +/-- Indexes the poly by the coordinates of `AddMonoidAlgebra F (Mon m × Mon m)`. -/ +abbrev Poly (F : Type) [Field F] (m : ℕ) := AddMonoidAlgebra F (Mon m × Mon m) + +variable (F : Type) [Field F] {m : ℕ} + +/-- The value specified by `AddMonoidAlgebra.single (u, v) 1`. -/ +def mon (u v : Mon m) : Poly F m := AddMonoidAlgebra.single (u, v) 1 + +/-- The monomial `X^u Y^v (X+Y)^w` in a formal polynomial ring. -/ +def mix (u v w : Mon m) : Poly F m := + mon F u v * (w.map fun i => mon F {i} 0 + mon F 0 {i}).prod + +private theorem mon_mul (u v p q : Mon m) : mon F u v * mon F p q = mon F (u + p) (v + q) := by + simp [mon] + +private theorem mix_mul (u v w a b c : Mon m) : + mix F u v w * mix F a b c = mix F (u + a) (v + b) (w + c) := by + unfold mix + rw [mul_mul_mul_comm, mon_mul, Multiset.map_add, Multiset.prod_add] + +theorem mix_prod {ι : Type} (s : Finset ι) (u v w : ι → Mon m) : + ∏ i ∈ s, mix F (u i) (v i) (w i) = mix F (∑ i ∈ s, u i) (∑ i ∈ s, v i) (∑ i ∈ s, w i) := by + classical + induction s using Finset.induction_on with + | empty => simp [mix, mon, AddMonoidAlgebra.one_def]; rfl + | insert i s hi ih => simp only [prod_insert hi, sum_insert hi, ih, mix_mul] + +private theorem mix_cons (u v w : Mon m) (i : Letter m) : + mix F u v (i ::ₘ w) = mix F (i ::ₘ u) v w + mix F u (i ::ₘ v) w := by + unfold mix + rw [Multiset.map_cons, Multiset.prod_cons, ← mul_assoc, mul_add, add_mul, + mul_comm (mon F u v) (mon F _ _), mon_mul, mul_comm (mon F u v) (mon F _ _), mon_mul] + simp + +theorem mix_high (u v w p q : Mon m) (h : v.card + w.card ≤ q.card) : + (mix F u v w).coeff (p, q) = if (u, v + w) = (p, q) then 1 else 0 := by + induction w using Multiset.induction_on generalizing u v with + | empty => simp [mix, mon, Finsupp.single_apply] + | cons i w ih => + have hne : (i ::ₘ u, v + w) ≠ (p, q) := by + intro he + have he' := congrArg (fun z => z.2.card) he + simp at he' h + omega + rw [mix_cons, AddMonoidAlgebra.coeff_add, Finsupp.add_apply, ih, ih, ite_eq_right hne, zero_add] + · simp + all_goals simp at h ⊢; omega + +theorem mix_low (u v w p q : Mon m) (h : q.card < v.card) : + (mix F u v w).coeff (p, q) = 0 := by + induction w using Multiset.induction_on generalizing u v with + | empty => + have : v ≠ q := by rintro rfl; exact lt_irrefl _ h + simp [mix, mon, this] + | cons i w ih => + rw [mix_cons, AddMonoidAlgebra.coeff_add, Finsupp.add_apply, ih _ _ h, ih, add_zero] + simp; omega + +/-- Indexes the part by the coordinates of `Word m (a + b - t.val) × Word m t.val`. -/ +abbrev Part (m a b : ℕ) (t : Fin (a + 1)) := Word m (a + b - t.val) × Word m t.val + +/-- The new right degree can be at most the old left degree. -/ +theorem expand_mix {a b : ℕ} (x : Word m a) (y : Word m b) : + ∃ c : ∀ t : Fin (a + 1), Part m a b t → F, + ∑ t, ∑ z, c t z • mix F 0 z.2.val z.1.val = mix F x.val 0 y.val := by + classical + let B (z : Σ t : Fin (a + 1), Part m a b t) := mix F 0 z.2.2.val z.2.1.val + let W := Submodule.span F (Set.range B) + have h (u v w : Mon m) (hu : u.card + v.card ≤ a) (hw : u.card + v.card + w.card = a + b) : + mix F u v w ∈ W := by + induction u using Multiset.induction_on generalizing v w with + | empty => + simp only [Multiset.card_zero, zero_add] at hu hw + let t : Fin (a + 1) := ⟨v.card, by omega⟩ + let z : Part m a b t := (⟨w, by dsimp [t]; omega⟩, ⟨v, rfl⟩) + exact Submodule.subset_span ⟨⟨t, z⟩, rfl⟩ + | cons i u ih => + have h₁ : mix F u v (i ::ₘ w) ∈ W := ih _ _ (by simp at hu; omega) (by simp at hw ⊢; omega) + have h₂ : mix F u (i ::ₘ v) w ∈ W := ih _ _ (by simp at hu ⊢; omega) (by simp at hw ⊢; omega) + rw [mix_cons] at h₁ + exact (W.add_mem_iff_left h₂).mp h₁ + have he := h x.val 0 y.val (by simp) (by simp) + obtain ⟨c, hc⟩ := (Submodule.mem_span_range_iff_exists_fun F).mp he + refine ⟨fun t z => c ⟨t, z⟩, ?_⟩ + rw [Fintype.sum_sigma] at hc + exact hc + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- +# Redistributing degree budgets + +At each input expand in the variables `X+Y,Y`. At the output extract +the coefficient with the original Y-degree. Sectors above that degree +vanish. Each remaining sector is a pair of ordinary multiplications. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Finset +open scoped NNReal + +variable {ι F : Type} [Fintype ι] [Field F] {m : ℕ} + +private abbrev Slot (L : ι → ℕ) := ∀ i, Fin (L i + 1) +private abbrev left {L : ι → ℕ} (R : ι → ℕ) (t : Slot L) (i : ι) := L i + R i - (t i).val +private abbrev right {L : ι → ℕ} (t : Slot L) (i : ι) := (t i).val + +private def old (F : Type) [Field F] {a b : ℕ} (z : Word m a × Word m b) := + mix F z.1.val 0 z.2.val + +private def new (F : Type) [Field F] {a b : ℕ} (z : Word m a × Word m b) := + mix F 0 z.2.val z.1.val + +private def changeVar (F : Type) [Field F] {a b : ℕ} (z : Word m a × Word m b) := + (expand_mix F z.1 z.2).choose + +private theorem changeVar_spec {a b : ℕ} (z : Word m a × Word m b) : + old F z = ∑ t, ∑ y, changeVar F z t y • new F y := + (expand_mix F z.1 z.2).choose_spec.symm + +private def read (F : Type) [Field F] {a b : ℕ} (z : Word m a × Word m b) : Poly F m →ₗ[F] F := + (Finsupp.lapply (z.1.val, z.2.val)).comp (AddMonoidAlgebra.coeffLinearEquiv F).toLinearMap + +private theorem read_old {a b : ℕ} (z y : Word m a × Word m b) : + read F z (old F y) = if y = z then 1 else 0 := by + change (mix F y.1.val 0 y.2.val).coeff (z.1.val, z.2.val) = _ + rw [mix_high _ _ _ _ _ _ (by simp), zero_add] + congr 1 + exact propext (Prod.ext_iff.trans ((and_congr Subtype.ext_iff.symm Subtype.ext_iff.symm).trans + Prod.ext_iff.symm)) + +private theorem read_new {a b c d : ℕ} (z : Word m a × Word m b) (y : Word m c × Word m d) + (h : b < d) : read F z (new F y) = 0 := + mix_low F 0 y.2.val y.1.val z.1.val z.2.val (by simpa using h) + +variable (L R : ι → ℕ) + +private theorem old_prod (x : Inputs L R m) : + ∏ i, old F (x i) = old F (extend L R x none) := by + unfold old + rw [mix_prod, sum_const_zero] + rfl + +private theorem new_prod (x : Inputs L R m) : + ∏ i, new F (x i) = new F (extend L R x none) := by + unfold new + rw [mix_prod, sum_const_zero] + rfl + +variable [DecidableEq ι] + +private theorem expand_prod (x : Inputs L R m) : + old F (extend L R x none) = + ∑ t : Slot L, ∑ y : Inputs (left R t) (right t) m, + (∏ i, changeVar F (x i) (t i) (y i)) • new F (extend (left R t) (right t) y none) := by + rw [← old_prod] + simp_rw [changeVar_spec] + rw [Fintype.prod_sum] + refine sum_congr rfl fun t _ => ?_ + rw [Fintype.prod_sum] + refine sum_congr rfl fun y _ => ?_ + change Slot L at t + change Inputs (left R t) (right t) m at y + erw [← new_prod (left R t) (right t) y] + simp only [Algebra.smul_def, prod_mul_distrib, map_prod] + rfl + +private def maps (t : Slot L) : Raw.Local (double m (left R t) (right t) F) (double m L R F) + | none, x, y => read F x (new F y) + | some i, x, y => changeVar F x (t i) y + +private theorem apply_maps (t : Slot L) (x : ∀ s, Both L R m s) : + (double m (left R t) (right t) F).applyLocal (maps L R t) x = + ∑ y : Inputs (left R t) (right t) m, + (∏ i, changeVar F (x (some i)) (t i) (y i)) * + read F (x none) (new F (extend (left R t) (right t) y none)) := by + unfold Raw.applyLocal + refine sum_congr rfl fun y _ => ?_ + change Inputs (left R t) (right t) m at y + change (∏ s, ∑ z : Both (left R t) (right t) m s, + maps L R t s (x s) z * if extend (left R t) (right t) y s = z then 1 else 0) = _ + have hs s : (∑ z : Both (left R t) (right t) m s, + maps (F := F) L R t s (x s) z * if extend (left R t) (right t) y s = z then 1 else 0) = + maps L R t s (x s) (extend (left R t) (right t) y s) := by + rw [Fintype.sum_eq_single (extend (left R t) (right t) y s)] + · simp + · intro z hz + simp [hz.symm] + simp_rw [hs] + rw [Fintype.prod_option, mul_comm] + rfl + +private def sectors := (univ : Finset (Slot L)).filter (fun t => ∑ i, right t i ≤ ∑ i, R i) + +private theorem redistribution : + Tensor.ofRaw (double m L R F) ≤ + ∑ t ∈ sectors L R, Tensor.ofRaw (double m (left R t) (right t) F) := by + refine (Raw.restriction_sum_iff _ _ _).mpr ⟨maps L R, fun x => ?_⟩ + change (∀ s, Both L R m s) at x + have hfull : (double m L R F).coeff x = + ∑ t : Slot L, (double m (left R t) (right t) F).applyLocal (maps L R t) x := by + rw [double_coeff, ← read_old, expand_prod L R] + simp only [map_sum, map_smul, smul_eq_mul, apply_maps] + rw [hfull] + symm + apply sum_subset (subset_univ _) + intro t _ ht + have he : (∑ i, R i) < ∑ i, right t i := by simpa [sectors] using ht + rw [apply_maps] + apply sum_eq_zero + intro y _ + exact mul_eq_zero_of_right _ (read_new _ _ he) + +private theorem card_sectors : + (sectors L R).card ≤ (1 + ∑ i, (L i + R i)) ^ Fintype.card ι := by + calc + _ ≤ Fintype.card (Slot L) := card_le_univ _ + _ = ∏ i, (L i + 1) := by simp [Slot, Fintype.card_pi] + _ ≤ ∏ _i : ι, (1 + ∑ i, (L i + R i)) := by + apply prod_le_prod + intro i hi + have h := single_le_sum (f := fun i => L i + R i) (fun _ _ => Nat.zero_le _) hi + omega + _ = _ := by simp + +omit [DecidableEq ι] in +/-- The number of bidegree sectors is polynomial in the total degree. -/ +theorem sector (s : Finset ι) (hs : ∀ i ∈ s, L i = 0) + (f : Tensor F (Option ι) →+* NNReal) (hf : Monotone f) : + ∃ U V : ι → ℕ, U + V = L + R ∧ (∀ i ∈ s, V i = 0) ∧ (∑ i, V i) ≤ ∑ i, R i ∧ + f (simplex F m L) * f (simplex F m R) ≤ + ((1 + ∑ i, (L i + R i) : ℕ) : NNReal) ^ Fintype.card ι * + f (simplex F m U) * f (simplex F m V) := by + classical + have he : (sectors L R).Nonempty := ⟨fun _ => 0, by simp [sectors, right]⟩ + let g (t : Slot L) := f (Tensor.ofRaw (double m (left R t) (right t) F)) + obtain ⟨t, ht, hmax⟩ := exists_max_image (sectors L R) g he + refine ⟨left R t, right t, ?_, ?_, (mem_filter.mp ht).2, ?_⟩ + · funext i + simp only [Pi.add_apply, left, right] + have := (t i).isLt + omega + · intro i hi + have := (t i).isLt + have := hs i hi + unfold right + omega + rw [mul_assoc, ← map_mul, ← map_mul, ← double_eq, ← double_eq] + calc + _ ≤ ∑ u ∈ sectors L R, g u := by + rw [← map_sum] + exact hf (redistribution L R) + _ ≤ (sectors L R).card * g t := by + simpa using sum_le_sum (fun u hu => hmax u hu) + _ ≤ _ := mul_le_mul_of_nonneg_right (by exact_mod_cast card_sectors L R) (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- # Natural-log simplex prices at finite placements -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral + +variable {K ι : Type} [Field K] [Fintype ι] [DecidableEq ι] {X : Type*} [PseudoMetricSpace X] + +/-- Evaluates `i.elim o x` at the input `i`. -/ +def sites (o : X) (x : ι → X) : Option ι → X := fun i => i.elim o x + +/-- The quantity computed by `Real.log 2 * A.price (sites o x) (simplex K m L)`. -/ +def H (A : MatrixExponent.Prices.Atlas K X) (o : X) (x : ι → X) (m : ℕ) (L : ι → ℕ) : ℝ := + Real.log 2 * A.price (sites o x) (simplex K m L) + +theorem monotone_price [Nontrivial ι] (A : MatrixExponent.Prices.Atlas K X) (x : ι → X) : + Monotone (A.price x) := by + obtain ⟨_, d, hd, f, hf, he⟩ := A.valid x + rw [he] + intro B T h + by_cases hb : B = 0 + · simpa [hb, Tensor.values] using Tensor.values_nonneg hd.1 hf T + unfold Tensor.values + apply mul_le_mul_of_nonneg_left _ hd.1 + apply div_le_div_of_nonneg_right _ (Real.log_pos (by norm_num)).le + exact Real.log_le_log (zero_lt_one.trans_le (Tensor.value_one_le hf hb)) (hf h) + +theorem H_chord (A : MatrixExponent.Prices.Atlas K X) (o : X) (x y z : ι → X) {t : ℝ} + (ht : 0 ≤ t) (ht' : t ≤ 1) + (h₁ : ∀ i, Dist.dist (x i) (z i) = t * Dist.dist (x i) (y i)) + (h₂ : ∀ i, Dist.dist (z i) (y i) = (1 - t) * Dist.dist (x i) (y i)) (m : ℕ) (L : ι → ℕ) : + H A o z m L ≤ (1 - t) * H A o x m L + t * H A o y m L := by + have h := A.chord (x := sites o x) (y := sites o y) (z := sites o z) ht ht' + (by rintro (_|i); · simp [sites] + exact h₁ i) + (by rintro (_|i); · simp [sites] + exact h₂ i) (simplex K m L) + unfold H + linarith only [mul_le_mul_of_nonneg_left h (Real.log_pos (by norm_num : (1 : ℝ) < 2)).le] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- +# Merging polynomial inputs at each site + +Inputs grouped at a site multiply locally. Those reaching the output +site multiply into the answer there. The local coefficient maps use +total degrees, so the new budgets are the sums at the input sites. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Finset + +variable {K ι κ : Type} [Field K] [Fintype ι] [DecidableEq ι] [Fintype κ] [DecidableEq κ] + (m : ℕ) (L : ι → ℕ) (f : ι → Option κ) + +/-- Computes the route by the application `s.elim none f`. -/ +def route (s : Option ι) := s.elim none f + +/-- The sum of `if f i = s then g i else 0` indexed by `i`. -/ +def gather {G : Type*} [AddCommMonoid G] (g : ι → G) (s : Option κ) : G := + ∑ i, if f i = s then g i else 0 + +/-- Computes the merged by the application `gather f L (some j)`. -/ +def merged (j : κ) := gather f L (some j) + +omit [DecidableEq ι] in +private theorem gather_all {G : Type*} [AddCommMonoid G] (g : ι → G) : + gather f g none + ∑ j, gather f g (some j) = ∑ i, g i := by + rw [← Fintype.sum_option] + unfold gather + rw [sum_comm] + simp + +private abbrev Tuple (m : ℕ) (L : ι → ℕ) := ∀ s, leg m L s + +private def total {m : ℕ} (v : Fin m → ℕ) : ℕ := ∑ i, v i + +omit [DecidableEq ι] in +private theorem total_sum (g : ι → Fin m → ℕ) : total (∑ i, g i) = ∑ i, total (g i) := by + simp only [total, Finset.sum_apply] + exact sum_comm + +private def collect (x : Tuple m L) : Tuple m (merged L f) := by + let y j := gather f (fun i => (x (some i)).val) (some j) + have hy j : total (y j) ≤ merged L f j := by + unfold y merged gather + rw [total_sum] + refine sum_le_sum fun i _ => ?_ + split + · exact (x (some i)).property + · simp [total] + exact fun s => match s with + | some j => ⟨y j, hy j⟩ + | none => ⟨∑ j, y j, (total_sum _ _).le.trans (sum_le_sum (fun j _ => hy j))⟩ + +private abbrev Bundle (s : Option κ) := ∀ t : Raw.Fiber (route f) s, leg m L t + +private def localSum (s : Option κ) (x : Bundle m L f s) : Fin m → ℕ := + ∑ i, if h : f i = s then (x ⟨some i, h⟩).val else 0 + +private def unbundle (x : ∀ s, Bundle m L f s) : Tuple m L := fun t => x (route f t) ⟨t, rfl⟩ + +omit [DecidableEq ι] [Fintype κ] in +private theorem localSum_eq (x : ∀ s, Bundle m L f s) (s : Option κ) : + localSum m L f s (x s) = gather f (fun i => (unbundle m L f x (some i)).val) s := by + unfold localSum gather + refine sum_congr rfl fun i _ => ?_ + by_cases he : f i = s + · subst s + simp only [↓reduceDIte, ↓reduceIte] + rfl + · simp only [he, ↓reduceDIte, ↓reduceIte] + +private def fits : (s : Option κ) → Bundle m L f s → leg m (merged L f) s → Prop + | some j, x, y => y.val = localSum m L f (some j) x + | none, x, y => localSum m L f none x + y.val = (x ⟨none, rfl⟩).val + +omit [DecidableEq ι] in +private theorem valid (x : ∀ s, Bundle m L f s) (y : Tuple m (merged L f)) : + ((∀ s, fits m L f s (x s) (y s)) ∧ ∑ j, (y (some j)).val = (y none).val) ↔ + y = collect m L f (unbundle m L f x) ∧ + ∑ i, (unbundle m L f x (some i)).val = (unbundle m L f x none).val := by + let Y := collect m L f (unbundle m L f x) + have he (j) : (Y (some j)).val = localSum m L f (some j) (x (some j)) := + (localSum_eq m L f x _).symm + have hy : ∑ j, (Y (some j)).val = (Y none).val := rfl + have hh : localSum m L f none (x none) + (Y none).val = + ∑ i, (unbundle m L f x (some i)).val := by + rw [localSum_eq] + exact gather_all _ _ + constructor + · rintro ⟨h, hs⟩ + have h' (j) : y (some j) = Y (some j) := Subtype.ext ((h (some j)).trans (he j).symm) + have hz : y none = Y none := Subtype.ext (by simpa only [h', hy] using hs.symm) + refine ⟨funext fun s => ?_, hh.symm.trans ?_⟩ + · cases s with + | none => exact hz + | some j => exact h' j + · rw [← hz] + exact h none + · rintro ⟨rfl, h⟩ + exact ⟨fun s => match s with | none => hh.trans h | some j => he j, hy⟩ + +theorem simplex_merge : Tensor.place (route f) (simplex K m L) ≤ simplex K m (merged L f) := by + classical + let A := Raw.ofTable (leg m (merged L f)) (entry K m (merged L f)) + let B := (Raw.ofTable (leg m L) (entry K m L)).group (route f) + let Q s (x : Bundle m L f s) (y : leg m (merged L f) s) : K := if fits m L f s x y then 1 else 0 + apply (Raw.restricts_iff A B).mpr + refine ⟨Q, fun x => ?_⟩ + change (∀ s, Bundle m L f s) at x + have hA (y : Tuple m (merged L f)) : A.coeff y = entry K m (merged L f) y + := Raw.coeff_ofTable _ _ y + have hB : B.coeff x = entry K m L (unbundle m L f x) := + (Raw.coeff_group _ _ _).trans (Raw.coeff_ofTable _ _ _) + rw [hB] + change _ = ∑ y : Tuple m (merged L f), (∏ s, Q s (x s) (y s)) * A.coeff y + simp only [Q, hA, entry, Fintype.prod_ite_zero, prod_const_one, ite_mul, one_mul, + zero_mul, ← ite_and, valid m L f x] + simp only [ite_and, Fintype.sum_ite_eq'] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- # Zero-degree inputs are dummy sites -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Finset + +variable {K ι κ : Type} [Field K] [Fintype ι] [DecidableEq ι] [Fintype κ] [DecidableEq κ] + (m : ℕ) (L : ι → ℕ) (e : ι ↪ κ) + +private theorem deg_zero {d : ℕ} (x : Deg m d) (hd : d = 0) : x.val = 0 := by + funext i + have := (single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ i)).trans x.property + change x.val i = 0 + omega + +theorem simplex_embed : + Tensor.place (route (some ∘ e)) (simplex K m L) = simplex K m (merged L (some ∘ e)) := by + classical + let M := merged L (some ∘ e) + let f := route (some ∘ e) + have hm (s) : Profile.length M (f s) = Profile.length L s := by + cases s with + | none => + simp only [f, route, Option.elim_none, Profile.length, M, merged, gather] + rw [sum_comm] + simp + | some i => simp [f, route, Profile.length, M, merged, gather, e.injective.eq_iff] + apply le_antisymm (simplex_merge m L _) + let A := (Raw.ofTable (leg m L) (entry K m L)).group f + let lift (t : Option κ) (x : leg m M t) : A.leg t := fun s => + ⟨x.val, x.property.trans_eq (by rw [← hm s.val, s.property])⟩ + refine Raw.Restricts.pullback lift fun x => ?_ + change (∀ s, leg m M s) at x + have hzero {j} (hj : j ∉ univ.map e) : (x (some j)).val = 0 := by + apply deg_zero + have hne (i) : e i ≠ j := fun h => hj (mem_map.mpr ⟨i, mem_univ _, h⟩) + simp [Profile.length, M, merged, gather, hne] + have he : ∑ j, (x (some j)).val = ∑ i, (x (some (e i))).val := by + rw [← sum_map univ e (fun j => (x (some j)).val)] + exact (sum_subset (subset_univ _) (fun _ _ hj => hzero hj)).symm + erw [Raw.coeff_ofTable, Raw.coeff_group, Raw.coeff_ofTable] + change (if ∑ j, (x (some j)).val = (x none).val then (1 : K) else 0) = + if ∑ i, (x (some (e i))).val = (x none).val then 1 else 0 + rw [he] + +variable {X : Type*} [PseudoMetricSpace X] (A : MatrixExponent.Prices.Atlas K X) (o : X) + +private theorem embedded_H (x : κ → X) : + H A o x m (merged L (some ∘ e)) = H A o (x ∘ e) m L := by + have hv : sites o (x ∘ e) = sites o x ∘ route (some ∘ e) := by + funext s + cases s <;> rfl + rw [H, H, hv, A.place, Function.comp_apply, simplex_embed] + +theorem left_H (x : ι → X) (y : κ → X) : + H A o (Sum.elim x y) m (Sum.elim L 0) = H A o x m L := by + let e : ι ↪ ι ⊕ κ := ⟨Sum.inl, Sum.inl_injective⟩ + have he : merged L (some ∘ e) = Sum.elim L 0 := by + funext s + rcases s with i | j <;> simp [merged, gather, e] + rw [← he, embedded_H] + rfl + +theorem right_H (x : κ → X) (y : ι → X) : + H A o (Sum.elim x y) m (Sum.elim 0 L) = H A o y m L := by + let e : ι ↪ κ ⊕ ι := ⟨Sum.inr, Sum.inr_injective⟩ + have he : merged L (some ∘ e) = Sum.elim (0 : κ → ℕ) L := by + funext s + rcases s with i | j <;> simp [merged, gather, e] + rw [← he, embedded_H] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- +# Moving inputs toward the output + +Convexity rounds each intermediate placement to one endpoint of its +segment without decreasing the price minus the assigned costs. Merging +inputs then gives a degree budget on the original set of sites. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Finset + +variable {K ι κ : Type} [Field K] [Fintype ι] [DecidableEq ι] [Fintype κ] [DecidableEq κ] + {X : Type*} [PseudoMetricSpace X] (A : MatrixExponent.Prices.Atlas K X) (o : X) + +omit [DecidableEq ι] in +private theorem merged_cost (L : ι → ℕ) (r : ι → Option κ) (f : κ → ℝ) : + ∑ j, f j * merged L r j = ∑ i, (r i).elim 0 f * L i := by + simp only [merged, gather, Nat.cast_sum, Nat.cast_ite, Nat.cast_zero, mul_sum, mul_ite, mul_zero] + rw [sum_comm] + apply sum_congr rfl + intro i _ + cases r i <;> simp + +private theorem merge_price [Nonempty κ] (x : κ → X) (m : ℕ) (L : ι → ℕ) (r : ι → Option κ) : + H A o (fun i => (r i).elim o x) m L ≤ H A o x m (merged L r) := by + have he : sites o (fun i => (r i).elim o x) = sites o x ∘ route r := by + funext s + cases s <;> rfl + unfold H + rw [he, A.place, Function.comp_apply] + exact mul_le_mul_of_nonneg_left (monotone_price A _ (simplex_merge m L r)) + (Real.log_pos (by norm_num)).le + +private theorem round_sites (x y : ι → X) (f g t : ι → ℝ) (ht : ∀ i, 0 ≤ t i) (ht' : ∀ i, t i ≤ 1) + (h₁ : ∀ i, Dist.dist o (y i) = t i * Dist.dist o (x i)) + (h₂ : ∀ i, Dist.dist (y i) (x i) = (1 - t i) * Dist.dist o (x i)) + (hg : ∀ i, t i * f i ≤ g i) (m : ℕ) (L : ι → ℕ) : + ∃ b : ι → Bool, H A o y m L - ∑ i, g i * L i ≤ + H A o (fun i => if b i then x i else o) m L - ∑ i, (if b i then f i else 0) * L i := by + let p (b : ι → Option Bool) i := (b i).elim (y i) (fun a => if a then x i else o) + let c (b : ι → Option Bool) i := (b i).elim (g i) (fun a => if a then f i else 0) + let V b := H A o (p b) m L - ∑ i, c b i * L i + have step (b : ι → Option Bool) i (hi : b i = none) : + ∃ a : Bool, V b ≤ V (Function.update b i (some a)) := by + let l := Function.update b i (some false) + let r := Function.update b i (some true) + have hl j : Dist.dist (p l j) (p b j) = t i * Dist.dist (p l j) (p r j) := by + by_cases h : j = i + · subst j; simpa [p, l, r, hi] using h₁ i + · simp [p, l, r, h] + have hr j : Dist.dist (p b j) (p r j) = (1 - t i) * Dist.dist (p l j) (p r j) := by + by_cases h : j = i + · subst j; simpa [p, l, r, hi] using h₂ i + · simp [p, l, r, h] + have hc j : (1 - t i) * c l j + t i * c r j ≤ c b j := by + by_cases h : j = i + · subst j; simpa [c, l, r, hi] using hg i + · simp only [c, l, r, Function.update_of_ne h] + exact le_of_eq (by ring) + have hcost : (1 - t i) * (∑ j, c l j * L j) + t i * (∑ j, c r j * L j) ≤ ∑ j, c b j * L j := by + rw [mul_sum, mul_sum, ← sum_add_distrib] + apply sum_le_sum + intro j _ + rw [← mul_assoc, ← mul_assoc, ← add_mul] + exact mul_le_mul_of_nonneg_right (hc j) (by positivity) + have he : V b ≤ (1 - t i) * V l + t i * V r := by + unfold V + linarith only [H_chord A o _ _ _ (ht i) (ht' i) hl hr m L, hcost] + rcases le_total (V l) (V r) with h | h + · exact ⟨true, he.trans (by linarith [mul_le_mul_of_nonneg_left h (sub_nonneg.mpr (ht' i))])⟩ + · exact ⟨false, he.trans (by linarith [mul_le_mul_of_nonneg_left h (ht i)])⟩ + have aux (s : Finset ι) : ∃ b : ι → Option Bool, + (∀ i, b i = none ↔ i ∉ s) ∧ V (fun _ => none) ≤ V b := by + induction s using Finset.induction_on with + | empty => exact ⟨fun _ => none, by simp, le_rfl⟩ + | insert i s hi ih => + obtain ⟨b, hb, h⟩ := ih + obtain ⟨a, ha⟩ := step b i ((hb i).mpr hi) + refine ⟨_, fun j => ?_, h.trans ha⟩ + by_cases he : j = i <;> simp [he, hb] + obtain ⟨b, hb, h⟩ := aux univ + have he : ∀ i, ∃ a, b i = some a := by + intro i + have : b i ≠ none := by simp [hb] + cases h' : b i <;> simp_all + choose a ha using he + refine ⟨a, ?_⟩ + have hba : b = fun i => some (a i) := funext ha + rw [hba] at h + exact h + +/-- Every budget for the mixed placement is dominated, after costs, by +some budget at the outer placement. -/ +theorem contract [Nonempty ι] (x y : ι → X) (f g t : ι → ℝ) (ht : ∀ i, 0 ≤ t i) (ht' : ∀ i, t i ≤ 1) + (h₁ : ∀ i, Dist.dist o (y i) = t i * Dist.dist o (x i)) + (h₂ : ∀ i, Dist.dist (y i) (x i) = (1 - t i) * Dist.dist o (x i)) + (hg : ∀ i, t i * f i ≤ g i) (m : ℕ) (L : ι ⊕ ι → ℕ) : + ∃ R, H A o (Sum.elim x y) m L - ∑ i, Sum.elim f g i * L i ≤ H A o x m R - ∑ i, f i * R i := by + let a : ι ⊕ ι → ι := Sum.elim id id + obtain ⟨b, hb⟩ := round_sites A o (x ∘ a) (Sum.elim x y) (f ∘ a) (Sum.elim f g) + (Sum.elim (fun _ => 1) t) (by rintro (i|i) <;> simp [ht]) (by rintro (i|i) <;> simp [ht']) + (by rintro (i|i) <;> simp [a, h₁]) (by rintro (i|i) <;> simp [a, h₂]) + (by rintro (i|i) <;> simp [a, hg]) m L + let r i := if b i then some (a i) else none + have he : (fun i => if b i then (x ∘ a) i else o) = fun i => (r i).elim o x := by + funext i + simp only [r] + split <;> rfl + have he' i : (if b i then (f ∘ a) i else 0) = (r i).elim 0 f := by + simp only [r] + split <;> rfl + refine ⟨merged L r, hb.trans ?_⟩ + simp only [he, he', merged_cost] + exact sub_le_sub_right (merge_price A o x m L r) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Multi/Radial.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Multi/Radial.lean new file mode 100644 index 0000000000..39f9cd8d8c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Multi/Radial.lean @@ -0,0 +1,826 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Multi.Count +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Pairing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Root +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth + +/-! +# Packing independent cubes into a degree simplex + +Index the cubes by nonnegative translation vectors with sum at most +`q`. Summing the one-variable grading over the coordinates keeps +only terms whose input and output translation vectors all agree. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Finset + +variable {ι : Type} [Fintype ι] (F : Type) [Field F] (m q : ℕ) (L : ι → ℕ) + +private abbrev blockFromCubes (s : Option ι) := Deg m q × (Fin m → Profile.leg L s) + +private def join (s : Option ι) (x : blockFromCubes m q L s) : leg m (fun i => (q + m) * L i) s + := by + refine ⟨fun l => x.1.val l * Profile.length L s + (x.2 l).val, ?_⟩ + have he : Profile.length (fun i => (q + m) * L i) s = (q + m) * Profile.length L s := by + cases s <;> simp [Profile.length, mul_sum] + rw [he, sum_add_distrib, ← sum_mul, add_mul] + apply Nat.add_le_add (Nat.mul_le_mul_right _ x.1.property) + simpa using sum_le_sum (s := univ) (fun l _ => (x.2 l).isLt.le) + +private def bigFromCubes (x : ∀ s, blockFromCubes m q L s) := + entry F m (fun i => (q + m) * L i) (fun s => join m q L s (x s)) + +private def score (l : Fin m) (s : Option ι) (p : blockFromCubes m q L s) : ℤ := + if s.isNone then -Profile.weight (p.1.val l) (Profile.length L s) (p.2 l).val (Fintype.card ι) + else Profile.weight (p.1.val l) (Profile.length L s) (p.2 l).val 1 + +private def gradingFromCubes (s : Option ι) (p : blockFromCubes m q L s) : ℤ := ∑ l, + score m q L l s p + +private theorem grading_ruleFromCubes (x : ∀ s, blockFromCubes m q L s) (hx : bigFromCubes F m q L + x ≠ 0) : + 0 ≤ ∑ s, gradingFromCubes m q L s (x s) ∧ + ((∑ s, gradingFromCubes m q L s (x s)) = 0 ↔ ∀ i, (x (some i)).1 = (x none).1) := by + have he : ∑ i, (join m q L (some i) (x (some i))).val = (join m q L none (x none)).val := by + simpa [bigFromCubes, entry] using hx + have hs (l : Fin m) : 0 ≤ ∑ s, score m q L l s (x s) ∧ + ((∑ s, score m q L l s (x s)) = 0 ↔ ∀ i, (x (some i)).1.val l = (x none).1.val l) := by + have hh : ∑ i, ((x (some i)).1.val l * L i + ((x (some i)).2 l).val) = + (x none).1.val l * (∑ i, L i) + ((x none).2 l).val := by + simpa only [Finset.sum_apply, join, Profile.length] using congrFun he l + have hw := Profile.weights (fun i => ((x (some i)).1.val l : ℤ)) (fun i => (L i : ℤ)) + (fun i => (((x (some i)).2 l).val : ℤ)) ((x none).1.val l) ((x none).2 l).val + (fun _ => by positivity) (fun i => by exact_mod_cast ((x (some i)).2 l).isLt) + (by exact_mod_cast hh) + simpa [Fintype.sum_option, score, Profile.length] using hw + unfold gradingFromCubes + rw [sum_comm] + refine ⟨sum_nonneg (fun l _ => (hs l).1), ?_⟩ + simp only [sum_eq_zero_iff_of_nonneg (fun l _ => (hs l).1), mem_univ, forall_true_left, (hs _).2] + exact ⟨fun h i => Subtype.ext (funext fun l => h l i), fun h l i => by rw [h i]⟩ + +open Classical in +private theorem aligned (x : ∀ s, blockFromCubes m q L s) + (h : ∀ i, (x (some i)).1 = (x none).1) : + bigFromCubes F m q L x = copyTable (Profile.entry F L) m (fun s => (x s).2) := by + unfold bigFromCubes entry copyTable Profile.entry + rw [Fintype.prod_ite_zero, prod_const_one] + congr 1 + apply propext + rw [funext_iff] + simp only [Finset.sum_apply, join, Profile.length, h, sum_add_distrib, ← mul_sum, add_right_inj] + +private theorem table_cubes : + Profile.array (Profile.grade (gradingFromCubes m q L) (bigFromCubes F m q L)) = + (Fintype.card (Deg m q) : Tensor F (Option ι)) * Profile.polynomial F L ^ m := by + rw [Profile.polynomial, ← table_pow] + exact Profile.grade_labels (gradingFromCubes m q L) (bigFromCubes F m q L) (copyTable + (Profile.entry F L) m) + (fun x hx => (grading_ruleFromCubes F m q L x hx).2) (aligned F m q L) + +theorem cubes_le [Infinite F] (f : Tensor F (Option ι) →+* NNReal) (hf : Monotone + f) : + ((q : ℝ) * f (Profile.polynomial F L)) ^ m ≤ + m.factorial * (f (simplex F m (fun i => (q + m) * L i)) : ℝ) := by + classical + have hb : Profile.array (bigFromCubes F m q L) ≤ simplex F m (fun i => (q + m) * L i) := by + refine Raw.Restricts.pullback (join m q L) fun x => ?_ + change (∀ s, blockFromCubes m q L s) at x + exact (Raw.coeff_ofTable _ _ x).trans + (Raw.coeff_ofTable _ (entry F m (fun i => (q + m) * L i)) (fun s => join m q L s (x s))).symm + have h := Profile.grade_price f hf (bigFromCubes F m q L) (gradingFromCubes m q L) + (fun x hx => (grading_ruleFromCubes F m q L x hx).1) + rw [table_cubes, map_mul, map_natCast, map_pow] at h + have he := NNReal.coe_le_coe.mpr (h.trans (hf hb)) + simp only [NNReal.coe_mul, NNReal.coe_natCast, NNReal.coe_pow] at he + have hc : (q : ℝ) ^ m ≤ m.factorial * (Fintype.card (Deg m q) : ℝ) + := by exact_mod_cast count_lower m q + rw [mul_pow] + refine (mul_le_mul_of_nonneg_right hc (by positivity)).trans ?_ + rw [mul_assoc] + exact mul_le_mul_of_nonneg_left he (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- +# Packing ordered simplices into a cube + +Cumulative degrees with strictly increasing offsets give one copy for +each coordinate ordering. The variation grading removes mixed orders. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Finset + +variable {m : ℕ} {ι : Type} [Fintype ι] + +private def cum (x : Fin m → ℕ) (t : Fin m) := ∑ u ∈ Iic t, x u + +private theorem cum_inj : Function.Injective (cum (m := m)) := by + intro x y h + funext t + induction t using WellFoundedLT.induction with + | ind t ih => + have he := congrFun h t + have h' : ∑ u ∈ Iio t, x u = ∑ u ∈ Iio t, y u := sum_congr rfl fun u hu => ih u (mem_Iio.mp hu) + unfold cum at he + rw [← Finset.insert_Iio t] at he + simp only [sum_insert (show t ∉ Iio t by simp), h'] at he + exact Nat.add_right_cancel he + +private theorem cum_sum (x : ι → Fin m → ℕ) (t : Fin m) : + cum (∑ i, x i) t = ∑ i, cum (x i) t := by + simp only [cum, Finset.sum_apply] + exact sum_comm + +private def shifted (x : Fin m → ℕ) (d : ℕ) (t : Fin m) := cum x t + d * t.val + +private theorem shifted_mono (x : Fin m → ℕ) {d : ℕ} (hd : 0 < d) : StrictMono (shifted x d) := by + intro u v huv + exact add_lt_add_of_le_of_lt (sum_le_sum_of_subset (Iic_subset_Iic.mpr huv.le)) + (Nat.mul_lt_mul_of_pos_left huv hd) + +variable (m) (L : ι → ℕ) + +private abbrev blockFromOrdered (s : Option ι) := Equiv.Perm (Fin m) × leg m L s + +private def offset : Option ι → ℕ + | none => Fintype.card ι + | some _ => 1 + +private theorem offset_pos [Nonempty ι] (s : Option ι) : 0 < offset s := by + cases s <;> simp [offset, Fintype.card_pos] + +private def degreeFromOrdered (s : Option ι) (x : blockFromOrdered m L s) (t : Fin m) := + shifted x.2.val (offset s) (x.1 t) + +private def embed [Nonempty ι] (s : Option ι) (x : blockFromOrdered m L s) (t : Fin m) : + Profile.leg (fun i => L i + m) s := by + refine ⟨degreeFromOrdered m L s x t, ?_⟩ + rw [show Profile.length (fun i => L i + m) s = Profile.length L s + offset s * m by + cases s <;> simp [Profile.length, offset, sum_add_distrib]] + exact add_lt_add_of_le_of_lt ((sum_le_sum_of_subset (subset_univ _)).trans x.2.property) + (Nat.mul_lt_mul_of_pos_left (x.1 t).isLt (offset_pos s)) + +private theorem agree (x : ∀ s, blockFromOrdered m L s) (hp : ∀ i, (x (some i)).1 = (x none).1) : + (∀ t, ∑ i, degreeFromOrdered m L (some i) (x (some i)) t + = degreeFromOrdered m L none (x none) t) ↔ + ∑ i, (x (some i)).2.val = (x none).2.val := by + simp only [degreeFromOrdered, shifted, hp, offset, one_mul, sum_add_distrib, sum_const, card_univ, + smul_eq_mul, add_left_inj, ← cum_sum] + constructor + · intro h + apply cum_inj + funext t + simpa using h ((x none).1.symm t) + · intro h t + rw [h] + +variable (F : Type) [Field F] [Nonempty ι] + +private def bigFromOrdered (x : ∀ s, blockFromOrdered m L s) := + if ∀ t, ∑ i, degreeFromOrdered m L (some i) (x (some i)) t = degreeFromOrdered m L none (x none) t + then (1 : F) else 0 + +private def gradingFromOrdered (s : Option ι) (x : blockFromOrdered m L s) := + let w := variation (fun t => degreeFromOrdered m L s x t) + if s.isNone then -w else w + +private theorem grading_ruleFromOrdered (x : ∀ s, + blockFromOrdered m L s) (hx : bigFromOrdered m L F x ≠ 0) : + 0 ≤ ∑ s, gradingFromOrdered m L s (x s) ∧ + ((∑ s, gradingFromOrdered m L s (x s)) = 0 ↔ ∀ i, (x (some i)).1 = (x none).1) := by + have he : ∀ t, ∑ i, degreeFromOrdered m L (some i) (x (some i)) t + = degreeFromOrdered m L none (x none) t := by + simpa [bigFromOrdered] using hx + let d (s) (t) : ℤ := degreeFromOrdered m L s (x s) t + have hd s u v : d s u < d s v ↔ (x s).1 u < (x s).1 v := by + simp only [d, Nat.cast_lt, degreeFromOrdered, (shifted_mono _ (offset_pos s)).lt_iff_lt] + have hw := variation_rule (fun s => (x s).1) d hd (fun t => by + unfold d; exact_mod_cast he t) + simpa [Fintype.sum_option, gradingFromOrdered, d, neg_add_eq_zero, le_add_iff_nonneg_left] + using hw + +private theorem big_le : Profile.array (bigFromOrdered m L F) ≤ (Profile.polynomial F (fun i => L i + + m)) ^ m := by + rw [Profile.polynomial, ← table_pow] + refine Raw.Restricts.pullback (embed m L) fun x => ?_ + change (∀ s, blockFromOrdered m L s) at x + erw [Raw.coeff_ofTable, Raw.coeff_ofTable] + unfold copyTable Profile.entry + rw [Fintype.prod_ite_zero, prod_const_one] + unfold bigFromOrdered + congr + +private theorem graded_simplex : + Profile.array (Profile.grade (gradingFromOrdered m L) (bigFromOrdered m L F)) = + (m.factorial : Tensor F (Option ι)) * simplex F m L := by + have he := Profile.grade_labels (gradingFromOrdered m L) (bigFromOrdered m L F) (entry F m L) + (fun x hx => (grading_ruleFromOrdered m L F x hx).2) (by + intro x hp + simp only [bigFromOrdered, entry, agree m L x hp]) + rw [Fintype.card_perm, Fintype.card_fin] at he + exact he + +variable {F m} + +/-- Each of the `m!` orderings contributes a disjoint simplex at grade zero. -/ +theorem simplex_le [Infinite F] (L : ι → ℕ) + (f : Tensor F (Option ι) →+* NNReal) (hf : Monotone f) : + m.factorial * f (simplex F m L) ≤ f (Profile.polynomial F (fun i => L i + m)) ^ m := by + classical + have h := Profile.grade_price f hf (bigFromOrdered m L F) (gradingFromOrdered m L) + (fun x hx => (grading_ruleFromOrdered m L F x hx).1) + rw [graded_simplex, map_mul, map_natCast] at h + rw [← map_pow] + exact h.trans (hf (big_le m L F)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- # Independent groups of polynomial variables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Finset + +variable {ι : Type} [Fintype ι] (K : Type) [Field K] + +theorem simplex_ne_zero (m : ℕ) (L : ι → ℕ) : simplex K m L ≠ 0 := by + intro h + let x (s : Option ι) : leg m L s := ⟨0, by simp⟩ + have he := (Tensor.ofRaw_eq_zero _).mp h x + rw [Raw.coeff_ofTable] at he + simp [entry, x] at he + +theorem simplex_pos (m : ℕ) (L : ι → ℕ) (f : Tensor K (Option ι) →+* NNReal) (hf : Monotone f) : + 0 < (f (simplex K m L) : ℝ) := by + have hh := hf (Tensor.one_le _ (simplex_ne_zero K m L)) + rw [map_one] at hh + exact_mod_cast zero_lt_one.trans_le hh + +private def concat (n m : ℕ) (L : ι → ℕ) (s : Option ι) (x : Fin n → leg m L s) : + leg (n * m) (fun i => n * L i) s := by + refine ⟨fun i => (x (finProdFinEquiv.symm i).1).val (finProdFinEquiv.symm i).2, ?_⟩ + rw [← finProdFinEquiv.sum_comp, Fintype.sum_prod_type] + simp only [Equiv.symm_apply_apply] + have h := sum_le_sum (s := univ) (fun i _ => (x i).property) + have he : Profile.length (fun i => n * L i) s = n * Profile.length L s := by + cases s <;> simp [Profile.length, mul_sum] + simpa [he] using h + +theorem simplex_pow (m n : ℕ) (L : ι → ℕ) : + (simplex K m L) ^ n ≤ simplex K (n * m) (fun i => n * L i) := by + classical + unfold simplex + rw [← table_pow] + refine Raw.Restricts.pullback (concat n m L) fun x => ?_ + change (∀ s, Fin n → leg m L s) at x + erw [Raw.coeff_ofTable, Raw.coeff_ofTable] + unfold copyTable entry + rw [Fintype.prod_ite_zero, prod_const_one] + congr 1 + apply propext + simp only [funext_iff, Finset.sum_apply, concat] + constructor + · intro h i; exact h _ _ + · intro h i j + simpa only [Equiv.symm_apply_apply] using h (finProdFinEquiv (i, j)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- +# Degree energy and its upper bound at small costs + +Use total-degree budgets in `m` variables. A common slack variable +homogenizes each input and the output without changing the tensor. +The ordering degeneration gives the upper bound directly, uniformly +in the number of variables. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Energy Set Finset +open scoped Topology + +variable {ι K : Type} [Fintype ι] [Field K] + +/-- The sum of `s i * L i` indexed by `i`. -/ +def penalty (s : ι → ℝ) (L : ι → ℕ) := ∑ i, s i * L i + +/-- The quantity computed by `{a | ∃ m : ℕ, 0 < m ∧ ∃ L, a = (H m L - penalty s L) / m}`. -/ +def scores (H : ℕ → (ι → ℕ) → ℝ) (s : ι → ℝ) : Set ℝ := + {a | ∃ m : ℕ, 0 < m ∧ ∃ L, a = (H m L - penalty s L) / m} + +/-- The supremum of `(scores H s)`. -/ +def degree (H : ℕ → (ι → ℕ) → ℝ) (s : ι → ℝ) := sSup (scores H s) + +theorem scores_nonempty (H : ℕ → (ι → ℕ) → ℝ) (s : ι → ℝ) : (scores H s).Nonempty := + ⟨_, 1, by decide, 0, rfl⟩ + +variable [Nonempty ι] [DecidableEq ι] [Infinite K] + +/-- The quantity computed by `d * Real.log (f (simplex K m L))`. -/ +def degrees (f : Tensor K (Option ι) →+* NNReal) (d : ℝ) (m : ℕ) (L : ι → ℕ) := + d * Real.log (f (simplex K m L)) + +/-- The quantity computed by `d * Real.log (Profile.profile f x)`. -/ +def widths (f : Tensor K (Option ι) →+* NNReal) (d : ℝ) (x : ι → ℝ) := + d * Real.log (Profile.profile f x) + +variable {f : Tensor K (Option ι) →+* NNReal} (hf : Monotone f) {d N : ℝ} + (hd : 0 < d) {s : ι → ℝ} (hs : ∀ i, 0 < s i) +include hf hd hs + +omit [DecidableEq ι] in +theorem widths_le {x : ι → ℝ} (hx : ∀ i, 0 < x i) : + d + widths f d x - cost s x ≤ variational (widths f d) d s := by + classical + refine le_csSup ?_ ⟨x, hx, rfl⟩ + obtain ⟨j, _, hm⟩ := Finset.exists_min_image univ s univ_nonempty + refine ⟨d * Real.log (d / s j), ?_⟩ + rintro _ ⟨y, hy, rfl⟩ + have hc : s j * ∑ i, y i ≤ cost s y := by + rw [cost, Finset.mul_sum] + exact sum_le_sum (fun i _ => mul_le_mul_of_nonneg_right (hm _ (mem_univ i)) (hy i).le) + have hp : 0 < ∑ i, y i := sum_pos (fun i _ => hy i) univ_nonempty + have hh := Real.log_le_log (Profile.profile_pos hf hy) ((Profile.scaling_polynomial f + hf).scale_bound hy) + change d + d * Real.log (Profile.profile f y) - _ ≤ _ + linarith only [hc, mul_le_mul_of_nonneg_left hh hd.le, log_max hd (hs j) hp] + +omit [DecidableEq ι] in +theorem scores_upper (hN : 0 < N) : + d * Real.log N + variational (widths f d) d s + 2 * (∑ i, s i) / N ∈ + upperBounds (scores (degrees f d) (fun i => s i / N)) := by + classical + rintro _ ⟨m, hm, L, rfl⟩ + have hm' : 0 < (m : ℝ) := by positivity + let M := fun i => L i + m + let x := fun i => ((L i : ℝ) + 2 * m) / (m * N) + have hx (i) : 0 < x i := by unfold x; positivity + let y := Profile.profile f x + have hy : 0 < y := Profile.profile_pos hf hx + have hscale : (f (Profile.polynomial K M) : ℝ) ≤ (m * N) * y := by + apply (inv_mul_le_iff₀ (mul_pos hm' hN)).mp + apply (Profile.scaling_polynomial f hf).le_scale (by positivity) + intro i + unfold x M + rw [inv_mul_eq_div, Nat.cast_add, div_lt_div_iff_of_pos_right (mul_pos hm' hN)] + linarith + have ht := simplex_le (m := m) L f hf + have hfac : 0 < (m.factorial : ℝ) := by positivity + have hp := simplex_pos K m L f hf + have hh : (m.factorial : ℝ) * f (simplex K m L) ≤ ((m * N) * y) ^ m := by + refine le_trans ?_ (pow_le_pow_left₀ (by positivity) hscale _) + exact_mod_cast ht + have he := Real.log_le_log (mul_pos hfac hp) hh + rw [Real.log_mul hfac.ne' hp.ne', Real.log_pow, Real.log_mul (by positivity) hy.ne', + Real.log_mul hm'.ne' hN.ne'] at he + have hc : Real.log m - Real.log m.factorial / m ≤ 1 := correction_le m + have hv : degrees f d m L / m ≤ d * (Real.log N + Real.log y + 1) := by + unfold degrees + rw [mul_div_assoc] + apply mul_le_mul_of_nonneg_left _ hd.le + have hh := (div_le_iff₀ hm').mpr (he.trans_eq (mul_comm _ _)) + rw [add_div] at hh + linarith only [hh, hc] + have hpen : penalty (fun i => s i / N) L / m + 2 * (∑ i, s i) / N = cost s x := by + unfold penalty cost x + rw [Finset.mul_sum, Finset.sum_div, Finset.sum_div, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + field_simp + have hu := widths_le hf hd hs hx + change d + d * Real.log y - cost s x ≤ _ at hu + rw [sub_div] + linarith only [hu, hpen, hv] + +omit [DecidableEq ι] in +theorem bounded_scores : BddAbove (scores (degrees f d) s) := by + classical + have hh := scores_upper hf hd hs zero_lt_one + simp only [div_one] at hh + exact ⟨_, hh⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +section +/- +# The continuum limit of degree energy + +Fix a cube shape in the univariate supremum, then pack translated +copies inside a multivariate simplex. The strict slack in each +width pays for rounding the number of translates. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Energy Filter Set +open scoped Topology + +variable {ι K : Type} [Fintype ι] [Nonempty ι] [DecidableEq ι] [Field K] [Infinite K] + {f : Tensor K (Option ι) →+* NNReal} (hf : Monotone f) + {d : ℝ} (hd : 0 < d) {s : ι → ℝ} (hs : ∀ i, 0 < s i) + +include hf hd hs in +omit [DecidableEq ι] in +private theorem lower_cube {x : ι → ℝ} {c : ℝ} {L : ι → ℕ} + (hc : 0 < c) (hc' : 0 < c * f (Profile.polynomial K L)) + (hx : ∀ i, c * L i < x i) {m : ℕ} (hm : 0 < m) : + ∀ᶠ N : ℝ in atTop, + d * (Real.log (c * f (Profile.polynomial K L)) + correction m) - cost s x ≤ + degree (degrees f d) (fun i => s i / N) - d * Real.log N := by + classical + have hm' : 0 < (m : ℝ) := by positivity + let q (N : ℝ) := ⌈m * N * c⌉₊ + have hlarge : ∀ᶠ N : ℝ in atTop, ∀ i, ((q N : ℝ) + m) * L i ≤ (m * N) * x i := by + apply eventually_all.mpr + intro i + have hi := sub_pos.mpr (hx i) + filter_upwards [eventually_gt_atTop 0, eventually_ge_atTop (((1 + + m) * L i) / (m * (x i - c * L i)))] + with N hN hN' + have hq : (q N : ℝ) ≤ m * N * c + 1 := (Nat.ceil_lt_add_one (by positivity)).le + linarith only [mul_le_mul_of_nonneg_right hq (Nat.cast_nonneg (L i)), + (div_le_iff₀ (mul_pos hm' hi)).mp hN'] + filter_upwards [eventually_gt_atTop 0, hlarge] with N hN hsize + let A := fun i => (q N + m) * L i + let y := c * (f (Profile.polynomial K L) : ℝ) + have hy : 0 < y := hc' + have hw : ((m * N) * y) ^ m ≤ m.factorial * (f (simplex K m A) : ℝ) := by + refine le_trans ?_ (cubes_le K m (q N) L f hf) + apply pow_le_pow_left₀ (by positivity) + unfold y + rw [← mul_assoc] + exact mul_le_mul_of_nonneg_right (Nat.le_ceil _) (by positivity) + have hv := Real.log_le_log (by positivity) hw + rw [Real.log_pow, Real.log_mul (by positivity) hy.ne', Real.log_mul hm'.ne' hN.ne', + Real.log_mul (by positivity) (simplex_pos K m A f hf).ne'] at hv + have he : d * (Real.log N + Real.log y + correction m) ≤ degrees f d m A / m := by + rw [degrees, mul_div_assoc] + apply mul_le_mul_of_nonneg_left _ hd.le + have he := (le_div_iff₀ hm').mpr ((mul_comm _ _).trans_le hv) + rw [add_div] at he + unfold correction + linarith only [he] + have hcost : penalty (fun i => s i / N) A / m ≤ cost s x := by + unfold penalty cost + rw [Finset.sum_div] + apply Finset.sum_le_sum + intro i _ + change s i / N * ((q N + m) * L i : ℕ) / m ≤ _ + rw [Nat.cast_mul, Nat.cast_add, div_mul_eq_mul_div, div_div, div_le_iff₀ (mul_pos hN hm')] + linarith only [mul_le_mul_of_nonneg_left (hsize i) (hs i).le] + have hb := bounded_scores hf hd (s := fun i => s i / N) (fun i => div_pos (hs i) hN) + have hh : (degrees f d m A - penalty (fun i => s i / N) A) / m ≤ + degree (degrees f d) (fun i => s i / N) := le_csSup hb ⟨m, hm, A, rfl⟩ + rw [sub_div] at hh + change d * (Real.log y + correction m) - _ ≤ _ + linarith only [he, hcost, hh] + +include hf hd hs in +omit [DecidableEq ι] in +theorem degree_limit : + Tendsto (fun N : ℝ => degree (degrees f d) (fun i => s i / N) - d * Real.log N) atTop + (𝓝 (variational (widths f d) d s)) := by + classical + apply tendsto_order.mpr + constructor + · intro t ht + obtain ⟨_, ⟨x, hx, rfl⟩, hx'⟩ := exists_lt_of_lt_csSup + (show ((fun x => d + widths f d x - cost s x) '' {x | ∀ i, 0 < x i}).Nonempty from + ⟨_, fun _ => 1, fun _ => zero_lt_one, rfl⟩) ht + have hc : Tendsto (fun m => d * (Real.log (Profile.profile f x) + correction m) - cost s x) + atTop (𝓝 (d + widths f d x - cost s x)) := by + convert ((correction_limit.const_add _).const_mul d).sub_const (cost s x) using 1 + unfold widths + ring_nf + obtain ⟨m, hm, hval⟩ := ((eventually_gt_atTop 0).and (hc.eventually_const_lt hx')).exists + let y := (t + cost s x) / d - correction m + have hy : Real.exp y < Profile.profile f x := by + apply (Real.lt_log_iff_exp_lt (Profile.profile_pos hf hx)).mp + unfold y + rw [sub_lt_iff_lt_add, div_lt_iff₀ hd] + linarith only [hval] + unfold Profile.profile Profile.scale at hy + obtain ⟨_, ⟨L, c, hc', hL, rfl⟩, hhigh⟩ := + exists_lt_of_lt_csSup (by exact ⟨_, 0, 1, zero_lt_one, by simpa using hx, rfl⟩) hy + have h' := (Real.exp_pos _).trans hhigh + have hh := (Real.lt_log_iff_exp_lt h').mpr hhigh + unfold y at hh + rw [sub_lt_iff_lt_add, div_lt_iff₀ hd] at hh + filter_upwards [lower_cube hf hd hs hc' h' hL hm] with N hN + linarith only [hh, hN] + · intro t ht + have hc : Tendsto (fun N : ℝ => 2 * (∑ i, s i) / N) atTop (𝓝 0) := + tendsto_const_nhds.div_atTop tendsto_id + filter_upwards [eventually_gt_atTop 0, hc.eventually_lt_const (sub_pos.mpr ht)] with N hN hN' + have he := csSup_le (scores_nonempty _ _) (scores_upper hf hd hs hN) + unfold degree + linarith only [he, hN'] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- # Degree and width energy at a fixed finite placement -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral Filter +open scoped Topology + +variable {ι K : Type} [Fintype ι] [DecidableEq ι] [Nonempty ι] [Field K] + {X : Type*} [PseudoMetricSpace X] (A : MatrixExponent.Prices.Atlas K X) (o : X) (x : ι → X) + +theorem H_eq : H A o x = degrees (Profile.point A (sites o x)) (A.price (sites o x) 2) := by + funext m L + exact Profile.price_eq A _ _ + +theorem H_pow (n m : ℕ) (L : ι → ℕ) : + n * H A o x m L ≤ H A o x (n * m) (fun i => n * L i) := by + let f := Profile.point A (sites o x) + have hf := Profile.point_mono A (sites o x) + have h := hf (simplex_pow K m n L) + rw [map_pow] at h + have hp : (f (simplex K m L) : ℝ) ^ n ≤ f (simplex K (n * m) (fun i => n * L i)) := by + exact_mod_cast h + have h' := Real.log_le_log (pow_pos (simplex_pos K m L f hf) _) hp + rw [Real.log_pow] at h' + rw [H_eq, degrees, degrees, mul_left_comm] + exact mul_le_mul_of_nonneg_left h' (A.nonnegative _ _) + +/-- The construction uses `A.price (sites o x) 2` for its intermediate `d`. -/ +def Q (s : ι → ℝ) := + let d := A.price (sites o x) 2 + Energy.variational (widths (Profile.point A (sites o x)) d) d s + +theorem H_limit [Infinite K] (hd : 0 < A.price (sites o x) 2) + (s : ι → ℝ) (hs : ∀ i, 0 < s i) : + Tendsto (fun N : ℝ => degree (H A o x) (fun i => s i / N) - A.price (sites o x) 2 * Real.log N) + atTop (𝓝 (Q A o x s)) := by + rw [H_eq] + exact degree_limit (Profile.point_mono A _) hd hs + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +section +/- +# Increasing returns from substitution in two groups of variables + +Tensor the two test products up to the same number of variables. The +sector expansion loses only a logarithmic cost, which disappears under +further joint powering. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Finset + +variable {ι : Type} [Fintype ι] {H : ℕ → (ι → ℕ) → ℝ} + {f : ι → ℝ} {s a b C : ℝ} {L R : ι → ℕ} + +theorem penalty_mul (f : ι → ℝ) (L : ι → ℕ) (n : ℕ) : + penalty f (fun i => n * L i) = n * penalty f L := by + simp only [penalty, Nat.cast_mul, mul_sum] + exact sum_congr rfl (fun _ _ => by ring) + +private theorem penalty_add (L R : ι → ℕ) (f : ι → ℝ) (s : ℝ) : + penalty f L + penalty (fun i => f i + s) R = penalty f (L + R) + s * (∑ i, R i : ℕ) := by + simp only [penalty, Pi.add_apply, Nat.cast_add, Nat.cast_sum, mul_sum, ← sum_add_distrib] + exact sum_congr rfl (fun _ _ => by ring) + +private theorem absorb_log {A B C D : ℝ} (hC : 0 ≤ C) (hD : 0 ≤ D) + (h : ∀ n : ℕ, 0 < n → n * A ≤ n * B + C * Real.log (1 + n * D)) : A ≤ B := by + apply Real.exp_le_exp.mp + apply TensorSpectrum.le_of_pow_le_polynomial_mul_pow _ _ ((1 + D) ^ C) C + (by positivity) (by positivity) + intro n hn + rw [← Real.mul_rpow (by positivity) (by positivity), Real.rpow_def_of_pos (by positivity), + ← Real.exp_nat_mul, ← Real.exp_nat_mul, ← Real.exp_add, Real.exp_le_exp] + have he := Real.log_le_log (by positivity : 0 < 1 + (n : ℝ) * D) + (show 1 + (n : ℝ) * D ≤ (1 + D) * (n + 1) by linarith) + linarith only [h n hn, mul_le_mul_of_nonneg_left he hC] + +/-- Log-price comparison with a polynomial number of degree sectors. -/ +def Sectors (H : ℕ → (ι → ℕ) → ℝ) (S : Finset ι) (C : ℝ) : Prop := + ∀ m : ℕ, 0 < m → ∀ L R : ι → ℕ, (∀ i ∈ S, L i = 0) → + ∃ U V : ι → ℕ, U + V = L + R ∧ (∀ i ∈ S, V i = 0) ∧ (∑ i, V i) ≤ ∑ i, R i ∧ + H m L + H m R ≤ H m U + H m V + C * Real.log (1 + (∑ i, (L i + R i) : ℕ)) + +theorem increase {S : Finset ι} (hC : 0 ≤ C) (hs : 0 ≤ s) + (hpow : ∀ n m L, (n : ℕ) * H m L ≤ H (n * m) (fun i => n * L i)) + (hsec : Sectors H S C) + (ha : ∀ m : ℕ, 0 < m → ∀ L, H m L - penalty f L ≤ m * a) + (hb : ∀ m : ℕ, 0 < m → ∀ R, (∀ i ∈ S, R i = 0) → H m R - penalty (fun i => f i + s) R ≤ m * b) + {m n : ℕ} (hm : 0 < m) (hn : 0 < n) (hL : ∀ i ∈ S, L i = 0) : + (H m L - penalty f L) / m + (H n R - penalty (fun i => f i + s) R) / n ≤ a + b := by + let g i := f i + s + have same (m : ℕ) (hm : 0 < m) (L R : ι → ℕ) (hL : ∀ i ∈ S, L i = 0) : + H m L - penalty f L + (H m R - penalty g R) ≤ m * (a + b) := by + apply absorb_log (D := (∑ i, (L i + R i) : ℕ)) hC (by positivity) + intro t ht + let U i := t * L i + let V i := t * R i + have h₀ : ∀ i ∈ S, U i = 0 := by intro i hi; simp [U, hL i hi] + obtain ⟨X, Y, he, hY, hv, hh⟩ := hsec (t * m) (Nat.mul_pos ht hm) U V h₀ + have hp : penalty f X + penalty g Y ≤ penalty f U + penalty g V := by + unfold g + rw [penalty_add, penalty_add, he] + gcongr + have hmass : ∑ i, (U i + V i) = t * ∑ i, (L i + R i) := by simp [U, V, mul_sum, mul_add] + rw [hmass, Nat.cast_mul] at hh + rw [show penalty f U = t * penalty f L from penalty_mul _ _ _, + show penalty g V = t * penalty g R from penalty_mul _ _ _] at hp + have ha' := ha (t * m) (Nat.mul_pos ht hm) X + have hb' := hb (t * m) (Nat.mul_pos ht hm) Y hY + rw [Nat.cast_mul] at ha' hb' + have hu : (t : ℝ) * H m L ≤ H (t * m) U := hpow _ _ _ + have hv : (t : ℝ) * H m R ≤ H (t * m) V := hpow _ _ _ + change H (t * m) Y - penalty g Y ≤ _ at hb' + linarith only [hh, hp, ha', hb', hu, hv] + have he := same (n * m) (Nat.mul_pos hn hm) (fun i => n * L i) (fun i => m * R i) + (by intro i hi; simp [hL i hi]) + have hr := hpow m n R + rw [Nat.mul_comm m n] at hr + rw [penalty_mul, penalty_mul, Nat.cast_mul] at he + change _ + (H n R - penalty g R) / n ≤ a + b + field_simp + linarith only [he, hpow n m L, hr] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +section +/- # The cost of a polynomial number of bidegree sectors -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Spectral + +variable {ι K : Type} [Fintype ι] [DecidableEq ι] [Nonempty ι] [Field K] + {X : Type*} [PseudoMetricSpace X] (A : MatrixExponent.Prices.Atlas K X) (o : X) (x : ι → X) + +theorem H_sectors (S : Finset ι) : + ∃ C : ℝ, 0 ≤ C ∧ Sectors (H A o x) S C := by + let d := A.price (sites o x) 2 + let f := Profile.point A (sites o x) + have hf : Monotone f := Profile.point_mono A _ + have hd : 0 ≤ d := A.nonnegative _ _ + refine ⟨d * Fintype.card ι, by positivity, ?_⟩ + intro m _ L R hL + obtain ⟨U, V, he, hv, ht, h⟩ := sector (m := m) L R S hL f hf + refine ⟨U, V, he, hv, ht, ?_⟩ + let y (L : ι → ℕ) : ℝ := f (simplex K m L) + let t : ℕ := 1 + ∑ i, (L i + R i) + have hp L : 0 < y L := simplex_pos K m L f hf + have ht : 0 < (t : ℝ) := by unfold t; positivity + have he : y L * y R ≤ (t : ℝ) ^ Fintype.card ι * y U * y V := by + exact_mod_cast h + have hl := Real.log_le_log (mul_pos (hp _) (hp _)) he + rw [Real.log_mul (hp _).ne' (hp _).ne', Real.log_mul (mul_pos (pow_pos ht _) (hp _)).ne' + (hp _).ne', Real.log_mul (pow_pos ht _).ne' (hp _).ne', Real.log_pow] at hl + rw [H_eq, ← Nat.cast_one (R := ℝ), ← Nat.cast_add] + change d * Real.log (y L) + d * Real.log (y R) ≤ d * Real.log (y U) + d * Real.log (y V) + + d * Fintype.card ι * Real.log t + linarith only [mul_le_mul_of_nonneg_left hl hd] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +/- +# Radial comparison of degree-energy differences + +In the mixed placement one test uses only inner inputs and one uses +only outer inputs. Increasing returns compares these two tests to an +unrestricted test and a shifted inner test. The former contracts onto +the outer sites. The latter discards zero-degree inputs. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Finset + +variable {K ι : Type} [Field K] [Fintype ι] [DecidableEq ι] [Nonempty ι] + {X : Type*} [PseudoMetricSpace X] (A : MatrixExponent.Prices.Atlas K X) (o : X) + +private theorem test_le_degree [Infinite K] (x : ι → X) (f : ι → ℝ) + (hd : 0 < A.price (sites o x) 2) (hf : ∀ i, 0 < f i) (m : ℕ) (hm : 0 < m) (L : ι → ℕ) : + H A o x m L - penalty f L ≤ m * degree (H A o x) f := by + have hb : BddAbove (scores (H A o x) f) := by + rw [H_eq] + exact bounded_scores (Profile.point_mono _ _) hd hf + rw [mul_comm, ← div_le_iff₀ (by positivity : (0 : ℝ) < m)] + exact le_csSup hb ⟨m, hm, L, rfl⟩ + +private theorem add_sups {s t : Set ℝ} {C : ℝ} (hs : s.Nonempty) (ht : t.Nonempty) + (h : ∀ a ∈ s, ∀ b ∈ t, a + b ≤ C) : sSup s + sSup t ≤ C := by + rw [← le_sub_iff_add_le] + apply csSup_le hs + intro a ha + rw [le_sub_iff_add_le, ← le_sub_iff_add_le'] + exact csSup_le ht (fun b hb => le_sub_iff_add_le'.mpr (h a ha b hb)) + +theorem degree_contract [Infinite K] (x y : ι → X) (f g t : ι → ℝ) + (ht : ∀ i, 0 ≤ t i) (ht' : ∀ i, t i ≤ 1) + (h₁ : ∀ i, Dist.dist o (y i) = t i * Dist.dist o (x i)) + (h₂ : ∀ i, Dist.dist (y i) (x i) = (1 - t i) * Dist.dist o (x i)) + (hg : ∀ i, t i * f i ≤ g i) (hf₀ : ∀ i, 0 < f i) (hg₀ : ∀ i, 0 < g i) + (hx : 0 < A.price (sites o x) 2) (hy : 0 < A.price (sites o y) 2) {s : ℝ} (hs : 0 ≤ s) : + degree (H A o y) g - degree (H A o y) (fun i => g i + s) ≤ + degree (H A o x) f - degree (H A o x) (fun i => f i + s) := by + let M := H A o (Sum.elim x y) + let S : Finset (ι ⊕ ι) := univ.image Sum.inl + obtain ⟨C, hC, hsec⟩ := H_sectors A o (Sum.elim x y) S + have hpow := H_pow A o (Sum.elim x y) + let c := Sum.elim f g + let a := degree (H A o x) f + let b := degree (H A o y) (fun i => g i + s) + have ha (m : ℕ) (hm : 0 < m) (L : ι ⊕ ι → ℕ) : M m L - penalty c L ≤ m * a := by + obtain ⟨R, hR⟩ := contract A o x y f g t ht ht' h₁ h₂ hg m L + exact hR.trans (test_le_degree A o x f hx hf₀ m hm R) + have hb (m : ℕ) (hm : 0 < m) (R : ι ⊕ ι → ℕ) (hR : ∀ i ∈ S, R i = 0) : + M m R - penalty (fun i => c i + s) R ≤ m * b := by + let V i := R (.inr i) + have he : R = Sum.elim (0 : ι → ℕ) V := by + funext i + rcases i with i | i + · exact hR (.inl i) (by simp [S]) + · rfl + rw [he, show M m (Sum.elim 0 V) = H A o y m V from right_H m V A o x y] + have hh := test_le_degree A o y (fun i => g i + s) hy (fun i + => add_pos_of_pos_of_nonneg (hg₀ i) hs) m hm V + simpa [penalty, c, b, Fintype.sum_sum_type] using hh + have he : degree (H A o y) g + degree (H A o x) (fun i => f i + s) ≤ a + b := by + apply add_sups (scores_nonempty _ _) (scores_nonempty _ _) + rintro _ ⟨m, hm, L, rfl⟩ _ ⟨n, hn, R, rfl⟩ + have hL : ∀ i ∈ S, Sum.elim (0 : ι → ℕ) L i = 0 := by + intro i hi + obtain ⟨j, _, rfl⟩ := mem_image.mp hi + rfl + have hh := increase hC hs hpow hsec ha hb (R := Sum.elim R 0) hm hn hL + simpa [M, right_H, left_H, penalty, c, Fintype.sum_sum_type] using hh + unfold a b at he + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end + +section +/- # Radial contraction of width energy at finite placements -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +open Filter +open scoped Topology + +variable {ι K : Type} [Fintype ι] [DecidableEq ι] [Nonempty ι] [Field K] [Infinite K] + {X : Type*} [PseudoMetricSpace X] (A : MatrixExponent.Prices.Atlas K X) (o : X) + +theorem Q_contract (x y : ι → X) (f g t : ι → ℝ) + (ht : ∀ i, 0 ≤ t i) (ht' : ∀ i, t i ≤ 1) + (h₁ : ∀ i, Dist.dist o (y i) = t i * Dist.dist o (x i)) + (h₂ : ∀ i, Dist.dist (y i) (x i) = (1 - t i) * Dist.dist o (x i)) + (hg : ∀ i, t i * f i ≤ g i) (hf₀ : ∀ i, 0 < f i) (hg₀ : ∀ i, 0 < g i) + (hx : 0 < A.price (sites o x) 2) (hy : 0 < A.price (sites o y) 2) {s : ℝ} (hs : 0 ≤ s) : + Q A o y g - Q A o y (fun i => g i + s) ≤ Q A o x f - Q A o x (fun i => f i + s) := by + have hl := (H_limit A o y hy g hg₀).sub + (H_limit A o y hy _ (fun i => add_pos_of_pos_of_nonneg (hg₀ i) hs)) + have hu := (H_limit A o x hx f hf₀).sub + (H_limit A o x hx _ (fun i => add_pos_of_pos_of_nonneg (hf₀ i) hs)) + refine le_of_tendsto_of_tendsto hl hu ?_ + filter_upwards [eventually_gt_atTop 0] with N hN + have hp (i) : t i * (f i / N) ≤ g i / N := by + rw [← mul_div_assoc]; exact div_le_div_of_nonneg_right (hg i) hN.le + have h := degree_contract A o x y _ _ t ht ht' h₁ h₂ hp (fun i => div_pos (hf₀ i) hN) + (fun i => div_pos (hg₀ i) hN) hx hy (div_nonneg hs hN.le) + simp only [← add_div] at h + linarith only [h] + +theorem Q_scale (x : ι → X) (f : ι → ℝ) (hf : ∀ i, 0 < f i) + (hx : 0 < A.price (sites o x) 2) {r : ℝ} (hr : 0 < r) : + Q A o x (fun i => r * f i) = Q A o x f - A.price (sites o x) 2 * Real.log r := by + have he := H_limit A o x hx _ (fun i => mul_pos hr (hf i)) + have h := (H_limit A o x hx f hf).comp (tendsto_id.atTop_div_const hr) + refine tendsto_nhds_unique he ((h.sub_const _).congr' ?_) + filter_upwards [eventually_gt_atTop 0] with N hN + simp only [Function.comp_apply, id_eq] + rw [Real.log_div hN.ne' hr.ne', show (fun i => f i / (N / r)) = (fun i => r * f i / N) by + ext i; field_simp] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Multi +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Poly.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Poly.lean new file mode 100644 index 0000000000..a499e062ed --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Poly.lean @@ -0,0 +1,50 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Tag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.PolynomialDegeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.PolynomialValues +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagPolynomialBranches +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.PermutationPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weighted +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialGrowth + +/-! +# The weighted growth bound for actual tensor characters + +Use the optimized tag inequality on the determinant and tripling +degenerations for each leg permutation separately. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Upper Upper.TensorClass + +/-- The character value of convolution with positive input lengths. -/ +abbrev poly (f : Character) (m n : ℕ) : ℝ := + TensorSpectrum.PolynomialGrowth.poly f m n + +theorem poly_row (f : Character) (hp : 0 < f.pX) (m : ℕ) : + Row (fun n => poly f m n ^ (1 / f.pX)) + (fun n => (f (swapYZ (ofTensor (polynomialTensor (m + 1) (n + 1)))) : ℝ) ^ (1 / f.pX)) m := + TensorSpectrum.PolynomialGrowth.poly_row + Character.polynomial_value_pos + Character.shared_tag_optimized_of_pos + Character.determinant_graded_le Character.tripling_graded_le f hp m + +theorem character_bound (f : Character) (A B C : ℕ) (hA : 0 < A) (hB : 0 < B) (hC : 0 < C) : + 4 * (f.pX * B * C + f.pY * A * C + f.pZ * A * B) ≤ ((A : ℝ) + B + C) ^ 2 := + TensorSpectrum.PolynomialGrowth.character_bound + Character.polynomial_value_pos + Character.shared_tag_optimized_of_pos + Character.determinant_graded_le Character.tripling_graded_le + Character.polynomial_value_le f A B C hA hB hC + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Arms.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Arms.lean new file mode 100644 index 0000000000..3917d4958a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Arms.lean @@ -0,0 +1,418 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Face.Contact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Chord + +/-! # Critical widths for a tripod with positive arms -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Minimum + +/-- The sum of `v i` indexed by `i`. -/ +def mass (v : Vec) := ∑ i, v i + +/-- The quantity computed by `1 - v i / mass v`. -/ +def criticalWidth (v : Vec) (i : Fin 3) := 1 - v i / mass v + +/-- The quantity computed by `mass v⁻¹ - (v i)⁻¹`. -/ +def opposite (v : Vec) (i : Fin 3) := mass v⁻¹ - (v i)⁻¹ + +/-- The quantity computed by `D v⁻¹ - opposite v i`. -/ +def residual (D : Vec → ℝ) (v : Vec) (i : Fin 3) := D v⁻¹ - opposite v i + +variable {v : Vec} {i j k : Fin 3} + +theorem mass_pos (hv : Positive v) : 0 < mass v := + Finset.sum_pos (fun i _ => hv i) Finset.univ_nonempty + +theorem mass_eq (v : Vec) (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + mass v = v i + v j + v k := by + have he : {i, j, k} = (Finset.univ : Finset (Fin 3)) := by + apply Finset.eq_univ_of_card + simp [hij, hik, hjk] + simp [mass, ← he, hij, hik, hjk, add_assoc] + +theorem critical_pos (hv : Positive v) : Positive (criticalWidth v) := by + intro i + apply sub_pos.mpr + apply (div_lt_one (mass_pos hv)).mpr + rw [mass_eq v (i := i) (j := i + 1) (k := i + 2) (by omega) (by omega) (by omega)] + linarith [hv (i + 1), hv (i + 2)] + +theorem critical_le (hv : Positive v) (i : Fin 3) : criticalWidth v i ≤ 1 := + sub_le_self _ (div_nonneg (hv i).le (mass_pos hv).le) + +theorem critical_sum (hv : Positive v) (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + criticalWidth v i + criticalWidth v j + criticalWidth v k = 2 := by + have hm := (mass_pos hv).ne' + unfold criticalWidth + field_simp + rw [mass_eq v hij hik hjk] + ring + +theorem opposite_eq (v : Vec) (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + opposite v i = (v j)⁻¹ + (v k)⁻¹ := by + rw [opposite, mass_eq v⁻¹ hij hik hjk] + simp only [Pi.inv_apply] + ring + +theorem opposite_pos (hv : Positive v) : Positive (opposite v) := by + intro i + rw [opposite_eq v (i := i) (j := i + 1) (k := i + 2) (by omega) (by omega) (by omega)] + exact add_pos (inv_pos.mpr (hv _)) (inv_pos.mpr (hv _)) + +theorem critical_pair (D : Vec → ℝ) (hv : Positive v) (hij : i ≠ j) : + D v⁻¹ = opposite v i * criticalWidth v j + opposite v j * criticalWidth v i + defect D v := by + obtain ⟨k, hik, hjk⟩ := other (i := i) (j := j) + have hi := hv i + have hj := hv j + have hk := hv k + change _ = _ + (D v⁻¹ - mass v⁻¹ + (mass v)⁻¹) + unfold opposite criticalWidth + rw [mass_eq v hij hik hjk, mass_eq v⁻¹ hij hik hjk] + simp only [Pi.inv_apply] + field_simp + ring + +theorem residual_eq (D : Vec → ℝ) (hv : Positive v) (i : Fin 3) : + residual D v i = (v i)⁻¹ * criticalWidth v i + defect D v := by + unfold residual opposite criticalWidth + change _ = _ + (D v⁻¹ - mass v⁻¹ + (mass v)⁻¹) + have hi := hv i + have hm := mass_pos hv + field_simp + ring + +theorem residual_bounds {F : Type} [Field F] {D : Vec → ℝ} (h : StarTripod F D) + (hv : Positive v) (i : Fin 3) : 0 < residual D v i ∧ residual D v i ≤ (v i)⁻¹ := by + constructor + · rw [residual_eq D hv i] + exact add_pos_of_pos_of_nonneg (mul_pos (inv_pos.mpr (hv i)) (critical_pos hv i)) + (h.toTripod.regular.nonneg _ hv) + · have he := h.star v⁻¹ (fun i => inv_pos.mpr (hv i)) + unfold residual opposite mass + linarith + +/-- Widths stay bounded below locally even towards a reciprocal face. -/ +theorem uniform_width (hv : Positive v) : ∃ ε : ℝ, 0 < ε ∧ ∀ w, Positive w → + w ≤ (2 : ℝ) • v → v 1 ≤ w 1 → v 2 ≤ w 2 → ∀ i, ε ≤ criticalWidth w i := by + let m := min (v 1) (v 2) + have hm : 0 < m := lt_min (hv 1) (hv 2) + have hv' := mass_pos hv + refine ⟨m / (2 * mass v), by positivity, ?_⟩ + intro w hw hbound h₁ h₂ i + have hw' := mass_pos hw + have ht : mass w ≤ 2 * mass v := by + unfold mass + rw [Finset.mul_sum] + exact Finset.sum_le_sum fun i _ => hbound i + have hi : m ≤ mass w - w i := by + rw [mass, Fin.sum_univ_three] + have h₁' : m ≤ w 1 := (min_le_left _ _).trans h₁ + have h₂' : m ≤ w 2 := (min_le_right _ _).trans h₂ + fin_cases i <;> simp <;> linarith [hw 0, hw 1, hw 2] + calc + _ ≤ m / mass w := div_le_div_of_nonneg_left hm.le hw' ht + _ ≤ (mass w - w i) / mass w := div_le_div_of_nonneg_right hi hw'.le + _ = criticalWidth w i := by rw [sub_div, div_self hw'.ne']; rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- A tripod of three rays with a common origin. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +/-- The data for the twig construction, including `arm`, `length`. -/ +structure Twig where + /-- The `Twig` component of type `Fin 3`. -/ + arm : Fin 3 + /-- The length of the indexed record carried by `Twig`, with type `ℝ`. -/ + length : ℝ + +namespace Twig +open Minimum Spectral + +/-- The maximum of the quantities in `x.length 0`. -/ +def radius (x : Twig) := max x.length 0 + +theorem radius_nonneg (x : Twig) : 0 ≤ x.radius := le_max_right _ _ + +/-- Returns `|x.radius - y.radius|` when `x.arm = y.arm` holds, and `x.radius + y.radius` +otherwise. -/ +def gap (x y : Twig) : ℝ := + if x.arm = y.arm then |x.radius - y.radius| else x.radius + y.radius + +instance : PseudoMetricSpace Twig where + dist := gap + dist_self x := by simp [gap] + dist_comm x y := by simp [gap, eq_comm, abs_sub_comm, add_comm] + dist_triangle x y z := by + have hx := x.radius_nonneg + have hy := y.radius_nonneg + have hz := z.radius_nonneg + unfold gap + grind [abs_sub_le, abs_sub_comm] + +theorem dist_eq (x y : Twig) : Dist.dist x y = + if x.arm = y.arm then |x.radius - y.radius| else x.radius + y.radius := rfl + +/-- Uses `⟨i, a i⟩` as the representation. -/ +def mark (a : Vec) (i : Fin 3) : Twig := ⟨i, a i⟩ +/-- Uses `⟨0, 0⟩` as the representation. -/ +def origin : Twig := ⟨0, 0⟩ +/-- The quantity computed by `⟨x.arm, s * x.length⟩`. -/ +def dilate (s : ℝ) (x : Twig) : Twig := ⟨x.arm, s * x.length⟩ + +theorem radius_dilate (s : ℝ) (hs : 0 ≤ s) (x : Twig) : (dilate s x).radius = s * x.radius := by + simp [radius, dilate, mul_max_of_nonneg _ _ hs] + +theorem dilate_dist (s : ℝ) (hs : 0 ≤ s) (x y : Twig) : + Dist.dist (dilate s x) (dilate s y) = s * Dist.dist x y := by + simp only [dist_eq, radius_dilate _ hs, mul_ite, ← mul_sub, abs_mul, abs_of_nonneg hs, ← mul_add] + rfl + +@[simp] theorem origin_dist (x : Twig) : Dist.dist origin x = x.radius := by + rw [dist_eq] + simp only [show origin.radius = 0 by simp [origin, radius], zero_sub, zero_add, abs_neg, + abs_of_nonneg x.radius_nonneg, ite_self] + +theorem radial_dist (s t : ℝ) (hs : 0 ≤ s) (ht : 0 ≤ t) (x : Twig) : + Dist.dist (dilate s x) (dilate t x) = |s - t| * x.radius := by + rw [dist_eq, ite_eq_left (by rfl), radius_dilate s hs, radius_dilate t ht, ← sub_mul, + abs_mul, abs_of_nonneg x.radius_nonneg] + +theorem mark_dist {x y : Vec} (hx : Positive x) (hy : Positive y) (i j : Fin 3) : + Dist.dist (mark x i) (mark y j) = if i = j then |x i - y j| else x i + y j := by + simp [dist_eq, mark, radius, (hx i).le, (hy j).le] + +variable {F : Type} [Field F] + +/-- Computes the label by the application `A.price (mark x) 2`. -/ +def label (A : MatrixExponent.Prices.Atlas F Twig) (x : Vec) := A.price (mark x) 2 + +/-- The defining condition `∀ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (v : S → Twig) +(s : ℝ), 0 < s → ∀ T, A.price (dilate s ∘ v) T = s * A.price v T`. -/ +def Homogeneous (A : MatrixExponent.Prices.Atlas F Twig) : Prop := + ∀ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (v : S → Twig) (s : ℝ), 0 < s → + ∀ T, A.price (dilate s ∘ v) T = s * A.price v T + +end Twig +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- A homogeneous atlas on three rays supplies a spectral tripod. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral Minimum +open scoped NNReal + +variable {F : Type} [Field F] + +/-- Normalize an ordinary three-terminal placement with at least one +nonzero edge to a spectral point. -/ +theorem prices_of_ordinary {P : Tensor F (Fin 3) → ℝ} {D x y z : ℝ} + (h : P ∈ Tensor.ordinary F (Fin 3) D) (hxy : P (Tensor.wire F 0 1 2) = x + y) + (hxz : P (Tensor.wire F 0 2 2) = x + z) (hyz : P (Tensor.wire F 1 2 2) = y + z) + (hn : 0 < y + z) : 0 < P 2 ∧ Prices F (x / P 2) (y / P 2) (z / P 2) := by + obtain ⟨d, hd, f, hf, rfl⟩ := h + have he : Tensor.values d f 2 = d := by + rw [Tensor.values, map_ofNat, div_self (Real.log_pos (by norm_num)).ne', mul_one] + have hp : 0 < d := hd.1.lt_of_ne (by intro h; simp [← h, Tensor.values] at hyz; linarith) + have h₀ (A : Tensor F (Fin 3)) : 0 ≤ f A := by simpa using hf (Tensor.zero_le A) + let v : Point F := + { toFun := fun A => ⟨f A, h₀ A⟩ + map_zero' := Subtype.ext f.map_zero + map_one' := Subtype.ext f.map_one + map_add' := fun A B => Subtype.ext (f.map_add A B) + map_mul' := fun A B => Subtype.ext (f.map_mul A B) } + have hdist (i j : Fin 3) (a b : ℝ) (h : Tensor.values d f (Tensor.wire F i j 2) = a + b) : + dist v i j = a / d + b / d := by + rw [← add_div, eq_div_iff hp.ne', mul_comm] + exact h + rw [he] + exact ⟨hp, v, fun i j h => hf h, hdist _ _ _ _ hxy, hdist _ _ _ _ hxz, hdist _ _ _ _ hyz⟩ + +namespace Twig + +variable (A : MatrixExponent.Prices.Atlas F Twig) {a : Vec} + +private theorem positive_update (ha : Positive a) (i : Fin 3) {r : ℝ} (hr : 0 < r) : + Positive (Function.update a i r) := by + intro j + by_cases h : j = i <;> simp [h, hr, ha j] + +private theorem update_dist (ha : Positive a) (i j : Fin 3) {x y : ℝ} + (hx : 0 < x) (hy : 0 < y) : + Dist.dist (mark (Function.update a i x) j) (mark (Function.update a i y) j) = + if j = i then |x - y| else 0 := by + rw [mark_dist (positive_update ha i hx) (positive_update ha i hy)] + by_cases h : j = i <;> simp [h] + +theorem label_convex (ha : Positive a) (i : Fin 3) : + ConvexOn ℝ (Set.Ioi 0) (fun t => label A (Function.update a i t)) := by + refine ⟨convex_Ioi _, ?_⟩ + intro x hx y hy u v hu hv h + have he : u = 1 - v := by linarith + let z := u * x + v * y + have hz : 0 < z := convex_Ioi (0 : ℝ) hx hy hu hv h + let f t := mark (Function.update a i t) + have hh (j : Fin 3) : Dist.dist (f x j) (f z j) = v * Dist.dist (f x j) (f y j) := by + unfold f + rw [update_dist ha _ _ hx hz, update_dist ha _ _ hx hy] + have hd : x - z = v * (x - y) := by + unfold z + rw [he] + ring + rw [hd, abs_mul, abs_of_nonneg hv, mul_ite, mul_zero] + have hk (j : Fin 3) : Dist.dist (f z j) (f y j) = (1 - v) * Dist.dist (f x j) (f y j) := by + unfold f + rw [update_dist ha _ _ hz hy, update_dist ha _ _ hx hy] + have hd : z - y = u * (x - y) := by + unfold z + rw [he] + ring + rw [hd, abs_mul, abs_of_nonneg hu, ← he, mul_ite, mul_zero] + change A.price (f z) 2 ≤ u * A.price (f x) 2 + v * A.price (f y) 2 + rw [he] + exact A.chord hv (by linarith) hh hk _ + +theorem Homogeneous.star {A : MatrixExponent.Prices.Atlas F Twig} (h : Homogeneous A) : + StarTripod F (label A) := by + have hp (a : Vec) (ha : Positive a) : + 0 < label A a ∧ Prices F (a 0 / label A a) (a 1 / label A a) (a 2 / label A a) := by + obtain ⟨D, hD⟩ := A.valid (mark a) + apply prices_of_ordinary hD + · simp [A.wire, mark_dist ha ha] + · simp [A.wire, mark_dist ha ha] + · simp [A.wire, mark_dist ha ha] + · exact add_pos (ha 1) (ha 2) + refine ⟨⟨fun a ha => (hp a ha).1, fun a ha => (hp a ha).2, fun a _ s hs => h (mark a) s hs _, + fun _ ha i => label_convex A ha i, ?_⟩, ?_⟩ + · intro a ha i x hx y hy hxy + have hm := A.label_move (mark (Function.update a i x)) (mark (Function.update a i y)) + simp only [update_dist ha i _ hx hy, Finset.sum_ite_eq', Finset.mem_univ, ite_true, + abs_of_nonpos (sub_nonpos.mpr hxy)] at hm + unfold label + linarith only [(abs_le.mp hm).2] + · intro a ha + have hm := A.label_move (fun _ : Fin 3 => origin) (mark a) + rw [A.collapsed _ (by simp) 2, zero_sub, abs_neg] at hm + have he i : Dist.dist origin (mark a i) = a i := by simp [mark, radius, (ha i).le] + simp only [he] at hm + exact (le_abs_self _).trans hm + +end Twig +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# The homogeneous tangent + +Dilation along the rays decreases each normalized price as the radius +tends to zero. At the origin the tangent prices are their infima. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Twig + +open Spectral Filter +open scoped Topology + +variable {F S : Type} [Field F] [Fintype S] [DecidableEq S] [Nonempty S] + +theorem dilate_mul (t s : ℝ) (x : Twig) : dilate t (dilate s x) = dilate (t * s) x := by + simp [dilate, mul_assoc] + +variable (A : MatrixExponent.Prices.Atlas F Twig) (v : S → Twig) (T : Tensor F S) + +private def slope (r : ℝ) := A.price (dilate r ∘ v) T / r + +private theorem slope_mono : MonotoneOn (slope A v T) (Set.Ioi 0) := by + intro a ha b hb h + change 0 < a at ha + change 0 < b at hb + have h₁ (i : S) : Dist.dist origin (dilate a (v i)) = a / b * Dist.dist origin (dilate b (v i)) + := by + rw [origin_dist, origin_dist, radius_dilate _ ha.le, radius_dilate _ hb.le, ← mul_assoc, + div_mul_cancel₀ _ hb.ne'] + have h₂ (i : S) : Dist.dist (dilate a (v i)) (dilate b (v i)) = + (1 - a / b) * Dist.dist origin (dilate b (v i)) := by + rw [origin_dist, radius_dilate _ hb.le, radial_dist _ _ ha.le hb.le, + abs_of_nonpos (sub_nonpos.mpr h), + ← mul_assoc, sub_mul, one_mul, div_mul_cancel₀ _ hb.ne', neg_sub] + have hc := A.chord (x := fun _ => origin) (y := dilate b ∘ v) (z := dilate a ∘ v) + (div_nonneg ha.le hb.le) ((div_le_one hb).mpr h) h₁ h₂ T + rw [A.collapsed (fun _ : S => origin) (by simp) T, mul_zero, zero_add] at hc + rw [slope, slope, div_le_iff₀ ha] + refine hc.trans_eq ?_ + ring + +private theorem slope_rescale {t s : ℝ} (ht : 0 < t) (hs : 0 < s) : + slope A (dilate s ∘ v) T t = s * slope A v T (t * s) := by + have eq : dilate t ∘ (dilate s ∘ v) = dilate (t * s) ∘ v := funext fun i => dilate_mul _ _ _ + rw [slope, slope, eq] + field_simp + +private def mag (n : ℕ) : ℝ := n + 1 + +private theorem mag_pos (n : ℕ) : 0 < mag n := by unfold mag; positivity + +private theorem inv_mag_limit : Tendsto (fun n => (mag n)⁻¹) atTop (𝓝 0) := by + simpa [mag] using (tendsto_one_div_add_atTop_nhds_zero_nat (𝕜 := ℝ)) + +theorem tangent : ∃ B : MatrixExponent.Prices.Atlas F Twig, Homogeneous B ∧ + ∀ {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (v : S → Twig) (T : Tensor F S), + B.price v T ≤ A.price v T := by + let l := Ultrafilter.of (atTop : Filter ℕ) + have hl : (l : Filter ℕ) ≤ atTop := Ultrafilter.of_le _ + obtain ⟨B, hB⟩ := MatrixExponent.Prices.Atlas.scaled_limit l (fun _ => Twig) (fun _ => A) + (fun n => dilate (mag n)⁻¹) mag (fun n => (mag_pos n).le) (fun x y => by + refine tendsto_const_nhds.congr' (Eventually.of_forall fun n => ?_) + dsimp only + rw [dilate_dist _ (inv_nonneg.mpr (mag_pos n).le), ← mul_assoc, + mul_inv_cancel₀ (mag_pos n).ne', + one_mul]) + have lim {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (v : S → Twig) (T : Tensor F S) : + Tendsto (fun n => slope A v T (mag n)⁻¹) (l : Filter ℕ) (𝓝 (B.price v T)) := by + refine (hB v T).congr' (Eventually.of_forall fun n => ?_) + dsimp only + rw [slope, div_inv_eq_mul, mul_comm] + rfl + have below {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (v : S → Twig) (T : Tensor F S) + (r : ℝ) (hr : 0 < r) : B.price v T ≤ slope A v T r := by + apply le_of_tendsto (lim v T) + filter_upwards [(inv_mag_limit.mono_left hl).eventually_le_const hr] with n hn + exact slope_mono A v T (inv_pos.mpr (mag_pos n)) hr hn + have above {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] (v : S → Twig) (T : Tensor F S) + (a : ℝ) (ha : ∀ r, 0 < r → a ≤ slope A v T r) : a ≤ B.price v T := + ge_of_tendsto (lim v T) (Eventually.of_forall fun n => ha _ (inv_pos.mpr (mag_pos n))) + refine ⟨B, ?_, ?_⟩ + · intro S _ _ _ v s hs T + refine le_antisymm ?_ ?_ + · rw [mul_comm, ← div_le_iff₀ hs] + refine above v T _ fun r hr => ?_ + rw [div_le_iff₀ hs, mul_comm] + have h := below (dilate s ∘ v) T (r / s) (div_pos hr hs) + rwa [slope_rescale _ _ _ (div_pos hr hs) hs, div_mul_cancel₀ _ hs.ne'] at h + · refine above _ _ _ fun t ht => ?_ + rw [slope_rescale _ _ _ ht hs] + exact mul_le_mul_of_nonneg_left (below _ _ _ (mul_pos ht hs)) hs.le + · intro S _ _ _ v T + have he : dilate 1 ∘ v = v := by funext i; simp [dilate] + simpa [slope, he] using below v T 1 zero_lt_one + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Twig +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Binary.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Binary.lean new file mode 100644 index 0000000000..4e201c28d7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Binary.lean @@ -0,0 +1,164 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Pairing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Poly + +/-! +# The binary profile bound over the coefficient field + +Interpret a three-leg tensor class on three labelled sites to apply the +binary spectral estimate to rectangular matrix multiplication. +-/ + +@[expose] public section + +/- # Interpreting the three-leg tensor semiring on labelled sites -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Upper Spectral + +local notation "CT" => MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor +variable {X Y Z U V W : Type} [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] + [Fintype W] + +theorem restricts {A : CT Coeff X Y Z} {B : CT Coeff U V W} + (h : CoefficientTensor.Restricts A B) : (triple A).Restricts (triple B) := by + obtain ⟨a, b, c, rfl⟩ := h + exact restricts_triple _ _ a b c fun _ _ _ => rfl + +/-- Extends the representative-level operation to quotient classes. -/ +def interp : TensorClass → Tensor Coeff Site := + Quotient.lift (fun A : TensorRep => Tensor.ofRaw (triple A.coeff)) + (fun _ _ h => Tensor.ofRaw_eq ⟨restricts h.1, restricts h.2⟩) + +theorem interp_tensor (T : CT Coeff X Y Z) : + interp (TensorClass.ofTensor T) = Tensor.ofRaw (triple T) := + Tensor.ofRaw_eq ⟨restricts (TensorRep.ofTensor_restricts T), + restricts (TensorRep.restricts_ofTensor T)⟩ + +theorem read_mul (A B : Raw Coeff Site) : + read (A * B) = MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor.product + (read A) (read B) := by + funext x y z + rw [read, Raw.coeff_mul] + unfold MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor.product read + congr 2 <;> funext s <;> rcases s with _ | (_ | _) <;> rfl + +theorem read_add (A B : Raw Coeff Site) : + read (A + B) = CoefficientTensor.blockSum (read A) (read B) := by + funext x y z + rw [read_apply] + change (∑ i : A.term ⊕ B.term, (A + B).factor i (some false) x * + (A + B).factor i (some true) y * (A + B).factor i none z) = _ + have h₁ (l : A.term) s (u : A.leg s ⊕ B.leg s) : + (A + B).factor (.inl l) s u = Sum.elim (A.factor l s) (fun _ => 0) u := rfl + have h₂ (l : B.term) s (u : A.leg s ⊕ B.leg s) : + (A + B).factor (.inr l) s u = Sum.elim (fun _ => 0) (B.factor l s) u := rfl + rw [Fintype.sum_sum_type] + change A.leg (some false) ⊕ B.leg (some false) at x + change A.leg (some true) ⊕ B.leg (some true) at y + change A.leg none ⊕ B.leg none at z + rcases x with x | x <;> rcases y with y | y <;> rcases z with z | z <;> + simp [h₁, h₂, CoefficientTensor.blockSum, read_apply] + +/-- Builds `TensorClass →+* Tensor Coeff Site where toFun` with the specified `toFun`, +`map_zero'`, `change`, `rw`. -/ +def interpret : TensorClass →+* Tensor Coeff Site where + toFun := interp + map_zero' := by + change interp (TensorClass.ofTensor TensorClass.emptyTensor) = 0 + rw [interp_tensor, Tensor.ofRaw_eq_zero] + exact fun x => Empty.elim (x none) + map_one' := by + change interp (TensorClass.ofTensor TensorClass.unitTensor) = Tensor.ofRaw 1 + rw [interp_tensor, ← triple_read (1 : Raw Coeff Site)] + have he : read (1 : Raw Coeff Site) = TensorClass.unitTensor := by + funext x y z + change (∑ _ : Unit, ∏ _ : Site, (1 : Coeff)) = 1 + simp + rw [he] + map_mul' X Y := by + refine Quotient.inductionOn₂ X Y fun A B => ?_ + change interp (TensorClass.ofTensor + (MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor.product + A.coeff B.coeff)) = + Tensor.ofRaw (triple A.coeff * triple B.coeff) + rw [interp_tensor, ← triple_read (triple A.coeff * triple B.coeff), read_mul, + read_triple, read_triple] + rfl + map_add' X Y := by + refine Quotient.inductionOn₂ X Y fun A B => ?_ + change interp (TensorClass.ofTensor (CoefficientTensor.blockSum A.coeff B.coeff)) = + Tensor.ofRaw (triple A.coeff + triple B.coeff) + rw [interp_tensor, ← triple_read (triple A.coeff + triple B.coeff), read_add, + read_triple, read_triple] + rfl + +theorem interpret_tensor (T : CT Coeff X Y Z) : + interpret (TensorClass.ofTensor T) = Tensor.ofRaw (triple T) := interp_tensor T + +theorem interpret_mono : Monotone interpret := + fun X Y => Quotient.inductionOn₂ X Y fun _ _ h => restricts h + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Determinant and tripling for spectral points on labelled sites -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Upper Upper.TensorClass Spectral + +private theorem interpret_dot : + interpret (dotX 2) = Tensor.wire Coeff (some true) none 2 := by + let W := Raw.wire Coeff (some true) none 2 + let T (x y z : Fin 2) : Coeff := if x = 0 ∧ y = z then 1 else 0 + have he : read W = T := by + funext x y z + change Fin 2 at x y z + refine (read_apply W x y z).trans ?_ + change (∑ i : Fin 2, (if x = 0 then (1 : Coeff) else 0) * + (if y = i then 1 else 0) * (if z = i then 1 else 0)) = T x y z + by_cases he : x = 0 <;> simp [T, he, mul_ite] + rw [dotX, TensorSpectrum.TensorClass.dotX, interpret_tensor] + change _ = Tensor.ofRaw W + rw [← triple_read W, he] + change Tensor.ofRaw (triple (CoefficientTensor.dotXCoeff 2)) = Tensor.ofRaw (triple T) + let δ (x y : Fin 2) : Coeff := if x = y then 1 else 0 + apply Tensor.ofRaw_eq + constructor + · refine restricts_triple _ _ (fun x _ => δ x 0) δ δ fun x y z => ?_ + fin_cases x <;> fin_cases y <;> fin_cases z <;> + simp [δ, T, TensorSpectrum.CoefficientTensor.dotXCoeff] + · refine restricts_triple _ _ (fun _ x => δ x 0) δ δ fun x y z => ?_ + fin_cases y <;> fin_cases z <;> + simp [δ, T, TensorSpectrum.CoefficientTensor.dotXCoeff, Fin.sum_univ_two] + +theorem coeff_binary : BinaryLaw Coeff := by + intro f hf p hp he m + let g : Character := ⟨f.comp interpret, hf.comp interpret_mono⟩ + have hg : g.pX = p := by + apply (Real.rpow_right_inj (by norm_num : (0 : ℝ) < 2) (by norm_num : (2 : ℝ) ≠ 1)).mp + have hd := TensorSpectrum.TensorClass.Character.dotXValue_eq_rpow g 2 (by decide) + change (f (interpret (dotX 2)) : ℝ) = (2 : ℝ) ^ g.pX at hd + rw [interpret_dot, he] at hd + exact hd.symm + have h := poly_row g (hg.symm ▸ hp) m + rw [hg] at h + change Row (fun n => (f (interpret (ofTensor (polynomialTensor (m + 1) (n + 1)))) : ℝ) ^ (1 / p)) + (fun n => (f (interpret (swapYZ (ofTensor (polynomialTensor (m + 1) (n + + 1))))) : ℝ) ^ (1 / p)) m at h + simp only [swapYZ_ofTensor, interpret_tensor] at h + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Pairing.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Pairing.lean new file mode 100644 index 0000000000..7d95aace2e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Pairing.lean @@ -0,0 +1,908 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rank +public import Mathlib.LinearAlgebra.Vandermonde +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Wire +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Chord +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place + +/-! +# Polynomial multiplication with many input lengths + +The output has the sum of the input lengths as its capacity. Extra +coordinates, if any, have zero coefficients. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral Finset + +variable {ι : Type} [Fintype ι] + +/-- In the case `none`, this construction gives `∑ i, L i`. -/ +def length (L : ι → ℕ) : Option ι → ℕ + | none => ∑ i, L i + | some i => L i + +/-- Computes the leg by the application `Fin (length L s)`. -/ +abbrev leg (L : ι → ℕ) (s : Option ι) := Fin (length L s) + +variable (K : Type) [Field K] (L : ι → ℕ) + +/-- Returns `1` when `∑ i, (x (some i)).val = (x none).val` holds, and `0` otherwise. -/ +def entry (x : ∀ s, leg L s) : K := if ∑ i, (x (some i)).val = (x none).val then 1 else 0 + +/-- Computes the polynomial by the application `Tensor.ofRaw (Raw.ofTable (leg L) (entry K L))`. -/ +def polynomial : Tensor K (Option ι) := Tensor.ofRaw (Raw.ofTable (leg L) (entry K L)) + +variable {L} + +theorem polynomial_mono : Monotone (polynomial (ι := ι) K) := by + intro L L' h + have he (s) : length L s ≤ length L' s := by + cases s with + | none => exact sum_le_sum (fun i _ => h i) + | some i => exact h i + refine Raw.Restricts.pullback (fun s x => Fin.castLE (he s) x) ?_ + intro x + change (∀ s, leg L s) at x + refine (Raw.coeff_ofTable _ _ x).trans ?_ + exact (Raw.coeff_ofTable (leg L') (entry K L') (fun s => Fin.castLE (he s) (x s))).symm + +theorem polynomial_ne_zero [Nonempty ι] (hL : ∀ i, 0 < L i) : polynomial K L ≠ 0 := by + have hp (s) : 0 < length L s := by + cases s with + | none => exact sum_pos (fun i _ => hL i) univ_nonempty + | some i => exact hL i + intro h + let x (s) : leg L s := ⟨0, hp s⟩ + have h' := (Tensor.ofRaw_eq_zero _).mp h x + rw [Raw.coeff_ofTable] at h' + simp [entry, x] at h' + +/-- Vandermonde evaluation and interpolation give one rank-one term +for each available output coefficient. -/ +theorem polynomial_rank [Infinite K] [Nonempty ι] (L : ι → ℕ) : + polynomial K L ≤ (∑ i, L i : ℕ) := by + classical + let m := ∑ i, L i + let v (i : Fin m) := Infinite.natEmbedding K i.val + let M := Matrix.vandermonde v + have hdet : IsUnit M.det := isUnit_iff_ne_zero.mpr + (Matrix.det_vandermonde_ne_zero_iff.mpr ((Infinite.natEmbedding K).injective.comp + Fin.val_injective)) + let f (l : Fin m) : (s : Option ι) → leg L s → K + | none, u => M⁻¹ u l + | some _, u => v l ^ u.val + let A : Raw K (Option ι) := ⟨leg L, Fin m, f⟩ + have he : polynomial K L = Tensor.ofRaw A := by + refine Tensor.ofRaw_eq (Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_) + change (∀ s, leg L s) at x + refine (Raw.coeff_ofTable _ _ x).trans ?_ + change entry K L x = ∑ l, ∏ s, f l s (x s) + let b : Fin m := ⟨∑ i, (x (some i)).val, + sum_lt_sum_of_nonempty univ_nonempty (fun i _ => (x (some i)).isLt)⟩ + simp only [Fintype.prod_option, f, prod_pow_eq_pow_sum] + let a : Fin m := x none + change entry K L x = (M⁻¹ * M) a b + rw [Matrix.nonsing_inv_mul _ hdet, Matrix.one_apply] + change (if b.val = a.val then (1 : K) else 0) = _ + simp only [Fin.ext_iff, eq_comm] + rw [he] + have h := Tensor.le_term_count A + change _ ≤ (Fintype.card (Fin m) : Tensor K (Option ι)) at h + rwa [Fintype.card_fin] at h + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Three labelled sites with two inputs and one output -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral + +/-- Computes the site by the application `Option Bool`. -/ +abbrev Site := Option Bool + +/-- In the case `some false`, this construction gives `X`. -/ +abbrev sides (X Y Z : Type) : Site → Type + | some false => X + | some true => Y + | none => Z + +variable {K X Y Z U V W : Type} [Field K] +variable [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] [Fintype W] + +instance instSides : (s : Site) → Fintype (sides X Y Z s) + | some false => inferInstanceAs (Fintype X) + | some true => inferInstanceAs (Fintype Y) + | none => inferInstanceAs (Fintype Z) + +/-- In the case `some false`, this construction gives `x`. -/ +def tuple {L : Site → Type} (x : L (some false)) (y : L (some true)) (z : L none) : ∀ s, L s + | some false => x + | some true => y + | none => z + +@[simp] theorem tuple_eta {L : Site → Type} (x : ∀ s, L s) : + tuple (x (some false)) (x (some true)) (x none) = x := by + funext s + rcases s with _ | (_ | _) <;> rfl + +/-- The indexed operation `Raw.ofTable (sides X Y Z) (fun x => T (x (some false)) (x (some +true)) (x none))`. -/ +def triple (T : X → Y → Z → K) : Raw K Site := + Raw.ofTable (sides X Y Z) (fun x => T (x (some false)) (x (some true)) (x none)) + +/-- Computes the read by the application `A.coeff (tuple x y z)`. -/ +def read (A : Raw K Site) (x : A.leg (some false)) (y : A.leg (some true)) (z : A.leg none) := + A.coeff (tuple x y z) + +theorem prod_site (f : Site → K) : ∏ s, f s = f (some false) * f (some true) * f none := by + rw [Fintype.prod_option, Fintype.prod_bool] + ring + +theorem read_apply (A : Raw K Site) (x : A.leg (some false)) (y : A.leg (some true)) (z : A.leg + none) : + read A x y z = ∑ i, A.factor i (some false) x * A.factor i (some true) y * A.factor i none z + := by + simp only [read, Raw.coeff, prod_site, tuple] + +theorem read_triple (T : X → Y → Z → K) : read (triple T) = T := by + funext x y z + exact Raw.coeff_ofTable _ _ _ + +theorem triple_read (A : Raw K Site) : Tensor.ofRaw (triple (read A)) = Tensor.ofRaw A := by + let e (s : Site) : (triple (read A)).leg s ≃ A.leg s := match s with + | none => Equiv.refl _ + | some false => Equiv.refl _ + | some true => Equiv.refl _ + refine Tensor.ofRaw_eq (Raw.equiv_coeff e fun x => ?_) + refine (Raw.coeff_ofTable _ _ x).trans ?_ + apply congrArg A.coeff + funext s + rcases s with _ | (_ | _) <;> rfl + +private def coordinates (L : Site → Type) : + L (some false) × L (some true) × L none ≃ (∀ s, L s) where + toFun p := tuple p.1 p.2.1 p.2.2 + invFun x := (x (some false), x (some true), x none) + left_inv _ := rfl + right_inv _ := tuple_eta _ + +theorem restricts_triple (A : X → Y → Z → K) (B : U → V → W → K) + (f : U → X → K) (g : V → Y → K) (h : W → Z → K) + (he : ∀ u v w, B u v w = ∑ x, ∑ y, ∑ z, f u x * g v y * h w z * A x y z) : + (triple A).Restricts (triple B) := by + let L (s : Site) : (triple B).leg s → (triple A).leg s → K := match s with + | none => h + | some false => f + | some true => g + refine (Raw.restricts_iff _ _).mpr ⟨L, fun x => ?_⟩ + rw [← (coordinates (triple A).leg).sum_comp] + simp only [Fintype.sum_prod_type, prod_site] + refine (Raw.coeff_ofTable _ _ x).trans ((he _ _ _).trans ?_) + refine Finset.sum_congr rfl fun i _ => Finset.sum_congr rfl fun j _ => + Finset.sum_congr rfl fun k _ => ?_ + exact congrArg _ (congrFun (congrFun (congrFun (read_triple A).symm i) j) k) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Finite row inequalities for ordered polynomial multiplication -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral + +variable (K : Type) [Field K] + +/-- Returns `1` when `x.val + y.val = z.val` holds, and `0` otherwise. -/ +def convolution (a b : ℕ) (x : Fin a) (y : Fin b) (z : Fin (a + b - 1)) : K := + if x.val + y.val = z.val then 1 else 0 + +/-- Computes the binary by the application `Tensor.ofRaw (triple (convolution K a b))`. -/ +def binary (a b : ℕ) := Tensor.ofRaw (triple (convolution K a b)) + +/-- The indexed operation `Tensor.ofRaw (triple (fun x z y => convolution K a b x y z))`. -/ +def reverseOutput (a b : ℕ) := Tensor.ofRaw (triple (fun x z y => convolution K a b x y z)) + +/-- The finite determinant and tripling inequalities, in degree indices. -/ +def BinaryLaw : Prop := + ∀ (f : Tensor K Site →+* NNReal), Monotone f → ∀ p : ℝ, 0 < p → + (f (Tensor.wire K (some true) none 2) : ℝ) = (2 : ℝ) ^ p → ∀ m : ℕ, + Row (fun n => (f (binary K (m + 1) (n + 1)) : ℝ) ^ (1 / p)) + (fun n => (f (reverseOutput K (m + 1) (n + 1)) : ℝ) ^ (1 / p)) m + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Keeping the weight-zero coefficients of a nonnegatively graded tensor -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral Finset + +variable {K S : Type} [Field K] [Fintype S] [Nonempty S] {X : S → Type} [∀ s, Fintype (X s)] + +/-- Computes the array by the application `Tensor.ofRaw (Raw.ofTable X v)`. -/ +abbrev array (v : (∀ s, X s) → K) := Tensor.ofRaw (Raw.ofTable X v) + +/-- Returns `v x` when `∑ s, w s (x s) = 0` holds, and `0` otherwise. -/ +def grade (w : (s : S) → X s → ℤ) (v : (∀ s, X s) → K) (x : ∀ s, X s) : K := + if ∑ s, w s (x s) = 0 then v x else 0 + +private theorem rescale (v : (∀ s, X s) → K) (f : (s : S) → X s → K) : + array (fun x => (∏ s, f s (x s)) * v x) ≤ array v := by + classical + let A := Raw.ofTable X v + let B := Raw.ofTable X (fun x => (∏ s, f s (x s)) * v x) + let L (s) (x y : X s) := if y = x then f s x else 0 + refine ⟨L, fun x => ?_⟩ + change (∀ s, X s) at x + change B.coeff x = ∑ l : A.term, ∏ s, ∑ y : X s, L s (x s) y * A.factor l s y + simp only [L, ite_mul, zero_mul, Fintype.sum_ite_eq', prod_mul_distrib, ← mul_sum] + exact (Raw.coeff_ofTable _ _ x).trans (congrArg _ (Raw.coeff_ofTable X v x).symm) + +theorem grade_price [Infinite K] (f : Tensor K S →+* NNReal) (hf : Monotone f) + (v : (∀ s, X s) → K) (w : (s : S) → X s → ℤ) + (hw : ∀ x, v x ≠ 0 → 0 ≤ ∑ s, w s (x s)) : f (array (grade w v)) ≤ f (array v) := by + classical + let P x := Polynomial.X ^ (∑ s, w s (x s)).toNat * Polynomial.C (v x) + have he : (fun x => (P x).eval 0) = grade w v := by + funext x + by_cases hv : v x = 0 + · simp [P, grade, hv] + by_cases hz : ∑ s, w s (x s) = 0 + · simp [P, grade, hz] + have hn : (∑ s, w s (x s)).toNat ≠ 0 := by have := hw x hv; omega + simp [P, grade, hz, hn] + have h : ZClosure {u | array u ≤ array v} (grade w v) := by + rw [← he] + apply Speedup.path_closure P Polynomial.X Polynomial.X_ne_zero + intro t ht + rw [Polynomial.eval_X] at ht + let a s x := t ^ (w s x) + have ha (x : ∀ s, X s) (l : Finset S) : ∏ s ∈ l, a s (x s) = t ^ (∑ s ∈ l, w s (x s)) := by + induction l using Finset.induction_on with + | empty => simp + | insert i l hi ih => rw [prod_insert hi, sum_insert hi, ih, zpow_add₀ ht] + have hp : (fun x => (P x).eval t) = fun x => (∏ s, a s (x s)) * v x := by + funext x + by_cases hv : v x = 0 + · simp [P, hv] + simp only [P, Polynomial.eval_mul, Polynomial.eval_pow, Polynomial.eval_X, Polynomial.eval_C, + ha, ← zpow_natCast, Int.toNat_of_nonneg (hw x hv)] + rw [hp] + exact rescale v a + exact NNReal.coe_le_coe.mp (h.price f hf (by positivity) (fun _ ht + => NNReal.coe_le_coe.mpr (hf ht))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- Grading away unequal labels exposes a diagonal of identical copies. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral Finset + +variable {F ι B : Type} [Field F] [Fintype ι] [Fintype B] [DecidableEq B] + {X : Option ι → Type} [∀ s, Fintype (X s)] + +omit [DecidableEq B] in +theorem grade_labels (w : ∀ s, B × X s → ℤ) (v : (∀ s, B × X s) → F) (u : (∀ s, X s) → F) + (rule : ∀ x, v x ≠ 0 → ((∑ s, w s (x s)) = 0 ↔ ∀ i, (x (some i)).1 = (x none).1)) + (aligned : ∀ x, (∀ i, (x (some i)).1 = (x none).1) → v x = u (fun s => (x s).2)) : + array (grade w v) = (Fintype.card B : Tensor F (Option ι)) * array u := by + classical + rw [← Tensor.diag_eq_natCast B] + refine Tensor.ofRaw_eq (Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_) + change (∀ s, B × X s) at x + erw [Raw.coeff_ofTable, Raw.coeff_mul, Raw.coeff_ofTable] + have hd : (Raw.diag F (Option ι) B).coeff (fun s => (x s).1) = + if ∀ i, (x (some i)).1 = (x none).1 then 1 else 0 := by + change ∑ p, ∏ s, (if (x s).1 = p then (1 : F) else 0) = _ + rw [Fintype.sum_eq_single (x none).1] + · rw [Fintype.prod_option] + simp [Fintype.prod_ite_zero] + · intro p hp + exact prod_eq_zero (mem_univ none) (ite_eq_right hp.symm) + change grade w v x = (Raw.diag F (Option ι) B).coeff (fun s => (x s).1) * u (fun s => (x s).2) + rw [hd, grade] + by_cases h : ∀ i, (x (some i)).1 = (x none).1 + · rw [ite_eq_left h, one_mul, ← aligned x h] + by_cases hv : v x = 0 + · simp [hv] + · rw [ite_eq_left ((rule x hv).mpr h)] + · rw [ite_eq_right h, zero_mul] + by_cases hv : v x = 0 + · simp [hv] + · rw [ite_eq_right (mt (rule x hv).mp h)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- +# Equal-block degeneration + +For block number `a`, length `l` and offset `d`, assign the input the +integer weight `a(a-1)l + a(2d+1)`. Its excess above the supporting +line for the output block `b` is positive unless `a=b`. The supporting +lines add to the output weight because degrees add. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Finset Spectral + +variable {ι : Type} [Fintype ι] + +/-- The quantity computed by `a * (a - 1) * l + a * (2 * d + m)`. -/ +def weight (a l d m : ℤ) := a * (a - 1) * l + a * (2 * d + m) + +private theorem excess (a b l d : ℤ) (hd : 0 ≤ d) (hl : d < l) (hne : a ≠ b) : + 0 < (a - b) * ((a - b - 1) * l + 2 * d + 1) := by + rcases lt_or_gt_of_ne hne with h | h + · have ht := mul_le_mul_of_nonneg_right (show a - b - 1 ≤ -2 by omega) (show 0 ≤ l by omega) + exact mul_pos_of_neg_of_neg (by omega) (by omega) + · have ht := mul_nonneg (show 0 ≤ a - b - 1 by omega) (show 0 ≤ l by omega) + exact mul_pos (by omega) (by omega) + +theorem weights (a l d : ι → ℤ) (b u : ℤ) + (hd : ∀ i, 0 ≤ d i) (hl : ∀ i, d i < l i) (he : ∑ i, (a i * l i + d i) = b * (∑ i, l i) + u) : + let W := -weight b (∑ i, l i) u (Fintype.card ι) + ∑ i, weight (a i) (l i) (d i) 1 + 0 ≤ W ∧ (W = 0 ↔ ∀ i, a i = b) := by + let v i := (a i - b) * ((a i - b - 1) * l i + 2 * d i + 1) + have hv i : 0 ≤ v i ∧ (v i = 0 ↔ a i = b) := by + by_cases h : a i = b + · simp [v, h] + · have hp : 0 < v i := excess _ _ _ _ (hd i) (hl i) h + exact ⟨hp.le, iff_of_false hp.ne' h⟩ + have he' i : weight (a i) (l i) (d i) 1 = + v i + (2 * b) * (a i * l i + d i) - b * (b + 1) * l i + b := by unfold v weight; ring + have hW : -weight b (∑ i, l i) u (Fintype.card ι) + ∑ i, weight (a i) (l i) (d i) 1 = + ∑ i, v i := by + simp_rw [he'] + rw [sum_add_distrib, sum_sub_distrib, sum_add_distrib, ← mul_sum, he, ← mul_sum, sum_const] + simp only [weight, card_univ, nsmul_eq_mul] + ring + dsimp only + rw [hW] + refine ⟨sum_nonneg (fun i _ => (hv i).1), ?_⟩ + simp only [sum_eq_zero_iff_of_nonneg (fun i _ => (hv i).1), mem_univ, forall_true_left, (hv _).2] + +variable (K : Type) [Field K] (L : ι → ℕ) (k : ℕ) + +private abbrev block (s : Option ι) := Fin k × leg L s + +private def join (s : Option ι) (p : block L k s) : leg (fun i => k * L i) s := + Fin.cast (by cases s <;> simp [length, mul_sum]) (finProdFinEquiv p) + +private theorem join_val (s : Option ι) (p : block L k s) : + (join L k s p).val = p.1.val * length L s + p.2.val := by + simp [join, finProdFinEquiv, add_comm, mul_comm] + +private def big (x : ∀ s, block L k s) := entry K (fun i => k * L i) (fun s => join L k s (x s)) + +private def grading (s : Option ι) (p : block L k s) : ℤ := + if s.isNone then -weight p.1.val (length L s) p.2.val (Fintype.card ι) + else weight p.1.val (length L s) p.2.val 1 + +private theorem grading_rule (x : ∀ s, block L k s) (hx : big K L k x ≠ 0) : + 0 ≤ ∑ s, grading L k s (x s) ∧ + ((∑ s, grading L k s (x s)) = 0 ↔ ∀ i, (x (some i)).1 = (x none).1) := by + have he : ∑ i, ((x (some i)).1.val * L i + (x (some i)).2.val) = + (x none).1.val * (∑ i, L i) + (x none).2.val := by + simpa [big, entry, join_val, length] using hx + have hw := weights (fun i => ((x (some i)).1.val : ℤ)) (fun i => (L i : ℤ)) + (fun i => ((x (some i)).2.val : ℤ)) (x none).1.val (x none).2.val + (fun _ => by positivity) (fun i => by exact_mod_cast (x (some i)).2.isLt) (by exact_mod_cast he) + simpa [Fintype.sum_option, grading, length, Fin.ext_iff] using hw + +private theorem table_blocks : + array (grade (grading L k) (big K L k)) = (k : Tensor K (Option ι)) * polynomial K L := by + have he := grade_labels (grading L k) (big K L k) (entry K L) + (fun x hx => (grading_rule K L k x hx).2) (by + intro x h + simp only [big, entry, join_val, length, h, sum_add_distrib, ← mul_sum, add_right_inj]) + rw [Fintype.card_fin] at he + exact he + +theorem polynomial_dilate [Infinite K] (f : Tensor K (Option ι) →+* NNReal) + (hf : Monotone f) : k * f (polynomial K L) ≤ f (polynomial K (fun i => k * L i)) := by + classical + have hb : array (big K L k) ≤ polynomial K (fun i => k * L i) := by + refine Raw.Restricts.pullback (join L k) fun x => ?_ + change (∀ s, block L k s) at x + refine (Raw.coeff_ofTable _ _ x).trans ?_ + exact (Raw.coeff_ofTable _ (entry K (fun i => k * L i)) (fun s => join L k s (x s))).symm + have h := grade_price f hf (big K L k) (grading L k) (fun x hx => (grading_rule K L k x hx).1) + rw [table_blocks, map_mul, map_natCast] at h + exact h.trans (hf hb) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Continuum profile for univariate polynomial multiplication -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral Filter +open scoped Topology + +variable {ι K : Type} [Fintype ι] [DecidableEq ι] [Nonempty ι] [Field K] [Infinite K] + +omit [DecidableEq ι] in +theorem scaling_polynomial (f : Tensor K (Option ι) →+* NNReal) (hf : Monotone f) : + Scaling (fun L => (f (polynomial K L) : ℝ)) := by + classical + refine ⟨fun _ => by positivity, ?_, ?_, ?_⟩ + · intro _ _ h + exact NNReal.coe_le_coe.mpr (hf (polynomial_mono K h)) + · intro L + have h := hf (polynomial_rank K L) + rw [map_natCast] at h + exact_mod_cast h + · intro k L + exact_mod_cast polynomial_dilate K L k f hf + +/-- The indexed operation `scale (fun L => (f (polynomial K L) : ℝ)) t`. -/ +def profile (f : Tensor K (Option ι) →+* NNReal) (t : ι → ℝ) := + scale (fun L => (f (polynomial K L) : ℝ)) t + +variable {f : Tensor K (Option ι) →+* NNReal} (hf : Monotone f) {t : ι → ℝ} (ht : ∀ i, 0 < t i) +include hf ht + +omit [DecidableEq ι] in +theorem profile_pos : 0 < profile f t := by + classical + apply (scaling_polynomial f hf).scale_pos ht (L := fun _ => 1) + have h := hf (Tensor.one_le _ (polynomial_ne_zero K (L := fun _ => 1) (fun _ => zero_lt_one))) + rw [map_one] at h + exact_mod_cast zero_lt_one.trans_le h + +omit [DecidableEq ι] in +theorem log_profile_limit {α : Type*} {l : Filter α} {N : α → ℝ} + (hN : Tendsto N l atTop) {L : α → ι → ℕ} + (hL : ∀ i, Tendsto (fun n => (L n i : ℝ) / N n) l (𝓝 (t i))) : + Tendsto (fun n => Real.log (f (polynomial K (L n))) - Real.log (N n)) + l (𝓝 (Real.log (profile f t))) := by + classical + have h := (scaling_polynomial f hf).limit ht hN hL + have hp := profile_pos hf ht + apply (h.log hp.ne').congr' + filter_upwards [hN.eventually_gt_atTop 0, h.eventually_const_lt hp] with n hn hn' + exact Real.log_div ((div_pos_iff_of_pos_right hn).mp hn').ne' hn.ne' + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # From ordinary base-two prices to natural-log profiles -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral + +/-- In the case `false`, this construction gives `x`. -/ +def two {α : Type*} (x y : α) : Bool → α + | false => x + | true => y + +/-- In the case `none`, this construction gives `-i - j`. -/ +def pairSite (i j : Fin 3) : Site → Fin 3 + | none => -i - j + | some false => i + | some true => j + +/-- The value specified by `v ∘ pairSite i j`. -/ +def placement {X : Type*} (v : Fin 3 → X) (i j : Fin 3) := v ∘ pairSite i j + +theorem pairSite_bijective {i j : Fin 3} (hij : i ≠ j) : Function.Bijective (pairSite i j) := by + fin_cases i <;> fin_cases j <;> first | contradiction | decide + +variable {K S : Type} [Field K] [Fintype S] [Nontrivial S] [DecidableEq S] + {X : Type*} [PseudoMetricSpace X] (A : MatrixExponent.Prices.Atlas K X) (v : S → X) + +theorem exists_point : + ∃ f : Tensor K S →+* NNReal, Monotone f ∧ + ∀ B, Real.log 2 * A.price v B = A.price v 2 * Real.log (f B) := by + obtain ⟨_, d, _, f, hf, he⟩ := A.valid v + have hn (B : Tensor K S) : 0 ≤ f B := by simpa using hf (Tensor.zero_le B) + let g : Tensor K S →+* NNReal := + { toFun := fun B => ⟨f B, hn B⟩ + map_zero' := Subtype.ext (map_zero f) + map_one' := Subtype.ext (map_one f) + map_add' := fun a b => Subtype.ext (f.map_add a b) + map_mul' := fun a b => Subtype.ext (f.map_mul a b) } + refine ⟨g, hf, fun B => ?_⟩ + change Real.log 2 * A.price v B = A.price v 2 * Real.log (f B) + rw [he, Tensor.values, Tensor.values, map_ofNat] + ring + +/-- The value specified by `(exists_point A v).choose`. -/ +def point : Tensor K S →+* NNReal := (exists_point A v).choose + +theorem point_mono : Monotone (point A v) := (exists_point A v).choose_spec.1 + +theorem price_eq (B : Tensor K S) : + Real.log 2 * A.price v B = A.price v 2 * Real.log (point A v B) := + (exists_point A v).choose_spec.2 B + +theorem placement_two (v : Fin 3 → X) {i j : Fin 3} (hij : i ≠ j) : + A.price (placement v i j) 2 = A.price v 2 := by + unfold placement + rw [A.place, Function.comp_apply, Tensor.place_eq_group _ (pairSite_bijective hij).2, map_ofNat] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Reindexing the two-input polynomial tensor -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral + +variable {K X Y Z : Type} [Field K] [Fintype X] [Fintype Y] [Fintype Z] + +/-- In the case `none`, this construction gives `none`. -/ +def flip : Site → Site + | none => none + | some false => some true + | some true => some false + +/-- In the case `none`, this construction gives `some true`. -/ +def turn : Site → Site + | none => some true + | some false => some false + | some true => none + +private theorem turn_le (T : X → Y → Z → K) : + Tensor.place turn (Tensor.ofRaw (triple T)) ≤ Tensor.ofRaw (triple (fun x z y => T x y z)) := by + let A := (triple T).group turn + let L (s : Site) : A.leg s → sides X Z Y s := match s with + | none => fun x => x ⟨some true, rfl⟩ + | some false => fun x => x ⟨some false, rfl⟩ + | some true => fun x => x ⟨none, rfl⟩ + refine Raw.Restricts.pullback L fun x => ?_ + erw [Raw.coeff_group, Raw.coeff_ofTable, Raw.coeff_ofTable] + rfl + +theorem place_turn (a b : ℕ) : Tensor.place turn (binary K a b) = reverseOutput K a b := by + apply le_antisymm (turn_le _) + have h := Tensor.place_mono turn (turn_le (fun x z y => convolution K a b x y z)) + rw [← Tensor.place_comp, show turn ∘ turn = id by funext s; rcases s with _ | (_ | _) <;> rfl, + Tensor.place_id] at h + exact h + +private theorem flip_le (a b : ℕ) : Tensor.place flip (binary K a b) ≤ binary K b a := by + let A := (triple (convolution K a b)).group flip + let L (s : Site) : A.leg s → sides (Fin b) (Fin a) (Fin (b + a - 1)) s := match s with + | none => fun x => Fin.cast (show a + b - 1 = b + a - 1 by omega) (x ⟨none, rfl⟩) + | some false => fun x => x ⟨some true, rfl⟩ + | some true => fun x => x ⟨some false, rfl⟩ + refine Raw.Restricts.pullback L fun x => ?_ + erw [Raw.coeff_group, Raw.coeff_ofTable, Raw.coeff_ofTable] + unfold convolution + rw [Nat.add_comm] + rfl + +theorem place_flip (a b : ℕ) : Tensor.place flip (binary K a b) = binary K b a := by + apply le_antisymm (flip_le _ _) + have h := Tensor.place_mono flip (flip_le (K := K) b a) + rw [← Tensor.place_comp, show flip ∘ flip = id by funext s; rcases s with _ | (_ | _) <;> rfl, + Tensor.place_id] at h + exact h + +theorem binary_eq (a b : ℕ) : binary K a b = polynomial K (two a b) := by + classical + let d := length (two a b) none + have hd : d = a + b := by simp [d, length, two, add_comm] + let W (x : Fin a) (y : Fin b) (z : Fin d) : K := if x.val + y.val = z.val then 1 else 0 + let A := Raw.ofTable (leg (two a b)) (entry K (two a b)) + have he : read A = W := by + funext x y z + refine (Raw.coeff_ofTable _ _ _).trans ?_ + simp [entry, W, tuple, Nat.add_comm] + change Tensor.ofRaw (triple _) = Tensor.ofRaw A + rw [← triple_read A, he] + change Tensor.ofRaw (triple (convolution K a b)) = Tensor.ofRaw (triple W) + let e := Fin.castLE (show a + b - 1 ≤ d by omega) + let δ {α : Type} (x y : α) : K := if x = y then 1 else 0 + apply Tensor.ofRaw_eq + constructor + · refine restricts_triple _ _ δ δ (fun z z' => δ z (e z')) fun x y z => ?_ + simp only [δ, ite_mul, one_mul, zero_mul, Finset.sum_ite_irrel, Finset.sum_const_zero, + Fintype.sum_ite_eq] + let l : Fin (a + b - 1) := ⟨x.val + y.val, by have := x.isLt; have := y.isLt; omega⟩ + rw [Fintype.sum_eq_single l] + · simp [convolution, l, W, e, Fin.ext_iff, eq_comm] + · intro j hj + have h' : x.val + y.val ≠ j.val := fun h' => hj (Fin.ext h'.symm) + simp [convolution, h'] + · refine restricts_triple _ _ δ δ (fun z z' => δ (e z) z') fun x y z => ?_ + simp only [δ, ite_mul, one_mul, zero_mul, Finset.sum_ite_irrel, Finset.sum_const_zero, + Fintype.sum_ite_eq] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Width profiles on a three-point placement -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Filter +open scoped Topology + +variable {K : Type} [Field K] {X : Type*} [PseudoMetricSpace X] + (A : MatrixExponent.Prices.Atlas K X) + (v : Fin 3 → X) + +/-- Selects the appropriate branch of `if i ≠ j ∧ 0 < x ∧ 0 < y then A.price v 2 * Real.log +(profile (point A (placement v i j)) (two x y)) else 0`. -/ +def pairs (i j : Fin 3) (x y : ℝ) : ℝ := + if i ≠ j ∧ 0 < x ∧ 0 < y then + A.price v 2 * Real.log (profile (point A (placement v i j)) (two x y)) + else 0 + +variable [Infinite K] {i j : Fin 3} {x y : ℝ} + +theorem pairs_limit (hij : i ≠ j) (hx : 0 < x) (hy : 0 < y) + {α : Type*} {l : Filter α} {N : α → ℝ} (hN : Tendsto N l atTop) {L : α → Bool → ℕ} + (hL : ∀ i, Tendsto (fun n => (L n i : ℝ) / N n) l (𝓝 (two x y i))) : + Tendsto (fun n => Real.log 2 * A.price (placement v i j) (polynomial K (L n)) - + A.price v 2 * Real.log (N n)) l (𝓝 (pairs A v i j x y)) := by + have ht : ∀ b, 0 < two x y b := by rintro (_ | _) <;> assumption + have h := (log_profile_limit (point_mono A (placement v i j)) ht hN hL).const_mul (A.price v 2) + rw [pairs, ite_eq_left ⟨hij, hx, hy⟩] + apply h.congr' + filter_upwards [] with n + rw [price_eq A (placement v i j), placement_two A v hij, mul_sub] + +theorem pairs_scale (hij : i ≠ j) {s : ℝ} (hs : 0 < s) (hx : 0 < x) (hy : 0 < y) : + pairs A v i j (s * x) (s * y) = pairs A v i j x y + A.price v 2 * Real.log s := by + have ht : ∀ b, 0 < two x y b := by rintro (_ | _) <;> assumption + let f := point A (placement v i j) + have hf : Monotone f := point_mono _ _ + have he : profile f (two (s * x) (s * y)) = s * profile f (two x y) := by + rw [show two (s * x) (s * y) = s • two x y by funext b; cases b <;> rfl] + exact (scaling_polynomial f hf).scale_smul ht hs + rw [pairs, pairs, ite_eq_left ⟨hij, mul_pos hs hx, mul_pos hs hy⟩, ite_eq_left ⟨hij, hx, hy⟩, + he, Real.log_mul hs.ne' (profile_pos hf ht).ne'] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- Restrictions by absorbing the last input at the output site +or extracting a fixed total degree. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral Finset + +variable {K : Type} [Field K] + +private theorem placed_le {S T U : Type} [Fintype S] [Fintype T] [Fintype U] + [DecidableEq S] [DecidableEq T] [DecidableEq U] {L : S → ℕ} {M : T → ℕ} + (f : Option S → U) (g : Option T → U) + (v : ∀ t, (∀ s, f s = g t → leg L s) → leg M t) + (he : ∀ x, entry K L x = entry K M (fun t => v t (fun s _ => x s))) : + Tensor.place f (polynomial K L) ≤ Tensor.place g (polynomial K M) := by + let A := Raw.ofTable (leg L) (entry K L) + let B := Raw.ofTable (leg M) (entry K M) + let V (u : U) (x : (A.group f).leg u) : (B.group g).leg u := + fun t => v t (fun s h => x ⟨s, h.trans t.property⟩) + refine Raw.Restricts.pullback V fun x => ?_ + erw [Raw.coeff_group, Raw.coeff_group, Raw.coeff_ofTable, Raw.coeff_ofTable, he] + congr 1 + funext t + unfold V + congr 1 + funext s h + have aux (u : U) (h : f s = u) : x (f s) ⟨s, rfl⟩ = x u ⟨s, h⟩ := by cases h; rfl + exact aux _ h + +private def pins (i j k : Fin 3) : Site → Fin 3 + | none => k + | some false => i + | some true => j + +/-- In the case `none`, this construction gives `k`. -/ +def terminal (k : Fin 3) : Option (Fin 3) → Fin 3 + | none => k + | some i => i + +variable {i j k : Fin 3} {L : Fin 3 → ℕ} + +private theorem pairSite_eq (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + pairSite i j = pins i j k := by + funext t + rcases t with _ | (_ | _) <;> simp only [pairSite, pins] + fin_cases i <;> fin_cases j <;> fin_cases k <;> first | contradiction | decide + +private theorem sum_three (v : Fin 3 → ℕ) (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + ∑ t, v t = v i + v j + v k := by + have he : {i, j, k} = (univ : Finset (Fin 3)) := by + apply Finset.eq_univ_of_card + simp [hij, hik, hjk] + simp [← he, hij, hik, hjk, add_assoc] + +private theorem pair_length (a b : ℕ) : length (two a b) none = a + b := by + simp [length, two, add_comm] + +/-- An out-of-range difference uses the spare output coordinate of the pair. -/ +private def shift (d z w : ℕ) : ℕ := + if w ≤ z ∧ z - w < d then z - w else d - 1 + +theorem absorb (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) (hi : 0 < L i) : + Tensor.place (terminal k) (polynomial K L) ≤ + Tensor.place (pairSite i j) (polynomial K (two (L i) (L j))) := by + rw [pairSite_eq hij hik hjk] + let M := two (L i) (L j) + let D := L i + L j + have hd : length M none = D := pair_length _ _ + have hshift (z w : ℕ) : shift D z w < length M none := by + rw [hd] + unfold shift D + split <;> omega + let v : ∀ t, (∀ s, terminal k s = pins i j k t → leg L s) → leg M t + | some false, x => x (some i) rfl + | some true, x => x (some j) rfl + | none, x => ⟨shift D (x none rfl).val (x (some k) rfl).val, hshift _ _⟩ + refine placed_le _ _ v fun x => ?_ + have h₁ : (x (some i)).val < L i := (x (some i)).isLt + have h₂ : (x (some j)).val < L j := (x (some j)).isLt + simp only [entry, sum_three _ hij hik hjk, Fintype.sum_bool, v] + congr 1 + apply propext + unfold shift D + split <;> omega + +/-- Pin the output at degree `L i + L j - 1` and reverse the degree +on input `k` to expose a two-input polynomial with output at `k`. -/ +theorem extract_pair (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) (hi : 0 < L i) + (hk : L i + L j ≤ L k) : + Tensor.place (some ∘ pairSite i j) (polynomial K (two (L i) (L j))) ≤ polynomial K L := by + rw [pairSite_eq hij hik hjk] + let M := two (L i) (L j) + let D := L i + L j + have hd : length M none = D := pair_length _ _ + have hout : D - 1 < length L none := by + rw [length, sum_three _ hij hik hjk] + unfold D + omega + let v : ∀ t, (∀ s, some (pins i j k s) = t → leg M s) → leg L t + | none, _ => ⟨D - 1, hout⟩ + | some l, x => + if hi' : i = l then Fin.cast (congrArg L hi') (x (some false) (congrArg some hi')) + else if hj' : j = l then Fin.cast (congrArg L hj') (x (some true) (congrArg some hj')) + else + have eq : k = l := by omega + have hD : D - 1 < L l := by rw [← eq]; unfold D; omega + ⟨D - 1 - (x none (congrArg some eq)).val, (Nat.sub_le _ _).trans_lt hD⟩ + rw [← Tensor.place_id (polynomial K L)] + refine placed_le _ _ v fun x => ?_ + have h₁ : (x none).val < D := hd ▸ (x none).isLt + simp only [entry, sum_three _ hij hik hjk, Fintype.sum_bool, v, hij, hik, hjk, + dite_eq_right, dite_eq_left, eq_self, not_false_eq_true] + congr 1 + apply propext + change (x (some true)).val + (x (some false)).val = (x none).val ↔ + (x (some false)).val + (x (some true)).val + (D - 1 - (x none).val) = D - 1 + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Compatibility of the width profiles with site permutations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Filter Spectral +open scoped Topology + +variable {K : Type} [Field K] {X : Type*} [PseudoMetricSpace X] + (A : MatrixExponent.Prices.Atlas K X) + (v : Fin 3 → X) {i j k : Fin 3} {x y : ℝ} + +theorem remaining (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : -i - j = k := by + fin_cases i <;> fin_cases j <;> fin_cases k <;> first | contradiction | decide + +theorem price_flip (i j : Fin 3) (a b : ℕ) : + A.price (placement v i j) (binary K a b) = A.price (placement v j i) (binary K b a) := by + have he : placement v i j = placement v j i ∘ flip := by + funext s + rcases s with _ | (_ | _) <;> simp [placement, pairSite, flip, sub_eq_add_neg, add_comm] + rw [he, A.place, Function.comp_apply, place_flip] + +theorem price_turn (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) (a b : ℕ) : + A.price (placement v i k) (binary K a b) = A.price (placement v i j) (reverseOutput K a b) := by + have he : placement v i k = placement v i j ∘ turn := by + funext s + rcases s with _ | (_ | _) <;> + simp [placement, pairSite, turn, remaining hij hik hjk, remaining hik hij hjk.symm] + rw [he, A.place, Function.comp_apply, place_turn] + +theorem binary_ne_zero (a b : ℕ) : binary K (a + 1) (b + 1) ≠ 0 := by + rw [binary_eq] + exact polynomial_ne_zero K (by rintro (_|_) <;> exact Nat.succ_pos _) + +theorem reverse_ne_zero (a b : ℕ) : reverseOutput K (a + 1) (b + 1) ≠ 0 := by + rw [← place_turn] + intro hz + have he := congrArg (Tensor.place turn) hz + rw [← Tensor.place_comp, show turn ∘ turn = id by funext s; rcases s with _ | (_ | _) <;> rfl, + Tensor.place_id, Tensor.place_zero] at he + exact binary_ne_zero a b he + +theorem point_pos {f : Tensor K Site →+* NNReal} (hf : Monotone f) + {T : Tensor K Site} (hT : T ≠ 0) : 0 < (f T : ℝ) := by + have h := hf (Tensor.one_le _ hT) + rw [map_one] at h + exact_mod_cast zero_lt_one.trans_le h + +theorem scaled_wire (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) + {d : ℝ} (hd : 0 < d) (he : Dist.dist (v j) (v k) = d) : + 0 < A.price v 2 ∧ + (point A (placement v i j) (Tensor.wire K (some true) none 2) : ℝ) + = (2 : ℝ) ^ (d / A.price v 2) := by + let w := placement v i j + let B := Tensor.wire K (some true) none 2 + have he' : A.price w B = d := by + rw [show A.price w B = Dist.dist (w (some true)) (w none) from A.wire _ _ _] + simpa [w, placement, pairSite, remaining hij hik hjk] using he + have hD := price_eq A w B + rw [he', placement_two A v hij] at hD + have hlog : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hone : (1 : ℝ) ≤ point A w B := by + have h := point_mono A w (Tensor.one_le_wire K (some true) none (n := 2) (by decide)) + rw [map_one] at h + exact_mod_cast h + have hpos : 0 < A.price v 2 := pos_of_mul_pos_left (hD ▸ mul_pos hlog hd) (Real.log_nonneg hone) + refine ⟨hpos, ?_⟩ + rw [Real.rpow_def_of_pos (by norm_num), ← mul_div_assoc, hD, mul_div_cancel_left₀ _ hpos.ne', + Real.exp_log (zero_lt_one.trans_le hone)] + +variable [Infinite K] + +theorem binary_limit (hij : i ≠ j) (hx : 0 < x) (hy : 0 < y) {a b : ℝ → ℕ} + (ha : Tendsto (fun n => (a n : ℝ) / n) atTop (𝓝 x)) + (hb : Tendsto (fun n => (b n : ℝ) / n) atTop (𝓝 y)) : + Tendsto (fun n => Real.log 2 * A.price (placement v i j) (binary K (a n + 1) (b n + 1)) - + A.price v 2 * Real.log n) atTop (𝓝 (pairs A v i j x y)) := by + have h₁ : Tendsto (fun n : ℝ => 1 / n) atTop (𝓝 0) := tendsto_const_nhds.div_atTop tendsto_id + simp_rw [binary_eq] + apply pairs_limit A v hij hx hy tendsto_id + rintro (_ | _) + · simpa only [two, Nat.cast_add, Nat.cast_one, add_div, add_zero, id_eq] using ha.add h₁ + · simpa only [two, Nat.cast_add, Nat.cast_one, add_div, add_zero, id_eq] using hb.add h₁ + +theorem pairs_symm (i j : Fin 3) (x y : ℝ) : pairs A v i j x y = pairs A v j i y x := by + by_cases h : i ≠ j ∧ 0 < x ∧ 0 < y + swap; · have : ¬(j ≠ i ∧ 0 < y ∧ 0 < x) := by tauto + simp only [pairs, ite_eq_right h, ite_eq_right this] + obtain ⟨hij, hx, hy⟩ := h + have ha := tendsto_nat_floor_mul_div_atTop hx.le + have hb := tendsto_nat_floor_mul_div_atTop hy.le + have h := binary_limit A v hij hx hy ha hb + simp_rw [price_flip A v i j] at h + exact tendsto_nhds_unique h (binary_limit A v hij.symm hy hx hb ha) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Root.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Root.lean new file mode 100644 index 0000000000..e40f65915e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Root.lean @@ -0,0 +1,872 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Scale +public import Mathlib.Analysis.SpecificLimits.Basic +public import Mathlib.Analysis.SpecialFunctions.Log.Deriv +public import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Pairing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Fields +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.UpperBound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Face.Contact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Arms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Multi.Count + +/-! # Passing discrete concavity and tripling to a continuum profile -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Filter Set +open scoped Topology + +private theorem secants {f g : ℕ → ℝ} {m i j k : ℕ} (h : Row f g m) + (hij : i ≤ j) (hjk : j ≤ k) : + (f k - f j) * ((j : ℝ) - i) ≤ (f j - f i) * ((k : ℝ) - j) := by + have hl := (TensorSpectrum.row_secant_bounds f h.dec i (j - i)).2 + have hu := (TensorSpectrum.row_secant_bounds f h.dec j (k - j)).1 + rw [Nat.add_sub_of_le hij, Nat.cast_sub hij] at hl + rw [Nat.add_sub_of_le hjk, Nat.cast_sub hjk] at hu + linarith only [mul_le_mul_of_nonneg_right hl (sub_nonneg.mpr (Nat.cast_le.mpr hjk : (j : ℝ) ≤ k)), + mul_le_mul_of_nonneg_right hu (sub_nonneg.mpr (Nat.cast_le.mpr hij : (i : ℝ) ≤ j))] + +theorem curve_limit {f g : ℝ → ℕ → ℝ} {F G : ℝ → ℝ} {a : ℝ} {m : ℝ → ℕ} {q : ℝ → ℝ} + (ha : 0 < a) (hm : Tendsto (fun n => (m n : ℝ) / n) atTop (𝓝 a)) + (hq : ∀ n, 0 < n → 0 < q n) (hr : ∀ n, Row (f n) (g n) (m n)) + (hF : ∀ x, 0 < x → 0 < F x) + (hf : ∀ x, 0 < x → ∀ k : ℝ → ℕ, Tendsto (fun n => (k n : ℝ) / n) atTop (𝓝 x) → + Tendsto (fun n => f n (k n) / q n) atTop (𝓝 (F x))) + (hg : ∀ x, 0 < x → ∀ k : ℝ → ℕ, Tendsto (fun n => (k n : ℝ) / n) atTop (𝓝 x) → + Tendsto (fun n => g n (k n) / q n) atTop (𝓝 (G x))) : Curve F G a := by + let L (x n : ℝ) := ⌊x * n⌋₊ + have hL {x} (hx : 0 < x) : Tendsto (fun n => (L x n : ℝ) / n) atTop (𝓝 x) := + tendsto_nat_floor_mul_div_atTop hx.le + have hfl {x} (hx : 0 < x) := hf x hx _ (hL hx) + refine ⟨hF, ?_, ?_⟩ + · apply concaveOn_of_slope_anti_adjacent (convex_Ioi 0) + intro x y z hx hz hxy hyz + have hy := lt_trans (show 0 < x from hx) hxy + rw [div_le_div_iff₀ (sub_pos.mpr hyz) (sub_pos.mpr hxy)] + apply le_of_tendsto_of_tendsto (((hfl hz).sub (hfl hy)).mul ((hL hy).sub (hL hx))) + (((hfl hy).sub (hfl hx)).mul ((hL hz).sub (hL hy))) + filter_upwards [eventually_gt_atTop (0 : ℝ)] with n hn + have h₁ : L x n ≤ L y n := Nat.floor_mono (mul_le_mul_of_nonneg_right hxy.le hn.le) + have h₂ : L y n ≤ L z n := Nat.floor_mono (mul_le_mul_of_nonneg_right hyz.le hn.le) + simp only [← sub_div, div_mul_div_comm] + exact div_le_div_of_nonneg_right (secants (hr n) h₁ h₂) (mul_nonneg (hq n hn).le hn.le) + · intro x hx + let k n := 3 * L x n + m n + 2 + have hk : Tendsto (fun n => (k n : ℝ) / n) atTop (𝓝 (3 * x + a)) := by + have h₂ : Tendsto (fun n : ℝ => 2 / n) atTop (𝓝 0) := tendsto_const_nhds.div_atTop tendsto_id + simpa only [k, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, add_div, mul_div_assoc, add_zero] + using (((hL hx).const_mul 3).add hm).add h₂ + apply le_of_tendsto_of_tendsto (((hfl hx).const_mul 2).add (hg x hx _ (hL hx))) + (hf _ (by positivity) k hk) + filter_upwards [eventually_gt_atTop (0 : ℝ)] with n hn + rw [← mul_div_assoc, ← add_div] + exact div_le_div_of_nonneg_right ((hr n).trip _) (hq n hn).le + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +section +/- # A derivative from comparison with equal-cost energy increments -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +open Set Filter +open scoped Topology + +variable {f g : ℝ → ℝ} {a b d x : ℝ} + +private theorem profile_derivative (c d x y : ℝ) (hc : 0 < c) : + HasDerivAt (fun t => y - c * d * Real.log (1 + (t - x) / c)) (-d) x := by + have h := (((hasDerivAt_id x).sub_const x).div_const c).const_add 1 + have h' := (h.log (by simp)).const_mul (c * d) + convert! h'.const_sub y using 1 + simp only [id_eq, sub_self, zero_div, add_zero, div_one] + field_simp + +theorem right_derivative (ha : 0 < a) (hb : 0 < b) + (h : ∀ u : ℝ, 0 < u → + a * d * Real.log (1 + u / a) ≤ f x - f (x + u) ∧ f x - f (x + u) ≤ b * d * Real.log (1 + + u / b)) : + HasDerivWithinAt f (-d) (Ioi x) x := by + let p c t := f x - c * d * Real.log (1 + (t - x) / c) + have he c : p c x = f x := by simp [p] + have ht c (hc : 0 < c) := hasDerivWithinAt_iff_tendsto_slope.mp + ((profile_derivative c d x (f x) hc).hasDerivWithinAt (s := Ioi x)) + have hs (t : ℝ) (ht : x < t) : + slope (p b) x t ≤ slope f x t ∧ slope f x t ≤ slope (p a) x t := by + obtain ⟨h₁, h₂⟩ := h (t - x) (sub_pos.mpr ht) + rw [show x + (t - x) = t by ring] at h₁ h₂ + simp only [slope_def_field, he] + constructor <;> apply div_le_div_of_nonneg_right _ (sub_nonneg.mpr ht.le) <;> + unfold p <;> linarith + apply hasDerivWithinAt_iff_tendsto_slope.mpr + refine tendsto_of_tendsto_of_tendsto_of_le_of_le' (ht b hb) (ht a ha) ?_ ?_ + · filter_upwards [self_mem_nhdsWithin] with t h; exact (hs t h.1).1 + · filter_upwards [self_mem_nhdsWithin] with t h; exact (hs t h.1).2 + +/-- The right derivative suffices when its value is continuous. -/ +theorem of_right (hf : ContinuousOn f (Ioi 0)) (hg : ContinuousOn g (Ioi 0)) + (hd : ∀ t, 0 < t → HasDerivWithinAt f (g t) (Ioi t) t) (hx : 0 < x) : + HasDerivAt f (g x) x := by + have hi := intervalIntegral.integral_hasDerivAt_right (f := g) (a := x) (b := x) + (by simp) (hg.stronglyMeasurableAtFilter isOpen_Ioi x hx) + (hg.continuousAt (isOpen_Ioi.mem_nhds hx)) + apply (hi.const_add (f x)).congr_of_eventuallyEq + filter_upwards [Ioi_mem_nhds hx] with t ht + have hpos : 0 < min x t := lt_min hx ht + have hs : uIcc x t ⊆ Ioi 0 := fun _ he => hpos.trans_le he.1 + rw [intervalIntegral.integral_eq_sub_of_hasDeriv_right (hf.mono hs) + (fun y hy => hd y (hpos.trans hy.1)) (hg.mono hs).intervalIntegrable] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +end + +section +/- # Scalar extension of the finite polynomial row inequalities -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral + +variable {K L : Type} [Field K] [Field L] + +private theorem map_triple (φ : K →+* L) {X Y Z : Type} [Fintype X] [Fintype Y] [Fintype Z] + (T : X → Y → Z → K) (U : X → Y → Z → L) (he : ∀ x y z, φ (T x y z) = U x y z) : + Tensor.map φ (Tensor.ofRaw (triple T)) = Tensor.ofRaw (triple U) := by + rw [Tensor.map_ofRaw] + refine Tensor.ofRaw_eq (Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_) + erw [Raw.coeff_map, Raw.coeff_ofTable, Raw.coeff_ofTable] + exact he _ _ _ + +theorem binary_of_closed (h : ∀ (L : Type) [Field L] [IsAlgClosed L], BinaryLaw L) : BinaryLaw K + := by + intro f hf p hp he m + let L := AlgebraicClosure K + let φ := algebraMap K L + obtain ⟨g, hg, hmap⟩ := Tensor.extend_field L f hf + have h₁ (a b : ℕ) : g (binary L a b) = f (binary K a b) := by + rw [← hmap] + exact congrArg g (map_triple φ _ _ (fun _ _ _ => by simp [convolution, apply_ite φ])).symm + have h₂ (a b : ℕ) : g (reverseOutput L a b) = f (reverseOutput K a b) := by + rw [← hmap] + exact congrArg g (map_triple φ _ _ (fun _ _ _ => by simp [convolution, apply_ite φ])).symm + rw [← hmap, Tensor.map_wire] at he + simpa only [h₁, h₂] using h L g hg p hp he m + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Coupled width curves at an actual finite placement -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Filter Minimum Spectral +open scoped Topology + +theorem binary_law (K : Type) [Field K] : BinaryLaw K := + binary_of_closed (fun L _ _ => (closed_fulfills L).binary) + +variable {K : Type} [Field K] {X : Type*} [PseudoMetricSpace X] + (A : MatrixExponent.Prices.Atlas K X) + (v : Fin 3 → X) {i j : Fin 3} + +private theorem scaled_limit (hij : i ≠ j) {T : ℝ → Tensor K Site} (ht : ∀ n, T n ≠ 0) + {B d : ℝ} (hd : 0 < d) (hD : 0 < A.price v 2) + (h : Tendsto (fun n => Real.log 2 * A.price (placement v i j) (T n) - + A.price v 2 * Real.log n) atTop (𝓝 B)) : + Tendsto (fun n : ℝ => (point A (placement v i j) (T n) : ℝ) ^ (1 / (d / A.price v 2)) / + n ^ (1 / (d / A.price v 2))) atTop (𝓝 (Real.exp (B / d))) := by + apply ((h.div_const d).rexp).congr' + filter_upwards [eventually_gt_atTop (0 : ℝ)] with n hn + have hp := point_pos (point_mono A (placement v i j)) (ht n) + rw [price_eq A (placement v i j), placement_two A v hij, Real.rpow_def_of_pos hp, + Real.rpow_def_of_pos hn, ← Real.exp_sub] + congr 1 + field_simp + +theorem family [Infinite K] (u d : Vec) (hu : Positive u) (hd : Positive d) + (hopp : ∀ i j k : Fin 3, i ≠ j → i ≠ k → j ≠ k → Dist.dist (v j) (v k) = d i) : + Family (pairs A v) d u (A.price v 2) := by + refine ⟨pairs_symm A v, fun i j hij _ _ _ => pairs_scale A v hij, ?_⟩ + intro i j k hij hik hjk + obtain ⟨hD, he⟩ := scaled_wire A v hij hik hjk (hd i) (hopp i j k hij hik hjk) + let f := point A (placement v i j) + let p := d i / A.price v 2 + have hp : 0 < p := div_pos (hd i) hD + let a (n : ℝ) := ⌊u i * n⌋₊ + have ha : Tendsto (fun n => (a n : ℝ) / n) atTop (𝓝 (u i)) + := tendsto_nat_floor_mul_div_atTop (hu i).le + have hr (n : ℝ) := binary_law K f (point_mono _ _) p hp he (a n) + apply curve_limit (q := fun n => n ^ (1 / p)) (hu i) ha (fun _ hn => by positivity) hr + (fun _ _ => Real.exp_pos _) + · intro x hx b hb + exact scaled_limit A v hij (fun n => binary_ne_zero _ _) (hd i) hD + (binary_limit A v hij (hu i) hx ha hb) + · intro x hx b hb + have h := binary_limit A v hik (hu i) hx ha hb + simp_rw [price_turn A v hij hik hjk] at h + exact scaled_limit A v hij (fun n => reverse_ne_zero _ _) (hd i) hD h + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- +# Radial contraction and the directional derivative + +The energy `Q v s` is evaluated at reciprocal arm lengths `v` and +costs `s i / v i`. Increasing all costs by `t` adds `t • v` to `s`. +For a common cost the increment is explicit by log homogeneity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +open Minimum Set Filter + +/-- The data for the radial construction, including `continuous`, `scale`, `contract`. -/ +structure Radial (D : Vec → ℝ) (Q : Vec → Vec → ℝ) : Prop where + continuous : ∀ v, Positive v → ContinuousOn (Q v) {s | Positive s} + scale : ∀ v s, Positive v → Positive s → ∀ r : ℝ, 0 < r → + Q v (r • s) = Q v s - D v⁻¹ * Real.log r + contract : ∀ v w s, Positive v → Positive w → Positive s → v ≤ w → ∀ t : ℝ, 0 < t → + Q w s - Q w (s + t • w) ≤ Q v s - Q v (s + t • v) + +/-- The quantity computed by `Q v s + ∑ i, (v i)⁻¹ * Real.log (s i) - (∑ i, v i)⁻¹ * Real.log (∑ +i, s i)`. -/ +def potential (Q : Vec → Vec → ℝ) (v s : Vec) : ℝ := + Q v s + ∑ i, (v i)⁻¹ * Real.log (s i) - (∑ i, v i)⁻¹ * Real.log (∑ i, s i) + +variable {F : Type} [Field F] {D : Vec → ℝ} {Q : Vec → Vec → ℝ} {v s : Vec} + +private theorem pos_inv (h : Positive v) : Positive v⁻¹ := fun i => inv_pos.mpr (h i) +private theorem pos_sum (h : Positive v) : 0 < ∑ i, v i := + Finset.sum_pos (fun i _ => h i) Finset.univ_nonempty +private theorem pos_scale (h : Positive v) {r : ℝ} (hr : 0 < r) : Positive (r • v) := + fun i => mul_pos hr (h i) + +theorem Radial.potential_scale (h : Radial D Q) (hv : Positive v) (hs : Positive s) + {r : ℝ} (hr : 0 < r) : + potential Q v (r • s) = potential Q v s - defect D v * Real.log r := by + unfold potential defect + rw [h.scale _ _ hv hs _ hr] + simp only [Pi.smul_apply, smul_eq_mul, ← Finset.mul_sum, Real.log_mul hr.ne' (pos_sum hs).ne'] + simp_rw [Real.log_mul hr.ne' (hs _).ne', mul_add, Finset.sum_add_distrib, ← Finset.sum_mul] + ring + +theorem Radial.potential_continuous (h : Radial D Q) (hv : Positive v) : + ContinuousOn (potential Q v) {s | Positive s} := by + have hi (i : Fin 3) : ContinuousOn (fun s : Vec => Real.log (s i)) {s | Positive s} := + (continuous_apply i).continuousOn.log fun _ hs => (hs i).ne' + have hs : ContinuousOn (fun s : Vec => Real.log (∑ i, s i)) {s | Positive s} := + (continuous_finsetSum _ (fun i _ => continuous_apply i)).continuousOn.log + fun _ hs => (pos_sum hs).ne' + exact ((h.continuous v hv).add (continuousOn_finsetSum _ (fun i _ => + (hi i).const_mul _))).sub (hs.const_mul _) + +private theorem common_cost (h : Radial D Q) (hd : Tripod F D) (hs : Positive s) + {r t : ℝ} (hr : 0 < r) (ht : 0 < t) : + Q (r⁻¹ • s) s - Q (r⁻¹ • s) (s + t • (r⁻¹ • s)) = + r * D s⁻¹ * Real.log (1 + t / r) := by + have he : s + t • (r⁻¹ • s) = (1 + t / r) • s := by + ext i; simp only [Pi.add_apply, Pi.smul_apply, smul_eq_mul]; ring + have hi : (r⁻¹ • s)⁻¹ = r • s⁻¹ := by ext i; simp [mul_comm] + rw [he, h.scale _ _ (pos_scale hs (inv_pos.mpr hr)) hs _ (by positivity), hi, + hd.scale _ (pos_inv hs) r hr] + ring + +private theorem radii (hv : Positive v) (hs : Positive s) : + ∃ a b : ℝ, 0 < a ∧ 0 < b ∧ v ≤ a⁻¹ • s ∧ b⁻¹ • s ≤ v := by + let x := ∑ i, v i / s i + let y := ∑ i, s i / v i + have hx : 0 < x := Finset.sum_pos (fun i _ => div_pos (hv i) (hs i)) Finset.univ_nonempty + have hy : 0 < y := Finset.sum_pos (fun i _ => div_pos (hs i) (hv i)) Finset.univ_nonempty + refine ⟨x⁻¹, y, by positivity, hy, ?_, ?_⟩ + · rw [inv_inv] + intro i + exact (div_le_iff₀ (hs i)).mp (Finset.single_le_sum + (fun j _ => (div_pos (hv j) (hs j)).le) (Finset.mem_univ i)) + · intro i + have he : s i / v i ≤ y := Finset.single_le_sum + (fun j _ => (div_pos (hs j) (hv j)).le) (Finset.mem_univ i) + exact (inv_mul_le_iff₀ hy).2 ((div_le_iff₀ (hv i)).mp he) + +private theorem Radial.right (h : Radial D Q) (hd : Tripod F D) (hv : Positive v) + {p : ℝ → Vec} {x : ℝ} (hs : Positive (p x)) + (hp : ∀ t : ℝ, p (x + t) = p x + t • v) : + HasDerivWithinAt (fun t => Q v (p t)) (-D (p x)⁻¹) (Ioi x) x := by + obtain ⟨a, b, ha, hb, ha', hb'⟩ := radii hv hs + apply right_derivative ha hb + intro t ht + rw [hp t, ← common_cost h hd hs ha ht, ← common_cost h hd hs hb ht] + exact ⟨h.contract _ _ _ hv (pos_scale hs (by positivity)) hs ha' t ht, + h.contract _ _ _ (pos_scale hs (by positivity)) hv hs hb' t ht⟩ + +theorem Radial.direction (h : Radial D Q) (hd : Tripod F D) (hv : Positive v) + {u : Vec} {t : ℝ} (hp : Positive (u + t • v)) : + HasDerivWithinAt (fun s => potential Q v (u + s • v)) + (-defect D (u + t • v)) (Ioi t) t := by + let p (s : ℝ) := u + s • v + have he := h.right hd hv (p := p) hp (by intro x; unfold p; rw [add_smul, add_assoc]) + have h₁ (i : Fin 3) : HasDerivAt (fun s => p s i) (v i) t := by + simpa only [p, Pi.add_apply, Pi.smul_apply, smul_eq_mul, id_eq, one_mul] using! + ((hasDerivAt_id t).mul_const (v i)).const_add (u i) + have h₂ (i : Fin 3) : + HasDerivAt (fun s => (v i)⁻¹ * Real.log (p s i)) (p t i)⁻¹ t := by + have he : (v i)⁻¹ * (v i / p t i) = (p t i)⁻¹ := by + rw [div_eq_mul_inv, ← mul_assoc, inv_mul_cancel₀ (hv i).ne', one_mul] + rw [← he] + exact ((h₁ i).log (hp i).ne').const_mul _ + have h₃ : HasDerivAt (fun s => ∑ i, p s i) (∑ i, v i) t := + HasDerivAt.fun_sum fun i _ => h₁ i + have h₄ : HasDerivAt (fun s => (∑ i, v i)⁻¹ * Real.log (∑ i, p s i)) (∑ i, p t i)⁻¹ t := by + have he : (∑ i, v i)⁻¹ * ((∑ i, v i) / ∑ i, p t i) = (∑ i, p t i)⁻¹ := by + rw [div_eq_mul_inv, ← mul_assoc, inv_mul_cancel₀ (pos_sum hv).ne', one_mul] + rw [← he] + exact (h₃.log (pos_sum hp).ne').const_mul _ + have h₅ : HasDerivAt (fun s => ∑ i, (v i)⁻¹ * Real.log (p s i)) (∑ i, (p t i)⁻¹) t := + HasDerivAt.fun_sum fun i _ => h₂ i + rw [show -defect D (u + t • v) = -D (p t)⁻¹ + (∑ i, (p t i)⁻¹) - (∑ i, p t i)⁻¹ by + unfold defect p; ring] + exact (he.add h₅.hasDerivWithinAt).sub h₄.hasDerivWithinAt + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +end + +/- # Integrating the energy along a ray from a coordinate axis -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +open Minimum Set Filter +open scoped Topology + +/-- Evaluates `if j = i then 1 else 0` at the input `j`. -/ +def unit (i : Fin 3) : Vec := fun j => if j = i then 1 else 0 + +theorem unit_move (v : Vec) (i : Fin 3) : unit i + v = move v i 1 := by + ext j; by_cases h : j = i <;> simp [unit, move, h, add_comm] + +/-- The quantity computed by `potential Q v (unit i + t • v)`. -/ +def along (Q : Vec → Vec → ℝ) (v : Vec) (i : Fin 3) (t : ℝ) : ℝ := + potential Q v (unit i + t • v) + +variable {F : Type} [Field F] {D : Vec → ℝ} {Q : Vec → Vec → ℝ} {v u : Vec} {s t : ℝ} + +theorem pos_along (hv : Positive v) (i : Fin 3) (ht : 0 < t) : + Positive (unit i + t • v) := by + rw [unit_move] + exact (show Positive (t • v) from fun j => mul_pos ht (hv j)).move i zero_le_one + +theorem Radial.axis_deriv (h : Radial D Q) (hd : Tripod F D) (hv : Positive v) (i : Fin 3) + (ht : 0 < t) : HasDerivAt (along Q v i) (-defect D (move (t • v) i 1)) t := by + have hp : ContinuousOn (along Q v i) (Ioi 0) := + (h.potential_continuous hv).comp (by fun_prop) (fun _ hx => pos_along hv i hx) + let f (x : ℝ) := -defect D (move (x • v) i 1) + have hc : ContinuousOn f (Ioi 0) := by + have he : ContinuousOn (fun x : ℝ => 1 / x) (Ioi 0) := + continuousOn_const.div continuousOn_id (fun _ hx => ne_of_gt hx) + have h₁ := (hd.regular.continuous _ hv i).comp he (fun x hx + => mem_Ici.mpr (one_div_pos.mpr (show 0 < x from hx)).le) + refine ((h₁.div continuousOn_id (fun _ hx => ne_of_gt hx)).neg).congr ?_ + intro x hx + exact congrArg Neg.neg (hd.regular.scale hv i hx zero_le_one) + refine of_right hp hc ?_ ht + intro x hx + unfold f + rw [← unit_move] + exact h.direction hd hv (pos_along hv i hx) + +theorem Radial.axis_far (h : Radial D Q) (hv : Positive v) (i j : Fin 3) : + Tendsto (fun T : ℝ => along Q v i T - along Q v j T) atTop (𝓝 0) := by + let p (i : Fin 3) (T : ℝ) := T⁻¹ • unit i + v + have hpos i T (ht : 0 < T) : Positive (p i T) := by + intro j + have := hv j + unfold p unit + simp only [Pi.add_apply, Pi.smul_apply, smul_eq_mul] + split <;> positivity + have he i T (ht : 0 < T) : along Q v i T = potential Q v (p i T) - defect D v * Real.log T := by + unfold along + rw [show unit i + T • v = T • p i T by simp [p, smul_add, ht.ne']] + exact h.potential_scale hv (hpos _ _ ht) ht + have hl (i : Fin 3) : Tendsto (fun T => potential Q v (p i T)) atTop (𝓝 (potential Q v v)) := by + apply ((h.potential_continuous hv) v hv).tendsto.comp + apply tendsto_nhdsWithin_iff.mpr + refine ⟨?_, (eventually_gt_atTop 0).mono (fun T hT => hpos _ _ hT)⟩ + simpa [p] using ((tendsto_inv_atTop_zero : Tendsto (fun x : ℝ + => x⁻¹) atTop (𝓝 0)).smul_const (unit i)).add_const v + have hh := (hl i).sub (hl j) + rw [sub_self] at hh + apply hh.congr' + filter_upwards [eventually_gt_atTop 0] with T ht + rw [he _ _ ht, he _ _ ht] + ring + +/-- A segment starting near an axis has rate derivative of absolute value +at most one by the star bound, uniformly in its distance to that axis. -/ +theorem Radial.segment (h : Radial D Q) (hd : StarTripod F D) (hv : Positive v) + (hu : Positive u) (hs : 1 ≤ ∑ i, u i) (ht : 0 ≤ t) : + |potential Q v (u + t • v) - potential Q v u| ≤ t := by + let p (x : ℝ) := u + x • v + have hu' (x) (hx : 0 ≤ x) : u ≤ p x := + fun i => le_add_of_nonneg_right (mul_nonneg hx (hv i).le) + have hp x (hx : 0 ≤ x) : Positive (p x) := fun i => (hu i).trans_le (hu' x hx i) + have hc : ContinuousOn (fun x => potential Q v (p x)) (Icc 0 t) := + (h.potential_continuous hv).comp (by unfold p; fun_prop) (fun _ hx => hp _ hx.1) + have hb (x : ℝ) (hx : x ∈ Ico 0 t) : ‖-defect D (p x)‖ ≤ 1 := by + rw [norm_neg, Real.norm_of_nonneg (hd.toTripod.regular.nonneg _ (hp _ hx.1))] + refine (hd.cap (hp _ hx.1)).trans (inv_le_one_of_one_le₀ ?_) + exact hs.trans (Finset.sum_le_sum (fun i _ => hu' x hx.1 i)) + have he := norm_image_sub_le_of_norm_deriv_right_le_segment hc + (fun _ hx => (h.direction hd.toTripod hv (hp _ hx.1)).Ici_of_Ioi) hb t ⟨ht, le_rfl⟩ + simpa only [p, zero_smul, add_zero, Real.norm_eq_abs, sub_zero, one_mul] using he + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +end + +/- # Directional comparison from energy and the axis limits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +open Minimum Set Filter +open scoped Topology + +/-- Evaluates `if j = i then 1 else r` at the input `j`. -/ +def near (i : Fin 3) (r : ℝ) : Vec := fun j => if j = i then 1 else r + +private theorem near_pos (i : Fin 3) {r : ℝ} (hr : 0 < r) : Positive (near i r) := by + intro j + unfold near + split <;> positivity + +private theorem near_sum (i : Fin 3) {r : ℝ} (hr : 0 < r) : 1 ≤ ∑ j, near i r j := by + have he := Finset.single_le_sum (fun j _ => (near_pos i hr j).le) (Finset.mem_univ i) + simpa [near] using he + +private theorem near_limit (i : Fin 3) : Tendsto (near i) (𝓝[>] 0) (𝓝 (unit i)) := by + apply tendsto_pi_nhds.mpr + intro j + by_cases h : j = i + · simp [near, unit, h] + · simpa only [near, unit, ite_eq_right h] using! + (tendsto_id.mono_left nhdsWithin_le_nhds : Tendsto (fun x : ℝ => x) (𝓝[>] 0) (𝓝 0)) + +variable {F : Type} [Field F] {D : Vec → ℝ} {Q : Vec → Vec → ℝ} {v : Vec} + +private theorem Radial.axis_near (h : Radial D Q) (hd : StarTripod F D) + (hv : Positive v) {i : Fin 3} {b : ℝ} + (hb : Tendsto (fun r => potential Q v (near i r)) (𝓝[>] 0) (𝓝 b)) : + Tendsto (fun T : ℝ => along Q v i (1 / T)) atTop (𝓝 b) := by + have he (t : ℝ) (ht : 0 < t) : |along Q v i t - b| ≤ t := by + have hu : Tendsto (fun r => potential Q v (near i r + t • v)) (𝓝[>] 0) + (𝓝 (along Q v i t)) := by + apply ((h.potential_continuous hv) _ (pos_along hv i ht)).tendsto.comp + apply tendsto_nhdsWithin_iff.mpr + refine ⟨(near_limit i).add_const _, ?_⟩ + filter_upwards [self_mem_nhdsWithin] with r hr j + exact add_pos (near_pos i hr j) (mul_pos ht (hv j)) + apply le_of_tendsto (hu.sub hb).abs + filter_upwards [self_mem_nhdsWithin] with r hr + exact h.segment hd hv (near_pos i hr) (near_sum i hr) ht.le + apply Metric.tendsto_nhds.mpr + intro ε hε + filter_upwards [eventually_gt_atTop (1 / ε)] with T hT + rw [Real.dist_eq] + have hT₀ := (one_div_pos.mpr hε).trans hT + exact (he _ (one_div_pos.mpr hT₀)).trans_lt ((one_div_lt hT₀ hε).mpr hT) + +/-- Axis limits of the corrected energy agree to the accuracy of +the diagonal defect, with local control up to the open face. -/ +def AxisLimits (D : Vec → ℝ) (Q : Vec → Vec → ℝ) : Prop := + ∀ v, Positive v → ∃ E : ℝ, 0 ≤ E ∧ ∀ w, Positive w → w ≤ (2 : ℝ) • v → + v 1 ≤ w 1 → v 2 ≤ w 2 → ∃ b : Fin 3 → ℝ, + (∀ i, Tendsto (fun r => potential Q w (near i r)) (𝓝[>] 0) (𝓝 (b i))) ∧ + ∀ i j, b i - b j ≤ E * defect D w + +theorem Radial.uniform (h : Radial D Q) (hd : StarTripod F D) (ha : AxisLimits D Q) : + Face.Uniform (defect D) := by + intro v hv + obtain ⟨E, hE, hb⟩ := ha v hv + refine ⟨E, hE, ?_⟩ + intro w hw hu h₁ h₂ i j ζ hζ + obtain ⟨b, hl, he⟩ := hb w hw hu h₁ h₂ + have ht := ((h.axis_near hd hw (hl i)).sub (h.axis_near hd hw (hl j))).sub + (h.axis_far hw i j) + rw [sub_zero] at ht + have hs := (he i j).trans_lt (lt_add_of_pos_right _ hζ) + filter_upwards [eventually_ge_atTop (1 : ℝ), ht.eventually_lt_const hs] with T hT hh + have hm (k : Fin 3) := integral_potential hd.toTripod.regular hw + (fun x hx => h.axis_deriv hd.toTripod hw k hx) hT + rw [hm i, hm j] + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +end + +/- # Degree costs and log-homogeneous variational energies -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +open Minimum Profile Set + +variable {p d x s : ℝ} + +theorem log_max (hp : 0 < p) (hs : 0 < s) (hx : 0 < x) : + p * Real.log x - s * x ≤ p * Real.log (p / s) - p := by + have h := Real.log_le_sub_one_of_pos (div_pos (mul_pos hs hx) hp) + rw [Real.log_div (by positivity) hp.ne', Real.log_mul hs.ne' hx.ne'] at h + have hh := mul_le_mul_of_nonneg_left h hp.le + rw [mul_sub p (s * x / p), mul_div_cancel₀ _ hp.ne'] at hh + rw [Real.log_div hp.ne' hs.ne'] + linarith only [hh] + +/-- The sum of `s i * x i` indexed by `i`. -/ +def cost {ι : Type} [Fintype ι] (s x : ι → ℝ) := ∑ i, s i * x i + +/-- The supremum of `((fun x => d + R x - cost s x) '' {x | ∀ i, 0 < x i})`. -/ +def variational {ι : Type} [Fintype ι] (R : (ι → ℝ) → ℝ) (d : ℝ) (s : ι → ℝ) : ℝ := + sSup ((fun x => d + R x - cost s x) '' {x | ∀ i, 0 < x i}) + +/-- The data for the growth construction, including `pos`, `scale`, `bound`. -/ +structure Growth (R : Vec → ℝ) (d : ℝ) : Prop where + pos : 0 < d + scale : ∀ x, Positive x → ∀ t : ℝ, 0 < t → R (t • x) = R x + d * Real.log t + bound : ∀ x, Positive x → R x ≤ d * Real.log (mass x) + +variable {R : Vec → ℝ} {v w u : Vec} {t : ℝ} + +theorem variational_le {s : Vec} {B : ℝ} (h : ∀ x, Positive x → d + R x - cost s x ≤ B) : + variational R d s ≤ B := by + apply csSup_le + · exact ⟨_, fun _ => 1, fun _ => zero_lt_one, rfl⟩ + · rintro _ ⟨x, hx, rfl⟩ + exact h x hx + +theorem Growth.lower (h : Growth R d) (hv : Positive v) (hw : Positive w) : + d + R w - cost v w ≤ variational R d v := by + refine le_csSup ?_ ⟨w, hw, rfl⟩ + let p := min (v 0) (min (v 1) (v 2)) + have hp : 0 < p := lt_min (hv _) (lt_min (hv _) (hv _)) + have hv' (i : Fin 3) : p ≤ v i := by fin_cases i <;> simp [p] + refine ⟨d * Real.log (d / p), ?_⟩ + rintro _ ⟨x, hx, rfl⟩ + have hc : p * mass x ≤ cost v x := by + rw [cost, mass, Finset.mul_sum] + exact Finset.sum_le_sum (fun i _ => mul_le_mul_of_nonneg_right (hv' i) (hx i).le) + linarith only [hc, h.bound _ hx, log_max h.pos hp (mass_pos hx)] + +private theorem cost_scale (s x : Vec) (t : ℝ) : cost (t • s) x = cost s (t • x) := by + unfold cost + apply Finset.sum_congr rfl + intro i _ + simp only [Pi.smul_apply, smul_eq_mul]; ring + +theorem Growth.log_scale (h : Growth R d) (hv : Positive v) (ht : 0 < t) : + variational R d (t • v) = variational R d v - d * Real.log t := by + have upper {v : Vec} {t : ℝ} (hv : Positive v) (ht : 0 < t) : + variational R d (t • v) ≤ variational R d v - d * Real.log t := by + apply variational_le + intro x hx + have he := h.lower hv (show Positive (t • x) from fun i => mul_pos ht (hx i)) + rw [h.scale x hx _ ht, ← cost_scale] at he + linarith + refine le_antisymm (upper hv ht) ?_ + have he := upper (show Positive (t • v) from fun i => mul_pos ht (hv i)) (inv_pos.mpr ht) + rw [inv_smul_smul₀ ht.ne', Real.log_inv] at he + linarith + +private theorem open_positive : IsOpen {v : Vec | Positive v} := by + simp only [Positive, Set.ofPred_forall] + exact isOpen_iInter_of_finite fun i => isOpen_lt continuous_const (continuous_apply i) + +theorem Growth.continuous (h : Growth R d) : + ContinuousOn (variational R d) {v | Positive v} := by + apply ConvexOn.continuousOn open_positive + constructor + · intro v hv w hw a b ha hb hab i + change 0 < a * v i + b * w i + rcases eq_or_lt_of_le ha with rfl | ha + · simpa [show b = 1 by linarith] using hw i + exact add_pos_of_pos_of_nonneg (mul_pos ha (hv i)) (mul_nonneg hb (hw i).le) + intro v hv w hw a b ha hb hab + apply variational_le + intro x hx + have he : cost (a • v + b • w) x = a * cost v x + b * cost w x := by + simp only [cost, Pi.smul_apply, smul_eq_mul, Pi.add_apply, Finset.mul_sum, + ← Finset.sum_add_distrib] + exact Finset.sum_congr rfl (fun _ _ => by ring) + have hh : (a + b) * (d + R x) = d + R x := by rw [hab, one_mul] + rw [he, smul_eq_mul, smul_eq_mul] + linarith only [mul_le_mul_of_nonneg_left (h.lower hv hx) ha, + mul_le_mul_of_nonneg_left (h.lower hw hx) hb, hh] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +end + +/- # Profiles at the origin and the terminals of a tripod -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +open Minimum Profile + +/-- At reciprocal lengths `v`, `R` is the three-input profile with +output at the origin. `P i j` has inputs `i,j` and the third terminal +as output. -/ +structure Root (D : Vec → ℝ) (v : Vec) (R : Vec → ℝ) (P : PairPrices) : Prop where + growth : Growth R (D v⁻¹) + family : Family P (opposite v) (criticalWidth v) (D v⁻¹) + chord : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → ∀ x, Positive x → + opposite v i * R x ≤ (v j)⁻¹ * P i j (x i) (x j) + (v k)⁻¹ * P i k (x i) (x k) + pairing : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → ∀ x, Positive x → x k = x i + x j → + P i j (x i) (x j) ≤ R x + +/-- Costs and arm lengths are both rescaled by `1/v i`. -/ +def adjusted (D : Vec → ℝ) (R : Vec → Vec → ℝ) (v s : Vec) := + variational (R v⁻¹) (D v⁻¹) (s / v) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +end + +/- # Locally uniform axis agreement on a homogeneous spectral tripod -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Minimum Filter +open scoped Topology + +variable {F : Type} [Field F] {D : Vec → ℝ} {v : Vec} {P : PairPrices} + +/-- The value specified by `intercept P (opposite v) (criticalWidth v) i + residual D v i * +Real.log (residual D v i / ((v i)⁻¹ * criticalWidth v i))`. -/ +def axisValue (D : Vec → ℝ) (v : Vec) (P : PairPrices) (i : Fin 3) : ℝ := + intercept P (opposite v) (criticalWidth v) i + + residual D v i * Real.log (residual D v i / ((v i)⁻¹ * criticalWidth v i)) + +theorem Family.at_critical (h : Family P (opposite v) (criticalWidth v) (D v⁻¹)) + (hd : StarTripod F D) (hv : Positive v) : + Critical (criticalWidth v) (intercept P (opposite v) (criticalWidth v)) (opposite v) + (fun i j => P i j (criticalWidth v i) (criticalWidth v j)) (defect D v) := + h.critical (critical_pos hv) (opposite_pos hv) (hd.pos _ (fun i => inv_pos.mpr (hv i))).le + (fun _ _ _ => critical_sum hv) (fun _ _ => critical_pair D hv) + +private theorem correction {a u b Δ ε : ℝ} (ha : 0 < a) (hε : 0 < ε) (hu : ε ≤ u) + (hΔ : 0 ≤ Δ) (hb : b = a * u + Δ) (hb' : b ≤ a) : + 0 ≤ b * Real.log (b / (a * u)) ∧ b * Real.log (b / (a * u)) ≤ Δ / ε := by + have hu' := hε.trans_le hu + have hb₀ : 0 < b := by rw [hb]; positivity + have hh := (one_le_div (mul_pos ha hu')).mpr (show a * u ≤ b by linarith) + have hl := Real.log_nonneg hh + refine ⟨by positivity, ?_⟩ + calc + _ ≤ a * Real.log (b / (a * u)) := mul_le_mul_of_nonneg_right hb' hl + _ ≤ a * (b / (a * u) - 1) := mul_le_mul_of_nonneg_left (Real.log_le_sub_one_of_pos (by + positivity)) ha.le + _ = Δ / u := by rw [hb]; field_simp; ring + _ ≤ Δ / ε := div_le_div_of_nonneg_left hΔ hε hu + +/-- The intercept differences cost at most a constant times the +absolute defect, even when an arm length tends to infinity. -/ +theorem Family.axis_bound (h : Family P (opposite v) (criticalWidth v) (D v⁻¹)) + (hd : StarTripod F D) (hv : Positive v) {ε : ℝ} (hε : 0 < ε) + (hu : ∀ i, ε ≤ criticalWidth v i) (i j : Fin 3) : + axisValue D v P i - axisValue D v P j ≤ (5 / ε ^ 2 + 1 / ε) * defect D v := by + have hz := hd.toTripod.regular.nonneg _ hv + have he := (h.at_critical hd hv).intercepts (opposite_pos hv) hz hε hu (critical_le hv) i j + have hh (i) := correction (inv_pos.mpr (hv i)) hε (hu i) hz (residual_eq D hv i) + (residual_bounds hd hv i).2 + have hi := (hh i).2 + have hj := (hh j).1 + unfold axisValue + simp only [div_eq_mul_inv] at hi hj he ⊢ + linarith only [hi, hj, he] + +theorem axisLimits {Q : Vec → Vec → ℝ} (hd : StarTripod F D) + (h : ∀ v, Positive v → ∃ P : PairPrices, Family P (opposite v) (criticalWidth v) (D v⁻¹) ∧ + ∀ i, Tendsto (fun r => Energy.potential Q v (Energy.near i r)) (𝓝[>] 0) + (𝓝 (axisValue D v P i))) : + Energy.AxisLimits D Q := by + intro v hv + obtain ⟨ε, hε, he⟩ := uniform_width hv + refine ⟨5 / ε ^ 2 + 1 / ε, by positivity, ?_⟩ + intro w hw hw' h₁ h₂ + obtain ⟨P, hp, hlim⟩ := h w hw + exact ⟨axisValue D w P, hlim, hp.axis_bound hd hw hε (he _ hw hw' h₁ h₂)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # The polynomial profile at the origin of a tripod -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Spectral Minimum Filter +open scoped Topology + +variable {F : Type} [Field F] (A : MatrixExponent.Prices.Atlas F Twig) {a v x : Vec} {i j k : Fin 3} + +/-- Computes the root placement by the application `Multi.sites Twig.origin (Twig.mark a)`. -/ +def rootPlacement (a : Vec) : Option (Fin 3) → Twig := Multi.sites Twig.origin (Twig.mark a) + +/-- The quantity computed by `Twig.label A a * Real.log (profile (point A (rootPlacement a)) +x)`. -/ +def rootPrices (a x : Vec) : ℝ := + Twig.label A a * Real.log (profile (point A (rootPlacement a)) x) + +/-- Only the output moves along the geodesic through the origin. -/ +private theorem root_chord (ha : Positive a) (hjk : j ≠ k) (T : Tensor F (Option (Fin 3))) : + (a j + a k) * A.price (rootPlacement a) T ≤ + a j * A.price (Twig.mark a ∘ terminal k) T + a k * A.price (Twig.mark a ∘ terminal j) T := by + let t := a k / (a j + a k) + have hd := add_pos (ha j) (ha k) + have ht : 0 ≤ t := (div_pos (ha k) hd).le + have ht' : t ≤ 1 := (div_le_one hd).mpr (by linarith [ha j]) + have hk : t * (a j + a k) = a k := div_mul_cancel₀ _ hd.ne' + have hj : (1 - t) * (a j + a k) = a j := by linarith + let f l := Twig.mark a ∘ terminal l + have hm (l) : Dist.dist Twig.origin (Twig.mark a l) = a l := by + simp [Twig.mark, Twig.radius, (ha l).le] + have hdist : Dist.dist (Twig.mark a k) (Twig.mark a j) = a j + a k := by + rw [Twig.mark_dist ha ha, ite_eq_right hjk.symm, add_comm] + have h₁ (s) : Dist.dist (f k s) (rootPlacement a s) = t * Dist.dist (f k s) (f j s) := by + cases s with + | some l => simp [f, terminal, rootPlacement, Multi.sites] + | none => + change Dist.dist (Twig.mark a k) Twig.origin = t * Dist.dist (Twig.mark a k) (Twig.mark a j) + rw [dist_comm, hm, hdist, hk] + have h₂ (s) : Dist.dist (rootPlacement a s) (f j s) = (1 - t) * Dist.dist (f k s) (f j s) := by + cases s with + | some l => simp [f, terminal, rootPlacement, Multi.sites] + | none => + change Dist.dist Twig.origin (Twig.mark a j) + = (1 - t) * Dist.dist (Twig.mark a k) (Twig.mark a j) + rw [hm, hdist, hj] + have h := mul_le_mul_of_nonneg_left (A.chord ht ht' h₁ h₂ T) hd.le + rwa [mul_add, ← mul_assoc, ← mul_assoc, mul_comm (a j + a k) (1 - t), hj, mul_comm (a j + a k) t, + hk] at h + +theorem root_label (ha : Positive a) : A.price (rootPlacement a) 2 = Twig.label A a := by + have he (l : Fin 3) : A.price (Twig.mark a ∘ terminal l) 2 = Twig.label A a := by + have hs : Function.Surjective (terminal l) := fun m => ⟨some m, rfl⟩ + rw [A.place, Function.comp_apply, Tensor.place_eq_group _ hs, map_ofNat] + rfl + apply le_antisymm + · have h := root_chord A ha (j := 0) (k := 1) (by decide) 2 + rw [he, he, ← add_mul] at h + exact le_of_mul_le_mul_left h (add_pos (ha 0) (ha 1)) + · change A.price (rootPlacement a ∘ some) 2 ≤ _ + rw [A.place, Function.comp_apply] + apply Multi.monotone_price + have h := Tensor.place_add_le (K := F) (some : Fin 3 → Option (Fin 3)) 1 1 + simp only [Tensor.place_one, one_add_one_eq_two] at h + exact h + +variable [Infinite F] + +theorem root_limit (ha : Positive a) (hx : Positive x) + {α : Type*} {l : Filter α} {N : α → ℝ} (hN : Tendsto N l atTop) {L : α → Fin 3 → ℕ} + (hL : ∀ i, Tendsto (fun n => (L n i : ℝ) / N n) l (𝓝 (x i))) : + Tendsto (fun n => Real.log 2 * A.price (rootPlacement a) (polynomial F (L n)) - + Twig.label A a * Real.log (N n)) l (𝓝 (rootPrices A a x)) := by + have h := (log_profile_limit (point_mono A (rootPlacement a)) hx hN hL).const_mul (Twig.label A a) + apply h.congr' + filter_upwards [] with n + rw [price_eq A (rootPlacement a), root_label A ha, mul_sub] + +theorem root_growth (hA : Twig.Homogeneous A) (ha : Positive a) : + Energy.Growth (rootPrices A a) (Twig.label A a) := by + let f := point A (rootPlacement a) + have hf : Monotone f := point_mono A _ + have hp := hA.star.pos a ha + refine ⟨hp, ?_, ?_⟩ + · intro x hx s hs + have he : profile f (s • x) = s * profile f x := (scaling_polynomial f hf).scale_smul hx hs + unfold rootPrices + rw [he, Real.log_mul hs.ne' (profile_pos hf hx).ne'] + ring + · intro x hx + exact mul_le_mul_of_nonneg_left (Real.log_le_log (profile_pos hf hx) + ((scaling_polynomial f hf).scale_bound hx)) hp.le + +private def floors (x : Vec) (N : ℝ) (i : Fin 3) := ⌊x i * N⌋₊ + +private theorem floor_lim (hx : Positive x) (i : Fin 3) : + Tendsto (fun N : ℝ => (floors x N i : ℝ) / N) atTop (𝓝 (x i)) := + tendsto_nat_floor_mul_div_atTop (hx i).le + +private theorem floors_pos (hx : Positive x) (i : Fin 3) : + ∀ᶠ N : ℝ in atTop, 0 < floors x N i := by + filter_upwards [eventually_ge_atTop (1 / x i)] with N hN + exact Nat.floor_pos.mpr (by rw [mul_comm]; exact (div_le_iff₀ (hx i)).mp hN) + +private theorem pair_lim (a : Vec) (hx : Positive x) (hij : i ≠ j) : + Tendsto (fun N : ℝ => + Real.log 2 * A.price (placement (Twig.mark a) i j) + (polynomial F (two (floors x N i) (floors x N j))) - Twig.label A a * Real.log N) + atTop (𝓝 (pairs A (Twig.mark a) i j (x i) (x j))) := by + apply pairs_limit A (Twig.mark a) hij (hx i) (hx j) tendsto_id + rintro (_ | _) <;> exact floor_lim hx _ + +theorem profile_pairing (ha : Positive a) (hx : Positive x) + (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) (hk : x k = x i + x j) : + pairs A (Twig.mark a) i j (x i) (x j) ≤ rootPrices A a x := by + refine le_of_tendsto_of_tendsto (pair_lim A a hx hij) + (root_limit A ha hx tendsto_id (floor_lim hx)) ?_ + filter_upwards [floors_pos hx i, eventually_ge_atTop 0] with N h₁ hN + have h₂ : floors x N i + floors x N j ≤ floors x N k := by + unfold floors + rw [hk, add_mul] + apply Nat.le_floor + rw [Nat.cast_add] + exact add_le_add (Nat.floor_le (mul_nonneg (hx i).le hN)) (Nat.floor_le (mul_nonneg (hx j).le + hN)) + apply sub_le_sub_right + apply mul_le_mul_of_nonneg_left _ (by positivity) + rw [show placement (Twig.mark a) i j = rootPlacement a ∘ (some ∘ pairSite i j) from rfl, + A.place, Function.comp_apply] + exact Multi.monotone_price A _ (extract_pair hij hik hjk h₁ h₂) + +theorem profile_chord (ha : Positive a) (hx : Positive x) + (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + (a j + a k) * rootPrices A a x ≤ + a j * pairs A (Twig.mark a) i j (x i) (x j) + a k * pairs A (Twig.mark a) i k (x i) (x k) + := by + refine le_of_tendsto_of_tendsto + ((root_limit A ha hx tendsto_id (floor_lim hx)).const_mul (a j + a k)) + (((pair_lim A a hx hij).const_mul (a j)).add ((pair_lim A a hx hik).const_mul (a k))) ?_ + filter_upwards [floors_pos hx i] with N h₁ + let T := polynomial F (floors x N) + have hbound {j k} (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + A.price (Twig.mark a ∘ terminal k) T ≤ A.price (placement (Twig.mark a) i j) + (polynomial F (two (floors x N i) (floors x N j))) := by + rw [placement, A.place, A.place] + exact Multi.monotone_price A _ (absorb hij hik hjk h₁) + have h := (root_chord A ha hjk T).trans + (add_le_add (mul_le_mul_of_nonneg_left (hbound hij hik hjk) (ha j).le) + (mul_le_mul_of_nonneg_left (hbound hik hij hjk.symm) (ha k).le)) + have h' := mul_le_mul_of_nonneg_left h (show 0 ≤ Real.log 2 by positivity) + dsimp only [id_eq, T] at h' ⊢ + linarith only [h'] + +theorem root (hA : Twig.Homogeneous A) (hv : Positive v) + (hf : Family (pairs A (Twig.mark v⁻¹)) (opposite v) (criticalWidth v) (Twig.label A v⁻¹)) : + Energy.Root (Twig.label A) v (rootPrices A v⁻¹) (pairs A (Twig.mark v⁻¹)) := by + have ha : Positive v⁻¹ := fun i => inv_pos.mpr (hv i) + refine ⟨root_growth A hA ha, hf, ?_, ?_⟩ + · intro i j k hij hik hjk x hx + rw [opposite_eq v hij hik hjk] + exact profile_chord A ha hx hij hik hjk + · intro i j k hij hik hjk x hx hk + exact profile_pairing A ha hx hij hik hjk hk + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Scale.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Scale.lean new file mode 100644 index 0000000000..65ba76395b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Profile/Scale.lean @@ -0,0 +1,761 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Log.Basic +public import Mathlib.Analysis.SpecificLimits.Basic +public import Mathlib.Analysis.Convex.Slope +public import Mathlib.Algebra.Order.Archimedean.Real.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Minimum.FaceZero + +/-! +# Dilation and the two one-coordinate slopes + +Vary one width forward and the other backward by reciprocal factors. +Homogeneity gives the exact difference of the two log-prices. Taking +the limit in rational lower bounds on the increments needs no +differentiability of the two-width profile. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Filter +open scoped Topology + +private theorem log_growth {x y p r : ℝ} (hp : 0 < p) (hr : 0 ≤ r) + (h : r ≤ Real.exp (y / p) - Real.exp (x / p)) : + p * r / (Real.exp (x / p) + r) ≤ y - x ∧ p * r / Real.exp (y / p) ≤ y - x := by + let a := Real.exp (x / p) + have ha : 0 < a := Real.exp_pos _ + have hb : 0 < a + r := by positivity + have hc : a + r ≤ Real.exp (y / p) := by unfold a; linarith + have hd := Real.log_le_sub_one_of_pos (div_pos ha hb) + rw [Real.log_div ha.ne' hb.ne', show Real.log a = x / p from Real.log_exp _] at hd + have he := Real.log_le_log hb hc + rw [Real.log_exp] at he + have heq : a / (a + r) - 1 = -r / (a + r) := by field_simp; ring + rw [heq, neg_div] at hd + have hlo : p * r / (a + r) ≤ y - x := by + rw [mul_div_assoc, mul_comm, ← le_div_iff₀ hp, sub_div] + linarith + exact ⟨hlo, (div_le_div_of_nonneg_left (by positivity) hb hc).trans hlo⟩ + +theorem pair_growth (P : ℝ → ℝ → ℝ) {x y a b L M D : ℝ} + (hx : 0 < x) (hy : 0 < y) (ha : 0 < a) (hb : 0 < b) + (hL : 0 < L) (hM : 0 < M) (hD : 0 ≤ D) + (hscale : ∀ u : ℝ, 1 < u → P x (u * y) = P (x / u) y + D * Real.log u) + (h₁ : ∀ t, y ≤ t → L * (t - y) ≤ Real.exp (P x t / a) - Real.exp (P x y / a)) + (h₂ : ∀ s, 0 < s → s ≤ x → M * (x - s) ≤ Real.exp (P x y / b) - Real.exp (P s y / b)) : + a * y * (L / Real.exp (P x y / a)) + b * x * (M / Real.exp (P x y / b)) ≤ D := by + let F (t : ℝ) := a * y * L / (Real.exp (P x y / a) + L * t * y) + + b * x * M / ((1 + t) * Real.exp (P x y / b)) + have hbound (t : ℝ) (ht : 0 < t) : F t ≤ D := by + have hu : 1 < 1 + t := by linarith + have hx' : x / (1 + t) ≤ x := div_le_self hx.le hu.le + have hy' : y ≤ (1 + t) * y := le_mul_of_one_le_left hy.le hu.le + have hl := (log_growth ha (mul_nonneg hL.le (sub_nonneg.mpr hy')) (h₁ _ hy')).1 + have hr := (log_growth hb (mul_nonneg hM.le (sub_nonneg.mpr hx')) + (h₂ _ (by positivity) hx')).2 + rw [show L * ((1 + t) * y - y) = L * t * y by ring, hscale (1 + t) hu] at hl + have hh : Real.log (1 + t) ≤ t := by + linarith [Real.log_le_sub_one_of_pos (by positivity : 0 < 1 + t)] + apply le_of_mul_le_mul_right _ ht + calc + F t * t = a * (L * t * y) / (Real.exp (P x y / a) + L * t * y) + + b * (M * (x - x / (1 + t))) / Real.exp (P x y / b) := by + unfold F + rw [show x - x / (1 + t) = x * t / (1 + t) by field_simp; ring] + simp only [div_eq_mul_inv, mul_inv_rev] + ring + _ ≤ D * Real.log (1 + t) := by linarith only [hl, hr] + _ ≤ D * t := mul_le_mul_of_nonneg_left hh hD + have hc : ContinuousAt F 0 := by unfold F; fun_prop (disch := positivity) + have hh : F 0 ≤ D := le_of_tendsto (hc.continuousWithinAt (s := Set.Ioi 0)) + (Filter.Eventually.mono self_mem_nhdsWithin hbound) + simpa [F, mul_div_assoc] using hh + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- +# A continuum profile from integer dilations + +Approximate each ray from below by a common rescaling of a lattice +point. Integer dilation makes every such lower bound valid eventually. +Slightly enlarging the target widths bounds arbitrary approximations +from above. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Set Filter +open scoped Topology + +variable {ι : Type*} [Fintype ι] + +/-- The data for the scaling construction, including `nonneg`, `mono`, `bound`, `dilate`. -/ +structure Scaling (M : (ι → ℕ) → ℝ) : Prop where + nonneg : ∀ L, 0 ≤ M L + mono : Monotone M + bound : ∀ L, M L ≤ ∑ i, (L i : ℝ) + dilate : ∀ (k : ℕ) L, (k : ℝ) * M L ≤ M (fun i => k * L i) + +/-- The quantity computed by `{v | ∃ L : ι → ℕ, ∃ c : ℝ, 0 < c ∧ (∀ i, c * L i < t i) ∧ v = c * +M L}`. -/ +def candidates (M : (ι → ℕ) → ℝ) (t : ι → ℝ) : Set ℝ := + {v | ∃ L : ι → ℕ, ∃ c : ℝ, 0 < c ∧ (∀ i, c * L i < t i) ∧ v = c * M L} + +/-- The supremum of `(candidates M t)`. -/ +def scale (M : (ι → ℕ) → ℝ) (t : ι → ℝ) := sSup (candidates M t) + +namespace Scaling + +variable {M : (ι → ℕ) → ℝ} (h : Scaling M) {t u : ι → ℝ} {c : ℝ} + +omit [Fintype ι] in +private theorem inhabited (ht : ∀ i, 0 < t i) : (candidates M t).Nonempty := + ⟨1 * M 0, 0, 1, zero_lt_one, by simpa using ht, rfl⟩ + +include h + +private theorem upper : ∑ i, t i ∈ upperBounds (candidates M t) := by + rintro _ ⟨L, c, hc, hL, rfl⟩ + calc + _ ≤ c * ∑ i, (L i : ℝ) := mul_le_mul_of_nonneg_left (h.bound L) hc.le + _ ≤ _ := by rw [Finset.mul_sum]; exact Finset.sum_le_sum (fun i _ => (hL i).le) + +theorem scale_bound (ht : ∀ i, 0 < t i) : scale M t ≤ ∑ i, t i := + csSup_le (inhabited ht) h.upper + +theorem le_scale {L : ι → ℕ} (hc : 0 < c) (hL : ∀ i, c * L i < t i) : c * M L ≤ scale M t := + le_csSup ⟨_, h.upper⟩ ⟨L, c, hc, hL, rfl⟩ + +theorem scale_nonneg (ht : ∀ i, 0 < t i) : 0 ≤ scale M t := by + have := h.le_scale (L := 0) (t := t) zero_lt_one (by simpa using ht) + simpa using (mul_nonneg zero_le_one (h.nonneg 0)).trans this + +theorem scale_pos (ht : ∀ i, 0 < t i) {L : ι → ℕ} (hL : 0 < M L) : 0 < scale M t := by + have he : ∀ᶠ c in 𝓝[>] (0 : ℝ), ∀ i, c * L i < t i := by + apply eventually_all.mpr + intro i + have hd : Tendsto (fun c : ℝ => c * L i) (𝓝[>] 0) (𝓝 0) := by + have h₀ : Tendsto (fun c : ℝ => c) (𝓝[>] 0) (𝓝 0) := tendsto_id.mono_left nhdsWithin_le_nhds + simpa using h₀.mul_const (L i : ℝ) + exact hd.eventually_lt_const (ht i) + obtain ⟨c, hc, hc'⟩ := (he.and self_mem_nhdsWithin).exists + exact (mul_pos hc' hL).trans_le (h.le_scale hc' hc) + +theorem scale_mono (ht : ∀ i, 0 < t i) (htu : t ≤ u) : scale M t ≤ scale M u := by + apply csSup_le (inhabited ht) + rintro _ ⟨L, c, hc, hL, rfl⟩ + exact h.le_scale hc (fun i => (hL i).trans_le (htu i)) + +theorem scale_smul (ht : ∀ i, 0 < t i) (hc : 0 < c) : scale M (c • t) = c * scale M t := by + have hu : ∀ i, 0 < (c • t) i := fun i => mul_pos hc (ht i) + apply le_antisymm + · apply csSup_le (inhabited hu) + rintro _ ⟨L, a, ha, hL, rfl⟩ + have he : ∀ i, (a / c) * L i < t i := by + intro i + rw [div_mul_eq_mul_div, div_lt_iff₀ hc, mul_comm (t i)] + exact hL i + have hh := h.le_scale (div_pos ha hc) he + rwa [div_mul_eq_mul_div, div_le_iff₀ hc, mul_comm (scale M t)] at hh + · rw [mul_comm, ← le_div_iff₀ hc] + apply csSup_le (inhabited ht) + rintro _ ⟨L, a, ha, hL, rfl⟩ + rw [le_div_iff₀ hc, mul_comm _ c, ← mul_assoc] + apply h.le_scale (mul_pos hc ha) + intro i + rw [mul_assoc] + exact mul_lt_mul_of_pos_left (hL i) hc + +private theorem enlarge (ht : ∀ i, 0 < t i) {b : ℝ} (hb : scale M t < b) : + ∃ u : ι → ℝ, (∀ i, t i < u i) ∧ scale M u < b := by + have he : ∀ᶠ c in 𝓝[>] (1 : ℝ), c * scale M t < b := + ((tendsto_id.mono_left nhdsWithin_le_nhds).mul_const _).eventually_lt_const (by simpa using hb) + obtain ⟨c, hc, hc'⟩ := (he.and self_mem_nhdsWithin).exists + refine ⟨c • t, fun i => lt_mul_of_one_lt_left (ht i) hc', ?_⟩ + rwa [h.scale_smul ht (zero_lt_one.trans hc')] + +theorem scale_continuous (ht : ∀ i, 0 < t i) : ContinuousAt (scale M) t := by + apply tendsto_order.mpr + constructor + · intro a ha + obtain ⟨_, ⟨L, c, hc, hL, rfl⟩, ha'⟩ := exists_lt_of_lt_csSup (inhabited ht) ha + have he : ∀ᶠ u in 𝓝 t, ∀ i, c * L i < u i := eventually_all.mpr + (fun i => (continuous_apply i).continuousAt.tendsto.eventually_const_lt (hL i)) + exact he.mono fun _ hu => ha'.trans_le (h.le_scale hc hu) + · intro b hb + obtain ⟨u, hu, hu'⟩ := h.enlarge ht hb + have he : ∀ᶠ v in 𝓝 t, ∀ i, 0 < v i ∧ v i < u i := eventually_all.mpr (fun i => + (continuous_apply i).continuousAt.tendsto.eventually (Ioo_mem_nhds (ht i) (hu i))) + exact he.mono fun _ hv => (h.scale_mono (fun i => (hv i).1) (fun i => (hv i).2.le)).trans_lt hu' + +theorem limit (ht : ∀ i, 0 < t i) {α : Type*} {l : Filter α} {N : α → ℝ} + (hN : Tendsto N l atTop) {L : α → ι → ℕ} + (hL : ∀ i, Tendsto (fun n => (L n i : ℝ) / N n) l (𝓝 (t i))) : + Tendsto (fun n => M (L n) / N n) l (𝓝 (scale M t)) := by + apply tendsto_order.mpr + constructor + · intro a ha + obtain ⟨_, ⟨W, c, hc, hW, rfl⟩, ha'⟩ := exists_lt_of_lt_csSup (inhabited ht) ha + let k n := ⌈c * N n⌉₊ + have hk : Tendsto (fun n => (k n : ℝ) / N n) l (𝓝 c) := + (tendsto_nat_ceil_mul_div_atTop hc.le).comp hN + have he : ∀ᶠ n in l, ∀ i, (k n : ℝ) / N n * W i < L n i / N n := + eventually_all.mpr (fun i => (hk.mul_const _).eventually_lt (hL i) (hW i)) + filter_upwards [hN.eventually_gt_atTop 0, he] with n hn he + have hw : (fun i => k n * W i) ≤ L n := by + intro i + specialize he i + rw [div_mul_eq_mul_div, div_lt_div_iff_of_pos_right hn] at he + exact_mod_cast he.le + refine ha'.trans_le ((le_div_iff₀ hn).mpr ?_) + rw [mul_right_comm] + exact (mul_le_mul_of_nonneg_right (Nat.le_ceil _) (h.nonneg W)).trans + ((h.dilate _ _).trans (h.mono hw)) + · intro b hb + obtain ⟨u, hu, hu'⟩ := h.enlarge ht hb + have he := eventually_all.mpr (fun i => (hL i).eventually_lt_const (hu i)) + filter_upwards [hN.eventually_gt_atTop 0, he] with n hn he + refine lt_of_le_of_lt ?_ hu' + rw [div_eq_inv_mul] + apply h.le_scale (inv_pos.mpr hn) + simpa only [← div_eq_inv_mul] using he + +theorem floor_limit (ht : ∀ i, 0 < t i) : + Tendsto (fun N : ℝ => M (fun i => ⌊N * t i⌋₊) / N) atTop (𝓝 (scale M t)) := by + apply h.limit ht tendsto_id + intro i + simpa only [id_eq, mul_comm (t i)] using tendsto_nat_floor_mul_div_atTop (ht i).le + +end Scaling +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- +# Common slope of two coupled rows + +Taking the supremum of a two-width quotient gives the common limiting +slope. A single tripling beyond the widths under test bounds that +quotient by every earlier secant, even at unequal widths. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Set + +/-- The data for the curve construction, including `pos`, `concave`, `trip`. -/ +structure Curve (f g : ℝ → ℝ) (a : ℝ) : Prop where + pos : ∀ x, 0 < x → 0 < f x + concave : ConcaveOn ℝ (Ioi 0) f + trip : ∀ x, 0 < x → 2 * f x + g x ≤ f (3 * x + a) + +variable {f g : ℝ → ℝ} {a L x y z s t N : ℝ} + +private theorem Curve.advance (h : Curve f g a) (ha : 0 < a) (hs : 0 < s) (ht : s < t) + (hN : t ≤ N) (hL : L * (2 * N + a) = f N + g N) : L * (t - s) ≤ f t - f s := by + have hN' : 0 < N := (hs.trans ht).trans_le hN + have hz : N < 3 * N + a := by linarith + have lo : L ≤ (f (3 * N + a) - f N) / (3 * N + a - N) := + (le_div_iff₀ (sub_pos.mpr hz)).2 (by linarith [h.trip N hN']) + apply (le_div_iff₀ (sub_pos.mpr ht)).mp + rcases eq_or_lt_of_le hN with rfl | hN + · exact lo.trans (h.concave.slope_anti_adjacent hs (hs.trans (ht.trans hz)) ht hz) + · exact lo.trans ((h.concave.slope_anti_adjacent (hs.trans ht) (hN'.trans hz) hN hz).trans + (h.concave.slope_anti_adjacent hs hN' ht hN)) + +/-- The quantity computed by `{v | ∃ y z : ℝ, 0 < y ∧ 0 < z ∧ v = (f y + g z) / (y + z + a)}`. -/ +def ratios (f g : ℝ → ℝ) (a : ℝ) : Set ℝ := + {v | ∃ y z : ℝ, 0 < y ∧ 0 < z ∧ v = (f y + g z) / (y + z + a)} + +/-- The supremum of `(ratios f g a)`. -/ +def common (f g : ℝ → ℝ) (a : ℝ) := sSup (ratios f g a) + +theorem common_comm (f g : ℝ → ℝ) (a : ℝ) : common f g a = common g f a := by + unfold common + congr 1 + ext v + constructor <;> rintro ⟨y, z, hy, hz, rfl⟩ <;> exact ⟨z, y, hz, hy, by ring⟩ + +private theorem upper (ha : 0 < a) (hf : Curve f g a) (hg : Curve g f a) + (hs : 0 < s) (ht : s < t) : (f t - f s) / (t - s) ∈ upperBounds (ratios f g a) := by + rintro _ ⟨y, z, hy, hz, rfl⟩ + let N := t + y + z + have hN : 0 < N := by unfold N; linarith + let L := (f N + g N) / (2 * N + a) + have he : L * (2 * N + a) = f N + g N := div_mul_cancel₀ _ (by positivity) + have h₁ := hf.advance ha hy (by unfold N; linarith : y < N) le_rfl he + have h₂ := hg.advance ha hz (by unfold N; linarith : z < N) le_rfl (he.trans (add_comm _ _)) + have h₃ := hf.advance ha hs ht (by unfold N; linarith : t ≤ N) he + refine le_trans ?_ ((le_div_iff₀ (sub_pos.mpr ht)).mpr h₃) + exact (div_le_iff₀ (by positivity)).mpr (by linarith only [h₁, h₂, he]) + +theorem common_bound (ha : 0 < a) (hf : Curve f g a) (hg : Curve g f a) + (hy : 0 < y) (hz : 0 < z) : f y + g z ≤ common f g a * (y + z + a) := by + apply (div_le_iff₀ (by positivity)).mp + exact le_csSup ⟨_, upper ha hf hg zero_lt_one (by norm_num : (1 : ℝ) < 2)⟩ ⟨y, z, hy, hz, rfl⟩ + +theorem common_pos (ha : 0 < a) (hf : Curve f g a) (hg : Curve g f a) : 0 < common f g a := + pos_of_mul_pos_left ((add_pos (hf.pos 1 zero_lt_one) (hg.pos 1 zero_lt_one)).trans_le + (common_bound ha hf hg zero_lt_one zero_lt_one)) (by positivity) + +theorem common_step (ha : 0 < a) (hf : Curve f g a) (hg : Curve g f a) + (hs : 0 < s) (ht : s ≤ t) : common f g a * (t - s) ≤ f t - f s := by + rcases eq_or_lt_of_le ht with rfl | ht + · simp + apply (le_div_iff₀ (sub_pos.mpr ht)).mp + exact csSup_le ⟨_, 1, 1, zero_lt_one, zero_lt_one, rfl⟩ (upper ha hf hg hs ht) + +theorem common_lower (ha : 0 < a) (hf : Curve f g a) (hg : Curve g f a) (hx : 0 < x) : + common f g a * x ≤ f x := by + by_contra! he + let L := common f g a + have hL := common_pos ha hf hg + let s := x - f x / L + have hs : 0 < s := sub_pos.mpr ((div_lt_iff₀ hL).2 (by linarith)) + have hs' : s ≤ x := sub_le_self _ (div_nonneg (hf.pos _ hx).le hL.le) + have h := common_step ha hf hg hs hs' + have hh : L * (x - s) = f x := by unfold s; rw [sub_sub_cancel, mul_div_cancel₀ _ hL.ne'] + rw [hh] at h + linarith [hf.pos _ hs] + +theorem common_upper (ha : 0 < a) (hf : Curve f g a) (hg : Curve g f a) (hx : 0 < x) : + f x ≤ common f g a * (x + a) := by + have he := common_lower ha hg hf hx + rw [common_comm g f] at he + linarith only [he, common_bound ha hf hg hx hx] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +section +/- +# Strong minimum principle for a homogeneous defect + +A positive value on one coordinate ray makes its integral decrease +strictly at first order under radial dilation. Telescoping the three +coordinate increments bounds any such decrease by an arbitrarily +small multiple of the dilation parameter. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +open Filter Set + +variable {D : Vec → ℝ} {v w : Vec} + +private theorem ray_vanishes (h : Regular D) (hc : Comparison D) + (hv : Positive v) (hz : D v = 0) (k : Fin 3) {t : ℝ} (ht : 0 ≤ t) : + D (move v k t) = 0 := by + change ray D v k t = 0 + rcases eq_or_lt_of_le ht with rfl | ht + · simpa + have hn : ∀ u, 0 ≤ u → 0 ≤ ray D v k u := fun _ hu => h.nonneg _ (hv.move k hu) + by_contra hne + obtain ⟨B, hB, hdrop⟩ := dilation (h.continuous _ hv k) hn (by simpa) + ⟨t, ht, (hn t ht.le).lt_of_ne' hne⟩ + obtain ⟨C, hC, hconv⟩ := h.convex v hv + obtain ⟨E, hE, hswitch⟩ := hc v hv + let S := v 0 + v 1 + v 2 + have hS : 0 < S := add_pos (add_pos (hv _) (hv _)) (hv _) + have hmax (i : Fin 3) : v i ≤ S := by + unfold S + rw [← Fin.sum_univ_three] + exact Finset.single_le_sum (fun j _ => (hv j).le) (Finset.mem_univ i) + let R := B / (8 * (C * S + 1)) + have hR : 0 < R := by unfold R; positivity + have hcost : 2 * C * S * R ≤ B / 4 := by + have he : R * (8 * (C * S + 1)) = B := div_mul_cancel₀ _ (by positivity) + linarith + let r := R / (2 * Real.exp (2 * E + 4)) + have hr : 0 < r := by unfold r; positivity + have hr' : 2 * r ≤ R := by + have he : r * (2 * Real.exp (2 * E + 4)) = R := div_mul_cancel₀ _ (by positivity) + have he' : 1 ≤ Real.exp (2 * E + 4) := Real.one_le_exp (by linarith) + nlinarith only [he, he', hr] + have hlog : Real.log (R / (2 * r)) = 2 * E + 4 := by + have he : R / (2 * r) = Real.exp (2 * E + 4) := by unfold r; field_simp + rw [he, Real.log_exp] + let ε := min 1 (r / (S * (2 * E + 6))) + have hε : 0 < ε := by unfold ε; positivity + have hε' : ε ≤ 1 := min_le_left _ _ + have hstep (i : Fin 3) : ε * v i * (2 * E + 6) ≤ r := calc + _ ≤ ε * S * (2 * E + 6) := by gcongr; apply hmax + _ ≤ r := by + rw [mul_assoc] + exact (le_div_iff₀ (by positivity)).mp (min_le_right _ _) + let ζ := ε * B / 16 + have hζ : 0 < ζ := by unfold ζ; positivity + have hl := telescope h hv hz hC hE hconv + (fun w hw i j => hswitch w hw i j ζ hζ) hε hε' hr hr' hlog hstep k + obtain ⟨T, hT, hu, hl⟩ := ((eventually_ge_atTop 1).and ((hdrop ε hε hε').and hl)).exists + have he : J D ((1 + ε) • v) k T = + price (fun t => ray D v k (t / (1 + ε)) / (1 + ε)) (1 / T) T := by + unfold J price + apply intervalIntegral.integral_congr + intro u hu + have hu₀ : 0 ≤ u := (le_min (by positivity) (by positivity)).trans hu.1 + exact congrArg (· / u) (h.scale hv k (by positivity : 0 < 1 + ε) hu₀) + rw [he] at hl + change -2 * C * ε * S * R - 4 * ζ ≤ _ - price (ray D v k) (1 / T) T at hl + unfold ζ at hl + linarith only [hu, hl, mul_le_mul_of_nonneg_left hcost hε.le, mul_pos hε hB] + +private theorem vanishes_above (h : Regular D) (hc : Comparison D) + (hv : Positive v) (hz : D v = 0) (hvw : v ≤ w) : D w = 0 := by + let p (n : ℕ) (i : Fin 3) := if i.val < n then w i else v i + have hp (n : ℕ) : Positive (p n) := by + intro i + unfold p + split_ifs + · exact (hv i).trans_le (hvw i) + · exact hv i + have hh (i : Fin 3) (hi : D (p i.val) = 0) : D (p (i.val + 1)) = 0 := by + have he : p (i.val + 1) = move (p i.val) i (w i - v i) := by + funext j + by_cases he : j = i + · subst j; simp [move, p] + · have hj : j.val < i.val + 1 ↔ j.val < i.val := by omega + simp only [move, Function.update_of_ne he, p, hj] + rw [he] + exact ray_vanishes h hc (hp _) hi i (sub_nonneg.mpr (hvw i)) + have h₀ : p 0 = v := by funext i; simp [p] + have h₃ : p 3 = w := by funext i; simp [p, i.isLt] + rw [← h₃] + exact hh 2 (hh 1 (hh 0 (h₀.symm ▸ hz))) + +/-- A single interior zero forces vanishing throughout the positive orthant. -/ +theorem vanishes (h : Regular D) (hc : Comparison D) + (hv : Positive v) (hz : D v = 0) (hw : Positive w) : D w = 0 := by + let s := ∑ i, v i / w i + have hp (i) : 0 < v i / w i := div_pos (hv i) (hw i) + have hs : 0 < s := Finset.sum_pos (fun i _ => hp i) Finset.univ_nonempty + have hvw : v ≤ s • w := by + intro i + exact (div_le_iff₀ (hw i)).mp + (Finset.single_le_sum (fun j _ => (hp j).le) (Finset.mem_univ i)) + have he := vanishes_above h hc hv hz hvw + rw [h.homogeneous w hw s hs, div_eq_zero_iff] at he + exact he.resolve_right hs.ne' + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Minimum +end + +section +/- +# Matching intercepts at the three critical width pairs + +Write each log-price as its first intercept plus a normalized +displacement. The two displacements in each row sum to at most +zero. Across an edge the two displacements sum to at least minus +the scaled defect. A displacement exceeding twice this error would +force the three intercepts to increase strictly around a cycle. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Minimum + +variable {u c d : Vec} {p : Fin 3 → Fin 3 → ℝ} {ε Δ : ℝ} + +private theorem third (i j : Fin 3) (h : i ≠ j) : ∃ k : Fin 3, i ≠ k ∧ j ≠ k := by + fin_cases i <;> fin_cases j <;> first | contradiction | decide + +/-- Price at a critical width pair, shared between its two orders. -/ +structure Critical (u c d : Vec) (p : Fin 3 → Fin 3 → ℝ) (Δ : ℝ) : Prop where + symm : ∀ i j, p i j = p j i + row : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → p i j + p i k ≤ 2 * c i + edge : ∀ i j, i ≠ j → + d i * u j * Real.exp ((c i - p i j) / d i) + d j * u i * Real.exp ((c j - p j i) / d j) ≤ + d i * u j + d j * u i + Δ + +private theorem linearize {d u c p : ℝ} (hd : 0 < d) (hu : 0 ≤ u) : + d * u + u * (c - p) ≤ d * u * Real.exp ((c - p) / d) := by + calc + _ = d * u * ((c - p) / d + 1) := by field_simp; ring + _ ≤ _ := mul_le_mul_of_nonneg_left (Real.add_one_le_exp _) (mul_nonneg hd.le hu) + +private theorem cycle_bound {w : Fin 3 → Fin 3 → ℝ} {c : Vec} {B : ℝ} + (hB : 0 ≤ B) (he : ∀ i j, i ≠ j → -B ≤ w i j + w j i) + (hr : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → w i j + w i k ≤ 0) + (hc : ∀ i j, 0 < w i j → w j i < 0 → c i < c j) + (i j : Fin 3) (h : i ≠ j) : w i j ≤ 2 * B := by + by_contra! hh + obtain ⟨k, hik, hjk⟩ := third i j h + have h₁ := hr i j k h hik hjk + have h₂ := he i k hik + have h₃ := hr k i j hik.symm hjk.symm h + have h₄ := he k j hjk.symm + have h₅ := hr j k i hjk h.symm hik.symm + have e₁ := hc i j (by linarith) (by linarith) + have e₂ := hc j k (by linarith) (by linarith) + have e₃ := hc k i (by linarith) (by linarith) + exact (e₁.trans (e₂.trans e₃)).false + +/-- Uniform error at a critical pair. No upper bound on the arm +lengths or distances is needed. -/ +theorem Critical.error (h : Critical u c d p Δ) (hd : Positive d) (hΔ : 0 ≤ Δ) + (hε : 0 < ε) (hlo : ∀ i, ε ≤ u i) (hhi : ∀ i, u i ≤ 1) {i j : Fin 3} (hij : i ≠ j) : + -3 * (Δ / ε ^ 2) ≤ p i j - c i ∧ p i j - c i ≤ 2 * (Δ / ε ^ 2) := by + let w i j := (p i j - c i) / u i + let B := Δ / ε ^ 2 + have hu i := hε.trans_le (hlo i) + have hB : 0 ≤ B := by unfold B; positivity + have heq i j : w i j * u i = p i j - c i := div_mul_cancel₀ _ (hu i).ne' + have he i j (hij : i ≠ j) : -B ≤ w i j + w j i := by + have hi := linearize (c := c i) (p := p i j) (hd i) (hu j).le + have hj := linearize (c := c j) (p := p j i) (hd j) (hu i).le + have hlow : -Δ ≤ (w i j + w j i) * (u i * u j) := by + rw [show (w i j + w j i) * (u i * u j) = (w i j * u i) * u j + (w j i * u j) * u i by ring, + heq, heq] + linarith only [hi, hj, h.edge i j hij] + apply le_of_mul_le_mul_right _ (mul_pos (hu i) (hu j)) + refine le_trans ?_ hlow + have he : ε ^ 2 ≤ u i * u j := by rw [pow_two]; exact mul_le_mul (hlo i) (hlo j) hε.le (hu i).le + have := mul_le_mul_of_nonneg_left he hB + rw [show B * ε ^ 2 = Δ from div_mul_cancel₀ _ (by positivity)] at this + linarith + have hr i j k (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : w i j + w i k ≤ 0 := by + unfold w + rw [← add_div] + exact div_nonpos_of_nonpos_of_nonneg (by linarith [h.row i j k hij hik hjk]) (hu i).le + have hc i j (hi : 0 < w i j) (hj : w j i < 0) : c i < c j := by + have h₁ := mul_pos hi (hu i) + have h₂ := mul_neg_of_neg_of_pos hj (hu j) + rw [heq] at h₁ h₂ + linarith [h.symm i j] + have h₁ := cycle_bound hB he hr hc i j hij + have h₂ : -3 * B ≤ w i j := by linarith [cycle_bound hB he hr hc j i hij.symm, he i j hij] + rw [← heq] + have h₃ := mul_le_of_le_one_right hB (hhi i) + constructor + · exact (by linarith : -3 * B ≤ -3 * B * u i).trans (mul_le_mul_of_nonneg_right h₂ (hu i).le) + · exact (mul_le_mul_of_nonneg_right h₁ (hu i).le).trans (by linarith : 2 * B * u i ≤ 2 * B) + +theorem Critical.intercepts (h : Critical u c d p Δ) (hd : Positive d) (hΔ : 0 ≤ Δ) + (hε : 0 < ε) (hlo : ∀ i, ε ≤ u i) (hhi : ∀ i, u i ≤ 1) (i j : Fin 3) : + c i - c j ≤ 5 * (Δ / ε ^ 2) := by + by_cases he : i = j + · subst j; rw [sub_self]; positivity + linarith only [(h.error hd hΔ hε hlo hhi he).1, (h.error hd hΔ hε hlo hhi (Ne.symm he)).2, + h.symm i j] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Critical estimates from polynomial width profiles -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Minimum + +/-- The indexing data represented by `Fin 3 → Fin 3 → ℝ → ℝ → ℝ`. -/ +abbrev PairPrices := Fin 3 → Fin 3 → ℝ → ℝ → ℝ + +/-- The quantity computed by `Real.exp (P i j (u i) t / d i)`. -/ +def row (P : PairPrices) (d u : Vec) (i j : Fin 3) (t : ℝ) : ℝ := + Real.exp (P i j (u i) t / d i) + +/-- The data for the family construction, including `symm`, `scale`, `curve`. -/ +structure Family (P : PairPrices) (d u : Vec) (D : ℝ) : Prop where + symm : ∀ i j x y, P i j x y = P j i y x + scale : ∀ i j, i ≠ j → ∀ s x y : ℝ, 0 < s → 0 < x → 0 < y → + P i j (s * x) (s * y) = P i j x y + D * Real.log s + curve : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → Curve (row P d u i j) (row P d u i k) (u i) + +/-- Common slope at first width `u i`. -/ +def rate (P : PairPrices) (d u : Vec) (i : Fin 3) : ℝ := + common (row P d u i (i + 1)) (row P d u i (i + 2)) (u i) + +/-- The quantity computed by `d i * Real.log (rate P d u i)`. -/ +def intercept (P : PairPrices) (d u : Vec) (i : Fin 3) : ℝ := + d i * Real.log (rate P d u i) + +variable {P : PairPrices} {d u : Vec} {D Δ : ℝ} {i j k : Fin 3} + +theorem rate_eq (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + rate P d u i = common (row P d u i j) (row P d u i k) (u i) := by + have he : (i + 1 = j ∧ i + 2 = k) ∨ (i + 1 = k ∧ i + 2 = j) := by omega + unfold rate + rcases he with ⟨h₁, h₂⟩ | ⟨h₁, h₂⟩ + · rw [h₁, h₂] + · rw [h₁, h₂, common_comm] + +theorem Family.rate_pos (h : Family P d u D) (hu : Positive u) (i : Fin 3) : + 0 < rate P d u i := + common_pos (hu i) (h.curve i (i + 1) (i + 2) (by omega) (by omega) (by omega)) + (h.curve i (i + 2) (i + 1) (by omega) (by omega) (by omega)) + +theorem other : ∃ k, i ≠ k ∧ j ≠ k := by + by_cases he : i + 1 = j + · exact ⟨i + 2, by omega, by omega⟩ + · exact ⟨i + 1, by omega, Ne.symm he⟩ + +theorem Family.step (h : Family P d u D) (hu : Positive u) (hij : i ≠ j) + {x y : ℝ} (hx : 0 < x) (hy : x ≤ y) : + rate P d u i * (y - x) ≤ row P d u i j y - row P d u i j x := by + obtain ⟨k, hik, hjk⟩ := other (i := i) (j := j) + rw [rate_eq hij hik hjk] + exact common_step (hu i) (h.curve i j k hij hik hjk) (h.curve i k j hik hij hjk.symm) hx hy + +private theorem log_pair {x y u v : ℝ} (hu : 0 < u) (hv : 0 < v) + (h : Real.exp (x / u) + Real.exp (y / u) ≤ 2 * v) : x + y ≤ 2 * (u * Real.log v) := by + have he (z : ℝ) : z / u - Real.log v + 1 ≤ Real.exp (z / u) / v := by + simpa [Real.exp_sub, Real.exp_log hv] using Real.add_one_le_exp (z / u - Real.log v) + have hh := add_le_add (he x) (he y) + rw [← add_div (Real.exp _)] at hh + have hv' := (div_le_iff₀ hv).mpr h + have he' : (x + y) / u ≤ 2 * Real.log v := by rw [add_div]; linarith only [hh, hv'] + linarith only [(div_le_iff₀ hu).mp he'] + +theorem Family.critical (h : Family P d u D) (hu : Positive u) (hd : Positive d) + (hD : 0 ≤ D) (hs : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → u i + u j + u k = 2) + (hg : ∀ i j, i ≠ j → D = d i * u j + d j * u i + Δ) : + Critical u (intercept P d u) d (fun i j => P i j (u i) (u j)) Δ := by + refine ⟨fun i j => h.symm _ _ _ _, ?_, ?_⟩ + · intro i j k hij hik hjk + apply log_pair (hd i) (h.rate_pos hu i) + have hb := common_bound (hu i) (h.curve i j k hij hik hjk) (h.curve i k j hik hij hjk.symm) + (hu j) (hu k) + rw [← rate_eq hij hik hjk, hs j k i hjk hij.symm hik.symm, mul_comm] at hb + exact hb + · intro i j hij + have he (i j : Fin 3) : + Real.exp ((intercept P d u i - P i j (u i) (u j)) / d i) = + rate P d u i / Real.exp (P i j (u i) (u j) / d i) := by + rw [intercept, sub_div, mul_div_cancel_left₀ _ (hd i).ne', Real.exp_sub, + Real.exp_log (h.rate_pos hu i)] + rw [he, he, h.symm j i, ← hg i j hij] + apply pair_growth (P i j) (hu i) (hu j) (hd i) (hd j) + (h.rate_pos hu i) (h.rate_pos hu j) hD + · intro t ht + have he := h.scale i j hij t (u i / t) (u j) (by linarith) + (div_pos (hu i) (by linarith)) (hu j) + rwa [mul_div_cancel₀ _ (by linarith : t ≠ 0)] at he + · intro t ht + exact h.step hu hij (hu j) ht + · intro t ht ht' + have hs := h.step hu hij.symm ht ht' + simpa only [row, h.symm j i] using hs + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end + +/- # Global two-input envelope and a sector estimate near contact -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +open Minimum + +variable {P : PairPrices} {d u : Vec} {D : ℝ} (h : Family P d u D) + (hu : Positive u) (hd : Positive d) {i j k : Fin 3} + +/-- The quantity computed by `row P d u i j y / rate P d u i`. -/ +def ratio (P : PairPrices) (d u : Vec) (i j : Fin 3) (y : ℝ) : ℝ := + row P d u i j y / rate P d u i + +/-- The quantity computed by `intercept P d u i + (D - d i) * Real.log (x / u i) + d i * +Real.log y`. -/ +def model (P : PairPrices) (d u : Vec) (D : ℝ) (i : Fin 3) (x y : ℝ) : ℝ := + intercept P d u i + (D - d i) * Real.log (x / u i) + d i * Real.log y + +include h hu in +theorem Family.ratio_pos (i j) (y : ℝ) : 0 < ratio P d u i j y := + div_pos (Real.exp_pos _) (h.rate_pos hu i) + +include h hu hd in +theorem Family.ratio_eq (i j) (y : ℝ) : + ratio P d u i j y = Real.exp ((P i j (u i) y - intercept P d u i) / d i) := by + rw [intercept, sub_div, mul_div_cancel_left₀ _ (hd i).ne', Real.exp_sub, + Real.exp_log (h.rate_pos hu i)] + rfl + +include h hu in +theorem Family.ratio_bounds (hij : i ≠ j) {y : ℝ} (hy : 0 < y) : + y ≤ ratio P d u i j y ∧ ratio P d u i j y ≤ y + u i := by + obtain ⟨k, hik, hjk⟩ := other (i := i) (j := j) + unfold ratio + rw [le_div_iff₀ (h.rate_pos hu i), div_le_iff₀ (h.rate_pos hu i), rate_eq hij hik hjk] + have h₁ := h.curve i j k hij hik hjk + have h₂ := h.curve i k j hik hij hjk.symm + exact ⟨by rw [mul_comm]; exact common_lower (hu i) h₁ h₂ hy, + by rw [mul_comm]; exact common_upper (hu i) h₁ h₂ hy⟩ + +include h hu hd in +theorem Family.price_eq (hij : i ≠ j) {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : + P i j x y = model P d u D i x ((x / u i) * ratio P d u i j (y / (x / u i))) := by + let t := x / u i + have ht : 0 < t := div_pos hx (hu i) + have he := h.scale i j hij t (u i) (y / t) ht (hu i) (div_pos hy ht) + rw [show t * u i = x from div_mul_cancel₀ _ (hu i).ne', mul_div_cancel₀ _ ht.ne'] at he + rw [he, model, Real.log_mul ht.ne' (h.ratio_pos hu i j _).ne', + h.ratio_eq hu hd, Real.log_exp, mul_add, mul_div_cancel₀ _ (hd i).ne'] + unfold t + ring + +private theorem model_mono (hp : 0 ≤ d i) {x s t : ℝ} (hs : 0 < s) (hst : s ≤ t) : + model P d u D i x s ≤ model P d u D i x t := by + unfold model + gcongr + +include h hu hd in +theorem Family.envelope (hij : i ≠ j) {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : + model P d u D i x y ≤ P i j x y ∧ P i j x y ≤ model P d u D i x (y + x) := by + rw [h.price_eq hu hd hij hx hy] + let t := x / u i + have ht : 0 < t := div_pos hx (hu i) + obtain ⟨hl, hr⟩ := h.ratio_bounds hu hij (div_pos hy ht) + have he : t * (y / t) = y := mul_div_cancel₀ _ ht.ne' + have he' : t * u i = x := div_mul_cancel₀ _ (hu i).ne' + have hlo := mul_le_mul_of_nonneg_left hl ht.le + have hhi := mul_le_mul_of_nonneg_left hr ht.le + rw [he] at hlo + rw [mul_add, he, he'] at hhi + exact ⟨model_mono (hd i).le hy hlo, model_mono (hd i).le (hy.trans_le hlo) hhi⟩ + +include h hu in +theorem Family.ratio_sum (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) + {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : + ratio P d u i j x + ratio P d u i k y ≤ x + y + u i := by + unfold ratio + rw [← add_div, div_le_iff₀ (h.rate_pos hu i), mul_comm, rate_eq hij hik hjk] + exact common_bound (hu i) (h.curve i j k hij hik hjk) (h.curve i k j hik hij hjk.symm) hx hy + +include h hu in +theorem Family.ratio_step (hij : i ≠ j) {x y : ℝ} (hx : 0 < x) (hy : x ≤ y) : + y - x ≤ ratio P d u i j y - ratio P d u i j x := by + rw [ratio, ratio, ← sub_div, le_div_iff₀ (h.rate_pos hu i), mul_comm] + exact h.step hu hij hx hy + +include h hu hd in +/-- Control the excess at every width by its value in the companion +row at a single critical width. -/ +theorem Family.ratio_contact {E : ℝ} (hE : 0 ≤ E) + (hs : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → u i + u j + u k = 2) + (herr : ∀ i j, i ≠ j → -E ≤ P i j (u i) (u j) - intercept P d u i) + (hij : i ≠ j) {y : ℝ} (hy : 0 < y) : + ratio P d u i j y ≤ y + 1 - u j + E / d i ∧ + (u j ≤ y → Real.exp (-E / d i) * (y + 1 - u j) ≤ ratio P d u i j y) := by + obtain ⟨k, hik, hjk⟩ := other (i := i) (j := j) + have hlo {j : Fin 3} (hij : i ≠ j) : Real.exp (-E / d i) ≤ ratio P d u i j (u j) := by + rw [h.ratio_eq hu hd] + exact Real.exp_le_exp.mpr (div_le_div_of_nonneg_right (herr i j hij) (hd i).le) + constructor + · have he := (Real.add_one_le_exp (-E / d i)).trans (hlo hik) + rw [neg_div] at he + linarith only [he, hs i j k hij hik hjk, h.ratio_sum hu hij hik hjk hy (hu k)] + · intro h' + have he : Real.exp (-E / d i) ≤ 1 := + Real.exp_le_one_iff.mpr (div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr hE) (hd i).le) + linarith only [hlo hij, h.ratio_step hu hij (hu j) h', + mul_le_mul_of_nonneg_right he (sub_nonneg.mpr h')] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Profile +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Rows.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Rows.lean new file mode 100644 index 0000000000..42169a4857 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Rows.lean @@ -0,0 +1,665 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.GrowthRow +public import Mathlib.Analysis.SpecialFunctions.Log.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Wire +public import Mathlib.Algebra.BigOperators.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Bounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Extension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Model +public import Mathlib.Algebra.MvPolynomial.Eval +public import Mathlib.LinearAlgebra.Dual.Lemmas +public import Mathlib.LinearAlgebra.Finsupp.LinearCombination +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldExtension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Mask +public import Mathlib.Algebra.Field.Shrink +public import Mathlib.Algebra.Ring.Shrink +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure +public import Mathlib.SetTheory.Cardinal.Subfield + +/-! +# Paired secant inequalities for polynomial multiplication + +One application of tripling controls both rows at a common comparison +index. Concavity transports the bound back to *different* indices in +the two rows. The reciprocal inequality then controls a weighted sum +of logarithmic increments. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open MatrixMultiplicationAllFields.TensorSpectrum + +/-- The indices are degrees, one less than the polynomial lengths. -/ +structure Row (f g : ℕ → ℝ) (m : ℕ) : Prop where + pos : ∀ n, 0 < f n + dec : Antitone (rowDifference f) + trip : ∀ n, 2 * f n + g n ≤ f (3 * n + m + 2) + +variable {f g : ℕ → ℝ} {m n : ℕ} + +private theorem Row.slope (h : Row f g m) (n : ℕ) : + (f n + g n) / (2 * (n : ℝ) + m + 2) ≤ rowDifference f n := by + have h₁ := (row_secant_bounds f h.dec n (2 * n + m + 2)).1 + rw [show n + (2 * n + m + 2) = 3 * n + m + 2 by omega] at h₁ + push_cast at h₁ + apply (div_le_iff₀ (by positivity)).mpr + linarith [h.trip n] + +private theorem Row.increase (h : Row f g m) {L : ℝ} (hL : L ≤ rowDifference f n) + {j k : ℕ} (hk : j + k ≤ n) : f j + k * L ≤ f (j + k) := by + refine le_trans ?_ (row_secant_bounds f h.dec j k).2 + gcongr + exact hL.trans (h.dec hk) + +private theorem log_increase {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : + (y - x) / y ≤ Real.log y - Real.log x := by + have h := Real.log_le_sub_one_of_pos (div_pos hx hy) + rw [Real.log_div hx.ne' hy.ne'] at h + rw [sub_div, div_self hy.ne'] + linarith + +/-- Lower bound on a pair of increments per unit increase of the index. -/ +theorem paired_secants (hf : Row f g m) (hg : Row g f m) (j k b c : ℕ) + (hb : 0 < b) (hc : 0 < c) : + 4 / (m + (j + b) + (k + c) + 2 : ℕ) ≤ + (Real.log (f (j + b)) - Real.log (f j)) / b + + (Real.log (g (k + c)) - Real.log (g k)) / c := by + let N := (j + b) + (k + c) + let L := (f N + g N) / (2 * (N : ℝ) + m + 2) + have hL : 0 < L := div_pos (add_pos (hf.pos _) (hg.pos _)) (by positivity) + have hLf : L ≤ rowDifference f N := hf.slope N + have hLg : L ≤ rowDifference g N := by + rw [show L = (g N + f N) / (2 * (N : ℝ) + m + 2) by unfold L; rw [add_comm (g N)]] + exact hg.slope N + let X := f (j + b) + let Y := g (k + c) + have hX : 0 < X := hf.pos _ + have hY : 0 < Y := hg.pos _ + have hsum : X + Y ≤ (m + (j + b) + (k + c) + 2 : ℕ) * L := by + have h₁ := hf.increase hLf (j := j + b) (k := k + c) le_rfl + have h₂ := hg.increase hLg (j := k + c) (k := j + b) (by unfold N; omega) + rw [add_comm (k + c)] at h₂ + have he : L * (2 * (N : ℝ) + m + 2) = f N + g N := div_mul_cancel₀ _ (by positivity) + unfold N at he + unfold X Y + push_cast at * + linarith + have part {f g : ℕ → ℝ} (h : Row f g m) (hf' : L ≤ rowDifference f N) + {j b : ℕ} (hb : 0 < b) (hN : j + b ≤ N) : + L / f (j + b) ≤ (Real.log (f (j + b)) - Real.log (f j)) / b := by + apply (le_div_iff₀ (by positivity)).mpr + rw [div_mul_eq_mul_div] + exact (div_le_div_of_nonneg_right (by linarith [h.increase hf' hN]) (h.pos _).le).trans + (log_increase (h.pos j) (h.pos (j + b))) + calc + _ ≤ 4 * L / (X + Y) := by + apply (div_le_div_iff₀ (by positivity) (by positivity)).mpr + linarith + _ ≤ L / X + L / Y := by + field_simp + nlinarith [sq_nonneg (X - Y)] + _ ≤ _ := add_le_add (part hf hLf hb (by unfold N; omega)) + (part hg hLg hc (by unfold N; omega)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# The polar formula for the rectangular benchmark + +The three arm lengths `x,y,z` give wire lengths `x+y,x+z,y+z`. +The dual inequality follows by weighted Cauchy–Schwarz. At an active +shape all three arms of a maximizing tripod can be strictly positive. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +/-- The quantity computed by `x * (a + b) + y * (a + c) + z * (b + c)`. -/ +def load (a b c x y z : ℝ) : ℝ := x * (a + b) + y * (a + c) + z * (b + c) + +/-- The quantity computed by `x + y + z - x * y * z / (x * y + y * z + z * x)`. -/ +def dStar (x y z : ℝ) : ℝ := x + y + z - x * y * z / (x * y + y * z + z * x) + +/-- The maximum of the quantities in `(a + b) (max (a + c) (b + c))`. -/ +def area (a b c : ℝ) : ℝ := max (a + b) (max (a + c) (b + c)) + +variable {a b c x y z s t u : ℝ} + +private theorem cauchy (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) (hs : s + t + u = 1) : + x * y * z / (x * y + y * z + z * x) ≤ x * s ^ 2 + y * t ^ 2 + z * u ^ 2 := by + rcases eq_or_lt_of_le (by positivity : 0 ≤ x * y + y * z + z * x) with h | h + · rw [← h, div_zero] + positivity + apply (div_le_iff₀ h).2 + have h' : 0 ≤ z * (x * s - y * t) ^ 2 + y * (x * s - z * u) ^ 2 + x * (y * t - z * u) ^ 2 + := by positivity + calc + _ = x * y * z * (s + t + u) ^ 2 := by rw [hs]; ring + _ ≤ _ := by linarith only [h'] + +theorem dStar_pos (hx : 0 < x) (hy : 0 < y) (hz : 0 < z) : 0 < dStar x y z := by + have := cauchy hx.le hy.le hz.le (show (1 : ℝ) + 0 + 0 = 1 by norm_num) + unfold dStar + linarith + +private theorem dStar_cycle (x y z : ℝ) : dStar z x y = dStar x y z := by + unfold dStar + ring + +private theorem load_cycle (a b c x y z : ℝ) : load b c a z x y = load a b c x y z := by + unfold load + ring + +private theorem area_cycle (a b c : ℝ) : area b c a = area a b c := by + unfold area + simp only [add_comm, max_comm, max_left_comm] + +/-- The polar upper bound, with attainment at positive arms above the +largest pair sum. At or below that sum a single nonzero arm suffices. -/ +structure Polar (a b c v : ℝ) : Prop where + area_le : area a b c ≤ v + bound : ∀ x y z : ℝ, 0 ≤ x → 0 ≤ y → 0 ≤ z → load a b c x y z ≤ v * dStar x y z + achieves : area a b c < v → ∃ x y z : ℝ, + 0 < x ∧ 0 < y ∧ 0 < z ∧ load a b c x y z = v * dStar x y z + +private theorem Polar.rotate {v : ℝ} (h : Polar b c a v) : Polar a b c v := by + refine ⟨(area_cycle a b c).symm.trans_le h.area_le, ?_, ?_⟩ + · intro x y z hx hy hz + simpa only [load_cycle a b c, dStar_cycle x y z] using h.bound z x y hz hx hy + · intro hlt + obtain ⟨z, x, y, hz, hx, hy, he⟩ := h.achieves ((area_cycle a b c).trans_lt hlt) + exact ⟨x, y, z, hx, hy, hz, by rwa [load_cycle a b c, dStar_cycle x y z] at he⟩ + +/-- Three weights adding to one certify an upper bound on the objective. -/ +private theorem certificate {v : ℝ} (hv : 0 ≤ v) (hs : s + t + u = 1) + (h₁ : a + b ≤ v * (1 - s ^ 2)) (h₂ : a + c ≤ v * (1 - t ^ 2)) + (h₃ : b + c ≤ v * (1 - u ^ 2)) (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) : + load a b c x y z ≤ v * dStar x y z := by + calc + _ ≤ x * (v * (1 - s ^ 2)) + y * (v * (1 - t ^ 2)) + z * (v * (1 - u ^ 2)) := by + unfold load + gcongr + _ = v * (x + y + z - (x * s ^ 2 + y * t ^ 2 + z * u ^ 2)) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left (sub_le_sub_left (cauchy hx hy hz hs) _) hv + +private theorem optimizer {v : ℝ} (hs : 0 < s) (ht : 0 < t) (hu : 0 < u) + (hsum : s + t + u = 1) (h₁ : a + b = v * (1 - s ^ 2)) + (h₂ : a + c = v * (1 - t ^ 2)) (h₃ : b + c = v * (1 - u ^ 2)) : + load a b c s⁻¹ t⁻¹ u⁻¹ = v * dStar s⁻¹ t⁻¹ u⁻¹ := by + have he : s⁻¹ * t⁻¹ * u⁻¹ / (s⁻¹ * t⁻¹ + t⁻¹ * u⁻¹ + u⁻¹ * s⁻¹) = 1 := by + field_simp + linarith + rw [load, h₁, h₂, h₃, dStar, he] + have hr (p : ℝ) (hp : 0 < p) : p⁻¹ * (v * (1 - p ^ 2)) = v * (p⁻¹ - p) := by field_simp + rw [hr s hs, hr t ht, hr u hu, ← hsum] + ring + +private theorem polar_ordered (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) + (hca : c ≤ a) (hcb : c ≤ b) : Polar a b c (benchmark a b c) := by + have hM : area a b c = a + b := max_eq_left (max_le (by linarith) (by linarith)) + by_cases h : (a + b) * c ≤ a * b + · have he : benchmark a b c = a + b := by simp [benchmark, max_eq_right (sub_nonpos.mpr h)] + rw [he] + refine ⟨hM.le, ?_, fun h' => (hM.ge.not_gt h').elim⟩ + intro x y z hx hy hz + refine certificate (s := 0) (t := b / (a + b)) (u := a / (a + b)) + (by positivity) ?_ (by simp) ?_ ?_ hx hy hz + · field_simp; ring + · field_simp; nlinarith only [h] + · field_simp; nlinarith only [h] + · have h' : a * b < (a + b) * c := lt_of_not_ge h + let K := a * b + a * c + b * c + have hK : 0 < K := by unfold K; positivity + let v := K ^ 2 / (4 * a * b * c) + have hv : 0 < v := by unfold v; positivity + have he : benchmark a b c = v := by + rw [benchmark, max_eq_left (sub_nonneg.mpr h'.le)] + unfold v K + field_simp + ring + rw [he] + let s := 1 - 2 * a * b / K + let t := 1 - 2 * a * c / K + let u := 1 - 2 * b * c / K + have hs : 0 < s := sub_pos.mpr ((div_lt_one hK).2 (by unfold K; linarith)) + have ht : 0 < t := sub_pos.mpr ((div_lt_one hK).2 (by unfold K; nlinarith)) + have hu : 0 < u := sub_pos.mpr ((div_lt_one hK).2 (by unfold K; nlinarith)) + have hsum : s + t + u = 1 := by unfold s t u; field_simp; unfold K; ring + have h₁ : a + b = v * (1 - s ^ 2) := by unfold v s; field_simp; unfold K; ring + have h₂ : a + c = v * (1 - t ^ 2) := by unfold v t; field_simp; unfold K; ring + have h₃ : b + c = v * (1 - u ^ 2) := by unfold v u; field_simp; unfold K; ring + refine ⟨?_, fun _ _ _ => certificate hv.le hsum h₁.le h₂.le h₃.le, fun _ => + ⟨s⁻¹, t⁻¹, u⁻¹, by positivity, by positivity, by positivity, + optimizer hs ht hu hsum h₁ h₂ h₃⟩⟩ + rw [hM, ← he, benchmark] + exact le_add_of_nonneg_right (by positivity) + +theorem polar (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : Polar a b c (U a b c) := by + unfold U + split_ifs with h h' + · exact polar_ordered ha hb hc (le_min_iff.mp h).1 (le_min_iff.mp h).2 + · rw [min_eq_left h'] at h + exact (polar_ordered hb hc ha h' (le_of_not_ge h)).rotate + · rw [min_eq_right (le_of_not_ge h')] at h + exact (polar_ordered hc ha hb (le_of_not_ge h) (le_of_not_ge h')).rotate.rotate + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- # Three wires for a rectangular matrix product -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral + +/-- The output is at site 0, the two inputs at sites 1 and 2. -/ +def tensor (K : Type) [Field K] (i j k : ℕ) : Tensor K (Fin 3) := + Tensor.wire K 0 1 i * Tensor.wire K 0 2 j * Tensor.wire K 1 2 k + +theorem tensor_power (K : Type) [Field K] (i j k t : ℕ) : + tensor K (i ^ t) (j ^ t) (k ^ t) = (tensor K i j k) ^ t := by + induction t with + | zero => simp [tensor, Tensor.wire, Tensor.shared_one] + | succ t ih => + rw [pow_succ, pow_succ, pow_succ, pow_succ, ← ih] + simp only [tensor, Tensor.wire, Tensor.shared_mul] + exact (congrArg (· * _) (mul_mul_mul_comm _ _ _ _)).trans (mul_mul_mul_comm _ _ _ _) + +variable {K L : Type} [Field K] [Field L] + +theorem tensor_map (φ : K →+* L) (i j k : ℕ) : + Tensor.map φ (tensor K i j k) = tensor L i j k := by + have hw (a b : Fin 3) (n : ℕ) : Tensor.map φ (Tensor.wire K a b n) = Tensor.wire L a b n := by + apply Tensor.ofRaw_eq + refine Raw.relabel (Equiv.refl _) (fun _ => Equiv.refl _) fun i s x => ?_ + change Fin n at i x + change φ (if x = Raw.port {a, b} s i then 1 else 0) = + if x = Raw.port {a, b} s i then 1 else 0 + split <;> simp + rw [tensor, tensor, map_mul, map_mul, hw, hw, hw] + +/-- The quantity computed by `Raw.wire K 0 1 i * Raw.wire K 0 2 j * Raw.wire K 1 2 k`. -/ +abbrev rawWires (K : Type) [Field K] (i j k : ℕ) : Raw K (Fin 3) := + Raw.wire K 0 1 i * Raw.wire K 0 2 j * Raw.wire K 1 2 k + +variable {i j k r : ℕ} + +theorem coeff_wires (x : Fin 3 → (Fin i × Fin j) × Fin k) : + (rawWires K i j k).coeff x = + if (x 0).2.val = 0 ∧ (x 1).1.2.val = 0 ∧ (x 2).1.1.val = 0 then + if (x 1).1.1 = (x 0).1.1 ∧ (x 1).2 = (x 2).2 ∧ (x 2).1.2 = (x 0).1.2 then 1 else 0 + else 0 := by + change (∑ t : (Fin i × Fin j) × Fin k, ∏ s : Fin 3, + ((if (x s).1.1 = Raw.port {0, 1} s t.1.1 then 1 else 0) * + (if (x s).1.2 = Raw.port {0, 2} s t.1.2 then 1 else 0) * + (if (x s).2 = Raw.port {1, 2} s t.2 then 1 else 0) : K)) = _ + rw [Fintype.sum_eq_single ((x 0).1, (x 1).2)] + · simp [Fin.prod_univ_three, Raw.port] + simp only [Fin.ext_iff] + grind + · intro t ht + simp [Fin.prod_univ_three, Raw.port] + grind + +/-- Restriction from a diagonal is exactly a coefficient decomposition. +Each site in the three-wire model has one unused index fixed to zero. -/ +theorem tensor_le_iff (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + tensor K i j k ≤ (r : Tensor K (Fin 3)) ↔ RankLE K i j k r := by + rw [← Tensor.diag_fin] + change (∃ A : Fin 3 → (Fin i × Fin j) × Fin k → Fin r → K, + ∀ x : Fin 3 → (Fin i × Fin j) × Fin k, + (rawWires K i j k).coeff x = + ∑ l : Fin r, ∏ s, ∑ y : Fin r, A s (x s) y * if y = l then 1 else 0) ↔ _ + simp only [mul_ite, mul_one, mul_zero, Fintype.sum_ite_eq', Fin.prod_univ_three, coeff_wires] + constructor + · rintro ⟨A, hA⟩ + let X (x : Pos i k) := ((x.1, (⟨0, hj⟩ : Fin j)), x.2) + let Y (y : Pos k j) := (((⟨0, hi⟩ : Fin i), y.2), y.1) + let Z (z : Pos i j) := (z, (⟨0, hk⟩ : Fin k)) + refine ⟨fun l x => A 1 (X x) l, fun l y => A 2 (Y y) l, fun l z => A 0 (Z z) l, ?_⟩ + intro x y z + have ha := (hA ![Z z, X x, Y y]).symm + convert ha using 1 + · simp [X, Y, Z, mul_assoc, mul_comm] + · by_cases hp : x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 <;> simp [X, Y, Z, hp] + · rintro ⟨a, b, c, h⟩ + refine ⟨![fun p l => if p.2.val = 0 then c l p.1 else 0, + fun p l => if p.1.2.val = 0 then a l (p.1.1, p.2) else 0, + fun p l => if p.1.1.val = 0 then b l (p.2, p.1.2) else 0], ?_⟩ + intro x + by_cases h₀ : (x 0).2.val = 0 + swap; · simp [h₀] + by_cases h₁ : (x 1).1.2.val = 0 + swap; · simp [h₁] + by_cases h₂ : (x 2).1.1.val = 0 + swap; · simp [h₂] + simpa [h₀, h₁, h₂, mul_assoc, mul_comm, mul_left_comm] using + (h ((x 1).1.1, (x 1).2) ((x 2).2, (x 2).1.2) (x 0).1).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Positive spectral contact implies rectangular rigidity + +The normalized price triples are arm lengths at diagonal rate one. +The two geometric inputs are the harmonic lower bound on the rate +and propagation from a positive triple attaining that lower bound. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} [Field F] {P : ℝ → ℝ → ℝ → Prop} + +/-- A support representation by nonnegative normalized arms. -/ +structure Support (F : Type*) [Field F] (P : ℝ → ℝ → ℝ → Prop) : Prop where + nonneg : ∀ {x y z}, P x y z → 0 ≤ x ∧ 0 ≤ y ∧ 0 ≤ z + bound : ∀ {a b c x y z}, 0 ≤ a → 0 ≤ b → 0 ≤ c → P x y z → + load a b c x y z ≤ exponent F a b c + attains : ∀ {a b c}, 0 ≤ a → 0 ≤ b → 0 ≤ c → + ∃ x y z, P x y z ∧ load a b c x y z = exponent F a b c + +/-- The condition `∀ x y z, P x y z → dStar x y z ≤ 1` on the specified data. -/ +def DiagonalBound (P : ℝ → ℝ → ℝ → Prop) : Prop := + ∀ x y z, P x y z → dStar x y z ≤ 1 + +/-- The propagation of type `Prop` for the given inputs. -/ +def Propagation (P : ℝ → ℝ → ℝ → Prop) : Prop := + (∃ x y z, 0 < x ∧ 0 < y ∧ 0 < z ∧ P x y z ∧ dStar x y z = 1) → + ∀ x y z, 0 < x → 0 < y → 0 < z → + P (x / dStar x y z) (y / dStar x y z) (z / dStar x y z) + +private theorem boundary {a b c x y z : ℝ} + (ha : 0 < a) (hb : 0 < b) (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) + (h : dStar x y z ≤ 1) (h' : x = 0 ∨ y = 0 ∨ z = 0) : + load a b c x y z ≤ area a b c := by + have hsum : x + y + z ≤ 1 := by + rcases h' with h' | h' | h' <;> simpa [dStar, h'] using h + let M := area a b c + have h₁ : a + b ≤ M := le_max_left _ _ + have h₂ : a + c ≤ M := (le_max_left _ _).trans (le_max_right _ _) + have h₃ : b + c ≤ M := (le_max_right _ _).trans (le_max_right _ _) + calc + _ ≤ x * M + y * M + z * M := by unfold load; gcongr + _ = (x + y + z) * M := by ring + _ ≤ M := mul_le_of_le_one_left (by linarith) hsum + +theorem upper_of_diagonal (hs : Support F P) (hd : DiagonalBound P) + {a b c : ℝ} (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : + exponent F a b c ≤ U a b c := by + have h := polar ha hb hc + have hU : 0 ≤ U a b c := (add_pos ha hb).le.trans ((le_max_left _ _).trans h.area_le) + obtain ⟨x, y, z, hP, he⟩ := hs.attains ha.le hb.le hc.le + obtain ⟨hx, hy, hz⟩ := hs.nonneg hP + exact he.ge.trans ((h.bound _ _ _ hx hy hz).trans + (mul_le_of_le_one_right hU (hd x y z hP))) + +theorem rigidity_of_contact (hs : Support F P) (hd : DiagonalBound P) + (hp : Propagation P) : Rigidity F := by + by_cases ht : ∃ x y z, 0 < x ∧ 0 < y ∧ 0 < z ∧ P x y z ∧ dStar x y z = 1 + · left + intro a b c ha hb hc + refine le_antisymm (upper_of_diagonal hs hd ha hb hc) ?_ + by_cases h : area a b c < U a b c + · obtain ⟨x, y, z, hx, hy, hz, he⟩ := (polar ha hb hc).achieves h + have hh := hs.bound ha.le hb.le hc.le (hp ht x y z hx hy hz) + let D := dStar x y z + have hD : 0 < D := dStar_pos hx hy hz + calc + U a b c = load a b c x y z / D := (eq_div_iff hD.ne').2 he.symm + _ = load a b c (x / D) (y / D) (z / D) := by unfold load; ring + _ ≤ _ := hh + · exact (le_of_not_gt h).trans (bounds F ha.le hb.le hc.le).1 + · right + intro a b c ha hb hc hactive + obtain ⟨x, y, z, hP, he⟩ := hs.attains ha.le hb.le hc.le + obtain ⟨hx, hy, hz⟩ := hs.nonneg hP + have hD := hd x y z hP + rw [← he] + by_cases h' : x = 0 ∨ y = 0 ∨ z = 0 + · exact (boundary ha hb hx hy hz hD h').trans_lt hactive + push Not at h' + have hD' : dStar x y z < 1 := lt_of_le_of_ne hD fun he => + ht ⟨x, y, z, hx.lt_of_ne' h'.1, hy.lt_of_ne' h'.2.1, hz.lt_of_ne' h'.2.2, hP, he⟩ + exact ((polar ha hb hc).bound _ _ _ hx hy hz).trans_lt + (mul_lt_of_lt_one_right ((add_pos ha hb).trans_le (le_max_left _ _) |>.trans hactive) hD') + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- # Three-site spectral points and normalized prices -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral +open scoped NNReal + +variable {F : Type} [Field F] + +/-- The value specified by `Tensor F (Fin 3) →+* ℝ≥0`. -/ +abbrev Point (F : Type) [Field F] := Tensor F (Fin 3) →+* ℝ≥0 + +/-- The value specified by `Tensor.dist (NNReal.toRealHom.comp f)`. -/ +def dist (f : Point F) : Fin 3 → Fin 3 → ℝ := Tensor.dist (NNReal.toRealHom.comp f) + +/-- The quantity computed by `a * dist f 0 1 + b * dist f 0 2 + c * dist f 1 2`. -/ +def score (f : Point F) (a b c : ℝ) : ℝ := + a * dist f 0 1 + b * dist f 0 2 + c * dist f 1 2 + +/-- The condition `∃ f : Point F, Monotone f ∧ dist f 0 1 = x + y ∧ dist f 0 2 = x + z ∧ dist f +1 2 = y + z` on the specified data. -/ +def Prices (F : Type) [Field F] (x y z : ℝ) : Prop := + ∃ f : Point F, Monotone f ∧ dist f 0 1 = x + y ∧ dist f 0 2 = x + z ∧ dist f 1 2 = y + z + +variable {f : Point F} {x y z a b c : ℝ} + +theorem mono_real (hf : Monotone f) : Monotone (NNReal.toRealHom.comp f) := + fun _ _ h => NNReal.coe_le_coe.mpr (hf h) + +theorem dist_bounds (hf : Monotone f) (i j : Fin 3) : 0 ≤ dist f i j ∧ dist f i j ≤ 1 := + ⟨Tensor.dist_nonneg _ (mono_real hf) i j, Tensor.dist_le_one _ (mono_real hf) i j⟩ + +theorem Prices.nonneg (h : Prices F x y z) : 0 ≤ x ∧ 0 ≤ y ∧ 0 ≤ z := by + obtain ⟨f, hf, h₁, h₂, h₃⟩ := h + have tri (i j k : Fin 3) : dist f i k ≤ dist f i j + dist f j k := + Tensor.dist_triangle _ (mono_real hf) i j k + have comm (i j : Fin 3) : dist f i j = dist f j i := Tensor.dist_comm _ i j + refine ⟨?_, ?_, ?_⟩ + · linarith [tri 1 0 2, comm 1 0] + · linarith [tri 0 1 2] + · linarith [tri 0 2 1, comm 2 1] + +theorem Prices.score (h : Prices F x y z) : + ∃ f : Point F, Monotone f ∧ load a b c x y z = score f a b c := by + obtain ⟨f, hf, h₁, h₂, h₃⟩ := h + refine ⟨f, hf, ?_⟩ + rw [Rectangle.score, load, h₁, h₂, h₃] + ring + +theorem score_eq_load (hf : Monotone f) : + ∃ x y z, Prices F x y z ∧ load a b c x y z = score f a b c := by + let p := (dist f 0 1 + dist f 0 2 + dist f 1 2) / 2 + refine ⟨p - dist f 1 2, p - dist f 0 2, p - dist f 0 1, ⟨f, hf, ?_, ?_, ?_⟩, ?_⟩ + all_goals simp only [p, load, score]; ring + +private theorem nonempty_points (F : Type) [Field F] : + (Spectrum.points (Tensor F (Fin 3))).Nonempty := by + obtain ⟨f, hf, _⟩ := Spectrum.extension Tensor.add_le_add_right Tensor.mul_le_mul_left + Tensor.zero_le Tensor.one_le Tensor.exists_bound (Nat.castRingHom (Tensor F (Fin 3))) + (Nat.castRingHom ℝ≥0) (fun m n h => Nat.cast_le.mpr ((Tensor.natCast_le_iff m n).mp h)) + exact ⟨f, f, hf, rfl⟩ + +theorem maximum_score (F : Type) [Field F] (a b c : ℝ) : + ∃ f : Point F, Monotone f ∧ ∀ g : Point F, Monotone g → score g a b c ≤ score f a b c := by + let P := Spectrum.points (Tensor F (Fin 3)) + let d (i j : Fin 3) (g : Tensor F (Fin 3) → ℝ≥0) := + Real.log (g (Tensor.wire F i j 2)) / Real.log 2 + have hd (i j : Fin 3) : ContinuousOn (d i j) P := by + apply ContinuousOn.div_const + have hc : Continuous (fun g : Tensor F (Fin 3) → ℝ≥0 => (g (Tensor.wire F i j 2) : ℝ)) + := by fun_prop + apply ContinuousOn.log hc.continuousOn + rintro _ ⟨g, hg, rfl⟩ + have h : 1 ≤ g (Tensor.wire F i j 2) := by + simpa using hg (Tensor.one_le_wire F i j (n := 2) (by decide)) + exact ne_of_gt (show (0 : ℝ) < g (Tensor.wire F i j 2) by positivity) + have ht : ContinuousOn (fun g => a * d 0 1 g + b * d 0 2 g + c * d 1 2 g) P := + (((hd 0 1).const_mul a).add ((hd 0 2).const_mul b)).add ((hd 1 2).const_mul c) + obtain ⟨_, ⟨f, hf, rfl⟩, h⟩ := + (Spectrum.compact_points Tensor.exists_bound).exists_isMaxOn (nonempty_points F) ht + exact ⟨f, hf, fun g hg => h ⟨g, hg, rfl⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Powers of a point in the Zariski closure + +Polynomial evaluation carries a closure point into the linear span of +the evaluations on the original set. The degree-`n` products only use +monomials with each exponent at most `n`, giving a polynomial bound on +the number of points needed in one simultaneous interpolation. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Finset + +variable {F : Type*} [Field F] {ι : Type} + +variable {s : Set (ι → F)} {x : ι → F} + +private theorem ZClosure.evaluate (h : ZClosure s x) {κ : Type} [Fintype κ] + (p : κ → MvPolynomial ι F) : + ∃ d : ℕ, d ≤ Fintype.card κ ∧ ∃ (y : Fin d → ι → F) (c : Fin d → F), + (∀ t, y t ∈ s) ∧ ∀ i, MvPolynomial.eval x (p i) = ∑ t, c t * MvPolynomial.eval (y t) (p i) + := by + classical + let v (z : ι → F) i := MvPolynomial.eval z (p i) + let W := Submodule.span F (v '' s) + have hx : v x ∈ W := by + apply (Subspace.forall_mem_dualAnnihilator_apply_eq_zero_iff W _).mp + intro φ hφ + let q := ∑ i, MvPolynomial.C (φ (Pi.basisFun F κ i)) * p i + have eqn (z : ι → F) : φ (v z) = MvPolynomial.eval z q := by + rw [← (Pi.basisFun F κ).sum_repr (v z), map_sum] + simp only [map_smul, Pi.basisFun_repr, smul_eq_mul, q, map_sum, map_mul, MvPolynomial.eval_C, + v, mul_comm] + rw [eqn] + apply h + intro z hz + rw [← eqn] + exact (Submodule.mem_dualAnnihilator φ).mp hφ _ (Submodule.subset_span ⟨z, hz, rfl⟩) + obtain ⟨b, hb, he, _⟩ := Submodule.exists_fun_fin_finrank_span_eq F (v '' s) + choose y hy hy' using hb + have hx' : v x ∈ Submodule.span F (Set.range b) := he.symm ▸ hx + obtain ⟨c, hc⟩ := (Submodule.mem_span_range_iff_exists_fun _).mp hx' + refine ⟨Module.finrank F W, ?_, y, c, hy, fun i => ?_⟩ + · simpa using W.finrank_le + · simpa only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul, ← hy', v] using congrFun hc.symm i + +theorem ZClosure.power [Fintype ι] (h : ZClosure s x) (n : ℕ) : + ∃ d : ℕ, d ≤ (n + 1) ^ Fintype.card ι ∧ ∃ (y : Fin d → ι → F) (c : Fin d → F), + (∀ t, y t ∈ s) ∧ ∀ f : Fin n → ι, ∏ l, x (f l) = ∑ t, c t * ∏ l, y t (f l) := by + classical + let p (e : ι → Fin (n + 1)) : MvPolynomial ι F := ∏ i, MvPolynomial.X i ^ (e i).val + obtain ⟨d, hd, y, c, hy, hc⟩ := h.evaluate p + refine ⟨d, by simpa using hd, y, c, hy, fun f => ?_⟩ + let e (i : ι) : Fin (n + 1) := ⟨(univ.filter (fun l => f l = i)).card, + Nat.lt_succ_of_le (by simpa using card_filter_le univ (fun l => f l = i))⟩ + have he (z : ι → F) : MvPolynomial.eval z (p e) = ∏ l, z (f l) := by + rw [← prod_fiberwise' univ f z] + simp only [p, map_prod, map_pow, MvPolynomial.eval_X, prod_const, e] + simpa only [he] using hc e + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Scalar extension for the density bound + +The weights and a rank witness lie in one countable subfield. Both embeddings +from that subfield preserve all coefficient equations and the set of nonzero +weights. The unweighted arithmetic exponent is invariant under extension. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F K : Type*} [Field F] [Field K] {i j k r : ℕ} {w : Fin i → Fin j → Fin k → F} + +theorem supportSize_map (φ : F →+* K) (w : Fin i → Fin j → Fin k → F) : + supportSize (fun x y z => φ (w x y z)) = supportSize w := by + classical + have he (x : F) : φ x = 0 ↔ x = 0 := by rw [← map_zero φ, φ.injective.eq_iff] + simp only [supportSize, he] + +theorem small_coefficients {ι : Type} [Countable ι] (v : ι → F) : + ∃ (L : Type) (_ : Field L) (φ : L →+* F) (u : ι → L), ∀ t, φ (u t) = v t := by + let H := Subfield.closure (Set.range v) + have : Countable H := Cardinal.mk_le_aleph0_iff.mp + ((Subfield.cardinalMk_closure_le_max (Set.range v)).trans + (max_le (Cardinal.le_aleph0_iff_set_countable.mpr (Set.countable_range v)) le_rfl)) + let e : Shrink.{0} H ≃+* H := Shrink.ringEquiv.{0} H + exact ⟨Shrink.{0} H, inferInstance, H.subtype.comp e.toRingHom, + fun t => e.symm ⟨v t, Subfield.subset_closure ⟨t, rfl⟩⟩, by simp⟩ + +theorem small_witness (h : WeightedRankLE w r) : + ∃ (L : Type) (_ : Field L) (φ : L →+* F) (v : Fin i → Fin j → Fin k → L), + WeightedRankLE v r ∧ (fun x y z => φ (v x y z)) = w := by + obtain ⟨a, b, c, hc⟩ := h + let data : (Fin i × Fin j × Fin k) ⊕ (Fin r × (Pos i k ⊕ Pos k j ⊕ Pos i j)) → F := + Sum.elim (fun p => w p.1 p.2.1 p.2.2) (fun p => Sum.elim (a p.1) (Sum.elim (b p.1) (c p.1)) p.2) + obtain ⟨L, _, φ, u, hu⟩ := small_coefficients data + refine ⟨L, inferInstance, φ, fun x y z => u (.inl (x, y, z)), ?_, funext fun x => + funext fun y => funext fun z => hu (.inl (x, y, z))⟩ + refine ⟨fun l x => u (.inr (l, .inl x)), fun l y => u (.inr (l, .inr (.inl y))), + fun l z => u (.inr (l, .inr (.inr z))), fun x y z => ?_⟩ + apply φ.injective + simp only [map_sum, map_mul, apply_ite φ, map_zero, hu] + exact hc x y z + +theorem density_of_closed (h : ∀ (K : Type) [Field K] [IsAlgClosed K], DensityBound K) + (F : Type*) [Field F] : DensityBound F := by + intro i j k r hi hj hk w hw + obtain ⟨L, _, φ, v, hv, he⟩ := small_witness hw + let : Algebra L F := φ.toAlgebra + have h' := h (AlgebraicClosure L) i j k r hi hj hk _ (hv.map (algebraMap L (AlgebraicClosure L))) + have ha : 0 ≤ Real.log i := Real.log_nonneg (by exact_mod_cast hi) + have hb : 0 ≤ Real.log j := Real.log_nonneg (by exact_mod_cast hj) + have hc : 0 ≤ Real.log k := Real.log_nonneg (by exact_mod_cast hk) + rw [← he, supportSize_map, exponent_extension L F ha hb hc] + rwa [supportSize_map, exponent_extension L (AlgebraicClosure L) ha hb hc] at h' + +theorem cells_of_closed (h : ∀ (K : Type) [Field K] [IsAlgClosed K], CellBound K) + (F : Type*) [Field F] : CellBound F := by + intro i j k r hi hj hk w u hu hw hr + obtain ⟨L, _, φ, v, hv, he⟩ := small_witness hr + let : Algebra L F := φ.toAlgebra + let ψ := algebraMap L (AlgebraicClosure L) + have he' (x y z) : ψ (v x y z) ≠ 0 ↔ (x, y) ∈ u := by + rw [← hw x y z, ← he] + simp + have h' := h (AlgebraicClosure L) i j k r hi hj hk _ u hu he' (hv.map ψ) + obtain ⟨ha, hb⟩ := short_bounds hi hj hu.card_pos + have hc : 0 ≤ Real.log k := Real.log_nonneg (by exact_mod_cast hk) + rw [exponent_extension L F ha (sub_nonneg.mpr hb) hc] + rwa [exponent_extension L (AlgebraicClosure L) ha (sub_nonneg.mpr hb) hc] at h' + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Degree.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Degree.lean new file mode 100644 index 0000000000..841bdf4959 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Degree.lean @@ -0,0 +1,799 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Tag +public import Mathlib.Analysis.MeanInequalities +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.PermutationPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.CharacterRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Mask +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows + +/-! # A mean bound for a shared label, including zero branches -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Upper Upper.TensorClass MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +theorem tag_nonneg (f : Character) {X Y Z : Type} [Fintype X] [Fintype Y] [Fintype Z] + {n : ℕ} (A : Fin n → Tensor Coeff X Y Z) (hp : 0 < f.pX) : + (∑ i, (f (ofTensor (A i)) : ℝ) ^ (1 / f.pX)) ^ f.pX ≤ + (f (ofTensor (Separation.shared A)) : ℝ) := by + induction n with + | zero => simp [Real.zero_rpow hp.ne'] + | succ n ih => + by_cases h : ∀ i, 0 < (f (ofTensor (A i)) : ℝ) + · exact f.shared_tag_optimized_of_pos (Nat.succ_pos _) A h hp + push Not at h + obtain ⟨i, hi⟩ := h + have hi' : (f (ofTensor (A i)) : ℝ) = 0 := le_antisymm hi (by positivity) + rw [Fin.sum_univ_succAbove _ i, hi', Real.zero_rpow (by positivity), zero_add] + apply (ih (fun j => A (i.succAbove j))).trans + apply NNReal.coe_le_coe.mpr + apply f.monotone' + apply ofTensor_le + let y (p : Fin n × Y) := (i.succAbove p.1, p.2) + let z (p : Fin n × Z) := (i.succAbove p.1, p.2) + have he : Tensor.pullback id y z (Separation.shared A) = + Separation.shared (fun j => A (i.succAbove j)) := by + funext p q r + simp [Tensor.pullback, Tensor.sharedFirst, y, z] + rw [← he] + exact CoefficientTensor.Restricts.pullback _ _ _ _ + +/-- The character value of a tagged family dominates the average value +of a branch times the value of a pairing of size `n`. -/ +theorem meanTag (f : Character) {X Y Z : Type} [Fintype X] [Fintype Y] [Fintype Z] + {n : ℕ} (hn : 0 < n) (A : Fin n → Tensor Coeff X Y Z) : + (n : ℝ) ^ f.pX * (∑ i, (f (ofTensor (A i)) : ℝ)) ≤ + n * (f (ofTensor (Separation.shared A)) : ℝ) := by + rcases eq_or_lt_of_le f.pX_nonneg with hp | hp + · rw [← hp, Real.rpow_zero, one_mul] + simpa using Finset.sum_le_sum (s := Finset.univ) (fun i _ => NNReal.coe_le_coe.mpr + (f.shared_branch_le A i)) + let v i := (f (ofTensor (A i)) : ℝ) + have hv i : 0 ≤ v i := (f (ofTensor (A i))).coe_nonneg + have hsum : 0 ≤ ∑ i, v i := Finset.sum_nonneg (fun i _ => hv i) + have hpow : 0 ≤ ∑ i, v i ^ (1 / f.pX) := Finset.sum_nonneg (fun i _ => Real.rpow_nonneg (hv i) _) + have hq : 1 ≤ 1 / f.pX := (le_div_iff₀ hp).mpr (by simpa using f.pX_le_one) + have h := Real.rpow_sum_le_const_mul_sum_rpow_of_nonneg Finset.univ hq (fun i _ => hv i) + rw [Finset.card_univ, Fintype.card_fin] at h + have h' := Real.rpow_le_rpow (Real.rpow_nonneg hsum _) h hp.le + rw [← Real.rpow_mul hsum, one_div_mul_cancel hp.ne', Real.rpow_one, + Real.mul_rpow (by positivity) hpow, ← Real.rpow_mul (by positivity), + show (1 / f.pX - 1) * f.pX = 1 - f.pX by field_simp] at h' + calc + _ ≤ (n : ℝ) ^ f.pX * ((n : ℝ) ^ (1 - f.pX) * (∑ i, v i ^ (1 / f.pX)) ^ f.pX) := + mul_le_mul_of_nonneg_left h' (by positivity) + _ = (n : ℝ) * (∑ i, v i ^ (1 / f.pX)) ^ f.pX := by + rw [← mul_assoc, ← Real.rpow_add (by positivity), add_sub_cancel, Real.rpow_one] + _ ≤ _ := mul_le_mul_of_nonneg_left (tag_nonneg f A hp) (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- # Shared-label inequality for probability vectors allowing empty branches -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Upper Upper.TensorClass MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +theorem gibbs {n : ℕ} {q p : Fin n → ℝ} + (hq : ∀ i, 0 ≤ q i) (hs : ∑ i, q i = 1) (hp : ∀ i, 0 ≤ p i) + (hs' : ∑ i, p i ≤ 1) (hv : ∀ i, 0 < q i → 0 < p i) : + ∑ i, q i * (Real.log (p i) - Real.log (q i)) ≤ 0 := by + calc + _ ≤ ∑ i, (p i - q i) := by + apply Finset.sum_le_sum + intro i _ + rcases eq_or_lt_of_le (hq i) with h | h + · simp [← h, hp i] + have he := Real.log_le_sub_one_of_pos (div_pos (hv i h) h) + rw [Real.log_div (hv i h).ne' h.ne'] at he + have := mul_le_mul_of_nonneg_left he h.le + rw [mul_sub (q i) (_ / _), mul_div_cancel₀ _ h.ne', mul_one] at this + exact this + _ ≤ 0 := by rw [Finset.sum_sub_distrib, hs]; linarith + +theorem entropy_log_card {n : ℕ} (hn : 0 < n) (q : Fin n → ℝ) + (hq : ∀ i, 0 ≤ q i) (hs : ∑ i, q i = 1) : + -(∑ i, q i * Real.log (q i)) ≤ Real.log n := by + have he := gibbs (p := fun _ => (n : ℝ)⁻¹) hq hs (fun _ => by positivity) + (by simp [hn.ne']) (fun _ _ => by positivity) + simp only [Real.log_inv, mul_sub, Finset.sum_sub_distrib, ← Finset.sum_mul, hs, one_mul] at he + linarith + +theorem logTag (f : Character) {X Y Z : Type} [Fintype X] [Fintype Y] [Fintype Z] + {n : ℕ} (A : Fin n → Tensor Coeff X Y Z) (q : Fin n → ℝ) + (hq : ∀ i, 0 ≤ q i) (hs : ∑ i, q i = 1) (hv : ∀ i, 0 < q i → 0 < (f (ofTensor (A i)) : ℝ)) : + 0 < (f (ofTensor (Separation.shared A)) : ℝ) ∧ + ∑ i, q i * (Real.log (f (ofTensor (A i))) - f.pX * Real.log (q i)) ≤ + Real.log (f (ofTensor (Separation.shared A))) := by + let v i := (f (ofTensor (A i)) : ℝ) + let V := (f (ofTensor (Separation.shared A)) : ℝ) + have hv₀ i : 0 ≤ v i := NNReal.coe_nonneg _ + have hb i : v i ≤ V := NNReal.coe_le_coe.mpr (f.shared_branch_le A i) + have hV : 0 < V := by + by_contra! h + have h' i : q i ≤ 0 := le_of_not_gt fun hi => (hv i hi).not_ge ((hb i).trans h) + have := Finset.sum_nonpos (s := Finset.univ) (fun i _ => h' i) + linarith + refine ⟨hV, ?_⟩ + change ∑ i, q i * (Real.log (v i) - f.pX * Real.log (q i)) ≤ Real.log V + rcases eq_or_lt_of_le f.pX_nonneg with hd | hd + · calc + _ ≤ ∑ i, q i * Real.log V := by + apply Finset.sum_le_sum + intro i _ + rcases eq_or_lt_of_le (hq i) with h | h + · simp [← h] + rw [← hd, zero_mul, sub_zero] + exact mul_le_mul_of_nonneg_left (Real.log_le_log (hv i h) (hb i)) h.le + _ = _ := by rw [← Finset.sum_mul, hs, one_mul] + let p i := (v i / V) ^ (1 / f.pX) + have hp i : 0 ≤ p i := Real.rpow_nonneg (div_nonneg (hv₀ i) hV.le) _ + have hp' i (h : 0 < q i) : 0 < p i := Real.rpow_pos_of_pos (div_pos (hv i h) hV) _ + have hsum : ∑ i, p i ≤ 1 := by + have h₀ : 0 ≤ ∑ i, (v i) ^ (1 / f.pX) := + Finset.sum_nonneg fun i _ => Real.rpow_nonneg (hv₀ i) _ + have he := Real.rpow_le_rpow (Real.rpow_nonneg h₀ _) (tag_nonneg f A hd) + (by positivity : 0 ≤ 1 / f.pX) + rw [← Real.rpow_mul h₀, mul_one_div_cancel hd.ne', Real.rpow_one] at he + simp only [p, Real.div_rpow (hv₀ _) hV.le, ← Finset.sum_div] + exact (div_le_one (by positivity)).mpr he + have hl := gibbs hq hs hp hsum hp' + calc + _ = ∑ i, (q i * Real.log V + f.pX * (q i * (Real.log (p i) - Real.log (q i)))) := by + apply Finset.sum_congr rfl + intro i _ + rcases eq_or_lt_of_le (hq i) with h | h + · simp [← h] + have hi : 0 < v i := hv i h + rw [show Real.log (p i) = 1 / f.pX * (Real.log (v i) - Real.log V) by + unfold p; rw [Real.log_rpow (by positivity), Real.log_div hi.ne' hV.ne']] + field_simp + ring + _ ≤ Real.log V := by + rw [Finset.sum_add_distrib, ← Finset.sum_mul, hs, one_mul, ← Finset.mul_sum] + exact add_le_of_nonpos_right (mul_nonpos_of_nonneg_of_nonpos hd.le hl) + +theorem uniformTag (f : Character) {X Y Z : Type} [Fintype X] [Fintype Y] [Fintype Z] + {n : ℕ} (A : Fin n → Tensor Coeff X Y Z) (s : Finset (Fin n)) (hs : s.Nonempty) + {t : ℝ} (hv : ∀ i ∈ s, 0 < (f (ofTensor (A i)) : ℝ) ∧ t ≤ Real.log (f (ofTensor (A i)))) : + 0 < (f (ofTensor (Separation.shared A)) : ℝ) ∧ + t + f.pX * Real.log s.card ≤ Real.log (f (ofTensor (Separation.shared A))) := by + classical + let q i := if i ∈ s then (s.card : ℝ)⁻¹ else 0 + have hq (i) : 0 ≤ q i := by unfold q; positivity + have hsum : ∑ i, q i = 1 := by simp [q, hs.card_pos.ne'] + have hpos {i} (h : 0 < q i) : i ∈ s := by by_contra hi; simp [q, hi] at h + obtain ⟨hp, he⟩ := logTag f A q hq hsum (fun i h => (hv i (hpos h)).1) + refine ⟨hp, le_trans ?_ he⟩ + have heq : t + f.pX * Real.log s.card = ∑ i, q i * (t + f.pX * Real.log s.card) := by + rw [← Finset.sum_mul, hsum, one_mul] + rw [heq] + apply Finset.sum_le_sum + intro i _ + rcases eq_or_lt_of_le (hq i) with h | h + · rw [← h, zero_mul, zero_mul] + apply mul_le_mul_of_nonneg_left _ h.le + have hi := hpos h + simp only [q, ite_eq_left hi, Real.log_inv] + linarith [(hv i hi).2] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- # Reading colors visible on two legs of a weighted product -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open Upper Upper.TensorClass MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +variable {X Y Z X' Y' Z' : Type} [Fintype X] [Fintype Y] [Fintype Z] + [Fintype X'] [Fintype Y'] [Fintype Z'] + +theorem scaled_pullback (T : Tensor Coeff X Y Z) (a : X' → X) (b : Y' → Y) (c : Z' → Z) + (α : X' → Coeff) (β : Y' → Coeff) (γ : Z' → Coeff) : + ofTensor (fun x y z => α x * β y * γ z * T (a x) (b y) (c z)) ≤ ofTensor T := by + classical + apply ofTensor_le + obtain ⟨A, B, C, he⟩ := CoefficientTensor.Restricts.pullback T a b c + refine ⟨fun x i => α x * A x i, fun y j => β y * B y j, fun z k => γ z * C z k, ?_⟩ + rw [Separation.restrict_scaled, ← he] + rfl + +private theorem read_label (T : Tensor Coeff X Y Z) (f : Character) {n : ℕ} (hn : 0 < n) + (a : Y → Fin n) (b : Z → Fin n) (h : ∀ x y z, T x y z ≠ 0 → a y = b z) + (A : Fin n → Tensor Coeff X Y Z) + (hA : ∀ i x y z, A i x y z = if a y = i then T x y z else 0) : + (n : ℝ) ^ f.pX * ∑ i, (f (ofTensor (A i)) : ℝ) ≤ n * (f (ofTensor T) : ℝ) := by + classical + have he := scaled_pullback T id (Prod.snd : Fin n × Y → Y) (Prod.snd : Fin n × Z → Z) + (fun _ => 1) (fun y => if a y.2 = y.1 then 1 else 0) (fun z => if b z.2 = z.1 then 1 else 0) + have hs : ofTensor (Separation.shared A) ≤ ofTensor T := by + convert he using 1 + congr 1 + funext x y z + simp only [Tensor.sharedFirst, hA, id_eq] + by_cases hz : T x y.2 z.2 = 0 + · simp [hz] + rw [← h _ _ _ hz] + grind + exact (meanTag f hn A).trans (mul_le_mul_of_nonneg_left + (NNReal.coe_le_coe.mpr (f.monotone' hs)) (by positivity)) + +/-- The indexing data represented by `Fin i → Fin j → Fin k → F`. -/ +abbrev Table (F : Type*) (i j k : ℕ) := Fin i → Fin j → Fin k → F +variable {i j k n : ℕ} + +/-- Evaluates `if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then w x.1 y.2 x.2 else 0` at the input `x y +z`. -/ +def coeff (w : Table Coeff i j k) : Tensor Coeff (Pos i k) (Pos k j) (Pos i j) := + fun x y z => if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then w x.1 y.2 x.2 else 0 + +/-- Computes the price by the application `f (ofTensor (coeff w))`. -/ +def price (f : Character) (w : Table Coeff i j k) : ℝ := f (ofTensor (coeff w)) + +/-- Evaluates `if a x = d then w x y z else 0` at the input `x y z`. -/ +def byRow (a : Fin i → Fin n) (w : Table Coeff i j k) (d : Fin n) : Table Coeff i j k := + fun x y z => if a x = d then w x y z else 0 + +/-- Evaluates `if a y = d then w x y z else 0` at the input `x y z`. -/ +def byCol (a : Fin j → Fin n) (w : Table Coeff i j k) (d : Fin n) : Table Coeff i j k := + fun x y z => if a y = d then w x y z else 0 + +/-- Evaluates `if a z = d then w x y z else 0` at the input `x y z`. -/ +def byKey (a : Fin k → Fin n) (w : Table Coeff i j k) (d : Fin n) : Table Coeff i j k := + fun x y z => if a z = d then w x y z else 0 + +theorem read_col (f : Character) (w : Table Coeff i j k) (a : Fin j → Fin n) (hn : 0 < n) : + (n : ℝ) ^ f.pX * ∑ t, price f (byCol a w t) ≤ n * price f w := by + apply read_label (coeff w) f hn (fun y => a y.2) (fun z => a z.2) _ + (fun t => coeff (byCol a w t)) <;> intros <;> grind [coeff, byCol] + +theorem read_row (f : Character) (w : Table Coeff i j k) (a : Fin i → Fin n) (hn : 0 < n) : + (n : ℝ) ^ f.pY * ∑ t, price f (byRow a w t) ≤ n * price f w := by + let T (w : Table Coeff i j k) := CoefficientTensor.swapXY (coeff w) + have he (w : Table Coeff i j k) : (f.permuted 1 (ofTensor (T w)) : ℝ) = price f w := rfl + have h := read_label (T w) (f.permuted 1) hn (fun x => a x.1) (fun z => a z.1) + (by intros; unfold T at *; grind [coeff, CoefficientTensor.swapXY]) + (fun t => T (byRow a w t)) (by intros; unfold T at *; grind [coeff, byRow, + CoefficientTensor.swapXY]) + simpa only [he, show (f.permuted 1).pX = f.pY by rw [f.permuted_pX]; rfl] using h + +theorem read_key (f : Character) (w : Table Coeff i j k) (a : Fin k → Fin n) (hn : 0 < n) : + (n : ℝ) ^ f.pZ * ∑ t, price f (byKey a w t) ≤ n * price f w := by + let T (w : Table Coeff i j k) := CoefficientTensor.swapXY (CoefficientTensor.swapYZ (coeff w)) + have he (w : Table Coeff i j k) : (f.permuted 4 (ofTensor (T w)) : ℝ) = price f w := rfl + have h := read_label (T w) (f.permuted 4) hn (fun x => a x.2) (fun y => a y.1) + (by intros; unfold T at *; grind [coeff, CoefficientTensor.swapXY, CoefficientTensor.swapYZ]) + (fun t => T (byKey a w t)) + (by intros; unfold T at *; grind [coeff, byKey, CoefficientTensor.swapXY, + CoefficientTensor.swapYZ]) + simpa only [he, show (f.permuted 4).pX = f.pZ by rw [f.permuted_pX]; rfl] using h + +theorem price_rank (f : Character) {w : Table Coeff i j k} {r : ℕ} + (h : WeightedRankLE w r) : price f w ≤ r := by + have hr : Tensor.RankAtMost (coeff w) r := by + obtain ⟨a, b, c, he⟩ := h + exact ⟨a, b, c, funext fun x => funext fun y => funext fun z => (he x y z).symm⟩ + have he := f.le_rank (ofTensor (coeff w)) + rw [rank_ofTensor] at he + exact_mod_cast he.trans (Nat.cast_le.mpr ((CoefficientTensor.rank_le_iff _ _).mpr hr)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +section +/- # Extracting a diagonal from isolated triples -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open Upper Upper.TensorClass MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +variable {i j k : ℕ} + +theorem diagonal_price (f : Character) (w : Table Coeff i j k) (S : Finset (Cell i j k)) + (hs : ∀ t ∈ S, w t.1 t.2.1 t.2.2 ≠ 0) + (ha : ∀ t ∈ S, ∀ x, w x t.2.1 t.2.2 ≠ 0 → x = t.1) + (hb : ∀ t ∈ S, ∀ y, w t.1 y t.2.2 ≠ 0 → y = t.2.1) + (hc : ∀ t ∈ S, ∀ z, w t.1 t.2.1 z ≠ 0 → z = t.2.2) : + (S.card : ℝ) ≤ price f w := by + classical + let T : Fin S.card ≃ S := (Fintype.equivFinOfCardEq (Fintype.card_coe S)).symm + let a l := (T l).val.1 + let b l := (T l).val.2.1 + let c l := (T l).val.2.2 + have hinj (x y : Fin S.card) (h₁ : a x = a y) (h₂ : b x = b y) (h₃ : c x = c y) : x = y := + T.injective (Subtype.ext (Prod.ext h₁ (Prod.ext h₂ h₃))) + have he : (fun x y z => (w (a x) (b x) (c x))⁻¹ * 1 * 1 * + coeff w (a x, c x) (c y, b y) (a z, b z)) = CoefficientTensor.natTensor S.card := by + funext x y z + simp only [coeff, CoefficientTensor.natTensor, TensorSpectrum.CoefficientTensor.natTensor, + Tensor.diagonal, mul_one] + by_cases h : x = y ∧ x = z + · obtain ⟨rfl, rfl⟩ := h + simp [show w (a x) (b x) (c x) ≠ 0 from hs _ (T x).property] + rw [ite_eq_right h] + split_ifs with hh + · have hz : w (a x) (b y) (c x) = 0 := by + by_contra h' + have hh₁ : a x = a y := ha _ (T y).property _ (by rw [hh.2.1] at h'; exact h') + have hh₂ : b y = b x := hb _ (T x).property _ h' + have hh₃ : c x = c z := hc _ (T z).property _ (by rw [hh.1, hh.2.2] at h'; exact h') + exact h ⟨hinj x y hh₁ hh₂.symm hh.2.1, hinj x z hh.1 (hh₂.symm.trans hh.2.2) hh₃⟩ + rw [hz, mul_zero] + · rw [mul_zero] + have h := scaled_pullback (coeff w) (fun x => (a x, c x)) (fun y => (c y, b y)) + (fun z => (a z, b z)) (fun x => (w (a x) (b x) (c x))⁻¹) (fun _ => 1) (fun _ => 1) + rw [he, ← natCast_eq_ofTensor_natTensor] at h + have hr := f.monotone' h + change f.toHom (S.card : TensorClass) ≤ _ at hr + rw [map_natCast] at hr + exact_mod_cast hr + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +/- # A price bound for triples with bounded completion counts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open Upper Upper.TensorClass Finset + +variable {i j k I J K : ℕ} + (a : Fin i → Fin I) (b : Fin j → Fin J) (c : Fin k → Fin K) (w : Table Coeff i j k) + +private def key (t : Cell i j k) : Cell I J K := (a t.1, b t.2.1, c t.2.2) + +private def bucket (t : Cell I J K) := byKey c (byCol b (byRow a w t.1) t.2.1) t.2.2 + +private theorem bucket_iff (s : Cell I J K) (x y z) : + bucket a b c w s x y z ≠ 0 ↔ (x, y, z) ∈ support w ∧ key a b c (x, y, z) = s := by + simp only [bucket, byKey, byCol, byRow, key, support, mem_filter, mem_univ, true_and, + Prod.ext_iff] + grind + +private theorem read_all (f : Character) (hI : 0 < I) (hJ : 0 < J) (hK : 0 < K) : + (I : ℝ) ^ f.pY * (J : ℝ) ^ f.pX * (K : ℝ) ^ f.pZ * (∑ s, price f (bucket a b c w s)) ≤ + (I : ℝ) * J * K * price f w := by + have h₁ := read_row f w a hI + have h₂ := sum_le_sum (s := univ) (fun t _ => read_col f (byRow a w t) b hJ) + have h₃ := sum_le_sum (s := univ) fun s _ => + sum_le_sum (s := univ) fun t _ => read_key f (byCol b (byRow a w s) t) c hK + simp only [← mul_sum] at h₂ h₃ + simp only [Fintype.sum_prod_type, bucket] + linarith only [mul_le_mul_of_nonneg_left h₁ (by positivity : 0 ≤ (J : ℝ) * K), + mul_le_mul_of_nonneg_left h₂ (by positivity : 0 ≤ (I : ℝ) ^ f.pY * K), + mul_le_mul_of_nonneg_left h₃ (by positivity : 0 ≤ (I : ℝ) ^ f.pY * (J : ℝ) ^ f.pX)] + +private theorem isolate (f : Character) (V : Finset (Cell i j k)) (hs : V ⊆ support w) + (ha : ∀ t ∈ V, ∀ x ∈ rows (support w) t, a x = a t.1 → x = t.1) + (hb : ∀ t ∈ V, ∀ y ∈ cols (support w) t, b y = b t.2.1 → y = t.2.1) + (hc : ∀ t ∈ V, ∀ z ∈ inner (support w) t, c z = c t.2.2 → z = t.2.2) : + (V.card : ℝ) ≤ ∑ s, price f (bucket a b c w s) := by + classical + let W s := V.filter (fun t => key a b c t = s) + have hh (s) : ((W s).card : ℝ) ≤ price f (bucket a b c w s) := by + apply diagonal_price + · intro t ht + exact (bucket_iff _ _ _ _ _ _ _ _).mpr ⟨hs (mem_filter.mp ht).1, (mem_filter.mp ht).2⟩ + · intro t ht x hx + obtain ⟨ht, he⟩ := mem_filter.mp ht + obtain ⟨hx, hx'⟩ := (bucket_iff _ _ _ _ _ _ _ _).mp hx + exact ha t ht x (mem_filter.mpr ⟨mem_univ _, hx⟩) (congrArg Prod.fst (hx'.trans he.symm)) + · intro t ht y hy + obtain ⟨ht, he⟩ := mem_filter.mp ht + obtain ⟨hy, hy'⟩ := (bucket_iff _ _ _ _ _ _ _ _).mp hy + exact hb t ht y (mem_filter.mpr ⟨mem_univ _, hy⟩) (congrArg (fun u + => u.2.1) (hy'.trans he.symm)) + · intro t ht z hz + obtain ⟨ht, he⟩ := mem_filter.mp ht + obtain ⟨hz, hz'⟩ := (bucket_iff _ _ _ _ _ _ _ _).mp hz + exact hc t ht z (mem_filter.mpr ⟨mem_univ _, hz⟩) (congrArg (fun u + => u.2.2) (hz'.trans he.symm)) + have he : ∑ s, (W s).card = V.card := by + simpa [W] using sum_fiberwise V (key a b c) (fun _ => (1 : ℕ)) + rw [← he, Nat.cast_sum] + exact sum_le_sum fun s _ => hh s + +theorem colored {r : ℕ} (hr : WeightedRankLE w r) (f : Character) + (U : Finset (Cell i j k)) (hu : U ⊆ support w) (hI : 0 < I) (hJ : 0 < J) (hK : 0 < K) + (h₁ : ∀ t ∈ U, (rows (support w) t).card ≤ I) + (h₂ : ∀ t ∈ U, (cols (support w) t).card ≤ J) + (h₃ : ∀ t ∈ U, (inner (support w) t).card ≤ K) : + (I : ℝ) ^ f.pY * (J : ℝ) ^ f.pX * (K : ℝ) ^ f.pZ * U.card ≤ 432 * (I : ℝ) * J * K * r := by + obtain ⟨a, b, c, V, hv, hv', ha, hb, hc⟩ := color (support w) U hI hJ hK h₁ h₂ h₃ + have he := read_all a b c w f (by positivity) (by positivity) (by positivity) + have hl := isolate a b c w f V (hv.trans hu) ha hb hc + have hV : (U.card : ℝ) ≤ 2 * V.card := by exact_mod_cast hv' + have hbound (n : ℕ) (x : ℝ) (hx : 0 ≤ x) : (n : ℝ) ^ x ≤ (6 * n : ℕ) ^ x := + Real.rpow_le_rpow (by positivity) (by exact_mod_cast (by omega : n ≤ 6 * n)) hx + have hs : (I : ℝ) ^ f.pY * (J : ℝ) ^ f.pX * (K : ℝ) ^ f.pZ * V.card ≤ + (6 * I : ℕ) * (6 * J : ℕ) * (6 * K : ℕ) * (r : ℝ) := by + refine (le_trans ?_ he).trans ?_ + · exact mul_le_mul (mul_le_mul (mul_le_mul (hbound I _ f.pY_nonneg) (hbound J _ f.pX_nonneg) + (by positivity) (by positivity)) (hbound K _ f.pZ_nonneg) (by positivity) (by positivity)) + hl (by positivity) (by positivity) + · exact mul_le_mul_of_nonneg_left (price_rank f hr) (by positivity) + push_cast at hs + linarith only [hs, mul_le_mul_of_nonneg_left hV (by positivity : 0 + ≤ (I : ℝ) ^ f.pY * (J : ℝ) ^ f.pX * (K : ℝ) ^ f.pZ)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +/- +# Reading the three labels of a weighted product + +Each label is visible on two legs. At each level the shared-tag bound +dominates the arithmetic mean of the child prices times the price of +that wire. Thus every nonzero leaf contributes the same lower bound, +regardless of the coefficient. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Upper Upper.TensorClass MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +variable {i j k : ℕ} (w : Fin i → Fin j → Fin k → Coeff) + +/-- Evaluates `w a b c` at the input `_ _ _`. -/ +def leaf (a : Fin i) (b : Fin j) (c : Fin k) : Tensor Coeff Unit Unit Unit := + fun _ _ _ => w a b c + +/-- Computes the inner by the application `CoefficientTensor.swapYZ (CoefficientTensor.swapXY +(Upper.Separation.shared (leaf w a b)))`. -/ +def inner (b : Fin j) (a : Fin i) := + CoefficientTensor.swapYZ (CoefficientTensor.swapXY (Upper.Separation.shared (leaf w a b))) + +/-- Computes the rows by the application `CoefficientTensor.swapXY (Upper.Separation.shared +(inner w b))`. -/ +def rows (b : Fin j) := CoefficientTensor.swapXY (Upper.Separation.shared (inner w b)) + +/-- Computes the all rows by the application `Upper.Separation.shared (rows w)`. -/ +def allRows := Upper.Separation.shared (rows w) + +theorem price_le_rank (f : Character) {r : ℕ} (h : WeightedRankLE w r) : + (f (ofTensor (allRows w)) : ℝ) ≤ r := by + have hr : Tensor.RankAtMost (allRows w) r := by + obtain ⟨a, b, c, he⟩ := h + refine ⟨fun l x => a l (x.1, x.2.1), fun l y => b l (y.2.1, y.1), + fun l z => c l (z.2.1, z.1), ?_⟩ + funext x y z + simp only [Tensor.rankOne] + rw [he] + simp only [allRows, rows, inner, leaf, Tensor.sharedFirst, + CoefficientTensor.swapXY, + CoefficientTensor.swapYZ] + grind + have hb := f.le_rank (ofTensor (allRows w)) + rw [rank_ofTensor] at hb + exact_mod_cast hb.trans (Nat.cast_le.mpr ((CoefficientTensor.rank_le_iff _ _).mpr hr)) + +private theorem combine (f : Character) {X Y Z : Type} [Fintype X] [Fintype Y] [Fintype Z] + {n : ℕ} (hn : 0 < n) (A : Fin n → Tensor Coeff X Y Z) (m : Fin n → ℕ) + {p q : ℝ} (hq : 0 ≤ q) (h : ∀ i, (m i : ℝ) * p ≤ q * (f (ofTensor (A i)) : ℝ)) : + (∑ i, m i : ℕ) * (p * (n : ℝ) ^ f.pX) ≤ (q * n) * (f (ofTensor (Upper.Separation.shared A)) : + ℝ) := by + have he := Finset.sum_le_sum (s := Finset.univ) (fun i _ => h i) + rw [← Finset.sum_mul, ← Finset.mul_sum, ← Nat.cast_sum] at he + have ht := mul_le_mul_of_nonneg_left (meanTag f hn A) hq + linarith only [ht, mul_le_mul_of_nonneg_right he (by positivity : 0 ≤ (n : ℝ) ^ f.pX)] + +private theorem density_price (f : Character) (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + supportSize w * ((j : ℝ) ^ f.pX * (i : ℝ) ^ f.pY * (k : ℝ) ^ f.pZ) ≤ + (i : ℝ) * j * k * (f (ofTensor (allRows w)) : ℝ) := by + classical + let bit (b : Fin j) (a : Fin i) (c : Fin k) := if w a b c = 0 then 0 else 1 + have hleaf (b : Fin j) (a : Fin i) (c : Fin k) : + (bit b a c : ℝ) * 1 ≤ 1 * (f.permuted 5 (ofTensor (leaf w a b c)) : ℝ) := by + unfold bit + split_ifs with h + · simp + · have he : leaf w a b c ≠ 0 := fun he => h (congrFun (congrFun (congrFun he ()) ()) ()) + simpa only [Nat.cast_one, one_mul] using + (show (1 : ℝ) ≤ f.permuted 5 (ofTensor (leaf w a b c)) by + exact_mod_cast (f.permuted 5).one_le_of_tensor_ne_zero _ he) + have hk' (b : Fin j) (a : Fin i) : + (∑ c, bit b a c : ℕ) * (k : ℝ) ^ f.pZ ≤ k * (f.permuted 1 (ofTensor (inner w b a)) : ℝ) := by + have he := combine (f.permuted 5) hk (leaf w a b) (bit b a) (by norm_num) (hleaf b a) + rw [show (f.permuted 5).pX = f.pZ by rw [f.permuted_pX]; rfl, one_mul, one_mul] at he + exact he + have hi' (b : Fin j) : + (∑ a, ∑ c, bit b a c : ℕ) * ((k : ℝ) ^ f.pZ * (i : ℝ) ^ f.pY) ≤ + ((k : ℝ) * i) * (f (ofTensor (rows w b)) : ℝ) := by + have he := combine (f.permuted 1) hi (inner w b) (fun a => ∑ c, bit b a c) + (by positivity) (hk' b) + rw [show (f.permuted 1).pX = f.pY by rw [f.permuted_pX]; rfl] at he + exact he + have he := combine f hj (rows w) (fun b => ∑ a, ∑ c, bit b a c) (by positivity) hi' + change supportSize w * ((k : ℝ) ^ f.pZ * (i : ℝ) ^ f.pY * (j : ℝ) ^ f.pX) ≤ + (k : ℝ) * i * j * (f (ofTensor (allRows w)) : ℝ) at he + linarith only [he] + +private theorem size_le : supportSize w ≤ i * j * k := by + classical + unfold supportSize + calc + _ ≤ ∑ _ : Fin j, ∑ _ : Fin i, ∑ _ : Fin k, (1 : ℕ) := by + gcongr + split <;> omega + _ = _ := by simp [mul_comm, mul_left_comm] + +private theorem size_zero (h : WeightedRankLE w 0) : supportSize w = 0 := by + obtain ⟨a, b, c, h⟩ := h + have hz (x y z) : w x y z = 0 := by simpa using (h (x, z) (z, y) (x, y)).symm + simp [supportSize, hz] + +theorem coeff_density : DensityBound Coeff := by + intro i j k r hi hj hk w hr + rcases eq_or_lt_of_le (Nat.zero_le (supportSize w)) with h | h + · rw [← h, Nat.cast_zero, zero_mul] + positivity + have hsize : 0 < (supportSize w : ℝ) := by exact_mod_cast h + have hr' : 1 ≤ r := Nat.pos_of_ne_zero fun he => h.ne' (size_zero w (he ▸ hr)) + let s := (i : ℝ) * j * k * r / supportSize w + have hs : 1 ≤ s := (one_le_div hsize).2 (by + exact_mod_cast (size_le w).trans (Nat.le_mul_of_pos_right _ hr')) + have hi' : 1 ≤ (i : ℝ) := by exact_mod_cast hi + have hj' : 1 ≤ (j : ℝ) := by exact_mod_cast hj + have hk' : 1 ≤ (k : ℝ) := by exact_mod_cast hk + have hL : exponent Coeff (Real.log i) (Real.log j) (Real.log k) ≤ Real.log s := by + apply exponent_le_of_characters (Real.log_nonneg hi') (Real.log_nonneg hj') + (Real.log_nonneg hk') (Real.log_nonneg hs) + intro f + apply (Real.le_log_iff_exp_le (by positivity)).2 + rw [Real.exp_add, Real.exp_add, ← Real.rpow_def_of_pos (by positivity), + ← Real.rpow_def_of_pos (by positivity), ← Real.rpow_def_of_pos (by positivity)] + apply (le_div_iff₀ hsize).mpr + rw [mul_comm] + exact (density_price w f hi hj hk).trans + (mul_le_mul_of_nonneg_left (price_le_rank w f hr) (by positivity)) + rw [mul_comm] + apply (le_div_iff₀ hsize).mp + exact (Real.le_log_iff_exp_le (zero_lt_one.trans_le hs)).mp hL + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# Sparse sets of output cells + +Read the column first, with probability proportional to its degree. +The log of the cell count splits into column entropy and average log +degree. Each part is bounded by the log of its alphabet size. The +spectral formula and transposition can only lower the arithmetic +exponent when balancing these two parts. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Upper Upper.TensorClass + +variable {i j k r : ℕ} (u : Finset (Pos i j)) + +private def column (b : Fin j) := Finset.univ.filter fun a : Fin i => (a, b) ∈ u + +private theorem sum_column : ∑ b, (column u b).card = u.card := by + classical + simp only [column, Finset.card_filter] + rw [Finset.sum_comm, ← Fintype.sum_prod_type (fun p : Pos i j => if p ∈ u then 1 else 0)] + simp + +private def prob (b : Fin j) := (column u b).card / (u.card : ℝ) +private def width := ∑ b, prob u b * Real.log (column u b).card + +private theorem prob_nonneg (b) : 0 ≤ prob u b := by unfold prob; positivity + +private theorem prob_sum (hu : u.Nonempty) : ∑ b, prob u b = 1 := by + simp only [prob, ← Finset.sum_div, ← Nat.cast_sum, sum_column] + exact div_self (by exact_mod_cast hu.card_pos.ne') + +private theorem column_pos {b} (h : 0 < prob u b) : (column u b).Nonempty := by + by_contra! he + simp [prob, he] at h + +private theorem entropy_eq (hu : u.Nonempty) : + -(∑ b, prob u b * Real.log (prob u b)) = Real.log u.card - width u := by + have he (b) : prob u b * Real.log (prob u b) = + prob u b * Real.log (column u b).card - prob u b * Real.log u.card := by + rcases eq_or_lt_of_le (prob_nonneg u b) with hb | hb + · simp [← hb] + have hc := (column_pos u hb).card_pos + have hd := hu.card_pos + unfold prob + rw [Real.log_div (by positivity) (by positivity), mul_sub] + simp_rw [he] + rw [Finset.sum_sub_distrib, ← Finset.sum_mul, prob_sum u hu, one_mul, neg_sub] + rfl + +private theorem width_bounds (hu : u.Nonempty) (hj : 0 < j) : + 0 ≤ width u ∧ width u ≤ Real.log i ∧ 0 ≤ Real.log u.card - width u ∧ + Real.log u.card - width u ≤ Real.log j := by + have hq := prob_nonneg u + have hs := prob_sum u hu + have hw₀ : 0 ≤ width u := by + apply Finset.sum_nonneg + intro b _ + rcases eq_or_lt_of_le (hq b) with h | h + · simp [← h] + exact mul_nonneg h.le (Real.log_nonneg (by exact_mod_cast (column_pos u h).card_pos)) + have hw : width u ≤ Real.log i := by + calc + _ ≤ ∑ b, prob u b * Real.log i := by + apply Finset.sum_le_sum + intro b _ + rcases eq_or_lt_of_le (hq b) with h | h + · simp [← h] + apply mul_le_mul_of_nonneg_left _ h.le + refine Real.log_le_log (by exact_mod_cast (column_pos u h).card_pos) ?_ + exact_mod_cast (show (column u b).card ≤ i by simpa using (column u b).card_le_univ) + _ = _ := by rw [← Finset.sum_mul, hs, one_mul] + rw [← entropy_eq u hu] + refine ⟨hw₀, hw, neg_nonneg.mpr (Finset.sum_nonpos ?_), entropy_log_card hj _ hq hs⟩ + intro b _ + have he : prob u b ≤ 1 := hs ▸ Finset.single_le_sum (fun a _ => hq a) (Finset.mem_univ b) + exact mul_nonpos_of_nonneg_of_nonpos (hq b) (Real.log_nonpos (hq b) he) + +variable {w : Fin i → Fin j → Fin k → Coeff} + +private theorem row_price (f : Character) (hk : 0 < k) + (hw : ∀ x y z, w x y z ≠ 0 ↔ (x, y) ∈ u) {b : Fin j} (hb : 0 < prob u b) : + 0 < (f (ofTensor (rows w b)) : ℝ) ∧ + f.pZ * Real.log k + f.pY * Real.log (column u b).card ≤ Real.log (f (ofTensor (rows w b))) := by + have hf (a : Fin i) (ha : a ∈ column u b) : + 0 < (f.permuted 1 (ofTensor (inner w b a)) : ℝ) ∧ + f.pZ * Real.log k ≤ Real.log (f.permuted 1 (ofTensor (inner w b a))) := by + have hl (c : Fin k) (_ : c ∈ Finset.univ) : + 0 < (f.permuted 5 (ofTensor (leaf w a b c)) : ℝ) ∧ + 0 ≤ Real.log (f.permuted 5 (ofTensor (leaf w a b c))) := by + have hh : w a b c ≠ 0 := (hw a b c).2 (Finset.mem_filter.mp ha).2 + have hn : leaf w a b c ≠ 0 := fun he => hh (congrFun (congrFun (congrFun he ()) ()) ()) + have he : (1 : ℝ) ≤ f.permuted 5 (ofTensor (leaf w a b c)) := by + exact_mod_cast (f.permuted 5).one_le_of_tensor_ne_zero _ hn + exact ⟨zero_lt_one.trans_le he, Real.log_nonneg he⟩ + have he := uniformTag (f.permuted 5) (leaf w a b) Finset.univ + ⟨⟨0, hk⟩, Finset.mem_univ _⟩ hl + rw [show (f.permuted 5).pX = f.pZ by rw [f.permuted_pX]; rfl, + Finset.card_univ, Fintype.card_fin, zero_add] at he + exact he + have he := uniformTag (f.permuted 1) (inner w b) _ (column_pos u hb) hf + rw [show (f.permuted 1).pX = f.pY by rw [f.permuted_pX]; rfl] at he + exact he + +private theorem cell_price (f : Character) (hk : 0 < k) (hu : u.Nonempty) + (hw : ∀ x y z, w x y z ≠ 0 ↔ (x, y) ∈ u) (hr : WeightedRankLE w r) : + (Real.log u.card - width u) * f.pX + width u * f.pY + Real.log k * f.pZ ≤ Real.log r := by + have hb {b : Fin j} := row_price u f hk hw (b := b) + obtain ⟨hp, he⟩ := logTag f (rows w) (prob u) (prob_nonneg u) (prob_sum u hu) + (fun b h => (hb h).1) + refine le_trans ?_ (he.trans (Real.log_le_log hp (price_le_rank w f hr))) + rw [← entropy_eq u hu] + calc + _ = ∑ b, (prob u b * Real.log (prob u b) * (-f.pX) + + prob u b * Real.log (column u b).card * f.pY + prob u b * (Real.log k * f.pZ)) := by + simp only [Finset.sum_add_distrib, ← Finset.sum_mul, prob_sum u hu, width] + ring + _ ≤ _ := by + apply Finset.sum_le_sum + intro b _ + rcases eq_or_lt_of_le (prob_nonneg u b) with h | h + · simp [← h] + linarith only [mul_le_mul_of_nonneg_left (hb h).2 h.le] + +private theorem balance {F : Type} [Field F] {a b c t : ℝ} + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) (ht : min a b ≤ t) (ht' : t ≤ max a b) : + exponent F t (a + b - t) c ≤ exponent F a b c := by + have h₁ : 0 ≤ t := (le_min ha hb).trans ht + have h₂ : 0 ≤ a + b - t := by + linarith [max_le (le_add_of_nonneg_right hb) (le_add_of_nonneg_left ha)] + obtain ⟨x, y, z, hp, he⟩ := (support F).attains h₁ h₂ hc + have hab := (support F).bound ha hb hc hp + have hba := (support F).bound hb ha hc hp + rw [transpose F hb ha hc] at hba + rw [← he] + unfold load at * + rcases le_total y z with h | h + · rcases min_le_iff.mp ht with h' | h' <;> + linarith only [hab, hba, mul_nonneg (sub_nonneg.mpr h) (sub_nonneg.mpr h')] + · rcases le_max_iff.mp ht' with h' | h' <;> + linarith only [hab, hba, mul_nonneg (sub_nonneg.mpr h) (sub_nonneg.mpr h')] + +theorem coeff_cells : CellBound Coeff := by + intro i j k r hi hj hk w u hu hw hr + have hr' : 0 < r := by + by_contra! hn + have he : r = 0 := by omega + subst r + obtain ⟨_, _, _, h⟩ := hr + obtain ⟨⟨a, b⟩, hab⟩ := hu + let c : Fin k := ⟨0, hk⟩ + apply (hw a b c).mpr hab + simpa using (h (a, c) (c, b) (a, b)).symm + let a := width u + let b := Real.log u.card - a + have he : a + b = Real.log u.card := by unfold b; ring + obtain ⟨ha, ha', hb, hb'⟩ := width_bounds u hu hj + have hc : 0 ≤ Real.log k := Real.log_nonneg (by exact_mod_cast hk) + have hs : exponent Coeff a b (Real.log k) ≤ Real.log r := + exponent_le_of_characters ha hb hc (Real.log_nonneg (by exact_mod_cast hr')) + (fun f => cell_price u f hk hu hw hr) + have ht : min a b ≤ short i j u.card := + le_min (le_min ((min_le_left _ _).trans ha') ((min_le_right _ _).trans hb')) + (by linarith [min_le_left a b, min_le_right a b]) + have ht' : short i j u.card ≤ max a b := + (min_le_right _ _).trans (by linarith [le_max_left a b, le_max_right a b]) + have hh := balance (F := Coeff) (a := a) (b := b) ha hb hc ht ht' + rw [he] at hh + exact (Real.le_log_iff_exp_le (by positivity)).mp (hh.trans hs) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- # Transferring the finite colored comparison to the arithmetic exponent -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open Upper Upper.TensorClass + +private theorem character_exists : Nonempty Character := by + obtain ⟨f, hf, _⟩ := Spectrum.extension + (fun _ _ _ h => add_mono h le_rfl) (fun _ _ _ h => mul_mono le_rfl h) + TensorClass.zero_le (fun _ => one_le_of_ne_zero) (fun A => ⟨rank A, le_rank_natCast A⟩) + (Nat.castRingHom TensorClass) (Nat.castRingHom NNReal) + (fun m n h => Nat.cast_le.mpr ((natCast_le_natCast_iff m n).mp h)) + exact ⟨⟨f, hf⟩⟩ + +theorem coeff_degrees : DegreeBound Coeff := by + intro i j k I J K r hI hJ hK w U hu h₁ h₂ h₃ hr + rcases U.card.eq_zero_or_pos with h | h + · rw [h, Nat.cast_zero, zero_mul]; positivity + have hU : 0 < (U.card : ℝ) := by positivity + let b := 432 * (I : ℝ) * J * K * r / U.card + have hb (f : Character) : + Real.exp (Real.log J * f.pX + Real.log I * f.pY + Real.log K * f.pZ) ≤ b := by + apply (le_div_iff₀ hU).mpr + rw [Real.exp_add, Real.exp_add, ← Real.rpow_def_of_pos (by positivity), + ← Real.rpow_def_of_pos (by positivity), ← Real.rpow_def_of_pos (by positivity), + mul_comm ((J : ℝ) ^ f.pX)] + exact colored w hr f U hu hI hJ hK h₁ h₂ h₃ + have hl {m : ℕ} (hm : 0 < m) := Real.log_nonneg (by exact_mod_cast hm : 1 ≤ (m : ℝ)) + obtain ⟨f⟩ := character_exists + have hpos : 1 ≤ b := le_trans (Real.one_le_exp (add_nonneg (add_nonneg + (mul_nonneg (hl hJ) f.pX_nonneg) (mul_nonneg (hl hI) f.pY_nonneg)) + (mul_nonneg (hl hK) f.pZ_nonneg))) (hb f) + have hp := zero_lt_one.trans_le hpos + have he := exponent_le_of_characters (hl hI) (hl hJ) (hl hK) (Real.log_nonneg hpos) + (fun f => (Real.le_log_iff_exp_le hp).mpr (hb f)) + rw [mul_comm] + exact (le_div_iff₀ hU).mp ((Real.le_log_iff_exp_le hp).mp he) + +theorem degrees_of_closed (h : ∀ (K : Type) [Field K] [IsAlgClosed K], DegreeBound K) + (F : Type*) [Field F] : DegreeBound F := by + intro i j k I J K r hI hJ hK w U hu h₁ h₂ h₃ hr + obtain ⟨L, _, φ, v, hv, he⟩ := small_witness hr + let _ : Algebra L F := φ.toAlgebra + let ψ := algebraMap L (AlgebraicClosure L) + have hs : support (fun x y z => ψ (v x y z)) = support w := by + rw [← he] + ext t + simp [support] + rw [← hs] at hu h₁ h₂ h₃ + have he := h (AlgebraicClosure L) i j k I J K r hI hJ hK _ U hu h₁ h₂ h₃ (hv.map ψ) + have hl {n : ℕ} (hn : 0 < n) := Real.log_nonneg (by exact_mod_cast hn : 1 ≤ (n : ℝ)) + rw [exponent_extension L F (hl hI) (hl hJ) (hl hK)] + rwa [exponent_extension L (AlgebraicClosure L) (hl hI) (hl hJ) (hl hK)] at he + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Entropy.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Entropy.lean new file mode 100644 index 0000000000..5711ba0fdd --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Entropy.lean @@ -0,0 +1,247 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.UpperBound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Law +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Surplus + +/-! +# Measuring the support by a weighted count + +In a fixed empirical type all three completion counts are constant. +The number of types is polynomial in the power. Consequently the +coloring loss and the cost of selecting a single type disappear. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open MatrixMultiplicationAllFields.TensorSpectrum.TagWords + +theorem degree_bound (F : Type*) [Field F] : DegreeBound F := + degrees_of_closed (fun K _ _ => (closed_fulfills K).degrees) F + +private theorem average (F : Type*) [Field F] {a b c : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + omega F / 3 * (a + b + c) ≤ exponent F a b c := by + obtain ⟨K, _, ⟨alg⟩⟩ := small_field F + rw [exponent_extension K F ha hb hc, omega_extension K F] + have h := Rectangle.support K + obtain ⟨x, y, z, hp, he⟩ := h.attains zero_le_one zero_le_one zero_le_one + rw [square] at he + have h₁ := h.bound ha hb hc hp + have h₂ := h.bound hb hc ha hp + have h₃ := h.bound hc ha hb hp + rw [← cycle K ha hb hc] at h₂ + rw [cycle K hc ha hb] at h₃ + rw [← he] + unfold load at * + linarith only [h₁, h₂, h₃] + +private theorem scalar {I J K : ℕ} {q r a : ℝ} (hi : 0 < I) (hj : 0 < J) (hk : 0 < K) + (h : q * Real.exp (a * (Real.log I + Real.log J + Real.log K)) ≤ 432 * (I : ℝ) * J * K * r) : + q * unitWeight (a - 1) I J K ≤ 432 * r := by + unfold unitWeight + rw [sub_mul, one_mul, Real.exp_sub, Real.exp_add, Real.exp_add, + Real.exp_log (by positivity), Real.exp_log (by positivity), Real.exp_log (by positivity), + ← mul_div_assoc, div_le_iff₀ (by positivity)] + linarith only [h] + +variable {F : Type*} [Field F] {i j k : ℕ} (w : Fin i → Fin j → Fin k → F) + (e : Fin (support w).card ≃ support w) + +private theorem counted (n : ℕ) : + (∑ b, weight (support w) e (omega F / 3 - 1) b) ^ n ≤ + 432 * ((n : ℝ) + 1) ^ (support w).card * rankW (WPower w n) := by + let S := support w + let p := omega F / 3 + let a := weight S e (p - 1) + obtain ⟨t, ht⟩ := exists_fiberMass_ge_average (N := n) a + obtain ⟨U, hU, he, h⟩ := Sparse.fiber w e n t + let I := countWeight (rCount S e) t + let J := countWeight (cCount S e) t + let K := countWeight (kCount S e) t + have hi : 0 < I := Finset.prod_pos (fun l _ => pow_pos (rCount_pos S e l) _) + have hj : 0 < J := Finset.prod_pos (fun l _ => pow_pos (cCount_pos S e l) _) + have hk : 0 < K := Finset.prod_pos (fun l _ => pow_pos (kCount_pos S e l) _) + have hb := degree_bound F _ _ _ I J K _ hi hj hk (WPower w n) U hU + (fun t ht => (h t ht).1.le) (fun t ht => (h t ht).2.1.le) (fun t ht => (h t ht).2.2.le) + (rankW_spec (WPower w n)) + have hl {m : ℕ} (hm : 0 < m) := Real.log_nonneg (by exact_mod_cast hm : 1 ≤ (m : ℝ)) + have hp := Real.exp_le_exp.mpr (average F (hl hi) (hl hj) (hl hk)) + have hh := scalar hi hj hk ((mul_le_mul_of_nonneg_left hp (Nat.cast_nonneg U.card)).trans hb) + have hc : countWeight a t = unitWeight (p - 1) I J K := + unit_count _ _ _ _ (rCount_pos S e) (cCount_pos S e) (kCount_pos S e) t + rw [fiberMass, ← he, hc] at ht + have hg := (div_le_iff₀ (by positivity)).mp (ht.trans hh) + exact hg.trans_eq (mul_right_comm _ _ _) + +theorem mass_bound (n : ℕ) : + (∑ b, weight (support w) e (omega F / 3 - 1) b) ^ n ≤ rankW (WPower w n) := by + have hnon : 0 ≤ ∑ b, weight (support w) e (omega F / 3 - 1) b := + Finset.sum_nonneg fun _ _ => (Real.exp_pos _).le + apply TensorSpectrum.le_of_pow_le_polynomial_mul_pow _ _ (432 * ((n : ℝ) + 1) ^ (support w).card) + (support w).card (by positivity) (by positivity) + intro m hm + rw [← pow_mul, Real.rpow_natCast] + refine (counted w e (n * m)).trans ?_ + have hr : (rankW (WPower w (n * m)) : ℝ) ≤ (rankW (WPower w n) : ℝ) ^ m := by + exact_mod_cast rankW_mul w n m hm + rw [mul_assoc 432 (((n : ℝ) + 1) ^ (support w).card), ← mul_pow, Nat.cast_mul] + gcongr + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +section +/- # The entropy refinement for sparse weighted products -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open Filter + +variable {F : Type*} [Field F] {i j k : ℕ} (w : Fin i → Fin j → Fin k → F) + +/-- Natural-log form with the actual arithmetic exponent. -/ +theorem entropy_lower (hw : (support w).Nonempty) : + (support w).card * Real.exp ((omega F / 3 - 1) * conditional (support w)) ≤ asymptoticRank w + := by + obtain ⟨t, ht⟩ := hw + have hw : (support w).Nonempty := ⟨t, ht⟩ + have hi := Nat.zero_lt_of_lt t.1.isLt + have hj := Nat.zero_lt_of_lt t.2.1.isLt + have hk := Nat.zero_lt_of_lt t.2.2.isLt + have hd : 0 < density w := by + rw [density, ← card_support] + exact div_pos (by exact_mod_cast hw.card_pos) (by positivity) + let S := support w + let e : Fin S.card ≃ S := (Fintype.equivFinOfCardEq (Fintype.card_coe S)).symm + refine (exp_conditional S e hw _).trans ?_ + apply ge_of_tendsto (tendsto_asymptoticRank hi hj hk hd) + filter_upwards [eventually_gt_atTop 0] with n hn + have h : 0 ≤ ∑ b, weight S e (omega F / 3 - 1) b := Finset.sum_nonneg fun _ _ + => (Real.exp_pos _).le + rw [← Real.pow_rpow_inv_natCast h hn.ne'] + exact Real.rpow_le_rpow (pow_nonneg h _) (mass_bound w e n) (by positivity) + +/-- A support and entropy lower bound for asymptotic rank at square exponent nine fourths. -/ +theorem support_exponent (hω : omega F = 9 / 4) (hw : (support w).Nonempty) : + (supportSize w : ℝ) ^ (3 / 4 : ℝ) * (2 : ℝ) ^ (premium (support w) / 4) ≤ asymptoticRank w := by + let S := support w + have hm : 0 < (S.card : ℝ) := Nat.cast_pos.mpr hw.card_pos + have ht : 0 < Real.log 2 := Real.log_pos (by norm_num) + have he := entropy_lower w hw + rw [hω] at he + rw [← card_support] + refine le_trans ?_ he + change (S.card : ℝ) ^ (3 / 4 : ℝ) * (2 : ℝ) ^ (premium S / 4) ≤ + S.card * Real.exp ((9 / 4 / 3 - 1) * conditional S) + apply le_of_eq + rw [Real.rpow_def_of_pos hm, Real.rpow_def_of_pos (by norm_num : (0 : ℝ) < 2), + ← Real.exp_add, premium] + have hlog : Real.log (S.card : ℝ) * (3 / 4) + + Real.log 2 * ((Real.log S.card - conditional S) / Real.log 2 / 4) = + Real.log S.card + (9 / 4 / 3 - 1) * conditional S := by field_simp; ring + rw [hlog, Real.exp_add, Real.exp_log hm] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +section +/- +# Preservation of the exponent at subpolynomial density + +The lower bound allows both the support and the coefficients to vary +with the size. All-ones weightings attain the exponent even for exact +rank, by taking powers of a single slightly more efficient block. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open Filter + +variable (F : Type*) [Field F] {a b c : ℝ} + +private theorem rounded_lower (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) : + (n : ℝ) ^ exponent F a b c ≤ + Real.exp (exponent F (Real.log (side n a)) (Real.log (side n b)) (Real.log (side n c))) := by + have h (x : ℝ) : Real.log n * x ≤ Real.log (side n x) := by + rw [mul_comm, ← Real.log_rpow (by positivity)] + exact Real.log_le_log (by positivity) (Nat.le_ceil _) + have h₀ (x : ℝ) : 0 ≤ Real.log (side n x) := Real.log_nonneg (by exact_mod_cast side_pos hn x) + have hn' : 0 ≤ Real.log n := Real.log_nonneg (by exact_mod_cast hn) + obtain ⟨K, _, ⟨alg⟩⟩ := small_field F + rw [Real.rpow_def_of_pos (by positivity), Real.exp_le_exp, + exponent_extension K F ha hb hc, exponent_extension K F (h₀ a) (h₀ b) (h₀ c), + ← homogeneous K ha hb hc hn'] + obtain ⟨x, y, z, hp, he⟩ := (Rectangle.support K).attains (mul_nonneg hn' ha) + (mul_nonneg hn' hb) (mul_nonneg hn' hc) + obtain ⟨hx, hy, hz⟩ := hp.nonneg + rw [← he] + refine le_trans ?_ ((Rectangle.support K).bound (h₀ a) (h₀ b) (h₀ c) hp) + unfold load + gcongr <;> apply h + +theorem preservation (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (w : ∀ n, Fin (side n a) → Fin (side n b) → Fin (side n c) → F) + (h : ∀ ε : ℝ, 0 < ε → ∀ᶠ n : ℕ in atTop, (n : ℝ) ^ (-ε) ≤ density (w n)) + {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ n : ℕ in atTop, (n : ℝ) ^ (exponent F a b c - ε) ≤ asymptoticRank (w n) ∧ + ∀ r, BorderRankLE (w n) r → (n : ℝ) ^ (exponent F a b c - ε) ≤ r := by + filter_upwards [eventually_gt_atTop 0, h ε hε] with n hn hd + have hi := side_pos hn a + have hj := side_pos hn b + have hk := side_pos hn c + have hw : 0 < density (w n) := lt_of_lt_of_le (by positivity) hd + rw [sub_eq_add_neg, add_comm, Real.rpow_add (by positivity)] + have hl := mul_le_mul hd (rounded_lower F ha hb hc hn) (by positivity) hw.le + exact ⟨hl.trans (asymptotic_density hi hj hk hw), fun _ hr => hl.trans (hr.density hi hj hk)⟩ + +theorem ordinary_bounds (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ n : ℕ in atTop, + let w := ordinary F (side n a) (side n b) (side n c) + density w = 1 ∧ (n : ℝ) ^ exponent F a b c ≤ asymptoticRank w ∧ + asymptoticRank w ≤ rankW w ∧ (rankW w : ℝ) ≤ (n : ℝ) ^ (exponent F a b c + ε) := by + let t := exponent F a b c + ε / 2 + have ht : 0 ≤ t := by + have := (le_max_left _ _).trans (bounds F ha hb hc).1 + unfold t; linarith + obtain ⟨d, r, hd, hr, hr'⟩ := (exponent_lt_iff_rank ha hb hc).mp + (show exponent F a b c < t by unfold t; linarith) + have hlim := (tendsto_rpow_atTop (half_pos hε)).comp tendsto_natCast_atTop_atTop + filter_upwards [eventually_gt_atTop 0, hlim.eventually_ge_atTop (r : ℝ)] with n hn hbig + intro w + have hi := side_pos hn a + have hj := side_pos hn b + have hk := side_pos hn c + have hw : ∀ x y z, w x y z ≠ 0 := fun _ _ _ => one_ne_zero + refine ⟨?_, ?_⟩ + · rw [density, full_size hw, Nat.cast_mul, Nat.cast_mul, div_self (by positivity)] + rw [ordinary_rank F hi hj hk] + refine ⟨rounded_lower F ha hb hc hn, (rankW_spec w).full hw hi hj hk, ?_⟩ + obtain ⟨p, hlo, hup⟩ := exists_nat_pow_near (by exact_mod_cast hn : 1 ≤ (n : ℝ)) + (by exact_mod_cast hd : 1 < (d : ℝ)) + have hp {x : ℝ} (hx : 0 ≤ x) : side n x ≤ (side d x) ^ (p + 1) := + (Nat.ceil_mono (Real.rpow_le_rpow (by positivity) (by exact_mod_cast hup.le) hx)).trans + (side_pow le_rfl (p + 1)) + have hh : rankW w ≤ r ^ (p + 1) := rankW_le ((hr.pow (p + 1)).cut (hp ha) (hp hb) (hp hc)) + calc + _ ≤ (r : ℝ) ^ (p + 1) := by exact_mod_cast hh + _ ≤ ((d : ℝ) ^ t) ^ p * r := by rw [pow_succ]; gcongr + _ = ((d : ℝ) ^ p) ^ t * r := by rw [Real.rpow_pow_comm (by positivity)] + _ ≤ (n : ℝ) ^ t * (n : ℝ) ^ (ε / 2) := + mul_le_mul (Real.rpow_le_rpow (by positivity) hlo ht) hbig (by positivity) (by positivity) + _ = _ := by + have ht' : t + ε / 2 = exponent F a b c + ε := by + unfold t + ring + rw [← Real.rpow_add (by positivity), ht'] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Law.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Law.lean new file mode 100644 index 0000000000..09f844b24a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Law.lean @@ -0,0 +1,690 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights +public import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +public import Mathlib.Logic.Equiv.Fin.Basic +public import Mathlib.LinearAlgebra.Matrix.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.FiniteModel +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Data.Fintype.BigOperators +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagWords +public import Mathlib.Algebra.BigOperators.Field +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagEntropy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Mask + +/-! # Decompositions of weighted rectangular products -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} [CommSemiring F] {i j k i' j' k' I J K r s : ℕ} + +/-- One term for every row, column and inner index. -/ +theorem weighted_volume (w : Fin i → Fin j → Fin k → F) : WeightedRankLE w (i * j * k) := by + rw [mul_right_comm i j k] + let e : Fin (i * k * j) ≃ Pos i k × Fin j := + finProdFinEquiv.symm.trans (Equiv.prodCongr finProdFinEquiv.symm (Equiv.refl _)) + refine ⟨fun l x => if (e l).1 = x then 1 else 0, + fun l y => if (e l).1.2 = y.1 ∧ (e l).2 = y.2 then 1 else 0, + fun l z => if (e l).1.1 = z.1 ∧ (e l).2 = z.2 then w (e l).1.1 (e l).2 (e l).1.2 else 0, ?_⟩ + intro x y z + rw [Fintype.sum_eq_single (e.symm (x, y.2))] + · by_cases h : x.2 = y.1 <;> simp [h] + · intro l hl + by_cases h : (e l).1 = x + · have h' : (e l).2 ≠ y.2 := fun h' => hl (e.eq_symm_apply.mpr (Prod.ext h h')) + simp [h'] + · simp [h] + +/-- Tensor two decompositions, allowing an arbitrary enumeration of paired +side indices. Summing over the paired terms factors the coefficient identity. -/ +theorem WeightedRankLE.tensor {w : Fin i → Fin j → Fin k → F} {v : Fin i' → Fin j' → Fin k' → F} + (h : WeightedRankLE w r) (h' : WeightedRankLE v s) + (u : Fin I ≃ Pos i i') (q : Fin J ≃ Pos j j') (p : Fin K ≃ Pos k k') : + WeightedRankLE (fun x y z => w (u x).1 (q y).1 (p z).1 * v (u x).2 (q y).2 (p z).2) (r * s) + := by + obtain ⟨a, b, c, h⟩ := h + obtain ⟨a', b', c', h'⟩ := h' + let coeff {n m g l N M : ℕ} (e : Fin N ≃ Pos n m) (f : Fin M ≃ Pos g l) + (α : Fin r → Pos n g → F) (β : Fin s → Pos m l → F) (t : Fin (r * s)) (x : Pos N M) := + α (finProdFinEquiv.symm t).1 ((e x.1).1, (f x.2).1) * + β (finProdFinEquiv.symm t).2 ((e x.1).2, (f x.2).2) + refine ⟨coeff u p a a', coeff p q b b', coeff u q c c', ?_⟩ + intro x y z + calc + _ = (∑ l, a l ((u x.1).1, (p x.2).1) * b l ((p y.1).1, (q y.2).1) * + c l ((u z.1).1, (q z.2).1)) * + (∑ l, a' l ((u x.1).2, (p x.2).2) * b' l ((p y.1).2, (q y.2).2) * + c' l ((u z.1).2, (q z.2).2)) := by + rw [← finProdFinEquiv.sum_comp, Fintype.sum_prod_type, Finset.sum_mul] + apply Finset.sum_congr rfl + intro l _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro l' _ + simp only [coeff, Equiv.symm_apply_apply] + rw [mul_mul_mul_comm (a _ _), mul_mul_mul_comm] + _ = _ := by + rw [h, h', ite_mul, zero_mul, mul_ite, mul_zero, ← ite_and] + have he {n m N : ℕ} (e : Fin N ≃ Pos n m) (u v : Fin N) : + u = v ↔ (e u).1 = (e v).1 ∧ (e u).2 = (e v).2 := + e.injective.eq_iff.symm.trans Prod.ext_iff + simp only [he u x.1 z.1, he p x.2 y.1, he q y.2 z.2, and_assoc, and_left_comm, and_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- Permutation symmetry and the elementary area and volume bounds. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} {i j k r : ℕ} + +theorem RankLE.cycle [CommSemiring F] (h : RankLE F i j k r) : RankLE F j k i r := by + obtain ⟨a, b, c, h⟩ := h + refine ⟨fun l x => c l x.swap, a, fun l z => b l z.swap, ?_⟩ + intro x y z + simpa only [Prod.fst_swap, Prod.snd_swap, mul_assoc, mul_comm, mul_left_comm, + and_assoc, and_comm, and_left_comm, eq_comm] using h y z.swap x.swap + +theorem RankLE.transpose [CommSemiring F] (h : RankLE F i j k r) : RankLE F j i k r := by + obtain ⟨a, b, c, h⟩ := h + refine ⟨fun l x => b l x.swap, fun l y => a l y.swap, fun l z => c l z.swap, ?_⟩ + intro x y z + simpa only [Prod.fst_swap, Prod.snd_swap, mul_comm, and_assoc, and_comm, and_left_comm, + eq_comm] using h y.swap x.swap z.swap + +/-- Fixing the inner index gives an identity submatrix of the output flattening. -/ +theorem RankLE.area [CommSemiring F] [StrongRankCondition F] (h : RankLE F i j k r) + (hk : 0 < k) : i * j ≤ r := by + obtain ⟨a, b, c, h⟩ := h + let v : Fin k := ⟨0, hk⟩ + let A : Matrix (Pos i j) (Fin r) F := fun x l => a l (x.1, v) * b l (v, x.2) + let B : Matrix (Fin r) (Pos i j) F := c + have hAB : A * B = 1 := by + ext x z + rw [Matrix.mul_apply, Matrix.one_apply] + simpa only [A, B, Prod.ext_iff, true_and] using h (x.1, v) (v, x.2) z + have := (Matrix.rank_mul_le_left A B).trans A.rank_le_card_width + simpa only [hAB, Matrix.rank_one, Pos, Fintype.card_prod, Fintype.card_fin] using this + +/-- One product per row, column and inner index. -/ +theorem rank_volume (F : Type*) [CommSemiring F] (i j k : ℕ) : RankLE F i j k (i * j * k) := + weighted_volume (fun (_ : Fin i) (_ : Fin j) (_ : Fin k) => (1 : F)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- Tensor products, powers and cyclic symmetrization of rectangular decompositions. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F K : Type*} {i j k i' j' k' r s : ℕ} + +theorem RankLE.map [CommSemiring F] [CommSemiring K] + (h : RankLE F i j k r) (f : F →+* K) : RankLE K i j k r := by + have weighted : WeightedRankLE (ordinary F i j k) r := h + have mapOrdinary : (fun x y z => f (ordinary F i j k x y z)) = ordinary K i j k := by + funext x y z + exact map_one f + change WeightedRankLE (ordinary K i j k) r + rw [← mapOrdinary] + exact weighted.map f + +/-- Split each matrix index into two digits and multiply the corresponding +coefficients. Summing over pairs of terms factors the coefficient identity. -/ +theorem RankLE.tensor [CommSemiring F] (h : RankLE F i j k r) (h' : RankLE F i' j' k' s) : + RankLE F (i * i') (j * j') (k * k') (r * s) := by + have hw : WeightedRankLE (fun (_ : Fin i) (_ : Fin j) (_ : Fin k) => (1 : F)) r := h + have hv : WeightedRankLE (fun (_ : Fin i') (_ : Fin j') (_ : Fin k') => (1 : F)) s := h' + have ht := hw.tensor hv finProdFinEquiv.symm finProdFinEquiv.symm finProdFinEquiv.symm + simp only [one_mul] at ht + exact ht + +theorem RankLE.pow [CommSemiring F] (h : RankLE F i j k r) (p : ℕ) : + RankLE F (i ^ p) (j ^ p) (k ^ p) (r ^ p) := by + induction p with + | zero => simpa using rank_volume F 1 1 1 + | succ p ih => simpa only [pow_succ] using ih.tensor h + +/-- Tensoring the three cyclic arrangements makes all sides equal to the volume. -/ +theorem RankLE.symmetrize [CommSemiring F] (h : RankLE F i j k r) : + MatrixExponent.RankLE F (i * j * k) (r ^ 3) := by + change RankLE F (i * j * k) (i * j * k) (i * j * k) (r ^ 3) + simpa only [pow_succ, pow_zero, mul_one, one_mul, mul_assoc, mul_comm, mul_left_comm] using + (h.tensor h.cycle).tensor h.cycle.cycle + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# Powers of weighted products + +Side indices of a power are digit strings. Coefficients multiply over +digits, so support sizes multiply and rank bounds are submultiplicative. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} {i j k r : ℕ} + +theorem rankW_spec [CommSemiring F] (w : Fin i → Fin j → Fin k → F) : WeightedRankLE w (rankW w) := + Nat.sInf_mem (show {r : ℕ | WeightedRankLE w r}.Nonempty from ⟨_, weighted_volume w⟩) + +theorem rankW_le [CommSemiring F] {w : Fin i → Fin j → Fin k → F} (h : WeightedRankLE w r) : + rankW w ≤ r := + Nat.sInf_le h + +@[simp] theorem WPower_one [CommMonoid F] (n : ℕ) : + WPower (fun (_ : Fin i) (_ : Fin j) (_ : Fin k) => (1 : F)) n = fun _ _ _ => 1 := by + funext a b c + simp [WPower] + +private def split (d n m : ℕ) : Fin (d ^ (n + m)) ≃ Fin (d ^ n) × Fin (d ^ m) := + finFunctionFinEquiv.symm.trans ((Fin.appendEquiv n m).symm.trans + (Equiv.prodCongr finFunctionFinEquiv finFunctionFinEquiv)) + +theorem rankW_add [CommSemiring F] (w : Fin i → Fin j → Fin k → F) (n m : ℕ) : + rankW (WPower w (n + m)) ≤ rankW (WPower w n) * rankW (WPower w m) := by + apply rankW_le + have h := (rankW_spec (WPower w n)).tensor (rankW_spec (WPower w m)) + (split i n m) (split j n m) (split k n m) + convert h using 1 + funext a b c + unfold WPower + rw [Fin.prod_univ_add] + simp [split, Fin.appendEquiv] + +private theorem sum_words {n d : ℕ} (f : Fin n → Fin d → ℕ) : + (∑ a : Fin (d ^ n), ∏ l, f l (finFunctionFinEquiv.symm a l)) = ∏ l, ∑ a, f l a := by + rw [← finFunctionFinEquiv.sum_comp, Fintype.prod_sum] + simp only [Equiv.symm_apply_apply] + +open Classical in +private theorem indicator_prod [CommMonoidWithZero F] [Nontrivial F] [NoZeroDivisors F] + {n : ℕ} (f : Fin n → F) : + (if ∏ l, f l = 0 then 0 else 1) = ∏ l, if f l = 0 then (0 : ℕ) else 1 := by + by_cases h : ∃ l, f l = 0 + · obtain ⟨l, hl⟩ := h + rw [Finset.prod_eq_zero (Finset.mem_univ l) hl, ite_eq_left rfl] + exact (Finset.prod_eq_zero (Finset.mem_univ l) (by simp [hl])).symm + · push Not at h + simp [h, Finset.prod_ne_zero_iff] + +theorem supportSize_power [CommMonoidWithZero F] [Nontrivial F] [NoZeroDivisors F] + (w : Fin i → Fin j → Fin k → F) (n : ℕ) : + supportSize (WPower w n) = (supportSize w) ^ n := by + classical + unfold supportSize WPower + simp_rw [indicator_prod] + let f a b c := if w a b c = 0 then (0 : ℕ) else 1 + have h₁ (a : Fin (i ^ n)) (b : Fin (j ^ n)) := + sum_words (fun l c => f (finFunctionFinEquiv.symm a l) (finFunctionFinEquiv.symm b l) c) + have h₂ (b : Fin (j ^ n)) := + sum_words (fun l a => ∑ c, f a (finFunctionFinEquiv.symm b l) c) + have h₃ := sum_words (fun (_ : Fin n) b => ∑ a, ∑ c, f a b c) + unfold f at h₁ h₂ h₃ + simp_rw [h₁, h₂, h₃] + simp only [Finset.prod_const, Finset.card_univ, Fintype.card_fin] + +theorem rankW_mul [CommSemiring F] (w : Fin i → Fin j → Fin k → F) (n m : ℕ) (hm : 1 ≤ m) : + rankW (WPower w (n * m)) ≤ (rankW (WPower w n)) ^ m := by + induction m, hm using Nat.le_induction with + | base => rw [mul_one, pow_one] + | succ m _ ih => + rw [Nat.mul_succ, pow_succ] + exact (rankW_add w _ _).trans (Nat.mul_le_mul_right _ ih) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Isolating triples by coloring the three alphabets + +For two different labels only a fraction `1/m` of the `m`-colorings +identify them. The union bound and averaging retain at least five +sixths of the candidate triples at each of the three steps. Completion +lists always refer to the original support. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open Finset + +variable {α : Type*} {i m d : ℕ} + +private def collisions (m : ℕ) (x y : Fin i) := + univ.filter fun c : Fin i → Fin m => c x = c y + +private theorem collision_bound {x y : Fin i} (h : x ≠ y) : + (collisions m x y).card * m ≤ Fintype.card (Fin i → Fin m) := by + let f (p : (collisions m x y) × Fin m) := Function.update p.1.val x p.2 + have hi : Function.Injective f := by + rintro ⟨c, a⟩ ⟨c', a'⟩ he + have ha : a = a' := by simpa [f] using congrFun he x + have hc (z) (hz : z ≠ x) : c.val z = c'.val z := by simpa [f, hz] using congrFun he z + have hh : c = c' := by + apply Subtype.ext + funext z + by_cases hz : z = x + · subst z + exact (mem_filter.mp c.property).2.trans ((hc y h.symm).trans (mem_filter.mp + c'.property).2.symm) + · exact hc z hz + exact Prod.ext hh ha + simpa only [Fintype.card_prod, Fintype.card_coe, Fintype.card_fin] + using Fintype.card_le_of_injective f hi + +private theorem one_label (U : Finset α) (label : α → Fin i) (N : α → Finset (Fin i)) + (hd : 0 < d) (hN : ∀ t ∈ U, (N t).card ≤ d) : + ∃ (c : Fin i → Fin (6 * d)) (V : Finset α), + V ⊆ U ∧ 5 * U.card ≤ 6 * V.card ∧ ∀ t ∈ V, ∀ x ∈ N t, c x = c (label t) → x = label t := by + classical + let C := Fin i → Fin (6 * d) + let bad (t : α) : Finset C := ((N t).erase (label t)).biUnion fun x + => collisions (6 * d) x (label t) + have hb (t) (ht : t ∈ U) : 6 * (bad t).card ≤ Fintype.card C := by + let A := (N t).erase (label t) + have hA : A.card ≤ d := card_erase_le.trans (hN t ht) + apply Nat.le_of_mul_le_mul_right _ hd + calc + 6 * (bad t).card * d = (bad t).card * (6 * d) := by ring + _ ≤ (∑ x ∈ A, (collisions (6 * d) x (label t)).card) * (6 * d) := + Nat.mul_le_mul_right _ card_biUnion_le + _ ≤ ∑ _ ∈ A, Fintype.card C := by + rw [sum_mul] + exact sum_le_sum (fun x hx => collision_bound (mem_erase.mp hx).1) + _ ≤ Fintype.card C * d := by + simp only [sum_const, nsmul_eq_mul, Nat.cast_id, mul_comm A.card] + exact Nat.mul_le_mul_left _ hA + have havg : (∑ c : C, 6 * (U.filter fun t => c ∈ bad t).card) ≤ ∑ _ : C, U.card := by + calc + _ = ∑ t ∈ U, 6 * (bad t).card := by + simp_rw [card_filter, mul_sum] + rw [sum_comm] + simp [← mul_sum, mul_comm] + _ ≤ ∑ _ ∈ U, Fintype.card C := sum_le_sum hb + _ = _ := by simp [mul_comm] + have : Nonempty C := ⟨fun _ => ⟨0, by omega⟩⟩ + obtain ⟨c, _, hc⟩ := exists_le_of_sum_le univ_nonempty havg + refine ⟨c, U.filter (fun t => c ∉ bad t), filter_subset _ _, ?_, ?_⟩ + · have he := card_filter_add_card_filter_not (s := U) (fun t => c ∈ bad t) + omega + · intro t ht x hx he + by_contra hne + exact (mem_filter.mp ht).2 (mem_biUnion.mpr + ⟨x, mem_erase.mpr ⟨hne, hx⟩, mem_filter.mpr ⟨mem_univ _, he⟩⟩) + +theorem color {i j k d e f : ℕ} (S U : Finset (Cell i j k)) + (hd : 0 < d) (he : 0 < e) (hf : 0 < f) + (hr : ∀ t ∈ U, (rows S t).card ≤ d) (hc : ∀ t ∈ U, (cols S t).card ≤ e) + (hi : ∀ t ∈ U, (inner S t).card ≤ f) : + ∃ (a : Fin i → Fin (6 * d)) (b : Fin j → Fin (6 * e)) (c : Fin k → Fin (6 * f)) + (V : Finset (Cell i j k)), V ⊆ U ∧ U.card ≤ 2 * V.card ∧ + (∀ t ∈ V, ∀ x ∈ rows S t, a x = a t.1 → x = t.1) ∧ + (∀ t ∈ V, ∀ y ∈ cols S t, b y = b t.2.1 → y = t.2.1) ∧ + (∀ t ∈ V, ∀ z ∈ inner S t, c z = c t.2.2 → z = t.2.2) := by + obtain ⟨a, X, hX, hx, ha⟩ := one_label U (·.1) (rows S) hd hr + obtain ⟨b, Y, hY, hy, hb⟩ := one_label X (·.2.1) (cols S) he fun t ht => hc t (hX ht) + obtain ⟨c, V, hV, hv, hc⟩ := one_label Y (·.2.2) (inner S) hf fun t ht => hi t (hX (hY ht)) + exact ⟨a, b, c, V, hV.trans (hY.trans hX), by omega, + fun t ht => ha t (hY (hV ht)), fun t ht => hb t (hV ht), hc⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +section +/- # A finite rank comparison for bounded completion sets -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse + +/-- The constant pays for three independent colorings and the +loss of at most half of the selected triples. Tensor powers remove it. -/ +def DegreeBound (F : Type*) [Field F] : Prop := + ∀ i j k I J K r : ℕ, 0 < I → 0 < J → 0 < K → + ∀ (w : Fin i → Fin j → Fin k → F) (U : Finset (Cell i j k)), U ⊆ support w → + (∀ t ∈ U, (rows (support w) t).card ≤ I) → + (∀ t ∈ U, (cols (support w) t).card ≤ J) → + (∀ t ∈ U, (inner (support w) t).card ≤ K) → + WeightedRankLE w r → + U.card * Real.exp (exponent F (Real.log I) (Real.log J) (Real.log K)) ≤ + 432 * (I : ℝ) * J * K * r + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +section +/- # Completion counts for powers of a partial product -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open Finset + +variable {F : Type*} {i j k n : ℕ} + +/-- The indexed operation `(finFunctionFinEquiv (fun l => (p l).1), finFunctionFinEquiv (fun l +=> (p l).2.1), finFunctionFinEquiv (fun l => (p l).2.2))`. -/ +def pack (p : Fin n → Cell i j k) : Cell (i ^ n) (j ^ n) (k ^ n) := + (finFunctionFinEquiv (fun l => (p l).1), finFunctionFinEquiv (fun l => (p l).2.1), + finFunctionFinEquiv (fun l => (p l).2.2)) + +theorem pack_injective : Function.Injective (@pack i j k n) := by + let unpack (t : Cell (i ^ n) (j ^ n) (k ^ n)) (l : Fin n) := + (finFunctionFinEquiv.symm t.1 l, finFunctionFinEquiv.symm t.2.1 l, + finFunctionFinEquiv.symm t.2.2 l) + apply Function.LeftInverse.injective (g := unpack) + intro p + funext l + simp [unpack, pack] + +variable (w : Fin i → Fin j → Fin k → F) (p : Fin n → Cell i j k) + +theorem card_support [Zero F] : (support w).card = supportSize w := by + classical + rw [support, card_filter, Fintype.sum_prod_type] + simp_rw [Fintype.sum_prod_type, ite_not] + rw [sum_comm] + rfl + +variable [CommMonoidWithZero F] [Nontrivial F] [NoZeroDivisors F] + +theorem mem_pack : pack p ∈ support (WPower w n) ↔ ∀ l, p l ∈ support w := by + simp only [support, mem_filter, mem_univ, true_and] + simp [WPower, pack, prod_ne_zero_iff] + +/-- Completed labels are independent digit strings. -/ +private theorem count_digits {d : ℕ} (A : Finset (Fin (d ^ n))) (B : Fin n → Finset (Fin d)) + (h : ∀ x, x ∈ A ↔ ∀ l, finFunctionFinEquiv.symm x l ∈ B l) : + A.card = ∏ l, (B l).card := by + have he : A = (Fintype.piFinset B).map finFunctionFinEquiv.toEmbedding := by + ext x + rw [h, mem_map_equiv, Fintype.mem_piFinset] + rw [he, card_map, Fintype.card_piFinset] + +theorem rows_power : + (rows (support (WPower w n)) (pack p)).card = ∏ l, (rows (support w) (p l)).card := by + apply count_digits + intro x + simp only [rows, mem_filter, mem_univ, true_and] + simp only [support, mem_filter, mem_univ, true_and] + simp [WPower, pack, prod_ne_zero_iff] + +theorem cols_power : + (cols (support (WPower w n)) (pack p)).card = ∏ l, (cols (support w) (p l)).card := by + apply count_digits + intro x + simp only [cols, mem_filter, mem_univ, true_and] + simp only [support, mem_filter, mem_univ, true_and] + simp [WPower, pack, prod_ne_zero_iff] + +theorem inner_power : + (inner (support (WPower w n)) (pack p)).card = ∏ l, (inner (support w) (p l)).card := by + apply count_digits + intro x + simp only [inner, mem_filter, mem_univ, true_and] + simp only [support, mem_filter, mem_univ, true_and] + simp [WPower, pack, prod_ne_zero_iff] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +section +/- # Completion counts on a fixed type of support words -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open MatrixMultiplicationAllFields.TensorSpectrum + +/-- A type of independent supported triples gives as many distinct +triples in the power, all with the same three completion counts. -/ +theorem fiber {F : Type*} [CommMonoidWithZero F] [Nontrivial F] [NoZeroDivisors F] {i j k m : ℕ} + (w : Fin i → Fin j → Fin k → F) (e : Fin m ≃ support w) (n : ℕ) (t : TagWords.CountVector m n) : + ∃ U : Finset (Cell (i ^ n) (j ^ n) (k ^ n)), U ⊆ support (WPower w n) ∧ + U.card = (TagWords.fiber t).card ∧ ∀ p ∈ U, + (rows (support (WPower w n)) p).card = TagWords.countWeight (fun a + => (rows (support w) (e a).val).card) t ∧ + (cols (support (WPower w n)) p).card = TagWords.countWeight (fun a + => (cols (support w) (e a).val).card) t ∧ + (inner (support (WPower w n)) p).card = TagWords.countWeight (fun a + => (inner (support w) (e a).val).card) t := by + let f : TagWords.Word m n ↪ Cell (i ^ n) (j ^ n) (k ^ n) := + ⟨fun x => pack fun l => (e (x l)).val, fun _ _ he => + funext fun l => e.injective (Subtype.ext (congrFun (pack_injective he) l))⟩ + refine ⟨(TagWords.fiber t).map f, ?_, Finset.card_map _, ?_⟩ + · intro p hp + obtain ⟨x, _, rfl⟩ := Finset.mem_map.mp hp + exact (mem_pack w _).2 fun l => (e (x l)).property + · intro p hp + obtain ⟨x, hx, rfl⟩ := Finset.mem_map.mp hp + rw [show f x = pack (fun l => (e (x l)).val) from rfl, rows_power, cols_power, inner_power] + have he (a : Fin m → ℕ) : ∏ l, a (x l) = TagWords.countWeight a t := + TagWords.wordWeight_eq_of_mem_fiber a hx + exact ⟨he (fun a => (rows (support w) (e a).val).card), + he (fun a => (cols (support w) (e a).val).card), + he (fun a => (inner (support w) (e a).val).card)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +section +/- +# Nonnegative dual total correlation + +Apply entropy subadditivity to the first index and the pair of +remaining indices, then to the two remaining indices within +each fixed first-index slice. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open Finset + +variable {X Y : Type*} [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] + +private def left (S : Finset (X × Y)) (y : Y) := univ.filter fun x => (x, y) ∈ S + +private def right (S : Finset (X × Y)) (x : X) := univ.filter fun y => (x, y) ∈ S + +private theorem sum_right (S : Finset (X × Y)) (f : X × Y → ℝ) : + ∑ x, ∑ y ∈ right S x, f (x, y) = ∑ p ∈ S, f p := by + simp only [right, sum_filter] + rw [← Fintype.sum_prod_type (fun p => if p ∈ S then f p else 0)] + simp + +private theorem count_right (S : Finset (X × Y)) : ∑ x, ((right S x).card : ℝ) = S.card := by + simpa using sum_right S (fun _ => 1) + +private theorem count_left (S : Finset (X × Y)) : ∑ y, ((left S y).card : ℝ) = S.card := by + rw [← count_right S] + simp only [left, right, card_filter, Nat.cast_sum] + rw [sum_comm] + +/-- For the uniform distribution on a relation, the sum of the +two conditional entropies is bounded by the joint entropy. -/ +private theorem pair_bound (S : Finset (X × Y)) : + ∑ p ∈ S, (Real.log (right S p.1).card + Real.log (left S p.2).card) ≤ + S.card * Real.log S.card := by + rcases S.eq_empty_or_nonempty with rfl | hS + · simp + let a x := ((right S x).card : ℝ) + let b y := ((left S y).card : ℝ) + let m : ℝ := S.card + have hm : 0 < m := Nat.cast_pos.mpr hS.card_pos + have hsum : ∑ p ∈ S, a p.1 * b p.2 ≤ m * m := by + calc + _ ≤ ∑ p : X × Y, a p.1 * b p.2 := sum_le_sum_of_subset_of_nonneg (subset_univ _) (by + intro p _ _ + unfold a b + positivity) + _ = m * m := by + rw [Fintype.sum_prod_type] + simp only [← mul_sum, ← sum_mul, a, b, count_left, count_right, m] + calc + _ ≤ ∑ p ∈ S, (a p.1 * b p.2 / m - 1 + Real.log m) := by + apply sum_le_sum + rintro ⟨x, y⟩ hxy + have ha : 0 < a x := Nat.cast_pos.mpr (card_pos.mpr ⟨y, mem_filter.mpr ⟨mem_univ _, hxy⟩⟩) + have hb : 0 < b y := Nat.cast_pos.mpr (card_pos.mpr ⟨x, mem_filter.mpr ⟨mem_univ _, hxy⟩⟩) + have hh := Real.log_le_sub_one_of_pos (div_pos (mul_pos ha hb) hm) + rw [Real.log_div (mul_pos ha hb).ne' hm.ne', Real.log_mul ha.ne' hb.ne'] at hh + exact sub_le_iff_le_add.mp hh + _ ≤ _ := by + simp only [sum_add_distrib, sum_sub_distrib, ← sum_div, sum_const, nsmul_eq_mul, mul_one] + change _ / m - m + m * Real.log m ≤ m * Real.log m + linarith only [(div_le_iff₀ hm).mpr hsum] + +theorem premium_nonneg {i j k : ℕ} (S : Finset (Cell i j k)) (hS : S.Nonempty) : + 0 ≤ premium S := by + have hm : 0 < (S.card : ℝ) := Nat.cast_pos.mpr hS.card_pos + have h₁ := pair_bound S + have h₂ : ∑ p ∈ S, (Real.log (cols S p).card + Real.log (inner S p).card) ≤ + ∑ p ∈ S, Real.log (right S p.1).card := by + rw [← sum_right S, ← sum_right S] + apply sum_le_sum + intro x _ + have he (t : Fin j × Fin k) : cols S (x, t) = left (right S x) t.2 := by + ext y; simp [cols, left, right] + have hf (t : Fin j × Fin k) : inner S (x, t) = right (right S x) t.1 := by + ext z; simp [inner, right] + simp only [he, hf, sum_const, nsmul_eq_mul] + simpa only [add_comm] using pair_bound (right S x) + unfold premium + apply div_nonneg _ (Real.log_nonneg (by norm_num)) + apply sub_nonneg.mpr + unfold conditional + rw [div_le_iff₀ hm, mul_comm] + have he (t : Cell i j k) : rows S t = left S t.2 := rfl + simp only [he, sum_add_distrib] at * + linarith only [h₁, h₂] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +/- # Multiplicative weights from completion counts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +open MatrixMultiplicationAllFields.TensorSpectrum.TagWords + +/-- The quantity computed by `Real.exp (s * (Real.log x + Real.log y + Real.log z))`. -/ +def unitWeight (s : ℝ) (x y z : ℕ) := Real.exp (s * (Real.log x + Real.log y + Real.log z)) + +variable {m n : ℕ} + +private theorem log_count (a : Fin m → ℕ) (ha : ∀ i, 0 < a i) (t : CountVector m n) : + Real.log (countWeight a t : ℕ) = ∑ i, (t i).val * Real.log (a i) := by + simp only [countWeight, Nat.cast_prod, Nat.cast_pow] + rw [Real.log_prod (fun i _ => pow_ne_zero _ (by exact_mod_cast (ha i).ne'))] + simp only [Real.log_pow] + +theorem unit_count (s : ℝ) (a b c : Fin m → ℕ) + (ha : ∀ i, 0 < a i) (hb : ∀ i, 0 < b i) (hc : ∀ i, 0 < c i) (t : CountVector m n) : + countWeight (fun i => unitWeight s (a i) (b i) (c i)) t = + unitWeight s (countWeight a t) (countWeight b t) (countWeight c t) := by + unfold unitWeight + rw [log_count a ha t, log_count b hb t, log_count c hc t, + ← Finset.sum_add_distrib, ← Finset.sum_add_distrib, Finset.mul_sum, Real.exp_sum] + apply Finset.prod_congr rfl + intro i _ + rw [← Real.exp_nat_mul] + congr 1 + ring + +theorem sum_exp_lower (hm : 0 < m) (a : Fin m → ℝ) : + m * Real.exp ((∑ i, a i) / m) ≤ ∑ i, Real.exp (a i) := by + have hm' : 0 < (m : ℝ) := by positivity + have hp : 0 < ∑ i, Real.exp (a i) := + Finset.sum_pos (fun _ _ => Real.exp_pos _) ⟨⟨0, hm⟩, Finset.mem_univ _⟩ + let b := (m : ℝ)⁻¹ * ∑ i, Real.exp (a i) + have he := TensorSpectrum.weighted_log_le_log_of_sum_le (fun _ => (m : ℝ)⁻¹) + (fun i => Real.exp (a i)) b (fun _ => by positivity) (by simp [hm.ne']) + (fun _ => Real.exp_pos _) (by unfold b; positivity) (by unfold b; rw [Finset.mul_sum]) + simp only [Real.log_exp, b, inv_mul_eq_div, ← Finset.sum_div] at he + rw [mul_comm, ← le_div_iff₀ hm'] + exact (Real.le_log_iff_exp_le (by positivity)).mp he + +variable {i j k : ℕ} (S : Finset (Cell i j k)) (e : Fin S.card ≃ S) + +/-- The value specified by `(rows S (e a).val).card`. -/ +def rCount (a : Fin S.card) := (rows S (e a).val).card +/-- The value specified by `(cols S (e a).val).card`. -/ +def cCount (a : Fin S.card) := (cols S (e a).val).card +/-- The value specified by `(inner S (e a).val).card`. -/ +def kCount (a : Fin S.card) := (inner S (e a).val).card + +theorem rCount_pos (a) : 0 < rCount S e a := Finset.card_pos.mpr + ⟨(e a).val.1, Finset.mem_filter.mpr ⟨Finset.mem_univ _, (e a).property⟩⟩ + +theorem cCount_pos (a) : 0 < cCount S e a := Finset.card_pos.mpr + ⟨(e a).val.2.1, Finset.mem_filter.mpr ⟨Finset.mem_univ _, (e a).property⟩⟩ + +theorem kCount_pos (a) : 0 < kCount S e a := Finset.card_pos.mpr + ⟨(e a).val.2.2, Finset.mem_filter.mpr ⟨Finset.mem_univ _, (e a).property⟩⟩ + +/-- Computes the weight by the application `unitWeight s (rCount S e a) (cCount S e a) (kCount S +e a)`. -/ +def weight (s : ℝ) (a : Fin S.card) := unitWeight s (rCount S e a) (cCount S e a) (kCount S e a) + +theorem exp_conditional (h : S.Nonempty) (s : ℝ) : + S.card * Real.exp (s * conditional S) ≤ ∑ a, weight S e s a := by + let f (t : Cell i j k) := Real.log (rows S t).card + Real.log (cols S t).card + + Real.log (inner S t).card + have he : ∑ a, s * f (e a).val = s * ∑ t ∈ S, f t := by + rw [← Finset.mul_sum, e.sum_comp (fun t => f t.val), Finset.sum_coe_sort] + have hp := sum_exp_lower h.card_pos (fun a => s * f (e a).val) + rw [he, mul_div_assoc] at hp + exact hp + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse +end + +/- # Powers of a weighting supported on a set of output cells -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +variable {F : Type*} {i j k : ℕ} + {w : Fin i → Fin j → Fin k → F} {u : Finset (Pos i j)} + +private theorem size_cells [Zero F] (hw : ∀ x y z, w x y z ≠ 0 ↔ (x, y) ∈ u) : + supportSize w = u.card * k := by + classical + have he x y z : (if w x y z = 0 then 0 else 1) = (if (x, y) ∈ u then 1 else 0 : ℕ) := by + by_cases h : (x, y) ∈ u + · simp [h, (hw x y z).mpr h] + · simp [h, not_ne_iff.mp (mt (hw x y z).mp h)] + unfold supportSize + simp_rw [he, Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul, Nat.cast_id] + rw [Finset.sum_comm, ← Fintype.sum_prod_type (fun p : Pos i j => k * if p ∈ u then 1 else 0)] + simp [mul_ite] + +theorem power_cells [CommMonoidWithZero F] [Nontrivial F] [NoZeroDivisors F] + (hw : ∀ x y z, w x y z ≠ 0 ↔ (x, y) ∈ u) (hk : 0 < k) (n : ℕ) : + ∃ v : Finset (Pos (i ^ n) (j ^ n)), v.card = u.card ^ n ∧ + ∀ x y z, WPower w n x y z ≠ 0 ↔ (x, y) ∈ v := by + classical + let v : Finset (Pos (i ^ n) (j ^ n)) := Finset.univ.filter fun p => + ∀ l : Fin n, (finFunctionFinEquiv.symm p.1 l, finFunctionFinEquiv.symm p.2 l) ∈ u + have hv x y z : WPower w n x y z ≠ 0 ↔ (x, y) ∈ v := by + simp [WPower, v, Finset.prod_ne_zero_iff, hw] + refine ⟨v, ?_, hv⟩ + have he := supportSize_power w n + rw [size_cells hv, size_cells hw, mul_pow] at he + exact Nat.eq_of_mul_eq_mul_right (pow_pos hk n) he + +theorem short_pow (i j q n : ℕ) : short (i ^ n) (j ^ n) (q ^ n) = n * short i j q := by + unfold short + simp only [Nat.cast_pow, Real.log_pow, mul_div_assoc, mul_min_of_nonneg _ _ (Nat.cast_nonneg n)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Model.lean new file mode 100644 index 0000000000..204ad04b35 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sparse/Model.lean @@ -0,0 +1,49 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights + +/-! # Completion counts and conditional entropies on the uniform support -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse + +/-- Indexes the cell by the coordinates of `Fin i × Fin j × Fin k`. -/ +abbrev Cell (i j k : ℕ) := Fin i × Fin j × Fin k +variable {F : Type*} {i j k : ℕ} + +open Classical in +/-- The subset of all indices on which the defining predicate holds. -/ +def support [Zero F] (w : Fin i → Fin j → Fin k → F) : Finset (Cell i j k) := + Finset.univ.filter fun t => w t.1 t.2.1 t.2.2 ≠ 0 + +/-- The subset of all indices on which the defining predicate holds. -/ +def rows (S : Finset (Cell i j k)) (t : Cell i j k) := + Finset.univ.filter fun x : Fin i => (x, t.2.1, t.2.2) ∈ S + +/-- The subset of all indices on which the defining predicate holds. -/ +def cols (S : Finset (Cell i j k)) (t : Cell i j k) := + Finset.univ.filter fun y : Fin j => (t.1, y, t.2.2) ∈ S + +/-- The subset of all indices on which the defining predicate holds. -/ +def inner (S : Finset (Cell i j k)) (t : Cell i j k) := + Finset.univ.filter fun z : Fin k => (t.1, t.2.1, z) ∈ S + +/-- The conditional law of each missing label given the other two +is uniform on its completion set. Entropy here uses natural logs. -/ +def conditional (S : Finset (Cell i j k)) : ℝ := + (∑ t ∈ S, (Real.log (rows S t).card + Real.log (cols S t).card + + Real.log (inner S t).card)) / S.card + +/-- Dual total correlation in bits. -/ +def premium (S : Finset (Cell i j k)) : ℝ := + (Real.log S.card - conditional S) / Real.log 2 + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sparse diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Dense.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Dense.lean new file mode 100644 index 0000000000..2855e9d5f3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Dense.lean @@ -0,0 +1,800 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.InformationTheory.Hamming +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Data.Finset.Powerset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.TreePrice +public import Mathlib.LinearAlgebra.Matrix.Rank +public import Mathlib.LinearAlgebra.Finsupp.LinearCombination +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Algebra.BigOperators.Field +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Span +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows +public import Mathlib.Algebra.Polynomial.Roots +public import Mathlib.LinearAlgebra.Matrix.NonsingularInverse + +/-! +# Codes with prescribed slot words + +A new word conflicts with an earlier word only if both the slot and +symbol match outside some set of `n` coordinates. Counting these sets +and the possibilities within them leaves room for a greedy assignment. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset + +variable {G H : Type*} [Fintype G] [Fintype H] [DecidableEq G] [DecidableEq H] {m n k b : ℕ} + +private def vary (x : Fin m → G) (s : Finset (Fin m)) := + univ.filter fun y : Fin m → G => ∀ i ∉ s, y i = x i + +private theorem vary_bound (x : Fin m → G) (s : Finset (Fin m)) : + (vary x s).card ≤ Fintype.card G ^ s.card := by + let f (y : vary x s) (i : s) := y.val i.val + have hf : Function.Injective f := by + intro y z he + apply Subtype.ext + funext i + by_cases hi : i ∈ s + · exact congrFun he ⟨i, hi⟩ + · exact ((mem_filter.mp y.property).2 i hi).trans ((mem_filter.mp z.property).2 i hi).symm + simpa only [Fintype.card_fun, Fintype.card_coe] using Fintype.card_le_of_injective f hf + +private theorem fresh (hn : n ≤ m) + (hgap : 2 ^ m * (Fintype.card G ^ n * k * Fintype.card H ^ n) < Fintype.card H ^ m) + (x : Fin m → G) (f : (Fin m → G) × Fin k → Fin m → H) : + ∃ z : Fin m → H, ∀ p, n ≤ hammingDist (fun i => (x i, z i)) (fun i => (p.1 i, f p i)) := by + let S := (univ : Finset (Fin m)).powersetCard n + let bad (s : Finset (Fin m)) := ((vary x s) ×ˢ univ).biUnion (fun p => vary (f p) s) + have hs : S.card ≤ 2 ^ m := by + exact (card_le_card (show S ⊆ univ.powerset from fun _ h => + mem_powerset.mpr (mem_powersetCard.mp h).1)).trans_eq (by simp) + have hc (s) (h : s ∈ S) : (bad s).card ≤ Fintype.card G ^ n * k * Fintype.card H ^ n := by + have he := (mem_powersetCard.mp h).2 + calc + _ ≤ ∑ p ∈ vary x s ×ˢ univ, (vary (f p) s).card := card_biUnion_le + _ ≤ ∑ _ ∈ vary x s ×ˢ (univ : Finset (Fin k)), Fintype.card H ^ s.card := + sum_le_sum (fun p _ => vary_bound (f p) s) + _ ≤ _ := by + simp only [sum_const, nsmul_eq_mul, Nat.cast_id, card_product, card_univ, Fintype.card_fin, + ← he] + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (vary_bound x s)) + have ht : (S.biUnion bad).card < (univ : Finset (Fin m → H)).card := by + calc + _ ≤ ∑ _ ∈ S, Fintype.card G ^ n * k * Fintype.card H ^ n := + card_biUnion_le.trans (sum_le_sum hc) + _ ≤ 2 ^ m * (Fintype.card G ^ n * k * Fintype.card H ^ n) := by + simpa using Nat.mul_le_mul_right _ hs + _ < _ := by simpa using hgap + obtain ⟨z, _, hz⟩ := exists_mem_notMem_of_card_lt_card ht + refine ⟨z, fun p => ?_⟩ + by_contra! hh + let D := univ.filter fun i => (x i, z i) ≠ (p.1 i, f p i) + obtain ⟨s, hDs, hs, he⟩ := exists_subsuperset_card_eq (subset_univ D) hh.le (by simpa using hn) + have hp i (hi : i ∉ s) : (x i, z i) = (p.1 i, f p i) := by + by_contra h + exact hi (hDs (mem_filter.mpr ⟨mem_univ _, h⟩)) + have hx : p.1 ∈ vary x s := mem_filter.mpr ⟨mem_univ _, fun i hi + => (congrArg Prod.fst (hp i hi)).symm⟩ + have hy : z ∈ vary (f p) s := mem_filter.mpr ⟨mem_univ _, fun i hi => congrArg Prod.snd (hp i hi)⟩ + exact hz (mem_biUnion.mpr ⟨s, mem_powersetCard.mpr ⟨hs, he⟩, mem_biUnion.mpr + ⟨p, mem_product.mpr ⟨hx, mem_univ _⟩, hy⟩⟩) + +theorem code (hb : 0 < b) (hgap : 2 ^ b * Fintype.card G * Fintype.card H * k < Fintype.card H ^ b) + (hn : 0 < n) : + ∃ c : (Fin (b * n) → G) → Fin (k ^ n) → Fin (b * n) → H, ∀ x a y d, (x, a) ≠ (y, d) → + n ≤ hammingDist (fun i => (x i, c x a i)) (fun i => (y i, c y d i)) := by + classical + have hH : 0 < Fintype.card H := by + by_contra! h + simp [Nat.eq_zero_of_le_zero h, hb.ne'] at hgap + let P := (Fin (b * n) → G) × Fin (k ^ n) + have hsize : 2 ^ (b * n) * (Fintype.card G ^ n * k ^ n * Fintype.card H ^ n) < + Fintype.card H ^ (b * n) := by + rw [pow_mul, pow_mul] + simpa only [mul_pow, mul_assoc, mul_comm, mul_left_comm] using + pow_lt_pow_left₀ hgap zero_le hn.ne' + have assign (s : Finset P) : ∃ f : P → Fin (b * n) → H, ∀ x ∈ s, ∀ y ∈ s, x ≠ y → + n ≤ hammingDist (fun i => (x.1 i, f x i)) (fun i => (y.1 i, f y i)) := by + induction s using Finset.induction_on with + | empty => exact ⟨fun _ _ => Classical.choice (Fintype.card_pos_iff.mp hH), by simp⟩ + | @insert p s hp ih => + obtain ⟨f, hf⟩ := ih + obtain ⟨z, hz⟩ := fresh (Nat.le_mul_of_pos_left _ hb) hsize p.1 f + refine ⟨Function.update f p z, ?_⟩ + intro x hx y hy hxy + rcases mem_insert.mp hx with rfl | hx <;> rcases mem_insert.mp hy with rfl | hy + · exact (hxy rfl).elim + · simpa [hxy.symm] using hz y + · rw [hammingDist_comm]; simpa [hxy] using hz x + · have hx' : x ≠ p := fun h => hp (h ▸ hx) + have hy' : y ≠ p := fun h => hp (h ▸ hy) + simpa [hx', hy'] using hf x hx y hy hxy + obtain ⟨f, hf⟩ := assign univ + exact ⟨fun x a => f (x, a), fun x a y d => hf (x, a) (mem_univ _) (y, d) (mem_univ _)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- # Sparse decoder rows and narrow factorizations with sparse right factors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset Prices.Motion + +variable {F X Y T I : Type} [Field F] [Fintype Y] + +open scoped Classical in +/-- The condition `∀ x, (#{y | M x y ≠ 0} : ℝ) ≤ p` on the specified data. -/ +def Rows (M : Matrix X Y F) (p : ℝ) : Prop := ∀ x, (#{y | M x y ≠ 0} : ℝ) ≤ p + +open scoped Classical in +/-- The condition `∃ e : ℕ, e ≤ r ∧ ∃ (A : Matrix X (Fin e) F) (B : Matrix (Fin e) Y F), M = A * +B ∧ Rows B p` on the specified data. -/ +def Narrow (M : Matrix X Y F) (r p : ℝ) : Prop := + ∃ e : ℕ, e ≤ r ∧ ∃ (A : Matrix X (Fin e) F) (B : Matrix (Fin e) Y F), M = A * B ∧ Rows B p + +open scoped Classical in +/-- The condition `∃ A B, M = A + B ∧ Rows A p ∧ Narrow B r p` on the specified data. -/ +def Packed (M : Matrix X Y F) (r p : ℝ) : Prop := + ∃ A B, M = A + B ∧ Rows A p ∧ Narrow B r p + +variable {M N : Matrix X Y F} {p q r s : ℝ} + +open scoped Classical in +theorem Rows.bound (M : Matrix X Y F) : Rows M (Fintype.card Y) := + fun _ => Nat.cast_le.mpr (card_le_card (filter_subset _ _)) + +open scoped Classical in +theorem Rows.mono (h : Rows M p) (hp : p ≤ q) : Rows M q := fun x => (h x).trans hp + +open scoped Classical in +theorem Rows.zero : Rows (0 : Matrix X Y F) 0 := by simp [Rows] + +open scoped Classical in +theorem Rows.add (h : Rows M p) (h' : Rows N q) : Rows (M + N) (p + q) := by + intro x + let A : Finset Y := {y | M x y ≠ 0} + let B : Finset Y := {y | N x y ≠ 0} + have hs : ({y | (M + N) x y ≠ 0} : Finset Y) ⊆ A ∪ B := by + intro y hy + simp only [A, B, mem_filter, mem_univ, true_and, mem_union, Matrix.add_apply] at * + grind + have he := (card_le_card hs).trans (card_union_le A B) + exact (show (#{y | (M + N) x y ≠ 0} : ℝ) ≤ A.card + B.card by exact_mod_cast he).trans + (add_le_add (h x) (h' x)) + +open scoped Classical in +theorem Rows.sub (h : Rows M p) (h' : Rows N q) : Rows (M - N) (p + q) := by + rw [sub_eq_add_neg] + apply h.add + simpa [Rows] using h' + +open scoped Classical in +theorem Narrow.of_factor [Fintype T] {A : Matrix X T F} {B : Matrix T Y F} + (hM : M = A * B) (hT : (Fintype.card T : ℝ) ≤ r) (hB : Rows B p) : Narrow M r p := by + let e := (Fintype.equivFin T).symm + refine ⟨_, hT, fun x i => A x (e i), fun i => B (e i), ?_, fun i => hB (e i)⟩ + rw [hM] + ext x y + exact (e.sum_comp (fun i => A x i * B i y)).symm + +open scoped Classical in +theorem Narrow.mono (h : Narrow M r p) (hr : r ≤ s) (hp : p ≤ q) : Narrow M s q := by + obtain ⟨e, he, A, B, hM, hB⟩ := h + exact ⟨e, he.trans hr, A, B, hM, hB.mono hp⟩ + +open scoped Classical in +theorem Narrow.trivial (M : Matrix X Y F) : Narrow M (Fintype.card Y) 1 := by + apply Narrow.of_factor (Matrix.mul_one M).symm le_rfl + intro y + simp [Matrix.one_apply, show ({t | y = t} : Finset Y) = {y} by ext; simp [eq_comm]] + +open scoped Classical in +theorem Narrow.zero (p : ℝ) : Narrow (0 : Matrix X Y F) 0 p := + ⟨0, by simp, 0, 0, by simp, fun i => Fin.elim0 i⟩ + +open scoped Classical in +theorem Narrow.add (h : Narrow M r p) (h' : Narrow N s p) : Narrow (M + N) (r + s) p := by + obtain ⟨a, ha, A, B, rfl, hB⟩ := h + obtain ⟨b, hb, C, D, rfl, hD⟩ := h' + let L : Matrix X (Fin a ⊕ Fin b) F := fun x => Sum.elim (A x) (C x) + let R : Matrix (Fin a ⊕ Fin b) Y F := Sum.elim B D + apply Narrow.of_factor (A := L) (B := R) _ (by simpa using add_le_add ha hb) + · rintro (i | i) + · exact hB i + · exact hD i + · ext x y + change (∑ i, A x i * B i y) + (∑ i, C x i * D i y) = + ∑ i, L x i * R i y + rw [Fintype.sum_sum_type] + rfl + +open scoped Classical in +/-- A basis selected from the rows retains their support bound. -/ +theorem Narrow.of_low [Finite X] (h : Low M r) (hr : Rows M p) : Narrow M r p := by + let : Fintype X := Fintype.ofFinite X + obtain ⟨T, _, hT, A, B, he⟩ := h + have hdim : (M.rank : ℝ) ≤ r := by + rw [he] + exact (Nat.cast_le.mpr ((Matrix.rank_mul_le_left _ _).trans A.rank_le_card_width)).trans hT + rw [Matrix.rank_eq_finrank_span_row] at hdim + obtain ⟨v, hv, heq, _⟩ := Submodule.exists_fun_fin_finrank_span_eq F (Set.range M.row) + choose e he using hv + have hx (x) : M.row x ∈ Submodule.span F (Set.range v) := by + rw [heq] + exact Submodule.subset_span ⟨x, rfl⟩ + choose c hc using fun x => (Submodule.mem_span_range_iff_exists_fun _).mp (hx x) + refine ⟨_, hdim, c, fun i => M (e i), ?_, fun i => hr (e i)⟩ + ext x y + change M x y = ∑ i, c x i * M (e i) y + have hh (i) : M (e i) y = v i y := congrFun (he i) y + simp_rw [hh] + simpa only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul, Matrix.row] + using (congrFun (hc x) y).symm + +open scoped Classical in +theorem Packed.sum {ι : Type} {M : ι → Matrix X Y F} (t : Finset ι) + (h : ∀ i ∈ t, Packed (M i) r p) (hp : 0 ≤ p) : Packed (∑ i ∈ t, M i) (t.card * r) (t.card * p) + := by + induction t using Finset.induction_on with + | empty => simpa using (show Packed (0 : Matrix X Y F) 0 0 from ⟨0, 0, + by simp, Rows.zero, Narrow.zero _⟩) + | @insert i t hi ih => + obtain ⟨A, B, h₁, ha, hb⟩ := h i (mem_insert_self _ _) + obtain ⟨C, D, h₂, hc, hd⟩ := ih (fun j hj => h j (mem_insert_of_mem hj)) + rw [sum_insert hi, card_insert_of_notMem hi, Nat.cast_add, Nat.cast_one, add_mul, add_mul, + one_mul, one_mul] + refine ⟨C + A, D + B, by rw [h₁, h₂]; abel, hc.add ha, ?_⟩ + exact (hd.mono le_rfl (le_add_of_nonneg_right hp)).add + (hb.mono le_rfl (le_add_of_nonneg_left (by positivity))) + +variable [Fintype I] [DecidableEq I] + +open scoped Classical in +private theorem product_rows (f : I → Y → F) (p : I → ℝ) + (h : ∀ i, (#{y | f i y ≠ 0} : ℝ) ≤ p i) : + (#{y : I → Y | (∏ i, f i (y i)) ≠ 0} : ℝ) ≤ ∏ i, p i := by + let B i : Finset Y := {y | f i y ≠ 0} + have he : ({y : I → Y | (∏ i, f i (y i)) ≠ 0} : Finset _) = Fintype.piFinset B := by + ext y + simp [B, prod_ne_zero_iff] + rw [he, Fintype.card_piFinset, Nat.cast_prod] + exact prod_le_prod₀ (by intros; positivity) (fun i _ => h i) + +open scoped Classical in +theorem Rows.prod (M : I → Matrix Y Y F) (p : I → ℝ) (h : ∀ i, Rows (M i) (p i)) : + Rows (matPower M) (∏ i, p i) := + fun x => product_rows (fun i y => M i (x i) y) _ (fun i => h i _) + +open scoped Classical in +theorem Narrow.prod (M : I → Matrix Y Y F) (r p : I → ℝ) (h : ∀ i, Narrow (M i) (r i) (p i)) : + Narrow (matPower M) (∏ i, r i) (∏ i, p i) := by + choose e he A B hd hs using h + let T := ∀ i, Fin (e i) + let L : Matrix (I → Y) T F := fun x t => ∏ i, A i (x i) (t i) + let R : Matrix T (I → Y) F := fun t y => ∏ i, B i (t i) (y i) + apply Narrow.of_factor (A := L) (B := R) + · ext x y + change ∏ i, M i (x i) (y i) = ∑ t : T, L x t * R t y + simp only [hd, Matrix.mul_apply, Fintype.prod_sum, prod_mul_distrib, L, R, T] + · simp only [T, Fintype.card_pi, Fintype.card_fin, Nat.cast_prod] + exact prod_le_prod₀ (by intros; positivity) (fun i _ => he i) + · exact fun t => product_rows (fun i y => B i (t i) y) _ (fun i => hs i _) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- # Multiscale approximation of a decoder -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset Prices.Motion + +variable {F Y : Type} [Field F] [Fintype Y] {M : Matrix Y Y F} {q : ℕ} + +open scoped Classical in +/-- Consecutive approximants give an exact expansion. Each difference +has controlled support and rank, including the two end terms. -/ +theorem layers {D : ℝ} (hD : 1 ≤ D) (hc : (Fintype.card Y : ℝ) ≤ D) + (P R : ℕ → Matrix Y Y F → Prop) (hz : P 0 0) (he : P (q + 1) M) + (hs : ∀ j A B, P (j + 1) A → P j B → R j (A - B)) + (h : ∀ j : ℕ, 0 < j → j ≤ q → ∃ A, Low (M - A) (D ^ (1 - (j : ℝ) / q)) ∧ P j A) : + ∃ W : Fin (q + 1) → Matrix Y Y F, M = ∑ j, W j ∧ + ∀ j, Low (W j) (2 * D ^ (1 - (j.val : ℝ) / q)) ∧ R j.val (W j) := by + have hex (j : ℕ) : ∃ A, (j = 0 → A = 0) ∧ (j = q + 1 → A = M) ∧ + Low (M - A) (D ^ (1 - (j : ℝ) / q)) ∧ (j ≤ q + 1 → P j A) := by + by_cases hj : j = 0 + · subst j + refine ⟨0, fun _ => rfl, by omega, ?_, fun _ => hz⟩ + simpa using (Low.full M).mono hc + by_cases hj' : j ≤ q + · obtain ⟨A, hA, hP⟩ := h j (by omega) hj' + exact ⟨A, by omega, by omega, hA, fun _ => hP⟩ + · refine ⟨M, by omega, fun _ => rfl, ?_, fun hlt => by rwa [show j = q + 1 by omega]⟩ + rw [sub_self] + exact Low.zero.mono (by positivity) + choose N h₀ h₁ hN hP using hex + refine ⟨fun j => N (j.val + 1) - N j.val, ?_, fun j => ⟨?_, + hs _ _ _ (hP _ (by omega)) (hP _ (by omega))⟩⟩ + · rw [Fin.sum_univ_eq_sum_range (fun i => N (i + 1) - N i), sum_range_sub, h₀ _ rfl, h₁ _ rfl, + sub_zero] + · change Low (N (j.val + 1) - N j.val) _ + rw [show N (j.val + 1) - N j.val = (M - N j.val) - (M - N (j.val + 1)) by abel, two_mul] + apply (hN j.val).sub + refine (hN (j.val + 1)).mono (Real.rpow_le_rpow_of_exponent_le hD ?_) + gcongr + omega + +open scoped Classical in +/-- Linear envelopes for the row costs suffice on the square grid. -/ +theorem row_layers {D C l : ℝ} (hD : 1 ≤ D) (hc : (Fintype.card Y : ℝ) ≤ D) + (hl : 1 ≤ l) (hq : (q : ℝ) = l * l) (hC : 1 ≤ C) + (h : ∀ j : ℕ, 0 < j → j ≤ q → ∃ A, Low (M - A) (D ^ (1 - (j : ℝ) / q)) ∧ + Rows A (D ^ (C * Real.sqrt ((j : ℝ) / q)))) : + ∃ W : Fin (q + 1) → Matrix Y Y F, M = ∑ j, W j ∧ ∀ j, + Low (W j) (2 * D ^ (1 - (j.val : ℝ) / q)) ∧ Rows (W j) (2 * D ^ (C * ((j.val : ℝ) + 1) / l)) + := by + let p (j : ℕ) := D ^ (C * (j : ℝ) / l) + have hp : Monotone p := by + intro a b hab + exact Real.rpow_le_rpow_of_exponent_le hD (by gcongr) + have hlast : D ≤ p (q + 1) := by + apply le_trans _ (hp (Nat.le_succ q)) + change D ≤ D ^ (C * q / l) + rw [hq, ← mul_assoc, mul_div_cancel_right₀ _ (by linarith : l ≠ 0)] + exact Real.self_le_rpow_of_one_le hD (one_le_mul_of_one_le_of_one_le hC hl) + apply layers hD hc (fun j A => Rows A (p j)) (fun j A => Rows A (2 * D ^ (C * ((j : ℝ) + 1) / l))) + (Rows.zero.mono (by dsimp [p]; positivity)) ((Rows.bound M).mono (hc.trans hlast)) + · intro j A B ha hb + have H := ha.sub (hb.mono (hp (Nat.le_succ j))) + simpa only [p, Nat.succ_eq_add_one, Nat.cast_add, Nat.cast_one, two_mul] using H + · intro j hj hjq + obtain ⟨A, he, ha⟩ := h j hj hjq + refine ⟨A, he, ha.mono (Real.rpow_le_rpow_of_exponent_le hD ?_)⟩ + have h1 : (1 : ℝ) ≤ j := Nat.one_le_cast.mpr hj + rw [hq, Real.sqrt_div (by positivity), Real.sqrt_mul_self (by linarith), ← mul_div_assoc] + gcongr + exact Real.sqrt_le_iff.mpr ⟨by positivity, by nlinarith⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- +# Packing short rows on both sides of the decomposition + +For a product of layers of total index below the threshold, pay for +every row. Otherwise select just enough high layers to reach the +threshold. Use a sparse row basis on those coordinates and the +identity on the rest. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +open Finset Prices.Motion + +variable {F Y : Type} [Field F] [Fintype Y] {M : Matrix Y Y F} {q : ℕ} + +open scoped Classical in +private theorem select (v : Fin q → ℝ) (hv : ∀ i, v i ≤ q) (s : Finset (Fin q)) + (h : (q : ℝ) ≤ ∑ i ∈ s, v i) : + ∃ t ⊆ s, (q : ℝ) ≤ ∑ i ∈ t, v i ∧ ∑ i ∈ t, v i ≤ 2 * q := by + induction s using Finset.induction_on with + | empty => exact ⟨∅, Subset.rfl, h, by simp⟩ + | @insert a s ha ih => + by_cases hs : (q : ℝ) ≤ ∑ i ∈ s, v i + · obtain ⟨t, ht, hv⟩ := ih hs + exact ⟨t, ht.trans (subset_insert _ _), hv⟩ + · refine ⟨_, Subset.rfl, h, ?_⟩ + rw [sum_insert ha] + linarith [hv a] + +open scoped Classical in +private theorem product_bound {D b : ℝ} (hD : 1 ≤ D) (a : Fin q → ℝ) + (ha : ∑ i, a i ≤ b) : ∏ i, (2 * D ^ (a i)) ≤ 2 ^ q * D ^ b := by + rw [prod_mul_distrib, prod_const, card_fin, ← Real.rpow_sum_of_pos (by linarith)] + exact mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hD ha) (by positivity) + +open scoped Classical in +private theorem collect_word {D C l : ℝ} (hD : 1 ≤ D) (hc : (Fintype.card Y : ℝ) ≤ D) + (hl : 1 ≤ l) (hq : (q : ℝ) = l * l) (hC : 1 ≤ C) + (W : Fin q → Matrix Y Y F) (v : Fin q → ℝ) (hv : ∀ i, v i ≤ q) + (h : ∀ i, Low (W i) (2 * D ^ (1 - v i / q)) ∧ Rows (W i) (2 * D ^ (C * (v i + 1) / l))) : + Packed (matPower W) (2 ^ q * D ^ ((q : ℝ) - 1)) (2 ^ q * D ^ (3 * C * l)) := by + have hq' : 0 < (q : ℝ) := by rw [hq]; positivity + have cost (u : Fin q → ℝ) (hu : ∑ i, u i ≤ 2 * q) : + ∏ i, (2 * D ^ (C * (u i + 1) / l)) ≤ 2 ^ q * D ^ (3 * C * l) := by + apply product_bound hD + rw [← sum_div, ← mul_sum, sum_add_distrib, sum_const, card_fin, nsmul_eq_mul, mul_one] + apply (div_le_iff₀ (by linarith)).mpr + calc + _ ≤ C * (2 * q + q) := by gcongr + _ = _ := by rw [hq]; ring + by_cases hsum : (q : ℝ) ≤ ∑ i, v i + · obtain ⟨s, _, hlo, hhi⟩ := select v hv univ hsum + let u i := if i ∈ s then v i else 0 + have hs : ∑ i, u i = ∑ i ∈ s, v i := by simp [u] + have hh i : Narrow (W i) (2 * D ^ (1 - u i / q)) (2 * D ^ (C * (u i + 1) / l)) := by + by_cases hi : i ∈ s + · simp only [u, ite_eq_left hi] + exact Narrow.of_low (h i).1 (h i).2 + · simp only [u, ite_eq_right hi, zero_div, sub_zero, Real.rpow_one, zero_add, mul_one] + exact (Narrow.trivial _).mono (by linarith) + (by linarith [Real.one_le_rpow hD (by positivity : 0 ≤ C / l)]) + have hr : ∑ i, (1 - u i / q) ≤ (q : ℝ) - 1 := by + rw [sum_sub_distrib, sum_const, card_fin, nsmul_eq_mul, mul_one, ← sum_div, hs] + exact sub_le_sub_left ((le_div_iff₀ hq').mpr (by simpa using hlo)) _ + exact ⟨0, _, by simp, Rows.zero.mono (by positivity), + (Narrow.prod W _ _ hh).mono (product_bound hD _ hr) (cost u (hs.le.trans hhi))⟩ + · exact ⟨_, 0, by simp, (Rows.prod W _ (fun i => (h i).2)).mono (cost v (by linarith)), + (Narrow.zero _).mono (by positivity) le_rfl⟩ + +open scoped Classical in +theorem collect {D C l : ℝ} (hD : 1 ≤ D) (hc : (Fintype.card Y : ℝ) ≤ D) + (hl : 1 ≤ l) (hq : (q : ℝ) = l * l) (hC : 1 ≤ C) + (h : ∀ j : ℕ, 0 < j → j ≤ q → ∃ A, Low (M - A) (D ^ (1 - (j : ℝ) / q)) ∧ + Rows A (D ^ (C * Real.sqrt ((j : ℝ) / q)))) : + Packed (matPower (fun _ : Fin q => M)) + ((2 * ((q : ℝ) + 1)) ^ q * D ^ ((q : ℝ) - 1)) ((2 * ((q : ℝ) + 1)) ^ q * D ^ (3 * C * l)) + := by + obtain ⟨W, he, hw⟩ := row_layers hD hc hl hq hC h + have H (v : Fin q → Fin (q + 1)) := collect_word hD hc hl hq hC (W ∘ v) + (fun i => ((v i).val : ℝ)) (fun i => Nat.cast_le.mpr (Nat.lt_succ_iff.mp (v i).isLt)) + (fun i => hw (v i)) + have eqn : matPower (fun _ : Fin q => M) = ∑ v : Fin q → Fin (q + 1), matPower (W ∘ v) := by + ext x y + simp only [matPower, he, Matrix.sum_apply, Fintype.prod_sum, Function.comp_apply] + rw [eqn] + have hh := Packed.sum univ (fun v _ => H v) (by positivity) + simpa [mul_pow, mul_left_comm, mul_comm, mul_assoc] using hh + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Interior +end + +/- # Finite decompositions and polynomial paths for grouped speedup -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +open Spectral Finset + +/-- Computes the leg by the application `Fin 3`. -/ +abbrev Leg := Fin 3 +/-- The indexing data represented by `Fin n → (s : Leg) → X s → R`. -/ +abbrev Family (R : Type) (X : Leg → Type) (n : ℕ) := Fin n → (s : Leg) → X s → R + +/-- The value specified by `∑ l, ∏ s, A l s (x s)`. -/ +def form {R : Type} [CommSemiring R] {X : Leg → Type} {n : ℕ} (A : Family R X n) + (x : ∀ s, X s) : R := ∑ l, ∏ s, A l s (x s) + +variable {K : Type} [Field K] {X : Leg → Type} [∀ s, Fintype (X s)] {n : ℕ} + +/-- Computes the table by the application `Tensor.ofRaw (Raw.ofTable X T)`. -/ +abbrev table (T : (∀ s, X s) → K) := Tensor.ofRaw (Raw.ofTable X T) + +/-- Uses `⟨X, Fin n, A⟩` as the representation. -/ +def raw (A : Family K X n) : Raw K Leg := ⟨X, Fin n, A⟩ + +theorem table_form (A : Family K X n) : table (form A) = Tensor.ofRaw (raw A) := + Tensor.ofRaw_eq (Raw.equiv_coeff (fun _ => Equiv.refl _) (Raw.coeff_ofTable _ _)) + +theorem form_le (A : Family K X n) : table (form A) ≤ n := by + rw [table_form] + have h := Tensor.le_term_count (raw A) + change _ ≤ (Fintype.card (Fin n) : Tensor K Leg) at h + rwa [Fintype.card_fin] at h + +theorem exists_form {T : (∀ s, X s) → K} (h : table T ≤ n) : ∃ A : Family K X n, T = form A := by + rw [← Tensor.diag_fin] at h + obtain ⟨L, hL⟩ := h + change (s : Leg) → X s → Fin n → K at L + refine ⟨fun l s y => L s y l, funext fun x => ?_⟩ + have he := (Raw.coeff_ofTable X T x).symm.trans (hL x) + change T x = ∑ i : Fin n, ∏ s, ∑ j : Fin n, L s (x s) j * if j = i then 1 else 0 at he + simpa [form, mul_ite] using he + +theorem table_add_le (A B : (∀ s, X s) → K) : table (A + B) ≤ table A + table B := by + simpa using Tensor.span_le X (A + B) (fun i : Bool => if i then A else B) + (fun _ => 1) (fun _ => by simp) + +theorem wire_le (A : Family K X n) (a b : Leg) + (h : ∀ l m s, s ≠ a → s ≠ b → A l s = A m s) : + table (form A) ≤ Tensor.wire K a b n := by + rw [table_form] + refine ⟨fun s x l => A l s x, fun x => ?_⟩ + change ∑ i, ∏ s, A i s (x s) = + ∑ i, ∏ s, ∑ j, A j s (x s) * if j = Raw.port {a, b} s i then 1 else 0 + simp only [mul_ite, mul_one, mul_zero, Fintype.sum_ite_eq'] + refine sum_congr rfl fun i _ => prod_congr rfl fun s _ => ?_ + by_cases he : s ∈ ({a, b} : Finset Leg) + · rw [Raw.port, ite_eq_left he] + · simp only [mem_insert, mem_singleton, not_or] at he + exact congrFun (h i _ s he.1 he.2) _ + +/-- A polynomial path stays in the Zariski closure if it is in the +set except possibly at the finitely many roots of a nonzero polynomial. -/ +theorem path_closure {K : Type*} [Field K] [Infinite K] + {ι : Type} {A : Set (ι → K)} (P : ι → Polynomial K) + (Q : Polynomial K) (hQ : Q ≠ 0) (hP : ∀ t, Q.eval t ≠ 0 → (fun i => (P i).eval t) ∈ A) : + ZClosure A (fun i => (P i).eval 0) := by + intro p hp + let R := MvPolynomial.eval₂ Polynomial.C P p + have he (t : K) : R.eval t = MvPolynomial.eval (fun i => (P i).eval t) p := by + change Polynomial.evalRingHom t R = _ + unfold R + rw [MvPolynomial.hom_eval₂, show (Polynomial.evalRingHom t).comp Polynomial.C = + RingHom.id K by ext; simp] + rfl + have hzero : Q * R = 0 := by + apply Polynomial.funext + intro t + rw [Polynomial.eval_mul, Polynomial.eval_zero, he] + by_cases ht : Q.eval t = 0 + · rw [ht, zero_mul] + · rw [hp _ (hP t ht), mul_zero] + rw [← he, (mul_eq_zero.mp hzero).resolve_left hQ, Polynomial.eval_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +end + +/- # Adjoining a disjoint wire to the original three legs -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +open Spectral Finset + +variable {K : Type} [Field K] {X : Leg → Type} {m n d : ℕ} {a b c : Leg} + +theorem third (h : a ≠ b) : ∃ c : Leg, a ≠ c ∧ b ≠ c := by + fin_cases a <;> fin_cases b <;> first | contradiction | decide + +theorem prod_three (hab : a ≠ b) (hac : a ≠ c) (hbc : b ≠ c) (f : Leg → K) : + ∏ s, f s = f a * f b * f c := by + have he : {a, b, c} = (univ : Finset Leg) := by + apply eq_univ_of_card + simp [hab, hac, hbc, Leg] + rw [← he] + simp [hab, hac, hbc, mul_assoc] + +/-- The condition `∀ s, ∃ u : Fin m → Fin d → K, ∀ j x, ∑ l, u j l * P l s x = A j s x` on the +specified data. -/ +def Spans (P : Family K X d) (A : Family K X m) : Prop := + ∀ s, ∃ u : Fin m → Fin d → K, ∀ j x, ∑ l, u j l * P l s x = A j s x + +/-- Evaluates `Sum.elim (A l s) (fun _ => 0)` at the input `l s`. -/ +def extend (m : ℕ) (A : Family K X n) : Family K (fun s => X s ⊕ Fin m) n := + fun l s => Sum.elim (A l s) (fun _ => 0) + +/-- Evaluates `Sum.elim (fun _ => 0) (fun x => if x = Raw.port {a, b} s l then 1 else 0)` at the +input `l s`. -/ +def extra (X : Leg → Type) (a b : Leg) (m : ℕ) : Family K (fun s => X s ⊕ Fin m) m := + fun l s => Sum.elim (fun _ => 0) (fun x => if x = Raw.port {a, b} s l then 1 else 0) + +theorem Spans.extend {P : Family K X d} {A : Family K X m} (h : Spans P A) : + Spans (extend m P) (extend m A) := by + intro s + obtain ⟨u, hu⟩ := h s + refine ⟨u, fun j x => ?_⟩ + cases x <;> simp [Speedup.extend, hu] + +theorem extra_const (a b : Leg) (l j : Fin m) (s : Leg) (ha : s ≠ a) (hb : s ≠ b) : + extra (K := K) X a b m l s = extra X a b m j s := by + have he : Raw.port {a, b} s l = Raw.port {a, b} s j := by simp [Raw.port, ha, hb] + simp only [extra, he] + +theorem form_append (P : Family K X d) (A : Family K X m) : + form (Fin.append P A) = form P + form A := by + funext x + rw [form, Fin.sum_univ_add] + simp [form] + +theorem table_extra [∀ s, Fintype (X s)] (P : Family K X d) (A : Family K X m) (a b : Leg) : + table (form (extend m P) + form (extend m A) + form (extra X a b m)) = + table (form P + form A) + Tensor.wire K a b m := by + let H := Fin.append P A + have he : extend m H = Fin.append (extend m P) (extend m A) := by + funext l s x + refine Fin.addCases (fun i => ?_) (fun j => ?_) l <;> simp [H, extend] + rw [← form_append, ← he, ← form_append P A, table_form] + change _ = Tensor.ofRaw (raw H + Raw.wire K a b m) + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (fun _ => Equiv.refl _) ?_ + intro x + change (∀ s, X s ⊕ Fin m) at x + refine (Raw.coeff_ofTable _ _ x).trans ?_ + change _ = ∑ l : Fin (d + m) ⊕ Fin m, ∏ s, (raw H + Raw.wire K a b m).factor l s (x s) + rw [Fintype.sum_sum_type] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +end + +/- +# Spanning pivot columns suffice + +Interpolate the first `d` columns at each site to a padded basis. +Away from the roots of three minors, these columns span the whole leg. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +open Finset + +variable {K : Type} [Field K] [Infinite K] {X : Leg → Type} [∀ s, Fintype (X s)] {d m : ℕ} + +theorem spanning_dense (P : Family K X d) (A : Family K X m) (hd : ∀ s, Fintype.card (X s) ≤ d) : + ZClosure {T | ∃ B : Family K X d, Spans B A ∧ T = form B + form A} + (form P + form A) := by + classical + let e (s : Leg) : X s ↪ Fin d := + (Fintype.equivFin (X s)).toEmbedding.trans (Fin.castLEEmb (hd s)) + let B : Family (Polynomial K) X d := fun l s x => + (1 - Polynomial.X) * Polynomial.C (P l s x) + Polynomial.X * (if e s x = l then 1 else 0) + let V (t : K) : Family K X d := fun l s x => (B l s x).eval t + let M (s : Leg) : Matrix (X s) (X s) (Polynomial K) := fun x y => B (e s y) s x + let N (t : K) (s : Leg) : Matrix (X s) (X s) K := fun x y => V t (e s y) s x + have heval (t : K) (s : Leg) : (M s).det.eval t = (N t s).det := + (Polynomial.evalRingHom t).map_det (M s) + have hone (s : Leg) : N 1 s = 1 := by + ext x y + simp [N, V, B, Matrix.one_apply, apply_ite] + let Q := ∏ s, (M s).det + have hQ : Q ≠ 0 := by + have : Q.eval 1 = 1 := by simp [Q, Polynomial.eval_prod, heval, hone] + intro hz + simp [hz] at this + let W x := form B x + Polynomial.C (form A x) + have he (t : K) : (fun x => (W x).eval t) = form (V t) + form A := by + funext x + simp only [W, Pi.add_apply, form, V, Polynomial.eval_add, Polynomial.eval_C, + Polynomial.eval_finsetSum, Polynomial.eval_prod] + have hv : V 0 = P := by funext l s x; simp [V, B, apply_ite] + rw [← hv, ← he] + apply path_closure W Q hQ + intro t ht + refine ⟨V t, ?_, he t⟩ + intro s + have hdet : (N t s).det ≠ 0 := by + simp only [Q, Polynomial.eval_prod, heval, prod_ne_zero_iff] at ht + exact ht s (mem_univ _) + have hsurj : Function.Surjective (N t s).mulVec := + Matrix.mulVec_surjective_iff_isUnit.mpr ((Matrix.isUnit_iff_isUnit_det _).mpr + (isUnit_iff_ne_zero.mpr hdet)) + choose c hc using fun j => hsurj (A j s) + refine ⟨fun j l => ∑ y, if e s y = l then c j y else 0, fun j x => ?_⟩ + simp_rw [sum_mul, ite_mul, zero_mul] + rw [sum_comm] + simp only [Fintype.sum_ite_eq] + simpa only [Matrix.mulVec, dotProduct, N, mul_comm] using congrFun (hc j) x + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +end + +/- +# Pole cancellation in one group + +The pivot columns `P,Q` span the remaining columns `X,Y`. A pairing +of size `d` cancels all the poles from the perturbation. Its only +uncancelled correction is divisible by the path parameter. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +open Finset + +variable {K : Type} [Field K] {d m : ℕ} + +private theorem exchange (u : Fin m → Fin d → K) (P : Fin d → K) (X Y : Fin m → K) + (h : ∀ j, ∑ l, u j l * P l = X j) : + ∑ l, P l * (∑ j, u j l * Y j) = ∑ j, X j * Y j := by + simp_rw [mul_sum, ← h, sum_mul] + rw [sum_comm] + exact sum_congr rfl fun _ _ => sum_congr rfl fun _ _ => by ring + +theorem pole (P Q H : Fin d → K) (X Y Z E F : Fin m → K) (G : K) + (u v : Fin m → Fin d → K) (hu : ∀ j, ∑ l, u j l * P l = X j) + (hv : ∀ j, ∑ l, v j l * Q l = Y j) : + ∃ W : Polynomial K, + W.eval 0 = (∑ l, P l * Q l * H l) + (∑ j, X j * Y j * Z j) + (∑ j, E j * F j * G) ∧ + ∀ t : K, t ≠ 0 → W.eval t = + (∑ l, P l * Q l * (H l + G / t ^ 4)) + + (∑ j, (X j + t * E j) * (Y j + t * F j) * (Z j + G / t ^ 2)) + + (∑ l, (P l + t ^ 3 * ∑ j, v j l * E j) * + (Q l + t ^ 2 * ∑ j, u j l * (Y j + t * F j)) * (-G / t ^ 4)) := by + let A l := ∑ j, v j l * E j + let B t l := ∑ j, u j l * (Y j + t * F j) + let C := Polynomial.C (R := K) + let T := Polynomial.X (R := K) + let W := C (∑ l, P l * Q l * H l) + + (∑ j, (C (X j) + T * C (E j)) * (C (Y j) + T * C (F j)) * C (Z j)) + + C (∑ j, E j * F j * G) - + (∑ l, C (A l) * (∑ j, C (u j l) * (C (Y j) + T * C (F j)))) * (T * C G) + have he (t : K) : W.eval t = (∑ l, P l * Q l * H l) + + (∑ j, (X j + t * E j) * (Y j + t * F j) * Z j) + + (∑ j, E j * F j * G) - (∑ l, A l * B t l) * (t * G) := by + simp only [W, C, T, B, Polynomial.eval_finsetSum, Polynomial.eval_add, Polynomial.eval_sub, + Polynomial.eval_mul, Polynomial.eval_X, Polynomial.eval_C] + refine ⟨W, by simp [he], fun t ht => ?_⟩ + have hB : ∑ l, P l * B t l = ∑ j, X j * (Y j + t * F j) := exchange u P X _ hu + have hA : ∑ l, Q l * A l = ∑ j, Y j * E j := exchange v Q Y E hv + have h₁ l : P l * Q l * (H l + G / t ^ 4) + + (P l + t ^ 3 * A l) * (Q l + t ^ 2 * B t l) * (-G / t ^ 4) = + P l * Q l * H l - P l * B t l * (G / t ^ 2) - Q l * A l * (G / t) - A l * B t l * (t * G) + := by + field_simp; ring + have h₂ j : (X j + t * E j) * (Y j + t * F j) * (Z j + G / t ^ 2) = + (X j + t * E j) * (Y j + t * F j) * Z j + X j * (Y j + t * F j) * (G / t ^ 2) + + Y j * E j * (G / t) + E j * F j * G := by field_simp; ring + change _ = _ + _ + ∑ l, (P l + t ^ 3 * A l) * (Q l + t ^ 2 * B t l) * (-G / t ^ 4) + rw [add_right_comm, ← sum_add_distrib] + simp only [h₁, h₂, sum_sub_distrib, sum_add_distrib, ← sum_mul, hA, hB, he] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +end + +/- # A group of rank-one terms returns a larger disjoint pairing -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +open Spectral Finset + +variable {K : Type} [Field K] [Infinite K] {X : Leg → Type} [∀ s, Fintype (X s)] + {d m : ℕ} {a b : Leg} + +theorem degeneration (P : Family K X d) (A E : Family K X m) (hm : 0 < m) (hab : a ≠ b) + (hs : Spans P A) (he : ∀ j l s, s ≠ a → s ≠ b → E j s = E l s) : + ZClosure {T | table T ≤ (d : Tensor K Leg) + (m : Tensor K Leg) + Tensor.wire K a b d} + (form P + form A + form E) := by + obtain ⟨c, hac, hbc⟩ := third hab + obtain ⟨u, hu⟩ := hs a + obtain ⟨v, hv⟩ := hs b + let G := E ⟨0, hm⟩ + have hG j : E j c = G c := he j _ c hac.symm hbc.symm + let P' (t : K) : Family K X d := fun l s x => + if s = c then P l s x + G s x / t ^ 4 else P l s x + let A' (t : K) : Family K X m := fun j s x => + if s = c then A j s x + G s x / t ^ 2 else A j s x + t * E j s x + let B' (t : K) : Family K X d := fun l s x => + if s = a then P l s x + t ^ 3 * ∑ j, v j l * E j s x + else if s = b then P l s x + t ^ 2 * ∑ j, u j l * (A j s x + t * E j s x) + else -G s x / t ^ 4 + have hpath (x : ∀ s, X s) : ∃ W : Polynomial K, + W.eval 0 = form P x + form A x + form E x ∧ + ∀ t, t ≠ 0 → W.eval t = form (P' t) x + form (A' t) x + form (B' t) x := by + let atX {n : ℕ} (M : Family K X n) (s : Leg) l := M l s (x s) + obtain ⟨W, h₀, hW⟩ := pole (atX P a) (atX P b) (atX P c) (atX A a) (atX A b) + (atX A c) (atX E a) (atX E b) (G c (x c)) u v (fun j => hu j _) (fun j => hv j _) + refine ⟨W, ?_, fun t ht => ?_⟩ + · simpa only [form, prod_three hab hac hbc, hG, atX] using h₀ + · simpa only [form, prod_three hab hac hbc, P', A', B', hac, hbc, hab.symm, + hac.symm, hbc.symm, ↓reduceIte, atX] using hW t ht + choose W h₀ hW using hpath + rw [show form P + form A + form E = (fun x => (W x).eval 0) from (funext h₀).symm] + apply path_closure W Polynomial.X Polynomial.X_ne_zero + intro t ht + rw [Polynomial.eval_X] at ht + change table _ ≤ _ + rw [show (fun x => (W x).eval t) = form (P' t) + form (A' t) + form (B' t) from + funext (fun x => hW x t ht)] + have hB := wire_le (B' t) a b (fun l j s ha hb => by funext x; simp [B', ha, hb]) + have hadd {x y x' y' : Tensor K Leg} (hx : x ≤ x') (hy : y ≤ y') : x + y ≤ x' + y' := + (Tensor.add_le_add_right _ _ _ hx).trans (by + rw [add_comm x' y, add_comm x' y'] + exact Tensor.add_le_add_right _ _ _ hy) + exact (table_add_le _ _).trans (hadd + ((table_add_le _ _).trans (hadd (form_le (P' t)) (form_le (A' t)))) hB) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Directions.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Directions.lean new file mode 100644 index 0000000000..456d3ac1b1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Directions.lean @@ -0,0 +1,28 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.Calculus.Deriv.Basic +public import Mathlib.Data.Fin.VecNotation + +/-! # The one-sided coordinate derivatives of an exponent -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Set + +/-- Changes the chosen one of three weights before applying the comparison function. -/ +def vary (L : ℝ → ℝ → ℝ → ℝ) (a b c : ℝ) (e : Fin 3) (t : ℝ) : ℝ := + ![L (a + t) b c, L a (b + t) c, L a b (c + t)] e + +/-- Computes the partial right by the application `derivWithin (vary L a b c e) (Ici 0) 0`. -/ +def partialRight (L : ℝ → ℝ → ℝ → ℝ) (a b c : ℝ) (e : Fin 3) : ℝ := + derivWithin (vary L a b c e) (Ici 0) 0 + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Model.lean new file mode 100644 index 0000000000..44dcdedc48 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Model.lean @@ -0,0 +1,33 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Model + +/-! # Parameters of the finite border-rank inequality -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +/-- The maximum of the quantities in `(i * j) (max (i * k) (j * k))`. -/ +def largest (i j k : ℕ) := max (i * j) (max (i * k) (j * k)) + +/-- Computes the value by the application `Real.exp (exponent F (Real.log i) (Real.log j) +(Real.log k))`. -/ +def value (F : Type*) [Field F] (i j k : ℕ) : ℝ := + Real.exp (exponent F (Real.log i) (Real.log j) (Real.log k)) + +/-- The quantity computed by `Real.log (value F i j k) / Real.log ((i : ℝ) * j * k)`. -/ +def slope (F : Type*) [Field F] (i j k : ℕ) : ℝ := + Real.log (value F i j k) / Real.log ((i : ℝ) * j * k) + +/-- The supremum of `{y | ∃ v : ℝ, 2 < v ∧ y = ((v - 1) ^ (3 / 4 : ℝ) - 1) / v}`. -/ +def Speedup.cStar : ℝ := sSup {y | ∃ v : ℝ, 2 < v ∧ y = ((v - 1) ^ (3 / 4 : ℝ) - 1) / v} + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Strict.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Strict.lean new file mode 100644 index 0000000000..8b8a2e7117 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Speedup/Strict.lean @@ -0,0 +1,923 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Model +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import Mathlib.Analysis.SpecialFunctions.Pow.Continuity +public import Mathlib.Analysis.SpecificLimits.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Directions +public import Mathlib.Analysis.Calculus.Deriv.Slope +public import Mathlib.Topology.Order.Monotone +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Surplus + +/-! # Supporting lines to the gain from a group -/ + +universe u + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup + +private theorem remainder_mono {a b : ℝ} (ha : 0 ≤ a) (hab : a ≤ b) (t : ℝ) : + Real.exp (a * t) - 1 - a * t ≤ Real.exp (b * t) - 1 - b * t := by + have h := mul_le_mul_of_nonneg_left (Real.add_one_le_exp ((b - a) * t)) (Real.exp_pos (a * t)).le + rw [← Real.exp_add, show a * t + (b - a) * t = b * t by ring] at h + have hh : 0 ≤ (Real.exp (a * t) - 1) * ((b - a) * t) := by + rcases le_total 0 t with ht | ht + · exact mul_nonneg (sub_nonneg.mpr (Real.one_le_exp (mul_nonneg ha ht))) + (mul_nonneg (sub_nonneg.mpr hab) ht) + · exact mul_nonneg_of_nonpos_of_nonpos + (sub_nonpos.mpr (Real.exp_le_one_iff.mpr (mul_nonpos_of_nonneg_of_nonpos ha ht))) + (mul_nonpos_of_nonneg_of_nonpos (sub_nonneg.mpr hab) ht) + linarith only [h, hh] + +theorem gain_tangent {d b x : ℝ} (hd : 1 ≤ d) (hdb : d ≤ b) (hx : 0 ≤ x) : + ∃ t : ℝ, 0 ≤ t ∧ ∀ y : ℝ, b ^ x - d ^ x + t * (y - x) ≤ b ^ y - d ^ y := by + have hd₀ := zero_lt_one.trans_le hd + have hb₀ := hd₀.trans_le hdb + have ha := Real.log_nonneg hd + have hab := Real.log_le_log hd₀ hdb + have hpow := Real.rpow_le_rpow hd₀.le hdb hx + refine ⟨b ^ x * Real.log b - d ^ x * Real.log d, sub_nonneg.mpr + (mul_le_mul hpow hab ha (by positivity)), ?_⟩ + intro y + have h := remainder_mono ha hab (y - x) + have h₀ : 0 ≤ Real.exp (Real.log d * (y - x)) - 1 - Real.log d * (y - x) := by + linarith only [Real.add_one_le_exp (Real.log d * (y - x))] + have he := mul_le_mul hpow h h₀ (by positivity) + have hr (a : ℝ) (ha : 0 < a) : a ^ x * Real.exp (Real.log a * (y - x)) = a ^ y := by + rw [← Real.rpow_def_of_pos ha, ← Real.rpow_add ha, add_sub_cancel] + linarith only [he, hr d hd₀, hr b hb₀] + +theorem log_tangent {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : + x + x * (Real.log y - Real.log x) ≤ y := by + have h := mul_le_mul_of_nonneg_left (Real.log_le_sub_one_of_pos (div_pos hy hx)) hx.le + rw [Real.log_div hy.ne' hx.ne', mul_sub x (y / x), mul_div_cancel₀ _ hx.ne'] at h + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +end + +/- +# Grouped speedup for spectral points + +Apply pole cancellation on the dense locus of spanning pivots, then +extend the price inequality to arbitrary decompositions. Subadditivity +lets us treat each full group independently. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral Speedup + +namespace Speedup + +variable {K : Type} [Field K] [Infinite K] {X : Leg → Type} [∀ s, Fintype (X s)] + {d m : ℕ} {a b : Leg} {f : Tensor K Leg →+* NNReal} + +private theorem one_group (P : Family K X d) (A : Family K X m) (hm : 0 < m) + (hd : ∀ s, Fintype.card (X s) ≤ d) (hf : Monotone f) (hab : a ≠ b) : + (f (table (form P + form A)) : ℝ) ≤ + (d : ℝ) + m + f (Tensor.wire K a b d) - f (Tensor.wire K a b m) := by + have hw : (f (Tensor.wire K a b m) : ℝ) ≤ m := by + have h := hf (Tensor.le_term_count (Raw.wire K a b m)) + change f (Tensor.wire K a b m) ≤ f (Fintype.card (Fin m) : Tensor K Leg) at h + rw [Fintype.card_fin, map_natCast] at h + exact_mod_cast h + apply (spanning_dense P A hd).price f hf + (by linarith [show 0 ≤ (f (Tensor.wire K a b d) : ℝ) by positivity]) + rintro _ ⟨B, hB, rfl⟩ + let M := (d : Tensor K Leg) + (m : Tensor K Leg) + Tensor.wire K a b d + have hpath := degeneration (extend m B) (extend m A) (extra X a b m) + hm hab hB.extend (extra_const a b) + have h := hpath.price f hf (B := (f M : ℝ)) (by positivity) + (fun _ hx => NNReal.coe_le_coe.mpr (hf hx)) + change (f (table _) : ℝ) ≤ _ at h + rw [table_extra] at h + unfold M at h + rw [map_add, map_add, map_add, map_natCast, map_natCast] at h + exact le_sub_iff_add_le.mpr h + +omit [Infinite K] [∀ s, Fintype (X s)] in +private theorem split_form (A : Family K X (d + m)) : + ∃ P : Family K X d, ∃ B : Family K X m, form A = form P + form B := by + exact ⟨fun l => A (Fin.castAdd m l), fun l => A (Fin.natAdd d l), + funext fun _ => Fin.sum_univ_add _⟩ + +theorem groups (hf : Monotone f) (hab : a ≠ b) (hd : ∀ s, Fintype.card (X s) ≤ d) (hm : 0 < m) + (h : ℕ) {r : ℕ} (hr : (d + m) * h ≤ r) (A : Family K X r) : + (f (table (form A)) : ℝ) + h * ((f (Tensor.wire K a b m) : ℝ) - f (Tensor.wire K a b d)) ≤ r + := by + induction h generalizing r with + | zero => + have h := hf (form_le A) + rw [map_natCast] at h + simp only [Nat.cast_zero, zero_mul, add_zero] + exact_mod_cast h + | succ h ih => + rw [Nat.mul_succ] at hr + obtain ⟨l, rfl⟩ := Nat.exists_eq_add_of_le (show d + m ≤ r by omega) + obtain ⟨P, B, hA⟩ := split_form A + obtain ⟨P₁, P₂, hP⟩ := split_form P + have h₁ := one_group P₁ P₂ hm hd hf hab + have h₂ := ih (by omega : (d + m) * h ≤ l) B + have h₃ := NNReal.coe_le_coe.mpr (hf (table_add_le (form P) (form B))) + rw [← hA, map_add, NNReal.coe_add, hP] at h₃ + rw [Nat.cast_succ, Nat.cast_add, Nat.cast_add] + linarith only [h₁, h₂, h₃] + +end Speedup + +theorem grouped_price {K : Type} [Field K] [Infinite K] + (X : Fin 3 → Type) [∀ s, Fintype (X s)] (T : (∀ s, X s) → K) {d g r : ℕ} + (hd : ∀ s, Fintype.card (X s) ≤ d) (hg : d < g) + (hr : Tensor.ofRaw (Raw.ofTable X T) ≤ (r : Tensor K (Fin 3))) + (f : Tensor K (Fin 3) →+* NNReal) (hf : Monotone f) (a b : Fin 3) (hab : a ≠ b) : + (f (Tensor.ofRaw (Raw.ofTable X T)) : ℝ) + (r / g : ℕ) * + ((f (Tensor.wire K a b (g - d)) : ℝ) - (f (Tensor.wire K a b d) : ℝ)) ≤ (r : ℝ) := by + obtain ⟨A, rfl⟩ := exists_form hr + apply groups hf hab hd (Nat.sub_pos_of_lt hg) (r / g) _ A + rw [Nat.add_sub_of_le hg.le] + exact Nat.mul_div_le _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- +# The square speedup constant + +For groups of size `⌈v s²⌉`, the normalized gain tends to the profile at +`v`. The profile is zero at two and tends to zero at infinity, so its +positive maximum is attained in the open range. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +open Set Filter +open scoped Topology + +private def profile (v : ℝ) := ((v - 1) ^ (3 / 4 : ℝ) - 1) / v + +private theorem sample : profile 17 = 7 / 17 := by + have h : (16 : ℝ) ^ (3 / 4 : ℝ) = 8 := by + rw [show (16 : ℝ) = 2 ^ (4 : ℕ) by norm_num, ← Real.rpow_natCast_mul (by norm_num)] + norm_num + unfold profile + rw [show (17 : ℝ) - 1 = 16 by norm_num, h] + norm_num + +theorem cStar_greatest : IsGreatest {y | ∃ v : ℝ, 2 < v ∧ y + = ((v - 1) ^ (3 / 4 : ℝ) - 1) / v} cStar := by + have ht : ∀ᶠ v : ℝ in atTop, profile v ≤ 7 / 17 := by + have h := tendsto_rpow_neg_atTop (by norm_num : (0 : ℝ) < 1 / 4) + filter_upwards [eventually_ge_atTop (2 : ℝ), h.eventually_lt_const (by norm_num : (0 : ℝ) + < 7 / 17)] + with v hv h' + have hv' : 0 < v := by linarith + calc + profile v ≤ v ^ (3 / 4 : ℝ) / v := by + unfold profile + gcongr + exact (sub_le_self _ zero_le_one).trans (Real.rpow_le_rpow (by linarith) (by linarith) (by + norm_num)) + _ = v ^ (-(1 / 4) : ℝ) := by + rw [show (-(1 / 4) : ℝ) = 3 / 4 - 1 by norm_num, Real.rpow_sub hv', Real.rpow_one] + _ ≤ _ := h'.le + obtain ⟨V, hV⟩ := eventually_atTop.mp ht + let I := Icc (2 : ℝ) (max 17 V) + have hi : (17 : ℝ) ∈ I := ⟨by norm_num, le_max_left _ _⟩ + have hc : ContinuousOn profile I := by + unfold profile + exact (((continuousOn_id.sub continuousOn_const).rpow_const (fun _ _ + => Or.inr (by norm_num))).sub + continuousOn_const).div continuousOn_id (fun v hv => by change v ≠ 0; linarith [hv.1]) + obtain ⟨v, hv, hm⟩ := isCompact_Icc.exists_isMaxOn ⟨_, hi⟩ hc + have hmax : 7 / 17 ≤ profile v := sample.symm.trans_le (hm hi) + have hlt : 2 < v := lt_of_le_of_ne hv.1 (by rintro rfl; norm_num [profile] at hmax) + have h : IsGreatest {y | ∃ v : ℝ, 2 < v ∧ y = ((v - 1) ^ (3 / 4 : ℝ) - 1) / v} (profile v) := by + refine ⟨⟨v, hlt, rfl⟩, ?_⟩ + rintro _ ⟨w, hw, rfl⟩ + by_cases h' : w ≤ max 17 V + · exact hm ⟨hw.le, h'⟩ + · exact (hV _ ((le_max_right _ _).trans (le_of_not_ge h'))).trans hmax + rwa [cStar, h.csSup_eq] + +theorem cStar_lower : 7 / 17 ≤ cStar := + cStar_greatest.2 ⟨17, by norm_num, sample.symm⟩ + +theorem square_limit {r : ℕ → ℕ} + (h : ∀ s g : ℕ, 2 ≤ s → 2 * s ^ 2 < g → + (s : ℝ) ^ (9 / 4 : ℝ) + (⌊(s : ℝ) ^ (9 / 4 : ℝ) / g⌋₊ : ℝ) * + (((g : ℝ) - (s : ℝ) ^ 2) ^ (3 / 4 : ℝ) - ((s : ℝ) ^ 2) ^ (3 / 4 : ℝ)) ≤ r s) + {c : ℝ} (hc : c < cStar) : + ∀ᶠ s : ℕ in atTop, (s : ℝ) ^ (9 / 4 : ℝ) + c * (s : ℝ) ^ (7 / 4 : ℝ) ≤ r s := by + obtain ⟨v, hv, he⟩ := cStar_greatest.1 + have hv₀ : 0 < v := by linarith + let g (s : ℕ) := ⌈v * (s : ℝ) ^ 2⌉₊ + let b (s : ℕ) := (g s : ℝ) / (s : ℝ) ^ 2 + let w (s : ℕ) := (s : ℝ) ^ (1 / 4 : ℝ) + have hs : Tendsto (fun s : ℕ => (s : ℝ) ^ 2) atTop atTop := by + simpa only [Function.comp_def, Real.rpow_two] using + (tendsto_rpow_atTop (by norm_num : (0 : ℝ) < 2)).comp tendsto_natCast_atTop_atTop + have hb : Tendsto b atTop (𝓝 v) := (tendsto_nat_ceil_mul_div_atTop hv₀.le).comp hs + have hw : Tendsto w atTop atTop := + (tendsto_rpow_atTop (by norm_num)).comp tendsto_natCast_atTop_atTop + have hratio : Tendsto (fun s => w s / b s) atTop atTop := + hw.atTop_mul_pos (inv_pos.mpr hv₀) (hb.inv₀ hv₀.ne') + have hfloor := tendsto_nat_floor_div_atTop.comp hratio + have hterm := ((hb.sub_const 1).rpow_const (p := (3 / 4 : ℝ)) (Or.inr (by norm_num))).sub_const 1 + have hlim := (hfloor.mul hterm).div hb hv₀.ne' + rw [one_mul, ← he] at hlim + filter_upwards [eventually_ge_atTop 2, hlim.eventually_const_lt hc] with s hs hlt + have hs₀ : 0 < (s : ℝ) := by exact_mod_cast (show 0 < s by omega) + have hg : 2 * s ^ 2 < g s := by + apply Nat.lt_ceil.mpr + push_cast + exact mul_lt_mul_of_pos_right hv (by positivity) + have hgs : (s : ℝ) ^ 2 < g s := by exact_mod_cast (show s ^ 2 < g s by omega) + have hg₀ : 0 < (g s : ℝ) := (sq_nonneg _).trans_lt hgs + have hw₀ : 0 < w s := by unfold w; positivity + have hb₀ : 1 < b s := (one_lt_div (by positivity)).mpr hgs + have h9 : (s : ℝ) ^ (9 / 4 : ℝ) / g s = w s / b s := by + rw [show (9 / 4 : ℝ) = 1 / 4 + 2 by norm_num, Real.rpow_add hs₀, Real.rpow_two] + unfold w b + field_simp + have h7 : (s : ℝ) ^ (7 / 4 : ℝ) = w s * ((s : ℝ) ^ 2) ^ (3 / 4 : ℝ) := by + unfold w + rw [← Real.rpow_natCast_mul hs₀.le, ← Real.rpow_add hs₀] + norm_num + have heq : ((g s : ℝ) - (s : ℝ) ^ 2) ^ (3 / 4 : ℝ) = + (b s - 1) ^ (3 / 4 : ℝ) * ((s : ℝ) ^ 2) ^ (3 / 4 : ℝ) := by + rw [← Real.mul_rpow (by linarith) (by positivity)] + unfold b + congr 1 + field_simp + refine le_trans ?_ (h s (g s) hs hg) + apply add_le_add_right + rw [h9, heq, h7] + change c < (⌊w s / b s⌋₊ : ℝ) / (w s / b s) * ((b s - 1) ^ (3 / 4 : ℝ) - 1) / b s at hlt + have h' : c * w s ≤ (⌊w s / b s⌋₊ : ℝ) * ((b s - 1) ^ (3 / 4 : ℝ) - 1) := by + apply (le_div_iff₀ hw₀).mp + convert hlt.le using 1 + field_simp + linarith only [mul_le_mul_of_nonneg_right h' (by positivity : 0 ≤ ((s : ℝ) ^ 2) ^ (3 / 4 : ℝ))] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Speedup +end + +section +/- +# Detecting a full-support product at an ordinary maximizer + +Mixed powers of the weighting and ordinary multiplication still have +full support. Their unconditional exact rank lower bound thus detects +a point maximizing the ordinary price without losing weighted price. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral + +theorem value_pow (F : Type*) [Field F] {i j k : ℕ} (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) + (n : ℕ) : value F (i ^ n) (j ^ n) (k ^ n) = (value F i j k) ^ n := by + have hlog {m : ℕ} (hm : 0 < m) := Real.log_nonneg (by exact_mod_cast hm : 1 ≤ (m : ℝ)) + simp only [value, Nat.cast_pow, Real.log_pow] + rw [homogeneous F (hlog hi) (hlog hj) (hlog hk) (Nat.cast_nonneg _), Real.exp_nat_mul] + +variable {F : Type} [Field F] {i j k : ℕ} + +theorem tensor_price {f : Point F} (hf : Monotone f) (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + (f (tensor F i j k) : ℝ) = Real.exp (score f (Real.log i) (Real.log j) (Real.log k)) := by + have h (a b : Fin 3) {n : ℕ} (hn : 0 < n) : + (f (Tensor.wire F a b n) : ℝ) = Real.exp (Real.log n * dist f a b) := + (Tensor.price_wire _ (mono_real hf) a b hn).trans (Real.rpow_def_of_pos (by positivity) _) + rw [tensor, f.map_mul, f.map_mul, NNReal.coe_mul, NNReal.coe_mul, h _ _ hi, h _ _ hj, + h _ _ hk, score, Real.exp_add, Real.exp_add] + +/-- The condition `∃ w : Fin i → Fin j → Fin k → F, (∀ a b c, w a b c ≠ 0) ∧ weightedTensor w ≤ +A` on the specified data. -/ +def Covers (i j k : ℕ) (A : Tensor F (Fin 3)) : Prop := + ∃ w : Fin i → Fin j → Fin k → F, (∀ a b c, w a b c ≠ 0) ∧ weightedTensor w ≤ A + +theorem Covers.mul {i' j' k' I J K : ℕ} {A B : Tensor F (Fin 3)} + (h : Covers i j k A) (h' : Covers i' j' k' B) + (hi : I = i * i') (hj : J = j * j') (hk : K = k * k') : Covers I J K (A * B) := by + obtain ⟨x, hx, hx'⟩ := h + obtain ⟨y, hy, hy'⟩ := h' + obtain ⟨z, hz, hz'⟩ := tensor_full hx hy hi hj hk + refine ⟨z, hz, hz'.trans ((Tensor.mul_le_mul_left _ _ _ hy').trans ?_)⟩ + rw [mul_comm, mul_comm A] + exact Tensor.mul_le_mul_left _ _ _ hx' + +theorem Covers.pow {A : Tensor F (Fin 3)} (h : Covers i j k A) (n : ℕ) : + Covers (i ^ n) (j ^ n) (k ^ n) (A ^ n) := by + induction n with + | zero => + simp only [pow_zero] + refine ⟨fun _ _ _ => 1, fun _ _ _ => one_ne_zero, ?_⟩ + have h₁ := ordinary_le_tensor F (i := 1) (j := 1) (k := 1) (by decide) (by decide) (by decide) + simpa [tensor, Tensor.wire, Tensor.shared_one] using h₁ + | succ n ih => + rw [pow_succ A] + exact ih.mul h (pow_succ _ _) (pow_succ _ _) (pow_succ _ _) + +theorem weighted_maximizer {w : Fin i → Fin j → Fin k → F} (hw : ∀ a b c, w a b c ≠ 0) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + ∃ f : Point F, Monotone f ∧ value F i j k ≤ (f (weightedTensor w) : ℝ) ∧ + (f (tensor F i j k) : ℝ) = value F i j k := by + have hρ : 0 < value F i j k := Real.exp_pos _ + refine simultaneous hρ hρ ?_ ?_ + · intro f hf + rw [tensor_price hf hi hj hk, value, Real.exp_le_exp] + exact score_le_exponent hf (Real.log_nonneg (by exact_mod_cast hi)) + (Real.log_nonneg (by exact_mod_cast hj)) (Real.log_nonneg (by exact_mod_cast hk)) + intro m n r hr + have h₁ : Covers i j k (weightedTensor w) := ⟨w, hw, le_rfl⟩ + have h₂ : Covers i j k (tensor F i j k) := + ⟨_, fun _ _ _ => one_ne_zero, ordinary_le_tensor F hi hj hk⟩ + have hm := h₁.mul (h₂.pow m) (pow_succ' i m) (pow_succ' j m) (pow_succ' k m) + obtain ⟨v, hv, hv'⟩ := hm.pow n + have hR : WeightedRankLE v r := (wtensor_le_iff (coefficients v)).mp (hv'.trans hr) + have hh := hR.full hv (pow_pos (pow_pos hi _) _) (pow_pos (pow_pos hj _) _) + (pow_pos (pow_pos hk _) _) + change value F _ _ _ ≤ r at hh + rwa [value_pow F (pow_pos hi _) (pow_pos hj _) (pow_pos hk _), + value_pow F hi hj hk, pow_succ'] at hh + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- # Mixed products of full-support and ordinary tensors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral Filter +open scoped Topology + +variable {F : Type} [Field F] {A B : Tensor F (Fin 3)} + +/-- The condition `∃ i j k, 0 < i ∧ 0 < j ∧ 0 < k ∧ Covers i j k A ∧ B = tensor F i j k` on the +specified data. -/ +def Dominates (A B : Tensor F (Fin 3)) : Prop := + ∃ i j k, 0 < i ∧ 0 < j ∧ 0 < k ∧ Covers i j k A ∧ B = tensor F i j k + +theorem Dominates.mul {A' B' : Tensor F (Fin 3)} (h : Dominates A B) (h' : Dominates A' B') : + Dominates (A * A') (B * B') := by + obtain ⟨i, j, k, hi, hj, hk, h, rfl⟩ := h + obtain ⟨i', j', k', hi', hj', hk', h', rfl⟩ := h' + refine ⟨i * i', j * j', k * k', by positivity, by positivity, by positivity, + h.mul h' rfl rfl rfl, ?_⟩ + simp only [tensor, Tensor.wire, Tensor.shared_mul] + exact (mul_mul_mul_comm _ _ _ _).trans (congrArg (· * _) (mul_mul_mul_comm _ _ _ _)) + +theorem Dominates.pow (h : Dominates A B) (m : ℕ) : Dominates (A ^ m) (B ^ m) := by + obtain ⟨i, j, k, hi, hj, hk, h, rfl⟩ := h + exact ⟨_, _, _, pow_pos hi _, pow_pos hj _, pow_pos hk _, h.pow m, (tensor_power _ _ _ _ _).symm⟩ + +theorem Dominates.price (h : Dominates A B) {f : Point F} (hf : Monotone f) : + ∃ g : Point F, Monotone g ∧ (f B : ℝ) ≤ g A := by + obtain ⟨i, j, k, hi, hj, hk, ⟨w, hw, hw'⟩, rfl⟩ := h + obtain ⟨g, hg, hg', _⟩ := weighted_maximizer hw hi hj hk + refine ⟨g, hg, le_trans ?_ (hg'.trans (NNReal.coe_le_coe.mpr (hg hw')))⟩ + rw [tensor_price hf hi hj hk, value, Real.exp_le_exp] + exact score_le_exponent hf (Real.log_nonneg (by exact_mod_cast hi)) + (Real.log_nonneg (by exact_mod_cast hj)) (Real.log_nonneg (by exact_mod_cast hk)) + +theorem Dominates.pos {f : Point F} (h : Dominates A B) (hf : Monotone f) : + 0 < (f B : ℝ) := by + obtain ⟨i, j, k, hi, hj, hk, _, rfl⟩ := h + rw [tensor_price hf hi hj hk] + exact Real.exp_pos _ + +theorem Dominates.one_le {f : Point F} (h : Dominates A B) (hf : Monotone f) : + 1 ≤ (f A : ℝ) := by + obtain ⟨g, _, hg⟩ := h.price hf + have hA : A ≠ 0 := by + intro he + have hp := (h.pos hf).trans_le hg + simp [he] at hp + have he := hf (Tensor.one_le A hA) + rw [map_one] at he + exact_mod_cast he + +/-- A uniform linear upper bound on two log-prices transfers from +the full-support weightings to their ordinary products. Integer +multiplicities approximate any nonnegative real slope. -/ +theorem Dominates.line {C D : Tensor F (Fin 3)} (h : Dominates A B) (h' : Dominates C D) + {t b : ℝ} (ht : 0 ≤ t) + (hu : ∀ f : Point F, Monotone f → Real.log (f A) + t * Real.log (f C) ≤ b) + {g : Point F} (hg : Monotone g) : + Real.log (g B) + t * Real.log (g D) ≤ b := by + have hp : Tendsto (fun n : ℕ => (⌊t * n⌋₊ : ℝ) / n) atTop (𝓝 t) := + (tendsto_nat_floor_mul_div_atTop ht).comp tendsto_natCast_atTop_atTop + apply le_of_tendsto ((hp.mul_const (Real.log (g D))).const_add (Real.log (g B))) + filter_upwards [eventually_gt_atTop 0] with n hn + let m := ⌊t * n⌋₊ + obtain ⟨f, hf, hf'⟩ := ((h.pow n).mul (h'.pow m)).price hg + simp only [g.map_mul, f.map_mul, map_pow, NNReal.coe_mul, NNReal.coe_pow] at hf' + have hgB := h.pos hg + have hgD := h'.pos hg + have hfA := h.one_le hf + have hfC := h'.one_le hf + have he := Real.log_le_log (by positivity) hf' + rw [Real.log_mul (by positivity) (by positivity), + Real.log_mul (by positivity) (by positivity)] at he + simp only [Real.log_pow] at he + have hn' : 0 < (n : ℝ) := by positivity + have hh : (m : ℝ) ≤ t * n := Nat.floor_le (by positivity) + have hh' := mul_le_mul_of_nonneg_right hh (Real.log_nonneg hfC) + have hf' := mul_le_mul_of_nonneg_left (hu f hf) hn'.le + change Real.log (g B) + (m : ℝ) / n * Real.log (g D) ≤ b + field_simp + linarith only [he, hh', hf'] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +/- # Right-hand slopes of the three-side exponent -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter Set Spectral +open scoped Topology + +@[simp] theorem vary_zero (L : ℝ → ℝ → ℝ → ℝ) (a b c : ℝ) (e : Fin 3) : + vary L a b c e 0 = L a b c := by + fin_cases e <;> simp [vary] + +variable {F : Type} [Field F] {a b c t : ℝ} + +private theorem maximizing (F : Type) [Field F] (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + ∃ f : Point F, Monotone f ∧ score f a b c = exponent F a b c := by + obtain ⟨x, y, z, h, he⟩ := (support F).attains ha hb hc + obtain ⟨f, hf, hf'⟩ := h.score (a := a) (b := b) (c := c) + exact ⟨f, hf, hf'.symm.trans he⟩ + +/-- The value specified by `![(0, 1), (0, 2), (1, 2)] e`. -/ +def edge (e : Fin 3) : Fin 3 × Fin 3 := ![(0, 1), (0, 2), (1, 2)] e + +theorem edge_ne (e : Fin 3) : (edge e).1 ≠ (edge e).2 := by fin_cases e <;> decide + +theorem vary_score (f : Point F) (e : Fin 3) (a b c t : ℝ) : + vary (score f) a b c e t = score f a b c + t * dist f (edge e).1 (edge e).2 := by + fin_cases e <;> simp [vary, score, edge] <;> ring + +theorem vary_max (F : Type) [Field F] (e : Fin 3) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (ht : 0 ≤ t) : + ∃ f : Point F, Monotone f ∧ vary (score f) a b c e t = vary (exponent F) a b c e t := by + fin_cases e + · exact maximizing F (add_nonneg ha ht) hb hc + · exact maximizing F ha (add_nonneg hb ht) hc + · exact maximizing F ha hb (add_nonneg hc ht) + +private theorem vary_le {f : Point F} (hf : Monotone f) (e : Fin 3) + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) (ht : 0 ≤ t) : + vary (score f) a b c e t ≤ vary (exponent F) a b c e t := by + fin_cases e + · exact score_le_exponent hf (add_nonneg ha ht) hb hc + · exact score_le_exponent hf ha (add_nonneg hb ht) hc + · exact score_le_exponent hf ha hb (add_nonneg hc ht) + +/-- A maximum of affine price functions has an increasing secant slope. +The slope at zero is interpreted from the positive side, even on a face. -/ +theorem partialRight_spec (F : Type) [Field F] (e : Fin 3) + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + let X := vary (exponent F) a b c e + let d := partialRight (exponent F) a b c e + HasDerivWithinAt X d (Ici 0) 0 ∧ 0 ≤ d ∧ ∀ t, 0 ≤ t → X 0 + t * d ≤ X t := by + intro X d + let Q t := (X t - X 0) / t + have hnon (t : ℝ) (ht : 0 < t) : 0 ≤ Q t := by + obtain ⟨f, hf, he⟩ := vary_max F e ha hb hc (le_rfl : (0 : ℝ) ≤ 0) + have hu := vary_le hf e ha hb hc ht.le + rw [vary_score, zero_mul, add_zero] at he + rw [vary_score, he] at hu + exact div_nonneg (sub_nonneg.mpr ((le_add_of_nonneg_right + (mul_nonneg ht.le (dist_bounds hf _ _).1)).trans hu)) ht.le + have hm : MonotoneOn Q (Ioi 0) := by + intro s hs t ht hst + obtain ⟨f, hf, he⟩ := vary_max F e ha hb hc hs.le + have h₀ := vary_le hf e ha hb hc (le_rfl : (0 : ℝ) ≤ 0) + have h₁ := vary_le hf e ha hb hc ht.le + rw [vary_score, zero_mul, add_zero] at h₀ + rw [vary_score] at he h₁ + unfold Q X + rw [div_le_div_iff₀ hs ht, ← he] + linarith only [mul_le_mul_of_nonneg_right h₀ (sub_nonneg.mpr hst), + mul_le_mul_of_nonneg_right h₁ hs.le] + have hbdd : BddBelow (Q '' Ioi 0) := ⟨0, by rintro _ ⟨t, ht, rfl⟩; exact hnon t ht⟩ + let b := sInf (Q '' Ioi 0) + have hd : HasDerivWithinAt X b (Ici 0) 0 := by + apply HasDerivWithinAt.Ici_of_Ioi + apply (hasDerivWithinAt_iff_tendsto_slope' (by simp)).mpr + have he : _root_.slope X 0 = Q := by ext t; rw [slope_def_field, sub_zero] + rw [he] + exact hm.tendsto_nhdsGT hbdd + have he : d = b := hd.derivWithin (uniqueDiffWithinAt_Ici 0) + rw [he] + refine ⟨hd, le_csInf ⟨_, 1, by norm_num, rfl⟩ ?_, ?_⟩ + · rintro _ ⟨t, ht, rfl⟩ + exact hnon t ht + · intro t ht + rcases eq_or_lt_of_le ht with rfl | ht + · simp + have he : b ≤ Q t := csInf_le hbdd ⟨t, ht, rfl⟩ + linarith only [(le_div_iff₀ ht).mp he] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Grouped speedup for geometric border rank + +Take a point maximizing the ordinary tensor while detecting the weighting. +An orientation with largest wire exponent achieves at least the average +exponent weighted by the three logarithmic side lengths. Spectral +sublevels are closed, so the group estimate survives geometric closure. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral + +private theorem ZClosure.ungroup {F : Type} [Field F] {i j k : ℕ} + {A : Set (Coordinates i j k → F)} {T : Coordinates i j k → F} + (h : ZClosure A T) : ZClosure ((fun v => v ∘ ungroup) '' A) (T ∘ ungroup) := by + intro p hp + rw [← MvPolynomial.eval_rename] + apply h + intro t ht + rw [MvPolynomial.eval_rename] + exact hp _ ⟨t, ht, rfl⟩ + +private theorem best_wire {F : Type} [Field F] {i j k : ℕ} {f : Point F} + (hf : Monotone f) (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) (hvol : 1 < i * j * k) + (h : (f (tensor F i j k) : ℝ) = value F i j k) : + ∃ a b : Fin 3, a ≠ b ∧ slope F i j k ≤ dist f a b := by + let d := max (dist f 0 1) (max (dist f 0 2) (dist f 1 2)) + have h₁ : dist f 0 1 ≤ d := le_max_left _ _ + have h₂ : dist f 0 2 ≤ d := (le_max_left _ _).trans (le_max_right _ _) + have h₃ : dist f 1 2 ≤ d := (le_max_right _ _).trans (le_max_right _ _) + have he : slope F i j k ≤ d := by + unfold slope + apply (div_le_iff₀ (Real.log_pos (by exact_mod_cast hvol))).2 + rw [← h, tensor_price hf hi hj hk, Real.log_exp, score, Real.log_mul (by positivity) + (by positivity), Real.log_mul (by positivity) (by positivity)] + have hlog {m : ℕ} (hm : 0 < m) := Real.log_nonneg (by exact_mod_cast hm : 1 ≤ (m : ℝ)) + linarith only [mul_le_mul_of_nonneg_left h₁ (hlog hi), mul_le_mul_of_nonneg_left h₂ (hlog hj), + mul_le_mul_of_nonneg_left h₃ (hlog hk)] + rcases le_max_iff.mp he with h | h + · exact ⟨0, 1, by decide, h⟩ + rcases le_max_iff.mp h with h | h + · exact ⟨0, 2, by decide, h⟩ + · exact ⟨1, 2, by decide, h⟩ + +theorem slope_nonneg (F : Type*) [Field F] {i j k : ℕ} (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) + (hvol : 1 < i * j * k) : 0 ≤ slope F i j k := by + have hlog {m : ℕ} (hm : 0 < m) := Real.log_nonneg (by exact_mod_cast hm : 1 ≤ (m : ℝ)) + have h := (bounds F (hlog hi) (hlog hj) (hlog hk)).1 + rw [slope, value, Real.log_exp] + exact div_nonneg ((add_nonneg (hlog hi) (hlog hj)).trans ((le_max_left _ _).trans h)) + (Real.log_pos (by exact_mod_cast hvol)).le + +private theorem gain_mono {x d a b : ℝ} (hd : 1 ≤ d) (hx : d ≤ x) + (ha : 0 ≤ a) (hab : a ≤ b) : x ^ a - d ^ a ≤ x ^ b - d ^ b := by + have hgap : 0 ≤ b - a := sub_nonneg.mpr hab + have hd' := zero_lt_one.trans_le hd + have hx' := hd'.trans_le hx + have he (y : ℝ) (hy : 0 < y) : y ^ b - y ^ a = y ^ a * (y ^ (b - a) - 1) := by + rw [mul_sub, ← Real.rpow_add hy, add_sub_cancel, mul_one] + have h : d ^ b - d ^ a ≤ x ^ b - x ^ a := by + rw [he d hd', he x hx'] + exact mul_le_mul (Real.rpow_le_rpow hd'.le hx ha) + (sub_le_sub_right (Real.rpow_le_rpow hd'.le hx hgap) 1) + (sub_nonneg.mpr (Real.one_le_rpow hd hgap)) (by positivity) + linarith + +theorem closure_grouped {K : Type} [Field K] [Infinite K] {i j k r d g : ℕ} + {u : Fin i → Fin j → Fin k → K} (hu : ZClosure (rankSet K i j k r) (coefficients u)) + (hmax : largest i j k ≤ d) (hd : 0 < d) (hg' : d < g) + (f : Point K) (hf : Monotone f) {x y : Fin 3} (hxy : x ≠ y) : + (f (weightedTensor u) : ℝ) + (r / g : ℕ) * + (((g : ℝ) - d) ^ dist f x y - (d : ℝ) ^ dist f x y) ≤ r := by + let gain := (f (Tensor.wire K x y (g - d)) : ℝ) - (f (Tensor.wire K x y d) : ℝ) + let B := (r : ℝ) - (r / g : ℕ) * gain + have hp (v) (hv : v ∈ rankSet K i j k r) : (f (wtensor v) : ℝ) ≤ B := by + exact le_sub_iff_add_le.mpr (grouped_price _ _ (fun s => (legs_card i j k s).trans hmax) hg' + ((wtensor_le_iff v).mpr hv) f hf x y hxy) + have hB : 0 ≤ B := by + have h₀ : (0 : Coordinates i j k → K) ∈ rankSet K i j k r := ⟨0, 0, 0, by simp⟩ + exact (NNReal.coe_nonneg _).trans (hp 0 h₀) + have hprice : (f (weightedTensor u) : ℝ) ≤ B := + hu.ungroup.price f hf hB (by rintro _ ⟨v, hv, rfl⟩; exact hp v hv) + have he : gain = ((g : ℝ) - d) ^ dist f x y - (d : ℝ) ^ dist f x y := by + have hw' {n : ℕ} (hn : 0 < n) : (f (Tensor.wire K x y n) : ℝ) = (n : ℝ) ^ dist f x y := + Tensor.price_wire _ (mono_real hf) _ _ hn + unfold gain + rw [hw' (Nat.sub_pos_of_lt hg'), hw' hd, Nat.cast_sub hg'.le] + rw [← he] + exact le_sub_iff_add_le.mp hprice + +theorem group_count {ρ : ℝ} {r g : ℕ} (hρ : 0 < ρ) (hr : ρ ≤ r) (hg : 0 < g) : + ⌊ρ / g⌋₊ ≤ r / g := by + apply (Nat.le_div_iff_mul_le hg).mpr + have hg₀ : 0 < (g : ℝ) := by positivity + exact_mod_cast ((le_div_iff₀ hg₀).mp (Nat.floor_le (div_nonneg hρ.le hg₀.le))).trans hr + +variable {F : Type*} [Field F] {i j k r : ℕ} {w : Fin i → Fin j → Fin k → F} + +/-- The grouped bound holds with the actual exponent, without assuming +a formula for its value. -/ +theorem BorderRankLE.grouped (h : BorderRankLE w r) (hw : ∀ a b c, w a b c ≠ 0) + (hvol : 1 < i * j * k) {g : ℕ} (hg : 2 * largest i j k < g) : + let d := largest i j k + let ρ := value F i j k + let a := slope F i j k + ρ + (⌊ρ / g⌋₊ : ℝ) * (((g : ℝ) - d) ^ a - (d : ℝ) ^ a) ≤ r := by + intro d ρ a + have hi : 0 < i := Nat.pos_of_ne_zero (by rintro rfl; simp at hvol) + have hj : 0 < j := Nat.pos_of_ne_zero (by rintro rfl; simp at hvol) + have hk : 0 < k := Nat.pos_of_ne_zero (by rintro rfl; simp at hvol) + have hd : 0 < d := (Nat.mul_pos hi hj).trans_le (le_max_left _ _) + have hg' : d < g := by omega + have hr : ρ ≤ r := h.full hw hi hj hk + have hρ : 0 < ρ := Real.exp_pos _ + have ha : 0 ≤ a := slope_nonneg F hi hj hk hvol + obtain ⟨K, _, _, alg, u, hs, hu⟩ := h.small + have hu' (x y z) : u x y z ≠ 0 := fun he => hw x y z ((hs x y z).mp he) + have hlog {m : ℕ} (hm : 0 < m) := Real.log_nonneg (by exact_mod_cast hm : 1 ≤ (m : ℝ)) + have he : value K i j k = ρ := by + rw [value, ← exponent_extension K (AlgebraicClosure F) (hlog hi) (hlog hj) (hlog hk), + exponent_extension F (AlgebraicClosure F) (hlog hi) (hlog hj) (hlog hk)] + rfl + have he' : slope K i j k = a := by rw [slope, he]; rfl + obtain ⟨f, hf, hf', heq⟩ := weighted_maximizer hu' hi hj hk + obtain ⟨x, y, hxy, hθ⟩ := best_wire hf hi hj hk hvol heq + rw [he'] at hθ + rw [he] at hf' + have hprice := closure_grouped hu le_rfl hd hg' f hf hxy + have hcount := group_count hρ hr (hd.trans hg') + have hgd : (d : ℝ) ≤ g - d := by + have hh : 2 * (d : ℝ) < g := by exact_mod_cast hg + linarith + have hgain := gain_mono (by exact_mod_cast hd) hgd ha hθ + have h₀ := sub_nonneg.mpr (Real.rpow_le_rpow (Nat.cast_nonneg _) hgd ha) + have hh := mul_le_mul (Nat.cast_le.mpr hcount) hgain h₀ (Nat.cast_nonneg _) + exact (add_le_add hf' hh).trans hprice + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Speedup with any one-sided slope + +Linearize both terms of the grouped price bound at the proposed +ordinary value and directional slope. The resulting linear upper +bound on log-prices transfers to the ordinary product by mixed powers. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Spectral Set + +private theorem ordinary_dominates (F : Type) [Field F] (i j k : ℕ) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) : + Dominates (tensor F i j k) (tensor F i j k) := + ⟨i, j, k, hi, hj, hk, ⟨_, fun _ _ _ => one_ne_zero, ordinary_le_tensor F hi hj hk⟩, rfl⟩ + +private theorem wire_dominates (F : Type) [Field F] (e : Fin 3) : + let W := Tensor.wire F (edge e).1 (edge e).2 2 + Dominates W W := by + fin_cases e + · simpa [edge, tensor, Tensor.wire, Tensor.shared_one] using + ordinary_dominates F 2 1 1 (by decide) (by decide) (by decide) + · simpa [edge, tensor, Tensor.wire, Tensor.shared_one] using + ordinary_dominates F 1 2 1 (by decide) (by decide) (by decide) + · simpa [edge, tensor, Tensor.wire, Tensor.shared_one] using + ordinary_dominates F 1 1 2 (by decide) (by decide) (by decide) + +private theorem closure_directional {F : Type} [Field F] [Infinite F] {i j k r g : ℕ} + {w : Fin i → Fin j → Fin k → F} (h : ZClosure (rankSet F i j k r) (coefficients w)) + (hw : ∀ a b c, w a b c ≠ 0) (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) + (hg : 2 * largest i j k < g) (e : Fin 3) : + let d := largest i j k + let θ := partialRight (exponent F) (Real.log i) (Real.log j) (Real.log k) e + value F i j k + (r / g : ℕ) * (((g : ℝ) - d) ^ θ - (d : ℝ) ^ θ) ≤ r := by + intro d θ + let ρ := value F i j k + let q : ℝ := (r / g : ℕ) + let B := ((g : ℝ) - d) ^ θ - (d : ℝ) ^ θ + let W := Tensor.wire F (edge e).1 (edge e).2 2 + let A := weightedTensor w + have hA : Dominates A (tensor F i j k) := ⟨i, j, k, hi, hj, hk, ⟨w, hw, le_rfl⟩, rfl⟩ + have hW : Dominates W W := wire_dominates F e + have hl {m : ℕ} (hm : 0 < m) := Real.log_nonneg (by exact_mod_cast hm : 1 ≤ (m : ℝ)) + obtain ⟨_, hθ, hvar⟩ := partialRight_spec F e (hl hi) (hl hj) (hl hk) + have hd : 0 < d := (Nat.mul_pos hi hj).trans_le (le_max_left _ _) + have hd' : 1 ≤ (d : ℝ) := by exact_mod_cast hd + have hg' : (d : ℝ) ≤ g - d := by + have : 2 * (d : ℝ) ≤ g := by exact_mod_cast hg.le + linarith + obtain ⟨t, ht, hline⟩ := Speedup.gain_tangent hd' hg' hθ + have hρ : 0 < ρ := Real.exp_pos _ + have hq : 0 ≤ q := Nat.cast_nonneg _ + have htwo : 0 < Real.log 2 := Real.log_pos (by norm_num) + let s := q * t / ρ + have hs : 0 ≤ s := div_nonneg (mul_nonneg hq ht) hρ.le + have he : ρ * s = q * t := mul_div_cancel₀ _ hρ.ne' + let b := ((r : ℝ) - ρ - q * B) / ρ + Real.log ρ + s * θ + have hwlog (f : Point F) : s / Real.log 2 * Real.log (f W) = s * dist f (edge e).1 (edge e).2 + := by + change _ = s * (Real.log (f W) / Real.log 2) + ring + have hu (f : Point F) (hf : Monotone f) : Real.log (f A) + s / Real.log 2 * Real.log (f W) ≤ b + := by + let z := dist f (edge e).1 (edge e).2 + have h₁ := closure_grouped h le_rfl hd (show d < g by omega) f hf (edge_ne e) + have h₂ := mul_le_mul_of_nonneg_left (hline z) hq + have h₃ := Speedup.log_tangent hρ (zero_lt_one.trans_le (hA.one_le hf)) + change (f A : ℝ) + q * (((g : ℝ) - d) ^ z - (d : ℝ) ^ z) ≤ r at h₁ + change q * (B + t * (z - θ)) ≤ q * (((g : ℝ) - d) ^ z - (d : ℝ) ^ z) at h₂ + rw [hwlog] + change Real.log (f A) + s * z ≤ b + apply le_of_mul_le_mul_left _ hρ + unfold b + rw [mul_add, mul_add, mul_add, mul_div_cancel₀ _ hρ.ne', ← mul_assoc, ← mul_assoc, he] + linarith only [h₁, h₂, h₃] + obtain ⟨f, hf, hscore⟩ := vary_max F e (hl hi) (hl hj) (hl hk) hs + have hb := hA.line hW (div_nonneg hs htwo.le) hu hf + rw [tensor_price hf hi hj hk, Real.log_exp, hwlog, ← vary_score, hscore] at hb + have hh := (hvar _ hs).trans hb + rw [vary_zero] at hh + have hval : exponent F (Real.log i) (Real.log j) (Real.log k) = Real.log ρ := + (Real.log_exp _).symm + rw [hval] at hh + change Real.log ρ + s * θ ≤ ((r : ℝ) - ρ - q * B) / ρ + Real.log ρ + s * θ at hh + have h₀ : 0 ≤ ((r : ℝ) - ρ - q * B) / ρ := by linarith only [hh] + change ρ + q * B ≤ r + linarith only [(le_div_iff₀ hρ).mp h₀] + +theorem vary_congr {X Y : ℝ → ℝ → ℝ → ℝ} {a b c : ℝ} (e : Fin 3) + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) + (he : ∀ x y z, 0 ≤ x → 0 ≤ y → 0 ≤ z → X x y z = Y x y z) : + EqOn (vary X a b c e) (vary Y a b c e) (Ici 0) := by + intro t ht + fin_cases e + · exact he _ _ _ (add_nonneg ha ht) hb hc + · exact he _ _ _ ha (add_nonneg hb ht) hc + · exact he _ _ _ ha hb (add_nonneg hc ht) + +/-- Every one-sided partial derivative can replace the average +exponent. In particular one may take the largest of the three. -/ +theorem BorderRankLE.directional {F : Type*} [Field F] {i j k r g : ℕ} + {w : Fin i → Fin j → Fin k → F} (h : BorderRankLE w r) (hw : ∀ a b c, w a b c ≠ 0) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) (hg : 2 * largest i j k < g) (e : Fin 3) : + let d := largest i j k + let ρ := value F i j k + let θ := partialRight (exponent F) (Real.log i) (Real.log j) (Real.log k) e + HasDerivWithinAt (vary (exponent F) (Real.log i) (Real.log j) (Real.log k) e) θ (Ici 0) 0 ∧ + ρ + (⌊ρ / g⌋₊ : ℝ) * (((g : ℝ) - d) ^ θ - (d : ℝ) ^ θ) ≤ r := by + intro d ρ θ + obtain ⟨K, _, _, alg, u, hs, hu⟩ := h.small + have hw' (a b c) : u a b c ≠ 0 := fun he => hw a b c ((hs a b c).mp he) + have hl {m : ℕ} (hm : 0 < m) := Real.log_nonneg (by exact_mod_cast hm : 1 ≤ (m : ℝ)) + have he (a b c : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + exponent K a b c = exponent F a b c := by + rw [← exponent_extension K (AlgebraicClosure F) ha hb hc, + exponent_extension F (AlgebraicClosure F) ha hb hc] + have hv : value K i j k = ρ := congrArg Real.exp (he _ _ _ (hl hi) (hl hj) (hl hk)) + have heq := vary_congr e (hl hi) (hl hj) (hl hk) he + have hθ : partialRight (exponent K) (Real.log i) (Real.log j) (Real.log k) e = θ := + derivWithin_congr heq (heq (mem_Ici.mpr le_rfl)) + obtain ⟨hd, hpos, _⟩ := partialRight_spec K e (hl hi) (hl hj) (hl hk) + rw [hθ] at hd hpos + refine ⟨hd.congr_of_mem heq.symm (mem_Ici.mpr le_rfl), ?_⟩ + have hb := closure_directional hu hw' hi hj hk hg e + rw [hv, hθ] at hb + have hgd : (d : ℝ) ≤ g - d := by + have : 2 * (d : ℝ) ≤ g := by exact_mod_cast hg.le + linarith + have hcount := group_count (show 0 < ρ from Real.exp_pos _) (h.full hw hi hj hk) (by omega : 0 + < g) + have hgain := sub_nonneg.mpr (Real.rpow_le_rpow (Nat.cast_nonneg _) hgd hpos) + exact le_trans (add_le_add_right (mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hcount) hgain) ρ) hb + +theorem BorderRankLE.directional_benchmark {F : Type*} [Field F] {i j k r g : ℕ} + {w : Fin i → Fin j → Fin k → F} (h : BorderRankLE w r) (hw : ∀ a b c, w a b c ≠ 0) + (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + (hi : 0 < i) (hj : 0 < j) (hk : 0 < k) (hg : 2 * largest i j k < g) (e : Fin 3) : + let d := largest i j k + let ρ := Real.exp (U (Real.log i) (Real.log j) (Real.log k)) + let θ := partialRight U (Real.log i) (Real.log j) (Real.log k) e + HasDerivWithinAt (vary U (Real.log i) (Real.log j) (Real.log k) e) θ (Ici 0) 0 ∧ + ρ + (⌊ρ / g⌋₊ : ℝ) * (((g : ℝ) - d) ^ θ - (d : ℝ) ^ θ) ≤ r := by + have hl {m : ℕ} (hm : 0 < m) := Real.log_nonneg (by exact_mod_cast hm : 1 ≤ (m : ℝ)) + have he := vary_congr e (hl hi) (hl hj) (hl hk) (fun _ _ _ => all_shapes hr hs) + obtain ⟨hd, hb⟩ := h.directional hw hi hj hk hg e + have hθ : partialRight (exponent F) (Real.log i) (Real.log j) (Real.log k) e = + partialRight U (Real.log i) (Real.log j) (Real.log k) e := + derivWithin_congr he (he (mem_Ici.mpr le_rfl)) + rw [hθ] at hd hb + rw [value, all_shapes hr hs (hl hi) (hl hj) (hl hk)] at hb + exact ⟨hd.congr_of_mem he.symm (mem_Ici.mpr le_rfl), hb⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end + +section +/- +# Strict speedup and the square surplus + +If the asymptotic minimum exceeds every leg dimension, take a power +where it exceeds three times the largest dimension. At least one full +group then gives a strictly positive gain. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +variable {F : Type u} [Field F] {i j k r : ℕ} {w : Fin i → Fin j → Fin k → F} + +private theorem largest_power (i j k n : ℕ) : + largest (i ^ n) (j ^ n) (k ^ n) ≤ (largest i j k) ^ n := by + simp only [largest, ← mul_pow] + refine max_le ?_ (max_le ?_ ?_) <;> gcongr <;> omega + +theorem BorderRankLE.strict (h : BorderRankLE w r) (hw : ∀ a b c, w a b c ≠ 0) + (hvol : 1 < i * j * k) (hgap : (largest i j k : ℝ) < value F i j k) : + value F i j k < (r : ℝ) := by + have hi : 0 < i := Nat.pos_of_ne_zero (by rintro rfl; simp at hvol) + have hj : 0 < j := Nat.pos_of_ne_zero (by rintro rfl; simp at hvol) + have hk : 0 < k := Nat.pos_of_ne_zero (by rintro rfl; simp at hvol) + have hd : 0 < (largest i j k : ℝ) := by unfold largest; positivity + obtain ⟨n, hn⟩ := pow_unbounded_of_one_lt (3 : ℝ) ((one_lt_div hd).mpr hgap) + have hn₀ : n ≠ 0 := by rintro rfl; norm_num at hn + rw [div_pow, lt_div_iff₀ (pow_pos hd n), ← value_pow F hi hj hk] at hn + let d := largest (i ^ n) (j ^ n) (k ^ n) + let ρ := value F (i ^ n) (j ^ n) (k ^ n) + let a := slope F (i ^ n) (j ^ n) (k ^ n) + have hvol' : 1 < i ^ n * j ^ n * k ^ n := by rw [← mul_pow, ← mul_pow]; exact one_lt_pow₀ hvol hn₀ + have hd' : 0 < d := by unfold d largest; positivity + have hd₁ : 1 ≤ (d : ℝ) := by exact_mod_cast hd' + have hρ : 3 * (d : ℝ) < ρ := lt_of_le_of_lt + (mul_le_mul_of_nonneg_left (by exact_mod_cast largest_power i j k n) (by norm_num)) hn + have ha : 0 < a := by + apply div_pos (Real.log_pos (by linarith : 1 < ρ)) + exact Real.log_pos (by exact_mod_cast hvol') + have hw' : ∀ x y z, WPower w n x y z ≠ 0 := by + intro x y z + exact Finset.prod_ne_zero_iff.mpr (fun _ _ => hw _ _ _) + have he := BorderRankLE.grouped (h.pow n) hw' hvol' (show 2 * d < 3 * d by omega) + change ρ + (⌊ρ / (3 * d : ℕ)⌋₊ : ℝ) * + ((((3 * d : ℕ) : ℝ) - d) ^ a - (d : ℝ) ^ a) ≤ ((r ^ n : ℕ) : ℝ) at he + push_cast at he + have hfloor : 0 < ⌊ρ / (3 * (d : ℝ))⌋₊ := + (Nat.one_le_floor_iff _).mpr ((one_le_div (by positivity)).mpr hρ.le) + have hg : (d : ℝ) ^ a < (3 * d - (d : ℝ)) ^ a := + Real.rpow_lt_rpow (by positivity) (by linarith) ha + have hl : ρ < (r : ℝ) ^ n := (lt_add_of_pos_right _ (mul_pos (by positivity) (sub_pos.mpr + hg))).trans_le he + unfold ρ at hl + rw [value_pow F hi hj hk] at hl + exact (pow_lt_pow_iff_left₀ (hd.trans hgap).le (Nat.cast_nonneg _) hn₀).mp hl + +theorem square_value (F : Type*) [Field F] {s : ℕ} (hs : 0 < s) : + value F s s s = (s : ℝ) ^ MatrixExponent.omega F := + (ordinary_rank F hs hs hs).symm.trans (ordinary_square F hs) + +theorem square_slope (F : Type*) [Field F] {s : ℕ} (hs : 2 ≤ s) + (hω : MatrixExponent.omega F = 9 / 4) : slope F s s s = 3 / 4 := by + have hs' : 1 < (s : ℝ) := by exact_mod_cast hs + have hlog := Real.log_pos hs' + rw [slope, square_value F (by omega), hω, Real.log_rpow (by positivity), + Real.log_mul (by positivity) (by positivity), Real.log_mul (by positivity) (by positivity)] + field_simp + ring + +theorem square_border_surplus {K : ℕ → Type u} [∀ n, Field (K n)] + (hsq : ∀ n, MatrixExponent.omega (K n) = 9 / 4) + (w : ∀ n, Fin n → Fin n → Fin n → K n) (hw : ∀ n a b c, w n a b c ≠ 0) + (r : ℕ → ℕ) (hr : ∀ n, BorderRankLE (w n) (r n)) {c : ℝ} (hc : c < Speedup.cStar) : + ∀ᶠ s : ℕ in atTop, (s : ℝ) ^ (9 / 4 : ℝ) + c * (s : ℝ) ^ (7 / 4 : ℝ) ≤ r s := by + apply Speedup.square_limit _ hc + intro s g hs hg + have hd : largest s s s = s ^ 2 := by simp [largest, pow_two] + have hvol : 1 < s * s * s := by + rw [show s * s * s = s ^ 3 by ring] + exact one_lt_pow₀ (by omega) (by decide) + have he := BorderRankLE.grouped (hr s) (hw s) hvol (g := g) (by rwa [hd]) + simpa only [hd, Nat.cast_pow, square_value (K s) (by omega : 0 < s), + square_slope (K s) hs (hsq s), hsq s] using he + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sums/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sums/Model.lean new file mode 100644 index 0000000000..34c71db0af --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Sums/Model.lean @@ -0,0 +1,70 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.WeightedModel + +/-! +# A sum of independently weighted products + +The site order throughout is output, left input, right input. +The spectral tensor semiring uses direct sum and tensor product. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sums +open Spectral Filter + +/-- The data for the shape construction, including `i`, `j`, `k`, `hi`, `hj`. -/ +structure Shape where + /-- The `Shape` field of type `ℕ`. -/ + i : ℕ + /-- The `Shape` field of type `ℕ`. -/ + j : ℕ + /-- The `Shape` field of type `ℕ`. -/ + k : ℕ + hi : 0 < i + hj : 0 < j + hk : 0 < k + +/-- The indexing data represented by `Fin v.i → Fin v.j → Fin v.k → F`. -/ +abbrev Weights (F : Type) (v : Shape) := Fin v.i → Fin v.j → Fin v.k → F +/-- Computes the three by the application `Tensor F (Fin 3)`. -/ +abbrev Three (F : Type) [Field F] := Tensor F (Fin 3) + +variable {F : Type} [Field F] {n : ℕ} + +/-- The infimum of `{r : ℕ | A ≤ (r : Three F)}`. -/ +def rank (A : Three F) : ℕ := sInf {r : ℕ | A ≤ (r : Three F)} + +/-- The quantity computed by `limUnder atTop fun t : ℕ => (rank (A ^ t) : ℝ) ^ (t : ℝ)⁻¹`. -/ +def asymptotic (A : Three F) : ℝ := + limUnder atTop fun t : ℕ => (rank (A ^ t) : ℝ) ^ (t : ℝ)⁻¹ + +/-- The sum of `weightedTensor (w t)` indexed by `t`. -/ +def blocks (v : Fin n → Shape) (w : ∀ t, Weights F (v t)) : Three F := + ∑ t, weightedTensor (w t) + +/-- Evaluates `1` at the input `_ _ _ _`. -/ +def unweighted (F : Type) [Field F] (v : Fin n → Shape) : ∀ t, Weights F (v t) := + fun _ _ _ _ => 1 + +/-- The quantity computed by `-(∑ i, p i * Real.log (p i))`. -/ +def entropy (p : Fin n → ℝ) := -(∑ i, p i * Real.log (p i)) + +/-- The sum of `p i * Real.log (q (v i))` indexed by `i`. -/ +def mean (v : Fin n → Shape) (p : Fin n → ℝ) (q : Shape → ℕ) := + ∑ i, p i * Real.log (q (v i)) + +/-- The quantity computed by `entropy p + L (mean v p Shape.i) (mean v p Shape.j) (mean v p +Shape.k)`. -/ +def objective (L : ℝ → ℝ → ℝ → ℝ) (v : Fin n → Shape) (p : Fin n → ℝ) := + entropy p + L (mean v p Shape.i) (mean v p Shape.j) (mean v p Shape.k) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Sums diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Support.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Support.lean new file mode 100644 index 0000000000..89d01f1a80 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Support.lean @@ -0,0 +1,143 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldExtension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows + +/-! +# The spectral formula for the arithmetic exponent + +For a fixed integer format the tensor is the product of the three +wires. Rounding the dimensions up costs a factor of at most eight at +every spectral point. Strict spectral comparison and block recursion +turn a uniform spectral upper bound into an arithmetic one. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter Spectral +open scoped NNReal + +variable {F : Type} [Field F] {f : Point F} {a b c s : ℝ} + +private theorem rounded_wire (hf : Monotone f) {n : ℕ} (hn : 0 < n) (ha : 0 ≤ a) + (i j : Fin 3) : + (n : ℝ) ^ (a * dist f i j) ≤ f (Tensor.wire F i j (side n a)) ∧ + (f (Tensor.wire F i j (side n a)) : ℝ) ≤ 2 * (n : ℝ) ^ (a * dist f i j) := by + have he : (f (Tensor.wire F i j (side n a)) : ℝ) = (side n a : ℝ) ^ dist f i j := + Tensor.price_wire _ (mono_real hf) i j (side_pos hn a) + rw [he, Real.rpow_mul (by positivity)] + obtain ⟨hl, hu⟩ := dist_bounds hf i j + refine ⟨Real.rpow_le_rpow (by positivity) (Nat.le_ceil _) hl, ?_⟩ + calc + _ ≤ (2 * (n : ℝ) ^ a) ^ dist f i j := + Real.rpow_le_rpow (by positivity) (side_le hn ha) hl + _ = (2 : ℝ) ^ dist f i j * ((n : ℝ) ^ a) ^ dist f i j := + Real.mul_rpow (by norm_num) (by positivity) + _ ≤ _ := by + apply mul_le_mul_of_nonneg_right _ (by positivity) + simpa using Real.rpow_le_rpow_of_exponent_le (by norm_num : (1 : ℝ) ≤ 2) hu + +private theorem rounded_price (hf : Monotone f) {n : ℕ} (hn : 0 < n) + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + let M := tensor F (side n a) (side n b) (side n c) + (n : ℝ) ^ score f a b c ≤ f M ∧ (f M : ℝ) ≤ 8 * (n : ℝ) ^ score f a b c := by + have hn₀ : 0 < (n : ℝ) := by positivity + obtain ⟨la, ua⟩ := rounded_wire hf hn ha 0 1 + obtain ⟨lb, ub⟩ := rounded_wire hf hn hb 0 2 + obtain ⟨lc, uc⟩ := rounded_wire hf hn hc 1 2 + dsimp only + simp only [score, Real.rpow_add hn₀, tensor, f.map_mul, NNReal.coe_mul] + constructor + · gcongr + · calc + _ ≤ (2 * (n : ℝ) ^ (a * dist f 0 1)) * (2 * (n : ℝ) ^ (b * dist f 0 2)) * + (2 * (n : ℝ) ^ (c * dist f 1 2)) := by gcongr + _ = _ := by ring + +theorem score_le_exponent (hf : Monotone f) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + score f a b c ≤ exponent F a b c := by + by_contra! h + obtain ⟨n, r, hn, hr, hsave⟩ := (exponent_lt_iff_rank ha hb hc).mp h + have hn₀ : 0 < n := by omega + have he := hf ((tensor_le_iff (side_pos hn₀ a) (side_pos hn₀ b) (side_pos hn₀ c)).mpr hr) + rw [map_natCast] at he + exact hsave.not_ge ((rounded_price hf hn₀ ha hb hc).1.trans (by exact_mod_cast he)) + +theorem price_gap {s t : ℝ} (hs : 0 ≤ s) (hlt : s < t) : + ∃ n r : ℕ, 2 ≤ n ∧ 8 * (n : ℝ) ^ s < r ∧ (r : ℝ) < (n : ℝ) ^ t := by + have ht : Tendsto (fun n : ℕ => (n : ℝ) ^ (t - s)) atTop atTop := + (tendsto_rpow_atTop (sub_pos.mpr hlt)).comp tendsto_natCast_atTop_atTop + obtain ⟨n, hn, hp⟩ := ((eventually_ge_atTop 2).and (ht.eventually_gt_atTop 10)).exists + have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast (show 1 ≤ n by omega) + have h₁ := Real.one_le_rpow hn₁ hs + refine ⟨n, ⌈9 * (n : ℝ) ^ s⌉₊, hn, (lt_of_lt_of_le (by linarith) (Nat.le_ceil _)), ?_⟩ + calc + _ < 9 * (n : ℝ) ^ s + 1 := Nat.ceil_lt_add_one (by positivity) + _ ≤ 10 * (n : ℝ) ^ s := by linarith + _ < (n : ℝ) ^ (t - s) * (n : ℝ) ^ s := mul_lt_mul_of_pos_right hp (by positivity) + _ = _ := by rw [← Real.rpow_add (by positivity), sub_add_cancel] + +/-- A uniform rank bound on tensor powers absorbs its fixed overhead in the exponent. -/ +theorem exponent_le_of_rank_powers (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) (hs : 0 ≤ s) + (rankForPowers : ∀ (n r : ℕ), 2 ≤ n → 8 * (n : ℝ) ^ s < r → 0 < (r : ℝ) → + ∃ C : ℕ, ∀ p : ℕ, + RankLE F ((side n a) ^ p) ((side n b) ^ p) ((side n c) ^ p) (r ^ p * C)) : + exponent F a b c ≤ s := by + by_contra! hlt + obtain ⟨n, r, hn, hlo, hhi⟩ := price_gap hs hlt + have hr : 0 < (r : ℝ) := (by positivity : 0 ≤ 8 * (n : ℝ) ^ s).trans_lt hlo + obtain ⟨C, hC⟩ := rankForPowers n r hn hlo hr + obtain ⟨p, hp, hsave⟩ := absorb_overhead (D := C) hn hr hhi + exact lt_irrefl _ (exponent_lt_of_rank ha hb hc hp + ((hC p).cut (side_pow le_rfl p) (side_pow le_rfl p) (side_pow le_rfl p)) hsave) + +private theorem exponent_le_of_scores (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) (hs : 0 ≤ s) + (h : ∀ f : Point F, Monotone f → score f a b c ≤ s) : exponent F a b c ≤ s := by + refine exponent_le_of_rank_powers ha hb hc hs ?_ + intro n r hn hlo hr + have hn₀ : 0 < n := by omega + have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast hn₀ + have hne : (r : Tensor F (Fin 3)) ≠ 0 := by + intro he + have hh : r ≤ 0 := (Tensor.natCast_le_iff (K := F) (S := Fin 3) r 0).mp (by simp [he]) + exact hr.not_ge (by exact_mod_cast hh) + let M := tensor F (side n a) (side n b) (side n c) + have hp (f : Point F) (hf : Monotone f) : f M < f (r : Tensor F (Fin 3)) := by + rw [map_natCast] + apply NNReal.coe_lt_coe.mp + calc + (f M : ℝ) ≤ 8 * (n : ℝ) ^ score f a b c := (rounded_price hf hn₀ ha hb hc).2 + _ ≤ 8 * (n : ℝ) ^ s := + mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hn₁ (h f hf)) (by norm_num) + _ < _ := hlo + obtain ⟨C, hC⟩ := Spectrum.strictComparison Tensor.add_le_add_right Tensor.mul_le_mul_left + Tensor.zero_le Tensor.one_le Tensor.exists_bound hne hp + refine ⟨C, fun p => ?_⟩ + apply (tensor_le_iff (pow_pos (side_pos hn₀ a) p) (pow_pos (side_pos hn₀ b) p) + (pow_pos (side_pos hn₀ c) p)).mp + rw [tensor_power, Nat.cast_mul, Nat.cast_pow, mul_comm] + exact hC p + +/-- The exponent is a maximum, with no limit or closure in the set of prices. -/ +theorem support (F : Type) [Field F] : Support F (Prices F) := by + refine ⟨fun h => h.nonneg, ?_, ?_⟩ + · intro a b c x y z ha hb hc h + obtain ⟨f, hf, he⟩ := h.score (a := a) (b := b) (c := c) + exact he.trans_le (score_le_exponent hf ha hb hc) + · intro a b c ha hb hc + obtain ⟨f, hf, hmax⟩ := maximum_score F a b c + obtain ⟨x, y, z, hP, he⟩ := score_eq_load (a := a) (b := b) (c := c) hf + obtain ⟨hx, hy, hz⟩ := hP.nonneg + have h₀ : 0 ≤ score f a b c := by rw [← he, load]; positivity + exact ⟨x, y, z, hP, he.trans (le_antisymm (score_le_exponent hf ha hb hc) + (exponent_le_of_scores ha hb hc h₀ hmax))⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Threshold.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Threshold.lean new file mode 100644 index 0000000000..33e036ceb1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Threshold.lean @@ -0,0 +1,314 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Threshold.Model +public import Mathlib.Analysis.SpecialFunctions.Exp +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import Mathlib.Analysis.Calculus.DSlope +public import Mathlib.Analysis.SpecialFunctions.ExpDeriv + +/-! # Optimizing the amount trimmed from the logarithmic output lengths -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Threshold +open Real + +variable {b C u : ℝ} + +private theorem upper {v : ℝ} (hp : 0 ≤ b + C * v) (hf : b + C * u ≤ (b + C * v) * (1 + + (u - v) / 2)) : + gain b C u ≤ gain b C v := by + have h : max (b + C * u) 0 ≤ (b + C * v) * exp ((u - v) / 2) := + max_le (hf.trans (mul_le_mul_of_nonneg_left (by linarith [add_one_le_exp ((u - v) / 2)]) hp)) + (by positivity) + unfold gain + rw [max_eq_left hp] + calc + _ ≤ exp (-u) * ((b + C * v) * exp ((u - v) / 2)) ^ 2 / 4 := by gcongr + _ = _ := by + rw [mul_pow, ← exp_nat_mul, show (2 : ℕ) * ((u - v) / 2) = u - v by ring, + mul_left_comm, ← exp_add, show -u + (u - v) = -v by ring] + ring + +/-- The maximum includes the boundary case of no trimming. -/ +theorem maximum (b : ℝ) (hC : 0 < C) : + let v := max 0 (2 - b / C) + gain b C v = optimum b C ∧ IsGreatest {s | ∃ u : ℝ, 0 ≤ u ∧ gain b C u = s} (optimum b C) := by + let v := max 0 (2 - b / C) + have he : gain b C v = optimum b C ∧ ∀ u : ℝ, 0 ≤ u → gain b C u ≤ gain b C v := by + by_cases h : b ≤ 2 * C + · have hv : v = 2 - b / C := max_eq_right (sub_nonneg.mpr ((div_le_iff₀ hC).mpr h)) + have hp : b + C * v = 2 * C := by rw [hv]; field_simp; ring + refine ⟨?_, fun u _ => upper (by linarith) ?_⟩ + · rw [optimum, ite_eq_left h, gain, hp, max_eq_left (by positivity), hv, neg_sub] + ring + · rw [hp] + linarith + · have hv : v = 0 := max_eq_left (sub_nonpos.mpr ((le_div_iff₀ hC).mpr (le_of_not_ge h))) + rw [hv] + refine ⟨by simp [optimum, h, gain, show 0 ≤ b by + linarith], fun u hu => upper (by linarith) ?_⟩ + linarith [mul_le_mul_of_nonneg_right (le_of_not_ge h) hu] + exact ⟨he.1, ⟨v, le_max_left _ _, he.1⟩, fun _ ⟨u, hu, heq⟩ => heq ▸ (he.2 u hu).trans_eq he.1⟩ + +theorem square_optimum {a : ℝ} (ha : 0 < a) (he : a ≤ Real.sqrt (exp 1)) : + optimum (4 * log a) 1 = exp (-2) * a ^ 4 := by + have h := log_le_log ha he + rw [log_sqrt (by positivity), log_exp] at h + rw [optimum, ite_eq_left (by linarith), one_pow, one_mul, div_one] + rw [show 4 * log a - 2 = -2 + (4 : ℕ) * log a by ring, exp_add, exp_nat_mul, exp_log ha] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Threshold +end + +section +/- +# The harmonic threshold + +The logarithms of the outer lengths are trimmed by fixed amounts. +All three logarithms may have errors tending to zero, as happens +when rounding the lengths to integers. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter +open scoped Topology + +variable {x y s t b : ℝ} {k X Y Z : ℕ → ℝ} + +private theorem side_ratio (hk : Tendsto k atTop atTop) + (hX : Tendsto (fun n => X n - x * k n) atTop (𝓝 s)) : + Tendsto (fun n => X n / k n) atTop (𝓝 x) := by + have h := (hX.div_atTop hk).add_const x + rw [zero_add] at h + apply h.congr' + filter_upwards [hk.eventually_gt_atTop 0] with n hn + field_simp + ring + +/-- At inner exponent `xy`, the excess over output area is of order +`1/k` or smaller. The limit includes the untrimmed case. -/ +theorem shifted_threshold_limit (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hk : Tendsto k atTop atTop) + (hX : Tendsto (fun n => X n - x * k n) atTop (𝓝 (-s))) + (hY : Tendsto (fun n => Y n - y * k n) atTop (𝓝 (-t))) + (hZ : Tendsto (fun n => Z n - x * y * k n) atTop (𝓝 (b * (x * y)))) : + Tendsto (fun n => k n * (U (X n) (Y n) (Z n) - X n - Y n)) atTop + (𝓝 ((max (b + (y / x) * s + (x / y) * t) 0) ^ 2 / 4)) := by + have h₁ := side_ratio hk hX + have h₂ := side_ratio hk hY + have h₃ := side_ratio hk hZ + have hy' : y = 1 - x := by linarith + let p n := (X n + Y n) * Z n - X n * Y n + have hp : Tendsto (fun n => p n / k n) atTop (𝓝 ((x * y) * (b + (y / x) * s + (x / y) * t))) := by + have h := (((h₁.add h₂).mul hZ).add ((h₂.const_sub (x * y)).mul hX)).add + (hY.const_mul (x * y - x)) + rw [show (x + y) * (b * (x * y)) + (x * y - y) * (-s) + (x * y - x) * (-t) = (x * y) * (b + + (y / x) * s + (x / y) * t) by + field_simp; rw [hy']; ring] at h + apply h.congr' + filter_upwards [hk.eventually_gt_atTop 0] with n hn + unfold p + rw [hy'] + field_simp + ring + have h := ((hp.max (tendsto_const_nhds (x := (0 : ℝ)))).pow 2).div + (((h₁.const_mul 4).mul h₂).mul h₃) (by positivity) + let u := b + (y / x) * s + (x / y) * t + have he : max ((x * y) * u) 0 = (x * y) * max u 0 := by + rw [mul_max_of_nonneg _ _ (mul_pos hx hy).le, mul_zero] + rw [he, show ((x * y) * max u 0) ^ 2 / (4 * x * y * (x * y)) + = (max u 0) ^ 2 / 4 by field_simp] at h + apply h.congr' + have hzx : x * y < x := mul_lt_of_lt_one_right hx (by linarith) + have hzy : x * y < y := mul_lt_of_lt_one_left hy (by linarith) + filter_upwards [hk.eventually_gt_atTop 0, h₃.eventually_const_lt (mul_pos hx hy), + h₃.eventually_lt h₁ hzx, h₃.eventually_lt h₂ hzy] with n hn hz hx' hy'' + have hZ₀ : 0 < Z n := (div_pos_iff_of_pos_right hn).mp hz + have hZX := (div_lt_div_iff_of_pos_right hn).mp hx' + have hZY := (div_lt_div_iff_of_pos_right hn).mp hy'' + have hX₀ := hZ₀.trans hZX + have hY₀ := hZ₀.trans hZY + have hmax : max (p n / k n) 0 = max (p n) 0 / k n := by + simpa only [zero_div] using max_div_div_right hn.le (p n) 0 + dsimp only [Pi.div_apply] + rw [hmax, U, ite_eq_left (le_min hZX.le hZY.le), benchmark] + change _ = k n * (X n + Y n + (max (p n) 0) ^ 2 / (4 * X n * Y n * Z n) - X n - Y n) + field_simp + ring + +/-- The derivative of the exponential gives the same scaled limit even +when the excess vanishes infinitely often. -/ +theorem exp_shifted_threshold_limit (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hk : Tendsto k atTop atTop) + (hX : Tendsto (fun n => X n - x * k n) atTop (𝓝 (-s))) + (hY : Tendsto (fun n => Y n - y * k n) atTop (𝓝 (-t))) + (hZ : Tendsto (fun n => Z n - x * y * k n) atTop (𝓝 (b * (x * y)))) : + Tendsto (fun n => k n * (Real.exp (U (X n) (Y n) (Z n) - X n - Y n) - 1)) atTop + (𝓝 ((max (b + (y / x) * s + (x / y) * t) 0) ^ 2 / 4)) := by + let f n := U (X n) (Y n) (Z n) - X n - Y n + have h := shifted_threshold_limit hx hy hxy hk hX hY hZ + have hf : Tendsto f atTop (𝓝 0) := by + apply (h.div_atTop hk).congr' + filter_upwards [hk.eventually_gt_atTop 0] with n hn + exact mul_div_cancel_left₀ (f n) hn.ne' + have hd := (continuousAt_dslope_same.mpr (Real.hasDerivAt_exp 0).differentiableAt).tendsto.comp hf + have he (u : ℝ) : u * dslope Real.exp 0 u = Real.exp u - 1 := by + simpa only [sub_zero, smul_eq_mul, Real.exp_zero] using sub_smul_dslope Real.exp 0 u + simpa only [dslope_same, (Real.hasDerivAt_exp 0).deriv, Real.exp_zero, mul_one, + Function.comp_apply, f, mul_assoc, he] using h.mul hd + +/-- The quantity computed by `⌈Real.exp (-s) * (n : ℝ) ^ x⌉₊`. -/ +noncomputable def trimmed (n : ℕ) (x s : ℝ) : ℕ := ⌈Real.exp (-s) * (n : ℝ) ^ x⌉₊ + +@[simp] theorem trimmed_zero (n : ℕ) (x : ℝ) : trimmed n x 0 = side n x := by + simp [trimmed, side] + +theorem trimmed_pos {n : ℕ} (hn : 0 < n) (x s : ℝ) : 0 < trimmed n x s := + Nat.ceil_pos.mpr (by positivity) + +theorem trimmed_le (n : ℕ) (x : ℝ) (hs : 0 ≤ s) : trimmed n x s ≤ side n x := by + apply Nat.ceil_mono + exact mul_le_of_le_one_left (by positivity) (Real.exp_le_one_iff.mpr (neg_nonpos.mpr hs)) + +theorem log_trimmed (hx : 0 < x) (s : ℝ) : + Tendsto (fun n : ℕ => Real.log (trimmed n x s) - x * Real.log n) atTop (𝓝 (-s)) := by + have hn : Tendsto (fun n : ℕ => (n : ℝ) ^ x) atTop atTop := + (tendsto_rpow_atTop hx).comp tendsto_natCast_atTop_atTop + have h := ((tendsto_nat_ceil_mul_div_atTop (Real.exp_pos (-s)).le).comp hn).log + (Real.exp_ne_zero _) + rw [Real.log_exp] at h + apply h.congr' + filter_upwards [eventually_gt_atTop 0] with n hn' + change Real.log ((trimmed n x s : ℝ) / (n : ℝ) ^ x) = _ + have hp := trimmed_pos hn' x s + rw [Real.log_div (by positivity) (by positivity), Real.log_rpow (by positivity)] + +theorem log_side (hx : 0 < x) : + Tendsto (fun n : ℕ => Real.log (side n x) - x * Real.log n) atTop (𝓝 0) := by + simpa only [trimmed_zero, neg_zero] using log_trimmed hx 0 + +theorem log_area (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) : + Tendsto (fun n : ℕ => Real.log ((side n x : ℝ) * side n y) - Real.log n) atTop (𝓝 0) := by + have h := (log_side hx).add (log_side hy) + rw [add_zero] at h + apply h.congr' + filter_upwards [eventually_gt_atTop 0] with n hn + have h₁ := trimmed_pos hn x 0 + have h₂ := trimmed_pos hn y 0 + rw [trimmed_zero] at h₁ h₂ + rw [Real.log_mul (by positivity) (by positivity)] + linear_combination -(Real.log n) * hxy + +/-- Normalize by the untrimmed output area. This version allows arbitrary +sequences of logarithmic side lengths with the stipulated shifts. -/ +theorem shifted_surplus_limit (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hX : Tendsto (fun n => X n - x * Real.log n) atTop (𝓝 (-s))) + (hY : Tendsto (fun n => Y n - y * Real.log n) atTop (𝓝 (-t))) + (hZ : Tendsto (fun n => Z n - x * y * Real.log n) atTop (𝓝 (b * (x * y)))) : + Tendsto (fun n => (Real.exp (U (X n) (Y n) (Z n)) - Real.exp (X n + Y n)) * + Real.log ((side n x : ℝ) * side n y) / ((side n x : ℝ) * side n y)) atTop + (𝓝 (Real.exp (-s - t) * (max (b + (y / x) * s + (x / y) * t) 0) ^ 2 / 4)) := by + let D n := (side n x : ℝ) * side n y + have hk : Tendsto (fun n : ℕ => Real.log n) atTop atTop := + Real.tendsto_log_atTop.comp tendsto_natCast_atTop_atTop + have hd := log_area hx hy hxy + have hlog : Tendsto (fun n => Real.log (D n) / Real.log n) atTop (𝓝 1) := + side_ratio (x := 1) hk (by simpa only [one_mul] using hd) + have he : Tendsto (fun n => X n + Y n - Real.log (D n)) atTop (𝓝 (-s - t)) := by + have he' := (hX.add hY).sub hd + rw [sub_zero, ← sub_eq_add_neg] at he' + apply he'.congr' + filter_upwards [] with n + unfold D + linear_combination -(Real.log n) * hxy + have h := (he.rexp.mul (exp_shifted_threshold_limit hx hy hxy hk hX hY hZ)).mul hlog + rw [mul_one, ← mul_div_assoc] at h + apply h.congr' + filter_upwards [eventually_gt_atTop 1] with n hn + have hk₀ : 0 < Real.log (n : ℝ) := Real.log_pos (by exact_mod_cast hn) + have hD : 0 < D n := by + have hn' : 0 < n := by omega + have h₁ := trimmed_pos hn' x 0 + have h₂ := trimmed_pos hn' y 0 + rw [trimmed_zero] at h₁ h₂ + unfold D + positivity + change _ = (Real.exp _ - Real.exp _) * Real.log (D n) / D n + rw [Real.exp_sub, Real.exp_log hD, Real.exp_sub, Real.exp_sub, Real.exp_add] + field_simp + +theorem trimmed_shifted_surplus_limit (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + {inner : ℕ → ℕ} (hinner : Tendsto (fun n => Real.log (inner n) - x * y * Real.log n) atTop + (𝓝 (b * (x * y)))) (s t : ℝ) : + Tendsto (fun n : ℕ => + (Real.exp (U (Real.log (trimmed n x s)) (Real.log (trimmed n y t)) (Real.log (inner n))) - + (trimmed n x s : ℝ) * trimmed n y t) * + Real.log ((side n x : ℝ) * side n y) / ((side n x : ℝ) * side n y)) atTop + (𝓝 (Real.exp (-s - t) * (max (b + (y / x) * s + (x / y) * t) 0) ^ 2 / 4)) := by + apply (shifted_surplus_limit hx hy hxy (log_trimmed hx s) (log_trimmed hy t) hinner).congr' + filter_upwards [eventually_gt_atTop 0] with n hn + have h₁ := trimmed_pos hn x s + have h₂ := trimmed_pos hn y t + rw [Real.exp_add, Real.exp_log (by positivity), Real.exp_log (by positivity)] + +theorem Threshold.log_width (hx : 0 < x) (hy : 0 < y) {a : ℝ} (ha : 0 < a) : + Tendsto (fun n => Real.log (Threshold.width n x y a) - x * y * Real.log n) atTop + (𝓝 ((Real.log a / (x * y)) * (x * y))) := by + rw [div_mul_cancel₀ _ (by positivity)] + simpa only [trimmed, Threshold.width, neg_neg, Real.exp_log ha] using + log_trimmed (mul_pos hx hy) (-Real.log a) + +theorem threshold_limit (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hs : 0 ≤ s) (ht : 0 ≤ t) (hk : Tendsto k atTop atTop) + (hX : Tendsto (fun n => X n - x * k n) atTop (𝓝 (-s))) + (hY : Tendsto (fun n => Y n - y * k n) atTop (𝓝 (-t))) + (hZ : Tendsto (fun n => Z n - x * y * k n) atTop (𝓝 0)) : + Tendsto (fun n => k n * (U (X n) (Y n) (Z n) - X n - Y n)) atTop + (𝓝 (((y / x) * s + (x / y) * t) ^ 2 / 4)) := by + simpa only [zero_add, max_eq_left (by positivity : 0 ≤ (y / x) * s + (x / y) * t)] using + shifted_threshold_limit (b := 0) hx hy hxy hk hX hY (by simpa using hZ) + +theorem exp_threshold_limit (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hs : 0 ≤ s) (ht : 0 ≤ t) (hk : Tendsto k atTop atTop) + (hX : Tendsto (fun n => X n - x * k n) atTop (𝓝 (-s))) + (hY : Tendsto (fun n => Y n - y * k n) atTop (𝓝 (-t))) + (hZ : Tendsto (fun n => Z n - x * y * k n) atTop (𝓝 0)) : + Tendsto (fun n => k n * (Real.exp (U (X n) (Y n) (Z n) - X n - Y n) - 1)) atTop + (𝓝 (((y / x) * s + (x / y) * t) ^ 2 / 4)) := by + simpa only [zero_add, max_eq_left (by positivity : 0 ≤ (y / x) * s + (x / y) * t)] using + exp_shifted_threshold_limit (b := 0) hx hy hxy hk hX hY (by simpa using hZ) + +theorem surplus_limit (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hs : 0 ≤ s) (ht : 0 ≤ t) + (hX : Tendsto (fun n => X n - x * Real.log n) atTop (𝓝 (-s))) + (hY : Tendsto (fun n => Y n - y * Real.log n) atTop (𝓝 (-t))) + (hZ : Tendsto (fun n => Z n - x * y * Real.log n) atTop (𝓝 0)) : + Tendsto (fun n => (Real.exp (U (X n) (Y n) (Z n)) - Real.exp (X n + Y n)) * + Real.log ((side n x : ℝ) * side n y) / ((side n x : ℝ) * side n y)) atTop + (𝓝 (Real.exp (-s - t) * ((y / x) * s + (x / y) * t) ^ 2 / 4)) := by + simpa only [zero_add, max_eq_left (by positivity : 0 ≤ (y / x) * s + (x / y) * t)] using + shifted_surplus_limit (b := 0) hx hy hxy hX hY (by simpa using hZ) + +theorem trimmed_surplus_limit (hx : 0 < x) (hy : 0 < y) (hxy : x + y = 1) + (hs : 0 ≤ s) (ht : 0 ≤ t) : + Tendsto (fun n : ℕ => + (Real.exp (U (Real.log (trimmed n x s)) (Real.log (trimmed n y t)) (Real.log (side n (x * + y)))) - + (trimmed n x s : ℝ) * trimmed n y t) * + Real.log ((side n x : ℝ) * side n y) / ((side n x : ℝ) * side n y)) atTop + (𝓝 (Real.exp (-s - t) * ((y / x) * s + (x / y) * t) ^ 2 / 4)) := by + simpa only [zero_add, max_eq_left (by positivity : 0 ≤ (y / x) * s + (x / y) * t)] using + trimmed_shifted_surplus_limit (b := 0) hx hy hxy (inner := fun n + => side n (x * y)) (by simpa using log_side (mul_pos hx hy)) s t + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Threshold/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Threshold/Model.lean new file mode 100644 index 0000000000..9fcadc9ab7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Threshold/Model.lean @@ -0,0 +1,27 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.FiniteModel + +/-! # Scaling the inner dimension at the harmonic threshold -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Threshold + +/-- The quantity computed by `⌈a * (n : ℝ) ^ (x * y)⌉₊`. -/ +def width (n : ℕ) (x y a : ℝ) := ⌈a * (n : ℝ) ^ (x * y)⌉₊ + +/-- The quantity computed by `Real.exp (-u) * (max (b + C * u) 0) ^ 2 / 4`. -/ +def gain (b C u : ℝ) := Real.exp (-u) * (max (b + C * u) 0) ^ 2 / 4 + +/-- Returns `C ^ 2 * Real.exp (b / C - 2)` when `b ≤ 2 * C` holds, and `b ^ 2 / 4` otherwise. -/ +def optimum (b C : ℝ) := if b ≤ 2 * C then C ^ 2 * Real.exp (b / C - 2) else b ^ 2 / 4 + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Threshold diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Threshold/Square.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Threshold/Square.lean new file mode 100644 index 0000000000..6872b55061 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Threshold/Square.lean @@ -0,0 +1,61 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Surplus +public import Mathlib.Data.Nat.Sqrt + +/-! # Square output of side s and inner width proportional to its square root -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +private theorem half_side (s : ℕ) : side (s * s) (1 / 2) = s := by + rw [side, Nat.cast_mul, ← Real.sqrt_eq_rpow, Real.sqrt_mul_self (by positivity), Nat.ceil_natCast] + +private theorem half_width (s : ℕ) (a : ℝ) : + Threshold.width (s * s) (1 / 2) (1 / 2) a = ⌈a * Real.sqrt s⌉₊ := by + rw [Threshold.width, Nat.cast_mul, Real.rpow_mul (by positivity), + ← Real.sqrt_eq_rpow, ← Real.sqrt_eq_rpow, Real.sqrt_mul_self (by positivity)] + +/-- Restrict the scaled threshold to the subsequence of square sizes. +Away from this subsequence use arbitrary ordinary products. -/ +theorem square_threshold {K : ℕ → Type*} [∀ n, Field (K n)] {a : ℝ} + (ha : 0 < a) (ha' : a ≤ Real.sqrt (Real.exp 1)) + (hrig : ∀ n, Rigidity (K n)) (hsq : ∀ n, MatrixExponent.omega (K n) = 9 / 4) + (w : ∀ s, Fin s → Fin s → Fin ⌈a * Real.sqrt s⌉₊ → K s) + (hw : ∀ s i j k, w s i j k ≠ 0) (r : ℕ → ℕ) (hr : ∀ s, BorderRankLE (w s) (r s)) + {L : ℝ} (hL : L < Real.exp (-2) * a ^ 4) : + ∀ᶠ s : ℕ in atTop, L < ((r s : ℝ) - (s : ℝ) ^ 2) * Real.log ((s : ℝ) ^ 2) / (s : ℝ) ^ 2 := by + have he (n : ℕ) : ∃ (v : Fin (side n (1 / 2)) → Fin (side n (1 / 2)) → + Fin (Threshold.width n (1 / 2) (1 / 2) a) → K (Nat.sqrt n)) (p : ℕ), + (∀ i j k, v i j k ≠ 0) ∧ BorderRankLE v p ∧ (∀ s : ℕ, n = s * s → p = r s) := by + by_cases hn : ∃ s, n = s * s + · obtain ⟨s, rfl⟩ := hn + rw [half_side, half_width, Nat.sqrt_eq] + refine ⟨w s, r s, hw s, hr s, fun t ht => ?_⟩ + simpa using congrArg (fun n => r (Nat.sqrt n)) ht + · let v := ordinary (K (Nat.sqrt n)) (side n (1 / 2)) (side n (1 / 2)) (Threshold.width n (1 / + 2) (1 / 2) a) + exact ⟨v, rankW v, fun _ _ _ => one_ne_zero, (rankW_spec v).border, fun s h => (hn ⟨s, + h⟩).elim⟩ + choose v p hv hp heq using he + have hopt := Threshold.square_optimum ha ha' + have hh := scaled_border_surplus (by norm_num) (by norm_num) (by norm_num) ha + (fun n => hrig (Nat.sqrt n)) (fun n => hsq (Nat.sqrt n)) v hv p hp (L := L) (by + rw [show (Real.log a) / ((1 / 2 : ℝ) * (1 / 2)) = 4 * Real.log a by ring, min_self, + div_self (by norm_num : (1 / 2 : ℝ) ≠ 0), hopt] + exact hL) + obtain ⟨n, hn⟩ := eventually_atTop.mp hh + filter_upwards [eventually_ge_atTop n] with s hs + simpa only [normalized, half_side, heq _ s rfl, pow_two] + using hn (s * s) (hs.trans (Nat.le_mul_self s)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Gaps.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Gaps.lean new file mode 100644 index 0000000000..bddbd3ea74 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Gaps.lean @@ -0,0 +1,285 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Model +public import Mathlib.Data.Fin.Tuple.Basic + +/-! +# Restricting a public seed to finitely many outcomes + +A retained set of mass greater than two thirds still strictly +separates every correct input from every incorrect one. The weights +need not be normalized again. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open Finset +variable {ι X : Type*} + +open scoped Classical in +/-- The condition `∀ x, 2 / 3 ≤ ∑' i, if (accept i x ↔ good x) then w i else 0` on the specified +data. -/ +def Accurate (w : ι → ℝ) (accept : ι → X → Prop) (good : X → Prop) : Prop := + ∀ x, 2 / 3 ≤ ∑' i, if (accept i x ↔ good x) then w i else 0 + +open scoped Classical in +/-- The condition `∀ x y, good x → ¬good y → (∑ i ∈ S, if accept i y then w i else 0) < ∑ i ∈ S, +if accept i x then w i else 0` on the specified data. -/ +def Gap (w : ι → ℝ) (accept : ι → X → Prop) (good : X → Prop) (S : Finset ι) : Prop := + ∀ x y, good x → ¬good y → + (∑ i ∈ S, if accept i y then w i else 0) < ∑ i ∈ S, if accept i x then w i else 0 + +variable {w : ι → ℝ} {accept : ι → X → Prop} {good : X → Prop} + (hw : ∀ i, 0 ≤ w i) (hs : HasSum w 1) (ha : Accurate w accept good) + +include hw hs ha in +open scoped Classical in +private theorem mistake (S : Finset ι) (x : X) : + (∑ i ∈ S, if (accept i x ↔ good x) then 0 else w i) ≤ 1 / 3 := by + let f i := if (accept i x ↔ good x) then w i else 0 + have hf : Summable f := Summable.of_nonneg_of_le + (fun i => by unfold f; split <;> simp [hw]) + (fun i => by unfold f; split <;> simp [hw]) hs.summable + have he (i) : w i - f i = if (accept i x ↔ good x) then 0 else w i := by + unfold f; split <;> simp_all + have ht := hs.sub hf.hasSum + simp_rw [he] at ht + refine (sum_le_hasSum S (fun i _ => by split <;> simp [hw]) ht).trans ?_ + have hh : 2 / 3 ≤ ∑' i, f i := ha x + linarith + +include hw hs ha in +open scoped Classical in +theorem retained_gap (S : Finset ι) {x y : X} (hx : good x) (hy : ¬good y) : + (∑ i ∈ S, w i) - 2 / 3 ≤ + (∑ i ∈ S, if accept i x then w i else 0) - (∑ i ∈ S, if accept i y then w i else 0) := by + have h := mistake hw hs ha S x + have k := mistake hw hs ha S y + simp only [hx, iff_true] at h + simp only [hy, iff_false, ite_not] at k + have he : (∑ i ∈ S, if accept i x then w i else 0) + + (∑ i ∈ S, if accept i x then 0 else w i) = ∑ i ∈ S, w i := by + rw [← sum_add_distrib] + exact sum_congr rfl (fun i _ => by split <;> simp_all) + linarith + +include hw hs ha in +open scoped Classical in +theorem mass_gap (S : Finset ι) (hm : 2 / 3 < ∑ i ∈ S, w i) : Gap w accept good S := + fun _ _ hx hy => sub_pos.mp ((sub_pos.mpr hm).trans_le (retained_gap hw hs ha S hx hy)) + +include hw hs ha in +open scoped Classical in +theorem finite_gap [Fintype ι] : Gap w accept good univ := by + apply mass_gap hw hs ha + have hm := hs.tsum_eq + rw [tsum_fintype] at hm + rw [hm] + norm_num + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Acceptance by a finite family of paths + +A path is a conjunction on scalar coordinates. Both intermediate +registers and post-seed witnesses are existentially quantified. +A verifier is their finite disjunction. Its cost bounds the longest +path, even if a different path accepts each input. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +/-- The operand used in the `Verification` construction. -/ +inductive Operand (F : Type*) (n t : ℕ) + | scalar (a : F) + | input (i : Index n) + | aux (j : Fin t) + +/-- The quantity `Op` in the `Verification` construction. -/ +inductive Op + | add | sub | mul + +/-- The instruction used in the `Verification` construction. -/ +inductive Instruction (F : Type*) (n t : ℕ) + | eq (a b : Operand F n t) + | ne (a b : Operand F n t) + | op (f : Op) (a b c : Operand F n t) + | div (a b c : Operand F n t) + +/-- The data for the path construction, including `vars`, `code`. -/ +structure Path (F : Type*) (n : ℕ) where + /-- Stores the vars associated with this `Path`. -/ + vars : ℕ + /-- The encoding map carried by `Path`, with type `List (Instruction F n vars)`. -/ + code : List (Instruction F n vars) + +/-- Computes the verifier by the application `List (Path F n)`. -/ +abbrev Verifier (F : Type*) (n : ℕ) := List (Path F n) + +variable {F : Type*} {n t : ℕ} + +/-- In the case `.scalar a`, this construction gives `a`. -/ +def Operand.eval (x : Index n → F) (w : Fin t → F) : Operand F n t → F + | .scalar a => a + | .input i => x i + | .aux j => w j + +/-- In the case `.add`, this construction gives `a + b`. -/ +def Op.eval [Ring F] (f : Op) (a b : F) : F := + match f with + | .add => a + b + | .sub => a - b + | .mul => a * b + +variable [Field F] + +/-- In the case `.eq a b`, this construction gives `a.eval x w = b.eval x w`. -/ +def Instruction.holds (x : Index n → F) (w : Fin t → F) : Instruction F n t → Prop + | .eq a b => a.eval x w = b.eval x w + | .ne a b => a.eval x w ≠ b.eval x w + | .op f a b c => f.eval (a.eval x w) (b.eval x w) = c.eval x w + | .div a b c => b.eval x w ≠ 0 ∧ a.eval x w / b.eval x w = c.eval x w + +/-- The condition `∃ w, ∀ i ∈ p.code, i.holds x w` on the specified data. -/ +def Path.accept (p : Path F n) (x : Index n → F) : Prop := + ∃ w, ∀ i ∈ p.code, i.holds x w + +/-- The condition `∃ p ∈ A, p.accept x` on the specified data. -/ +def Verifier.accept (A : Verifier F n) (x : Index n → F) : Prop := + ∃ p ∈ A, p.accept x + +/-- The condition `∀ p ∈ A, (p.code.length : ℝ) ≤ c` on the specified data. -/ +def Verifier.cost (A : Verifier F n) (c : ℝ) : Prop := + ∀ p ∈ A, (p.code.length : ℝ) ≤ c + +private def Operand.names : Operand F n t → Finset (Index n) + | .input i => {i} + | _ => ∅ + +omit [Field F] in +private theorem Operand.read (a : Operand F n t) : + a.names.card ≤ 1 ∧ ∀ x y w, (∀ i ∈ a.names, x i = y i) → a.eval x w = a.eval y w := by + cases a <;> simp [names, eval] + +private theorem Instruction.read (a : Instruction F n t) : + ∃ W : Finset (Index n), W.card ≤ 3 ∧ + ∀ x y w, (∀ i ∈ W, x i = y i) → a.holds x w → a.holds y w := by + have pick (a b c : Operand F n t) : + ∃ W : Finset (Index n), W.card ≤ 3 ∧ ∀ x y w, (∀ i ∈ W, x i = y i) → + a.eval x w = a.eval y w ∧ b.eval x w = b.eval y w ∧ c.eval x w = c.eval y w := by + refine ⟨a.names ∪ b.names ∪ c.names, ?_, fun x y w h => ?_⟩ + · exact (Finset.card_union_le ..).trans (Nat.add_le_add + ((Finset.card_union_le ..).trans (Nat.add_le_add a.read.1 b.read.1)) c.read.1) + · exact ⟨a.read.2 _ _ _ (fun i hi => h i (by simp [hi])), + b.read.2 _ _ _ (fun i hi => h i (by simp [hi])), + c.read.2 _ _ _ (fun i hi => h i (by simp [hi]))⟩ + cases a with + | eq a b | ne a b => + obtain ⟨W, hW, h⟩ := pick a b b + refine ⟨W, hW, fun x y w he => ?_⟩ + simp only [holds, (h x y w he).1, (h x y w he).2.1, imp_self] + | op _ a b c | div a b c => + obtain ⟨W, hW, h⟩ := pick a b c + refine ⟨W, hW, fun x y w he => ?_⟩ + simp only [holds, (h x y w he).1, (h x y w he).2.1, (h x y w he).2.2, imp_self] + +private theorem read_code (p : List (Instruction F n t)) : + ∃ W : Finset (Index n), W.card ≤ 3 * p.length ∧ ∀ x y w, (∀ i ∈ W, x i = y i) → + ∀ i ∈ p, i.holds x w → i.holds y w := by + induction p with + | nil => exact ⟨∅, by simp, by simp⟩ + | cons a p ih => + obtain ⟨A, hA, ha⟩ := a.read + obtain ⟨B, hB, hb⟩ := ih + refine ⟨A ∪ B, (Finset.card_union_le ..).trans (by simp only [List.length_cons]; omega), ?_⟩ + intro x y w h i hi + rcases List.mem_cons.mp hi with rfl|hi + · exact ha _ _ _ (fun j hj => h j (Finset.mem_union_left _ hj)) + · exact hb _ _ _ (fun j hj => h j (Finset.mem_union_right _ hj)) _ hi + +/-- One accepting assignment continues to work on any change outside +the coordinates read by its path. -/ +theorem Verifier.read (A : Verifier F n) {c : ℝ} (hc : A.cost c) {x} (hx : A.accept x) : + ∃ W : Finset (Index n), (W.card : ℝ) ≤ 3 * c ∧ ∀ y, (∀ i ∈ W, x i = y i) → A.accept y := by + obtain ⟨p, hp, w, hw⟩ := hx + obtain ⟨W, hW, h⟩ := read_code p.code + refine ⟨W, ?_, fun y he => ⟨p, hp, w, fun i hi => h x y w he i hi (hw i hi)⟩⟩ + exact (show (W.card : ℝ) ≤ 3 * p.code.length by exact_mod_cast hW).trans + (mul_le_mul_of_nonneg_left (hc p hp) (by norm_num)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Finite arithmetic trees with equality branches + +The initial auxiliary coordinates are existential witnesses. Each +arithmetic operation appends a register. Division branches on a +zero denominator and appends a register only on success. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open scoped Classical in +/-- The tree used in the `Verification` construction. -/ +inductive Tree (F : Type*) (n : ℕ) : ℕ → Type _ + | yes {t} : Tree F n t + | no {t} : Tree F n t + | test {t} (a b : Operand F n t) (equal unequal : Tree F n t) : Tree F n t + | op {t} (f : Op) (a b : Operand F n t) (next : Tree F n (t + 1)) : Tree F n t + | divide {t} (a b : Operand F n t) (next : Tree F n (t + 1)) (failure : Tree F n t) : Tree F n t + +variable {F : Type*} {n t : ℕ} + +open scoped Classical in +/-- In the case `.scalar a`, this construction gives `.scalar a`. -/ +def Operand.raise : Operand F n t → Operand F n (t + 1) + | .scalar a => .scalar a + | .input i => .input i + | .aux j => .aux j.castSucc + +open scoped Classical in +@[simp] theorem Operand.eval_raise (a : Operand F n t) (x : Index n → F) (w : Fin (t + 1) → F) : + a.raise.eval x w = a.eval x (Fin.init w) := by + cases a <;> rfl + +open scoped Classical in +/-- In the case `.yes | .no`, this construction gives `0`. -/ +def Tree.depth {t : ℕ} : Tree F n t → ℕ + | .yes | .no => 0 + | .test _ _ u v => max u.depth v.depth + 1 + | .op _ _ _ u => u.depth + 1 + | .divide _ _ u v => max u.depth v.depth + 1 + +variable [Field F] + +open scoped Classical in +/-- In the case `.yes, _, _`, this construction gives `True`. -/ +def Tree.run {t : ℕ} : Tree F n t → (Index n → F) → (Fin t → F) → Prop + | .yes, _, _ => True + | .no, _, _ => False + | .test a b u v, x, w => if a.eval x w = b.eval x w then u.run x w else v.run x w + | .op f a b u, x, w => u.run x (Fin.snoc w (f.eval (a.eval x w) (b.eval x w))) + | .divide a b u v, x, w => if b.eval x w = 0 then v.run x w + else u.run x (Fin.snoc w (a.eval x w / b.eval x w)) + +open scoped Classical in +/-- The condition `∃ w, u.run x w` on the specified data. -/ +def Tree.accept (u : Tree F n t) (x : Index n → F) := ∃ w, u.run x w + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Cuts.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Cuts.lean new file mode 100644 index 0000000000..33b8ef2509 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Cuts.lean @@ -0,0 +1,832 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Jacobian +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.RingTheory.Localization.AsSubring +public import Mathlib.FieldTheory.IsAlgClosed.Basic +public import Mathlib.RingTheory.Ideal.GoingUp +public import Mathlib.RingTheory.IntegralClosure.IsIntegralClosure.Basic +public import Mathlib.Algebra.MvPolynomial.Eval +public import Mathlib.RingTheory.Ideal.MinimalPrime.Basic +public import Mathlib.RingTheory.MvPolynomial.Basic +public import Mathlib.Algebra.Module.Submodule.Union +public import Mathlib.RingTheory.Ideal.MinimalPrime.Noetherian +public import Mathlib.RingTheory.KrullDimension.Polynomial +public import Mathlib.RingTheory.KrullDimension.Field +public import Mathlib.RingTheory.Ideal.KrullsHeightTheorem +public import Mathlib.FieldTheory.IntermediateField.Adjoin.Algebra +public import Mathlib.FieldTheory.Minpoly.Field +public import Mathlib.RingTheory.FiniteType +public import Mathlib.RingTheory.Nullstellensatz + +/-! +# Localizing a normalized affine parameter line + +A point of a larger subring selects the prime on the normalization. +If the inverse of an element of the larger ring belongs to the +localization, clearing its denominator and evaluating at the point +shows that its numerator is also invertible there. +-/ + +universe u + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +variable {K E : Type*} [Field K] [Field E] [Algebra K E] + (B D : Subalgebra K E) [IsFractionRing B E] [IsDedekindDomain B] + +theorem local_branch (fg : B.FG) (h : B ≤ D) (δ : D →ₐ[K] K) + (t : B) (hne : t ≠ 0) (hz : δ (Subalgebra.inclusion h t) = 0) : + ∃ b : Branch K E (t : E), ∃ l : D ≤ b.ring, ∀ x : D, b.res ⟨x.val, l x.property⟩ = δ x := by + let f := Subalgebra.inclusion h + let ψ := δ.comp f + let P := RingHom.ker ψ + have : P.IsPrime := RingHom.ker_isPrime _ + have hP : P ≠ ⊥ := by + intro hh + have ht : t ∈ P := hz + rw [hh] at ht + exact hne ht + let A := Localization.subalgebra.ofField E P.primeCompl P.primeCompl_le_nonZeroDivisors + let O := A.restrictScalars K + have : IsFractionRing O E := inferInstanceAs (IsFractionRing A E) + have : IsDiscreteValuationRing O := + IsLocalization.AtPrime.isDiscreteValuationRing_of_dedekind_domain B hP A + have lift : B ≤ O := fun x hx => A.algebraMap_mem (⟨x, hx⟩ : B) + let g := Subalgebra.inclusion lift + have units : ∀ x : P.primeCompl, IsUnit (ψ x.val) := fun x => isUnit_iff_ne_zero.mpr x.property + let φ : O →ₐ[K] K := (IsLocalization.liftAlgHom units : A →ₐ[K] K) + have restrict (x : B) : φ (g x) = ψ x := IsLocalization.lift_eq (S := A) units x + have ne (b : B) (hb : ψ b ≠ 0) : (b : E) ≠ 0 := by + intro he + exact hb (by rw [show b = 0 from Subtype.ext he, map_zero]) + have inv (b : B) (hb : ψ b ≠ 0) : (b : E)⁻¹ ∈ O := + ⟨1, b, hb, by simp⟩ + have fraction (x : E) (hx : x ∈ O) : ∃ a b : B, ψ b ≠ 0 ∧ x = (a : E) / (b : E) := by + obtain ⟨a, b, hb, he⟩ := hx + exact ⟨a, b, hb, he.trans (div_eq_mul_inv ..).symm⟩ + have gen : ∃ S : Subalgebra K E, S.FG ∧ S ≤ O ∧ + ∀ x : O, ∃ a b : S, (b : E)⁻¹ ∈ O ∧ (x : E) = (a : E) / (b : E) := by + refine ⟨B, fg, lift, fun x => ?_⟩ + obtain ⟨a, b, hb, he⟩ := fraction x.val x.property + exact ⟨a, b, inv b hb, he⟩ + have le : D ≤ O := by + intro x hx + by_cases he : x = 0 + · rw [he]; exact O.zero_mem + rcases mem_or_inv O x with hin | hin + · exact hin + obtain ⟨a, b, hb, hfrac⟩ := fraction _ hin + have heq : x * (a : E) = b := by + rw [← (eq_div_iff (ne b hb)).mp hfrac, ← mul_assoc, mul_inv_cancel₀ he, one_mul] + have eq : (⟨x, hx⟩ : D) * f a = f b := Subtype.ext heq + have hg : ψ a ≠ 0 := by + intro hn + apply hb + change δ (f b) = 0 + rw [← eq, map_mul, show δ (f a) = 0 from hn, mul_zero] + rw [(eq_div_iff (ne a hg)).mpr heq, div_eq_mul_inv] + exact O.mul_mem (lift b.property) (inv a hg) + have he (x : D) : φ ⟨x.val, le x.property⟩ = δ x := by + obtain ⟨a, b, hb, hx⟩ := fraction _ (le x.property) + have eq := (eq_div_iff (ne b hb)).mp hx + have hx₁ : (⟨x.val, le x.property⟩ : O) * g b = g a := Subtype.ext eq + have hx₂ : x * f b = f a := Subtype.ext eq + apply mul_right_cancel₀ hb + calc + _ = ψ a := by rw [← restrict, ← map_mul, hx₁, restrict] + _ = _ := by change δ (f a) = δ x * δ (f b); rw [← map_mul, hx₂] + have ht : g t ≠ 0 := fun he => hne (Subtype.ext (congrArg (fun x : O => x.val) he)) + exact ⟨discreteBranch O φ (g t) ht ((restrict t).trans hz) gen, le, he⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +section +/- # Extending rational points to the integral closure -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +private theorem extend_integral {K R S : Type*} [Field K] [IsAlgClosed K] + [CommRing R] [CommRing S] [Algebra K R] [Algebra K S] [Algebra R S] + [IsScalarTower K R S] [FaithfulSMul R S] [Algebra.IsIntegral R S] + (δ : R →ₐ[K] K) : ∃ φ : S →ₐ[K] K, ∀ x, φ (algebraMap R S x) = δ x := by + have : (RingHom.ker δ).IsMaximal := RingHom.ker_isMaximal_of_surjective δ + (fun a => ⟨algebraMap K R a, δ.commutes a⟩) + obtain ⟨I, hI, ho⟩ := Ideal.exists_maximal_ideal_liesOver_of_isIntegral (S := S) (RingHom.ker δ) + let q := Ideal.Quotient.mkₐ K I + have h (x : R) : algebraMap K (S ⧸ I) (δ x) = q (algebraMap R S x) := by + rw [← q.commutes, IsScalarTower.algebraMap_apply K R S] + apply Ideal.Quotient.eq.mpr + rw [← map_sub] + change _ ∈ Ideal.under R I + rw [← (Ideal.liesOver_iff _ _).mp ho] + simp + have : Algebra.IsIntegral K (S ⧸ I) := ⟨by + intro y + obtain ⟨x, rfl⟩ := Ideal.Quotient.mk_surjective y + exact IsIntegral.map_of_comp_eq δ.toRingHom q.toRingHom (RingHom.ext h) + (Algebra.IsIntegral.isIntegral x)⟩ + let f : (S ⧸ I) →ₐ[K] K := IsAlgClosed.lift + exact ⟨f.comp q, fun x => by rw [AlgHom.comp_apply, ← h, f.commutes]; rfl⟩ + +/-- Every rational point of the subalgebra extends over its integral closure. -/ +theorem extend_point {K E : Type*} [Field K] [Field E] [Algebra K E] [IsAlgClosed K] + (R : Subalgebra K E) (δ : R →ₐ[K] K) : + ∃ φ : ((integralClosure R E).restrictScalars K) →ₐ[K] K, + ∀ (x : R) (hx : (x : E) ∈ integralClosure R E), φ ⟨x.val, hx⟩ = δ x := by + obtain ⟨φ, hφ⟩ := extend_integral (S := integralClosure R E) δ + exact ⟨φ, fun x _ => hφ x⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +section +/- # A branch of the deformation curve at the prescribed point -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +/-- Normalize over the parameter, then choose the prime below a point +on the integral closure of the affine algebra. This works even when +the original point is singular. -/ +theorem exists_branch {K E : Type*} [Field K] [Field E] [Algebra K E] [CharZero K] [IsAlgClosed K] + (R : Subalgebra K E) [IsFractionRing R E] (fg : R.FG) (δ : R →ₐ[K] K) + (t : R) (ht : t ≠ 0) (hδ : δ t = 0) + (alg : Algebra.IsAlgebraic (IntermediateField.adjoin K {(t : E)}) E) : + ∃ b : Branch K E (t : E), ∃ h : R ≤ b.ring, ∀ a : R, b.res ⟨a.val, h a.property⟩ = δ a := by + let D := (integralClosure R E).restrictScalars K + have hR : R ≤ D := fun x hx => isIntegral_algebraMap (R := R) (A := E) (x := ⟨x, hx⟩) + obtain ⟨B, hB, inc, mem, frac, ded⟩ := curve R fg t alg + obtain ⟨φ, hφ⟩ := extend_point R δ + let x : B := ⟨t.val, mem⟩ + have hx : x ≠ 0 := fun hn => ht (Subtype.ext (congrArg (fun x : B => x.val) hn)) + have hz : φ (Subalgebra.inclusion inc x) = 0 := (hφ t _).trans hδ + obtain ⟨b, hb, h⟩ := local_branch B D hB inc φ x hx hz + exact ⟨b, hR.trans hb, fun a => (h ⟨a.val, hR a.property⟩).trans (hφ a _)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Isolation at a rational point of affine space -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +variable {K : Type*} {σ : Type} [Field K] + +/-- Computes the max point by the application `RingHom.ker (eval x)`. -/ +abbrev maxPoint (x : σ → K) : Ideal (MvPolynomial σ K) := RingHom.ker (eval x) + +/-- Requires `maxPoint x ∈ I.minimalPrimes`. -/ +def Isolated (x : σ → K) (I : Ideal (MvPolynomial σ K)) : Prop := maxPoint x ∈ I.minimalPrimes + +/-- The sum of `C (a i : K) * y i` indexed by `i`. -/ +def comb {B : Type} [Fintype B] (y : B → MvPolynomial σ K) (a : B → ℚ) := + ∑ i, C (a i : K) * y i + +/-- The quantity computed by `X (.inl i) - C (β i)`. -/ +def offset {Z W : Type} (β : Z → K) (i : Z) : MvPolynomial (Z ⊕ W) K := X (.inl i) - C (β i) + +/-- Transforms the indexed data by `⨆ j, (I j).map (rename (Sum.map id (Sigma.mk j)))`. -/ +def diagonalIdeal {J Z : Type} {W : J → Type} (I : ∀ j, Ideal (MvPolynomial (Z ⊕ W j) K)) : + Ideal (MvPolynomial (Z ⊕ (Σ j, W j)) K) := + ⨆ j, (I j).map (rename (Sum.map id (Sigma.mk j))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Rational cuts avoiding finitely many minimal primes -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +variable {K : Type*} [Field K] [CharZero K] {B σ : Type} [Fintype B] + (y : B → MvPolynomial σ K) + +omit [CharZero K] in +open scoped Classical in +theorem comb_mem (a : B → ℚ) : comb y a ∈ Ideal.span (Set.range y) := by + exact Submodule.sum_mem _ (fun i _ => Ideal.mul_mem_left _ _ (Ideal.subset_span ⟨i, rfl⟩)) + +open scoped Classical in +private def bad (P : Ideal (MvPolynomial σ K)) : Submodule ℚ (B → ℚ) where + carrier := {a | comb y a ∈ P} + zero_mem' := by simp [comb] + add_mem' := by + intro a b ha hb + change comb y (a + b) ∈ P + simpa only [comb, Pi.add_apply, Rat.cast_add, map_add, add_mul, Finset.sum_add_distrib] + using P.add_mem ha hb + smul_mem' := by + intro c a ha + change comb y (c • a) ∈ P + simpa only [comb, Pi.smul_apply, smul_eq_mul, Rat.cast_mul, map_mul, mul_assoc, Finset.mul_sum] + using P.mul_mem_left (C (c : K)) ha + +omit [CharZero K] in +open scoped Classical in +private theorem coeff_one (i : B) : comb y (fun j => if j = i then 1 else 0) = y i := by + unfold comb + rw [Finset.sum_eq_single i] + · simp + · intro j _ hj; simp [hj] + · simp + +open scoped Classical in +theorem avoid [Finite σ] {I m : Ideal (MvPolynomial σ K)} + (h : m ∈ (I ⊔ Ideal.span (Set.range y)).minimalPrimes) : + ∃ a, ∀ P ∈ I.minimalPrimes, P < m → comb y a ∉ P := by + let t := {P | P ∈ I.minimalPrimes ∧ P < m} + have : Finite ↥t := + (I.finite_minimalPrimes_of_isNoetherianRing.subset + (fun P (h : P ∈ t) => h.1)).to_subtype + have hb (P : t) : bad y P.val ≠ ⊤ := by + intro e + have hs : Ideal.span (Set.range y) ≤ P.val := by + apply Ideal.span_le.mpr + rintro _ ⟨i, rfl⟩ + rw [← coeff_one y i] + change (fun j => if j = i then 1 else 0) ∈ bad y P.val + rw [e]; exact Submodule.mem_top + exact P.2.2.not_ge (h.2 ⟨P.2.1.1.1, sup_le P.2.1.1.2 hs⟩ P.2.2.le) + have : Infinite ℚ := Infinite.of_injective (fun n : ℕ => (n : ℚ)) Nat.cast_injective + obtain ⟨a, ha⟩ := Submodule.exists_forall_notMem_of_forall_ne_top (fun P : t => bad y P.val) hb + exact ⟨a, fun P hp hm => ha ⟨P, hp, hm⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Isolating a point by rational combinations of given equations + +One cut removes all positive-dimensional components through the +chosen point. The length of every chain remaining below it drops +by at least one. Applied to the zero ideal this gives a square +system of equations. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +variable {K : Type*} [Field K] [CharZero K] {σ B : Type} [Fintype σ] [Fintype B] + (x : σ → K) (y : B → MvPolynomial σ K) +local notation "m" => maxPoint x +local notation "Y" => Ideal.span (Set.range y) + +open scoped Classical in +private theorem span_cons {A R : Type*} [CommRing R] {d : ℕ} (f : A → R) (a : A) (b : Fin d → A) : + Ideal.span (Set.range (f ∘ Fin.cons a b)) = Ideal.span {f a} ⊔ Ideal.span (Set.range (f ∘ b)) + := by + rw [Set.range_comp, Set.range_comp, Fin.range_cons, Set.image_insert_eq, Ideal.span_insert] + +open scoped Classical in +omit [Fintype σ] in +theorem cut [Finite σ] {I : Ideal (MvPolynomial σ K)} (h : Isolated x (I ⊔ Y)) {d : ℕ} + (hd : ∀ p, I ≤ p → ¬Chain p m (d + 1)) : + ∃ A : Fin d → B → ℚ, Isolated x (I ⊔ Ideal.span (Set.range (fun t => comb y (A t)))) := by + let : Fintype σ := Fintype.ofFinite σ + induction d generalizing I with + | zero => + refine ⟨Fin.elim0, ?_⟩ + rw [Set.range_eq_empty, Ideal.span_empty, sup_bot_eq] + refine ⟨⟨h.1.1, le_sup_left.trans h.1.2⟩, ?_⟩ + intro p hp hm + by_contra hn + exact hd p hp.2 (.cons hp.1 (lt_of_le_not_ge hm hn) (.nil h.1.1 le_rfl)) + | succ d ih => + obtain ⟨a, ha⟩ := avoid y h + let J := I ⊔ Ideal.span {comb y a} + have he : J ⊔ Y = I ⊔ Y := by + rw [show J = _ from rfl, sup_assoc, sup_eq_right.mpr (Ideal.span_singleton_le_iff_mem _ + |>.mpr (comb_mem y a))] + have short (p : Ideal (MvPolynomial σ K)) (hp : J ≤ p) (hc : Chain p m (d + 1)) : False := by + have := hc.prime + obtain ⟨q, hq, hle⟩ := Ideal.exists_minimalPrimes_le (le_sup_left.trans hp : I ≤ p) + have hlt : q < p := lt_of_le_of_ne hle fun eq => + ha q hq (hle.trans_lt hc.lt) (by + rw [eq] + exact (le_sup_right.trans hp : Ideal.span {comb y a} ≤ p) (Ideal.subset_span rfl)) + exact hd q hq.1.2 (.cons hq.1.1 hlt hc) + obtain ⟨A, hA⟩ := ih (he.symm ▸ h) short + refine ⟨Fin.cons a A, ?_⟩ + change Isolated x (I ⊔ Ideal.span (Set.range (comb y ∘ Fin.cons a A))) + rw [span_cons, ← sup_assoc] + exact hA + +omit [CharZero K] in +open scoped Classical in +theorem point_height_le : (m).height ≤ Fintype.card σ := by + have : (m).IsPrime := RingHom.ker_isPrime _ + have h := Ideal.height_le_ringKrullDim_of_isPrime (I := m) + rw [MvPolynomial.ringKrullDim_of_isNoetherianRing, ringKrullDim_eq_zero_of_field, zero_add, + ENat.card_eq_coe_fintype_card] at h + exact_mod_cast h + +open scoped Classical in +omit [Fintype σ] in +theorem square_system [Finite σ] (h : Isolated x Y) : + ∃ A : σ → B → ℚ, Isolated x (Ideal.span (Set.range (fun j => comb y (A j)))) := by + let : Fintype σ := Fintype.ofFinite σ + have short (p : Ideal (MvPolynomial σ K)) (_ : ⊥ ≤ p) (hc : Chain p m (Fintype.card σ + + 1)) : False := by + have ht := hc.length_le.trans (point_height_le x) + exact Nat.not_succ_le_self _ (ENat.natCast_le_natCast.mp ht) + obtain ⟨A, hA⟩ := cut x y (I := ⊥) (by rwa [bot_sup_eq]) short + let e := Fintype.equivFin σ + refine ⟨A ∘ e, ?_⟩ + rw [bot_sup_eq] at hA + change Isolated x (Ideal.span (Set.range ((fun j => comb y (A j)) ∘ e))) + rwa [Set.range_comp, e.surjective.range_eq, Set.image_univ] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Transferring isolation to extended coefficients and to separate coordinates -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +variable {K : Type*} {σ : Type} [Field K] + +/-- Every ideal fixing all coordinates contains the evaluation kernel. -/ +theorem point_le (x : σ → K) (P : Ideal (MvPolynomial σ K)) + (h : ∀ i, X i - C (x i) ∈ P) : maxPoint x ≤ P := by + let q := Ideal.Quotient.mk P + have e : q = (q.comp C).comp (eval x) := by + apply MvPolynomial.ringHom_ext + · intro r + simp + · intro i + simp only [RingHom.comp_apply, eval_X] + exact Ideal.Quotient.eq.mpr (h i) + intro p hp + change eval x p = 0 at hp + apply Ideal.Quotient.eq_zero_iff_mem.mp + change q p = 0 + rw [e, RingHom.comp_apply, hp, map_zero] + +/-- An isolated rational point remains isolated under a field extension. -/ +theorem Isolated.map {L : Type*} [Field L] {x : σ → K} {I : Ideal (MvPolynomial σ K)} + (h : Isolated x I) (f : K →+* L) : Isolated (f ∘ x) (I.map (MvPolynomial.map f)) := by + refine ⟨⟨RingHom.ker_isPrime _, Ideal.map_le_iff_le_comap.mpr ?_⟩, ?_⟩ + · intro p hp + change eval (f ∘ x) (MvPolynomial.map f p) = 0 + have hx : eval x p = 0 := h.1.2 hp + rw [← map_eval, hx, map_zero] + · intro P hP hle + have : P.IsPrime := hP.1 + have hp : maxPoint x ≤ P.comap (MvPolynomial.map f) := by + apply h.2 ⟨Ideal.comap_isPrime _ _, Ideal.map_le_iff_le_comap.mp hP.2⟩ + intro p hm + have hz : eval (f ∘ x) (MvPolynomial.map f p) = 0 := hle hm + change eval x p = 0 + apply f.injective + rw [map_eval, hz, map_zero] + apply point_le + intro i + have hm : X i - C (x i) ∈ maxPoint x := by simp [maxPoint] + have hz : MvPolynomial.map f (X i - C (x i)) ∈ P := hp hm + simpa using hz + +variable {J Z : Type} {W : J → Type} + +/-- Equality of a repeated coordinate with its value in the reference block. -/ +def difference (j₀ : J) (p : {j // j ≠ j₀} × Z) : MvPolynomial (Σ j, Z ⊕ W j) K := + X ⟨p.1.1, Sum.inl p.2⟩ - X ⟨j₀, Sum.inl p.2⟩ + +/-- Replace a shared block of coordinates by separate copies, imposing equality to one copy. -/ +theorem Isolated.separate {β : Z → K} {w : ∀ j, W j → K} + {I : ∀ j, Ideal (MvPolynomial (Z ⊕ W j) K)} + (h : Isolated (Sum.elim β (fun x => w x.1 x.2)) (diagonalIdeal I)) (j₀ : J) : + Isolated (fun x : (Σ j, Z ⊕ W j) => Sum.elim β (w x.1) x.2) + ((⨆ j, (I j).map (rename (@Sigma.mk J (fun k => Z ⊕ W k) j))) ⊔ + Ideal.span (Set.range (difference j₀))) := by + let x : Z ⊕ (Σ j, W j) → K := Sum.elim β (fun a => w a.1 a.2) + let y : (Σ j, Z ⊕ W j) → K := fun a => Sum.elim β (w a.1) a.2 + let s : Z ⊕ (Σ j, W j) → (Σ j, Z ⊕ W j) := + Sum.elim (fun z => ⟨j₀, .inl z⟩) (fun a => ⟨a.1, .inr a.2⟩) + have he : y ∘ s = x := by funext a; cases a <;> rfl + refine ⟨⟨RingHom.ker_isPrime _, sup_le (iSup_le fun j => ?_) (Ideal.span_le.mpr ?_)⟩, ?_⟩ + · apply Ideal.map_le_iff_le_comap.mpr + intro p hp + have hblock : (I j).map (rename (Sum.map id (Sigma.mk j))) ≤ diagonalIdeal I := + le_iSup (fun k => (I k).map (rename (Sum.map id (Sigma.mk k)))) j + have hz : eval x (rename (Sum.map id (Sigma.mk j)) p) = 0 := + h.1.2 (hblock (Ideal.mem_map_of_mem _ hp)) + have hem : y ∘ Sigma.mk j = x ∘ Sum.map id (Sigma.mk j) := by + funext a; cases a <;> rfl + change eval y (rename (Sigma.mk j) p) = 0 + rwa [eval_rename, hem, ← eval_rename] + · rintro _ ⟨a, rfl⟩ + change eval y (difference j₀ a) = 0 + simp [difference, y] + · intro P hP hle + have : P.IsPrime := hP.1 + have hd (j : J) (z : Z) : + X ⟨j, Sum.inl z⟩ - X ⟨j₀, Sum.inl z⟩ ∈ P := by + by_cases hj : j = j₀ + · subst j; simp + · exact (le_sup_right.trans hP.2) (Ideal.subset_span ⟨(⟨j, hj⟩, z), rfl⟩) + have hs : diagonalIdeal I ≤ P.comap (rename s) := by + refine iSup_le fun j => Ideal.map_le_iff_le_comap.mpr ?_ + intro p hp + let q := Ideal.Quotient.mk P + have heq : (q.comp (rename s).toRingHom).comp + (rename (Sum.map id (Sigma.mk j))).toRingHom = + q.comp (rename (Sigma.mk j)).toRingHom := by + apply MvPolynomial.ringHom_ext + · intro r; simp + · rintro (z | v) + · simpa [s] using (Ideal.Quotient.eq.mpr (hd j z)).symm + · simp [s] + have hj : (I j).map (rename (@Sigma.mk J (fun k => Z ⊕ W k) j)) ≤ P := + (iSup_le_iff.mp (le_sup_left.trans hP.2)) j + change rename s (rename (Sum.map id (Sigma.mk j)) p) ∈ P + apply Ideal.Quotient.eq_zero_iff_mem.mp + exact (RingHom.congr_fun heq p).trans + (Ideal.Quotient.eq_zero_iff_mem.mpr (hj (Ideal.mem_map_of_mem _ hp))) + have hm : maxPoint x ≤ P.comap (rename s) := by + apply h.2 ⟨Ideal.comap_isPrime _ _, hs⟩ + intro p hp + have hz : eval y (rename s p) = 0 := hle hp + rwa [eval_rename, he] at hz + have hh (i : Z ⊕ (Σ j, W j)) : X (s i) - C (x i) ∈ P := by + have hz : rename s (X i - C (x i)) ∈ P := hm (by simp [maxPoint]) + simpa using hz + apply point_le + rintro ⟨j, z | v⟩ + · simpa [s, x] using P.add_mem (hd j z) (hh (.inl z)) + · exact hh (.inr ⟨j, v⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Height of a rational point by successively evaluating its coordinates -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial Finset + +variable {K : Type*} [Field K] {σ : Type} (x : σ → K) + +open scoped Classical in +private def fixAt (s : Finset σ) : MvPolynomial σ K →ₐ[K] MvPolynomial σ K := + aeval (fun j => if j ∈ s then C (x j) else X j) + +open scoped Classical in +private theorem fix_insert (s : Finset σ) (i : σ) (hi : i ∉ s) : + RingHom.ker (fixAt x s) < RingHom.ker (fixAt x (insert i s)) := by + let a := fixAt x s + let b := fixAt x (insert i s) + have he : b.comp a = b := by + apply algHom_ext + intro j + by_cases h : j ∈ s <;> simp [a, b, fixAt, h] + refine lt_of_le_of_ne ?_ ?_ + · intro z hz + change a z = 0 at hz + change b z = 0 + rw [← he, AlgHom.comp_apply, hz, map_zero] + · intro h + have hz : X i - C (x i) ∈ RingHom.ker b := by simp [b, fixAt] + rw [show RingHom.ker b = RingHom.ker a from h.symm] at hz + have ha : X i - C (x i) = (0 : MvPolynomial σ K) := by simpa [a, fixAt, hi] using hz + have := congrArg (eval (fun _ => x i + 1)) ha + simp at this + +open scoped Classical in +theorem height_maxPoint [Fintype σ] : (Fintype.card σ : ℕ∞) ≤ (maxPoint x).height := by + have bound (s : Finset σ) : (s.card : ℕ∞) ≤ (RingHom.ker (fixAt x s)).height := by + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi ih => + have lt := fix_insert x s i hi + let _ := RingHom.ker_isPrime (fixAt x s) + let _ := RingHom.ker_isPrime (fixAt x (insert i s)) + rw [card_insert_of_notMem hi, Nat.cast_add, Nat.cast_one] + exact (add_le_add_left ih _).trans (Ideal.height_add_one_le_of_lt_of_isPrime lt) + have eq : (aeval x).comp (fixAt x univ) = aeval x := by + apply algHom_ext + intro i + simp [fixAt] + refine (bound univ).trans (Ideal.height_mono ?_) + intro z hz + change fixAt x univ z = 0 at hz + change aeval x z = 0 + rw [← eq, AlgHom.comp_apply, hz, map_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Perturbing a square system at an isolated point + +Add one variable and subtract a multiple of it from each equation. +No minimal prime through the given point can contain the new variable. +Otherwise isolation in the original fiber forces that prime to equal +the maximal ideal, whose height exceeds the number of equations. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial +variable {K : Type*} [Field K] {σ : Type} (G : σ → MvPolynomial σ K) (c : σ → K) + +open scoped Classical in +/-- The quantity computed by `rename some (G i) - X none * C (c i)`. -/ +def perturb (i : σ) : MvPolynomial (Option σ) K := + rename some (G i) - X none * C (c i) + +open scoped Classical in +/-- Computes the fixed zero by the application `i.elim 0 x`. -/ +def fixedZero (x : σ → K) (i : Option σ) := i.elim 0 x + +open scoped Classical in +theorem perturb_prime [Finite σ] {x : σ → K} (hx : Isolated x (Ideal.span (Set.range G))) : + ∃ P : Ideal (MvPolynomial (Option σ) K), P.IsPrime ∧ P ≤ maxPoint (fixedZero x) ∧ + (∀ i, perturb G c i ∈ P) ∧ X none ∉ P := by + let : Fintype σ := Fintype.ofFinite σ + let z := fixedZero x + let M := maxPoint z + let I := Ideal.span (Set.range (perturb G c)) + have h : I ≤ M := by + refine Ideal.span_le.mpr ?_ + rintro _ ⟨i, rfl⟩ + have hg : eval x (G i) = 0 := hx.1.2 (Ideal.subset_span ⟨i, rfl⟩) + change eval z (perturb G c i) = 0 + simp [perturb, eval_rename, z, fixedZero, Function.comp_def, hg] + have : M.IsPrime := RingHom.ker_isPrime _ + obtain ⟨P, hP, hm⟩ := Ideal.exists_minimalPrimes_le h + have : P.IsPrime := hP.1.1 + have hs i : perturb G c i ∈ P := hP.1.2 (Ideal.subset_span ⟨i, rfl⟩) + refine ⟨P, hP.1.1, hm, hs, fun ht => ?_⟩ + let Q := P.comap (rename some) + have he : Ideal.span (Set.range G) ≤ Q := by + refine Ideal.span_le.mpr ?_ + rintro _ ⟨i, rfl⟩ + change rename some (G i) ∈ P + simpa [perturb] using P.add_mem (hs i) (P.mul_mem_right (C (c i)) ht) + have hle : Q ≤ maxPoint x := by + intro q hq + have hh : eval z (rename some q) = 0 := hm hq + rw [eval_rename] at hh + exact hh + have inv := hx.2 ⟨Ideal.comap_isPrime _ _, he⟩ hle + have eq : M ≤ P := by + apply point_le + rintro (_|i) + · simpa [z, fixedZero] using ht + · have hp : rename some (X i - C (x i)) ∈ P := inv (by simp [maxPoint]) + simpa [z, fixedZero] using hp + have lower := (height_maxPoint z).trans (Ideal.height_mono eq) + have upper := Ideal.height_le_ncard_of_mem_minimalPrimes_span (Set.finite_range _) hP + have small : (Set.range (perturb G c)).ncard ≤ Fintype.card σ := by + simpa using Set.ncard_image_le (f := perturb G c) (s := Set.univ) + have le : Fintype.card (Option σ) ≤ Fintype.card σ := by + exact_mod_cast (lower.trans upper).trans (show (_ : ℕ∞) + ≤ Fintype.card σ by exact_mod_cast small) + rw [Fintype.card_option] at le + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # The function field of a component of the perturbed system -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial +variable {K E : Type u} [Field K] [Field E] [Algebra K E] {σ : Type} + +open scoped Classical in +theorem transcendental_of_residue (R : Subalgebra K E) (f : R →ₐ[K] K) + (t : R) (hn : t ≠ 0) (hz : f t = 0) : Transcendental K (t : E) := by + intro h + let p := minpoly K (t : E) + have ht : Polynomial.aeval t p = 0 := by + apply Subtype.ext + change R.val (Polynomial.aeval t p) = 0 + rw [← Polynomial.aeval_algHom_apply] + exact minpoly.aeval _ _ + have hp := congrArg f ht + rw [← Polynomial.aeval_algHom_apply, hz, map_zero] at hp + have he : p.coeff 0 = 0 := by + rw [Polynomial.coeff_zero_eq_eval_zero] + simpa using hp + exact minpoly.coeff_zero_ne_zero h.isIntegral (fun h => hn (Subtype.ext h)) he + +open scoped Classical in +/-- The data for the deformation construction, including `E`, `[field`, `[alg`, `ring`, +`[fraction`. -/ +structure Deformation (G : σ → MvPolynomial σ K) (c x : σ → K) where + /-- The type of edges. -/ + E : Type u + [field : Field E] + [alg : Algebra K E] + /-- The `Deformation` component of type `Subalgebra K E`. -/ + ring : Subalgebra K E + [fraction : IsFractionRing ring E] + fg : ring.FG + /-- The `Deformation` component of type `ring →ₐ[K] K`. -/ + res : ring →ₐ[K] K + /-- The `Deformation` component of type `ring`. -/ + t : ring + nonzero : t ≠ 0 + zero : res t = 0 + /-- The `Deformation` component of type `σ → ring`. -/ + y : σ → ring + point : ∀ i, res (y i) = x i + ray : ∀ i, aeval (fun j => (y j : E)) (G i) = (t : E) * algebraMap K E (c i) + generates : IntermediateField.adjoin K (insert (t : E) (Set.range (fun i => (y i : E)))) = ⊤ + +attribute [instance] Deformation.field Deformation.alg Deformation.fraction + +open scoped Classical in +private theorem generates {ι : Type} (f : MvPolynomial ι K →ₐ[K] E) [IsFractionRing f.range E] : + IntermediateField.adjoin K (Set.range (f ∘ X)) = ⊤ := by + have h : f.range ≤ (IntermediateField.adjoin K (Set.range (f ∘ X))).toSubalgebra := by + have := IntermediateField.algebra_adjoin_le_adjoin K (Set.range (f ∘ X)) + rwa [Algebra.adjoin_range_eq_range_aeval, ← aeval_unique f] at this + apply top_unique + intro z _ + obtain ⟨a, b, _, rfl⟩ := IsFractionRing.div_surjective f.range z + exact IntermediateField.div_mem _ (h a.property) (h b.property) + +open scoped Classical in +private theorem generated {ι : Type} [Finite ι] (f : MvPolynomial ι K →ₐ[K] E) : f.range.FG := by + let s := Set.range (f ∘ X) + have hs : s.Finite := Set.finite_range _ + refine ⟨hs.toFinset, ?_⟩ + rw [Set.Finite.coe_toFinset, show s = Set.range (f ∘ X) from rfl, + Algebra.adjoin_range_eq_range_aeval, ← aeval_unique f] + +open scoped Classical in +theorem exists_deformation [Finite σ] (G : σ → MvPolynomial σ K) (c x : σ → K) + (h : Isolated x (Ideal.span (Set.range G))) : Nonempty (Deformation G c x) := by + classical + let : Fintype σ := Fintype.ofFinite σ + obtain ⟨P, hP, hm, hs, ht⟩ := perturb_prime G c h + have : P.IsPrime := hP + let A := MvPolynomial (Option σ) K ⧸ P + let E := FractionRing A + let f := (IsScalarTower.toAlgHom K A E).comp (Ideal.Quotient.mkₐ K P) + have ker (z : MvPolynomial (Option σ) K) : f z = 0 ↔ z ∈ P := by + change algebraMap A E (Ideal.Quotient.mk P z) = 0 ↔ _ + rw [← map_zero (algebraMap A E), (IsFractionRing.injective A E).eq_iff, + Ideal.Quotient.eq_zero_iff_mem] + have hf : IsFractionRing f.range E := by + apply IsFractionRing.of_field + intro z + obtain ⟨a, b, _, rfl⟩ := IsFractionRing.div_surjective A z + obtain ⟨a, rfl⟩ := Ideal.Quotient.mkₐ_surjective K P a + obtain ⟨b, rfl⟩ := Ideal.Quotient.mkₐ_surjective K P b + exact ⟨f.rangeRestrict a, f.rangeRestrict b, rfl⟩ + let _ := hf + let z := fixedZero x + have he : RingHom.ker f.rangeRestrict.toRingHom ≤ RingHom.ker (aeval z).toRingHom := by + intro g hg + exact hm ((ker g).mp (congrArg Subtype.val hg)) + let δ := f.rangeRestrict.liftOfSurjective f.rangeRestrict_surjective (aeval z) he + let y (i : Option σ) := f.rangeRestrict (X i) + have hd i : δ (y i) = z i := by simp [δ, y] + refine ⟨{ E := E + ring := f.range + fg := generated f + res := δ + t := y none + nonzero := fun he => ht ((ker _).mp (congrArg Subtype.val he)) + zero := hd none + y := y ∘ some + point := fun i => hd (some i) + ray := ?_ + generates := ?_ }⟩ + · intro i + have hi := (ker _).mpr (hs i) + rw [aeval_unique f, perturb, map_sub, map_mul, aeval_X, aeval_C, aeval_rename, sub_eq_zero] + at hi + exact hi + · have eq : Set.range (f ∘ X) = insert (y none : E) (Set.range (fun i => (y (some i) : E))) := by + ext t + constructor + · rintro ⟨_|i, rfl⟩ + · exact .inl rfl + · exact .inr ⟨i, rfl⟩ + · rintro (rfl|⟨i, rfl⟩) + · exact ⟨none, rfl⟩ + · exact ⟨some i, rfl⟩ + exact eq ▸ generates f + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Isolation from finite witness fibers and a unique common output + +Each coordinate has finitely many possible values. Its split +annihilating polynomial belongs to every prime over the equations. +At the specified point only one linear factor can vanish. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial +variable {K : Type*} [Field K] + +open scoped Classical in +private theorem isolate_coordinates [IsAlgClosed K] {σ : Type} [Finite σ] + {I : Ideal (MvPolynomial σ K)} {x : σ → K} (hx : I ≤ maxPoint x) + (h : ∀ i, ∃ s : Finset K, ∀ y : σ → K, I ≤ maxPoint y → y i ∈ s) : + Isolated x I := by + refine ⟨⟨RingHom.ker_isPrime _, hx⟩, fun P hP hle => point_le x P fun i => ?_⟩ + have : P.IsPrime := hP.1 + obtain ⟨s, hs⟩ := h i + have hp : ∏ a ∈ s, (X i - C a) ∈ P := by + rw [← MvPolynomial.IsPrime.vanishingIdeal_zeroLocus (K:=K) P] + intro y hy + have ht : I ≤ maxPoint y := fun p hm => hy p (hP.2 hm) + rw [map_prod] + exact Finset.prod_eq_zero (hs y ht) (by simp) + obtain ⟨a, _, ha⟩ := Ideal.IsPrime.prod_mem_iff.mp hp + have he : x i = a := by simpa [maxPoint, sub_eq_zero] using hle ha + rwa [he] + +variable {J Z : Type} {W : J → Type} + (I : ∀ j, Ideal (MvPolynomial (Z ⊕ W j) K)) + +open scoped Classical in +private theorem diagonal_eval (y : Z ⊕ (Σ j, W j) → K) : + diagonalIdeal I ≤ maxPoint y ↔ ∀ j, I j ≤ + maxPoint (Sum.elim (y ∘ Sum.inl) (fun a => y (.inr ⟨j, a⟩))) := by + have he (j : J) : (maxPoint y).comap (rename (Sum.map id (Sigma.mk j))) = + maxPoint (Sum.elim (y ∘ Sum.inl) (fun a => y (.inr ⟨j, a⟩))) := by + have e : y ∘ Sum.map id (Sigma.mk j) = Sum.elim (y ∘ Sum.inl) (fun a => y (.inr ⟨j, a⟩)) := by + funext i; cases i <;> rfl + ext p + change eval y (rename _ p) = 0 ↔ eval _ p = 0 + rw [eval_rename, e] + simp only [diagonalIdeal, iSup_le_iff, Ideal.map_le_iff_le_comap, he] + +open scoped Classical in +theorem isolate_family [IsAlgClosed K] [Finite J] [Finite Z] [∀ j, Finite (W j)] + (β : Z → K) (w : ∀ j, W j → K) (hw : ∀ j, I j ≤ maxPoint (Sum.elim β (w j))) + (hf : ∀ j, Set.Finite {y : W j → K | I j ≤ maxPoint (Sum.elim β y)}) + (hu : ∀ z, (∀ j, ∃ y : W j → K, I j ≤ maxPoint (Sum.elim z y)) → z = β) : + Isolated (Sum.elim β (fun x => w x.1 x.2)) (diagonalIdeal I) ∧ + ∀ j, Isolated (Sum.elim β (w j)) (I j ⊔ Ideal.span (Set.range (offset β))) := by + let : ∀ j : J, Fintype (W j) := fun j => Fintype.ofFinite (W j) + let : Fintype J := Fintype.ofFinite J + let : Fintype Z := Fintype.ofFinite Z + have witness (j : J) (a : W j) : + ∃ s : Finset K, ∀ y, I j ≤ maxPoint (Sum.elim β y) → y a ∈ s := + ⟨(hf j).toFinset.image (fun y => y a), fun y hy => + Finset.mem_image.mpr ⟨y, (hf j).mem_toFinset.mpr hy, rfl⟩⟩ + constructor + · have out (y : Z ⊕ (Σ j, W j) → K) (hy : diagonalIdeal I ≤ maxPoint y) : + y ∘ Sum.inl = β := + hu _ (fun j => ⟨_, (diagonal_eval I y).mp hy j⟩) + let x : Z ⊕ (Σ j, W j) → K := Sum.elim β (fun x => w x.1 x.2) + have he : diagonalIdeal I ≤ maxPoint x := (diagonal_eval I x).mpr hw + refine isolate_coordinates he ?_ + rintro (i | ⟨j, a⟩) + · exact ⟨{β i}, fun y hy => Finset.mem_singleton.mpr (congrFun (out y hy) i)⟩ + · obtain ⟨s, hs⟩ := witness j a + refine ⟨s, fun y hy => hs (fun b => y (.inr ⟨j, b⟩)) ?_⟩ + rw [← out y hy] + exact (diagonal_eval I y).mp hy j + · intro j + let A := I j ⊔ Ideal.span (Set.range (offset β)) + have hit : A ≤ maxPoint (Sum.elim β (w j)) := by + refine sup_le (hw j) (Ideal.span_le.mpr ?_) + rintro _ ⟨i, rfl⟩ + simp [maxPoint, offset] + have out (y : Z ⊕ W j → K) (hy : A ≤ maxPoint y) (i : Z) : y (.inl i) = β i := by + have he := (le_sup_right.trans hy) (Ideal.subset_span ⟨i, rfl⟩) + simpa [maxPoint, offset, sub_eq_zero] using he + apply isolate_coordinates hit + rintro (i|a) + · exact ⟨{β i}, fun y hy => Finset.mem_singleton.mpr (out y hy i)⟩ + · obtain ⟨s, hs⟩ := witness j a + refine ⟨s, fun y hy => hs (y ∘ Sum.inr) ?_⟩ + have he : Sum.elim β (y ∘ Sum.inr) = y := by + funext b + cases b with + | inl i => exact (out y hy i).symm + | inr v => rfl + rw [he] + exact le_sup_left.trans hy + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Energy.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Energy.lean new file mode 100644 index 0000000000..70eef40db3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Energy.lean @@ -0,0 +1,272 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Root +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Multi.Radial + +/-! # Variational bounds for the tripod -/ + +@[expose] public section + +section +/- # The variational energy near an axis -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +open Minimum Profile + +variable {D : Vec → ℝ} {P : PairPrices} {v : Vec} {R : Vec → ℝ} {i j k : Fin 3} + +private theorem Root.upper (h : Root D v R P) (hv : Positive v) (hij : i ≠ j) + (hik : i ≠ k) (hjk : j ≠ k) (x : Vec) (hx : Positive x) : + R x ≤ intercept P (opposite v) (criticalWidth v) i + + Profile.residual D v i * Real.log (x i / criticalWidth v i) + + (v j)⁻¹ * Real.log (x j + x i) + (v k)⁻¹ * Real.log (x k + x i) := by + have hu := critical_pos hv + have hd := opposite_pos hv + have h₁ := (h.family.envelope hu hd hij (hx i) (hx j)).2 + have h₂ := (h.family.envelope hu hd hik (hx i) (hx k)).2 + apply le_of_mul_le_mul_left _ (hd i) + refine (h.chord _ _ _ hij hik hjk x hx).trans ?_ + refine (add_le_add (mul_le_mul_of_nonneg_left h₁ (inv_pos.mpr (hv j)).le) + (mul_le_mul_of_nonneg_left h₂ (inv_pos.mpr (hv k)).le)).trans_eq ?_ + unfold model Profile.residual + rw [opposite_eq v hij hik hjk] + ring + +private theorem near_cost (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) (r : ℝ) (x : Vec) : + cost (near i r / v) x = (v i)⁻¹ * x i + r * (v j)⁻¹ * x j + r * (v k)⁻¹ * x k := by + change mass _ = _ + rw [mass_eq _ hij hik hjk] + simp only [Pi.div_apply, near, ite_true, ite_eq_right hij.symm, ite_eq_right hik.symm, + div_eq_mul_inv, one_mul] + +private theorem scaled_max {u a b x : ℝ} (hu : 0 < u) (ha : 0 < a) (hb : 0 < b) (hx : 0 < x) : + b * Real.log (x / u) - a * x ≤ b * Real.log (b / (a * u)) - b := by + rw [Real.log_div hx.ne' hu.ne', ← div_div, Real.log_div (div_pos hb ha).ne' hu.ne'] + linarith only [log_max hb ha hx] + +private theorem unit_max {r x : ℝ} (hr : 0 < r) (hx : 0 < x) : + Real.log x - r * x ≤ -Real.log r - 1 := by + simpa only [one_mul, one_div, Real.log_inv] using log_max zero_lt_one hr hx + +theorem Root.axis_upper (h : Root D v R P) (hv : Positive v) (i : Fin 3) + (hb : 0 < Profile.residual D v i) {r : ℝ} (hr : 0 < r) (ha : 0 < (v i)⁻¹ - r * opposite v i) : + variational R (D v⁻¹) (near i r / v) + opposite v i * Real.log r ≤ + intercept P (opposite v) (criticalWidth v) i + Profile.residual D v i * + Real.log (Profile.residual D v i / (((v i)⁻¹ - r * opposite v i) * criticalWidth v i)) := by + let j := i + 1 + let k := i + 2 + have hij : i ≠ j := by unfold j; omega + have hik : i ≠ k := by unfold k; omega + have hjk : j ≠ k := by unfold j k; omega + apply le_sub_iff_add_le.mp + apply variational_le + intro x hx + have h₁ := scaled_max (critical_pos hv i) ha hb (hx i) + have h₂ := mul_le_mul_of_nonneg_left (unit_max hr (add_pos (hx j) (hx i))) (inv_pos.mpr (hv j)).le + have h₃ := mul_le_mul_of_nonneg_left (unit_max hr (add_pos (hx k) (hx i))) (inv_pos.mpr (hv k)).le + have hu := h.upper hv hij hik hjk x hx + rw [near_cost hij hik hjk] + simp only [Profile.residual, opposite_eq v hij hik hjk] at hu h₁ ⊢ + linarith only [hu, h₁, h₂, h₃] + +theorem Root.axis_lower (h : Root D v R P) (hv : Positive v) (i : Fin 3) + (hb : 0 < Profile.residual D v i) {r : ℝ} (hr : 0 < r) : + axisValue D v P i - r * (v (i + 2))⁻¹ * (Profile.residual D v i * v i) ≤ + variational R (D v⁻¹) (near i r / v) + opposite v i * Real.log r := by + let j := i + 1 + let k := i + 2 + have hij : i ≠ j := by unfold j; omega + have hik : i ≠ k := by unfold k; omega + have hjk : j ≠ k := by unfold j k; omega + let X := Profile.residual D v i * v i + have hX : 0 < X := mul_pos hb (hv i) + let x : Vec := fun l => if l = i then X else if l = j then r⁻¹ else X + r⁻¹ + have hx : Positive x := by intro l; unfold x; split_ifs <;> positivity + have hxi : x i = X := by simp [x] + have hxj : x j = r⁻¹ := by simp [x, hij.symm] + have hxk : x k = X + r⁻¹ := by simp [x, hik.symm, hjk.symm] + have hu := (h.family.envelope (critical_pos hv) (opposite_pos hv) hij (hx i) (hx j)).1 + have hp := h.pairing _ _ _ hij hik hjk x hx (by rw [hxi, hxj, hxk]) + have hs : Positive (near i r / v) := by + intro l + apply div_pos _ (hv l) + unfold near + split <;> positivity + have he := h.growth.lower hs hx + have hcost : cost (near i r / v) x = D v⁻¹ + r * (v k)⁻¹ * X := by + rw [near_cost hij hik hjk, hxi, hxj, hxk] + have hi : (v i)⁻¹ * X = Profile.residual D v i := by + unfold X; rw [mul_left_comm, inv_mul_cancel₀ (hv i).ne', mul_one] + have ht (a : ℝ) : r * a * r⁻¹ = a := by rw [mul_right_comm, mul_inv_cancel₀ hr.ne', one_mul] + rw [hi, mul_add, ht, ht, Profile.residual, opposite_eq v hij hik hjk] + ring + rw [hcost] at he + have hlo := hu.trans hp + rw [model, hxi, hxj, Real.log_inv] at hlo + have heq : X / criticalWidth v i = Profile.residual D v i / ((v i)⁻¹ * criticalWidth v i) := by + simp [X, div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] + rw [heq] at hlo + change axisValue D v P i - r * (v k)⁻¹ * X ≤ _ + unfold axisValue Profile.residual at * + linarith only [hlo, he] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +end + +section +/- +# From radial energy contraction to spectral propagation + +The test widths and the chord estimate give matching one-sided +limits at each axis. The intercept comparison controls their +differences uniformly up to a reciprocal face. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +open Profile Minimum Set Filter +open scoped Topology + +variable {F : Type} [Field F] {D : Vec → ℝ} {R : Vec → Vec → ℝ} + {P : PairPrices} {v : Vec} + +private theorem near_potential (i : Fin 3) (r : ℝ) : + potential (adjusted D R) v (near i r) = + variational (R v⁻¹) (D v⁻¹) (near i r / v) + opposite v i * Real.log r - + (mass v)⁻¹ * Real.log (1 + 2 * r) := by + unfold potential adjusted opposite mass + fin_cases i <;> simp [near, Fin.sum_univ_three] <;> ring_nf + +theorem Root.axis_limit (h : Root D v (R v⁻¹) P) (hd : StarTripod F D) + (hv : Positive v) (i : Fin 3) : + Tendsto (fun r => potential (adjusted D R) v (near i r)) (𝓝[>] 0) + (𝓝 (axisValue D v P i)) := by + let a := (v i)⁻¹ + let d := opposite v i + let B := Profile.residual D v i + let u := criticalWidth v i + let C := intercept P (opposite v) (criticalWidth v) i + have ha : 0 < a := inv_pos.mpr (hv i) + have hB : 0 < B := (residual_bounds hd hv i).1 + have hu : 0 < u := critical_pos hv i + let lo (r : ℝ) := axisValue D v P i - r * (v (i + 2))⁻¹ * (B * v i) + let hi (r : ℝ) := C + B * Real.log (B / ((a - r * d) * u)) + let g (r : ℝ) := variational (R v⁻¹) (D v⁻¹) (near i r / v) + d * Real.log r + have hlo : ContinuousAt lo 0 := by unfold lo; fun_prop + have hhi : ContinuousAt hi 0 := by + unfold hi + fun_prop (disch := simp [ha.ne', hu.ne', hB.ne']) + have hl₀ : lo 0 = axisValue D v P i := by simp [lo] + have hh₀ : hi 0 = axisValue D v P i := by simp [hi, axisValue, C, B, a, u] + have hn : ∀ᶠ r in 𝓝[>] (0 : ℝ), 0 < a - r * d := by + have he : ContinuousAt (fun r : ℝ => a - r * d) 0 := by fun_prop + exact he.continuousWithinAt.eventually_const_lt (by simpa using ha) + have hg : Tendsto g (𝓝[>] 0) (𝓝 (axisValue D v P i)) := by + refine tendsto_of_tendsto_of_tendsto_of_le_of_le' + (hl₀ ▸ hlo.continuousWithinAt.tendsto) (hh₀ ▸ hhi.continuousWithinAt.tendsto) ?_ ?_ + · filter_upwards [self_mem_nhdsWithin] with r hr + exact h.axis_lower hv i hB hr + · filter_upwards [self_mem_nhdsWithin, hn] with r hr ha' + exact h.axis_upper hv i hB hr ha' + have hx : ContinuousAt (fun r : ℝ => (mass v)⁻¹ * Real.log (1 + 2 * r)) 0 := by + fun_prop (disch := norm_num) + simp_rw [near_potential] + simpa only [mul_zero, add_zero, Real.log_one, sub_zero, g] using hg.sub hx.continuousWithinAt + +/-- All costs increase by the same amount. Initial costs are +proportional to the arm lengths when the terminals move. -/ +def Contracts (D : Vec → ℝ) (R : Vec → Vec → ℝ) : Prop := + ∀ v w s, Positive v → Positive w → Positive s → v ≤ w → ∀ t : ℝ, 0 < t → + adjusted D R w s - adjusted D R w (s + t • w) ≤ + adjusted D R v s - adjusted D R v (s + t • v) + +theorem uniform_of_contraction (hd : StarTripod F D) + (h : ∀ v, Positive v → ∃ P, Root D v (R v⁻¹) P) (hc : Contracts D R) : + Face.Uniform (defect D) := by + have hp {v s : Vec} (hv : Positive v) (hs : Positive s) : Positive (s / v) := + fun i => div_pos (hs i) (hv i) + have hr : Radial D (adjusted D R) := by + refine ⟨?_, ?_, hc⟩ + · intro v hv + obtain ⟨P, hP⟩ := h v hv + exact hP.growth.continuous.comp (by fun_prop (disch := exact (hv _).ne')) + (fun _ hs => hp hv hs) + · intro v s hv hs t ht + obtain ⟨P, hP⟩ := h v hv + unfold adjusted + rw [show (t • s) / v = t • (s / v) by ext i; simp [mul_div_assoc]] + exact hP.growth.log_scale (hp hv hs) ht + apply hr.uniform hd + apply axisLimits hd + intro v hv + obtain ⟨P, hP⟩ := h v hv + exact ⟨P, hP.family, hP.axis_limit hd hv⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Energy +end + +section +/- Radial contraction on the three rays controls the tripod defect uniformly. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Twig +open Energy Minimum Profile + +variable {K : Type} [Field K] {A : MatrixExponent.Prices.Atlas K Twig} + +private theorem adjusted_eq {v : Vec} (hv : Positive v) (s : Vec) : + adjusted (label A) (rootPrices A) v s = Multi.Q A origin (mark v⁻¹) (s / v) := by + unfold Multi.Q + rw [← rootPlacement, + root_label A (a := v⁻¹) (fun i => inv_pos.mpr (hv i))] + rfl + +variable [Infinite K] + +private theorem Homogeneous.contracts (hA : Homogeneous A) : Contracts (label A) (rootPrices A) + := by + intro v w s hv hw hs hvw t ht + have hp (z : Vec) (hz : Positive z) : Positive z⁻¹ := fun i => inv_pos.mpr (hz i) + have hl (z : Vec) (hz : Positive z) : 0 < A.price (Multi.sites origin (mark z⁻¹)) 2 := by + rw [← rootPlacement, root_label A (hp z hz)] + exact hA.star.pos _ (hp z hz) + have hm (z : Vec) (hz : Positive z) (i) : Dist.dist origin (mark z⁻¹ i) = (z i)⁻¹ := by + simp [mark, radius, (hz i).le] + have hd (z : Vec) (hz : Positive z) : + (s + t • z) / z = (fun i => (s / z) i + t) := by + funext i + simp [add_div, (hz i).ne'] + rw [adjusted_eq hw, adjusted_eq hw, adjusted_eq hv, adjusted_eq hv, hd w hw, hd v hv] + refine Multi.Q_contract A origin (mark v⁻¹) (mark w⁻¹) (s / v) (s / w) (v / w) + (fun i => (div_pos (hv i) (hw i)).le) (fun i => (div_le_one (hw i)).mpr (hvw i)) + ?_ ?_ ?_ (fun i => div_pos (hs i) (hv i)) (fun i => div_pos (hs i) (hw i)) + (hl v hv) (hl w hw) ht.le + · intro i + rw [hm v hv, hm w hw, Pi.div_apply] + field_simp [(hv i).ne', (hw i).ne'] + · intro i + rw [hm v hv, mark_dist (hp w hw) (hp v hv), ite_eq_left rfl] + simp only [Pi.inv_apply, Pi.div_apply] + rw [abs_of_nonpos (sub_nonpos.mpr (inv_anti₀ (hv i) (hvw i)))] + field_simp [(hv i).ne', (hw i).ne']; ring + · intro i + apply le_of_eq + simp only [Pi.div_apply] + field_simp [(hv i).ne', (hw i).ne'] + +theorem Homogeneous.uniform (hA : Homogeneous A) : Face.Uniform (defect (label A)) := by + apply uniform_of_contraction hA.star _ hA.contracts + intro v hv + refine ⟨_, root A hA hv ?_⟩ + apply family A (mark v⁻¹) _ _ (critical_pos hv) (opposite_pos hv) + intro i j k hij hik hjk + have ha : Positive v⁻¹ := fun l => inv_pos.mpr (hv l) + rw [mark_dist ha ha, ite_eq_right hjk, opposite_eq v hij hik hjk] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Twig +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Jacobian.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Jacobian.lean new file mode 100644 index 0000000000..e09e34a7bf --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Jacobian.lean @@ -0,0 +1,887 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Algebra.Subalgebra.Basic +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Matrix.Basic +public import Mathlib.Data.Fin.Tuple.Basic +public import Mathlib.RingTheory.Nullstellensatz +public import Mathlib.Algebra.MvPolynomial.Funext +public import Mathlib.RingTheory.AlgebraicIndependent.Basic +public import Mathlib.RingTheory.Localization.Ideal +public import Mathlib.RingTheory.MvPolynomial.Localization +public import Mathlib.RingTheory.FiniteType +public import Mathlib.RingTheory.Ideal.KrullsHeightTheorem +public import Mathlib.RingTheory.Derivation.Basic +public import Mathlib.Tactic.Ring +public import Mathlib.Algebra.TrivSqZeroExt.Basic +public import Mathlib.RingTheory.Smooth.Field +public import Mathlib.Algebra.TrivSqZeroExt.Ideal +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure +public import Mathlib.Algebra.MvPolynomial.PDeriv +public import Mathlib.LinearAlgebra.Matrix.NonsingularInverse +public import Mathlib.FieldTheory.IntermediateField.Adjoin.Algebra +public import Mathlib.RingTheory.DedekindDomain.IntegralClosure +public import Mathlib.RingTheory.DedekindDomain.Dvr + +/-! # Elimination with coefficients in a valuation ring -/ + +universe u w + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset +variable {K E : Type*} [Field K] [Field E] [Algebra K E] + (A : Subalgebra K E) (hA : ∀ x : E, x ∈ A ∨ x⁻¹ ∈ A) + {I : Type} [Fintype I] [DecidableEq I] + +include hA in +omit [DecidableEq I] [Fintype I] in +/-- Pick a nonzero pivot dividing every entry over the valuation ring. -/ +private theorem pivot [Finite I] (v : I → E) {k : I} (hk : v k ≠ 0) : + ∃ m, v m ≠ 0 ∧ ∀ i, v i / v m ∈ A := by + classical + let : Fintype I := Fintype.ofFinite I + have aux (s : Finset I) : ∃ m, v m ≠ 0 ∧ ∀ i ∈ s, v i / v m ∈ A := by + induction s using Finset.induction_on with + | empty => exact ⟨k, hk, by simp⟩ + | insert j _ _ ih => + obtain ⟨m, hm, hr⟩ := ih + simp only [mem_insert, forall_eq_or_imp] + by_cases h : v j / v m ∈ A + · exact ⟨m, hm, h, hr⟩ + have hj : v j ≠ 0 := fun e => h (by simp [e]) + have h' : v m / v j ∈ A := by simpa using (hA _).resolve_left h + refine ⟨j, hj, by simp [hj], fun i hi => ?_⟩ + rw [← div_mul_div_cancel₀ hm] + exact A.mul_mem (hr i hi) h' + simpa using aux univ + +include hA in +/-- The surviving columns are kept equal to the standard basis columns. +Subtracting a multiple of row `m` therefore preserves all of them except `m`. -/ +theorem eliminate {d : ℕ} (w : Fin d → I → E) : + ∃ (S : Finset I) (P : Matrix I I A), Fintype.card I - d ≤ S.card ∧ + (∀ i ∈ S, ∀ j ∈ S, P i j = if i = j then 1 else 0) ∧ + ∀ i l, ∑ j, (P i j : E) * w l j = 0 := by + suffices ∃ (S : Finset I) (P : Matrix I I A), Fintype.card I - d ≤ S.card ∧ + (∀ i j, j ∈ S → P i j = if i = j then 1 else 0) ∧ + ∀ i l, ∑ j, (P i j : E) * w l j = 0 by + obtain ⟨S, P, hS, hP, h⟩ := this + exact ⟨S, P, hS, fun i _ => hP i, h⟩ + induction d with + | zero => exact ⟨univ, 1, by simp, fun _ _ _ => rfl, fun _ l => Fin.elim0 l⟩ + | succ d ih => + obtain ⟨S, P, hS, hP, h⟩ := ih (fun l => w l.succ) + let v i := ∑ j, (P i j : E) * w 0 j + by_cases hz : ∀ i, v i = 0 + · exact ⟨S, P, by omega, hP, fun i => Fin.cases (hz i) (h i)⟩ + obtain ⟨k, hk⟩ := not_forall.mp hz + obtain ⟨m, hm, hr⟩ := pivot A hA v hk + let r (i : I) : A := ⟨v i / v m, hr i⟩ + let Q : Matrix I I A := fun i j => P i j - r i * P m j + refine ⟨S.erase m, Q, ?_, ?_, ?_⟩ + · exact (Nat.sub_le_sub_right hS 1).trans pred_card_le_card_erase + · intro i j hj + obtain ⟨hne, hj⟩ := mem_erase.mp hj + simp only [Q, hP m j hj, ite_eq_right hne.symm, mul_zero, sub_zero, hP i j hj] + · intro i l + change ∑ j, ((P i j : E) - (v i / v m) * (P m j : E)) * w l j = 0 + simp only [sub_mul, mul_assoc, sum_sub_distrib, ← mul_sum] + induction l using Fin.cases with + | zero => exact sub_eq_zero.mpr (div_mul_cancel₀ (v i) hm).symm + | succ l => rw [h i l, h m l, mul_zero, sub_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +section +/- # Existence and descent of common zeros in finitely many variables -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open MvPolynomial + +theorem point_of_proper {k K : Type*} [Field k] [Field K] [IsAlgClosed K] [Algebra k K] + {I : Type*} [Finite I] (s : Set (MvPolynomial I k)) (h : Ideal.span s ≠ ⊤) : + ∃ x : I → K, ∀ p ∈ s, aeval x p = 0 := by + obtain ⟨J, hJ, hs⟩ := Ideal.exists_le_maximal (Ideal.span s) h + obtain ⟨x, rfl⟩ := eq_vanishingIdeal_singleton_of_isMaximal K hJ + exact ⟨x, fun p hp => (mem_vanishingIdeal_singleton_iff x p).mp (hs (Ideal.subset_span hp))⟩ + +theorem descend_point {F K : Type*} [Field F] [Field K] [IsAlgClosed F] [Algebra F K] + {I : Type*} [Finite I] (s : Set (MvPolynomial I F)) (z : I → K) + (h : ∀ p ∈ s, aeval z p = 0) : + ∃ v : I → F, ∀ p ∈ s, eval v p = 0 := by + have hz : z ∈ zeroLocus K (Ideal.span s) := by rw [zeroLocus_span]; exact h + have hs : Ideal.span s ≠ ⊤ := by + intro he + rw [he, zeroLocus_top] at hz + exact hz + obtain ⟨v, hv⟩ := point_of_proper (K:=F) s hs + exact ⟨v, hv⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Generic parameters in a finite union of polynomial projections + +If a system has no solution over the generic parameters, localization +produces a nonzero polynomial vanishing on every ground-field parameter +where that system has a solution. The product of finitely many such +obstructions cannot vanish on the whole parameter space. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial +variable {F K P J : Type*} [Field F] [Field K] [Algebra F K] + +open scoped Classical in +private def curry : MvPolynomial (P ⊕ J) F →+* MvPolynomial J (MvPolynomial P F) := + eval₂Hom (C.comp C) (Sum.elim (C ∘ X) X) + +open scoped Classical in +private theorem curry_eval (x : P → K) (y : J → K) (p : MvPolynomial (P ⊕ J) F) : + eval₂ (aeval x).toRingHom y (curry p) = aeval (Sum.elim x y) p := by + have h : (eval₂Hom (aeval (R:=F) x).toRingHom y).comp curry = (aeval (Sum.elim x y)).toRingHom + := by + apply ringHom_ext + · intro a; simp [curry] + · rintro (i|i) <;> simp [curry] + exact DFunLike.congr_fun h p + +attribute [local instance] algebraMvPolynomial + +open scoped Classical in +private theorem solve_localized {R : Type*} [CommRing R] [IsDomain R] [IsAlgClosed K] + [Finite J] (f : R →+* K) (hf : Function.Injective f) (s : Set (MvPolynomial J R)) + (h : ∀ a : R, C a ∈ Ideal.span s → a = 0) : ∃ y : J → K, ∀ p ∈ s, eval₂ f y p = 0 := by + let L := FractionRing R + let g : L →+* K := IsFractionRing.lift hf + let _ : Algebra L K := g.toAlgebra + have hg : (algebraMap L K).comp (algebraMap R L) = f := + RingHom.ext fun a => IsFractionRing.lift_algebraMap hf a + have hs : Ideal.span (map (algebraMap R L) '' s) ≠ ⊤ := by + rw [← Ideal.map_span, ← MvPolynomial.algebraMap_def] + apply (IsLocalization.map_algebraMap_ne_top_iff_disjoint + ((nonZeroDivisors R).map (C (σ:=J))) (MvPolynomial J L) (Ideal.span s)).mpr + refine Set.disjoint_left.mpr ?_ + rintro _ ⟨a, ha, rfl⟩ hm + exact (mem_nonZeroDivisors_iff_ne_zero.mp ha) (h a hm) + obtain ⟨y, hy⟩ := point_of_proper (K:=K) _ hs + refine ⟨y, fun p hp => ?_⟩ + simpa only [aeval_def, eval₂_map, hg] using hy _ ⟨p, hp, rfl⟩ + +open scoped Classical in +private theorem obstruction [Finite J] [IsAlgClosed K] {x : P → K} (hx : AlgebraicIndependent F x) + (s : Set (MvPolynomial (P ⊕ J) F)) (h : ¬ ∃ y : J → K, ∀ p ∈ s, aeval (Sum.elim x y) p = 0) : + ∃ q : MvPolynomial P F, q ≠ 0 ∧ ∀ (v : P → F) (y : J → F), + (∀ p ∈ s, eval (Sum.elim v y) p = 0) → eval v q = 0 := by + have ex : ∃ q : MvPolynomial P F, C q ∈ Ideal.span (curry '' s) ∧ q ≠ 0 := by + by_contra! hn + obtain ⟨y, hy⟩ := solve_localized (aeval (R:=F) x).toRingHom hx (curry '' s) hn + exact h ⟨y, fun p hp => (curry_eval x y p).symm.trans (hy _ ⟨p, hp, rfl⟩)⟩ + obtain ⟨q, hq, hn⟩ := ex + refine ⟨q, hn, fun v y he => ?_⟩ + have hold : Ideal.span (curry '' s) ≤ RingHom.ker (eval₂Hom (aeval v).toRingHom y) := by + apply Ideal.span_le.mpr + rintro _ ⟨p, hp, rfl⟩ + exact (curry_eval v y p).trans (he p hp) + have hc : eval₂ (aeval v).toRingHom y (C q) = 0 := hold hq + rw [eval₂_C] at hc + exact hc + +open scoped Classical in +theorem generic_point [IsAlgClosed F] [IsAlgClosed K] {X A : Type*} [Finite A] + {x : X → K} (hx : AlgebraicIndependent F x) (J : A → Type*) [∀ i, Finite (J i)] + (S : (i : A) → Set (MvPolynomial (X ⊕ J i) F)) + (h : ∀ v : X → F, ∃ i, ∃ w : J i → F, ∀ p ∈ S i, eval (Sum.elim v w) p = 0) : + ∃ i, ∃ w : J i → K, ∀ p ∈ S i, aeval (Sum.elim x w) p = 0 := by + let : Fintype A := Fintype.ofFinite A + by_contra hn + have fails (i : A) : ¬ ∃ w : J i → K, ∀ p ∈ S i, aeval (Sum.elim x w) p = 0 := + fun a => hn ⟨i, a⟩ + choose q hq hzero using fun i => obstruction hx (S i) (fails i) + have ne : ∏ i, q i ≠ 0 := Finset.prod_ne_zero_iff.mpr fun i _ => hq i + apply ne + apply MvPolynomial.funext + intro v + obtain ⟨i, w, hw⟩ := h v + rw [map_zero, map_prod] + exact Finset.prod_eq_zero (Finset.mem_univ i) (hzero i v w hw) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +section +/- +# The local ring of an algebraic deformation + +At the selected point of a normalized curve the residue field is +the field of constants. The deformation parameter is a power of a +uniformizer times a unit. Essential finite generation will give +a uniform bound on the poles of a derivation. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +/-- The data for the branch construction, including `ring`, `res`, `val`, `π`, `nonzero`. -/ +structure Branch (K E : Type*) [Field K] [Field E] [Algebra K E] (t : E) where + /-- The `Branch` component of type `Subalgebra K E`. -/ + ring : Subalgebra K E + /-- The `Branch` component of type `ring →ₐ[K] K`. -/ + res : ring →ₐ[K] K + val : ∀ x : E, x ∈ ring ∨ x⁻¹ ∈ ring + /-- The `Branch` component of type `ring`. -/ + π : ring + nonzero : (π : E) ≠ 0 + zero : res π = 0 + residue : ∀ x : ring, ∃ b : ring, (x : E) = algebraMap K E (res x) + (π : E) * b + factor : ∃ e : ℕ, ∃ u : ringˣ, t = (π : E) ^ (e + 1) * (u.val : E) + clear : ∀ x : E, ∃ m : ℕ, (π : E) ^ m * x ∈ ring + generated : ∃ B : Subalgebra K E, B.FG ∧ B ≤ ring ∧ + ∀ x : ring, ∃ a b : B, (b : E)⁻¹ ∈ ring ∧ (x : E) = (a : E) / (b : E) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +section +/- +# Lengths of prime chains below a fixed point + +Keep the lower prime explicit so that chains can be concatenated +in a product ring and mapped to a quotient. The final upper bound +need not itself be a member of the chain. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +variable {R S : Type*} [CommRing R] [CommRing S] + +/-- The chain used in the `Verification` construction. -/ +inductive Chain : Ideal R → Ideal R → ℕ → Prop + | nil {p m} : p.IsPrime → p ≤ m → Chain p m 0 + | cons {p q m n} : p.IsPrime → p < q → Chain q m n → Chain p m (n + 1) + +namespace Chain +variable {p q m : Ideal R} {n : ℕ} + +theorem prime (h : Chain p m n) : p.IsPrime := by cases h <;> assumption + +theorem le (h : Chain p m n) : p ≤ m := by + induction h with + | nil _ e => exact e + | cons _ h _ ih => exact h.le.trans ih + +theorem lt (h : Chain p m (n + 1)) : p < m := by + cases h with | cons _ h t => exact h.trans_le t.le + +theorem weaken (h : Chain p q n) (hm : q ≤ m) : Chain p m n := by + induction h with + | nil hp he => exact .nil hp (he.trans hm) + | cons hp he _ ih => exact .cons hp he (ih hm) + +theorem start (h : Chain q m n) (hp : p.IsPrime) (hsub : p ≤ q) : Chain p m n := by + cases h with + | nil _ he => exact .nil hp (hsub.trans he) + | cons _ he h => exact .cons hp (hsub.trans_lt he) h + +theorem append {k : ℕ} (h : Chain p q n) (g : Chain q m k) : Chain p m (k + n) := by + induction h with + | nil hp he => exact g.start hp he + | cons hp he _ ih => exact .cons hp he (ih g) + +theorem bound (h : Chain p m n) : p.height + n ≤ m.height := by + induction h with + | nil _ e => simpa using Ideal.height_mono e + | cons hp e h ih => + have := hp + have := h.prime + rw [Nat.cast_add, Nat.cast_one, add_comm _ 1, ← add_assoc] + exact (add_le_add_left (Ideal.height_add_one_le_of_lt_of_isPrime e) _).trans ih + +theorem length_le (h : Chain p m n) : (n : ℕ∞) ≤ m.height := le_add_self.trans h.bound + +theorem transport (f : Ideal R → Ideal S) (hf : Monotone f) + (hp : ∀ i, i.IsPrime → (f i).IsPrime) + (he : ∀ i j, i.IsPrime → j.IsPrime → f i = f j → i = j) + (h : Chain p m n) : Chain (f p) (f m) n := by + induction h with + | nil e hm => exact .nil (hp _ e) (hf hm) + | cons e hi g ih => + exact .cons (hp _ e) (lt_of_le_of_ne (hf hi.le) (fun hu => hi.ne (he _ _ e g.prime hu))) ih + +variable {I : Ideal R} + +private theorem quotient (h : Chain p m n) (hi : I ≤ p) : + Chain (p.map (Ideal.Quotient.mk I)) (m.map (Ideal.Quotient.mk I)) n := by + let f := Ideal.Quotient.mk I + have hf : Function.Surjective f := Ideal.Quotient.mk_surjective + have hp (j : Ideal R) (h : j.IsPrime) (e : I ≤ j) : (j.map f).IsPrime := by + have := h + exact Ideal.map_isPrime_of_surjective hf (I.mk_ker.trans_le e) + have he (j : Ideal R) (e : I ≤ j) : (j.map f).comap f = j := by + rw [Ideal.comap_map_of_surjective' _ hf, I.mk_ker, sup_eq_left.mpr e] + induction h with + | nil h e => exact .nil (hp _ h hi) (Ideal.map_mono e) + | cons h e _ ih => + refine .cons (hp _ h hi) (lt_of_le_of_ne (Ideal.map_mono e.le) ?_) (ih (hi.trans e.le)) + intro eq + exact e.ne ((he _ hi).symm.trans ((congrArg (Ideal.comap f) eq).trans (he _ (hi.trans e.le)))) + +theorem equations [IsNoetherianRing R] {σ : Type} [Fintype σ] (y : σ → R) + (hm : m ∈ (I ⊔ Ideal.span (Set.range y)).minimalPrimes) (h : Chain p m n) (hi : I ≤ p) : + n ≤ Fintype.card σ := by + classical + let f := Ideal.Quotient.mk I + have hf : Function.Surjective f := Ideal.Quotient.mk_surjective + let s := Finset.univ.image (f ∘ y) + have he : Ideal.span (s : Set (R ⧸ I)) = (Ideal.span (Set.range y)).map f := by + simp only [s, Finset.coe_image, Finset.coe_univ, Set.image_univ, Set.range_comp, Ideal.map_span] + have hk : m.map f ∈ (Ideal.span (s : Set (R ⧸ I))).minimalPrimes := by + rw [he, Ideal.minimalPrimes_map_of_surjective hf, I.mk_ker, sup_comm] + exact ⟨m, hm, rfl⟩ + have hb := (h.quotient hi).length_le.trans (Ideal.height_le_card_of_mem_minimalPrimes_span_finset + hk) + exact (ENat.natCast_le_natCast.mp hb).trans Finset.card_image_le + +end Chain +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Derivatives on a normalized curve commute with specialization + +A derivation fixing the deformation parameter has a uniform pole +bound on the local ring. Differentiating the ramification relation +improves the bound on the uniformizer by one. Subtracting each +element's residue then improves the bound on the whole ring. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification.Branch + +variable {F K E : Type*} [Field F] [Field K] [Field E] [Algebra F K] [Algebra F E] + [Algebra K E] {t : E} (b : Branch K E t) (D : Derivation F E E) + (d : Derivation F K K) (he : ∀ x, D (algebraMap K E x) = algebraMap K E (d x)) + +/-- The condition `∀ x ∈ b.ring, (b.π : E) ^ m * D x ∈ b.ring` on the specified data. -/ +def bounded (m : ℕ) := ∀ x ∈ b.ring, (b.π : E) ^ m * D x ∈ b.ring + +include he in +theorem pole_bound : ∃ m, b.bounded D m := by + classical + obtain ⟨B, ⟨s, rfl⟩, hB, hfrac⟩ := b.generated + choose l hl using fun x : E => b.clear (D x) + let m := s.sup l + let c := (b.π : E) ^ m + have hc : c ∈ b.ring := b.ring.pow_mem b.π.property _ + have ha {x : E} (hx : x ∈ Algebra.adjoin K (↑s : Set E)) : c * D x ∈ b.ring := by + induction hx using Algebra.adjoin_induction with + | mem x hx => + obtain ⟨k, hk⟩ := Nat.exists_eq_add_of_le (Finset.le_sup (f := l) hx) + change (b.π : E) ^ m * D x ∈ b.ring + rw [show m = l x + k from hk, add_comm, pow_add, mul_assoc] + exact b.ring.mul_mem (b.ring.pow_mem b.π.property _) (hl x) + | algebraMap x => rw [he]; exact b.ring.mul_mem hc (b.ring.algebraMap_mem _) + | add x y _ _ hx hy => rw [map_add, mul_add]; exact b.ring.add_mem hx hy + | mul x y hx hy ex ey => + rw [D.leibniz, smul_eq_mul, smul_eq_mul, mul_add, mul_left_comm c x, mul_left_comm c y] + exact b.ring.add_mem (b.ring.mul_mem (hB hx) ey) (b.ring.mul_mem (hB hy) ex) + refine ⟨m, fun x hx => ?_⟩ + obtain ⟨p, q, hi, hr⟩ := hfrac ⟨x, hx⟩ + change x = (p : E) / (q : E) at hr + change c * D x ∈ b.ring + rw [hr, D.leibniz_div, smul_eq_mul, smul_eq_mul, smul_eq_mul, mul_left_comm c, mul_sub, + mul_left_comm c (q : E), mul_left_comm c (p : E)] + exact b.ring.mul_mem (b.ring.pow_mem hi _) (b.ring.sub_mem + (b.ring.mul_mem (hB q.property) (ha p.property)) (b.ring.mul_mem (hB p.property) (ha + q.property))) + +variable [CharZero K] (ht : D t = 0) + +omit [Algebra F K] in +include ht in +private theorem uniformizer : ∃ c x : b.ring, D (b.π : E) = (b.π : E) * c * D (x : E) := by + obtain ⟨e, u, hu⟩ := b.factor + let v : E := u.val + let q : E := b.π + have hh : D (q ^ (e + 1) * v) = 0 := by rw [← hu]; exact ht + rw [D.leibniz, D.leibniz_pow] at hh + simp only [smul_eq_mul, nsmul_eq_mul, Nat.add_sub_cancel, pow_succ] at hh + have hv : q * D v + (↑(e + 1) : E) * v * D q = 0 := by + apply (mul_eq_zero.mp (show q ^ e * (q * D v + (↑(e + 1) : E) * v * D q) + = 0 from ?_)).resolve_left + (pow_ne_zero _ b.nonzero) + calc + _ = q ^ e * q * D v + v * ((↑(e + 1) : E) * (q ^ e * D q)) := by ring + _ = _ := hh + let k := ((↑(e + 1) : K))⁻¹ + let c : b.ring := -(algebraMap K b.ring k) * (u⁻¹).val + have eqn : (c : E) * ((↑(e + 1) : E) * v) = -1 := by + have hk : k * (↑(e + 1) : K) = 1 := inv_mul_cancel₀ (by exact_mod_cast Nat.succ_ne_zero e) + have hu' : ((u⁻¹).val : E) * v = 1 := congrArg Subtype.val (Units.inv_mul u) + calc + _ = -(algebraMap K E k * (↑(e + 1) : E)) * (((u⁻¹).val : E) * v) := by + change (-(algebraMap K E k) * _) * _ = _ + ring + _ = -1 := by rw [← map_natCast (algebraMap K E), ← map_mul, hk, map_one, hu', mul_one] + refine ⟨c, u.val, ?_⟩ + change D q = q * (c : E) * D v + calc + _ = -((c : E) * ((↑(e + 1) : E) * v)) * D q := by rw [eqn, neg_neg, one_mul] + _ = (c : E) * (-((↑(e + 1) : E) * v * D q)) := by ring + _ = _ := by rw [neg_eq_of_add_eq_zero_left hv]; ring + +include he ht in +theorem regular (a : b.ring) : D (a : E) ∈ b.ring := by + obtain ⟨c, x, hu⟩ := b.uniformizer D ht + have step (m : ℕ) (h : b.bounded D (m + 1)) : b.bounded D m := by + intro y hy + obtain ⟨z, hz⟩ := b.residue ⟨y, hy⟩ + let s := b.res ⟨y, hy⟩ + change y = algebraMap K E s + (b.π : E) * z at hz + rw [hz, map_add, he, D.leibniz, smul_eq_mul, smul_eq_mul, hu] + rw [show (b.π : E) ^ m * (algebraMap K E (d s) + ((b.π : E) * D (z : E) + + (z : E) * ((b.π : E) * c * D (x : E)))) = + (b.π : E) ^ m * algebraMap K E (d s) + ((b.π : E) ^ (m + 1) * D (z : E) + + (z : E) * c * ((b.π : E) ^ (m + 1) * D (x : E))) by ring] + exact b.ring.add_mem (b.ring.mul_mem (b.ring.pow_mem b.π.property _) (b.ring.algebraMap_mem _)) + (b.ring.add_mem (h _ z.property) (b.ring.mul_mem (b.ring.mul_mem z.property c.property) (h _ + x.property))) + obtain ⟨m, hm⟩ := b.pole_bound D d he + induction m with + | zero => simpa using hm _ a.property + | succ m ih => exact ih (step m hm) + +/-- Uses `⟨D (a : E), b.regular D d he ht a⟩` as the representation. -/ +def lift (a : b.ring) : b.ring := ⟨D (a : E), b.regular D d he ht a⟩ + +theorem specialize (a : b.ring) : b.res (b.lift D d he ht a) = d (b.res a) := by + obtain ⟨c, x, hu⟩ := b.uniformizer D ht + obtain ⟨z, hz⟩ := b.residue a + let g := b.lift D d he ht + have h : g a = algebraMap K b.ring (d (b.res a)) + b.π * (g z + z * c * g x) := by + apply Subtype.ext + change D (a : E) = algebraMap K E _ + (b.π : E) * (D (z : E) + (z : E) * c * D (x : E)) + conv_lhs => rw [hz, map_add, he, D.leibniz, smul_eq_mul, smul_eq_mul, hu] + ring + change b.res (g a) = _ + rw [h, map_add, b.res.commutes, map_mul, b.zero, zero_mul, add_zero] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification.Branch +end + +section +/- +# Derivations as maps to dual numbers + +The first coordinate records the field embedding and the second records the derivation. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +variable {F K E : Type u} [Field F] [Field K] [Field E] + +/-- Builds `K →+* TrivSqZeroExt E E where toFun x` with the specified `toFun`, `map_one'`, +`map_zero'`, `map_add'`. -/ +def prolong [Algebra F K] [Algebra K E] (D : Derivation F K K) : + K →+* TrivSqZeroExt E E where + toFun x := (algebraMap K E x, algebraMap K E (D x)) + map_one' := by ext <;> simp + map_zero' := by ext <;> simp + map_add' x y := by + simp only [map_add] + rfl + map_mul' x y := by + apply TrivSqZeroExt.ext + · exact map_mul (algebraMap K E) x y + · change algebraMap K E (D (x * y)) = + algebraMap K E x * algebraMap K E (D y) + algebraMap K E (D x) * algebraMap K E y + simp [Derivation.leibniz, smul_eq_mul, mul_comm] + +/-- Builds `Derivation F E E where toFun x` with the specified `toFun`, `map_add'`, `map_smul'`, +`map_one_eq_zero'`. -/ +def extract [Algebra F E] (f : E →+* TrivSqZeroExt E E) (fst : ∀ x, (f x).fst = x) + (zero : ∀ a : F, (f (algebraMap F E a)).snd = 0) : Derivation F E E where + toFun x := (f x).snd + map_add' x y := by simp + map_smul' c x := by simp [Algebra.smul_def, TrivSqZeroExt.snd_mul, fst, zero] + map_one_eq_zero' := by change (f 1).snd = 0; simp + leibniz' x y := by + change (f (x * y)).snd = x • (f y).snd + y • (f x).snd + simp [TrivSqZeroExt.snd_mul, fst, smul_eq_mul, mul_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Concatenating chains of primes in independent blocks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification.Chain +open Finset + +variable {J : Type} [Fintype J] {R : J → Type*} [∀ j, CommRing (R j)] {S : Type*} [CommRing S] + +open scoped Classical in +theorem product (D : (∀ j, Ideal (R j)) → Ideal S) (hm : Monotone D) + (hp : ∀ I, (∀ j, (I j).IsPrime) → (D I).IsPrime) + (he : ∀ I I', (∀ j, (I j).IsPrime) → (∀ j, (I' j).IsPrime) → D I = D I' → I = I') + {P Q : ∀ j, Ideal (R j)} (hq : ∀ j, (Q j).IsPrime) {n : ℕ} (h : ∀ j, Chain (P j) (Q j) n) : + Chain (D P) (D Q) (Fintype.card J * n) := by + let g (s : Finset J) j := if j ∈ s then Q j else P j + have hg (s : Finset J) (j : J) : (g s j).IsPrime := by + unfold g + split + · exact hq j + · exact (h j).prime + have step (s : Finset J) (j : J) (hj : j ∉ s) : Chain (D (g s)) (D (g (insert j s))) n := by + let f (P : Ideal (R j)) := Function.update (g s) j P + have hf (a : Ideal (R j)) (ha : a.IsPrime) (k : J) : (f a k).IsPrime := by + by_cases e : k = j + · subst k; simpa [f] using ha + · simpa [f, e] using hg s k + have hmono : Monotone f := by + intro a b hab k + by_cases e : k = j + · subst k; simpa [f] using hab + · simp [f, e] + have hleft : f (P j) = g s := by + funext k + by_cases e : k = j + · subst k; simp [f, g, hj] + · simp [f, e] + have hright : f (Q j) = g (insert j s) := by + funext k + by_cases e : k = j + · subst k; simp [f, g] + · simp [f, g, e] + rw [← hleft, ← hright] + apply (h j).transport (D ∘ f) (hm.comp hmono) (fun a ha => hp _ (hf a ha)) + intro a b ha hb heq + simpa only [f, Function.update_self] using congrFun (he _ _ (hf a ha) (hf b hb) heq) j + have aux (s : Finset J) : Chain (D (g ∅)) (D (g s)) (s.card * n) := by + induction s using Finset.induction with + | empty => rw [card_empty, zero_mul]; exact .nil (hp _ (hg _)) le_rfl + | @insert j s hj ih => + rw [card_insert_of_notMem hj, Nat.succ_mul, add_comm] + exact ih.append (step s j hj) + simpa [g] using aux univ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification.Chain +end + +/- +# Lifting values on independent elements to dual numbers + +A field of characteristic zero is formally smooth over any subfield. +It is also formally smooth over the polynomial subalgebra generated +by independent elements, since passing to its fraction field is a +localization. Consequently we can specify first-order increments +on the generators and on the coefficient field simultaneously. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +private theorem smooth (K E : Type u) [Field K] [Field E] [Algebra K E] [CharZero E] : + Algebra.FormallySmooth K E := by + obtain ⟨ι, x, hx⟩ := exists_isTranscendenceBasis' K E + have := hx.isAlgebraic_field + exact Algebra.FormallySmooth.of_algebraicIndependent_of_isSeparable hx.1 + +private theorem section_of_smooth {A E : Type u} [CommRing A] [Field E] [Algebra A E] + [Algebra.FormallySmooth A E] (q : A →+* TrivSqZeroExt E E) + (hq : ∀ a, (q a).fst = algebraMap A E a) : + ∃ f : E →+* TrivSqZeroExt E E, (∀ a, (f a).fst = a) ∧ + ∀ a : A, f (algebraMap A E a) = q a := by + let : Algebra A (TrivSqZeroExt E E) := q.toAlgebra + let π : TrivSqZeroExt E E →ₐ[A] E := + { (TrivSqZeroExt.fstHom E E E).toRingHom with commutes' := hq } + have ep : Function.Surjective π := fun x => ⟨(x, 0), rfl⟩ + have hn : IsNilpotent (RingHom.ker π) := ⟨2, TrivSqZeroExt.kerIdeal_sq E E⟩ + let f := Algebra.FormallySmooth.liftOfSurjective (AlgHom.id A E) π ep hn + exact ⟨f.toRingHom, Algebra.FormallySmooth.liftOfSurjective_apply _ π ep hn, f.commutes⟩ + +open scoped IntermediateField.algebraAdjoinAdjoin in +theorem lift_independent {K E : Type u} [Field K] [Field E] [Algebra K E] [CharZero E] + {ι : Type w} {x : ι → E} (hx : AlgebraicIndependent K x) (v : ι → E) + (d : K →+* TrivSqZeroExt E E) (hd : ∀ a, (d a).fst = algebraMap K E a) : + ∃ f : E →+* TrivSqZeroExt E E, (∀ a, (f a).fst = a) ∧ + (∀ a : K, f (algebraMap K E a) = d a) ∧ ∀ i, (f (x i)).snd = v i := by + let A := Algebra.adjoin K (Set.range x) + let L := IntermediateField.adjoin K (Set.range x) + have : Algebra.FormallySmooth A L := .of_isLocalization (nonZeroDivisors A) + have : Algebra.FormallySmooth L E := smooth L E + have : Algebra.FormallySmooth A E := .comp A L E + let y : ι → TrivSqZeroExt E E := fun i => (x i, v i) + let φ := MvPolynomial.eval₂Hom d y + have hC (r : K) : φ (MvPolynomial.C r) = d r := MvPolynomial.eval₂Hom_C d y r + have hX (i : ι) : φ (MvPolynomial.X i) = y i := MvPolynomial.eval₂Hom_X' d y i + let π := (TrivSqZeroExt.fstHom E E E).toRingHom + have hh : π.comp φ = (MvPolynomial.aeval x).toRingHom := by + apply MvPolynomial.ringHom_ext + · intro a + simpa [hC, π] using hd a + · intro i + simp [hX, π, y] + rfl + let q : A →+* TrivSqZeroExt E E := φ.comp hx.aevalEquiv.symm.toRingHom + have eval (p : MvPolynomial ι K) : q (hx.aevalEquiv p) = φ p := by + change φ (hx.aevalEquiv.symm (hx.aevalEquiv p)) = _ + rw [AlgEquiv.symm_apply_apply] + have hq (a : A) : (q a).fst = algebraMap A E a := by + obtain ⟨p, rfl⟩ := hx.aevalEquiv.surjective a + rw [eval, hx.algebraMap_aevalEquiv] + exact DFunLike.congr_fun hh p + obtain ⟨f, hf, hf'⟩ := section_of_smooth q hq + have hp (p : MvPolynomial ι K) : f (MvPolynomial.aeval x p) = φ p := by + rw [← hx.algebraMap_aevalEquiv, hf', eval] + refine ⟨f, hf, ?_, ?_⟩ + · intro a + simpa [hC] using hp (MvPolynomial.C a) + · intro i + simpa [hX, y] using congrArg TrivSqZeroExt.snd (hp (MvPolynomial.X i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Independent coordinates and derivations of field extensions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +variable {F K E : Type u} [Field F] [Field K] [Field E] [Algebra K E] [CharZero E] + +/-- Prescribe increments over an arbitrary derivation on the coefficient field. -/ +theorem extend_derivation [Algebra F K] [Algebra F E] [IsScalarTower F K E] + {ι : Type w} {x : ι → E} (h : AlgebraicIndependent K x) (D : Derivation F K K) (v : ι → E) : + ∃ D' : Derivation F E E, (∀ a, D' (algebraMap K E a) = algebraMap K E (D a)) ∧ + ∀ i, D' (x i) = v i := by + obtain ⟨f, hf, hc, hi⟩ := lift_independent h v (prolong D) (fun _ => rfl) + have extend (x : K) : (f (algebraMap K E x)).snd = algebraMap K E (D x) := by rw [hc]; rfl + have hz (a : F) : (f (algebraMap F E a)).snd = 0 := by + rw [IsScalarTower.algebraMap_apply F K E, extend, D.map_algebraMap, map_zero] + exact ⟨extract f hf hz, extend, hi⟩ + +/-- The infinitesimal increments of an independent family may be prescribed arbitrarily. -/ +theorem derivation_of_independent {ι : Type w} {x : ι → E} + (hx : AlgebraicIndependent K x) (v : ι → E) : + ∃ D : Derivation K E E, ∀ i, D (x i) = v i := by + obtain ⟨D, _, h⟩ := extend_derivation hx (0 : Derivation K K K) v + exact ⟨D, h⟩ + +/-- Extend a derivation of the coefficient field, holding a transcendental element fixed. -/ +theorem exists_derivation_extension [Algebra F K] [Algebra F E] [IsScalarTower F K E] + {t : E} (ht : Transcendental K t) (D : Derivation F K K) : + ∃ D' : Derivation F E E, + (∀ x, D' (algebraMap K E x) = algebraMap K E (D x)) ∧ D' t = 0 := by + have h : AlgebraicIndependent K (fun _ : Unit => t) := algebraicIndependent_unique_type_iff.mpr ht + obtain ⟨D', he, hzero⟩ := extend_derivation h D (fun _ => 0) + exact ⟨D', he, hzero ()⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # An algebraically closed extension with new independent coordinates -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +/-- The value specified by `AlgebraicClosure (FractionRing (MvPolynomial σ K))`. -/ +abbrev Free (K : Type u) [Field K] (σ : Type) := AlgebraicClosure (FractionRing (MvPolynomial σ K)) + +namespace Free + +variable (K : Type u) [Field K] (σ : Type) + +/-- Uses `MvPolynomial σ K` as the representation. -/ +abbrev P := MvPolynomial σ K +/-- The value specified by `FractionRing (P K σ)`. -/ +abbrev R := FractionRing (P K σ) + +/-- The value specified by `algebraMap (R K σ) (Free K σ) (algebraMap (P K σ) (R K σ) +(MvPolynomial.X i))`. -/ +def point (i : σ) : Free K σ := + algebraMap (R K σ) (Free K σ) (algebraMap (P K σ) (R K σ) (MvPolynomial.X i)) + +private theorem injective_map {A B : Type u} [CommRing A] [CommRing B] [Algebra K A] + [Algebra K B] [Algebra A B] [IsScalarTower K A B] {x : σ → A} + (h : AlgebraicIndependent K x) (hf : Function.Injective (algebraMap A B)) : + AlgebraicIndependent K (fun i => algebraMap A B (x i)) := + h.map' (f := IsScalarTower.toAlgHom K A B) hf + +theorem independent : AlgebraicIndependent K (point K σ) := by + have hr := injective_map K σ (MvPolynomial.algebraicIndependent_X σ K) + (IsFractionRing.injective (P K σ) (R K σ)) + exact injective_map K σ hr (algebraMap (R K σ) (Free K σ)).injective + +variable {K} {F : Type u} [Field F] [Algebra F K] [CharZero K] + +theorem derivation (D : Derivation F K K) : + ∃ D' : Derivation F (Free K σ) (Free K σ), + (∀ a, D' (algebraMap K (Free K σ) a) = algebraMap K (Free K σ) (D a)) ∧ + ∀ i, D' (point K σ i) = 0 := + extend_derivation (independent K σ) D (fun _ => 0) + +end Free +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +section +/- +# The Jacobian at a point with algebraically independent images + +Given arbitrary derivatives of the images, extend to a derivation of the field. +The polynomial chain rule writes the prescribed derivatives as the Jacobian +times the derivatives of the coordinates. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +variable {F K : Type u} [Field F] [Field K] [Algebra F K] {ι : Type} + +theorem derivation_aeval [Fintype ι] (D : Derivation F K K) (a : ι → K) + (p : MvPolynomial ι F) : + D (aeval a p) = ∑ j, aeval a (pderiv j p) * D (a j) := by + classical + induction p using MvPolynomial.induction_on with + | C c => simp + | add p q hp hq => simp only [map_add, hp, hq, add_mul, Finset.sum_add_distrib] + | mul_X p i hp => + simp only [map_mul, aeval_X, Derivation.leibniz, smul_eq_mul, map_add, hp, + add_mul, mul_assoc, Finset.sum_add_distrib, ← Finset.mul_sum] + simp [Pi.single_apply, apply_ite] + +/-- Evaluates `aeval a (pderiv j (G i))` at the input `i j`. -/ +noncomputable def jacobian (G : ι → MvPolynomial ι F) (a : ι → K) : Matrix ι ι K := + fun i j => aeval a (pderiv j (G i)) + +theorem isUnit_jacobian [CharZero K] [Fintype ι] [DecidableEq ι] + (G : ι → MvPolynomial ι F) (a : ι → K) + (ha : AlgebraicIndependent F (fun i => aeval a (G i))) : + IsUnit (jacobian G a) := by + apply Matrix.mulVec_surjective_iff_isUnit.mp + intro v + obtain ⟨D, hD⟩ := derivation_of_independent ha v + refine ⟨fun j => D (a j), funext fun i => ?_⟩ + exact (derivation_aeval D a (G i)).symm.trans (hD i) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +section +/- +# Normalization over the parameter + +The integral closure of the parameter algebra in the function field is Dedekind. +It is contained in the integral closure of the original affine algebra, so +points above the original algebra restrict to points on this model. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open scoped IntermediateField.algebraAdjoinAdjoin + +theorem curve {K E : Type*} [Field K] [Field E] [Algebra K E] [CharZero K] + (R : Subalgebra K E) [IsFractionRing R E] (fg : R.FG) (t : R) + (alg : Algebra.IsAlgebraic (IntermediateField.adjoin K {(t : E)}) E) : + ∃ B : Subalgebra K E, B.FG ∧ B ≤ (integralClosure R E).restrictScalars K ∧ + (t : E) ∈ B ∧ IsFractionRing B E ∧ IsDedekindDomain B := by + classical + let A := Algebra.adjoin K {(t : E)} + let F := IntermediateField.adjoin K {(t : E)} + have : IsPrincipalIdealRing A := by + unfold A + rw [Algebra.adjoin_singleton_eq_range_aeval] + let f := Polynomial.aeval (R := K) (t : E) + exact IsPrincipalIdealRing.of_surjective f.rangeRestrict f.rangeRestrict_surjective + have : Algebra.FiniteType K R := R.fg_iff_finiteType.mp fg + have : Algebra.EssFiniteType R E := .of_isLocalization E (nonZeroDivisors R) + have : Algebra.EssFiniteType K E := .comp K R E + have : Algebra.EssFiniteType F E := .of_comp K F E + have : Algebra.IsAlgebraic F E := alg + have : Module.Finite F E := Algebra.finite_of_essFiniteType_of_isAlgebraic + let C := integralClosure A E + have : Module.Finite A C := IsIntegralClosure.finite A F E C + have ft : Algebra.FiniteType K C := + (Algebra.FiniteType.adjoin_of_finite (Set.finite_singleton (t : E))).trans + (inferInstance : Algebra.FiniteType A C) + refine ⟨C.restrictScalars K, (Subalgebra.fg_iff_finiteType _).mpr ft, ?_, ?_, + IsIntegralClosure.isFractionRing_of_finite_extension A F E C, + integralClosure.isDedekindDomain A F E⟩ + · have h : A ≤ R := Algebra.adjoin_le (Set.singleton_subset_iff.mpr t.property) + let _ := (Subalgebra.inclusion h).toAlgebra + have : IsScalarTower A R E := Subalgebra.inclusion.isScalarTower_right h E + exact fun x hx => (show IsIntegral A x from hx).tower_top + · exact isIntegral_algebraMap (R := A) (A := E) + (x := ⟨(t : E), Algebra.self_mem_adjoin_singleton K (t : E)⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # The branch parameters of a discrete valuation ring -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open IsDiscreteValuationRing + +variable {K E : Type*} [Field K] [Field E] [Algebra K E] + (O : Subalgebra K E) [IsFractionRing O E] [IsDiscreteValuationRing O] + +theorem mem_or_inv (x : E) : x ∈ O ∨ x⁻¹ ∈ O := by + rcases ValuationRing.isInteger_or_isInteger O x with ⟨y, hy⟩ | ⟨y, hy⟩ + · exact Or.inl (hy ▸ y.property) + · exact Or.inr (hy ▸ y.property) + +theorem clear_denominator (π : O) (hirr : Irreducible π) (x : E) : + ∃ m : ℕ, (π : E) ^ m * x ∈ O := by + obtain ⟨a, b, hb, he⟩ := IsFractionRing.div_surjective O x + have hb' : b ≠ 0 := nonZeroDivisors.ne_zero hb + obtain ⟨m, u, hu⟩ := eq_unit_mul_pow_irreducible hb' hirr + have hf : π ^ m = (u⁻¹ : Oˣ).val * b := by rw [hu]; simp + have ht : (π : E) ^ m = ((u⁻¹ : Oˣ).val : E) * (b : E) := congrArg Subtype.val hf + refine ⟨m, ?_⟩ + change (a : E) / (b : E) = x at he + rw [ht, ← he, mul_assoc, mul_div_cancel₀ _ (show (b : E) ≠ 0 by simpa)] + exact O.mul_mem (u⁻¹ : Oˣ).val.property a.property + +/-- In the case `zero`, this construction gives `have ht : IsUnit t := by rw [hu, pow_zero, +mul_one]; exact u.isUnit`. -/ +def discreteBranch (φ : O →ₐ[K] K) (t : O) (hne : t ≠ 0) (hz : φ t = 0) + (gen : ∃ B : Subalgebra K E, B.FG ∧ B ≤ O ∧ + ∀ x : O, ∃ a b : B, (b : E)⁻¹ ∈ O ∧ (x : E) = (a : E) / (b : E)) : Branch K E (t : E) := by + let π := (exists_irreducible O).choose + have hirr : Irreducible π := (exists_irreducible O).choose_spec + have hker : RingHom.ker φ = Ideal.span {π} := + (IsLocalRing.eq_maximalIdeal (RingHom.ker_isMaximal_of_surjective φ + (fun x => ⟨algebraMap K O x, by simp⟩))).trans ((irreducible_iff_uniformizer π).mp hirr) + refine ⟨O, φ, mem_or_inv O, π, by simpa using hirr.ne_zero, ?_, ?_, ?_, + clear_denominator O π hirr, gen⟩ + · change π ∈ RingHom.ker φ + rw [hker, Ideal.mem_span_singleton] + · intro x + have hx : x - algebraMap K O (φ x) ∈ RingHom.ker φ := by simp + rw [hker, Ideal.mem_span_singleton] at hx + obtain ⟨b, hb⟩ := hx + exact ⟨b, congrArg Subtype.val (sub_eq_iff_eq_add'.mp hb)⟩ + · obtain ⟨m, u, hu⟩ := eq_unit_mul_pow_irreducible hne hirr + cases m with + | zero => + have ht : IsUnit t := by rw [hu, pow_zero, mul_one]; exact u.isUnit + exact ((ht.map φ).ne_zero hz).elim + | succ m => + rw [mul_comm] at hu + exact ⟨m, u, congrArg Subtype.val hu⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Ray.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Ray.lean new file mode 100644 index 0000000000..221b274aa8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/Ray.lean @@ -0,0 +1,676 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.RingTheory.Nullstellensatz +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Algebra.BigOperators.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Cuts +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Jacobian +public import Mathlib.RingTheory.Spectrum.Prime.Chevalley +public import Mathlib.RingTheory.Spectrum.Prime.Noetherian +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Root +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Multi.Radial + +/-! +# Products of prime polynomial ideals over an algebraically closed field + +Work in the quotient by the block equations. Finite linear elimination +and the Nullstellensatz permit replacing a rational point of a block +by any solution in this quotient. Thus vanishing on the product detects +membership in the sum of the ideals, before knowing it is radical. +-/ + +universe u + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +variable {K J : Type*} [Field K] {W : J → Type*} + +/-- Transforms the indexed data by `⨆ j, (P j).map (rename (Sigma.mk j))`. -/ +def productIdeal (P : ∀ j, Ideal (MvPolynomial (W j) K)) : Ideal (MvPolynomial (Sigma W) K) := + ⨆ j, (P j).map (rename (Sigma.mk j)) + +namespace BlockProduct +variable {Z R : Type*} [CommRing R] [Algebra K R] + +private theorem point [IsAlgClosed K] [Finite Z] (P : Ideal (MvPolynomial Z K)) [P.IsPrime] + (p : MvPolynomial Z K) (hp : p ∉ P) : ∃ x ∈ zeroLocus K P, aeval x p ≠ 0 := by + by_contra! h + apply hp + rw [← MvPolynomial.IsPrime.vanishingIdeal_zeroLocus (K := K) P] + exact h + +private def specialize (x : Z → K) : MvPolynomial Z K →ₐ[K] R := + (Algebra.ofId K R).comp (aeval x) + +/-- Change the evaluation of an isolated block of variables. Eliminate +one coefficient at a time by evaluating it at a point where it survives. -/ +private theorem eliminate [IsAlgClosed K] [Finite Z] (P : Ideal (MvPolynomial Z K)) [P.IsPrime] + (φ : MvPolynomial Z K →ₐ[K] R) (hφ : ∀ u ∈ P, φ u = 0) + (n : ℕ) (u : Fin n → MvPolynomial Z K) (w : Fin n → R) + (h : ∀ x ∈ zeroLocus K P, ∑ i, specialize x (u i) * w i = 0) : + ∑ i, φ (u i) * w i = 0 := by + induction n with + | zero => simp + | succ n ih => + by_cases hm : u 0 ∈ P + · rw [Fin.sum_univ_succ, hφ _ hm, zero_mul, zero_add] + apply ih + intro x hx + have he : specialize (R := R) x (u 0) = 0 := by + change algebraMap K R (aeval x (u 0)) = 0 + rw [hx _ hm, map_zero] + simpa only [Fin.sum_univ_succ, he, zero_mul, zero_add] using h x hx + obtain ⟨x, hx, hn⟩ := point P _ hm + let c (i : Fin n) := -(aeval x (u 0))⁻¹ * aeval x (u i.succ) + have e : w 0 = ∑ i : Fin n, algebraMap K R (c i) * w i.succ := by + have H := h x hx + rw [Fin.sum_univ_succ] at H + simp only [c, map_mul, map_neg, mul_assoc, ← Finset.mul_sum] + change w 0 = -algebraMap K R (aeval x (u 0))⁻¹ * ∑ i : Fin n, + specialize x (u i.succ) * w i.succ + rw [eq_neg_of_add_eq_zero_right H, neg_mul_neg, ← mul_assoc] + change w 0 = (algebraMap K R (aeval x (u 0))⁻¹ * algebraMap K R (aeval x (u 0))) * w 0 + rw [← map_mul, inv_mul_cancel₀ hn, map_one, one_mul] + let u' (i : Fin n) := u 0 * C (c i) + u i.succ + have H (ψ : MvPolynomial Z K →ₐ[K] R) : + (∑ i, ψ (u i) * w i) = ∑ i, ψ (u' i) * w i.succ := by + rw [Fin.sum_univ_succ, e, Finset.mul_sum, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + rw [show u' i = _ from rfl, map_add ψ, map_mul ψ, ← algebraMap_eq, ψ.commutes, add_mul, + mul_assoc] + rw [H] + exact ih _ _ fun z hz => (H _).symm.trans (h z hz) + +private def total (x : ∀ j, W j → R) : MvPolynomial (Sigma W) K →ₐ[K] R := + aeval (fun i => x i.1 i.2) + +variable [DecidableEq J] + +private def plug (x : ∀ j, W j → R) (j : J) (φ : MvPolynomial (W j) K →ₐ[K] R) := + total (K := K) (Function.update x j (fun v => φ (X v))) + +private theorem expand (x : ∀ j, W j → R) (j : J) (p : MvPolynomial (Sigma W) K) : + ∃ (n : ℕ) (u : Fin n → MvPolynomial (W j) K) (w : Fin n → R), + ∀ φ : MvPolynomial (W j) K →ₐ[K] R, plug x j φ p = ∑ i, φ (u i) * w i := by + induction p using MvPolynomial.induction_on with + | C a => + exact ⟨1, fun _ => 1, fun _ => algebraMap K R a, fun _ => by simp [plug, total]⟩ + | add a b ha hb => + obtain ⟨n, u, w, hu⟩ := ha + obtain ⟨m, v, t, hv⟩ := hb + refine ⟨n + m, Fin.append u v, Fin.append w t, fun φ => ?_⟩ + rw [map_add, hu, hv, Fin.sum_univ_add] + simp only [Fin.append_left, Fin.append_right] + | mul_X a i ha => + obtain ⟨n, u, w, hu⟩ := ha + obtain ⟨i, v⟩ := i + by_cases h : i = j + · subst i + refine ⟨n, fun i => u i * X v, w, fun φ => ?_⟩ + rw [map_mul, hu, Finset.sum_mul] + simp only [plug, total, aeval_X, Function.update_self, map_mul] + exact Finset.sum_congr rfl fun _ _ => mul_right_comm _ _ _ + · refine ⟨n, u, fun t => w t * x i v, fun φ => ?_⟩ + rw [map_mul, hu, Finset.sum_mul] + simp only [plug, total, aeval_X, Function.update_of_ne h, mul_assoc] + +variable (P : ∀ j, Ideal (MvPolynomial (W j) K)) + +private abbrev Points := ∀ j, ↥(zeroLocus K (P j)) + +private def ev (x : Points P) : MvPolynomial (Sigma W) K →ₐ[K] K := + total (fun j => (x j).val) + +omit [DecidableEq J] in +private theorem ev_rename (x : Points P) (j : J) (f : MvPolynomial (W j) K) : + ev P x (rename (Sigma.mk j) f) = aeval (x j).val f := aeval_rename _ _ _ + +omit [DecidableEq J] in +private theorem ev_zero (x : Points P) {p : MvPolynomial (Sigma W) K} (hp : p ∈ productIdeal P) : + ev P x p = 0 := by + have h : productIdeal P ≤ RingHom.ker (ev P x) := by + refine iSup_le fun j => Ideal.map_le_iff_le_comap.mpr fun f hf => ?_ + exact (ev_rename P x j f).trans ((x j).property f hf) + exact h hp + +variable [IsAlgClosed K] [∀ j, Finite (W j)] (hP : ∀ j, (P j).IsPrime) +include hP + +omit [DecidableEq J] in +private theorem inhabited : Nonempty (Points P) := by + have h (j : J) : (zeroLocus K (P j)).Nonempty := by + let _ := hP j + obtain ⟨x, hx, _⟩ := point (P j) 1 (hP j).one_notMem + exact ⟨x, hx⟩ + exact ⟨fun j => ⟨(h j).choose, (h j).choose_spec⟩⟩ + +variable [Fintype J] + +omit [DecidableEq J] [Fintype J] in +private theorem vanishes [Finite J] (p : MvPolynomial (Sigma W) K) (hp : ∀ x, ev P x p = 0) : + p ∈ productIdeal P := by + classical + let : Fintype J := Fintype.ofFinite J + let R := MvPolynomial (Sigma W) K ⧸ productIdeal P + let f := Ideal.Quotient.mkₐ K (productIdeal P) + let φ (j : J) := f.comp (rename (Sigma.mk j)) + have hφ (j : J) (p : MvPolynomial (W j) K) (h : p ∈ P j) : φ j p = 0 := + Ideal.Quotient.eq_zero_iff_mem.mpr + ((le_iSup (fun j => (P j).map (rename (Sigma.mk j))) j) (Ideal.mem_map_of_mem _ h)) + let X' (s : Finset J) (x : Points P) (j : J) (t : W j) : R := + if j ∈ s then φ j (X t) else algebraMap K R ((x j).val t) + have H (s : Finset J) (x : Points P) : total (X' s x) p = 0 := by + induction s using Finset.induction_on generalizing x with + | empty => + have e : total (X' ∅ x) = (Algebra.ofId K R).comp (ev P x) := by + apply algHom_ext + rintro ⟨j, t⟩ + simp [total, ev, X'] + rw [e, AlgHom.comp_apply, hp, map_zero] + | @insert j s hj ih => + let _ := hP j + obtain ⟨n, u, w, he⟩ := expand (X' s x) j p + have e : total (X' (insert j s) x) = plug (X' s x) j (φ j) := by + unfold plug + apply congrArg + funext k t + by_cases h : k = j + · subst k; simp [X'] + · simp [X', h] + rw [e, he] + refine eliminate (P j) (φ j) (hφ j) n u w fun y hy => ?_ + rw [← he] + let z := Function.update x j (⟨y, hy⟩ : zeroLocus K (P j)) + have h : plug (X' s x) j (specialize y) = total (X' s z) := by + unfold plug + apply congrArg + funext k t + by_cases h : k = j + · subst k; simp [X', z, hj, specialize] + · simp [X', z, h] + rw [h, ih] + obtain ⟨x⟩ := inhabited P hP + have e : total (X' Finset.univ x) = f := by + apply algHom_ext + rintro ⟨j, t⟩ + simp [X', total, φ] + apply Ideal.Quotient.eq_zero_iff_mem.mp + change f p = 0 + rw [← e, H] + +omit [IsAlgClosed K] [∀ j, Finite (W j)] [Fintype J] hP in +private theorem section_eval (x : Points P) (j : J) (p : MvPolynomial (Sigma W) K) : + ∃ q : MvPolynomial (W j) K, ∀ y : zeroLocus K (P j), + ev P (Function.update x j y) p = aeval y.val q := by + obtain ⟨n, u, w, he⟩ := expand (fun i => (x i).val) j p + refine ⟨∑ i, u i * C (w i), fun y => ?_⟩ + have e : ev P (Function.update x j y) = plug (fun i => (x i).val) j (aeval y.val) := by + unfold ev plug + apply congrArg + funext k t + by_cases h : k = j + · subst k; simp + · simp [h] + rw [e, he] + simp + +omit [DecidableEq J] [Fintype J] in +/-- Move a pair of nonvanishing witnesses together, one block at a time. -/ +private theorem common [Finite J] (p q : MvPolynomial (Sigma W) K) (x y : Points P) + (hx : ev P x p ≠ 0) (hy : ev P y q ≠ 0) : ∃ z, ev P z (p * q) ≠ 0 := by + classical + let : Fintype J := Fintype.ofFinite J + have H (s : Finset J) : ∃ x y : Points P, + ev P x p ≠ 0 ∧ ev P y q ≠ 0 ∧ ∀ i ∈ s, x i = y i := by + induction s using Finset.induction_on with + | empty => exact ⟨x, y, hx, hy, by simp⟩ + | @insert j s hj ih => + obtain ⟨x, y, hx, hy, e⟩ := ih + obtain ⟨u, hu⟩ := section_eval P x j p + obtain ⟨w, hw⟩ := section_eval P y j q + have h₁ : u ∉ P j := by + intro h + apply hx + simpa using (hu (x j)).trans ((x j).property _ h) + have h₂ : w ∉ P j := by + intro h + apply hy + simpa using (hw (y j)).trans ((y j).property _ h) + let _ := hP j + obtain ⟨z, hz, he⟩ := point (P j) (u * w) (fun h => ((hP j).mem_or_mem h).elim h₁ h₂) + let a : zeroLocus K (P j) := ⟨z, hz⟩ + rw [map_mul] at he + refine ⟨Function.update x j a, Function.update y j a, ?_, ?_, ?_⟩ + · rw [hu]; exact left_ne_zero_of_mul he + · rw [hw]; exact right_ne_zero_of_mul he + · intro i hi + rcases Finset.mem_insert.mp hi with rfl | hi + · simp + · have h : i ≠ j := fun he => hj (he ▸ hi) + simpa [h] using e i hi + obtain ⟨x, y, hx, hy, e⟩ := H Finset.univ + have h : x = y := funext fun i => e i (Finset.mem_univ _) + subst y + exact ⟨x, by rw [map_mul]; exact mul_ne_zero hx hy⟩ + +end BlockProduct +open BlockProduct +variable [IsAlgClosed K] [∀ j, Finite (W j)] (P : ∀ j, Ideal (MvPolynomial (W j) K)) + (hP : ∀ j, (P j).IsPrime) + +include hP + +/-- The sum of prime ideals on disjoint polynomial blocks is prime. -/ +theorem productIdeal_prime [Finite J] : (productIdeal P).IsPrime := by + classical + let _ := Fintype.ofFinite J + obtain ⟨x⟩ := inhabited P hP + constructor + · intro h + have hh := ev_zero P x (show 1 ∈ productIdeal P by rw [h]; trivial) + simp at hh + · intro p q h + by_contra! hn + obtain ⟨x, hx⟩ := not_forall.mp (mt (vanishes P hP p) hn.1) + obtain ⟨y, hy⟩ := not_forall.mp (mt (vanishes P hP q) hn.2) + obtain ⟨z, hz⟩ := common P hP p q x y hx hy + exact hz (ev_zero P z h) + +/-- The product equations impose no new relations within a single block. -/ +theorem productIdeal_comap (j : J) : (productIdeal P).comap (rename (Sigma.mk j)) = P j := by + classical + let _ := hP j + refine le_antisymm ?_ (Ideal.map_le_iff_le_comap.mp (le_iSup (fun j + => (P j).map (rename (Sigma.mk j))) j)) + intro p hp + by_contra h + obtain ⟨z, hz, hn⟩ := point (P j) p h + obtain ⟨x⟩ := inhabited P hP + let y := Function.update x j (⟨z, hz⟩ : zeroLocus K (P j)) + have he := ev_zero P y (show rename (Sigma.mk j) p ∈ productIdeal P from hp) + rw [ev_rename] at he + apply hn + simpa [y] using he + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Local dimension of systems with shared coordinates + +Separate the common coordinates and impose equality to the first +copy. If every factor had a long prime chain through the point, +their product would have a chain longer than the number of these +diagonal equations. The remaining short factor admits rational cuts. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +variable {K : Type*} [Field K] {J Z : Type} {W : J → Type} + +open scoped Classical in +private theorem mono_product : Monotone (productIdeal (K := K) (W := W)) := by + intro p q h + exact iSup_mono fun i => Ideal.map_mono (h i) + +open scoped Classical in +private theorem point_product (w : ∀ j, W j → K) : + productIdeal (fun j => maxPoint (w j)) ≤ maxPoint (fun t : Sigma W => w t.1 t.2) := by + refine iSup_le fun j => Ideal.map_le_iff_le_comap.mpr fun p hp => ?_ + change eval (fun t : Sigma W => w t.1 t.2) (rename (Sigma.mk j) p) = 0 + rw [eval_rename] + exact hp + +open scoped Classical in +private theorem lengths [IsAlgClosed K] [Fintype J] [∀ j, Finite (W j)] + (I : ∀ j, Ideal (MvPolynomial (W j) K)) (w : ∀ j, W j → K) {B : Type} [Fintype B] + (y : B → MvPolynomial (Sigma W) K) + (h : Isolated (fun t : Sigma W => w t.1 t.2) (productIdeal I ⊔ Ideal.span (Set.range y))) + {n : ℕ} (hc : ∀ j, ∃ p, I j ≤ p ∧ Chain p (maxPoint (w j)) n) : + Fintype.card J * n ≤ Fintype.card B := by + let : ∀ j, Fintype (W j) := fun j => Fintype.ofFinite (W j) + choose p hp hchain using hc + have he (u v : ∀ j, Ideal (MvPolynomial (W j) K)) + (hu : ∀ j, (u j).IsPrime) (hv : ∀ j, (v j).IsPrime) (he : productIdeal u + = productIdeal v) : u = v := by + funext j + rw [← productIdeal_comap u hu j, ← productIdeal_comap v hv j, he] + have chain := Chain.product productIdeal mono_product (fun u hu => productIdeal_prime u hu) he + (fun j => RingHom.ker_isPrime (eval (w j))) hchain + exact (chain.weaken (point_product w)).equations y h (mono_product hp) + +open scoped Classical in +private theorem threshold (L N : ℕ) (h : 0 < L) : + ∃ d ≤ N, N ≤ L * (N - d) ∧ (L - 1) * N < L * (d + 1) := by + let A := (L - 1) * N + let d := A / L + have hd : L * d ≤ A := Nat.mul_div_le A L + have ht : A < (d + 1) * L := (Nat.div_lt_iff_lt_mul h).mp (Nat.lt_succ_self d) + have ha : A + N = L * N := by + unfold A + rw [← Nat.succ_mul, show (L - 1).succ = L by omega] + refine ⟨d, Nat.le_of_mul_le_mul_left (hd.trans (by omega)) h, ?_, ?_⟩ + · rw [Nat.mul_sub_left_distrib]; omega + · rwa [mul_comm L] + +open scoped Classical in +theorem local_cut [CharZero K] [IsAlgClosed K] [Fintype J] [Fintype Z] + [∀ j, Finite (W j)] [Nonempty J] + (I : ∀ j, Ideal (MvPolynomial (Z ⊕ W j) K)) (β : Z → K) (w : ∀ j, W j → K) + (joint : Isolated (Sum.elim β (fun x => w x.1 x.2)) (diagonalIdeal I)) + (fiber : ∀ j, Isolated (Sum.elim β (w j)) (I j ⊔ Ideal.span (Set.range (offset β)))) : + ∃ (j : J) (d : ℕ), d ≤ Fintype.card Z ∧ Fintype.card Z ≤ Fintype.card J * (Fintype.card Z - d) ∧ + ∃ A : Fin d → Z → ℚ, Isolated (Sum.elim β (w j)) + (I j ⊔ Ideal.span (Set.range (fun t => comb (offset β) (A t)))) := by + obtain ⟨d, hd, hsize, hmax⟩ := threshold (Fintype.card J) (Fintype.card Z) Fintype.card_pos + have ex : ∃ j, ∀ p, I j ≤ p → ¬Chain p (maxPoint (Sum.elim β (w j))) (d + 1) := by + by_contra! hh + let k := Classical.arbitrary J + have hc := lengths I (fun j => Sum.elim β (w j)) (difference k) (joint.separate k) hh + have he : Fintype.card {j // j ≠ k} = Fintype.card J - 1 := by simp + rw [Fintype.card_prod, he] at hc + exact hmax.not_ge hc + obtain ⟨j, hj⟩ := ex + exact ⟨j, d, hd, hsize, cut _ _ (fiber j) hj⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# A coordinate projection missing an infinite subfield + +Chevalley's theorem makes the image constructible in the prime spectrum +of the polynomial ring in one variable. The Nullstellensatz identifies +its rational points. Each basic constructible piece has finite or +cofinite rational points. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open PrimeSpectrum Topology +variable {K W : Type*} [Field K] + +private def polyPoint (x : K) : PrimeSpectrum (Polynomial K) := + ⟨RingHom.ker (Polynomial.evalRingHom x), RingHom.ker_isPrime _⟩ + +private def coord (i : W) : Polynomial K →+* MvPolynomial W K := + (Polynomial.aeval (MvPolynomial.X i)).toRingHom + +private theorem presented [Finite W] (i : W) : (coord (K := K) i).FinitePresentation := by + apply RingHom.FinitePresentation.of_finiteType.mp + apply RingHom.FiniteType.of_comp_finiteType (f := algebraMap K (Polynomial K)) + have he : (coord i).comp (algebraMap K (Polynomial K)) = algebraMap K (MvPolynomial W K) := by + ext1 t + exact AlgHom.commutes (Polynomial.aeval (MvPolynomial.X i : MvPolynomial W K)) t + rw [he, RingHom.finiteType_algebraMap] + infer_instance + +private theorem eval_coord (i : W) (x : W → K) (f : Polynomial K) : + MvPolynomial.eval x (coord i f) = f.eval (x i) := by + have h := Polynomial.aeval_algHom_apply (MvPolynomial.aeval x) (MvPolynomial.X i) f + simpa [coord, MvPolynomial.aeval_eq_eval] using h.symm + +private theorem projected [Finite W] [IsAlgClosed K] (P : Set (MvPolynomial W K)) (i : W) (t : K) : + polyPoint t ∈ comap (coord i) '' zeroLocus P ↔ + ∃ x : W → K, (∀ p ∈ P, MvPolynomial.eval x p = 0) ∧ x i = t := by + constructor + · rintro ⟨q, hq, he⟩ + obtain ⟨m, hm, hle⟩ := Ideal.exists_le_maximal q.asIdeal q.isPrime.ne_top + obtain ⟨x, hx⟩ := MvPolynomial.eq_vanishingIdeal_singleton_of_isMaximal K hm + have h (p) (hp : p ∈ q.asIdeal) : MvPolynomial.eval x p = 0 := by + have h := hle hp + rw [hx, MvPolynomial.mem_vanishingIdeal_singleton_iff, MvPolynomial.aeval_eq_eval] at h + exact h + refine ⟨x, fun p hp => h p (hq hp), ?_⟩ + let f := Polynomial.X - Polynomial.C t + have hf : f ∈ (comap (coord i) q).asIdeal := by + rw [he] + change f.eval t = 0 + simp [f] + have hh := h (coord i f) hf + simpa [eval_coord, f, sub_eq_zero] using hh + · rintro ⟨x, hx, rfl⟩ + let q : PrimeSpectrum (MvPolynomial W K) := + ⟨RingHom.ker (MvPolynomial.eval x), RingHom.ker_isPrime _⟩ + refine ⟨q, fun p hp => hx p hp, PrimeSpectrum.ext ?_⟩ + ext f + change MvPolynomial.eval x (coord i f) = 0 ↔ f.eval (x i) = 0 + rw [eval_coord] + +private theorem constructible_projection [Finite W] (P : Set (MvPolynomial W K)) (i : W) : + IsConstructible (comap (coord i) '' zeroLocus P) := by + apply isConstructible_comap_image (presented i) + have hc := (isClosed_zeroLocus P).isOpen_compl + have h : IsRetrocompact (zeroLocus P)ᶜ := fun _ _ _ + => TopologicalSpace.NoetherianSpace.isCompact _ + simpa using (h.isConstructible hc).compl + +private theorem basic_thin (s : BasicConstructibleSetData (Polynomial K)) (T : Set K) + (ht : T.Infinite) (h : ∀ x ∈ T, polyPoint x ∉ s.toSet) : + (polyPoint ⁻¹' s.toSet).Finite := by + classical + by_cases hx : ∃ j, s.g j ≠ 0 + · obtain ⟨j, hj⟩ := hx + apply (Polynomial.finite_setOfPred_isRoot hj).subset + intro y hy + exact hy.1 ⟨j, rfl⟩ + push Not at hx + have hf : s.f = 0 := by + by_contra he + apply ht + refine (Polynomial.finite_setOfPred_isRoot he).subset (fun x hxt => ?_) + by_contra hn + apply h x hxt + constructor + · rintro _ ⟨j, rfl⟩ + rw [hx] + exact (polyPoint x).asIdeal.zero_mem + · exact fun hh => hn (hh (Set.mem_singleton _)) + apply Set.finite_empty.subset + intro x h + apply h.2 + rintro _ rfl + rw [hf] + exact (polyPoint x).asIdeal.zero_mem + +/-- If the projected rational points avoid an infinite set, their +coordinate assumes only finitely many values. -/ +theorem finite_projection [Finite W] [IsAlgClosed K] (P : Set (MvPolynomial W K)) (i : W) + (T : Set K) (ht : T.Infinite) (ha : ∀ x, (∀ p ∈ P, MvPolynomial.eval x p = 0) → x i ∉ T) : + {t | ∃ x : W → K, (∀ p ∈ P, MvPolynomial.eval x p = 0) ∧ x i = t}.Finite := by + obtain ⟨D, hD⟩ := exists_constructibleSetData_iff.mpr (constructible_projection P i) + have hs : (polyPoint ⁻¹' D.toSet).Finite := by + simp only [ConstructibleSetData.toSet, Set.preimage_iUnion] + apply D.finite_toSet.biUnion + intro s hs + apply basic_thin s T ht + intro t ht' he + have hz : polyPoint t ∈ D.toSet := Set.mem_iUnion₂.mpr ⟨s, hs, he⟩ + rw [hD, projected] at hz + obtain ⟨x, hx, rfl⟩ := hz + exact ha x hx ht' + rw [hD] at hs + exact hs.subset (fun t hx => (projected P i t).mpr hx) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# The field along a generic ray + +Specializing the scaling parameter to one proves independence. +Over the field generated by the parameter, every derivation kills +the given polynomial values. The Jacobian then forces it to kill +all the generating coordinates. In characteristic zero this excludes +any further transcendental element. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial +variable {K L E : Type u} [Field K] [Field L] [Field E] + [Algebra K L] [Algebra L E] [Algebra K E] [IsScalarTower K L E] + {σ : Type} {c : σ → L} (hc : AlgebraicIndependent K c) + {t : E} (ht : Transcendental L t) {a : σ → E} {G : σ → MvPolynomial σ K} + (h : ∀ i, aeval a (G i) = t * algebraMap L E (c i)) + +include hc ht h in +theorem independent_ray : AlgebraicIndependent K (fun i => aeval a (G i)) := by + let P := aeval (R := K) (fun i => Polynomial.X * Polynomial.C (c i)) + have param : ((Polynomial.aeval t).restrictScalars K).comp P = + aeval (fun i => aeval a (G i)) := by + ext i + simp [P, h] + ring + have one : ((Polynomial.aeval (1 : L)).restrictScalars K).comp P = aeval c := by + ext i + simp [P] + rw [algebraicIndependent_iff_injective_aeval, ← param] + intro x y he + have he' : P x = P y := (transcendental_iff_injective.mp ht) he + apply algebraicIndependent_iff_injective_aeval.mp hc + rw [← one] + exact congrArg (Polynomial.aeval (1 : L)) he' + +include hc ht h in +theorem algebraic_ray [Finite σ] [CharZero E] + (ha : IntermediateField.adjoin L (insert t (Set.range a)) = ⊤) : + Algebra.IsAlgebraic (IntermediateField.adjoin L {t}) E := by + classical + let : Fintype σ := Fintype.ofFinite σ + let M := IntermediateField.adjoin L {t} + have unit := isUnit_jacobian G a (independent_ray hc ht h) + constructor + intro z + by_contra hz + have ind : AlgebraicIndependent M (fun _ : Unit => z) + := algebraicIndependent_unique_type_iff.mpr hz + obtain ⟨d, hd⟩ := derivation_of_independent ind (fun _ => 1) + let D := d.restrictScalars L + have hdt : D t = 0 := d.map_algebraMap (⟨t, IntermediateField.subset_adjoin L _ (by simp)⟩ : M) + have eval (i : σ) : D (aeval a (G i)) = 0 := by + rw [h, D.leibniz, hdt, D.map_algebraMap, smul_zero, smul_zero, add_zero] + have killed : (fun i => D (a i)) = 0 := by + apply Matrix.mulVec_injective_iff_isUnit.mpr unit + rw [Matrix.mulVec_zero] + funext i + exact (derivation_aeval (D.restrictScalars K) a (G i)).symm.trans (eval i) + have zero (z : E) (hm : z ∈ IntermediateField.adjoin L (insert t (Set.range a))) : D z = 0 := by + induction hm using IntermediateField.adjoin_induction with + | mem z hz => + rcases hz with rfl | ⟨j, rfl⟩ + · exact hdt + · exact congrFun killed j + | algebraMap z => exact D.map_algebraMap z + | add z w _ _ hz hw => rw [map_add, hz, hw, add_zero] + | inv z _ hz => rw [D.leibniz_inv, hz, smul_zero] + | mul z w _ _ hz hw => rw [D.leibniz, hz, hw, smul_zero, smul_zero, add_zero] + exact one_ne_zero ((hd ()).symm.trans (zero z (by rw [ha]; trivial))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # A finite, nonempty slice by base-field coordinate equations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +variable {F K W : Type*} [Field F] [Field K] [Algebra F K] + +open scoped Classical in +/-- The indexing data represented by `{x | (∀ p ∈ P, MvPolynomial.eval x p = 0) ∧ ∀ j t, b j = +some t → x j = algebraMap F K t}`. -/ +def slice (P : Set (MvPolynomial W K)) (b : W → Option F) : Set (W → K) := + {x | (∀ p ∈ P, MvPolynomial.eval x p = 0) ∧ ∀ j t, b j = some t → x j = algebraMap F K t} + +open scoped Classical in +private def equations (P : Set (MvPolynomial W K)) (b : W → Option F) := + P ∪ {p | ∃ j t, b j = some t ∧ p = MvPolynomial.X j - MvPolynomial.C (algebraMap F K t)} + +open scoped Classical in +private theorem equations_iff (P : Set (MvPolynomial W K)) (b : W → Option F) (x : W → K) : + (∀ p ∈ equations P b, MvPolynomial.eval x p = 0) ↔ x ∈ slice P b := by + constructor + · intro h + refine ⟨fun p hp => h _ (.inl hp), fun j t ht => ?_⟩ + simpa [sub_eq_zero] using h _ (.inr ⟨j, t, ht, rfl⟩) + · rintro ⟨h, h'⟩ p (hp|⟨j, t, ht, rfl⟩) + · exact h _ hp + · simp [h' j t ht] + +open scoped Classical in +private theorem single_slice [Finite W] [Infinite F] [IsAlgClosed K] + (P : Set (MvPolynomial W K)) (b : W → Option F) (hb : (slice P b).Nonempty) (i : W) : + ∃ b' : W → Option F, (slice P b').Nonempty ∧ slice P b' ⊆ slice P b ∧ + ((fun x => x i) '' slice P b').Finite := by + by_cases hh : ∃ x ∈ slice P b, ∃ t, x i = algebraMap F K t + · obtain ⟨x, hx, t, ht⟩ := hh + let b' := Function.update b i (some t) + have he (y : W → K) (hy : y ∈ slice P b') : y i = x i := + (hy.2 i t (by simp [b'])).trans ht.symm + refine ⟨b', ⟨x, hx.1, ?_⟩, ?_, ?_⟩ + · intro j s hs + by_cases hj : j = i + · subst j + have : t = s := by simpa [b'] using hs + rwa [← this] + · exact hx.2 j s (by simpa [b', hj] using hs) + · intro y hy + refine ⟨hy.1, fun j s hs => ?_⟩ + by_cases hj : j = i + · subst j; exact (he y hy).trans (hx.2 i s hs) + · exact hy.2 j s (by simpa [b', hj] using hs) + · apply (Set.finite_singleton (x i)).subset + rintro _ ⟨y, hy, rfl⟩ + exact he y hy + · refine ⟨b, hb, Set.Subset.rfl, ?_⟩ + have hp := finite_projection (equations P b) i (Set.range (algebraMap F K)) + (Set.infinite_range_of_injective (algebraMap F K).injective) (by + rintro x hx ⟨t, ht⟩ + exact hh ⟨x, (equations_iff P b x).mp hx, t, ht.symm⟩) + refine hp.subset ?_ + rintro _ ⟨x, hx, rfl⟩ + exact ⟨x, (equations_iff P b x).mpr hx, rfl⟩ + +open scoped Classical in +/-- Fix a coordinate when possible. Otherwise its projection omits the +entire infinite subfield, hence is already finite. Later cuts can only +shrink the projections already controlled. -/ +theorem finite_slice (F : Type*) [Field F] [Infinite F] {K W : Type*} + [Field K] [Algebra F K] [IsAlgClosed K] [Finite W] (P : Set (MvPolynomial W K)) + (h : ∃ x, ∀ p ∈ P, MvPolynomial.eval x p = 0) : + ∃ b : W → Option F, (slice P b).Nonempty ∧ (slice P b).Finite := by + let _ := Fintype.ofFinite W + have step (s : Finset W) : ∃ b : W → Option F, (slice P b).Nonempty ∧ + ∀ i ∈ s, ((fun x => x i) '' slice P b).Finite := by + induction s using Finset.induction_on with + | empty => + obtain ⟨x, hx⟩ := h + exact ⟨fun _ => none, ⟨x, hx, by simp⟩, by simp⟩ + | @insert i s _ ih => + obtain ⟨b, hb, hs⟩ := ih + obtain ⟨b', hb', hle, hi⟩ := single_slice P b hb i + refine ⟨b', hb', fun j hj => ?_⟩ + rcases Finset.mem_insert.mp hj with rfl|hj + · exact hi + · exact (hs j hj).subset (Set.image_mono hle) + obtain ⟨b, hb, hs⟩ := step Finset.univ + exact ⟨b, hb, (Set.Finite.pi' (fun j => hs j (Finset.mem_univ _))).subset + (fun x hx _ => ⟨x, hx, rfl⟩)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/SimpleLift.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/SimpleLift.lean new file mode 100644 index 0000000000..53806da5b6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Geometry/SimpleLift.lean @@ -0,0 +1,1002 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Gaps +public import Mathlib.Algebra.MvPolynomial.Equiv +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Jacobian +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Cuts +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Ray +public import Mathlib.Tactic.LinearCombination +public import Mathlib.Algebra.MvPolynomial.Rename +public import Mathlib.Algebra.MvPolynomial.Funext + +/-! # Equations with at most one product of affine forms -/ + +universe u + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open scoped Classical in +/-- Indexes the affine by the coordinates of `F × (I → F)`. -/ +abbrev Affine (I : Type) (F : Type*) := F × (I → F) + +open scoped Classical in +/-- The data for the equation construction, including `left`, `right`, `value`. -/ +structure Equation (I : Type) (F : Type*) where + /-- The left-side data carried by `Equation`, with type `Affine I F`. -/ + left : Affine I F + /-- The right-side data carried by `Equation`, with type `Affine I F`. -/ + right : Affine I F + /-- The evaluation map carried by `Equation`, with type `Affine I F`. -/ + value : Affine I F + +variable {I : Type} [Fintype I] {F K : Type*} [Field F] [Field K] [Algebra F K] + +namespace Affine + +open scoped Classical in +/-- The quantity computed by `algebraMap F K a.1 + ∑ i, algebraMap F K (a.2 i) * x i`. -/ +def eval (a : Affine I F) (x : I → K) : K := + algebraMap F K a.1 + ∑ i, algebraMap F K (a.2 i) * x i + +open scoped Classical in +/-- The value specified by `(x, 0)`. -/ +def const (x : F) : Affine I F := (x, 0) +open scoped Classical in +/-- The value specified by `(0, fun j => if j = i then 1 else 0)`. -/ +def coord (i : I) : Affine I F := (0, fun j => if j = i then 1 else 0) + +open scoped Classical in +@[simp] theorem eval_const (z : F) (x : I → K) : (const z).eval x = algebraMap F K z := by + simp [eval, const] + +open scoped Classical in +@[simp] theorem eval_coord (i : I) (x : I → K) : (coord (F:=F) i).eval x = x i := by + simp [eval, coord, apply_ite] + +open scoped Classical in +@[simp] theorem eval_add (a b : Affine I F) (x : I → K) : + eval (a + b) x = a.eval x + b.eval x := by + simp [eval, add_mul, Finset.sum_add_distrib, add_add_add_comm] + +open scoped Classical in +@[simp] theorem eval_sub (a b : Affine I F) (x : I → K) : + eval (a - b) x = a.eval x - b.eval x := by + simp only [eval, Prod.fst_sub, Prod.snd_sub, Pi.sub_apply, map_sub, sub_mul, + Finset.sum_sub_distrib] + abel + +open scoped Classical in +/-- The quantity computed by `MvPolynomial.C a.1 + ∑ i, MvPolynomial.C (a.2 i) * MvPolynomial.X +i`. -/ +def poly (a : Affine I F) : MvPolynomial I F := + MvPolynomial.C a.1 + ∑ i, MvPolynomial.C (a.2 i) * MvPolynomial.X i + +open scoped Classical in +@[simp] theorem aeval_poly (a : Affine I F) (x : I → K) : + MvPolynomial.aeval x a.poly = a.eval x := by + simp [poly, eval] + +end Affine + +open scoped Classical in +/-- The quantity computed by `a.left.eval x * a.right.eval x = a.value.eval x`. -/ +def Equation.holds (a : Equation I F) (x : I → K) := a.left.eval x * a.right.eval x = a.value.eval x + +open scoped Classical in +/-- The quantity computed by `a.left.poly * a.right.poly - a.value.poly`. -/ +def Equation.poly (a : Equation I F) : MvPolynomial I F := + a.left.poly * a.right.poly - a.value.poly + +open scoped Classical in +theorem Equation.zero (a : Equation I F) (x : I → K) : + MvPolynomial.aeval x a.poly = 0 ↔ a.holds x := by + simp only [Equation.poly, map_sub, map_mul, Affine.aeval_poly, sub_eq_zero, holds] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Covering correct products by conjunctions of accepting paths + +For a given correct input, retain one path for each accepting seed. +Any input accepted by all of those paths has at least the same +accepting weight, so the strict gap forces it to be correct. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset + +open scoped Classical in +theorem packet_cover {F : Type*} [Field F] {n : ℕ} (hn : 0 < n) + {ι : Type*} {w : ι → ℝ} {S : Finset ι} {A : ι → Verifier F n} {c : ℝ} + (hw : ∀ i ∈ S, 0 ≤ w i) (hc : ∀ i ∈ S, (A i).cost c) + (gap : Gap w (fun i => (A i).accept) Correct S) : + ∃ B : Finset (Finset (Path F n)), + (∀ t ∈ B, 0 < t.card ∧ t.card ≤ S.card ∧ (∀ p ∈ t, (p.code.length : ℝ) ≤ c) ∧ + ∀ y, (∀ p ∈ t, p.accept y) → Correct y) ∧ + ∀ x, Correct x → ∃ t ∈ B, ∀ p ∈ t, p.accept x := by + let paths := S.biUnion fun i => (A i).toFinset + let sound (t : Finset (Path F n)) := ∀ y, (∀ p ∈ t, p.accept y) → Correct y + refine ⟨paths.powerset.filter (fun t => t.card ≤ S.card ∧ sound t), ?_, ?_⟩ + · intro t ht + obtain ⟨ht, hs, hy⟩ := mem_filter.mp ht + refine ⟨?_, hs, ?_, hy⟩ + · by_contra! he + have hempty : t = ∅ := card_eq_zero.mp (Nat.eq_zero_of_le_zero he) + let y : Index n → F := fun i => if i.1 = 2 then 1 else 0 + have h := hy y (by simp [hempty]) ⟨0, hn⟩ ⟨0, hn⟩ + simp [y] at h + · intro p hp + obtain ⟨i, hi, hp⟩ := mem_biUnion.mp (mem_powerset.mp ht hp) + exact hc i hi p (List.mem_toFinset.mp hp) + · intro x hx + let I := S.filter (fun i => (A i).accept x) + have ex (i : ↥I) : ∃ p ∈ A i.val, p.accept x := (mem_filter.mp i.property).2 + choose f hf ha using ex + let t := I.attach.image f + refine ⟨t, mem_filter.mpr ⟨mem_powerset.mpr ?_, ?_, ?_⟩, ?_⟩ + · intro p hp + obtain ⟨i, _, rfl⟩ := mem_image.mp hp + exact mem_biUnion.mpr ⟨i.val, (mem_filter.mp i.property).1, List.mem_toFinset.mpr (hf i)⟩ + · exact card_image_le.trans (card_attach.le.trans (card_filter_le ..)) + · intro y hy + by_contra hn + refine (gap x y hx hn).not_ge (sum_le_sum fun i hi => ?_) + by_cases he : (A i).accept x + · let j : ↥I := ⟨i, mem_filter.mpr ⟨hi, he⟩⟩ + have h : (A i).accept y := ⟨f j, hf j, hy _ (mem_image.mpr ⟨j, mem_attach _ _, rfl⟩)⟩ + simp [he, h] + · by_cases h : (A i).accept y <;> simp [he, h, hw i hi] + · intro p hp + obtain ⟨i, _, rfl⟩ := mem_image.mp hp + exact ha i + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Defined division and nonzero tests as product equations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +namespace Instruction +variable {I : Type} [Fintype I] {n t : ℕ} {F : Type*} [Field F] + +open scoped Classical in +/-- The two cases impose `True` and `False`, respectively. -/ +def needs : Instruction F n t → Prop + | .ne .. | .div .. => True + | _ => False + +open scoped Classical in +/-- In the case `.ne a b`, this construction gives `a.eval x w - b.eval x w`. -/ +def denominator (x : Index n → F) (w : Fin t → F) : Instruction F n t → F + | .ne a b => a.eval x w - b.eval x w + | .div _ b _ => b.eval x w + | _ => 1 + +variable (r : Operand F n t → Affine I F) (s : Affine I F) + +open scoped Classical in +/-- In the case `.eq a b`, this construction gives `[⟨r a, Affine.const 1, r b⟩]`. -/ +def emit : Instruction F n t → List (Equation I F) + | .eq a b => [⟨r a, Affine.const 1, r b⟩] + | .ne a b => [⟨r a - r b, s, Affine.const 1⟩] + | .op .add a b c => [⟨r a + r b, Affine.const 1, r c⟩] + | .op .sub a b c => [⟨r a - r b, Affine.const 1, r c⟩] + | .op .mul a b c => [⟨r a, r b, r c⟩] + | .div a b c => [⟨r c, r b, r a⟩, ⟨r b, s, Affine.const 1⟩] + +omit [Fintype I] in +open scoped Classical in +theorem emit_length (i : Instruction F n t) : (i.emit r s).length ≤ 2 := by + cases i <;> first | exact le_rfl | exact Nat.one_le_ofNat | rename_i f a b c; cases f + <;> exact one_le_two + +open scoped Classical in +theorem nonzero {x : Index n → F} {w : Fin t → F} (i : Instruction F n t) (hi : i.holds x w) : + i.denominator x w ≠ 0 := by + cases i with + | eq | op => exact one_ne_zero + | ne => exact sub_ne_zero.mpr hi + | div => exact hi.1 + +open scoped Classical in +theorem emit_iff (i : Instruction F n t) (x : Index n → F) (w : Fin t → F) (y : I → F) + (hr : ∀ a, (r a).eval y = a.eval x w) : + (∀ a ∈ i.emit r s, a.holds y) ↔ + i.holds x w ∧ (i.needs → i.denominator x w * s.eval y = 1) := by + have nz (a : F) (ha : a * s.eval y = 1) : a ≠ 0 := fun h => by simp [h] at ha + cases i with + | eq a b => simp [emit, holds, Equation.holds, needs, hr] + | op f a b c => cases f <;> simp [emit, holds, Op.eval, Equation.holds, needs, hr] + | ne a b => + simp only [emit, List.mem_singleton, forall_eq, Equation.holds, Affine.eval_sub, + Affine.eval_const, + map_one, hr, holds, needs, true_implies, denominator] + exact ⟨fun he => ⟨sub_ne_zero.mp (nz _ he), he⟩, And.right⟩ + | div a b c => + simp only [emit, List.forall_mem_cons, List.not_mem_nil, IsEmpty.forall_iff, implies_true, + and_true, + Equation.holds, Affine.eval_const, map_one, hr, holds, needs, true_implies, denominator] + exact ⟨fun ⟨he, hq⟩ => ⟨⟨nz _ hq, (div_eq_iff (nz _ hq)).mpr he.symm⟩, hq⟩, + fun ⟨⟨hn, he⟩, hq⟩ => ⟨((div_eq_iff hn).mp he).symm, hq⟩⟩ + +end Instruction +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# A polynomial system for one accepting path + +Only nonzero tests and quotients introduce extra inverse variables. +Projecting away those variables recovers the original path on every +assignment of the inputs and registers. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +namespace Path + +variable {F K : Type*} {n : ℕ} (p : Path F n) + +open scoped Classical in +/-- The subtype of `j : Fin p.code.length` satisfying `(p.code.get j).needs`. -/ +abbrev Inv := {j : Fin p.code.length // (p.code.get j).needs} +open scoped Classical in +/-- Counts the elements of `p.Inv`. -/ +def extra := Fintype.card p.Inv +open scoped Classical in +/-- Indexes the witness by the coordinates of `Fin p.vars ⊕ Fin p.extra`. -/ +abbrev Witness := Fin p.vars ⊕ Fin p.extra +open scoped Classical in +/-- Indexes the var by the coordinates of `Index n ⊕ p.Witness`. -/ +abbrev Var := Index n ⊕ p.Witness + +open scoped Classical in +theorem extra_le : p.extra ≤ p.code.length := + (Fintype.card_subtype_le _).trans_eq (Fintype.card_fin _) + +variable [Field F] + +open scoped Classical in +/-- In the case `.scalar c`, this construction gives `Affine.const c`. -/ +def name : Operand F n p.vars → Affine p.Var F + | .scalar c => Affine.const c + | .input i => Affine.coord (.inl i) + | .aux j => Affine.coord (.inr (.inl j)) + +open scoped Classical in +/-- Returns `Affine.coord (.inr (.inr (Fintype.equivFin p.Inv ⟨j, h⟩)))` when `h : (p.code.get +j).needs` holds, and `Affine.const 0` otherwise. -/ +def invName (j : Fin p.code.length) : Affine p.Var F := + if h : (p.code.get j).needs then + Affine.coord (.inr (.inr (Fintype.equivFin p.Inv ⟨j, h⟩))) else Affine.const 0 + +open scoped Classical in +/-- The indexed operation `(List.finRange p.code.length).flatMap fun j => (p.code.get j).emit +p.name (p.invName j)`. -/ +def equations : List (Equation p.Var F) := + (List.finRange p.code.length).flatMap fun j => (p.code.get j).emit p.name (p.invName j) + +open scoped Classical in +theorem equations_length : p.equations.length ≤ 2 * p.code.length := by + let f := fun j => (p.code.get j).emit p.name (p.invName j) + have size (l : List (Fin p.code.length)) : (l.flatMap f).length ≤ 2 * l.length := by + induction l with + | nil => simp + | cons a l ih => + have ha : (f a).length ≤ 2 := Instruction.emit_length _ _ _ + simp only [List.flatMap_cons, List.length_append, List.length_cons]; omega + simpa only [equations, List.length_finRange] using size (List.finRange p.code.length) + +open scoped Classical in +/-- The condition `∃ v : p.Witness → K, ∀ e ∈ p.equations, e.holds (Sum.elim x v)` on the +specified data. -/ +def Solves [Field K] [Algebra F K] (x : Index n → K) := + ∃ v : p.Witness → K, ∀ e ∈ p.equations, e.holds (Sum.elim x v) + +open scoped Classical in +private theorem name_eq (x : Index n → F) (w : Fin p.vars → F) (v : Fin p.extra → F) + (a : Operand F n p.vars) : (p.name a).eval (Sum.elim x (Sum.elim w v)) = a.eval x w := by + cases a <;> simp [name, Operand.eval] + +open scoped Classical in +theorem project (x : Index n → F) (w : Fin p.vars → F) : + (∃ v : Fin p.extra → F, ∀ e ∈ p.equations, e.holds (Sum.elim x (Sum.elim w v))) ↔ + ∀ i ∈ p.code, i.holds x w := by + constructor + · rintro ⟨v, hv⟩ i hi + obtain ⟨j, rfl⟩ := List.mem_iff_get.mp hi + exact ((Instruction.emit_iff p.name (p.invName j) (p.code.get j) x w _ (p.name_eq x w v)).mp + (fun e he => hv e (List.mem_flatMap.mpr ⟨j, List.mem_finRange _, he⟩))).1 + · intro hx + let v (t : Fin p.extra) := + ((p.code.get ((Fintype.equivFin p.Inv).symm t).val).denominator x w)⁻¹ + refine ⟨v, ?_⟩ + intro e he + obtain ⟨j, _, he⟩ := List.mem_flatMap.mp he + have hj := hx (p.code.get j) (List.get_mem _ _) + refine (Instruction.emit_iff p.name (p.invName j) (p.code.get j) x w _ (p.name_eq x w v)).mpr + ⟨hj, ?_⟩ e he + intro h + simp only [invName, dite_eq_left h, Affine.eval_coord, Sum.elim_inr] + change _ * v ((Fintype.equivFin p.Inv) ⟨j, h⟩) = 1 + simp only [v, Equiv.symm_apply_apply] + exact mul_inv_cancel₀ ((p.code.get j).nonzero hj) + +open scoped Classical in +theorem solves_iff (x : Index n → F) : p.Solves x ↔ p.accept x := by + constructor + · rintro ⟨v, hv⟩ + have h : Sum.elim (v ∘ Sum.inl) (v ∘ Sum.inr) = v := by funext i; cases i <;> rfl + exact ⟨_, (p.project x _).mp ⟨v ∘ Sum.inr, h.symm ▸ hv⟩⟩ + · rintro ⟨w, hw⟩ + obtain ⟨v, hv⟩ := (p.project x w).mpr hw + exact ⟨_, hv⟩ + +end Path +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Separating the matrix pair from the proposed product -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open scoped Classical in +/-- Indexes the pair index by the coordinates of `Fin 2 × Pos n n`. -/ +abbrev PairIndex (n : ℕ) := Fin 2 × Pos n n + +variable {F : Type*} {n : ℕ} + +open scoped Classical in +/-- The value specified by `![x (0, i.2), x (1, i.2), y i.2] i.1`. -/ +def join (x : PairIndex n → F) (y : Pos n n → F) (i : Index n) : F := + ![x (0, i.2), x (1, i.2), y i.2] i.1 + +open scoped Classical in +/-- The quantity computed by `∑ j, x (0, i.1, j) * x (1, j, i.2)`. -/ +def beta [CommRing F] (x : PairIndex n → F) (i : Pos n n) : F := + ∑ j, x (0, i.1, j) * x (1, j, i.2) + +open scoped Classical in +theorem correct_join [Field F] (x : PairIndex n → F) (y : Pos n n → F) : + Correct (join x y) ↔ y = beta x := + ⟨fun h => funext fun z => (h z.1 z.2).symm, fun h i j => (congrFun h (i, j)).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # A system of affine equations with shared products and offsets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +/-- The data for the jet construction, including `affine`, `left`, `right`, `c`, `f`. -/ +structure Jet (F : Type*) (τ σ : Type) (q d : ℕ) where + /-- The `Jet` component of type `σ → Affine (τ ⊕ σ) F`. -/ + affine : σ → Affine (τ ⊕ σ) F + /-- The left-side data carried by `Jet`, with type `Fin q → Affine (τ ⊕ σ) F`. -/ + left : Fin q → Affine (τ ⊕ σ) F + /-- The right-side data carried by `Jet`, with type `Fin q → Affine (τ ⊕ σ) F`. -/ + right : Fin q → Affine (τ ⊕ σ) F + /-- The remaining component of type `Matrix σ (Fin q) F`. -/ + c : Matrix σ (Fin q) F + /-- The `Jet` component of type `Matrix σ (Fin d) F`. -/ + f : Matrix σ (Fin d) F + +variable {F K E : Type*} [Field F] [Field K] [Algebra F K] + {τ σ : Type} [Fintype τ] [Fintype σ] {q d : ℕ} + +/-- The value specified by `aeval (Sum.elim (C ∘ x) X) a.poly`. -/ +def Affine.specialize (a : Affine (τ ⊕ σ) F) (x : τ → K) : MvPolynomial σ K := + aeval (Sum.elim (C ∘ x) X) a.poly + +/-- The system of type `MvPolynomial σ K` for the given inputs. -/ +def Jet.system (J : Jet F τ σ q d) (x : τ → K) (m : Fin d → K) (i : σ) : MvPolynomial σ K := + (J.affine i).specialize x + ∑ j, C (algebraMap F K (J.c i j)) * + ((J.left j).specialize x * (J.right j).specialize x) - C (∑ j, algebraMap F K (J.f i j) * m j) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Changing the coefficient field of the equations and their Jacobian -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +section +variable {F K L : Type*} [Field F] [Field K] [Field L] [Algebra F K] [Algebra K L] + [Algebra F L] [IsScalarTower F K L] {τ σ : Type} [Fintype τ] [Fintype σ] {q d : ℕ} + +private theorem Affine.map_specialize (a : Affine (τ ⊕ σ) F) (x : τ → K) : + MvPolynomial.map (algebraMap K L) (a.specialize x) = a.specialize (algebraMap K L ∘ x) := by + have hc : (MvPolynomial.map (σ := σ) (algebraMap K L)).comp (algebraMap F (MvPolynomial σ K)) = + algebraMap F (MvPolynomial σ L) := by + apply RingHom.ext + intro c + change MvPolynomial.map (algebraMap K L) (C (algebraMap F K c)) = C (algebraMap F L c) + rw [map_C, ← IsScalarTower.algebraMap_apply F K L] + rw [Affine.specialize, map_aeval, hc] + have hv : (fun i : τ ⊕ σ => MvPolynomial.map (algebraMap K L) (Sum.elim (C ∘ x) X i)) = + Sum.elim (C ∘ (algebraMap K L ∘ x)) X := by + funext i + cases i <;> simp + rw [hv] + rfl + +theorem Jet.map_system (J : Jet F τ σ q d) (x : τ → K) (m : Fin d → K) (i : σ) : + MvPolynomial.map (algebraMap K L) (J.system x m i) = + J.system (algebraMap K L ∘ x) (algebraMap K L ∘ m) i := by + simp only [system, map_sub, map_add, map_sum, map_mul, map_C, Affine.map_specialize, + ← IsScalarTower.algebraMap_apply F K L, Function.comp_apply] + +end + +theorem map_jacobian {K L E : Type u} [Field K] [Field L] [Field E] + [Algebra K L] [Algebra L E] [Algebra K E] [IsScalarTower K L E] + {σ : Type} (G : σ → MvPolynomial σ K) (a : σ → E) : + jacobian (fun i => MvPolynomial.map (algebraMap K L) (G i)) a = jacobian G a := by + ext i j + rw [jacobian, pderiv_map, jacobian, aeval_def, aeval_def, eval₂_map, + ← IsScalarTower.algebraMap_eq K L E] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# A simple solution specializing to an isolated one + +Move the polynomial values along a ray whose direction is algebraically +independent over the original coefficients. Isolation supplies a component +on which the ray parameter varies. The values on this component are +algebraically independent over the original field, so the Jacobian is +invertible. Normalizing the curve gives a local ring for specialization. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial +variable {K L : Type u} [Field K] [Field L] [Algebra K L] {σ : Type} + +private theorem map_isolated {G : σ → MvPolynomial σ K} {x : σ → K} + (h : Isolated x (Ideal.span (Set.range G))) : + Isolated (algebraMap K L ∘ x) (Ideal.span (Set.range (MvPolynomial.map (algebraMap K L) ∘ G))) + := by + rw [Set.range_comp, ← Ideal.map_span] + exact h.map (algebraMap K L) + +theorem simple_lift [Fintype σ] [DecidableEq σ] [CharZero L] [IsAlgClosed L] + (G : σ → MvPolynomial σ K) (x : σ → K) (h : Isolated x (Ideal.span (Set.range G))) + (c : σ → L) (hc : AlgebraicIndependent K c) : + let g := MvPolynomial.map (algebraMap K L) ∘ G + ∃ (E : Type u) (_ : Field E) (_ : Algebra L E) (t : E) (b : Branch L E t) (y : σ → b.ring), + Transcendental L t ∧ (∀ i, b.res (y i) = algebraMap K L (x i)) ∧ + (∀ i, aeval (fun j => (y j : E)) (g i) = t * algebraMap L E (c i)) ∧ + IsUnit (jacobian g (fun j => (y j : E))) := by + intro g + obtain ⟨d⟩ := exists_deformation g c (algebraMap K L ∘ x) (map_isolated h) + let E := d.E + let _ : Algebra K E := ((algebraMap L E).comp (algebraMap K L)).toAlgebra + have : IsScalarTower K L E := IsScalarTower.of_algebraMap_eq' rfl + have : CharZero E := charZero_of_injective_algebraMap (algebraMap L E).injective + let a (j : σ) : E := d.y j + have ht := transcendental_of_residue d.ring d.res d.t d.nonzero d.zero + have eqn (i : σ) : aeval a (G i) = (d.t : E) * algebraMap L E (c i) := by + have eq := d.ray i + simp only [g, Function.comp_apply, aeval_def, eval₂_map] at eq + exact eq + have hi := isUnit_jacobian G a (independent_ray hc ht eqn) + have alg := algebraic_ray hc ht eqn d.generates + obtain ⟨b, hb, hs⟩ := exists_branch d.ring d.fg d.res d.t d.nonzero d.zero alg + let y i : b.ring := ⟨a i, hb (d.y i).property⟩ + refine ⟨E, inferInstance, inferInstance, d.t, b, y, ht, fun i => (hs _).trans (d.point i), d.ray, + ?_⟩ + change IsUnit (jacobian (fun i => MvPolynomial.map (algebraMap K L) (G i)) a) + rw [map_jacobian] + exact hi + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # The path equations with both input matrices fixed -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset MvPolynomial + +variable {I J : Type} [Fintype I] [Fintype J] {F K : Type*} [Field F] [Field K] [Algebra F K] + +namespace Affine + +open scoped Classical in +/-- Builds `Affine I F →ₗ[F] K where toFun a` with the specified `toFun`, `map_add'`, +`map_smul'`. -/ +def evalₗ (x : I → K) : Affine I F →ₗ[F] K where + toFun a := a.eval x + map_add' _ _ := eval_add _ _ _ + map_smul' c a := by + simp [eval, Algebra.smul_def, mul_assoc, mul_add, mul_sum] + +open scoped Classical in +theorem eval_specialize (a : Affine (I ⊕ J) F) (x : I → K) (y : J → K) : + MvPolynomial.eval y (a.specialize x) = a.eval (Sum.elim x y) := by + simp [specialize, poly, eval] + +open scoped Classical in +/-- The quantity computed by `const a.1 + ∑ i, a.2 i • coord (f i)`. -/ +def relabel (f : I → J) (a : Affine I F) : Affine J F := + const a.1 + ∑ i, a.2 i • coord (f i) + +open scoped Classical in +theorem eval_relabel (f : I → J) (a : Affine I F) (x : J → K) : + (a.relabel f).eval x = a.eval (x ∘ f) := by + change evalₗ x (_ + _) = _ + rw [map_add, map_sum] + simp_rw [map_smul] + simp only [evalₗ, LinearMap.coe_mk, AddHom.coe_mk, eval_const, eval_coord, Algebra.smul_def] + rfl + +end Affine + +namespace Path +variable {n : ℕ} (p : Path F n) + +open scoped Classical in +/-- Indexes the unk by the coordinates of `Pos n n ⊕ p.Witness`. -/ +abbrev Unk := Pos n n ⊕ p.Witness + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def split : p.Var → PairIndex n ⊕ p.Unk := + Sum.elim (join Sum.inl (Sum.inr ∘ Sum.inl)) (Sum.inr ∘ Sum.inr) + +omit [Field F] [Field K] [Algebra F K] in +open scoped Classical in +theorem eval_split (x : PairIndex n → K) (β : Pos n n → K) (y : p.Witness → K) : + Sum.elim x (Sum.elim β y) ∘ p.split = Sum.elim (join x β) y := by + funext t + rcases t with ⟨i, u⟩ | j + · fin_cases i <;> rfl + · rfl + +open scoped Classical in +/-- In the case `none`, this construction gives `Affine.const 0`. -/ +def fixedEq (fixed : p.Witness → Option F) (i : p.Witness) : Affine (PairIndex n ⊕ p.Unk) F := + match fixed i with + | none => Affine.const 0 + | some a => Affine.coord (.inr (.inr i)) - Affine.const a + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def generators (x : PairIndex n → K) (fixed : p.Witness → Option F) : + Fin p.equations.length ⊕ p.Witness → MvPolynomial p.Unk K := + Sum.elim (fun i => + let e := p.equations.get i + (e.left.relabel p.split).specialize x * (e.right.relabel p.split).specialize x - + (e.value.relabel p.split).specialize x) (fun i => (p.fixedEq fixed i).specialize x) + +open scoped Classical in +/-- Computes the ideal by the application `Ideal.span (Set.range (p.generators x fixed))`. -/ +def ideal (x : PairIndex n → K) (fixed : p.Witness → Option F) := + Ideal.span (Set.range (p.generators x fixed)) + +open scoped Classical in +theorem ideal_iff (x : PairIndex n → K) (fixed : p.Witness → Option F) (β : Pos n n → K) + (y : p.Witness → K) : p.ideal x fixed ≤ maxPoint (Sum.elim β y) ↔ + (∀ e ∈ p.equations, e.holds (Sum.elim (join x β) y)) ∧ + (∀ i a, fixed i = some a → y i = algebraMap F K a) := by + have he (i : Fin p.equations.length) : + p.generators x fixed (.inl i) ∈ maxPoint (Sum.elim β y) ↔ + (p.equations.get i).holds (Sum.elim (join x β) y) := by + simp only [maxPoint, RingHom.mem_ker, generators, Sum.elim_inl, map_sub, map_mul, + Affine.eval_specialize, + Affine.eval_relabel, eval_split, sub_eq_zero, Equation.holds] + have hf (i : p.Witness) : + p.generators x fixed (.inr i) ∈ maxPoint (Sum.elim β y) ↔ + (∀ a, fixed i = some a → y i = algebraMap F K a) := by + simp only [maxPoint, RingHom.mem_ker, generators, Sum.elim_inr, Affine.eval_specialize, fixedEq] + cases fixed i <;> simp [sub_eq_zero] + rw [ideal, Ideal.span_le, Set.range_subset_iff] + constructor + · intro h + refine ⟨fun e he' => ?_, fun i => (hf i).mp (h _)⟩ + obtain ⟨i, rfl⟩ := List.mem_iff_get.mp he' + exact (he i).mp (h _) + · rintro ⟨h, h'⟩ (i|i) + · exact (he i).mpr (h _ (List.get_mem _ _)) + · exact (hf i).mpr (h' i) + +end Path +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Mixed derivatives of the verification equations + +Subtract the Jacobian applied to the mixed derivatives of the unknowns. +The remainder is additive and vanishes on affine forms when the inputs +have vanishing mixed derivatives. Each shared product contributes two +products of first derivatives. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial + +variable {F K E : Type u} [Field F] [Field K] [Field E] [Algebra K E] [Algebra F E] + {τ σ : Type} [Fintype τ] [Fintype σ] + {q d : ℕ} + +variable (Y : σ → E) (D D' : Derivation F E E) + +private def remMixed : MvPolynomial σ K →+ E where + toFun p := D' (D (aeval Y p)) - ∑ j, aeval Y (pderiv j p) * D' (D (Y j)) + map_zero' := by simp + map_add' p p' := by + simp only [map_add, add_mul, Finset.sum_add_distrib] + abel + +private theorem rem_C (k : K) : + remMixed Y D D' (C k) = D' (D (algebraMap K E k)) := by + simp [remMixed] + +private theorem rem_X (j : σ) : + remMixed Y D D' (X j : MvPolynomial σ K) = 0 := by + classical + simp [remMixed, Pi.single_apply, apply_ite] + +private theorem rem_mul (p r : MvPolynomial σ K) : + remMixed Y D D' (p * r) = + aeval Y p * remMixed Y D D' r + aeval Y r * remMixed Y D D' p + + (D (aeval Y p) * D' (aeval Y r) + D (aeval Y r) * D' (aeval Y p)) := by + simp only [remMixed, AddMonoidHom.coe_mk, ZeroHom.coe_mk, map_mul, Derivation.leibniz, + smul_eq_mul, map_add, add_mul, mul_assoc, Finset.sum_add_distrib, ← Finset.mul_sum] + ring + +variable [Algebra F K] [IsScalarTower F K E] + +private theorem rem_const_mul (z : F) (p : MvPolynomial σ K) : + remMixed Y D D' (C (algebraMap F K z) * p) = algebraMap F E z * remMixed Y D D' p := by + simp [rem_mul, rem_C, ← IsScalarTower.algebraMap_apply F K E] + +private theorem rem_affine (a : Affine (τ ⊕ σ) F) (x : τ → K) + (hx : ∀ k, D' (D (algebraMap K E (x k))) = 0) : + remMixed Y D D' (a.specialize x) = 0 := by + simp [Affine.specialize, Affine.poly, rem_const_mul, rem_C, rem_X, hx, + ← IsScalarTower.algebraMap_apply F K E] + +theorem Jet.mixed (J : Jet F τ σ q d) (x : τ → K) (m : Fin d → K) + (Y : σ → E) (D D' : Derivation F E E) (i : σ) + (hi : D' (D (aeval Y (J.system x m i))) = 0) + (hx : ∀ k, D' (D (algebraMap K E (x k))) = 0) : + (∑ j, jacobian (J.system x m) Y i j * D' (D (Y j))) + + (∑ j, algebraMap F E (J.c i j) * + (D (aeval Y ((J.left j).specialize x)) * D' (aeval Y ((J.right j).specialize x)) + + D (aeval Y ((J.right j).specialize x)) * D' (aeval Y ((J.left j).specialize x)))) = + ∑ j, algebraMap F E (J.f i j) * D' (D (algebraMap K E (m j))) := by + have h := show remMixed Y D D' (J.system x m i) = + D' (D (aeval Y (J.system x m i))) - ∑ j, jacobian (J.system x m) Y i j * D' (D (Y j)) from rfl + conv at h => + lhs + simp only [Jet.system, map_sub, map_add, map_sum, map_mul, rem_const_mul] + simp only [rem_mul, rem_affine Y D D' _ x hx, rem_C, mul_zero, zero_add] + linear_combination hi + h + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Combining paths while sharing the same product claim + +All path witnesses have disjoint names. One reserved variable permits +a test that a specified output coordinate differs from the true one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +namespace Packet +open MvPolynomial +variable {F K : Type*} [Field F] [Field K] [Algebra F K] {n : ℕ} + (T : Finset (Path F n)) + +open scoped Classical in +/-- Indexes the extra by the coordinates of `Pos n n ⊕ (Σ i : ↥T, i.val.Witness) ⊕ Unit`. -/ +abbrev Extra := Pos n n ⊕ (Σ i : ↥T, i.val.Witness) ⊕ Unit +open scoped Classical in +/-- Indexes the name by the coordinates of `PairIndex n ⊕ Extra T`. -/ +abbrev Name := PairIndex n ⊕ Extra T + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def locate (i : ↥T) : i.val.Var → Name T := + Sum.elim (join Sum.inl (fun j => .inr (.inl j))) (fun j => .inr (.inr (.inl ⟨i, j⟩))) + +open scoped Classical in +/-- Uses `{f | ∃ i : ↥T, ∃ e ∈ i.val.equations, f = rename (locate T i) e.poly}` as the +representation. -/ +def equations : Set (MvPolynomial (Name T) F) := + {f | ∃ i : ↥T, ∃ e ∈ i.val.equations, f = rename (locate T i) e.poly} + +open scoped Classical in +/-- The value specified by `w ∘ Sum.inl`. -/ +def output (w : Extra T → K) : Pos n n → K := w ∘ Sum.inl + +open scoped Classical in +private def registers (w : Extra T → K) (i : ↥T) (j : i.val.Witness) : K := + w (.inr (.inl ⟨i, j⟩)) + +open scoped Classical in +/-- The value specified by `.inr (.inr ())`. -/ +def inverse : Extra T := .inr (.inr ()) + +omit [Field F] [Field K] [Algebra F K] in +open scoped Classical in +private theorem locate_eq (x : PairIndex n → K) (w : Extra T → K) (i : ↥T) : + Sum.elim x w ∘ locate T i = Sum.elim (join x (output T w)) (registers T w i) := by + funext j + rcases j with ⟨a, b⟩ | j + · fin_cases a <;> rfl + · rfl + +variable (x : PairIndex n → K) (w : Extra T → K) + +open scoped Classical in +theorem solves (hz : ∀ f ∈ equations T, aeval (Sum.elim x w) f = 0) : + ∀ p ∈ T, p.Solves (join x (output T w)) := by + intro p hp + let i : ↥T := ⟨p, hp⟩ + refine ⟨registers T w i, fun e he => ?_⟩ + have h := hz _ ⟨i, e, he, rfl⟩ + rw [aeval_rename, locate_eq, Equation.zero] at h + exact h + +open scoped Classical in +theorem pack (z : Pos n n → K) (a : K) (hs : ∀ p ∈ T, p.Solves (join x z)) : + ∃ w : Extra T → K, output T w = z ∧ w (inverse T) = a ∧ + ∀ f ∈ equations T, aeval (Sum.elim x w) f = 0 := by + choose v hv using fun i : ↥T => hs i.val i.property + let w : Extra T → K := Sum.elim z (Sum.elim (fun j => v j.1 j.2) (fun _ => a)) + refine ⟨w, rfl, rfl, ?_⟩ + rintro _ ⟨i, e, he, rfl⟩ + rw [aeval_rename, locate_eq, Equation.zero] + exact hv i e he + +open scoped Classical in +/-- The quantity computed by `(X (.inr (.inl i)) - beta (fun v => X (.inl v)) i) * X (.inr +(inverse T)) - 1`. -/ +def discrepancy (i : Pos n n) : MvPolynomial (Name T) F := + (X (.inr (.inl i)) - beta (fun v => X (.inl v)) i) * X (.inr (inverse T)) - 1 + +open scoped Classical in +theorem discrepancy_zero (i : Pos n n) : + aeval (Sum.elim x w) (discrepancy T i) = 0 ↔ (output T w i - beta x i) * w (inverse T) = 1 := by + simp only [discrepancy, beta, output, Function.comp_apply, map_sub, map_mul, map_sum, map_one, + aeval_X, Sum.elim_inl, Sum.elim_inr, sub_eq_zero] + +end Packet +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Isolating the correct product at algebraically independent inputs + +A strict probability gap supplies a finite cover by conjunctions of +paths. Each conjunction excludes every false product even after +extending scalars. At least one conjunction is feasible generically. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +variable {F K : Type*} [Field F] [Field K] [Algebra F K] [IsAlgClosed F] {n : ℕ} + +open scoped Classical in +private theorem Packet.sound (T : Finset (Path F n)) + (h : ∀ y, (∀ p ∈ T, p.accept y) → Correct y) {x : PairIndex n → K} {z : Pos n n → K} + (hz : ∀ p ∈ T, p.Solves (join x z)) : z = beta x := by + funext i + by_contra hi + obtain ⟨w, ho, ha, he⟩ := Packet.pack T x z (z i - beta x i)⁻¹ hz + let B := insert (Packet.discrepancy T i) (Packet.equations T) + have bad : ∀ e ∈ B, MvPolynomial.aeval (Sum.elim x w) e = 0 := by + rintro e (rfl|he') + · rw [Packet.discrepancy_zero, ho, ha] + exact mul_inv_cancel₀ (sub_ne_zero.mpr hi) + · exact he _ he' + obtain ⟨y, hy⟩ := descend_point B _ bad + let x' := y ∘ Sum.inl + let w' := y ∘ Sum.inr + have eq : Sum.elim x' w' = y := by funext v; cases v <;> rfl + rw [← eq] at hy + have hs := Packet.solves T x' w' (fun e he => hy e (Set.mem_insert_of_mem _ he)) + have ok := h _ (fun p hp => (p.solves_iff _).mp (hs p hp)) + have he := (Packet.discrepancy_zero T x' w' i).mp (hy _ (Set.mem_insert _ _)) + rw [(correct_join ..).mp ok, sub_self, zero_mul] at he + exact zero_ne_one he + +open scoped Classical in +theorem specialization [IsAlgClosed K] (hn : 0 < n) + {ι : Type*} {w : ι → ℝ} {S : Finset ι} {A : ι → Verifier F n} {c : ℝ} + (hw : ∀ i ∈ S, 0 ≤ w i) (hc : ∀ i ∈ S, (A i).cost c) + (gap : Gap w (fun i => (A i).accept) Correct S) + {X : PairIndex n → K} (hx : AlgebraicIndependent F X) : + ∃ l : ℕ, 0 < l ∧ l ≤ S.card ∧ ∃ p : Fin l → Path F n, + (∀ i, ((p i).code.length : ℝ) ≤ c) ∧ ∀ Z, (∀ i, (p i).Solves (join X Z)) ↔ Z = beta X := by + obtain ⟨B, sound, live⟩ := packet_cover hn hw hc gap + have lift (x : PairIndex n → F) : ∃ i : ↥B, ∃ w : Packet.Extra i.val → F, + ∀ e ∈ Packet.equations i.val, MvPolynomial.eval (Sum.elim x w) e = 0 := by + obtain ⟨t, ht, hp⟩ := live _ ((correct_join x (beta x)).mpr rfl) + obtain ⟨v, _, _, hv⟩ := Packet.pack t x (beta x) 0 (fun p h => (p.solves_iff _).mpr (hp p h)) + exact ⟨⟨t, ht⟩, v, hv⟩ + obtain ⟨⟨t, ht⟩, v, hv⟩ := generic_point hx (fun i : ↥B => Packet.Extra i.val) + (fun i => Packet.equations i.val) lift + obtain ⟨hl, hcard, hcost, hs⟩ := sound t ht + have good := Packet.solves t X v hv + have correct := Packet.sound t hs good + let E : Fin t.card ≃ ↥t := (Fintype.equivOfCardEq (by simp)) + refine ⟨t.card, hl, hcard, fun i => (E i).val, fun i => hcost _ (E i).property, fun Z => ?_⟩ + constructor + · intro h + apply Packet.sound t hs + intro p hp + simpa only [Equiv.apply_symm_apply] using h (E.symm ⟨p, hp⟩) + · intro he i + rw [he, ← correct] + exact good _ (E i).property + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Isolating a solution of one path by rational output measurements -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +variable {F K : Type*} [Field F] [Field K] [Algebra F K] {n : ℕ} + +namespace Path +variable (p : Path F n) (x : PairIndex n → K) (z : Pos n n → K) + +open scoped Classical in +private def atOutput (e : Equation p.Var F) : MvPolynomial p.Witness K := + e.left.specialize (join x z) * e.right.specialize (join x z) - e.value.specialize (join x z) + +open scoped Classical in +private theorem eval_output (e : Equation p.Var F) (y : p.Witness → K) : + MvPolynomial.eval y (p.atOutput x z e) = 0 ↔ e.holds (Sum.elim (join x z) y) := by + simp only [atOutput, map_sub, map_mul, Affine.eval_specialize, sub_eq_zero, Equation.holds] + +open scoped Classical in +theorem finite_fiber [Infinite F] [IsAlgClosed K] (h : p.Solves (join x z)) : + ∃ b : p.Witness → Option F, ∃ y : p.Witness → K, + p.ideal x b ≤ maxPoint (Sum.elim z y) ∧ + Set.Finite {v : p.Witness → K | p.ideal x b ≤ maxPoint (Sum.elim z v)} := by + let B := p.atOutput x z '' {e | e ∈ p.equations} + have he (y : p.Witness → K) : (∀ q ∈ B, MvPolynomial.eval y q = 0) ↔ + ∀ e ∈ p.equations, e.holds (Sum.elim (join x z) y) := by + simp only [B, Set.forall_mem_image, Set.mem_ofPred_eq, eval_output] + obtain ⟨y, hy⟩ := h + obtain ⟨b, ⟨w, hw⟩, hb⟩ := finite_slice F B ⟨y, (he y).mpr hy⟩ + have eq (v : p.Witness → K) : v ∈ slice B b ↔ p.ideal x b ≤ maxPoint (Sum.elim z v) := by + simp only [slice, Set.mem_ofPred_eq, he, ideal_iff] + exact ⟨b, w, (eq w).mp hw, hb.subset (fun v hv => (eq v).mpr hv)⟩ + +end Path + +open scoped Classical in +theorem path_cut [Infinite F] [CharZero K] [IsAlgClosed K] {l : ℕ} (hl : 0 < l) + (p : Fin l → Path F n) (x : PairIndex n → K) (z : Pos n n → K) + (h : ∀ y, (∀ i, (p i).Solves (join x y)) ↔ y = z) : + ∃ (i : Fin l) (d : ℕ), d ≤ n * n ∧ n * n ≤ l * (n * n - d) ∧ + ∃ (b : (p i).Witness → Option F) (y : (p i).Witness → K) (H : Fin d → Pos n n → ℚ), + Isolated (Sum.elim z y) ((p i).ideal x b ⊔ Ideal.span (Set.range (fun t + => comb (offset z) (H t)))) := by + let _ : Nonempty (Fin l) := ⟨⟨0, hl⟩⟩ + choose b w hw hf using fun i => (p i).finite_fiber x z ((h z).mpr rfl i) + let I i := (p i).ideal x (b i) + have hu (y : Pos n n → K) (hy : ∀ i, ∃ v, I i ≤ maxPoint (Sum.elim y v)) : y = z := by + apply (h y).mp + intro i + obtain ⟨v, hv⟩ := hy i + exact ⟨v, ((p i).ideal_iff x (b i) y v).mp hv |>.1⟩ + obtain ⟨joint, fiber⟩ := isolate_family I z w hw hf hu + obtain ⟨i, d, hd, hl, H, hH⟩ := local_cut I z w joint fiber + simp only [Pos, Fintype.card_prod, Fintype.card_fin] at hd hl + exact ⟨i, d, hd, hl, b i, w i, H, hH⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # A square system using only the products from the original path -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset MvPolynomial + +variable {F K : Type*} [Field F] [Field K] [Algebra F K] + +namespace Affine +variable {I L : Type} [Fintype I] [Fintype L] + +open scoped Classical in +private def blend (b : L → ℚ) (a : L → Affine I F) : Affine I F := ∑ i, (b i : F) • a i + +open scoped Classical in +private theorem eval_blend (b : L → ℚ) (a : L → Affine I F) (x : I → K) : + (blend b a).eval x = ∑ i, (b i : K) * (a i).eval x := by + change evalₗ x (∑ i, (b i : F) • a i) = _ + rw [map_sum] + simp_rw [map_smul, Algebra.smul_def, map_ratCast] + rfl + +end Affine + +namespace Path + +variable {n : ℕ} (p : Path F n) + +open scoped Classical in +/-- Fixing witnesses and measuring outputs adds only affine terms. +The rational combinations isolating the solution reuse every original +quadratic term, even when several equations need the same product. -/ +theorem jet [CharZero K] (x : PairIndex n → K) (fixed : p.Witness → Option F) + (β : Pos n n → K) (y : p.Witness → K) {d : ℕ} (H : Fin d → Pos n n → ℚ) + (h : Isolated (Sum.elim β y) (p.ideal x fixed ⊔ Ideal.span (Set.range fun t + => comb (offset β) (H t)))) : + ∃ J : Jet F (PairIndex n) p.Unk p.equations.length d, ∃ m : Fin d → K, + Isolated (Sum.elim β y) (Ideal.span (Set.range (J.system x m))) := by + let G := Sum.elim (p.generators x fixed) (fun t => comb (offset β) (H t)) + have hg : Isolated (Sum.elim β y) (Ideal.span (Set.range G)) := by + rw [show Set.range G = _ from Set.Sum.elim_range _ _, Ideal.span_union] + exact h + obtain ⟨A, hA⟩ := square_system (Sum.elim β y) G hg + let a i j := A i (.inl (.inl j)) + let b i j := A i (.inl (.inr j)) + let c i j := A i (.inr j) + let M (j : Fin d) : Affine (PairIndex n ⊕ p.Unk) F := + Affine.blend (H j) (fun z => Affine.coord (.inr (.inl z))) + let m (j : Fin d) := ∑ z, (H j z : K) * β z + let e := p.equations.get + let J : Jet F (PairIndex n) p.Unk p.equations.length d := + { affine := fun i => Affine.blend (b i) (p.fixedEq fixed) + Affine.blend (c i) M - + Affine.blend (a i) (fun j => (e j).value.relabel p.split) + left := fun j => (e j).left.relabel p.split + right := fun j => (e j).right.relabel p.split + c := fun i j => a i j + f := fun i j => c i j } + refine ⟨J, m, ?_⟩ + suffices he : J.system x m = (fun i => comb G (A i)) by rwa [he] + funext i + have : Infinite K := Infinite.of_injective (fun n : ℕ => (n : K)) Nat.cast_injective + apply MvPolynomial.funext + intro z + have hm (j) : MvPolynomial.eval z (comb (offset β) (H j)) = (M j).eval (Sum.elim x z) - m j := by + simp only [comb, offset, map_sum, map_mul, eval_C, map_sub, eval_X, M, Affine.eval_blend, + Affine.eval_coord, Sum.elim_inr, m, mul_sub, sum_sub_distrib] + rw [Jet.system, comb] + simp only [map_sub, map_add, map_mul, map_sum, eval_C, Affine.eval_specialize] + rw [Fintype.sum_sum_type (α₁ := Fin p.equations.length ⊕ p.Witness), + Fintype.sum_sum_type (α₁ := Fin p.equations.length)] + simp only [G, generators, Sum.elim_inl, Sum.elim_inr, map_mul, map_sub, Affine.eval_specialize, + hm, + J, Affine.eval_sub, Affine.eval_add, Affine.eval_blend, map_ratCast, a, b, c, e, mul_sub, + sum_sub_distrib] + abel + +end Path +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Lower.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Lower.lean new file mode 100644 index 0000000000..8cc63fb2fb --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Lower.lean @@ -0,0 +1,844 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Gaps +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Model +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Tactic.Linarith +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BlockProducts +public import Mathlib.LinearAlgebra.Vandermonde +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CircuitCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Possible +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.TreePossible +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Bounds +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Surplus + +/-! +# Finite support from a Shannon entropy bound + +Keep every atom of weight at least `exp (-L)`. No zero-weight atom +contributes, and the discarded mass times `L` is bounded by the entropy. +Both entropy and the scale logarithm are taken in natural units. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open Filter Finset +variable {ι X : Type*} {w : ι → ℝ} {E : ℝ} + +open scoped Classical in +theorem entropy_mass (hw : ∀ i, 0 ≤ w i) (hs : HasSum w 1) + (he : HasSum (fun i => -w i * Real.log (w i)) E) (L : ℝ) : + ∃ S : Finset ι, (∀ i ∈ S, 0 < w i) ∧ (S.card : ℝ) ≤ Real.exp L ∧ + (1 - ∑ i ∈ S, w i) * L ≤ E := by + have hf := hs.summable.tendsto_cofinite_zero.eventually_lt_const (Real.exp_pos (-L)) + let S := (eventually_cofinite.mp hf).toFinset + have hS (i) : i ∈ S ↔ Real.exp (-L) ≤ w i := by simp [S] + have hm (T : Finset ι) : ∑ i ∈ T, w i ≤ 1 := sum_le_hasSum T (fun i _ => hw i) hs + refine ⟨S, fun i hi => (Real.exp_pos _).trans_le ((hS i).mp hi), ?_, ?_⟩ + · have ht : ∑ _ ∈ S, Real.exp (-L) ≤ (1 : ℝ) := + (sum_le_sum (fun i hi => (hS i).mp hi)).trans (hm S) + rw [sum_const, nsmul_eq_mul, Real.exp_neg, ← div_eq_mul_inv, div_le_one (Real.exp_pos L)] at ht + exact ht + · have hr : HasSum (fun i => if i ∈ S then w i else 0) (∑ i ∈ S, w i) := by + convert hasSum_sum_of_ne_finset_zero (L := .unconditional ι) (s := S) (f := fun i + => if i ∈ S then w i else 0) + (fun i hi => ite_eq_right hi) using 1 + simp + apply hasSum_le _ ((hs.sub hr).mul_right L) he + intro i + by_cases hi : i ∈ S + · rw [ite_eq_left hi, sub_self, zero_mul] + exact mul_nonneg_of_nonpos_of_nonpos (neg_nonpos.mpr (hw i)) + (Real.log_nonpos (hw i) (by simpa using hm {i})) + · rw [ite_eq_right hi, sub_zero] + rcases (hw i).eq_or_lt with hz | hp + · simp [← hz] + · have hh := Real.log_le_log hp (le_of_not_ge (mt (hS i).mpr hi)) + rw [Real.log_exp] at hh + nlinarith only [hh, hp] + +open scoped Classical in +/-- A positive gap remains at support rate `3*η+ε`. This includes +entropy rate zero without requiring that the seed be deterministic. -/ +theorem entropy_gap {accept : ι → X → Prop} {good : X → Prop} {n : ℕ} {η ε : ℝ} + (hw : ∀ i, 0 ≤ w i) (hs : HasSum w 1) (ha : Accurate w accept good) + (he : HasSum (fun i => -w i * Real.log (w i)) E) (hn : 2 ≤ n) (hη : 0 ≤ η) + (hε : 0 < ε) (hb : E ≤ (η + ε / 4) * Real.log n) : + ∃ S : Finset ι, S.Nonempty ∧ (S.card : ℝ) ≤ (n : ℝ) ^ (3 * η + ε) ∧ Gap w accept good S := by + have hn' : 1 < (n : ℝ) := by exact_mod_cast hn + have hl := Real.log_pos hn' + obtain ⟨S, _, hc, hm⟩ := entropy_mass hw hs he (Real.log n * (3 * η + ε)) + have hmass : 2 / 3 < ∑ i ∈ S, w i := by + by_contra! h + have hx := mul_le_mul_of_nonneg_right (by linarith : 1 / 3 ≤ 1 - ∑ i ∈ S, w i) + (by positivity : 0 ≤ Real.log n * (3 * η + ε)) + nlinarith only [hb, hm, hx, mul_pos hl hε] + refine ⟨S, ?_, ?_, mass_gap hw hs ha S hmass⟩ + · exact nonempty_of_ne_empty (by rintro rfl; norm_num at hmass) + · rwa [Real.rpow_def_of_pos (by linarith)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- A mixture of a uniform verifier and two constant decisions. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Filter Finset +variable {F : Type*} [Field F] {n : ℕ} + +open scoped Classical in +private def constantValue (n : ℕ) (a : F) : Test F n := + ⟨1, fun _ => MvPolynomial.C a, fun _ => MvPolynomial.C 0⟩ + +open scoped Classical in +private theorem const_accept (x : Index n → F) (a : F) : + (constantValue n a).accept x ↔ a = 0 := by simp [Test.accept, constantValue] + +open scoped Classical in +private theorem const_cost (a : F) {c : ℝ} (h : 1 ≤ c) : (constantValue n a).cost c := + ⟨0, _, .nil, fun _ => ⟨.inl ⟨_, rfl⟩, .inl ⟨_, rfl⟩⟩, by simpa [constantValue] using h⟩ + +open scoped Classical in +private def overhead (q : ℝ) := + -((2 / 3 - q) * Real.log (2 / 3 - q) + (1 / 3) * Real.log (1 / 3) + q * Real.log q) + +open scoped Classical in +private theorem mix {s c p q : ℝ} (h : Uniform F n s c p) (hc : 1 ≤ c) + (hq : 0 < q) (hq' : q ≤ 2 / 3) (hg : 1 / 3 ≤ q - p * q) : + ∃ (L : ℕ) (A : Fin L → Test F n) (w : Fin L → ℝ), + (∀ i, 0 ≤ w i) ∧ (∑ i, w i) = 1 ∧ -(∑ i, w i * Real.log (w i)) ≤ overhead q + q * Real.log s ∧ + (∀ i, (A i).cost c) ∧ + ∀ x, (∑ i, if (A i).accept x ↔ Correct x then w i else 0) ≥ 2 / 3 := by + obtain ⟨L, T, hL, hLs, hcost, on, off⟩ := h + let A : Fin (L + 1 + 1) → Test F n := + Fin.cons (constantValue n 0) (Fin.cons (constantValue n 1) T) + let u := q / (L : ℝ) + let w : Fin (L + 1 + 1) → ℝ := Fin.cons (2 / 3 - q) (Fin.cons (1 / 3) (fun _ => u)) + have pos : (0 : ℝ) < L := Nat.cast_pos.mpr hL + have hu : 0 ≤ u := (div_pos hq pos).le + have hu' : (L : ℝ) * u = q := mul_div_cancel₀ q pos.ne' + have mass : (∑ _ : Fin L, u) = q := by simp [hu'] + refine ⟨_, A, w, ?_, ?_, ?_, ?_, ?_⟩ + · exact Fin.cases (sub_nonneg.mpr hq') (Fin.cases (by norm_num [w]) (fun _ => hu)) + · simp only [w, Fin.sum_univ_succ, Fin.cons_zero, Fin.cons_succ, mass] + ring + · simp only [w, Fin.sum_univ_succ, Fin.cons_zero, Fin.cons_succ, ← Finset.sum_mul, mass] + rw [show Real.log u = Real.log q - Real.log L from Real.log_div hq.ne' pos.ne'] + unfold overhead + linarith [mul_le_mul_of_nonneg_left (Real.log_le_log pos hLs) hq.le] + · exact Fin.cases (const_cost 0 hc) (Fin.cases (const_cost 1 hc) hcost) + · intro x + simp only [A, w, Fin.sum_univ_succ, Fin.cons_zero, Fin.cons_succ, const_accept, one_ne_zero] + by_cases hx : Correct x + · simp only [hx, on x hx, iff_true, ite_true, ite_false, mass] + linarith + · have loss : (∑ i, if (T i).accept x then u else 0) ≤ p * q := by + rw [← Finset.sum_filter, Finset.sum_const, nsmul_eq_mul] + simpa only [mul_assoc, hu'] using mul_le_mul_of_nonneg_right (off x hx) hu + have both : (∑ i, if ¬ (T i).accept x then u else 0) + + (∑ i, if (T i).accept x then u else 0) = q := by + rw [← mass, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + by_cases hi : (T i).accept x <;> simp [hi] + simp only [hx, iff_false, not_true_eq_false, ite_false, ite_true] + linarith + +open scoped Classical in +/-- Pay for the original seed with probability just above the required +acceptance gap. Its error is chosen small enough to preserve that gap. -/ +theorem Support.entropy {ρ v η : ℝ} (h : Support F ρ v) (hρ : 0 ≤ ρ) (hv : 0 ≤ v) + (hη : ρ / 3 ≤ η) : Entropy F η v := by + intro ε hε + let p := min (1 / 6 : ℝ) (ε / (4 * (ρ + 1))) + have hp : 0 < p := by dsimp [p]; positivity + have hp' : p ≤ 1 / 6 := min_le_left .. + have hpρ : p * (4 * (ρ + 1)) ≤ ε := (le_div_iff₀ (by positivity)).mp (min_le_right ..) + let q := 1 / 3 + p + have hq : 0 < q := by dsimp [q]; linarith + have hq' : q ≤ 1 / 2 := by dsimp [q]; linarith + have hg : 1 / 3 ≤ q - p * q := by + have := mul_le_mul_of_nonneg_left hq' hp.le + dsimp [q] at this ⊢ + linarith + have hrate : q * (ρ + ε) ≤ η + 3 * ε / 4 := by + have := mul_le_mul_of_nonneg_right hq' hε.le + dsimp [q] at this ⊢ + linarith + have grow := Real.tendsto_log_atTop.comp tendsto_natCast_atTop_atTop + filter_upwards [h ε hε p hp, eventually_ge_atTop 1, + grow.eventually_ge_atTop (overhead q / (ε / 4))] + with n hs hn he + have hn' : (1 : ℝ) ≤ n := Nat.one_le_cast.mpr hn + obtain ⟨L, A, w, h₀, h₁, h₂, h₃, h₄⟩ := mix hs (Real.one_le_rpow hn' (by linarith)) hq (by + linarith) hg + refine ⟨L, A, w, h₀, h₁, h₂.trans ?_, h₃, h₄⟩ + have hc : overhead q ≤ Real.log n * (ε / 4) := (div_le_iff₀ (by positivity)).mp he + rw [Real.log_rpow (by positivity)] + linarith [mul_le_mul_of_nonneg_right hrate (Real.log_nonneg hn')] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # A polynomial encoding of all output blocks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset + +variable {A : Type*} [CommRing A] {n U R : ℕ} + +open scoped Classical in +/-- Returns `f ⟨(finProdFinEquiv i).val, h⟩` when `h : (finProdFinEquiv i).val < n` holds, and +`0` otherwise. -/ +def pad (f : Fin n → A) (i : Pos R U) : A := + if h : (finProdFinEquiv i).val < n then f ⟨(finProdFinEquiv i).val, h⟩ else 0 + +open scoped Classical in +/-- The indexed operation `pad (fun a => x (0, a, p.2)) (i, p.1)`. -/ +def row (x : Index n → A) (i : Fin R) (p : Pos U n) := pad (fun a => x (0, a, p.2)) (i, p.1) +open scoped Classical in +/-- The indexed operation `pad (fun b => x (1, p.1, b)) (j, p.2)`. -/ +def col (x : Index n → A) (j : Fin R) (p : Pos n U) := pad (fun b => x (1, p.1, b)) (j, p.2) +open scoped Classical in +/-- The indexed operation `pad (fun a => pad (fun b => x (2, a, b)) (s.2, p.2)) (s.1, p.1)`. -/ +def block (x : Index n → A) (s : Pos R R) (p : Pos U U) := + pad (fun a => pad (fun b => x (2, a, b)) (s.2, p.2)) (s.1, p.1) + +open scoped Classical in +/-- The sum of `t ^ (R * i.val) * row x i p` indexed by `i : Fin R`. -/ +def left (R : ℕ) (x : Index n → A) (t : A) (p : Pos U n) := + ∑ i : Fin R, t ^ (R * i.val) * row x i p + +open scoped Classical in +/-- The sum of `t ^ j.val * col x j p` indexed by `j : Fin R`. -/ +def right (R : ℕ) (x : Index n → A) (t : A) (p : Pos n U) := + ∑ j : Fin R, t ^ j.val * col x j p + +open scoped Classical in +/-- The sum of `t ^ (finProdFinEquiv s).val * block x s p` indexed by `s : Pos R R`. -/ +def claimed (R : ℕ) (x : Index n → A) (t : A) (p : Pos U U) := + ∑ s : Pos R R, t ^ (finProdFinEquiv s).val * block x s p + +open scoped Classical in +/-- The quantity computed by `mm (row x s.1) (col x s.2) p - block x s p`. -/ +def residual (x : Index n → A) (p : Pos U U) (s : Pos R R) := + mm (row x s.1) (col x s.2) p - block x s p + +open scoped Classical in +theorem expand (x : Index n → A) (t : A) (p : Pos U U) : + mm (left R x t) (right R x t) p - claimed R x t p = + ∑ s : Pos R R, t ^ (finProdFinEquiv s).val * residual x p s := by + simp only [residual, mul_sub, sum_sub_distrib, claimed] + congr 1 + rw [Fintype.sum_prod_type] + simp only [mm, left, right, sum_mul_sum] + simp only [mul_sum] + rw [sum_comm] + apply sum_congr rfl + intro i _ + rw [sum_comm] + apply sum_congr rfl + intro j _ + apply sum_congr rfl + intro k _ + change _ = t ^ (j.val + R * i.val) * _ + rw [pow_add] + ring + +variable {F : Type*} [Field F] + +open scoped Classical in +theorem complete {x : Index n → F} (h : Correct x) (p : Pos U U) (s : Pos R R) : + residual x p s = 0 := by + unfold residual mm row col block pad + by_cases hi : (finProdFinEquiv (s.1, p.1)).val < n + · by_cases hj : (finProdFinEquiv (s.2, p.2)).val < n + · simp only [dite_eq_left hi, dite_eq_left hj] + exact sub_eq_zero.mpr (h ⟨_, hi⟩ ⟨_, hj⟩) + · simp only [dite_eq_left hi, dite_eq_right hj, mul_zero, sum_const_zero, sub_zero] + · simp only [dite_eq_right hi, zero_mul, sum_const_zero, sub_zero] + +open scoped Classical in +private theorem reconstruct (hn : n ≤ R * U) {x : Index n → F} + (h : ∀ (p : Pos U U) (s : Pos R R), residual x p s = 0) : Correct x := by + let e (i : Fin n) : Pos R U := finProdFinEquiv.symm (Fin.castLE hn i) + have he (f : Fin n → F) (i) : pad f (e i) = f i := by + simp only [pad, e, Equiv.apply_symm_apply, Fin.val_castLE, dite_eq_left i.isLt, Fin.eta] + intro i j + have hh := h ((e i).2, (e j).2) ((e i).1, (e j).1) + simpa only [residual, mm, row, col, block, Prod.mk.eta, he, sub_eq_zero] using hh + +open scoped Classical in +/-- Enough distinct successful evaluations force every coefficient +of the block residual to vanish. -/ +theorem sound (hn : n ≤ R * U) {L : ℕ} (v : Fin L ↪ F) (x : Index n → F) (hx : ¬ Correct x) : + #{i | ∀ p : Pos U U, mm (left R x (v i)) (right R x (v i)) p = claimed R x (v i) p} < R * R + := by + by_contra! he + let S : Finset (Fin L) := {i | ∀ p : Pos U U, + mm (left R x (v i)) (right R x (v i)) p = claimed R x (v i) p} + let e : Fin (R * R) ↪ ↥S := (Fin.castLEEmb (show R * R ≤ Fintype.card ↥S by + rwa [Fintype.card_coe])).trans (Fintype.equivFin S).symm.toEmbedding + apply hx + apply reconstruct hn + intro p s + let c (i : Fin (R * R)) := residual x p (finProdFinEquiv.symm i) + have hinj : Function.Injective (fun i => v (e i).val) := + v.injective.comp (Subtype.val_injective.comp e.injective) + have hc : c = 0 := by + apply Matrix.eq_zero_of_forall_index_sum_pow_mul_eq_zero hinj + intro j + rw [← finProdFinEquiv.sum_comp] + simp only [c, Equiv.symm_apply_apply] + rw [← expand, (mem_filter.mp (e j).property).2 p, sub_self] + simpa only [c, Equiv.symm_apply_apply, Pi.zero_apply] using congrFun hc (finProdFinEquiv s) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Arithmetic instructions and equality tests in a block sketch -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset MvPolynomial + +variable {F : Type*} [Field F] {n R U : ℕ} + +open scoped Classical in +/-- The indexed operation `⟨U * U, fun i => mm (left R X (C t)) (right R X (C t)) +(finProdFinEquiv.symm i), fun i => claimed R X (C t) (finProdFinEquiv.symm i)⟩`. -/ +def sketch (n R U : ℕ) (t : F) : Test F n := + ⟨U * U, fun i => mm (left R X (C t)) (right R X (C t)) (finProdFinEquiv.symm i), + fun i => claimed R X (C t) (finProdFinEquiv.symm i)⟩ + +open scoped Classical in +private theorem eval_pad (x : Index n → F) (z : Pos R U) (f : Fin n → Poly F n) : + eval x (pad f z) = pad (fun i => eval x (f i)) z := by + unfold pad; split <;> simp_all + +open scoped Classical in +theorem sketch_accept (x : Index n → F) (t : F) : + (sketch n R U t).accept x ↔ + ∀ p : Pos U U, mm (left R x t) (right R x t) p = claimed R x t p := by + unfold sketch Test.accept + simp only [mm, left, right, claimed, row, col, block, map_sum, map_mul, map_pow, eval_C, + eval_pad, eval_X] + constructor + · intro h p + simpa only [Equiv.symm_apply_apply] using h (finProdFinEquiv p) + · exact fun h i => h (finProdFinEquiv.symm i) + +open scoped Classical in +private theorem substitute {m : ℕ} (h : Integral.Computes F U U n m) {S : Set (Poly F n)} + (A : Pos U n → Poly F n) (B : Pos n U → Poly F n) + (hS : inputs F n ⊆ S) (hA : Set.range A ⊆ S) (hB : Set.range B ⊆ S) : + CanMake S m (Set.range (mm A B)) := by + let f := eval₂Hom (C : F →+* Poly F n) (Sum.elim A B) + obtain ⟨V, hV, hout⟩ := h + obtain ⟨W, hW, hm⟩ := hV.map (U := S) f (by + rintro _ (⟨x, rfl⟩ | ⟨x, rfl⟩) + · simpa [f] using hS (show C x ∈ inputs F n from Or.inl ⟨x, rfl⟩) + · rcases x with x | x + · simpa [f, Integral.input] using hA ⟨x, rfl⟩ + · simpa [f, Integral.input] using hB ⟨x, rfl⟩) + refine ⟨m, le_rfl, W, hW, ?_⟩ + rintro _ ⟨p, rfl⟩ + simpa [mm, Integral.output, Integral.input, f] using hm _ (hout p) + +open scoped Classical in +private theorem pad_mem (z : Pos R U) (f : Fin n → Poly F n) (h : ∀ i, f i ∈ inputs F n) : + pad f z ∈ inputs F n := by + unfold pad + split + · exact h _ + · exact Or.inl ⟨0, map_zero _⟩ + +open scoped Classical in +private theorem prepare {I J : Type} [Fintype I] [Fintype J] + (t : F) (a : I → ℕ) (f : I → J → Poly F n) (h : ∀ i j, f i j ∈ inputs F n) : + CanMake (inputs F n) (Fintype.card J * (Fintype.card I * 2)) + (Set.range (fun j => ∑ i, (C t) ^ (a i) * f i j)) := by + apply CanMake.range + intro j + exact CanMake.linear (Or.inl ⟨0, map_zero _⟩) (fun i => Or.inl ⟨_, map_pow _ _ _⟩) (fun i + => h i j) + +open scoped Classical in +/-- The large rectangular multiplication is the only non-linear +part. Each scalar of the padded inputs contributes at most two gates. -/ +theorem sketch_cost {m : ℕ} (h : Integral.Computes F U U n m) (t : F) : + (sketch n R U t).cost (m + 4 * (R : ℝ) * U * n + 2 * ((R : ℝ) * U) ^ 2 + (U : ℝ) ^ 2) := by + let A : Pos U n → Poly F n := left R X (C t) + let B : Pos n U → Poly F n := right R X (C t) + let E : Pos U U → Poly F n := claimed R X (C t) + have hX (i) : X i ∈ inputs F n := Or.inr ⟨i, rfl⟩ + have hA : CanMake (inputs F n) (U * n * (R * 2)) (Set.range A) := by + unfold A left + simpa only [Pos, Fintype.card_prod, Fintype.card_fin] using + prepare t (fun i : Fin R => R * i.val) (row (U := U) X) (fun _ _ => pad_mem _ _ (fun _ + => hX _)) + have hB : CanMake (inputs F n) (n * U * (R * 2)) (Set.range B) := by + unfold B right + simpa only [Pos, Fintype.card_prod, Fintype.card_fin] using + prepare t (fun i : Fin R => i.val) (col (U := U) X) (fun _ _ => pad_mem _ _ (fun _ => hX _)) + have hE : CanMake (inputs F n) (U * U * (R * R * 2)) (Set.range E) := by + unfold E claimed + simpa only [Pos, Fintype.card_prod, Fintype.card_fin] using + prepare t (fun i : Pos R R => (finProdFinEquiv i).val) (block (U := U) X) + (fun _ _ => pad_mem _ _ (fun _ => pad_mem _ _ (fun _ => hX _))) + have hp := (hA.union hB).keep.trans (substitute h A B Set.subset_union_left + (fun _ hx => Or.inr (Or.inl hx)) (fun _ hx => Or.inr (Or.inr hx))) + obtain ⟨l, hl, V, hV, hv⟩ := hp.union hE + refine ⟨l, V, hV, fun i => ⟨hv (Or.inl ⟨_, rfl⟩), hv (Or.inr ⟨_, rfl⟩)⟩, ?_⟩ + have hh := (Nat.cast_le (α := ℝ)).mpr hl + change (l : ℝ) + (U * U : ℕ) ≤ _ + push_cast at hh ⊢ + linarith only [hh] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- Simulating each seed separately preserves its decision and probability. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open Filter Finset +variable {F : Type*} [Field F] {ρ η v : ℝ} + +open scoped Classical in +theorem Support.tree_possible (h : Support F ρ v) : TreeSupportPossible F ρ v := by + intro ε hε + filter_upwards [h ε hε (1 / 3) (by norm_num)] with n hn + obtain ⟨L, A, hL, size, cost, on, off⟩ := hn + choose V hv he using fun i => (A i).tree (cost i) + have pos : (0 : ℝ) < L := Nat.cast_pos.mpr hL + let u := (L : ℝ)⁻¹ + have mass : (∑ _ : Fin L, u) = 1 := by simp [u, pos.ne'] + refine ⟨Fin L, inferInstance, fun _ => u, fun _ => 0, V, + by simpa using size, fun _ => (inv_pos.mpr pos).le, + mass ▸ hasSum_fintype _, hv, ?_⟩ + intro x + simp only [tsum_fintype, he] + by_cases hx : Correct x + · simp only [hx, on x hx, ite_true, mass] + norm_num + · simp only [hx, iff_false, ite_not] + have loss : (∑ i, if (A i).accept x then u else 0) ≤ 1 / 3 := by + rw [← sum_filter, sum_const, nsmul_eq_mul] + exact (div_le_iff₀ pos).mpr (off x hx) + have eq (i) : (if (A i).accept x then 0 else u) = + u - (if (A i).accept x then u else 0) := by split <;> simp + simp_rw [eq] + rw [sum_sub_distrib, mass] + linarith + +open scoped Classical in +theorem Entropy.tree_possible (h : Entropy F η v) : TreeEntropyPossible F η v := by + intro ε hε + filter_upwards [h ε hε] with n hn + obtain ⟨L, A, w, hw, mass, budget, cost, correct⟩ := hn + choose V hv he using fun i => (A i).tree (cost i) + refine ⟨Fin L, inferInstance, w, fun _ => 0, V, ⟨_, hasSum_fintype _, ?_⟩, hw, + mass ▸ hasSum_fintype w, hv, ?_⟩ + · simpa only [neg_mul, sum_neg_distrib] using budget + · intro x + simpa only [tsum_fintype, he] using correct x + +open scoped Classical in +private theorem paths {n : ℕ} {ι : Type} {w : ι → ℝ} {t : ι → ℕ} (A : ∀ i, Tree F n (t i)) + {c : ℝ} (hc : ∀ i, ((A i).depth : ℝ) ≤ c) (ha : Accurate w (fun i => (A i).accept) Correct) : + ∃ V : ι → Verifier F n, (∀ i, (V i).cost c) ∧ Accurate w (fun i => (V i).accept) Correct := by + choose V hv he using fun i => (A i).simulate + refine ⟨V, fun i p hp => (hv i p hp).trans (hc i), ?_⟩ + simpa only [he] using ha + +open scoped Classical in +theorem TreeSupportPossible.possible (h : TreeSupportPossible F ρ v) : SupportPossible F ρ v := by + intro ε he + filter_upwards [h ε he] with n hn + obtain ⟨ι, _, w, t, A, hb, hw, hs, hc, ha⟩ := hn + obtain ⟨V, hv, ha⟩ := paths A hc ha + exact ⟨ι, inferInstance, w, V, hb, hw, hs, hv, ha⟩ + +open scoped Classical in +theorem TreeEntropyPossible.possible (h : TreeEntropyPossible F η v) : EntropyPossible F η v := by + intro ε he + filter_upwards [h ε he] with n hn + obtain ⟨ι, _, w, t, A, hb, hw, hs, hc, ha⟩ := hn + obtain ⟨V, hv, ha⟩ := paths A hc ha + exact ⟨ι, inferInstance, w, V, hb, hw, hs, hv, ha⟩ + +open scoped Classical in +theorem Support.possible (h : Support F ρ v) : SupportPossible F ρ v := h.tree_possible.possible + +open scoped Classical in +theorem Entropy.possible (h : Entropy F η v) : EntropyPossible F η v := h.tree_possible.possible + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +section +/- +# The rectangular expression in the verification characterization + +The rectangular benchmark evaluates the tradeoff and its two critical budgets. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +variable {F : Type*} [Field F] + +theorem shape {k : ℝ} (hk : 0 ≤ k) (hk' : k ≤ 1) : U k k 1 = (1 + k / 2) ^ 2 := by + rcases eq_or_lt_of_le hk with rfl | hk + · norm_num [U, benchmark] + rcases eq_or_lt_of_le hk' with rfl | hk' + · norm_num [U, benchmark] + rw [U, min_self, ite_eq_right hk'.not_ge, ite_eq_left le_rfl, benchmark, + max_eq_left (by nlinarith)] + field_simp + ring + +theorem support_formula (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + {ρ : ℝ} (hρ : 0 ≤ ρ) (hρ' : ρ ≤ 2) : + max 2 (exponent F (1 - ρ / 2) (1 - ρ / 2) 1) = max 2 ((3 / 2 - ρ / 4) ^ 2) := by + have hk : 0 ≤ 1 - ρ / 2 := by linarith + rw [all_shapes hr hs hk hk zero_le_one, shape hk (by linarith)] + congr 1 + ring + +theorem entropy_formula (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + {η : ℝ} (hη : 0 ≤ η) : + let ρ := min (3 * η) 2 + max 2 (exponent F (1 - ρ / 2) (1 - ρ / 2) 1) = max 2 ((3 / 2 - ρ / 4) ^ 2) := + support_formula hr hs (le_min (by positivity) (by norm_num)) (min_le_right _ _) + +private theorem critical_mem : 6 - 4 * Real.sqrt 2 ∈ Set.Icc (0 : ℝ) 2 := by + have hh := Real.sq_sqrt (by norm_num : (0 : ℝ) ≤ 2) + have hp := Real.sqrt_nonneg 2 + constructor <;> nlinarith + +theorem support_threshold {ρ : ℝ} (hρ : ρ ≤ 2) : + max 2 ((3 / 2 - ρ / 4) ^ 2) = 2 ↔ 6 - 4 * Real.sqrt 2 ≤ ρ := by + rw [max_eq_left_iff, ← Real.le_sqrt (by linarith) (by norm_num)] + constructor <;> intro h <;> linarith + +theorem entropy_threshold (η : ℝ) : + max 2 ((3 / 2 - min (3 * η) 2 / 4) ^ 2) = 2 ↔ (6 - 4 * Real.sqrt 2) / 3 ≤ η := by + rw [support_threshold (min_le_right _ _), le_min_iff, and_iff_left critical_mem.2] + constructor <;> intro h <;> linarith + +theorem least_support (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) : + IsLeast {ρ ∈ Set.Icc 0 2 | max 2 (exponent F (1 - ρ / 2) (1 - ρ / 2) 1) = 2} + (6 - 4 * Real.sqrt 2) := by + have he (ρ : ℝ) (hρ : ρ ∈ Set.Icc 0 2) : + max 2 (exponent F (1 - ρ / 2) (1 - ρ / 2) 1) = 2 ↔ 6 - 4 * Real.sqrt 2 ≤ ρ := by + rw [support_formula hr hs hρ.1 hρ.2, support_threshold hρ.2] + exact ⟨⟨critical_mem, (he _ critical_mem).mpr le_rfl⟩, fun ρ h => (he ρ h.1).mp h.2⟩ + +theorem least_entropy (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) : + IsLeast {η : ℝ | 0 ≤ η ∧ max 2 (exponent F (1 - min (3 * η) 2 / 2) (1 - min (3 * η) 2 / 2) 1) + = 2} + ((6 - 4 * Real.sqrt 2) / 3) := by + have he (η : ℝ) (hη : 0 ≤ η) : + max 2 (exponent F (1 - min (3 * η) 2 / 2) (1 - min (3 * η) 2 / 2) 1) = 2 ↔ + (6 - 4 * Real.sqrt 2) / 3 ≤ η := by + rw [entropy_formula hr hs hη, entropy_threshold] + have h : 0 ≤ (6 - 4 * Real.sqrt 2) / 3 := div_nonneg critical_mem.1 (by norm_num) + exact ⟨⟨h, (he _ h).mpr le_rfl⟩, fun η hη => (he η hη.1).mp hη.2⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # From a rectangular algorithm to uniform public-seed verification -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset Filter + +variable {F : Type*} [Field F] [Infinite F] + +open scoped Classical in +private theorem uniform {n U R m L : ℕ} {s c p : ℝ} + (h : Integral.Computes F U U n m) (hn : n ≤ R * U) (hL : 0 < L) (hs : (L : ℝ) ≤ s) + (hc : m + 4 * (R : ℝ) * U * n + 2 * ((R : ℝ) * U) ^ 2 + (U : ℝ) ^ 2 ≤ c) (hp : (R : ℝ) * R + ≤ p * L) : + Uniform F n s c p := by + let v : Fin L ↪ F := Fin.valEmbedding.trans (Infinite.natEmbedding F) + refine ⟨L, fun i => sketch n R U (v i), hL, hs, ?_, ?_, ?_⟩ + · intro i + obtain ⟨k, V, hV, hout, hk⟩ := sketch_cost h (R := R) (v i) + exact ⟨k, V, hV, hout, hk.trans hc⟩ + · intro x hx i + apply (sketch_accept x _).mpr + intro z + rw [← sub_eq_zero, expand] + simp only [complete hx, mul_zero, sum_const_zero] + · intro x hx + simp only [sketch_accept] + apply le_trans _ hp + exact_mod_cast (sound hn v x hx).le + +open scoped Classical in +private theorem dimensions {ρ : ℝ} (hρ : 0 ≤ ρ) (hρ' : ρ ≤ 2) {n : ℕ} (hn : 0 < n) : + let R := side n (ρ / 2) + let U := side n (1 - ρ / 2) + n ≤ R * U ∧ (R : ℝ) * R ≤ 4 * (n : ℝ) ^ ρ ∧ + 4 * (R : ℝ) * U * n + 2 * ((R : ℝ) * U) ^ 2 + (U : ℝ) ^ 2 ≤ 64 * (n : ℝ) ^ 2 := by + let R := side n (ρ / 2) + let U := side n (1 - ρ / 2) + have hn' : 0 < (n : ℝ) := by positivity + have hr : (R : ℝ) ≤ 2 * (n : ℝ) ^ (ρ / 2) := side_le hn (by linarith) + have hu : (U : ℝ) ≤ 2 * (n : ℝ) ^ (1 - ρ / 2) := side_le hn (by linarith) + have he : (n : ℝ) ^ (ρ / 2) * (n : ℝ) ^ (1 - ρ / 2) = n + := by rw [← Real.rpow_add hn', add_sub_cancel, Real.rpow_one] + have hm : (R : ℝ) * U ≤ 4 * n := by + have hh := mul_le_mul hr hu (by positivity) (by positivity) + linarith only [he, hh] + have hbound : (U : ℝ) ≤ 4 * n := + (le_mul_of_one_le_left (by positivity) (by exact_mod_cast side_pos hn (ρ / 2))).trans hm + refine ⟨?_, ?_, ?_⟩ + · have hh : (n : ℝ) ≤ (R : ℝ) * U := he.ge.trans + (mul_le_mul (Nat.le_ceil _) (Nat.le_ceil _) (by positivity) (by positivity)) + exact_mod_cast hh + · calc + _ ≤ (2 * (n : ℝ) ^ (ρ / 2)) ^ 2 := by rw [pow_two]; gcongr + _ = _ := by rw [mul_pow, ← Real.rpow_mul_natCast hn'.le]; norm_num + · calc + _ = 4 * ((R : ℝ) * U) * n + 2 * ((R : ℝ) * U) ^ 2 + (U : ℝ) ^ 2 := by ring + _ ≤ 4 * (4 * (n : ℝ)) * n + 2 * (4 * (n : ℝ)) ^ 2 + (4 * (n : ℝ)) ^ 2 := by gcongr + _ = _ := by ring + +open scoped Classical in +theorem support_of_rectangles {ρ v : ℝ} (hρ : 0 ≤ ρ) (hρ' : ρ ≤ 2) + (h : Integral.Admissible F (1 - ρ / 2) (1 - ρ / 2) 1 v) : Support F ρ (max 2 v) := by + intro ε hε p hp + obtain ⟨C, hC, hm⟩ := h (ε / 2) (half_pos hε) + obtain ⟨J, hJ⟩ := exists_nat_gt (1 / p) + have hj : 0 < J := Nat.cast_pos.mp ((by positivity : 0 < 1 / p).trans hJ) + have hp' : 1 ≤ p * J := by rw [mul_comm]; exact (div_le_iff₀ hp).mp hJ.le + have grow (e : ℝ) (he : 0 < e) := (tendsto_rpow_atTop he).comp tendsto_natCast_atTop_atTop + filter_upwards [eventually_gt_atTop 0, (grow ε hε).eventually_ge_atTop (4 * J), + (grow (ε / 2) (half_pos hε)).eventually_ge_atTop (C + 64)] with n hn hs hc + let R := side n (ρ / 2) + let U := side n (1 - ρ / 2) + have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast hn + have hr : 0 < R := side_pos hn _ + obtain ⟨hlo, hsize, hcost⟩ := dimensions hρ hρ' hn + obtain ⟨m, hcomp, hb⟩ := hm n hn + rw [show Integral.side n 1 = n from side_one n] at hcomp + refine uniform (L := J * (R * R)) hcomp hlo (by positivity) ?_ ?_ ?_ + · rw [Nat.cast_mul, Nat.cast_mul, Real.rpow_add (by positivity)] + calc + _ ≤ J * (4 * (n : ℝ) ^ ρ) := mul_le_mul_of_nonneg_left hsize (by positivity) + _ = (n : ℝ) ^ ρ * (4 * J) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left hs (by positivity) + · calc + _ ≤ C * (n : ℝ) ^ (v + ε / 2) + 64 * (n : ℝ) ^ 2 := by linarith + _ ≤ C * (n : ℝ) ^ (max 2 v + ε / 2) + 64 * (n : ℝ) ^ (max 2 v + ε / 2) := by + rw [← Real.rpow_two] + gcongr <;> linarith [le_max_left 2 v, le_max_right 2 v] + _ = (C + 64) * (n : ℝ) ^ (max 2 v + ε / 2) := by ring + _ ≤ (n : ℝ) ^ (ε / 2) * (n : ℝ) ^ (max 2 v + ε / 2) + := mul_le_mul_of_nonneg_right hc (by positivity) + _ = _ := by rw [← Real.rpow_add (by positivity)]; congr 1; ring + · rw [Nat.cast_mul, Nat.cast_mul, ← mul_assoc] + exact le_mul_of_one_le_left (by positivity) hp' + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +section +/- +# The cost forced by independent output combinations + +The finite bound uses the actual field exponent. At the benchmark, +the bound yields the verification tradeoff whenever a verifier +provides enough independent output combinations at low border rank. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Filter + +variable {F : Type*} [Field F] {n q r : ℕ} + +theorem Projected.size (h : Projected F n q r) : q ≤ n * n := by + obtain ⟨P, hq, _⟩ := h + simpa [Pos] using hq.trans P.rank_le_card_width + +private theorem log_size (h : Projected F n q r) (hn : 0 < n) (hq : 0 < q) : + Real.log q / 2 ≤ Real.log n := by + have he := Real.log_le_log (Nat.cast_pos.mpr hq) (show (q : ℝ) + ≤ (n : ℝ) * n by exact_mod_cast h.size) + rw [Real.log_mul (by positivity) (by positivity)] at he + linarith + +variable [Infinite F] + +theorem Projected.lower (h : Projected F n q r) (hn : 0 < n) (hq : 0 < q) : + Real.exp (exponent F (Real.log q / 2) (Real.log q / 2) (Real.log n)) ≤ r := by + obtain ⟨S, he, hcut⟩ := h.cells + have hS : S.Nonempty := Finset.card_pos.mp (he.symm ▸ hq) + have hv (x y z) : mask (ordinary F n n n) S x y z ≠ 0 ↔ (x, y) ∈ S := by simp [mask, ordinary] + have hh := hcut.cells hS hv hn hn hn + rw [he, short, min_self, min_eq_right (log_size h hn hq), + show Real.log (q : ℝ) - Real.log q / 2 = Real.log q / 2 by ring] at hh + exact hh + +private theorem finite_rate (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + {L : ℕ} {ρ v ε : ℝ} (hρ : 0 ≤ ρ) (hρ' : ρ ≤ 2) (hε : 0 < ε) + (hn : 2 ≤ n) (hL : (L : ℝ) ≤ (n : ℝ) ^ (ρ + ε)) (hv : (r : ℝ) ≤ (n : ℝ) ^ (v + ε)) + (harea : n * n ≤ L * q) (hp : Projected F n q r) : (3 / 2 - ρ / 4) ^ 2 ≤ v + 2 * ε := by + have hn' : 1 < (n : ℝ) := by exact_mod_cast hn + have hq : 0 < q := (Nat.pos_of_mul_pos_left ((Nat.mul_pos (by omega) (by omega)).trans_le harea)) + let t := Real.log (n : ℝ) + have ht : 0 < t := Real.log_pos hn' + let k := (Real.log (q : ℝ) / 2) / t + have hk : 0 ≤ k := div_nonneg (div_nonneg (Real.log_nonneg (by exact_mod_cast hq)) (by norm_num)) + ht.le + have hk' : k ≤ 1 := (div_le_one ht).mpr (log_size hp (by omega) hq) + have he : t * k = Real.log (q : ℝ) / 2 := mul_div_cancel₀ _ ht.ne' + have lower : 1 - ρ / 2 - ε / 2 ≤ k := by + have hb := (show (n : ℝ) * n ≤ (L : ℝ) * q by exact_mod_cast harea).trans + (mul_le_mul_of_nonneg_right hL (by positivity)) + have hh := Real.log_le_log (by positivity) hb + rw [Real.log_mul (by positivity) (by positivity), Real.log_mul (by positivity) (by positivity), + Real.log_rpow (by positivity)] at hh + apply le_of_mul_le_mul_left _ ht + rw [he] + unfold t + linarith only [hh] + have upper : (1 + k / 2) ^ 2 ≤ v + ε := by + have h := (hp.lower (by omega) hq).trans hv + rw [Real.rpow_def_of_pos (by positivity), Real.exp_le_exp] at h + have e := homogeneous F hk hk zero_le_one ht.le + rw [he, mul_one, all_shapes hr hs hk hk zero_le_one, shape hk hk'] at e + exact le_of_mul_le_mul_left (e.ge.trans h) ht + let x := 3 / 2 - ρ / 4 + let y := 1 + k / 2 + have hxy : 0 ≤ x + y ∧ x + y ≤ 3 := by unfold x y; constructor <;> linarith + have hsub : x - y ≤ ε / 4 := by unfold x y; linarith + have hh := mul_le_mul hsub hxy.2 hxy.1 (show 0 ≤ ε / 4 by positivity) + change y ^ 2 ≤ v + ε at upper + change x ^ 2 ≤ v + 2 * ε + linarith only [hh, upper, hε] + +theorem profile_lower (hr : Rigidity F) (hs : MatrixExponent.omega F = 9 / 4) + {ρ v : ℝ} (hρ : 0 ≤ ρ) (hρ' : ρ ≤ 2) (hv : 2 ≤ v) + (h : ∀ ε > (0 : ℝ), ∀ᶠ n : ℕ in atTop, ∃ L q r : ℕ, (L : ℝ) ≤ (n : ℝ) ^ (ρ + ε) ∧ + (r : ℝ) ≤ (n : ℝ) ^ (v + ε) ∧ n * n ≤ L * q ∧ Projected F n q r) : + max 2 ((3 / 2 - ρ / 4) ^ 2) ≤ v := by + refine max_le hv (le_of_forall_pos_le_add fun ε hε => ?_) + obtain ⟨n, hn, L, q, r, hL, hv', ha, hp⟩ := ((eventually_ge_atTop 2).and (h (ε / 2) (half_pos + hε))).exists + linarith only [finite_rate hr hs hρ hρ' (half_pos hε) hn hL hv' ha hp] + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Public-seed verification lower bounds + +Both budgets give a finite set of seeds with a strict acceptance +gap. Its size bounds the loss of independent output combinations. +Reading entries gives a quadratic bound even for large seed sets. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Filter Finset + +variable {F : Type*} [Field F] {ρ η v : ℝ} + +open scoped Classical in +private def Retained (F : Type*) [Field F] (ρ v : ℝ) : Prop := + ∀ ε > (0 : ℝ), ∀ᶠ n : ℕ in atTop, + ∃ (ι : Type) (w : ι → ℝ) (A : ι → Verifier F n) (S : Finset ι), + (S.card : ℝ) ≤ (n : ℝ) ^ (ρ + ε) ∧ (∀ i, 0 ≤ w i) ∧ HasSum w 1 ∧ + (∀ i, (A i).cost ((n : ℝ) ^ (v + ε))) ∧ Accurate w (fun i => (A i).accept) Correct ∧ + Gap w (fun i => (A i).accept) Correct S + +open scoped Classical in +private theorem of_support (h : SupportPossible F ρ v) : Retained F ρ v := by + intro ε he + filter_upwards [h ε he] with n hn + obtain ⟨ι, _, w, A, hsize, hw, hs, hc, ha⟩ := hn + exact ⟨ι, w, A, univ, hsize, hw, hs, hc, ha, finite_gap hw hs ha⟩ + +open scoped Classical in +private theorem of_entropy (h : EntropyPossible F η v) (hη : 0 ≤ η) : Retained F (3 * η) v := by + intro ε he + filter_upwards [h (ε / 4) (by positivity), eventually_ge_atTop 2] with n hn h₂ + obtain ⟨ι, _, w, A, ⟨E, hE, hb⟩, hw, hs, hc, ha⟩ := hn + obtain ⟨S, _, hcard, hgap⟩ := entropy_gap hw hs ha hE h₂ hη he hb + refine ⟨ι, w, A, S, hcard, hw, hs, ?_, ha, hgap⟩ + intro i p hp + exact (hc i p hp).trans (Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast (show 1 + ≤ n by omega)) (by linarith)) + +open scoped Classical in +private theorem absorb (v c : ℝ) {ε : ℝ} (he : 0 < ε) : + ∀ᶠ n : ℕ in atTop, c * (n : ℝ) ^ (v + ε / 2) < (n : ℝ) ^ (v + ε) := by + have h := (tendsto_rpow_atTop (half_pos he)).comp tendsto_natCast_atTop_atTop + filter_upwards [h.eventually_gt_atTop c, eventually_gt_atTop 0] with n hn hp + have nh : 0 < (n : ℝ) := Nat.cast_pos.mpr hp + calc + _ < (n : ℝ) ^ (ε / 2) * (n : ℝ) ^ (v + ε / 2) := mul_lt_mul_of_pos_right hn (by positivity) + _ = _ := by rw [← Real.rpow_add nh]; congr 1; ring + +open scoped Classical in +private theorem quadratic (h : Retained F ρ v) : 2 ≤ v := by + by_contra! hv + have hp : 0 < 2 - v := sub_pos.mpr hv + obtain ⟨n, ⟨ι, w, A, _, _, hw, hs, hc, ha, _⟩, hn⟩ + := ((h _ (half_pos hp)).and (absorb v 9 hp)).exists + rw [show v + (2 - v) = 2 by ring, Real.rpow_two] at hn + exact hn.not_ge (read_bound hw hs A hc ha) + +variable [IsAlgClosed F] [CharZero F] + +open scoped Classical in +private theorem gap_lower (h : Retained F ρ v) (hr : Rigidity F) (hs : MatrixExponent.omega F + = 9 / 4) + (hρ : 0 ≤ ρ) (ht : ρ ≤ 2) : max 2 ((3 / 2 - ρ / 4) ^ 2) ≤ v := by + apply profile_lower hr hs hρ ht (quadratic h) + intro ε he + filter_upwards [h _ (half_pos he), absorb v 4 he, eventually_ge_atTop 1] with n hn hp h₁ + obtain ⟨ι, w, A, S, hcard, hw, _, hc, _, hg⟩ := hn + obtain ⟨q, r, hcost, hsize, hrank⟩ := gap_projection (show 0 + < n by omega) (fun i _ => hw i) (fun i _ => hc i) hg + refine ⟨S.card, q, r, ?_, hcost.trans hp.le, hsize, hrank⟩ + exact hcard.trans (Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast h₁) (by linarith)) + +open scoped Classical in +theorem SupportPossible.lower (h : SupportPossible F ρ v) (hr : Rigidity F) (hs : + MatrixExponent.omega F = 9 / 4) + (hρ : 0 ≤ ρ) (ht : ρ ≤ 2) : max 2 ((3 / 2 - ρ / 4) ^ 2) ≤ v := + gap_lower (of_support h) hr hs hρ ht + +open scoped Classical in +theorem EntropyPossible.lower (h : EntropyPossible F η v) (hr : Rigidity F) (hs : + MatrixExponent.omega F = 9 / 4) + (hη : 0 ≤ η) : max 2 ((3 / 2 - min (3 * η) 2 / 4) ^ 2) ≤ v := by + have he := of_entropy h hη + by_cases ht : 3 * η ≤ 2 + · rw [min_eq_left ht] + exact gap_lower he hr hs (by positivity) ht + · rw [min_eq_right (le_of_not_ge ht)] + norm_num + exact quadratic he + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Model.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Model.lean new file mode 100644 index 0000000000..7551def33a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Model.lean @@ -0,0 +1,92 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Model +public import Mathlib.Algebra.MvPolynomial.Eval + +/-! +# Public seeds and division-free arithmetic verification + +Each seed chooses a straight-line program followed by scalar equality +tests. Its cost counts all binary arithmetic instructions and all tests. +The straight-line program for a seed is chosen before its equality tests. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Filter Finset + +open scoped Classical in +/-- Indexes the index by the coordinates of `Fin 3 × Rectangle.Pos n n`. -/ +abbrev Index (n : ℕ) := Fin 3 × Rectangle.Pos n n +open scoped Classical in +/-- Computes the poly by the application `MvPolynomial (Index n) F`. -/ +abbrev Poly (F : Type*) [CommRing F] (n : ℕ) := MvPolynomial (Index n) F + +open scoped Classical in +/-- The set of values attained by `MvPolynomial.C ∪ Set.range MvPolynomial.X`. -/ +def inputs (F : Type*) [CommRing F] (n : ℕ) : Set (Poly F n) := + Set.range MvPolynomial.C ∪ Set.range MvPolynomial.X + +variable {F : Type*} [CommRing F] {n : ℕ} + +open scoped Classical in +/-- The condition `∀ i j : Fin n, ∑ k, x (0, i, k) * x (1, k, j) = x (2, i, j)` on the specified +data. -/ +def Correct (x : Index n → F) : Prop := + ∀ i j : Fin n, ∑ k, x (0, i, k) * x (1, k, j) = x (2, i, j) + +open scoped Classical in +/-- The data for the test construction, including `count`, `left`, `right`. -/ +structure Test (F : Type*) [CommRing F] (n : ℕ) where + /-- The number of entries. -/ + count : ℕ + /-- The left-side data carried by `Test`, with type `Fin count → Poly F n`. -/ + left : Fin count → Poly F n + /-- The right-side data carried by `Test`, with type `Fin count → Poly F n`. -/ + right : Fin count → Poly F n + +open scoped Classical in +/-- The condition `∀ i, MvPolynomial.eval x (T.left i) = MvPolynomial.eval x (T.right i)` on the +specified data. -/ +def Test.accept (T : Test F n) (x : Index n → F) : Prop := + ∀ i, MvPolynomial.eval x (T.left i) = MvPolynomial.eval x (T.right i) + +open scoped Classical in +/-- The condition `∃ (m : ℕ) (V : Set (Poly F n)), Integral.Build (inputs F n) m V ∧ (∀ i, +T.left i ∈ V ∧ T.right i ∈ V) ∧ (m : ℝ) + T.count ≤ c` on the specified data. -/ +def Test.cost (T : Test F n) (c : ℝ) : Prop := + ∃ (m : ℕ) (V : Set (Poly F n)), Integral.Build (inputs F n) m V ∧ + (∀ i, T.left i ∈ V ∧ T.right i ∈ V) ∧ (m : ℝ) + T.count ≤ c + +open scoped Classical in +/-- The uniform of type `Prop` for the given inputs. -/ +def Uniform (F : Type*) [CommRing F] (n : ℕ) (s c p : ℝ) : Prop := + ∃ (L : ℕ) (A : Fin L → Test F n), 0 < L ∧ (L : ℝ) ≤ s ∧ (∀ i, (A i).cost c) ∧ + (∀ x, Correct x → ∀ i, (A i).accept x) ∧ + ∀ x, ¬ Correct x → (#{i | (A i).accept x} : ℝ) ≤ p * L + +open scoped Classical in +/-- The condition `∀ ε > (0 : ℝ), ∀ p > (0 : ℝ), ∀ᶠ n : ℕ in atTop, Uniform F n ((n : ℝ) ^ (ρ + +ε)) ((n : ℝ) ^ (v + ε)) p` on the specified data. -/ +def Support (F : Type*) [CommRing F] (ρ v : ℝ) : Prop := + ∀ ε > (0 : ℝ), ∀ p > (0 : ℝ), ∀ᶠ n : ℕ in atTop, Uniform F n ((n : ℝ) ^ (ρ + ε)) ((n : ℝ) ^ (v + + ε)) p + +open scoped Classical in +/-- The entropy of type `Prop` for the given inputs. -/ +def Entropy (F : Type*) [CommRing F] (η v : ℝ) : Prop := + ∀ ε > (0 : ℝ), ∀ᶠ n : ℕ in atTop, + ∃ (L : ℕ) (A : Fin L → Test F n) (w : Fin L → ℝ), + (∀ i, 0 ≤ w i) ∧ (∑ i, w i) = 1 ∧ -(∑ i, w i * Real.log (w i)) ≤ (η + ε) * Real.log n ∧ + (∀ i, (A i).cost ((n : ℝ) ^ (v + ε))) ∧ + ∀ x, (∑ i, if (A i).accept x ↔ Correct x then w i else 0) ≥ 2 / 3 + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Possible.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Possible.lean new file mode 100644 index 0000000000..436886bd2b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/Possible.lean @@ -0,0 +1,888 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.SimpleLift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Gaps +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Model +public import Mathlib.LinearAlgebra.Matrix.Rank +public import Mathlib.LinearAlgebra.Finsupp.LinearCombination +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Speedup.Dense +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Mask +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.FiniteModel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Border.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Geometry.Jacobian +public import Mathlib.Algebra.BigOperators.Fin + +/-! +# One small isolated system for generic matrix multiplication + +The shared affine products come from a single accepting path. +The additional measurements lose at most the stated number of +independent output coordinates. +-/ + +universe u + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +variable {F K : Type*} [Field F] [Field K] [Algebra F K] + [CharZero K] [IsAlgClosed F] [IsAlgClosed K] {n : ℕ} + +open scoped Classical in +theorem isolated_jet (hn : 0 < n) + {ι : Type*} {w : ι → ℝ} {S : Finset ι} {A : ι → Verifier F n} {c : ℝ} + (hw : ∀ i ∈ S, 0 ≤ w i) (hc : ∀ i ∈ S, (A i).cost c) + (gap : Gap w (fun i => (A i).accept) Correct S) + {X : PairIndex n → K} (hx : AlgebraicIndependent F X) : + ∃ q d : ℕ, (q : ℝ) ≤ 2 * c ∧ d ≤ n * n ∧ n * n ≤ S.card * (n * n - d) ∧ + ∃ (σ : Type) (_ : Fintype σ) (J : Jet F (PairIndex n) σ q d) + (m : Fin d → K) (y : σ → K) (pos : Pos n n → σ), + y ∘ pos = beta X ∧ Isolated y (Ideal.span (Set.range (J.system X m))) := by + obtain ⟨l, hl, hs, p, hp, he⟩ := specialization hn hw hc gap hx + obtain ⟨i, d, hd, hr, b, y, H, h⟩ := path_cut hl p X (beta X) he + obtain ⟨J, m, hJ⟩ := (p i).jet X b (beta X) y H h + have size : ((p i).equations.length : ℝ) ≤ 2 * (p i).code.length := by + exact_mod_cast (p i).equations_length + exact ⟨_, d, size.trans (mul_le_mul_of_nonneg_left (hp i) (by norm_num)), hd, + hr.trans (Nat.mul_le_mul_right _ hs), (p i).Unk, inferInstance, J, m, _, Sum.inl, rfl, hJ⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Arithmetic verification with a public random seed + +The seed distribution is input independent. Each outcome selects a +finite collection of accepting paths with a uniform bound on their +lengths. Accuracy is pointwise, allowing error on either answer. +Entropy uses natural logarithms in both the budget and its rate. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Filter +variable (F : Type*) [Field F] + +/-- The support possible of type `Prop` for the given inputs. -/ +def SupportPossible (ρ v : ℝ) : Prop := + ∀ ε > (0 : ℝ), ∀ᶠ n : ℕ in atTop, + ∃ (ι : Type) (_ : Fintype ι) (w : ι → ℝ) (A : ι → Verifier F n), + (Fintype.card ι : ℝ) ≤ (n : ℝ) ^ (ρ + ε) ∧ (∀ i, 0 ≤ w i) ∧ HasSum w 1 ∧ + (∀ i, (A i).cost ((n : ℝ) ^ (v + ε))) ∧ Accurate w (fun i => (A i).accept) Correct + +/-- The entropy possible of type `Prop` for the given inputs. -/ +def EntropyPossible (η v : ℝ) : Prop := + ∀ ε > (0 : ℝ), ∀ᶠ n : ℕ in atTop, + ∃ (ι : Type) (_ : Countable ι) (w : ι → ℝ) (A : ι → Verifier F n), + (∃ E, HasSum (fun i => -w i * Real.log (w i)) E ∧ E ≤ (η + ε) * Real.log n) ∧ + (∀ i, 0 ≤ w i) ∧ HasSum w 1 ∧ (∀ i, (A i).cost ((n : ℝ) ^ (v + ε))) ∧ + Accurate w (fun i => (A i).accept) Correct + +/-- The infimum of `{v : ℝ | SupportPossible F ρ v}`. -/ +def supportExponent (ρ : ℝ) := sInf {v : ℝ | SupportPossible F ρ v} +/-- The infimum of `{v : ℝ | EntropyPossible F η v}`. -/ +def entropyExponent (η : ℝ) := sInf {v : ℝ | EntropyPossible F η v} + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Cost of detecting single-entry errors in a proposed product -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +open Filter Finset +variable {ι X J : Type*} {w : ι → ℝ} {accept : ι → X → Prop} {good : X → Prop} + (hw : ∀ i, 0 ≤ w i) (hs : HasSum w 1) (ha : Accurate w accept good) + +include hw hs ha in +open scoped Classical in +/-- Every error must be detected on at least one third of the seed +mass. Count errors first on a finite subset, then take its mass to one. -/ +private theorem detect [Fintype J] (x : X) (y : J → X) (hx : good x) (hy : ∀ j, ¬good (y j)) + (C : ℝ) (hc : ∀ i, accept i x → ((univ.filter (fun j => ¬accept i (y j))).card : ℝ) ≤ C) : + (Fintype.card J : ℝ) ≤ 3 * C := by + have hC : 0 ≤ C := by + by_contra! h + have hn (i) : ¬accept i x := fun hi => + h.not_ge ((Nat.cast_nonneg _).trans (hc i hi)) + have := ha x + simp only [hx, iff_true, hn, ite_false, tsum_zero] at this + norm_num at this + let δ i j := (if accept i x then w i else 0) - (if accept i (y j) then w i else 0) + have ht (i : ι) : ∑ j, δ i j ≤ C * w i := by + by_cases hi : accept i x + · have he (j) : δ i j = if ¬accept i (y j) then w i else 0 := by + by_cases h : accept i (y j) <;> simp [δ, hi, h] + simp_rw [he] + rw [← sum_filter, sum_const, nsmul_eq_mul] + exact mul_le_mul_of_nonneg_right (hc i hi) (hw i) + · apply le_trans _ (mul_nonneg hC (hw i)) + apply sum_nonpos + intro j _ + by_cases h : accept i (y j) <;> simp [δ, hi, h, hw] + have bound (S : Finset ι) : (Fintype.card J : ℝ) * ((∑ i ∈ S, w i) - 2 / 3) ≤ C := by + calc + _ = ∑ _j : J, ((∑ i ∈ S, w i) - 2 / 3) := by simp only [sum_const, card_univ, nsmul_eq_mul] + _ ≤ ∑ j, ∑ i ∈ S, δ i j := by + apply sum_le_sum + intro j _ + simpa only [δ, sum_sub_distrib] using retained_gap hw hs ha S hx (hy j) + _ = ∑ i ∈ S, ∑ j, δ i j := sum_comm + _ ≤ ∑ i ∈ S, C * w i := sum_le_sum (fun i _ => ht i) + _ ≤ C := by + rw [← mul_sum] + exact mul_le_of_le_one_right hC (sum_le_hasSum S (fun i _ => hw i) hs) + have htend : Tendsto (fun S : Finset ι => ∑ i ∈ S, w i) atTop (nhds 1) := hs + have := le_of_tendsto ((htend.sub_const (2 / 3)).const_mul (Fintype.card J : ℝ)) + (Eventually.of_forall bound) + linarith + +variable {F : Type*} [Field F] {n : ℕ} + +open scoped Classical in +private def wrong (p : Rectangle.Pos n n) (i : Index n) : F := + if i = (2, p) then 1 else 0 + +open scoped Classical in +private theorem wrong_not_correct (p : Rectangle.Pos n n) : ¬ Correct (wrong (F := F) p) := by + intro h + have := h p.1 p.2 + simp [wrong, Prod.ext_iff] at this + +include hw hs in +open scoped Classical in +/-- This bound uses no restriction on support size or entropy. -/ +theorem read_bound (A : ι → Verifier F n) {c : ℝ} (hc : ∀ i, (A i).cost c) + (ha : Accurate w (fun i => (A i).accept) Correct) : (n : ℝ) ^ 2 ≤ 9 * c := by + let z : Index n → F := fun _ => 0 + have hz : Correct z := by simp [Correct, z] + have h : (Fintype.card (Rectangle.Pos n n) : ℝ) ≤ 3 * (3 * c) := by + apply detect hw hs ha z wrong hz wrong_not_correct (3 * c) + intro i hi + obtain ⟨W, hW, hread⟩ := (A i).read (hc i) hi + apply le_trans _ hW + apply Nat.cast_le.mpr + apply card_le_card_of_injOn (fun p => (2, p)) + · intro p hp + by_contra hn + apply (mem_filter.mp hp).2 + apply hread + intro j hj + have : j ≠ (2, p) := by rintro rfl; exact hn hj + simp [wrong, z, this] + · exact fun _ _ _ _ he => congrArg Prod.snd he + simp only [Rectangle.Pos, Fintype.card_prod, Fintype.card_fin, Nat.cast_mul] at h + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Simulating an arithmetic tree by existential paths + +Each path keeps the constraints accumulated on its branch. +A fresh register is uniquely determined by its instruction. +A failed division costs a single equality test. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +variable {F : Type*} {n t : ℕ} + +open scoped Classical in +private def Instruction.raise : Instruction F n t → Instruction F n (t + 1) + | .eq a b => .eq a.raise b.raise + | .ne a b => .ne a.raise b.raise + | .op f a b c => .op f a.raise b.raise c.raise + | .div a b c => .div a.raise b.raise c.raise + +namespace Tree + +variable [Field F] +open scoped Classical in +private abbrev Code (F : Type*) (n t : ℕ) := List (Instruction F n t) + +open scoped Classical in +private def paths {t : ℕ} : Tree F n t → Code F n t → Verifier F n + | .yes, p => [⟨t, p⟩] + | .no, _ => [] + | .test a b u v, p => paths u (.eq a b :: p) ++ paths v (.ne a b :: p) + | .op f a b u, p => paths u (.op f a.raise b.raise (.aux (Fin.last t)) :: p.map Instruction.raise) + | .divide a b u v, p => paths v (.eq b (.scalar 0) :: p) ++ + paths u (.div a.raise b.raise (.aux (Fin.last t)) :: p.map Instruction.raise) + +open scoped Classical in +private theorem paths_length (u : Tree F n t) (p : Code F n t) (q : Path F n) + (h : q ∈ paths u p) : q.code.length ≤ p.length + u.depth := by + induction u with + | yes => + simp only [paths, List.mem_singleton] at h + subst q + simp [depth] + | no => simp [paths] at h + | test _ _ _ _ hu hv => + rcases List.mem_append.mp h with hl|hr + · have := hu _ hl + simp only [depth, List.length_cons] at * + omega + · have := hv _ hr + simp only [depth, List.length_cons] at * + omega + | op _ _ _ _ hu => + have := hu _ h + simp only [depth, List.length_cons, List.length_map] at * + omega + | divide _ _ _ _ hu hv => + rcases List.mem_append.mp h with hl|hr + · have := hv _ hl + simp only [depth, List.length_cons] at * + omega + · have := hu _ hr + simp only [depth, List.length_cons, List.length_map] at * + omega + +open scoped Classical in +private def valid (p : Code F n t) (x : Index n → F) (w : Fin t → F) := + ∀ i ∈ p, i.holds x w + +open scoped Classical in +private theorem valid_cons (p : Code F n t) (i : Instruction F n t) (x w) : + valid (i::p) x w ↔ i.holds x w ∧ valid p x w := by + simp [valid] + +open scoped Classical in +private theorem valid_raise (p : Code F n t) (x w) : + valid (p.map Instruction.raise) x w ↔ valid p x (Fin.init w) := by + have h (i : Instruction F n t) : i.raise.holds x w ↔ i.holds x (Fin.init w) := by + cases i <;> simp [Instruction.raise, Instruction.holds] + simp only [valid, List.forall_mem_map, h] + +open scoped Classical in +private theorem append (A B : Verifier F n) (x) : + (A++B).accept x ↔ A.accept x ∨ B.accept x := by + simp only [Verifier.accept, List.mem_append, or_and_right, exists_or] + +omit [Field F] in +open scoped Classical in +private theorem exists_snoc (P : (Fin (t + 1) → F) → Prop) : + (∃ w, P w) ↔ ∃ w : Fin t → F, ∃ y, P (Fin.snoc w y) := by + constructor + · rintro ⟨w, hw⟩ + exact ⟨Fin.init w, w (Fin.last t), by rwa [Fin.snoc_init_self]⟩ + · rintro ⟨w, y, hy⟩ + exact ⟨_, hy⟩ + +open scoped Classical in +private theorem branch {α : Type*} (P C U V : α → Prop) : + (∃ w, (P w ∧ C w) ∧ U w) ∨ (∃ w, (¬P w ∧ C w) ∧ V w) ↔ + ∃ w, C w ∧ (if P w then U w else V w) := by + rw [← exists_or] + apply exists_congr + intro w + by_cases h : P w <;> simp [h] + +open scoped Classical in +private theorem paths_accept (u : Tree F n t) (p : Code F n t) (x : Index n → F) : + (paths u p).accept x ↔ ∃ w, valid p x w ∧ u.run x w := by + induction u with + | yes => simp [paths, Verifier.accept, Path.accept, valid, run] + | no => simp [paths, Verifier.accept, run] + | test a b u v hu hv => + simp only [paths, append, hu, hv, valid_cons, Instruction.holds, run] + exact branch _ _ _ _ + | op f a b u hu => + rw [paths, hu, exists_snoc] + simp only [valid_cons, valid_raise, Instruction.holds, Operand.eval_raise, Operand.eval.eq_3, + Fin.init_snoc, Fin.snoc_last, and_assoc, exists_eq_left', run] + | divide a b u v hu hv => + rw [paths, append, hu, hv, exists_snoc] + simp only [valid_cons, valid_raise, Instruction.holds, Operand.eval_raise, Operand.eval.eq_1, + Operand.eval.eq_3, + Fin.init_snoc, Fin.snoc_last, and_assoc, exists_and_left, exists_eq_left', run] + simpa only [and_assoc] using branch (fun w => b.eval x w = 0) (valid p x) + (v.run x) (fun w => u.run x (Fin.snoc w (a.eval x w / b.eval x w))) + +open scoped Classical in +/-- Every finite tree has an existential path verifier of at most its depth. -/ +theorem simulate (u : Tree F n t) : ∃ A : Verifier F n, A.cost u.depth ∧ A.accept = u.accept := by + refine ⟨paths u [], ?_, funext fun x => propext ?_⟩ + · intro q h + have hh := paths_length u [] q h + simp only [List.length_nil, zero_add] at hh + exact_mod_cast hh + · simp [paths_accept, accept, valid] + +end Tree +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Simulating division-free tests by witness-free decision trees + +After a prefix of arithmetic operations, each available polynomial +can be read from a scalar, input, or register. Prepending this prefix +to any subsequent tree fixes all its initial registers and adds one +level per operation. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +variable {F : Type*} [Field F] {n m : ℕ} {T : Set (Poly F n)} + +open scoped Classical in +private def Implements (m : ℕ) (T : Set (Poly F n)) : Prop := + ∃ w : (Index n → F) → Fin m → F, + (∀ a ∈ T, ∃ b : Operand F n m, ∀ x, b.eval x (w x) = MvPolynomial.eval x a) ∧ + ∀ next : Tree F n m, ∃ v : Tree F n 0, + v.depth = m + next.depth ∧ ∀ x, v.accept x ↔ next.run x (w x) + +open scoped Classical in +private theorem Implements.step (h : Implements m T) (f : Op) + {a b : Poly F n} (ha : a ∈ T) (hb : b ∈ T) : Implements (m + 1) (insert (f.eval a b) T) := by + obtain ⟨w, read, attach⟩ := h + obtain ⟨u, hu⟩ := read _ ha + obtain ⟨v, hv⟩ := read _ hb + let val x := f.eval (u.eval x (w x)) (v.eval x (w x)) + let reg (x : Index n → F) : Fin (m + 1) → F := Fin.snoc (w x) (val x) + refine ⟨reg, ?_, ?_⟩ + · rintro q (rfl | hq) + · refine ⟨.aux (Fin.last m), fun x => ?_⟩ + change reg x (Fin.last m) = _ + simp only [reg, Fin.snoc_last, val, hu, hv] + cases f <;> simp [Op.eval] + · obtain ⟨s, hs⟩ := read _ hq + exact ⟨s.raise, fun x => by simp [reg, hs]⟩ + · intro next + obtain ⟨t, ht, he⟩ := attach (.op f u v next) + exact ⟨t, by rw [ht, Tree.depth]; omega, he⟩ + +open scoped Classical in +private theorem implements (h : Integral.Build (inputs F n) m T) : Implements m T := by + induction h with + | nil => + refine ⟨fun _ => Fin.elim0, ?_, ?_⟩ + · rintro _ (⟨a, rfl⟩ | ⟨i, rfl⟩) + · exact ⟨.scalar a, by simp [Operand.eval]⟩ + · exact ⟨.input i, by simp [Operand.eval]⟩ + · intro next + refine ⟨next, by simp, fun x => ?_⟩ + exact ⟨fun ⟨w, hw⟩ => Subsingleton.elim w Fin.elim0 ▸ hw, fun h => ⟨_, h⟩⟩ + | add _ ha hb ih => exact ih.step .add ha hb + | sub _ ha hb ih => exact ih.step .sub ha hb + | mul _ ha hb ih => exact ih.step .mul ha hb + +open scoped Classical in +private theorem tests {j : ℕ} (l r : Fin j → Operand F n m) : + ∃ v : Tree F n m, v.depth = j ∧ ∀ x w, v.run x w ↔ ∀ i, (l i).eval x w = (r i).eval x w := by + induction j with + | zero => exact ⟨.yes, rfl, by simp [Tree.run]⟩ + | succ j ih => + obtain ⟨v, hv, he⟩ := ih (l ∘ Fin.succ) (r ∘ Fin.succ) + refine ⟨.test (l 0) (r 0) v .no, by simp [Tree.depth, hv], fun x w => ?_⟩ + rw [Fin.forall_fin_succ] + by_cases h : (l 0).eval x w = (r 0).eval x w <;> simp [Tree.run, h, he] + +open scoped Classical in +/-- The deterministic tree needs no witness. Its depth counts one step +per arithmetic operation and one per final equality. -/ +theorem Test.tree (A : Test F n) {c : ℝ} (hc : A.cost c) : + ∃ v : Tree F n 0, (v.depth : ℝ) ≤ c ∧ v.accept = A.accept := by + obtain ⟨m, T, hb, ha, hc⟩ := hc + obtain ⟨w, read, attach⟩ := implements hb + choose l left using fun i => read _ (ha i).1 + choose r right using fun i => read _ (ha i).2 + obtain ⟨t, ht, he⟩ := tests l r + obtain ⟨v, hv, hv'⟩ := attach t + refine ⟨v, by simpa only [hv, ht, Nat.cast_add] using hc, funext fun x => propext ?_⟩ + simp only [hv', he, left, right, Test.accept] + +open scoped Classical in +theorem Test.simulate (A : Test F n) {c : ℝ} (hc : A.cost c) : + ∃ V : Verifier F n, V.cost c ∧ V.accept = A.accept := by + obtain ⟨t, ht, e⟩ := A.tree hc + obtain ⟨v, hv, e'⟩ := t.simulate + exact ⟨v, fun i hi => (hv i hi).trans ht, e'.trans e⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Independent output combinations in a matrix product -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification + +/-- Evaluates `if x.2 = y.1 then P z (x.1, y.2) else 0` at the input `(x, y, z)`. -/ +def projection {F : Type*} [Field F] {n : ℕ} (P : Matrix (Pos n n) (Pos n n) F) : + Coordinates n n n → F := + fun (x, y, z) => if x.2 = y.1 then P z (x.1, y.2) else 0 + +/-- The linear combinations need not be individual output entries. +The closure here uses polynomials and decompositions over F itself. -/ +def Projected (F : Type*) [Field F] (n q r : ℕ) : Prop := + ∃ P : Matrix (Pos n n) (Pos n n) F, q ≤ P.rank ∧ + ZClosure (rankSet F n n n r) (projection P) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Selecting independent leading output cells -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset + +variable {F : Type*} [Field F] {I : Type} [Fintype I] + +open scoped Classical in +/-- Restriction to all possible leading indices is injective on the +row space. Use any requested number of them as normalized pivots. -/ +theorem pivots (v : I → ℕ) (P : Matrix I I F) {q : ℕ} (hq : q ≤ P.rank) : + ∃ (S : Finset I) (A : Matrix I I F), S.card = q ∧ + (∀ i, (A * P) i i = if i ∈ S then 1 else 0) ∧ + ∀ i j, v j < v i → (A * P) i j = 0 := by + let V := Submodule.span F (Set.range P.row) + let t : Finset I := {i | ∃ w ∈ V, w i ≠ 0 ∧ ∀ j, v j < v i → w j = 0} + let f : V →ₗ[F] (t → F) := + { toFun := fun w i => w.val i, map_add' := fun _ _ => rfl, map_smul' := fun _ _ => rfl } + have hinj : Function.Injective f := by + apply LinearMap.ker_eq_bot.mp + apply bot_unique + intro w hw + have hz : f w = 0 := hw + change w = 0 + apply Subtype.ext + funext i + change w.val i = 0 + by_contra h + let U : Finset I := {j | w.val j ≠ 0} + obtain ⟨j, hj, hmin⟩ := U.exists_min_image v ⟨i, by simp [U, h]⟩ + have hj' : w.val j ≠ 0 := (mem_filter.mp hj).2 + have hlead : j ∈ t := by + refine mem_filter.mpr ⟨mem_univ _, w.val, w.property, hj', fun l hl => ?_⟩ + by_contra hn + exact hl.not_ge (hmin l (by simp [U, hn])) + exact hj' (congrFun hz ⟨j, hlead⟩) + have hdim := LinearMap.finrank_le_finrank_of_injective hinj + rw [Matrix.rank_eq_finrank_span_row] at hq + obtain ⟨S, hS, he⟩ := exists_subset_card_eq (show q ≤ t.card by simpa using hq.trans hdim) + have hl (i : I) : ∃ w ∈ V, (w i = if i ∈ S then 1 else 0) ∧ ∀ j, v j < v i → w j = 0 := by + by_cases hi : i ∈ S + · obtain ⟨w, hw, hi', hj⟩ := (mem_filter.mp (hS hi)).2 + exact ⟨(w i)⁻¹ • w, V.smul_mem _ hw, by simp [hi, hi'], fun j h => by simp [hj j h]⟩ + · exact ⟨0, V.zero_mem, by simp [hi], fun _ _ => rfl⟩ + choose w hw hdiag htri using hl + choose c hc using fun i => (Submodule.mem_span_range_iff_exists_fun _).mp (hw i) + let A : Matrix I I F := c + have heq (i j) : (A * P) i j = w i j := by + rw [Matrix.mul_apply] + simpa only [A, Finset.sum_apply, Pi.smul_apply, smul_eq_mul, Matrix.row] using congrFun (hc i) j + exact ⟨S, A, he, by simpa only [heq] using hdiag, by simpa only [heq] using htri⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Degenerating an output projection to its leading cells -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset + +variable {F : Type*} [Field F] {n q r : ℕ} + +open scoped Classical in +private def transform (a b : Fin n → F) (P : Matrix (Pos n n) (Pos n n) F) + (v : Coordinates n n n → F) : Coordinates n n n → F := + fun (x, y, z) => a x.1 * b y.2 * ∑ o, P z o * v (x, y, o) + +open scoped Classical in +private theorem transform_rank (a b : Fin n → F) (P : Matrix (Pos n n) (Pos n n) F) + {v : Coordinates n n n → F} (h : v ∈ rankSet F n n n r) : + transform a b P v ∈ rankSet F n n n r := by + obtain ⟨A, B, C, h⟩ := h + refine ⟨fun i x => a x.1 * A i x, fun i y => b y.2 * B i y, fun i z => ∑ o, P z o * C i o, ?_⟩ + intro x y z + simp only [transform, ← h, mul_sum] + rw [sum_comm] + exact sum_congr rfl (fun _ _ => sum_congr rfl (fun _ _ => by ring)) + +open scoped Classical in +open MvPolynomial in +private theorem transform_closure (a b : Fin n → F) (P : Matrix (Pos n n) (Pos n n) F) + {v : Coordinates n n n → F} (h : ZClosure (rankSet F n n n r) v) : + ZClosure (rankSet F n n n r) (transform a b P v) := by + intro p hp + let f : Coordinates n n n → MvPolynomial (Coordinates n n n) F := + fun (x, y, z) => C (a x.1 * b y.2) * ∑ o, C (P z o) * X (x, y, o) + have he (u : Coordinates n n n → F) : eval u (eval₂ C f p) = eval (transform a b P u) p := by + rw [hom_eval₂, show (eval u).comp C = RingHom.id F by ext; simp] + have hh : (fun i => eval u (f i)) = transform a b P u := by + funext ⟨x, y, z⟩ + simp [transform, f] + rw [hh] + rfl + rw [← he] + exact h _ fun u hu => (he u).trans (hp _ (transform_rank _ _ _ hu)) + +open scoped Classical in +private def degree (i : Pos n n) := (finProdFinEquiv i).val + +open scoped Classical in +/-- The additive weight of a cell is distinct for each pair of +indices. Negative powers cancel by the leading-index property. -/ +theorem Projected.cells [Infinite F] (h : Projected F n q r) : + ∃ S : Finset (Pos n n), S.card = q ∧ + ZClosure (rankSet F n n n r) (coefficients (mask (ordinary F n n n) S)) := by + obtain ⟨P, hq, hP⟩ := h + obtain ⟨S, A, he, hd, ht⟩ := pivots degree P hq + let path : Coordinates n n n → Polynomial F := fun (x, y, z) => + Polynomial.C (projection (A * P) (x, y, z)) * Polynomial.X ^ (degree (x.1, y.2) - degree z) + have hs (t : F) (hne : t ≠ 0) : ZClosure (rankSet F n n n r) (fun i => (path i).eval t) := by + let a (i : Fin n) := t ^ (n * i.val) + let b (j : Fin n) := t ^ j.val + let L : Matrix (Pos n n) (Pos n n) F := fun z o => (t ^ degree z)⁻¹ * A z o + convert transform_closure a b L hP using 1 + funext ⟨x, y, z⟩ + simp only [path, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_pow, Polynomial.eval_X, + transform, projection] + by_cases hh : x.2 = y.1 + · simp only [ite_eq_left hh, L, mul_assoc, ← mul_sum] + rw [← Matrix.mul_apply] + by_cases hlt : degree (x.1, y.2) < degree z + · simp [ht z (x.1, y.2) hlt] + · rw [pow_sub₀ t hne (le_of_not_gt hlt)] + change _ * (t ^ (y.2.val + n * x.1.val) * _) = _ + rw [pow_add] + unfold a b + ring + · simp [hh] + have hzero : (fun i => (path i).eval 0) = coefficients (mask (ordinary F n n n) S) := by + funext ⟨x, y, z⟩ + simp only [path, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_pow, Polynomial.eval_X, + projection, coefficients, mask, ordinary] + by_cases hxy : x.2 = y.1 + · by_cases he : (x.1, y.2) = z + · subst z + simp [hd, hxy] + · have he' : degree (x.1, y.2) ≠ degree z := fun h + => he (finProdFinEquiv.injective (Fin.ext h)) + have hn : ¬ (x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2) := fun h => he (Prod.ext h.1 h.2.2) + rw [ite_eq_right hn, ite_eq_left hxy] + rcases lt_or_gt_of_ne he' with hl | hl + · rw [ht _ _ hl, zero_mul] + · rw [zero_pow (by omega), mul_zero] + · simp [hxy] + refine ⟨S, he, ?_⟩ + rw [← hzero] + have hc := Speedup.path_closure (A := {v | ZClosure (rankSet F n n n r) v}) + path Polynomial.X Polynomial.X_ne_zero (fun t h => hs t (by simpa using h)) + exact fun p hp => hc p (fun _ h => h p hp) + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Descending projections by isolating their output cells -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset MvPolynomial + +variable {F K E : Type*} [Field F] [Field K] [Field E] {n q r : ℕ} + +open scoped Classical in +theorem rank_minor {I : Type} [Fintype I] [DecidableEq I] (S : Finset I) (P : Matrix I I F) + (h : ∀ i ∈ S, ∀ j ∈ S, P i j = if i = j then 1 else 0) : S.card ≤ P.rank := by + let f : ↥S → I := Subtype.val + have he : P.submatrix f f = 1 := by + ext i j + simp [Matrix.submatrix_apply, h _ i.property _ j.property, f, Matrix.one_apply] + simpa only [he, Matrix.rank_one, Fintype.card_coe] using P.rank_submatrix_le f f + +open scoped Classical in +/-- A leading-cell tensor descends to the ground field because its +coefficients are zeros and ones. No descent of the original +projection matrix is required. -/ +theorem Projected.descend [Infinite F] (f : F →+* K) (h : Projected K n q r) : Projected F n q r + := by + have : Infinite K := Infinite.of_injective f f.injective + obtain ⟨S, he, hS⟩ := h.cells + let P : Matrix (Pos n n) (Pos n n) F := fun i j => if i = j ∧ j ∈ S then 1 else 0 + have hr : S.card ≤ P.rank := rank_minor S P (fun _ _ _ hj => by simp [P, hj]) + refine ⟨P, he ▸ hr, ?_⟩ + have hc : f ∘ projection P = coefficients (mask (ordinary K n n n) S) := by + funext ⟨x, y, z⟩ + simp only [Function.comp_apply, projection, P, apply_ite f, map_one, map_zero, coefficients, + mask, ordinary, + ← ite_and, Prod.ext_iff] + congr 1 + exact propext (by grind) + intro p hp + apply f.injective + rw [map_zero, eval₂_comp, hc, ← eval_map] + exact hS _ (fun z hz => by rw [eval_map]; exact Border.identity_of_rank hp f hz) + +open scoped Classical in +/-- Specialize entries integral at a place, allowing arbitrary poles +in the rank decomposition itself. -/ +theorem specialize_rank [Infinite K] [Algebra K E] (A : Subalgebra K E) (ρ : A →ₐ[K] K) + (T : Coordinates n n n → A) (h : (fun z => (T z : E)) ∈ rankSet E n n n r) : + ZClosure (rankSet K n n n r) (ρ ∘ T) := by + intro p hp + have he := Border.identity_of_rank hp (algebraMap K E) h + have hA : eval₂ (algebraMap K A) T p = 0 := by + apply Subtype.val_injective + change A.val.toRingHom _ = A.val.toRingHom 0 + rw [map_zero, hom_eval₂] + exact he + have hh := congrArg ρ.toRingHom hA + rw [hom_eval₂, show ρ.toRingHom.comp (algebraMap K A) = RingHom.id K by ext; simp, map_zero] at hh + exact hh + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Specializing a projected quadratic term + +Some terms separate only in the output index. Eliminate their +output vectors over the valuation ring before specializing. The +remaining projection has an identity minor and bounded border rank. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset + +variable {F K E : Type*} [Field F] [Infinite F] [Field K] [Algebra F K] [Field E] [Algebra K E] + +theorem specialize_projection (A : Subalgebra K E) (hA : ∀ x : E, x ∈ A ∨ x⁻¹ ∈ A) + (ρ : A →ₐ[K] K) {n r d : ℕ} (T : Pos n n → Pos n n → Pos n n → A) + (hT : ∀ x y z, ρ (T x y z) = coefficients (ordinary K n n n) (x, y, z)) + (a b c : Fin r → Pos n n → E) (v : Fin d → Pos n n → Pos n n → E) (w : Fin d → Pos n n → E) + (he : ∀ x y z, (T x y z : E) = (∑ i, a i x * b i y * c i z) + ∑ i, v i x y * w i z) : + Projected F n (n * n - d) r := by + classical + have : Infinite K := Infinite.of_injective (algebraMap F K) (algebraMap F K).injective + obtain ⟨S, P, hs, hP, hkill⟩ := eliminate A hA w + let g := A.val.toRingHom + let Q : Matrix (Pos n n) (Pos n n) K := fun i j => ρ (P i j) + let v' : Coordinates n n n → A := fun (x, y, z) => ∑ o, P z o * T x y o + have hq : S.card ≤ Q.rank := rank_minor S Q (fun i hi j hj => by simp [Q, hP i hi j hj]) + have hh : (fun z => (v' z : E)) ∈ rankSet E n n n r := by + refine ⟨a, b, fun i z => ∑ o, (P z o : E) * c i o, fun x y z => ?_⟩ + have hz : (∑ o, (P z o : E) * (∑ i, v i x y * w i o)) = 0 := by + simp_rw [mul_sum] + rw [sum_comm] + apply sum_eq_zero + intro i _ + simp_rw [mul_left_comm _ (v i x y), ← mul_sum, hkill, mul_zero] + change _ = g (∑ o, P z o * T x y o) + rw [map_sum] + simp_rw [map_mul] + change _ = ∑ o, (P z o : E) * (T x y o : E) + simp only [he, mul_add, sum_add_distrib, hz, add_zero] + simp only [mul_sum] + rw [sum_comm] + exact sum_congr rfl (fun _ _ => sum_congr rfl (fun _ _ => by ring)) + have heq : ρ ∘ v' = projection Q := by + funext ⟨x, y, z⟩ + simp only [v', projection, Function.comp_apply, map_sum, map_mul, hT, coefficients, ordinary] + by_cases hxy : x.2 = y.1 + · have hj (o : Pos n n) : (x.1 = o.1 ∧ x.2 = y.1 ∧ y.2 = o.2) ↔ (x.1, y.2) = o := by + simp [Prod.ext_iff, hxy] + simp_rw [hj] + simp [hxy, Q, mul_ite] + · simp [hxy] + have hl := specialize_rank A ρ v' hh + rw [heq] at hl + apply Projected.descend (algebraMap F K) + exact ⟨Q, by simpa [Pos] using hs.trans hq, hl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- # Inverting a Jacobian preserves the count of mixed products -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Finset Matrix +open scoped Matrix + +variable {F K E : Type*} [Field F] [Infinite F] [Field K] [Algebra F K] [Field E] [Algebra K E] + +/-- Each quadratic term has two separated mixed derivatives. +Auxiliary measurements separate only in the output index. -/ +theorem linearized_projection (A : Subalgebra K E) (hA : ∀ x : E, x ∈ A ∨ x⁻¹ ∈ A) + (ρ : A →ₐ[K] K) {σ : Type} [Fintype σ] [DecidableEq σ] {n q d : ℕ} + (pos : Pos n n → σ) (T : Pos n n → Pos n n → σ → A) + (hT : ∀ x y z, ρ (T x y (pos z)) = coefficients (ordinary K n n n) (x, y, z)) + (J : Matrix σ σ E) (hJ : IsUnit J) (l₁ l₂ r₁ r₂ : Fin q → Pos n n → E) + (c : Matrix σ (Fin q) E) (f : Matrix σ (Fin d) E) (m : Fin d → Pos n n → Pos n n → E) + (he : ∀ x y i, (∑ t, J i t * (T x y t : E)) + + (∑ j, c i j * (l₁ j x * r₂ j y + r₁ j x * l₂ j y)) = ∑ j, f i j * m j x y) : + Projected F n (n * n - d) (2 * q) := by + let B : Matrix σ σ E := ↑(hJ.unit⁻¹) + have hi : B * J = 1 := by simpa [B] using hJ.unit.inv_mul + let g (j : Fin q) (z : Pos n n) := -(B * c) (pos z) j + rw [two_mul] + apply specialize_projection A hA ρ (fun x y z => T x y (pos z)) hT + (Fin.append l₁ r₁) (Fin.append r₂ l₂) (Fin.append g g) m (fun i z => (B * f) (pos z) i) + intro x y z + let X i := (T x y i : E) + let Y j := l₁ j x * r₂ j y + r₁ j x * l₂ j y + let Z j := m j x y + have h : J *ᵥ X + c *ᵥ Y = f *ᵥ Z := funext (he x y) + have hh := congrArg B.mulVec h + rw [mulVec_add, mulVec_mulVec, mulVec_mulVec, mulVec_mulVec, hi, one_mulVec] at hh + have hz := congrFun hh (pos z) + change (T x y (pos z) : E) + ∑ j, (B * c) (pos z) j * Y j = ∑ j, (B * f) (pos z) j * m j x y at hz + rw [eq_sub_of_add_eq hz, Fin.sum_univ_add] + simp only [Fin.append_left, Fin.append_right, g, Y, mul_add, sum_add_distrib, mul_neg, + sum_neg_distrib] + simp only [mul_comm] + abel + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Differentiating the deformed verification equations + +A left and a right coordinate derivation lift to the generic point +of the curve, fixing the parameter. Their action commutes with +specialization at the chosen branch. Therefore the mixed derivative +of the output specializes to the matrix multiplication tensor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial +variable {F L E : Type u} [Field F] [Field L] [Algebra F L] {n : ℕ} + +private theorem mixed_beta (X : PairIndex n → L) (x y z : Pos n n) + (D D' : Derivation F L L) + (h : ∀ i, D (X i) = if i = (0, x) then 1 else 0) + (h' : ∀ i, D' (X i) = if i = (1, y) then 1 else 0) : + D' (D (beta X z)) = coefficients (ordinary L n n n) (x, y, z) := by + obtain ⟨a, b⟩ := x + obtain ⟨c, d⟩ := y + by_cases hz : z.1 = a + · have first : D (beta X z) = X (1, b, z.2) := by + simp [beta, map_sum, D.leibniz, smul_eq_mul, h, hz] + rw [first, h'] + simp [coefficients, ordinary, hz, eq_comm] + · have first : D (beta X z) = 0 := by + simp [beta, map_sum, D.leibniz, smul_eq_mul, h, hz] + simp [first, coefficients, Ne.symm hz] + +variable [Infinite F] [CharZero L] [Field E] [Algebra L E] [Algebra F E] [IsScalarTower F L E] + {σ : Type} [Fintype σ] [DecidableEq σ] {q d : ℕ} + +theorem Jet.project (J : Jet F (PairIndex n) σ q d) (X : PairIndex n → L) + (m : Fin d → L) {t : E} (b : Branch L E t) (Y : σ → b.ring) (pos : Pos n n → σ) (c : σ → L) + (ht : Transcendental L t) + (hy : ∀ j, b.res (Y (pos j)) = beta X j) + (heq : ∀ i, aeval (fun j => (Y j : E)) (J.system X m i) = t * algebraMap L E (c i)) + (hinv : IsUnit (jacobian (J.system X m) (fun j => (Y j : E)))) + (hd : ∀ j : PairIndex n, ∃ D : Derivation F L L, + (∀ i, D (X i) = if i = j then 1 else 0) ∧ ∀ i, D (c i) = 0) : + Projected F n (n * n - d) (2 * q) := by + classical + have : CharZero E := charZero_of_injective_algebraMap (algebraMap L E).injective + choose D hX hc using hd + choose H ext fixed using fun i => exists_derivation_extension ht (D i) + let lift i := b.lift (H i) (D i) (ext i) (fixed i) + let T (x y : Pos n n) (s : σ) := lift (1, y) (lift (0, x) (Y s)) + have sample (x y z : Pos n n) : b.res (T x y (pos z)) = coefficients (ordinary L n n n) (x, y, z) + := by + unfold T lift + rw [b.specialize, b.specialize, hy] + exact mixed_beta X x y z _ _ (hX (0, x)) (hX (1, y)) + let a (j : σ) : E := Y j + let left (i : Fin 2) (j : Fin q) (x : Pos n n) := H (i, x) (aeval a ((J.left j).specialize X)) + let right (i : Fin 2) (j : Fin q) (x : Pos n n) := H (i, x) (aeval a ((J.right j).specialize X)) + refine linearized_projection b.ring b.val b.res pos T sample _ hinv + (left 0) (left 1) (right 0) (right 1) + (fun i j => algebraMap F E (J.c i j)) (fun i j => algebraMap F E (J.f i j)) + (fun j x y => H (1, y) (H (0, x) (algebraMap L E (m j)))) ?_ + intro x y i + apply J.mixed X m a (H (0, x)) (H (1, y)) i + · rw [heq, Derivation.leibniz, fixed, ext, hc, map_zero, smul_zero, smul_zero, add_zero, map_zero] + · intro j + rw [ext, hX] + split_ifs <;> simp + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end + +/- +# Independent projected outputs from equality-test verification + +An isolated system at a generic input comes from just one accepting +path. A second family of independent constants gives the direction +of a simple deformation. Input derivations fix these new constants. +The mixed derivatives recover matrix multiplication upon specialization. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open MvPolynomial +variable {F K : Type u} [Field F] [CharZero F] [Field K] [Algebra F K] [CharZero K] {n : ℕ} + +theorem Jet.project_isolated {σ : Type} [Fintype σ] {q d : ℕ} + (J : Jet F (PairIndex n) σ q d) (X : PairIndex n → K) (hx : AlgebraicIndependent F X) + (m : Fin d → K) (y : σ → K) (pos : Pos n n → σ) + (hy : y ∘ pos = beta X) (isolated : Isolated y (Ideal.span (Set.range (J.system X m)))) : + Projected F n (n * n - d) (2 * q) := by + classical + have : Infinite F := Infinite.of_injective (fun n : ℕ => (n : F)) Nat.cast_injective + let L := Free K σ + let c := Free.point K σ + let Y := algebraMap K L ∘ X + let m' := algebraMap K L ∘ m + have eq : MvPolynomial.map (algebraMap K L) ∘ J.system X m = J.system Y m' := + funext (J.map_system X m) + have h := simple_lift (J.system X m) y isolated c (Free.independent K σ) + dsimp only at h + rw [eq] at h + obtain ⟨E, field, alg, t, b, z, ht, hz, heq, hinv⟩ := h + let _ : Algebra F E := ((algebraMap L E).comp (algebraMap F L)).toAlgebra + have : IsScalarTower F L E := IsScalarTower.of_algebraMap_eq' rfl + refine J.project Y m' b z pos c ht ?_ heq hinv ?_ + · intro i + have hi : y (pos i) = beta X i := congrFun hy i + rw [hz, hi] + simp only [beta, Y, L, Function.comp_apply, map_sum, map_mul] + · intro j + obtain ⟨D, hD⟩ := derivation_of_independent hx (fun i => if i = j then (1 : K) else 0) + obtain ⟨d, hd, hc⟩ := Free.derivation σ D + refine ⟨d, fun i => ?_, hc⟩ + change d (algebraMap K L (X i)) = _ + rw [hd, hD] + split <;> simp + +/-- A strict gap on a finite set of seeds suffices. The rank bound +uses the maximum length of one path, independently of the seed count. -/ +theorem gap_projection [IsAlgClosed F] (hn : 0 < n) {ι : Type*} + {w : ι → ℝ} {S : Finset ι} {A : ι → Verifier F n} {c : ℝ} + (hw : ∀ i ∈ S, 0 ≤ w i) (hc : ∀ i ∈ S, (A i).cost c) + (gap : Gap w (fun i => (A i).accept) Correct S) : + ∃ q r : ℕ, (r : ℝ) ≤ 4 * c ∧ n * n ≤ S.card * q ∧ Projected F n q r := by + let X := Free.point F (PairIndex n) + have hx := Free.independent F (PairIndex n) + obtain ⟨q, d, hs, _, hd, σ, finite, J, m, y, pos, hy, hi⟩ := isolated_jet hn hw hc gap hx + refine ⟨n * n - d, 2 * q, ?_, hd, J.project_isolated X hx m y pos hy hi⟩ + push_cast + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/TreePossible.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/TreePossible.lean new file mode 100644 index 0000000000..a28b901bea --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Verification/TreePossible.lean @@ -0,0 +1,46 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Verification.Gaps + +/-! +# Verification by arithmetic and equality-test trees + +Each seed has its own finite tree and number of witness coordinates. +The witness is chosen after the seed is known. The size bound counts +the maximum number of arithmetic operations and tests on a path. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification +open Filter +variable (F : Type*) [Field F] + +/-- The tree support possible of type `Prop` for the given inputs. -/ +def TreeSupportPossible (ρ v : ℝ) : Prop := + ∀ ε > (0 : ℝ), ∀ᶠ n : ℕ in atTop, + ∃ (ι : Type) (_ : Fintype ι) (w : ι → ℝ) (t : ι → ℕ) (A : ∀ i, Tree F n (t i)), + (Fintype.card ι : ℝ) ≤ (n : ℝ) ^ (ρ + ε) ∧ (∀ i, 0 ≤ w i) ∧ HasSum w 1 ∧ + (∀ i, ((A i).depth : ℝ) ≤ (n : ℝ) ^ (v + ε)) ∧ Accurate w (fun i => (A i).accept) Correct + +/-- The tree entropy possible of type `Prop` for the given inputs. -/ +def TreeEntropyPossible (η v : ℝ) : Prop := + ∀ ε > (0 : ℝ), ∀ᶠ n : ℕ in atTop, + ∃ (ι : Type) (_ : Countable ι) (w : ι → ℝ) (t : ι → ℕ) (A : ∀ i, Tree F n (t i)), + (∃ E, HasSum (fun i => -w i * Real.log (w i)) E ∧ E ≤ (η + ε) * Real.log n) ∧ + (∀ i, 0 ≤ w i) ∧ HasSum w 1 ∧ (∀ i, ((A i).depth : ℝ) ≤ (n : ℝ) ^ (v + ε)) ∧ + Accurate w (fun i => (A i).accept) Correct + +/-- The infimum of `{v : ℝ | TreeSupportPossible F ρ v}`. -/ +def treeSupportExponent (ρ : ℝ) := sInf {v : ℝ | TreeSupportPossible F ρ v} +/-- The infimum of `{v : ℝ | TreeEntropyPossible F η v}`. -/ +def treeEntropyExponent (η : ℝ) := sInf {v : ℝ | TreeEntropyPossible F η v} + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle.Verification diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Weighted.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Weighted.lean new file mode 100644 index 0000000000..2898a1b34a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Weighted.lean @@ -0,0 +1,135 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Rows +public import Mathlib.Analysis.SpecialFunctions.Pow.Real + +/-! +# Discrete weighted growth of three polynomial prices + +Move the three widths from `n(A,B,C)` to `(n+1)(A,B,C)`. For each +pair of widths use both orders of the two increments. Their sum +allows the paired row estimates to be applied at each unchanged +width, both before and after the change. The harmonic lower bound +on the increments telescopes against a difference of logarithms. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +open Filter + +variable {P Q R : ℕ → ℕ → ℝ} {x y z : ℝ} + +/-- Paired growth for the logs of two prices with the same first input. -/ +def Increments (P Q : ℕ → ℕ → ℝ) (d : ℝ) : Prop := + ∀ m j k b c : ℕ, 0 < b → 0 < c → + 4 * d * b * c / (m + (j + b) + (k + c) + 2 : ℕ) ≤ + (P m (j + b) - P m j) * c + (Q m (k + c) - Q m k) * b + +theorem increments_of_rows (hx : 0 < x) + (hp : ∀ m n, 0 < P m n) (hq : ∀ m n, 0 < Q m n) + (h₁ : ∀ m, Row (fun n => (P m n) ^ (1 / x)) (fun n => (Q m n) ^ (1 / x)) m) + (h₂ : ∀ m, Row (fun n => (Q m n) ^ (1 / x)) (fun n => (P m n) ^ (1 / x)) m) : + Increments (fun m n => Real.log (P m n)) (fun m n => Real.log (Q m n)) x := by + intro m j k b c hb hc + have h := paired_secants (h₁ m) (h₂ m) j k b c hb hc + simp only [Real.log_rpow (hp _ _), Real.log_rpow (hq _ _)] at h + dsimp only + field_simp at h ⊢ + linarith only [h] + +private theorem Increments.step (hp : Increments P Q x) (hx : 0 ≤ x) + {A B C n m : ℕ} (hA : 0 < A) (hB : 0 < B) (hC : 0 < C) (hm : m ≤ (n + 1) * A) : + 4 * x * B * C / (((n : ℝ) + 3) * (A + B + C)) ≤ + (P m ((n + 1) * B) - P m (n * B)) * C + (Q m ((n + 1) * C) - Q m (n * C)) * B := by + have he := hp m (n * B) (n * C) B C hB hC + simp only [← Nat.succ_mul] at he + apply le_trans _ he + apply div_le_div_of_nonneg_left (by positivity) (by positivity) + push_cast + have hm' : (m : ℝ) ≤ (n + 1) * A := by exact_mod_cast hm + have hA' : 1 ≤ (A : ℝ) := by exact_mod_cast hA + linarith + +/-- If a potential grows by at least `v/(n+3)` at every step and is +at most `w log(n+3)+C`, then `v ≤ w`. -/ +private theorem growth {f : ℕ → ℝ} {v w C : ℝ} (hv : 0 ≤ v) + (hl : ∀ n : ℕ, v / ((n : ℝ) + 3) ≤ f (n + 1) - f n) + (hu : ∀ n, f n ≤ w * Real.log ((n : ℝ) + 3) + C) : v ≤ w := by + have hb (n : ℕ) : f 0 + v * (Real.log ((n : ℝ) + 3) - Real.log 3) ≤ f n := by + induction n with + | zero => simp + | succ n ih => + have h : Real.log ((n : ℝ) + 4) - Real.log (n + 3) ≤ 1 / ((n : ℝ) + 3) := by + rw [← Real.log_div (by positivity) (by positivity)] + refine (Real.log_le_sub_one_of_pos (by positivity)).trans_eq ?_ + field_simp + ring + have hh := mul_le_mul_of_nonneg_left h hv + rw [mul_one_div] at hh + rw [Nat.cast_succ, show (n : ℝ) + 1 + 3 = n + 4 by ring] + linarith [hl n] + by_contra! hlt + have ht : Tendsto (fun n : ℕ => Real.log ((n : ℝ) + 3)) atTop atTop := + Real.tendsto_log_atTop.comp (tendsto_natCast_atTop_atTop.atTop_add tendsto_const_nhds) + obtain ⟨n, hn⟩ := (ht.eventually_gt_atTop ((C - f 0 + v * Real.log 3) / (v - w))).exists + have := (div_lt_iff₀ (sub_pos.mpr hlt)).mp hn + linarith [hb n, hu n] + +/-- The condition `∀ i j, P i j ≤ Real.log ((i : ℝ) + j + 1)` on the specified data. -/ +def LogBound (P : ℕ → ℕ → ℝ) : Prop := + ∀ i j, P i j ≤ Real.log ((i : ℝ) + j + 1) + +theorem weighted_growth (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) + (p : Increments P Q x) (q : Increments (Function.swap P) R y) + (r : Increments (Function.swap Q) (Function.swap R) z) + (hP : LogBound P) (hQ : LogBound Q) (hR : LogBound R) + {A B C : ℕ} (hA : 0 < A) (hB : 0 < B) (hC : 0 < C) : + 4 * (x * B * C + y * A * C + z * A * B) ≤ ((A : ℝ) + B + C) ^ 2 := by + let S := (A : ℝ) + B + C + have hS : 0 < S := by unfold S; positivity + let v := 4 * (x * B * C + y * A * C + z * A * B) / S + let f (n : ℕ) := P (n * A) (n * B) * C + Q (n * A) (n * C) * B + R (n * B) (n * C) * A + have hl (n : ℕ) : v / ((n : ℝ) + 3) ≤ f (n + 1) - f n := by + have h (D : ℕ) : n * D ≤ (n + 1) * D := Nat.mul_le_mul_right D (Nat.le_succ n) + have h₁ := p.step hx hA hB hC (h A) + have h₂ := p.step hx hA hB hC (n := n) le_rfl + have h₃ := q.step hy hB hA hC (h B) + have h₄ := q.step hy hB hA hC (n := n) le_rfl + have h₅ := r.step hz hC hA hB (h C) + have h₆ := r.step hz hC hA hB (n := n) le_rfl + rw [show (B : ℝ) + A + C = S by unfold S; ring] at h₃ h₄ + rw [show (C : ℝ) + A + B = S by unfold S; ring] at h₅ h₆ + dsimp only [Function.swap, f, v, S] at * + rw [div_div, mul_comm ((A : ℝ) + B + C)] + simp only [div_eq_mul_inv] at h₁ h₂ h₃ h₄ h₅ h₆ ⊢ + linarith only [h₁, h₂, h₃, h₄, h₅, h₆] + have hu (n : ℕ) : f n ≤ S * Real.log ((n : ℝ) + 3) + S * Real.log S := by + have hu' {P : ℕ → ℕ → ℝ} (h : LogBound P) {i j : ℕ} (hij : (i : ℝ) + j ≤ S) : + P (n * i) (n * j) ≤ Real.log ((n : ℝ) + 3) + Real.log S := by + rw [← Real.log_mul (by positivity) hS.ne'] + refine (h _ _).trans (Real.log_le_log (by positivity) ?_) + have h₁ : 1 ≤ (A : ℝ) := by exact_mod_cast hA + have h₂ := mul_le_mul_of_nonneg_left hij (Nat.cast_nonneg (α := ℝ) n) + push_cast + unfold S at * + linarith + let L := Real.log ((n : ℝ) + 3) + Real.log S + calc + _ ≤ L * C + L * B + L * A := by + unfold f + gcongr + · apply hu' hP; unfold S; linarith + · apply hu' hQ; unfold S; linarith + · apply hu' hR; unfold S; linarith + _ = _ := by unfold L S; ring + have he : v ≤ S := growth (by unfold v; positivity) hl hu + exact (pow_two S).symm ▸ (div_le_iff₀ hS).mp he + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Weights.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Weights.lean new file mode 100644 index 0000000000..469c96de96 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rectangle/Weights.lean @@ -0,0 +1,45 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Model + +/-! # Weighted products and the size of their support -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle +variable {F : Type*} {i j k : ℕ} + +/-- The weighted rank le of type `Prop` for the given inputs. -/ +def WeightedRankLE [CommSemiring F] (w : Fin i → Fin j → Fin k → F) (r : ℕ) : Prop := + ∃ (a : Fin r → Pos i k → F) (b : Fin r → Pos k j → F) (c : Fin r → Pos i j → F), + ∀ x y z, ∑ l : Fin r, a l x * b l y * c l z = + if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then w x.1 y.2 x.2 else 0 + +theorem WeightedRankLE.map {K : Type*} [CommSemiring F] [CommSemiring K] + {w : Fin i → Fin j → Fin k → F} {r : ℕ} (h : WeightedRankLE w r) (φ : F →+* K) : + WeightedRankLE (fun x y z => φ (w x y z)) r := by + obtain ⟨a, b, c, h⟩ := h + refine ⟨fun l x => φ (a l x), fun l y => φ (b l y), fun l z => φ (c l z), ?_⟩ + intro x y z + simpa only [map_sum, map_mul, apply_ite φ, map_zero] using congrArg φ (h x y z) + +open Classical in +/-- The value specified by `∑ c, ∑ a, ∑ b, if w a c b = 0 then 0 else 1`. -/ +noncomputable def supportSize [Zero F] (w : Fin i → Fin j → Fin k → F) : ℕ := + ∑ c, ∑ a, ∑ b, if w a c b = 0 then 0 else 1 + +/-- Density times the ordinary asymptotic rank bounds the cost of +any exact decomposition, including a sparsely supported one. -/ +def DensityBound (F : Type*) [Field F] : Prop := + ∀ i j k r : ℕ, 0 < i → 0 < j → 0 < k → ∀ w : Fin i → Fin j → Fin k → F, + WeightedRankLE w r → + supportSize w * Real.exp (exponent F (Real.log i) (Real.log j) (Real.log k)) ≤ + (i : ℝ) * j * k * r + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Bins.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Bins.lean new file mode 100644 index 0000000000..c9e3932dc0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Bins.lean @@ -0,0 +1,641 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Data.Nat.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path + +/-! +# Transposing a stack of parallel ports + +At each layer one bit of the copy address is exchanged with the +corresponding bit of the port address. The remaining bits record the +order inside the bundle. This gives bounded degree without requiring +adjacent original stations to have comparable arities. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing + +variable {V : Type} {t : ℕ} (d : V → ℕ) + +open Classical in +/-- Indexes the node by the coordinates of `(Σ v, Cell (d v)) × Fin (t + 1)`. -/ +abbrev Node := (Σ v, Cell (d v)) × Fin (t + 1) + +namespace Node + +variable {d} (hd : ∀ v, d v ≤ t) + +open Classical in +/-- Evaluates `if i.val < k then p i else x (i.castLE (hd v))` at the input `i`. -/ +def address (k : ℕ) (v : V) (x : Cell t) (p : Cell (d v)) : Cell (d v) := + fun i => if i.val < k then p i else x (i.castLE (hd v)) + +open Classical in +/-- Evaluates `if h : k ≤ i.val ∧ i.val < d v then p ⟨i.val, h.2⟩ else x i` at the input `i`. -/ +def residue (k : ℕ) (v : V) (x : Cell t) (p : Cell (d v)) : Cell t := + fun i => if h : k ≤ i.val ∧ i.val < d v then p ⟨i.val, h.2⟩ else x i + +open Classical in +theorem inject (k : ℕ) (v : V) {x y : Cell t} {p q : Cell (d v)} + (h₁ : address hd k v x p = address hd k v y q) + (h₂ : residue k v x p = residue k v y q) : x = y ∧ p = q := by + constructor + · funext i + by_cases h : k ≤ i.val ∧ i.val < d v + · simpa only [address, ite_eq_right h.1.not_gt, Fin.castLE_mk, Fin.eta] using + congrFun h₁ (⟨i, h.2⟩ : Fin (d v)) + · simpa [residue, h] using congrFun h₂ i + · funext i + by_cases h : i.val < k + · simpa [address, h] using congrFun h₁ i + · simpa [residue, not_lt.mp h] using congrFun h₂ (i.castLE (hd v)) + +open Classical in +/-- The value specified by `(⟨p.1, address hd k.val p.1 x p.2⟩, k)`. -/ +def atLayer (k : Fin (t + 1)) (x : Cell t) (p : Σ v, Cell (d v)) : Node (t := t) d := + (⟨p.1, address hd k.val p.1 x p.2⟩, k) + +open Classical in +/-- The value specified by `(⟨v, ancestor (hd v) x⟩, 0)`. -/ +def start (v : V) (x : Cell t) : Node (t := t) d := (⟨v, ancestor (hd v) x⟩, 0) + +open Classical in +@[simp] theorem layer_zero (x : Cell t) (p : Σ v, Cell (d v)) : + atLayer hd 0 x p = start hd p.1 x := rfl + +open Classical in +@[simp] theorem layer_last (x : Cell t) (p : Σ v, Cell (d v)) : + atLayer hd (Fin.last t) x p = (p, Fin.last t) := by + have he : address hd t p.1 x p.2 = p.2 := by + funext i; exact ite_eq_left (i.isLt.trans_le (hd _)) + simp only [atLayer, Fin.val_last, he, Sigma.eta] + +open Classical in +/-- At most one endpoint uses a given position and residual bit address. -/ +theorem layer_inj {i j : Fin (t + 1)} {x y : Cell t} {p q : Σ v, Cell (d v)} + (hp : atLayer hd i x p = atLayer hd j y q) + (hr : residue i.val p.1 x p.2 = residue j.val q.1 y q.2) : + i = j ∧ x = y ∧ p = q := by + have hij : i = j := congrArg Prod.snd hp + subst j + rcases p with ⟨u, p⟩; rcases q with ⟨v, q⟩ + have huv : u = v := congrArg (fun z => z.1.1) hp + subst v + have h : address hd i u x p = address hd i u y q := by + simpa [atLayer] using congrArg Prod.fst hp + obtain ⟨rfl, rfl⟩ := inject hd i u h hr + exact ⟨rfl, rfl, rfl⟩ + +-- Neighbours on adjacent layers can differ at only one coordinate. +open Classical in +/-- The value specified by `(⟨p.1.1, fun i => if i.val = min p.2.val j.val then b else p.1.2 i⟩, +j)`. -/ +def next (p : Node (t := t) d) (j : Fin (t + 1)) (b : ZMod 2) : Node (t := t) d := + (⟨p.1.1, fun i => if i.val = min p.2.val j.val then b else p.1.2 i⟩, j) + +open Classical in +/-- The links of type `Finset (Node (t := t) d)` for the given inputs. -/ +def links (p : Node (t := t) d) : Finset (Node (t := t) d) := + (Finset.univ.image (next p ⟨p.2.val - 1, by have := p.2.isLt; omega⟩)) ∪ + (Finset.univ.image (next p ⟨min t (p.2.val + 1), by omega⟩)) + +open Classical in +theorem links_card (p : Node (t := t) d) : (links p).card ≤ 4 := by + unfold links + refine (Finset.card_union_le _ _).trans ?_ + have h (j) : (Finset.univ.image (next p j)).card ≤ 2 := + Finset.card_image_le.trans (by simp) + exact Nat.add_le_add (h _) (h _) + +open Classical in +theorem layer_link (i j : Fin (t + 1)) (hc : i.val + 1 = j.val ∨ j.val + 1 = i.val) + (x : Cell t) (p : Σ v, Cell (d v)) : atLayer hd j x p ∈ links (atLayer hd i x p) := by + let v := p.1 + let k := min i.val j.val + let b := if h : k < d v then address hd j.val v x p.2 ⟨k, h⟩ else 0 + have hm : next (atLayer hd i x p) j b = atLayer hd j x p := by + unfold next atLayer + congr 2 + funext e + change (if e.val = k then b else address hd i.val v x p.2 e) = address hd j.val v x p.2 e + by_cases he : e.val = k + · have hv : e.val < d v := e.isLt + simp [he.symm, b, hv] + · have : (e.val < i.val) = (e.val < j.val) := propext (by unfold k at he; omega) + simp only [ite_eq_right he, address, this] + unfold links + apply Finset.mem_union.mpr + rcases hc with h|h + · right + have h' : min t ((atLayer hd i x p).2.val + 1) = j.val := by + change min t (i.val + 1) = _; have := j.isLt; omega + simp only [h', Fin.eta] + exact Finset.mem_image.mpr ⟨b, Finset.mem_univ _, hm⟩ + · left + have h' : (atLayer hd i x p).2.val - 1 = j.val := by change i.val - 1 = _; omega + simp only [h', Fin.eta] + exact Finset.mem_image.mpr ⟨b, Finset.mem_univ _, hm⟩ + +end Node +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# Packing stations without losing the square budget + +At each cell place the next station in any slot of load at most +the final average bound. This avoids a separate case for large stations. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +open scoped Classical in +theorem bins {A B : Type} [Fintype A] [Fintype B] (f : A → B) (l : A → ℝ) + (D : ℕ) (T : ℝ) (hD : 0 < D) (hl : ∀ x, 0 ≤ l x) (hb : ∀ b, push f l b ≤ D * T) : + ∃ s : A → Fin D, (∑ z, (push (fun x => (f x, s x)) l z) ^ 2) ≤ + (∑ x, l x ^ 2) + 2 * T * (∑ x, l x) := by + have : Nonempty (Fin D) := ⟨⟨0, hD⟩⟩ + let mass (S : Finset A) (s : A → Fin D) (z : B × Fin D) := + ∑ x ∈ S, if (f x, s x) = z then l x else 0 + have cap S s b : (∑ i, mass S s (b, i)) ≤ D * T := by + unfold mass + rw [sum_comm] + simp only [Prod.mk.injEq, ite_and, sum_ite_irrel, sum_ite_eq, mem_univ, ite_true, + sum_const_zero] + refine le_trans ?_ (hb b) + exact sum_le_sum_of_subset_of_nonneg (subset_univ _) fun x _ _ => by + split_ifs <;> first | exact hl x | exact le_rfl + have aux (S : Finset A) : ∃ s, (∑ z, (mass S s z) ^ 2) ≤ + (∑ x ∈ S, l x ^ 2) + 2 * T * (∑ x ∈ S, l x) := by + induction S using Finset.induction with + | empty => exact ⟨fun _ => ⟨0, hD⟩, by simp [mass]⟩ + | @insert x S hx ih => + obtain ⟨s, hs⟩ := ih + have he : (∑ i, mass S s (f x, i)) ≤ ∑ _i : Fin D, T := by simpa using cap S s (f x) + obtain ⟨i, _, hi⟩ := exists_le_of_sum_le univ_nonempty he + let s' := Function.update s x i + have eq z : mass (insert x S) s' z = (if (f x, i) = z then l x else 0) + mass S s z := by + unfold mass + rw [sum_insert hx, show s' x = i by simp [s']] + congr 1 + apply sum_congr rfl + intro y hy + rw [show s' y = s y from Function.update_of_ne (show y ≠ x from fun e => hx (e ▸ hy)) _ _] + have sq z : (mass (insert x S) s' z) ^ 2 ≤ + (if (f x, i) = z then l x ^ 2 + 2 * T * l x else 0) + (mass S s z) ^ 2 := by + rw [eq] + split_ifs with h + · subst z + nlinarith only [mul_le_mul_of_nonneg_right hi (hl x)] + · simp + refine ⟨s', ?_⟩ + have := sum_le_sum (s := univ) (fun z _ => sq z) + simp only [sum_add_distrib, sum_ite_eq, mem_univ, ite_true] at this + rw [sum_insert hx, sum_insert hx] + linarith + obtain ⟨s, hs⟩ := aux univ + refine ⟨s, ?_⟩ + have he z : push (fun x => (f x, s x)) l z = mass univ s z := by + apply sum_congr rfl + intro x _ + split_ifs <;> rfl + simpa only [he] using hs + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# A bounded-degree host for an initial stack + +The links along one station form a butterfly. On its last layer, +distinct original port addresses can each be joined to at most one +other address. This works also for parallel edges and loops. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +open Packing + +variable {F : Type} {a b : Wire} (G : Diagram F a b) {h t : ℕ} + +open Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def dim (v : G.V) := Nat.clog 2 (G.arity v) + +open Classical in +/-- The value specified by `Node (t := t) (dim G)`. -/ +abbrev Site (t : ℕ) := Node (t := t) (dim G) + +open Classical in +theorem card (t : ℕ) : Fintype.card (Site G t) ≤ 2 * G.cost * (t + 1) := by + rw [Fintype.card_prod, Fintype.card_sigma, Fintype.card_fin, Diagram.cost, Finset.mul_sum] + refine Nat.mul_le_mul_right _ (Finset.sum_le_sum (fun v _ => ?_)) + rw [card_cell, dim] + by_cases h : G.arity v = 0 + · simp [h] + · exact (Transcript.pow_clog_le_twice (Nat.pos_of_ne_zero h)).trans (by omega) + +open Classical in +/-- Embeds `G.Port v` into `Cell (dim G v)`. -/ +def address (v : G.V) : G.Port v ↪ Cell (dim G v) := + Classical.choice (Function.Embedding.nonempty_of_card_le (by + rw [Fintype.card_sum, card_slots, card_slots, card_cell] + exact Nat.le_pow_clog (by decide) _)) + +open Classical in +/-- Embeds `G.End` into `Σ v, Cell (dim G v)`. -/ +def port : G.End ↪ Σ v, Cell (dim G v) := + G.portEquiv.symm.toEmbedding.trans + ⟨fun z => ⟨z.1, address G z.1 z.2⟩, by + rintro ⟨v, p⟩ ⟨w, q⟩ he + have hv : v = w := congrArg Sigma.fst he + subst w + have hp := (address G v).injective (eq_of_heq (Sigma.mk.inj_iff.mp he).2) + exact congrArg (Sigma.mk v) hp⟩ + +open Classical in +theorem station (e : G.End) : (port G e).1 = G.station e := by + have := (G.station_port (G.portEquiv.symm e)).symm + rwa [Equiv.apply_symm_apply] at this + +open Classical in +/-- In the case `.inl (.inr e)`, this construction gives `.inr (.inr e)`. -/ +def other : G.End → G.End + | .inl (.inr e) => .inr (.inr e) + | .inr (.inr e) => .inl (.inr e) + | x => x + +open Classical in +/-- Returns `(port G (other G h.choose), z.2)` when `h : ∃ e, port G e = z.1` holds, and `z` +otherwise. -/ +def peer (z : Site G t) : Site G t := + if h : ∃ e, port G e = z.1 then (port G (other G h.choose), z.2) else z + +open Classical in +theorem peer_port (e : G.End) (i : Fin (t + 1)) : + peer G (port G e, i) = (port G (other G e), i) := by + have h : ∃ z, port G z = port G e := ⟨e, rfl⟩ + simp only [peer, dite_eq_left h, (port G).injective h.choose_spec] + +-- Require mutual inclusion so the host is symmetric by construction. +open Classical in +/-- Selects the elements of `(insert (peer G z) (Node.links z))` satisfying `fun w => z ∈ insert +(peer G w) (Node.links w)`. -/ +def adjacent (z : Site G t) := + (insert (peer G z) (Node.links z)).filter fun w => z ∈ insert (peer G w) (Node.links w) + +open Classical in +theorem adj_sym (v z : Site G t) (hv : z ∈ adjacent G v) : v ∈ adjacent G z := by + simpa only [adjacent, Finset.mem_filter, and_comm] using hv + +open Classical in +theorem adj_card (v : Site G t) : (adjacent G v).card ≤ 5 := + (Finset.card_filter_le _ _).trans ((Finset.card_insert_le _ _).trans + (Nat.add_le_add_right (Node.links_card v) 1)) + +variable (bound : ∀ v, dim G v ≤ t) + +open Classical in +/-- Computes the place by the application `Node.atLayer bound i x (port G e)`. -/ +def place (i : Fin (t + 1)) (x : Cell t) (e : G.End) : Site G t := + Node.atLayer bound i x (port G e) + +open Classical in +theorem line (i j : Fin (t + 1)) (h : i.val + 1 = j.val ∨ j.val + 1 + = i.val) (x : Cell t) (e : G.End) : + place G bound j x e ∈ adjacent G (place G bound i x e) := + Finset.mem_filter.mpr + ⟨Finset.mem_insert_of_mem (Node.layer_link bound i j h x _), + Finset.mem_insert_of_mem (Node.layer_link bound j i h.symm x _)⟩ + +open Classical in +/-- Returns `.inl (.inr e)` when `k ≤ t` holds, and `.inr (.inr e)` otherwise. -/ +def endpoint {t : ℕ} (e : G.E) (k : ℕ) : G.End := + if k ≤ t then .inl (.inr e) else .inr (.inr e) + +open Classical in +/-- The quantity computed by `⟨min k (2 * t + 1 - k), by omega⟩`. -/ +def level (t k : ℕ) : Fin (t + 1) := ⟨min k (2 * t + 1 - k), by omega⟩ + +open Classical in +/-- The value specified by `place G bound (level t k) x (endpoint (t := t) G e k)`. -/ +def walk (k : ℕ) (x : Cell t) (e : G.E) : Site G t := + place G bound (level t k) x (endpoint (t := t) G e k) + +open Classical in +theorem walk_start (x : Cell t) (e : G.E) : + walk G bound 0 x e = Node.start bound (G.source e) x := by + rw [walk, place, show level t 0 = 0 by ext; simp [level], Node.layer_zero, station] + simp [endpoint, Diagram.station, Diagram.source] + +open Classical in +theorem walk_end (x : Cell t) (e : G.E) : + walk G bound (2 * t + 1) x e = Node.start bound (G.target e) x := by + rw [walk, place, show level t (2 * t + 1) = 0 by ext; simp [level], Node.layer_zero, station] + simp [endpoint, Diagram.station, Diagram.target, show ¬ 2 * t + 1 ≤ t by omega] + +open Classical in +theorem walk_adj (x : Cell t) (e : G.E) (k : ℕ) (hk : k < 2 * t + 1) : + walk G bound (k + 1) x e ∈ adjacent G (walk G bound k x e) := by + rcases lt_trichotomy k t with h | he | h + · unfold walk endpoint + rw [ite_eq_left (show k + 1 ≤ t by omega), ite_eq_left h.le] + exact line G bound _ _ (by left; dsimp [level]; omega) _ _ + · subst k + have h₁ : level t t = Fin.last t := Fin.ext (by simp [level]; omega) + have h₂ : level t (t + 1) = Fin.last t := Fin.ext (by simp [level]; omega) + simp only [walk, h₁, h₂, endpoint, ite_eq_left le_rfl, ite_eq_right (show ¬t + 1 ≤ t by omega), + place, Node.layer_last, adjacent, Finset.mem_filter, Finset.mem_insert, peer_port, other] + simp + · unfold walk endpoint + rw [ite_eq_right (show ¬ k + 1 ≤ t by omega), ite_eq_right h.not_ge] + exact line G bound _ _ (by right; dsimp [level]; omega) _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end + +/- # Bounding port occupancy in a stack -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +open Packing + +variable {F : Type} {a b : Wire} (G : Diagram F a b) {t h : ℕ} (bound : ∀ v, dim G v ≤ t) + +open Classical in +/-- Indexes the index by the coordinates of `Cell t × Cell h`. -/ +abbrev Index (t h : ℕ) := Cell t × Cell h +open Classical in +/-- Indexes the task by the coordinates of `Fin (t + 1) × Index t h × G.End`. -/ +abbrev Task := Fin (t + 1) × Index t h × G.End + +open Classical in +/-- Indexes the at task by the coordinates of `t) (h := h)) : Site G t × Cell h := (place G +bound e.1 e.2.1.1 e.2.2, e.2.1.2)`. -/ +def atTask (e : Task G (t := t) (h := h)) : Site G t × Cell h := + (place G bound e.1 e.2.1.1 e.2.2, e.2.1.2) + +open Classical in +private def rest (e : Task G (t := t) (h := h)) : Cell t := + Node.residue e.1.val (port G e.2.2).1 e.2.1.1 (port G e.2.2).2 + +open Classical in +private theorem unique_task {e f : Task G (t := t) (h := h)} + (he : atTask G bound e = atTask G bound f) (hr : rest G e = rest G f) : e = f := by + obtain ⟨h₁, h₂, h₃⟩ := Node.layer_inj bound (congrArg Prod.fst he) hr + have h₄ := congrArg Prod.snd he + exact Prod.ext h₁ (Prod.ext (Prod.ext h₂ h₄) ((port G).injective h₃)) + +open Classical in +theorem capacity {X : Type} [Fintype X] (f : X ↪ Task G (t := t) (h := h)) + (k : X → Site G t × Cell h) (eqn : ∀ x, atTask G bound (f x) = k x) + (y : Site G t × Cell h) : Fintype.card {x // k x = y} ≤ 2 ^ t := by + rw [← card_cell t] + apply Fintype.card_le_of_injective (fun x : {x // k x = y} => rest G (f x)) + intro x z hr + exact Subtype.ext (f.injective (unique_task G bound + (by rw [eqn, eqn, x.property, z.property]) hr)) + +open Classical in +/-- Indexes the channel by the coordinates of `Fin (2 * t + 1) × Index t h × G.E`. -/ +abbrev Channel := Fin (2 * t + 1) × Index t h × G.E + +open Classical in +/-- The value specified by `(walk G bound j e.1.1 e.2, e.1.2)`. -/ +def route (j : ℕ) (e : Index t h × G.E) : Site G t × Cell h := + (walk G bound j e.1.1 e.2, e.1.2) + +open Classical in +private def task (s : ℕ) (e : Channel G (t := t) (h := h)) : Task G (t := t) (h := h) := + (level t (e.1.val + s), e.2.1, endpoint (t := t) G e.2.2 (e.1.val + s)) + +open Classical in +private theorem task_inj (s : ℕ) (hs : s ≤ 1) : + Function.Injective (task (t := t) (h := h) G s) := by + rintro ⟨i, x, e⟩ ⟨j, y, f⟩ he + have h₁ : min (i.val + s) (2 * t + 1 - (i.val + s)) = min (j.val + s) (2 * t + 1 - (j.val + s)) := + congrArg (fun z => z.1.val) he + have h₂ : x = y := congrArg (fun z => z.2.1) he + have h₃ : endpoint (t := t) G e (i.val + s) = endpoint (t := t) G f (j.val + s) := + congrArg (fun z => z.2.2) he + by_cases hi : i.val + s ≤ t <;> by_cases hj : j.val + s ≤ t + all_goals simp [endpoint, hi, hj] at h₃ + all_goals have : i = j := Fin.ext (by have := i.isLt; have := j.isLt; omega) + all_goals simp only [this, h₂, h₃] + +open Classical in +theorem edge_capacity (s : ℕ) (hs : s ≤ 1) (y : Site G t × Cell h) : + Fintype.card {e : Channel G (t := t) (h := h) // route G bound (e.1.val + s) e.2 = y} ≤ 2 ^ t := + capacity G bound ⟨_, task_inj G s hs⟩ _ (fun _ => rfl) y + +open Classical in +/-- The value specified by `(Node.start bound p.2 p.1.1, p.1.2)`. -/ +def owner (p : Index t h × G.V) : Site G t × Cell h := + (Node.start bound p.2 p.1.1, p.1.2) + +open Classical in +theorem exterior_capacity {n : ℕ} (c : Index t h ≃ Fin n) (y : Site G t × Cell h) : + Fintype.card {i : slots (copies a n) // owner G bound ((G.replicate c).src.symm (.inl i)).1 = y} + ≤ 2 ^ t ∧ + Fintype.card {i : slots (copies b n) // owner G bound ((G.replicate c).dst.symm (.inl i)).1 = y} + ≤ 2 ^ t := by + have aux (w : Wire) (f : slots w ↪ G.End) : + Fintype.card {i : slots (copies w n) // + owner G bound (c.symm (Diagonal.port w n i).1, G.station (f (Diagonal.port w n i).2)) = y} + ≤ 2 ^ t := by + let e : slots (copies w n) ↪ Task G (t := t) (h := h) := + ((Diagonal.port w n).toEmbedding.trans (c.symm.toEmbedding.prodMap f)).trans + ⟨fun p => (0, p), fun _ _ h => congrArg Prod.snd h⟩ + refine capacity G bound e _ ?_ y + intro i + change (Node.atLayer bound 0 _ _, _) = _ + rw [Node.layer_zero, station] + rfl + exact ⟨aux a (Function.Embedding.inl.trans Function.Embedding.inl), + aux b (Function.Embedding.inl.trans Function.Embedding.inr)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end + +section +/- +# The invariants at the boundary of each round + +There is at most one station per occurrence. Empty hardware can carry +a scalar with zero charge. Positive charge covers the arity and has +a lower bound proportional to the current width. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +/-- The data for the board construction, including `V`, `[fv`, `diagram`, `place`, `one`. -/ +structure Board (F : Type) (x y : Wire) (h : ℕ) where + /-- The type of vertices. -/ + V : Type + [fv : Fintype V] + /-- The `Board` component of type `Diagram F x y`. -/ + diagram : Diagram F x y + /-- The `Board` component of type `diagram.V → V × Cell h`. -/ + place : diagram.V → V × Cell h + one : Function.Injective place + /-- The neighbors of each vertex of type `V → Finset V`. -/ + adj : V → Finset V + sym : ∀ v z, z ∈ adj v → v ∈ adj z + edge : ∀ e, let q := place (diagram.source e) + let p := place (diagram.target e) + p.2 = q.2 ∧ p.1 ∈ adj q.1 + /-- The `Board` component of type `diagram.V → ℝ`. -/ + charge : diagram.V → ℝ + cover : ∀ v, diagram.arity v ≤ charge v + +attribute [instance] Board.fv + +namespace Board + +variable {F : Type} {x y : Wire} {h : ℕ} (P : Board F x y h) + +/-- Counts the elements of `P.V * 2 ^ h`. -/ +def seats := Fintype.card P.V * 2 ^ h + +/-- The ready of type `Prop` for the given inputs. -/ +def Ready (g D T : ℕ) (L θ : ℝ) : Prop := + (∀ v, (P.adj v).card ≤ g) ∧ + (∑ v, P.charge v) ≤ L ∧ (∑ v, P.charge v ^ 2) ≤ L * T ∧ + ∀ v, P.charge v ≤ (D : ℝ) * T / 2 ∧ (P.charge v = 0 ∨ θ * T ≤ P.charge v) + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# The initial bounded-degree stack + +Each original wire is replaced by a path between the appropriate +addresses. Contracting its vertices layer by layer gives an exact +power, with all external bits of every copy exposed. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +open Packing + +variable {F : Type} [Field F] {a b : Wire} (G : Diagram F a b) {t h n : ℕ} + (bound : ∀ v, dim G v ≤ t) (c : Index t h ≃ Fin n) + +open Classical in +/-- The quantity computed by `Spectral.Packet.Rule.path F (route (h := h) G bound) (2 * t + 1)`. -/ +abbrev paths := Spectral.Packet.Rule.path F (route (h := h) G bound) (2 * t + 1) + +omit [Field F] in +open Classical in +private theorem aligned : + (G.replicate c).Aligned (fun _ : Unit => owner G bound) (fun _ => id) + (fun e => (route G bound 0 e, route G bound (2 * t + 1) e)) := by + rintro _ ⟨⟨x, y⟩, e⟩ + simp only [Diagram.source_replicate, Diagram.target_replicate, owner, route, id_eq, + walk_start, walk_end, and_self] + +open Classical in +/-- The indexed operation `(G.replicate c).replaced (paths G bound) (fun _ => owner G bound) +(fun _ => id) ()`. -/ +abbrev diagram := (G.replicate c).replaced (paths G bound) (fun _ => owner G bound) (fun _ => id) () + +open Classical in +theorem eval : (diagram G bound c).eval = power G.eval n := by + funext x y + have he := (G.replicate c).eval_replaced (paths G bound) + (fun _ => owner G bound) (fun _ => id) x y + rw [Fintype.sum_unique, Diagram.eval_replicate] at he + exact he + +open Classical in +theorem linked (e : (diagram G bound c).E) : + let p := (diagram G bound c).source e + let q := (diagram G bound c).target e + q.2 = p.2 ∧ q.1 ∈ adjacent G p.1 := by + obtain ⟨⟨⟨k, x, w⟩, he⟩, rfl⟩ := ((G.replicate c).cutEdges (paths G bound) _ _ (aligned G bound + c) ()).surjective e + exact ⟨rfl, walk_adj G bound x.1 w _ k.isLt⟩ + +open Classical in +theorem arity (v : Site G t × Cell h) : + (diagram G bound c).arity v ≤ 4 * 2 ^ t := by + have hw := (G.replicate c).arity_replaced (paths G bound) _ _ (aligned G bound c) () v + obtain ⟨hin, hout⟩ := exterior_capacity G bound c v + have hs := edge_capacity G bound 0 (by decide) v + have ht := edge_capacity G bound 1 le_rfl v + have hy := Nat.add_le_add (Nat.add_le_add hin hout) (Nat.add_le_add hs ht) + simp only [← Nat.card_eq_fintype_card, id_eq, add_zero] at hw hy + refine hw.trans ?_ + refine hy.trans ?_ + omega + +open Classical in +/-- Builds `Board F (copies a n) (copies b n) h where V` with the specified `diagram`, `place`, +`one`, `adj`. -/ +def board : Board F (copies a n) (copies b n) h where + V := Site G t + diagram := diagram G bound c + place := id + one := Function.injective_id + adj := adjacent G + sym := adj_sym G + edge := linked G bound c + charge _ := 4 * (2 : ℝ) ^ t + cover := by + intro v + exact_mod_cast arity G bound c v + +open Classical in +theorem ready {D : ℕ} {θ : ℝ} (hD : 8 ≤ D) (hθ : θ ≤ (4 : ℝ)) : + (board G bound c).Ready 5 D (2 ^ t) (16 * (2 : ℝ) ^ t * (Fintype.card (Site G t) * 2 ^ h : ℕ)) + θ := by + have hv : Fintype.card (diagram G bound c).V = Fintype.card (Site G t) * 2 ^ h := by + change Fintype.card (Site G t × Cell h) = _ + rw [Fintype.card_prod, card_cell] + have hD' : 8 ≤ (D : ℝ) := by exact_mod_cast hD + refine ⟨adj_card G, ?_, ?_, ?_⟩ + · change (∑ _ : (diagram G bound c).V, 4 * (2 : ℝ) ^ t) ≤ _ + rw [Finset.sum_const, Finset.card_univ, hv, nsmul_eq_mul, mul_comm] + gcongr; norm_num + · change (∑ _ : (diagram G bound c).V, (4 * (2 : ℝ) ^ t) ^ 2) ≤ _ + rw [Finset.sum_const, Finset.card_univ, hv, nsmul_eq_mul, Nat.cast_pow, Nat.cast_ofNat] + exact le_of_eq (by ring) + · intro v + change 4 * (2 : ℝ) ^ t ≤ _ ∧ (_ ∨ θ * _ ≤ 4 * (2 : ℝ) ^ t) + simp only [Nat.cast_pow, Nat.cast_ofNat] + exact ⟨by rw [le_div_iff₀ (by norm_num)]; nlinarith [pow_pos (by norm_num : (0 : ℝ) < 2) t], + Or.inr (mul_le_mul_of_nonneg_right hθ (by positivity))⟩ + +open Classical in +/-- The host cost per station is linear in its arity times the stack +address length. Its degree is bounded independently of that length. -/ +theorem initial (G : Diagram F a b) (t h D : ℕ) (θ : ℝ) + (hu : ∀ v, G.arity v ≤ 2 ^ t) (hD : 8 ≤ D) (hθ : θ ≤ 4) : + ∃ P : Board F (copies a (2 ^ t * 2 ^ h)) (copies b (2 ^ t * 2 ^ h)) h, + P.diagram.eval = power G.eval (2 ^ t * 2 ^ h) ∧ + Fintype.card P.V ≤ 2 * G.cost * (t + 1) ∧ + P.Ready 5 D (2 ^ t) (16 * (2 : ℝ) ^ t * P.seats) θ := by + have bound (v) : dim G v ≤ t := (Nat.clog_le_iff_le_pow (by decide)).mpr (hu v) + let c : Index t h ≃ Fin (2 ^ t * 2 ^ h) := Fintype.equivOfCardEq (by simp [Index, Cell]) + exact ⟨board G bound c, eval G bound c, card G t, ready G bound c hD hθ⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Construct.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Construct.lean new file mode 100644 index 0000000000..1d3645132e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Construct.lean @@ -0,0 +1,385 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Passage +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Plan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Beat.Fanout +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Majorants +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Dual + +/-! +# Exposed ports and the scalar case + +A nonempty exterior supplies a host at every stage. A tensor with +no exterior bits is a scalar and has a constant-size installation. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Coloring + +variable {F : Type} {x y : Wire} + +theorem Diagram.nonempty_of_exterior (G : Diagram F x y) (h : 0 < wd x + wd y) : + Nonempty G.V := by + by_cases hx : 0 < wd x + · obtain ⟨p⟩ := Fintype.card_pos_iff.mp (by rw [card_slots]; exact hx) + exact ⟨(G.src.symm (.inl p)).1⟩ + · have hy : 0 < wd y := by omega + obtain ⟨p⟩ := Fintype.card_pos_iff.mp (by rw [card_slots]; exact hy) + exact ⟨(G.dst.symm (.inl p)).1⟩ + +theorem Rounds.Board.nonempty_of_exterior {h : ℕ} (P : Rounds.Board F x y h) + (he : 0 < wd x + wd y) : Nonempty P.V := by + obtain ⟨v⟩ := P.diagram.nonempty_of_exterior he + exact ⟨(P.place v).1⟩ + +theorem Rounds.LocalTerm.nonempty_of_exterior {h u : ℕ} (Q : Rounds.LocalTerm F x y h u) + (he : 0 < wd x + wd y) : Nonempty Q.V := by + obtain ⟨v⟩ := Q.diagram.nonempty_of_exterior he + exact ⟨(Q.frame.place v).1⟩ + +namespace Rounds + +private theorem zero_width_subsingleton {w : Wire} (h : wd w = 0) : Subsingleton (Val w) := by + let : IsEmpty (slots w) := Fintype.card_eq_zero_iff.mp (by rw [card_slots, h]) + exact ⟨fun a b => (bits w).injective (funext fun p => isEmptyElim p)⟩ + +variable [Field F] + +private theorem empty_ports_kernel {A B : Format} (ha : A.width = 0) (hb : B.width = 0) : + Kernel F 3 ∅ A B (fun _ _ => 1) 1 := by + intro a b i j + have hi : Fintype.card (slots a) = 0 := (Fintype.card_congr i).symm.trans ha + have hj : Fintype.card (slots b) = 0 := (Fintype.card_congr j).symm.trans hb + let e : slots Wire.unit ≃ slots a := Fintype.equivOfCardEq (by simpa using hi.symm) + let f : slots b ≃ slots Wire.unit := Fintype.equivOfCardEq (by simpa using hj) + have hw : Wide F 3 ∅ .unit .unit (fun _ _ => 1) 1 := + .table _ _ _ (Nat.zero_le _) (.inl (by decide)) + exact ⟨1, le_rfl, (hw.pre (rewire_reindex e)).post (rewire_reindex f.symm)⟩ + +theorem scalar_installation {k : Val x → Val y → F} {d : ℕ} + (he : wd x + wd y = 0) : + ∃ I : Installation k d, I.u = 3 ∧ I.labels = ∅ ∧ I.cost = 3 := by + classical + let S : Snapshot.{1} F (copies x d) (copies y d) := + ⟨ULift.{1} Unit, fun _ _ _ => 1, .wire .unit, fun _ _ _ => ()⟩ + have hx : wd (copies x d) = 0 := by rw [wd_copies, show wd x = 0 by omega, mul_zero] + have hy : wd (copies y d) = 0 := by rw [wd_copies, show wd y = 0 by omega, mul_zero] + let : Subsingleton (Val (copies x d)) := zero_width_subsingleton hx + let : Subsingleton (Val (copies y d)) := zero_width_subsingleton hy + let a := (bits (copies x d)).symm (fun _ => false) + let b := (bits (copies y d)).symm (fun _ => false) + let z := power k d a b + have ex : (fun s t => z * S.eval (ULift.up ()) s t) = power k d := by + funext s t + rw [Subsingleton.elim s a, Subsingleton.elim t b] + exact mul_one _ + have hs : (.wire (.pair (copies x d) (copies y d)) : Format).width = 0 := by + change Fintype.card (slots (.pair (copies x d) (copies y d))) = 0 + rw [card_slots] + change wd (copies x d) + wd (copies y d) = 0 + omega + have hin : Map F 3 ∅ (.wire (.pair (copies x d) (copies y d))) S.port (fun _ => ()) 1 := by + unfold Map + have hk : Kernel F 3 ∅ (.wire (.pair (copies x d) (copies y d))) S.port + (fun _ _ => 1) 1 := empty_ports_kernel hs rfl + convert hk using 1 + funext _ p + exact ite_eq_left (@Subsingleton.elim (Val .unit) inferInstance () p) + have run : Transforms F 3 ∅ S S 0 := Transforms.refl le_rfl S + have stop : Finishes F 3 ∅ S 1 := ⟨fun _ => 1, empty_ports_kernel rfl rfl, fun _ _ _ => rfl⟩ + let I : Installation k d := + ⟨3, le_rfl, ∅, S, S, ULift.up (), z, ex, 1, 0, 1, by simpa [S] using hin, + by simpa using run, by simpa using stop⟩ + refine ⟨I, rfl, rfl, ?_⟩ + change 1 + (0 + 1) + 4 * (d * wd y) + 1 = 3 + rw [show wd y = 0 by omega] + simp + +theorem Levels.installed_scalar {δ : ℝ} {p : Design δ} {R n T₀ m c : ℕ} + {a b ξ : ℝ} {v : Levels p R} {k : Val x → Val y → F} + (ok : v.Suits n T₀ a b ξ) (ha : 0 < a) (hδ : 0 < δ) (hm : 0 < m) + (he : wd x + wd y = 0) : v.Installed n m c a k := by + let h : ℝ := Nat.clog 2 n + have h1 : 1 ≤ h := ok.2.1.le + have hτ : 1 ≤ h ^ (a * δ / 6) := Real.one_le_rpow h1 (by positivity) + have hwork : (3 : ℝ) ≤ v.work m (wd x + wd y) h a c := by + have hb : 1 ≤ m * (v.stack + 1) * 2 ^ v.blocks := by + exact Nat.succ_le_iff.mpr (by positivity) + have hA : 3 ≤ v.allocation m := calc + _ ≤ 32 := by decide + _ ≤ _ := by + unfold Levels.allocation + simpa only [Nat.mul_assoc, Nat.mul_one] using Nat.mul_le_mul_left 32 hb + have hB : 1 ≤ p.overhead ^ v.j := + Nat.one_le_iff_ne_zero.mpr (by have := p.overhead_large; positivity) + have hC : 3 ≤ p.overhead ^ v.j * v.allocation m := by + exact (by simpa using Nat.mul_le_mul hB hA : 1 * 3 ≤ p.overhead ^ v.j * v.allocation m) + have hD : 1 ≤ h ^ (c * a) := Real.one_le_rpow h1 (by positivity) + have hfin : 0 ≤ v.finalBudget m := by unfold Levels.finalBudget; positivity + have hext : (0 : ℝ) ≤ (v.batch * (wd x + wd y) : ℕ) := by positivity + unfold Levels.work + calc + _ ≤ ((p.overhead ^ v.j * v.allocation m : ℕ) : ℝ) := by exact_mod_cast hC + _ ≤ ((p.overhead ^ v.j * v.allocation m : ℕ) : ℝ) * h ^ (c * a) := + le_mul_of_one_le_right (by positivity) hD + _ ≤ _ := by linarith + have hD : (3 : ℝ) ≤ p.D := by have := p.large; exact_mod_cast (show 3 ≤ p.D by omega) + have hw : (1 : ℝ) ≤ v.finalWidth := by + have positive : 0 < v.finalWidth := by + unfold Levels.finalWidth + positivity + exact_mod_cast (Nat.succ_le_of_lt positive) + obtain ⟨I, hu, hl, hc⟩ := scalar_installation (k := k) (d := v.batch) he + refine ⟨I, by simp [hl], ?_, ?_⟩ + · simpa only [hc, Nat.cast_ofNat] using + hwork.trans (le_mul_of_one_le_left (by linarith : 0 ≤ v.work m (wd x + wd y) h a c) hτ) + · have h' : 3 ≤ (p.D : ℝ) * v.finalWidth := + hD.trans (le_mul_of_one_le_right (by positivity) hw) + simpa only [hu, Nat.cast_ofNat] using + h'.trans (le_mul_of_one_le_left (by positivity) hτ) + +end Rounds +end MatrixMultiplicationAllFields.MatrixExponent +end + +section +/- # Admitting arbitrary fixed powers of the logarithm as label lengths -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Filter + +/-- The quantity computed by `2 ^ ((Nat.clog 2 (Nat.clog 2 n)) ^ e)`. -/ +def inputDictionary (e n : ℕ) := 2 ^ ((Nat.clog 2 (Nat.clog 2 n)) ^ e) + +/-- All scale and field constants are fixed before the label exponent. -/ +def PolyInstallable (F : Type) [Field F] : Prop := + InstallableFor F inputDictionary + +theorem PolyInstallable.installable {F : Type} [Field F] (h : PolyInstallable F) : Installable F + := by + intro δ β hd hd' hb hb' + obtain ⟨p, A, T₀, c, L, _, _, _, go⟩ := h δ β hd hd' hb hb' + exact ⟨p, A, T₀, c, L, inferInstance, inferInstance, inferInstance, fun a b ξ ha ha' hb hb' hξ => + fun _ => go a b ξ ha ha' hb hb' hξ 2⟩ + +namespace Levels +variable {δ a : ℝ} + +theorem eventually_inputDictionary (p : Design δ) (M e : ℕ) (ha : 0 < a) : + ∀ᶠ n : ℕ in atTop, ∀ (v : Levels p M) (T₀ : ℕ) (b ξ : ℝ), b ≤ 1 → + v.Suits n T₀ a b ξ → inputDictionary e n ≤ 2 ^ (v.box 2) := by + obtain ⟨k, hk⟩ := exists_nat_ge (1 / a) + have hak : 1 ≤ a * k := by rw [mul_comm]; exact (div_le_iff₀ ha).mp hk + let c := 100 + 2 * (1 + p.gain * k) + p.growth + M * (1 + p.gain * k) + 2 * p.steps * p.groupRate + have grow : ∀ᶠ j : ℕ in atTop, (c * j ^ 2) ^ e ≤ 2 ^ j := by + have h := (isLittleO_pow_const_const_pow_of_one_lt (R := ℝ) (2 * e) + (by norm_num : (1 : ℝ) < 2)).const_mul_left (c ^ e : ℝ) + filter_upwards [h.eventuallyLE] with j hj + have h' : (c : ℝ) ^ e * (j : ℝ) ^ (2 * e) ≤ (2 : ℝ) ^ j + := (le_abs_self _).trans (by simpa using hj) + rw [mul_pow, ← pow_mul] + exact_mod_cast h' + obtain ⟨j, hj⟩ := eventually_atTop.mp grow + filter_upwards [eventually_rounds p M ha j] with n hn v T₀ b ξ hb hv + have hcl : Nat.clog 2 (Nat.clog 2 n) ≤ v.height + := Nat.clog_le_of_le_pow (by exact_mod_cast hv.2.2.1) + have hr : v.height ≤ c * v.j ^ 2 := + (show v.height ≤ v.span from Nat.le_add_left ..).trans (Suits.span_square hv hb hak) + unfold inputDictionary + apply Nat.pow_le_pow_right (by decide) + exact (Nat.pow_le_pow_left (hcl.trans hr) e).trans + ((hj _ (hn v T₀ b ξ hv)).trans (Nat.pow_le_pow_right (by decide) (by omega))) + +end Levels +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Assembly of the compression stage over the common working field -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Filter Contraction Levels + +private theorem factor_le {C D h σ X : ℝ} {r s : ℕ} + (hc : C ≤ D) (hD : 0 ≤ D) (hl : 1 ≤ Real.log h) + (hr : r ≤ s) (hh : 0 ≤ h) (hx : 0 ≤ X) : + C * (Real.log h) ^ r * h ^ σ * X ≤ D * (Real.log h) ^ s * h ^ σ * X := + mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_right + (mul_le_mul hc (pow_le_pow_right₀ hl hr) (by positivity) hD) + (Real.rpow_nonneg hh _)) hx + +/-- Install the weighted rounds using a controller for local concentration. +The remaining construction is uniform in the finite working field. -/ +theorem polyInstallable_of_controller (k : Type) [Field k] [Finite k] + (sync : MatrixExponent.Prices.SharedPrice (AlgebraicClosure k)) + (sphere : ∀ (F : Type) [Field F] [Fintype F] (s : Plan), + s.C = Input.terminalExponent localDegree 10 → + ∀ p l b : ℕ, ∃ A J, SphereScale.Controlled F s p l b A J) : + PolyInstallable k := by + intro δ β hδ hδ' hβ hβ' + have hδ₁ : δ ≤ 1 := by linarith + have tag := Routing.wide_of_shared_price sync + obtain ⟨s, hs, hv, hp, ratio, unit, _, overhead, ⟨window⟩, restarts⟩ := + restart_plan tag sync hδ hδ₁ + obtain ⟨A, J, control⟩ := sphere window.F s window.coefficient window.p window.l window.b + obtain ⟨H, hH, restart⟩ := restarts J + obtain ⟨L, terminal⟩ := Current.finish + let B := 5 * A + 2 + let G := max groupPower (3 * J + 4) + have hD : 8 ≤ s.D := localDegree_large.trans window.large.le + obtain ⟨p, E, C, q, admissible, hD', hf, hOver, allow, hE, expG, expL, hq, enough, initMeta⟩ := + s.assembly_design J G H L B hD hv hp ratio + refine ⟨p, A, window.T₀, p.groupRate * q, window.F, window.field, inferInstance, window.ext, ?_⟩ + intro a b ξ ha small hb hb' hξ e + have hqa : (p.groupRate * q : ℕ) * a ≤ b := by + refine le_trans ?_ (small.le.trans hb) + exact mul_le_mul_of_nonneg_right (Nat.cast_le.mpr (by omega)) ha.le + have ha₁ : a ≤ 1 := by + have hN : (1 : ℝ) ≤ (p.groupRate + p.groupRate * q + 1 : ℕ) := + by exact_mod_cast (show 1 ≤ p.groupRate + p.groupRate * q + 1 by omega) + have he := mul_le_mul_of_nonneg_right hN ha.le + linarith only [he, small, hβ'] + let σ := a * δ / 12 + have hσ : 0 < σ := by unfold σ; positivity + have hσ₁ : σ ≤ 1 := by + have h := mul_le_mul ha₁ hδ' hδ.le (by norm_num : 0 ≤ (1 : ℝ)) + unfold σ + linarith only [h] + let d := G + H + L + 2 + let τ := σ / (d : ℝ) + have ht : 0 < τ := by unfold τ d; positivity + have tolerance {t : ℕ} (ht' : t ≤ d) : (t : ℝ) * τ ≤ σ := calc + _ ≤ (d : ℝ) * τ := mul_le_mul_of_nonneg_right (Nat.cast_le.mpr ht') ht.le + _ = σ := by + have hd : (d : ℝ) ≠ 0 := by unfold d; positivity + unfold τ + field_simp + obtain ⟨R, prices⟩ := Contraction.Prices.eventual tag ht + let M := 1 + (7 + max R 1) * (G + H + L + 1) + have reserve {t : ℕ} (ht : t ≤ G + H + L + 1) : (7 + max R 1) * t ≤ M := + (Nat.mul_le_mul_left _ ht).trans (Nat.le_add_left ..) + let margin := (J + s.d + s.p + 1) + (groupCoefficient s J + s.d + s.p + 2 * E + 6) + + (frameRate s J + 2 * E + 1) + have small' := p.small_exponent hq ha hβ' small + obtain ⟨J₀, hJ, levels⟩ := funded_levels p M B C window.T₀ (s.d + s.p + 1) margin + hδ₁ ha ha₁ (hβ.trans_le hb) (hb'.trans (by norm_num)) hξ small' + let initC := 10000 + 280 * J₀ + 140 + let roundC := Current.roundCostFactor s B J G H J₀ + let gateC : ℝ := 2 ^ (max G H + 2 * p.groupRate * q) + let endC := terminalFactor p s q L J₀ + let C₁ := 1 + initC + roundC + gateC + endC + let r := 2 * (G + H + L + 1) + 2 + let keys := 5 + J + 2 ^ H + 3 + have hinitC : 0 ≤ initC := by unfold initC; positivity + have hroundC : 0 ≤ roundC := by unfold roundC Current.roundCostFactor; positivity + have hgateC : 0 ≤ gateC := by unfold gateC; positivity + have hendC : 0 ≤ endC := zero_le_one.trans (terminalFactor_one p s q L hJ) + have hC₁ : 1 ≤ C₁ := by unfold C₁; linarith + have hin : initC ≤ C₁ := by unfold C₁; linarith + have hround : roundC ≤ C₁ := by unfold C₁; linarith + have hgate : gateC ≤ C₁ := by unfold C₁; linarith + have hend : endC ≤ C₁ := by unfold C₁; linarith + have roundR : 2 * max G H ≤ r := by unfold r; omega + have endR : 2 * (L + 1) ≤ r := by unfold r; omega + have trace := installed_trace (p := p) (M := M) (T₀ := window.T₀) (b := b) (ξ:=ξ) + ha ha₁ hδ C₁ hC₁ r q keys 2 + refine ⟨M, ?_⟩ + filter_upwards [levels, prices, trace, eventually_inputDictionary p M e ha] + with n level priceExists install hlabels + obtain ⟨hh, hl, v, ok, fit, large, hspan⟩ := level + have span : ((v.span + s.d + s.p + 1 : ℕ) : ℝ) ≤ J₀ * (Real.log (Nat.clog 2 n)) ^ 2 := by + simpa only [Nat.add_assoc] using hspan + refine ⟨v, ok, ?_⟩ + intro F _ _ _ _ _ + dsimp only + intro fieldLo fieldHi x y G₀ m u labels hm hm' hsize had few hu he + obtain ⟨hm₀, hm₂⟩ := ok.input_size hm hm' + by_cases he₀ : wd x + wd y = 0 + · exact Levels.installed_scalar ok ha hδ hm₀ he₀ + have hepos : 0 < wd x + wd y := Nat.pos_of_ne_zero he₀ + obtain ⟨price, space, wide, priceW⟩ := priceExists F + have hw : 16 * Nat.clog 2 n ≤ price.w := space.ge + obtain ⟨P, i, z, exactPower, current, empty⟩ := + starting_layer_of_box ok fit (hβ.trans_le hb) hm hD (hf ▸ p.floor_le) fieldHi allow + G₀ had hsize (few.trans (hlabels v _ _ _ (by linarith) ok)) hu + have height : (P.height : ℝ) + 1 ≤ J₀ * (Real.log (Nat.clog 2 n)) ^ 2 := by + have hb₀ := Nat.add_le_add_right current.height 1 + exact (by exact_mod_cast hb₀ : (P.height : ℝ) + 1 ≤ ((v.span + s.d + s.p + + 1 : ℕ) : ℝ)).trans span + have startup := current.init_budget fit empty hm₂ (by unfold M; omega) initMeta + (by omega : 1 ≤ E) (by unfold margin at large; omega) hJ (by linarith) hl height + let h : ℝ := Nat.clog 2 n + let exp := v.expense h m (wd x + wd y) q + let width := (p.D : ℝ) * (v.finalWidth : ℝ) + have h₀ : 0 ≤ h := by positivity + have hExp : 0 ≤ exp := by unfold exp Levels.expense Levels.finalBudget; positivity + have hWidth : 0 ≤ width := by unfold width; positivity + have hpow : 1 ≤ h ^ σ := Real.one_le_rpow (by linarith) hσ.le + have budget (j : ℕ) {D : ℝ} (hD : D ≤ C₁) (hj : j ≤ r) {X : ℝ} (hx : 0 ≤ X) : + D * (Real.log h) ^ j * h ^ σ * X ≤ C₁ * (Real.log h) ^ r * h ^ σ * X := + factor_le hD (zero_le_one.trans hC₁) hl hj h₀ hx + have startCost : ((140 * (P.snapshot.port.width + v.batch * (wd x + wd y)) + 1 : ℕ) : ℝ) ≤ + C₁ * (Real.log h) ^ r * h ^ σ * exp := calc + _ ≤ initC * (Real.log h) ^ 2 * exp := startup + _ ≤ initC * (Real.log h) ^ 2 * h ^ σ * exp := + mul_le_mul_of_nonneg_right (le_mul_of_one_le_right (by positivity) hpow) hExp + _ ≤ _ := budget 2 hin (by unfold r; omega) hExp + refine install v m ok F x y G₀.eval P (fun j Q => v.Current s n m j E Q) i z current exactPower + startCost ?_ ?_ + · intro j hj Q cur + obtain ⟨low, high⟩ := ok.width_window hj.le + obtain ⟨pchar, repr⟩ := window.extension F high fieldLo + let _ := pchar + obtain ⟨d₀, z₀, sc, ready, hz, lo, up⟩ := window.scales (v.width j) low + obtain ⟨Q', L₁, u₁, c₁, cur', few', cap', cost', run⟩ := + cur.paid_round ok fit control restart admissible sc ready repr fieldHi hs unit overhead hz lo + up + hD' hOver hj hm hm₂ hepos he + (by unfold margin at large; omega) (by + unfold margin at large + omega) (by unfold margin at large; omega) + (Nat.le_max_left ..) (Nat.le_max_right ..) hH expG enough hqa hh hl ht.le + (tolerance (by unfold d; omega)) (tolerance (by unfold d; omega)) hσ₁ + priceW hw wide (reserve (by omega)) (reserve (by omega)) hJ span + refine ⟨Q', L₁, u₁, c₁, cur', few'.trans (Nat.mul_le_mul_right _ (Nat.le_add_right ..)), + ?_, cost'.trans (budget _ hround roundR hExp), run⟩ + apply cap'.trans + simpa only [pow_zero, mul_one] using (budget 0 hgate (Nat.zero_le _) hWidth) + · intro Q cur + obtain ⟨L₁, few', run⟩ := terminal (F := F) (Q := Q) price cur fit hm₂ + (by unfold margin at large; omega) hw + have heq : wd (copies x v.batch) + wd (copies y v.batch) = v.batch * (wd x + wd y) := by + rw [wd_copies, wd_copies, Nat.mul_add] + rw [heq] at run + obtain ⟨cap', cost'⟩ := paid_finish v s price m (wd x + wd y) ok fit expL hh hl ht.le + (tolerance (by unfold d; omega)) priceW wide (reserve (by omega)) enough hqa hJ span + refine ⟨L₁, _, _, few'.trans ?_, cap'.trans (budget _ hend endR hWidth), + cost'.trans (budget _ hend endR hExp), run⟩ + have hN : 2 ≤ Nat.clog 2 n := by exact_mod_cast hh + have hN₂ : 0 < (Nat.clog 2 n) ^ 2 := pow_pos (Nat.zero_lt_two.trans_le hN) _ + exact (show 3 ≤ keys from Nat.le_add_left ..).trans (Nat.le_mul_of_pos_right _ hN₂) + +theorem installable_of_controller (k : Type) [Field k] [Finite k] + (sync : MatrixExponent.Prices.SharedPrice (AlgebraicClosure k)) + (sphere : ∀ (F : Type) [Field F] [Fintype F] (s : Plan), + s.C = Input.terminalExponent localDegree 10 → + ∀ p l b : ℕ, ∃ A J, SphereScale.Controlled F s p l b A J) : + Installable k := + (polyInstallable_of_controller k sync sphere).installable + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Access.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Access.lean new file mode 100644 index 0000000000..6ca8b08b48 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Access.lean @@ -0,0 +1,785 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Normalize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import Mathlib.Algebra.Order.Chebyshev +public import Mathlib.Analysis.Real.Sqrt +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.RestoreCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.WideTag +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Status + +/-! # Bundle preparation and local contraction -/ + +@[expose] public section + +/- # Preparing the parallel bundles for local concentration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Packing + +variable {F : Type} {x y : Wire} {h D T R g : ℕ} {W : ℝ} + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun v => P.place v = p`. -/ +def residents (P : Input F x y h D T R g W) (p : P.V × Cell h) : Finset P.diagram.V := + univ.filter fun v => P.place v = p + +open scoped Classical in +theorem resident_count (P : Input F x y h D T R g W) (p : P.V × Cell h) : + (P.residents p).card ≤ 100 * D := by + simpa only [residents, Fintype.card_subtype] using P.count p + +open scoped Classical in +theorem station_count (P : Input F x y h D T R g W) : + Fintype.card P.diagram.V ≤ (univ.image P.place).card * (100 * D) := by + classical + let cells := univ.image P.place + have sub : (univ : Finset P.diagram.V) ⊆ cells.biUnion P.residents := fun v _ => + mem_biUnion.mpr ⟨P.place v, mem_image_of_mem _ (mem_univ _), mem_filter.mpr ⟨mem_univ _, rfl⟩⟩ + calc + _ = (univ : Finset P.diagram.V).card := (card_univ).symm + _ ≤ (cells.biUnion P.residents).card := card_le_card sub + _ ≤ ∑ p ∈ cells, (P.residents p).card := card_biUnion_le + _ ≤ ∑ _ ∈ cells, 100 * D := sum_le_sum fun p _ => P.resident_count p + _ = _ := by simp [cells] + +open scoped Classical in +private theorem neighbors (P : Input F x y h D T R g W) (v : P.diagram.V) : + Fintype.card {w // 0 < P.diagram.width v w ∨ 0 < P.diagram.width w v} ≤ (g + 1) * (100 * D) + := by + classical + let sites := insert (P.place v).1 (P.adj (P.place v).1) + let cells := sites.image (fun s => (s, (P.place v).2)) + let N := univ.filter fun w => 0 < P.diagram.width v w ∨ 0 < P.diagram.width w v + have live (w) (hw : w ∈ N) : (P.place w).2 = (P.place v).2 ∧ (P.place w).1 ∈ sites := by + rcases (mem_filter.mp hw).2 with hv | hv + · obtain ⟨e⟩ := Fintype.card_pos_iff.mp hv + have he := P.edge e.val + dsimp only at he + rw [e.2.1, e.2.2] at he + exact ⟨he.1, mem_insert.mpr he.2⟩ + · obtain ⟨e⟩ := Fintype.card_pos_iff.mp hv + have he := P.edge e.val + dsimp only at he + rw [e.2.1, e.2.2] at he + exact ⟨he.1.symm, mem_insert.mpr (he.2.imp Eq.symm (fun hh => P.sym _ _ hh))⟩ + have sub : N ⊆ cells.biUnion P.residents := by + intro w hw + obtain ⟨h₁, h₂⟩ := live w hw + refine mem_biUnion.mpr ⟨P.place w, ?_, mem_filter.mpr ⟨mem_univ _, rfl⟩⟩ + exact mem_image.mpr ⟨(P.place w).1, h₂, Prod.ext rfl h₁.symm⟩ + have cnt : cells.card ≤ g + 1 := + card_image_le.trans ((card_insert_le _ _).trans (Nat.add_le_add_right (P.degree _) _)) + calc + _ = N.card := Fintype.card_subtype _ + _ ≤ (cells.biUnion P.residents).card := card_le_card sub + _ ≤ ∑ p ∈ cells, (P.residents p).card := card_biUnion_le + _ ≤ ∑ _ ∈ cells, 100 * D := sum_le_sum fun p _ => P.resident_count p + _ = cells.card * (100 * D) := by simp + _ ≤ _ := Nat.mul_le_mul_right _ cnt + +variable [Field F] + +open scoped Classical in +theorem packet_arity (P : Input F x y h D T R g W) (r : ℕ) + (hD : 400 * (g + 1) ≤ D) (hr : r * D ^ 2 ≤ 2 * T) (v : P.diagram.V) : + (P.diagram.pad r).arity v ≤ P.diagram.arity v + T := by + have addBound : 2 * r * ((g + 1) * (100 * D)) ≤ T := by + have hb : 2 * (2 * r * ((g + 1) * (100 * D))) ≤ 2 * T := calc + _ = (400 * (g + 1)) * (r * D) := by ring + _ ≤ D * (r * D) := Nat.mul_le_mul_right _ hD + _ = r * D ^ 2 := by ring + _ ≤ _ := hr + exact Nat.le_of_mul_le_mul_left hb (by decide) + exact (P.diagram.arity_pad r v).trans + (Nat.add_le_add_left ((Nat.mul_le_mul_left _ (P.neighbors v)).trans addBound) _) + +open scoped Classical in +/-- Pad each nonempty ordered bundle by zero bits. This retains the +original stations and exterior ports. Doubling the width scale and +multiplying the mass budget by 101 pays for the extra bits. -/ +def packetize (P : Input F x y h D T R g W) (r : ℕ) (hr₀ : 0 < r) + (hD : 400 * (g + 1) ≤ D) (hr : r * D ^ 2 ≤ 2 * T) : + Input F x y h D (2 * T) r g (101 * W) := by + classical + have hW : 0 ≤ W := (by positivity : (0 : ℝ) ≤ (univ.image P.place).card * D * T).trans P.occupied + have arity (v : P.diagram.V) : ((P.diagram.pad r).arity v : ℝ) ≤ (P.diagram.arity v : ℝ) + T := by + exact_mod_cast P.packet_arity r hD hr v + refine ⟨P.V, P.diagram.pad r, P.place, P.adj, P.sym, P.degree, ?_, ?_, ?_, ?_, P.mobile, + ?_, ?_, ?_, P.count, ?_, ?_, P.ranks⟩ + · intro e + obtain ⟨e', hs, ht⟩ := P.diagram.contact_pad r e + simpa only [hs, ht] using P.edge e' + · intro e + obtain ⟨e', hs, ht⟩ := P.diagram.contact_pad r e + simpa only [hs, ht] using P.loopless e' + · intro v + exact (P.positive v).trans_le (P.diagram.arity_le_pad r v) + · exact fun v w => P.diagram.divisible_pad hr₀ v w + · rintro (q|q) + · exact P.ext (.inl q) + · exact P.ext (.inr q) + · push_cast + nlinarith only [P.occupied, hW] + · push_cast + nlinarith only [P.immobile, hW] + · intro p + have hcount : ((P.residents p).card : ℝ) ≤ 100 * (D : ℝ) := by exact_mod_cast P.resident_count p + calc + _ ≤ push P.place (fun v => (P.diagram.arity v : ℝ) + T) p := push_le_push P.place arity _ + _ = push P.place (fun v => P.diagram.arity v) p + (P.residents p).card * (T : ℝ) := by + simp only [push, residents, ← sum_filter, sum_add_distrib, sum_const, nsmul_eq_mul] + _ ≤ 100 * (D : ℝ) * T + 100 * (D : ℝ) * T := + add_le_add (P.mass p) (mul_le_mul_of_nonneg_right hcount (by positivity)) + _ = _ := by push_cast; ring + · have hn : (Fintype.card P.diagram.V : ℝ) * T ≤ 100 * W := calc + _ ≤ (((univ.image P.place).card : ℝ) * (100 * D)) * T := + mul_le_mul_of_nonneg_right (by exact_mod_cast P.station_count) (by positivity) + _ = 100 * ((univ.image P.place).card * (D : ℝ) * T) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left P.occupied (by norm_num) + have hs (v : P.diagram.V) : + ((P.diagram.pad r).arity v : ℝ) ^ 2 ≤ 2 * (P.diagram.arity v : ℝ) ^ 2 + 2 * (T : ℝ) ^ 2 + := calc + _ ≤ ((P.diagram.arity v : ℝ) + T) ^ 2 := pow_le_pow_left₀ (by positivity) (arity v) _ + _ ≤ _ := by nlinarith only [sq_nonneg ((P.diagram.arity v : ℝ) - T)] + have hw := sum_le_sum (s:=univ) fun v _ => hs v + calc + _ ≤ 2 * (∑ v, (P.diagram.arity v : ℝ) ^ 2)+ + (Fintype.card P.diagram.V : ℝ) * (2 * (T : ℝ) ^ 2) := by + have hsums : (∑ v, ((P.diagram.pad r).arity v : ℝ) ^ 2) ≤ + 2 * (∑ v, (P.diagram.arity v : ℝ) ^ 2) + + 2 * ((Fintype.card P.diagram.V : ℝ) * (T : ℝ) ^ 2) := by + simpa only [sum_add_distrib, ← mul_sum, sum_const, card_univ, nsmul_eq_mul] using hw + exact hsums.trans_eq (by ring) + _ ≤ (101 * W) * ((2 * T : ℕ) : ℝ) := by + push_cast + nlinarith only [P.squares, mul_le_mul_of_nonneg_right hn (show (0 : ℝ) ≤ T by positivity)] + +open scoped Classical in +theorem packetize_eval (P : Input F x y h D T R g W) (r : ℕ) (hr₀ : 0 < r) + (hD : 400 * (g + 1) ≤ D) (hr : r * D ^ 2 ≤ 2 * T) : + (P.packetize r hr₀ hD hr).diagram.eval = P.diagram.eval := + P.diagram.eval_pad r + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Extending the geometric concentration estimates to arbitrary scales -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Finset Filter Packing + +variable {F : Type} {x y : Wire} {h D T R g u C ℓ : ℕ} {W : ℝ} + +open scoped Classical in +theorem pad_bounds (hD : 0 < D) : + D ≤ 2 ^ Nat.clog 2 D ∧ 2 ^ Nat.clog 2 D ≤ 2 * D := + ⟨Nat.le_pow_clog (by decide) D, Transcript.pow_clog_le_twice hD⟩ + +open scoped Classical in +private theorem pad_power (hD : 2 ≤ D) (j : ℕ) : + ((2 : ℕ) ^ Nat.clog 2 D) ^ j ≤ D ^ (2 * j) := by + have hd : (2 : ℕ) ^ Nat.clog 2 D ≤ D ^ 2 := (pad_bounds (by omega : 0 < D)).2.trans + (by rw [pow_two]; exact Nat.mul_le_mul_right _ hD) + exact (Nat.pow_le_pow_left hd _).trans_eq (pow_mul ..).symm + +open scoped Classical in +/-- The round up of type `Input F x y h (2 ^ Nat.clog 2 D) T R g (2 * W)` for the given inputs. -/ +def Input.roundUp (P : Input F x y h D T R g W) (hD : 0 < D) : + Input F x y h (2 ^ Nat.clog 2 D) T R g (2 * W) := by + have low := (pad_bounds hD).1 + have high := (pad_bounds hD).2 + have low' : (D : ℝ) ≤ (2 : ℝ) ^ Nat.clog 2 D := by exact_mod_cast low + have high' : (2 : ℝ) ^ Nat.clog 2 D ≤ 2 * (D : ℝ) := by exact_mod_cast high + have hW : 0 ≤ W := (by positivity : (0 : ℝ) ≤ (univ.image P.place).card * D * T).trans P.occupied + refine ⟨P.V, P.diagram, P.place, P.adj, P.sym, P.degree, P.edge, P.loopless, P.positive, P.width, + P.mobile, P.ext, ?_, ?_, ?_, ?_, ?_, P.ranks⟩ + · have hx := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left high' + (by positivity : (0 : ℝ) ≤ (univ.image P.place).card)) (show (0 : ℝ) ≤ T by positivity) + calc + _ ≤ ((univ.image P.place).card : ℝ) * (2 * D) * T := by exact_mod_cast hx + _ = 2 * ((univ.image P.place).card * D * T) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left P.occupied (by norm_num) + · have hx := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left high' + (by positivity : (0 : ℝ) ≤ Fintype.card {v // ¬P.mobile v})) (show (0 : ℝ) ≤ T by positivity) + calc + _ ≤ (Fintype.card {v // ¬P.mobile v} : ℝ) * (2 * D) * T := by exact_mod_cast hx + _ = 2 * (Fintype.card {v // ¬P.mobile v} * D * T) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left P.immobile (by norm_num) + · exact fun p => (P.count p).trans (Nat.mul_le_mul_left _ low) + · intro p + refine (P.mass p).trans ?_ + push_cast + exact mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left low' (by norm_num)) (by positivity) + · refine P.squares.trans (mul_le_mul_of_nonneg_right (by linarith) (by positivity)) + +open scoped Classical in +theorem Concentrated.of_round_up (P : Input F x y h D T R g W) {Q : LocalTerm F x y h u} + (hD : 2 ≤ D) (hc : Concentrated (P.roundUp (by omega)) Q C (Nat.clog 2 D) ℓ) : + Concentrated P Q (2 * C) (Nat.clog 2 D) ℓ := by + obtain ⟨low, high⟩ := pad_bounds (by omega : 0 < D) + have low' : (D : ℝ) ≤ (2 : ℝ) ^ Nat.clog 2 D := by exact_mod_cast low + have high' : (2 : ℝ) ^ Nat.clog 2 D ≤ 2 * (D : ℝ) := by exact_mod_cast high + have powD := pad_power hD C + refine ⟨hc.cells.trans (Nat.mul_le_mul_right _ powD), ?_, fun v => (hc.fullDegree v).trans powD, + ?_, ?_, ?_, ?_, ?_⟩ + · exact fun v => (hc.coreDegree v).trans (by omega) + · calc + _ ≤ (Fintype.card Q.freeze.Fixed : ℝ) * (2 : ℝ) ^ Nat.clog 2 D * T := by + exact mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left low' (by positivity)) (by + positivity) + _ ≤ C * (2 * W) := by simpa only [Nat.cast_pow, Nat.cast_ofNat] using hc.frozenCount + _ = _ := by push_cast; ring + · intro v + have hv := hc.frozenMax v + push_cast at hv ⊢ + exact hv.trans ((mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left high' + (by positivity)) (by positivity)).trans_eq (by ring)) + · exact hc.frozenSquare.trans_eq (by push_cast; ring) + · intro v + have nonneg : 0 ≤ Q.charge v.val := (Nat.cast_nonneg _).trans (Q.cover v.val) + have hx : (D : ℝ) ^ ℓ ≤ ((2 : ℝ) ^ Nat.clog 2 D) ^ ℓ := pow_le_pow_left₀ (by positivity) low' _ + exact (mul_le_mul_of_nonneg_left hx nonneg).trans (by + simpa only [Nat.cast_pow, Nat.cast_ofNat] using hc.coreMax v) + · exact hc.coreSum.trans_eq (by push_cast; ring) + +open scoped Classical in +theorem LocalExpansion.of_round_up [Field F] (P : Input F x y h D T R g W) {A : ℕ} + (hD : 2 ≤ D) (hc : LocalExpansion (P.roundUp (by omega)) u C (Nat.clog 2 D) ℓ A) : + LocalExpansion P u (2 * C) (Nat.clog 2 D) ℓ A := by + obtain ⟨I, _, Q, c, size, eval, geo⟩ := hc + exact ⟨I, inferInstance, Q, c, size, eval, fun i => Concentrated.of_round_up P hD (geo i)⟩ + +open scoped Classical in +/-- Taking an integral quotient loses at most a factor of two. -/ +theorem floor_units {B T : ℕ} (hB : 0 < B) (ht : B ≤ T) : + let u := T / B + 0 < u ∧ u * B ≤ T ∧ T ≤ 2 * u * B := by + let u := T / B + have hu : 0 < u := by + change 1 ≤ T / B + exact (Nat.le_div_iff_mul_le hB).mpr (by simpa using ht) + have hupper : T ≤ (u + 1) * B := calc + _ = T % B + B * u := (Nat.mod_add_div ..).symm + _ ≤ B + B * u := Nat.add_le_add_right (Nat.mod_lt _ hB).le _ + _ = _ := by ring + refine ⟨hu, Nat.div_mul_le_self .., hupper.trans (Nat.mul_le_mul_right _ (by omega))⟩ + +open scoped Classical in +private theorem unit_bound {D T C : ℕ} (hD : 2 ≤ D) + (ht : ((2 : ℕ) ^ Nat.clog 2 D) ^ C ≤ T) : + ∃ u : ℕ, 0 < u ∧ u * ((2 : ℕ) ^ Nat.clog 2 D) ^ C ≤ T ∧ T ≤ u * D ^ (2 * C + 1) := by + let B := ((2 : ℕ) ^ Nat.clog 2 D) ^ C + let u := T / B + obtain ⟨hu, lower, upper⟩ := floor_units (B:=B) (by unfold B; positivity) ht + have last : 2 * B ≤ D ^ (2 * C + 1) := by + rw [pow_succ] + exact (Nat.mul_le_mul hD (pad_power hD C)).trans_eq (mul_comm ..) + refine ⟨u, hu, lower, upper.trans ?_⟩ + calc + _ = u * (2 * B) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ last + +open scoped Classical in +/-- The geometric expansion for all sufficiently large integral D. +The positive bundle floor is at least `T / D^(2*C+1)`. -/ +theorem LocalLaw.arbitrary {k : Type} [Field k] {ℓ : ℕ} (law : LocalLaw k ℓ) (g : ℕ) (hg : 0 < g) : + ∃ C : ℕ, ∀ᶠ D : ℕ in atTop, ∃ (A : ℕ) (L : Type) (_ : Field L) (_ : Finite L) (_ : Algebra k L), + ∀ᶠ T : ℕ in atTop, ∃ R u : ℕ, 0 < R ∧ R * D ^ 2 ≤ T ∧ 0 < u ∧ T ≤ u * D ^ (2 * C + 1) ∧ + ∀ (K : Type) (_ : Field K) (_ : Fintype K) (_ : Algebra L K), + A * (1 + T) ^ A ≤ Fintype.card K → + ∀ (x y : Wire) (h : ℕ) (W : ℝ) (P : Input K x y h D T R g W), + LocalExpansion P u (2 * C) (Nat.clog 2 D) ℓ A := by + obtain ⟨C, hC⟩ := law g hg + obtain ⟨j, hj⟩ := eventually_atTop.mp hC + refine ⟨C, ?_⟩ + filter_upwards [eventually_ge_atTop 2, eventually_ge_atTop ((2 : ℕ) ^ j)] with D hD hd + have hpos : 0 < D := by omega + have hlog : j ≤ Nat.clog 2 D := + (Nat.pow_le_pow_iff_right (by decide)).mp (hd.trans (pad_bounds hpos).1) + obtain ⟨A, L, _, _, _, hT⟩ := hj _ hlog + refine ⟨A, L, inferInstance, inferInstance, inferInstance, ?_⟩ + filter_upwards [hT, eventually_ge_atTop (((2 : ℕ) ^ Nat.clog 2 D) ^ C)] with T choose ht + obtain ⟨R, hR, hbudget, run⟩ := choose + obtain ⟨u, hu, hw, low⟩ := unit_bound hD ht + have hh : R * D ^ 2 ≤ T := (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (pad_bounds hpos).1 + _)).trans hbudget + refine ⟨R, u, hR, hh, hu, low, ?_⟩ + intro K _ _ _ hcard x y h W P + exact LocalExpansion.of_round_up P hD (run K inferInstance inferInstance inferInstance hcard + u hu hw x y h (2 * W) (P.roundUp hpos)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Returning to the arity scale before bundle padding -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Finset + +variable {F : Type} [Field F] {x y : Wire} {h D T R r g u C d ℓ A : ℕ} {W : ℝ} + (P : Input F x y h D T R g W) + (hr₀ : 0 < r) (hD : 400 * (g + 1) ≤ D) (hr : r * D ^ 2 ≤ 2 * T) + +open scoped Classical in +theorem Concentrated.of_packetize {Q : LocalTerm F x y h u} + (hc : Concentrated (P.packetize r hr₀ hD hr) Q C d (ℓ + 1)) : + Concentrated P Q (202 * C) d ℓ := by + have hD₂ : 2 ≤ D := by omega + have hD₀ : 0 < D := by omega + have hd : (2 : ℝ) ≤ D := by exact_mod_cast hD₂ + have Wnonneg : 0 ≤ W := (by positivity : 0 ≤ ((univ.image P.place).card : ℝ) * D * T).trans + P.occupied + have hCW : 0 ≤ (C : ℝ) * W := by positivity + have hPow : D ^ C ≤ D ^ (202 * C) := Nat.pow_le_pow_right hD₀ (by omega) + refine ⟨hc.cells.trans (Nat.mul_le_mul_right _ hPow), fun v => (hc.coreDegree v).trans (by omega), + fun v => (hc.fullDegree v).trans hPow, ?_, ?_, ?_, ?_, ?_⟩ + · have h₁ := hc.frozenCount + have h₂ : 0 ≤ (Fintype.card Q.freeze.Fixed : ℝ) * D * T := by positivity + push_cast at h₁ ⊢ + nlinarith only [h₁, h₂, hCW] + · intro v + have h₁ := hc.frozenMax v + have h₂ : 0 ≤ (C : ℝ) * D * T := by positivity + push_cast at h₁ ⊢ + nlinarith only [h₁, h₂] + · exact hc.frozenSquare.trans_eq (by push_cast; ring) + · intro v + have h₁ := hc.coreMax v + have h₂ : 0 ≤ Q.charge v.val := (Nat.cast_nonneg _).trans (Q.cover v.val) + have h₃ := mul_le_mul_of_nonneg_left hd (show 0 ≤ Q.charge v.val * (D : ℝ) ^ ℓ by positivity) + rw [pow_succ] at h₁ + push_cast at h₁ + linarith only [h₁, h₃] + · refine hc.coreSum.trans ?_ + push_cast + have h : (C : ℝ) * (101 * W) ≤ 202 * C * W := by nlinarith only [hCW] + exact mul_le_mul_of_nonneg_right h (by positivity) + +open scoped Classical in +theorem LocalExpansion.of_packetize + (hc : LocalExpansion (P.packetize r hr₀ hD hr) u C d (ℓ + 1) A) : + LocalExpansion P u (202 * C) d ℓ (2 * A) := by + obtain ⟨I, _, Q, c, hN, hEval, hGeo⟩ := hc + refine ⟨I, inferInstance, Q, c, ?_, ?_, fun i => Concentrated.of_packetize P hr₀ hD hr (hGeo i)⟩ + · have hL : Nat.clog 2 (2 * T + 1) ≤ Nat.clog 2 (T + 1) + 1 := by + apply Nat.clog_le_of_le_pow + rw [pow_succ] + have h := Nat.le_pow_clog (by decide : 1 < 2) (T + 1) + omega + have hA : A * (1 + Nat.clog 2 (2 * T + 1)) ≤ (2 * A) * (1 + Nat.clog 2 (T + 1)) := calc + _ ≤ A * (2 * (1 + Nat.clog 2 (T + 1))) := Nat.mul_le_mul_left _ (by omega) + _ = _ := by ring + exact hN.trans (Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ hA)) + · intro a b + exact (hEval a b).trans (congrFun (congrFun (P.packetize_eval r hr₀ hD hr) a) b) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # The total frozen arity in a concentration summand -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Finset + +variable {F : Type} {x y : Wire} {h D T R g u C d ℓ : ℕ} {W : ℝ} + {P : Input F x y h D T R g W} {Q : LocalTerm F x y h u} + +open scoped Classical in +theorem Concentrated.frozen_total (hc : Concentrated P Q C d ℓ) + (hD : 0 < D) (hT : 0 < T) : + (∑ v : Q.freeze.Fixed, Q.charge v.val) ≤ (C : ℝ) * W / Real.sqrt D := by + let r : ℝ := (C : ℝ) * W + let a : Q.freeze.Fixed → ℝ := fun v => Q.charge v.val + let n : ℝ := Fintype.card Q.freeze.Fixed + let S := ∑ v, (a v) ^ 2 + have hW := (show (0 : ℝ) ≤ (univ.image P.place).card * D * T by positivity).trans P.occupied + have hr : 0 ≤ r := by unfold r; positivity + have hd : (0 : ℝ) < D := Nat.cast_pos.mpr hD + have ht : (0 : ℝ) < T := Nat.cast_pos.mpr hT + have hc₁ : n ≤ r / ((D : ℝ) * T) := by + apply (le_div_iff₀ (mul_pos hd ht)).mpr + rw [← mul_assoc] + exact hc.frozenCount + have hc₂ : S ≤ r * T := hc.frozenSquare + have hs : 0 ≤ S := by unfold S; positivity + have hs' : 0 ≤ ∑ v, a v := + sum_nonneg fun v _ => (Nat.cast_nonneg _).trans (Q.cover v.val) + apply (sq_le_sq₀ hs' (div_nonneg hr (Real.sqrt_nonneg _))).mp + change (∑ v, a v) ^ 2 ≤ (r / Real.sqrt D) ^ 2 + calc + _ ≤ n * S := by + simpa only [card_univ] using (sq_sum_le_card_mul_sum_sq (s := univ) (f := a)) + _ ≤ (r / ((D : ℝ) * T)) * (r * T) := + mul_le_mul hc₁ hc₂ hs (by positivity) + _ = r ^ 2 / (D : ℝ) := by + field_simp [ne_of_gt hd, ne_of_gt ht] + _ = _ := by rw [div_pow, Real.sq_sqrt (Nat.cast_nonneg _)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# Common record format for a family of round states + +Different states may have different diagrams. A stage acts on their +encodings, allowing the controller to inspect the short records and +carry the exposed bits independently. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Assembly Coloring + +/-- The data for the layer construction, including `template`, `volume`, `height`, `State`, +`board`. -/ +structure Layer (F : Type) [Field F] (x y : Wire) where + /-- The `Layer` component of type `Template F`. -/ + template : Template F + /-- Stores the volume associated with this `Layer`. -/ + volume : ℕ + /-- The height parameter carried by `Layer`, with type `ℕ`. -/ + height : ℕ + /-- The `Layer` component of type `Type 1`. -/ + State : Type 1 + /-- The `Layer` component of type `State → Board F x y template.scheme.h`. -/ + board : State → Board F x y template.scheme.h + /-- The carried data of type `State → template.format.obj`. -/ + data : State → template.format.obj + /-- The `Layer` component of type `∀ i, template.Presents (data i) (board i)`. -/ + presents : ∀ i, template.Presents (data i) (board i) + fits : ∀ i, template.scheme.Fits (data i).1 volume height + +namespace Layer +variable {F : Type} [Field F] {x y : Wire} (P : Layer F x y) + +/-- The value specified by `(P.board i).diagram`. -/ +abbrev graph (i : P.State) := (P.board i).diagram + +/-- Builds `Encoding P.graph where scheme` with the specified `scheme`, `volume`, `height`, +`extra`. -/ +abbrev encoding : Encoding P.graph where + scheme := P.template.scheme + volume := P.volume + height := P.height + extra := .vec P.template.scheme.m P.template.header + data i := (P.data i).2 + rows i := (P.data i).1 + presents i := (P.presents i).pres + fits := P.fits + +/-- Uses `P.encoding.snapshot` as the representation. -/ +abbrev snapshot := P.encoding.snapshot + +theorem width : P.snapshot.port.width ≤ P.template.format.width + (P.height + 1) * (2 * P.volume) + := by + change (P.template.format.pair (Fmt.payload _ P.volume P.height)).width ≤ _ + rw [Format.width_pair] + exact Nat.add_le_add_left (Fmt.width_payload _ _ _) _ + +/-- Scalar-only stations have had their entries pulled into the branch +weight. This permits discarding them when packing live atoms. -/ +def Neutral : Prop := + ∀ i v, (P.graph i).arity v = 0 → ∀ z, Transcript.sample ((P.graph i).table v) z = 1 + +/-- The condition `∀ i (e : (P.graph i).E), (P.graph i).source e ≠ (P.graph i).target e` on the +specified data. -/ +def Loopless : Prop := + ∀ i (e : (P.graph i).E), (P.graph i).source e ≠ (P.graph i).target e + +/-- Requires `P.template.scheme.k = 0 ∧ P.Neutral ∧ ∀ i, (P.board i).Ready 5 D T L θ`. -/ +def Ready (D T : ℕ) (L θ : ℝ) : Prop := + P.template.scheme.k = 0 ∧ P.Neutral ∧ ∀ i, (P.board i).Ready 5 D T L θ + +theorem installation {k : Val x → Val y → F} {d u n m : ℕ} {L : Finset (Table F)} + (R Q : Layer F (copies x d) (copies y d)) (i : R.State) + (z : F) (h : (fun x y => z * (R.graph i).eval x y) = power k d) (hu : 3 ≤ u) + (run : Transforms F u L R.snapshot Q.snapshot n) + (stop : Finishes F u L Q.snapshot m) : + ∃ I : Installation k d, I.labels = L ∧ I.u = u ∧ + I.cost ≤ 140 * (R.snapshot.port.width + d * (wd x + wd y)) + n + m + 1 := by + let v := 4 * (wd (copies x d) + wd (copies y d) + 34 * R.encoding.port.width) + let A : Installation k d := + ⟨u, hu, L, R.snapshot, Q.snapshot, i, z, h, v, n, m, R.encoding.start hu i, run, stop⟩ + refine ⟨A, rfl, rfl, ?_⟩ + change v + (n + m) + 4 * (d * wd y) + 1 ≤ 140 * (R.encoding.port.width + d * (wd x + wd y)) + n + + m + 1 + simp only [v, wd_copies, mul_add] + omega + +end Layer +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# An encoded contraction with a frozen border + +Physical load and the exponent on the full degree are fixed before +choosing the degree of the input graph. Circuit exponents may depend +on this degree. The dependence of the new label width on the old +width is linear, so successive rounds can reuse the labels. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Packing + +variable {F : Type} [Field F] {T : Template F} {x y : Wire} + +/-- The data for the bound construction, including `load`, `width`, `mass`. -/ +structure Bound where + /-- Stores the load associated with this `Bound`. -/ + load : ℝ + /-- The width parameter carried by `Bound`, with type `ℝ`. -/ + width : ℝ + /-- Stores the mass associated with this `Bound`. -/ + mass : ℝ + +/-- The data for the prices construction, including `w`, `power`, `W`, `tag`. -/ +structure Prices (F : Type) [Field F] where + /-- The `Prices` field of type `ℕ`. -/ + w : ℕ + /-- Stores the power associated with this `Prices`. -/ + power : ℕ + /-- The `Prices` field of type `ℕ`. -/ + W : ℕ + tag : ∀ j v, 1 ≤ j → j ≤ w → w ^ power ≤ v → ∃ s ≤ W * (2 ^ j * v), Radix.Tag F j v s + +/-- The data for the border limit construction, including `denom`, `discount`, `cap`, `total`, +`test`. -/ +structure BorderLimit (F : Type) (x y : Wire) where + /-- Stores the denom associated with this `BorderLimit`. -/ + denom : ℕ + /-- Stores the discount associated with this `BorderLimit`. -/ + discount : ℕ + /-- The capacity bound. -/ + cap : ℕ + /-- Stores the total associated with this `BorderLimit`. -/ + total : ℝ + /-- The `BorderLimit` component of type `(C : Type) → [Fintype C] → (a b : Wire) → Fringe a b + C → Border F C x y a b → Prop`. -/ + test : (C : Type) → [Fintype C] → (a b : Wire) → Fringe a b C → Border F C x y a b → Prop + +variable {u v z : ℕ} (A : Attachment T) (L : BorderLimit F x y) + +/-- The data for the ready construction, including `neutral`, `live`, `simple`, `span`, +`parallel`. -/ +structure Ready (z Δ C : ℕ) (P : Bound) (s : Attachment.Data A x y u) : Prop where + neutral : s.Neutral + live : Nonempty s.G.V + simple : Δ ≤ 3 → ∀ e, s.G.src e ≠ s.G.dst e + span : ∀ j, u ≤ s.q.core.post.toPresentation.borderWidth j + parallel : ∀ i, z ≤ s.G.parallelBits i + scale : s.L.scale = 1 / (L.denom : ℝ) + discount : s.L.discount = L.discount + cap : s.L.cap = L.cap + total : s.L.Z ≤ L.total + charge : ∀ i, ∃ n : ℕ, z ≤ n ∧ s.L.charge i = n + test : L.test s.T s.a s.b s.L s.Z + bounded : s.G.Bounded Δ C P.load + width : (s.G.X : ℝ) ≤ P.width + mass : (s.G.mass : ℝ) ≤ P.mass + +/-- The value specified by `A.frame x y u payload (Ready A L z Δ C P)`. -/ +abbrev frame (u z payload Δ C : ℕ) (P : Bound) := + A.frame x y u payload (Ready A L z Δ C P) + +/-- The base used in the `Contraction` construction. -/ +def base (r z payload : ℕ) := + 100 + 2 ^ r + T.scheme.h + Nat.clog 2 (1 + z) + 2 ^ A.k + 2 ^ A.e + 2 ^ T.scheme.e + payload + + Nat.clog 2 (1 + T.scheme.ℓ + A.ℓ) + +/-- The quantity computed by `base A r z payload + T.scheme.ℓ + A.ℓ + T.count`. -/ +def short (r z payload : ℕ) := base A r z payload + T.scheme.ℓ + A.ℓ + T.count + +/-- The construction uses `short A r z payload` for its intermediate `R`. -/ +def size (p : Prices F) (r z payload H : ℕ) := + let R := short A r z payload + 2 ^ T.scheme.m * (100 + p.w + p.w ^ p.power + p.W + R) ^ H + + 2 ^ (T.scheme.m + T.scheme.h) * (R + p.W) ^ H + (wd x + wd y) * (100 + payload + p.W) ^ H + +/-- The quantity computed by `⟨K * P.load, ρ * P.width + c * (L.total + σ), P.mass + 2 * +P.width⟩`. -/ +def after (P : Bound) (K : ℕ) (ρ c σ : ℝ) : Bound := + ⟨K * P.load, ρ * P.width + c * (L.total + σ), P.mass + 2 * P.width⟩ + +/-- The data for the input construction, including `units`, `zpos`, `vpos`, `load`, `ceiling`. -/ +structure Input (P : Bound) (p : Prices F) (r b u v z payload d B K H : ℕ) + (σ : ℝ) : Prop where + units : u = b * v + zpos : 0 < z + vpos : z ≤ v + load : (u : ℝ) ≤ P.load + ceiling : P.load ≤ B * z + denom : 0 < L.denom + scale : L.denom ≤ B + discount : 2 ^ L.discount ≤ B + total : 0 ≤ L.total + group : r ≤ T.scheme.h + room : K ≤ 2 ^ r + degree : T.scheme.d ≤ d + full : T.full = true + single : T.scheme.k = 0 + positive : 0 < H + alphabet : Nat.clog 2 (Nat.card F) ≤ 2 ^ r + four : 4 * T.scheme.h ≤ T.scheme.m + small : (short A r z payload) ^ H ≤ T.scheme.m + upper : 2 * T.scheme.m ≤ p.w + width : 0 ≤ P.width + mass : 0 ≤ P.mass + history : P.mass + 2 * P.width ≤ L.cap + slack : (K : ℝ) * P.load * (2 ^ (T.scheme.m + T.scheme.h) : ℕ) ≤ σ * (2 : ℝ) ^ r + +/-- The data for the output construction, including `next`, `pack`, `height`, `lower`, `upper`. -/ +structure Output (P : Bound) (p : Prices F) (r u v z payload Δ Δ' C C' K H : ℕ) + (ρ c σ : ℝ) where + /-- The successor of each choice of type `Template F`. -/ + next : Template F + /-- The `Output` component of type `Attachment next`. -/ + pack : Attachment next + height : next.scheme.h + r = T.scheme.h + lower : T.scheme.m ≤ next.scheme.m + upper : next.scheme.m ≤ T.scheme.m + r + K + degree : next.scheme.d ≤ H + full : next.full = true + single : next.scheme.k = 0 + spans : 2 ^ next.scheme.e ≤ H + stations : pack.k ≤ A.k + r + K + outer : 2 ^ pack.e ≤ 2 ^ A.e + H + counters : next.count ≤ (base A r z payload) ^ H + labels : next.scheme.ℓ + pack.ℓ ≤ H * (T.scheme.ℓ + A.ℓ) + (base A r z payload) ^ H + /-- The `Output` component of type `Finset (Table F)`. -/ + keys : Finset (Table F) + few : keys.card ≤ (short A r z payload) ^ H + transfer : Transforms F ((short A r z payload) ^ H) keys + (frame A L u z payload Δ C P) (frame pack L v z payload Δ' C' (after L P K ρ c σ)) + (size (x := x) (y := y) A p r z payload H) + +/-- The phase of type `Prop` for the given inputs. -/ +def Phase (k : Type) [Field k] (Δ Δ' b e K : ℕ) (ρ c : ℝ) : Prop := + ∀ C d B, Δ ≤ C → ∃ H, 0 < H ∧ ∀ (F : Type) [Field F] [Fintype F] [Algebra k F] + {x y : Wire} {T : Template F} (A : Attachment T) (L : BorderLimit F x y) + (P : Bound) (p : Prices F) (r u v z payload : ℕ) (σ : ℝ), + Input A L P p r b u v z payload d B K H σ → + Nonempty (Output A L P p r u v z payload Δ Δ' C (C ^ e) K H ρ c σ) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Shorter payloads may use a padded tag above the price threshold -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Prices +open Coloring Assembly + +variable {F : Type} [Field F] (p : Prices F) + +/-- The quantity computed by `1000 * (1 + p.W) * 2 ^ j * (v + 1 + p.w ^ p.power)`. -/ +def fee (j v : ℕ) := 1000 * (1 + p.W) * 2 ^ j * (v + 1 + p.w ^ p.power) + +theorem access {u j : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) (hj : 1 ≤ j) (hw : j ≤ p.w) (v : ℕ) : + Access F u L j v (p.fee j v) := by + let x := v + p.w ^ p.power + obtain ⟨s, hs, tag⟩ := p.tag j x hj hw (Nat.le_add_left ..) + intro A ha + have h := Access.tag (L := L) hu tag A (ha.trans (Nat.le_add_right ..)) + refine h.mono (le_trans (Nat.add_le_add_right (Nat.mul_le_mul_left 4 hs) _) ?_) + have h' (x W j a v : ℕ) : + 4 * (W * (a * (v + x))) + 1000 * a * (j + (v + x) + 1) ≤ + 4 * (1000 * (1 + W) * a * (v + 1 + x)) + 1000 * a * (j + v + 1) := by ring_nf; omega + exact h' _ _ _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Prices +end + +/- # The common grouping for a layer of boards -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {a H T R : ℕ} {θ L : ℝ} + (P : Layer F x y) (b : P.template.Binning a H T R θ) + +/-- Builds `b.Trial (P.presents i) L where ready` with the specified `ready`, `slack`, `ext`, +`neutral`. -/ +def trial (hp : P.Ready H T L θ) (hn : P.Loopless) + (hs : ∀ i, ((P.board i).seats : ℝ) * H * T ≤ L * (2 : ℝ) ^ (P.template.scheme.h - a)) + (he : ((wd x + wd y : ℕ) : ℝ) * H ≤ L) (i : P.State) : b.Trial (P.presents i) L where + ready := hp.2.2 i + slack := hs i + ext := he + neutral := hp.2.1 i + loopless := hn i + plan := ((P.presents i).plan b.ha (by decide) b.pos b.hT (hp.2.2 i)).some + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # A snapshot of the local inputs after grouping a layer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {a H T R : ℕ} {θ L : ℝ} + (P : Layer F x y) (b : P.template.Binning a H T R θ) + (t : ∀ i, b.Trial (P.presents i) L) + +/-- The quantity computed by `2 ^ b.target.m + wd x + wd y`. -/ +abbrev groupedVolume := 2 ^ b.target.m + wd x + wd y + +/-- Builds `Snapshot.{1} F x y where state` with the specified `state`, `eval`, `port`, +`encode`. -/ +def grouped (q : ℕ) : Snapshot.{1} F x y where + state := P.State + eval i := ((t i).normal q).diagram.eval + port := b.target.format.pair (Fmt.payload b.target.m (P.groupedVolume b) P.height) + encode i a c := (b.data (P.data i), b.target.store _ ((t i).fits (P.fits i)) ((t + i).order.exterior a c)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # A grouped input with the original one-step host graph marked -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {a H T R : ℕ} {θ L : ℝ} + (P : Layer F x y) (b : P.template.Binning a H T R θ) + (t : ∀ i, b.Trial (P.presents i) L) + +/-- Builds `Snapshot.{1} F x y where state` with the specified `state`, `eval`, `port`, +`encode`. -/ +def masked (q : ℕ) : Snapshot.{1} F x y where + state := P.State + eval i := ((t i).normal q).diagram.eval + port := b.target.format.pair (b.Flags.pair (Fmt.payload b.target.m (P.groupedVolume b) P.height)) + encode i a c := (b.data (P.data i), b.status (P.data i), ((P.grouped b t q).encode i a c).2) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Beat/Fanout.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Beat/Fanout.lean new file mode 100644 index 0000000000..9e7752389c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Beat/Fanout.lean @@ -0,0 +1,965 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.Reads +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.FieldStage +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Beat + +/-! # The dyadic banks and their child channels fit the sorting range -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Assembly +variable {F : Type} [Field F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r b u v z payload d B K H : ℕ} {σ : ℝ} + +private theorem bank_size (m n h w : ℕ) (hm : 2 * n + h + 4 ≤ m) (hw : 2 * m ≤ w) : + 2 ^ (n + 1) * ((h + 1) * (2 ^ m + 2 ^ (m + (n + 1)))) < 2 ^ w := by + have hx : 2 ^ m + 2 ^ (m + (n + 1)) ≤ 2 ^ (m + (n + 1) + 1) := by + rw [pow_succ, Nat.mul_two] + exact Nat.add_le_add_right (Nat.pow_le_pow_right (by decide) (Nat.le_add_right ..)) _ + calc + _ ≤ 2 ^ (n + 1) * (2 ^ h * 2 ^ (m + (n + 1) + 1)) + := Nat.mul_le_mul_left _ (Nat.mul_le_mul Nat.lt_two_pow_self hx) + _ = 2 ^ ((n + 1) + (h + (m + (n + 1) + 1))) := by rw [← pow_add, ← pow_add] + _ < _ := Nat.pow_lt_pow_right (by decide) (by omega) + +theorem fanout (h : Input A L P p r b u v z payload d B K H σ) : + 2 ^ (r + 1) * ((payload + 1) * (2 ^ T.scheme.m + 2 ^ (T.scheme.m + (r + 1)))) < 2 ^ p.w := by + apply bank_size _ _ _ _ _ h.upper + have hs : short A r z payload ≤ T.scheme.m := + (Nat.le_self_pow h.positive.ne' _).trans h.small + have hj := h.group + have ha := Nat.two_pow_pos A.k + have hb := Nat.two_pow_pos A.e + have hc := Nat.two_pow_pos T.scheme.e + have hr : r < 2 ^ r := Nat.lt_two_pow_self + unfold short base at hs + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Common bounds on the widths and counters in both phases -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Packing Assembly + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r b u v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r b u v z payload d B K H σ) + (q : (frame A L u z payload Δ C P).state) + +include h in +open scoped Classical in +theorem size_bound (j : q.val.q.core.post.toPresentation.BorderSpan) : + q.val.q.core.post.toPresentation.borderWidth j ≤ B * z := by + let s := q.val.q.core.post + let t := q.val.G.units.place j.val.1 + have hu : (s.atBlock t).peer 0 j.val.2 = none := by + have he := j.property.2 + rw [s.vertex_eq] at he + exact Option.map_eq_none_iff.mp he + have hh : s.toPresentation.borderWidth j = (s.atBlock t).width 0 j.val.2 := by + rw [Scheme.Presentation.borderWidth, s.vertex_eq] + rfl + have hs : s.toPresentation.borderWidth j ≤ q.val.G.tetherLoad t := by + rw [hh, ← s.exterior_volume] + unfold Pattern.volume + apply le_trans _ (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ j.val.2)) + simp [hu] + refine hs.trans ?_ + have hl := (q.val.G.core_le_load t.1 t.2).trans ((q.property.1.bounded.2.2 t.1 t.2).trans + h.ceiling) + have he : (q.val.G.tetherLoad t : ℝ) ≤ B * (z : ℝ) + := (le_add_of_nonneg_right (by positivity)).trans hl + exact_mod_cast he + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def precision (z B g : ℕ) := Nat.clog 2 (B * g * B * z + 1) + +variable (g : ℕ) + +include h in +open scoped Classical in +theorem count_bound {m : ℕ} (hb' : m ≤ B) : + (m : ℝ) * (g * P.load) < 2 ^ (precision z B g) := by + have hn : (B * g * B) * z < 2 ^ (precision z B g) + := Nat.lt_of_succ_le (Nat.le_pow_clog (by decide) _) + have hm : (m : ℝ) ≤ B := Nat.cast_le.mpr hb' + calc + _ ≤ (B : ℝ) * ((g : ℝ) * (B * z)) := + mul_le_mul hm (mul_le_mul_of_nonneg_left h.ceiling (Nat.cast_nonneg _)) + (mul_nonneg (Nat.cast_nonneg _) ((Nat.cast_nonneg _).trans h.load)) (Nat.cast_nonneg _) + _ = ((B * g * B) * z : ℕ) := by simp only [Nat.cast_mul, mul_assoc] + _ < _ := by exact_mod_cast hn + +variable {a z' : ℕ} (G : HostNet F q.val.L a z') + +include h in +open scoped Classical in +theorem valid_of_charge (hmass : G.mass ≤ q.val.L.cap) (bound : ∀ v i, G.load v i ≤ g * P.load) : + (Template.Meter.bounded (precision z B g) (1 / (L.denom : ℝ)) (1 / (2 : ℝ) ^ L.discount)).Valid + G := by + have he := q.property.1 + have hscale : g * P.load < q.val.L.scale * (2 : ℝ) ^ (precision z B g) := by + rw [he.scale, one_div_mul_eq_div, lt_div_iff₀ (Nat.cast_pos.mpr h.denom)] + exact (mul_comm _ _).trans_lt (count_bound h g h.scale) + have hrate : (2 : ℝ) ^ q.val.L.discount * (g * P.load) < 2 ^ (precision z B g) := by + simpa only [he.discount, Nat.cast_pow, Nat.cast_ofNat] using count_bound h g h.discount + have hm := Template.Meter.valid_of_charge (G) (precision z B g) _ hmass bound hscale hrate (by + intro j + obtain ⟨u, _, hu⟩ := he.charge j + exact ⟨u, hu⟩) + change (Template.Meter.bounded _ q.val.L.scale (1 / (2 : ℝ) ^ q.val.L.discount)).Valid G at hm + rw [he.scale, he.discount] at hm + exact hm + +include h in +open scoped Classical in +theorem charges (bound : ∀ v i, G.load v i ≤ g * P.load) : + ∃ δ : ℝ, 0 < δ ∧ (∀ t, δ ≤ q.val.L.scale * q.val.L.charge t) ∧ + ∀ v i, G.load v i ≤ (B * g * B : ℕ) * δ := by + have hd : (0 : ℝ) < L.denom := Nat.cast_pos.mpr h.denom + refine ⟨(z : ℝ) / L.denom, div_pos (Nat.cast_pos.mpr h.zpos) hd, ?_, ?_⟩ + · intro t + obtain ⟨n, hn, hq⟩ := q.property.1.charge t + rw [hq, q.property.1.scale, one_div_mul_eq_div] + exact div_le_div_of_nonneg_right (Nat.cast_le.mpr hn) hd.le + · intro v i + refine ((bound v i).trans (mul_le_mul_of_nonneg_left h.ceiling (Nat.cast_nonneg _))).trans ?_ + rw [← mul_div_assoc, le_div_iff₀ hd, Nat.cast_mul, Nat.cast_mul] + have hpos : 0 ≤ (g : ℝ) * (B * z) := by positivity + exact (mul_le_mul_of_nonneg_left (Nat.cast_le.mpr h.scale) hpos).trans_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Parameters for uniform bounds during contractions with a fixed border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Packing +export BatchDescent.Phase (Poly) +namespace Poly +export MatrixExponent.BatchDescent.Phase.Poly (const of_le pow_sum) +end Poly + +/-- The data for the case construction, including `F`, `[field`, `[finite`, `[alg`, `x`. -/ +structure Case (k : Type) [Field k] (b d B : ℕ) where + /-- The `Case` component of type `Type`. -/ + F : Type + [field : Field F] + [finite : Fintype F] + [alg : Algebra k F] + /-- The `Case` component of type `Wire`. -/ + x : Wire + /-- The `Case` component of type `Wire`. -/ + y : Wire + /-- The `Case` component of type `Template F`. -/ + T : Template F + /-- The `Case` component of type `Attachment T`. -/ + A : Attachment T + /-- The `Case` component of type `BorderLimit F x y`. -/ + L : BorderLimit F x y + /-- The `Case` component of type `Bound`. -/ + P : Bound + /-- The `Case` component of type `Prices F`. -/ + p : Prices F + /-- The `Case` field of type `ℕ`. -/ + r : ℕ + /-- The `Case` field of type `ℕ`. -/ + u : ℕ + /-- The `Case` field of type `ℕ`. -/ + v : ℕ + /-- The `Case` field of type `ℕ`. -/ + z : ℕ + /-- Stores the payload associated with this `Case`. -/ + payload : ℕ + /-- The `Case` field of type `ℕ`. -/ + K : ℕ + /-- The `Case` field of type `ℕ`. -/ + H : ℕ + /-- The `Case` field of type `ℝ`. -/ + σ : ℝ + h : Input A L P p r b u v z payload d B K H σ + +attribute [instance] Case.field Case.finite Case.alg + +namespace Case +variable {k : Type} [Field k] {b d B : ℕ} (i : Case k b d B) +local notation "I" => Case k b d B + +/-- Uses `i.T.scheme.m` as the representation. -/ +abbrev m := i.T.scheme.m +/-- Uses `i.T.scheme.h` as the representation. -/ +abbrev height := i.T.scheme.h +/-- The quantity computed by `i.height - i.r`. -/ +abbrev a := i.height - i.r +/-- The quantity computed by `i.height - i.a`. -/ +abbrev n := i.height - i.a +/-- Uses `Contraction.base i.A i.r i.z i.payload` as the representation. -/ +abbrev base := Contraction.base i.A i.r i.z i.payload +/-- Uses `Contraction.short i.A i.r i.z i.payload` as the representation. -/ +abbrev short := Contraction.short i.A i.r i.z i.payload +/-- The quantity computed by `i.short + i.p.W`. -/ +abbrev block := i.short + i.p.W +/-- The quantity computed by `100 + i.payload + i.p.W`. -/ +abbrev outer := 100 + i.payload + i.p.W +/-- The quantity computed by `100 + i.p.w + i.p.w ^ i.p.power + i.p.W + i.short`. -/ +abbrev long := 100 + i.p.w + i.p.w ^ i.p.power + i.p.W + i.short + +theorem n_eq : i.n = i.r := Nat.sub_sub_self i.h.group +theorem positive : 0 < i.v := i.h.zpos.trans_le i.h.vpos + +private theorem nonneg : 0 ≤ 2 ^ i.r ∧ 0 ≤ 2 ^ i.A.k ∧ 0 ≤ 2 ^ i.A.e ∧ 0 ≤ 2 ^ i.T.scheme.e := + ⟨Nat.zero_le _, Nat.zero_le _, Nat.zero_le _, Nat.zero_le _⟩ + +theorem base_two : 2 ≤ i.base := by unfold base Contraction.base; have := i.nonneg; omega +theorem base_short : i.base ≤ i.short := by unfold short Contraction.short base; omega +theorem short_block : i.short ≤ i.block := Nat.le_add_right .. +theorem outer_block : i.outer ≤ i.block := by + unfold outer block short Contraction.short Contraction.base + have := i.nonneg + omega +theorem block_long : i.block ≤ i.long := by + unfold block long + have := Nat.zero_le (i.p.w ^ i.p.power) + omega +theorem short_two : 2 ≤ i.short := i.base_two.trans i.base_short +theorem block_two : 2 ≤ i.block := i.short_two.trans i.short_block +theorem outer_two : 2 ≤ i.outer := by unfold outer; omega +theorem long_two : 2 ≤ i.long := i.block_two.trans i.block_long + +/-- Computes the base by the application `Poly base f`. -/ +abbrev Base (f : I → ℕ) := Poly base f +/-- Computes the short by the application `Poly short f`. -/ +abbrev Short (f : I → ℕ) := Poly short f +/-- Computes the block by the application `Poly block f`. -/ +abbrev Block (f : I → ℕ) := Poly block f +/-- Computes the outer by the application `Poly outer f`. -/ +abbrev Outer (f : I → ℕ) := Poly outer f +/-- Computes the long by the application `Poly long f`. -/ +abbrev Long (f : I → ℕ) := Poly long f + +variable {f : Case k b d B → ℕ} + +theorem Base.short (h : Base f) : Short f := h.grow base_short +theorem Short.block (h : Short f) : Block f := h.grow short_block +theorem Outer.block (h : Outer f) : Block f := h.grow outer_block +theorem Block.long (h : Block f) : Long f := h.grow block_long +theorem Short.long (h : Short f) : Long f := h.block.long + +theorem base_const (c : ℕ) : Base (fun _ : I => c) := Poly.const base_two c +theorem short_const (c : ℕ) : Short (fun _ : I => c) := Poly.const short_two c +theorem block_const (c : ℕ) : Block (fun _ : I => c) := Poly.const block_two c +theorem outer_const (c : ℕ) : Outer (fun _ : I => c) := Poly.const outer_two c +theorem long_const (c : ℕ) : Long (fun _ : I => c) := Poly.const long_two c + +theorem blocks : Base (fun i : I => 2 ^ i.r) := + Poly.of_le base_two (fun i => by unfold base Contraction.base; have := i.nonneg; omega) +theorem levels : Base (fun i : I => i.height) := + Poly.of_le base_two (fun i => by unfold base Contraction.base height; have := i.nonneg; omega) +theorem units : Base (fun i : I => Nat.clog 2 (1 + i.z)) := + Poly.of_le base_two (fun i => by unfold base Contraction.base; have := i.nonneg; omega) +theorem stations : Base (fun i : I => 2 ^ i.A.k) := + Poly.of_le base_two (fun i => by unfold base Contraction.base; have := i.nonneg; omega) +theorem ports : Base (fun i : I => 2 ^ i.A.e) := + Poly.of_le base_two (fun i => by unfold base Contraction.base; have := i.nonneg; omega) +theorem spans : Base (fun i : I => 2 ^ i.T.scheme.e) := + Poly.of_le base_two (fun i => by unfold base Contraction.base; have := i.nonneg; omega) +theorem lengths : Base (fun i : I => Nat.clog 2 (1 + i.T.scheme.ℓ + i.A.ℓ)) := + Poly.of_le base_two (fun i => by unfold base Contraction.base; have := i.nonneg; omega) +theorem counters : Short (fun i : I => i.T.count) := + Poly.of_le short_two (fun i => by unfold short Contraction.short; omega) +theorem bits : Short (fun i : I => i.T.scheme.ℓ) := + Poly.of_le short_two (fun i => by unfold short Contraction.short; omega) +theorem labels : Short (fun i : I => i.A.ℓ) := + Poly.of_le short_two (fun i => by unfold short Contraction.short; omega) +theorem price : Outer (fun i : I => i.p.W) := Poly.of_le outer_two (fun _ => Nat.le_add_left ..) +theorem loads : Outer (fun i : I => i.payload) := Poly.of_le outer_two (fun i + => by unfold outer; omega) +theorem world : Long (fun i : I => i.p.w) := + Poly.of_le long_two (fun i => by unfold long; have := Nat.zero_le (i.p.w ^ i.p.power); omega) +theorem power : Long (fun i : I => i.p.w ^ i.p.power) := Poly.of_le long_two (fun i + => by unfold long; omega) +theorem hosts : Long (fun i : I => i.m) := world.mono fun i + => (Nat.le_mul_of_pos_left _ (by decide)).trans i.h.upper +theorem groups : Base (fun i : I => i.a) := levels.mono fun _ => Nat.sub_le .. +theorem tiles : Base (fun i : I => 2 ^ i.n) := by + simpa only [n_eq] using (blocks : Base (fun i : I => _)) +theorem slots : Base (fun i : I => 2 ^ i.T.scheme.d) := + (base_const (2 ^ d)).mono fun i => Nat.pow_le_pow_right (by decide) i.h.degree + +end Case +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- +# Charges on host addresses and short block records + +Multiplication by a short quantity is allowed in both terms of the +budget. Multiplication by the world size is confined to the first. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case +variable {κ : Type} [Field κ] {b d B : ℕ} +local notation "I" => Case κ b d B + +/-- The condition `∃ k : ℕ, ∀ i, f i ≤ 2 ^ (j i) * i.long ^ k + 2 ^ (j i + i.height) * i.block ^ +k` on the specified data. -/ +abbrev Mixed (j f : I → ℕ) : Prop := + BatchDescent.Phase.MixedCost (fun i => i.long) (fun i => i.block) (fun i => i.height) j f + +/-- Computes the cost by the application `Mixed m f`. -/ +abbrev Cost (f : I → ℕ) := Mixed m f +/-- The indexed operation `Mixed (fun _ => 0) f`. -/ +abbrev Row (f : I → ℕ) := Mixed (fun _ => 0) f + +variable {j f g n : Case κ b d B → ℕ} + +namespace Mixed + +theorem mono (h : Mixed j f) (hg : ∀ i, g i ≤ f i) : Mixed j g := + BatchDescent.Phase.MixedCost.mono h hg + +theorem add (h : Mixed j f) (h' : Mixed j g) : Mixed j (fun i => f i + g i) := + BatchDescent.Phase.MixedCost.add h h' (fun i => i.long_two) (fun i => i.block_two) + +theorem mul (h : Mixed j f) (h' : Block g) : Mixed j (fun i => f i * g i) := + BatchDescent.Phase.MixedCost.mul h h' (fun i => i.block_long) + +theorem left (h : Mixed j f) (h' : Block g) : Mixed j (fun i => g i * f i) := + (h.mul h').mono fun _ => le_of_eq (mul_comm ..) + +theorem scale (h : Mixed j f) (k : ℕ) : Mixed j (fun i => k * f i) := h.left (block_const k) + +theorem long (j : I → ℕ) (h : Long f) : Mixed j (fun i => 2 ^ (j i) * f i) := + BatchDescent.Phase.MixedCost.long j h + +theorem short (j : I → ℕ) (h : Block f) : Mixed j (fun i => 2 ^ (j i + i.height) * f i) := + BatchDescent.Phase.MixedCost.short j h + +end Mixed + +theorem Long.row (h : Long f) : Row f := by + simpa only [pow_zero, one_mul] using Mixed.long (fun _ => 0) h + +theorem Block.blocks (h : Block f) : Row (fun i => 2 ^ i.height * f i) := by + simpa only [zero_add] using Mixed.short (fun _ => 0) h + +theorem Block.groups (h : Block f) : Row (fun i => 2 ^ i.a * f i) := + h.blocks.mono (fun i => Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (Nat.sub_le ..))) + +theorem Row.hosts (h : Row f) : Cost (fun i => 2 ^ i.m * f i) := + BatchDescent.Phase.MixedCost.hosts (fun i => i.m) h + +theorem Row.expand (h : Row f) (h' : Block (fun i => 2 ^ n i)) : + Cost (fun i => 2 ^ (i.m + n i) * f i) := by + simpa only [pow_add, mul_assoc] using Row.hosts (h.left h') + +theorem Row.cost (h : Row f) : Cost f := + h.hosts.mono fun _ => Nat.le_mul_of_pos_left _ (by positivity) + +/-- Payload transfer can pay a separate charge per exterior bit. -/ +def Total (f : I → ℕ) : Prop := + ∃ k : ℕ, ∀ i, f i ≤ size (x := i.x) (y := i.y) i.A i.p i.r i.z i.payload k + +theorem Cost.total (h : Cost f) : Total f := + let ⟨k, hk⟩ := h + ⟨k, fun i => (hk i).trans (Nat.le_add_right ..)⟩ + +theorem Outer.total (h : Outer f) : Total (fun i => (wd i.x + wd i.y) * f i) := + let ⟨k, hk⟩ := h.bound + ⟨k, fun i => (Nat.mul_le_mul_left _ (hk i)).trans (Nat.le_add_left ..)⟩ + +theorem Total.mono (h : Total f) (hg : ∀ i, g i ≤ f i) : Total g := + let ⟨k, hk⟩ := h + ⟨k, fun i => (hg i).trans (hk i)⟩ + +theorem Total.add (h : Total f) (h' : Total g) : Total (fun i => f i + g i) := by + obtain ⟨l, hl⟩ := h + obtain ⟨k, hk⟩ := h' + refine ⟨max l k + 1, fun i => (Nat.add_le_add (hl i) (hk i)).trans ?_⟩ + have aux (s a : ℕ) (hs : 2 ≤ s) := Nat.mul_le_mul_left a (Poly.pow_sum hs l k) + have h₁ := aux _ (2 ^ i.m) i.long_two + have h₂ := aux _ (2 ^ (i.m + i.height)) i.block_two + have h₃ := aux _ (wd i.x + wd i.y) i.outer_two + simp only [mul_add] at h₁ h₂ h₃ + change (2 ^ i.m * i.long ^ l + 2 ^ (i.m + i.height) * i.block ^ l + (wd i.x + + wd i.y) * i.outer ^ l) + + (2 ^ i.m * i.long ^ k + 2 ^ (i.m + i.height) * i.block ^ k + (wd i.x + wd i.y) * i.outer ^ k) ≤ + 2 ^ i.m * i.long ^ _ + 2 ^ (i.m + i.height) * i.block ^ _ + (wd i.x + wd i.y) * i.outer ^ _ + omega + +theorem Total.mul (h : Total f) (h' : Outer g) : Total (fun i => f i * g i) := by + obtain ⟨l, hl⟩ := h + obtain ⟨k, hk⟩ := h'.bound + refine ⟨l + k, fun i => (Nat.mul_le_mul (hl i) (hk i)).trans ?_⟩ + change (2 ^ i.m * i.long ^ l + 2 ^ (i.m + i.height) * i.block ^ l + (wd i.x + + wd i.y) * i.outer ^ l) * i.outer ^ k ≤ + 2 ^ i.m * i.long ^ (l + k) + 2 ^ (i.m + i.height) * i.block ^ (l + k) + (wd i.x + + wd i.y) * i.outer ^ (l + k) + rw [add_mul, add_mul] + simp only [pow_add, mul_assoc] + gcongr + · exact i.outer_block.trans i.block_long + · exact i.outer_block + +theorem Total.left (h : Total f) (h' : Outer g) : Total (fun i => g i * f i) := + (h.mul h').mono fun _ => le_of_eq (mul_comm ..) + +theorem Total.scale (h : Total f) (k : ℕ) : Total (fun i => k * f i) := h.left (outer_const k) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case +end + +/- # Controlling widths after an expansion of hosts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case +open Assembly Coloring +variable {κ : Type} [Field κ] {b d B : ℕ} +local notation "I" => Case κ b d B + +/-- The data for the child construction, including `extent`, `allocation`, `growth`, `single`, +`spans`. -/ +structure Child (N : (i : I) → Template i.F) (δ : I → ℕ) : Prop where + extent : ∀ i, (N i).scheme.h ≤ i.height + allocation : ∀ i, (N i).scheme.m ≤ i.m + δ i + growth : Short (fun i : I => 2 ^ δ i) + single : ∀ i, (N i).scheme.k = 0 + spans : Short (fun i : I => 2 ^ (N i).scheme.e) + neighbors : Short (fun i : I => 2 ^ (N i).scheme.d) + bits : Short (fun i : I => (N i).scheme.ℓ) + count : Short (fun i : I => (N i).count) + +namespace Child + +theorem parent : Child (fun i : I => i.T) (fun _ => 0) := + ⟨fun _ => le_rfl, fun _ => le_rfl, short_const 1, fun i : I => i.h.single, + Case.spans.short, Case.slots.short, Case.bits, counters⟩ + +variable {N : (i : Case κ b d B) → Template i.F} {δ f : Case κ b d B → ℕ} (H : Child N δ) +include H + +theorem layer (h : Block f) : Row (fun i : I => 2 ^ (N i).scheme.h * f i) := + BatchDescent.Phase.MixedCost.exp_mul_mono h.blocks H.extent + +theorem cost (h : Row f) : Cost (fun i : I => 2 ^ (N i).scheme.m * f i) := + BatchDescent.Phase.MixedCost.exp_mul_mono (h.expand H.growth.block) H.allocation + +theorem address : Long (fun i : I => (N i).scheme.m) := + (hosts.add H.growth.long.of_exp).mono H.allocation + +theorem format : Cost (fun i : I => (N i).format.width) := by + have top := Long.row (((H.neighbors.long.mul (H.address.add (long_const 2))).add (long_const 2))) + have body := H.layer (H.bits.block.add H.count.block) + refine (H.cost (top.add body)).mono fun i : I => ?_ + rw [Template.width] + +theorem scheme : Cost (fun i : I => (N i).scheme.format.width) := + H.format.mono fun i => (N i).scheme_width_le + +variable {j v : Case κ b d B → ℕ} (hj : Short (fun i => 2 ^ j i)) (hv : Row v) + +include hj hv + +theorem expand : Cost (fun i : I => 2 ^ ((N i).scheme.m + j i) * v i) := by + simpa only [pow_add, mul_assoc] using H.cost (hv.left hj.block) + +theorem access : Cost (fun i : I => i.p.fee ((N i).scheme.m + j i) (v i)) := by + have p : Block (fun i : I => 1000 * (1 + i.p.W)) + := (block_const 1000).mul ((block_const 1).add price.block) + have w : Row (fun i : I => v i + 1 + i.p.w ^ i.p.power) + := (hv.add (long_const 1).row).add Case.power.row + refine ((H.expand hj w).left p).mono fun i => ?_ + rw [Prices.fee, mul_assoc] + +theorem gather : Cost (fun i : I => + gatherCost ((N i).scheme.m) (j i) (v i) (i.p.fee ((N i).scheme.m + j i) (v i))) := by + have m := H.address + have q := m.add hj.long.of_exp + have hi := ((long_const 100).add ((q.add ((long_const 3).mul m)).add (long_const 1))).pow 200 + have w := ((Long.row q).add hv).add (long_const 1).row + refine ((((H.access hj hv).scale 4).add ((H.expand hj (Long.row hi)).scale 4)).add + ((H.expand hj w).scale 1100)).mono fun i => ?_ + rw [gatherCost, mul_assoc 1100] + +theorem read : Cost (fun i : I => + Window.readCost ((N i).scheme.m) (j i) (v i) (i.p.fee ((N i).scheme.m + j i) (v i))) := + (H.gather hj hv).add ((H.cost (((H.address.row.add hv).left hj.block).add hv)).scale 1000) + +end Child +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case +end + +/- # Budgets for common headers and per-block fields -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case +open Coloring Assembly + +variable {κ : Type} [Field κ] {b d B : ℕ} +local notation "I" => Case κ b d B + +namespace Width +variable {A E : Case κ b d B → Format} {t f g : Case κ b d B → ℕ} + +theorem expMax (h : Poly t (fun i => 2 ^ f i)) (k : Poly t (fun i => 2 ^ g i)) : + Poly t (fun i => 2 ^ max (f i) (g i)) := by + refine (h.add k).mono fun i => ?_ + rcases le_total (f i) (g i) with h|h + · rw [max_eq_right h]; exact Nat.le_add_left .. + · rw [max_eq_left h]; exact Nat.le_add_right .. + +theorem bit : Short (fun _ : I => Format.bit.width) := short_const _ +theorem addr (h : Poly t f) : Poly t (fun i => (Format.addr (f i)).width) := + h.mono (fun _ => (Format.width_addr _).le) +theorem pair (h : Poly t (fun i => (A i).width)) (k : Poly t (fun i => (E i).width)) : + Poly t (fun i => ((A i).pair (E i)).width) := + (h.add k).mono (fun _ => (Format.width_pair ..).le) +theorem vec (h : Poly t (fun i => 2 ^ f i)) (k : Poly t (fun i => (A i).width)) : + Poly t (fun i => (Format.vec (f i) (A i)).width) := + (h.mul k).mono (fun _ => (Format.width_vec ..).le) +theorem pack {n : I → ℕ} (h : Mixed n (fun i => (A i).width)) (k : Mixed n (fun i => (E i).width)) : + Mixed n (fun i => ((A i).pair (E i)).width) := + (h.add k).mono (fun _ => (Format.width_pair ..).le) +theorem many (h : Short (fun i => 2 ^ f i)) (k : Row (fun i => (A i).width)) : + Row (fun i => (Format.vec (f i) (A i)).width) := + (k.left h.block).mono (fun _ => (Format.width_vec ..).le) +end Width + +namespace Child +variable {N : (i : Case κ b d B) → Template i.F} {δ : Case κ b d B → ℕ} + {A : Case κ b d B → Format} (h : Child N δ) +include h + +theorem vector (a : Row (fun i => (A i).width)) : + Cost (fun i => (Format.vec (N i).scheme.m (A i)).width) := + (h.cost a).mono (fun _ => (Format.width_vec ..).le) + +theorem stack (a : Short (fun i => (A i).width)) : + Row (fun i => (Format.vec (N i).scheme.h (A i)).width) := + (h.layer a.block).mono (fun _ => (Format.width_vec ..).le) + +theorem bank (a : Row (fun i => (A i).width)) : + Cost (fun i => (Fmt.bank (N i).scheme.m (N i).scheme.d (A i)).width) := + h.vector (Width.pack (Long.row (Width.vec h.neighbors.long (Width.addr h.address))) a) + +theorem attached {Z : (i : I) → Attachment (N i)} (a : Short (fun i => (Z i).ℓ)) : + Cost (fun i => (Z i).format.width) := + Width.pack h.format (h.vector (h.stack (Width.addr a))) + +end Child +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case +end + +/- +# Uniform sorting prices over extensions of the ground field + +Choose the exponent of the width threshold before the extension +field is chosen. Mapping a permutation tensor to the extension +preserves its cost and all its zero-one entries. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Prices +open Filter + +variable {F : Type} [Field F] + +/-- Builds `Prices K where w` with the specified `power`, `tag`, `obtain`. -/ +def extend (p : Prices F) (K : Type) [Field K] [Algebra F K] : Prices K where + w := p.w + power := p.power + W := p.W + tag j v hj hw hv := by + obtain ⟨m, hm, ht⟩ := p.tag j v hj hw hv + exact ⟨m, hm, Assembly.tag_map ht⟩ + +private theorem pad (h A : ℕ) (hh : 16 ≤ h) : + 16 * h + (16 * h) ^ A ≤ h ^ (2 * (A + 1) + 1) := by + have ha : 16 * h ≤ h ^ 2 := by rw [pow_two]; gcongr + have hb : h ^ 2 ≤ h ^ (2 * (A + 1)) := Nat.pow_le_pow_right (by omega) (by omega) + have hc : (16 * h) ^ A ≤ h ^ (2 * (A + 1)) := calc + _ ≤ (h ^ 2) ^ A := Nat.pow_le_pow_left ha _ + _ ≤ _ := by rw [← pow_mul]; exact Nat.pow_le_pow_right (by omega) (by omega) + calc + _ ≤ h ^ (2 * (A + 1)) + h ^ (2 * (A + 1)) := Nat.add_le_add (ha.trans hb) hc + _ ≤ _ := by rw [pow_succ, ← mul_two]; gcongr; omega + +theorem eventual (wide : Radix.WideTag F) {τ : ℝ} (hτ : 0 < τ) : + ∃ R : ℕ, ∀ᶠ n : ℕ in atTop, + let h := Nat.clog 2 n + ∀ (K : Type) [Field K] [Algebra F K], ∃ p : Prices K, + p.w = 16 * h ∧ p.w + p.w ^ p.power ≤ h ^ R ∧ (p.W : ℝ) ≤ (h : ℝ) ^ τ := by + obtain ⟨A, C, hC, h⟩ := Assembly.wide_cost wide (half_pos hτ) + refine ⟨2 * (A + 1) + 1, ?_⟩ + have grows := (tendsto_rpow_atTop (half_pos hτ)).comp Shaving.tendsto_height + filter_upwards [Shaving.tendsto_height.eventually_ge_atTop 16, + grows.eventually_ge_atTop (C * (16 : ℝ) ^ (τ / 2) + 1)] with n hn hg + intro t K _ _ + let p : Prices F := ⟨16 * t, A, ⌈C * ((16 * t : ℕ) : ℝ) ^ (τ / 2)⌉₊, h (16 * t)⟩ + have ht : 16 ≤ t := by exact_mod_cast hn + refine ⟨p.extend K, rfl, pad t A ht, ?_⟩ + have hn' : 1 ≤ (t : ℝ) := by exact_mod_cast (show 1 ≤ t by omega) + calc + _ ≤ C * ((16 * t : ℕ) : ℝ) ^ (τ / 2) + 1 := (Nat.ceil_lt_add_one (by positivity)).le + _ ≤ (C * (16 : ℝ) ^ (τ / 2) + 1) * (t : ℝ) ^ (τ / 2) := by + rw [Nat.cast_mul, Nat.cast_ofNat, Real.mul_rpow (by norm_num) (by positivity), + add_mul, one_mul, mul_assoc] + exact add_le_add_right (Real.one_le_rpow hn' (half_pos hτ).le) _ + _ ≤ (t : ℝ) ^ (τ / 2) * (t : ℝ) ^ (τ / 2) := mul_le_mul_of_nonneg_right hg (by positivity) + _ = _ := by rw [← Real.rpow_add (by positivity), add_halves] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Prices +end + +/- # The two elementary operations on an attached core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Packing + +/-- The condition `∀ (P : Gadget k) Δ, 3 ≤ Δ → ∃ K, 0 < K ∧ Phase k Δ (Δ ^ degreePower) P.b +degreePower K P.ratio 1` on the specified data. -/ +def SubroundRule (k : Type) [Field k] : Prop := + ∀ (P : Gadget k) Δ, 3 ≤ Δ → ∃ K, 0 < K ∧ Phase k Δ (Δ ^ degreePower) P.b degreePower K P.ratio 1 + +/-- The reset rule of type `Prop` for the given inputs. -/ +def ResetRule (k : Type) [Field k] : Prop := + ∀ (y w Δ : ℕ) (R : Rotor k (2 ^ y) w) (c : ℝ), 0 < w → 3 ≤ Δ → 4 * coreBins Δ ≤ 2 ^ y → + 1 ≤ c → (Fintype.card R.E : ℝ) ≤ c * (2 : ℝ) ^ y * w → + ∃ K, 0 < K ∧ Phase k Δ 3 1 (900 + 2 ^ y + 1) K (2 * resetWidth c w) (2 * resetWidth c w) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Interface to a fixed number of reductions on an attached core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction + +open Assembly +variable {F : Type} [Field F] {x y : Wire} {T Y : Template F} + +/-- The data for the growth construction, including `height`, `lower`, `upper`, `degree`, +`full`. -/ +structure Growth (A : Attachment T) (A' : Attachment Y) (r z payload n K H : ℕ) : Prop where + height : Y.scheme.h + n * r = T.scheme.h + lower : T.scheme.m ≤ Y.scheme.m + upper : Y.scheme.m ≤ T.scheme.m + n * r + K + degree : Y.scheme.d ≤ H + full : Y.full = true + single : Y.scheme.k = 0 + spans : 2 ^ Y.scheme.e ≤ H + stations : A'.k ≤ A.k + n * r + K + outer : 2 ^ A'.e ≤ 2 ^ A.e + H + counters : Y.count ≤ (base A r z payload) ^ H + labels : Y.scheme.ℓ + A'.ℓ ≤ H * (T.scheme.ℓ + A.ℓ) + (base A r z payload) ^ H + +variable (A : Attachment T) (L : BorderLimit F x y) + +/-- The quantity computed by `{after L P K ρ c σ with mass := P.mass + 2 * K * (P.width + +(L.total + σ))}`. -/ +def limit (P : Bound) (K : ℕ) (ρ c σ : ℝ) : Bound := + {after L P K ρ c σ with mass := P.mass + 2 * K * (P.width + (L.total + σ))} + +/-- The data for the start construction, including `nonneg`, `height`, `space`, `reserve`. -/ +structure Start (P : Bound) (p : Prices F) (r b u v z payload d B n K H : ℕ) (σ : ℝ) : Prop + extends Input A L P p r b u v z payload d B K H σ where + nonneg : 0 ≤ σ + height : n * r ≤ T.scheme.h + space : 2 * (T.scheme.m + n * r + K) ≤ p.w + reserve : P.mass + 2 * K * (P.width + (L.total + σ)) ≤ L.cap + +/-- The data for the stop construction, including `next`, `pack`, `growth`, `keys`, `few`. -/ +structure Stop (P : Bound) (p : Prices F) (r u v z payload Δ Δ' C C' n K H : ℕ) + (ρ c σ : ℝ) where + /-- The successor of each choice of type `Template F`. -/ + next : Template F + /-- The `Stop` component of type `Attachment next`. -/ + pack : Attachment next + growth : Growth A pack r z payload n K H + /-- The `Stop` component of type `Finset (Table F)`. -/ + keys : Finset (Table F) + few : keys.card ≤ (short A r z payload) ^ H + transfer : Transforms F ((short A r z payload) ^ H) keys + (frame A L u z payload Δ C P) (frame pack L v z payload Δ' C' (limit L P K ρ c σ)) + (size (x := x) (y := y) A p r z payload H) + +/-- The data for the block construction, including `unit`, `steps`, `overhead`, `degree`, +`factor`. -/ +structure Block (k : Type) [Field k] (Δ Δ' b n e K : ℕ) (ρ c : ℝ) : Prop where + unit : 0 < b + steps : 0 < n + overhead : 0 < K + degree : ∀ C, Δ ≤ C → Δ' ≤ C ^ e + factor : 0 ≤ ρ + loss : 0 ≤ c + run : ∀ C d B, Δ ≤ C → ∃ H, 0 < H ∧ ∀ (F : Type) [Field F] [Fintype F] [Algebra k F] + {x y : Wire} {T : Template F} (A : Attachment T) (L : BorderLimit F x y) + (P : Bound) (p : Prices F) (r u v z payload : ℕ) (σ : ℝ), + Start A L P p r b u v z payload d B n K H σ → + Nonempty (Stop A L P p r u v z payload Δ Δ' C (C ^ e) n K H ρ c σ) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +section +/- # Growth of the control parameters in one contraction -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Growth +open Assembly + +/-- The quantity computed by `n + K + 2 * H + 100`. -/ +def rate (n K H : ℕ) := n + K + 2 * H + 100 + +variable {F : Type} {T Y : Template F} {A : Attachment T} {A' : Attachment Y} + {r z payload n K H : ℕ} (g : Growth A A' r z payload n K H) + +private theorem height_le_pow {X : ℕ} (h : 2 ≤ X) (k : ℕ) : k ≤ X ^ k := + (Nat.lt_two_pow_self (n := k)).le.trans (Nat.pow_le_pow_left h _) + +include g in +private theorem base_bound : + base A' r z payload ≤ 8 * (base A r z payload) ^ (n + K + H + 1) := by + let X := base A r z payload + let C := X ^ (n + K + H + 1) + have hx : X = 100 + 2 ^ r + T.scheme.h + Nat.clog 2 (1 + z) + 2 ^ A.k + 2 ^ A.e + + 2 ^ T.scheme.e + payload + Nat.clog 2 (1 + T.scheme.ℓ + A.ℓ) := rfl + have := Nat.two_pow_pos r + have := Nat.two_pow_pos A.k + have := Nat.two_pow_pos A.e + have := Nat.two_pow_pos T.scheme.e + have h2 : 2 ≤ X := by omega + have hX : X ≤ C := Nat.le_pow (by omega) + have hc : X ^ H ≤ C := Nat.pow_le_pow_right (by omega) (by omega) + have hH := (height_le_pow h2 H).trans hc + have hl : 1 + Y.scheme.ℓ + A'.ℓ ≤ (1 + T.scheme.ℓ + A.ℓ) * (C + 1) := by + have h := g.labels + change _ ≤ _ + X ^ H at h + have ht := Nat.mul_le_mul_right (T.scheme.ℓ + A.ℓ) hH + nlinarith only [h, ht, hc] + have hlog : Nat.clog 2 (1 + Y.scheme.ℓ + A'.ℓ) ≤ X + C := by + apply Nat.clog_le_of_le_pow + rw [pow_add] + apply hl.trans + apply Nat.mul_le_mul + · exact (Nat.le_pow_clog (by decide : 1 < 2) _).trans (Nat.pow_le_pow_right (by decide) (by + omega)) + · exact Nat.lt_two_pow_self + have hs : 2 ^ A'.k ≤ C := calc + _ ≤ 2 ^ (A.k + n * r + K) := Nat.pow_le_pow_right (by decide) g.stations + _ = 2 ^ A.k * (2 ^ r) ^ n * 2 ^ K := by rw [pow_add, pow_add, mul_comm n, pow_mul] + _ ≤ X * X ^ n * X ^ K := by gcongr <;> omega + _ ≤ _ := by rw [← pow_succ', ← pow_add]; exact Nat.pow_le_pow_right (by omega) (by omega) + have := g.height + have := g.outer + have := g.spans + change base A' r z payload ≤ 8 * C + unfold base + omega + +include g in +theorem base_le : base A' r z payload ≤ (base A r z payload) ^ (rate n K H) := by + let X := base A r z payload + have hx : 100 ≤ X := by unfold X base; grind + apply g.base_bound.trans + calc + _ ≤ X * X ^ (n + K + H + 1) := Nat.mul_le_mul_right _ (by omega) + _ ≤ _ := by rw [← pow_succ']; exact Nat.pow_le_pow_right (by omega) (by unfold rate; omega) + +include g in +theorem short_le : short A' r z payload ≤ (short A r z payload) ^ (rate n K H) := by + let X := short A r z payload + let C := X ^ (n + K + H + 1) + have hx : 100 ≤ X := by unfold X short base; grind + have hB : base A r z payload ≤ X := by unfold X short; omega + have hL : T.scheme.ℓ + A.ℓ ≤ X := by unfold X short; omega + have hc : X ^ H ≤ C := Nat.pow_le_pow_right (by omega) (by omega) + have hp := (Nat.pow_le_pow_left hB H).trans hc + have hH := (height_le_pow (by omega : 2 ≤ X) H).trans hc + have ht : base A' r z payload ≤ 8 * C := + g.base_bound.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hB _)) + have hl := g.labels.trans (Nat.add_le_add (Nat.mul_le_mul hH hL) hp) + have hcnt := g.counters.trans hp + calc + _ ≤ 10 * C + C * X := by unfold short; omega + _ ≤ C * X ^ 2 := by + rw [mul_comm 10, ← mul_add] + exact Nat.mul_le_mul_left _ (by nlinarith only [hx]) + _ ≤ _ := by + unfold C + rw [← pow_add] + exact Nat.pow_le_pow_right (by omega) (by unfold rate; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Growth +end + +/- +# Composing quantitative bounds for attached contractions + +Growth of the host count is controlled by the number of block +coordinates consumed in the phase. For local work the bound stays +polynomial in the short records without the global address length. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Growth +open Assembly + +variable {F : Type} {x y : Wire} {T Y Z : Template F} + {A : Attachment T} {A' : Attachment Y} {A'' : Attachment Z} + {r z payload n K H n' K' H' : ℕ} + +/-- The quantity computed by `rate n K H * (J + 1) + J + H + 2`. -/ +def join (n K H J : ℕ) := rate n K H * (J + 1) + J + H + 2 + +theorem add_le (n K H J : ℕ) : H + J ≤ join n K H J := by unfold join; omega + +private theorem absorb {X u v k : ℕ} (h : 2 ≤ X) (hu : u < k) (hv : v < k) : + X ^ u + X ^ v ≤ X ^ k := by + have hp : 0 < X := by omega + calc + _ ≤ X ^ (k - 1) + X ^ (k - 1) := Nat.add_le_add + (Nat.pow_le_pow_right hp (by omega)) (Nat.pow_le_pow_right hp (by omega)) + _ = X ^ (k - 1) * 2 := by omega + _ ≤ X ^ (k - 1) * X := Nat.mul_le_mul_left _ h + _ = _ := by rw [← pow_succ, Nat.sub_add_cancel (by omega)] + +private theorem first (n K H J : ℕ) : H < join n K H J := by unfold join; omega + +private theorem second (n K H J : ℕ) : + rate n K H + (rate n K H + 1) * J < join n K H J := by + simp only [join, add_mul, mul_add, mul_one, one_mul] + omega + +private theorem raised {X k : ℕ} (h : 2 ≤ X) : k ≤ X ^ k := + Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left h k) + +private theorem base_room (A : Attachment T) (r z payload : ℕ) : + 2 ≤ base A r z payload ∧ 2 ^ r ≤ base A r z payload := by + unfold base + have hk := Nat.two_pow_pos A.k + have hr := Nat.two_pow_pos r + have he := Nat.two_pow_pos A.e + have hd := Nat.two_pow_pos T.scheme.e + omega + +private theorem short_room (A : Attachment T) (r z payload : ℕ) : + 2 ≤ short A r z payload ∧ 2 ^ r ≤ short A r z payload := by + have := base_room A r z payload + unfold short + omega + +theorem keys (g : Growth A A' r z payload n K H) (J : ℕ) : + (short A r z payload) ^ H + (short A' r z payload) ^ J ≤ (short A r z payload) ^ (join n K H J) + := by + refine (Nat.add_le_add_left (Nat.pow_le_pow_left g.short_le J) _).trans ?_ + rw [← pow_mul] + apply absorb (short_room A r z payload).1 (first ..) + unfold join + rw [mul_add] + omega + +theorem comp (g : Growth A A' r z payload n K H) (g' : Growth A' A'' r z payload n' K' H') : + Growth A A'' r z payload (n + n') (K + K') (join n K H H') := by + let X := base A r z payload + let j := join n K H H' + let p := rate n K H + have hp : 2 ≤ X := (base_room A r z payload).1 + have ht : H + H' < j := by unfold j join; omega + have hu : p * H' < j := by unfold j join p; rw [mul_add]; omega + have hv : H' * H ≤ j := by + have : H ≤ p := by unfold p rate; omega + exact (Nat.mul_le_mul_left H' this).trans ((mul_comm H' p).trans_le hu.le) + have hm : (base A' r z payload) ^ H' ≤ X ^ (p * H') := by + rw [pow_mul] + exact Nat.pow_le_pow_left g.base_le H' + refine ⟨?_, g.lower.trans g'.lower, ?_, g'.degree.trans (by omega), g'.full, g'.single, + g'.spans.trans (by omega), ?_, ?_, g'.counters.trans + (hm.trans (Nat.pow_le_pow_right (by omega) hu.le)), ?_⟩ + · have := g.height; have := g'.height; rw [add_mul]; omega + · have := g.upper; have := g'.upper; rw [add_mul]; omega + · have := g.stations; have := g'.stations; rw [add_mul]; omega + · have := g.outer; have := g'.outer; omega + · calc + _ ≤ H' * (H * (T.scheme.ℓ + A.ℓ) + X ^ H) + X ^ (p * H') := + g'.labels.trans (Nat.add_le_add (Nat.mul_le_mul_left _ g.labels) hm) + _ = (H' * H) * (T.scheme.ℓ + A.ℓ) + (H' * X ^ H + X ^ (p * H')) := by ring + _ ≤ j * (T.scheme.ℓ + A.ℓ) + (X ^ (H + H') + X ^ (p * H')) := by + rw [pow_add, mul_comm (X ^ H)] + exact Nat.add_le_add (Nat.mul_le_mul_right _ hv) + (Nat.add_le_add_right (Nat.mul_le_mul_right _ (raised hp)) _) + _ ≤ _ := Nat.add_le_add_left (absorb hp ht hu) _ + +private theorem sum_pow {X C j : ℕ} (hX : 2 ≤ X) (hj : 0 < j) : + X ^ j + C ≤ (X + C) ^ (j + 1) := + (Nat.add_le_add (Nat.pow_le_pow_left (by omega) _) (show C ≤ (X + C) ^ 1 by simp)).trans + (absorb (by omega) (by omega) (by omega)) + +private theorem site_count {a b X : ℕ} (h : b ≤ a + n * r + K) (hX : 2 ≤ X) (hr : 2 ^ r ≤ X) : + 2 ^ b ≤ 2 ^ a * X ^ (rate n K H) := by + calc + _ ≤ 2 ^ (a + n * r + K) := Nat.pow_le_pow_right (by decide) h + _ = 2 ^ a * ((2 ^ r) ^ n * 2 ^ K) := by rw [pow_add, pow_add, mul_comm n, pow_mul, mul_assoc] + _ ≤ 2 ^ a * (X ^ n * X ^ K) := by gcongr + _ ≤ _ := by + rw [← pow_add] + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) (by unfold rate; omega)) + +private theorem pair_cost (g : Growth A A' r z payload n K H) (C J : ℕ) {a b : ℕ} + (hab : b ≤ a + n * r + K) : + 2 ^ a * (short A r z payload + C) ^ H + 2 ^ b * (short A' r z payload + C) ^ J ≤ + 2 ^ a * (short A r z payload + C) ^ (join n K H J) := by + let X := short A r z payload + C + let p := rate n K H + obtain ⟨hh, ht⟩ := short_room A r z payload + have hu : 2 ≤ X := by omega + have hb : 2 ^ b ≤ 2 ^ a * X ^ p := site_count hab hu (by omega) + have hs : short A' r z payload + C ≤ X ^ (p + 1) := + (Nat.add_le_add_right g.short_le _).trans (sum_pow hh (by unfold rate; omega)) + calc + _ ≤ 2 ^ a * X ^ H + (2 ^ a * X ^ p) * (X ^ (p + 1)) ^ J := + Nat.add_le_add_left (Nat.mul_le_mul hb (Nat.pow_le_pow_left hs J)) _ + _ = 2 ^ a * (X ^ H + X ^ (p + (p + 1) * J)) := by + rw [mul_add, pow_add X p ((p + 1) * J), pow_mul, mul_assoc] + _ ≤ _ := Nat.mul_le_mul_left _ (absorb hu (first ..) (second ..)) + +theorem cost [Field F] (g : Growth A A' r z payload n K H) (J : ℕ) (p : Prices F) : + size (x := x) (y := y) A p r z payload H + size (x := x) (y := y) A' p r z payload J ≤ + size (x := x) (y := y) A p r z payload (join n K H J) := by + let C := 100 + p.w + p.w ^ p.power + p.W + let X := 100 + payload + p.W + have ha := pair_cost g C J g.upper + have hb := pair_cost g p.W J (a := T.scheme.m + T.scheme.h) (b := Y.scheme.m + Y.scheme.h) + (by have := g.height; have := g.upper; omega) + have ht := absorb (show 2 ≤ X by omega) (first n K H J) + (show J < join n K H J by unfold join; omega) + have hc := Nat.mul_le_mul_left (wd x + wd y) ht + rw [mul_add] at hc + rw [add_comm (short A r z payload) C, add_comm (short A' r z payload) C] at ha + dsimp only [X, C] at hc ha + dsimp only [size] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Growth +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Beat/Select.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Beat/Select.lean new file mode 100644 index 0000000000..3f2497c817 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Beat/Select.lean @@ -0,0 +1,962 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.HeaderCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Reset.Label +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Pass + +/-! # Shared parameters of a contraction with its border attached -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Assembly.History + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} + (Q : Gadget F) (A : Attachment T) (L : BorderLimit F x y) + (v : ℕ) (hv : 0 < v) (z Δ C B r : ℕ) + +open scoped Classical in +/-- Uses `BatchDescent.Beat.k Δ` as the representation. -/ +abbrev k := BatchDescent.Beat.k Δ +open scoped Classical in +/-- Uses `BatchDescent.Beat.b Q` as the representation. -/ +abbrev b := BatchDescent.Beat.b Q +open scoped Classical in +/-- Uses `BatchDescent.Beat.gain Δ` as the representation. -/ +abbrev gain := BatchDescent.Beat.gain Δ +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def e := Nat.clog 2 (gain Δ * B) +open scoped Classical in +/-- The quantity computed by `B * gain Δ * B`. -/ +def copies := B * gain Δ * B +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def c := Nat.clog 2 (copies Δ B * z + 1) + +open scoped Classical in +/-- The quantity computed by `Template.Meter.bounded (c z Δ B) (1 / (L.denom : ℝ)) (1 / (2 : ℝ) +^ L.discount)`. -/ +abbrev meter := Template.Meter.bounded (c z Δ B) (1 / (L.denom : ℝ)) (1 / (2 : ℝ) ^ L.discount) + +open scoped Classical in +/-- The quantity computed by `Book.make T.scheme Q v hv T.order (Finset.range (B * z + 1))`. -/ +abbrev book (Q : Gadget F) (_A : Attachment T) (v : ℕ) (hv : 0 < v) (z B : ℕ) := + Book.make T.scheme Q v hv T.order (Finset.range (B * z + 1)) +open scoped Classical in +/-- The quantity computed by `(book Q A v hv z B).overhead (e Δ B) + 2 ^ (e Δ B) * T.scheme.ℓ`. -/ +abbrev cap := (book Q A v hv z B).overhead (e Δ B) + 2 ^ (e Δ B) * T.scheme.ℓ +open scoped Classical in +/-- The quantity computed by `T.after (T.scheme.h - r) Δ C (book Q A v hv z B) (e Δ B) (cap Q A +v hv z Δ B) (meter L z Δ B)`. -/ +abbrev raw := T.after (T.scheme.h - r) Δ C (book Q A v hv z B) (e Δ B) + (cap Q A v hv z Δ B) (meter L z Δ B) +open scoped Classical in +/-- The value specified by `(raw Q A L v hv z Δ C B r).sweep`. -/ +abbrev next := (raw Q A L v hv z Δ C B r).sweep +open scoped Classical in +/-- The quantity computed by `T.scheme.h - (T.scheme.h - r) + A.k`. -/ +abbrev slots := T.scheme.h - (T.scheme.h - r) + A.k +open scoped Classical in +/-- The value specified by `A.transport (next Q A L v hv z Δ C B r) (slots A r)`. -/ +abbrev out := A.transport (next Q A L v hv z Δ C B r) (slots A r) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Separating short metadata costs from wide exterior transfers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Assembly.History Coloring +variable {F : Type} [Field F] {x y : Wire} {T : Template F} + (Q : Gadget F) (A : Attachment T) (L : BorderLimit F x y) + (v : ℕ) (hv : 0 < v) (z Δ C B r : ℕ) (p : Prices F) + +local notation "a" => (T.scheme.h - r) +local notation "n" => (T.scheme.h - a) +local notation "m" => T.scheme.m +local notation "d" => T.scheme.d +local notation "Y" => next Q A L v hv z Δ C B r +local notation "M" => book Q A v hv z B +local notation "𝓔" => e Δ B +local notation "𝓒" => cap Q A v hv z Δ B +local notation "𝓚" => meter L z Δ B +local notation "q" => ((d + 1) * n) + +open scoped Classical in +/-- The value specified by `A.shrink Y (slots A r) (copies Δ B)`. -/ +abbrev target := A.shrink Y (slots A r) (copies Δ B) +open scoped Classical in +/-- Computes the input by the application `A.format.pair (T.Candidate a (b Q))`. -/ +abbrev input := A.format.pair (T.Candidate a (b Q)) +open scoped Classical in +/-- The value specified by `A.format.pair (T.Headed a (b Q) Δ C)`. -/ +abbrev headed := A.format.pair (T.Headed a (b Q) Δ C) +open scoped Classical in +/-- The quantity computed by `A.Requests Y (slots A r) (d + 1)`. -/ +abbrev requests := A.Requests Y (slots A r) (d + 1) +open scoped Classical in +/-- The construction uses `T.scheme.h - r` for its intermediate `g`. -/ +def precision (T : Template F) (Δ C r : ℕ) := + let g := T.scheme.h - r + T.size g + 2 ^ (Window.Tile.radius T.scheme.d + (T.scheme.h - g + 1)) + 2 ^ (T.degree g Δ C) + +open scoped Classical in +/-- The construction uses `T.scheme.h - r` for its intermediate `g`. -/ +def prepareCost (Q : Gadget F) (T : Template F) (r : ℕ) (p : Prices F) := + let g := T.scheme.h - r + let u := BatchDescent.Beat.parcel T r + let v := BatchDescent.Beat.labels T r + T.prepareCost g (b Q) u (p.fee (T.scheme.m + (T.scheme.d + 1) * (T.scheme.h - g)) u) + v (p.fee (T.scheme.m + T.scheme.d) v) + +open scoped Classical in +/-- The bound obtained by adding the component charges `1000 * ((input Q A r).width + (headed Q +A Δ C r).width) + prepareCost Q T r p + T.headedCost a (b Q) Δ C (BatchDescent.Beat.profile +Q)`. -/ +def firstCost := 1000 * ((input Q A r).width + (headed Q A Δ C r).width) + + prepareCost Q T r p + T.headedCost a (b Q) Δ C (BatchDescent.Beat.profile Q) +open scoped Classical in +/-- The bound obtained by adding the component charges `let t := BatchDescent.Beat.walk Q T r +A.groupedCost a (b Q) Δ C M 𝓔 𝓒 𝓚 t (p.fee (m + d) t) (precision T Δ C r)`. -/ +def secondCost := + let t := BatchDescent.Beat.walk Q T r + A.groupedCost a (b Q) Δ C M 𝓔 𝓒 𝓚 t (p.fee (m + d) t) (precision T Δ C r) +open scoped Classical in +/-- The construction uses `2 ^ d * m + 2 ^ T.scheme.h * A.ℓ` for its intermediate `u`. -/ +def rebuildCost := + let u := 2 ^ d * m + 2 ^ T.scheme.h * A.ℓ + let t := (Attachment.Inspect.Packet m d (d + 1) a (A.bundle Y (slots A r) (d + 1))).width + A.rebuildCost Y (slots A r) (d + 1) u (p.fee (m + d) u) t (p.fee ((Y).scheme.m + (Y).scheme.d) t) + +open scoped Classical in +/-- The value specified by `T.issueWidth a (b Q) Δ C M 𝓔 𝓒 𝓚 (A.Supplement a 𝓔)`. -/ +def issueWidth := T.issueWidth a (b Q) Δ C M 𝓔 𝓒 𝓚 (A.Supplement a 𝓔) +open scoped Classical in +/-- The arity used in the `Beat` construction. -/ +def arity := T.arity a (b Q) + BatchDescent.Beat.markWidth Q T r + + issueWidth Q A L v hv z Δ C B r + 2 * (Y).scheme.ℓ + A.rebuildWidth Y (slots A r) (d + 1) +open scoped Classical in +/-- The quantity computed by `(d + 1) * n + T.degree a Δ C + n + 1`. -/ +def range := (d + 1) * n + T.degree a Δ C + n + 1 + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Grouping and matching with a retained border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + +local notation "a" => (T.scheme.h - r) +local notation "X" => frame A L (Q.b * v) z payload Δ C P + +include h in +open scoped Classical in +theorem pos : 0 < v := h.zpos.trans_le h.vpos + +include h in +open scoped Classical in +theorem cost_pos : 0 < P.load := + (Nat.cast_pos.mpr (Nat.mul_pos Q.pos (pos h))).trans_le h.load + +include h in +open scoped Classical in +theorem slack_pos : 0 ≤ σ := by + have := cost_pos h + exact nonneg_of_mul_nonneg_left (le_trans (by positivity) h.slack) (by positivity) + +include h in +open scoped Classical in +theorem enough (hK : 2 ^ (k Δ) ≤ K) : k Δ ≤ T.scheme.h - a := by + rw [Nat.sub_sub_self h.group] + exact (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp (hK.trans h.room) + +include h in +open scoped Classical in +theorem slack (hK : 2 ^ (k Δ) ≤ K) (v : ℕ) (hv : v ≤ 2 ^ T.scheme.m) : + (2 : ℝ) ^ (k Δ) * P.load * (v * 2 ^ a : ℕ) ≤ σ := by + exact BatchDescent.slack_of_width_count (cost_pos h).le h.group hK hv h.slack + +variable (q : (frame A L (Q.b * v) z payload Δ C P).state) + +open scoped Classical in +/-- The value specified by `T.Selection a (Nat.sub_le _ _) (b Q) (k Δ) P.load Δ C q.val.q.core σ +(Nat.mul_pos Q.pos (pos h))`. -/ +abbrev Poll := T.Selection a (Nat.sub_le _ _) (b Q) (k Δ) P.load Δ C q.val.q.core σ + (Nat.mul_pos Q.pos (pos h)) + +open scoped Classical in +theorem elect (hd : 0 < Δ) (hc : Δ ≤ C) (hk : 2 ^ (k Δ) ≤ K) : Nonempty (Poll h q) := by + have hv : Fintype.card q.val.G.V ≤ 2 ^ T.scheme.m := by + simpa using Fintype.card_le_of_injective _ q.val.q.core.post.host.injective + exact T.selection a (Nat.sub_le _ _) (b Q) (k Δ) P.load Δ C q.val.q.core σ _ + hd (hd.trans_le hc) (BatchDescent.Beat.positive Δ) (enough h hk) + (cost_pos h) q.property.1.bounded (BatchDescent.Beat.bins Δ) (slack h hk _ hv) (by simp + [h.full]) + +open scoped Classical in +/-- The value specified by `T.Branch Q a (Nat.sub_le _ _) (b Q) (k Δ) P.load Δ C v σ +(Nat.mul_pos Q.pos (pos h))`. -/ +abbrev Ticket := T.Branch Q a (Nat.sub_le _ _) (b Q) (k Δ) P.load Δ C v σ (Nat.mul_pos Q.pos (pos + h)) + +open scoped Classical in +/-- The ticket of type `Ticket (Δ := Δ) (C := C) h where T` for the given inputs. -/ +def ticket (s : Poll h q) (i : s.choices) : Ticket (Δ := Δ) (C := C) h where + T := q.val.T + x := q.val.a + y := q.val.b + L := q.val.L + G := q.val.G + r := q.val.raw.1 + p := q.val.q.core + s := s + i := i + v := ((Classical.choice q.property.1.live, 0), ⟨0, 0⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Core budgets for a contraction with a retained border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + (q : (frame A L (Q.b * v) z payload Δ C P).state) (s : Poll h q) (i : s.choices) + (hd : 0 < Δ) (hc : Δ ≤ C) + +local notation "hb" => BatchDescent.Beat.choices Q +local notation "G" => Template.Branch.layout (ticket h q s i) hc +local notation "St" => Template.Branch.state (ticket h q s i) hb +local notation "M" => book Q A v (pos h) z B + +include hd in +open scoped Classical in +theorem estimates : + (G).Bounded ((4 * Δ) ^ 900) ((4 * C) ^ 900) (gain Δ * P.load) ∧ + ((G).X : ℝ) ≤ Q.ratio * P.width + (L.total + σ) ∧ + q.val.G.Preserves G ∧ ((G).mass : ℝ) ≤ P.mass + 2 * P.width := by + obtain ⟨bounds, width, preserve, mass, _⟩ := + (ticket h q s i).estimates hc hd (slack_pos h) (cost_pos h).le q.property.1.bounded + refine ⟨⟨bounds.1, bounds.2.1, ?_⟩, ?_, preserve, ?_⟩ + · intro u j + refine (bounds.2.2 u j).trans ?_ + simp only [gain, BatchDescent.Beat.gain, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, mul_assoc] + have := cost_pos h + gcongr; norm_num + · exact width.trans (add_le_add (mul_le_mul_of_nonneg_left q.property.1.width Q.ratio_bounds.1) + (add_le_add_left q.property.1.total _)) + · rw [mass, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat] + exact add_le_add q.property.1.mass (mul_le_mul_of_nonneg_left q.property.1.width (by norm_num)) + +include hd in +open scoped Classical in +theorem mass : (G).mass ≤ q.val.L.cap := by + rw [q.property.1.cap] + exact Nat.cast_le.mp ((estimates h q s i hd hc).2.2.2.trans h.history) + +include hd in +open scoped Classical in +theorem room : (St).Room (e Δ B) := by + apply (ticket h q s i).room hb hd (cost_pos h).le q.property.1.bounded _ q.property.1.span + have hh := Nat.le_pow_clog (by decide : 1 < 2) (gain Δ * B) + have hv : gain Δ * B * z ≤ 2 ^ (e Δ B) * v := Nat.mul_le_mul hh h.vpos + calc + _ = (gain Δ : ℝ) * P.load := by + simp only [gain, BatchDescent.Beat.gain, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat] + _ ≤ (gain Δ : ℝ) * (B * z) := mul_le_mul_of_nonneg_left h.ceiling (Nat.cast_nonneg _) + _ ≤ _ := by rw [← mul_assoc]; exact_mod_cast hv + +local notation "rm" => room h q s i hd + +open scoped Classical in +theorem ready : (ticket h q s i).Ready hb hc M rm (cap Q A v (pos h) z Δ B) := by + apply (ticket h q s i).direct hb hc hd M rm q.property.1.neutral + intro j + exact History.Book.represent T.scheme Q v (pos h) T.order (Finset.range (B * z + 1)) + (Finset.mem_range.mpr (Nat.lt_succ_of_le (size_bound h q j))) + +include hd in +open scoped Classical in +theorem valid : (meter L z Δ B).Valid G := + valid_of_charge h q (gain Δ) G (mass h q s i hd hc) (estimates h q s i hd hc).1.2.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # The core and frozen border of a selected contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + (q : (frame A L (Q.b * v) z payload Δ C P).state) (s : Poll h q) (i : s.choices) + (hd : 0 < Δ) (hc : Δ ≤ C) + +local notation "hb" => BatchDescent.Beat.choices Q +local notation "G" => Template.Branch.layout (ticket h q s i) hc +local notation "M" => book Q A v (pos h) z B +local notation "rm" => room h q s i hd +local notation "𝓚" => meter L z Δ B +local notation "𝓒" => cap Q A v (pos h) z Δ B +local notation "Y" => raw Q A L v (pos h) z Δ C B r +local notation "U" => out Q A L v (pos h) z Δ C B r + +open scoped Classical in +/-- Uses `A.query M 𝓒 𝓚 hb hc t rm q.val.raw.2` as the representation. -/ +abbrev query : A.Query Y (slots A r) (T.scheme.d + 1) := + A.query M 𝓒 𝓚 hb hc (ticket h q s i) rm q.val.raw.2 +open scoped Classical in +/-- The value specified by `(t).encodes hb hc M rm 𝓒 𝓚 hd (ready h q s i hd hc) (valid h q s i +hd hc)`. -/ +abbrev posted : (Y).Encodes (query h q s i hd hc).fresh G + := (ticket h q s i).encodes hb hc M rm 𝓒 𝓚 hd (ready h q s i hd hc) (valid h q s i hd hc) + +local notation "S" => query h q s i hd hc +local notation "E" => posted h q s i hd hc + +open scoped Classical in +theorem active : Attachment.Relocation.WriteActive E (S).active := by + intro x j + let selectedTicket := ticket h q s i + exact (selectedTicket.board hb).live_at M rm 𝓒 hc + (selectedTicket.s.canonical_live hb selectedTicket.i selectedTicket.v) x j + +open scoped Classical in +theorem moves : (S).R.Moves q.val.q E (A.newSlot (ticket h q s i) q.val.q.slot) := + A.grouped_moves (ticket h q s i) M _ 𝓒 𝓚 hc hb hd rm (ready h q s i hd hc) + (valid h q s i hd hc) q.val.q rfl + +open scoped Classical in +theorem agrees : (S).M.Agrees q.val.q.core.post.toPresentation (E).post.toPresentation := + (ticket h q s i).move_agrees hb hc M rm 𝓒 (ready h q s i hd hc) + +local notation "hm" => moves h q s i hd hc +local notation "ha" => active h q s i hd hc +local notation "hx" => agrees h q s i hd hc + +open scoped Classical in +/-- The value specified by `(S).apply hm ha hx (show (Y).full = true from h.full)`. -/ +def result := (S).apply hm ha hx (show (Y).full = true from h.full) + +open scoped Classical in +theorem fits : (result h q s i hd hc).Fits payload := (S).fits hm ha hx (show (Y).full + = true from h.full) q.property.2 + +open scoped Classical in +theorem spare : A.Sparse (Y).sweep (slots A r) (copies Δ B) (result h q s i hd hc).raw := by + obtain ⟨δ, hδ, hl, hb'⟩ := charges h q (gain Δ) G (estimates h q s i hd hc).1.2.2 + exact (S).spare hm ha hx (show (Y).full = true from h.full) hδ hl hb' + +open scoped Classical in +theorem exterior (l : MatrixExponent.slots x ⊕ MatrixExponent.slots y) : + let a := ((result h q s i hd hc).q.pres.boundary l).val + let b := (q.val.q.pres.boundary l).val + (S).sweep.R.kept q.val.raw a.1.1 = some b.1.1 ∧ a.1.2 = A.outer (Y).sweep b.1.2 ∧ a.2.val + = b.2.val := + (S).exterior hm ha hx (show (Y).full = true from h.full) l + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Retaining the entire original frame during selector validation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + +local notation "a" => (T.scheme.h - r) +local notation "n" => (T.scheme.h - a) +local notation "X" => frame A L (Q.b * v) z payload Δ C P +local notation "Z" => T.Candidate a (b Q) +local notation "D" => Attachment.payload x y payload T.scheme.m +local notation "Mid" => Format.pair (headed Q A Δ C r) D +local notation "Pr" => BatchDescent.Beat.profile Q + +variable (hd : 0 < Δ) (hc : Δ ≤ C) (hk : 2 ^ (k Δ) ≤ K) + (hs : range (T := T) Δ C r ≤ T.scheme.m) + +include h hk hs in +open scoped Classical in +theorem address (j : ℕ) (lo : T.scheme.m ≤ j) (hi : j ≤ T.scheme.m + range (T := T) Δ C r) : + 1 ≤ j ∧ j ≤ p.w := by + have hh := h.upper + have := (BatchDescent.Beat.positive Δ).trans (enough h hk) + unfold range at * + omega + +variable (s : ∀ q : (frame A L (Q.b * v) z payload Δ C P).state, Poll h q) + +open scoped Classical in +/-- The start of type `(Mid).obj` for the given inputs. -/ +def start (i : (X).state) (l : (Z).obj) (u : Val x) (w : Val y) : (Mid).obj := + ((i.val.raw, T.headed a (Nat.sub_le ..) (b Q) Δ C Q + (T.prepared a (Nat.sub_le ..) (b Q) (k Δ) P.load Δ C (i.val.raw.1, l))), + i.val.data i.property.2 u w) + +include hk hs in +open scoped Classical in +theorem first {u : ℕ} {W : Set (Table F)} (hu : 3 ≤ u) + (fit : arity Q A L v (pos h) z Δ C B r ≤ u) + (keys : (T.keys a (b Q) (k Δ) P.load Δ C : Set _) ⊆ W) (mark : T.markTable a (b Q) ∈ W) : + Computes F u W ((X).port.pair Z) Mid + (fun t : ((X).state × (Z).obj) × Val x × Val y => ((X).encode t.1.1 t.2.1 t.2.2, t.1.2)) + (fun t => start (Q := Q) (r := r) t.1.1 t.1.2 t.2.1 t.2.2) + (fun t => if (((s t.1.1).selector (BatchDescent.Beat.choices Q)).read t.1.2).isSome then 1 + else 0) + (firstCost Q A Δ C r p + 200 * (D).width) := by + let A₀ := (A.port x y payload).pair Z + let A₁ := (T.format.pair (A.port x y payload)).pair Z + let A₂ := (T.Headed a (b Q) Δ C).pair (T.scheme.format.pair (A.port x y payload)) + let I := ((X).state × (Z).obj) × Val x × Val y + let load : A₀.obj → A₁.obj := fun x => ((x.1.1.1, x.1), x.2) + let save : A₂.obj → (Mid).obj := fun x => ((x.2.2.1, x.1), x.2.2.2) + have hload : Circuit F A₀ A₁ load (A₀.width + 2 * A₁.width) := + Circuit.project (Sum.elim (Sum.elim (Sum.inl ∘ Sum.inl ∘ Sum.inl) Sum.inl) Sum.inr) + (by rintro x ((i|i)|i) <;> rfl) + have hsave : Circuit F A₂ Mid save (A₂.width + 2 * (Mid).width) := + Circuit.project (Sum.elim (Sum.elim (Sum.inr ∘ Sum.inr ∘ Sum.inl) Sum.inl) (Sum.inr ∘ Sum.inr ∘ + Sum.inr)) + (by rintro x ((i|i)|i) <;> rfl) + let E (t : I) : A₀.obj := ((X).encode t.1.1 t.2.1 t.2.2, t.1.2) + have h₁ := Computes.of_map (L := W) (x := E) (Map.circuit hu hload) (fun _ => rfl) + have hpos := (BatchDescent.Beat.positive Δ).trans (enough h hk) + have hb := address h hk hs (T.scheme.m + (T.scheme.d + + 1) * n) (Nat.le_add_right ..) (by unfold range; omega) + have hj : T.scheme.m + T.scheme.d ≤ T.scheme.m + (T.scheme.d + 1) * n := + Nat.add_le_add_left ((Nat.le_succ _).trans (Nat.le_mul_of_pos_right _ hpos)) _ + have hm := address h hk hs (T.scheme.m + T.scheme.d) (Nat.le_add_right ..) (by + unfold range + omega) + unfold arity at fit + have ar : BatchDescent.Beat.markWidth Q T r ≤ u := by omega + have hp : 4 * Q.b ≤ 2 ^ Pr := (Nat.le_add_left ..).trans Nat.lt_two_pow_self.le + have hs' := T.start_net Q a (Nat.sub_le ..) (b Q) (k Δ) P.load Δ C (A.port x y payload) + hu hpos (p.access hu hb.1 hb.2 (BatchDescent.Beat.parcel T r)) le_rfl + (p.access hu hm.1 hm.2 (BatchDescent.Beat.labels T r)) le_rfl (by omega) keys ar mark + Pr (Nat.le_add_right ..) hp (load ∘ E) (fun i => i.1.1.val.q.core.reciprocal) + have all := (h₁.comp hs').comp (Computes.of_map (Map.circuit hu hsave) (fun _ => rfl)) + simp only [one_mul, mul_one] at all + obtain ⟨f, hf, he⟩ := all + refine ⟨f, hf.mono ?_, fun i t => (he i t).trans ?_⟩ + · unfold firstCost prepareCost + simp only [A₀, A₁, A₂, input, headed, Attachment.port, Attachment.format, Format.width_pair, + Template.format] + omega + · have hw := (s i.1.1).valid_eq (BatchDescent.Beat.choices Q) i.1.2 + change (@ite F (start (Q := Q) (r := r) i.1.1 i.1.2 i.2.1 i.2.2 + = t) (Classical.propDecidable _) (T.valid a (b Q) Q + (T.prepared a (Nat.sub_le ..) (b Q) (k Δ) P.load Δ C (i.1.1.val.raw.1, i.1.2))) 0) = _ + rw [hw] + dsimp only + cases ((s i.1.1).selector (BatchDescent.Beat.choices Q)).read i.1.2 <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Effect of the contraction on the expansion and its invariants -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + (q : (frame A L (Q.b * v) z payload Δ C P).state) (s : Poll h q) + (hd : 0 < Δ) (hc : Δ ≤ C) + +open scoped Classical in +theorem expands (x' : Val x) (y' : Val y) : + ∑ i : s.choices, (query h q s i hd hc).sweepWeight * (result h q s i hd hc).diagram.eval x' y' + = + q.val.diagram.eval x' y' := by + let G (i : s.choices) : Diagram F q.val.a q.val.b := ((ticket h q s i).layout hc).diagram + have he (a b) : ∑ i, (G i).eval a b = q.val.G.diagram.eval a b := + s.group.eval_contract s.matching Q (q.val.G.regroup _ (Nat.sub_le _ _)).units (pos h) a b + refine Eq.trans ?_ (q.val.Z.attach_sum q.val.G.diagram G he x' y') + refine Finset.sum_congr rfl fun i _ => ?_ + exact (q.val.Z.attach_factor (posted h q s i hd hc).post.toPresentation x' y').symm + +variable (i : s.choices) +local notation "G" => Template.Branch.layout (ticket h q s i) hc +local notation "N" => next Q A L v (pos h) z Δ C B r +local notation "U" => out Q A L v (pos h) z Δ C B r +local notation "V" => target Q A L v (pos h) z Δ C B r +local notation "X" => result h q s i hd hc + +open scoped Classical in +theorem preserved (hΔ : 3 ≤ Δ) (hg : gain Δ ≤ K) : + Ready (A.transport (raw Q A L v (pos h) z Δ C B r).sweep (slots A r)) L z (Δ ^ degreePower) (C + ^ degreePower) (after L P K Q.ratio 1 σ) X := by + have env := estimates h q s i hd hc + have bounds := env.1 + have width := env.2.1 + have stayed := env.2.2.1 + have mass := env.2.2.2 + have ha := q.property.1 + let post := posted h q s i hd hc + let root := query h q s i hd hc + have live : Nonempty (G).V := ⟨((ticket h q s i).v.1.1, (ticket h q s i).v.2)⟩ + have low : ∀ j, v ≤ post.post.toPresentation.borderWidth j := + (ready h q s i hd hc).floor (fun j => (Nat.le_mul_of_pos_left _ Q.pos).trans (ha.span j)) + refine moved_ready q.val root G q.val.q post _ (moves h q s i hd hc) (active h q s i hd hc) + (agrees h q s i hd hc) (show (raw Q A L v (pos h) z Δ C B r).full = true from h.full) + ha live ?_ low stayed ⟨?_, ?_, ?_⟩ ?_ mass + · intro he + have hit : Δ ^ 1 < Δ ^ degreePower := Nat.pow_lt_pow_right (by omega) (by decide) + exact (not_lt_of_ge he (hΔ.trans_lt (by rw [pow_one] at hit; exact hit))).elim + · exact fun j => (bounds.1 j).trans (Reduction.power_growth hΔ 900 degreePower rfl) + · exact fun j => (bounds.2.1 j).trans (Reduction.power_growth (hΔ.trans hc) 900 degreePower rfl) + · intro u j + change (G).load u j ≤ (K : ℝ) * P.load + exact (bounds.2.2 u j).trans (mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hg) (cost_pos h).le) + · change ((G).X : ℝ) ≤ Q.ratio * P.width + 1 * (L.total + σ) + rw [one_mul] + exact width + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Issuing the history and frozen-seat requests, and extracting scalar factors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + (s : ∀ q : (frame A L (Q.b * v) z payload Δ C P).state, Poll h q) + (hd : 0 < Δ) (hc : Δ ≤ C) (hk : 2 ^ (k Δ) ≤ K) (hs : range (T := T) Δ C r ≤ T.scheme.m) + +local notation "a" => (T.scheme.h - r) +local notation "n" => (T.scheme.h - a) +local notation "hb" => BatchDescent.Beat.choices Q +local notation "M" => book Q A v (pos h) z B +local notation "𝓒" => cap Q A v (pos h) z Δ B +local notation "𝓚" => meter L z Δ B +local notation "Y" => raw Q A L v (pos h) z Δ C B r +local notation "N" => next Q A L v (pos h) z Δ C B r +local notation "k'" => slots A r +local notation "p'" => (T.scheme.d + 1) + +open scoped Classical in +/-- Indexes the path by the coordinates of `Σ q : (frame A L (Q.b * v) z payload Δ C P).state, +(s q).choices`. -/ +abbrev Path := Σ q : (frame A L (Q.b * v) z payload Δ C P).state, (s q).choices + +open scoped Classical in +/-- The value specified by `(i.1.val.raw, (ticket h i.1 (s i.1) i.2).head hb)`. -/ +def mid (i : Path h s) : (headed Q A Δ C r).obj := (i.1.val.raw, (ticket h i.1 (s i.1) i.2).head hb) + +open scoped Classical in +/-- Computes the issued by the application `query h i.1 (s i.1) i.2 hd hc`. -/ +abbrev issued (i : Path h s) := query h i.1 (s i.1) i.2 hd hc + +include hk hs in +open scoped Classical in +theorem second : ∃ gate : Table F, Processor.arity gate = issueWidth Q A L v (pos h) z Δ C B r ∧ + ∀ {u : ℕ} {W : Set (Table F)}, 3 ≤ u → arity Q A L v (pos h) z Δ C B r ≤ u → + gate ∈ W → BatchDescent.Snapshot.sweepTable Y ∈ W → + Computes F u W (headed Q A Δ C r) (requests Q A L v (pos h) z Δ C B r) + (mid h s) (fun i => (issued h s hd hc i).sweep.requests) + (fun i => (issued h s hd hc i).sweepWeight) + (secondCost Q A L v (pos h) z Δ C B r p + A.sweepCost Y k' p') := by + let q (i : Path h s) := ticket h i.1 (s i.1) i.2 + let rm (i : Path h s) := room h i.1 (s i.1) i.2 hd + obtain ⟨gate, hw, hnet⟩ := A.grouped_net M 𝓒 𝓚 hb hc q rm (fun i => i.1.val.raw.2) + (fun i => ready h i.1 (s i.1) i.2 hd hc) + refine ⟨gate, hw, ?_⟩ + intro u W hu fit hg hgate + let l := precision T Δ C r + have hl : T.size a ≤ l := (Nat.le_add_right ..).trans (Nat.le_add_right ..) + have hh : 2 ^ (Window.Tile.radius T.scheme.d + (n + 1)) ≤ l := + (Nat.le_add_left ..).trans (Nat.le_add_right ..) + have hq : 2 ^ (T.degree a Δ C) ≤ l := Nat.le_add_left .. + unfold arity at fit + have hi : issueWidth Q A L v (pos h) z Δ C B r ≤ u := by omega + have he : 2 * (N).scheme.ℓ ≤ u := by omega + have hn := (BatchDescent.Beat.positive Δ).trans (enough h hk) + have hd' : T.scheme.d ≤ (T.scheme.d + 1) * n := (Nat.le_succ _).trans (Nat.le_mul_of_pos_right _ + hn) + have ha := address h hk hs (T.scheme.m + T.scheme.d) (Nat.le_add_right ..) (by + unfold range + omega) + have out := hnet hu hg hi (p.access hu ha.1 ha.2 (BatchDescent.Beat.walk Q T r)) le_rfl hl hh hq + have run := out.comp (Attachment.Query.sweep_net (issued h s hd hc) hu he hgate) + simp only [one_mul] at run + exact run + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Applying the common border decoder to a contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Coloring BatchDescent.Trail + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + (s : ∀ q : (frame A L (Q.b * v) z payload Δ C P).state, Poll h q) + (hd : 0 < Δ) (hc : Δ ≤ C) (hk : 2 ^ (k Δ) ≤ K) (hs : range (T := T) Δ C r ≤ T.scheme.m) + +local notation "a" => (T.scheme.h - r) +local notation "n" => (T.scheme.h - a) +local notation "N" => next Q A L v (pos h) z Δ C B r +local notation "k'" => slots A r +local notation "p'" => (T.scheme.d + 1) +local notation "self" => hop T.scheme.d none + +open scoped Classical in +/-- The value specified by `(issued h s hd hc i).sweep`. -/ +abbrev swept (i : Path h s) := (issued h s hd hc i).sweep +open scoped Classical in +/-- Computes the moved by the application `result h i.1 (s i.1) i.2 hd hc`. -/ +abbrev moved (i : Path h s) := result h i.1 (s i.1) i.2 hd hc + +open scoped Classical in +private def step (d : ℕ) (i : Coloring.B (d + 1)) : Option (Coloring.B d) := + if h : i.val < 2 ^ d then some ⟨i.val, h⟩ else none + +open scoped Classical in +private theorem nav (i : Path h s) (j : Coloring.B (N).scheme.m) (l : Coloring.B p') : + (swept h s hd hc i).M.nav j l = + (step T.scheme.d l).elim (T.parent a j) (T.nav (swept h s hd hc i).old.1 (T.parent a j)) := by + change subroundNav (U := (N).scheme) (T.parent a) i.1.val.raw.1.1 j l = _ + unfold subroundNav step + split <;> rfl + +open scoped Classical in +private theorem parent (i : Path h s) (j : Coloring.B (N).scheme.m) : + (swept h s hd hc i).M.nav j self = (swept h s hd hc i).R.parent j := + nav_hop (U := (N).scheme) (T.parent a) i.1.val.raw.1.1 j none + +include hk hs in +open scoped Classical in +theorem rebuild {u : ℕ} {W : Set (Table F)} (hu : 3 ≤ u) + (fit : arity Q A L v (pos h) z Δ C B r ≤ u) + (allow : A.rebuildGate N k' p' self ∈ W) : + Computes F u W (requests Q A L v (pos h) z Δ C B r) (A.transport N k').format + (fun i => (swept h s hd hc i).requests) (fun i => (swept h s hd hc i).result) + (fun _ => 1) (rebuildCost Q A L v (pos h) z Δ C B r p) := by + have hn := (BatchDescent.Beat.positive Δ).trans (enough h hk) + have hd' : T.scheme.d ≤ (T.scheme.d + 1) * n := (Nat.le_succ _).trans (Nat.le_mul_of_pos_right _ + hn) + have old := address h hk hs (T.scheme.m + T.scheme.d) (Nat.le_add_right ..) (by + unfold range + omega) + have fresh := address h hk hs (T.scheme.m + (n + 1) + + T.degree a Δ C) (by omega) (by unfold range; omega) + have hf : A.rebuildWidth N k' p' ≤ u := (Nat.le_add_left ..).trans fit + exact Attachment.Query.rebuild_net hu (Nat.sub_le ..) (p.access hu old.1 old.2 _) le_rfl + (p.access hu fresh.1 fresh.2 _) le_rfl (T.parent a) (step T.scheme.d) (swept h s hd hc) self + (nav h s hd hc) (fun i => i.1.val.q.core.reciprocal) + (fun i => (posted h i.1 (s i.1) i.2 hd hc).reciprocal) + (parent h s hd hc) hf allow + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # A common selector for contractions of different attached networks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + +open scoped Classical in +/-- The stage used in the `Beat` construction. -/ +abbrev stage (Δ C : ℕ) := + interim A (raw Q A L v (pos h) z Δ C B r).sweep (slots A r) (copies Δ B) L v z payload + (Δ ^ degreePower) (C ^ degreePower) (after L P K Q.ratio 1 σ) + +variable (s : ∀ q : (frame A L (Q.b * v) z payload Δ C P).state, Poll h q) + (hd : 0 < Δ) (hc : Δ ≤ C) (hΔ : 3 ≤ Δ) (hg : gain Δ ≤ K) + +local notation "X" => frame A L (Q.b * v) z payload Δ C P +local notation "Y" => stage h Δ C +local notation "Z" => T.Candidate (T.scheme.h - r) (b Q) + +open scoped Classical in +/-- Builds `Selected X Y Z where choice q` with the specified `choice`, `index`, `next`, +`spare`. -/ +def selected : Selected X Y Z where + choice q := (s q).choices + index q := (s q).selector (BatchDescent.Beat.choices Q) + next q i := ⟨result h q (s q) i hd hc, ⟨preserved h q (s q) hd hc i hΔ hg, + spare h q (s q) i hd hc⟩, + fits h q (s q) i hd hc⟩ + scalar q i := (query h q (s q) i hd hc).sweepWeight + expands q x y := (expands h q (s q) hd hc x y).symm + +open scoped Classical in +/-- Indexes the case bit by the coordinates of `Path h s × Val x × Val y`. -/ +abbrev CaseBit := Path h s × Val x × Val y + +open scoped Classical in +/-- Computes the old bits by the application `i.1.1.val.data i.1.1.property.2 i.2.1 i.2.2`. -/ +def oldBits (i : CaseBit h s) := i.1.1.val.data i.1.1.property.2 i.2.1 i.2.2 + +open scoped Classical in +/-- The construction uses `i.1` for its intermediate `j`. -/ +def output (i : CaseBit h s) := + let j := i.1 + let q := result h j.1 (s j.1) j.2 hd hc + (q.raw, q.data (fits h j.1 (s j.1) j.2 hd hc) i.2.1 i.2.2) + +open scoped Classical in +theorem start_at (i : CaseBit h s) : + start (Q := Q) (r := r) i.1.1 (((s i.1.1).selector (BatchDescent.Beat.choices Q)).write i.1.2) + i.2.1 i.2.2 = + (mid h s i.1, oldBits h s i) := + Prod.ext (Prod.ext rfl ((ticket h i.1.1 (s i.1.1) i.1.2).headed_eq (BatchDescent.Beat.choices + Q))) rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Description size in a contraction with a retained border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Assembly History Packing Case Coloring + +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) +local notation "I" => Case κ Q.b d B +local notation "E" => e Δ B + +open scoped Classical in +/-- The value specified by `raw (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B i.r`. -/ +abbrev plan (i : I) := raw (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B i.r +open scoped Classical in +/-- The value specified by `(plan Q Δ C d B i).sweep`. -/ +abbrev fresh (i : I) := (plan Q Δ C d B i).sweep +open scoped Classical in +/-- The value specified by `target (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B i.r`. -/ +abbrev pack (i : I) := target (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B i.r +open scoped Classical in +/-- Computes the menu by the application `book (Q.extend i.F) i.A i.v i.positive i.z B`. -/ +abbrev menu (i : I) := book (Q.extend i.F) i.A i.v i.positive i.z B +open scoped Classical in +/-- The quantity computed by `(Post.headerFmt (i.T.degree i.a Δ C) E (menu Q d B i).d).width + +(menu Q d B i).overhead E`. -/ +abbrev added (i : I) := (Post.headerFmt (i.T.degree i.a Δ C) E (menu Q d B i).d).width + + (menu Q d B i).overhead E + +open scoped Classical in +theorem meter_bound : Base (fun i : I => (meter i.L i.z Δ B).count) := by + refine (base_const 3).mul (((base_const (copies Δ B)).add units).mono fun i => ?_) + exact BatchDescent.Phase.clog_le_add_of_le_mul_succ _ _ _ + (by simp only [add_mul, mul_add, one_mul, mul_one]; omega) + +open scoped Classical in +/-- The quantity computed by `(d + Nat.clog 2 ((4 * C) ^ 300) + 1) * 3`. -/ +abbrev maxDegree := Assembly.Child.degreeLimit C d + +open scoped Classical in +theorem child_degree (i : I) : i.T.degree i.a Δ C ≤ maxDegree C d := by + simpa only [Template.degree, Template.bound, i.h.full, ↓reduceIte] using + Assembly.Child.nextWidth_le_degreeLimit (i.T.scheme.h - i.a) C i.h.degree + +open scoped Classical in +theorem child_slots : Base (fun i : I => 2 ^ i.T.degree i.a Δ C) := + (base_const (2 ^ maxDegree C d)).mono fun i => Nat.pow_le_pow_right (by decide) (child_degree Q Δ + C d B i) + +open scoped Classical in +theorem child_factor : Base (fun i : I => 2 ^ (i.n + 1)) := tiles.exp_add (base_const (2 ^ 1)) +open scoped Classical in +theorem place_factor : Base (fun i : I => 2 ^ slots i.A i.r) := tiles.exp_add stations +open scoped Classical in +theorem hop_factor : Base (fun i : I => 2 ^ (i.T.scheme.d + 1)) + := Case.slots.exp_add (base_const (2 ^ 1)) + +open scoped Classical in +private theorem length_bound : Base (fun i : I => (menu Q d B i).d) := by + refine ((base_const (B + 4)).add units).mono fun i => ?_ + change Nat.clog 2 ((Finset.range (B * i.z + 1)).card + 3) ≤ _ + rw [Finset.card_range] + exact BatchDescent.Phase.clog_le_add_of_le_mul_succ _ _ _ + (by simp only [add_mul, mul_add, one_mul, mul_one]; omega) + +open scoped Classical in +private theorem role_bound : Base (fun i : I => Kind.width i.T.scheme (Q.extend i.F) (i.T.scheme.e + + 2)) := by + have h : Base (fun i : I => 1 + (Fintype.card (Role Q) + 2 ^ (i.T.scheme.e + 2))) := + (base_const 1).add ((base_const _).add (spans.exp_add (base_const (2 ^ 2)))) + refine ((h.add (base_const 1)).clog).mono fun i => ?_ + simp only [Kind.width, Kind.Small, Fintype.card_sum, Fintype.card_fin, Dense.used, i.h.single, + pow_zero] + rfl + +open scoped Classical in +private theorem overhead_bound : Base (fun i : I => (menu Q d B i).overhead E) := by + have he : Base (fun _ : I => 2 ^ E) := base_const _ + have hs : Base (fun i : I => 2 ^ (menu Q d B i).s) := + (spans.exp_add (base_const (2 ^ 2))).exp_add (base_const (2 ^ Nat.clog 2 (Q.b + 1))) + have hd := length_bound Q d B + have hr := role_bound Q d B + have hl : Base (fun i : I => Dense.used (i.T.scheme.ℓ + + Kind.width i.T.scheme (Q.extend i.F) (i.T.scheme.e + 2))) := by + refine (hr.add lengths).mono fun i => ?_ + rw [add_assoc 1] + exact BatchDescent.Phase.clog_le_add_of_le_mul_succ _ _ _ + (by simp only [add_mul, mul_add, one_mul, mul_one]; omega) + have hw := (he.mul hd).add (he.mul ((base_const 1).add + ((base_const 0).add (hs.mul ((base_const 1).add ((base_const E).add hd)))))) + refine ((hw.add (he.mul hl)).add (he.mul hr)).mono fun i => ?_ + rw [Book.overhead, Post.bookkeeping, Dense.overhead, width_code] + +open scoped Classical in +theorem added_bound : Base (added Q Δ C d B) := by + have hd := (child_slots Q Δ C d B).of_exp + have core := Width.pair (Width.addr hd) (Width.addr (base_const E)) + have bit : Base (fun _ : I => Format.bit.width) := base_const _ + have row := Width.pair (Width.addr (length_bound Q d B)) (Width.pair bit (Width.pair bit core)) + exact (Width.pair bit (Width.vec (base_const (2 ^ E)) row)).add (overhead_bound Q Δ d B) + +open scoped Classical in +theorem bits_eq (i : I) : (plan Q Δ C d B i).scheme.ℓ = added Q Δ C d B i + 2 ^ E * i.T.scheme.ℓ + := by + change (Post.record _ _ _ (.addr _)).width = _ + simp only [added, cap, Post.record, Post.headerFmt, Format.width_pair, Format.width_addr, + add_assoc] + +open scoped Classical in +theorem child_bound : Child (plan Q Δ C d B) (fun i => i.n + 1) where + extent _ := Nat.sub_le .. + allocation _ := le_rfl + growth := (child_factor Q d B).short + single _ := rfl + spans := short_const (2 ^ E) + neighbors := (child_slots Q Δ C d B).short + bits := ((added_bound Q Δ C d B).short.add ((short_const (2 ^ E)).mul Case.bits)).mono + fun i => (bits_eq Q Δ C d B i).le + count := (meter_bound Q Δ d B).short + +open scoped Classical in +theorem fresh_bound : Child (fresh Q Δ C d B) (fun i => i.n + 1) := by + obtain ⟨a, b, c, d, e, f, g, h⟩ := child_bound Q Δ C d B + exact ⟨a, b, c, d, e, f, g, h⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Exterior transfer in one beat -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) + +theorem carryWidth_bound : Case.Short (fun i : Case κ Q.b d B => + i.A.carryWidth (fresh Q Δ C d B i) (slots i.A i.r) (i.n + 1) i.payload) := + (fresh_bound Q Δ C d B).carryWidth (place_factor Q d B).short (child_factor Q d B).short + +theorem carrySize_bound : Case.Total (fun i : Case κ Q.b d B => + i.A.carryCost (fresh Q Δ C d B i) (slots i.A i.r) (i.T.scheme.d + 1) (i.n + 1) + i.x i.y i.payload i.p) := + (fresh_bound Q Δ C d B).carryCost (place_factor Q d B).short (hop_factor Q d B).short + (child_factor Q d B).short + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Linear dependence on the length of old contraction labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Assembly Packing Case + +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) +local notation "I" => Case κ Q.b d B +local notation "Y" => fresh Q Δ C d B +local notation "E" => e Δ B +local notation "N" => copies Δ B + +private def links (i : I) := + 2 ^ (slots i.A i.r) * (1 + i.A.k + 2 ^ max i.A.e E * (2 + i.T.degree i.a Δ C + slots i.A i.r + + max i.A.e E)) + +private theorem links_bound : Base (links Q Δ C d B) := by + have q := place_factor Q d B + have t := Width.expMax (ports : Base (fun i : I => _)) (base_const (2 ^ E)) + have d := (child_slots Q Δ C d B).of_exp + exact q.mul (((base_const 1).add stations.of_exp).add + (t.mul ((((base_const 2).add d).add q.of_exp).add t.of_exp))) + +theorem labels_bound : ∃ H : ℕ, ∀ i : I, + (Y i).scheme.ℓ + (pack Q Δ C d B i).ℓ ≤ H * (i.T.scheme.ℓ + i.A.ℓ) + i.base ^ H := by + obtain ⟨j, hj⟩ := (((base_const 2).mul (added_bound Q Δ C d B)).add (links_bound Q Δ C d B)).bound + let H := j + 2 * 2 ^ E + N + refine ⟨H, fun i => ?_⟩ + have h₁ : 2 * 2 ^ E * i.T.scheme.ℓ + N * i.A.ℓ ≤ H * (i.T.scheme.ℓ + i.A.ℓ) := by + rw [mul_add] + exact Nat.add_le_add (Nat.mul_le_mul_right _ ((Nat.le_add_left ..).trans (Nat.le_add_right ..))) + (Nat.mul_le_mul_right _ (Nat.le_add_left ..)) + have h₂ : 2 * added Q Δ C d B i + links Q Δ C d B i ≤ i.base ^ H := + (hj i).trans (Nat.pow_le_pow_right (lt_of_lt_of_le (by decide) i.base_two) + ((Nat.le_add_right ..).trans (Nat.le_add_right ..))) + have he : (pack Q Δ C d B i).ℓ = (Y i).scheme.ℓ + N * i.A.ℓ + links Q Δ C d B i := + i.A.short_width (Y i) _ N + have hh : (Y i).scheme.ℓ = _ := bits_eq Q Δ C d B i + rw [he, hh] + rw [mul_assoc] at h₁ + omega + +theorem range_bound : Short (fun i : I => range (T := i.T) Δ C i.r) := + (((hop_factor Q d B).short.of_exp.mul tiles.short.of_exp).add + (child_slots Q Δ C d B).short.of_exp |>.add tiles.short.of_exp).add (short_const 1) + +theorem shrinkWidth_bound : Short (fun i : I => i.A.shrinkWidth (Y i) (slots i.A i.r) N) := + (fresh_bound Q Δ C d B).shrinkWidth (place_factor Q d B).short N + +theorem rebuildCost_bound : Cost (fun i : I => + rebuildCost (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B i.r i.p) := + (fresh_bound Q Δ C d B).rebuildCost (place_factor Q d B).short (hop_factor Q d B).short + +theorem sweepCost_bound : Cost (fun i : I => + i.A.sweepCost (plan Q Δ C d B i) (slots i.A i.r) (i.T.scheme.d + 1)) := + (child_bound Q Δ C d B).sweepCost (place_factor Q d B).short (hop_factor Q d B).short + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Pass.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Pass.lean new file mode 100644 index 0000000000..9c494d5a24 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Pass.lean @@ -0,0 +1,439 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Carry +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Shipment.Bound +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Reset.Label +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.FreezeInput.Retain +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact + +/-! # Transferring the exterior after a change of host or station -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case.Child +open Assembly Coloring Width +variable {κ : Type} [Field κ] {b d B : ℕ} {N : (i : Case κ b d B) → Template i.F} + {δ j p z : Case κ b d B → ℕ} (h : Child N δ) (hj : Short (fun i => 2 ^ j i)) + (hp : Short (fun i => 2 ^ p i)) (hz : Short (fun i => 2 ^ z i)) +local notation "I" => Case κ b d B + +private theorem loadsShort : Short (fun i : I => i.payload) := + (Poly.of_le base_two (fun i : I => by + unfold base Contraction.base + have := Nat.zero_le (2 ^ i.r) + have := Nat.zero_le (2 ^ i.A.k) + have := Nat.zero_le (2 ^ i.A.e) + have := Nat.zero_le (2 ^ i.T.scheme.e) + omega)).grow base_short + +include h hj in +private theorem rowLog : Short (fun i : I => i.A.carryRows (N i) (j i)) := by + have a : Short (fun i : I => i.height + (i.A.k + i.A.e)) + := levels.short.add (stations.short.of_exp.add ports.short.of_exp) + have v := ((levels.short.mono h.extent).add (hj.of_exp.add (expMax ports.short h.spans).of_exp)) + exact (a.add v).mono (fun _ => max_le (Nat.le_add_right ..) (Nat.le_add_left ..)) + +include h hj in +private theorem rowCount : Row (fun i : I => 2 ^ i.A.carryRows (N i) (j i)) := by + have a : Row (fun i : I => 2 ^ i.height * 2 ^ (i.A.k + i.A.e)) := + (Short.block (stations.short.exp_add ports.short)).blocks + have v := h.layer (Short.block (hj.exp_add (expMax ports.short h.spans))) + refine (a.add v).mono fun i => ?_ + unfold Attachment.carryRows + rw [← pow_add, ← pow_add] + rcases le_total (i.height + (i.A.k + i.A.e)) ((N i).scheme.h + (j i + + i.A.spanBits (N i))) with a|a + · rw [max_eq_right a]; exact Nat.le_add_left .. + · rw [max_eq_left a]; exact Nat.le_add_right .. + +include h hj hz in +theorem carryWidth : Short (fun i : I => i.A.carryWidth (N i) (j i) (z i) i.payload) := by + have ptr : Short (fun i : I => i.A.pointer.width) + := pair bit (pair (addr levels.short) (addr stations.short.of_exp)) + have req := pair (addr (h.transport hj)) (vec hj ptr) + have rep := pair (addr hz.of_exp) (pair (addr (loadsShort.add (short_const 1))) (addr (h.rowLog + hj))) + exact req.add (vec hj (vec (expMax ports.short h.spans) rep)) + +include h in +private theorem bothHosts {f : I → ℕ} (hf : Row f) : + Cost (fun i => (2 ^ i.m + 2 ^ (N i).scheme.m) * f i) := by + simpa only [add_mul] using hf.hosts.add (h.cost hf) + +include h hj hz in +private theorem emit : Cost (fun i : I => SpanPlan.emitCost i.m (N i).scheme.m (i.payload + 1) (z i) + (i.A.carryRows (N i) (j i))) := by + have w : Short (fun i : I => i.payload + 1) := loadsShort.add (short_const 1) + have rows := h.rowCount hj + have exp := rows.mul hz.block + have size := ((short_const 100).add (((((short_const 2).mul (h.rowLog hj)).add hz.of_exp).add + w))).pow 140 + have work := h.bothHosts (exp.mul (Short.block size)) + have entry := pair (addr hz.of_exp) (pair (addr w) (pair (addr w) (addr w))) + have records : Row (fun i : I => (Format.vec (i.A.carryRows (N i) (j i)) + (Fragments.Entry (i.payload + 1) (z i))).width) := + (rows.mul (Short.block entry)).mono fun _ => (Format.width_vec ..).le + have unit := (Short.long (addr w)).row + have lengths := (Short.long (vec hz (addr w))).row + have tab := pack unit (pack lengths records) + have grid := pack (parent.vector tab) (h.vector tab) + have ll := pack (parent.vector unit) (parent.vector lengths) + have lr := pack (h.vector unit) (h.vector lengths) + have keys : Cost (fun i : I => (Format.vec (i.m + z i) (.addr ((N i).scheme.m + z i))).width) := + ((Long.row (addr (h.address.add hz.long.of_exp))).expand hz.block).mono fun _ + => (Format.width_vec ..).le + have cols := pack (pack (pack ll lr) keys) (pack (parent.vector records) (h.vector records)) + refine (work.add (grid.add (cols.scale 34))).mono fun i => ?_ + rw [SpanPlan.emitCost, pow_add] + +include h hj hp hz in +private theorem prep : Cost (fun i : I => i.A.carryPrep (N i) (j i) (z i) i.payload (p i)) := by + have input := pack (h.requests hj hp) (h.attached (h.transport hj)) + have act := h.cost (h.layer (Short.block ((short_const 1).add (h.carryWidth hj hz)))) + have size := ((short_const 110).add ((short_const 4).mul ((hz.of_exp.add (h.rowLog hj)).add + loadsShort))).pow 200 + have rows := (h.rowCount hj).mul (Short.block size) + have data := (h.cost rows).add (Row.hosts (rows.left hz.block)) + refine (((((input.add act).add data).add (h.emit hj hz)).scale 1000)).mono fun i => ?_ + unfold Attachment.carryPrep + simp only [add_mul, mul_assoc] + rfl + +include h in +private theorem volume : Total (fun i : I => Attachment.volume i.x i.y (N i).scheme.m) := by + simpa only [Attachment.volume, add_assoc, mul_one] using + (h.cost (long_const 1).row).total.add (outer_const 1).total + +include h hj hp hz in +theorem carryCost : Total (fun i : I => + i.A.carryCost (N i) (j i) (p i) (z i) i.x i.y i.payload i.p) := by + obtain ⟨K, hK⟩ := Prices.shipment_le + have small : Outer (fun i : I => 1000 + i.p.W + i.payload + i.payload) := + (((outer_const 1000).add price).add loads).add loads + have medium := ((small.block.add hz.block.of_exp).add (loads.block.add (block_const 1))).add + (h.rowLog hj).block + have big := ((((Block.long medium).add hosts).add h.address).add world).add power + have row := (Long.row (big.pow K)).add ((h.rowCount hj).mul (medium.pow K)) + have work := h.bothHosts (row.left hz.block) + have traffic := (parent.volume.add h.volume).mul (small.pow K) + have costs := (Cost.total (((h.attached (h.transport hj)).scale 4).add work)).add traffic + refine ((h.prep hj hp hz).total.add costs).mono fun i => ?_ + unfold Attachment.carryCost + apply Nat.add_le_add_left + simpa only [mul_assoc] using hK i.F i.p (i.A.transport (N i) (j i)).format.width + i.m (Attachment.volume i.x i.y i.m) i.payload + (N i).scheme.m (Attachment.volume i.x i.y (N i).scheme.m) i.payload + (z i) (i.payload + 1) (i.A.carryRows (N i) (j i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case.Child +end + +/- # The common state space after local concentration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} + (D : Template F) (s : Plan) (T : ℕ) (L : ℝ) (z payload : ℕ) + +/-- The data for the publication construction, including `R`, `g`, `P`, `Q`, `ready`. -/ +structure Publication where + /-- The `Publication` field of type `ℕ`. -/ + R : ℕ + /-- The `Publication` field of type `ℕ`. -/ + g : ℕ + /-- The `Publication` component of type `Rounds.Input F x y D.scheme.h s.D T R g (10000 * L)`. -/ + P : Rounds.Input F x y D.scheme.h s.D T R g (10000 * L) + /-- The `Publication` component of type `LocalTerm F x y D.scheme.h (s.b * z)`. -/ + Q : LocalTerm F x y D.scheme.h (s.b * z) + ready : Concentrated P Q s.C s.d 10 + live : Nonempty Q.V + /-- The `Publication` component of type `D.format.obj`. -/ + r : D.format.obj + /-- The `Publication` component of type `D.Shows r Q`. -/ + showing : D.Shows r Q + fits : D.scheme.Fits r.1 (2 ^ D.scheme.m + wd x + wd y) payload + +/-- The quantity computed by `D.scheme volume := 2 ^ D.scheme.m + wd x + wd y height := payload +extra := .vec D.scheme.m D.header`. -/ +abbrev publicEncoding : + Encoding (fun i : Publication (x := x) (y := y) D s T L z payload => i.Q.diagram) where + scheme := D.scheme + volume := 2 ^ D.scheme.m + wd x + wd y + height := payload + extra := .vec D.scheme.m D.header + rows i := i.r.1 + data i := i.r.2 + presents i := i.showing.pres + fits i := i.fits + +/-- The value specified by `(publicEncoding D s T L z payload).snapshot`. -/ +abbrev publication : Snapshot.{1} F x y := (publicEncoding D s T L z payload).snapshot +/-- The quantity computed by `D.sweep.border (s.b * z) (1 / (s.D : ℝ) ^ 4)`. -/ +abbrev border := D.sweep.border (s.b * z) (1 / (s.D : ℝ) ^ 4) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Resource limits from a published term to the next charged board -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly +variable {F : Type} [Field F] {x y : Wire} + +namespace BoundaryScale +variable (D : Template F) (z payload r : ℕ) (p : Prices F) + +/-- The value specified by `100 + 2 ^ r + D.scheme.h + Nat.clog 2 (1 + z) + 2 ^ D.scheme.e + +payload + Nat.clog 2 (1 + D.scheme.ℓ + D.count)`. -/ +def base := 100 + 2 ^ r + D.scheme.h + Nat.clog 2 (1 + z) + 2 ^ D.scheme.e + payload + + Nat.clog 2 (1 + D.scheme.ℓ + D.count) +/-- The quantity computed by `base D z payload r + D.scheme.ℓ + D.count`. -/ +def metadata := base D z payload r + D.scheme.ℓ + D.count +/-- The quantity computed by `metadata D z payload r + p.W`. -/ +def short := metadata D z payload r + p.W +/-- The quantity computed by `100 + p.W + D.scheme.h + payload + D.scheme.e + Nat.clog 2 (1 + +z)`. -/ +def outer := 100 + p.W + D.scheme.h + payload + D.scheme.e + Nat.clog 2 (1 + z) +/-- The quantity computed by `100 + p.w + p.w ^ p.power + short D z payload r p`. -/ +def long := 100 + p.w + p.w ^ p.power + short D z payload r p +/-- The cost used in the `BoundaryScale` construction. -/ +def cost (K : ℕ) := + 2 ^ D.scheme.m * (long D z payload r p) ^ K + 2 ^ (D.scheme.m + + D.scheme.h) * (short D z payload r p) ^ K + + (wd x + wd y) * (outer D z payload p) ^ K + +end BoundaryScale + +/-- The data for the requirements construction, including `positive`, `unit`, `lower`, `upper`, +`height`. -/ +structure Requirements (D : Template F) (s : Plan) (T : ℕ) (L : ℝ) (z payload : ℕ) (p : Prices F) + (r d K : ℕ) : Prop where + positive : 1 ≤ L + unit : 0 < z + lower : (s.b * z) * s.D ^ s.c ≤ T + upper : T ≤ z * s.M + height : s.n * r ≤ D.scheme.h + room : s.K ≤ 2 ^ r + slack : (s.K : ℝ) * T * (2 ^ (D.scheme.m + D.scheme.h) : ℕ) ≤ L * (2 : ℝ) ^ r + degree : D.scheme.d ≤ d + single : D.scheme.k = 0 + alphabet : Nat.clog 2 (Nat.card F) ≤ 2 ^ r + small : (BoundaryScale.metadata D z payload r) ^ K ≤ D.scheme.m + address : 4 * D.scheme.m ≤ p.w + +/-- The data for the restored construction, including `next`, `ready`, `loopless`, `lower`, +`seats`. -/ +structure Restored (D : Template F) (s : Plan) (T : ℕ) (L : ℝ) (z payload : ℕ) (p : Prices F) + (r K : ℕ) where + /-- The successor of each choice of type `Layer F x y`. -/ + next : Layer F x y + ready : next.Ready s.D (2 ^ s.p * T) (L / (2 : ℝ) ^ s.v) s.floor + loopless : next.Loopless + lower : D.scheme.m ≤ next.template.scheme.m + seats : next.template.scheme.m + next.template.scheme.h ≤ D.scheme.m + D.scheme.h + K + blocks : next.template.scheme.h + s.n * r = D.scheme.h + ports : next.template.scheme.e ≤ 5 + degree : next.template.scheme.d = 3 + volume : next.volume = 2 ^ next.template.scheme.m + wd x + wd y + height : next.height ≤ next.template.scheme.h + s.d + s.p + Nat.clog 2 T + labels : next.template.scheme.ℓ + next.template.count ≤ + K * (D.scheme.ℓ + D.count) + (BoundaryScale.base D z payload r) ^ K + /-- The `Restored` component of type `Finset (Table F)`. -/ + keys : Finset (Table F) + few : keys.card ≤ (BoundaryScale.short D z payload r p) ^ K + transfer : Transforms F ((BoundaryScale.short D z payload r p) ^ K) keys + (publication D s T L z payload) next.snapshot (BoundaryScale.cost (x := x) (y + := y) D z payload r p K) + +/-- The restarts of type `Prop` for the given inputs. -/ +def Restarts (k : Type) [Field k] (s : Plan) (d K : ℕ) : Prop := + ∀ (F : Type) [Field F] [Fintype F] [Algebra k F] {x y : Wire} (D : Template F) + (T : ℕ) (L : ℝ) (z payload : ℕ) (p : Prices F) (r : ℕ), + Requirements D s T L z payload p r d K → Nonempty (Restored (x := x) (y + := y) D s T L z payload p r K) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Metadata lengths immediately after cutting off the border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Coloring + +variable {F : Type} [Field F] (D : Template F) (s : Plan) (z payload r : ℕ) + +theorem width_bits {s : Plan} {T z : ℕ} (h : T ≤ z * s.M) : Nat.clog 2 T ≤ Nat.clog 2 (1 + z) + s.M + := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_add] + exact h.trans (Nat.mul_le_mul ((Nat.le_add_left ..).trans (Nat.le_pow_clog (by decide) _)) + Nat.lt_two_pow_self.le) + +/-- The quantity computed by `D.sweep.cut (s.b * z) (1 / (s.D : ℝ) ^ 4)`. -/ +abbrev inside := D.sweep.cut (s.b * z) (1 / (s.D : ℝ) ^ 4) + +theorem cut_length : + (inside D s z).scheme.ℓ = D.scheme.ℓ + 1 + 2 ^ D.scheme.d ∧ + (border D s z).ℓ = D.scheme.ℓ + 1 + 2 ^ D.scheme.d + D.count ∧ + (inside D s z).count = 1 + D.count := by + refine ⟨D.sweep.scheme.cut_length, D.sweep.border_length .., ?_⟩ + change (Format.pair .bit (.addr D.count)).width = _ + rw [Format.width_pair, Format.width_bit, Format.width_addr] + +namespace BoundaryScale + +omit [Field F] in +theorem base_lower : 100 + 2 ^ r + D.scheme.h + Nat.clog 2 (1 + z) + 2 ^ D.scheme.e + payload + ≤ base D z payload r := + Nat.le_add_right .. + +omit [Field F] in +theorem two : 2 ≤ base D z payload r := by + have := base_lower D z payload r + have := Nat.zero_le (2 ^ r) + have := Nat.zero_le (2 ^ D.scheme.e) + omega + +omit [Field F] in +theorem lower : base D z payload r ≤ metadata D z payload r := by unfold metadata; omega + +private theorem logarithm (a b c : ℕ) : + Nat.clog 2 (1 + (a + 1 + 2 ^ b) + (a + 1 + 2 ^ b + c)) ≤ Nat.clog 2 (1 + a + c) + b + 3 := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + have h := Nat.le_pow_clog (by decide : 1 < 2) (1 + a + c) + have h₁ := Nat.le_mul_of_pos_right (2 ^ Nat.clog 2 (1 + a + c)) (Nat.two_pow_pos b) + have h₂ := Nat.le_mul_of_pos_left (2 ^ b) (Nat.two_pow_pos (Nat.clog 2 (1 + a + c))) + rw [pow_add, pow_add] + omega + +variable {d : ℕ} (hd : D.scheme.d ≤ d) +include hd + +theorem cut_base : Contraction.base (border D s z) r z payload ≤ 3 * base D z payload r + d := by + obtain ⟨h₁, h₂, _⟩ := cut_length D s z + change 100 + 2 ^ r + D.scheme.h + Nat.clog 2 (1 + z) + 2 + 2 ^ D.scheme.e + 2 ^ D.scheme.e + + payload+ + Nat.clog 2 (1 + (inside D s z).scheme.ℓ + (border D s z).ℓ) ≤ _ + rw [h₁, h₂] + have h := logarithm D.scheme.ℓ D.scheme.d D.count + have := Nat.zero_le (2 ^ r) + have := Nat.zero_le (2 ^ D.scheme.e) + unfold base + omega + +theorem cut_short : Contraction.short (border D s z) r z payload ≤ + 4 * metadata D z payload r + (4 + d + 2 * 2 ^ d) := by + have h := cut_base D s z payload r hd + have hg := Nat.pow_le_pow_right (by decide : 0 < 2) hd + change Contraction.base (border D s z) r z payload + (inside D s z).scheme.ℓ + + (border D s z).ℓ + (inside D s z).count ≤ _ + obtain ⟨h₁, h₂, h₃⟩ := cut_length D s z + rw [h₁, h₂, h₃] + unfold metadata + omega + +end BoundaryScale + +variable {D s z payload r} {T d K K' : ℕ} {L : ℝ} {p : Prices F} + +theorem Requirements.shrink (h : Requirements D s T L z payload p r d K) (hk : K' ≤ K) : + Requirements D s T L z payload p r d K' := + { h with small := (Nat.pow_le_pow_right + ((show 0 < 2 by decide).trans_le + ((BoundaryScale.two ..).trans (BoundaryScale.lower ..))) hk).trans h.small } + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Capacity required to pass from a printed diagram to the core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly +variable {F : Type} [Field F] {x y : Wire} {D : Template F} {s : Plan} {p : Prices F} + {r d z payload T H K : ℕ} {L : ℝ} + +namespace BoundaryScale + +theorem linear {N : ℕ} (hn : 2 ≤ N) (a b : ℕ) : a * N + b ≤ N ^ (a + b + 1) := by + have hf := Nat.lt_two_pow_self (n := a + b) + have hb := Nat.le_mul_of_pos_right b (show 0 < N by omega) + calc + _ ≤ (a + b) * N := by rw [add_mul]; omega + _ ≤ N ^ (a + b) * N := Nat.mul_le_mul_right _ (hf.le.trans (Nat.pow_le_pow_left hn _)) + _ = _ := (pow_succ ..).symm + +/-- The quantity computed by `4 + (4 + d + 2 * 2 ^ d) + 1`. -/ +def charge (d : ℕ) := 4 + (4 + d + 2 * 2 ^ d) + 1 + +theorem coded (hd : D.scheme.d ≤ d) : + Contraction.short (border D s z) r z payload ≤ (metadata D z payload r) ^ (charge d) := + (cut_short D s z payload r hd).trans (linear ((two ..).trans (lower ..)) _ _) + +theorem origin (hd : D.scheme.d ≤ d) : + Contraction.base (border D s z) r z payload ≤ (base D z payload r) ^ (3 + d + 1) := + (cut_base D s z payload r hd).trans (linear (two ..) _ _) + +theorem increasing (hj : H ≤ K) : cost (x := x) (y := y) D z payload r p H ≤ + cost (x := x) (y := y) D z payload r p K := by + have hm := (two D z payload r).trans (lower ..) + have hS : 0 < short D z payload r p := by unfold short; omega + have hO : 0 < outer D z payload p := by unfold outer; omega + have hL : 0 < long D z payload r p := by unfold long; positivity + unfold cost + gcongr + +theorem plus : cost (x := x) (y := y) D z payload r p H + cost (x := x) (y := y) D z payload r p K ≤ + cost (x := x) (y := y) D z payload r p (max H K + 1) := by + have hm := (two D z payload r).trans (lower ..) + have hs : 2 ≤ short D z payload r p := by unfold short; omega + have ho : 2 ≤ outer D z payload p := by unfold outer; omega + have hl : 2 ≤ long D z payload r p := hs.trans (Nat.le_add_left ..) + unfold cost + rw [add_add_add_comm, add_add_add_comm (2 ^ D.scheme.m * _ ^ H), ← mul_add, ← mul_add, ← mul_add] + exact Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ (BatchDescent.Phase.Poly.pow_sum hl + ..)) + (Nat.mul_le_mul_left _ (BatchDescent.Phase.Poly.pow_sum hs ..))) + (Nat.mul_le_mul_left _ (BatchDescent.Phase.Poly.pow_sum ho ..)) + +end BoundaryScale + +theorem Requirements.pass (h : Requirements D s T L z payload p r d K) + (hk : BoundaryScale.charge d * H + 5 ≤ K) : + 4 * D.scheme.h ≤ D.scheme.m ∧ (short (border D s z) r z payload) ^ H ≤ D.scheme.m ∧ + 2 * (D.scheme.m + s.n * r + s.K) ≤ p.w := by + let a := BoundaryScale.metadata D z payload r + have hm : 2 ≤ a := (BoundaryScale.two ..).trans (BoundaryScale.lower ..) + have hb := (BoundaryScale.base_lower D z payload r).trans (BoundaryScale.lower ..) + have hx : 4 * a ≤ D.scheme.m := calc + _ ≤ a ^ 5 := BoundaryScale.linear hm 4 0 + _ ≤ a ^ K := Nat.pow_le_pow_right (by omega) (by omega) + _ ≤ _ := h.small + have height := h.height + have room := h.room + have address := h.address + have := Nat.zero_le (2 ^ D.scheme.e) + have := Nat.zero_le (2 ^ r) + refine ⟨by omega, ?_, by omega⟩ + calc + _ ≤ (a ^ BoundaryScale.charge d) ^ H := Nat.pow_le_pow_left (BoundaryScale.coded h.degree) H + _ ≤ a ^ K := by rw [← pow_mul]; exact Nat.pow_le_pow_right (by omega) (by omega) + _ ≤ _ := h.small + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Plan.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Plan.lean new file mode 100644 index 0000000000..164cbca716 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Plan.lean @@ -0,0 +1,679 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Costs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.MixCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Reset.WindowCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Beat.Fanout +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Headers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Attachment.WriteNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Reset.Label +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Carry +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Pass +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Restart +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Subround + +/-! +# One working subfield and a common range of round widths + +The concentration and the beat use different packet sizes. Choose +both from the width alone, before specifying the working extension +or any of the terms in the local expansion. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Filter SphereScale + +/-- The data for the window construction, including `F`, `[field`, `[finite`, `[ext`, `p`. -/ +structure Window (k : Type) [Field k] (s : Plan) where + /-- The `Window` component of type `Type`. -/ + F : Type + [field : Field F] + [finite : Fintype F] + [ext : Algebra k F] + /-- The `Window` field of type `ℕ`. -/ + p : ℕ + /-- The `Window` field of type `ℕ`. -/ + l : ℕ + /-- The right component. -/ + b : ℕ + /-- The `Window` field of type `ℕ`. -/ + T₀ : ℕ + [prime : Fact p.Prime] + [char : CharP F p] + large : localDegree < s.D + coefficient : s.C = Rounds.Input.terminalExponent localDegree 10 + scales : ∀ T ≥ T₀, ∃ d z, Scales localDegree 10 s.D T (p ^ l) b d ∧ + SphereScale.Ready F 10 s.D localDegree (p ^ l) b d ∧ + 0 < z ∧ (s.b * z) * s.D ^ s.c ≤ T ∧ T ≤ z * s.M + +attribute [instance] Window.field Window.finite Window.ext Window.prime Window.char + +variable {k : Type} [Field k] {s : Plan} + +theorem makeWindow [Finite k] (sync : MatrixExponent.Prices.SharedPrice (AlgebraicClosure k)) + (hs : s.Fits) (hb : 0 < s.b) (hc : s.C = Rounds.Input.terminalExponent localDegree 10) + (hd : localDegree + 2 * SphereScale.budget localDegree ≤ s.d) : Nonempty (Window k s) := by + have large : s.d < s.D := Nat.lt_two_pow_self + have hd' : 2 * SphereScale.budget localDegree ≤ s.D := by omega + obtain ⟨F, _, _, _, p, l, b, _, _, sc⟩ := SphereScale.choose (ℓ := 10) k sync hd' + obtain ⟨T₀, ht⟩ := eventually_atTop.mp sc + refine ⟨⟨F, p, l, b, T₀ + s.b * s.D ^ s.c, by omega, hc, ?_⟩⟩ + intro T hT + obtain ⟨d, hs', hr⟩ := ht T (by omega) + obtain ⟨z, hz, hl, hu⟩ := s.units hs hb T (by omega) + exact ⟨d, z, hs', hr, hz, hl, hu⟩ + +theorem Window.extension (w : Window k s) (K : Type) [Field K] [Fintype K] [Algebra w.F K] + {A T h : ℕ} (ht : T ≤ h ^ 4) (hk : A * (1 + h ^ 4) ^ A ≤ Fintype.card K) : + ExpChar K w.p ∧ A * (1 + T) ^ A ≤ Fintype.card K := by + have : CharP K w.p := charP_of_injective_algebraMap' w.F w.p + refine ⟨inferInstance, le_trans ?_ hk⟩ + gcongr + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Cost of a reset election over the working field -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Case Coloring Template + +variable {F : Type} [Field F] (Δ t d B : ℕ) +local notation "I" => Case F 1 d B +local notation "K" => keyBits d B +local notation "D" => digits Δ d B + +private theorem sourceSize : Cost (fun i : I => (Mix.Sources i.T).width) := by + refine (data_short d B).block.blocks.hosts.mono fun i => ?_ + rw [Format.width_vec, Format.width_vec] + +private theorem callWidth : Short (fun i : I => 1 + Mix.arity i.T (K i) (D i)) := + (short_const 1).add (summaryWidth Δ d B) + +private theorem tallySize : Cost (fun i : I => Mix.tallyCost i.T (K i) (D i)) := by + have hd := (summandWidth (F := F) Δ d B).block.blocks + have h₁ : Row (fun i : I => (Mix.Digits i.T (D i)).width) := + hd.mono fun _ => (Format.width_vec ..).le + have h₂ : Row (fun i : I => (Mix.Split i.T (D i)).width) := by + refine hd.mono fun i => ?_ + simp only [Mix.Split, Summand, Mixing.Matrix, Mixing.Num, Format.width_pair, Format.width_vec, + Format.width_addr, mul_add, le_refl] + have c := counterBits (F := F) d B + have hs := (Short.block (((short_const 3).mul c).add (((short_const 100).add c).pow 5))).blocks + have ht : Row (fun i : I => Mixing.collectCost i.height i.T.scheme.d i.T.CounterBits) := by + refine (hs.left Case.slots.short.block).mono fun i => ?_ + rw [Mixing.collectCost, mul_assoc] + have hw := callWidth (F := F) Δ d B + have hb := (Short.block (((short_const 100).add (indices_bound (F := F) Δ d B)).pow 5)).blocks + exact Mix.tallyCost_mixed (large := Case.long) (small := Case.block) + (F := Case.F) (T := fun i : I => i.T) + (k := K) (d := D) (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + Case.Child.parent.format (sourceSize d B) h₁ h₂ hw.block.blocks hw.long.row hb ht + +private theorem depthSize : Cost (fun i : I => (i.T.Depths (K i)).width) := by + refine (Mixed.long Case.m (Short.long (keys_bound d B).of_exp)).mono fun i => ?_ + rw [Format.width_vec, Format.width_addr] + +private theorem netSize : Cost (fun i : I => (i.T.NetworkDepths (K i)).width) := + pair_budget d B Case.Child.parent.format (depthSize d B) + +private theorem travelSize : Cost (fun i : I => (Mix.Travel i.T (K i)).width) := + pair_budget d B (netSize d B) (depthSize d B) + +private theorem nearSize : Cost (fun i : I => i.T.nearCost (K i)) := by + have hq : Cost (fun i : I => (Format.vec i.T.scheme.d (Perm i.m)).width) := by + refine ((Mixed.long Case.m hosts).left Case.slots.short.block).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_addr] + have projection := Mix.project_mixed (large := Case.long) (small := Case.block) + (height := Case.height) (hosts := Case.m) + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (netSize d B) (pair_budget d B (depthSize d B) hq) + have v := (hosts.add (keys_bound (F := F) d B).long.of_exp).add Case.slots.short.long + exact Mixed.add projection ((Mixed.long Case.m (((long_const 100).add v).pow 12)).scale 4) + +private theorem gatherSize : Cost (fun i : I => Mix.gatherCost i.T (K i)) := by + have hn : Cost (fun i : I => (i.T.Next (K i)).width) := by + refine (Mixed.long Case.m (Case.slots.short.long.mul (keys_bound d B).long.of_exp)).mono fun i + => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_addr] + exact Mix.gatherCost_mixed (large := Case.long) (small := Case.block) + (F := Case.F) (T := fun i : I => i.T) + (height := Case.height) (hosts := Case.m) (k := K) + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (travelSize d B) (netSize d B) (nearSize d B) hn + (Case.Child.parent.vector (windowWidth d B).long.row) + +private theorem waveSize : Cost (fun i : I => Mix.waveCost i.T (K i) (D i) (i.height - t - i.a)) + := by + have hn : Short (fun i : I => i.height - t - i.a) := + (height_short d B).mono (fun i => (Nat.sub_le ..).trans (Nat.sub_le ..)) + exact Mix.waveCost_mixed (large := Case.long) (small := Case.block) + (F := Case.F) (T := fun i : I => i.T) + (k := K) (d := D) (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (netSize d B) (depthSize d B) (gatherSize d B) + (callWidth Δ d B).long.row hn.block + +private theorem profileSize : Cost (fun i : I => Mix.profileCost i.T (K i) (D i)) := by + have a := (headWidth (F := F) d B).long.row + have b : Row (fun i : I => (Mixing.Num i.height i.T.profileBits).width) := by + refine ((Short.block (Case.bits.add counters)).blocks).mono fun i => ?_ + rw [Format.width_vec, Format.width_addr] + have sides := pair_budget d B (Case.Child.parent.vector a) (Case.Child.parent.vector b) + have rows : Cost (fun i : I => (i.T.profileShape (K i)).width) := + Case.Child.parent.vector ((a.add b).mono (fun _ => (Format.width_pair ..).le)) + have w := callWidth (F := F) Δ d B + exact Mix.profileCost_mixed (large := Case.long) (small := Case.block) + (F := Case.F) (T := fun i : I => i.T) + (k := K) (d := D) (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (netSize d B) (travelSize d B) (gatherSize d B) (sourceSize d B) + w.long.row w.block.blocks sides rows + +theorem summaryCost : Cost (fun i : I => + Mix.cost i.T (K i) (indices i.T Δ i.z B) (i.height - t - i.a)) := by + exact Mix.cost_mixed (large := Case.long) (small := Case.block) + (F := Case.F) (T := fun i : I => i.T) + (k := K) (d := D) (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + Case.Child.parent.format (Case.Child.parent.vector (stats_bound d B).long.row) + (depthSize d B) (netSize d B) (tallySize Δ d B) (waveSize Δ t d B) + (profileSize Δ d B) (profile_cost Δ d B) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Bounds for the complete dictionary writer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Packing Assembly Assembly.History.Reset Case Coloring + +variable {F : Type} + +variable [Field F] {Y l : ℕ} (P : Rotor F Y l) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B +local notation "keys" => keyBits d B +local notation "walk" => depth d B +local notation "dest" => child P Δ C t d B +local notation "growBy" => Reset.shift P Δ d B + +theorem graph_bound : Cost (fun i : I => (Tile.graph (dest i)).width) := + (child_bound P Δ C t d B).format.mono (fun i => Tile.graph_width_le (dest i)) + +theorem whole_bound : Cost (fun i : I => (Tile.whole i.T (dest i)).width) := by + have H := child_bound P Δ C t d B + have aux : Cost (fun i : I => (BatchDescent.Trail.controls i.T.scheme (dest i).scheme 0).width) + := by + have len := ((short_const 1).add (height_short (F := F) d B)).add Case.spans.short.of_exp + refine (H.cost (H.layer (Short.block (H.spans.mul len)))).mono fun i => ?_ + rw [BatchDescent.Trail.width_controls, H.single, i.h.single, add_zero, add_zero, add_zero, + pow_add 2 (dest i).scheme.h, mul_assoc, mul_assoc] + exact pair_budget d B H.format aux + +theorem printCost_bound {H : I → ℕ} (hs : Cost H) : Cost (fun i : I => + Tile.printCost i.T (dest i) (keys i) (walk i) (growBy i) (readCost P Δ C t d B i) (H i)) := by + have hd := child_bound P Δ C t d B + have hbody := carry_blocks P Δ C t d B (answer_bound P Δ C t d B) + have hg := hd.cost (hd.layer ((block_const 1).add (printWidth_bound P Δ C t d B).block)) + exact BatchDescent.Phase.MixedCost.resetPrint + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (pair_bound d B) hs (windowCost_bound P Δ C t d B) hg + (pair_budget d B (graph_bound P Δ C t d B) hbody) (whole_bound P Δ C t d B) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Charging relative headers to short records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Packing Assembly Assembly.History.Reset Case Coloring + +variable {F : Type} [Field F] {Y l : ℕ} (P : Rotor F Y l) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B +local notation "keys" => keyBits d B +local notation "walk" => depth d B +local notation "dest" => child P Δ C t d B +local notation "growBy" => Reset.shift P Δ d B + +theorem vertex_bound : Short (fun i : I => (Tile.vertexFormat i.T (dest i) (keys i) (walk i) + (growBy i)).width) := by + refine ((short_const 1).add (sample_bound P Δ d B)).mono fun i => ?_ + rw [Format.width_pair, Format.width_bit] + +theorem suffix_bound : Short (fun i : I => (History.Reset.Child.Suffix i.T.scheme.d (growBy i) + (dest i).scheme.d).width) := by + have H := child_bound P Δ C t d B + have addr := ((Case.slots.short.of_exp.add (short_const 1)).add H.growth.of_exp) + refine ((short_const 2).add (H.neighbors.mul ((short_const 2).add addr))).mono fun i => ?_ + simp only [History.Reset.Child.Suffix, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit] + rw [Format.width_addr] + +theorem headerWidth_bound : Short (fun i : I => Tile.headerWidth i.T (dest i) (keys i) (walk i) + (growBy i)) := + (vertex_bound P Δ C t d B).add (suffix_bound P Δ C t d B) + +theorem request_bound : Cost (fun i : I => (Tile.request i.T (dest i) (keys i) (walk i) (growBy + i)).width) := by + have nav : Cost (fun i : I => (Neighborhood.Rows i.m i.T.scheme.d).width) := by + refine (Mixed.long Case.m (Case.slots.short.long.mul hosts)).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_addr] + have keys' : Cost (fun i : I => + (Format.vec (i.m + growBy i) (Tile.vertexFormat i.T (dest i) (keys i) (walk i) (growBy + i))).width) := by + refine ((vertex_bound P Δ C t d B).long.row.expand (child_factor P Δ d B).short.block).mono fun + i => ?_ + rw [Format.width_vec] + exact pair_budget d B nav keys' + +theorem keyCost_bound : Cost (fun i : I => + Tile.headerCost i.T (dest i) (keys i) (walk i) (growBy i) (readCost P Δ C t d B i)) := by + have query := carry_blocks P Δ C t d B (sample_bound P Δ d B) + have init := (((pair_bound d B).add query).add (request_bound P Δ C t d B)).scale 100 + have gate := ((short_const 1).add (headerWidth_bound P Δ C t d B)) + exact (init.add (windowCost_bound P Δ C t d B)).add + ((Short.long gate).row.expand (child_factor P Δ d B).short.block) + +theorem headerCost_bound : Cost (fun i : I => + Tile.headerCost i.T (dest i) (keys i) (walk i) (growBy i) (readCost P Δ C t d B i) + + 4 * History.Reset.Child.buildCost i.m i.T.scheme.d (growBy i) (dest i).scheme.d) := by + have old : Long (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.short.long + have H := child_bound P Δ C t d B + have grow : Long (fun i : I => 2 ^ growBy i) := H.growth.long + have new : Long (fun i : I => 2 ^ (dest i).scheme.d) := H.neighbors.long + have build := History.Reset.Child.buildCost_mixed + (large := Case.long) (small := Case.block) + (height := Case.height) (hosts := Case.m) + (fun i => i.long_two) hosts old grow new + exact (keyCost_bound P Δ C t d B).add (Mixed.scale build 4) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Uniform bounds for issuing the frozen-station requests -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Packing Assembly Assembly.History.Reset Case Coloring + +variable {F : Type} [Field F] {Y l : ℕ} (P : Rotor F Y l) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B +local notation "keys" => keyBits d B +local notation "walk" => depth d B +local notation "dest" => child P Δ C t d B +local notation "growBy" => Reset.shift P Δ d B + +theorem queryWidth_bound : Short (fun i : I => + Tile.queryWidth i.T (dest i) i.A (keys i) (walk i) (growBy i) (i.n + i.A.k)) := by + have hj : Short (fun i : I => 2 ^ (i.n + i.A.k)) := tiles.short.exp_add stations.short + have hp : Short (fun _ : I => 2 ^ 0) := short_const 1 + have h := (child_bound P Δ C t d B).orders hj hp + exact (sample_bound P Δ d B).add (Width.pair Width.bit h) + +theorem attachedWidth_bound : Short (fun i : I => + Tile.attachedWidth i.T (dest i) i.A (keys i) (walk i) (growBy i) (i.n + i.A.k)) := by + have h := (printWidth_bound P Δ C t d B).add (headerWidth_bound P Δ C t d B) + refine (h.add (queryWidth_bound P Δ C t d B)).mono fun i => ?_ + unfold Tile.attachedWidth + omega + +theorem attachedCost_bound : Cost (fun i : I => + Tile.attachedCost i.T (dest i) i.A (keys i) (walk i) (growBy i) (i.n + i.A.k) + (readCost P Δ C t d B i)) := by + have hd := child_bound P Δ C t d B + have hs : Cost (fun i : I => i.A.format.width) := Case.Child.parent.attached Case.labels + have hwrite := printCost_bound P Δ C t d B (headerCost_bound P Δ C t d B) + have proj := ((whole_bound P Δ C t d B).add (hd.format.scale 2)).scale 4 + have hw := ((hs.scale 4).add ((pair_bound d B).scale 20)).add (hwrite.add proj) + have localGate := hd.cost (hd.layer ((block_const 1).add (queryWidth_bound P Δ C t d B).block)) + exact (hw.add (windowCost_bound P Δ C t d B)).add localGate + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Uniform costs of the reset controller over working fields -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing Case + +variable {F : Type} [Field F] {Y w : ℕ} (R : Rotor F Y w) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B +local notation "dst" => swept R Δ C t d B + +theorem zero_width : Short (fun _ : I => 2 ^ 0) := short_const 1 + +/-- The value specified by `width (R.extend i.F) i.A i.L i.u t i.z Δ C B i.r`. -/ +def arity (i : I) := width (R.extend i.F) i.A i.L i.u t i.z Δ C B i.r +/-- The value specified by `controlCost (R.extend i.F) i.A i.L i.u t i.z Δ C B i.r i.p`. -/ +def control (i : I) := controlCost (R.extend i.F) i.A i.L i.u t i.z Δ C B i.r i.p +/-- The value specified by `rebuildCost (R.extend i.F) i.A i.L i.u t i.z Δ C B i.r i.p`. -/ +def rebuild (i : I) := rebuildCost (R.extend i.F) i.A i.L i.u t i.z Δ C B i.r i.p + +theorem width_bound : Short (arity R Δ C t d B) := by + have h := swept_bound R Δ C t d B + have a := (summaryWidth (F := F) Δ d B).add (attachedWidth_bound R Δ C t d B) + have b := ((short_const 2).mul h.bits) + have c := h.rebuildWidth (seats_bound d B).short (p := fun _ => 0) (zero_width d B) + exact (a.add b).add c + +theorem control_bound : Cost (control R Δ C t d B) := by + have h := child_bound R Δ C t d B + have s : Cost (fun i : I => i.A.format.width) := Case.Child.parent.attached Case.labels + have setup := (s.scale 40).add (summaryCost Δ t d B) + have sweep := h.sweepCost (seats_bound d B).short (p := fun _ => 0) (zero_width d B) + exact (setup.add (attachedCost_bound R Δ C t d B)).add sweep + +theorem rebuild_bound : Cost (rebuild R Δ C t d B) := by + have h := swept_bound R Δ C t d B + exact h.rebuildCost (seats_bound d B).short (p := fun _ => 0) (zero_width d B) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- +# A reset phase over every finite extension + +The bound on physical expansion is chosen before fixing the full +graph degree. Exponents for the control costs can then depend on +that degree. Only the alphabet size uses the working field. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing Case + +variable {F : Type} [Field F] {Y w : ℕ} (R : Rotor F Y w) (Δ t : ℕ) + (κ : ℝ) + +/-- The quantity computed by `1 + 2 ^ t + gain t + Nat.clog 2 (resetPositions R Δ)`. -/ +def factor := 1 + 2 ^ t + gain t + Nat.clog 2 (resetPositions R Δ) + +variable (C d B : ℕ) +local notation "I" => Case F 1 d B +local notation "ρ" => (2 * resetWidth κ w) + +/-- The implements of type `Prop` for the given inputs. -/ +def Implements (i : I) (n k : ℕ) : Prop := + ∃ keys : Finset (Table i.F), keys.card ≤ k ∧ + Transforms i.F (i.short ^ i.H) keys (frame i.A i.L i.u i.z i.payload Δ C i.P) + (frame (target R Δ C t d B i) i.L i.u i.z i.payload 3 (C ^ (900 + Y + + 1)) (after i.L i.P i.K ρ ρ i.σ)) n + +/-- The demands used in the `Reset` construction. -/ +def demands (i : I) := + 3 + arity R Δ C t d B i + i.T.scheme.d + shift R Δ d B i + + (swept R Δ C t d B i).scheme.d + + i.A.shrinkWidth (swept R Δ C t d B i) (seats d B i) (copies t B) + +theorem demands_bound : Short (demands R Δ t C d B) := by + have h := swept_bound R Δ C t d B + have s := h.shrinkWidth (seats_bound d B).short (copies t B) + exact (((((short_const 3).add (width_bound R Δ C t d B)).add Case.slots.short.of_exp).add + h.growth.of_exp).add h.neighbors.of_exp).add s + +theorem output_of_control {size keys need : I → ℕ} (hcost : Total size) (hkeys : Short keys) (hneed + : Short need) + (run : ∀ i : I, i.u = i.v → factor R Δ t ≤ i.K → + demands R Δ t C d B i ≤ i.short ^ i.H → need i ≤ i.short ^ i.H → + Implements R Δ t κ C d B i (size i) (keys i)) : + ∃ H, 0 < H ∧ ∀ (E : Type) [Field E] [Fintype E] [Algebra F E] + {x y : Wire} {T : Template E} (A : Attachment T) (L : BorderLimit E x y) + (P : Bound) (p : Prices E) (r u v z payload : ℕ) (σ : ℝ), + Input A L P p r 1 u v z payload d B (factor R Δ t) H σ → + Nonempty (Output A L P p r u v z payload Δ 3 C (C ^ (900 + Y + 1)) (factor R Δ t) H ρ ρ σ) + := by + obtain ⟨a, ha⟩ := hcost + obtain ⟨b, hb⟩ := hkeys.bound + obtain ⟨c, hc⟩ := (meter_bound (F := F) t d B).bound + obtain ⟨q, hq⟩ := labels_bound R Δ C t d B + obtain ⟨g, hg⟩ := ((demands_bound R Δ t C d B).add hneed).bound + let H := 1 + degree C Y + 2 ^ (e t B) + a + b + c + q + g + have pos := Nat.two_pow_pos (e t B) + refine ⟨H, by unfold H; omega, ?_⟩ + intro E _ _ _ x y T A L P p r u v z payload σ h + have hv : u = v := h.units.trans (one_mul _) + subst v + let i : I := ⟨E, x, y, T, A, L, P, p, r, u, u, z, payload, _, H, σ, h⟩ + have step {m n : ℕ} (hm : 2 ≤ m) (hn : n ≤ H) : m ^ n ≤ m ^ H := + Nat.pow_le_pow_right (by omega) hn + have hp := (hg i).trans (step i.short_two (by unfold H; omega)) + obtain ⟨labels, hl, hnet⟩ := run i rfl le_rfl ((Nat.le_add_right ..).trans hp) ((Nat.le_add_left + ..).trans hp) + have lim : q ≤ H := by unfold H; omega + have count : 2 ^ e t B ≤ H := by unfold H; omega + let N := swept R Δ C t d B i + refine ⟨⟨N, target R Δ C t d B i, Nat.sub_add_cancel h.group, Nat.le_add_right .., ?_, ?_, h.full, + rfl, count, ?_, ?_, (hc i).trans (step i.base_two (by unfold H; omega)), ?_, labels, + (hl.trans (hb i)).trans (step i.short_two (by unfold H; omega)), hnet.mono ?_⟩⟩ + · change T.scheme.m + (T.scheme.h - (T.scheme.h - r) + Nat.clog 2 (resetPositions R Δ)) ≤ _ + rw [Nat.sub_sub_self h.group] + unfold factor + have := Nat.two_pow_pos t + omega + · exact (child_degree R Δ C t d B i).le.trans (by unfold H; omega) + · change T.scheme.h - (T.scheme.h - r) + A.k ≤ _ + rw [Nat.sub_sub_self h.group] + omega + · change 2 ^ max A.e (e t B) ≤ 2 ^ A.e + H + rcases max_choice A.e (e t B) with he|he <;> rw [he] + · exact Nat.le_add_right .. + · exact count.trans (Nat.le_add_left ..) + · exact (hq i).trans (Nat.add_le_add (Nat.mul_le_mul_right _ lim) (step i.base_two lim)) + · refine (ha i).trans ?_ + change 2 ^ i.m * i.long ^ a + 2 ^ (i.m + i.height) * i.block ^ a + (wd x + wd y) * i.outer ^ a ≤ + 2 ^ i.m * i.long ^ H + 2 ^ (i.m + i.height) * i.block ^ H + (wd x + wd y) * i.outer ^ H + have hi : a ≤ H := by unfold H; omega + exact Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ (step i.long_two hi)) + (Nat.mul_le_mul_left _ (step i.block_two hi))) (Nat.mul_le_mul_left _ (step i.outer_two hi)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Room for transferring exterior bits between a host and its children -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing Case + +variable {F : Type} [Field F] {Y w : ℕ} (R : Rotor F Y w) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B +local notation "dst" => swept R Δ C t d B +local notation "xtra" => shift R Δ d B +local notation "s" => seats d B + +/-- The quantity computed by `i.A.carryWidth (dst i) (s i) (xtra i) i.payload + 2 + 2 * (xtra i) ++ i.payload`. -/ +def requirement (i : I) := i.A.carryWidth (dst i) (s i) (xtra i) i.payload + + 2 + 2 * (xtra i) + i.payload + +theorem requirement_bound (h : Short (fun i : I => i.A.carryWidth (dst i) (s i) (xtra i) + i.payload)) : + Short (requirement R Δ C t d B) := by + have hb : Base (fun i : I => i.payload) := by + refine Poly.of_le base_two fun i => ?_ + unfold Case.base Contraction.base + exact (Nat.le_add_left ..).trans (Nat.le_add_right ..) + exact ((h.add (short_const 2)).add ((short_const 2).mul (child_factor R Δ d B).short.of_exp)).add + hb.short + +private theorem large {m v j q : ℕ} (h : 2 + 2 * j + q ≤ m) (hv : 2 * m ≤ v) : + 2 ^ j * ((q + 1) * (2 ^ m + 2 ^ (m + j))) < 2 ^ v := by + calc + _ ≤ 2 ^ j * (2 ^ q * (2 ^ (m + j) + 2 ^ (m + j))) := + Nat.mul_le_mul_left _ (Nat.mul_le_mul (Nat.lt_two_pow_self (n := q)) + (Nat.add_le_add_right (Nat.pow_le_pow_right (by decide) (by omega)) _)) + _ = 2 ^ (j + q + (m + j) + 1) := by rw [pow_succ, pow_add, pow_add, pow_add, pow_add]; ring + _ < _ := Nat.pow_lt_pow_right (by decide) (by omega) + +theorem volume (i : I) (h : requirement R Δ C t d B i ≤ i.short ^ i.H) : + 2 ^ (xtra i) * ((i.payload + 1) * (2 ^ i.m + 2 ^ (dst i).scheme.m)) < 2 ^ i.p.w := by + have hs : requirement R Δ C t d B i ≤ i.m := h.trans i.h.small + unfold requirement at hs + exact large (m := i.m) (j := xtra i) (by omega) i.h.upper + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Installing one elected reset over the working field -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing +section +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ κ : ℝ} + +namespace Choice +variable [NeZero Y] [NeZero w] {h : Input A L P p r 1 u u z payload d B K H σ} + {s : Slice Δ Y w t} {hC : Δ ≤ C} {hk : 2 ^ t ≤ K} {R : Rotor F Y w} {hc : 1 ≤ κ} + {cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w} + (E : Choice h s hC hk R hc cost) + +local notation "src" => (frame A L u z payload Δ C P) +local notation "N" => Template.sweep (raw R T L u t z Δ C B r) +local notation "k'" => slots A r +local notation "sfx" => History.Reset.Child.extra R Δ (T.scheme.h - (T.scheme.h - r)) + +open scoped Classical in +private theorem ship {v : ℕ} {W : Set (Table F)} (hu : 3 ≤ v) (hm : 1 ≤ T.scheme.m) + (ht : 2 ^ sfx * ((payload + 1) * (2 ^ T.scheme.m + 2 ^ (N).scheme.m)) < 2 ^ p.w) + (hw : A.carryWidth N k' sfx payload ≤ v) (gate : A.carryGate N k' sfx payload ∈ W) : + E.Carries v W (A.carryCost N k' 0 sfx x y payload p) := by + have hm' : 1 ≤ (N).scheme.m := hm.trans (Nat.le_add_right _ sfx) + unfold Carries next + exact Attachment.carry E.swept (fun q => q.val) E.result (fun q => q.property.2) E.fits + (Match.rowIndex T.scheme.m sfx) (fun _ => rfl) (fun _ _ => rfl) E.exterior + hu hm hm' ht hw gate + +end Choice + +end + +variable {F : Type} [Field F] {Y w : ℕ} (R : Rotor F Y w) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B +local notation "N" => swept R Δ C t d B +local notation "j" => shift R Δ d B +local notation "k" => seats d B + +open scoped Classical in +/-- The value specified by `runCost (R.extend i.F) i.A i.L i.u t i.z Δ C B i.r i.payload i.p + +i.A.carryCost (N i) (k i) 0 (j i) i.x i.y i.payload i.p`. -/ +def work (i : I) := + runCost (R.extend i.F) i.A i.L i.u t i.z Δ C B i.r i.payload i.p + + i.A.carryCost (N i) (k i) 0 (j i) i.x i.y i.payload i.p + +open scoped Classical in +theorem transfer [NeZero Y] [NeZero w] (s : Slice Δ Y w t) + (hC : Δ ≤ C) {κ : ℝ} (hc : 1 ≤ κ) (cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w) + (i : I) (hv : i.u = i.v) (hK : factor R Δ t ≤ i.K) + (hd : demands R Δ t C d B i ≤ i.short ^ i.H) (hr : requirement R Δ C t d B i ≤ i.short ^ i.H) : + Implements R Δ t κ C d B i (work R Δ C t d B i) 19 := by + have hu : Input i.A i.L i.P i.p i.r 1 i.u i.u i.z i.payload d B i.K i.H i.σ := by + have h := i.h + rwa [← hv] at h + have ht : 2 ^ t ≤ i.K := by unfold factor at hK; omega + have hg : gain t ≤ i.K := by unfold factor at hK; have := Nat.two_pow_pos t; omega + obtain ⟨E⟩ : Nonempty (Choice hu s hC ht (R.extend i.F) hc cost) + := ⟨choose hu s hC ht (R.extend i.F) hc cost⟩ + have hm : (N i).scheme.m = i.m + j i := rfl + have hs : i.short ^ i.H ≤ i.m := i.h.small + have hw : 2 * i.m ≤ i.p.w := i.h.upper + unfold demands at hd + have h₃ : 3 ≤ i.short ^ i.H := by omega + have h₁ : 1 ≤ i.m := by omega + have hwidth : arity R Δ C t d B i ≤ i.short ^ i.H := by omega + have hunder : i.m + i.T.scheme.d ≤ i.p.w := by omega + have hlarge : (N i).scheme.m + (N i).scheme.d ≤ i.p.w := by omega + have hfit : i.A.shrinkWidth (N i) (k i) (copies t B) ≤ i.short ^ i.H := by omega + obtain ⟨labels, hcard, net⟩ := E.controller h₃ hwidth h₁ hunder hlarge hg hfit + let gate := i.A.carryGate (N i) (k i) (j i) i.payload + let W := insert gate labels + have ha : i.A.carryWidth (N i) (k i) (j i) i.payload ≤ i.short ^ i.H := by + unfold requirement at hr + omega + have carry : E.Carries (i.short ^ i.H) W (i.A.carryCost (N i) (k i) 0 (j i) i.x i.y i.payload + i.p) := by + exact E.ship h₃ h₁ (volume R Δ C t d B i hr) ha (Finset.mem_insert_self ..) + unfold Implements target work seats swept child + refine ⟨W, (Finset.card_insert_le ..).trans (by omega), ?_⟩ + exact net (Finset.subset_insert ..) carry + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Uniform attached reset at fixed core degree -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Packing + +namespace Reset +open Case + +variable {F : Type} [Field F] {Y w : ℕ} (R : Rotor F Y w) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B + +private theorem enough : Short (requirement R Δ C t d B) := by + have h := swept_bound R Δ C t d B + exact requirement_bound R Δ C t d B (h.carryWidth (seats_bound d B).short h.growth) + +private theorem work_bound : Total (work R Δ C t d B) := by + have h := swept_bound R Δ C t d B + have slots := (seats_bound (F := F) d B).short + have gates : Short (fun _ : I => 2 ^ 0) := short_const 1 + have req := h.requests slots (p := fun _ => 0) gates + have supply := ((control_bound R Δ C t d B).add (req.scale 24)).add (rebuild_bound R Δ C t d B) + have inputs : Total (fun i : I => (Attachment.payload i.x i.y i.payload i.m).width) := + Case.Child.parent.payload + have body := ((Cost.total supply).add (inputs.scale 4)).add (h.shrinkCost slots (copies t B)) + exact body.add (h.carryCost slots (p := fun _ => 0) gates h.growth) + +end Reset + +theorem resetRule (F : Type) [Field F] : ResetRule F := by + intro y w Δ R κ hw hΔ hy hc cost + let _ : NeZero w := ⟨hw.ne'⟩ + have hcost : (Fintype.card R.E : ℝ) ≤ κ * (2 ^ y : ℕ) * w + := by simpa only [Nat.cast_pow, Nat.cast_ofNat] using cost + obtain ⟨t, s⟩ := BatchDescent.Restore.exists_slice Δ (2 ^ y) w hy hΔ + refine ⟨Reset.factor R Δ t, by unfold Reset.factor; positivity, ?_⟩ + intro C d B hC + exact Reset.output_of_control R Δ t κ C d B (Reset.work_bound R Δ C t d B) + (Case.short_const 19) (Reset.enough R Δ C t d B) + (fun i hi hk hd hr => Reset.transfer R Δ C t d B s hC hc hcost i hi hk hd hr) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Joint choice of concentration parameters and encoded contractions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction + +theorem restart_plan {k : Type} [Field k] [Finite k] (tag : Radix.WideTag k) + (sync : MatrixExponent.Prices.SharedPrice (AlgebraicClosure k)) {δ : ℝ} (hδ : 0 < δ) (hd : δ + ≤ 1) : + ∃ s : Plan, s.Fits ∧ 0 < s.v ∧ 0 < s.p ∧ (s.p : ℝ) ≤ s.v * (1 + δ / 3) ∧ + 0 < s.b ∧ 0 < s.n ∧ 0 < s.K ∧ Nonempty (Window k s) ∧ ∀ d, ∃ K, 0 < K ∧ Restarts k s d K := by + obtain ⟨s, hC, large, hs, hv, hp, gain, q⟩ := plan (subroundRule k) (resetRule k) tag hδ hd + (Rounds.Input.terminalExponent localDegree 10) (localDegree + + 2 * SphereScale.budget localDegree) + exact ⟨s, hs, hv, hp, gain, q.unit, q.steps, q.overhead, makeWindow sync hs q.unit hC large, + restarts hs q⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Reset/Label.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Reset/Label.lean new file mode 100644 index 0000000000..b7d64ebae0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Reset/Label.lean @@ -0,0 +1,746 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Beat.Fanout +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.ShortNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Apply +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Restore.Elect +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Factor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Attachment.WriteNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Ports.Correspondence +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames + +/-! # Record and payload widths after reattachment -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case.Child +open Coloring Assembly Width BatchDescent + +variable {κ : Type} [Field κ] {b d B : ℕ} {N : (i : Case κ b d B) → Template i.F} + {δ j p : Case κ b d B → ℕ} (h : Child N δ) (hj : Short (fun i => 2 ^ j i)) (hp : Short (fun i + => 2 ^ p i)) +local notation "I" => Case κ b d B + +include h in +theorem payload : Total (fun i : I => (Attachment.payload i.x i.y i.payload (N i).scheme.m).width) + := by + have u := (h.cost (long_const 1).row).total + have v : Total (fun i : I => (wd i.x + wd i.y) * 1) := (outer_const 1).total + refine (((u.add v).scale 2).left (loads.add (outer_const 1))).mono fun i => ?_ + simpa only [mul_one, Attachment.payload, Attachment.volume, add_assoc] + using Fmt.width_payload (N i).scheme.m + (Attachment.volume i.x i.y (N i).scheme.m) i.payload + +include h hj in +theorem transport : Short (fun i : I => (i.A.transport (N i) (j i)).ℓ) := by + have t : Short (fun i : I => 2 ^ (i.A.spanBits (N i))) := expMax ports.short h.spans + have member : Short (fun i : I => i.A.member.width) + := pair bit (pair (addr labels) (addr stations.short.of_exp)) + have target := pair (addr h.neighbors.of_exp) (pair (addr hj.of_exp) (addr t.of_exp)) + exact pair (addr h.bits) (vec hj (pair member (vec t (pair bit (pair bit target))))) + +include h hj in +theorem shrink (c : ℕ) : Short (fun i : I => (i.A.shrink (N i) (j i) c).ℓ) := by + have t : Short (fun i : I => 2 ^ (i.A.spanBits (N i))) := expMax ports.short h.spans + have endpt := (((short_const 2).add h.neighbors.of_exp).add hj.of_exp).add t.of_exp + have extra := hj.mul (((short_const 1).add stations.short.of_exp).add (t.mul endpt)) + refine ((h.bits.add ((short_const c).mul labels)).add extra).mono fun i => ?_ + exact (i.A.short_width (N i) (j i) c).le + +include h hj in +theorem shrinkWidth (c : ℕ) : Short (fun i : I => i.A.shrinkWidth (N i) (j i) c) := + (h.transport hj).add (h.shrink hj c) + +include h hj in +theorem shrinkCost (c : ℕ) : Total (fun i : I => i.A.shrinkCost (N i) (j i) c i.x i.y i.payload) + := by + have labels := h.cost (h.layer ((block_const 1).add (h.shrinkWidth hj c).block)) + exact (Cost.total ((h.format.scale 4).add labels)).add (h.payload.scale 4) + +include h hj hp in +theorem orders : Short (fun i : I => (i.A.orders (N i) (j i) (p i)).width) := by + have a : Short (fun i : I => i.T.scheme.k) := (short_const 0).mono fun i => (i.h.single).le + have p₁ := pair bit (pair (addr hp.of_exp) (pair (addr levels.short) (pair (addr a) (addr + Case.spans.short.of_exp)))) + have p₂ : Short (fun i : I => i.A.pointer.width) + := pair bit (pair (addr levels.short) (addr stations.short.of_exp)) + exact pair (vec h.spans p₁) (vec hj p₂) + +include h hj hp in +theorem requests : Cost (fun i : I => (i.A.Requests (N i) (j i) (p i)).width) := + pack (parent.attached labels) (pack h.format (h.vector (h.stack (pair bit (h.orders hj hp))))) + +include h hj hp in +theorem sweepCost : Cost (fun i : I => i.A.sweepCost (N i) (j i) (p i)) := by + have tags := h.layer (((block_const 1).add h.bits.block).add h.bits.block) + have graph := Long.row ((long_const 4).mul (h.neighbors.long.mul h.address)) + have aux : Cost (fun i : I => (Format.vec (N i).scheme.m (N i).header).width) := by + refine h.format.mono fun i => ?_ + rw [Format.width_pair] + exact Nat.le_add_left .. + have orders := h.vector (h.stack (pair bit (h.orders hj hp))) + have src : Cost (fun i : I => i.A.format.width) := parent.attached labels + refine ((src.scale 4).add (((h.cost (graph.add tags)).add (aux.scale 4)).add (orders.scale + 4))).mono fun i => ?_ + rw [Attachment.sweepCost, updateCost, Format.width_addr] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case.Child +end + +/- # Transporting a ready border across an exact change of core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Packing Assembly.Attachment + +variable {F : Type} [Field F] {D Y : Template F} {A : Attachment D} {x y : Wire} + {k m u v z Δ C Δ' C' : ℕ} {L : BorderLimit F x y} {P P' : Bound} + (X : A.Data x y u) (q : A.Query Y k m) (G : HostNet F X.L Y.scheme.h v) + (old : A.Encloses q.old X.G X.Z) (fresh : Y.Encodes q.fresh G) (slot : X.T → Coloring.B k) + (h : q.R.Moves old fresh slot) (ok : Relocation.WriteActive fresh q.active) + (move : q.M.Agrees old.core.post.toPresentation fresh.post.toPresentation) (full : Y.full = true) + +open scoped Classical in +theorem moved_ready (hx : Ready A L z Δ C P X) (live : Nonempty G.V) + (simple : Δ' ≤ 3 → ∀ e, G.src e ≠ G.dst e) + (low : ∀ j, v ≤ fresh.post.toPresentation.borderWidth j) + (stay : X.G.Preserves G) (hb : G.Bounded Δ' C' P'.load) + (hw : (G.X : ℝ) ≤ P'.width) (hm : (G.mass : ℝ) ≤ P'.mass) : + Ready (A.transport Y.sweep k) L z Δ' C' P' (q.apply h ok move full) where + neutral := G.diagram.sweep_neutral + live := live + simple := simple + span := q.floor h ok move full low + parallel j := (hx.parallel j).trans (stay.parallelBits _ j) + scale := hx.scale + discount := hx.discount + cap := hx.cap + total := hx.total + charge := hx.charge + test := hx.test + bounded := hb + width := hw + mass := hm + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Control parameters for a reset with attached border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Packing Assembly + +export BatchDescent.Restore (gain tolerance Slice) + +variable {F : Type} {x y : Wire} + +open scoped Classical in +/-- The quantity computed by `4 * (Template.Encodes.margin Δ) ^ 2 + 4 + T.scheme.h + Nat.clog 2 +(1 + B ^ 3 * z)`. -/ +def indices (T : Template F) (Δ z B : ℕ) := + 4 * (Template.Encodes.margin Δ) ^ 2 + 4 + T.scheme.h + Nat.clog 2 (1 + B ^ 3 * z) + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def e (t B : ℕ) := Nat.clog 2 (gain t * B) +open scoped Classical in +/-- The quantity computed by `B * gain t * B`. -/ +def copies (t B : ℕ) := B * gain t * B +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def c (t z B : ℕ) := Nat.clog 2 (copies t B * z + 1) + +open scoped Classical in +/-- The quantity computed by `Template.Meter.bounded (c t z B) (1 / (L.denom : ℝ)) (1 / (2 : ℝ) +^ L.discount)`. -/ +abbrev meter (L : BorderLimit F x y) (t z B : ℕ) := + Template.Meter.bounded (c t z B) (1 / (L.denom : ℝ)) (1 / (2 : ℝ) ^ L.discount) + +open scoped Classical in +/-- The quantity computed by `History.Reset.overhead T.scheme (e t B) + T.scheme.ℓ * copies t +B`. -/ +abbrev cap [Fintype F] (T : Template F) (t B : ℕ) := + History.Reset.overhead T.scheme (e t B) + T.scheme.ℓ * copies t B +open scoped Classical in +/-- The quantity computed by `History.Reset.Book.make T.scheme u (e t B) (cap T t B) T.order +(Finset.range (B * z + 1))`. -/ +abbrev book [Fintype F] (T : Template F) (u t z B : ℕ) := + History.Reset.Book.make T.scheme u (e t B) (cap T t B) T.order (Finset.range (B * z + 1)) + +variable [Field F] [Fintype F] {Y w : ℕ} (R : Rotor F Y w) + (T : Template F) (L : BorderLimit F x y) (u t z Δ C B r : ℕ) + +open scoped Classical in +/-- The quantity computed by `T.reset R Δ C (T.scheme.h - r) (book T u t z B) (meter L t z B)`. -/ +abbrev raw := T.reset R Δ C (T.scheme.h - r) (book T u t z B) (meter L t z B) +open scoped Classical in +/-- The value specified by `(raw R T L u t z Δ C B r).sweep`. -/ +abbrev next := (raw R T L u t z Δ C B r).sweep + +open scoped Classical in +/-- The quantity computed by `T.scheme.h - (T.scheme.h - r) + A.k`. -/ +def slots {T : Template F} (A : Attachment T) (r : ℕ) := T.scheme.h - (T.scheme.h - r) + A.k + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- +# Uniform widths over a changing working field + +The base bounds the logarithm of the alphabet and the precision of +the physical counters. Only the cost of retaining old labels is +linear in the full input label length. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Packing Assembly Coloring Case + +variable {F : Type} [Field F] {Y w : ℕ} (R : Rotor F Y w) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B + +/-- The value specified by `raw (R.extend i.F) i.T i.L i.u t i.z Δ C B i.r`. -/ +abbrev child (i : I) := raw (R.extend i.F) i.T i.L i.u t i.z Δ C B i.r +/-- Uses `History.Reset.Child.extra R Δ i.n` as the representation. -/ +abbrev shift (i : I) := History.Reset.Child.extra R Δ i.n +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev keyBits (i : I) := Nat.clog 2 (i.height + 1) +/-- The quantity computed by `i.n + 8`. -/ +abbrev depth (i : I) := i.n + 8 + +theorem child_factor : Base (fun i : I => 2 ^ shift R Δ d B i) := + tiles.exp_add (base_const (2 ^ Nat.clog 2 (resetPositions R Δ))) + +/-- The least binary width whose power of two reaches the stated size. -/ +def degree (C Y : ℕ) := Nat.clog 2 (4 + terminalWidth C Y) + +theorem child_degree (i : I) : (child R Δ C t d B i).scheme.d = degree C Y := by + change History.Reset.Child.width C Y i.T.full = _ + rw [i.h.full] + rfl + +private theorem clog_mul (n z : ℕ) : Nat.clog 2 (n * z + 4) ≤ n + 4 + Nat.clog 2 (1 + z) := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_add] + calc + _ ≤ (n + 4) * (1 + z) := by simp only [mul_add, add_mul, mul_one]; omega + _ ≤ _ := Nat.mul_le_mul Nat.lt_two_pow_self.le (Nat.le_pow_clog (by decide) _) + +theorem meter_bound : Base (fun i : I => (meter i.L t i.z B).count) := by + have h : Base (fun i : I => c t i.z B) := + ((base_const (copies t B + 4)).add units).mono fun i => + (Nat.clog_mono_right _ (by omega : copies t B * i.z + 1 ≤ copies t B * i.z + + 4)).trans (clog_mul ..) + exact (base_const 3).mul h + +theorem palette_bound : Base (fun i : I => (book i.T i.u t i.z B).d) := by + refine ((base_const (B + 4)).add units).mono fun i => ?_ + simp only [book, History.Reset.Book.make, History.Reset.Book.lenBits, History.lengthBits, + Finset.card_range] + exact clog_mul B i.z + +theorem overhead_bound : Base (fun i : I => History.Reset.overhead i.T.scheme (e t B)) := by + have hl : Base (fun i : I => History.Dense.used i.T.scheme.ℓ) := by + refine lengths.mono fun i => ?_ + exact Nat.clog_mono_right _ (by omega) + have hk : Base (fun i : I => 1 + i.T.scheme.k) := + (base_const 1).mono fun i => by rw [i.h.single, Nat.add_zero] + have hs : Base (fun i : I => Nat.clog 2 (Fintype.card i.F)) := by + refine blocks.mono fun i => ?_ + rw [← Nat.card_eq_fintype_card] + exact i.h.alphabet + have he : Base (fun _ : I => 2 ^ (e t B)) := base_const _ + have hy := he.of_exp.add (base_const 1) + have ht := (((he.add he).add (base_const 1)).pow 3).mul (base_const 8) + have hh := (hy.add (he.mul (hk.add (spans.mul hy)))).add (ht.mul hs) + refine (hh.add (he.mul hl)).mono fun i => ?_ + simp only [History.Reset.overhead, History.Reset.shapeWidth, History.Reset.tripleCost, + History.Reset.Addr, Coloring.B, Fintype.card_sum, Fintype.card_fin] + rfl + +/-- The added used in the `Reset` construction. -/ +def added (i : I) := (History.Post.headerFmt (child R Δ C t d B i).scheme.d (e t B) + (book i.T i.u t i.z B).d).width + History.Reset.overhead i.T.scheme (e t B) + +theorem added_bound : Base (added R Δ C t d B) := by + have one := (base_const 1 : Base (fun _ : I => _)) + have he : Base (fun _ : I => 2 ^ (e t B)) := base_const _ + have hd : Base (fun i : I => (child R Δ C t d B i).scheme.d) := + (base_const (degree C Y)).mono fun i => (child_degree R Δ C t d B i).le + have hdr := one.add (he.mul ((palette_bound (F := F) t d B).add (one.add (one.add (hd.add + he.of_exp))))) + refine (hdr.add (overhead_bound t d B)).mono fun i => ?_ + simp only [added, History.Post.headerFmt, History.Post.field, Format.width_pair, + Format.width_vec, Format.width_addr] + rfl + +theorem label_eq (i : I) : + (child R Δ C t d B i).scheme.ℓ = added R Δ C t d B i + i.T.scheme.ℓ * copies t B := by + change (History.Post.record _ _ _ (.addr _)).width = _ + simp only [added, book, History.Reset.Book.make, cap, History.Post.record, History.Post.headerFmt, + Format.width_pair, Format.width_addr, add_assoc] + +theorem bits_bound : Short (fun i : I => (child R Δ C t d B i).scheme.ℓ) := + ((added_bound R Δ C t d B).short.add (Case.bits.mul (short_const (copies t B)))).mono + (fun i => (label_eq R Δ C t d B i).le) + +theorem child_bound : Case.Child (child R Δ C t d B) (shift R Δ d B) := by + refine ⟨fun _ => Nat.sub_le .., fun _ => le_rfl, (child_factor R Δ d B).short, fun _ => rfl, + short_const (2 ^ e t B), ?_, bits_bound R Δ C t d B, (meter_bound t d B).short⟩ + exact (short_const (2 ^ degree C Y)).mono fun i + => (congrArg (2^·) (child_degree R Δ C t d B i)).le + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- +# Precision for a reset with two kinds of charge + +The exterior and the incidence history have different denominators. +Their product clears both denominators, uniformly over all states. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C : ℕ} {σ : ℝ} + +open scoped Classical in +/-- The quantity computed by `L.denom * 2 ^ L.discount`. -/ +def denominator (L : BorderLimit F x y) := L.denom * 2 ^ L.discount + +omit [Field F] in +open scoped Classical in +theorem limits (T : Template F) (Δ z B : ℕ) : + let b := indices T Δ z B + 4 * (Template.Encodes.margin Δ) ^ 2 < 2 ^ b ∧ 6 * 2 ^ T.scheme.h < 2 ^ b ∧ B ^ 3 * z < 2 ^ b + := by + dsimp only + unfold indices + constructor + · exact (by omega : _ ≤ 4 * (Template.Encodes.margin Δ) ^ 2 + 4 + T.scheme.h+ + Nat.clog 2 (1 + B ^ 3 * z)).trans_lt Nat.lt_two_pow_self + constructor + · calc + _ < 2 ^ 3 * 2 ^ T.scheme.h := Nat.mul_lt_mul_of_pos_right (by decide) (by positivity) + _ ≤ _ := by rw [← pow_add]; exact Nat.pow_le_pow_right (by decide) (by omega) + · exact (Nat.lt_add_one _).trans_le (by + rw [add_comm (B ^ 3 * z)] + exact (Nat.le_pow_clog (by decide) _).trans (Nat.pow_le_pow_right (by decide) + (Nat.le_add_left ..))) + +variable (h : Input A L P p r 1 u u z payload d B K H σ) + (q : (frame A L u z payload Δ C P).state) + +include h in +open scoped Classical in +theorem integer (v : q.val.G.V) (i : Cell T.scheme.h) : + ∃ n : Coloring.B (indices T Δ z B), q.val.G.load v i * denominator L = n.val := by + let G := q.val.G + let c := (v, i) + have Hq := q.property.1 + have hm : G.mass ≤ q.val.L.cap := by + rw [Hq.cap] + exact Nat.cast_le.mp (Hq.mass.trans (le_trans (le_add_of_nonneg_right + (mul_nonneg (by norm_num) h.width)) h.history)) + choose f _ hf using Hq.charge + let park := ∑ j, if G.park j = c then f j else 0 + have hp : push G.park q.val.L.charge c = (park : ℝ) := by + simp only [park, Nat.cast_sum, Nat.cast_ite, Nat.cast_zero, push, hf] + let n := (G.tetherLoad c + Packing.degree G.pair c * u) * denominator L + park * 2 ^ L.discount + + G.past c * L.denom + have he : G.load v i * denominator L = (n : ℝ) := by + rw [HostNet.load, hp, HostNet.rate, ite_eq_left hm, Hq.scale, Hq.discount] + simp only [n, c, denominator, Nat.cast_add, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat] + have hpos : (L.denom : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr h.denom.ne' + field_simp + have hn : n ≤ B ^ 3 * z := by + have hd : denominator L ≤ B * B := Nat.mul_le_mul h.scale h.discount + apply (Nat.cast_le (α := ℝ)).mp + rw [← he] + calc + _ ≤ ((B : ℝ) * z) * (B * B : ℕ) := mul_le_mul ((Hq.bounded.2.2 v i).trans h.ceiling) + (Nat.cast_le.mpr hd) (by positivity) (by positivity) + _ = _ := by push_cast; ring + exact ⟨⟨n, hn.trans_lt (limits T Δ z B).2.2⟩, he⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Electing a reset at the current physical load bound -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ : ℝ} + (h : Input A L P p r 1 u u z payload d B K H σ) (s : Slice Δ Y w t) + (hC : Δ ≤ C) (hk : 2 ^ t ≤ K) (q : (frame A L u z payload Δ C P).state) +local notation "a" => (T.scheme.h - r) +local notation "W" => ((2 : ℝ) ^ t * P.load) +local notation "g" => Template.Encodes.margin Δ + +include h in +open scoped Classical in +private theorem positive : 0 < P.load := + (Nat.cast_pos.mpr (h.zpos.trans_le h.vpos)).trans_le h.load + +include h in +open scoped Classical in +private theorem normalized (x : ℝ) (hb : x ≤ P.load) : x / W ≤ 1 / (2 : ℝ) ^ t := by + have := positive h + rw [div_le_div_iff₀ (by positivity) (by positivity), one_mul, mul_comm x] + exact mul_le_mul_of_nonneg_left hb (by positivity) + +include h in +open scoped Classical in +theorem unit : (u : ℝ) / W ≤ 1 / (2 : ℝ) ^ t := normalized h u h.load + +include h hk in +open scoped Classical in +theorem slack : W * (Fintype.card q.val.G.V * 2 ^ a : ℕ) ≤ σ := by + have hv : Fintype.card q.val.G.V ≤ 2 ^ T.scheme.m := by + simpa using Fintype.card_le_of_injective _ q.val.q.core.post.host.injective + exact BatchDescent.slack_of_width_count (positive h).le h.group hk hv h.slack + +include h hC s hk in +open scoped Classical in +theorem ok : Template.Encodes.Fits (G := q.val.G) a t Δ C g (denominator L) + (Nat.clog 2 (T.scheme.h + 1)) (indices T Δ z B) W (tolerance Δ Y) where + corePos := by have := s.core; omega + full := hC + late hf := by rw [h.full] at hf; cases hf + gap := by + have := (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp (hk.trans h.room) + have := h.group + omega + depth := Nat.le_pow_clog (by decide : 1 < 2) _ + integer := integer h q + denominator := Nat.mul_pos h.denom (Nat.two_pow_pos _) + width := h.zpos.trans_le h.vpos + margin := by unfold Template.Encodes.margin; have := s.core; positivity + widthLimit := (limits T Δ z B).1 + weightLimit := (limits T Δ z B).2.1 + capacity := mul_pos (by positivity) (positive h) + bound v i := normalized h _ (q.property.1.bounded.2.2 v i) + cdeg := q.property.1.bounded.1 + ndeg := q.property.1.bounded.2.1 + small := s.small + +open scoped Classical in +/-- Computes the poll by the application `q.val.q.core.elected (ok h s hC hk q) s.enough s.space +(unit (t := t) h)`. -/ +abbrev poll := q.val.q.core.elected (ok h s hC hk q) s.enough s.space (unit (t := t) h) +open scoped Classical in +/-- Computes the board by the application `History.Reset.electedBoard q.val.q.core (ok h s hC hk +q) s.enough s.space (unit (t := t) h)`. -/ +abbrev board := + History.Reset.electedBoard q.val.q.core (ok h s hC hk q) s.enough s.space (unit (t := t) h) + +open scoped Classical in +theorem fits (R : Rotor F Y w) {c : ℝ} (hc : 1 ≤ c) (cost : (Fintype.card R.E : ℝ) ≤ c * Y * w) : + (poll h s hC hk q).Fits R c where + upper := hC + full := q.property.1.bounded.2.1 + nonneg := zero_le_one.trans hc + cost := cost + small := by + change (Detour.steps (terminalWidth Δ Y) : ℝ) * tolerance Δ Y ≤ 1 + unfold tolerance + rw [mul_one_div, div_le_one (by positivity)] + exact le_add_of_nonneg_right zero_le_one + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Linear propagation of label lengths under an attached reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Packing Assembly Coloring Case + +variable {F : Type} [Field F] {Y w : ℕ} (R : Rotor F Y w) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B +local notation "Z" => child R Δ C t d B + +/-- The value specified by `(Z i).sweep`. -/ +abbrev swept (i : I) := (Z i).sweep +/-- Computes the seats by the application `slots i.A i.r`. -/ +abbrev seats (i : I) := slots i.A i.r +/-- The value specified by `i.A.shrink (swept R Δ C t d B i) (seats d B i) (copies t B)`. -/ +abbrev target (i : I) := i.A.shrink (swept R Δ C t d B i) (seats d B i) (copies t B) + +theorem swept_bound : Case.Child (swept R Δ C t d B) (shift R Δ d B) := by + obtain ⟨ha, hm, hg, hk, he, hd, hb, hc⟩ := child_bound R Δ C t d B + exact ⟨ha, hm, hg, hk, he, hd, hb, hc⟩ + +theorem seats_bound : Base (fun i : I => 2 ^ seats d B i) := tiles.exp_add stations + +private def overhead (i : I) := + 2 * added R Δ C t d B i + 2 ^ seats d B i * + (1 + i.A.k + 2 ^ (i.A.spanBits (Z i)) * (2 + (Z i).scheme.d + seats d B i + i.A.spanBits (Z i))) + +private theorem overhead_base : Base (overhead R Δ C t d B) := by + have spans : Base (fun i : I => 2 ^ i.A.spanBits (Z i)) := + Width.expMax ports (base_const (2 ^ e t B)) + have slots := seats_bound (F := F) d B + have hd : Base (fun i : I => (Z i).scheme.d) := + (base_const (degree C Y)).mono fun i => (child_degree R Δ C t d B i).le + have len := (((base_const 2).add hd).add slots.of_exp).add spans.of_exp + exact ((base_const 2).mul (added_bound R Δ C t d B)).add + (slots.mul (((base_const 1).add stations.of_exp).add (spans.mul len))) + +theorem labels_bound : ∃ J, ∀ i : I, + (Z i).scheme.ℓ + (target R Δ C t d B i).ℓ ≤ J * (i.T.scheme.ℓ + i.A.ℓ) + i.base ^ J := by + obtain ⟨k, hk⟩ := (overhead_base R Δ C t d B).bound + let J := max (2 * copies t B) k + refine ⟨J, fun i => ?_⟩ + have hg : (target R Δ C t d B i).ℓ = (Z i).scheme.ℓ + copies t B * i.A.ℓ+ + 2 ^ seats d B i * (1 + i.A.k + 2 ^ (i.A.spanBits (Z i)) * (2 + (Z i).scheme.d + seats d B i + + i.A.spanBits (Z i))) := + i.A.short_width _ _ _ + calc + _ = (2 * copies t B * i.T.scheme.ℓ + copies t B * i.A.ℓ) + overhead R Δ C t d B i := by + rw [hg, label_eq] + unfold overhead + ring + _ ≤ J * (i.T.scheme.ℓ + i.A.ℓ) + i.base ^ J := by + have he := i.base_two + have hc : 2 * copies t B ≤ J := le_max_left _ _ + rw [mul_add] + exact Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_right _ hc) (Nat.mul_le_mul_right _ (by + omega))) + ((hk i).trans (Nat.pow_le_pow_right (by omega) (le_max_right _ _))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Comparing old and new host names without storing them at every block -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case.Child +open Coloring Assembly Width Attachment + +variable {κ : Type} [Field κ] {b d B : ℕ} {N : (i : Case κ b d B) → Template i.F} + {δ j p : Case κ b d B → ℕ} (h : Child N δ) (hj : Short (fun i => 2 ^ j i)) (hp : Short (fun i + => 2 ^ p i)) +local notation "I" => Case κ b d B + +include h hj in +theorem depth : Short (fun i : I => 2 ^ (Attachment.depth (N i) (j i))) := + (expMax h.spans hj).exp_add (short_const (2 ^ 1)) + +include h hp in +private theorem aliases : Short (fun i : I => (Alias.Output i.T.scheme.d (N i).scheme.d (p + i)).width) := + vec hp (vec Case.slots.short (vec h.neighbors (vec hp bit))) + +/-- The quantity computed by `2 ^ i.T.scheme.d * i.m + 2 ^ i.height * i.A.ℓ`. -/ +def incoming (i : I) := 2 ^ i.T.scheme.d * i.m + 2 ^ i.height * i.A.ℓ + +/-- Computes the packet by the application `Inspect.Packet i.m i.T.scheme.d (p i) (N i).scheme.h +(i.A.bundle (N i) (j i) (p i))`. -/ +def packet (N : (i : I) → Template i.F) (j p : I → ℕ) (i : I) := + Inspect.Packet i.m i.T.scheme.d (p i) (N i).scheme.h (i.A.bundle (N i) (j i) (p i)) + +include h hj hp + +private theorem ticket_bound : Short (fun i : I => (i.A.ticket (N i) (j i) (p i)).width) := + pair (addr h.bits) (pair bit (h.orders hj hp)) + +theorem bundle_bound : Short (fun i : I => (i.A.bundle (N i) (j i) (p i)).width) := + pair (h.ticket_bound hj hp) (vec (h.depth hj) (addr labels)) + +theorem review : Short (fun i : I => (i.A.Review (N i) (j i) (p i)).width) := + pair (h.aliases hp) (pair (h.bundle_bound hj hp) (vec h.neighbors (h.bundle_bound hj hp))) + +theorem rebuildWidth : Short (fun i : I => i.A.rebuildWidth (N i) (j i) (p i)) := + (h.review hj hp).add (h.transport hj) + +theorem packet_bound : Row (fun i : I => (packet N j p i).width) := by + have host : Row (fun i : I => (Format.addr i.m).width) := Long.row (addr hosts) + exact pack (many hp host) (pack (many hp (many Case.slots.short host)) (h.stack (h.bundle_bound + hj hp))) + +theorem inputs : Cost (fun i : I => (i.A.Inputs (N i) (j i) (p i)).width) := by + have ask := vec (h.depth hj) (pair (addr hp.of_exp) (addr levels.short)) + have fresh := h.bank (h.stack (pair (h.ticket_bound hj hp) ask)) + exact pack (parent.bank (parent.stack (addr labels))) fresh + +private theorem receive_bound : Cost (fun i : I => Receive.cost i.m i.T.scheme.d i.height i.A.ℓ + (N i).scheme.m (N i).scheme.d (N i).scheme.h (p i) (Attachment.depth (N i) (j i)) + (i.A.ticket (N i) (j i) (p i)) (incoming i) (i.p.fee (i.m + i.T.scheme.d) (incoming i))) := by + have hd : Short (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.short + have hw : Row (fun i : I => incoming i) := (Long.row (hd.long.mul hosts)).add labels.block.blocks + have send := parent.gather hd hw + have rx := h.bank (h.packet_bound hj hp) + have work := ((((block_const 100).add levels.short.block).add hp.block).add (h.depth + hj).block).add labels.block + have tail := h.cost ((labels.block.blocks.left hp.block).add (Block.blocks (work.pow 100))) + exact send.add (((((h.inputs hj hp).add rx).add (hw.expand hd.block)).add tail).scale 500) + +private theorem inspect_bound : Cost (fun i : I => Inspect.cost i.m i.T.scheme.d (N i).scheme.m + (N i).scheme.d (p i) (N i).scheme.h (i.A.bundle (N i) (j i) (p i)) (packet N j p i).width + (i.p.fee ((N i).scheme.m + (N i).scheme.d) (packet N j p i).width)) := by + have hd : Short (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.short + have cv : Row (fun i : I => (Format.addr i.m).width) := Long.row (addr hosts) + have hw := h.packet_bound hj hp + have pre := (h.gather h.neighbors hw).add ((h.bank hw).scale 56) + have rx := h.vector (many h.neighbors hw) + have query := h.vector (pack (many hp (many hd cv)) (many h.neighbors (many hp cv))) + have result := h.vector (h.aliases hp).long.row + have out := h.vector (h.stack (h.review hj hp)) + have work := ((((long_const 100).add hosts).add hd.long).add h.neighbors.long).add hp.long + exact ((((pre.add (rx.scale 32)).add (query.scale 8)).add (result.scale 4)).add (out.scale 8)).add + ((h.cost (Long.row (work.pow 100))).scale 4) + +theorem rebuildCost : Cost (fun i : I => i.A.rebuildCost (N i) (j i) (p i) + (incoming i) (i.p.fee (i.m + i.T.scheme.d) (incoming i)) (packet N j p i).width + (i.p.fee ((N i).scheme.m + (N i).scheme.d) (packet N j p i).width)) := by + have req := h.requests hj hp + have query := (req.add ((h.inputs hj hp).scale 34)).scale 4 + have run := (query.add (h.receive_bound hj hp)).add (h.inspect_bound hj hp) + have print := h.cost (h.layer ((block_const 1).add (h.rebuildWidth hj hp).block)) + exact (((req.scale 24).add (h.format.scale 8)).add run).add print + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Case.Child +end + +/- # Physical and label bounds after a reset with a retained border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ κ : ℝ} + (h : Input A L P p r 1 u u z payload d B K H σ) (s : Slice Δ Y w t) + (hC : Δ ≤ C) (hk : 2 ^ t ≤ K) (q : (frame A L u z payload Δ C P).state) +local notation "a" => (T.scheme.h - r) +local notation "W" => ((2 : ℝ) ^ t * P.load) +local notation "U" => poll h s hC hk q + +include h in +open scoped Classical in +theorem charged : History.Reset.Charged q.val.q.core.post T.order z T.scheme.ℓ := by + intro j hj + refine Nat.mul_le_mul (History.Dense.used_le.mpr (Fin.isLt _)) ?_ + let G := q.val.G + change z ≤ G.past j + G.tetherLoad j + Packing.degree G.pair j * u + change 0 < G.tetherLoad j + Packing.degree G.pair j * u at hj + by_cases hd : 0 < Packing.degree G.pair j + · have ht := h.vpos.trans (Nat.le_mul_of_pos_left u hd) + omega + have ht : 0 < G.tetherLoad j := by + rw [show Packing.degree G.pair j = 0 by omega, zero_mul, add_zero] at hj + exact hj + have witness : ∃ i, G.far i = j := by + let _ : DecidableEq (G.V × Cell T.scheme.h) := Classical.typeDecidableEq _ + unfold HostNet.tetherLoad exterior at ht + rcases Nat.add_pos_iff_pos_or_pos.mp ht with hx|hy + · obtain ⟨i, hi⟩ := (Fintype.card_pos_iff.mp hx).some + exact ⟨.inl i, hi⟩ + · obtain ⟨i, hi⟩ := (Fintype.card_pos_iff.mp hy).some + exact ⟨.inr i, hi⟩ + obtain ⟨i, rfl⟩ := witness + have hb := (q.property.1.parallel i).trans (G.parallel_le_tether i) + omega + +open scoped Classical in +theorem gain_eq : 89 * W = gain t * P.load := by + simp only [gain, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, mul_assoc] + +include h in +open scoped Classical in +theorem gain_le : 89 * W ≤ (gain t * B : ℕ) * (z : ℝ) := by + rw [gain_eq, Nat.cast_mul, mul_assoc] + exact mul_le_mul_of_nonneg_left h.ceiling (by positivity) + +variable [NeZero Y] [NeZero w] (R : Rotor F Y w) (hc : 1 ≤ κ) + (cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w) +local notation "hf" => fits h s hC hk q R hc cost +local notation "Q" => History.Reset.Setup.result U R hf +local notation "G" => History.Reset.Setup.graph U R hf + +open scoped Classical in +theorem estimates : + (∀ x y, (G).diagram.eval x y = q.val.G.diagram.eval x y) ∧ + (G).Bounded 3 (3 + terminalWidth C Y) (gain t * P.load) ∧ + ((G).X : ℝ) ≤ 2 * resetWidth κ w * P.width + 2 * resetWidth κ w * (L.total + σ) ∧ + q.val.G.Preserves G ∧ ((G).mass : ℝ) ≤ P.mass + 2 * P.width := by + obtain ⟨eval, _, bounds, width, preserve, mass, _⟩ := (U).bounds R hf (slack h hk q) + refine ⟨eval, ?_, ?_, preserve, ?_⟩ + · rw [← gain_eq]; exact bounds + · have hσ : 0 ≤ σ := by + have hp : 0 ≤ P.load := (Nat.cast_nonneg _).trans h.load + exact nonneg_of_mul_nonneg_left (le_trans (by positivity) h.slack) (by positivity) + have hr : 0 ≤ resetWidth κ w := by unfold resetWidth; positivity + refine width.trans ?_ + calc + _ ≤ resetWidth κ w * (2 * σ + 2 * P.width + 2 * L.total) := + mul_le_mul_of_nonneg_left (add_le_add + (add_le_add (by linarith only [hσ]) (mul_le_mul_of_nonneg_left q.property.1.width (by + norm_num))) + (mul_le_mul_of_nonneg_left q.property.1.total (by norm_num))) hr + _ = _ := by ring + · rw [mass, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat] + exact add_le_add q.property.1.mass (mul_le_mul_of_nonneg_left q.property.1.width (by norm_num)) + +open scoped Classical in +theorem mass : (G).mass ≤ q.val.L.cap := by + rw [q.property.1.cap] + exact Nat.cast_le.mp ((estimates h s hC hk q R hc cost).2.2.2.2.trans h.history) + +open scoped Classical in +theorem room (v : Cell a × (Q).vertex) : + Fintype.card (History.Reset.Visible q.val.q.core.post Q v) ≤ 2 ^ (e t B) := + (History.Reset.seats_fit q.val.q.core.post Q v h.zpos h.vpos q.property.1.span (gain_le + h)).2.2.trans + (Nat.le_pow_clog (by decide) _) + +open scoped Classical in +theorem valid : (meter L t z B).Valid G := + valid_of_charge h q (gain t) G (mass h s hC hk q R hc cost) + (estimates h s hC hk q R hc cost).2.1.2.2 + +variable [Fintype F] +local notation "b" => book T u t z B +local notation "N" => raw R T L u t z Δ C B r + +open scoped Classical in +theorem ready (S : History.Reset.Allocation q.val.q.core.post Q (N).scheme) + (nav : Coloring.B (N).scheme.m → Coloring.B (N).scheme.d → Coloring.B (N).scheme.m) + (hop : ∀ (i : (Q).Survivors) j, + let host := History.Reset.Allocation.endHost (q := Q) + nav (S.host (host i j)) (S.index (host i j) (host i (!j))) = S.host (host i (!j))) : + (b).Ready S nav := by + have hd : 2 ^ q.val.L.discount * (gain t * B) ≤ copies t B := by + rw [q.property.1.discount, copies, mul_assoc] + exact Nat.mul_le_mul_right _ h.discount + apply (b).ready S nav _ hop ((U).result_simple R hf) q.property.1.neutral + (charged h q) h.zpos h.vpos q.property.1.span (mass h s hC hk q R hc cost) (gain_le h) + (Nat.le_pow_clog (by decide) _) (Nat.add_le_add_left (Nat.mul_le_mul_left _ hd) _) + intro j + exact History.Reset.Book.represent T.scheme u (e t B) (cap T t B) T.order (Finset.range (B * z + + 1)) + (Finset.mem_range.mpr (Nat.lt_succ_of_le (size_bound h q j))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Reset/WindowCost.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Reset/WindowCost.lean new file mode 100644 index 0000000000..42791720e7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Reset/WindowCost.lean @@ -0,0 +1,959 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Reset.Label + +/-! # Attaching the frozen border to the elected reset -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ κ : ℝ} + [NeZero Y] [NeZero w] + (h : Input A L P p r 1 u u z payload d B K H σ) (s : Slice Δ Y w t) + (hC : Δ ≤ C) (hk : 2 ^ t ≤ K) (R : Rotor F Y w) (hc : 1 ≤ κ) + (cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w) +local notation "b" => book T u t z B +local notation "M" => meter L t z B +local notation "N" => raw R T L u t z Δ C B r + +open scoped Classical in +/-- The indexed operation `History.Reset.Setup.Selection (poll h s hC hk) R (fun q => fits h s +hC hk q R hc cost) (board h s hC hk) b M (Nat.sub_le T.scheme.h r)`. -/ +abbrev Choice := History.Reset.Setup.Selection (poll h s hC hk) R (fun q + => fits h s hC hk q R hc cost) + (board h s hC hk) b M (Nat.sub_le T.scheme.h r) + +open scoped Classical in +/-- The choose of type `Choice h s hC hk R hc cost` for the given inputs. -/ +def choose : Choice h s hC hk R hc cost := + History.Reset.Setup.select (poll h s hC hk) R (fun q => fits h s hC hk q R hc cost) + (board h s hC hk) b M (Nat.sub_le T.scheme.h r) (fun q => room h s hC hk q R hc cost) + +namespace Choice +variable {h s hC hk R hc cost} (E : Choice h s hC hk R hc cost) (q : (frame A L u z payload Δ C + P).state) +local notation "U" => poll h s hC hk q +local notation "hf" => fits h s hC hk q R hc cost +local notation "G" => History.Reset.Setup.graph U R hf +local notation "g" => E.graph q +local notation "S" => E.layout q + +open scoped Classical in +theorem valid : (b).Ready S (g).1 := + ready h s hC hk q R hc cost S (g).1 (History.Reset.Setup.hop S g (E.describes q)) + +open scoped Classical in +/-- Uses `History.Reset.Setup.query A M S g q.val.raw` as the representation. -/ +abbrev query : A.Query N (slots A r) 0 := History.Reset.Setup.query A M S g q.val.raw + +open scoped Classical in +/-- Computes the posted by the application `History.Reset.Setup.outputEncodes M S g (E.valid q) +(E.placed q).block (E.describes q) (Reset.valid h s hC hk q R hc cost)`. -/ +abbrev posted : (N).Encodes (E.query q).fresh G := History.Reset.Setup.outputEncodes M S g (E.valid + q) (E.placed q).block (E.describes q) + (Reset.valid h s hC hk q R hc cost) + +end Choice +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Budgets for selecting, printing and attaching a reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing History.Reset +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {Y w : ℕ} {T : Template F} + (R : Rotor F Y w) (A : Attachment T) (L : BorderLimit F x y) + (u t z Δ C B r : ℕ) (p : Prices F) + +local notation "a" => (T.scheme.h - r) +local notation "k" => Nat.clog 2 (T.scheme.h + 1) +local notation "n" => (T.scheme.h - (T.scheme.h - r) + 8) +local notation "j" => History.Reset.Child.extra R Δ (T.scheme.h - (T.scheme.h - r)) +local notation "Y₀" => raw R T L u t z Δ C B r +local notation "Y₁" => next R T L u t z Δ C B r +local notation "s" => slots A r + +open scoped Classical in +/-- The value specified by `Template.Mix.arity T k (indices T Δ z B) + Tile.attachedWidth T Y₀ A +k n j s + 2 * (Y₀).scheme.ℓ + A.rebuildWidth Y₁ s 0`. -/ +def width := Template.Mix.arity T k (indices T Δ z B) + Tile.attachedWidth T Y₀ A k n j s + + 2 * (Y₀).scheme.ℓ + A.rebuildWidth Y₁ s 0 + +open scoped Classical in +/-- The quantity computed by `40 * A.format.width + Template.Mix.cost T k (indices T Δ z B) +(T.scheme.h - t - a)`. -/ +def setupCost := 40 * A.format.width + Template.Mix.cost T k (indices T Δ z B) (T.scheme.h - t - a) +open scoped Classical in +/-- The quantity computed by `Tile.attachedCost T Y₀ A k n j s (p.fee (T.scheme.m + T.scheme.d) +(Tile.volume T Y₀ k n))`. -/ +def decideCost := Tile.attachedCost T Y₀ A k n j s (p.fee (T.scheme.m + + T.scheme.d) (Tile.volume T Y₀ k n)) +open scoped Classical in +/-- The quantity computed by `setupCost A t z Δ B r + decideCost R A L u t z Δ C B r p + +A.sweepCost Y₀ s 0`. -/ +def controlCost := setupCost A t z Δ B r + decideCost R A L u t z Δ C B r p + A.sweepCost Y₀ s 0 + +open scoped Classical in +/-- The construction uses `2 ^ T.scheme.d * T.scheme.m + 2 ^ T.scheme.h * A.ℓ` for its +intermediate `v`. -/ +def rebuildCost := + let v := 2 ^ T.scheme.d * T.scheme.m + 2 ^ T.scheme.h * A.ℓ + let v' := (Attachment.Inspect.Packet T.scheme.m T.scheme.d 0 a (A.bundle Y₁ s 0)).width + A.rebuildCost Y₁ s 0 v (p.fee (T.scheme.m + T.scheme.d) v) v' (p.fee ((Y₁).scheme.m + + (Y₁).scheme.d) v') + +open scoped Classical in +/-- The quantity computed by `⟨a, u, Δ, C, denominator L, Template.Encodes.margin Δ, (2 : ℝ) ^ t +* P.load⟩`. -/ +def params (P : Bound) : Template.Mix.Params := + ⟨a, u, Δ, C, denominator L, Template.Encodes.margin Δ, (2 : ℝ) ^ t * P.load⟩ + +open scoped Classical in +/-- The labels used in the `Reset` construction. -/ +def labels (P : Bound) (gates : Finset (Table F)) := + insert (BatchDescent.Snapshot.sweepTable Y₀) (insert (A.rebuildGate Y₁ s 0 0) + (gates ∪ Template.Mix.keys T k (indices T Δ z B) (params (T := T) L u t Δ C r P))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Attaching the frozen border to the elected reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ κ : ℝ} + [NeZero Y] [NeZero w] + (h : Input A L P p r 1 u u z payload d B K H σ) (s : Slice Δ Y w t) + (hC : Δ ≤ C) (hk : 2 ^ t ≤ K) (R : Rotor F Y w) (hc : 1 ≤ κ) + (cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w) +local notation "b" => book T u t z B +local notation "M" => meter L t z B +local notation "N" => raw R T L u t z Δ C B r + +namespace Choice +variable {h s hC hk R hc cost} (E : Choice h s hC hk R hc cost) (q : (frame A L u z payload Δ C + P).state) +local notation "U" => poll h s hC hk q +local notation "hf" => fits h s hC hk q R hc cost +local notation "G" => History.Reset.Setup.graph U R hf +local notation "g" => E.graph q +local notation "S" => E.layout q + +local notation "Z" => E.query q +local notation "e" => E.posted q + +open scoped Classical in +theorem active : Attachment.Relocation.WriteActive e (Z).active := + History.Reset.Setup.query_active A M S g q.val.raw e rfl + +open scoped Classical in +theorem moves : (Z).R.Moves q.val.q e (History.Reset.Setup.resetSlot A U q.val.q.slot) := + (E.placed q).moves A M q.val.q e rfl rfl + +open scoped Classical in +theorem agrees : (Z).M.Agrees q.val.q.core.post.toPresentation (e).post.toPresentation := + (S).move_agrees (E.valid q).lengths (E.valid q).agrees _ (E.placed q).parent + +open scoped Classical in +/-- The value specified by `(Z).apply (E.moves q) (E.active q) (E.agrees q) (show (N).full = +true from h.full)`. -/ +def result := (Z).apply (E.moves q) (E.active q) (E.agrees q) (show (N).full = true from h.full) + +open scoped Classical in +theorem fits : (E.result q).Fits payload := + (Z).fits (E.moves q) (E.active q) (E.agrees q) (show (N).full = true from h.full) q.property.2 + +open scoped Classical in +theorem spare : A.Sparse (N).sweep (slots A r) (copies t B) (E.result q).raw := by + obtain ⟨δ, hδ, hl, hb⟩ := charges h q (gain t) G (estimates h s hC hk q R hc cost).2.1.2.2 + exact (Z).spare (E.moves q) (E.active q) (E.agrees q) (show (N).full = true from h.full) hδ hl hb + +open scoped Classical in +theorem exterior (l : MatrixExponent.slots x ⊕ MatrixExponent.slots y) : + let j := ((E.result q).q.pres.boundary l).val + let old := (q.val.q.pres.boundary l).val + (Z).sweep.R.kept q.val.raw j.1.1 = some old.1.1 ∧ j.1.2 = A.outer (N).sweep old.1.2 ∧ j.2.val + = old.2.val := + by unfold result; apply Attachment.Query.exterior + +end Choice +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # One reset writer shared by all states of the attached network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset.Choice +open Assembly Packing History.Reset + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ κ : ℝ} + [NeZero Y] [NeZero w] + {h : Input A L P p r 1 u u z payload d B K H σ} {s : Slice Δ Y w t} + {hC : Δ ≤ C} {hk : 2 ^ t ≤ K} {R : Rotor F Y w} {hc : 1 ≤ κ} + {cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w} + (E : Choice h s hC hk R hc cost) +local notation "k" => Nat.clog 2 (T.scheme.h + 1) +local notation "n" => (T.scheme.h - (T.scheme.h - r) + 8) +local notation "j" => History.Reset.Child.extra R Δ (T.scheme.h - (T.scheme.h - r)) +local notation "N" => raw R T L u t z Δ C B r +local notation "M" => meter L t z B +local notation "Tapes" => + (fun i : (frame A L u z payload Δ C P).state => Board.tape (board h s hC hk i)) + +open scoped Classical in +theorem selected : Tile.Local T N k n j (Nat.sub_le ..) rfl Tapes + (fun i => ((E.query i).fresh, (E.query i).M.commands)) := by + exact E.fields (by have := s.core; omega) (by simp [h.full]) + (fun i => i.property.1.neutral) (fun i => E.valid i) + +open scoped Classical in +theorem attached : Tile.QueryLocal T N A k n j (slots A r) (Nat.sub_le ..) rfl Tapes E.query := by + intro q q' v v' i i' eq + exact Board.query_eq A M (E.placed q) (E.placed q') (by omega) + (by have := s.core; omega) (by simp [h.full]) eq q.val.raw q'.val.raw + (E.selected q q' v v' i i' eq) + +open scoped Classical in +theorem local_net : + ∃ gates : Finset (Table F), gates.card ≤ 3 ∧ + (∀ f ∈ gates, Processor.arity f ≤ Tile.attachedWidth T N A k n j (slots A r)) ∧ + ∀ {v m : ℕ} {W : Set (Table F)}, 3 ≤ v → Tile.attachedWidth T N A k n j (slots A r) ≤ v → + (∀ f ∈ gates, f ∈ W) → Access F v W (T.scheme.m + T.scheme.d) (Tile.volume T N k n) m → + Computes F v W (A.format.pair (Tile.pair T k)) (A.Requests N (slots A r) 0) + (fun i : (frame A L u z payload Δ C P).state => (i.val.raw, (board h s hC hk i).tape)) + (fun i => (E.query i).requests) (fun _ => 1) (Tile.attachedCost T N A k n j (slots A r) + m) := by + exact Tile.attached_net T N A k n j (slots A r) (Nat.sub_le ..) rfl Tapes E.query E.headers + E.selected E.control (fun i => E.build i) E.attached (fun i + => i.val.q.core.reciprocal) (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset.Choice +end + +/- # Width, degree and evaluation of the reattached reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Query +open Packing Coloring +variable {F T : Type} [Field F] [Fintype T] {x y a b : Wire} {D Y : Template F} {A : Attachment D} + {k m u v : ℕ} {L : Fringe x y T} {G : HostNet F L D.scheme.h u} {H : HostNet F L Y.scheme.h v} + {Z : Border F T a b x y} (q : A.Query Y k m) + {old : A.Encloses q.old G Z} {fresh : Y.Encodes q.fresh H} {slot : T → B k} + (h : q.R.Moves old fresh slot) (ok : Relocation.WriteActive fresh q.active) + (move : q.M.Agrees old.core.post.toPresentation fresh.post.toPresentation) (full : Y.full = true) + +theorem apply_eq (he : ∀ i j, H.diagram.eval i j = G.diagram.eval i j) (i : Val a) (j : Val b) : + (Z.attach G.diagram).eval i j = q.sweepWeight * (q.apply h ok move full).diagram.eval i j := by + refine Eq.trans ?_ (Z.attach_factor fresh.post.toPresentation i j) + rw [Z.eval_attach, Z.eval_attach] + simp only [he] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Attachment.Query + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset.Choice +open Assembly Packing +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ κ : ℝ} + [NeZero Y] [NeZero w] + {h : Input A L P p r 1 u u z payload d B K H σ} {s : Slice Δ Y w t} + {hC : Δ ≤ C} {hk : 2 ^ t ≤ K} {R : Rotor F Y w} {hc : 1 ≤ κ} + {cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w} + (E : Choice h s hC hk R hc cost) (q : (frame A L u z payload Δ C P).state) +local notation "U" => poll h s hC hk q +local notation "hf" => Reset.fits h s hC hk q R hc cost +local notation "Q" => History.Reset.Setup.result U R hf +local notation "G" => History.Reset.Setup.graph U R hf +local notation "N" => raw R T L u t z Δ C B r +local notation "Z" => A.transport (Template.sweep N) (slots A r) + +open scoped Classical in +theorem eval (v : Val x) (j : Val y) : + q.val.diagram.eval v j = (E.query q).sweepWeight * (E.result q).diagram.eval v j := by + unfold result + apply Attachment.Query.apply_eq + exact (estimates h s hC hk q R hc cost).1 + +open scoped Classical in +theorem preserved (hg : gain t ≤ K) : + Ready Z L z 3 (C ^ (900 + Y + 1)) (after L P K (2 * resetWidth κ w) (2 * resetWidth κ w) σ) + (E.result q) := by + obtain ⟨_, bounds, width, moves, mass⟩ := estimates h s hC hk q R hc cost + have ha := q.property.1 + unfold result + refine moved_ready q.val (E.query q) G q.val.q (E.posted q) _ + (E.moves q) (E.active q) (E.agrees q) (show (N).full = true from h.full) ha + ⟨((Q).owner (Classical.choice ha.live, 0)).2⟩ ?_ ?_ moves ⟨bounds.1, ?_, ?_⟩ width mass + · intro _ j eq + exact j.property (Prod.ext ((Q).support j.val).1 eq) + · exact (E.valid q).floor ha.span + · exact fun j => (bounds.2.1 j).trans (Reduction.degree_reset (s.core.trans hC)) + · intro v j + change (G).load v j ≤ (K : ℝ) * P.load + exact (bounds.2.2 v j).trans + (mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hg) ((Nat.cast_nonneg _).trans h.load)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset.Choice +end + +/- # Selecting the mixer while retaining the old border labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ : ℝ} + (h : Input A L P p r 1 u u z payload d B K H σ) (s : Slice Δ Y w t) + (hC : Δ ≤ C) (hk : 2 ^ t ≤ K) (R : Rotor F Y w) (gates : Finset (Table F)) +local notation "k" => Nat.clog 2 (T.scheme.h + 1) +local notation "keys" => labels R A L u t z Δ C B r P gates +local notation "D" => indices T Δ z B +local notation "Z" => params (T := T) L u t Δ C r P +local notation "N" => raw R T L u t z Δ C B r + +open scoped Classical in +theorem few (hg : gates.card ≤ 3) : (keys).card ≤ 17 := by + unfold labels + iterate 2 + apply (Finset.card_insert_le ..).trans + apply Nat.add_le_add_right + exact (Finset.card_union_le ..).trans (Nat.add_le_add hg (Template.Mix.few T k D Z)) + +open scoped Classical in +theorem start {v : ℕ} (hu : 3 ≤ v) (hw : width R A L u t z Δ C B r ≤ v) : + Computes F v keys A.format (A.format.pair (History.Reset.Tile.pair T k)) + (fun i : (frame A L u z payload Δ C P).state => i.val.raw) + (fun i => (i.val.raw, (board h s hC hk i).tape)) + (fun _ => 1) (setupCost A t z Δ B r) := by + let L' : Set (Table F) := keys + have hk' : T.scheme.h < 2 ^ k := Nat.le_pow_clog (by decide : 1 < 2) _ + have hkeys : (Template.Mix.keys T k D Z : Set (Table F)) ⊆ L' := + fun _ hj => Finset.mem_insert_of_mem (Finset.mem_insert_of_mem (Finset.mem_union_right _ hj)) + have hf : Template.Mix.arity T k D ≤ v := by unfold width at hw; omega + have select : Circuit F A.format T.format Prod.fst (A.format.width + 2 * T.format.width) := + Circuit.project Sum.inl (fun _ _ => rfl) + have init := (Map.circuit hu select).comp (Template.Mix.prepare_net T k D Z hf hkeys t hk') + let data := fun i : (frame A L u z payload Δ C P).state => i.val.raw + have pre := Computes.of_map (x := data) (y := fun i => (board h s hC hk i).tape) init (fun _ + => rfl) + have cp := Computes.of_map (x := data) (Map.circuit (L := L') hu (Circuit.id F A.format)) (fun _ + => rfl) + have net := cp.pair hu pre + simp only [one_mul] at net + refine net.mono ?_ + have ha : T.format.width ≤ A.format.width := by rw [Attachment.width]; exact Nat.le_add_right .. + change _ + (_ + (_ + Template.Mix.cost T k D (T.scheme.h - t - (T.scheme.h - r)))) ≤ _ + unfold setupCost + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Combining the shared reset dictionaries and withdrawing scalar factors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset.Choice +open Assembly Packing Coloring History.Reset + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ κ : ℝ} + [NeZero Y] [NeZero w] + {h : Input A L P p r 1 u u z payload d B K H σ} {s : Slice Δ Y w t} + {hC : Δ ≤ C} {hk : 2 ^ t ≤ K} {R : Rotor F Y w} {hc : 1 ≤ κ} + {cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w} + (E : Choice h s hC hk R hc cost) + +local notation "k" => Nat.clog 2 (T.scheme.h + 1) +local notation "n" => (T.scheme.h - (T.scheme.h - r) + 8) +local notation "j" => History.Reset.Child.extra R Δ (T.scheme.h - (T.scheme.h - r)) +local notation "N" => raw R T L u t z Δ C B r +local notation "N'" => next R T L u t z Δ C B r +local notation "s'" => slots A r + +open scoped Classical in +theorem device {v : ℕ} (hu : 3 ≤ v) (hw : width R A L u t z Δ C B r ≤ v) + (lo : 1 ≤ T.scheme.m) (hi : T.scheme.m + T.scheme.d ≤ p.w) : + ∃ W : Finset (Table F), W.card ≤ 17 ∧ A.rebuildGate N' s' 0 0 ∈ W ∧ + Computes F v W A.format (A.Requests N' s' 0) + (fun i : (frame A L u z payload Δ C P).state => i.val.raw) + (fun i => (E.query i).sweep.requests) + (fun i => (E.query i).sweepWeight) (controlCost R A L u t z Δ C B r p) := by + obtain ⟨gates, card, _, net⟩ := E.local_net + let keys := labels R A L u t z Δ C B r P gates + have hpre := start h s hC hk R gates hu hw + have ha : Tile.attachedWidth T N A k n j s' ≤ v := by unfold width at hw; omega + have hs : 2 * (N).scheme.ℓ ≤ v := by unfold width at hw; omega + have small (f) (hf : f ∈ gates) : f ∈ (keys : Set _) := + Finset.mem_insert_of_mem (Finset.mem_insert_of_mem (Finset.mem_union_left _ hf)) + have ready := net hu ha small (p.access hu (lo.trans (Nat.le_add_right ..)) hi _) + have sweep := Attachment.Query.sweep_net (L := (keys : Set (Table F))) E.query hu hs + (Finset.mem_insert_self ..) + have run := (hpre.comp ready).comp sweep + simp only [one_mul] at run + exact ⟨keys, few R gates card, Finset.mem_insert_of_mem (Finset.mem_insert_self ..), run⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset.Choice +end + +/- # Reattaching old records to the selected reset -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing Coloring History.Reset + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ κ : ℝ} + +open scoped Classical in +/-- The bound obtained by adding the component charges `let N := next R T L u t z Δ C B r +controlCost R A L u t z Δ C B r p + 24 * (A.Requests N (slots A r) 0).width + rebuildCost R +A L u t z Δ C B r p`. -/ +def supplyCost (R : Rotor F Y w) (A : Attachment T) (L : BorderLimit F x y) + (u t z Δ C B r : ℕ) (p : Prices F) := + let N := next R T L u t z Δ C B r + controlCost R A L u t z Δ C B r p + 24 * (A.Requests N (slots A r) 0).width + + rebuildCost R A L u t z Δ C B r p + +namespace Choice +variable [NeZero Y] [NeZero w] {h : Input A L P p r 1 u u z payload d B K H σ} + {s : Slice Δ Y w t} {hC : Δ ≤ C} {hk : 2 ^ t ≤ K} {R : Rotor F Y w} {hc : 1 ≤ κ} + {cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w} + (E : Choice h s hC hk R hc cost) + +local notation "shift" => History.Reset.Child.extra R Δ (T.scheme.h - (T.scheme.h - r)) +local notation "N" => next R T L u t z Δ C B r +local notation "s'" => slots A r +local notation "V" => A.Requests N s' 0 +local notation "U" => A.transport N s' +local notation "Wiring" => Format.pair V (Attachment.format U) + +open scoped Classical in +/-- The value specified by `(E.query i).sweep`. -/ +abbrev swept (i : (frame A L u z payload Δ C P).state) := (E.query i).sweep + +open scoped Classical in +theorem rebuild {v : ℕ} {W : Set (Table F)} + (hu : 3 ≤ v) (hw : width R A L u t z Δ C B r ≤ v) + (lo : 1 ≤ T.scheme.m) (hi : T.scheme.m + T.scheme.d ≤ p.w) (end' : (N).scheme.m + (N).scheme.d + ≤ p.w) + (allow : A.rebuildGate N s' 0 0 ∈ W) : + Computes F v W V (U).format (fun i => (E.swept i).requests) (fun i => (E.swept i).result) + (fun _ => 1) (rebuildCost R A L u t z Δ C B r p) := by + have first := lo.trans (Nat.le_add_right _ T.scheme.d) + have last : 1 ≤ (N).scheme.m + (N).scheme.d := + (lo.trans (Nat.le_add_right _ shift)).trans (Nat.le_add_right ..) + exact Attachment.Query.rebuild_net hu (Nat.sub_le ..) + (p.access hu first hi _) le_rfl (p.access hu last end' _) le_rfl + (Setup.parent T shift) (fun _ => none) E.swept 0 (fun _ _ _ => rfl) + (fun i => i.val.q.core.reciprocal) (fun i => (E.posted i).reciprocal) + (fun _ _ => rfl) ((Nat.le_add_left ..).trans hw) allow + +open scoped Classical in +/-- The value specified by `((E.swept i).requests, (E.swept i).result)`. -/ +def pending (i : (frame A L u z payload Δ C P).state) : (Wiring).obj := + ((E.swept i).requests, (E.swept i).result) + +open scoped Classical in +theorem supply {v : ℕ} (hu : 3 ≤ v) (hw : width R A L u t z Δ C B r ≤ v) + (lo : 1 ≤ T.scheme.m) (hi : T.scheme.m + T.scheme.d ≤ p.w) (end' : (N).scheme.m + (N).scheme.d + ≤ p.w) : + ∃ W : Finset (Table F), W.card ≤ 17 ∧ + Computes F v W A.format Wiring (fun i : (frame A L u z payload Δ C P).state => i.val.raw) + E.pending + (fun i => (E.query i).sweepWeight) (supplyCost R A L u t z Δ C B r p) := by + obtain ⟨W, hw', ok, net⟩ := E.device hu hw lo hi + have decode := E.rebuild (W := ↑W) hu hw lo hi end' ok + have keep := Computes.of_map (L := (W : Set (Table F))) (x := fun i => (E.swept i).requests) + (Map.circuit hu (Circuit.id F V)) (fun _ => rfl) + have run := net.comp (keep.pair hu decode) + simp only [mul_one] at run + refine ⟨W, hw', run.mono ?_⟩ + unfold supplyCost + dsimp only + omega + +end Choice +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Total transformation with an attached payload and sparse frozen labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Packing Coloring + +variable {F : Type} [Field F] [Fintype F] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u z payload d B K H Δ C Y w t : ℕ} {σ κ : ℝ} + +omit [Fintype F] in +open scoped Classical in +private theorem raise {I : Type*} {X Y : Format} {v n : ℕ} {W L : Set (Table F)} + {x : I → X.obj} {y : I → Y.obj} {c : I → F} + (h : Computes F v L X Y x y c n) (hl : L ⊆ W) : Computes F v W X Y x y c n := + let ⟨f, hf, he⟩ := h + ⟨f, hf.widen le_rfl hl, he⟩ + +omit [Fintype F] in +open scoped Classical in +private theorem send {X Y : Snapshot.{1} F x y} {v n : ℕ} {W : Set (Table F)} + (dest : X.state → Y.state) (weight : X.state → F) + (ev : ∀ i a b, X.eval i a b = weight i * Y.eval (dest i) a b) + (net : Computes F v W X.port Y.port + (fun i : X.state × Val x × Val y => X.encode i.1 i.2.1 i.2.2) + (fun i => Y.encode (dest i.1) i.2.1 i.2.2) (fun i => weight i.1) n) : + Transforms F v W X Y n := by + obtain ⟨f, hf, he⟩ := net + refine ⟨f, hf, fun i => ⟨Unit, inferInstance, fun _ => dest i, fun _ => weight i, ?_, ?_⟩⟩ + · intro a b + rw [Fintype.sum_unique] + exact ev i a b + · intro a b j + rw [Fintype.sum_unique] + exact he (i, a, b) j + +open scoped Classical in +/-- The run cost used in the `Reset` construction. -/ +def runCost (R : Rotor F Y w) (A : Attachment T) (L : BorderLimit F x y) + (u t z Δ C B r payload : ℕ) (p : Prices F) := + supplyCost R A L u t z Δ C B r p + 4 * (Attachment.payload x y payload T.scheme.m).width + + A.shrinkCost (next R T L u t z Δ C B r) (slots A r) (copies t B) x y payload + +namespace Choice +variable [NeZero Y] [NeZero w] {h : Input A L P p r 1 u u z payload d B K H σ} + {s : Slice Δ Y w t} {hC : Δ ≤ C} {hk : 2 ^ t ≤ K} {R : Rotor F Y w} {hc : 1 ≤ κ} + {cost : (Fintype.card R.E : ℝ) ≤ κ * Y * w} + (E : Choice h s hC hk R hc cost) + +local notation "N" => Template.sweep (raw R T L u t z Δ C B r) +local notation "k'" => slots A r +local notation "U" => A.transport N k' +local notation "Wiring" => Format.pair (A.Requests (next R T L u t z Δ C B r) (slots A r) 0) + (Attachment.format (A.transport (next R T L u t z Δ C B r) (slots A r))) +local notation "D" => Attachment.payload x y payload T.scheme.m +local notation "B'" => after L P K (2 * resetWidth κ w) (2 * resetWidth κ w) σ +local notation "C'" => (C ^ (900 + Y + 1)) +local notation "I" => (Assembly.Snapshot.state (frame A L u z payload Δ C P) × Val x × Val y) + +open scoped Classical in +/-- Computes the old bits by the application `i.1.val.data i.1.property.2 i.2.1 i.2.2`. -/ +def oldBits (i : I) := i.1.val.data i.1.property.2 i.2.1 i.2.2 + +open scoped Classical in +/-- The value specified by `((E.result i.1).raw, (E.result i.1).data (E.fits i.1) i.2.1 i.2.2)`. -/ +def output (i : I) := + ((E.result i.1).raw, (E.result i.1).data (E.fits i.1) i.2.1 i.2.2) + +open scoped Classical in +/-- The indexed operation `Computes F v L' ((Wiring).pair D) ((U).port x y payload) (fun i : I +=> (E.pending i.1, oldBits i)) E.output (fun _ => 1) n`. -/ +def Carries (v : ℕ) (L' : Set (Table F)) (n : ℕ) := + Computes F v L' ((Wiring).pair D) ((U).port x y payload) + (fun i : I => (E.pending i.1, oldBits i)) E.output (fun _ => 1) n + +open scoped Classical in +private theorem transform {v n : ℕ} {W : Set (Table F)} (hg : gain t ≤ K) + (net : Computes F v W (frame A L u z payload Δ C P).port ((U).port x y payload) + (fun i : I => (frame A L u z payload Δ C P).encode i.1 i.2.1 i.2.2) E.output + (fun i => (E.query i.1).sweepWeight) n) : + Transforms F v W (frame A L u z payload Δ C P) + (interim A N k' (copies t B) L u z payload 3 C' B') n := by + let Y' := interim A (raw R T L u t z Δ C B r).sweep k' (copies t B) L u z payload 3 C' B' + let dest (i : (frame A L u z payload Δ C P).state) : Y'.state := + Subtype.mk (E.result i) (And.intro (And.intro (E.preserved i hg) (E.spare i)) (E.fits i)) + refine send (X := frame A L u z payload Δ C P) (Y := Y') dest + (fun i => (E.query i).sweepWeight) ?_ ?_ + · intro i a b + exact E.eval i a b + · exact net + +open scoped Classical in +theorem controller {v : ℕ} (hu : 3 ≤ v) (hw : width R A L u t z Δ C B r ≤ v) + (lo : 1 ≤ T.scheme.m) (hi : T.scheme.m + T.scheme.d ≤ p.w) (end' : (N).scheme.m + (N).scheme.d + ≤ p.w) + (hg : gain t ≤ K) (fit : A.shrinkWidth N k' (copies t B) ≤ v) : + ∃ labels : Finset (Table F), labels.card ≤ 18 ∧ ∀ {W : Set (Table F)} {n : ℕ}, + (labels : Set _) ⊆ W → E.Carries v W n → + Transforms F v W (frame A L u z payload Δ C P) + (frame (A.shrink N k' (copies t B)) L u z payload 3 C' B') + (runCost R A L u t z Δ C B r payload p + n) := by + obtain ⟨old, hcard, net⟩ := E.supply hu hw lo hi end' + let gate := A.shrinkGate N k' (copies t B) + refine ⟨insert gate old, (Finset.card_insert_le ..).trans (by omega), ?_⟩ + intro W n include' ship + have inc : (old : Set (Table F)) ⊆ W := fun _ hx => include' (Finset.mem_insert_of_mem hx) + have first := raise net inc + have keep := Computes.of_map (x := fun i : I => oldBits i) (L + := W) (Map.circuit hu (Circuit.id F D)) + (fun _ => rfl) + have run := ((first.restrict Prod.fst).par keep).comp ship + simp only [mul_one, Function.comp_apply] at run + have lift := transform E hg run + have all := lift.comp (Contraction.shrink hu fit (include' (Finset.mem_insert_self ..))) + exact all.mono (by unfold runCost next; omega) + +end Choice +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Width of a local reset decision -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Packing Assembly Assembly.History.Reset Case Coloring + +variable {F : Type} [Field F] {Y l : ℕ} (P : Rotor F Y l) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B + +theorem height_short : Short (fun i : I => i.height) := levels.short + +theorem data_short : Short (fun i : I => (Tile.data i.T).width) := by + refine (Case.bits.add counters).mono fun i => ?_ + rw [Format.width_pair, Format.width_addr, Format.width_addr] + +theorem walks_bound : Short (fun i : I => 2 ^ ((i.T.scheme.d + 1) * depth d B i)) := by + have h : Short (fun i : I => 2 ^ (i.n + 8)) := tiles.short.exp_add (short_const (2 ^ 8)) + refine (h.pow (d + 1)).mono fun i => ?_ + rw [← pow_mul, mul_comm (i.n + 8)] + exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ (Nat.add_le_add_right i.h.degree + 1)) + +theorem mask_bound : Short (fun i : I => (Tile.coincides i.T.scheme.d (depth d B i)).width) := by + refine ((walks_bound (F := F) d B).mul (walks_bound d B)).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_bit, mul_one] + +theorem stats_bound : Short (fun i : I => (i.T.Statistics (keyBits d B i)).width) := by + have hc : Short (fun i : I => i.T.CountBits) := + (spans.short.of_exp.add (short_const 1)).add (height_short d B) + refine ((((height_short d B).add (short_const 1)).clog).add (Case.slots.short.mul hc)).mono fun i + => ?_ + rw [Format.width_pair, Format.width_vec, Format.width_addr, Format.width_addr] + +theorem row_bound : Short (fun i : I => (Tile.row i.T i.a (keyBits d B i)).width) := by + have hf : Short (fun i : I => (Group.Flags i.T.scheme.d).width) := by + refine (Case.slots.short.mul (short_const 2)).mono fun i => ?_ + rw [Format.width_vec, Format.width_pair, Format.width_bit] + refine ((stats_bound d B).add (hf.add (tiles.short.mul (data_short d B)))).mono fun i => ?_ + rw [Format.width_pair, Format.width_pair (Group.Flags _), Format.width_vec (i.T.scheme.h - i.a)] + +theorem history_bound : + Short (fun i : I => (Window.Walks (depth d B i) i.T.scheme.d (Tile.row i.T i.a (keyBits d B + i))).width) := by + refine ((walks_bound d B).mul (row_bound d B)).mono fun i => ?_ + rw [Format.width_vec] + +theorem sample_bound : Short (fun i : I => + (Tile.sample i.T i.a (keyBits d B i) (depth d B i) (shift P Δ d B i)).width) := by + have extra := (child_factor P Δ d B).short.of_exp + have start := (short_const 1).add extra + have end' := (mask_bound (F := F) d B).add (history_bound d B) + refine (start.add (((height_short d B).add Case.groups.short).add end')).mono fun i => ?_ + simp only [Tile.sample, Format.width_pair, Format.width_addr] + rfl + +theorem answer_bound : Short (fun i : I => (Tile.output i.T (child P Δ C t d B i)).width) := by + have h := child_bound P Δ C t d B + have s : Short (fun i : I => (BatchDescent.Trail.pointer i.T.scheme 0).width) := by + refine ((short_const 1).add ((height_short d B).add spans.short.of_exp)).mono fun i => ?_ + simp only [BatchDescent.Trail.pointer, Format.width_pair, Format.width_addr, i.h.single] + rw [Format.width_bit, Format.width_addr 0, zero_add, zero_add] + refine ((h.bits.add h.count).add (h.spans.mul s)).mono fun i => ?_ + rw [Format.width_pair, Format.width_pair, Format.width_addr, Format.width_addr, + Format.width_vec, Format.width_vec, show (child P Δ C t d B i).scheme.k = 0 from rfl, pow_zero, + one_mul] + +theorem printWidth_bound : Short (fun i : I => + Tile.printWidth i.T (child P Δ C t d B i) (keyBits d B i) (depth d B i) (shift P Δ d B i)) := + (sample_bound P Δ d B).add (answer_bound P Δ C t d B) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Width of reset summaries over varying coefficient fields -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Coloring Template Case + +variable {F : Type} [Field F] (Δ d B : ℕ) +local notation "I" => Case F 1 d B +local notation "K" => keyBits d B +/-- Uses `indices i.T Δ i.z B` as the representation. -/ +abbrev digits (i : I) := indices i.T Δ i.z B +local notation "D" => digits Δ d B + +theorem apply_bound : Cost (fun i : I => Mixing.applyCost i.height (History.Reset.Tile.data i.T) + i.m) := by + have h := (height_short (F := F) d B).add (data_short d B) + have p := ((short_const 100).mul (((short_const 1).add h).pow 2)).add (((short_const 100).add + h).pow 8) + refine (Mixed.short Case.m (Short.block p)).mono fun i => ?_ + have hm : i.height ≤ i.m := (Nat.le_mul_of_pos_left _ (by decide : 0 < 4)).trans i.h.four + simpa only [add_assoc] using BatchDescent.Restore.application i.height i.m + (History.Reset.Tile.data i.T) hm + +theorem indices_bound : Short (fun i : I => indices i.T Δ i.z B) := by + let c := 4 * (Template.Encodes.margin Δ) ^ 2 + 4 + refine (((short_const c).add (height_short d B)).add + ((short_const (B ^ 3)).add units.short)).mono fun i => ?_ + apply Nat.add_le_add_left + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_add] + calc + _ ≤ (B ^ 3 + 1) * (1 + i.z) := by simp only [add_mul, mul_add, one_mul, mul_one]; omega + _ ≤ _ := Nat.mul_le_mul Nat.lt_two_pow_self (Nat.le_pow_clog (by decide) _) + +theorem keys_bound : Short (fun i : I => 2 ^ (K i)) := + ((height_short d B).add (short_const 1)).exp_clog + +theorem cols_bound : Short (fun i : I => 2 ^ i.T.widthCols) := + Case.slots.short.exp_add (short_const (2 ^ 1)) + +theorem precision_bound : Short (fun i : I => Mixing.precision i.height (D i)) := + ((short_const 2).mul ((height_short d B).add (indices_bound Δ d B))).add (short_const 1) + +theorem profile_arity : Short (fun i : I => + Mixing.arity i.T.widthCols i.height (K i) i.T.profileBits (D i)) := by + have hh := indices_bound (F := F) Δ d B + have hk := keys_bound (F := F) d B + have a := (short_const 4).mul (precision_bound (F := F) Δ d B) + have b := (Case.bits.add counters).add ((cols_bound d B).mul hh) + have c := ((short_const 2).add hk.of_exp).add (hk.mul hh) + refine (a.add (b.add c)).mono fun i => ?_ + unfold Mixing.arity profileBits digits + omega + +theorem counterBits : Short (fun i : I => i.T.CounterBits) := + spans.short.of_exp.add (short_const 1) + +theorem headWidth : Short (fun i : I => (Mix.Heads i.T (K i)).width) := by + refine ((cols_bound d B).mul ((short_const 1).add ((short_const 1).add (keys_bound d + B).of_exp))).mono + fun i => ?_ + simp only [Mix.Heads, Mixing.Header, Format.width_vec, Format.width_pair, Format.width_addr] + exact le_rfl + +theorem windowWidth : Short (fun i : I => (Mix.Window i.T (K i)).width) := by + have s : Short (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.short + have k := (keys_bound (F := F) d B).of_exp + refine ((short_const 1).add ((s.mul (short_const 2)).add (k.add (s.mul k)))).mono fun i => ?_ + simp only [Mix.Window, Group.Flags, Mixing.Num, Format.width_vec, Format.width_pair, + Format.width_addr] + exact le_rfl + +theorem summandWidth : Short (fun i : I => (i.T.Summand (D i)).width) := by + refine ((indices_bound Δ d B).add (Case.slots.short.mul (counterBits d B))).mono fun i => ?_ + rw [Format.width_pair, Format.width_addr, Format.width_vec, Format.width_addr] + +theorem summaryWidth : Short (fun i : I => Mix.arity i.T (K i) (indices i.T Δ i.z B)) := by + have a := ((short_const 3).add (data_short (F := F) d B)).add (summandWidth Δ d B) + have b := (a.add ((indices_bound Δ d B).add (height_short d B))).add (keys_bound d B).of_exp + exact (((b.add (windowWidth d B)).add (headWidth d B)).add (Case.bits.add counters)).add + (profile_arity Δ d B) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Paying for profile tests once and short arithmetic at each host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Assembly Coloring Case + +variable {F : Type} [Field F] (Δ d B : ℕ) +local notation "I" => Case F 1 d B +local notation "K" => keyBits d B +local notation "D" => digits Δ d B + +private theorem twice {g : I → ℕ} (hg : Long g) : Cost (fun i : I + => 2 ^ i.height * (2 ^ i.height * g i)) := by + refine (Mixed.long Case.m hg).mono fun i => ?_ + rw [← mul_assoc, ← pow_add] + have hf : 4 * i.height ≤ i.m := i.h.four + exact Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (by omega)) + +private theorem once {g : I → ℕ} (hg : Long g) : Cost (fun i : I => 2 ^ i.height * g i) := + (twice d B hg).mono fun _ => Nat.le_mul_of_pos_left _ (by positivity) + +private theorem rowCost : Row (fun i : I => Mixing.rowCost i.height (K i) (D i)) := by + have p := (precision_bound (F := F) Δ d B).block + have a := (height_short (F := F) d B).block + have k := (keys_bound (F := F) d B).block + have g := (indices_bound (F := F) Δ d B).block + let x (j) := block_const (k := F) (b := 1) (d := d) (B := B) j + have hcorr : Row (fun i : I => Mixing.corrCost i.height (D i)) := + Block.blocks ((((x 1).add g).add p).add ((((x 2).mul a).add (x 3)).mul + ((x 1).add ((x 4).mul p))) |>.add (((x 1).add p).add p)) + have small := Long.row (Block.long (k.mul g)) + have hp : Row (fun i : I => Mixing.pairCost i.height (K i) (Mixing.precision i.height (D i)) (D + i)) := by + refine ((p.blocks.add small).add (((Block.blocks (p.add g)).left k).scale 2)).mono fun i => ?_ + simp only [Mixing.pairCost, pow_add, mul_assoc] + exact le_rfl + have hword := p.add g + have last := (Block.blocks (((x 1).add hword).add hword)).left k + refine (((hcorr.add (small.scale 4)).add (hp.scale 4)).add last).mono fun i => ?_ + simp only [Mixing.rowCost, Mixing.wordLength, pow_add, mul_assoc] + exact le_rfl + +private theorem testCost {g : I → ℕ} (hg : Case.Block g) : + Cost (fun i : I => Mixing.testCost (i.m + i.T.widthCols) (K i + i.height) (g i) i.height) := by + have hk := (keys_bound (F := F) d B).block + have he := (cols_bound (F := F) d B).block + have l := hg.long.add (hosts.add he.long.of_exp) + have hc : Cost (fun i : I => Mixing.collectCost (i.m + i.T.widthCols) (K i + i.height) (g i)) + := by + have a := ((block_const 3).mul hg).add (((block_const 100).add hg).pow 5) + refine ((Block.blocks a).expand he |>.left hk).mono fun i => ?_ + unfold Mixing.collectCost + rw [pow_add] + exact le_of_eq (by ac_rfl) + have hm : Cost (fun i : I => Mixing.maskCost (K i + i.height) i.height (g i + (i.m + + i.T.widthCols))) := by + refine (((once d B l).left hk).add (((twice d B l).left hk).scale (Install.localCost 1))).mono + fun i => ?_ + unfold Mixing.maskCost + rw [pow_add] + exact le_of_eq (by ac_rfl) + have t := (height_short (F := F) d B).long + have h₁ := (twice d B (((long_const 100).add l).pow 5)).left hk + have h₂ := once d B (((long_const 100).add (t.add (l.add (hk.long.of_exp.add t)))).pow 42) + refine ((hc.add hm).add (h₁.add h₂)).mono fun i => ?_ + unfold Mixing.testCost + rw [mul_add, pow_add] + exact le_of_eq (by ac_rfl) + +theorem profile_cost : Cost (fun i : I => + Mixing.extractionCost i.m i.T.widthCols i.height (K i) i.T.profileBits (D i) + + Mixing.cost (i.m + i.T.widthCols) i.height (K i) (D i)) := by + have hk := (keys_bound (F := F) d B).block + have he := (cols_bound (F := F) d B).block + have hg := (indices_bound (F := F) Δ d B).block + have w := (precision_bound (F := F) Δ d B).block.add hg + have cost : Cost (fun i : I => Mixing.cost (i.m + i.T.widthCols) i.height (K i) (D i)) := + ((rowCost Δ d B).expand he).add ((testCost d B w).scale 4) + refine Mixed.add ?_ cost + have a := (block_const 1).add (profile_arity (F := F) Δ d B).block + have hd := Long.row (Block.long (hk.mul hg)) + have h₁ := (he.long.row.add ((block_const 1).blocks)).mul a + have h₂ := (hd.left he).add (Block.blocks (he.mul hg)) + have h₃ := Row.expand (hg.blocks.add hd) he + refine ((Row.hosts h₁).add (((Row.hosts h₂).add (h₃.scale 2)).scale 4)).mono fun i => ?_ + change _ + 4 * ((Format.vec i.m (.pair (Mixing.Matrix i.T.widthCols (K i) (D i)) + (Mixing.Matrix i.height i.T.widthCols (D i)))).width + 2 * (Mixing.Rows _ _ _ _).width) ≤ _ + simp only [Mixing.Matrix, Mixing.Rows, Mixing.Input, Mixing.Num, Format.width_vec, + Format.width_pair, + Format.width_addr, mul_one] + exact le_rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end + +/- # Bounds for gathering a reset window -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +open Packing Assembly Assembly.History.Reset Case Coloring + +variable {F : Type} [Field F] {Y l : ℕ} (P : Rotor F Y l) (Δ C t d B : ℕ) +local notation "I" => Case F 1 d B +local notation "keys" => keyBits d B +local notation "walk" => depth d B + +theorem pair_budget {A Z : I → Format} + (h : Cost (fun i => (A i).width)) (k : Cost (fun i => (Z i).width)) : + Cost (fun i => ((A i).pair (Z i)).width) := + (h.add k).mono fun _ => (Format.width_pair ..).le + +private theorem vec_budget {A : I → Format} (h : Row (fun i => (A i).width)) : + Cost (fun i => (Format.vec i.m (A i)).width) := + h.hosts.mono fun _ => (Format.width_vec ..).le + +private theorem height_budget : Cost (fun i : I => (Format.addr i.height).width) := by + refine (height_short (F := F) d B).long.row.cost.mono fun i => ?_ + rw [Format.width_addr] + +theorem pair_bound : Cost (fun i : I => (Tile.pair i.T (keys i)).width) := + pair_budget d B Case.Child.parent.format (pair_budget d B (height_budget d B) (vec_budget d B + (stats_bound d B).long.row)) + +theorem window_groups {A : I → Format} (h : Short (fun i => (A i).width)) : + Cost (fun i : I => (Fmt.groups i.m i.T.scheme.d i.a (A i)).width) := by + have hc : Long (fun i : I => 2 ^ i.T.scheme.d * i.m) := Case.slots.short.long.mul hosts + refine (Row.hosts (hc.row.add h.block.groups)).mono fun i => ?_ + exact (Fmt.width_rows ..).le + +private theorem data_budget : Cost (fun i : I => (Mixing.Data i.height (Tile.data i.T) i.m).width) + := by + refine ((data_short (F := F) d B).block.blocks.hosts).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec] + +private theorem groups_budget : Cost (fun i : I => (Mixing.Groups i.height i.a (Tile.data i.T) + i.m).width) := by + refine (Row.hosts (Block.groups (tiles.short.block.mul (data_short d B).block))).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_vec] + +theorem packet_bound : Cost (fun i : I => Tile.packetCost i.T i.a (keys i)) := by + have h₁ := pair_budget d B (height_budget (F := F) d B) (data_budget d B) + have h₂ := window_groups d B (row_bound (F := F) d B) + exact BatchDescent.Phase.MixedCost.resetPacket + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (pair_bound d B) h₁ (groups_budget d B) h₂ (apply_bound d B) + +theorem maskCost_bound : Cost (fun i : I => Tile.maskCost i.T (walk i)) := by + have h : Long (fun i : I => (100 + (i.m + 2 ^ ((i.T.scheme.d + 1) * walk i))) ^ 50) := + ((long_const 100).add (hosts.add (walks_bound d B).long)).pow 50 + exact Case.Child.parent.format.add (Mixed.long Case.m h) + +local notation "dest" => child P Δ C t d B +local notation "growBy" => Reset.shift P Δ d B + +theorem carry_blocks {A : I → Format} (h : Short (fun i => (A i).width)) : + Cost (fun i : I => (Format.vec (dest i).scheme.m (.vec (dest i).scheme.h (A i))).width) := by + have H := child_bound P Δ C t d B + refine (H.cost (H.layer h.block)).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec] + +/-- The quantity computed by `i.p.fee (i.m + i.T.scheme.d) (Tile.volume i.T (dest i) (keys i) +(walk i))`. -/ +def readCost (i : I) := i.p.fee (i.m + i.T.scheme.d) (Tile.volume i.T (dest i) (keys i) (walk i)) + +theorem windowCost_bound : Cost (fun i : I => + Tile.windowCost i.T (dest i) (keys i) (walk i) (growBy i) (readCost P Δ C t d B i)) := by + have hc : Cost (fun i : I => (Tile.gathered i.T (dest i) (keys i) (walk i)).width) := + pair_budget d B (pair_bound d B) (pair_budget d B (vec_budget d B (mask_bound d B).long.row) + (window_groups d B (history_bound d B))) + have hquery := carry_blocks P Δ C t d B (sample_bound P Δ d B) + have hv : Row (fun i : I => Tile.volume i.T (dest i) (keys i) (walk i)) := + (history_bound d B).block.groups + have hread := Case.Child.parent.read Case.slots.short hv + have hsteps : Short (fun i : I => walk i + 1) := + (tiles.short.of_exp.add (short_const 8)).add (short_const 1) + exact BatchDescent.Phase.MixedCost.resetWindow + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (pair_bound d B) (packet_bound d B) (maskCost_bound d B) hc hquery (hread.left hsteps.block) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Reset +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Restart.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Restart.lean new file mode 100644 index 0000000000..895df6522a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Restart.lean @@ -0,0 +1,548 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.FreezeInput.Cost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Pass +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Recovery.Run + +/-! # Admission fits the three boundary budgets -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly + +theorem admission (d : ℕ) : ∃ j, ∀ {F : Type} [Field F] (D : Template F) (s : Plan) + (z payload : ℕ) (x y : Wire) (p : Prices F) (r : ℕ), D.scheme.d ≤ d → D.scheme.m ≤ p.w → + 3 + 2 * D.scheme.ℓ ≤ (BoundaryScale.short D z payload r p) ^ j ∧ + admitCost D s z payload x y ≤ BoundaryScale.cost (x := x) (y := y) D z payload r p j := by + let b := 10000 + 2 ^ d + let k := 2 + b + 1 + refine ⟨k * 14, ?_⟩ + intro F _ D s z payload x y p r hd hm + let A := BoundaryScale.short D z payload r p + let B := BoundaryScale.long D z payload r p + let C := BoundaryScale.outer D z payload p + let u := 10000 + 2 ^ D.scheme.d + D.scheme.ℓ + D.count + payload + have hb : 3 ≤ b := by unfold b; generalize 2 ^ d = n; omega + have ha : 100 + D.scheme.ℓ + D.count + payload ≤ A := by + unfold A BoundaryScale.short BoundaryScale.metadata BoundaryScale.base + generalize 2 ^ D.scheme.e = i, 2 ^ r = j + omega + have hB : A + D.scheme.m ≤ B := by + unfold B BoundaryScale.long + change _ ≤ 100 + p.w + _ + A + omega + have hC : 100 + payload ≤ C := by unfold C BoundaryScale.outer; omega + have hu : u ≤ A + b := by + have hh := Nat.pow_le_pow_right (by decide : 0 < 2) hd + unfold u b + omega + have powbound (N t : ℕ) (hN : 2 ≤ N) (ht : t ≤ 2 * N + b) : t ^ 14 ≤ N ^ (k * 14) := by + rw [pow_mul] + exact Nat.pow_le_pow_left (ht.trans (BoundaryScale.linear hN 2 b)) 14 + refine ⟨?_, (admit_cost D s z payload x y).trans ?_⟩ + · exact (Nat.le_self_pow (by decide : 14 ≠ 0) _).trans (powbound A _ (by omega) (by omega)) + · exact Nat.add_le_add (Nat.add_le_add + (Nat.mul_le_mul_left _ (powbound B (u + D.scheme.m) (by omega) (by omega))) + (Nat.mul_le_mul_left _ (powbound A u (by omega) (by omega)))) + (Nat.mul_le_mul_left _ (powbound C (100 + payload) (by omega) (by omega))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Room for the final recovery addresses after a fixed sequence of reductions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly + +private theorem power_room {M K : ℕ} (hm : 2 ≤ M) (hk : 2 ≤ K) : M + K ≤ M ^ K := by + have hp : 0 < M := by omega + have ha : M ≤ M ^ (K - 1) := Nat.le_pow (by omega) + have hb : K ≤ M ^ (K - 1) := by + have := (Nat.lt_two_pow_self (n := K - 1)).trans_le (Nat.pow_le_pow_left hm _) + omega + calc + _ ≤ M ^ (K - 1) * 2 := by omega + _ ≤ M ^ (K - 1) * M := Nat.mul_le_mul_left _ hm + _ = _ := by rw [← pow_succ, Nat.sub_add_cancel (by omega)] + +private theorem capacity (l n m w : ℕ) (h : n + m + 2 * l + 1 ≤ w) : + 2 ^ l * (n * (2 ^ m + 2 ^ (m + l))) < 2 ^ w := by + have hm : 2 ^ m ≤ 2 ^ (m + l) := Nat.pow_le_pow_right (by decide) (by omega) + calc + _ ≤ 2 ^ l * (n * (2 ^ (m + l) + 2 ^ (m + l))) := by gcongr + _ = n * 2 ^ (l + (m + l) + 1) := by rw [pow_succ, pow_add 2 l]; ring + _ < 2 ^ n * 2 ^ (l + (m + l) + 1) := Nat.mul_lt_mul_of_pos_right Nat.lt_two_pow_self + (Nat.two_pow_pos _) + _ ≤ _ := by rw [← pow_add]; exact Nat.pow_le_pow_right (by decide) (by omega) + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} {s : Plan} {T z payload r H d K l : ℕ} + {p : Prices F} {L : ℝ} + +theorem Result.address (q : Result (x := x) (y := y) (border D s z) s T L z payload p r H) + (h : Requirements D s T L z payload p r d K) (hk : H + s.K + s.M + s.d + s.p + 2 * l + 10 ≤ K) : + 1 ≤ q.next.scheme.m ∧ q.next.scheme.m + q.next.scheme.d ≤ p.w ∧ + 2 ^ l * ((max payload (q.next.scheme.h + Recovery.height s T) + 1)* + (2 ^ q.next.scheme.m + 2 ^ (q.next.scheme.m + l))) < 2 ^ p.w := by + have hv := (BoundaryScale.base_lower D z payload r).trans (BoundaryScale.lower D z payload r) + have ht := (BoundaryScale.two D z payload r).trans (BoundaryScale.lower D z payload r) + have hb := (power_room ht (show 2 ≤ K by omega)).trans h.small + have hu := width_bits h.upper + have hm : D.scheme.m ≤ q.next.scheme.m := q.growth.lower + have hn : q.next.scheme.m ≤ D.scheme.m + s.n * r + s.K := q.growth.upper + have hg : q.next.scheme.h + s.n * r = D.scheme.h := q.growth.height + have hd := q.growth.degree + have hw := h.address + have := Nat.zero_le (2 ^ r) + have := Nat.zero_le (2 ^ D.scheme.e) + refine ⟨by omega, by omega, capacity _ _ _ _ ?_⟩ + unfold Recovery.height + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- +# Label sizes after recovery + +Each restored station references one attachment label. All further +metadata is polynomially bounded in the initial short dimensions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly +variable {F : Type} [Field F] {x y : Wire} {D : Template F} {s : Plan} + {T z payload r H : ℕ} {L : ℝ} {p : Prices F} + +private theorem restored_size (q : Result (x := x) (y := y) (border D s z) s T L z payload p r H) + (hs : s.Fits) (hz : 0 < z) (ht : T ≤ z * s.M) (hl : 0 ≤ L) : + let X := Recovery.restored x y q.pack payload hs hz ht hl + X.template.scheme.ℓ + X.template.count = + 2 * q.pack.ℓ + 2 * q.pack.k + 4 * 2 ^ q.pack.e * (6 + q.pack.e) + 26 := by + let E := (Recovery.layer x y q.pack payload hs hz ht hl).template + change (Merge.scheme E.scheme).ℓ + E.count = _ + rw [Merge.label_width] + change (Restore.script q.pack.scheme).width + 2 ^ 3 * 3 + (Restore.script q.pack.scheme).width = _ + rw [Restore.script_width] + simp only [pow_add, pow_one] + ring + +theorem restored_labels (s : Plan) (hs : s.Fits) (d H : ℕ) : + ∃ j : ℕ, ∀ {F : Type} [Field F] {x y : Wire} {D : Template F} {T z payload r K : ℕ} + {L : ℝ} {p : Prices F} (q : Result (x := x) (y := y) (border D s z) s T L z payload p r H) + (h : Requirements D s T L z payload p r d K), + let X := Recovery.restored x y q.pack payload hs h.unit h.upper (zero_le_one.trans h.positive) + X.template.scheme.ℓ + X.template.count ≤ + j * (D.scheme.ℓ + D.count) + (BoundaryScale.base D z payload r) ^ j := by + let C := 4 * H * (1 + 2 ^ d) + 2 + 2 * (2 + s.K) + 4 * (1 + H) * (7 + H) + 26 + let k := (3 + d + 1) * H + 2 + let j := 4 * H + k + C + refine ⟨j, ?_⟩ + intro F _ x y D T z payload r K L p q h + let X := BoundaryScale.base D z payload r + let Y := D.scheme.ℓ + D.count + have h2 : 2 ≤ X := BoundaryScale.two .. + have hp : 0 < X := by omega + have hK : 2 ≤ k := Nat.le_add_left .. + have hx : 1 ≤ X ^ k := Nat.one_le_pow _ _ hp + have hh := BoundaryScale.base_lower D z payload r + have he := Nat.zero_le (2 ^ D.scheme.e) + have hr := Nat.zero_le (2 ^ r) + have hscale : ∀ c : ℕ, c ≤ c * X := fun c => Nat.le_mul_of_pos_right _ hp + have hslots : q.pack.k ≤ (2 + s.K) * X := calc + _ ≤ 1 + s.n * r + s.K := q.growth.stations + _ ≤ 1 + X + s.K := by have := h.height; omega + _ ≤ _ := by rw [add_mul]; have := hscale s.K; omega + have hext : 2 ^ q.pack.e ≤ (1 + H) * X := calc + _ ≤ 2 ^ D.scheme.e + H := q.growth.outer + _ ≤ _ := by rw [add_mul]; have := hscale H; omega + have hband : 6 + q.pack.e ≤ (7 + H) * X := by + have := Nat.lt_two_pow_self (n:=q.pack.e) + rw [add_mul] at hext ⊢ + omega + have hprev : q.pack.ℓ ≤ H * (2 * Y + 2 * (1 + 2 ^ d)) + X ^ k := by + have hl := (Nat.le_add_left q.pack.ℓ q.next.scheme.ℓ).trans q.growth.labels + have hc := cut_length D s z + change q.pack.ℓ ≤ H * ((inside D s z).scheme.ℓ + (border D s z).ℓ) + _ at hl + rw [hc.1, hc.2.1] at hl + refine hl.trans (Nat.add_le_add (Nat.mul_le_mul_left _ ?_) ?_) + · have := Nat.pow_le_pow_right (by decide : 0 < 2) h.degree + omega + · have := Nat.pow_le_pow_left (BoundaryScale.origin (r:=r) (z:=z) (payload:=payload) (s:=s) + h.degree) H + rw [← pow_mul] at this + exact this.trans (Nat.pow_le_pow_right hp (by omega)) + have hcost : C * X ^ k ≤ X ^ j := calc + _ ≤ X ^ C * X ^ k := Nat.mul_le_mul_right _ (Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left + h2 _)) + _ = X ^ (C + k) := (pow_add ..).symm + _ ≤ _ := Nat.pow_le_pow_right hp (by omega) + have hl : X ≤ X ^ k := Nat.le_pow (by omega) + have hh' : X ^ 2 ≤ X ^ k := Nat.pow_le_pow_right hp hK + dsimp only + rw [restored_size q hs h.unit h.upper (zero_le_one.trans h.positive)] + calc + _ ≤ 2 * (H * (2 * Y + 2 * (1 + 2 ^ d)) + X ^ k) + 2 * ((2 + s.K) * X) + 4 * ((1 + H) * X) * ((7 + + H) * X) + 26 := by gcongr + _ = 4 * H * Y + (4 * H * (1 + 2 ^ d) * 1 + 2 * X ^ k + 2 * (2 + s.K) * X + 4 * (1 + H) * (7 + + H) * X ^ 2 + 26 * 1) := by ring + _ ≤ 4 * H * Y + (4 * H * (1 + 2 ^ d) * X ^ k + 2 * X ^ k + 2 * (2 + s.K) * X ^ k + 4 * (1 + + H) * (7 + H) * X ^ k + 26 * X ^ k) := by gcongr + _ = 4 * H * Y + C * X ^ k := by unfold C; ring + _ ≤ _ := Nat.add_le_add (Nat.mul_le_mul_right _ (by omega)) hcost + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- +# Bounds on the three resources used by restoration + +Span counts enter the cost per occurrence. Only their logarithms +enter the factor multiplying the number of exterior ports. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly BatchDescent.Phase + +/-- Computes the extra by the application `Restore.bits s.slots s.slots s.w`. -/ +abbrev extra (s : Plan) := Restore.bits s.slots s.slots s.w + +/-- The data for the sample construction, including `F`, `[field`, `x`, `y`, `D`. -/ +structure Sample (s : Plan) (d H : ℕ) where + /-- The `Sample` component of type `Type`. -/ + F : Type + [field : Field F] + /-- The `Sample` component of type `Wire`. -/ + x : Wire + /-- The `Sample` component of type `Wire`. -/ + y : Wire + /-- The `Sample` component of type `Template F`. -/ + D : Template F + /-- The `Sample` field of type `ℕ`. -/ + T : ℕ + /-- The `Sample` field of type `ℝ`. -/ + L : ℝ + /-- The `Sample` field of type `ℕ`. -/ + z : ℕ + /-- Stores the payload associated with this `Sample`. -/ + payload : ℕ + /-- The `Sample` component of type `Prices F`. -/ + p : Prices F + /-- The `Sample` field of type `ℕ`. -/ + r : ℕ + /-- The `Sample` field of type `ℕ`. -/ + K : ℕ + h : Requirements D s T L z payload p r d K + /-- The `Sample` component of type `Result (x := x) (y := y) (border D s z) s T L z payload p + r H`. -/ + q : Result (x := x) (y := y) (border D s z) s T L z payload p r H + +attribute [instance] Sample.field + +namespace Sample +variable {s : Plan} {d H : ℕ} +local notation "I" => Sample s d H +variable (i : Sample s d H) + +/-- Computes the data by the application `BoundaryScale.metadata i.D i.z i.payload i.r`. -/ +abbrev data := BoundaryScale.metadata i.D i.z i.payload i.r +/-- Computes the fast by the application `BoundaryScale.short i.D i.z i.payload i.r i.p`. -/ +abbrev fast := BoundaryScale.short i.D i.z i.payload i.r i.p +/-- Computes the slow by the application `BoundaryScale.long i.D i.z i.payload i.r i.p`. -/ +abbrev slow := BoundaryScale.long i.D i.z i.payload i.r i.p +/-- Uses `BoundaryScale.outer i.D i.z i.payload i.p` as the representation. -/ +abbrev outer := BoundaryScale.outer i.D i.z i.payload i.p +/-- Uses `Recovery.measure i.q.pack s i.T i.payload i.p` as the representation. -/ +abbrev measure := Recovery.measure i.q.pack s i.T i.payload i.p +/-- Computes the core by the application `border i.D s i.z`. -/ +abbrev core := border i.D s i.z + +theorem two : 2 ≤ i.outer := by unfold outer BoundaryScale.outer; omega +theorem small : i.outer ≤ i.fast := by + have h := Nat.lt_two_pow_self (n := i.D.scheme.e) + have := Nat.zero_le (2 ^ i.r) + unfold outer BoundaryScale.outer fast BoundaryScale.short BoundaryScale.metadata + BoundaryScale.base + omega +theorem large : i.fast ≤ i.slow := Nat.le_add_left .. +theorem two_fast : 2 ≤ i.fast := i.two.trans i.small +theorem two_slow : 2 ≤ i.slow := i.two_fast.trans i.large + +/-- Computes the fast by the application `Poly fast f`. -/ +abbrev Fast (f : I → ℕ) := Poly fast f +/-- Computes the slow by the application `Poly slow f`. -/ +abbrev Slow (f : I → ℕ) := Poly slow f +/-- Computes the outer by the application `Poly outer f`. -/ +abbrev Outer (f : I → ℕ) := Poly outer f +variable {f : Sample s d H → ℕ} + +theorem Fast.slow (h : Fast f) : Slow f := h.grow large +theorem Outer.fast (h : Outer f) : Fast f := h.grow small +theorem constantValue (j : ℕ) : Fast (fun _ : I => j) := Poly.const two_fast j +theorem body : Fast (fun i : I => i.fast) := Poly.of_le two_fast fun _ => le_rfl +theorem high : Slow (fun i : I => i.slow) := Poly.of_le two_slow fun _ => le_rfl +theorem fields : Fast (fun i : I => i.data) := body.mono fun _ => Nat.le_add_right .. + +theorem old : Fast (fun i : I => short i.core i.r i.z i.payload) := + (fields.pow (BoundaryScale.charge d)).mono fun i => BoundaryScale.coded i.h.degree + +private theorem oldBase : Fast (fun i : I => base i.core i.r i.z i.payload) := + old.mono fun i => by unfold short; omega + +private theorem log_bound {a b c : ℕ} (h : 2 ^ a ≤ 2 ^ b + c) : a ≤ b + c := by + apply (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp + rw [pow_add] + refine h.trans ((Nat.add_le_add_left (Nat.le_mul_of_pos_left c (Nat.two_pow_pos b)) _).trans ?_) + simpa only [mul_add, mul_one] using Nat.mul_le_mul_left (2 ^ b) (show 1 + c ≤ 2 ^ c by + have := Nat.lt_two_pow_self (n := c) + omega) + +theorem exterior : Outer (fun i : I => i.measure.outer) := by + let j := 1010 + 2 * s.d + 2 * s.p + 2 * s.M + extra s + s.K + H + refine ⟨two, ⟨10 + j + 1, fun i => le_trans ?_ (BoundaryScale.linear i.two 10 j)⟩⟩ + have hh := i.q.growth.height + have hw := width_bits i.h.upper + have hk := i.q.growth.stations + have he := log_bound i.q.growth.outer + change i.q.next.scheme.h + s.n * i.r = i.D.scheme.h at hh + change i.q.pack.k ≤ 1 + s.n * i.r + s.K at hk + change i.q.pack.e ≤ i.D.scheme.e + H at he + change 1000 + i.p.W + i.payload + (i.q.next.scheme.h + (s.d + s.p + Nat.clog 2 i.T)) + extra s + + (max i.payload (i.q.next.scheme.h + (s.d + s.p + Nat.clog 2 i.T)) + 1) + + (i.q.next.scheme.h + (i.q.pack.k + (1 + i.q.pack.e))) ≤ _ + unfold outer BoundaryScale.outer j + omega + +private theorem groups : Fast (fun i : I => 2 ^ i.r) := by + refine fields.mono fun i => ?_ + have h := (BoundaryScale.base_lower i.D i.z i.payload i.r).trans (BoundaryScale.lower ..) + have := Nat.zero_le (2 ^ i.D.scheme.e) + unfold data + omega + +theorem copies : Fast (fun i : I => 2 ^ (s.n * i.r + s.K)) := by + simpa only [pow_add, pow_mul'] using (groups.pow s.n).mul (constantValue (2 ^ s.K)) + +private theorem spans : Fast (fun i : I => 2 ^ i.q.pack.e) := by + have h : Fast (fun i : I => 2 ^ i.D.scheme.e) := by + refine fields.mono fun i => ?_ + have h := (BoundaryScale.base_lower i.D i.z i.payload i.r).trans (BoundaryScale.lower ..) + have := Nat.zero_le (2 ^ i.r) + unfold data + omega + exact (h.add (constantValue H)).mono (fun i => i.q.growth.outer) + +private theorem stations : Fast (fun i : I => 2 ^ i.q.pack.k) := by + refine ((constantValue (2 ^ 1)).exp_add copies).mono fun i => ?_ + rw [← add_assoc] + exact Nat.pow_le_pow_right (by decide) i.q.growth.stations + +private theorem labels : Fast (fun i : I => i.q.pack.ℓ + i.q.next.scheme.ℓ + i.q.next.count) := by + have a : Fast (fun i : I => (inside i.D s i.z).scheme.ℓ + i.core.ℓ) := by + refine old.mono fun i => ?_ + change _ ≤ base i.core i.r i.z i.payload + (inside i.D s i.z).scheme.ℓ + i.core.ℓ + _ + omega + have b := (oldBase (s := s) (d := d) (H := H)).pow H + refine ((((constantValue H).mul a).add b).add b).mono fun i => ?_ + rw [add_comm i.q.pack.ℓ] + exact Nat.add_le_add i.q.growth.labels i.q.growth.counters + +theorem controls : Fast (fun i : I => i.measure.short) := by + have h : Fast (fun i : I => 2 ^ i.q.next.scheme.d) := + (constantValue (2 ^ H)).mono fun i => Nat.pow_le_pow_right (by decide) i.q.growth.degree + have n : Fast (fun i : I => 2 ^ i.measure.n) := stations.exp_add ((constantValue (2 ^ 1)).exp_add + spans) + have c : Fast (fun i : I => Install.localCost (2 ^ i.measure.d + (2 + i.measure.d + + i.measure.l))) := by + refine (constantValue (Install.localCost (2 ^ H + (2 + H + extra s)))).mono fun i => ?_ + have e := i.q.growth.degree + change Install.localCost (2 ^ i.q.next.scheme.d + (2 + i.q.next.scheme.d + extra s)) ≤ _ + unfold Install.localCost + gcongr + exact (((((exterior.fast.add labels).add h).add n).add (constantValue (2 ^ extra s))).add c) + +theorem addresses : Slow (fun i : I => i.measure.long) := by + have a : Slow (fun i : I => i.p.w + i.p.w ^ i.p.power) := + high.mono fun i => by unfold slow BoundaryScale.long; omega + have b : Slow (fun i : I => i.measure.m) := by + refine high.mono fun i => ?_ + have h := i.q.growth.upper + change i.q.next.scheme.m ≤ i.D.scheme.m + s.n * i.r + s.K at h + change i.q.next.scheme.m ≤ _ + have h₁ := i.h.address + have h₂ := i.h.height + have h₃ := i.h.room + have h₄ := Nat.zero_le (i.p.w ^ i.p.power) + unfold slow BoundaryScale.long BoundaryScale.short BoundaryScale.metadata BoundaryScale.base + have h₅ := Nat.zero_le (2 ^ i.D.scheme.e) + omega + refine (((controls.slow.add b).add (b.add (constantValue (extra s)).slow)).add a).mono fun i => ?_ + unfold Restore.Measure.long + rw [add_assoc _ i.measure.c.w] + exact le_rfl + +end Sample +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # One cost allowance for both the contractions and restoration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Sample +open Assembly BatchDescent.Phase +variable {s : Plan} {d H : ℕ} +local notation "I" => Sample s d H + +private theorem addr : Slow (fun i : I => 100 + i.p.w + i.p.w ^ i.p.power + i.p.W + + short i.core i.r i.z i.payload) := by + refine (high.add old.slow).mono fun i => ?_ + unfold slow BoundaryScale.long BoundaryScale.short + omega + +private theorem volume : Fast (fun i : I => short i.core i.r i.z i.payload + i.p.W) := by + refine (old.add body).mono fun i => ?_ + unfold fast BoundaryScale.short + omega + +private theorem ports : Outer (fun i : I => 100 + i.payload + i.p.W) := + Poly.of_le two fun i => by unfold outer BoundaryScale.outer; omega + +/-- The growth of the host count can be paid from the grouping size. -/ +private theorem hosts (i : I) : + 2 ^ i.measure.m ≤ 2 ^ i.D.scheme.m * 2 ^ (s.n * i.r + s.K) ∧ + 2 ^ (i.measure.m + i.measure.h) ≤ 2 ^ (i.D.scheme.m + i.D.scheme.h) * 2 ^ (s.n * i.r + s.K) + := by + have ha := i.q.growth.upper + have hb := i.q.growth.height + change i.measure.m ≤ i.D.scheme.m + s.n * i.r + s.K at ha + change i.measure.h + s.n * i.r = i.D.scheme.h at hb + constructor <;> rw [← pow_add] <;> exact Nat.pow_le_pow_right (by decide) (by omega) + +theorem bounds (s : Plan) (d H J : ℕ) : + ∃ j, ∀ i : Sample s d H, + 5 + (short i.core i.r i.z i.payload) ^ H + i.measure.short ^ J ≤ i.fast ^ j ∧ + size (x := i.x) (y := i.y) i.core i.p i.r i.z i.payload H + i.measure.budget i.x i.y J ≤ + BoundaryScale.cost (x := i.x) (y := i.y) i.D i.z i.payload i.r i.p j := by + let g := copies (s := s) (d := d) (H := H) + have c := controls (s := s) (d := d) (H := H) + obtain ⟨a, ha⟩ := ((addr.pow H).add (g.slow.mul (addresses.pow J))).bound + obtain ⟨b, hb⟩ := ((volume.pow H).add (g.mul (c.pow J))).bound + obtain ⟨l, hl⟩ := (((ports (s := s) (d := d) (H := H)).pow H).add (exterior.pow J)).bound + obtain ⟨k, hk⟩ := (((constantValue 5).add (old.pow H)).add (c.pow J)).bound + let j := a + b + l + k + refine ⟨j, fun i => ?_⟩ + have rr {X Y t : ℕ} (h : 2 ≤ Y) (f : X ≤ Y ^ t) (ht : t ≤ j) : X ≤ Y ^ j := + f.trans (Nat.pow_le_pow_right (by omega) ht) + refine ⟨rr i.two_fast (hk i) (by unfold j; omega), ?_⟩ + have x := Nat.mul_le_mul_left (2 ^ i.D.scheme.m) (rr i.two_slow (ha i) (by unfold j; omega)) + have y := Nat.mul_le_mul_left (2 ^ (i.D.scheme.m + + i.D.scheme.h)) (rr i.two_fast (hb i) (by unfold j; omega)) + have z := Nat.mul_le_mul_left (wd i.x + wd i.y) (rr i.two (hl i) (by unfold j; omega)) + have m := Nat.mul_le_mul_right (i.measure.long ^ J) i.hosts.1 + have b := Nat.mul_le_mul_right (i.measure.short ^ J) i.hosts.2 + rw [mul_add, ← mul_assoc] at x y + rw [mul_add] at z + change 2 ^ i.D.scheme.m * (100 + i.p.w + i.p.w ^ i.p.power + i.p.W + + short i.core i.r i.z i.payload) ^ H + + 2 ^ (i.D.scheme.m + i.D.scheme.h) * (short i.core i.r i.z i.payload + i.p.W) ^ H + + (wd i.x + wd i.y) * (100 + i.payload + i.p.W) ^ H + _ ≤ + 2 ^ i.D.scheme.m * i.slow ^ j + 2 ^ (i.D.scheme.m + i.D.scheme.h) * i.fast ^ j + (wd i.x + + wd i.y) * i.outer ^ j + unfold Restore.Measure.budget + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Sample +end + +/- +# Restarting after local concentration + +Compose admission, reduction of the core, and reassembly of the frozen +border. This is a transformation of the complete weighted state space. +The dictionaries and capacity limits are shared by all summands. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly + +open scoped Classical in +theorem restarts {k : Type} [Field k] {s : Plan} (hs : s.Fits) + (q : Block k s.c 3 s.b s.n s.e s.K s.ρ s.loss) (d : ℕ) : ∃ K, 0 < K ∧ Restarts k s d K := by + obtain ⟨a, ha⟩ := admission d + obtain ⟨H, _, red⟩ := reduce hs q d + obtain ⟨J, hJ⟩ := Recovery.run + obtain ⟨b, hb⟩ := Sample.bounds s d H J + obtain ⟨c, hc⟩ := restored_labels s hs d H + let K := a + b + c + BoundaryScale.charge d * H + H + s.K + s.M + s.d + s.p + 2 * extra s + 15 + refine ⟨K, by unfold K; omega, ?_⟩ + intro F _ _ _ x y D T L z payload p r h + have hz : 0 < s.b * z := Nat.mul_pos q.unit h.unit + have hT : 0 < T := (Nat.mul_pos hz (pow_pos (show 0 + < s.D by have := s.two hs; omega) _)).trans_le h.lower + have hL := zero_le_one.trans h.positive + obtain ⟨hfour, hsmall, hupper⟩ := h.pass (H := H) (by unfold K; omega) + let A := border D s z + obtain ⟨v⟩ := red F (x := x) (y := y) A T L z payload p r + h.positive h.unit h.lower h.upper h.height h.room h.slack h.degree rfl h.single h.alphabet + hfour hsmall hupper + obtain ⟨hpos, hdeg, hprice⟩ := v.address (l := extra s) h (by unfold K; omega) + obtain ⟨E, he, endStage⟩ := hJ x y v.pack payload hs h.unit h.upper hL p hpos hdeg hprice + let X := Recovery.restored x y v.pack payload hs h.unit h.upper hL + let Y := Recovery.measure v.pack s T payload p + let B := BoundaryScale.short D z payload r p + let S := BoundaryScale.cost (x := x) (y := y) D z payload r p + let M := short A r z payload + let menu := insert (admitLabel D) (v.keys ∪ E) + let i : Sample s d H := ⟨F, x, y, D, T, L, z, payload, p, r, K, h, v⟩ + have raised {j : ℕ} (hj : j ≤ K) : B ^ j ≤ B ^ K := + Nat.pow_le_pow_right ((by decide : 0 < 2).trans_le i.two_fast) hj + have h₁ := ha D s z payload x y p r h.degree (by have := h.address; omega) + have h₂ := hb i + have u₁ : 3 + 2 * D.scheme.ℓ ≤ B ^ K := h₁.1.trans (raised (by unfold K; omega)) + have u₂ : 5 + M ^ H + Y.short ^ J ≤ B ^ K := h₂.1.trans (raised (by unfold K; omega)) + have few : menu.card ≤ B ^ K := by + have hs := Finset.card_insert_le (admitLabel D) (v.keys ∪ E) + have hu := Finset.card_union_le v.keys E + have hv : v.keys.card ≤ M ^ H := v.few + unfold menu + omega + have f := (admit_transfer (x := x) (y := y) (payload + := payload) hs hz h.positive hT h.single).widen + (L' := ↑menu) u₁ (Set.singleton_subset_iff.mpr (Finset.mem_insert_self ..)) + have g := v.transfer.widen (L' := ↑menu) (show M ^ H ≤ B ^ K by omega) + (fun _ ht => Finset.mem_insert_of_mem (Finset.mem_union_left _ ht)) + have e := endStage (C := ↑menu) (show 3 ≤ B ^ K by omega) + (fun _ ht => Finset.mem_insert_of_mem (Finset.mem_union_right _ ht)) + (show Y.short ^ J ≤ B ^ K by omega) + have cost : S a + S b ≤ S K := + BoundaryScale.plus.trans (BoundaryScale.increasing (by unfold K; omega)) + have net := (f.comp (g.comp e)).mono ((Nat.add_le_add h₁.2 h₂.2).trans cost) + have st := Recovery.stable x y v.pack payload hs h.unit h.upper hL + have low : D.scheme.m ≤ v.next.scheme.m := v.growth.lower + have high : v.next.scheme.m ≤ D.scheme.m + s.n * r + s.K := v.growth.upper + have height : v.next.scheme.h + s.n * r = D.scheme.h := v.growth.height + refine ⟨⟨X, st.1, st.2, low.trans (Nat.le_add_right ..), ?_, height, le_rfl, rfl, rfl, ?_, ?_, + menu, few, net⟩⟩ + · change v.next.scheme.m + extra s + v.next.scheme.h ≤ _ + unfold K + omega + · change v.next.scheme.h + (s.d + s.p + Nat.clog 2 T) ≤ v.next.scheme.h + s.d + s.p + Nat.clog 2 T + omega + · refine (hc v h).trans ?_ + have hk : c ≤ K := by unfold K; omega + exact Nat.add_le_add (Nat.mul_le_mul_right _ hk) + (Nat.pow_le_pow_right ((by decide : 0 < 2).trans_le (BoundaryScale.two ..)) hk) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Shipment.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Shipment.lean new file mode 100644 index 0000000000..ade215ae98 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Shipment.lean @@ -0,0 +1,896 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Beat.Fanout +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanSupplies +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Volumes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.ShortNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Beat + +/-! # Relaxing the degree and resource allowances after a contraction -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction + +open Assembly +variable {F k : Type} [Field F] [Field k] {x y : Wire} {T Y : Template F} + {A : Attachment T} {A' : Attachment Y} {L : BorderLimit F x y} + {r b u v z payload d B n e K K' H H' Δ Δ' Δ'' C C' : ℕ} + {ρ c ρ' c' σ : ℝ} {P P' : Bound} {p : Prices F} + +theorem relax_frame {X : Snapshot.{1} F x y} {G : Set (Table F)} + (f : Transforms F H G X (frame A L u z payload Δ C P) n) + (hd : Δ ≤ Δ') (hc : C ≤ C') (hb : P.load ≤ P'.load) + (hw : P.width ≤ P'.width) (hm : P.mass ≤ P'.mass) : + Transforms F H G X (frame A L u z payload Δ' C' P') n := by + obtain ⟨q, hq, he⟩ := f + refine ⟨q, hq, fun s => ?_⟩ + obtain ⟨I, _, a, l, ha, hl⟩ := he s + have h (i : I) : Ready A L z Δ' C' P' (a i).val := + { (a i).property.1 with + simple := fun h => (a i).property.1.simple (hd.trans h) + bounded := (a i).property.1.bounded.mono hd hc hb + width := (a i).property.1.width.trans hw + mass := (a i).property.1.mass.trans hm } + exact ⟨I, inferInstance, fun i => ⟨(a i).val, h i, (a i).property.2⟩, l, ha, hl⟩ + +omit [Field F] in +theorem Growth.overhead (g : Growth A A' r z payload n K H) (hk : K ≤ K') : + Growth A A' r z payload n K' H := + { g with upper := g.upper.trans (Nat.add_le_add_left hk _) + stations := g.stations.trans (Nat.add_le_add_left hk _) } + +theorem Phase.block (q : Phase k Δ Δ' b e K ρ c) (hu : 0 < b) (hk : 0 < K) + (hd : ∀ C, Δ ≤ C → Δ' ≤ C ^ e) (hf : 0 ≤ ρ) (hl : 0 ≤ c) : + Block k Δ Δ' b 1 e K ρ c := by + refine ⟨hu, by decide, hk, hd, hf, hl, fun C d B hC => ?_⟩ + obtain ⟨H, hH, run⟩ := q C d B hC + refine ⟨H, hH, ?_⟩ + intro F _ _ _ x y T A L P p r u v z payload σ h + obtain ⟨s⟩ := run F A L P p r u v z payload σ h.toInput + have g : Growth A s.pack r z payload 1 K H := + ⟨by simpa only [one_mul] using s.height, s.lower, by simpa only [one_mul] using s.upper, + s.degree, s.full, s.single, s.spans, by simpa only [one_mul] using s.stations, + s.outer, s.counters, s.labels⟩ + refine ⟨⟨s.next, s.pack, g, s.keys, s.few, relax_frame s.transfer le_rfl le_rfl le_rfl le_rfl ?_⟩⟩ + have hx := h.width + have hs := add_nonneg h.total h.nonneg + change P.mass + 2 * P.width ≤ P.mass + 2 * K * (P.width + (L.total + σ)) + have hK : (1 : ℝ) ≤ K := by exact_mod_cast hk + nlinarith only [mul_nonneg (sub_nonneg.mpr hK) hx, mul_nonneg (Nat.cast_nonneg (α := ℝ) K) hs] + +theorem Start.shrink (h : Start A L P p r b u v z payload d B n K H σ) (hk : K' ≤ K) + (hh : 0 < H') (hH : H' ≤ H) : Start A L P p r b u v z payload d B n K' H' σ := by + have hw := h.width + have hZ := add_nonneg h.total h.nonneg + have hB := (Nat.cast_nonneg u).trans h.load + have hs : 0 < short A r z payload := by unfold short base; positivity + refine { h with + room := hk.trans h.room + positive := hh + small := (Nat.pow_le_pow_right hs hH).trans h.small + space := (by have := h.space; omega) + slack := le_trans ?_ h.slack + reserve := le_trans ?_ h.reserve } <;> gcongr + +theorem Block.relax (q : Block k Δ Δ' b n e K ρ c) (hk : K ≤ K') (hρ : ρ ≤ ρ') (hc : c ≤ c') : + Block k Δ Δ' b n e K' ρ' c' := by + refine ⟨q.unit, q.steps, q.overhead.trans_le hk, q.degree, q.factor.trans hρ, q.loss.trans hc, + fun C d B hC => ?_⟩ + obtain ⟨H, hH, run⟩ := q.run C d B hC + refine ⟨H, hH, ?_⟩ + intro F _ _ _ x y T A L P p r u v z payload σ h + obtain ⟨s⟩ := run F A L P p r u v z payload σ (h.shrink hk hH le_rfl) + have hw := h.width + have hZ := add_nonneg h.total h.nonneg + have hb := (Nat.cast_nonneg u).trans h.load + refine ⟨⟨s.next, s.pack, s.growth.overhead hk, s.keys, s.few, + relax_frame s.transfer le_rfl le_rfl ?_ ?_ ?_⟩⟩ <;> dsimp only [limit, after] <;> gcongr + +theorem Block.degree_mono (q : Block k Δ Δ' b n e K ρ c) (hd : Δ' ≤ Δ'') + (hf : ∀ C, Δ ≤ C → Δ'' ≤ C ^ e) : Block k Δ Δ'' b n e K ρ c := by + refine ⟨q.unit, q.steps, q.overhead, hf, q.factor, q.loss, fun C d B hC => ?_⟩ + obtain ⟨H, hH, run⟩ := q.run C d B hC + refine ⟨H, hH, ?_⟩ + intro F _ _ _ x y T A L P p r u v z payload σ h + obtain ⟨s⟩ := run F A L P p r u v z payload σ h + exact ⟨⟨s.next, s.pack, s.growth, s.keys, s.few, + relax_frame s.transfer hd le_rfl le_rfl le_rfl le_rfl⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Physical costs of two consecutive blocks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Block + +open Assembly +variable {F : Type} {x y : Wire} {T Y : Template F} + {A : Attachment T} {A' : Attachment Y} {L : BorderLimit F x y} + {r z payload n K J H : ℕ} {ρ c τ b σ : ℝ} {P : Bound} + +/-- The host address can grow by `K` extra bits. Only the charge +for the *first* block is exponentiated. -/ +def fee (K : ℕ) (ρ c : ℝ) := K + K * 2 ^ K + ⌈ρ + c + 1⌉₊ + 1 + +theorem add_fee (hj : 0 < J) : K + J ≤ fee K ρ c * J := calc + _ ≤ K * J + J := Nat.add_le_add_right (Nat.le_mul_of_pos_right K hj) J + _ = (K + 1) * J := by ring + _ ≤ _ := Nat.mul_le_mul_right _ (by unfold fee; omega) + +private theorem load_fee : J * K ≤ fee K ρ c * J := by + rw [mul_comm J] + exact Nat.mul_le_mul_right _ (by unfold fee; omega) + +theorem chain_load (hl : 0 ≤ P.load) : + (limit L (limit L P K ρ c σ) J τ b σ).load ≤ + (limit L P (fee K ρ c * J) (τ * ρ) (τ * c + b) σ).load := by + dsimp only [limit, after] + rw [← mul_assoc, ← Nat.cast_mul] + exact mul_le_mul_of_nonneg_right (Nat.cast_le.mpr load_fee) hl + +theorem chain_width : + (limit L (limit L P K ρ c σ) J τ b σ).width = + (limit L P (fee K ρ c * J) (τ * ρ) (τ * c + b) σ).width := by + dsimp only [limit, after] + ring + +theorem chain_mass (hj : 0 < J) (hw : 0 ≤ P.width) (ht : 0 ≤ L.total + σ) (hr : 0 ≤ ρ) (hc : 0 + ≤ c) : + (limit L (limit L P K ρ c σ) J τ b σ).mass ≤ + (limit L P (fee K ρ c * J) (τ * ρ) (τ * c + b) σ).mass := by + let a := ⌈ρ + c + 1⌉₊ + have hs : ρ * P.width + c * (L.total + σ) + (L.total + σ) ≤ a * (P.width + (L.total + σ)) := calc + _ ≤ (ρ + c + 1) * (P.width + (L.total + σ)) := by + nlinarith only [mul_nonneg hr ht, mul_nonneg hc hw, hw] + _ ≤ _ := mul_le_mul_of_nonneg_right (Nat.le_ceil _) (add_nonneg hw ht) + have hf : K + J * a ≤ fee K ρ c * J := calc + _ ≤ K * J + J * a := Nat.add_le_add_right (Nat.le_mul_of_pos_right K hj) _ + _ = (K + a) * J := by ring + _ ≤ _ := Nat.mul_le_mul_right _ (by unfold fee a; omega) + dsimp only [limit, after] + calc + _ ≤ (P.mass + 2 * K * (P.width + (L.total + σ))) + 2 * J * ((a : ℝ) * (P.width + (L.total + + σ))) := by gcongr + _ = P.mass + 2 * (K + J * a : ℕ) * (P.width + (L.total + σ)) := by push_cast; ring + _ ≤ _ := by gcongr + +theorem chain_seats (g : Growth A A' r z payload n K H) (hl : 0 ≤ P.load) : + (J : ℝ) * (limit L P K ρ c σ).load * (2 ^ (Y.scheme.m + Y.scheme.h) : ℕ) ≤ + (fee K ρ c * J : ℕ) * P.load * (2 ^ (T.scheme.m + T.scheme.h) : ℕ) := by + have h : 2 ^ (Y.scheme.m + Y.scheme.h) ≤ (2 ^ K : ℕ) * 2 ^ (T.scheme.m + T.scheme.h) := by + rw [← pow_add] + exact Nat.pow_le_pow_right (by decide) (by have := g.upper; have := g.height; omega) + have hf : K * 2 ^ K * J ≤ fee K ρ c * J := Nat.mul_le_mul_right _ (by unfold fee; omega) + change (J : ℝ) * (K * P.load) * _ ≤ _ + calc + _ ≤ (J : ℝ) * (K * P.load) * (2 ^ K * 2 ^ (T.scheme.m + T.scheme.h) : ℕ) := by gcongr + _ = (K * 2 ^ K * J : ℕ) * P.load * (2 ^ (T.scheme.m + T.scheme.h) : ℕ) := by push_cast; ring + _ ≤ _ := by gcongr + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Block +end + +/- # Reserving wire histories within the frozen-charge bound -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing + +namespace Contraction + +/-- The quantity computed by `2 * s.K * (s.A * (1 + s.d) ^ 2 + s.A + 1)`. -/ +def allowance (s : Plan) := 2 * s.K * (s.A * (1 + s.d) ^ 2 + s.A + 1) + +/-- The quantity computed by `⌈(allowance s : ℝ) * L⌉₊`. -/ +def reserve (s : Plan) (L : ℝ) : ℕ := ⌈(allowance s : ℝ) * L⌉₊ + +/-- One extra unit in the coefficient covers rounding the cap when `1 ≤ L`. -/ +def discount (s : Plan) := Nat.clog 2 ((allowance s + 1) * s.D) + +variable {s : Plan} {L : ℝ} + +theorem le_reserve (hs : s.Fits) (hL : 1 ≤ L) : + 2 * s.K * (s.A * (1 + (s.d : ℝ)) ^ 2 * L + (s.A / Real.sqrt s.D * L + L / s.D)) ≤ reserve s L + := by + have hd : (1 : ℝ) ≤ s.D := Nat.one_le_cast.mpr (le_trans (by decide) (s.two hs)) + calc + _ ≤ 2 * s.K * (s.A * (1 + (s.d : ℝ)) ^ 2 * L + (s.A * L + L)) := by + gcongr + · exact div_le_self (Nat.cast_nonneg _) (Real.one_le_sqrt.mpr hd) + · exact div_le_self (by linarith) hd + _ = (allowance s : ℝ) * L := by unfold allowance; push_cast; ring + _ ≤ _ := Nat.le_ceil _ + +theorem discount_bound (hs : s.Fits) (hL : 1 ≤ L) : + s.C * (10000 * L) / Real.sqrt s.D + (reserve s L : ℝ) / (2 : ℝ) ^ (discount s) ≤ + s.A / Real.sqrt s.D * L := by + have hd : (1 : ℝ) ≤ s.D := Nat.one_le_cast.mpr (le_trans (by decide) (s.two hs)) + have hcap : (reserve s L : ℝ) ≤ (allowance s + 1) * L := calc + _ ≤ (allowance s : ℝ) * L + 1 := (Nat.ceil_lt_add_one (by positivity)).le + _ ≤ _ := by linarith + have hsize : ((allowance s : ℝ) + 1) * s.D ≤ (2 : ℝ) ^ (discount s) := by + exact_mod_cast Nat.le_pow_clog (by decide : 1 < 2) ((allowance s + 1) * s.D) + have small : (reserve s L : ℝ) / (2 : ℝ) ^ (discount s) ≤ L / Real.sqrt s.D := by + apply (div_le_div_iff₀ (by positivity) (by positivity)).mpr + calc + _ ≤ ((allowance s : ℝ) + 1) * L * s.D := + mul_le_mul hcap (Real.sqrt_le_self_iff.mpr (.inr hd)) (by positivity) (by positivity) + _ = L * (((allowance s : ℝ) + 1) * s.D) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left hsize (by positivity) + calc + _ ≤ s.C * (10000 * L) / Real.sqrt s.D + L / Real.sqrt s.D := add_le_add_right small _ + _ = ((s.C : ℝ) * 10000 + 1) / Real.sqrt s.D * L := by ring + _ ≤ _ := by gcongr; simp [Plan.A]; linarith + +end Contraction + +open scoped Classical in +theorem Concentrated.reserve {F : Type} {x y : Wire} {h u : ℕ} + {Q : LocalTerm F x y h u} {s : Plan} (hs : s.Fits) {L : ℝ} {T R g : ℕ} + {P : Input F x y h s.D T R g (10000 * L)} (hq : Concentrated P Q s.C s.d 10) + (hL : 1 ≤ L) (hT : 0 < T) (hu : 0 < u) : + Fringe.Z { Q.fringe (s.two hs) with + cap := Contraction.reserve s L, discount := Contraction.discount s } + ≤ s.A / Real.sqrt s.D * L ∧ + ((Q.host (s.two hs) hu).X : ℝ) ≤ s.A * (1 + (s.d : ℝ)) ^ 2 * L := by + refine ⟨?_, (hq.raw hs (by positivity) hT hu).2⟩ + refine le_trans ?_ (Contraction.discount_bound hs hL) + apply add_le_add _ le_rfl + exact (le_add_of_nonneg_right (Fringe.reserve_nonneg _)).trans (hq.frozen_mass (s.two hs) hT) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # From a concentrated term to a restorable attached core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Packing Finset + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} + (A : Attachment D) (s : Plan) (T : ℕ) (L : ℝ) (z payload : ℕ) + +/-- The data for the protected construction, including `cover`, `square`, `maximum`, `fixed`. -/ +structure Protected {I : Type} [Fintype I] {a b : Wire} + (G : Fringe a b I) (Z : Border F I x y a b) : Prop where + cover : ∀ i, (wd (Z.table i).1 + wd (Z.table i).2.1 : ℕ) ≤ G.charge i + square : (∑ i, G.charge i ^ 2) ≤ (s.A : ℝ) * L * T + maximum : ∀ i, G.charge i ≤ (s.A : ℝ) * s.D * T + fixed : ∀ i, G.charge i ≤ (s.C : ℝ) * s.D * T + +/-- Builds `BorderLimit F x y where denom` with the specified `denom`, `discount`, `cap`, +`total`. -/ +abbrev fringe : BorderLimit F x y where + denom := s.D ^ 4 + discount := discount s + cap := reserve s L + total := s.A / Real.sqrt s.D * L + test _ _ _ _ G Z := Protected s T L G Z + +/-- The quantity computed by `⟨T / s.D, s.A * (1 + (s.d : ℝ)) ^ 2 * L, 0⟩`. -/ +abbrev origin : Bound := ⟨T / s.D, s.A * (1 + (s.d : ℝ)) ^ 2 * L, 0⟩ + +/-- The quantity computed by `⟨T, (s.ρ * s.A * (1 + (s.d : ℝ)) ^ 2 + s.loss * ((s.A + 1) / +Real.sqrt s.D)) * L, reserve s L⟩`. -/ +abbrev destination : Bound := + ⟨T, (s.ρ * s.A * (1 + (s.d : ℝ)) ^ 2 + s.loss * ((s.A + 1) / Real.sqrt s.D)) * L, reserve s L⟩ + +/-- The quantity computed by `frame (x := x) (y := y) A (fringe s T L) (s.b * z) z payload s.c +(s.D ^ s.c) (origin s T L)`. -/ +abbrev initial := frame (x := x) (y := y) A (fringe s T L) (s.b * z) z payload s.c (s.D ^ s.c) + (origin s T L) +/-- The value specified by `frame (x := x) (y := y) A (fringe s T L) z z payload 3 s.full +(destination s T L)`. -/ +abbrev final := frame (x := x) (y := y) A (fringe s T L) z z payload 3 s.full (destination s T L) + +variable {A s T L z payload} + +theorem allocation (hs : s.Fits) (hz : 0 < z) (hunit : T ≤ z * s.M) + (X : (final (x := x) (y := y) A s T L z payload).state) : + Nonempty (X.val.G.Restore s.full s.slots s.slots) := by + have h := X.property.1 + have hd : (1 : ℝ) ≤ s.D := by exact_mod_cast (show 1 ≤ s.D by have := s.two hs; omega) + have hcap := s.slots_cover hs T z hunit + have lower (i : X.val.T) : (z : ℝ) ≤ X.val.L.charge i := by + obtain ⟨n, hn, he⟩ := h.charge i + rw [he] + exact Nat.cast_le.mpr hn + have upper (i : X.val.T) : X.val.L.charge i ≤ (s.slots : ℝ) * z := calc + _ ≤ (s.C : ℝ) * s.D * T := h.test.fixed i + _ ≤ (s.D : ℝ) ^ 2 * T := by + rw [pow_two] + gcongr + exact s.small.trans hs.degree + _ ≤ (s.D : ℝ) ^ 4 * T := mul_le_mul_of_nonneg_right (pow_le_pow_right₀ hd (by decide)) + (Nat.cast_nonneg _) + _ ≤ _ := hcap + have ha : (T : ℝ) ≤ X.val.L.scale * (s.slots * (z : ℝ)) := by + rw [h.scale, show (fringe (F := F) (x := x) (y := y) s T L).denom = s.D ^ 4 from rfl, + Nat.cast_pow, one_div_mul_eq_div, le_div_iff₀ (by positivity), mul_comm (T : ℝ)] + exact hcap + exact X.val.G.restore s.full s.slots s.slots T z (Nat.cast_pos.mpr hz) h.bounded ha + (fun i => ⟨lower i, upper i⟩) (fun i => Nat.cast_le.mpr (h.parallel i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- +# Concentration bounds for a specified ordering of the core packets + +The presentation fixes a packet order. Changing this order leaves the +initial charge, core width and parallel tether counts unchanged. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Packing + +variable {F : Type} {x y : Wire} {h u : ℕ} {s : Plan} (hs : s.Fits) + (L : ℝ) (Q : LocalTerm F x y h u) + +open scoped Classical in +/-- Uses `{ Q.fringe (s.two hs) with cap := reserve s L, discount := discount s }` as the +representation. -/ +abbrev frozen : Fringe Q.freeze.x Q.freeze.y Q.freeze.Fixed := + { Q.fringe (s.two hs) with cap := reserve s L, discount := discount s } + +variable (hu : 0 < u) (E : Packets Q.freeze.core u) + +open scoped Classical in +/-- Computes the hosted by the application `Q.frame.hostOf hu (frozen hs L Q) rfl E`. -/ +abbrev hosted := Q.frame.hostOf hu (frozen hs L Q) rfl E + +local notation "G" => hosted hs L Q hu E +local notation "old" => Q.host (s.two hs) hu + +open scoped Classical in +theorem hosted_load (v : Q.V) (i : Cell h) : (G).load v i = (old).load v i := by + have hae := HostNet.load_eq (G) (v, i) + have hbe := HostNet.load_eq (old) (v, i) + rw [show (G).past (v, i) = 0 from rfl, Nat.cast_zero, mul_zero, add_zero] at hae + rw [show (old).past (v, i) = 0 from rfl, Nat.cast_zero, mul_zero, add_zero] at hbe + exact hae.trans hbe.symm + +open scoped Classical in +theorem hosted_width : (G).X = (old).X := by + have he := Fintype.card_congr ((G).units.bits.symm.trans (old).units.bits) + simpa only [HostNet.X, Fintype.card_prod, Fintype.card_fin] using he + +variable {L Q} {R T g : ℕ} {P : Rounds.Input F x y h s.D T R g (10000 * L)} + (hc : Concentrated P Q s.C s.d 10) + +include hc in +open scoped Classical in +theorem protected_charge (hL : 0 ≤ L) : Protected s T L (frozen hs L Q) Q.freeze.border where + cover i := Q.cover i.val + square := hc.frozenSquare.trans (mul_le_mul_of_nonneg_right (by + rw [← mul_assoc]; exact mul_le_mul_of_nonneg_right s.cost_le hL) (Nat.cast_nonneg T)) + maximum i := by + refine (hc.frozenMax i).trans ?_ + gcongr + unfold Plan.A + omega + fixed := hc.frozenMax + +include hc in +open scoped Classical in +theorem hosted_bounded : (G).Bounded s.c (s.D ^ s.c) (origin s T L).load := by + have hd := s.two hs + have t := (hc.bounded hd hu (s.small.trans hs.degree)).mono s.small + (Nat.pow_le_pow_right (by omega) s.small) le_rfl + exact ⟨t.1, t.2.1, fun v i => (hosted_load hs L Q hu E v i).le.trans (t.2.2 v i)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Admitting a posted term of the concentration expansion -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Packing Assembly + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} + {A : Attachment D} {s : Plan} {z : ℕ} (hs : s.Fits) (L : ℝ) + (Q : LocalTerm F x y D.scheme.h (s.b * z)) (hu : 0 + < s.b * z) (E : Packets Q.freeze.core (s.b * z)) + {rows : A.format.obj} (q : open scoped Classical in + A.Encloses rows (hosted hs L Q hu E) Q.freeze.border) + +open scoped Classical in +/-- The incoming of type `Attachment.Data A x y (s.b * z) where T` for the given inputs. -/ +abbrev incoming : Attachment.Data A x y (s.b * z) where + T := Q.freeze.Fixed + a := Q.freeze.x + b := Q.freeze.y + L := frozen hs L Q + G := hosted hs L Q hu E + Z := Q.freeze.border + raw := rows + q := q + +variable {L Q hu E} {T R g : ℕ} {P : Rounds.Input F x y D.scheme.h s.D T R g (10000 * L)} +local notation "X" => incoming hs L Q hu E q + +open scoped Classical in +theorem incoming_ready (hc : Concentrated P Q s.C s.d 10) (hL : 1 ≤ L) (hT : 0 < T) + (hv : Nonempty Q.V) (hn : (X).Neutral) + (hspan : ∀ j, s.b * z ≤ q.core.post.toPresentation.borderWidth j) + (hi : ∀ i : Q.freeze.Fixed, ∃ n : ℕ, Q.charge i.val = n) : + Ready A (fringe s T L) z s.c (s.D ^ s.c) (origin s T L) X := by + have hz : z ≤ s.b * z := Nat.le_mul_of_pos_left z (Nat.pos_of_mul_pos_right hu) + have hr := hc.reserve hs hL hT hu + refine ⟨hn, hv, (by intro h; unfold Plan.c at h; omega), hspan, ?_, ?_, rfl, rfl, hr.1, ?_, + protected_charge hs hc (by positivity), hosted_bounded hs hu E hc, ?_, ?_⟩ + · intro i + exact hz.trans (Q.parallel (s.two hs) hu i) + · change 1 / (s.D : ℝ) ^ 4 = 1 / (s.D ^ 4 : ℕ) + rw [Nat.cast_pow] + · intro i + obtain ⟨n, he⟩ := hi i + refine ⟨n, hz.trans ?_, he⟩ + exact Nat.cast_le.mp ((Q.floor i.val).trans_eq he) + · change ((hosted hs L Q hu E).X : ℝ) ≤ _ + rw [hosted_width] + exact hr.2 + · change (↑(∑ _ : Q.V × Cell D.scheme.h, (0 : ℕ)) : ℝ) ≤ 0 + rw [Finset.sum_const_zero, Nat.cast_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Running the core contractions at the scale of a complete round -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly + +variable {F k : Type} [Field F] [Field k] {x y : Wire} {D : Template F} + +/-- The output carries the same exterior records and frozen-charge bounds. -/ +structure Result (A : Attachment D) (s : Plan) (T : ℕ) (L : ℝ) (z payload : ℕ) + (p : Prices F) (r H : ℕ) where + /-- The successor of each choice of type `Template F`. -/ + next : Template F + /-- The `Result` component of type `Attachment next`. -/ + pack : Attachment next + growth : Growth A pack r z payload s.n s.K H + /-- The `Result` component of type `Finset (Table F)`. -/ + keys : Finset (Table F) + few : keys.card ≤ (short A r z payload) ^ H + transfer : Transforms F ((short A r z payload) ^ H) keys (initial (x := x) (y + := y) A s T L z payload) + (final pack s T L z payload) (size (x := x) (y := y) A p r z payload H) + +private def ceiling (s : Plan) := s.M + s.D ^ 4 + 2 ^ discount s + +theorem reduce {s : Plan} (hs : s.Fits) + (q : Block k s.c 3 s.b s.n s.e s.K s.ρ s.loss) (d : ℕ) : + ∃ H, 0 < H ∧ ∀ (F : Type) [Field F] [Fintype F] [Algebra k F] + {x y : Wire} {D : Template F} (A : Attachment D) (T : ℕ) (L : ℝ) + (z payload : ℕ) (p : Prices F) (r : ℕ), + 1 ≤ L → 0 < z → (s.b * z) * s.D ^ s.c ≤ T → T ≤ z * s.M → s.n * r ≤ D.scheme.h → s.K ≤ 2 ^ r → + (s.K : ℝ) * T * (2 ^ (D.scheme.m + D.scheme.h) : ℕ) ≤ L * (2 : ℝ) ^ r → + D.scheme.d ≤ d → D.full = true → D.scheme.k = 0 → + Nat.clog 2 (Nat.card F) ≤ 2 ^ r → 4 * D.scheme.h ≤ D.scheme.m → + (short A r z payload) ^ H ≤ D.scheme.m → 2 * (D.scheme.m + s.n * r + s.K) ≤ p.w → + Nonempty (Result (x := x) (y := y) A s T L z payload p r H) := by + have hd : (1 : ℝ) ≤ s.D := by exact_mod_cast (show 1 ≤ s.D by have := s.two hs; omega) + have hd₀ : (0 : ℝ) < s.D := zero_lt_one.trans_le hd + have hdeg := Nat.le_self_pow (show s.c ≠ 0 by unfold Plan.c; omega) s.D + obtain ⟨H, hH, run⟩ := q.run (s.D ^ s.c) d (ceiling s) (hs.degree.trans hdeg) + refine ⟨H, hH, ?_⟩ + intro F _ _ _ x y D A T L z payload p r hL hz hunit hunit' hlen hroom slack hc hf hk hal hfour + hsmall hspace + let X : BorderLimit F x y := fringe s T L + let P := origin s T L + have hu : (s.b * z : ℕ) ≤ P.load := (le_div_iff₀ hd₀).mpr (by + exact_mod_cast (Nat.mul_le_mul_left (s.b * z) hdeg).trans hunit) + have hmax : P.load ≤ ceiling s * (z : ℝ) := calc + _ ≤ (T : ℝ) := div_le_self (by positivity) hd + _ ≤ (z : ℝ) * s.M := by exact_mod_cast hunit' + _ ≤ _ := by + rw [mul_comm] + have hceiling : s.M ≤ ceiling s := by + unfold ceiling + have := Nat.zero_le (2 ^ discount s) + omega + exact mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hceiling) (by positivity) + have ht : 0 ≤ X.total := by unfold X fringe; positivity + have hw : 0 ≤ P.width := by unfold P origin; positivity + have hσ : 0 ≤ L / s.D := by positivity + have hK : (1 : ℝ) ≤ s.K := by exact_mod_cast q.overhead + have hres : P.mass + 2 * s.K * (P.width + (X.total + L / s.D)) ≤ X.cap := by + simpa only [P, origin, zero_add, X, fringe] using le_reserve hs hL + have hhist : P.mass + 2 * P.width ≤ X.cap := by + refine le_trans ?_ hres + nlinarith only [mul_nonneg (sub_nonneg.mpr hK) hw, + mul_nonneg (Nat.cast_nonneg (α := ℝ) s.K) (add_nonneg ht hσ)] + have hsl : (s.K : ℝ) * P.load * (2 ^ (D.scheme.m + D.scheme.h) : ℕ) ≤ L / s.D * (2 : ℝ) ^ r := by + change (s.K : ℝ) * (T / (s.D : ℝ)) * _ ≤ _ + rw [← mul_div_assoc, div_mul_eq_mul_div, div_mul_eq_mul_div] + exact div_le_div_of_nonneg_right slack hd₀.le + have pre : Start A X P p r s.b (s.b * z) z z payload d (ceiling s) s.n s.K H (L / s.D) := + ⟨⟨rfl, hz, le_rfl, hu, hmax, (by change 0 < s.D ^ 4; have := s.two hs; positivity), + (Nat.le_add_left ..).trans (Nat.le_add_right ..), Nat.le_add_left .., ht, + (Nat.le_mul_of_pos_left _ q.steps).trans hlen, hroom, hc, hf, hk, hH, hal, hfour, + hsmall, (by omega), hw, le_rfl, hhist, hsl⟩, hσ, hlen, hspace, hres⟩ + obtain ⟨v⟩ := run F A X P p r (s.b * z) z z payload _ pre + refine ⟨⟨v.next, v.pack, v.growth, v.keys, v.few, + relax_frame v.transfer le_rfl (pow_mul ..).ge ?_ ?_ hres⟩⟩ + · change (s.K : ℝ) * (T / (s.D : ℝ)) ≤ T + rw [← mul_div_assoc, div_le_iff₀ hd₀, mul_comm (T : ℝ)] + exact mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hs.overhead) (by positivity) + · have hh : L / (s.D : ℝ) ≤ L / Real.sqrt s.D := + div_le_div_of_nonneg_left (by positivity) (by positivity) (Real.sqrt_le_self_iff.mpr (.inr + hd)) + calc + _ ≤ s.ρ * P.width + s.loss * (X.total + L / Real.sqrt s.D) := + add_le_add le_rfl (mul_le_mul_of_nonneg_left (add_le_add le_rfl hh) q.loss) + _ = _ := by dsimp only [P, origin, X, fringe, destination]; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- +# The cost of a transfer using wide tagged permutation + +Pad the control width past the sorting threshold. The bound on +the number of contacts pays for the dyadic payload transfer as well. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Prices +open Assembly Coloring + +variable {F : Type} [Field F] (W : Prices F) + +/-- The bound obtained by adding the component charges `let q := max k k' 500000 * ((102 + q) ^ +8 + W.W) * (q + 1) ^ 2 * (1 + (V + V') + 2 ^ p * (2 ^ m + 2 ^ m') * (W.w ^ W.power + W.w + +1))`. -/ +def transferCost (m V k m' V' k' p : ℕ) := + let q := max k k' + 500000 * ((102 + q) ^ 8 + W.W) * (q + 1) ^ 2 * (1 + (V + V') + 2 ^ p * (2 ^ m + + 2 ^ m') * (W.w ^ W.power + W.w + 1)) + +/-- The construction uses `(Payload.Script.item l p n).width + W.w ^ W.power` for its +intermediate `v`. -/ +def shipment (size m V k m' V' k' p l n : ℕ) := + let v := (Payload.Script.item l p n).width + W.w ^ W.power + 4 * size + (Payload.Script.cost m k m' k' p l v (W.W * (2 ^ m * v)) (W.W * (2 ^ m' * v)) + + Payload.Script.commandCost m V k m' V' k' (2 ^ p) p l n) + + W.transferCost m V k m' V' k' p + +variable {I : Type*} {X Y : Format} {x : I → X.obj} {y : I → Y.obj} {weight : I → F} + {u s : ℕ} {L : Set (Table F)} {m V k m' V' k' p l n : ℕ} +local notation "Ch" => PeerLayout.S m V k m' V' k' (2 ^ p) +local notation "Cmd" => Payload.Script m m' p l n + +private theorem kernel (hu : 3 ≤ u) (ht : 2 ^ p * ((max k k' + 1) * (2 ^ m + 2 ^ m')) < 2 ^ W.w) : + Kernel F u L ((Ch).control.pair (Fmt.payload m V k)) (Fmt.payload m' V' k') + ((Ch).kernel F) (W.transferCost m V k m' V' k' p) := by + have h := payload_kernel (K := F) (L := L) m V k m' V' k' (2 ^ p) hu ht W.tag + simp only [payloadChannels] at h + unfold PeerLayout.S PeerLayout.P transferCost + exact h + +theorem ship {cmd : I → (Cmd).obj} {f : I → (Fmt.payload m V k).obj} {g : I → (Fmt.payload m' V' + k').obj} + (hu : 3 ≤ u) (hm : 1 ≤ m) (hm' : 1 ≤ m') (ht : 2 ^ p * ((max k k' + 1) * (2 ^ m + 2 ^ m')) + < 2 ^ W.w) + (h : Computes F u L X (.pair Y Cmd) x (fun i => (y i, cmd i)) weight s) + (ok : ∀ i b, (Ch).Carries (Payload.Script.decode le_rfl (cmd i)) (f i) b ↔ g i = b) : + Computes F u L (.pair X (Fmt.payload m V k)) (.pair Y (Fmt.payload m' V' k')) + (fun i => (x i, f i)) (fun i => (y i, g i)) weight (s + + W.shipment Y.width m V k m' V' k' p l n) := by + let v := (Payload.Script.item l p n).width + W.w ^ W.power + have width : 2 ^ m + 2 ^ m' < 2 ^ W.w := + ((Nat.le_mul_of_pos_left _ (Nat.succ_pos _)).trans (Nat.le_mul_of_pos_left _ (by + positivity))).trans_lt ht + have a : m ≤ W.w := ((Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp + ((Nat.le_add_right _ _).trans_lt width)).le + have b : m' ≤ W.w := ((Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp + ((Nat.le_add_left _ _).trans_lt width)).le + obtain ⟨q, hq, h₁⟩ := W.tag m v hm a (Nat.le_add_left ..) + obtain ⟨r, hr, h₂⟩ := W.tag m' v hm' b (Nat.le_add_left ..) + have hh := h.shipped ok hu h₁ h₂ (Nat.le_add_right _ _) (W.kernel hu ht) + refine hh.mono ?_ + have he : Payload.Script.cost m k m' k' p l v q r ≤ + Payload.Script.cost m k m' k' p l v (W.W * (2 ^ m * v)) (W.W * (2 ^ m' * v)) := by + unfold Payload.Script.cost + gcongr + rw [add_assoc s] + exact Nat.add_le_add_left (Nat.add_le_add_right + (Nat.add_le_add_left (Nat.add_le_add_right he _) _) _) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Prices +end + +/- # Compacting the frozen selectors after either elementary phase -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Packing Assembly +variable {F : Type} [Field F] {T Y : Template F} {A : Attachment T} {x y : Wire} + {L : BorderLimit F x y} {k N u z payload Δ C : ℕ} {P : Bound} + +theorem Ready.shrink {s : (A.transport Y k).Data x y u} + (h : Ready (A.transport Y k) L z Δ C P s) (hs : A.Sparse Y k N s.raw) : + Ready (A.shrink Y k N) L z Δ C P (s.shrink hs) where + neutral := h.neutral + live := h.live + simple := h.simple + span := by + change ∀ j, u ≤ (s.q.shrink hs).core.post.toPresentation.borderWidth j + rw [s.q.shrink_core hs] + exact h.span + parallel := h.parallel + scale := h.scale + discount := h.discount + cap := h.cap + total := h.total + charge := h.charge + test := h.test + bounded := h.bounded + width := h.width + mass := h.mass + +/-- The indexed operation `(A.transport Y k).frame x y u payload (fun s => Ready (A.transport Y +k) L z Δ C P s ∧ A.Sparse Y k N s.raw)`. -/ +abbrev interim (A : Attachment T) (Y : Template F) (k N : ℕ) (L : BorderLimit F x y) + (u z payload Δ C : ℕ) (P : Bound) := + (A.transport Y k).frame x y u payload + (fun s => Ready (A.transport Y k) L z Δ C P s ∧ A.Sparse Y k N s.raw) + +theorem shrink {n : ℕ} {W : Set (Table F)} (hu : 3 ≤ n) + (fit : A.shrinkWidth Y k N ≤ n) (allow : A.shrinkGate Y k N ∈ W) : + Transforms F n W (interim A Y k N L u z payload Δ C P) + (frame (A.shrink Y k N) L u z payload Δ C P) (A.shrinkCost Y k N x y payload) := + Attachment.shrink_frames hu fit allow (fun _ h => h.2) (fun _ h => h.1.shrink h.2) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # The available reserves and address space at the intermediate boundary -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly Block +variable {F : Type} [Field F] {x y : Wire} {T Y : Template F} + {A : Attachment T} {A' : Attachment Y} {L : BorderLimit F x y} + {r b b' u v z payload d B n n' K J H G H' : ℕ} + {ρ c σ : ℝ} {P : Bound} {p : Prices F} + +variable (h : Start A L P p r (b * b') u v z payload d B (n + n') (fee K ρ c * J) G σ) + +include h + +theorem Start.first (hb : 0 < b') (hj : 0 < J) (hh : 0 < H) (hH : H ≤ G) : + Start A L P p r b u (b' * v) z payload d B n K H σ := by + have hk := (Nat.le_add_right K J).trans (add_fee (ρ := ρ) (c := c) hj) + have f := h.shrink hk hh hH + have hn := Nat.mul_le_mul_right r (Nat.le_add_right n n') + exact { f with + units := by rw [h.units, mul_assoc] + vpos := h.vpos.trans (Nat.le_mul_of_pos_left _ hb) + height := hn.trans f.height + space := by have := f.space; omega } + +theorem Start.second (hb : 0 < b) (hn : 0 < n') (hk : 0 < K) (hj : 0 < J) + (hr : 0 ≤ ρ) (hc : 0 ≤ c) (hh : 0 < H') (g : Growth A A' r z payload n K H) + (hs : (short A' r z payload) ^ H' ≤ (short A r z payload) ^ G) : + Start A' L (limit L P K ρ c σ) p r b' (b' * v) v z payload H (K * B) n' J H' σ := by + let Q := limit L P K ρ c σ + have hfee := add_fee (K := K) (ρ := ρ) (c := c) hj + have hw := h.width + have ht := add_nonneg h.total h.nonneg + have hl := (Nat.cast_nonneg u).trans h.load + have hw' : 0 ≤ Q.width := add_nonneg (mul_nonneg hr hw) (mul_nonneg hc ht) + have hm' : 0 ≤ Q.mass := by + have := h.mass + unfold Q limit + positivity + have hn' : n' * r ≤ Y.scheme.h := by + have := g.height + have ht := h.height + rw [add_mul] at ht + omega + have hspace : 2 * (Y.scheme.m + n' * r + J) ≤ p.w := by + have := g.upper + have ht := h.space + rw [add_mul] at ht + omega + have hreserve : Q.mass + 2 * J * (Q.width + (L.total + σ)) ≤ L.cap := + (chain_mass (τ := 0) (b := 0) hj hw ht hr hc).trans h.reserve + have hKK : (1 : ℝ) ≤ K := by exact_mod_cast hk + have hJJ : (1 : ℝ) ≤ J := by exact_mod_cast hj + refine ⟨⟨rfl, h.zpos, h.vpos, ?_, ?_, h.denom, h.scale.trans (Nat.le_mul_of_pos_left _ hk), + h.discount.trans (Nat.le_mul_of_pos_left _ hk), h.total, + (Nat.le_mul_of_pos_left _ hn).trans hn', + (Nat.le_add_left J K).trans (hfee.trans h.room), g.degree, g.full, g.single, hh, h.alphabet, + (by have := h.four; have := g.height; have := g.lower; omega), hs.trans (h.small.trans g.lower), + (by omega), hw', hm', ?_, (chain_seats g hl).trans h.slack⟩, h.nonneg, hn', hspace, hreserve⟩ + · have hv : b' * v ≤ u := by rw [h.units, mul_assoc]; exact Nat.le_mul_of_pos_left _ hb + exact ((Nat.cast_le.mpr hv).trans h.load).trans (le_mul_of_one_le_left hl hKK) + · change K * P.load ≤ (K * B : ℕ) * (z : ℝ) + rw [Nat.cast_mul, mul_assoc] + exact mul_le_mul_of_nonneg_left h.ceiling (Nat.cast_nonneg _) + · change Q.mass + 2 * Q.width ≤ L.cap + refine le_trans ?_ hreserve + nlinarith only [mul_nonneg (sub_nonneg.mpr hJJ) hw', mul_nonneg (Nat.cast_nonneg (α := ℝ) J) ht] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- +# Composing contractions with frozen vertices + +Form the union of the two finite sets of labels. Since both +transformations use the same border and intermediate port order, +composition sums exactly over the intermediate records. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Assembly + +variable {F k : Type} [Field F] [Field k] {x y : Wire} {T : Template F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r u v w z payload Δ Δ' Δ'' C C' C'' b b' n n' e e' K J H H' : ℕ} {ρ c τ a σ : ℝ} + +open scoped Classical in +private theorem Stop.chain (s : Stop A L P p r u v z payload Δ Δ' C C' n K H ρ c σ) + (t : Stop s.pack L (limit L P K ρ c σ) p r v w z payload Δ' Δ'' C' C'' n' J H' τ a σ) + (hj : 0 < J) (hl : 0 ≤ P.load) (hw : 0 ≤ P.width) (ht : 0 ≤ L.total + σ) + (hr : 0 ≤ ρ) (hc : 0 ≤ c) : + Nonempty (Stop A L P p r u w z payload Δ Δ'' C C'' (n + n') (Block.fee K ρ c * J) + (Growth.join n K H H') (τ * ρ) (τ * c + a) σ) := by + let U := s.keys ∪ t.keys + let h := s.growth.keys H' + have h₁ := (Nat.le_add_right ..).trans h + have h₂ := (Nat.le_add_left ..).trans h + have f := s.transfer.widen (L' := ↑U) h₁ (fun _ he => Finset.mem_union_left _ he) + have g := t.transfer.widen (L' := ↑U) h₂ (fun _ he => Finset.mem_union_right _ he) + refine ⟨⟨t.next, t.pack, (s.growth.comp t.growth).overhead (Block.add_fee hj), U, + (Finset.card_union_le ..).trans ((Nat.add_le_add s.few t.few).trans h), ?_⟩⟩ + exact relax_frame ((f.comp g).mono (s.growth.cost H' p)) le_rfl le_rfl + (Block.chain_load hl) Block.chain_width.le (Block.chain_mass hj hw ht hr hc) + +open scoped Classical in +theorem Block.comp (s : Block k Δ Δ' b n e K ρ c) (t : Block k Δ' Δ'' b' n' e' J τ a) : + Block k Δ Δ'' (b * b') (n + n') (e * e') (Block.fee K ρ c * J) (τ * ρ) (τ * c + a) := by + have hp := (Nat.add_pos_left s.overhead J).trans_le (Block.add_fee (ρ := ρ) (c := c) t.overhead) + refine ⟨Nat.mul_pos s.unit t.unit, Nat.add_pos_left s.steps _, hp, ?_, + mul_nonneg t.factor s.factor, + add_nonneg (mul_nonneg t.factor s.loss) t.loss, fun C d B hC => ?_⟩ + · intro C hC + rw [pow_mul] + exact t.degree _ (s.degree C hC) + obtain ⟨H, hH, step⟩ := s.run C d B hC + obtain ⟨H', hH', next⟩ := t.run (C ^ e) H (K * B) (s.degree C hC) + have hs := (Nat.le_add_right H H').trans (Growth.add_le n K H H') + refine ⟨Growth.join n K H H', hH.trans_le hs, ?_⟩ + intro F _ _ _ x y T A L P p r u v z payload σ h + obtain ⟨f⟩ := step F A L P p r u (b' * v) z payload σ (h.first t.unit t.overhead hH hs) + have h' := h.second s.unit t.steps s.overhead t.overhead s.factor s.loss hH' f.growth + ((Nat.le_add_left ..).trans (f.growth.keys H')) + obtain ⟨g⟩ := next F f.pack L _ p r (b' * v) v z payload σ h' + rw [pow_mul] + exact f.chain g t.overhead ((Nat.cast_nonneg u).trans h.load) h.width + (add_nonneg h.total h.nonneg) s.factor s.loss + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end + +/- # Repeated contraction and degree reset on an attached core -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Packing + +variable {k : Type} [Field k] + +private theorem subrounds (sub : SubroundRule k) (P : Gadget k) (Δ : ℕ) (hΔ : 3 ≤ Δ) + (t : ℕ) (ht : 0 < t) : + ∃ K c, Block k Δ (Δ ^ (degreePower ^ t)) (P.b ^ t) t (degreePower ^ t) K (P.ratio ^ t) c := by + have step (D : ℕ) (hd : 3 ≤ D) : + ∃ K, Block k D (D ^ degreePower) P.b 1 degreePower K P.ratio 1 := by + obtain ⟨K, hK, p⟩ := sub P D hd + exact ⟨K, p.block P.pos hK (fun _ h => Nat.pow_le_pow_left h _) P.ratio_bounds.1 zero_le_one⟩ + have : 0 < degreePower := by decide + induction t, ht using Nat.le_induction with + | base => + obtain ⟨K, p⟩ := step Δ hΔ + exact ⟨K, 1, by simpa only [pow_one] using p⟩ + | succ t _ ih => + obtain ⟨K, c, p⟩ := ih + obtain ⟨K', q⟩ := step (Δ ^ (degreePower ^ t)) (hΔ.trans (Nat.le_self_pow (by positivity) _)) + have h := p.comp q + rw [← pow_mul Δ (degreePower ^ t) degreePower, ← pow_succ degreePower, + ← pow_succ P.b, ← pow_succ' P.ratio] at h + exact ⟨_, _, h⟩ + +private theorem beat (sub : SubroundRule k) (reset : ResetRule k) (tag : Radix.WideTag k) + (Δ : ℕ) (hΔ : 3 ≤ Δ) : + ∃ b n e K c, 0 < e ∧ Block k Δ 3 b n e K (1 / 2) c := by + obtain ⟨P⟩ := gadget_exists k + obtain ⟨t, y, w, R, c, ht, hw, hc, hsize, en, hdecay⟩ := + choose_rotor (.inl tag) Δ degreePower P.ratio 250 P.ratio_bounds.1 P.ratio_bounds.2 (by + norm_num) + obtain ⟨K, a, p⟩ := subrounds sub P Δ hΔ t ht + have : 0 < degreePower := by decide + let D := Δ ^ (degreePower ^ t) + have hd : 3 ≤ D := hΔ.trans (Nat.le_self_pow (by positivity) _) + have enough : 4 * coreBins D ≤ 2 ^ y := by + simpa only [coreBins, mul_assoc] using en D le_rfl + obtain ⟨K', hK', q⟩ := reset y w D R c hw hd enough hc + ((le_add_of_nonneg_left (Nat.cast_nonneg _)).trans hsize) + have hp : 0 ≤ 2 * resetWidth c w := by unfold resetWidth; positivity + have q' := q.block (by decide) hK' + (fun C hC => (hd.trans hC).trans (Nat.le_self_pow (by positivity) C)) hp hp + have bound : 2 * resetWidth c w ≤ 250 * (1 + c + Nat.clog 2 w) := by + unfold resetWidth + linarith [Nat.cast_nonneg (α := ℝ) (Nat.clog 2 w)] + have decrease := (mul_le_mul_of_nonneg_right bound (pow_nonneg P.ratio_bounds.1 t)).trans hdecay + exact ⟨_, _, _, _, _, by positivity, (p.comp q').relax le_rfl decrease le_rfl⟩ + +/-- Prepending the same block keeps its composition fee fixed. The loss +after each repetition is bounded by a geometric sum. -/ +theorem Block.iterate {Δ b n e K : ℕ} {c : ℝ} (p : Block k Δ 3 b n e K (1 / 2) c) + (hΔ : 3 ≤ Δ) (he : 0 < e) (t : ℕ) (ht : 0 < t) : + Block k Δ 3 (b ^ t) (n * t) (e ^ t) ((fee K (1 / 2) c) ^ t) ((1 / 2) ^ t) (2 * c) := by + let H := Block.fee K (1 / 2) c + have w := p.degree_mono hΔ (fun D hd => hd.trans (Nat.le_self_pow he.ne' D)) + have hk : K ≤ H := by unfold H Block.fee; omega + have hit (t : ℕ) (ht : 0 < t) : + Block k Δ 3 (b ^ t) (n * t) (e ^ t) (H ^ t) ((1 / 2) ^ t) (2 * c * (1 - (1 / 2) ^ t)) := by + induction t, ht using Nat.le_induction with + | base => + simp only [Nat.succ_eq_add_one, Nat.zero_add, pow_one, mul_one, half_loss_one] + exact p.relax hk le_rfl le_rfl + | succ t _ ih => + have h := w.comp ih + rw [show Block.fee K (1 / 2) c = H from rfl, + ← pow_succ' b, ← pow_succ' e, ← pow_succ' H, ← pow_succ (1 / 2 : ℝ), + show n + n * t = n * (t + 1) by rw [Nat.mul_succ, add_comm], + half_loss_succ] at h + exact h + refine (hit t ht).relax le_rfl le_rfl ?_ + exact half_loss_le p.loss t + +/-- For any positive number of repetitions the core degree returns to three +and the width factor halves at each repetition, with uniformly bounded loss. -/ +theorem beats (sub : SubroundRule k) (reset : ResetRule k) (tag : Radix.WideTag k) + (Δ : ℕ) (hΔ : 3 ≤ Δ) : + ∃ (b n e H : ℕ) (C : ℝ), 0 < n ∧ 0 < e ∧ ∀ t : ℕ, 0 < t → + Block k Δ 3 (b ^ t) (n * t) (e ^ t) (H ^ t) ((1 / 2) ^ t) C := by + obtain ⟨b, n, e, K, c, he, p⟩ := beat sub reset tag Δ hΔ + exact ⟨b, n, e, Block.fee K (1 / 2) c, 2 * c, p.steps, he, p.iterate hΔ he⟩ + +/-- Fix the degree scale and repetition count together so that restoring +the core fits the next round's budgets. -/ +theorem plan (sub : SubroundRule k) (reset : ResetRule k) (tag : Radix.WideTag k) + {δ : ℝ} (hδ : 0 < δ) (hd : δ ≤ 1) (C d₀ : ℕ) : + ∃ s : Plan, s.C = C ∧ d₀ ≤ s.d ∧ s.Fits ∧ 0 < s.v ∧ 0 < s.p ∧ + (s.p : ℝ) ≤ s.v * (1 + δ / 3) ∧ Block k s.c 3 s.b s.n s.e s.K s.ρ s.loss := by + obtain ⟨b, n, e, H, B, _, _, run⟩ := beats sub reset tag (C + 12) (by omega) + obtain ⟨d, v, p, hlarge, hv, hp, hvp, hb, hK, hm, hq, ha⟩ := + choose_restart (C + 12) e b H (d₀ + C + 12) (↑(10000 * (C + 1) : ℕ)) B δ + (by positivity) (run 1 (by decide)).loss hδ hd + let s : Plan := ⟨C, d, v, p, b ^ (2 * v), n * (2 * v), e ^ (2 * v), H ^ (2 * v), B⟩ + have grow : d < s.D := Nat.lt_two_pow_self + have fits : s.Fits := ⟨(show C + 12 ≤ s.D by omega), hK, hb, hm, hq, ha⟩ + exact ⟨s, rfl, show d₀ ≤ d by omega, fits, hv, hp, hvp, run (2 * v) (by omega)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Subround.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Subround.lean new file mode 100644 index 0000000000..c1393d716c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Contraction/Subround.lean @@ -0,0 +1,927 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Beat.TemplateCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Beat.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Beat.Fanout +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Carry + +/-! # Local controller widths with the full border retained -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Assembly History Packing Case Coloring Window +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) +local notation "I" => Case κ Q.b d B +local notation "E" => e Δ B + +theorem seat_factor : Short (fun i : I => 2 ^ (i.n + i.T.scheme.e)) := + tiles.short.exp_add spans.short + +theorem radius_factor : Short (fun i : I => 2 ^ (Tile.radius i.T.scheme.d)) := + (short_const (2 ^ (Tile.radius d))).mono fun i => + Tile.exp_radius_mono i.h.degree + +theorem mask_factor : Short (fun i : I => 2 ^ (Tile.radius i.T.scheme.d + (i.n + 1))) := + (radius_factor Q d B).exp_add (child_factor Q d B).short + +theorem outgoing : Short (fun i : I => (Window.Outgoing i.T.scheme).width) := + Width.vec spans.short (Width.pair Width.bit + (Width.pair (Width.addr Case.slots.short.of_exp) (Width.addr spans.short.of_exp))) + +theorem source_bound : Short (fun i : I => (i.T.Source i.a (b Q)).width) := by + have hn : Short (fun i : I => 2 ^ i.n) := tiles.short + have hw := Width.addr (child_factor Q d B).short.of_exp + have occ := Width.pair hw (outgoing Q d B) + have mat := Width.pair (Width.vec hn Width.bit) + (Width.pair (Width.vec hn occ) (Width.vec hn (Width.vec Case.slots.short hw))) + exact Width.pair (Width.vec hn (Width.addr Case.bits)) + (Width.pair (Width.vec (seat_factor Q d B) (Width.addr (short_const (b Q)))) mat) + +theorem count_bound : Short (fun i : I => (i.T.WithCount i.a (b Q)).width) := + Width.pair (source_bound Q d B) (Width.vec tiles.short (Width.addr counters)) + +theorem pollRow_bound : Short (fun i : I => (i.T.PollRow i.a (b Q)).width) := + Width.pair Width.bit (source_bound Q d B) + +theorem side_bound : Short (fun i : I => (Side.Input (i.n + i.T.scheme.e) (b Q)).width) := + Width.vec (seat_factor Q d B) (short_const (Side.Entry (b Q)).width) + +theorem supplement_bound : Short (fun i : I => (i.A.Supplement i.a E).width) := by + have a : Short (fun i : I => i.T.scheme.k) := (short_const 0).mono fun i => (i.h.single).le + have p := Width.pair Width.bit (Width.pair (Width.addr (hop_factor Q d B).short.of_exp) + (Width.pair (Width.addr levels.short) (Width.pair (Width.addr a) (Width.addr + spans.short.of_exp)))) + have f : Short (fun i : I => i.A.pointer.width) := + Width.pair Width.bit (Width.pair (Width.addr levels.short) (Width.addr stations.short.of_exp)) + exact Width.pair (Width.vec (short_const (2 ^ 0)) (Width.vec (short_const (2 ^ E)) p)) + (Width.vec (place_factor Q d B).short f) + +/-- The value specified by `i.T.Label i.a Δ C (menu Q d B i) E (cap (Q.extend i.F) i.A i.v +i.positive i.z Δ B) (meter i.L i.z Δ B) (i.A.Supplement i.a E)`. -/ +abbrev label (i : I) := i.T.Label i.a Δ C (menu Q d B i) E + (cap (Q.extend i.F) i.A i.v i.positive i.z Δ B) (meter i.L i.z Δ B) (i.A.Supplement i.a E) + +theorem label_bound : Short (fun i : I => (label Q Δ C d B i).width) := + Width.pair (Width.addr (child_bound Q Δ C d B).bits) + (Width.pair (Width.addr (meter_bound Q Δ d B).short) (supplement_bound Q Δ d B)) + +theorem mask_bound : Short (fun i : I => (Tile.mask i.T.scheme.d i.n (i.T.degree i.a Δ C)).width) := + Width.vec (mask_factor Q d B) (Width.vec (child_slots Q Δ C d B).short (Width.vec (mask_factor Q + d B) Width.bit)) + +theorem walk_bound : Short (fun i : I => (Walks 8 i.T.scheme.d (i.T.WithCount i.a (b Q))).width) := + Width.vec (radius_factor Q d B) (count_bound Q d B) + +theorem word_bound : Short (fun i : I => (Tile.word i.T.scheme.d i.a i.n + (i.T.degree i.a Δ C) (i.T.WithCount i.a (b Q))).width) := + Width.pair Width.bit (Width.pair Width.bit (Width.pair (Width.addr groups.short) + (Width.pair (Width.addr (child_factor Q d B).short.of_exp) + (Width.pair (mask_bound Q Δ C d B) (walk_bound Q d B))))) + +theorem path_factor : Short (fun i : I => 2 ^ ((i.T.scheme.d + 1) * i.n)) := by + refine (tiles.short.pow (d + 1)).mono fun i => ?_ + rw [← pow_mul, mul_comm i.n] + exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ (Nat.succ_le_succ i.h.degree)) + +theorem tableWidth_bound : Short (fun i : I => i.T.tableWidth) := Case.bits.add (outgoing Q d B) + +theorem patch_bound : Short (fun i : I => (Group.Patch ((i.T.scheme.d + + 1) * i.n) i.n i.T.count).width) := by + have hp := path_factor Q d B + refine ((short_const 1).add (hp.mul ((hp.mul (short_const 2)).add (tiles.short.mul + counters)))).mono fun i => ?_ + rw [Group.width_patch] + +theorem groupLabels_bound : Short (fun i : I => (Group.Labels i.n).width) := + Width.vec tiles.short (Width.addr (child_factor Q d B).short.of_exp) + +theorem groupArity_bound : Short (fun i : I => Group.arity ((i.T.scheme.d + + 1) * i.n) i.n i.T.count) := by + have hn : Short (fun i : I => 2 ^ i.n) := tiles.short + have hs : Short (fun i : I => (Group.Summary i.n).width) := + (hn.mul (hn.of_exp.add (hn.mul (child_factor Q d B).short.of_exp))).mono fun i + => by rw [Group.width_summary] + exact (((patch_bound Q d B).add hs).add hn.of_exp).add (groupLabels_bound Q d B) + +theorem colors_bound : Short (fun i : I => (i.T.Colors i.a).width) + := Width.vec tiles.short Width.bit + +theorem vote_bound : Short (fun i : I => (i.T.Vote i.a).width) := + Width.vec (child_factor Q d B).short (Width.addr ((seat_factor Q d B).of_exp.add (short_const 1))) + +theorem arity_bound : Short (fun i : I => arity (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B + i.r) := by + have h := child_bound Q Δ C d B + have g := (((tableWidth_bound Q d B).add (groupArity_bound Q d B)).add + ((child_factor Q d B).short.of_exp.add (colors_bound Q d B))).add ((pollRow_bound Q d B).add + (vote_bound Q d B)) + have mark := (pollRow_bound Q d B).add (side_bound Q d B) + have issue := (word_bound Q Δ C d B).add (label_bound Q Δ C d B) + have back := (fresh_bound Q Δ C d B).rebuildWidth (place_factor Q d B).short (hop_factor Q d + B).short + exact ((((g.add mark).add issue).add ((short_const 2).mul h.bits)).add back) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Controller arrays indexed by parent groups and expanded hosts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Assembly Packing Case Coloring Window +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) +local notation "I" => Case κ Q.b d B + +theorem original : Cost (fun i : I => i.T.format.width) := Case.Child.parent.format +theorem attached : Cost (fun i : I => i.A.format.width) := Case.Child.parent.attached Case.labels + +theorem expanded {f : I → ℕ} (h : Row f) : Cost (fun i : I => 2 ^ (i.T.size i.a) * f i) := + h.expand (child_factor Q d B).short.block + +theorem grouped {A : I → Format} (h : Short (fun i => (A i).width)) : + Cost (fun i : I => (Fmt.groups i.m i.T.scheme.d i.a (A i)).width) := + Case.Child.parent.bank (h.block.groups.mono (fun _ => (Format.width_vec ..).le)) + +theorem counted_bound : Cost (fun i : I => (i.T.Counted i.a (b Q)).width) + := grouped Q d B (count_bound Q d B) + +theorem poll_bound : Cost (fun i : I => (i.T.Poll i.a (b Q)).width) := + Width.pack (original Q d B) (grouped Q d B (source_bound Q d B)) + +theorem seats_bound : Cost (fun i : I => Fintype.card (i.T.Slots i.a)) := by + refine (seat_factor Q d B).block.groups.hosts.mono fun i => ?_ + rw [Fintype.card_congr (i.T.seatIndex i.a).symm, Fintype.card_fin, pow_add, pow_add, mul_assoc] + +theorem seats_width (Z : Format) : + Cost (fun i : I => (Fmt.pi (fun _ : i.T.Slots i.a => Z)).width) := by + refine ((seats_bound Q d B).mul (block_const Z.width)).mono fun i => ?_ + simp only [Fmt.width_pi, Finset.sum_const, Finset.card_univ, smul_eq_mul, le_refl] + +theorem candidate_bound : Cost (fun i : I => (i.T.Candidate i.a (b Q)).width) := + seats_width Q d B (.addr (b Q)) + +theorem groups_cost {f : I → ℕ} (hf : Short f) : Cost (fun i : I => 2 ^ (i.m + i.a) * f i) := by + simpa only [pow_add, mul_assoc] using hf.block.groups.hosts + +theorem groups_width {A : I → Format} (h : Short (fun i => (A i).width)) : + Cost (fun i : I => (Format.vec (i.m + i.a) (A i)).width) := + (groups_cost Q d B h).mono fun _ => (Format.width_vec ..).le + +theorem status_bound : Cost (fun i : I => (i.T.Status i.a).width) := + (expanded Q d B (long_const Format.bit.width).row).mono fun _ => (Format.width_vec ..).le + +theorem graph_bound : Cost (fun i : I => (i.T.Graph i.a Δ C).width) := by + have h := child_bound Q Δ C d B + exact h.vector (Width.many h.neighbors (Long.row (Width.addr h.address))) + +theorem header_bound : Cost (fun i : I => (i.T.ChildHeader i.a Δ C).width) := by + have h := child_bound Q Δ C d B + have s : Short (fun _ : I => (Format.bit.pair .bit).width) := short_const _ + exact h.vector (Short.long (Width.pair s (Width.vec h.neighbors s))).row + +theorem raw_bound : Cost (fun i : I => (i.T.Raw i.a (b Q) Δ C).width) := + Width.pack (status_bound Q d B) (Width.pack (long_const Format.bit.width).row.cost + (Width.pack (graph_bound Q Δ C d B) (counted_bound Q d B))) + +theorem headed_bound : Cost (fun i : I => (i.T.Headed i.a (b Q) Δ C).width) := + Width.pack (raw_bound Q Δ C d B) (header_bound Q Δ C d B) + +theorem parcel_bound : Row (fun i : I => BatchDescent.Beat.parcel i.T i.r) := by + have flags : Short (fun i : I => (Group.Flags i.T.scheme.d).width) := + Width.vec Case.slots.short (Width.pair Width.bit Width.bit) + have count : Short (fun i : I => (Format.vec i.n (.addr i.T.count)).width) := + Width.vec tiles.short (Width.addr counters) + exact Width.pack Width.bit.long.row (Width.pack flags.long.row + (count.block.groups.mono (fun _ => (Format.width_vec ..).le))) + +theorem groupInput_bound : Cost (fun i : I => (i.T.groupInput i.a).width) := + Case.Child.parent.bank (parcel_bound Q d B) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Layout and header construction with both core and full graph masks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Assembly Packing Case Coloring + +variable {κ : Type} [Field κ] (P : Gadget κ) (Δ C d B : ℕ) +local notation "I" => Case κ P.b d B + +private theorem childInput_bound : Cost (fun i : I => (Child.Input i.m i.T.scheme.d).width) := by + have hd : Long (fun i : I => 2 ^ i.T.scheme.d) := Case.slots.short.long + refine (Mixed.long Case.m (hd.mul ((long_const 1).add hosts))).mono fun i => ?_ + simp only [Child.Input, Format.width_vec, Format.width_pair, Format.width_addr] + rw [Format.width_bit] + +private theorem nav_bound {q : I → ℕ} (h : Short (fun i => 2 ^ (q i))) : + Cost (fun i : I => i.T.navCost i.a (q i)) := by + have bits := Template.navComputation (hosts.add (child_factor P d B).short.long.of_exp) h.long + exact Template.navCost_mixed (large := Case.long) (small := Case.block) + (height := Case.height) (hosts := Case.m) (F := Case.F) + (T := fun i : I => i.T) (a := fun i => i.a) + (degree := q) (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (original P d B) (groupInput_bound P d B) (childInput_bound P d B) + (expanded P d B (Long.row bits)) + +private theorem childCost_bound : Cost (fun i : I => i.T.childCost i.a Δ C) := by + exact Template.childCost_mixed (large := Case.long) (small := Case.block) + (height := Case.height) (hosts := Case.m) (F := Case.F) + (T := fun i : I => i.T) (a := fun i => i.a) + (delta := fun _ => Δ) (C := fun _ => C) + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (original P d B) (status_bound P d B) (nav_bound P d B (child_slots P Δ C d B).short) + +private theorem headerCost_bound : Cost (fun i : I => i.T.headerCost i.a Δ C) := by + have p := (child_slots P Δ C d B).short + have q : Short (fun i : I => 2 ^ (Child.nextWidth i.n Δ i.T.scheme.d)) := by + refine (short_const (2 ^ maxDegree Δ d)).mono fun i => ?_ + refine Nat.pow_le_pow_right (by decide) ?_ + exact Nat.mul_le_mul_right 3 (Nat.add_le_add_right (Nat.add_le_add i.h.degree (min_le_right + ..)) 1) + have bits := Template.headerComputation (hosts.add (child_factor P d B).short.long.of_exp) + p.long q.long + have flags : Cost (fun i : I => (Format.vec (i.T.size i.a) + (.vec (i.T.degree i.a Δ C) .bit)).width) := by + refine (expanded P d B p.long.row).mono fun i => ?_ + rw [Format.width_vec, Format.width_vec, Format.width_bit, mul_one] + exact Template.headerCost_mixed (large := Case.long) (small := Case.block) + (height := Case.height) (hosts := Case.m) (F := Case.F) + (T := fun i : I => i.T) (a := fun i => i.a) + (delta := fun _ => Δ) (C := fun _ => C) + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (original P d B) (status_bound P d B) (nav_bound P d B p) (nav_bound P d B q) + (expanded P d B (Long.row bits)) flags (header_bound P Δ C d B) + +private theorem entries_bound : Cost (fun i : I => (i.T.Entries i.a (b P)).width) := + seats_width P d B (Side.Entry (b P)) + +private theorem markCost_bound : Cost (fun i : I => i.T.markCost i.a (b P)) := by + have p := pollRow_bound P d B + have s := side_bound P d B + exact Template.markCost_mixed (large := Case.long) (small := Case.block) + (height := Case.height) (hosts := Case.m) (F := Case.F) + (T := fun i : I => i.T) (a := fun i => i.a) + (b := fun _ => b P) + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (poll_bound P d B) (groups_width P d B p) (groups_width P d B s) + (entries_bound P d B) (groups_cost P d B (((short_const 1).add p).add s)) + +private theorem layoutCost_bound : Cost (fun i : I + => i.T.layoutCost i.a (b P) (BatchDescent.Beat.profile P)) := by + exact Template.layoutCost_mixed (large := Case.long) (small := Case.block) + (height := Case.height) (hosts := Case.m) (F := Case.F) + (T := fun i : I => i.T) (a := fun i => i.a) + (bits := b P) + (profile := BatchDescent.Beat.profile P) + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (markCost_bound P d B) (seats_bound P d B) (entries_bound P d B) + +private theorem rawCost_bound : Cost (fun i : I => + i.T.rawCost i.a (b P) Δ C (BatchDescent.Beat.profile P)) := by + have hb : Cost (fun _ : I => Format.bit.width) := (long_const _).row.cost + exact Template.rawCost_mixed (large := Case.long) (small := Case.block) + (height := Case.height) (hosts := Case.m) (F := Case.F) + (T := fun i : I => i.T) (a := fun i => i.a) + (b := fun _ => b P) + (delta := fun _ => Δ) (C := fun _ => C) (profile := BatchDescent.Beat.profile P) + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (original P d B) (poll_bound P d B) (counted_bound P d B) (status_bound P d B) + (graph_bound P Δ C d B) hb (childCost_bound P Δ C d B) + (layoutCost_bound P d B) (raw_bound P Δ C d B) + +theorem headedCost_bound : Cost (fun i : I => i.T.headedCost i.a (b P) Δ C + (BatchDescent.Beat.profile P)) := by + exact Template.headedCost_mixed (large := Case.long) (small := Case.block) + (height := Case.height) (hosts := Case.m) (F := Case.F) + (T := fun i : I => i.T) (a := fun i => i.a) + (b := fun _ => b P) (delta := fun _ => Δ) (C := fun _ => C) + (profile := BatchDescent.Beat.profile P) + (fun i => i.long_two) (fun i => i.block_two) (fun i => i.block_long) + (original P d B) (poll_bound P d B) (rawCost_bound P Δ C d B) (headerCost_bound P Δ C d B) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Cost of the common grouping and voting circuits over an extension field -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Assembly Packing Case Coloring + +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) +local notation "I" => Case κ Q.b d B + +private theorem labels_bound_row : Row (fun i : I => BatchDescent.Beat.labels i.T i.r) := + (groupLabels_bound Q d B).block.groups.mono fun _ => (Format.width_vec ..).le + +private theorem fields_bound : Cost (fun i : I => (Window.Fields i.T.scheme i.a i.n (b Q)).width) := + Width.pack Child.parent.scheme (Width.pack (Child.parent.vector (labels_bound_row Q d B)) + (Width.pack (colors_bound Q d B).long.row.cost (candidate_bound Q d B))) + +private theorem patchCost_bound : Cost (fun i : I => + let v := BatchDescent.Beat.parcel i.T i.r + Group.patchCost i.m i.T.scheme.d i.a i.n i.T.count v (i.p.fee (i.m + (i.T.scheme.d + + 1) * i.n) v)) := by + have hp := path_factor Q d B + have v := parcel_bound Q d B + have patches := groups_width Q d B (patch_bound Q d B) + have loads := Child.parent.vector (Width.many hp v) + have cost := Mixed.long Case.m (((long_const 100).add (hosts.add hp.long)).pow 220) + exact (((((groupInput_bound Q d B).add patches).add loads).add cost).scale 1000).add + (Child.parent.gather hp v) + +private theorem election_bound {c w : I → ℕ} (hc : Short (fun i => 2 ^ c i)) (hw : Short w) : + Cost (fun i : I => 2 ^ c i * (2 ^ (i.m + i.a) * (100 + w i) ^ 5 + (100 + (c i + (w i + (i.m + + i.a)))) ^ 42)) := by + have a := groups_cost Q d B (((short_const 100).add hw).pow 5) + have j : Long (fun i : I => i.m + i.a) := hosts.add Case.groups.short.long + have g := Template.electionComputation hc.long.of_exp hw.long j + exact (a.add (Long.row g).cost).left hc.block + +private theorem groupCost_bound : + Cost (fun i : I => Group.cost (i.m + i.a) ((i.T.scheme.d + 1) * i.n) i.n i.T.count) := by + have hn : Short (fun i : I => 2 ^ i.n) := tiles.short + exact Template.groupCost_mixed (dimension := fun i : I => i.m + i.a) + (query := fun i => (i.T.scheme.d + 1) * i.n) (width := fun i => i.n) + (labels := fun i => i.T.count) (fun i => i.long_two) (fun i => i.block_two) + (fun i => i.block_long) (groups_cost Q d B ((short_const 1).add (groupArity_bound Q d B))) + (election_bound Q d B hn hn.of_exp) + +private theorem light_bound : Cost (fun i : I => i.T.lightCost i.a (b Q)) := by + have hc := (colors_bound Q d B).long.row.cost + have hv := vote_bound Q d B + have hr := pollRow_bound Q d B + have hp := poll_bound Q d B + have polls := groups_width Q d B hr + have votes := groups_width Q d B hv + have ht := groups_cost Q d B (((short_const 1).add hr).add hv) + have field := (child_factor Q d B).short + have he := election_bound Q d B field ((seat_factor Q d B).of_exp.add (short_const 1)) + have cost := (((hp.add (polls.scale 2)).scale 4).add ht).add (((votes.scale 3).add he).scale 4) + have hdr := (cost.add (long_const 1).row.cost).add (Long.row field.long.of_exp).cost + exact (hdr.add hc).add ((Width.pack hp hc).scale 40) + +private theorem prepareCost_bound : Cost (fun i : I => prepareCost (Q.extend i.F) i.T i.r i.p) := by + have hr := Width.pack (original Q d B) (candidate_bound Q d B) + have hf := fields_bound Q d B + have elected := groups_width Q d B (groupLabels_bound Q d B) + have hv := Child.parent.gather Case.slots.short (labels_bound_row Q d B) + have records := (hf.add (grouped Q d B (source_bound Q d B))).scale 100 + have install : Cost (fun i : I => 2 ^ i.m * 2 ^ i.a * 2 ^ i.n * (1 + i.T.tableWidth)) := by + refine (groups_cost Q d B (tiles.short.mul ((short_const 1).add (tableWidth_bound Q d + B)))).mono fun i => ?_ + rw [pow_add, mul_assoc] + have gather := (hv.add records).add install + have setup := (((hr.add (groupInput_bound Q d B)).add elected).add hf).scale 200 + have collect := ((setup.add (patchCost_bound Q d B)).add (groupCost_bound Q d B)).add gather + exact ((hr.scale 40).add collect).add (light_bound Q d B) + +theorem firstCost_bound : Cost (fun i : I => firstCost (Q.extend i.F) i.A Δ C i.r i.p) := by + have input := Width.pack (attached Q d B) (candidate_bound Q d B) + have head := Width.pack (attached Q d B) (headed_bound Q Δ C d B) + exact (((input.add head).scale 1000).add (prepareCost_bound Q d B)).add (headedCost_bound Q Δ C d + B) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Cost of transporting and compressing all child labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Assembly Packing Case Coloring Window +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) +local notation "I" => Case κ Q.b d B +local notation "Y" => fresh Q Δ C d B + +private theorem tile_bound : Cost (fun i : I => Tile.cost i.m i.T.scheme.d i.a i.n (i.T.degree i.a + Δ C) + (i.T.WithCount i.a (b Q)) (label Q Δ C d B i)) := by + have masks := Case.Child.parent.vector (mask_bound Q Δ C d B).long.row + have body := Width.pack masks (grouped Q d B (walk_bound Q d B)) + have pre := Width.pack (status_bound Q d B) (Width.pack Width.bit.long.row.cost body) + have work := ((block_const 1).add ((block_const 137).mul (word_bound Q Δ C d B).block)).add + (label_bound Q Δ C d B).block + refine ((pre.scale 4).add (expanded Q d B (Block.groups work))).mono fun i => ?_ + rw [Tile.cost, mul_assoc] + +private theorem bank_bound : Cost (fun i : I => Tile.bankCost i.m i.T.scheme.d i.a i.n (i.T.degree + i.a Δ C) + (i.T.WithCount i.a (b Q)) (BatchDescent.Beat.walk (Q.extend i.F) i.T i.r) + (i.p.fee (i.m + i.T.scheme.d) (BatchDescent.Beat.walk (Q.extend i.F) i.T i.r)) (precision i.T Δ + C i.r)) := by + have h := child_bound Q Δ C d B + have hp : Long (fun i : I => precision i.T Δ C i.r) := + (h.address.add (mask_factor Q d B).long).add h.neighbors.long + have in₁ := Mixed.long Case.m (((long_const 100).add (hosts.add (radius_factor Q d B).long)).pow + 20) + have in₂ := h.cost (Long.row (((long_const 100).add hp).pow 40)) + have read := Case.Child.parent.read Case.slots.short (walk_bound Q d B).block.groups + exact (((raw_bound Q Δ C d B).scale 24).add ((in₁.add in₂).scale 4)).add (read.scale 9) + +private theorem issue_bound : Cost (fun i : I => + let t := BatchDescent.Beat.walk (Q.extend i.F) i.T i.r + i.T.issueCost i.a (b Q) Δ C (menu Q d B i) (e Δ B) + (cap (Q.extend i.F) i.A i.v i.positive i.z Δ B) (meter i.L i.z Δ B) (i.A.Supplement i.a (e Δ + B)) + t (i.p.fee (i.m + i.T.scheme.d) t) (precision i.T Δ C i.r)) := by + have h := child_bound Q Δ C d B + have h₀ := headed_bound Q Δ C d B + have h₁ := Width.pack (graph_bound Q Δ C d B) (header_bound Q Δ C d B) + have h₂ := raw_bound Q Δ C d B + have h₃ := h.vector (h.stack (label_bound Q Δ C d B)) + have h₄ := Width.pack h.format (h.vector (h.stack (supplement_bound Q Δ d B))) + have N := (bank_bound Q Δ C d B).add (tile_bound Q Δ C d B) + have keep := (h₀.add (h₁.scale 2)).scale 4 + have run := ((h₀.add (h₂.scale 2)).scale 4).add N + exact ((h₀.scale 20).add (keep.add run)).add (((Width.pack h₁ h₃).add (h₄.scale 2)).scale 4) + +theorem secondCost_bound : Cost (fun i : I => + secondCost (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B i.r i.p) := by + have h := child_bound Q Δ C d B + have h₄ := Width.pack h.format (h.vector (h.stack (supplement_bound Q Δ d B))) + have issue := issue_bound Q Δ C d B + have a := attached Q d B + have req := h.requests (place_factor Q d B).short (hop_factor Q d B).short + exact ((a.scale 4).add issue).add (((Width.pack a h₄).add (req.scale 2)).scale 4) + +theorem tailCost_bound : Case.Total (fun i : I => + i.A.shrinkCost (Y i) (slots i.A i.r) (copies Δ B) i.x i.y i.payload + + 208 * (Attachment.payload i.x i.y i.payload i.m).width + 4 * (i.T.Candidate i.a (b Q)).width) + := by + have h := (fresh_bound Q Δ C d B).shrinkCost (place_factor Q d B).short (copies Δ B) + exact (h.add (Case.Child.parent.payload.scale 208)).add ((candidate_bound Q d B).total.scale 4) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Supplying both the border labels and the return pointers to the exterior transfer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + (s : ∀ q : (frame A L (Q.b * v) z payload Δ C P).state, Poll h q) + (hd : 0 < Δ) (hc : Δ ≤ C) (hk : 2 ^ (k Δ) ≤ K) (hs : range (T := T) Δ C r ≤ T.scheme.m) + +local notation "Y" => raw Q A L v (pos h) z Δ C B r +local notation "N" => next Q A L v (pos h) z Δ C B r +local notation "k'" => slots A r +local notation "p'" => (T.scheme.d + 1) +local notation "R" => requests Q A L v (pos h) z Δ C B r +local notation "U" => out Q A L v (pos h) z Δ C B r +local notation "self" => BatchDescent.Trail.hop T.scheme.d none + +open scoped Classical in +/-- The value specified by `(requests Q A L v (pos h) z Δ C B r).pair (out Q A L v (pos h) z Δ C +B r).format`. -/ +abbrev wiring (Δ C : ℕ) := (requests Q A L v (pos h) z Δ C B r).pair + (out Q A L v (pos h) z Δ C B r).format + +open scoped Classical in +/-- The value specified by `((swept h s hd hc i).requests, (swept h s hd hc i).result)`. -/ +def pending (i : Path h s) : (wiring h Δ C).obj := + ((swept h s hd hc i).requests, (swept h s hd hc i).result) + +open scoped Classical in +/-- The supply cost used in the `Beat` construction. -/ +def supplyCost (Δ C : ℕ) := secondCost Q A L v (pos h) z Δ C B r p + + A.sweepCost (raw Q A L v (pos h) z Δ C B r) (slots A r) (T.scheme.d + 1) + + 24 * (requests Q A L v (pos h) z Δ C B r).width + rebuildCost Q A L v (pos h) z Δ C B r p + +include hk hs in +open scoped Classical in +theorem supply : ∃ gate : Table F, Processor.arity gate = issueWidth Q A L v (pos h) z Δ C B r ∧ + ∀ {u : ℕ} {W : Set (Table F)}, 3 ≤ u → arity Q A L v (pos h) z Δ C B r ≤ u → + gate ∈ W → BatchDescent.Snapshot.sweepTable Y ∈ W → A.rebuildGate N k' p' self ∈ W → + Computes F u W (headed Q A Δ C r) (wiring h Δ C) + (mid h s) (pending h s hd hc) (fun i => (issued h s hd hc i).sweepWeight) + (supplyCost h Δ C) := by + obtain ⟨gate, hw, hn⟩ := second h s hd hc hk hs + refine ⟨gate, hw, ?_⟩ + intro u W hu fit hg ha hrec + have start := hn hu fit hg ha + have decode := rebuild h s hd hc hk hs hu fit hrec + have keep := Computes.of_map (L := W) (x := fun i => (swept h s hd hc i).requests) + (Map.circuit hu (Circuit.id F R)) (fun _ => rfl) + have run := start.comp (keep.pair hu decode) + simp only [mul_one] at run + refine run.mono ?_ + unfold supplyCost + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Composing the selector test, reattachment, bit transport and compaction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + +local notation "a" => (T.scheme.h - r) +local notation "Y" => raw Q A L v (pos h) z Δ C B r +local notation "N" => Template.sweep Y +local notation "U" => A.transport N (slots A r) +local notation "V" => A.shrink N (slots A r) (copies Δ B) +local notation "k'" => slots A r +local notation "p'" => (T.scheme.d + 1) +local notation "D" => Attachment.payload x y payload T.scheme.m +local notation "Z" => T.Candidate a (b Q) +local notation "self" => BatchDescent.Trail.hop T.scheme.d none + +variable (Δ C) +open scoped Classical in +/-- The tables used in the `Beat` construction. -/ +def tables (gate : Table F) := + insert gate (insert (BatchDescent.Snapshot.sweepTable Y) + (insert (A.rebuildGate N k' p' self) (insert (A.shrinkGate N k' (copies Δ B)) + (insert (T.markTable a (b Q)) (T.keys a (b Q) (k Δ) P.load Δ C))))) + +open scoped Classical in +theorem few (gate : Table F) : (tables Δ C h gate).card ≤ 10 := by + unfold tables + iterate 5 + apply (Finset.card_insert_le _ _).trans + apply Nat.add_le_add_right + exact T.card_keys .. + +open scoped Classical in +/-- The bound obtained by adding the component charges `firstCost Q A Δ C r p + supplyCost h Δ C ++ (A.shrinkCost N k' (copies Δ B) x y payload + 208 * (D).width + 4 * (Z).width)`. -/ +def runCost := firstCost Q A Δ C r p + supplyCost h Δ C + + (A.shrinkCost N k' (copies Δ B) x y payload + 208 * (D).width + 4 * (Z).width) + +variable {Δ C} (s : ∀ q : (frame A L (Q.b * v) z payload Δ C P).state, Poll h q) + (hd : 0 < Δ) (hc : Δ ≤ C) + +open scoped Classical in +/-- The carries used in the `Beat` construction. -/ +def Carries (u : ℕ) (W : Set (Table F)) (cost : ℕ) := + Computes F u W ((wiring h Δ C).pair D) ((U).port x y payload) + (fun i : CaseBit h s => (pending h s hd hc i.1, oldBits h s i)) (output h s hd hc) (fun _ + => 1) cost + +open scoped Classical in +theorem controller (hΔ : 3 ≤ Δ) (hg : gain Δ ≤ K) (hk : 2 ^ (k Δ) ≤ K) + (hs : range (T := T) Δ C r ≤ T.scheme.m) : + ∃ gate : Table F, ∀ {u cost : ℕ} {W : Set (Table F)}, 3 ≤ u → arity Q A L v (pos h) z Δ C B r + ≤ u → + A.shrinkWidth N k' (copies Δ B) ≤ u → (tables Δ C h gate : Set _) ⊆ W → + Carries h s hd hc u W cost → + Transforms F u W (frame A L (Q.b * v) z payload Δ C P) + (frame V L v z payload (Δ ^ degreePower) (C ^ degreePower) (after L P K Q.ratio 1 σ)) + (runCost Δ C h + cost) := by + obtain ⟨gate, _, net⟩ := supply h s hd hc hk hs + refine ⟨gate, ?_⟩ + intro u cost W hu hf hsh hw ship + simp only [tables, Finset.coe_insert, Set.insert_subset_iff] at hw + have init := first h hk hs s hu hf hw.2.2.2.2.2 hw.2.2.2.2.1 + have act := net hu hf hw.1 hw.2.1 hw.2.2.1 + have keep := Computes.of_map (L := W) (x := oldBits h s) (Map.circuit hu (Circuit.id F D)) + (fun _ => rfl) + have run := ((act.restrict Prod.fst).par keep).comp ship + simp only [mul_one, Function.comp_apply] at run + have hi : (fun i : CaseBit h s => (mid h s i.1, oldBits h s i)) = + fun i => start (Q := Q) (r := r) i.1.1 (((s i.1.1).selector (BatchDescent.Beat.choices + Q)).write i.1.2) + i.2.1 i.2.2 := funext fun i => (start_at h s i).symm + rw [hi] at run + let desc := selected h s hd hc hΔ hg + have lift := Transforms.checked hu desc (start (Q := Q) (r := r)) init run + have result := lift.comp (Contraction.shrink hu hsh hw.2.2.2.1) + refine result.mono ?_ + unfold runCost + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Realizing the relocation of the exposed bits of a contracted network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + (s : ∀ q : (frame A L (Q.b * v) z payload Δ C P).state, Poll h q) + (hd : 0 < Δ) (hc : Δ ≤ C) + +local notation "n" => (T.scheme.h - (T.scheme.h - r)) +local notation "N" => Template.sweep (raw Q A L v (pos h) z Δ C B r) + +open scoped Classical in +theorem ship {W : Set (Table F)} {u : ℕ} (hu : 3 ≤ u) (hm : 1 ≤ T.scheme.m) + (hw : A.carryWidth N (slots A r) (n + 1) payload ≤ u) + (gate : A.carryGate N (slots A r) (n + 1) payload ∈ W) : + Carries h s hd hc u W (A.carryCost N (slots A r) (T.scheme.d + 1) (n + 1) x y payload p) := by + have hh : 2 ^ (n + 1) * ((payload + 1) * (2 ^ T.scheme.m + 2 ^ (T.scheme.m + (n + 1)))) < 2 ^ p.w + := by + rw [Nat.sub_sub_self h.group] + exact fanout h + have hm' : 1 ≤ T.scheme.m + (n + 1) := hm.trans (Nat.le_add_right ..) + exact Attachment.carry (swept h s hd hc) (fun i => i.1.val) (moved h s hd hc) + (fun i => i.1.property.2) (fun i => fits h i.1 (s i.1) i.2 hd hc) + (Match.rowIndex T.scheme.m (n + 1)) (fun _ => rfl) (fun _ _ => rfl) + (fun i => exterior h i.1 (s i.1) i.2 hd hc) hu hm hm' hh hw gate + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Realization with prescribed arity and cost budgets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Coloring + +variable {F : Type} [Field F] {x y : Wire} {T : Template F} {Q : Gadget F} + {A : Attachment T} {L : BorderLimit F x y} {P : Bound} {p : Prices F} + {r v z payload d B K H Δ C : ℕ} {σ : ℝ} + (h : Input A L P p r Q.b (Q.b * v) v z payload d B K H σ) + +local notation "n" => (T.scheme.h - (T.scheme.h - r)) +local notation "N" => Template.sweep (raw Q A L v (pos h) z Δ C B r) +local notation "Y" => A.shrink N (slots A r) (copies Δ B) + +open scoped Classical in +theorem realize (hd : 3 ≤ Δ) (hc : Δ ≤ C) (hg : gain Δ ≤ K) (hk : 2 ^ (k Δ) ≤ K) + (hs : range (T := T) Δ C r ≤ T.scheme.m) {u : ℕ} (hu : 3 ≤ u) (hm : 1 ≤ T.scheme.m) + (hf : arity Q A L v (pos h) z Δ C B r ≤ u) + (hsh : A.shrinkWidth N (slots A r) (copies Δ B) ≤ u) + (hv : A.carryWidth N (slots A r) (n + 1) payload ≤ u) : + ∃ W : Finset (Table F), W.card ≤ 11 ∧ + Transforms F u W (frame A L (Q.b * v) z payload Δ C P) + (frame Y L v z payload (Δ ^ degreePower) (C ^ degreePower) (after L P K Q.ratio 1 σ)) + (runCost Δ C h + A.carryCost N (slots A r) (T.scheme.d + 1) (n + 1) x y payload p) := by + have hp : 0 < Δ := by omega + let s (q : (frame A L (Q.b * v) z payload Δ C P).state) := Classical.choice (elect h q hp hc hk) + obtain ⟨gate, go⟩ := controller h s hp hc hd hg hk hs + let keys := insert (A.carryGate N (slots A r) (n + 1) payload) (tables Δ C h gate) + have move := ship h s hp hc (W := (keys : Set _)) hu hm hv (Finset.mem_insert_self ..) + have run := go (W := (keys : Set _)) hu hf hsh (fun _ h => Finset.mem_insert_of_mem h) move + exact ⟨keys, (Finset.card_insert_le ..).trans (Nat.add_le_add_right (few Δ C h gate) 1), run⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Cost prior to moving the outer payload -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Case +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) + +local notation "I" => Case κ Q.b d B +local notation "Y" => fresh Q Δ C d B +local notation "M" => plan Q Δ C d B + +/-- The subtotal used in the `Beat` construction. -/ +def subtotal (i : I) := + firstCost (Q.extend i.F) i.A Δ C i.r i.p + + (secondCost (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B i.r i.p + + i.A.sweepCost (M i) (slots i.A i.r) (i.T.scheme.d + 1) + + 24 * (i.A.Requests (Y i) (slots i.A i.r) (i.T.scheme.d + 1)).width + + rebuildCost (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B i.r i.p) + + (i.A.shrinkCost (Y i) (slots i.A i.r) (copies Δ B) i.x i.y i.payload + + 208 * (Attachment.payload i.x i.y i.payload i.m).width + 4 * (i.T.Candidate i.a (b Q)).width) + +theorem subtotal_bound : Total (subtotal Q Δ C d B) := by + have s := (fresh_bound Q Δ C d B).requests (place_factor Q d B).short (hop_factor Q d B).short + have sub := (((secondCost_bound Q Δ C d B).add (sweepCost_bound Q Δ C d B)).add + (s.scale 24)).add (rebuildCost_bound Q Δ C d B) + exact (Cost.total ((firstCost_bound Q Δ C d B).add sub)).add (tailCost_bound Q Δ C d B) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Choosing one exponent for all controllers at fixed degrees -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Packing Assembly Case + +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) +local notation "I" => Case κ Q.b d B +local notation "Y" => fresh Q Δ C d B + +/-- The quantity computed by `i.A.carryCost (Y i) (slots i.A i.r) (i.T.scheme.d + 1) (i.n + 1) +i.x i.y i.payload i.p`. -/ +def shipment (i : I) := + i.A.carryCost (Y i) (slots i.A i.r) (i.T.scheme.d + 1) (i.n + 1) i.x i.y i.payload i.p + +/-- The quantity computed by `i.A.carryWidth (Y i) (slots i.A i.r) (i.n + 1) i.payload`. -/ +def shippingWidth (i : I) := + i.A.carryWidth (Y i) (slots i.A i.r) (i.n + 1) i.payload + +/-- The data for the adequate construction, including `few`, `degree`, `spans`, `counters`, +`labels`. -/ +structure Adequate (i : I) (H : ℕ) : Prop where + few : 11 ≤ i.short ^ H + degree : i.T.degree i.a Δ C ≤ H + spans : 2 ^ e Δ B ≤ H + counters : (meter i.L i.z Δ B).count ≤ i.base ^ H + labels : (Y i).scheme.ℓ + (pack Q Δ C d B i).ℓ ≤ H * (i.T.scheme.ℓ + i.A.ℓ) + i.base ^ H + arity : Beat.arity (Q.extend i.F) i.A i.L i.v i.positive i.z Δ C B i.r ≤ i.short ^ H + shrink : i.A.shrinkWidth (Y i) (slots i.A i.r) (copies Δ B) ≤ i.short ^ H + range : Beat.range (T := i.T) Δ C i.r ≤ i.short ^ H + carry : shippingWidth Q Δ C d B i ≤ i.short ^ H + size : subtotal Q Δ C d B i + shipment Q Δ C d B i ≤ + Contraction.size (x := i.x) (y := i.y) i.A i.p i.r i.z i.payload H + +theorem sufficient (ha : Short (shippingWidth Q Δ C d B)) (hc : Total (shipment Q Δ C d B)) : + ∃ H, 0 < H ∧ ∀ i : I, Adequate Q Δ C d B i H := by + obtain ⟨j₁, h₁⟩ := (meter_bound Q Δ d B).bound + obtain ⟨j₂, h₂⟩ := labels_bound Q Δ C d B + obtain ⟨j₃, h₃⟩ := (arity_bound Q Δ C d B).bound + obtain ⟨j₄, h₄⟩ := (shrinkWidth_bound Q Δ C d B).bound + obtain ⟨j₅, h₅⟩ := (range_bound Q Δ C d B).bound + obtain ⟨j₆, h₆⟩ := ha.bound + obtain ⟨j₇, h₇⟩ := (subtotal_bound Q Δ C d B).add hc + let H := 11 + maxDegree C d + 2 ^ e Δ B + j₁ + j₂ + j₃ + j₄ + j₅ + j₆ + j₇ + have hp : 0 < 2 ^ e Δ B := by positivity + have hl : 11 ≤ H := by unfold H; omega + refine ⟨H, by omega, fun i => ?_⟩ + have raised {n l : ℕ} (hn : 2 ≤ n) (hl : l ≤ H) : n ^ l ≤ n ^ H := + Nat.pow_le_pow_right (by omega) hl + refine ⟨hl.trans (Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left i.short_two H)), + (child_degree Q Δ C d B i).trans (by unfold H; omega), + by unfold H; omega, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · exact (h₁ i).trans (raised i.base_two (by unfold H; omega)) + · have ht : j₂ ≤ H := by unfold H; omega + exact (h₂ i).trans (Nat.add_le_add (Nat.mul_le_mul_right _ ht) (raised i.base_two ht)) + · exact (h₃ i).trans (raised i.short_two (by unfold H; omega)) + · exact (h₄ i).trans (raised i.short_two (by unfold H; omega)) + · exact (h₅ i).trans (raised i.short_two (by unfold H; omega)) + · exact (h₆ i).trans (raised i.short_two (by unfold H; omega)) + · have ht : j₇ ≤ H := by unfold H; omega + exact (h₇ i).trans (Nat.add_le_add (Nat.add_le_add + (Nat.mul_le_mul_left _ (raised i.long_two ht)) (Nat.mul_le_mul_left _ (raised i.block_two + ht))) + (Nat.mul_le_mul_left _ (raised i.outer_two ht))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Realizing a wire-saving phase with its frozen border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +open Assembly Packing + +variable {κ : Type} [Field κ] (Q : Gadget κ) (Δ C d B : ℕ) + +open scoped Classical in +/-- The quantity computed by `1 + 2 ^ (k Δ) + gain Δ`. -/ +def fixed := 1 + 2 ^ (k Δ) + gain Δ + +open scoped Classical in +theorem fixed_pos : 0 < fixed Δ := by unfold fixed; positivity + +variable {d B} (u : Case κ Q.b d B) +local notation "G" => Q.extend u.F + +open scoped Classical in +private theorem normalized : Input u.A u.L u.P u.p u.r Q.b (Q.b * u.v) u.v u.z u.payload d B u.K + u.H u.σ := by + rw [← u.h.units] + exact u.h + +local notation "N" => + Template.sweep (raw G u.A u.L u.v (pos (Q := G) (normalized Q u)) u.z Δ C B u.r) +local notation "Y" => Attachment.shrink u.A N (slots u.A u.r) (copies Δ B) + +local notation "n" => (u.T.scheme.h - (u.T.scheme.h - u.r)) + +-- Explicit equalities keep comparisons of widths from unfolding the +-- station tables in the template over the extension field. +open scoped Classical in +private theorem plan_def : plan Q Δ C d B u = raw G u.A u.L u.v (pos (Q + := G) (normalized Q u)) u.z Δ C B u.r := + rfl + +open scoped Classical in +private theorem fresh_def : fresh Q Δ C d B u = N := congrArg Template.sweep (plan_def Q Δ C u) + +open scoped Classical in +private theorem short_width (ha : Adequate Q Δ C d B u u.H) : + u.A.shrinkWidth N (slots u.A u.r) (copies Δ B) ≤ (short u.A u.r u.z u.payload) ^ u.H := + (congrArg (fun J => u.A.shrinkWidth J (slots u.A u.r) (copies Δ B)) (fresh_def Q Δ C + u)).symm.trans_le ha.shrink + +open scoped Classical in +private theorem combined_width (ha : Adequate Q Δ C d B u u.H) : + (N).scheme.ℓ + (Y).ℓ ≤ u.H * (u.T.scheme.ℓ + u.A.ℓ) + u.base ^ u.H := + (congrArg (fun J => J.scheme.ℓ + (u.A.shrink J (slots u.A u.r) (copies Δ B)).ℓ) + (fresh_def Q Δ C u)).symm.trans_le ha.labels + +open scoped Classical in +private theorem deliver_width (ha : Adequate Q Δ C d B u u.H) : + u.A.carryWidth N (slots u.A u.r) (n + 1) u.payload ≤ (short u.A u.r u.z u.payload) ^ u.H := + (congrArg (fun J => u.A.carryWidth J (slots u.A u.r) (n + 1) u.payload) + (fresh_def Q Δ C u)).symm.trans_le ha.carry + +open scoped Classical in +private theorem expense (ha : Adequate Q Δ C d B u u.H) : + runCost (Q := G) Δ C (normalized Q u) + u.A.carryCost N (slots u.A u.r) (u.T.scheme.d + 1) (n + + 1) u.x u.y u.payload u.p ≤ + size (x := u.x) (y := u.y) u.A u.p u.r u.z u.payload u.H := by + let bill (J V : Template u.F) := + firstCost G u.A Δ C u.r u.p + + (secondCost G u.A u.L u.v (pos (Q := G) (normalized Q u)) u.z Δ C B u.r u.p + + u.A.sweepCost J (slots u.A u.r) (u.T.scheme.d + 1) + + 24 * (u.A.Requests V (slots u.A u.r) (u.T.scheme.d + 1)).width + + rebuildCost G u.A u.L u.v (pos (Q := G) (normalized Q u)) u.z Δ C B u.r u.p) + + (u.A.shrinkCost V (slots u.A u.r) (copies Δ B) u.x u.y u.payload + + 208 * (Attachment.payload u.x u.y u.payload u.m).width + + 4 * (u.T.Candidate u.a (b Q)).width) + + u.A.carryCost V (slots u.A u.r) (u.T.scheme.d + 1) (n + 1) u.x u.y u.payload u.p + exact (congrArg₂ bill (plan_def Q Δ C u) (fresh_def Q Δ C u)).symm.trans_le ha.size + +open scoped Classical in +private theorem hardware (hd : 3 ≤ Δ) (hc : Δ ≤ C) (hk : fixed Δ ≤ u.K) + (ha : Adequate Q Δ C d B u u.H) : + ∃ W : Finset (Table u.F), W.card ≤ (short u.A u.r u.z u.payload) ^ u.H ∧ + Transforms u.F ((short u.A u.r u.z u.payload) ^ u.H) W (frame u.A u.L (Q.b * u.v) u.z + u.payload Δ C u.P) + (frame Y u.L u.v u.z u.payload (Δ ^ degreePower) (C ^ degreePower) (after u.L u.P u.K + Q.ratio 1 u.σ)) + (size (x := u.x) (y := u.y) u.A u.p u.r u.z u.payload u.H) := by + have h := normalized Q u + have h₁ : 2 ^ (k Δ) ≤ u.K := ((Nat.le_add_left ..).trans (Nat.le_add_right ..)).trans hk + have h₂ : gain Δ ≤ u.K := (Nat.le_add_left ..).trans hk + have wid : range (T := u.T) Δ C u.r ≤ u.T.scheme.m := ha.range.trans h.small + have low : 3 ≤ (short u.A u.r u.z u.payload) ^ u.H := (by decide : 3 ≤ 11).trans ha.few + have hm : 1 ≤ u.T.scheme.m := ((by decide : 1 ≤ 11).trans ha.few).trans h.small + obtain ⟨keys, hkeys, run⟩ := realize (Q := G) (normalized Q u) hd hc h₂ h₁ wid low hm ha.arity + (short_width Q Δ C u ha) (deliver_width Q Δ C u ha) + have last := run.mono (expense Q Δ C u ha) + have hr : (G).ratio = Q.ratio := rfl + rw [hr] at last + exact ⟨keys, hkeys.trans ha.few, last⟩ + +open scoped Classical in +theorem build (hd : 3 ≤ Δ) (hc : Δ ≤ C) (hk : fixed Δ ≤ u.K) + (ha : Adequate Q Δ C d B u u.H) : + Nonempty (Output u.A u.L u.P u.p u.r (Q.b * u.v) u.v u.z u.payload Δ (Δ ^ degreePower) + C (C ^ degreePower) u.K u.H Q.ratio 1 u.σ) := by + have h := normalized Q u + have hp : 0 < u.K := (fixed_pos Δ).trans_le hk + obtain ⟨keys, hkeys, run⟩ := hardware Q Δ C u hd hc hk ha + refine ⟨⟨N, Y, Nat.sub_add_cancel h.group, Nat.le_add_right .., ?_, ha.degree, h.full, rfl, + ha.spans, ?_, ?_, ha.counters, combined_width Q Δ C u ha, keys, hkeys, run⟩⟩ + · change u.T.scheme.m + (n + 1) ≤ _ + rw [Nat.sub_sub_self h.group]; omega + · change n + u.A.k ≤ _ + rw [Nat.sub_sub_self h.group]; omega + · change 2 ^ max u.A.e (e Δ B) ≤ 2 ^ u.A.e + u.H + rcases le_total u.A.e (e Δ B) with hl|hl + · rw [max_eq_right hl] + exact ha.spans.trans (Nat.le_add_left ..) + · rw [max_eq_left hl] + exact Nat.le_add_right .. + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.Beat +end + +/- # Uniform realization of a contraction step over all finite extensions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +open Beat + +theorem subroundRule (κ : Type) [Field κ] : SubroundRule κ := by + intro Q Δ hd + refine ⟨fixed Δ, fixed_pos Δ, fun C d B hc => ?_⟩ + obtain ⟨H, hH, fit⟩ := sufficient Q Δ C d B (carryWidth_bound Q Δ C d B) (carrySize_bound Q Δ C d + B) + refine ⟨H, hH, ?_⟩ + intro F _ _ _ x y T A L P p r u v z payload σ h + have eq := h.units + subst u + let i : Case κ Q.b d B := ⟨F, x, y, T, A, L, P, p, r, Q.b * v, v, z, payload, fixed Δ, H, σ, h⟩ + exact build Q Δ C i hd hc le_rfl (fit i) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Costs.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Costs.lean new file mode 100644 index 0000000000..f617694e2c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Costs.lean @@ -0,0 +1,962 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Bins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.FieldLift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Downstream +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Present +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Design + +/-! +# Packing the occurrences into sphere cells + +First treat the group number as a host coordinate. Split it off again +after choosing simultaneous balanced partitions. The candidate host +is common to all groups, while the occupied cells can vary. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +variable {F : Type} {x y : Wire} {h a g D T : ℕ} {L θ : ℝ} +variable (P : Board F x y h) + +open scoped Classical in +/-- The data for the cells construction, including `V`, `[fv`, `seats`, `A`, `[fa`. -/ +structure Cells (a g D T : ℕ) (L : ℝ) where + /-- The type of vertices. -/ + V : Type + [fv : Fintype V] + seats : Fintype.card V * 2 ^ a ≤ 2 * P.seats + /-- The `Cells` component of type `Type`. -/ + A : Type + [fa : Fintype A] + size : (Fintype.card A : ℝ) * D * T ≤ 17 * L + /-- Embeds the coordinates as `A ↪ V × Cell a`. -/ + site : A ↪ V × Cell a + /-- The `Cells` component of type `P.diagram.V → A`. -/ + cell : P.diagram.V → A + mass : ∀ c, push cell P.charge c ≤ (D : ℝ) * T + /-- The neighbors of each vertex of type `V → Finset V`. -/ + adj : V → Finset V + sym : ∀ v z, z ∈ adj v → v ∈ adj z + degree : ∀ v, (adj v).card ≤ g + edge : ∀ e, let q := site (cell (P.diagram.source e)) + let p := site (cell (P.diagram.target e)) + p.2 = q.2 ∧ p.1 ∈ adj q.1 + +attribute [instance] Cells.fv Cells.fa + +open scoped Classical in +theorem Board.charge_nonneg (v : P.diagram.V) : 0 ≤ P.charge v := + (Nat.cast_nonneg _).trans (P.cover v) + +open scoped Classical in +/-- The value specified by `push (splitAddr P.V a ha ∘ P.place) P.charge (v, i)`. -/ +abbrev Board.groupLoad (a : ℕ) (ha : a ≤ h) (v : P.V × Cell a) (i : Cell (h - a)) := + push (splitAddr P.V a ha ∘ P.place) P.charge (v, i) + +open scoped Classical in +/-- The quantity computed by `Grouping (inGroup a P.adj) (inGroup a P.adj) g g 1 ((D : ℝ) * T / +2) (P.groupLoad a ha)`. -/ +abbrev Board.Plan (a : ℕ) (ha : a ≤ h) (g D T : ℕ) := + Grouping (inGroup a P.adj) (inGroup a P.adj) g g 1 ((D : ℝ) * T / 2) (P.groupLoad a ha) + +open scoped Classical in +theorem Board.groupBound (ha : a ≤ h) (ok : P.Ready g D T L θ) (v : P.V × Cell a) (i : Cell (h - + a)) : + 0 ≤ P.groupLoad a ha v i ∧ P.groupLoad a ha v i ≤ (D : ℝ) * T / 2 := by + refine ⟨push_nonneg _ _ P.charge_nonneg _, ?_⟩ + exact push_max _ (fun _ => True) P.charge _ (by positivity) (fun v => (ok.2.2.2 v).1) + (by simp) ((splitAddr _ a ha).injective.comp P.one).injOn _ + +open scoped Classical in +theorem inGroup_sym (v z : P.V × Cell a) (hz : z ∈ inGroup a P.adj v) : + v ∈ inGroup a P.adj z := by + obtain ⟨he, hb⟩ := (mem_inGroup _ _ _ _).mp hz + exact (mem_inGroup _ _ _ _).mpr ⟨P.sym _ _ he, hb.symm⟩ + +open scoped Classical in +/-- The with cells of type `Cells P a ((4 * g) ^ 300) D T L`, constructed using `splitAddr P.V a +ha.le ∘ P.place`. -/ +def Board.withCells (hg : 0 < g) (hD : 0 < D) (hT : 0 < T) (ha : a < h) (ok : P.Ready g D T L θ) + (slack : (P.seats : ℝ) * D * T ≤ L * (2 : ℝ) ^ (h - a)) + (G : P.Plan a ha.le g D T) : Cells P a ((4 * g) ^ 300) D T L := by + let f := splitAddr P.V a ha.le ∘ P.place + let w v i := push f P.charge (v, i) + let N := inGroup a P.adj + let B := (D : ℝ) * T / 2 + have hb : 0 < B := by unfold B; positivity + let loc (p : (P.V × Cell a) × Cell (h - a)) := G.loc p.1 p.2 + let place : G.Colony ↪ Site P.V (h - a) × Cell a := + ⟨splitSite ∘ G.site, splitSite.injective.comp G.site_injective⟩ + have eq : (2 : ℝ) ^ 1 * B = (D : ℝ) * T := by unfold B; ring + have count : (Fintype.card G.Colony : ℝ) * D * T ≤ 17 * L := by + have total : (∑ v, ∑ i, w v i) ≤ L := by + rw [← Fintype.sum_prod_type (push f P.charge), sum_push] + exact ok.2.1 + have hs : (Fintype.card (P.V × Cell a) : ℝ) * ((D : ℝ) * T) ≤ L := by + apply le_of_mul_le_mul_right _ (by positivity : (0 : ℝ) < 2 ^ (h - a)) + refine le_trans ?_ slack + simp only [Board.seats, Fintype.card_prod, card_cell, Nat.cast_mul, Nat.cast_pow, + Nat.cast_ofNat] + have he : (2 : ℝ) ^ a * 2 ^ (h - a) = 2 ^ h := by rw [← pow_add, Nat.add_sub_of_le ha.le] + rw [← he] + exact le_of_eq (by ring) + have hm := G.card_bound + change (Fintype.card G.Colony : ℝ) ≤ Fintype.card (P.V × Cell a) + 16 * (∑ v, ∑ i, + w v i) / ((2 : ℝ) ^ 1 * B) at hm + rw [eq] at hm + have ht := mul_le_mul_of_nonneg_right hm (show 0 ≤ (D : ℝ) * T by positivity) + rw [add_mul, div_mul_cancel₀ _ (by positivity)] at ht + linarith + refine { + V := Site P.V (h - a) + seats := ?_ + A := G.Colony + size := count + site := place + cell := loc ∘ f + mass := ?_ + adj := near P.adj g + sym := near_symm P.sym g + degree := near_card P.adj g hg ok.1 + edge := ?_ } + · refine (Nat.mul_le_mul_right _ (Site.card P.V (h - a))).trans_eq ?_ + unfold Board.seats + have he : (2 : ℕ) ^ (h - a) * 2 ^ a = 2 ^ h := by rw [← pow_add, Nat.sub_add_cancel ha.le] + rw [← he] + ring + · intro c + rw [← push_comp] + refine le_trans ?_ eq.le + have hm := G.here_load hb.le (G.site c) + simp only [Grouping.here, G.site_injective.eq_iff] at hm + refine le_trans ?_ hm + exact sum_le_sum (fun p _ => by unfold loc; split_ifs <;> rfl) + · intro e + let v := P.place (P.diagram.source e) + let z := P.place (P.diagram.target e) + obtain ⟨he, hz⟩ := P.edge e + change z.2 = v.2 at he + have h' : (z.1, ancestor ha.le z.2) ∈ N (v.1, ancestor ha.le v.2) := + (mem_inGroup _ _ _ _).mpr ⟨hz, congrArg (ancestor ha.le) he⟩ + have hd := G.here_full (inGroup_sym P) le_rfl h' (suffix a v.2) + have hm := split_near P.adj g hd + change (splitSite (G.here (z.1, ancestor ha.le z.2) (suffix a z.2))).2 = _ ∧ + (splitSite (G.here (z.1, ancestor ha.le z.2) (suffix a z.2))).1 ∈ _ + rw [congrArg (suffix a) he] + exact ⟨hm.1.symm, hm.2⟩ + +open scoped Classical in +theorem cells (hg : 0 < g) (hD : 0 < D) (hT : 0 < T) (ha : a < h) (ok : P.Ready g D T L θ) + (slack : (P.seats : ℝ) * D * T ≤ L * (2 : ℝ) ^ (h - a)) : + Nonempty (Cells P a ((4 * g) ^ 300) D T L) := by + let N := inGroup a P.adj + have hd v : (N v).card ≤ g := by simpa [N, inGroup] using ok.1 v.1 + obtain ⟨G⟩ := pack_group N N g g hg hg (inGroup_sym P) (inGroup_sym P) (fun _ => subset_rfl) hd hd + (le_refl 1) (by omega : 1 ≤ h - a) _ (by positivity) _ (P.groupBound ha.le ok) + exact ⟨P.withCells hg hD hT ha ok slack G⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# Moving exterior bits to identity stations + +Introduce one identity per exterior bit. Coarsening these by cell gives +one immobile station in each cell that has exterior ports. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +variable {F V : Type} [Field F] {x y : Wire} + +open scoped Classical in +/-- Reindexes `(Σ _ : T, Unit)` and `T where toFun` by an equivalence. -/ +def forget (T : Type) : (Σ _ : T, Unit) ≃ T where + toFun := Sigma.fst + invFun t := ⟨t, ()⟩ + left_inv _ := rfl + right_inv _ := rfl + +open scoped Classical in +/-- Builds `Border F (slots x ⊕ slots y) x y x y where table _` with the specified `table`, +`src`, `dst`. -/ +def ident (F : Type) [Field F] (x y : Wire) : Border F (slots x ⊕ slots y) x y x y where + table _ := ⟨.bit, .bit, fun i j => if i = j then 1 else 0⟩ + src := forget _ + dst := (forget _).trans (Equiv.sumComm _ _) + +open scoped Classical in +theorem ident_tensor (t : slots x ⊕ slots y) : (ident F x y).tensor t = t := by + cases t <;> rfl + +open scoped Classical in +private theorem weight_ident (s u : Val x) (t v : Val y) : + (ident F x y).weight s t u v = if s = u ∧ t = v then 1 else 0 := by + unfold Border.weight + rw [Fintype.prod_sum_type] + change (∏ i, if bits x s i = bits x u i then (1 : F) else 0) * + (∏ j, if bits y v j = bits y t j then 1 else 0) = _ + have delta (a : Wire) (b c : Val a) : + (∏ i, if bits a b i = bits a c i then (1 : F) else 0) = if b = c then 1 else 0 := by + by_cases h : b = c + · simp [h] + · obtain ⟨i, hi⟩ := Function.ne_iff.mp ((bits a).injective.ne h) + rw [ite_eq_right h] + exact prod_eq_zero (mem_univ i) (ite_eq_right hi) + simp only [delta, eq_comm (a := v), ite_mul, one_mul, zero_mul, ite_and] + +variable (G : Diagram F x y) + +open scoped Classical in +theorem eval_ident : ((ident F x y).attach G).eval = G.eval := by + funext s t + rw [Border.eval_attach] + simp [weight_ident, ite_and, mul_ite] + +open scoped Classical in +theorem port_ident (i : slots x ⊕ slots y) : portEnd ((ident F x y).attach G) i = Sum.inr i := by + cases i <;> rfl + +variable [Fintype V] (o : G.V → V) + +open scoped Classical in +theorem port_coarsen (i : slots x ⊕ slots y) : + portEnd (G.coarsen o) i = o (portEnd G i) := by cases i <;> rfl + +open scoped Classical in +theorem arity_coarsen (v : V) : (G.coarsen o).arity v ≤ push o (fun i => (G.arity i : ℝ)) v := by + let f := fun i => (o (G.source i), o (G.target i)) + let e : (G.coarsen o).E ↪ G.E := Function.Embedding.subtype _ + have ha := site_arity (G.coarsen o) id v + have h₁ : push id (fun i : (G.coarsen o).V => ((G.coarsen o).arity i : ℝ)) v = + (G.coarsen o).arity v := by simp [push] + rw [h₁] at ha + rw [ha, site_arity] + apply add_le_add + · simp only [port_load, Function.id_comp] + rw [show portEnd (G.coarsen o) = o ∘ portEnd G from funext (port_coarsen _ _)] + · exact Nat.cast_le.mpr (degree_select f e v) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# The mobile and immobile stations in a cell + +Use `D` slots for mobile stations and one for the exterior identity. +Discard the scalar slots only after retaining their product. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Cells + +open Packing Finset + +variable {F : Type} [Field F] {x y : Wire} {h a g D T : ℕ} {L : ℝ} +variable {P : Board F x y h} (C : Cells P a g D T L) (bin : P.diagram.V → Fin D) + +open scoped Classical in +/-- Indexes the slot by the coordinates of `C.A × Option (Fin D)`. -/ +abbrev Slot := C.A × Option (Fin D) +open scoped Classical in +/-- The value specified by `(ident F x y).attach P.diagram`. -/ +abbrev before (P : Board F x y h) := (ident F x y).attach P.diagram + +open scoped Classical in +/-- The value specified by `(C.cell v, bin v)`. -/ +def pack (v : P.diagram.V) : C.A × Fin D := (C.cell v, bin v) + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `(C.cell v, some (bin v))`. -/ +def seat : (before P).V → C.Slot + | .inl v => (C.cell v, some (bin v)) + | .inr q => (C.cell (portEnd P.diagram q), none) + +open scoped Classical in +/-- The value specified by `(before P).coarsen (C.seat bin)`. -/ +abbrev grouped := (before P).coarsen (C.seat bin) +open scoped Classical in +/-- The value specified by `(C.grouped bin).prune`. -/ +abbrev stations := (C.grouped bin).prune + +open scoped Classical in +/-- Computes the place by the application `C.site v.val.1`. -/ +def place (v : (C.stations bin).V) := C.site v.val.1 + +open scoped Classical in +theorem evaluation : ∃ c : F, ∀ x y, + c * (C.stations bin).eval x y = P.diagram.eval x y := by + obtain ⟨c, hc⟩ := (C.grouped bin).eval_prune + refine ⟨c, fun x y => (hc _ _).trans ?_⟩ + rw [Diagram.eval_coarsen, eval_ident] + +open scoped Classical in +theorem port (q : slots x ⊕ slots y) : + (portEnd (C.stations bin) q).val = (C.cell (portEnd P.diagram q), none) := by + cases q <;> rfl + +open scoped Classical in +theorem loopless (e : (C.stations bin).E) : + (C.stations bin).source e ≠ (C.stations bin).target e := + fun h => e.property (congrArg Subtype.val h) + +open scoped Classical in +theorem contact (e : (C.stations bin).E) : + let p := C.place bin ((C.stations bin).source e) + let q := C.place bin ((C.stations bin).target e) + q.2 = p.2 ∧ (q.1 = p.1 ∨ q.1 ∈ C.adj p.1) := by + rcases e with ⟨i|j|k, _⟩ + · exact ⟨(C.edge i).1, .inr (C.edge i).2⟩ + · exact ⟨rfl, .inl rfl⟩ + · exact ⟨rfl, .inl rfl⟩ + +open scoped Classical in +/-- The quantity computed by `q.2.elim (2 * exterior P.diagram C.cell q.1) (fun i => push +(C.pack bin) P.charge (q.1, i))`. -/ +def estimate (q : C.Slot) : ℝ := + q.2.elim (2 * exterior P.diagram C.cell q.1) + (fun i => push (C.pack bin) P.charge (q.1, i)) + +omit [Field F] in +open scoped Classical in +theorem estimate_nonneg (q : C.Slot) : 0 ≤ C.estimate bin q := by + obtain ⟨c, _|i⟩ := q + · exact mul_nonneg (by norm_num) (Nat.cast_nonneg _) + · exact push_nonneg _ _ P.charge_nonneg _ + +open scoped Classical in +theorem arity (v : (C.stations bin).V) : (C.stations bin).arity v ≤ C.estimate bin v.1 := by + refine (arity_coarsen (before P) (C.seat bin) v.val).trans ?_ + unfold push + rw [Fintype.sum_sum_type] + obtain ⟨⟨c, _|i⟩, hv⟩ := v + · simp only [seat, Prod.mk.injEq, reduceCtorEq, and_false, ite_false, sum_const_zero, zero_add, + and_true] + change _ ≤ 2 * (exterior P.diagram C.cell c : ℝ) + rw [port_load, push, mul_sum] + apply sum_le_sum + intro q _ + change (if C.cell (portEnd P.diagram q) = c then (2 : ℝ) else 0) ≤ _ + simp [Function.comp_apply, mul_ite] + · simp only [seat, Prod.mk.injEq, reduceCtorEq, and_false, ite_false, sum_const_zero, add_zero, + Option.some.injEq] + apply sum_le_sum + intro v _ + simp only [pack, Prod.mk.injEq] + split_ifs + · exact P.cover v + · exact le_rfl + +omit [Field F] in +open scoped Classical in +theorem exterior_le (c : C.A) : (exterior P.diagram C.cell c : ℝ) ≤ (D : ℝ) * T := calc + _ ≤ push C.cell (fun v => (P.diagram.arity v : ℝ)) c := by + rw [site_arity] + exact le_add_of_nonneg_right (Nat.cast_nonneg _) + _ ≤ push C.cell P.charge c := push_le_push _ P.cover _ + _ ≤ _ := C.mass c + +omit [Field F] in +open scoped Classical in +theorem cell_estimate (c : C.A) : (∑ i, C.estimate bin (c, i)) ≤ 3 * (D : ℝ) * T := by + rw [Fintype.sum_option] + change 2 * (exterior P.diagram C.cell c : ℝ) + (∑ i, push (C.pack bin) P.charge (c, i)) ≤ _ + rw [← push_fst, push_comp, show Prod.fst ∘ C.pack bin = C.cell from rfl] + linarith [C.exterior_le c, C.mass c] + +omit [Field F] in +open scoped Classical in +theorem estimate_squares + (bound : ∑ z, (push (C.pack bin) P.charge z) ^ 2 ≤ 3 * L * T) + (exposed : ((wd x + wd y : ℕ) : ℝ) * D ≤ L) : + (∑ z, (C.estimate bin z) ^ 2) ≤ 7 * L * T := by + have he : (∑ c, (exterior P.diagram C.cell c : ℝ)) = wd x + wd y := by + simp only [port_load, sum_push, sum_const, card_univ, nsmul_eq_mul, mul_one, + Fintype.card_sum, card_slots, Nat.cast_add] + have he' : (∑ c, (2 * (exterior P.diagram C.cell c : ℝ)) ^ 2) ≤ 4 * L * T := calc + _ ≤ ∑ c, 4 * ((D : ℝ) * T) * exterior P.diagram C.cell c := by + apply sum_le_sum + intro c _ + nlinarith only [mul_le_mul_of_nonneg_right (C.exterior_le c) + (Nat.cast_nonneg (α := ℝ) (exterior P.diagram C.cell c))] + _ ≤ _ := by + rw [← mul_sum, he] + rw [Nat.cast_add] at exposed + linarith only [mul_le_mul_of_nonneg_right exposed (Nat.cast_nonneg (α := ℝ) T)] + rw [Fintype.sum_prod_type] + simp_rw [Fintype.sum_option] + rw [sum_add_distrib] + rw [Fintype.sum_prod_type] at bound + exact (add_le_add he' bound).trans_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Cells +end + +/- +# Uniform width for the local input + +A station can touch at most `D+1` slots in each of at most `g+1` +cells. Padding both orientations therefore adds at most `4T` to +its arity when `g < D` and `R D² ≤ T`. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Cells + +open Packing Finset + +variable {F : Type} [Field F] {x y : Wire} {h a g D T R : ℕ} {L : ℝ} +variable {P : Board F x y h} (C : Cells P a g D T L) (bin : P.diagram.V → Fin D) + +open scoped Classical in +theorem count_slots (s : Finset C.V) (i : Cell a) (p : (C.stations bin).V → Prop) + [DecidablePred p] + (hp : ∀ v, p v → (C.place bin v).1 ∈ s ∧ (C.place bin v).2 = i) : + Fintype.card {v // p v} ≤ s.card * (D + 1) := by + let f (v : {v // p v}) : s × Option (Fin D) := + (⟨(C.place bin v.1).1, (hp _ v.2).1⟩, v.1.val.2) + have inj : Function.Injective f := by + intro v w he + have ha := congrArg (fun t : s × Option (Fin D) => t.1.val) he + have hz := (hp _ v.2).2.trans (hp _ w.2).2.symm + have hb := congrArg Prod.snd he + exact Subtype.ext (Subtype.ext (Prod.ext (C.site.injective (Prod.ext ha hz)) hb)) + simpa [Fintype.card_prod] using Fintype.card_le_of_injective f inj + +omit [Field F] in +open scoped Classical in +private theorem width_pos {G : Diagram F x y} {v w : G.V} (h : 0 < G.width v w) : + ∃ e, G.source e = v ∧ G.target e = w := by + obtain ⟨e⟩ := Fintype.card_pos_iff.mp h + exact ⟨e.1, e.2⟩ + +open scoped Classical in +private theorem contacts (v : (C.stations bin).V) : + Fintype.card {w // 0 < (C.stations bin).width v w ∨ 0 < (C.stations bin).width w v} ≤ + (g + 1) * (D + 1) := by + let p := C.place bin v + let s := insert p.1 (C.adj p.1) + have hs : s.card ≤ g + 1 := (card_insert_le _ _).trans (Nat.add_le_add_right (C.degree p.1) _) + refine le_trans (C.count_slots bin s p.2 _ ?_) (Nat.mul_le_mul_right _ hs) + intro w hw + rw [show s = insert p.1 (C.adj p.1) from rfl, mem_insert] + rcases hw with hw | hw + · obtain ⟨e, hs, ht⟩ := width_pos hw + have he := C.contact bin e + rw [hs, ht] at he + exact ⟨he.2, he.1⟩ + · obtain ⟨e, hs, ht⟩ := width_pos hw + have he := C.contact bin e + rw [hs, ht] at he + exact ⟨he.2.imp Eq.symm (C.sym _ _), he.1.symm⟩ + +open scoped Classical in +/-- The value specified by `(C.stations bin).pad R`. -/ +abbrev padded (R : ℕ) := (C.stations bin).pad R + +open scoped Classical in +theorem arity_padded (hg : g < D) (hR : R * D ^ 2 ≤ T) (v : (C.stations bin).V) : + ((C.padded bin R).arity v : ℝ) ≤ C.estimate bin v.1 + 4 * T := by + have hm : 2 * R * ((g + 1) * (D + 1)) ≤ 4 * T := calc + _ ≤ 2 * R * (D * (2 * D)) := by gcongr <;> omega + _ = 4 * (R * D ^ 2) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ hR + have hx : (C.padded bin R).arity v ≤ (C.stations bin).arity v + 4 * T := + ((C.stations bin).arity_pad R v).trans (Nat.add_le_add_left + ((Nat.mul_le_mul_left (2 * R) (C.contacts bin v)).trans hm) _) + exact (Nat.cast_le.mpr hx).trans (by push_cast; exact add_le_add_left (C.arity bin v) _) + +open scoped Classical in +private theorem sum_slots (f : C.Slot → ℝ) (hf : ∀ z, 0 ≤ f z) : + (∑ v : (C.stations bin).V, f v.1) ≤ ∑ z, f z := by + let e : (C.stations bin).V ↪ C.Slot := Function.Embedding.subtype _ + change (∑ v : (C.stations bin).V, f (e v)) ≤ _ + rw [← sum_map] + exact sum_le_sum_of_subset_of_nonneg (subset_univ _) fun z _ _ => hf z + +open scoped Classical in +theorem padded_mass (hg : g < D) (hR : R * D ^ 2 ≤ T) (p : C.V × Cell a) : + push (C.place bin) (fun v => ((C.padded bin R).arity v : ℝ)) p ≤ 100 * (D : ℝ) * T := by + let f (z : C.Slot) := if C.site z.1 = p then C.estimate bin z + 4 * T else 0 + have hf z : 0 ≤ f z := by + have := C.estimate_nonneg bin z + unfold f + positivity + refine le_trans ?_ ((C.sum_slots bin f hf).trans ?_) + · apply sum_le_sum + intro v _ + by_cases h : C.site v.1.1 = p + · simpa only [f, place, h, ite_true] using C.arity_padded bin hg hR v + · simp only [f, place, h, ite_false, le_refl] + rw [Fintype.sum_prod_type] + by_cases hp : ∃ c, C.site c = p + · obtain ⟨c, rfl⟩ := hp + rw [Fintype.sum_eq_single c] + swap + · intro b hb + simp [f, hb] + simp only [f, ite_true, sum_add_distrib, sum_const, card_univ, Fintype.card_option, + Fintype.card_fin, + nsmul_eq_mul, Nat.cast_add, Nat.cast_one] + have ht : (T : ℝ) ≤ D * T := le_mul_of_one_le_left (by positivity) + (by exact_mod_cast (show 1 ≤ D by omega)) + nlinarith only [ht, C.cell_estimate bin c, Nat.cast_nonneg (α := ℝ) T] + · have hn c : C.site c ≠ p := fun he => hp ⟨c, he⟩ + simp only [f, hn, ite_false, sum_const_zero] + positivity + +open scoped Classical in +theorem padded_squares (hg : g < D) (hR : R * D ^ 2 ≤ T) + (budget : ∑ z, (C.estimate bin z) ^ 2 ≤ 7 * L * T) : + (∑ v, ((C.padded bin R).arity v : ℝ) ^ 2) ≤ 10000 * L * T := by + let f (z : C.Slot) := 2 * (C.estimate bin z) ^ 2 + 32 * (T : ℝ) ^ 2 + have hf z : 0 ≤ f z := by unfold f; positivity + refine le_trans ?_ ((C.sum_slots bin f hf).trans ?_) + · apply sum_le_sum + intro v _ + have he := C.arity_padded bin hg hR v + have := pow_le_pow_left₀ (Nat.cast_nonneg _) he 2 + unfold f + nlinarith only [this, sq_nonneg (C.estimate bin v.1 - 4 * T)] + have hL : 0 ≤ L := by + have hn : (0 : ℝ) ≤ (Fintype.card C.A : ℝ) * D * T := by positivity + linarith [C.size] + have count : Fintype.card C.Slot ≤ 2 * Fintype.card C.A * D := by + simp only [Slot, Fintype.card_prod, Fintype.card_option, Fintype.card_fin] + rw [mul_comm 2, mul_assoc] + exact Nat.mul_le_mul_left _ (by omega) + have hcount : (Fintype.card C.Slot : ℝ) * T ≤ 34 * L := by + have hx := mul_le_mul_of_nonneg_right (Nat.cast_le.mpr count) (Nat.cast_nonneg (α := ℝ) T) + push_cast at hx + linarith only [hx, C.size] + have ht := mul_le_mul_of_nonneg_right hcount (Nat.cast_nonneg (α := ℝ) T) + simp only [f, sum_add_distrib, ← mul_sum, sum_const, card_univ, nsmul_eq_mul] + nlinarith only [budget, ht, mul_nonneg hL (Nat.cast_nonneg (α := ℝ) T)] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Cells +end + +/- # The grouping step before local concentration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Packing Finset + +variable {F : Type} [Field F] {x y : Wire} {h a g D T R : ℕ} {L θ : ℝ} + +open scoped Classical in +/-- The input of type `Input F x y a D T R g (10000 * L)`, constructed using `C.stations b`. -/ +def Cells.input {P : Board F x y h} (C : Cells P a g D T L) + (hg : g < D) (hR : 0 < R) (hr : R * D ^ 2 ≤ T) + (hL : 0 ≤ L) (ext : ((wd x + wd y : ℕ) : ℝ) * D ≤ L) (b : P.diagram.V → Fin D) + (hb' : ∑ z, (push (C.pack b) P.charge z) ^ 2 ≤ 3 * L * T) : + Input F x y a D T R g (10000 * L) := by + let G := C.stations b + let p := C.place b + let mobile (v : G.V) := v.val.2 ≠ none + have present : (univ.image p).card ≤ Fintype.card C.A := by + refine (card_le_card (t := univ.image C.site) ?_).trans card_image_le + rintro z hz + obtain ⟨v, _, rfl⟩ := mem_image.mp hz + exact mem_image_of_mem _ (mem_univ v.val.1) + have fixed : Fintype.card {v : G.V // ¬mobile v} ≤ Fintype.card C.A := by + apply Fintype.card_le_of_injective (fun v : {v : G.V // ¬mobile v} => v.val.val.1) + intro v w he + exact Subtype.ext (Subtype.ext (Prod.ext he ((not_ne_iff.mp v.2).trans (not_ne_iff.mp + w.2).symm))) + have hsize (m : ℕ) (hm : m ≤ Fintype.card C.A) : (m : ℝ) * D * T ≤ 10000 * L := calc + _ ≤ (Fintype.card C.A : ℝ) * D * T := by gcongr + _ ≤ _ := C.size.trans (by linarith) + exact { + V := C.V + diagram := G.pad R + place := p + adj := C.adj + sym := C.sym + degree := C.degree + edge e := by + obtain ⟨i, h₁, h₂⟩ := G.contact_pad R e + rw [← h₁, ← h₂] + exact C.contact b i + loopless e := by + obtain ⟨i, h₁, h₂⟩ := G.contact_pad R e + rw [← h₁, ← h₂] + exact C.loopless b i + positive v := v.property.trans_le (G.arity_le_pad R v) + width := G.divisible_pad hR + mobile := mobile + ext t := by + have hv : portEnd (G.pad R) t = portEnd G t := by cases t <;> rfl + unfold mobile + rw [hv, C.port b] + exact not_not.mpr rfl + occupied := by exact_mod_cast hsize _ present + immobile := by + have hh := hsize _ fixed + simp only [Fintype.card_eq_nat_card] at hh ⊢ + exact_mod_cast hh + count m := by + have hx := C.count_slots b {m.1} m.2 (fun v => C.place b v = m) + (fun _ he => by rw [he]; simp) + rw [card_singleton, one_mul] at hx + exact hx.trans (by omega) + mass := C.padded_mass b hg hr + squares := C.padded_squares b hg hr (C.estimate_squares b hb' ext) } + +open scoped Classical in +private theorem Cells.prepare {P : Board F x y h} (C : Cells P a g D T L) + (hg : g < D) (hR : 0 < R) (hr : R * D ^ 2 ≤ T) + (sum : ∑ v, P.charge v ≤ L) (sq : ∑ v, P.charge v ^ 2 ≤ L * T) + (ext : ((wd x + wd y : ℕ) : ℝ) * D ≤ L) : + ∃ (Q : Input F x y a D T R g (10000 * L)) (c : F), + (∀ i j, c * Q.diagram.eval i j = P.diagram.eval i j) ∧ + Fintype.card Q.V * 2 ^ a ≤ 2 * P.seats := by + obtain ⟨b, hb⟩ := bins C.cell P.charge D T (by omega) P.charge_nonneg C.mass + have hb' : ∑ z, (push (C.pack b) P.charge z) ^ 2 ≤ 3 * L * T := by + refine hb.trans ?_ + linarith only [sq, mul_le_mul_of_nonneg_left sum (Nat.cast_nonneg (α := ℝ) T)] + let G := C.stations b + let Q := C.input hg hR hr ((sum_nonneg fun v _ => P.charge_nonneg v).trans sum) ext b hb' + obtain ⟨c, hc⟩ := C.evaluation b + refine ⟨Q, c, fun i j => ?_, C.seats⟩ + change c * (G.pad R).eval i j = _ + rw [G.eval_pad] + exact hc i j + +open scoped Classical in +/-- The first grouping step supplies the input to local concentration with +an absolute change in the total budget. -/ +theorem prepare (P : Board F x y h) (hg : 0 < g) (hd : (4 * g) ^ 300 < D) (ht : 0 < T) + (hR : 0 < R) (hr : R * D ^ 2 ≤ T) (ha : a < h) (ok : P.Ready g D T L θ) + (slack : (P.seats : ℝ) * D * T ≤ L * (2 : ℝ) ^ (h - a)) (ext : ((wd x + wd y : ℕ) : ℝ) * D + ≤ L) : + ∃ (Q : Input F x y a D T R ((4 * g) ^ 300) (10000 * L)) (c : F), + (∀ i j, c * Q.diagram.eval i j = P.diagram.eval i j) ∧ + Fintype.card Q.V * 2 ^ a ≤ 2 * P.seats := by + obtain ⟨C⟩ := cells P hg (by omega) ht ha ok slack + exact C.prepare hd hR hr ok.2.1 ok.2.2.1 ext + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Adding the sphere grouping to the downstream round -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Finset + +/-- The fixed local degree bound used by the contraction and concentration stages. -/ +def localDegree := (4 * 5 : ℕ) ^ 300 + +theorem localDegree_large : 8 ≤ localDegree := by + unfold localDegree + generalize he : 300 = n + exact (by decide : 8 ≤ 4 * 5).trans (Nat.le_self_pow (by omega : n ≠ 0) _) + +variable {F : Type} [Field F] {δ : ℝ} + +theorem Design.step (p : Design δ) (T R H n : ℕ) (θ : ℝ) + (hD : localDegree < p.D) (ht : 0 < T) (hR : 0 < R) (hr' : R * p.D ^ 2 ≤ T) + (hH : 2 * H ≤ p.overhead) (hd : p.D ≤ p.overhead) (hs : p.steps = n + 1) (hf : p.floor ≤ θ) + (next : ∀ (x y : Wire) (h a r : ℕ) (L : ℝ) + (Q : Input F x y h p.D T R localDegree (10000 * L)), + a + n * r ≤ h → H ≤ 2 ^ r → (H : ℝ) * T * (Fintype.card Q.V * 2 ^ h : ℕ) ≤ L * (2 : ℝ) ^ r → + Expansion Q.diagram.eval (H * (1 + Nat.clog 2 (T + 1)) * ⌈L / (T : ℝ)⌉₊) + (fun S : Board F x y a => + S.Ready 4 p.D (2 ^ p.growth * T) (L / 2 ^ p.gain) θ ∧ S.seats + ≤ H * (Fintype.card Q.V * 2 ^ h))) : + p.Works F T := by + intro x y h P r a L ok ha hsize ext slack + have hr : 0 < r := by + by_contra! h + have := p.overhead_large + rw [show r = 0 by omega, pow_zero] at hsize + omega + have hL : 0 ≤ L := (by positivity : 0 ≤ ((wd x + wd y : ℕ) : ℝ) * p.D).trans ext + let b := a + n * r + have hb : b + r ≤ h := by + rw [hs, add_mul, one_mul] at ha + unfold b + omega + have budget : (P.seats : ℝ) * p.D * T ≤ L * (2 : ℝ) ^ (h - b) := calc + _ = (p.D : ℝ) * T * P.seats := by ring + _ ≤ (p.overhead : ℝ) * T * P.seats := by gcongr + _ ≤ L * (2 : ℝ) ^ r := slack + _ ≤ _ := by gcongr <;> solve | norm_num | omega + obtain ⟨Q, c, he, hq⟩ := prepare P (by decide : 0 < 5) hD ht hR hr' + (by omega : b < h) ok budget ext + have cap : H * (Fintype.card Q.V * 2 ^ b) ≤ p.overhead * P.seats := calc + _ ≤ H * (2 * P.seats) := Nat.mul_le_mul_left _ hq + _ = 2 * H * P.seats := by ring + _ ≤ _ := Nat.mul_le_mul_right _ hH + have hsl : (H : ℝ) * T * (Fintype.card Q.V * 2 ^ b : ℕ) ≤ L * (2 : ℝ) ^ r := by + have ht' := mul_le_mul_of_nonneg_right (Nat.cast_le.mpr cap) (Nat.cast_nonneg (α := ℝ) T) + simp only [Nat.cast_mul] at ht' ⊢ + linarith + obtain ⟨I, _, Q', coeff, hI, he', out⟩ := next x y b a r L Q le_rfl (by omega) hsl + refine ⟨I, inferInstance, Q', fun i => c * coeff i, hI.trans ?_, ?_, ?_⟩ + · unfold bits + gcongr; omega + · intro x y + simp only [mul_assoc, ← mul_sum, he', he] + · exact fun i => ⟨(out i).1.relax (by decide) le_rfl hf, (out i).2.trans cap⟩ + +/-- One working extension can serve arbitrarily many width scales. -/ +theorem design (tag : Radix.WideTag F) (law : LocalLaw F 10) (hδ : 0 < δ) (hδ' : δ ≤ 1) : + ∃ (p : Design δ) (A T₀ : ℕ) (M : Type) (_ : Field M) (_ : Finite M) (_ : Algebra F M), + ∀ T ≥ T₀, ∀ (K : Type) (_ : Field K) (_ : Fintype K) (_ : Algebra M K), + A * (1 + T) ^ A ≤ Fintype.card K → p.Works K T := by + obtain ⟨D, n, v, b, H, θ, hD, hn, hv, hb, hvb, hθ, A, M, _, _, _, hm⟩ := + downstream tag law hδ hδ' localDegree (by have := localDegree_large; omega) + let p : Design δ := + ⟨D, n + 1, v, b, 2 * H + D, min θ 4, localDegree_large.trans hD.le, by omega, hv, hb, + by have := localDegree_large; omega, lt_min hθ (by norm_num), min_le_right _ _, hvb⟩ + obtain ⟨T₀, hcut⟩ := Filter.eventually_atTop.mp hm + refine ⟨p, A, T₀ + 1, M, inferInstance, inferInstance, inferInstance, ?_⟩ + intro T hT K _ _ _ large + obtain ⟨R, hR, hr, ok⟩ := hcut T (by omega) + exact p.step T R H n θ hD (by omega) hR hr (Nat.le_add_right _ _) (Nat.le_add_left _ _) + rfl (min_le_left _ _) (ok K inferInstance inferInstance inferInstance large) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# Terminal family of a stage + +The weighted sum represents the whole tensor power exactly. This is +the expansion before the realization of its transcript as one network. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Filter + +variable {δ : ℝ} {p : Design δ} {M n T₀ : ℕ} {a b ξ : ℝ} + +/-- The terminal of type `Prop` for the given inputs. -/ +def Levels.Terminal {K : Type} [Field K] {x y : Wire} (v : Levels p M) + (k : Val x → Val y → K) (m : ℕ) : Prop := + Expansion (power k v.batch) (v.selector m) + (fun Q : Board K _ _ v.remaining => + Q.Ready 5 p.D v.finalWidth (v.finalBudget m) p.floor ∧ + Q.seats ≤ p.overhead ^ v.j * v.allocation m) + +theorem Levels.Suits.mass {v : Levels p M} (h : v.Suits n T₀ a b ξ) (m : ℕ) : + v.finalBudget m ≤ 32 * (m : ℝ) * (v.stack + 1) * v.batch * (Nat.clog 2 n : ℝ) ^ (-a) := by + obtain ⟨_, hh, _, _, _, _, _, hb, _⟩ := h + rw [Real.rpow_neg (by positivity), ← div_eq_mul_inv] + unfold Levels.finalBudget + have eq : (v.allocation m : ℝ) * 2 ^ v.stack = 32 * (m : ℝ) * (v.stack + 1) * v.batch := by + unfold Levels.allocation Levels.batch + push_cast + ring + rw [eq] + gcongr + +private theorem exterior_limit {e D m j : ℕ} {H a : ℝ} (hh : 1 < H) + (he : (e : ℝ) ≤ m * H ^ (-(2 * a))) (hsize : (D : ℝ) * (2 : ℝ) ^ j ≤ H ^ (2 * a)) : + e * D * 2 ^ j ≤ m := by + have bound : (e : ℝ) * D * 2 ^ j ≤ m := by + rw [mul_assoc] + refine le_trans (mul_le_mul_of_nonneg_left hsize (Nat.cast_nonneg _)) ?_ + rw [Real.rpow_neg (by positivity), ← div_eq_mul_inv] at he + exact (le_div_iff₀ (by positivity)).mp he + exact_mod_cast bound + +theorem Levels.Suits.run {v : Levels p M} (h : v.Suits n T₀ a b ξ) + {K : Type} [Field K] (works : ∀ T, T₀ ≤ T → T ≤ (Nat.clog 2 n) ^ 4 → p.Works K T) + {x y : Wire} (G : Diagram K x y) (m : ℕ) (hm : G.cost ≤ m) + (arity : ∀ i, (G.arity i : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ b) + (ext : ((wd x + wd y : ℕ) : ℝ) ≤ m * (Nat.clog 2 n : ℝ) ^ (-(2 * a))) : + v.Terminal G.eval m := by + obtain ⟨_, hh, _, _, hw, _, hcut, _, hsize, _, hT, _⟩ := h + apply p.run G v.stack v.j v.remaining v.group m hm _ _ + (exterior_limit hh ext hsize) v.room + · intro i + exact_mod_cast (arity i).trans hw + · intro i hi + apply works + · exact hcut.trans (Nat.le_mul_of_pos_left _ (by positivity)) + · refine le_trans ?_ hT + unfold Design.width Levels.finalWidth + rw [mul_comm, ← pow_add] + gcongr + +/-- Sections 4 and 5 up to the terminal expansion. The size of the +working field and the replication bound are uniform in the input. -/ +theorem terminal {F : Type} [Field F] (tag : Radix.WideTag F) (law : LocalLaw F 10) + (hδ : 0 < δ) (hd : δ ≤ 1) : + ∃ (p : Design δ) (A T₀ : ℕ) (L : Type) (_ : Field L) (_ : Finite L) (_ : Algebra F L), + ∀ (M : ℕ) (a b ξ : ℝ), 0 < a → a ≤ 1 → 0 < b → b ≤ 1 → 0 < ξ → + ∀ᶠ n : ℕ in atTop, ∃ v : Levels p M, v.Suits n T₀ a b ξ ∧ + ∀ (K : Type) (_ : Field K) (_ : Fintype K) (_ : Algebra L K), + A * (1 + (Nat.clog 2 n) ^ 4) ^ A ≤ Fintype.card K → + ∀ (x y : Wire) (k : Val x → Val y → K) (m s u : ℕ) (labels : Set (Table K)), + Wide K u labels x y k s → s ≤ m → (u : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ b → + ((wd x + wd y : ℕ) : ℝ) ≤ m * (Nat.clog 2 n : ℝ) ^ (-(2 * a)) → v.Terminal k m := by + obtain ⟨p, A, T₀, L, _, _, _, ok⟩ := design tag law hδ hd + refine ⟨p, A, T₀, L, inferInstance, inferInstance, inferInstance, ?_⟩ + intro M a b ξ ha ha' hb hb' hx + filter_upwards [p.levels hd T₀ M ha ha' hb hb' hx] with n hn + obtain ⟨v, hv⟩ := hn + refine ⟨v, hv, ?_⟩ + intro K _ _ _ size x y k m s u labels net hm hu he + obtain ⟨G, rfl, hs, hc⟩ := net.diagram + refine hv.run ?_ G m (hc.le.trans hm) (fun i => (Nat.cast_le.mpr (hs i).1).trans hu) he + intro T ht hmax + apply ok T ht K inferInstance inferInstance inferInstance + refine le_trans ?_ size + gcongr + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# Terminal size estimates + +Absorb powers of the logarithm of the height using arbitrary positive +slack. The exponent in the seat estimate does not depend on how many +blocks are reserved at the end. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Filter + +variable {δ : ℝ} {p : Design δ} {M n T₀ : ℕ} {a b ξ : ℝ} + +private def C₀ := 2 / Real.log 2 + 3 + +private theorem c_pos : 0 < C₀ := by unfold C₀; positivity + +private theorem log_bound {t : ℕ} {h : ℝ} (hh : 1 ≤ Real.log h) + (ht : (2 : ℝ) ^ t ≤ h ^ 2) : (t : ℝ) + 2 ≤ C₀ * Real.log h := by + have hb := Real.log_le_log (by positivity) ht + rw [Real.log_pow, Real.log_pow, Nat.cast_ofNat] at hb + have := (le_div_iff₀ (Real.log_pos (by norm_num : (1 : ℝ) < 2))).mpr hb + unfold C₀ + rw [add_mul, div_mul_eq_mul_div] + linarith + +private theorem indices {v : Levels p M} (hv : v.Suits n T₀ a b ξ) + (ha : a ≤ 1) (hb : b ≤ 1) (hh : 2 ≤ (Nat.clog 2 n : ℝ)) (hl : 1 ≤ Real.log (Nat.clog 2 n)) : + let c := C₀ * Real.log (Nat.clog 2 n) + (v.stack : ℝ) + 2 ≤ c ∧ (v.j : ℝ) ≤ c := by + let h : ℝ := Nat.clog 2 n + have hh' : 1 ≤ h := by linarith + obtain ⟨_, _, _, _, _, ht, _, _, hj, _⟩ := hv + constructor + · apply log_bound hl + calc + _ ≤ _ := ht + _ ≤ h * h := mul_le_mul hh (by simpa using Real.rpow_le_rpow_of_exponent_le hh' hb) + (by positivity) (by positivity) + _ = _ := (pow_two h).symm + · have he : (2 : ℝ) ^ v.j ≤ h ^ 2 := calc + _ ≤ (2 : ℝ) ^ (p.gain * v.j) := pow_le_pow_right₀ (by norm_num) (Nat.le_mul_of_pos_left _ + p.gain_pos) + _ ≤ (p.D : ℝ) * (2 : ℝ) ^ (p.gain * v.j) := le_mul_of_one_le_left (by positivity) + (by exact_mod_cast (show 1 ≤ p.D by have := p.large; omega)) + _ ≤ h ^ (2 * a) := hj + _ ≤ h ^ (2 : ℝ) := Real.rpow_le_rpow_of_exponent_le hh' (by linarith) + _ = _ := Real.rpow_two h + exact (le_add_of_nonneg_right (by norm_num)).trans (log_bound hl he) + +/-- The least binary width whose power of two reaches the stated size. -/ +def Levels.Costs (v : Levels p M) (n m : ℕ) (a b τ : ℝ) : Prop := + let h : ℝ := Nat.clog 2 n + let S := (2 : ℝ) ^ v.blocks + (v.selector m : ℝ) ≤ m * S * h ^ τ ∧ + ((p.overhead ^ v.j * v.allocation m : ℕ) : ℝ) ≤ m * S * h ^ (p.groupRate * a + τ) ∧ + v.finalBudget m ≤ m * v.batch * h ^ (-a + τ) ∧ + (p.D : ℝ) * v.finalWidth ≤ h ^ (b + (1 + δ / 3) * a + τ) + +theorem Design.costs (p : Design δ) {τ : ℝ} (hτ : 0 < τ) (ha : a ≤ 1) (hb : b ≤ 1) : + ∀ᶠ n : ℕ in atTop, ∀ (v : Levels p M), v.Suits n T₀ a b ξ → + ∀ m, v.Costs n m a b τ := by + let A : ℝ := 32 * p.overhead * (1 + p.growth) * C₀ ^ 3 + let B : ℝ := 32 * (2 : ℝ) ^ (2 * p.groupRate) * C₀ + have ht := Shaving.tendsto_height + filter_upwards [ht.eventually_ge_atTop 2, + (Real.tendsto_log_atTop.comp ht).eventually_ge_atTop 1, + ht.eventually (Shaving.polylog_le A 3 hτ), + ht.eventually (Shaving.polylog_le B 1 hτ), + ht.eventually (Shaving.polylog_le (32 * C₀) 1 hτ), + ((tendsto_rpow_atTop hτ).comp ht).eventually_ge_atTop ((p.D : ℝ) * (2 : ℝ) ^ (p.growth + 1))] + with n hh hl hA hB hC hD v hv m + let h : ℝ := Nat.clog 2 n + have hpos : 0 < h := by linarith + let S := (2 : ℝ) ^ v.blocks + let c := C₀ * Real.log h + have hc : 0 ≤ c := mul_nonneg c_pos.le (zero_le_one.trans hl) + obtain ⟨hs, hj⟩ := indices hv ha hb hh hl + have hs' : (v.stack : ℝ) + 1 ≤ c := by linarith + have hi : 2 + (v.stack : ℝ) + p.growth * v.j ≤ (1 + p.growth) * c := by + linarith only [hs, mul_le_mul_of_nonneg_left hj (Nat.cast_nonneg (α := ℝ) p.growth)] + have mass := hv.mass m + obtain ⟨_, _, _, _, _, _, _, _, _, hw, _, hr, _⟩ := hv + refine ⟨?_, ?_, ?_, ?_⟩ + · calc + _ ≤ c * (p.overhead * ((1 + p.growth) * c) * (32 * m * c * S)) := by + unfold Levels.selector Levels.allocation + push_cast + gcongr + _ = m * S * (A * (Real.log h) ^ 3) := by unfold A c; ring + _ ≤ m * S * h ^ τ := mul_le_mul_of_nonneg_left hA (by unfold S; positivity) + · have hp : p.overhead ^ v.j ≤ 2 ^ v.group := calc + _ ≤ p.overhead ^ (v.j + 1) := by + apply Nat.pow_le_pow_right _ (by omega) + have := p.overhead_large + omega + _ ≤ _ := (Nat.le_mul_of_pos_right _ (by positivity)).trans v.room + have hp' : (p.overhead : ℝ) ^ v.j ≤ (2 : ℝ) ^ (2 * p.groupRate) * h ^ (p.groupRate * a) := + le_trans (by exact_mod_cast hp) hr + calc + _ ≤ ((2 : ℝ) ^ (2 * p.groupRate) * h ^ (p.groupRate * a)) * (32 * m * c * S) := by + unfold Levels.allocation + push_cast + gcongr + _ = m * S * h ^ (p.groupRate * a) * (B * (Real.log h) ^ 1) := by unfold B c; ring + _ ≤ m * S * h ^ (p.groupRate * a) * h ^ τ := by + apply mul_le_mul_of_nonneg_left hB + unfold S + positivity + _ = _ := by rw [Real.rpow_add hpos, mul_assoc] + · calc + _ ≤ _ := mass + _ ≤ 32 * (m : ℝ) * c * v.batch * h ^ (-a) := by gcongr + _ = (m : ℝ) * v.batch * h ^ (-a) * (32 * C₀ * (Real.log h) ^ 1) := by unfold c; ring + _ ≤ (m : ℝ) * v.batch * h ^ (-a) * h ^ τ := mul_le_mul_of_nonneg_left hC (by positivity) + _ = _ := by rw [Real.rpow_add hpos, mul_assoc] + · calc + _ ≤ (p.D : ℝ) * ((2 : ℝ) ^ (p.growth + 1) * h ^ (b + (1 + δ / 3) * a)) + := mul_le_mul_of_nonneg_left hw (by positivity) + _ ≤ h ^ τ * h ^ (b + (1 + δ / 3) * a) := by + rw [← mul_assoc] + exact mul_le_mul_of_nonneg_right hD (by positivity) + _ = _ := by rw [mul_comm, ← Real.rpow_add hpos] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Downstream.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Downstream.lean new file mode 100644 index 0000000000..5051dde937 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Downstream.lean @@ -0,0 +1,149 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Beat + +/-! # Combining the local and beat selectors -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +open scoped Classical in +/-- A common upper bound on the fixed overheads, independent of the +width scale, working field and input tensor. -/ +def Plan.budget (s : Plan) (A : ℕ) := s.seats + (s.K * s.cover + A * 10000) + s.K * s.D ^ s.C + s.K + +variable {F : Type} [Field F] {x y : Wire} {h a r z : ℕ} + {s : Plan} (hs : s.Fits) (p : Reduction F s.c 3 s.b s.n s.e s.K s.ρ s.loss) + {L : ℝ} {T R g A : ℕ} {P : Input F x y h s.D T R g (10000 * L)} +include hs p + +open scoped Classical in +theorem LocalExpansion.finish (hT : 0 < T) (hz : 0 < z) + (unit : (s.b * z) * s.D ^ s.c ≤ T) (unit' : T ≤ z * s.M) + (ex : LocalExpansion P (s.b * z) s.C s.d 10 A) + (ha : a + s.n * r ≤ h) (hr : s.budget A ≤ 2 ^ r) + (slack : (s.budget A : ℝ) * T * (Fintype.card P.V * 2 ^ h : ℕ) ≤ L * (2 : ℝ) ^ r) : + Expansion P.diagram.eval (s.budget A * (1 + Nat.clog 2 (T + 1))*⌈L / (T : ℝ)⌉₊) + (fun B : Board F x y a => B.Ready 4 s.D (2 ^ s.p * T) (L / (2 : ℝ) ^ s.v) s.floor ∧ + B.seats ≤ s.budget A * (Fintype.card P.V * 2 ^ h)) := by + have hL : 0 ≤ L := by + have : (0 : ℝ) ≤ 10000 * L := (by positivity : (0 : ℝ) + ≤ (univ.image P.place).card * s.D * T) |>.trans P.occupied + linarith + let m := ⌈L / (T : ℝ)⌉₊ + let n := 1 + Nat.clog 2 (T + 1) + have hocc : (univ.image P.place).card ≤ 10000 * m := by + have hD : (1 : ℝ) ≤ s.D := by exact_mod_cast (le_trans (by decide : 1 ≤ 2) (s.two hs)) + have hf := (div_le_iff₀ (Nat.cast_pos.mpr hT : (0 : ℝ) < T)).mp (Nat.le_ceil (L / (T : ℝ))) + have hb : ((univ.image P.place).card : ℝ) * T ≤ 10000 * (m : ℝ) * T := calc + _ ≤ ((univ.image P.place).card : ℝ) * s.D * T := + mul_le_mul_of_nonneg_right (le_mul_of_one_le_right (by positivity) hD) (by positivity) + _ ≤ 10000 * L := P.occupied + _ ≤ _ := by rw [mul_assoc]; exact mul_le_mul_of_nonneg_left hf (by norm_num) + exact_mod_cast le_of_mul_le_mul_right hb (Nat.cast_pos.mpr hT) + have hk : s.K ≤ s.budget A := by unfold Plan.budget; omega + have hh : s.K * s.D ^ s.C ≤ s.budget A := by unfold Plan.budget; omega + have hsl : (s.K * s.D ^ s.C : ℕ) * (T : ℝ) * (Fintype.card P.V * 2 ^ h : ℕ) ≤ L * (2 : ℝ) ^ r + := by + refine le_trans ?_ slack + gcongr + obtain ⟨I, _, Q, c, hi, he, hc⟩ := ex + have second i := (hc i).process hs p hL hT hz rfl unit unit' ha (hk.trans hr) hsl + choose J hJ B b hj he' hB using second + let : ∀ i, Fintype (J i) := hJ + refine ⟨Σ i, J i, inferInstance, fun q => B q.1 q.2, fun q => c q.1 * b q.1 q.2, ?_, ?_, ?_⟩ + · have hi' : Fintype.card I ≤ 2 ^ (A * n * (10000 * m)) := + hi.trans (Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_left _ hocc)) + have hn : 1 ≤ n := by unfold n; omega + have hs' : A * 10000 + s.K * s.cover ≤ s.budget A := by unfold Plan.budget; omega + have hnum : A * n * (10000 * m) + s.K * (s.cover * m) ≤ s.budget A * n * m := calc + _ ≤ A * n * (10000 * m) + s.K * (s.cover * m) * n := + Nat.add_le_add_left (Nat.le_mul_of_pos_right _ hn) _ + _ = (A * 10000 + s.K * s.cover) * n * m := by ring + _ ≤ _ := Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ hs') + rw [Fintype.card_sigma] + calc + _ ≤ ∑ _i : I, 2 ^ (s.K * (s.cover * m)) := sum_le_sum fun i _ => hj i + _ ≤ 2 ^ (A * n * (10000 * m)) * 2 ^ (s.K * (s.cover * m)) := by + simpa only [sum_const, card_univ, Nat.nsmul_eq_mul] using Nat.mul_le_mul_right _ hi' + _ ≤ _ := by rw [← pow_add]; exact Nat.pow_le_pow_right (by decide) hnum + · intro x y + rw [Fintype.sum_sigma, ← he x y] + apply sum_congr rfl + intro i _ + rw [← he' i x y, mul_sum] + exact sum_congr rfl (fun _ _ => mul_assoc _ _ _) + · rintro ⟨i, j⟩ + exact ⟨(hB i j).1, (hB i j).2.trans (Nat.mul_le_mul_right _ (by unfold Plan.budget; omega))⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +section +/- +# A round from local concentration + +The subdivision factor and reset overhead are fixed over the ground +field. Only the input packet width and the necessary working-field +size change as the scale grows. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Filter + +theorem downstream {k : Type} [Field k] (tag : Radix.WideTag k) (law : LocalLaw k 10) + {δ : ℝ} (hδ : 0 < δ) (hd : δ ≤ 1) (g : ℕ) (hg : 0 < g) : + ∃ (D n v p H : ℕ) (θ : ℝ), + g < D ∧ 0 < n ∧ 0 < v ∧ 0 < p ∧ (p : ℝ) ≤ v * (1 + δ / 3) ∧ 0 < θ ∧ + ∃ (A : ℕ) (M : Type) (_ : Field M) (_ : Finite M) (_ : Algebra k M), + ∀ᶠ T : ℕ in atTop, ∃ R : ℕ, 0 < R ∧ R * D ^ 2 ≤ T ∧ + ∀ (K : Type) (_ : Field K) (_ : Fintype K) (_ : Algebra M K), + A * (1 + T) ^ A ≤ Fintype.card K → + ∀ (x y : Wire) (h a r : ℕ) (L : ℝ) (P : Input K x y h D T R g (10000 * L)), + a + n * r ≤ h → H ≤ 2 ^ r → + (H : ℝ) * T * (Fintype.card P.V * 2 ^ h : ℕ) ≤ L * (2 : ℝ) ^ r → + Expansion P.diagram.eval (H * (1 + Nat.clog 2 (T + 1))*⌈L / (T : ℝ)⌉₊) + (fun B : Board K x y a => B.Ready 4 D (2 ^ p * T) (L / (2 : ℝ) ^ v) θ ∧ + B.seats ≤ H * (Fintype.card P.V * 2 ^ h)) := by + obtain ⟨C, hC⟩ := law g hg + obtain ⟨d₀, hex⟩ := eventually_atTop.mp hC + obtain ⟨b, n, e, H, B, hn, he, beat⟩ := beats (.inl tag) (C + 12) (by omega) + have hB := (beat 1 (by decide) k).loss + obtain ⟨d, v, p, hlarge, hv, hp, hvp, hb, hK, hm, hq, ha⟩ := + choose_restart (C + 12) e b H (d₀ + g + C + 12) (↑(10000 * (C + + 1) : ℕ)) B δ (by positivity) hB hδ hd + let s : Plan := ⟨C, d, v, p, b ^ (2 * v), n * (2 * v), e ^ (2 * v), H ^ (2 * v), B⟩ + have grow : d < s.D := Nat.lt_two_pow_self + have fits : s.Fits := ⟨(show C + 12 ≤ s.D by omega), hK, hb, hm, hq, ha⟩ + have red (K : Type) [Field K] [Algebra k K] : + Reduction K s.c 3 s.b s.n s.e s.K s.ρ s.loss := + beat (2 * v) (by omega) K + have pos := (red k).unit + obtain ⟨A, M, _, _, _, go⟩ := hex d (by omega) + have hd' : 0 < s.D := by unfold Plan.D; positivity + have hf : 0 < s.floor := by unfold Plan.floor Plan.M; positivity + refine ⟨s.D, s.n, v, p, s.budget A, s.floor, by omega, Nat.mul_pos hn (by omega), hv, hp, hvp, hf, + A, M, inferInstance, inferInstance, inferInstance, ?_⟩ + filter_upwards [go, eventually_ge_atTop (s.b * s.D ^ s.c)] with T hloc hT + obtain ⟨R, hR, hRT, ex⟩ := hloc + obtain ⟨z, hz, hunit, hunit'⟩ := s.units fits pos T hT + refine ⟨R, hR, hRT, ?_⟩ + intro K fK tK aK hcard x y h a r L P hlen hr slack + let : Algebra k K := ((algebraMap M K).comp (algebraMap k M)).toAlgebra + have ok : (s.b * z) * s.D ^ s.C ≤ T := + (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right hd' s.small)).trans hunit + have hlocal := ex K fK tK aK hcard (s.b * z) (Nat.mul_pos pos hz) ok x y h (10000 * L) P + exact hlocal.finish fits (red K) (lt_of_lt_of_le (by positivity) hT) hz hunit hunit' hlen hr slack + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Install.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Install.lean new file mode 100644 index 0000000000..904bc0c1ed --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Install.lean @@ -0,0 +1,210 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Costs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.FieldStage + +/-! +# Installing the expansion as one network + +An installation consists of an initialization map, a sequence of +weighted transitions and a terminal evaluator. The inequalities +separate the short-control cost per allocated seat from the cost +of handling the terminal payload and the original exterior. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Filter Assembly + +variable {δ : ℝ} {p : Design δ} {M : ℕ} +variable {K : Type} [Field K] {x y : Wire} + +/-- The data for the installation construction, including `u`, `hu`, `labels`, `start`, `stop`. -/ +structure Installation (k : Val x → Val y → K) (d : ℕ) where + /-- The `Installation` field of type `ℕ`. -/ + u : ℕ + hu : 3 ≤ u + /-- The label data of type `Finset (Table K)`. -/ + labels : Finset (Table K) + /-- The initial point of type `Snapshot.{1} K (copies x d) (copies y d)`. -/ + start : Snapshot.{1} K (copies x d) (copies y d) + /-- The `Installation` component of type `Snapshot.{1} K (copies x d) (copies y d)`. -/ + stop : Snapshot.{1} K (copies x d) (copies y d) + /-- The `Installation` component of type `start.state`. -/ + first : start.state + /-- The scalar prefactor of type `K`. -/ + scalar : K + exactPower : (fun x y => scalar * start.eval first x y) = power k d + /-- The `Installation` field of type `ℕ`. -/ + m₁ : ℕ + /-- The `Installation` field of type `ℕ`. -/ + m₂ : ℕ + /-- The `Installation` field of type `ℕ`. -/ + m₃ : ℕ + init : Map K u labels (.wire (.pair (copies x d) (copies y d))) start.port + (fun q => start.encode first q.1 q.2) m₁ + run : Transforms K u labels start stop m₂ + finish : Finishes K u labels stop m₃ + +/-- The quantity computed by `A.m₁ + (A.m₂ + A.m₃) + 4 * (d * wd y) + 1`. -/ +def Installation.cost {k : Val x → Val y → K} {d : ℕ} (A : Installation k d) := + A.m₁ + (A.m₂ + A.m₃) + 4 * (d * wd y) + 1 + +theorem Installation.labeled {k : Val x → Val y → K} {d : ℕ} (A : Installation k d) + {B : ℕ} (h : A.labels.card ≤ B) : + ∃ s ≤ A.cost, Labeled (power k d) B s A.u := by + obtain ⟨s, hs, hw⟩ := Finishes.start A.hu A.first A.init (A.run.finish A.finish) + have sc : Wide K A.u A.labels .unit .unit (fun _ _ => A.scalar) 1 := + .table _ _ _ (Nat.zero_le _) (.inl (by decide)) + have net := ((hw.par sc).pre (.unit' _)).post (.unit' _) + rw [wd_copies] at hs + refine ⟨s + 1, Nat.add_le_add_right hs _, A.labels, h, ?_⟩ + rw [← A.exactPower] + simpa only [mul_comm] using net + +variable (v : Levels p M) + +/-- The quantity computed by `(p.overhead ^ v.j * v.allocation m : ℕ) * h ^ (c * a) + +v.finalBudget m + (v.batch * e : ℕ)`. -/ +def Levels.work (m e : ℕ) (h a : ℝ) (c : ℕ) : ℝ := + (p.overhead ^ v.j * v.allocation m : ℕ) * h ^ (c * a) + v.finalBudget m + (v.batch * e : ℕ) + +/-- Cost and arity required of the explicit implementation. The +logarithmic slack must also pay for reading the input and closing +the output of the sequence of transformations. -/ +def Levels.Installed (n m c : ℕ) (a : ℝ) (k : Val x → Val y → K) : Prop := + let h : ℝ := Nat.clog 2 n + let τ := a * δ / 6 + ∃ I : Installation k v.batch, I.labels.card ≤ Shaving.dictionary n ∧ + (I.cost : ℝ) ≤ h ^ τ * v.work m (wd x + wd y) h a c ∧ + (I.u : ℝ) ≤ h ^ τ * (p.D * (v.finalWidth : ℝ)) + +private theorem costs {n m c T₀ : ℕ} {a b ξ : ℝ} (ha : 0 < a) (hd : 0 < δ) + (small : (p.groupRate + c + 1 : ℕ) * a ≤ b) + (hv : v.Suits n T₀ a b ξ) (hcost : v.Costs n m a b (a * δ / 6)) + (large : 3 ≤ (Nat.clog 2 n : ℝ) ^ (a * δ / 6)) + {e : ℕ} (he : (e : ℝ) ≤ m * (Nat.clog 2 n : ℝ) ^ (-(2 * a))) : + let h : ℝ := Nat.clog 2 n + h ^ (a * δ / 6) * v.work m e h a c ≤ m * (v.batch : ℝ) * h ^ (-((1 - δ) * a)) ∧ + h ^ (a * δ / 6) * (p.D * (v.finalWidth : ℝ)) ≤ h ^ (b + (1 + δ) * a) := by + let h : ℝ := Nat.clog 2 n + let τ := a * δ / 6 + have hτ : 0 < τ := by unfold τ; positivity + have hh : 1 ≤ h := hv.2.1.le + have hh' : 0 < h := zero_lt_one.trans_le hh + let X := (m : ℝ) * (v.batch : ℝ) * h ^ (-a + τ) + have hx : 0 ≤ X := by unfold X; positivity + have hS : (2 : ℝ) ^ v.blocks * h ^ b ≤ v.batch := by + unfold Levels.batch + push_cast + rw [mul_comm] + exact mul_le_mul_of_nonneg_right hv.2.2.2.2.1 (by positivity) + obtain ⟨_, hctrl, hterm, hwidth⟩ := hcost + have control : (p.overhead ^ v.j * v.allocation m : ℕ) * h ^ (c * a) ≤ X := calc + _ ≤ (m : ℝ) * (2 : ℝ) ^ v.blocks * h ^ (p.groupRate * a + τ) * h ^ (c * a) := by gcongr + _ = (m : ℝ) * (2 : ℝ) ^ v.blocks * h ^ (p.groupRate * a + τ + c * a) + := by rw [Real.rpow_add hh' _ (c * a)]; ring + _ ≤ (m : ℝ) * (2 : ℝ) ^ v.blocks * h ^ (b + (-a + τ)) := by + apply mul_le_mul_of_nonneg_left _ (by positivity) + apply Real.rpow_le_rpow_of_exponent_le hh + push_cast at small; linarith + _ = m * ((2 : ℝ) ^ v.blocks * h ^ b) * h ^ (-a + τ) := by rw [Real.rpow_add hh']; ring + _ ≤ X := by unfold X; gcongr + have ext : (v.batch * e : ℕ) ≤ X := calc + _ = (v.batch : ℝ) * e := Nat.cast_mul _ _ + _ ≤ v.batch * ((m : ℝ) * h ^ (-(2 * a))) := by gcongr + _ = (m : ℝ) * v.batch * h ^ (-(2 * a)) := by ring + _ ≤ X := by unfold X; gcongr; linarith + have work : v.work m e h a c ≤ 3 * X := by + unfold Levels.work + change v.finalBudget m ≤ X at hterm + linarith only [control, hterm, ext] + constructor + · calc + _ ≤ h ^ τ * (h ^ τ * X) := mul_le_mul_of_nonneg_left + (work.trans (mul_le_mul_of_nonneg_right large hx)) (by positivity) + _ = (m : ℝ) * v.batch * h ^ (τ + (τ + (-a + τ))) := by + rw [Real.rpow_add hh' τ, Real.rpow_add hh' τ]; unfold X; ring + _ ≤ _ := by gcongr; dsimp [τ]; nlinarith + · calc + _ ≤ h ^ τ * h ^ (b + (1 + δ / 3) * a + τ) := mul_le_mul_of_nonneg_left hwidth (by positivity) + _ = h ^ (τ + (b + (1 + δ / 3) * a + τ)) := (Real.rpow_add hh' _ _).symm + _ ≤ _ := Real.rpow_le_rpow_of_exponent_le hh (by unfold τ; nlinarith) + +/-- One stage can accept any input dictionary for which installations +are supplied. Its output uses the fixed smaller dictionary bound. -/ +theorem Levels.stage_of_installations {n c T₀ S : ℕ} {a b ξ : ℝ} + (ha : 0 < a) (hδ : 0 < δ) (small : (p.groupRate + c + 1 : ℕ) * a ≤ b) + (hv : v.Suits n T₀ a b ξ) (hc : ∀ m, v.Costs n m a b (a * δ / 6)) + (hg : 3 ≤ (Nat.clog 2 n : ℝ) ^ (a * δ / 6)) + (h : ∀ (x y : Wire) (G : Diagram K x y) (m u : ℕ) (labels : Finset (Table K)), + n ≤ m → (m : ℝ) ≤ (n : ℝ) ^ (11 / 10 : ℝ) → G.cost ≤ m → + G.Admits u labels → labels.card ≤ S → (u : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ b → + ((wd x + wd y : ℕ) : ℝ) ≤ m * (Nat.clog 2 n : ℝ) ^ (-(2 * a)) → v.Installed n m c a G.eval) : + ArityStep K n S (Shaving.dictionary n) b δ a ξ := by + intro x y k s u m hnet hu hs hl hm he + obtain ⟨labels, hlabels, hnet⟩ := hnet + obtain ⟨G, rfl, had, hsc⟩ := hnet.diagram + obtain ⟨I, hfew, hsize, hwidth⟩ := h x y G m u labels hl hm (hsc.le.trans hs) had hlabels hu he + obtain ⟨t, ht, hnet⟩ := I.labeled hfew + obtain ⟨hc, hw⟩ := costs v ha hδ small hv (hc m) hg he + have hpos : 1 ≤ v.batch := by + unfold Levels.batch + exact Nat.one_le_iff_ne_zero.mpr (by positivity) + have hbatch : (v.batch : ℝ) ≤ (n : ℝ) ^ ξ := by + rcases hv with ⟨_, _, _, _, _, _, _, _, _, _, _, _, h⟩ + exact h + exact ⟨v.batch, t, I.u, hpos, hbatch, hnet, (Nat.cast_le.mpr ht).trans (hsize.trans hc), + hwidth.trans hw⟩ + +/-- The installation contract fixes its field and scales before choosing the dictionary index. +The level bound may depend on that index. -/ +def InstallableFor {Index : Type} (F : Type) [Field F] (dictionary : Index → ℕ → ℕ) : Prop := + ∀ δ β : ℝ, 0 < δ → δ ≤ 1 / 10 → 0 < β → β ≤ 1 / 2 → + ∃ (p : Design δ) (A T₀ c : ℕ) (L : Type) (_ : Field L) (_ : Finite L) (_ : Algebra F L), + ∀ a b ξ : ℝ, 0 < a → (p.groupRate + c + 1 : ℕ) * a < β → β ≤ b → b ≤ 1 / 2 → 0 < ξ → + ∀ index, ∃ M : ℕ, ∀ᶠ n : ℕ in atTop, ∃ v : Levels p M, v.Suits n T₀ a b ξ ∧ + ∀ (K : Type) [Field K] [Fintype K] [Algebra L K] [Algebra F K] [IsScalarTower F L K], + let h := Nat.clog 2 n + A * (1 + h ^ 4) ^ A ≤ Fintype.card K → Fintype.card K ≤ h ^ (5 * A + 2) → + ∀ (x y : Wire) (G : Diagram K x y) (m u : ℕ) (labels : Finset (Table K)), + n ≤ m → (m : ℝ) ≤ (n : ℝ) ^ (11 / 10 : ℝ) → G.cost ≤ m → + G.Admits u labels → labels.card ≤ dictionary index n → (u : ℝ) ≤ (h : ℝ) ^ b → + ((wd x + wd y : ℕ) : ℝ) ≤ m * (h : ℝ) ^ (-(2 * a)) → v.Installed n m c a G.eval + +/-- Installation with the fixed label bound used by arity reduction. -/ +def Installable (F : Type) [Field F] : Prop := + InstallableFor F (fun _ : Unit => Shaving.dictionary) + +theorem Installable.reduction {F : Type} [Field F] (install : Installable F) : ArityReduction F + := by + apply Shaving.UniformStage.reduction + intro δ β hδ hδ' hβ hβ' + obtain ⟨p, A, T₀, c, L, _, _, _, go⟩ := install δ β hδ hδ' hβ hβ' + let q := p.groupRate + c + 1 + have hq : 1 ≤ (q : ℝ) := by unfold q; push_cast; linarith + refine ⟨β / q, A, L, inferInstance, inferInstance, inferInstance, by positivity, ?_⟩ + intro a b ξ ha ha' hb hb' hξ + have small : (q : ℝ) * a < β := by rwa [lt_div_iff₀ (by positivity), mul_comm] at ha' + have ha1 : a ≤ 1 := by nlinarith + have hτ : 0 < a * δ / 6 := by positivity + obtain ⟨M, hm⟩ := go a b ξ ha small hb hb' hξ () + have hc := p.costs (M := M) (T₀ := T₀) (ξ := ξ) (b := b) hτ ha1 (by linarith) + have grow := (tendsto_rpow_atTop hτ).comp Shaving.tendsto_height + filter_upwards [hm, hc, grow.eventually_ge_atTop 3] with n hn hc hg K _ _ _ _ _ + dsimp only + intro hlo hhi x y k s u m hnet hu hs hl hm he + obtain ⟨v, hv, h⟩ := hn + exact v.stage_of_installations ha hδ (small.le.trans hb) hv (hc v hv) hg (h K hlo hhi) + x y k s u m hnet hu hs hl hm he + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Installation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Installation.lean new file mode 100644 index 0000000000..a59f057915 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Installation.lean @@ -0,0 +1,35 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Construct +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Price.Run +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Shared + +/-! # Compression of tensor powers over finite fields -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem Rounds.installable (F : Type) [Field F] [Finite F] + (h : Prices.SharedPrice (AlgebraicClosure F)) : Rounds.Installable F := by + apply Rounds.installable_of_controller F h + intro K _ _ s hs p l b + exact Rounds.SphereScale.controlled K s hs p l b + +theorem compresses_of_shared_price {F : Type} [Field F] [Finite F] + (h : Prices.SharedPrice (AlgebraicClosure F)) : Compresses F := by + obtain ⟨q, hq, hq₂, sort⟩ := Routing.sorting_of_shared_price h + exact compresses_of_stages hq hq₂ sort (Rounds.installable F h).reduction + +theorem compression_of_square_saving {F : Type} [Field F] [Finite F] + (h : omega F < 9 / 4) : Compression (Realizes F) := + (compresses_of_shared_price (shared_of_saving h)).lists + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Log.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Log.lean new file mode 100644 index 0000000000..8bf00b14ea --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Log.lean @@ -0,0 +1,493 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Sweep + +/-! +# Sizes that can be absorbed by the grouping parameter + +When the gain exponent is positive the number of rounds tends to +infinity. The stack depth and reserved block height grow at most +quadratically in this number, uniformly over suitable levels. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Filter + +variable {δ : ℝ} {p : Design δ} {M n T₀ : ℕ} {a b ξ : ℝ} (v : Levels p M) + +/-- The quantity computed by `2 ^ (c * (v.j + 1))`. -/ +def box (c : ℕ) := 2 ^ (c * (v.j + 1)) +/-- The quantity computed by `100 + v.stack + p.growth * v.j + v.blocks + v.height`. -/ +def span := 100 + v.stack + p.growth * v.j + v.blocks + v.height + +theorem box_mono {s t : ℕ} (h : s ≤ t) : v.box s ≤ v.box t := + Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ h) + +theorem box_add (s t : ℕ) : v.box (s + t) = v.box s * v.box t := by + simp only [box, add_mul, pow_add] + +theorem box_mul (s t : ℕ) : v.box (s * t) = v.box s ^ t := by + unfold box + rw [mul_right_comm, pow_mul] + +theorem le_box (s : ℕ) : s ≤ v.box s := + Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_right (by decide) (Nat.le_mul_of_pos_right _ (by + omega))) + +theorem group_eq : 2 ^ v.group = v.box p.groupRate := rfl + +variable {v} + +theorem Suits.box_le (hs : v.Suits n T₀ a b ξ) (c : ℕ) (ha : 4 * a * c ≤ 1) : + v.box c ≤ Nat.clog 2 n := by + obtain ⟨hj, hh, _, _, _, _, _, _, ht, _⟩ := hs + let h : ℝ := Nat.clog 2 n + have hD : (1 : ℝ) ≤ p.D := by exact_mod_cast (show 1 ≤ p.D by have := p.large; omega) + have hx : (2 : ℝ) ^ v.j ≤ h ^ (2 * a) := + (pow_le_pow_right₀ (by norm_num) (Nat.le_mul_of_pos_left _ p.gain_pos)).trans + ((le_mul_of_one_le_left (by positivity) hD).trans ht) + have he : c * (v.j + 1) ≤ v.j * (2 * c) := by + calc + _ ≤ c * (2 * v.j) := Nat.mul_le_mul_left _ (by omega) + _ = _ := by ring + have ht' : (2 : ℝ) ^ (c * (v.j + 1)) ≤ h := calc + _ ≤ (2 ^ v.j : ℝ) ^ (2 * c) := by rw [← pow_mul]; exact pow_le_pow_right₀ (by norm_num) he + _ ≤ (h ^ (2 * a)) ^ (2 * c) := pow_le_pow_left₀ (by positivity) hx _ + _ = h ^ (4 * a * c) := by + rw [← Real.rpow_natCast, ← Real.rpow_mul (by linarith : 0 ≤ h)] + push_cast + ring_nf + _ ≤ h := (Real.rpow_le_rpow_of_exponent_le hh.le ha).trans_eq (Real.rpow_one _) + unfold h at ht' + unfold box + exact_mod_cast ht' + +theorem eventually_rounds (p : Design δ) (M : ℕ) (ha : 0 < a) (j : ℕ) : + ∀ᶠ n : ℕ in atTop, ∀ (v : Levels p M) (T₀ : ℕ) (b ξ : ℝ), v.Suits n T₀ a b ξ → j ≤ v.j := by + filter_upwards [((tendsto_rpow_atTop ha).comp Shaving.tendsto_height).eventually_ge_atTop + ((2 : ℝ) ^ (p.gain * j))] with n hn v T₀ b ξ hs + obtain ⟨_, _, _, _, _, _, _, hx, _⟩ := hs + have he := (pow_le_pow_iff_right₀ (by norm_num : (1 : ℝ) < 2)).mp (hn.trans hx) + exact Nat.le_of_mul_le_mul_left he p.gain_pos + +private theorem Suits.linear (hs : v.Suits n T₀ a b ξ) (hb : b ≤ 1) + {k : ℕ} (hak : 1 ≤ a * k) : v.stack ≤ 1 + p.gain * v.j * k ∧ v.height ≤ 1 + p.gain * v.j * k + := by + obtain ⟨_, hh, _, he, _, ht, _, hg, _⟩ := hs + let h : ℝ := Nat.clog 2 n + have hx : h ≤ (2 : ℝ) ^ (p.gain * v.j * k) := calc + h ≤ h ^ (a * k) := by + simpa only [Real.rpow_one] using Real.rpow_le_rpow_of_exponent_le hh.le hak + _ = (h ^ a) ^ k := by rw [Real.rpow_mul (by linarith : 0 ≤ h), Real.rpow_natCast] + _ ≤ ((2 : ℝ) ^ (p.gain * v.j)) ^ k := pow_le_pow_left₀ (by positivity) hg _ + _ = _ := (pow_mul ..).symm + have hp : 2 * h ≤ (2 : ℝ) ^ (1 + p.gain * v.j * k) := by rw [pow_add, pow_one]; gcongr + have hq : h ^ b ≤ h := (Real.rpow_le_rpow_of_exponent_le hh.le hb).trans_eq (Real.rpow_one _) + have ht' := ht.trans ((mul_le_mul_of_nonneg_left hq (by norm_num)).trans hp) + exact ⟨(pow_le_pow_iff_right₀ (by norm_num)).mp ht', + (pow_le_pow_iff_right₀ (by norm_num)).mp (he.trans hp)⟩ + +theorem Suits.span_square (hs : v.Suits n T₀ a b ξ) (hb : b ≤ 1) + {k : ℕ} (hak : 1 ≤ a * k) : + v.span ≤ (100 + 2 * (1 + p.gain * k) + p.growth + M * (1 + p.gain * k) + + 2 * p.steps * p.groupRate) * v.j ^ 2 := by + let c := 1 + p.gain * k + have hv := hs.1 + have h₂ : v.j ≤ v.j ^ 2 := Nat.le_self_pow (by decide) _ + have h₁ : 1 ≤ v.j ^ 2 := hv.trans_le h₂ + obtain ⟨ht, hh⟩ := hs.linear hb hak + have he : 1 + p.gain * v.j * k ≤ c * v.j ^ 2 := by + rw [show p.gain * v.j * k = p.gain * k * v.j by + ring, show c = 1 + p.gain * k from rfl, add_mul, one_mul] + exact Nat.add_le_add h₁ (Nat.mul_le_mul_left _ h₂) + have hg : p.steps * v.j * v.group ≤ p.steps * p.groupRate * 2 * v.j ^ 2 := by + unfold group + calc + _ ≤ p.steps * v.j * (p.groupRate * (2 * v.j)) := by gcongr; omega + _ = _ := by ring + unfold span blocks remaining + calc + _ ≤ 100 * v.j ^ 2 + c * v.j ^ 2 + p.growth * v.j ^ 2 + (M * (c * v.j ^ 2) + + p.steps * p.groupRate * 2 * v.j ^ 2) + c * v.j ^ 2 := by + have hstack := ht.trans he + have hheight := hh.trans he + have hcst : 100 ≤ 100 * v.j ^ 2 := Nat.le_mul_of_pos_right _ h₁ + gcongr + _ = _ := by unfold c; ring + +theorem eventually_span (p : Design δ) (M : ℕ) (ha : 0 < a) (A : ℕ) : + ∀ᶠ n : ℕ in atTop, ∀ (v : Levels p M) (T₀ : ℕ) (b ξ : ℝ), b ≤ 1 → + v.Suits n T₀ a b ξ → A * v.span ≤ 2 ^ v.j := by + obtain ⟨k, hk⟩ := exists_nat_ge (1 / a) + have hak : 1 ≤ a * k := by rw [mul_comm]; exact (div_le_iff₀ ha).mp hk + let c := 1 + p.gain * k + let f := A * (100 + 2 * c + p.growth + M * c + 2 * p.steps * p.groupRate) + have he : ∀ᶠ j : ℕ in atTop, f * j ^ 2 ≤ 2 ^ j := by + have hx := (isLittleO_pow_const_const_pow_of_one_lt (R := ℝ) 2 + (by norm_num : (1 : ℝ) < 2)).const_mul_left (f : ℝ) + filter_upwards [hx.eventuallyLE] with j hj + have he : (f : ℝ) * (j : ℝ) ^ 2 ≤ (2 : ℝ) ^ j := (le_abs_self _).trans (by simpa using hj) + exact_mod_cast he + obtain ⟨j, hj⟩ := eventually_atTop.mp he + filter_upwards [eventually_rounds p M ha j] with n hn v T₀ b ξ hb hs + refine le_trans ?_ (hj _ (hn v T₀ b ξ hs)) + unfold f + rw [mul_assoc] + exact Nat.mul_le_mul_left A (hs.span_square hb hak) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Grouping slack and the address space at intermediate rounds -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Filter + +variable {δ : ℝ} {p : Design δ} {M : ℕ} (v : Levels p M) + +/-- The quantity computed by `p.width (2 ^ v.stack) i`. -/ +def width (i : ℕ) := p.width (2 ^ v.stack) i +/-- The quantity computed by `p.budget (8 * (v.allocation m : ℝ) * 2 ^ v.stack) i`. -/ +def budget (m i : ℕ) := p.budget (8 * (v.allocation m : ℝ) * 2 ^ v.stack) i + +theorem width_eq (i : ℕ) : v.width i = 2 ^ (v.stack + p.growth * i) := by + simp only [width, Design.width, pow_add, mul_comm] + +theorem budget_zero (m : ℕ) : v.budget m 0 = 256 * (m : ℝ) * v.batch * (v.stack + 1) := by + simp only [budget, Design.budget, allocation, batch, mul_zero, pow_zero, div_one, Nat.cast_mul, + Nat.cast_pow, + Nat.cast_ofNat, Nat.cast_one, Nat.cast_add] + ring + +theorem budget_final (m : ℕ) : v.budget m v.j = 8 * v.finalBudget m := by + unfold budget Design.budget finalBudget + ring + +theorem rounds_le_group : v.j ≤ v.group := by + have := p.overhead_large + exact (Nat.le_succ _).trans (Nat.le_mul_of_pos_left _ (by unfold Design.groupRate; omega)) + +theorem overhead_le_group : p.overhead ≤ v.group := + (Nat.le_add_right ..).trans (Nat.le_mul_of_pos_right _ (by omega)) + +/-- The data for the fits construction, including `positive`, `span`, `group`, `small`, +`height`. -/ +structure Fits (n A C : ℕ) : Prop where + positive : 0 < v.j + span : (A + 4) * v.span ≤ 2 ^ v.j + group : 2 ^ v.group ≤ Nat.clog 2 n + small : v.box C ≤ Nat.clog 2 n + height : Nat.clog 2 n ≤ 2 ^ v.height + +theorem eventually_fits (p : Design δ) (M A C : ℕ) {a : ℝ} (ha : 0 < a) + (hsize : 4 * a * (p.groupRate + C : ℕ) ≤ 1) : + ∀ᶠ n : ℕ in atTop, ∀ (v : Levels p M) (T₀ : ℕ) (b ξ : ℝ), b ≤ 1 → + v.Suits n T₀ a b ξ → v.Fits n A C := by + filter_upwards [eventually_span p M ha (A + 4)] with n hn v T₀ b ξ hb hv + have h := hv.box_le _ hsize + refine ⟨hv.1, hn v T₀ b ξ hb hv, (v.box_mono (Nat.le_add_right ..)).trans h, + (v.box_mono (Nat.le_add_left ..)).trans h, ?_⟩ + exact_mod_cast hv.2.2.1 + +variable {v} {n A C m i : ℕ} (h : v.Fits n A C) + +include h in +theorem Fits.four_span : 4 * v.span ≤ 2 ^ v.group := + ((Nat.mul_le_mul_right _ (Nat.le_add_left 4 A)).trans h.span).trans + (Nat.pow_le_pow_right (by decide) v.rounds_le_group) + +include h in +theorem Fits.alphabet {t : ℕ} (ht : t ≤ (Nat.clog 2 n) ^ A) : Nat.clog 2 t ≤ 2 ^ v.group := by + have hx : Nat.clog 2 t ≤ v.height * A := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_mul] + exact ht.trans (Nat.pow_le_pow_left h.height _) + have hh : v.height ≤ v.span := Nat.le_add_left .. + rw [mul_comm] at hx + exact ((hx.trans (Nat.mul_le_mul (Nat.le_add_right ..) hh)).trans h.span).trans + (Nat.pow_le_pow_right (by decide) v.rounds_le_group) + +include h in +theorem Fits.one_le_budget (hm : n ≤ m) (hi : i ≤ v.j) : 1 ≤ v.budget m i := by + have hk : p.gain * i ≤ v.group := + Nat.mul_le_mul (by unfold Design.groupRate; omega) (hi.trans (Nat.le_succ _)) + have hn : Nat.clog 2 n ≤ n := (Nat.clog_le_iff_le_pow (by decide)).mpr Nat.lt_two_pow_self.le + have hb : m ≤ v.allocation m := by + unfold allocation + exact ((Nat.le_mul_of_pos_left _ (by decide : 0 < 32)).trans + (Nat.le_mul_of_pos_right _ (by omega))).trans (Nat.le_mul_of_pos_right _ (by positivity)) + have hx : 2 ^ (p.gain * i) ≤ v.allocation m := + (((Nat.pow_le_pow_right (by decide) hk).trans h.group).trans hn).trans (hm.trans hb) + rw [budget, Design.budget, le_div_iff₀ (by positivity), one_mul] + exact le_trans (by exact_mod_cast hx : (2 : ℝ) ^ (p.gain * i) ≤ v.allocation m) + ((le_mul_of_one_le_left (by positivity) (by norm_num)).trans + (le_mul_of_one_le_right (by positivity) (one_le_pow₀ (by norm_num)))) + +theorem slack (hi : i ≤ v.j) {N : ℕ} (hN : N ≤ p.overhead ^ (i + 1) * v.allocation m) : + (N : ℝ) * (v.width i : ℝ) ≤ v.budget m i * (2 : ℝ) ^ v.group := by + have hh : p.overhead ^ (i + 1) * 2 ^ ((p.gain + p.growth) * i) ≤ 2 ^ v.group := by + refine le_trans ?_ v.room + have := p.overhead_large + gcongr + have he : N * v.width i * 2 ^ (p.gain * i) ≤ 8 * v.allocation m * 2 ^ v.stack * 2 ^ v.group + := calc + _ ≤ (p.overhead ^ (i + 1) * v.allocation m) * v.width i * 2 ^ (p.gain * i) := by gcongr + _ = v.allocation m * 2 ^ v.stack * (p.overhead ^ (i + 1) * 2 ^ ((p.gain + p.growth) * i)) := by + rw [width_eq, add_mul, pow_add 2, pow_add 2] + ring + _ ≤ _ := by gcongr; exact Nat.le_mul_of_pos_left _ (by decide) + rw [budget, Design.budget, div_mul_eq_mul_div, le_div_iff₀ (by positivity)] + exact_mod_cast he + +include h in +theorem Fits.address (hm : m ≤ n ^ 2) (hi : i ≤ v.j) {w : ℕ} + (hw : 2 ^ w ≤ p.overhead ^ (i + 1) * v.allocation m) : w ≤ 4 * Nat.clog 2 n := by + let l := Nat.clog 2 n + have hm' : m ≤ 2 ^ (l * 2) := by + rw [pow_mul] + exact hm.trans (Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) n) _) + have ho : p.overhead ^ (i + 1) ≤ 2 ^ v.group := by + refine le_trans ?_ ((Nat.le_mul_of_pos_right _ (by positivity)).trans v.room) + exact Nat.pow_le_pow_right (by have := p.overhead_large; omega) (Nat.succ_le_succ hi) + have hv : 5 + v.stack + v.blocks ≤ l := by + have hx : 4 * (100 + v.stack + p.growth * v.j + v.blocks + v.height) ≤ l + := h.four_span.trans h.group + omega + have hr : v.group ≤ l := Nat.lt_two_pow_self.le.trans h.group + have he : 2 ^ w ≤ (2 : ℕ) ^ (4 * l) := calc + _ ≤ _ := hw + _ ≤ 2 ^ v.group * (2 ^ 5 * 2 ^ (l * 2) * 2 ^ v.stack * 2 ^ v.blocks) := + Nat.mul_le_mul ho (Nat.mul_le_mul_right _ + (Nat.mul_le_mul (Nat.mul_le_mul_left _ hm') Nat.lt_two_pow_self)) + _ ≤ _ := by + simp only [← pow_add] + exact Nat.pow_le_pow_right (by decide) (by omega) + exact (Nat.pow_le_pow_iff_right (by decide)).mp he + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +section +/- # Uniform ranges of the intermediate widths and the input size -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Suits + +variable {δ a b ξ : ℝ} {p : Design δ} {M n m T₀ : ℕ} {v : Levels p M} + (ok : v.Suits n T₀ a b ξ) +include ok + +theorem width_window {i : ℕ} (hi : i ≤ v.j) : + T₀ ≤ v.width i ∧ v.width i ≤ (Nat.clog 2 n) ^ 4 := by + obtain ⟨_, _, _, _, _, _, lo, _, _, _, up, _⟩ := ok + rw [v.width_eq] + refine ⟨lo.trans (Nat.pow_le_pow_right (by decide) (Nat.le_add_right ..)), le_trans ?_ up⟩ + exact Nat.pow_le_pow_right (by decide) (Nat.add_le_add_left (Nat.mul_le_mul_left _ hi) _) + +theorem input_size (nm : n ≤ m) (upper : (m : ℝ) ≤ (n : ℝ) ^ (11 / 10 : ℝ)) : 0 < m ∧ m ≤ n ^ 2 + := by + have hn : 0 < n := by + have hw := ok.2.1 + by_contra h + rw [show n = 0 by omega] at hw + norm_num at hw + have le : (m : ℝ) ≤ (n : ℝ) ^ (2 : ℕ) := calc + _ ≤ _ := upper + _ ≤ (n : ℝ) ^ (2 : ℝ) := Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast hn) (by norm_num) + _ = _ := Real.rpow_two _ + exact ⟨hn.trans_le nm, by exact_mod_cast le⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Suits +end + +/- # Bounds on fixed-degree control expressions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +variable {δ : ℝ} {p : Design δ} {R n T₀ : ℕ} {a b ξ : ℝ} {v : Levels p R} + +theorem Levels.box_le_group_power {E q : ℕ} (he : E ≤ q * p.groupRate) : + v.box E ≤ 2 ^ (q * v.group) := by + unfold Levels.box Levels.group + rw [← mul_assoc] + exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ he) + +theorem Levels.Suits.group_power_le_width (ok : v.Suits n T₀ a b ξ) + {q : ℕ} (hq : (p.groupRate * q : ℕ) * a ≤ b) : + (2 : ℝ) ^ (q * v.group) ≤ (2 : ℝ) ^ (2 * p.groupRate * q) * (v.finalWidth : ℝ) := by + let h : ℝ := Nat.clog 2 n + have hh : 1 ≤ h := ok.2.1.le + have hpos : 0 < h := zero_lt_one.trans_le hh + obtain ⟨_, _, _, _, ht, _, _, _, _, _, _, hg, _⟩ := ok + have hp : h ^ ((p.groupRate * q : ℕ) * a) ≤ v.finalWidth := calc + _ ≤ h ^ b := Real.rpow_le_rpow_of_exponent_le hh hq + _ ≤ (2 : ℝ) ^ v.stack := ht + _ ≤ (v.finalWidth : ℝ) := by + unfold Levels.finalWidth + push_cast + exact pow_le_pow_right₀ (by norm_num) (Nat.le_add_right ..) + calc + _ = ((2 : ℝ) ^ v.group) ^ q := by rw [mul_comm q, pow_mul] + _ ≤ ((2 : ℝ) ^ (2 * p.groupRate) * h ^ (p.groupRate * a)) ^ q + := pow_le_pow_left₀ (by positivity) hg _ + _ = (2 : ℝ) ^ (2 * p.groupRate * q) * h ^ ((p.groupRate * q : ℕ) * a) := by + rw [mul_pow, ← pow_mul, ← Real.rpow_mul_natCast hpos.le, Nat.cast_mul] + rw [mul_right_comm (p.groupRate : ℝ)] + _ ≤ _ := mul_le_mul_of_nonneg_left hp (by positivity) + +/-- If a controller uses a fixed power of a record length plus the +price of wide routing, choose the sorting tolerance before taking +this power. -/ +theorem power_with_routing {x W h τ σ : ℝ} {e : ℕ} + (hx : 1 ≤ x) (hW : 0 ≤ W) (hh : 1 ≤ h) (hτ : 0 ≤ τ) + (hprice : W ≤ h ^ τ) (hσ : (e : ℝ) * τ ≤ σ) : + (x + W) ^ e ≤ (2 * x) ^ e * h ^ σ := by + have hpos : 0 < h := zero_lt_one.trans_le hh + have hpow : 1 ≤ h ^ τ := Real.one_le_rpow hh hτ + have xx : x + W ≤ 2 * x * h ^ τ := by + have h₁ : x ≤ x * h ^ τ := le_mul_of_one_le_right (zero_le_one.trans hx) hpow + have h₂ : W ≤ x * h ^ τ := hprice.trans (le_mul_of_one_le_left (by positivity) hx) + linarith only [h₁, h₂] + calc + _ ≤ (2 * x * h ^ τ) ^ e := pow_le_pow_left₀ (by linarith) xx _ + _ = (2 * x) ^ e * h ^ (τ * (e : ℝ)) := by rw [mul_pow, Real.rpow_mul_natCast hpos.le] + _ ≤ _ := by + apply mul_le_mul_of_nonneg_left _ (by positivity) + exact Real.rpow_le_rpow_of_exponent_le hh (by simpa only [mul_comm] using hσ) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Uniform assembly with one common arity ceiling -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels + +open Assembly Filter + +variable {δ : ℝ} {p : Design δ} {M T₀ : ℕ} {a b ξ : ℝ} + +theorem installed_trace (ha : 0 < a) (ha' : a ≤ 1) (hδ : 0 < δ) + (C : ℝ) (hC : 1 ≤ C) (r q B s : ℕ) : + ∀ᶠ n : ℕ in atTop, ∀ (v : Levels p M) (m : ℕ), v.Suits n T₀ a b ξ → + ∀ (F : Type) [Field F] (x y : Wire) (k : Val x → Val y → F), + let h : ℝ := Nat.clog 2 n + let W := C * (Real.log h) ^ r * h ^ (a * δ / 12) + let budget := W * v.expense h m (wd x + wd y) q + let cap := W * (p.D * (v.finalWidth : ℝ)) + let menu := B * (Nat.clog 2 n) ^ s + ∀ (P : Layer F (copies x v.batch) (copies y v.batch)) + (good : ℕ → Layer F (copies x v.batch) (copies y v.batch) → Prop) + (i : P.State) (z : F), + good 0 P → + (fun a b => z * (P.graph i).eval a b) = power k v.batch → + ((140 * (P.snapshot.port.width + v.batch * (wd x + wd y)) + 1 : ℕ) : ℝ) ≤ budget → + (∀ j < v.j, ∀ Q, good j Q → + ∃ (R : Layer F (copies x v.batch) (copies y v.batch)) (L : Finset (Table F)) (u t : ℕ), + good (j + 1) R ∧ L.card ≤ menu ∧ (u : ℝ) ≤ cap ∧ (t : ℝ) ≤ budget ∧ + Transforms F u L Q.snapshot R.snapshot t) → + (∀ Q, good v.j Q → + ∃ (L : Finset (Table F)) (u t : ℕ), L.card ≤ menu ∧ (u : ℝ) ≤ cap ∧ (t : ℝ) ≤ budget ∧ + Finishes F u L Q.snapshot t) → + v.Installed n m (p.groupRate * q) a k := by + have hl := (Real.tendsto_log_atTop.comp Shaving.tendsto_height).eventually_ge_atTop 1 + filter_upwards [hl, Levels.installed_of_round_budget (p:=p) (R:=M) (T₀:=T₀) (b:=b) + (ξ:=ξ) ha ha' hδ C r q B s] with n hlog bound v m ok F _ x y k + dsimp only + intro P good i z h₀ exactPower initial next final + let h : ℝ := Nat.clog 2 n + let W := C * (Real.log h) ^ r * h ^ (a * δ / 12) + let budget := W * v.expense h m (wd x + wd y) q + let cap := W * (p.D * (v.finalWidth : ℝ)) + let menu := B * (Nat.clog 2 n) ^ s + have hh : 1 ≤ h := ok.2.1.le + have hW : 1 ≤ W := one_le_mul_of_one_le_of_one_le + (one_le_mul_of_one_le_of_one_le hC (one_le_pow₀ hlog)) (Real.one_le_rpow hh (by positivity)) + have hD : (3 : ℝ) ≤ p.D := by exact_mod_cast (show 3 ≤ p.D by have := p.large; omega) + have hwidth : (1 : ℝ) ≤ v.finalWidth := by + have positive : 1 ≤ v.finalWidth := by + unfold Levels.finalWidth + exact Nat.one_le_iff_ne_zero.mpr (by positivity) + exact_mod_cast positive + have hcap : (3 : ℝ) ≤ cap := hD.trans + ((le_mul_of_one_le_right (by positivity) hwidth).trans (le_mul_of_one_le_left (by positivity) + hW)) + have hpos : 0 ≤ cap := (by norm_num : (0 : ℝ) ≤ 3).trans hcap + have hbudget : 0 ≤ budget := by unfold budget W Levels.expense Levels.finalBudget; positivity + have next' j (hj : j < v.j) Q (hq₀ : good j Q) : + ∃ (R : Layer F (copies x v.batch) (copies y v.batch)) (L : Finset (Table F)) (u t : ℕ), + good (j + 1) R ∧ L.card ≤ menu ∧ u ≤ ⌊cap⌋₊ ∧ (t : ℝ) ≤ budget ∧ + Transforms F u L Q.snapshot R.snapshot t := by + obtain ⟨R, L, u, t, hR, hL, hu, ht, hnet⟩ := next j hj Q hq₀ + exact ⟨R, L, u, t, hR, hL, Nat.le_floor hu, ht, hnet⟩ + have final' Q (hq₀ : good v.j Q) : + ∃ (L : Finset (Table F)) (u t : ℕ), L.card ≤ menu ∧ u ≤ ⌊cap⌋₊ ∧ (t : ℝ) ≤ budget ∧ + Finishes F u L Q.snapshot t := by + obtain ⟨L, u, t, hL, hu, ht, hnet⟩ := final Q hq₀ + exact ⟨L, u, t, hL, Nat.le_floor hu, ht, hnet⟩ + obtain ⟨I, hu, hL, hs⟩ := P.install_with_bounds good h₀ ok.1 + (Nat.le_floor (by simpa using hcap)) i z exactPower budget hbudget initial next' final' + refine bound v m ok F x y k I hL ?_ ?_ + · simpa only [abs_of_nonneg (zero_le_one.trans hC)] using hs + · have hc : (I.u : ℝ) ≤ cap := by rw [hu]; exact Nat.floor_le hpos + have hsum : (1 : ℝ) ≤ (v.j : ℝ) + 2 := by + have := Nat.cast_nonneg (α := ℝ) v.j + linarith + have hle : (I.u : ℝ) ≤ (v.j + 2) * cap := + hc.trans (le_mul_of_one_le_left hpos hsum) + simpa only [abs_of_nonneg (zero_le_one.trans hC)] using hle + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # A polylogarithmic bound on payload-index lengths -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Filter + +variable {δ : ℝ} + +theorem eventual_span_log (p : Design δ) (M extra : ℕ) {a : ℝ} (ha : 0 < a) (ha' : a ≤ 1) : + ∃ J : ℝ, 0 ≤ J ∧ ∀ᶠ n : ℕ in atTop, ∀ (v : Levels p M) (T₀ : ℕ) (b ξ : ℝ), + b ≤ 1 → v.Suits n T₀ a b ξ → + ((v.span + extra : ℕ) : ℝ) ≤ J * (Real.log (Nat.clog 2 n)) ^ 2 := by + obtain ⟨k, hk⟩ := exists_nat_ge (1 / a) + have hak : 1 ≤ a * k := by rw [mul_comm]; exact (div_le_iff₀ ha).mp hk + let c : ℕ := 100 + 2 * (1 + p.gain * k) + p.growth + M * (1 + p.gain * k) + + 2 * p.steps * p.groupRate + let d : ℝ := 2 / Real.log 2 + let J : ℝ := (c : ℝ) * d ^ 2 + extra + have hJ : 0 ≤ J := by unfold J; positivity + have hl := (Real.tendsto_log_atTop.comp Shaving.tendsto_height).eventually_ge_atTop 1 + refine ⟨J, hJ, ?_⟩ + filter_upwards [hl] with n hn v T₀ b ξ hb ok + let h : ℝ := Nat.clog 2 n + change 1 ≤ Real.log h at hn + have hj : (v.j : ℝ) ≤ d * Real.log h := ok.rounds_log ha' + have ha1 : 1 ≤ (Real.log h) ^ 2 := one_le_pow₀ hn + have hs : (v.span : ℝ) ≤ (c : ℝ) * (v.j : ℝ) ^ 2 := by + have := ok.span_square hb hak + change v.span ≤ c * v.j ^ 2 at this + exact_mod_cast this + push_cast + calc + _ ≤ (c : ℝ) * (v.j : ℝ) ^ 2 + extra := add_le_add hs le_rfl + _ ≤ (c : ℝ) * (d * Real.log h) ^ 2 + (extra : ℝ) * (Real.log h) ^ 2 := + add_le_add (mul_le_mul_of_nonneg_left (pow_le_pow_left₀ (by positivity) hj _) (by positivity)) + (le_mul_of_one_le_right (by positivity) ha1) + _ = _ := by unfold J; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Majorants.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Majorants.lean new file mode 100644 index 0000000000..559f693ab8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Majorants.lean @@ -0,0 +1,839 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.ContractRates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Payload.Price + +/-! # Common majorants for the three scales of terminal work -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly Contraction + +variable {δ : ℝ} {p : Design δ} {M : ℕ} (v : Levels p M) (s : Plan) + {F : Type} [Field F] {x y : Wire} (W : Prices F) + +/-- The quantity computed by `1000 + W.W + 2 * (v.span + s.d + s.p)`. -/ +def bitPrice := 1000 + W.W + 2 * (v.span + s.d + s.p) +/-- The quantity computed by `v.bitPrice s W + 8 + v.box (E + E)`. -/ +def recordPrice (E : ℕ) := v.bitPrice s W + 8 + v.box (E + E) +/-- The quantity computed by `v.recordPrice s W E + 4 * Nat.clog 2 n + W.w + W.w ^ W.power`. -/ +def hostPrice (n E : ℕ) := v.recordPrice s W E + 4 * Nat.clog 2 n + W.w + W.w ^ W.power +/-- The quantity computed by `3 + 32 * s.D * v.finalWidth + 64 * v.recordPrice s W E`. -/ +def endCap (E : ℕ) := 3 + 32 * s.D * v.finalWidth + 64 * v.recordPrice s W E + +/-- The end cost used in the `Levels` construction. -/ +def endCost (n m E e J : ℕ) := + ⌊((p.overhead ^ v.j * v.allocation m : ℕ) : ℝ) * + ((v.hostPrice s W n E : ℝ) ^ J / (2 : ℝ) ^ v.remaining + (v.recordPrice s W E : ℝ) ^ J) + + ((e : ℝ) + 256 * s.D / s.floor * v.finalBudget m) * (v.bitPrice s W : ℝ) ^ J⌋₊ + +/-- Computes the bill by the application `Assembly.Terminal.Rates.Size.mk F Q.template.scheme W +(v.capacity s m Q) (v.depth s) Q.volume Q.height`. -/ +abbrev bill (m : ℕ) (Q : Layer F x y) := + Assembly.Terminal.Rates.Size.mk F Q.template.scheme W (v.capacity s m Q) (v.depth s) Q.volume + Q.height + +theorem prices (n E : ℕ) : 1000 ≤ v.bitPrice s W ∧ v.bitPrice s W ≤ v.recordPrice s W E ∧ + v.recordPrice s W E ≤ v.hostPrice s W n E := by + unfold hostPrice recordPrice bitPrice + have := Nat.zero_le (W.w ^ W.power) + omega + +namespace Current +variable {v s} {Q : Layer F x y} {n m E : ℕ} (h : v.Current s n m v.j E Q) + (upper : Q.template.scheme.m ≤ 4 * Nat.clog 2 n) + +local notation "B" => v.bitPrice s W +local notation "T" => v.recordPrice s W E +local notation "H" => v.hostPrice s W n E +local notation "bill₀" => v.bill s W m Q +local notation "Y" => (2 ^ Q.template.scheme.m) +local notation "Z" => (2 ^ (Q.template.scheme.m + Q.template.scheme.h)) +local notation "X" => (v.capacity s m Q - 2 ^ Q.template.scheme.m + (wd x + wd y)) +include h + +theorem bill_bits : (bill₀).B ≤ B := by + have hh := h.terminal_height + change 1000 + W.W + Assembly.Terminal.height Q.template.scheme (v.depth s) + Q.height ≤ _ + unfold bitPrice + omega + +theorem bill_records : (bill₀).T ≤ T := by + have hu := h.bill_bits W + have hℓ := h.bits le_rfl + change (bill₀).B + 2 ^ Q.template.scheme.d + Q.template.scheme.ℓ ≤ B + 8 + v.box (E + E) + rw [h.degree] + omega + +include upper in +theorem bill_hosts : (bill₀).M ≤ H := by + have ht := h.bill_records W + change (bill₀).T + Q.template.scheme.m + W.w + W.w ^ W.power ≤ _ + unfold hostPrice + omega + +theorem bill_spans : (bill₀).spans ≤ Z * 32 := by + change Y * 2 ^ (Q.template.scheme.h + Q.template.scheme.k + Q.template.scheme.e) ≤ _ + rw [h.ready.1, add_zero, pow_add, ← mul_assoc, ← pow_add] + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide) h.ports) + +theorem bill_volume : (bill₀).volume = 2 * Y + X := by + change v.capacity s m Q + Q.volume = _ + have := h.volume + have hh : Y ≤ v.capacity s m Q := Nat.le_add_right .. + omega + +theorem bill_arity : 2 ^ (Q.template.scheme.e + v.depth s) + 64 * (bill₀).T ≤ v.endCap s W E := by + have hb := h.bill_records W + have he := Nat.mul_le_mul_right (s.D * v.finalWidth) (show 2 ^ Q.template.scheme.e ≤ 32 from + Nat.pow_le_pow_right (by decide) h.ports) + rw [pow_add, v.depth_eq, endCap, mul_assoc] + omega + +include upper in +theorem readCost : 4 * Q.snapshot.port.width ≤ Y * (100 * H) + Z * (4 * T) + X * (8 * B) := by + have hp := v.prices s W n E + have hH : Q.template.scheme.m + 2 ≤ H := by + unfold hostPrice + have := Nat.zero_le (W.w ^ W.power) + omega + have hT : Q.template.scheme.ℓ + Q.template.count ≤ T := (h.bits le_rfl).trans (Nat.le_add_left ..) + have hB : Q.height + 1 ≤ B := by have := h.height; unfold bitPrice; omega + have hX : Q.volume ≤ Y + X := by have := h.volume; omega + have hfmt : Q.template.format.width ≤ Y * (8 * H + 2 + 2 ^ Q.template.scheme.h * T) := by + rw [Template.width, h.degree] + exact Nat.mul_le_mul_left _ (Nat.add_le_add (Nat.add_le_add_right (Nat.mul_le_mul_left _ hH) 2) + (Nat.mul_le_mul_left _ hT)) + calc + 4 * Q.snapshot.port.width ≤ 4 * (Y * (8 * H + 2 + 2 ^ Q.template.scheme.h * T) + B * (2 * (Y + + X))) := + Nat.mul_le_mul_left _ (Q.width.trans (Nat.add_le_add hfmt (Nat.mul_le_mul hB + (Nat.mul_le_mul_left _ hX)))) + _ = Y * (32 * H + 8 + 8 * B) + Z * (4 * T) + X * (8 * B) := by rw [pow_add]; ring + _ ≤ _ := by gcongr; omega + +end Current +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Paying for the final evaluator from the common seat and charge budgets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +open Assembly Contraction + +private theorem absorb (x j : ℕ) (hx : 1000 ≤ x) : 100 * x + 32 * x ^ j ≤ x ^ (j + 2) := by + have h := Nat.le_self_pow (show j + 1 ≠ 0 by omega) x + have g : x ^ j ≤ x ^ (j + 1) := Nat.pow_le_pow_right (show 0 < x by omega) (Nat.le_succ j) + calc + _ ≤ x ^ (j + 1) * 132 := by omega + _ ≤ x ^ (j + 1) * x := Nat.mul_le_mul_left _ (by omega) + _ = _ := (pow_succ ..).symm + +private theorem combine (Y Z X H T B j : ℕ) (hb : 1000 ≤ B) (ht : B ≤ T) (hh : T ≤ H) : + (Y * (100 * H) + Z * (4 * T) + X * (8 * B)) + (Y * H ^ j + Z * 32 * T ^ j + (2 * Y + + X) * B ^ j) ≤ + Y * H ^ (j + 2) + Z * T ^ (j + 2) + X * B ^ (j + 2) := by + have hz := Nat.pow_le_pow_left (ht.trans hh) j + have h₁ := absorb H j (hb.trans (ht.trans hh)) + have h₂ := absorb T j (hb.trans ht) + have h₃ := absorb B j hb + calc + _ = Y * (100 * H + H ^ j + 2 * B ^ j) + Z * (4 * T + 32 * T ^ j) + X * (8 * B + B ^ j) + := by ring + _ ≤ _ := by gcongr <;> omega + +variable {δ : ℝ} {p : Design δ} {M : ℕ} {v : Levels p M} {s : Plan} + {F : Type} [Field F] {x y : Wire} {Q : Layer F x y} {n m E : ℕ} + (h : v.Current s n m v.j E Q) (W : Prices F) (upper : Q.template.scheme.m ≤ 4 * Nat.clog 2 n) + +local notation "B" => v.bitPrice s W +local notation "T" => v.recordPrice s W E +local notation "H" => v.hostPrice s W n E +local notation "bill₀" => v.bill s W m Q +local notation "Y" => (2 ^ Q.template.scheme.m) +local notation "Z" => (2 ^ (Q.template.scheme.m + Q.template.scheme.h)) +local notation "X" => (v.capacity s m Q - 2 ^ Q.template.scheme.m + (wd x + wd y)) +include h upper + +private theorem terminal_bill (j : ℕ) : + 4 * Q.snapshot.port.width + (bill₀).bound j ≤ Y * H ^ (j + 2) + Z * T ^ (j + 2) + X * B ^ (j + + 2) := by + have ht := h.bill_records W + have hb := h.bill_bits W + have hm := h.bill_hosts W upper + have hz := h.bill_spans W + have hs : (bill₀).bound j ≤ Y * H ^ j + Z * 32 * T ^ j + (2 * Y + X) * B ^ j := by + rw [Terminal.Rates.Size.bound, h.bill_volume W] + exact Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hm j)) + (Nat.mul_le_mul hz (Nat.pow_le_pow_left ht j))) (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left + hb j)) + obtain ⟨h₁, h₂, h₃⟩ := v.prices s W n E + exact (Nat.add_le_add (h.readCost W upper) hs).trans (combine _ _ _ _ _ _ _ h₁ h₂ h₃) + +theorem endCost_le (j : ℕ) : + 4 * Q.snapshot.port.width + (bill₀).bound j ≤ v.endCost s W n m E (wd x + wd y) (j + 2) := by + refine (h.terminal_bill W upper j).trans (Nat.le_floor ?_) + let N := p.overhead ^ v.j * v.allocation m + have h₁ : (Y : ℝ) ≤ N / (2 : ℝ) ^ v.remaining := v.host_budget (h.terminal rfl).2.1.ge h.seats + have h₂ : (Z : ℝ) ≤ N := by exact_mod_cast h.seats + have h₃ : ((X : ℕ) : ℝ) ≤ ((wd x + wd y : ℕ) : ℝ) + 256 * s.D / s.floor * v.finalBudget m := by + have hc := h.capacity_le + have hu : Y ≤ v.capacity s m Q := Nat.le_add_right .. + rw [Nat.cast_add, Nat.cast_sub hu, Nat.cast_pow, Nat.cast_ofNat] + linarith + calc + _ = (Y : ℝ) * (H : ℝ) ^ (j + 2) + (Z : ℝ) * (T : ℝ) ^ (j + 2) + ((X : ℕ) : ℝ) * (B : ℝ) ^ (j + + 2) := by push_cast; rfl + _ ≤ (N / (2 : ℝ) ^ v.remaining) * (H : ℝ) ^ (j + 2) + N * (T : ℝ) ^ (j + 2) + + (((wd x + wd y : ℕ) : ℝ) + 256 * s.D / s.floor * v.finalBudget m) * (B : ℝ) ^ (j + 2) + := by gcongr + _ = _ := by unfold N; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +end + +/- +# Paying for the terminal network + +Long addresses are charged once per host. The short records are +charged once per block, and the bit price applies only to live +terminal volume and the original exterior. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Contraction + +variable {δ : ℝ} {p : Design δ} {M n E B C J q T₀ R : ℕ} + {a b ξ τ σ J₀ : ℝ} {F : Type} [Field F] + +/-- The value specified by `(1000 + 64 * (2 : ℝ) ^ (2 * p.groupRate * q) + 32 * s.D + 256 * s.D +/ s.floor) * (2048 * (J₀ + 1)) ^ (J + 1)`. -/ +def terminalFactor (p : Design δ) (s : Plan) (q J : ℕ) (J₀ : ℝ) := + (1000 + 64 * (2 : ℝ) ^ (2 * p.groupRate * q) + 32 * s.D + 256 * s.D / s.floor) * (2048 * (J₀ + + 1)) ^ (J + 1) + +theorem terminalFactor_one (p : Design δ) (s : Plan) (q J : ℕ) (hJ : 0 ≤ J₀) : + 1 ≤ terminalFactor p s q J J₀ := by + have hs : 0 ≤ 256 * (s.D : ℝ) / s.floor := by unfold Plan.floor; positivity + unfold terminalFactor + refine one_le_mul_of_one_le_of_one_le ?_ (one_le_pow₀ (by linarith)) + linarith [show 0 ≤ (2 : ℝ) ^ (2 * p.groupRate * q) by positivity, Nat.cast_nonneg (α:=ℝ) s.D] + +theorem paid_finish (v : Levels p M) (s : Plan) (W : Prices F) (m e : ℕ) + (ready : v.Suits n T₀ a b ξ) (fit : v.Fits n B C) + (exponent : (E + E) * (J + 1) ≤ C) + (hh : 2 ≤ (Nat.clog 2 n : ℝ)) (hl : 1 ≤ Real.log (Nat.clog 2 n)) + (hτ : 0 ≤ τ) (hτσ : ((J + 1 : ℕ) : ℝ) * τ ≤ σ) + (hw : (W.W : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ τ) + (wide : W.w + W.w ^ W.power ≤ (Nat.clog 2 n) ^ R) + (reserve : (7 + max R 1) * (J + 1) ≤ M) (enough : C ≤ q * p.groupRate) + (hq : (p.groupRate * q : ℕ) * a ≤ b) (hJ : 0 ≤ J₀) + (logSpan : ((v.span + s.d + s.p + 1 : ℕ) : ℝ) ≤ J₀ * (Real.log (Nat.clog 2 n)) ^ 2) : + let h : ℝ := Nat.clog 2 n + let K := terminalFactor p s q J J₀ * (Real.log h) ^ (2 * (J + 1)) * h ^ σ + (v.endCap s W E : ℝ) ≤ K * (p.D * (v.finalWidth : ℝ)) ∧ + (v.endCost s W n m E (v.batch * e) J : ℝ) ≤ K * v.expense h m e q := by + intro h K + let Z := 2048 * (J₀ + 1) * (Real.log h) ^ 2 * h ^ τ + let V := (2048 * (J₀ + 1)) ^ (J + 1) * (Real.log h) ^ (2 * (J + 1)) * h ^ σ + let X : ℝ := v.box (E + E) + let D := (2 : ℝ) ^ (2 * p.groupRate * q) + let c : ℝ := 256 * s.D / s.floor + have hc : 0 ≤ c := by unfold c Plan.floor; positivity + have hd : 0 ≤ D := by unfold D; positivity + have hK : K = (1000 + 64 * D + 32 * s.D + c) * V := by unfold K terminalFactor D c V; ring + have hh' : 1 ≤ h := by linarith + have hy : 1 ≤ h ^ τ := Real.one_le_rpow hh' hτ + have hz₀ : 1 ≤ (J₀ + 1) * (Real.log h) ^ 2 := + one_le_mul_of_one_le_of_one_le (by linarith) (one_le_pow₀ hl) + have hz₁ : 1 ≤ Z := by + unfold Z + exact one_le_mul_of_one_le_of_one_le (by linarith only [hz₀]) hy + have hv : Z ^ (J + 1) ≤ V := by + unfold Z V + rw [mul_pow, mul_pow, ← pow_mul, ← Real.rpow_mul_natCast (by positivity), mul_comm τ] + exact mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hh' hτσ) (by positivity) + have hz : Z ^ J ≤ V := (pow_le_pow_right₀ hz₁ (Nat.le_succ J)).trans hv + have large : Z ≤ V := by simpa using (pow_le_pow_right₀ hz₁ (Nat.le_add_left 1 J)).trans hv + have vv := hz₁.trans large + have small : V ≤ K := by + rw [hK] + exact le_mul_of_one_le_left (by linarith) (by linarith [Nat.cast_nonneg (α:=ℝ) s.D]) + have hp : 1 ≤ X := by unfold X box; push_cast; exact one_le_pow₀ (by norm_num) + have budget : X ^ (J + 1) ≤ (v.box C : ℝ) := by + unfold X + rw [← Nat.cast_pow, ← box_mul] + exact_mod_cast v.box_mono exponent + have cap : X ≤ (v.box C : ℝ) := by + simpa using (pow_le_pow_right₀ hp (Nat.le_add_left 1 J)).trans budget + have hs : (v.box C : ℝ) ≤ (2 : ℝ) ^ (q * v.group) := by exact_mod_cast v.box_le_group_power enough + have hX : X ^ J ≤ (2 : ℝ) ^ (q * v.group) := (pow_le_pow_right₀ hp (Nat.le_succ J)).trans + (budget.trans hs) + have bit : (v.bitPrice s W : ℝ) + 9 ≤ Z := by + let U := (J₀ + 1) * (Real.log h) ^ 2 + have hi : ((v.span + s.d + s.p : ℕ) : ℝ) ≤ U := by + refine (Nat.cast_le.mpr (Nat.le_succ _)).trans (logSpan.trans ?_) + exact mul_le_mul_of_nonneg_right (by linarith) (by positivity) + have hv : 1 ≤ U := hz₀ + have h₁ := le_mul_of_one_le_right (by linarith : 0 ≤ U) hy + have h₂ := le_mul_of_one_le_left (by positivity : 0 ≤ h ^ τ) hv + have he : Z = 2048 * (U * h ^ τ) := by unfold Z U; ring + rw [he, bitPrice, Nat.cast_add, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, Nat.cast_ofNat] + change (W.W : ℝ) ≤ h ^ τ at hw + linarith only [hi, hv, hw, h₁, h₂] + have recd : (v.recordPrice s W E : ℝ) ≤ Z * X := by + rw [recordPrice, Nat.cast_add, Nat.cast_add, Nat.cast_ofNat] + change (v.bitPrice s W : ℝ) + 8 + X ≤ _ + nlinarith only [bit, mul_nonneg (sub_nonneg.mpr hz₁) (sub_nonneg.mpr hp)] + have hlive : 1 ≤ (v.finalWidth : ℝ) := by + unfold finalWidth + push_cast + exact one_le_pow₀ (by norm_num) + constructor + · have hD : 1 ≤ (p.D : ℝ) := by exact_mod_cast (show 1 ≤ p.D by have := p.large; omega) + have hR : (v.recordPrice s W E : ℝ) ≤ V * (D * v.finalWidth) := + recd.trans (mul_le_mul large (cap.trans (hs.trans (ready.group_power_le_width hq))) (by + linarith) (by linarith)) + calc + _ = 3 + 32 * (s.D : ℝ) * v.finalWidth + 64 * v.recordPrice s W E + := by unfold endCap; push_cast; rfl + _ ≤ 3 * (V * v.finalWidth) + 32 * (s.D : ℝ) * (V * v.finalWidth) + + 64 * (V * (D * v.finalWidth)) := by + have h₁ := one_le_mul_of_one_le_of_one_le vv hlive + have h₂ := le_mul_of_one_le_left (by positivity : (0 : ℝ) ≤ v.finalWidth) vv + gcongr; linarith + _ = (3 + 64 * D + 32 * s.D) * V * v.finalWidth := by ring + _ ≤ K * v.finalWidth := by + rw [hK] + exact mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right (by linarith only [hc]) (by + positivity)) + (by positivity) + _ ≤ _ := mul_le_mul_of_nonneg_left (le_mul_of_one_le_left (by positivity) hD) (by linarith) + · have hhost : (v.hostPrice s W n E : ℝ) ≤ Z * h ^ (7 + max R 1) := by + let r := max R 1 + have hx : X ≤ h := cap.trans (Nat.cast_le.mpr fit.small) + have hhR : h ≤ h ^ r := by simpa only [pow_one] using pow_le_pow_right₀ hh' (le_max_right R 1) + have hu : (W.w : ℝ) + (W.w : ℝ) ^ W.power ≤ h ^ R := by unfold h; exact_mod_cast wide + have hu' := hu.trans (pow_le_pow_right₀ hh' (le_max_left R 1)) + have ht : (v.recordPrice s W E : ℝ) ≤ Z * h ^ r := + recd.trans (mul_le_mul_of_nonneg_left (hx.trans hhR) (by linarith)) + have hp' := le_mul_of_one_le_left (by positivity : 0 ≤ h ^ r) hz₁ + have hwide : (6 : ℝ) ≤ h ^ 7 := le_trans (by norm_num : (6 : ℝ) ≤ 2 ^ 7) + (pow_le_pow_left₀ (by norm_num) hh _) + calc + _ ≤ 6 * (Z * h ^ r) := by + unfold hostPrice; push_cast + change (v.recordPrice s W E : ℝ) + 4 * h + W.w + (W.w : ℝ) ^ W.power ≤ _ + linarith only [ht, hu', hhR, hp'] + _ ≤ h ^ 7 * (Z * h ^ r) := mul_le_mul_of_nonneg_right hwide (by positivity) + _ = _ := by rw [pow_add]; ring + have hosts : (v.hostPrice s W n E : ℝ) ^ J ≤ V * h ^ M := calc + _ ≤ (Z * h ^ (7 + max R 1)) ^ J := pow_le_pow_left₀ (by positivity) hhost _ + _ ≤ _ := by + rw [mul_pow, ← pow_mul] + exact mul_le_mul hz (pow_le_pow_right₀ hh' ((Nat.mul_le_mul_left _ (Nat.le_succ J)).trans + reserve)) + (by positivity) (by positivity) + have recs : (v.recordPrice s W E : ℝ) ^ J ≤ V * (2 : ℝ) ^ (q * v.group) := + (pow_le_pow_left₀ (by positivity) recd _).trans (by rw [mul_pow]; gcongr) + have bits : (v.bitPrice s W : ℝ) ^ J ≤ V := (pow_le_pow_left₀ (by positivity) (by linarith only + [bit]) J).trans hz + have hfin : 0 ≤ v.finalBudget m := by unfold finalBudget; positivity + have hcv : c * V ≤ K := by rw [hK]; gcongr; linarith [Nat.cast_nonneg (α:=ℝ) s.D] + let N : ℝ := (p.overhead ^ v.j * v.allocation m : ℕ) + let U : ℝ := (v.batch * e : ℕ) + have hN : 0 ≤ N := Nat.cast_nonneg _ + have hU : 0 ≤ U := Nat.cast_nonneg _ + unfold endCost + refine (Nat.floor_le (by positivity)).trans ?_ + calc + _ ≤ N * ((V * h ^ M) / (2 : ℝ) ^ v.remaining + V * (2 : ℝ) ^ (q * v.group)) + (U + + c * v.finalBudget m) * V := by gcongr + _ = V * (N * ((2 : ℝ) ^ (q * v.group) + h ^ M / (2 : ℝ) ^ v.remaining) + U) + + c * V * v.finalBudget m := by ring + _ ≤ K * (N * ((2 : ℝ) ^ (q * v.group) + h ^ M / (2 : ℝ) ^ v.remaining) + U) + + K * v.finalBudget m := + add_le_add (mul_le_mul_of_nonneg_right small (by positivity)) (mul_le_mul_of_nonneg_right + hcv hfin) + _ = _ := by unfold expense N U; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # An absolute bound for finishing any admissible terminal layer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly Contraction + +theorem Current.finish : ∃ J : ℕ, + ∀ {δ : ℝ} {p : Design δ} {M : ℕ} {v : Levels p M} {s : Plan} + {F : Type} [Field F] {x y : Wire} {Q : Layer F x y} {n m E B C : ℕ} + (W : Prices F), v.Current s n m v.j E Q → v.Fits n B C → m ≤ n ^ 2 → + s.d + s.p ≤ 2 ^ v.j → 16 * Nat.clog 2 n ≤ W.w → + ∃ L : Finset (Table F), L.card ≤ 3 ∧ + Finishes F (v.endCap s W E) L Q.snapshot (v.endCost s W n m E (wd x + wd y) J) := by + obtain ⟨J, run⟩ := Layer.terminal + refine ⟨J + 2, ?_⟩ + intro δ p M v s F _ x y Q n m E B C W h fit hm hs hw + let z := v.bill s W m Q + obtain ⟨hm', _, hr⟩ := h.terminal_space fit hm hs hw + have cap : 3 ≤ v.endCap s W E := by unfold endCap; omega + have room : 2 ^ z.p * (z.w * (2 ^ z.S.m + 2 ^ z.S.m)) < 2 ^ W.w := by + rw [max_comm] at hr + exact hr + have arity := (Terminal.arity_le z).trans (h.bill_arity W) + let L := Terminal.labels z.S z.t z.w + refine ⟨L, Terminal.labels_card .., ?_⟩ + obtain ⟨k, hk, done⟩ := run F x y Q W z.V z.t hm' room h.fits_terminal _ (↑L) cap arity + Set.Subset.rfl + exact ⟨k, hk.mono (h.endCost_le W ((Nat.le_add_right ..).trans (h.long fit le_rfl hm)) J), done⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Selecting the grouping of every state at an intermediate round -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly + +variable {δ : ℝ} {p : Design δ} {M : ℕ} {v : Levels p M} {s : Plan} + {F : Type} [Field F] {x y : Wire} {Q : Layer F x y} {n m i E : ℕ} + +theorem Suits.exterior {T₀ : ℕ} {a b ξ : ℝ} (hs : v.Suits n T₀ a b ξ) (hi : i ≤ v.j) + (he : ((wd x + wd y : ℕ) : ℝ) ≤ m * (Nat.clog 2 n : ℝ) ^ (-(2 * a))) : + ((wd (copies x v.batch) + wd (copies y v.batch) : ℕ) : ℝ) * p.D ≤ v.budget m i := by + obtain ⟨_, hh, _, _, _, _, _, _, hsize, _⟩ := hs + have hgain : (p.D : ℝ) * (2 : ℝ) ^ (p.gain * i) ≤ (Nat.clog 2 n : ℝ) ^ (2 * a) := + (mul_le_mul_of_nonneg_left (pow_le_pow_right₀ (by norm_num) (Nat.mul_le_mul_left _ hi)) + (by positivity)).trans hsize + have hscale : ((wd x + wd y : ℕ) : ℝ) * (p.D * (2 : ℝ) ^ (p.gain * i)) ≤ m := by + rw [Real.rpow_neg (by positivity), ← div_eq_mul_inv] at he + exact (mul_le_mul_of_nonneg_left hgain (by positivity)).trans ((le_div_iff₀ (by positivity)).mp + he) + rw [budget, Design.budget, le_div_iff₀ (by positivity), wd_copies, wd_copies, ← mul_add, + Nat.cast_mul] + calc + _ = (v.batch : ℝ) * (((wd x + wd y : ℕ) : ℝ) * (p.D * (2 : ℝ) ^ (p.gain * i))) := by ring + _ ≤ (v.batch : ℝ) * m := mul_le_mul_of_nonneg_left hscale (by positivity) + _ ≤ 256 * (m : ℝ) * v.batch * (v.stack + 1) := by + rw [mul_comm (v.batch : ℝ)] + exact (mul_le_mul_of_nonneg_right (le_mul_of_one_le_left (by positivity) (by norm_num)) + (by positivity)).trans (le_mul_of_one_le_right (by positivity) (by simp)) + _ = _ := by rw [← budget_zero, budget, Design.budget, mul_zero, pow_zero, div_one] + +theorem live (Q : Layer F x y) (he : 0 < wd x + wd y) (j : Q.State) : Nonempty (Q.board j).V := by + have hp : Nonempty (slots x ⊕ slots y) := Fintype.card_pos_iff.mp (by simpa using he) + obtain ⟨w⟩ := hp + exact ⟨((Q.board j).place (Packing.portEnd (Q.board j).diagram w)).1⟩ + +namespace Current +variable (cur : v.Current s n m i E Q) +include cur + +theorem group_le (hi : i < v.j) : v.group ≤ Q.template.scheme.h := + (Nat.le_mul_of_pos_left _ p.steps_pos).trans (cur.enough hi) + +theorem binning (hi : i < v.j) {P b d : ℕ} + (sc : SphereScale.Scales ((4 * 5) ^ 300) 10 s.D (v.width i) P b d) : + Q.template.Binning (Q.template.scheme.h - v.group) s.D (v.width i) (d * b) s.floor := by + have hg : 0 < v.group := lt_of_lt_of_le (by have := p.overhead_large; omega : 0 < p.overhead) + v.overhead_le_group + have ht := cur.group_le hi + refine ⟨by omega, ?_, sc.Tpos, sc.Rpos, sc.smallR, by unfold Plan.floor Plan.M Plan.D; positivity⟩ + exact (lt_mul_of_one_lt_left (by positivity) (by decide)).trans_le sc.degree + +/-- The trials of type `∀ j, b.Trial (Q.presents j) (v.budget m i)` for the given inputs. -/ +def trials {a R : ℕ} (b : Q.template.Binning a s.D (v.width i) R s.floor) + (ha : a + v.group = Q.template.scheme.h) (hd : s.D ≤ p.overhead) (hi : i ≤ v.j) + (he : ((wd x + wd y : ℕ) : ℝ) * s.D ≤ v.budget m i) : + ∀ j, b.Trial (Q.presents j) (v.budget m i) := by + refine Q.trial b cur.ready cur.loopless ?_ he + intro j + have hc : Fintype.card (Q.board j).V ≤ 2 ^ Q.template.scheme.m := by + simpa only [Fintype.card_fin] using Fintype.card_le_of_injective _ (Q.presents j).host.injective + have hs : (Q.board j).seats ≤ 2 ^ (Q.template.scheme.m + Q.template.scheme.h) := by + rw [Board.seats, pow_add] + exact Nat.mul_le_mul_right _ hc + rw [show Q.template.scheme.h - a = v.group by omega] + refine le_trans ?_ (cur.slack hi hd) + rw [mul_assoc, mul_comm ((Q.board j).seats : ℝ)] + exact mul_le_mul_of_nonneg_left (Nat.cast_le.mpr hs) (by positivity) + +end Current +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Domination of the grouping cost by the common phase scale -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly Contraction + +/-- The quantity computed by `2 * Layer.masked_bound.choose + 1`. -/ +def groupPower : ℕ := 2 * Layer.masked_bound.choose + 1 + +namespace Current + +variable {δ : ℝ} {p : Design δ} {M : ℕ} {v : Levels p M} {s : Plan} + {F : Type} [Field F] {x y : Wire} {Q : Layer F x y} {n m i E a R : ℕ} + +theorem group_size (cur : v.Current s n m i E Q) + (bin : Q.template.Binning a s.D (v.width i) R s.floor) (price : Prices F) + {B J K : ℕ} (ha : a + v.group = Q.template.scheme.h) (hm : bin.target.m ≤ price.w) + (hk : groupPower ≤ K) : + let u := v.groupPayload s B J Q.height + bin.programArity (Q.height + 1) ≤ (BoundaryScale.short Q.template 1 u v.group price) ^ K ∧ + Q.maskedCost bin price ≤ BoundaryScale.cost (x := x) (y := y) Q.template 1 u v.group price K + := by + intro u + let k := Layer.masked_bound.choose + have hj : k ≤ K := by change 2 * k + 1 ≤ K at hk; omega + have hd : Q.template.scheme.d ≤ 4 := by rw [cur.degree]; decide + let t := Q.grouping bin price hd cur.ready.1 + let S := BoundaryScale.short Q.template 1 u v.group price + let A := BoundaryScale.long Q.template 1 u v.group price + let O := BoundaryScale.outer Q.template 1 u price + have h₁ : t.short ≤ S := by + change 1000000 + s.D + 2 ^ Template.Presents.Plan.depth s.D s.floor + Q.template.scheme.ℓ + + Q.template.count+ + 2 ^ Q.template.scheme.e + Q.template.scheme.h + 2 ^ (Q.template.scheme.h - a) + price.W + + Q.height ≤ S + rw [show Q.template.scheme.h - a = v.group by omega] + unfold S BoundaryScale.short BoundaryScale.metadata BoundaryScale.base u groupPayload + groupCoefficient + omega + have h₂ : t.bitBase ≤ O := by + change 1000 + price.W + Q.height + Q.height ≤ O + unfold O BoundaryScale.outer u groupPayload groupCoefficient + have := Nat.two_pow_pos (Template.Presents.Plan.depth s.D s.floor) + omega + have hw := Nat.zero_le (price.w ^ price.power) + have hl : 2 ≤ A := by change 2 ≤ 100 + price.w + price.w ^ price.power + S; omega + have h₃ : t.long ≤ A ^ 2 := calc + _ ≤ A + A := by + have hh : Q.template.scheme.m ≤ price.w := (Nat.le_add_right ..).trans hm + change t.short + Q.template.scheme.m + price.w + price.w ^ price.power ≤ A + A + change _ ≤ (100 + price.w + price.w ^ price.power + S) + (100 + price.w + + price.w ^ price.power + S) + omega + _ ≤ _ := by rw [← two_mul, pow_two]; exact Nat.mul_le_mul_right _ hl + have hg : t.short ^ k ≤ S ^ K := (Nat.pow_le_pow_left h₁ k).trans + (Nat.pow_le_pow_right ((lt_of_lt_of_le (by decide) t.short_two).trans_le h₁) hj) + have he : t.bitBase ^ k ≤ O ^ K := (Nat.pow_le_pow_left h₂ k).trans + (Nat.pow_le_pow_right ((lt_of_lt_of_le (by decide) t.bitBase_two).trans_le h₂) hj) + have ht : t.long ^ k ≤ A ^ K := + ((Nat.pow_le_pow_left h₃ k).trans_eq (pow_mul ..).symm).trans + (Nat.pow_le_pow_right (by omega) ((Nat.le_add_right _ _).trans hk)) + obtain ⟨w, c⟩ := Layer.masked_bound.choose_spec F x y _ _ _ _ _ Q bin price hd cur.ready.1 + cur.volume + exact ⟨w.trans hg, c.trans (Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ ht) + (Nat.mul_le_mul_left _ hg)) (Nat.mul_le_mul_left _ he))⟩ + +end Current +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Uniformly admitting the controlled sphere terms to contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +open Assembly + +variable {δ : ℝ} {p : Design δ} {M : ℕ} {v : Levels p M} {s : Plan} + {K F : Type} [Field K] [Field F] [Fintype F] [Algebra K F] + {x y : Wire} {Q : Layer F x y} {n m i E B C a : ℕ} + {char l b d z A J : ℕ} [ExpChar F char] + (cur : v.Current s n m i E Q) (fit : v.Fits n B C) + +include cur fit in +theorem publish (law : SphereScale.Controlled K s char l b A J) + (sc : SphereScale.Scales ((4 * 5) ^ 300) 10 s.D (v.width i) (char ^ l) b d) + (ready : SphereScale.Ready K 10 s.D ((4 * 5) ^ 300) (char ^ l) b d) + (repr : A * (1 + v.width i) ^ A ≤ Fintype.card F) (field : Fintype.card F ≤ (Nat.clog 2 n) ^ B) + (unit : 0 < s.b) (hz : 0 < z) (small : (s.b * z) * s.D ^ s.c ≤ v.width i) (big : v.width i + ≤ z * s.M) + (bin : Q.template.Binning a s.D (v.width i) (d * b) s.floor) + (trial : ∀ j, bin.Trial (Q.presents j) (v.budget m i)) (price : Contraction.Prices F) + (ha : a + v.group = Q.template.scheme.h) (hi : i ≤ v.j) (hm : m ≤ n ^ 2) + (he : 0 < wd x + wd y) (margin : J + s.d + s.p + 1 ≤ 2 ^ v.j) (hw : 16 * Nat.clog 2 n + ≤ price.w) : + ∃ (U : Template F) (labels : Finset (Table F)), + v.Passage Q U (1 + J) ∧ v.FrameBound Q U Q.height (frameRate s J) ∧ + U.scheme.k = 0 ∧ U.scheme.d ≤ J ∧ labels.card ≤ J ∧ + Transforms F (SphereScale.fullArity bin.target Q.height (v.precision s B) J) (↑labels) + (Q.masked bin trial (Layer.panelRadius s.D)) (Contraction.publication U s (v.width i) + (v.budget m i) z Q.height) + (SphereScale.fullCost bin.target price Q.height (v.precision s B) (wd x + wd y) J) := by + have hl := (Nat.mul_le_mul_left (s.b * z) (Nat.pow_le_pow_right sc.Dpos s.small)).trans small + have hr := big.trans (Nat.mul_le_mul_right s.M (Nat.le_mul_of_pos_left z unit)) + obtain ⟨U, labels, height, lo, up, hk, hd, hp, hw', few, run⟩ := + law F (v.width i) d (v.precision s B) z sc ready repr (width_precision hi) (fit.field field) + (Nat.mul_pos unit hz) hl hr x y Q a s.floor (v.budget m i) bin trial price + (Levels.live Q he) (by rw [cur.degree]; decide) (cur.binSpace fit bin hi hm margin hw) + exact ⟨U, labels, Passage.fromBin bin ha height lo up, cur.fromBin fit bin (by omega) hp hw', hk, + hd, few, run⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +end + +/- Charge a controlled concentration step to the pre-grouping budget. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +open Assembly Contraction SphereScale + +variable {δ : ℝ} {p : Design δ} {M : ℕ} {v : Levels p M} {s : Plan} + {F : Type} [Field F] {x y : Wire} {Q : Layer F x y} {n m i E a R : ℕ} + +/-- A quadratic change of base and a quadratic multiplicity loss. -/ +private theorem grouped_pow {x y b c J K : ℕ} (hx : x ≤ y * b ^ 2) (hb : 2 ≤ b) + (hc : c ≤ b ^ 2) (hk : 3 * J + 4 ≤ K) : x * c ^ J ≤ y * b ^ K := by + calc + _ ≤ (y * b ^ 2) * (b ^ 2) ^ J := Nat.mul_le_mul hx (Nat.pow_le_pow_left hc J) + _ = y * b ^ (2 + 2 * J) := by rw [mul_assoc, ← pow_mul, ← pow_add] + _ ≤ _ := Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) (by omega)) + +theorem sphere_work (cur : v.Current s n m i E Q) + (bin : Q.template.Binning a s.D (v.width i) R s.floor) (price : Prices F) + {B J K : ℕ} (ha : a + v.group = Q.template.scheme.h) (hm : bin.target.m ≤ price.w) + (hk : 3 * J + 4 ≤ K) : + let u := v.groupPayload s B J Q.height + fullArity bin.target Q.height (v.precision s B) J ≤ + (BoundaryScale.short Q.template 1 u v.group price) ^ K ∧ + fullCost bin.target price Q.height (v.precision s B) (wd x + wd y) J ≤ + BoundaryScale.cost (x := x) (y := y) Q.template 1 u v.group price K := by + let u := v.groupPayload s B J Q.height + let T := BoundaryScale.short Q.template 1 u v.group price + let L := BoundaryScale.long Q.template 1 u v.group price + let O := BoundaryScale.outer Q.template 1 u price + let A := portBase bin.target price Q.height + let S := rowBase bin.target price Q.height (v.precision s B) + have hu : 1000 + 2 * Levels.binBits s + binFactor s + v.precision s B + Q.height + J ≤ u := by + unfold u groupPayload groupCoefficient + have := Nat.two_pow_pos (Template.Presents.Plan.depth s.D s.floor) + omega + have hT : 2 + 2 ^ v.group + Q.template.scheme.h + u + Q.template.scheme.ℓ + price.W ≤ T := by + unfold T BoundaryScale.short BoundaryScale.metadata BoundaryScale.base + have := Nat.two_pow_pos Q.template.scheme.e + omega + have hL : T + price.w + price.w ^ price.power ≤ L := by + change _ ≤ 100 + price.w + price.w ^ price.power + T + omega + have h₂ := Nat.two_pow_pos v.group + have hp := Nat.zero_le (price.w ^ price.power) + have hbits := cur.binBits bin + have he := (Nat.lt_two_pow_self (n := bin.target.e)).le.trans hbits + have ht := bin.shape.2.1 + have hA : A ≤ O := by unfold A O portBase BoundaryScale.outer; omega + have hs : A + 2 ^ bin.target.e + v.precision s B ≤ T := by unfold A portBase; omega + have hlabel := cur.binLabel bin + have hshort : S ≤ T ^ 2 := calc + _ ≤ T + binFactor s * T := by + have hx := hlabel.trans (Nat.mul_le_mul_left _ (show Q.template.scheme.ℓ + 1 ≤ T by omega)) + change A + 2 ^ bin.target.e + bin.target.ℓ + v.precision s B ≤ _ + omega + _ = (1 + binFactor s) * T := by ring + _ ≤ _ := by rw [pow_two]; exact Nat.mul_le_mul_right _ (by omega) + have hlong : hostBase bin.target price Q.height (v.precision s B) ≤ L ^ 2 := calc + _ ≤ 2 * L + binFactor s * L := by + have hx := hlabel.trans (Nat.mul_le_mul_left _ (show Q.template.scheme.ℓ + 1 ≤ L by omega)) + change A + 2 ^ bin.target.e + bin.target.ℓ + v.precision s B + bin.target.m + price.w + + price.w ^ price.power ≤ _ + omega + _ = (2 + binFactor s) * L := by ring + _ ≤ _ := by rw [pow_two]; exact Nat.mul_le_mul_right _ (by omega) + constructor + · calc + _ ≤ J * S := by + unfold fullArity S rowBase portBase + apply Nat.mul_le_mul_left + have := Nat.two_pow_pos bin.target.e + omega + _ ≤ T * T ^ 2 := Nat.mul_le_mul (by omega) hshort + _ = T ^ 3 := by ring + _ ≤ _ := Nat.pow_le_pow_right (by omega : 0 < T) (by omega) + · have hosts : 2 ^ bin.target.m ≤ 2 ^ Q.template.scheme.m * L ^ 2 := by + rw [bin.shape.1, show Q.template.scheme.h - a = v.group by omega, pow_add, pow_succ, pow_two] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul (by omega) (by omega)) + have seats : 2 ^ (bin.target.m + bin.target.h) ≤ 2 ^ (Q.template.scheme.m + + Q.template.scheme.h) * T ^ 2 := by + rw [pow_add, bin.capacity, ← pow_add, mul_comm 2] + exact Nat.mul_le_mul_left _ ((show 2 ≤ T by omega).trans (Nat.le_self_pow (by decide) T)) + have ho : 0 < O := by unfold O BoundaryScale.outer; omega + exact Nat.add_le_add + (Nat.add_le_add (grouped_pow hosts (by omega : 2 ≤ L) hlong hk) + (grouped_pow seats (by omega : 2 ≤ T) hshort hk)) + (Nat.mul_le_mul_left _ ((Nat.pow_le_pow_left hA J).trans (Nat.pow_le_pow_right ho (by + omega)))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +end + +/- # A complete encoded round, with a uniform budget -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +open Assembly Contraction + +variable {F K k : Type} [Field F] [Fintype F] [Field K] [Algebra K F] [Field k] [Algebra k F] + {x y : Wire} {δ : ℝ} {p : Design δ} {M n m i E B C J G H q T₀ R z : ℕ} + {v : Levels p M} {s : Plan} {Q : Layer F (copies x v.batch) (copies y v.batch)} + {price : Prices F} {a b ξ τ σ J₀ : ℝ} + +open scoped Classical in +/-- The value specified by `2 * (2 * ((groupCoefficient s J + B + 128 : ℕ) : ℝ) * (J₀ + 1)) ^ G ++ (2 * ((frameRate s J + 2 : ℕ) : ℝ) * (J₀ + 1)) ^ H`. -/ +def roundCostFactor (s : Plan) (B J G H : ℕ) (J₀ : ℝ) := + 2 * (2 * ((groupCoefficient s J + B + 128 : ℕ) : ℝ) * (J₀ + 1)) ^ G + + (2 * ((frameRate s J + 2 : ℕ) : ℝ) * (J₀ + 1)) ^ H + +open scoped Classical in +theorem paid_round (cur : v.Current s n m i E Q) (level : v.Suits n T₀ a b ξ) (fit : v.Fits n B C) + {char l b₀ d A : ℕ} [ExpChar F char] + (law : SphereScale.Controlled K s char l b₀ A J) + (restart : Restarts k s J H) + (ok : Admissible p s (1 + J) (frameRate s J) H E C) + (sc : SphereScale.Scales ((4 * 5) ^ 300) 10 s.D (v.width i) (char ^ l) b₀ d) + (ready : SphereScale.Ready K 10 s.D ((4 * 5) ^ 300) (char ^ l) b₀ d) + (repr : A * (1 + v.width i) ^ A ≤ Fintype.card F) (field : Fintype.card F ≤ (Nat.clog 2 n) ^ B) + (hs : s.Fits) (unit : 0 < s.b) (overhead : 0 < s.K) + (hz : 0 < z) (low : (s.b * z) * s.D ^ s.c ≤ v.width i) (high : v.width i ≤ z * s.M) + (hD : p.D = s.D) (hOver : s.D ≤ p.overhead) + (hi : i < v.j) (hm : n ≤ m) (hm' : m ≤ n ^ 2) + (he₀ : 0 < wd x + wd y) (he : ((wd x + wd y : ℕ) : ℝ) ≤ m * (Nat.clog 2 n : ℝ) ^ (-(2 * a))) + (margin₁ : J + s.d + s.p + 1 ≤ 2 ^ v.j) + (margin₂ : groupCoefficient s J + s.d + s.p + 2 * E + 6 ≤ 2 ^ v.j) + (margin₃ : frameRate s J + 2 * E + 1 ≤ 2 ^ v.j) + (hG₁ : groupPower ≤ G) (hG₂ : 3 * J + 4 ≤ G) (hH : 0 < H) + (exponent : (5 + 2 * E + p.groupRate + 6) * G ≤ C) (enough : C ≤ q * p.groupRate) + (hq : (p.groupRate * q : ℕ) * a ≤ b) (hh : 2 ≤ (Nat.clog 2 n : ℝ)) + (hl : 1 ≤ Real.log (Nat.clog 2 n)) (hτ : 0 ≤ τ) + (hGτσ : (G : ℝ) * τ ≤ σ) (hHτσ : (H : ℝ) * τ ≤ σ) (hσ : σ ≤ 1) + (hw : (price.W : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ τ) + (space : 16 * Nat.clog 2 n ≤ price.w) + (wide : price.w + price.w ^ price.power ≤ (Nat.clog 2 n) ^ R) + (reserveG : (7 + max R 1) * G ≤ M) (reserveH : (7 + max R 1) * H ≤ M) + (hJ : 0 ≤ J₀) + (span : ((v.span + s.d + s.p + 1 : ℕ) : ℝ) ≤ J₀ * (Real.log (Nat.clog 2 n)) ^ 2) : + let h : ℝ := Nat.clog 2 n + ∃ (P : Layer F (copies x v.batch) (copies y v.batch)) (L : Finset (Table F)) (u t : ℕ), + v.Current s n m (i + 1) E P ∧ L.card ≤ (5 + J + 2 ^ H) * (Nat.clog 2 n) ^ 2 ∧ + (u : ℝ) ≤ (2 : ℝ) ^ (max G H + 2 * p.groupRate * q) * h ^ σ * (p.D * (v.finalWidth : ℝ)) ∧ + (t : ℝ) ≤ roundCostFactor s B J G H J₀ * (Real.log h) ^ (2 * max G H) * h ^ σ * v.expense h m + (wd x + wd y) q ∧ + Transforms F u L Q.snapshot P.snapshot t := by + let t := Q.template.scheme.h - v.group + let bin := cur.binning hi sc + have ht : t + v.group = Q.template.scheme.h := Nat.sub_add_cancel (cur.group_le hi) + have he₁ := level.exterior hi.le he + rw [hD] at he₁ + let trial := cur.trials bin ht hOver hi.le he₁ + have he₂ : 0 < wd (copies x v.batch) + wd (copies y v.batch) := by + rw [wd_copies, wd_copies, ← mul_add] + exact Nat.mul_pos (by unfold Levels.batch; positivity) he₀ + have hzT : z ≤ v.width i := + ((Nat.le_mul_of_pos_left _ unit).trans + (Nat.le_mul_of_pos_right _ (pow_pos (by have := s.two hs; omega) _))).trans low + obtain ⟨D, L₁, pass, data, hk, hd, hL₁, sphere⟩ + := cur.publish fit law sc ready repr field unit hz low high + bin trial price ht hi.le hm' he₂ margin₁ space + have field' : Nat.card F ≤ (Nat.clog 2 n) ^ B := by rw [Nat.card_eq_fintype_card]; exact field + have rq := cur.requirements pass data ok fit hi margin₃ hs unit overhead hm hm' hz low high hd hk + field' space + obtain ⟨finish, next, finishFew, finishArity, finishCost⟩ + := cur.paid_restart level fit pass data ok hi margin₃ + hH overhead hzT rq restart hh hl hτ hHτσ hσ hw wide reserveH enough hq hJ span + have extSpace : Q.template.scheme.m + 5 * (Q.template.scheme.h - t) + Q.height + 4 ≤ price.w := by + have h₁ := cur.long fit hi.le hm' + have h₂ := fit.group + have h₃ := Nat.lt_two_pow_self.le.trans h₂ + have h₄ : 4 * v.span ≤ Nat.clog 2 n := fit.four_span.trans fit.group + have h₅ := margin₁.trans ((Nat.pow_le_pow_right (by decide) v.rounds_le_group).trans h₂) + have h₆ := cur.height + have h₇ : 2 ≤ Nat.clog 2 n := by exact_mod_cast hh + omega + have hp₀ : 1 ≤ Nat.clog 2 n := by + exact_mod_cast (show (1 : ℝ) ≤ (Nat.clog 2 n : ℝ) by linarith) + have baseAddr : 1 ≤ Q.template.scheme.m := hp₀.trans cur.address + have masked := Q.masked_transfer bin trial price (Layer.panelRadius s.D) + (by rw [cur.degree]; decide) baseAddr extSpace + have newAddr : bin.target.m ≤ price.w := + (Nat.le_add_right ..).trans ((Nat.le_add_right ..).trans (cur.binSpace fit bin hi.le hm' + margin₁ space)) + have maskBound := cur.group_size bin price (B:=B) (J:=J) (K:=G) ht newAddr hG₁ + have waveBound := cur.sphere_work bin price (B:=B) (J:=J) (K:=G) ht newAddr hG₂ + obtain ⟨_, groupArity, groupCost⟩ := cur.paid_group level fit hi.le margin₂ (by omega : 0 + < G) exponent + hh hl hτ hGτσ hσ hw wide reserveG enough hq hJ span + have h₀ := (Nat.cast_le.mpr maskBound.1).trans groupArity + have h₁ := (Nat.cast_le.mpr waveBound.1).trans groupArity + let keys := (bin.programKeys (Q.height + 1) ∪ L₁) ∪ finish.keys + have net := (masked.comp_union sphere).comp_union finish.transfer + refine ⟨finish.next, keys, _, _, next, ?_, ?_, ?_, net⟩ + · have hc₁ := Finset.card_union_le (bin.programKeys (Q.height + 1) ∪ L₁) finish.keys + have hc₂ := Finset.card_union_le (bin.programKeys (Q.height + 1)) L₁ + have hc := hc₁.trans (Nat.add_le_add hc₂ le_rfl) + refine hc.trans ((Nat.add_le_add (Nat.add_le_add (bin.few _) hL₁) finishFew).trans ?_) + rw [add_mul] + have hp₂ : 0 < (Nat.clog 2 n) ^ 2 := pow_pos (Nat.zero_lt_one.trans_le hp₀) _ + exact Nat.add_le_add (Nat.le_mul_of_pos_right _ hp₂) le_rfl + · have hₛ : (2 : ℝ) ^ (G + 2 * p.groupRate * q) ≤ (2 : ℝ) ^ (max G H + 2 * p.groupRate * q) := + pow_le_pow_right₀ (by norm_num) (Nat.add_le_add_right (Nat.le_max_left ..) _) + have hᵣ : (2 : ℝ) ^ (H + 2 * p.groupRate * q) ≤ (2 : ℝ) ^ (max G H + 2 * p.groupRate * q) := + pow_le_pow_right₀ (by norm_num) (Nat.add_le_add_right (Nat.le_max_right ..) _) + have hpow : 0 ≤ (Nat.clog 2 n : ℝ) ^ σ := by positivity + have hwidth : 0 ≤ (p.D : ℝ) * (v.finalWidth : ℝ) := by positivity + have g := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right hₛ hpow) hwidth + have h := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right hᵣ hpow) hwidth + rw [Nat.cast_max, Nat.cast_max] + exact max_le (max_le (h₀.trans g) (h₁.trans g)) (finishArity.trans h) + · let h : ℝ := Nat.clog 2 n + let d₁ : ℝ := (2 * ((groupCoefficient s J + B + 128 : ℕ) : ℝ) * (J₀ + 1)) ^ G + let d₂ : ℝ := (2 * ((frameRate s J + 2 : ℕ) : ℝ) * (J₀ + 1)) ^ H + let U := h ^ σ * v.expense h m (wd x + wd y) q + have hU : 0 ≤ U := by unfold U Levels.expense Levels.finalBudget; positivity + have g₀ := (Nat.cast_le.mpr maskBound.2).trans groupCost + have g₁ := (Nat.cast_le.mpr waveBound.2).trans groupCost + have g₂ : (_ : ℝ) ≤ d₂ * (Real.log h) ^ (2 * H) * U := finishCost.trans_eq (by unfold U; ring) + have hleG : (Real.log h) ^ (2 * G) ≤ (Real.log h) ^ (2 * max G H) := + pow_le_pow_right₀ hl (Nat.mul_le_mul_left _ (Nat.le_max_left ..)) + have hleH : (Real.log h) ^ (2 * H) ≤ (Real.log h) ^ (2 * max G H) := + pow_le_pow_right₀ hl (Nat.mul_le_mul_left _ (Nat.le_max_right ..)) + have cG : d₁ * (Real.log h) ^ (2 * G) * h ^ σ * v.expense h m (wd x + wd y) q ≤ + d₁ * (Real.log h) ^ (2 * max G H) * U := by + calc + _ = d₁ * (Real.log h) ^ (2 * G) * U := by unfold U; ring + _ ≤ _ := mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_left hleG (by unfold d₁; positivity)) hU + have cH : d₂ * (Real.log h) ^ (2 * H) * U ≤ d₂ * (Real.log h) ^ (2 * max G H) * U := + mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hleH (by unfold d₂; positivity)) hU + push_cast + have sum : d₁ * (Real.log h) ^ (2 * max G H) * U + d₁ * (Real.log h) ^ (2 * max G H) * U+ + d₂ * (Real.log h) ^ (2 * max G H) * U = + roundCostFactor s B J G H J₀ * (Real.log h) ^ (2 * max G H) * h ^ σ * v.expense h m (wd x + + wd y) q := by + unfold roundCostFactor d₁ d₂ U + ring + simpa only [Layer.maskedCost, Nat.cast_mul, Nat.cast_ofNat] using + (add_le_add (add_le_add (g₀.trans cG) (g₁.trans cG)) (g₂.trans cH)).trans_eq sum + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Passage.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Passage.lean new file mode 100644 index 0000000000..0138324892 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Passage.lean @@ -0,0 +1,822 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Stack.Mates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Canonical +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access + +/-! # A short record at each station in an initial board -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Codec +open Assembly Coloring Packing Label + +variable {F : Type} [Field F] {a b : Wire} {h t m ℓ : ℕ} {G : Diagram F a b} + {f : ∀ v, Device (G.table v) t} (L : Codec G f ℓ) (A : Directory (Device.neighbors G f) m) + +open scoped Classical in +/-- Uses `⟨m, 3, h, 0, 4, ℓ, L.decode⟩` as the representation. -/ +abbrev scheme (m h : ℕ) : Scheme F := ⟨m, 3, h, 0, 4, ℓ, L.decode⟩ + +open scoped Classical in +/-- The indexed operation `fun j => ((f p.1).line p.2 j).bind fun s => (mate G f ⟨p.1, s⟩).map +fun k => (A.index p (site G f k), 0, slot G f k)`. -/ +def guide (p : Location G f) : Device.Guide := fun j => + ((f p.1).line p.2 j).bind fun s => + (mate G f ⟨p.1, s⟩).map fun k => (A.index p (site G f k), 0, slot G f k) + +open scoped Classical in +/-- The indexed operation `fun i => (A.nav i, fun _ => Function.extend A.host (fun p => L.label +p.1 p.2 (guide A p)) (fun _ => L.blank) i)`. -/ +def records (h : ℕ) : (L.scheme m h).format.obj := fun i => + (A.nav i, fun _ => Function.extend A.host + (fun p => L.label p.1 p.2 (guide A p)) (fun _ => L.blank) i) + +local notation "S" => L.scheme m h +local notation "r" => L.records A h + +open scoped Classical in +/-- The value specified by `(A.host p, z, 0)`. -/ +def atSite (p : Location G f) (z : B h) : B m × B h × B 0 := (A.host p, z, 0) + +open scoped Classical in +theorem pattern_at (p : Location G f) (z : B h) : + (S).pattern r (atSite A p z) = (f p.1).pattern p.2 (guide A p) := by + exact (congrArg L.decode (A.host.injective.extend_apply + (fun x => L.label x.1 x.2 (guide A x)) (fun _ => L.blank) p)).trans (L.read ..) + +open scoped Classical in +theorem pattern_off {v : (S).Vtx} (hv : v.1 ∉ Set.range A.host) : + (S).pattern r v = emptyPattern F := by + exact (congrArg L.decode (Function.extend_apply' + (fun x => L.label x.1 x.2 (guide A x)) (fun _ => L.blank) v.1 hv)).trans L.empty + +open scoped Classical in +/-- The value specified by `(atSite A (site G f s) z, slot G f s)`. -/ +def span (z : B h) (s : Stub G f) := (atSite A (site G f s) z, slot G f s) + +open scoped Classical in +theorem width_at (z : B h) (s : Stub G f) : + (S).width r (span A z s) = Label.width G f s := by + unfold Scheme.width span + rw [pattern_at] + exact (f s.1).sizeAt_slot _ s.2 rfl + +open scoped Classical in +theorem direction_at (z : B h) (s : Stub G f) : + (S).direction r (span A z s) = side G f s := by + unfold Scheme.direction span + rw [pattern_at] + change ((f s.1).line ((f s.1).site s.2) ((f s.1).slot s.2)).elim false (f s.1).side = _ + rw [((f s.1).line_eq _ _ s.2).mpr ⟨rfl, rfl⟩]; rfl + +open scoped Classical in +theorem peer_at (z : B h) (s : Stub G f) : + (S).peer r (span A z s) = (mate G f s).map (span A z) := by + unfold Scheme.peer + change (((S).pattern r (atSite A (site G f s) z)).peer 0 (slot G f s)).map _ = _ + rw [pattern_at] + have hg : guide A (site G f s) (slot G f s) = + (mate G f s).map (fun k => (A.index (site G f s) (site G f k), 0, slot G f k)) := by + unfold guide site slot + rw [((f s.1).line_eq _ _ s.2).mpr ⟨rfl, rfl⟩]; rfl + change (guide A (site G f s) (slot G f s)).map _ = _ + rw [hg] + cases e : mate G f s with + | none => rfl + | some k => + have ha := A.nav_link _ _ (mate_props G f e).2.2.2 + exact congrArg (fun i => some ((i, z, (0 : B 0)), slot G f k)) ha + +open scoped Classical in +private theorem peer_source {p q : (S).Span} (hp : (S).peer r p = some q) : + ∃ (z : B h) (s : Stub G f), span A z s = p := by + rcases p with ⟨⟨i, z, k⟩, j⟩ + have hk : k = 0 := Fin.eq_zero k + subst k + by_cases hv : i ∈ Set.range A.host + · obtain ⟨v, rfl⟩ := hv + change (((S).pattern r (atSite A v z)).peer 0 j).map _ = _ at hp + rw [pattern_at] at hp + change (guide A v j).map _ = _ at hp + cases e : (f v.1).line v.2 j with + | none => simp [guide, e] at hp + | some s => + obtain ⟨hv, hj⟩ := ((f v.1).line_eq ..).mp e + refine ⟨z, ⟨v.1, s⟩, ?_⟩ + simp only [span, site, slot, hv, hj]; rfl + · unfold Scheme.peer at hp + rw [pattern_off L A hv] at hp + cases hp + +open scoped Classical in +theorem proper : (S).Proper r := by + intro p q hp + obtain ⟨z, s, rfl⟩ := L.peer_source A hp + rw [peer_at] at hp + cases hm : mate G f s with + | none => simp [hm] at hp + | some k => + rw [hm] at hp + obtain rfl := Option.some.inj hp + obtain ⟨he, hw, hs, _⟩ := mate_props G f hm + rw [peer_at, he, width_at, width_at, direction_at, direction_at] + exact ⟨rfl, hw, hs⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Codec +end + +/- # Seating product stations by their local span ordinals -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Codec +open Assembly Coloring Packing Label Transcript + +variable {F : Type} [Field F] {a b : Wire} {h t m ℓ n : ℕ} {G : Diagram F a b} + {f : ∀ v, Device (G.table v) t} (L : Codec G f ℓ) (A : Directory (Device.neighbors G f) m) + (c : Cell h × Fin (2 ^ t) ≃ Fin n) + +local notation "S" => L.scheme m h +local notation "r" => L.records A h +local notation "H" => built G f c + +open scoped Classical in +/-- Embeds `(H).V` into `(S).Vtx where toFun v`. -/ +def vertex : (H).V ↪ (S).Vtx where + toFun v := atSite A (Device.place G f c v).1 (cellIndex h (Device.place G f c v).2) + inj' _ _ e := (Device.place G f c).injective (Prod.ext (A.host.injective (congrArg Prod.fst e)) + ((cellIndex h).injective (congrArg (fun i => i.2.1) e))) + +open scoped Classical in +theorem occupied (v : (S).Vtx) (e : v.1 ∈ Set.range A.host) : + v ∈ Set.range (L.vertex A c) := by + obtain ⟨p, hp⟩ := e + refine ⟨(Device.place G f c).symm (p, (cellIndex h).symm v.2.1), ?_⟩ + exact Prod.ext hp (Prod.ext ((cellIndex h).apply_symm_apply v.2.1) (Fin.eq_zero _).symm) + +open scoped Classical in +theorem pattern_vertex (v : (H).V) : + (S).pattern r (L.vertex A c v) = + (f v.1.2).pattern v.2 (guide A (Device.place G f c v).1) := + L.pattern_at A _ _ + +open scoped Classical in +theorem size_vertex (v : (H).V) (s : B 4) : + (f v.1.2).sizeAt v.2 s = (S).width r (L.vertex A c v, s) := by + unfold Scheme.width + rw [pattern_vertex] + rfl + +open scoped Classical in +/-- Reindexes `(H).Port v` and `(S).LocalPin r (L.vertex A c v)` by an equivalence. -/ +def pins (v : (H).V) : (H).Port v ≃ (S).LocalPin r (L.vertex A c v) := + (Equiv.ofBijective _ ((f v.1.2).bijective v.2)).trans + (Equiv.sigmaCongrRight fun s => finCongr (L.size_vertex A c v s)) + +open scoped Classical in +theorem value_at {T : Table F} (D : Device T t) (v : D.diagram.V) (g : Device.Guide) + (p : Pattern F 3 0 4) (hp : p = D.pattern v g) (x : ∀ s, Fin (p.width 0 s) → Bool) + (w : ∀ s, D.sizeAt v s = p.width 0 s) : + p.value 0 x = sample (D.diagram.table v) (fun i => + x (D.address v i).1 ((D.address v i).2.cast (w _))) := by subst p; rfl + +open scoped Classical in +theorem idle (p : Pattern F 3 0 4) (hp : p = emptyPattern F) + (v : B 0) (x : ∀ s, Fin (p.width v s) → Bool) : p.value v x = 1 := by subst p; rfl + +open scoped Classical in +/-- Builds `(S).Seating r H where vertex` with the specified `vertex`, `pin`, `cover`, `apply`. -/ +def seating : (S).Seating r H where + vertex := L.vertex A c + pin := L.pins A c + cover p := by + apply L.occupied A c + by_contra hv + have hw := Nat.zero_lt_of_lt p.2.isLt + unfold Scheme.width at hw + rw [pattern_off L A hv] at hw + exact Nat.not_lt_zero _ hw + sample v x := value_at (f v.1.2) _ _ _ (L.pattern_vertex A c v) + (fun s i => x ⟨s, i⟩) (L.size_vertex A c v) + vacant v hv x := idle _ (L.pattern_off A (fun he => hv (L.occupied A c v he))) _ _ + +open scoped Classical in +theorem ends_read (q : (H).End) : + let i := Label.read G f c q + ((L.seating A c).ends q).1 = span A (cellIndex h i.1) i.2.1 ∧ + ((L.seating A c).ends q).2.val = i.2.2 := by + obtain ⟨⟨⟨⟨z, v⟩, u⟩, p⟩, rfl⟩ := (H).portEquiv.surjective q + rw [Scheme.Seating.ends_at] + have he := (BatchDescent.Stack.gathered G c).plugEnd_port + (fun k => (f k.2).diagram) (z, v) ⟨u, p⟩ + have hr : (lift G f c).symm ((H).portEquiv ⟨⟨(z, v), u⟩, p⟩) = + ⟨(z, v), (f v).diagram.portEquiv ⟨u, p⟩⟩ := (lift G f c).symm_apply_eq.mpr he.symm + unfold Label.read + rw [hr] + refine ⟨?_, rfl⟩ + change (atSite A ⟨v, u⟩ (cellIndex h z), _) = + (atSite A ⟨v, (f v).site ((f v).localBit u p).1⟩ (cellIndex h z), _) + rw [Device.local_site] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Codec +end + +/- # A directed presentation of the replicated board -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Codec +open Assembly Coloring Packing Label + +variable {F : Type} [Field F] {a b : Wire} {h t m ℓ n : ℕ} {G : Diagram F a b} + {f : ∀ v, Device (G.table v) t} (L : Codec G f ℓ) (A : Directory (Device.neighbors G f) m) + (c : Cell h × Fin (2 ^ t) ≃ Fin n) + +local notation "S" => L.scheme m h +local notation "r" => L.records A h +local notation "H" => built G f c + +open scoped Classical in +theorem joins (e : (H).E) : + (S).Joins r ((L.seating A c).ends (wireEnd H e false)) ((L.seating A c).ends (wireEnd H e + true)) := by + obtain ⟨hv, hi⟩ := L.ends_read A c (wireEnd H e false) + obtain ⟨hw, hj⟩ := L.ends_read A c (wireEnd H e true) + refine ⟨?_, ?_⟩ + · rw [hv, hw, peer_at] + rcases e with ⟨k, e⟩|⟨⟨z, v⟩, e⟩ + · rw [read_edge, read_edge, mate_edge]; rfl + · rw [read_inner, read_inner, mate_inner]; rfl + · rw [hi, hj] + rcases e with ⟨k, e⟩|⟨⟨z, v⟩, e⟩ + · rw [read_edge, read_edge] + · rw [read_inner, read_inner] + +open scoped Classical in +theorem exposed (i : slots (copies a n) ⊕ slots (copies b n)) : + (S).peer r ((L.seating A c).ends (boundaryEnd H i)).1 = none := by + rw [(L.ends_read A c _).1, read_boundary, peer_at, mate_boundary] + rfl + +open scoped Classical in +/-- Builds `(S).Presentation r H where toSeating` with the specified `toSeating`, `proper`, +`internal`, `input`. -/ +def presentation : (S).Presentation r H where + toSeating := L.seating A c + proper := L.proper A + internal := L.joins A c + input i := L.exposed A c (.inl i) + output i := L.exposed A c (.inr i) + +open scoped Classical in +theorem directed : (L.presentation A c).Directed := by + intro e + change (S).direction r ((L.seating A c).ends e).1 = _ + rw [(L.ends_read A c e).1, direction_at] + obtain ⟨⟨⟨z, v⟩, q⟩, rfl⟩ := (lift G f c).surjective e + unfold Label.read + rw [Equiv.symm_apply_apply] + exact ((f v).side_codec q).trans (by cases q <;> rfl) + +open scoped Classical in +/-- The quantity computed by `L.scheme m h count := 0 load _ := 4 * (2 : ℝ) ^ t park _ := 0 past +_ := 0`. -/ +abbrev template (m h : ℕ) : Template F where + scheme := L.scheme m h + count := 0 + load _ := 4 * (2 : ℝ) ^ t + park _ := 0 + past _ := 0 + order := Equiv.refl _ + +open scoped Classical in +/-- The indexed operation `(L.records A h, fun i => ((decide (i ∈ Set.range A.host), false), fun +j => (A.flags i j, A.flags i j), fun _ => 0))`. -/ +def entry (h : ℕ) : (L.template m h).format.obj := + (L.records A h, fun i => ((decide (i ∈ Set.range A.host), false), + fun j => (A.flags i j, A.flags i j), fun _ => 0)) + +open scoped Classical in +/-- Builds `(L.template m h).Presents (L.entry A h) (Device.board G f c) where pres` with the +specified `pres`, `host`, `vertex`, `directed`. -/ +def presents : (L.template m h).Presents (L.entry A h) (Device.board G f c) where + pres := L.presentation A c + host := A.host + vertex _ := rfl + directed := L.directed A c + live _ := decide_eq_true_iff + closed := A.closed + reciprocal := A.reciprocal + edge := A.marks + core := A.marks + load v i := by + change 4 * (2 : ℝ) ^ t = push (Device.place G f c) (fun _ => 4 * (2 : ℝ) ^ t) (v, i) + unfold push + simp only [← (Device.place G f c).eq_symm_apply, Finset.sum_ite_eq', Finset.mem_univ, ite_true] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Codec +end + +/- +# Initial layer + +Normalize the input diagram and use a common local device for +equal tables. Isolated station values move into one scalar before +the rounds begin. This also covers an empty exterior or zero scalar. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +open Assembly Packing + +variable {F : Type} [Field F] [Fintype F] {a b : Wire} + +open scoped Classical in +/-- The initial layer represents independent copies of the whole input +tensor. Host and dictionary addresses have independent length bounds. -/ +theorem start (G : Diagram F a b) {M u D t h : ℕ} {L : Finset (Table F)} {θ : ℝ} + (admits : G.Admits u ↑L) (size : G.cost ≤ M) (ht : 0 < t) (hu : u ≤ 2 ^ t) + (hD : 8 ≤ D) (hθ : θ ≤ 4) : + let d := 2 ^ t * 2 ^ h + ∃ (P : Layer F (copies a d) (copies b d)) (i : P.State) (z : F), + (fun x y => z * (P.graph i).eval x y) = power G.eval d ∧ + P.Ready D (2 ^ t) (256 * (M : ℝ) * d * (t + 1)) θ ∧ P.Loopless ∧ + P.template.scheme.m = Nat.clog 2 (16 * M * (t + 1)) ∧ + P.template.scheme.h = h ∧ P.template.scheme.d = 3 ∧ + P.template.scheme.e = 4 ∧ P.template.scheme.ℓ = + Nat.clog 2 (1 + (L.card + 16 * Fintype.card F ^ 8) * 4 * (1 + 2 ^ t) * (t + + 1) * Nat.card Device.Guide) ∧ + P.template.count = 0 ∧ + P.volume = 2 ^ P.template.scheme.m + d * (wd a + wd b) ∧ P.height = h + t + 2 := by + let d := 2 ^ t * 2 ^ h + let H := G.normalized.canonical + let m := Nat.clog 2 (16 * M * (t + 1)) + obtain ⟨he, hs, ha, _, hl⟩ := G.canonical_normalized admits + have hwidth (v : H.V) : H.arity v ≤ 2 ^ t := + (ha v).trans (max_le (Nat.le_self_pow ht.ne' 2) hu) + obtain ⟨f, ⟨codec⟩⟩ := codec H hwidth hl + have hcard : Fintype.card (Location H f) ≤ 16 * M * (t + 1) := by + refine (Device.location_bound H f).trans (Nat.mul_le_mul_right _ ?_) + change 4 * G.normalized.canonical.cost ≤ _ + omega + obtain ⟨dir⟩ := directory (Device.neighbors H f) m (Device.sym_neighbors H f) + (fun v => (Device.neighbors_bound H f v).trans (by decide)) + (hcard.trans (Nat.le_pow_clog (by decide) _)) + let c : Cell h × Fin (2 ^ t) ≃ Fin d := Fintype.equivOfCardEq (by simp [d, Cell, mul_comm]) + let p := codec.presents dir c + have height (v : (built H f c).V) : (built H f c).arity v ≤ 2 ^ (t + 2) := by + change (f v.1.2).diagram.arity v.2 ≤ _ + simpa [pow_add, mul_comm] using (f v.1.2).arity v.2 + let B := p.singleton height + refine ⟨B, PUnit.unit, Fmt.weight (codec.template m h).scheme.scalar (codec.entry dir h).1, + ?_, ?_, fun _ => Device.built_loopless H f c, rfl, rfl, rfl, rfl, rfl, rfl, ?_, rfl⟩ + · funext x y + refine (p.pres.sweep_eval x y).symm.trans ?_ + change (built H f c).eval x y = _ + rw [Device.exact_value, he] + · refine ⟨rfl, fun _ => (built H f c).sweep_neutral, fun _ => ?_⟩ + have hseat : (Device.board H f c).seats ≤ 16 * M * (t + 1) * 2 ^ h + := Nat.mul_le_mul_right _ hcard + have budget : 16 * (2 : ℝ) ^ t * (Device.board H f c).seats ≤ 256 * (M : ℝ) * d * (t + 1) + := calc + _ ≤ 16 * (2 : ℝ) ^ t * (16 * M * (t + 1) * 2 ^ h : ℕ) := by gcongr + _ = _ := by unfold d; push_cast; ring + exact (Device.ready H f c hD hθ).relax le_rfl budget le_rfl + · change 2 ^ m + wd (copies a d) + wd (copies b d) = 2 ^ m + d * (wd a + wd b) + rw [wd_copies, wd_copies, mul_add, add_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end + +/- +# Cost of installing the initial stack + +Long identifiers are counted per host. The shorter table labels are +counted per host and block. The exposed bit cost scales with the full +tensor power. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack + +variable {F : Type} [Field F] {x y : Wire} {d : ℕ} + +theorem start_cost (P : Layer F (copies x d) (copies y d)) + {H B : ℕ} (hosts : 2 ^ P.template.scheme.m ≤ H) (blocks : P.template.scheme.h = B) + (degree : P.template.scheme.d = 3) (empty : P.template.count = 0) + (volume : P.volume = 2 ^ P.template.scheme.m + d * (wd x + wd y)) : + 140 * (P.snapshot.port.width + d * (wd x + wd y)) + 1 ≤ + 140 * (H * (8 * (P.template.scheme.m + 2) + 2) + + H * 2 ^ B * (P.template.scheme.ℓ + 2 * (P.height + 1)) + + (2 * (P.height + 1) + 1) * (d * (wd x + wd y))) + 1 := by + let e := d * (wd x + wd y) + have fmt : P.template.format.width ≤ + H * (8 * (P.template.scheme.m + 2) + 2) + H * 2 ^ B * P.template.scheme.ℓ := by + rw [P.template.width, degree, blocks, empty, add_zero] + norm_num + rw [Nat.mul_add, ← Nat.mul_assoc] + exact Nat.add_le_add (Nat.mul_le_mul_right _ hosts) + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ hosts)) + have bits : P.volume ≤ H * 2 ^ B + e := by + rw [volume] + exact Nat.add_le_add_right (hosts.trans + (Nat.le_mul_of_pos_right _ (by positivity))) e + have hw := P.width.trans (Nat.add_le_add fmt + (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left 2 bits))) + refine Nat.add_le_add_right (Nat.mul_le_mul_left _ (Nat.add_le_add_right hw e)) _ |>.trans_eq ?_ + congr 1 + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end + +section +/- # Sizes of the initial stack addresses -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack + +private theorem sum_pow_bound {x y i j : ℕ} (hx : x ≤ 2 ^ i) (hy : y ≤ 2 ^ j) : + x + y ≤ 2 ^ (i + j + 1) := by + have hi : (2 : ℕ) ^ i ≤ 2 ^ (i + j) := Nat.pow_le_pow_right (by decide) (by omega) + have hj : (2 : ℕ) ^ j ≤ 2 ^ (i + j) := Nat.pow_le_pow_right (by decide) (by omega) + rw [pow_succ] + omega + +private theorem mul_pow_bound {x y i j : ℕ} (hx : x ≤ 2 ^ i) (hy : y ≤ 2 ^ j) : + x * y ≤ 2 ^ (i + j) := + (Nat.mul_le_mul hx hy).trans_eq (pow_add 2 i j).symm + +theorem label_bits {L f g t E B : ℕ} (hL : L ≤ 2 ^ B) (hf : f ≤ 2 ^ E) : + Nat.clog 2 (1 + (L + 16 * f ^ 8) * 4 * (1 + 2 ^ t) * (t + 1) * g) ≤ + B + 8 * E + 2 * t + Nat.clog 2 g + 10 := by + have h8 : f ^ 8 ≤ 2 ^ (E * 8) := by + rw [pow_mul] + exact Nat.pow_le_pow_left hf _ + have h16 : 16 * f ^ 8 ≤ 2 ^ (4 + E * 8) := + mul_pow_bound (by decide : 16 ≤ 2 ^ 4) h8 + have hleft := sum_pow_bound hL h16 + have hpow := sum_pow_bound (show 1 ≤ (2 : ℕ) ^ 0 by decide) (le_refl ((2 : ℕ) ^ t)) + have ht : t + 1 ≤ (2 : ℕ) ^ (t + 1) := Nat.lt_two_pow_self.le + have hg := Nat.le_pow_clog (by decide : 1 < 2) g + have hprod := mul_pow_bound (mul_pow_bound + (mul_pow_bound (mul_pow_bound hleft (by decide : 4 ≤ 2 ^ 2)) hpow) ht) hg + apply Nat.clog_le_of_le_pow + simpa only [show 0 + (B + (4 + E * 8) + 1 + 2 + (0 + t + 1) + (t + 1) + Nat.clog 2 g) + 1 = + B + 8 * E + 2 * t + Nat.clog 2 g + 10 by omega] using + sum_pow_bound (show 1 ≤ (2 : ℕ) ^ 0 by decide) hprod + +theorem host_bits {m n t : ℕ} (hm : m ≤ n ^ 2) : + Nat.clog 2 (16 * m * (t + 1)) ≤ 2 * Nat.clog 2 n + t + 5 := by + have hn := Nat.le_pow_clog (by decide : 1 < 2) n + have h2 : m ≤ 2 ^ (Nat.clog 2 n * 2) := by + rw [pow_mul] + exact hm.trans (Nat.pow_le_pow_left hn _) + have ht : t + 1 ≤ (2 : ℕ) ^ (t + 1) := Nat.lt_two_pow_self.le + apply Nat.clog_le_of_le_pow + rw [show 2 * Nat.clog 2 n + t + 5 = 4 + Nat.clog 2 n * 2 + (t + 1) by omega] + exact mul_pow_bound (mul_pow_bound (by decide : 16 ≤ 2 ^ 4) h2) ht + +theorem padded_hosts {m t : ℕ} (hm : 0 < m) : + 2 ^ (Nat.clog 2 (16 * m * (t + 1))) ≤ 32 * m * (t + 1) := + (Transcript.pow_clog_le_twice (by positivity)).trans_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end + +/- +# The invariant at the boundaries of complete rounds + +Consuming group bits can increase the number of addresses. We bound +the product of the number of addresses and the number of blocks. +The full record length can grow by a constant factor per round. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly + +variable {δ : ℝ} {p : Design δ} {M : ℕ} (v : Levels p M) {F : Type} [Field F] {x y : Wire} + +/-- The data for the current construction, including `ready`, `loopless`, `address`, `blocks`, +`seats`. -/ +structure Current (s : Plan) (n m i E : ℕ) (Q : Layer F x y) : Prop where + ready : Q.Ready s.D (v.width i) (v.budget m i) s.floor + loopless : Q.Loopless + address : Nat.clog 2 n ≤ Q.template.scheme.m + blocks : Q.template.scheme.h + p.steps * i * v.group = v.blocks + seats : 2 ^ (Q.template.scheme.m + Q.template.scheme.h) ≤ p.overhead ^ i * v.allocation m + ports : Q.template.scheme.e ≤ 5 + degree : Q.template.scheme.d = 3 + volume : Q.volume = 2 ^ Q.template.scheme.m + wd x + wd y + height : Q.height ≤ v.span + s.d + s.p + labels : Q.template.scheme.ℓ + Q.template.count ≤ E ^ i * v.box E + +variable {v} {s : Plan} {n m i E : ℕ} {Q : Layer F x y} + +theorem initial {Q : Layer F (copies x v.batch) (copies y v.batch)} + (positive : 0 < m) (hm : n ≤ m) + (ready : Q.Ready s.D (2 ^ v.stack) (256 * (m : ℝ) * v.batch * (v.stack + 1)) s.floor) + (loopless : Q.Loopless) (addr : Q.template.scheme.m = Nat.clog 2 (16 * m * (v.stack + 1))) + (blk : Q.template.scheme.h = v.blocks) (deg : Q.template.scheme.d = 3) + (port : Q.template.scheme.e = 4) (bits : Q.template.scheme.ℓ ≤ v.box E) + (ct : Q.template.count = 0) (vol : Q.volume = 2 ^ Q.template.scheme.m + v.batch * (wd x + wd y)) + (ht : Q.height = v.blocks + v.stack + 2) : v.Current s n m 0 E Q where + ready := by simpa only [budget_zero, width_eq, mul_zero, add_zero] using ready + loopless := loopless + address := by + rw [addr] + exact Nat.clog_mono_right _ (hm.trans ((Nat.le_mul_of_pos_left _ (by decide : 0 < 16)).trans + (Nat.le_mul_of_pos_right _ (by omega)))) + blocks := by simp only [blk, mul_zero, zero_mul, add_zero] + seats := by + rw [addr, blk, pow_add, pow_zero, one_mul] + exact Nat.mul_le_mul_right _ (Stack.padded_hosts positive) + ports := by omega + degree := deg + volume := by rw [vol, wd_copies, wd_copies, mul_add, add_assoc] + height := by rw [ht]; unfold span; omega + labels := by simpa only [ct, add_zero, pow_zero, one_mul] using bits + +namespace Current +variable (h : v.Current s n m i E Q) +include h + +theorem left (hi : i ≤ v.j) : + Q.template.scheme.h = v.remaining + p.steps * (v.j - i) * v.group := by + apply Nat.add_right_cancel (m := p.steps * i * v.group) + rw [h.blocks, Levels.blocks, add_assoc, ← add_mul, ← mul_add, Nat.sub_add_cancel hi] + +theorem enough (hi : i < v.j) : p.steps * v.group ≤ Q.template.scheme.h := by + rw [h.left hi.le] + exact (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (by omega))).trans (Nat.le_add_left ..) + +theorem bits (hi : i ≤ v.j) : Q.template.scheme.ℓ + Q.template.count ≤ v.box (E + E) := by + rw [v.box_add] + refine h.labels.trans (Nat.mul_le_mul_right _ ?_) + unfold box + rw [pow_mul] + exact (Nat.pow_le_pow_left Nat.lt_two_pow_self.le _).trans + (Nat.pow_le_pow_right (by positivity) (by omega)) + +end Current +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Passing through the one-group concentration before the contractions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly + +variable {δ : ℝ} {p : Design δ} {M : ℕ} (v : Levels p M) {F : Type} [Field F] {x y : Wire} + +/-- The excess over the consumed block coordinates is constant. -/ +structure Passage (Q : Layer F x y) (D : Template F) (J : ℕ) : Prop where + height : D.scheme.h + v.group = Q.template.scheme.h + lower : Q.template.scheme.m ≤ D.scheme.m + upper : D.scheme.m ≤ Q.template.scheme.m + v.group + J + +variable {v} {s : Plan} {n m i E J : ℕ} {Q : Layer F x y} {D : Template F} + (cur : v.Current s n m i E Q) + +include cur in +theorem Current.expand {w c : ℕ} (hc : c * 2 ^ J ≤ p.overhead) + (hw : w ≤ Q.template.scheme.m + Q.template.scheme.h + J) : + c * 2 ^ w ≤ p.overhead ^ (i + 1) * v.allocation m := calc + _ ≤ c * 2 ^ (Q.template.scheme.m + Q.template.scheme.h + J) := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide) hw) + _ = (c * 2 ^ J) * 2 ^ (Q.template.scheme.m + Q.template.scheme.h) := by rw [pow_add]; ring + _ ≤ p.overhead * (p.overhead ^ i * v.allocation m) := Nat.mul_le_mul hc cur.seats + _ = _ := by rw [pow_succ]; ring + +include cur in +theorem Current.height_le : Q.template.scheme.h ≤ v.blocks := by have := cur.blocks; omega + +include cur in +theorem Current.long {C B : ℕ} (fit : v.Fits n B C) (hi : i ≤ v.j) (hm : m ≤ n ^ 2) : + Q.template.scheme.m + Q.template.scheme.h ≤ 4 * Nat.clog 2 n := by + apply fit.address hm hi + exact cur.seats.trans (Nat.mul_le_mul_right _ + (Nat.pow_le_pow_right (by have := p.overhead_large; omega) (Nat.le_succ _))) + +include cur in +theorem Current.slack (hi : i ≤ v.j) {k : ℕ} (hk : k ≤ p.overhead) : + (k : ℝ) * (v.width i : ℝ) * (2 ^ (Q.template.scheme.m + Q.template.scheme.h) : ℕ) + ≤ v.budget m i * (2 : ℝ) ^ v.group := by + have h := Levels.slack hi (cur.expand (J := 0) (by simpa using hk) le_rfl) + simpa only [Nat.cast_mul, mul_right_comm, add_zero] using h + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Instantiating the initial stack at the chosen levels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly + +variable {δ : ℝ} {p : Design δ} {M n m B C E T₀ : ℕ} {v : Levels p M} + {a b ξ : ℝ} {s : Plan} {F : Type} [Field F] [Fintype F] {x y : Wire} + +private theorem dictionary_le_box (fit : v.Fits n B C) : + Shaving.dictionary n ≤ 2 ^ (v.box 2) := by + have hcl : Nat.clog 2 (Nat.clog 2 n) ≤ v.height := Nat.clog_le_of_le_pow fit.height + have hx : v.height ≤ v.span := Nat.le_add_left .. + have hy : v.span ≤ (2 : ℕ) ^ v.j := + (Nat.le_mul_of_pos_left _ (by omega : 0 < B + 4)).trans fit.span + have h := Nat.pow_le_pow_left ((hcl.trans hx).trans hy) 2 + rw [← pow_mul] at h + apply Nat.pow_le_pow_right (by decide) + exact h.trans (Nat.pow_le_pow_right (by decide) (by omega)) + +omit [Field F] in +theorem startup_labels_of_box (fit : v.Fits n B C) + {L : ℕ} (labels : L ≤ 2 ^ (v.box 2)) + (hF : Fintype.card F ≤ (Nat.clog 2 n) ^ B) + (allow : 15 + 8 * B + Nat.clog 2 (Nat.card Stack.Device.Guide) ≤ E) : + Nat.clog 2 (1 + (L + 16 * Fintype.card F ^ 8) * 4 * (1 + 2 ^ v.stack) * (v.stack + 1)* + Nat.card Stack.Device.Guide) ≤ v.box E := by + have hcard : Fintype.card F ≤ 2 ^ (B * v.height) := by + rw [mul_comm, pow_mul] + exact hF.trans (Nat.pow_le_pow_left fit.height _) + let g := Nat.clog 2 (Nat.card Stack.Device.Guide) + let D := 13 + 8 * B + g + have hspan : v.span ≤ v.box 2 := + ((Nat.le_mul_of_pos_left _ (by omega : 0 < B + 4)).trans fit.span).trans + (Nat.pow_le_pow_right (by decide) (by omega)) + have ht : v.stack ≤ v.box 2 := (show v.stack ≤ v.span by unfold Levels.span; omega).trans hspan + have hh : v.height ≤ v.box 2 := (Nat.le_add_left ..).trans hspan + have hb : 0 < v.box 2 := Nat.two_pow_pos _ + have hbound : v.box 2 + 8 * (B * v.height) + 2 * v.stack + g + 10 ≤ D * v.box 2 := by + have := Nat.mul_le_mul_left (8 * B) hh + have := Nat.le_mul_of_pos_right (g + 10) hb + unfold D + simp only [add_mul, mul_assoc] at * + omega + have he : D + 2 ≤ E := by unfold D g; omega + exact (Stack.label_bits labels hcard).trans (hbound.trans + ((Nat.mul_le_mul_right _ (v.le_box D)).trans + ((v.box_add D 2).symm.le.trans (v.box_mono he)))) + +theorem startup_labels {F : Type} [Fintype F] (fit : v.Fits n B C) + {L : ℕ} (labels : L ≤ Shaving.dictionary n) + (hF : Fintype.card F ≤ (Nat.clog 2 n) ^ B) + (allow : 15 + 8 * B + Nat.clog 2 (Nat.card Stack.Device.Guide) ≤ E) : + Nat.clog 2 (1 + (L + 16 * Fintype.card F ^ 8) * 4 * (1 + 2 ^ v.stack) * (v.stack + 1)* + Nat.card Stack.Device.Guide) ≤ v.box E := + startup_labels_of_box fit (labels.trans (dictionary_le_box fit)) hF allow + +theorem starting_layer_of_box (ok : v.Suits n T₀ a b ξ) (fit : v.Fits n B C) + (hb : 0 < b) (hm : n ≤ m) (hD : 8 ≤ s.D) (hθ : s.floor ≤ 4) + (hF : Fintype.card F ≤ (Nat.clog 2 n) ^ B) + (allow : 15 + 8 * B + Nat.clog 2 (Nat.card Stack.Device.Guide) ≤ E) + (G : Diagram F x y) {u : ℕ} {L : Finset (Table F)} + (hints : G.Admits u L) (size : G.cost ≤ m) (labels : L.card ≤ 2 ^ (v.box 2)) + (arity : (u : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ b) : + ∃ (P : Layer F (copies x v.batch) (copies y v.batch)) (i : P.State) (z : F), + (fun f g => z * (P.graph i).eval f g) = power G.eval v.batch ∧ + v.Current s n m 0 E P ∧ P.template.count = 0 := by + have hh : 1 < (Nat.clog 2 n : ℝ) := ok.2.1 + have ht' : (Nat.clog 2 n : ℝ) ^ b ≤ (2 : ℝ) ^ v.stack := ok.2.2.2.2.1 + have hpos : 0 < v.stack := by + by_contra! h + have hz := Nat.eq_zero_of_le_zero h + rw [hz, pow_zero] at ht' + exact (Real.one_lt_rpow hh hb).not_ge ht' + have hn : 0 < n := by + by_contra! h + have hz := Nat.eq_zero_of_le_zero h + norm_num [hz] at hh + have hu : u ≤ 2 ^ v.stack := by exact_mod_cast arity.trans ht' + obtain ⟨P, i, z, exactPower, ready, loopless, addr, blk, deg, port, l, ct, vol, ht⟩ := + Stack.start G hints size hpos hu hD hθ + have bits : P.template.scheme.ℓ ≤ v.box E := l.le.trans (startup_labels_of_box fit labels hF + allow) + exact ⟨P, i, z, exactPower, initial (hn.trans_le hm) hm ready loopless addr blk deg port bits ct + vol ht, ct⟩ + +theorem starting_layer (ok : v.Suits n T₀ a b ξ) (fit : v.Fits n B C) + (hb : 0 < b) (hm : n ≤ m) (hD : 8 ≤ s.D) (hθ : s.floor ≤ 4) + (hF : Fintype.card F ≤ (Nat.clog 2 n) ^ B) + (allow : 15 + 8 * B + Nat.clog 2 (Nat.card Stack.Device.Guide) ≤ E) + (G : Diagram F x y) {u : ℕ} {L : Finset (Table F)} + (hints : G.Admits u L) (size : G.cost ≤ m) (labels : L.card ≤ Shaving.dictionary n) + (arity : (u : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ b) : + ∃ (P : Layer F (copies x v.batch) (copies y v.batch)) (i : P.State) (z : F), + (fun f g => z * (P.graph i).eval f g) = power G.eval v.batch ∧ + v.Current s n m 0 E P ∧ P.template.count = 0 := + starting_layer_of_box ok fit hb hm hD hθ hF allow G hints size (labels.trans (dictionary_le_box + fit)) arity + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # The initialization budget of the realized stack -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly + +variable {δ : ℝ} {p : Design δ} {M n m B C E q : ℕ} {v : Levels p M} + {s : Plan} {F : Type} [Field F] {x y : Wire} + {P : Layer F (copies x v.batch) (copies y v.batch)} + +theorem Current.init_budget (cur : v.Current s n m 0 E P) + (fit : v.Fits n B C) (empty : P.template.count = 0) + (upper : m ≤ n ^ 2) (reserve : 1 ≤ M) + (hmeta : E ≤ q * p.groupRate) (hE : 1 ≤ E) + (const : s.d + s.p + 1 ≤ 2 ^ v.j) {J : ℝ} (hJ : 0 ≤ J) + (hh : 1 ≤ (Nat.clog 2 n : ℝ)) (hl : 1 ≤ Real.log (Nat.clog 2 n)) + (height : (P.height : ℝ) + 1 ≤ J * (Real.log (Nat.clog 2 n)) ^ 2) : + let h : ℝ := Nat.clog 2 n + ((140 * (P.snapshot.port.width + v.batch * (wd x + wd y)) + 1 : ℕ) : ℝ) ≤ + (10000 + 280 * J + 140) * (Real.log h) ^ 2 * v.expense h m (wd x + wd y) q := by + let h : ℝ := Nat.clog 2 n + let W := (10000 + 280 * J + 140) * (Real.log h) ^ 2 + let addr := P.template.scheme.m + let nb := P.template.scheme.h + let e := wd x + wd y + let long := 140 * (8 * (addr + 2) + 2) + 1 + let short := 140 * (P.template.scheme.ℓ + 2 * (P.height + 1)) + let ext := 140 * (2 * (P.height + 1) + 1) + have hm₀ : 2 ^ (addr + nb) ≤ v.allocation m := by + simpa only [pow_zero, one_mul] using cur.seats + have hbase : 1 ≤ p.overhead := (by decide : 1 ≤ 2).trans p.overhead_large + have hm₁ : 2 ^ addr ≤ p.overhead ^ (0 + 1) * v.allocation m := + (Nat.pow_le_pow_right (by decide) (Nat.le_add_right ..)).trans + (hm₀.trans (Nat.le_mul_of_pos_left _ (by positivity))) + have hm₂ : addr ≤ 4 * Nat.clog 2 n := fit.address upper (Nat.zero_le _) hm₁ + have hr : v.remaining ≤ nb := by + dsimp only [nb] + rw [cur.left (Nat.zero_le _)] + exact Nat.le_add_right .. + have seats : 2 ^ (addr + nb) ≤ p.overhead ^ v.j * v.allocation m := + hm₀.trans (Nat.le_mul_of_pos_left _ (by positivity)) + have hhi : P.volume = 2 ^ addr + v.batch * e := by + simpa only [addr, e, wd_copies, Nat.mul_add, Nat.add_assoc] using cur.volume + have actual := Stack.start_cost P (H:=2 ^ addr) (B:=nb) le_rfl rfl cur.degree empty hhi + have pay : 140 * (P.snapshot.port.width + v.batch * e) + 1 ≤ + 2 ^ addr * long + 2 ^ (addr + nb) * short + v.batch * e * ext := calc + _ ≤ 140 * (2 ^ addr * (8 * (addr + 2) + 2) + 2 ^ addr * 2 ^ nb * (P.template.scheme.ℓ + + 2 * (P.height + 1)) + + (2 * (P.height + 1) + 1) * (v.batch * e)) + 1 := actual + _ ≤ 140 * (2 ^ addr * (8 * (addr + 2) + 2) + 2 ^ addr * 2 ^ nb * (P.template.scheme.ℓ + + 2 * (P.height + 1)) + + (2 * (P.height + 1) + 1) * (v.batch * e)) + 2 ^ addr + := by gcongr; exact Nat.one_le_iff_ne_zero.mpr (by positivity) + _ = _ := by rw [pow_add]; unfold long short ext; ring + have hlog : 0 ≤ Real.log h := zero_le_one.trans hl + have hlog₂ : 1 ≤ (Real.log h) ^ 2 := one_le_pow₀ hl + have wbig : 10000 ≤ W := by + unfold W + exact le_trans (show (10000 : ℝ) ≤ 10000 + 280 * J + 140 by linarith) + (le_mul_of_one_le_right (by positivity) hlog₂) + have hl₁ : (long : ℝ) ≤ W * h ^ M := calc + _ ≤ 10000 * h := by + have hraddr : (addr : ℝ) ≤ 4 * h := by unfold h; exact_mod_cast hm₂ + unfold long; push_cast + linarith only [hraddr, hh] + _ ≤ W * h ^ M := mul_le_mul wbig + (by simpa only [pow_one] using (pow_le_pow_right₀ hh reserve)) (by positivity) (by positivity) + have hspan : v.span ≤ 2 ^ v.j := (Nat.le_mul_of_pos_left _ (by omega : 0 < B + 4)).trans fit.span + have hbox₁ : 2 ^ v.j ≤ v.box 1 := by + unfold Levels.box + rw [one_mul] + exact Nat.pow_le_pow_right (by decide) (by omega) + have hbox : 2 ^ v.j ≤ v.box E := hbox₁.trans (v.box_mono hE) + have ht : P.height + 1 ≤ 2 * v.box E := by + have h₁ := cur.height + have h₂ := hspan.trans hbox + have h₃ := const.trans hbox + omega + have hlen : P.template.scheme.ℓ ≤ v.box E := by + simpa only [empty, add_zero, pow_zero, one_mul] using cur.labels + have hs₁ : short ≤ 700 * 2 ^ (q * v.group) := calc + _ ≤ 700 * v.box E := by + unfold short + omega + _ ≤ _ := Nat.mul_le_mul_left _ (v.box_le_group_power hmeta) + have hs₂ : (short : ℝ) ≤ W * (2 : ℝ) ^ (q * v.group) := calc + _ ≤ 700 * (2 : ℝ) ^ (q * v.group) := by exact_mod_cast hs₁ + _ ≤ _ := mul_le_mul_of_nonneg_right (le_trans (by norm_num) wbig) (by positivity) + have he₁ : (ext : ℝ) ≤ W := by + unfold ext W + push_cast + nlinarith only [height, hlog₂] + exact v.phase_expense (by linarith) (by linarith : 0 ≤ W) hr seats pay hl₁ hs₂ he₁ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Terminal.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Terminal.lean new file mode 100644 index 0000000000..e6c42e9126 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Levels/Terminal.lean @@ -0,0 +1,943 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Passage +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Pass +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Levels.Log +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Status +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Stack.Mates +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Sweep + +/-! +# Keeping the dependence on prior labels linear + +The base of the polynomial part of the restored label size uses +only the logarithm of the inherited selectors. Its exponent is +independent of the coefficient allowed for linear growth. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly Contraction + +variable {δ : ℝ} {p : Design δ} {M : ℕ} (v : Levels p M) {F : Type} [Field F] {x y : Wire} + +/-- The data for the frame bound construction, including `ports`, `height`, `labels`. -/ +structure FrameBound (Q : Layer F x y) (D : Template F) (payload K : ℕ) : Prop where + ports : 2 ^ D.scheme.e ≤ v.box K + height : payload ≤ v.box K + labels : D.scheme.ℓ + D.count ≤ K * (Q.template.scheme.ℓ + Q.template.count) + v.box K + +theorem pow_le_box (t : ℕ) : 2 ^ t ≤ v.box t := + Nat.pow_le_pow_right (by decide) (Nat.le_mul_of_pos_right _ (by omega)) + +theorem box_sum {a b c : ℕ} (h : a ≤ v.box c) (h' : b ≤ v.box c) : + a + b ≤ v.box (c + 1) := by + rw [box_add] + refine (Nat.add_le_add h h').trans ?_ + rw [← Nat.mul_two] + exact Nat.mul_le_mul_left _ (v.pow_le_box 1) + +theorem log_box {a k : ℕ} (ha : a ≤ v.box k) (hk : k ≤ 2 ^ v.j) : + Nat.clog 2 (1 + a) ≤ v.box 2 := by + have hn : Nat.clog 2 (1 + a) ≤ k * (v.j + 1) + 1 := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_succ] + have := Nat.two_pow_pos (k * (v.j + 1)) + unfold box at ha + omega + have hh := Nat.mul_le_mul hk (show v.j + 1 ≤ 2 ^ v.j from Nat.lt_two_pow_self) + refine hn.trans ((Nat.add_le_add_right hh 1).trans ?_) + rw [box, show 2 * (v.j + 1) = (v.j + v.j) + 2 by omega, ← pow_add, pow_add _ _ 2] + have := Nat.two_pow_pos (v.j + v.j) + omega + +theorem log_width {i z : ℕ} (hi : i ≤ v.j) (hz : z ≤ v.width i) : + Nat.clog 2 (1 + z) ≤ 1 + v.stack + p.growth * v.j := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [width_eq] at hz + have hk : 2 ^ (v.stack + p.growth * i) ≤ (2 : ℕ) ^ (v.stack + p.growth * v.j) := by gcongr + rw [add_assoc, pow_add, pow_one] + have ht := Nat.two_pow_pos (v.stack + p.growth * v.j) + omega + +namespace FrameBound +variable {v} {s : Plan} {m i E z payload K n B C : ℕ} + {Q : Layer F x y} {D : Template F} (f : v.FrameBound Q D payload K) + (cur : v.Current s n m i E Q) (hi : i ≤ v.j) + +include f cur hi + +theorem bits : D.scheme.ℓ + D.count ≤ v.box (K + 2 * E + 1) := by + refine f.labels.trans (v.box_sum ?_ (v.box_mono (Nat.le_add_right ..))) + rw [v.box_add, two_mul] + exact Nat.mul_le_mul (v.le_box _) (cur.bits hi) + +variable (h : v.Fits n B C) (hh : D.scheme.h ≤ v.blocks) (hz : z ≤ v.width i) + (hk : K + 2 * E + 1 ≤ 2 ^ v.j) +include h hh hz hk + +theorem base_le : BoundaryScale.base D z payload v.group ≤ v.box (K + p.groupRate + 5) := by + have hl := v.log_width hi hz + have hd := v.log_box (f.bits cur hi) hk + let N := v.box (K + p.groupRate + 2) + have hN : 2 ^ v.group ≤ N := v.box_mono (by omega) + have hK : v.box K ≤ N := v.box_mono (by omega) + have hd' : v.box 2 ≤ N := v.box_mono (by omega) + have hv : 4 * (100 + v.stack + p.growth * v.j + v.blocks + v.height) ≤ N := h.four_span.trans hN + have h' : BoundaryScale.base D z payload v.group ≤ N * 8 := by + have := f.ports.trans hK + have := f.height.trans hK + unfold BoundaryScale.base + rw [add_assoc 1 D.scheme.ℓ] + omega + rw [show K + p.groupRate + 5 = (K + p.groupRate + 2) + 3 by omega, v.box_add] + exact h'.trans (Nat.mul_le_mul_left _ (v.pow_le_box 3)) + +theorem metadata_le : BoundaryScale.metadata D z payload v.group ≤ v.box (K + 2 * E + p.groupRate + + 6) := by + have hb := f.base_le cur hi h hh hz hk + have hl := f.bits cur hi + rw [BoundaryScale.metadata, add_assoc, show K + 2 * E + p.groupRate + 6 = (K + 2 * E + + p.groupRate + 5) + 1 by omega] + exact v.box_sum (hb.trans (v.box_mono (by omega))) (hl.trans (v.box_mono (by omega))) + +end FrameBound +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Uniform applicability of a contraction and restoration phase -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly Contraction + +variable {δ : ℝ} {p : Design δ} {M : ℕ} {v : Levels p M} {s : Plan} + {F : Type} [Field F] {x y : Wire} {D : Template F} {Q : Layer F x y} + {n m i B C E J K H d z payload : ℕ} {price : Prices F} + +/-- First choose the overhead from the constant address costs, then +the coefficient of linear label growth, then the smallness exponent. -/ +structure Admissible (p : Design δ) (s : Plan) (J K H E C : ℕ) : Prop where + steps : p.steps = s.n + 1 + growth : p.growth = s.p + gain : p.gain = s.v + input : s.K * 2 ^ J ≤ p.overhead + output : 2 ^ (J + H) ≤ p.overhead + margin : K ≤ E + factor : H * (K + 1) + 1 ≤ E + additive : (K + p.groupRate + 5) * H ≤ E + exponent : (K + 2 * E + p.groupRate + 6) * H ≤ C + +namespace Current +variable (cur : v.Current s n m i E Q) (f : v.Passage Q D J) + (data : v.FrameBound Q D payload K) (ok : Admissible p s J K H E C) + (h : v.Fits n B C) (hi : i < v.j) (hk : K + 2 * E + 1 ≤ 2 ^ v.j) +include cur f data ok h hi hk + +theorem requirements (hs : s.Fits) (unit : 0 < s.b) (overhead : 0 < s.K) (hm : n ≤ m) (hm' : m + ≤ n ^ 2) + (hz : 0 < z) (hsmall : (s.b * z) * s.D ^ s.c ≤ v.width i) (hbig : v.width i ≤ z * s.M) + (hd : D.scheme.d ≤ d) (hslot : D.scheme.k = 0) + (field : Nat.card F ≤ (Nat.clog 2 n) ^ B) (space : 16 * Nat.clog 2 n ≤ price.w) : + Requirements D s (v.width i) (v.budget m i) z payload price v.group d H := by + have axes : D.scheme.m + D.scheme.h ≤ Q.template.scheme.m + Q.template.scheme.h + J := by + have := f.height + have := f.upper + omega + have seats := cur.expand ok.input axes + have addr := h.address hm' hi.le ((Nat.le_mul_of_pos_left _ overhead).trans seats) + have small : s.K ≤ p.overhead := (Nat.le_mul_of_pos_right _ (by positivity)).trans ok.input + have size : D.scheme.h ≤ v.blocks := by have := cur.height_le; have := f.height; omega + have lower : z ≤ v.width i := + ((Nat.le_mul_of_pos_left _ unit).trans + (Nat.le_mul_of_pos_right _ (pow_pos (by have := s.two hs; omega) _))).trans hsmall + have hmeta := data.metadata_le cur hi.le h size lower hk + refine ⟨h.one_le_budget hm hi.le, hz, hsmall, hbig, ?_, + (small.trans v.overhead_le_group).trans Nat.lt_two_pow_self.le, ?_, hd, hslot, + h.alphabet field, ?_, by omega⟩ + · have hh := cur.enough hi + rw [ok.steps, add_mul, one_mul, ← f.height] at hh + exact Nat.le_of_add_le_add_right hh + · simpa only [Nat.cast_mul, mul_right_comm] using Levels.slack hi.le seats + · refine (Nat.pow_le_pow_left hmeta H).trans ?_ + rw [← v.box_mul] + exact ((v.box_mono ok.exponent).trans h.small).trans (cur.address.trans f.lower) + +end Current +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Preservation of the round invariant through concentration and restoration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly Contraction + +variable {δ : ℝ} {p : Design δ} {M : ℕ} {v : Levels p M} {s : Plan} + {F : Type} [Field F] {x y : Wire} {D : Template F} {Q : Layer F x y} + {n m i B C E J K H d z payload : ℕ} {price : Prices F} + +namespace Current +variable (cur : v.Current s n m i E Q) (f : v.Passage Q D J) (data : v.FrameBound Q D payload K) + (ok : Admissible p s J K H E C) (h : v.Fits n B C) (hi : i < v.j) + (hk : K + 2 * E + 1 ≤ 2 ^ v.j) (hz : z ≤ v.width i) + (result : Restored (x := x) (y := y) D s (v.width i) (v.budget m i) z payload price v.group H) + +include cur f data ok h hi hk hz + +private theorem restored_labels : + result.next.template.scheme.ℓ + result.next.template.count ≤ E ^ (i + 1) * v.box E := by + let a := E ^ i * v.box E + have hE : 0 < E := by have := ok.factor; omega + have hp : v.box E ≤ a := Nat.le_mul_of_pos_left _ (pow_pos hE _) + have hf : D.scheme.h ≤ v.blocks := by have := f.height; have := cur.height_le; omega + have hbase := data.base_le cur hi.le h hf hz hk + have hb : BoundaryScale.base D z payload v.group ^ H ≤ a := by + refine (Nat.pow_le_pow_left hbase H).trans ?_ + rw [← v.box_mul] + exact (v.box_mono ok.additive).trans hp + have hmeta : D.scheme.ℓ + D.count ≤ K * a + a := + data.labels.trans (Nat.add_le_add (Nat.mul_le_mul_left _ cur.labels) ((v.box_mono + ok.margin).trans hp)) + calc + _ ≤ H * (D.scheme.ℓ + D.count) + BoundaryScale.base D z payload v.group ^ H := result.labels + _ ≤ H * (K * a + a) + a := Nat.add_le_add (Nat.mul_le_mul_left _ hmeta) hb + _ = (H * (K + 1) + 1) * a := by ring + _ ≤ E * a := Nat.mul_le_mul_right _ ok.factor + _ = _ := by unfold a; rw [pow_succ]; ring + +theorem advance : v.Current s n m (i + 1) E result.next where + ready := by + simpa only [budget, width, Design.width_succ, Design.budget_succ, ok.growth, ok.gain] + using result.ready + loopless := result.loopless + address := (cur.address.trans f.lower).trans result.lower + blocks := by + have ht : p.steps * (i + 1) * v.group = p.steps * i * v.group + s.n * v.group + v.group + := by rw [ok.steps]; ring + have := cur.blocks + have := f.height + have := result.blocks + omega + seats := by + have hw : result.next.template.scheme.m + result.next.template.scheme.h ≤ + Q.template.scheme.m + Q.template.scheme.h + (J + H) := by + have := f.height + have := f.upper + have := result.seats + omega + simpa only [one_mul] using cur.expand (c := 1) (by rw [one_mul]; exact ok.output) hw + ports := result.ports + degree := result.degree + volume := result.volume + height := by + have ht : Nat.clog 2 (v.width i) ≤ 1 + v.stack + p.growth * v.j := + (Nat.clog_mono_right _ (Nat.le_add_left _ 1)).trans (v.log_width hi.le le_rfl) + have := cur.height_le + have := f.height + have := result.blocks + have := result.height + unfold span + omega + labels := cur.restored_labels f data ok h hi hk hz result + +end Current +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Choosing a common round design and its label exponent -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +variable {δ : ℝ} + +theorem Plan.choose_design (s : Plan) (J K H E₀ C₀ : ℕ) (hD : 8 ≤ s.D) + (hv : 0 < s.v) (hp : 0 < s.p) (ratio : (s.p : ℝ) ≤ s.v * (1 + δ / 3)) : + ∃ (p : Design δ) (E C : ℕ), Levels.Admissible p s J K H E C ∧ p.D = s.D ∧ + p.floor = s.floor ∧ E₀ ≤ E ∧ C₀ ≤ C ∧ s.D ≤ p.overhead := by + have hm : 1 ≤ (s.M : ℝ) := by + exact_mod_cast (show 1 ≤ s.M by unfold Plan.M; exact Nat.one_le_pow _ _ (by omega)) + have hden : 1 ≤ (s.M : ℝ) * (2 : ℝ) ^ s.p := + one_le_mul_of_one_le_of_one_le hm (one_le_pow₀ (by norm_num)) + let p : Design δ := + { D := s.D, steps := s.n + 1, gain := s.v, growth := s.p + overhead := max s.D (max (s.K * 2 ^ J) (2 ^ (J + H))), floor := s.floor + large := hD, steps_pos := by omega, gain_pos := hv, growth_pos := hp + overhead_large := (show 2 ≤ s.D by omega).trans (le_max_left _ _), ratio := ratio + floor_pos := by unfold Plan.floor; positivity + floor_le := (one_div_le_one_div_of_le (by norm_num) hden).trans (by norm_num) } + let E := max (max E₀ K) (max (H * (K + 1) + 1) ((K + p.groupRate + 5) * H)) + let C := max C₀ ((K + 2 * E + p.groupRate + 6) * H) + refine ⟨p, E, C, ⟨rfl, rfl, rfl, ?_, ?_, ?_, ?_, ?_, le_max_right _ _⟩, rfl, rfl, ?_, + le_max_left _ _, le_max_left _ _⟩ + · exact (le_max_left _ _).trans (le_max_right _ _) + · exact (le_max_right _ _).trans (le_max_right _ _) + all_goals unfold E; omega + +theorem Design.small_exponent (p : Design δ) {C q : ℕ} (hq : 2 * C + 1 ≤ q) + {a β : ℝ} (ha : 0 < a) (hβ : β ≤ 1 / 2) (h : (p.groupRate + p.groupRate * q + 1 : ℕ) * a < β) : + 4 * a * (p.groupRate + C : ℕ) ≤ 1 := by + have hg : 1 ≤ p.groupRate := by unfold Design.groupRate; have := p.overhead_large; omega + have hn : 2 * (p.groupRate + C) ≤ p.groupRate + p.groupRate * q + 1 := by + nlinarith only [Nat.mul_le_mul_left p.groupRate hq, Nat.mul_le_mul_right C hg] + have hh := mul_le_mul_of_nonneg_right (Nat.cast_le.mpr hn : (_ : ℝ) ≤ _) ha.le + push_cast at hh h ⊢ + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Simultaneous cutoff for the chosen stage parameters -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels + +open Filter + +variable {δ : ℝ} {p : Design δ} + +theorem Admissible.enlarge {s : Plan} {J K H E C D : ℕ} + (h : Admissible p s J K H E C) (hd : C ≤ D) : + Admissible p s J K H E D := + ⟨h.steps, h.growth, h.gain, h.input, h.output, h.margin, h.factor, h.additive, + h.exponent.trans hd⟩ + +theorem funded_levels (p : Design δ) (M B C T₀ extra margin : ℕ) + {a b ξ : ℝ} (hδ : δ ≤ 1) (ha : 0 < a) (ha' : a ≤ 1) + (hb : 0 < b) (hb' : b ≤ 1) (hξ : 0 < ξ) + (small : 4 * a * (p.groupRate + C : ℕ) ≤ 1) : + ∃ J : ℝ, 0 ≤ J ∧ ∀ᶠ n : ℕ in atTop, + 2 ≤ (Nat.clog 2 n : ℝ) ∧ 1 ≤ Real.log (Nat.clog 2 n) ∧ + ∃ v : Levels p M, v.Suits n T₀ a b ξ ∧ v.Fits n B C ∧ + margin ≤ 2 ^ v.j ∧ ((v.span + extra : ℕ) : ℝ) ≤ J * (Real.log (Nat.clog 2 n)) ^ 2 := by + obtain ⟨J, hJ, span⟩ := eventual_span_log p M extra ha ha' + refine ⟨J, hJ, ?_⟩ + filter_upwards [Design.levels p hδ T₀ M ha ha' hb hb' hξ, + eventually_fits p M B C ha small, eventually_rounds p M ha margin, span, + Shaving.tendsto_height.eventually_ge_atTop 2, + (Real.tendsto_log_atTop.comp Shaving.tendsto_height).eventually_ge_atTop 1] + with n ex fit big bound hh hl + obtain ⟨v, ok⟩ := ex + exact ⟨hh, hl, v, ok, fit v T₀ b ξ hb' ok, + (big v T₀ b ξ ok).trans Nat.lt_two_pow_self.le, bound v T₀ b ξ hb' ok⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Resources for the grouped input to local concentration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly + +variable {δ : ℝ} {p : Design δ} {M : ℕ} (v : Levels p M) (s : Plan) + +/-- The quantity computed by `(B + 2) * v.span + s.d + s.p`. -/ +def precision (B : ℕ) := (B + 2) * v.span + s.d + s.p +/-- The quantity computed by `2 ^ (Template.Presents.Plan.depth s.D s.floor + 5 + 2)`. -/ +def binBits := 2 ^ (Template.Presents.Plan.depth s.D s.floor + 5 + 2) +/-- The construction uses `Template.Presents.Plan.depth s.D s.floor` for its intermediate `t`. -/ +def binFactor := + let t := Template.Presents.Plan.depth s.D s.floor + let c := Template.Sheet.slots s.D + 2 ^ t * (1 + c + 32 * (s.D ^ 10 + (c + t))) + +variable {v s} {F : Type} [Field F] {x y : Wire} {Q : Layer F x y} {n m i E B C a R : ℕ} + (cur : v.Current s n m i E Q) (fit : v.Fits n B C) + +theorem Fits.precision (fit : v.Fits n B C) (hs : s.d + s.p ≤ 2 ^ v.j) : v.precision s B ≤ v.box 1 + := by + have h := (Nat.mul_le_mul_right v.span (show B + 2 ≤ B + 4 by omega)).trans fit.span + unfold Levels.precision box + rw [one_mul, pow_succ] + omega + +include cur in +theorem Current.precision : Q.height ≤ v.precision s B := by + have hx : v.span ≤ (B + 2) * v.span := Nat.le_mul_of_pos_left _ (by omega) + exact cur.height.trans (Nat.add_le_add_right (Nat.add_le_add_right hx _) _) + +include fit in +theorem Fits.field {t : ℕ} (ht : t ≤ (Nat.clog 2 n) ^ B) : t ≤ 2 ^ (v.precision s B) := by + have hx : v.height ≤ v.span := Nat.le_add_left .. + refine (ht.trans (Nat.pow_le_pow_left fit.height _)).trans ?_ + rw [← pow_mul, mul_comm v.height] + apply Nat.pow_le_pow_right (by decide) + unfold Levels.precision + have := Nat.mul_le_mul (show B ≤ B + 2 by omega) hx + omega + +theorem width_precision (hi : i ≤ v.j) : v.width i ≤ 2 ^ (v.precision s B) := by + rw [v.width_eq] + apply Nat.pow_le_pow_right (by decide) + have hs : v.stack + p.growth * i ≤ v.span := by + have := Nat.mul_le_mul_left p.growth hi + unfold span + omega + unfold precision + have := Nat.le_mul_of_pos_left v.span (show 0 < B + 2 by omega) + omega + +variable (b : Q.template.Binning a s.D (v.width i) R s.floor) + +include cur in +theorem Current.binBits : 2 ^ b.target.e ≤ binBits s := by + rw [b.shape.2.2.2.2] + unfold Levels.binBits + exact Nat.pow_le_pow_right (by decide) (Nat.add_le_add_right (Nat.add_le_add_left cur.ports _) _) + +include cur in +theorem Current.binLabel : b.target.ℓ ≤ binFactor s * (Q.template.scheme.ℓ + 1) := by + have hd := b.nav_bound (by rw [cur.degree]; decide) + have hn := (Nat.le_add_right b.target.d 1).trans (Nat.lt_two_pow_self.le.trans hd) + have he : (2 : ℕ) ^ Q.template.scheme.e ≤ 32 := Nat.pow_le_pow_right (by decide) cur.ports + let c := Template.Sheet.slots s.D + let t := b.depth + let a := 32 * (s.D ^ 10 + (c + t)) + rw [b.fields] + calc + _ ≤ 2 ^ t * (c + (Q.template.scheme.ℓ + a)) := by unfold a; gcongr + _ ≤ 2 ^ t * ((1 + c + a) * (Q.template.scheme.ℓ + 1)) := by + apply Nat.mul_le_mul_left + simp only [add_mul, mul_add, one_mul, mul_one] + omega + _ = _ := by rw [← mul_assoc]; rfl + +include cur fit in +theorem Current.binSpace (hi : i ≤ v.j) (hm : m ≤ n ^ 2) {J w : ℕ} + (hk : J + s.d + s.p + 1 ≤ 2 ^ v.j) (hw : 16 * Nat.clog 2 n ≤ w) : + b.target.m + Q.height + J ≤ w := by + have hy := cur.long fit hi hm + have hs := fit.four_span.trans fit.group + have hd := hk.trans ((Nat.pow_le_pow_right (by decide) v.rounds_le_group).trans fit.group) + have ht := cur.height + rw [b.shape.1] + omega + +theorem Passage.fromBin {D : Template F} {J : ℕ} (ha : a + v.group = Q.template.scheme.h) + (hh : D.scheme.h = a) (lo : b.target.m ≤ D.scheme.m) (up : D.scheme.m ≤ b.target.m + J) : + v.Passage Q D (1 + J) := by + rw [b.shape.1] at lo up + exact ⟨by omega, by omega, by omega⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Absorbing the grouped table and the fresh sphere data -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly + +variable {δ : ℝ} {p : Design δ} {M : ℕ} {v : Levels p M} {s : Plan} {F : Type} [Field F] + {x y : Wire} + {Q : Layer F x y} {D : Template F} {n m i E B C a R J : ℕ} + (cur : v.Current s n m i E Q) (fit : v.Fits n B C) + (b : Q.template.Binning a s.D (v.width i) R s.floor) + +/-- The quantity computed by `J * (binFactor s + 2) + 1`. -/ +def frameRate (s : Plan) (J : ℕ) := J * (binFactor s + 2) + 1 + +include cur fit in +theorem Current.fromBin (hs : s.d + s.p ≤ 2 ^ v.j) (ports : 2 ^ D.scheme.e ≤ J) + (labels : D.scheme.ℓ + D.count ≤ J * (b.target.ℓ + 1 + v.precision s B)) : + v.FrameBound Q D Q.height (frameRate s J) := by + let k := binFactor s + let r := J * (k + 2) + let l := Q.template.scheme.ℓ + Q.template.count + have hr : frameRate s J = r + 1 := rfl + have ht := fit.precision hs + have hJ : J ≤ r := Nat.le_mul_of_pos_right _ (by omega) + have h₁ : 1 ≤ v.box 1 := v.le_box _ + have front : b.target.ℓ + 1 + v.precision s B ≤ (k + 2) * (l + v.box 1) := calc + _ ≤ k * (Q.template.scheme.ℓ + 1) + 1 + v.box 1 := by gcongr; exact cur.binLabel b + _ ≤ k * (l + v.box 1) + v.box 1 + v.box 1 := by gcongr; exact Nat.le_add_right .. + _ ≤ _ := by rw [add_mul, two_mul]; omega + rw [hr] + refine ⟨(ports.trans (hJ.trans (Nat.le_succ _))).trans (v.le_box _), + (cur.precision.trans ht).trans (v.box_mono (by omega)), ?_⟩ + calc + _ ≤ J * (b.target.ℓ + 1 + v.precision s B) := labels + _ ≤ J * ((k + 2) * (l + v.box 1)) := Nat.mul_le_mul_left _ front + _ = r * l + r * v.box 1 := by rw [← mul_assoc, mul_add] + _ ≤ (r + 1) * l + v.box r * v.box 1 := + Nat.add_le_add (Nat.mul_le_mul_right _ (Nat.le_succ _)) (Nat.mul_le_mul_right _ (v.le_box _)) + _ = _ := by rw [← box_add] + +include cur in +theorem Current.terminal (hi : i = v.j) : + Q.Ready s.D v.finalWidth (8 * v.finalBudget m) s.floor ∧ + Q.template.scheme.h = v.remaining ∧ + 2 ^ Q.template.scheme.m * 2 ^ v.remaining ≤ p.overhead ^ v.j * v.allocation m ∧ + Q.template.scheme.ℓ + Q.template.count ≤ v.box (E + E) := by + subst i + have hh : Q.template.scheme.h = v.remaining := by + simpa only [Nat.sub_self, mul_zero, zero_mul, add_zero] using cur.left le_rfl + refine ⟨?_, hh, ?_, cur.bits le_rfl⟩ + · simpa only [budget_final, width_eq, finalWidth] using cur.ready + · simpa only [hh, pow_add] using cur.seats + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Common exponents for startup, grouping, contractions and the terminal step -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +theorem Plan.assembly_design {δ : ℝ} (s : Plan) (J G H L B : ℕ) (hD : 8 ≤ s.D) + (hv : 0 < s.v) (hp : 0 < s.p) (ratio : (s.p : ℝ) ≤ s.v * (1 + δ / 3)) : + ∃ (p : Design δ) (E C q : ℕ), + Levels.Admissible p s (1 + J) (Levels.frameRate s J) H E C ∧ + p.D = s.D ∧ p.floor = s.floor ∧ s.D ≤ p.overhead ∧ + 15 + 8 * B + Nat.clog 2 (Nat.card Stack.Device.Guide) ≤ E ∧ E ≤ C ∧ + (5 + 2 * E + p.groupRate + 6) * G ≤ C ∧ (E + E) * (L + 1) ≤ C ∧ + 2 * C + 1 ≤ q ∧ C ≤ q * p.groupRate ∧ E ≤ q * p.groupRate := by + obtain ⟨p, E, K, ok, degree, floor, start, _, overhead⟩ := + s.choose_design (1 + J) (Levels.frameRate s J) H + (15 + 8 * B + Nat.clog 2 (Nat.card Stack.Device.Guide)) 0 hD hv hp ratio + let C := max (max K E) (max ((5 + 2 * E + p.groupRate + 6) * G) ((E + E) * (L + 1))) + have hK : K ≤ C := (le_max_left ..).trans (le_max_left ..) + have hE : E ≤ C := (le_max_right ..).trans (le_max_left ..) + let q := 2 * C + 1 + have positive : 0 < p.groupRate := by unfold Design.groupRate; have := p.overhead_large; omega + have cover : C ≤ q * p.groupRate := + (show C ≤ q by unfold q; omega).trans (Nat.le_mul_of_pos_right _ positive) + exact ⟨p, E, C, q, ok.enlarge hK, degree, floor, overhead, start, hE, + (le_max_left ..).trans (le_max_right ..), (le_max_right ..).trans (le_max_right ..), + le_rfl, cover, hE.trans cover⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # A common scale for the first two operations of a round -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly + +/-- The quantity computed by `1000000 + s.D + 2 ^ Template.Presents.Plan.depth s.D s.floor + 2 * +binBits s + binFactor s + J`. -/ +def groupCoefficient (s : Plan) (J : ℕ) := + 1000000 + s.D + 2 ^ Template.Presents.Plan.depth s.D s.floor + 2 * binBits s + binFactor s + J + +variable {δ : ℝ} {p : Design δ} {M : ℕ} (v : Levels p M) + +/-- The quantity computed by `groupCoefficient s J + v.precision s B + 2 * payload`. -/ +def groupPayload (s : Plan) (B J payload : ℕ) := groupCoefficient s J + v.precision s B + + 2 * payload + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end + +/- # Charging the restart to the common stage budget -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.BoundaryScale + +open Assembly + +variable {F : Type} [Field F] {x y : Wire} {δ : ℝ} {p : Design δ} + +theorem budget {M : ℕ} (v : Levels p M) (D : Template F) (price : Prices F) + {n m C q K R z payload : ℕ} {τ σ J : ℝ} + (hK : 0 < K) (hh : 2 ≤ (Nat.clog 2 n : ℝ)) (hl : 1 ≤ Real.log (Nat.clog 2 n)) + (hJ : 1 ≤ J) (hτ : 0 ≤ τ) (hτσ : (K : ℝ) * τ ≤ σ) (hσ : σ ≤ 1) + (hw : (price.W : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ τ) + (wide : (price.w + price.w ^ price.power : ℕ) ≤ (Nat.clog 2 n) ^ R) + (reserve : (7 + max R 1) * K ≤ M) + (shortBase : (metadata D z payload v.group) ^ K ≤ v.box C) + (hmeta : v.box C ≤ Nat.clog 2 n) (enough : C ≤ q * p.groupRate) + (payloadBase : ((100 + D.scheme.h + payload + D.scheme.e + Nat.clog 2 (1 + z) : ℕ) : ℝ) + ≤ J * (Real.log (Nat.clog 2 n)) ^ 2) + (remain : v.remaining ≤ D.scheme.h) + (seats : 2 ^ (D.scheme.m + D.scheme.h) ≤ p.overhead ^ v.j * v.allocation m) : + let h : ℝ := Nat.clog 2 n + let S := (short D z payload v.group price) ^ K + let W := (2 * J) ^ K * (Real.log h) ^ (2 * K) * h ^ σ + S ≤ 2 ^ K * (Nat.clog 2 n) ^ 2 ∧ + (S : ℝ) ≤ (2 : ℝ) ^ K * h ^ σ * (2 : ℝ) ^ (q * v.group) ∧ + (cost (x := copies x v.batch) (y := copies y v.batch) D z payload v.group price K : ℝ) + ≤ W * v.expense h m (wd x + wd y) q := by + let h : ℝ := Nat.clog 2 n + let L := Real.log h + let W := (2 * J) ^ K * L ^ (2 * K) * h ^ σ + let S₀ := metadata D z payload v.group + let E₀ := 100 + D.scheme.h + payload + D.scheme.e + Nat.clog 2 (1 + z) + let S := short D z payload v.group price + let A := long D z payload v.group price + let E := outer D z payload price + have h₁ : 1 ≤ h := (by norm_num : (1 : ℝ) ≤ 2).trans hh + have hσ₀ : 0 ≤ σ := (mul_nonneg (by positivity) hτ).trans hτσ + have hτ₁ : τ ≤ 1 := + (le_mul_of_one_le_left hτ (Nat.one_le_cast.mpr hK)).trans (hτσ.trans hσ) + have hW₀ : 0 ≤ W := by unfold W; positivity + have hW₁ : 1 ≤ W := by + unfold W + exact one_le_mul_of_one_le_of_one_le + (one_le_mul_of_one_le_of_one_le (one_le_pow₀ (by linarith)) (one_le_pow₀ hl)) + (Real.one_le_rpow h₁ hσ₀) + have hS₀ : 1 ≤ S₀ := Nat.succ_le_of_lt (by unfold S₀ metadata base; positivity) + have hE₀ : 1 ≤ E₀ := by unfold E₀; omega + have powers : (S : ℝ) ^ K ≤ (2 : ℝ) ^ K * h ^ σ * (S₀ : ℝ) ^ K := calc + _ = ((S₀ : ℝ) + (price.W : ℝ)) ^ K := by unfold S short; push_cast; rfl + _ ≤ (2 * (S₀ : ℝ)) ^ K * h ^ σ := power_with_routing (by exact_mod_cast hS₀) (by positivity) + h₁ hτ hw hτσ + _ = _ := by rw [mul_pow]; ring + have hS₁ : (S₀ : ℝ) ^ K ≤ h := by + unfold h + exact_mod_cast shortBase.trans hmeta + have hsmall : (S : ℝ) ^ K ≤ (2 : ℝ) ^ K * h ^ 2 := calc + _ ≤ (2 : ℝ) ^ K * h ^ σ * h := mul_le_mul_of_nonneg_left hS₁ (by positivity) |>.trans' powers + _ ≤ (2 : ℝ) ^ K * h * h := by + have hσh : h ^ σ ≤ h := (Real.rpow_le_rpow_of_exponent_le h₁ hσ).trans_eq (Real.rpow_one _) + gcongr + _ = _ := by ring + have hshort : (S : ℝ) ^ K ≤ (2 : ℝ) ^ K * h ^ σ * (2 : ℝ) ^ (q * v.group) := + powers.trans (mul_le_mul_of_nonneg_left + (by exact_mod_cast shortBase.trans (v.box_le_group_power enough)) (by positivity)) + have hσW : (2 : ℝ) ^ K * h ^ σ ≤ W := by + unfold W + have hfront : (2 : ℝ) ^ K ≤ (2 * J) ^ K := pow_le_pow_left₀ (by positivity) (by linarith) _ + have hfact := le_mul_of_one_le_right (by positivity : 0 ≤ (2 * J) ^ K) (one_le_pow₀ (n + := 2 * K) hl) + exact mul_le_mul_of_nonneg_right (hfront.trans hfact) (by positivity) + have hA : (A : ℝ) ^ K ≤ h ^ M := by + let r := max R 1 + have hp : h ≤ h ^ r := by + simpa only [pow_one] using (pow_le_pow_right₀ h₁ (Nat.le_max_right R 1)) + have hq : h ^ R ≤ h ^ r := pow_le_pow_right₀ h₁ (Nat.le_max_left ..) + have hs : (S₀ : ℝ) ≤ h := + (by exact_mod_cast Nat.le_self_pow (Nat.ne_of_gt hK) S₀ : (S₀ : ℝ) ≤ (S₀ : ℝ) ^ K).trans hS₁ + have hw' : (price.W : ℝ) ≤ h := hw.trans + ((Real.rpow_le_rpow_of_exponent_le h₁ hτ₁).trans_eq (Real.rpow_one _)) + have ww : (price.w : ℝ) + (price.w : ℝ) ^ price.power ≤ h ^ R + := by unfold h; exact_mod_cast wide + have hl : (A : ℝ) ≤ 100 + h ^ r + 2 * h := by + have w' := ww.trans hq + change ((100 + price.w + price.w ^ price.power + (S₀ + price.W) : ℕ) : ℝ) ≤ _ + push_cast + linarith only [w', hs, hw'] + have hr : 1 ≤ h ^ r := one_le_pow₀ h₁ + have hlong : (A : ℝ) ≤ h ^ (7 + r) := calc + _ ≤ 103 * h ^ r := by nlinarith only [hl, hp, hr] + _ ≤ h ^ 7 * h ^ r := mul_le_mul_of_nonneg_right + ((by norm_num : (103 : ℝ) ≤ 2 ^ 7).trans (pow_le_pow_left₀ (by norm_num) hh _)) (by + positivity) + _ = _ := (pow_add ..).symm + exact ((pow_le_pow_left₀ (by positivity) hlong K).trans_eq (pow_mul ..).symm).trans + (pow_le_pow_right₀ h₁ reserve) + have hEnd : (E : ℝ) ^ K ≤ W := calc + _ = ((E₀ : ℝ) + (price.W : ℝ)) ^ K := by unfold E E₀ outer; push_cast; ring + _ ≤ (2 * (E₀ : ℝ)) ^ K * h ^ σ := power_with_routing (by exact_mod_cast hE₀) (by positivity) + h₁ hτ hw hτσ + _ ≤ (2 * (J * L ^ 2)) ^ K * h ^ σ := by gcongr + _ = _ := by unfold W; rw [← mul_assoc, mul_pow, ← pow_mul] + have payment : cost (x := copies x v.batch) (y := copies y v.batch) D z payload v.group price K ≤ + 2 ^ D.scheme.m * A ^ K + 2 ^ (D.scheme.m + D.scheme.h) * S ^ K + v.batch * (wd x + + wd y) * E ^ K := by + unfold cost + rw [wd_copies, wd_copies, ← Nat.mul_add] + refine ⟨by unfold h S at hsmall; exact_mod_cast hsmall, by exact_mod_cast hshort, ?_⟩ + apply v.phase_expense (h:=h) (W:=W) (by positivity) hW₀ remain seats payment + · push_cast + exact hA.trans (le_mul_of_one_le_left (by positivity) hW₁) + · push_cast + exact hshort.trans (mul_le_mul_of_nonneg_right hσW (by positivity)) + · exact_mod_cast hEnd + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Contraction.BoundaryScale +end + +/- # Charging grouping and local concentration to the same phase budget -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +open Contraction + +variable {F : Type} [Field F] + {x y : Wire} {δ : ℝ} {p : Design δ} {M n m i E B C J K q T₀ R : ℕ} + {v : Levels p M} {s : Plan} {Q : Layer F (copies x v.batch) (copies y v.batch)} + {price : Prices F} {a b ξ τ σ J₀ : ℝ} + +theorem paid_group (cur : v.Current s n m i E Q) (ready : v.Suits n T₀ a b ξ) + (fit : v.Fits n B C) (hi : i ≤ v.j) + (margin : groupCoefficient s J + s.d + s.p + 2 * E + 6 ≤ 2 ^ v.j) + (hK : 0 < K) (exponent : (5 + 2 * E + p.groupRate + 6) * K ≤ C) + (hh : 2 ≤ (Nat.clog 2 n : ℝ)) (hl : 1 ≤ Real.log (Nat.clog 2 n)) + (hτ : 0 ≤ τ) (hτσ : (K : ℝ) * τ ≤ σ) (hσ : σ ≤ 1) + (hw : (price.W : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ τ) + (wide : (price.w + price.w ^ price.power : ℕ) ≤ (Nat.clog 2 n) ^ R) + (reserve : (7 + max R 1) * K ≤ M) (enough : C + ≤ q * p.groupRate) (hq : (p.groupRate * q : ℕ) * a ≤ b) + (hJ : 0 ≤ J₀) + (logSpan : ((v.span + s.d + s.p + 1 : ℕ) : ℝ) ≤ J₀ * (Real.log (Nat.clog 2 n)) ^ 2) : + let H := v.groupPayload s B J Q.height + let h : ℝ := Nat.clog 2 n + let W := (2 * ((groupCoefficient s J + B + 128 : ℕ) : ℝ) * (J₀ + + 1)) ^ K * (Real.log h) ^ (2 * K) * h ^ σ + (BoundaryScale.short Q.template 1 H v.group price) ^ K ≤ 2 ^ K * (Nat.clog 2 n) ^ 2 ∧ + (((BoundaryScale.short Q.template 1 H v.group price) ^ K : ℕ) : ℝ) ≤ + (2 : ℝ) ^ (K + 2 * p.groupRate * q) * h ^ σ * (p.D * (v.finalWidth : ℝ)) ∧ + (BoundaryScale.cost (x := copies x v.batch) (y := copies y v.batch) + Q.template 1 H v.group price K : ℝ) ≤ W * v.expense h m (wd x + wd y) q := by + intro H h W + have remain : v.remaining ≤ Q.template.scheme.h := by rw [cur.left hi]; exact Nat.le_add_right .. + have overheadPositive : 0 < p.overhead := by + have := p.overhead_large + omega + have seats : 2 ^ (Q.template.scheme.m + Q.template.scheme.h) ≤ + p.overhead ^ v.j * v.allocation m := + cur.seats.trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right overheadPositive hi)) + have hm : v.FrameBound Q Q.template H 5 := by + refine ⟨(Nat.pow_le_pow_right (by decide) cur.ports).trans (v.pow_le_box 5), ?_, by omega⟩ + have small : groupCoefficient s J ≤ v.box 1 := by unfold box; rw [one_mul, pow_succ]; omega + have prec := fit.precision (s := s) (by omega) + have old := (cur.precision (B := B)).trans prec + have double : 2 * Q.height ≤ v.box 2 := by rw [two_mul]; exact v.box_sum old old + exact (v.box_sum (v.box_sum small prec) double).trans (v.box_mono (by decide)) + have hz : 1 ≤ v.width i := by rw [v.width_eq]; exact Nat.one_le_pow _ _ (by decide) + have metaPow : (BoundaryScale.metadata Q.template 1 H v.group) ^ K ≤ v.box C := calc + _ ≤ (v.box (5 + 2 * E + p.groupRate + 6)) ^ K := + Nat.pow_le_pow_left (hm.metadata_le cur hi fit cur.height_le hz (by omega)) _ + _ ≤ _ := by rw [← v.box_mul]; exact v.box_mono exponent + let c := groupCoefficient s J + B + 128 + have c₁ : 1 ≤ (c : ℝ) := by exact_mod_cast (show 1 ≤ c by unfold c; omega) + have hc : 1 ≤ (c : ℝ) * (J₀ + 1) := one_le_mul_of_one_le_of_one_le c₁ (by linarith) + have size : 100 + Q.template.scheme.h + H + Q.template.scheme.e + Nat.clog 2 (1 + 1) + ≤ c * (v.span + s.d + s.p + 1) := by + have hp := cur.ports + have hq := cur.height + have hx : Q.template.scheme.h ≤ v.span := cur.height_le.trans (by unfold span; omega) + have ha := Nat.mul_le_mul_left B (show v.span ≤ v.span + s.d + s.p + 1 by omega) + have hb := Nat.le_mul_of_pos_right (groupCoefficient s J) (show 0 < v.span + s.d + s.p + + 1 by omega) + rw [show Nat.clog 2 (1 + 1) = 1 by decide] + unfold H groupPayload Levels.precision c + simp only [add_mul] + omega + have outer : ((100 + Q.template.scheme.h + H + Q.template.scheme.e + Nat.clog 2 (1 + 1) : ℕ) : ℝ) + ≤ + ((c : ℝ) * (J₀ + 1)) * (Real.log (Nat.clog 2 n)) ^ 2 := calc + _ ≤ (c : ℝ) * ((v.span + s.d + s.p + 1 : ℕ) : ℝ) := by exact_mod_cast size + _ ≤ (c : ℝ) * ((J₀ + 1) * (Real.log (Nat.clog 2 n)) ^ 2) := mul_le_mul_of_nonneg_left + (logSpan.trans (mul_le_mul_of_nonneg_right (by linarith) (by positivity))) (by positivity) + _ = _ := (mul_assoc ..).symm + obtain ⟨few, gate, paid⟩ := BoundaryScale.budget (x:=x) (y:=y) v Q.template price hK hh hl hc hτ + hτσ hσ + hw wide reserve metaPow fit.small enough outer remain seats + refine ⟨few, ?_, ?_⟩ + · calc + _ ≤ _ := gate + _ ≤ (2 : ℝ) ^ K * h ^ σ * ((2 : ℝ) ^ (2 * p.groupRate * q) * (v.finalWidth : ℝ)) := + mul_le_mul_of_nonneg_left (ready.group_power_le_width hq) (by positivity) + _ = (2 : ℝ) ^ (K + 2 * p.groupRate * q) * h ^ σ * (v.finalWidth : ℝ) := by rw [pow_add]; ring + _ ≤ _ := by + have hd : (1 : ℝ) ≤ p.D := by exact_mod_cast (show 1 ≤ p.D by have := p.large; omega) + exact mul_le_mul_of_nonneg_left (le_mul_of_one_le_left (by positivity) hd) (by positivity) + · simpa only [W, h, c, mul_assoc] using paid + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +end + +/- # Exact restart and its quantitative guarantee at the chosen levels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current + +open Assembly Contraction + +variable {F k : Type} [Field F] [Fintype F] [Field k] [Algebra k F] + {x y : Wire} {δ : ℝ} {p : Design δ} {M n m i E B C J K H d q T₀ z R : ℕ} + {v : Levels p M} {s : Plan} {Q : Layer F (copies x v.batch) (copies y v.batch)} + {D : Template F} {price : Prices F} {a b ξ τ σ J₀ : ℝ} + +omit [Fintype F] in +theorem paid_restart [Finite F] + (cur : v.Current s n m i E Q) (ready : v.Suits n T₀ a b ξ) + (fit : v.Fits n B C) (f : v.Passage Q D J) (data : v.FrameBound Q D Q.height K) + (ok : Admissible p s J K H E C) (hi : i < v.j) (hk : K + 2 * E + 1 ≤ 2 ^ v.j) + (hK : 0 < H) (overhead : 0 < s.K) (hz : z ≤ v.width i) + (hs : Requirements D s (v.width i) (v.budget m i) z Q.height price v.group d H) + (restart : Restarts k s d H) + (hh : 2 ≤ (Nat.clog 2 n : ℝ)) (hl : 1 ≤ Real.log (Nat.clog 2 n)) + (hτ : 0 ≤ τ) (hτσ : (H : ℝ) * τ ≤ σ) (hσ : σ ≤ 1) + (hw : (price.W : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ τ) + (wide : (price.w + price.w ^ price.power : ℕ) ≤ (Nat.clog 2 n) ^ R) + (reserve : (7 + max R 1) * H ≤ M) (enough : C + ≤ q * p.groupRate) (hq : (p.groupRate * q : ℕ) * a ≤ b) + (hJ : 0 ≤ J₀) + (logSpan : ((v.span + s.d + s.p + 1 : ℕ) : ℝ) ≤ J₀ * (Real.log (Nat.clog 2 n)) ^ 2) : + let h : ℝ := Nat.clog 2 n + let W := (2 * ((K + 2 : ℕ) : ℝ) * (J₀ + 1)) ^ H * (Real.log h) ^ (2 * H) * h ^ σ + ∃ result : Restored (x := copies x v.batch) (y := copies y v.batch) + D s (v.width i) (v.budget m i) z Q.height price v.group H, + v.Current s n m (i + 1) E result.next ∧ + result.keys.card ≤ 2 ^ H * (Nat.clog 2 n) ^ 2 ∧ + (((BoundaryScale.short D z Q.height v.group price) ^ H : ℕ) : ℝ) ≤ + (2 : ℝ) ^ (H + 2 * p.groupRate * q) * h ^ σ * (p.D * (v.finalWidth : ℝ)) ∧ + (BoundaryScale.cost (x := copies x v.batch) (y := copies y v.batch) + D z Q.height v.group price H : ℝ) ≤ W * v.expense h m (wd x + wd y) q := by + let : Fintype F := Fintype.ofFinite F + obtain ⟨result⟩ := restart F (x := copies x v.batch) (y := copies y v.batch) + D (v.width i) (v.budget m i) z Q.height price v.group hs + have hD : D.scheme.h ≤ v.blocks := by + have := f.height + have := cur.height_le + omega + have hremain : v.remaining ≤ D.scheme.h := by + have hstep : v.group ≤ p.steps * (v.j - i) * v.group := + Nat.le_mul_of_pos_left _ (Nat.mul_pos p.steps_pos (Nat.sub_pos_of_lt hi)) + have left := cur.left hi.le + have ht := f.height + omega + have axes : D.scheme.m + D.scheme.h ≤ Q.template.scheme.m + Q.template.scheme.h + J := by + have := f.height + have := f.upper + omega + have seats : 2 ^ (D.scheme.m + D.scheme.h) ≤ p.overhead ^ v.j * v.allocation m := + (Nat.le_mul_of_pos_left _ overhead).trans ((cur.expand ok.input axes).trans + (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by have := p.overhead_large; omega) hi))) + have metaPow : (BoundaryScale.metadata D z Q.height v.group) ^ H ≤ v.box C := calc + _ ≤ (v.box (K + 2 * E + p.groupRate + 6)) ^ H + := Nat.pow_le_pow_left (data.metadata_le cur hi.le fit hD hz hk) _ + _ ≤ _ := by rw [← v.box_mul]; exact v.box_mono ok.exponent + let c : ℝ := ((K + 2 : ℕ) : ℝ) * (J₀ + 1) + have hc : 1 ≤ c := by + have hc₁ : (1 : ℝ) ≤ (K + 2 : ℕ) := by exact_mod_cast (show 1 ≤ K + 2 by omega) + unfold c + exact one_le_mul_of_one_le_of_one_le hc₁ (by linarith) + have hlog := v.log_width hi.le hz + have hsmall : 100 + D.scheme.h + Nat.clog 2 (1 + z) ≤ v.span + 1 := by + unfold span + omega + have hsp : v.j + 1 ≤ v.span := by + have ht : v.j ≤ p.growth * v.j := Nat.le_mul_of_pos_left _ p.growth_pos + unfold span + omega + have hd : D.scheme.e ≤ K * v.span := by + apply le_trans _ (Nat.mul_le_mul_left K hsp) + exact (Nat.pow_le_pow_iff_right (by decide)).mp data.ports + have hsize : 100 + D.scheme.h + Q.height + D.scheme.e + Nat.clog 2 (1 + z) ≤ + (K + 2) * (v.span + s.d + s.p + 1) := calc + _ ≤ (v.span + 1) + (v.span + s.d + s.p) + K * v.span := by + have := cur.height + omega + _ ≤ (v.span + s.d + s.p + 1) + (v.span + s.d + s.p + 1) + K * (v.span + s.d + s.p + 1) := + Nat.add_le_add (Nat.add_le_add (by omega) (by omega)) + (Nat.mul_le_mul_left _ (by omega)) + _ = _ := by ring + have hExt : ((100 + D.scheme.h + Q.height + D.scheme.e + Nat.clog 2 (1 + z) : ℕ) : ℝ) ≤ + c * (Real.log (Nat.clog 2 n)) ^ 2 := calc + _ ≤ ((K + 2 : ℕ) : ℝ) * ((v.span + s.d + s.p + 1 : ℕ) : ℝ) := by exact_mod_cast hsize + _ ≤ ((K + 2 : ℕ) : ℝ) * ((J₀ + 1) * (Real.log (Nat.clog 2 n)) ^ 2) := by + apply mul_le_mul_of_nonneg_left _ (by positivity) + exact logSpan.trans (mul_le_mul_of_nonneg_right (by linarith) (by positivity)) + _ = _ := by unfold c; ring + obtain ⟨few, gate, paid⟩ := BoundaryScale.budget (x:=x) (y:=y) v D price hK hh hl hc hτ hτσ hσ + hw wide reserve metaPow fit.small enough hExt hremain seats + refine ⟨result, cur.advance f data ok fit hi hk hz result, result.few.trans few, ?_, ?_⟩ + · calc + _ ≤ _ := gate + _ ≤ (2 : ℝ) ^ H * (Nat.clog 2 n : ℝ) ^ σ * ((2 : ℝ) ^ (2 * p.groupRate * q) * (v.finalWidth : + ℝ)) := + mul_le_mul_of_nonneg_left (ready.group_power_le_width hq) (by positivity) + _ = (2 : ℝ) ^ (H + 2 * p.groupRate * q) * (Nat.clog 2 n : ℝ) ^ σ * (v.finalWidth : ℝ) := by + rw [pow_add]; ring + _ ≤ _ := by + have hd : (1 : ℝ) ≤ p.D := by exact_mod_cast (show 1 ≤ p.D by have := p.large; omega) + exact mul_le_mul_of_nonneg_left (le_mul_of_one_le_left (by positivity) hd) (by positivity) + · simpa only [c, Nat.cast_add, Nat.cast_ofNat, mul_assoc] using paid + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels.Current +end + +/- # Terminal bank capacity at the last round -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +open Assembly + +variable {δ : ℝ} {p : Design δ} {M : ℕ} (v : Levels p M) (s : Plan) + {F : Type} [Field F] {x y : Wire} + +/-- The quantity computed by `s.d + (v.stack + p.growth * v.j)`. -/ +def depth := s.d + (v.stack + p.growth * v.j) +/-- The value specified by `2 ^ Q.template.scheme.m + ⌊8 * v.finalBudget m / (s.floor * +v.finalWidth)⌋₊*2 ^ (Q.template.scheme.e + v.depth s)`. -/ +def capacity (m : ℕ) (Q : Layer F x y) := + 2 ^ Q.template.scheme.m + ⌊8 * v.finalBudget m / (s.floor * v.finalWidth)⌋₊*2 ^ + (Q.template.scheme.e + v.depth s) + +theorem depth_eq : 2 ^ v.depth s = s.D * v.finalWidth := pow_add .. + +namespace Current +variable {v s} {Q : Layer F x y} {n m E : ℕ} (h : v.Current s n m v.j E Q) +local notation "S" => Q.template.scheme +include h + +theorem fits_terminal (i : Q.State) : + Assembly.Terminal.Fits S (Q.data i).1 (v.capacity s m Q) (v.depth s) ∧ + Assembly.Terminal.Neutral S (Q.data i).1 := + (h.terminal rfl).1.terminal (by unfold Plan.floor Plan.M Plan.D; positivity) + (by unfold finalWidth; positivity) (v.depth_eq s).ge le_rfl i + +theorem capacity_le : + (v.capacity s m Q : ℝ) ≤ (2 : ℝ) ^ Q.template.scheme.m + + (256 * s.D / s.floor) * v.finalBudget m := by + have hf : 0 < s.floor := by unfold Plan.floor Plan.M Plan.D; positivity + have hT : 0 < (v.finalWidth : ℝ) := by unfold finalWidth; positivity + have hL : 0 ≤ v.finalBudget m := by unfold finalBudget; positivity + have he : (2 : ℝ) ^ Q.template.scheme.e ≤ 32 := by + exact_mod_cast (show (2 : ℕ) ^ Q.template.scheme.e + ≤ 32 from Nat.pow_le_pow_right (by decide) h.ports) + rw [capacity, pow_add, v.depth_eq] + simp only [Nat.cast_mul, Nat.cast_add, Nat.cast_pow, Nat.cast_ofNat] + apply add_le_add_right + calc + _ ≤ (8 * v.finalBudget m / (s.floor * v.finalWidth)) * (32 * ((s.D : ℝ) * v.finalWidth)) := by + gcongr + exact Nat.floor_le (by positivity) + _ = _ := by field_simp; ring + +theorem terminal_height : + max Q.height (Assembly.Terminal.height S (v.depth s)) ≤ v.span + s.d + s.p := by + apply max_le h.height + unfold Assembly.Terminal.height depth span + have := h.ready.1 + have := h.ports + have := h.height_le + omega + +theorem terminal_space {B C w : ℕ} (fit : v.Fits n B C) (hm : m ≤ n ^ 2) + (hs : s.d + s.p ≤ 2 ^ v.j) (hw : 16 * Nat.clog 2 n ≤ w) : + 1 ≤ Q.template.scheme.m ∧ Q.template.scheme.m + (Q.template.scheme.d + 1) ≤ w ∧ + 2 ^ (Q.template.scheme.d + 1) * ((max Q.height (Assembly.Terminal.height S (v.depth s)) + 1)* + (2 ^ Q.template.scheme.m + 2 ^ Q.template.scheme.m)) < 2 ^ w := by + let t := max Q.height (Assembly.Terminal.height S (v.depth s)) + have h₀ := h.long fit le_rfl hm + have h₁ := fit.four_span.trans fit.group + have h₂ := hs.trans ((Nat.pow_le_pow_right (by decide) v.rounds_le_group).trans fit.group) + have hv : 100 ≤ v.span := by unfold span; omega + have ht : t ≤ v.span + s.d + s.p := h.terminal_height + have hd := h.degree + have hm := h.address + refine ⟨by omega, by omega, ?_⟩ + have key : Q.template.scheme.d + 1 + (t + (Q.template.scheme.m + 1)) < w := by omega + refine lt_of_le_of_lt ?_ (Nat.pow_lt_pow_right (by decide : 1 < 2) key) + rw [pow_add 2 (Q.template.scheme.d + 1), pow_add 2 t, pow_succ 2 Q.template.scheme.m, + ← Nat.mul_two] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ Nat.lt_two_pow_self) + +end Current +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Levels +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Local.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Local.lean new file mode 100644 index 0000000000..bb9266846c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Local.lean @@ -0,0 +1,123 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame + +/-! +# The graph interface to local concentration + +Each index in `Cell h` identifies an independent block. Host positions +name cells and each station belongs to one cell of one block. The input +has positive arities and integral packets of width `R`. The output +reserves individual host slots for the stations and is padded to units +of width `u` before the beats. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +open scoped Classical in +/-- The data for the input construction, including `V`, `[fv`, `diagram`, `place`, `adj`. -/ +structure Input (F : Type) (x y : Wire) (h D T R g : ℕ) (W : ℝ) where + /-- The type of vertices. -/ + V : Type + [fv : Fintype V] + /-- The `Input` component of type `Diagram F x y`. -/ + diagram : Diagram F x y + /-- The `Input` component of type `diagram.V → V × Cell h`. -/ + place : diagram.V → V × Cell h + /-- The neighbors of each vertex of type `V → Finset V`. -/ + adj : V → Finset V + sym : ∀ v z, z ∈ adj v → v ∈ adj z + degree : ∀ v, (adj v).card ≤ g + edge : ∀ e, let q := place (diagram.source e) + let p := place (diagram.target e) + p.2 = q.2 ∧ (p.1 = q.1 ∨ p.1 ∈ adj q.1) + loopless : ∀ e, diagram.source e ≠ diagram.target e + positive : ∀ v, 0 < diagram.arity v + width : ∀ v w, R ∣ Fintype.card {e // diagram.source e = v ∧ diagram.target e = w} + /-- The `Input` component of type `diagram.V → Prop`. -/ + mobile : diagram.V → Prop + ext : ∀ q, ¬mobile (portEnd diagram q) + occupied : (univ.image place).card * D * T ≤ W + immobile : Fintype.card {v // ¬mobile v} * D * T ≤ W + count : ∀ p, Fintype.card {v // place v = p} ≤ 100 * D + mass : ∀ p, push place (fun v => (diagram.arity v : ℝ)) p ≤ 100 * (D : ℝ) * T + squares : (∑ v, (diagram.arity v : ℝ) ^ 2) ≤ W * T + /-- Optional local station and host keys for deterministic numbering. -/ + ranks : Option ((diagram.V → ℕ) × (V → ℕ)) := none + +attribute [instance] Input.fv + +open scoped Classical in +/-- The data for the local term construction, including `V`, `[fv`, `diagram`, `freeze`, +`frame`. -/ +structure LocalTerm (F : Type) (x y : Wire) (h u : ℕ) where + /-- The type of vertices. -/ + V : Type + [fv : Fintype V] + /-- The `LocalTerm` component of type `Diagram F x y`. -/ + diagram : Diagram F x y + /-- The `LocalTerm` component of type `Freeze diagram`. -/ + freeze : Freeze diagram + /-- The `LocalTerm` component of type `freeze.Frame V h`. -/ + frame : freeze.Frame V h + one : Function.Injective frame.place + width : ∀ v w, u ∣ Fintype.card {e // diagram.source e = v ∧ diagram.target e = w} + /-- The `LocalTerm` component of type `diagram.V → ℝ`. -/ + charge : diagram.V → ℝ + cover : ∀ v, diagram.arity v ≤ charge v + floor : ∀ v, u ≤ charge v + +attribute [instance] LocalTerm.fv + +variable {F : Type} {x y : Wire} {h D T R g u : ℕ} {W : ℝ} + +open scoped Classical in +/-- The graph and arity estimates needed from one summand. Here `D=2^d` +in applications. All implicit constants are bounded by `C`. -/ +structure Concentrated (P : Input F x y h D T R g W) (Q : LocalTerm F x y h u) + (C d ℓ : ℕ) : Prop where + cells : Fintype.card Q.V ≤ D ^ C * Fintype.card P.V + coreDegree : ∀ v, (Q.frame.C v).card ≤ C + fullDegree : ∀ v, (Q.frame.N v).card ≤ D ^ C + frozenCount : Fintype.card Q.freeze.Fixed * D * T ≤ C * W + frozenMax : ∀ v : Q.freeze.Fixed, Q.charge v.val ≤ (C : ℝ) * D * T + frozenSquare : (∑ v : Q.freeze.Fixed, Q.charge v.val ^ 2) ≤ C * W * T + coreMax : ∀ v : Q.freeze.Core, Q.charge v.val * (D : ℝ) ^ ℓ ≤ T + coreSum : (∑ v : Q.freeze.Core, Q.charge v.val) ≤ C * W * (1 + (d : ℝ)) ^ 2 + +open scoped Classical in +/-- The exact expansion and control-index count. Algorithmic locality +of the chosen terms is an additional requirement for realizing the sum. -/ +def LocalExpansion [Field F] (P : Input F x y h D T R g W) (u C d ℓ A : ℕ) : Prop := + ∃ (I : Type) (_ : Fintype I) (Q : I → LocalTerm F x y h u) (c : I → F), + Fintype.card I ≤ 2 ^ (A * (1 + Nat.clog 2 (T + 1)) * (univ.image P.place).card) ∧ + (∀ x y, ∑ i, c i * (Q i).diagram.eval x y = P.diagram.eval x y) ∧ + ∀ i, Concentrated P (Q i) C d ℓ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Filter + +/-- Uniform local concentration uses a fixed finite extension for +planting and polynomially many field points for the motions. -/ +def LocalLaw (k : Type) [Field k] (ℓ : ℕ) : Prop := + ∀ g : ℕ, 0 < g → ∃ C : ℕ, ∀ᶠ d : ℕ in atTop, + let D := 2 ^ d + ∃ (A : ℕ) (L : Type) (_ : Field L) (_ : Finite L) (_ : Algebra k L), + ∀ᶠ T : ℕ in atTop, ∃ R : ℕ, 0 < R ∧ R * D ^ 2 ≤ T ∧ + ∀ (K : Type) (_ : Field K) (_ : Fintype K) (_ : Algebra L K), + A * (1 + T) ^ A ≤ Fintype.card K → ∀ u : ℕ, 0 < u → u * D ^ C ≤ T → + ∀ (x y : Wire) (h : ℕ) (W : ℝ) (P : Input K x y h D T R g W), LocalExpansion P u C d ℓ A + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Recovery/Run.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Recovery/Run.lean new file mode 100644 index 0000000000..783476ebb4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Recovery/Run.lean @@ -0,0 +1,224 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Rate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Repost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Carry + +/-! # Restoring the frozen border after the final contraction -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Recovery +open Assembly Contraction + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} + {A : Attachment D} {s : Plan} {T : ℕ} {L : ℝ} {z k : ℕ} + (hs : s.Fits) (hz : 0 < z) (ht : T ≤ z * s.M) +local notation "I" => Snapshot.state (final (x := x) (y := y) A s T L z k) + +include hs hz ht in +theorem feasible (i : I) : Restore.Feasible i.val s.full s.slots s.slots := + ⟨allocation hs hz ht i, i.property.1.bounded.1, i.property.1.simple le_rfl⟩ + +/-- The value specified by `(feasible hs hz ht i).data`. -/ +abbrev data (i : I) := (feasible hs hz ht i).data + +theorem board_ready (hL : 0 ≤ L) (i : I) : + (data hs hz ht i).board.Ready 5 s.D (2 ^ s.p * T) (L / (2 : ℝ) ^ s.v) s.floor := by + have h := i.property.1 + have lo (t : i.val.T) : (z : ℝ) ≤ i.val.L.charge t := by + obtain ⟨n, hn, he⟩ := h.charge t + rw [he]; exact Nat.cast_le.mpr hn + exact Restore.Data.ready (data hs hz ht i) hs hL ht h.test.cover + (fun j => Nat.cast_le.mpr (h.parallel j)) lo h.bounded h.width h.total h.test.square + h.test.maximum + +/-- The quantity computed by `s.d + s.p + Nat.clog 2 T`. -/ +def height (s : Plan) (T : ℕ) := s.d + s.p + Nat.clog 2 T + +theorem arity (hL : 0 ≤ L) (i : I) (v : (data hs hz ht i).board.diagram.V) : + (data hs hz ht i).board.diagram.arity v ≤ 2 ^ (height s T) := by + let P := (data hs hz ht i).board + have hc := (P.cover v).trans ((board_ready hs hz ht hL i).2.2.2 v).1 + have hu : (P.diagram.arity v : ℝ) ≤ (s.D : ℝ) * (2 ^ s.p * T : ℕ) := + hc.trans (div_le_self (by positivity) (by norm_num)) + have hu' : P.diagram.arity v ≤ s.D * (2 ^ s.p * T) := by exact_mod_cast hu + refine hu'.trans ?_ + rw [height, pow_add, pow_add, mul_assoc, Plan.D] + exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ (Nat.le_pow_clog (by decide) _)) + +variable (x y A k) (hL : 0 ≤ L) +/-- The indexed operation `Restore.rawLayer (fun i : I => data hs hz ht i) (height s T) (arity +hs hz ht hL)`. -/ +abbrev raw := Restore.rawLayer (fun i : I => data hs hz ht i) (height s T) (arity hs hz ht hL) +/-- The indexed operation `Restore.layer (fun i : I => data hs hz ht i) (height s T) (arity hs +hz ht hL)`. -/ +abbrev layer := Restore.layer (fun i : I => data hs hz ht i) (height s T) (arity hs hz ht hL) + +theorem ready : + (layer x y A k hs hz ht hL).Ready s.D (2 ^ s.p * T) (L / (2 : ℝ) ^ s.v) s.floor ∧ + (layer x y A k hs hz ht hL).Loopless := + Restore.ready _ _ _ (board_ready hs hz ht hL) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Recovery +end + +/- # Fixed port count at a round boundary -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Recovery +open Assembly Contraction + +section +variable {F : Type} [Field F] {D : Template F} (A : Attachment D) (s : Plan) (T k : ℕ) (W : Prices + F) + +/-- Builds `Restore.Measure where F` with the specified `fst`, `snd`. -/ +abbrev measure : Restore.Measure where + F := F + D := D + A := A + N := s.full + r := s.slots + s := s.slots + c := W + w := max k (D.scheme.h + height s T) + 1 + fst := k + snd := height s T + +end +variable {F : Type} [Field F] {D : Template F} (x y : Wire) (A : Attachment D) (k : ℕ) + {s : Plan} {T : ℕ} {L : ℝ} {z : ℕ} + (hs : s.Fits) (hz : 0 < z) (ht : T ≤ z * s.M) (hL : 0 ≤ L) +local notation "Y" => layer x y A k hs hz ht hL + +/-- Computes the restored by the application `Merge.layer (layer x y A k hs hz ht hL) (ready x y +A k hs hz ht hL).2 rfl`. -/ +abbrev restored : Layer F x y := + Merge.layer (layer x y A k hs hz ht hL) (ready x y A k hs hz ht hL).2 rfl + +theorem stable : + (restored x y A k hs hz ht hL).Ready s.D (2 ^ s.p * T) (L / (2 : ℝ) ^ s.v) s.floor ∧ + (restored x y A k hs hz ht hL).Loopless := + ⟨Merge.ready Y _ _ (ready x y A k hs hz ht hL).1, Merge.loopless Y _ _⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Recovery +end + +/- # A uniform budget for restoration, scalar withdrawal and span merging -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Recovery +open Assembly Contraction BatchDescent.Phase + +/-- One exponent works for all fields and legal input layers. The sum +of the four gate sizes bounds the largest gate arity. -/ +theorem estimate : ∃ K : ℕ, ∀ {F : Type} [Field F] {D : Template F} + (x y : Wire) (A : Attachment D) (k : ℕ) {s : Plan} {T : ℕ} {L : ℝ} {z : ℕ} + (hs : s.Fits) (hz : 0 < z) (ht : T ≤ z * s.M) (hL : 0 ≤ L) (W : Prices F), + let i := measure A s T k W + let P := raw x y A k hs hz ht hL + let Q := layer x y A k hs hz ht hL + Restore.gateWidth A i.N i.r i.s + Restore.commandSize A i.N i.r i.s i.w + + 2 * (Restore.script A.scheme).width + + SpanProgram.size Q.template.scheme 0 (Q.height + 1) (Merge.dim Q.template.scheme) + ≤ i.short ^ K ∧ + Restore.stageCost A i.N i.r i.s z i.w x y i.fst i.snd W + + P.encoding.sweepCost + Merge.layerCost Q W ≤ i.budget x y K := by + obtain ⟨f, hf⟩ := Restore.Measure.bound + obtain ⟨g, hg⟩ := Restore.Measure.sweep_bound + obtain ⟨h, hh⟩ := Merge.price + refine ⟨max (max f g + 1) h + 1, ?_⟩ + intro F _ D x y A k s T L z hs hz ht hL W i P Q + obtain ⟨gate, stage⟩ := hf i z x y + have sweep := (i.sweep_estimate x y z P rfl rfl rfl).trans (hg i x y) + obtain ⟨merge, hcost⟩ := hh i Q z rfl rfl rfl + constructor + · have ht : i.short ^ f ≤ i.short ^ (max f g + 1) := + Nat.pow_le_pow_right (lt_of_lt_of_le (by decide) i.short_two) (by omega) + exact (Nat.add_le_add (gate.trans ht) merge).trans (Poly.pow_sum i.short_two ..) + · have hj := (Nat.add_le_add stage sweep).trans (i.add x y f g) + exact (Nat.add_le_add hj hcost).trans (i.add x y _ h) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Recovery +end + +/- +# Reassembling one complete round + +Choose four shared dictionary entries before fixing the admissible +set of tables. The output has one station at each occurrence and +a fixed, degree-independent number of port indices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Recovery +open Assembly Contraction + +open scoped Classical in +private theorem more {a b m l : ℕ} : + (b + 1) * (2 ^ (m + l) + 2 ^ (m + l)) ≤ 2 ^ l * ((max a b + 1) * (2 ^ m + 2 ^ (m + l))) := by + rw [mul_left_comm (2 ^ l), mul_add (2 ^ l), pow_add] + apply Nat.mul_le_mul (Nat.succ_le_succ (le_max_right a b)) + exact Nat.add_le_add (mul_comm ..).le (Nat.le_mul_of_pos_left _ (Nat.two_pow_pos l)) + +open scoped Classical in +theorem run : ∃ K : ℕ, ∀ {F : Type} [Field F] {D : Template F} + (x y : Wire) (A : Attachment D) (k : ℕ) {s : Plan} {T : ℕ} {L : ℝ} {z : ℕ} + (hs : s.Fits) (hz : 0 < z) (ht : T ≤ z * s.M) (hL : 0 ≤ L) (W : Prices F), + let i := measure A s T k W + 1 ≤ i.m → i.m + i.d ≤ W.w → + 2 ^ i.l * ((max i.fst (i.h + i.snd) + 1) * (2 ^ i.m + 2 ^ (i.m + i.l))) < 2 ^ W.w → + ∃ gates : Finset (Table F), gates.card ≤ 4 ∧ + ∀ {U : ℕ} {C : Set (Table F)}, 3 ≤ U → ↑gates ⊆ C → i.short ^ K ≤ U → + Transforms F U C (final (x := x) (y := y) A s T L z k) + (restored x y A k hs hz ht hL).snapshot (i.budget x y K) := by + obtain ⟨K, hK⟩ := estimate + refine ⟨K, ?_⟩ + intro F _ D x y A k s T L z hs hz ht hL W i hm hd hc + let ok := Ready (u := z) A (fringe (x := x) (y := y) s T L) z 3 s.full (destination s T L) + let P := raw x y A k hs hz ht hL + let Q := layer x y A k hs hz ht hL + have hk : k < i.w := Nat.lt_succ_of_le (le_max_left ..) + have hw : i.h + i.snd < i.w := Nat.lt_succ_of_le (le_max_right ..) + obtain ⟨a, ha⟩ := Restore.stage ok (feasible hs hz ht) (arity hs hz ht hL) W hm hd hc hk hw + let b := (Restore.program A i.N i.r i.s i.w).gate + let c := P.encoding.sweepTable + let d := (Merge.script Q).gate + let menu : Finset (Table F) := {a, b, c, d} + refine ⟨menu, ?_, ?_⟩ + · exact (Finset.card_insert_le ..).trans (Nat.add_le_add_right Finset.card_le_three _) + intro U C hu incl fit + have ga : a ∈ C := incl (by simp [menu]) + have gb : b ∈ C := incl (by simp [menu]) + have gc : c ∈ C := incl (by simp [menu]) + have gd : d ∈ C := incl (by simp [menu]) + obtain ⟨hf, he⟩ := hK x y A k hs hz ht hL W + have widths := hf.trans fit + obtain ⟨h₁, h₂, h₃, h₄⟩ : + Restore.gateWidth A i.N i.r i.s ≤ U ∧ Restore.commandSize A i.N i.r i.s i.w ≤ U ∧ + 2 * (Restore.script A.scheme).width ≤ U ∧ + SpanProgram.size Q.template.scheme 0 (Q.height + 1) (Merge.dim Q.template.scheme) ≤ U := by + refine ⟨?_, ?_, ?_, (Nat.le_add_left ..).trans widths⟩ + · exact ((Nat.le_add_right ..).trans + ((Nat.le_add_right ..).trans (Nat.le_add_right ..))).trans widths + · exact ((Nat.le_add_left ..).trans + ((Nat.le_add_right ..).trans (Nat.le_add_right ..))).trans widths + · exact ((Nat.le_add_left ..).trans (Nat.le_add_right ..)).trans widths + have recode := ha hu ga gb h₁ h₂ + have clean := Restore.withdraw (fun j => data hs hz ht j) (height s T) (arity hs hz ht hL) hu h₃ + gc + have join := Merge.transforms Q (ready x y A k hs hz ht hL).2 rfl W hu h₄ gd + (hm.trans (Nat.le_add_right ..)) (more.trans_lt hc) + exact ((recode.comp clean).comp join).mono he + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Recovery +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Scale.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Scale.lean new file mode 100644 index 0000000000..042c796062 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Scale.lean @@ -0,0 +1,993 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Bins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.RestoreCost +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Design +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Projection + +/-! # Weighted expansions with independent exterior positions -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Finset + +variable {F : Type} [Field F] {x y : Wire} {a b : ℕ} + +/-- The index budget counts binary choices. Scalar factors include any +zero-arity stations removed between rounds. -/ +def Expansion (f : Val x → Val y → F) (n : ℕ) (P : Board F x y a → Prop) : Prop := + ∃ (I : Type) (_ : Fintype I) (q : I → Board F x y a) (c : I → F), + Fintype.card I ≤ 2 ^ n ∧ (∀ x y, ∑ i, c i * (q i).diagram.eval x y = f x y) ∧ ∀ i, P (q i) + +variable {f : Val x → Val y → F} {P P' : Board F x y a → Prop} {Q : Board F x y b → Prop} + {n m : ℕ} + +theorem Expansion.single (q : Board F x y a) (hq : P q) : Expansion q.diagram.eval n P := + ⟨Unit, inferInstance, fun _ => q, fun _ => 1, Nat.one_le_pow _ _ (by decide), + fun _ _ => by simp, fun _ => hq⟩ + +theorem Expansion.mono (hf : Expansion f n P) (h : n ≤ m) (hp : ∀ q, P q → P' q) : + Expansion f m P' := by + obtain ⟨I, _, q, c, hi, he, hq⟩ := hf + exact ⟨I, inferInstance, q, c, hi.trans (Nat.pow_le_pow_right (by decide) h), he, fun i + => hp _ (hq i)⟩ + +theorem Expansion.bind (hf : Expansion f n P) (hg : ∀ q, P q → Expansion q.diagram.eval m Q) : + Expansion f (n + m) Q := by + obtain ⟨I, _, q, c, hi, he, hp⟩ := hf + choose J hJ t d ht he' hp' using fun i => hg (q i) (hp i) + let : ∀ i, Fintype (J i) := hJ + refine ⟨Σ i, J i, inferInstance, fun p => t p.1 p.2, fun p => c p.1 * d p.1 p.2, ?_, ?_, ?_⟩ + · rw [Fintype.card_sigma, pow_add] + refine le_trans (sum_le_sum (s := univ) fun i _ => ht i) ?_ + simpa only [sum_const, card_univ, Nat.nsmul_eq_mul] using Nat.mul_le_mul_right (2 ^ m) hi + · intro x y + rw [Fintype.sum_sigma, ← he x y] + apply sum_congr rfl + intro i _ + rw [← he' i x y, mul_sum] + exact sum_congr rfl (fun j _ => mul_assoc _ _ _) + · exact fun p => hp' p.1 p.2 + +omit [Field F] in +theorem Board.Ready.relax {P : Board F x y a} {g g' D T : ℕ} {L L' θ θ' : ℝ} + (h : P.Ready g D T L θ) (hg : g ≤ g') (hL : L ≤ L') (hθ : θ' ≤ θ) : + P.Ready g' D T L' θ' := by + refine ⟨fun v => (h.1 v).trans hg, h.2.1.trans hL, + h.2.2.1.trans (mul_le_mul_of_nonneg_right hL (Nat.cast_nonneg _)), fun v => ?_⟩ + exact ⟨(h.2.2.2 v).1, (h.2.2.2 v).2.imp_right fun ht => + (mul_le_mul_of_nonneg_right hθ (Nat.cast_nonneg _)).trans ht⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Iterating rounds with uniform control of all summands -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +/-- A round divides the total budget by `2^gain` and multiplies the +width by `2^growth`. The initial host degree bound is five. -/ +structure Design (δ : ℝ) where + /-- The `Design` field of type `ℕ`. -/ + D : ℕ + /-- The number of transitions. -/ + steps : ℕ + /-- Stores the gain associated with this `Design`. -/ + gain : ℕ + /-- Stores the growth associated with this `Design`. -/ + growth : ℕ + /-- Stores the overhead associated with this `Design`. -/ + overhead : ℕ + /-- Stores the floor associated with this `Design`. -/ + floor : ℝ + large : 8 ≤ D + steps_pos : 0 < steps + gain_pos : 0 < gain + growth_pos : 0 < growth + overhead_large : 2 ≤ overhead + floor_pos : 0 < floor + floor_le : floor ≤ 4 + ratio : (growth : ℝ) ≤ gain * (1 + δ / 3) + +namespace Design + +variable {δ : ℝ} (p : Design δ) + +/-- The quantity computed by `2 ^ (p.growth * i) * T`. -/ +def width (T i : ℕ) := 2 ^ (p.growth * i) * T + +/-- The quantity computed by `L / (2 : ℝ) ^ (p.gain * i)`. -/ +def budget (L : ℝ) (i : ℕ) := L / (2 : ℝ) ^ (p.gain * i) + +/-- The quantity computed by `p.overhead * (1 + Nat.clog 2 (T + 1)) * ⌈L / (T : ℝ)⌉₊`. -/ +def bits (T : ℕ) (L : ℝ) := p.overhead * (1 + Nat.clog 2 (T + 1)) * ⌈L / (T : ℝ)⌉₊ + +/-- The works of type `Prop` for the given inputs. -/ +def Works (F : Type) [Field F] (T : ℕ) : Prop := + ∀ {x y : Wire} {h : ℕ} (P : Board F x y h) (r a : ℕ) (L : ℝ), + P.Ready 5 p.D T L p.floor → a + p.steps * r ≤ h → p.overhead ≤ 2 ^ r → + ((wd x + wd y : ℕ) : ℝ) * p.D ≤ L → (p.overhead : ℝ) * T * P.seats ≤ L * (2 : ℝ) ^ r → + Expansion P.diagram.eval (p.bits T L) (fun Q : Board F x y a => + Q.Ready 5 p.D (2 ^ p.growth * T) (L / 2 ^ p.gain) p.floor ∧ Q.seats ≤ p.overhead * P.seats) + +theorem width_succ (T i : ℕ) : p.width T (i + 1) = 2 ^ p.growth * p.width T i := by + simp only [width, mul_add, mul_one, pow_add] + ring + +theorem budget_succ (L : ℝ) (i : ℕ) : p.budget L (i + 1) = p.budget L i / 2 ^ p.gain := by + simp only [budget, mul_add, mul_one, pow_add, div_div] + +theorem iterate {F : Type} [Field F] {x y : Wire} {h : ℕ} (P : Board F x y h) + (T j a r : ℕ) (L : ℝ) (initial : P.Ready 5 p.D T L p.floor) + (steps : a + p.steps * j * r = h) (size : p.overhead ≤ 2 ^ r) + (ok : ∀ i < j, p.Works F (p.width T i)) + (exposed : ∀ i < j, ((wd x + wd y : ℕ) : ℝ) * p.D ≤ p.budget L i) + (slack : ∀ i < j, (p.overhead : ℝ) * p.width T i * (p.overhead ^ i * P.seats : ℕ) ≤ + p.budget L i * (2 : ℝ) ^ r) : + Expansion P.diagram.eval (∑ i ∈ Finset.range j, p.bits (p.width T i) (p.budget L i)) + (fun Q : Board F x y a => Q.Ready 5 p.D (p.width T j) (p.budget L j) p.floor ∧ + Q.seats ≤ p.overhead ^ j * P.seats) := by + induction j generalizing a with + | zero => + have : a = h := by simpa using steps + subst a + refine Expansion.single P ?_ + simpa only [width, budget, pow_zero, mul_zero, div_one, one_mul, le_refl, and_true] + | succ j ih => + have he := ih (a + p.steps * r) (by rw [← steps]; ring) + (fun i hi => ok i (by omega)) (fun i hi => exposed i (by omega)) + (fun i hi => slack i (by omega)) + rw [Finset.sum_range_succ] + apply he.bind + rintro q ⟨hr, hb⟩ + have hm := ok j (by omega) q r a (p.budget L j) hr le_rfl size (exposed j (by omega)) + ((mul_le_mul_of_nonneg_left (Nat.cast_le.mpr hb) (by positivity)).trans (slack j (by omega))) + refine hm.mono le_rfl (fun t ht => ?_) + rw [p.width_succ, p.budget_succ, pow_succ', mul_assoc] + exact ⟨ht.1, ht.2.trans (Nat.mul_le_mul_left _ hb)⟩ + +end Design +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +section +/- +# Restarting a round after tether restoration + +The full degree may grow as a power whose exponent itself grows +exponentially in the number of beats. Only its logarithm enters the +mass loss. The square loss uses the shorter tree at a frozen member. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing + +private theorem tether_steps (l j : ℕ) : + Detour.steps (Tether.width (2 ^ l) (2 ^ j) (2 ^ j)) ≤ 2 * (l + 2 * j + 2) + 3 := by + have h : Nat.clog 2 (Tether.width (2 ^ l) (2 ^ j) (2 ^ j)) ≤ l + 2 * j + 2 := by + apply Nat.clog_le_of_le_pow + rw [Tether.width, Nat.clog_pow _ _ (by decide)] + have hs : 2 ^ j + 1 ≤ 2 ^ (j + 1) := by + rw [pow_succ] + have := Nat.one_le_pow j 2 (by decide) + omega + calc + _ ≤ 2 ^ l * 2 ^ (j + 1) * 2 ^ (j + 1) := by gcongr + _ = _ := by rw [← pow_add, ← pow_add]; congr 1; omega + unfold Detour.steps + omega + +/-- Choose a working scale, number of beats and restart multiplier +before choosing the input network or working extension. -/ +theorem choose_restart (c e b H d₀ : ℕ) (A B δ : ℝ) + (hA : 0 ≤ A) (hB : 0 ≤ B) (hδ : 0 < δ) (hδ' : δ ≤ 1) : + ∃ d v p : ℕ, + let D : ℕ := 2 ^ d + let t := 2 * v + let s := D ^ (c + 15) + let a : ℝ := Nat.clog 2 s + let m : ℝ := Detour.steps (Tether.width (D ^ (c * e ^ t)) s s) + d₀ ≤ d ∧ 0 < v ∧ 0 < p ∧ (p : ℝ) ≤ v * (1 + δ / 3) ∧ b ^ t ≤ D ∧ H ^ t ≤ D ∧ + 2 * ((1 / 2) ^ t * A * (1 + (d : ℝ)) ^ 2 + B * ((A + 1) / Real.sqrt D)) + + (1 + 2 * (m + a)) * (A / Real.sqrt D) ≤ 1 / (2 : ℝ) ^ v ∧ + 3 * (1 + 4 * a) * A + 9 ≤ (2 : ℝ) ^ p / (2 : ℝ) ^ v ∧ + 3 * (1 + A * (D : ℝ)) ≤ (D : ℝ) * (2 : ℝ) ^ p / 2 := by + let k := 29 * A + 2 * B * (A + 1) + 9 + have hk : 0 ≤ k := by unfold k; positivity + obtain ⟨d, v, p, hd, hv, hvd, hscale, hvp, hp, hsmall, hgain⟩ := + Shaving.choose_round hδ hδ' (e + b + H) (k * (c + 15)) (by positivity) 2 d₀ + let D : ℕ := 2 ^ d + let t := 2 * v + let s := D ^ (c + 15) + let a : ℝ := Nat.clog 2 s + let m : ℝ := Detour.steps (Tether.width (D ^ (c * e ^ t)) s s) + let G := (2 : ℝ) ^ v + let E := (D : ℝ) ^ (1 / 100 : ℝ) + have hD : 1 ≤ (D : ℝ) := by + simp only [D, Nat.cast_pow, Nat.cast_ofNat] + exact one_le_pow₀ (by norm_num) + have hG : 1 ≤ G := one_le_pow₀ (by norm_num) + have hGE : G ≤ E := by + have ht : (100 : ℝ) * v ≤ d := by exact_mod_cast hvd + unfold G E D + rw [Nat.cast_pow, Nat.cast_ofNat, ← Real.rpow_natCast_mul (by norm_num), + ← Real.rpow_natCast 2 v] + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + have hE : 1 ≤ E := hG.trans hGE + have hED : E ≤ (D : ℝ) := by + simpa only [Real.rpow_one] using Real.rpow_le_rpow_of_exponent_le hD (by norm_num : (1 / 100 : + ℝ) ≤ 1) + have hroot : G ^ 2 * E ≤ Real.sqrt D := calc + _ ≤ E ^ 2 * E := by gcongr + _ = (D : ℝ) ^ ((1 / 100 : ℝ) * 3) := by + rw [← pow_succ, show (3 : ℝ) = ↑(3 : ℕ) by norm_num, Real.rpow_mul_natCast (by positivity)] + _ ≤ _ := by rw [Real.sqrt_eq_rpow]; exact Real.rpow_le_rpow_of_exponent_le hD (by norm_num) + have grow (x : ℕ) (hx : x ≤ e + b + H) : (x : ℝ) ^ t ≤ E := calc + _ ≤ ((e : ℝ) + b + H) ^ t := pow_le_pow_left₀ (Nat.cast_nonneg _) (by exact_mod_cast hx) _ + _ ≤ _ := by simpa only [E, D, Nat.cast_pow, Nat.cast_ofNat] using hscale + have bound (x : ℕ) (hx : x ≤ e + b + H) : x ^ t ≤ D := by + exact_mod_cast (grow x hx).trans hED + have hp' : 0 < p := by + have : (0 : ℝ) < p := lt_of_lt_of_le (by positivity) hvp + exact_mod_cast this + let f := (1 + (d : ℝ)) ^ 2 * ((c : ℝ) + 15) + have hdf : (1 + (d : ℝ)) ^ 2 ≤ f := le_mul_of_one_le_right (by positivity) (by linarith) + have hf : 1 ≤ f := le_trans (one_le_pow₀ (by linarith)) hdf + have hfE : f ≤ f * E := le_mul_of_one_le_right (by positivity) hE + have square_bound : (d : ℝ) ≤ (1 + (d : ℝ)) ^ 2 := by + nlinarith only [Nat.cast_nonneg (α := ℝ) d, sq_nonneg (d : ℝ)] + have hf₂ : (d : ℝ) * (c + 15) ≤ f := + mul_le_mul_of_nonneg_right square_bound (by positivity) + have ha : a ≤ f := by + simpa only [a, s, D, ← pow_mul, Nat.clog_pow 2 _ (by decide), Nat.cast_mul, Nat.cast_add, + Nat.cast_ofNat] using hf₂ + have hm : m ≤ 13 * f * E := by + have hm' : Detour.steps (Tether.width (D ^ (c * e ^ t)) s s) ≤ + 2 * (d * (c * e ^ t) + 2 * (d * (c + 15)) + 2) + 3 := by + simpa only [D, s, pow_mul] using tether_steps (d * (c * e ^ t)) (d * (c + 15)) + have h : m ≤ 2 * ((d : ℝ) * (c * (e : ℝ) ^ t) + 2 * (d * (c + 15)) + 2) + 3 := by + unfold m + exact_mod_cast hm' + have hi : (d : ℝ) * c * (e : ℝ) ^ t ≤ f * E := mul_le_mul + (le_trans (by gcongr; linarith) hf₂) (grow e (by omega)) (by positivity) (by positivity) + linarith only [h, hi, hf₂, hfE, hf] + have hfirst : k * f ≤ G / 2 := by unfold f G; linarith only [hsmall] + have hsecond : 2 * k * f ≤ (2 : ℝ) ^ p / G := by + apply (le_div_iff₀ (by positivity)).mpr + unfold G f + linarith only [hgain] + have hbase : 29 * A + 9 ≤ k := by + have cross_nonneg : 0 ≤ 2 * B * (A + 1) := by positivity + unfold k + linarith only [cross_nonneg] + refine ⟨d, v, p, hd, hv, hp', hp, bound b (by omega), bound H (by omega), ?_, ?_, ?_⟩ + · have hcore : 2 * A * (1 + d) ^ 2 ≤ G / 2 := + (mul_le_mul (by linarith : 2 * A ≤ k) hdf (by positivity) hk).trans hfirst + have htail : 2 * B * (A + 1) + (1 + 2 * (m + a)) * A ≤ G / 2 * E := by + have h₁ := mul_le_mul_of_nonneg_right (show 1 + 2 * (m + a) + ≤ 29 * f * E by linarith only [hm, ha, hf, hfE]) hA + have h₂ := le_mul_of_one_le_right (show 0 ≤ 2 * B * (A + 1) by positivity) (hf.trans hfE) + refine le_trans ?_ (mul_le_mul_of_nonneg_right hfirst (by positivity : 0 ≤ E)) + unfold k + linarith only [h₁, h₂, hf, hfE] + have hpow : (1 / 2 : ℝ) ^ t = 1 / G ^ 2 := by simp only [t, G, one_div_pow, pow_mul'] + change 2 * ((1 / 2 : ℝ) ^ t * A * (1 + d) ^ 2 + B * ((A + 1) / Real.sqrt D)) + (1 + 2 * (m + + a)) * (A / Real.sqrt D) ≤ 1 / G + calc + _ = (2 * A * (1 + d) ^ 2) / G ^ 2 + (2 * B * (A + 1) + (1 + 2 * (m + a)) * A) / Real.sqrt D + := by rw [hpow]; ring + _ ≤ (G / 2) / G ^ 2 + (G / 2 * E) / (G ^ 2 * E) := by gcongr + _ = _ := by field_simp; ring + · have hi := mul_le_mul_of_nonneg_right (show 3 * (1 + 4 * a) + ≤ 15 * f by linarith only [ha, hf]) hA + have := mul_le_mul_of_nonneg_right hbase (show 0 ≤ f by positivity) + change 3 * (1 + 4 * a) * A + 9 ≤ (2 : ℝ) ^ p / G + linarith only [hi, this, hf, hsecond, mul_nonneg hA (show 0 ≤ f by positivity)] + · have hi : 6 * (1 + A) ≤ (2 : ℝ) ^ p := calc + _ ≤ 2 * k := by linarith + _ ≤ 2 * k * f := le_mul_of_one_le_right (by positivity) hf + _ ≤ (2 : ℝ) ^ p / G := hsecond + _ ≤ _ := div_le_self (by positivity) hG + have := mul_le_mul_of_nonneg_left hi (show 0 ≤ (D : ℝ) by positivity) + change 3 * (1 + A * (D : ℝ)) ≤ (D : ℝ) * (2 : ℝ) ^ p / 2 + linarith only [hD, this] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # From the initial stack to the terminal family of charged boards -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Design + +open Finset +variable {δ : ℝ} (p : Design δ) + +private theorem width_pow (t i : ℕ) : p.width (2 ^ t) i = 2 ^ (t + p.growth * i) := by + rw [width, pow_add, mul_comm] + +private theorem bits_le (t i j S : ℕ) (hi : i ≤ j) : + p.bits (p.width (2 ^ t) i) (p.budget ((S : ℝ) * 2 ^ t) i) ≤ + p.overhead * (2 + t + p.growth * j) * S := by + have hw : 0 < p.width (2 ^ t) i := by rw [width_pow]; positivity + have hlog : Nat.clog 2 (p.width (2 ^ t) i + 1) ≤ 1 + t + p.growth * j := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [p.width_pow, show 1 + t + p.growth * j = (t + p.growth * j) + 1 by omega, pow_succ] + have a : 2 ^ (t + p.growth * i) ≤ (2 : ℕ) ^ (t + p.growth * j) := by gcongr + have b : 0 < (2 : ℕ) ^ (t + p.growth * j) := by positivity + omega + have hs : ⌈p.budget ((S : ℝ) * 2 ^ t) i / p.width (2 ^ t) i⌉₊ ≤ S := by + apply Nat.ceil_le.mpr + rw [div_le_iff₀ (Nat.cast_pos.mpr hw)] + refine le_trans (div_le_self (by positivity) (one_le_pow₀ (by norm_num))) ?_ + rw [width_pow, Nat.cast_pow, Nat.cast_ofNat] + gcongr + · norm_num + · omega + unfold bits + exact Nat.mul_le_mul (Nat.mul_le_mul_left _ (by omega)) hs + +/-- Each round can spend the same exponent of two on grouping. +Both the exterior condition and slack are checked before iteration. -/ +theorem run {F : Type} [Field F] {x y : Wire} (G : Diagram F x y) (t j a r m : ℕ) + (size : G.cost ≤ m) (arity : ∀ v, G.arity v ≤ 2 ^ t) + (ok : ∀ i < j, p.Works F (p.width (2 ^ t) i)) + (ext : (wd x + wd y) * p.D * 2 ^ (p.gain * j) ≤ m) + (room : p.overhead ^ (j + 1) * 2 ^ ((p.gain + p.growth) * j) ≤ 2 ^ r) : + let h := a + p.steps * j * r + let d := 2 ^ t * 2 ^ h + let S := 32 * m * (t + 1) * 2 ^ h + Expansion (power G.eval d) (j * (p.overhead * (2 + t + p.growth * j) * S)) + (fun Q : Board F _ _ a => + Q.Ready 5 p.D (2 ^ (t + p.growth * j)) (((S : ℝ) * 2 ^ t) / (2 : ℝ) ^ (p.gain * j)) p.floor + ∧ + Q.seats ≤ p.overhead ^ j * S) := by + intro h d S + obtain ⟨P, he, hp, initial⟩ := Stack.initial G t h p.D p.floor arity p.large p.floor_le + have total : 16 * P.seats ≤ S := calc + _ ≤ 16 * (2 * m * (t + 1) * 2 ^ h) := by + unfold Board.seats + gcongr + exact hp.trans (by gcongr) + _ = _ := by unfold S; ring + have hseat : P.seats ≤ S := (Nat.le_mul_of_pos_left _ (by decide : 0 < 16)).trans total + let L := (S : ℝ) * 2 ^ t + have start : P.Ready 5 p.D (2 ^ t) L p.floor := by + refine initial.relax le_rfl ?_ le_rfl + have hx : 16 * (P.seats : ℝ) ≤ S := by exact_mod_cast total + rw [mul_right_comm] + exact mul_le_mul_of_nonneg_right hx (by positivity) + have limit i (hi : i ≤ j) : p.overhead ^ (i + 1) * 2 ^ ((p.gain + p.growth) * i) ≤ 2 ^ r := by + have := p.overhead_large + refine le_trans ?_ room + gcongr + have hsize : p.overhead ≤ 2 ^ r := by simpa using limit 0 (Nat.zero_le j) + have exposed i (hi : i < j) : + ((wd (copies x d) + wd (copies y d) : ℕ) : ℝ) * p.D ≤ p.budget L i := by + have hx : (wd x + wd y) * p.D * 2 ^ (p.gain * i) ≤ m := by + apply le_trans _ ext + gcongr + rw [budget, le_div_iff₀ (by positivity), wd_copies, wd_copies, ← Nat.mul_add] + have hm : m * 2 ^ h ≤ S := by + unfold S + exact Nat.mul_le_mul_right _ ((Nat.le_mul_of_pos_left _ (by decide : 0 < 32)).trans + (Nat.le_mul_of_pos_right _ (by omega))) + have he : d * (wd x + wd y) * p.D * 2 ^ (p.gain * i) ≤ S * 2 ^ t := calc + _ = ((wd x + wd y) * p.D * 2 ^ (p.gain * i)) * 2 ^ h * 2 ^ t := by unfold d; ring + _ ≤ _ := Nat.mul_le_mul_right _ ((Nat.mul_le_mul_right _ hx).trans hm) + unfold L + exact_mod_cast he + have slack i (hi : i < j) : + (p.overhead : ℝ) * p.width (2 ^ t) i * (p.overhead ^ i * P.seats : ℕ) ≤ p.budget L i * 2 ^ r + := by + have hh : p.overhead * p.width (2 ^ t) i * (p.overhead ^ i * P.seats) * 2 ^ (p.gain * i) ≤ + S * 2 ^ t * 2 ^ r := calc + _ = (P.seats * 2 ^ t) * (p.overhead ^ (i + 1) * 2 ^ ((p.gain + p.growth) * i)) := by + rw [width, add_mul, pow_add 2 (p.gain * i) (p.growth * i), pow_succ p.overhead] + ring + _ ≤ _ := Nat.mul_le_mul (Nat.mul_le_mul_right _ hseat) (limit i hi.le) + rw [budget, div_mul_eq_mul_div, le_div_iff₀ (by positivity)] + unfold L + exact_mod_cast hh + have ht := p.iterate P (2 ^ t) j a r L start rfl hsize ok exposed slack + have hb : (∑ i ∈ range j, p.bits (p.width (2 ^ t) i) (p.budget L i)) ≤ + j * (p.overhead * (2 + t + p.growth * j) * S) := by + simpa using sum_le_sum (s := range j) (fun i hi => p.bits_le t i j S (mem_range.mp hi).le) + rw [he, width_pow] at ht + exact ht.mono hb (fun _ hq => ⟨hq.1, hq.2.trans (Nat.mul_le_mul_left _ hseat)⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Design +end + +/- +# A uniform choice of stack and group sizes + +The reserve exponent `M` affects the number of remaining blocks. +The exponent controlling the cost of one group is independent of `M`. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Filter + +variable {δ : ℝ} (p : Design δ) + +/-- All size parameters here are exponents of two. -/ +structure Levels (p : Design δ) (M : ℕ) where + /-- The `Levels` field of type `ℕ`. -/ + j : ℕ + /-- Stores the stack associated with this `Levels`. -/ + stack : ℕ + /-- The height parameter carried by `Levels`, with type `ℕ`. -/ + height : ℕ + +/-- The quantity computed by `p.overhead + (p.gain + p.growth)`. -/ +def Design.groupRate := p.overhead + (p.gain + p.growth) + +namespace Levels + +variable {p} {M : ℕ} (v : Levels p M) + +/-- The quantity computed by `p.groupRate * (v.j + 1)`. -/ +def group := p.groupRate * (v.j + 1) +/-- The quantity computed by `M * v.height`. -/ +def remaining := M * v.height +/-- The quantity computed by `v.remaining + p.steps * v.j * v.group`. -/ +def blocks := v.remaining + p.steps * v.j * v.group +/-- The quantity computed by `2 ^ v.stack * 2 ^ v.blocks`. -/ +def batch := 2 ^ v.stack * 2 ^ v.blocks +/-- The quantity computed by `2 ^ (v.stack + p.growth * v.j)`. -/ +def finalWidth := 2 ^ (v.stack + p.growth * v.j) +/-- The quantity computed by `32 * m * (v.stack + 1) * 2 ^ v.blocks`. -/ +def allocation (m : ℕ) := 32 * m * (v.stack + 1) * 2 ^ v.blocks +/-- The quantity computed by `(v.allocation m : ℝ) * 2 ^ v.stack / (2 : ℝ) ^ (p.gain * v.j)`. -/ +def finalBudget (m : ℕ) := (v.allocation m : ℝ) * 2 ^ v.stack / (2 : ℝ) ^ (p.gain * v.j) +/-- The quantity computed by `v.j * (p.overhead * (2 + v.stack + p.growth * v.j) * v.allocation +m)`. -/ +def selector (m : ℕ) := v.j * (p.overhead * (2 + v.stack + p.growth * v.j) * v.allocation m) + +theorem room : p.overhead ^ (v.j + 1) * 2 ^ ((p.gain + p.growth) * v.j) ≤ 2 ^ v.group := by + unfold group Design.groupRate + rw [add_mul p.overhead, pow_add 2, pow_mul 2 p.overhead] + exact Nat.mul_le_mul (Nat.pow_le_pow_left Nat.lt_two_pow_self.le _) + (Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_left _ (Nat.le_succ v.j))) + +/-- The least binary width whose power of two reaches the stated size. -/ +def Suits (n T₀ : ℕ) (a b ξ : ℝ) : Prop := + let h : ℝ := Nat.clog 2 n + 0 < v.j ∧ 1 < h ∧ h ≤ (2 : ℝ) ^ v.height ∧ (2 : ℝ) ^ v.height ≤ 2 * h ∧ + h ^ b ≤ (2 : ℝ) ^ v.stack ∧ (2 : ℝ) ^ v.stack ≤ 2 * h ^ b ∧ T₀ ≤ 2 ^ v.stack ∧ + h ^ a ≤ (2 : ℝ) ^ (p.gain * v.j) ∧ (p.D : ℝ) * (2 : ℝ) ^ (p.gain * v.j) ≤ h ^ (2 * a) ∧ + (v.finalWidth : ℝ) ≤ (2 : ℝ) ^ (p.growth + 1) * h ^ (b + (1 + δ / 3) * a) ∧ + v.finalWidth ≤ (Nat.clog 2 n) ^ 4 ∧ + (2 : ℝ) ^ v.group ≤ (2 : ℝ) ^ (2 * p.groupRate) * h ^ (p.groupRate * a) ∧ + (v.batch : ℝ) ≤ (n : ℝ) ^ ξ + +end Levels + +theorem Design.levels (hδ : δ ≤ 1) (T₀ M : ℕ) {a b ξ : ℝ} + (ha : 0 < a) (ha' : a ≤ 1) (hb : 0 < b) (hb' : b ≤ 1) (hξ : 0 < ξ) : + ∀ᶠ n : ℕ in atTop, ∃ v : Levels p M, v.Suits n T₀ a b ξ := by + have ht := Shaving.tendsto_height + filter_upwards [Shaving.stage_parameters p.gain p.growth p.groupRate p.steps M + p.gain_pos a b δ ξ ha ha' hb hb' p.ratio hξ, ht.eventually_gt_atTop 1, + ((tendsto_rpow_atTop hb).comp ht).eventually_ge_atTop (T₀ : ℝ), + ((tendsto_rpow_atTop ha).comp ht).eventually_ge_atTop ((p.D : ℝ) * (2 : ℝ) ^ p.gain), + ht.eventually_ge_atTop ((2 : ℝ) ^ (p.growth + 1))] with n scales hh hlow hgain hmax + let h : ℝ := Nat.clog 2 n + have hpos : 0 < h := zero_lt_one.trans hh + obtain ⟨j, t, l, hj, hl, hl', hw, hw', hg, hg', hq, hr, hd⟩ := scales + let v : Levels p M := ⟨j, t, l⟩ + have hbig : (v.finalWidth : ℝ) ≤ (2 : ℝ) ^ (p.growth + 1) * h ^ (b + (1 + δ / 3) * a) := by + calc + _ = (2 : ℝ) ^ t * 2 ^ (p.growth * j) := by + change ((2 ^ (t + p.growth * j) : ℕ) : ℝ) = _ + rw [Nat.cast_pow, Nat.cast_ofNat, pow_add] + _ ≤ (2 * h ^ b) * ((2 : ℝ) ^ p.growth * h ^ ((1 + δ / 3) * a)) := + mul_le_mul hw' hq (by positivity) (by positivity) + _ = _ := by rw [Real.rpow_add hpos, pow_succ]; ring + refine ⟨v, hj, hh, hl, hl', hw, hw', ?_, hg, ?_, hbig, ?_, hr, ?_⟩ + · have : (T₀ : ℝ) ≤ (2 : ℝ) ^ t := hlow.trans hw + exact_mod_cast this + · calc + _ ≤ (p.D : ℝ) * ((2 : ℝ) ^ p.gain * h ^ a) := mul_le_mul_of_nonneg_left hg' (by positivity) + _ ≤ h ^ a * h ^ a := by + rw [← mul_assoc] + exact mul_le_mul_of_nonneg_right hgain (by positivity) + _ = _ := by rw [← Real.rpow_add hpos, two_mul] + · have product_bound : δ * a ≤ 1 := + (mul_le_mul_of_nonneg_right hδ ha.le).trans (by simpa only [one_mul] using ha') + have hbound : b + (1 + δ / 3) * a ≤ 3 := by + nlinarith only [hb', ha', product_bound] + have hh' : (v.finalWidth : ℝ) ≤ h ^ 4 := calc + _ ≤ _ := hbig + _ ≤ h * h ^ (3 : ℝ) := mul_le_mul hmax (Real.rpow_le_rpow_of_exponent_le hh.le hbound) + (by positivity) hpos.le + _ = h ^ (4 : ℕ) := by norm_num; ring + unfold h at hh' + exact_mod_cast hh' + · unfold Levels.batch Levels.blocks Levels.remaining Levels.group + simp only [v, Nat.cast_pow, Nat.cast_ofNat, ← pow_add] + rw [show t + (M * l + p.steps * j * (p.groupRate * (j + 1))) = + t + M * l + p.groupRate * (j + 1) * (p.steps * j) by ring] + exact hd + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Budgets at the exit of a round -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing + +/-- Fixed parameters after the number of beats has been chosen. -/ +structure Plan where + /-- The `Plan` field of type `ℕ`. -/ + C : ℕ + /-- The `Plan` field of type `ℕ`. -/ + d : ℕ + /-- The `Plan` field of type `ℕ`. -/ + v : ℕ + /-- The `Plan` field of type `ℕ`. -/ + p : ℕ + /-- The right component. -/ + b : ℕ + /-- The `Plan` field of type `ℕ`. -/ + n : ℕ + /-- The `Plan` field of type `ℕ`. -/ + e : ℕ + /-- The `Plan` field of type `ℕ`. -/ + K : ℕ + /-- Stores the loss associated with this `Plan`. -/ + loss : ℝ + +namespace Plan +variable (s : Plan) + +/-- The quantity computed by `2 ^ s.d`. -/ +def D := 2 ^ s.d +/-- The quantity computed by `s.C + 12`. -/ +def c := s.C + 12 +/-- The quantity computed by `10000 * (s.C + 1)`. -/ +def A := 10000 * (s.C + 1) +/-- The quantity computed by `(1 / 2) ^ (2 * s.v)`. -/ +def ρ : ℝ := (1 / 2) ^ (2 * s.v) +/-- The quantity computed by `s.D ^ (s.c * s.e)`. -/ +def full := s.D ^ (s.c * s.e) +/-- The quantity computed by `s.D ^ (s.c + 15)`. -/ +def slots := s.D ^ (s.c + 15) +/-- Computes the w by the application `Tether.width s.full s.slots s.slots`. -/ +def w := Tether.width s.full s.slots s.slots +/-- The quantity computed by `s.D ^ (s.c + 2)`. -/ +def M := s.D ^ (s.c + 2) +/-- The quantity computed by `1 / ((s.M : ℝ) * (2 : ℝ) ^ s.p)`. -/ +def floor : ℝ := 1 / ((s.M : ℝ) * (2 : ℝ) ^ s.p) +/-- The quantity computed by `(1 + s.slots * 2 ^ (Nat.clog 2 s.slots + 1)) * (1 + 2 ^ (Nat.clog +2 s.w + 1)) * s.K * s.D ^ s.C`. -/ +def seats := (1 + s.slots * 2 ^ (Nat.clog 2 s.slots + 1)) * (1 + 2 ^ (Nat.clog 2 s.w + + 1)) * s.K * s.D ^ s.C +/-- The quantity computed by `(s.A * (1 + s.d) ^ 2 + s.A + 1) * s.M`. -/ +def cover := (s.A * (1 + s.d) ^ 2 + s.A + 1) * s.M + +/-- The data for the fits construction, including `degree`, `overhead`, `unit`, `mass`, +`squares`. -/ +structure Fits : Prop where + degree : s.c ≤ s.D + overhead : s.K ≤ s.D + unit : s.b ≤ s.D + mass : 2 * (s.ρ * s.A * (1 + (s.d : ℝ)) ^ 2 + s.loss * ((s.A + 1) / Real.sqrt s.D)) + + (1 + 2 * ((Detour.steps s.w : ℝ) + Nat.clog 2 s.slots)) * (s.A / Real.sqrt s.D) + ≤ 1 / (2 : ℝ) ^ s.v + squares : 3 * (1 + 4 * (Nat.clog 2 s.slots : ℝ)) * s.A + 9 ≤ (2 : ℝ) ^ s.p / (2 : ℝ) ^ s.v + max : 3 * (1 + (s.A : ℝ) * s.D) ≤ (s.D : ℝ) * (2 : ℝ) ^ s.p / 2 + +theorem small : s.C ≤ s.c := Nat.le_add_right _ _ +theorem two (hs : s.Fits) : 2 ≤ s.D := (show 2 ≤ s.c by unfold c; omega).trans hs.degree +theorem cost_le : (s.C : ℝ) * 10000 ≤ s.A := by simp [A]; linarith + +/-- Round down to a multiple of the complete subdivision factor. -/ +theorem units (hs : s.Fits) (hb : 0 < s.b) (T : ℕ) (ht : s.b * s.D ^ s.c ≤ T) : + ∃ z : ℕ, 0 < z ∧ (s.b * z) * s.D ^ s.c ≤ T ∧ T ≤ z * s.M := by + let n := s.b * s.D ^ s.c + have hd := s.two hs + have hn : 0 < n := by unfold n; positivity + let z := T / n + have hz : 0 < z := Nat.div_pos ht hn + refine ⟨z, hz, ?_, ?_⟩ + · rw [mul_comm s.b, mul_assoc] + exact Nat.div_mul_le_self _ _ + have hcap : 2 * n ≤ s.M := by + unfold M n + rw [pow_add, pow_two] + calc + _ = s.D ^ s.c * (2 * s.b) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ (Nat.mul_le_mul hd hs.unit) + calc + T ≤ z * n + n := (Nat.lt_div_mul_add hn).le + _ ≤ z * (2 * n) := by + rw [two_mul, mul_add] + exact Nat.add_le_add_left (Nat.le_mul_of_pos_left n hz) _ + _ ≤ _ := Nat.mul_le_mul_left _ hcap + +theorem slots_cover (hs : s.Fits) (T z : ℕ) (hz : T ≤ z * s.M) : + (s.D : ℝ) ^ 4 * T ≤ (s.slots : ℝ) * z := by + have hd : 0 < s.D := by have := s.two hs; omega + have bound : s.D ^ 4 * T ≤ s.slots * z := calc + _ ≤ s.D ^ 4 * (z * s.M) := Nat.mul_le_mul_left _ hz + _ = s.D ^ (s.c + 6) * z := by unfold M; rw [pow_add, pow_add]; ring + _ ≤ _ := Nat.mul_le_mul_right _ (Nat.pow_le_pow_right hd (by omega)) + exact_mod_cast bound + +theorem floor_le (T z : ℕ) (hz : T ≤ z * s.M) : + s.floor * (2 ^ s.p * T : ℕ) ≤ z := by + have hd : 0 < s.D := by unfold D; positivity + have hm : (0 : ℝ) < s.M := by unfold M; positivity + have ht : (T : ℝ) / s.M ≤ z := (div_le_iff₀ hm).mpr (by exact_mod_cast hz) + refine le_trans ?_ ht + unfold floor + push_cast + field_simp + exact le_rfl + +end Plan +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Splitting a concentrated term into core and frozen border -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +variable {F : Type} {x y : Wire} {h D T R g u : ℕ} + (Q : LocalTerm F x y h u) (hD : 2 ≤ D) (hu : 0 < u) + +namespace LocalTerm + +open scoped Classical in +/-- The fringe used in the `LocalTerm` construction. -/ +def fringe := Q.freeze.fringe (fun t => Q.charge t.val) (fun t => Q.cover t.val) + (1 / (D : ℝ) ^ 4) (by positivity) + (by exact (div_le_one (by positivity)).mpr (one_le_pow₀ (by exact_mod_cast (show 1 + ≤ D by omega)))) + +open scoped Classical in +theorem divisible : Q.freeze.Divisible u := fun v w _ _ => Q.width v w + +open scoped Classical in +/-- The value specified by `Q.frame.host hu Q.divisible (Q.fringe hD) rfl`. -/ +abbrev host := Q.frame.host hu Q.divisible (Q.fringe hD) rfl + +open scoped Classical in +theorem parallel (i : slots Q.freeze.x ⊕ slots Q.freeze.y) : + u ≤ (Q.host hD hu).parallelBits i := Q.frame.host_parallel hu Q.divisible _ rfl Q.width i + +end LocalTerm + +namespace Concentrated +variable {Q hD hu} {C d : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + (hq : Concentrated P Q C d 10) +include hq + +open scoped Classical in +/-- Balance the count and the square sum at the scale `T √D`. -/ +theorem frozen_mass (hD : 2 ≤ D) (hT : 0 < T) : + (Q.fringe hD).Z ≤ (C : ℝ) * W / Real.sqrt D := by + have hz : (Q.fringe hD).reserve = 0 := by simp [Fringe.reserve, LocalTerm.fringe, Freeze.fringe] + rw [Fringe.Z, hz, add_zero] + have hsq : (Real.sqrt D) ^ 2 = (D : ℝ) := Real.sq_sqrt (Nat.cast_nonneg _) + have each (i : Q.freeze.Fixed) : + Q.charge i.val * Real.sqrt D * (2 * (T : ℝ)) ≤ (D : ℝ) * T * T + (Q.charge i.val) ^ 2 := by + nlinarith only [sq_nonneg (Q.charge i.val - Real.sqrt D * (T : ℝ)), + congrArg (fun x => x * (T : ℝ) ^ 2) hsq] + have hs := sum_le_sum (fun i (_ : i ∈ univ) => each i) + simp only [← sum_mul, sum_add_distrib, sum_const, card_univ, nsmul_eq_mul] at hs + rw [le_div_iff₀ (by positivity)] + apply le_of_mul_le_mul_right _ (show 0 < (2 : ℝ) * T by positivity) + change (∑ i : Q.freeze.Fixed, Q.charge i.val) * Real.sqrt D * (2 * (T : ℝ)) ≤ _ + have hc := mul_le_mul_of_nonneg_right hq.frozenCount (Nat.cast_nonneg (α := ℝ) T) + linarith [hq.frozenSquare] + +open scoped Classical in +theorem core_mass (hD : 2 ≤ D) (hu : 0 < u) : + ((Q.host hD hu).X : ℝ) ≤ C * W * (1 + (d : ℝ)) ^ 2 := by + let A := Q.host hD hu + have size : Fintype.card Q.freeze.core.E = A.X := by + change Fintype.card A.diagram.E = _ + simp [HostNet.X, Fintype.card_congr A.units.bits] + have hb : A.X ≤ ∑ i, Q.freeze.core.arity i := by + rw [Diagram.sum_arity, size] + omega + refine (Nat.cast_le.mpr hb).trans (le_trans ?_ hq.coreSum) + rw [Nat.cast_sum] + exact sum_le_sum fun i _ => Q.cover i.val + +omit hq in +open scoped Classical in +private theorem max_at {A B : Type} [Fintype A] (f : A → B) (hf : Function.Injective f) + (x : A → ℝ) (n : ℝ) (hn : 0 ≤ n) (hx : ∀ i, x i ≤ n) (b : B) : + push f x b ≤ n := + push_max f (fun _ => True) x n hn hx (fun _ h => (h trivial).elim) hf.injOn b + +open scoped Classical in +theorem bounded (hD : 2 ≤ D) (hu : 0 < u) (hC : C ≤ D) : + (Q.host hD hu).Bounded C (D ^ C) ((T : ℝ) / D) := by + have hD' : (2 : ℝ) ≤ D := by exact_mod_cast hD + have hd : (0 : ℝ) < D := by positivity + refine ⟨hq.coreDegree, hq.fullDegree, fun v i => ?_⟩ + rw [show (Q.host hD hu).load v i = _ from Q.frame.host_load hu Q.divisible _ rfl (v, i)] + have hcore : push (fun t : Q.freeze.Core => Q.frame.place t.val) + (fun t => (Q.diagram.arity t.val : ℝ)) (v, i) ≤ (T : ℝ) / D ^ 2 := by + apply max_at _ (Q.one.comp Subtype.val_injective) _ _ (by positivity) + intro t + apply (Q.cover _).trans + refine (le_div_iff₀ (by positivity)).mpr (le_trans ?_ (hq.coreMax t)) + exact mul_le_mul_of_nonneg_left (pow_le_pow_right₀ (by linarith) (by decide)) + ((Nat.cast_nonneg _).trans (Q.cover _)) + have hf : push (fun t : Q.freeze.Fixed => Q.frame.place t.val) + (Q.fringe hD).charge (v, i) ≤ (D : ℝ) ^ 2 * T := by + apply max_at _ (Q.one.comp Subtype.val_injective) _ _ (by positivity) + intro t + refine (hq.frozenMax t).trans ?_ + rw [pow_two] + gcongr + calc + _ ≤ (T : ℝ) / D ^ 2 + 1 / (D : ℝ) ^ 4 * (D ^ 2 * T) := + add_le_add hcore (mul_le_mul_of_nonneg_left hf (by positivity : 0 ≤ 1 / (D : ℝ) ^ 4)) + _ = 2 * ((T : ℝ) / D) / D := by field_simp; ring + _ ≤ (T : ℝ) / D := by + rw [div_le_iff₀ hd, mul_comm 2] + exact mul_le_mul_of_nonneg_left hD' (by positivity) + +end Concentrated +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Turning a reduced core back into a charged board -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +open scoped Classical in +theorem Plan.restored {F V : Type} [Fintype V] {x y : Wire} {h z T : ℕ} {L : ℝ} + {R : Fringe x y V} {G : HostNet F R h z} {s : Plan} (hs : s.Fits) + (A : G.Restore s.full s.slots s.slots) (hL : 0 ≤ L) + (bound : G.Bounded 3 s.full T) + (hw : (G.X : ℝ) ≤ (s.ρ * s.A * (1 + (s.d : ℝ)) ^ 2 + s.loss * ((s.A + 1) / Real.sqrt s.D)) * L) + (hf : R.Z ≤ s.A / Real.sqrt s.D * L) + (hsq : (∑ i, R.charge i ^ 2) ≤ (s.A : ℝ) * L * T) + (hmax : ∀ i, R.charge i ≤ (s.A : ℝ) * s.D * T) : + (∑ p, A.charge p) ≤ L / (2 : ℝ) ^ s.v ∧ + (∑ p, A.charge p ^ 2) ≤ L / (2 : ℝ) ^ s.v * (2 ^ s.p * T : ℕ) ∧ + ∀ p, A.charge p ≤ (s.D : ℝ) * (2 ^ s.p * T : ℕ) / 2 := by + have mass : (∑ p, A.charge p) ≤ L / (2 : ℝ) ^ s.v := calc + _ ≤ _ := A.mass + _ ≤ (2 * (s.ρ * s.A * (1 + (s.d : ℝ)) ^ 2 + s.loss * ((s.A + 1) / Real.sqrt s.D)) + + (1 + 2 * ((Detour.steps s.w : ℝ) + Nat.clog 2 s.slots)) * (s.A / Real.sqrt s.D)) * L := by + conv_rhs => rw [add_mul, mul_assoc 2, mul_assoc (1 + 2 * ((Detour.steps s.w : ℝ) + + Nat.clog 2 s.slots))] + exact add_le_add (mul_le_mul_of_nonneg_left hw (by norm_num)) + (mul_le_mul_of_nonneg_left hf (by positivity)) + _ ≤ _ := by simpa only [one_div_mul_eq_div] using mul_le_mul_of_nonneg_right hs.mass hL + refine ⟨mass, ?_, ?_⟩ + · have hm : (∑ p, A.charge p) ≤ L := mass.trans (div_le_self hL (one_le_pow₀ (by norm_num))) + calc + _ ≤ _ := A.squares T (Nat.cast_nonneg _) bound + _ ≤ 3 * (1 + 4 * (Nat.clog 2 s.slots : ℝ)) * (s.A * L * T) + 9 * T * L := by gcongr + _ = (3 * (1 + 4 * (Nat.clog 2 s.slots : ℝ)) * s.A + 9) * (L * T) := by ring + _ ≤ ((2 : ℝ) ^ s.p / (2 : ℝ) ^ s.v) * (L * T) + := mul_le_mul_of_nonneg_right hs.squares (by positivity) + _ = _ := by push_cast; ring + · intro v + calc + _ ≤ _ := A.maximum T _ (Nat.cast_nonneg _) (by positivity) bound hmax v + _ ≤ _ := by + have := mul_le_mul_of_nonneg_right hs.max (Nat.cast_nonneg (α := ℝ) T) + push_cast + linarith + +variable {F : Type} [Field F] {x y : Wire} {h a u z D : ℕ} (Q : LocalTerm F x y h u) + +open scoped Classical in +private abbrev recovered {hD : 2 ≤ D} {G : HostNet F (Q.fringe hD) a z} + {N r : ℕ} (A : G.Restore N r r) : Board F x y a where + V := A.Space + diagram := A.graph Q.freeze.border rfl + place := Prod.swap + one := Prod.swap_injective + adj := A.adj + sym := Tether.adj_symm A.sw G.C G.cs + edge e := ⟨(A.supported _ _ e).1.symm, (A.supported _ _ e).2⟩ + charge := A.charge + cover := A.charge_covers Q.freeze.border rfl (fun t => Q.cover t.val) + +variable {Q} {s : Plan} (hs : s.Fits) {L : ℝ} {T R g : ℕ} + {P : Input F x y h s.D T R g (10000 * L)} + (hq : Concentrated P Q s.C s.d 10) +include hq + +omit [Field F] in +open scoped Classical in +theorem Concentrated.raw (hL : 0 ≤ L) (hT : 0 < T) (hu : 0 < u) : + (Q.fringe (s.two hs)).Z ≤ (s.A / Real.sqrt s.D) * L ∧ + ((Q.host (s.two hs) hu).X : ℝ) ≤ s.A * (1 + (s.d : ℝ)) ^ 2 * L := by + have hc : (s.C : ℝ) * (10000 * L) ≤ s.A * L := by + rw [← mul_assoc] + exact mul_le_mul_of_nonneg_right s.cost_le hL + constructor + · refine (hq.frozen_mass _ hT).trans ?_ + rw [div_mul_eq_mul_div] + exact div_le_div_of_nonneg_right hc (Real.sqrt_nonneg _) + · refine (hq.core_mass _ hu).trans ?_ + rw [mul_right_comm (s.A : ℝ)] + exact mul_le_mul_of_nonneg_right hc (by positivity) + +open scoped Classical in +theorem Concentrated.recover (hL : 0 ≤ L) (hT : 0 < T) (hu : 0 < u) (hz : 0 < z) + (hzu : z ≤ u) (hunit : T ≤ z * s.M) (hc : 0 ≤ s.loss) + (G : HostNet F (Q.fringe (s.two hs)) a z) + (same : (Q.host (s.two hs) hu).Preserves G) + (sites : G.seats ≤ s.K * (Q.host (s.two hs) hu).seats) + (bound : G.Bounded 3 s.full T) + (width : (G.X : ℝ) ≤ s.ρ * (Q.host (s.two hs) hu).X + + s.loss * ((Q.fringe (s.two hs)).Z + L / s.D)) : + ∃ B : Board F x y a, + B.diagram.eval = (Q.freeze.border.attach G.diagram).eval ∧ + B.Ready 4 s.D (2 ^ s.p * T) (L / (2 : ℝ) ^ s.v) s.floor ∧ + B.seats ≤ s.seats * (Fintype.card P.V * 2 ^ h) := by + have hd := s.two hs + have hd' : (1 : ℝ) ≤ s.D := by exact_mod_cast (show 1 ≤ s.D by omega) + have hcap : (s.D : ℝ) ^ 4 * T ≤ (s.slots : ℝ) * z := s.slots_cover hs T z hunit + have lower (i : Q.freeze.Fixed) : (z : ℝ) ≤ (Q.fringe hd).charge i := + (Nat.cast_le.mpr hzu).trans (Q.floor _) + have upper (i : Q.freeze.Fixed) : (Q.fringe hd).charge i ≤ (s.slots : ℝ) * z := calc + _ ≤ (s.C : ℝ) * s.D * T := hq.frozenMax i + _ ≤ (s.D : ℝ) ^ 2 * T := by + rw [pow_two] + gcongr + exact s.small.trans hs.degree + _ ≤ (s.D : ℝ) ^ 4 * T := mul_le_mul_of_nonneg_right + (pow_le_pow_right₀ hd' (by decide)) (Nat.cast_nonneg _) + _ ≤ _ := hcap + have contact i : (z : ℝ) ≤ G.parallelBits i := + Nat.cast_le.mpr (hzu.trans ((Q.parallel hd hu i).trans (same.parallelBits _ i))) + have allocated : (T : ℝ) ≤ (Q.fringe hd).scale * (s.slots * (z : ℝ)) := by + change _ ≤ 1 / (s.D : ℝ) ^ 4 * _ + rw [one_div_mul_eq_div, le_div_iff₀ (by positivity), mul_comm (T : ℝ)] + exact hcap + obtain ⟨A⟩ := G.restore s.full s.slots s.slots T z (Nat.cast_pos.mpr hz) bound allocated + (fun i => ⟨lower i, upper i⟩) contact + obtain ⟨hf, hx⟩ := hq.raw hs hL hT hu + have slack : L / (s.D : ℝ) ≤ L / Real.sqrt s.D := + div_le_div_of_nonneg_left hL (by positivity) (Real.sqrt_le_self_iff.mpr (.inr hd')) + have hw : (G.X : ℝ) ≤ (s.ρ * s.A * (1 + (s.d : ℝ)) ^ 2 + s.loss * ((s.A + + 1) / Real.sqrt s.D)) * L := calc + _ ≤ _ := width + _ ≤ s.ρ * (s.A * (1 + (s.d : ℝ)) ^ 2 * L) + s.loss * (s.A / Real.sqrt s.D * L + + L / Real.sqrt s.D) := + add_le_add (mul_le_mul_of_nonneg_left hx (by unfold Plan.ρ; positivity)) + (mul_le_mul_of_nonneg_left (add_le_add hf slack) hc) + _ = _ := by ring + have hsq : (∑ i, (Q.fringe hd).charge i ^ 2) ≤ (s.A : ℝ) * L * T := + hq.frozenSquare.trans (mul_le_mul_of_nonneg_right (by + rw [← mul_assoc]; exact mul_le_mul_of_nonneg_right s.cost_le hL) (Nat.cast_nonneg T)) + have hmax (i : Q.freeze.Fixed) : (Q.fringe hd).charge i ≤ (s.A : ℝ) * s.D * T := by + refine (hq.frozenMax i).trans ?_ + gcongr + unfold Plan.A + omega + obtain ⟨mass, square, mx⟩ := Plan.restored hs A hL bound hw hf hsq hmax + refine ⟨recovered Q A, A.eval Q.freeze.border rfl, ⟨Tether.adj_degree _ _ bound.1, mass, square, + ?_⟩, ?_⟩ + · intro v + exact ⟨mx v, (A.floor z le_rfl contact lower v).imp_right ((s.floor_le T z hunit).trans ·)⟩ + · let N := (1 + s.slots * 2 ^ (Nat.clog 2 s.slots + 1)) * (1 + 2 ^ (Nat.clog 2 s.w + 1)) + have hb : G.seats ≤ s.K * s.D ^ s.C * (Fintype.card P.V * 2 ^ h) := calc + _ ≤ s.K * (Fintype.card Q.V * 2 ^ h) := sites + _ ≤ s.K * ((s.D ^ s.C * Fintype.card P.V) * 2 ^ h) := by gcongr; exact hq.cells + _ = _ := by ring + calc + _ = N * G.seats := by + change Fintype.card (Tether.Host G.V _ _ _) * 2 ^ a = _ + rw [Tether.size] + unfold N Plan.w HostNet.seats + ring + _ ≤ N * (s.K * s.D ^ s.C * (Fintype.card P.V * 2 ^ h)) := Nat.mul_le_mul_left N hb + _ = _ := by unfold N Plan.seats; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Reducing one term of the local expansion -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +variable {F : Type} [Field F] {x y : Wire} {h a r u z : ℕ} + {Q : LocalTerm F x y h u} {s : Plan} (hs : s.Fits) + (p : Reduction F s.c 3 s.b s.n s.e s.K s.ρ s.loss) + {L : ℝ} {T R g : ℕ} {P : Input F x y h s.D T R g (10000 * L)} + (hq : Concentrated P Q s.C s.d 10) +include hs p hq + +open scoped Classical in +/-- Execute all beats, restore the frozen members and reattach their +tables in each summand. -/ +theorem Concentrated.process (hL : 0 ≤ L) (hT : 0 < T) (hz : 0 < z) + (hu : u = s.b * z) (hunit : u * s.D ^ s.c ≤ T) (hunit' : T ≤ z * s.M) + (ha : a + s.n * r ≤ h) (hr : s.K ≤ 2 ^ r) + (slack : (s.K * s.D ^ s.C : ℕ) * (T : ℝ) * (Fintype.card P.V * 2 ^ h : ℕ) ≤ L * (2 : ℝ) ^ r) : + Expansion Q.diagram.eval (s.K * (s.cover * ⌈L / (T : ℝ)⌉₊)) + (fun B : Board F x y a => B.Ready 4 s.D (2 ^ s.p * T) (L / (2 : ℝ) ^ s.v) s.floor ∧ + B.seats ≤ s.seats * (Fintype.card P.V * 2 ^ h)) := by + have hd := s.two hs + have hd' : (1 : ℝ) ≤ s.D := by exact_mod_cast (show 1 ≤ s.D by omega) + have hd₀ : (0 : ℝ) < s.D := zero_lt_one.trans_le hd' + have hzu : z ≤ u := by rw [hu]; exact Nat.le_mul_of_pos_left _ p.unit + have hu₀ := hz.trans_le hzu + have hc : 0 < s.c := by unfold Plan.c; omega + have hdeg := Nat.le_self_pow hc.ne' s.D + let G := Q.host hd hu₀ + let B := (T : ℝ) / s.D + have hB : (u : ℝ) ≤ B := (le_div_iff₀ hd₀).mpr (by + exact_mod_cast (Nat.mul_le_mul_left u hdeg).trans hunit) + have hG : G.Bounded s.c (s.D ^ s.c) B := + (hq.bounded hd hu₀ (s.small.trans hs.degree)).mono s.small + (Nat.pow_le_pow_right (by omega) s.small) le_rfl + have hseat : G.seats ≤ s.D ^ s.C * (Fintype.card P.V * 2 ^ h) := by + rw [← mul_assoc] + exact Nat.mul_le_mul_right _ hq.cells + have hslack : (s.K : ℝ) * B * G.seats ≤ (L / s.D) * (2 : ℝ) ^ r := calc + _ ≤ (s.K : ℝ) * B * (s.D ^ s.C * (Fintype.card P.V * 2 ^ h) : ℕ) := + mul_le_mul_of_nonneg_left (Nat.cast_le.mpr hseat) (by unfold B; positivity) + _ = ((s.K * s.D ^ s.C : ℕ) * (T : ℝ) * (Fintype.card P.V * 2 ^ h : ℕ)) / s.D := by + unfold B; push_cast; ring + _ ≤ _ := by rw [div_mul_eq_mul_div]; exact div_le_div_of_nonneg_right slack hd₀.le + have hcover : (G.X : ℝ) + ((Q.fringe hd).Z + L / s.D) ≤ (s.cover * ⌈L / (T : ℝ)⌉₊ : ℕ) * (z : ℝ) + := by + obtain ⟨hf, hx⟩ := hq.raw hs hL hT hu₀ + have hf' := hf.trans (mul_le_mul_of_nonneg_right + (div_le_self (Nat.cast_nonneg s.A) (Real.one_le_sqrt.mpr hd')) hL) + have hround : L ≤ (⌈L / (T : ℝ)⌉₊:ℝ) * (z * s.M) := calc + _ ≤ (⌈L / (T : ℝ)⌉₊:ℝ) * T := (div_le_iff₀ (Nat.cast_pos.mpr hT)).mp (Nat.le_ceil _) + _ ≤ _ := mul_le_mul_of_nonneg_left (by exact_mod_cast hunit') (by positivity) + have hh := mul_le_mul_of_nonneg_left hround (by positivity : (0 : ℝ) ≤ s.A * (1 + + (s.d : ℝ)) ^ 2 + s.A + 1) + have := div_le_self hL hd' + unfold Plan.cover G + push_cast + linarith + obtain ⟨I, _, Q', num, eval, ok⟩ := p.run G z r a (s.D ^ s.c) _ B (L / s.D) hz hu hB + (hs.degree.trans hdeg) hG (by positivity) ha hr hslack hcover + have hload : s.K * B ≤ (T : ℝ) := by + unfold B + rw [← mul_div_assoc, div_le_iff₀ hd₀, mul_comm] + exact mul_le_mul_of_nonneg_left (Nat.cast_le.mpr hs.overhead) (Nat.cast_nonneg _) + have term (i : I) : ∃ Z : Board F x y a, + Z.diagram.eval = (Q.freeze.border.attach (Q' i).diagram).eval ∧ + Z.Ready 4 s.D (2 ^ s.p * T) (L / (2 : ℝ) ^ s.v) s.floor ∧ + Z.seats ≤ s.seats * (Fintype.card P.V * 2 ^ h) := by + obtain ⟨same, size, hbd, wd, _⟩ := ok i + refine hq.recover hs hL hT hu₀ hz hzu hunit' p.loss _ same size ?_ wd + simpa only [Plan.full, pow_mul] using hbd.mono le_rfl le_rfl hload + choose Z he hZ using term + refine ⟨I, inferInstance, Z, fun _ => 1, num, fun x y => ?_, hZ⟩ + simp only [one_mul, he] + exact (Q.freeze.border.attach_sum Q.freeze.core _ eval x y).trans (Q.freeze.reconstruct x y) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Stack/Mates.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Stack/Mates.lean new file mode 100644 index 0000000000..4af23cd1a5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Stack/Mates.lean @@ -0,0 +1,1017 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Dictionary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Bins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Canonical +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.History.FaceNames + +/-! # Local replacement of a stack of identical tables -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack + +/-- All copies of each original exterior port meet one named vertex. +There is room for one more adjacency when joining devices. -/ +structure Device {F : Type} [Field F] (T : Table F) (t : ℕ) where + /-- The `Device` component of type `Diagram F (copies T.1 (2 ^ t)) (copies T.2.1 (2 ^ t))`. -/ + diagram : Diagram F (copies T.1 (2 ^ t)) (copies T.2.1 (2 ^ t)) + eval : diagram.eval = (BatchDescent.Stack.tensor T (2 ^ t)).2.2 + /-- The name assigned to each index of type `Transcript.Ports T ↪ diagram.V`. -/ + name : Transcript.Ports T ↪ diagram.V + external : ∀ p : Transcript.Ports (BatchDescent.Stack.tensor T (2 ^ t)), + Packing.portEnd diagram p = name ((BatchDescent.Stack.pin T (2 ^ t)) p).2 + /-- The neighbors of each vertex of type `diagram.V → Finset diagram.V`. -/ + adj : diagram.V → Finset diagram.V + sym : ∀ v w, w ∈ adj v → v ∈ adj w + degree : ∀ v, (adj v).card ≤ 4 + linked : ∀ e, diagram.target e ∈ adj (diagram.source e) + loopless : ∀ e, diagram.source e ≠ diagram.target e + arity : ∀ v, diagram.arity v ≤ 4 * 2 ^ t + size : Fintype.card diagram.V ≤ 4 * (1 + wd T.1 + wd T.2.1) * (t + 1) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end + +/- +# Joining the station devices of a replicated network + +The local graph contributes at most four neighbors. Distinct port +names leave at most one further neighbor on the original network. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +open Packing Finset + +variable {F : Type} [Field F] {a b : Wire} {h t n : ℕ} + (G : Diagram F a b) (f : ∀ v, Device (G.table v) t) (c : Cell h × Fin (2 ^ t) ≃ Fin n) + +open scoped Classical in +/-- The indexed operation `(BatchDescent.Stack.gathered G c).plug (fun v => (f v.2).diagram)`. -/ +abbrev built := (BatchDescent.Stack.gathered G c).plug (fun v => (f v.2).diagram) + +open scoped Classical in +/-- Indexes the location by the coordinates of `Σ v, (f v).diagram.V`. -/ +abbrev Location := Σ v, (f v).diagram.V + +namespace Device + +open scoped Classical in +/-- Embeds `G.End` into `Location G f`. -/ +def endpoint : G.End ↪ Location G f := + G.portEquiv.symm.toEmbedding.trans ((Function.Embedding.refl G.V).sigmaMap fun v => (f v).name) + +open scoped Classical in +theorem exact_value : (built G f c).eval = power G.eval n := + ((BatchDescent.Stack.gathered G c).eval_plug _ (fun v => (f v.2).eval)).trans + ((BatchDescent.Stack.eval_gathered G c).trans (G.eval_replicate c)) + +open scoped Classical in +/-- Reindexes `(built G f c).V` and `Location G f × Cell h where toFun z` by an equivalence. -/ +def place : (built G f c).V ≃ Location G f × Cell h where + toFun z := (⟨z.1.2, z.2⟩, z.1.1) + invFun z := ⟨(z.2, z.1.1), z.1.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +open scoped Classical in +/-- Returns `endpoint G f (other G h.choose)` when `h : ∃ e, endpoint G f e = z` holds, and `z` +otherwise. -/ +def partner (z : Location G f) := + if h : ∃ e, endpoint G f e = z then endpoint G f (other G h.choose) else z + +open scoped Classical in +theorem partner_end (e : G.End) : + partner G f (endpoint G f e) = endpoint G f (other G e) := by + have he : ∃ d, endpoint G f d = endpoint G f e := ⟨e, rfl⟩ + simp only [partner, dite_eq_left he, (endpoint G f).injective he.choose_spec] + +open scoped Classical in +theorem partner_involution : Function.Involutive (partner G f) := by + intro z + by_cases he : ∃ e, endpoint G f e = z + · obtain ⟨e, rfl⟩ := he + rw [partner_end, partner_end] + rcases e with (i|e)|(j|e) <;> rfl + · have eq : partner G f z = z := dite_eq_right he + rw [eq, eq] + +open scoped Classical in +/-- Computes the neighbors by the application `insert (partner G f z) (((f z.1).adj z.2).image +(Sigma.mk z.1))`. -/ +def neighbors (z : Location G f) : Finset (Location G f) := + insert (partner G f z) (((f z.1).adj z.2).image (Sigma.mk z.1)) + +open scoped Classical in +theorem sym_neighbors (v w : Location G f) (h : w ∈ neighbors G f v) : + v ∈ neighbors G f w := by + rcases mem_insert.mp h with rfl | h + · exact mem_insert.mpr (.inl (partner_involution G f v).symm) + · obtain ⟨x, hx, rfl⟩ := mem_image.mp h + exact mem_insert_of_mem (mem_image_of_mem (Sigma.mk v.1) ((f v.1).sym _ _ hx)) + +open scoped Classical in +theorem neighbors_bound (v : Location G f) : (neighbors G f v).card ≤ 5 := + (card_insert_le _ _).trans (Nat.add_le_add_right (card_image_le.trans ((f v.1).degree _)) 1) + +open scoped Classical in +theorem outer_source (i : Cell h) (j : Fin (2 ^ t)) (e : G.E) : + place G f c ((built G f c).source (.inl ((i, j), e))) = (endpoint G f (.inl (.inr e)), i) := by + let p := G.src.symm (.inr e) + let k := (Diagonal.port (G.table p.1).1 (2 ^ t)).symm (j, p.2) + change ((⟨p.1, portEnd (f p.1).diagram (.inl k)⟩ : Location G f), i) = + (⟨p.1, (f p.1).name (.inl p.2)⟩, i) + rw [(f p.1).external] + simp [BatchDescent.Stack.pin, k] + +open scoped Classical in +theorem outer_target (i : Cell h) (j : Fin (2 ^ t)) (e : G.E) : + place G f c ((built G f c).target (.inl ((i, j), e))) = (endpoint G f (.inr (.inr e)), i) := by + let p := G.dst.symm (.inr e) + let k := (Diagonal.port (G.table p.1).2.1 (2 ^ t)).symm (j, p.2) + change ((⟨p.1, portEnd (f p.1).diagram (.inr k)⟩ : Location G f), i) = + (⟨p.1, (f p.1).name (.inr p.2)⟩, i) + rw [(f p.1).external] + simp [BatchDescent.Stack.pin, k] + +open scoped Classical in +theorem wires (e : (built G f c).E) : + let p := place G f c ((built G f c).source e) + let q := place G f c ((built G f c).target e) + q.2 = p.2 ∧ q.1 ∈ neighbors G f p.1 := by + rcases e with ⟨⟨i, j⟩, e⟩ | ⟨⟨i, v⟩, e⟩ + · rw [outer_source, outer_target] + exact ⟨rfl, mem_insert.mpr (.inl (partner_end G f (.inl (.inr e))).symm)⟩ + · exact ⟨rfl, mem_insert_of_mem (mem_image_of_mem (Sigma.mk v) ((f v).linked e))⟩ + +open scoped Classical in +theorem built_loopless (e : (built G f c).E) : + (built G f c).source e ≠ (built G f c).target e := by + intro he + rcases e with ⟨⟨i, j⟩, e⟩ | ⟨⟨i, v⟩, e⟩ + · have eq := congrArg (place G f c) he + rw [outer_source, outer_target] at eq + cases (endpoint G f).injective (congrArg Prod.fst eq) + · exact (f v).loopless e (eq_of_heq (Sigma.mk.inj_iff.mp he).2) + +open scoped Classical in +theorem location_bound : Fintype.card (Location G f) ≤ 4 * G.cost * (t + 1) := by + rw [Fintype.card_sigma] + calc + _ ≤ ∑ v, 4 * (1 + G.arity v) * (t + 1) := + sum_le_sum fun v _ => by simpa [Diagram.arity, add_assoc] using (f v).size + _ = _ := by rw [Diagram.cost, mul_sum, sum_mul] + +open scoped Classical in +/-- Builds `Board F (copies a n) (copies b n) h where V` with the specified `diagram`, `place`, +`one`, `adj`. -/ +abbrev board : Board F (copies a n) (copies b n) h where + V := Location G f + diagram := built G f c + place := place G f c + one := (place G f c).injective + adj := neighbors G f + sym := sym_neighbors G f + edge := wires G f c + charge _ := 4 * (2 : ℝ) ^ t + cover z := by + change ((f z.1.2).diagram.arity z.2 : ℝ) ≤ _ + exact_mod_cast (f z.1.2).arity z.2 + +open scoped Classical in +theorem seats_bound : (board G f c).seats ≤ 4 * G.cost * (t + 1) * 2 ^ h := + Nat.mul_le_mul_right _ (location_bound G f) + +open scoped Classical in +theorem ready {D : ℕ} {θ : ℝ} (hD : 8 ≤ D) (hθ : θ ≤ 4) : + (board G f c).Ready 5 D (2 ^ t) (16 * (2 : ℝ) ^ t * (board G f c).seats) θ := by + have size : Fintype.card (built G f c).V = (board G f c).seats := by + rw [Fintype.card_congr (place G f c), Fintype.card_prod, card_cell] + rfl + refine ⟨neighbors_bound G f, ?_, ?_, ?_⟩ + · change (∑ _ : (built G f c).V, 4 * (2 : ℝ) ^ t) ≤ _ + rw [sum_const, card_univ, size, nsmul_eq_mul, mul_comm] + gcongr; norm_num + · change (∑ _ : (built G f c).V, (4 * (2 : ℝ) ^ t) ^ 2) ≤ _ + rw [sum_const, card_univ, size, nsmul_eq_mul, Nat.cast_pow, Nat.cast_ofNat] + exact le_of_eq (by ring) + · intro v + change 4 * (2 : ℝ) ^ t ≤ _ ∧ (_ ∨ θ * _ ≤ 4 * (2 : ℝ) ^ t) + simp only [Nat.cast_pow, Nat.cast_ofNat] + refine ⟨?_, .inr (mul_le_mul_of_nonneg_right hθ (by positivity))⟩ + have hD' : (8 : ℝ) ≤ D := by exact_mod_cast hD + rw [le_div_iff₀ (by norm_num)] + nlinarith [pow_pos (by norm_num : (0 : ℝ) < 2) t] + +end Device +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end + +/- +# Transposing the copies of a single table + +Store every copy at layer zero. Route its bits to the final layer, +where each port of the table has one vertex shared by all copies. +The equality constraints have one solution for every exterior input. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +open Finset Packing Transcript BatchDescent.Stack + +variable {F : Type} [Field F] {T : Table F} {t : ℕ} + +namespace Butterfly + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev dim (T : Table F) (_ : Unit) := Nat.clog 2 (wd T.1 + wd T.2.1) +open scoped Classical in +/-- The value specified by `Node (t := t) (dim T)`. -/ +abbrev Site (T : Table F) (t : ℕ) := Node (t := t) (dim T) +open scoped Classical in +/-- The quantity computed by `Ports (tensor T (2 ^ t))`. -/ +abbrev Pin (T : Table F) (t : ℕ) := Ports (tensor T (2 ^ t)) +open scoped Classical in +/-- Indexes the link by the coordinates of `Fin t × Pin T t`. -/ +abbrev Link (T : Table F) (t : ℕ) := Fin t × Pin T t + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def idx (t : ℕ) : Fin (2 ^ t) ≃ Cell t := Fintype.equivOfCardEq (by simp [Cell]) + +open scoped Classical in +/-- Embeds `Ports T` into `Σ j, Cell (dim T j)`. -/ +def addr (T : Table F) : Ports T ↪ Σ j, Cell (dim T j) := + Classical.choice (Function.Embedding.nonempty_of_card_le (by + simp only [Ports, Fintype.card_sum, card_slots, Fintype.card_sigma, card_cell, dim, sum_const, + card_univ, Fintype.card_unit, one_smul] + exact Nat.le_pow_clog (by decide) _)) + +open scoped Classical in +/-- Embeds `Ports T` into `Site T t`. -/ +def terminal (T : Table F) (t : ℕ) : Ports T ↪ Site T t := + ⟨fun p => (addr T p, Fin.last t), fun _ _ h => (addr T).injective (congrArg Prod.fst h)⟩ + +variable (hd : ∀ j, dim T j ≤ t) + +open scoped Classical in +/-- Computes the loc by the application `Node.atLayer hd k (idx t (pin T _ p).1) (addr T (pin T +_ p).2)`. -/ +def loc (k : Fin (t + 1)) (p : Pin T t) : Site T t := + Node.atLayer hd k (idx t (pin T _ p).1) (addr T (pin T _ p).2) + +open scoped Classical in +/-- Computes the base by the application `Node.start hd () (idx t i)`. -/ +def base (i : Fin (2 ^ t)) : Site T t := Node.start hd () (idx t i) + +open scoped Classical in +private theorem first (i : Fin (2 ^ t)) (p : Ports T) : + loc hd 0 ((pin T _).symm (i, p)) = base hd i := by + simp only [loc, Equiv.apply_symm_apply, Node.layer_zero, base] + +open scoped Classical in +theorem last (p : Pin T t) : loc hd (Fin.last t) p = terminal T t ((pin T _ p).2) := by + rw [loc, Node.layer_last]; rfl + +open scoped Classical in +/-- Computes the code by the application `Node.residue k.val (addr T (pin T _ p).2).1 (idx t +(pin T _ p).1) (addr T (pin T _ p).2).2`. -/ +def code (k : Fin (t + 1)) (p : Pin T t) : Cell t := + Node.residue k.val (addr T (pin T _ p).2).1 (idx t (pin T _ p).1) (addr T (pin T _ p).2).2 + +open scoped Classical in +theorem unique {i j : Fin (t + 1)} {p q : Pin T t} + (hl : loc hd i p = loc hd j q) (hc : code i p = code j q) : i = j ∧ p = q := by + obtain ⟨hk, hx, hp⟩ := Node.layer_inj hd hl hc + exact ⟨hk, (pin T _).injective (Prod.ext ((idx t).injective hx) ((addr T).injective hp))⟩ + +open scoped Classical in +/-- At each layer there are at most as many bits at one site as copies. +Residual addresses distinguish bits with the same layer address. -/ +private theorem capacity {X : Type} [Fintype X] + (f : X → Pin T t) (hf : Function.Injective f) + (k : Fin t → Fin (t + 1)) (hk : Function.Injective k) (v : Site T t) : + Fintype.card {q : X ⊕ Link T t // Sum.elim (fun x => loc hd (Fin.last t) (f x)) + (fun e => loc hd (k e.1) e.2) q = v} ≤ 2 * 2 ^ t := by + let key : X ⊕ Link T t → Cell t ⊕ Cell t := Sum.elim + (fun x => .inl (code (Fin.last t) (f x))) (fun e => .inr (code (k e.1) e.2)) + refine le_trans ?_ (show Fintype.card (Cell t ⊕ Cell t) ≤ 2 * 2 ^ t by simp [two_mul, Cell]) + refine Fintype.card_le_of_injective (fun q => key q.val) ?_ + rintro ⟨x | e, hx⟩ ⟨y | j, hy⟩ h + · exact Subtype.ext (congrArg Sum.inl (hf (unique hd (hx.trans hy.symm) (Sum.inl.inj h)).2)) + · cases h + · cases h + · obtain ⟨ha, hp⟩ := unique hd (hx.trans hy.symm) (Sum.inr.inj h) + exact Subtype.ext (congrArg Sum.inr (Prod.ext (hk ha) hp)) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def src : slots (copies T.1 (2 ^ t)) ⊕ Link T t → Site T t := + Sum.elim (fun i => loc hd (Fin.last t) (.inl i)) (fun e => loc hd e.1.castSucc e.2) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def dst : slots (copies T.2.1 (2 ^ t)) ⊕ Link T t → Site T t := + Sum.elim (fun i => loc hd (Fin.last t) (.inr i)) (fun e => loc hd e.1.succ e.2) + +open scoped Classical in +/-- Indexes the x by the coordinates of `slots (copies T.1 (2 ^ t)) ⊕ Link T t → Bool`. -/ +abbrev X (T : Table F) (t : ℕ) := slots (copies T.1 (2 ^ t)) ⊕ Link T t → Bool +open scoped Classical in +/-- Indexes the y by the coordinates of `slots (copies T.2.1 (2 ^ t)) ⊕ Link T t → Bool`. -/ +abbrev Y (T : Table F) (t : ℕ) := slots (copies T.2.1 (2 ^ t)) ⊕ Link T t → Bool + +open scoped Classical in +/-- The indexed operation `Fin.lastCases (Sum.elim (x ∘ Sum.inl) (y ∘ Sum.inl) p) (fun k => x +(.inr (k, p))) k`. -/ +def read (x : X T t) (y : Y T t) (k : Fin (t + 1)) (p : Pin T t) : Bool := + Fin.lastCases (Sum.elim (x ∘ Sum.inl) (y ∘ Sum.inl) p) (fun k => x (.inr (k, p))) k + +open scoped Classical in +/-- The weight of type `F` for the given inputs. -/ +def weight (v : Site T t) (x : X T t) (y : Y T t) : F := + if ∀ e : Link T t, dst hd (.inr e) = v → y (.inr e) = read x y e.1.succ e.2 then + ∏ i ∈ univ.filter (fun i => base hd i = v), + sample T (fun p => read x y 0 ((pin T _).symm (i, p))) + else 0 + +open scoped Classical in +theorem local_weight : Diagram.Local (src hd) (dst hd) (weight hd) := by + intro v x y x' y' hx hy + have hr (k : Fin (t + 1)) (p : Pin T t) (h : loc hd k p = v) : + read x y k p = read x' y' k p := by + induction k using Fin.lastCases with + | last => + simp only [read, Fin.lastCases_last] + cases p with + | inl i => exact hx (.inl i) h + | inr i => exact hy (.inl i) h + | cast k => + simp only [read, Fin.lastCases_castSucc] + exact hx (.inr (k, p)) h + have hc : (∀ e : Link T t, dst hd (.inr e) = v → y (.inr e) = read x y e.1.succ e.2) ↔ + (∀ e : Link T t, dst hd (.inr e) = v → y' (.inr e) = read x' y' e.1.succ e.2) := by + refine forall_congr' fun e => imp_congr_right fun he => ?_ + rw [hy _ he, hr _ _ he] + simp only [weight, hc] + split + · refine prod_congr rfl fun i hi => congrArg (sample T) (funext fun p => ?_) + exact hr _ _ ((first hd i p).trans (mem_filter.mp hi).2) + · rfl + +open scoped Classical in +/-- Computes the network by the application `Diagram.ofLocal (src hd) (dst hd) (weight hd)`. -/ +abbrev network := Diagram.ofLocal (src hd) (dst hd) (weight hd) + +open scoped Classical in +private theorem evaluate : (network hd).eval = (tensor T (2 ^ t)).2.2 := by + funext x y + let f : Pin T t → Bool := Sum.elim (bits (copies T.1 (2 ^ t)) x) (bits (copies T.2.1 (2 ^ t)) y) + let z₀ : Link T t → Bool := fun e => f e.2 + let val (z : Link T t → Bool) := read (Sum.elim (bits (copies T.1 (2 ^ t)) x) z) (Sum.elim (bits + (copies T.2.1 (2 ^ t)) y) z) + have end_val (z) (p) : val z (Fin.last t) p = f p := by + simp only [val, read, Fin.lastCases_last] + cases p <;> rfl + have before (z) (i : Fin t) (p) : val z i.castSucc p = z (i, p) := by + simp [val, read] + have good (k : Fin (t + 1)) (p) : val z₀ k p = f p := by + induction k using Fin.lastCases with + | last => exact end_val _ _ + | cast k => exact before z₀ k p + have forced (z : Link T t → Bool) (h : ∀ e, z e = val z e.1.succ e.2) : z = z₀ := by + funext ⟨k, p⟩ + have eq (i : Fin (t + 1)) : val z i p = f p := by + induction i using Fin.reverseInduction with + | last => exact end_val _ _ + | cast i ih => exact (before z i p).trans ((h (i, p)).trans ih) + exact (h (k, p)).trans (eq k.succ) + have hw (v) (z : Link T t → Bool) : (network hd).vertex x y z v = + if ∀ e, dst hd (.inr e) = v → z e = val z e.1.succ e.2 then + ∏ i ∈ univ.filter (fun i => base hd i = v), + sample T (fun p => val z 0 ((pin T _).symm (i, p))) else 0 := + Diagram.vertex_ofLocal _ _ _ (local_weight hd) x y z v + unfold Diagram.eval + rw [sum_eq_single z₀] + · have ht (v) : (network hd).vertex x y z₀ v = + ∏ i ∈ univ.filter (fun i => base hd i = v), + sample T (fun p => f ((pin T _).symm (i, p))) := by + rw [hw, ite_eq_left (fun e _ => (good _ _).symm)] + simp only [good] + simp_rw [ht] + rw [prod_fiberwise, ←sample_tensor] + simp only [sample, f, Function.comp_def, Sum.elim_inl, Sum.elim_inr, Equiv.symm_apply_apply] + · intro z _ hne + have h : ¬∀ e, z e = val z e.1.succ e.2 := fun h => hne (forced z h) + push Not at h + obtain ⟨e, he⟩ := h + refine prod_eq_zero (mem_univ (dst hd (.inr e))) ?_ + rw [hw, ite_eq_right (fun h => he (h e rfl))] + · simp + +open scoped Classical in +theorem arity (v : Site T t) : (network hd).arity v ≤ 4 * 2 ^ t := by + rw [Diagram.arity_ofLocal] + have h₁ := capacity hd Sum.inl Sum.inl_injective Fin.castSucc (Fin.castSucc_injective _) v + have h₂ := capacity hd Sum.inr Sum.inr_injective Fin.succ (Fin.succ_injective _) v + convert! Nat.add_le_add h₁ h₂ using 1 <;> first | omega | congr! 3 + +omit [Field F] in +open scoped Classical in +theorem size (T : Table F) (t : ℕ) : + Fintype.card (Site T t) ≤ 4 * (1 + wd T.1 + wd T.2.1) * (t + 1) := by + simp only [Site, Node, Fintype.card_prod, Fintype.card_sigma, Fintype.card_fin, card_cell, dim, + sum_const, card_univ, Fintype.card_unit, one_smul] + apply Nat.mul_le_mul_right + by_cases h : wd T.1 + wd T.2.1 = 0 + · simp only [h, Nat.clog_zero_right, pow_zero]; omega + · exact (Transcript.pow_clog_le_twice (Nat.pos_of_ne_zero h)).trans (by omega) + +open scoped Classical in +private def make : Device T t where + diagram := network hd + eval := evaluate hd + name := terminal T t + external p := by cases p <;> exact last hd _ + adj v := (Node.links v).filter (fun w => v ∈ Node.links w) + sym _ _ hw := mem_filter.mpr ⟨(mem_filter.mp hw).2, (mem_filter.mp hw).1⟩ + degree v := (card_filter_le ..).trans (Node.links_card v) + linked e := mem_filter.mpr + ⟨Node.layer_link hd _ _ (.inl rfl) _ _, Node.layer_link hd _ _ (.inr rfl) _ _⟩ + loopless e he := by + have := congrArg (fun v : Site T t => v.2.val) he + change e.1.val = e.1.val + 1 at this + omega + arity := arity hd + size := size T t + +end Butterfly + +open scoped Classical in +/-- Replace one stacked table, preserving the copy order on every port. -/ +theorem device (T : Table F) (t : ℕ) (bound : wd T.1 + wd T.2.1 ≤ 2 ^ t) : + Nonempty (Device T t) := + ⟨Butterfly.make (fun _ => Nat.clog_le_of_le_pow bound)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end + +/- +# Spans inside one local butterfly + +Parallel wires in a fixed direction form one span. The exterior bits +at a device terminal form another span, ordered by stack index. All +numbering in this file uses only the device of a single input table. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Device +open Assembly Coloring Transcript Packing Finset + +variable {F : Type} [Field F] {T : Table F} {t : ℕ} (D : Device T t) +local notation "G" => D.diagram + +open scoped Classical in +/-- The value specified by `((G).source e, (G).target e)`. -/ +def pair (e : (G).E) := ((G).source e, (G).target e) +open scoped Classical in +/-- The set of values attained by `D.pair`. -/ +abbrev Link := Set.range D.pair +open scoped Classical in +/-- Uses `⟨D.pair e, e, rfl⟩` as the representation. -/ +def link (e : (G).E) : D.Link := ⟨D.pair e, e, rfl⟩ + +open scoped Classical in +/-- Indexes the line by the coordinates of `(D.Link × Bool) ⊕ Ports T`. -/ +abbrev Line := (D.Link × Bool) ⊕ Ports T + +open scoped Classical in +/-- In the case `.inl (e, b)`, this construction gives `cond b e.val.2 e.val.1`. -/ +def site : D.Line → (G).V + | .inl (e, b) => cond b e.val.2 e.val.1 + | .inr p => D.name p + +open scoped Classical in +/-- In the case `.inl (_, b)`, this construction gives `b`. -/ +def side : D.Line → Bool + | .inl (_, b) => b + | .inr p => p.isRight + +open scoped Classical in +/-- In the case `.inl (e, _)`, this construction gives `Fintype.card {i // D.link i = e}`. -/ +def width : D.Line → ℕ + | .inl (e, _) => Fintype.card {i // D.link i = e} + | .inr _ => 2 ^ t + +open scoped Classical in +theorem width_pos (l : D.Line) : 0 < D.width l := by + rcases l with ⟨e, b⟩|p + · obtain ⟨i, hi⟩ := e.property + exact Fintype.card_pos_iff.mpr ⟨⟨i, Subtype.ext hi⟩⟩ + · exact Nat.two_pow_pos _ + +open scoped Classical in +/-- Reindexes `(G).E` and `Σ e : D.Link, Fin (Fintype.card {i // D.link i = e})` by an +equivalence. -/ +def bundle : (G).E ≃ Σ e : D.Link, Fin (Fintype.card {i // D.link i = e}) := + (Equiv.sigmaFiberEquiv D.link).symm.trans (Equiv.sigmaCongrRight fun _ => Fintype.equivFin _) + +open scoped Classical in +/-- Indexes the bit by the coordinates of `Σ l, Fin (D.width l)`. -/ +abbrev Bit := Σ l, Fin (D.width l) + +open scoped Classical in +/-- Computes the inside by the application `cond b (.inr (.inr e)) (.inl (.inr e))`. -/ +def inside (e : (G).E) (b : Bool) : (G).End := cond b (.inr (.inr e)) (.inl (.inr e)) + +open scoped Classical in +/-- In the case `⟨.inl (e, b), i⟩`, this construction gives `D.inside (D.bundle.symm ⟨e, i⟩) b`. -/ +def decode : D.Bit → (G).End + | ⟨.inl (e, b), i⟩ => D.inside (D.bundle.symm ⟨e, i⟩) b + | ⟨.inr p, i⟩ => boundaryEnd (G) ((BatchDescent.Stack.pin T _).symm (i, p)) + +open scoped Classical in +/-- Uses `⟨.inl (D.link e, b), (D.bundle e).2⟩` as the representation. -/ +def internal (e : (G).E) (b : Bool) : D.Bit := ⟨.inl (D.link e, b), (D.bundle e).2⟩ + +open scoped Classical in +/-- The external pin of type `D.Bit`, constructed using `BatchDescent.Stack.pin T (2 ^ t) p`. -/ +def externalPin (p : Ports (BatchDescent.Stack.tensor T (2 ^ t))) : D.Bit := + let q := BatchDescent.Stack.pin T (2 ^ t) p + ⟨.inr q.2, q.1⟩ + +open scoped Classical in +/-- In the case `.inl (.inl p)`, this construction gives `D.externalPin (.inl p)`. -/ +def encode : (G).End → D.Bit + | .inl (.inl p) => D.externalPin (.inl p) + | .inr (.inl p) => D.externalPin (.inr p) + | .inl (.inr e) => D.internal e false + | .inr (.inr e) => D.internal e true + +open scoped Classical in +@[simp] theorem encode_inside (e : (G).E) (b : Bool) : D.encode (D.inside e b) = D.internal e b + := by + cases b <;> rfl + +open scoped Classical in +@[simp] theorem encode_boundary (p : Ports (BatchDescent.Stack.tensor T (2 ^ t))) : + D.encode (boundaryEnd (G) p) = D.externalPin p := by cases p <;> rfl + +open scoped Classical in +theorem decode_internal (e : (G).E) (b : Bool) : D.decode (D.internal e b) = D.inside e b := + congrArg (fun k => D.inside k b) (D.bundle.symm_apply_apply e) + +open scoped Classical in +theorem decode_outer (p : Ports (BatchDescent.Stack.tensor T (2 ^ t))) : + D.decode (D.externalPin p) = boundaryEnd (G) p := + congrArg (boundaryEnd (G)) ((BatchDescent.Stack.pin T _).symm_apply_apply p) + +open scoped Classical in +/-- Reindexes `(G).End` and `D.Bit where toFun` by an equivalence. -/ +def codec : (G).End ≃ D.Bit where + toFun := D.encode + invFun := D.decode + left_inv + | .inl (.inl p) => D.decode_outer (.inl p) + | .inr (.inl p) => D.decode_outer (.inr p) + | .inl (.inr e) => D.decode_internal e false + | .inr (.inr e) => D.decode_internal e true + right_inv q := by + rcases q with ⟨⟨e, b⟩|p, i⟩ + · rw [decode, encode_inside] + exact congrArg (fun p => (⟨.inl (p.1, b), p.2⟩ : D.Bit)) (D.bundle.apply_symm_apply ⟨e, i⟩) + · rw [decode, encode_boundary] + exact congrArg (fun q => (⟨.inr q.2, q.1⟩ : D.Bit)) + ((BatchDescent.Stack.pin T _).apply_symm_apply (i, p)) + +open scoped Classical in +theorem site_codec (e : (G).End) : D.site (D.codec e).1 = (G).station e := by + rcases e with (i|e)|(i|e) + · exact (D.external (.inl i)).symm + · rfl + · exact (D.external (.inr i)).symm + · rfl + +open scoped Classical in +theorem side_codec (e : (G).End) : D.side (D.codec e).1 = e.isRight := by + rcases e with (i|e)|(i|e) <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Device +end + +/- # Constantly many span names per butterfly station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Device +open Assembly Coloring Transcript Packing Finset + +variable {F : Type} [Field F] {T : Table F} {t : ℕ} (D : Device T t) +local notation "G" => D.diagram + +open scoped Classical in +/-- Computes the neighbor by the application `Classical.choice +(Function.Embedding.nonempty_of_card_le (by simpa using D.degree v))`. -/ +def neighbor (v : (G).V) : ↥(D.adj v) ↪ Fin 4 := + Classical.choice (Function.Embedding.nonempty_of_card_le (by simpa using D.degree v)) + +open scoped Classical in +/-- Returns `D.neighbor v ⟨w, h⟩` when `h : w ∈ D.adj v` holds, and `0` otherwise. -/ +def number (v w : (G).V) := if h : w ∈ D.adj v then D.neighbor v ⟨w, h⟩ else 0 + +open scoped Classical in +private theorem number_inj {v w x y : (G).V} (hw : w ∈ D.adj v) (hy : y ∈ D.adj x) + (he : v = x) (hn : D.number v w = D.number x y) : w = y := by + subst x + simp only [number, dite_eq_left hw, dite_eq_left hy] at hn + exact congrArg Subtype.val ((D.neighbor _).injective hn) + +open scoped Classical in +theorem linked_at (c : D.Link) : c.val.2 ∈ D.adj c.val.1 := by + obtain ⟨e, he⟩ := c.property + rw [← he]; exact D.linked e + +open scoped Classical in +/-- Computes the code by the application `Classical.choice +(Function.Embedding.nonempty_of_card_le (by simp))`. -/ +def code : Option (Bool × Fin 4) ↪ B 4 := + Classical.choice (Function.Embedding.nonempty_of_card_le (by simp)) + +open scoped Classical in +/-- The slot used in the `Device` construction. -/ +def slot : D.Line → B 4 + | .inl (c, b) => code (some (b, D.number (D.site (.inl (c, b))) (D.site (.inl (c, !b))))) + | .inr _ => code none + +open scoped Classical in +theorem slot_inj {x y : D.Line} (hv : D.site x = D.site y) (hs : D.slot x = D.slot y) : x = y := by + rcases x with ⟨c, b⟩|p <;> rcases y with ⟨d, a⟩|q + · obtain ⟨rfl, he⟩ := Prod.mk.inj (Option.some.inj (code.injective hs)) + have hc := D.linked_at c + have hd := D.linked_at d + have eq : c = d := by + apply Subtype.ext + cases b + · exact Prod.ext hv (D.number_inj hc hd hv he) + · exact Prod.ext (D.number_inj (D.sym _ _ hc) (D.sym _ _ hd) hv he) hv + rw [eq] + · cases code.injective hs + · cases code.injective hs + · exact congrArg Sum.inr (D.name.injective hv) + +open scoped Classical in +/-- Returns `some h.choose` when `h : ∃ p, D.site p = v ∧ D.slot p = s` holds, and `none` +otherwise. -/ +def line (v : (G).V) (s : B 4) : Option D.Line := + if h : ∃ p, D.site p = v ∧ D.slot p = s then some h.choose else none + +open scoped Classical in +theorem line_eq (v : (G).V) (s : B 4) (p : D.Line) : + D.line v s = some p ↔ D.site p = v ∧ D.slot p = s := by + unfold line + split + · rename_i h + rw [Option.some.injEq] + exact ⟨fun he => he ▸ h.choose_spec, fun he => + D.slot_inj (h.choose_spec.1.trans he.1.symm) (h.choose_spec.2.trans he.2.symm)⟩ + · rename_i h + exact iff_of_false (by simp) (fun e => h ⟨p, e⟩) + +open scoped Classical in +/-- The value specified by `(D.line v s).elim 0 D.width`. -/ +def sizeAt (v : (G).V) (s : B 4) := (D.line v s).elim 0 D.width + +open scoped Classical in +theorem sizeAt_slot (v : (G).V) (l : D.Line) (h : D.site l = v) : + D.sizeAt v (D.slot l) = D.width l := by + rw [sizeAt, (D.line_eq ..).mpr ⟨h, rfl⟩]; rfl + +open scoped Classical in +/-- The value specified by `D.codec ((G).portEquiv ⟨v, p⟩)`. -/ +def localBit (v : (G).V) (p : (G).Port v) := D.codec ((G).portEquiv ⟨v, p⟩) + +open scoped Classical in +theorem local_site (v : (G).V) (p : (G).Port v) : D.site (D.localBit v p).1 = v := by + rw [localBit, site_codec, Diagram.station_port] + +open scoped Classical in +/-- Uses `⟨D.slot (D.localBit v p).1, (D.localBit v p).2.cast (D.sizeAt_slot _ _ (D.local_site v +p)).symm⟩` as the representation. -/ +def address (v : (G).V) (p : (G).Port v) : Σ s, Fin (D.sizeAt v s) := + ⟨D.slot (D.localBit v p).1, (D.localBit v p).2.cast (D.sizeAt_slot _ _ (D.local_site v p)).symm⟩ + +open scoped Classical in +theorem bijective (v : (G).V) : Function.Bijective (D.address v) := by + constructor + · intro a b he + have h := D.slot_inj ((D.local_site _ a).trans (D.local_site _ b).symm) (congrArg Sigma.fst he) + have e : D.localBit v a = D.localBit v b := Sigma.ext h + ((Fin.heq_ext_iff (congrArg D.width h)).mpr (congrArg (fun i => i.2.val) he)) + exact eq_of_heq (Sigma.mk.inj ((G).portEquiv.injective (D.codec.injective e))).2 + · rintro ⟨s, i⟩ + cases h : D.line v s with + | none => have := i.isLt; simp [sizeAt, h] at this + | some l => + obtain ⟨hv, hs⟩ := (D.line_eq ..).mp h + have hw : D.sizeAt v s = D.width l := by rw [sizeAt, h]; rfl + obtain ⟨⟨u, p⟩, he⟩ := ((G).portEquiv.trans D.codec).surjective ⟨l, i.cast hw⟩ + change D.localBit u p = _ at he + have hu : u = v := (D.local_site u p).symm.trans (he ▸ hv) + subst u + refine ⟨p, ?_⟩ + have h₁ : (D.address v p).1 = s := (congrArg (fun k : D.Bit => D.slot k.1) he).trans hs + exact Sigma.ext h₁ ((Fin.heq_ext_iff (congrArg (D.sizeAt v) h₁)).mpr + (congrArg (fun k : D.Bit => k.2.val) he)) + +open scoped Classical in +/-- Indexes the guide by the coordinates of `B 4 → Option (B 3 × B 0 × B 4)`. -/ +abbrev Guide := B 4 → Option (B 3 × B 0 × B 4) + +open scoped Classical in +/-- Only the guide depends on the placement of the device. Its alphabet +is fixed independently of the original graph and the stack width. -/ +def pattern (v : (G).V) (g : Guide) : Pattern F 3 0 4 where + width _ := D.sizeAt v + direction _ s := (D.line v s).elim false D.side + peer _ := g + value _ x := sample ((G).table v) (fun p => x (D.address v p).1 (D.address v p).2) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Device +end + +/- # One shared dictionary for the devices of a stack -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +open Assembly Coloring Finset + +variable {F : Type} [Field F] {a b : Wire} {t : ℕ} + +open scoped Classical in +/-- Builds `Pattern F 3 0 4 where width _ _` with the specified `width`, `direction`, `peer`, +`value`. -/ +def emptyPattern (F : Type) [Field F] : Pattern F 3 0 4 where + width _ _ := 0 + direction _ _ := false + peer _ _ := none + value _ _ := 1 + +open scoped Classical in +/-- The data for the codec construction, including `decode`, `label`, `read`, `blank`, `empty`. -/ +structure Codec (G : Diagram F a b) (f : ∀ v, Device (G.table v) t) (ℓ : ℕ) where + /-- The `Codec` component of type `B ℓ → Pattern F 3 0 4`. -/ + decode : B ℓ → Pattern F 3 0 4 + /-- The label at each coordinate of type `∀ v, (f v).diagram.V → Device.Guide → B ℓ`. -/ + label : ∀ v, (f v).diagram.V → Device.Guide → B ℓ + read : ∀ v z a, decode (label v z a) = (f v).pattern z a + /-- The `Codec` field of type `B ℓ`. -/ + blank : B ℓ + empty : decode blank = emptyPattern F + +open scoped Classical in +/-- Equal tables use the same device. A label names only a table, a +vertex within that device and a guide. Reserve one extra blank label. -/ +theorem codec (G : Diagram F a b) (bound : ∀ v, G.arity v ≤ 2 ^ t) + {M : ℕ} (hc : (univ.image G.table).card ≤ M) : + ∃ f : ∀ v, Device (G.table v) t, + Nonempty (Codec G f (Nat.clog 2 (1 + M * 4 * (1 + 2 ^ t) * (t + 1) * Nat.card Device.Guide))) + := by + let L := univ.image G.table + have hwidth (T : L) : wd T.val.1 + wd T.val.2.1 ≤ 2 ^ t := by + obtain ⟨v, _, hv⟩ := mem_image.mp T.property + rw [← hv] + exact bound v + let D (T : L) := Classical.choice (device T.val t (hwidth T)) + let ofV (v : G.V) : L := ⟨G.table v, mem_image_of_mem _ (mem_univ v)⟩ + let f := fun v => D (ofV v) + let K := Option (Σ T : L, (D T).diagram.V × Device.Guide) + let N := 1 + M * 4 * (1 + 2 ^ t) * (t + 1) * Nat.card Device.Guide + have hcard : Fintype.card K ≤ N := by + have hs (T : L) : Fintype.card (D T).diagram.V ≤ 4 * (1 + 2 ^ t) * (t + 1) := by + refine (D T).size.trans ?_ + have := hwidth T + exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ (by omega)) + simp only [K, Fintype.card_option, Fintype.card_sigma, Fintype.card_prod, + ←Nat.card_eq_fintype_card (α := Device.Guide)] + calc + _ ≤ (∑ _ : L, 4 * (1 + 2 ^ t) * (t + 1) * Nat.card Device.Guide) + 1 := + Nat.add_le_add_right (sum_le_sum fun T _ => Nat.mul_le_mul_right _ (hs T)) _ + _ ≤ N := by + rw [sum_const, card_univ, Fintype.card_coe, Nat.nsmul_eq_mul] + unfold N + conv_rhs => rw [add_comm] + simp only [mul_assoc] + exact Nat.add_le_add_right (Nat.mul_le_mul_right _ hc) _ + obtain ⟨e⟩ := Function.Embedding.nonempty_of_card_le (α := K) (β := B (Nat.clog 2 N)) + (by rw [Fintype.card_fin]; exact hcard.trans (Nat.le_pow_clog (by decide) _)) + let pattern : K → Pattern F 3 0 4 + | none => emptyPattern F + | some z => (D z.1).pattern z.2.1 z.2.2 + let decode := pattern ∘ Function.invFun e + have read (k : K) : decode (e k) = pattern k := + congrArg pattern (Function.leftInverse_invFun e.injective k) + exact ⟨f, ⟨⟨decode, fun v z g => e (some ⟨ofV v, z, g⟩), + fun v z g => read (some ⟨ofV v, z, g⟩), e none, read none⟩⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack +end + +/- # Tracking all named ports through a stack of local devices -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Label +open Assembly Coloring Packing + +variable {F : Type} [Field F] {a b : Wire} {h t n : ℕ} (G : Diagram F a b) + (f : ∀ v, Device (G.table v) t) (c : Cell h × Fin (2 ^ t) ≃ Fin n) + +open scoped Classical in +/-- Computes the wire end by the application `cond b (.inr (.inr e)) (.inl (.inr e))`. -/ +def wireEnd (e : G.E) (b : Bool) : G.End := cond b (.inr (.inr e)) (.inl (.inr e)) + +open scoped Classical in +/-- Indexes the stub by the coordinates of `Σ v, (f v).Line`. -/ +abbrev Stub := Σ v, (f v).Line + +open scoped Classical in +/-- Uses `⟨s.1, (f s.1).site s.2⟩` as the representation. -/ +def site (s : Stub G f) : Location G f := ⟨s.1, (f s.1).site s.2⟩ +open scoped Classical in +/-- The value specified by `(f s.1).slot s.2`. -/ +def slot (s : Stub G f) := (f s.1).slot s.2 +open scoped Classical in +/-- The value specified by `(f s.1).side s.2`. -/ +def side (s : Stub G f) := (f s.1).side s.2 +open scoped Classical in +/-- The value specified by `(f s.1).width s.2`. -/ +def width (s : Stub G f) := (f s.1).width s.2 + +open scoped Classical in +/-- The outer of type `Stub G f`, constructed using `G.portEquiv.symm e`. -/ +def outer (e : G.End) : Stub G f := + let q := G.portEquiv.symm e + ⟨q.1, .inr q.2⟩ + +open scoped Classical in +/-- Uses `⟨v, .inl ((f v).link e, s)⟩` as the representation. -/ +def inner (v : G.V) (e : (f v).diagram.E) (s : Bool) : Stub G f := + ⟨v, .inl ((f v).link e, s)⟩ + +open scoped Classical in +/-- The indexed operation `(BatchDescent.Stack.gathered G c).plugEnd (fun v => (f +v.2).diagram)`. -/ +def lift := (BatchDescent.Stack.gathered G c).plugEnd (fun v => (f v.2).diagram) + +open scoped Classical in +/-- The read of type `Cell h × Stub G f × ℕ`, constructed using `(lift G f c).symm e`. -/ +def read (e : (built G f c).End) : Cell h × Stub G f × ℕ := + let i := (lift G f c).symm e + let b := (f i.1.2).codec i.2 + (i.1.1, ⟨i.1.2, b.1⟩, b.2.val) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Label +end + +/- # Matching local spans without using full vertex names in the labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Label +open Assembly Finset + +variable {F : Type} [Field F] {a b : Wire} {t : ℕ} (G : Diagram F a b) + (f : ∀ v, Device (G.table v) t) + +open scoped Classical in +/-- In the case `.inl (.inr e)`, this construction gives `some (outer G f (.inr (.inr e)))`. -/ +def across : G.End → Option (Stub G f) + | .inl (.inr e) => some (outer G f (.inr (.inr e))) + | .inr (.inr e) => some (outer G f (.inl (.inr e))) + | _ => none + +open scoped Classical in +/-- In the case `⟨v, .inl (e, b)⟩`, this construction gives `some ⟨v, .inl (e, !b)⟩`. -/ +def mate : Stub G f → Option (Stub G f) + | ⟨v, .inl (e, b)⟩ => some ⟨v, .inl (e, !b)⟩ + | ⟨v, .inr p⟩ => across G f (G.portEquiv ⟨v, p⟩) + +open scoped Classical in +private theorem mate_outer (e : G.End) : mate G f (outer G f e) = across G f e := + congrArg (across G f) (G.portEquiv.apply_symm_apply e) + +open scoped Classical in +theorem mate_edge (e : G.E) (b : Bool) : + mate G f (outer G f (wireEnd G e b)) = some (outer G f (wireEnd G e (!b))) := by + rw [mate_outer]; cases b <;> rfl + +open scoped Classical in +theorem mate_inner (v : G.V) (e : (f v).diagram.E) (b : Bool) : + mate G f (inner G f v e b) = some (inner G f v e (!b)) := rfl + +open scoped Classical in +theorem mate_boundary (i : slots a ⊕ slots b) : + mate G f (outer G f (boundaryEnd G i)) = none := by + rw [mate_outer]; cases i <;> rfl + +open scoped Classical in +theorem side_outer (e : G.End) : side G f (outer G f e) = e.isRight := by + cases e <;> rfl + +open scoped Classical in +private theorem adjacent_outer (e : G.End) : + site G f (outer G f (other G e)) ∈ Device.neighbors G f (site G f (outer G f e)) := + mem_insert.mpr (.inl (Device.partner_end G f e).symm) + +open scoped Classical in +theorem mate_props {i j : Stub G f} (h : mate G f i = some j) : + mate G f j = some i ∧ width G f i = width G f j ∧ side G f i ≠ side G f j ∧ + site G f j ∈ Device.neighbors G f (site G f i) := by + rcases i with ⟨v, ⟨e, z⟩|p⟩ + · have : j = ⟨v, .inl (e, !z)⟩ := (Option.some.inj h).symm + subst j + have w := (f v).linked_at e + cases z + · exact ⟨rfl, rfl, Bool.false_ne_true, mem_insert_of_mem (mem_image_of_mem (Sigma.mk v) w)⟩ + · exact ⟨rfl, rfl, Ne.symm Bool.false_ne_true, + mem_insert_of_mem (mem_image_of_mem (Sigma.mk v) ((f v).sym _ _ w))⟩ + · have e : (⟨v, .inr p⟩ : Stub G f) = outer G f (G.portEquiv ⟨v, p⟩) := + congrArg (fun k : Σ v, G.Port v => (⟨k.1, .inr k.2⟩ : Stub G f)) + (G.portEquiv.symm_apply_apply ⟨v, p⟩).symm + rw [e] at h ⊢ + rw [mate_outer] at h + generalize G.portEquiv ⟨v, p⟩ = k at h ⊢ + rcases k with (i|d)|(i|d) + · cases h + · obtain rfl := Option.some.inj h + exact ⟨mate_edge G f d true, rfl, Bool.false_ne_true, adjacent_outer G f (.inl (.inr d))⟩ + · cases h + · obtain rfl := Option.some.inj h + exact ⟨mate_edge G f d false, rfl, Ne.symm Bool.false_ne_true, + adjacent_outer G f (.inr (.inr d))⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Label +end + +/- # The block, span and ordinal of every end of the joined stack -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Label +open Assembly Packing + +variable {F : Type} [Field F] {a b : Wire} {h t n : ℕ} (G : Diagram F a b) + (f : ∀ v, Device (G.table v) t) (c : Cell h × Fin (2 ^ t) ≃ Fin n) + +private theorem read_outer (z : Cell h × Fin (2 ^ t)) (i : G.End) (e : (built G f c).End) + (he : let p := G.portEquiv.symm i + (lift G f c).symm e = ⟨(z.1, p.1), boundaryEnd (f p.1).diagram + ((BatchDescent.Stack.pin (G.table p.1) (2 ^ t)).symm (z.2, p.2))⟩) : + read G f c e = (z.1, outer G f i, z.2.val) := by + unfold read + rw [he] + let p := G.portEquiv.symm i + let D := f p.1 + let q := (BatchDescent.Stack.pin (G.table p.1) (2 ^ t)).symm (z.2, p.2) + have hc : D.codec (boundaryEnd D.diagram q) = ⟨.inr p.2, z.2⟩ := by + change D.encode _ = _ + rw [D.encode_boundary, Device.externalPin] + exact congrArg (fun r => (⟨.inr r.2, r.1⟩ : D.Bit)) + ((BatchDescent.Stack.pin (G.table p.1) (2 ^ t)).apply_symm_apply (z.2, p.2)) + exact congrArg (fun r : D.Bit => (z.1, (⟨p.1, r.1⟩ : Stub G f), r.2.val)) hc + +theorem read_edge (z : Cell h × Fin (2 ^ t)) (e : G.E) (s : Bool) : + read G f c (wireEnd (built G f c) (.inl (z, e)) s) = (z.1, outer G f (wireEnd G e s), z.2.val) + := by + apply read_outer + cases s <;> rfl + +theorem read_inner (z : Cell h) (v : G.V) (e : (f v).diagram.E) (s : Bool) : + read G f c (wireEnd (built G f c) (.inr ⟨(z, v), e⟩) s) = + (z, inner G f v e s, ((f v).bundle e).2.val) := by + cases s <;> rfl + +/-- Reindexes `slots (copies a n) ⊕ slots (copies b n)` and `Fin n × (slots a ⊕ slots b)` by an +equivalence. -/ +def copiedPort (a b : Wire) (n : ℕ) : + slots (copies a n) ⊕ slots (copies b n) ≃ Fin n × (slots a ⊕ slots b) := + ((Diagonal.port a n).sumCongr (Diagonal.port b n)).trans (Equiv.prodSumDistrib _ _ _).symm + +theorem read_boundary (i : slots (copies a n) ⊕ slots (copies b n)) : + let p := copiedPort a b n i + let z := c.symm p.1 + read G f c (boundaryEnd (built G f c) i) = (z.1, outer G f (boundaryEnd G p.2), z.2.val) := by + apply read_outer + cases i <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Stack.Label +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Sweep.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Sweep.lean new file mode 100644 index 0000000000..99135209e9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Rounds/Sweep.lean @@ -0,0 +1,849 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Terminal.DictionaryHeaders +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Hold +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Sweep +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Attachment.Apply + +/-! # Joining stages with their own arity and table budgets -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Transforms + +universe v +variable {F : Type} [Field F] {x y : Wire} {X Y Z : Snapshot.{v} F x y} + {u w m n : ℕ} {L M : Finset (Table F)} + +open scoped Classical in +theorem comp_union (f : Transforms F u L X Y m) (g : Transforms F w M Y Z n) : + Transforms F (max u w) (↑(L ∪ M) : Set (Table F)) X Z (m + n) := by + classical + exact (f.widen (Nat.le_max_left _ _) (fun t ht => Finset.mem_union_left _ ht)).comp + (g.widen (Nat.le_max_right _ _) (fun t ht => Finset.mem_union_right _ ht)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Transforms +end + +/- # Local concentration with arbitrary integral scales and bundles -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Filter + +/-- Apply concentration after zero-padding the actual ordered bundles. +The caller supplies a positive loopless diagram and its host, with no +condition on the divisibility of the old bundle widths. -/ +theorem LocalLaw.with_padding {k : Type} [Field k] {ℓ : ℕ} + (law : LocalLaw k (ℓ + 1)) (g : ℕ) (hg : 0 < g) : + ∃ C : ℕ, ∀ᶠ D : ℕ in atTop, + ∃ (A : ℕ) (L : Type) (_ : Field L) (_ : Finite L) (_ : Algebra k L), + ∀ᶠ T : ℕ in atTop, ∃ r u : ℕ, 0 < r ∧ r * D ^ 2 ≤ 2 * T ∧ 0 < u ∧ T ≤ u * D ^ (2 * C + 1) ∧ + ∀ (K : Type) (_ : Field K) (_ : Fintype K) (_ : Algebra L K), + A * (1 + 2 * T) ^ A ≤ Fintype.card K → + ∀ (x y : Wire) (h R : ℕ) (W : ℝ) (P : Input K x y h D T R g W), + LocalExpansion P u (202 * (2 * C)) (Nat.clog 2 D) ℓ (2 * A) := by + obtain ⟨C, hC⟩ := law.arbitrary g hg + refine ⟨C, ?_⟩ + filter_upwards [hC, eventually_ge_atTop (400 * (g + 1))] with D hD scope + obtain ⟨A, L, _, _, _, hT⟩ := hD + refine ⟨A, L, inferInstance, inferInstance, inferInstance, ?_⟩ + have twice : Tendsto (fun T : ℕ => 2 * T) atTop atTop := by + apply tendsto_atTop.2 + intro N + filter_upwards [eventually_ge_atTop N] with T ht + omega + filter_upwards [twice.eventually hT] with T h + obtain ⟨r, u, hr, hr', hu, hlo, run⟩ := h + refine ⟨r, u, hr, hr', hu, (show T ≤ 2 * T by omega).trans hlo, ?_⟩ + intro K _ _ _ field x y h R W P + exact LocalExpansion.of_packetize P hr scope hr' + (run K inferInstance inferInstance inferInstance field x y h (101 * W) + (P.packetize r hr scope hr')) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Fitting the charged stations into the terminal evaluator -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly + +variable {F : Type} [Field F] {x y : Wire} {Q : Layer F x y} {D T V t : ℕ} {L θ : ℝ} + (i : Q.State) + +local notation "S" => Q.template.scheme +local notation "r" => Prod.fst (Q.data i) +local notation "G" => Q.graph i +local notation "pr" => Template.Presents.pres (Q.presents i) + +open scoped Classical in +private theorem local_size (v : (G).V) : + Fintype.card ((S).LocalPin r ((pr).vertex v)) = (G).arity v := by + rw [← Fintype.card_congr ((pr).pin v)] + simp only [Diagram.Port, Fintype.card_sum, card_slots, Diagram.arity] + +open scoped Classical in +private theorem active (v : (G).V) : + Terminal.Active S r ((pr).vertex v) ↔ 0 < (G).arity v := by + rw [Terminal.Active, ← Fintype.card_pos_iff, local_size] + +open scoped Classical in +private theorem live : + Fintype.card (Terminal.Live S r) = Fintype.card {v : (G).V // 0 < (G).arity v} := by + let f : {v : (G).V // 0 < (G).arity v} → Terminal.Live S r := + fun v => ⟨(pr).vertex v.val, (active i v.val).mpr v.property⟩ + symm + refine Fintype.card_congr (Equiv.ofBijective f ⟨?_, ?_⟩) + · exact fun _ _ he => Subtype.ext ((pr).vertex.injective (Subtype.mk.inj he)) + · rintro ⟨v, ⟨j⟩⟩ + obtain ⟨w, hw⟩ := (pr).cover ((S).port r v j) + change (pr).vertex w = v at hw + subst v + exact ⟨⟨w, (active i w).mp ⟨j⟩⟩, rfl⟩ + +open scoped Classical in +theorem Neutral.terminal (h : Q.Neutral) : Terminal.Neutral S r := by + intro v hn t + by_cases hv : v ∈ Set.range (pr).vertex + · obtain ⟨w, rfl⟩ := hv + rw [(pr).sample] + exact h i w (Nat.eq_zero_of_not_pos (mt (active i w).mpr hn)) _ + · exact (pr).vacant v hv t + +open scoped Classical in +theorem Ready.live_bound (h : Q.Ready D T L θ) : + (Fintype.card (Terminal.Live S r) : ℝ) * (θ * T) ≤ L := by + rw [live] + let f := (Q.board i).charge + have nonneg (v : (G).V) : 0 ≤ f v := (by positivity : (0 : ℝ) + ≤ (G).arity v) |>.trans ((Q.board i).cover v) + let s := Finset.univ.filter (fun v : (G).V => 0 < (G).arity v) + have he : Fintype.card {v : (G).V // 0 < (G).arity v} = s.card := Fintype.card_subtype _ + rw [he, ← nsmul_eq_mul, ← Finset.sum_const] + calc + _ ≤ ∑ v ∈ s, f v := by + refine Finset.sum_le_sum fun v hv => ?_ + have hp := (Finset.mem_filter.mp hv).2 + have hg := (Nat.cast_pos.mpr hp).trans_le ((Q.board i).cover v) + exact ((h.2.2 i).2.2.2 v).2.resolve_left hg.ne' + _ ≤ ∑ v, f v := Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) (fun v _ _ + => nonneg v) + _ ≤ _ := (h.2.2 i).2.1 + +open scoped Classical in +private theorem Ready.span_bound (h : Q.Ready D T L θ) (w : (S).Span) : (S).width r w ≤ D * T := by + rcases w with ⟨v, j⟩ + by_cases hw : 0 < (S).width r (v, j) + swap + · exact (Nat.eq_zero_of_not_pos hw).le.trans (Nat.zero_le _) + obtain ⟨a, ha⟩ := (pr).cover ⟨(v, j), ⟨0, hw⟩⟩ + change (pr).vertex a = v at ha + subst v + have hcard := local_size i a + simp only [Scheme.LocalPin, Fintype.card_sigma, Fintype.card_fin] at hcard + apply le_trans (b := (G).arity a) + · rw [← hcard] + exact Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ j) + · have hp := ((Q.board i).cover a).trans ((h.2.2 i).2.2.2 a).1 + have ht : ((G).arity a : ℝ) ≤ (D : ℝ) * T := hp.trans (div_le_self (by positivity) (by + norm_num)) + exact_mod_cast ht + +open scoped Classical in +theorem Ready.terminal (h : Q.Ready D T L θ) (hθ : 0 < θ) (hT : 0 < T) (ht : D * T ≤ 2 ^ t) + (cap : 2 ^ Q.template.scheme.m + ⌊L / (θ * T)⌋₊ * 2 ^ (Q.template.scheme.e + t) ≤ V) + (i : Q.State) : Terminal.Fits S (Q.data i).1 V t ∧ Terminal.Neutral S (Q.data i).1 := by + refine ⟨⟨fun w => (h.span_bound i w).trans ht, ?_⟩, h.2.1.terminal i⟩ + have hc := Nat.le_floor ((le_div_iff₀ (by positivity : 0 < θ * (T : ℝ))).mpr (h.live_bound i)) + exact (Nat.add_le_add_left (Nat.mul_le_mul_right _ hc) _).trans cap + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- +# Accounting for a sequence of encoded rounds + +Each round carries its own finite dictionary. Their union suffices for +the entire sequence, and the network cost is the sum of the round costs. +The initialization and terminal contraction are paid separately. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Finset + +namespace Assembly.Transforms +universe v +variable {F : Type} [Field F] {x y : Wire} + +open scoped Classical in +/-- Compose a nonempty sequence, with one arity ceiling for the whole +sequence. No copy of the intermediate wires is charged at composition. -/ +theorem sequence (X : ℕ → Snapshot.{v} F x y) (keys : ℕ → Finset (Table F)) + (cost : ℕ → ℕ) {cap n : ℕ} (hn : 0 < n) + (step : ∀ i < n, Transforms F cap (keys i) (X i) (X (i + 1)) (cost i)) : + Transforms F cap (↑((range n).biUnion keys) : Set (Table F)) + (X 0) (X n) (∑ i ∈ range n, cost i) := by + classical + induction n with + | zero => omega + | succ n ih => + rw [sum_range_succ, range_add_one, biUnion_insert] + have last := (step n (by omega)).widen le_rfl + (show (↑(keys n) : Set (Table F)) ⊆ ↑(keys n ∪ (range n).biUnion keys) from + fun t ht => mem_union_left _ ht) + by_cases hz : n = 0 + · subst n + simpa using last + · have first := (ih (Nat.pos_of_ne_zero hz) (fun i hi => step i (by omega))).widen le_rfl + (show (↑((range n).biUnion keys) : Set (Table F)) ⊆ ↑(keys n ∪ (range n).biUnion keys) from + fun t ht => mem_union_right _ ht) + exact first.comp last + +end Assembly.Transforms + +namespace Rounds +variable {F : Type} [Field F] {x y : Wire} + +open scoped Classical in +/-- Install the rounds between initialization and the terminal evaluator, +keeping the original exact tensor power and accounting for every label. -/ +theorem Layer.install_sequence {k : Val x → Val y → F} {d cap j m : ℕ} + (P : ℕ → Layer F (copies x d) (copies y d)) + (keys : ℕ → Finset (Table F)) (endKeys : Finset (Table F)) + (cost : ℕ → ℕ) (hj : 0 < j) (hu : 3 ≤ cap) + (i : (P 0).State) (scalar : F) + (exactPower : (fun a b => scalar * ((P 0).graph i).eval a b) = power k d) + (step : ∀ l < j, Transforms F cap (keys l) (P l).snapshot (P (l + 1)).snapshot (cost l)) + (finish : Finishes F cap endKeys (P j).snapshot m) : + ∃ I : Installation k d, I.u = cap ∧ + I.labels = (range j).biUnion keys ∪ endKeys ∧ + I.labels.card ≤ (∑ l ∈ range j, (keys l).card) + endKeys.card ∧ + I.cost ≤ 140 * ((P 0).snapshot.port.width + d * (wd x + wd y)) + + (∑ l ∈ range j, cost l) + m + 1 := by + classical + let L := (range j).biUnion keys ∪ endKeys + have run := (Transforms.sequence (fun l => (P l).snapshot) keys cost hj step).widen le_rfl + (show (↑((range j).biUnion keys) : Set (Table F)) ⊆ ↑L from fun t ht => mem_union_left _ ht) + have stop := finish.widen (v := cap) (T := (↑L : Set (Table F))) le_rfl + (fun t ht => mem_union_right _ ht) + obtain ⟨I, hL, hU, hcost⟩ := (P 0).installation (P j) i scalar exactPower hu run stop + refine ⟨I, hU, hL, ?_, hcost⟩ + rw [hL] + exact (card_union_le _ _).trans (Nat.add_le_add_right card_biUnion_le _) + +end Rounds +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- +# Iteration of bounded round constructions + +Each step may choose the next representation and its tables from the +current representation. This packages those choices into one +installation, with the cost and vocabulary bounded by the given sums. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer + +open Assembly Finset + +variable {F : Type} [Field F] {x y : Wire} + +open scoped Classical in +private theorem choose_rounds {cap j : ℕ} (P : Layer F x y) + (good : ℕ → Layer F x y → Prop) (start : good 0 P) + (cost limit : ℕ → ℕ) + (next : ∀ i < j, ∀ Q : Layer F x y, good i Q → + ∃ (R : Layer F x y) (L : Finset (Table F)), good (i + 1) R ∧ L.card ≤ limit i ∧ + Transforms F cap L Q.snapshot R.snapshot (cost i)) : + ∃ (R : ℕ → Layer F x y) (keys : ℕ → Finset (Table F)), R 0 = P ∧ + (∀ i ≤ j, good i (R i)) ∧ + ∀ i < j, (keys i).card ≤ limit i ∧ + Transforms F cap (keys i) (R i).snapshot (R (i + 1)).snapshot (cost i) := by + induction j with + | zero => + exact ⟨fun _ => P, fun _ => ∅, rfl, fun i hi => (Nat.eq_zero_of_le_zero hi) ▸ start, + fun i hi => by omega⟩ + | succ j ih => + obtain ⟨R, keys, hzero, hgood, hstep⟩ := ih (fun i hi => next i (Nat.lt_succ_of_lt hi)) + obtain ⟨Q, L, hQ, hL, step⟩ := next j (Nat.lt_succ_self _) (R j) (hgood j le_rfl) + refine ⟨Function.update R (j + 1) Q, Function.update keys j L, ?_, ?_, ?_⟩ + · simpa using hzero + · intro i hi + by_cases he : i = j + 1 + · subst i + simpa using hQ + · rw [Function.update_of_ne he] + exact hgood i (by omega) + · intro i hi + by_cases he : i = j + · subst i + simpa [Function.update_of_ne (show j ≠ j + 1 by omega)] using And.intro hL step + · rw [Function.update_of_ne he, Function.update_of_ne (show i ≠ j + 1 by omega), + Function.update_of_ne (show i + 1 ≠ j + 1 by omega)] + exact hstep i (by omega) + +open scoped Classical in +theorem install_rounds {a b : Wire} {k : Val a → Val b → F} {d cap j : ℕ} + (P : Layer F (copies a d) (copies b d)) (good : ℕ → Layer F (copies a d) (copies b d) → Prop) + (start : good 0 P) (hj : 0 < j) (hcap : 3 ≤ cap) + (state : P.State) (z : F) + (exactPower : (fun x y => z * (P.graph state).eval x y) = power k d) + (cost limit : ℕ → ℕ) + (next : ∀ i < j, ∀ Q : Layer F (copies a d) (copies b d), good i Q → + ∃ (R : Layer F (copies a d) (copies b d)) (L : Finset (Table F)), + good (i + 1) R ∧ L.card ≤ limit i ∧ Transforms F cap L Q.snapshot R.snapshot (cost i)) + (endCost endLimit : ℕ) + (terminal : ∀ Q : Layer F (copies a d) (copies b d), good j Q → + ∃ L : Finset (Table F), L.card ≤ endLimit ∧ Finishes F cap L Q.snapshot endCost) : + ∃ I : Installation k d, I.u = cap ∧ + I.labels.card ≤ (∑ i ∈ range j, limit i) + endLimit ∧ + I.cost ≤ 140 * (P.snapshot.port.width + d * (wd a + wd b)) + + (∑ i ∈ range j, cost i) + endCost + 1 := by + classical + obtain ⟨R, keys, hzero, hgood, hstep⟩ := choose_rounds P good start cost limit next + obtain ⟨L, hL, finish⟩ := terminal (R j) (hgood j le_rfl) + have hin : ∃ state : (R 0).State, (fun x y => z * ((R 0).graph state).eval x y) = power k d := by + rw [hzero] + exact ⟨state, exactPower⟩ + obtain ⟨i, hi⟩ := hin + obtain ⟨I, hu, _, hk, hc⟩ := Layer.install_sequence R keys L cost hj hcap i z hi + (fun l hl => (hstep l hl).2) finish + refine ⟨I, hu, hk.trans (Nat.add_le_add ?_ hL), ?_⟩ + · exact sum_le_sum (fun l hl => (hstep l (mem_range.mp hl)).1) + · simpa only [hzero] using hc + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- +# Separating the cost of addresses, controls and payloads + +The long-address cost is charged per host. Retaining enough blocks at +the end pays for this cost from the occurrence budget. Short records +may use a fixed power of the grouping size, with a polylogarithmic +factor. The exponent on the terminal payload and the exterior can be +arbitrarily small. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Filter +variable {δ : ℝ} {p : Design δ} {R : ℕ} + +/-- Raw cost before absorbing fixed constants and logarithmic factors. -/ +def Levels.expense (v : Levels p R) (h : ℝ) (m e q : ℕ) : ℝ := + ((p.overhead ^ v.j * v.allocation m : ℕ) : ℝ) * + ((2 : ℝ) ^ (q * v.group) + h ^ R / (2 : ℝ) ^ v.remaining) + + v.finalBudget m + (v.batch * e : ℕ) + +theorem Levels.expense_le {v : Levels p R} {n T₀ m e q : ℕ} {a b ξ : ℝ} + (ha : 0 ≤ a) (ok : v.Suits n T₀ a b ξ) : + let h : ℝ := Nat.clog 2 n + v.expense h m e q ≤ ((2 : ℝ) ^ (2 * p.groupRate * q) + 1) * v.work m e h a (p.groupRate * q) + := by + let h : ℝ := Nat.clog 2 n + let A : ℝ := (2 : ℝ) ^ (2 * p.groupRate * q) + 1 + have hpos : 0 < h := zero_lt_one.trans ok.2.1 + have hh : 1 ≤ h := ok.2.1.le + have hA : 1 ≤ A := le_add_of_nonneg_left (by positivity : 0 ≤ (2 : ℝ) ^ (2 * p.groupRate * q)) + have hheight : h ≤ (2 : ℝ) ^ v.height := ok.2.2.1 + have hgroup : (2 : ℝ) ^ v.group ≤ 2 ^ (2 * p.groupRate) * h ^ (p.groupRate * a) := by + rcases ok with ⟨_, _, _, _, _, _, _, _, _, _, _, hg, _⟩ + exact hg + have long : h ^ R / (2 : ℝ) ^ v.remaining ≤ 1 := by + apply (div_le_one (by positivity)).2 + unfold Levels.remaining + rw [mul_comm R, pow_mul] + exact pow_le_pow_left₀ hpos.le hheight _ + have short : (2 : ℝ) ^ (q * v.group) ≤ (2 : ℝ) ^ (2 * p.groupRate * q) * h ^ ((p.groupRate * q : + ℕ) * a) := calc + _ = ((2 : ℝ) ^ v.group) ^ q := by rw [mul_comm, pow_mul] + _ ≤ ((2 : ℝ) ^ (2 * p.groupRate) * h ^ (p.groupRate * a)) ^ q := + pow_le_pow_left₀ (by positivity) hgroup _ + _ = _ := by + rw [mul_pow, ← pow_mul, ← Real.rpow_mul_natCast hpos.le] + congr 1 + push_cast + ring_nf + have scale : 1 ≤ h ^ ((p.groupRate * q : ℕ) * a) := Real.one_le_rpow hh (by positivity) + have controls : (2 : ℝ) ^ (q * v.group) + h ^ R / (2 : ℝ) ^ v.remaining + ≤ A * h ^ ((p.groupRate * q : ℕ) * a) := by + unfold A + rw [add_mul, one_mul] + exact add_le_add short (long.trans scale) + let N : ℝ := ((p.overhead ^ v.j * v.allocation m : ℕ) : ℝ) + have hctrl : + N * ((2 : ℝ) ^ (q * v.group) + h ^ R / (2 : ℝ) ^ v.remaining) ≤ + A * (N * h ^ ((p.groupRate * q : ℕ) * a)) := + (mul_le_mul_of_nonneg_left controls (by unfold N; positivity)).trans_eq (by ring) + change N * _ + v.finalBudget m + (v.batch * e : ℕ) ≤ + A * (N * h ^ ((p.groupRate * q : ℕ) * a) + v.finalBudget m + (v.batch * e : ℕ)) + have hfinal : 0 ≤ v.finalBudget m := by unfold Levels.finalBudget; positivity + calc + _ ≤ A * (N * h ^ ((p.groupRate * q : ℕ) * a)) + A * v.finalBudget m + A * (v.batch * e : ℕ) := + add_le_add (add_le_add hctrl (le_mul_of_one_le_left hfinal hA)) + (le_mul_of_one_le_left (by positivity) hA) + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- +# Absorbing the implementation overhead + +The logarithmic slack pays for fixed factors and powers of the logarithm +of the height. The vocabulary budget accommodates any fixed polynomial +in the height. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Filter + +theorem dictionary_dominates (C s : ℕ) : + ∀ᶠ n : ℕ in atTop, C * (Nat.clog 2 n) ^ s ≤ Shaving.dictionary n := by + let S := C + s + 1 + have hS := Shaving.tendsto_height.eventually_ge_atTop ((2 : ℕ) ^ S : ℝ) + filter_upwards [hS] with n hn + let h := Nat.clog 2 n + let t := Nat.clog 2 h + have hh : h ≤ 2 ^ t := Nat.le_pow_clog (by decide : 1 < 2) _ + have ht : S ≤ t := by + apply (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp + exact (show (2 : ℕ) ^ S ≤ h by exact_mod_cast hn).trans hh + have hC : C ≤ (2 : ℕ) ^ t := by + exact (show C ≤ S by unfold S; omega).trans (ht.trans Nat.lt_two_pow_self.le) + calc + _ ≤ (2 : ℕ) ^ t * ((2 : ℕ) ^ t) ^ s := Nat.mul_le_mul hC (Nat.pow_le_pow_left hh _) + _ = (2 : ℕ) ^ (t * (s + 1)) := by rw [pow_mul, pow_succ'] + _ ≤ _ := by + apply Nat.pow_le_pow_right (by decide) + change t * (s + 1) ≤ t ^ 2 + rw [pow_two] + exact Nat.mul_le_mul_left _ (by unfold S at ht; omega) + +variable {δ : ℝ} {p : Design δ} {R T₀ : ℕ} +theorem Levels.installed_of_expense {a b ξ : ℝ} (ha : 0 < a) (hδ : 0 < δ) + (C : ℝ) (r q B s : ℕ) : + ∀ᶠ n : ℕ in atTop, ∀ (v : Levels p R) (m : ℕ), + v.Suits n T₀ a b ξ → + ∀ (K : Type) [Field K] (x y : Wire) (k : Val x → Val y → K), + let h : ℝ := Nat.clog 2 n + let σ := a * δ / 12 + ∀ I : Installation k v.batch, + I.labels.card ≤ B * (Nat.clog 2 n) ^ s → + (I.cost : ℝ) ≤ |C| *(Real.log h) ^ r * h ^ σ * v.expense h m (wd x + wd y) q → + (I.u : ℝ) ≤ |C| *(Real.log h) ^ r * h ^ σ * (p.D * (v.finalWidth : ℝ)) → + v.Installed n m (p.groupRate * q) a k := by + let A : ℝ := (2 : ℝ) ^ (2 * p.groupRate * q) + 1 + let σ := a * δ / 12 + have hσ : 0 < σ := by unfold σ; positivity + have ht := Shaving.tendsto_height + filter_upwards [dictionary_dominates B s, + ht.eventually (Shaving.polylog_le (|C| *A) r hσ), + ht.eventually (Shaving.polylog_le |C| r hσ)] with n hd hc hu v m hv K _ x y k + dsimp only + intro I hb hcost harity + let h : ℝ := Nat.clog 2 n + let e := wd x + wd y + have hh : 1 < h := hv.2.1 + have hpos : 0 < h := zero_lt_one.trans hh + have hlog := (Real.log_pos hh).le + have hwork : 0 ≤ v.work m e h a (p.groupRate * q) := by + unfold Levels.work Levels.finalBudget + positivity + have hw : 0 ≤ (p.D : ℝ) * v.finalWidth := by positivity + have he := v.expense_le (q:=q) (m:=m) (e:=e) ha.le hv + change v.expense h m e q ≤ A * _ at he + have hsc : h ^ σ * h ^ σ = h ^ (a * δ / 6) := by + rw [← Real.rpow_add hpos] + congr 1 + unfold σ + ring + refine ⟨I, hb.trans hd, ?_, ?_⟩ + · calc + _ ≤ _ := hcost + _ ≤ |C| *(Real.log h) ^ r * h ^ σ * (A * v.work m e h a (p.groupRate * q)) := + mul_le_mul_of_nonneg_left he (by positivity) + _ = ((|C| *A) * (Real.log h) ^ r) * h ^ σ * v.work m e h a (p.groupRate * q) := by ring + _ ≤ h ^ σ * h ^ σ * v.work m e h a (p.groupRate * q) := + mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right hc (by positivity)) hwork + _ = _ := by rw [hsc] + · calc + _ ≤ _ := harity + _ ≤ h ^ σ * h ^ σ * (p.D * (v.finalWidth : ℝ)) := + mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right hu (by positivity)) hw + _ = _ := by rw [hsc] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # The overhead of summing the rounds -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Filter +variable {δ : ℝ} {p : Design δ} {R n T₀ : ℕ} {a b ξ : ℝ} {v : Levels p R} + +theorem Levels.Suits.rounds_pow (ok : v.Suits n T₀ a b ξ) (ha : a ≤ 1) : + 2 ^ v.j ≤ (Nat.clog 2 n) ^ 2 := by + let h : ℝ := Nat.clog 2 n + have hh : 1 ≤ h := ok.2.1.le + have hD : 1 ≤ (p.D : ℝ) := by have := p.large; exact_mod_cast (show 1 ≤ p.D by omega) + obtain ⟨_, _, _, _, _, _, _, _, hw, _, _, _, _⟩ := ok + have hj : (2 : ℝ) ^ v.j ≤ h ^ 2 := calc + _ ≤ (2 : ℝ) ^ (p.gain * v.j) := pow_le_pow_right₀ (by norm_num) + (Nat.le_mul_of_pos_left _ p.gain_pos) + _ ≤ (p.D : ℝ) * (2 : ℝ) ^ (p.gain * v.j) := le_mul_of_one_le_left (by positivity) hD + _ ≤ h ^ (2 * a) := hw + _ ≤ h ^ (2 : ℝ) := Real.rpow_le_rpow_of_exponent_le hh (by linarith) + _ = _ := Real.rpow_two h + unfold h at hj + exact_mod_cast hj + +theorem Levels.Suits.rounds_log (ok : v.Suits n T₀ a b ξ) (ha : a ≤ 1) : + (v.j : ℝ) ≤ 2 / (Real.log 2) * Real.log (Nat.clog 2 n) := by + have hp : (2 : ℝ) ^ v.j ≤ (Nat.clog 2 n : ℝ) ^ 2 := by exact_mod_cast ok.rounds_pow ha + have hl := Real.log_le_log (by positivity) hp + rw [Real.log_pow, Real.log_pow, Nat.cast_ofNat] at hl + have hlog : 0 < Real.log 2 := Real.log_pos (by norm_num) + rw [div_mul_eq_mul_div, le_div_iff₀ hlog] + exact hl + +/-- The total cost allows one estimate per round and two more for the +initial and terminal stages. The vocabulary counts include the terminal +evaluator. All eventual bounds are uniform in the working field. -/ +theorem Levels.installed_of_round_budget (ha : 0 < a) (ha' : a ≤ 1) (hδ : 0 < δ) + (C : ℝ) (r q B s : ℕ) : + ∀ᶠ n : ℕ in atTop, ∀ (v : Levels p R) (m : ℕ), + v.Suits n T₀ a b ξ → + ∀ (K : Type) [Field K] (x y : Wire) (k : Val x → Val y → K), + let h : ℝ := Nat.clog 2 n + let σ := a * δ / 12 + ∀ I : Installation k v.batch, + I.labels.card ≤ (v.j + 1) * (B * (Nat.clog 2 n) ^ s) → + (I.cost : ℝ) ≤ (v.j + 2) * (|C| * (Real.log h) ^ r * h ^ σ * v.expense h m (wd x + + wd y) q) → + (I.u : ℝ) ≤ (v.j + 2) * (|C| * (Real.log h) ^ r * h ^ σ * (p.D * (v.finalWidth : ℝ))) → + v.Installed n m (p.groupRate * q) a k := by + let J : ℝ := 2 / (Real.log 2) + 2 + have hlog : 0 < Real.log 2 := Real.log_pos (by norm_num) + have hJ : 0 ≤ J := by unfold J; positivity + have h := (Real.tendsto_log_atTop.comp Shaving.tendsto_height).eventually_ge_atTop 1 + filter_upwards [h, Levels.installed_of_expense (p:=p) (R:=R) (T₀:=T₀) + (b:=b) (ξ:=ξ) ha hδ (J*|C|) (r + 1) q B (s + 2)] with n hn go v m ok K _ x y k + dsimp only + intro I keys size arity + let h : ℝ := Nat.clog 2 n + let σ := a * δ / 12 + have hh : 0 < h := zero_lt_one.trans ok.2.1 + change 1 ≤ Real.log h at hn + have hlogh : 0 ≤ Real.log h := zero_le_one.trans hn + have hs : (v.j : ℝ) + 2 ≤ J * Real.log h := by + have ht := ok.rounds_log ha' + have htwo := mul_le_mul_of_nonneg_left hn (by norm_num : (0 : ℝ) ≤ 2) + unfold J + rw [add_mul] + exact add_le_add ht (by simpa only [mul_one] using htwo) + have hcard : (v.j + 1) * (B * (Nat.clog 2 n) ^ s) ≤ B * (Nat.clog 2 n) ^ (s + 2) := calc + _ ≤ (Nat.clog 2 n) ^ 2 * (B * (Nat.clog 2 n) ^ s) := Nat.mul_le_mul_right _ + (Nat.lt_two_pow_self.trans_le (ok.rounds_pow ha')) + _ = _ := by rw [pow_add]; ring + refine go v m ok K x y k I (keys.trans hcard) ?_ ?_ + · have hexp : 0 ≤ v.expense h m (wd x + wd y) q := by + unfold Levels.expense Levels.finalBudget + positivity + calc + _ ≤ _ := size + _ ≤ J * Real.log h * (|C| * (Real.log h) ^ r * h ^ σ * v.expense h m (wd x + wd y) q) := + mul_le_mul_of_nonneg_right hs (by positivity) + _ = _ := by rw [abs_of_nonneg (mul_nonneg hJ (abs_nonneg C)), pow_succ]; ring + · calc + _ ≤ _ := arity + _ ≤ J * Real.log h * (|C| * (Real.log h) ^ r * h ^ σ * (p.D * (v.finalWidth : ℝ))) := + mul_le_mul_of_nonneg_right hs (by positivity) + _ = _ := by rw [abs_of_nonneg (mul_nonneg hJ (abs_nonneg C)), pow_succ]; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Charging phase operations to the shared compression budget -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +variable {δ : ℝ} {p : Design δ} {R : ℕ} (v : Levels p R) + +/-- Keeping at least the prescribed number of blocks pays for long +addresses out of a budget on occurrences. -/ +theorem Levels.host_budget {m addr blocks : ℕ} + (remain : v.remaining ≤ blocks) + (seats : 2 ^ (addr + blocks) ≤ p.overhead ^ v.j * v.allocation m) : + (2 : ℝ) ^ addr ≤ ((p.overhead ^ v.j * v.allocation m : ℕ) : ℝ) / (2 : ℝ) ^ v.remaining := by + apply (le_div_iff₀ (by positivity)).mpr + rw [← pow_add] + exact_mod_cast (Nat.pow_le_pow_right (by decide : 0 < 2) + (Nat.add_le_add_left remain addr)).trans seats + +/-- A phase may use a separate layout for long addresses, for short +records at each occurrence, and for the full exposed payload. -/ +theorem Levels.phase_expense {h W : ℝ} {m e q addr blocks long short ext cost : ℕ} + (hh : 0 ≤ h) (hW : 0 ≤ W) (remain : v.remaining ≤ blocks) + (seats : 2 ^ (addr + blocks) ≤ p.overhead ^ v.j * v.allocation m) + (size : cost ≤ 2 ^ addr * long + 2 ^ (addr + blocks) * short + v.batch * e * ext) + (hc₁ : (long : ℝ) ≤ W * h ^ R) (hc₂ : (short : ℝ) ≤ W * (2 : ℝ) ^ (q * v.group)) + (hc₃ : (ext : ℝ) ≤ W) : + (cost : ℝ) ≤ W * v.expense h m e q := by + let N : ℝ := ((p.overhead ^ v.j * v.allocation m : ℕ) : ℝ) + have ht : 0 ≤ h ^ R := by positivity + have a : (2 : ℝ) ^ addr * (long : ℝ) ≤ W * (N * (h ^ R / (2 : ℝ) ^ v.remaining)) := calc + _ ≤ (N / (2 : ℝ) ^ v.remaining) * (W * h ^ R) := + mul_le_mul (v.host_budget remain seats) hc₁ (by positivity) (by positivity) + _ = _ := by ring + have b : (2 : ℝ) ^ (addr + blocks) * (short : ℝ) ≤ W * (N * (2 : ℝ) ^ (q * v.group)) := calc + _ ≤ N * (W * (2 : ℝ) ^ (q * v.group)) := + mul_le_mul (by dsimp only [N]; exact_mod_cast seats) hc₂ (by positivity) (by positivity) + _ = _ := by ring + have c : ((v.batch * e : ℕ) : ℝ) * (ext : ℝ) ≤ W * ((v.batch * e : ℕ) : ℝ) := + (mul_le_mul_of_nonneg_left hc₃ (by positivity)).trans_eq (mul_comm _ _) + have hfin : 0 ≤ v.finalBudget m := by unfold Levels.finalBudget; positivity + calc + _ ≤ (2 : ℝ) ^ addr * (long : ℝ) + (2 : ℝ) ^ (addr + blocks) * (short : ℝ) + + ((v.batch * e : ℕ) : ℝ) * (ext : ℝ) := by + exact_mod_cast size + _ ≤ W * (N * (h ^ R / (2 : ℝ) ^ v.remaining)) + W * (N * (2 : ℝ) ^ (q * v.group)) + + W * ((v.batch * e : ℕ) : ℝ) := add_le_add (add_le_add a b) c + _ ≤ W * v.expense h m e q := by + change _ ≤ W * (N * ((2 : ℝ) ^ (q * v.group) + h ^ R / (2 : ℝ) ^ v.remaining) + + v.finalBudget m + ((v.batch * e : ℕ) : ℝ)) + nlinarith only [mul_nonneg hW hfin] + +/-- The terminal evaluator uses the final charge of the live graph and +the exposed bits. Control and wiring costs can also use the phase budget. -/ +theorem Levels.terminal_expense {h W : ℝ} {m e q cost : ℕ} + (hh : 0 ≤ h) (hW : 0 ≤ W) + (size : (cost : ℝ) ≤ W * (v.finalBudget m + (v.batch * e : ℕ))) : + (cost : ℝ) ≤ W * v.expense h m e q := by + apply size.trans + apply mul_le_mul_of_nonneg_left _ hW + unfold Levels.expense + have hp : 0 ≤ ((p.overhead ^ v.j * v.allocation m : ℕ) : ℝ) * + ((2 : ℝ) ^ (q * v.group) + h ^ R / (2 : ℝ) ^ v.remaining) := by positivity + linarith only [hp] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Installing a sequence with a uniform per-stage cost -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer + +open Assembly Finset + +variable {F : Type} [Field F] {x y : Wire} + +theorem install_with_bounds {k : Val x → Val y → F} {d cap j labelLimit : ℕ} + (P : Layer F (copies x d) (copies y d)) + (good : ℕ → Layer F (copies x d) (copies y d) → Prop) + (start : good 0 P) (hj : 0 < j) (hcap : 3 ≤ cap) + (state : P.State) (z : F) + (exactPower : (fun a b => z * (P.graph state).eval a b) = power k d) + (budget : ℝ) (hb : 0 ≤ budget) + (startCost : ((140 * (P.snapshot.port.width + d * (wd x + wd y)) + 1 : ℕ) : ℝ) ≤ budget) + (next : ∀ i < j, ∀ Q : Layer F (copies x d) (copies y d), good i Q → + ∃ (R : Layer F (copies x d) (copies y d)) (L : Finset (Table F)) (u m : ℕ), + good (i + 1) R ∧ L.card ≤ labelLimit ∧ u ≤ cap ∧ (m : ℝ) ≤ budget ∧ + Transforms F u L Q.snapshot R.snapshot m) + (terminal : ∀ Q : Layer F (copies x d) (copies y d), good j Q → + ∃ (L : Finset (Table F)) (u m : ℕ), + L.card ≤ labelLimit ∧ u ≤ cap ∧ (m : ℝ) ≤ budget ∧ Finishes F u L Q.snapshot m) : + ∃ I : Installation k d, I.u = cap ∧ I.labels.card ≤ (j + 1) * labelLimit ∧ + (I.cost : ℝ) ≤ (j + 2) * budget := by + let w := ⌊budget⌋₊ + have next' i (hi : i < j) Q (hQ : good i Q) : + ∃ (R : Layer F (copies x d) (copies y d)) (L : Finset (Table F)), + good (i + 1) R ∧ L.card ≤ labelLimit ∧ Transforms F cap L Q.snapshot R.snapshot w := by + obtain ⟨R, L, u, m, hr, hl, hu, hm, ht⟩ := next i hi Q hQ + exact ⟨R, L, hr, hl, (ht.mono (Nat.le_floor hm)).widen hu Set.Subset.rfl⟩ + have terminal' Q (hQ : good j Q) : + ∃ L : Finset (Table F), L.card ≤ labelLimit ∧ Finishes F cap L Q.snapshot w := by + obtain ⟨L, u, m, hl, hu, hm, ht⟩ := terminal Q hQ + obtain ⟨f, hf, he⟩ := ht.widen hu Set.Subset.rfl + exact ⟨L, hl, f, hf.mono (Nat.le_floor hm), he⟩ + obtain ⟨I, hi, hl, hcost⟩ := install_rounds P good start hj hcap state z exactPower + (fun _ => w) (fun _ => labelLimit) next' w labelLimit terminal' + simp only [sum_const, card_range, nsmul_eq_mul] at hl hcost + change I.labels.card ≤ j * labelLimit + labelLimit at hl + change I.cost ≤ _ + j * w + w + 1 at hcost + refine ⟨I, hi, hl.trans_eq (by rw [add_mul, one_mul]), ?_⟩ + have hf : (w : ℝ) ≤ budget := Nat.floor_le hb + have hprod := mul_le_mul_of_nonneg_left hf (show (0 : ℝ) ≤ j by positivity) + have hc : (I.cost : ℝ) ≤ (140 : ℝ) * (P.snapshot.port.width + d * (wd x + wd y)) + + (j : ℝ) * w + w + 1 := by exact_mod_cast hcost + push_cast at startCost + nlinarith only [hc, startCost, hf, hprod] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # Removing scalar-only entries from presented boards -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly + +variable {F : Type} [Field F] {x y : Wire} + +/-- Uses `{ B with diagram := B.diagram.sweep }` as the representation. -/ +abbrev Rounds.Board.sweep {h : ℕ} (B : Rounds.Board F x y h) : Rounds.Board F x y h := + { B with diagram := B.diagram.sweep } + +namespace Assembly.Template.Presents +variable {D : Template F} {r : D.format.obj} {B : Rounds.Board F x y D.scheme.h} (p : D.Presents r + B) + +/-- Builds `D.sweep.Presents r B.sweep where pres` with the specified `pres`, `host`, `vertex`, +`directed`. -/ +def sweep : D.sweep.Presents r B.sweep where + pres := p.pres.sweep + host := p.host + vertex := p.vertex + directed t := by + change D.scheme.direction r.1 (p.pres.sweepSeats.ends t).1 = t.isRight + rw [p.pres.sweep_end] + exact p.directed t + live := p.live + closed := p.closed + reciprocal := p.reciprocal + edge := p.edge + core := p.core + load := p.load + +/-- Presentation of a single board, with a separate initial scalar. -/ +abbrev singleton {t : ℕ} (bound : ∀ v, B.diagram.arity v ≤ 2 ^ t) : Rounds.Layer F x y where + template := D.sweep + volume := 2 ^ D.scheme.m + wd x + wd y + height := D.scheme.h + t + State := PUnit.{2} + board _ := B.sweep + data _ := r + presents _ := p.sweep + fits _ := p.fits bound + +end Assembly.Template.Presents +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- # A terminal circuit for a ready layer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Contraction + +variable {F : Type} [Field F] {a b : Wire} (Q : Layer F a b) (W : Prices F) + (V t w : ℕ) +local notation "S" => Q.template.scheme +local notation "J" => + Terminal.instruction Q.template.scheme V t (Q.template.scheme.d + 1) w Q.template.scheme.spanRows +local notation "Y" => Q.encoding.payload + +open scoped Classical in +/-- The bound obtained by adding the component charges `4 * (Q.template.format.width + 2 * +(S).format.width) + c + 4 * (Y).width + Terminal.price W (S) V t Q.volume Q.height ((S).d + +1) w (S).spanRows`. -/ +def finishCost (c : ℕ) := + 4 * (Q.template.format.width + 2 * (S).format.width) + c + 4 * (Y).width + + Terminal.price W (S) V t Q.volume Q.height ((S).d + 1) w (S).spanRows + +open scoped Classical in +theorem finish {u c : ℕ} {K : Set (Table F)} + (hu : 3 ≤ u) (hm : 1 ≤ (S).m) + (ht : 2 ^ ((S).d + 1) * ((max (Terminal.height (S) t) Q.height + 1) * (2 ^ (S).m + 2 ^ (S).m)) + < 2 ^ W.w) + (size : Terminal.Dictionary.arity (S) t ≤ u) (label : Terminal.Dictionary.label (S) t ∈ K) + (ok : ∀ i, Terminal.Fits (S) (Q.data i).1 V t ∧ Terminal.Neutral (S) (Q.data i).1) + (hw : Terminal.height (S) t < w) (hk : Q.height < w) + (generate : Map F u K (S).format J (Terminal.orders (S) V t w) c) : + Finishes F u K Q.snapshot (Q.finishCost W V t w c) := by + have read : Circuit F Q.template.format (S).format Prod.fst + (Q.template.format.width + 2 * (S).format.width) := Circuit.project Sum.inl (fun _ _ => rfl) + have start := ((Map.circuit (L := K) hu read).comp generate).par + (Map.circuit (L := K) hu (Circuit.id F Y)) + have stop := Terminal.evaluate (S) V t Q.volume Q.height ((S).d + + 1) w (S).spanRows W hu hm ht size label + let f (z : Q.encoding.port.obj) := + Terminal.value (S) V t Q.volume Q.height ((S).d + 1) w (S).spanRows + (Terminal.orders (S) V t w z.1.1) z.2 + have go : Kernel F u K Q.encoding.port (.wire .unit) (fun z _ => f z) (Q.finishCost W V t w c) := + start.then_kernel stop + refine Q.encoding.finishes go fun i x => ?_ + exact Terminal.value_orders (ok i).1 (Q.fits i) (Q.presents i).pres.proper (Q.presents + i).reciprocal + (ok i).2 hw hk x + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- +# Uniform termination of a layer + +One choice of the three labels serves every summand of the layer. +All hidden assignments are summed inside the same network. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Contraction + +theorem terminal : ∃ K : ℕ, ∀ (F : Type) [Field F] (x y : Wire) (Q : Layer F x y) + (W : Prices F) (V t : ℕ), + let i := Terminal.Rates.Size.mk F Q.template.scheme W V t Q.volume Q.height + 1 ≤ i.S.m → 2 ^ i.p * (i.w * (2 ^ i.S.m + 2 ^ i.S.m)) < 2 ^ W.w → + (∀ j, Terminal.Fits i.S (Q.data j).1 V t ∧ Terminal.Neutral i.S (Q.data j).1) → + ∀ (u : ℕ) (L : Set (Table F)), 3 ≤ u → Terminal.arity i.S t i.w ≤ u → + (↑(Terminal.labels i.S t i.w) : Set (Table F)) ⊆ L → + Finishes F u L Q.snapshot (4 * Q.snapshot.port.width + i.bound K) := by + classical + obtain ⟨K, hK⟩ := Terminal.Rates.terminal + refine ⟨K, ?_⟩ + intro F _ x y Q W V t i hm hw ok u L hu ha hl + have room : i.S.m ≤ W.w := by + apply (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp + refine (Nat.le_add_right _ (2 ^ i.S.m)).trans ?_ + exact ((Nat.le_mul_of_pos_left _ (Nat.succ_pos _)).trans + (Nat.le_mul_of_pos_left _ (Nat.two_pow_pos _))).trans hw.le + have size : Terminal.Dictionary.arity i.S t ≤ u := by unfold Terminal.arity at ha; omega + have label : Terminal.Dictionary.label i.S t ∈ L := hl (by simp [Terminal.labels]) + have build := Terminal.generate i hm room hu ha hl + obtain ⟨f, hf, he⟩ := Q.finish W V t i.w hu hm hw size label ok + (Nat.lt_succ_of_le (le_max_left ..)) (Nat.lt_succ_of_le (le_max_right ..)) build + refine ⟨f, hf.mono ?_, he⟩ + have b : 8 * i.S.format.width + Terminal.orderCost i + i.price ≤ i.bound K := hK i + change 4 * (Q.template.format.width + 2 * i.S.format.width) + Terminal.orderCost i+ + 4 * Q.encoding.payload.width + i.price ≤ 4 * (Q.template.format.pair Q.encoding.payload).width + + i.bound K + rw [Format.width_pair Q.template.format Q.encoding.payload] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Algorithm/Computability.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Algorithm/Computability.lean new file mode 100644 index 0000000000..add6d6350f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Algorithm/Computability.lean @@ -0,0 +1,307 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Shift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Formula +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Decor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryControl +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.System + +/-! # Numeric budgets and finite tests for local routing -/ + +@[expose] public section + +section +/- # Bounds for near-linear word programs -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Algorithm + +theorem budget_mono (h w : ℕ) {c d : ℕ} (hc : c ≤ d) : + 2 ^ h * (100 + w) ^ c ≤ 2 ^ h * (100 + w) ^ d := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) hc) + +theorem budget_step (h w c : ℕ) : + 100 * (2 ^ h * (100 + w) ^ c) ≤ 2 ^ h * (100 + w) ^ (c + 1) := by + rw [pow_succ, ← mul_assoc (2 ^ h), mul_comm 100] + exact Nat.mul_le_mul_left _ (by omega) + +theorem budget_base (h w c : ℕ) : 2 ^ h ≤ 2 ^ h * (100 + w) ^ c := by + simpa using budget_mono h w (Nat.zero_le c) + +theorem budget_width (h c : ℕ) : + 2 ^ h * (100 + (3 * h + 10)) ^ c ≤ 2 ^ h * (100 + h) ^ (2 * c) := by + rw [pow_mul] + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by ring_nf; omega) _) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Algorithm +end + +/- +# Compiling local observations + +The list of group elements and the table on their coincidences are +fixed before the height or the permutation is given. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Root +open Coloring + +private theorem Local.table {G : Type} [Group G] {q : ℕ} {f : Root G → B q} (hf : Local f) : + ∃ (t : ℕ) (g : B t → G) (b : (B t → B t → Bool) → B q), + ∀ r, b (fun i j => r.see (g i) (g j)) = f r := by + classical + obtain ⟨E, hE⟩ := hf + let e := encode ↥E + let g := Function.extend e (fun i : ↥E => i.val) (fun _ => 1) + have hg (x : G) (hx : x ∈ E) : g (e ⟨x, hx⟩) = x := + e.injective.extend_apply _ _ _ + let obs (r : Root G) i j := r.see (g i) (g j) + have same (r s : Root G) (he : obs r = obs s) : f r = f s := by + apply hE + intro i hi j hj + simpa only [obs, hg] using congrFun (congrFun he (e ⟨i, hi⟩)) (e ⟨j, hj⟩) + let b z := if h : ∃ r, obs r = z then f h.choose else 0 + refine ⟨_, g, b, fun r => ?_⟩ + have ex : ∃ s, obs s = obs r := ⟨r, rfl⟩ + change b (obs r) = _ + simp only [b, dite_eq_left ex] + exact same _ _ ex.choose_spec + +theorem Local.compile {F : Type} [Field F] {m q : ℕ} {T : Routes F m} + {V : Type*} {f : Root (controllers F T.embed) → V} (hf : Local f) (e : V ↪ B q) : + ∃ c k₀ : ℕ, ∀ h ≥ k₀, ∃ v, + Cheap F (h + 1) (h + 1) (Perm h) (.vec (h + 1) (.addr q)) v c ∧ + ∀ π : Equiv.Perm (B h), ∀ i, v π i = e (f (@Root.mk _ _ (B (h + 1)) (T.action h π) i)) := by + obtain ⟨t, g, b, hb⟩ := (hf.map e).table + obtain ⟨c, hc⟩ := T.controllers_net t g + obtain ⟨k, hk⟩ := Cheap.equalityTable F t q + refine ⟨max c 30 + 1, max (2 ^ t) k, fun h hh => ?_⟩ + obtain ⟨v, hv, he⟩ := hc h (by omega) + have net := hv.comp (hk (h + 1) (h + 1) le_rfl (by omega) b) + refine ⟨_, net, fun π i => ?_⟩ + let r := @Root.mk _ _ (B (h + 1)) (T.action h π) i + refine Eq.trans ?_ (hb r) + apply congrArg b + funext j l + rw [Bool.eq_iff_iff] + simp only [see, decide_eq_true_eq, he] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Root +end + +/- +# Compiling local functions of marked sites + +The permutation determines the addresses. Compare them and gather the +marks there before applying the fixed local table. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Decor +open Coloring + +private abbrev pattern (t : ℕ) := B t → B t → Bool + +private abbrev frame (t q : ℕ) := + Format.pair (.addr (Fintype.card (pattern t))) (.vec t (.addr q)) + +private def observe {G : Type} [Group G] {t q : ℕ} (g : B t → G) (r : Decor G q) : + (frame t q).obj := + (encode (pattern t) (fun i j => r.toRoot.see (g i) (g j)), fun i => r.mark (r.toRoot.label (g i))) + +private theorem Local.table {G : Type} [Group G] {q l : ℕ} {V : Type*} {f : Decor G q → V} + (hf : Local f) (enc : V ↪ B l) : + ∃ (t : ℕ) (g : B t → G) (b : (frame t q).obj → B l), + ∀ r, b (observe g r) = enc (f r) := by + classical + obtain ⟨E, hE⟩ := hf + let e := encode ↥E + let g := Function.extend e (fun i : ↥E => i.val) (fun _ => 1) + have hg (x : G) (hx : x ∈ E) : g (e ⟨x, hx⟩) = x := + e.injective.extend_apply _ _ _ + have same (r s : Decor G q) (he : observe g r = observe g s) : f r = f s := by + apply hE + · intro i hi j hj + have hp := (encode _).injective (congrArg Prod.fst he) + simpa only [hg] using congrFun (congrFun hp (e ⟨i, hi⟩)) (e ⟨j, hj⟩) + · intro i hi + simpa only [observe, hg] using congrFun (congrArg Prod.snd he) (e ⟨i, hi⟩) + let b z := if h : ∃ r, observe g r = z then enc (f h.choose) else 0 + refine ⟨_, g, b, fun r => ?_⟩ + have ex : ∃ s, observe g s = observe g r := ⟨r, rfl⟩ + simp only [b, dite_eq_left ex] + exact congrArg enc (same _ _ ex.choose_spec) + +theorem Local.compile {F : Type} [Field F] {m l q : ℕ} {T : Routes F m} + {V : Type*} {f : Decor (controllers F T.embed) q → V} (hf : Local f) (e : V ↪ B l) : + ∃ c k₀ : ℕ, ∀ h ≥ k₀, ∃ v, + Cheap F (h + 1) (h + 1) (.pair (Perm h) (.vec (h + 1) (.addr q))) (.vec (h + + 1) (.addr l)) v c ∧ + ∀ π : Equiv.Perm (B h), ∀ z i, + v (π, z) i = e (f ⟨@Root.mk _ _ (B (h + 1)) (T.action h π) i, z⟩) := by + obtain ⟨t, g, b, hb⟩ := hf.table e + obtain ⟨c, hc⟩ := T.controllers_net t g + obtain ⟨k, hk⟩ := Cheap.equalityTable F t (Fintype.card (pattern t)) + let Y := frame t q + let cost := 2 * Y.width + (Format.addr l).width + + Install.localCost Y.width * (Format.addr l).width + refine ⟨c + 50, 2 ^ t + k + q + cost, fun h hh => ?_⟩ + have ht := Nat.two_pow_pos t + let X := Format.pair (Perm h) (.vec (h + 1) (.addr q)) + have hw : X.width ≤ 2 ^ (h + 1) * (100 + (h + 1)) ^ 2 := by + simp only [X, Format.width_pair, Format.width_vec, Format.width_addr] + have hu := Nat.mul_le_mul_left (2 ^ (h + 1)) (show q ≤ h by omega) + ring_nf at hu ⊢ + omega + have input := Cheap.id F hw + obtain ⟨v, hv, he⟩ := hc h (by omega) + have addr := input.fst.comp hv + have eqs := addr.comp (hk (h + 1) (h + 1) le_rfl (by omega) (encode (pattern t))) + have marks := (input.snd.pair addr).comp (Cheap.neighbors F (.addr q) (h + 1) (h + 1) t + le_rfl (by rw [Format.width_addr]; omega) (by omega)) + have tab : Cheap F 0 (h + 1) Y (.addr l) b 1 := + Cheap.fixed F b (show cost ≤ h + 1 by omega) + have net := (eqs.pair marks).zip.comp (Cheap.map _ (fun _ => tab)) + refine ⟨_, net.mono (by omega), fun π z i => ?_⟩ + let r : Decor (controllers F T.embed) q := ⟨@Root.mk _ _ (B (h + 1)) (T.action h π) i, z⟩ + refine Eq.trans ?_ (hb r) + apply congrArg b + apply Prod.ext + · apply congrArg (encode (pattern t)) + funext j l + rw [Bool.eq_iff_iff] + simp only [Root.see, decide_eq_true_eq, Function.comp_apply, id_eq, he] + rfl + · funext j + exact congrArg z (he π j i) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Decor +end + +section +/- +# Dispatching to an action chosen at each site + +A local decision names a member of a fixed list of actions. To +materialize one address bit the circuit needs only the encoded decision +and the corresponding bit of each candidate address. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Decor +open Coloring + +/-- Indexes the plan by the coordinates of `B l × (B p → Bool × Bool × B k × B p)`. -/ +abbrev Plan (l p k : ℕ) := B l × (B p → Bool × Bool × B k × B p) + +/-- The indexed operation `(x.1, fun j => let t := x.2 j; (t.1, t.2.1, a t.2.2.1, t.2.2.2))`. -/ +def resolve {l p k h : ℕ} (x : Plan l p k) (a : B k → B (h + 1)) : + B l × (B p → (Transport.Command h p).obj) := + (x.1, fun j => let t := x.2 j; (t.1, t.2.1, a t.2.2.1, t.2.2.2)) + +private abbrev Row (h p l : ℕ) := Format.pair (.addr l) (.vec p (Transport.Command h p)) +private abbrev Source (h k s : ℕ) := Format.pair (.vec (h + 1) (.addr s)) (.vec k (Perm (h + 1))) + +variable {l p k h s : ℕ} + +private theorem resolve_bit (z : (Row h p l).pins) : + ∃ d : slots (word (h + 1)), ∀ (x : Plan l p k) (a b : B k → B (h + 1)), + (∀ i, (Format.addr (h + 1)).code (a i) d = (Format.addr (h + 1)).code (b i) d) → + (Row h p l).code (resolve x a) z = (Row h p l).code (resolve x b) z := by + rcases z with z | ⟨j, z | z | z | z⟩ + · exact ⟨.inl (), fun _ _ _ _ => rfl⟩ + · exact ⟨.inl (), fun _ _ _ _ => rfl⟩ + · exact ⟨.inl (), fun _ _ _ _ => rfl⟩ + · exact ⟨z, fun x a b he => he ((x.2 j).2.2.1)⟩ + · exact ⟨.inl (), fun _ _ _ _ => rfl⟩ + +private def select (g : B s → Plan l p k) (x : (Source h k s).obj) : + (Transport.Controls h p (.addr l)).obj := + fun i => resolve (g (x.1 i)) (fun j => x.2 j i) + +private theorem select_depends (g : B s → Plan l p k) : + Install.Depends ((Transport.Controls h p (.addr l)).code ∘ select g ∘ + (Source h k s).code.symm) (s + 2 ^ k) := by + classical + rintro ⟨i, z⟩ + obtain ⟨d, hd⟩ := resolve_bit (k := k) z + let key (u : slots (word s)) : (Source h k s).pins := .inl (i, u) + let val (u : B k) : (Source h k s).pins := .inr (u, i, d) + refine ⟨Finset.univ.image key ∪ Finset.univ.image val, ?_, fun x y he => ?_⟩ + · apply (Finset.card_union_le _ _).trans + have hl := Finset.card_image_le (s := Finset.univ) (f := key) + have hr := Finset.card_image_le (s := Finset.univ) (f := val) + simpa only [Finset.card_univ, card_slots, wd_word, Fintype.card_fin] using Nat.add_le_add hl hr + · let a := (Source h k s).code.symm x + let b := (Source h k s).code.symm y + have hl : a.1 i = b.1 i := by + apply congrArg (Control.decode s) + funext u + exact he (key u) (by simp) + have hr (j : B k) : (Format.addr (h + 1)).code (a.2 j i) d = + (Format.addr (h + 1)).code (b.2 j i) d := by + change (Source h k s).code a (val j) = (Source h k s).code b (val j) + simp only [a, b, Equiv.apply_symm_apply] + exact he (val j) (by simp) + change (Row h p l).code (resolve (g (a.1 i)) (fun j => a.2 j i)) z = + (Row h p l).code (resolve (g (b.1 i)) (fun j => b.2 j i)) z + rw [hl] + exact hd _ _ _ hr + +private theorem cheap_select (F : Type) [Field F] (g : B s → Plan l p k) : + ∃ k₀ : ℕ, ∀ h ≥ k₀, Cheap F (h + 1) (h + 1) (Source h k s) + (Transport.Controls h p (.addr l)) (select g) 5 := by + let C := Install.localCost (s + 2 ^ k) + refine ⟨max s (max l (max p (max (2 ^ k) (max (2 ^ p) C)))), fun h hb => ?_⟩ + simp only [ge_iff_le, max_le_iff] at hb + obtain ⟨hs, hl, hp, hk, hr, hc⟩ := hb + refine ⟨_, (select_depends (h := h) g).bnet F, ?_⟩ + change (Source h k s).width + (Transport.Controls h p (.addr l)).width + + ((Source h k s).width + C * (Transport.Controls h p (.addr l)).width) ≤ _ + simp only [Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit, Format.width_addr (h + 1)] + calc + _ = 2 ^ (h + 1) * (2 * (s + 2 ^ k * (h + 1)) + (C + 1) * (l + 2 ^ p * (2 + (h + 1) + p))) + := by ring + _ ≤ 2 ^ (h + 1) * (2 * (h + h * (h + 1)) + (h + 1) * (h + h * (2 + (h + 1) + h))) := by gcongr + _ ≤ _ := by gcongr; ring_nf; omega + +theorem Local.dispatch {F : Type} [Field F] {m q : ℕ} {T : Routes F m} + {f : Decor (controllers F T.embed) q → Plan l p k} (hf : Local f) + (w : B k → controllers F T.embed) : + ∃ c k₀ : ℕ, ∀ h ≥ k₀, ∃ v, + Cheap F (h + 1) (h + 1) (.pair (Perm h) (.vec (h + + 1) (.addr q))) (Transport.Controls h p (.addr l)) v c ∧ + ∀ π : Equiv.Perm (B h), ∀ z i, + v (π, z) i = resolve (f ⟨@Root.mk _ _ (B (h + 1)) (T.action h π) i, z⟩) + (fun j => (T.action h π).smul (w j) i) := by + let e := encode (Plan l p k) + let g := Function.invFun e + obtain ⟨c, h₀, hl⟩ := hf.compile e + obtain ⟨c', hr⟩ := T.controllers_net k w + obtain ⟨h₁, hs⟩ := cheap_select F g + refine ⟨c + c' + 10, max h₀ (max h₁ (2 ^ k)), fun h hh => ?_⟩ + obtain ⟨u, hu, eu⟩ := hl h (by omega) + obtain ⟨v, hv, ev⟩ := hr h (by omega) + let X := Format.pair (Perm h) (.vec (h + 1) (.addr q)) + have hx : X.width ≤ 2 ^ (h + 1) * (100 + (h + 1)) ^ c := by + obtain ⟨_, _, hw⟩ := hu + exact (Nat.le_add_right _ _).trans ((Nat.le_add_right _ _).trans hw) + have addresses := (Cheap.id F hx).fst.comp hv + have net := (hu.pair addresses).comp (hs h (by omega)) + refine ⟨_, net.mono (by omega), fun π z i => ?_⟩ + change resolve (g (u (π, z) i)) (fun j => v π j i) = _ + rw [eu, show ∀ x, g (e x) = x from Function.leftInverse_invFun e.injective] + exact congrArg _ (funext fun j => ev π j i) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Decor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Compatible.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Compatible.lean new file mode 100644 index 0000000000..252b57333b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Compatible.lean @@ -0,0 +1,877 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Focus +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Rig +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.ReplayRel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Alignment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Replay + +/-! +# Identifying incident charts by finite tokens + +The token stores the chart and the position of the focal site. Its +word, applied in reverse, identifies the center unambiguously. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Protocol (Near) +open scoped Pointwise + +variable {G K J : Type} [Group G] [Field K] {U : J → Subgroup G} {g : G} + +namespace Parameters +variable (p : Parameters K U g) + +open scoped Classical in +/-- Indexes the token by the coordinates of `Σ b : Board p.core p.radius, b.Site`. -/ +abbrev Token := Σ b : Board p.core p.radius, b.Site + +open scoped Classical in +/-- The value specified by `(j.1.word j.2)⁻¹`. -/ +def Token.back (j : p.Token) : G := (j.1.word j.2)⁻¹ + +open scoped Classical in +/-- Computes the boards by the application `Board.choose p.core p.radius p.unit g p.reach x`. -/ +def boards (x : Root G) := Board.choose p.core p.radius p.unit g p.reach x + +open scoped Classical in +/-- Requires `p.boards (x.shift (t.back p)) = t.1`. -/ +def Present (x : Root G) (t : p.Token) : Prop := p.boards (x.shift (t.back p)) = t.1 + +open scoped Classical in +theorem local_present : Root.Local p.Present := + Root.local_pi fun t => ((Board.local_choose _ _ _ _ _).shift (t.back p)).map (· = t.1) + +variable {I : Type} [MulAction G I] {i : I} + +open scoped Classical in +/-- Uses `⟨p.boards ⟨I, j.1⟩, j.2.1⟩` as the representation. -/ +def token (j : Near (p.balls I) i) : p.Token := ⟨p.boards ⟨I, j.1⟩, j.2.1⟩ + +open scoped Classical in +theorem back_eq (j : Near (p.balls I) i) : (p.token j).back p • i = j.1 := by + have h : (p.token j).1.word (p.token j).2 • j.1 = i := j.2.property + exact inv_smul_eq_iff.mpr h.symm + +open scoped Classical in +theorem token_present (j : Near (p.balls I) i) : p.Present ⟨I, i⟩ (p.token j) := by + change p.boards ⟨I, (p.token j).back p • i⟩ = _ + rw [p.back_eq] + rfl + +open scoped Classical in +theorem token_inj : Function.Injective (p.token (i := i)) := by + intro x y h + have hi : x.1 = y.1 := by rw [← p.back_eq x, ← p.back_eq y, h] + rcases x with ⟨x, u⟩ + rcases y with ⟨y, v⟩ + change x = y at hi + subst y + have hv : u = v := Subtype.ext ((p.balls I).name x |>.injective (u.2.trans v.2.symm)) + rw [hv] + +open scoped Classical in +theorem token_hit (x : I) (v : p.Token) + (h : p.boards ⟨I, x⟩ = v.1) (he : v.1.word v.2 • x = i) : + ∃ j : Near (p.balls I) i, p.token j = v := by + rcases v with ⟨s, k⟩ + change p.boards ⟨I, x⟩ = s at h + subst s + exact ⟨⟨x, ⟨k, he⟩⟩, rfl⟩ + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def incident (i : I) : Near (p.balls I) i ≃ {t // p.Present ⟨I, i⟩ t} := + Equiv.ofBijective (fun j => ⟨p.token j, p.token_present j⟩) ⟨ + fun _ _ h => p.token_inj (congrArg Subtype.val h), + fun ⟨t, h⟩ => by + obtain ⟨j, hj⟩ := p.token_hit (t.back p • i) t h (smul_inv_smul _ _) + exact ⟨j, Subtype.ext hj⟩⟩ + +variable {I' : Type} [MulAction G I'] {i' : I'} + (he : p.Present ⟨I, i⟩ = p.Present ⟨I', i'⟩) + +open scoped Classical in +/-- Reindexes `Near (p.balls I) i` and `Near (p.balls I') i'` by an equivalence. -/ +def sameNear : Near (p.balls I) i ≃ Near (p.balls I') i' := + (p.incident i).trans ((Equiv.subtypeEquivRight (fun x => iff_of_eq (congrFun he x))).trans + (p.incident i').symm) + +open scoped Classical in +theorem sameNear_token (x : Near (p.balls I) i) : p.token x = p.token (p.sameNear he x) := by + change _ = ((p.incident i') (p.sameNear he x)).val + rw [sameNear, Equiv.trans_apply, Equiv.trans_apply, Equiv.apply_symm_apply] + rfl + +end Parameters +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Passing from matching local tokens to a global bijection on pins +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {A B X Y : Type} + +private theorem induce_surj (e : A ≃ B) (a : A → X) (b : B → Y) + (ha : Function.Surjective a) (hb : Function.Surjective b) + (he : ∀ i j, a i = a j ↔ b (e i) = b (e j)) : + ∃ f : X ≃ Y, ∀ i, f (a i) = b (e i) := by + choose g hg using ha + let u := b ∘ e ∘ g + have hu (i : A) : u (a i) = b (e i) := (he _ _).mp (hg _) + have hh : Function.Bijective u := by + constructor + · intro x y h + exact (hg x).symm.trans (((he _ _).mpr h).trans (hg y)) + · intro y + obtain ⟨i, rfl⟩ := hb y + exact ⟨a (e.symm i), by rw [hu, e.apply_symm_apply]⟩ + exact ⟨Equiv.ofBijective u hh, hu⟩ + +/-- Local representatives may be redundant. Matching their equality +relation is enough to transport the global pins bijectively. -/ +theorem induced {P : A → Type} {Q : B → Type} + (e : A ≃ B) (h : ∀ i, P i = Q (e i)) (a : ∀ i, P i → X) (b : ∀ i, Q i → Y) + (ha : ∀ x, ∃ i j, a i j = x) (hb : ∀ y, ∃ i j, b i j = y) + (same : ∀ i j u v u' v', HEq u u' → HEq v v' → + (a i u = a j v ↔ b (e i) u' = b (e j) v')) : + ∃ f : X ≃ Y, ∀ i u v, HEq u v → f (a i u) = b (e i) v := by + let E := Equiv.sigmaCongr e fun i => Equiv.cast (h i) + obtain ⟨f, hf⟩ := induce_surj E (fun p => a p.1 p.2) (fun p => b p.1 p.2) (by + intro x + obtain ⟨i, j, he⟩ := ha x + exact ⟨⟨i, j⟩, he⟩) (by + intro x + obtain ⟨i, j, he⟩ := hb x + exact ⟨⟨i, j⟩, he⟩) (by + rintro ⟨i, u⟩ ⟨j, v⟩ + exact same i j u v _ _ (cast_heq (h i) u).symm (cast_heq (h j) v).symm) + refine ⟨f, fun i u v he => (hf ⟨i, u⟩).trans ?_⟩ + exact congrArg _ (eq_of_heq ((cast_heq (h i) u).trans he)) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Comparing request identities across incident charts + +A reference consists of an incident-chart token and a local request. +Global identifiers only enter through equalities between bounded words. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +open Protocol (Near) +open scoped Pointwise + +variable {G K J : Type} [Group G] [Field K] {U : J → Subgroup G} {g : G} + (p : Parameters K U g) + +open scoped Classical in +/-- Indexes the ref by the coordinates of `Σ u : p.Token, u.1.1.Req p.table`. -/ +abbrev Ref := Σ u : p.Token, u.1.1.Req p.table + +open scoped Classical in +/-- In the case `none, none`, this construction gives `x.see (a.1.back p) (b.1.back p) = true`. -/ +def equalRefs (x : Root G) (a b : p.Ref) : Prop := + match a.2, b.2 with + | none, none => x.see (a.1.back p) (b.1.back p) = true + | some (u, j), some (v, k) => j = k ∧ ∀ s, + x.see (a.1.1.word (u s) * a.1.back p) (b.1.1.word (v s) * b.1.back p) = true + | _, _ => False + +open scoped Classical in +theorem local_equalRefs : Root.Local p.equalRefs := by + apply Root.local_pi + rintro ⟨a, u⟩ + apply Root.local_pi + rintro ⟨b, v⟩ + rcases u with _ | ⟨u, j⟩ <;> rcases v with _ | ⟨v, k⟩ + · exact (Root.local_see _ _).map (· = true) + · exact ⟨∅, fun _ _ _ => rfl⟩ + · exact ⟨∅, fun _ _ _ => rfl⟩ + · have h : Root.Local (fun x : Root G => fun s => + x.see (a.1.word (u s) * a.back p) (b.1.word (v s) * b.back p)) := + Root.local_pi fun _ => Root.local_see _ _ + exact h.map fun f => j = k ∧ ∀ s, f s = true + +variable {t : ℕ} (w : Fin (2 ^ t) → G) + +open scoped Classical in +/-- The quantity computed by `x.index w (a.1.1.home p.table a.2 * a.1.back p) (b.back p)`. -/ +def refKey (x : Root G) (a : p.Ref) (b : p.Token) := + x.index w (a.1.1.home p.table a.2 * a.1.back p) (b.back p) + +open scoped Classical in +theorem local_refKey : Root.Local (p.refKey w) := + Root.local_pi fun _ => Root.local_pi fun _ => Root.index_local _ _ _ + +variable {I : Type} [MulAction G I] {i : I} + +open scoped Classical in +/-- Uses `⟨p.token j, x⟩` as the representation. -/ +def ref (j : Near (p.balls I) i) (x : ((p.balls I).code j.1).Req p.table) : p.Ref := + ⟨p.token j, x⟩ + +open scoped Classical in +private theorem see_true (x : Root G) (a b : G) : x.see a b = true ↔ x.label a = x.label b := by + simp only [Root.see, decide_eq_true_eq] + +open scoped Classical in +theorem ref_eq (j k : Near (p.balls I) i) + (x : ((p.balls I).code j.1).Req p.table) (y : ((p.balls I).code k.1).Req p.table) : + p.equalRefs ⟨I, i⟩ (p.ref j x) (p.ref k y) ↔ + (p.balls I).request p.table j.1 x = (p.balls I).request p.table k.1 y := by + rw [Market.request_eq] + rcases x with _ | ⟨x, a⟩ <;> rcases y with _ | ⟨y, b⟩ + · simp only [equalRefs, ref, see_true] + change (p.token j).back p • i = (p.token k).back p • i ↔ j.1 = k.1 + rw [p.back_eq, p.back_eq] + · rfl + · rfl + · simp only [equalRefs, ref, see_true] + change (a = b ∧ ∀ s, ((p.token j).1.word (x s) * (p.token j).back p) • i = + ((p.token k).1.word (y s) * (p.token k).back p) • i) ↔ _ + simp only [mul_smul, p.back_eq] + rfl + +variable [Fintype I] [DecidableEq I] (hw : Set.range w = offsets p.core p.radius) + +open scoped Classical in +theorem refKey_eq (j k : Near (p.balls I) i) (x : ((p.balls I).code j.1).Req p.table) : + let b := p.balls I + p.refKey w ⟨I, i⟩ (p.ref j x) (p.token k) = + (marketPorts p.core p.radius p.unit g p.reach w hw).key + (b.home p.table (b.request p.table j.1 x)) k.1 := by + unfold refKey + rw [index_eq p.core p.radius w p.unit g p.reach hw] + simp only [ref, mul_smul, p.back_eq] + rcases x with _ | ⟨x, v⟩ + · simp only [Board.home, one_smul]; rfl + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +end + +/- +# Local information needed by an incident kernel +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +open Protocol (Near) +open scoped Pointwise + +variable {G K J : Type} [Group G] [Field K] {U : J → Subgroup G} {g : G} + (p : Parameters K U g) {t : ℕ} (w : Fin (2 ^ t) → G) (j₀ : Fin (2 ^ t)) + +open scoped Classical in +/-- The value specified by `owns p.table p.core p.radius p.unit g p.reach w j₀ (x.shift +(a.1.back p)) ⟨a.1.1.1, a.2⟩`. -/ +def depotRef (x : Root G) (a : p.Ref) := + owns p.table p.core p.radius p.unit g p.reach w j₀ (x.shift (a.1.back p)) ⟨a.1.1.1, a.2⟩ + +open scoped Classical in +theorem local_depotRef : Root.Local (p.depotRef w j₀) := by + apply Root.local_pi + intro a + exact ((owns_local p.table p.core p.radius p.unit g p.reach w j₀).shift (a.1.back p)).map + fun f => f ⟨a.1.1.1, a.2⟩ + +variable (hw : Set.range w = offsets p.core p.radius) (h₀ : w j₀ = 1) + {I : Type} [MulAction G I] [Fintype I] [DecidableEq I] {i : I} + +include h₀ in +open scoped Classical in +theorem depotRef_iff (j : Near (p.balls I) i) (u : ((p.balls I).code j.1).Req p.table) : + let b := p.balls I + let a := marketPorts p.core p.radius p.unit g p.reach w hw + p.depotRef w j₀ ⟨I, i⟩ (p.ref j u) = true ↔ (b.depot p.table a (b.request p.table j.1 u)).1 + = j.1 := by + let b := p.balls I + let a := marketPorts (I := I) p.core p.radius p.unit g p.reach w hw + have he : p.depotRef w j₀ ⟨I, i⟩ (p.ref j u) = b.here p.table a j.1 u := by + change owns _ _ _ _ _ _ w j₀ ⟨I, (p.token j).back p • i⟩ ⟨b.code j.1, u⟩ = _ + rw [p.back_eq] + exact owns_here p.table _ _ _ _ _ w j₀ hw h₀ _ _ + dsimp only + rw [he, Market.here, decide_eq_true_eq] + constructor + · exact fun h => congrArg Sigma.fst h + · intro h + have h' := (b.depot_spec p.table a (b.request p.table j.1 u)).1 + change (b.depot p.table a (b.request p.table j.1 u)).1 = j.1 at h + generalize b.depot p.table a (b.request p.table j.1 u) = v at h h' ⊢ + rcases v with ⟨v, k⟩ + change v = j.1 at h + subst v + exact congrArg (fun x => (⟨j.1, x⟩ : b.Source p.table)) (b.request_inj p.table _ h') + +open scoped Classical in +/-- The value specified by `(p.Present x, p.equalRefs x, p.refKey w x, p.depotRef w j₀ x)`. -/ +def signature (x : Root G) := (p.Present x, p.equalRefs x, p.refKey w x, p.depotRef w j₀ x) + +open scoped Classical in +theorem local_signature : Root.Local (p.signature w j₀) := + p.local_present.pair (p.local_equalRefs.pair ((p.local_refKey w).pair (p.local_depotRef w j₀))) + +variable {p} +namespace Clock + +open scoped Classical in +/-- Computes the marks by the application `x.mark (x.label (u.back p))`. -/ +def marks (c : p.Clock) (x : c.Input) (u : p.Token) := x.mark (x.label (u.back p)) + +open scoped Classical in +theorem marks_local (c : p.Clock) : Decor.Local c.marks := + Decor.local_pi fun _ => Decor.local_mark _ + +open scoped Classical in +/-- The value specified by `(p.signature w j₀ x.toRoot, c.marks x)`. -/ +def chartView (c : p.Clock) (x : c.Input) := (p.signature w j₀ x.toRoot, c.marks x) + +open scoped Classical in +theorem chartView_local (c : p.Clock) : Decor.Local (c.chartView w j₀) := + (Decor.local_root (p.local_signature w j₀)).pair c.marks_local + +end Clock +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +end + +/- +# Matching global pins by agreement on incident charts +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +open Protocol (Pin Near Match localRequest localEdge placeReq placeEdge) +open scoped Pointwise + +variable {G K J : Type} [Group G] [Field K] {U : J → Subgroup G} {g : G} + (p : Parameters K U g) + +open scoped Classical in +/-- Computes the req pin by the application `Pin (localRequest u.1.1 p.table) u.2`. -/ +abbrev ReqPin (u : p.Token) := Pin (localRequest u.1.1 p.table) u.2 +open scoped Classical in +/-- Computes the core pin by the application `Pin (localEdge K u.1.1) u.2`. -/ +abbrev CorePin (u : p.Token) := Pin (localEdge K u.1.1) u.2 + +open scoped Classical in +theorem refPin_eq {u v : p.Token} (he : u = v) {x : p.ReqPin u} {y : p.ReqPin v} (h : HEq x y) : + (⟨u, x.1⟩ : p.Ref) = ⟨v, y.1⟩ ∧ HEq x.2.val y.2.val := by + subst v + cases eq_of_heq h + exact ⟨rfl, HEq.rfl⟩ + +variable {I V : Type} [MulAction G I] [MulAction G V] {i : I} {v : V} + +open scoped Classical in +theorem req_cover (x : Pin (Protocol.request (p.balls I) p.table) i) : + ∃ j l, placeReq p.table j l = x := by + obtain ⟨u, y, h⟩ := (p.balls I).request_surj p.table x.1 + obtain ⟨k, z, hz⟩ := Protocol.placeReq_surj x u y h + exact ⟨⟨u, k⟩, ⟨y, z⟩, hz⟩ + +open scoped Classical in +theorem edge_cover (x : Pin (Protocol.edge K (p.balls I)) i) : + ∃ j l, placeEdge K j l = x := by + obtain ⟨k, z, hz⟩ := Protocol.placeEdge_surj x x.1.1 x.1.2 rfl + exact ⟨⟨x.1.1, k⟩, ⟨x.1.2, z⟩, hz⟩ + +open scoped Classical in +private theorem same_heq {A B X Y : Type} {a : A} {b : B} {x : X} {y : Y} + (h : HEq a x) (g : HEq b y) : HEq a b ↔ HEq x y := + ⟨fun e => h.symm.trans (e.trans g), fun e => h.trans (e.trans g.symm)⟩ + +open scoped Classical in +theorem match_exists (he : p.Present ⟨I, i⟩ = p.Present ⟨V, v⟩) + (hr : p.equalRefs ⟨I, i⟩ = p.equalRefs ⟨V, v⟩) : + ∃ f : Match p.table (p.balls I) (p.balls V) i v, ∀ j, p.token j = p.token (f.near j) := by + let e := p.sameNear he + have ht (j) := p.sameNear_token he j + have req (j) : p.ReqPin (p.token j) = p.ReqPin (p.token (e j)) := congrArg p.ReqPin (ht j) + have core (j) : p.CorePin (p.token j) = p.CorePin (p.token (e j)) := congrArg p.CorePin (ht j) + obtain ⟨rq, hq⟩ := induced e req (placeReq p.table) (placeReq p.table) + (p.req_cover) (p.req_cover) (by + intro j k x y x' y' hx hy + obtain ⟨u, hu⟩ := p.refPin_eq (ht j) hx + obtain ⟨z, hz⟩ := p.refPin_eq (ht k) hy + refine (Protocol.placeReq_eq_iff _ _ _ _ _).trans + ((and_congr ?_ (same_heq hu hz)).trans (Protocol.placeReq_eq_iff _ _ _ _ _).symm) + exact (p.ref_eq j k _ _).symm.trans + ((iff_of_eq (congrArg₂ _ u z |>.trans (congrFun (congrFun hr _) _))).trans + (p.ref_eq (e j) (e k) _ _))) + obtain ⟨re, hee⟩ := induced e core (placeEdge K) (placeEdge K) + (p.edge_cover) (p.edge_cover) (by + intro j k x y x' y' hx hy + constructor + · intro h + have h' := Protocol.placeEdge_injective (a₁ := ⟨j, x⟩) (a₂ := ⟨k, y⟩) h + have eq := Sigma.mk.inj h' + cases eq.1 + rw [eq_of_heq ((same_heq hx hy).mp eq.2)] + · intro h + have h' := Protocol.placeEdge_injective (a₁ := ⟨e j, x'⟩) (a₂ := ⟨e k, y'⟩) h + have eq := Sigma.mk.inj h' + cases e.injective eq.1 + rw [eq_of_heq ((same_heq hx hy).mpr eq.2)]) + exact ⟨⟨rq, re, e, fun j => congrArg (fun x : p.Token => x.1.1) (ht j), + fun j => congrArg (fun x : p.Token => x.2.val) (ht j), hq, hee⟩, ht⟩ + +variable [Fintype I] [Fintype V] [DecidableEq I] [DecidableEq V] + {p} (c : p.Clock) {t : ℕ} (w : Fin (2 ^ t) → G) (j₀ : Fin (2 ^ t)) + (hw : Set.range w = offsets p.core p.radius) (h₀ : w j₀ = 1) + +include h₀ in +open scoped Classical in +theorem Clock.match_of_view (z : I → Fin (2 ^ c.bits)) (z' : V → Fin (2 ^ c.bits)) + (h : c.chartView w j₀ ⟨⟨I, i⟩, z⟩ = c.chartView w j₀ ⟨⟨V, v⟩, z'⟩) : + let a := marketPorts (I := I) p.core p.radius p.unit g p.reach w hw + let b := marketPorts (I := V) p.core p.radius p.unit g p.reach w hw + ∃ f : Match p.table (p.balls I) (p.balls V) i v, + (∀ j, p.token j = p.token (f.near j)) ∧ f.keys a b ∧ f.depots a b ∧ + ∀ j, z j.1 = z' (f.near j).1 := by + have hp : p.Present ⟨I, i⟩ = p.Present ⟨V, v⟩ := congrArg (fun u => u.1.1) h + have hr : p.equalRefs ⟨I, i⟩ = p.equalRefs ⟨V, v⟩ := congrArg (fun u => u.1.2.1) h + have hk : p.refKey w ⟨I, i⟩ = p.refKey w ⟨V, v⟩ := congrArg (fun u => u.1.2.2.1) h + have hd : p.depotRef w j₀ ⟨I, i⟩ = p.depotRef w j₀ ⟨V, v⟩ := congrArg (fun u => u.1.2.2.2) h + have hm : c.marks ⟨⟨I, i⟩, z⟩ = c.marks ⟨⟨V, v⟩, z'⟩ := congrArg Prod.snd h + obtain ⟨f, hf⟩ := p.match_exists hp hr + refine ⟨f, hf, ?_, ?_, ?_⟩ + · intro j x + obtain ⟨k, l, rfl⟩ := p.req_cover x + let l' := cast (congrArg p.ReqPin (hf k)) l + have hl : HEq l l' := (cast_heq _ _).symm + rw [f.req_eq k l l' hl] + have he : p.ref k l.1 = p.ref (f.near k) l'.1 := (p.refPin_eq (hf k) hl).1 + exact (p.refKey_eq w hw k j l.1).symm.trans + ((congrArg₂ _ he (hf j)).trans ((congrFun (congrFun hk _) _).trans + (p.refKey_eq w hw (f.near k) (f.near j) l'.1))) + · intro j x y he + have hr : p.ref j x = p.ref (f.near j) y := Sigma.ext (hf j) he + refine (p.depotRef_iff w j₀ hw h₀ j x).symm.trans ?_ + rw [hd, hr] + exact p.depotRef_iff w j₀ hw h₀ (f.near j) y + · intro j + have he := (congrFun hm (p.token j)).trans (congrArg _ (hf j)) + change z ((p.token j).back p • i) = z' ((p.token (f.near j)).back p • v) at he + rwa [p.back_eq, p.back_eq] at he + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +end + +/- +# Preserving physical coordinates across matching neighborhoods + +An exterior pin carries a source-or-target bit. A core pin carries +a local chart address, a side bit and the selected generator. These +finite observations suffice to compare any number of copies. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +open Protocol (Pin Match Near placeReq placeEdge) +open scoped Pointwise + +variable {G K J : Type} [Group G] [Field K] {U : J → Subgroup G} {g : G} + (p : Parameters K U g) + +open scoped Classical in +/-- Computes the generators by the application `a.generator p.unit (x.shift (u.back p))`. -/ +def generators (x : Root G) (u : p.Token) (a : Address p.core p.radius) := + a.generator p.unit (x.shift (u.back p)) + +open scoped Classical in +theorem local_generators : Root.Local p.generators := + Root.local_pi fun u => Root.local_pi fun a => (a.local_generator p.unit).shift (u.back p) + +variable {I V : Type} [MulAction G I] [MulAction G V] {i : I} {j : V} + +open scoped Classical in +/-- In the case `⟨.inl _, x⟩`, this construction gives `some x.val`. -/ +def reqMark : Pin (Protocol.request (p.balls I) p.table) i → Option Bool + | ⟨.inl _, x⟩ => some x.val + | ⟨.inr _, _⟩ => none + +open scoped Classical in +private def localMark (u : p.Token) : p.ReqPin u → Option Bool + | ⟨none, x⟩ => some x.val + | ⟨some _, _⟩ => none + +open scoped Classical in +private theorem mark_place (u : Near (p.balls I) i) (x : p.ReqPin (p.token u)) : + p.reqMark (placeReq p.table u x) = p.localMark (p.token u) x := by + obtain ⟨_ | _, x⟩ := x <;> rfl + +variable (r : Match p.table (p.balls I) (p.balls V) i j) + (he : ∀ t, p.token t = p.token (r.near t)) + +include he in +open scoped Classical in +theorem mark_match (x : Pin (Protocol.request (p.balls I) p.table) i) : + p.reqMark x = p.reqMark (r.req x) := by + obtain ⟨t, a, rfl⟩ := p.req_cover x + let b := cast (congrArg p.ReqPin (he t)) a + have hh : HEq a b := (cast_heq _ _).symm + rw [r.req_eq t a b hh, mark_place p t a, mark_place p (r.near t) b] + exact congrArg (fun x : Σ u, p.ReqPin u => p.localMark x.1 x.2) + (show (⟨p.token t, a⟩ : Σ u, p.ReqPin u) = ⟨_, b⟩ from Sigma.ext (he t) hh) + +open scoped Classical in +private theorem copies_mark [Fintype I] [DecidableEq I] (k : ℕ) + (x : Pin (Protocol.request (p.balls I) p.table) i) : + Stock.copies ((p.balls I).payload p.table) k x.1 = if (p.reqMark x).isSome then k else 0 := by + obtain ⟨x|x, y⟩ := x <;> simp [Stock.copies, Market.payload, reqMark, Option.isSome] + +include he in +open scoped Classical in +theorem copies_match [Fintype I] [DecidableEq I] [Fintype V] [DecidableEq V] (k : ℕ) : + Pin.Same r.req (Stock.copies ((p.balls I).payload p.table) k) + (Stock.copies ((p.balls V).payload p.table) k) := by + intro x + rw [copies_mark p k x, copies_mark p k (r.req x), p.mark_match r he x] + +open scoped Classical in +/-- The value specified by `(attach p.core p.unit p.radius g p.reach x.1 x.2.val l).2`. -/ +def socket {R : ℕ} (x : Pin (Protocol.edge K (p.balls I)) i) (l : Fin R) := + (attach p.core p.unit p.radius g p.reach x.1 x.2.val l).2 + +open scoped Classical in +private def localSocket {R : ℕ} (x : Root G) (l : Fin R) (a : Σ u, p.CorePin u) : + Socket p.core p.radius R := + let q : Address p.core p.radius := ⟨a.1.1, a.2.1⟩ + (q, a.2.2.val, l, p.generators x a.1 q) + +open scoped Classical in +private theorem socket_place {R : ℕ} (t : Near (p.balls I) i) (a : p.CorePin (p.token t)) + (l : Fin R) : p.socket (placeEdge K t a) l = p.localSocket ⟨I, i⟩ l ⟨p.token t, a⟩ := by + have hh : Root.shift ((p.token t).back p) ⟨I, i⟩ = (⟨I, t.1⟩ : Root G) := by + change (⟨I, (p.token t).back p • i⟩ : Root G) = _ + rw [p.back_eq t] + unfold localSocket generators + rw [hh] + rfl + +include he in +open scoped Classical in +theorem socket_match {R : ℕ} (hg : p.generators ⟨I, i⟩ = p.generators ⟨V, j⟩) + (x : Pin (Protocol.edge K (p.balls I)) i) (l : Fin R) : + p.socket x l = p.socket (r.core x) l := by + obtain ⟨t, a, rfl⟩ := p.edge_cover x + let b := cast (congrArg p.CorePin (he t)) a + have hh : HEq a b := (cast_heq _ _).symm + have h : (⟨p.token t, a⟩ : Σ u, p.CorePin u) = ⟨_, b⟩ := Sigma.ext (he t) hh + rw [r.core_eq t a b hh, socket_place p t a l, socket_place p (r.near t) b l, h] + simp only [localSocket, hg] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +end + +/- +# Comparing profiles at different sites + +Describe the kernel inputs directly at the unrenamed inventory pins. +Their side, ordinal and physical socket agree across matching charts. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +open Protocol (Pin Frame Match) +open Transport Coloring + +variable {G F J : Type} [Group G] [Field F] {U : J → Subgroup G} {g : G} + {a : Parameters F U g} (s : Rig a) +variable {I V : Type} [Fintype I] [MulAction G I] + [Fintype V] [MulAction G V] + +open scoped Classical in +/-- Computes the count req by the application `Stock.copies ((a.balls I).payload a.table) +s.clock.width`. -/ +abbrev countReq (I : Type) [Fintype I] [MulAction G I] := + Stock.copies ((a.balls I).payload a.table) s.clock.width + +open scoped Classical in +/-- Computes the in board by the application `Protocol.Board.orders (Protocol.request (a.balls +I) a.table) (s.countReq I)`. -/ +abbrev inBoard (I : Type) [Fintype I] [MulAction G I] := + Protocol.Board.orders (Protocol.request (a.balls I) a.table) (s.countReq I) + +open scoped Classical in +/-- Computes the out board by the application `Protocol.Board.orders (Protocol.edge F (a.balls +I)) (s.widthAt u)`. -/ +abbrev outBoard (u : s.clock.path I) := + Protocol.Board.orders (Protocol.edge F (a.balls I)) (s.widthAt u) + +open scoped Classical in +/-- The input pos of type `Fin s.clock.width ⊕ Fin s.clock.width`, constructed using `(Pin.slots +_ i (s.countReq I)).symm x`. -/ +def inputPos (i : I) (x : (s.inBoard I).localPort i) : + Fin s.clock.width ⊕ Fin s.clock.width := + let q := (Pin.slots _ i (s.countReq I)).symm x + let j := q.2.castLE (show s.countReq I q.1.1 ≤ s.clock.width from by + unfold countReq Stock.copies + split <;> omega) + if a.reqMark q.1 = some true then .inr j else .inl j + +open scoped Classical in +/-- The value specified by `(s.endpoints u x.val).2`. -/ +def outputPos (u : s.clock.path I) (i : I) (x : (s.outBoard u).localPort i) : B s.p := + (s.endpoints u x.val).2 + +open scoped Classical in +/-- The value specified by `(s.execute.kernel u i).pull (s.inputPos i) (s.outputPos u i)`. -/ +def unrenamed [Nonempty I] (u : s.clock.path I) (i : I) : Profile F s.p s.clock.width := + (s.execute.kernel u i).pull (s.inputPos i) (s.outputPos u i) + +variable {u : s.clock.path I} {v : s.clock.path V} {i : I} {j : V} + (r : Match a.table (a.balls I) (a.balls V) i j) (he : ∀ t, a.token t = a.token (r.near t)) + +include he in +open scoped Classical in +private theorem input_eq (x : (s.inBoard I).localPort i) : + s.inputPos i x = s.inputPos j (Pin.lift r.req (a.copies_match r he s.clock.width) x) := by + obtain ⟨p, k, rfl⟩ := Pin.exists_atCopy x + rw [Pin.lift_atCopy] + unfold inputPos + change (if a.reqMark p = some true then _ else _) = if a.reqMark (r.req p) + = some true then _ else _ + rw [a.mark_match r he p] + rfl + +include he in +open scoped Classical in +private theorem output_eq (hg : a.generators ⟨I, i⟩ = a.generators ⟨V, j⟩) + (hw : Pin.Same r.core (s.widthAt u) (s.widthAt v)) (x : (s.outBoard u).localPort i) : + s.outputPos u i x = s.outputPos v j (Pin.lift r.core hw x) := by + obtain ⟨p, k, rfl⟩ := Pin.exists_atCopy x + rw [Pin.lift_atCopy] + exact congrArg s.bank (a.socket_match r he hg p (k.castLE (s.bounded u p.1))) + +open scoped Classical in +theorem unrenamed_eq [Nonempty I] [Nonempty V] (hg : a.generators ⟨I, i⟩ = a.generators ⟨V, j⟩) + (hw : Pin.Same r.core (s.widthAt u) (s.widthAt v)) + (hk : Frame.Rel (Pin.lift r.req (a.copies_match r he s.clock.width)) (Pin.lift r.core hw) + (s.execute.kernel u i) (s.execute.kernel v j)) : s.unrenamed u i = s.unrenamed v j := by + have hh := hk.pull (a := .refl _) (b := .refl _) (s.input_eq r he) (s.output_eq r he hg hw) + exact funext fun z => funext fun x => funext fun y => hh z x y + +open scoped Classical in +private def demandPos {h W : ℕ} (i : Protocol.End (fun _ : Site h => W)) : Fin W ⊕ Fin W := + if i.2 then .inr i.1.2 else .inl i.1.2 + +open scoped Classical in +/-- Decidable equality on sites used in the routing compatibility argument. -/ +local instance {h : ℕ} : DecidableEq (Site h) := Classical.decEq _ + +open scoped Classical in +private theorem side_eq {h : ℕ} [MulAction G (Site h)] (σ : Equiv.Perm (B h)) + (hc : ∀ i : Site h, (a.balls (Site h)).name i ((a.balls (Site h)).shape i).dst = inflate h σ i) + (i : Site h) (x : (s.inBoard (Site h)).localPort i) : + demandPos ((Protocol.demandRename (a.balls (Site h)) a.table σ s.clock.width hc).eqv x.val) = + s.inputPos i x := by + obtain ⟨p, l, rfl⟩ := Pin.exists_atCopy (T := Protocol.request (a.balls (Site h)) a.table) + (z := s.countReq (Site h)) x + obtain ⟨j|j, v⟩ := p + · have hl : l.val < s.clock.width := by + have := l.isLt + simpa [countReq, Stock.copies, Market.payload] using this + have he := Protocol.demandRename_apply (a.balls (Site h)) a.table σ s.clock.width hc j + l ⟨l.val, hl⟩ rfl v.val + refine (congrArg demandPos he).trans ?_ + let side : Bool := v.val + let slot : Fin s.clock.width := ⟨l.val, hl⟩ + change (if side then (Sum.inr slot : Fin _ ⊕ Fin _) else Sum.inl slot) = + if some side = some true then Sum.inr slot else Sum.inl slot + simp only [Option.some.injEq] + · have := l.isLt + simp [countReq, Stock.copies, Market.payload] at this + +open scoped Classical in +private theorem side_def {m h : ℕ} (T : Routes F m) (s : Rig T.params) + (σ : Equiv.Perm (B h)) (i : Site h) (x : (initial T s σ).localPort i) : + side T s σ i x = demandPos x.val := by + unfold side demandPos + congr 1 + +open scoped Classical in +theorem sample_eq {m : ℕ} (T : Routes F m) (s : Rig T.params) (x : Example T s) : + sample T s x = letI := T.action x.h x.σ; s.unrenamed x.u x.i := by + let _ := T.action x.h x.σ + have eq := funext (s.side_eq x.σ (target_at T x.σ) x.i) + refine congrArg (fun k => (s.execute.kernel x.u x.i).pull k (s.outputPos x.u x.i)) (Eq.trans ?_ + eq) + exact funext fun j => side_def T s x.σ x.i _ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +end + +/- +# Equal local views match the full kernel history + +The equality of the per-center symbols lifts to equality of films. +Peeling the first frame preserves equality at every incident chart, +including the terminal inventories. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral +open Protocol (Near Match) +open scoped Pointwise + +variable {K S I V : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype I] [DecidableEq I] [Fintype V] [DecidableEq V] + {N M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} + (a : Atlas N A M ρ) (μ d m R : ℕ) + +omit [Nonempty S] in +open scoped Classical in +private theorem start_eq {k : ℕ} {s t : Shape N} {u : a.Timeline m R s k} {v : a.Timeline m R t k} + (h : (⟨s, u⟩ : a.Film m R k) = ⟨t, v⟩) {x : s.Req A} {y : t.Req A} (he : HEq x y) : + a.start m R s k u x = a.start m R t k v y := by + cases (Sigma.mk.inj h).1 + rw [eq_of_heq (Sigma.mk.inj h).2, eq_of_heq he] + +omit [Nonempty S] in +open scoped Classical in +private theorem record_eq {k : ℕ} {s t : Shape N} + {u : a.Timeline m R s (k + 1)} {v : a.Timeline m R t (k + 1)} + (h : (⟨s, u⟩ : a.Film m R (k + 1)) = ⟨t, v⟩) : HEq u.2.1 v.2.1 := by + cases (Sigma.mk.inj h).1 + rw [eq_of_heq (Sigma.mk.inj h).2] + +namespace Market + +variable (b : Market I N) + +omit [Nonempty S] in +open scoped Classical in +private theorem stock_eq {k : ℕ} {z : b.Request A → ℕ} (hz : ∀ i, z i + k * rateBound a m ≤ R) + (u : b.Path a μ d m k z) (i : I) (x : (b.code i).Req A) : + (a.start m R _ k (b.encodeLog a μ d m R k z u i) x).val = z (b.request A i x) := by + have h : z (b.request A i x) ≤ R := (Nat.le_add_right _ _).trans (hz _) + cases k <;> exact min_eq_left h + +variable {b} {c : Market V N} {i : I} {v : V} (f : Match A b c i v) + +open scoped Classical in +theorem replay (room : a.Room m) (hm : 1 ≤ M) (hd : d ≤ M) + (k : ℕ) (z : b.Request A → ℕ) (y : c.Request A → ℕ) + (hz : ∀ i, z i + k * rateBound a m ≤ R) (hy : ∀ i, y i + k * rateBound a m ≤ R) + (u : b.Path a μ d m k z) (w : c.Path a μ d m k y) + (hh : ∀ j : Near b i, b.film a m R (b.encodeLog a μ d m R k z u) j.1 = + c.film a m R (c.encodeLog a μ d m R k y w) (f.near j).1) : f.Replay a μ d m k z y u w := by + have step (I : Type) [Fintype I] [DecidableEq I] (b : Market I N) k z + (u : (b.decision a μ d m z).choice) (hz : ∀ i, z i + (k + 1) * rateBound a m ≤ R) (x) : + b.after a μ d m z u x + k * rateBound a m ≤ R := by + have h := b.after_bound a μ d m room hm hd z u x + have h' := hz x + rw [Nat.succ_mul] at h' + unfold rateBound at h' ⊢ + omega + induction k generalizing z y with + | zero => + intro j x y' he + refine (b.stock_eq a μ d m R hz u j.1 x).symm.trans ?_ + exact (congrArg Fin.val (start_eq a m R (hh j) he)).trans + (c.stock_eq a μ d m R hy w (f.near j).1 y') + | succ k ih => + refine ⟨fun j x y' he => ?_, fun j => record_eq a m R (hh j), + ih _ _ (step _ _ _ _ u.1 hz) (step _ _ _ _ w.1 hy) u.2 w.2 ?_⟩ + · refine (b.stock_eq a μ d m R hz u j.1 x).symm.trans ?_ + exact (congrArg Fin.val (start_eq a m R (hh j) he)).trans + (c.stock_eq a μ d m R hy w (f.near j).1 y') + · exact fun j => congrArg (a.tail m R) (hh j) + +end Market + +namespace Parameters.Clock + +variable {G J : Type} [Group G] {U : J → Subgroup G} {g : G} {p : Parameters K U g} + (c : p.Clock) {t : ℕ} (w : Fin (2 ^ t) → G) (j₀ : Fin (2 ^ t)) + (hw : Set.range w = offsets p.core p.radius) (h₀ : w j₀ = 1) + +include h₀ in +open scoped Classical in +theorem replay_of_view {X Y : Type} [MulAction G X] [MulAction G Y] [Fintype X] [Fintype Y] + {i : X} {v : Y} (x : c.path X) (y : c.path Y) + (h : c.chartView w j₀ ⟨⟨X, i⟩, c.selector x⟩ = c.chartView w j₀ ⟨⟨Y, v⟩, c.selector y⟩) : + let a := marketPorts (I := X) p.core p.radius p.unit g p.reach w hw + let b := marketPorts (I := Y) p.core p.radius p.unit g p.reach w hw + ∃ f : Match p.table (p.balls X) (p.balls Y) i v, + (∀ j, p.token j = p.token (f.near j)) ∧ f.keys a b ∧ f.depots a b ∧ + f.Replay p.offers c.μ p.path c.batch c.width 0 0 x y := by + obtain ⟨f, hu, hk, hd, hh⟩ := c.match_of_view w j₀ hw h₀ _ _ h + refine ⟨f, hu, hk, hd, Market.replay p.offers c.μ p.path c.batch c.bound f c.room + (p.path_pos.trans_le p.pay) p.pay c.width 0 0 (fun _ => by simp [bound]) + (fun _ => by simp [bound]) x y ?_⟩ + exact fun j => (p.offers.write c.batch c.bound).injective (hh j) + +end Parameters.Clock +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# The programmed kernel depends only on a finite local observation + +The observation matches the incident charts, local copy ordinals, +selected branches and terminal suppliers. Generator choices align +the physical sockets of the output. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig + +variable {K G J : Type} [Field K] [Group G] {U : J → Subgroup G} {g : G} + {a : Parameters K U g} (s : Rig a) + {I V : Type} [Fintype I] [MulAction G I] [Nonempty I] + [Fintype V] [MulAction G V] [Nonempty V] {i : I} {j : V} + +open scoped Classical in +private abbrev ports (I : Type) [Fintype I] [MulAction G I] := + marketPorts (I := I) a.core a.radius a.unit g a.reach s.w s.hw + +open scoped Classical in +private theorem local_match (x : s.clock.path I) (y : s.clock.path V) + (hh : s.clock.chartView s.w s.j₀ ⟨⟨I, i⟩, s.clock.selector x⟩ = + s.clock.chartView s.w s.j₀ ⟨⟨V, j⟩, s.clock.selector y⟩) + (hg : a.generators ⟨I, i⟩ = a.generators ⟨V, j⟩) : + s.unrenamed x i = s.unrenamed y j := by + obtain ⟨f, he, hk, hd, hr⟩ := s.clock.replay_of_view s.w s.j₀ s.hw s.h₀ x y hh + have hv := f.replay_rel a.offers (s.ports I) (s.ports V) s.clock.height a.nz s.clock.room + s.clock.μ a.path hk hd (a.ready I) (a.ready V) a.local_supply hr + obtain ⟨hw, heq⟩ := Protocol.execute_start_rel (s.clock.runs I) (s.clock.runs V) + (a.copies_match f he) hv + exact s.unrenamed_eq f he hg hw heq + +variable {F : Type} [Field F] {m : ℕ} (T : Routes F m) (s : Rig T.params) + +open scoped Classical in +theorem compatible : Compatible T s := by + have ht := (s.clock.chartView_local s.w s.j₀).pair (Decor.local_root T.params.local_generators) + obtain ⟨E, hE⟩ := ht + refine ⟨E, fun x y hx hy => ?_⟩ + obtain ⟨he, hg⟩ := Prod.mk.inj (hE (observed T s x) (observed T s y) hx hy) + let _ := T.action x.h x.σ + let _ := T.action y.h y.σ + exact (sample_eq T s x).trans ((s.local_match x.u y.u he hg).trans + (sample_eq T s y).symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Decor.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Decor.lean new file mode 100644 index 0000000000..eb36a7c0bc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Decor.lean @@ -0,0 +1,881 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.GroupTheory.GroupAction.Basic +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Fintype.Pi +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Round +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryPrices + +/-! +# Finite observations of a pointed group action + +A query compares the labels obtained by two fixed actions on the +center. A function of finitely many such comparisons is local. This +property is preserved by finite tuples and by moving the center. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped Classical in +/-- The data for the root construction, including `site`, `[act`, `center`. -/ +structure Root (G : Type) [Group G] where + /-- The `Root` component of type `Type`. -/ + site : Type + [act : MulAction G site] + /-- The `Root` component of type `site`. -/ + center : site + +attribute [instance] Root.act + +namespace Root + +variable {G : Type} [Group G] {X Y : Type*} + +open scoped Classical in +/-- The value specified by `a • r.center`. -/ +def label (r : Root G) (a : G) : r.site := a • r.center + +open scoped Classical in +/-- Uses `⟨r.site, r.label a⟩` as the representation. -/ +def shift (a : G) (r : Root G) : Root G := ⟨r.site, r.label a⟩ + +open scoped Classical in +/-- Tests whether `r.label a = r.label b` holds. -/ +def see (r : Root G) (a b : G) : Bool := decide (r.label a = r.label b) + +open scoped Classical in +/-- The condition `∀ a ∈ E, ∀ b ∈ E, r.see a b = s.see a b` on the specified data. -/ +def Agree (E : Finset G) (r s : Root G) : Prop := + ∀ a ∈ E, ∀ b ∈ E, r.see a b = s.see a b + +open scoped Classical in +/-- The condition `∃ E : Finset G, ∀ r s, Agree E r s → f r = f s` on the specified data. -/ +def Local (f : Root G → X) : Prop := + ∃ E : Finset G, ∀ r s, Agree E r s → f r = f s + +open scoped Classical in +theorem Agree.mono {E D : Finset G} {r s : Root G} (h : Agree E r s) (hd : D ⊆ E) : + Agree D r s := fun _ ha _ hb => h _ (hd ha) _ (hd hb) + +open scoped Classical in +theorem local_see (a b : G) : Local (fun r : Root G => r.see a b) := + ⟨{a, b}, fun _ _ h => h a (by simp) b (by simp)⟩ + +open scoped Classical in +theorem Local.map {f : Root G → X} (h : Local f) (g : X → Y) : Local (g ∘ f) := by + obtain ⟨E, hE⟩ := h + exact ⟨E, fun r s he => congrArg g (hE r s he)⟩ + +open scoped Classical in +theorem Local.pair {f : Root G → X} {g : Root G → Y} (h : Local f) (k : Local g) : + Local (fun r => (f r, g r)) := by + obtain ⟨E, hE⟩ := h + obtain ⟨D, hD⟩ := k + exact ⟨E ∪ D, fun r s he => Prod.ext (hE r s (he.mono Finset.subset_union_left)) + (hD r s (he.mono Finset.subset_union_right))⟩ + +open scoped Classical in +theorem local_pi {J : Type*} [Finite J] {V : J → Type*} {f : Root G → ∀ j, V j} + (h : ∀ j, Local (fun r => f r j)) : Local f := by + let _ := Fintype.ofFinite J + choose E hE using h + exact ⟨Finset.univ.biUnion E, fun r s he => funext fun j => + hE j r s (he.mono (Finset.subset_biUnion_of_mem _ (Finset.mem_univ j)))⟩ + +open scoped Classical in +theorem Local.shift {f : Root G → X} (h : Local f) (a : G) : Local (f ∘ Root.shift a) := by + obtain ⟨E, hE⟩ := h + refine ⟨E.image (· * a), fun r s he => hE _ _ ?_⟩ + intro x hx y hy + have hh := he _ (Finset.mem_image_of_mem _ hx) _ (Finset.mem_image_of_mem _ hy) + simp only [see, label, Root.shift, mul_smul] at hh ⊢ + exact hh + +open scoped Classical in +theorem Local.of_eq {f : Root G → X} {g : Root G → Y} + (h : Local f) (hg : ∀ r s, f r = f s → g r = g s) : Local g := by + obtain ⟨E, hE⟩ := h + exact ⟨E, fun r s he => hg r s (hE r s he)⟩ + +end Root +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Local observations with an input record at each site +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped Classical in +/-- The decor of type `site → Fin (2 ^ q)` for the given inputs. -/ +structure Decor (G : Type) [Group G] (q : ℕ) extends Root G where + /-- The `Decor` component of type `site → Fin (2 ^ q)`. -/ + mark : site → Fin (2 ^ q) + +namespace Decor + +variable {G : Type} [Group G] {q : ℕ} {X Y : Type*} + +open scoped Classical in +/-- The condition `∃ E : Finset G, ∀ x y, Root.Agree E x.toRoot y.toRoot → (∀ a ∈ E, x.mark +(x.label a) = y.mark (y.label a)) → f x = f y` on the specified data. -/ +def Local (f : Decor G q → X) : Prop := + ∃ E : Finset G, ∀ x y, Root.Agree E x.toRoot y.toRoot → + (∀ a ∈ E, x.mark (x.label a) = y.mark (y.label a)) → f x = f y + +open scoped Classical in +theorem local_root {f : Root G → X} (h : Root.Local f) : + Local (fun x : Decor G q => f x.toRoot) := by + obtain ⟨E, hE⟩ := h + exact ⟨E, fun x y he _ => hE x.toRoot y.toRoot he⟩ + +open scoped Classical in +theorem local_mark (a : G) : Local (fun x : Decor G q => x.mark (x.label a)) := + ⟨{a}, fun _ _ _ h => h a (Finset.mem_singleton_self _)⟩ + +open scoped Classical in +theorem Local.map {f : Decor G q → X} (h : Local f) (g : X → Y) : Local (g ∘ f) := by + obtain ⟨E, hE⟩ := h + exact ⟨E, fun x y he hv => congrArg g (hE x y he hv)⟩ + +open scoped Classical in +theorem Local.pair {f : Decor G q → X} {g : Decor G q → Y} (h : Local f) (k : Local g) : + Local (fun r => (f r, g r)) := by + obtain ⟨E, hE⟩ := h + obtain ⟨D, hD⟩ := k + exact ⟨E ∪ D, fun r s he hv => + Prod.ext (hE _ _ (he.mono Finset.subset_union_left) fun a ha + => hv a (Finset.mem_union_left _ ha)) + (hD _ _ (he.mono Finset.subset_union_right) fun a ha => hv a (Finset.mem_union_right _ ha))⟩ + +open scoped Classical in +theorem local_pi {J : Type*} [Finite J] {V : J → Type*} {f : Decor G q → ∀ j, V j} + (h : ∀ j, Local (fun r => f r j)) : Local f := by + let _ := Fintype.ofFinite J + choose E hE using h + refine ⟨Finset.univ.biUnion E, fun r s he hv => funext fun j => ?_⟩ + have hj := Finset.subset_biUnion_of_mem E (Finset.mem_univ j) + exact hE j r s (he.mono hj) (fun a ha => hv a (hj ha)) + +end Decor +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Commodities local to a single ball + +A shape records the endpoints of a payload and the available core +links. Extra commodities range over all placements of finitely many +tensor types. The core links are supplies only. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral + +open scoped Classical in +/-- The data for the ball shape construction, including `src`, `dst`, `edges`, `flip`, +`connected`. -/ +structure BallShape (B : Type) where + /-- Assigns the source of each connection. -/ + src : B + /-- The distinguished destination in the finite ball. -/ + dst : B + /-- The finite set of connections carried by `BallShape`, with type `Finset (B × B)`. -/ + edges : Finset (B × B) + flip : ∀ a b, (a, b) ∈ edges → (b, a) ∈ edges + connected : ∀ a b, Relation.EqvGen (fun x y => (x, y) ∈ edges) a b + +namespace BallShape + +variable {B S K : Type} [Fintype S] [Field K] + +open scoped Classical in +instance [Finite B] : Finite (BallShape B) := + Finite.of_injective (fun b => (b.src, b.dst, b.edges)) (by + rintro ⟨_, _, _, _, _⟩ ⟨_, _, _, _, _⟩ h + cases h + rfl) + +variable [Fintype B] [DecidableEq B] [DecidableEq S] (b : BallShape B) (A : Finset (Tensor K S)) + +open scoped Classical in +/-- Indexes the requests by the coordinates of `Option ((S → B) × Fin A.card)`. -/ +abbrev Requests (B : Type) (A : Finset (Tensor K S)) := Option ((S → B) × Fin A.card) +open scoped Classical in +/-- Indexes the goods by the coordinates of `Requests B A ⊕ b.edges`. -/ +abbrev Goods := Requests B A ⊕ b.edges + +open scoped Classical in +/-- In the case `.inl none`, this construction gives `Tensor.wire K b.src b.dst 2`. -/ +def tensor : b.Goods A → Tensor K B + | .inl none => Tensor.wire K b.src b.dst 2 + | .inl (some (z, i)) => Tensor.place z (A.equivFin.symm i).val + | .inr e => Tensor.wire K e.val.1 e.val.2 2 + +open scoped Classical in +/-- In the case `.inl none`, this construction gives `v`. -/ +def rates (v : ℝ) (x : (S → B) → Tensor K S → ℝ) : b.Goods A → ℝ + | .inl none => v + | .inl (some (z, i)) => x z (A.equivFin.symm i).val + | .inr _ => 1 + +open scoped Classical in +/-- Computes the demands by the application `Finset.univ.map Function.Embedding.inl`. -/ +def demands : Finset (b.Goods A) := Finset.univ.map Function.Embedding.inl +open scoped Classical in +/-- Computes the links by the application `Finset.univ.map Function.Embedding.inr`. -/ +def links : Finset (b.Goods A) := Finset.univ.map Function.Embedding.inr + +open scoped Classical in +/-- One binary broadcast uses at most one bit on every core link. -/ +theorem broadcast : (2 : Tensor K B) ≤ ∏ i ∈ b.links A, b.tensor A i := by + let _ : Nonempty B := ⟨b.src⟩ + simp only [links, Finset.prod_map] + apply Tensor.connected K (fun e : b.edges => e.val.1) (fun e => e.val.2) + intro U hn hu + by_contra! hh + have stable (x y : B) (h : (x, y) ∈ b.edges) : x ∈ U → y ∈ U := hh ⟨(x, y), h⟩ + have eqv {x y : B} (h : Relation.EqvGen (fun x y => (x, y) ∈ b.edges) x y) : + x ∈ U ↔ y ∈ U := by + induction h with + | rel x y h => exact ⟨stable x y h, stable y x (b.flip x y h)⟩ + | refl => rfl + | symm _ _ _ ih => exact ih.symm + | trans _ _ _ _ _ ih ih' => exact ih.trans ih' + obtain ⟨x, hx⟩ := hn + exact hu (Finset.eq_univ_of_forall fun y => (eqv (b.connected x y)).mp hx) + +open scoped Classical in +theorem nonzero [Nonempty S] (ha : 0 ∉ A) (i : b.Goods A) : b.tensor A i ≠ 0 := by + let _ : Nonempty B := ⟨b.src⟩ + suffices 1 ≤ b.tensor A i from fun he => + one_ne_zero (le_antisymm (he ▸ this) (Tensor.zero_le _)) + rcases i with (_ | ⟨z, j⟩) | e + · exact Tensor.one_le_wire K _ _ (by decide) + · have h : (A.equivFin.symm j).val ≠ 0 := ne_of_mem_of_not_mem (A.equivFin.symm j).property ha + exact (Tensor.place_one z).symm.le.trans (Tensor.place_mono z (Tensor.one_le _ h)) + · exact Tensor.one_le_wire K _ _ (by decide) + +open scoped Classical in +theorem menu [Nonempty S] (ha : 0 ∉ A) (M : ℝ) {ρ : ℝ} (hρ : 0 < ρ) : + ∃ m : Finset (Proposal (b.tensor A) b.edges.card), ∃ δ : ℝ, 0 < δ ∧ + ∀ p ∈ Set.Icc 0 (fun _ => M), NearPrices (b.tensor A) (b.demands A) ρ p ∨ + ∃ q ∈ m, q.demand ⊆ b.demands A ∧ q.demand.Nonempty ∧ q.Works δ p := by + let _ : Nonempty B := ⟨b.src⟩ + apply menu_dichotomy (b.tensor A) (b.nonzero A ha) (b.demands A) _ _ _ hρ + intro v hv + obtain ⟨i, j, h, h'⟩ := positive_link _ b.connected v hv + exact ⟨.inr ⟨(i, j), h⟩, h'⟩ + +end BallShape +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# One finite menu for all shapes of bounded order +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] + +open scoped Classical in +/-- Indexes the shape by the coordinates of `Σ n : Fin (N + 1), BallShape (Fin n.val)`. -/ +abbrev Shape (N : ℕ) := Σ n : Fin (N + 1), BallShape (Fin n.val) + +namespace Shape +variable {N : ℕ} (b : Shape N) (A : Finset (Tensor K S)) + +open scoped Classical in +/-- Computes the move by the application `Proposal (b.2.tensor A) b.2.edges.card`. -/ +abbrev Move := Proposal (b.2.tensor A) b.2.edges.card + +open scoped Classical in +/-- Requires `q.move.block ≤ C ∧ ∀ j, ∑ i, q.move.count j i ≤ C`. -/ +def small (C : ℕ) (q : b.Move A) : Prop := + q.move.block ≤ C ∧ ∀ j, ∑ i, q.move.count j i ≤ C + +end Shape + +open scoped Classical in +/-- The data for the atlas construction, including `menu`, `margin`, `positive`, `capacity`, +`small`. -/ +structure Atlas (N : ℕ) (A : Finset (Tensor K S)) (M ρ : ℝ) where + /-- The `Atlas` component of type `(b : Shape N) → Finset (b.Move A)`. -/ + menu : (b : Shape N) → Finset (b.Move A) + /-- Stores the margin associated with this `Atlas`. -/ + margin : ℝ + positive : 0 < margin + /-- The maximum capacity carried by `Atlas`, with type `ℕ`. -/ + capacity : ℕ + small : ∀ b, ∀ q ∈ menu b, b.small A capacity q + detect : ∀ b, ∀ p ∈ Set.Icc 0 (fun _ => M), NearPrices (b.2.tensor A) (b.2.demands A) ρ p ∨ + ∃ q ∈ menu b, q.demand ⊆ b.2.demands A ∧ q.demand.Nonempty ∧ q.Works margin p + +open scoped Classical in +theorem atlas [Nonempty S] (N : ℕ) (A : Finset (Tensor K S)) (hA : 0 ∉ A) (M : ℝ) + {ρ : ℝ} (hρ : 0 < ρ) : Nonempty (Atlas N A M ρ) := by + let _ : Fintype (Shape N) := Fintype.ofFinite _ + choose m d hd hm using fun b : Shape N => b.2.menu A hA M hρ + choose c hc using fun b : Shape N => uniform_move_bound (m b) + let s := insert 1 (Finset.univ.image d) + have hs : s.Nonempty := ⟨1, Finset.mem_insert_self _ _⟩ + refine ⟨⟨m, s.min' hs, ?_, ∑ b, c b, ?_, ?_⟩⟩ + · rcases Finset.mem_insert.mp (s.min'_mem hs) with h | h + · rw [h]; exact zero_lt_one + · obtain ⟨b, _, e⟩ := Finset.mem_image.mp h + exact e ▸ hd b + · intro b q hq + have h := Finset.single_le_sum (fun i _ => Nat.zero_le (c i)) (Finset.mem_univ b) + exact ⟨(hc b q hq).1.trans h, fun j => ((hc b q hq).2 j).trans h⟩ + · intro b p hp + rcases hm b p hp with h | ⟨q, hq, h₁, h₂, h₃⟩ + · exact .inl h + have h : d b ∈ s := Finset.mem_insert_of_mem (Finset.mem_image_of_mem _ (Finset.mem_univ b)) + exact .inr ⟨q, hq, h₁, h₂, h₃.mono (s.min'_le _ h)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Placing local trades across a larger set of sites -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Proposal + +open Spectral Stock Finset + +variable {K S B I E J : Type} [Field K] [Fintype S] [Fintype B] [DecidableEq S] + [DecidableEq B] [Nonempty S] [Fintype I] [Fintype E] [Fintype J] + [DecidableEq I] [DecidableEq E] [DecidableEq J] {T : J → Tensor K S} {H : ℝ} + +/-- Demand and supply can use different numbers of blocks, provided +there is a local comparison with the corresponding inventories. -/ +theorem place_trade (q : Proposal T H) (g : J → I ⊕ E) (u : Finset J) (m l : ℕ) + (hd : ∀ j ∈ q.demand, ∃ i, g j = .inl i) + (T' : J → Tensor K S) (n : S → B) (U : I ⊕ E → Tensor K B) + (he : ∀ j, Tensor.place n (T' j) = U (g j)) + (cmp : bundle T' (copies q.demand (q.move.block * m)) ≤ + ∑ h ∈ histograms q.move.letter l, bundle T' (q.output u l h)) : + ({ q.trade g u l with take := (q.trade g u m).take } : Intervention I E).Covers + (U ∘ Sum.inl) (U ∘ Sum.inr) := by + classical + let F : Tensor K S →* Tensor K B := + { toFun := Tensor.place n + map_one' := Tensor.place_one n + map_mul' := Tensor.place_mul n } + have hs (v : Finset (q.move.letter → ℕ)) (z : (q.move.letter → ℕ) → Tensor K S) : + F (∑ i ∈ v, z i) ≤ ∑ i ∈ v, F (z i) := by + induction v using Finset.induction_on with + | empty => rw [sum_empty, sum_empty]; exact (Tensor.place_zero n).le + | insert i v hi ih => + rw [sum_insert hi, sum_insert hi, add_comm (z i), add_comm (F (z i))] + exact (Tensor.place_add_le n _ _).trans (Tensor.add_le_add_right _ _ _ ih) + have hb (z : J → ℕ) : + F (bundle T' z) = bundle (U ∘ Sum.inl) (collect g z ∘ Sum.inl) * + bundle (U ∘ Sum.inr) (collect g z ∘ Sum.inr) := by + rw [← bundle_split, bundle_collect, bundle, map_prod] + apply prod_congr rfl + intro j _ + rw [map_pow] + exact congrArg (· ^ z j) (he j) + have ht : bundle (U ∘ Sum.inl) (q.trade g u m).take = + F (bundle T' (copies q.demand (q.move.block * m))) := by + rw [hb, show bundle (U ∘ Sum.inr) (collect g (copies q.demand (q.move.block * m)) ∘ Sum.inr) + = 1 by simp [bundle, q.take_core g m hd], mul_one] + rfl + unfold Intervention.Covers + rw [ht] + refine ((Tensor.place_mono n cmp).trans (hs _ _)).trans_eq ?_ + rw [← sum_coe_sort] + exact sum_congr rfl fun h _ => hb _ + +theorem trade_covers (q : Proposal T H) (g : J → I ⊕ E) (u : Finset J) (m : ℕ) + (hd : ∀ j ∈ q.demand, ∃ i, g j = .inl i) (hu : (2 : Tensor K S) ≤ ∏ j ∈ u, T j) + (n : S → B) (U : I ⊕ E → Tensor K B) (he : ∀ j, Tensor.place n (T j) = U (g j)) : + (q.trade g u m).Covers (U ∘ Sum.inl) (U ∘ Sum.inr) := by + exact q.place_trade g u m m hd T n U he (q.batch u hu m) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Proposal +end + +/- +# Reindexing a local price test on the coordinates of a ball +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.BallShape + +open Spectral + +variable {K S I B : Type} [Field K] [Fintype S] [DecidableEq S] [DecidableEq I] + [Fintype B] [DecidableEq B] {V : Finset I} + +open scoped Classical in +/-- A coordinate chart carries both orientations of each core link. -/ +def chart (e : V ≃ B) (a b : V) (c : I → I → Prop) + (h : ∀ x y : V, Relation.EqvGen (fun u v : V => c u.val v.val) x y) : BallShape B where + src := e a + dst := e b + edges := Finset.univ.filter fun xy => + c (e.symm xy.1) (e.symm xy.2) ∨ c (e.symm xy.2) (e.symm xy.1) + flip := by simp [or_comm] + connected x y := by + have hp (u v : V) (huv : Relation.EqvGen (fun z w : V => c z.val w.val) u v) : + Relation.EqvGen (fun z w => c (e.symm z) (e.symm w) ∨ c (e.symm w) (e.symm z)) + (e u) (e v) := by + induction huv with + | rel u v h => exact .rel _ _ (by simp [h]) + | refl => exact .refl _ + | symm _ _ _ ih => exact .symm _ _ ih + | trans _ _ _ _ _ ih ih' => exact .trans _ _ _ ih ih' + simpa using hp _ _ (h (e.symm x) (e.symm y)) + +variable (A : Finset (Tensor K S)) (b : BallShape B) (e : V ≃ B) + +open scoped Classical in +/-- The indexed operation `b.rates A v (fun z => x (Subtype.val ∘ e.symm ∘ z))`. -/ +def localRates (v : ℝ) (x : (S → I) → Tensor K S → ℝ) : b.Goods A → ℝ := + b.rates A v (fun z => x (Subtype.val ∘ e.symm ∘ z)) + +omit [DecidableEq S] [DecidableEq I] [Fintype B] [DecidableEq B] in +open scoped Classical in +theorem localRates_mem {v M : ℝ} (hM : 1 ≤ M) (hv : v ∈ Set.Icc 0 M) + (x : (S → I) → Tensor K S → ℝ) (hx : ∀ z a, a ∈ A → x z a ∈ Set.Icc 0 M) : + localRates A b e v x ∈ Set.Icc 0 (fun _ => M) := by + have h (i : b.Goods A) : localRates A b e v x i ∈ Set.Icc 0 M := by + rcases i with (_ | ⟨z, j⟩) | k + · exact hv + · exact hx _ _ (A.equivFin.symm j).property + · exact ⟨zero_le_one, hM⟩ + exact ⟨fun i => (h i).1, fun i => (h i).2⟩ + +open scoped Classical in +theorem near_passes (c : I → I → Prop) + (hc : ∀ i j : V, c i.val j.val → (e i, e j) ∈ b.edges) + (v : ℝ) (x : (S → I) → Tensor K S → ℝ) (ρ : ℝ) + (hp : NearPrices (b.tensor A) (b.demands A) ρ (localRates A b e v x)) : + ∃ P, (P = 0 ∨ ∃ D, P ∈ Tensor.ordinary K V D) ∧ + Passes A V c (e.symm b.src) (e.symm b.dst) v x ρ P := by + obtain ⟨P, hP, hs, hd⟩ := hp + have price : P ∘ Tensor.place e = 0 ∨ ∃ D, P ∘ Tensor.place e ∈ Tensor.ordinary K V D := by + rcases hP with rfl | ⟨D, d, h, f, hf, rfl⟩ + · exact .inl rfl + · exact .inr ⟨D, d, h, f.comp (Tensor.group _ e.surjective), + hf.comp (Tensor.group_mono _ e.surjective), rfl⟩ + have hd' (i : Requests B A) := hd (.inl i) (Finset.mem_map.mpr ⟨i, Finset.mem_univ _, rfl⟩) + refine ⟨P ∘ Tensor.place e, price, ?_, ?_, ?_⟩ + · intro i j hi hj + rw [Subtype.ext hi, Subtype.ext hj] + simp only [Function.comp_apply, Tensor.place_wire, Equiv.apply_symm_apply] + exact (hd' none).le + · intro i j h + rw [Function.comp_apply, Tensor.place_wire] + exact (hs (.inr ⟨(e i, e j), hc i j h⟩)).le + · intro z u hu + rw [Function.comp_apply, ← Tensor.place_comp] + have h := hd' (some (e ∘ z, A.equivFin ⟨u, hu⟩)) + have he : e.symm ∘ (e ∘ z) = z := funext fun s => e.symm_apply_apply _ + simpa only [localRates, rates, tensor, Equiv.symm_apply_apply, he] using h.le + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.BallShape +end + +/- +# Requests across a family of overlapping balls + +A tuple occurring at two centers names the same request. Core links +may be counted separately for each center. A site of a tuple gives +an anchor bounding the number of centers that can alter its stock. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral + +open scoped Classical in +/-- The data for the market construction, including `size`, `shape`, `name`, `origin`, +`overlap`. -/ +structure Market (I : Type) (N : ℕ) where + /-- The size parameter carried by `Market`, with type `I → Fin (N + 1)`. -/ + size : I → Fin (N + 1) + /-- The `Market` component of type `(i : I) → BallShape (Fin (size i).val)`. -/ + shape : (i : I) → BallShape (Fin (size i).val) + /-- The name assigned to each index of type `(i : I) → Fin (size i).val ↪ I`. -/ + name : (i : I) → Fin (size i).val ↪ I + origin : ∀ i, name i (shape i).src = i + overlap : ∀ x, ∃ U : Finset I, U.card ≤ N ∧ ∀ i t, name i t = x → i ∈ U + +namespace Market + +variable {K I S : Type} [Field K] [Fintype I] [DecidableEq I] + [Fintype S] [DecidableEq S] {N : ℕ} + +variable (b : Market I N) (A : Finset (Tensor K S)) + +open scoped Classical in +/-- Computes the site by the application `Fin (b.size i).val`. -/ +abbrev Site (i : I) := Fin (b.size i).val + +open scoped Classical in +/-- The value specified by `b.name w.1 ∘ w.2`. -/ +def tuple (w : Σ i, S → b.Site i) : S → I := b.name w.1 ∘ w.2 + +open scoped Classical in +/-- Indexes the request by the coordinates of `I ⊕ (Set.range (b.tuple (S := S)) × Fin A.card)`. -/ +abbrev Request := I ⊕ (Set.range (b.tuple (S := S)) × Fin A.card) +open scoped Classical in +/-- Indexes the edge by the coordinates of `Σ i, (b.shape i).edges`. -/ +abbrev Edge := Σ i, (b.shape i).edges +open scoped Classical in +/-- Indexes the good by the coordinates of `b.Request A ⊕ b.Edge`. -/ +abbrev Good := b.Request A ⊕ b.Edge + +open scoped Classical in +/-- In the case `none`, this construction gives `.inl i`. -/ +def request (i : I) : BallShape.Requests (b.Site i) A → b.Request A + | none => .inl i + | some (z, j) => .inr (⟨b.name i ∘ z, ⟨⟨i, z⟩, rfl⟩⟩, j) + +open scoped Classical in +/-- Transforms the indexed data by `Sum.map (b.request A i) (fun e => ⟨i, e⟩)`. -/ +def assign (i : I) : (b.shape i).Goods A → b.Good A := + Sum.map (b.request A i) (fun e => ⟨i, e⟩) + +open scoped Classical in +/-- In the case `.inl (.inl i)`, this construction gives `Tensor.wire K i (b.name i (b.shape +i).dst) 2`. -/ +def tensor : b.Good A → Tensor K I + | .inl (.inl i) => Tensor.wire K i (b.name i (b.shape i).dst) 2 + | .inl (.inr (z, j)) => Tensor.place z.val (A.equivFin.symm j).val + | .inr ⟨i, e⟩ => Tensor.wire K (b.name i e.val.1) (b.name i e.val.2) 2 + +open scoped Classical in +theorem place_tensor (i : I) (a : (b.shape i).Goods A) : + Tensor.place (b.name i) ((b.shape i).tensor A a) = b.tensor A (b.assign A i a) := by + rcases a with (_ | ⟨z, j⟩) | e + · simp only [BallShape.tensor, Tensor.place_wire, b.origin] + rfl + · exact (Tensor.place_comp _ _ _).symm + · exact Tensor.place_wire _ _ _ _ + +omit [Fintype I] [DecidableEq I] [DecidableEq S] in +open scoped Classical in +theorem assign_injective (i : I) : Function.Injective (b.assign A i) := by + unfold assign + apply Sum.map_injective.mpr + constructor + · rintro (_ | ⟨z, j⟩) (_ | ⟨w, k⟩) h + · rfl + · contradiction + · contradiction + · have e := Sum.inr.inj h + have he : b.name i ∘ z = b.name i ∘ w := congrArg (fun p => p.1.val) e + have hj : j = k := congrArg Prod.snd e + have hw : z = w := funext fun s => (b.name i).injective (congrFun he s) + rw [hj, hw] + · exact fun _ _ h => eq_of_heq (Sigma.mk.inj h).2 + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def rates (p : b.Request A → ℝ) : b.Good A → ℝ := Sum.elim p fun _ => 1 + +open scoped Classical in +/-- Shared prices extend arbitrarily outside the set of possible requests. -/ +def quote (p : b.Request A → ℝ) (z : S → I) (a : Tensor K S) : ℝ := + if h : z ∈ Set.range b.tuple ∧ a ∈ A then p (.inr (⟨z, h.1⟩, A.equivFin ⟨a, h.2⟩)) else 0 + +open scoped Classical in +theorem rates_assign (p : b.Request A → ℝ) (i : I) : + b.rates A p ∘ b.assign A i = + (b.shape i).rates A (p (.inl i)) (fun z => b.quote A p (b.name i ∘ z)) := by + funext a + rcases a with (_ | ⟨z, j⟩) | e + · rfl + · have h : b.name i ∘ z ∈ Set.range b.tuple ∧ (A.equivFin.symm j).val ∈ A := + ⟨⟨⟨i, z⟩, rfl⟩, (A.equivFin.symm j).property⟩ + change _ = b.quote A p (b.name i ∘ z) (A.equivFin.symm j).val + simp only [quote, dite_eq_left h, Subtype.eta, Equiv.apply_symm_apply] + rfl + · rfl + +open scoped Classical in +/-- Chooses the market vertex whose local requests include the given request. -/ +def home [Nonempty S] : b.Request A → I + | .inl i => i + | .inr (z, _) => z.val (Classical.arbitrary S) + +open scoped Classical in +/-- Computes the support by the application `Finset.univ.map (b.name i)`. -/ +def support (i : I) := Finset.univ.map (b.name i) + +omit [Fintype I] [DecidableEq I] [DecidableEq S] in +open scoped Classical in +theorem home_mem [Nonempty S] (i : I) (j : (b.shape i).Goods A) (x : b.Request A) + (h : b.assign A i j = .inl x) : b.home A x ∈ b.support i := by + rcases j with (_ | ⟨z, k⟩) | e + · rw [← Sum.inl.inj h] + exact Finset.mem_map.mpr ⟨_, Finset.mem_univ _, b.origin i⟩ + · rw [← Sum.inl.inj h] + exact Finset.mem_map.mpr ⟨_, Finset.mem_univ _, rfl⟩ + · contradiction + +omit [Fintype I] [DecidableEq I] in +open scoped Classical in +theorem card_support (i : I) : (b.support i).card ≤ N := by + simp only [support, Finset.card_map, Finset.card_univ, Fintype.card_fin] + exact Nat.lt_succ_iff.mp (b.size i).isLt + +open scoped Classical in +theorem count_support (x : I) : (Finset.univ.filter fun i => x ∈ b.support i).card ≤ N := by + obtain ⟨U, hU, hu⟩ := b.overlap x + refine (Finset.card_le_card ?_).trans hU + intro i hi + obtain ⟨t, _, ht⟩ := Finset.mem_map.mp (Finset.mem_filter.mp hi).2 + exact hu i t ht + +open scoped Classical in +theorem card_request : + Fintype.card (b.Request A) ≤ Fintype.card I * (1 + N ^ Fintype.card S * A.card) := by + have ht : Fintype.card (Set.range (b.tuple (S := S))) ≤ Fintype.card I * N ^ Fintype.card S := by + refine (Fintype.card_le_of_surjective (Set.rangeFactorization b.tuple) ?_).trans ?_ + · rintro ⟨_, j, rfl⟩ + exact ⟨j, rfl⟩ + · simp only [Fintype.card_sigma, Fintype.card_fun, Site, Fintype.card_fin] + calc + _ ≤ ∑ _ : I, N ^ Fintype.card S := Finset.sum_le_sum fun i _ => + Nat.pow_le_pow_left (Nat.lt_succ_iff.mp (b.size i).isLt) _ + _ = _ := by simp + simp only [Request, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + mul_add, mul_one, ← mul_assoc] + exact Nat.add_le_add_left (Nat.mul_le_mul_right _ ht) _ + +end Market +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Placing all the selected trades + +No greedy packing is needed for the stock bound: each request has a +home site, and only centers whose balls contain that site can affect it. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +open Spectral + +variable {K I S : Type} [Field K] [Fintype I] [DecidableEq I] + [Fintype S] [DecidableEq S] {N : ℕ} {M ρ : ℝ} + (b : Market I N) (A : Finset (Tensor K S)) + +open scoped Classical in +/-- Uses `⟨b.size i, b.shape i⟩` as the representation. -/ +abbrev code (i : I) : Shape N := ⟨b.size i, b.shape i⟩ + +open scoped Classical in +/-- Requires `¬ NearPrices ((b.shape i).tensor A) ((b.shape i).demands A) ρ (b.rates A p ∘ +b.assign A i)`. -/ +def Fails (p : b.Request A → ℝ) (ρ : ℝ) (i : I) : Prop := + ¬ NearPrices ((b.shape i).tensor A) ((b.shape i).demands A) ρ (b.rates A p ∘ b.assign A i) + +open scoped Classical in +/-- Computes the batch by the application `q.trade (b.assign A i) ((b.shape i).links A) m`. -/ +def batch (i : I) (q : (b.code i).Move A) (m : ℕ) : Intervention (b.Request A) b.Edge := + q.trade (b.assign A i) ((b.shape i).links A) m + +variable {A} + +open scoped Classical in +theorem choose_batch (a : Atlas N A M ρ) (hM : 1 ≤ M) + (p : b.Request A → ℝ) (hp : ∀ j, p j ∈ Set.Icc 0 M) + (i : I) (hi : b.Fails A p ρ i) : + ∃ q ∈ a.menu (b.code i), ∀ m, + (b.batch A i q m).Covers (b.tensor A ∘ Sum.inl) (b.tensor A ∘ Sum.inr) ∧ + (b.batch A i q m).Efficient p a.margin a.capacity m := by + let _ : Nonempty (b.Site i) := ⟨(b.shape i).src⟩ + let E := b.shape i + let g := b.assign A i + have h (j : E.Goods A) : b.rates A p (g j) ∈ Set.Icc 0 M := by + cases g j with + | inl x => exact hp x + | inr x => exact ⟨zero_le_one, hM⟩ + obtain ⟨q, hq, hd, _, hw⟩ := (a.detect (b.code i) (b.rates A p ∘ g) + ⟨fun j => (h j).1, fun j => (h j).2⟩).resolve_left hi + have h₁ : ∀ j ∈ q.demand, ∃ l, g j = .inl l := by + intro j hj + obtain ⟨x, _, rfl⟩ := Finset.mem_map.mp (hd hj) + exact ⟨_, rfl⟩ + have h₂ : ∀ j ∈ E.links A, ∃ l, g j = .inr l := by + intro j hj + obtain ⟨x, _, rfl⟩ := Finset.mem_map.mp hj + exact ⟨_, rfl⟩ + have h₃ : ((E.links A).card : ℝ) ≤ E.edges.card := by simp [BallShape.links] + obtain ⟨hb, ho⟩ := a.small _ q hq + refine ⟨q, hq, fun m => ⟨?_, ?_⟩⟩ + · exact q.trade_covers g (E.links A) m h₁ (E.broadcast A) (b.name i) (b.tensor A) + (b.place_tensor A i) + · exact q.trade_efficient g (E.links A) m (b.assign_injective A i) + h₁ h₂ h₃ a.positive.le hw hb ho + +open scoped Classical in +omit [Fintype I] in +theorem batch_overlap [Finite I] [Nonempty S] (J : Finset I) + (q : (i : J) → (b.code i).Move A) (m : ℕ) (x : b.Request A) : + ∃ U : Finset J, U.card ≤ N ∧ ∀ j, (b.batch A j.val (q j) m).affects x → j ∈ U := by + let : Fintype I := Fintype.ofFinite I + let U := Finset.univ.filter fun j : J => b.home A x ∈ b.support j + have h : U.map (Function.Embedding.subtype _) ⊆ + Finset.univ.filter (fun j => b.home A x ∈ b.support j) := by + rintro _ hi + obtain ⟨j, hj, rfl⟩ := Finset.mem_map.mp hi + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, (Finset.mem_filter.mp hj).2⟩ + refine ⟨U, ?_, fun j he => ?_⟩ + · simpa only [Finset.card_map] using (Finset.card_le_card h).trans (b.count_support _) + · obtain ⟨k, hk⟩ := (q j).trade_support _ _ _ he + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, b.home_mem A j k x hk⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +end + +/- +# Choosing a chart by local observations only + +A chart lists a word representing each site of the ball. Its validity +is a finite test of equalities between words at the center. Choosing +from the legal charts therefore needs only a fixed table. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open scoped Pointwise + +variable {G : Type} [Group G] (H : Finset G) (r : ℕ) + +open scoped Classical in +/-- Indexes the board by the coordinates of `Σ s : Shape (H ^ r).card, Fin s.1.val → ↥(H ^ r)`. -/ +abbrev Board := Σ s : Shape (H ^ r).card, Fin s.1.val → ↥(H ^ r) + +namespace Board +variable {H r} + +open scoped Classical in +/-- Computes the site by the application `Fin b.1.1.val`. -/ +abbrev Site (b : Board H r) := Fin b.1.1.val + +open scoped Classical in +/-- The value specified by `(b.2 i).val⁻¹`. -/ +def word (b : Board H r) (i : b.Site) : G := (b.2 i).val⁻¹ + +open scoped Classical in +/-- The valid of type `Prop` for the given inputs. -/ +def Valid (g : G) (x : Root G) (b : Board H r) : Prop := + (∀ i j, x.see (b.word i) (b.word j) = true → i = j) ∧ + (∀ t : ↥(H ^ r), ∃ i, x.see (b.word i) t.val⁻¹ = true) ∧ + x.see (b.word b.1.2.src) 1 = true ∧ x.see (b.word b.1.2.dst) g⁻¹ = true ∧ + ∀ i j, (i, j) ∈ b.1.2.edges ↔ ∃ t : H, + x.see (t.val⁻¹ * b.word i) (b.word j) = true ∨ + x.see (t.val⁻¹ * b.word j) (b.word i) = true + +open scoped Classical in +/-- Uses `⟨x.label (b.word i), mem_ball _ (b.2 i).property⟩` as the representation. -/ +def name (x : Root G) (b : Board H r) (i : b.Site) : ball H r x.center := + ⟨x.label (b.word i), mem_ball _ (b.2 i).property⟩ + +open scoped Classical in +theorem valid_iff (g : G) (x : Root G) (b : Board H r) : + Valid g x b ↔ Function.Bijective (name x b) ∧ + (name x b b.1.2.src).val = x.center ∧ (name x b b.1.2.dst).val = g⁻¹ • x.center ∧ + ∀ i j, (i, j) ∈ b.1.2.edges ↔ link H (name x b i).val (name x b j).val ∨ + link H (name x b j).val (name x b i).val := by + simp only [Valid, Root.see, decide_eq_true_eq] + simp only [Root.label, one_smul, mul_smul] + have hi : (∀ i j, b.word i • x.center = b.word j • x.center → i = j) ↔ + Function.Injective (name x b) := + ⟨fun h _ _ he => h _ _ (congrArg Subtype.val he), fun h _ _ he => h (Subtype.ext he)⟩ + have hs : (∀ t : ↥(H ^ r), ∃ i, b.word i • x.center = t.val⁻¹ • x.center) ↔ + Function.Surjective (name x b) := by + constructor + · rintro h ⟨y, hy⟩ + obtain ⟨t, ht, rfl⟩ := Finset.mem_image.mp hy + obtain ⟨i, hi⟩ := h ⟨t, ht⟩ + exact ⟨i, Subtype.ext hi⟩ + · intro h t + obtain ⟨i, hi⟩ := h ⟨_, mem_ball _ t.property⟩ + exact ⟨i, congrArg Subtype.val hi⟩ + rw [hi, hs, ← and_assoc] + simp only [Function.Bijective, name, Root.label, link, exists_or, Subtype.exists, exists_prop] + +variable (H) (hH : 1 ∈ H) (r) (g : G) + (hg : letI := Classical.decEq G; g ∈ H ^ r) + +include hH hg in +open scoped Classical in +theorem exists_valid (x : Root G) : ∃ b : Board H r, Valid g x b := by + let V := ball H r x.center + let e := V.equivFin + let s := BallShape.chart e ⟨x.center, center_mem_ball hH r x.center⟩ + ⟨g⁻¹ • x.center, mem_ball _ hg⟩ (link H) (ball_connected hH r _) + have hs (i : Fin V.card) : ∃ a : ↥(H ^ r), a.val⁻¹ • x.center = (e.symm i).val := by + obtain ⟨a, ha, he⟩ := Finset.mem_image.mp (e.symm i).property + exact ⟨⟨a, ha⟩, he⟩ + choose w hw using hs + let b : Board H r := ⟨⟨⟨V.card, Nat.lt_succ_of_le Finset.card_image_le⟩, s⟩, w⟩ + have he : name x b = e.symm := funext fun i => Subtype.ext (hw i) + refine ⟨b, (valid_iff _ _ _).mpr ?_⟩ + rw [he] + exact ⟨e.symm.bijective, congrArg Subtype.val (e.symm_apply_apply _), + congrArg Subtype.val (e.symm_apply_apply _), fun _ _ => by simp [b, s, BallShape.chart]⟩ + +open scoped Classical in +/-- The value specified by `Classical.choose (exists_valid H r hH g hg x)`. -/ +def choose (x : Root G) : Board H r := Classical.choose (exists_valid H r hH g hg x) + +open scoped Classical in +theorem valid_choose (x : Root G) : Valid g x (choose H r hH g hg x) := + Classical.choose_spec (exists_valid H r hH g hg x) + +open scoped Classical in +theorem local_choose : Root.Local (choose H r hH g hg) := by + let V := (H ^ r)⁻¹ + let W := insert 1 (insert g⁻¹ (V ∪ H⁻¹ * V)) + have hV (t : ↥(H ^ r)) : t.val⁻¹ ∈ V := by simp [V] + have hv (t : ↥(H ^ r)) : t.val⁻¹ ∈ W := by simp [W, hV t] + have hw (t : H) (u : ↥(H ^ r)) : t.val⁻¹ * u.val⁻¹ ∈ W := by + have h : t.val⁻¹ * u.val⁻¹ ∈ H⁻¹ * V := Finset.mul_mem_mul (by simp) (hV u) + simp [W, h] + refine ⟨W, fun x y he => ?_⟩ + have same : Valid (H := H) (r := r) g x = Valid g y := by + funext b + have h (i : b.Site) (u : ↥(H ^ r)) : x.see (b.word i) u.val⁻¹ = y.see (b.word i) u.val⁻¹ := + he _ (hv (b.2 i)) _ (hv u) + have h' (i j : b.Site) : x.see (b.word i) (b.word j) = y.see (b.word i) (b.word j) := + h i (b.2 j) + have hm (i j : b.Site) (t : H) : + x.see (t.val⁻¹ * b.word i) (b.word j) = y.see (t.val⁻¹ * b.word i) (b.word j) := + he _ (hw t (b.2 i)) _ (hv (b.2 j)) + have h₀ := he (b.word b.1.2.src) (hv _) 1 (by simp [W]) + have h₁ := he (b.word b.1.2.dst) (hv _) g⁻¹ (by simp [W]) + simp only [Valid, h, h', hm, h₀, h₁] + unfold choose + congr + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Install.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Install.lean new file mode 100644 index 0000000000..7053eb7d8e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Install.lean @@ -0,0 +1,550 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Rig +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Focus +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.Table +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Wired +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Packets + +/-! +# Local profiles of a branch + +The inventory protocol computes a local linear kernel in abstract +coordinates. Read its demand coordinates in the two exterior arrays +and its supply coordinates at their assigned physical sockets. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig + +open Coloring Transport + +variable {F : Type} [Field F] {m h : ℕ} (T : Routes F m) (s : Rig T.params) + (σ : Equiv.Perm (B h)) + +open scoped Classical in +/-- The value specified by `letI := T.action h σ T.params.balls (Site h)`. -/ +abbrev arena := + letI := T.action h σ + T.params.balls (Site h) + +open scoped Classical in +/-- The value specified by `letI := T.action h σ s.clock.path (Site h)`. -/ +abbrev Path := + letI := T.action h σ + s.clock.path (Site h) + +open scoped Classical in +/-- The value specified by `letI := T.action h σ s.widthAt u`. -/ +abbrev requests (u : Path T s σ) : (arena T σ).Edge → ℕ := + letI := T.action h σ + s.widthAt u + +open scoped Classical in +/-- The value specified by `letI := T.action h σ s.clock.selector u`. -/ +abbrev choose (u : Path T s σ) : Site h → B s.clock.bits := + letI := T.action h σ + s.clock.selector u + +open scoped Classical in +/-- Embeds `Protocol.End (requests T s σ u)` into `Port h s.p`. -/ +abbrev place (u : Path T s σ) : Protocol.End (requests T s σ u) ↪ Port h s.p := + letI := T.action h σ + s.endpoints u + +open scoped Classical in +/-- The value specified by `(arena T σ).name e.1 e.2.val.1`. -/ +abbrev src (e : (arena T σ).Edge) := (arena T σ).name e.1 e.2.val.1 +open scoped Classical in +/-- The value specified by `(arena T σ).name e.1 e.2.val.2`. -/ +abbrev dst (e : (arena T σ).Edge) := (arena T σ).name e.1 e.2.val.2 + +open scoped Classical in +/-- Uses `Protocol.Demand F σ s.clock.width` as the representation. -/ +abbrev initial := Protocol.Demand F σ s.clock.width +open scoped Classical in +/-- The value specified by `Protocol.Links F (src T σ) (dst T σ) (requests T s σ u)`. -/ +abbrev result (u : Path T s σ) := Protocol.Links F (src T σ) (dst T σ) (requests T s σ u) + +open scoped Classical in +theorem target_at (i : Site h) : + (arena T σ).name i ((arena T σ).shape i).dst = inflate h σ i := by + let _ := T.action h σ + change (market _ _ _ _ _).name i ((market _ _ _ _ _).shape i).dst = _ + rw [market_dst, inv_inv] + exact T.target_action h σ i + +open scoped Classical in +/-- The execute of type `let b` for the given inputs. -/ +def execute {G J I : Type} [Group G] {U : J → Subgroup G} {g : G} + {a : Parameters F U g} (s : Rig a) [Fintype I] [Nonempty I] [MulAction G I] : + let b := a.balls I + (Protocol.Board.orders (Protocol.request b a.table) + (Stock.copies (b.payload a.table) s.clock.width)).Expansion + (fun u : s.clock.path I => Protocol.Board.orders (Protocol.edge F b) (s.widthAt u)) := + Protocol.program (a.balls I) a.offers + (marketPorts (I := I) a.core a.radius a.unit g a.reach s.w s.hw) + s.clock.height a.nz s.clock.room s.clock.μ a.path s.clock.width + (a.ready I) a.local_supply (s.clock.runs I) + +open scoped Classical in +/-- The indexed operation `(s.execute (I := Site h)).rename (Protocol.demandRename (a.balls +(Site h)) a.table σ s.clock.width hc) (fun _ => .refl _)`. -/ +def transfer {G J : Type} [Group G] {U : J → Subgroup G} {g : G} + {a : Parameters F U g} (s : Rig a) [MulAction G (Site h)] + (hc : ∀ i : Site h, (a.balls (Site h)).name i ((a.balls (Site h)).shape i).dst + = inflate h σ i) : + (Protocol.Demand F σ s.clock.width).Expansion + (fun u : s.clock.path (Site h) => + Protocol.Board.orders (Protocol.edge F (a.balls (Site h))) (s.widthAt u)) := + (s.execute (I := Site h)).rename + (Protocol.demandRename (a.balls (Site h)) a.table σ s.clock.width hc) (fun _ => .refl _) + +open scoped Classical in +/-- The operator of type `(initial T s σ).Expansion (result T s σ)`, constructed using `T.action +h σ`. -/ +def operator : (initial T s σ).Expansion (result T s σ) := by + let _ := T.action h σ + exact transfer σ s (target_at T σ) + +open scoped Classical in +/-- Returns `.inr x.val.1.2` when `(x.val.2 : Bool) = true` holds, and `.inl x.val.1.2` +otherwise. -/ +def side (i : Site h) (x : (initial T s σ).localPort i) : Fin s.clock.width ⊕ Fin s.clock.width := + if (x.val.2 : Bool) = true then .inr x.val.1.2 else .inl x.val.1.2 + +open scoped Classical in +/-- The value specified by `(place T s σ u x.val).2`. -/ +def channel (u : Path T s σ) (i : Site h) (x : (result T s σ u).localPort i) : B s.p := + (place T s σ u x.val).2 + +open scoped Classical in +/-- The data for the example construction, including `h`, `σ`, `u`, `i`. -/ +structure Example where + /-- The `Example` field of type `ℕ`. -/ + h : ℕ + /-- The `Example` component of type `Equiv.Perm (B h)`. -/ + σ : Equiv.Perm (B h) + /-- The `Example` component of type `Path T s σ`. -/ + u : Path T s σ + /-- The `Example` component of type `Site h`. -/ + i : Site h + +open scoped Classical in +/-- The value specified by `((operator T s t.σ).kernel t.u t.i).pull (side T s t.σ t.i) (channel +T s t.σ t.u t.i)`. -/ +def sample (t : Example T s) : Profile F s.p s.clock.width := + ((operator T s t.σ).kernel t.u t.i).pull (side T s t.σ t.i) (channel T s t.σ t.u t.i) + +open scoped Classical in +/-- Uses `⟨@Root.mk _ _ _ (T.action t.h t.σ) t.i, choose T s t.σ t.u⟩` as the representation. -/ +def observed (t : Example T s) : s.clock.Input := + ⟨@Root.mk _ _ _ (T.action t.h t.σ) t.i, choose T s t.σ t.u⟩ + +open scoped Classical in +/-- The compatible of type `Prop`, constructed using `observed T s x`. -/ +def Compatible : Prop := + ∃ E : Finset (controllers F T.embed), ∀ x y : Example T s, + let u := observed T s x + let v := observed T s y + Root.Agree E u.toRoot v.toRoot → + (∀ i ∈ E, u.mark (u.label i) = v.mark (v.label i)) → sample T s x = sample T s y + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +end + +/- +# The finite menu of local profiles + +A profile can depend on the branch only through finitely many +observations. Record these observations, the local guard, and the +enable mask. A class with no representative receives weight zero. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig + +open Coloring Transport + +variable {F : Type} [Field F] {m : ℕ} (T : Routes F m) (s : Rig T.params) + +open scoped Classical in +/-- The value specified by `(s.bank.program T.params.unit _ T.params.reach s.count x j).1`. -/ +abbrev active (x : s.clock.Input) (j : B s.p) := + (s.bank.program T.params.unit _ T.params.reach s.count x j).1 + +open scoped Classical in +/-- The value specified by `(sample T s v).mask (s.clock.guard s.w (observed T s v)) (active T s +(observed T s v))`. -/ +def masked (v : Example T s) : Profile F s.p s.clock.width := + (sample T s v).mask (s.clock.guard s.w (observed T s v)) (active T s (observed T s v)) + +open scoped Classical in +/-- The data for the palette construction, including `l`, `key`, `local_key`, `table`, `fast`. -/ +structure Palette where + /-- The `Palette` field of type `ℕ`. -/ + l : ℕ + /-- The `Palette` component of type `s.clock.Input → B l`. -/ + key : s.clock.Input → B l + local_key : Decor.Local key + /-- The local table at each indexed position carried by `Palette`, with type `B l → Profile F + s.p s.clock.width`. -/ + table : B l → Profile F s.p s.clock.width + fast : ∀ i, Protocol.Frame.Fast (table i) + agrees : ∀ v, table (key (observed T s v)) = masked T s v + valid : ∀ x z a c, table (key x) z a c ≠ 0 → + s.clock.guard s.w x = true ∧ ∀ j, active T s x j ≠ true → ∀ i, c j i = false + +open scoped Classical in +private abbrev Pattern (E : Finset (controllers F T.embed)) := + ((↥E → ↥E → Bool) × (↥E → B s.clock.bits)) × Bool × (B s.p → Bool) + +open scoped Classical in +private def pattern (E : Finset (controllers F T.embed)) (x : s.clock.Input) : Pattern T s E := + ((fun i j => x.see i j, fun i => x.mark (x.label i)), s.clock.guard s.w x, active T s x) + +open scoped Classical in +private theorem pattern_local (E : Finset (controllers F T.embed)) : + Decor.Local (pattern T s E) := by + have ho : Decor.Local (fun x : s.clock.Input => (pattern T s E x).1) := + ⟨E, fun _ _ hh hm => Prod.ext (funext fun i => funext fun j => hh _ i.property _ j.property) + (funext fun i => hm _ i.property)⟩ + have he := s.bank.program_local T.params.unit _ T.params.reach s.count + (s.clock.count_local s.w s.j₀) + exact ho.pair ((s.clock.guard_local s.w).pair (he.map (fun v j => (v j).1))) + +open scoped Classical in +theorem palette (he : Compatible T s) : Nonempty (Palette T s) := by + obtain ⟨E, hE⟩ := he + let code := Coloring.encode (Pattern T s E) + let k := code ∘ pattern T s E + have same (x y : Example T s) (eq : k (observed T s x) = k (observed T s y)) : + masked T s x = masked T s y := by + have e := code.injective eq + have hs := hE x y + (fun i hi j hj => congrArg (fun z => z.1.1 ⟨i, hi⟩ ⟨j, hj⟩) e) + (fun i hi => congrArg (fun z => z.1.2 ⟨i, hi⟩) e) + exact congrArg₂ (fun (f : Profile F s.p s.clock.width) v => f.mask v.1 v.2) + hs (congrArg Prod.snd e) + let off : Profile F s.p s.clock.width := Protocol.Frame.diagonal (fun _ _ => 0) + let f i := if h : ∃ v, k (observed T s v) = i then masked T s h.choose else off + refine ⟨⟨_, k, (pattern_local T s E).map code, f, ?_, ?_, ?_⟩⟩ + · intro i + dsimp only [f] + split + · rename_i hh + apply Profile.mask_fast + exact ((operator T s hh.choose.σ).fast _ _).pull _ _ + · exact Protocol.Frame.fast_diagonal _ + · intro v + have hv : ∃ u, k (observed T s u) = k (observed T s v) := ⟨v, rfl⟩ + simp only [f, dite_eq_left hv] + exact same _ _ hv.choose_spec + · intro x z a c hn + dsimp only [f] at hn + split at hn + · rename_i hv + have eq := congrArg Prod.snd (code.injective hv.choose_spec) + obtain ⟨hg, ha⟩ := Prod.mk.inj eq + unfold masked Profile.mask at hn + rw [hg, ha] at hn + by_contra hh + exact hn (ite_eq_right hh) + · simp [off, Protocol.Frame.diagonal] at hn + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +end + +/- # Resolving profile and slot commands at every site -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +open Coloring Transport + +variable {F : Type} [Field F] {m h : ℕ} (T : Routes F m) (s : Rig T.params) + (P : Palette T s) + +open scoped Classical in +/-- The quantity computed by `Format.vec (h + 1) (.addr s.clock.bits)`. -/ +abbrev Selectors (h : ℕ) := Format.vec (h + 1) (.addr s.clock.bits) +open scoped Classical in +/-- Computes the commands by the application `Controls h s.p (.addr P.l)`. -/ +abbrev Commands (h : ℕ) := Controls h s.p (.addr P.l) + +open scoped Classical in +/-- Uses `⟨@Root.mk _ _ _ (T.action h σ) i, z⟩` as the representation. -/ +def atSite (σ : Equiv.Perm (B h)) (z : (Selectors T s h).obj) (i : Site h) : s.clock.Input := + ⟨@Root.mk _ _ _ (T.action h σ) i, z⟩ + +open scoped Classical in +/-- The data for the engine construction, including `f`, `group`, `resolves`, `groups`. -/ +structure Engine (h : ℕ) where + /-- The `Engine` component of type `((Perm h).pair (Selectors T s h)).obj → (Commands T s P + h).obj`. -/ + f : ((Perm h).pair (Selectors T s h)).obj → (Commands T s P h).obj + /-- The `Engine` component of type `Port h s.p → ℕ`. -/ + group : Port h s.p → ℕ + resolves : ∀ σ : Equiv.Perm (B h), ∀ z i, f (σ, z) i = + Decor.resolve (s.program P.key (atSite T s σ z i)) + (fun j => (T.action h σ).smul (s.bank.hop j) i) + groups : ∀ σ x y i j, s.bank.generator T.params.unit i = s.bank.generator T.params.unit j → + (T.action h σ).smul (s.bank.generator T.params.unit i).val x = y → + group (x, i) = group (y, j) + +namespace Engine + +variable {T s P} (H : Engine T s P h) (σ : Equiv.Perm (B h)) + +open scoped Classical in +/-- Builds `System F h s.p s.clock.width (2 ^ z) where selector` with the specified `selector`, +`config`, `group`, `dispatch`. -/ +abbrev system (z : ℕ) : System F h s.p s.clock.width (2 ^ z) where + selector := Selectors T s h + config := .addr P.l + group := H.group + dispatch := H.f + kernel i := (P.table i).apply z + +open scoped Classical in +theorem key (z : (Selectors T s h).obj) (i : Site h) : + (H.f (σ, z) i).1 = P.key (atSite T s σ z i) := by rw [H.resolves]; rfl + +open scoped Classical in +theorem orders (z : (Selectors T s h).obj) : + letI := T.action h σ + commands (H.f (σ, z)) = s.bank.orders T.params.unit _ T.params.reach s.count z := by + funext ⟨i, j⟩ + unfold commands + rw [H.resolves] + rfl + +open scoped Classical in +theorem enabled (z : (Selectors T s h).obj) (i : Site h) (j : B s.p) : + (i, j) ∈ Enabled (commands (H.f (σ, z))) ↔ active T s (atSite T s σ z i) j = true := by + simp only [Enabled, Finset.mem_filter, Finset.mem_univ, true_and] + rw [H.orders] + rfl + +open scoped Classical in +/-- The placement of type `Protocol.Placement (src T σ) (dst T σ) (requests T s σ u) H.group +(commands (H.f (σ, choose T s σ u)))`, constructed using `T.action h σ`. -/ +def placement (u : Path T s σ) : + Protocol.Placement (src T σ) (dst T σ) (requests T s σ u) H.group + (commands (H.f (σ, choose T s σ u))) := by + let _ := T.action h σ + exact s.bank.placement T.params.unit _ T.params.reach s.count (s.clock.selector u) (s.widthAt u) + (s.bounded u) (s.clock.count_branch s.w s.j₀ s.hw s.h₀ u) + H.group (H.groups σ) _ (H.orders σ _) + +end Engine +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +end + +/- # Reading a branch kernel at its physical pins -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +open Coloring Transport + +variable {F : Type} [Field F] {m h z : ℕ} (T : Routes F m) (s : Rig T.params) + (σ : Equiv.Perm (B h)) (u : Path T s σ) (i : Site h) + +open scoped Classical in +theorem sample_apply {group : Port h s.p → ℕ} {a : Orders h s.p} + (P : Protocol.Placement (src T σ) (dst T σ) (requests T s σ u) group a) + (hP : P.embed = place T s σ u) (x y : Site h → Data s.clock.width (2 ^ z)) + (c : Site h → Channels s.p (2 ^ z)) : + (sample T s ⟨h, σ, u, i⟩).apply z (x i) (y i) (c i) = + (operator T s σ).kernel u i z ((initial T s σ).view i (Protocol.outside σ _ x y)) + ((result T s σ u).view i (P.inside c)) := by + unfold sample Profile.apply Protocol.Frame.pull + refine congrArg₂ ((operator T s σ).kernel u i z) ?_ ?_ + · funext ⟨⟨⟨j, k⟩, b⟩, e⟩ t + let v := Sum.elim (Function.curry (x i)) (Function.curry (y i)) + cases b + · have hs : side T s σ i ⟨⟨⟨j, k⟩, false⟩, e⟩ = .inl k := ite_eq_right Bool.false_ne_true + change v (side T s σ i ⟨⟨⟨j, k⟩, false⟩, e⟩) t = x j (k, t) + rw [hs] + exact congrArg (fun l => x l (k, t)) (show j = i from e).symm + · have hs : side T s σ i ⟨⟨⟨j, k⟩, true⟩, e⟩ = .inr k := ite_eq_left rfl + change v (side T s σ i ⟨⟨⟨j, k⟩, true⟩, e⟩) t = y (inflate h σ j) (k, t) + rw [hs] + exact congrArg (fun l => y l (k, t)) (show inflate h σ j = i from e).symm + · funext k t + have he : (P.embed k.val).1 = i := (P.owner _).trans k.property + change c i ((place T s σ u k.val).2, t) = c (P.embed k.val).1 ((P.embed k.val).2, t) + rw [he, hP] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +end + +/- +# Correctness of the programmed transport + +Every surviving selector describes exactly one legal branch. Its +disabled slots are pinned to zero. On all other slots the program +executes the physical copy of the branch kernel. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +open Coloring Transport + +variable {F : Type} [Field F] {m h z : ℕ} + +open scoped Classical in +private theorem injective_selector {G J I : Type} [Group G] {U : J → Subgroup G} {g : G} + {a : Parameters F U g} (s : Rig a) [Fintype I] [MulAction G I] : + Function.Injective (s.clock.selector (I := I)) := + (a.balls I).selector_injective a.offers s.clock.batch s.clock.bound s.clock.μ a.path s.clock.width + +namespace Engine +variable {T : Routes F m} {s : Rig T.params} {P : Palette T s} (H : Engine T s P h) + (σ : Equiv.Perm (B h)) + +open scoped Classical in +private def codes : Path T s σ ↪ (Selectors T s h).obj := by + let _ := T.action h σ + exact ⟨choose T s σ, s.injective_selector⟩ + +open scoped Classical in +private theorem eligible (t : (Selectors T s h).obj) : + (∀ i, s.clock.guard s.w (atSite T s σ t i) = true) ↔ ∃ u, choose T s σ u = t := by + let _ := T.action h σ + have ht := s.clock.guard_iff s.w s.hw t + refine ⟨fun h => (ht.mp h).exists, fun ⟨u, hu⟩ => ht.mpr ⟨u, hu, ?_⟩⟩ + exact fun v hv => s.injective_selector (hv.trans hu.symm) + +open scoped Classical in +theorem agrees (u : Path T s σ) (x y : Site h → Data s.clock.width (2 ^ z)) + (c : Site h → Channels s.p (2 ^ z)) (hc : Protocol.Padded (commands (H.f (σ, + choose T s σ u))) c) + (i : Site h) : + (P.table (H.f (σ, choose T s σ u) i).1).apply z (x i) (y i) (c i) = + (operator T s σ).kernel u i z ((initial T s σ).view i (Protocol.outside σ _ x y)) + ((result T s σ u).view i ((H.placement σ u).inside c)) := by + let e : Example T s := ⟨h, σ, u, i⟩ + rw [H.key] + change (P.table (P.key (observed T s e))).apply _ _ _ _ = _ + rw [P.agrees] + have hg : s.clock.guard s.w (observed T s e) = true := + (eligible σ (choose T s σ u)).mpr ⟨u, rfl⟩ i + have hy : ∀ j, active T s (observed T s e) j ≠ true → ∀ k, c i (j, k) = false := by + intro j hj + exact hc (i, j) (mt (H.enabled σ _ i j).mp hj) + trans (sample T s e).apply z (x i) (y i) (c i) + · exact ite_eq_left ⟨hg, hy⟩ + · exact sample_apply T s σ u i _ rfl x y c + +open scoped Classical in +private theorem surviving (t : (Selectors T s h).obj) (x y : Site h → Data s.clock.width (2 ^ z)) + (c : Site h → Channels s.p (2 ^ z)) (hne : (H.system z).value (H.f (σ, t)) x y c ≠ 0) : + (∃ u, choose T s σ u = t) ∧ Protocol.Padded (commands (H.f (σ, t))) c := by + have hi (i : Site h) : s.clock.guard s.w (atSite T s σ t i) = true ∧ + ∀ j, active T s (atSite T s σ t i) j ≠ true → ∀ k, c i (j, k) = false := by + have hw := Finset.prod_ne_zero_iff.mp hne i (Finset.mem_univ _) + change (P.table (H.f (σ, t) i).1).apply z (x i) (y i) (c i) ≠ 0 at hw + rw [H.key] at hw + exact P.valid _ _ _ _ hw + refine ⟨(eligible σ t).mp (fun i => (hi i).1), ?_⟩ + rintro ⟨i, j⟩ hij k + exact (hi i).2 _ (mt (H.enabled σ t i j).mpr hij) k + +open scoped Classical in +theorem width (u : Path T s σ) : + 2 * (∑ e, requests T s σ u e) ≤ 4812 * s.clock.width * 2 ^ h := by + let _ := T.action h σ + have he := s.clock.width_total s.w s.hw u + change (∑ e, requests T s σ u e) ≤ 1203 * Fintype.card (Site h) * s.clock.width at he + rw [show Fintype.card (Site h) = 2 ^ h * 2 by simp [pow_succ]] at he + exact (Nat.mul_le_mul_left 2 he).trans_eq (by ring) + +open scoped Classical in +theorem correct (z : ℕ) : (H.system z).Correct 4812 := by + apply Protocol.system_correct + intro σ + exact ⟨{ + E := (arena T σ).Edge + I := Path T s σ + src := src T σ + dst := dst T σ + m := requests T s σ + proc := operator T s σ + choose := codes σ + place := H.placement σ + cost := width σ + agrees := H.agrees σ + invalid := H.surviving σ + }⟩ + +end Engine +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Rig +end + +/- +# Uniform routing across widths + +Choose a height ratio before fixing the menu. All overhead depending +on the menu can be absorbed into the eventual height cutoff and a +polynomial cost exponent. The bound on transported width stays 4812. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Coloring Transport + +open scoped Classical in +private theorem heights (τ : ℝ) (hτ : 0 < τ) : + ∃ m : ℕ, 0 < m ∧ ∀ K : ℕ, ∀ᶠ h : ℕ in Filter.atTop, + h / m + K ≤ h ∧ (↑(h / m + K) : ℝ) ≤ τ * h := by + obtain ⟨m, hm⟩ := exists_nat_gt (max 2 (2 / τ)) + have hm' : 2 < m := by exact_mod_cast (lt_of_le_of_lt (le_max_left _ _) hm) + have ht : 2 ≤ (m : ℝ) * τ := ((div_lt_iff₀ hτ).mp ((le_max_right _ _).trans_lt hm)).le + refine ⟨m, by omega, fun K => ?_⟩ + filter_upwards [Filter.eventually_ge_atTop (K * m)] with h hh + have he : (h / m + K) * m ≤ 2 * h := by + rw [add_mul, two_mul] + exact Nat.add_le_add (Nat.div_mul_le_self h m) hh + constructor + · have := (Nat.mul_le_mul_left (h / m + K) hm'.le).trans he + omega + · apply le_of_mul_le_mul_right _ (by exact_mod_cast (by omega : 0 < m) : (0 : ℝ) < m) + have hh' : (↑(h / m + K) : ℝ) * m ≤ 2 * h := by exact_mod_cast he + exact hh'.trans (by nlinarith only [mul_le_mul_of_nonneg_right ht (Nat.cast_nonneg h)]) + +variable {F : Type} [Field F] + +open scoped Classical in +theorem local_of_routes + (routes : ∀ m : ℕ, 0 < m → ∃ (T : Routes F m) (s : Rig T.params), Rig.Compatible T s) : + LocalProtocol F := by + refine ⟨4812, fun τ hτ => ?_⟩ + obtain ⟨m, hm, hcut⟩ := heights τ hτ + obtain ⟨T, s, hr⟩ := routes m hm + obtain ⟨P⟩ := Rig.palette T s hr + obtain ⟨d, k, hd⟩ := (s.program_local P.local_key).dispatch (T := T) s.bank.hop + obtain ⟨c, hc⟩ := profile_weight P.table P.fast + refine ⟨s.p, s.clock.width, max d c, s.clock.wide, ?_⟩ + filter_upwards [hcut (T.overhead + s.p + 22), Filter.eventually_ge_atTop k] with h hb hk + obtain ⟨f, hf, he⟩ := hd h hk + let b := h / m + T.overhead + obtain ⟨g, hg, hm⟩ := T.portGroup h b s.p le_rfl (by dsimp [b]; omega) + (s.bank.generator T.params.unit) + let engine : Rig.Engine T s P h := ⟨f, g, he, hm⟩ + refine ⟨b + s.p + 22, Nat.add_le_add_right (Nat.le_add_left ..) 22, + by dsimp [b]; omega, ?_, fun j _ => ?_⟩ + · simpa [b, Nat.add_assoc] using hb.2 + · refine ⟨engine.system j, engine.correct j, ?_, hf.mono (le_max_left ..), ?_⟩ + · exact fun i => (hg i).trans (Nat.pow_le_pow_right (by decide) (by omega)) + · exact (hc j).mono (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) (le_max_right ..))) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Keys.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Keys.lean new file mode 100644 index 0000000000..6588ee7c59 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Keys.lean @@ -0,0 +1,766 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Decor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Packets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Parameters +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Alignment + +/-! +# Ordering disjoint blocks by local keys + +Only the keys of nonempty blocks need to be distinct. In particular +unused centers do not need to be globally ordered. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Finset +variable {J : Type} [Fintype J] (v key : J → ℕ) + +/-- The sum of `v i` indexed by `i ∈ univ.filter (fun i => key i < key j)`. -/ +def offset (j : J) := ∑ i ∈ univ.filter (fun i => key i < key j), v i + +theorem offset_le (j : J) (A : Finset J) (hA : ∀ i, key i ≤ key j → i ∈ A) : + offset v key j + v j ≤ ∑ i ∈ A, v i := by + classical + let S := univ.filter fun i => key i < key j + have he : j ∉ S := by simp [S] + have hs : insert j S ⊆ A := insert_subset (hA j le_rfl) + (fun i hi => hA i (mem_filter.mp hi).2.le) + have h := sum_le_sum_of_subset (f := v) hs + rw [sum_insert he, add_comm] at h + exact h + +/-- The indexed operation `⟨offset v key u.1 + u.2.val, (Nat.add_lt_add_left u.2.isLt +_).trans_le (offset_le v key u.1 univ (fun i _ => mem_univ i))⟩`. -/ +def offsetIndex (u : Σ j, Fin (v j)) : Fin (∑ i, v i) := + ⟨offset v key u.1 + u.2.val, + (Nat.add_lt_add_left u.2.isLt _).trans_le (offset_le v key u.1 univ (fun i _ => mem_univ i))⟩ + +theorem offset_lt {u z : Σ j, Fin (v j)} (h : key u.1 < key z.1) : + offsetIndex v key u < offsetIndex v key z := by + have e : offset v key u.1 + v u.1 ≤ offset v key z.1 := + offset_le v key _ _ fun i hi => mem_filter.mpr ⟨mem_univ _, hi.trans_lt h⟩ + exact ((Nat.add_lt_add_left u.2.isLt _).trans_le e).trans_le (Nat.le_add_right _ _) + +/-- The condition `∀ i j, v i ≠ 0 → v j ≠ 0 → key i = key j → i = j` on the specified data. -/ +def Ordered : Prop := ∀ i j, v i ≠ 0 → v j ≠ 0 → key i = key j → i = j + +/-- Bundles the indexing function as an equivalence. -/ +def pack (h : Ordered v key) : (Σ j, Fin (v j)) ≃ Fin (∑ i, v i) := + Equiv.ofBijective (offsetIndex v key) (by + rw [Fintype.bijective_iff_injective_and_card] + refine ⟨?_, by simp⟩ + rintro ⟨i, x⟩ ⟨j, y⟩ he + have hk : key i = key j := by + rcases lt_trichotomy (key i) (key j) with h | h | h + · exact ((offset_lt v key (u := ⟨i, x⟩) (z := ⟨j, y⟩) h).ne he).elim + · exact h + · exact ((offset_lt v key (u := ⟨j, y⟩) (z := ⟨i, x⟩) h).ne he.symm).elim + have hij := h i j (Nat.ne_of_gt (Nat.zero_lt_of_lt x.isLt)) + (Nat.ne_of_gt (Nat.zero_lt_of_lt y.isLt)) hk + subst j + exact congrArg (fun t : Fin (v i) => (⟨i, t⟩ : Σ j, Fin (v j))) + (Fin.ext (Nat.add_left_cancel (congrArg Fin.val he)))) + +theorem pack_val (h : Ordered v key) (j : J) (i : Fin (v j)) : + (pack v key h ⟨j, i⟩).val = offset v key j + i := rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Decor + +variable {G : Type} [Group G] {q : ℕ} {X : Type*} + +open scoped Classical in +/-- Uses `⟨r.toRoot.shift a, r.mark⟩` as the representation. -/ +def shift (a : G) (r : Decor G q) : Decor G q := ⟨r.toRoot.shift a, r.mark⟩ + +open scoped Classical in +theorem Local.shift {f : Decor G q → X} (h : Local f) (a : G) : Local (f ∘ Decor.shift a) := by + obtain ⟨E, hE⟩ := h + refine ⟨E.image (· * a), fun r s he hm => hE _ _ ?_ ?_⟩ + · intro x hx y hy + have hh := he _ (Finset.mem_image_of_mem _ hx) _ (Finset.mem_image_of_mem _ hy) + simp only [Root.see, Root.label, Decor.shift, Root.shift, mul_smul] at hh ⊢ + exact hh + · intro x hx + have hh := hm _ (Finset.mem_image_of_mem _ hx) + simp only [Root.label, Decor.shift, Root.shift, mul_smul] at hh ⊢ + exact hh + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Decor +end + +/- +# Addressing overlapping action balls + +Two centers are neighbors precisely when they differ by a product +of two radius words, one inverted. A fixed list enumerates these +products, and its first occurrence of each label is used. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open scoped Pointwise + +variable {G I : Type} [Group G] [MulAction G I] (H : Finset G) (r : ℕ) + +namespace Root + +variable {t : ℕ} (w : Fin (2 ^ t) → G) + +open scoped Classical in +/-- The subset of all indices on which the defining predicate holds. -/ +def first (x : Root G) := Finset.univ.filter fun j : Fin (2 ^ t) => + ∀ l, x.see (w l) (w j) = true → j ≤ l + +open scoped Classical in +theorem local_first : Local (first w) := by + have h : Local (fun x : Root G => fun j l => x.see (w l) (w j)) := + local_pi fun j => local_pi fun l => local_see _ _ + exact h.map (fun f => Finset.univ.filter fun j => ∀ l, f j l = true → j ≤ l) + +open scoped Classical in +theorem first_char (x : Root G) (j : Fin (2 ^ t)) : + j ∈ x.first w ↔ ∀ l, x.label (w l) = x.label (w j) → j ≤ l := by + simp only [first, Finset.mem_filter, Finset.mem_univ, true_and, see, decide_eq_true_eq] + +open scoped Classical in +theorem first_distinct (x : Root G) : Set.InjOn (fun j => x.label (w j)) (x.first w) := + fun _ hi _ hj he => le_antisymm ((first_char _ _ _).mp hi _ he.symm) + ((first_char _ _ _).mp hj _ he) + +open scoped Classical in +theorem first_rep (x : Root G) (j : Fin (2 ^ t)) : + ∃ i ∈ x.first w, x.label (w i) = x.label (w j) := by + let u := Finset.univ.filter fun l => x.label (w l) = x.label (w j) + have hu : u.Nonempty := ⟨j, by simp [u]⟩ + have hj := (Finset.mem_filter.mp (u.min'_mem hu)).2 + exact ⟨u.min' hu, (first_char _ _ _).mpr fun l hl => + u.min'_le l (Finset.mem_filter.mpr ⟨Finset.mem_univ _, hl.trans hj⟩), hj⟩ + +end Root + +open scoped Classical in +/-- The quantity computed by `H ^ r * (H ^ r)⁻¹`. -/ +def offsets := H ^ r * (H ^ r)⁻¹ + +open scoped Classical in +theorem exists_offsets (hH : 1 ∈ H) : + ∃ t : ℕ, ∃ w : Fin (2 ^ t) → G, Set.range w = offsets H r := by + let D := offsets H r + have hD : D.Nonempty := by + have h := Finset.one_mem_pow (n := r) hH + exact ⟨_, Finset.mul_mem_mul h (Finset.inv_mem_inv h)⟩ + let _ : Nonempty D := hD.to_subtype + let f := D.equivFin.toEmbedding.trans (Fin.castLEEmb Nat.lt_two_pow_self.le) + refine ⟨D.card, fun j => (Function.invFun f j).val, Set.ext fun x => ?_⟩ + exact ⟨fun ⟨_, he⟩ => he ▸ (Function.invFun f _).property, + fun h => ⟨f ⟨x, h⟩, congrArg Subtype.val (Function.leftInverse_invFun f.injective _)⟩⟩ + +variable [Fintype I] (hH : 1 ∈ H) (g : G) (hg : letI := Classical.decEq G; g ∈ H ^ r) + +omit [Fintype I] in +open scoped Classical in +theorem market_support (i : I) : (market H hH r g hg).support i = ball H r i := by + ext j + rw [Market.support, Finset.mem_map] + constructor + · rintro ⟨t, _, rfl⟩ + exact (labels H hH r g hg i t).property + · intro h + obtain ⟨t, ht⟩ := (labels H hH r g hg i).surjective ⟨j, h⟩ + exact ⟨t, Finset.mem_univ _, congrArg Subtype.val ht⟩ + +variable [DecidableEq I] + +open scoped Classical in +theorem market_neighbors (i j : I) : + j ∈ (market H hH r g hg).neighbors i ↔ ∃ a ∈ offsets H r, a • i = j := by + simp only [Market.neighbors, Finset.mem_biUnion, Finset.mem_filter, Finset.mem_univ, true_and, + market_support, ball, Finset.mem_image] + constructor + · rintro ⟨x, ⟨a, ha, rfl⟩, b, hb, he⟩ + exact ⟨b * a⁻¹, Finset.mul_mem_mul hb (Finset.inv_mem_inv ha), + by rw [mul_smul, ← he, smul_inv_smul]⟩ + · rintro ⟨a, ha, rfl⟩ + obtain ⟨b, hb, c, hc, rfl⟩ := Finset.mem_mul.mp ha + exact ⟨c • i, ⟨c⁻¹, by simpa using hc, by rw [inv_inv]⟩, + b, hb, by rw [mul_smul, inv_smul_smul]⟩ + +open scoped Classical in +/-- The market ports of type `(market (I := I) H hH r g hg).Ports t where addr j i` for the +given inputs. -/ +def marketPorts {t : ℕ} (w : Fin (2 ^ t) → G) (hw : Set.range w = offsets H r) : + (market (I := I) H hH r g hg).Ports t where + addr j i := w j • i + use i := Root.first w ⟨I, i⟩ + distinct i := Root.first_distinct w ⟨I, i⟩ + image i := by + ext j + rw [market_neighbors, Finset.mem_image] + constructor + · rintro ⟨l, _, he⟩ + exact ⟨w l, Set.ext_iff.mp hw _ |>.mp ⟨l, rfl⟩, he⟩ + · rintro ⟨a, ha, rfl⟩ + obtain ⟨l, rfl⟩ := (Set.ext_iff.mp hw _).mpr ha + exact Root.first_rep w ⟨I, i⟩ l + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# The control metadata uses only a bounded orbit diagram + +In particular, comparing two request tuples does not require forming +an array indexed by every possible tuple of global labels. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral +open scoped Pointwise + +variable {G K S : Type} [Group G] [Field K] [Fintype S] [DecidableEq S] + (A : Finset (Tensor K S)) (H : Finset G) (r : ℕ) (hH : 1 ∈ H) (g : G) + (hg : letI := Classical.decEq G; g ∈ H ^ r) + {t : ℕ} (w : Fin (2 ^ t) → G) + +open scoped Classical in +/-- The quantity computed by `Fin (2 ^ t) → Key N A → Key N A → Bool`. -/ +abbrev Mask (N t : ℕ) (A : Finset (Tensor K S)) := Fin (2 ^ t) → Key N A → Key N A → Bool + +open scoped Classical in +/-- In the case `none, none`, this construction gives `same = true`. -/ +def agreeSlots (a b : Board H r) (same : Bool) (names : ↥(H ^ r) → ↥(H ^ r) → Bool) : + a.1.Req A → b.1.Req A → Prop + | none, none => same = true + | some (x, i), some (y, j) => i = j ∧ ∀ s, names (a.2 (x s)) (b.2 (y s)) = true + | _, _ => False + +open scoped Classical in +/-- Tests whether `use ∧ ∃ u v, x = ⟨a.1, u⟩ ∧ y = ⟨b.1, v⟩ ∧ agreeSlots A H r a b same names u +v` holds. -/ +def linksAt (a b : Board H r) (use : Prop) (same : Bool) + (names : ↥(H ^ r) → ↥(H ^ r) → Bool) (x y : Key (H ^ r).card A) : Bool := + decide (use ∧ ∃ u v, x = ⟨a.1, u⟩ ∧ y = ⟨b.1, v⟩ ∧ agreeSlots A H r a b same names u v) + +open scoped Classical in +/-- The observations of type `Mask (H ^ r).card t A` for the given inputs. -/ +def observations (x : Root G) : Mask (H ^ r).card t A := fun j => + linksAt A H r (Board.choose H r hH g hg x) (Board.choose H r hH g hg (x.shift (w j))) + (j ∈ x.first w) (x.see 1 (w j)) (fun u v => x.see u.val⁻¹ (v.val⁻¹ * w j)) + +open scoped Classical in +theorem local_observations : Root.Local (observations A H r hH g hg w) := by + apply Root.local_pi + intro j + have he : Root.Local (fun x : Root G => fun u v : ↥(H ^ r) => x.see u.val⁻¹ (v.val⁻¹ * w j)) := + Root.local_pi fun _ => Root.local_pi fun _ => Root.local_see _ _ + have h := Board.local_choose H r hH g hg + exact ((h.pair (h.shift (w j))).pair + ((Root.local_first w).pair ((Root.local_see 1 (w j)).pair he))).map + fun y => linksAt A H r y.1.1 y.1.2 (j ∈ y.2.1) y.2.2.1 y.2.2.2 + +variable {I : Type} [MulAction G I] [Fintype I] [DecidableEq I] (hw : Set.range w = offsets H r) + +open scoped Classical in +theorem observations_eq (i : I) : + observations A H r hH g hg w ⟨I, i⟩ = + (market H hH r g hg).mask A (marketPorts H r hH g hg w hw) i := by + let b := market (I := I) H hH r g hg + let x : Root G := ⟨I, i⟩ + let p := board H hH r g hg i + funext j l n + let y := w j • i + let q := board H hH r g hg y + let names := fun u v : ↥(H ^ r) => x.see u.val⁻¹ (v.val⁻¹ * w j) + have he (u : p.1.Req A) (v : q.1.Req A) : + agreeSlots A H r p q (x.see 1 (w j)) names u v ↔ b.request A i u = b.request A y v := by + erw [b.request_eq] + rcases u with _ | ⟨u, k⟩ <;> rcases v with _ | ⟨v, k'⟩ + · simp only [agreeSlots, Root.see, decide_eq_true_eq] + change 1 • i = y ↔ i = y + rw [one_smul] + · rfl + · rfl + · simp only [agreeSlots, names, Root.see, decide_eq_true_eq] + change (k = k' ∧ ∀ s, p.word (u s) • i = (q.word (v s) * w j) • i) ↔ + (k = k' ∧ ∀ s, p.word (u s) • i = q.word (v s) • (w j • i)) + simp only [mul_smul] + apply Bool.eq_iff_iff.mpr + simp only [observations, linksAt, Market.mask, decide_eq_true_eq] + change (j ∈ x.first w ∧ ∃ u v, l = ⟨p.1, u⟩ ∧ n = ⟨q.1, v⟩ ∧ + agreeSlots A H r p q (x.see 1 (w j)) names u v) ↔ _ + simp only [he] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# A bounded local transcript of a whole schedule + +A transcript records the initial stocks, the successive decisions +and the stocks after each round. The initial state and the local +update tests characterize the image of the branch encoding. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral + +variable {K S I : Type} [Field K] [Fintype S] [DecidableEq S] + [Fintype I] [DecidableEq I] {N M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} + +namespace Atlas +variable (a : Atlas N A M ρ) (m R : ℕ) (s : Shape N) + +open scoped Classical in +/-- In the case `0`, this construction gives `ULift (s.Req A → Fin (R + 1))`. -/ +abbrev Timeline : ℕ → Type 1 + | 0 => ULift (s.Req A → Fin (R + 1)) + | k + 1 => (s.Req A → Fin (R + 1)) × a.Record s m × Timeline k + +open scoped Classical in +instance finiteTimeline (k : ℕ) : Finite (a.Timeline m R s k) := by + have _ : Finite (a.Record s m) := inferInstance + induction k with + | zero => unfold Timeline; infer_instance + | succ k ih => unfold Timeline; infer_instance + +open scoped Classical in +/-- In the case `0, t`, this construction gives `t.down`. -/ +def start : (k : ℕ) → a.Timeline m R s k → s.Req A → Fin (R + 1) + | 0, t => t.down + | _ + 1, t => t.1 + +end Atlas + +namespace Market + +variable (b : Market I N) (a : Atlas N A M ρ) (μ d m R : ℕ) + +open scoped Classical in +/-- The value specified by `Protocol.Branch (b.payload A) (b.decision a μ d m)`. -/ +abbrev Path := Protocol.Branch (b.payload A) (b.decision a μ d m) +open scoped Classical in +/-- The condition `∀ i, a.Timeline m R (b.code i) k` on the specified data. -/ +abbrev Logset (k : ℕ) := ∀ i, a.Timeline m R (b.code i) k + +open scoped Classical in +/-- The value specified by `(a.start m R _ k (x i) j).val`. -/ +def initialLog {k : ℕ} (x : b.Logset a m R k) (i : I) (j : (b.code i).Req A) := + (a.start m R _ k (x i) j).val + +open scoped Classical in +/-- The two cases impose `True` and `let y := fun i => (x i).2.2`, respectively. -/ +def checkedLog : (k : ℕ) → b.Logset a m R k → Prop + | 0, _ => True + | k + 1, x => + let y := fun i => (x i).2.2 + b.Checks a μ d m (b.initialLog a m R x) (fun i => (x i).2.1) (b.initialLog a m R y) ∧ + checkedLog k y + +open scoped Classical in +/-- Uses `⟨min (b.localStock A z i j) R, Nat.lt_succ_of_le (min_le_right _ _)⟩` as the +representation. -/ +def project (z : b.Request A → ℕ) (i : I) (j : (b.code i).Req A) : Fin (R + 1) := + ⟨min (b.localStock A z i j) R, Nat.lt_succ_of_le (min_le_right _ _)⟩ + +open scoped Classical in +/-- In the case `0, z, _ => fun i`, this construction gives `⟨b.project R z i⟩`. -/ +def encodeLog : (k : ℕ) → (z : b.Request A → ℕ) → b.Path a μ d m k z → b.Logset a m R k + | 0, z, _ => fun i => ⟨b.project R z i⟩ + | k + 1, z, u => fun i => + (b.project R z i, b.record a (b.stockPrice (M := M) μ d z) m u.1 i, + encodeLog k (b.after a μ d m z u.1) u.2 i) + +open scoped Classical in +theorem encodeLog_injective (k : ℕ) (z : b.Request A → ℕ) : + Function.Injective (b.encodeLog a μ d m R k z) := by + induction k generalizing z with + | zero => exact fun u v _ => Subsingleton.elim (α := Unit) u v + | succ k ih => + rintro ⟨u, v⟩ ⟨u', v'⟩ he + have hu : u = u' := b.record_injective a (b.stockPrice (M := M) μ d z) m + (funext fun i => congrArg (fun x => x.2.1) (congrFun he i)) + subst u' + have hv : v = v' := ih _ (funext fun i => congrArg (fun x => x.2.2) (congrFun he i)) + rw [hv] + +variable [Nonempty S] + +open scoped Classical in +/-- The quantity computed by `N * (2 * a.capacity * m) + 1`. -/ +def rateBound := N * (2 * a.capacity * m) + 1 + +open scoped Classical in +theorem encodeLog_spec (room : a.Room m) (hm : 1 ≤ M) (hd : d ≤ M) + (k : ℕ) (z : b.Request A → ℕ) (hz : ∀ i, z i + k * rateBound a m ≤ R) + (x : b.Logset a m R k) : + (b.initialLog a m R x = b.localStock A z ∧ b.checkedLog a μ d m R k x) ↔ + ∃ u, b.encodeLog a μ d m R k z u = x := by + have init (k : ℕ) (z : b.Request A → ℕ) (hz : ∀ i, z i + k * rateBound a m ≤ R) + (u : b.Path a μ d m k z) : + b.initialLog a m R (b.encodeLog a μ d m R k z u) = b.localStock A z := by + funext i j + have h : b.localStock A z i j ≤ R := (Nat.le_add_right _ _).trans (hz _) + cases k <;> exact min_eq_left h + induction k generalizing z with + | zero => + constructor + · rintro ⟨hx, _⟩ + refine ⟨(), funext fun i => ULift.ext (funext fun j => Fin.ext ?_)⟩ + exact congrFun (congrFun ((init _ z hz ()).trans hx.symm) i) j + · rintro ⟨u, rfl⟩ + exact ⟨init _ _ hz u, trivial⟩ + | succ k ih => + have hb (u : (b.decision a μ d m z).choice) (i) : + b.after a μ d m z u i + k * rateBound a m ≤ R := by + have ht := b.after_bound a μ d m room hm hd z u i + have hh := hz i + rw [Nat.succ_mul] at hh + unfold rateBound at hh ⊢ + omega + constructor + · rintro ⟨hx, hs, ht⟩ + rw [hx, b.checks_iff] at hs + obtain ⟨u, ⟨hu, hu'⟩, _⟩ := hs + obtain ⟨v, hv⟩ := (ih _ (hb u) _).mp ⟨hu', ht⟩ + let j : b.Path a μ d m (k + 1) z := ⟨u, v⟩ + refine ⟨j, funext fun i => Prod.ext ?_ (Prod.ext (congrFun hu i) (congrFun hv i))⟩ + exact funext fun y => Fin.ext (congrFun (congrFun ((init _ z hz j).trans hx.symm) i) y) + · rintro ⟨u, rfl⟩ + have ht := (ih _ (hb u.1) _).mpr ⟨u.2, rfl⟩ + refine ⟨init _ _ hz u, ?_, ht.2⟩ + rw [init _ _ hz u, b.checks_iff] + exact ⟨u.1, ⟨rfl, ht.1⟩, fun _ h => b.record_injective a _ m h.1⟩ + +end Market +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Local allocation of copies + +A request is held at the same home by all its users. Their common +ordering is given by the list of neighbors at that home. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +open Spectral Finset + +variable {I S K : Type} [Fintype I] [DecidableEq I] [Field K] [Fintype S] [DecidableEq S] + {N t M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} {b : Market I N} + +namespace Ports + +variable (g : b.Ports t) + +open scoped Classical in +/-- The sum of `if g.addr j x = i then j.val else 0` indexed by `j ∈ g.use x`. -/ +def key (x i : I) : ℕ := ∑ j ∈ g.use x, if g.addr j x = i then j.val else 0 + +open scoped Classical in +theorem key_addr (x : I) (j : Fin (2 ^ t)) (hj : j ∈ g.use x) : + g.key x (g.addr j x) = j.val := by + unfold key + rw [sum_eq_single j] + · simp + · intro k hk hne + exact ite_eq_right (fun he => hne (g.distinct x hk hj he)) + · exact fun h => (h hj).elim + +open scoped Classical in +theorem key_inj (x : I) : Set.InjOn (g.key x) (b.neighbors x) := by + rw [← g.image] + intro i hi j hj hk + obtain ⟨u, hu, rfl⟩ := mem_image.mp hi + obtain ⟨v, hv, rfl⟩ := mem_image.mp hj + rw [key_addr _ _ _ hu, key_addr _ _ _ hv] at hk + rw [Fin.ext hk] + +end Ports + +variable (b) (a : Atlas N A M ρ) (p : b.Request A → ℝ) (m : ℕ) + +open scoped Classical in +theorem core_owner (j : b.active a p) (h : (b.localMove a p m j).choice) (e : b.Edge) + (he : (b.localMove a p m j).core h e ≠ 0) : j.val = e.1 := by + obtain ⟨i, hi⟩ := (b.moveAt a p j).trade_edge _ _ _ _ _ he + rcases i with x | y + · contradiction + · exact congrArg Sigma.fst (Sum.inr.inj hi) + +variable [Nonempty S] (g : b.Ports t) + +open scoped Classical in +/-- Computes the position by the application `g.key (b.home A x) j`. -/ +def position (x : b.Request A) (j : b.active a p) : ℕ := g.key (b.home A x) j + +open scoped Classical in +theorem ordered (x : b.Request A) (v : b.active a p → ℕ) + (hv : ∀ j, v j ≠ 0 → (b.localMove a p m j).affects x) : + Ordered v (b.position a p g x) := by + have hn (j : b.active a p) (hj : v j ≠ 0) : j.val ∈ b.neighbors (b.home A x) := by + obtain ⟨k, hk⟩ := (b.moveAt a p j).flex_support _ _ _ (hv j hj) + refine mem_biUnion.mpr ⟨b.home A x, mem_map.mpr ⟨_, mem_univ _, b.origin _⟩, ?_⟩ + exact mem_filter.mpr ⟨mem_univ _, b.home_mem A _ _ _ hk⟩ + exact fun i j hi hj he => Subtype.ext (g.key_inj _ (hn i hi) (hn j hj) he) + +open scoped Classical in +/-- Builds `Protocol.Allocation (b.localMove a p m) where take x` with the specified `take`, +`put`, `core`. -/ +def allocation : Protocol.Allocation (b.localMove a p m) where + take x := (pack (fun j => (b.localMove a p m j).take x) (b.position a p g x) + (b.ordered a p m g x _ (fun _ h => .inl h))).symm + put h x := (pack (fun j => (b.localMove a p m j).put (h j) x) (b.position a p g x) + (b.ordered a p m g x _ (fun _ e => .inr ⟨_, e⟩))).symm + core h e := (pack (fun j => (b.localMove a p m j).core (h j) e) (fun _ => 0) + (fun i j hi hj _ => Subtype.ext + ((b.core_owner a p m i _ _ hi).trans (b.core_owner a p m j _ _ hj).symm))).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +end + +/- +# Designating one supplier per request + +Use the first center in the common order at the request's home. +After this choice the route itself is fixed by the local shape. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Finset +variable {K S I : Type} [Field K] [Fintype I] [DecidableEq I] [Fintype S] [DecidableEq S] + {N t : ℕ} (A : Finset (Tensor K S)) (d M : ℕ) + +namespace Shape +variable (s : Shape N) (x : s.Req A) + +open scoped Classical in +/-- Returns `d` when `x = none` holds, and `M` otherwise. -/ +def priceCap := if x = none then d else M + +open scoped Classical in +/-- Returns `h.choose` when `h : s.2.Direct K (s.2.tensor A (.inl x)) (s.priceCap A d M x)` +holds, and `0` otherwise. -/ +def route : s.2.edges → ℕ := + if h : s.2.Direct K (s.2.tensor A (.inl x)) (s.priceCap A d M x) then h.choose else 0 + +open scoped Classical in +theorem route_spec (h : s.2.Direct K (s.2.tensor A (.inl x)) (s.priceCap A d M x)) : + (∑ e, s.route A d M x e) ≤ s.priceCap A d M x ∧ + s.2.tensor A (.inl x) ≤ Stock.bundle (s.2.wire K) (s.route A d M x) := by + rw [route, dite_eq_left h] + exact h.choose_spec + +end Shape + +namespace Market +variable (b : Market I N) + +omit [Fintype I] [DecidableEq I] in +open scoped Classical in +theorem local_route (h : b.ready A d) (hc : UniformCap N A M) + (i : I) (x : (b.code i).Req A) : + (b.shape i).Direct K ((b.shape i).tensor A (.inl x)) ((b.code i).priceCap A d M x) := by + cases x with + | none => exact h i + | some u => exact hc (b.code i) (.inl (some u)) + +omit [Fintype I] [DecidableEq I] [DecidableEq S] in +open scoped Classical in +theorem priceCap_eq (i : I) (x : (b.code i).Req A) : + ((b.code i).priceCap A d M x : ℝ) = b.cap A d M (b.request A i x) := by + rcases x with _ | ⟨z, j⟩ <;> rfl + +variable [Nonempty S] (g : b.Ports t) + +open scoped Classical in +/-- Indexes the source by the coordinates of `Σ i, (b.code i).Req A`. -/ +abbrev Source := Σ i, (b.code i).Req A + +open scoped Classical in +/-- Computes the request of by the application `b.request A u.1 u.2`. -/ +def requestOf (u : b.Source A) := b.request A u.1 u.2 + +open scoped Classical in +/-- Requires `b.requestOf A u = x ∧ ∀ v : b.Source A, b.requestOf A v = x → g.key (b.home A x) +u.1 ≤ g.key (b.home A x) v.1`. -/ +def earliest (x : b.Request A) (u : b.Source A) : Prop := + b.requestOf A u = x ∧ ∀ v : b.Source A, b.requestOf A v = x → + g.key (b.home A x) u.1 ≤ g.key (b.home A x) v.1 + +open scoped Classical in +omit [DecidableEq S] in +theorem depot_exists (x : b.Request A) : ∃! u, b.earliest A g x u := by + classical + let key (u : b.Source A) := g.key (b.home A x) u.1 + let P (n : ℕ) := ∃ u : b.Source A, b.requestOf A u = x ∧ key u = n + have h : ∃ n, P n := by + obtain ⟨i, j, h⟩ := b.request_surj A x + exact ⟨_, ⟨i, j⟩, h, rfl⟩ + obtain ⟨u, hu, hk⟩ := Nat.find_spec h + have min' (v : b.Source A) (hv : b.requestOf A v = x) : key u ≤ key v := + hk.le.trans (Nat.find_min' h ⟨v, hv, rfl⟩) + refine ⟨u, ⟨hu, min'⟩, fun v hv => ?_⟩ + have hn (w : b.Source A) (hw : b.requestOf A w = x) : w.1 ∈ b.neighbors (b.home A x) := by + refine mem_biUnion.mpr ⟨b.home A x, mem_map.mpr ⟨_, mem_univ _, b.origin _⟩, ?_⟩ + exact mem_filter.mpr ⟨mem_univ _, b.home_mem A _ (.inl w.2) _ (congrArg Sum.inl hw)⟩ + have he := g.key_inj _ (hn v hv.1) (hn u hu) (le_antisymm (hv.2 u hu) (min' v hv.1)) + rcases u with ⟨i, u⟩ + rcases v with ⟨j, v⟩ + change j = i at he + subst j + have e : b.assign A i (.inl v) = b.assign A i (.inl u) := congrArg Sum.inl (hv.1.trans hu.symm) + rw [Sum.inl.inj (b.assign_injective A i e)] + +omit [DecidableEq S] in +open scoped Classical in +/-- The value specified by `(b.depot_exists A g x).exists.choose`. -/ +def depot (x : b.Request A) := (b.depot_exists A g x).exists.choose + +omit [DecidableEq S] in +open scoped Classical in +theorem depot_spec (x : b.Request A) : b.earliest A g x (b.depot A g x) := + (b.depot_exists A g x).exists.choose_spec + +open scoped Classical in +omit [DecidableEq S] in +theorem depot_iff (u : b.Source A) : + b.depot A g (b.requestOf A u) = u ↔ + ∀ j ∈ b.neighbors u.1, ∀ v, b.request A j v = b.requestOf A u → + g.key (b.home A (b.requestOf A u)) u.1 ≤ g.key (b.home A (b.requestOf A u)) j := by + classical + constructor + · intro h j _ v hv + have he := (b.depot_spec A g (b.requestOf A u)).2 ⟨j, v⟩ hv + rwa [h] at he + · intro h + refine (b.depot_exists A g _).unique (b.depot_spec A g _) ⟨rfl, fun v hv => ?_⟩ + exact h _ (b.overlap_neighbor A _ _ _ _ hv.symm) _ hv + +open scoped Classical in +/-- The tally of type `b.Edge → ℕ`, constructed using `b.depot A g x`. -/ +def tally (x : b.Request A) : b.Edge → ℕ := + let u := b.depot A g x + Stock.collect (fun e => ⟨u.1, e⟩) ((b.code u.1).route A d M u.2) + +open scoped Classical in +theorem tally_cost (h : b.ready A d) (hc : UniformCap N A M) (x : b.Request A) : + (∑ e, b.tally A d M g x e : ℕ) ≤ b.cap A d M x := by + let u := b.depot A g x + have he := ((b.code u.1).route_spec A d M u.2 (b.local_route A d M h hc u.1 u.2)).1 + change (↑(∑ e, Stock.collect (fun t => (⟨u.1, t⟩ + : b.Edge)) ((b.code u.1).route A d M u.2) e) : ℝ) ≤ _ + rw [show (∑ e, Stock.collect _ _ e) = ∑ e, (b.code u.1).route A d M u.2 e + from sum_fiberwise _ _ _] + exact (Nat.cast_le.mpr he).trans_eq ((b.priceCap_eq A d M u.1 u.2).trans + (congrArg _ (b.depot_spec A g x).1)) + +end Market +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Computing allocation keys from local orbit observations +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral +open scoped Pointwise +variable {G K S : Type} [Group G] [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + {H : Finset G} {r t : ℕ} (w : Fin (2 ^ t) → G) + +namespace Root + +open scoped Classical in +/-- The sum of `if x.see (w i * a) b then i.val else 0` indexed by `i ∈ first w (x.shift a)`. -/ +def index (a b : G) (x : Root G) : ℕ := + ∑ i ∈ first w (x.shift a), if x.see (w i * a) b then i.val else 0 + +open scoped Classical in +theorem index_local (a b : G) : Local (index w a b) := by + have h : Local (fun x : Root G => fun j => x.see (w j * a) b) := + local_pi (fun j => local_see _ _) + exact (((local_first w).shift a).pair h).map + (fun y => ∑ i ∈ y.1, if y.2 i then i.val else 0) + +end Root + +variable (A : Finset (Tensor K S)) + +open scoped Classical in +/-- In the case `none`, this construction gives `1`. -/ +def Board.home (b : Board H r) : b.1.Req A → G + | none => 1 + | some (z, _) => b.word (z (Classical.arbitrary S)) + +variable (H) (hH : 1 ∈ H) (r) (g : G) (hg : letI := Classical.decEq G; g ∈ H ^ r) + +open scoped Classical in +/-- The keys of type `ℕ`, constructed using `Board.choose H r hH g hg x`. -/ +def keys (x : Root G) (j : Fin (2 ^ t)) (u : Key (H ^ r).card A) : ℕ := + let b := Board.choose H r hH g hg x + if h : u.1 = b.1 then x.index w (b.home A (h ▸ u.2)) (w j) else 0 + +omit [DecidableEq S] in +open scoped Classical in +theorem local_keys : Root.Local (keys H r w A hH g hg) := by + have h : Root.Local (fun x : Root G => fun (b : Board H r) (v : b.1.Req A) (j : Fin (2 ^ t)) => + x.index w (b.home A v) (w j)) := + Root.local_pi fun _ => Root.local_pi fun _ => Root.local_pi fun _ => Root.index_local _ _ _ + exact ((Board.local_choose H r hH g hg).pair h).map + (fun y j (u : Key (H ^ r).card A) => if h : u.1 = y.1.1 then y.2 y.1 (h ▸ u.2) j else 0) + +variable {I : Type} [MulAction G I] [Fintype I] [DecidableEq I] (hw : Set.range w = offsets H r) + +open scoped Classical in +theorem index_eq (i : I) (a b : G) : + Root.index w a b ⟨I, i⟩ = (marketPorts H r hH g hg w hw).key (a • i) (b • i) := by + unfold Root.index Market.Ports.key + refine Finset.sum_congr rfl fun j _ => ?_ + simp only [Root.see, decide_eq_true_eq] + change (if (w j * a) • i = b • i then j.val else 0) = _ + simp only [mul_smul, marketPorts] + congr + +omit [DecidableEq S] in +open scoped Classical in +theorem keys_eq (i : I) (j : Fin (2 ^ t)) (u : ((market H hH r g hg).code i).Req A) : + let b := market H hH r g hg + keys H r w A hH g hg ⟨I, i⟩ j ⟨b.code i, u⟩ = + (marketPorts H r hH g hg w hw).key (b.home A (b.request A i u)) (w j • i) := by + let b := market (I := I) H hH r g hg + let x := board H hH r g hg i + have he : x.home A u • i = b.home A (b.request A i u) := by + rcases u with _ | ⟨z, k⟩ + · exact one_smul _ _ + · rfl + dsimp only [keys] + rw [dite_eq_left (show b.code i = x.1 from rfl)] + exact (index_eq H r w hH g hg hw i (x.home A u) (w j)).trans + (congrArg (fun y => (marketPorts H r hH g hg w hw).key y (w j • i)) he) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Rig.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Rig.lean new file mode 100644 index 0000000000..5ba96277cd --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Control/Rig.lean @@ -0,0 +1,1068 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Parameters +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Decor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Keys +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.System +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Wired +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Formula +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Focus +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Algorithm.Computability + +/-! +# Fixed slots for core transports + +A slot records the entire chart, a directed local edge, an end, a +copy number and a hop generator. Its chart word recovers the center +from the endpoint. This makes placement injective without using the +ambient size as part of the slot alphabet. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open scoped Pointwise + +variable {G I : Type} [Group G] [MulAction G I] + +open scoped Classical in +/-- Indexes the address by the coordinates of `Σ b : Board H r, ↥b.1.2.edges`. -/ +abbrev Address (H : Finset G) (r : ℕ) := Σ b : Board H r, ↥b.1.2.edges +open scoped Classical in +/-- Indexes the socket by the coordinates of `Address H r × Bool × Fin R × ↥H`. -/ +abbrev Socket (H : Finset G) (r R : ℕ) := Address H r × Bool × Fin R × ↥H + +namespace Address +variable {H : Finset G} {r : ℕ} (e : Address H r) + +open scoped Classical in +/-- Returns `e.2.val.2` when `b` holds, and `e.2.val.1` otherwise. -/ +def point (b : Bool) : e.1.Site := if b then e.2.val.2 else e.2.val.1 + +open scoped Classical in +/-- The value specified by `e.1.word (e.point b)`. -/ +def word (b : Bool) : G := e.1.word (e.point b) + +open scoped Classical in +/-- Requires `x.see (u.val⁻¹ * e.word false) (e.word true) = true ∨ x.see (u.val⁻¹ * e.word +true) (e.word false) = true`. -/ +def test (x : Root G) (u : ↥H) : Prop := + x.see (u.val⁻¹ * e.word false) (e.word true) = true ∨ + x.see (u.val⁻¹ * e.word true) (e.word false) = true + +open scoped Classical in +/-- Returns `h.choose` when `h : ∃ u, e.test x u` holds, and `⟨1, hH⟩` otherwise. -/ +def generator (hH : 1 ∈ H) (x : Root G) : ↥H := + if h : ∃ u, e.test x u then h.choose else ⟨1, hH⟩ + +open scoped Classical in +theorem local_generator (hH : 1 ∈ H) : Root.Local (e.generator hH) := by + have h (u : ↥H) : Root.Local (fun x => e.test x u) := + ((Root.local_see (u.val⁻¹ * e.word false) (e.word true)).pair + (Root.local_see (u.val⁻¹ * e.word true) (e.word false))).map + (fun p => p.1 = true ∨ p.2 = true) + apply (Root.local_pi h).of_eq + intro x y he + unfold generator + rw [he] + +end Address + +namespace Socket +variable {H : Finset G} {r R : ℕ} + +open scoped Classical in +/-- The value specified by `(a.1, !a.2.1, a.2.2)`. -/ +def peer (a : Socket H r R) : Socket H r R := (a.1, !a.2.1, a.2.2) +open scoped Classical in +/-- Uses `a.1.word a.2.1` as the representation. -/ +def word (a : Socket H r R) : G := a.1.word a.2.1 +open scoped Classical in +/-- The quantity computed by `a.peer.word * a.word⁻¹`. -/ +def hop (a : Socket H r R) := a.peer.word * a.word⁻¹ + +open scoped Classical in +@[simp] theorem peer_peer (a : Socket H r R) : a.peer.peer = a := by simp [peer] + +end Socket + +variable (H : Finset G) (hH : 1 ∈ H) (r : ℕ) (g : G) + (hg : letI := Classical.decEq G; g ∈ H ^ r) {R : ℕ} + +open scoped Classical in +/-- Uses `⟨board H hH r g hg e.1, e.2⟩` as the representation. -/ +def address (e : (market (I := I) H hH r g hg).Edge) : Address H r := + ⟨board H hH r g hg e.1, e.2⟩ + +open scoped Classical in +/-- The attach of type `I × Socket H r R`, constructed using `address H hH r g hg e`. -/ +def attach (e : (market (I := I) H hH r g hg).Edge) (b : Bool) (j : Fin R) : + I × Socket H r R := + let a := address H hH r g hg e + (a.word b • e.1, a, b, j, a.generator hH ⟨I, e.1⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Injectivity and range of the core slot placement -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open scoped Pointwise + +variable {G I : Type} [Group G] [MulAction G I] + (H : Finset G) (hH : 1 ∈ H) (r : ℕ) (g : G) + (hg : letI := Classical.decEq G; g ∈ H ^ r) {R : ℕ} + (e : (market (I := I) H hH r g hg).Edge) (b : Bool) (j : Fin R) + +open scoped Classical in +theorem attach_owner : + (attach H hH r g hg e b j).1 = + if b then (market H hH r g hg).name e.1 e.2.val.2 + else (market H hH r g hg).name e.1 e.2.val.1 := by + cases b <;> rfl + +open scoped Classical in +theorem attach_center : + ((attach H hH r g hg e b j).2.word)⁻¹ • (attach H hH r g hg e b j).1 = e.1 := + inv_smul_smul _ _ + +open scoped Classical in +theorem attach_peer : + let t := attach H hH r g hg e b j + attach H hH r g hg e (!b) j = (t.2.hop • t.1, t.2.peer) := by + simp only [attach, Socket.hop, Socket.word, Socket.peer, mul_smul, inv_smul_smul] + +open scoped Classical in +theorem attach_inj (f : (market (I := I) H hH r g hg).Edge) (c : Bool) (k : Fin R) + (he : attach H hH r g hg e b j = attach H hH r g hg f c k) : + e = f ∧ b = c ∧ j = k := by + have hc := attach_center H hH r g hg e b j + rw [he, attach_center] at hc + have ha := congrArg (fun i => i.2.1) he + refine ⟨?_, congrArg (fun i => i.2.2.1) he, congrArg (fun i => i.2.2.2.1) he⟩ + rcases e with ⟨a, u⟩ + rcases f with ⟨a', u'⟩ + change a' = a at hc + subst a' + exact congrArg (Sigma.mk a) (eq_of_heq (Sigma.mk.inj ha).2) + +open scoped Classical in +theorem attach_link : + let x := attach H hH r g hg e b j + let y := attach H hH r g hg e (!b) j + (x.2.2.2.2 : G) • x.1 = y.1 ∨ (x.2.2.2.2 : G) • y.1 = x.1 := by + let q := address H hH r g hg e + let c : Root G := ⟨I, e.1⟩ + have he : ∃ u, q.test c u := + ((Board.valid_choose H r hH g hg c).2.2.2.2 _ _).mp e.2.property + have hu : q.test c (q.generator hH c) := by + unfold Address.generator + rw [dite_eq_left he] + exact he.choose_spec + simp only [Address.test, Root.see, Root.label, decide_eq_true_eq, mul_smul, inv_smul_eq_iff] at hu + cases b + · exact hu.symm.imp Eq.symm Eq.symm + · exact hu.imp Eq.symm Eq.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Programming a fixed socket by inspecting its center -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Socket +open scoped Pointwise + +variable {G I : Type} [Group G] [MulAction G I] {H : Finset G} {r R q : ℕ} + (s : Socket H r R) (hH : 1 ∈ H) (g : G) (hg : letI := Classical.decEq G; g ∈ H ^ r) + (cnt : Decor G q → Address H r → ℕ) + +open scoped Classical in +/-- The enabled of type `Bool`, constructed using `x.shift s.word⁻¹`. -/ +def enabled (x : Decor G q) : Bool := + let y := x.shift s.word⁻¹ + decide (Board.choose H r hH g hg y.toRoot = s.1.1 ∧ + s.1.generator hH y.toRoot = s.2.2.2 ∧ s.2.2.1.val < cnt y s.1) + +open scoped Classical in +theorem local_enabled (hc : Decor.Local cnt) : Decor.Local (s.enabled hH g hg cnt) := by + have hd := (Board.local_choose H r hH g hg).pair (s.1.local_generator hH) + have hl := ((Decor.local_root hd).pair hc).map + (fun p => decide (p.1.1 = s.1.1 ∧ p.1.2 = s.2.2.2 ∧ s.2.2.1.val < p.2 s.1)) + exact hl.shift s.word⁻¹ + +variable (mark : I → Fin (2 ^ q)) + +open scoped Classical in +theorem enabled_at (i : I) : + s.enabled hH g hg cnt ⟨⟨I, i⟩, mark⟩ = true ↔ + let c := s.word⁻¹ • i + board H hH r g hg c = s.1.1 ∧ s.1.generator hH ⟨I, c⟩ = s.2.2.2 ∧ + s.2.2.1.val < cnt ⟨⟨I, c⟩, mark⟩ s.1 := by + simp only [enabled, decide_eq_true_eq] + rfl + +open scoped Classical in +theorem enabled_attach (e : (market (I := I) H hH r g hg).Edge) (b : Bool) (j : Fin R) : + let a := attach H hH r g hg e b j + a.2.enabled hH g hg cnt ⟨⟨I, a.1⟩, mark⟩ = true ↔ + j.val < cnt ⟨⟨I, e.1⟩, mark⟩ (address H hH r g hg e) := by + dsimp only + rw [enabled_at, attach_center] + simp only [attach, address, true_and] + +open scoped Classical in +private theorem exists_edge (c : I) (hb : board H hH r g hg c = s.1.1) : + ∃ e : (market (I := I) H hH r g hg).Edge, e.1 = c ∧ address H hH r g hg e = s.1 := by + rcases s with ⟨⟨a, e⟩, b, j, u⟩ + change board H hH r g hg c = a at hb + subst a + exact ⟨⟨c, e⟩, rfl, rfl⟩ + +open scoped Classical in +theorem of_enabled {i : I} (he : s.enabled hH g hg cnt ⟨⟨I, i⟩, mark⟩ = true) : + ∃ e : (market (I := I) H hH r g hg).Edge, + attach H hH r g hg e s.2.1 s.2.2.1 = (i, s) ∧ + s.2.2.1.val < cnt ⟨⟨I, e.1⟩, mark⟩ (address H hH r g hg e) := by + obtain ⟨hb, hgen, hcount⟩ := (s.enabled_at hH g hg cnt mark i).mp he + obtain ⟨e, hc, ha⟩ := exists_edge s hH g hg _ hb + refine ⟨e, ?_, by rwa [hc, ha]⟩ + simp only [attach, ha, hc, hgen] + exact Prod.ext (smul_inv_smul _ i) rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Socket +end + +/- +# Encoding sockets by a fixed number of bits + +The command names the generator word by the physical index of its +own slot. A separate finite list of actions resolves these words into +the addresses of the opposite endpoints. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open scoped Pointwise +open Coloring + +variable {G I : Type} [Group G] [MulAction G I] {H : Finset G} {r R p q : ℕ} + +open scoped Classical in +/-- The value specified by `Socket H r R ↪ B p`. -/ +abbrev Bank (H : Finset G) (r R p : ℕ) := Socket H r R ↪ B p + +namespace Bank +variable (bank : Bank H r R p) + +open scoped Classical in +/-- Returns `some h.choose` when `h : ∃ s, bank s = i` holds, and `none` otherwise. -/ +def read (i : B p) : Option (Socket H r R) := + if h : ∃ s, bank s = i then some h.choose else none + +open scoped Classical in +@[simp] theorem read_slot (s : Socket H r R) : bank.read (bank s) = some s := by + have h : ∃ t, bank t = bank s := ⟨s, rfl⟩ + rw [read, dite_eq_left h, bank.injective h.choose_spec] + +open scoped Classical in +theorem of_read {i : B p} {s : Socket H r R} (he : bank.read i = some s) : bank s = i := by + unfold read at he + split at he + · rename_i h + rw [← Option.some.inj he] + exact h.choose_spec + · cases he + +open scoped Classical in +/-- The value specified by `(bank.read j).elim 1 Socket.hop`. -/ +def hop (j : B p) : G := (bank.read j).elim 1 Socket.hop + +open scoped Classical in +/-- The indexed operation `(bank.read j).elim ⟨1, hH⟩ (fun s => s.2.2.2)`. -/ +def generator (hH : 1 ∈ H) (j : B p) : ↥H := + (bank.read j).elim ⟨1, hH⟩ (fun s => s.2.2.2) + +variable (hH : 1 ∈ H) (g : G) (hg : letI := Classical.decEq G; g ∈ H ^ r) + (cnt : Decor G q → Address H r → ℕ) + +open scoped Classical in +/-- In the case `none`, this construction gives `(false, false, j, j)`. -/ +def program (x : Decor G q) (j : B p) : Bool × Bool × B p × B p := + match bank.read j with + | none => (false, false, j, j) + | some s => (s.enabled hH g hg cnt x, s.2.1, j, bank s.peer) + +open scoped Classical in +theorem program_local (hc : Decor.Local cnt) : Decor.Local (bank.program hH g hg cnt) := by + apply Decor.local_pi + intro j + unfold program + cases bank.read j with + | none => exact ⟨∅, fun _ _ _ _ => rfl⟩ + | some s => + exact (s.local_enabled hH g hg cnt hc).map (fun b => (b, s.2.1, j, bank s.peer)) + +open scoped Classical in +/-- The orders of type `Bool × Bool × I × B p`, constructed using `bank.program hH g hg cnt ⟨⟨I, +a.1⟩, mark⟩ a.2`. -/ +def orders (mark : I → B q) (a : I × B p) : Bool × Bool × I × B p := + let k := bank.program hH g hg cnt ⟨⟨I, a.1⟩, mark⟩ a.2 + (k.1, k.2.1, bank.hop k.2.2.1 • a.1, k.2.2.2) + +open scoped Classical in +/-- Indexes the pin by the coordinates of `I) H hH r g hg).Edge) (b : Bool) (j : Fin R) : I × B +p := Prod.map id bank (attach H hH r g hg e b j)`. -/ +def pin (e : (market (I := I) H hH r g hg).Edge) (b : Bool) (j : Fin R) : I × B p := + Prod.map id bank (attach H hH r g hg e b j) + +open scoped Classical in +theorem orders_pin (mark : I → B q) (e : (market (I := I) H hH r g hg).Edge) + (b : Bool) (j : Fin R) (hj : j.val < cnt ⟨⟨I, e.1⟩, mark⟩ (address H hH r g hg e)) : + bank.orders hH g hg cnt mark (bank.pin hH g hg e b j) = + (true, b, bank.pin hH g hg e (!b) j) := by + have he := (Socket.enabled_attach hH g hg cnt mark e b j).mpr hj + simp only [orders, pin, Prod.map, id_eq, program, read_slot, hop, Option.elim_some, he] + rw [attach_peer H hH r g hg e b j] + rfl + +open scoped Classical in +theorem covered (mark : I → B q) (i : I × B p) + (hi : (bank.orders hH g hg cnt mark i).1 = true) : + ∃ (e : (market (I := I) H hH r g hg).Edge) (b : Bool) (j : Fin R), + bank.pin hH g hg e b j = i ∧ j.val < cnt ⟨⟨I, e.1⟩, mark⟩ (address H hH r g hg e) := by + rcases i with ⟨i, k⟩ + simp only [orders, program] at hi + cases hr : bank.read k with + | none => simp [hr] at hi + | some s => + simp only [hr] at hi + obtain ⟨e, he, hj⟩ := s.of_enabled hH g hg cnt mark hi + exact ⟨e, s.2.1, s.2.2.1, by simp [pin, he, bank.of_read hr], hj⟩ + +end Bank +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# From counted edges to transport commands + +Every copy has its own two slots. The two chart words give opposite +orders even for a loop or parallel copies. Only a hop generator of the +fixed menu is needed to prove the two slots share a transport group. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Bank +open Coloring Transport +open scoped Pointwise + +variable {G I : Type} [Group G] [MulAction G I] {H : Finset G} {r R p q h : ℕ} + (bank : Bank H r R p) (hH : 1 ∈ H) (g : G) (hg : letI := Classical.decEq G; g ∈ H ^ r) + +open scoped Classical in +/-- Embeds `Protocol.End m` into `I × B p where toFun a`. -/ +def endpoints (m : (market (I := I) H hH r g hg).Edge → ℕ) (hr : ∀ e, m e ≤ R) : + Protocol.End m ↪ I × B p where + toFun a := bank.pin hH g hg a.1.1 a.2 (a.1.2.castLE (hr _)) + inj' := by + rintro ⟨⟨e, j⟩, b⟩ ⟨⟨f, k⟩, c⟩ he + have hx := congrArg Prod.fst he + have hh : attach H hH r g hg e b (j.castLE (hr e)) = + attach H hH r g hg f c (k.castLE (hr f)) := + Prod.ext hx (bank.injective (congrArg Prod.snd he)) + obtain ⟨rfl, rfl, eq⟩ := attach_inj H hH r g hg e b _ f c _ hh + have hk : j = k := Fin.ext (congrArg (fun x : Fin R => x.val) eq) + subst k + rfl + +variable [MulAction G (Site h)] (cnt : Decor G q → Address H r → ℕ) + (mark : Site h → B q) (m : (market (I := Site h) H hH r g hg).Edge → ℕ) + +open scoped Classical in +/-- The construction uses `i.1.2.castLE (hr i.1.1)` for its intermediate `j`. -/ +def placement (hr : ∀ e, m e ≤ R) + (hc : ∀ e, cnt ⟨⟨Site h, e.1⟩, mark⟩ (address H hH r g hg e) = m e) + (group : Port h p → ℕ) + (same : ∀ x y i j, bank.generator hH i = bank.generator hH j → + (bank.generator hH i).val • x = y → group (x, i) = group (y, j)) + (a : Orders h p) (ha : a = bank.orders hH g hg cnt mark) : + Protocol.Placement + (fun e => (market H hH r g hg).name e.1 e.2.val.1) + (fun e => (market H hH r g hg).name e.1 e.2.val.2) m group a where + embed := bank.endpoints hH g hg m hr + owner i := attach_owner H hH r g hg _ _ (i.1.2.castLE (hr _)) + cmd i := by + rw [ha] + apply bank.orders_pin + rw [hc] + exact i.1.2.isLt + cover i hi := by + rw [ha] at hi + obtain ⟨e, b, j, he, hj⟩ := bank.covered hH g hg cnt mark i (Finset.mem_filter.mp hi).2 + rw [hc] at hj + exact ⟨⟨⟨e, ⟨j.val, hj⟩⟩, b⟩, he⟩ + group i := by + let j := i.1.2.castLE (hr i.1.1) + let x := attach H hH r g hg i.1.1 i.2 j + let y := attach H hH r g hg i.1.1 (!i.2) j + have hgen (k : Socket H r R) : bank.generator hH (bank k) = k.2.2.2 := by + simp [generator] + have he : bank.generator hH (bank x.2) = bank.generator hH (bank y.2) := by + rw [hgen, hgen]; rfl + change group (y.1, bank y.2) = group (x.1, bank x.2) + rcases attach_link H hH r g hg i.1.1 i.2 j with h | h + · exact (same _ _ _ _ he (by rw [hgen]; exact h)).symm + · exact same _ _ _ _ he.symm (by rw [hgen]; exact h) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Bank +end + +/- +# Finite selectors and local verification + +A selector contains one bounded transcript per center. A local test +checks all rounds at once using the neighbor transcripts. As the +encoding is injective, inactive and spare symbols have no multiplicity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral + +variable {K S I : Type} [Field K] [Fintype S] [DecidableEq S] + [Fintype I] [DecidableEq I] {N M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} + (a : Atlas N A M ρ) (m R : ℕ) + +namespace Atlas + +open scoped Classical in +/-- Indexes the film by the coordinates of `Σ s : Shape N, a.Timeline m R s k`. -/ +abbrev Film (k : ℕ) := Σ s : Shape N, a.Timeline m R s k + +open scoped Classical in +instance (k : ℕ) : Fintype (a.Film m R k) := Fintype.ofFinite _ + +open scoped Classical in +/-- Uses `⟨x.1, x.2.1, x.2.2.1, a.start m R _ _ x.2.2.2⟩` as the representation. -/ +def frame {k : ℕ} (x : a.Film m R (k + 1)) : Σ s : Shape N, a.Cell m R s := + ⟨x.1, x.2.1, x.2.2.1, a.start m R _ _ x.2.2.2⟩ + +open scoped Classical in +/-- Uses `⟨x.1, x.2.2.2⟩` as the representation. -/ +def tail {k : ℕ} (x : a.Film m R (k + 1)) : a.Film m R k := ⟨x.1, x.2.2.2⟩ + +open scoped Classical in +/-- In the case `0, _, _`, this construction gives `True`. -/ +def Watch (t μ d : ℕ) (v : Mask N t A) : + (k : ℕ) → a.Film m R k → (Fin (2 ^ t) → a.Film m R k) → Prop + | 0, _, _ => True + | k + 1, x, y => + a.test m t R μ d (a.frame m R x, v) (fun j => (a.frame m R (y j), v)) ∧ + Watch t μ d v k (a.tail m R x) (fun j => a.tail m R (y j)) + +open scoped Classical in +/-- Counts the elements of `(a.Film m R k)`. -/ +abbrev bits (k : ℕ) := Fintype.card (a.Film m R k) +open scoped Classical in +/-- The quantity computed by `Fin (2 ^ a.bits m R k)`. -/ +abbrev Symbol (k : ℕ) := Fin (2 ^ a.bits m R k) + +open scoped Classical in +/-- Computes the write by the application `Coloring.encode _`. -/ +def write {k : ℕ} : a.Film m R k ↪ a.Symbol m R k := Coloring.encode _ + +open scoped Classical in +/-- The accept of type `Prop` for the given inputs. -/ +def Accept (t μ d k : ℕ) (s : Shape N) (v : Mask N t A) + (x : a.Symbol m R k) (y : Fin (2 ^ t) → a.Symbol m R k) : Prop := + ∃ (u : a.Timeline m R s k) (w : Fin (2 ^ t) → a.Film m R k), + a.write m R ⟨s, u⟩ = x ∧ (∀ j, a.write m R (w j) = y j) ∧ + (∀ j, (a.start m R s k u j).val = 0) ∧ a.Watch m R t μ d v k ⟨s, u⟩ w + +end Atlas + +namespace Market +variable (b : Market I N) {t : ℕ} (g : b.Ports t) (μ d : ℕ) + +open scoped Classical in +/-- Uses `⟨_, x i⟩` as the representation. -/ +def film {k : ℕ} (x : b.Logset a m R k) (i : I) : a.Film m R k := ⟨_, x i⟩ + +open scoped Classical in +theorem watch_iff (k : ℕ) (x : b.Logset a m R k) : + (∀ i, a.Watch m R t μ d (b.mask A g i) k (b.film a m R x i) + (fun j => b.film a m R x (g.addr j i))) ↔ b.checkedLog a μ d m R k x := by + induction k with + | zero => simp [Atlas.Watch, checkedLog] + | succ k ih => + let y (i : I) := (x i).2.2 + let c (i : I) : a.Cell m R (b.code i) := ((x i).1, (x i).2.1, a.start m R _ _ (y i)) + simp only [Atlas.Watch, checkedLog, forall_and] + exact and_congr (b.checked a g c μ d) (ih y) + +open scoped Classical in +/-- The value specified by `a.write m R ∘ b.film a m R (b.encodeLog a μ d m R k 0 u)`. -/ +def selector (k : ℕ) (u : b.Path a μ d m k 0) : I → a.Symbol m R k := + a.write m R ∘ b.film a m R (b.encodeLog a μ d m R k 0 u) + +open scoped Classical in +theorem selector_injective (k : ℕ) : Function.Injective (b.selector a m R μ d k) := by + intro u v h + apply b.encodeLog_injective a μ d m R k 0 + exact funext fun i => eq_of_heq (Sigma.mk.inj ((a.write m R).injective (congrFun h i))).2 + +open scoped Classical in +/-- The condition `∀ i, a.Accept m R t μ d k (b.code i) (b.mask A g i) (z i) (fun j => z (g.addr +j i))` on the specified data. -/ +def Legal (k : ℕ) (z : I → a.Symbol m R k) := + ∀ i, a.Accept m R t μ d k (b.code i) (b.mask A g i) (z i) (fun j => z (g.addr j i)) + +variable [Nonempty S] (room : a.Room m) (hm : 1 ≤ M) (hd : d ≤ M) (k : ℕ) + (hk : k * rateBound a m ≤ R) + +include room hm hd hk in +open scoped Classical in +theorem legal_iff (z : I → a.Symbol m R k) : + b.Legal a m R g μ d k z ↔ ∃ u, b.selector a m R μ d k u = z := by + have hbound : ∀ i : b.Request A, (0 : ℕ) + k * rateBound a m ≤ R := fun _ => by + rw [zero_add] + exact hk + have h := b.encodeLog_spec a μ d m R room hm hd k 0 hbound + constructor + · intro hz + choose x y hx hy h₀ hvalid using hz + have he (i) : y i = fun j => b.film a m R x (g.addr j i) := + funext fun j => (a.write m R).injective ((hy i j).trans (hx _).symm) + have hv : b.checkedLog a μ d m R k x := (b.watch_iff a m R g μ d k x).mp fun i => by + rw [← he] + exact hvalid i + obtain ⟨u, hu⟩ := (h x).mp ⟨funext fun i => funext (h₀ i), hv⟩ + exact ⟨u, by unfold selector; rw [hu]; exact funext hx⟩ + · rintro ⟨u, rfl⟩ + let x := b.encodeLog a μ d m R k 0 u + obtain ⟨h₀, hv⟩ := (h x).mpr ⟨u, rfl⟩ + exact fun i => ⟨x i, fun j => b.film a m R x (g.addr j i), rfl, fun _ => rfl, + fun j => congrFun (congrFun h₀ i) j, (b.watch_iff a m R g μ d k x).mpr hv i⟩ + +open scoped Classical in +/-- Reindexes `b.Path a μ d m k 0` and `{z // b.Legal a m R g μ d k z}` by an equivalence. -/ +def branches : b.Path a μ d m k 0 ≃ {z // b.Legal a m R g μ d k z} := by + have h := b.legal_iff a m R g μ d room hm hd k hk + exact Equiv.ofBijective (fun u => ⟨_, (h _).mpr ⟨u, rfl⟩⟩) + ⟨fun _ _ e => b.selector_injective a m R μ d k (congrArg Subtype.val e), + fun z => let ⟨u, hu⟩ := (h _).mp z.property; ⟨u, Subtype.ext hu⟩⟩ + +end Market +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Local replay of the number of wires at an edge + +The edge belongs to a single center. At termination only requests +whose designated depot is there can contribute to its width. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Finset + +variable {K S I : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype I] [DecidableEq I] {N t M : ℕ} {ρ : ℝ} (A : Finset (Tensor K S)) + +namespace Market +variable (b : Market I N) (g : b.Ports t) (d M : ℕ) + +open scoped Classical in +/-- Tests whether `b.depot A g (b.request A i x) = ⟨i, x⟩` holds. -/ +def here (i : I) (x : (b.code i).Req A) : Bool := + decide (b.depot A g (b.request A i x) = ⟨i, x⟩) + +omit [Nonempty S] [Fintype I] [DecidableEq I] [DecidableEq S] in +open scoped Classical in +theorem request_inj (i : I) : Function.Injective (b.request A i) := + fun x y h => Sum.inl.inj (b.assign_injective A i (a₁ := .inl x) (a₂ + := .inl y) (congrArg Sum.inl h)) + +open scoped Classical in +theorem tally_here (i : I) (x : (b.code i).Req A) (e : (b.shape i).edges) : + b.tally A d M g (b.request A i x) ⟨i, e⟩ = + if b.here A g i x then (b.code i).route A d M x e else 0 := by + by_cases h : b.depot A g (b.request A i x) = ⟨i, x⟩ + · rw [tally, h, ite_eq_left (show b.here A g i x = true from decide_eq_true h)] + exact Stock.collect_inj (g := fun e => (⟨i, e⟩ : b.Edge)) + (fun _ _ h => eq_of_heq (Sigma.mk.inj h).2) _ _ + · rw [ite_eq_right (show b.here A g i x ≠ true from fun he => h (of_decide_eq_true he))] + by_contra! hz + have hi := Protocol.tally_origin A d M b g _ _ hz + have hu := (b.depot_spec A g (b.request A i x)).1 + generalize b.depot A g (b.request A i x) = u at hi hu h + rcases u with ⟨j, y⟩ + change j = i at hi + subst j + exact h (congrArg (fun v => (⟨i, v⟩ : b.Source A)) (b.request_inj A i hu)) + +open scoped Classical in +theorem tally_at (z : b.Request A → ℕ) (i : I) (e : (b.shape i).edges) : + (∑ x, b.tally A d M g x ⟨i, e⟩ * z x) = + ∑ x, (if b.here A g i x then (b.code i).route A d M x e else 0) * b.localStock A z i x := by + let U := univ.image (b.request A i) + have zero (x : b.Request A) (hx : x ∉ U) : b.tally A d M g x ⟨i, e⟩ = 0 := by + by_contra hz + have hi := Protocol.tally_origin A d M b g _ _ hz + have hu := (b.depot_spec A g x).1 + generalize b.depot A g x = u at hi hu + rcases u with ⟨j, v⟩ + change j = i at hi + subst j + exact hx (mem_image.mpr ⟨v, mem_univ _, hu⟩) + rw [← sum_subset (subset_univ U) (fun x _ hx => by rw [zero x hx, zero_mul])] + rw [show U = univ.image (b.request A i) from rfl, sum_image (b.request_inj A i).injOn] + exact sum_congr rfl fun x _ => congrArg (· * z (b.request A i x)) (b.tally_here A g d M i x e) + +end Market +variable {A} (a : Atlas N A M ρ) (μ d m R : ℕ) + +open scoped Classical in +/-- In the case `0, x`, this construction gives `∑ j, (if owner j then s.route A d M j e else 0) +* (x.down j).val`. -/ +def Atlas.edgeCount (s : Shape N) (owner : s.Req A → Bool) (e : s.2.edges) : + (k : ℕ) → a.Timeline m R s k → ℕ + | 0, x => ∑ j, (if owner j then s.route A d M j e else 0) * (x.down j).val + | k + 1, x => a.changeAt s m x.2.1 true (.inr e) + edgeCount s owner e k x.2.2 + +namespace Market +variable (b : Market I N) (g : b.Ports t) + +omit [Fintype I] [Nonempty S] [DecidableEq S] in +open scoped Classical in +private theorem read_core {E J : Type} [Fintype J] [DecidableEq J] [DecidableEq E] + {T : J → Tensor K S} {H : ℝ} (q : Proposal T H) + (f : J → I ⊕ E) (hf : Function.Injective f) (U : Finset J) (j : J) (e : E) + (he : f j = .inr e) (u : (q.flex f U m).choice) : + (q.flex f U m).core u e = + q.output U (m + Fintype.card q.move.letter) u.val j := by + change Stock.collect f _ (.inr e) = _ + rw [← he, Stock.collect_inj hf] + +omit [Nonempty S] in +open scoped Classical in +theorem step_count (p : b.Request A → ℝ) (i : I) (e : (b.shape i).edges) + (u : (b.policy a p m).choice) : + (b.policy a p m).core u ⟨i, e⟩ = a.changeAt (b.code i) m (b.record a p m u i) true (.inr e) + := by + let F (j : b.active a p) := (b.localMove a p m j).core (u j) ⟨i, e⟩ + change (∑ j, F j) = _ + have he (j : b.active a p) (hj : j.val ≠ i) : F j = 0 := by + by_contra hn + exact hj (b.core_owner a p m j (u j) _ hn) + by_cases hi : i ∈ b.active a p + · let j : b.active a p := ⟨i, hi⟩ + rw [Fintype.sum_eq_single j (fun k hk => he k fun h => hk (Subtype.ext h))] + have hh := b.record_active a p m u j + change b.record a p m u i = _ at hh + rw [hh] + let q := b.moveAt a p j + refine (read_core m q (b.assign A i) (b.assign_injective A i) ((b.shape i).links A) + (.inr e) ⟨i, e⟩ rfl (u j)).trans ?_ + congr + · rw [sum_eq_zero (fun j _ => he j fun h => hi (h ▸ j.property))] + rw [show b.record a p m u i = none from dite_eq_right hi] + rfl + +open scoped Classical in +theorem edge_count (room : a.Room m) (hm : 1 ≤ M) (hd : d ≤ M) + (k : ℕ) (z : b.Request A → ℕ) (hz : ∀ i, z i + k * rateBound a m ≤ R) + (u : b.Path a μ d m k z) (i : I) (e : (b.shape i).edges) : + Protocol.edges (b.payload A) (b.decision a μ d m) (b.tally A d M g) k z u ⟨i, e⟩ = + a.edgeCount d m R (b.code i) (b.here A g i) e k (b.encodeLog a μ d m R k z u i) := by + induction k generalizing z with + | zero => + refine (b.tally_at A g d M z i e).trans ?_ + refine sum_congr rfl fun j _ => congrArg _ (min_eq_left ?_).symm + exact (Nat.le_add_right _ _).trans (hz (b.request A i j)) + | succ k ih => + have hb (x) : b.after a μ d m z u.1 x + k * rateBound a m ≤ R := by + have h := b.after_bound a μ d m room hm hd z u.1 x + have hh := hz x + rw [Nat.succ_mul] at hh + unfold rateBound at hh ⊢ + omega + exact congrArg₂ (· + ·) (b.step_count a m (b.stockPrice (M := M) μ d z) i e u.1) + (ih _ hb u.2) + +end Market +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# A local guard for each selector + +On a group action, all these guards pass precisely for those +selectors representing a branch of the scheduled protocol. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +open scoped Pointwise + +variable {K G J : Type} [Field K] [Group G] {U : J → Subgroup G} {g : G} + (p : Parameters K U g) + +open scoped Classical in +/-- Positive scale and bounded stock fit every branch simultaneously. -/ +structure Clock where + /-- The height parameter carried by `Clock`, with type `ℕ`. -/ + height : ℕ + /-- The `Clock` field of type `ℕ`. -/ + μ : ℕ + /-- The width parameter carried by `Clock`, with type `ℕ`. -/ + width : ℕ + room : p.offers.Room (2 ^ height) + wide : 4 ≤ width + runs : ∀ (I : Type) [Fintype I] [Nonempty I] [MulAction G I], + let b := p.balls I + Runs (b.payload p.table) (b.cap p.table p.path p.limit) + (b.decision p.offers μ p.path (2 ^ height)) (1203 * Fintype.card I * width) width 0 0 + +open scoped Classical in +theorem has_clock : Nonempty p.Clock := by + let _ : Nonempty p.sites := ⟨⟨1, p.start⟩⟩ + obtain ⟨h, μ, W, hm, _, hw, h⟩ := p.offers.schedule (p.path_pos.trans_le p.pay) p.pos + exact ⟨⟨_, μ, W, hm, hw, fun I _ _ _ => h I (p.balls I) _ p.pay (p.frequent I)⟩⟩ + +variable {p} (c : p.Clock) +namespace Clock + +open scoped Classical in +/-- The quantity computed by `2 ^ c.height`. -/ +abbrev batch := 2 ^ c.height +open scoped Classical in +/-- The quantity computed by `c.width * Market.rateBound p.offers c.batch`. -/ +abbrev bound := c.width * Market.rateBound p.offers c.batch +open scoped Classical in +/-- Uses `p.offers.bits c.batch c.bound c.width` as the representation. -/ +abbrev bits := p.offers.bits c.batch c.bound c.width +open scoped Classical in +/-- Computes the input by the application `Decor G c.bits`. -/ +abbrev Input := Decor G c.bits + +variable {t : ℕ} (w : Fin (2 ^ t) → G) + +open scoped Classical in +/-- The guard of type `Bool` for the given inputs. -/ +def guard (x : c.Input) : Bool := + decide (p.offers.Accept c.batch c.bound t c.μ p.path c.width + (Board.choose p.core p.radius p.unit g p.reach x.toRoot).1 + (observations p.table p.core p.radius p.unit g p.reach w x.toRoot) + (x.mark (x.label 1)) (fun j => x.mark (x.label (w j)))) + +open scoped Classical in +theorem guard_local : Decor.Local (c.guard w) := by + have ha := Board.local_choose p.core p.radius p.unit g p.reach + have hb := local_observations p.table p.core p.radius p.unit g p.reach w + have hm : Decor.Local (fun x : c.Input => fun j => x.mark (x.label (w j))) := + Decor.local_pi fun j => Decor.local_mark _ + exact ((Decor.local_root (ha.pair hb)).pair ((Decor.local_mark 1).pair hm)).map fun y => + decide (p.offers.Accept c.batch c.bound t c.μ p.path c.width y.1.1.1 y.1.2 y.2.1 y.2.2) + +variable (hw : Set.range w = offsets p.core p.radius) + {I : Type} [Fintype I] [MulAction G I] (z : I → Fin (2 ^ c.bits)) + +open scoped Classical in +/-- The value specified by `(p.balls I).Path p.offers c.μ p.path c.batch c.width 0`. -/ +abbrev path (I : Type) [Fintype I] [MulAction G I] := + (p.balls I).Path p.offers c.μ p.path c.batch c.width 0 + +open scoped Classical in +/-- The value specified by `(p.balls I).selector p.offers c.batch c.bound c.μ p.path c.width u`. -/ +def selector (u : c.path I) : I → Fin (2 ^ c.bits) := + (p.balls I).selector p.offers c.batch c.bound c.μ p.path c.width u + +include hw in +open scoped Classical in +theorem guard_iff : + (∀ i, c.guard w ⟨⟨I, i⟩, z⟩ = true) ↔ ∃! u : c.path I, c.selector u = z := by + let _ : Nonempty p.sites := ⟨⟨1, p.start⟩⟩ + let b := p.balls I + let a := marketPorts (I := I) p.core p.radius p.unit g p.reach w hw + have he (i) := observations_eq p.table p.core p.radius p.unit g p.reach w hw (i : I) + have h : (∀ i, c.guard w ⟨⟨I, i⟩, z⟩ = true) ↔ + b.Legal p.offers c.batch c.bound a c.μ p.path c.width z := by + unfold guard + simp only [decide_eq_true_eq, he, Root.label, one_smul] + rfl + rw [h, b.legal_iff p.offers c.batch c.bound a c.μ p.path c.room + (p.path_pos.trans_le p.pay) p.pay _ le_rfl] + exact ⟨fun ⟨u, hu⟩ => ⟨u, hu, fun _ he => + b.selector_injective p.offers c.batch c.bound c.μ p.path c.width (he.trans hu.symm)⟩, + fun h => h.exists⟩ + +end Clock +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +end + +/- # A finite local test for the designated depot -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral +open scoped Pointwise + +variable {G K S : Type} [Group G] [Field K] [Fintype S] [Nonempty S] + (A : Finset (Tensor K S)) (H : Finset G) (r : ℕ) (hH : 1 ∈ H) (g : G) + (hg : letI := Classical.decEq G; g ∈ H ^ r) + {t : ℕ} (w : Fin (2 ^ t) → G) (j₀ : Fin (2 ^ t)) + +open scoped Classical in +/-- The value specified by `decide (∀ j v, observations A H r hH g hg w x j u v = true → keys H +r w A hH g hg x j₀ u ≤ keys H r w A hH g hg x j u)`. -/ +def owns (x : Root G) (u : Key (H ^ r).card A) : Bool := + decide (∀ j v, observations A H r hH g hg w x j u v = true → + keys H r w A hH g hg x j₀ u ≤ keys H r w A hH g hg x j u) + +open scoped Classical in +theorem owns_local : Root.Local (owns A H r hH g hg w j₀) := + ((local_observations A H r hH g hg w).pair (local_keys H r w A hH g hg)).map + fun p u => decide (∀ j v, p.1 j u v = true → p.2 j₀ u ≤ p.2 j u) + +variable {I : Type} [MulAction G I] [Fintype I] [DecidableEq I] + (hw : Set.range w = offsets H r) (h₀ : w j₀ = 1) + +include h₀ in +open scoped Classical in +theorem owns_here (i : I) (u : ((market H hH r g hg).code i).Req A) : + let b := market H hH r g hg + owns A H r hH g hg w j₀ ⟨I, i⟩ ⟨b.code i, u⟩ = + b.here A (marketPorts H r hH g hg w hw) i u := by + let b := market (I := I) H hH r g hg + let P := marketPorts (I := I) H r hH g hg w hw + let x := b.home A (b.request A i u) + apply Bool.eq_iff_iff.mpr + simp only [owns, Market.here, decide_eq_true_eq] + rw [observations_eq A H r hH g hg w hw i] + simp only [keys_eq H r w A hH g hg hw, h₀, one_smul] + change (∀ j v, b.mask A P i j ⟨_, u⟩ v = true → P.key x i ≤ P.key x (P.addr j i)) ↔ + b.depot A P (b.requestOf A ⟨i, u⟩) = ⟨i, u⟩ + rw [b.depot_iff] + constructor + · intro h j hj v hv + change j ∈ b.neighbors i at hj + rw [← P.image] at hj + obtain ⟨l, hl, rfl⟩ := Finset.mem_image.mp hj + exact h _ ⟨_, v⟩ ((b.mask_test A P i l u v).mpr ⟨hl, hv.symm⟩) + · intro h j v hv + rw [Market.mask, decide_eq_true_eq] at hv + obtain ⟨hj, a, c, he, _, hreq⟩ := hv + have he' : u = a := eq_of_heq (Sigma.mk.inj he).2 + subst a + exact h _ (b.overlap_neighbor A _ _ _ _ hreq) c hreq.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Programming edge widths from the bounded transcript +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +open scoped Pointwise + +variable {K G J : Type} [Field K] [Group G] {U : J → Subgroup G} {g : G} + {p : Parameters K U g} + +open scoped Classical in +instance inhabitedSites : Nonempty p.sites := ⟨⟨1, p.start⟩⟩ + +namespace Clock + +variable (c : p.Clock) +open scoped Classical in +/-- Computes the spot by the application `Address p.core p.radius`. -/ +abbrev Spot := Address p.core p.radius +open scoped Classical in +/-- The quantity computed by `Key (p.core ^ p.radius).card p.table`. -/ +abbrev Index := Key (p.core ^ p.radius).card p.table + +open scoped Classical in +/-- The read of type `ℕ` for the given inputs. -/ +def read (v : Fin (2 ^ c.bits)) (here : Index (p := p) → Bool) (e : Spot (p := p)) : ℕ := + if h : ∃ x, p.offers.write c.batch c.bound ⟨e.1.1, x⟩ = v then + p.offers.edgeCount p.path c.batch c.bound e.1.1 (fun u => here ⟨_, u⟩) e.2 c.width h.choose + else 0 + +open scoped Classical in +theorem read_eq (here : Index (p := p) → Bool) (e : Spot (p := p)) + (u : p.offers.Timeline c.batch c.bound e.1.1 c.width) : + c.read (p.offers.write c.batch c.bound ⟨e.1.1, u⟩) here e = + p.offers.edgeCount p.path c.batch c.bound e.1.1 (fun j => here ⟨_, j⟩) e.2 c.width u := by + have h : ∃ x, p.offers.write c.batch c.bound ⟨e.1.1, x⟩ = p.offers.write c.batch c.bound ⟨e.1.1, + u⟩ := + ⟨u, rfl⟩ + have he := (p.offers.write c.batch c.bound).injective h.choose_spec + rw [read, dite_eq_left h, eq_of_heq (Sigma.mk.inj he).2] + +variable {t : ℕ} (w : Fin (2 ^ t) → G) (j₀ : Fin (2 ^ t)) + +open scoped Classical in +/-- The value specified by `c.read (x.mark (x.label 1)) (owns p.table p.core p.radius p.unit g +p.reach w j₀ x.toRoot)`. -/ +def count (x : c.Input) := c.read (x.mark (x.label 1)) + (owns p.table p.core p.radius p.unit g p.reach w j₀ x.toRoot) + +open scoped Classical in +theorem count_local : Decor.Local (c.count w j₀) := + ((Decor.local_mark 1).pair (Decor.local_root + (owns_local p.table p.core p.radius p.unit g p.reach w j₀))).map (fun x => c.read x.1 x.2) + +open scoped Classical in +theorem count_bound : ∃ B : ℕ, ∀ x e, c.count w j₀ x e ≤ B := by + let T := Fin (2 ^ c.bits) × (Index (p := p) → Bool) × Spot (p := p) + let _ : Fintype T := Fintype.ofFinite _ + let f (v : T) := c.read v.1 v.2.1 v.2.2 + refine ⟨Finset.univ.sup f, fun x e => ?_⟩ + exact Finset.le_sup (f := f) (Finset.mem_univ (x.mark (x.label 1), + owns p.table p.core p.radius p.unit g p.reach w j₀ x.toRoot, e)) + +variable (hw : Set.range w = offsets p.core p.radius) (h₀ : w j₀ = 1) + {I : Type} [Fintype I] [MulAction G I] + +open scoped Classical in +/-- The width at of type `(p.balls I).Edge → ℕ`, constructed using `p.balls I`. -/ +def widthAt (u : c.path I) : (p.balls I).Edge → ℕ := + let b := p.balls I + let a := marketPorts (I := I) p.core p.radius p.unit g p.reach w hw + Protocol.edges (b.payload p.table) (b.decision p.offers c.μ p.path c.batch) + (b.tally p.table p.path p.limit a) c.width 0 u + +include h₀ in +open scoped Classical in +theorem count_branch (u : c.path I) (e : (p.balls I).Edge) : + c.count w j₀ ⟨⟨I, e.1⟩, c.selector u⟩ (address p.core p.unit p.radius g p.reach e) = + c.widthAt w hw u e := by + rcases e with ⟨i, e⟩ + let b := p.balls I + let a := marketPorts (I := I) p.core p.radius p.unit g p.reach w hw + let v := b.encodeLog p.offers c.μ p.path c.batch c.bound c.width 0 u i + let here := owns p.table p.core p.radius p.unit g p.reach w j₀ ⟨I, i⟩ + let o := address p.core p.unit p.radius g p.reach (⟨i, e⟩ : b.Edge) + have he : (fun j => here ⟨b.code i, j⟩) = b.here p.table a i := + funext fun j => owns_here _ _ _ _ _ _ w j₀ hw h₀ i j + simp only [count, Root.label, one_smul] + refine (c.read_eq here o v).trans ?_ + change p.offers.edgeCount _ _ _ (b.code i) (fun j => here ⟨b.code i, j⟩) e _ v = _ + rw [he] + exact (b.edge_count p.offers c.μ p.path c.batch c.bound a c.room + (p.path_pos.trans_le p.pay) p.pay _ _ (fun _ => by simp [bound]) u i e).symm + +open scoped Classical in +theorem width_total [Nonempty I] (u : c.path I) : + (∑ e, c.widthAt w hw u e) ≤ 1203 * Fintype.card I * c.width := by + let b := p.balls I + let a := marketPorts (I := I) p.core p.radius p.unit g p.reach w hw + have h := Protocol.edges_cost (b.payload p.table) (b.decision p.offers c.μ p.path c.batch) + (b.tally p.table p.path p.limit a) (b.tally_cost _ _ _ _ (p.ready I) p.local_supply) (c.runs I) + u + rw [zero_add] at h + change (↑(∑ e, c.widthAt w hw u e) : ℝ) ≤ _ at h + exact_mod_cast h + +end Clock +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Parameters +end + +/- +# Fixed choices for a transport program + +The clock, offset list, and bank of physical slots are fixed across +actions, input permutations and scales. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Coloring Transport +open scoped Pointwise + +variable {F G J : Type} [Field F] [Group G] {U : J → Subgroup G} {g : G} + (a : Parameters F U g) + +open scoped Classical in +/-- The data for the rig construction, including `clock`, `t`, `w`, `hw`, `j₀`. -/ +structure Rig where + /-- The `Rig` component of type `a.Clock`. -/ + clock : a.Clock + /-- The `Rig` field of type `ℕ`. -/ + t : ℕ + /-- The `Rig` component of type `B t → G`. -/ + w : B t → G + hw : Set.range w = offsets a.core a.radius + /-- The `Rig` field of type `B t`. -/ + j₀ : B t + h₀ : w j₀ = 1 + /-- The `Rig` field of type `ℕ`. -/ + R : ℕ + bound : ∀ x e, clock.count w j₀ x e ≤ R + /-- The `Rig` field of type `ℕ`. -/ + p : ℕ + /-- The `Rig` component of type `Bank a.core a.radius R p`. -/ + bank : Bank a.core a.radius R p + +open scoped Classical in +theorem Parameters.rig : Nonempty (Rig a) := by + obtain ⟨c⟩ := a.has_clock + obtain ⟨t, w, hw⟩ := exists_offsets a.core a.radius a.unit + have hx : (1 : G) ∈ Set.range w := by + rw [hw] + have h := Finset.one_mem_pow (n := a.radius) a.unit + change 1 ∈ a.core ^ a.radius * (a.core ^ a.radius)⁻¹ + simpa only [inv_one, mul_one] using Finset.mul_mem_mul h (Finset.inv_mem_inv h) + obtain ⟨j, hj⟩ := hx + obtain ⟨R, hR⟩ := c.count_bound w j + let V := Socket a.core a.radius R + let _ : Fintype V := Fintype.ofFinite V + exact ⟨⟨c, t, w, hw, j, hj, R, hR, _, Coloring.encode V⟩⟩ + +namespace Rig +variable {a} (s : Rig a) {I : Type} [Fintype I] [MulAction G I] + +open scoped Classical in +/-- Uses `s.clock.count s.w s.j₀` as the representation. -/ +abbrev count := s.clock.count s.w s.j₀ +open scoped Classical in +/-- Uses `s.clock.widthAt s.w s.hw u` as the representation. -/ +abbrev widthAt (u : s.clock.path I) := s.clock.widthAt s.w s.hw u + +open scoped Classical in +theorem bounded (u : s.clock.path I) (e : (a.balls I).Edge) : s.widthAt u e ≤ s.R := by + rw [widthAt, ← s.clock.count_branch s.w s.j₀ s.hw s.h₀] + exact s.bound _ _ + +open scoped Classical in +/-- Embeds `Protocol.End (s.widthAt u)` into `I × B s.p`. -/ +def endpoints (u : s.clock.path I) : Protocol.End (s.widthAt u) ↪ I × B s.p := + s.bank.endpoints a.unit g a.reach (s.widthAt u) (s.bounded u) + +open scoped Classical in +/-- The value specified by `(f x, s.bank.program a.unit g a.reach s.count x)`. -/ +def program {l : ℕ} (f : s.clock.Input → B l) (x : s.clock.Input) : Decor.Plan l s.p s.p := + (f x, s.bank.program a.unit g a.reach s.count x) + +open scoped Classical in +theorem program_local {l : ℕ} {f : s.clock.Input → B l} (hf : Decor.Local f) : + Decor.Local (s.program f) := + hf.pair (s.bank.program_local a.unit g a.reach s.count (s.clock.count_local s.w s.j₀)) + +end Rig +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Dual.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Dual.lean new file mode 100644 index 0000000000..c031cd7302 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Dual.lean @@ -0,0 +1,385 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.PartitionsPlane +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Nat.Log +public import Mathlib.FieldTheory.Finiteness +public import Mathlib.LinearAlgebra.FreeModule.Finite.Matrix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometrySharp +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryControl +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Run +public import Mathlib.FieldTheory.Finite.Extension +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.SortSpec +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Budget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Short +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Compatible +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.Scale +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.SumOut +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Close +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Estimate +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Scan +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Shared +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave +public import Mathlib.RingTheory.Algebraic.Cardinality + +/-! +# Address length for plane motions + +Choose the number of ordinary coordinates sufficiently large for any +prescribed reduction of the address length. Pad by fewer than a factor +of two. All motions on a given plane preserve the same partition. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped Classical in +private theorem sizes (q v w m : ℕ) (hq : 2 ≤ q) (hm : 0 < m) (hv : m * (2 + w) ≤ v + w) : + ∃ K : ℕ, ∀ h : ℕ, ∃ r c : ℕ, 0 < c ∧ + 2 ^ h ≤ q ^ ((v + w) * r) * c ∧ q ^ ((v + w) * r) * c < 2 ^ (h + 1) ∧ + q ^ ((2 + w) * r) * c ≤ 2 ^ (h / m + K) := by + let b := q ^ (v + w) + have hb : 1 < b := one_lt_pow₀ (by omega) (by nlinarith) + refine ⟨1 + Nat.clog 2 b, fun h => ?_⟩ + let n := 2 ^ h + have hn : 0 < n := by unfold n; positivity + let r := Nat.log b n + let a := b ^ r + let c := (n - 1) / a + 1 + have ha : 0 < a := by unfold a; positivity + have heq : q ^ ((v + w) * r) = a := pow_mul _ _ _ + have hlo : a ≤ n := Nat.pow_log_le_self b hn.ne' + have hhi : n < a * b := by + rw [show a * b = b ^ (r + 1) by rw [pow_succ]] + exact Nat.lt_pow_succ_log_self hb n + have hc : c ≤ b := (Nat.div_lt_iff_lt_mul ha).mpr (by rw [mul_comm]; omega) + have hc' : n - 1 < a * c := by + rw [mul_comm] + exact (Nat.div_lt_iff_lt_mul ha).mp (by unfold c; omega) + have hc'' : a * c ≤ n - 1 + a := by + unfold c + rw [mul_add, mul_one, mul_comm a] + exact Nat.add_le_add_right (Nat.div_mul_le_self _ _) _ + have hsize : q ^ ((2 + w) * r) ≤ 2 ^ (h / m + 1) := by + apply (pow_le_pow_iff_left₀ (by positivity) (by positivity) hm.ne').mp + rw [← pow_mul, ← pow_mul] + calc + q ^ ((2 + w) * r * m) = q ^ ((m * (2 + w)) * r) := by ring + _ ≤ q ^ ((v + w) * r) := Nat.pow_le_pow_right (by omega) (Nat.mul_le_mul_right r hv) + _ ≤ 2 ^ h := heq.le.trans hlo + _ ≤ 2 ^ ((h / m + 1) * m) := Nat.pow_le_pow_right (by decide) + ((Nat.div_lt_iff_lt_mul hm).mp (Nat.lt_succ_self _)).le + refine ⟨r, c, Nat.succ_pos _, ?_, ?_, ?_⟩ + · rw [heq]; change n ≤ _; omega + · rw [heq, pow_succ]; change _ < n * 2; omega + · rw [← Nat.add_assoc, pow_add] + exact Nat.mul_le_mul hsize (hc.trans (Nat.le_pow_clog (by decide) b)) + +variable {k V W : Type} [Field k] [Fintype k] + [AddCommGroup V] [Module k V] [Fintype V] [AddCommGroup W] [Module k W] [Fintype W] + +open scoped Classical in +private theorem card_labels (I R : ℕ → Type) [∀ j, Fintype (I j)] [∀ j, Fintype (R j)] (j : ℕ) : + Fintype.card (Labels V I (Aux k W I R) j) = + (Fintype.card k) ^ ((Module.finrank k V + Module.finrank k W) * Fintype.card (I j)) * + Fintype.card (R j) := by + have : Finite (W →ₗ[k] I j → k) := + Finite.of_injective (fun f : W →ₗ[k] I j → k => (f : W → I j → k)) DFunLike.coe_injective + let : Fintype (W →ₗ[k] I j → k) := Fintype.ofFinite _ + rw [← Nat.card_eq_fintype_card] + unfold Labels Aux + rw [Nat.card_prod, Nat.card_prod, Nat.card_eq_fintype_card, Fintype.card_fun, + Module.card_eq_pow_finrank (K := k) (V := V), Nat.card_eq_fintype_card, + Module.card_eq_pow_finrank (K := k) (V := W →ₗ[k] I j → k), + Module.finrank_linearMap, Module.finrank_pi, Nat.card_eq_fintype_card] + ring + +open scoped Classical in +theorem address_sizes (m : ℕ) (hm : 0 < m) + (hv : m * (2 + Module.finrank k W) ≤ Module.finrank k V + Module.finrank k W) : + ∃ (I R : ℕ → Type) (_ : ∀ h, Fintype (I h)) (_ : ∀ h, Fintype (R h)) + (_ : ∀ h, Nonempty (R h)) (K : ℕ), ∀ h, + 2 ^ h ≤ Fintype.card (Labels V I (Aux k W I R) h) ∧ + Fintype.card (Labels V I (Aux k W I R) h) < 2 ^ (h + 1) ∧ + ∀ P : VPlane k V, Fintype.card (Labels P.1 I (Aux k W I R) h) ≤ 2 ^ (h / m + K) := by + obtain ⟨K, hK⟩ := sizes (Fintype.card k) _ _ m Fintype.one_lt_card hm hv + choose r c hc hl hu hd using hK + refine ⟨fun h => Fin (r h), fun h => Fin (c h), inferInstance, inferInstance, + fun h => ⟨⟨0, hc h⟩⟩, K, fun h => ?_⟩ + simp only [card_labels, Fintype.card_fin] + exact ⟨hl h, hu h, fun P => by rw [P.2]; exact hd h⟩ + +omit [Fintype k] [Fintype V] in +open scoped Classical in +/-- The second factor is the fixed capacity of a hop along this plane. -/ +theorem plane_partition {J : Type} (I R : J → Type) (P : VPlane k V) : + ∃ (D : Submodule k V) (f : ∀ j, Labels V I R j ≃ (I j → D) × Labels P.1 I R j), + ∀ g ∈ motion I R P.1, ∀ j x, (f j (g j x)).1 = (f j x).1 := by + obtain ⟨D, hD⟩ := P.1.exists_isCompl + let e := (D.prodEquivOfIsCompl P.1 hD.symm).symm + let f (j : J) : Labels V I R j ≃ (I j → D) × Labels P.1 I R j := + { toFun := fun x => (fun i => (e (x.1 i)).1, (fun i => (e (x.1 i)).2), x.2) + invFun := fun y => (fun i => e.symm (y.1 i, y.2.1 i), y.2.2) + left_inv := by intro x; simp + right_inv := by intro y; simp } + refine ⟨D, f, fun g hg j x => ?_⟩ + funext i + change (e ((g j x).1 i)).1 = (e (x.1 i)).1 + have hz : (e ((g j x).1 i - x.1 i)).1 = 0 := + (Submodule.prodEquivOfIsCompl_symm_apply_fst_eq_zero _ _ hD.symm).mpr (hg j x i) + simpa only [map_sub, Prod.fst_sub, sub_eq_zero] using hz + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Choosing a single routing layout and test menu for all heights -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Coloring + +variable {F k V W L : Type} [Field F] + +open scoped Classical in +private theorem make_routes [Field k] [Fintype k] [AddCommGroup V] [Module k V] [Finite V] + [AddCommGroup W] [Module k W] [Fintype W] {c : ℕ} (hf : Factors F c) + (hmod : HasModels F (flagPoint (K := k) (V := V)) Prod.fst Prod.fst + (affineGraph (K := k) (V := W))) (hV : 2 ≤ Module.finrank k V) (hW : 4 < Module.finrank k W) + (m : ℕ) (hm : 0 < m) (hd : m * (2 + Module.finrank k W) ≤ Module.finrank k V + + Module.finrank k W) : + Nonempty (Routes F m) := by + let : Fintype V := Fintype.ofFinite V + obtain ⟨I, R, _, _, _, K, hK⟩ := address_sizes m hm hd + let X := Labels V I (Aux k W I R) + let x (h : ℕ) := Fintype.equivFin (X h) + let e (h : ℕ) : X h ↪ B (h + 1) := (x h).toEmbedding.trans (Fin.castLEEmb (hK h).2.1.le) + let b (h : ℕ) : B h ↪ X h := (Fin.castLEEmb (hK h).1).trans (x h).symm.toEmbedding + have hi (h : ℕ) (i : B h) : (e h (b h i)).val = i.val := by simp [e, b] + have : Nonempty (VPlane k V) := flat_nonempty hV + have : Nonempty (VPoint k V) := flat_nonempty (le_trans (by decide) hV) + let M := Coloring.system F e hf + let G := M.planes I R + have gen : iSup G = ⊤ := M.motion_generate I _ hV + obtain ⟨params⟩ := Rigid.parameters gen (M.rigid I R hV hW) hmod (Coloring.target F e)⁻¹ + refine ⟨⟨X, fun h => ⟨(hK h).1, (hK h).2.1⟩, e, b, hi, VPlane k V, G, params, K, ?_⟩⟩ + intro g hg h + obtain ⟨P, hp⟩ := Set.mem_iUnion.mp (params.hop hg) + obtain ⟨D, f, he⟩ := plane_partition I (Aux k W I R) P + refine ⟨_, _, inferInstance, inferInstance, f h, (hK h).2.2 P, ?_⟩ + intro σ i + let t := Function.update (fun j => (1 : Equiv.Perm (X j))) h σ + have hh := he _ (hp t) h i + change (f h (g.val h (t h) i)).1 = (f h i).1 at hh + simpa [t] using hh + +open scoped Classical in +/-- Degree seven supplies a field of size at least 128 even in +characteristic two. Degree five suffices for four independent +parameters in the affine pair argument. -/ +theorem routes_of_shared_price [Finite F] + (hs : Prices.SharedPrice (AlgebraicClosure F)) + (m : ℕ) (hm : 0 < m) : Nonempty (Routes F m) := by + let p := ringChar F + have : Fact p.Prime := ⟨CharP.char_is_prime F _⟩ + let k := FiniteField.Extension F p 7 + have : CharP k p := charP_of_injective_algebraMap' F p + let W := FiniteField.Extension k p 5 + let V := Fin (7 * m) → k + let L := AlgebraicClosure F + let : Algebra k L := (IsAlgClosed.lift : k →ₐ[F] L).toRingHom.toAlgebra + let : Algebra W L := (IsAlgClosed.lift : W →ₐ[k] L).toRingHom.toAlgebra + let : Fintype k := Fintype.ofFinite k + let : Fintype W := Fintype.ofFinite W + have hq : 100 ≤ Fintype.card k := by + rw [Fintype.card_eq_nat_card, show Nat.card k = Nat.card F ^ 7 from + FiniteField.natCard_extension F p 7] + exact le_trans (show 100 ≤ 2 ^ 7 by decide) (Nat.pow_le_pow_left Finite.one_lt_card _) + have hw : Module.finrank k W = 5 := FiniteField.finrank_extension k p 5 + have hv : Module.finrank k V = 7 * m := by simp [V] + exact make_routes (V := V) (W := W) (Coloring.factors F) (models_of_shared_price hs hq) + (by omega) (by omega) m hm (by rw [hv, hw]; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Selecting keys and checking the stable order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {F : Type} [Field F] {h w k W m : ℕ} + +private theorem key_net (F : Type) [Field F] (e : slots (word k) ↪ slots (word w)) : + DNet F (word w) (word k) (key e) w := by + classical + let R : Set (slots (word w)) := Set.range e + let _ : Fintype (↥(Rᶜ)) := Fintype.ofFinite _ + let b : Wire := word (Fintype.card ↥(Rᶜ)) + let z : slots b ≃ ↥(Rᶜ) := @Fintype.equivOfCardEq (slots b) ↥(Rᶜ) (slotsFintype b) _ + (by rw [card_slots]; exact wd_word _) + let r : slots (.pair (word k) b) ≃ slots (word w) := + ((Equiv.ofInjective e e.injective).sumCongr z).trans (Equiv.Set.sumCompl R) + have hw : wd (.pair (word k) b) = w := by + exact (card_slots _).symm.trans ((@Fintype.card_congr _ _ (slotsFintype _) (slotsFintype _) + r).trans + ((card_slots _).trans (wd_word _))) + have he : (fun x : Val (word w) => (reindex r x).1) = key e := by + funext x + apply (bits (word k)).injective + funext i + rw [key, Equiv.apply_symm_apply] + exact bits_reindex r x (.inl i) + rw [← he] + exact ((DNet.fst F (word k) b).pre (rewire_reindex r)).mono hw.le + +private theorem stable_unique {α : Type} {d : α → Val (word k)} {xs ys zs : List α} + (hy : Radix.Stable d xs ys) (hz : Radix.Stable d xs zs) : ys = zs := by + have h := hy.1.trans hz.1.symm + have h₁ := hy.2.1 + have h₂ := hz.2.1 + have h₃ i := (hy.2.2 i).trans (hz.2.2 i).symm + clear hy hz xs + induction ys generalizing zs with + | nil => exact h.symm.eq_nil.symm + | cons y ys ih => + cases zs with + | nil => simp at h + | cons z zs => + have min₁ : d y ≤ d z := by + rcases List.mem_cons.mp (h.mem_iff.mpr (List.mem_cons_self ..)) with eq | mem + · exact eq ▸ le_rfl + · exact (List.pairwise_cons.mp h₁).1 _ mem + have min₂ : d z ≤ d y := by + rcases List.mem_cons.mp (h.mem_iff.mp (List.mem_cons_self ..)) with eq | mem + · exact eq ▸ le_rfl + · exact (List.pairwise_cons.mp h₂).1 _ mem + have eq := le_antisymm min₁ min₂ + have same : y = z := by + have heads := congrArg List.head? (h₃ (d z)) + simpa [eq] using heads + subst z + congr 1 + apply ih h.cons_inv (List.pairwise_cons.mp h₁).2 (List.pairwise_cons.mp h₂).2 + intro i + have he := h₃ i + by_cases hj : d y = i <;> simpa [hj] using he + +/-- A sufficiently wide tagged-permutation network supplies both +checks, including the cost of exposing their independent arguments. -/ +theorem sorting_bound (ht : Radix.Tag F h W m) (hu : 1 + h + 2 * w ≤ W) : + SortingBound F h w ((4 * m + 3000000 * 2 ^ h * W : ℕ) : ℝ) := by + constructor + · obtain ⟨v, hv, hnet⟩ := Tagged.tag_shrink (b := word w) (Tagged.Batch.of_net ht 1) + (by simp only [wd_word]; omega) + refine ⟨v, ?_, ?_⟩ + · simpa only [power, mul_one] using (hnet.pre (.unit' _)).post (.unit' _) + · simp only [wd_word, one_mul] at hv + apply Nat.cast_le.mpr + have hb : 2 ^ h * (h + 2 * w) ≤ 2 ^ h * W := Nat.mul_le_mul_left _ (by omega) + have hc : 2 ^ h * (h + 2 * W) ≤ 2 ^ h * (3 * W) := Nat.mul_le_mul_left _ (by omega) + linarith [Nat.zero_le (2 ^ h * W)] + · intro k e + have hw : k ≤ w := by simpa using Fintype.card_le_of_injective _ e.injective + have bound : 1 + h + wd (word w) + k ≤ W := by + simp only [wd_word] + omega + obtain ⟨f, ⟨v, hv, hnet⟩, hs⟩ := Radix.stable_net (key_net F e) bound ht + have he (x y : Val (tree h (word w))) : + Radix.Stable (key e) (flatten h x) (flatten h y) ↔ f x = y := + ⟨fun hy => Tagged.flatten_inj h (stable_unique (hs x) hy), fun h => h ▸ hs x⟩ + refine ⟨v, ?_, ?_⟩ + · unfold stableTensor + simp only [he] + exact hnet + · apply Nat.cast_le.mpr + have hh : 2 ^ h * w ≤ 2 ^ h * W := Nat.mul_le_mul_left _ (by omega) + linarith [Nat.zero_le (2 ^ h * W)] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Tagged permutations and batched lookup from shared prices + +For each height ratio the price tests give a fixed hop menu. The +controller handles an arbitrary input permutation; the inventory +bound is uniform in the ratio. Installing and recursively realizing +the shorter calls gives the wide-record bound. Radix passes supply +the logarithmic-width estimate. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {F : Type} [Field F] [Finite F] + +theorem wide_of_shared_price (hs : Prices.SharedPrice (AlgebraicClosure F)) : Radix.WideTag F := by + apply Radix.wide_of_protocol + apply Install.protocol_of_open + apply Install.open_of_groups + apply Transport.groups_of_local + apply local_of_routes + intro m hm + obtain ⟨t⟩ := routes_of_shared_price (F := F) hs m hm + obtain ⟨r⟩ := t.params.rig + exact ⟨t, r, Rig.compatible t r⟩ + +theorem sorting_of_shared_price (hs : Prices.SharedPrice (AlgebraicClosure F)) : + ∃ p : ℝ, 1 < p ∧ p < 2 ∧ Lookup.Sorting F p := by + obtain ⟨p, hl, hu, h⟩ := Radix.short_of_wide (wide_of_shared_price hs) + exact ⟨p, hl, hu, Lookup.sorting_of_tag hl.le h⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# A strict dual saving supplies sorting and local concentration + +The dual exponent is unchanged on field extension. This allows the +synchronization argument to use the countable algebraic closure while +all routing and concentration estimates remain over the original field. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem Rectangle.dual_extension (F K : Type*) [Field F] [Field K] [Algebra F K] + {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) : dual K a b = dual F a b := by + unfold dual + apply congrArg sSup + ext c + simp only [Set.mem_ofPred_eq] + by_cases hc : c ∈ Set.Icc 0 (min a b) + · rw [exponent_extension F K ha hb hc.1] + · simp only [hc, false_and] + +variable {F : Type} [Field F] [Finite F] + +theorem shared_of_dual (h : 1 / 2 < Rectangle.dual F 1 1) : + Prices.SharedPrice (AlgebraicClosure F) := by + by_contra bad + obtain ⟨hs, hr⟩ := contact_of_not_shared bad + exact h.ne' (Rectangle.dual_square hr hs) + +theorem wide_of_dual (h : 1 / 2 < Rectangle.dual F 1 1) : Radix.WideTag F := + Routing.wide_of_shared_price (shared_of_dual h) + +theorem local_of_dual (h : 1 / 2 < Rectangle.dual F 1 1) (ℓ : ℕ) : Rounds.LocalLaw F ℓ := + Rounds.local_law (shared_of_dual h) ℓ + +theorem local_of_saving (h : omega F < 9 / 4) (ℓ : ℕ) : Rounds.LocalLaw F ℓ := + Rounds.local_law (shared_of_saving h) ℓ + +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Fixed.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Fixed.lean new file mode 100644 index 0000000000..240180108a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Fixed.lean @@ -0,0 +1,907 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Round +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Ranks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Address +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryComparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Decor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Parameters +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.Named +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.SumOut + +/-! # Rounding repetition counts for a scalable substitution -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Finset + +variable {A : Type} [Fintype A] [DecidableEq A] + +/-- Round each count up to a whole block, charging one extra block per +letter. Put the unused budget on the distinguished letter. -/ +def rounded (a₀ : A) (m z : ℕ) (t : A → ℕ) (a : A) : ℕ := + t a / z + 1 + if a = a₀ then m - ∑ j, t j / z else 0 + +theorem rounded_mem (a₀ : A) {m z : ℕ} (hz : 0 < z) + {t : A → ℕ} (ht : t ∈ histograms A (m * z)) : + rounded a₀ m z t ∈ histograms A (m + Fintype.card A) := by + have hs : ∑ a, t a / z ≤ m := by + apply Nat.le_of_mul_le_mul_right _ hz + rw [sum_mul, ← mem_histograms.mp ht] + exact sum_le_sum fun a _ => Nat.div_mul_le_self _ _ + apply mem_histograms.mpr + simp only [rounded, sum_add_distrib, sum_const, card_univ, nsmul_eq_mul, Nat.cast_id, + mul_one, sum_ite_eq', mem_univ, ite_true] + omega + +theorem rounded_covers (a₀ : A) (m : ℕ) {z : ℕ} (hz : 0 < z) (t : A → ℕ) (a : A) : + t a ≤ rounded a₀ m z t a * z := by + rw [mul_comm] + exact (Nat.lt_mul_div_succ _ hz).le.trans (Nat.mul_le_mul_left z (Nat.le_add_right _ _)) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Local coefficients of a rounded substitution + +Occurrences of each letter use consecutive addresses. All addresses +left over after rounding contract to the scalar one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.WordSum + +open Finset Control + +variable {K S X Y A : Type} [Field K] [Fintype A] [DecidableEq A] {n : ℕ} + +/-- The indexed operation `rounded a₀ m z (fun a => histogram w a none)`. -/ +def profile (a₀ : A) (m z : ℕ) (w : Fin n → A) : A → ℕ := + rounded a₀ m z (fun a => histogram w a none) + +theorem profile_mem (a₀ : A) {m z : ℕ} (hn : n = m * z) (hz : 0 < z) (w : Fin n → A) : + profile a₀ m z w ∈ histograms A (m + Fintype.card A) := by + apply rounded_mem a₀ hz + rw [mem_histograms, ← hn] + simpa only [histogram_none, card_univ, Fintype.card_fin] using + (card_eq_sum_card_fiberwise (s := univ) (t := univ) (f := w) (by simp)).symm + +/-- Indexes the address by the coordinates of `Σ a : A, Fin (t a * z)`. -/ +abbrev Address (z : ℕ) (t : A → ℕ) := Σ a : A, Fin (t a * z) + +variable [Inhabited Y] + +/-- Values on out-of-range addresses only matter for rejected profiles. -/ +def factor (L : A → S → X → Y → K) (U : A → S → Y → K) + (z : ℕ) (w : Fin n → A) (t : A → ℕ) (s : S) (x : Fin n → X) (y : Address z t → Y) : K := + (∏ i, L (w i) s (x i) (if h : rank w i < t (w i) * z then y ⟨w i, ⟨rank w i, h⟩⟩ else default)) * + ∏ u : Address z t, if histogram w u.1 none ≤ u.2.val then U u.1 s (y u) else 1 + +variable [Fintype S] [DecidableEq S] [Fintype Y] + (P : A → (S → Y) → K) (L : A → S → X → Y → K) (U : A → S → Y → K) + (hU : ∀ a, ∑ y, (∏ s, U a s (y s)) * P a y = 1) + +include hU in +private theorem contract (w : Fin n → A) {z : ℕ} (t : A → ℕ) + (ht : ∀ a, histogram w a none ≤ t a * z) (x : Fin n → S → X) : + (∑ y : Address z t → S → Y, + (∏ s, factor L U z w t s (fun i => x i s) (fun u => y u s)) * ∏ u, P u.1 (y u)) = + ∏ i, ∑ y, (∏ s, L (w i) s (x i s) (y s)) * P (w i) y := by + classical + have ok (i) := (rank_lt w i).trans_le (ht (w i)) + let send (i : Fin n) : Address z t := ⟨w i, ⟨rank w i, ok i⟩⟩ + have inj : Function.Injective send := fun i j h => + rank_injective w (congrArg (fun u : Address z t => (u.1, u.2.val)) h) + let unused (u : Address z t) := histogram w u.1 none ≤ u.2.val + have used (i) : ¬ unused (send i) := (rank_lt w i).not_ge + have spare {u} (hu : u ∉ univ.image send) : unused u := by + by_contra h + obtain ⟨i, hi, hr⟩ := (rank_range w u.1 u.2.val).mpr (lt_of_not_ge h) + refine hu (mem_image.mpr ⟨i, mem_univ _, Sigma.ext hi ?_⟩) + exact (Fin.heq_ext_iff (congrArg (fun a => t a * z) hi)).mpr hr + let row (s : S) (u : Address z t) (v : Y) := + (∏ i, if send i = u then L (w i) s (x i s) v else 1) * + if unused u then U u.1 s v else 1 + have split (s) (y : Address z t → Y) : + factor L U z w t s (fun i => x i s) y = ∏ u, row s u (y u) := by + unfold row + rw [prod_mul_distrib, prod_comm] + simp only [factor, dite_eq_left (ok _), prod_ite_eq, mem_univ, ite_true] + rfl + let weight (u : Address z t) (v : S → Y) := (∏ s, row s u (v s)) * P u.1 v + have factors (y : Address z t → S → Y) : + (∏ s, factor L U z w t s (fun i => x i s) (fun u => y u s)) * (∏ u, P u.1 (y u)) = + ∏ u, weight u (y u) := by + simp_rw [split] + rw [prod_comm, ← prod_mul_distrib] + simp_rw [factors] + rw [← Fintype.prod_sum weight] + have empty (u) (_ : u ∈ univ) (hu : u ∉ univ.image send) : ∑ y, weight u y = 1 := by + have hne (i) : send i ≠ u := fun he => hu (mem_image.mpr ⟨i, mem_univ _, he⟩) + simpa only [weight, row, hne, ite_false, prod_const_one, spare hu, ite_true, one_mul] + using hU u.1 + rw [← prod_subset (subset_univ _) empty, prod_image inj.injOn] + apply prod_congr rfl + intro i _ + simp only [weight, row, inj.eq_iff, prod_ite_eq', mem_univ, ite_true, used, ite_false, mul_one] + rfl + +include hU in +/-- Separate the outer histogram from the selector word. Exactly one +histogram contributes per word. The identity does not divide by a +multiplicity and holds in positive characteristic. -/ +theorem expand (T : (S → X) → K) + (hT : ∀ x, T x = ∑ a, ∑ y, (∏ s, L a s (x s) (y s)) * P a y) + (a₀ : A) {m z : ℕ} (hn : n = m * z) (hz : 0 < z) (x : Fin n → S → X) : + (∏ i, T (x i)) = + ∑ t : ↥(histograms A (m + Fintype.card A)), ∑ w : Fin n → A, + if profile a₀ m z w = t.val then + ∑ y : Address z t.val → S → Y, + (∏ s, factor L U z w t.val s (fun i => x i s) (fun u => y u s)) * + ∏ u, P u.1 (y u) + else 0 := by + classical + rw [sum_comm] + simp_rw [hT] + rw [Fintype.prod_sum] + apply sum_congr rfl + intro w _ + let t : ↥(histograms A (m + Fintype.card A)) := ⟨profile a₀ m z w, profile_mem a₀ hn hz w⟩ + rw [Fintype.sum_eq_single t] + · rw [ite_eq_left (show profile a₀ m z w = t.val from rfl)] + exact (contract P L U hU w t.val (rounded_covers a₀ m hz _) x).symm + · intro u hu + exact ite_eq_right (fun he => hu (Subtype.ext he.symm)) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.WordSum +end + +/- +# Checking a rounded profile + +The total count fixes the distinguished letter. Every other count can +be checked in a separate table on just one logarithmic-width counter. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.WordSum + +open Control Install Finset + +variable {K A R : Type} [Field K] [Fintype A] [DecidableEq A] [Fintype R] + (a₀ : A) (D : (R → Bool) → A) + +private theorem profile_eq {m z n : ℕ} (hn : n = m * z) (hz : 0 < z) + (t : ↥(histograms A (m + Fintype.card A))) (w : Fin n → A) : + profile a₀ m z w = t.val ↔ ∀ a ≠ a₀, histogram w a none / z + 1 = t.val a := by + have e (a : A) (ha : a ≠ a₀) : profile a₀ m z w a = histogram w a none / z + 1 := by + simp [profile, rounded, ha] + constructor + · exact fun he a ha => (e a ha).symm.trans (congrFun he a) + · intro h + have h' (a : A) (ha : a ≠ a₀) : profile a₀ m z w a = t.val a := (e a ha).trans (h a ha) + funext a + by_cases ha : a ≠ a₀ + · exact h' a ha + have : a = a₀ := not_ne_iff.mp ha + subst a + have hs := (mem_histograms.mp (profile_mem a₀ hn hz w)).trans (mem_histograms.mp + t.property).symm + rw [← sum_erase_add univ _ (mem_univ a₀), ← sum_erase_add univ _ (mem_univ a₀), + sum_congr rfl (fun i hi => h' i (mem_erase.mp hi).1)] at hs + exact add_left_cancel hs + +omit [Fintype R] in +/-- Tests on all counters cost linear times logarithmic in the number +of positions, for each fixed alphabet and encoding. -/ +theorem check_net [Finite R] : ∃ B : ℕ, ∀ h m z : ℕ, 2 ^ h = m * z → 0 < z → + ∀ t : ↥(histograms A (m + Fintype.card A)), + Weight K (fun x : Fin (2 ^ h) × R → Bool => + if profile a₀ m z (letters D x) = t.val then 1 else 0) (B * 2 ^ h * (h + 1)) := by + let : Fintype R := Fintype.ofFinite R + let B := rankCost R A + Fintype.card A + 20 + refine ⟨Fintype.card R + Fintype.card A * (5 * Fintype.card R + B), fun h m z hn hz t => ?_⟩ + let test (a : A) (x : Fin (2 ^ h) × R → Bool) := + if a ≠ a₀ → histogram (letters D x) a none / z + 1 = t.val a then (1 : K) else 0 + have one (a : A) : Weight K (test a) (B * 2 ^ h * (h + 1)) := by + let q (x : slots (word (h + 1)) → Bool) := + if a ≠ a₀ → (decode (h + 1) x).val / z + 1 = t.val a then (1 : K) else 0 + let select (i : slots (word (h + 1))) : (A ⊕ Fin (2 ^ h)) × slots (word (h + 1)) := (.inl a, i) + have H := (ranks_bnet K R A D h).weight ((Weight.dense K _ q).pull select) + have he : (fun x => q (x ∘ select)) ∘ ranks D h = test a := by + funext x + have hc : histogram (letters D x) a none < 2 ^ (h + 1) := + (histogram_le _ _ _).trans_lt (by exact pow_lt_pow_right₀ (by decide) (by omega)) + change q (bits (word (h + 1)) (Lookup.bits (h + 1) (histogram (letters D x) a none))) = _ + simp [q, test, decode, index, Lookup.value_bits hc] + rw [he] at H + apply H.mono + simp only [Fintype.card_prod, Fintype.card_sum, Fintype.card_fin, card_slots, wd_word, B, + show Fintype.card (slots .bit) = 1 from rfl, Nat.add_comm 1 h, pow_succ] + have hp : 1 ≤ 2 ^ h := Nat.one_le_pow _ _ (by decide) + nlinarith only [Nat.mul_le_mul_right (Fintype.card A * (h + 1)) hp, + Nat.mul_le_mul_right (h + 1) hp, Nat.zero_le (2 ^ h * h)] + have hv : (fun x => ∏ a, test a x) = + (fun x => if profile a₀ m z (letters D x) = t.val then (1 : K) else 0) := by + funext x + simp only [profile_eq a₀ hn hz] + by_cases hp : ∀ a ≠ a₀, histogram (letters D x) a none / z + 1 = t.val a + · rw [ite_eq_left hp] + exact prod_eq_one fun a _ => ite_eq_left (hp a) + · rw [ite_eq_right hp] + obtain ⟨a, ha⟩ := not_forall.mp hp + exact prod_eq_zero (mem_univ a) (ite_eq_right ha) + rw [← hv] + apply (Weight.finite_product test one).mono + simp only [Fintype.card_prod, Fintype.card_fin] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.WordSum +end + +/- # Exact coverage at arbitrary scale with a fixed selector set -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Proposal + +open Spectral Stock Finset + +variable {K S B I E J : Type} [Field K] [Fintype S] [Fintype B] [DecidableEq S] + [DecidableEq B] [Nonempty S] [Fintype I] [Fintype E] [Fintype J] + [DecidableEq I] [DecidableEq E] [DecidableEq J] {T : J → Tensor K S} {H : ℝ} + +/-- After fixing the number of blocks, every positive tensor power +uses the same selector alphabet of rounded histograms. -/ +theorem flex_covers (q : Proposal T H) (g : J → I ⊕ E) (u : Finset J) (m : ℕ) + (hd : ∀ j ∈ q.demand, ∃ i, g j = .inl i) (hu : (2 : Tensor K S) ≤ ∏ j ∈ u, T j) + (n : S → B) (U : I ⊕ E → Tensor K B) (he : ∀ j, Tensor.place n (T j) = U (g j)) + (hT : ∀ j, 1 ≤ T j) (hm : 0 < m) (z : ℕ) (hz : 0 < z) : + (q.flex g u m).Covers (fun i => U (.inl i) ^ z) (fun e => U (.inr e) ^ z) := by + classical + let : MulLeftMono (Tensor K S) := ⟨fun c a b h => Tensor.mul_le_mul_left _ _ _ h⟩ + let V j := bundle T (q.orders j) + have hV (j) : 1 ≤ V j := by + apply one_le_prod + intro i _ + have h := pow_le_pow_left' (hT i) (q.orders j i) + rw [one_pow] at h + exact h + let l := m + Fintype.card q.move.letter + have round (t) (ht : t ∈ histograms q.move.letter (m * z)) : + ∃ h ∈ histograms q.move.letter l, bundle V t ≤ (bundle V h) ^ z := by + have hpos : 0 < ∑ i, t i := by rw [mem_histograms.mp ht]; exact Nat.mul_pos hm hz + obtain ⟨a, _, _⟩ := Finset.exists_ne_zero_of_sum_ne_zero hpos.ne' + refine ⟨rounded a m z t, rounded_mem a hz ht, ?_⟩ + rw [bundle, bundle, ← prod_pow] + exact prod_le_prod fun i _ => by + rw [← pow_mul] + exact pow_le_pow_right' (hV i) (rounded_covers a m hz t i) + have cmp := q.batch_scaled u hu m l z (Nat.le_add_right _ _) round + refine q.place_trade g u m l hd (fun j => T j ^ z) n (fun j => U j ^ z) ?_ ?_ + · intro j + have aux (k : ℕ) : Tensor.place n (T j ^ k) = U (g j) ^ k := by + induction k with + | zero => simp [Tensor.place_one] + | succ k ih => rw [pow_succ, Tensor.place_mul, ih, he, pow_succ] + exact aux z + · have hp (t) : bundle (fun j => T j ^ z) t = (bundle T t) ^ z := by + rw [bundle, bundle, ← prod_pow] + exact prod_congr rfl (fun i _ => pow_right_comm _ _ _) + simpa only [hp] using cmp + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Proposal +end + +/- +# A fixed local decision at every center + +A price vector restricted to a shape determines whether it acts and +what it does. Acting at every enabled center avoids testing a global +average or computing a packing in the protocol. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral + +variable {K I S : Type} [Field K] [Fintype I] [DecidableEq I] [Fintype S] [DecidableEq S] + {A : Finset (Tensor K S)} {N M : ℕ} {ρ : ℝ} (a : Atlas N A M ρ) + +namespace Atlas + +open scoped Classical in +/-- The condition `∃ q ∈ a.menu s, q.demand ⊆ s.2.demands A ∧ q.demand.Nonempty ∧ q.Works +a.margin p` on the specified data. -/ +def Enabled (s : Shape N) (p : s.2.Goods A → ℝ) : Prop := + ∃ q ∈ a.menu s, q.demand ⊆ s.2.demands A ∧ q.demand.Nonempty ∧ q.Works a.margin p + +open scoped Classical in +/-- Computes the select by the application `Classical.choose h`. -/ +def select (s : Shape N) (p : s.2.Goods A → ℝ) (h : a.Enabled s p) : s.Move A := + Classical.choose h + +open scoped Classical in +theorem selected (s : Shape N) (p : s.2.Goods A → ℝ) (h : a.Enabled s p) : + let q := a.select s p h + q ∈ a.menu s ∧ q.demand ⊆ s.2.demands A ∧ q.demand.Nonempty ∧ q.Works a.margin p := + Classical.choose_spec h + +open scoped Classical in +/-- The extra supply for rounding each symbol costs at most half the saving. -/ +def Room (m : ℕ) : Prop := + ∀ s q, q ∈ a.menu s → Fintype.card q.move.letter ≤ m ∧ + ∀ p : s.2.Goods A → ℝ, p ≤ (fun _ => (M : ℝ)) → + (Fintype.card q.move.letter : ℝ) * q.move.block * (∑ j ∈ q.demand, p j) ≤ m * (a.margin / 2) + +open scoped Classical in +theorem room : ∃ m₀ : ℕ, ∀ m ≥ m₀, a.Room m := by + obtain ⟨C, hC⟩ := a.bound (fun _ q => Fintype.card q.move.letter) + obtain ⟨D, hD⟩ := a.bound (fun _ q => Fintype.card q.move.letter * q.move.block * q.demand.card * + M) + obtain ⟨t, ht⟩ := exists_nat_gt ((D : ℝ) / (a.margin / 2)) + refine ⟨max C t, fun m hm s q hq => ⟨(hC _ _ hq).trans ((le_max_left _ _).trans hm), ?_⟩⟩ + intro p hp + calc + _ ≤ (Fintype.card q.move.letter : ℝ) * q.move.block * (q.demand.card * M) := by + refine mul_le_mul_of_nonneg_left ?_ (by positivity) + simpa using Finset.sum_le_sum (s := q.demand) fun i _ => hp i + _ ≤ (D : ℝ) := by rw [← mul_assoc]; exact_mod_cast hD _ _ hq + _ ≤ _ := (div_le_iff₀ (half_pos a.positive)).mp (ht.le.trans + (Nat.cast_le.mpr ((le_max_right _ _).trans hm))) + +end Atlas + +namespace Market + +variable (b : Market I N) (p : b.Request A → ℝ) + +open scoped Classical in +/-- The subset of all indices on which the defining predicate holds. -/ +def active : Finset I := Finset.univ.filter fun i + => a.Enabled (b.code i) (b.rates A p ∘ b.assign A i) + +open scoped Classical in +/-- The value specified by `a.select (b.code i) (b.rates A p ∘ b.assign A i) +(Finset.mem_filter.mp i.property).2`. -/ +def moveAt (i : b.active a p) : (b.code i).Move A := + a.select (b.code i) (b.rates A p ∘ b.assign A i) (Finset.mem_filter.mp i.property).2 + +omit [DecidableEq I] in +open scoped Classical in +theorem moving (i : b.active a p) : + let q := b.moveAt a p i + q ∈ a.menu (b.code i) ∧ q.demand ⊆ (b.shape i).demands A ∧ q.demand.Nonempty ∧ + q.Works a.margin (b.rates A p ∘ b.assign A i) := + a.selected _ _ _ + +open scoped Classical in +/-- The value specified by `(b.moveAt a p i).flex (b.assign A i) ((b.shape i).links A) m`. -/ +def localMove (m : ℕ) (i : b.active a p) : Intervention (b.Request A) b.Edge := + (b.moveAt a p i).flex (b.assign A i) ((b.shape i).links A) m + +open scoped Classical in +/-- Computes the policy by the application `Intervention.parallel (b.localMove a p m)`. -/ +def policy (m : ℕ) : Intervention (b.Request A) b.Edge := + Intervention.parallel (b.localMove a p m) + +open scoped Classical in +theorem local_overlap [Nonempty S] (m : ℕ) : + Intervention.Overlap (b.localMove a p m) N := by + intro x + let J := b.active a p + let U := Finset.univ.filter fun j : J => b.home A x ∈ b.support j + have h : U.map (Function.Embedding.subtype _) ⊆ + Finset.univ.filter (fun j => b.home A x ∈ b.support j) := by + rintro _ hi + obtain ⟨j, hj, rfl⟩ := Finset.mem_map.mp hi + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, (Finset.mem_filter.mp hj).2⟩ + refine ⟨U, ?_, fun j he => ?_⟩ + · simpa only [Finset.card_map] using (Finset.card_le_card h).trans (b.count_support _) + · obtain ⟨k, hk⟩ := (b.moveAt a p j).flex_support _ _ _ he + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, b.home_mem A j k x hk⟩ + +omit [DecidableEq I] in +open scoped Classical in +theorem demand_slot (i : b.active a p) : + ∀ j ∈ (b.moveAt a p i).demand, ∃ l, b.assign A i j = .inl l := by + intro j hj + obtain ⟨x, _, rfl⟩ := Finset.mem_map.mp ((b.moving a p i).2.1 hj) + exact ⟨_, rfl⟩ + +open scoped Classical in +theorem local_efficient (m : ℕ) (hm : a.Room m) (hM : 1 ≤ M) + (hp : ∀ i, p i ≤ M) (i : b.active a p) : + (b.localMove a p m i).Efficient p (a.margin / 2) (2 * a.capacity) m := by + let E := b.shape i + let g := b.assign A i + let q := b.moveAt a p i + have hs := b.moving a p i + have hu : ∀ j ∈ E.links A, ∃ l, g j = .inr l := by + intro j hj + obtain ⟨x, _, rfl⟩ := Finset.mem_map.mp hj + exact ⟨_, rfl⟩ + obtain ⟨hb, ho⟩ := a.small _ q hs.1 + obtain ⟨hm₁, hm₂⟩ := hm _ q hs.1 + refine q.flex_efficient g (E.links A) m (b.assign_injective A i) (b.demand_slot a p i) hu + (by simp [BallShape.links, E]) a.positive.le hs.2.2.2 hb ho hm₁ (hm₂ _ ?_) + intro j + change b.rates A p (g j) ≤ _ + cases g j with + | inl x => exact hp x + | inr x => exact Nat.one_le_cast.mpr hM + +end Market +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# A local schedule independent of the payload width +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral +open scoped BigOperators + +variable {K I S : Type} [Field K] [Fintype I] [DecidableEq I] [Fintype S] [DecidableEq S] + {A : Finset (Tensor K S)} {N M : ℕ} {ρ : ℝ} (b : Market I N) (a : Atlas N A M ρ) + +namespace Market + +open scoped Classical in +theorem policy_covers [Nonempty S] (p : b.Request A → ℝ) (ha : 0 ∉ A) + (m : ℕ) (hm : 0 < m) (z : ℕ) (hz : 0 < z) : + (b.policy a p m).Covers (fun i => b.tensor A (.inl i) ^ z) (fun e => b.tensor A (.inr e) ^ z) + := by + apply Intervention.parallel_covers + intro i + let _ : Nonempty (b.Site i) := ⟨(b.shape i).src⟩ + exact (b.moveAt a p i).flex_covers _ _ _ (b.demand_slot a p i) + ((b.shape i).broadcast A) (b.name i) (b.tensor A) (b.place_tensor A i) + (fun j => Tensor.one_le _ ((b.shape i).nonzero A ha j)) hm z hz + +omit [DecidableEq I] in +open scoped Classical in +theorem active_count [Nonempty I] (hM : 1 ≤ M) (d : ℕ) (hf : b.Frequent A ρ d) + (p : b.Request A → ℝ) (hp : ∀ i, p i ∈ Set.Icc 0 (M : ℝ)) (hd : ∀ i, |p (.inl i)| ≤ d) + (h : 1201 * (b.payload A).card < ∑ i ∈ b.payload A, p i) : + ρ * (b.payload A).card ≤ Fintype.card (b.active a p) := by + have h' : 1201 < (𝔼 i, p (.inl i)) := by + rw [Fintype.expect_eq_sum_div_card, lt_div_iff₀ (by positivity)] + rw [card_payload, payload, Finset.sum_map] at h + exact h + obtain ⟨J, hJ, hj⟩ := hf p hd h' + have sub : J ⊆ b.active a p := by + intro i hi + let g := b.assign A i + have hb (j) : b.rates A p (g j) ∈ Set.Icc 0 (M : ℝ) := by + cases g j with + | inl x => exact hp x + | inr x => exact ⟨zero_le_one, Nat.one_le_cast.mpr hM⟩ + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, (a.detect (b.code i) (b.rates A p ∘ g) + ⟨fun j => (hb j).1, fun j => (hb j).2⟩).resolve_left (hj _ hi)⟩ + rw [card_payload, Fintype.card_coe] + exact hJ.le.trans (Nat.cast_le.mpr (Finset.card_le_card sub)) + +open scoped Classical in +/-- The indexed operation `b.policy a (fun i => price μ (b.cap A d M i) (z i)) m`. -/ +def decision (μ d m : ℕ) (z : b.Request A → ℕ) : Intervention (b.Request A) b.Edge := + b.policy a (fun i => price μ (b.cap A d M i) (z i)) m + +end Market + +open scoped Classical in +theorem Atlas.schedule [Nonempty S] (hM : 1 ≤ M) (hρ : 0 < ρ) : + ∃ h μ W : ℕ, a.Room (2 ^ h) ∧ 0 < μ ∧ 4 ≤ W ∧ + ∀ (I : Type) [Fintype I] [Nonempty I] [DecidableEq I] (b : Market I N) (d : ℕ), d ≤ M → + b.Frequent A ρ d → + Runs (b.payload A) (b.cap A d M) (b.decision a μ d (2 ^ h)) (1203 * Fintype.card I * W) W + 0 0 := by + let C := max M (1 + N ^ Fintype.card S * A.card) + obtain ⟨m₀, hm₀⟩ := a.room + obtain ⟨h, μ, W, hm, hμ, hw, hr⟩ := Routing.schedule N (2 * a.capacity) C m₀ + (half_pos a.positive) hρ (show (0 : ℝ) ≤ 1201 by norm_num) + have room := hm₀ _ hm + refine ⟨h, μ, W, room, hμ, hw, fun I _ _ _ b d hd hf => ?_⟩ + have hb (i) : 0 ≤ b.cap A d M i ∧ b.cap A d M i ≤ M := by + cases i with + | inl x => exact ⟨Nat.cast_nonneg _, Nat.cast_le.mpr hd⟩ + | inr x => exact ⟨Nat.cast_nonneg _, le_rfl⟩ + rw [show (1203 : ℝ) = 1201 + 2 by norm_num, ← b.card_payload A] + apply hr + · rw [b.card_payload, mul_comm] + exact (b.card_request A).trans (Nat.mul_le_mul_left _ (le_max_right _ _)) + · exact fun i => ⟨(hb i).1, (hb i).2.trans (Nat.cast_le.mpr (le_max_left _ _))⟩ + · intro z + let p i := price μ (b.cap A d M i) (z i) + have hp (i) : p i ∈ Set.Icc 0 (M : ℝ) := + ⟨price_nonneg (Nat.cast_pos.mpr hμ) (hb i).1 (Nat.cast_nonneg _), price_le.trans (hb i).2⟩ + have hv (i) : |p (.inl i)| ≤ d := by + rw [abs_of_nonneg (hp _).1] + exact price_le + exact ⟨b.active a p, inferInstance, inferInstance, b.localMove a p (2 ^ h), + b.active_count a hM d hf p hp hv, b.local_overlap a p (2 ^ h), + b.local_efficient a p (2 ^ h) room hM (fun i => (hp i).2), rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Access to the supply bits selected by a word -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.WordSum + +open Install Control + +/-- The quantity computed by `Fin (2 ^ h)`. -/ +abbrev Row (h : ℕ) := Fin (2 ^ h) + +variable {A R B C K : Type} + +/-- Indexes the input by the coordinates of `(Row h × (R ⊕ B)) ⊕ (Address z t × C)`. -/ +abbrev Input (R B C : Type) (h z : ℕ) (t : A → ℕ) := + (Row h × (R ⊕ B)) ⊕ (Address z t × C) + +/-- Indexes the work by the coordinates of `Input R B C h z t ⊕ ((A ⊕ Row h) × slots (word (h + +1)))`. -/ +abbrev Work (R B C : Type) (h z : ℕ) (t : A → ℕ) := + Input R B C h z t ⊕ ((A ⊕ Row h) × slots (word (h + 1))) + +/-- The quantity computed by `2 ^ h * (h + 1) ^ 3`. -/ +def scale (h : ℕ) := 2 ^ h * (h + 1) ^ 3 + +theorem rows_le (h : ℕ) : 2 ^ h ≤ scale h := Nat.le_mul_of_pos_right _ (by positivity) + +theorem rows_succ_le (h : ℕ) : 2 ^ (h + 1) ≤ 2 * scale h := by + rw [pow_succ'] + exact Nat.mul_le_mul_left _ (rows_le h) + +private theorem row_bits (h : ℕ) : 2 ^ h * (h + 1) ≤ scale h := by + unfold scale + ring_nf + omega + +variable [Field K] [Fintype A] [DecidableEq A] [Fintype R] [Fintype B] [Fintype C] + {h z : ℕ} {t : A → ℕ} + +omit [DecidableEq A] in +theorem work_size : + ∃ M : ℕ, ∀ (h z : ℕ) (t : A → ℕ), (∀ a, t a * z ≤ 2 ^ (h + 1)) → + Fintype.card (Work R B C h z t) ≤ M * scale h := by + refine ⟨Fintype.card R + Fintype.card B + 2 * Fintype.card A * Fintype.card C + + (Fintype.card A + 1), fun h z t ht => ?_⟩ + have ha : Fintype.card (Address z t) ≤ Fintype.card A * (2 * scale h) := by + rw [Fintype.card_sigma] + simpa using Finset.sum_le_sum (s := Finset.univ) (fun a _ => (ht a).trans (rows_succ_le h)) + have hi : Fintype.card A + 2 ^ h ≤ (Fintype.card A + 1) * 2 ^ h := by + rw [add_mul, one_mul] + exact Nat.add_le_add_right (Nat.le_mul_of_pos_right _ (by positivity)) _ + simp only [Work, Input, Row, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, card_slots, + wd_word, + show Fintype.card (slots .bit) = 1 from rfl, Nat.add_comm 1 h] + calc + _ ≤ scale h * (Fintype.card R + Fintype.card B) + + (Fintype.card A * (2 * scale h)) * Fintype.card C + + ((Fintype.card A + 1) * 2 ^ h) * (h + 1) := by gcongr; exact rows_le h + _ ≤ _ := by + have := Nat.mul_le_mul_left (Fintype.card A + 1) (row_bits h) + ring_nf at this ⊢ + omega + +/-- Chooses the operation for the left or right summand. -/ +def prepare (D : (R → Bool) → A) (v : Input R B C h z t → Bool) : Work R B C h z t → Bool := + Sum.elim v (ranks D h (fun ij => v (.inl (ij.1, .inl ij.2)))) + +theorem prepare_net (D : (R → Bool) → A) {M : ℕ} (hm : Fintype.card (Work R B C h z t) + ≤ M * scale h) : + BNet K (prepare (B := B) (C := C) (h := h) (z := z) (t := t) D) + ((7 * M + 2 * Fintype.card R + rankCost R A) * scale h) := by + let sel (p : Row h × R) : Input R B C h z t := .inl (p.1, .inl p.2) + apply ((BNet.id K _).pair ((ranks_bnet K R A D h).pull sel)).mono + have hc : Fintype.card (Input R B C h z t) ≤ M * scale h := + (Fintype.card_le_of_injective Sum.inl Sum.inl_injective).trans hm + rw [Fintype.card_prod, Fintype.card_fin] + have := Nat.mul_le_mul_right (Fintype.card R) (rows_le h) + have hk := Nat.mul_le_mul_left (rankCost R A) (row_bits h) + ring_nf at this hk hc ⊢ + omega + +/-- Returns `v (.inl (.inr (⟨a, ⟨j, hj⟩⟩, c)))` when `hj : j < t a * z` holds, and `false` +otherwise. -/ +def load (v : Work R B C h z t → Bool) (a : A) (j : ℕ) (c : C) : Bool := + if hj : j < t a * z then v (.inl (.inr (⟨a, ⟨j, hj⟩⟩, c))) else false + +/-- The quantity computed by `(decode (h + 1) (fun j => v (.inr (i, j)))).val`. -/ +def number (v : Work R B C h z t → Bool) (i : A ⊕ Row h) : ℕ := + (decode (h + 1) (fun j => v (.inr (i, j)))).val + +omit [Fintype R] [Fintype B] [Fintype C] [Fintype A] in +theorem number_prepare (D : (R → Bool) → A) (v : Input R B C h z t → Bool) (i : A ⊕ Row h) : + number (prepare D v) i = + let w := fun j => D (fun k => v (.inl (j, .inl k))) + Sum.elim (fun a => histogram w a none) (rank w) i := by + let w := fun j => D (fun k => v (.inl (j, .inl k))) + let n := Sum.elim (fun a => histogram w a none) (rank w) i + have hn : n ≤ 2 ^ h := by + cases i <;> exact histogram_le w _ _ + have hr : n < 2 ^ (h + 1) := by + rw [pow_succ] + have : 0 < 2 ^ h := by positivity + omega + change ((decode (h + 1)) ((decode (h + 1)).symm ⟨n, hr⟩)).val = n + rw [Equiv.apply_symm_apply] + +/-- Uses `⟨i, by rw [pow_succ]; have := i.isLt; omega⟩` as the representation. -/ +def up (i : Row h) : Row (h + 1) := ⟨i, by rw [pow_succ]; have := i.isLt; omega⟩ + +/-- Returns `⟨i, hi⟩` when `hi : i.val < 2 ^ h` holds, and `0` otherwise. -/ +def down (i : Row (h + 1)) : Row h := if hi : i.val < 2 ^ h then ⟨i, hi⟩ else 0 + +/-- Indexes the buffer by the coordinates of `Row (h + 1) ⊕ (Row (h + 1) × slots (word (h + +1)))`. -/ +abbrev Buffer (h : ℕ) := Row (h + 1) ⊕ (Row (h + 1) × slots (word (h + 1))) + +/-- In the case `.inl j`, this construction gives `load v a j c`. -/ +def buf (a : A) (c : C) (v : Work R B C h z t → Bool) : Buffer h → Bool + | .inl j => load v a j c + | .inr p => v (.inr (.inr (down p.1), p.2)) + +omit [DecidableEq A] [Fintype A] [Fintype R] [Fintype B] [Fintype C] in +private theorem buf_depends (a : A) (c : C) : + Depends (buf (R := R) (B := B) (h := h) (z := z) (t := t) a c) 1 := by + classical + intro k + cases k with + | inl i => + by_cases he : i.val < t a * z + · refine ⟨{.inl (.inr (⟨a, ⟨i, he⟩⟩, c))}, by simp, fun x y hxy => ?_⟩ + simp only [buf, load, he, dite_true] + exact hxy _ (by simp) + · exact ⟨∅, by simp, fun x y _ => by simp [buf, load, he]⟩ + | inr p => exact ⟨{.inr (.inr (down p.1), p.2)}, by simp, fun x y hxy => hxy _ (by simp)⟩ + +/-- Run one batched read for each possible letter and payload bit. -/ +def fetchColumn (ac : A × C) (v : Work R B C h z t → Bool) : Row (h + 1) → Bool := + Control.read (h + 1) (buf ac.1 ac.2 v) + +omit [DecidableEq A] [Fintype A] [Fintype R] [Fintype B] [Fintype C] in +theorem fetchColumn_up (a : A) (c : C) (v : Work R B C h z t → Bool) (i : Row h) : + fetchColumn (a, c) v (up i) = load v a (number v (.inr i)) c := by + have hd : down (up i) = i := by simp [up, down, i.isLt] + simp only [fetchColumn, Control.read, buf, hd, number] + +omit [DecidableEq A] in +theorem column_net {M : ℕ} (hm : Fintype.card (Work R B C h z t) ≤ M * scale h) (ac : A × C) : + BNet K (fetchColumn (R := R) (B := B) (h := h) (z := z) (t := t) ac) + ((M + 4 * localCost 1 + 160000) * scale h) := by + apply (((buf_depends ac.1 ac.2).bnet K).comp (read_net K (h + 1))).mono + have hb : Fintype.card (Buffer h) ≤ 4 * scale h := by + unfold Buffer + rw [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, card_slots, wd_word] + unfold scale + ring_nf + omega + have hr : 10000 * 2 ^ (h + 1) * (h + 1 + 1) ^ 3 ≤ 160000 * scale h := by + unfold scale + ring_nf + omega + have hb' := Nat.mul_le_mul_left (localCost 1) hb + ring_nf at hm hb' hr ⊢ + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.WordSum +end + +/- +# Trivalent implementation of a local rounded-word factor + +All bit alphabets are fixed. Query every payload column in parallel, +then select the letter and apply its kernel in a fixed-arity table. +Unused supplies are handled by thresholds on the per-letter counts. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.WordSum + +open Install Control + +variable {K A R B C S : Type} [Field K] [Fintype A] [DecidableEq A] + [Fintype R] [Fintype B] [Fintype C] {h z : ℕ} {t : A → ℕ} + +private def active (L : A → (B → Bool) → (C → Bool) → K) (D : (R → Bool) → A) + (v : Work R B C h z t → Bool) := + ∏ i : Row h, + let a := D (fun r => v (.inl (.inl (i, .inl r)))) + L a (fun b => v (.inl (.inl (i, .inr b)))) (load v a (number v (.inr i))) + +omit [DecidableEq A] in +private theorem active_net (D : (R → Bool) → A) (M : ℕ) : + ∃ N : ℕ, ∀ h z (t : A → ℕ), Fintype.card (Work R B C h z t) ≤ M * scale h → + ∀ L : A → (B → Bool) → (C → Bool) → K, + Weight K (active (h := h) (z := z) (t := t) L D) (N * scale h) := by + let J := A × C + let Q := (R ⊕ B) ⊕ J + let n := M + 4 * localCost 1 + 160000 + let q := 8 * 2 ^ Fintype.card Q + refine ⟨8 * M + Fintype.card J * (5 * M + n + 2) + 2 * Fintype.card Q + q, + fun h z t hm L => ?_⟩ + let W := Work R B C h z t + let cols := BNet.finite_share _ (fun j : J => column_net (K := K) hm j) + let e (ij : Row h × Q) : W ⊕ (J × Row (h + 1)) := + Sum.elim (fun k => .inl (.inl (.inl (ij.1, k)))) (fun k => .inr (k, up ij.1)) ij.2 + let table (v : Q → Bool) := + let a := D (fun r => v (.inl (.inl r))) + L a (fun b => v (.inl (.inr b))) (fun c => v (.inr (a, c))) + have net := ((BNet.id K W).pair cols).weight (((Weight.dense K Q table).prod h).pull e) + convert net.mono (n := (8 * M + Fintype.card J * (5 * M + n + 2) + + 2 * Fintype.card Q + q) * scale h) ?_ using 1 + · funext v + simp only [active, Function.comp_def, table, e, Sum.elim_inl, Sum.elim_inr, id_eq, + fetchColumn_up] + · change 5 * Fintype.card W + Fintype.card W + + (Fintype.card W + Fintype.card J * (5 * Fintype.card W + n * scale h)) + + (Fintype.card (W ⊕ (J × Row (h + 1))) + 2 * Fintype.card (Row h × Q) + 2 ^ h * q) ≤ _ + have hc : Fintype.card (W ⊕ (J × Row (h + 1))) = + Fintype.card W + Fintype.card J * 2 ^ (h + 1) := by + rw [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + rw [hc, show Fintype.card (Row h × Q) = 2 ^ h * Fintype.card Q by + rw [Fintype.card_prod, Fintype.card_fin]] + change Fintype.card W ≤ _ at hm + have h₁ := Nat.mul_le_mul_left (Fintype.card J) hm + have h₂ := Nat.mul_le_mul_left (Fintype.card J) (rows_succ_le h) + have h₃ := Nat.mul_le_mul_right (Fintype.card Q) (rows_le h) + have h₄ := Nat.mul_le_mul_right q (rows_le h) + ring_nf at hm h₁ h₂ h₃ h₄ ⊢ + omega + +private def extra (a : A) (U : (C → Bool) → K) (v : Work R B C h z t → Bool) := + ∏ j : Row (h + 1), if j.val < t a * z then + if number v (.inl a) ≤ j.val then U (load v a j.val) else 1 else 1 + +private def flags (a : A) (v : Work R B C h z t ⊕ Row (h + 1) → Bool) + (p : Row (h + 1) × (Unit ⊕ C)) : Bool := + if hj : p.1.val < t a * z then + Sum.elim (fun _ => v (.inr p.1)) (fun c => v (.inl (.inl (.inr (⟨a, ⟨p.1.val, hj⟩⟩, c))))) p.2 + else false + +omit [DecidableEq A] [Fintype A] [Fintype R] [Fintype B] [Fintype C] in +private theorem flags_depends (a : A) : + Depends (flags (R := R) (B := B) (C := C) (h := h) (z := z) (t := t) a) 1 := by + classical + rintro ⟨j, k⟩ + by_cases hj : j.val < t a * z + · cases k with + | inl u => + refine ⟨{.inr j}, by simp, fun x y he => ?_⟩ + simp only [flags, hj, dite_true, Sum.elim_inl] + exact he _ (by simp) + | inr c => + refine ⟨{.inl (.inl (.inr (⟨a, ⟨j.val, hj⟩⟩, c)))}, by simp, fun x y he => ?_⟩ + simp only [flags, hj, dite_true, Sum.elim_inr] + exact he _ (by simp) + · exact ⟨∅, by simp, fun x y _ => by simp [flags, hj]⟩ + +omit [DecidableEq A] in +private theorem extra_net (M : ℕ) : + ∃ N : ℕ, ∀ h z (t : A → ℕ), Fintype.card (Work R B C h z t) ≤ M * scale h → + ∀ (a : A) (U : (C → Bool) → K), + Weight K (extra (R := R) (B := B) (h := h) (z := z) (t := t) a U) (N * scale h) := by + let q := 8 * 2 ^ Fintype.card (Unit ⊕ C) + refine ⟨8 * M + 8004 + 2 * (localCost 1 * Fintype.card (Unit ⊕ C) + q), fun h z t hm a U => ?_⟩ + let W := Work R B C h z t + let e (k : slots (word (h + 1))) : W := .inr (.inl a, k) + let table (v : Unit ⊕ C → Bool) := if v (.inl ()) then U (v ∘ Sum.inr) else 1 + have ht := (BNet.id K W).pair ((threshold_bnet K (h + 1)).pull e) + have net := (ht.comp ((flags_depends a).bnet K)).weight ((Weight.dense K _ table).prod (h + 1)) + convert net.mono (n := (8 * M + 8004 + 2 * (localCost 1 * Fintype.card (Unit ⊕ C) + q)) * + scale h) ?_ using 1 + · funext v + unfold extra + apply Finset.prod_congr rfl + intro j _ + by_cases hj : j.val < t a * z + · have hl : load v a j.val = fun c => v (.inl (.inr (⟨a, ⟨j.val, hj⟩⟩, c))) := by + funext c + simp [load, hj] + simp [table, flags, e, number, Function.comp_def, hj, hl] + · simp [table, flags, hj] + · change 5 * Fintype.card W + Fintype.card W + (Fintype.card W + + 2 * Fintype.card (slots (word (h + 1))) + 2000 * 2 ^ (h + 1) * (h + 1 + 1)) + + (Fintype.card (W ⊕ Row (h + 1)) + localCost 1 * Fintype.card (Row (h + 1) × (Unit ⊕ C))) + + 2 ^ (h + 1) * q ≤ _ + rw [card_slots, wd_word, + show Fintype.card (W ⊕ Row (h + 1)) = Fintype.card W + 2 ^ (h + 1) by + rw [Fintype.card_sum, Fintype.card_fin], + show Fintype.card (Row (h + 1) × (Unit ⊕ C)) = 2 ^ (h + 1) * Fintype.card (Unit ⊕ C) by + rw [Fintype.card_prod, Fintype.card_fin]] + change Fintype.card W ≤ _ at hm + have hh : h + 1 ≤ scale h := by + have hp := Nat.lt_two_pow_self (n := h) + exact Nat.le_trans hp (rows_le h) + have ht : 2000 * 2 ^ (h + 1) * (h + 1 + 1) ≤ 8000 * scale h := by + unfold scale + ring_nf + omega + have hk := Nat.mul_le_mul_right (1 + localCost 1 * Fintype.card (Unit ⊕ C) + q) (rows_succ_le h) + ring_nf at hh ht hk hm ⊢ + omega + +private theorem prod_prefix {m n : ℕ} (hm : m ≤ n) (f : ℕ → K) : + (∏ i : Fin n, if i.val < m then f i.val else 1) = ∏ i : Fin m, f i.val := by + obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le hm + rw [Fin.prod_univ_add] + simp + +omit [Fintype R] [Fintype B] [Fintype C] in +private theorem factor_eq (L : A → S → (B → Bool) → (C → Bool) → K) (U : A → S → (C → Bool) → K) + (D : (R → Bool) → A) (ht : ∀ a, t a * z ≤ 2 ^ (h + 1)) (s : S) + (v : Input R B C h z t → Bool) : + factor L U z (fun i => D (fun k => v (.inl (i, .inl k)))) t s + (fun i b => v (.inl (i, .inr b))) (fun j c => v (.inr (j, c))) = + active (fun a => L a s) D (prepare D v) * ∏ a, extra a (U a s) (prepare D v) := by + have hload (a : A) (j : ℕ) : load (prepare D v) a j = + if hj : j < t a * z then (fun c => v (.inr (⟨a, ⟨j, hj⟩⟩, c))) else default := by + funext c + by_cases hj : j < t a * z <;> simp [load, prepare, hj] + unfold factor + apply congrArg₂ (· * ·) + · simp only [active, number_prepare, Sum.elim_inr, hload] + rfl + · rw [Fintype.prod_sigma] + apply Finset.prod_congr rfl + intro a _ + unfold extra + rw [prod_prefix (ht a) (fun j => if number (prepare D v) (.inl a) ≤ j then + U a s (load (prepare D v) a j) else 1)] + apply Finset.prod_congr rfl + intro j _ + simp only [number_prepare, Sum.elim_inl, hload, dite_eq_left j.isLt] + +omit [Fintype B] [Fintype C] [Fintype R] in +/-- The constant is independent of the site, histogram, power and +batch length. Invalid addresses read the all-false word. -/ +theorem factor_net [Finite B] [Finite C] [Finite R] + (L : A → S → (B → Bool) → (C → Bool) → K) (U : A → S → (C → Bool) → K) + (D : (R → Bool) → A) : + ∃ N : ℕ, ∀ h z (t : A → ℕ), (∀ a, t a * z ≤ 2 ^ (h + 1)) → ∀ s, + Weight K (fun v : Input R B C h z t → Bool => + factor L U z (fun i => D (fun k => v (.inl (i, .inl k)))) t s + (fun i b => v (.inl (i, .inr b))) (fun j c => v (.inr (j, c)))) + (N * 2 ^ h * (h + 1) ^ 3) := by + let : Fintype B := Fintype.ofFinite B + let : Fintype C := Fintype.ofFinite C + let : Fintype R := Fintype.ofFinite R + obtain ⟨M, hM⟩ := work_size (A := A) (R := R) (B := B) (C := C) + obtain ⟨N, hN⟩ := active_net (K := K) (B := B) (C := C) D M + obtain ⟨P, hP⟩ := extra_net (K := K) (A := A) (R := R) (B := B) (C := C) M + let cost := 13 * M + 2 * Fintype.card R + rankCost R A + N + Fintype.card A * (5 * M + P) + refine ⟨cost, fun h z t ht s => ?_⟩ + have hm := hM h z t ht + have ha := hN h z t hm (fun a => L a s) + have he := Weight.finite_product _ (fun a => hP h z t hm a (U a s)) + have net := (prepare_net (K := K) D hm).weight (ha.mul he) + rw [mul_assoc] + change Weight K _ (cost * scale h) + convert net.mono (n := cost * scale h) ?_ using 1 + · exact funext (factor_eq L U D ht s) + · have := Nat.mul_le_mul_left (Fintype.card A) hm + unfold cost + ring_nf at hm this ⊢ + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.WordSum +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryComparison.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryComparison.lean new file mode 100644 index 0000000000..4ce0729863 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryComparison.lean @@ -0,0 +1,893 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Round +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometrySector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.ScaleSlope +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Crossing.Form +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryJets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.FusedTerms + +/-! +# A fixed schedule of local interventions + +There is one unit of injection at every round. Use all locally +available moves, even when the mean price is low. At high prices the +aggregate saving pays for an entire injection. No global price test +or packing algorithm is required by the schedule. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Stock Finset + +section Run + +variable {I E : Type} [Fintype I] [Fintype E] [DecidableEq I] + (L : Finset I) (a : I → ℝ) (Q : (I → ℕ) → Intervention I E) (budget : ℝ) + +/-- The two cases impose `v + total a z ≤ budget` and `(Q z).take ≤ z ∧ ∀ j,`, respectively. -/ +def Runs : ℕ → (I → ℕ) → ℝ → Prop + | 0, z, v => v + total a z ≤ budget + | k + 1, z, v => (Q z).take ≤ z ∧ ∀ j, + Runs k ((Q z).next z j + copies L 1) (v + (Q z).cost j) + +private theorem runs_of_change {μ : ℝ} (hμ : 0 < μ) (r : ℝ) + (h : ∀ z, (Q z).take ≤ z ∧ ∀ j, + potential μ a ((Q z).next z j + copies L 1) + (Q z).cost j ≤ potential μ a z + r) + (k : ℕ) (z : I → ℕ) (v : ℝ) + (hv : v + potential μ a z + r * k + μ * (∑ i, a i ^ 2) / 2 ≤ budget) : Runs L a Q budget k z v + := by + induction k generalizing z v with + | zero => + have he : total a z ≤ potential μ a z + μ * (∑ i, a i ^ 2) / 2 := by + simpa only [total, mul_comm] using potential_close (z := z) (a := a) hμ + change v + total a z ≤ budget + simp only [Nat.cast_zero, mul_zero, add_zero] at hv + linarith + | succ k ih => + obtain ⟨hq, hg⟩ := h z + refine ⟨hq, fun j => ih _ _ ?_⟩ + rw [Nat.cast_succ] at hv + linarith only [hv, hg j] + +end Run + +theorem schedule (N B A m₀ : ℕ) {δ ρ C : ℝ} + (hδ : 0 < δ) (hρ : 0 < ρ) (hC : 0 ≤ C) : + ∃ h μ W : ℕ, m₀ ≤ 2 ^ h ∧ 0 < μ ∧ 4 ≤ W ∧ + ∀ (I E : Type) [Fintype I] [Fintype E] [DecidableEq I] (L : Finset I) + (a : I → ℝ) (Q : (I → ℕ) → Intervention I E), + Fintype.card I ≤ A * L.card → (∀ i, 0 ≤ a i ∧ a i ≤ A) → + (∀ z : I → ℕ, let p := fun i => price μ (a i) (z i) + ∃ (J : Type) (_ : Fintype J) (_ : DecidableEq J) (q : J → Intervention I E), + (C * L.card < ∑ i ∈ L, p i → ρ * L.card ≤ Fintype.card J) ∧ + Intervention.Overlap q N ∧ (∀ j, (q j).Efficient p δ B (2 ^ h)) ∧ + Q z = Intervention.parallel q) → + Runs L a Q ((C + 2) * L.card * W) W 0 0 := by + obtain ⟨h, hh⟩ := pow_unbounded_of_one_lt (max (m₀ : ℝ) (A / (ρ * δ))) (by norm_num : (1 : ℝ) < 2) + let m : ℕ := 2 ^ h + have hm : m₀ ≤ 2 ^ h := by exact_mod_cast ((le_max_left _ _).trans_lt hh).le + have hpay : (A : ℝ) ≤ (m : ℝ) * (ρ * δ) := by + simpa [m] using ((div_lt_iff₀ (mul_pos hρ hδ)).mp ((le_max_right _ _).trans_lt hh)).le + let R := N * (B * m) + obtain ⟨μ, hμ⟩ := exists_nat_gt (max ((R : ℝ) / δ) ((A : ℝ) * ((R : ℝ) + 1) ^ 2)) + have hsize := ((div_lt_iff₀ hδ).mp ((le_max_left _ _).trans_lt hμ)).le + have herr := ((le_max_right _ _).trans_lt hμ).le + have hμpos : (0 : ℝ) < μ := (show (0 : ℝ) ≤ _ by positivity).trans_lt hμ + let W := μ * (A ^ 3 + 4) + have hW : 4 ≤ W := (Nat.le_add_left _ _).trans (Nat.le_mul_of_pos_left _ (Nat.cast_pos.mp hμpos)) + refine ⟨h, μ, W, hm, Nat.cast_pos.mp hμpos, hW, ?_⟩ + intro I E _ _ _ L a Q hi ha hact + have hi' : (Fintype.card I : ℝ) ≤ A * (L.card : ℝ) := by exact_mod_cast hi + have hl : (0 : ℝ) ≤ L.card := Nat.cast_nonneg _ + have error : (Fintype.card I : ℝ) * ((R : ℝ) + 1) ^ 2 / (2 * μ) ≤ L.card := by + rw [div_le_iff₀ (by positivity)] + nlinarith only [mul_le_mul_of_nonneg_left herr hl, mul_nonneg hl hμpos.le, + mul_le_mul_of_nonneg_right hi' (sq_nonneg ((R : ℝ) + 1))] + apply runs_of_change L a Q _ hμpos ((C + 1) * L.card) + · intro z + let p i := price (μ : ℝ) (a i) (z i) + obtain ⟨J, _, _, q, hd, ho, he, hq⟩ := hact z + rw [hq] + obtain ⟨hz, ht⟩ := Intervention.parallel_change q (copies L 1) (M := 1) + (by intro i; unfold copies; split <;> omega) hμpos ho he hsize + have cost : ∑ i ∈ L, p i ≤ C * L.card + Fintype.card J * ((m : ℝ) * δ) := by + by_cases hp : C * L.card < ∑ i ∈ L, p i + · have hmax : ∑ i ∈ L, p i ≤ L.card * (A : ℝ) := by + simpa using sum_le_sum (s := L) (fun i _ => (show p i + ≤ (A : ℝ) from price_le.trans (ha i).2)) + linarith only [hmax, mul_nonneg hC hl, mul_le_mul_of_nonneg_left hpay hl, + mul_le_mul_of_nonneg_right (hd hp) (by positivity : 0 ≤ (m : ℝ) * δ)] + · exact (le_of_not_gt hp).trans (le_add_of_nonneg_right (by positivity)) + refine ⟨hz, fun j => ?_⟩ + have hg := ht j + rw [total_copies, Nat.cast_one, one_mul] at hg + change _ + _ + Fintype.card J * ((m : ℝ) * δ) ≤ _ + ∑ i ∈ L, p i + + (Fintype.card I : ℝ) * ((R : ℝ) + 1) ^ 2 / (2 * μ) at hg + linarith only [hg, error, cost] + · have hsum : ∑ i, a i ^ 2 ≤ L.card * (A : ℝ) ^ 3 := calc + _ ≤ ∑ _ : I, (A : ℝ) ^ 2 := sum_le_sum fun i _ => pow_le_pow_left₀ (ha i).1 (ha i).2 _ + _ ≤ _ := by + simp only [sum_const, card_univ, nsmul_eq_mul] + nlinarith only [mul_le_mul_of_nonneg_right hi' (sq_nonneg (A : ℝ))] + rw [potential_zero (fun i => (ha i).1)] + unfold W + push_cast + nlinarith only [mul_le_mul_of_nonneg_left hsum hμpos.le, mul_nonneg hl hμpos.le, + show 0 ≤ (L.card : ℝ) * (μ : ℝ) * (A : ℝ) ^ 3 by positivity] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Reserving extra supplies to round each frequency + +Add one repetition per alphabet symbol on the supply side. A large +enough fixed number of repetitions absorbs this slack. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Proposal + +open Spectral Stock Finset + +variable {K S I E J : Type} [Field K] [Fintype S] [Fintype J] + [DecidableEq I] [DecidableEq E] [DecidableEq J] {T : J → Tensor K S} {H : ℝ} + (q : Proposal T H) (g : J → I ⊕ E) (u : Finset J) (m : ℕ) + +/-- Stock consumption is unchanged. Outcomes and supplies have rounding room. -/ +def flex : Intervention I E := + { q.trade g u (m + Fintype.card q.move.letter) with take := (q.trade g u m).take } + +theorem flex_support {i : I} (h : (q.flex g u m).affects i) : ∃ j, g j = .inl i := by + rcases h with h | h + · exact q.trade_support g u m (.inl h) + · exact q.trade_support g u _ (.inr h) + +variable [Fintype I] [Fintype E] + +theorem flex_efficient (hg : Function.Injective g) + (hd : ∀ j ∈ q.demand, ∃ i, g j = .inl i) + (hu : ∀ j ∈ u, ∃ e, g j = .inr e) (hc : (u.card : ℝ) ≤ H) + {p : I → ℝ} {δ : ℝ} (hδ : 0 ≤ δ) + (hw : q.Works δ (Sum.elim p (fun _ => 1) ∘ g)) + {B : ℕ} (hb : q.move.block ≤ B) (ho : ∀ j, ∑ k, q.move.count j k ≤ B) + (hm : Fintype.card q.move.letter ≤ m) + (hm' : (Fintype.card q.move.letter : ℝ) * q.move.block * + (∑ j ∈ q.demand, (Sum.elim p (fun _ => 1) ∘ g) j) ≤ m * (δ / 2)) : + (q.flex g u m).Efficient p (δ / 2) (2 * B) m := by + let k := Fintype.card q.move.letter + have he (n) := q.trade_efficient g u n hg hd hu hc hδ hw hb ho + constructor + · intro i + obtain ⟨hi, hk⟩ := (he m).1 i + exact ⟨hi.trans (by rw [mul_assoc]; omega), fun e => (half_le_self hδ).trans (hk e)⟩ + intro j + obtain ⟨hi, hs⟩ := (he (m + k)).2 j + refine ⟨fun i => (hi i).trans ?_, ?_⟩ + · calc + _ ≤ B * (m + m) := Nat.mul_le_mul_left B (Nat.add_le_add_left hm _) + _ = _ := by ring + let v := ∑ j ∈ q.demand, (Sum.elim p (fun _ => 1) ∘ g) j + have cost (n : ℕ) : total p (q.trade g u n).take = (q.move.block * n : ℕ) * v := by + unfold v + rw [← total_copies, ← total_collect, total_split] + simp only [q.take_core g n hd, sum_const_zero, Nat.cast_zero, add_zero] + rfl + change total p ((q.trade g u (m + k)).put j) + (q.trade g u (m + k)).cost j + _ ≤ + total p (q.trade g u m).take + rw [cost] at hs ⊢ + change (k : ℝ) * q.move.block * v ≤ m * (δ / 2) at hm' + push_cast at hs ⊢ + linarith only [hs, hm', mul_nonneg (Nat.cast_nonneg (α := ℝ) k) hδ] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Proposal +end + +/- +# Interpolation and the midpoint criterion + +Subdivision and uniqueness give constant speed. Doubling a segment +parameter halves the maximal defect in squared-distance comparison. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {Y : Type*} [PseudoMetricSpace Y] (h : Busemann Y) (s : Segments Y) + +/-- The value specified by `(s t x y).choose`. -/ +def Segments.pt (t : Fraction) (x y : Y) : Y := (s t x y).choose + +theorem Segments.divides (t : Fraction) (x y : Y) : Divides t x y (s.pt t x y) := + (s t x y).choose_spec + +theorem Divides.rev {x y m : Y} {t : Fraction} (hm : Divides t x y m) : + Divides t.rev y x m := by + simp only [Divides, Fraction.rev, sub_sub_cancel, dist_comm y m, dist_comm y x, dist_comm m x] + exact ⟨hm.2, hm.1⟩ + +include h s in +theorem nested {x y a b : Y} {t u v : Fraction} (ha : Divides t x y a) + (hb : Divides u x y b) (he : t.val = v.val * u.val) : Divides v x b a := by + obtain ⟨m, hm⟩ := s v x b + have hm' : Divides t x y m := by + apply Divides.of_le + · rw [hm.1, hb.1, he, mul_assoc] + · have hd := dist_triangle m b y + rw [hm.2, hb.1, hb.2] at hd + rw [he] + linarith only [hd] + exact hm.replace (h.unique hm' ha) + +include h s in +theorem speed {x y a b : Y} {t u : Fraction} (ha : Divides t x y a) + (hb : Divides u x y b) : dist a b = |t.val - u.val| * dist x y := by + wlog hle : t.val ≤ u.val generalizing a b t u + · rw [dist_comm, abs_sub_comm] + exact this hb ha (le_of_not_ge hle) + rw [abs_of_nonpos (sub_nonpos.mpr hle)] + rcases u.2.1.eq_or_lt with hz | hp + · have he : t = u := Subtype.ext (le_antisymm hle (hz ▸ t.2.1)) + subst t + rw [h.unique ha hb, sub_self, neg_zero, zero_mul] + let v : Fraction := ⟨t.val / u.val, div_nonneg t.2.1 hp.le, (div_le_one hp).mpr hle⟩ + have he : t.val = v.val * u.val := (div_mul_cancel₀ _ hp.ne').symm + rw [(nested h s ha hb he).2, hb.1, he] + ring + +include h in +theorem Segments.radial (x y z : Y) {t u : Fraction} (hle : t.val ≤ u.val) : + u.val * dist (s.pt t x y) (s.pt t x z) ≤ t.val * dist (s.pt u x y) (s.pt u x z) := by + rcases u.2.1.eq_or_lt with hz | hp + · rw [← hz, zero_mul] + exact mul_nonneg t.2.1 dist_nonneg + let v : Fraction := ⟨t.val / u.val, div_nonneg t.2.1 hp.le, (div_le_one hp).mpr hle⟩ + have he : t.val = v.val * u.val := (div_mul_cancel₀ _ hp.ne').symm + have hv (w : Y) := nested h s (s.divides t x w) (s.divides u x w) he + have hh := h v _ _ _ _ _ _ (hv y) (hv z) + rw [dist_self, mul_zero, zero_add] at hh + rw [he] + linarith only [mul_le_mul_of_nonneg_left hh hp.le] + +/-- The quantity computed by `⟨1 / 2, by norm_num, by norm_num⟩`. -/ +def half : Fraction := ⟨1 / 2, by norm_num, by norm_num⟩ + +/-- The condition `∀ x y m : Y, Divides half x y m → Along half x y m` on the specified data. -/ +def MidpointBound (Y : Type*) [PseudoMetricSpace Y] : Prop := + ∀ x y m : Y, Divides half x y m → Along half x y m + +private def excess (x y z m : Y) (t : Fraction) := + dist m z ^ 2 - (1 - t.val) * dist x z ^ 2 - t.val * dist y z ^ 2 + + t.val * (1 - t.val) * dist x y ^ 2 + +private theorem excess_rev (x y z m : Y) (t : Fraction) : + excess y x z m t.rev = excess x y z m t := by + unfold excess Fraction.rev + rw [dist_comm y x] + ring + +include h s in +private theorem double_excess (hm : MidpointBound Y) (x y z m : Y) (t : Fraction) + (ht : Divides t x y m) (hle : t.val ≤ 1 / 2) : + ∃ b u, Divides u x y b ∧ 2 * excess x y z m t ≤ excess x y z b u := by + let u : Fraction := ⟨2 * t.val, mul_nonneg (by norm_num) t.2.1, by linarith⟩ + obtain ⟨b, hb⟩ := s u x y + have he : t.val = half.val * u.val := by dsimp [u, half]; ring + have hh := hm x b m (nested h s ht hb he) z + rw [hb.1] at hh + refine ⟨b, u, hb, ?_⟩ + dsimp only [excess, half, u] at hh ⊢ + linarith only [hh] + +include h s in +theorem MidpointBound.all (hm : MidpointBound Y) {x y m : Y} {t : Fraction} + (ht : Divides t x y m) : Along t x y m := by + intro z + let E := {a : ℝ | ∃ b u, Divides u x y b ∧ a = excess x y z b u} + have ht' : excess x y z m t ∈ E := ⟨m, t, ht, rfl⟩ + have hbd : BddAbove E := by + refine ⟨(dist x y + dist x z) ^ 2 + dist x y ^ 2, ?_⟩ + rintro _ ⟨b, u, hb, rfl⟩ + have hu := u.2.1 + have hu' := sub_nonneg.mpr u.2.2 + have hd : dist b z ≤ dist x y + dist x z := by + have := dist_triangle b x z + rw [dist_comm b x, hb.1] at this + linarith [mul_nonneg hu' (dist_nonneg (x := x) (y := y))] + have he : u.val * (1 - u.val) ≤ 1 := by nlinarith + unfold excess + linarith only [pow_le_pow_left₀ dist_nonneg hd 2, mul_nonneg hu' (sq_nonneg (dist x z)), + mul_nonneg hu (sq_nonneg (dist y z)), mul_le_mul_of_nonneg_right he (sq_nonneg (dist x y))] + have hsup : sSup E ≤ sSup E / 2 := by + apply csSup_le ⟨_, ht'⟩ + rintro _ ⟨b, u, hb, rfl⟩ + by_cases hu : u.val ≤ 1 / 2 + · obtain ⟨c, v, hc, he⟩ := double_excess h s hm x y z b u hb hu + exact (le_div_iff₀ (by norm_num)).mpr (by linarith [le_csSup hbd ⟨c, v, hc, rfl⟩]) + · have hu' : u.rev.val ≤ 1 / 2 := by change 1 - u.val ≤ _; linarith + obtain ⟨c, v, hc, he⟩ := double_excess h s hm y x z b u.rev hb.rev hu' + rw [excess_rev, ← excess_rev y x z c] at he + linarith [le_csSup hbd ⟨c, v.rev, hc.rev, rfl⟩] + have he := le_csSup hbd ht' + unfold excess at he + linarith only [hsup, he] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Distances on affine sectors + +Sliding both endpoints along parallel segments does not change their +distance. This gives a seminorm on the whole coordinate plane, also +when the sector collapses to a line. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {Y : Type*} [PseudoMetricSpace Y] {F : Coord → Y} + +private theorem slide_le (hf : AffineSector F) (hb : Busemann Y) + {a b x y : Coord} (ha : 0 ≤ a) (hb' : 0 ≤ b) (hx : 0 ≤ x) (hy : 0 ≤ y) + (he : a - b = x - y) : dist (F a) (F b) ≤ dist (F x) (F y) := by + apply le_of_forall_pos_le_add + intro ε hε + let M := dist (F a) (F x) + dist (F b) (F y) + 1 + have hM : 0 < M := by unfold M; positivity + let t : Fraction := ⟨min 1 (ε / M), (lt_min zero_lt_one (div_pos hε hM)).le, min_le_left _ _⟩ + have ht : 0 < t.val := lt_min zero_lt_one (div_pos hε hM) + have heps : t.val * M ≤ ε := (le_div_iff₀ hM).mp (min_le_right _ _) + let A := mix t a x + let B := mix t b y + have hA : 0 ≤ A := add_nonneg (smul_nonneg (sub_nonneg.mpr t.2.2) ha) (smul_nonneg ht.le hx) + have hB : 0 ≤ B := add_nonneg (smul_nonneg (sub_nonneg.mpr t.2.2) hb') (smul_nonneg ht.le hy) + have hh : mix t A B = mix t a y := by + have eqb : b = a - x + y := by rw [show a - x + y = a - (x - y) by abel, ← he]; abel + unfold A B mix + rw [eqb] + module + have h₁ := hf t a x ha hx + have h₂ := hf t b y hb' hy + have hd : dist (F A) (F B) ≤ dist (F x) (F y) := by + apply le_of_mul_le_mul_left _ ht + rw [← (hf t A B hA hB).1, hh] + simpa only [dist_self, mul_zero, zero_add] using hb t _ _ _ _ _ _ h₁ (hf t a y ha hy) + have ht' := dist_triangle4 (F a) (F A) (F B) (F b) + rw [dist_comm (F B), h₁.1, h₂.1] at ht' + unfold M at heps + linarith + +/-- A common translation into the quadrant induces the same distance. -/ +private theorem same_length (hf : AffineSector F) (hb : Busemann Y) + {a b x y : Coord} (ha : 0 ≤ a) (hb' : 0 ≤ b) (hx : 0 ≤ x) (hy : 0 ≤ y) + (he : a - b = x - y) : dist (F a) (F b) = dist (F x) (F y) := + le_antisymm (slide_le hf hb ha hb' hx hy he) (slide_le hf hb hx hy ha hb' he.symm) + +private theorem translate (s : Finset Coord) : ∃ z, ∀ x ∈ s, 0 ≤ x + z := by + obtain ⟨y, hy⟩ := s.finite_toSet.bddBelow + exact ⟨-y, fun x hx => by rw [← sub_eq_add_neg]; exact sub_nonneg.mpr (hy hx)⟩ + +theorem AffineSector.seminorm (hf : AffineSector F) (hb : Busemann Y) : + ∃ p : Seminorm ℝ Coord, ∀ x y : Coord, 0 ≤ x → 0 ≤ y → p (x - y) = dist (F x) (F y) := by + have hdec (x : Coord) : ∃ a b : Coord, 0 ≤ a ∧ 0 ≤ b ∧ x = a - b := by + obtain ⟨z, hz⟩ := translate {0, x} + exact ⟨x + z, z, hz _ (by simp), by simpa using hz 0 (by simp), by abel⟩ + choose a b ha hb' heq using hdec + let p := fun x => dist (F (a x)) (F (b x)) + have hp (x y : Coord) (hx : 0 ≤ x) (hy : 0 ≤ y) : p (x - y) = dist (F x) (F y) := + same_length hf hb (ha _) (hb' _) hx hy (heq _).symm + have hneg (x : Coord) : p (-x) = p x := by + rw [heq x, neg_sub, hp _ _ (hb' _) (ha _), hp _ _ (ha _) (hb' _), dist_comm] + have hadd (x y : Coord) : p (x + y) ≤ p x + p y := by + obtain ⟨z, hz⟩ := translate {0, x, x + y} + have hz' : 0 ≤ z := by simpa using hz 0 (by simp) + have hx := hz x (by simp) + have hy := hz (x + y) (by simp) + have h := dist_triangle (F (x + y + z)) (F (x + z)) (F z) + rw [← hp _ _ hy hz', ← hp _ _ hy hx, ← hp _ _ hx hz'] at h + rwa [add_sub_cancel_right, show x + y + z - (x + z) + = y by abel, add_sub_cancel_right, add_comm (p y)] at h + have hsmul (t : Fraction) (x : Coord) : p (t.val • x) = t.val * p x := by + have h := (hf t (b x) (a x) (hb' x) (ha x)).1 + have hy : 0 ≤ mix t (b x) (a x) := + add_nonneg (smul_nonneg (sub_nonneg.mpr t.2.2) (hb' x)) (smul_nonneg t.2.1 (ha x)) + have he : mix t (b x) (a x) - b x = t.val • x := by + rw [show t.val • x = t.val • (a x - b x) by rw [← heq]] + unfold mix + module + rw [dist_comm (F (b x)), ← hp _ _ hy (hb' x), he, dist_comm (F (b x))] at h + exact h + have hpos (r : ℝ) (hr : 0 ≤ r) (x : Coord) : p (r • x) = r * p x := by + rcases le_total r 1 with hl | hl + · exact hsmul ⟨r, hr, hl⟩ x + have h₀ : r ≠ 0 := (zero_lt_one.trans_le hl).ne' + have h := hsmul ⟨r⁻¹, inv_nonneg.mpr hr, inv_le_one_of_one_le₀ hl⟩ (r • x) + dsimp only at h + rw [inv_smul_smul₀ h₀] at h + rw [h, mul_inv_cancel_left₀ h₀] + refine ⟨Seminorm.of p hadd ?_, hp⟩ + intro r x + rw [Real.norm_eq_abs] + rcases le_total 0 r with hr | hr + · rw [abs_of_nonneg hr, hpos r hr] + · rw [abs_of_nonpos hr, ← hpos (-r) (neg_nonneg.mpr hr), neg_smul, hneg] + +theorem sector_cuts (h : CutBound (dist : Y → Y → ℝ)) (p : Seminorm ℝ Coord) + (hf : ∀ x y : Coord, 0 ≤ x → 0 ≤ y → p (x - y) = dist (F x) (F y)) : + CutBound (fun x y => p (x - y)) := by + intro x x' y y' z z' w w' t u α β ht hu hα hβ hh + let S : Finset Coord := {x, x', y, y', z, z', w, w'} + obtain ⟨a, ha⟩ := translate S + let f := fun v => F (v + a) + have he (v v' : Coord) (hv : v ∈ S) (hv' : v' ∈ S) : + dist (f v) (f v') = p (v - v') := by + rw [← hf _ _ (ha v hv) (ha v' hv'), add_sub_add_right_eq_sub] + have H := h (f x) (f x') (f y) (f y') (f z) (f z') (f w) (f w') t u α β ht hu hα hβ hh + simpa (disch := simp [S]) only [he] using H + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Comparison for three rays + +The parallelogram law makes the second differences constant along +integer translates of an axis. For opposite rays the triangle +inequality then controls the linear coefficient. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +private theorem quadratic (p : Seminorm ℝ Coord) (hc : CutBound (fun x y => p (x - y))) + (x y : Coord) (n : ℕ) : + p ((n : ℝ) • x - y) ^ 2 = + n * p (x - y) ^ 2 + n * ((n : ℝ) - 1) * p x ^ 2 - ((n : ℝ) - 1) * p y ^ 2 := by + induction n using Nat.twoStepInduction with + | zero => simp + | one => simp + | more n h₀ h₁ => + have h := parallelogram_of_cuts p hc (((n : ℝ) + 1) • x - y) x + have he : ((n : ℝ) + 1) • x - y + x = ((n : ℝ) + 2) • x - y := by module + have he' : ((n : ℝ) + 1) • x - y - x = (n : ℝ) • x - y := by module + push_cast at h₁ ⊢ + rw [he, he', h₀, h₁] at h + linarith only [h] + +variable {Y : Type*} [PseudoMetricSpace Y] + +theorem dist_match {x y z t : Y} (h : dist x z = 0) (h' : dist y t = 0) : + dist x y = dist z t := by + linarith only [h, h', dist_triangle4 x z t y, dist_triangle4 z x y t, dist_comm x z, + dist_comm y t] + +theorem ray_polynomial (h : Busemann Y) (hs : Segments Y) (hc : CutBound (@dist Y _)) + {a b : ℝ → Y} {A B c : ℝ} (ha : Ray a A) (hb : Ray b B) + (he : ∀ r, 0 ≤ r → dist (a r) (b r) = r * c) (n : ℕ) : + dist (a n) (b 1) ^ 2 = n * c ^ 2 + n * ((n : ℝ) - 1) * A ^ 2 - ((n : ℝ) - 1) * B ^ 2 := by + obtain ⟨F, hF, hab⟩ := exists_sector h hs ha hb he + obtain ⟨p, hp⟩ := hF.seminorm h + have h₁ (r s : ℝ) (hr : 0 ≤ r) (hs : 0 ≤ s) : + p ((r, 0) - (0, s)) = dist (a r) (b s) := + (hp (r, 0) (0, s) ⟨hr, le_rfl⟩ ⟨le_rfl, hs⟩).trans (dist_match (hab r hr).1 (hab s hs).2) + have h₀ : dist (a 0) (b 0) = 0 := by simpa using he 0 le_rfl + have hA : p (1, 0) = A := by + have hx := h₁ 1 0 zero_le_one le_rfl + rw [← dist_match (dist_self (a 1)) h₀, ha 1 0 zero_le_one le_rfl] at hx + simpa using hx + have hB : p (0, 1) = B := by + have hx := h₁ 0 1 le_rfl zero_le_one + rw [dist_match h₀ (dist_self (b 1)), hb 0 1 le_rfl zero_le_one] at hx + change p (0 - (0, 1)) = _ at hx + rw [zero_sub, map_neg_eq_map] at hx + simpa using hx + have H := quadratic p (sector_cuts hc p hp) (1, 0) (0, 1) n + rw [show (n : ℝ) • ((1, 0) : Coord) = ((n : ℝ), 0) by simp, + h₁ _ _ (by positivity) zero_le_one, h₁ _ _ zero_le_one zero_le_one, he 1 zero_le_one, + one_mul, hA, hB] at H + exact H + +/-- Midpoint comparison at the common origin in the infinitesimal geometry. -/ +theorem opposite_rays (h : Busemann Y) (hs : Segments Y) (hc : CutBound (@dist Y _)) + {a b z : ℝ → Y} {A B X Z : ℝ} (ha : Ray a A) (hb : Ray b A) (hz : Ray z B) + (ho : ∀ r, 0 ≤ r → dist (a r) (b r) = 2 * r * A) + (hx : ∀ r, 0 ≤ r → dist (a r) (z r) = r * X) + (hy : ∀ r, 0 ≤ r → dist (b r) (z r) = r * Z) : + 2 * (A ^ 2 + B ^ 2) ≤ X ^ 2 + Z ^ 2 := by + by_contra! bad + obtain ⟨n, hn⟩ := exists_nat_gt (2 * B ^ 2 / (2 * (A ^ 2 + B ^ 2) - (X ^ 2 + Z ^ 2))) + rw [div_lt_iff₀ (sub_pos.mpr bad)] at hn + have hh := pow_le_pow_left₀ dist_nonneg (dist_triangle (a n) (z 1) (b n)) 2 + rw [ho _ (Nat.cast_nonneg _), dist_comm (z 1)] at hh + linarith only [hh, hn, ray_polynomial h hs hc ha hz hx n, ray_polynomial h hs hc hb hz hy n, + sq_nonneg (dist (a n) (z 1) - dist (b n) (z 1))] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Infinitesimal rays from scaled segment distances + +The distance of two equal-time points, divided by elapsed time, +is nondecreasing by Busemann convexity. Its limiting slope is +therefore independent of the parametrization used in the limit. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Filter +open scoped Topology + +/-- The time of type `Fraction` for the given inputs. -/ +def time (n : ℕ) (r : ℝ) : Fraction := + if h : 0 ≤ r ∧ r ≤ (n : ℝ) + 1 + then ⟨r / (n + 1), div_nonneg h.1 (by positivity), (div_le_one (by positivity)).mpr h.2⟩ + else ⟨0, le_rfl, zero_le_one⟩ + +private theorem time_scale {n : ℕ} {r : ℝ} (h : 0 ≤ r ∧ r ≤ (n : ℝ) + 1) : + ((n : ℝ) + 1) * (time n r).val = r := by + rw [time, dite_eq_left h] + exact mul_div_cancel₀ _ (by positivity) + +private theorem eventually_large (r : ℝ) : ∀ᶠ n : ℕ in atTop, r ≤ (n : ℝ) + 1 := by + obtain ⟨N, hN⟩ := exists_nat_gt r + filter_upwards [eventually_ge_atTop N] with n hn + exact (hN.le.trans (Nat.cast_le.mpr hn)).trans (le_add_of_nonneg_right zero_le_one) + +variable {Y Z : Type} [PseudoMetricSpace Y] [PseudoMetricSpace Z] + +/-- Computes the rescale by the application `s.pt (time n p.2) o p.1`. -/ +def rescale (s : Segments Y) (o : Y) (n : ℕ) (p : Y × ℝ) := s.pt (time n p.2) o p.1 + +theorem rescale_bound (s : Segments Y) (o : Y) (p : Y × ℝ) : + ∃ D : ℝ, ∀ n : ℕ, ((n : ℝ) + 1) * dist (rescale s o n p) o ≤ D := by + refine ⟨|p.2| * dist o p.1, fun n => ?_⟩ + unfold rescale + rw [dist_comm, (s.divides _ _ _).1, ← mul_assoc] + apply mul_le_mul_of_nonneg_right _ dist_nonneg + by_cases h : 0 ≤ p.2 ∧ p.2 ≤ (n : ℝ) + 1 + · rw [time_scale h]; exact le_abs_self _ + · simp only [time, dite_eq_right h, mul_zero]; exact abs_nonneg _ + +/-- The condition `∀ a b, Tendsto (fun n : ℕ => ((n : ℝ) + 1) * dist (rescale s o n a) (rescale +s o n b)) v (𝓝 (dist (g a) (g b)))` on the specified data. -/ +def Rescaled (s : Segments Y) (o : Y) (g : Y × ℝ → Z) (v : Filter ℕ) : Prop := + ∀ a b, Tendsto (fun n : ℕ => ((n : ℝ) + 1) * dist (rescale s o n a) (rescale s o n b)) + v (𝓝 (dist (g a) (g b))) + +namespace Rescaled + +variable {s : Segments Y} {o : Y} {g : Y × ℝ → Z} {v : Filter ℕ} [v.NeBot] + (h : Rescaled s o g v) (hv : v ≤ atTop) (hb : Busemann Y) + +include h hv hb in +theorem ray (x : Y) : Ray (fun r => g (x, r)) (dist o x) := by + intro r t hr ht + refine tendsto_nhds_unique (h (x, r) (x, t)) ?_ + apply tendsto_const_nhds.congr' + filter_upwards [hv (eventually_large r), hv (eventually_large t)] with n hn hn' + simp only [rescale] + rw [speed hb s (s.divides _ _ _) (s.divides _ _ _), ← mul_assoc, + show ((n : ℝ) + 1) * |(time n r).val - (time n t).val| = + |((n : ℝ) + 1) * ((time n r).val - (time n t).val)| by + rw [abs_mul, abs_of_pos (show 0 < (n : ℝ) + 1 by positivity)], + mul_sub, time_scale ⟨hr, hn⟩, time_scale ⟨ht, hn'⟩] + +include h hv hb in +private theorem lower (x y : Y) {r : ℝ} (hr : 0 ≤ r) (u : Fraction) (hu : 0 < u.val) : + u.val * dist (g (x, r)) (g (y, r)) ≤ r * dist (s.pt u o x) (s.pt u o y) := by + apply le_of_tendsto ((h (x, r) (y, r)).const_mul u.val) + filter_upwards [hv (eventually_large r), hv (eventually_large (r / u.val))] with n hn hn' + rw [div_le_iff₀ hu] at hn' + have he := time_scale ⟨hr, hn⟩ + have hl : (time n r).val ≤ u.val := + le_of_mul_le_mul_left (he.le.trans hn') (by positivity) + have hd := mul_le_mul_of_nonneg_left (Segments.radial hb s o x y hl) + (show 0 ≤ (n : ℝ) + 1 by positivity) + rw [← mul_assoc _ (time n r).val, he, mul_left_comm] at hd + exact hd + +include h hv hb in +private theorem slope (x y : Y) {r t : ℝ} (hr : 0 ≤ r) (ht : 0 ≤ t) : + t * dist (g (x, r)) (g (y, r)) ≤ r * dist (g (x, t)) (g (y, t)) := by + rcases ht.eq_or_lt with rfl | ht + · rw [zero_mul]; exact mul_nonneg hr dist_nonneg + apply ge_of_tendsto ((h (x, t) (y, t)).const_mul r) + filter_upwards [hv (eventually_large t)] with n hn + have he := time_scale ⟨ht.le, hn⟩ + have hu : 0 < (time n t).val := by + apply pos_of_mul_pos_right (he.symm ▸ ht) (by positivity) + have hd := mul_le_mul_of_nonneg_left (h.lower hv hb x y hr _ hu) + (show 0 ≤ (n : ℝ) + 1 by positivity) + rw [← mul_assoc, he, mul_left_comm] at hd + exact hd + +include h hv hb in +theorem linear (x y : Y) (r : ℝ) (hr : 0 ≤ r) : + dist (g (x, r)) (g (y, r)) = r * dist (g (x, 1)) (g (y, 1)) := by + simpa only [one_mul] using le_antisymm (h.slope hv hb x y hr zero_le_one) + (h.slope hv hb x y zero_le_one hr) + +include h hb in +theorem contract (x y : Y) : dist (g (x, 1)) (g (y, 1)) ≤ dist x y := by + apply le_of_tendsto' (h (x, 1) (y, 1)) + intro n + let t := time n 1 + have he : ((n : ℝ) + 1) * t.val = 1 := time_scale ⟨zero_le_one, by linarith⟩ + have hh := hb t _ _ _ _ _ _ (s.divides t o x) (s.divides t o y) + rw [dist_self, mul_zero, zero_add] at hh + simpa only [rescale, ← mul_assoc, he, one_mul] using + mul_le_mul_of_nonneg_left hh (show 0 ≤ (n : ℝ) + 1 by positivity) + +include h hb in +theorem opposite {x y : Y} (heq : dist x o + dist o y = dist x y) : + dist (g (x, 1)) (g (y, 1)) = dist x y := by + refine le_antisymm (h.contract hb _ _) (ge_of_tendsto' (h (x, 1) (y, 1)) ?_) + intro n + let t := time n 1 + have he : ((n : ℝ) + 1) * t.val = 1 := time_scale ⟨zero_le_one, by linarith⟩ + have hh := dist_triangle4 x (s.pt t o x) (s.pt t o y) y + rw [dist_comm x (s.pt t o x), (s.divides t o x).2, (s.divides t o y).2, + dist_comm o x, ← heq] at hh + have hd : t.val * dist x y ≤ dist (s.pt t o x) (s.pt t o y) := by rw [← heq]; linarith + simpa only [rescale, ← mul_assoc, he, one_mul] using + mul_le_mul_of_nonneg_left hd (show 0 ≤ (n : ℝ) + 1 by positivity) + +end Rescaled +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Spectral squared-distance comparison + +Blow up three segments about their common origin. In the limit the +first two rays are opposite, and each pair spans an affine sector. +The shifted crossing theorem forces the parallelogram law on these +sectors. The comparison for opposite rays gives the midpoint +inequality downstairs, which implies the inequality at every fraction. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Filter + +theorem WireModels.midpoints {K Y : Type} [Field K] [PseudoMetricSpace Y] + (h : WireModels K Y) (s : Segments Y) : MidpointBound Y := by + intro x y m hm z + let v := Ultrafilter.of (atTop : Filter ℕ) + have hv : (v : Filter ℕ) ≤ atTop := Ultrafilter.of_le _ + obtain ⟨Z, _, g, hg, hs, hu⟩ := h.zoom s m (rescale s m) (rescale_bound s m) v + change Rescaled s m g v at hu + have hb := h.busemann + have hx := hm.1 + have hy := hm.2 + dsimp only [half] at hx hy ⊢ + have he : dist m y = dist m x := by rw [dist_comm m x]; linarith + have ho := hu.opposite hb (show dist x m + dist m y = dist x y by linarith) + have hy' := hu.ray hv hb y + rw [he] at hy' + have hc (t : ℝ) (ht : 0 ≤ t) : dist (g (x, t)) (g (y, t)) = 2 * t * dist m x := by + rw [hu.linear hv hb _ _ t ht, ho, dist_comm m x, hx] + ring + have hbnd := opposite_rays hg.busemann hs (hg.cuts (Sphere.shifted_crossing K)) + (hu.ray hv hb x) hy' (hu.ray hv hb z) hc (hu.linear hv hb x z) (hu.linear hv hb y z) + rw [dist_comm m x, hx] at hbnd + linarith only [hbnd, pow_le_pow_left₀ dist_nonneg (hu.contract hb x z) 2, + pow_le_pow_left₀ dist_nonneg (hu.contract hb y z) 2] + +/-- Comparison holds at any spectral site which divides a wire in the +prescribed ratio. The argument applies over every coefficient field. -/ +theorem spectralComparison (K : Type) [Field K] : SpectralComparison K := by + intro S _ _ _ f hf a m b u hm z + let := TermModel.termMetric hf 1 zero_le_one + have hd (x y : Term S) : dist x y = TermModel.length hf x y := one_mul _ + have h : WireModels K (Term S) := by + intro B _ _ _ x D hD hx + simp only [hd] at hx ⊢ + exact TermModel.length_ordinary hf B x D hx + have hs : Segments (Term S) := by + intro t x y + refine ⟨.seg t x y, ?_⟩ + simp only [Divides, hd] + exact TermModel.length_seg hf t x y + have ht : Divides u (Term.mark a) (.mark b) (.mark m) := by + simp only [Divides, hd, TermModel.length_mark] + exact hm + have he := (h.midpoints hs).all h.busemann hs ht (.mark z) + simpa only [hd, TermModel.length_mark] using he + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- Fusion candidates at the actual collision blocks of an affine arrangement. -/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Motion + +open Polynomial Sphere Finset + +variable {F A : Type} [Field F] [Fintype A] (a : A → Fin 2 → F) (d : Option F) + +open scoped Classical in +/-- The indexed operation `univ.image fun i => projection (a i) d`. -/ +def centers : Finset F := univ.image fun i => projection (a i) d + +open scoped Classical in +/-- Computes the index by the application `Fin (centers a d).card`. -/ +abbrev Index := Fin (centers a d).card + +open scoped Classical in +/-- Reindexes `Index a d` and `↥(centers a d)` by an equivalence. -/ +def label : Index a d ≃ ↥(centers a d) := + (Fintype.equivFinOfCardEq (Fintype.card_coe _)).symm + +open scoped Classical in +/-- The value specified by `(label a d j).1`. -/ +def point (j : Index a d) : F := (label a d j).1 + +open scoped Classical in +/-- The indexed operation `(label a d).symm ⟨projection (a i) d, mem_image_of_mem (fun j => +projection (a j) d) (mem_univ i)⟩`. -/ +def group (i : A) := (label a d).symm + ⟨projection (a i) d, mem_image_of_mem (fun j => projection (a j) d) (mem_univ i)⟩ + +open scoped Classical in +theorem group_spec (i : A) : point a d (group a d i) = projection (a i) d := by + simp [point, group] + +open scoped Classical in +theorem point_inj : Function.Injective (point a d) := + Subtype.val_injective.comp (label a d).injective + +open scoped Classical in +theorem point_mem (j : Index a d) : point a d j ∈ centers a d := (label a d j).2 + +open scoped Classical in +theorem at_block (j : Index a d) (i : A) : + group a d i = j ↔ i ∈ pointsOn a (d, point a d j) := by + rw [← (point_inj a d).eq_iff, group_spec] + simp [pointsOn] + +open scoped Classical in +theorem block_index (k : Option F × F) (h : k ∈ blocks a) : ∃ j, point a k.1 j = k.2 := by + obtain ⟨i, hi⟩ := (mem_blocks.mp h).2 + exact ⟨group a k.1 i, (group_spec _ _ _).trans (mem_filter.mp hi).2⟩ + +open scoped Classical in +theorem sum_blocks {R : Type*} [AddCommMonoid R] (b : Option F × F → R) : + ∑ k ∈ blocks a, b k = ∑ d ∈ directions a, ∑ j, b (d, point a d j) := by + rw [← sum_fiberwise_of_maps_to (fun k h => (mem_blocks.mp h).1) b] + refine sum_congr rfl fun d hd => ?_ + symm + refine sum_bij (fun j _ => (d, point a d j)) ?_ ?_ ?_ (fun _ _ => rfl) + · intro j _ + obtain ⟨i, _, hi⟩ := mem_image.mp (point_mem a d j) + exact mem_filter.mpr ⟨mem_blocks.mpr ⟨hd, i, mem_filter.mpr ⟨mem_univ _, hi⟩⟩, rfl⟩ + · exact fun _ _ _ _ h => point_inj a d (congrArg Prod.snd h) + · intro k h + obtain ⟨hk, rfl⟩ := mem_filter.mp h + obtain ⟨j, hj⟩ := block_index a k hk + exact ⟨j, mem_univ _, Prod.ext rfl hj⟩ + +open scoped Classical in +/-- Computes the choice by the application `Pattern (centers a d).card M`. -/ +abbrev Choice (M : ℕ) := Pattern (centers a d).card M + +variable {M : ℕ} + +open scoped Classical in +/-- The sum of `(t j).val` indexed by `j`. -/ +def budget (t : Choice a d M) := ∑ j, (t j).val + +open scoped Classical in +/-- The indexed operation `fusedTerm (point a d) (group a d) (fun i => collisionOffset (a i) d) +(fun i => (t i).val)`. -/ +def term (t : Choice a d M) {e : A → ℕ} : States 1 e → F := + fusedTerm (point a d) (group a d) (fun i => collisionOffset (a i) d) (fun i => (t i).val) + +open scoped Classical in +/-- The indexed operation `wick (fun i j => fieldKernel (position (a i.1) s 1, i.2) (position (a +j.1) s 1, j.2)) (inputs x)`. -/ +def form (e : A → ℕ) (s : F) (x : States 1 e) : F := + wick (fun i j => fieldKernel (position (a i.1) s 1, i.2) (position (a j.1) s 1, j.2)) (inputs x) + +open scoped Classical in +/-- The quantity computed by `((directions a).card - 1) * ((∑ i, e i) / 2)`. -/ +def degree (e : A → ℕ) := ((directions a).card - 1) * ((∑ i, e i) / 2) + +open scoped Classical in +theorem jets (hd : d ∈ directions a) (e : A → ℕ) (hM : 2 * degree a e < M) + {i : ℕ} (hi : i ≤ degree a e) : + (fun b : States 1 e => jetAt (degree a e) d i (correlatorPoly a (X : F[X]) 1 (inputs b))) ∈ + Submodule.span F {v | ∃ t : Choice a d M, budget a d t ≤ 2 * i ∧ term a d t = v} := by + obtain ⟨c, hc⟩ := fusion_terms (r := 1) (e := e) (point a d) (point_inj a d) + (group a d) (fun j => collisionOffset (a j) d) (jetVar F M) M (jetVar_pow F M) + rw [show point a d ∘ group a d = fun j => projection (a j) d from funext (group_spec a d)] at hc + have h := jets_of_fusion a (inputs (r := 1) (e := e)) d hd ((∑ i, e i) / 2) + (degree a e) M (fun b => by rw [weight_inputs]) rfl hM + (fun t : Choice a d M => c • term a d t) (budget a d) hc _ hi + apply (Submodule.span_le.mpr ?_) h + rintro _ ⟨t, ht, rfl⟩ + exact Submodule.smul_mem _ _ (Submodule.subset_span ⟨t, ht, rfl⟩) + +open scoped Classical in +theorem select (e : A → ℕ) (hM : 2 * degree a e < M) (W : Submodule F (States 1 e → F)) + (s : F) (hs : denominator (directions a) s 1 ≠ 0) (he : form a e s ∉ W) : + ∃ t : ∀ d, Choice a d M, (∀ d ∈ directions a, term a d (t d) ∉ W) ∧ + ∑ d ∈ directions a, budget a d (t d) ≤ 2 * degree a e := by + let P (x : States 1 e) := correlatorPoly a (X : F[X]) 1 (inputs x) + refine select_fusions (directions a) P (degree a e) + (fun d (t : Choice a d M) => term a d t (e := e)) (fun d t => budget a d t) + ?_ (fun d hd _ hi => jets a d hd e hM hi) W s ?_ + · intro b + simpa [P, degree, weight_inputs] using (correlator_form a (inputs b)).1 + · have eqn : (fun b => (P b).eval s) = + (denominator (directions a) s 1 ^ ((∑ i, e i) / 2)) • form a e s := by + funext b + have e := correlator_map (aeval s) a (X : F[X]) 1 (inputs b) + simp only [aeval_X, map_one, correlator_specialize a s 1 hs, weight_inputs] at e + simpa [P, form] using e + rw [eqn, W.smul_mem_iff (pow_ne_zero _ hs)] + exact he + +open scoped Classical in +/-- The indexed operation `(directions a).biUnion fun d => univ.image (fun t : Choice a d M => +term a d t)`. -/ +def menu (e : A → ℕ) (M : ℕ) : Finset (States 1 e → F) := + (directions a).biUnion fun d => univ.image (fun t : Choice a d M => term a d t) + +open scoped Classical in +theorem menu_size (e : A → ℕ) (M : ℕ) : + (menu a e M).card ≤ (directions a).card * (M + 1) ^ Fintype.card A := by + apply card_biUnion_le.trans + rw [← smul_eq_mul, ← sum_const] + refine sum_le_sum fun d _ => card_image_le.trans ?_ + simp only [card_univ, Choice, Pattern, Fintype.card_fun, Fintype.card_fin] + exact Nat.pow_le_pow_right (by omega) card_image_le + +open scoped Classical in +/-- Every block has its own cut decomposition of an expensive term, paid +for from a common budget of doubled energy. -/ +theorem select_cuts (e : A → ℕ) (hM : 2 * degree a e < M) (W : Submodule F (States 1 e → F)) + (s : F) (hs : denominator (directions a) s 1 ≠ 0) (he : form a e s ∉ W) : + ∃ b : Option F × F → ℕ, (∑ k ∈ blocks a, b k) ≤ 2 * degree a e ∧ + ∀ k ∈ blocks a, ∃ T ∈ menu a e M, T ∉ W ∧ + ∃ L R : Level 1 (b k) → States 1 e → F, + (∀ x, T x = ∑ j, L j x * R j x) ∧ + (∀ j x y, (∀ i ∈ pointsOn a k, x i = y i) → L j x = L j y) ∧ + (∀ j x y, (∀ i ∉ pointsOn a k, x i = y i) → R j x = R j y) := by + obtain ⟨t, ht, hcost⟩ := select a e hM W s hs he + let b (k : Option F × F) := if h : k.2 ∈ centers a k.1 then + (t k.1 ((label a k.1).symm ⟨k.2, h⟩)).val else 0 + have hb (d : Option F) (j : Index a d) : b (d, point a d j) = (t d j).val := by + simp [b, point] + refine ⟨b, ?_, ?_⟩ + · simpa [sum_blocks, hb, budget] using hcost + · rintro ⟨d, v⟩ hk + have hd := (mem_blocks.mp hk).1 + obtain ⟨j, hj⟩ := block_index a _ hk + change Index a d at j + change point a d j = v at hj + subst v + refine ⟨term a d (t d), mem_biUnion.mpr ⟨d, hd, mem_image_of_mem _ (mem_univ _)⟩, ht d hd, ?_⟩ + rw [hb] + simp_rw [← at_block a d j] + exact fused_separates (point a d) (group a d) (fun i => collisionOffset (a i) d) (fun i + => (t d i).val) j + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Motion +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryControl.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryControl.lean new file mode 100644 index 0000000000..724a3344b5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryControl.lean @@ -0,0 +1,296 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryEfficient +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Shift +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Parameters +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Pad + +/-! +# The permutation group for finite detection + +A world chooses one input permutation at each height. Evaluation at +these inputs is a group homomorphism. The choice of a controller +depends on the height but is independent of the input. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable {F J : Type} [Field F] {X : J → Type} {h : J → ℕ} {e : ∀ j, X j ↪ B (h j)} + +open scoped Classical in +theorem Efficient.inv {g : Family X} (hg : Efficient F e g) : Efficient F e g⁻¹ := by + obtain ⟨c, hc⟩ := hg + refine ⟨max c 100 + 1, fun j => ?_⟩ + obtain ⟨f, hf, he⟩ := hc j + obtain ⟨v, hv, hi⟩ := cheap_inverse F (h j) + refine ⟨_, hf.comp hv, fun p => ?_⟩ + simp only [Function.comp_apply, he, pack, Pi.inv_apply, map_inv] + exact hi _ + +variable (F e) + +open scoped Classical in +/-- Builds `Subgroup (Family X) where carrier` with the specified `carrier`, `one_mem'`, +`mul_mem'`, `inv_mem'`. -/ +def controllers : Subgroup (Family X) where + carrier := {g | Efficient F e g} + one_mem' := efficient_fixed F e 1 + mul_mem' := Efficient.mul + inv_mem' := Efficient.inv + +open scoped Classical in +/-- Uses `⟨fun _ p => p, efficient_target F e⟩` as the representation. -/ +def target : controllers F e := ⟨fun _ p => p, efficient_target F e⟩ + +open scoped Classical in +/-- Builds `controllers F e →* (∀ j, Equiv.Perm (X j)) where toFun g j` with the specified +`toFun`, `map_one'`, `map_mul'`. -/ +def read (t : ∀ j, Equiv.Perm (X j)) : controllers F e →* (∀ j, Equiv.Perm (X j)) where + toFun g j := g.val j (t j) + map_one' := rfl + map_mul' _ _ := rfl + +open scoped Classical in +/-- At a fixed height and a given input the group acts directly on the +labels. The distinguished target acts by that input permutation. -/ +def run (j : J) (p : Equiv.Perm (X j)) : controllers F e →* Equiv.Perm (X j) where + toFun g := g.val j p + map_one' := rfl + map_mul' _ _ := rfl + +variable [∀ j, Fintype (X j)] [∀ j, Nonempty (X j)] + +open scoped Classical in +/-- Builds `Routing.PermSystem X (controllers F e) where World` with the specified `World`, +`read`, `fixed`, `read_fixed`. -/ +def system {c : ℕ} (H : Factors F c) : Routing.PermSystem X (controllers F e) where + World := ∀ j, Equiv.Perm (X j) + read := read F e + fixed g := ⟨fun j _ => g j, efficient_fixed F e g⟩ + read_fixed _ _ := rfl + factor s g hg := by + have hf (j : J) (p : Equiv.Perm (X j)) (x : X j) : + (s j (g.val j p x)).1 = (s j x).1 := by + let t := Function.update (fun j => (1 : Equiv.Perm (X j))) j p + have he := hg t j x + change (s j (g.val j (t j) x)).1 = _ at he + simpa [t] using he + obtain ⟨u, v, w, hu, hv, hw, he, hu', hv', hw'⟩ := Efficient.factor s H g.property hf + exact ⟨⟨u, hu⟩, ⟨v, hv⟩, ⟨w, hw⟩, Subtype.ext he, + fun t j => hu' j (t j), fun t j => hv' j (t j), fun t j => hw' j (t j)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +/- +# Efficient hops and local price tests for tagged routing + +A member of the fixed hop menu computes its permutation from the +input permutation by a controller of near-linear size. Its groups +are fixed before the input is given. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral Coloring +open scoped Pointwise BigOperators + +open scoped Classical in +/-- The data for the routes construction, including `labels`, `[finiteLabels`, +`[inhabitedLabels`, `size`, `embed`. -/ +structure Routes (F : Type) [Field F] (m : ℕ) where + /-- The label data of type `ℕ → Type`. -/ + labels : ℕ → Type + [finiteLabels : ∀ h, Fintype (labels h)] + [inhabitedLabels : ∀ h, Nonempty (labels h)] + size : ∀ h, 2 ^ h ≤ Fintype.card (labels h) ∧ Fintype.card (labels h) < 2 ^ (h + 1) + /-- Embeds the coordinates as `∀ h, labels h ↪ Coloring.B (h + 1)`. -/ + embed : ∀ h, labels h ↪ Coloring.B (h + 1) + /-- Embeds the coordinates as `∀ h, Coloring.B h ↪ labels h`. -/ + base : ∀ h, Coloring.B h ↪ labels h + initial : ∀ h i, (embed h (base h i)).val = i.val + /-- The `Routes` component of type `Type`. -/ + Plane : Type + /-- The `Routes` component of type `Plane → Subgroup (controllers F embed)`. -/ + moves : Plane → Subgroup (controllers F embed) + /-- The `Routes` component of type `Parameters F moves (Coloring.target F embed)⁻¹`. -/ + params : Parameters F moves (Coloring.target F embed)⁻¹ + /-- Stores the overhead associated with this `Routes`. -/ + overhead : ℕ + groups : ∀ g ∈ params.core, ∀ h : ℕ, ∃ (A B : Type) (_ : Fintype A) (_ : Fintype B) + (f : labels h ≃ A × B), Fintype.card B ≤ 2 ^ (h / m + overhead) ∧ + ∀ σ i, (f (g.val h σ i)).1 = (f i).1 + +attribute [instance] Routes.finiteLabels Routes.inhabitedLabels + +variable {F : Type} [Field F] {m : ℕ} + +open scoped Classical in +/-- The value specified by `MulAction.compHom _ ((Equiv.Perm.viaEmbeddingHom (T.embed h)).comp +(Coloring.run F T.embed h σ))`. -/ +abbrev Routes.onLabels (T : Routes F m) (h : ℕ) (σ : Equiv.Perm (T.labels h)) : + MulAction (controllers F T.embed) (Coloring.B (h + 1)) := + MulAction.compHom _ ((Equiv.Perm.viaEmbeddingHom (T.embed h)).comp (Coloring.run F T.embed h σ)) + +open scoped Classical in +/-- The value specified by `T.onLabels h (σ.viaEmbedding (T.base h))`. -/ +abbrev Routes.action (T : Routes F m) (h : ℕ) (σ : Equiv.Perm (Coloring.B h)) : + MulAction (controllers F T.embed) (Coloring.B (h + 1)) := + T.onLabels h (σ.viaEmbedding (T.base h)) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Computing the finite menu of routes + +Pad a listed permutation by fixed points. For a fixed number of +controllers, parallel evaluation has near-linear size in the input. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Coloring + +open scoped Classical in +private def extendWord : (h : ℕ) → Val (word h) → Val (word (h + 1)) + | 0, _ => (false, ()) + | h + 1, x => (x.1, extendWord h x.2) + +open scoped Classical in +private theorem extend_value (h : ℕ) (x : Val (word h)) : + Lookup.value (h + 1) (extendWord h x) = Lookup.value h x := by + induction h with + | zero => rfl + | succ h ih => + change _ + 2 * Lookup.value (h + 1) (extendWord h x.2) = _ + rw [ih] + rfl + +open scoped Classical in +private theorem extend_bits (h : ℕ) (j : slots (word (h + 1))) : + (∃ i : slots (word h), ∀ x, bits (word (h + 1)) (extendWord h x) j = bits (word h) x i) ∨ + ∀ x, bits (word (h + 1)) (extendWord h x) j = false := by + induction h with + | zero => + right + cases j with + | inl => exact fun _ => rfl + | inr a => exact a.elim + | succ h ih => + cases j with + | inl a => exact .inl ⟨.inl a, fun _ => rfl⟩ + | inr j => + rcases ih j with ⟨i, hi⟩ | hi + · exact .inl ⟨.inr i, fun x => hi x.2⟩ + · exact .inr (fun x => hi x.2) + +open scoped Classical in +private theorem lower_code (h : ℕ) (k : B h) : + (Format.addr (h + 1)).code (lowerHalf h k) = + bits (word (h + 1)) (extendWord h ((Control.index h).symm k)) := by + apply (Control.decode (h + 1)).injective + rw [show (Format.addr (h + 1)).code = (Control.decode (h + 1)).symm from rfl, + Equiv.apply_symm_apply, Control.decode, Equiv.trans_apply, Equiv.symm_apply_apply] + apply Fin.ext + change k.val = Lookup.value _ (extendWord _ _) + rw [extend_value] + exact (Lookup.value_bits k.isLt).symm + +open scoped Classical in +private theorem cheap_inflate (F : Type) [Field F] (h : ℕ) : + Cheap F (h + 1) (h + 1) (Perm h) (Perm (h + 1)) (inflate h) 2 := by + let f := (Perm (h + 1)).code ∘ inflate h ∘ (Perm h).code.symm + have hc : Install.Depends f 1 := by + rintro ⟨a, b⟩ + have he (x) : f x (a, b) = (Format.addr (h + 1)).code (inflate h ((Perm h).code.symm x) a) b + := rfl + by_cases ha : a.val < 2 ^ h + · let k : B h := ⟨a.val, ha⟩ + have he' (x) : f x (a, b) = + bits (word (h + 1)) (extendWord h ((Control.index h).symm (((Perm h).code.symm x) k))) b + := by + rw [he, inflate, dite_eq_left ha, lower_code] + rcases extend_bits h b with ⟨i, hi⟩ | hi + · have hh (x) : f x (a, b) = x (k, i) := by + rw [he', hi] + exact congrFun ((Perm h).code.apply_symm_apply x) (k, i) + refine ⟨{(k, i)}, by simp, fun x y hxy => ?_⟩ + rw [hh, hh, hxy _ (Finset.mem_singleton_self _)] + · exact ⟨∅, by simp, fun _ _ _ => by rw [he', he', hi, hi]⟩ + · refine ⟨∅, by simp, fun _ _ _ => ?_⟩ + rw [he, he, inflate, inflate, dite_eq_right ha, dite_eq_right ha] + refine ⟨_, hc.bnet F, ?_⟩ + change (Perm h).width + (Perm (h + 1)).width + ((Perm h).width + 34 * (Perm (h + 1)).width) ≤ _ + simp only [Perm, Format.width_vec, Format.width_addr] + rw [Format.width_addr (h + 1)] + have hh : 2 ^ h * h ≤ 2 ^ (h + 1) * (h + 1) := by gcongr <;> omega + calc + _ ≤ 37 * (2 ^ (h + 1) * (h + 1)) := by nlinarith only [hh] + _ = 2 ^ (h + 1) * (37 * (h + 1)) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ (by nlinarith) + +variable {F : Type} [Field F] {m : ℕ} (T : Routes F m) + +open scoped Classical in +theorem Routes.embed_base (h : ℕ) (i : B h) : T.embed h (T.base h i) = lowerHalf h i := + Fin.ext (T.initial _ _) + +open scoped Classical in +theorem Routes.pack_eq (h : ℕ) (π : Equiv.Perm (B h)) : + pack (T.embed h) (π.viaEmbedding (T.base h)) = inflate h π := by + funext a + change (π.viaEmbedding (T.base h)).viaEmbedding (T.embed h) a = inflate h π a + unfold inflate + split + · rename_i ha + let i : B h := ⟨a, ha⟩ + have eq : a = T.embed h (T.base h i) := (Fin.ext (T.initial h i)).symm + change _ = lowerHalf h (π i) + rw [eq, Equiv.Perm.viaEmbedding_apply, Equiv.Perm.viaEmbedding_apply, T.embed_base] + · rename_i ha + by_cases he : a ∈ Set.range (T.embed h) + · obtain ⟨b, rfl⟩ := he + have hb : b ∉ Set.range (T.base h) := by + rintro ⟨i, rfl⟩ + exact ha ((T.initial h i).trans_lt i.isLt) + rw [Equiv.Perm.viaEmbedding_apply, Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ hb] + · exact Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ he + +open scoped Classical in +theorem Routes.target_action (h : ℕ) (π : Equiv.Perm (B h)) (i : B (h + 1)) : + (T.action h π).smul (Coloring.target F T.embed) i = inflate h π i := + congrFun (T.pack_eq h π) i + +open scoped Classical in +theorem Routes.controllers_net (t : ℕ) (f : B t → controllers F T.embed) : + ∃ c : ℕ, ∀ h : ℕ, 2 ^ t ≤ h + 1 → + ∃ v, Cheap F (h + 1) (h + 1) (Perm h) (.vec t (Perm (h + 1))) v c ∧ + ∀ π : Equiv.Perm (B h), ∀ i j, v π i j = (T.action h π).smul (f i) j := by + have he (i : B t) : Efficient F T.embed (f i).val := (f i).property + choose c hc using he + let C := Finset.univ.sup c + refine ⟨max 2 (C + 2) + 1, fun h ht => ?_⟩ + choose u hu hu' using fun i => hc i h + have hall (i : B t) : Cheap F (h + 1) (h + 1) (Perm (h + 1)) (Perm (h + 1)) (u i) C := + (hu i).mono (Finset.le_sup (Finset.mem_univ i)) + refine ⟨_, (cheap_inflate F h).comp (Cheap.share u hall ht), ?_⟩ + intro π i j + change u i (inflate h π) j = _ + rw [← T.pack_eq, hu'] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryEfficient.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryEfficient.lean new file mode 100644 index 0000000000..47628347cb --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryEfficient.lean @@ -0,0 +1,153 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Parameters +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Partitions +public import Mathlib.GroupTheory.Perm.ViaEmbedding + +/-! +# Near-linear controllers on packed addresses + +An input permutation and each output permutation are extended by +the identity outside the label set. Circuits may depend on the +height and the fixed address format. Their cost exponent is uniform. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +open Equiv + +variable {F J : Type} [Field F] {X : J → Type} {h : J → ℕ} {e : ∀ j, X j ↪ B (h j)} + +open scoped Classical in +/-- The condition `∀ j, Equiv.Perm (X j) → Equiv.Perm (X j)` on the specified data. -/ +abbrev Family (X : J → Type) := ∀ j, Equiv.Perm (X j) → Equiv.Perm (X j) + +open scoped Classical in +/-- The value specified by `⇑(Equiv.Perm.viaEmbeddingHom i g)`. -/ +abbrev pack {T : Type} {h : ℕ} (i : T ↪ B h) (g : Equiv.Perm T) : (Perm h).obj := + ⇑(Equiv.Perm.viaEmbeddingHom i g) + +open scoped Classical in +/-- The condition `∃ c : ℕ, ∀ j, ∃ f, Cheap F (h j) (h j) (Perm (h j)) (Perm (h j)) f c ∧ ∀ p, f +(pack (e j) p) = pack (e j) (g j p)` on the specified data. -/ +def Efficient (F : Type) [Field F] (e : ∀ j, X j ↪ B (h j)) (g : Family X) : Prop := + ∃ c : ℕ, ∀ j, ∃ f, Cheap F (h j) (h j) (Perm (h j)) (Perm (h j)) f c ∧ + ∀ p, f (pack (e j) p) = pack (e j) (g j p) + +open scoped Classical in +private theorem perm_width (h : ℕ) : (Perm h).width ≤ 2 ^ h * (100 + h) ^ 1 := by + simp [Perm] + +open scoped Classical in +theorem efficient_fixed (F : Type) [Field F] (e : ∀ j, X j ↪ B (h j)) + (g : ∀ j, Equiv.Perm (X j)) : Efficient F e (fun j _ => g j) := + ⟨2, fun j => ⟨_, Cheap.const F (perm_width _) (perm_width _) (pack (e j) (g j)), fun _ => rfl⟩⟩ + +open scoped Classical in +theorem efficient_target (F : Type) [Field F] (e : ∀ j, X j ↪ B (h j)) : + Efficient F e (fun _ p => p) := + ⟨2, fun _ => ⟨_, Cheap.id F (perm_width _), fun _ => rfl⟩⟩ + +variable {g g' : Family X} + +open scoped Classical in +theorem Efficient.mul (hg : Efficient F e g) (hg' : Efficient F e g') : Efficient F e (g * g') := by + obtain ⟨c, hc⟩ := hg + obtain ⟨d, hd⟩ := hg' + refine ⟨max (max c d + 1) 8 + 1, fun j => ?_⟩ + obtain ⟨u, hu, he⟩ := hc j + obtain ⟨v, hv, hf⟩ := hd j + refine ⟨_, (hu.pair hv).comp (Cheap.lookup F (h j) (h j) (.addr (h j)) le_rfl (by simp)), ?_⟩ + intro p + simp only [Function.comp_apply, he, hf, Pi.mul_apply, pack, map_mul] + rfl + +open scoped Classical in +private def clean {T : Type} {n : ℕ} (i : T ↪ B n) (x : (Perm n).obj) (a : B n) := + if a ∈ Set.range i then x a else a + +open scoped Classical in +private theorem cheap_clean {T : Type} {n : ℕ} (i : T ↪ B n) : + Cheap F n n (Perm n) (Perm n) (clean i) 2 := by + have he (x : (Perm n).pins → Bool) (a : B n) (b : slots (word n)) : + ((Perm n).code ∘ clean i ∘ (Perm n).code.symm) x (a, b) = + if a ∈ Set.range i then x (a, b) else (Format.addr n).code a b := by + change (Format.addr n).code (clean i ((Perm n).code.symm x) a) b = _ + unfold clean + split + · exact congrFun ((Perm n).code.apply_symm_apply x) (a, b) + · rfl + have hc : Install.Depends ((Perm n).code ∘ clean i ∘ (Perm n).code.symm) 1 := by + rintro ⟨a, b⟩ + refine ⟨{(a, b)}, by simp, fun x y h => ?_⟩ + rw [he, he, h (a, b) (Finset.mem_singleton_self _)] + refine ⟨_, hc.bnet F, ?_⟩ + change (Perm n).width + (Perm n).width + ((Perm n).width + 34 * (Perm n).width) ≤ _ + simp only [Perm, Format.width_vec, Format.width_addr] + calc + _ = 2 ^ n * (37 * n) := by ring + _ ≤ _ := Nat.mul_le_mul_left _ (by nlinarith) + +open scoped Classical in +theorem efficient_of_on + {c : ℕ} (hh : ∀ j, ∃ f, Cheap F (h j) (h j) (Perm (h j)) (Perm (h j)) f c ∧ + ∀ p a, f (pack (e j) p) (e j a) = e j (g j p a)) : Efficient F e g := by + refine ⟨max c 2 + 1, fun j => ?_⟩ + obtain ⟨f, hf, he⟩ := hh j + refine ⟨_, hf.comp (cheap_clean (e j)), fun p => ?_⟩ + funext a + change clean (e j) _ a = (g j p).viaEmbedding (e j) a + unfold clean + split + · rename_i ha + obtain ⟨b, rfl⟩ := ha + rw [Equiv.Perm.viaEmbedding_apply] + exact he _ _ + · exact (Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ ‹_›).symm + +variable [∀ j, Finite (X j)] [∀ j, Nonempty (X j)] + +open scoped Classical in +/-- A single output circuit for all valid inputs induces three +permutation families, each with a uniform polynomial overhead. -/ +theorem Efficient.factor {C A D : J → Type} [∀ j, Finite (A j)] [∀ j, Finite (D j)] + (s : ∀ j, X j ≃ C j × (A j × D j)) {c : ℕ} (H : Factors F c) (hg : Efficient F e g) + (hf : ∀ j p x, (s j (g j p x)).1 = (s j x).1) : + ∃ u v w : Family X, Efficient F e u ∧ Efficient F e v ∧ Efficient F e w ∧ g = u * v * w ∧ + (∀ j p x, (s j (u j p x)).1 = (s j x).1 ∧ (s j (u j p x)).2.1 = (s j x).2.1) ∧ + (∀ j p x, (s j (v j p x)).1 = (s j x).1 ∧ (s j (v j p x)).2.2 = (s j x).2.2) ∧ + (∀ j p x, (s j (w j p x)).1 = (s j x).1 ∧ (s j (w j p x)).2.1 = (s j x).2.1) := by + let : ∀ j, Fintype (X j) := fun j => Fintype.ofFinite (X j) + let : ∀ j, Fintype (A j) := fun j => Fintype.ofFinite (A j) + let : ∀ j, Fintype (D j) := fun j => Fintype.ofFinite (D j) + have (j : J) : Finite (C j) := Finite.of_surjective (fun x => (s j x).1) (by + intro a + exact ⟨(s j).symm (a, (s j (Classical.arbitrary _)).2), by simp⟩) + let (j : J) : Fintype (C j) := Fintype.ofFinite _ + choose f hc he using fun j => H (h j) _ _ _ _ (s j) (e j) + obtain ⟨d, hd⟩ := hg + choose f' hc' he' using hd + have hy (j) (p : Equiv.Perm (X j)) (x : X j) : + f' j (pack (e j) p) (e j x) = e j (g j p x) := by + rw [he'] + exact Equiv.Perm.viaEmbedding_apply _ _ _ + choose u v w heq hu hv hw hu' hv' hw' using + fun j p => he j (g j p) (hf j p) _ (hy j p) + have hb (j) := (hc' j).comp (hc j) + refine ⟨u, v, w, ?_, ?_, ?_, funext (fun j => funext (heq j)), hu, hv, hw⟩ + · exact efficient_of_on (fun j => ⟨_, (hb j).fst, hu' j⟩) + · exact efficient_of_on (fun j => ⟨_, (hb j).snd.fst, hv' j⟩) + · exact efficient_of_on (fun j => ⟨_, (hb j).snd.snd, hw' j⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryJets.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryJets.lean new file mode 100644 index 0000000000..b7b3ce3a19 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryJets.lean @@ -0,0 +1,941 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Polynomial.Roots +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Algebra.Polynomial.Taylor +public import Mathlib.LinearAlgebra.Dual.Lemmas +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryTerms +public import Mathlib.Algebra.Module.Basic +public import Mathlib.Algebra.Polynomial.AlgebraMap +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Block +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import Mathlib.Algebra.Polynomial.Expand +public import Mathlib.RingTheory.AdjoinRoot + +/-! +# Selecting fusion terms by a common functional + +After clearing poles a family is a polynomial of degree at most `N`. +The order at infinity is then `N - P.natDegree`. A single functional +annihilating the span of cheap tensors keeps the total order of the +first surviving coefficients over all collision charts at most `N`. +Energies are recorded in half-integer units. +-/ + +@[expose] public section + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset Polynomial + +variable {F B : Type*} [Field F] + +open scoped Classical in +/-- In the case `none`, this construction gives `lcoeff F (N - i)`. -/ +def jetAt (N : ℕ) (d : Option F) (i : ℕ) : F[X] →ₗ[F] F := + match d with + | none => lcoeff F (N - i) + | some s => (lcoeff F i).comp (taylor (-s)) + +open scoped Classical in +private def firstOrder (N : ℕ) (P : F[X]) : Option F → ℕ + | none => N - P.natDegree + | some s => P.rootMultiplicity (-s) + +open scoped Classical in +private theorem jet_first (P : F[X]) {N : ℕ} (hP : P ≠ 0) (hN : P.natDegree ≤ N) + (d : Option F) : jetAt N d (firstOrder N P d) P ≠ 0 := by + cases d with + | none => + change P.coeff (N - (N - P.natDegree)) ≠ 0 + rw [Nat.sub_sub_self hN, coeff_natDegree] + exact leadingCoeff_ne_zero.mpr hP + | some s => + change ((taylor (-s)) P).coeff (P.rootMultiplicity (-s)) ≠ 0 + rw [rootMultiplicity_eq_natTrailingDegree, ← taylor_apply, coeff_natTrailingDegree_ne_zero] + simpa using hP + +open scoped Classical in +private theorem sum_first (P : F[X]) {N : ℕ} (hN : P.natDegree ≤ N) + (D : Finset (Option F)) : ∑ d ∈ D, firstOrder N P d ≤ N := by + have hs : D ⊆ insertNone (eraseNone D) := by + intro d hd + cases d <;> simp [hd] + let S := (eraseNone D).image Neg.neg + have h : ∑ z ∈ S, P.roots.count z ≤ P.natDegree := calc + _ ≤ ∑ z ∈ S ∪ P.roots.toFinset, P.roots.count z := sum_le_sum_of_subset subset_union_left + _ = P.roots.card := Multiset.sum_count_eq_card (fun _ hz + => mem_union_right _ (Multiset.mem_toFinset.mpr hz)) + _ ≤ _ := card_roots' _ + rw [show S = _ from rfl, sum_image neg_injective.injOn] at h + simp_rw [count_roots] at h + apply le_trans (sum_le_sum_of_subset hs) + rw [sum_insertNone] + change N - P.natDegree + (∑ z ∈ eraseNone D, P.rootMultiplicity (-z)) ≤ N + omega + +variable [Fintype B] + +open scoped Classical in +omit [Fintype B] in +private theorem scalarize [Finite B] (f : (B → F) →ₗ[F] F) (P : B → F[X]) {N : ℕ} + (hn : ∀ b, (P b).natDegree ≤ N) : + ∃ Q : F[X], Q.natDegree ≤ N ∧ ∀ g : F[X] →ₗ[F] F, g Q = f (fun b => g (P b)) := by + let : Fintype B := Fintype.ofFinite B + let c (b : B) := f (Pi.single b 1) + refine ⟨∑ b, c b • P b, ?_, fun g => ?_⟩ + · refine natDegree_sum_le_of_forall_le _ _ fun b _ => ?_ + exact (natDegree_smul_le _ _).trans (hn b) + rw [map_sum, ← univ_sum_single (fun b => g (P b)), map_sum] + refine sum_congr rfl fun b _ => ?_ + rw [map_smul, smul_eq_mul, mul_comm, ← smul_eq_mul] + dsimp only [c] + rw [← map_smul, ← Pi.single_smul, smul_eq_mul, mul_one] + +open scoped Classical in +omit [Fintype B] in +/-- Each local jet lies in the span of candidates costing at most twice +its order. If one value survives modulo `W`, select a surviving candidate +in every chart with a *joint* budget of twice the degree bound. -/ +theorem select_fusions [Finite B] {T : Option F → Type*} [∀ d, Nonempty (T d)] + (D : Finset (Option F)) (P : B → F[X]) (N : ℕ) + (term : ∀ d, T d → B → F) (cost : ∀ d, T d → ℕ) + (hn : ∀ b, (P b).natDegree ≤ N) + (hjet : ∀ d ∈ D, ∀ i ≤ N, (fun b => jetAt N d i (P b)) ∈ + Submodule.span F {v | ∃ t : T d, cost d t ≤ 2 * i ∧ term d t = v}) + (W : Submodule F (B → F)) (s : F) (he : (fun b => (P b).eval s) ∉ W) : + ∃ t : ∀ d, T d, (∀ d ∈ D, term d (t d) ∉ W) ∧ + ∑ d ∈ D, cost d (t d) ≤ 2 * N := by + let : Fintype B := Fintype.ofFinite B + have h := mt (Subspace.forall_mem_dualAnnihilator_apply_eq_zero_iff W _).mp he + push Not at h + obtain ⟨f, hf, hval⟩ := h + obtain ⟨Q, hN, hQ⟩ := scalarize f P hn + have hne : Q ≠ 0 := by + intro hz + apply hval + simpa [hz] using (hQ (leval s)).symm + have hsum := sum_first Q hN D + have ex (d : Option F) (hd : d ∈ D) : + ∃ t, cost d t ≤ 2 * firstOrder N Q d ∧ term d t ∉ W := by + have hm : firstOrder N Q d ≤ N := + (single_le_sum (fun _ _ => Nat.zero_le _) hd).trans hsum + by_contra! hall + have hw : (fun b => jetAt N d (firstOrder N Q d) (P b)) ∈ W := by + apply (Submodule.span_le.mpr ?_) (hjet d hd _ hm) + rintro _ ⟨t, ht, rfl⟩ + exact hall t ht + apply jet_first Q hne hN d + rw [hQ] + exact (Submodule.mem_dualAnnihilator f).mp hf _ hw + choose! t ht ht' using ex + refine ⟨t, ht', (sum_le_sum ht).trans ?_⟩ + rw [← mul_sum] + exact Nat.mul_le_mul_left _ hsum + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Secant widths and incidence energy + +The unit-mass transport inequality in the proof of the secant bound gives a +width for each line, with a bound on the sum of their squares. Transport along +a short segment, followed by squared distance comparison, lets us use those +widths directly, without introducing angles or first variation. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset + +variable {Y : Type*} [MetricSpace Y] + +/-- The transport bound controls the loss in the law of cosines, summed +over the points incident with a line. -/ +theorem secant_comparison {E : Type*} (C : Comparison Y) (S : Finset E) + (x : E → Y) (o z : Y) (b : ℝ) + (h : ∀ m : Y, (∑ i ∈ S, dist o (x i) ^ 2) ≤ + b * dist o m + ∑ i ∈ S, dist o (x i) * dist m (x i)) : + (∑ i ∈ S, dist o (x i) ^ 2) + S.card * dist o z ^ 2 ≤ + (∑ i ∈ S, dist (x i) z ^ 2) + 2 * b * dist o z := by + let B := (S.card : ℝ) * dist o z ^ 2 + have hB : 0 ≤ B := by positivity + apply le_of_forall_pos_le_add + intro ε hε + let t := min 1 (ε / (1 + B)) + have ht : 0 < t := lt_min zero_lt_one (by positivity) + have he : t * B ≤ ε := calc + _ ≤ t * (1 + B) := mul_le_mul_of_nonneg_left (by linarith) ht.le + _ ≤ ε := (le_div_iff₀ (by positivity)).mp (min_le_right _ _) + obtain ⟨m, hm, hcmp⟩ := C o z t ht.le (min_le_left _ _) + have hl := h m + rw [hm] at hl + have hu : ∑ i ∈ S, 2 * (dist o (x i) * dist m (x i)) ≤ + ∑ i ∈ S, ((2 - t) * dist o (x i) ^ 2 + t * dist (x i) z ^ 2 - + t * (1 - t) * dist o z ^ 2) := by + apply sum_le_sum + intro i _ + rw [dist_comm (x i) z] + nlinarith only [hcmp (x i), sq_nonneg (dist o (x i) - dist m (x i))] + simp only [sum_sub_distrib, sum_add_distrib, ← mul_sum, sum_const, nsmul_eq_mul] at hu + have hh : (∑ i ∈ S, dist o (x i) ^ 2) + B ≤ + (∑ i ∈ S, dist (x i) z ^ 2) + 2 * b * dist o z + t * B := by + refine le_of_mul_le_mul_left ?_ ht + dsimp [B] + linarith only [hu, hl] + exact hh.trans (add_le_add_right he _) + +variable {A L E : Type*} [Fintype L] [Fintype E] [DecidableEq L] + +/-- Raw sums over flags. In a biregular graph the normalized left hand +side uses the uniform distribution on each class of vertices. -/ +theorem incidence_of_widths (C : Comparison Y) (p : E → A) (l : E → L) + (x : A → Y) (y : L → Y) (o : Y) (b : L → ℝ) {s : ℕ} (hs : 0 < s) + (hc : ∀ k, #{i | l i = k} = s) + (transport : ∀ k m, (∑ i with l i = k, dist o (x (p i)) ^ 2) ≤ + b k * dist o m + ∑ i with l i = k, dist o (x (p i)) * dist m (x (p i))) + {t : ℝ} (ht : 0 ≤ t) + (budget : t ^ 2 * ∑ k, b k ^ 2 ≤ (s : ℝ) * ∑ i, dist o (x (p i)) ^ 2) : + (t - 1) * (∑ i, (dist o (x (p i)) ^ 2 + dist o (y (l i)) ^ 2)) ≤ + t * ∑ i, dist (x (p i)) (y (l i)) ^ 2 := by + have hs' : 0 < (s : ℝ) := Nat.cast_pos.mpr hs + have step (k : L) : + (s : ℝ) * ((t - 1) * + ∑ i with l i = k, (dist o (x (p i)) ^ 2 + dist o (y (l i)) ^ 2)) + + s * (∑ i with l i = k, dist o (x (p i)) ^ 2) ≤ + s * (t * ∑ i with l i = k, dist (x (p i)) (y (l i)) ^ 2) + t ^ 2 * b k ^ 2 := by + have eqn (f : E → L → ℝ) : + ∑ i with l i = k, f i (l i) = ∑ i with l i = k, f i k := + sum_congr rfl (fun i hi => congrArg (f i) (mem_filter.mp hi).2) + rw [eqn (fun i v => dist o (x (p i)) ^ 2 + dist o (y v) ^ 2), + eqn (fun i v => dist (x (p i)) (y v) ^ 2), sum_add_distrib, sum_const, hc, nsmul_eq_mul] + have h := secant_comparison C {i | l i = k} (fun i => x (p i)) o (y k) (b k) (transport k) + rw [hc] at h + linarith only [mul_le_mul_of_nonneg_left h (mul_nonneg hs'.le ht), + sq_nonneg ((s : ℝ) * dist o (y k) - t * b k)] + have htotal := sum_le_sum (s := univ) (fun k _ => step k) + simp only [sum_add_distrib, ← mul_sum, sum_fiberwise] at htotal + refine le_of_mul_le_mul_left ?_ hs' + rw [sum_add_distrib] + linarith only [htotal, budget] + +variable [Fintype A] + +/-- The fused widths on the retained lines, after dropping the nonnegative +contributions of omitted secants. Here `n + 1` counts *all* secants +through each point. This is the input from the spectral spaces argument. -/ +def SecantBound (p : E → A) (l : E → L) (x : A → Y) (o : Y) (n : ℕ) : Prop := + ∃ b : L → ℝ, (∑ k, b k ^ 2) ≤ n * ∑ a, dist o (x a) ^ 2 ∧ + ∀ k m, (∑ i with l i = k, dist o (x (p i)) ^ 2) ≤ + b k * dist o m + ∑ i with l i = k, dist o (x (p i)) * dist m (x (p i)) + +variable [DecidableEq A] + +theorem uniform_sum (p : E → A) {j : ℕ} (hp : ∀ a, #{i | p i = a} = j) (f : A → ℝ) : + ∑ i, f (p i) = j * ∑ a, f a := by + rw [← sum_fiberwise univ p, mul_sum] + refine sum_congr rfl fun a _ => ?_ + calc + _ = ∑ i with p i = a, f a := + sum_congr rfl (fun i hi => congrArg f (mem_filter.mp hi).2) + _ = _ := by rw [sum_const, hp, nsmul_eq_mul] + +/-- The projective degrees are `s = q+1`, `j = n+1`. For affine points +of order `Q` with `q+1` retained directions they are `s = n = Q`, +`j = q+1`. In both cases `q*n ≤ j*s`. -/ +theorem regular_incidence (C : Comparison Y) (p : E → A) (l : E → L) + (x : A → Y) (y : L → Y) (o : Y) {j s n q : ℕ} (hs : 0 < s) + (hp : ∀ a, #{i | p i = a} = j) (hl : ∀ k, #{i | l i = k} = s) + (hd : q * n ≤ j * s) (h : SecantBound p l x o n) : + (Real.sqrt q - 1) * (∑ i, (dist o (x (p i)) ^ 2 + dist o (y (l i)) ^ 2)) ≤ + Real.sqrt q * ∑ i, dist (x (p i)) (y (l i)) ^ 2 := by + obtain ⟨b, hb, htrans⟩ := h + apply incidence_of_widths C p l x y o b hs hl htrans (Real.sqrt_nonneg _) + rw [Real.sq_sqrt (Nat.cast_nonneg _), uniform_sum p hp (fun a => dist o (x a) ^ 2)] + calc + _ ≤ q * (n * ∑ a, dist o (x a) ^ 2) := mul_le_mul_of_nonneg_left hb (Nat.cast_nonneg _) + _ ≤ (j : ℝ) * s * (∑ a, dist o (x a) ^ 2) := by + rw [← mul_assoc] + exact mul_le_mul_of_nonneg_right (by exact_mod_cast hd) (by positivity) + _ = _ := by ring + +theorem incidence_bound (C : Comparison Y) (p : E → A) (l : E → L) + (x : A → Y) (y : L → Y) (o : Y) {j s n : ℕ} (hs : 0 < s) + (hp : ∀ a, #{i | p i = a} = j) (hl : ∀ k, #{i | l i = k} = s) + (hd : 100 * n ≤ j * s) (h : SecantBound p l x o n) : + 9 * (∑ i, (dist o (x (p i)) ^ 2 + dist o (y (l i)) ^ 2)) ≤ + 10 * ∑ i, dist (x (p i)) (y (l i)) ^ 2 := by + have e := regular_incidence C p l x y o hs hp hl hd h + have hr : Real.sqrt 100 = 10 := by + rw [show (100 : ℝ) = 10 ^ 2 by norm_num, Real.sqrt_sq (by norm_num)] + norm_num [hr] at e + exact e + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- A slope in the base field, or the vertical direction. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {K V : Type*} [Field K] [AddCommGroup V] [Module K V] + +/-- In the case `none`, this construction gives `a 0`. -/ +def projection (a : Fin 2 → V) : Option K → V + | none => a 0 + | some t => a 1 - t • a 0 + +/-- The value specified by `(i.2, projection i.1 i.2)`. -/ +def affineGraph (i : (Fin 2 → V) × Option K) : Option K × V := + (i.2, projection i.1 i.2) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- Finite arrangements of affine points and their secants. -/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset + +variable {F : Type*} [Field F] + +open scoped Classical in +/-- Returns `(none, a 0)` when `a 0 = b 0` holds, and `let d := (a 1 - b 1) / (a 0 - b 0) (some +d, a 1 - d * a 0)` otherwise. -/ +def through (a b : Fin 2 → F) : Option F × F := + if a 0 = b 0 then (none, a 0) + else + let d := (a 1 - b 1) / (a 0 - b 0) + (some d, a 1 - d * a 0) + +open scoped Classical in +theorem through_left (a b : Fin 2 → F) : + projection a (through a b).1 = (through a b).2 := by + unfold through + split <;> rfl + +open scoped Classical in +theorem through_right (a b : Fin 2 → F) : + projection b (through a b).1 = (through a b).2 := by + unfold through + split + · rename_i h + exact h.symm + · rename_i h + simp only [projection, smul_eq_mul] + linear_combination div_mul_cancel₀ (a 1 - b 1) (sub_ne_zero.mpr h) + +open scoped Classical in +theorem eq_through {a b : Fin 2 → F} {k : Option F × F} (h : a ≠ b) + (ha : projection a k.1 = k.2) (hb : projection b k.1 = k.2) : k = through a b := by + obtain ⟨_ | d, z⟩ := k + · change a 0 = z at ha + change b 0 = z at hb + simp [through, ha, hb] + · change a 1 - d * a 0 = z at ha + change b 1 - d * b 0 = z at hb + have h₀ : a 0 ≠ b 0 := by + intro he + rw [he] at ha + have h₁ := sub_left_inj.mp (ha.trans hb.symm) + apply h + funext i + fin_cases i <;> assumption + have hd : d = (a 1 - b 1) / (a 0 - b 0) := by + apply (eq_div_iff (sub_ne_zero.mpr h₀)).mpr + linear_combination hb - ha + simp [through, h₀, ← hd, ha] + +variable {A : Type*} [Fintype A] + +open scoped Classical in +/-- Indexes the secant lines by the coordinates of `({i : A × A | i.1 ≠ i.2} : Finset _).image +(fun i => through (a i.1) (a i.2))`. -/ +def secantLines (a : A → Fin 2 → F) : Finset (Option F × F) := + ({i : A × A | i.1 ≠ i.2} : Finset _).image (fun i => through (a i.1) (a i.2)) + +open scoped Classical in +theorem mem_secantLines {a : A → Fin 2 → F} (ha : Function.Injective a) (k : Option F × F) : + k ∈ secantLines a ↔ ∃ i j, i ≠ j ∧ projection (a i) k.1 = k.2 ∧ + projection (a j) k.1 = k.2 := by + constructor + · intro h + obtain ⟨⟨i, j⟩, hij, rfl⟩ := mem_image.mp h + exact ⟨i, j, (mem_filter.mp hij).2, through_left _ _, through_right _ _⟩ + · rintro ⟨i, j, hij, hi, hj⟩ + exact mem_image.mpr ⟨(i, j), mem_filter.mpr ⟨mem_univ _, hij⟩, + (eq_through (ha.ne hij) hi hj).symm⟩ + +open scoped Classical in +/-- Selects the elements of `(secantLines a)` satisfying `fun k => projection (a i) k.1 = k.2`. -/ +def pointSecants (a : A → Fin 2 → F) (i : A) : Finset (Option F × F) := + (secantLines a).filter fun k => projection (a i) k.1 = k.2 + +open scoped Classical in +/-- Unit-mass conclusion of the secant argument, expressed with the +transport bounds for fused widths. `n+1` bounds the number of secants +through each marked point. -/ +def Secants (F Y : Type*) [Field F] [MetricSpace Y] : Prop := + ∀ {A : Type} [Fintype A] (a : A → Fin 2 → F), Function.Injective a → + ∀ n : ℕ, (∀ i, (pointSecants a i).card ≤ n + 1) → + ∀ (x : A → Y) (o : Y), Bary x o → + ∃ b : Option F × F → ℝ, (∑ k ∈ secantLines a, b k ^ 2) ≤ n * ∑ i, dist o (x i) ^ 2 ∧ + ∀ k ∈ secantLines a, ∀ m : Y, (∑ i with projection (a i) k.1 = k.2, dist o (x i) ^ 2) ≤ + b k * dist o m + ∑ i with projection (a i) k.1 = k.2, dist o (x i) * dist m (x i) + +open scoped Classical in +theorem Secants.widths {A L E : Type} [Fintype A] [Fintype L] [Fintype E] [DecidableEq L] + {Y : Type*} [MetricSpace Y] (S : Secants F Y) + (a : A → Fin 2 → F) (k : L → Option F × F) + (ha : Function.Injective a) (hk : Function.Injective k) + {n : ℕ} (hn : ∀ i, (pointSecants a i).card ≤ n + 1) + (hmem : ∀ t, k t ∈ secantLines a) (p : E → A) (l : E → L) + (he : Function.Injective fun i => (p i, l i)) + (hi : ∀ j t, projection (a j) (k t).1 = (k t).2 ↔ ∃ i, p i = j ∧ l i = t) + (x : A → Y) (o : Y) (ho : Bary x o) : SecantBound p l x o n := by + obtain ⟨b, hb, ht⟩ := S a ha n hn x o ho + refine ⟨fun t => b (k t), ?_, fun t m => ?_⟩ + · refine le_trans ?_ hb + rw [← sum_image (s := univ) (f := fun q => b q ^ 2) hk.injOn] + exact sum_le_sum_of_subset_of_nonneg (image_subset_iff.mpr fun t _ => hmem t) + (fun _ _ _ => sq_nonneg _) + · have eqn (f : A → ℝ) : + ∑ i with l i = t, f (p i) = ∑ j with projection (a j) (k t).1 = (k t).2, f j := by + refine sum_bij (fun i _ => p i) ?_ ?_ ?_ (fun _ _ => rfl) + · exact fun i h => mem_filter.mpr ⟨mem_univ _, (hi _ _).mpr ⟨i, rfl, (mem_filter.mp h).2⟩⟩ + · exact fun i h j h' e => he (Prod.ext e ((mem_filter.mp h).2.trans (mem_filter.mp + h').2.symm)) + · intro j h + obtain ⟨i, hp, hl⟩ := (hi _ _).mp (mem_filter.mp h).2 + exact ⟨i, mem_filter.mpr ⟨mem_univ _, hl⟩, hp⟩ + rw [eqn (fun j => dist o (x j) ^ 2), eqn (fun j => dist o (x j) * dist m (x j))] + exact ht _ (hmem t) m + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Deleting singleton blocks + +The collision parameters are the secant directions and infinity. +For a singleton block testing its own site in the transport inequality +shows that its width pays at least the distance from the center. +-/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset + +variable {F Y : Type*} [Field F] [MetricSpace Y] {A : Type} [Fintype A] + +open scoped Classical in +/-- Computes the directions by the application `insert none ((secantLines a).image Prod.fst)`. -/ +def directions (a : A → Fin 2 → F) : Finset (Option F) := + insert none ((secantLines a).image Prod.fst) + +open scoped Classical in +/-- The indexed operation `(directions a ×ˢ univ).image (fun i => (i.1, projection (a i.2) +i.1))`. -/ +def blocks (a : A → Fin 2 → F) : Finset (Option F × F) := + (directions a ×ˢ univ).image (fun i => (i.1, projection (a i.2) i.1)) + +open scoped Classical in +/-- Uses `{i | projection (a i) k.1 = k.2}` as the representation. -/ +def pointsOn (a : A → Fin 2 → F) (k : Option F × F) : Finset A := + {i | projection (a i) k.1 = k.2} + +open scoped Classical in +theorem mem_blocks {a : A → Fin 2 → F} {k : Option F × F} : + k ∈ blocks a ↔ k.1 ∈ directions a ∧ (pointsOn a k).Nonempty := by + constructor + · intro hk + obtain ⟨⟨d, i⟩, hd, rfl⟩ := mem_image.mp hk + exact ⟨(mem_product.mp hd).1, i, mem_filter.mpr ⟨mem_univ _, rfl⟩⟩ + · rintro ⟨hd, i, hi⟩ + exact mem_image.mpr ⟨(k.1, i), mem_product.mpr ⟨hd, mem_univ _⟩, + Prod.ext rfl (mem_filter.mp hi).2⟩ + +open scoped Classical in +theorem secants_subset_blocks (a : A → Fin 2 → F) (ha : Function.Injective a) : + secantLines a ⊆ blocks a := by + intro k hk + obtain ⟨i, _, _, hi, _⟩ := (mem_secantLines ha k).mp hk + exact mem_blocks.mpr ⟨mem_insert_of_mem (mem_image_of_mem Prod.fst hk), + i, mem_filter.mpr ⟨mem_univ i, hi⟩⟩ + +open scoped Classical in +private theorem blocks_per_point (a : A → Fin 2 → F) (i : A) : + #((blocks a).filter (fun k => projection (a i) k.1 = k.2)) = (directions a).card := by + let f (d : Option F) := (d, projection (a i) d) + have hf : Function.Injective f := fun _ _ e => congrArg Prod.fst e + rw [← card_image_of_injective _ hf] + congr 1 + ext k + simp only [mem_filter, mem_image] + constructor + · rintro ⟨hk, hi⟩ + exact ⟨k.1, (mem_blocks.mp hk).1, Prod.ext rfl hi⟩ + · rintro ⟨d, hd, rfl⟩ + exact ⟨mem_blocks.mpr ⟨hd, i, mem_filter.mpr ⟨mem_univ _, rfl⟩⟩, rfl⟩ + +open scoped Classical in +private theorem total_on_lines (a : A → Fin 2 → F) (r : A → ℝ) + (s : Finset (Option F × F)) : + ∑ k ∈ s, ∑ i ∈ pointsOn a k, r i = + ∑ i, #({k ∈ s | projection (a i) k.1 = k.2}) * r i := by + unfold pointsOn + simp_rw [sum_filter] + rw [sum_comm] + refine sum_congr rfl fun i _ => ?_ + rw [← sum_filter, sum_const, nsmul_eq_mul] + +open scoped Classical in +/-- Input from the rational-function fusion argument for sphere forms. +Finite collision parameters use the negative of the slope. -/ +def CollisionBound (F Y : Type*) [Field F] [MetricSpace Y] : Prop := + ∀ {A : Type} [Fintype A] (a : A → Fin 2 → F), Function.Injective a → 1 < Fintype.card A → + ∀ (x : A → Y) (o : Y), Bary x o → + ∃ b : Option F × F → ℝ, + (∑ k ∈ blocks a, b k ^ 2) ≤ ((directions a).card - 1 : ℝ) * ∑ i, dist o (x i) ^ 2 ∧ + ∀ k ∈ blocks a, ∀ m : Y, (∑ i ∈ pointsOn a k, dist o (x i) ^ 2) ≤ + b k * dist o m + ∑ i ∈ pointsOn a k, dist o (x i) * dist m (x i) + +open scoped Classical in +theorem CollisionBound.secants (H : CollisionBound F Y) : Secants F Y := by + intro A _ a ha n hn x o ho + rcases (secantLines a).eq_empty_or_nonempty with hempty | ⟨k, hk⟩ + · refine ⟨fun _ => 0, ?_, ?_⟩ + · rw [hempty, sum_empty] + positivity + · simp [hempty] + obtain ⟨i, j, hij, _⟩ := (mem_secantLines ha k).mp hk + have hcard : 1 < Fintype.card A := one_lt_card.mpr ⟨i, mem_univ _, j, mem_univ _, hij⟩ + obtain ⟨b, hbudget, ht⟩ := H a ha hcard x o ho + have hsub := secants_subset_blocks a ha + refine ⟨b, ?_, fun k hk => ht k (hsub hk)⟩ + let r (i : A) := dist o (x i) ^ 2 + let mass (k : Option F × F) := ∑ i ∈ pointsOn a k, r i + have hall : ∑ k ∈ blocks a, mass k = (directions a).card * ∑ i, r i := by + simp [mass, total_on_lines, blocks_per_point, ← mul_sum] + have hsec : ∑ k ∈ secantLines a, mass k ≤ ((n : ℝ) + 1) * ∑ i, r i := by + simp only [mass, total_on_lines, mul_sum] + refine sum_le_sum fun i _ => mul_le_mul_of_nonneg_right ?_ (sq_nonneg _) + exact_mod_cast hn i + have hsing : ∑ k ∈ blocks a \ secantLines a, mass k ≤ + ∑ k ∈ blocks a \ secantLines a, b k ^ 2 := by + refine sum_le_sum fun k hk => ?_ + obtain ⟨hb, hs⟩ := mem_sdiff.mp hk + obtain ⟨i, hi⟩ := (mem_blocks.mp hb).2 + have he : pointsOn a k = {i} := by + refine eq_singleton_iff_unique_mem.mpr ⟨hi, fun j hj => ?_⟩ + by_contra hne + exact hs ((mem_secantLines ha k).mpr ⟨j, i, hne, (mem_filter.mp hj).2, (mem_filter.mp hi).2⟩) + have hc := ht k hb (x i) + simp only [he, sum_singleton, dist_self, mul_zero, add_zero] at hc + simp only [mass, he, sum_singleton, r] + nlinarith only [hc, sq_nonneg (b k - dist o (x i))] + rw [← sum_sdiff hsub] at hall hbudget + change _ ≤ (n : ℝ) * ∑ i, r i + change _ ≤ _ * ∑ i, r i at hbudget + linarith only [hall, hsec, hsing, hbudget] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Clearing all poles of the moving sphere form + +A marked point (a,b) has moving position aX+bY. For each +pair of points remove its vanishing linear factor from the common +denominator. This gives a polynomial contraction kernel and works +over any coefficient algebra, including truncated local rings. +-/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset Polynomial Sphere + +variable {F R : Type*} [Field F] [CommRing R] [Algebra F R] +variable {A : Type} [Fintype A] {r : ℕ} + +open scoped Classical in +/-- In the case `none`, this construction gives `Y`. -/ +def linearFactor (X Y : R) : Option F → R + | none => Y + | some s => X + algebraMap F R s * Y + +open scoped Classical in +/-- In the case `none`, this construction gives `a 1`. -/ +def collisionOffset (a : Fin 2 → F) : Option F → F + | none => a 1 + | some _ => a 0 + +open scoped Classical in +/-- The quantity computed by `algebraMap F R (a 0) * X + algebraMap F R (a 1) * Y`. -/ +def position (a : Fin 2 → F) (X Y : R) : R := + algebraMap F R (a 0) * X + algebraMap F R (a 1) * Y + +open scoped Classical in +/-- The product of `linearFactor X Y d` indexed by `d ∈ D`. -/ +def denominator (D : Finset (Option F)) (X Y : R) : R := + ∏ d ∈ D, linearFactor X Y d + +open scoped Classical in +/-- The value specified by `(through a b).1`. -/ +def pole (a b : Fin 2 → F) := (through a b).1 + +open scoped Classical in +/-- The reciprocal poly of type `R`, constructed using `pole a b`. -/ +def reciprocalPoly (D : Finset (Option F)) (a b : Fin 2 → F) (X Y : R) : R := + let d := pole a b + algebraMap F R (collisionOffset b d - collisionOffset a d)⁻¹ * denominator (D.erase d) X Y + +open scoped Classical in +/-- Computes the polynomial kernel by the application `Sphere.coeff i.2 j.2 (reciprocalPoly +(directions a) (a i.1) (a j.1) X Y)`. -/ +def polynomialKernel (a : A → Fin 2 → F) (X Y : R) (i j : A × Mode r) : R := + Sphere.coeff i.2 j.2 (reciprocalPoly (directions a) (a i.1) (a j.1) X Y) + +open scoped Classical in +/-- Computes the correlator poly by the application `wick (polynomialKernel a X Y) xs`. -/ +def correlatorPoly (a : A → Fin 2 → F) (X Y : R) (xs : List (A × Mode r)) : R := + wick (polynomialKernel a X Y) xs + +open scoped Classical in +private theorem pole_comm (a b : Fin 2 → F) : pole b a = pole a b := by + by_cases h : a = b + · rw [h] + exact congrArg Prod.fst (eq_through h (through_right b a) (through_left b a)) + +open scoped Classical in +theorem polynomial_skew (a : A → Fin 2 → F) (x y : A × Mode r) : + polynomialKernel a (Polynomial.X : Polynomial F) 1 y x = + -polynomialKernel a Polynomial.X 1 x y := by + unfold polynomialKernel reciprocalPoly + rw [pole_comm (a x.1) (a y.1)] + dsimp only + rw [← neg_sub (collisionOffset (a y.1) _) (collisionOffset (a x.1) _), inv_neg, map_neg, neg_mul, + coeff_skew] + +open scoped Classical in +theorem pole_mem (a : A → Fin 2 → F) (i j : A) : pole (a i) (a j) ∈ directions a := by + by_cases h : i = j + · simp [h, pole, through, directions] + · exact mem_insert_of_mem (mem_image_of_mem Prod.fst + (mem_image.mpr ⟨(i, j), mem_filter.mpr ⟨mem_univ _, h⟩, rfl⟩)) + +open scoped Classical in +private theorem form_factor (d : Option F) : + BinaryForm 1 (linearFactor (X : F[X]) 1 d) (linearFactor 1 X d) := by + cases d with + | none => simp [linearFactor, BinaryForm, reflect_one] + | some s => + simp [linearFactor, BinaryForm, reflect_add, reflect_C] + +open scoped Classical in +private theorem form_denominator (D : Finset (Option F)) : + BinaryForm D.card (denominator D (X : F[X]) 1) (denominator D 1 X) := by + induction D using Finset.induction_on with + | empty => simpa [denominator] using BinaryForm.const (1 : F) + | @insert d D hd ih => + simpa [denominator, hd, Nat.add_comm] using (form_factor d).mul ih + +open scoped Classical in +theorem correlator_form (a : A → Fin 2 → F) (xs : List (A × Mode r)) : + BinaryForm (((directions a).card - 1) * (weight xs / 2)) + (correlatorPoly a (X : F[X]) 1 xs) (correlatorPoly a 1 X xs) := by + apply wick_form + intro i j + let D := directions a + let d := pole (a i.1) (a j.1) + let c := (collisionOffset (a j.1) d - collisionOffset (a i.1) d)⁻¹ + have hr := (BinaryForm.const c).mul (form_denominator (D.erase d)) + rw [zero_add, card_erase_of_mem (pole_mem a _ _)] at hr + unfold polynomialKernel Sphere.coeff + split + · have ht := (BinaryForm.const + ((-1 : F) ^ j.2.2 * (i.2.2 + j.2.2).choose j.2.2)).mul (hr.pow (i.2.2 + j.2.2 + 1)) + simpa [reciprocalPoly, c, d, D] using ht + · exact BinaryForm.zero _ + +open scoped Classical in +theorem correlator_map {S : Type*} [CommRing S] [Algebra F S] (f : R →ₐ[F] S) + (a : A → Fin 2 → F) (X Y : R) (xs : List (A × Mode r)) : + f (correlatorPoly a X Y xs) = correlatorPoly a (f X) (f Y) xs := by + have hf (d : Option F) : f (linearFactor X Y d) = linearFactor (f X) (f Y) d := by + cases d <;> simp [linearFactor] + unfold correlatorPoly + change f.toRingHom (wick _ _) = _ + rw [wick_hom] + apply wick_eq_on + intro i _ j _ + change f (polynomialKernel a X Y i j) = _ + simp only [polynomialKernel, Sphere.coeff] + split <;> simp [reciprocalPoly, denominator, hf] + +open scoped Classical in +private theorem offset_ne (a b : Fin 2 → F) (h : a ≠ b) : + collisionOffset b (pole a b) - collisionOffset a (pole a b) ≠ 0 := by + by_cases h₀ : a 0 = b 0 + · have h₁ : a 1 ≠ b 1 := by + intro he + apply h + funext j + fin_cases j <;> assumption + simpa [collisionOffset, pole, through, h₀] using sub_ne_zero.mpr h₁.symm + · simpa [collisionOffset, pole, through, h₀] using sub_ne_zero.mpr (Ne.symm h₀) + +open scoped Classical in +private theorem factorization (a b : Fin 2 → F) (X Y : R) : + let d := pole a b + position b X Y - position a X Y = + algebraMap F R (collisionOffset b d - collisionOffset a d) * linearFactor X Y d := by + have eq : projection b (pole a b) = projection a (pole a b) := + (through_right a b).trans (through_left a b).symm + generalize pole a b = d at * + cases d with + | none => + change b 0 = a 0 at eq + simp only [collisionOffset, position, linearFactor, map_sub, eq] + ring + | some s => + change b 1 - s * b 0 = a 1 - s * a 0 at eq + have e := congrArg (algebraMap F R) eq + simp only [map_sub, map_mul] at e + simp only [collisionOffset, position, linearFactor, map_sub] + linear_combination Y * e + +open scoped Classical in +private theorem reciprocal_mul (D : Finset (Option F)) (a b : Fin 2 → F) (X Y : R) + (h : a ≠ b) (hd : pole a b ∈ D) : + reciprocalPoly D a b X Y * (position b X Y - position a X Y) = denominator D X Y := by + rw [factorization] + unfold reciprocalPoly + dsimp only + rw [mul_mul_mul_comm, ← map_mul, inv_mul_cancel₀ (offset_ne a b h), map_one, one_mul] + exact prod_erase_mul _ _ hd + +open scoped Classical in +private theorem coeff_scale (x y : Mode r) (u v : R) : + Sphere.coeff x y (u * v) = u ^ (x.2 + y.2 + 1) * Sphere.coeff x y v := by + unfold Sphere.coeff + split <;> simp [mul_pow, mul_left_comm, mul_assoc] + +open scoped Classical in +theorem correlator_specialize {E : Type*} [Field E] [Algebra F E] (a : A → Fin 2 → F) (X Y : E) + (hD : denominator (directions a) X Y ≠ 0) (xs : List (A × Mode r)) : + correlatorPoly a X Y xs = denominator (directions a) X Y ^ (weight xs / 2) * + wick (fun i j => fieldKernel (position (a i.1) X Y, i.2) (position (a j.1) X Y, j.2)) xs := by + rw [← wick_scale_energy] + unfold correlatorPoly + apply wick_eq_on + intro i _ j _ + unfold polynomialKernel fieldKernel + rw [← coeff_scale] + congr 1 + by_cases h : a i.1 = a j.1 + · simp [h, reciprocalPoly] + · have hm := reciprocal_mul (directions a) _ _ X Y h (pole_mem a _ _) + have hn : position (a j.1) X Y - position (a i.1) X Y ≠ 0 := by + intro hz + exact hD (by rw [← hm, hz, mul_zero]) + exact (eq_mul_inv_iff_mul_eq₀ hn).mpr hm + +open scoped Classical in +/-- In the case `none`, this construction gives `1`. -/ +def localX (z : R) : Option F → R + | none => 1 + | some d => z - algebraMap F R d + +open scoped Classical in +/-- In the case `none`, this construction gives `z`. -/ +def localY (z : R) : Option F → R + | none => z + | some _ => 1 + +open scoped Classical in +theorem local_position (a : Fin 2 → F) (d : Option F) (z : R) : + position a (localX z d) (localY z d) = + algebraMap F R (projection a d) + z * algebraMap F R (collisionOffset a d) := by + cases d <;> simp [position, projection, localX, localY, collisionOffset] <;> ring + +open scoped Classical in +private theorem shifted_inverse (u : R) (N : ℕ) (hu : u ^ N = 0) (δ Δ : F) (h : Δ ≠ 0) : + (algebraMap F R Δ + u ^ 2 * algebraMap F R δ) * + shifted u (algebraMap F R Δ⁻¹) (algebraMap F R (-δ)) N = 1 := by + have he : algebraMap F R Δ⁻¹ * algebraMap F R Δ = 1 := by + rw [← map_mul, inv_mul_cancel₀ h, map_one] + rw [mul_comm, show algebraMap F R Δ + u ^ 2 * algebraMap F R δ = + (1 - algebraMap F R (-δ) * u ^ 2 * algebraMap F R Δ⁻¹) * algebraMap F R Δ by + rw [sub_mul, mul_assoc _ (algebraMap F R Δ⁻¹), he, map_neg] + ring, ← mul_assoc, shifted_mul _ _ _ N hu, he] + +open scoped Classical in +private theorem local_reciprocal (D : Finset (Option F)) (a b : Fin 2 → F) + (d : Option F) (hd : d ∈ D) (hp : pole a b ∈ D) (u : R) (N : ℕ) (hu : u ^ N = 0) : + let X := localX (u ^ 2) d + let Y := localY (u ^ 2) d + let Δ := projection b d - projection a d + let δ := collisionOffset b d - collisionOffset a d + reciprocalPoly D a b X Y = denominator (D.erase d) X Y * + (if Δ = 0 then algebraMap F R δ⁻¹ + else u ^ 2 * shifted u (algebraMap F R Δ⁻¹) (algebraMap F R (-δ)) N) := by + intro X Y Δ δ + by_cases he : a = b + · simp [he, reciprocalPoly, Δ, δ] + by_cases h : Δ = 0 + · rw [ite_eq_left h] + have hpole : d = pole a b := congrArg Prod.fst + (eq_through (k := (d, projection a d)) he rfl (sub_eq_zero.mp h)) + simp [reciprocalPoly, ← hpole, δ, mul_comm] + · rw [ite_eq_right h] + have eq : position b X Y - position a X Y = + algebraMap F R Δ + u ^ 2 * algebraMap F R δ := by + simp only [X, Y, Δ, δ, local_position, map_sub] + ring + have hm := reciprocal_mul D a b X Y he hp + rw [eq, show denominator D X Y = denominator (D.erase d) X Y * u ^ 2 by + rw [denominator, ← prod_erase_mul D _ hd] + congr 1 + cases d <;> simp [linearFactor, X, Y, localX, localY]] at hm + rw [← mul_assoc, ← hm, mul_assoc, shifted_inverse u N hu _ _ h, mul_one] + +open scoped Classical in +/-- After factoring a common scalar, the local polynomial is the +normalized motion kernel at every finite order. -/ +theorem local_correlator (a : A → Fin 2 → F) (d : Option F) (hd : d ∈ directions a) + (u : R) (N : ℕ) (hu : u ^ N = 0) (xs : List (A × Mode r)) : + let X := localX (u ^ 2) d + let Y := localY (u ^ 2) d + correlatorPoly a X Y xs = denominator ((directions a).erase d) X Y ^ (weight xs / 2) * + wick (clusterKernel u N (fun i => projection (a i) d) (fun i => collisionOffset (a i) d)) xs + := by + intro X Y + rw [← wick_scale_energy] + unfold correlatorPoly + apply wick_eq_on + intro i _ j _ + unfold polynomialKernel clusterKernel + rw [local_reciprocal (directions a) _ _ d hd (pole_mem a _ _) u N hu, coeff_scale] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- Reading polynomial coefficients from truncated local fusion identities. -/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Polynomial Sphere Finset + +variable {F : Type*} [Field F] {A : Type} [Fintype A] {r : ℕ} + +open scoped Classical in +private theorem jet_local (a : A → Fin 2 → F) (d : Option F) (xs : List (A × Mode r)) + {i N : ℕ} (hi : i ≤ N) (hN : ((directions a).card - 1) * (weight xs / 2) = N) : + jetAt N d i (correlatorPoly a (X : F[X]) 1 xs) = + (correlatorPoly a (localX (X ^ 2 : F[X]) d) (localY (X ^ 2) d) xs).coeff (2 * i) := by + have he := correlator_map (expand F 2) a (localX (X : F[X]) d) (localY X d) xs + have he' : expand F 2 (correlatorPoly a (localX (X : F[X]) d) (localY X d) xs) = + correlatorPoly a (localX (X ^ 2 : F[X]) d) (localY (X ^ 2) d) xs := by + cases d <;> simpa [localX, localY] using he + rw [← he', coeff_expand_mul' (by decide : 0 < 2)] + cases d with + | none => + change _ = (correlatorPoly a 1 X xs).coeff i + rw [← (correlator_form a xs).2, hN, coeff_reflect, revAt_le hi] + rfl + | some s => + change ((taylor (-s)) (correlatorPoly a X 1 xs)).coeff i = _ + have hc := correlator_map (aeval (X - C s)) a X 1 xs + simp only [aeval_X, map_one] at hc + rw [taylor_apply, map_neg, ← sub_eq_add_neg] + exact congrArg (fun P : F[X] => P.coeff i) hc + +open scoped Classical in +/-- The quantity computed by `AdjoinRoot (X ^ M : F[X])`. -/ +abbrev JetRing (F : Type*) [Field F] (M : ℕ) := AdjoinRoot (X ^ M : F[X]) +open scoped Classical in +/-- The quantity computed by `AdjoinRoot.mk (X ^ M) X`. -/ +def jetVar (F : Type*) [Field F] (M : ℕ) : JetRing F M := AdjoinRoot.mk (X ^ M) X + +open scoped Classical in +theorem jetVar_pow (F : Type*) [Field F] (M : ℕ) : jetVar F M ^ M = 0 := by + rw [jetVar, ← map_pow, AdjoinRoot.mk_eq_zero] + +open scoped Classical in +private theorem jetRing_coeff {M i : ℕ} (hi : i < M) (P Q : F[X]) + (h : AdjoinRoot.mkₐ (X ^ M) P = AdjoinRoot.mkₐ (X ^ M) Q) : P.coeff i = Q.coeff i := by + have e := X_pow_dvd_iff.mp (AdjoinRoot.mk_eq_mk.mp h) i hi + rwa [coeff_sub, sub_eq_zero] at e + +variable {B T : Type*} [Fintype T] + +open scoped Classical in +/-- The same scalar multiplies all coordinates, so after clearing the +denominator the jet still lies in the span of low energy terms. -/ +theorem jets_of_fusion (a : A → Fin 2 → F) (xs : B → List (A × Mode r)) + (d : Option F) (hd : d ∈ directions a) (H N M : ℕ) + (hw : ∀ b, weight (xs b) / 2 = H) (hN : ((directions a).card - 1) * H = N) + (hM : 2 * N < M) (term : T → B → F) (cost : T → ℕ) + (hf : ∀ b, wick (clusterKernel (jetVar F M) M + (fun i => projection (a i) d) (fun i => collisionOffset (a i) d)) (xs b) = + ∑ t, jetVar F M ^ cost t * algebraMap F (JetRing F M) (term t b)) + (i : ℕ) (hi : i ≤ N) : + (fun b => jetAt N d i (correlatorPoly a (X : F[X]) 1 (xs b))) ∈ + Submodule.span F {v | ∃ t, cost t ≤ 2 * i ∧ term t = v} := by + let f := AdjoinRoot.mkₐ (X ^ M : F[X]) + let u := jetVar F M + let x := localX (X ^ 2 : F[X]) d + let y := localY (X ^ 2 : F[X]) d + let Q := denominator ((directions a).erase d) x y ^ H + have hX : f X = u := rfl + have hC (z : F) : f (C z) = AdjoinRoot.of (X ^ M) z := rfl + have hx : f x = localX (u ^ 2) d := by cases d <;> simp [x, localX, hX, hC] + have hy : f y = localY (u ^ 2) d := by cases d <;> simp [y, localY, hX] + have hq : f Q = denominator ((directions a).erase d) (localX (u ^ 2) d) (localY (u ^ 2) d) ^ H + := by + have hl (k : Option F) : f (linearFactor x y k) = linearFactor (f x) (f y) k := by + cases k <;> simp [linearFactor, hC] + simp only [Q, denominator, map_pow, map_prod, hl, hx, hy] + have he (b : B) : f (correlatorPoly a x y (xs b)) = + f (∑ t, Q * X ^ (cost t) * C (term t b)) := by + rw [correlator_map, hx, hy, local_correlator a d hd u M (jetVar_pow F M), hw, hf b, + ← hq, mul_sum, map_sum] + refine sum_congr rfl fun t _ => ?_ + rw [map_mul, map_mul, map_pow f X, hX, mul_assoc] + rfl + have eqn : (fun b => jetAt N d i (correlatorPoly a (X : F[X]) 1 (xs b))) = + ∑ t, (Q * X ^ (cost t)).coeff (2 * i) • term t := by + funext b + rw [jet_local a d (xs b) hi (by rw [hw, hN]), jetRing_coeff (by omega : 2 * i < M) _ _ (he b)] + simp only [finsetSum_coeff, coeff_mul_C, Finset.sum_apply, Pi.smul_apply, smul_eq_mul] + rw [eqn] + refine Submodule.sum_mem _ fun t _ => ?_ + by_cases h : cost t ≤ 2 * i + · exact Submodule.smul_mem _ _ (Submodule.subset_span ⟨t, h, rfl⟩) + · rw [coeff_mul_X_pow', ite_eq_right h, zero_smul] + exact Submodule.zero_mem _ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryPrices.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryPrices.lean new file mode 100644 index 0000000000..9ca25da8ca --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryPrices.lean @@ -0,0 +1,927 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Partitions +public import Mathlib.Algebra.Group.Subgroup.Pointwise +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Finite + +/-! +# Local tensor price test + +The tuple is allowed to repeat sites. Placement groups the +corresponding legs and gives unused sites trivial legs. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral + +/-- The passes of type `Prop` for the given inputs. -/ +def Passes {K S I : Type} [Field K] [Fintype S] [DecidableEq S] [DecidableEq I] + (A : Finset (Tensor K S)) (B : Finset I) (c : I → I → Prop) + (i j : I) (v : ℝ) (x : (S → I) → Tensor K S → ℝ) (ρ : ℝ) + (P : Tensor K B → ℝ) : Prop := + (∀ a b : B, a.val = i → b.val = j → |v - P (Tensor.wire K a b 2)| ≤ ρ) ∧ + (∀ a b : B, c a.val b.val → P (Tensor.wire K a b 2) ≤ 1 + ρ) ∧ + ∀ z : S → B, ∀ u ∈ A, |x (Subtype.val ∘ z) u - P (Tensor.place z u)| ≤ ρ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Finitely many constraints detect large displacement + +Compactness is used on the table of squared distances itself. A +counterexample satisfying every constraint gives a complete geometric +action by metric completion. This avoids choosing an ultrafilter on +permutation inputs. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators +open Set + +variable {G : Type} + +open scoped Classical in +private abbrev Distances (G : Type) := Term G → Term G → ℝ + +open scoped Classical in +private theorem closed_table : IsClosed {R : Distances G | Table R} := by + simp only [Table, ofPred_and, ofPred_forall] + refine (isClosed_iInter fun _ => isClosed_iInter fun _ => ?_).inter + ((isClosed_iInter fun _ => ?_).inter + ((isClosed_iInter fun _ => isClosed_iInter fun _ => ?_).inter + ((isClosed_iInter fun _ => isClosed_iInter fun _ => isClosed_iInter fun _ => ?_).inter + (isClosed_iInter fun _ => isClosed_iInter fun _ => isClosed_iInter fun _ => + isClosed_iInter fun _ => ?_)))) + all_goals first | exact isClosed_le (by fun_prop) (by fun_prop) + | exact isClosed_eq (by fun_prop) (by fun_prop) + +open scoped Classical in +private theorem closed_tests {E A B : Type} [Fintype E] [Fintype A] (p : E → A) (l : E → B) : + IsClosed {R : Distances G | Tests R Term.seg p l} := by + simp only [Tests, ofPred_forall] + refine isClosed_iInter fun _ => isClosed_iInter fun _ => isClosed_iInter fun _ => + isClosed_iInter fun _ => isClosed_iInter fun _ => isClosed_iInter fun _ => ?_ + simp only [joint, Fintype.expect_eq_sum_div_card] + exact isClosed_le (by fun_prop) (by fun_prop) + +open scoped Classical in +/-- Extract a uniform tolerance and a finite menu of continuous tests. -/ +private theorem compact_tests {X I : Type} [TopologicalSpace X] {S : Set X} + (hs : IsCompact S) (f : I → X → ℝ) (hc : ∀ i, Continuous (f i)) + (hf : ∀ x ∈ S, ∃ i, 0 < f i x) : + ∃ t : Finset I, ∃ δ : ℝ, 0 < δ ∧ ∀ x ∈ S, ∃ i ∈ t, δ < f i x := by + let U (a : I × {t : ℝ // 0 < t}) := {x | a.2.val < f a.1 x} + have ho (a) : IsOpen (U a) := isOpen_lt continuous_const (hc _) + have hu : S ⊆ ⋃ a, U a := by + intro x hx + obtain ⟨i, hi⟩ := hf x hx + exact mem_iUnion.mpr ⟨(i, ⟨f i x / 2, half_pos hi⟩), half_lt_self hi⟩ + obtain ⟨t, ht⟩ := hs.elim_finite_subcover U ho hu + let s := insert 1 (t.image fun a => a.2.val) + have hn : s.Nonempty := ⟨1, Finset.mem_insert_self _ _⟩ + refine ⟨t.image Prod.fst, s.min' hn, ?_, ?_⟩ + · have h := s.min'_mem hn + rcases Finset.mem_insert.mp h with he | he + · rw [he]; exact zero_lt_one + · obtain ⟨a, _, he⟩ := Finset.mem_image.mp he + exact he ▸ a.2.property + · intro x hx + obtain ⟨a, ha, he⟩ := mem_iUnion₂.mp (ht hx) + have hm : a.2.val ∈ s := Finset.mem_insert_of_mem (Finset.mem_image_of_mem _ ha) + exact ⟨_, Finset.mem_image_of_mem _ ha, (s.min'_le _ hm).trans_lt he⟩ + +variable [Group G] {E A B E' A' B' : Type} [Fintype E] [Fintype A] + [Fintype E'] [Fintype A'] + +open scoped Classical in +/-- Uniform displacement for complete actions satisfying two incidence estimates. -/ +def Rigid (K : Set G) (p : E → A) (l : E → B) (p' : E' → A') (l' : E' → B') : Prop := + ∀ (Y : Type) [MetricSpace Y] [CompleteSpace Y] [MulAction G Y] [IsIsometricSMul G Y], + Comparison Y → Incidence Y p l → Incidence Y p' l' → + ∀ x : Y, (∀ g ∈ K, dist x (g • x) ≤ 1) → ∀ g : G, dist x (g • x) ≤ 1200 + +open scoped Classical in +/-- A local hop constraint or a test of translation invariance. -/ +abbrev Constraint (K : Set G) := K ⊕ (G × Term G × Term G) + +open scoped Classical in +/-- In the case `.inl g`, this construction gives `R (.mark 1) (.mark g.val) - 1`. -/ +def defect {K : Set G} (i : Constraint K) (R : Term G → Term G → ℝ) : ℝ := + match i with + | .inl g => R (.mark 1) (.mark g.val) - 1 + | .inr (g, a, b) => |R (g • a) (g • b) - R a b| + +variable [Nonempty E] [Nonempty A] [Nonempty E'] [Nonempty A'] + {K : Set G} {p : E → A} {l : E → B} {p' : E' → A'} {l' : E' → B'} + +open scoped Classical in +private theorem Rigid.exact (h : Rigid K p l p' l') {R : Distances G} + (hr : Table R) (h₁ : Tests R Term.seg p l) (h₂ : Tests R Term.seg p' l') + (hc : ∀ i : Constraint K, defect i R ≤ 0) (π : G) : + R (.mark 1) (.mark π) ≤ 1200 ^ 2 := by + have hg (g : G) (a b : Term G) : R (g • a) (g • b) = R a b := + sub_eq_zero.mp (abs_nonpos_iff.mp (hc (.inr (g, a, b)))) + obtain ⟨Y, _, _, _, _, C, f, hd, hs, he, hf⟩ := hr.realize hg + let x := f (.mark 1) + have hx (g : G) : dist x (g • x) ^ 2 = R (.mark 1) (.mark g) := by + have heq : g • x = f (.mark g) := by + rw [show x = f (.mark 1) from rfl, ← hf] + change f (.mark (g * 1)) = _ + rw [mul_one] + rw [heq] + exact he _ _ + have hb : ∀ g ∈ K, dist x (g • x) ≤ 1 := by + intro g hg + have hh := hc (.inl ⟨g, hg⟩) + change R (.mark 1) (.mark g) - 1 ≤ 0 at hh + rw [← hx] at hh + nlinarith + rw [← hx] + exact pow_le_pow_left₀ dist_nonneg + (h Y C (h₁.dense C f hd hs he).incidence (h₂.dense C f hd hs he).incidence x hb π) 2 + +open scoped Classical in +theorem Rigid.detect (h : Rigid K p l p' l') (π : G) (bound : Term G → Term G → ℝ) : + ∃ t : Finset (Constraint K), ∃ δ : ℝ, 0 < δ ∧ + ∀ R : Term G → Term G → ℝ, R ≤ bound → Table R → + Tests R Term.seg p l → Tests R Term.seg p' l' → + (∀ i ∈ t, defect i R ≤ δ) → R (.mark 1) (.mark π) < 1200 ^ 2 + 1 := by + let S := Icc 0 bound ∩ {R | Table R} ∩ {R | Tests R Term.seg p l} ∩ + {R | Tests R Term.seg p' l'} ∩ {R | 1200 ^ 2 + 1 ≤ R (.mark 1) (.mark π)} + have hs : IsCompact S := + ((((isCompact_Icc.inter_right closed_table).inter_right (closed_tests p l)).inter_right + (closed_tests p' l')).inter_right (isClosed_le (by fun_prop) (by fun_prop))) + have hc (i : Constraint K) : Continuous (defect i) := by + rcases i with g | ⟨g, a, b⟩ <;> unfold defect <;> fun_prop + obtain ⟨t, δ, hδ, ht⟩ := compact_tests hs defect hc (by + rintro R ⟨⟨⟨⟨_, hr⟩, h₁⟩, h₂⟩, bad⟩ + by_contra! hh + exact (not_le_of_gt (lt_add_one _)) (bad.trans (h.exact hr h₁ h₂ hh π))) + refine ⟨t, δ, hδ, ?_⟩ + intro R hb hr h₁ h₂ hd + by_contra! bad + obtain ⟨i, hi, he⟩ := ht R ⟨⟨⟨⟨⟨hr.1, hb⟩, hr⟩, h₁⟩, h₂⟩, bad⟩ + exact he.not_ge (hd i hi) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Averaging finite placements + +Tables of squared distances average linearly. The pseudometric triangle +inequality for the square root follows by Cauchy-Schwarz. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators +variable {G I E A B : Type} + +/-- The data for the placement construction, including `Site`, `[space`, `[complete`, `cmp`, +`mark`. -/ +structure Placement (G : Type) where + /-- The `Placement` component of type `Type`. -/ + Site : Type + [space : MetricSpace Site] + [complete : CompleteSpace Site] + cmp : Comparison Site + /-- The `Placement` component of type `G → Site`. -/ + mark : G → Site + +attribute [instance] Placement.space Placement.complete + +namespace Placement + +/-- Uses `Term.eval X.cmp X.mark` as the representation. -/ +def eval (X : Placement G) : Term G → X.Site := Term.eval X.cmp X.mark + +/-- Computes the sq by the application `dsq (X.eval u) (X.eval v)`. -/ +def sq (X : Placement G) (u v : Term G) := dsq (X.eval u) (X.eval v) + +variable [Fintype I] + +/-- The value specified by `𝔼 i, (Z i).sq u v`. -/ +def average (Z : I → Placement G) (u v : Term G) := 𝔼 i, (Z i).sq u v + +private theorem rms_triangle (a b c : I → ℝ) (h₀ : ∀ i, 0 ≤ c i) + (h : ∀ i, c i ≤ a i + b i) : + Real.sqrt (𝔼 i, c i ^ 2) ≤ Real.sqrt (𝔼 i, a i ^ 2) + Real.sqrt (𝔼 i, b i ^ 2) := by + let x := 𝔼 i, a i ^ 2 + let y := 𝔼 i, b i ^ 2 + have hx : 0 ≤ x := Finset.expect_nonneg fun _ _ => sq_nonneg _ + have hy : 0 ≤ y := Finset.expect_nonneg fun _ _ => sq_nonneg _ + have hxy : (𝔼 i, a i * b i) ≤ Real.sqrt x * Real.sqrt y := by + rw [← Real.sqrt_mul hx] + exact Real.le_sqrt_of_sq_le (Finset.expect_mul_sq_le_sq_mul_sq Finset.univ a b) + have hh (i : I) : c i ^ 2 ≤ a i ^ 2 + b i ^ 2 + 2 * (a i * b i) := by + linarith only [pow_le_pow_left₀ (h₀ i) (h i) 2] + have he := Finset.expect_le_expect (s := Finset.univ) fun i _ => hh i + simp only [Finset.expect_add_distrib, ← Finset.mul_expect] at he + change Real.sqrt _ ≤ Real.sqrt x + Real.sqrt y + apply Real.sqrt_le_iff.mpr + refine ⟨by positivity, ?_⟩ + change _ ≤ x + y + 2 * (𝔼 i, a i * b i) at he + linarith only [he, hxy, Real.sq_sqrt hx, Real.sq_sqrt hy] + +theorem table (Z : I → Placement G) : Table (average Z) := by + refine ⟨fun _ _ => Finset.expect_nonneg (fun _ _ => sq_nonneg _), ?_, ?_, ?_, ?_⟩ + · intro x + simp [average, sq, dsq] + · intro x y + simp only [average, sq, dsq, dist_comm] + · intro x y z + exact rms_triangle _ _ _ (fun _ => dist_nonneg) (fun _ => dist_triangle _ _ _) + · intro t x y z + have h (i : I) : (Z i).sq (.seg t x y) z ≤ + (1 - t.val) * (Z i).sq x z + t.val * (Z i).sq y z - t.val * (1 - t.val) * (Z i).sq x y := + (Z i).cmp.along t _ _ _ + have he := Finset.expect_le_expect (s := Finset.univ) (fun i _ => h i) + simpa only [average, Finset.expect_sub_distrib, Finset.expect_add_distrib, + ← Finset.mul_expect] using he + +variable [Fintype E] [Nonempty E] [Fintype A] [Nonempty A] {p : E → A} {l : E → B} + +private theorem tests (X : Placement G) (h : Incidence X.Site p l) : Tests X.sq Term.seg p l := by + intro x y b n t ht + have hs (u : Fin (n + 1) → A) : + X.eval (sampleMean Term.seg n (x ∘ u)) = sampleMean X.cmp.seg n ((X.eval ∘ x) ∘ u) := + sampleMean_map Term.seg X.cmp.seg X.eval (fun _ _ _ => rfl) n _ + simp only [joint, sq, hs, Function.comp_apply] + exact h.tests X.cmp (X.eval ∘ x) (X.eval ∘ y) (X.eval b) n t ht + +theorem average_tests (Z : I → Placement G) (h : ∀ i, Incidence (Z i).Site p l) : + Tests (average Z) Term.seg p l := by + intro x y b n t ht + have he := Finset.expect_le_expect (s := Finset.univ) + (fun i _ => (Z i).tests (h i) x y b n t ht) + simp only [Finset.expect_add_distrib, ← Finset.mul_expect] at he + have hj (u : Term G) : + joint (average Z) (x ∘ p) (y ∘ l) u = 𝔼 i, joint (Z i).sq (x ∘ p) (y ∘ l) u := by + unfold joint average + simp only [← Finset.expect_add_distrib] + exact Finset.expect_comm _ _ _ + simp only [hj, average] + rw [Finset.expect_comm (Finset.univ : Finset (Fin (n + 1) → A)), + Finset.expect_comm (Finset.univ : Finset E), Finset.expect_comm (Finset.univ : Finset A)] + exact he + +end Placement +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Finite detection on almost all centers + +Each center may have a different metric space. Comparisons are made +after reindexing centers by a permutation, off a small exceptional set. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators +variable {G I : Type} [Group G] [Fintype I] [Nonempty I] + +omit [Nonempty I] in +open scoped Classical in +private theorem expect_perm (π : Equiv.Perm I) (f : I → ℝ) : + (𝔼 i, f (π i)) = 𝔼 i, f i := + Fintype.expect_equiv π _ _ (fun _ => rfl) + +open scoped Classical in +/-- Probability of falling outside a set of good centers. -/ +def badFraction (good : Set I) := 𝔼 i, if i ∈ good then 0 else (1 : ℝ) + +open scoped Classical in +private theorem expect_good (good : Set I) (π : Equiv.Perm I) (f : I → ℝ) + {M δ : ℝ} (hM : 0 ≤ M) (hδ : 0 ≤ δ) (hb : badFraction good ≤ δ) + (hall : ∀ i, f i ≤ M) (hgood : ∀ i ∈ good, π i ∈ good → f i ≤ δ) : + (𝔼 i, f i) ≤ (1 + 2 * M) * δ := by + let b := fun i => if i ∈ good then 0 else (1 : ℝ) + have h (i : I) : f i ≤ δ + M * (b i + b (π i)) := by + by_cases hi : i ∈ good + · by_cases hj : π i ∈ good + · simpa [b, hi, hj] using hgood i hi hj + · simp only [b, ite_eq_left hi, ite_eq_right hj] + linarith [hall i] + · have hn : 0 ≤ b (π i) := by unfold b; split <;> norm_num + rw [show b i = 1 from ite_eq_right hi] + linarith [hall i, mul_nonneg hM hn] + have he := Finset.expect_le_expect (s := Finset.univ) fun i _ => h i + rw [Finset.expect_add_distrib, Fintype.expect_const, ← Finset.mul_expect, + Finset.expect_add_distrib, expect_perm] at he + change (𝔼 i, b i) ≤ δ at hb + linarith only [he, mul_le_mul_of_nonneg_left hb hM] + +variable {K : Set G} + +open scoped Classical in +/-- In the case `.inl _`, this construction gives `Equiv.refl _`. -/ +def Constraint.shift (π : G → Equiv.Perm I) : Constraint K → Equiv.Perm I + | .inl _ => Equiv.refl _ + | .inr (g, _, _) => π g + +open scoped Classical in +/-- In the case `.inl g`, this construction gives `(Z i).sq (.mark 1) (.mark g.val) - 1`. -/ +def Constraint.error (Z : I → Placement G) (π : G → Equiv.Perm I) (i : I) : + Constraint K → ℝ + | .inl g => (Z i).sq (.mark 1) (.mark g.val) - 1 + | .inr (g, x, y) => |(Z i).sq (g • x) (g • y) - (Z (π g i)).sq x y| + +open scoped Classical in +private theorem average_defect (Z : I → Placement G) (π : G → Equiv.Perm I) (c : Constraint K) : + defect c (Placement.average Z) ≤ (𝔼 i, Constraint.error Z π i c) := by + rcases c with g | ⟨g, x, y⟩ + · simp only [defect, Placement.average, Constraint.error, + Finset.expect_sub_distrib, Fintype.expect_const, le_refl] + · simp only [defect, Placement.average, Constraint.error] + rw [← expect_perm (π g) (fun i => (Z i).sq x y), ← Finset.expect_sub_distrib] + apply abs_le.mpr + constructor + · rw [← Finset.expect_neg_distrib] + exact Finset.expect_le_expect (fun _ _ => neg_abs_le _) + · exact Finset.expect_le_expect (fun _ _ => le_abs_self _) + +open scoped Classical in +private def cap (bound : Term G → Term G → ℝ) : Constraint K → ℝ + | .inl g => bound (.mark 1) (.mark g.val) + | .inr (g, x, y) => bound (g • x) (g • y) + bound x y + +omit [Fintype I] [Nonempty I] in +open scoped Classical in +private theorem error_le_cap (Z : I → Placement G) (π : G → Equiv.Perm I) + (bound : Term G → Term G → ℝ) (h : ∀ i, (Z i).sq ≤ bound) + (i : I) (c : Constraint K) : Constraint.error Z π i c ≤ cap bound c := by + rcases c with g | ⟨g, x, y⟩ + · exact (sub_le_self _ zero_le_one).trans (h i _ _) + · have h₁ : 0 ≤ (Z i).sq (g • x) (g • y) := sq_nonneg _ + have h₂ : 0 ≤ (Z (π g i)).sq x y := sq_nonneg _ + apply abs_le.mpr + dsimp only [cap] + constructor <;> linarith [h i (g • x) (g • y), h (π g i) x y] + +variable {E A B E' A' B' : Type} [Fintype E] [Fintype A] [Fintype E'] [Fintype A'] + [Nonempty E] [Nonempty A] [Nonempty E'] [Nonempty A'] + {p : E → A} {l : E → B} {p' : E' → A'} {l' : E' → B'} + +open scoped Classical in +/-- The finite metric tests, payload tolerance and exceptional fraction +are independent of the number of centers. -/ +theorem Rigid.detect_local (h : Rigid K p l p' l') (g : G) + (bound : Term G → Term G → ℝ) (pay : ℝ) : + ∃ t : Finset (Constraint K), ∃ δ : ℝ, 0 < δ ∧ + ∀ (I : Type) [Fintype I] [Nonempty I] (Z : I → Placement G) + (π : G → Equiv.Perm I) (good : Set I) (v : I → ℝ), + (∀ i, Incidence (Z i).Site p l) → (∀ i, Incidence (Z i).Site p' l') → + (∀ i, (Z i).sq ≤ bound) → (∀ i, v i ^ 2 ≤ pay) → badFraction good ≤ δ → + (∀ c ∈ t, ∀ i ∈ good, Constraint.shift π c i ∈ good → Constraint.error Z π i c ≤ δ) → + (∀ i ∈ good, v i ^ 2 ≤ (Z i).sq (.mark 1) (.mark g) + δ) → + (𝔼 i, v i) ≤ 1201 := by + obtain ⟨t, ε, hε, ht⟩ := h.detect g bound + let M := |pay| + ∑ c ∈ t, |cap bound c| + have hM : 0 ≤ M := by unfold M; positivity + have hm (c) (hc : c ∈ t) : cap bound c ≤ M := + (le_abs_self _).trans ((Finset.single_le_sum (fun c _ => abs_nonneg (cap bound c)) hc).trans + (le_add_of_nonneg_left (abs_nonneg _))) + have hp : pay ≤ M := (le_abs_self _).trans (le_add_of_nonneg_right (by positivity)) + let δ := min 1 ε / (1 + 2 * M) + have hδ : 0 < δ := div_pos (lt_min zero_lt_one hε) (by positivity) + have hd : (1 + 2 * M) * δ = min 1 ε := mul_div_cancel₀ _ (by positivity) + refine ⟨t, δ, hδ, ?_⟩ + intro I _ _ Z π good v h₁ h₂ hb hv hg hc hv' + have havg : Placement.average Z ≤ bound := fun x y => + Finset.expect_le Finset.univ_nonempty (fun i _ => hb i x y) + have hctrl (c) (hc' : c ∈ t) : defect c (Placement.average Z) ≤ ε := by + refine (average_defect Z π c).trans ((expect_good good (Constraint.shift π c) _ + hM hδ.le hg ?_ (hc c hc')).trans (hd.le.trans (min_le_right _ _))) + intro i + exact (error_le_cap Z π bound hb i c).trans (hm c hc') + have H := ht _ havg (Placement.table Z) (Placement.average_tests Z h₁) + (Placement.average_tests Z h₂) hctrl + have L := expect_good good (Equiv.refl I) + (fun i => v i ^ 2 - (Z i).sq (.mark 1) (.mark g)) hM hδ.le hg + (fun i => (sub_le_self _ (sq_nonneg _)).trans ((hv i).trans hp)) + (fun i hi _ => sub_le_iff_le_add'.mpr (hv' i hi)) + rw [Finset.expect_sub_distrib, hd] at L + have hs := Finset.expect_mul_sq_le_sq_mul_sq Finset.univ v (fun _ => (1 : ℝ)) + simp only [one_pow, Fintype.expect_const, mul_one] at hs + unfold Placement.average at H + nlinarith [min_le_left (1 : ℝ) ε] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Restricting detection to finitely many marked sites + +We discard marks outside their prescribed distance bounds. All +expressions needed by the finite tests use only marks in a single +finite set and its translates. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators +variable {G F : Type} {Y : Type*} [MetricSpace Y] + +namespace Term + +open scoped Classical in +/-- In the case `.mark g`, this construction gives `{g}`. -/ +def support : Term G → Finset G + | .mark g => {g} + | .seg _ a b => support a ∪ support b + +open scoped Classical in +theorem eval_map (C : Comparison Y) (x : F → Y) (f : G → F) (a : Term G) : + eval C x (map f a) = eval C (x ∘ f) a := by + induction a <;> simp [eval, map, *] + +open scoped Classical in +theorem eval_congr (C : Comparison Y) (x y : G → Y) (a : Term G) + (h : ∀ g ∈ a.support, x g = y g) : eval C x a = eval C y a := by + induction a with + | mark g => exact h g (Finset.mem_singleton_self _) + | seg u a b ha hb => + exact congrArg₂ (C.seg u) (ha (fun g hg => h g (Finset.mem_union_left _ hg))) + (hb (fun g hg => h g (Finset.mem_union_right _ hg))) + +open scoped Classical in +private def height (L : G → ℝ) : Term G → ℝ + | .mark g => L g ^ 2 + | .seg t a b => (1 - t.val) * height L a + t.val * height L b + +open scoped Classical in +private theorem eval_bound (C : Comparison Y) (x : G → Y) (o : Y) (L : G → ℝ) + (h : ∀ g, dist (x g) o ^ 2 ≤ L g ^ 2) (a : Term G) : + dist (eval C x a) o ^ 2 ≤ height L a := by + induction a with + | mark => exact h _ + | seg t a b ha hb => + have h₁ := t.2.1 + have h₂ := sub_nonneg.mpr t.2.2 + exact ((C.along _ _ _ _).trans (sub_le_self _ (by positivity))).trans + (add_le_add (mul_le_mul_of_nonneg_left ha h₂) (mul_le_mul_of_nonneg_left hb h₁)) + +end Term + +variable [Group G] {K : Set G} + +open scoped Classical in +private def truncate (L : G → ℝ) (X : Placement G) (g : G) : X.Site := + if dist (X.mark g) (X.mark 1) ^ 2 ≤ L g ^ 2 then X.mark g else X.mark 1 + +open scoped Classical in +private def bounded (L : G → ℝ) (X : Placement G) : Placement G := + { X with mark := truncate L X } + +open scoped Classical in +private theorem bounded_sq (L : G → ℝ) (X : Placement G) (a b : Term G) : + (bounded L X).sq a b ≤ 2 * Term.height L a + 2 * Term.height L b := by + have h (g : G) : dist (truncate L X g) (X.mark 1) ^ 2 ≤ L g ^ 2 := by + unfold truncate + split + · assumption + · simpa using sq_nonneg (L g) + let f := Term.eval X.cmp (truncate L X) + change dist (f a) (f b) ^ 2 ≤ _ + have ht := dist_sq_triangle (f a) (X.mark 1) (f b) + rw [dist_comm (X.mark 1)] at ht + dsimp only [f] at ht ⊢ + linarith only [ht, Term.eval_bound X.cmp _ _ _ h a, Term.eval_bound X.cmp _ _ _ h b] + +open scoped Classical in +private def words : Constraint K → Finset (Term G) + | .inl g => {.mark g.val} + | .inr (g, a, b) => {.mark g, a, b} + +open scoped Classical in +private def retract (S : Finset G) (hS : 1 ∈ S) (g : G) : S := + if h : g ∈ S then ⟨g, h⟩ else ⟨1, hS⟩ + +open scoped Classical in +/-- Squared distance in a translated finite marking. -/ +def Placement.on (X : Placement G) (S : Finset G) (g : G) (a b : Term S) := + let f := Term.eval X.cmp (fun j : S => X.mark (g * j.val)) + dsq (f a) (f b) + +open scoped Classical in +private theorem bounded_on (L : G → ℝ) (X : Placement G) (S : Finset G) (hS : 1 ∈ S) + (g : G) (hg : ∀ j ∈ S, dist (X.mark (g * j)) (X.mark 1) ^ 2 ≤ L (g * j) ^ 2) + (a b : Term G) (ha : a.support ⊆ S) (hb : b.support ⊆ S) : + (bounded L X).sq (g • a) (g • b) = + X.on S g (a.map (retract S hS)) (b.map (retract S hS)) := by + have eq (w : Term G) (hw : w.support ⊆ S) : + Term.eval X.cmp (truncate L X) (g • w) = + Term.eval X.cmp (fun j : S => X.mark (g * j.val)) (w.map (retract S hS)) := by + change Term.eval _ _ (Term.map _ w) = _ + rw [Term.eval_map, Term.eval_map] + apply Term.eval_congr + intro i hi + simp only [Function.comp_apply, retract, dite_eq_left (hw hi), truncate, + ite_eq_left (hg i (hw hi))] + exact congrArg₂ dsq (eq a ha) (eq b hb) + +variable {E A B E' A' B' : Type} [Fintype E] [Fintype A] [Fintype E'] [Fintype A'] + [Nonempty E] [Nonempty A] [Nonempty E'] [Nonempty A'] + {p : E → A} {l : E → B} {p' : E' → A'} {l' : E' → B'} + +open scoped Classical in +theorem Rigid.detect_sites (h : Rigid K p l p' l') (g : G) (L : G → ℝ) (pay : ℝ) : + ∃ S : Finset G, 1 ∈ S ∧ g ∈ S ∧ ∃ U : Finset (Term S), ∃ δ : ℝ, 0 < δ ∧ + ∀ (I : Type) [Fintype I] [Nonempty I] (Z : I → Placement G) + (π : G → Equiv.Perm I) (good : Set I) (v : I → ℝ), + (∀ i, Incidence (Z i).Site p l) → (∀ i, Incidence (Z i).Site p' l') → + (∀ i, v i ^ 2 ≤ pay) → badFraction good ≤ δ → + (∀ i ∈ good, ∀ a ∈ S, ∀ b ∈ S, dist ((Z i).mark (a * b)) ((Z i).mark 1) ^ 2 ≤ L (a * b) ^ 2) → + (∀ i ∈ good, ∀ a ∈ S, a ∈ K → dist ((Z i).mark 1) ((Z i).mark a) ^ 2 ≤ 1 + δ) → + (∀ i ∈ good, ∀ a ∈ S, π a i ∈ good → ∀ u ∈ U, ∀ w ∈ U, + |(Z i).on S a u w - (Z (π a i)).on S 1 u w| ≤ δ) → + (∀ i ∈ good, v i ^ 2 ≤ dist ((Z i).mark 1) ((Z i).mark g) ^ 2 + δ) → + (𝔼 i, v i) ≤ 1201 := by + obtain ⟨t, δ, hδ, ht⟩ := h.detect_local g (fun u v => 2 * Term.height L u + + 2 * Term.height L v) pay + let F := t.biUnion words + let S := insert 1 (insert g (F.biUnion Term.support)) + have hS : 1 ∈ S := by simp [S] + have hg : g ∈ S := by simp [S] + have hs {u : Term G} (hu : u ∈ F) : u.support ⊆ S := by + intro x hx + exact Finset.mem_insert_of_mem (Finset.mem_insert_of_mem (Finset.mem_biUnion.mpr ⟨u, hu, hx⟩)) + have hm {a : G} (ha : Term.mark a ∈ F) : a ∈ S := hs ha (Finset.mem_singleton_self _) + let U := F.image (Term.map (retract S hS)) + refine ⟨S, hS, hg, U, δ, hδ, ?_⟩ + intro I _ _ Z π good v h₁ h₂ hv hgood hb hhop hterm hpay + have he (i : I) (hi : i ∈ good) (a : G) (ha : a ∈ S) : + (bounded L (Z i)).sq (.mark 1) (.mark a) = + dist ((Z i).mark 1) ((Z i).mark a) ^ 2 := by + have h' (j : G) (hj : j ∈ S) : truncate L (Z i) j = (Z i).mark j := by + apply ite_eq_left + simpa using hb i hi 1 hS j hj + change dist (truncate L (Z i) 1) (truncate L (Z i) a) ^ 2 = _ + rw [h' 1 hS, h' a ha] + refine ht I (fun i => bounded L (Z i)) π good v h₁ h₂ + (fun i a b => bounded_sq L (Z i) a b) hv hgood ?_ ?_ + · intro c hc i hi hi' + have hc' : words c ⊆ F := fun _ hu => Finset.mem_biUnion.mpr ⟨c, hc, hu⟩ + rcases c with a | ⟨a, u, w⟩ + · have ha : a.val ∈ S := hm (hc' (by simp [words])) + simp only [Constraint.error, he i hi a.val ha] + linarith [hhop i hi a.val ha a.property] + · have ha : a ∈ S := hm (hc' (by simp [words])) + have hu : u ∈ F := hc' (by simp [words]) + have hw : w ∈ F := hc' (by simp [words]) + have hk := bounded_on L (Z (π a i)) S hS 1 (hb _ hi' 1 hS) u w (hs hu) (hs hw) + simp only [one_smul] at hk + rw [Constraint.error, bounded_on L (Z i) S hS a (hb _ hi a ha) u w (hs hu) (hs hw), hk] + exact hterm i hi a ha hi' _ (Finset.mem_image_of_mem _ hu) _ (Finset.mem_image_of_mem _ hw) + · intro i hi + rw [he i hi g hg] + exact hpay i hi + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Finite balls of hops + +A fixed factorization length is assigned to each element of a group +generated by subgroups. For any finite list of elements, finitely many +hops suffice to realize all those lengths in every permutation action. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped Pointwise +variable {G P I : Type} [Group G] + +open scoped Classical in +/-- The value specified by `⋃ p, (K p : Set G)`. -/ +def hops (K : P → Subgroup G) : Set G := ⋃ p, (K p : Set G) + +open scoped Classical in +private theorem factor (K : P → Subgroup G) (hg : iSup K = ⊤) (g : G) : + ∃ (n : ℕ) (s : Finset G), (↑s : Set G) ⊆ hops K ∧ g ∈ s ^ n := by + have h : g ∈ iSup K := by rw [hg]; trivial + refine Subgroup.iSup_induction K (C := fun g => ∃ (n : ℕ) (s : Finset G), + (↑s : Set G) ⊆ hops K ∧ g ∈ s ^ n) h ?_ ?_ ?_ + · intro p x hx + refine ⟨1, {x}, ?_, by simp⟩ + simpa only [Finset.coe_singleton, Set.singleton_subset_iff, hops, Set.mem_iUnion] using + (show ∃ p, x ∈ (K p : Set G) from ⟨p, hx⟩) + · exact ⟨0, ∅, by simp, by simp⟩ + · intro x y hx hy + obtain ⟨n, s, hs, hx⟩ := hx + obtain ⟨m, t, ht, hy⟩ := hy + refine ⟨n + m, s ∪ t, ?_, ?_⟩ + · rw [Finset.coe_union] + exact Set.union_subset hs ht + · rw [pow_add] + exact Finset.mul_mem_mul (Finset.pow_subset_pow_left Finset.subset_union_left hx) + (Finset.pow_subset_pow_left Finset.subset_union_right hy) + +open scoped Classical in +theorem finite_hops [Nonempty P] (K : P → Subgroup G) (hg : iSup K = ⊤) : + ∃ len : G → ℕ, ∀ S : Finset G, ∃ (H : Finset G) (r : ℕ), + 1 ∈ H ∧ H⁻¹ = H ∧ (↑H : Set G) ⊆ hops K ∧ + (∀ g ∈ S, g ∈ hops K → g ∈ H) ∧ (∀ g ∈ S, g ∈ H ^ (len g) ∧ len g ≤ r) := by + choose len t ht he using factor K hg + refine ⟨len, ?_⟩ + intro S + let F := insert 1 ((S.filter (· ∈ hops K)) ∪ S.biUnion t) + let H := F ∪ F⁻¹ + have hF : (↑F : Set G) ⊆ hops K := by + intro x hx + rcases Finset.mem_insert.mp hx with rfl | hx + · exact Set.mem_iUnion.mpr ⟨Classical.arbitrary P, Subgroup.one_mem _⟩ + rcases Finset.mem_union.mp hx with hx | hx + · exact (Finset.mem_filter.mp hx).2 + · obtain ⟨k, _, hk⟩ := Finset.mem_biUnion.mp hx + exact ht k hk + refine ⟨H, S.sup len, by simp [H, F], ?_, ?_, ?_, ?_⟩ + · ext + simp [H, or_comm] + · intro x hx + rcases Finset.mem_union.mp hx with hx | hx + · exact hF hx + obtain ⟨y, hy, rfl⟩ := Finset.mem_inv.mp hx + obtain ⟨p, hp⟩ := Set.mem_iUnion.mp (hF hy) + exact Set.mem_iUnion.mpr ⟨p, (K p).inv_mem hp⟩ + · intro g hs hh + simp [H, F, hs, hh] + · intro g hs + refine ⟨Finset.pow_subset_pow_left ?_ (he g), Finset.le_sup hs⟩ + intro a ha + exact Finset.mem_union_left _ (Finset.mem_insert_of_mem + (Finset.mem_union_right _ (Finset.mem_biUnion.mpr ⟨g, hs, ha⟩))) + +variable [MulAction G I] + +open scoped Classical in +/-- The quantity computed by `(H ^ r).image (fun a => a⁻¹ • i)`. -/ +def ball (H : Finset G) (r : ℕ) (i : I) : Finset I := (H ^ r).image (fun a => a⁻¹ • i) + +open scoped Classical in +/-- The condition `∃ a ∈ H, a⁻¹ • i = j` on the specified data. -/ +def link (H : Finset G) (i j : I) : Prop := ∃ a ∈ H, a⁻¹ • i = j + +open scoped Classical in +theorem mem_ball {H : Finset G} {r : ℕ} (i : I) {a : G} (ha : a ∈ H ^ r) : + a⁻¹ • i ∈ ball H r i := Finset.mem_image_of_mem _ ha + +open scoped Classical in +/-- A path of the prescribed length stays inside the ball. -/ +theorem ball_path {H : Finset G} (hH : 1 ∈ H) {r : ℕ} (i : I) + {Q : I → ℕ → Prop} (h₀ : Q i 0) + (hs : ∀ j ∈ ball H r i, ∀ k ∈ ball H r i, ∀ n, link H j k → Q j n → Q k (n + 1)) + {n : ℕ} (hn : n ≤ r) {a : G} (ha : a ∈ H ^ n) : Q (a⁻¹ • i) n := by + induction n generalizing a with + | zero => + have : a = 1 := Finset.mem_one.mp (by simpa using ha) + simpa [this] + | succ n ih => + have hm := mem_ball i (Finset.pow_subset_pow_right hH hn ha) + rw [pow_succ, Finset.mem_mul] at ha + obtain ⟨b, hb, c, hc, rfl⟩ := ha + have hnr : n ≤ r := by omega + exact hs _ (mem_ball i (Finset.pow_subset_pow_right hH hnr hb)) _ hm n + ⟨c, hc, by rw [mul_inv_rev, mul_smul]⟩ (ih hnr hb) + +open scoped Classical in +theorem ball_dist {Y : Type*} [MetricSpace Y] {H : Finset G} (hH : 1 ∈ H) + {r : ℕ} {i : I} (x : I → Y) (hs : ∀ j ∈ ball H r i, ∀ k ∈ ball H r i, + link H j k → dist (x j) (x k) ≤ 2) + {n : ℕ} (hn : n ≤ r) {a : G} (ha : a ∈ H ^ n) : + dist (x (a⁻¹ • i)) (x i) ≤ 2 * n := by + refine ball_path hH i (Q := fun j n => dist (x j) (x i) ≤ 2 * n) (by simp) ?_ hn ha + intro j hj k hk m he hd + have ht := dist_triangle (x k) (x j) (x i) + rw [dist_comm (x k) (x j)] at ht + push_cast + linarith [hs j hj k hk he] + +open scoped Classical in +theorem center_mem_ball {H : Finset G} (hH : 1 ∈ H) (r : ℕ) (i : I) : i ∈ ball H r i := by + simpa using mem_ball i (Finset.one_mem_pow (n := r) hH) + +open scoped Classical in +theorem ball_connected {H : Finset G} (hH : 1 ∈ H) (r : ℕ) (i : I) (x y : ball H r i) : + Relation.EqvGen (fun j k : ball H r i => link H j.val k.val) x y := by + let c : ball H r i := ⟨i, center_mem_ball hH r i⟩ + let l := fun j k : ball H r i => link H j.val k.val + have hc (z : ball H r i) : Relation.EqvGen l c z := by + obtain ⟨a, ha, he⟩ := Finset.mem_image.mp z.property + have h : ∀ hm : a⁻¹ • i ∈ ball H r i, Relation.EqvGen l c ⟨a⁻¹ • i, hm⟩ := by + refine ball_path hH i (Q := fun j _ => ∀ hj, Relation.EqvGen l c ⟨j, hj⟩) ?_ ?_ le_rfl ha + · exact fun _ => .refl _ + · exact fun _ hj _ hk _ he h _ => .trans _ _ _ (h hj) (.rel _ _ he) + simpa only [he, Subtype.eta] using h (mem_ball i ha) + exact .trans _ _ _ (.symm _ _ (hc x)) (hc y) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Finite detection of expensive payloads + +Prices are shared by all balls containing a given tuple, including +tuples with coincidences. The certificate consists of symmetric hops, +a radius, a finite list of nonzero tensors and a positive tolerance. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral +open scoped BigOperators Pointwise + +variable {k G J I E A B E' A' B' : Type} [Field k] + [Fintype E] [Fintype A] [Fintype E'] [Fintype A'] + +open scoped Classical in +/-- Realization of ordinary and collapsed prices with the two links. -/ +def HasModels (k : Type) [Field k] (p : E → A) (l : E → B) (p' : E' → A') (l' : E' → B') : Prop := + ∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (P : Tensor k S → ℝ), + (P = 0 ∨ ∃ D, P ∈ Tensor.ordinary k S D) → ∃ X : Placement S, + Represents k P X.mark ∧ Incidence X.Site p l ∧ Incidence X.Site p' l' + +variable {p : E → A} {l : E → B} {p' : E' → A'} {l' : E' → B'} + +open scoped Classical in +private theorem HasModels.extend (h : HasModels k p l p' l') (N : Finset I) + (i : N) (P : Tensor k N → ℝ) (hp : P = 0 ∨ ∃ D, P ∈ Tensor.ordinary k N D) : + ∃ X : Placement I, Represents k P (X.mark ∘ Subtype.val) ∧ + Incidence X.Site p l ∧ Incidence X.Site p' l' := by + have : Nonempty N := ⟨i⟩ + obtain ⟨X, hx, h₁, h₂⟩ := h N P hp + let y := fun j => if hj : j ∈ N then X.mark ⟨j, hj⟩ else X.mark i + have hy : y ∘ Subtype.val = X.mark := by ext j; simp [y, j.property] + refine ⟨⟨X.Site, X.cmp, y⟩, ?_, h₁, h₂⟩ + change Represents k P (y ∘ Subtype.val) + rwa [hy] + +open scoped Classical in +private theorem price_zero {T : Type} [Fintype T] {P : Tensor k T → ℝ} + (hp : P = 0 ∨ ∃ D, P ∈ Tensor.ordinary k T D) : P 0 = 0 := by + rcases hp with rfl | ⟨_, _, _, _, _, rfl⟩ <;> simp [Tensor.values] + +variable [Group G] + +open scoped Classical in +private def markOrbit [MulAction G I] (i : I) (X : Placement I) : Placement G := + ⟨X.Site, X.cmp, fun g => X.mark (g⁻¹ • i)⟩ + +open scoped Classical in +/-- Both sampled marks and all intermediate hops on their paths lie in +the indicated ball. -/ +private theorem orbit_estimates [MulAction G I] {H S : Finset G} (hH : 1 ∈ H) + {len : G → ℕ} {r : ℕ} (hl : ∀ a ∈ S * S, a ∈ H ^ (len a) ∧ len a ≤ r) + (i : I) (X : Placement I) + (hd : ∀ j ∈ ball H r i, ∀ u ∈ ball H r i, link H j u → dist (X.mark j) (X.mark u) ≤ 2) + (a : G) (ha : a ∈ S) (b : G) (hb : b ∈ S) : + (a * b)⁻¹ • i ∈ ball H r i ∧ + dist (X.mark ((a * b)⁻¹ • i)) (X.mark i) ≤ 2 * len (a * b) := by + obtain ⟨h₁, h₂⟩ := hl _ (Finset.mul_mem_mul ha hb) + exact ⟨mem_ball i (Finset.pow_subset_pow_right hH h₂ h₁), + ball_dist hH X.mark hd h₂ h₁⟩ + +variable [Nonempty E] [Nonempty A] [Nonempty E'] [Nonempty A'] [Nonempty J] + +open scoped Classical in +theorem Rigid.finite_detection (K : J → Subgroup G) (hgen : iSup K = ⊤) + (h : Rigid (hops K) p l p' l') (hm : HasModels k p l p' l') (g : G) : + ∃ S H : Finset G, ∃ d r : ℕ, ∃ T : Finset (Tensor k S), ∃ ρ : ℝ, + 1 ∈ S ∧ 1 ∈ H ∧ H⁻¹ = H ∧ (↑H : Set G) ⊆ hops K ∧ 0 < d ∧ d ≤ r ∧ g ∈ H ^ d ∧ 0 ∉ T ∧ 0 < ρ ∧ + ∀ (I : Type) [Fintype I] [Nonempty I] [MulAction G I] (v : I → ℝ) + (x : (S → I) → Tensor k S → ℝ) (good : Set I), + (∀ i, |v i| ≤ d) → badFraction good ≤ ρ → + (∀ i ∈ good, ∃ P : Tensor k (ball H r i) → ℝ, + (P = 0 ∨ ∃ D, P ∈ Tensor.ordinary k (ball H r i) D) ∧ + Passes T (ball H r i) (link H) i (g⁻¹ • i) (v i) x ρ P) → + (𝔼 i, v i) ≤ 1201 := by + obtain ⟨len, hf⟩ := finite_hops K hgen + let d := len g + 1 + obtain ⟨S, hS, hg, U, δ, hδ, hdet⟩ := h.detect_sites g (fun a => 2 * len a) ((d : ℝ) ^ 2) + have : Nonempty S := ⟨⟨1, hS⟩⟩ + obtain ⟨H, r₀, hH, hinv, hK, hhop, hl₀⟩ := hf (S * S) + let r := max r₀ d + have hl (a : G) (ha : a ∈ S * S) : a ∈ H ^ (len a) ∧ len a ≤ r := + ⟨(hl₀ a ha).1, (hl₀ a ha).2.trans (le_max_left _ _)⟩ + have hsub (a : G) (ha : a ∈ S) : a ∈ S * S := by + simpa using Finset.mul_mem_mul hS ha + have hmem (a : G) (ha : a ∈ S * S) : a ∈ H ^ r := + Finset.pow_subset_pow_right hH (hl a ha).2 (hl a ha).1 + let D : ℝ := 4 * r + 1 + obtain ⟨T, η, hη, htest⟩ := finite_terms_tests k U D hδ + let ρ := min (min 1 (η / 2)) (δ / (D + 3)) + have hD : 0 < D := by unfold D; positivity + have hp : 0 < ρ := by unfold ρ; positivity + have hρ : ρ ≤ 1 := (min_le_left _ _).trans (min_le_left _ _) + have hη' : 2 * ρ ≤ η := by + have hh : ρ ≤ η / 2 := (min_le_left _ _).trans (min_le_right _ _) + linarith + have hd : ρ * (D + 3) ≤ δ := (le_div_iff₀ (by positivity)).mp (min_le_right _ _) + have hroute : g ∈ H ^ d := Finset.pow_subset_pow_right hH (Nat.le_succ _) (hl g (hsub g hg)).1 + refine ⟨S, H, d, r, T.erase 0, ρ, hS, hH, hinv, hK, Nat.succ_pos _, le_max_right _ _, hroute, + Finset.notMem_erase _ _, hp, ?_⟩ + intro I _ _ _ v x good hv hbad hpass + let N : I → Finset I := ball H r + have hc (i : I) : i ∈ N i := center_mem_ball hH r i + have hmemb (i : I) (a : G) (ha : a ∈ S) : a⁻¹ • i ∈ N i := mem_ball i (hmem a (hsub a ha)) + have hall (i : I) : ∃ P : Tensor k (N i) → ℝ, + (P = 0 ∨ ∃ D, P ∈ Tensor.ordinary k (N i) D) ∧ + (i ∈ good → Passes (T.erase 0) (N i) (link H) i (g⁻¹ • i) (v i) x ρ P) := by + by_cases hi : i ∈ good + · obtain ⟨P, hP, he⟩ := hpass i hi + exact ⟨P, hP, fun _ => he⟩ + · exact ⟨0, Or.inl rfl, fun hj => (hi hj).elim⟩ + choose P hP ht using hall + choose X hX h₁ h₂ using fun i => hm.extend (N i) ⟨i, hc i⟩ (P i) (hP i) + have hh (i : I) (hi : i ∈ good) (a : I) (ha : a ∈ N i) (b : I) (hb : b ∈ N i) + (he : link H a b) : dist ((X i).mark a) ((X i).mark b) ≤ 1 + ρ := by + have hh := (ht i hi).2.1 ⟨a, ha⟩ ⟨b, hb⟩ he + rwa [(hX i).1] at hh + have hdist (i : I) (hi : i ∈ good) (a : G) (ha : a ∈ S) (b : G) (hb : b ∈ S) := + orbit_estimates hH hl i (X i) (fun j hj u hu he => (hh i hi j hj u hu he).trans + (show 1 + ρ ≤ 2 by linarith)) a ha b hb + have hrad (i : I) (hi : i ∈ good) (a : G) (ha : a ∈ S) (b : G) (hb : b ∈ S) : + dist ((X i).mark ((a * b)⁻¹ • i)) ((X i).mark i) ≤ 2 * (r : ℝ) := + (hdist i hi a ha b hb).2.trans (by gcongr; exact (hl _ (Finset.mul_mem_mul ha hb)).2) + let Z := fun i => markOrbit (G := G) i (X i) + let π := fun a : G => MulAction.toPerm (β := I) a⁻¹ + refine hdet I Z π good v h₁ h₂ ?_ (hbad.trans (by nlinarith)) ?_ ?_ ?_ ?_ + · intro i + simpa using pow_le_pow_left₀ (abs_nonneg _) (hv i) 2 + · intro i hi a ha b hb + change dist ((X i).mark ((a * b)⁻¹ • i)) ((X i).mark ((1 : G)⁻¹ • i)) ^ 2 ≤ _ + rw [inv_one, one_smul] + exact pow_le_pow_left₀ dist_nonneg (hdist i hi a ha b hb).2 2 + · intro i hi a ha hka + have he := hh i hi _ (hc i) _ (hmemb i a ha) ⟨a, hhop a (hsub a ha) hka, rfl⟩ + change dist ((X i).mark ((1 : G)⁻¹ • i)) ((X i).mark (a⁻¹ • i)) ^ 2 ≤ _ + rw [inv_one, one_smul] + nlinarith [pow_le_pow_left₀ dist_nonneg he 2] + · intro i hi a ha hi' u hu w hw + let z (i : I) (b : G) (hb : b ∈ S) (s : S) : N i := + ⟨(b * s.val)⁻¹ • i, mem_ball i (hmem _ (Finset.mul_mem_mul hb s.property))⟩ + have hz (i : I) (hi : i ∈ good) (b : G) (hb : b ∈ S) : + Realized (fun s : S => (Z i).mark (b * s.val)) (P i ∘ Tensor.place (z i b hb)) D := by + apply (hX i).2 S (z i b hb) D hD + intro s t + have hh := dist_triangle ((X i).mark ((b * s.val)⁻¹ • i)) ((X i).mark i) + ((X i).mark ((b * t.val)⁻¹ • i)) + rw [dist_comm ((X i).mark i)] at hh + change dist ((X i).mark ((b * s.val)⁻¹ • i)) ((X i).mark ((b * t.val)⁻¹ • i)) ≤ 4 * r + 1 + linarith [hrad i hi b hb s s.property, hrad i hi b hb t t.property] + have heq : Subtype.val ∘ z i a ha = Subtype.val ∘ z (π a i) 1 hS := by + ext s + simp [z, π, mul_smul] + refine htest _ _ (hz i hi a ha) (hz _ hi' 1 hS) ?_ u hu w hw + intro A hA + by_cases h0 : A = 0 + · simp [h0, Tensor.place_zero, price_zero (hP i), price_zero (hP (π a i)), hη.le] + have htA := Finset.mem_erase.mpr ⟨h0, hA⟩ + have hL := (ht i hi).2.2 (z i a ha) A htA + have hR := (ht _ hi').2.2 (z _ 1 hS) A htA + rw [heq] at hL + rw [abs_le] at hL hR ⊢ + simp only [Function.comp_apply] + constructor <;> linarith + · intro i hi + have hval := (ht i hi).1 ⟨i, hc i⟩ ⟨_, hmemb i g hg⟩ rfl rfl + rw [(hX i).1, abs_le] at hval + have hd' := hrad i hi 1 hS g hg + rw [one_mul, dist_comm] at hd' + let d := dist ((X i).mark i) ((X i).mark (g⁻¹ • i)) + change -ρ ≤ v i - d ∧ v i - d ≤ ρ at hval + have hd0 : 0 ≤ d := dist_nonneg + have hv' : |v i| ≤ d + ρ := abs_le.mpr ⟨by linarith, by linarith⟩ + have hs := pow_le_pow_left₀ (abs_nonneg _) hv' 2 + rw [sq_abs] at hs + have hprod : ρ * (2 * d + ρ) ≤ δ := (mul_le_mul_of_nonneg_left + (show 2 * d + ρ ≤ D + 3 by unfold D d; linarith) hp.le).trans hd + simp only [Z, markOrbit, inv_one, one_smul] + change _ ≤ d ^ 2 + δ + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometrySector.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometrySector.lean new file mode 100644 index 0000000000..7b131de987 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometrySector.lean @@ -0,0 +1,568 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Basic.Real.Basic +public import Mathlib.Algebra.Order.Algebra +public import Mathlib.Analysis.Normed.Group.Basic +public import Mathlib.Data.EReal.Operations +public import Mathlib.Topology.Algebra.InfiniteSum.Order +public import Mathlib.Topology.MetricSpace.Bounded +public import Mathlib.Analysis.SpecialFunctions.Sqrt +public import Mathlib.Tactic.Module +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryTerms +public import Mathlib.Algebra.Order.Monoid.Prod +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Block +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Span + +/-! +# The metric consequence of shifted crossing + +The two original wires connect opposite terminals. On either cut we +may move terminals to a pair of centers and connect those centers. +At least one cut must pay the full cost of the original wires. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +/-- The cut bound of type `Prop` for the given inputs. -/ +def CutBound {S : Type*} (d : S → S → ℝ) : Prop := + ∀ (x x' y y' z z' w w' : S) (t u α β : ℝ), + 0 < t → 0 < u → 0 < α → 0 < β → 2 * (t ^ 2 + u ^ 2) < α ^ 2 + β ^ 2 → + t * (d x x' - d x z - d x' z') + u * (d y y' - d y z - d y' z') ≤ α * d z z' ∨ + t * (d x x' - d x w - d x' w') + u * (d y y' - d y w' - d y' w) ≤ β * d w w' + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# The parallelogram law from shifted crossing + +There is no regularity assumption on the seminorm. The directional +savings on two cuts are estimated using a finite difference at an +approximate minimizer of `p (r • (z+w) + z) - r * p (z+w)`. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {V : Type*} [AddCommGroup V] [Module ℝ V] (p : Seminorm ℝ V) + +private theorem scale {r : ℝ} (hr : 0 ≤ r) (x : V) : p (r • x) = r * p x := by + rw [map_smul_eq_mul, Real.norm_eq_abs, abs_of_nonneg hr] + +/-- The sum of the two directional savings approaches the norm of +the sum of the directions. -/ +private theorem gain (z w : V) {ε : ℝ} (hε : 0 < ε) : + ∃ x : V, p (z + w) - ε ≤ 2 * p x - p (x - z) - p (x - w) := by + let f (r : ℝ) := p (r • (z + w) + z) - r * p (z + w) + let S := f '' Set.Ici 0 + have hne : S.Nonempty := ⟨_, 0, by simp, rfl⟩ + have hbd : BddBelow S := by + refine ⟨-p z, ?_⟩ + rintro _ ⟨r, hr, rfl⟩ + have h := map_add_le_add p (r • (z + w) + z) (-z) + rw [add_neg_cancel_right, map_neg_eq_map, scale p hr] at h + unfold f + linarith + obtain ⟨_, ⟨r, hr, rfl⟩, he⟩ := exists_lt_of_csInf_lt hne + (show sInf S < sInf S + ε / 2 by linarith) + let s := 2 * r + 1 + have hs : 0 ≤ s := by change 0 ≤ r at hr; dsimp [s]; linarith + have h := csInf_le hbd (show f s ∈ S from ⟨s, hs, rfl⟩) + let x := s • (z + w) + z + refine ⟨x, ?_⟩ + have eq : x - w = (2 : ℝ) • (r • (z + w) + z) := by unfold x s; module + rw [eq, scale p (by norm_num), show x - z = s • (z + w) by unfold x; abel, scale p hs] + unfold f at h he + unfold x s at * + linarith + +private theorem tradeoff {t u X Y a b : ℝ} + (ha : a ≤ (t + u) * X) (hb : b ≤ (t + u) * Y) + (hc : ∀ α β : ℝ, 0 < α → 0 < β → 2 * (t ^ 2 + u ^ 2) < α ^ 2 + β ^ 2 → + a ≤ α * X ∨ b ≤ β * Y) : + a + b ≤ (t ^ 2 + u ^ 2) / 2 + X ^ 2 + Y ^ 2 := by + let s := (t ^ 2 + u ^ 2) / 2 + have hA : a - X ^ 2 ≤ s := by + unfold s + linarith only [ha, sq_nonneg (t - X), sq_nonneg (u - X)] + have hB : b - Y ^ 2 ≤ s := by + unfold s + linarith only [hb, sq_nonneg (t - Y), sq_nonneg (u - Y)] + change a + b ≤ s + X ^ 2 + Y ^ 2 + by_contra! bad + let δ := (a + b - s - X ^ 2 - Y ^ 2) / 3 + have hd : 0 < δ := by unfold δ; linarith + let A := a - X ^ 2 - δ + let B := b - Y ^ 2 - δ + have h₁ : 0 < A := by unfold A δ; linarith + have h₂ : 0 < B := by unfold B δ; linarith + have h₃ : s < A + B := by unfold A B δ; linarith + have h₄ := Real.sq_sqrt h₁.le + have h₅ := Real.sq_sqrt h₂.le + obtain h | h := hc (2 * Real.sqrt A) (2 * Real.sqrt B) (by positivity) (by positivity) + (by unfold s at h₃; linarith only [h₃, h₄, h₅]) + · have he : A + X ^ 2 < a := by unfold A; linarith + linarith only [h, he, h₄, sq_nonneg (Real.sqrt A - X)] + · have he : B + Y ^ 2 < b := by unfold B; linarith + linarith only [h, he, h₅, sq_nonneg (Real.sqrt B - Y)] + +private theorem gain_bound (hc : CutBound (fun x y => p (x - y))) (x y z w : V) + {t u : ℝ} (ht : 0 < t) (hu : 0 < u) : + t * (2 * p x - p (x - z) - p (x - w)) + u * (2 * p y - p (y - z) - p (y + w)) ≤ + (t ^ 2 + u ^ 2) / 2 + p z ^ 2 + p w ^ 2 := by + let f := fun a b : V => p a - p (a - b) + have hf (a b : V) : f a b ≤ p b := by + have h := map_add_le_add p (a - b) b + rw [sub_add_cancel] at h + unfold f + linarith + have hsum (z w : V) (hw : p w = p z) : t * f x z + u * f y w ≤ (t + u) * p z := by + rw [add_mul] + exact add_le_add (mul_le_mul_of_nonneg_left (hf _ _) ht.le) + (mul_le_mul_of_nonneg_left ((hf _ _).trans_eq hw) hu.le) + have h := tradeoff (hsum z z rfl) (hsum w (-w) (map_neg_eq_map _ _)) (by + intro α β hα hβ h + have h' := hc x (-x) y (-y) z (-z) w (-w) t u α β ht hu hα hβ h + have hd (a : V) : p (a - -a) = 2 * p a := by + rw [sub_neg_eq_add, ← two_smul ℝ, scale p (by norm_num)] + have hm (a b : V) : p (-a - -b) = p (a - b) := by + rw [show -a - -b = -(a - b) by abel, map_neg_eq_map] + have hm' : p (-y - w) = p (y - -w) := by simpa using hm y (-w) + simp only [hd, hm, hm'] at h' + rcases h' with h' | h' + · left; unfold f; linarith only [h'] + · right; unfold f; linarith only [h']) + simp only [f, sub_neg_eq_add] at h + linarith only [h] + +private theorem parallelogram_le (hc : CutBound (fun x y => p (x - y))) (z w : V) : + p (z + w) ^ 2 + p (z - w) ^ 2 ≤ 2 * (p z ^ 2 + p w ^ 2) := by + let t := p (z + w) + let u := p (z - w) + have h (x y : V) : p (x + y) ^ 2 ≤ 2 * (p x ^ 2 + p y ^ 2) := by + have he := pow_le_pow_left₀ (apply_nonneg p _) (map_add_le_add p x y) 2 + linarith only [he, sq_nonneg (p x - p y)] + rcases (apply_nonneg p (z + w)).eq_or_lt with ht | ht + · simpa [← ht, sub_eq_add_neg] using h z (-w) + rcases (apply_nonneg p (z - w)).eq_or_lt with hu | hu + · simpa [← hu] using h z w + apply le_of_forall_pos_le_add + intro ε hε + have hd : 0 < ε / (2 * (t + u)) := div_pos hε (by unfold t u; positivity) + obtain ⟨x, hx⟩ := gain p z w hd + obtain ⟨y, hy⟩ := gain p z (-w) hd + rw [← sub_eq_add_neg, sub_neg_eq_add] at hy + have he := div_mul_cancel₀ ε (show 2 * (t + u) ≠ 0 by unfold t u; positivity) + dsimp only [t, u] at hx hy he + linarith only [he, mul_le_mul_of_nonneg_left hx ht.le, mul_le_mul_of_nonneg_left hy hu.le, + gain_bound p hc x y z w ht hu] + +theorem parallelogram_of_cuts (hc : CutBound (fun x y => p (x - y))) (z w : V) : + p (z + w) ^ 2 + p (z - w) ^ 2 = 2 * (p z ^ 2 + p w ^ 2) := by + refine le_antisymm (parallelogram_le p hc z w) ?_ + have h := parallelogram_le p hc (z + w) (z - w) + rw [show z + w + (z - w) = (2 : ℝ) • z by module, show z + w - (z - w) = (2 : ℝ) • w by module, + scale p (by norm_num), scale p (by norm_num)] at h + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Geodesic sectors + +Two rays from a common origin whose equal-time distances grow linearly +span an affine quadrant. Only Busemann convexity is used here. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {Y : Type*} [PseudoMetricSpace Y] + +/-- Requires `dist x z = t.val * dist x y ∧ dist z y = (1 - t.val) * dist x y`. -/ +def Divides (t : Fraction) (x y z : Y) : Prop := + dist x z = t.val * dist x y ∧ dist z y = (1 - t.val) * dist x y + +/-- The condition `∀ (t : Fraction) (x y m a b n : Y), Divides t x y m → Divides t a b n → dist +m n ≤ (1 - t.val) * dist x a + t.val * dist y b` on the specified data. -/ +def Busemann (Y : Type*) [PseudoMetricSpace Y] : Prop := + ∀ (t : Fraction) (x y m a b n : Y), Divides t x y m → Divides t a b n → + dist m n ≤ (1 - t.val) * dist x a + t.val * dist y b + +/-- The condition `∀ (t : Fraction) (x y : Y), ∃ m, Divides t x y m` on the specified data. -/ +def Segments (Y : Type*) [PseudoMetricSpace Y] : Prop := + ∀ (t : Fraction) (x y : Y), ∃ m, Divides t x y m + +theorem Divides.of_le {t : Fraction} {x y z : Y} (hx : dist x z ≤ t.val * dist x y) + (hy : dist z y ≤ (1 - t.val) * dist x y) : Divides t x y z := by + have h := dist_triangle x z y + constructor <;> linarith + +theorem Divides.same (t : Fraction) (x : Y) : Divides t x x x := by simp [Divides] + +theorem Busemann.unique (h : Busemann Y) {t : Fraction} {x y z w : Y} + (hz : Divides t x y z) (hw : Divides t x y w) : dist z w = 0 := by + refine le_antisymm ?_ dist_nonneg + simpa using h t _ _ _ _ _ _ hz hw + +theorem Divides.replace {t : Fraction} {x y z w : Y} (h : Divides t x y z) + (he : dist z w = 0) : Divides t x y w := by + apply Divides.of_le + · linarith [h.1, dist_triangle x z w] + · rw [dist_comm] at he + linarith [h.2, dist_triangle w z y] + +/-- The quantity computed by `(1 - t.val) • x + t.val • y`. -/ +def mix {V : Type*} [AddCommGroup V] [Module ℝ V] (t : Fraction) (x y : V) : V := + (1 - t.val) • x + t.val • y + +/-- Indexes the coord by the coordinates of `ℝ × ℝ`. -/ +abbrev Coord := ℝ × ℝ + +/-- The condition `∀ (t : Fraction) (x y : Coord), 0 ≤ x → 0 ≤ y → Divides t (F x) (F y) (F (mix +t x y))` on the specified data. -/ +def AffineSector (F : Coord → Y) : Prop := + ∀ (t : Fraction) (x y : Coord), 0 ≤ x → 0 ≤ y → Divides t (F x) (F y) (F (mix t x y)) + +/-- The condition `∀ s t : ℝ, 0 ≤ s → 0 ≤ t → dist (f s) (f t) = |s - t| * A` on the specified +data. -/ +def Ray (f : ℝ → Y) (A : ℝ) : Prop := + ∀ s t : ℝ, 0 ≤ s → 0 ≤ t → dist (f s) (f t) = |s - t| * A + +theorem Ray.divides {f : ℝ → Y} {A s t : ℝ} (hf : Ray f A) + (hs : 0 ≤ s) (ht : 0 ≤ t) (u : Fraction) : Divides u (f s) (f t) (f (mix u s t)) := by + have hm : 0 ≤ mix u s t := add_nonneg (mul_nonneg (sub_nonneg.mpr u.2.2) hs) + (mul_nonneg u.2.1 ht) + rw [Divides, hf _ _ hs hm, hf _ _ hm ht, hf _ _ hs ht] + have eq : s - mix u s t = u.val * (s - t) := by unfold mix; simp only [smul_eq_mul]; ring + have eq' : mix u s t - t = (1 - u.val) * (s - t) := by unfold mix; simp only [smul_eq_mul]; ring + rw [eq, eq', abs_mul, abs_mul, abs_of_nonneg u.2.1, abs_of_nonneg (sub_nonneg.mpr u.2.2)] + exact ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩ + +private def weight (v : Coord) : ℝ := v.1 + v.2 + +private theorem mix_pos (t : Fraction) {x y : Coord} (hx : 0 ≤ x) (hy : 0 ≤ y) : + 0 ≤ mix t x y := + add_nonneg (smul_nonneg (sub_nonneg.mpr t.2.2) hx) (smul_nonneg t.2.1 hy) + +/-- Boundary values are preserved up to zero distance, since the +ambient metric need not separate points. -/ +theorem exists_sector (h : Busemann Y) (hs : Segments Y) + {a b : ℝ → Y} {A B c : ℝ} (ha : Ray a A) (hb : Ray b B) + (he : ∀ r, 0 ≤ r → dist (a r) (b r) = r * c) : + ∃ F : Coord → Y, AffineSector F ∧ + ∀ r, 0 ≤ r → dist (F (r, 0)) (a r) = 0 ∧ dist (F (0, r)) (b r) = 0 := by + have hw (v : Coord) (hv : 0 ≤ v) : 0 ≤ weight v := add_nonneg hv.1 hv.2 + have hn (v : Coord) (hv : 0 ≤ v) : ∃ t : Fraction, t.val * weight v = v.2 := by + rcases (hw v hv).eq_or_lt with hz | hp + · have hv₁ : 0 ≤ v.1 := hv.1 + have hv₂ : 0 ≤ v.2 := hv.2 + exact ⟨⟨0, by norm_num, by norm_num⟩, by unfold weight at hz; dsimp; linarith⟩ + refine ⟨⟨v.2 / weight v, div_nonneg hv.2 hp.le, (div_le_one hp).mpr ?_⟩, + div_mul_cancel₀ _ hp.ne'⟩ + exact le_add_of_nonneg_left hv.1 + let s := fun v : Coord => if hv : 0 ≤ v then (hn v hv).choose else ⟨0, by norm_num, by norm_num⟩ + let F := fun v => (hs (s v) (a (weight v)) (b (weight v))).choose + have hF (v : Coord) : Divides (s v) (a (weight v)) (b (weight v)) (F v) := + (hs _ _ _).choose_spec + have he' (v : Coord) (hv : 0 ≤ v) : + dist (a (weight v)) (F v) = v.2 * c ∧ dist (F v) (b (weight v)) = v.1 * c := by + have heq : (s v).val * weight v = v.2 := by + simp only [s, dite_eq_left hv] + exact (hn v hv).choose_spec + have hh := hF v + unfold Divides at hh + rw [he _ (hw _ hv)] at hh + constructor + · rw [hh.1, ← mul_assoc, heq] + · rw [hh.2, ← mul_assoc, sub_mul, one_mul, heq, weight, add_sub_cancel_right] + refine ⟨F, ?_, ?_⟩ + · intro t x y hx hy + let v := mix t x y + have hv := mix_pos t hx hy + have eq : weight v = mix t (weight x) (weight y) := by + change (1 - t.val) * x.1 + t.val * y.1 + ((1 - t.val) * x.2 + t.val * y.2) = + (1 - t.val) * (x.1 + x.2) + t.val * (y.1 + y.2) + ring + obtain ⟨m, hm⟩ := hs t (F x) (F y) + have h₁ := h t _ _ _ _ _ _ (ha.divides (hw _ hx) (hw _ hy) t) hm + have h₂ := h t _ _ _ _ _ _ hm (hb.divides (hw _ hx) (hw _ hy) t) + rw [← eq, (he' x hx).1, (he' y hy).1] at h₁ + rw [← eq, (he' x hx).2, (he' y hy).2] at h₂ + apply hm.replace + apply h.unique _ (hF v) + apply Divides.of_le + · rw [← (hF v).1, (he' _ hv).1] + change _ ≤ ((1 - t.val) * x.2 + t.val * y.2) * c + linarith + · rw [← (hF v).2, (he' _ hv).2] + change _ ≤ ((1 - t.val) * x.1 + t.val * y.1) * c + linarith + · intro r hr + constructor + · simpa [weight, dist_comm] using (he' (r, 0) ⟨hr, le_rfl⟩).1 + · simpa [weight] using (he' (0, r) ⟨le_rfl, hr⟩).2 + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Four-terminal wire prices from shifted crossings + +Each summand of the crossing moves to the two centers of its cut. +There its separated factorization costs a single wire. All placements +allow coincidences, including at the two centers. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral + +private abbrev Role := Bool ⊕ Bool +private abbrev leg (a b : ℕ) : Role → Type := Sum.elim (fun _ => Fin a) (fun _ => Fin b) +private instance (a b : ℕ) : ∀ s, Fintype (leg a b s) := + Sum.rec (fun _ => inferInstanceAs (Fintype (Fin a))) (fun _ => inferInstanceAs (Fintype (Fin b))) + +variable {K : Type} [Field K] {a b r : ℕ} + +private abbrev Row (a b : ℕ) := ∀ s, leg a b s + +private def ind (i i' : Fin a) (j j' : Fin b) : K := + if i = i' ∧ j = j' then 1 else 0 + +private def matchRow (a b : ℕ) (x : Row a b) : K := + ind (a := a) (b := b) (x (.inl true)) (x (.inl false)) (x (.inr true)) (x (.inr false)) + +private abbrev pairWire (K : Type) [Field K] (a b : ℕ) : Raw K Role where + leg := leg a b + term := Fin a × Fin b + factor i s := match s with + | .inl _ => fun (x : Fin a) => if x = i.1 then 1 else 0 + | .inr _ => fun (x : Fin b) => if x = i.2 then 1 else 0 + +private theorem pairWire_coeff (x : Row a b) : (pairWire K a b).coeff x = matchRow a b x := by + unfold Raw.coeff + erw [Fintype.sum_prod_type] + simp only [Fintype.prod_sum_type, Fintype.prod_bool] + have key (i i' : Fin a) (j j' : Fin b) : + (∑ p : Fin a, ∑ q : Fin b, + ((if i = p then (1 : K) else 0) * (if i' = p then 1 else 0)) * + ((if j = q then 1 else 0) * (if j' = q then 1 else 0))) = ind i i' j j' := by + rw [← Finset.sum_mul_sum] + by_cases h : i = i' <;> simp [mul_ite, ind, h] + exact key _ _ _ _ + +private theorem crossing_pair : + Tensor.wire K (.inl true : Role) (.inl false) a * + Tensor.wire K (.inr true) (.inr false) b ≤ + Tensor.ofRaw (Raw.ofTable (leg a b) (matchRow a b)) := by + have e : pairWire K a b ≈ Raw.ofTable (leg a b) (matchRow a b) := + Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => + (pairWire_coeff x).trans (Raw.coeff_ofTable _ _ x).symm + rw [← Tensor.ofRaw_eq e] + refine Raw.Restricts.rows (Equiv.refl _) ?_ + intro s x + change Fin a × Fin b at x + cases s with + | inl s => + by_cases h : x.2.val = 0 + · refine .inl ⟨x.1, fun i => ?_⟩ + change Fin a × Fin b at i + change (if x.1 = Raw.port {Sum.inl true, Sum.inl false} (.inl s : Role) i.1 then (1 : K) else + 0) * + (if x.2 = Raw.port {Sum.inr true, Sum.inr false} (.inl s : Role) i.2 then 1 else 0) = + if x.1 = i.1 then 1 else 0 + cases s <;> simp [Raw.port, Fin.ext_iff, h] + · refine .inr (fun i => ?_) + change Fin a × Fin b at i + change _ * (if x.2 = Raw.port {Sum.inr true, + Sum.inr false} (.inl s : Role) i.2 then (1 : K) else 0) = 0 + simp [Raw.port, Fin.ext_iff, h] + | inr s => + by_cases h : x.1.val = 0 + · refine .inl ⟨x.2, fun i => ?_⟩ + change Fin a × Fin b at i + change (if x.1 = Raw.port {Sum.inl true, Sum.inl false} (.inr s : Role) i.1 then (1 : K) else + 0) * + (if x.2 = Raw.port {Sum.inr true, Sum.inr false} (.inr s : Role) i.2 then 1 else 0) = + if x.2 = i.2 then 1 else 0 + cases s <;> simp [Raw.port, Fin.ext_iff, h] + · refine .inr (fun i => ?_) + change Fin a × Fin b at i + change (if x.1 = Raw.port {Sum.inl true, Sum.inl false} (.inr s : Role) i.1 then (1 : K) else + 0) * _ = 0 + simp [Raw.port, Fin.ext_iff, h] + +private def cut (σ : Bool) (A B : Fin a → Fin b → Fin r → K) (x : Row a b) : K := + ∑ j, A (x (.inl true)) (x (.inr σ)) j * B (x (.inl false)) (x (.inr (!σ))) j + +variable {S : Type} [Fintype S] [DecidableEq S] [Nonempty S] + +private theorem cut_price (f : Tensor K S →+* ℝ) (hf : Monotone f) (s : Role → S) + (σ : Bool) (A B : Fin a → Fin b → Fin r → K) (z z' : S) : + f (Tensor.place s (Tensor.ofRaw (Raw.ofTable (leg a b) (cut σ A B)))) ≤ + f (Tensor.wire K z z' r) * + (f (Tensor.wire K (s (.inl true)) z a) * f (Tensor.wire K (s (.inl false)) z' a) * + (f (Tensor.wire K (s (.inr σ)) z b) * f (Tensor.wire K (s (.inr (!σ))) z' b))) := by + let X := Raw.ofTable (leg a b) (cut σ A B) + let G (s : Role) := s = .inl true ∨ s = .inr σ + let c (s : Role) := if G s then z else z' + have h : Tensor.place c (Tensor.ofRaw X) ≤ Tensor.wire K z z' r := by + let L j (x : Row a b) := A (x (.inl true)) (x (.inr σ)) j + let R j (x : Row a b) := B (x (.inl false)) (x (.inr (!σ))) j + have hL j x y (h : ∀ i, G i → x i = y i) : L j x = L j y := by + unfold L + rw [h _ (Or.inl rfl), h _ (Or.inr rfl)] + have hR j x y (h : ∀ i, ¬ G i → x i = y i) : R j x = R j y := by + unfold R + rw [h (.inl false) (by simp [G]), h (.inr (!σ)) (by cases σ <;> simp [G])] + simpa only [Fintype.card_fin] using + Tensor.separated_le (leg a b) (cut σ A B) G L R (fun _ => rfl) hL hR z z' + let W := ∏ i, Tensor.wire K (c i) (s i) (Fintype.card (X.leg i)) + have hm := hf (Tensor.transport X c s) + change f (Tensor.place s (Tensor.ofRaw X)) ≤ f (Tensor.place c (Tensor.ofRaw X) * W) at hm + rw [map_mul] at hm + have hW : 0 ≤ f W := by simpa using hf (Tensor.zero_le W) + refine (hm.trans (mul_le_mul_of_nonneg_right (hf h) hW)).trans_eq ?_ + congr 1 + unfold W + rw [map_prod, Fintype.prod_sum_type, Fintype.prod_bool, Fintype.prod_bool] + have hl (i : Bool) : Fintype.card (X.leg (.inl i)) = a := Fintype.card_fin _ + have hr (i : Bool) : Fintype.card (X.leg (.inr i)) = b := Fintype.card_fin _ + simp only [hl, hr] + cases σ <;> simp [c, G, Tensor.wire_comm, mul_comm] + +private def pairValue (f : Tensor K S →+* ℝ) (x x' y y' z z' : S) (a b r : ℕ) := + f (Tensor.wire K z z' r) * + (f (Tensor.wire K x z a) * f (Tensor.wire K x' z' a) * + (f (Tensor.wire K y z b) * f (Tensor.wire K y' z' b))) + +private theorem crossing_price (f : Tensor K S →+* ℝ) (hf : Monotone f) + (x x' y y' z z' w w' : S) {p q : ℕ} (h : Sphere.Crossing K a b p q) : + f (Tensor.wire K x x' a) * f (Tensor.wire K y y' b) ≤ + pairValue f x x' y y' z z' a b p + pairValue f x x' y' y w w' a b q := by + obtain ⟨A, B, C, D, hab⟩ := h + let s : Role → S := Sum.elim (fun i => if i then x else x') (fun j => if j then y else y') + let V := fun i : Bool => if i then cut true A B else cut false C D + have he (u : Row a b) : matchRow a b u = ∑ i : Bool, (1 : K) * V i u := by + rw [Fintype.sum_bool, one_mul, one_mul] + exact hab _ _ _ _ + have hv := Tensor.span_le (leg a b) (matchRow a b) V (fun _ => 1) he + rw [Fintype.sum_bool] at hv + have H := hf ((Tensor.place_mono s (crossing_pair.trans hv)).trans (Tensor.place_add_le s _ _)) + rw [Tensor.place_mul, Tensor.place_wire, Tensor.place_wire, f.map_mul, f.map_add] at H + exact H.trans (add_le_add (cut_price f hf s true A B z z') (cut_price f hf s false C D w w')) + +private theorem crossing_trim {p q a' b' : ℕ} (h : Sphere.Crossing K a b p q) + (ha : a' ≤ a) (hb : b' ≤ b) : Sphere.Crossing K a' b' p q := by + obtain ⟨A, B, C, D, H⟩ := h + let L {r : ℕ} (M : Fin a → Fin b → Fin r → K) (i : Fin a') (j : Fin b') := + M (Fin.castLE ha i) (Fin.castLE hb j) + refine ⟨L A, L B, L C, L D, fun i i' j j' => ?_⟩ + simpa [L] using H (Fin.castLE ha i) (Fin.castLE ha i') (Fin.castLE hb j) (Fin.castLE hb j') + +private theorem log_bound {v : ℝ} (hv : 0 ≤ v) : + let a := ⌈Real.exp v⌉₊ + v ≤ Real.log (a : ℝ) ∧ Real.log (a : ℝ) ≤ v + 1 := by + have hp := Real.exp_pos v + have ha := Nat.le_ceil (Real.exp v) + constructor + · simpa using Real.log_le_log hp ha + · apply (Real.log_le_iff_le_exp (hp.trans_le ha)).mpr + rw [Real.exp_add] + have h := Nat.ceil_lt_add_one hp.le + have h₁ := Real.add_one_le_exp v + have h₂ := mul_le_mul_of_nonneg_left (Real.add_one_le_exp 1) hp.le + linarith + +omit [Nonempty S] in +private theorem finite_cut (f : Tensor K S →+* ℝ) (hf : Monotone f) + (x x' y y' z z' : S) {t u α n : ℝ} (ht : 0 ≤ t * n) (hu : 0 ≤ u * n) + (ha : a = ⌈Real.exp (t * n)⌉₊) (hb : b = ⌈Real.exp (u * n)⌉₊) + (hr : 0 < r) (hr' : (r : ℝ) ≤ Real.exp (α * n)) + (h : f (Tensor.wire K x x' a) * f (Tensor.wire K y y' b) ≤ + 2 * pairValue f x x' y y' z z' a b r) : + let d := Tensor.dist f + n * (t * (d x x' - d x z - d x' z') + u * (d y y' - d y z - d y' z') - α * d z z') ≤ 5 := by + have ha' : 0 < a := by rw [ha]; positivity + have hb' : 0 < b := by rw [hb]; positivity + have pos (v w : S) (m : ℕ) (hm : 0 < m) : 0 < f (Tensor.wire K v w m) := by + rw [Tensor.price_wire f hf v w hm] + exact Real.rpow_pos_of_pos (Nat.cast_pos.mpr hm) _ + have H := Real.log_le_log (mul_pos (pos _ _ _ ha') (pos _ _ _ hb')) h + unfold pairValue at H + have h₀ := pos z z' _ hr + have h₁ := pos x z _ ha' + have h₂ := pos x' z' _ ha' + have h₃ := pos y z _ hb' + have h₄ := pos y' z' _ hb' + have h₅ := pos x x' _ ha' + have h₆ := pos y y' _ hb' + simp (disch := positivity) only [Real.log_mul] at H + have L (v w : S) (m : ℕ) (hm : 0 < m) : + Real.log (f (Tensor.wire K v w m)) = Tensor.dist f v w * Real.log m := by + rw [Tensor.price_wire f hf v w hm, Real.log_rpow (Nat.cast_pos.mpr hm)] + have cost (v w : S) {m : ℕ} {l : ℝ} (hl : 0 ≤ l) (hm : m = ⌈Real.exp l⌉₊) : + Tensor.dist f v w * l ≤ Real.log (f (Tensor.wire K v w m)) ∧ + Real.log (f (Tensor.wire K v w m)) ≤ Tensor.dist f v w * l + 1 := by + rw [L _ _ _ (by rw [hm]; positivity), hm] + obtain ⟨hl, hu⟩ := log_bound hl + have hpos := Tensor.dist_nonneg f hf v w + refine ⟨mul_le_mul_of_nonneg_left hl hpos, ?_⟩ + linarith only [mul_le_mul_of_nonneg_left hu hpos, Tensor.dist_le_one f hf v w] + have h₇ : Real.log (f (Tensor.wire K z z' r)) ≤ Tensor.dist f z z' * (α * n) := by + rw [L _ _ _ hr] + exact mul_le_mul_of_nonneg_left ((Real.log_le_iff_le_exp (Nat.cast_pos.mpr hr)).mpr hr') + (Tensor.dist_nonneg f hf _ _) + dsimp only + linarith only [H, h₇, Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2), + (cost x x' ht ha).1, (cost y y' hu hb).1, (cost x z ht ha).2, + (cost x' z' ht ha).2, (cost y z hu hb).2, (cost y' z' hu hb).2] + +/-- Remove the constant loss by using arbitrarily large shifted crossings. -/ +theorem shifted_metric (H : Sphere.ShiftedCrossing K) (f : Tensor K S →+* ℝ) + (hf : Monotone f) : CutBound (Tensor.dist f) := by + intro x x' y y' z z' w w' t u α β ht hu hα hβ hquad + by_contra! h + let d := Tensor.dist f + let v := t * (d x x' - d x z - d x' z') + u * (d y y' - d y z - d y' z') - α * d z z' + let v' := t * (d x x' - d x w - d x' w') + u * (d y y' - d y w' - d y' w) - β * d w w' + have hv : 0 < v := sub_pos.mpr h.1 + have hv' : 0 < v' := sub_pos.mpr h.2 + obtain ⟨n, a, b, p, q, hn, hp, hq, ha, hb, hp', hq', hx⟩ := + H t u α β ht hu hα hβ hquad (max (6 / v) (6 / v')) + have h₁ := (div_le_iff₀ hv).mp ((le_max_left _ _).trans hn) + have h₂ := (div_le_iff₀ hv').mp ((le_max_right _ _).trans hn) + have hn' : 0 ≤ n := (div_pos (by norm_num : (0 : ℝ) < 6) hv).le.trans ((le_max_left _ _).trans hn) + have ht' := mul_nonneg ht.le hn' + have hu' := mul_nonneg hu.le hn' + have h₃ := crossing_price f hf x x' y y' z z' w w' + (crossing_trim hx (Nat.ceil_le.mpr ha) (Nat.ceil_le.mpr hb)) + have split (a b c : ℝ) (h : a ≤ b + c) : a ≤ 2 * b ∨ a ≤ 2 * c := by + by_contra! he + linarith + rcases split _ _ _ h₃ with hl | hr + · have hu := finite_cut f hf x x' y y' z z' ht' hu' rfl rfl hp hp' hl + change n * v ≤ 5 at hu + linarith + · rw [Tensor.wire_comm K y y'] at hr + have hu := finite_cut f hf x x' y' y w w' ht' hu' rfl rfl hq hq' hr + dsimp only at hu + rw [Tensor.dist_comm f y' y] at hu + unfold v' d at h₂ + linarith only [hu, h₂] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometrySharp.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometrySharp.lean new file mode 100644 index 0000000000..4497f242ac --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometrySharp.lean @@ -0,0 +1,903 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Partitions +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Analysis.SpecificLimits.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Finite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.WireRecovery +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Chord +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryComparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.PartitionsPlane +public import Mathlib.Algebra.BigOperators.Field +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryPrices +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Fields +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.MovingForms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Seating +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Shared + +/-! +# Uniform displacement from incidence + +Average the plane sites over the incident planes at each line. The +projective estimate and the variance inequality then bound the mean +square deviation of these line sites by 1/18 of the line-plane energy. +The single-plane displacement estimate loses 160/9. Their product +80/81 is strictly less than one, so iteration gives a common fixed point. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators Topology +open Filter + +variable {Y E L P D A B G : Type*} [MetricSpace Y] + +open scoped Classical in +private theorem expect_fiber [Fintype E] [Finite L] + (l : E → L) (f g : E → ℝ) + (h : ∀ i, (𝔼 e : {e // l e = i}, f e.val) ≤ (𝔼 e : {e // l e = i}, g e.val)) : + (𝔼 e, f e) ≤ (𝔼 e, g e) := by + let : Fintype L := Fintype.ofFinite L + simp only [Fintype.expect_eq_sum_div_card] + apply div_le_div_of_nonneg_right _ (by positivity) + rw [← Fintype.sum_fiberwise l f, ← Fintype.sum_fiberwise l g] + apply Finset.sum_le_sum + intro i _ + simpa only [Fintype.card_mul_expect] using + mul_le_mul_of_nonneg_left (h i) (show 0 ≤ (Fintype.card {e // l e = i} : ℝ) by positivity) + +variable [Group G] [MulAction G Y] [IsIsometricSMul G Y] + [Fintype P] [Nonempty P] [Fintype L] [Nonempty L] [Fintype D] [Nonempty D] + +open scoped Classical in +private def NearPlanes (K : P → Subgroup G) (x : Y) (R : ℝ) : Prop := + ∃ z : P → Y, (∀ p, Fixes (K p) (z p)) ∧ (𝔼 p, dist x (z p) ^ 2) ≤ R + +open scoped Classical in +/-- One simultaneous update, using two sets of barycenters. -/ +private theorem contract [CompleteSpace Y] (C : Comparison Y) (l : P × D → L) + (hs : Function.Surjective l) (hi : Incidence Y l Prod.fst) + (H : Subgroup G) (S : L → Subgroup G) (K : P → Subgroup G) + (h₀ : ∀ i, H ≤ S i) (h₁ : ∀ e, S (l e) ≤ K e.1) + (hp : ∀ (p : P) (b : Y) (y : L → Y), Fixes H b → (∀ i, Fixes (S i) (y i)) → + ∃ z, Fixes (K p) z ∧ 9 * dist b z ^ 2 ≤ 160 * (𝔼 d, dist b (y (l (p, d))) ^ 2)) + {x : Y} {R : ℝ} (hx : NearPlanes K x R) : + ∃ b, NearPlanes K b (80 / 81 * R) ∧ dist x b ^ 2 ≤ 9 * R := by + obtain ⟨z, hz, hr⟩ := hx + let u (i : L) := {e : P × D // l e = i} + have (i : L) : Nonempty (u i) := by + obtain ⟨e, he⟩ := hs i + exact ⟨⟨e, he⟩⟩ + choose y hy using (fun i => C.bary (fun e : u i => z e.val.1)) + have hf (i : L) : Fixes (S i) (y i) := by + intro g hg + apply (hy i).fixed + intro e + exact hz _ g (h₁ e.val (by rwa [e.property])) + obtain ⟨b, hb⟩ := C.bary y + have hb' : Fixes H b := fun g hg => hb.fixed (fun i => hf i g (h₀ i hg)) + let E := 𝔼 e : P × D, dist (y (l e)) (z e.1) ^ 2 + let X := fun a : Y => 𝔼 e : P × D, dist a (y (l e)) ^ 2 + let Z := fun a : Y => 𝔼 p : P, dist a (z p) ^ 2 + have hZ (a : Y) : (𝔼 e : P × D, dist a (z e.1) ^ 2) = Z a := by + rw [expect_pair] + simp only [Fintype.expect_const, Z] + have hv (a : Y) : E + X a ≤ Z a := by + rw [← hZ] + unfold E X + rw [← Finset.expect_add_distrib] + apply expect_fiber l + intro i + have he (e : u i) : l e.val = i := e.property + simp only [he, Finset.expect_add_distrib, Fintype.expect_const] + rw [dist_comm a (y i)] + exact hy i a + have hX (a : Y) : 0 ≤ X a := Finset.expect_nonneg (fun _ _ => sq_nonneg _) + have hh : 9 * (X b + Z b) ≤ 10 * E := by + rw [← hZ] + exact hi.estimate z hb + change Z x ≤ R at hr + have hE : E ≤ R := by linarith [hv x, hX x] + have hxb : 18 * X b ≤ R := by linarith [hv b] + choose w hw hw' using fun p => hp p b y hb' hf + refine ⟨b, ⟨w, hw, ?_⟩, ?_⟩ + · have hv' := Finset.expect_le_expect (s := Finset.univ) fun p _ => hw' p + simp only [← Finset.mul_expect] at hv' + unfold X at hxb + rw [expect_pair] at hxb + linarith only [hxb, hv'] + · have hh' (p : P) : dist x b ^ 2 ≤ 2 * dist x (z p) ^ 2 + 2 * dist b (z p) ^ 2 := by + rw [dist_comm b] + exact dist_sq_triangle _ _ _ + have ht := Finset.expect_le_expect (s := Finset.univ) fun p _ => hh' p + simp only [Fintype.expect_const, Finset.expect_add_distrib, ← Finset.mul_expect] at ht + change dist x b ^ 2 ≤ 2 * Z x + 2 * Z b at ht + have hR : 0 ≤ R := (Finset.expect_nonneg (fun _ _ => sq_nonneg _)).trans hr + linarith [hX b] + +open scoped Classical in +private theorem NearPlanes.bound {K : P → Subgroup G} {x : Y} {R : ℝ} + (h : NearPlanes K x R) (i : P) {g : G} (hg : g ∈ K i) : + dist x (g • x) ^ 2 ≤ 4 * Fintype.card P * R := by + obtain ⟨z, hz, hr⟩ := h + have hb := mul_le_mul_of_nonneg_left hr (show 0 ≤ (Fintype.card P : ℝ) by positivity) + rw [Fintype.card_mul_expect] at hb + have hd : dist x (z i) ^ 2 ≤ ∑ p, dist x (z p) ^ 2 := + Finset.single_le_sum (fun p _ => sq_nonneg (dist x (z p))) (Finset.mem_univ i) + have ht := dist_sq_triangle x (z i) (g • x) + have he : dist (z i) (g • x) = dist x (z i) := by + rw [← hz i g hg, dist_smul, dist_comm, hz i g hg] + rw [he] at ht + linarith + +open scoped Classical in +/-- Summing the displacements of the contracting placements gives an +absolute bound, independent of the number of planes. -/ +private theorem common_fixed [CompleteSpace Y] (K : P → Subgroup G) + (hgen : iSup K = ⊤) (x : Y) (hx : NearPlanes K x 1) + (hc : ∀ (x : Y) (R : ℝ), NearPlanes K x R → + ∃ b, NearPlanes K b (80 / 81 * R) ∧ dist x b ^ 2 ≤ 9 * R) : + ∃ b, (∀ g : G, g • b = b) ∧ dist x b ≤ 600 := by + let r : ℝ := 80 / 81 + let s : ℝ := 199 / 200 + have hr : 0 ≤ r := by norm_num [r] + have hr' : r < 1 := by norm_num [r] + have hs : 0 ≤ s := by norm_num [s] + have hs' : s < 1 := by norm_num [s] + have hrs : r ≤ s ^ 2 := by norm_num [r, s] + let S (n : ℕ) := {y : Y // NearPlanes K y (r ^ n)} + have hnext (n : ℕ) (a : S n) : ∃ b : S (n + 1), dist a.val b.val ≤ 3 * s ^ n := by + obtain ⟨b, hb, hd⟩ := hc _ _ a.property + refine ⟨⟨b, by rwa [pow_succ']⟩, ?_⟩ + have hh : r ^ n ≤ (s ^ n) ^ 2 := by + rw [pow_right_comm] + exact pow_le_pow_left₀ hr hrs n + change dist a.val b ≤ _ + nlinarith [pow_nonneg hs n] + choose next hn using hnext + let u : ∀ n, S n := Nat.rec ⟨x, by rwa [pow_zero]⟩ next + let y n := (u n).val + have hm (n : ℕ) : dist (y n) (y (n + 1)) ≤ 3 * s ^ n := hn n (u n) + obtain ⟨b, hb⟩ := cauchySeq_tendsto_of_complete (cauchySeq_of_le_geometric s 3 hs' hm) + have hfix : iSup K ≤ MulAction.stabilizer G b := by + apply iSup_le + intro i g hg + have hl : Tendsto (fun n => dist (y n) (g • y n) ^ 2) atTop (𝓝 (dist b (g • b) ^ 2)) := + (hb.dist (hb.const_smul g)).pow 2 + have hu : Tendsto (fun n => 4 * (Fintype.card P : ℝ) * r ^ n) atTop (𝓝 0) := by + simpa using (tendsto_pow_atTop_nhds_zero_of_lt_one hr hr').const_mul (4 * Fintype.card P : ℝ) + have hle := le_of_tendsto_of_tendsto' hl hu (fun n => (u n).property.bound i hg) + exact (dist_eq_zero.mp (by nlinarith : dist b (g • b) = 0)).symm + rw [hgen] at hfix + refine ⟨b, fun g => hfix (Subgroup.mem_top g), ?_⟩ + have hd := dist_le_of_le_geometric_of_tendsto₀ s 3 hs' hm hb + change dist x b ≤ 3 / (1 - s) at hd + norm_num [s] at hd + exact hd + +open scoped Classical in +/-- Uniform displacement. The only group-specific inputs are generation, +nesting, and the affine partition action on each plane. -/ +theorem uniform_displacement [Fintype A] [Nonempty A] [CompleteSpace Y] + (C : Comparison Y) (l : P × D → L) (hs : Function.Surjective l) + (a : A × D → B) (hi : Incidence Y l Prod.fst) (ha : Incidence Y Prod.fst a) + (H : Subgroup G) (S : L → Subgroup G) (K : P → Subgroup G) + (h₀ : ∀ i, H ≤ S i) (h₁ : ∀ e, S (l e) ≤ K e.1) (hgen : iSup K = ⊤) + (hplane : ∀ p, ∃ σ, PlaneAction H (K p) (fun d => S (l (p, d))) a σ) + (x : Y) (hx : ∀ p g, g ∈ K p → dist x (g • x) ≤ 1) : + (∃ b, (∀ g : G, g • b = b) ∧ dist x b ≤ 600) ∧ + ∀ g : G, dist x (g • x) ≤ 1200 := by + have hstart : NearPlanes K x 1 := by + have hz (p : P) : ∃ z, Fixes (K p) z ∧ dist x z ^ 2 ≤ 1 := by + obtain ⟨z, hf, hd⟩ := C.orbit (K p) x 1 (fun g hg => by + simpa using pow_le_pow_left₀ dist_nonneg (hx p g hg) 2) + exact ⟨z, hf, by linarith⟩ + choose z hf hd using hz + exact ⟨z, hf, Finset.expect_le Finset.univ_nonempty (fun p _ => hd p)⟩ + obtain ⟨b, hb, hd⟩ := common_fixed K hgen x hstart (by + intro x R hr + refine contract C l hs hi H S K h₀ h₁ ?_ hr + intro p b y hb hy + obtain ⟨σ, hσ⟩ := hplane p + exact hσ.fixed C ha hb (fun d => y (l (p, d))) (fun d => hy _)) + refine ⟨⟨b, hb, hd⟩, ?_⟩ + intro g + have ht := dist_triangle x b (g • x) + have he : dist b (g • x) = dist x b := by rw [← hb g, dist_smul, dist_comm, hb] + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Variance survives adjoining a spectral site + +The barycenter belongs to the closure of the finite geodesic terms. +Their costs are identical in any two realizations of the same prices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral +open scoped BigOperators +variable {F A Y Z : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + [MetricSpace Y] [MetricSpace Z] + +omit [DecidableEq A] in +open scoped Classical in +theorem Bary.mem_closure {x : A → Y} {o : Y} (ho : Bary x o) (C : Comparison Y) : + o ∈ closure (Set.range (Term.eval C x)) := by + rw [Metric.mem_closure_iff] + intro ε hε + obtain ⟨n, hn⟩ := exists_nat_gt ((𝔼 i, dist o (x i) ^ 2) / ε ^ 2) + rw [div_lt_iff₀ (by positivity)] at hn + by_contra! bad + have h (u : Fin (n + 1) → A) : ε ^ 2 ≤ dist (sampleMean C.seg n (x ∘ u)) o ^ 2 := by + apply pow_le_pow_left₀ hε.le + rw [dist_comm] + apply bad + exact ⟨sampleMean Term.seg n (Term.mark ∘ u), + sampleMean_map Term.seg C.seg (Term.eval C x) (fun _ _ _ => rfl) n _⟩ + have he := Finset.expect_le_expect (s := Finset.univ) (fun u _ => h u) + rw [Fintype.expect_const] at he + linarith only [sampleMean_error C ho n, hn, sq_nonneg ε, + mul_le_mul_of_nonneg_left he (show 0 ≤ (n : ℝ) + 1 by positivity)] + +open scoped Classical in +private theorem ExtendsAt.eq_terms {x : A → Y} {y : A → Z} {P : Tensor F A → ℝ} + (hx : ExtendsAt P x) (hy : ExtendsAt P y) (C : Comparison Y) (C' : Comparison Z) + (s t : Term A) : dist (s.eval C x) (t.eval C x) ^ 2 = dist (s.eval C' y) (t.eval C' y) ^ 2 := by + obtain ⟨B, hB⟩ := (Set.finite_range (fun i : A × A => + max (dist (x i.1) (x i.2)) (dist (y i.1) (y i.2)))).bddAbove + let D := max B 1 + have hd : 0 < D := zero_lt_one.trans_le (le_max_right _ _) + have h (i j : A) : max (dist (x i) (x j)) (dist (y i) (y j)) ≤ D := + (hB ⟨(i, j), rfl⟩).trans (le_max_left _ _) + apply sub_eq_zero.mp + apply abs_nonpos_iff.mp + apply le_of_forall_pos_le_add + intro ε hε + obtain ⟨T, δ, hδ, hT⟩ := finite_terms_tests F {s, t} D hε + rw [zero_add] + exact hT C C' (hx D hd (fun i j => (le_max_left _ _).trans (h i j))) + (hy D hd (fun i j => (le_max_right _ _).trans (h i j))) (by simp [hδ.le]) + s (by simp) t (by simp) + +omit [Nonempty A] [DecidableEq A] in +open scoped Classical in +private theorem Bary.le_sum {x : A → Y} {o : Y} (h : Bary x o) (z : Y) : + (∑ i, dist o (x i) ^ 2) ≤ ∑ i, dist z (x i) ^ 2 := by + have he := le_trans (le_add_of_nonneg_right (sq_nonneg _)) (h z) + simpa only [Fintype.card_mul_expect] using + mul_le_mul_of_nonneg_left he (Nat.cast_nonneg (α := ℝ) (Fintype.card A)) + +open scoped Classical in +theorem ExtendsAt.variance [CompleteSpace Z] {x : A → Y} {y : A → Z} + {P : Tensor F A → ℝ} (hx : ExtendsAt P x) (hy : ExtendsAt P y) + (C : Comparison Y) (C' : Comparison Z) {o : Y} (ho : Bary x o) (z : Z) : + (∑ i, dist o (x i) ^ 2) ≤ ∑ i, dist z (y i) ^ 2 := by + obtain ⟨b, hb⟩ := C'.bary y + let T := {w : Z | (∑ i, dist o (x i) ^ 2) ≤ ∑ i, dist w (y i) ^ 2} + have hc : IsClosed T := isClosed_le continuous_const (by fun_prop) + have hs : Set.range (Term.eval C' y) ⊆ T := by + rintro _ ⟨a, rfl⟩ + exact (ho.le_sum (a.eval C x)).trans_eq (Finset.sum_congr rfl fun i _ => + hx.eq_terms hy C C' a (.mark i)) + exact (closure_minimal hs hc (hb.mem_closure C')).trans (hb.le_sum z) + +open scoped Classical in +private theorem ExtendsAt.ordinary [Nontrivial A] {x : A → Y} {P : Tensor F A → ℝ} + (h : ExtendsAt P x) : ∃ D, P ∈ Tensor.ordinary F A D := by + obtain ⟨d, hd, f, hf, he, _⟩ := h.prices x + let Q := Tensor.values d f + have heq : P = Q ∘ Tensor.place Sum.inl := by + funext a + apply mul_right_cancel₀ (Real.log_pos (by norm_num : (1 : ℝ) < 2)).ne' + unfold Q + rw [he, Function.comp_apply, Tensor.place_inl, Tensor.values, mul_assoc, + div_mul_cancel₀ _ (Real.log_pos (by norm_num)).ne'] + have hh : Q ∈ Tensor.ordinary F (A ⊕ A) d := ⟨d, ⟨hd, le_rfl⟩, f, hf, rfl⟩ + rw [heq] + refine ⟨d * Fintype.card A, Tensor.ordinary_restrict hh Sum.inl (fun a b => ?_)⟩ + exact (mul_le_mul_of_nonneg_left (Tensor.dist_le_one _ hf _ _) hd).trans_eq (mul_one d) + +open scoped Classical in +theorem SpectralSpace.variance_test (S : SpectralSpace F Y) (C : Comparison Y) : VarianceTest F Y + := by + intro A _ _ _ x o ho + obtain ⟨P, _, hP⟩ := S A x + change ExtendsAt P x at hP + obtain ⟨_, d, ⟨hd, _⟩, f, hf, rfl⟩ := hP.ordinary + refine ⟨d, hd, f, hf, hP, ?_⟩ + intro g hg he + have hh : Tensor.values d g ∈ Tensor.ordinary F (A ⊕ Unit) d := ⟨d, ⟨hd, le_rfl⟩, g, hg, rfl⟩ + obtain ⟨Z, _, _, y, C', _, hy⟩ := realize (spectralComparison F) hh + have heq : Tensor.values d g ∘ Tensor.place (Sum.inl : A → A ⊕ Unit) = Tensor.values d f := by + funext a + simp only [Function.comp_apply, Tensor.place_inl, Tensor.values, he] + have hx : ExtendsAt (Tensor.values d f) (y ∘ Sum.inl) := by + rw [← heq] + exact hy.2 A Sum.inl + refine (hP.variance hx C C' ho (y (.inr ()))).trans_eq (Finset.sum_congr rfl ?_) + intro i _ + rw [Function.comp_apply, dist_comm, ← hy.1] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Generation by plane motions + +A motion in a direct sum of subspaces factors into three motions along +the two summands. The factors act simultaneously across all instances. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {k V J : Type} [Field k] [AddCommGroup V] [Module k V] + +private def sumChart (S T : Submodule k V) (h : Disjoint S T) : + S × T ≃ ↥(S ⊔ T) := + Equiv.ofBijective (fun p => ⟨p.1 + p.2, Submodule.add_mem_sup p.1.2 p.2.2⟩) (by + constructor + · intro x y he + have eqn : (x.1 : V) + x.2 = (y.1 : V) + y.2 := congrArg Subtype.val he + have hx : (x.1 : V) - y.1 = (y.2 : V) - x.2 := by + rw [sub_eq_sub_iff_add_eq_add, add_comm (y.2 : V)] + exact eqn + have hz := Submodule.disjoint_def.mp h _ (S.sub_mem x.1.2 y.1.2) + (hx.symm ▸ T.sub_mem y.2.2 x.2.2) + exact Prod.ext (Subtype.ext (sub_eq_zero.mp hz)) + (Subtype.ext (sub_eq_zero.mp (hx.symm.trans hz)).symm) + · intro z + obtain ⟨s, t, he⟩ := Submodule.mem_sup'.mp z.2 + exact ⟨(s, t), Subtype.ext he⟩) + +variable [Fintype V] (I A : J → Type) [∀ j, Finite (I j)] [∀ j, Finite (A j)] + +variable {G : Type} [Group G] (M : PermSystem (Labels V I A) G) + +omit [Fintype V] in +private lemma motion_sup [Finite V] (S T : Submodule k V) (h : Disjoint S T) : + M.pull (motion I A (S ⊔ T)) ≤ M.pull (motion I A S) ⊔ M.pull (motion I A T) := by + classical + let : Fintype V := Fintype.ofFinite V + let : ∀ j, Fintype (I j) := fun j => Fintype.ofFinite (I j) + let : ∀ j, Fintype (A j) := fun j => Fintype.ofFinite (A j) + obtain ⟨D, hd⟩ := (S ⊔ T).exists_isCompl + let e := (D.prodEquivOfIsCompl (S ⊔ T) hd.symm).symm + let f := e.toEquiv.trans ((Equiv.refl D).prodCongr (sumChart S T h).symm) + let c (j : J) : Labels V I A j ≃ (I j → D) × ((I j → S) × ((I j → T) × A j)) := + { toFun := fun x => (fun i => (f (x.1 i)).1, fun i => (f (x.1 i)).2.1, + fun i => (f (x.1 i)).2.2, x.2) + invFun := fun y => (fun i => f.symm (y.1 i, y.2.1 i, y.2.2.1 i), y.2.2.2) + left_inv := by intro x; simp + right_inv := by intro y; simp } + have read (j : J) (x : Labels V I A j) (i : I j) : + x.1 i = ((c j x).1 i : V) + (((c j x).2.1 i : V) + ((c j x).2.2.1 i : V)) := + (f.symm_apply_apply (x.1 i)).symm + intro g hg + have fixed (t : M.World) (j : J) (x : Labels V I A j) : + (c j (M.read t g j x)).1 = (c j x).1 := by + funext i + change (e ((M.read t g j x).1 i)).1 = (e (x.1 i)).1 + have hz : (e ((M.read t g j x).1 i - x.1 i)).1 = 0 := + (Submodule.prodEquivOfIsCompl_symm_apply_fst_eq_zero _ _ hd.symm).mpr (hg t j x i) + simpa only [map_sub, Prod.fst_sub, sub_eq_zero] using hz + obtain ⟨u, v, w, he, hu, hv, hw⟩ := M.factor c g fixed + have outer (z : G) + (hz : ∀ t j x, (c j (M.read t z j x)).1 = (c j x).1 ∧ (c j (M.read t z j x)).2.1 + = (c j x).2.1) : + z ∈ M.pull (motion I A T) := by + intro t j x i + rw [read j (M.read t z j x) i, read j x i, (hz t j x).1, (hz t j x).2, + add_sub_add_left_eq_sub, add_sub_add_left_eq_sub] + exact T.sub_mem ((c j (M.read t z j x)).2.2.1 i).2 ((c j x).2.2.1 i).2 + have middle : v ∈ M.pull (motion I A S) := by + intro t j x i + rw [read j (M.read t v j x) i, read j x i, (hv t j x).1, (hv t j x).2, + add_sub_add_left_eq_sub, add_sub_add_right_eq_sub] + exact S.sub_mem ((c j (M.read t v j x)).2.1 i).2 ((c j x).2.1 i).2 + rw [he] + exact Subgroup.mul_mem _ (Subgroup.mul_mem _ (Subgroup.mem_sup_right (outer u hu)) + (Subgroup.mem_sup_left middle)) (Subgroup.mem_sup_right (outer w hw)) + +omit [Fintype V] in +/-- Plane motions generate any group closed under the required factorizations. -/ +theorem PermSystem.motion_generate [Finite V] (h : 2 ≤ Module.finrank k V) : + (⨆ P : VPlane k V, M.pull (motion I A P.1)) = ⊤ := by + classical + let : Fintype V := Fintype.ofFinite V + let H := ⨆ P : VPlane k V, M.pull (motion I A P.1) + have plane (P : VPlane k V) : M.pull (motion I A P.1) ≤ H := le_iSup (fun P + => M.pull (motion I A P.1)) P + have spans (s : Finset V) : M.pull (motion I A (Submodule.span k (s : Set V))) ≤ H := by + induction s using Finset.induction_on with + | empty => + obtain ⟨P⟩ := flat_nonempty h + rw [Finset.coe_empty, Submodule.span_empty] + exact (M.pull_mono (motion_mono I A bot_le)).trans (plane P) + | @insert x s _ ih => + rw [Finset.coe_insert, Submodule.span_insert] + by_cases hx : x ∈ Submodule.span k (s : Set V) + · rwa [sup_eq_right.mpr ((Submodule.span_singleton_le_iff_mem _ _).mpr hx)] + · have hn : x ≠ 0 := fun he => hx (he.symm ▸ Submodule.zero_mem _) + let p : VPoint k V := ⟨_, finrank_span_singleton hn⟩ + obtain ⟨⟨P, d⟩, hd⟩ := surjective_flagPoint h p + have hl : p.1 ≤ P.1 := by rw [← hd]; exact dir_le P d + exact (motion_sup I A M _ _ (Submodule.disjoint_span_singleton_of_notMem hx).symm).trans + (sup_le ((M.pull_mono (motion_mono I A hl)).trans (plane P)) ih) + have ht := spans Finset.univ + rw [Finset.coe_univ, Submodule.span_univ] at ht + exact top_unique fun g _ => ht (fun _ _ _ _ => Submodule.mem_top) + +omit [Fintype V] in +theorem motion_generate [Finite V] (h : 2 ≤ Module.finrank k V) : + (⨆ P : VPlane k V, motion I A P.1) = ⊤ := by + let : Fintype V := Fintype.ofFinite V + simpa only [PermSystem.full_pull] using + PermSystem.motion_generate I A (PermSystem.full (Labels V I A)) h + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- Finite transport bounds at every block of every collision. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Motion + +open Finset Sphere Spectral + +variable {F A : Type} [Field F] [Fintype A] (a : A → Fin 2 → F) + +open scoped Classical in +theorem regular_parameter [Infinite F] (ha : Function.Injective a) : + ∃ s : F, denominator (directions a) s 1 ≠ 0 ∧ + Function.Injective (fun i => position (a i) s 1) := by + obtain ⟨v, hv⟩ := Infinite.exists_notMem_finset ((directions a).eraseNone) + have hd : denominator (directions a) (-v) 1 ≠ 0 := by + refine prod_ne_zero_iff.mpr fun d hd => ?_ + cases d with + | none => exact one_ne_zero + | some t => + have ht : t ≠ v := fun he => hv (by simpa [he] using hd) + simpa [linearFactor, sub_eq_add_neg, add_comm] using sub_ne_zero.mpr ht + refine ⟨-v, hd, fun i j h => ?_⟩ + by_contra hi + have he : projection (a i) (some v) = projection (a j) (some v) := by + simpa [projection, position, mul_comm, sub_eq_add_neg, add_comm] using h + have e := eq_through (k := (some v, projection (a j) (some v))) (ha.ne hi) he rfl + have he' : some v = pole (a i) (a j) := congrArg Prod.fst e + exact hv (by simpa [← he'] using pole_mem a i j) + +open scoped Classical in +theorem degree_le (e : A → ℕ) : + 2 * degree a e ≤ ((directions a).card - 1) * ∑ i, e i := by + unfold degree + rw [mul_left_comm] + exact Nat.mul_le_mul_left _ (by omega) + +open scoped Classical in +/-- The quantity computed by `((directions a).card + 1) * (2 * degree a e + 2) ^ Fintype.card +A`. -/ +def countBound (e : A → ℕ) := ((directions a).card + 1) * (2 * degree a e + 2) ^ Fintype.card A + +variable [DecidableEq A] [Nonempty A] {Y : Type*} [MetricSpace Y] +variable {P : Tensor F A → ℝ} {x : A → Y} + +open scoped Classical in +theorem finite_transport (hx : ExtendsAt P x) (s : F) (hs : denominator (directions a) s 1 ≠ 0) : + ∃ d : ℝ, 0 ≤ d ∧ ∀ e : A → ℕ, ∃ b : Option F × F → ℕ, + (∑ k ∈ blocks a, b k) ≤ 2 * degree a e ∧ + ∀ k ∈ blocks a, ∀ m o : Y, + spherePrice P (fun i => position (a i) s 1) e ≤ + d * Real.log (countBound a e) + dist o m * width (b k) + + ∑ i, dist (if i ∈ pointsOn a k then m else o) (x i) * width (e i) := by + obtain ⟨d, hd, hspan⟩ := hx.span + refine ⟨d, hd, fun e => ?_⟩ + let X := fun i => Level 1 (e i) + let p := tablePrice X P + let T := form a e s + let M := 2 * degree a e + 1 + let C := countBound a e + change ∃ b : Option F × F → ℕ, _ ∧ ∀ k ∈ blocks a, ∀ m o : Y, p T ≤ _ + by_cases hp : 0 < p T + swap + · refine ⟨fun _ => 0, by simp, fun k _ m o => (le_of_not_gt hp).trans ?_⟩ + unfold width + have := entropy_pos + positivity + let bad := (menu a e M).filter fun v => p v + d * Real.log C < p T + have hbad : bad.card ≤ C := calc + _ ≤ (menu a e M).card := card_filter_le _ _ + _ ≤ _ := (menu_size a e M).trans (Nat.mul_le_mul_right _ (Nat.le_succ _)) + let W := Submodule.span F (bad : Set (States 1 e → F)) + have hn : T ∉ W := by + intro ht + obtain ⟨v, hv, h⟩ := hspan X T bad hp ht + have hl : Real.log bad.card ≤ Real.log C := + Real.log_le_log (Nat.cast_pos.mpr (card_pos.mpr ⟨v, hv⟩)) (Nat.cast_le.mpr hbad) + exact (mem_filter.mp hv).2.not_ge (h.trans (add_le_add_right (mul_le_mul_of_nonneg_left hl hd) + _)) + obtain ⟨b, hb, hcuts⟩ := select_cuts a e (M := M) (by omega) W s hs hn + refine ⟨b, hb, fun k hk m o => ?_⟩ + obtain ⟨v, hv, hw, L, R, he, hl, hr⟩ := hcuts k hk + have h₁ : p T ≤ p v + d * Real.log C := by + by_contra! hh + exact hw (Submodule.subset_span (mem_filter.mpr ⟨hv, hh⟩)) + have h₂ : p v ≤ dist o m * width (b k) + + ∑ i, dist (if i ∈ pointsOn a k then m else o) (x i) * width (e i) := + (hx.cut X v (pointsOn a k) L R he hl hr m o).trans + (add_le_add (mul_le_mul_of_nonneg_left (entropy_bound _) dist_nonneg) + (sum_le_sum fun i _ => mul_le_mul_of_nonneg_left (entropy_bound _) dist_nonneg)) + exact h₁.trans (by linarith only [h₂]) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Motion +end + +/- +# The limiting widths of collision blocks + +The finite fusion terms have polynomially many energy patterns, so their +logarithmic overhead vanishes after normalization. Compactness gives a +single limit for every block, independent of the transport test site. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset Filter +open scoped Topology + +variable {F A : Type} [Field F] [Fintype A] + +open scoped Classical in +theorem width_budget {I J : Type*} (s : Finset I) (t : Finset J) + (b : I → ℕ) (e : J → ℕ) (D : ℕ) (n : ℝ) + (h : (∑ i ∈ s, b i) ≤ D * ∑ j ∈ t, e j) : + (∑ i ∈ s, (width (b i) / n) ^ 2) ≤ D * ∑ j ∈ t, (width (e j) / n) ^ 2 := by + have he : (∑ i ∈ s, (b i : ℝ)) ≤ D * ∑ j ∈ t, (e j : ℝ) := by exact_mod_cast h + simp only [div_pow, width_sq, ← sum_div, ← mul_sum] + rw [← mul_div_assoc, mul_left_comm (D : ℝ)] + exact div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left he (sq_nonneg _)) (sq_nonneg _) + +open scoped Classical in +private theorem log_limit {f : ℕ → ℕ} {k : ℕ} (h : ∀ᶠ n in atTop, f n ≤ n ^ k) : + Tendsto (fun n => Real.log (f n) / (n : ℝ)) atTop (𝓝 0) := by + have hl : Tendsto (fun n : ℕ => Real.log (n : ℝ) / n) atTop (𝓝 0) := by + simpa [Function.comp_def] using + (Real.tendsto_pow_log_div_mul_add_atTop 1 0 1 one_ne_zero).comp tendsto_natCast_atTop_atTop + have hk : Tendsto (fun n : ℕ => Real.log ((n : ℝ) ^ k) / n) atTop (𝓝 0) := by + simpa only [Real.log_pow, mul_div_assoc, mul_zero] using hl.const_mul (k : ℝ) + apply tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds hk + · exact Eventually.of_forall fun n => by positivity + filter_upwards [h] with n hn + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg n) + by_cases hf : f n = 0 + · simp only [hf, Nat.cast_zero, Real.log_zero, Real.log_pow] + positivity + exact Real.log_le_log (by exact_mod_cast Nat.pos_of_ne_zero hf) (by exact_mod_cast hn) + +open scoped Classical in +theorem Motion.countBound_limit (a : A → Fin 2 → F) (e : ℕ → A → ℕ) {R : ℝ} + (he : Tendsto (fun n => ∑ i, (width (e n i) / (n : ℝ)) ^ 2) atTop (𝓝 R)) : + Tendsto (fun n => Real.log (Motion.countBound a (e n)) / (n : ℝ)) atTop (𝓝 0) := by + have hc := sq_pos_of_pos Sphere.entropy_pos + let D := (directions a).card + obtain ⟨K, hK⟩ := exists_nat_gt ((R + 1) / Sphere.entropy ^ 2) + have he' : ∀ᶠ n in atTop, (∑ i, e n i) ≤ K * n ^ 2 := by + filter_upwards [he.eventually_le_const (lt_add_one _), eventually_gt_atTop 0] with n h hn + have hn' : 0 < (n : ℝ) ^ 2 := by positivity + simp only [div_pow, width_sq, ← sum_div, ← mul_sum] at h + rw [div_le_iff₀ hn'] at h + have h' := mul_le_mul_of_nonneg_right ((div_lt_iff₀ hc).mp hK).le hn'.le + have h'' : (∑ i, (e n i : ℝ)) ≤ K * (n : ℝ) ^ 2 := + le_of_mul_le_mul_left (by linarith only [h, h']) hc + exact_mod_cast h'' + apply log_limit (k := 3 * Fintype.card A + 1) + filter_upwards [he', eventually_ge_atTop (D + 1), eventually_ge_atTop (D * K + 2)] with n hn hD hK + have hdeg : 2 * Motion.degree a (e n) + 2 ≤ n ^ 3 := calc + _ ≤ D * (K * n ^ 2) + 2 := Nat.add_le_add_right + ((Motion.degree_le a _).trans (Nat.mul_le_mul (Nat.sub_le _ _) hn)) _ + _ ≤ (D * K + 2) * n ^ 2 := by nlinarith [show 1 ≤ n ^ 2 from Nat.one_le_pow 2 n (by omega)] + _ ≤ n ^ 3 := by rw [pow_succ' n 2]; exact Nat.mul_le_mul_right _ hK + rw [pow_succ', pow_mul] + exact Nat.mul_le_mul hD (Nat.pow_le_pow_left hdeg _) + +open scoped Classical in +private theorem budget_limit {I : Type*} (s : Finset I) (u : ℕ → I → ℝ) (r : ℕ → ℝ) {R : ℝ} + (hu : ∀ n i, 0 ≤ u n i) (hb : ∀ n, ∑ i ∈ s, (u n i) ^ 2 ≤ r n) + (hr : Tendsto r atTop (𝓝 R)) : + ∃ b : I → ℝ, (∑ i ∈ s, (b i) ^ 2) ≤ R ∧ ∃ φ : ℕ → ℕ, StrictMono φ ∧ + ∀ i ∈ s, Tendsto (fun n => u (φ n) i) atTop (𝓝 (b i)) := by + let f (n : ℕ) (i : ↥s) := u n i.1 + have hh : ∀ᶠ n in atTop, f n ∈ Set.Icc 0 (fun _ => R + 2) := by + filter_upwards [hr.eventually_le_const (lt_add_one _)] with n hn + refine ⟨fun i => hu _ _, fun i => ?_⟩ + have hi : (f n i) ^ 2 ≤ R + 1 := + ((single_le_sum (fun j _ => sq_nonneg (u n j)) i.2).trans (hb n)).trans hn + nlinarith only [hi, sq_nonneg (f n i - 1)] + obtain ⟨v, _, φ, hφ, hv⟩ := isCompact_Icc.tendsto_subseq' hh.frequently + let b (i : I) := if h : i ∈ s then v ⟨i, h⟩ else 0 + have he (i : I) (hi : i ∈ s) : Tendsto (fun n => u (φ n) i) atTop (𝓝 (b i)) := by + simpa [b, hi, f] using tendsto_pi_nhds.mp hv ⟨i, hi⟩ + refine ⟨b, ?_, φ, hφ, he⟩ + exact le_of_tendsto_of_tendsto' (tendsto_finsetSum s (fun i hi => (he i hi).pow 2)) + (hr.comp hφ.tendsto_atTop) (fun n => hb (φ n)) + +open scoped Classical in +/-- The unit-mass sphere price profile implies the full collision +budget and the transport inequality on every block. -/ +theorem Saturation.collisions {Y : Type*} [MetricSpace Y] [Infinite F] + (h : Saturation F Y) : CollisionBound F Y := by + intro A _ a ha hcard x o ho + have : Nonempty A := Fintype.card_pos_iff.mp (by omega) + obtain ⟨s, hs, hz⟩ := Motion.regular_parameter a ha + let z i := position (a i) s 1 + obtain ⟨P, hP, e, he, hp⟩ := h x o ho z hz + obtain ⟨d, hd, hf⟩ := Motion.finite_transport a hP s hs + choose b hb ht using fun n => hf (e n) + let D := (directions a).card - 1 + let v n i := width (e n i) / (n : ℝ) + let u n k := width (b n k) / (n : ℝ) + let r i := dist o (x i) + have hr : Tendsto (fun n => ∑ i, (v n i) ^ 2) atTop (𝓝 (∑ i, (r i) ^ 2)) := + tendsto_finsetSum _ fun i _ => (he i).pow 2 + have hbudget (n) : ∑ k ∈ blocks a, (u n k) ^ 2 ≤ D * ∑ i, (v n i) ^ 2 := + width_budget _ _ _ _ _ _ ((hb n).trans (Motion.degree_le a _)) + obtain ⟨w, hw, φ, hφ, hl⟩ := budget_limit (blocks a) u _ + (fun n k => div_nonneg (width_nonneg _) (Nat.cast_nonneg n)) hbudget (hr.const_mul _) + refine ⟨w, ?_, fun k hk m => ?_⟩ + · have hD : 1 ≤ (directions a).card := card_pos.mpr ⟨none, mem_insert_self _ _⟩ + simpa only [D, Nat.cast_sub hD, Nat.cast_one] using hw + let p i := dist (if i ∈ pointsOn a k then m else o) (x i) + have hsum : Tendsto (fun n => ∑ i, p i * v (φ n) i) atTop (𝓝 (∑ i, p i * r i)) := + tendsto_finsetSum _ fun i _ => ((he i).comp hφ.tendsto_atTop).const_mul _ + have hcost := ((Motion.countBound_limit a e hr).comp hφ.tendsto_atTop).const_mul d + have hineq : ∑ i, r i ^ 2 ≤ (d * 0 + dist o m * w k) + ∑ i, p i * r i := by + refine le_of_tendsto_of_tendsto' (hp.comp hφ.tendsto_atTop) + ((hcost.add ((hl k hk).const_mul _)).add hsum) fun n => ?_ + have hn := div_le_div_of_nonneg_right (ht (φ n) k hk m o) ((show (0 : ℝ) + ≤ φ n from Nat.cast_nonneg _)) + simpa only [Function.comp_apply, add_div, sum_div, mul_div_assoc] using hn + have heq : ∑ i, p i * r i = (∑ i ∈ pointsOn a k, r i * dist m (x i)) + + ∑ i ∈ univ \ pointsOn a k, r i ^ 2 := by + rw [← sum_sdiff (subset_univ (pointsOn a k)), add_comm] + congr 1 + · exact sum_congr rfl (fun i hi => by simp [p, hi, mul_comm]) + · exact sum_congr rfl (fun i hi => by simp [p, (mem_sdiff.mp hi).2, r, pow_two]) + rw [heq, ← sum_sdiff (subset_univ (pointsOn a k))] at hineq + change (∑ i ∈ pointsOn a k, r i ^ 2) ≤ _ + ∑ i ∈ pointsOn a k, r i * dist m (x i) + linarith only [hineq] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Bounded displacement for families of permutations + +Here the group is the product of all the finite permutation groups. No +restriction on the computation of a permutation family is imposed. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {k V W J : Type} [Field k] [Fintype k] [AddCommGroup V] [Module k V] + [Fintype V] [AddCommGroup W] [Module k W] [Fintype W] + (I R : J → Type) [∀ j, Finite (I j)] [∀ j, Finite (R j)] + +variable (k V W) in +/-- The condition `∀ j, Equiv.Perm (Labels V I (Aux k W I R) j)` on the specified data. -/ +abbrev PermFamilies := ∀ j, Equiv.Perm (Labels V I (Aux k W I R) j) + +local notation "𝒢" => PermFamilies k V W I R + +omit [Fintype V] in +/-- Uniform displacement for arbitrary permutation families, conditional +on the two metric incidence inequalities. -/ +theorem permutation_displacement [Finite V] {Y : Type*} [MetricSpace Y] [CompleteSpace Y] + [MulAction 𝒢 Y] [IsIsometricSMul 𝒢 Y] (C : Comparison Y) + (hV : 2 ≤ Module.finrank k V) (hW : 4 < Module.finrank k W) + (hi : Incidence Y (flagPoint (K := k) (V := V)) Prod.fst) + (ha : Incidence Y Prod.fst (affineGraph (K := k) (V := W))) + (x : Y) (hx : ∀ (p : VPlane k V) (g : 𝒢), + g ∈ motion I (Aux k W I R) p.1 → dist x (g • x) ≤ 1) : + (∃ b, (∀ g : 𝒢, g • b = b) ∧ dist x b ≤ 600) ∧ + ∀ g : 𝒢, dist x (g • x) ≤ 1200 := by + let : ∀ j, Fintype (I j) := fun j => Fintype.ofFinite (I j) + let : ∀ j, Fintype (R j) := fun j => Fintype.ofFinite (R j) + let (j : J) : Finite (Aux k W I R j) := inferInstance + have : Nonempty (VPlane k V) := flat_nonempty hV + have : Nonempty (VPoint k V) := flat_nonempty (le_trans (by decide) hV) + let M := motion (k := k) (V := V) I (Aux k W I R) + exact uniform_displacement C flagPoint (surjective_flagPoint hV) affineGraph hi ha + (M ⊥) (fun i => M i.val) (fun p => M p.val) + (fun _ => motion_mono I _ bot_le) (fun e => motion_mono I _ (dir_le e.1 e.2)) + (motion_generate I _ hV) (fun p => motion_plane_action I R p hW) x hx + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Inputs to the finite detection theorem + +Use the affine and projective links over an infinite extension of +the coefficient field. No extension is made to the actual tensors +in the local price tests. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral + +variable {k V W : Type} [Field k] [Fintype k] + [AddCommGroup V] [Module k V] [Fintype V] + +omit [Fintype V] in +theorem models_of_shared_price [Finite V] {F L : Type} [Field F] [Field L] [Infinite L] + [Algebra F L] [Field W] [Fintype W] [Algebra k W] [Algebra k L] [Algebra W L] + (hsync : Prices.SharedPrice L) (hq : 100 ≤ Fintype.card k) : + HasModels F (flagPoint (K := k) (V := V)) Prod.fst Prod.fst (affineGraph (K := k) (V := W)) + := by + intro S _ _ _ P hp + have hm : ∃ (Y : Type) (_ : MetricSpace Y) (_ : CompleteSpace Y) (x : S → Y), + Comparison Y ∧ SpectralSpace F Y ∧ Represents F P x := by + rcases hp with rfl | ⟨D, hp⟩ + · exact realize_zero F S + · exact realize (spectralComparison F) hp + obtain ⟨Y, _, _, x, C, hY, hr⟩ := hm + have hs := hY.extend_field L + have he := (bounded_forms L).extension hsync + have hh : Saturation L Y := + saturation_of_controlled (controlled_of_probes (hs.variance_test C) he (wireProbe L) hs) + have ht : Secants L Y := CollisionBound.secants (Saturation.collisions hh) + exact ⟨⟨Y, C, x⟩, hr, Secants.projective ht C hq, Secants.affine ht C hq⟩ + +variable [AddCommGroup W] [Module k W] [Fintype W] {G J : Type} [Group G] + (I R : J → Type) [∀ j, Finite (I j)] [∀ j, Finite (R j)] + (M : PermSystem (Labels V I (Aux k W I R)) G) + +/-- Computes the planes by the application `M.pull (motion I (Aux k W I R) p.val)`. -/ +def PermSystem.planes (p : VPlane k V) : Subgroup G := M.pull (motion I (Aux k W I R) p.val) + +omit [Fintype V] in +theorem PermSystem.rigid [Finite V] (hV : 2 ≤ Module.finrank k V) (hW : 4 < Module.finrank k W) : + Rigid (hops (M.planes I R)) (flagPoint (K := k) (V := V)) Prod.fst + Prod.fst (affineGraph (K := k) (V := W)) := by + intro Y _ _ _ _ C hi ha x hx + let : ∀ j, Fintype (I j) := fun j => Fintype.ofFinite (I j) + let : ∀ j, Fintype (R j) := fun j => Fintype.ofFinite (R j) + let (j : J) : Finite (Aux k W I R j) := inferInstance + have : Nonempty (VPlane k V) := flat_nonempty hV + have : Nonempty (VPoint k V) := flat_nonempty (le_trans (by decide) hV) + let f := fun s : Submodule k V => M.pull (motion I (Aux k W I R) s) + exact (uniform_displacement C flagPoint (surjective_flagPoint hV) affineGraph hi ha + (f ⊥) (fun i => f i.val) (M.planes I R) + (fun _ => M.pull_mono (motion_mono I _ bot_le)) + (fun e => M.pull_mono (motion_mono I _ (dir_le e.1 e.2))) + (M.motion_generate I _ hV) (fun p => M.motion_plane_action I R p hW) x + (fun p g hg => hx g (Set.mem_iUnion.mpr ⟨p, hg⟩))).2 + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Sharp incidence estimates under a strict square saving + +Points, lines and flags each carry their own uniform probability +measure. Regularity converts the sums over flags to these means. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset +open scoped BigOperators + +variable {Y A B E : Type} [MetricSpace Y] [Fintype A] [Fintype B] [Fintype E] + +open scoped Classical in +/-- The point barycenter serves both sets of sites. -/ +def SharpIncidence (Y : Type) [MetricSpace Y] (q : ℕ) (p : E → A) (l : E → B) : Prop := + ∀ (x : A → Y) (y : B → Y) (o : Y), Bary x o → + (1 - 1 / Real.sqrt q) * ((𝔼 a, dist o (x a) ^ 2) + (𝔼 b, dist o (y b) ^ 2)) ≤ + 𝔼 e, dist (x (p e)) (y (l e)) ^ 2 + +open scoped Classical in +private theorem uniform_expect [DecidableEq A] [Nonempty E] (p : E → A) {j : ℕ} + (hp : ∀ a, #{i | p i = a} = j) (f : A → ℝ) : (𝔼 e, f (p e)) = 𝔼 a, f a := by + have hc : (Fintype.card E : ℝ) = j * Fintype.card A := by + simpa using uniform_sum p hp (fun _ => 1) + have hj : (j : ℝ) ≠ 0 := by + intro hz + rw [hz, zero_mul] at hc + exact (by positivity : (Fintype.card E : ℝ) ≠ 0) hc + simp only [Fintype.expect_eq_sum_div_card, uniform_sum p hp f, hc, mul_div_mul_left _ _ hj] + +open scoped Classical in +private theorem sharp [DecidableEq A] [DecidableEq B] [Nonempty E] + (C : Comparison Y) (p : E → A) (l : E → B) {j s n q : ℕ} (hq : 0 < q) (hs : 0 < s) + (hp : ∀ a, #{i | p i = a} = j) (hl : ∀ k, #{i | l i = k} = s) (hd : q * n ≤ j * s) + (h : ∀ (x : A → Y) o, Bary x o → SecantBound p l x o n) : SharpIncidence Y q p l := by + intro x y o ho + rw [← uniform_expect p hp (fun a => dist o (x a) ^ 2), + ← uniform_expect l hl (fun b => dist o (y b) ^ 2), ← expect_add_distrib] + simp only [Fintype.expect_eq_sum_div_card, ← mul_div_assoc] + apply div_le_div_of_nonneg_right _ (by positivity) + have hr : 0 < Real.sqrt q := by positivity + rw [show 1 - 1 / Real.sqrt q = (Real.sqrt q - 1) / Real.sqrt q by field_simp, div_mul_eq_mul_div, + div_le_iff₀ hr, mul_comm _ (Real.sqrt q)] + exact regular_incidence C p l x y o hs hp hl hd (h x o ho) + +variable {F K : Type} [Field F] [Finite F] [Field K] [Fintype K] + +open scoped Classical in +omit [Fintype K] in +private theorem common_field [Finite K] (hc : ringChar K = ringChar F) : + Nonempty (Algebra K (AlgebraicClosure F)) := by + let : Fintype K := Fintype.ofFinite K + let p := ringChar F + have : Fact p.Prime := ⟨CharP.char_is_prime F p⟩ + have : CharP K p := by unfold p; rw [← hc]; infer_instance + let _ := ZMod.algebra K p + let _ := ZMod.algebra (AlgebraicClosure F) p + exact ⟨(IsAlgClosed.lift : K →ₐ[ZMod p] AlgebraicClosure F).toRingHom.toAlgebra⟩ + +open scoped Classical in +private theorem secants_of_saving (h : omega F < 9 / 4) + (S : SpectralSpace F Y) (C : Comparison Y) : Secants (AlgebraicClosure F) Y := by + let L := AlgebraicClosure F + have hs := S.extend_field L + have he := (bounded_forms L).extension (shared_of_saving h) + have hh : Saturation L Y := saturation_of_controlled (controlled_of_probes (hs.variance_test C) + he (wireProbe L) hs) + have ht : Secants L Y := CollisionBound.secants (Saturation.collisions hh) + exact @ht + +open scoped Classical in +/-- Points and lines of projective space over the finite field of +order `q`, in the characteristic of the coefficient field. -/ +theorem projective_of_saving (h : omega F < 9 / 4) + (S : SpectralSpace F Y) (C : Comparison Y) (hc : ringChar K = ringChar F) + {V : Type} [AddCommGroup V] [Module K V] [Finite V] (hV : 2 ≤ Module.finrank K V) : + SharpIncidence Y (Fintype.card K) (flagPoint (K := K) (V := V)) Prod.fst := by + let _ := (common_field hc).some + have : Nonempty (VPlane K V) := flat_nonempty hV + have hs : Secants (AlgebraicClosure F) Y := secants_of_saving h S C + refine sharp C flagPoint Prod.fst Fintype.card_pos (Nat.succ_pos _) + projective_point_degree projective_plane_degree ?_ (Secants.projective_widths hs) + rw [Nat.mul_comm (Fintype.card K)] + exact Nat.mul_le_mul (Nat.sub_le _ _) (Nat.le_succ _) + +open scoped Classical in +/-- Points in the affine plane of a finite extension and lines in +the `q+1` directions defined over the base field. -/ +theorem affine_of_saving (h : omega F < 9 / 4) + (S : SpectralSpace F Y) (C : Comparison Y) (hc : ringChar K = ringChar F) + {W : Type} [Field W] [Fintype W] [Algebra K W] : + SharpIncidence Y (Fintype.card K) Prod.fst (affineGraph (K := K) (V := W)) := by + let _ := (common_field hc).some + let _ : Algebra W (AlgebraicClosure F) := + (IsAlgClosed.lift : W →ₐ[K] AlgebraicClosure F).toRingHom.toAlgebra + have hs : Secants (AlgebraicClosure F) Y := secants_of_saving h S C + refine sharp C Prod.fst affineGraph Fintype.card_pos Fintype.card_pos + affine_point_degree affine_line_degree ?_ (Secants.affine_widths hs) + exact Nat.mul_le_mul_right _ (Nat.le_succ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryTerms.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryTerms.lean new file mode 100644 index 0000000000..925290127f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/GeometryTerms.lean @@ -0,0 +1,160 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Expect +public import Mathlib.Analysis.SpecialFunctions.Sqrt +public import Mathlib.Topology.MetricSpace.IsometricSMul +public import Mathlib.Topology.MetricSpace.Completion + +/-! +# Squared-distance comparison and variance + +We use the geodesic comparison form of the CAT(0) inequality. +The expectations are uniform finite averages. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators + +/-- The comparison of type `Prop` for the given inputs. -/ +def Comparison (Y : Type*) [MetricSpace Y] : Prop := + ∀ (x y : Y) (t : ℝ), 0 ≤ t → t ≤ 1 → + ∃ m : Y, dist x m = t * dist x y ∧ + ∀ z, dist m z ^ 2 ≤ + (1 - t) * dist x z ^ 2 + t * dist y z ^ 2 - t * (1 - t) * dist x y ^ 2 + +/-- The condition `∀ z, (𝔼 i, dist o (x i) ^ 2) + dist o z ^ 2 ≤ (𝔼 i, dist z (x i) ^ 2)` on the +specified data. -/ +def Bary {Y A : Type*} [MetricSpace Y] [Fintype A] (x : A → Y) (o : Y) : Prop := + ∀ z, (𝔼 i, dist o (x i) ^ 2) + dist o z ^ 2 ≤ (𝔼 i, dist z (x i) ^ 2) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Geodesic terms + +For a fixed fraction, interpolation in a space satisfying squared +distance comparison is uniformly continuous in both endpoints. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open UniformSpace + +/-- The value specified by `↥(Set.Icc (0 : ℝ) 1)`. -/ +abbrev Fraction := ↥(Set.Icc (0 : ℝ) 1) + +/-- The condition `∀ z, dist m z ^ 2 ≤ (1 - u.val) * dist x z ^ 2 + u.val * dist y z ^ 2 - u.val +* (1 - u.val) * dist x y ^ 2` on the specified data. -/ +def Along {Y : Type*} [PseudoMetricSpace Y] (u : Fraction) (x y m : Y) : Prop := + ∀ z, dist m z ^ 2 ≤ (1 - u.val) * dist x z ^ 2 + u.val * dist y z ^ 2 - + u.val * (1 - u.val) * dist x y ^ 2 + +section +variable {Y : Type*} [PseudoMetricSpace Y] {u : Fraction} {x y m x' y' m' : Y} + +/-- The quantity computed by `⟨1 - u.val, sub_nonneg.mpr u.2.2, sub_le_self _ u.2.1⟩`. -/ +def Fraction.rev (u : Fraction) : Fraction := + ⟨1 - u.val, sub_nonneg.mpr u.2.2, sub_le_self _ u.2.1⟩ + +theorem Along.rev (h : Along u x y m) : Along u.rev y x m := by + intro z + rw [dist_comm y x] + change dist m z ^ 2 ≤ (1 - (1 - u.val)) * dist y z ^ 2 + (1 - u.val) * dist x z ^ 2 - + (1 - u.val) * (1 - (1 - u.val)) * dist x y ^ 2 + linarith only [h z] + +private theorem Along.dist_le (h : Along u x y m) : dist x m ≤ u.val * dist x y := by + have hh := h x + rw [dist_self, dist_comm m x, dist_comm y x] at hh + apply (sq_le_sq₀ dist_nonneg (mul_nonneg u.2.1 dist_nonneg)).mp + linarith only [hh] + +theorem Along.start (h : Along u x y m) : dist x m = u.val * dist x y := by + have hh := h.rev.dist_le + change dist y m ≤ (1 - u.val) * dist y x at hh + rw [dist_comm y m, dist_comm y x] at hh + linarith [h.dist_le, dist_triangle x m y] + +theorem Along.dist_right (h : Along u x y m) (h' : Along u x y' m') : + dist m m' ≤ u.val * dist y y' := by + have h₁ := h m' + rw [h'.start, dist_comm y m'] at h₁ + have h₂ := mul_le_mul_of_nonneg_left (h' y) u.2.1 + rw [dist_comm y' y] at h₂ + apply (sq_le_sq₀ dist_nonneg (mul_nonneg u.2.1 dist_nonneg)).mp + linarith only [h₁, h₂] + +theorem uniformContinuous_along (f : Y → Y → Y) (hf : ∀ x y, Along u x y (f x y)) : + UniformContinuous₂ f := by + apply LipschitzWith.uniformContinuous (K := 1) + apply LipschitzWith.of_dist_le_mul + rintro ⟨x, y⟩ ⟨z, w⟩ + have h₁ := (hf x y).rev.dist_right (hf z y).rev + have h₂ := (hf z y).dist_right (hf z w) + have h₃ := mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist y w)) u.rev.2.1 + have h₄ := mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist y w)) u.2.1 + change dist (f x y) (f z w) ≤ 1 * max (dist x z) (dist y w) + dsimp only [Fraction.rev] at h₁ h₃ + linarith only [h₁, h₂, h₃, h₄, dist_triangle (f x y) (f z y) (f z w)] +end + +variable {Y : Type*} [MetricSpace Y] (C : Comparison Y) + +/-- The value specified by `(C x y u u.2.1 u.2.2).choose`. -/ +def Comparison.seg (u : Fraction) (x y : Y) : Y := (C x y u u.2.1 u.2.2).choose + +theorem Comparison.along (u : Fraction) (x y : Y) : Along u x y (C.seg u x y) := + (C x y u u.2.1 u.2.2).choose_spec.2 + +theorem Along.unique {u : Fraction} {x y m m' : Y} + (h : Along u x y m) (h' : Along u x y m') : m = m' := by + have hh := h.dist_right h' + simpa using hh + +/-- Expressions in marked sites, with no new generators for barycenters. -/ +inductive Term (G : Type*) where + | mark (g : G) + | seg (u : Fraction) (a b : Term G) + +namespace Term +variable {G : Type*} + +/-- In the case `.mark g`, this construction gives `x g`. -/ +def eval (x : G → Y) : Term G → Y + | .mark g => x g + | .seg u a b => C.seg u (eval x a) (eval x b) + +/-- In the case `.mark g`, this construction gives `.mark (f g)`. -/ +def map {G' : Type*} (f : G → G') : Term G → Term G' + | .mark g => .mark (f g) + | .seg u a b => .seg u (map f a) (map f b) + +instance [Group G] : MulAction G (Term G) where + smul g := map (g * ·) + one_smul t := by + change map (1 * ·) t = t + induction t with + | mark => simp [map] + | seg u a b ha hb => exact congrArg₂ (seg u) ha hb + mul_smul g h t := by + change map (g * h * ·) t = map (g * ·) (map (h * ·) t) + induction t with + | mark => simp [map, mul_assoc] + | seg u a b ha hb => exact congrArg₂ (seg u) ha hb + +end Term +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Packets.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Packets.lean new file mode 100644 index 0000000000..54704f935e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Packets.lean @@ -0,0 +1,667 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.FieldTheory.Finiteness +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Fixed +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryControl +public import Mathlib.Logic.Equiv.Fintype + +/-! +# Independent samples for affine partitions + +A dependent tuple and one extra vector fit injectively into a coefficient +tuple and a vector tuple. Store a nonzero relation, then shift the tuple so +that evaluating this relation recovers the extra vector. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped Classical in +theorem half_independent (k V I : Type) [Field k] [Finite k] + [AddCommGroup V] [Module k V] [Fintype V] [Fintype I] [DecidableEq I] + (h : Fintype.card I < Module.finrank k V) : + Fintype.card (I → V) ≤ + 2 * (Finset.univ.filter (fun x : I → V => LinearIndependent k x)).card := by + let : Fintype k := Fintype.ofFinite k + let D := {x : I → V // ¬ LinearIndependent k x} + choose c hc hn using fun x : D => Fintype.not_linearIndependent_iff.mp x.2 + have correction (a : I → k) (ha : ∃ i, a i ≠ 0) (v : V) : + ∃ y : I → V, ∑ i, a i • y i = v := by + obtain ⟨j, hj⟩ := ha + refine ⟨fun i => if i = j then (a j)⁻¹ • v else 0, ?_⟩ + simp [smul_ite, hj] + choose! t ht using correction + let f (p : D × V) : (I → k) × (I → V) := + (c p.1, p.1.val + t (c p.1) p.2) + have recover (p : D × V) : ∑ i, (f p).1 i • (f p).2 i = p.2 := by + simp only [f, Pi.add_apply, smul_add, Finset.sum_add_distrib, hc, ht _ (hn p.1), zero_add] + have hinj : Function.Injective f := by + rintro ⟨x, u⟩ ⟨y, v⟩ he + have huv : u = v := by + have hu := recover (x, u) + rw [he, recover] at hu + exact hu.symm + subst v + have hxy : c x = c y := congrArg Prod.fst he + have hs := congrArg Prod.snd he + simp only [f, hxy] at hs + exact Prod.ext (Subtype.ext (add_right_cancel hs)) rfl + have hb := Fintype.card_le_of_injective f hinj + rw [Fintype.card_prod, Fintype.card_prod] at hb + have hd : 2 * Fintype.card (I → k) ≤ Fintype.card V := by + rw [Fintype.card_fun, Module.card_eq_pow_finrank (K := k) (V := V)] + calc + _ ≤ Fintype.card k * Fintype.card k ^ Fintype.card I := + Nat.mul_le_mul_right _ Fintype.one_lt_card + _ = Fintype.card k ^ (Fintype.card I + 1) := (pow_succ' _ _).symm + _ ≤ _ := Nat.pow_le_pow_right Fintype.card_pos h + have hbad : 2 * Fintype.card D ≤ Fintype.card (I → V) := by + apply Nat.le_of_mul_le_mul_right (c := Fintype.card (I → k)) _ Fintype.card_pos + calc + _ = Fintype.card D * (2 * Fintype.card (I → k)) := by ac_rfl + _ ≤ Fintype.card D * Fintype.card V := Nat.mul_le_mul_left _ hd + _ ≤ _ := hb.trans_eq (Nat.mul_comm _ _) + rw [show Fintype.card D = _ from Fintype.card_subtype_compl _, Fintype.card_subtype] at hbad + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Replicating each request at the centers that can use it +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Finset + +variable {K S I : Type} [Field K] [Fintype S] [DecidableEq S] [Fintype I] [DecidableEq I] + {N : ℕ} (b : Market I N) (A : Finset (Tensor K S)) + +namespace Shape + +open scoped Classical in +/-- Computes the req by the application `BallShape.Requests (Fin s.1.val) A`. -/ +abbrev Req (s : Shape N) := BallShape.Requests (Fin s.1.val) A + +open scoped Classical in +/-- In the case `.inl none`, this construction gives `price μ d (x none)`. -/ +def prices (s : Shape N) (μ d M : ℕ) (x : s.Req A → ℕ) : s.2.Goods A → ℝ + | .inl none => price μ d (x none) + | .inl (some a) => price μ M (x (some a)) + | .inr _ => 1 + +end Shape + +namespace Market + +open scoped Classical in +/-- The value specified by `z ∘ b.request A i`. -/ +def localStock (z : b.Request A → ℕ) (i : I) : (b.code i).Req A → ℕ := z ∘ b.request A i + +open scoped Classical in +/-- The indexed operation `(b.support i).biUnion fun x => univ.filter fun j => x ∈ b.support j`. -/ +def neighbors (i : I) := (b.support i).biUnion fun x => univ.filter fun j => x ∈ b.support j + +open scoped Classical in +theorem count_neighbors (i : I) : (b.neighbors i).card ≤ N * N := by + refine card_biUnion_le.trans ?_ + calc + _ ≤ ∑ _ ∈ b.support i, N := sum_le_sum fun x _ => b.count_support x + _ ≤ N * N := by simpa using Nat.mul_le_mul_right N (b.card_support i) + +omit [Fintype I] [DecidableEq I] [DecidableEq S] in +open scoped Classical in +theorem request_surj (x : b.Request A) : ∃ i t, b.request A i t = x := by + rcases x with i | ⟨⟨_, ⟨i, v⟩, rfl⟩, j⟩ + · exact ⟨i, none, rfl⟩ + · exact ⟨i, some (v, j), rfl⟩ + +omit [Fintype I] [DecidableEq I] [DecidableEq S] in +open scoped Classical in +theorem localStock_injective : Function.Injective (b.localStock A) := by + intro z w h + funext x + obtain ⟨i, t, rfl⟩ := b.request_surj A x + exact congrFun (congrFun h i) t + +omit [Fintype I] [DecidableEq I] [DecidableEq S] in +open scoped Classical in +theorem localStock_rates (z : b.Request A → ℕ) (μ d M : ℕ) (i : I) : + b.rates A (fun x => price μ (b.cap A d M x) (z x)) ∘ b.assign A i = + (b.code i).prices A μ d M (b.localStock A z i) := by + funext x + rcases x with (_ | ⟨v, j⟩) | e <;> rfl + +omit [DecidableEq S] in +open scoped Classical in +theorem overlap_neighbor [Nonempty S] (i j : I) (x : (b.code i).Req A) (y : (b.code j).Req A) + (he : b.request A i x = b.request A j y) : j ∈ b.neighbors i := + mem_biUnion.mpr ⟨b.home A (b.request A i x), b.home_mem A i (.inl x) _ rfl, + mem_filter.mpr ⟨mem_univ _, he.symm ▸ b.home_mem A j (.inl y) _ rfl⟩⟩ + +omit [Fintype I] [DecidableEq I] [DecidableEq S] in +open scoped Classical in +theorem request_eq (i j : I) (x : (b.code i).Req A) (y : (b.code j).Req A) : + b.request A i x = b.request A j y ↔ + match x, y with + | none, none => i = j + | some (a, k), some (c, l) => k = l ∧ ∀ s, b.name i (a s) = b.name j (c s) + | _, _ => False := by + cases x <;> cases y <;> simp [request, Prod.ext_iff, Subtype.ext_iff, funext_iff, and_comm] + +end Market +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Unique finite descriptions of the outcomes of a policy round + +Only active centers have an outcome. At each center the local prices +determine the active menu entry. Its histogram, or a unique inactive +marker, records the branch without adding multiplicity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Finset + +variable {K S I : Type} [Field K] [Fintype S] [DecidableEq S] [Fintype I] [DecidableEq I] + {N M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} (a : Atlas N A M ρ) + +namespace Atlas + +open scoped Classical in +/-- The quantity computed by `↥(histograms q.val.move.letter (m + Fintype.card +q.val.move.letter))`. -/ +abbrev Branch (s : Shape N) (m : ℕ) (q : a.menu s) := + ↥(histograms q.val.move.letter (m + Fintype.card q.val.move.letter)) + +open scoped Classical in +/-- Indexes the record by the coordinates of `Option (Σ q : a.menu s, a.Branch s m q)`. -/ +abbrev Record (s : Shape N) (m : ℕ) := Option (Σ q : a.menu s, a.Branch s m q) + +open scoped Classical in +/-- Uses `⟨a.select s p h, (a.selected s p h).1⟩` as the representation. -/ +def entry (s : Shape N) (p : s.2.Goods A → ℝ) (h : a.Enabled s p) : a.menu s := + ⟨a.select s p h, (a.selected s p h).1⟩ + +open scoped Classical in +/-- Returns `∃ j, r = some ⟨a.entry s p h, j⟩` when `h : a.Enabled s p` holds, and `r = none` +otherwise. -/ +def Valid (s : Shape N) (m : ℕ) (p : s.2.Goods A → ℝ) (r : a.Record s m) : Prop := + if h : a.Enabled s p then ∃ j, r = some ⟨a.entry s p h, j⟩ else r = none + +open scoped Classical in +/-- In the case `none`, this construction gives `0`. -/ +def changeAt (s : Shape N) (m : ℕ) (r : a.Record s m) (put : Bool) (j : s.2.Goods A) : ℕ := + match r with + | none => 0 + | some ⟨q, h⟩ => + if put then q.val.output (s.2.links A) (m + Fintype.card q.val.move.letter) h.val j + else Stock.copies q.val.demand (q.val.move.block * m) j + +end Atlas + +namespace Market +variable (b : Market I N) (p : b.Request A → ℝ) (m : ℕ) + +open scoped Classical in +/-- The value specified by `a.entry _ (b.rates A p ∘ b.assign A i) (mem_filter.mp +i.property).2`. -/ +def live (i : b.active a p) : a.menu (b.code i) := + a.entry _ (b.rates A p ∘ b.assign A i) (mem_filter.mp i.property).2 + +open scoped Classical in +/-- Returns `some ⟨b.live a p ⟨i, h⟩, j ⟨i, h⟩⟩` when `h : i ∈ b.active a p` holds, and `none` +otherwise. -/ +def record (j : (b.policy a p m).choice) (i : I) : a.Record (b.code i) m := + if h : i ∈ b.active a p then some ⟨b.live a p ⟨i, h⟩, j ⟨i, h⟩⟩ else none + +open scoped Classical in +theorem record_active (j : (b.policy a p m).choice) (i : b.active a p) : + b.record a p m j i = some ⟨b.live a p i, j i⟩ := dite_eq_left i.property + +open scoped Classical in +theorem record_valid (j : (b.policy a p m).choice) (i : I) : + a.Valid (b.code i) m (b.rates A p ∘ b.assign A i) (b.record a p m j i) := by + by_cases he : a.Enabled (b.code i) (b.rates A p ∘ b.assign A i) + · let u : b.active a p := ⟨i, mem_filter.mpr ⟨mem_univ _, he⟩⟩ + rw [Atlas.Valid, dite_eq_left he] + exact ⟨j u, b.record_active a p m j u⟩ + · rw [Atlas.Valid, dite_eq_right he] + have hi : i ∉ b.active a p := fun h => he (mem_filter.mp h).2 + exact dite_eq_right hi + +open scoped Classical in +theorem record_injective : Function.Injective (b.record a p m) := by + intro u v h + funext i + have he := congrFun h i.val + rw [record_active, record_active] at he + exact eq_of_heq (Sigma.mk.inj (Option.some.inj he)).2 + +open scoped Classical in +theorem exists_record (r : ∀ i, a.Record (b.code i) m) + (h : ∀ i, a.Valid (b.code i) m (b.rates A p ∘ b.assign A i) (r i)) : + ∃! j, b.record a p m j = r := by + have each (i : b.active a p) : ∃ j : (b.localMove a p m i).choice, r i = some ⟨b.live a p i, j⟩ + := by + have he := h i.val + rw [Atlas.Valid, dite_eq_left (mem_filter.mp i.property).2] at he + exact he + choose j hj using each + have he : b.record a p m j = r := by + funext i + by_cases hi : i ∈ b.active a p + · exact (b.record_active a p m j ⟨i, hi⟩).trans (hj ⟨i, hi⟩).symm + · have hv := h i + have hn : ¬ a.Enabled (b.code i) (b.rates A p ∘ b.assign A i) := + fun hh => hi (mem_filter.mpr ⟨mem_univ _, hh⟩) + rw [Atlas.Valid, dite_eq_right hn] at hv + exact (dite_eq_right hi).trans hv.symm + exact ⟨j, he, fun _ h => b.record_injective a p m (h.trans he.symm)⟩ + +end Market +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Updating a replicated stock from local records + +Only the request coincidences between neighboring centers are used. +The order or naming of the global requests is immaterial. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +open Spectral Finset + +variable {K S I : Type} [Field K] [Fintype S] [DecidableEq S] [Fintype I] [DecidableEq I] + {N M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} + (b : Market I N) (a : Atlas N A M ρ) (p : b.Request A → ℝ) (m : ℕ) + +open scoped Classical in +/-- The sum of `a.changeAt (b.code j) m r put (.inl y)` indexed by `y ∈ univ.filter (fun y => +b.request A j y = x)`. -/ +def sent (j : I) (r : a.Record (b.code j) m) (put : Bool) (x : b.Request A) := + ∑ y ∈ univ.filter (fun y => b.request A j y = x), a.changeAt (b.code j) m r put (.inl y) + +omit [Fintype I] in +open scoped Classical in +private theorem sent_collect (j : I) (r : a.Record (b.code j) m) (put : Bool) (x : b.Request A) : + b.sent a m j r put x = + Stock.collect (b.assign A j) (a.changeAt (b.code j) m r put) (.inl x) := by + simp only [sent, Stock.collect, sum_filter] + rw [Fintype.sum_sum_type] + simp [assign] + +open scoped Classical in +theorem sent_active (j : b.active a p) (u : (b.policy a p m).choice) (put : Bool) (x : b.Request A) + : + b.sent a m j (b.record a p m u j) put x = + if put then (b.localMove a p m j).put (u j) x else (b.localMove a p m j).take x := by + rw [sent_collect, record_active] + cases put <;> simp only [Bool.false_eq_true, ↓reduceIte, localMove, + Proposal.flex, Proposal.trade, Function.comp_apply] <;> congr + +open scoped Classical in +theorem sent_inactive (j : I) (u : (b.policy a p m).choice) (put : Bool) (x : b.Request A) + (hj : j ∉ b.active a p) : b.sent a m j (b.record a p m u j) put x = 0 := by + rw [show b.record a p m u j = none from dite_eq_right hj] + exact sum_eq_zero fun _ _ => rfl + +variable [Nonempty S] + +open scoped Classical in +/-- The sum of `b.sent a m j (r j) put (b.request A i x)` indexed by `j ∈ b.neighbors i`. -/ +def incoming (r : ∀ i, a.Record (b.code i) m) (put : Bool) (i : I) (x : (b.code i).Req A) := + ∑ j ∈ b.neighbors i, b.sent a m j (r j) put (b.request A i x) + +open scoped Classical in +theorem incoming_eq (u : (b.policy a p m).choice) (put : Bool) (i : I) (x : (b.code i).Req A) : + b.incoming a m (b.record a p m u) put i x = + if put then (b.policy a p m).put u (b.request A i x) + else (b.policy a p m).take (b.request A i x) := by + let f j := b.sent a m j (b.record a p m u j) put (b.request A i x) + change (∑ j ∈ b.neighbors i, f j) = _ + calc + _ = ∑ j, f j := sum_subset (subset_univ _) fun j _ hj => + sum_eq_zero fun y hy => (hj (b.overlap_neighbor A i j x y (mem_filter.mp hy).2.symm)).elim + _ = ∑ j ∈ b.active a p, f j := + (sum_subset (subset_univ _) fun j _ hj => b.sent_inactive a p m j u put _ hj).symm + _ = ∑ j : b.active a p, f j := (sum_coe_sort _ _).symm + _ = _ := by + simp only [f, sent_active] + cases put <;> rfl + +open scoped Classical in +/-- The quantity computed by `v x - b.incoming a m r false i x + b.incoming a m r true i x + if +x = none then 1 else 0`. -/ +def localNext (r : ∀ i, a.Record (b.code i) m) (i : I) + (v : (b.code i).Req A → ℕ) (x : (b.code i).Req A) : ℕ := + v x - b.incoming a m r false i x + b.incoming a m r true i x + if x = none then 1 else 0 + +open scoped Classical in +theorem localNext_eq (u : (b.policy a p m).choice) (z : b.Request A → ℕ) (i : I) : + b.localNext a m (b.record a p m u) i (b.localStock A z i) = + b.localStock A ((b.policy a p m).next z u + Stock.copies (b.payload A) 1) i := by + funext x + simp only [localNext, incoming_eq, Bool.false_eq_true, ↓reduceIte, + localStock, Function.comp_apply, Pi.add_apply, Intervention.next] + congr 1 + rcases x with _ | ⟨v, j⟩ <;> simp [Stock.copies, payload, request] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +end + +/- +# Checking one policy round with no spurious outcomes +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +open Spectral + +variable {K S I : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype I] [DecidableEq I] {N M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} + (b : Market I N) (a : Atlas N A M ρ) (μ d m : ℕ) + +open scoped Classical in +/-- The value specified by `price μ (b.cap A d M x) (z x)`. -/ +abbrev stockPrice (z : b.Request A → ℕ) (x : b.Request A) := price μ (b.cap A d M x) (z x) + +open scoped Classical in +/-- The condition `∀ i, a.Valid (b.code i) m ((b.code i).prices A μ d M (v i)) (r i) ∧ w i = +b.localNext a m r i (v i)` on the specified data. -/ +def Checks (v : (i : I) → (b.code i).Req A → ℕ) + (r : ∀ i, a.Record (b.code i) m) (w : (i : I) → (b.code i).Req A → ℕ) : Prop := + ∀ i, a.Valid (b.code i) m ((b.code i).prices A μ d M (v i)) (r i) ∧ + w i = b.localNext a m r i (v i) + +open scoped Classical in +/-- The quantity computed by `(b.decision a μ d m z).next z u + Stock.copies (b.payload A) 1`. -/ +def after (z : b.Request A → ℕ) (u : (b.decision a μ d m z).choice) : b.Request A → ℕ := + (b.decision a μ d m z).next z u + Stock.copies (b.payload A) 1 + +open scoped Classical in +theorem checks_iff (z : b.Request A → ℕ) (r : ∀ i, a.Record (b.code i) m) + (w : (i : I) → (b.code i).Req A → ℕ) : + b.Checks a μ d m (b.localStock A z) r w ↔ + ∃! u : (b.decision a μ d m z).choice, + b.record a (b.stockPrice (M := M) μ d z) m u = r ∧ w = b.localStock A (b.after a μ d m z u) + := by + let p := b.stockPrice (M := M) μ d z + have he (i) : b.rates A p ∘ b.assign A i = + (b.code i).prices A μ d M (b.localStock A z i) := b.localStock_rates A z μ d M i + constructor + · intro h + have hv (i) : a.Valid (b.code i) m (b.rates A p ∘ b.assign A i) (r i) := by + rw [he] + exact (h i).1 + obtain ⟨u, hu, hh⟩ := b.exists_record a p m r hv + refine ⟨u, ⟨hu, funext fun i => ?_⟩, fun j hj => hh j hj.1⟩ + rw [(h i).2, ← hu] + exact b.localNext_eq a p m u z i + · rintro ⟨u, ⟨rfl, rfl⟩, _⟩ i + rw [← he] + exact ⟨b.record_valid a p m u i, (b.localNext_eq a p m u z i).symm⟩ + +open scoped Classical in +/-- Each update introduces only boundedly many units of each type, +including the one newly injected payload bit. -/ +theorem after_bound (room : a.Room m) (hm : 1 ≤ M) (hd : d ≤ M) + (z : b.Request A → ℕ) (u : (b.decision a μ d m z).choice) (i : b.Request A) : + b.after a μ d m z u i ≤ z i + N * (2 * a.capacity * m) + 1 := by + let p := b.stockPrice (M := M) μ d z + have hp (i) : p i ≤ M := by + refine price_le.trans ?_ + cases i with + | inl x => exact Nat.cast_le.mpr hd + | inr x => exact le_rfl + have he := b.local_efficient a p m room hm hp + have h := (Intervention.parallel_bounds _ (b.local_overlap a p m) he i).2.2 u + have hb : Stock.copies (b.payload A) 1 i ≤ 1 := by unfold Stock.copies; split <;> simp + exact Nat.add_le_add (Nat.add_le_add (Nat.sub_le _ _) h) hb + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +end + +/- +# An action-independent alphabet for one round + +Only neighbor addresses and coincidence masks depend on the number +of centers. The local trade and its replay use a fixed finite table. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Finset + +variable {K S I : Type} [Field K] [Fintype S] [DecidableEq S] + [Fintype I] [DecidableEq I] {N M : ℕ} {ρ : ℝ} {A : Finset (Tensor K S)} + +open scoped Classical in +/-- Indexes the key by the coordinates of `Σ s : Shape N, s.Req A`. -/ +abbrev Key (N : ℕ) (A : Finset (Tensor K S)) := Σ s : Shape N, s.Req A + +namespace Market + +variable (b : Market I N) (A : Finset (Tensor K S)) + +open scoped Classical in +/-- The data for the ports construction, including `addr`, `use`, `image`, `distinct`. -/ +structure Ports (t : ℕ) where + /-- The `Ports` component of type `Fin (2 ^ t) → I → I`. -/ + addr : Fin (2 ^ t) → I → I + /-- The `Ports` component of type `I → Finset (Fin (2 ^ t))`. -/ + use : I → Finset (Fin (2 ^ t)) + image : ∀ i, (use i).image (fun j => addr j i) = b.neighbors i + distinct : ∀ i, Set.InjOn (fun j => addr j i) (use i) + +open scoped Classical in +/-- The value specified by `decide (j ∈ g.use i ∧ ∃ u v, x = ⟨b.code i, u⟩ ∧ y = ⟨b.code (g.addr +j i), v⟩ ∧ b.request A i u = b.request A (g.addr j i) v)`. -/ +def mask {t : ℕ} (g : b.Ports t) (i : I) (j : Fin (2 ^ t)) + (x y : Key N A) : Bool := + decide (j ∈ g.use i ∧ ∃ u v, x = ⟨b.code i, u⟩ ∧ y = ⟨b.code (g.addr j i), v⟩ ∧ + b.request A i u = b.request A (g.addr j i) v) + +open scoped Classical in +theorem mask_test {t : ℕ} (g : b.Ports t) (i : I) (j : Fin (2 ^ t)) + (x : (b.code i).Req A) (y : (b.code (g.addr j i)).Req A) : + b.mask A g i j ⟨_, x⟩ ⟨_, y⟩ = true ↔ + j ∈ g.use i ∧ b.request A i x = b.request A (g.addr j i) y := by + rw [mask, decide_eq_true_eq] + constructor + · rintro ⟨hu, x', y', hx, hy, he⟩ + rw [eq_of_heq (Sigma.mk.inj hx).2, eq_of_heq (Sigma.mk.inj hy).2] + exact ⟨hu, he⟩ + · exact fun h => ⟨h.1, x, y, rfl, rfl, h.2⟩ + +end Market + +namespace Atlas +variable (a : Atlas N A M ρ) (m t R : ℕ) + +open scoped Classical in +/-- Indexes the cell by the coordinates of `(s.Req A → Fin (R + 1)) × a.Record s m × (s.Req A → +Fin (R + 1))`. -/ +abbrev Cell (s : Shape N) := + (s.Req A → Fin (R + 1)) × a.Record s m × (s.Req A → Fin (R + 1)) + +open scoped Classical in +/-- Indexes the packet by the coordinates of `(Σ s : Shape N, a.Cell m R s) × (Fin (2 ^ t) → Key +N A → Key N A → Bool)`. -/ +abbrev Packet := (Σ s : Shape N, a.Cell m R s) × (Fin (2 ^ t) → Key N A → Key N A → Bool) + +open scoped Classical in +open scoped Classical in +/-- The indexed operation `∑ j, ∑ v ∈ univ.filter (fun v => x.2 j ⟨_, u⟩ ⟨(y j).1.1, v⟩ = true), +a.changeAt (y j).1.1 m (y j).1.2.2.1 put (.inl v)`. -/ +def received (x : a.Packet m t R) (y : Fin (2 ^ t) → a.Packet m t R) + (put : Bool) (u : x.1.1.Req A) : ℕ := + ∑ j, ∑ v ∈ univ.filter (fun v => x.2 j ⟨_, u⟩ ⟨(y j).1.1, v⟩ = true), + a.changeAt (y j).1.1 m (y j).1.2.2.1 put (.inl v) + +open scoped Classical in +/-- The test of type `Prop` for the given inputs. -/ +def test (μ d : ℕ) (x : a.Packet m t R) (y : Fin (2 ^ t) → a.Packet m t R) : Prop := + a.Valid x.1.1 m (x.1.1.prices A μ d M fun u => (x.1.2.1 u).val) x.1.2.2.1 ∧ + ∀ u, (x.1.2.2.2 u).val = + (x.1.2.1 u).val - a.received m t R x y false u + a.received m t R x y true u + + if u = none then 1 else 0 + +end Atlas +namespace Market + +variable (b : Market I N) (a : Atlas N A M ρ) {m t R : ℕ} (g : b.Ports t) + (c : (i : I) → a.Cell m R (b.code i)) + +open scoped Classical in +/-- The value specified by `(⟨b.code i, c i⟩, b.mask A g i)`. -/ +def packet (i : I) : a.Packet m t R := (⟨b.code i, c i⟩, b.mask A g i) + +open scoped Classical in +theorem received_eq (put : Bool) (i : I) (u : (b.code i).Req A) : + a.received m t R (b.packet a g c i) (fun j => b.packet a g c (g.addr j i)) put u = + b.incoming a m (fun j => (c j).2.1) put i u := by + rw [incoming, ← g.image i, sum_image (g.distinct i)] + change (∑ j, ∑ v ∈ univ.filter (fun v => b.mask A g i j ⟨_, u⟩ ⟨b.code (g.addr j i), v⟩ = true), + a.changeAt (b.code (g.addr j i)) m (c (g.addr j i)).2.1 put (.inl v)) = _ + simp only [mask_test] + rw [← sum_subset (subset_univ (g.use i)) (fun j _ hj => by simp [hj])] + refine sum_congr rfl fun j hj => ?_ + simp only [hj, true_and, sent, eq_comm] + +open scoped Classical in +theorem checked (μ d : ℕ) : + (∀ i, a.test m t R μ d (b.packet a g c i) (fun j => b.packet a g c (g.addr j i))) ↔ + b.Checks a μ d m (fun i x => ((c i).1 x).val) (fun i => (c i).2.1) + (fun i x => ((c i).2.2 x).val) := by + simp only [Atlas.test, Checks, funext_iff, localNext] + refine forall_congr' fun i => and_congr Iff.rfl (forall_congr' fun u => ?_) + erw [received_eq, received_eq] + rfl + +end Market +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Packing the fixed groups for a hop + +Round the common group size up to a power of two. This wastes at +most a factor of two, and allows the smaller groups to be packed +whole into dyadic groups of the prescribed capacity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Coloring + +open scoped Classical in +private theorem dyadic_round (n : ℕ) (hn : 0 < n) : 2 ^ (Nat.clog 2 n) ≤ n * 2 := by + cases he : Nat.clog 2 n with + | zero => simp; omega + | succ k => + rw [pow_succ] + exact Nat.mul_le_mul_right 2 (Nat.pow_lt_of_lt_clog (show k < Nat.clog 2 n by omega)).le + +open scoped Classical in +private theorem group_chart (A D : Type) [Fintype A] [Fintype D] [Nonempty D] (h b : ℕ) + (hb : b ≤ h) (hd : Fintype.card D ≤ 2 ^ b) (ha : Fintype.card A * Fintype.card D ≤ 2 ^ (h + + 1)) : + ∃ f : A × D ↪ B (h + 2 - b) × B b, ∀ i j : A × D, i.1 = j.1 → (f i).1 = (f j).1 := by + let t := Nat.clog 2 (Fintype.card D) + have ht : t ≤ b := Nat.clog_le_of_le_pow hd + have hd' : Fintype.card A * 2 ^ t ≤ 2 ^ (h + 2) := calc + _ ≤ Fintype.card A * (Fintype.card D * 2) := + Nat.mul_le_mul_left _ (dyadic_round _ Fintype.card_pos) + _ ≤ 2 ^ (h + 1) * 2 := by rw [← mul_assoc]; exact Nat.mul_le_mul_right _ ha + _ = _ := (pow_succ _ _).symm + obtain ⟨a⟩ : Nonempty (A ↪ B (h + 2 - b) × B (b - t)) := by + apply Function.Embedding.nonempty_of_card_le + simp only [Fintype.card_prod, Fintype.card_fin, ← pow_add] + apply Nat.le_of_mul_le_mul_right _ (Nat.two_pow_pos t) + rwa [← pow_add, show h + 2 - b + (b - t) + t = h + 2 by omega] + obtain ⟨d⟩ : Nonempty (D ↪ B t) := by + apply Function.Embedding.nonempty_of_card_le + rw [Fintype.card_fin] + exact Nat.le_pow_clog (by decide) _ + let f : B (b - t) × B t ≃ B b := Fintype.equivOfCardEq (by + simp only [Fintype.card_prod, Fintype.card_fin, ← pow_add, Nat.sub_add_cancel ht]) + let g := (a.prodMap d).trans ((Equiv.prodAssoc _ _ _).toEmbedding.trans + ((Equiv.refl _).prodCongr f).toEmbedding) + exact ⟨g, fun _ _ he => congrArg (fun i => (a i).1) he⟩ + +open scoped Classical in +/-- One packing works at the given height for all input permutations. +The group index is unchanged by the selected controller. -/ +theorem Routes.grouping {F : Type} [Field F] {m : ℕ} (T : Routes F m) + {g : controllers F T.embed} (hg : g ∈ T.params.core) (h b : ℕ) + (hb : h / m + T.overhead ≤ b) (hb' : b ≤ h) : + ∃ f : B (h + 1) ↪ B (h + 2 - b) × B b, ∀ σ i, (f ((T.action h σ).smul g i)).1 = (f i).1 := by + obtain ⟨A, D, _, _, s, hd, hs⟩ := T.groups g hg h + have : Nonempty D := ⟨(s (Classical.arbitrary _)).2⟩ + have ha : Fintype.card A * Fintype.card D ≤ 2 ^ (h + 1) := by + rw [← Fintype.card_prod, ← Fintype.card_congr s] + exact (T.size h).2.le + obtain ⟨u, hu⟩ := group_chart A D h b hb' (hd.trans (Nat.pow_le_pow_right (by decide) hb)) ha + obtain ⟨v⟩ : Nonempty (B (h + 1) ↪ B (h + 2 - b) × B b) := by + apply Function.Embedding.nonempty_of_card_le + simp only [Fintype.card_prod, Fintype.card_fin, ← pow_add] + exact Nat.pow_le_pow_right (by decide) (by omega) + obtain ⟨p, hp⟩ := Equiv.Perm.exists_extending_pair ((T.embed h).trans v) (s.toEmbedding.trans u) + ((T.embed h).trans v).injective (s.toEmbedding.trans u).injective + let f := v.trans p.toEmbedding + have he (i : T.labels h) : f (T.embed h i) = u (s i) := hp i + refine ⟨f, fun σ i => ?_⟩ + let q := g.val h (σ.viaEmbedding (T.base h)) + change (f (q.viaEmbedding (T.embed h) i)).1 = _ + by_cases hi : i ∈ Set.range (T.embed h) + · obtain ⟨j, rfl⟩ := hi + rw [Equiv.Perm.viaEmbedding_apply, he, he] + exact hu _ _ (hs _ _) + · rw [Equiv.Perm.viaEmbedding_apply_of_notMem _ _ _ hi] + +open scoped Classical in +/-- Ports using the same generator retain a common group across each +hop. A group has at most the slot multiplicity times the site capacity. -/ +theorem Routes.portGroup {F : Type} [Field F] {m : ℕ} (T : Routes F m) + (h b p : ℕ) (hb : h / m + T.overhead ≤ b) (hb' : b ≤ h) (f : B p → T.params.core) : + ∃ group : B (h + 1) × B p → ℕ, + (∀ i, (Finset.univ.filter (fun k => group k = i)).card ≤ 2 ^ (b + p)) ∧ + ∀ σ x y i j, f i = f j → (T.action h σ).smul (f i).val x = y → + group (x, i) = group (y, j) := by + choose d hd using fun g : T.params.core => T.grouping g.property h b hb hb' + let group := fun k : B (h + 1) × B p => (d (f k.2) k.1).1.val + refine ⟨group, ?_, ?_⟩ + · intro i + let g := fun k : B (h + 1) × B p => ((d (f k.2) k.1).2, k.2) + have he : (Finset.univ.filter (fun k => group k = i)).card ≤ + (Finset.univ : Finset (B b × B p)).card := by + refine Finset.card_le_card_of_injOn g (fun _ _ => Finset.mem_univ _) ?_ + rintro ⟨x, j⟩ hx ⟨y, l⟩ hy hxy + obtain ⟨he, rfl⟩ := Prod.mk.inj hxy + have hh := (Finset.mem_filter.mp hx).2.trans (Finset.mem_filter.mp hy).2.symm + exact Prod.ext ((d (f j)).injective (Prod.ext (Fin.ext hh) he)) rfl + simpa [pow_add] using he + · intro σ x y i j he hh + subst y + change (d (f i) x).1.val = (d (f j) ((T.action h σ).smul (f i).val x)).1.val + rw [← he, hd] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Parameters.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Parameters.lean new file mode 100644 index 0000000000..297688b696 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Parameters.lean @@ -0,0 +1,670 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Round +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Control.Decor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Uniform.System +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryPrices + +/-! +# Parameters for routing on packed permutations +-/ + +@[expose] public section + +section +/- The three-stage routing problem on packed permutations. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +/-- A single controller works for every input permutation preserving +the base of the given product chart. Entries outside the packed set +are unspecified. The cost exponent is uniform over all charts. -/ +def Factors (F : Type) [Field F] (cost : ℕ) : Prop := + ∀ (h : ℕ) (X C A D : Type) [Fintype X] [Fintype C] [Fintype A] [Fintype D] + (s : X ≃ C × (A × D)) (e : X ↪ B h), + ∃ f, Cheap F h h (Perm h) (.pair (Perm h) (.pair (Perm h) (Perm h))) f cost ∧ + ∀ (g : Equiv.Perm X), (∀ i, (s (g i)).1 = (s i).1) → + ∀ y : (Perm h).obj, (∀ i, y (e i) = e (g i)) → + ∃ u v w : Equiv.Perm X, g = u * v * w ∧ + (∀ i, (s (u i)).1 = (s i).1 ∧ (s (u i)).2.1 = (s i).2.1) ∧ + (∀ i, (s (v i)).1 = (s i).1 ∧ (s (v i)).2.2 = (s i).2.2) ∧ + (∀ i, (s (w i)).1 = (s i).1 ∧ (s (w i)).2.1 = (s i).2.1) ∧ + (∀ i, (f y).1 (e i) = e (u i)) ∧ (∀ i, (f y).2.1 (e i) = e (v i)) ∧ + (∀ i, (f y).2.2 (e i) = e (w i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +/- +# A bounded-overlap market from a finite set of group elements +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral +open scoped Pointwise + +variable {G I K S : Type} [Group G] [MulAction G I] (H : Finset G) (hH : 1 ∈ H) + (r : ℕ) (g : G) (hg : letI := Classical.decEq G; g ∈ H ^ r) + +open scoped Classical in +/-- The value specified by `Board.choose H r hH g hg ⟨I, i⟩`. -/ +abbrev board (i : I) : Board H r := Board.choose H r hH g hg ⟨I, i⟩ + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def labels (i : I) : (board H hH r g hg i).Site ≃ ball H r i := + Equiv.ofBijective (Board.name ⟨I, i⟩ (board H hH r g hg i)) + ((Board.valid_iff _ _ _).mp (Board.valid_choose H r hH g hg ⟨I, i⟩)).1 + +open scoped Classical in +/-- Builds `Market I (H ^ r).card where size i` with the specified `size`, `shape`, `name`, +`origin`. -/ +def market : Market I (H ^ r).card where + size i := (board H hH r g hg i).1.1 + shape i := (board H hH r g hg i).1.2 + name i := (labels H hH r g hg i).toEmbedding.trans (Function.Embedding.subtype _) + origin i := ((Board.valid_iff _ _ _).mp (Board.valid_choose H r hH g hg ⟨I, i⟩)).2.1 + overlap x := by + refine ⟨(H ^ r).image (fun a => a • x), Finset.card_image_le, fun i t ht => ?_⟩ + have hx : x ∈ ball H r i := ht ▸ (labels H hH r g hg i t).property + obtain ⟨a, ha, he⟩ := Finset.mem_image.mp hx + exact Finset.mem_image.mpr ⟨a, ha, by simp [← he]⟩ + +variable [Field K] [Fintype S] [DecidableEq S] (A : Finset (Tensor K S)) + +open scoped Classical in +theorem market_dst (i : I) : + (market H hH r g hg).name i ((market H hH r g hg).shape i).dst = g⁻¹ • i := + ((Board.valid_iff _ _ _).mp (Board.valid_choose H r hH g hg ⟨I, i⟩)).2.2.1 + +open scoped Classical in +theorem market_link (i : I) (e : ((market H hH r g hg).shape i).edges) : + let n := (market H hH r g hg).name i + link H (n e.val.1) (n e.val.2) ∨ link H (n e.val.2) (n e.val.1) := + (((Board.valid_iff _ _ _).mp (Board.valid_choose H r hH g hg ⟨I, i⟩)).2.2.2 _ _).mp e.property + +open scoped Classical in +theorem market_edge (i : I) (x y : ball H r i) (he : link H x.val y.val) : + ((labels H hH r g hg i).symm x, (labels H hH r g hg i).symm y) ∈ + ((market H hH r g hg).shape i).edges := by + let e := labels H hH r g hg i + apply (((Board.valid_iff _ _ _).mp (Board.valid_choose H r hH g hg ⟨I, i⟩)).2.2.2 _ _).mpr + left + change link H (e (e.symm x)).val (e (e.symm y)).val + simpa using he + +variable [Fintype I] + +open scoped Classical in +theorem market_passes (p : (market (I := I) H hH r g hg).Request A → ℝ) (ρ : ℝ) (i : I) + (hp : let b := market H hH r g hg + NearPrices ((b.shape i).tensor A) ((b.shape i).demands A) ρ (b.rates A p ∘ b.assign A i)) : + ∃ P, (P = 0 ∨ ∃ D, P ∈ Tensor.ordinary K (ball H r i) D) ∧ + Passes A (ball H r i) (link H) i (g⁻¹ • i) (p (.inl i)) ((market H hH r g hg).quote A p) ρ P + := by + let b := market (I := I) H hH r g hg + let e := (labels H hH r g hg i).symm + change NearPrices _ _ _ (b.rates A p ∘ b.assign A i) at hp + rw [b.rates_assign] at hp + obtain ⟨P, hP, he⟩ := BallShape.near_passes A (b.shape i) e (link H) + (market_edge H hH r g hg i) (p (.inl i)) (b.quote A p) ρ hp + change Passes _ _ _ (b.name i (b.shape i).src) (b.name i (b.shape i).dst) _ _ _ _ at he + rw [b.origin, show b.name i (b.shape i).dst = _ from market_dst H hH r g hg i] at he + exact ⟨P, hP, he⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Direct transport along an orbit path + +The baseline price of a payload is its path length. The path stays +inside its own center's ball, even when the radius is larger. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral +open scoped Pointwise + +variable {I G K B : Type} [Group G] [MulAction G I] [Field K] [Fintype B] [DecidableEq B] + +namespace BallShape + +variable (K) (b : BallShape B) + +open scoped Classical in +/-- Uses `Tensor.wire K e.val.1 e.val.2 2` as the representation. -/ +def wire (e : b.edges) := Tensor.wire K e.val.1 e.val.2 2 + +open scoped Classical in +/-- The condition `∃ z : b.edges → ℕ, (∑ e, z e) ≤ d ∧ D ≤ Stock.bundle (b.wire K) z` on the +specified data. -/ +def Direct (D : Tensor K B) (d : ℕ) : Prop := + ∃ z : b.edges → ℕ, (∑ e, z e) ≤ d ∧ D ≤ Stock.bundle (b.wire K) z + +open scoped Classical in +theorem direct_self (x : B) : b.Direct K (Tensor.wire K x x 2) 0 := by + refine ⟨fun _ => 0, by simp, ?_⟩ + simp [Stock.bundle, Tensor.wire_self K x (n := 2) (by decide)] + +open scoped Classical in +theorem direct_step (x y t : B) (d : ℕ) (h : (y, t) ∈ b.edges) + (h' : b.Direct K (Tensor.wire K x y 2) d) : b.Direct K (Tensor.wire K x t 2) (d + 1) := by + obtain ⟨z, hz, hz'⟩ := h' + let e : b.edges := ⟨(y, t), h⟩ + refine ⟨fun i => Stock.copies {e} 1 i + z i, ?_, ?_⟩ + · rw [Finset.sum_add_distrib] + have he : (∑ i, Stock.copies {e} 1 i) = 1 := by simp [Stock.copies] + rw [he] + omega + · rw [Stock.bundle_add, Stock.bundle_copies, Finset.prod_singleton, pow_one] + refine (Tensor.wire_triangle K x y t 2).trans ?_ + rw [mul_comm] + exact Tensor.mul_le_mul_left _ _ _ hz' + +end BallShape + +open scoped Classical in +theorem market_path (H : Finset G) (hH : 1 ∈ H) (r : ℕ) (g : G) (hg : g ∈ H ^ r) + (d : ℕ) (hd : d ≤ r) (hgd : g ∈ H ^ d) (i : I) : + let b := (market H hH r g hg).shape i + b.Direct K (Tensor.wire K b.src b.dst 2) d := by + let V := ball H r i + let e := (labels H hH r g hg i).symm + let b := (market H hH r g hg).shape i + let Q (x : I) (n : ℕ) := ∀ hx : x ∈ V, b.Direct K (Tensor.wire K b.src (e ⟨x, hx⟩) 2) n + have q : Q (g⁻¹ • i) d := by + refine ball_path hH i (Q := Q) ?_ ?_ hd hgd + · intro hi + have he : e ⟨i, hi⟩ = b.src := (labels H hH r g hg i).symm_apply_eq.mpr + (Subtype.ext ((market H hH r g hg).origin i).symm) + change b.Direct K (Tensor.wire K b.src (e ⟨i, hi⟩) 2) 0 + rw [he] + exact b.direct_self K _ + · intro x hx y hy n hxy hx' _ + have he := market_edge H hH r g hg i ⟨x, hx⟩ ⟨y, hy⟩ hxy + exact b.direct_step K _ _ _ n he (hx' hx) + have he : e ⟨g⁻¹ • i, mem_ball i hg⟩ = b.dst := (labels H hH r g hg i).symm_apply_eq.mpr + (Subtype.ext (market_dst H hH r g hg i).symm) + change b.Direct K (Tensor.wire K b.src b.dst 2) d + rw [← he] + exact q (mem_ball i hg) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Uniform cost of supplying a local tensor + +On a fixed shape a connected core can broadcast as many labels as +the coordinate expansion requires. There are only finitely many +shapes and tuple commodities, so a uniform cap suffices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral + +variable {K S B : Type} [Field K] [Fintype S] [DecidableEq S] [Fintype B] [DecidableEq B] + +open scoped Classical in +theorem BallShape.Direct.mono {b : BallShape B} {D : Tensor K B} {d e : ℕ} + (h : b.Direct K D d) (he : d ≤ e) : b.Direct K D e := by + obtain ⟨z, h, h'⟩ := h + exact ⟨z, h.trans he, h'⟩ + +open scoped Classical in +theorem BallShape.direct_exists (b : BallShape B) (D : Tensor K B) : ∃ n, b.Direct K D n := by + let _ : Nonempty B := ⟨b.src⟩ + have hc := b.broadcast (∅ : Finset (Tensor K B)) + rw [BallShape.links, Finset.prod_map] at hc + change (2 : Tensor K B) ≤ ∏ e, b.wire K e at hc + obtain ⟨n, hn⟩ := Tensor.exists_bound D + have he := (Tensor.natCast_le (K := K) (S := B) (Nat.lt_two_pow_self (n := n)).le) + rw [Nat.cast_pow, Nat.cast_ofNat] at he + refine ⟨_, fun _ => n, le_rfl, (hn.trans he).trans ?_⟩ + rw [Stock.bundle, Finset.prod_pow] + exact Tensor.powers_le hc _ + +open scoped Classical in +/-- The condition `∀ (b : Shape N) (j : b.2.Goods A), b.2.Direct K (b.2.tensor A j) M` on the +specified data. -/ +def UniformCap (N : ℕ) (A : Finset (Tensor K S)) (M : ℕ) : Prop := + ∀ (b : Shape N) (j : b.2.Goods A), b.2.Direct K (b.2.tensor A j) M + +open scoped Classical in +theorem uniform_cap (N : ℕ) (A : Finset (Tensor K S)) (d : ℕ) : + ∃ M : ℕ, d ≤ M ∧ UniformCap N A M := by + let _ : Fintype (Shape N) := Fintype.ofFinite _ + let J := Σ b : Shape N, b.2.Goods A + choose n hn using fun j : J => j.1.2.direct_exists (j.1.2.tensor A j.2) + refine ⟨d + ∑ j, n j, Nat.le_add_right _ _, fun b j => ?_⟩ + refine (hn ⟨b, j⟩).mono ?_ + exact (Finset.single_le_sum (fun i _ => Nat.zero_le (n i)) (Finset.mem_univ _)).trans + (Nat.le_add_left _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Many admissible substitutions when payload prices are high +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral +open scoped BigOperators Pointwise + +variable {I G K S : Type} [Field K] [Fintype S] [DecidableEq S] [Fintype I] [Nonempty I] + +open scoped Classical in +/-- The defining condition `∀ p : b.Request A → ℝ, (∀ i, |p (.inl i)| ≤ d) → 1201 < (𝔼 i, p +(.inl i)) → ∃ J : Finset I, ρ * Fintype.card I < J.card ∧ ∀ i ∈ J, b.Fails A p ρ i`. -/ +def Market.Frequent {N : ℕ} (b : Market I N) (A : Finset (Tensor K S)) (ρ d : ℝ) : Prop := + ∀ p : b.Request A → ℝ, (∀ i, |p (.inl i)| ≤ d) → 1201 < (𝔼 i, p (.inl i)) → + ∃ J : Finset I, ρ * Fintype.card I < J.card ∧ ∀ i ∈ J, b.Fails A p ρ i + +variable [Group G] [MulAction G I] + +open scoped Classical in +theorem market_frequent (H : Finset G) (hH : 1 ∈ H) (r : ℕ) (g : G) (hg : g ∈ H ^ r) + (A : Finset (Tensor K S)) (ρ d : ℝ) + (h : ∀ (v : I → ℝ) (x : (S → I) → Tensor K S → ℝ) (good : Set I), + (∀ i, |v i| ≤ d) → badFraction good ≤ ρ → + (∀ i ∈ good, ∃ P : Tensor K (ball H r i) → ℝ, + (P = 0 ∨ ∃ D, P ∈ Tensor.ordinary K (ball H r i) D) ∧ + Passes A (ball H r i) (link H) i (g⁻¹ • i) (v i) x ρ P) → + (𝔼 i, v i) ≤ 1201) : (market (I := I) H hH r g hg).Frequent A ρ d := by + let b := market (I := I) H hH r g hg + intro p hp h₀ + let J := Finset.univ.filter (b.Fails A p ρ) + let good := {i | ¬ b.Fails A p ρ i} + refine ⟨J, ?_, fun i hi => (Finset.mem_filter.mp hi).2⟩ + by_contra! hsmall + apply h₀.not_ge + apply h _ (b.quote A p) good hp + · rw [badFraction, Fintype.expect_eq_sum_div_card, div_le_iff₀ (by positivity)] + simp only [J, Finset.card_filter, Nat.cast_sum, Nat.cast_ite, Nat.cast_one, Nat.cast_zero] + at hsmall + refine le_trans (le_of_eq (Finset.sum_congr rfl fun i _ => ?_)) hsmall + by_cases h : b.Fails A p ρ i <;> simp [good, h] + · intro i hi + exact market_passes H hH r g hg A p ρ i (not_not.mp hi) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Certified rounds in a bounded-overlap market +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Market + +open Spectral +open scoped BigOperators + +variable {I S K : Type} [Fintype I] [DecidableEq I] [Fintype S] [DecidableEq S] [Field K] + {N : ℕ} (b : Market I N) (A : Finset (Tensor K S)) + +open scoped Classical in +/-- Computes the payload by the application `Finset.univ.map Function.Embedding.inl`. -/ +def payload : Finset (b.Request A) := Finset.univ.map Function.Embedding.inl + +omit [DecidableEq I] [DecidableEq S] in +open scoped Classical in +theorem card_payload : (b.payload A).card = Fintype.card I := by simp [payload] + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def cap (d M : ℕ) : b.Request A → ℝ := Sum.elim (fun _ => d) (fun _ => M) + +variable {A} {M : ℕ} {ρ : ℝ} + +open scoped Classical in +/-- Record the actual local moves, besides the induced order relation and +the volume bound for each newly issued request. -/ +def Allowed (a : Atlas N A M ρ) (m : ℕ) (q : Intervention (b.Request A) b.Edge) : Prop := + q.Covers (b.tensor A ∘ Sum.inl) (b.tensor A ∘ Sum.inr) ∧ + (∀ u i, q.put u i ≤ N * (a.capacity * m)) ∧ + ∃ (J : Finset I) (moves : (i : J) → (b.code i).Move A), + (∀ i : J, moves i ∈ a.menu (b.code i)) ∧ + q = Intervention.parallel (fun i : J => b.batch A i (moves i) m) + +open scoped Classical in +theorem high_price_round [Nonempty I] [Nonempty S] + (a : Atlas N A M ρ) (hM : 1 ≤ M) (m d : ℕ) (hd : d ≤ M) + (hf : b.Frequent A ρ d) + (p : b.Request A → ℝ) (hp : ∀ i, 0 ≤ p i ∧ p i ≤ b.cap A d M i) + (h : 1201 * (b.payload A).card < ∑ i ∈ b.payload A, p i) : + ∃ (J : Type) (_ : Fintype J) (_ : DecidableEq J) (q : J → Intervention (b.Request A) b.Edge), + ρ * (b.payload A).card ≤ Fintype.card J ∧ Intervention.Overlap q N ∧ + (∀ j, (q j).Efficient p a.margin a.capacity m) ∧ b.Allowed a m (Intervention.parallel q) := by + have hp' (i) : p i ∈ Set.Icc 0 (M : ℝ) := by + refine ⟨(hp i).1, (hp i).2.trans ?_⟩ + cases i with + | inl x => exact Nat.cast_le.mpr hd + | inr x => exact le_rfl + have hp'' (i) : |p (.inl i)| ≤ d := by + rw [abs_of_nonneg (hp _).1] + exact (hp _).2 + have h' : 1201 < (𝔼 i, p (.inl i)) := by + rw [Fintype.expect_eq_sum_div_card, lt_div_iff₀ (by positivity)] + rw [card_payload, payload, Finset.sum_map] at h + exact h + obtain ⟨J, hJ, hj⟩ := hf p hp'' h' + choose moves hmove htrade using fun i : J => + b.choose_batch a (by exact_mod_cast hM) p hp' i (hj _ i.property) + let q := fun i : J => b.batch A i (moves i) m + have ho : Intervention.Overlap q N := b.batch_overlap J moves m + have he (i : J) : (q i).Efficient p a.margin a.capacity m := (htrade i m).2 + refine ⟨J, inferInstance, inferInstance, q, ?_, ho, he, + Intervention.parallel_covers q (fun i => (htrade i m).1), ?_, J, moves, hmove, rfl⟩ + · simpa only [card_payload, Fintype.card_coe] using hJ.le + · exact fun u i => (Intervention.parallel_bounds q ho he i).2.2 u + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +end + +/- +# Width at each core slot + +Slots of different centers carry separate labels. Within a center the +selector communication is paid on top of the stock for the supplied +link tensors. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral Stock Finset + +variable {I E J K S : Type} [Fintype I] [DecidableEq I] [DecidableEq E] [Fintype J] [DecidableEq J] + [Field K] [Fintype S] + +omit [Fintype I] in +open scoped Classical in +theorem Proposal.trade_core {T : J → Tensor K S} {H : ℝ} (q : Proposal T H) + (g : J → I ⊕ E) (hg : Function.Injective g) (u : Finset J) (m C : ℕ) + (ho : ∀ j, ∑ k, q.move.count j k ≤ C) (h : (q.trade g u m).choice) (e : E) : + (q.trade g u m).core h e ≤ (q.move.bits + C) * m := by + by_cases hz : (q.trade g u m).core h e = 0 + · rw [hz]; exact Nat.zero_le _ + obtain ⟨j, hj, _⟩ := collect_nonzero hz + change collect g _ (.inr e) ≤ _ + rw [← hj, collect_inj hg, Proposal.output, add_mul] + apply Nat.add_le_add + · unfold copies + split <;> simp + · calc + _ ≤ ∑ k, C * h.val k := by + apply sum_le_sum + intro k _ + apply Nat.mul_le_mul_right + exact (sum_le_sum_of_subset (filter_subset _ _)).trans (ho k) + _ = _ := by rw [← mul_sum, mem_histograms.mp h.property] + +omit [Fintype I] in +open scoped Classical in +theorem Proposal.trade_edge {T : J → Tensor K S} {H : ℝ} (q : Proposal T H) + (g : J → I ⊕ E) (u : Finset J) (m : ℕ) (h : (q.trade g u m).choice) (e : E) + (hn : (q.trade g u m).core h e ≠ 0) : ∃ j, g j = .inr e := by + obtain ⟨j, hj, _⟩ := collect_nonzero hn + exact ⟨j, hj⟩ + +variable [DecidableEq S] {A : Finset (Tensor K S)} {N M : ℕ} {ρ : ℝ} + +open scoped Classical in +theorem Market.width (b : Market I N) (a : Atlas N A M ρ) (C : ℕ) + (hc : ∀ s q, q ∈ a.menu s → q.move.bits ≤ C) + (m : ℕ) (q : Intervention (b.Request A) b.Edge) (hq : b.Allowed a m q) + (h : q.choice) (e : b.Edge) : q.core h e ≤ (C + a.capacity) * m := by + obtain ⟨_, _, J, moves, hm, rfl⟩ := hq + let v (j : J) := (b.batch A j (moves j) m).core (h j) e + have zero (j : J) (hj : j.val ≠ e.1) : v j = 0 := by + by_contra hn + obtain ⟨i, hi⟩ := (moves j).trade_edge _ _ _ _ _ hn + rcases i with x | y + · contradiction + · exact hj (congrArg Sigma.fst (Sum.inr.inj hi)) + change (∑ j, v j) ≤ _ + by_cases he : e.1 ∈ J + · let j : J := ⟨e.1, he⟩ + rw [Fintype.sum_eq_single j (fun i hi => zero i fun h => hi (Subtype.ext h))] + exact ((moves j).trade_core _ (b.assign_injective _ _) _ _ _ (a.small _ _ (hm j)).2 _ e).trans + (Nat.mul_le_mul_right _ (Nat.add_le_add_right (hc _ _ (hm j)) _)) + · rw [sum_eq_zero (fun j _ => zero j fun h => he (h ▸ j.property))] + exact Nat.zero_le _ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Polynomial cost of choosing histograms in parallel -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Atlas + +open Spectral Finset + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] + {N : ℕ} {A : Finset (Tensor K S)} {ρ : ℝ} + +/-- The atlas has finitely many shapes and finitely many moves at each shape. -/ +theorem bound {M : ℝ} (a : Atlas N A M ρ) (f : (b : Shape N) → b.Move A → ℕ) : + ∃ D, ∀ b q, q ∈ a.menu b → f b q ≤ D := by + classical + let _ : Fintype (Shape N) := Fintype.ofFinite _ + let g (b : Shape N) := (a.menu b).sup (f b) + exact ⟨univ.sup g, fun b q h => + (le_sup (f := f b) h).trans (le_sup (f := g) (mem_univ b))⟩ + +/-- Each selected center contributes a histogram on a bounded alphabet. -/ +theorem card_choice {M : ℕ} (a : Atlas N A M ρ) : + ∃ C : ℕ, ∀ (I : Type) [Fintype I] [DecidableEq I] (b : Market I N) (m : ℕ) + (q : Intervention (b.Request A) b.Edge), + b.Allowed a m q → Fintype.card q.choice ≤ (m + 1) ^ (C * Fintype.card I) := by + classical + obtain ⟨C, hC⟩ := a.bound (fun _ q => Fintype.card q.move.letter) + refine ⟨C, fun I _ _ b m q h => ?_⟩ + obtain ⟨_, _, J, moves, hm, rfl⟩ := h + change Fintype.card (∀ i : J, ↥(histograms (moves i).move.letter m)) ≤ _ + rw [Fintype.card_pi] + calc + _ ≤ ∏ _ : J, (m + 1) ^ C := by + apply prod_le_prod + intro i _ + rw [Fintype.card_coe] + exact (card_histograms _ _).trans (Nat.pow_le_pow_right (by omega) (hC _ _ (hm i))) + _ = (m + 1) ^ (C * J.card) := by rw [prod_const, card_univ, Fintype.card_coe, pow_mul] + _ ≤ _ := Nat.pow_le_pow_right (by omega) (Nat.mul_le_mul_left C (card_le_univ J)) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Atlas +end + +/- +# Terminal supply of outstanding requests + +Each request can be assigned a route wholly inside one ball. Thus +each edge is charged by only boundedly many request types. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +open Spectral + +variable {I S K : Type} [Fintype I] [DecidableEq I] [Fintype S] [DecidableEq S] [Field K] + {N d M : ℕ} (b : Market I N) (A : Finset (Tensor K S)) + +open scoped Classical in +/-- The condition `∀ i, (b.shape i).Direct K ((b.shape i).tensor A (.inl none)) d` on the +specified data. -/ +def ready (d : ℕ) : Prop := + ∀ i, (b.shape i).Direct K ((b.shape i).tensor A (.inl none)) d + +open scoped Classical in +theorem supply_route (i : I) (j : BallShape.Requests (b.Site i) A) + (h : (b.shape i).Direct K ((b.shape i).tensor A (.inl j)) d) : + ∃ z : b.Edge → ℕ, (∑ e, z e) ≤ d ∧ + b.tensor A (.inl (b.request A i j)) ≤ Stock.bundle (b.tensor A ∘ Sum.inr) z ∧ + ∀ e, z e ≠ 0 → e.1 = i := by + obtain ⟨z, hz, hz'⟩ := h + let g : (b.shape i).edges → b.Edge := fun e => ⟨i, e⟩ + refine ⟨Stock.collect g z, ?_, ?_, ?_⟩ + · rw [show (∑ e, Stock.collect g z e) = ∑ e, z e from Finset.sum_fiberwise _ _ _] + exact hz + · rw [Stock.bundle_collect] + let F : Tensor K (b.Site i) →* Tensor K I := + { toFun := Tensor.place (b.name i) + map_one' := Tensor.place_one _ + map_mul' := Tensor.place_mul _ } + have he : F ((b.shape i).tensor A (.inl j)) ≤ F (Stock.bundle ((b.shape i).wire K) z) := + Tensor.place_mono _ hz' + refine (b.place_tensor A i (.inl j)).symm.le.trans (he.trans_eq ?_) + unfold Stock.bundle + rw [map_prod] + refine Finset.prod_congr rfl fun e _ => ?_ + rw [map_pow] + exact congrArg (· ^ z e) (b.place_tensor A i (.inr e)) + · intro e he + obtain ⟨k, hk, _⟩ := Stock.collect_nonzero he + exact congrArg Sigma.fst hk.symm + +omit [Fintype I] [DecidableEq I] in +open scoped Classical in +theorem local_count (i : I) : + Fintype.card (BallShape.Requests (b.Site i) A) ≤ 1 + N ^ Fintype.card S * A.card := by + simp only [BallShape.Requests, Fintype.card_option, Fintype.card_prod, Fintype.card_fun, + Site, Fintype.card_fin, add_comm 1] + exact Nat.add_le_add_right (Nat.mul_le_mul_right _ + (Nat.pow_le_pow_left (Nat.lt_succ_iff.mp (b.size i).isLt) _)) _ + +open scoped Classical in +theorem supply (h : b.ready A d) (hd : d ≤ M) (hM : UniformCap N A M) : + ∃ z : b.Request A → b.Edge → ℕ, + (∀ x, (∑ e, z x e : ℕ) ≤ b.cap A d M x ∧ + b.tensor A (.inl x) ≤ Stock.bundle (b.tensor A ∘ Sum.inr) (z x)) ∧ + ∀ e, ∑ x, z x e ≤ (1 + N ^ Fintype.card S * A.card) * M := by + let U (i : I) := Finset.univ.image (b.request A i) + have hu (i) : (U i).card ≤ 1 + N ^ Fintype.card S * A.card := + Finset.card_image_le.trans (b.local_count A i) + have each (x : b.Request A) : ∃ z : b.Edge → ℕ, + (∑ e, z e : ℕ) ≤ b.cap A d M x ∧ + b.tensor A (.inl x) ≤ Stock.bundle (b.tensor A ∘ Sum.inr) z ∧ + ∀ e, z e ≠ 0 → x ∈ U e.1 := by + rcases x with i | ⟨⟨z, ⟨i, u⟩, rfl⟩, j⟩ + · obtain ⟨z, hz, ht, hu⟩ := b.supply_route A i none (h i) + refine ⟨z, Nat.cast_le.mpr hz, ht, fun e he => ?_⟩ + rw [hu e he] + exact Finset.mem_image_of_mem _ (Finset.mem_univ none) + · let a := some (u, j) + obtain ⟨z, hz, ht, hu⟩ := b.supply_route A i a (hM (b.code i) (.inl a)) + refine ⟨z, Nat.cast_le.mpr hz, ht, fun e he => ?_⟩ + rw [hu e he] + exact Finset.mem_image_of_mem _ (Finset.mem_univ a) + choose z hz ht he using each + refine ⟨z, fun x => ⟨hz x, ht x⟩, fun e => ?_⟩ + rw [← Finset.sum_subset (Finset.subset_univ (U e.1)) + (fun x _ hx => Classical.byContradiction (fun hn => hx (he x e hn)))] + calc + _ ≤ ∑ _ ∈ U e.1, M := Finset.sum_le_sum fun x _ => by + have hcap : b.cap A d M x ≤ M := by cases x <;> simp [cap, hd] + exact (Finset.single_le_sum (fun i _ => Nat.zero_le (z x i)) (Finset.mem_univ e)).trans + (Nat.cast_le.mp ((hz x).trans hcap)) + _ ≤ _ := by simpa using Nat.mul_le_mul_right M (hu e.1) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Market +end + +/- +# Finite parameters uniform over permutation actions + +The finite detection radius may exceed the designated payload path +length. Keeping these separate permits an independent cap for all +auxiliary requests created inside a ball. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral +open scoped Pointwise + +variable {k G J E A B E' A' B' : Type} [Field k] [Group G] + +open scoped Classical in +/-- The data for the parameters construction, including `sites`, `start`, `core`, `unit`, `hop`. -/ +structure Parameters (k : Type) [Field k] (K : J → Subgroup G) (g : G) where + /-- The `Parameters` component of type `Finset G`. -/ + sites : Finset G + start : 1 ∈ sites + /-- The `Parameters` component of type `Finset G`. -/ + core : Finset G + unit : 1 ∈ core + hop : (↑core : Set G) ⊆ hops K + /-- Stores the path associated with this `Parameters`. -/ + path : ℕ + /-- Stores the radius associated with this `Parameters`. -/ + radius : ℕ + path_pos : 0 < path + path_le : path ≤ radius + route : g ∈ core ^ path + reach : g ∈ core ^ radius + /-- The local table at each indexed position carried by `Parameters`, with type `Finset + (Tensor k sites)`. -/ + table : Finset (Tensor k sites) + nz : 0 ∉ table + /-- Stores the tolerance associated with this `Parameters`. -/ + tolerance : ℝ + pos : 0 < tolerance + /-- Stores the limit associated with this `Parameters`. -/ + limit : ℕ + pay : path ≤ limit + local_supply : UniformCap (core ^ radius).card table limit + /-- The `Parameters` component of type `Atlas (core ^ radius).card table limit tolerance`. -/ + offers : Atlas (core ^ radius).card table limit tolerance + frequent : ∀ (I : Type) [Fintype I] [Nonempty I] [MulAction G I], + (market (I := I) core unit radius g reach).Frequent table tolerance path + +variable {K : J → Subgroup G} {g : G} + +namespace Parameters + +open scoped Classical in +/-- The value specified by `market (I := I) a.core a.unit a.radius g a.reach`. -/ +abbrev balls (a : Parameters k K g) (I : Type) [MulAction G I] := + market (I := I) a.core a.unit a.radius g a.reach + +open scoped Classical in +theorem ready (a : Parameters k K g) (I : Type) [MulAction G I] : + (a.balls I).ready a.table a.path := + fun i => market_path _ _ _ _ _ _ a.path_le a.route i + +end Parameters + +variable [Fintype E] [Fintype A] [Fintype E'] [Fintype A'] + [Nonempty E] [Nonempty A] [Nonempty E'] [Nonempty A'] [Nonempty J] + {p : E → A} {l : E → B} {p' : E' → A'} {l' : E' → B'} + +open scoped Classical in +theorem Rigid.parameters (hgen : iSup K = ⊤) (h : Rigid (hops K) p l p' l') + (hm : HasModels k p l p' l') (g : G) : Nonempty (Parameters k K g) := by + obtain ⟨S, H, d, r, T, ρ, hS, hH, _, hhop, hd, hdr, hgd, hT, hρ, hh⟩ := + Rigid.finite_detection K hgen h hm g + have hgr := Finset.pow_subset_pow_right hH hdr hgd + let _ : Nonempty S := ⟨⟨1, hS⟩⟩ + obtain ⟨M, hdM, hM⟩ := uniform_cap (H ^ r).card T d + obtain ⟨a⟩ := atlas (H ^ r).card T hT M hρ + exact ⟨⟨S, hS, H, hH, hhop, d, r, hd, hdr, hgd, hgr, T, hT, ρ, hρ, M, hdM, hM, a, + fun I _ _ _ => market_frequent H hH r g hgr T ρ d (hh I)⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Partitions.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Partitions.lean new file mode 100644 index 0000000000..0ab1b25358 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Partitions.lean @@ -0,0 +1,895 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Combinatorics.Hall.Finite +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Finset.Prod +public import Mathlib.Data.Fintype.Perm +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryTerms +public import Mathlib.GroupTheory.GroupAction.Basic +public import Mathlib.Algebra.Group.Subgroup.Basic +public import Mathlib.Algebra.Group.End +public import Mathlib.Algebra.Group.Pi.Basic +public import Mathlib.Data.Fintype.Prod +public import Mathlib.Logic.Equiv.Prod +public import Mathlib.Data.Fin.Tuple.Basic +public import Mathlib.Analysis.SpecificLimits.Basic + +/-! +# Routing permutations of a finite product + +Peel off perfect matchings between the source and destination first coordinates. +Each matching becomes a row by permuting second coordinates before and after +the given permutation. This is an existence result without runtime bounds. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Equiv + +variable {A B : Type*} [Fintype A] + +omit [Fintype A] in +/-- A bijection fixing the row of every point outside `s` preserves the +remaining rows as a set. -/ +private lemma stays_inside [Finite A] (g : Perm (A × B)) (s : Finset B) + (hg : ∀ a b, b ∉ s → (g (a, b)).2 = b) (a : A) (b : B) (hb : b ∈ s) : + (g (a, b)).2 ∈ s := by + let : Fintype A := Fintype.ofFinite A + by_contra h + let c := (g (a, b)).2 + have inj : Function.Injective (fun x => (g (x, c)).1) := by + intro x y hxy + exact congrArg Prod.fst (g.injective (Prod.ext hxy ((hg x c h).trans (hg y c h).symm))) + obtain ⟨x, hx⟩ := inj.bijective_of_finite.2 (g (a, b)).1 + have he : (x, c) = (a, b) := g.injective (Prod.ext hx (hg x c h)) + have : c = b := congrArg Prod.snd he + exact h (show c ∈ s from this.symm ▸ hb) + +omit [Fintype A] in +private lemma matching [Finite A] (g : Perm (A × B)) (s : Finset B) (hs : s.Nonempty) + (hg : ∀ a b, b ∉ s → (g (a, b)).2 = b) : + ∃ p : Perm A, ∀ a, ∃ b ∈ s, (g (a, b)).1 = p a := by + classical + let : Fintype A := Fintype.ofFinite A + let N (a : A) := s.image fun b => (g (a, b)).1 + have hall (t : Finset A) : t.card ≤ (t.biUnion N).card := by + have maps : Set.MapsTo g (↑(t ×ˢ s)) (↑(t.biUnion N ×ˢ s)) := by + rintro ⟨a, b⟩ hab + obtain ⟨ha, hb⟩ := Finset.mem_product.mp hab + exact Finset.mem_product.mpr + ⟨Finset.mem_biUnion.mpr ⟨a, ha, Finset.mem_image.mpr ⟨b, hb, rfl⟩⟩, + stays_inside g s hg a b hb⟩ + have h := Finset.card_le_card_of_injOn g maps g.injective.injOn + simp only [Finset.card_product] at h + exact Nat.le_of_mul_le_mul_right h hs.card_pos + obtain ⟨f, hf, hm⟩ := (Finset.all_card_le_biUnion_card_iff_existsInjective' N).mp hall + exact ⟨Equiv.ofBijective f hf.bijective_of_finite, fun a => Finset.mem_image.mp (hm a)⟩ + +omit [Fintype A] in +/-- Any permutation factors into permutations of columns, rows, then columns. -/ +theorem perm_factor [Finite A] [Finite B] (g : Perm (A × B)) : + ∃ u v w : Perm (A × B), + (∀ p, (u p).1 = p.1) ∧ (∀ p, (v p).2 = p.2) ∧ (∀ p, (w p).1 = p.1) ∧ + g = u * v * w := by + classical + let : Fintype A := Fintype.ofFinite A + let : Fintype B := Fintype.ofFinite B + suffices ∀ (s : Finset B) (g : Perm (A × B)), (∀ a b, b ∉ s → (g (a, b)).2 = b) → + ∃ u v w : Perm (A × B), + (∀ p, (u p).1 = p.1) ∧ (∀ p, (v p).2 = p.2) ∧ (∀ p, (w p).1 = p.1) ∧ + g = u * v * w from this Finset.univ g (by simp) + intro s + induction s using Finset.induction_on with + | empty => + intro g hg + exact ⟨1, g, 1, fun _ => rfl, fun p => hg _ _ (by simp), fun _ => rfl, by simp⟩ + | @insert b s hb ih => + intro g hg + obtain ⟨p, hp⟩ := matching g (insert b s) ⟨b, by simp⟩ hg + choose x hx he using hp + let y (a : A) := (g (p.symm a, x (p.symm a))).2 + have hy (a : A) : y a ∈ insert b s := stays_inside g _ hg _ _ (hx _) + let X := prodCongrRight fun a => swap b (x a) + let Y := prodCongrRight fun a => swap b (y a) + have ht (a : A) (c : B) (hc : c ∉ s) : ((Y * g * X) (a, c)).2 = c := by + by_cases heq : c = b + · subst c + have ht : g (a, x a) = (p a, y (p a)) := Prod.ext (he a) (by simp [y]) + simp [X, Y, Perm.mul_apply, ht] + · have h : c ∉ insert b s := by simp [heq, hc] + have xne : c ≠ x a := fun e => h (e.symm ▸ hx a) + have yne (j : A) : c ≠ y j := fun e => h (e.symm ▸ hy j) + change (Y (g (a, swap b (x a) c))).2 = c + rw [swap_apply_of_ne_of_ne heq xne] + change swap b (y (g (a, c)).1) (g (a, c)).2 = c + rw [hg a c h, swap_apply_of_ne_of_ne heq (yne _)] + obtain ⟨u, v, w, hu, hv, hw, he⟩ := ih (Y * g * X) ht + refine ⟨Y⁻¹ * u, v, w * X⁻¹, hu, hv, fun z => hw (X⁻¹ z), ?_⟩ + calc + g = Y⁻¹ * (Y * g * X) * X⁻¹ := by simp [mul_assoc] + _ = (Y⁻¹ * u) * v * (w * X⁻¹) := by rw [he]; simp [mul_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Centers for finite placements and bounded group orbits + +Minimizing the common upper bound of a family of strongly convex +functions treats both the average and the largest squared distance. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators Topology +open Filter + +variable {Y : Type*} [MetricSpace Y] + +/-- Minimize a simultaneous upper bound. The midpoint estimate forces any +decreasing minimizing sequence to be Cauchy. -/ +theorem minimize [CompleteSpace Y] {I : Type*} [Nonempty I] + (f : I → Y → ℝ) (hc : ∀ i, Continuous (f i)) (hn : ∀ i z, 0 ≤ f i z) + (hb : ∃ (a : ℝ) (z : Y), ∀ i, f i z ≤ a) + (hv : ∀ (x y : Y) (t : ℝ), 0 ≤ t → t ≤ 1 → ∃ m, ∀ i, + f i m ≤ (1 - t) * f i x + t * f i y - t * (1 - t) * dist x y ^ 2) : + ∃ (o : Y) (a : ℝ), (∀ i, f i o ≤ a) ∧ + ∀ (z : Y) (b : ℝ), (∀ i, f i z ≤ b) → a + dist o z ^ 2 ≤ b := by + let S := {a : ℝ | ∃ z, ∀ i, f i z ≤ a} + have hbelow : BddBelow S := by + refine ⟨0, ?_⟩ + rintro b ⟨z, hz⟩ + exact (hn (Classical.arbitrary I) z).trans (hz _) + let a := sInf S + have hmin (z : Y) (b : ℝ) (h : ∀ i, f i z ≤ b) : a ≤ b := + csInf_le hbelow ⟨z, h⟩ + obtain ⟨u, hu, hlim, hS⟩ := exists_seq_tendsto_sInf (show S.Nonempty from hb) hbelow + choose x hx using hS + have hxu : CauchySeq x := by + refine cauchySeq_of_le_tendsto_0' (fun n => Real.sqrt (4 * (u n - a))) ?_ ?_ + · intro n k hnk + obtain ⟨m, hm⟩ := hv (x n) (x k) (1 / 2) (by norm_num) (by norm_num) + have h : a ≤ u n - dist (x n) (x k) ^ 2 / 4 := by + apply hmin m + intro i + linarith [hm i, hx n i, hx k i, hu hnk] + exact Real.le_sqrt_of_sq_le (by linarith) + · have ha : Tendsto u atTop (𝓝 a) := hlim + simpa using ((ha.sub_const a).const_mul 4).sqrt + obtain ⟨o, ho⟩ := cauchySeq_tendsto_of_complete hxu + have hfo (i : I) : f i o ≤ a := + le_of_tendsto_of_tendsto' ((hc i).tendsto o |>.comp ho) hlim (fun n => hx n i) + refine ⟨o, a, hfo, ?_⟩ + intro z b hz + have hab := hmin z b hz + by_contra! bad + have hd : 0 < dist o z ^ 2 := by linarith + let t := (a + dist o z ^ 2 - b) / (2 * dist o z ^ 2) + have hpos : 0 < t := div_pos (sub_pos.mpr bad) (by positivity) + have hle : t ≤ 1 := (div_le_one (by positivity)).mpr (by linarith) + have he : t * (2 * dist o z ^ 2) = a + dist o z ^ 2 - b := + div_mul_cancel₀ _ (by positivity) + obtain ⟨m, hm⟩ := hv o z t hpos.le hle + have hh : a ≤ (1 - t) * a + t * b - t * (1 - t) * dist o z ^ 2 := by + apply hmin m + intro i + refine (hm i).trans ?_ + gcongr + · exact hfo i + · exact hz i + have : 0 < t * (a + dist o z ^ 2 - b - t * dist o z ^ 2) := + mul_pos hpos (by linarith) + linarith + +theorem Comparison.bary [CompleteSpace Y] (h : Comparison Y) + {A : Type*} [Fintype A] [Nonempty A] (x : A → Y) : ∃ o, Bary x o := by + let f (_ : Unit) (z : Y) := 𝔼 i, dist z (x i) ^ 2 + have hc (i : Unit) : Continuous (f i) := by + simp only [f, Fintype.expect_eq_sum_div_card] + fun_prop + have hn (i : Unit) (z : Y) : 0 ≤ f i z := + Finset.expect_nonneg fun _ _ => sq_nonneg _ + let z := x (Classical.arbitrary A) + obtain ⟨o, a, ha, ho⟩ := minimize f hc hn ⟨f () z, z, fun _ => le_rfl⟩ (by + intro u v t ht ht' + obtain ⟨m, _, hm⟩ := h u v t ht ht' + refine ⟨m, fun _ => ?_⟩ + have he := Finset.expect_le_expect (s := Finset.univ) fun i _ => hm (x i) + simpa only [Finset.expect_sub_distrib, Finset.expect_add_distrib, ← Finset.mul_expect, + Fintype.expect_const] using he) + exact ⟨o, fun y => (add_le_add_left (ha ()) _).trans (ho y (f () y) fun _ => le_rfl)⟩ + +variable {G : Type*} [Group G] [MulAction G Y] [IsIsometricSMul G Y] + +theorem Bary.fixed {A : Type*} [Fintype A] {x : A → Y} {o : Y} + (h : Bary x o) {g : G} (hx : ∀ i, g • x i = x i) : g • o = o := by + have hd (i : A) : dist (g • o) (x i) = dist o (x i) := by + rw [← hx i, dist_smul, hx] + have hv := h (g • o) + simp_rw [hd] at hv + exact (dist_eq_zero.mp (by nlinarith : dist o (g • o) = 0)).symm + +/-- The center of a bounded orbit is fixed and within half the squared bound of +the starting point. The bound is on squared distances. -/ +theorem Comparison.orbit [CompleteSpace Y] (h : Comparison Y) (K : Subgroup G) + (x : Y) (R : ℝ) (hb : ∀ g ∈ K, dist x (g • x) ^ 2 ≤ R) : + ∃ o, (∀ g ∈ K, g • o = o) ∧ 2 * dist x o ^ 2 ≤ R := by + let f (g : K) (y : Y) := dist y ((g : G) • x) ^ 2 + obtain ⟨o, a, ha, ho⟩ := minimize f (fun _ => by unfold f; fun_prop) + (fun _ _ => sq_nonneg _) ⟨R, x, fun g => hb g g.property⟩ (by + intro u v t ht ht' + obtain ⟨m, _, hm⟩ := h u v t ht ht' + exact ⟨m, fun g => hm _⟩) + refine ⟨o, ?_, ?_⟩ + · intro g hg + have hk : ∀ i, f i (g • o) ≤ a := by + intro i + have hh := ha ⟨g⁻¹ * i, K.mul_mem (K.inv_mem hg) i.property⟩ + change dist o ((g⁻¹ * i.val) • x) ^ 2 ≤ a at hh + rw [← dist_smul g, ← mul_smul, mul_inv_cancel_left] at hh + exact hh + have := ho (g • o) a hk + exact (dist_eq_zero.mp (by nlinarith : dist o (g • o) = 0)).symm + · have hrad : dist o x ^ 2 ≤ a := by simpa [f] using ha 1 + rw [dist_comm] + linarith [ho x R fun g => hb g g.property] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Matching independent partitions + +The partition represented by `g` is the coset `g H` of the stabilizer of +the original partition. An independent pair `e, f` of lists can be matched +with a third list in two ways. The group-theoretic condition below is all +that the displacement estimate uses about matching. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +/-- `v` fixes the `e`-partitions, `w` takes them to their `g`-translates, +and both take the `f`-partitions to the same third list. -/ +def Bridges {G : Type*} [Group G] (H K : Subgroup G) {d : ℕ} (e f : Fin d → G) : Prop := + ∀ g ∈ K, ∃ v w : G, + (∀ i, (e i)⁻¹ * (v * e i) ∈ H) ∧ + (∀ i, (g * e i)⁻¹ * (w * e i) ∈ H) ∧ + (∀ i, (v * f i)⁻¹ * (w * f i) ∈ H) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Independent partition lists admit simultaneous matching + +In each fiber write the address as a product of the first list of names +and the second list with its unused coordinates. Three-stage permutation +routing then gives the common third list needed in the displacement estimate. +The same argument works in a smaller group closed under this factorization. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +/-- A factorization alternating between the two joint stabilizers produces +the two matches required for the displacement estimate. -/ +theorem bridges_of_factor {G : Type*} [Group G] (H K : Subgroup G) {d : ℕ} + (e f : Fin d → G) + (factor : ∀ g ∈ K, ∃ u v w : G, g = u * v * w ∧ + (∀ i, (e i)⁻¹ * (u * e i) ∈ H) ∧ (∀ i, (f i)⁻¹ * (v * f i) ∈ H) ∧ + (∀ i, (e i)⁻¹ * (w * e i) ∈ H)) : + Bridges H K e f := by + intro g hg + obtain ⟨u, v, w, rfl, hu, hv, hw⟩ := factor g hg + refine ⟨u, u * v, hu, ?_, ?_⟩ + · intro i + simpa [mul_inv_rev, mul_assoc] using H.inv_mem (hw i) + · intro i + simpa [mul_inv_rev, mul_assoc] using hv i + +variable {J : Type} {X C : J → Type} + +/-- The permutations preserving each name, simultaneously for all instances. -/ +def preserving (name : ∀ i, X i → C i) : Subgroup (∀ i, Equiv.Perm (X i)) where + carrier := {g | ∀ i x, name i (g i x) = name i x} + one_mem' := fun _ _ => rfl + mul_mem' hg hh := fun i x => (hg i _).trans (hh i x) + inv_mem' {g} hg := fun i x => by simpa using (hg i ((g i).symm x)).symm + +theorem factor_in_fibers {X C A B : Type} [Finite A] [Finite B] + (s : X ≃ C × (A × B)) (g : Equiv.Perm X) (hg : ∀ x, (s (g x)).1 = (s x).1) : + ∃ u v w : Equiv.Perm X, g = u * v * w ∧ + (∀ x, (s (u x)).1 = (s x).1 ∧ (s (u x)).2.1 = (s x).2.1) ∧ + (∀ x, (s (v x)).1 = (s x).1 ∧ (s (v x)).2.2 = (s x).2.2) ∧ + (∀ x, (s (w x)).1 = (s x).1 ∧ (s (w x)).2.1 = (s x).2.1) := by + let : Fintype A := Fintype.ofFinite A + let : Fintype B := Fintype.ofFinite B + let r := s.permCongr g + have hr (c : C) (p : A × B) : (r (c, p)).1 = c := by simp [r, hg] + let φ (c : C) (p : A × B) := (r (c, p)).2 + have hi (c : C) : Function.Injective (φ c) := by + intro x y h + exact congrArg Prod.snd (r.injective (Prod.ext ((hr c x).trans (hr c y).symm) h)) + let ψ (c : C) := Equiv.ofBijective (φ c) ⟨hi c, Finite.surjective_of_injective (hi c)⟩ + choose u v w hu hv hw he using fun c => perm_factor (ψ c) + let lift (t : C → Equiv.Perm (A × B)) := s.symm.permCongr (Equiv.prodCongrRight t) + have hl (t : C → Equiv.Perm (A × B)) (x : X) : + s (lift t x) = ((s x).1, t (s x).1 (s x).2) := by + simp [lift, Equiv.prodCongrRight] + refine ⟨lift u, lift v, lift w, ?_, ?_, ?_, ?_⟩ + · apply Equiv.ext + intro x + apply s.injective + rw [Equiv.Perm.mul_apply, Equiv.Perm.mul_apply, hl, hl, hl] + refine Prod.ext (hg x) ?_ + have hx := DFunLike.congr_fun (he (s x).1) (s x).2 + simpa [ψ, φ, r] using hx + · intro x; rw [hl]; exact ⟨rfl, hu _ _⟩ + · intro x; rw [hl]; exact ⟨rfl, hv _ _⟩ + · intro x; rw [hl]; exact ⟨rfl, hw _ _⟩ + +/-- A family of permutation functions. An instance index determines the +address format, and a world supplies the input at every instance. Fixed +families and the three factors in a product chart must be available. -/ +structure PermSystem (X : J → Type) (G : Type) [Group G] where + /-- The `PermSystem` component of type `Type`. -/ + World : Type + /-- The read operation of type `World → G →* (∀ j, Equiv.Perm (X j))`. -/ + read : World → G →* (∀ j, Equiv.Perm (X j)) + /-- The `PermSystem` component of type `(∀ j, Equiv.Perm (X j)) → G`. -/ + fixed : (∀ j, Equiv.Perm (X j)) → G + read_fixed : ∀ t a, read t (fixed a) = a + factor : ∀ {C A B : J → Type} [∀ i, Fintype (A i)] [∀ i, Fintype (B i)] + (s : ∀ i, X i ≃ C i × (A i × B i)) (g : G), + (∀ t i x, (s i (read t g i x)).1 = (s i x).1) → + ∃ u v w : G, g = u * v * w ∧ + (∀ t i x, (s i (read t u i x)).1 = (s i x).1 ∧ (s i (read t u i x)).2.1 = (s i x).2.1) ∧ + (∀ t i x, (s i (read t v i x)).1 = (s i x).1 ∧ (s i (read t v i x)).2.2 = (s i x).2.2) ∧ + (∀ t i x, (s i (read t w i x)).1 = (s i x).1 ∧ (s i (read t w i x)).2.1 = (s i x).2.1) + +namespace PermSystem +variable {G : Type} [Group G] (M : PermSystem X G) + +/-- Require membership on every input. -/ +def pull (H : Subgroup (∀ i, Equiv.Perm (X i))) : Subgroup G where + carrier := {g | ∀ t, M.read t g ∈ H} + one_mem' := by simp + mul_mem' ha hb t := by rw [map_mul]; exact H.mul_mem (ha t) (hb t) + inv_mem' ha t := by rw [map_inv]; exact H.inv_mem (ha t) + +theorem pull_mono {H K : Subgroup (∀ i, Equiv.Perm (X i))} (h : H ≤ K) : + M.pull H ≤ M.pull K := fun _ hg t => h (hg t) + +/-- Builds `PermSystem X (∀ i, Equiv.Perm (X i)) where World` with the specified `World`, +`read`, `fixed`, `read_fixed`. -/ +def full (X : J → Type) : PermSystem X (∀ i, Equiv.Perm (X i)) where + World := Unit + read _ := MonoidHom.id _ + fixed := id + read_fixed _ _ := rfl + factor s g h := by + choose u v w he hu hv hw using fun i => factor_in_fibers (s i) (g i) (h () i) + exact ⟨u, v, w, funext he, fun _ => hu, fun _ => hv, fun _ => hw⟩ + +@[simp] theorem full_pull (H : Subgroup (∀ i, Equiv.Perm (X i))) : (full X).pull H = H := + le_antisymm (fun _ hg => hg ()) (fun _ hg _ => hg) + +/-- The joint names are coordinates on a product in each base fiber. +Unused coordinates may be included in either of the two factors. -/ +theorem bridges_of_product {Y A B : J → Type} [∀ i, Finite (A i)] [∀ i, Finite (B i)] + (base : ∀ i, X i → C i) (name : ∀ i, X i → Y i) + {d : ℕ} (e f : Fin d → ∀ i, Equiv.Perm (X i)) (s : ∀ i, X i ≃ C i × (A i × B i)) + (hs : ∀ i x, (s i x).1 = base i x) + (he : ∀ j i x y, (s i x).1 = (s i y).1 → (s i x).2.1 = (s i y).2.1 → + name i ((e j i).symm x) = name i ((e j i).symm y)) + (hf : ∀ j i x y, (s i x).1 = (s i y).1 → (s i x).2.2 = (s i y).2.2 → + name i ((f j i).symm x) = name i ((f j i).symm y)) : + Bridges (M.pull (preserving name)) (M.pull (preserving base)) (M.fixed ∘ e) (M.fixed ∘ f) := by + let : ∀ i : J, Fintype (A i) := fun i => Fintype.ofFinite (A i) + let : ∀ i : J, Fintype (B i) := fun i => Fintype.ofFinite (B i) + apply bridges_of_factor + intro g hg + have hg' (t : M.World) (i : J) (x : X i) : (s i (M.read t g i x)).1 = (s i x).1 := by + rw [hs, hs, hg t] + obtain ⟨u, v, w, heq, hu, hv, hw⟩ := M.factor s g hg' + refine ⟨u, v, w, heq, ?_, ?_, ?_⟩ + · intro j t + simp only [map_inv, map_mul, Function.comp_apply, read_fixed] + intro i x + simpa using he j i _ _ (hu t i (e j i x)).1 (hu t i (e j i x)).2 + · intro j t + simp only [map_inv, map_mul, Function.comp_apply, read_fixed] + intro i x + simpa using hf j i _ _ (hv t i (f j i x)).1 (hv t i (f j i x)).2 + · intro j t + simp only [map_inv, map_mul, Function.comp_apply, read_fixed] + intro i x + simpa using he j i _ _ (hw t i (e j i x)).1 (hw t i (e j i x)).2 + +end PermSystem +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Displacement on a single plane + +We only need to match *pairs* of partitions. For at least half of the +ordered pairs the matching argument bounds the diameter of the orbit by +twice the pair distance. Squaring and averaging gives a diameter bound +in terms of the variance of the affine placement. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators + +variable {Y A B D E G : Type*} [MetricSpace Y] + +open scoped Classical in +/-- The incidence estimate at `q ≥ 100` in flag-counting normalization. -/ +def Incidence (Y : Type*) [MetricSpace Y] [Fintype E] [Fintype A] + (p : E → A) (l : E → B) : Prop := + ∀ (x : A → Y) (y : B → Y) (o : Y), Bary x o → + 9 * (∑ i, (dist o (x (p i)) ^ 2 + dist o (y (l i)) ^ 2)) ≤ + 10 * ∑ i, dist (x (p i)) (y (l i)) ^ 2 + +open scoped Classical in +theorem Incidence.estimate [Fintype E] [Nonempty E] [Fintype A] + {p : E → A} {l : E → B} (h : Incidence Y p l) + {x : A → Y} (y : B → Y) {o : Y} (ho : Bary x o) : + 9 * ((𝔼 i, dist o (x (p i)) ^ 2) + (𝔼 i, dist o (y (l i)) ^ 2)) ≤ + 10 * (𝔼 i, dist (x (p i)) (y (l i)) ^ 2) := by + rw [← Finset.expect_add_distrib] + simp only [Fintype.expect_eq_sum_div_card, ← mul_div_assoc] + exact div_le_div_of_nonneg_right (h x y o ho) (by positivity) + +open scoped Classical in +theorem expect_pair [Fintype A] [Fintype B] (f : A × B → ℝ) : + (𝔼 p, f p) = 𝔼 i, 𝔼 j, f (i, j) := by + rw [← Finset.univ_product_univ, Finset.expect_product] + +open scoped Classical in +theorem dist_sq_triangle (x y z : Y) : + dist x z ^ 2 ≤ 2 * dist x y ^ 2 + 2 * dist y z ^ 2 := by + have h := pow_le_pow_left₀ dist_nonneg (dist_triangle x y z) 2 + nlinarith only [h, sq_nonneg (dist x y - dist y z)] + +variable [Group G] [MulAction G Y] [IsIsometricSMul G Y] + +open scoped Classical in +/-- The condition `∀ g ∈ K, g • x = x` on the specified data. -/ +def Fixes (K : Subgroup G) (x : Y) : Prop := ∀ g ∈ K, g • x = x + +omit [MetricSpace Y] [IsIsometricSMul G Y] in +open scoped Classical in +private theorem Fixes.coset {K : Subgroup G} {x : Y} (hx : Fixes K x) + {g h : G} (he : g⁻¹ * h ∈ K) : h • x = g • x := by + rw [← mul_inv_cancel_left g h, mul_smul, hx _ he] + +open scoped Classical in +private theorem pair_displacement {H K : Subgroup G} {x : Y} (hx : Fixes H x) + {a b : G} (ha : a ∈ K) + (hp : Bridges H K (fun _ : Fin 1 => a) (fun _ => b)) {g : G} (hg : g ∈ K) : + dist x (g • x) ≤ 2 * dist (a • x) (b • x) := by + obtain ⟨v, w, hv, hw, hb⟩ := hp (a * g * a⁻¹) (K.mul_mem (K.mul_mem ha hg) (K.inv_mem ha)) + have h₁ : v • (a • x) = a • x := by simpa [mul_smul] using hx.coset (hv 0) + have h₂ : w • (a • x) = a • (g • x) := by simpa [mul_smul] using hx.coset (hw 0) + have h₃ : w • (b • x) = v • (b • x) := by simpa [mul_smul] using hx.coset (hb 0) + calc + dist x (g • x) = dist (v • (a • x)) (w • (a • x)) := by rw [h₁, h₂, dist_smul] + _ ≤ dist (v • (a • x)) (v • (b • x)) + dist (w • (b • x)) (w • (a • x)) := by + rw [h₃] + exact dist_triangle _ _ _ + _ = _ := by rw [dist_smul, dist_smul, dist_comm (b • x), two_mul] + +open scoped Classical in +/-- Cosets for the affine point partitions and their projections along +each direction. `l` gives the affine line through a flag. -/ +structure PlaneAction [Fintype A] (H K : Subgroup G) (L : D → Subgroup G) + (l : A × D → B) (σ : A → G) : Prop where + mem : ∀ a, σ a ∈ K + projects : ∀ a a' d d', l (a, d) = l (a', d') → + d = d' ∧ (σ a)⁻¹ * σ a' ∈ L d + half : Fintype.card (A × A) ≤ 2 * (Finset.univ.filter fun p : A × A => + Bridges H K (fun _ : Fin 1 => σ p.1) (fun _ => σ p.2)).card + +open scoped Classical in +private theorem half_bound [Fintype E] [Nonempty E] (s : Finset E) (f : E → ℝ) (v : ℝ) + (hv : 0 ≤ v) (hf : ∀ e, 0 ≤ f e) (hs : Fintype.card E ≤ 2 * s.card) + (h : ∀ e ∈ s, v ≤ f e) : v ≤ 2 * (𝔼 e, f e) := by + have hm : (s.card : ℝ) * v ≤ ∑ e : E, f e := by + calc + _ = ∑ _ ∈ s, v := by simp + _ ≤ ∑ e ∈ s, f e := Finset.sum_le_sum h + _ ≤ _ := Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ s) (fun i _ _ => hf i) + rw [← Fintype.card_mul_expect] at hm + have hs' : (Fintype.card E : ℝ) ≤ 2 * s.card := by exact_mod_cast hs + apply le_of_mul_le_mul_left _ (show 0 < (Fintype.card E : ℝ) by positivity) + linarith only [hm, mul_le_mul_of_nonneg_right hs' hv] + +variable [Fintype A] [Nonempty A] {H K : Subgroup G} {L : D → Subgroup G} + {l : A × D → B} {σ : A → G} + +open scoped Classical in +private theorem PlaneAction.orbit_bound (h : PlaneAction H K L l σ) {x : Y} + (hx : Fixes H x) (o : Y) (g : G) (hg : g ∈ K) : + dist x (g • x) ^ 2 ≤ 32 * (𝔼 i, dist o (σ i • x) ^ 2) := by + let f (e : A × A) := 8 * dist o (σ e.1 • x) ^ 2 + 8 * dist o (σ e.2 • x) ^ 2 + have hb : dist x (g • x) ^ 2 ≤ 2 * (𝔼 e, f e) := by + refine half_bound _ f _ (sq_nonneg _) (fun _ => by unfold f; positivity) h.half ?_ + intro e he + have ht := dist_sq_triangle (σ e.1 • x) o (σ e.2 • x) + rw [dist_comm (σ e.1 • x) o] at ht + have hd := pair_displacement hx (h.mem _) (Finset.mem_filter.mp he).2 hg + dsimp only [f] + linarith only [ht, pow_le_pow_left₀ dist_nonneg hd 2] + rw [expect_pair] at hb + simp only [f, Finset.expect_add_distrib, ← Finset.mul_expect, Fintype.expect_const] at hb + linarith + +open scoped Classical in +/-- Given a point fixed by the base and one fixed by each direction, there +is a plane-fixed point controlled by the mean base-to-direction energy. -/ +theorem PlaneAction.fixed [Fintype D] [Nonempty D] [CompleteSpace Y] + (h : PlaneAction H K L l σ) (C : Comparison Y) (hi : Incidence Y Prod.fst l) + {x : Y} (hx : Fixes H x) (y : D → Y) (hy : ∀ d, Fixes (L d) (y d)) : + ∃ z, Fixes K z ∧ 9 * dist x z ^ 2 ≤ 160 * (𝔼 d, dist x (y d) ^ 2) := by + let v := fun a => σ a • x + let w := fun e : A × D => σ e.1 • y e.2 + have hline : ∃ u : B → Y, ∀ e, u (l e) = w e := by + have hw : ∀ b, ∃ z, ∀ e, l e = b → z = w e := by + intro b + by_cases he : ∃ e, l e = b + · obtain ⟨⟨a, d⟩, h₁⟩ := he + refine ⟨w (a, d), ?_⟩ + rintro ⟨a', d'⟩ h₂ + obtain ⟨rfl, hp⟩ := h.projects _ _ _ _ (h₁.trans h₂.symm) + exact ((hy d).coset hp).symm + · exact ⟨x, fun e he' => (he ⟨e, he'⟩).elim⟩ + choose u hu using hw + exact ⟨u, fun e => hu _ e rfl⟩ + obtain ⟨u, hu⟩ := hline + obtain ⟨o, ho⟩ := C.bary v + obtain ⟨z, hz, hd⟩ := C.orbit K x _ (h.orbit_bound hx o) + refine ⟨z, hz, ?_⟩ + have hb := hi.estimate u ho + have hn : 0 ≤ (𝔼 i : A × D, dist o (u (l i)) ^ 2) := + Finset.expect_nonneg (fun _ _ => sq_nonneg _) + have hv : 9 * (𝔼 i : A × D, dist o (v i.1) ^ 2) ≤ + 10 * (𝔼 i : A × D, dist (v i.1) (u (l i)) ^ 2) := by linarith + simp only [hu, v, w, dist_smul] at hv + rw [expect_pair, expect_pair] at hv + simp only [Fintype.expect_const] at hv + linarith only [hd, hv] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Successive geodesic means + +The sample space is a full finite power. Conditioning on the tail of a +tuple reduces the mean squared error to a one-step variance computation. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators + +variable {Y : Type*} [MetricSpace Y] (C : Comparison Y) + +/-- The quantity computed by `⟨1 / ((n : ℝ) + 2), by positivity, (div_le_one (by +positivity)).mpr (by linarith)⟩`. -/ +def weight (n : ℕ) : Set.Icc (0 : ℝ) 1 := + ⟨1 / ((n : ℝ) + 2), by positivity, (div_le_one (by positivity)).mpr (by linarith)⟩ + +/-- Mean of an ordered tuple, read from its last entry to its first. -/ +def sampleMean {T : Type*} (f : Fraction → T → T → T) : + (n : ℕ) → (Fin (n + 1) → T) → T + | 0, x => x 0 + | n + 1, x => f (weight n) (sampleMean f n (Fin.tail x)) (x 0) + +theorem sampleMean_map {T T' : Type*} (f : Fraction → T → T → T) + (g : Fraction → T' → T' → T') (φ : T → T') + (h : ∀ u x y, φ (f u x y) = g u (φ x) (φ y)) (n : ℕ) (x : Fin (n + 1) → T) : + φ (sampleMean f n x) = sampleMean g n (φ ∘ x) := by + induction n with + | zero => rfl + | succ n ih => + rw [sampleMean, h, ih] + rfl + +@[fun_prop] theorem continuous_sampleMean (n : ℕ) : Continuous (sampleMean C.seg n) := by + induction n with + | zero => exact continuous_apply _ + | succ n ih => + have h := (uniformContinuous_along (C.seg (weight n)) (C.along (weight n))).continuous + have ht : Continuous (fun x : Fin (n + 1 + 1) → Y => Fin.tail x) := + continuous_pi fun i => continuous_apply i.succ + exact h.comp ((ih.comp ht).prodMk (continuous_apply 0)) + +variable {A : Type*} [Fintype A] [Nonempty A] + +private theorem step_estimate {x : A → Y} {o : Y} (ho : Bary x o) (n : ℕ) (y : Y) : + ((n : ℝ) + 2) ^ 2 * (𝔼 i, dist (C.seg (weight n) y (x i)) o ^ 2) ≤ + ((n : ℝ) + 1) ^ 2 * dist y o ^ 2 + (𝔼 i, dist o (x i) ^ 2) := by + let t := (weight n).val + have ht : 0 ≤ t * (1 - t) := mul_nonneg (weight n).2.1 (sub_nonneg.mpr (weight n).2.2) + have h (i : A) : dist (C.seg (weight n) y (x i)) o ^ 2 ≤ + (1 - t) * dist y o ^ 2 + t * dist o (x i) ^ 2 - t * (1 - t) * dist y (x i) ^ 2 := by + rw [dist_comm o] + exact C.along _ _ _ o + have he := Finset.expect_le_expect (s := Finset.univ) (fun i _ => h i) + simp only [Finset.expect_sub_distrib, Finset.expect_add_distrib, ← Finset.mul_expect, + Fintype.expect_const] at he + have hb := mul_le_mul_of_nonneg_left (ho y) ht + rw [dist_comm o y] at hb + have hh : (𝔼 i, dist (C.seg (weight n) y (x i)) o ^ 2) ≤ + (1 - t) ^ 2 * dist y o ^ 2 + t ^ 2 * (𝔼 i, dist o (x i) ^ 2) := by linarith only [he, hb] + calc + _ ≤ ((n : ℝ) + 2) ^ 2 * ((1 - t) ^ 2 * dist y o ^ 2 + t ^ 2 * (𝔼 i, dist o (x i) ^ 2)) := + mul_le_mul_of_nonneg_left hh (sq_nonneg _) + _ = _ := by dsimp [t, weight]; field_simp; ring + +/-- The expected squared error of the sample mean is at most the variance +of one draw divided by the number of independent draws. -/ +theorem sampleMean_error {x : A → Y} {o : Y} (ho : Bary x o) (n : ℕ) : + ((n : ℝ) + 1) * (𝔼 u : Fin (n + 1) → A, dist (sampleMean C.seg n (x ∘ u)) o ^ 2) ≤ + 𝔼 i, dist o (x i) ^ 2 := by + induction n with + | zero => + simp only [Nat.cast_zero, zero_add, one_mul] + refine le_of_eq (Fintype.expect_equiv (Equiv.funUnique (Fin 1) A) _ _ ?_) + intro u + exact congrArg (· ^ 2) (dist_comm _ _) + | succ n ih => + let f := fun u : Fin (n + 1) → A => sampleMean C.seg n (x ∘ u) + have he : (𝔼 u : Fin (n + 1 + 1) → A, dist (sampleMean C.seg (n + 1) (x ∘ u)) o ^ 2) = + 𝔼 u : Fin (n + 1) → A, 𝔼 i, dist (C.seg (weight n) (f u) (x i)) o ^ 2 := by + let E := (Fin.consEquiv (fun _ : Fin (n + 1 + 1) => A)).symm.trans (Equiv.prodComm _ _) + let F := fun p : (Fin (n + 1) → A) × A => dist (C.seg (weight n) (f p.1) (x p.2)) o ^ 2 + exact (Fintype.expect_equiv E _ F (fun _ => rfl)).trans (expect_pair F) + have h := Finset.expect_le_expect (s := Finset.univ) + (fun u _ => step_estimate C ho n (f u)) + simp only [Finset.expect_add_distrib, ← Finset.mul_expect, Fintype.expect_const] at h + rw [he, Nat.cast_succ] + have hb := mul_le_mul_of_nonneg_left ih (show 0 ≤ (n : ℝ) + 1 by positivity) + dsimp only [f] at h ⊢ + apply le_of_mul_le_mul_left _ (show 0 < (n : ℝ) + 2 by positivity) + linarith only [h, hb] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Incidence as inequalities in finitely many geodesic terms + +Replace the barycenter by a random successive mean. Its mean squared +error is uniformly controlled by the second moment about any anchor. +The resulting tests are linear in squared distances. They pass through +uniform finite averages and pointwise limits without any choice of +compatible barycenters. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators Topology +open Filter + +variable {Y A E B T : Type*} [MetricSpace Y] + +/-- The quantity computed by `dist x y ^ 2`. -/ +def dsq (x y : Y) : ℝ := dist x y ^ 2 + +private theorem young (x y z : Y) {t : ℝ} (ht : 0 < t) : + dsq x z ≤ (1 + t) * dsq y z + (1 + t⁻¹) * dsq x y := by + have h := pow_le_pow_left₀ dist_nonneg (dist_triangle x y z) 2 + apply le_of_mul_le_mul_left _ ht + unfold dsq + rw [mul_add, ← mul_assoc t (1 + t⁻¹), mul_add t 1, mul_inv_cancel₀ ht.ne'] + linarith only [mul_le_mul_of_nonneg_left h ht.le, sq_nonneg (t * dist y z - dist x y)] + +variable [Fintype E] [Nonempty E] [Fintype A] [Nonempty A] + +/-- Cost of moving both sides of the flag distribution to `z`. -/ +def joint (R : T → T → ℝ) (u v : E → T) (z : T) : ℝ := + 𝔼 i, (R z (u i) + R z (v i)) + +private theorem joint_le (u v : E → Y) (z w : Y) {t : ℝ} (ht : 0 < t) : + joint dsq u v z ≤ (1 + t) * joint dsq u v w + 2 * (1 + t⁻¹) * dsq z w := by + have h (i : E) : dsq z (u i) + dsq z (v i) ≤ + (1 + t) * (dsq w (u i) + dsq w (v i)) + 2 * (1 + t⁻¹) * dsq z w := by + linarith only [young z w (u i) ht, young z w (v i) ht] + have hh := Finset.expect_le_expect (s := Finset.univ) (fun i _ => h i) + simpa only [joint, Finset.expect_add_distrib, ← Finset.mul_expect, Fintype.expect_const] using hh + +/-- The tests of type `Prop` for the given inputs. -/ +def Tests (R : T → T → ℝ) (s : Fraction → T → T → T) (p : E → A) (l : E → B) : Prop := + ∀ (x : A → T) (y : B → T) (b : T) (n : ℕ) (t : ℝ), 0 < t → + 9 * (𝔼 u : Fin (n + 1) → A, joint R (x ∘ p) (y ∘ l) (sampleMean s n (x ∘ u))) ≤ + 10 * (1 + t) * (𝔼 i, R (x (p i)) (y (l i))) + + 18 * (1 + t⁻¹) / (n + 1) * (𝔼 i, R b (x i)) + +omit [Nonempty E] in +private theorem sample_variance (C : Comparison Y) {x : A → Y} {o : Y} + (ho : Bary x o) (b : Y) (n : ℕ) : + (𝔼 u : Fin (n + 1) → A, dsq (sampleMean C.seg n (x ∘ u)) o) ≤ + (𝔼 i, dsq b (x i)) / (n + 1) := by + unfold dsq + apply (le_div_iff₀ (by positivity)).mpr + linarith only [sampleMean_error C ho n, ho b, sq_nonneg (dist o b)] + +theorem Incidence.tests [CompleteSpace Y] {p : E → A} {l : E → B} + (h : Incidence Y p l) (C : Comparison Y) : Tests dsq C.seg p l := by + intro x y b n t ht + obtain ⟨o, ho⟩ := C.bary x + let J := joint dsq (x ∘ p) (y ∘ l) + let m := fun u : Fin (n + 1) → A => sampleMean C.seg n (x ∘ u) + have hJ : 9 * J o ≤ 10 * (𝔼 i, dsq (x (p i)) (y (l i))) := by + unfold J joint dsq + rw [Finset.expect_add_distrib] + exact h.estimate y ho + have h₁ (u : Fin (n + 1) → A) : J (m u) ≤ (1 + t) * J o + 2 * (1 + t⁻¹) * dsq (m u) o := + joint_le _ _ _ _ ht + have he := Finset.expect_le_expect (s := Finset.univ) (fun u _ => h₁ u) + simp only [Finset.expect_add_distrib, ← Finset.mul_expect, Fintype.expect_const] at he + have hv := mul_le_mul_of_nonneg_left (sample_variance C ho b n) + (show 0 ≤ 18 * (1 + t⁻¹) by positivity) + have hi := mul_le_mul_of_nonneg_left hJ (show 0 ≤ 1 + t by positivity) + dsimp only [m, J] at he hi + simp only [div_eq_mul_inv] at hv ⊢ + linarith only [he, hv, hi] + +theorem Tests.incidence {p : E → A} {l : E → B} + {C : Comparison Y} (h : Tests dsq C.seg p l) : Incidence Y p l := by + intro x y o ho + let J := joint dsq (x ∘ p) (y ∘ l) + let R := 𝔼 i, dsq (x (p i)) (y (l i)) + let V := 𝔼 i, dsq o (x i) + have htend : Tendsto (fun n : ℕ => ((n : ℝ) + 1)⁻¹) atTop (𝓝 0) := by + simpa only [one_div] using (tendsto_one_div_add_atTop_nhds_zero_nat (𝕜 := ℝ)) + have hlim (t : ℝ) (ht : 0 < t) : 9 * J o ≤ 10 * (1 + t) ^ 2 * R := by + let K := 18 * (2 + t) * (1 + t⁻¹) * V + have hb (n : ℕ) : 9 * J o ≤ 10 * (1 + t) ^ 2 * R + K * ((n : ℝ) + 1)⁻¹ := by + let m := fun u : Fin (n + 1) → A => sampleMean C.seg n (x ∘ u) + have h₁ (u : Fin (n + 1) → A) : J o ≤ (1 + t) * J (m u) + 2 * (1 + t⁻¹) * dsq (m u) o := by + rw [show dsq (m u) o = dsq o (m u) by simp only [dsq, dist_comm]] + exact joint_le _ _ _ _ ht + have he := Finset.expect_le_expect (s := Finset.univ) (fun u _ => h₁ u) + simp only [Finset.expect_add_distrib, ← Finset.mul_expect, Fintype.expect_const] at he + have hv := mul_le_mul_of_nonneg_left (sample_variance C ho o n) + (show 0 ≤ 18 * (1 + t⁻¹) by positivity) + have hi := mul_le_mul_of_nonneg_left (h x y o n t ht) (show 0 ≤ 1 + t by positivity) + dsimp only [m, J, K, R, V] at he ⊢ + simp only [div_eq_mul_inv] at hi hv + linarith only [he, hi, hv] + simpa using ge_of_tendsto' ((htend.const_mul K).const_add (10 * (1 + t) ^ 2 * R)) hb + have hf : Continuous (fun t : ℝ => 10 * (1 + t) ^ 2 * R) := by fun_prop + have hJ : 9 * J o ≤ 10 * R := by + simpa using ge_of_tendsto' ((hf.tendsto 0).comp htend) (fun n => hlim _ (by positivity)) + simp only [J, joint, R, dsq, Function.comp_apply, Fintype.expect_eq_sum_div_card, + ← mul_div_assoc, div_le_div_iff_of_pos_right (show 0 + < (Fintype.card E : ℝ) by positivity)] at hJ + exact hJ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Completing a table of squared distances on geodesic terms + +The table need not separate terms. Metric completion identifies terms +of zero distance and extends both interpolation and the group action. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped BigOperators +open UniformSpace + +variable {G Y A B E T : Type*} + +theorem Tests.dense [MetricSpace Y] [Fintype E] [Fintype A] {p : E → A} {l : E → B} + {R : T → T → ℝ} {s : Fraction → T → T → T} + (h : Tests R s p l) (C : Comparison Y) (f : T → Y) + (hd : DenseRange f) (hs : ∀ u x y, f (s u x y) = C.seg u (f x) (f y)) + (hr : ∀ x y, dsq (f x) (f y) = R x y) : Tests dsq C.seg p l := by + intro x y b n t ht + let P := fun z : (A → Y) × (B → Y) × Y => + 9 * (𝔼 u : Fin (n + 1) → A, + joint dsq (z.1 ∘ p) (z.2.1 ∘ l) (sampleMean C.seg n (z.1 ∘ u))) ≤ + 10 * (1 + t) * (𝔼 i, dsq (z.1 (p i)) (z.2.1 (l i))) + + 18 * (1 + t⁻¹) / (n + 1) * (𝔼 i, dsq z.2.2 (z.1 i)) + have hclosed : IsClosed {z | P z} := by + simp only [P, joint, dsq, Fintype.expect_eq_sum_div_card, Function.comp_def] + exact isClosed_le (by fun_prop) (by fun_prop) + have h' := (DenseRange.piMap (fun _ : A => hd)).prodMap + ((DenseRange.piMap (fun _ : B => hd)).prodMap hd) + refine h'.induction_on (p := P) (x, y, b) hclosed ?_ + rintro ⟨a, c, d⟩ + change P (f ∘ a, f ∘ c, f d) + have hm (u : Fin (n + 1) → A) : + sampleMean C.seg n ((f ∘ a) ∘ u) = f (sampleMean s n (a ∘ u)) := + (sampleMean_map s C.seg f hs n _).symm + dsimp only [P] + simp only [hm, joint, Function.comp_apply, hr] + exact h a c d n t ht + +/-- Comparison and pseudometric laws on a table of squared distances. -/ +def Table (R : Term G → Term G → ℝ) : Prop := + (∀ x y, 0 ≤ R x y) ∧ + (∀ x, R x x = 0) ∧ + (∀ x y, R x y = R y x) ∧ + (∀ x y z, Real.sqrt (R x z) ≤ Real.sqrt (R x y) + Real.sqrt (R y z)) ∧ + ∀ t x y z, R (.seg t x y) z ≤ + (1 - t.val) * R x z + t.val * R y z - t.val * (1 - t.val) * R x y + +private abbrev Table.metric {R : Term G → Term G → ℝ} (h : Table R) : + PseudoMetricSpace (Term G) where + dist x y := Real.sqrt (R x y) + dist_self x := by rw [h.2.1]; exact Real.sqrt_zero + dist_comm x y := by rw [h.2.2.1] + dist_triangle := h.2.2.2.1 + +theorem completion_along [PseudoMetricSpace T] {s : T → T → T} {u : Fraction} + (h : ∀ x y, Along u x y (s x y)) (x y : Completion T) : + Along u x y (Completion.map₂ s x y) := by + intro z + induction x, y, z using Completion.induction_on₃ with + | hp => + have hc : Continuous (fun a : Completion T × Completion T × Completion T => + Completion.map₂ s a.1 a.2.1) := Completion.continuous_map₂ (by fun_prop) (by fun_prop) + exact isClosed_le (by fun_prop) (by fun_prop) + | ih x y z => + rw [Completion.map₂_coe_coe _ _ _ (uniformContinuous_along s h)] + simpa only [Completion.dist_eq] using h x y z + +/-- An invariant table gives an isometric action on a complete space. -/ +theorem Table.realize {G : Type} [Group G] {R : Term G → Term G → ℝ} + (h : Table R) (hg : ∀ (g : G) x y, R (g • x) (g • y) = R x y) : + ∃ (Y : Type) (_ : MetricSpace Y) (_ : CompleteSpace Y) (_ : MulAction G Y) + (_ : IsIsometricSMul G Y) (C : Comparison Y) (f : Term G → Y), + DenseRange f ∧ (∀ t x y, f (.seg t x y) = C.seg t (f x) (f y)) ∧ + (∀ x y, dsq (f x) (f y) = R x y) ∧ ∀ (g : G) x, f (g • x) = g • f x := by + let := h.metric + have he (x y : Term G) : dist x y ^ 2 = R x y := Real.sq_sqrt (h.1 x y) + have hs (u : Fraction) (x y : Term G) : Along u x y (.seg u x y) := by + intro z + simp only [he] + exact h.2.2.2.2 _ _ _ _ + have hi (g : G) : Isometry ((g • ·) : Term G → Term G) := + Isometry.of_dist_eq (fun x y => congrArg Real.sqrt (hg g x y)) + have : UniformContinuousConstSMul G (Term G) := ⟨fun g => (hi g).uniformContinuous⟩ + let Y := Completion (Term G) + have : IsIsometricSMul G Y := ⟨fun g => (hi g).completion_map⟩ + have C : Comparison Y := by + intro x y t ht ht' + have ha := completion_along (hs ⟨t, ht, ht'⟩) x y + exact ⟨_, ha.start, ha⟩ + refine ⟨Y, inferInstance, inferInstance, inferInstance, inferInstance, C, Completion.coe', + Completion.denseRange_coe, ?_, ?_, Completion.coe_smul⟩ + · intro t x y + have ha := completion_along (hs t) (x : Y) (y : Y) + rw [Completion.map₂_coe_coe _ _ _ (uniformContinuous_along _ (hs t))] at ha + exact ha.unique (C.along _ _ _) + · intro x y + exact (congrArg (· ^ 2) (Completion.dist_eq x y)).trans (he x y) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/PartitionsPlane.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/PartitionsPlane.lean new file mode 100644 index 0000000000..535c8c5593 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/PartitionsPlane.lean @@ -0,0 +1,945 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Partitions +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.LinearAlgebra.Projection +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryJets +public import Mathlib.Data.Fin.VecNotation +public import Mathlib.LinearAlgebra.FiniteDimensional.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Packets +public import Mathlib.LinearAlgebra.Basis.VectorSpace +public import Mathlib.GroupTheory.Coset.Basic +public import Mathlib.Algebra.Module.Submodule.Union +public import Mathlib.LinearAlgebra.Dual.Lemmas +public import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas + +/-! A motion along a subspace may freely permute the auxiliary labels. -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {k V J : Type} [Field k] [AddCommGroup V] [Module k V] + +/-- Indexes the labels by the coordinates of `(I j → V) × A j`. -/ +abbrev Labels (V : Type) (I A : J → Type) (j : J) := (I j → V) × A j + +/-- Builds `Subgroup (∀ j, Equiv.Perm (Labels V I A j)) where carrier` with the specified +`Subgroup`, `one_mem'`, `mul_mem'`, `simpa`. -/ +def motion (I A : J → Type) (S : Submodule k V) : + Subgroup (∀ j, Equiv.Perm (Labels V I A j)) where + carrier := {g | ∀ j x i, (g j x).1 i - x.1 i ∈ S} + one_mem' := by simp + mul_mem' {g h} hg hh j x i := by + simpa using S.add_mem (hg j (h j x) i) (hh j x i) + inv_mem' {g} hg j x i := by + simpa using S.neg_mem (hg j ((g j).symm x) i) + +theorem motion_mono (I A : J → Type) {S T : Submodule k V} (h : S ≤ T) : + motion I A S ≤ motion I A T := + fun _ hg j x i => h (hg j x i) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Flags of projective points and lines + +An ordered basis in each vector plane identifies its directions with the +same slope parameters used by the affine graph. +-/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset + +variable (K V : Type*) [Field K] [AddCommGroup V] [Module K V] + +/-- The subtype of `S : Submodule K V` satisfying `Module.finrank K S = d`. -/ +abbrev Flat (d : ℕ) := { S : Submodule K V // Module.finrank K S = d } +/-- Computes the vpoint by the application `Flat K V 1`. -/ +abbrev VPoint := Flat K V 1 +/-- Computes the vplane by the application `Flat K V 2`. -/ +abbrev VPlane := Flat K V 2 +/-- Indexes the vflag by the coordinates of `VPlane K V × Option K`. -/ +abbrev VFlag := VPlane K V × Option K + +instance [Finite V] (d : ℕ) : Fintype (Flat K V d) := by + haveI : Finite (Submodule K V) := + Finite.of_injective (fun S : Submodule K V => (S : Set V)) SetLike.coe_injective + exact Fintype.ofFinite _ + +variable {K V} + +theorem flat_nonempty {d : ℕ} (h : d ≤ Module.finrank K V) : Nonempty (Flat K V d) := by + obtain ⟨f, hf⟩ := exists_linearIndependent_of_le_finrank h + exact ⟨⟨_, (finrank_span_eq_card hf).trans (Fintype.card_fin _)⟩⟩ + +variable [Finite V] + +/-- Reindexes `(Fin 2 → K)` and `ₗ[K] P.1` by an equivalence. -/ +def planeChart (P : VPlane K V) : (Fin 2 → K) ≃ₗ[K] P.1 := + LinearEquiv.ofFinrankEq _ _ (by simp [P.2]) + +/-- In the case `none`, this construction gives `![0, 1]`. -/ +def ray : Option K → Fin 2 → K + | none => ![0, 1] + | some t => ![1, t] + +theorem ray_ne_zero (d : Option K) : ray d ≠ 0 := by + intro h + cases d with + | none => simpa [ray] using congrFun h 1 + | some t => simpa [ray] using congrFun h 0 + +/-- The dir of type `VPoint K V` for the given inputs. -/ +def dir (P : VPlane K V) (d : Option K) : VPoint K V := + ⟨Submodule.span K {((planeChart P (ray d) : P.1) : V)}, finrank_span_singleton (by + simpa using (planeChart P).map_ne_zero_iff.mpr (ray_ne_zero d))⟩ + +/-- Computes the flag point by the application `dir i.1 i.2`. -/ +def flagPoint (i : VFlag K V) : VPoint K V := dir i.1 i.2 + +theorem dir_le (P : VPlane K V) (d : Option K) : (dir P d).1 ≤ P.1 := + (Submodule.span_singleton_le_iff_mem _ _).mpr (planeChart P (ray d)).2 + +theorem mem_dir (P : VPlane K V) (d : Option K) (w : Fin 2 → K) : + (planeChart P w : V) ∈ (dir P d).1 ↔ projection w d = 0 := by + change (planeChart P w : V) ∈ Submodule.span K {(planeChart P (ray d) : V)} ↔ _ + rw [Submodule.mem_span_singleton] + constructor + · rintro ⟨c, hc⟩ + have eq : c • ray d = w := (planeChart P).injective (by + rw [map_smul] + exact Subtype.ext hc) + rw [← eq] + cases d <;> simp [projection, ray, mul_comm] + · intro h + suffices ∃ c : K, c • ray d = w by + obtain ⟨c, rfl⟩ := this + exact ⟨c, by simp⟩ + cases d with + | none => + refine ⟨w 1, ?_⟩ + funext i + fin_cases i <;> simp [ray, show w 0 = 0 from h] + | some s => + refine ⟨w 0, ?_⟩ + funext i + have hh : w 1 = s * w 0 := sub_eq_zero.mp h + fin_cases i <;> simp [ray, hh, mul_comm] + +theorem dir_injective (P : VPlane K V) : Function.Injective (dir P) := by + intro d e he + have h := (mem_dir P e (ray d)).mp (he ▸ Submodule.mem_span_singleton_self _) + cases d <;> cases e + · rfl + · simp [projection, ray] at h + · simp [projection, ray] at h + · simpa [projection, ray, sub_eq_zero] using h + +theorem exists_dir (P : VPlane K V) (p : VPoint K V) (h : p.1 ≤ P.1) : + ∃ d, dir P d = p := by + obtain ⟨v, hv⟩ := Module.finrank_pos_iff_exists_ne_zero.mp + (show 0 < Module.finrank K p.1 by rw [p.2]; decide) + let w := (planeChart P).symm ⟨v, h v.2⟩ + have hw : (planeChart P w : V) = v := by simp [w] + have zero_proj : ∃ d : Option K, projection w d = 0 := by + by_cases h0 : w 0 = 0 + · exact ⟨none, h0⟩ + · exact ⟨some (w 1 / w 0), by simp [projection, h0]⟩ + obtain ⟨d, hd⟩ := zero_proj + have hdir : (v : V) ∈ (dir P d).1 := hw ▸ (mem_dir P d w).mpr hd + have hv' : (v : V) ≠ 0 := fun he => hv (Subtype.ext he) + have unique (q : VPoint K V) (hq : (v : V) ∈ q.1) : Submodule.span K {(v : V)} = q.1 := + Submodule.eq_of_le_of_finrank_eq ((Submodule.span_singleton_le_iff_mem _ _).mpr hq) + ((finrank_span_singleton hv').trans q.2.symm) + exact ⟨d, Subtype.ext ((unique _ hdir).symm.trans (unique p v.2))⟩ + +private def planesAt (p : VPoint K V) : + {i : VFlag K V // flagPoint i = p} ≃ + {S : Submodule K V // Module.finrank K S = 2 ∧ p.1 ≤ S} := by + let f (i : {i : VFlag K V // flagPoint i = p}) : + {S : Submodule K V // Module.finrank K S = 2 ∧ p.1 ≤ S} := + ⟨i.1.1.1, i.1.1.2, (congrArg Subtype.val i.2).symm.le.trans (dir_le i.1.1 i.1.2)⟩ + refine Equiv.ofBijective f ⟨?_, ?_⟩ + · rintro ⟨⟨P, d⟩, hd⟩ ⟨⟨Q, e⟩, he⟩ h + have hpq := congrArg Subtype.val h + have hPQ : P = Q := Subtype.ext hpq + subst Q + have hde : d = e := dir_injective P (hd.trans he.symm) + subst e + rfl + · rintro ⟨S, hs, h⟩ + obtain ⟨d, hd⟩ := exists_dir ⟨S, hs⟩ p h + exact ⟨⟨(⟨S, hs⟩, d), hd⟩, rfl⟩ + +private theorem same_degree (p q : VPoint K V) : + Nonempty ({i : VFlag K V // flagPoint i = p} ≃ {i : VFlag K V // flagPoint i = q}) := by + let f := LinearEquiv.ofFinrankEq p.1 q.1 (p.2.trans q.2.symm) + obtain ⟨g, hg⟩ := Submodule.exists_linearEquiv_restrict_eq f + let e := Submodule.orderIsoMapComap g + have he (S : Submodule K V) : Module.finrank K (e S) = Module.finrank K S := + g.finrank_map_eq S + have hm : e p.1 = q.1 := by + apply Submodule.eq_of_le_of_finrank_eq _ ((he _).trans (p.2.trans q.2.symm)) + rintro _ ⟨x, hx, rfl⟩ + change g x ∈ q.1 + rw [← hg ⟨x, hx⟩] + exact (f ⟨x, hx⟩).2 + refine ⟨(planesAt p).trans ((e.toEquiv.subtypeEquiv ?_).trans (planesAt q).symm)⟩ + intro S + change (_ ∧ _) ↔ Module.finrank K (e S) = 2 ∧ q.1 ≤ e S + rw [he, ← hm, e.le_iff_le] + +theorem surjective_flagPoint (h : 2 ≤ Module.finrank K V) : + Function.Surjective (flagPoint (K := K) (V := V)) := by + intro p + obtain ⟨P⟩ := flat_nonempty h + let i : VFlag K V := (P, none) + obtain ⟨e⟩ := same_degree (flagPoint i) p + exact ⟨_, (e ⟨i, rfl⟩).2⟩ + +variable (K V) + +/-- The quantity computed by `Nat.card (VFlag K V) / Nat.card (VPoint K V)`. -/ +def projectiveDegree := Nat.card (VFlag K V) / Nat.card (VPoint K V) + +variable {K V} [Fintype K] + +theorem projective_point_degree [DecidableEq (VPoint K V)] (p : VPoint K V) : + #{i : VFlag K V | flagPoint i = p} = projectiveDegree K V := by + have eqn (q : VPoint K V) : #{i : VFlag K V | flagPoint i = q} = + #{i : VFlag K V | flagPoint i = p} := by + obtain ⟨e⟩ := same_degree q p + simpa only [Fintype.card_subtype] using Fintype.card_congr e + have h := sum_fiberwise univ (flagPoint (K := K) (V := V)) (fun _ => 1 : VFlag K V → ℕ) + simp only [card_univ, eqn, sum_const, smul_eq_mul, mul_one] at h + have : Nonempty (VPoint K V) := ⟨p⟩ + rw [projectiveDegree, Nat.card_eq_fintype_card, Nat.card_eq_fintype_card, ← h, + Nat.mul_div_cancel_left _ Fintype.card_pos] + +theorem projective_plane_degree [DecidableEq (VPlane K V)] (P : VPlane K V) : + #{i : VFlag K V | i.1 = P} = Fintype.card K + 1 := by + rw [← Fintype.card_subtype, ← Fintype.card_option] + apply Fintype.card_congr + exact { toFun := fun i => i.1.2 + invFun := fun d => ⟨(P, d), rfl⟩ + left_inv := fun i => Subtype.ext (Prod.ext i.2.symm rfl) + right_inv := fun _ => rfl } + +theorem projective_incidence [DecidableEq (VPlane K V)] {Y : Type*} [MetricSpace Y] + (C : Comparison Y) (x : VPoint K V → Y) (y : VPlane K V → Y) (o : Y) + (hq : 100 ≤ Fintype.card K) + (h : SecantBound flagPoint Prod.fst x o (projectiveDegree K V - 1)) : + 9 * (∑ i, (dist o (x (flagPoint i)) ^ 2 + dist o (y i.1) ^ 2)) ≤ + 10 * ∑ i, dist (x (flagPoint i)) (y i.1) ^ 2 := by + classical + refine incidence_bound C flagPoint Prod.fst x y o (Nat.succ_pos _) + projective_point_degree projective_plane_degree ?_ h + rw [Nat.mul_comm 100] + exact Nat.mul_le_mul (Nat.sub_le _ _) (le_trans hq (Nat.le_succ _)) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- +# Affine partitions from independent evaluations + +The linear map is an auxiliary address coordinate and varies independently +in every fiber. Independence of the parameters makes the joint name map +surjective. Its kernel supplies the residual product coordinate. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {J : Type} (k V : Type) (X C U R : J → Type) + [Field k] [AddCommGroup V] [Module k V] + [∀ i, AddCommGroup (U i)] [∀ i, Module k (U i)] + +open scoped Classical in +/-- The indexing data represented by `Fin 2 → V`. -/ +abbrev Point (V : Type) := Fin 2 → V + +open scoped Classical in +/-- Indexes the address from partitions affine by the coordinates of `Point W × (V →ₗ[k] W)`. -/ +abbrev AddressFromPartitionsAffine (k V W : Type) [Field k] [AddCommGroup V] [Module k V] + [AddCommGroup W] [Module k W] := Point W × (V →ₗ[k] W) + +open scoped Classical in +/-- Coordinates for a plane, with base, plane position, linear map and spare label. -/ +abbrev PlaneChart := ∀ i, X i ≃ C i × (AddressFromPartitionsAffine k V (U i) × R i) + +namespace PlaneChart + +variable {k V X C U R} (s : PlaneChart k V X C U R) + +open scoped Classical in +/-- The value specified by `(s i x).1`. -/ +def base (i : J) (x : X i) := (s i x).1 + +open scoped Classical in +/-- The value specified by `(s.base i x, (s i x).2.1.1)`. -/ +def origin (i : J) (x : X i) : C i × (Fin 2 → U i) := (s.base i x, (s i x).2.1.1) + +open scoped Classical in +/-- The inverse shear evaluates the affine name at a given address. -/ +def shear (p : Fin 2 → V) (i : J) : Equiv.Perm (X i) := + (s i).symm.permCongr ((Equiv.refl _).prodCongr + ((Equiv.prodCongrLeft (fun u : V →ₗ[k] U i => Equiv.subRight (fun j => u (p j)))).prodCongr + (Equiv.refl _))) + +open scoped Classical in +theorem shear_mem (p : Fin 2 → V) : s.shear p ∈ preserving s.base := by + intro i x + simp [shear, base] + +open scoped Classical in +private theorem origin_shear (p : Point V) (i : J) (x : X i) : + s.origin i ((s.shear p i).symm x) = + (s.base i x, fun j => (s i x).2.1.1 j + (s i x).2.1.2 (p j)) := by + let y := s i x + change s.origin i ((s i).symm + (y.1, ((fun j => y.2.1.1 j + y.2.1.2 (p j)), y.2.1.2), y.2.2)) = _ + simp only [origin, base, Equiv.apply_symm_apply, y] + +open scoped Classical in +/-- The value specified by `(s.base i x, projection (s i x).2.1.1 t)`. -/ +def projected (t : Option k) (i : J) (x : X i) := + (s.base i x, projection (s i x).2.1.1 t) + +open scoped Classical in +theorem shear_line (p q : Fin 2 → V) (t : Option k) (h : projection p t = projection q t) : + (s.shear p)⁻¹ * s.shear q ∈ preserving (s.projected t) := by + intro i x + have aux (r : Point V) (y : X i) : + s.projected t i ((s.shear r i).symm y) = + (s.base i y, projection (s i y).2.1.1 t + (s i y).2.1.2 (projection r t)) := by + change ((s.origin i _).1, projection (s.origin i _).2 t) = _ + rw [origin_shear] + cases t with + | none => rfl + | some t => + simp only [projection, smul_add, map_sub, map_smul] + congr 1 + abel + change s.projected t i ((s.shear p i).symm (s.shear q i x)) = _ + rw [aux, h, ← aux, Equiv.symm_apply_apply] + +open scoped Classical in +private abbrev Draw (d : ℕ) (W : Type) := Fin d → Point W +open scoped Classical in +private abbrev Sample (d : ℕ) := (Fin d ⊕ Fin d) × Fin 2 + +variable {d : ℕ} + +open scoped Classical in +private def coordinates : Draw d V × Draw d V ≃ (Sample d → V) := + (Equiv.sumPiEquivProdPi (fun _ : Fin d ⊕ Fin d => Point V)).symm.trans + (Equiv.curry _ _ _).symm + +variable {W : Type} [AddCommGroup W] [Module k W] + +open scoped Classical in +private def names (p : Draw d V) : AddressFromPartitionsAffine k V W →+ Draw d W where + toFun x i j := x.1 j + x.2 (p i j) + map_zero' := by ext; simp + map_add' _ _ := by ext; simp [add_add_add_comm] + +open scoped Classical in +private def joint (p : Draw d V × Draw d V) : AddressFromPartitionsAffine k V W →+ Draw d W × Draw + d W := + (names p.1).prod (names p.2) + +open scoped Classical in +private theorem joint_surj (p : Draw d V × Draw d V) + (h : LinearIndependent k (coordinates p)) : + Function.Surjective (joint (k := k) (W := W) p) := by + intro y + let b := Module.Basis.span h + obtain ⟨f, hf⟩ := (b.constr k (coordinates y)).exists_extend + have he (i : Sample d) : f (coordinates p i) = coordinates y i := by + have hi := DFunLike.congr_fun hf (b i) + rw [b.constr_basis] at hi + simpa [b] using hi + refine ⟨(0, f), Prod.ext ?_ ?_⟩ + · funext i j + change 0 + f (p.1 i j) = y.1 i j + rw [zero_add] + exact he (.inl i, j) + · funext i j + change 0 + f (p.2 i j) = y.2 i j + rw [zero_add] + exact he (.inr i, j) + +open scoped Classical in +private noncomputable def split {A B : Type} [AddGroup A] [AddGroup B] + (f : A →+ B) (hf : Function.Surjective f) : A ≃ B × f.ker := + (Equiv.sigmaFiberEquiv f).symm.trans + (Equiv.sigmaEquivProdOfEquiv (AddMonoidHom.fiberEquivKerOfSurjective hf)) + +variable [Fintype V] [∀ i, Finite (U i)] [∀ i, Finite (R i)] + +variable {G : Type} [Group G] (M : PermSystem X G) + +open scoped Classical in +omit [Fintype V] in +private theorem independent_bridges [Finite V] (p : Draw d V × Draw d V) + (h : LinearIndependent k (coordinates p)) : + Bridges (M.pull (preserving s.origin)) (M.pull (preserving s.base)) (M.fixed ∘ s.shear ∘ p.1) + (M.fixed ∘ s.shear ∘ p.2) := by + let : Fintype V := Fintype.ofFinite V + let (i : J) : Fintype (U i) := Fintype.ofFinite _ + let A i := Draw d (U i) + let B i := A i × ((joint (k := k) (W := U i) p).ker × R i) + have (i : J) : Finite (V →ₗ[k] U i) := + Finite.of_injective (fun f : V →ₗ[k] U i => (f : V → U i)) DFunLike.coe_injective + let (i : J) : Fintype (B i) := Fintype.ofFinite _ + let e (i : J) : X i ≃ C i × (A i × B i) := (s i).trans ((Equiv.refl _).prodCongr + ((((split _ (joint_surj (W := U i) p h)).prodCongr (Equiv.refl _)).trans + (Equiv.prodAssoc _ _ _)).trans (Equiv.prodAssoc _ _ _))) + apply M.bridges_of_product s.base s.origin _ _ e (fun _ _ => rfl) + · intro j i x y hb ha + simp only [Function.comp_apply, origin_shear] + exact Prod.ext hb (congrFun ha j) + · intro j i x y hb ha + simp only [Function.comp_apply, origin_shear] + exact Prod.ext hb (congrFun (congrArg Prod.fst ha) j) + +open scoped Classical in +/-- At least half of all pairs of lists can be matched with a third list. +The same affine parameters work for every instance and every base fiber. -/ +theorem half_bridges [Finite k] (hd : 4 * d < Module.finrank k V) : + Fintype.card ((Fin d → Fin 2 → V) × (Fin d → Fin 2 → V)) ≤ + 2 * (Finset.univ.filter fun p : (Fin d → Fin 2 → V) × (Fin d → Fin 2 → V) => + Bridges (M.pull (preserving s.origin)) (M.pull (preserving s.base)) (M.fixed ∘ s.shear ∘ + p.1) (M.fixed ∘ s.shear ∘ p.2)).card := by + let : Fintype k := Fintype.ofFinite k + have hdim : Fintype.card (Sample d) < Module.finrank k V := by + simp only [Sample, Fintype.card_prod, Fintype.card_sum, Fintype.card_fin] + omega + rw [Fintype.card_congr (coordinates (d := d) (V := V))] + refine (half_independent k V _ hdim).trans (Nat.mul_le_mul_left 2 ?_) + apply Finset.card_le_card_of_injOn (coordinates (d := d) (V := V)).symm + · intro v hv + simp only [Finset.mem_coe, Finset.mem_filter, Finset.mem_univ, true_and] at hv ⊢ + exact independent_bridges s M _ (by simpa using hv) + · exact (coordinates (d := d) (V := V)).symm.injective.injOn + +open scoped Classical in +theorem half_bridges_one [Finite k] (hd : 4 < Module.finrank k V) : + Fintype.card ((Fin 2 → V) × (Fin 2 → V)) ≤ + 2 * (Finset.univ.filter fun p : (Fin 2 → V) × (Fin 2 → V) => + Bridges (M.pull (preserving s.origin)) (M.pull (preserving s.base)) + (fun _ : Fin 1 => M.fixed (s.shear p.1)) (fun _ => M.fixed (s.shear p.2))).card := by + let : Fintype k := Fintype.ofFinite k + let u := Equiv.funUnique (Fin 1) (Fin 2 → V) + rw [← Fintype.card_congr (u.prodCongr u)] + refine (s.half_bridges M (d := 1) hd).trans (Nat.mul_le_mul_left 2 ?_) + apply Finset.card_le_card_of_injOn (u.prodCongr u) + · intro p hp + simp only [Finset.mem_coe, Finset.mem_filter, Finset.mem_univ, true_and] at hp ⊢ + have he (x : Fin 1 → Fin 2 → V) : M.fixed ∘ s.shear ∘ x = fun _ => M.fixed (s.shear (u x)) := by + funext i + rw [Subsingleton.elim i default] + rfl + rw [he, he] at hp + exact hp + · exact (u.prodCongr u).injective.injOn + +end PlaneChart +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# A secant-preserving affine chart of finite projective space + +Choose three linear functionals successively, avoiding finitely many +hyperplanes at each step. The first does not vanish on representatives, +the second separates their normalized first coordinates, and the third +rules out spurious incidences. +-/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {K V : Type*} [Field K] [AddCommGroup V] [Module K V] [Finite V] + +private theorem point_le_point {p q : VPoint K V} (h : p.1 ≤ q.1) : p = q := + Subtype.ext (Submodule.eq_of_le_of_finrank_eq h (p.2.trans q.2.symm)) + +private theorem sup_rank (p q : VPoint K V) (h : p ≠ q) : + Module.finrank K ↥(p.1 ⊔ q.1) = 2 := by + have hlt : p.1 ⊓ q.1 < p.1 := + lt_of_le_of_ne inf_le_left (fun e => h (point_le_point (e.symm.le.trans inf_le_right))) + have hint := Submodule.finrank_lt_finrank_of_lt hlt + have he := Submodule.finrank_sup_add_finrank_inf_eq p.1 q.1 + rw [p.2] at hint he + rw [q.2] at he + omega + +theorem joining_plane (p q : VPoint K V) (h : p ≠ q) : + ∃! P : VPlane K V, p.1 ≤ P.1 ∧ q.1 ≤ P.1 := by + have hr := sup_rank p q h + refine ⟨⟨_, hr⟩, ⟨le_sup_left, le_sup_right⟩, fun P hP => ?_⟩ + exact Subtype.ext (Submodule.eq_of_le_of_finrank_eq (sup_le hP.1 hP.2) (hr.trans P.2.symm)).symm + +private theorem exists_rep (p : VPoint K V) : + ∃ v : V, v ≠ 0 ∧ Submodule.span K {v} = p.1 := by + obtain ⟨v, hv⟩ := Module.finrank_pos_iff_exists_ne_zero.mp + (show 0 < Module.finrank K p.1 by rw [p.2]; decide) + have hv' : (v : V) ≠ 0 := fun e => hv (Subtype.ext e) + exact ⟨v, hv', Submodule.eq_of_le_of_finrank_eq + ((Submodule.span_singleton_le_iff_mem _ _).mpr v.2) ((finrank_span_singleton hv').trans + p.2.symm)⟩ + +private def rep (p : VPoint K V) : V := (exists_rep p).choose + +private theorem rep_mem (p : VPoint K V) (S : Submodule K V) : + rep p ∈ S ↔ p.1 ≤ S := by + rw [← (exists_rep p).choose_spec.2, Submodule.span_singleton_le_iff_mem] + rfl + +variable (F : Type*) [Field F] [Algebra K F] + +private def evalRep (p : VPoint K V) : Module.Dual F (V →ₗ[K] F) where + toFun f := f (rep p) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +private theorem separate (p : VPoint K V) (S : Submodule K V) (h : ¬ p.1 ≤ S) : + ∃ f : V →ₗ[K] F, evalRep F p f ≠ 0 ∧ S ≤ f.ker := by + have hn := mt (Subspace.forall_mem_dualAnnihilator_apply_eq_zero_iff S (rep p)).mp + (mt (rep_mem p S).mp h) + push Not at hn + obtain ⟨f, hf, hne⟩ := hn + refine ⟨(Algebra.linearMap K F).comp f, ?_, ?_⟩ + · exact (map_ne_zero (algebraMap K F)).mpr hne + · intro v hv + change algebraMap K F (f v) = 0 + rw [(Submodule.mem_dualAnnihilator f).mp hf v hv, map_zero] + +variable [Infinite F] + +private theorem chart_abscissa : + ∃ f g : V →ₗ[K] F, (∀ p : VPoint K V, f (rep p) ≠ 0) ∧ + Function.Injective (fun p : VPoint K V => g (rep p) / f (rep p)) := by + have hn (p : VPoint K V) : ∃ f, evalRep F p f ≠ 0 := by + obtain ⟨f, hf, _⟩ := separate F p ⊥ (fun h => + (exists_rep p).choose_spec.1 ((rep_mem p ⊥).mpr h)) + exact ⟨f, hf⟩ + obtain ⟨f, hf⟩ := Module.Dual.exists_forall_ne_zero_of_forall_exists (evalRep F) hn + let u (p : VPoint K V) := (f (rep p))⁻¹ • evalRep F p + have hu (p : VPoint K V) (a : V →ₗ[K] F) : u p a = a (rep p) / f (rep p) := by + simp [u, evalRep, div_eq_inv_mul] + let D := {pq : VPoint K V × VPoint K V // pq.1 ≠ pq.2} + let m (i : D) := u i.1.1 - u i.1.2 + have hm (i : D) : ∃ a, m i a ≠ 0 := by + obtain ⟨⟨p, q⟩, hpq⟩ := i + obtain ⟨a, ha, hz⟩ := separate F p q.1 (fun h => hpq (point_le_point h)) + have hz' : a (rep q) = 0 := hz ((rep_mem q _).mpr le_rfl) + refine ⟨a, ?_⟩ + change u p a - u q a ≠ 0 + rw [hu, hu, hz', zero_div, sub_zero] + exact div_ne_zero ha (hf p) + obtain ⟨g, hg⟩ := Module.Dual.exists_forall_ne_zero_of_forall_exists m hm + refine ⟨f, g, hf, fun p q h => ?_⟩ + by_contra hn + apply hg ⟨(p, q), hn⟩ + exact sub_eq_zero.mpr ((hu p g).trans (h.trans (hu q g).symm)) + +/-- A generic affine chart containing all the marked points. -/ +theorem projective_chart : + ∃ (a : VPoint K V → Fin 2 → F) (l : VPlane K V → Option F × F), + Function.Injective a ∧ Function.Injective l ∧ + ∀ p P, projection (a p) (l P).1 = (l P).2 ↔ p.1 ≤ P.1 := by + obtain ⟨f, g, hf, hg⟩ := chart_abscissa (K := K) (V := V) F + let u (p : VPoint K V) := g (rep p) / f (rep p) + let v (p : VPoint K V) := (f (rep p))⁻¹ • evalRep F p + have hv (p : VPoint K V) (h : V →ₗ[K] F) : v p h = h (rep p) / f (rep p) := by + simp [v, evalRep, div_eq_inv_mul] + let p₀ (P : VPlane K V) := dir P none + let p₁ (P : VPlane K V) := dir P (some 0) + have ne (P : VPlane K V) : p₀ P ≠ p₁ P := (dir_injective P).ne (by simp) + let s (P : VPlane K V) := (u (p₀ P) - u (p₁ P))⁻¹ • (v (p₀ P) - v (p₁ P)) + let b (P : VPlane K V) := v (p₀ P) - u (p₀ P) • s P + let test (p : VPoint K V) (P : VPlane K V) := v p - u p • s P - b P + let D := {i : VPoint K V × VPlane K V // ¬ i.1.1 ≤ i.2.1} + have ht (i : D) : ∃ h, test i.1.1 i.1.2 h ≠ 0 := by + obtain ⟨⟨p, P⟩, hn⟩ := i + obtain ⟨h, hp, hP⟩ := separate F p P.1 hn + have h₀ : h (rep (p₀ P)) = 0 := hP ((rep_mem _ _).mpr (dir_le P none)) + have h₁ : h (rep (p₁ P)) = 0 := hP ((rep_mem _ _).mpr (dir_le P (some 0))) + refine ⟨h, ?_⟩ + simpa [test, b, s, hv, h₀, h₁] using div_ne_zero (show h (rep p) ≠ 0 from hp) (hf p) + obtain ⟨h, hh⟩ := Module.Dual.exists_forall_ne_zero_of_forall_exists + (fun i : D => test i.1.1 i.1.2) ht + have eqn (p : VPoint K V) (P : VPlane K V) : + v p h - s P h * u p = b P h ↔ p.1 ≤ P.1 := by + constructor + · intro he + by_contra hn + apply hh ⟨(p, P), hn⟩ + change v p h - u p * s P h - b P h = 0 + rw [mul_comm (u p), he, sub_self] + · intro hp + let k := h - s P h • g - b P h • f + have iff_ker (q : VPoint K V) : + v q h - s P h * u q = b P h ↔ q.1 ≤ k.ker := by + rw [← rep_mem, hv] + change h (rep q) / f (rep q) - s P h * (g (rep q) / f (rep q)) = b P h ↔ + h (rep q) - s P h * g (rep q) - b P h * f (rep q) = 0 + rw [← mul_div_assoc, ← sub_div, div_eq_iff (hf q), sub_eq_zero] + have h₀ : (p₀ P).1 ≤ k.ker := (iff_ker _).mp (by simp [b, mul_comm]) + have h₁ : (p₁ P).1 ≤ k.ker := by + apply (iff_ker _).mp + have he : (u (p₀ P) - u (p₁ P)) * s P h = v (p₀ P) h - v (p₁ P) h := by + have hn : u (p₀ P) - u (p₁ P) ≠ 0 := sub_ne_zero.mpr (hg.ne (ne P)) + simp [s, hn] + change v (p₁ P) h - s P h * u (p₁ P) = v (p₀ P) h - u (p₀ P) * s P h + linear_combination he + apply (iff_ker _).mpr + have hs : (p₀ P).1 ⊔ (p₁ P).1 = P.1 := + Submodule.eq_of_le_of_finrank_eq (sup_le (dir_le P none) (dir_le P (some 0))) + ((sup_rank _ _ (ne P)).trans P.2.symm) + rw [← hs] at hp + exact hp.trans (sup_le h₀ h₁) + let a (p : VPoint K V) := ![u p, v p h] + let l (P : VPlane K V) := (some (s P h), b P h) + have iff_mem (p : VPoint K V) (P : VPlane K V) : + projection (a p) (l P).1 = (l P).2 ↔ p.1 ≤ P.1 := eqn p P + refine ⟨a, l, fun _ _ he => hg (congrFun he 0), ?_, iff_mem⟩ + intro P Q he + have hm (d : Option K) : (dir P d).1 ≤ Q.1 := by + rw [← iff_mem, ← he, iff_mem] + exact dir_le P d + exact (joining_plane _ _ (ne P)).unique ⟨dir_le P none, dir_le P (some 0)⟩ + ⟨hm none, hm (some 0)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Plane actions on address families + +Write ordinary addresses as lists of vectors. For each vector plane, +choose a complement and express every vector in the associated coordinates. +The partition names then recover the motion subgroups for the plane, +the zero subspace, and its individual directions. +-/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +variable {J : Type} (k W : Type) [Field k] [AddCommGroup W] [Module k W] + (I R : J → Type) + +/-- Indexes the aux by the coordinates of `(W →ₗ[k] I j → k) × R j`. -/ +abbrev Aux (j : J) := (W →ₗ[k] I j → k) × R j + +instance auxFintype [Fintype k] [Fintype W] [∀ j, Fintype (I j)] + [∀ j, Fintype (R j)] (j : J) : Fintype (Aux k W I R j) := by + haveI : Finite (W →ₗ[k] I j → k) := + Finite.of_injective (fun f : W →ₗ[k] I j → k => (f : W → I j → k)) DFunLike.coe_injective + exact Fintype.ofFinite _ + +variable {k W} {V : Type} [AddCommGroup V] [Module k V] [Fintype V] + +private def planeCoords (P : VPlane k V) (T : Submodule k V) (hT : IsCompl T P.1) : + V ≃ₗ[k] T × (Fin 2 → k) := + (T.prodEquivOfIsCompl P.1 hT).symm.trans + ((LinearEquiv.refl k T).prodCongr (planeChart P).symm) + +private theorem plane_mem (P : VPlane k V) (T : Submodule k V) (hT : IsCompl T P.1) + (x y : V) : (planeCoords P T hT x).1 = (planeCoords P T hT y).1 ↔ x - y ∈ P.1 := by + rw [← sub_eq_zero, ← Prod.fst_sub, ← map_sub] + exact Submodule.prodEquivOfIsCompl_symm_apply_fst_eq_zero T P.1 hT + +/-- The chart labels of type `PlaneChart k W (Labels V I (Aux k W I R)) (fun j => I j → T) (fun +j => I j → k) R` for the given inputs. -/ +def chartLabels {T : Type} (c : V ≃ T × (Fin 2 → k)) : + PlaneChart k W (Labels V I (Aux k W I R)) (fun j => I j → T) (fun j => I j → k) R := + fun j => + { toFun := fun x => (fun i => (c (x.1 i)).1, ((fun t i => (c (x.1 i)).2 t), x.2.1), x.2.2) + invFun := fun y => (fun i => c.symm (y.1 i, fun t => y.2.1.1 t i), y.2.1.2, y.2.2) + left_inv := by intro x; simp + right_inv := by intro x; simp } + +omit [Fintype V] in +theorem PermSystem.motion_plane_action [Finite V] [Finite k] [Fintype W] [∀ j, Finite (I j)] + [∀ j, Finite (R j)] {G : Type} [Group G] + (M : PermSystem (Labels V I (Aux k W I R)) G) (P : VPlane k V) (hW : 4 < Module.finrank k W) : + ∃ σ, PlaneAction (M.pull (motion I (Aux k W I R) (⊥ : Submodule k V))) + (M.pull (motion I (Aux k W I R) P.1)) (fun t => M.pull (motion I (Aux k W I R) (dir P t).1)) + (affineGraph (K := k) (V := W)) σ := by + classical + let : Fintype V := Fintype.ofFinite V + let : Fintype k := Fintype.ofFinite k + let : ∀ j, Fintype (I j) := fun j => Fintype.ofFinite (I j) + let : ∀ j, Fintype (R j) := fun j => Fintype.ofFinite (R j) + obtain ⟨T, hT⟩ := P.1.exists_isCompl + let c := planeCoords P T hT.symm + let s := chartLabels (W := W) I R c.toEquiv + have hP : preserving s.base = motion I (Aux k W I R) P.1 := by + ext g + constructor + · intro hg j x i + exact (plane_mem P T hT.symm _ _).mp (congrFun (hg j x) i) + · intro hg j x + funext i + exact (plane_mem P T hT.symm _ _).mpr (hg j x i) + have h0 : preserving s.origin = motion I (Aux k W I R) (⊥ : Submodule k V) := by + ext g + constructor + · intro hg j x i + rw [Submodule.mem_bot, sub_eq_zero] + apply c.injective + exact Prod.ext (congrFun (congrArg Prod.fst (hg j x)) i) + (funext fun t => congrFun (congrFun (congrArg Prod.snd (hg j x)) t) i) + · intro hg j x + have hx : (g j x).1 = x.1 := funext fun i => sub_eq_zero.mp (hg j x i) + exact congrArg (fun y => (fun i => (c (y i)).1, fun t i => (c (y i)).2 t)) hx + have hL (t : Option k) : preserving (s.projected t) ≤ motion I (Aux k W I R) (dir P t).1 := by + intro g hg j x i + let u := (g j x).1 i + let v := x.1 i + have hm := (plane_mem P T hT.symm u v).mp (congrFun (congrArg Prod.fst (hg j x)) i) + let z : P.1 := ⟨u - v, hm⟩ + have hz : (c (u - v)).2 = (planeChart P).symm z := by + change (planeChart P).symm ((T.prodEquivOfIsCompl P.1 hT.symm).symm (z : V)).2 = _ + rw [Submodule.prodEquivOfIsCompl_symm_apply_right] + have hp : projection (c u).2 t = projection (c v).2 t := by + have hp := congrFun (congrArg Prod.snd (hg j x)) i + cases t <;> exact hp + have h : projection ((planeChart P).symm z) t = 0 := by + rw [← hz, map_sub, Prod.snd_sub] + cases t <;> simp only [projection, Pi.sub_apply, smul_sub] at hp ⊢ + · exact sub_eq_zero.mpr hp + · linear_combination hp + simpa only [LinearEquiv.apply_symm_apply] using (mem_dir P t _).mpr h + refine ⟨M.fixed ∘ s.shear, ?_, ?_, ?_⟩ + · intro a t + rw [Function.comp_apply, M.read_fixed, ← hP] + exact s.shear_mem a + · intro a a' d d' h + obtain ⟨rfl, hp⟩ := Prod.mk.inj h + refine ⟨rfl, fun t => ?_⟩ + simp only [map_mul, map_inv, Function.comp_apply, M.read_fixed] + exact hL d (s.shear_line a a' d hp) + · rw [← h0, ← hP] + exact s.half_bridges_one M hW + +omit [Fintype V] in +theorem motion_plane_action [Finite V] [Finite k] [Fintype W] [∀ j, Finite (I j)] + [∀ j, Finite (R j)] (P : VPlane k V) (hW : 4 < Module.finrank k W) : + ∃ σ, PlaneAction (motion I (Aux k W I R) (⊥ : Submodule k V)) + (motion I (Aux k W I R) P.1) (fun t => motion I (Aux k W I R) (dir P t).1) + (affineGraph (K := k) (V := W)) σ := by + let : Fintype V := Fintype.ofFinite V + let : Fintype k := Fintype.ofFinite k + let : ∀ j, Fintype (I j) := fun j => Fintype.ofFinite (I j) + let : ∀ j, Fintype (R j) := fun j => Fintype.ofFinite (R j) + simpa only [PermSystem.full_pull] using + PermSystem.motion_plane_action I R (PermSystem.full (Labels V I (Aux k W I R))) P hW + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +section +/- Incidence of affine points with lines in the base-field directions. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset + +variable {K V : Type*} [Field K] [AddCommGroup V] [Module K V] + +private def affineParam (k : Option K × V) (v : V) : Fin 2 → V := + match k.1 with + | none => ![k.2, v] + | some s => ![v, k.2 + s • v] + +private def affineCoord (a : Fin 2 → V) : Option K → V + | none => a 1 + | some _ => a 0 + +private def affineFiber (k : Option K × V) : + V ≃ {i : (Fin 2 → V) × Option K // affineGraph i = k} where + toFun v := ⟨(affineParam k v, k.1), by + rcases k with ⟨_ | s, b⟩ <;> simp [affineGraph, projection, affineParam]⟩ + invFun i := affineCoord i.1.1 i.1.2 + left_inv v := by rcases k with ⟨_ | s, b⟩ <;> rfl + right_inv i := by + rcases i with ⟨⟨a, d⟩, rfl⟩ + refine Subtype.ext (Prod.ext ?_ rfl) + funext j + cases d <;> fin_cases j <;> simp [affineParam, affineGraph, projection, affineCoord] + +variable [Fintype K] [Fintype V] [DecidableEq K] [DecidableEq V] + +theorem affine_line_degree (k : Option K × V) : + #{i | affineGraph i = k} = Fintype.card V := by + rw [← Fintype.card_subtype] + exact Fintype.card_congr (affineFiber k).symm + +omit [Field K] [AddCommGroup V] [Module K V] [DecidableEq K] in +theorem affine_point_degree (a : Fin 2 → V) : + #{i : (Fin 2 → V) × Option K | i.1 = a} = Fintype.card K + 1 := by + rw [← Fintype.card_subtype, ← Fintype.card_option] + apply Fintype.card_congr + exact { toFun := fun i => i.1.2 + invFun := fun d => ⟨(a, d), rfl⟩ + left_inv := fun i => Subtype.ext (Prod.ext i.2.symm rfl) + right_inv := fun _ => rfl } + +theorem affine_incidence {Y : Type*} [MetricSpace Y] (C : Comparison Y) + (x : (Fin 2 → V) → Y) (y : Option K × V → Y) (o : Y) + (hq : 100 ≤ Fintype.card K) + (h : SecantBound Prod.fst (affineGraph (K := K)) x o (Fintype.card V)) : + 9 * (∑ i, (dist o (x i.1) ^ 2 + dist o (y (affineGraph i)) ^ 2)) ≤ + 10 * ∑ i, dist (x i.1) (y (affineGraph i)) ^ 2 := by + refine incidence_bound C Prod.fst affineGraph x y o Fintype.card_pos + affine_point_degree affine_line_degree ?_ h + exact Nat.mul_le_mul_right _ (le_trans hq (Nat.le_add_right _ _)) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- Both incidence estimates follow from the same secant bound. -/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset + +variable {K : Type} [Field K] [Fintype K] +variable {F Y : Type*} [Field F] [MetricSpace Y] + +open scoped Classical in +theorem Secants.projective_widths {V : Type} [AddCommGroup V] [Module K V] [Finite V] + [Infinite F] [Algebra K F] (S : Secants F Y) (x : VPoint K V → Y) (o : Y) + (ho : Bary x o) : SecantBound flagPoint Prod.fst x o (projectiveDegree K V - 1) := by + obtain ⟨a, k, ha, hk, hc⟩ := projective_chart (K := K) (V := V) F + have hmem (P : VPlane K V) : k P ∈ secantLines a := by + apply (mem_secantLines ha _).mpr + exact ⟨dir P none, dir P (some 0), (dir_injective P).ne (by simp), + (hc _ _).mpr (dir_le _ _), (hc _ _).mpr (dir_le _ _)⟩ + have hfull (b : Option F × F) (hb : b ∈ secantLines a) : ∃ P, k P = b := by + obtain ⟨i, j, hij, hi, hj⟩ := (mem_secantLines ha b).mp hb + obtain ⟨P, ⟨hiP, hjP⟩, _⟩ := joining_plane i j hij + refine ⟨P, ?_⟩ + rw [eq_through (ha.ne hij) hi hj] + exact eq_through (ha.ne hij) ((hc _ _).mpr hiP) ((hc _ _).mpr hjP) + have hi (p : VPoint K V) (P : VPlane K V) : + projection (a p) (k P).1 = (k P).2 ↔ ∃ i, flagPoint i = p ∧ i.1 = P := by + rw [hc] + constructor + · intro h + obtain ⟨d, hd⟩ := exists_dir P p h + exact ⟨(P, d), hd, rfl⟩ + · rintro ⟨⟨P, d⟩, rfl, rfl⟩ + exact dir_le _ _ + have hn (p : VPoint K V) : (pointSecants a p).card ≤ projectiveDegree K V - 1 + 1 := by + let T := ({i : VFlag K V | flagPoint i = p} : Finset _) + have hT : pointSecants a p ⊆ T.image (fun i => k i.1) := by + intro b hb + obtain ⟨hb, hp⟩ := mem_filter.mp hb + obtain ⟨P, rfl⟩ := hfull b hb + obtain ⟨i, hip, rfl⟩ := (hi p P).mp hp + exact mem_image.mpr ⟨i, mem_filter.mpr ⟨mem_univ _, hip⟩, rfl⟩ + have ht := (card_le_card hT).trans card_image_le + rw [show T.card = _ from projective_point_degree p] at ht + omega + have he : Function.Injective (fun i : VFlag K V => (flagPoint i, i.1)) := by + rintro ⟨P, d⟩ ⟨Q, e⟩ h + have hPQ : P = Q := congrArg Prod.snd h + subst Q + have hde : d = e := dir_injective P (congrArg Prod.fst h) + exact Prod.ext rfl hde + exact S.widths a k ha hk hn hmem flagPoint Prod.fst he hi x o ho + +open scoped Classical in +theorem Secants.projective {V : Type} [AddCommGroup V] [Module K V] [Finite V] + [Infinite F] [Algebra K F] (S : Secants F Y) (C : Comparison Y) + (hq : 100 ≤ Fintype.card K) : Incidence Y (flagPoint (K := K) (V := V)) Prod.fst := by + exact fun x y o ho => projective_incidence C x y o hq (S.projective_widths x o ho) + +open scoped Classical in +theorem Secants.affine_widths {W : Type} [Field W] [Fintype W] [Algebra K W] [Algebra W F] + (S : Secants F Y) (x : (Fin 2 → W) → Y) (o : Y) (ho : Bary x o) : + SecantBound Prod.fst (affineGraph (K := K)) x o (Fintype.card W) := by + let f := algebraMap W F + let g := algebraMap K W + let a (w : Fin 2 → W) (i : Fin 2) := f (w i) + let k (l : Option K × W) := (l.1.map (f ∘ g), f l.2) + have ha : Function.Injective a := fun _ _ h => funext fun i => f.injective (congrFun h i) + have hk : Function.Injective k := by + intro i j h + have hd : i.1.map (f ∘ g) = j.1.map (f ∘ g) := congrArg Prod.fst h + have hi : f i.2 = f j.2 := congrArg Prod.snd h + exact Prod.ext (Option.map_injective (f.injective.comp g.injective) hd) (f.injective hi) + have hc (w : Fin 2 → W) (d : Option K) : + projection (a w) (d.map (f ∘ g)) = f (projection w d) := by + cases d <;> simp [a, g, projection, Algebra.smul_def] + have hi (p : Fin 2 → W) (l : Option K × W) : + projection (a p) (k l).1 = (k l).2 ↔ + ∃ i, i.1 = p ∧ affineGraph i = l := by + change projection (a p) (l.1.map (f ∘ g)) = f l.2 ↔ _ + rw [hc, f.injective.eq_iff] + constructor + · exact fun h => ⟨(p, l.1), rfl, Prod.ext rfl h⟩ + · rintro ⟨⟨p, d⟩, rfl, rfl⟩ + rfl + have he : Function.Injective (fun i : (Fin 2 → W) × Option K => (i.1, affineGraph i)) := by + intro i j h + have h₁ := congrArg Prod.fst h + have h₂ := congrArg (fun v => v.2.1) h + exact Prod.ext h₁ h₂ + have hmem (l : Option K × W) : k l ∈ secantLines a := by + have hm : 1 < #{i | affineGraph i = l} := by + rw [affine_line_degree] + exact Fintype.one_lt_card + obtain ⟨i, hi', j, hj, hij⟩ := one_lt_card.mp hm + replace hi' := (mem_filter.mp hi').2 + replace hj := (mem_filter.mp hj).2 + exact (mem_secantLines ha _).mpr ⟨i.1, j.1, + fun h => hij (he (Prod.ext h (hi'.trans hj.symm))), + (hi _ _).mpr ⟨i, rfl, hi'⟩, (hi _ _).mpr ⟨j, rfl, hj⟩⟩ + have hd (u v : Fin 2 → W) : (through (a u) (a v)).1 = (through u v).1.map f := by + by_cases h : u 0 = v 0 + · simp [through, a, h] + · simp [through, a, h, f.injective.ne h] + have hn (p : Fin 2 → W) : (pointSecants a p).card ≤ Fintype.card W + 1 := by + let line (d : Option W) := (d.map f, projection (a p) (d.map f)) + have hs : pointSecants a p ⊆ univ.image line := by + intro l hl + obtain ⟨hl, hp⟩ := mem_filter.mp hl + obtain ⟨⟨i, j⟩, _, rfl⟩ := mem_image.mp hl + refine mem_image.mpr ⟨(through i j).1, mem_univ _, ?_⟩ + dsimp only [line] + rw [← hd, hp] + simpa using (card_le_card hs).trans card_image_le + exact S.widths a k ha hk hn hmem Prod.fst affineGraph he hi x o ho + +open scoped Classical in +theorem Secants.affine {W : Type} [Field W] [Fintype W] [Algebra K W] [Algebra W F] + (S : Secants F Y) (C : Comparison Y) (hq : 100 ≤ Fintype.card K) : + Incidence Y Prod.fst (affineGraph (K := K) (V := W)) := by + exact fun x y o ho => affine_incidence C x y o hq (S.affine_widths x o ho) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Round.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Round.lean new file mode 100644 index 0000000000..a4836c8010 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Round.lean @@ -0,0 +1,839 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Uniform.System +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Comparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import Mathlib.Algebra.Order.Archimedean.Real.Basic + +/-! +# Local substitutions including selector cost + +The alphabet of offers stays fixed as the common rate is multiplied. +The constant from strict spectral comparison is absorbed later, by +repeating the entire construction. Even a unary selector for each +letter then fits in the strict margin. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral +open scoped NNReal + +variable {K S I J : Type} [Field K] [Fintype S] [Nonempty S] + +/-- A direct sum of words in supplies restricts to a block of demands. +A selector chooses a summand. Its transmission costs at most `H` per bit. -/ +structure Replacement (D : Tensor K S) (T : I → Tensor K S) + (p : I → ℝ) (L H : ℝ) where + /-- Stores the block associated with this `Replacement`. -/ + block : ℕ + positive : 0 < block + /-- The `Replacement` component of type `Type`. -/ + letter : Type + [finiteLetter : Fintype letter] + /-- The length of the indexed record carried by `Replacement`, with type `ℕ`. -/ + length : ℕ + /-- Stores the bits associated with this `Replacement`. -/ + bits : ℕ + fits : Fintype.card letter ≤ 2 ^ bits + /-- The `Replacement` component of type `letter → Fin length → I`. -/ + good : letter → Fin length → I + /-- The number of entries of type `letter → Fin length → ℕ`. -/ + count : letter → Fin length → ℕ + cheaper : ∀ j, (∑ i, (count j i : ℝ) * p (good j i)) + bits * H < block * L + covers : D ^ block ≤ ∑ j, ∏ i, T (good j i) ^ count j i + +attribute [instance] Replacement.finiteLetter + +private theorem scale_margin [Finite J] (g : J → ℝ) (hg : ∀ j, 0 < g j) (H : ℝ) : + ∃ k : ℕ, 0 < k ∧ ∀ j, H < g j * k := by + let : Fintype J := Fintype.ofFinite J + choose a ha using fun j => exists_nat_gt (H / g j) + refine ⟨(∑ j, a j) + 1, Nat.zero_lt_succ _, fun j => ?_⟩ + rw [mul_comm, ← div_lt_iff₀ (hg j)] + apply (ha j).trans_le + exact_mod_cast (Finset.single_le_sum (fun i _ => Nat.zero_le (a i)) + (Finset.mem_univ j)).trans (Nat.le_succ _) + +omit [Nonempty S] in +private theorem expand_word [Fintype J] (V : J → Tensor K S) (C r : ℕ) : + (C : Tensor K S) * (∑ j, V j) ^ r = + ∑ j : Fin C × (Fin r → J), ∏ i, V (j.2 i) := by + simp only [Fintype.sum_prod_type, ← Fintype.sum_pow, Finset.sum_const, Finset.card_univ, + Fintype.card_fin, nsmul_eq_mul] + +private theorem replace_aux [Finite J] (D : Tensor K S) (T : I → Tensor K S) + (p : I → ℝ) (L H : ℝ) (t : J → I) (n : J → ℕ) (b : ℕ) (hb : 0 < b) + (hmargin : ∀ j, (n j : ℝ) * p (t j) < (b : ℝ) * L) + (hspec : ∀ v : Tensor K S →+* ℝ≥0, Monotone v → ∃ j, v D ^ b < v (T (t j)) ^ n j) + (hunit : ∃ j, n j = 0) : Nonempty (Replacement D T p L H) := by + classical + let : Fintype J := Fintype.ofFinite J + let m := Fintype.card J + obtain ⟨k, hk, hg⟩ := scale_margin (fun j => (b : ℝ) * L - n j * p (t j)) + (fun j => sub_pos.mpr (hmargin j)) (m * H + 1) + let V j := T (t j) ^ (n j * k) + have hn : (∑ j, V j) ≠ 0 := by + obtain ⟨j, hj⟩ := hunit + have hv : V j = 1 := by simp [V, hj] + have hs : 1 ≤ ∑ i, V i := by + rw [← Finset.sum_erase_add _ _ (Finset.mem_univ j), hv] + have h := Tensor.add_le_add_right 0 (∑ i ∈ Finset.univ.erase j, V i) 1 (Tensor.zero_le _) + rw [zero_add] at h + exact h + intro h + rw [h] at hs + exact one_ne_zero (le_antisymm hs (Tensor.zero_le _)) + have hstrict (v : Tensor K S →+* ℝ≥0) (hv : Monotone v) : + v (D ^ (b * k)) < v (∑ j, V j) := by + obtain ⟨j, hj⟩ := hspec v hv + rw [map_sum, map_pow, pow_mul] + refine lt_of_lt_of_le ?_ (Finset.single_le_sum (fun _ _ => zero_le) (Finset.mem_univ j)) + simp only [V, map_pow, pow_mul] + exact pow_lt_pow_left₀ hj zero_le hk.ne' + obtain ⟨C, hC⟩ := Spectrum.strictComparison Tensor.add_le_add_right Tensor.mul_le_mul_left + Tensor.zero_le Tensor.one_le Tensor.exists_bound hn hstrict + obtain ⟨r, hr⟩ := exists_nat_gt (max 0 ((C : ℝ) * H)) + have hr0 : 0 < r := Nat.cast_pos.mp ((le_max_left _ _).trans_lt hr) + let W := Fin C × (Fin r → J) + refine ⟨{ block := b * k * r + positive := by positivity + letter := W + length := r + bits := C + m * r + fits := ?_ + good := fun j i => t (j.2 i) + count := fun j i => n (j.2 i) * k + cheaper := ?_ + covers := ?_ }⟩ + · simp only [W, Fintype.card_prod, Fintype.card_fin, Fintype.card_fun, pow_add, pow_mul] + exact Nat.mul_le_mul (Nat.lt_two_pow_self.le) (Nat.pow_le_pow_left Nat.lt_two_pow_self.le r) + · intro j + have hs : (∑ i : Fin r, ((n (j.2 i) * k : ℕ) : ℝ) * p (t (j.2 i))) ≤ + ∑ _ : Fin r, ((b : ℝ) * k * L - (m * H + 1)) := by + refine Finset.sum_le_sum fun i _ => ?_ + rw [Nat.cast_mul] + linarith only [hg (j.2 i)] + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] at hs + push_cast at hs ⊢ + linarith only [hs, (le_max_right _ _).trans_lt hr] + · have he := hC r + rw [← pow_mul, expand_word] at he + exact he + +/-- A failed test on one ball gives a local restriction at strictly lower +cost in every branch, including the cost of transmitting the selector. -/ +theorem failed_replacement [Nonempty I] + (T : I → Tensor K S) (hT : ∀ i, T i ≠ 0) + (p : I → ℝ) (hp : ∀ i, 0 ≤ p i) (s : Finset I) (hL : 0 < ∑ i ∈ s, p i) + (hpos : ∀ v : Tensor K S →+* ℝ, Monotone v → ∃ i, 1 < v (T i)) + (hfail : ¬ Consistent T p s) (H : ℝ) : + Nonempty (Replacement (∏ i ∈ s, T i) T p (∑ i ∈ s, p i) H) := by + obtain ⟨J, _, b, t, n, hb, hc, hv⟩ := failed_offers T hT p hp s hL hpos hfail + refine replace_aux _ _ _ _ _ (fun j : Option J => j.elim (Classical.arbitrary I) t) + (fun j => j.elim 0 n) b hb ?_ ?_ ⟨none, rfl⟩ + · rintro (_ | j) + · simpa using mul_pos (Nat.cast_pos.mpr hb) hL + · exact hc j + · intro v h + obtain ⟨j, hj⟩ := hv v h + exact ⟨some j, hj⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# A finite menu of local substitutions + +Prices may vary on a compact set. Only coordinates of positive price +are demanded. Strict bounds for the selected demands and all branches +persist on an open neighborhood of the original price vector. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral Set + +variable {K S I : Type} [Field K] [Fintype S] + +/-- The data for the proposal construction, including `demand`, `posted`, `move`. -/ +structure Proposal (T : I → Tensor K S) (H : ℝ) where + /-- The requested data of type `Finset I`. -/ + demand : Finset I + /-- The `Proposal` component of type `I → ℝ`. -/ + posted : I → ℝ + /-- The selected move of type `Replacement (∏ i ∈ demand, T i) T posted (∑ i ∈ demand, posted + i) H`. -/ + move : Replacement (∏ i ∈ demand, T i) T posted (∑ i ∈ demand, posted i) H + +variable {T : I → Tensor K S} {H : ℝ} + +namespace Proposal + +/-- The quantity computed by `(∑ i, (q.move.count j i : ℝ) * p (q.move.good j i)) + q.move.bits +* H`. -/ +def cost (q : Proposal T H) (j : q.move.letter) (p : I → ℝ) : ℝ := + (∑ i, (q.move.count j i : ℝ) * p (q.move.good j i)) + q.move.bits * H + +/-- Requires `(∀ i ∈ q.demand, δ < p i) ∧ ∀ j, q.cost j p < q.move.block * ((∑ i ∈ q.demand, p +i) - δ)`. -/ +def Works (q : Proposal T H) (δ : ℝ) (p : I → ℝ) : Prop := + (∀ i ∈ q.demand, δ < p i) ∧ ∀ j, q.cost j p < q.move.block * ((∑ i ∈ q.demand, p i) - δ) + +theorem Works.mono {q : Proposal T H} {δ ε : ℝ} {p : I → ℝ} (h : q.Works ε p) + (hδε : δ ≤ ε) : q.Works δ p := + ⟨fun i hi => hδε.trans_lt (h.1 i hi), fun j => (h.2 j).trans_le + (mul_le_mul_of_nonneg_left (sub_le_sub_left hδε _) (Nat.cast_nonneg _))⟩ + +private theorem open_works (q : Proposal T H) : + IsOpen {x : ℝ × (I → ℝ) | q.Works x.1 x.2} := by + simp only [Works, ofPred_and, ofPred_forall] + apply IsOpen.inter + · exact isOpen_biInter_finset fun i _ => isOpen_lt continuous_fst ((continuous_apply i).comp + continuous_snd) + · refine isOpen_iInter_of_finite fun j => isOpen_lt ?_ (by fun_prop) + unfold cost + fun_prop + +private theorem positive_margin (q : Proposal T H) + (hp : ∀ i ∈ q.demand, 0 < q.posted i) : ∃ δ : ℝ, 0 < δ ∧ q.Works δ q.posted := by + have ho : IsOpen {δ : ℝ | q.Works δ q.posted} := + q.open_works.preimage (continuous_id.prodMk continuous_const) + have h0 : q.Works 0 q.posted := ⟨hp, fun j => by simpa [cost] using q.move.cheaper j⟩ + obtain ⟨δ, hδ, hs⟩ := Metric.isOpen_iff.mp ho 0 h0 + refine ⟨δ / 2, half_pos hδ, hs ?_⟩ + simpa [Metric.mem_ball, abs_of_pos hδ] using half_lt_self hδ + +end Proposal + +theorem uniform_move_bound (menu : Finset (Proposal T H)) : + ∃ C : ℕ, ∀ q ∈ menu, q.move.block ≤ C ∧ ∀ j, ∑ k, q.move.count j k ≤ C := by + let size (q : Proposal T H) := q.move.block + ∑ j, ∑ k, q.move.count j k + refine ⟨∑ q ∈ menu, size q, fun q hq => ?_⟩ + have h := Finset.single_le_sum (fun i _ => Nat.zero_le (size i)) hq + refine ⟨(Nat.le_add_right _ _).trans h, fun j => ?_⟩ + exact (Finset.single_le_sum (f := fun i => ∑ k, q.move.count i k) + (fun i _ => Nat.zero_le _) (Finset.mem_univ j)).trans ((Nat.le_add_left _ _).trans h) + +variable [Nonempty S] [Nonempty I] + +/-- At each failing price vector a uniform saving is possible, using +one of finitely many demand sets and restrictions. -/ +theorem finite_menu (T : I → Tensor K S) (hT : ∀ i, T i ≠ 0) (s : Finset I) + (hpos : ∀ v : Tensor K S →+* ℝ, Monotone v → ∃ i, 1 < v (T i)) + (Q : Set (I → ℝ)) (hc : IsCompact Q) (hp : ∀ p ∈ Q, ∀ i, 0 ≤ p i) + (hn : ∀ p ∈ Q, ∃ i ∈ s, 0 < p i) (hf : ∀ p ∈ Q, ¬ Consistent T p s) (H : ℝ) : + ∃ menu : Finset (Proposal T H), ∃ δ : ℝ, 0 < δ ∧ + ∀ p ∈ Q, ∃ q ∈ menu, q.demand ⊆ s ∧ q.demand.Nonempty ∧ q.Works δ p := by + classical + let J := {q : Proposal T H // q.demand ⊆ s ∧ q.demand.Nonempty} × {δ : ℝ // 0 < δ} + let U (j : J) := {p : I → ℝ | j.1.val.Works j.2 p} + have ho (j : J) : IsOpen (U j) := + j.1.val.open_works.preimage (continuous_const.prodMk continuous_id) + have hu : Q ⊆ ⋃ j, U j := by + intro p h + let t := s.filter fun i => 0 < p i + have ht : t.Nonempty := by + obtain ⟨i, hi, hpi⟩ := hn p h + exact ⟨i, Finset.mem_filter.mpr ⟨hi, hpi⟩⟩ + have ht' : ∀ i ∈ t, 0 < p i := fun i hi => (Finset.mem_filter.mp hi).2 + have bad : ¬ Consistent T p t := by + rintro ⟨d, v, hd, hv, hcap, he⟩ + refine hf p h ⟨d, v, hd, hv, hcap, fun i hi => ?_⟩ + by_cases hpi : 0 < p i + · exact he i (Finset.mem_filter.mpr ⟨hi, hpi⟩) + · exact le_antisymm (hcap i) ((le_of_not_gt hpi).trans (Tensor.values_nonneg hd hv _)) + obtain ⟨R⟩ := failed_replacement T hT p (hp p h) t (Finset.sum_pos ht' ht) hpos bad H + let q : Proposal T H := ⟨t, p, R⟩ + obtain ⟨δ, hδ, hq⟩ := q.positive_margin ht' + exact mem_iUnion.mpr ⟨(⟨q, Finset.filter_subset _ _, ht⟩, ⟨δ, hδ⟩), hq⟩ + obtain ⟨u, h⟩ := hc.elim_finite_subcover U ho hu + let v := insert 1 (u.image fun j => j.2.val) + have hv : v.Nonempty := ⟨1, Finset.mem_insert_self _ _⟩ + refine ⟨u.image (fun j => j.1.val), v.min' hv, ?_, fun p hp => ?_⟩ + · rcases Finset.mem_insert.mp (v.min'_mem hv) with he | he + · rw [he]; exact zero_lt_one + · obtain ⟨j, _, hj⟩ := Finset.mem_image.mp he + exact hj ▸ j.2.property + · obtain ⟨j, hj, hh⟩ := mem_iUnion₂.mp (h hp) + have hδ : j.2.val ∈ v := Finset.mem_insert_of_mem (Finset.mem_image_of_mem _ hj) + exact ⟨_, Finset.mem_image_of_mem _ hj, j.1.property.1, j.1.property.2, + Proposal.Works.mono hh (v.min'_le _ hδ)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Local price tests with a tolerance + +A near match is open in the posted prices, even with no scale bound. +On the compact remainder the finite menu gives a uniform improvement. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral Set + +variable {K S I : Type} [Field K] [Fintype S] [Nonempty S] [Fintype I] + +/-- The condition `∃ P, (P = 0 ∨ ∃ D, P ∈ Tensor.ordinary K S D) ∧ (∀ i, P (T i) < p i + ρ) ∧ ∀ +i ∈ s, |p i - P (T i)| < ρ` on the specified data. -/ +def NearPrices (T : I → Tensor K S) (s : Finset I) (ρ : ℝ) (p : I → ℝ) : Prop := + ∃ P, (P = 0 ∨ ∃ D, P ∈ Tensor.ordinary K S D) ∧ + (∀ i, P (T i) < p i + ρ) ∧ ∀ i ∈ s, |p i - P (T i)| < ρ + +omit [Nonempty S] in +omit [Fintype I] in +private theorem near_open [Finite I] (T : I → Tensor K S) (s : Finset I) (ρ : ℝ) : + IsOpen {p | NearPrices T s ρ p} := by + let : Fintype I := Fintype.ofFinite I + let J := {P // P = 0 ∨ ∃ D, P ∈ Tensor.ordinary K S D} + let U (j : J) := {p : I → ℝ | (∀ i, j.val (T i) < p i + ρ) ∧ + ∀ i ∈ s, |p i - j.val (T i)| < ρ} + have he : {p | NearPrices T s ρ p} = ⋃ j, U j := by + ext p + rw [mem_iUnion] + exact ⟨fun ⟨P, hP, h⟩ => ⟨⟨P, hP⟩, h⟩, fun ⟨j, h⟩ => ⟨j.val, j.property, h⟩⟩ + rw [he] + refine isOpen_iUnion fun j => ?_ + simp only [U, ofPred_and, ofPred_forall] + refine IsOpen.inter ?_ ?_ + · exact isOpen_iInter_of_finite fun i => isOpen_lt continuous_const (by fun_prop) + · exact isOpen_biInter_finset fun i _ => + isOpen_lt ((continuous_apply i).sub continuous_const).abs continuous_const + +omit [Fintype I] in +theorem menu_dichotomy [Finite I] [Nonempty I] (T : I → Tensor K S) (hT : ∀ i, T i ≠ 0) + (s : Finset I) (hpos : ∀ v : Tensor K S →+* ℝ, Monotone v → ∃ i, 1 < v (T i)) + (a : I → ℝ) (H : ℝ) {ρ : ℝ} (hρ : 0 < ρ) : + ∃ menu : Finset (Proposal T H), ∃ δ : ℝ, 0 < δ ∧ + ∀ p ∈ Icc 0 a, NearPrices T s ρ p ∨ + ∃ q ∈ menu, q.demand ⊆ s ∧ q.demand.Nonempty ∧ q.Works δ p := by + let : Fintype I := Fintype.ofFinite I + let Q := Icc 0 a ∩ {p | NearPrices T s ρ p}ᶜ + have hc : IsCompact Q := isCompact_Icc.inter_right (near_open T s ρ).isClosed_compl + have hp : ∀ p ∈ Q, ∀ i, 0 ≤ p i := fun _ h => h.1.1 + have hn (p) (h : p ∈ Q) : ∃ i ∈ s, 0 < p i := by + by_contra! hz + refine h.2 ⟨0, .inl rfl, fun i => add_pos_of_nonneg_of_pos (hp p h i) hρ, fun i hi => ?_⟩ + simpa [le_antisymm (hz i hi) (hp p h i)] using hρ + have hf (p) (h : p ∈ Q) : ¬ Consistent T p s := by + rintro ⟨d, v, hd, hv, hb, he⟩ + refine h.2 ⟨Tensor.values d v, .inr ⟨d, d, ⟨hd, le_rfl⟩, v, hv, rfl⟩, + fun i => (hb i).trans_lt (lt_add_of_pos_right _ hρ), fun i hi => ?_⟩ + simpa [he i hi] using hρ + obtain ⟨m, δ, hd, hm⟩ := finite_menu T hT s hpos Q hc hp hn hf H + exact ⟨m, δ, hd, fun p hp => (em (NearPrices T s ρ p)).imp_right fun h => hm p ⟨hp, h⟩⟩ + +variable [DecidableEq S] + +/-- A connected core cannot have zero length at every link: it would +transport the full diagonal to a single site at no cost. -/ +theorem positive_link (c : S → S → Prop) (hc : ∀ x y, Relation.EqvGen c x y) + (v : Tensor K S →+* ℝ) (hv : Monotone v) : + ∃ x y, c x y ∧ 1 < v (Tensor.wire K x y 2) := by + by_contra! hh + have hz {x y : S} (h : Relation.EqvGen c x y) : Tensor.dist v x y = 0 := by + induction h with + | rel x y h => + have he : v (Tensor.wire K x y 2) = 1 := le_antisymm (hh x y h) (by + simpa using hv (Tensor.one_le_wire K x y (n := 2) (by decide))) + simp [Tensor.dist, he] + | refl x => exact Tensor.dist_self _ _ + | symm x y _ ih => rw [Tensor.dist_comm, ih] + | trans x y z _ _ ih ij => + exact le_antisymm (by simpa [ih, ij] using Tensor.dist_triangle v hv x y z) + (Tensor.dist_nonneg v hv _ _) + let x := Classical.arbitrary S + have he := Tensor.price_place_eq v hv id (fun _ => x) (fun s => hz (hc s x)) + (Tensor.shared K Finset.univ 2) + have h : (Finset.univ.image (fun _ : S => x)) = {x, x} := by ext t; simp [eq_comm] + rw [Tensor.place_id, Tensor.place_shared, h, Tensor.shared_all] at he + change v (2 : Tensor K S) = v (Tensor.wire K x x 2) at he + rw [Tensor.wire_self K x (by decide), map_one, map_ofNat] at he + norm_num at he + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Repeating a local substitution at a fixed inventory + +Only the histogram remains in the outer sum. Sending a selector at +every repetition suffices to pay for all words with that histogram. +The outer alphabet grows polynomially in the repetition count. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Finset Spectral Stock + +/-- The histograms of type `Finset (A → ℕ)` for the given inputs. -/ +def histograms (A : Type) [Fintype A] (m : ℕ) : Finset (A → ℕ) := by + classical + exact (Fintype.piFinset (fun _ : A => range (m + 1))).filter (fun t => ∑ i, t i = m) + +theorem mem_histograms {A : Type} [Fintype A] {m : ℕ} {t : A → ℕ} : + t ∈ histograms A m ↔ ∑ i, t i = m := by + classical + rw [histograms, mem_filter] + refine ⟨And.right, fun h => ⟨Fintype.mem_piFinset.mpr fun i => ?_, h⟩⟩ + exact mem_range.mpr (Nat.lt_succ_of_le + ((single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ i)).trans_eq h)) + +theorem card_histograms (A : Type) [Fintype A] (m : ℕ) : + (histograms A m).card ≤ (m + 1) ^ Fintype.card A := by + classical + unfold histograms + refine (card_filter_le _ _).trans_eq ?_ + simp + +variable {K S I : Type} [Field K] [Fintype S] [Nonempty S] + +omit [Nonempty S] in +/-- Bound each word by its inventory and pay separately for the selector words. -/ +theorem word_bound {A : Type} [Fintype A] (V : A → Tensor K S) (m : ℕ) + {X : Tensor K S} (hX : ∀ h ∈ histograms A m, bundle V h ≤ X) : + (∑ i, V i) ^ m ≤ (Fintype.card A : Tensor K S) ^ m * X := by + classical + let : AddLeftMono (Tensor K S) := + ⟨fun c a b h => by rw [add_comm c a, add_comm c b]; exact Tensor.add_le_add_right _ _ _ h⟩ + calc + _ = ∑ f : Fin m → A, ∏ j, V (f j) := Fintype.sum_pow _ _ + _ ≤ ∑ _ : Fin m → A, X := sum_le_sum fun f _ => by + let t (i : A) := (univ.filter (fun j => f j = i)).card + have ht : t ∈ histograms A m := by + apply mem_histograms.mpr + simpa only [card_univ, Fintype.card_fin] using + (card_eq_sum_card_fiberwise (s := univ) (t := univ) (f := f) (by simp)).symm + have h : (∏ j, V (f j)) = bundle V t := by + rw [← prod_fiberwise' univ f V] + simp only [prod_const, bundle, t] + rw [h] + exact hX t ht + _ = _ := by simp [nsmul_eq_mul] + +namespace Proposal + +variable {T : I → Tensor K S} {H : ℝ} [DecidableEq I] (q : Proposal T H) + +/-- Computes the orders by the application `collect (q.move.good j) (q.move.count j)`. -/ +def orders (j : q.move.letter) : I → ℕ := collect (q.move.good j) (q.move.count j) + +/-- The quantity computed by `copies u (q.move.bits * m) i + ∑ j, q.orders j i * h j`. -/ +def output (u : Finset I) (m : ℕ) (h : q.move.letter → ℕ) (i : I) : ℕ := + copies u (q.move.bits * m) i + ∑ j, q.orders j i * h j + +variable [Fintype I] + +/-- A comparison of selector inventories suffices to scale a whole batch. -/ +theorem batch_scaled (u : Finset I) (hu : (2 : Tensor K S) ≤ ∏ i ∈ u, T i) + (m n z : ℕ) (hmn : m ≤ n) + (hcover : ∀ t ∈ histograms q.move.letter (m * z), ∃ h ∈ histograms q.move.letter n, + bundle (fun j => bundle T (q.orders j)) t ≤ (bundle (fun j => bundle T (q.orders j)) h) ^ z) : + (bundle T (copies q.demand (q.move.block * m))) ^ z ≤ + ∑ h ∈ histograms q.move.letter n, (bundle T (q.output u n h)) ^ z := by + classical + let : MulLeftMono (Tensor K S) := ⟨fun c a b h => Tensor.mul_le_mul_left _ _ _ h⟩ + let : AddLeftMono (Tensor K S) := + ⟨fun c a b h => by rw [add_comm c a, add_comm c b]; exact Tensor.add_le_add_right _ _ _ h⟩ + let V j := bundle T (q.orders j) + have hv (j) : V j = ∏ k, T (q.move.good j k) ^ q.move.count j k := + bundle_collect T (q.move.good j) (q.move.count j) + have h : (∏ i ∈ q.demand, T i) ^ q.move.block ≤ ∑ j, V j := by + simp only [hv] + exact q.move.covers + have hc : (Fintype.card q.move.letter : Tensor K S) ≤ (∏ i ∈ u, T i) ^ q.move.bits := by + refine (Tensor.natCast_le q.move.fits).trans ?_ + rw [Nat.cast_pow, Nat.cast_ofNat] + exact pow_le_pow_left' hu _ + let X := ∑ h ∈ histograms q.move.letter n, (bundle V h) ^ z + have hX (t) (ht : t ∈ histograms q.move.letter (m * z)) : bundle V t ≤ X := by + obtain ⟨r, hr, htr⟩ := hcover t ht + exact htr.trans (single_le_sum (f := fun h => (bundle V h) ^ z) (fun _ _ + => Tensor.zero_le _) hr) + have h₁ : 1 ≤ ∏ i ∈ u, T i := by + have h₂ := Tensor.natCast_le (K := K) (S := S) (by decide : 1 ≤ 2) + rw [Nat.cast_one, Nat.cast_ofNat] at h₂ + exact h₂.trans hu + have hp := pow_le_pow_left' h₁ q.move.bits + rw [one_pow] at hp + rw [bundle_copies, pow_mul, ← pow_mul _ m z] + refine ((pow_le_pow_left' h (m * z)).trans (word_bound V (m * z) hX)).trans ?_ + have hh := (pow_le_pow_left' hc (m * z)).trans (pow_le_pow_right' hp (Nat.mul_le_mul_right z hmn)) + refine (mul_le_mul_left hh X).trans_eq ?_ + unfold X + rw [mul_sum] + apply sum_congr rfl + intro t _ + unfold output + rw [bundle_add, bundle_copies, bundle_sum, mul_pow, pow_mul, pow_mul] + rfl + +theorem batch (u : Finset I) (hu : (2 : Tensor K S) ≤ ∏ i ∈ u, T i) (m : ℕ) : + bundle T (copies q.demand (q.move.block * m)) ≤ + ∑ h ∈ histograms q.move.letter m, bundle T (q.output u m h) := by + simpa only [pow_one] using q.batch_scaled u hu m m 1 le_rfl + (fun t ht => ⟨t, by simpa using ht, by rw [pow_one]⟩) + +omit [Nonempty S] in +theorem batch_cost (u : Finset I) (p : I → ℝ) {δ : ℝ} + (hw : q.Works δ p) (hu : ∑ i ∈ u, p i ≤ H) + {m : ℕ} {h : q.move.letter → ℕ} (hh : h ∈ histograms q.move.letter m) : + total p (q.output u m h) ≤ (q.move.block * m : ℕ) * ((∑ i ∈ q.demand, p i) - δ) := by + have hh' : ∑ j, (h j : ℝ) = m := by exact_mod_cast mem_histograms.mp hh + let v := (∑ i ∈ q.demand, p i) - δ + have hj (j : q.move.letter) : total p (q.orders j) ≤ q.move.block * v - q.move.bits * H := by + rw [orders, total_collect] + exact (le_sub_iff_add_le).mpr (hw.2 j).le + unfold output + rw [total_add, total_copies, total_sum] + calc + _ ≤ (q.move.bits * m : ℕ) * H + ∑ j, (q.move.block * v - q.move.bits * H) * (h j : ℝ) := + add_le_add (mul_le_mul_of_nonneg_left hu (Nat.cast_nonneg _)) + (sum_le_sum fun j _ => mul_le_mul_of_nonneg_right (hj j) (Nat.cast_nonneg _)) + _ = _ := by rw [← mul_sum, hh']; unfold v; push_cast; ring + +end Proposal +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # An inventory change with an outcome-dependent supply -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +/-- The data for the intervention construction, including `choice`, `[finiteChoice`, `take`, +`put`, `core`. -/ +structure Intervention (I E : Type) where + /-- The `Intervention` component of type `Type`. -/ + choice : Type + [finiteChoice : Fintype choice] + /-- The `Intervention` component of type `I → ℕ`. -/ + take : I → ℕ + /-- The `Intervention` component of type `choice → I → ℕ`. -/ + put : choice → I → ℕ + /-- The `Intervention` component of type `choice → E → ℕ`. -/ + core : choice → E → ℕ + +attribute [instance] Intervention.finiteChoice + +namespace Intervention + +variable {I E : Type} (q : Intervention I E) + +/-- The quantity computed by `z i - q.take i + q.put j i`. -/ +def next (z : I → ℕ) (j : q.choice) (i : I) := z i - q.take i + q.put j i + +/-- Counts the core intervention at each edge for the chosen routing. -/ +def cost [Fintype E] (j : q.choice) : ℕ := ∑ e, q.core j e + +open Spectral Stock + +variable {K S : Type} [Field K] [Fintype S] [Fintype I] [Fintype E] + +/-- Requires `bundle T q.take ≤ ∑ j, bundle T (q.put j) * bundle V (q.core j)`. -/ +def Covers (T : I → Tensor K S) (V : E → Tensor K S) : Prop := + bundle T q.take ≤ ∑ j, bundle T (q.put j) * bundle V (q.core j) + +theorem covers_next {T : I → Tensor K S} {V : E → Tensor K S} (h : q.Covers T V) + (z : I → ℕ) (hz : q.take ≤ z) : + bundle T z ≤ ∑ j, bundle T (q.next z j) * bundle V (q.core j) := by + let x := fun i => z i - q.take i + calc + _ = bundle T x * bundle T q.take := by + rw [← bundle_add, show (fun i => x i + q.take i) = z from funext fun i + => Nat.sub_add_cancel (hz i)] + _ ≤ bundle T x * ∑ j, bundle T (q.put j) * bundle V (q.core j) := Tensor.mul_le_mul_left _ _ _ h + _ = _ := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro j _ + rw [← mul_assoc, ← bundle_add] + rfl + +end Intervention +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- # Posting a batch of local orders to a shared inventory -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open Spectral Stock Finset + +variable {I E J : Type} [Fintype I] [Fintype E] [Fintype J] + +namespace Intervention + +/-- Linear saving for each outcome, and the per-commodity volume limit. +Only positive-price stock may be consumed. -/ +def Efficient (q : Intervention I E) (p : I → ℝ) (δ : ℝ) (B m : ℕ) : Prop := + (∀ i, q.take i ≤ B * m ∧ (q.take i ≠ 0 → δ ≤ p i)) ∧ + ∀ j, (∀ i, q.put j i ≤ B * m) ∧ + total p (q.put j) + q.cost j + m * δ ≤ total p q.take + +/-- Requires `q.take i ≠ 0 ∨ ∃ j, q.put j i ≠ 0`. -/ +def affects (q : Intervention I E) (i : I) : Prop := + q.take i ≠ 0 ∨ ∃ j, q.put j i ≠ 0 + +end Intervention + +namespace Stock + +omit [Fintype I] in +theorem collect_nonzero [DecidableEq I] {g : J → I} {x : J → ℕ} {i : I} + (h : collect g x i ≠ 0) : ∃ j, g j = i ∧ x j ≠ 0 := by + obtain ⟨j, hj, hn⟩ := exists_ne_zero_of_sum_ne_zero h + exact ⟨j, (mem_filter.mp hj).2, hn⟩ + +omit [Fintype I] in +theorem collect_inj [DecidableEq I] {g : J → I} (hg : Function.Injective g) + (x : J → ℕ) (j : J) : collect g x (g j) = x j := by + unfold collect + exact sum_eq_single j (fun k hk hn => (hn (hg (mem_filter.mp hk).2)).elim) (by simp) + +theorem total_split (p : I → ℝ) (x : I ⊕ E → ℕ) : + total (Sum.elim p (fun _ => 1)) x = total p (x ∘ Sum.inl) + (∑ e, x (.inr e) : ℕ) := by + simp [total, Fintype.sum_sum_type] + +theorem bundle_split {R : Type*} [CommMonoid R] (T : I ⊕ E → R) (x : I ⊕ E → ℕ) : + bundle T x = bundle (T ∘ Sum.inl) (x ∘ Sum.inl) * bundle (T ∘ Sum.inr) (x ∘ Sum.inr) := + Fintype.prod_sum_type _ + +end Stock + +namespace Proposal + +variable {K S : Type} [Field K] [Fintype S] {T : J → Tensor K S} {H : ℝ} + [DecidableEq I] [DecidableEq E] [DecidableEq J] + (q : Proposal T H) (g : J → I ⊕ E) (u : Finset J) (m : ℕ) + +/-- Builds `Intervention I E where choice` with the specified `choice`, `take`, `put`, `core`. -/ +def trade : Intervention I E where + choice := ↥(histograms q.move.letter m) + take := collect g (copies q.demand (q.move.block * m)) ∘ Sum.inl + put j := collect g (q.output u m j.val) ∘ Sum.inl + core j := collect g (q.output u m j.val) ∘ Sum.inr + +omit [Fintype I] [Fintype E] in +theorem trade_support {i : I} (h : (q.trade g u m).affects i) : ∃ j, g j = .inl i := by + rcases h with h | ⟨_, h⟩ <;> + obtain ⟨j, hj, _⟩ := collect_nonzero h <;> exact ⟨j, hj⟩ + +omit [Fintype I] [Fintype E] in +theorem take_core (hd : ∀ j ∈ q.demand, ∃ i, g j = .inl i) (e : E) : + collect g (copies q.demand (q.move.block * m)) (.inr e) = 0 := by + by_contra h + obtain ⟨j, hj, hn⟩ := collect_nonzero h + obtain ⟨i, hi⟩ := hd j (by by_contra h; simp [copies, h] at hn) + rw [hi] at hj + contradiction + +theorem trade_efficient (hg : Function.Injective g) + (hd : ∀ j ∈ q.demand, ∃ i, g j = .inl i) + (hu : ∀ j ∈ u, ∃ e, g j = .inr e) (hc : (u.card : ℝ) ≤ H) + {p : I → ℝ} {δ : ℝ} (hδ : 0 ≤ δ) + (hw : q.Works δ (Sum.elim p (fun _ => 1) ∘ g)) + {B : ℕ} (hb : q.move.block ≤ B) (ho : ∀ j, ∑ k, q.move.count j k ≤ B) : + (q.trade g u m).Efficient p δ B m := by + let P : I ⊕ E → ℝ := Sum.elim p (fun _ => 1) + have hcore : ∑ i ∈ u, (P ∘ g) i ≤ H := by + refine le_trans ?_ hc + rw [show (u.card : ℝ) = ∑ _ ∈ u, (1 : ℝ) by simp] + apply sum_le_sum + intro j hj + obtain ⟨e, he⟩ := hu j hj + simp [P, he] + constructor + · intro i + by_cases hz : (q.trade g u m).take i = 0 + · simp [hz] + obtain ⟨j, hj, hne⟩ := collect_nonzero hz + have hjd : j ∈ q.demand := by by_contra h; simp [copies, h] at hne + refine ⟨?_, fun _ => ?_⟩ + · change collect g _ (.inl i) ≤ _ + rw [← hj, collect_inj hg, copies, ite_eq_left hjd] + exact Nat.mul_le_mul_right m hb + · simpa [hj] using (hw.1 j hjd).le + intro h + constructor + · intro i + by_cases hz : (q.trade g u m).put h i = 0 + · simp [hz] + obtain ⟨j, hj, _⟩ := collect_nonzero hz + have hju : j ∉ u := by + intro hj' + obtain ⟨e, he⟩ := hu j hj' + rw [hj] at he + contradiction + change collect g _ (.inl i) ≤ _ + rw [← hj, collect_inj hg, output, copies, ite_eq_right hju, zero_add] + calc + _ ≤ ∑ k, B * h.val k := by + apply sum_le_sum + intro k _ + apply Nat.mul_le_mul_right + exact (sum_le_sum_of_subset (filter_subset _ _)).trans (ho k) + _ = _ := by rw [← mul_sum, mem_histograms.mp h.property] + · have hs := q.batch_cost u (P ∘ g) hw hcore h.property + have hy : total p (q.trade g u m).take = (q.move.block * m : ℕ) * ∑ j ∈ q.demand, (P ∘ g) j + := by + rw [← total_copies, ← total_collect, total_split] + simp only [q.take_core g m hd, sum_const_zero, Nat.cast_zero, add_zero] + rfl + rw [← total_collect, total_split] at hs + change total p ((q.trade g u m).put h) + (q.trade g u m).cost h ≤ _ at hs + have hm : (m : ℝ) ≤ (q.move.block * m : ℕ) := by + exact_mod_cast Nat.le_mul_of_pos_left m q.move.positive + linarith only [hs, hy, mul_le_mul_of_nonneg_right hm hδ] + +end Proposal +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Simultaneous inventory changes + +Bounded overlap suffices. A smaller batch per center allows all +selected centers to act simultaneously, without choosing a packing. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Intervention + +open Stock Spectral Finset + +variable {I E J : Type} [Fintype I] [Fintype E] [Fintype J] [DecidableEq J] +variable (q : J → Intervention I E) + +/-- The condition `∀ j, (q j).choice take i := ∑ j, (q j).take i put u i := ∑ j, (q j).put (u j) +i core u e := ∑ j, (q j).core (u j) e` on the specified data. -/ +def parallel : Intervention I E where + choice := ∀ j, (q j).choice + take i := ∑ j, (q j).take i + put u i := ∑ j, (q j).put (u j) i + core u e := ∑ j, (q j).core (u j) e + +/-- The condition `∀ i, ∃ U : Finset J, U.card ≤ N ∧ ∀ j, (q j).affects i → j ∈ U` on the +specified data. -/ +def Overlap (N : ℕ) : Prop := + ∀ i, ∃ U : Finset J, U.card ≤ N ∧ ∀ j, (q j).affects i → j ∈ U + +theorem parallel_covers {K S : Type} [Field K] [Fintype S] + {T : I → Tensor K S} {V : E → Tensor K S} (h : ∀ j, (q j).Covers T V) : + (parallel q).Covers T V := by + let : MulLeftMono (Tensor K S) := ⟨fun c a b h => Tensor.mul_le_mul_left _ _ _ h⟩ + have hb {A : Type} [Fintype A] (t : A → Tensor K S) (z : J → A → ℕ) : + bundle t (fun i => ∑ j, z j i) = ∏ j, bundle t (z j) := by + simpa only [mul_one, pow_one] using bundle_sum t z (fun _ => 1) + unfold Covers parallel + simp only [hb, ← prod_mul_distrib] + rw [← Fintype.prod_sum (fun j c => bundle T ((q j).put c) * bundle V ((q j).core c))] + exact prod_le_prod fun j _ => h j + +theorem parallel_bounds {N B m : ℕ} {p : I → ℝ} {δ : ℝ} + (ho : Overlap q N) (h : ∀ j, (q j).Efficient p δ B m) (i : I) : + (parallel q).take i ≤ N * (B * m) ∧ ((parallel q).take i ≠ 0 → δ ≤ p i) ∧ + ∀ u, (parallel q).put u i ≤ N * (B * m) := by + obtain ⟨U, hu, hl⟩ := ho i + have bound (f : J → ℕ) (hf : ∀ j, f j ≤ B * m) (hs : ∀ j, f j ≠ 0 → (q j).affects i) : + ∑ j, f j ≤ N * (B * m) := by + rw [← sum_subset (subset_univ U) (fun j _ hj => Classical.byContradiction + (fun h => hj (hl j (hs j h))))] + refine (sum_le_sum (fun j _ => hf j)).trans ?_ + simpa using Nat.mul_le_mul_right (B * m) hu + refine ⟨bound _ (fun j => ((h j).1 i).1) (fun _ => Or.inl), ?_, ?_⟩ + · intro ht + obtain ⟨j, _, hj⟩ := exists_ne_zero_of_sum_ne_zero ht + exact ((h j).1 i).2 hj + · intro u + exact bound _ (fun j => ((h j).2 (u j)).1 i) (fun j h => .inr ⟨u j, h⟩) + +theorem parallel_saving {B m : ℕ} {p : I → ℝ} {δ : ℝ} + (h : ∀ j, (q j).Efficient p δ B m) (u : (parallel q).choice) : + total p ((parallel q).put u) + (parallel q).cost u + Fintype.card J * ((m : ℝ) * δ) ≤ + total p (parallel q).take := by + have hp (z : J → I → ℕ) : total p (fun i => ∑ j, z j i) = ∑ j, total p (z j) := by + simpa using total_sum p z (fun _ => 1) + have hc : (parallel q).cost u = ∑ j, (q j).cost (u j) := sum_comm + rw [hc, Nat.cast_sum] + change total p (fun i => ∑ j, (q j).put (u j) i) + _ + _ ≤ total p (fun i => ∑ j, (q j).take i) + rw [hp, hp] + simpa only [sum_add_distrib, sum_const, card_univ, nsmul_eq_mul] using + sum_le_sum (s := univ) (fun j _ => ((h j).2 (u j)).2) + +/-- The account drops by the linear saving minus a quadratic error. -/ +theorem parallel_change {N B m M : ℕ} (d : I → ℕ) (hd : ∀ i, d i + ≤ M) {a : I → ℝ} {z : I → ℕ} {μ δ : ℝ} (hμ : 0 < μ) + (ho : Overlap q N) (h : ∀ j, (q j).Efficient (fun i => price μ (a i) (z i)) δ B m) + (hs : (N * (B * m) : ℕ) ≤ μ * δ) : + (parallel q).take ≤ z ∧ ∀ u, + potential μ a ((parallel q).next z u + d) + (parallel q).cost u + + Fintype.card J * ((m : ℝ) * δ) ≤ + potential μ a z + total (fun i => price μ (a i) (z i)) d + + Fintype.card I * (((N * (B * m) : ℕ) : ℝ) + M) ^ 2 / (2 * μ) := by + let Q := parallel q + let t : ℝ := (N * (B * m) : ℕ) + have ht (i) : (Q.take i : ℝ) ≤ t := Nat.cast_le.mpr (parallel_bounds q ho h i).1 + have hz : Q.take ≤ z := by + intro i + by_cases he : Q.take i = 0 + · simp [he] + apply (Nat.cast_le (α := ℝ)).mp + refine (ht i).trans (hs.trans ?_) + exact (mul_le_mul_of_nonneg_left ((parallel_bounds q ho h i).2.1 he) hμ.le).trans + (mul_price_le hμ) + refine ⟨hz, fun u => ?_⟩ + let p i := price μ (a i) (z i) + let y := Q.next z u + d + have diff (i) : (y i : ℝ) - z i = (Q.put u i : ℝ) - Q.take i + d i := by + simp only [y, Pi.add_apply, next, Nat.cast_add, Nat.cast_sub (hz i)] + ring + have linear : (∑ i, p i * ((y i : ℝ) - z i)) = total p (Q.put u) - total p Q.take + total p d + := by + simp only [diff, total, ← sum_sub_distrib, ← sum_add_distrib] + exact sum_congr rfl fun _ _ => by ring + have error : (∑ i, ((y i : ℝ) - z i) ^ 2) ≤ Fintype.card I * (t + M) ^ 2 := by + rw [show (Fintype.card I : ℝ) * (t + M) ^ 2 = ∑ _ : I, (t + M) ^ 2 by simp] + apply sum_le_sum + intro i _ + rw [diff] + have hk : (Q.put u i : ℝ) ≤ t := Nat.cast_le.mpr ((parallel_bounds q ho h i).2.2 u) + have hi : (d i : ℝ) ≤ M := Nat.cast_le.mpr (hd i) + nlinarith only [hk, ht i, hi, Nat.cast_nonneg (α := ℝ) (Q.take i), Nat.cast_nonneg (α + := ℝ) (Q.put u i), + Nat.cast_nonneg (α := ℝ) (d i)] + have inc := potential_increment (z := z) (y := y) (a := a) hμ + rw [linear] at inc + have red := parallel_saving q h u + change total p (Q.put u) + Q.cost u + _ ≤ total p Q.take at red + change potential μ a y + Q.cost u + _ ≤ potential μ a z + total p d + Fintype.card I * (t + + M) ^ 2 / (2 * μ) + linarith only [inc, red, div_le_div_of_nonneg_right error (by positivity : 0 ≤ 2 * μ)] + +theorem parallel_gain {N B m : ℕ} {a : I → ℝ} {z : I → ℕ} {μ δ : ℝ} (hμ : 0 < μ) + (ho : Overlap q N) (h : ∀ j, (q j).Efficient (fun i => price μ (a i) (z i)) δ B m) + (hs : (N * (B * m) : ℕ) ≤ μ * δ) : + (parallel q).take ≤ z ∧ ∀ u, + potential μ a ((parallel q).next z u) + (parallel q).cost u + + Fintype.card J * ((m : ℝ) * δ) ≤ + potential μ a z + Fintype.card I * (N * (B * m) : ℕ) ^ 2 / (2 * μ) := by + simpa [total] using parallel_change q 0 (M := 0) (fun _ => le_rfl) hμ ho h hs + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Intervention +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/SortSpec.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/SortSpec.lean new file mode 100644 index 0000000000..f427e3b5df --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/SortSpec.lean @@ -0,0 +1,42 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Tags +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Radix.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute + +/-! # Tensor specifications for tagged permutation and stable sorting -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +/-- Select any ordered subsequence of distinct bit positions, in order +from most to least significant. -/ +def key {w k : ℕ} (e : slots (word k) ↪ slots (word w)) (x : Val (word w)) : Val (word k) := + (bits (word k)).symm (fun i => bits (word w) x (e i)) + +open Classical in +/-- Returns `1` when `Radix.Stable (key e) (flatten h x) (flatten h y)` holds, and `0` +otherwise. -/ +noncomputable def stableTensor (F : Type) [Field F] (h w k : ℕ) + (e : slots (word k) ↪ slots (word w)) + (x y : Val (tree h (word w))) : F := + if Radix.Stable (key e) (flatten h x) (flatten h y) then 1 else 0 + +/-- In the tag predicate the untagged rows are the proposed outputs, +and the tagged rows are inputs bearing their destination addresses. +Both bounds count vertices plus all exterior positions. -/ +def SortingBound (F : Type) [Field F] (h w : ℕ) (M : ℝ) : Prop := + (∃ v, Net F (Tagged.inputs h (word w)) .unit (Tagged.tag F h (word w)) v ∧ + (v + 2 ^ h * (h + 2 * w) : ℕ) ≤ M) ∧ + ∀ k (e : slots (word k) ↪ slots (word w)), + ∃ v, Net F (tree h (word w)) (tree h (word w)) (stableTensor F h w k e) v ∧ + (v + 2 ^ h * (2 * w) : ℕ) ≤ M + +end MatrixMultiplicationAllFields.MatrixExponent.Routing diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Square.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Square.lean new file mode 100644 index 0000000000..0bcf77b5b7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Square.lean @@ -0,0 +1,88 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Dual +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Shared + +/-! # Stable sorting under a strict square saving -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {F : Type} [Field F] [Finite F] + +theorem wide_of_saving (h : omega F < 9 / 4) : Radix.WideTag F := + Routing.wide_of_shared_price (shared_of_saving h) + +theorem short_of_saving (h : omega F < 9 / 4) : + ∃ p : ℝ, 1 < p ∧ p < 2 ∧ Lookup.ShortTag F p := + Radix.short_of_wide (wide_of_saving h) + +theorem sorting_of_saving (h : omega F < 9 / 4) : + ∃ p : ℝ, 1 < p ∧ p < 2 ∧ Lookup.Sorting F p := + Routing.sorting_of_shared_price (shared_of_saving h) + +namespace Routing + +omit [Finite F] in +private theorem SortingBound.mono {h w : ℕ} {a b : ℝ} + (ha : SortingBound F h w a) (hab : a ≤ b) : SortingBound F h w b := by + obtain ⟨⟨m, ht, hm⟩, h⟩ := ha + refine ⟨⟨m, ht, hm.trans hab⟩, fun k e => ?_⟩ + obtain ⟨n, hs, hn⟩ := h k e + exact ⟨n, hs, hn.trans hab⟩ + +/-- A square exponent below nine fourths gives stable sorting bounds over a fixed finite field. +The bounds cover bounded multiples of the height and sufficiently wide records. -/ +theorem conditional_sorting (F : Type) [Field F] [Finite F] (hs : omega F < 9 / 4) : + (∃ p : ℝ, 1 < p ∧ p < 2 ∧ ∀ k : ℕ, ∃ C : ℝ, 0 < C ∧ + ∀ h w : ℕ, 1 ≤ h → w ≤ k * h → SortingBound F h w (C * (2 : ℝ) ^ h * (h : ℝ) ^ p)) ∧ + (∀ ζ : ℝ, 0 < ζ → ∃ A : ℕ, 1 < A ∧ ∃ C : ℝ, 0 < C ∧ + ∀ h w : ℕ, 1 ≤ h → h ^ A ≤ w → SortingBound F h w (C * (2 : ℝ) ^ h * w * (h : ℝ) ^ ζ)) := by + constructor + · obtain ⟨p, hp, hp', C, ht⟩ := short_of_saving hs + refine ⟨p, hp, hp', fun k => ?_⟩ + let K := 2 + 2 * k + have hk : 1 ≤ K := by unfold K; omega + refine ⟨(8*|C|+3000400) * K, by positivity, fun h w hh hw => ?_⟩ + obtain ⟨m, hm, hcost⟩ := ht h hh + obtain ⟨n, hn, hb⟩ := Radix.widen hh le_rfl (show h ≤ K * h by nlinarith) hm + have hW : 1 + h + 2 * w ≤ K * h := by unfold K; linarith + have hN : n ≤ 2 * K * m + 100 * 2 ^ h * (K * h) := by + refine Nat.le_of_mul_le_mul_right ?_ hh + convert hb using 1 + ring + have hn' : (n : ℝ) ≤ 2 * K * m + 100 * (2 : ℝ) ^ h * (K * h) := by exact_mod_cast hN + have hh' : (h : ℝ) ≤ (h : ℝ) ^ p := by + simpa using Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast hh : 1 ≤ (h : ℝ)) hp.le + have hcost' : (m : ℝ) ≤ |C| * (2 : ℝ) ^ h * (h : ℝ) ^ p := by + refine hcost.trans ?_ + gcongr + exact le_abs_self _ + refine (sorting_bound hn hW).mono ?_ + push_cast + linarith only [hn', mul_le_mul_of_nonneg_left hcost' (Nat.cast_nonneg K), + mul_le_mul_of_nonneg_left hh' (show 0 ≤ (K : ℝ) * (2 : ℝ) ^ h by positivity)] + · intro ζ hζ + obtain ⟨A, hA, C, ht⟩ := wide_of_saving hs ζ hζ + refine ⟨A, hA, 16*|C|+12000000, by positivity, fun h w hh hw => ?_⟩ + have hl := (Nat.le_self_pow (by omega : A ≠ 0) h).trans hw + obtain ⟨m, hm, hcost⟩ := ht h (4 * w) hh (by omega) + refine (sorting_bound hm (by omega : 1 + h + 2 * w ≤ 4 * w)).mono ?_ + have hh' : 1 ≤ (h : ℝ) ^ ζ := Real.one_le_rpow (by exact_mod_cast hh) hζ.le + have hcost' : (m : ℝ) ≤ |C| * (2 : ℝ) ^ h * (4 * w) * (h : ℝ) ^ ζ := by + push_cast at hcost + refine hcost.trans ?_ + gcongr + exact le_abs_self _ + push_cast + linarith only [hcost', mul_le_mul_of_nonneg_left hh' (show 0 ≤ (2 : ℝ) ^ h * w by positivity)] + +end Routing +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Uniform/System.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Uniform/System.lean new file mode 100644 index 0000000000..3b6b06ded6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Routing/Uniform/System.lean @@ -0,0 +1,380 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Field +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.Linarith +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Comparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rank +public import Mathlib.Analysis.SpecialFunctions.Log.Basic +public import Mathlib.Tactic.Positivity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Space +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place +public import Mathlib.Tactic.Ring +public import Mathlib.Data.Fintype.Sigma +public import Mathlib.Data.Fintype.Perm +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.Partitions +public import Mathlib.Data.Nat.Log +public import Mathlib.Logic.Equiv.Fintype + +/-! +# Paying for outstanding requests + +Stock is measured in raw bits, with the batch scale absorbed into the +smoothing parameter. The potential is the maximum linear valuation +minus a quadratic penalty under a separate price cap for each type. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +/-- The minimum of the quantities in `a (z / μ)`. -/ +def price (μ a z : ℝ) : ℝ := min a (z / μ) + +/-- The quantity computed by `z * price μ a z - μ * (price μ a z) ^ 2 / 2`. -/ +def value (μ a z : ℝ) : ℝ := z * price μ a z - μ * (price μ a z) ^ 2 / 2 + +section Scalar + +variable {μ a y z : ℝ} + +theorem price_nonneg (hμ : 0 < μ) (ha : 0 ≤ a) (hz : 0 ≤ z) : + 0 ≤ price μ a z := le_min ha (div_nonneg hz hμ.le) + +theorem price_le : price μ a z ≤ a := min_le_left _ _ + +theorem mul_price_le (hμ : 0 < μ) : μ * price μ a z ≤ z := by + rw [mul_comm] + exact (le_div_iff₀ hμ).mp (min_le_right _ _) + +/-- The first-order condition remains valid when the cap binds. -/ +private theorem first_order (hμ : 0 < μ) {b : ℝ} (hb : b ≤ a) : + (b - price μ a z) * (z - μ * price μ a z) ≤ 0 := by + rcases le_total a (z / μ) with h | h + · exact mul_nonpos_of_nonpos_of_nonneg + (sub_nonpos.mpr (by rw [price, min_eq_left h]; exact hb)) + (sub_nonneg.mpr (mul_price_le hμ)) + · rw [price, min_eq_right h, mul_div_cancel₀ _ hμ.ne', sub_self, mul_zero] + +private theorem value_optimal (hμ : 0 < μ) {b : ℝ} (hb : b ≤ a) : + z * b - μ * b ^ 2 / 2 ≤ value μ a z := by + unfold value + nlinarith only [first_order (z := z) hμ hb, mul_nonneg hμ.le (sq_nonneg (b - price μ a z))] + +theorem value_nonneg (hμ : 0 < μ) (ha : 0 ≤ a) : + 0 ≤ value μ a z := by simpa using value_optimal (z := z) hμ ha + +theorem value_zero (ha : 0 ≤ a) : value μ a 0 = 0 := by + simp [value, price, ha] + +theorem value_close (hμ : 0 < μ) : a * z ≤ value μ a z + μ * a ^ 2 / 2 := by + linarith only [value_optimal (z := z) hμ (le_refl a)] + +theorem value_increment (hμ : 0 < μ) : + value μ a y ≤ value μ a z + price μ a z * (y - z) + (y - z) ^ 2 / (2 * μ) := by + apply sub_le_iff_le_add'.mp + apply (le_div_iff₀ (mul_pos zero_lt_two hμ)).mpr + have h := first_order (z := z) hμ (price_le (μ := μ) (a := a) (z := y)) + unfold value + nlinarith only [mul_nonpos_of_nonneg_of_nonpos hμ.le h, + sq_nonneg (μ * (price μ a y - price μ a z) - (y - z))] + +theorem value_drain (hμ : 0 < μ) (hth : μ * a ≤ y) (hyz : y ≤ z) : + value μ a y + (z - y) * a ≤ value μ a z := by + have h (w : ℝ) (hw : μ * a ≤ w) : price μ a w = a := + min_eq_left ((le_div_iff₀ hμ).mpr (by rwa [mul_comm])) + rw [value, value, h y hth, h z (hth.trans hyz)] + linarith + +end Scalar + +variable {I : Type*} [Fintype I] + +/-- The sum of `value μ (a i) (z i)` indexed by `i`. -/ +def potential (μ : ℝ) (a : I → ℝ) (z : I → ℕ) : ℝ := + ∑ i, value μ (a i) (z i) + +variable {μ : ℝ} {a : I → ℝ} {y z : I → ℕ} + +theorem potential_nonneg (hμ : 0 < μ) (ha : ∀ i, 0 ≤ a i) : 0 ≤ potential μ a z := + Finset.sum_nonneg (fun i _ => value_nonneg hμ (ha i)) + +theorem potential_zero (ha : ∀ i, 0 ≤ a i) : potential μ a 0 = 0 := by + simp [potential, value_zero (ha _)] + +theorem potential_close (hμ : 0 < μ) : + ∑ i, a i * z i ≤ potential μ a z + μ * (∑ i, a i ^ 2) / 2 := by + rw [potential, Finset.mul_sum, Finset.sum_div, ← Finset.sum_add_distrib] + exact Finset.sum_le_sum (fun _ _ => value_close hμ) + +theorem potential_increment (hμ : 0 < μ) : + potential μ a y ≤ potential μ a z + (∑ i, price μ (a i) (z i) * ((y i : ℝ) - z i)) + + (∑ i, ((y i : ℝ) - z i) ^ 2) / (2 * μ) := by + rw [potential, potential, Finset.sum_div, ← Finset.sum_add_distrib, ← Finset.sum_add_distrib] + exact Finset.sum_le_sum (fun _ _ => value_increment hμ) + +theorem potential_drain (hμ : 0 < μ) (hyz : ∀ i, y i ≤ z i) + (hth : ∀ i, y i < z i → μ * a i ≤ y i) : + potential μ a y + ∑ i, ((z i : ℝ) - y i) * a i ≤ potential μ a z := by + rw [potential, potential, ← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro i _ + rcases (hyz i).eq_or_lt with he | hl + · simp [he] + · exact value_drain hμ (hth i hl) (Nat.cast_le.mpr hl.le) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Local tensor substitution rates + +Strict comparisons can first be made with a separate rational rate at +each spectral point. A finite subcover and a common denominator replace +all these rates by integer powers with the same number of demands. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing + +open scoped NNReal + +private theorem round_rate {a b p q : ℝ} (ha : 0 ≤ a) (hb : 0 < b) + (hp : 0 ≤ p) (h : a * p < b * q) : + ∃ d n : ℕ, 0 < d ∧ (d : ℝ) * a < n * b ∧ (n : ℝ) * p < d * q := by + have gap : 0 < q - a / b * p := by + rw [sub_pos, div_mul_eq_mul_div, div_lt_iff₀ hb, mul_comm q] + exact h + obtain ⟨d, hd⟩ := exists_nat_gt (p / (q - a / b * p)) + have hd0 : 0 < d := Nat.cast_pos.mp ((div_nonneg hp gap.le).trans_lt hd) + rw [div_lt_iff₀ gap] at hd + let n := ⌊(d : ℝ) * (a / b)⌋₊ + 1 + refine ⟨d, n, hd0, ?_, ?_⟩ + · rw [← div_lt_iff₀ hb, mul_div_assoc] + simpa only [n, Nat.cast_add, Nat.cast_one] using Nat.lt_floor_add_one ((d : ℝ) * (a / b)) + · have hn : (n : ℝ) ≤ (d : ℝ) * (a / b) + 1 := by + simp only [n, Nat.cast_add, Nat.cast_one] + exact add_le_add_left (Nat.floor_le (by positivity)) _ + calc + _ ≤ ((d : ℝ) * (a / b) + 1) * p := mul_le_mul_of_nonneg_right hn hp + _ < _ := by linarith + +open Spectral + +variable {K S I : Type} [Field K] [Fintype S] + +private structure Offer (price : I → ℝ) (L : ℝ) where + good : I + demand : ℕ + supply : ℕ + positive : 0 < demand + cheaper : (supply : ℝ) * price good < (demand : ℝ) * L + +/-- The supplies can be raised to powers strictly cheaper than a common +power of the demand, yet at each spectral point some supply is worth more. -/ +theorem finite_offers (D : Tensor K S) (T : I → Tensor K S) + (p : I → ℝ) (hp : ∀ i, 0 ≤ p i) {L : ℝ} + (hD : 1 ≤ D) + (gap : ∀ v : Tensor K S →+* ℝ≥0, Monotone v → + ∃ i, 1 < v (T i) ∧ Real.log (v D) * p i < Real.log (v (T i)) * L) : + ∃ (J : Type) (_ : Fintype J) (b : ℕ) (t : J → I) (n : J → ℕ), + 0 < b ∧ (∀ j, (n j : ℝ) * p (t j) < (b : ℝ) * L) ∧ + ∀ v : Tensor K S →+* ℝ≥0, Monotone v → ∃ j, v D ^ b < v (T (t j)) ^ n j := by + classical + let U (o : Offer p L) : Set (Tensor K S → ℝ≥0) := + {v | v (D ^ o.demand) < v (T o.good ^ o.supply)} + have ho (o) : IsOpen (U o) := isOpen_lt (continuous_apply _) (continuous_apply _) + have hu : Spectrum.points (Tensor K S) ⊆ ⋃ o, U o := by + rintro _ ⟨v, hv, rfl⟩ + obtain ⟨i, hi, hg⟩ := gap v hv + have hd' : (1 : ℝ) ≤ v D := by exact_mod_cast (show 1 ≤ v D by simpa using hv hD) + have hi' : (1 : ℝ) < v (T i) := hi + obtain ⟨d, n, hd, hdn, hc⟩ := + round_rate (Real.log_nonneg hd') (Real.log_pos hi') (hp i) hg + refine Set.mem_iUnion.mpr ⟨⟨i, d, n, hd, hc⟩, ?_⟩ + change v (D ^ d) < v (T i ^ n) + rw [map_pow, map_pow, ← NNReal.coe_lt_coe, NNReal.coe_pow, NNReal.coe_pow, + ← Real.log_lt_log_iff (by positivity) (by positivity), Real.log_pow, Real.log_pow] + exact hdn + obtain ⟨s, hs⟩ := (Spectrum.compact_points Tensor.exists_bound).elim_finite_subcover U ho hu + let b := ∏ o ∈ s, o.demand + have hb : 0 < b := Finset.prod_pos fun o _ => o.positive + have each (j : s) : ∃ m, b = j.val.demand * m := + Finset.dvd_prod_of_mem (fun o => o.demand) j.property + choose m hm using each + have hm0 (j : s) : 0 < m j := by rw [hm j] at hb; exact Nat.pos_of_mul_pos_left hb + refine ⟨s, inferInstance, b, fun j => j.val.good, fun j => j.val.supply * m j, + hb, fun j => ?_, fun v hv => ?_⟩ + · rw [hm j, Nat.cast_mul, Nat.cast_mul, mul_right_comm, mul_right_comm _ (m j : ℝ)] + exact mul_lt_mul_of_pos_right j.val.cheaper (Nat.cast_pos.mpr (hm0 j)) + · obtain ⟨o, hos, hov⟩ := Set.mem_iUnion₂.mp (hs ⟨v, hv, rfl⟩) + change v (D ^ o.demand) < v (T o.good ^ o.supply) at hov + rw [map_pow, map_pow] at hov + let j : s := ⟨o, hos⟩ + refine ⟨j, ?_⟩ + rw [hm j, pow_mul, pow_mul] + exact pow_lt_pow_left₀ hov zero_le (hm0 j).ne' + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# A failed price test gives a strict spectral margin + +Rescale each positive demand value to the total proposed price. Unless a +supply then exceeds its cap, every demand must be at its cap, contradicting +the failed test. A positive-price link handles zero demand values. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Spectral +open scoped NNReal + +variable {K S I : Type} [Field K] [Fintype S] [Nonempty S] + +/-- A spectral test with demand coordinates marked for equality. -/ +def Consistent (T : I → Tensor K S) (p : I → ℝ) (s : Finset I) : Prop := + ∃ (d : ℝ) (v : Tensor K S →+* ℝ), 0 ≤ d ∧ Monotone v ∧ + (∀ i, Tensor.values d v (T i) ≤ p i) ∧ ∀ i ∈ s, Tensor.values d v (T i) = p i + +private theorem prod_unit_le (T : I → Tensor K S) (hT : ∀ i, T i ≠ 0) (s : Finset I) : + 1 ≤ ∏ i ∈ s, T i := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi ih => + rw [Finset.prod_insert hi] + refine (Tensor.one_le _ (hT i)).trans ?_ + have hh := Tensor.mul_le_mul_left _ _ (T i) ih + rw [mul_one] at hh + exact hh + +theorem failed_offers (T : I → Tensor K S) (hT : ∀ i, T i ≠ 0) + (p : I → ℝ) (hp : ∀ i, 0 ≤ p i) (s : Finset I) (hL : 0 < ∑ i ∈ s, p i) + (hpos : ∀ v : Tensor K S →+* ℝ, Monotone v → ∃ i, 1 < v (T i)) + (hfail : ¬ Consistent T p s) : + ∃ (J : Type) (_ : Fintype J) (b : ℕ) (t : J → I) (n : J → ℕ), + 0 < b ∧ (∀ j, (n j : ℝ) * p (t j) < (b : ℝ) * (∑ i ∈ s, p i)) ∧ + ∀ v : Tensor K S →+* ℝ≥0, Monotone v → + ∃ j, v (∏ i ∈ s, T i) ^ b < v (T (t j)) ^ n j := by + classical + let D := ∏ i ∈ s, T i + let L := ∑ i ∈ s, p i + have hD := prod_unit_le T hT s + apply finite_offers D T p hp hD + intro v hv + let f := NNReal.toRealHom.comp v + have hf : Monotone f := hv + change ∃ i, (1 : ℝ) < f (T i) ∧ Real.log (f D) * p i < Real.log (f (T i)) * L + have hD0 : 0 ≤ Real.log (f D) := Real.log_nonneg (by simpa only [map_one] using hf hD) + rcases hD0.eq_or_lt with he | hg + · obtain ⟨i, hi⟩ := hpos f hf + exact ⟨i, hi, by rw [← he, zero_mul]; exact mul_pos (Real.log_pos hi) hL⟩ + let d := (L / Real.log (f D)) * Real.log 2 + have hd : 0 < d := mul_pos (div_pos hL hg) (Real.log_pos (by norm_num)) + have value i : Tensor.values d f (T i) = Real.log (f (T i)) * L / Real.log (f D) := by + unfold Tensor.values d + field_simp + have ht i : 1 ≤ f (T i) := Tensor.value_one_le hf (hT i) + have total : ∑ i ∈ s, Tensor.values d f (T i) = ∑ i ∈ s, p i := by + simp only [value, div_eq_mul_inv, ← Finset.sum_mul] + rw [← Real.log_prod (fun i _ => (zero_lt_one.trans_le (ht i)).ne'), ← map_prod] + rw [← div_eq_mul_inv] + exact mul_div_cancel_left₀ _ hg.ne' + have bad : ¬ ∀ i, Tensor.values d f (T i) ≤ p i := by + intro hall + exact hfail ⟨d, f, hd.le, hf, hall, + (Finset.sum_eq_sum_iff_of_le (fun i _ => hall i)).mp total⟩ + push Not at bad + obtain ⟨i, hi⟩ := bad + rw [value, lt_div_iff₀ hg, mul_comm (p i)] at hi + have hlog : 0 < Real.log (f (T i)) := + pos_of_mul_pos_left ((mul_nonneg hg.le (hp i)).trans_lt hi) hL.le + exact ⟨i, (Real.log_pos_iff (zero_lt_one.trans_le (ht i)).le).mp hlog, hi⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end + +/- +# Counting and pricing stock + +Stocks are counts indexed by commodity. Collecting a list of orders by +commodity changes neither its tensor product nor the total price. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Stock + +open Finset + +variable {I J : Type} {S : Type*} [Fintype I] [Fintype J] [CommMonoid S] + +/-- The product of `T i ^ z i` indexed by `i`. -/ +def bundle (T : I → S) (z : I → ℕ) : S := ∏ i, T i ^ z i + +/-- The sum of `(z i : ℝ) * p i` indexed by `i`. -/ +def total (p : I → ℝ) (z : I → ℕ) : ℝ := ∑ i, (z i : ℝ) * p i + +/-- The sum of `n j` indexed by `j ∈ univ.filter (fun j => g j = i)`. -/ +def collect [DecidableEq I] (g : J → I) (n : J → ℕ) (i : I) : ℕ := + ∑ j ∈ univ.filter (fun j => g j = i), n j + +theorem bundle_add (T : I → S) (x y : I → ℕ) : + bundle T (fun i => x i + y i) = bundle T x * bundle T y := by + simp only [bundle, pow_add, prod_mul_distrib] + +theorem total_add (p : I → ℝ) (x y : I → ℕ) : + total p (fun i => x i + y i) = total p x + total p y := by + simp only [total, Nat.cast_add, add_mul, sum_add_distrib] + +theorem bundle_sum (T : I → S) (z : J → I → ℕ) (n : J → ℕ) : + bundle T (fun i => ∑ j, z j i * n j) = ∏ j, bundle T (z j) ^ n j := by + simp only [bundle, ← prod_pow_eq_pow_sum, pow_mul, ← prod_pow] + exact prod_comm + +theorem total_sum (p : I → ℝ) (z : J → I → ℕ) (n : J → ℕ) : + total p (fun i => ∑ j, z j i * n j) = ∑ j, total p (z j) * n j := by + simp only [total, Nat.cast_sum, Nat.cast_mul, sum_mul] + rw [sum_comm] + exact sum_congr rfl fun j _ => sum_congr rfl fun i _ => by ring + +variable [DecidableEq I] + +theorem bundle_collect (T : I → S) (g : J → I) (n : J → ℕ) : + bundle T (collect g n) = bundle (T ∘ g) n := by + rw [bundle, bundle, ← prod_fiberwise univ g] + apply prod_congr rfl + intro i _ + rw [collect, ← prod_pow_eq_pow_sum] + exact prod_congr rfl fun j hj => by simp [(mem_filter.mp hj).2] + +theorem total_collect (p : I → ℝ) (g : J → I) (n : J → ℕ) : + total p (collect g n) = total (p ∘ g) n := by + rw [total, total, ← sum_fiberwise univ g] + apply sum_congr rfl + intro i _ + rw [collect, Nat.cast_sum, sum_mul] + exact sum_congr rfl fun j hj => by simp [(mem_filter.mp hj).2] + +/-- Returns `n` when `i ∈ u` holds, and `0` otherwise. -/ +def copies (u : Finset I) (n : ℕ) (i : I) : ℕ := if i ∈ u then n else 0 + +theorem bundle_copies (T : I → S) (u : Finset I) (n : ℕ) : + bundle T (copies u n) = (∏ i ∈ u, T i) ^ n := by + simp [bundle, copies, apply_ite, prod_pow] + +theorem total_copies (p : I → ℝ) (u : Finset I) (n : ℕ) : + total p (copies u n) = n * ∑ i ∈ u, p i := by + simp [total, copies, apply_ite, ite_mul, mul_sum] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Stock +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/Defs.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/Defs.lean new file mode 100644 index 0000000000..1a1ff7af4c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/Defs.lean @@ -0,0 +1,71 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Wide +public import Mathlib.LinearAlgebra.Dimension.Finrank +public import Mathlib.RingTheory.Finiteness.Defs + +/-! +# The two compression scales + +A wide network counts stations and all their ports. A trivalent network +counts stations and exposed ports. Tables of arity above three must come +from a finite dictionary. The stages may use different dictionary limits +but must all work over the same field. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent +open Filter + +/-- Trivalent size of an exact tensor power with independent exterior bits. -/ +def PowerSize {F : Type} [Field F] {a b : Wire} (k : Val a → Val b → F) (d m : ℕ) : Prop := + ∃ v, Net F (copies a d) (copies b d) (power k d) v ∧ m = v + d * (wd a + wd b) + +/-- Uniform savings per copy for powers of networks with bounded initial size. -/ +def Compresses (F : Type) [Field F] : Prop := + ∀ η : ℝ, 0 < η → ∃ γ : ℝ, 0 < γ ∧ ∀ κ : ℝ, 0 < κ → + ∀ᶠ n : ℕ in atTop, ∀ (a b : Wire) (k : Val a → Val b → F) (v : ℕ), + Net F a b k v → + let e := wd a + wd b + let m := v + e + let h : ℝ := Nat.clog 2 n + n ≤ e → (m : ℝ) ≤ (n : ℝ) ^ (21 / 20 : ℝ) → + ∃ d m' : ℕ, 1 ≤ d ∧ (d : ℝ) ≤ (n : ℝ) ^ κ ∧ PowerSize k d m' ∧ + (m' : ℝ) ≤ d * ((m : ℝ) * h ^ (-γ) + (e : ℝ) * h ^ η) + +/-- A station and port count with at most `B` distinct high-arity labels. -/ +def Labeled {K : Type} [Field K] {a b : Wire} (k : Val a → Val b → K) + (B s u : ℕ) : Prop := + ∃ L : Finset (Table K), L.card ≤ B ∧ Wide K u (↑L) a b k s + +/-- One reduction step for a table network with bounded arity and label count. -/ +def ArityStep (K : Type) [Field K] (n B B' : ℕ) (b δ a ξ : ℝ) : Prop := + let h : ℝ := Nat.clog 2 n + ∀ (x y : Wire) (k : Val x → Val y → K) (s u M : ℕ), + Labeled k B s u → (u : ℝ) ≤ h ^ b → + s ≤ M → n ≤ M → (M : ℝ) ≤ (n : ℝ) ^ (11 / 10 : ℝ) → + ((wd x + wd y : ℕ) : ℝ) ≤ M * h ^ (-(2 * a)) → + ∃ r s' u' : ℕ, 1 ≤ r ∧ (r : ℝ) ≤ (n : ℝ) ^ ξ ∧ + Labeled (power k r) B' s' u' ∧ + (s' : ℝ) ≤ (M : ℝ) * r * h ^ (-((1 - δ) * a)) ∧ + (u' : ℝ) ≤ h ^ (b + (1 + δ) * a) + +/-- Only finitely many arity exponents are needed for a fixed saving. The +field and label limits are chosen before the starting network. -/ +def ArityReduction (F : Type) [Field F] : Prop := + ∀ δ β : ℝ, 0 < δ → δ ≤ 1 / 10 → 0 < β → β ≤ 1 / 2 → + ∃ α : ℝ, 0 < α ∧ ∀ (a : ℝ) (J : ℕ), 0 < a → a < α → 0 < J → + β + (1 + δ) * a * J ≤ 1 / 2 → ∀ ξ : ℝ, 0 < ξ → ∃ C : ℝ, 0 < C ∧ + ∀ᶠ n : ℕ in atTop, ∃ (K : Type) (_ : Field K) (_ : Algebra F K) + (_ : Module.Finite F K) (B : ℕ → ℕ), + (Module.finrank F K : ℝ) ≤ C * Real.log (Nat.clog 2 n) ∧ + ∀ j : ℕ, j < J → ArityStep K n (B j) (B (j + 1)) (β + (1 + δ) * a * j) δ a ξ + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/Design.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/Design.lean new file mode 100644 index 0000000000..9ac4ce2cc4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/Design.lean @@ -0,0 +1,389 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.FieldStage +public import Mathlib.Analysis.SpecificLimits.Normed + +/-! +# Iteration budgets + +Work with exponents of two throughout. A grouping of `2^r` blocks +consumes exactly `r` bits of the block index. After `s j` such +groupings there are `2^(M l)` blocks, each descended from stacks +of `2^t` independent copies. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Shaving +open Filter + +private theorem round_up (x : ℝ) (hx : 0 ≤ x) (k : ℕ) : + (2 : ℝ) ^ (x * k) ≤ (2 : ℝ) ^ (k*⌈x⌉₊) ∧ (2 : ℝ) ^ (k*⌈x⌉₊) ≤ (2 : ℝ) ^ k * (2 : ℝ) ^ (x * k) + := by + rw [← Real.rpow_natCast 2 (k*⌈x⌉₊), Nat.cast_mul, ← Real.rpow_natCast 2 k, + ← Real.rpow_add (by norm_num)] + have lo := mul_le_mul_of_nonneg_right (Nat.le_ceil x) (Nat.cast_nonneg k) + have hi := mul_le_mul_of_nonneg_right (Nat.ceil_lt_add_one hx).le (Nat.cast_nonneg k) + constructor <;> exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + +/-- Set `G=2^g`, `q=2^p`. Choose a round count `j`, stack exponent `t` +and height exponent `l`. The final bound covers the complete replication +cost with group exponent `c(j+1)`, uniformly before seeing any input. -/ +theorem stage_parameters (g p c s M : ℕ) (hg : 0 < g) (a b δ ξ : ℝ) + (ha : 0 < a) (ha' : a ≤ 1) (hb : 0 < b) (hb' : b ≤ 1) + (hp : (p : ℝ) ≤ g * (1 + δ / 3)) (hξ : 0 < ξ) : + ∀ᶠ n : ℕ in atTop, + let h : ℝ := Nat.clog 2 n + ∃ j t l : ℕ, 0 < j ∧ h ≤ (2 : ℝ) ^ l ∧ (2 : ℝ) ^ l ≤ 2 * h ∧ + h ^ b ≤ (2 : ℝ) ^ t ∧ (2 : ℝ) ^ t ≤ 2 * h ^ b ∧ + h ^ a ≤ (2 : ℝ) ^ (g * j) ∧ (2 : ℝ) ^ (g * j) ≤ (2 : ℝ) ^ g * h ^ a ∧ + (2 : ℝ) ^ (p * j) ≤ (2 : ℝ) ^ p * h ^ ((1 + δ / 3) * a) ∧ + (2 : ℝ) ^ (c * (j + 1)) ≤ (2 : ℝ) ^ (2 * c) * h ^ (c * a) ∧ + (2 : ℝ) ^ (t + M * l + c * (j + 1) * (s * j)) ≤ (n : ℝ) ^ ξ := by + let K := 2 + 1 / Real.log 2 + let C := (1 + M + c * s : ℝ) * K ^ 2 + have hlog : 0 < Real.log 2 := by positivity + have hk : 1 ≤ K := by unfold K; linarith [one_div_pos.mpr hlog] + filter_upwards [tendsto_height.eventually_gt_atTop 1, + (Real.tendsto_log_atTop.comp tendsto_height).eventually_ge_atTop 1, + tendsto_height.eventually (cost_le C (by norm_num : (0 : ℝ) < 1 / 2)), + batch_le hξ] with n hh hl hpoly hbatch + let h : ℝ := Nat.clog 2 n + change 1 < h at hh + change 1 ≤ Real.log h at hl + let x := Real.log h / Real.log 2 + have hx : 0 < x := div_pos (by linarith) hlog + have he : (2 : ℝ) ^ x = h := by + unfold x + rw [Real.rpow_def_of_pos (by norm_num), mul_div_cancel₀ _ hlog.ne', Real.exp_log (by linarith)] + have bound (u : ℝ) (hu : 0 ≤ u) (k : ℕ) : + h ^ (u * k) ≤ (2 : ℝ) ^ (k*⌈x * u⌉₊) ∧ (2 : ℝ) ^ (k*⌈x * u⌉₊) ≤ (2 : ℝ) ^ k * h ^ (u * k) + := by + rw [← he, ← Real.rpow_mul (by norm_num), ← mul_assoc] + exact round_up _ (mul_nonneg hx.le hu) k + let v := a / g + have hgr : (0 : ℝ) < g := Nat.cast_pos.mpr hg + have hv : 0 < v := div_pos ha hgr + have hva : v ≤ a := div_le_self ha.le (by exact_mod_cast hg) + have hvg : v * g = a := div_mul_cancel₀ _ hgr.ne' + let l := ⌈x * 1⌉₊ + let t := ⌈x * b⌉₊ + let j := ⌈x * v⌉₊ + have hj : 0 < j := Nat.ceil_pos.mpr (mul_pos hx hv) + have hL : h ≤ (2 : ℝ) ^ l ∧ (2 : ℝ) ^ l ≤ 2 * h := by simpa [l] using bound 1 zero_le_one 1 + have hT : h ^ b ≤ (2 : ℝ) ^ t ∧ (2 : ℝ) ^ t ≤ 2 * h ^ b := by simpa [t] using bound b hb.le 1 + have hG := bound v hv.le g + rw [hvg] at hG + refine ⟨j, t, l, hj, hL.1, hL.2, hT.1, hT.2, hG.1, hG.2, ?_, ?_, ?_⟩ + · refine (bound v hv.le p).2.trans (mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow_of_exponent_le hh.le ?_) (by positivity)) + have := mul_le_mul_of_nonneg_left hp hv.le + rwa [← mul_assoc, hvg, mul_comm a] at this + · have hc : v * c ≤ (c : ℝ) * a := by + rw [mul_comm]; exact mul_le_mul_of_nonneg_left hva (Nat.cast_nonneg _) + calc + _ = (2 : ℝ) ^ c * (2 : ℝ) ^ (c * j) := by rw [← pow_add]; congr 1; ring + _ ≤ (2 : ℝ) ^ c * ((2 : ℝ) ^ c * h ^ ((c : ℝ) * a)) := by + apply mul_le_mul_of_nonneg_left _ (by positivity) + exact (bound v hv.le c).2.trans (mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow_of_exponent_le hh.le hc) (by positivity)) + _ = _ := by rw [← mul_assoc, ← pow_add, ← two_mul] + · let H := K * Real.log h + have hH : 1 ≤ H := one_le_mul_of_one_le_of_one_le hk hl + have small (u : ℝ) (hu : 0 ≤ u) (hu' : u ≤ 1) : (⌈x * u⌉₊:ℝ) + 1 ≤ H := by + have := Nat.ceil_lt_add_one (mul_nonneg hx.le hu) + have hxu := mul_le_mul_of_nonneg_left hu' hx.le + have hH' : H = 2 * Real.log h + x := by unfold H K x; ring + linarith + have hsq : H ≤ H ^ 2 := by nlinarith + have ht' : (t : ℝ) ≤ H ^ 2 := by linarith [small b hb.le hb'] + have hl' : (l : ℝ) ≤ H ^ 2 := by linarith [small 1 zero_le_one le_rfl] + have hj' : (j : ℝ) + 1 ≤ H := small v hv.le (hva.trans ha') + apply hbatch + refine le_trans ?_ hpoly + push_cast + change (t : ℝ) + M * l + c * (j + 1) * (s * j) ≤ C * (Real.log h) ^ 2 + calc + _ ≤ H ^ 2 + M * H ^ 2 + c * H * (s * H) := by gcongr; linarith + _ = _ := by unfold C H; ring + +/-- Choose the exponent controlling all group sizes before the height +is known. The factor `C^(j+1)` covers growth in host occurrences. -/ +theorem group_exponent (C G q ε : ℝ) (hC : 1 ≤ C) (hG : 1 ≤ G) (hq : 1 ≤ q) + (hε : 0 < ε) (r₀ : ℝ) : + ∃ c : ℕ, ∀ i j : ℕ, i ≤ j → + r₀ ≤ (2 : ℝ) ^ (c * (j + 1)) ∧ C ^ (j + 1) * (q * G) ^ i ≤ ε * (2 : ℝ) ^ (c * (j + 1)) := by + let B := C * (q * G) + have hqG := one_le_mul_of_one_le_of_one_le hq hG + have hB : 1 ≤ B := one_le_mul_of_one_le_of_one_le hC hqG + have ht := tendsto_pow_atTop_atTop_of_one_lt (by norm_num : (1 : ℝ) < 2) + obtain ⟨c, hc, hr, hd⟩ := ((ht.eventually_ge_atTop B).and + ((ht.eventually_ge_atTop r₀).and (ht.eventually_ge_atTop (B / ε)))).exists + refine ⟨c, fun i j hij => ?_⟩ + rw [pow_mul] + have hb := hB.trans hc + constructor + · exact hr.trans (by simpa using pow_le_pow_right₀ hb (by omega : 1 ≤ j + 1)) + · calc + _ ≤ B ^ (j + 1) := by + rw [show B = C * (q * G) by rfl, mul_pow C] + exact mul_le_mul_of_nonneg_left + (pow_le_pow_right₀ hqG (hij.trans (Nat.le_succ _))) (by positivity) + _ = B ^ j * B := pow_succ _ _ + _ ≤ ((2 : ℝ) ^ c) ^ j * ((2 : ℝ) ^ c * ε) := + mul_le_mul (pow_le_pow_left₀ (by positivity) hc j) + ((div_le_iff₀ hε).mp hd) (by positivity) (by positivity) + _ = _ := by rw [pow_succ]; ring + +/-- Check both admission conditions of round `i`. Here `A` counts all +allocated occurrences at the current grouping step and `T,L` are the +initial scale and total width budget. -/ +theorem iteration_slack {D G q C L T A m d h a e ε r : ℝ} {i j : ℕ} + (hD : 0 < D) (hG : 1 ≤ G) (hq : 1 ≤ q) (hh : 0 < h) + (dr : 0 < r) (hm : 0 ≤ m) (hd : 0 ≤ d) (hij : i ≤ j) + (initial : m * d ≤ L) (allocated : A * T ≤ C ^ (j + 1) * L) + (steps : G ^ j ≤ G * h ^ a) (height : D * G ≤ h ^ a) + (group : C ^ (j + 1) * (q * G) ^ i ≤ ε * r) (exterior : e ≤ m * h ^ (-(2 * a))) : + A * (T * q ^ i) / r ≤ ε * (L / G ^ i) ∧ e * d ≤ (L / G ^ i) / D := by + have hL : 0 ≤ L := (mul_nonneg hm hd).trans initial + have hg : 0 < G ^ i := pow_pos (zero_lt_one.trans_le hG) _ + constructor + · rw [← mul_div_assoc, div_le_div_iff₀ dr hg] + calc + _ = (A * T) * (q * G) ^ i := by rw [mul_pow]; ring + _ ≤ (C ^ (j + 1) * L) * (q * G) ^ i := mul_le_mul_of_nonneg_right allocated (by positivity) + _ = L * (C ^ (j + 1) * (q * G) ^ i) := by ring + _ ≤ L * (ε * r) := mul_le_mul_of_nonneg_left group hL + _ = _ := by ring + · rw [le_div_iff₀ hD, le_div_iff₀ hg] + have hcap : D * G ^ i ≤ h ^ (2 * a) := calc + _ ≤ D * (G * h ^ a) := mul_le_mul_of_nonneg_left ((pow_le_pow_right₀ hG hij).trans steps) + hD.le + _ ≤ h ^ a * h ^ a := by + rw [← mul_assoc] + exact mul_le_mul_of_nonneg_right height (by positivity) + _ = _ := by rw [← Real.rpow_add hh, ← two_mul] + calc + _ = (e * d) * (D * G ^ i) := by ring + _ ≤ (m * h ^ (-(2 * a)) * d) * h ^ (2 * a) := + mul_le_mul (mul_le_mul_of_nonneg_right exterior hd) hcap (by positivity) (by positivity) + _ = m * d := by rw [mul_right_comm m, mul_assoc, ← Real.rpow_add hh]; simp + _ ≤ _ := initial + +end MatrixMultiplicationAllFields.MatrixExponent.Shaving +end + +section +/- +# Volume and arity at the end of a stage + +The iteration saves `h^a` in total width. Split the logarithmic slack +`aδ` between the descriptions, the cost of realizing the transcript, and +the remaining constant factors. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Shaving +open Filter + +/-- Any fixed power of the logarithm fits in any positive power budget. -/ +theorem polylog_le (C : ℝ) (r : ℕ) {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ h : ℝ in atTop, C * (Real.log h) ^ r ≤ h ^ ε := by + have hl := (isLittleO_log_rpow_rpow_atTop r hε).const_mul_left C + filter_upwards [eventually_ge_atTop 0, hl.eventuallyLE] with h hh ht + rw [Real.rpow_natCast, Real.norm_of_nonneg (Real.rpow_nonneg hh ε)] at ht + exact (le_abs_self _).trans ht + +/-- Quasipolynomial work in the height uses at most `1/h` of a linear +input-size budget. -/ +theorem assembly_remainder (C : ℝ) (r : ℕ) : + ∀ᶠ n : ℕ in atTop, let h : ℝ := Nat.clog 2 n + (2 : ℝ) ^ (C * (Real.log h) ^ r) * h ≤ n := by + filter_upwards [tendsto_height.eventually_gt_atTop 1, + tendsto_height.eventually (polylog_le (3*|C|) r (by norm_num : (0 : ℝ) < 1 / 2)), + tendsto_height.eventually (polylog_le (3 / Real.log 2) 1 (by norm_num : (0 : ℝ) < 1 / 2)), + (tendsto_rpow_atTop (by norm_num : (0 : ℝ) < 1 / 2) |>.comp tendsto_height).eventually_ge_atTop + 3, + batch_le (by norm_num : (0 : ℝ) < 1)] with n hh h₁ h₂ h₃ hb + let h : ℝ := Nat.clog 2 n + change 1 < h at hh + change 3*|C| * (Real.log h) ^ r ≤ h ^ (1 / 2 : ℝ) at h₁ + change 3 / Real.log 2 * (Real.log h) ^ 1 ≤ h ^ (1 / 2 : ℝ) at h₂ + change 3 ≤ h ^ (1 / 2 : ℝ) at h₃ + let x := |C| * (Real.log h) ^ r + Real.log h / Real.log 2 + have hlog : 0 < Real.log h := Real.log_pos hh + have hx : 0 ≤ x := by unfold x; positivity + have he : (2 : ℝ) ^ (Real.log h / Real.log 2) = h := by + rw [Real.rpow_def_of_pos (by norm_num), mul_div_cancel₀ _ (by positivity), + Real.exp_log (by linarith)] + have hsmall : (⌈x⌉₊:ℝ) ≤ h ^ (1 / 2 : ℝ) := by + refine (Nat.ceil_lt_add_one hx).le.trans ?_ + unfold x + simp only [pow_one, div_eq_mul_inv] at h₂ ⊢ + linarith + calc + _ ≤ (2 : ℝ) ^ x := by + unfold x + rw [Real.rpow_add (by norm_num), he] + exact mul_le_mul_of_nonneg_right (Real.rpow_le_rpow_of_exponent_le (by norm_num) + (mul_le_mul_of_nonneg_right (le_abs_self C) (by positivity))) (by positivity) + _ ≤ (2 : ℝ)^⌈x⌉₊ := by + rw [← Real.rpow_natCast] + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (Nat.le_ceil _) + _ ≤ _ := by simpa only [Real.rpow_one] using hb _ hsmall + +/-- `P` is the processor count, `V` the record volume, `m` the input size, +`S` the initial block count and `d` the replication factor. The five volume +terms are common work, short control, terminal payloads, exposed bits, +and the subpolynomial additive error. -/ +theorem assembly_saving {h m S d K P V size arity a b C C₀ C₂ M δ : ℝ} + (hh : 1 ≤ h) (hm : 0 ≤ m) (hS : 0 ≤ S) (hd : S * h ^ b ≤ d) + (hK : 0 ≤ K) (ha : 0 ≤ a) (ha' : a ≤ 1) (hδ : 0 < δ) + (hC : C * a + 2 * a ≤ b) (h₀ : C₀ ≤ M) (h₂ : C₂ ≤ M) : + let τ := a * δ / 3 + 7 * K ≤ h ^ τ → + P ≤ m * S * h ^ (C * a + τ) / h ^ M → + V ≤ P * h ^ C₂ + m * S * h ^ (C * a + τ) + m * d * h ^ (-a + τ) + m * d * h ^ (-(2 * a) + τ) + + m * d / h → + size ≤ K * (P * h ^ C₀ + V * h ^ τ + m * d / h) → + arity ≤ K * (h ^ (b + (1 + δ / 3) * a) + h ^ (C * a + τ)) → + size ≤ m * d * h ^ (-((1 - δ) * a)) ∧ arity ≤ h ^ (b + (1 + δ) * a) := by + intro τ large processors volume work key + have ht : 0 ≤ τ := by unfold τ; positivity + have hh' : 0 < h := zero_lt_one.trans_le hh + have hd' : 0 ≤ d := (mul_nonneg hS (by positivity)).trans hd + let z := m * d * h ^ (-a + τ) + have hz : 0 ≤ z := by unfold z; positivity + have ctrl : m * S * h ^ (C * a + τ) ≤ z := calc + _ ≤ m * S * h ^ (b + (-a + τ)) := + mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hh (by linarith)) (by positivity) + _ = m * (S * h ^ b) * h ^ (-a + τ) := by rw [Real.rpow_add hh']; ring + _ ≤ _ := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hd hm) (by positivity) + have setup (r : ℝ) (hr : r ≤ M) : P * h ^ r ≤ z := calc + _ ≤ (m * S * h ^ (C * a + τ) / h ^ M) * h ^ r + := mul_le_mul_of_nonneg_right processors (by positivity) + _ ≤ (m * S * h ^ (C * a + τ) / h ^ M) * h ^ M := + mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hh hr) (by positivity) + _ ≤ _ := by rw [div_mul_cancel₀ _ (by positivity)]; exact ctrl + have ext : m * d * h ^ (-(2 * a) + τ) ≤ z := + mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hh (by linarith)) (by positivity) + have rem : m * d / h ≤ z := by + rw [div_eq_mul_inv, ← Real.rpow_neg_one] + exact mul_le_mul_of_nonneg_left (Real.rpow_le_rpow_of_exponent_le hh (by linarith)) (by + positivity) + have hV : V ≤ 5 * z := by + change V ≤ _ + _ + z + _ + _ at volume + linarith [setup C₂ h₂] + have hτ : 1 ≤ h ^ τ := Real.one_le_rpow hh ht + constructor + · calc + _ ≤ K * (P * h ^ C₀ + V * h ^ τ + m * d / h) := work + _ ≤ 7 * K * z * h ^ τ := by + have hvol := mul_le_mul_of_nonneg_right hV (by positivity : 0 ≤ h ^ τ) + have hx := le_mul_of_one_le_right hz hτ + have := mul_le_mul_of_nonneg_left + (show P * h ^ C₀ + V * h ^ τ + m * d / h ≤ 7 * z * h ^ τ by linarith [setup C₀ h₀]) hK + linarith + _ ≤ h ^ τ * z * h ^ τ := by gcongr + _ = _ := by + rw [show -((1 - δ) * a) = τ + (-a + τ) + τ by unfold τ; ring, + Real.rpow_add hh', Real.rpow_add hh'] + unfold z; ring + · let e := b + (1 + δ / 3) * a + have hx : C * a + τ ≤ e := by unfold e τ; linarith + have hinc : h ^ (C * a + τ) ≤ h ^ e := Real.rpow_le_rpow_of_exponent_le hh hx + calc + _ ≤ K * (h ^ e + h ^ (C * a + τ)) := key + _ ≤ K * (h ^ e + h ^ e) := by gcongr + _ = (2 * K) * h ^ e := by ring + _ ≤ h ^ τ * h ^ e := mul_le_mul_of_nonneg_right (by linarith) (by positivity) + _ ≤ _ := by + rw [← Real.rpow_add hh'] + apply Real.rpow_le_rpow_of_exponent_le hh + unfold e τ at * + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Shaving +end + +section +/- +# Dyadic parameters of one round + +Write `D = 2^d`, `G = 2^g`, `q = 2^p`. Run exactly `2g` beats. +Any fixed power of the logarithm of `D` fits into both `G` and `q/G`. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Shaving +open Filter + +private theorem absorbs_power (K : ℝ) (r : ℕ) : + ∀ᶠ t : ℕ in atTop, K * (t : ℝ) ^ r ≤ (2 : ℝ) ^ t := by + have h := (isLittleO_pow_const_const_pow_of_one_lt (R := ℝ) r + (by norm_num : (1 : ℝ) < 2)).const_mul_left K + filter_upwards [h.eventuallyLE] with t ht + exact (le_abs_self _).trans (by simpa using ht) + +/-- The beat multiplier and all logarithmic losses are independent of +`D`. The lower cutoff on its logarithm is arbitrary. -/ +theorem choose_round {δ : ℝ} (hδ : 0 < δ) (hδ' : δ ≤ 1) (B K : ℝ) + (hK : 0 ≤ K) (r d₀ : ℕ) : + ∃ d g p : ℕ, d₀ ≤ d ∧ 0 < g ∧ 100 * g ≤ d ∧ + B ^ (2 * g) ≤ ((2 : ℝ) ^ d) ^ (1 / 100 : ℝ) ∧ + (g : ℝ) * (1 + δ / 4) ≤ p ∧ (p : ℝ) ≤ g * (1 + δ / 3) ∧ + 2 * K * (1 + d) ^ r ≤ (2 : ℝ) ^ g ∧ 2 * K * (1 + d) ^ r * (2 : ℝ) ^ g ≤ (2 : ℝ) ^ p := by + let e := ⌈3 / δ⌉₊ + have he : 0 < e := Nat.ceil_pos.mpr (by positivity) + have he₁ : 3 ≤ (e : ℝ) * δ := (div_le_iff₀ hδ).mp (Nat.le_ceil _) + have he₂ : (e : ℝ) * δ ≤ 4 := by + have := mul_le_mul_of_nonneg_right + (Nat.ceil_lt_add_one (by positivity : 0 ≤ 3 / δ)).le hδ.le + rw [add_mul, div_mul_cancel₀ _ hδ.ne', one_mul] at this + exact this.trans (by linarith) + obtain ⟨b, hb, hB⟩ := ((eventually_gt_atTop 0).and + ((tendsto_pow_atTop_atTop_of_one_lt (by norm_num : (1 : ℝ) + < 2)).eventually_ge_atTop (B ^ 2))).exists + let f := 100 * b * e + obtain ⟨t, ht, hpoly⟩ := ((eventually_gt_atTop d₀).and + (absorbs_power (2 * K * (1 + f) ^ r) r)).exists + let g := e * t + let d := f * t + let p := g + t + have htg : t ≤ g := Nat.le_mul_of_pos_left _ he + have hd : d = 100 * (b * g) := by simp [d, f, g, mul_assoc] + have hgd : 100 * g ≤ d := by rw [hd]; exact Nat.mul_le_mul_left _ (Nat.le_mul_of_pos_left _ hb) + have hc : 2 * K * (1 + d) ^ r ≤ (2 : ℝ) ^ t := by + refine le_trans ?_ hpoly + rw [mul_assoc (2 * K), ← mul_pow] + gcongr + have : (1 : ℝ) ≤ t := by exact_mod_cast (show 1 ≤ t by omega) + simp only [d, Nat.cast_mul] + linarith + refine ⟨d, g, p, by omega, by omega, hgd, ?_, ?_, ?_, ?_, ?_⟩ + · rw [pow_mul] + calc + _ ≤ ((2 : ℝ) ^ b) ^ g := pow_le_pow_left₀ (sq_nonneg B) hB _ + _ = _ := by + rw [← pow_mul, ← Real.rpow_natCast_mul (by norm_num), ← Real.rpow_natCast 2 (b * g), hd] + congr 1 + push_cast + ring + · have := mul_le_mul_of_nonneg_right he₂ (Nat.cast_nonneg t) + simp only [p, g, Nat.cast_add, Nat.cast_mul] + linarith + · have := mul_le_mul_of_nonneg_right he₁ (Nat.cast_nonneg t) + simp only [p, g, Nat.cast_add, Nat.cast_mul] + linarith + · exact hc.trans (pow_le_pow_right₀ (by norm_num) htg) + · rw [show p = t + g by simp [p, add_comm], pow_add] + exact mul_le_mul_of_nonneg_right hc (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Shaving +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/FieldStage.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/FieldStage.lean new file mode 100644 index 0000000000..df5ae455fb --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/FieldStage.lean @@ -0,0 +1,186 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import Mathlib.Data.Nat.Log +public import Mathlib.FieldTheory.Finite.Extension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Defs + +/-! Logarithmic costs and subpolynomial batch sizes in the compression theorem. -/ + +@[expose] public section + +section + +open Filter + +namespace MatrixMultiplicationAllFields.MatrixExponent.Shaving + +theorem tendsto_height : Tendsto (fun n : ℕ => (Nat.clog 2 n : ℝ)) atTop atTop := by + have h : Tendsto (Nat.clog 2) atTop atTop := by + refine tendsto_atTop.2 fun k => ?_ + filter_upwards [eventually_gt_atTop (2 ^ k)] with n hn + exact ((Nat.lt_clog_iff_pow_lt (by decide)).2 hn).le + exact tendsto_natCast_atTop_atTop.comp h + +/-- Tables with arity bounded by the square root of the height fit into +batches of size at most any fixed positive power of the input size. -/ +theorem batch_le {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ n : ℕ in atTop, ∀ u : ℕ, (u : ℝ) ≤ (Nat.clog 2 n : ℝ) ^ (1 / 2 : ℝ) → + (2 : ℝ) ^ u ≤ (n : ℝ) ^ ε := by + filter_upwards [eventually_gt_atTop 1, tendsto_height.eventually_ge_atTop 2, + (Real.tendsto_sqrt_atTop.comp tendsto_height).eventually_ge_atTop (2 / ε)] + with n hn hh hs u hu + let H := Nat.clog 2 n + change 2 / ε ≤ Real.sqrt H at hs + have hpred : (H.pred : ℝ) = (H : ℝ) - 1 := by + rw [Nat.pred_eq_sub_one, Nat.cast_sub (Nat.clog_pos (by decide) hn), Nat.cast_one] + have hstep : (u : ℝ) ≤ (H.pred : ℝ) * ε := by + rw [hpred] + calc + (u : ℝ) ≤ Real.sqrt H := by simpa only [Real.sqrt_eq_rpow] using hu + _ ≤ (H : ℝ) / 2 * ε := by + have hx := mul_le_mul_of_nonneg_left ((div_le_iff₀ hε).1 hs) (Real.sqrt_nonneg H) + rw [← mul_assoc, Real.mul_self_sqrt (by positivity)] at hx + linarith + _ ≤ ((H : ℝ) - 1) * ε := mul_le_mul_of_nonneg_right (by linarith) hε.le + calc + (2 : ℝ) ^ u = (2 : ℝ) ^ (u : ℝ) := (Real.rpow_natCast _ _).symm + _ ≤ (2 : ℝ) ^ ((H.pred : ℝ) * ε) := Real.rpow_le_rpow_of_exponent_le (by norm_num) hstep + _ = ((2 : ℝ) ^ H.pred) ^ ε := by rw [Real.rpow_mul (by norm_num), Real.rpow_natCast] + _ ≤ _ := by + apply Real.rpow_le_rpow (by positivity) _ hε.le + exact_mod_cast (Nat.pow_pred_clog_lt_self 2 hn).le + +theorem cost_le (C : ℝ) {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ h : ℝ in atTop, C * (Real.log h) ^ 2 ≤ h ^ ε := by + have hl := (isLittleO_log_rpow_rpow_atTop 2 hε).const_mul_left C + filter_upwards [eventually_ge_atTop 0, hl.eventuallyLE] with h hh hle + rw [Real.rpow_two, Real.norm_of_nonneg (Real.rpow_nonneg hh ε)] at hle + exact (le_abs_self _).trans hle + +end MatrixMultiplicationAllFields.MatrixExponent.Shaving +end + +/- +# A single finite extension for all width scales + +A fixed extension for the local identities must embed into the working +field. Rounding a target cardinality up to a power of its order gives +both the polynomial upper bound and the logarithmic degree bound. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Shaving +open Filter + +theorem extension (F L : Type) [Field F] [Field L] [Finite L] [Algebra F L] (A : ℕ) : + ∃ C : ℝ, 0 < C ∧ ∀ᶠ h : ℕ in atTop, + ∃ (K : Type) (_ : Field K) (_ : Fintype K) (_ : Algebra L K) (_ : Algebra F K) + (_ : IsScalarTower F L K) (_ : Module.Finite F K), + A * (1 + h ^ 4) ^ A ≤ Fintype.card K ∧ Fintype.card K ≤ h ^ (5 * A + 2) ∧ + (Module.finrank F K : ℝ) ≤ C * Real.log h := by + let Q := Nat.card L + have hQ : 1 < Q := Finite.one_lt_card + let B := 5 * A + 1 + let C := (Module.finrank F L : ℝ) * (B + 1) / Real.log Q + have hlog : 0 < Real.log (Q : ℝ) := Real.log_pos (by exact_mod_cast hQ) + have : Module.Finite F L := Module.Finite.of_finite + have hdim : 0 < Module.finrank F L := Module.finrank_pos + refine ⟨C, by unfold C; positivity, ?_⟩ + filter_upwards [eventually_ge_atTop A, eventually_ge_atTop Q] with h hA hq + have hh : 1 < h := hQ.trans_le hq + have hb : 0 < B := by dsimp [B]; omega + have hl : 1 < h ^ B := Nat.one_lt_pow hb.ne' hh + let n := Nat.clog Q (h ^ B) + have hn : 0 < n := Nat.clog_pos hQ hl + have : NeZero n := ⟨hn.ne'⟩ + let p := ringChar L + have : Fact p.Prime := ⟨CharP.char_is_prime L p⟩ + let K := FiniteField.Extension L p n + let : Fintype K := Fintype.ofFinite _ + let : Algebra F K := Algebra.compHom K (algebraMap F L) + have : IsScalarTower F L K := IsScalarTower.of_algebraMap_eq (fun _ => rfl) + have hc : Fintype.card K = Q ^ n := by + rw [← Nat.card_eq_fintype_card] + exact FiniteField.natCard_extension L p n + have hlo : h ^ B ≤ Q ^ n := Nat.le_pow_clog hQ _ + have hhi : Q ^ n ≤ h ^ (B + 1) := by + rw [show n = n.pred + 1 from (Nat.succ_pred_eq_of_pos hn).symm, pow_succ, pow_succ] + exact Nat.mul_le_mul (Nat.pow_pred_clog_lt_self Q hl).le hq + refine ⟨K, inferInstance, inferInstance, inferInstance, inferInstance, inferInstance, + Module.Finite.of_finite, ?_, by rwa [hc], ?_⟩ + · rw [hc] + have hp : 1 + h ^ 4 ≤ h ^ 5 := by + rw [show h ^ 5 = h * h ^ 4 by ring] + have := Nat.mul_le_mul_right (h ^ 4) hh + have := Nat.one_le_pow 4 h (by omega) + omega + calc + _ ≤ h * (h ^ 5) ^ A := Nat.mul_le_mul hA (Nat.pow_le_pow_left hp A) + _ = h ^ B := by unfold B; rw [pow_succ' h (5 * A), pow_mul] + _ ≤ _ := hlo + · have he : (Q : ℝ) ^ n ≤ (h : ℝ) ^ (B + 1 : ℕ) := by exact_mod_cast hhi + have hd := Real.log_le_log (by positivity) he + rw [Real.log_pow, Real.log_pow, Nat.cast_add, Nat.cast_one] at hd + rw [← Module.finrank_mul_finrank F L K, Nat.cast_mul, + show Module.finrank L K = n from FiniteField.finrank_extension L p n] + calc + _ ≤ (Module.finrank F L : ℝ) * ((B + 1) * Real.log h / Real.log Q) := + mul_le_mul_of_nonneg_left ((le_div_iff₀ hlog).mpr hd) (by positivity) + _ = _ := by unfold C; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Shaving +end + +section +/- +# Keeping the working field fixed across stages + +Only a finite progression of width exponents is used. Uniformity of +a cutoff in the continuum of possible exponents is unnecessary. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Shaving +open Filter + +/-- Enough names to include any polynomial-sized dictionary. -/ +def dictionary (n : ℕ) := 2 ^ ((Nat.clog 2 (Nat.clog 2 n)) ^ 2) + +/-- One stage, uniformly over fields in the permitted size window. -/ +def UniformStage (F : Type) [Field F] : Prop := + ∀ δ β : ℝ, 0 < δ → δ ≤ 1 / 10 → 0 < β → β ≤ 1 / 2 → + ∃ (α : ℝ) (A : ℕ) (L : Type) (_ : Field L) (_ : Finite L) (_ : Algebra F L), + 0 < α ∧ ∀ a b ξ : ℝ, 0 < a → a < α → β ≤ b → b ≤ 1 / 2 → 0 < ξ → + ∀ᶠ n : ℕ in atTop, ∀ (K : Type) [Field K] [Fintype K] [Algebra L K] + [Algebra F K] [IsScalarTower F L K], let h := Nat.clog 2 n + A * (1 + h ^ 4) ^ A ≤ Fintype.card K → Fintype.card K ≤ h ^ (5 * A + 2) → + ArityStep K n (dictionary n) (dictionary n) b δ a ξ + +theorem UniformStage.reduction {F : Type} [Field F] (step : UniformStage F) : + ArityReduction F := by + intro δ β hd hd' hb hb' + obtain ⟨α, A, L, _, _, _, hα, hs⟩ := step δ β hd hd' hb hb' + refine ⟨α, hα, ?_⟩ + intro a J ha ha' _ hJ ξ hx + have hs' (j : Fin J) := hs a (β + (1 + δ) * a * j.val) ξ ha ha' + (le_add_of_nonneg_right (by positivity)) (le_trans (by gcongr; exact j.isLt.le) hJ) hx + obtain ⟨C, hC, he⟩ := extension F L A + have ht : Tendsto (Nat.clog 2) atTop atTop := by + apply tendsto_atTop.2 + intro B + filter_upwards [tendsto_height.eventually_ge_atTop (B : ℝ)] with n hn + exact_mod_cast hn + refine ⟨C, hC, ?_⟩ + filter_upwards [ht.eventually he, eventually_all.mpr hs'] with n hf hu + obtain ⟨K, _, _, _, _, _, _, hlo, hhi, hdeg⟩ := hf + exact ⟨K, inferInstance, inferInstance, inferInstance, fun _ => dictionary n, hdeg, + fun j hj => hu ⟨j, hj⟩ K hlo hhi⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Shaving +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/Network.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/Network.lean new file mode 100644 index 0000000000..267828ee39 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Shaving/Network.lean @@ -0,0 +1,390 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.FieldStage +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Lookup.Network +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network.Matrix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Distinctness + +/-! +# Quantitative reduction of trivalent compression to stages and lookup + +`R j d s u` describes the intermediate realization after `j` stages, +with `d` copies, size `s` counting stations and ports, and arity at most +`u`. It can track the admissible table dictionary at each stage. +`T d m` describes a trivalent realization over the original field. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Shaving +open Filter + +/-- One arity reduction with an integer size budget. -/ +def Stage (R : ℕ → ℕ → ℕ → ℕ → Prop) (n e J : ℕ) (β δ a ξ : ℝ) : Prop := + let h : ℝ := Nat.clog 2 n + ∀ j d s u M : ℕ, j < J → 1 ≤ d → R j d s u → + (u : ℝ) ≤ h ^ (β + (1 + δ) * a * j) → + s ≤ M → n ≤ M → (M : ℝ) ≤ (n : ℝ) ^ (11 / 10 : ℝ) → + (d : ℝ) * e ≤ M * h ^ (-(2 * a)) → + ∃ r s' u' : ℕ, 1 ≤ r ∧ (r : ℝ) ≤ (n : ℝ) ^ ξ ∧ R (j + 1) (d * r) s' u' ∧ + (s' : ℝ) ≤ (M : ℝ) * r * h ^ (-((1 - δ) * a)) ∧ + (u' : ℝ) ≤ h ^ (β + (1 + δ) * a * (j + 1)) + +/-- Batch lookup followed by descent from a degree `O(log h)` extension. -/ +def Finish (T : ℕ → ℕ → Prop) (R : ℕ → ℕ → ℕ → ℕ → Prop) (n J : ℕ) + (ρ C : ℝ) : Prop := + let h : ℝ := Nat.clog 2 n + ∀ d s u : ℕ, 1 ≤ d → R J d s u → + ∃ m : ℕ, T (d * 2 ^ u) m ∧ + (m : ℝ) ≤ C * (Real.log h) ^ 2 * (2 : ℝ) ^ u * s * (1 + (u : ℝ)) ^ ρ + +/-- In the large-cost case the descending size envelope leaves enough +room for every exterior bit, even after rounding down. -/ +private theorem budget {m n e d h η x a : ℝ} (hn : 1 ≤ n) (hne : n ≤ e) + (hd : 1 ≤ d) (hh : 1 ≤ h) (hm : e * h ^ η ≤ m) + (ha : 0 ≤ a) (hx : 0 ≤ x) (hs : 2 * a + x ≤ η) + (hm' : m ≤ n ^ (21 / 20 : ℝ)) (hd' : d ≤ n ^ (1 / 40 : ℝ)) + (hfour : 4 ≤ n ^ (1 / 40 : ℝ)) : + let M := ⌊4 * m * d * h ^ (-x)⌋₊ + n ≤ (M : ℝ) ∧ (M : ℝ) ≤ n ^ (11 / 10 : ℝ) ∧ d * e ≤ M * h ^ (-(2 * a)) := by + have he : 1 ≤ e := hn.trans hne + have hm₀ : 0 ≤ m := le_trans (by positivity) hm + have hh₀ : 0 < h := zero_lt_one.trans_le hh + have hn₀ : 0 < n := zero_lt_one.trans_le hn + let z := d * e * h ^ (2 * a) + have hnz : n ≤ z := calc + n ≤ e := hne + _ ≤ d * e := le_mul_of_one_le_left (by positivity) hd + _ ≤ z := le_mul_of_one_le_right (by positivity) (Real.one_le_rpow hh (by positivity)) + have hz : z ≤ m * d * h ^ (-x) := by + rw [Real.rpow_neg hh₀.le, ← div_eq_mul_inv, le_div_iff₀ (by positivity)] + calc + z * h ^ x = d * (e * h ^ (2 * a + x)) := by + rw [Real.rpow_add hh₀]; unfold z; ring + _ ≤ d * (e * h ^ η) := by gcongr + _ ≤ m * d := by rw [mul_comm m]; gcongr + let M := ⌊4 * m * d * h ^ (-x)⌋₊ + have hzM : z ≤ (M : ℝ) := by + have hf : 4 * m * d * h ^ (-x) < (M : ℝ) + 1 := Nat.lt_floor_add_one _ + linarith + refine ⟨hnz.trans hzM, ?_, ?_⟩ + · calc + (M : ℝ) ≤ 4 * m * d * h ^ (-x) := Nat.floor_le (by positivity) + _ ≤ 4 * m * d := mul_le_of_le_one_right (by positivity) + (Real.rpow_le_one_of_one_le_of_nonpos hh (neg_nonpos.mpr hx)) + _ ≤ n ^ (1 / 40 : ℝ) * n ^ (21 / 20 : ℝ) * n ^ (1 / 40 : ℝ) := by gcongr + _ = n ^ (11 / 10 : ℝ) := by rw [← Real.rpow_add hn₀, ← Real.rpow_add hn₀]; norm_num + · change d * e ≤ (M : ℝ) * h ^ (-(2 * a)) + rw [Real.rpow_neg hh₀.le, ← div_eq_mul_inv, le_div_iff₀ (by positivity)] + exact hzM + +private theorem stages {R : ℕ → ℕ → ℕ → ℕ → Prop} {n m e J : ℕ} + {β δ a ξ η : ℝ} (ha : 0 < a) (hd : δ ≤ 1) (hξ : 0 < ξ) + (hroom : 2 * a + (1 - δ) * a * J ≤ η) (hcard : ξ * J ≤ 1 / 40) + (hn : 1 ≤ n) (hne : n ≤ e) (hfour : 4 ≤ (n : ℝ) ^ (1 / 40 : ℝ)) + (hm : (m : ℝ) ≤ (n : ℝ) ^ (21 / 20 : ℝ)) + (hinit : ∃ s u : ℕ, R 0 1 s u ∧ s ≤ 4 * m ∧ u ≤ 3) + (hstage : Stage R n e J β δ a ξ) : + let h : ℝ := Nat.clog 2 n + 1 ≤ h → 3 ≤ h ^ β → (e : ℝ) * h ^ η ≤ m → + ∃ d s u : ℕ, 1 ≤ d ∧ (d : ℝ) ≤ (n : ℝ) ^ (ξ * J) ∧ R J d s u ∧ + (s : ℝ) ≤ 4 * m * d * h ^ (-((1 - δ) * a * J)) ∧ + (u : ℝ) ≤ h ^ (β + (1 + δ) * a * J) := by + intro h hh hthree he + have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast hn + have hn₀ : 0 < (n : ℝ) := zero_lt_one.trans_le hn₁ + have hh₀ : 0 < h := zero_lt_one.trans_le hh + let x := (1 - δ) * a + suffices ∀ j : ℕ, j ≤ J → ∃ d s u : ℕ, + 1 ≤ d ∧ (d : ℝ) ≤ (n : ℝ) ^ (ξ * j) ∧ R j d s u ∧ + (s : ℝ) ≤ 4 * m * d * h ^ (-(x * j)) ∧ + (u : ℝ) ≤ h ^ (β + (1 + δ) * a * j) from this J le_rfl + intro j hj + induction j with + | zero => + obtain ⟨s, u, hR, hs, hu⟩ := hinit + refine ⟨1, s, u, le_rfl, by simp, hR, ?_, ?_⟩ + · simpa using (by exact_mod_cast hs : (s : ℝ) ≤ 4 * m) + · simpa using (show (u : ℝ) ≤ 3 by exact_mod_cast hu).trans hthree + | succ j ih => + have hj' : j ≤ J := Nat.le_of_succ_le hj + obtain ⟨d, s, u, hd₁, hdj, hR, hs, hu⟩ := ih hj' + have hξj : ξ * j ≤ 1 / 40 := + (mul_le_mul_of_nonneg_left (by exact_mod_cast hj') hξ.le).trans hcard + have hd' := hdj.trans (Real.rpow_le_rpow_of_exponent_le hn₁ hξj) + have hroom' : 2 * a + x * j ≤ η := by + apply le_trans _ hroom + change 2 * a + x * j ≤ 2 * a + x * J + gcongr + let M := ⌊4 * (m : ℝ) * d * h ^ (-(x * j))⌋₊ + obtain ⟨hnM, hM, heM⟩ := budget hn₁ (by exact_mod_cast hne) (by exact_mod_cast hd₁) + hh he ha.le (by positivity) hroom' hm hd' hfour + obtain ⟨r, s', u', hr, hr', hR', hs', hu'⟩ := + hstage j d s u M hj hd₁ hR hu (Nat.le_floor hs) (Nat.cast_le.mp hnM) hM heM + refine ⟨d * r, s', u', Nat.mul_pos hd₁ hr, ?_, hR', ?_, by simpa using hu'⟩ + · rw [Nat.cast_succ, mul_add, mul_one, Real.rpow_add hn₀, Nat.cast_mul] + exact mul_le_mul hdj hr' (by positivity) (by positivity) + · have hM' : (M : ℝ) ≤ 4 * m * d * h ^ (-(x * j)) := Nat.floor_le (by positivity) + calc + _ ≤ (M : ℝ) * r * h ^ (-x) := hs' + _ ≤ (4 * m * d * h ^ (-(x * j))) * r * h ^ (-x) := by gcongr + _ = 4 * m * (d * r : ℕ) * h ^ (-(x * (j.succ : ℝ))) := by + rw [Nat.cast_succ, Nat.cast_mul, mul_add, mul_one, neg_add, Real.rpow_add hh₀] + ring + +private theorem lookup_cost {s u m d : ℕ} {C h ρ γ x b : ℝ} + (hh : 1 ≤ h) (hC : 0 < C) (hρ : 0 < ρ) (hb : 0 ≤ b) + (hs : (s : ℝ) ≤ 4 * m * d * h ^ (-x)) (hu : (u : ℝ) ≤ h ^ b) + (hcost : (4 * (2 : ℝ) ^ ρ * C) * (Real.log h) ^ 2 ≤ h ^ γ) + (hgap : 2 * γ = x - b * ρ) : + C * (Real.log h) ^ 2 * (2 : ℝ) ^ u * s * (1 + (u : ℝ)) ^ ρ ≤ + (d * 2 ^ u : ℕ) * ((m : ℝ) * h ^ (-γ)) := by + have hh₀ : 0 < h := zero_lt_one.trans_le hh + have hu' : (1 + (u : ℝ)) ^ ρ ≤ (2 : ℝ) ^ ρ * h ^ (b * ρ) := by + rw [Real.rpow_mul hh₀.le, ← Real.mul_rpow (by norm_num) (by positivity)] + apply Real.rpow_le_rpow (by positivity) _ hρ.le + linarith [Real.one_le_rpow hh hb] + calc + _ ≤ C * (Real.log h) ^ 2 * (2 : ℝ) ^ u * (4 * m * d * h ^ (-x)) * + ((2 : ℝ) ^ ρ * h ^ (b * ρ)) := by gcongr + _ = (d * 2 ^ u : ℕ) * (m : ℝ) * h ^ (-x + b * ρ) * + ((4 * (2 : ℝ) ^ ρ * C) * (Real.log h) ^ 2) := by + rw [Real.rpow_add hh₀]; push_cast; ring + _ ≤ (d * 2 ^ u : ℕ) * (m : ℝ) * h ^ (-x + b * ρ) * h ^ γ := by gcongr + _ = _ := by + rw [mul_assoc, ← Real.rpow_add hh₀, show -x + b * ρ + γ = -γ by linarith, mul_assoc] + +/-- All parameters except the power bound are fixed before the replication +slack `κ` is specified. The cutoff for `n` is uniform in the input tensor. -/ +theorem shave {ρ η : ℝ} (hρ : 0 < ρ) (hρ' : ρ < 1) (hη : 0 < η) : + ∃ γ δ β : ℝ, 0 < γ ∧ 0 < δ ∧ δ ≤ 1 / 10 ∧ 0 < β ∧ β ≤ 1 / 2 ∧ + ∀ α : ℝ, 0 < α → ∃ (a : ℝ) (J : ℕ), 0 < a ∧ a < α ∧ 0 < J ∧ + β + (1 + δ) * a * J ≤ 1 / 2 ∧ + ∀ κ : ℝ, 0 < κ → ∃ ξ : ℝ, 0 < ξ ∧ ∀ C : ℝ, 0 < C → + ∀ᶠ n : ℕ in atTop, ∀ (m e : ℕ) (T : ℕ → ℕ → Prop) (R : ℕ → ℕ → ℕ → ℕ → Prop), + n ≤ e → (m : ℝ) ≤ (n : ℝ) ^ (21 / 20 : ℝ) → T 1 m → + (∃ s u : ℕ, R 0 1 s u ∧ s ≤ 4 * m ∧ u ≤ 3) → + Stage R n e J β δ a ξ → Finish T R n J ρ C → + ∃ d m' : ℕ, 1 ≤ d ∧ (d : ℝ) ≤ (n : ℝ) ^ κ ∧ T d m' ∧ + let h : ℝ := Nat.clog 2 n + (m' : ℝ) ≤ d * ((m : ℝ) * h ^ (-γ) + (e : ℝ) * h ^ η) := by + let δ := (1 - ρ) / 10 + have hd : 0 < δ := by dsimp [δ]; linarith + have hd' : δ ≤ 1 / 10 := by dsimp [δ]; linarith + let A := min 1 η / 8 + have hA : 0 < A := by unfold A; positivity + have hA₁ : A ≤ 1 / 8 := by dsimp [A]; linarith [min_le_left 1 η] + have hAη : 3 * A ≤ η := by dsimp [A]; linarith [min_le_right 1 η] + let β := δ * A + let b := β + (1 + δ) * A + let x := (1 - δ) * A + let γ := (x - b * ρ) / 2 + have hβ : 0 < β := mul_pos hd hA + have hβb : β ≤ b := le_add_of_nonneg_right (by positivity) + have hb : b ≤ 1 / 2 := by + unfold b β + nlinarith + have hgap : 2 * γ = x - b * ρ := by unfold γ; ring + have hγ : 0 < γ := by + have hw : 0 < 1 - δ - (1 + 2 * δ) * ρ := by + have : δ * ρ ≤ δ := mul_le_of_le_one_right hd.le hρ'.le + unfold δ at * + linarith + apply half_pos + convert mul_pos hw hA using 1 + unfold x b β + ring + refine ⟨γ, δ, β, hγ, hd, hd', hβ, hβb.trans hb, ?_⟩ + intro α hα + obtain ⟨J, hJ⟩ := exists_nat_gt (A / α) + have hJ₀ : 0 < (J : ℝ) := lt_trans (by positivity) hJ + have hJ₁ : 1 ≤ J := Nat.cast_pos.mp hJ₀ + let a := A / J + have ha : 0 < a := div_pos hA hJ₀ + have ha' : a < α := (div_lt_iff₀ hJ₀).2 (by linarith [(div_lt_iff₀ hα).1 hJ]) + have haA : a ≤ A := div_le_self hA.le (by exact_mod_cast hJ₁) + have hAJ : a * J = A := div_mul_cancel₀ _ hJ₀.ne' + have hxJ : (1 - δ) * a * J = x := by rw [mul_assoc, hAJ] + have hbJ : β + (1 + δ) * a * J = b := by rw [mul_assoc, hAJ] + have hroom : 2 * a + (1 - δ) * a * J ≤ η := by + rw [hxJ] + unfold x + nlinarith + refine ⟨a, J, ha, ha', hJ₁, hbJ.trans_le hb, ?_⟩ + intro κ hκ + let ξ := min (κ / 2) (1 / 40) / J + have hξ : 0 < ξ := by unfold ξ; positivity + have hξJ : ξ * J = min (κ / 2) (1 / 40) := div_mul_cancel₀ _ hJ₀.ne' + refine ⟨ξ, hξ, ?_⟩ + intro C hC + have hfour : ∀ᶠ n : ℕ in atTop, 4 ≤ (n : ℝ) ^ (1 / 40 : ℝ) := + ((tendsto_rpow_atTop (by norm_num)).comp tendsto_natCast_atTop_atTop).eventually_ge_atTop 4 + filter_upwards [eventually_ge_atTop 1, tendsto_height.eventually_ge_atTop 1, hfour, + ((tendsto_rpow_atTop hβ).comp tendsto_height).eventually_ge_atTop 3, + batch_le (half_pos hκ), tendsto_height.eventually (cost_le (4 * (2 : ℝ) ^ ρ * C) hγ)] + with n hn hh hf hthree hbatch hcost m e T R hne hm hT hinit hstage hfinish + let h : ℝ := Nat.clog 2 n + have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast hn + -- Small input cost already meets the target without any replication. + by_cases he : (m : ℝ) ≤ e * h ^ η + · refine ⟨1, m, le_rfl, by simpa using Real.one_le_rpow hn₁ hκ.le, hT, ?_⟩ + simp only [Nat.cast_one, one_mul] + exact he.trans (le_add_of_nonneg_left (by positivity)) + obtain ⟨d, s, u, hd₁, hdξ, hR, hs, hu⟩ := + stages ha (by linarith) hξ hroom (hξJ.trans_le (min_le_right _ _)) + hn hne hf hm hinit hstage hh hthree (le_of_not_ge he) + rw [hxJ] at hs + rw [hbJ] at hu + have hdκ := hdξ.trans + (Real.rpow_le_rpow_of_exponent_le hn₁ (hξJ.trans_le (min_le_left _ _))) + have huκ := hbatch u (hu.trans (Real.rpow_le_rpow_of_exponent_le hh hb)) + obtain ⟨m', hT', hm'⟩ := hfinish d s u hd₁ hR + refine ⟨d * 2 ^ u, m', Nat.mul_pos hd₁ (by positivity), ?_, hT', ?_⟩ + · push_cast + calc + _ ≤ (n : ℝ) ^ (κ / 2) * (n : ℝ) ^ (κ / 2) := + mul_le_mul hdκ huκ (by positivity) (by positivity) + _ = _ := by rw [← Real.rpow_add (by positivity), add_halves] + · exact (hm'.trans (lookup_cost hh hC hρ (hβ.le.trans hβb) hs hu hcost hgap)).trans + (mul_le_mul_of_nonneg_left (le_add_of_nonneg_right (by positivity)) (by positivity)) + +end MatrixMultiplicationAllFields.MatrixExponent.Shaving +end + +section +/- +# From wide networks to compression + +Packing, substitution and field descent preserve the exterior labels. +The same field is used throughout each sequence of arity reductions. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent +open Filter + +variable {F K : Type} [Field F] [Field K] {x y : Wire} + +private theorem Labeled.join {k : Val x → Val y → K} {d r B s u : ℕ} + (h : Labeled (power (power k d) r) B s u) : Labeled (power k (d * r)) B s u := by + obtain ⟨L, hL, h⟩ := h + obtain ⟨f, hf, ef⟩ := (Rewire.joinCopies x d r).inverse + obtain ⟨g, hg, eg⟩ := (Rewire.joinCopies y d r).inverse + have he : (fun a b => power (power k d) r (f a) (g b)) = power k (d * r) := by + funext a b + rw [← power_join, (ef _ a).mpr rfl, (eg _ b).mpr rfl] + exact ⟨L, hL, he ▸ (h.pre hf).post hg⟩ + +private theorem stages {n J : ℕ} {B : ℕ → ℕ} {β δ a ξ : ℝ} + (h : ∀ j : ℕ, j < J → ArityStep K n (B j) (B (j + 1)) (β + (1 + δ) * a * j) δ a ξ) + (k : Val x → Val y → K) : + Shaving.Stage (fun j d s u => Labeled (power k d) (B j) s u) + n (wd x + wd y) J β δ a ξ := by + intro j d s u M hj _ hk hu hs hn hM he + obtain ⟨r, s', u', hr, hr', hnet, hsize, hmax⟩ := + h j hj _ _ _ s u M hk hu hs hn hM (by simpa only [wd_copies, ← Nat.mul_add, Nat.cast_mul] + using he) + refine ⟨r, s', u', hr, hr', hnet.join, hsize, ?_⟩ + rwa [show β + (1 + δ) * a * (j + 1) = (β + (1 + δ) * a * j) + (1 + δ) * a by ring] + +private theorem map_power (f : F →+* K) (k : Val x → Val y → F) (d : ℕ) : + power (fun a b => f (k a b)) d = fun a b => f (power k d a b) := by + induction d with + | zero => simp [power] + | succ d ih => funext a b; simp only [power, map_mul, ih] + +-- Include exposed bits in the cost of the network after descent. +private theorem finish_cost {u s e d v v' D : ℕ} {A C H ρ : ℝ} + (hA : 1 ≤ A) (hρ : 0 ≤ ρ) (hd : 1 ≤ D) (hD : (D : ℝ) ≤ C * Real.log H) + (hs : d * e ≤ s) (hv : (v : ℝ) ≤ A * (2 : ℝ) ^ u * s * (1 + (u : ℝ)) ^ ρ) + (hv' : v' ≤ 288 * D ^ 2 * v) : + ((v' + d * 2 ^ u * e : ℕ) : ℝ) ≤ + 289 * A * C ^ 2 * (Real.log H) ^ 2 * (2 : ℝ) ^ u * s * (1 + (u : ℝ)) ^ ρ := by + let X := A * (2 : ℝ) ^ u * s * (1 + (u : ℝ)) ^ ρ + have hX : 0 ≤ X := by unfold X; positivity + have hrp : 1 ≤ (1 + (u : ℝ)) ^ ρ := Real.one_le_rpow (by simp) hρ + have hbits : ((d * 2 ^ u * e : ℕ) : ℝ) ≤ X := by + have hde : (d : ℝ) * e ≤ s := by exact_mod_cast hs + push_cast + calc + _ = 1 * (2 : ℝ) ^ u * (d * (e : ℝ)) * 1 := by ring + _ ≤ X := by unfold X; gcongr + have hd' : 1 ≤ (D : ℝ) ^ 2 := one_le_pow₀ (by exact_mod_cast hd) + have hv'' : (v' : ℝ) ≤ 288 * (D : ℝ) ^ 2 * v := by exact_mod_cast hv' + rw [Nat.cast_add] + calc + _ ≤ 288 * (D : ℝ) ^ 2 * X + (D : ℝ) ^ 2 * X := + add_le_add (hv''.trans (mul_le_mul_of_nonneg_left hv (by positivity))) + (hbits.trans (le_mul_of_one_le_left hX hd')) + _ = 289 * (D : ℝ) ^ 2 * X := by ring + _ ≤ 289 * (C * Real.log H) ^ 2 * X := by gcongr + _ = _ := by unfold X; ring + +/-- Compression of arbitrary tensors specializes to the independent lists. -/ +theorem Compresses.lists (h : Compresses F) : Compression (Realizes F) := by + have ht : Tendsto listBits atTop atTop := + tendsto_atTop_mono (fun w => show w ≤ listBits w by + unfold listBits + have : 1 ≤ 2 ^ w := Nat.one_le_pow w 2 (by decide) + nlinarith) tendsto_id + intro η hη + obtain ⟨γ, hγ, h⟩ := h η hη + refine ⟨γ, hγ, fun κ hκ => ?_⟩ + filter_upwards [ht.eventually (h κ hκ)] with w hw t m ht' hreal hm + obtain ⟨v, hv, rfl⟩ := hreal + specialize hw _ _ _ v hv + simp only [wd_lists, wd, add_zero] at hw + obtain ⟨d, m', hd, hd', ⟨v', hv', heq⟩, hc⟩ := + hw (Nat.le_mul_of_pos_left _ ht') hm + refine ⟨d, m', hd, hd', ⟨v', hv'.power_lists, ?_⟩, ?_⟩ + · simpa only [wd_lists, wd, add_zero, Nat.mul_left_comm, Nat.mul_assoc] using heq + · simpa only [Nat.cast_mul] using hc + +/-- Compression from ordinary-width sorting and one-stage arity reduction. The construction +uses batch lookup and iterates the resulting descent. -/ +theorem compresses_of_stages {p : ℝ} (hp : 1 < p) (hp' : p < 2) + (sort : Lookup.Sorting F p) (reduce : ArityReduction F) : Compresses F := by + obtain ⟨A, hA, lookup⟩ := Lookup.lookup_network hp.le sort + have hρ : 0 < p - 1 := by linarith + intro η hη + obtain ⟨γ, δ, β, hγ, hd, hd', hb, hb', h⟩ := Shaving.shave hρ (by linarith) hη + obtain ⟨α, hα, step⟩ := reduce δ β hd hd' hb hb' + obtain ⟨a, J, ha, ha', hJ, hmax, h⟩ := h α hα + refine ⟨γ, hγ, fun κ hκ => ?_⟩ + obtain ⟨ξ, hξ, h⟩ := h κ hκ + obtain ⟨C, hC, red⟩ := step a J ha ha' hJ hmax ξ hξ + filter_upwards [red, h (289 * A * C ^ 2) (by positivity)] with n hn hh x y k v hv + dsimp only + intro he hm + obtain ⟨K, _, _, _, B, hdeg, hstep⟩ := hn + let e := wd x + wd y + let k' := fun a b => algebraMap F K (k a b) + let R := fun j d s u => Labeled (power k' d) (B j) s u + apply hh (v + e) e (PowerSize k) R he hm + · exact ⟨1 * v, hv.power 1, by simp [e]⟩ + · obtain ⟨s, hs, hw⟩ := ((hv.map (algebraMap F K)).power 1).wide + refine ⟨s, 3, ⟨∅, by simp, ?_⟩, by omega, le_rfl⟩ + simpa only [Finset.coe_empty] using hw + · exact stages hstep k' + · intro d s u _ hnet + obtain ⟨L, _, hw⟩ := hnet + have hw' : d * e ≤ s := by + simpa only [wd_copies, ← Nat.mul_add] using hw.width + obtain ⟨v₁, h₁, cost₁⟩ := lookup K inferInstance inferInstance u _ _ _ _ s hw + have hr := h₁.rewire (Rewire.joinCopies x d (2 ^ u)) (Rewire.joinCopies y d (2 ^ u)) + (power_join k' d (2 ^ u)) + rw [show power k' (d * 2 ^ u) = _ from map_power (algebraMap F K) k _] at hr + obtain ⟨v₂, h₂, cost₂⟩ := hr.descend + exact ⟨v₂ + d * 2 ^ u * e, ⟨v₂, h₂, rfl⟩, + finish_cost hA hρ.le Module.finrank_pos hdeg hw' cost₁ cost₂⟩ + +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Specialization.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Specialization.lean new file mode 100644 index 0000000000..90fb9b9b7a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Specialization.lean @@ -0,0 +1,129 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weights +public import Mathlib.RingTheory.Ideal.Quotient.HasFiniteQuotients.Basic +public import Mathlib.RingTheory.Jacobson.Ring + +/-! +# Specializing a rank decomposition + +A maximal ideal containing the kernel of polynomial evaluation at the +decomposition coefficients preserves all their equations. Over the integers +the residue field is finite. Over a base field it is a finite extension. +-/ + +universe u v + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent + +private theorem int_jacobson : IsJacobsonRing ℤ := by + apply isJacobsonRing_iff_prime_eq.mpr + intro P hP + by_cases hp : P = ⊥ + · subst P + apply bot_unique + intro x hx + change x = 0 + -- The only integer x for which 3x + 1 is a unit is zero. + have hx' : x ∈ Ring.jacobson ℤ := by simpa only [Ideal.jacobson_bot] using hx + have hu := Int.isUnit_iff.mp (Ring.mem_jacobson_iff.mp hx' 3) + omega + · have : P.IsMaximal := Ring.HasFiniteQuotients.maximalOfPrime hp + exact Ideal.jacobson_eq_self_of_isMaximal + +/-- A field finitely generated as a ring is finite. -/ +private theorem finite_field_of_finiteType (k : Type*) [Field k] [Algebra ℤ k] + [Algebra.FiniteType ℤ k] : Finite k := by + cases Subsingleton.elim (inferInstance : Algebra ℤ k) (Ring.toIntAlgebra k) + have := int_jacobson + have := finite_of_finite_type_of_isJacobsonRing ℤ k + let p : Ideal ℤ := (⊥ : Ideal k).under ℤ + have hp : p.IsMaximal := Ideal.isMaximal_under_of_isIntegral_of_isMaximal (⊥ : Ideal k) + have : Finite (ℤ ⧸ p) := Ring.HasFiniteQuotients.finiteQuotient + (Ring.ne_bot_of_isMaximal_of_not_isField hp Int.not_isField) + have : Module.Finite (ℤ ⧸ p) (k ⧸ (⊥ : Ideal k)) := + Module.Finite.of_restrictScalars_finite ℤ _ _ + have : Finite (k ⧸ (⊥ : Ideal k)) := Module.finite_of_finite (ℤ ⧸ p) + exact Finite.of_equiv _ (RingEquiv.quotientBot k).toEquiv + +namespace Rectangle + +/-- Rank witnesses over a field can be realized over a field of finite type +over any base ring mapping into the given field. -/ +theorem finiteTypeWeighted {R : Type u} {K : Type v} [CommRing R] [Field K] + (φ : R →+* K) {i j k r : ℕ} (w : Fin i → Fin j → Fin k → R) + (h : WeightedRankLE (fun a b c => φ (w a b c)) r) : + ∃ (L : Type u) (_ : Field L) (_ : Algebra R L) (_ : Algebra.FiniteType R L), + WeightedRankLE (fun a b c => algebraMap R L (w a b c)) r := by + classical + obtain ⟨a, b, c, habc⟩ := h + let S := MvPolynomial (Fin r × (Pos i k ⊕ Pos k j ⊕ Pos i j)) R + let X (l : Fin r) (x : Pos i k) : S := MvPolynomial.X (l, .inl x) + let Y (l : Fin r) (y : Pos k j) : S := MvPolynomial.X (l, .inr (.inl y)) + let Z (l : Fin r) (z : Pos i j) : S := MvPolynomial.X (l, .inr (.inr z)) + let f : S →+* K := MvPolynomial.eval₂Hom φ + (fun u ↦ Sum.elim (a u.1) (Sum.elim (b u.1) (c u.1)) u.2) + obtain ⟨m, hm, hker⟩ := Ideal.exists_le_maximal (RingHom.ker f) (RingHom.ker_ne_top f) + let : Field (S ⧸ m) := Ideal.Quotient.field m + let g := Ideal.Quotient.mk m + refine ⟨S ⧸ m, inferInstance, inferInstance, inferInstance, + fun l x ↦ g (X l x), fun l y ↦ g (Y l y), fun l z ↦ g (Z l z), ?_⟩ + intro x y z + let t : S := ∑ l : Fin r, X l x * Y l y * Z l z + let d : S := if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then MvPolynomial.C (w x.1 y.2 x.2) else 0 + have hf : f t = f d := by + simpa [t, d, apply_ite f, f, X, Y, Z, S] using habc x y z + have hg : g t = g d := Ideal.Quotient.eq.mpr (hker (by + change f (t - d) = 0 + rw [map_sub, hf, sub_self])) + have hc (a : R) : g (MvPolynomial.C a) = algebraMap R (S ⧸ m) a := rfl + simpa only [t, d, map_sum, map_mul, apply_ite g, hc, map_zero] using hg + +theorem finiteTypeRank {R : Type u} {K : Type v} [CommRing R] [Field K] + (φ : R →+* K) {i j k r : ℕ} (h : RankLE K i j k r) : + ∃ (L : Type u) (_ : Field L) (_ : Algebra R L) (_ : Algebra.FiniteType R L), + RankLE L i j k r := by + obtain ⟨L, _, _, _, hL⟩ := finiteTypeWeighted φ (fun _ _ _ => 1) (by + simpa only [map_one, WeightedRankLE, RankLE, TensorSpectrum.MatrixRank] using h) + exact ⟨L, inferInstance, inferInstance, inferInstance, by + simpa only [map_one, WeightedRankLE, RankLE, TensorSpectrum.MatrixRank] using hL⟩ + +/-- Specialization preserves all three side lengths and the number of summands. -/ +theorem specializeRank {F : Type*} [Field F] {i j k r : ℕ} (h : RankLE F i j k r) : + ∃ (K : Type) (_ : Field K) (_ : Finite K), RankLE K i j k r := by + obtain ⟨K, _, _, _, hK⟩ := finiteTypeRank (Int.castRingHom F) h + exact ⟨K, inferInstance, finite_field_of_finiteType K, hK⟩ + +/-- A rank bound over an arbitrary extension holds over some finite extension. -/ +theorem finiteExtensionRank {F : Type u} {K : Type v} [Field F] [Field K] [Algebra F K] + {i j k r : ℕ} (h : RankLE K i j k r) : + ∃ (L : Type u) (_ : Field L) (_ : Algebra F L) (_ : Module.Finite F L), RankLE L i j k r := by + obtain ⟨L, _, _, _, hL⟩ := finiteTypeRank (algebraMap F K) h + exact ⟨L, inferInstance, inferInstance, finite_of_finite_type_of_isJacobsonRing F L, hL⟩ + +end Rectangle + +theorem finiteTypeRank {R : Type u} {K : Type v} [CommRing R] [Field K] + (φ : R →+* K) {n r : ℕ} (h : RankLE K n r) : + ∃ (L : Type u) (_ : Field L) (_ : Algebra R L) (_ : Algebra.FiniteType R L), + RankLE L n r := + Rectangle.finiteTypeRank φ h + +theorem specializeRank {F : Type*} [Field F] {n r : ℕ} (h : RankLE F n r) : + ∃ (k : Type) (_ : Field k) (_ : Finite k), RankLE k n r := + Rectangle.specializeRank h + +theorem finiteExtensionRank {F : Type u} {K : Type v} [Field F] [Field K] [Algebra F K] + {n r : ℕ} (h : RankLE K n r) : + ∃ (L : Type u) (_ : Field L) (_ : Algebra F L) (_ : Module.Finite F L), RankLE L n r := + Rectangle.finiteExtensionRank h + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/CubeGadget.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/CubeGadget.lean new file mode 100644 index 0000000000..2c543a2a84 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/CubeGadget.lean @@ -0,0 +1,406 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Gadget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place +public import Mathlib.Algebra.Order.BigOperators.Ring.Finset + +/-! # A strict comparison at six sites -/ + +@[expose] public section + +section + +open scoped NNReal + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable (K : Type) [Field K] + +/-- The sites are A, B, C, D, M, N in that order. -/ +def sixPair : Fin 8 → Fin 6 × Fin 6 := + ![(0, 2), (0, 4), (2, 4), (3, 5), (1, 2), (1, 5), (2, 5), (3, 4)] + +/-- The quantity computed by `wire K 0 1 2 * wire K 2 3 2`. -/ +def sixDemand : Tensor K (Fin 6) := wire K 0 1 2 * wire K 2 3 2 + +/-- Computes the six supply by the application `wire K (sixPair i).1 (sixPair i).2 2`. -/ +def sixSupply (i : Fin 8) : Tensor K (Fin 6) := + wire K (sixPair i).1 (sixPair i).2 2 + +private def edge (i : Fin 8) : Finset (Fin 6) := {(sixPair i).1, (sixPair i).2} + +private theorem six_connected : (2 : Tensor K (Fin 6)) ≤ ∏ i, sixSupply K i := by + let covered (U : Finset (Fin 8)) := shared K (U.biUnion edge) 2 ≤ ∏ i ∈ U, sixSupply K i + have extend {U : Finset (Fin 8)} (h : covered U) (i : Fin 8) (s : Fin 6) + (hi : i ∉ U) (hs : s ∈ edge i) (ht : s ∈ U.biUnion edge) : covered (insert i U) := by + unfold covered + rw [Finset.biUnion_insert, Finset.prod_insert hi] + exact (shared_join K hs ht 2).trans (mul_le_mul_left _ _ _ h) + have h0 : covered {0} := by simp [covered, edge, sixSupply, wire] + have h1 := extend h0 1 0 (by decide) (by decide) (by decide) + have h2 := extend h1 4 2 (by decide) (by decide) (by decide) + have h3 := extend h2 5 1 (by decide) (by decide) (by decide) + have h4 := extend h3 3 5 (by decide) (by decide) (by decide) + unfold covered at h4 + rw [show ({3, 5, 4, 1, 0} : Finset (Fin 8)).biUnion edge = Finset.univ by decide, + shared_all, Nat.cast_ofNat] at h4 + let : MulLeftMono (Tensor K (Fin 6)) := ⟨fun c a b h => mul_le_mul_left a b c h⟩ + exact h4.trans (Finset.prod_le_prod_of_subset_of_one_le (Finset.subset_univ _) + (fun _ _ _ => one_le_wire K _ _ (by decide))) + +/-- Equality would put M and N at the midpoint of CD and then both +C and M at the midpoint of AB. All eight supply lengths would vanish. -/ +private theorem six_gap (f : Tensor K (Fin 6) →+* ℝ) (hf : Monotone f) : + ∃ i, f (sixDemand K) < f (sixSupply K i) ^ 4 := by + by_contra! bad + let d := dist f + let l := (d 0 1 + d 2 3) / 4 + have edge_le (i : Fin 8) : d (sixPair i).1 (sixPair i).2 ≤ l := by + have h := bad i + simp only [sixDemand, sixSupply, f.map_mul, price_wire f hf _ _ (n := 2) (by decide), + Nat.cast_ofNat, ← Real.rpow_add (by norm_num : (0 : ℝ) < 2), + ← Real.rpow_mul_natCast (by norm_num : (0 : ℝ) ≤ 2)] at h + have := (Real.rpow_le_rpow_left_iff (by norm_num : (1 : ℝ) < 2)).mp h + unfold l d + linarith + have tri : ∀ a b c, d a c ≤ d a b + d b c := dist_triangle f hf + have sym : ∀ a b, d a b = d b a := dist_comm f + have ac : d 0 2 ≤ l := edge_le 0 + have am : d 0 4 ≤ l := edge_le 1 + have cm : d 2 4 ≤ l := edge_le 2 + have nd : d 5 3 ≤ l := (sym 5 3).le.trans (edge_le 3) + have cb : d 2 1 ≤ l := (sym 2 1).le.trans (edge_le 4) + have nb : d 5 1 ≤ l := (sym 5 1).le.trans (edge_le 5) + have cn : d 2 5 ≤ l := edge_le 6 + have md : d 4 3 ≤ l := (sym 4 3).le.trans (edge_le 7) + have ab : d 0 1 = 2 * l := by + have : 4 * l = d 0 1 + d 2 3 := by unfold l; ring + linarith [tri 0 2 1, tri 2 4 3] + have cd : d 2 3 = 2 * l := by unfold l at ab ⊢; linarith + have mid {a b c x} (hab : d a b = 2 * l) (h₁ : d a c ≤ l) (h₂ : d c b ≤ l) + (h₃ : d a x ≤ l) (h₄ : d x b ≤ l) : d c x = 0 := by + have h (z : Fin 6) (ha : d a z ≤ l) (hb : d z b ≤ l) : + d a z = d a b / 2 ∧ d z b = d a b / 2 := by + constructor <;> linarith [tri a z b] + exact unique_midpoint f hf (h c h₁ h₂).1 (h c h₁ h₂).2 (h x h₃ h₄).1 (h x h₃ h₄).2 + have mn := mid cd cm md cn nd + have mb : d 4 1 ≤ l := by linarith [tri 4 5 1] + have h := mid ab ac cb am mb + have hl : l = 0 := by linarith [tri 2 4 3] + have hu (i : Fin 8) : f (sixSupply K i) = 1 := by + have he := le_antisymm ((edge_le i).trans_eq hl) (dist_nonneg f hf _ _) + unfold d at he + rw [sixSupply, price_wire f hf _ _ (by decide), he, Real.rpow_zero] + have := hf (six_connected K) + simp only [map_ofNat, map_prod, hu, Finset.prod_const_one] at this + norm_num at this + +/-- Two demands can be supplied with strictly fewer than four wires +per block, up to a bounded direct sum independent of the power. -/ +theorem six_site : + ∃ (b C : ℕ) (H : Finset (Fin 8 → ℕ)), 0 < b ∧ (∀ h ∈ H, ∑ i, h i < 4 * b) ∧ + ∀ z : ℕ, 0 < z → sixDemand K ^ (b * z) ≤ + (C : Tensor K (Fin 6)) * ∑ h ∈ H, ∏ i, sixSupply K i ^ (h i * z) := by + refine Spectrum.powered_gadget add_le_add_right mul_le_mul_left zero_le one_le exists_bound + _ _ _ (by decide) (fun _ => one_le_wire K _ _ (by decide)) ?_ (six_connected K) + intro g hg + obtain ⟨i, hi⟩ := six_gap K (NNReal.toRealHom.comp g) (fun a b h => hg h) + exact ⟨i, NNReal.coe_lt_coe.mp hi⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end +end + +/- +# A uniform gap for metric squares + +Placement preserves products and can only lower the price of a direct +sum. Taking powers removes the fixed overhead in the six-site comparison. +Identifying two pairs of sites gives a saving for squares at every scale. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +private theorem remove_factor {x y C : ℝ} (hy : 0 < y) + (h : ∀ z : ℕ, 0 < z → x ^ z ≤ C * y ^ z) : x ≤ y := by + by_contra! bad + obtain ⟨z, hz⟩ := pow_unbounded_of_one_lt (max C 1) ((one_lt_div hy).mpr bad) + have hz' : 0 < z := by + by_contra! hn + rw [Nat.eq_zero_of_le_zero hn, pow_zero] at hz + exact not_lt_of_ge (le_max_right _ _) hz + rw [div_pow] at hz + exact not_lt_of_ge (h z hz') ((lt_div_iff₀ (pow_pos hy z)).mp ((le_max_left C 1).trans_lt hz)) + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] + +private theorem placed_bound + {b C : ℕ} {H : Finset (Fin 8 → ℕ)} (hbudget : ∀ h ∈ H, ∑ i, h i < 4 * b) + (hcomp : ∀ z : ℕ, 0 < z → sixDemand K ^ (b * z) ≤ + (C : Tensor K (Fin 6)) * ∑ h ∈ H, ∏ i, sixSupply K i ^ (h i * z)) + (f : Tensor K S →+* ℝ) (hf : Monotone f) (p : Fin 6 → S) (m : ℝ) (hm : 0 ≤ m) + (hs : ∀ i, dist f (p (sixPair i).1) (p (sixPair i).2) ≤ m) : + (dist f (p 0) (p 1) + dist f (p 2) (p 3)) * b ≤ m * (4 * b - 1 : ℕ) := by + classical + let g : Tensor K (Fin 6) →* ℝ := + { toFun := fun X => f (place p X) + map_one' := by rw [place_one, f.map_one] + map_mul' := fun X Y => by rw [place_mul, f.map_mul] } + have mono : Monotone g := hf.comp (place_mono p) + have gz : g 0 = 0 := by change f (place p 0) = 0; rw [place_zero, f.map_zero] + have pos (X) : 0 ≤ g X := gz ▸ mono (zero_le X) + have sum_le (U : Finset (Fin 8 → ℕ)) (F : (Fin 8 → ℕ) → Tensor K (Fin 6)) : + g (∑ h ∈ U, F h) ≤ ∑ h ∈ U, g (F h) := by + induction U using Finset.induction_on with + | empty => simp [gz] + | insert h U hh ih => + rw [Finset.sum_insert hh, Finset.sum_insert hh] + refine le_trans ?_ (add_le_add le_rfl ih) + exact (hf (place_add_le p _ _)).trans_eq (f.map_add _ _) + have gw (i j : Fin 6) : g (wire K i j 2) = (2 : ℝ) ^ dist f (p i) (p j) := by + change f (place p _) = _ + rw [place_wire, price_wire f hf _ _ (by decide), Nat.cast_ofNat] + let R := (2 : ℝ) ^ m + have hr : 1 ≤ R := Real.one_le_rpow (by norm_num) hm + have hwire (i) : g (sixSupply K i) ≤ R := by + rw [sixSupply, gw] + exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (hs i) + have h : g (sixDemand K) ^ b ≤ R ^ (4 * b - 1) := by + apply remove_factor (C := g C * H.card) (by positivity) + intro z hz + let F (h : Fin 8 → ℕ) := ∏ i, sixSupply K i ^ (h i * z) + have term (h) (hh : h ∈ H) : g (F h) ≤ (R ^ (4 * b - 1)) ^ z := by + unfold F + rw [map_prod] + simp only [map_pow] + calc + _ ≤ ∏ i, R ^ (h i * z) := Finset.prod_le_prod₀ + (fun i _ => pow_nonneg (pos _) _) (fun i _ => pow_le_pow_left₀ (pos _) (hwire i) _) + _ = R ^ ((∑ i, h i) * z) := by rw [Finset.prod_pow_eq_pow_sum, Finset.sum_mul] + _ ≤ _ := by + rw [← pow_mul] + exact pow_le_pow_right₀ hr (Nat.mul_le_mul_right z (Nat.le_sub_one_of_lt (hbudget h hh))) + rw [← pow_mul, ← map_pow, mul_assoc] + refine (mono (hcomp z hz)).trans ?_ + rw [g.map_mul] + apply mul_le_mul_of_nonneg_left _ (pos _) + refine (sum_le H F).trans ?_ + simpa only [nsmul_eq_mul] using Finset.sum_le_card_nsmul H (fun h => g (F h)) _ term + rw [sixDemand, g.map_mul, gw, gw, ← Real.rpow_add (by norm_num : (0 : ℝ) < 2)] at h + unfold R at h + simp only [← Real.rpow_mul_natCast (by norm_num : (0 : ℝ) ≤ 2)] at h + exact (Real.rpow_le_rpow_left_iff (by norm_num : (1 : ℝ) < 2)).mp h + +/-- A gap relative to the longest side gives a squared gap. The loss +controls both the variance of the four sides and the diagonal deficit. -/ +private theorem squared_gap {a b c d x y δ : ℝ} + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) (hd : 0 ≤ d) + (hx : 0 ≤ x) (hy : 0 ≤ y) (hδ : 0 ≤ δ) + (hx' : 2 * x ≤ a + b + c + d) (hy' : 2 * y ≤ a + b + c + d) + (hgap : x + y ≤ (4 - δ) * max (max a b) (max c d)) : + x ^ 2 + y ^ 2 ≤ (2 - δ ^ 2 / 80) * (a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) := by + let m := max (max a b) (max c d) + let u := a + b + c + d + let v := a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 + let e := 2 * v - (x ^ 2 + y ^ 2) + change x + y ≤ (4 - δ) * m at hgap + change 2 * x ≤ u at hx' + change 2 * y ≤ u at hy' + have ham : a ≤ m := (le_max_left a b).trans (le_max_left _ _) + have hbm : b ≤ m := (le_max_right a b).trans (le_max_left _ _) + have hcm : c ≤ m := (le_max_left c d).trans (le_max_right _ _) + have hdm : d ≤ m := (le_max_right c d).trans (le_max_right _ _) + have hv : v ≤ 4 * m ^ 2 := by + unfold v + linarith only [pow_le_pow_left₀ ha ham 2, pow_le_pow_left₀ hb hbm 2, + pow_le_pow_left₀ hc hcm 2, pow_le_pow_left₀ hd hdm 2] + have dev : (4 * m - u) ^ 2 ≤ 4 * (4 * v - u ^ 2) := by + have eqn : 4 * (4 * v - u ^ 2) = (4 * a - u) ^ 2 + (4 * b - u) ^ 2 + (4 * c - u) ^ 2 + + (4 * d - u) ^ 2 := by + unfold v u + ring + rw [eqn] + have h (s t : ℝ) : (4 * max s t - u) ^ 2 ≤ (4 * s - u) ^ 2 + (4 * t - u) ^ 2 := by + rcases le_total s t with h | h + · rw [max_eq_right h]; exact le_add_of_nonneg_left (sq_nonneg _) + · rw [max_eq_left h]; exact le_add_of_nonneg_right (sq_nonneg _) + unfold m + linarith only [h (max a b) (max c d), h a b, h c d] + have loss : (4 * v - u ^ 2) + (u - x - y) ^ 2 ≤ 2 * e := by + unfold e + nlinarith only [mul_le_mul_of_nonneg_left hx' hx, mul_le_mul_of_nonneg_left hy' hy, + mul_nonneg (show 0 ≤ u - x - y by linarith) (add_nonneg hx hy)] + have hp := mul_nonneg hδ (ha.trans ham) + have hs := pow_le_pow_left₀ hp (show δ * m ≤ 4 * m - x - y by linarith only [hgap]) 2 + have hh : (δ * m) ^ 2 ≤ 20 * e := by + nlinarith only [hs, loss, dev, sq_nonneg (4 * m - u), sq_nonneg (u - x - y), + sq_nonneg ((4 * m - u) - (u - x - y))] + unfold e at hh + change _ ≤ _ * v + nlinarith only [hh, mul_le_mul_of_nonneg_left hv (sq_nonneg δ)] + +/-- A single constant works for every spectral point on every finite site set. -/ +theorem square (K : Type) [Field K] : + ∃ κ : ℝ, 1 < κ ∧ κ < 2 ∧ + ∀ (S : Type) [Fintype S] [Nonempty S] [DecidableEq S] + (f : Tensor K S →+* ℝ), Monotone f → ∀ a b c d : S, + (dist f a c) ^ 2 + (dist f b d) ^ 2 ≤ + κ * ((dist f a b) ^ 2 + (dist f b c) ^ 2 + (dist f c d) ^ 2 + (dist f d a) ^ 2) := by + obtain ⟨n, C, H, hn, hbudget, hcomp⟩ := six_site K + let δ := (n : ℝ)⁻¹ + have hn' : (0 : ℝ) < n := Nat.cast_pos.mpr hn + have hp : 0 < δ := inv_pos.mpr hn' + have hle : δ ≤ 1 := (inv_le_one₀ hn').mpr (by exact_mod_cast hn) + refine ⟨2 - δ ^ 2 / 80, by nlinarith, by nlinarith, ?_⟩ + intro S _ _ _ f hf a b c d + let r := dist f + have tri : ∀ a b c, r a c ≤ r a b + r b c := dist_triangle f hf + have sym : ∀ a b, r a b = r b a := dist_comm f + have nn : ∀ a b, 0 ≤ r a b := dist_nonneg f hf + refine squared_gap (nn a b) (nn b c) (nn c d) (nn d a) (nn a c) (nn b d) hp.le ?_ ?_ ?_ + · linarith [tri a b c, tri c d a, sym a c] + · linarith [tri b c d, tri d a b, sym b d] + let m := max (max (r a b) (r b c)) (max (r c d) (r d a)) + have h₁ : r a b ≤ m := (le_max_left _ _).trans (le_max_left _ _) + have h₂ : r b c ≤ m := (le_max_right _ _).trans (le_max_left _ _) + have h₃ : r c d ≤ m := (le_max_left _ _).trans (le_max_right _ _) + have h₄ : r d a ≤ m := (le_max_right _ _).trans (le_max_right _ _) + have hm := (nn a b).trans h₁ + let p : Fin 6 → S := ![a, c, b, d, a, c] + have hs (i : Fin 8) : r (p (sixPair i).1) (p (sixPair i).2) ≤ m := by + fin_cases i + · exact h₁ + · exact (dist_self f a).le.trans hm + · exact (sym b a).le.trans h₁ + · exact (sym d c).le.trans h₃ + · exact (sym c b).le.trans h₂ + · exact (dist_self f c).le.trans hm + · exact h₂ + · exact h₄ + have hh : (r a c + r b d) * n ≤ m * (4 * n - 1 : ℕ) := + placed_bound hbudget hcomp f hf p m hm hs + rw [Nat.cast_sub (by omega), Nat.cast_mul, Nat.cast_ofNat, Nat.cast_one] at hh + apply (mul_le_mul_iff_left₀ hn').mp + change (r a c + r b d) * n ≤ (4 - δ) * m * n + refine hh.trans_eq ?_ + unfold δ + field_simp + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- +# Simultaneous antipodal wires on a binary cube + +Take all ordered antipodal pairs. Their aggregate cost, divided by +the dimension and number of pairs, can be made arbitrarily small. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable (K : Type) [Field K] + +/-- The product of `wire K x (Cube.flip Finset.univ x) 2` indexed by `x`. -/ +def cubeDemand (n : ℕ) : Tensor K (Cube n) := + ∏ x, wire K x (Cube.flip Finset.univ x) 2 + +/-- The value specified by `wire K i.1 (Cube.flip {i.2} i.1) 2`. -/ +def cubeSupply (n : ℕ) (i : Cube n × Fin n) : Tensor K (Cube n) := + wire K i.1 (Cube.flip {i.2} i.1) 2 + +private theorem cube_gap {κ : ℝ} (hk : 0 ≤ κ) (k L : ℕ) + (hs : (L : ℝ) ^ 2 * (2 * κ) ^ k < ((2 : ℝ) ^ k) ^ 2) + (f : Tensor K (Cube (2 ^ k)) →+* ℝ) (hf : Monotone f) + (hq : ∀ a b c e, (dist f a c) ^ 2 + (dist f b e) ^ 2 ≤ + κ * ((dist f a b) ^ 2 + (dist f b c) ^ 2 + (dist f c e) ^ 2 + (dist f e a) ^ 2)) : + ∃ i, f (cubeDemand K (2 ^ k) ^ L) < f (cubeSupply K (2 ^ k) i) ^ (2 ^ k * Fintype.card (Cube (2 + ^ k))) := by + let n := 2 ^ k + let N := Fintype.card (Cube n) + let D := ∑ x, dist f x (Cube.flip Finset.univ x) + let w (i : Cube n × Fin n) := dist f i.1 (Cube.flip {i.2} i.1) + have hN : (0 : ℝ) < N := by exact_mod_cast (Fintype.card_pos : 0 < Fintype.card (Cube n)) + let : Nonempty (Fin n) := Fin.pos_iff_nonempty.mp (by unfold n; positivity) + obtain ⟨i, _, hi⟩ := Finset.exists_max_image Finset.univ w Finset.univ_nonempty + have he (j) : w j ≤ w i := hi j (Finset.mem_univ _) + have hw : 0 < w i := by + by_contra! bad + have hz (j : Cube n × Fin n) : dist f j.1 (Cube.flip {j.2} j.1) = 0 := + le_antisymm ((he j).trans bad) (dist_nonneg f hf _ _) + have hp (j : Cube n × Fin n) : f (wire K j.1 (Cube.flip {j.2} j.1) 2) = 1 := by + rw [price_wire f hf _ _ (by decide), hz, Real.rpow_zero] + have h := hf (cube_connected K n) + simp only [map_ofNat, map_prod, hp, Finset.prod_const_one] at h + norm_num at h + have hbound := Cube.energy_bound (dist f) hq hk (m := (w i) ^ 2) + (fun x j => pow_le_pow_left₀ (dist_nonneg f hf _ _) (he (x, j)) _) k Finset.univ (by simp) + have hcauchy : D ^ 2 ≤ N * Cube.energy (dist f) Finset.univ := by + simpa [D, N, Cube.energy] using Finset.sum_mul_sq_le_sq_mul_sq Finset.univ + (fun _ : Cube n => (1 : ℝ)) (fun x => dist f x (Cube.flip Finset.univ x)) + have h : ((L : ℝ) * D) ^ 2 < ((n : ℝ) * N * w i) ^ 2 := calc + _ ≤ (L : ℝ) ^ 2 * (N * ((2 * κ) ^ k * N * (w i) ^ 2)) := by + rw [mul_pow] + exact mul_le_mul_of_nonneg_left (hcauchy.trans (mul_le_mul_of_nonneg_left hbound hN.le)) + (sq_nonneg _) + _ = ((L : ℝ) ^ 2 * (2 * κ) ^ k) * ((N : ℝ) * w i) ^ 2 := by ring + _ < ((2 : ℝ) ^ k) ^ 2 * ((N : ℝ) * w i) ^ 2 := mul_lt_mul_of_pos_right hs (by positivity) + _ = _ := by unfold n; push_cast; ring + have hl : (L : ℝ) * D < (n : ℝ) * N * w i := by + by_contra! bad + exact h.not_ge (pow_le_pow_left₀ (by positivity) bad _) + refine ⟨i, ?_⟩ + simp only [cubeDemand, cubeSupply, map_pow, map_prod, price_wire f hf _ _ (n := 2) (by decide), + Nat.cast_ofNat, ← Real.rpow_sum_of_pos (by norm_num : (0 : ℝ) < 2), + ← Real.rpow_mul_natCast (by norm_num : (0 : ℝ) ≤ 2)] + apply (Real.rpow_lt_rpow_left_iff (by norm_num : (1 : ℝ) < 2)).mpr + rw [Nat.cast_mul] + exact (mul_comm D _).trans_lt (hl.trans_eq (mul_comm _ _)) + +private theorem cube_dimension {κ : ℝ} (h1 : 1 < κ) (h2 : κ < 2) (L k₀ : ℕ) : + ∃ k ≥ k₀, (L : ℝ) ^ 2 * (2 * κ) ^ k < ((2 : ℝ) ^ k) ^ 2 := by + have hr : 1 < 4 / (2 * κ) := (one_lt_div (by positivity)).mpr (by linarith) + obtain ⟨j, hj⟩ := pow_unbounded_of_one_lt ((L : ℝ) ^ 2) hr + refine ⟨max j k₀, le_max_right _ _, ?_⟩ + have hg := hj.trans_le (pow_le_pow_right₀ hr.le (le_max_left j k₀)) + rw [div_pow, lt_div_iff₀ (by positivity)] at hg + simpa only [show (4 : ℝ) = 2 ^ 2 by norm_num, ← pow_mul, Nat.mul_comm] using hg + +theorem cube_site (L k₀ : ℕ) (hL : 0 < L) : + ∃ n ≥ k₀, ∃ (b C : ℕ) (H : Finset (Cube n × Fin n → ℕ)), 0 < b ∧ + (∀ h ∈ H, L * ∑ i, h i < n * Fintype.card (Cube n) * b) ∧ + ∀ z : ℕ, 0 < z → cubeDemand K n ^ (b * z) ≤ + (C : Tensor K (Cube n)) * ∑ h ∈ H, ∏ i, cubeSupply K n i ^ (h i * z) := by + obtain ⟨κ, h1, h2, hq⟩ := square K + obtain ⟨k, hk, hs⟩ := cube_dimension h1 h2 L k₀ + let n := 2 ^ k + have hn : 0 < n := by unfold n; positivity + let : Nonempty (Fin n) := Fin.pos_iff_nonempty.mp hn + have hsize : 0 < n * Fintype.card (Cube n) := Nat.mul_pos hn Fintype.card_pos + obtain ⟨b, C, H, hb, hcost, hcomp⟩ := Spectrum.powered_gadget + add_le_add_right mul_le_mul_left zero_le one_le exists_bound + (cubeDemand K n ^ L) (cubeSupply K n) _ hsize + (fun _ => one_le_wire K _ _ (by decide)) (by + intro g hg + let f := NNReal.toRealHom.comp g + have hf : Monotone f := fun _ _ h => hg h + obtain ⟨i, hi⟩ := cube_gap K (by linarith) k L hs f hf (hq _ f hf) + exact ⟨i, NNReal.coe_lt_coe.mp hi⟩) (cube_connected K n) + refine ⟨n, hk.trans (Nat.lt_two_pow_self (n := k)).le, L * b, C, H, Nat.mul_pos hL hb, ?_, ?_⟩ + · intro h hh + exact (Nat.mul_lt_mul_of_pos_left (hcost h hh) hL).trans_eq (by ring) + · intro z hz + rw [Nat.mul_assoc, pow_mul] + exact hcomp z hz + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Extra.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Extra.lean new file mode 100644 index 0000000000..48e64039ba --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Extra.lean @@ -0,0 +1,102 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place + +/-! +# Closing sites in the presence of additional trivial legs + +A closure uses one covector on each removed leg. An additional site +with a trivial source leg remains trivial until the final restriction. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +variable {K S U V : Type} [Field K] [Fintype S] [Fintype U] [Fintype V] + +namespace Raw + +/-- Insert trivial legs in the middle, preserving the last set of legs. -/ +def extra (V : Type) (A : Raw K (S ⊕ U)) : Raw K ((S ⊕ V) ⊕ U) where + leg := Sum.elim (Sum.elim (fun s => A.leg (.inl s)) (fun _ => Unit)) (fun u => A.leg (.inr u)) + fleg := Sum.rec (Sum.rec (fun s => A.fleg (.inl s)) (fun _ => inferInstanceAs (Fintype Unit))) + (fun u => A.fleg (.inr u)) + term := A.term + factor i := Sum.rec (Sum.rec (fun s => A.factor i (.inl s)) (fun _ _ => 1)) + (fun u => A.factor i (.inr u)) + +private theorem coeff_extra (A : Raw K (S ⊕ U)) (x : ∀ s, (extra V A).leg s) : + (extra V A).coeff x = + A.coeff (Sum.rec (fun s => x (.inl (.inl s))) (fun u => x (.inr u))) := by + simp only [coeff, Fintype.prod_sum_type] + change (∑ i : A.term, ((∏ s, A.factor i (.inl s) (x (.inl (.inl s)))) * ∏ _ : V, (1 : K)) * + ∏ u, A.factor i (.inr u) (x (.inr u))) = _ + simp only [Finset.prod_const_one, mul_one] + +theorem group_extra {O : Subring K} [DecidableEq S] [DecidableEq U] [DecidableEq V] + (A : Raw K (S ⊕ U)) : + (Valued.equiv O).r (A.group (Sum.map (Sum.inl : S → S ⊕ V) id)) (extra V A) := by + let f : S ⊕ U → (S ⊕ V) ⊕ U := Sum.map Sum.inl id + let E := extra V A + let F (s : (S ⊕ V) ⊕ U) (x : E.leg s) : (A.group f).leg s := + fun t => match t with + | ⟨.inl _, h⟩ => cast (congrArg E.leg h.symm) x + | ⟨.inr _, h⟩ => cast (congrArg E.leg h.symm) x + let G (s : (S ⊕ V) ⊕ U) : (A.group f).leg s → E.leg s := + match s with + | .inl (.inl a) => fun x => x ⟨.inl a, rfl⟩ + | .inl (.inr _) => fun _ => () + | .inr u => fun x => x ⟨.inr u, rfl⟩ + constructor + · refine .pullback F fun x => ?_ + erw [coeff_extra, coeff_group] + exact congrArg A.coeff (funext fun t => by cases t <;> rfl) + · refine .pullback G fun x => ?_ + erw [coeff_group, coeff_extra] + exact congrArg A.coeff (funext fun t => by cases t <;> rfl) + +variable [Nonempty S] + +private theorem coeff_close (A : Raw K (S ⊕ U)) (v : A.Covectors) (x : ∀ s, (A.close v).leg s) : + (A.close v).coeff x = ∑ i : A.term, (∏ s, A.factor i (.inl s) (x s)) * A.scalar v i := by + classical + change (∑ i : A.term, ∏ s, A.factor i (.inl s) (x s) * weight (A.scalar v i) s) = _ + simp only [Finset.prod_mul_distrib] + simp [weight] + +theorem close_extra {O : Subring K} (A : Raw K (S ⊕ U)) (v : (extra V A).Covectors) : + (Valued.equiv O).r ((extra V A).close v) (pad V (A.close v)) := by + refine Valued.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_ + erw [coeff_close, pad_coeff, coeff_close] + simp only [Fintype.prod_sum_type] + change (∑ i : A.term, ((∏ s, A.factor i (.inl s) (x (.inl s))) * ∏ _ : V, (1 : K)) * + A.scalar v i) = _ + simp only [Finset.prod_const_one, mul_one] + rfl + +end Raw + +namespace Tensor + +theorem close_extra [Nonempty S] [DecidableEq S] [DecidableEq V] [DecidableEq U] + {A : Tensor K (S ⊕ U)} {B : Tensor K (S ⊕ V)} + (h : pad U B ≤ place (Sum.map Sum.inl id) A) : + ∃ C : Tensor K S, B ≤ pad V C ∧ pad U C ≤ A := by + revert h + refine Quotient.inductionOn A fun a h => ?_ + change pad U B ≤ ofRaw (a.group _) at h + rw [ofRaw_eq (Valued.forget_equiv (Raw.group_extra (O := ⊤) a)), pad_le_ofRaw_iff] at h + obtain ⟨v, hv⟩ := h + rw [ofRaw_eq (Valued.forget_equiv (Raw.close_extra (O := ⊤) a v))] at hv + exact ⟨ofRaw (a.close v), hv, pad_close_le U a v⟩ + +end Tensor +end MatrixMultiplicationAllFields.MatrixExponent.Spectral diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Packets.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Packets.lean new file mode 100644 index 0000000000..d7a5df25cc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Packets.lean @@ -0,0 +1,70 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.CubeGadget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path + +/-! +# Exact six-site and cube packets + +The selector set is independent of the common bundle width `z`. Within +a summand, a permitted pair receives a whole number of width-`z` bundles. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable (K : Type) [Field K] + +private theorem expand_profile {S I J : Type} [Fintype S] [DecidableEq S] + [Fintype I] [Fintype J] (A : I → S × S) (hA : ∀ i, (A i).1 ≠ (A i).2) + (B : J → S × S) (w C : ℕ) (H : Finset (J → ℕ)) (z : ℕ) + (h : (∏ i, wire K (A i).1 (A i).2 2) ^ w ≤ + (C : Tensor K S) * ∑ q ∈ H, ∏ j, wire K (B j).1 (B j).2 2 ^ (q j * z)) : + Packet K (fun e : I × Fin w => A e.1) + (fun i : Fin C × ↥H => fun e : Σ j : J, Fin (i.2.1 j * z) => B e.1) := by + classical + apply packet_of_restriction _ (fun e => hA e.1) + simp only [Fintype.prod_prod_type, Fintype.prod_sigma, Finset.prod_const, Finset.card_univ, + Fintype.card_fin, Finset.prod_pow, Fintype.sum_prod_type, Finset.sum_const, nsmul_eq_mul] + rw [Finset.sum_coe_sort H (fun q => ∏ j, wire K (B j).1 (B j).2 2 ^ (q j * z))] + exact h + +/-- The value specified by `![(0, 1), (2, 3)]`. -/ +def sixDemandPair : Fin 2 → Fin 6 × Fin 6 := ![(0, 1), (2, 3)] + +theorem six_packets : + ∃ (b C : ℕ) (H : Finset (Fin 8 → ℕ)), 0 < b ∧ + (∀ h ∈ H, ∑ i, h i < 4 * b) ∧ ∀ z : ℕ, 0 < z → + Packet K (fun e : Fin 2 × Fin (b * z) => sixDemandPair e.1) + (fun i : Fin C × ↥H => fun e : Σ j : Fin 8, Fin (i.2.1 j * z) => sixPair e.1) := by + obtain ⟨b, C, H, hb, hcost, h⟩ := six_site K + refine ⟨b, C, H, hb, hcost, fun z hz => ?_⟩ + apply expand_profile K sixDemandPair (by decide) sixPair + rw [Fin.prod_univ_two] + exact h z hz + +theorem cube_packets (L k₀ : ℕ) (hL : 0 < L) : + ∃ n ≥ k₀, ∃ (b C : ℕ) (H : Finset (Cube n × Fin n → ℕ)), 0 < b ∧ + (∀ h ∈ H, L * ∑ i, h i < n * Fintype.card (Cube n) * b) ∧ ∀ z : ℕ, 0 < z → + Packet K (fun e : Cube n × Fin (b * z) => (e.1, Cube.flip Finset.univ e.1)) + (fun i : Fin C × ↥H => fun e : Σ j : Cube n × Fin n, Fin (i.2.1 j * z) => + (e.1.1, Cube.flip {e.1.2} e.1.1)) := by + obtain ⟨n, hn, b, C, H, hb, hcost, h⟩ := cube_site K L (k₀ + 1) hL + refine ⟨n, by omega, b, C, H, hb, hcost, fun z hz => ?_⟩ + have ha (x : Cube n) : x ≠ Cube.flip Finset.univ x := by + intro he + have := congrFun he (⟨0, by omega⟩ : Fin n) + simp [Cube.flip] at this + refine expand_profile K (fun x : Cube n => (x, Cube.flip Finset.univ x)) ha + (fun i : Cube n × Fin n => (i.1, Cube.flip {i.2} i.1)) (b * z) C H z ?_ + exact h z hz + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Path.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Path.lean new file mode 100644 index 0000000000..6e7524af0a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Path.lean @@ -0,0 +1,898 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport +public import Mathlib.Data.Fintype.Option +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rule + +/-! +# Direct sums as ordinary sums of restrictions + +Expanding the source direct sum gives independent local matrices for +each summand. The formula holds in all characteristics. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S I : Type} [Field K] [Fintype S] + +/-- The indexing data represented by `(s : S) → B.leg s → A.leg s → K`. -/ +abbrev Local (A B : Raw K S) := (s : S) → B.leg s → A.leg s → K + +/-- The quantity computed by `∑ i : A.term, ∏ s, ∑ y : A.leg s, L s (x s) y * A.factor i s y`. -/ +def applyLocal (A : Raw K S) {B : Raw K S} (L : Local A B) (x : ∀ s, B.leg s) : K := + ∑ i : A.term, ∏ s, ∑ y : A.leg s, L s (x s) y * A.factor i s y + +theorem applyLocal_add (A B C : Raw K S) (L : Local (A + B) C) (x : ∀ s, C.leg s) : + (A + B).applyLocal L x = + A.applyLocal (fun s u y => L s u (.inl y)) x + + B.applyLocal (fun s u y => L s u (.inr y)) x := by + change (∑ i : A.term ⊕ B.term, ∏ s, ∑ y : A.leg s ⊕ B.leg s, + L s (x s) y * (A + B).factor i s y) = _ + simp only [Fintype.sum_sum_type] + change + (∑ i, ∏ s, ((∑ y, L s (x s) (.inl y) * A.factor i s y) + + ∑ y : B.leg s, L s (x s) (.inr y) * 0)) + + (∑ i, ∏ s, ((∑ y : A.leg s, L s (x s) (.inl y) * 0) + + ∑ y, L s (x s) (.inr y) * B.factor i s y)) = _ + simp only [mul_zero, Finset.sum_const_zero, zero_add, add_zero, applyLocal] + +private theorem sum_maps (A : I → Raw K S) (B : Raw K S) (s : Finset I) : + ∃ C : Raw K S, Tensor.ofRaw C = ∑ i ∈ s, Tensor.ofRaw (A i) ∧ + (∀ L : Local C B, ∃ M : ∀ i, Local (A i) B, + ∀ x, C.applyLocal L x = ∑ i ∈ s, (A i).applyLocal (M i) x) ∧ + (∀ M : ∀ i, Local (A i) B, ∃ L : Local C B, + ∀ x, C.applyLocal L x = ∑ i ∈ s, (A i).applyLocal (M i) x) := by + classical + induction s using Finset.induction_on with + | empty => + have e (L : Local 0 B) (x : ∀ s, B.leg s) : (0 : Raw K S).applyLocal L x = 0 := + Finset.sum_eq_zero fun i _ => Empty.elim i + exact ⟨0, rfl, fun L => ⟨fun _ _ _ _ => 0, e L⟩, fun _ => ⟨fun _ _ _ => 0, e _⟩⟩ + | @insert i s hi ih => + obtain ⟨C, he, hl, hr⟩ := ih + refine ⟨A i + C, by rw [Finset.sum_insert hi, Tensor.ofRaw_add, he], ?_, ?_⟩ + · intro L + obtain ⟨M, hM⟩ := hl fun s u y => L s u (.inr y) + refine ⟨Function.update M i (fun s u y => L s u (.inl y)), fun x => ?_⟩ + rw [applyLocal_add, hM, Finset.sum_insert hi, Function.update_self] + refine congrArg _ (Finset.sum_congr rfl fun j hj => ?_) + rw [Function.update_of_ne (ne_of_mem_of_not_mem hj hi)] + · intro M + obtain ⟨L, hL⟩ := hr M + refine ⟨fun s u => Sum.elim (M i s u) (L s u), fun x => ?_⟩ + rw [applyLocal_add, Finset.sum_insert hi] + exact congrArg _ (hL x) + +theorem restriction_sum_iff (A : I → Raw K S) (B : Raw K S) (s : Finset I) : + Tensor.ofRaw B ≤ ∑ i ∈ s, Tensor.ofRaw (A i) ↔ + ∃ M : ∀ i, Local (A i) B, ∀ x, B.coeff x = ∑ i ∈ s, (A i).applyLocal (M i) x := by + obtain ⟨C, he, hl, hr⟩ := sum_maps A B s + rw [← he, Tensor.ofRaw_le] + constructor + · rintro ⟨L, hL⟩ + obtain ⟨M, hM⟩ := hl L + exact ⟨M, fun x => (hL x).trans (hM x)⟩ + · rintro ⟨M, hM⟩ + obtain ⟨L, hL⟩ := hr M + exact ⟨L, fun x => (hM x).trans (hL x).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +/- # Bit-label coordinates for arbitrary products of wires -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S E X Y : Type} [Field K] [Fintype S] + +private theorem signals_relabel [Fintype X] [DecidableEq X] [Fintype Y] [DecidableEq Y] + (f : S → X → X) (g : S → Y → Y) (e : X ≃ Y) (h : ∀ v x, e (f v x) = g v (e x)) : + signals K f = signals K g := by + apply ofRaw_eq + refine Raw.relabel e (fun _ => e) (fun i v x => ?_) + change (if x = f v i then (1 : K) else 0) = if e x = g v (e i) then 1 else 0 + simp only [← h, e.injective.eq_iff] + +private def separate (E : Type) : (Option E → Bool) ≃ Fin 2 × (E → Bool) where + toFun x := (finTwoEquiv.symm (x none), fun e => x (some e)) + invFun x e := e.elim (finTwoEquiv x.1) x.2 + left_inv x := by funext e; cases e <;> simp + right_inv x := by simp + +variable [DecidableEq S] + +/-- Keep the bits incident to the given site. -/ +def mask (D : E → S × S) (v : S) (x : E → Bool) (e : E) := + if (D e).1 = v ∨ (D e).2 = v then x e else false + +/-- Each bit is visible at its two endpoints. Other sites see a fixed +dummy value in the same coordinate. -/ +theorem signals_prod [Fintype E] [DecidableEq E] (D : E → S × S) : + signals K (mask D) = + ∏ e, wire K (D e).1 (D e).2 2 := by + classical + refine Fintype.induction_empty_option + (P := fun T => ∀ [DecidableEq T] (D : T → S × S), + signals K (mask D) = ∏ e, wire K (D e).1 (D e).2 2) + ?_ ?_ ?_ E D + · intro A B _ e ih _ F + let := Fintype.ofEquiv B e.symm + rw [← e.prod_comp (fun j => wire K (F j).1 (F j).2 2)] + refine (signals_relabel _ _ (e.symm.arrowCongr (Equiv.refl Bool)) ?_).trans + (ih (fun i => F (e i))) + intro v x + rfl + · intro _ F + rw [Finset.prod_of_isEmpty] + apply ofRaw_eq + let e := Equiv.ofUnique (PEmpty → Bool) Unit + refine Raw.relabel e (fun _ => e) (fun i v x => ?_) + change (if x = mask F v i then (1 : K) else 0) = 1 + rw [ite_eq_left (Subsingleton.elim _ _)] + · intro A _ ih _ F + rw [Fintype.prod_option, ← ih (fun i => F (some i)), + ← signals_wire, ← signals_mul] + apply signals_relabel _ _ (separate A) + intro v x + apply Prod.ext + · change finTwoEquiv.symm (mask F v x none) = Raw.port _ v (finTwoEquiv.symm (x none)) + simp only [mask, Raw.port, Finset.mem_insert, Finset.mem_singleton, + eq_comm (a := v)] + split <;> rfl + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- # From a direct-sum restriction to local bit tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S E I : Type} [Field K] [Fintype S] [DecidableEq S] [Fintype E] + +open Classical in +private def expose (D : E → S × S) (v : S) (x y : E → Bool) (e : E) : Bool := + if (D e).1 = v then x e else if (D e).2 = v then y e else false + +open Classical in +private def graph (K : Type) [Field K] (D : E → S × S) : Raw K S := + ⟨fun _ => E → Bool, E → Bool, fun i s x => if x = mask D s i then 1 else 0⟩ + +open Classical in +private theorem graph_coeff (D : E → S × S) (hd : ∀ e, (D e).1 ≠ (D e).2) + (x y : E → Bool) : + (graph K D).coeff (fun v => expose D v x y) = if x = y then 1 else 0 := by + change (∑ i : E → Bool, ∏ v, if expose D v x y = mask D v i then (1 : K) else 0) = _ + rw [Fintype.sum_eq_single x] + · by_cases h : x = y + · subst y + rw [ite_eq_left rfl] + apply Finset.prod_eq_one + intro v _ + apply ite_eq_left + funext e + by_cases ha : (D e).1 = v <;> simp [mask, expose, ha] + · rw [ite_eq_right h] + obtain ⟨e, he⟩ := Function.ne_iff.mp h + apply Finset.prod_eq_zero (Finset.mem_univ (D e).2) + apply ite_eq_right + intro eq + exact he (by simpa [expose, mask, hd e] using (congrFun eq e).symm) + · intro i hi + obtain ⟨e, he⟩ := Function.ne_iff.mp hi + apply Finset.prod_eq_zero (Finset.mem_univ (D e).1) + apply ite_eq_right + intro eq + exact he (by simpa [expose, mask] using (congrFun eq e).symm) + +variable {J : I → Type} [Fintype I] [∀ i, Fintype (J i)] + +open Classical in +private theorem packet_of_graph (D : E → S × S) (hd : ∀ e, (D e).1 ≠ (D e).2) + (W : (i : I) → J i → S × S) + (h : ofRaw (graph K D) ≤ ∑ i, ofRaw (graph K (W i))) : + Packet K D W := by + obtain ⟨L, hL⟩ := (Raw.restriction_sum_iff (fun i => graph K (W i)) (graph K D) Finset.univ).mp h + change (i : I) → S → (E → Bool) → (J i → Bool) → K at L + refine ⟨fun i v x y u => L i v (expose D v x y) (mask (W i) v u), ?_, ?_⟩ + · intro i v x y u x' y' u' hx hy hu + apply congrArg₂ (L i v) + · funext e + unfold expose + split + · exact hx _ ‹_› + split + · exact hy _ ‹_› + · rfl + · funext e + unfold mask + split + · exact hu _ ‹_› + · rfl + · intro x y + refine (graph_coeff D hd x y).symm.trans ((hL _).trans ?_) + change (∑ i, ∑ u : J i → Bool, ∏ v, ∑ z, L i v (expose D v x y) z * + if z = mask (W i) v u then 1 else 0) = _ + simp [mul_ite] + +open Classical in +/-- Expanding the direct sum and acting on the shared-label +coordinates gives one independent sum of local products per summand. -/ +theorem packet_of_restriction (D : E → S × S) (hd : ∀ e, (D e).1 ≠ (D e).2) + (W : (i : I) → J i → S × S) + (h : (∏ e, wire K (D e).1 (D e).2 2) ≤ ∑ i, ∏ e, wire K (W i e).1 (W i e).2 2) : + Packet K D W := by + apply packet_of_graph D hd W + have eq {A : Type} [Fintype A] (P : A → S × S) : + ofRaw (graph K P) = ∏ e, wire K (P e).1 (P e).2 2 := signals_prod P + simpa only [eq] using h + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- # Serial composition of exact wire packets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet + +open Finset + +variable {K S E X Y : Type} [Field K] [Fintype S] [Fintype E] [Fintype X] [Fintype Y] + +open Classical in +/-- Returns `x ⟨e, h⟩` when `h : b e = v` holds, and `false` otherwise. -/ +def fill (b : E → S) (v : S) (x : {e // b e = v} → Bool) (e : E) := + if h : b e = v then x ⟨e, h⟩ else false + +open Classical in +theorem contract (b : E → S) (f : S → (E → Bool) → K) + (loc : ∀ v x y, (∀ e, b e = v → x e = y e) → f v x = f v y) : + (∏ v, ∑ z, f v (fill b v z)) = ∑ z, ∏ v, f v z := by + let e : (E → Bool) ≃ (∀ v, {j // b j = v} → Bool) := + ((Equiv.sigmaFiberEquiv b).symm.arrowCongr (Equiv.refl _)).trans + (Equiv.piCurry fun v (_ : {j // b j = v}) => Bool) + rw [Fintype.prod_sum, ← e.sum_comp] + apply sum_congr rfl + intro z _ + exact prod_congr rfl fun v _ => loc _ _ _ (fun i hi => by rw [fill, dite_eq_left hi]; rfl) + +open Classical in +/-- Joining the last endpoint of each first demand to the first endpoint +of its successor requires no additional wires, even when sites coincide. -/ +def Rule.series {a b c : E → S} {W : X → S × S} {U : Y → S × S} + (hf : Rule K (fun e => (a e, b e)) (fun _ : Unit => W)) + (hg : Rule K (fun e => (b e, c e)) (fun _ : Unit => U)) : + Rule K (fun e => (a e, c e)) (fun _ : Unit => Sum.elim W U) := by + obtain ⟨f, lf, sf⟩ := hf + obtain ⟨g, lg, sg⟩ := hg + let L (x y : E → Bool) (u : X ⊕ Y → Bool) (v : S) (z : E → Bool) := + f () v x z (u ∘ Sum.inl) * g () v z y (u ∘ Sum.inr) + have loc x y u v z z' (hz : ∀ e, b e = v → z e = z' e) : L x y u v z = L x y u v z' := + congrArg₂ (· * ·) + (lf _ _ _ _ _ _ _ _ (fun _ _ => rfl) hz (fun _ _ => rfl)) + (lg _ _ _ _ _ _ _ _ hz (fun _ _ => rfl) (fun _ _ => rfl)) + refine ⟨fun _ v x y u => ∑ z, L x y u v (fill b v z), ?_, ?_⟩ + · intro _ v x y u x' y' u' hx hy hu + refine sum_congr rfl fun z _ => congrArg₂ (· * ·) ?_ ?_ + · exact lf _ _ _ _ _ _ _ _ hx (fun _ _ => rfl) (fun e h => hu (.inl e) h) + · exact lg _ _ _ _ _ _ _ _ (fun _ _ => rfl) hy (fun e h => hu (.inr e) h) + · intro x y + simp only [Fintype.sum_unique] at sf sg ⊢ + simp_rw [contract b _ (loc x y _)] + rw [sum_comm] + have expand (z : E → Bool) : + (∑ u, ∏ v, L x y u v z) = + (if x = z then (1 : K) else 0) * (if z = y then 1 else 0) := by + rw [sf x z, sg z y, sum_mul_sum, + ← (Equiv.sumArrowEquivProdArrow X Y Bool).symm.sum_comp, Fintype.sum_prod_type] + apply sum_congr rfl + intro u _ + apply sum_congr rfl + intro w _ + rw [← prod_mul_distrib] + rfl + calc + _ = ∑ z, (if x = z then (1 : K) else 0) * (if z = y then 1 else 0) := by simp + _ = _ := by + apply sum_congr rfl + intro z _ + exact (expand z).symm.trans (sum_congr (by ext; simp) (fun _ _ => rfl)) + +open Classical in +/-- Several paths may share sites. Their wire variables remain distinct. -/ +def Rule.path (K : Type) [Field K] (D : ℕ → E → S) (n : ℕ) : + Rule K (fun e => (D 0 e, D n e)) + (fun _ : Unit => fun q : Fin n × E => (D q.1.val q.2, D (q.1.val + 1) q.2)) := by + let left (x : E → Bool) (u : Fin n × E → Bool) : Fin (n + 1) → E → Bool := + Fin.cons x (Function.curry u) + let right (y : E → Bool) (u : Fin n × E → Bool) : Fin (n + 1) → E → Bool := + Fin.snoc (Function.curry u) y + let ok v x y u := ∀ (i : Fin (n + 1)) e, D i.val e = v → left x u i e = right y u i e + refine ⟨fun _ v x y u => if ok v x y u then 1 else 0, ?_, ?_⟩ + · intro _ v x y u x' y' u' hx hy hu + have hl (i : Fin (n + 1)) e (he : D i.val e = v) : left x u i e = left x' u' i e := by + induction i using Fin.cases with + | zero => exact hx e he + | succ i => simpa [left] using hu (i, e) (.inr he) + have hr (i : Fin (n + 1)) e (he : D i.val e = v) : right y u i e = right y' u' i e := by + induction i using Fin.lastCases with + | last => simpa [right] using hy e he + | cast i => simpa [right] using hu (i, e) (.inl he) + have he : ok v x y u ↔ ok v x' y' u' := + ⟨fun h i e hi => (hl i e hi).symm.trans ((h i e hi).trans (hr i e hi)), + fun h i e hi => (hl i e hi).trans ((h i e hi).trans (hr i e hi).symm)⟩ + simp only [he] + · intro x y + let z (p : Fin n × E) := x p.2 + have unique (u : Fin n × E → Bool) (hu : ∀ v, ok v x y u) : x = y ∧ u = z := by + have eq (i : Fin (n + 1)) e : left x u i e = right y u i e := hu _ i e rfl + have same (i : Fin (n + 1)) e : left x u i e = x e := by + induction i using Fin.induction with + | zero => rfl + | succ i ih => simpa [left, right] using (eq i.castSucc e).symm.trans ih + constructor + · funext e + simpa [right] using ((same (Fin.last n) e).symm.trans (eq (Fin.last n) e)) + · funext ⟨i, e⟩ + simpa [left, z] using same i.succ e + have zero (u : Fin n × E → Bool) (hu : ¬(x = y ∧ u = z)) : + (∏ v, if ok v x y u then (1 : K) else 0) = 0 := by + obtain ⟨v, hv⟩ := not_forall.mp (fun h => hu (unique u h)) + exact prod_eq_zero (mem_univ v) (ite_eq_right hv) + simp only [Fintype.sum_unique] + rw [sum_eq_single z] + rotate_left + · exact fun u _ hu => zero u (fun h => hu h.2) + · simp + by_cases he : x = y + · subst y + have hl (i : Fin (n + 1)) e : left x z i e = x e := by + induction i using Fin.cases <;> simp [left, z] + have hr (i : Fin (n + 1)) e : right x z i e = x e := by + induction i using Fin.lastCases <;> simp [right, z] + simp [ok, hl, hr] + · rw [ite_eq_right he, zero z (fun h => he h.1)] + +open Classical in +theorem series {a b c : E → S} {W : X → S × S} {U : Y → S × S} + (hf : Packet K (fun e => (a e, b e)) (fun _ : Unit => W)) + (hg : Packet K (fun e => (b e, c e)) (fun _ : Unit => U)) : + Packet K (fun e => (a e, c e)) (fun _ : Unit => Sum.elim W U) := + (Rule.series hf.rule hg.rule).packet + +open Classical in +theorem path (K : Type) [Field K] (D : ℕ → E → S) (n : ℕ) : + Packet K (fun e => (D 0 e, D n e)) + (fun _ : Unit => fun q : Fin n × E => (D q.1.val q.2, D (q.1.val + 1) q.2)) := + (Rule.path K D n).packet + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet +end + +/- # Reindexing a packet and keeping extra wires unchanged -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet + +variable {K S U E Z I : Type} {J : I → Type} [Field K] + +open Classical in +/-- Disjoint union of two indexed families of directed edges. -/ +def together (D : E → S × S) (L : Z → U × U) : E ⊕ Z → (S ⊕ U) × (S ⊕ U) + | .inl e => (.inl (D e).1, .inl (D e).2) + | .inr e => (.inr (L e).1, .inr (L e).2) + +variable [Fintype Z] + +open Classical in +/-- Returns `1` when `∀ e, l e = v → x e = u e` holds, and `0` otherwise. -/ +def checkAt (K : Type) [Field K] (l : Z → U) (v : U) (x u : Z → Bool) : K := + if ∀ e, l e = v → x e = u e then 1 else 0 + +open Classical in +theorem check_congr {l : Z → U} {v : U} {x y u w : Z → Bool} + (hx : ∀ e, l e = v → x e = y e) (hu : ∀ e, l e = v → u e = w e) : + checkAt K l v x u = checkAt K l v y w := by + have he : (∀ e, l e = v → x e = u e) ↔ (∀ e, l e = v → y e = w e) := by + constructor <;> intro h e hv + · rw [← hx e hv, ← hu e hv, h e hv] + · rw [hx e hv, hu e hv, h e hv] + simp only [checkAt, he] + +variable [Fintype U] + +open Classical in +theorem check_prod (l : Z → U) (x u : Z → Bool) : + (∏ v, checkAt K l v x u) = if x = u then 1 else 0 := by + by_cases h : x = u + · simp [checkAt, h] + obtain ⟨e, he⟩ := Function.ne_iff.mp h + rw [ite_eq_right h] + exact Finset.prod_eq_zero (Finset.mem_univ (l e)) (ite_eq_right (fun h => he (h e rfl))) + +variable [Fintype S] [Fintype E] [Fintype I] [∀ i, Fintype (J i)] + {D : E → S × S} {W : (i : I) → J i → S × S} + +open Classical in +/-- The reindex of type `Rule K (D ∘ e) W`, constructed using `h.entry`. -/ +def Rule.reindex (h : Rule K D W) (e : Z ≃ E) : Rule K (D ∘ e) W := by + let f := h.entry + have hl := h.local' + have hi := h.eval + refine ⟨fun i v x y u => f i v (x ∘ e.symm) (y ∘ e.symm) u, ?_, ?_⟩ + · intro i v x y u x' y' u' hx hy hu + exact hl i v _ _ _ _ _ _ (fun j hj => hx _ (by simpa using hj)) + (fun j hj => hy _ (by simpa using hj)) hu + · intro x y + have he : x ∘ e.symm = y ∘ e.symm ↔ x = y := + (e.arrowCongr (Equiv.refl Bool)).injective.eq_iff + simpa only [he] using hi (x ∘ e.symm) (y ∘ e.symm) + +open Classical in +theorem reindex (h : Packet K D W) (e : Z ≃ E) : Packet K (D ∘ e) W := + (h.rule.reindex e).packet + +open Classical in +/-- Keeping a wire costs one additional supply bit and no selector. -/ +def Rule.keep (h : Rule K D W) (L : Z → U × U) : + Rule K (together D L) (fun i => together (W i) L) := by + let f := h.entry + have hl := h.local' + have hi := h.eval + let g (i : I) (v : S ⊕ U) (x y : E ⊕ Z → Bool) (u : J i ⊕ Z → Bool) := + Sum.elim (fun s => f i s (x ∘ Sum.inl) (y ∘ Sum.inl) (u ∘ Sum.inl)) + (fun s => checkAt K (fun e => (L e).1) s (x ∘ Sum.inr) (u ∘ Sum.inr) * + checkAt K (fun e => (L e).2) s (y ∘ Sum.inr) (u ∘ Sum.inr)) v + refine ⟨g, ?_, ?_⟩ + · intro i v x y u x' y' u' hx hy hu + cases v with + | inl s => + exact hl i s _ _ _ _ _ _ (fun e he => hx (.inl e) (congrArg Sum.inl he)) + (fun e he => hy (.inl e) (congrArg Sum.inl he)) + (fun e he => hu (.inl e) (he.imp (congrArg Sum.inl) (congrArg Sum.inl))) + | inr s => + apply congrArg₂ (· * ·) + · exact check_congr (fun e he => hx (.inr e) (congrArg Sum.inr he)) + (fun e he => hu (.inr e) (.inl (congrArg Sum.inr he))) + · exact check_congr (fun e he => hy (.inr e) (congrArg Sum.inr he)) + (fun e he => hu (.inr e) (.inr (congrArg Sum.inr he))) + · intro x y + have he : x = y ↔ x ∘ Sum.inl = y ∘ Sum.inl ∧ x ∘ Sum.inr = y ∘ Sum.inr := + (Equiv.sumArrowEquivProdArrow E Z Bool).injective.eq_iff.symm.trans Prod.ext_iff + have delta : (if x = y then (1 : K) else 0) = + (if x ∘ Sum.inl = y ∘ Sum.inl then 1 else 0) * + (if x ∘ Sum.inr = y ∘ Sum.inr then 1 else 0) := by + simp only [he, ite_and, ite_mul, one_mul, zero_mul] + rw [delta, hi, Finset.sum_mul] + apply Finset.sum_congr rfl + intro i _ + let : DecidableEq (J i ⊕ Z) := Classical.decEq _ + rw [← (Equiv.sumArrowEquivProdArrow (J i) Z Bool).symm.sum_comp, Fintype.sum_prod_type, + Finset.sum_mul] + apply Finset.sum_congr rfl + intro u _ + simp only [Fintype.prod_sum_type, g, Sum.elim_inl, Sum.elim_inr, Finset.prod_mul_distrib, + check_prod] + change _ = ∑ w : Z → Bool, (∏ s, f i s (x ∘ Sum.inl) (y ∘ Sum.inl) u) * + ((if x ∘ Sum.inr = w then 1 else 0) * (if y ∘ Sum.inr = w then 1 else 0)) + simp only [f, mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + +open Classical in +theorem keep (h : Packet K D W) (L : Z → U × U) : + Packet K (together D L) (fun i => together (W i) L) := + (h.rule.keep L).packet + +open Classical in +/-- Transports the supply indices of a rule along an equivalence. -/ +def Rule.suppliesEquiv {C : I → Type} [∀ i, Fintype (C i)] + (h : Rule K D W) (e : ∀ i, C i ≃ J i) : + Rule K D (fun i => W i ∘ e i) := by + let f := h.entry + have loc := h.local' + have eval := h.eval + refine ⟨fun i v x y z => f i v x y (z ∘ (e i).symm), ?_, ?_⟩ + · intro i v x y z x' y' z' hx hy hz + exact loc i v _ _ _ _ _ _ hx hy (fun b hb => hz ((e i).symm b) (by simpa using hb)) + · intro x y + rw [eval] + refine Finset.sum_congr rfl fun i _ => ?_ + rw [← ((e i).arrowCongr (Equiv.refl Bool)).sum_comp] + rfl + +open Classical in +theorem suppliesEquiv {C : I → Type} [∀ i, Fintype (C i)] + (h : Packet K D W) (e : ∀ i, C i ≃ J i) : + Packet K D (fun i => W i ∘ e i) := + (h.rule.suppliesEquiv e).packet + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet +end + +/- # Parallel composition and placement of wire packets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet + +variable {K : Type} [Field K] + +open Classical in +/-- Identify sites along an arbitrary map, multiplying the tables in each fiber. -/ +def Rule.place {S U E I : Type} {J : I → Type} + [Fintype S] [Fintype U] [Fintype E] [Fintype I] [∀ i, Fintype (J i)] + {D : E → S × S} {W : (i : I) → J i → S × S} + (h : Rule K D W) (g : S → U) : + Rule K (fun e => (g (D e).1, g (D e).2)) (fun i e => (g (W i e).1, g (W i e).2)) := by + obtain ⟨f, hloc, hid⟩ := h + refine ⟨fun i v x y u => ∏ w ∈ Finset.univ.filter (fun w => g w = v), f i w x y u, ?_, ?_⟩ + · intro i v x y u x' y' u' hx hy hu + apply Finset.prod_congr rfl + intro w hw + have he := (Finset.mem_filter.mp hw).2 + exact hloc i w _ _ _ _ _ _ + (fun e h => hx e ((congrArg g h).trans he)) + (fun e h => hy e ((congrArg g h).trans he)) + (fun e h => hu e (h.imp (fun h => (congrArg g h).trans he) (fun h + => (congrArg g h).trans he))) + · intro x y + rw [hid x y] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro u _ + exact (Finset.prod_fiberwise Finset.univ g (fun v => f i v x y u)).symm + +open Classical in +theorem place {S U E I : Type} {J : I → Type} + [Fintype S] [Fintype U] [Fintype E] [Fintype I] [∀ i, Fintype (J i)] + {D : E → S × S} {W : (i : I) → J i → S × S} + (h : Packet K D W) (g : S → U) : + Packet K (fun e => (g (D e).1, g (D e).2)) (fun i e => (g (W i e).1, g (W i e).2)) := + (h.rule.place g).packet + +variable {A : Type} {S E I : A → Type} {J : (a : A) → I a → Type} + +open Classical in +/-- Demand legs keep their component labels. -/ +def parallelDemand (D : (a : A) → E a → S a × S a) (e : Sigma E) : Sigma S × Sigma S := + (⟨e.1, (D e.1 e.2).1⟩, ⟨e.1, (D e.1 e.2).2⟩) + +open Classical in +/-- Each component activates its own supply according to its own selector. -/ +def parallelSupply (W : (a : A) → (i : I a) → J a i → S a × S a) + (i : ∀ a, I a) (e : Sigma (fun a => J a (i a))) : Sigma S × Sigma S := + parallelDemand (fun a => W a (i a)) e + +open Classical in +/-- Reindexes `(Sigma E → Bool)` and `((a : A) → E a → Bool) where toFun x a e` by an +equivalence. -/ +def parts (E : A → Type) : (Sigma E → Bool) ≃ ((a : A) → E a → Bool) where + toFun x a e := x ⟨a, e⟩ + invFun x e := x e.1 e.2 + left_inv _ := rfl + right_inv _ := rfl + +variable [Fintype A] [DecidableEq A] [∀ a, Fintype (S a)] [∀ a, Fintype (E a)] + [∀ a, Fintype (I a)] [∀ a i, Fintype (J a i)] + +open Classical in +/-- The selector set is a Cartesian product. Assignments to different +components remain independent even when their endpoints coincide. -/ +def Rule.parallel {D : (a : A) → E a → S a × S a} + {W : (a : A) → (i : I a) → J a i → S a × S a} + (h : ∀ a, Rule K (D a) (W a)) : Rule K (parallelDemand D) (parallelSupply W) := by + let f a := (h a).entry + have hloc a := (h a).local' + have hid a := (h a).eval + refine ⟨fun i v x y u => + f v.1 (i v.1) v.2 (parts E x v.1) (parts E y v.1) (parts _ u v.1), ?_, ?_⟩ + · rintro i ⟨a, v⟩ x y u x' y' u' hx hy hu + apply hloc + · intro e he + exact hx ⟨a, e⟩ (congrArg (Sigma.mk a) he) + · intro e he + exact hy ⟨a, e⟩ (congrArg (Sigma.mk a) he) + · intro e he + exact hu ⟨a, e⟩ (he.imp (congrArg (Sigma.mk a)) (congrArg (Sigma.mk a))) + · intro x y + have delta : (if x = y then (1 : K) else 0) = + ∏ a, if parts E x a = parts E y a then 1 else 0 := by + by_cases he : x = y + · simp [he] + · rw [ite_eq_right he] + obtain ⟨a, ha⟩ := Function.ne_iff.mp ((parts E).injective.ne he) + exact (Finset.prod_eq_zero (Finset.mem_univ a) (ite_eq_right ha)).symm + rw [delta] + simp_rw [hid] + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro i _ + rw [Fintype.prod_sum, ← (parts (fun a => J a (i a))).sum_comp] + refine Finset.sum_congr (by ext; simp) ?_ + intro u _ + rw [Fintype.prod_sigma] + +open Classical in +theorem parallel {D : (a : A) → E a → S a × S a} + {W : (a : A) → (i : I a) → J a i → S a × S a} + (h : ∀ a, Packet K (D a) (W a)) : Packet K (parallelDemand D) (parallelSupply W) := + (Rule.parallel (fun a => (h a).rule)).packet + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet +end + +/- # Selecting and deploying exact wire packets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet + +variable {F S A B I : Type} [Field F] [Fintype S] [Fintype A] [Fintype B] [Fintype I] + {J : I → Type} [∀ i, Fintype (J i)] {D : A → S × S} {W : (i : I) → J i → S × S} + +open scoped Classical in +/-- Pin both ends of each unused demand to zero. -/ +def Rule.select (h : Rule F D W) (e : B ↪ A) : Rule F (fun a => D (e a)) W := by + let fill (x : B → Bool) (a : A) := if ha : ∃ b, e b = a then x ha.choose else false + have read (x : B → Bool) (b : B) : fill x (e b) = x b := by + have hh : ∃ c, e c = e b := ⟨b, rfl⟩ + simp only [fill, dite_eq_left hh, e.injective hh.choose_spec] + have inj : Function.Injective fill := by + intro x y eq + funext b + simpa only [read] using congrFun eq (e b) + have same (x y : B → Bool) (a : A) (hx : ∀ b, e b = a → x b = y b) : + fill x a = fill y a := by + unfold fill + split + · rename_i ha + exact hx _ ha.choose_spec + · rfl + obtain ⟨f, loc, eval⟩ := h + refine ⟨fun i v x y => f i v (fill x) (fill y), ?_, ?_⟩ + · intro i v x y u x' y' u' hx hy hu + exact loc i v _ _ _ _ _ _ + (fun a ha => same _ _ _ (fun b hb => hx b (by simp only [hb, ha]))) + (fun a ha => same _ _ _ (fun b hb => hy b (by simp only [hb, ha]))) hu + · intro x y + simpa only [inj.eq_iff] using eval (fill x) (fill y) + +open scoped Classical in +/-- Parallel one-term packets need no selector. -/ +def Rule.parallelOne {S E J : A → Type} [∀ a, Fintype (S a)] + [∀ a, Fintype (E a)] [∀ a, Fintype (J a)] + {D : (a : A) → E a → S a × S a} {W : (a : A) → J a → S a × S a} + (h : ∀ a, Rule F (D a) (fun _ : Unit => W a)) : + Rule F (parallelDemand D) (fun _ : Unit => parallelDemand W) := by + obtain ⟨f, loc, eval⟩ := Rule.parallel h + refine ⟨fun _ => f default, fun _ => loc default, fun x y => ?_⟩ + simpa only [Fintype.sum_unique] using eval x y + +open scoped Classical in +/-- Exchange the two endpoints of every demand. -/ +def Rule.reverse (h : Rule F D W) : Rule F (fun a => ((D a).2, (D a).1)) W := by + obtain ⟨f, loc, eval⟩ := h + exact ⟨fun i v x y => f i v y x, + fun i v _ _ _ _ _ _ hx hy hu => loc i v _ _ _ _ _ _ hy hx hu, + fun x y => by simpa only [eq_comm (a := y)] using eval y x⟩ + +open scoped Classical in +/-- Join the two output legs of a pair of demands by one new supply +wire. The input legs become the endpoints of a single demand. -/ +def Rule.joinOutputs {a b : A × Bool → S} {W : B → S × S} + (h : Rule F (fun e => (a e, b e)) (fun _ : Unit => W)) : + Rule F (fun e => (a (e, false), a (e, true))) + (fun _ : Unit => Sum.elim W (fun e => (b (e, false), b (e, true)))) := by + obtain ⟨f, loc, eval⟩ := h + let pair (x y : A → Bool) (q : A × Bool) := if q.2 then y q.1 else x q.1 + have eq (x y z : A → Bool) : pair x y = z ∘ Prod.fst ↔ x = z ∧ y = z := by + refine ⟨fun he => ⟨funext fun e => congrFun he (e, false), funext fun e => congrFun he (e, + true)⟩, ?_⟩ + rintro ⟨rfl, rfl⟩ + funext ⟨e, t⟩ + cases t <;> rfl + refine ⟨fun _ v x y z => f () v (pair x y) (fun e => z (.inr e.1)) (z ∘ Sum.inl), ?_, ?_⟩ + · intro _ v x y z x' y' z' hx hy hz + apply loc + · rintro ⟨e, _|_⟩ he + · exact hx _ he + · exact hy _ he + · rintro ⟨e, _|_⟩ he + · exact hz (.inr e) (.inl he) + · exact hz (.inr e) (.inr he) + · exact fun e he => hz (.inl e) he + · intro x y + simp only [Fintype.sum_unique] + trans ∑ z : B ⊕ A → Bool, ∏ v, f () v (pair x y) (fun e => z (.inr e.1)) (z ∘ Sum.inl) + swap + · exact Finset.sum_congr (by ext; simp) (fun _ _ => rfl) + rw [← (Equiv.sumArrowEquivProdArrow B A Bool).symm.sum_comp, + Fintype.sum_prod_type, Finset.sum_comm] + change _ = ∑ z : A → Bool, ∑ u : B → Bool, ∏ v, f () v (pair x y) (z ∘ Prod.fst) u + simp only [Fintype.sum_unique] at eval + simp_rw [← eval, eq, ite_and] + simp [eq_comm] + +open scoped Classical in +/-- Reindex the supply of a one-term packet. -/ +def Rule.supplyEquiv {C : Type} [Fintype C] {W : B → S × S} + (h : Rule F D (fun _ : Unit => W)) (e : C ≃ B) : + Rule F D (fun _ : Unit => W ∘ e) := + h.suppliesEquiv (fun _ => e) + +open scoped Classical in +/-- Replace each single-bit wire by a bundle of independent bits. -/ +def Rule.bundle {W : B → S × S} (h : Rule F D (fun _ : Unit => W)) (b : ℕ) : + Rule F (fun a : A × Fin b => D a.1) (fun _ : Unit => fun z : B × Fin b => W z.1) := by + let read (C : Type) (x : C × Fin b → Bool) (i : Fin b) (j : C) := x (j, i) + refine ⟨fun _ v x y u => ∏ i : Fin b, h.entry () v (read _ x i) (read _ y i) (read _ u i), + ?_, ?_⟩ + · intro _ v x y u x' y' u' hx hy hu + apply Finset.prod_congr rfl + exact fun i _ => h.local' _ _ _ _ _ _ _ _ + (fun t ht => hx (t, i) ht) (fun t ht => hy (t, i) ht) (fun t ht => hu (t, i) ht) + · intro x y + let e : (B × Fin b → Bool) ≃ (Fin b → B → Bool) := + ((Equiv.prodComm _ _).arrowCongr (.refl _)).trans (Equiv.curry _ _ _) + have delta : (if x = y then (1 : F) else 0) = + ∏ i, if read _ x i = read _ y i then (1 : F) else 0 := by + by_cases he : x = y + · simp [he] + · rw [ite_eq_right he] + obtain ⟨⟨t, i⟩, hi⟩ := Function.ne_iff.mp he + symm + exact Finset.prod_eq_zero (Finset.mem_univ i) (ite_eq_right (fun he => hi (congrFun he t))) + simp only [Fintype.sum_unique] + rw [delta] + simp_rw [h.eval, Fintype.sum_unique] + rw [Fintype.prod_sum, ← e.sum_comp] + refine Finset.sum_congr (by ext; simp) (fun z _ => ?_) + rw [Finset.prod_comm] + rfl + +open scoped Classical in +theorem select (h : Packet F D W) (e : B ↪ A) : Packet F (fun a => D (e a)) W := + (Rule.select h.rule e).packet + +open scoped Classical in +theorem parallelOne {S E J : A → Type} [∀ a, Fintype (S a)] + [∀ a, Fintype (E a)] [∀ a, Fintype (J a)] + {D : (a : A) → E a → S a × S a} {W : (a : A) → J a → S a × S a} + (h : ∀ a, Packet F (D a) (fun _ : Unit => W a)) : + Packet F (parallelDemand D) (fun _ : Unit => parallelDemand W) := + (Rule.parallelOne (fun i => (h i).rule)).packet + +open scoped Classical in +theorem reverse (h : Packet F D W) : Packet F (fun a => ((D a).2, (D a).1)) W := + (Rule.reverse h.rule).packet + +open scoped Classical in +theorem joinOutputs {a b : A × Bool → S} {W : B → S × S} + (h : Packet F (fun e => (a e, b e)) (fun _ : Unit => W)) : + Packet F (fun e => (a (e, false), a (e, true))) + (fun _ : Unit => Sum.elim W (fun e => (b (e, false), b (e, true)))) := + (Rule.joinOutputs h.rule).packet + +open scoped Classical in +theorem supplyEquiv {C : Type} [Fintype C] {W : B → S × S} + (h : Packet F D (fun _ : Unit => W)) (e : C ≃ B) : + Packet F D (fun _ : Unit => W ∘ e) := + (Rule.supplyEquiv h.rule e).packet + +open scoped Classical in +theorem bundle {W : B → S × S} (h : Packet F D (fun _ : Unit => W)) (b : ℕ) : + Packet F (fun a : A × Fin b => D a.1) (fun _ : Unit => fun z : B × Fin b => W z.1) := + (Rule.bundle h.rule b).packet + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet +end + +/- # A wire packet from a partition of its demands -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet +open Finset + +variable {K S E X Y : Type} [Field K] [Fintype S] [Fintype E] [Fintype X] [Fintype Y] + +open Classical in +/-- Independent supply bits serve the selected demands and their complement. -/ +def Rule.partition (G : E → Prop) [DecidablePred G] + (D : E → S × S) {W : X → S × S} {U : Y → S × S} + (hf : Rule K (fun e : {i // G i} => D e.1) (fun _ : Unit => W)) + (hg : Rule K (fun e : {i // ¬ G i} => D e.1) (fun _ : Unit => U)) : + Rule K D (fun _ : Unit => Sum.elim W U) := by + obtain ⟨f, lf, sf⟩ := hf + obtain ⟨g, lg, sg⟩ := hg + let lo (x : E → Bool) (i : {i // G i}) := x i + let hi (x : E → Bool) (i : {i // ¬G i}) := x i + refine ⟨fun _ v x y u => f () v (lo x) (lo y) (u ∘ Sum.inl) * + g () v (hi x) (hi y) (u ∘ Sum.inr), ?_, ?_⟩ + · intro _ v x y u x' y' u' hx hy hu + refine congrArg₂ (· * ·) ?_ ?_ + · exact lf _ _ _ _ _ _ _ _ (fun e h => hx e.1 h) (fun e h => hy e.1 h) (fun e h + => hu (.inl e) h) + · exact lg _ _ _ _ _ _ _ _ (fun e h => hx e.1 h) (fun e h => hy e.1 h) (fun e h + => hu (.inr e) h) + · intro x y + have eq : x = y ↔ lo x = lo y ∧ hi x = hi y := by + refine ⟨fun h => ⟨congrArg lo h, congrArg hi h⟩, ?_⟩ + rintro ⟨hl, hr⟩ + funext e + by_cases he : G e + · exact congrFun hl ⟨e, he⟩ + · exact congrFun hr ⟨e, he⟩ + have delta : (if x = y then (1 : K) else 0) = + (if lo x = lo y then (1 : K) else 0) * (if hi x = hi y then (1 : K) else 0) := by + simp only [eq, ite_and, ite_mul, one_mul, zero_mul] + simp only [Fintype.sum_unique] at sf sg ⊢ + rw [delta, sf, sg, sum_mul_sum] + let H (z : X ⊕ Y → Bool) := ∏ v, f () v (lo x) (lo y) (z ∘ Sum.inl) * + g () v (hi x) (hi y) (z ∘ Sum.inr) + trans ∑ z, H z + swap + · exact sum_congr (by ext; simp) (fun _ _ => rfl) + rw [← (Equiv.sumArrowEquivProdArrow X Y Bool).symm.sum_comp, Fintype.sum_prod_type] + apply sum_congr rfl + intro u _ + apply sum_congr rfl + intro w _ + rw [← prod_mul_distrib] + rfl + +open Classical in +theorem partition (G : E → Prop) [DecidablePred G] + (D : E → S × S) {W : X → S × S} {U : Y → S × S} + (hf : Packet K (fun e : {i // G i} => D e.1) (fun _ : Unit => W)) + (hg : Packet K (fun e : {i // ¬ G i} => D e.1) (fun _ : Unit => U)) : + Packet K D (fun _ : Unit => Sum.elim W U) := + (Rule.partition G D hf.rule hg.rule).packet + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet +end + +/- # Orientation of individual wire demands -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet + +variable {F S E I : Type} [Field F] [Fintype S] [Fintype E] [Fintype I] + {J : I → Type} [∀ i, Fintype (J i)] {D : E → S × S} {W : (i : I) → J i → S × S} + +open scoped Classical in +/-- A demand is an equality test, so its two legs can be exchanged. -/ +theorem orient (h : Packet F D W) (t : E → Bool) : + Packet F (fun e => if t e then (D e).swap else D e) W := by + obtain ⟨f, loc, eval⟩ := h + let p (x y : E → Bool) (e : E) := if t e then y e else x e + have eq (x y : E → Bool) : p x y = p y x ↔ x = y := by + refine ⟨fun he => funext fun e => ?_, fun he => by rw [he]⟩ + have := congrFun he e + cases ht : t e + · simpa only [p, ht, Bool.false_eq_true, ite_false] using this + · simpa only [p, ht, ite_true] using this.symm + refine ⟨fun i v x y => f i v (p x y) (p y x), ?_, fun x y => ?_⟩ + · intro i v x y u x' y' u' hx hy hu + refine loc i v _ _ _ _ _ _ ?_ ?_ hu + · intro e he + cases ht : t e + · simpa [p, ht] using hx e (by simp [ht, he]) + · simpa [p, ht] using hy e (by simp [ht, he]) + · intro e he + cases ht : t e + · simpa [p, ht] using hy e (by simp [ht, he]) + · simpa [p, ht] using hx e (by simp [ht, he]) + · simpa only [eq] using eval (p x y) (p y x) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Place.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Place.lean new file mode 100644 index 0000000000..e3cb003ff5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Place.lean @@ -0,0 +1,568 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Restriction +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Data.Finset.Powerset +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Ring +public import Mathlib.Basic.Real.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Wire + +/-! +# Grouping local coordinates by a map of sites + +The grouped substitutions preserve membership in any fixed subring. +The ordinary restriction statements specialize to the full field. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S T : Type} [Field K] [Fintype S] [Fintype T] [DecidableEq S] [DecidableEq T] + +/-- The subtype of `t` satisfying `f t = s`. -/ +abbrev Fiber (f : T → S) (s : S) := {t // f t = s} + +/-- Builds `Raw K S where term` with the specified `term`, `leg`, `factor`. -/ +def group (f : T → S) (A : Raw K T) : Raw K S where + term := A.term + leg s := ∀ t : Fiber f s, A.leg t + factor i s x := ∏ t : Fiber f s, A.factor i t (x t) + +omit [DecidableEq T] in +private theorem fiber_prod (f : T → S) (v : ∀ s, Fiber f s → K) : + (∏ s, ∏ t, v s t) = ∏ t, v (f t) ⟨t, rfl⟩ := by + rw [← Fintype.prod_fiberwise f (fun t => v (f t) ⟨t, rfl⟩)] + refine Finset.prod_congr rfl fun s _ => Finset.prod_congr rfl fun t _ => ?_ + rcases t with ⟨t, rfl⟩ + rfl + +theorem coeff_group (f : T → S) (A : Raw K T) (x : ∀ s, (A.group f).leg s) : + (A.group f).coeff x = A.coeff (fun t => x (f t) ⟨t, rfl⟩) := by + refine Finset.sum_congr rfl fun i _ => ?_ + exact fiber_prod f (fun s t => A.factor i t (x s t)) + +theorem _root_.MatrixMultiplicationAllFields.MatrixExponent.Valued.Restricts.group {O : Subring K} + {A B : Raw K T} + (h : Valued.Restricts O A B) (f : T → S) : + Valued.Restricts O (A.group f) (B.group f) := by + obtain ⟨L, hL, h⟩ := h + let M (s : S) (x : (B.group f).leg s) (y : (A.group f).leg s) := + ∏ t : Fiber f s, L t (x t) (y t) + refine ⟨M, fun _ _ _ => O.prod_mem fun t _ => hL t _ _, fun x => ?_⟩ + have hw (i : A.term) (s : S) : + (∑ y, M s (x s) y * (A.group f).factor i s y) = + ∏ t : Fiber f s, ∑ y, L t (x s t) y * A.factor i t y := by + rw [Fintype.prod_sum] + refine Finset.sum_congr rfl fun y _ => ?_ + exact Finset.prod_mul_distrib.symm + rw [coeff_group, h] + refine Finset.sum_congr rfl fun i _ => ?_ + exact (fiber_prod f (fun s t => ∑ y, L t (x s t) y * A.factor i t y)).symm.trans + (Finset.prod_congr rfl fun s _ => (hw i s).symm) + +theorem Restricts.group {A B : Raw K T} (h : A.Restricts B) (f : T → S) : + (A.group f).Restricts (B.group f) := + ((Valued.top_restricts h).group f).forget + +omit [DecidableEq S] in +/-- A local coordinate may be copied from the source or set to zero. -/ +theorem _root_.MatrixMultiplicationAllFields.MatrixExponent.Valued.Restricts.rows {O : Subring K} + {A B : Raw K S} (e : B.term ≃ A.term) + (h : ∀ s x, (∃ y, ∀ i, B.factor i s x = A.factor (e i) s y) ∨ + (∀ i, B.factor i s x = 0)) : Valued.Restricts O A B := by + classical + have each s x : ∃ v : A.leg s → K, (∀ y, v y ∈ O) ∧ + ∀ i, B.factor i s x = ∑ y, v y * A.factor (e i) s y := by + rcases h s x with ⟨y, hy⟩ | hz + · exact ⟨fun z => if z = y then 1 else 0, fun z => by by_cases e : z = y <;> simp [e], + fun i => by simp [hy, ite_mul]⟩ + · exact ⟨fun _ => 0, fun _ => O.zero_mem, fun i => by simp [hz]⟩ + choose v hi hv using each + refine ⟨v, hi, fun x => ?_⟩ + rw [← e.sum_comp] + simp only [coeff, hv] + +omit [DecidableEq S] in +theorem Restricts.rows {A B : Raw K S} (e : B.term ≃ A.term) + (h : ∀ s x, (∃ y, ∀ i, B.factor i s x = A.factor (e i) s y) ∨ + (∀ i, B.factor i s x = 0)) : A.Restricts B := + (Valued.Restricts.rows (O := ⊤) e h).forget + +theorem integral_group_zero {O : Subring K} (f : T → S) : + (Valued.equiv O).r ((0 : Raw K T).group f) 0 := + ⟨.rows (Equiv.refl _) fun _ _ => Or.inr (fun i => Empty.elim i), + .rows (Equiv.refl _) fun _ _ => Or.inr (fun i => Empty.elim i)⟩ + +theorem group_zero (f : T → S) : (0 : Raw K T).group f ≈ 0 := + Valued.forget_equiv (integral_group_zero (O := ⊤) f) + +theorem integral_group_one {O : Subring K} (f : T → S) : + (Valued.equiv O).r ((1 : Raw K T).group f) 1 := by + refine Valued.relabel (Equiv.refl _) (fun s => Equiv.ofUnique (Fiber f s → Unit) Unit) ?_ + exact fun i s x => Finset.prod_const_one + +theorem group_one (f : T → S) : (1 : Raw K T).group f ≈ 1 := + Valued.forget_equiv (integral_group_one (O := ⊤) f) + +theorem integral_group_mul {O : Subring K} (f : T → S) (A B : Raw K T) : + (Valued.equiv O).r ((A * B).group f) (A.group f * B.group f) := by + let g (s : S) : ((A * B).group f).leg s ≃ (A.group f * B.group f).leg s := + { toFun := fun x => (fun t => (x t).1, fun t => (x t).2) + invFun := fun x t => (x.1 t, x.2 t) + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + exact Valued.relabel (Equiv.refl _) g fun _ _ _ => Finset.prod_mul_distrib + +theorem group_mul (f : T → S) (A B : Raw K T) : + (A * B).group f ≈ A.group f * B.group f := + Valued.forget_equiv (integral_group_mul (O := ⊤) f A B) + +/-- On each nonempty fiber, mixed blocks give zero rows. -/ +theorem integral_group_add {O : Subring K} (f : T → S) (hf : Function.Surjective f) (A B : Raw K T) + : + (Valued.equiv O).r ((A + B).group f) (A.group f + B.group f) := by + classical + let X := (A + B).group f + let Y := A.group f + B.group f + let inc (s : S) : Y.leg s → X.leg s := + Sum.elim (fun x t => .inl (x t)) (fun x t => .inr (x t)) + have matchRows (s : S) (x : Y.leg s) (i : Y.term) : + Y.factor i s x = X.factor i s (inc s x) := by + obtain ⟨t, ht⟩ := hf s + rcases i with i | i <;> rcases x with x | x + · rfl + · exact (Finset.prod_eq_zero (Finset.mem_univ (⟨t, ht⟩ : Fiber f s)) rfl).symm + · exact (Finset.prod_eq_zero (Finset.mem_univ (⟨t, ht⟩ : Fiber f s)) rfl).symm + · rfl + change (Valued.equiv O).r X Y + refine ⟨.rows (Equiv.refl _) (fun s x => .inl ⟨inc s x, matchRows s x⟩), + .rows (Equiv.refl _) fun s x => ?_⟩ + by_cases hz : ∀ i, X.factor i s x = 0 + · exact Or.inr hz + obtain ⟨i, hi⟩ := not_forall.mp hz + suffices ∃ y, inc s y = x by + obtain ⟨y, rfl⟩ := this + exact Or.inl ⟨y, fun j => (matchRows s y j).symm⟩ + have each (t : Fiber f s) : (A + B).factor i t (x t) ≠ 0 := + fun h => hi (Finset.prod_eq_zero (Finset.mem_univ t) h) + rcases i with i | i + · have h (t : Fiber f s) : ∃ y, Sum.inl y = x t := by + have hh := each t + cases hx : x t with + | inl y => exact ⟨y, rfl⟩ + | inr y => exact False.elim (hh (by rw [hx]; rfl)) + choose y hy using h + exact ⟨.inl y, funext hy⟩ + · have h (t : Fiber f s) : ∃ y, Sum.inr y = x t := by + have hh := each t + cases hx : x t with + | inl y => exact False.elim (hh (by rw [hx]; rfl)) + | inr y => exact ⟨y, rfl⟩ + choose y hy using h + exact ⟨.inr y, funext hy⟩ + +theorem group_add (f : T → S) (hf : Function.Surjective f) (A B : Raw K T) : + (A + B).group f ≈ A.group f + B.group f := + Valued.forget_equiv (integral_group_add (O := ⊤) f hf A B) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S T : Type} [Field K] [Fintype S] [Fintype T] [DecidableEq S] [DecidableEq T] + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def group (f : T → S) (hf : Function.Surjective f) : Tensor K T →+* Tensor K S where + toFun := Quotient.map (Raw.group f) fun _ _ h => ⟨h.1.group f, h.2.group f⟩ + map_zero' := ofRaw_eq (Raw.group_zero f) + map_one' := ofRaw_eq (Raw.group_one f) + map_mul' A B := Quotient.inductionOn₂ A B fun a b => ofRaw_eq (Raw.group_mul f a b) + map_add' A B := Quotient.inductionOn₂ A B fun a b => ofRaw_eq (Raw.group_add f hf a b) + +theorem group_ofRaw (f : T → S) (hf : Function.Surjective f) (A : Raw K T) : + group f hf (ofRaw A) = ofRaw (A.group f) := rfl + +theorem group_mono (f : T → S) (hf : Function.Surjective f) : + Monotone (group (K := K) f hf) := + fun A B => Quotient.inductionOn₂ A B fun _ _ h => Raw.Restricts.group h f + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- +# Averaging quadrilateral inequalities on a binary cube + +Apply the square bound at every translate and sum. Each side and each +diagonal then occurs twice. Recurse by halving the flipped coordinate set. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +/-- The indexing data represented by `Fin n → Bool`. -/ +abbrev Cube (n : ℕ) := Fin n → Bool + +namespace Cube + +variable {n : ℕ} + +/-- Evaluates `if i ∈ J then !(x i) else x i` at the input `i`. -/ +def flip (J : Finset (Fin n)) (x : Cube n) : Cube n := + fun i => if i ∈ J then !(x i) else x i + +@[simp] theorem flip_flip (J : Finset (Fin n)) (x : Cube n) : flip J (flip J x) = x := by + funext i + by_cases h : i ∈ J <;> simp [flip, h] + +theorem flip_union {I J : Finset (Fin n)} (h : Disjoint I J) (x : Cube n) : + flip (I ∪ J) x = flip I (flip J x) := by + funext i + by_cases hi : i ∈ I + · simp [flip, hi, Finset.disjoint_left.mp h hi] + · simp [flip, hi] + +private theorem sum_flip (J : Finset (Fin n)) (f : Cube n → ℝ) : + ∑ x, f (flip J x) = ∑ x, f x := + Equiv.sum_comp (⟨flip J, flip J, flip_flip J, flip_flip J⟩ : Equiv.Perm (Cube n)) f + +variable (d : Cube n → Cube n → ℝ) {κ : ℝ} +variable (hs : ∀ a b c e, (d a c) ^ 2 + (d b e) ^ 2 ≤ + κ * ((d a b) ^ 2 + (d b c) ^ 2 + (d c e) ^ 2 + (d e a) ^ 2)) + +/-- The sum of `(d x (flip J x)) ^ 2` indexed by `x`. -/ +def energy (J : Finset (Fin n)) : ℝ := ∑ x, (d x (flip J x)) ^ 2 + +include hs in +private theorem energy_split {I J : Finset (Fin n)} (h : Disjoint I J) : + energy d (I ∪ J) ≤ κ * (energy d I + energy d J) := by + let f (I : Finset (Fin n)) (x : Cube n) := (d x (flip I x)) ^ 2 + have bound (x : Cube n) : + f (I ∪ J) x + f (I ∪ J) (flip I x) ≤ + κ * (f I x + f J (flip I x) + f I (flip (I ∪ J) x) + f J (flip J x)) := by + have hj : flip (I ∪ J) (flip I x) = flip J x := by + rw [Finset.union_comm, flip_union h.symm, flip_flip] + have hi : flip I (flip (I ∪ J) x) = flip J x := by rw [flip_union h, flip_flip] + have hu : flip J (flip I x) = flip (I ∪ J) x := by rw [← flip_union h.symm, Finset.union_comm] + simp only [f, hj, hi, hu, flip_flip] + exact hs _ _ _ _ + have H := Finset.sum_le_sum (s := Finset.univ) (fun x _ => bound x) + simp only [Finset.sum_add_distrib, ← Finset.mul_sum, sum_flip] at H + change energy d (I ∪ J) + energy d (I ∪ J) ≤ + κ * (energy d I + energy d J + energy d I + energy d J) at H + linarith + +include hs in +theorem energy_bound (hk : 0 ≤ κ) {m : ℝ} + (he : ∀ x i, (d x (flip {i} x)) ^ 2 ≤ m) (k : ℕ) + (J : Finset (Fin n)) (hJ : J.card = 2 ^ k) : + energy d J ≤ (2 * κ) ^ k * Fintype.card (Cube n) * m := by + induction k generalizing J with + | zero => + obtain ⟨i, rfl⟩ := Finset.card_eq_one.mp hJ + simpa [energy] using Finset.sum_le_sum (s := Finset.univ) (fun x _ => he x i) + | succ k ih => + rw [pow_succ] at hJ + obtain ⟨I, hi, hI⟩ := Finset.exists_subset_card_eq (show 2 ^ k ≤ J.card by omega) + have hr : (J \ I).card = 2 ^ k := by rw [Finset.card_sdiff_of_subset hi]; omega + calc + energy d J = energy d (I ∪ (J \ I)) := by rw [Finset.union_sdiff_of_subset hi] + _ ≤ κ * (energy d I + energy d (J \ I)) := energy_split d hs Finset.disjoint_sdiff + _ ≤ κ * ((2 * κ) ^ k * Fintype.card (Cube n) * m + (2 * κ) ^ k * Fintype.card (Cube n) * m) := + mul_le_mul_of_nonneg_left (add_le_add (ih I hI) (ih _ hr)) hk + _ = _ := by ring + +end Cube +end MatrixMultiplicationAllFields.MatrixExponent.Spectral +end + +/- # A connected wire graph supplies a common binary label -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable (K : Type) [Field K] {S I : Type} [Fintype S] [DecidableEq S] [Nonempty S] [Fintype I] + +theorem connected (A B : I → S) + (h : ∀ U : Finset S, U.Nonempty → U ≠ Finset.univ → ∃ i, A i ∈ U ∧ B i ∉ U) : + (2 : Tensor K S) ≤ ∏ i, wire K (A i) (B i) 2 := by + classical + let P (U : Finset S) := U.Nonempty ∧ ∃ E : Finset I, + (∀ i ∈ E, B i ∈ U) ∧ shared K U 2 ≤ ∏ i ∈ E, wire K (A i) (B i) 2 + have hi : ∃ U, P U := by + let a := Classical.arbitrary S + refine ⟨{a}, by simp, ∅, by simp, ?_⟩ + have hsingle : shared K {a} 2 = 1 := by + simpa [wire] using wire_self K a (n := 2) (by decide) + rw [hsingle, Finset.prod_empty] + obtain ⟨U, ⟨hne, E, hE, hU⟩, hmax⟩ := Set.Finite.exists_maximal (Set.toFinite {U | P U}) hi + have hu : U = Finset.univ := by + by_contra hu + obtain ⟨i, ha, hb⟩ := h U hne hu + have fresh : i ∉ E := fun hk => hb (hE i hk) + have ext : P (insert (B i) U) := by + refine ⟨by simp, insert i E, ?_, ?_⟩ + · intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · simp + · exact Finset.mem_insert_of_mem (hE _ hj) + · rw [Finset.prod_insert fresh] + have step := shared_join K (U := {A i, B i}) (by simp) ha 2 + rw [show ({A i, B i} : Finset S) ∪ U = insert (B i) U by simp [ha]] at step + exact step.trans (mul_le_mul_left _ _ _ hU) + exact hb (hmax ext (Finset.subset_insert _ _) (Finset.mem_insert_self _ _)) + rw [hu, shared_all, Nat.cast_ofNat] at hU + let : MulLeftMono (Tensor K S) := ⟨fun c a b h => mul_le_mul_left a b c h⟩ + exact hU.trans (Finset.prod_le_prod_of_subset_of_one_le (Finset.subset_univ _) + (fun _ _ _ => one_le_wire K _ _ (by decide))) + +theorem cube_connected (n : ℕ) : + (2 : Tensor K (Cube n)) ≤ ∏ i : Cube n × Fin n, wire K i.1 (Cube.flip {i.2} i.1) 2 := by + apply connected + intro U ⟨x, hx⟩ hU + by_contra! bad + have closed (J : Finset (Fin n)) : Cube.flip J x ∈ U := by + induction J using Finset.induction_on with + | empty => rw [show Cube.flip ∅ x = x by funext i; simp [Cube.flip]]; exact hx + | insert i J hi ih => + rw [← Finset.singleton_union, Cube.flip_union (by simp [hi])] + exact bad (Cube.flip J x, i) ih + apply hU + apply Finset.eq_univ_of_forall + intro y + let J := Finset.univ.filter (fun i => x i ≠ y i) + have he : Cube.flip J x = y := by + funext i + cases h₁ : x i <;> cases h₂ : y i <;> simp [J, Cube.flip, h₁, h₂] + exact he ▸ closed J + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- +# Grouping trivial sites and shared labels +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +variable {K S T : Type} [Field K] [Fintype S] [Fintype T] [DecidableEq S] [DecidableEq T] + +namespace Raw + +theorem group_pad (f : S ⊕ T → S) (h : ∀ s, f (.inl s) = s) (A : Raw K S) : + (pad T A).group f ≈ A := by + let src (s : S) : Fiber f s := ⟨.inl s, h s⟩ + let B := (pad T A).group f + let get (s : S) (x : B.leg s) : A.leg s := x (src s) + have hg (s : S) : Function.Surjective (get s) := by + intro x + let y : B.leg s := fun t => match t with + | ⟨.inl u, hu⟩ => ((h u).symm.trans hu).symm ▸ x + | ⟨.inr _, _⟩ => () + exact ⟨y, rfl⟩ + have he (s : S) (x : B.leg s) (i : A.term) : B.factor i s x = A.factor i s (get s x) := by + change (∏ t : Fiber f s, (pad T A).factor i t (x t)) = _ + rw [Fintype.prod_eq_single (src s)] + · rfl + · rintro ⟨u | u, hu⟩ hn + · exact False.elim (hn (Subtype.ext (congrArg Sum.inl ((h u).symm.trans hu)))) + · rfl + change B ≈ A + refine ⟨.rows (Equiv.refl _) (fun s x => ?_), .rows (Equiv.refl _) fun s x => .inl ⟨_, he s x⟩⟩ + obtain ⟨y, rfl⟩ := hg s x + exact .inl ⟨y, fun i => (he s y i).symm⟩ + +omit [DecidableEq S] in +private theorem label_rows {A B : Raw K S} [∀ s, DecidableEq (A.leg s)] + [∀ s, DecidableEq (B.leg s)] (e : B.term ≃ A.term) + (a : ∀ s, A.term → A.leg s) (b : ∀ s, B.term → B.leg s) + (ha : ∀ i s x, A.factor i s x = if x = a s i then 1 else 0) + (hb : ∀ i s x, B.factor i s x = if x = b s i then 1 else 0) + (h : ∀ s i j, b s i = b s j ↔ a s (e i) = a s (e j)) : A.Restricts B := by + refine Restricts.rows e fun s x => ?_ + by_cases hx : ∃ i, x = b s i + · obtain ⟨i, rfl⟩ := hx + exact .inl ⟨a s (e i), fun j => by simp only [ha, hb, h]⟩ + · exact .inr (fun i => by rw [hb, ite_eq_right (fun hi => hx ⟨i, hi⟩)]) + +theorem group_shared (f : T → S) (U : Finset T) (n : ℕ) : + (shared K U n).group f ≈ shared K (U.image f) n := by + classical + let A := (shared K U n).group f + let B := shared K (U.image f) n + let a (s : S) (i : Fin n) (t : Fiber f s) := port U t.val i + let b (s : S) (i : Fin n) := port (U.image f) s i + have ha (i : Fin n) (s : S) (x : Fiber f s → Fin n) : + A.factor i s x = if x = a s i then 1 else 0 := by + change (∏ t, if x t = a s i t then (1 : K) else 0) = _ + by_cases e : x = a s i + · simp [e] + · obtain ⟨t, ht⟩ := Function.ne_iff.mp e + rw [ite_eq_right e] + exact Finset.prod_eq_zero (Finset.mem_univ t) (ite_eq_right ht) + have hb (i : Fin n) (s : S) (x : Fin n) : + B.factor i s x = if x = b s i then 1 else 0 := rfl + have hl (s : S) (i j : Fin n) : b s i = b s j ↔ a s i = a s j := by + by_cases hs : s ∈ U.image f + · obtain ⟨t, ht, he⟩ := Finset.mem_image.mp hs + simp only [b, port, ite_eq_left hs] + refine ⟨fun h => congrArg _ h, fun h => ?_⟩ + simpa [a, port, ht] using congrFun h ⟨t, he⟩ + · have hz (t : Fiber f s) : t.val ∉ U := + fun h => hs (Finset.mem_image.mpr ⟨t, h, t.property⟩) + exact iff_of_true (by simp only [b, port, ite_eq_right hs]) (by funext t; simp [a, port, hz]) + let _ : ∀ s, DecidableEq (A.leg s) := fun s => (inferInstance : DecidableEq (Fiber f s → Fin n)) + let _ : ∀ s, DecidableEq (B.leg s) := fun _ => (inferInstance : DecidableEq (Fin n)) + change A ≈ B + exact ⟨label_rows (Equiv.refl _) a b ha hb hl, + label_rows (Equiv.refl _) b a hb ha (fun s i j => (hl s i j).symm)⟩ + +end Raw + +namespace Tensor + +theorem group_pad [Nonempty S] (f : S ⊕ T → S) (hf : Function.Surjective f) + (h : ∀ s, f (.inl s) = s) (A : Tensor K S) : + group f hf (pad T A) = A := + Quotient.inductionOn A fun a => ofRaw_eq (Raw.group_pad f h a) + +theorem group_shared (f : T → S) (hf : Function.Surjective f) (U : Finset T) (n : ℕ) : + group f hf (shared K U n) = shared K (U.image f) n := + ofRaw_eq (Raw.group_shared f U n) + +theorem group_wire (f : T → S) (hf : Function.Surjective f) (a b : T) (n : ℕ) : + group f hf (wire K a b n) = wire K (f a) (f b) n := by + simpa [wire] using group_shared (K := K) f hf {a, b} n + +end Tensor +end MatrixMultiplicationAllFields.MatrixExponent.Spectral +end + +/- +# Arbitrary placements + +Sites outside the image have trivial legs. Placement is multiplicative +and functorial. Additivity is only used for surjective site maps. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +variable {K S T R : Type} [Field K] [Fintype S] [Fintype T] [Fintype R] + [DecidableEq S] [DecidableEq T] [DecidableEq R] + +namespace Raw + +theorem integral_group_id {O : Subring K} (A : Raw K S) : + (Valued.equiv O).r (A.group id) A := by + constructor + · refine .pullback (fun s x t => cast (congrArg A.leg t.property.symm) x) fun x => ?_ + erw [coeff_group] + rfl + · exact .pullback (fun s x => x ⟨s, rfl⟩) (coeff_group id A) + +theorem group_id (A : Raw K S) : A.group id ≈ A := + Valued.forget_equiv (integral_group_id (O := ⊤) A) + +theorem integral_group_comp {O : Subring K} (f : T → S) (g : R → T) (A : Raw K R) : + (Valued.equiv O).r (A.group (f ∘ g)) ((A.group g).group f) := by + constructor + · refine .pullback (fun s x t => x ⟨g t, t.property⟩ ⟨t, rfl⟩) fun x => ?_ + erw [coeff_group, coeff_group, coeff_group] + rfl + · refine .pullback (fun s x t r => x ⟨r, (congrArg f r.property).trans t.property⟩) + fun x => ?_ + erw [coeff_group, coeff_group, coeff_group] + rfl + +theorem group_comp (f : T → S) (g : R → T) (A : Raw K R) : + A.group (f ∘ g) ≈ (A.group g).group f := + Valued.forget_equiv (integral_group_comp (O := ⊤) f g A) + +theorem integral_group_inl {O : Subring K} (A : Raw K S) : + (Valued.equiv O).r (A.group (Sum.inl : S → S ⊕ T)) (A.pad T) := by + let f : S → S ⊕ T := Sum.inl + let F (s : S ⊕ T) (x : (A.pad T).leg s) : (A.group f).leg s := + fun t => cast (congrArg (pad T A).leg t.property.symm) x + let G (s : S ⊕ T) : (A.group f).leg s → (A.pad T).leg s := + match s with + | .inl a => fun x => x ⟨a, rfl⟩ + | .inr _ => fun _ => () + constructor + · refine .pullback F fun x => ?_ + rw [pad_coeff, coeff_group] + rfl + · refine .pullback G fun x => ?_ + rw [coeff_group, pad_coeff] + +theorem group_inl (A : Raw K S) : A.group (Sum.inl : S → S ⊕ T) ≈ A.pad T := + Valued.forget_equiv (integral_group_inl (O := ⊤) A) + +end Raw + +namespace Tensor + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def place (f : T → S) : Tensor K T → Tensor K S := + Quotient.map (Raw.group f) fun _ _ h => ⟨h.1.group f, h.2.group f⟩ + +theorem place_ofRaw (f : T → S) (A : Raw K T) : + place f (ofRaw A) = ofRaw (A.group f) := rfl + +theorem place_eq_group (f : T → S) (hf : Function.Surjective f) (A : Tensor K T) : + place f A = group f hf A := rfl + +theorem place_mono (f : T → S) : Monotone (place (K := K) f) := + fun A B => Quotient.inductionOn₂ A B fun _ _ h => Raw.Restricts.group h f + +theorem place_zero (f : T → S) : place f (0 : Tensor K T) = 0 := ofRaw_eq (Raw.group_zero f) +theorem place_one (f : T → S) : place f (1 : Tensor K T) = 1 := ofRaw_eq (Raw.group_one f) + +theorem place_mul (f : T → S) (A B : Tensor K T) : + place f (A * B) = place f A * place f B := + Quotient.inductionOn₂ A B fun a b => ofRaw_eq (Raw.group_mul f a b) + +theorem place_id (A : Tensor K S) : place id A = A := + Quotient.inductionOn A fun a => ofRaw_eq (Raw.group_id a) + +theorem place_comp (f : T → S) (g : R → T) (A : Tensor K R) : + place (f ∘ g) A = place f (place g A) := + Quotient.inductionOn A fun a => ofRaw_eq (Raw.group_comp f g a) + +theorem place_inl [Nonempty S] (A : Tensor K S) : + place (Sum.inl : S → S ⊕ T) A = pad T A := + Quotient.inductionOn A fun a => ofRaw_eq (Raw.group_inl a) + +theorem place_add_le [Nonempty T] (f : T → S) (A B : Tensor K T) : + place f (A + B) ≤ place f A + place f B := by + let g : T ⊕ S → S := Sum.elim f id + have hg : Function.Surjective g := fun s => ⟨.inr s, rfl⟩ + have he (X : Tensor K T) : place f X = group g hg (pad S X) := by + rw [← place_eq_group, ← place_inl, ← place_comp] + rfl + rw [he, he, he, ← (group g hg).map_add] + exact group_mono g hg ((padding S).add_le A B) + +theorem place_shared (f : T → S) (U : Finset T) (n : ℕ) : + place f (shared K U n) = shared K (U.image f) n := + ofRaw_eq (Raw.group_shared f U n) + +theorem place_wire (f : T → S) (a b : T) (n : ℕ) : + place f (wire K a b n) = wire K (f a) (f b) n := by + simpa [wire] using place_shared (K := K) f {a, b} n + +end Tensor +end MatrixMultiplicationAllFields.MatrixExponent.Spectral +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Placements.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Placements.lean new file mode 100644 index 0000000000..638d2b76d6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Placements.lean @@ -0,0 +1,466 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rank +public import Mathlib.LinearAlgebra.Dual.Lemmas +public import Mathlib.RingTheory.Jacobson.Ring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Extension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Transport + +/-! +# Mapping tensor coefficients + +A semiring homomorphism acts entrywise on both tensor factors and local +restriction matrices. It therefore induces a monotone semiring homomorphism. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +variable {K L S : Type} [CommSemiring K] [CommSemiring L] [Fintype S] + +namespace Raw + +/-- Uses `⟨A.leg, A.term, fun i s x => f (A.factor i s x)⟩` as the representation. -/ +def map (A : Raw K S) (f : K →+* L) : Raw L S := + ⟨A.leg, A.term, fun i s x => f (A.factor i s x)⟩ + +@[simp] theorem coeff_map (A : Raw K S) (f : K →+* L) (x : ∀ s, A.leg s) : + (A.map f).coeff x = f (A.coeff x) := by + change (∑ i : A.term, ∏ s, f (A.factor i s (x s))) = _ + simp only [coeff, map_sum, map_prod] + +/-- Apply the same coefficient homomorphism to the entries of every local matrix. -/ +def mapRestrictionMaps {A B : Raw K S} (P : RestrictionMaps A B) (f : K →+* L) : + RestrictionMaps (A.map f) (B.map f) := fun s x y => f (P s x y) + +theorem coeff_mapRestrictionMaps {A B : Raw K S} (P : RestrictionMaps A B) (f : K →+* L) + (h : ∀ x, B.coeff x = ∑ i : A.term, ∏ s, ∑ y, P s (x s) y * A.factor i s y) + (x : ∀ s, (B.map f).leg s) : + (B.map f).coeff x = ∑ i : (A.map f).term, ∏ s, + ∑ y, mapRestrictionMaps P f s (x s) y * (A.map f).factor i s y := by + change ∀ s, B.leg s at x + change (B.map f).coeff x = ∑ i : A.term, ∏ s, ∑ y, f (P s (x s) y) * f (A.factor i s y) + rw [coeff_map, h] + simp only [map_sum, map_prod, map_mul] + +theorem Restricts.map {A B : Raw K S} (h : A.Restricts B) (f : K →+* L) : + (A.map f).Restricts (B.map f) := by + obtain ⟨P, hP⟩ := h + exact ⟨mapRestrictionMaps P f, coeff_mapRestrictionMaps P f hP⟩ + +omit [Fintype S] in +theorem map_zero_relabels (f : K →+* L) : Relabels ((0 : Raw K S).map f) 0 := + ⟨Equiv.refl _, fun _ => Equiv.refl _, fun i => Empty.elim i⟩ + +omit [Fintype S] in +theorem map_one_relabels (f : K →+* L) : Relabels ((1 : Raw K S).map f) 1 := + ⟨Equiv.refl _, fun _ => Equiv.refl _, fun _ _ _ => map_one f⟩ + +omit [Fintype S] in +theorem map_mul_relabels (f : K →+* L) (A B : Raw K S) : + Relabels ((A * B).map f) (A.map f * B.map f) := + ⟨Equiv.refl _, fun _ => Equiv.refl _, fun _ _ _ => map_mul f _ _⟩ + +omit [Fintype S] in +theorem map_add_relabels (f : K →+* L) (A B : Raw K S) : + Relabels ((A + B).map f) (A.map f + B.map f) := by + refine ⟨Equiv.refl _, fun _ => Equiv.refl _, ?_⟩ + rintro (i | i) s (x | x) + · rfl + · exact map_zero f + · exact map_zero f + · rfl + +end Raw + +namespace Tensor + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def map (f : K →+* L) : Tensor K S →+* Tensor L S where + toFun := Quotient.map (fun A => A.map f) fun _ _ h => ⟨h.1.map f, h.2.map f⟩ + map_zero' := ofRaw_eq (Raw.relabel_of_relabels (Raw.map_zero_relabels f)) + map_one' := ofRaw_eq (Raw.relabel_of_relabels (Raw.map_one_relabels f)) + map_mul' X Y := Quotient.inductionOn₂ X Y fun A B => + ofRaw_eq (Raw.relabel_of_relabels (Raw.map_mul_relabels f A B)) + map_add' X Y := Quotient.inductionOn₂ X Y fun A B => + ofRaw_eq (Raw.relabel_of_relabels (Raw.map_add_relabels f A B)) + +@[simp] theorem map_ofRaw (f : K →+* L) (A : Raw K S) : + map f (ofRaw A) = ofRaw (A.map f) := rfl + +theorem map_mono (f : K →+* L) : Monotone (map (S := S) f) := + fun X Y => Quotient.inductionOn₂ X Y fun _ _ h => Raw.Restricts.map h f + +end Tensor +end MatrixMultiplicationAllFields.MatrixExponent.Spectral +end + +/- +# Descent of restriction along a finite field extension + +One extra diagonal label records one basis index at every site. Its +dimension depends on the field and the sites, and stays fixed even as +the local dimensions grow under tensor powers. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K L S : Type} [Field K] [Field L] [Algebra K L] [Fintype S] + +private theorem project_prod [DecidableEq S] {d : ℕ} (b : Module.Basis (Fin d) K L) + (π : L →ₗ[K] K) (v : S → L) : + π (∏ s, v s) = ∑ j : S → Fin d, (∏ s, b.repr (v s) (j s)) * π (∏ s, b (j s)) := by + have e : (∏ s, v s) = ∏ s, ∑ i, b.repr (v s) i • b i := + Finset.prod_congr rfl fun s _ => (b.sum_repr _).symm + rw [e, Fintype.prod_sum, map_sum] + refine Finset.sum_congr rfl fun j _ => ?_ + simp only [Algebra.smul_def, Finset.prod_mul_distrib, ← map_prod] + rw [← Algebra.smul_def, map_smul, smul_eq_mul] + +private theorem repr_sum {d : ℕ} (b : Module.Basis (Fin d) K L) (j : Fin d) + {X : Type} [Fintype X] (u : X → L) (v : X → K) : + b.repr (∑ y, u y * algebraMap K L (v y)) j = ∑ y, b.repr (u y) j * v y := by + rw [map_sum, Finsupp.finsetSum_apply] + refine Finset.sum_congr rfl fun y _ => ?_ + rw [mul_comm, ← Algebra.smul_def, map_smul, Finsupp.smul_apply, smul_eq_mul, mul_comm] + +open Classical in +theorem descend [Nonempty S] [Module.Finite K L] {A B : Raw K S} + (h : (A.map (algebraMap K L)).Restricts (B.map (algebraMap K L))) : + (diag K S (S → Fin (Module.finrank K L)) * A).Restricts B := by + classical + obtain ⟨P, hP⟩ := h + change (s : S) → B.leg s → A.leg s → L at P + obtain ⟨π, hπ⟩ := Module.Projective.exists_dual_eq_one K (one_ne_zero : (1 : L) ≠ 0) + have hbase (c : K) : π (algebraMap K L c) = c := by + rw [Algebra.algebraMap_eq_smul_one, map_smul, hπ, smul_eq_mul, mul_one] + let b := Module.finBasis K L + let J := S → Fin (Module.finrank K L) + let w (j : J) (s : S) := if s = Classical.arbitrary S then π (∏ a, b (j a)) else 1 + let Q (s : S) (x : B.leg s) (z : J × A.leg s) := + b.repr (P s x z.2) (z.1 s) * w z.1 s + have localSum (i : A.term) (j : J) (s : S) (x : B.leg s) : + (∑ z : J × A.leg s, Q s x z * ((if z.1 = j then 1 else 0) * A.factor i s z.2)) = + b.repr (∑ y, P s x y * algebraMap K L (A.factor i s y)) (j s) * w j s := by + rw [repr_sum, Finset.sum_mul, Fintype.sum_prod_type, Finset.sum_comm] + simp [Q, J, mul_ite, ite_mul, mul_right_comm] + refine ⟨Q, fun x => ?_⟩ + have hh : algebraMap K L (B.coeff x) = + ∑ i : A.term, ∏ s, ∑ y : A.leg s, P s (x s) y * algebraMap K L (A.factor i s y) := + (B.coeff_map _ x).symm.trans (hP x) + rw [← hbase (B.coeff x), hh, map_sum] + change _ = ∑ t : J × A.term, ∏ s, ∑ z : J × A.leg s, Q s (x s) z * + ((if z.1 = t.1 then 1 else 0) * A.factor t.2 s z.2) + rw [Fintype.sum_prod_type, Finset.sum_comm] + refine Finset.sum_congr rfl fun i _ => ?_ + rw [project_prod b π] + refine Finset.sum_congr rfl fun j _ => ?_ + simp only [localSum, Finset.prod_mul_distrib] + simp [w] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +section +/- +# Specializing a tensor restriction + +The equations in the local matrix entries have coefficients in the base +field. A maximal ideal containing the kernel of evaluation preserves all +the equations simultaneously. Its residue field is a finite extension by +Zariski's lemma. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K L S : Type} [Field K] [Field L] [Algebra K L] [Fintype S] + +theorem specialize {A B : Raw K S} + (h : (A.map (algebraMap K L)).Restricts (B.map (algebraMap K L))) : + ∃ (E : Type) (_ : Field E) (_ : Algebra K E) (_ : Module.Finite K E), + (A.map (algebraMap K E)).Restricts (B.map (algebraMap K E)) := by + classical + obtain ⟨M, hM⟩ := h + change (s : S) → B.leg s → A.leg s → L at M + let R := MvPolynomial (Σ s, B.leg s × A.leg s) K + let X (s : S) (x : B.leg s) (y : A.leg s) : R := MvPolynomial.X ⟨s, x, y⟩ + let f : R →ₐ[K] L := MvPolynomial.aeval (fun t => M t.1 t.2.1 t.2.2) + obtain ⟨m, hm, hker⟩ := Ideal.exists_le_maximal (RingHom.ker f.toRingHom) + (RingHom.ker_ne_top f.toRingHom) + let : Field (R ⧸ m) := Ideal.Quotient.field m + let g := Ideal.Quotient.mkₐ K m + refine ⟨R ⧸ m, inferInstance, inferInstance, finite_of_finite_type_of_isJacobsonRing K _, + fun s x y => g (X s x y), fun x => ?_⟩ + let t : R := ∑ i : B.term, ∏ s, algebraMap K R (B.factor i s (x s)) + let d : R := ∑ i : A.term, ∏ s, ∑ y : A.leg s, X s (x s) y * algebraMap K R (A.factor i s y) + have hf : f t = f d := by + simp only [t, d, map_sum, map_prod, map_mul, AlgHom.commutes] + simp only [f, X, R, MvPolynomial.aeval_X] + exact hM x + have hg : g t = g d := Ideal.Quotient.eq.mpr (hker (by + change f (t - d) = 0 + rw [map_sub, hf, sub_self])) + simp only [t, d, map_sum, map_prod, map_mul, AlgHom.commutes] at hg + exact hg + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +/- +# Extension of spectral points under extension of scalars + +One restriction specializes to a single finite extension. All powers +then descend with the same overhead, so every spectral point respects +the new comparison. Compact spectral extension yields agreement on +every tensor over the base field simultaneously. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +open scoped NNReal + +variable {K S : Type} [Field K] [Fintype S] + +theorem powers_le {A B : Tensor K S} (h : A ≤ B) (r : ℕ) : A ^ r ≤ B ^ r := by + induction r with + | zero => simp + | succ r ih => + rw [pow_succ, pow_succ'] + exact (mul_le_mul_left A B _ h).trans (by + rw [mul_comm] + exact mul_le_mul_left _ _ B ih) + +variable [Nonempty S] {L : Type} [Field L] [Algebra K L] + +private theorem finite_descent [Module.Finite K L] (A B : Tensor K S) + (h : map (algebraMap K L) A ≤ map (algebraMap K L) B) : + A ≤ ((Module.finrank K L ^ Fintype.card S : ℕ) : Tensor K S) * B := by + classical + revert h + refine Quotient.inductionOn₂ A B fun a b hab => ?_ + have hd : ofRaw a ≤ ofRaw (Raw.diag K S (S → Fin (Module.finrank K L)) * b) := + Raw.descend hab + rw [ofRaw_mul, diag_eq_natCast, Fintype.card_fun, Fintype.card_fin] at hd + exact hd + +theorem descent_powers (A B : Tensor K S) + (h : map (algebraMap K L) A ≤ map (algebraMap K L) B) : + ∃ C : ℕ, ∀ r : ℕ, A ^ r ≤ (C : Tensor K S) * B ^ r := by + revert h + refine Quotient.inductionOn₂ A B fun a b hab => ?_ + obtain ⟨E, _, _, _, hE⟩ := Raw.specialize (L := L) (A := b) (B := a) hab + have he : map (algebraMap K E) (ofRaw a) ≤ map (algebraMap K E) (ofRaw b) := hE + refine ⟨Module.finrank K E ^ Fintype.card S, fun r => finite_descent (L + := E) (ofRaw a ^ r) (ofRaw b ^ r) ?_⟩ + rw [map_pow, map_pow] + exact powers_le he r + +theorem extend_field (L : Type) [Field L] [Algebra K L] + (f : Tensor K S →+* ℝ≥0) (hf : Monotone f) : + ∃ g : Tensor L S →+* ℝ≥0, Monotone g ∧ ∀ A, g (map (algebraMap K L) A) = f A := by + apply Spectrum.extension add_le_add_right mul_le_mul_left zero_le one_le exists_bound + intro A B h + obtain ⟨C, hc⟩ := descent_powers A B h + apply Spectrum.le_of_powers_le (C := C) + intro r + rw [← map_pow, ← map_pow, ← map_natCast f, ← map_mul f] + exact hf (hc r) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- +# Moving a single leg along a wire + +The old and new sites both pin the wire label to the corresponding +leg coordinate. For each target assignment there is exactly one +source assignment satisfying these local conditions and the wire. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S T : Type} [Field K] [Fintype S] [Fintype T] [DecidableEq S] [DecidableEq T] + +private theorem shared_on {U : Finset S} (hU : U.Nonempty) {n : ℕ} (i : Fin n) : + (shared K U n).coeff (fun s => port U s i) = 1 := by + change (∑ j : Fin n, ∏ s, if port U s i = port U s j then (1 : K) else 0) = 1 + rw [Fintype.sum_eq_single i] + · simp + · intro j hj + obtain ⟨s, hs⟩ := hU + exact Finset.prod_eq_zero (Finset.mem_univ s) (by simp [port, hs, hj.symm]) + +private theorem shared_support {U : Finset S} {n : ℕ} (x : S → Fin n) + (h : (shared K U n).coeff x ≠ 0) : ∃ i, ∀ s, x s = port U s i := by + change (∑ i : Fin n, ∏ s, if x s = port U s i then (1 : K) else 0) ≠ 0 at h + obtain ⟨i, _, hi⟩ := Finset.exists_ne_zero_of_sum_ne_zero h + exact ⟨i, fun s => by + by_contra he + exact hi (Finset.prod_eq_zero (Finset.mem_univ s) (ite_eq_right he))⟩ + +theorem integral_move {O : Subring K} (A : Raw K T) (f g : T → S) (t : T) (h : ∀ u, u ≠ t → f u + = g u) : + Valued.Restricts O (A.group f * wire K (f t) (g t) (Fintype.card (A.leg t))) (A.group g) := by + classical + let e := Fintype.equivFin (A.leg t) + let U : Finset S := {f t, g t} + let W := shared K U (Fintype.card (A.leg t)) + let C := A.group f * W + let ok (s : S) (x : (A.group g).leg s) (y : C.leg s) := + (∀ u (hf : f u = s) (hg : g u = s), y.1 ⟨u, hf⟩ = x ⟨u, hg⟩) ∧ + (∀ hf : f t = s, e (y.1 ⟨t, hf⟩) = y.2) ∧ + (∀ hg : g t = s, e (x ⟨t, hg⟩) = y.2) + change Valued.Restricts O C (A.group g) + refine (Valued.restricts_iff _ _).mpr ⟨fun s x y => if ok s x y then 1 else 0, + fun s x y => by by_cases h : ok s x y <;> simp [h], fun x => ?_⟩ + let v (u : T) := x (g u) ⟨u, rfl⟩ + have hv u s (hg : g u = s) : x s ⟨u, hg⟩ = v u := by subst s; rfl + let z := e (v t) + let y₀ (s : S) : C.leg s := (fun u => v u, port U s z) + have ho (s : S) : ok s (x s) (y₀ s) := by + refine ⟨fun u hf hg => (hv u s hg).symm, ?_, ?_⟩ + · rintro rfl + simp [y₀, port, U, z] + · rintro rfl + simp [y₀, port, U, z, v] + rw [Fintype.sum_eq_single y₀] + · simp only [ho, ↓reduceIte, Finset.prod_const_one, one_mul] + change (A.group g).coeff x = (A.group f * W).coeff y₀ + rw [coeff_mul, coeff_group, coeff_group] + change A.coeff v = A.coeff v * (shared K U _).coeff (fun s => port U s z) + rw [shared_on (by simp [U]), mul_one] + · intro y hy + by_cases he : ∀ s, ok s (x s) (y s) + swap + · obtain ⟨s, hs⟩ := not_forall.mp he + exact mul_eq_zero_of_left (Finset.prod_eq_zero (Finset.mem_univ s) (ite_eq_right hs)) _ + by_cases hw : W.coeff (fun s => (y s).2) = 0 + · simp only [C, coeff_mul, hw, mul_zero] + obtain ⟨i, hi⟩ := shared_support (fun s => (y s).2) hw + have hin (s : S) (hs : s ∈ U) : (y s).2 = i := (hi s).trans (ite_eq_left hs) + have hiz : i = z := (hin (g t) (by simp [U])).symm.trans ((he (g t)).2.2 rfl).symm + subst i + exfalso + apply hy + funext s + refine Prod.ext ?_ (hi s) + funext u + rcases u with ⟨u, hu⟩ + by_cases hut : u = t + · subst u + exact e.injective (((he s).2.1 hu).trans (hin s (by simp [U, hu]))) + · have hg : g u = s := (h u hut).symm.trans hu + exact ((he s).1 u hu hg).trans (hv u s hg) + +theorem move (A : Raw K T) (f g : T → S) (t : T) (h : ∀ u, u ≠ t → f u = g u) : + (A.group f * wire K (f t) (g t) (Fintype.card (A.leg t))).Restricts (A.group g) := + (integral_move (O := ⊤) A f g t h).forget + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +/- +# Transporting a tensor between placements +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S T : Type} [Field K] [Fintype S] [Fintype T] [DecidableEq S] [DecidableEq T] + +omit [Fintype S] [DecidableEq S] in +omit [DecidableEq T] in +/-- Iterate a transport bound proved for one leg at a time. -/ +theorem move_all {M : Type*} [CommMonoid M] [Preorder M] + (V : (T → S) → M) (W : T → S → S → M) + (hmul : ∀ a b c : M, a ≤ b → c * a ≤ c * b) + (move : ∀ (f g : T → S) (t : T), (∀ u, u ≠ t → f u = g u) → + V g ≤ V f * W t (f t) (g t)) (f g : T → S) : + V g ≤ V f * ∏ t, W t (f t) (g t) := by + classical + let mix (U : Finset T) (t : T) := if t ∈ U then g t else f t + have step (U : Finset T) : V (mix U) ≤ V f * ∏ t ∈ U, W t (f t) (g t) := by + induction U using Finset.induction_on with + | empty => simp [mix] + | @insert t U ht ih => + have hm := move (mix U) (mix (insert t U)) t (by intro u hu; simp [mix, hu]) + have hfg : mix U t = f t := ite_eq_right ht + have hgg : mix (insert t U) t = g t := ite_eq_left (Finset.mem_insert_self _ _) + rw [hfg, hgg, mul_comm] at hm + rw [Finset.prod_insert ht, mul_left_comm] + exact hm.trans (hmul _ _ _ ih) + simpa [mix] using step Finset.univ + +theorem transport (A : Raw K T) (f g : T → S) : + place g (ofRaw A) ≤ place f (ofRaw A) * ∏ t, wire K (f t) (g t) (Fintype.card (A.leg t)) := + move_all (fun f => place f (ofRaw A)) (fun t i j => wire K i j (Fintype.card (A.leg t))) + mul_le_mul_left (Raw.move A) f g + +variable [Nonempty T] (p : Tensor K S →+* ℝ) (hp : Monotone p) +include hp + +theorem price_place_pos (f : T → S) {A : Tensor K T} (h : A ≠ 0) : + 0 < p (place f A) := by + have e := hp (place_mono f (one_le A h)) + rw [place_one, map_one] at e + exact zero_lt_one.trans_le e + +omit [Nonempty T] [DecidableEq T] in +/-- Convert multiplicative wire bounds into an additive estimate on logs. -/ +theorem log_transport (V : (T → S) → ℝ) (n : T → ℕ) + (pos : ∀ f, 0 < V f) (dim : ∀ t, 0 < n t) + (h : ∀ f g, V g ≤ V f * ∏ t, p (wire K (f t) (g t) (n t))) (f g : T → S) : + |Real.log (V f) - Real.log (V g)| ≤ ∑ t, dist p (f t) (g t) * Real.log (n t) := by + have bound (f g : T → S) : + Real.log (V g) - Real.log (V f) ≤ + ∑ t, dist p (f t) (g t) * Real.log (n t) := by + have hg := pos g + have hf := pos f + have hW (t : T) : 0 < p (wire K (f t) (g t) (n t)) := by + rw [price_wire p hp _ _ (dim t)] + exact Real.rpow_pos_of_pos (Nat.cast_pos.mpr (dim t)) _ + have he := Real.log_le_log hg (h f g) + rw [Real.log_mul hf.ne' (Finset.prod_pos fun t _ => hW t).ne', + Real.log_prod (fun t _ => (hW t).ne')] at he + apply sub_le_iff_le_add'.mpr + refine he.trans_eq (congrArg _ (Finset.sum_congr rfl fun t _ => ?_)) + rw [price_wire p hp _ _ (dim t), Real.log_rpow (Nat.cast_pos.mpr (dim t))] + refine abs_sub_le_iff.mpr ⟨?_, bound f g⟩ + simpa only [dist_comm p (g _) (f _)] using bound g f + +theorem price_transport (A : Raw K T) (h : ofRaw A ≠ 0) (f g : T → S) : + |Real.log (p (place f (ofRaw A))) - Real.log (p (place g (ofRaw A)))| ≤ + ∑ t, dist p (f t) (g t) * Real.log (Fintype.card (A.leg t)) := by + have dim (t : T) : 0 < Fintype.card (A.leg t) := by + obtain ⟨x, _⟩ := not_forall.mp (fun he => h ((ofRaw_eq_zero A).mpr he)) + exact Fintype.card_pos_iff.mpr ⟨x t⟩ + refine log_transport p hp (fun v => p (place v (ofRaw A))) _ (fun v => price_place_pos p hp v h) + dim ?_ f g + intro v w + have H := hp (transport A v w) + rwa [p.map_mul, map_prod] at H + +theorem price_place_eq (f g : T → S) (h : ∀ t, dist p (f t) (g t) = 0) (A : Tensor K T) : + p (place f A) = p (place g A) := by + refine Quotient.inductionOn A fun a => ?_ + change p (place f (ofRaw a)) = p (place g (ofRaw a)) + by_cases hz : ofRaw a = 0 + · simp only [hz, place_zero] + have he := price_transport p hp a hz f g + simp only [h, zero_mul, Finset.sum_const_zero, abs_nonpos_iff, sub_eq_zero] at he + exact Real.log_injOn_pos (price_place_pos p hp f hz) (price_place_pos p hp g hz) he + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Rank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Rank.lean new file mode 100644 index 0000000000..ae5a74581c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Rank.lean @@ -0,0 +1,540 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Semiring +public import Mathlib.Logic.Equiv.Prod +public import Mathlib.LinearAlgebra.Matrix.Rank +public import Mathlib.Logic.Equiv.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Padding + +/-! +# Adding trivial sites and closing them with local covectors +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S : Type} [CommSemiring K] [Fintype S] (U : Type) [Fintype U] + +/-- The new sites have one trivial coordinate. -/ +def pad (A : Raw K S) : Raw K (S ⊕ U) where + leg := Sum.elim A.leg fun _ => Unit + fleg := Sum.rec (fun s => A.fleg s) (fun _ => inferInstanceAs (Fintype Unit)) + term := A.term + factor i := Sum.rec (A.factor i) fun _ _ => 1 + +variable {U} [Nonempty S] + +/-- The condition `∀ u, A.leg (.inr u) → K` on the specified data. -/ +abbrev Covectors (A : Raw K (S ⊕ U)) := ∀ u, A.leg (.inr u) → K + +/-- Scalar from closing the extra sites, evaluated separately on each term. -/ +def scalar (A : Raw K (S ⊕ U)) (v : A.Covectors) (i : A.term) : K := + ∏ u, ∑ y, v u y * A.factor i (.inr u) y + +open Classical in +/-- Returns `a` when `s = Classical.arbitrary S` holds, and `1` otherwise. -/ +def weight (a : K) (s : S) : K := if s = Classical.arbitrary S then a else 1 + +/-- Closing a term multiplies one of its remaining factors by the scalar. -/ +def close (A : Raw K (S ⊕ U)) (v : A.Covectors) : Raw K S where + leg s := A.leg (.inl s) + term := A.term + factor i s x := A.factor i (.inl s) x * weight (A.scalar v i) s + +omit [Nonempty S] in +theorem pad_coeff (A : Raw K S) (x : ∀ s, (pad U A).leg s) : + (pad U A).coeff x = A.coeff (fun s => x (.inl s)) := by + simp only [coeff, Fintype.prod_sum_type] + change (∑ i : A.term, (∏ s, A.factor i s (x (.inl s))) * ∏ _ : U, (1 : K)) = _ + simp + +theorem close_action (A : Raw K (S ⊕ U)) (v : A.Covectors) + (w : ∀ s, A.leg (.inl s) → K) : + (∑ i : (A.close v).term, ∏ s, ∑ y, w s y * (A.close v).factor i s y) = + ∑ i : A.term, (∏ s, ∑ y, w s y * A.factor i (.inl s) y) * A.scalar v i := by + classical + change (∑ i : A.term, ∏ s, ∑ y, w s y * (A.factor i (.inl s) y * weight (A.scalar v i) s)) = _ + simp only [← mul_assoc, ← Finset.sum_mul, Finset.prod_mul_distrib] + simp [weight] + +/-- The local maps to the padded legs are covectors because those legs have one coordinate. -/ +def padCovectors {A : Raw K (S ⊕ U)} {B : Raw K S} + (L : RestrictionMaps A (pad U B)) : A.Covectors := + fun u => L (.inr u) () + +/-- Extend the original-site maps with the covectors at the extra sites. -/ +def padMaps {A : Raw K (S ⊕ U)} {B : Raw K S} (v : A.Covectors) + (L : RestrictionMaps (A.close v) B) : RestrictionMaps A (pad U B) := + Sum.rec L fun u _ => v u + +/-- The padded coefficient equation is the original-site equation after closing the extra legs. -/ +theorem pad_coefficients_iff (A : Raw K (S ⊕ U)) (B : Raw K S) + (L : RestrictionMaps A (pad U B)) : + let v := padCovectors (B := B) L + (∀ x, (pad U B).coeff x = ∑ i : A.term, ∏ s, ∑ y, L s (x s) y * A.factor i s y) ↔ + ∀ x, B.coeff x = ∑ i : (A.close v).term, ∏ s, + ∑ y, L (.inl s) (x s) y * (A.close v).factor i s y := by + dsimp only + constructor + · intro coefficients x + let padded : ∀ s, (pad U B).leg s := Sum.rec x (fun _ => ()) + refine Eq.trans ?_ (close_action A _ (fun s => L (.inl s) (x s))).symm + have eq := coefficients padded + rw [pad_coeff] at eq + simp only [Fintype.prod_sum_type] at eq + exact eq + · intro coefficients x + refine (pad_coeff B x).trans ((coefficients (fun s => x (.inl s))).trans + ((close_action A _ (fun s => L (.inl s) (x (.inl s)))).trans ?_)) + have unitCoordinate (u : U) : x (.inr u) = () := + @Subsingleton.elim Unit inferInstance (x (.inr u)) () + simp only [Fintype.prod_sum_type, scalar, padCovectors, unitCoordinate] + +/-- A restriction to a padded tensor uses one covector per extra site. -/ +theorem restricts_pad_iff (A : Raw K (S ⊕ U)) (B : Raw K S) : + A.Restricts (pad U B) ↔ ∃ v : A.Covectors, (A.close v).Restricts B := by + constructor + · rintro ⟨L, h⟩ + exact ⟨padCovectors (B := B) L, fun s => L (.inl s), (pad_coefficients_iff A B L).mp h⟩ + · rintro ⟨v, L, h⟩ + exact ⟨padMaps v L, (pad_coefficients_iff A B (padMaps v L)).mpr h⟩ + +omit [Fintype S] [Nonempty S] in +theorem pad_scalar (A : Raw K S) (v : (pad U A).Covectors) (i : A.term) : + (pad U A).scalar v i = ∏ u, v u () := by + change U → Unit → K at v + change (∏ u, ∑ y : Unit, v u y * 1) = _ + simp + +open Classical in +/-- Distribute the scalar from closing unit legs at one original site. -/ +def closePadMap (A : Raw K S) (v : (pad U A).Covectors) : RestrictionMaps A ((pad U A).close v) := + fun s x y => if y = x then weight (∏ u, v u ()) s else 0 + +theorem close_pad_coefficients (A : Raw K S) (v : (pad U A).Covectors) + (x : ∀ s, ((pad U A).close v).leg s) : + ((pad U A).close v).coeff x = + ∑ i : A.term, ∏ s, ∑ y, closePadMap A v s (x s) y * A.factor i s y := by + classical + change (∀ s, A.leg s) at x + change (∑ i : A.term, ∏ s, A.factor i s (x s) * weight ((pad U A).scalar v i) s) = _ + simp [closePadMap, pad_scalar, mul_comm] + +omit [Fintype S] in +theorem close_pad_one_relabels (A : Raw K S) : + Relabels ((pad U A).close (fun _ _ => 1)) A := by + refine ⟨Equiv.refl _, fun _ => Equiv.refl _, ?_⟩ + intro i s x + change A.term at i + change A.factor i s x * weight ((pad U A).scalar (fun _ _ => 1) i) s = A.factor i s x + simp [pad_scalar, weight] + +theorem pad_restricts_iff (A B : Raw K S) : + (pad U A).Restricts (pad U B) ↔ A.Restricts B := by + rw [restricts_pad_iff] + constructor + · rintro ⟨v, h⟩ + exact (show A.Restricts ((pad U A).close v) from + ⟨closePadMap A v, close_pad_coefficients A v⟩).trans h + · intro h + exact ⟨fun _ _ => 1, (relabel_of_relabels (close_pad_one_relabels (U := U) A)).1.trans h⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +/- +# Adjoining unit legs + +Padding preserves zero, one and products up to mutual restriction. +For sums, one can erase the summand label at every new site. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S : Type} [CommSemiring K] [Fintype S] (U : Type) [Fintype U] + +theorem empty_terms_restriction {A B : Raw K S} [IsEmpty A.term] [IsEmpty B.term] + (maps : ∀ s, B.leg s → A.leg s → K) (x : ∀ s, B.leg s) : + B.coeff x = ∑ i : A.term, ∏ s, ∑ y : A.leg s, maps s (x s) y * A.factor i s y := by + simp [coeff] + +theorem pad_zero : pad U (0 : Raw K S) ≈ 0 := by + let : IsEmpty (pad U (0 : Raw K S)).term := inferInstanceAs (IsEmpty Empty) + let : IsEmpty (0 : Raw K (S ⊕ U)).term := inferInstanceAs (IsEmpty Empty) + constructor <;> exact ⟨fun _ _ _ => 0, empty_terms_restriction (fun _ _ _ => 0)⟩ + +omit [Fintype S] [Fintype U] in +theorem pad_one_relabels : Relabels (pad U (1 : Raw K S)) 1 := by + let e (s : S ⊕ U) : (pad U (1 : Raw K S)).leg s ≃ Unit := + match s with + | .inl _ => Equiv.refl Unit + | .inr _ => Equiv.refl Unit + refine ⟨Equiv.refl _, e, ?_⟩ + rintro i (s | u) x <;> rfl + +omit [Fintype S] [Fintype U] in +theorem pad_mul_relabels (A B : Raw K S) : Relabels (pad U (A * B)) (pad U A * pad U B) := by + let e (s : S ⊕ U) : (pad U (A * B)).leg s ≃ (pad U A * pad U B).leg s := + match s with + | .inl s => Equiv.refl (A.leg s × B.leg s) + | .inr _ => (Equiv.punitProd Unit).symm + refine ⟨Equiv.refl _, e, ?_⟩ + rintro i (s | u) x + · rfl + · exact (one_mul (1 : K)).symm + +theorem pad_one : pad U (1 : Raw K S) ≈ 1 := + relabel_of_relabels (pad_one_relabels U) + +theorem pad_mul (A B : Raw K S) : pad U (A * B) ≈ pad U A * pad U B := + relabel_of_relabels (pad_mul_relabels U A B) + +omit [Fintype S] [Fintype U] in +/-- Duplicate the unit coordinate on new sites and copy retained coordinates identically. -/ +def padAddMap (A B : Raw K S) (s : S ⊕ U) : + (pad U (A + B)).leg s → (pad U A + pad U B).leg s → K := by + classical + exact match s with + | .inl s => fun (x y : A.leg s ⊕ B.leg s) => if y = x then 1 else 0 + | .inr _ => fun _ _ => 1 + +theorem pad_add_coeff (A B : Raw K S) (x : ∀ s, (pad U (A + B)).leg s) : + (pad U (A + B)).coeff x = + ∑ i : (pad U A + pad U B).term, ∏ s, + ∑ y : (pad U A + pad U B).leg s, + padAddMap U A B s (x s) y * (pad U A + pad U B).factor i s y := by + classical + exact Finset.sum_congr rfl fun i _ => Finset.prod_congr rfl fun s _ => by + change A.term ⊕ B.term at i + cases s with + | inl s => + have key (z : A.leg s ⊕ B.leg s) (f : A.leg s ⊕ B.leg s → K) : + f z = ∑ y, (if y = z then (1 : K) else 0) * f y := by simp [ite_mul] + exact key (x (.inl s)) ((A + B).factor i s) + | inr u => + change 1 = ∑ y : Unit ⊕ Unit, 1 * (pad U A + pad U B).factor i (.inr u) y + rw [Fintype.sum_sum_type] + simp only [Fintype.sum_unique, one_mul] + cases i + · exact (add_zero (1 : K)).symm + · exact (zero_add (1 : K)).symm + +theorem pad_add (A B : Raw K S) : (pad U A + pad U B).Restricts (pad U (A + B)) := + ⟨padAddMap U A B, pad_add_coeff U A B⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +/- +# Arrays and diagonal tensors +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable (K S : Type) [CommSemiring K] [Fintype S] + +/-- One copy of the scalar unit for each possible value of a common label. -/ +def diag (X : Type) [Fintype X] [DecidableEq X] : Raw K S := + ⟨fun _ => X, X, fun i _ x => if x = i then 1 else 0⟩ + +variable {K S} + +theorem Restricts.zero (A : Raw K S) [Nonempty S] : A.Restricts 0 := + ⟨fun _ x _ => Empty.elim x, fun x => Empty.elim (x (Classical.arbitrary S))⟩ + +theorem zero_restricts_iff (A : Raw K S) : + (0 : Raw K S).Restricts A ↔ ∀ x, A.coeff x = 0 := by + constructor + · rintro ⟨L, h⟩ x + rw [h] + exact Finset.sum_eq_zero (fun i _ => Empty.elim i) + · intro h + refine ⟨fun _ _ _ => 0, fun x => ?_⟩ + rw [h] + exact (Finset.sum_eq_zero (fun i _ => Empty.elim i)).symm + +theorem diag_equiv {X Y : Type} [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] + (e : X ≃ Y) : diag K S X ≈ diag K S Y := by + refine relabel e (fun _ => e) fun i _ x => ?_ + change X at x i + change (if x = i then (1 : K) else 0) = if e x = e i then 1 else 0 + simp only [e.apply_eq_iff_eq] + +theorem diag_sum (X Y : Type) [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] : + diag K S (X ⊕ Y) ≈ diag K S X + diag K S Y := by + refine relabel (Equiv.refl _) (fun _ => Equiv.refl _) ?_ + intro i s x + change X ⊕ Y at x i + change (if x = i then (1 : K) else 0) = _ + rcases i with i | i <;> rcases x with x | x <;> + simp only [Sum.inl.injEq, Sum.inr.injEq, reduceCtorEq, ↓reduceIte] <;> rfl + +theorem term_bound (A : Raw K S) [DecidableEq A.term] : + (diag K S A.term).Restricts A := by + refine ⟨fun s x i => A.factor i s x, fun x => ?_⟩ + change A.coeff x = ∑ i : A.term, ∏ s, ∑ j : A.term, + A.factor j s (x s) * if j = i then 1 else 0 + simp [coeff, mul_ite] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +/- +# A diagonal restriction cannot increase the number of labels + +Assign one label to a single site and a second label to all remaining +sites. This slice of the target diagonal is the identity matrix. The +restriction factors the slice through the source label space. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S : Type} [CommSemiring K] [Fintype S] [Nontrivial S] + +theorem diag_restricts_le [StrongRankCondition K] {m n : ℕ} + (h : (diag K S (Fin n)).Restricts (diag K S (Fin m))) : m ≤ n := by + classical + obtain ⟨u, v, huv⟩ := exists_pair_ne S + obtain ⟨L, hL⟩ := h + change S → Fin m → Fin n → K at L + change ∀ x : S → Fin m, (∑ i : Fin m, ∏ s, if x s = i then (1 : K) else 0) = + ∑ i : Fin n, ∏ s, ∑ y : Fin n, L s (x s) y * if y = i then 1 else 0 at hL + simp only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', Finset.mem_univ, ite_true] at hL + let A : Matrix (Fin m) (Fin n) K := L u + let B : Matrix (Fin n) (Fin m) K := fun k j => ∏ s ∈ Finset.univ.erase u, L s j k + have hAB : A * B = 1 := by + ext i j + let x : S → Fin m := fun s => if s = u then i else j + rw [Matrix.mul_apply, Matrix.one_apply] + calc + _ = ∑ k : Fin n, ∏ s, L s (x s) k := by + apply Finset.sum_congr rfl + intro k _ + rw [← Finset.mul_prod_erase _ _ (Finset.mem_univ u)] + simp only [A, B, x, ↓reduceIte] + congr 1 + apply Finset.prod_congr rfl + intro s hs + rw [ite_eq_right (Finset.ne_of_mem_erase hs)] + _ = ∑ k : Fin m, ∏ s, if x s = k then (1 : K) else 0 := (hL x).symm + _ = _ := by + rw [Finset.sum_eq_single i] + · by_cases hij : i = j + · simp [x, hij] + · rw [ite_eq_right hij] + exact Finset.prod_eq_zero (Finset.mem_univ v) (by simp [x, huv.symm, Ne.symm hij]) + · intro k _ hk + exact Finset.prod_eq_zero (Finset.mem_univ u) (by simp [x, Ne.symm hk]) + · simp + have hr := (Matrix.rank_mul_le_left A B).trans A.rank_le_card_width + simpa [hAB] using hr + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +section +/- +# Closing sums and products + +On a direct sum the covector is restricted to each summand. In a +product with a padded tensor only the other tensor is contracted. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S U : Type} [CommSemiring K] [Fintype U] [Nonempty S] + +theorem close_add_relabels (A B : Raw K (S ⊕ U)) (v : (A + B).Covectors) : + Relabels ((A + B).close v) + (A.close (fun u x => v u (.inl x)) + B.close (fun u x => v u (.inr x))) := by + have hl (i : A.term) : + (A + B).scalar v (.inl i) = A.scalar (fun u x => v u (.inl x)) i := by + apply Finset.prod_congr rfl + intro u _ + change (∑ y : A.leg (.inr u) ⊕ B.leg (.inr u), + v u y * Sum.elim (A.factor i (.inr u)) (fun _ => 0) y) = _ + simp [Fintype.sum_sum_type] + have hr (i : B.term) : + (A + B).scalar v (.inr i) = B.scalar (fun u x => v u (.inr x)) i := by + apply Finset.prod_congr rfl + intro u _ + change (∑ y : A.leg (.inr u) ⊕ B.leg (.inr u), + v u y * Sum.elim (fun _ => 0) (B.factor i (.inr u)) y) = _ + simp [Fintype.sum_sum_type] + refine ⟨Equiv.refl _, fun _ => Equiv.refl _, ?_⟩ + rintro (i | i) s (x | x) + · exact congrArg (fun a => A.factor i (.inl s) x * weight a s) (hl i) + · exact zero_mul _ + · exact zero_mul _ + · exact congrArg (fun a => B.factor i (.inl s) x * weight a s) (hr i) + +theorem close_mul_relabels (A : Raw K S) (B : Raw K (S ⊕ U)) (v : (pad U A * B).Covectors) : + Relabels ((pad U A * B).close v) (A * B.close (fun u x => v u ((), x))) := by + refine ⟨Equiv.refl _, fun _ => Equiv.refl _, ?_⟩ + rintro ⟨i, j⟩ s ⟨x, y⟩ + have h : (pad U A * B).scalar v (i, j) = B.scalar (fun u z => v u ((), z)) j := by + apply Finset.prod_congr rfl + intro u _ + change (∑ z : Unit × B.leg (.inr u), v u z * (1 * B.factor j (.inr u) z.2)) = _ + simp [Fintype.sum_prod_type] + rfl + change A.factor i s x * B.factor j (.inl s) y * weight ((pad U A * B).scalar v (i, j)) s = _ + rw [h, mul_assoc] + rfl + + +variable [Fintype S] + +theorem close_add (A B : Raw K (S ⊕ U)) (v : (A + B).Covectors) : + (A + B).close v ≈ A.close (fun u x => v u (.inl x)) + B.close (fun u x => v u (.inr x)) := + relabel_of_relabels (close_add_relabels A B v) + +theorem close_mul (A : Raw K S) (B : Raw K (S ⊕ U)) (v : (pad U A * B).Covectors) : + (pad U A * B).close v ≈ A * B.close (fun u x => v u ((), x)) := + relabel_of_relabels (close_mul_relabels A B v) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +/- +# Natural units and rank bounds + +A decomposition with `n` terms is a restriction from the `n`-fold diagonal. +Reflection of the natural order requires at least two sites. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S : Type} [Fintype S] + +section +variable [CommSemiring K] + +theorem diag_fin (n : ℕ) : ofRaw (Raw.diag K S (Fin n)) = n := by + induction n with + | zero => + rw [Nat.cast_zero] + exact ofRaw_eq (Raw.relabel (Equiv.equivOfIsEmpty (Fin 0) Empty) + (fun _ => Equiv.equivOfIsEmpty (Fin 0) Empty) (fun i => Fin.elim0 i)) + | succ n ih => + have h : ofRaw (Raw.diag K S (Fin 1)) = (1 : Tensor K S) := by + apply ofRaw_eq + refine Raw.relabel (Equiv.ofUnique (Fin 1) Unit) + (fun _ => Equiv.ofUnique (Fin 1) Unit) fun i s x => ?_ + change Fin 1 at x i + change (if x = i then (1 : K) else 0) = 1 + rw [ite_eq_left (Subsingleton.elim _ _)] + rw [ofRaw_eq (Raw.diag_equiv finSumFinEquiv.symm), ofRaw_eq (Raw.diag_sum _ _), + ofRaw_add, ih, h, Nat.cast_succ] + +theorem diag_eq_natCast (X : Type) [Fintype X] [DecidableEq X] : + ofRaw (Raw.diag K S X) = Fintype.card X := by + rw [ofRaw_eq (Raw.diag_equiv (Fintype.equivFin X)), diag_fin] + +theorem le_term_count (A : Raw K S) : ofRaw A ≤ Fintype.card A.term := by + classical + rw [← diag_eq_natCast, ofRaw_le] + exact Raw.term_bound A + +theorem exists_bound (A : Tensor K S) : ∃ n : ℕ, A ≤ n := + Quotient.inductionOn A fun a => ⟨_, le_term_count a⟩ + +variable [Nonempty S] + +theorem zero_le (A : Tensor K S) : 0 ≤ A := + Quotient.inductionOn A fun a => Raw.Restricts.zero a + +theorem ofRaw_eq_zero (A : Raw K S) : ofRaw A = 0 ↔ ∀ x, A.coeff x = 0 := by + rw [← Raw.zero_restricts_iff, ← ofRaw_le] + exact ⟨le_of_eq, fun h => le_antisymm h (zero_le _)⟩ + +instance [Nontrivial K] : Nontrivial (Tensor K S) := by + refine ⟨1, 0, fun h => ?_⟩ + have he := (ofRaw_eq_zero (1 : Raw K S)).mp h (fun _ => ()) + change (∑ _ : Unit, ∏ _ : S, (1 : K)) = 0 at he + simp at he + +theorem natCast_le {m n : ℕ} (h : m ≤ n) : (m : Tensor K S) ≤ n := by + obtain ⟨d, rfl⟩ := Nat.exists_eq_add_of_le h + simpa [Nat.cast_add, add_comm] using + add_le_add_right 0 (d : Tensor K S) m (zero_le _) + +theorem natCast_le_iff [StrongRankCondition K] [Nontrivial S] (m n : ℕ) : + (m : Tensor K S) ≤ n ↔ m ≤ n := by + refine ⟨?_, natCast_le⟩ + rw [← diag_fin, ← diag_fin, ofRaw_le] + exact Raw.diag_restricts_le + +/-- The coordinate expansion bounds rank by the product of the leg dimensions. -/ +theorem le_dimension (A : Raw K S) : ofRaw A ≤ (∏ s, Fintype.card (A.leg s) : ℕ) := by + classical + let B := Raw.ofTable A.leg A.coeff + have he : A ≈ B := Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => + (Raw.coeff_ofTable _ _ x).symm + rw [ofRaw_eq he, ← Fintype.card_pi] + exact le_term_count B + +end + +theorem one_le [Field K] [Nonempty S] (A : Tensor K S) : A ≠ 0 → 1 ≤ A := by + refine Quotient.inductionOn A fun a ha => Raw.restricts_one a ?_ + exact not_forall.mp (fun h => ha ((ofRaw_eq_zero _).mpr h)) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- +# Orders after adjoining trivial tensor legs +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S : Type} [CommSemiring K] [Fintype S] [Nonempty S] (U : Type) [Fintype U] + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def pad : Tensor K S → Tensor K (S ⊕ U) := + Quotient.map (Raw.pad U) fun _ _ h => + ⟨(Raw.pad_restricts_iff _ _).mpr h.1, (Raw.pad_restricts_iff _ _).mpr h.2⟩ + +theorem pad_ofRaw (A : Raw K S) : pad U (ofRaw A) = ofRaw (Raw.pad U A) := rfl + +theorem pad_le_ofRaw_iff {U : Type} [Fintype U] (s : Tensor K S) (A : Raw K (S ⊕ U)) : + pad U s ≤ ofRaw A ↔ ∃ v : A.Covectors, s ≤ ofRaw (A.close v) := + Quotient.inductionOn s fun a => Raw.restricts_pad_iff A a + +theorem pad_close_le (A : Raw K (S ⊕ U)) (v : A.Covectors) : + pad U (ofRaw (A.close v)) ≤ ofRaw A := + (pad_le_ofRaw_iff _ A).mpr ⟨v, le_rfl⟩ + +theorem padding : Prices.Padding (pad (K := K) (S := S) U) where + zero := ofRaw_eq (Raw.pad_zero U) + one := ofRaw_eq (Raw.pad_one U) + le_iff s t := Quotient.inductionOn₂ s t fun a b => Raw.pad_restricts_iff b a + mul s t := Quotient.inductionOn₂ s t fun a b => ofRaw_eq (Raw.pad_mul U a b) + add_le s t := Quotient.inductionOn₂ s t fun a b => Raw.pad_add U a b + split {s x y} := by + refine Quotient.inductionOn₂ x y fun A B h => ?_ + obtain ⟨v, hv⟩ := (pad_le_ofRaw_iff s (A + B)).mp h + rw [ofRaw_eq (Raw.close_add _ _ v), ofRaw_add] at hv + exact ⟨_, _, pad_close_le U A _, pad_close_le U B _, hv⟩ + factor {s a x} := by + refine Quotient.inductionOn₂ a x fun A B h => ?_ + obtain ⟨v, hv⟩ := (pad_le_ofRaw_iff s (Raw.pad U A * B)).mp h + rw [ofRaw_eq (Raw.close_mul _ _ v), ofRaw_mul] at hv + exact ⟨_, pad_close_le U B _, hv⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Rule.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Rule.lean new file mode 100644 index 0000000000..36401c55d8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Rule.lean @@ -0,0 +1,76 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Wire + +/-! # Local table expansions of simultaneous wire demands -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +open Classical in +/-- Each demand leg has a named bit. A summand may introduce independent +supply bits. Each local table reads only the incident bits. -/ +def Packet (K : Type) [Field K] {S E I : Type} {J : I → Type} + [Fintype S] [Fintype E] [Fintype I] [∀ i, Fintype (J i)] + (D : E → S × S) (W : (i : I) → J i → S × S) : Prop := + ∃ f : (i : I) → S → (E → Bool) → (E → Bool) → (J i → Bool) → K, + (∀ i v x y u x' y' u', + (∀ e, (D e).1 = v → x e = x' e) → + (∀ e, (D e).2 = v → y e = y' e) → + (∀ e, (W i e).1 = v ∨ (W i e).2 = v → u e = u' e) → + f i v x y u = f i v x' y' u') ∧ + ∀ x y, (if x = y then (1 : K) else 0) = ∑ i, ∑ u, ∏ v, f i v x y u + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral +end + +/- +# Keeping the local factors of a wire identity + +An existence proof can be used to choose a single basic gadget. +Composing gadgets needs the actual factors, since the label of a +derived table can only depend on its own local history. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet + +variable {S E I : Type} {J : I → Type} [Fintype S] [Fintype E] [Fintype I] [∀ i, Fintype (J i)] + +open Classical in +/-- The data for the rule construction, including `entry`, `local'`, `eval`. -/ +structure Rule (K : Type) [Field K] (D : E → S × S) (W : (i : I) → J i → S × S) where + /-- The `Rule` component of type `(i : I) → S → (E → Bool) → (E → Bool) → (J i → Bool) → K`. -/ + entry : (i : I) → S → (E → Bool) → (E → Bool) → (J i → Bool) → K + local' : ∀ i v x y u x' y' u', + (∀ e, (D e).1 = v → x e = x' e) → + (∀ e, (D e).2 = v → y e = y' e) → + (∀ e, (W i e).1 = v ∨ (W i e).2 = v → u e = u' e) → + entry i v x y u = entry i v x' y' u' + eval : ∀ x y, (if x = y then (1 : K) else 0) = ∑ i, ∑ u, ∏ v, entry i v x y u + +variable {K : Type} [Field K] {D : E → S × S} {W : (i : I) → J i → S × S} + +open Classical in +/-- Uses `⟨p.choose, p.choose_spec.1, p.choose_spec.2⟩` as the representation. -/ +def rule (p : Packet K D W) : Rule K D W := ⟨p.choose, p.choose_spec.1, p.choose_spec.2⟩ + +open Classical in +theorem Rule.packet (p : Rule K D W) : Packet K D W := ⟨p.entry, p.local', p.eval⟩ + +open Classical in +/-- Change endpoint notation without transporting the factor array. -/ +def Rule.congr {W' : (i : I) → J i → S × S} {D' : E → S × S} + (p : Rule K D W) (hd : D = D') (hw : W = W') : Rule K D' W' := + ⟨p.entry, by rw [← hd, ← hw]; exact p.local', p.eval⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Packet +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Semiring.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Semiring.lean new file mode 100644 index 0000000000..60bd34760b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Semiring.lean @@ -0,0 +1,567 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Data.Fintype.Pi +public import Mathlib.Algebra.Field.Basic +public import Mathlib.Logic.Equiv.Prod +public import Mathlib.Logic.Equiv.Sum + +/-! +# Coefficient tensors on a finite set of named sites + +We store a finite sum of pure tensors. Restriction acts by a local matrix +on every summand and compares the resulting coefficient arrays. It need +not preserve the chosen decomposition. Every array has a coordinate +expansion, and two expansions of the same array restrict to each other. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +/-- The data for the raw construction, including `leg`, `term`, `[fleg`, `[fterm`, `factor`. -/ +structure Raw (K S : Type) where + /-- The `Raw` component of type `S → Type`. -/ + leg : S → Type + /-- The `Raw` component of type `Type`. -/ + term : Type + [fleg : ∀ s, Fintype (leg s)] + [fterm : Fintype term] + /-- The multiplicative factor of type `term → (s : S) → leg s → K`. -/ + factor : term → (s : S) → leg s → K + +attribute [instance] Raw.fleg Raw.fterm + +namespace Raw + +variable {K S : Type} [CommSemiring K] [Fintype S] + +/-- The value specified by `∑ i : A.term, ∏ s, A.factor i s (x s)`. -/ +def coeff (A : Raw K S) (x : ∀ s, A.leg s) : K := + ∑ i : A.term, ∏ s, A.factor i s (x s) + +/-- The defining condition `∃ L : (s : S) → B.leg s → A.leg s → K, ∀ x : ∀ s, B.leg s, B.coeff x += ∑ i : A.term, ∏ s, ∑ y : A.leg s, L s (x s) y * A.factor i s y`. -/ +def Restricts (A B : Raw K S) : Prop := + ∃ L : (s : S) → B.leg s → A.leg s → K, ∀ x : ∀ s, B.leg s, + B.coeff x = ∑ i : A.term, ∏ s, ∑ y : A.leg s, L s (x s) y * A.factor i s y + +instance : Zero (Raw K S) := + ⟨⟨fun _ => Empty, Empty, fun i => i.elim⟩⟩ + +instance : One (Raw K S) := + ⟨⟨fun _ => Unit, Unit, fun _ _ _ => 1⟩⟩ + +instance : Add (Raw K S) where + add A B := ⟨fun s => A.leg s ⊕ B.leg s, A.term ⊕ B.term, + fun i s => Sum.elim + (fun j => Sum.elim (A.factor j s) (fun _ => 0)) + (fun j => Sum.elim (fun _ => 0) (B.factor j s)) i⟩ + +instance : Mul (Raw K S) where + mul A B := ⟨fun s => A.leg s × B.leg s, A.term × B.term, + fun i s x => A.factor i.1 s x.1 * B.factor i.2 s x.2⟩ + +/-- One local matrix at each site, from the source legs to the target legs. -/ +abbrev RestrictionMaps (A B : Raw K S) := (s : S) → B.leg s → A.leg s → K + +variable {A B C : Raw K S} + +open Classical in +/-- The local matrix that copies or selects a source coordinate. -/ +def pullbackMap (f : ∀ s, B.leg s → A.leg s) : RestrictionMaps A B := + fun s x y => if y = f s x then 1 else 0 + +theorem coeff_pullbackMap (f : ∀ s, B.leg s → A.leg s) + (h : ∀ x, B.coeff x = A.coeff (fun s => f s (x s))) (x : ∀ s, B.leg s) : + B.coeff x = ∑ i : A.term, ∏ s, ∑ y, pullbackMap f s (x s) y * A.factor i s y := by + classical + rw [h] + simp [pullbackMap, coeff, ite_mul] + +/-- Copying or selecting local coordinates is a restriction. -/ +theorem Restricts.pullback (f : ∀ s, B.leg s → A.leg s) + (h : ∀ x, B.coeff x = A.coeff (fun s => f s (x s))) : A.Restricts B := + ⟨pullbackMap f, coeff_pullbackMap f h⟩ + +theorem Restricts.refl (A : Raw K S) : A.Restricts A := + Restricts.pullback (fun _ x => x) (fun _ => rfl) + +theorem expand [DecidableEq S] (A : Raw K S) (v : ∀ s, A.leg s → K) : + (∑ i : A.term, ∏ s, ∑ y : A.leg s, v s y * A.factor i s y) = + ∑ y : ∀ s, A.leg s, (∏ s, v s (y s)) * A.coeff y := by + simp only [Fintype.prod_sum, Finset.prod_mul_distrib, coeff, Finset.mul_sum] + rw [Finset.sum_comm] + +/-- Formula independent of the chosen expansions of both arrays. -/ +theorem restricts_iff [DecidableEq S] (A B : Raw K S) : + A.Restricts B ↔ + ∃ L : (s : S) → B.leg s → A.leg s → K, ∀ x : ∀ s, B.leg s, + B.coeff x = ∑ y : ∀ s, A.leg s, (∏ s, L s (x s) (y s)) * A.coeff y := by + simp only [Restricts, expand] + +/-- Compose the local restriction maps by matrix multiplication at each site. -/ +def composeRestrictionMaps (L : RestrictionMaps A B) (M : RestrictionMaps B C) : + RestrictionMaps A C := fun s x z => ∑ y, M s x y * L s y z + +theorem coeff_composeRestrictionMaps (L : RestrictionMaps A B) (M : RestrictionMaps B C) + (hL : ∀ x, B.coeff x = ∑ i : A.term, ∏ s, ∑ y, L s (x s) y * A.factor i s y) + (hM : ∀ x, C.coeff x = ∑ j : B.term, ∏ s, ∑ y, M s (x s) y * B.factor j s y) + (x : ∀ s, C.leg s) : + C.coeff x = ∑ i : A.term, ∏ s, ∑ y, composeRestrictionMaps L M s (x s) y * A.factor i s y := by + classical + rw [hM, B.expand] + simp only [hL, Finset.mul_sum] + rw [Finset.sum_comm] + refine Finset.sum_congr rfl fun i _ => ?_ + simp only [← Finset.prod_mul_distrib] + rw [← Fintype.prod_sum (fun s y => M s (x s) y * ∑ z, L s y z * A.factor i s z)] + refine Finset.prod_congr rfl fun s _ => ?_ + simp only [composeRestrictionMaps, Finset.mul_sum, Finset.sum_mul, mul_assoc] + rw [Finset.sum_comm] + +theorem Restricts.trans (h : A.Restricts B) (g : B.Restricts C) : A.Restricts C := by + obtain ⟨L, hL⟩ := h + obtain ⟨M, hM⟩ := g + exact ⟨composeRestrictionMaps L M, coeff_composeRestrictionMaps L M hL hM⟩ + +instance : Setoid (Raw K S) where + r A B := A.Restricts B ∧ B.Restricts A + iseqv := ⟨fun A => ⟨.refl A, .refl A⟩, fun h => ⟨h.2, h.1⟩, + fun h g => ⟨h.1.trans g.1, g.2.trans h.2⟩⟩ + +theorem equiv_coeff (f : ∀ s, A.leg s ≃ B.leg s) + (h : ∀ x, A.coeff x = B.coeff (fun s => f s (x s))) : A ≈ B := by + refine ⟨Restricts.pullback (fun s => (f s).symm) ?_, Restricts.pullback (fun s => f s) h⟩ + intro x + simp only [h, Equiv.apply_symm_apply] + +theorem relabel (e : A.term ≃ B.term) (f : ∀ s, A.leg s ≃ B.leg s) + (h : ∀ i s x, A.factor i s x = B.factor (e i) s (f s x)) : A ≈ B := by + refine equiv_coeff f fun x => ?_ + simp only [coeff, h] + exact e.sum_comp (fun i => ∏ s, B.factor i s (f s (x s))) + +/-- Equivalences of all coordinates and terms that preserve the tensor factors. -/ +def Relabels (A B : Raw K S) : Prop := + ∃ (terms : A.term ≃ B.term) (legs : ∀ s, A.leg s ≃ B.leg s), + ∀ i s x, A.factor i s x = B.factor (terms i) s (legs s x) + +theorem relabel_of_relabels {A B : Raw K S} (h : Relabels A B) : A ≈ B := by + obtain ⟨terms, legs, factors⟩ := h + exact relabel terms legs factors + +end Raw +end MatrixMultiplicationAllFields.MatrixExponent.Spectral +end + +/- +# Direct sums and products of restrictions + +Use block diagonal matrices for sums and Kronecker products for products. +The identities concern coefficient arrays and require no termwise +correspondence between the decompositions. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S : Type} [CommSemiring K] [Fintype S] {A B C D : Raw K S} + +theorem coeff_mul (A B : Raw K S) (x : ∀ s, (A * B).leg s) : + (A * B).coeff x = A.coeff (fun s => (x s).1) * B.coeff (fun s => (x s).2) := by + change (∑ i : A.term × B.term, ∏ s, A.factor i.1 s (x s).1 * B.factor i.2 s (x s).2) = _ + simp only [coeff, Fintype.sum_prod_type, Finset.prod_mul_distrib, Finset.sum_mul_sum] + +/-- The Kronecker product of the local maps witnessing two restrictions. -/ +def restrictMulMap (L : (s : S) → B.leg s → A.leg s → K) + (M : (s : S) → D.leg s → C.leg s → K) : + (s : S) → (B * D).leg s → (A * C).leg s → K := + fun s x y => L s x.1 y.1 * M s x.2 y.2 + +theorem coeff_restrictMulMap (L : (s : S) → B.leg s → A.leg s → K) + (M : (s : S) → D.leg s → C.leg s → K) + (hL : ∀ x, B.coeff x = ∑ i : A.term, ∏ s, ∑ y, L s (x s) y * A.factor i s y) + (hM : ∀ x, D.coeff x = ∑ i : C.term, ∏ s, ∑ y, M s (x s) y * C.factor i s y) + (x : ∀ s, (B * D).leg s) : + (B * D).coeff x = ∑ i : (A * C).term, ∏ s, ∑ y : (A * C).leg s, + restrictMulMap L M s (x s) y * (A * C).factor i s y := by + rw [coeff_mul, hL, hM] + change _ = ∑ i : A.term × C.term, ∏ s, ∑ y : A.leg s × C.leg s, + L s (x s).1 y.1 * M s (x s).2 y.2 * (A.factor i.1 s y.1 * C.factor i.2 s y.2) + rw [Finset.sum_mul_sum, Fintype.sum_prod_type] + refine Finset.sum_congr rfl fun i _ => Finset.sum_congr rfl fun j _ => ?_ + rw [← Finset.prod_mul_distrib] + refine Finset.prod_congr rfl fun s _ => ?_ + rw [Finset.sum_mul_sum, Fintype.sum_prod_type] + exact Finset.sum_congr rfl fun _ _ => Finset.sum_congr rfl fun _ _ => mul_mul_mul_comm _ _ _ _ + +theorem Restricts.mul (h : A.Restricts B) (g : C.Restricts D) : + (A * C).Restricts (B * D) := by + obtain ⟨L, hL⟩ := h + obtain ⟨M, hM⟩ := g + exact ⟨restrictMulMap L M, coeff_restrictMulMap L M hL hM⟩ + +/-- Equality of coefficient arrays survives extending the factors by zero. -/ +theorem extend {I J : Type} [Fintype I] [Fintype J] {Z : S → Type} + (f : I → (s : S) → Z s → K) (g : J → (s : S) → Z s → K) + (h : ∀ x : ∀ s, Z s, (∑ i, ∏ s, f i s (x s)) = ∑ j, ∏ s, g j s (x s)) + {u : I → S → K} {v : J → S → K} + (huv : ∀ s, (∃ z, (∀ i, u i s = f i s z) ∧ (∀ j, v j s = g j s z)) ∨ + ((∀ i, u i s = 0) ∧ (∀ j, v j s = 0))) : + (∑ i, ∏ s, u i s) = ∑ j, ∏ s, v j s := by + classical + by_cases he : ∃ s, (∀ i, u i s = 0) ∧ (∀ j, v j s = 0) + · obtain ⟨s, hu, hv⟩ := he + exact (Finset.sum_eq_zero fun i _ => Finset.prod_eq_zero (Finset.mem_univ s) (hu i)).trans + (Finset.sum_eq_zero fun j _ => Finset.prod_eq_zero (Finset.mem_univ s) (hv j)).symm + · have hx (s : S) := (huv s).resolve_right fun hs => he ⟨s, hs⟩ + choose x hu hv using hx + simp only [hu, hv, h] + +/-- The block-diagonal sum of the local maps witnessing two restrictions. -/ +def restrictAddMap (L : (s : S) → B.leg s → A.leg s → K) + (M : (s : S) → D.leg s → C.leg s → K) (s : S) : + (B + D).leg s → (A + C).leg s → K := + Sum.elim (fun b => Sum.elim (L s b) (fun _ => 0)) + (fun d => Sum.elim (fun _ => 0) (M s d)) + +theorem coeff_restrictAddMap (L : (s : S) → B.leg s → A.leg s → K) + (M : (s : S) → D.leg s → C.leg s → K) + (hL : ∀ x, B.coeff x = ∑ i : A.term, ∏ s, ∑ y, L s (x s) y * A.factor i s y) + (hM : ∀ x, D.coeff x = ∑ i : C.term, ∏ s, ∑ y, M s (x s) y * C.factor i s y) + (x : ∀ s, (B + D).leg s) : + (B + D).coeff x = ∑ i : (A + C).term, ∏ s, ∑ y : (A + C).leg s, + restrictAddMap L M s (x s) y * (A + C).factor i s y := by + have left (i : A.term) (s : S) (y : A.leg s ⊕ C.leg s) : + (A + C).factor (.inl i) s y = Sum.elim (A.factor i s) (fun _ => 0) y := rfl + have right (i : C.term) (s : S) (y : A.leg s ⊕ C.leg s) : + (A + C).factor (.inr i) s y = Sum.elim (fun _ => 0) (C.factor i s) y := rfl + change (∑ i : B.term ⊕ D.term, ∏ s, (B + D).factor i s (x s)) = + ∑ i : A.term ⊕ C.term, ∏ s, ∑ y : A.leg s ⊕ C.leg s, + restrictAddMap L M s (x s) y * (A + C).factor i s y + simp only [Fintype.sum_sum_type, left, right] + refine congrArg₂ (· + ·) ?_ ?_ + · refine extend B.factor (fun i s z => ∑ y, L s z y * A.factor i s y) hL ?_ + intro s + cases x s with + | inl z => exact Or.inl ⟨z, fun _ => rfl, fun _ => by simp [restrictAddMap]⟩ + | inr z => exact Or.inr ⟨fun _ => rfl, fun _ => by simp [restrictAddMap]⟩ + · refine extend D.factor (fun i s z => ∑ y, M s z y * C.factor i s y) hM ?_ + intro s + cases x s with + | inl z => exact Or.inr ⟨fun _ => rfl, fun _ => by simp [restrictAddMap]⟩ + | inr z => exact Or.inl ⟨z, fun _ => rfl, fun _ => by simp [restrictAddMap]⟩ + +theorem Restricts.add (h : A.Restricts B) (g : C.Restricts D) : + (A + C).Restricts (B + D) := by + obtain ⟨L, hL⟩ := h + obtain ⟨M, hM⟩ := g + exact ⟨restrictAddMap L M, coeff_restrictAddMap L M hL hM⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +section +/- +# Semiring laws up to mutual restriction + +Each identity reindexes the terms and the coordinates at every site by +the same sum or product equivalence. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S : Type} [CommSemiring K] (A B C : Raw K S) + +theorem comm_add_relabels : Relabels (A + B) (B + A) := by + refine ⟨(Equiv.sumComm _ _), (fun _ => Equiv.sumComm _ _), ?_⟩ + rintro (i | i) s (x | x) <;> rfl + +theorem assoc_add_relabels : Relabels ((A + B) + C) (A + (B + C)) := by + refine ⟨(Equiv.sumAssoc _ _ _), (fun _ => Equiv.sumAssoc _ _ _), ?_⟩ + rintro ((i | i) | i) s ((x | x) | x) <;> rfl + +theorem nil_add_relabels : Relabels (0 + A) A := by + refine ⟨(Equiv.emptySum Empty _), (fun _ => Equiv.emptySum Empty _), ?_⟩ + rintro (i | i) + · exact i.elim + rintro s (x | x) + · exact x.elim + rfl + +theorem comm_mul_relabels : Relabels (A * B) (B * A) := by + refine ⟨(Equiv.prodComm _ _), (fun _ => Equiv.prodComm _ _), ?_⟩ + intro i s x + exact mul_comm _ _ + +theorem assoc_mul_relabels : Relabels ((A * B) * C) (A * (B * C)) := by + refine ⟨(Equiv.prodAssoc _ _ _), (fun _ => Equiv.prodAssoc _ _ _), ?_⟩ + intro i s x + exact mul_assoc _ _ _ + +theorem unit_mul_relabels : Relabels (1 * A) A := by + refine ⟨(Equiv.punitProd _), (fun _ => Equiv.punitProd _), ?_⟩ + intro i s x + exact one_mul _ + +theorem nil_mul_relabels : Relabels (0 * A) 0 := by + refine ⟨(Equiv.emptyProd _), (fun _ => Equiv.emptyProd _), ?_⟩ + intro i + exact i.1.elim + +theorem distrib_left_relabels : Relabels (A * (B + C)) (A * B + A * C) := by + refine ⟨(Equiv.prodSumDistrib _ _ _), (fun _ => Equiv.prodSumDistrib _ _ _), ?_⟩ + rintro ⟨i, j | j⟩ s ⟨x, y | y⟩ + · rfl + · exact mul_zero _ + · exact mul_zero _ + · rfl +variable [Fintype S] + +theorem comm_add : A + B ≈ B + A := + relabel_of_relabels (comm_add_relabels A B) + +theorem assoc_add : (A + B) + C ≈ A + (B + C) := + relabel_of_relabels (assoc_add_relabels A B C) + +theorem nil_add : 0 + A ≈ A := + relabel_of_relabels (nil_add_relabels A) + +theorem comm_mul : A * B ≈ B * A := + relabel_of_relabels (comm_mul_relabels A B) + +theorem assoc_mul : (A * B) * C ≈ A * (B * C) := + relabel_of_relabels (assoc_mul_relabels A B C) + +theorem unit_mul : 1 * A ≈ A := + relabel_of_relabels (unit_mul_relabels A) + +theorem nil_mul : 0 * A ≈ 0 := + relabel_of_relabels (nil_mul_relabels A) + +theorem distrib_left : A * (B + C) ≈ A * B + A * C := + relabel_of_relabels (distrib_left_relabels A B C) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end + +/- +# The restriction semiring on a fixed finite set of sites +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +namespace Raw + +variable {K S : Type} [CommSemiring K] + +/-- Order tensor classes by reverse restriction for the chosen relation. -/ +@[instance_reducible] +def quotientLE (s : Setoid (Raw K S)) (restricts : Raw K S → Raw K S → Prop) + (equivalent : ∀ a b, s.r a b ↔ restricts a b ∧ restricts b a) + (transitive : ∀ {a b c}, restricts a b → restricts b c → restricts a c) : LE (Quotient s) := + ⟨Quotient.lift₂ (fun a b => restricts b a) fun a b a' b' ha hb => by + obtain ⟨haa', ha'a⟩ := (equivalent a a').mp ha + obtain ⟨hbb', hb'b⟩ := (equivalent b b').mp hb + exact propext ⟨fun h => transitive hb'b (transitive h haa'), + fun h => transitive hbb' (transitive h ha'a)⟩⟩ + +/-- Mutual restriction yields antisymmetry on tensor classes. -/ +@[instance_reducible] +def quotientOrder (s : Setoid (Raw K S)) (restricts : Raw K S → Raw K S → Prop) + (equivalent : ∀ a b, s.r a b ↔ restricts a b ∧ restricts b a) + (reflexive : ∀ a, restricts a a) + (transitive : ∀ {a b c}, restricts a b → restricts b c → restricts a c) : + PartialOrder (Quotient s) := + letI : LE (Quotient s) := quotientLE s restricts equivalent transitive + { le_refl := fun A => Quotient.inductionOn A reflexive + le_trans := fun A B C => Quotient.inductionOn₃ A B C fun _ _ _ h g => transitive g h + le_antisymm := fun A B => Quotient.inductionOn₂ A B fun a b h g => + Quotient.sound ((equivalent a b).mpr ⟨g, h⟩) } + +/-- Lift a binary operation on tensor tables that respects the chosen setoid. -/ +def quotientOperation (s : Setoid (Raw K S)) (operation : Raw K S → Raw K S → Raw K S) + (congruent : ∀ {a a' b b'}, s.r a a' → s.r b b' → s.r (operation a b) (operation a' b')) : + Quotient s → Quotient s → Quotient s := + Quotient.map₂ operation fun _ _ ha _ _ hb => congruent ha hb + +/-- The raw tensor relabelings supply the laws for either restriction semiring. -/ +@[instance_reducible] +def quotientSemiring (s : Setoid (Raw K S)) + (addCongr : ∀ {a a' b b'}, s.r a a' → s.r b b' → s.r (a + b) (a' + b')) + (mulCongr : ∀ {a a' b b'}, s.r a a' → s.r b b' → s.r (a * b) (a' * b')) + (relabel : ∀ {a b}, Relabels a b → s.r a b) : CommSemiring (Quotient s) := by + letI : Zero (Quotient s) := ⟨Quotient.mk s 0⟩ + letI : One (Quotient s) := ⟨Quotient.mk s 1⟩ + letI : Add (Quotient s) := ⟨quotientOperation s (· + ·) addCongr⟩ + letI : Mul (Quotient s) := ⟨quotientOperation s (· * ·) mulCongr⟩ + have addComm (A B : Quotient s) : A + B = B + A := + Quotient.inductionOn₂ A B fun a b => Quotient.sound (relabel (comm_add_relabels a b)) + have mulComm (A B : Quotient s) : A * B = B * A := + Quotient.inductionOn₂ A B fun a b => Quotient.sound (relabel (comm_mul_relabels a b)) + have zeroAdd (A : Quotient s) : 0 + A = A := + Quotient.inductionOn A fun a => Quotient.sound (relabel (nil_add_relabels a)) + have oneMul (A : Quotient s) : 1 * A = A := + Quotient.inductionOn A fun a => Quotient.sound (relabel (unit_mul_relabels a)) + have zeroMul (A : Quotient s) : 0 * A = 0 := + Quotient.inductionOn A fun a => Quotient.sound (relabel (nil_mul_relabels a)) + have leftDistrib (A B C : Quotient s) : A * (B + C) = A * B + A * C := + Quotient.inductionOn₃ A B C fun a b c => Quotient.sound (relabel (distrib_left_relabels a b c)) + exact { + add := (· + ·) + mul := (· * ·) + zero := 0 + one := 1 + nsmul := nsmulRec + add_assoc := fun A B C => Quotient.inductionOn₃ A B C fun a b c => + Quotient.sound (relabel (assoc_add_relabels a b c)) + add_comm := addComm + zero_add := zeroAdd + add_zero := fun A => (addComm A 0).trans (zeroAdd A) + mul_assoc := fun A B C => Quotient.inductionOn₃ A B C fun a b c => + Quotient.sound (relabel (assoc_mul_relabels a b c)) + mul_comm := mulComm + one_mul := oneMul + mul_one := fun A => (mulComm A 1).trans (oneMul A) + zero_mul := zeroMul + mul_zero := fun A => (mulComm A 0).trans (zeroMul A) + left_distrib := leftDistrib + right_distrib := fun A B C => by rw [mulComm, leftDistrib, mulComm C A, mulComm C B] } + +end Raw + +/-- Coefficient tensors modulo mutual local linear restriction. -/ +def Tensor (K S : Type) [CommSemiring K] [Fintype S] := + Quotient (inferInstance : Setoid (Raw K S)) + +namespace Tensor + +variable {K S : Type} [CommSemiring K] [Fintype S] + +/-- Passes a raw multilinear table to its equivalence class under mutual restriction. -/ +def ofRaw (A : Raw K S) : Tensor K S := Quotient.mk _ A + +theorem ofRaw_eq {A B : Raw K S} (h : A ≈ B) : ofRaw A = ofRaw B := + Quotient.sound h + +instance : LE (Tensor K S) := + Raw.quotientLE (inferInstance : Setoid (Raw K S)) Raw.Restricts (fun _ _ => Iff.rfl) + (fun h g => Raw.Restricts.trans h g) + +theorem ofRaw_le (A B : Raw K S) : ofRaw A ≤ ofRaw B ↔ B.Restricts A := Iff.rfl + +instance : PartialOrder (Tensor K S) := + Raw.quotientOrder (inferInstance : Setoid (Raw K S)) Raw.Restricts + (fun _ _ => Iff.rfl) Raw.Restricts.refl (fun h g => Raw.Restricts.trans h g) + +instance : Zero (Tensor K S) := ⟨ofRaw 0⟩ +instance : One (Tensor K S) := ⟨ofRaw 1⟩ + +instance : Add (Tensor K S) := + ⟨Raw.quotientOperation (inferInstance : Setoid (Raw K S)) (· + ·) + fun h g => ⟨h.1.add g.1, h.2.add g.2⟩⟩ + +instance : Mul (Tensor K S) := + ⟨Raw.quotientOperation (inferInstance : Setoid (Raw K S)) (· * ·) + fun h g => ⟨h.1.mul g.1, h.2.mul g.2⟩⟩ + +theorem ofRaw_add (A B : Raw K S) : ofRaw (A + B) = ofRaw A + ofRaw B := rfl +theorem ofRaw_mul (A B : Raw K S) : ofRaw (A * B) = ofRaw A * ofRaw B := rfl + +instance : CommSemiring (Tensor K S) := by + let laws : CommSemiring (Tensor K S) := + Raw.quotientSemiring (inferInstance : Setoid (Raw K S)) + (fun h g => ⟨h.1.add g.1, h.2.add g.2⟩) + (fun h g => ⟨h.1.mul g.1, h.2.mul g.2⟩) Raw.relabel_of_relabels + exact { laws with + add := (· + ·) + mul := (· * ·) + zero := 0 + one := 1 } + +theorem comm_add (A B : Tensor K S) : A + B = B + A := add_comm A B + +theorem comm_mul (A B : Tensor K S) : A * B = B * A := mul_comm A B + +theorem distrib_left (A B C : Tensor K S) : A * (B + C) = A * B + A * C := + (inferInstance : CommSemiring (Tensor K S)).left_distrib A B C + +theorem add_le_add_right (A B C : Tensor K S) : A ≤ B → A + C ≤ B + C := + Quotient.inductionOn₃ A B C fun _ _ c h => Raw.Restricts.add h (.refl c) + +theorem mul_le_mul_left (A B C : Tensor K S) : A ≤ B → C * A ≤ C * B := + Quotient.inductionOn₃ A B C fun _ _ c h => Raw.Restricts.mul (.refl c) h + +end Tensor +end MatrixMultiplicationAllFields.MatrixExponent.Spectral +end + +/- +# Finite coefficient tables + +The product of local coordinate selectors is a weighted Kronecker delta. +It suffices to put the weight at one site. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw + +variable {K S : Type} [Fintype S] [Nonempty S] + +section Tables + +variable [CommSemiring K] + +open Classical in +/-- Selects the appropriate branch of `if y = x s then if s = Classical.arbitrary S then a else +1 else 0`. -/ +def selector {X : S → Type} (x : ∀ s, X s) (a : K) (s : S) (y : X s) : K := + if y = x s then if s = Classical.arbitrary S then a else 1 else 0 + +open Classical in +private theorem prod_selector {X : S → Type} (x y : ∀ s, X s) (a : K) : + (∏ s, selector x a s (y s)) = if y = x then a else 0 := by + by_cases h : y = x + · subst y + simp [selector] + · rw [ite_eq_right h] + obtain ⟨s, hs⟩ := Function.ne_iff.mp h + exact Finset.prod_eq_zero (Finset.mem_univ s) (ite_eq_right hs) + +variable (X : S → Type) [∀ s, Fintype (X s)] + +/-- Coordinate expansion of any finite array as a sum of pure tensors. -/ +def ofTable (f : (∀ s, X s) → K) : Raw K S := by + classical + exact ⟨X, ∀ s, X s, fun i => selector i (f i)⟩ + +@[simp] theorem coeff_ofTable (f : (∀ s, X s) → K) (x : ∀ s, X s) : + (ofTable X f).coeff x = f x := by + classical + change (∑ i : ∀ s, X s, ∏ s, selector i (f i) s (x s)) = _ + simp [prod_selector] + +end Tables + +variable [Field K] + +/-- Selecting a nonzero coefficient and scaling by its inverse recovers the unit. -/ +theorem restricts_one (A : Raw K S) (h : ∃ x, A.coeff x ≠ 0) : A.Restricts 1 := by + classical + obtain ⟨x, hx⟩ := h + refine (restricts_iff _ _).mpr ⟨fun s _ => selector x (A.coeff x)⁻¹ s, fun _ => ?_⟩ + change (∑ _ : Unit, ∏ _ : S, (1 : K)) = _ + simp [prod_selector, ite_mul, hx] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Raw +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Span.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Span.lean new file mode 100644 index 0000000000..5372278eb0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Span.lean @@ -0,0 +1,91 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place + +/-! +# Ordinary linear combinations and bipartite decompositions +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S J U : Type} [Field K] [Fintype S] [Nonempty S] [Fintype J] + (X : S → Type) [∀ s, Fintype (X s)] (T : (∀ s, X s) → K) + +theorem span_le (V : J → (∀ s, X s) → K) (a : J → K) (h : ∀ x, T x = ∑ j, a j * V j x) : + ofRaw (Raw.ofTable X T) ≤ ∑ j, ofRaw (Raw.ofTable X (V j)) := by + classical + let A j := Raw.ofTable X (V j) + let w j s := if s = Classical.arbitrary S then a j else 1 + let M j (s : S) (x y : X s) := if y = x then w j s else 0 + refine (Raw.restriction_sum_iff A (Raw.ofTable X T) Finset.univ).mpr ⟨M, fun x => ?_⟩ + change (∀ s, X s) at x + rw [Raw.coeff_ofTable, h] + refine Finset.sum_congr rfl fun j _ => ?_ + rw [← Raw.coeff_ofTable X (V j) x] + change a j * (∑ i : (A j).term, ∏ s, (A j).factor i s (x s)) = + ∑ i : (A j).term, ∏ s, ∑ y : X s, M j s (x s) y * (A j).factor i s y + simp only [M, ite_mul, zero_mul, Finset.sum_ite_eq', Finset.mem_univ, ite_true, + Finset.prod_mul_distrib, Finset.mul_sum] + simp [w] + +variable [DecidableEq S] [Fintype U] [DecidableEq U] + +/-- Transport two groups of sites to two endpoints. A separated-variable +expansion costs no more than one wire indexed by the summands. -/ +theorem separated_le (B : S → Prop) [DecidablePred B] (L R : J → (∀ s, X s) → K) + (h : ∀ x, T x = ∑ j, L j x * R j x) + (hL : ∀ j x y, (∀ s, B s → x s = y s) → L j x = L j y) + (hR : ∀ j x y, (∀ s, ¬ B s → x s = y s) → R j x = R j y) (m o : U) : + place (fun s => if B s then m else o) (ofRaw (Raw.ofTable X T)) ≤ + wire K m o (Fintype.card J) := by + classical + let f s := decide (B s) + let g (b : Bool) := if b then m else o + let A := Raw.ofTable X T + by_cases hx : Nonempty (∀ s, X s) + swap + · have hz : ofRaw A = 0 := (ofRaw_eq_zero A).mpr (fun x => False.elim (hx ⟨x⟩)) + let _ : Nonempty U := ⟨m⟩ + rw [show ofRaw (Raw.ofTable X T) = 0 from hz, place_zero] + exact zero_le _ + let fill (b : Bool) (x : (A.group f).leg b) (s : S) : X s := + if hs : f s = b then x ⟨s, hs⟩ else hx.some s + let D : Raw K Bool := + ⟨(A.group f).leg, J, fun j b x => if b then L j (fill b x) else R j (fill b x)⟩ + have he : A.group f ≈ D := by + refine Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_ + let v (s : S) : X s := x (f s) ⟨s, rfl⟩ + have hv (b : Bool) (s : S) (hs : f s = b) : v s = fill b (x b) s := by + subst b + unfold fill + erw [dite_eq_left (show f s = f s from rfl)] + rw [Raw.coeff_group] + change A.coeff v = D.coeff x + rw [show A.coeff v = T v from Raw.coeff_ofTable _ _ _, h] + refine Finset.sum_congr rfl fun j _ => ?_ + change _ = ∏ b : Bool, if b then L j (fill b (x b)) else R j (fill b (x b)) + rw [Fintype.prod_bool] + simp only [Bool.false_eq_true, ↓reduceIte] + exact congrArg₂ (· * ·) (hL _ _ _ (fun s hs => hv _ _ (by simp [f, hs]))) + (hR _ _ _ (fun s hs => hv _ _ (by simp [f, hs]))) + have hd : place f (ofRaw A) ≤ wire K true false (Fintype.card J) := by + rw [place_ofRaw, ofRaw_eq he, wire, show ({true, false} : Finset Bool) = Finset.univ by decide, + shared_all] + exact le_term_count D + have hg := place_mono g hd + rw [← place_comp, place_wire] at hg + have e : g ∘ f = fun s => if B s then m else o := by ext s; simp [g, f] + rw [e] at hg + exact hg + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Transport.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Transport.lean new file mode 100644 index 0000000000..c059e5df3f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Transport.lean @@ -0,0 +1,879 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Fintype.Powerset +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.Ring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Wire +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterPower +public import Mathlib.Analysis.SpecialFunctions.Pow.Real + +/-! +# Exterior creation and contraction + +Use the signed subset basis. Index a degree by its cardinality plus +one, so degree zero has a predecessor with empty basis. Maximizing +the weighted dimension bounds both neighboring dimensions at once. +-/ + +@[expose] public section + +section + +open Finset + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +private def level (q l : ℕ) : Finset (Finset (Fin q)) := + univ.filter (fun x => x.card + 1 = l) + +private theorem optimal_level (q : ℕ) (r : ℝ) (hr : 0 < r) : + ∃ l : ℕ, 0 < (level q l).card ∧ + ((level q (l + 1)).card : ℝ) ≤ (level q l).card * r ∧ + ((level q (l - 1)).card : ℝ) * r ≤ (level q l).card := by + let score (l : ℕ) := ((level q l).card : ℝ) / r ^ l + obtain ⟨l, _, hmax⟩ := (range (q + 3)).exists_max_image score (by simp) + have hl : 0 < (level q l).card := by + have h1 : 0 < (level q 1).card := card_pos.mpr ⟨∅, by simp [level]⟩ + have hs : 0 < score 1 := div_pos (Nat.cast_pos.mpr h1) (pow_pos hr _) + exact Nat.cast_pos.mp ((div_pos_iff_of_pos_right (pow_pos hr l)).mp + (hs.trans_le (hmax 1 (by simp)))) + obtain ⟨x, hx⟩ := card_pos.mp hl + have hx' := (mem_filter.mp hx).2 + have hq : x.card ≤ q := by simpa using card_le_univ x + refine ⟨l, hl, ?_, ?_⟩ + · have h := (div_le_div_iff₀ (pow_pos hr _) (pow_pos hr _)).mp + (hmax (l + 1) (mem_range.mpr (by omega))) + apply (mul_le_mul_iff_left₀ (pow_pos hr l)).mp + simpa only [pow_succ', ← mul_assoc] using h + · have h := (div_le_div_iff₀ (pow_pos hr _) (pow_pos hr _)).mp + (hmax (l - 1) (mem_range.mpr (by omega))) + have heq : r ^ l = r * r ^ (l - 1) := by rw [← pow_succ', Nat.sub_add_cancel (by omega)] + apply (mul_le_mul_iff_left₀ (pow_pos hr (l - 1))).mp + simpa only [heq, ← mul_assoc] using h + +variable {q : ℕ} (K : Type) [Field K] + +private def sign (i : Fin q) (x : Finset (Fin q)) : K := + (-1) ^ (x.filter (· < i)).card + +private theorem sign_sq (i : Fin q) (x : Finset (Fin q)) : + sign K i x * sign K i x = 1 := by + simp [sign, ← mul_pow] + +private theorem sign_insert {i j : Fin q} {x : Finset (Fin q)} (hj : j ∉ x) : + sign K i (insert j x) = if j < i then -sign K i x else sign K i x := by + have h : j ∉ x.filter (· < i) := fun hj' => hj (mem_filter.mp hj').1 + by_cases e : j < i <;> simp [sign, filter_insert, e, h, pow_succ] + +private theorem sign_erase {i j : Fin q} {x : Finset (Fin q)} (hj : j ∈ x) : + sign K i (x.erase j) = if j < i then -sign K i x else sign K i x := by + have h := sign_insert K (i := i) (j := j) (x := x.erase j) (by simp) + rw [insert_erase hj] at h + by_cases e : j < i <;> simp [e, h] + +private def create (i : Fin q) (x y : Finset (Fin q)) : K := + if i ∈ x then 0 else if insert i x = y then sign K i x else 0 + +private def contract (i : Fin q) (x y : Finset (Fin q)) : K := + if i ∈ x then if x.erase i = y then sign K i x else 0 else 0 + +private theorem anticommutator {l : ℕ} (i j : Fin q) (x y : Finset (Fin q)) (hx : x ∈ level q l) : + (∑ z ∈ level q (l + 1), create K i x z * contract K j z y) + + (∑ z ∈ level q (l - 1), contract K j x z * create K i z y) = + if i = j ∧ x = y then 1 else 0 := by + have hx' := (mem_filter.mp hx).2 + have hu : (∑ z ∈ level q (l + 1), create K i x z * contract K j z y) = + if i ∈ x then 0 else sign K i x * contract K j (insert i x) y := by + by_cases hi : i ∈ x + · simp [create, hi] + · have ht : insert i x ∈ level q (l + 1) := by simp [level, hi, hx'] + simp [create, hi, ite_mul, ht] + have hd : (∑ z ∈ level q (l - 1), contract K j x z * create K i z y) = + if j ∈ x then sign K j x * create K i (x.erase j) y else 0 := by + by_cases hj : j ∈ x + · have ht : x.erase j ∈ level q (l - 1) := by + have := card_erase_add_one hj + exact mem_filter.mpr ⟨mem_univ _, by omega⟩ + simp [contract, hj, ite_mul, ht] + · simp [contract, hj] + rw [hu, hd] + by_cases he : i = j + · subst j + by_cases hi : i ∈ x + · simp [hi, create, insert_erase hi, sign_erase K hi, mul_ite, sign_sq] + · simp [hi, contract, sign_insert K hi, mul_ite, sign_sq] + · by_cases hi : i ∈ x + · simp [hi, he, create] + by_cases hj : j ∈ x + · rw [ite_eq_right hi, ite_eq_left hj] + simp only [contract, create, mem_erase, mem_insert, hj, hi, or_true, and_false, + ite_false, ite_true, erase_insert_of_ne he, sign_insert K hi, sign_erase K hj, + he, false_and] + by_cases ht : insert i (x.erase j) = y + · rcases lt_or_gt_of_ne he with h | h <;> simp [ht, h, h.not_gt, mul_comm] + · simp [ht] + · simp [hi, hj, he, Ne.symm he, contract] + +private noncomputable def entry (s : Finset (Finset (Fin q))) (i : Fin s.card) : Finset (Fin q) := + (s.equivFin.symm i).val + +private theorem sum_entry (s : Finset (Finset (Fin q))) (f : Finset (Fin q) → K) : + (∑ i, f (entry s i)) = ∑ x ∈ s, f x := + (s.equivFin.symm.sum_comp (fun x => f x.val)).trans (sum_coe_sort s f) + +/-- The two orders of creation and contraction sum to the identity +for equal labels and to zero for unequal labels, in every characteristic. -/ +theorem exterior (q : ℕ) (r : ℝ) (hr : 0 < r) : + ∃ H P M : ℕ, 0 < H ∧ (P : ℝ) ≤ H * r ∧ (M : ℝ) * r ≤ H ∧ + ∃ (L : Fin q → Fin H → Fin P → K) (D : Fin q → Fin P → Fin H → K) + (A : Fin q → Fin H → Fin M → K) (B : Fin q → Fin M → Fin H → K), + ∀ i j x y, (∑ z, L i x z * D j z y) + (∑ z, A j x z * B i z y) = + if i = j ∧ x = y then 1 else 0 := by + obtain ⟨l, hH, hP, hM⟩ := optimal_level q r hr + let H := level q l + let P := level q (l + 1) + let M := level q (l - 1) + refine ⟨H.card, P.card, M.card, hH, hP, hM, + fun i x z => create K i (entry H x) (entry P z), + fun j z y => contract K j (entry P z) (entry H y), + fun j x z => contract K j (entry H x) (entry M z), + fun i z y => create K i (entry M z) (entry H y), ?_⟩ + intro i j x y + have he : Function.Injective (entry H) := Subtype.val_injective.comp H.equivFin.symm.injective + rw [sum_entry K P (fun z => create K i (entry H x) z * contract K j z (entry H y)), + sum_entry K M (fun z => contract K j (entry H x) z * create K i z (entry H y))] + simpa only [he.eq_iff] using + anticommutator K i j (entry H x) (entry H y) (H.equivFin.symm x).property + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral +end + +/- # Joining shared labels by local equality tests -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +open Raw (port) +variable (K : Type) [Field K] {S : Type} [Fintype S] [DecidableEq S] + +theorem shared_subset {U V : Finset S} (h : U ⊆ V) (n : ℕ) : + shared K U n ≤ shared K V n := by + let L (s : S) (x y : Fin n) := if x = port U s y then (1 : K) else 0 + refine ⟨L, fun x => ?_⟩ + change S → Fin n at x + change (∑ i : Fin n, ∏ s, if x s = port U s i then (1 : K) else 0) = + ∑ i : Fin n, ∏ s, ∑ y, L s (x s) y * if y = port V s i then 1 else 0 + simp only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', Finset.mem_univ, ite_true, L] + apply Finset.sum_congr rfl + intro i _ + apply Finset.prod_congr rfl + intro s _ + by_cases hs : s ∈ U + · simp [port, hs, h hs] + · simp [port, hs] + +theorem shared_join {U V : Finset S} {c : S} (hu : c ∈ U) (hv : c ∈ V) (n : ℕ) : + shared K (U ∪ V) n ≤ shared K U n * shared K V n := by + let L (s : S) (x : Fin n) (y : Fin n × Fin n) := + if (s = c → y.1 = y.2) ∧ x = (if s ∈ U then y.1 else y.2) then (1 : K) else 0 + refine ⟨L, fun x => ?_⟩ + change S → Fin n at x + change (∑ i : Fin n, ∏ s, if x s = port (U ∪ V) s i then (1 : K) else 0) = + ∑ ij : Fin n × Fin n, ∏ s, ∑ y, L s (x s) y * + ((if y.1 = port U s ij.1 then 1 else 0) * (if y.2 = port V s ij.2 then 1 else 0)) + simp only [Fintype.sum_prod_type, mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', + Finset.mem_univ, ite_true] + apply Finset.sum_congr rfl + intro i _ + rw [Fintype.sum_eq_single i] + · apply Finset.prod_congr rfl + intro s _ + by_cases e : s = c + · subst s + simp [L, port, hu, hv] + · by_cases hs : s ∈ U <;> simp [L, port, hs, e] + · intro j hj + apply Finset.prod_eq_zero (Finset.mem_univ c) + simp [L, port, hu, hv, hj.symm] + +theorem wire_triangle (a b c : S) (n : ℕ) : + wire K a c n ≤ wire K a b n * wire K b c n := + (shared_subset K (by simp [Finset.insert_subset_iff]) n).trans + (shared_join K (c := b) (U := {a, b}) (V := {b, c}) (by simp) (by simp) n) + +theorem wire_self (a : S) {n : ℕ} (hn : 0 < n) : wire K a a n = 1 := by + apply le_antisymm _ (one_le_wire K a a hn) + let L (s : S) (x : Fin n) (_ : Unit) := + if s = a ∨ x.val = 0 then (1 : K) else 0 + refine ⟨L, fun x => ?_⟩ + change S → Fin n at x + change (∑ i : Fin n, ∏ s, if x s = port {a, a} s i then (1 : K) else 0) = + ∑ _ : Unit, ∏ s, ∑ j : Unit, L s (x s) j * 1 + rw [Fintype.sum_eq_single (x a)] + · simp only [Fintype.sum_unique, mul_one] + apply Finset.prod_congr rfl + intro s _ + by_cases hs : s = a <;> simp [L, port, hs, Fin.ext_iff] + · intro i hi + apply Finset.prod_eq_zero (Finset.mem_univ a) + simp [port, hi.symm] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- +# Restriction using shared indices + +Each assignment of shared indices exposes a label at each site. Local +maps may read the label, select an input coordinate and apply a scalar. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S X Y I J L M : Type} [Field K] [Fintype S] [Nonempty S] + [Fintype X] [Fintype Y] [Fintype I] [Fintype J] [Fintype L] [Fintype M] [DecidableEq L] + [DecidableEq M] + +open Classical in +/-- The indexed operation `ofRaw (Raw.ofTable (fun _ => X) f)`. -/ +def array (f : (S → X) → K) : Tensor K S := ofRaw (Raw.ofTable (fun _ => X) f) + +open Classical in +/-- The value specified by `ofRaw ⟨fun _ => L, I, fun i s x => if x = e s i then 1 else 0⟩`. -/ +def signals (K : Type) [Field K] (e : S → I → L) : Tensor K S := + ofRaw ⟨fun _ => L, I, fun i s x => if x = e s i then 1 else 0⟩ + +omit [Nonempty S] in +open Classical in +theorem signals_wire [DecidableEq S] (a b : S) (n : ℕ) : + signals K (Raw.port (n := n) {a, b}) = wire K a b n := rfl + +omit [Nonempty S] in +open Classical in +theorem signals_mul (e : S → I → L) (f : S → J → M) : + signals K (fun s (i : I × J) => (e s i.1, f s i.2)) = signals K e * signals K f := by + apply ofRaw_eq + refine Raw.relabel (Equiv.refl _) (fun _ => Equiv.refl _) fun i s x => ?_ + change I × J at i + change L × M at x + change (if x = (e s i.1, f s i.2) then (1 : K) else 0) = + (if x.1 = e s i.1 then 1 else 0) * (if x.2 = f s i.2 then 1 else 0) + simp only [Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul] + +open Classical in +theorem use_signals (A : (S → X) → K) (B : (S → Y) → K) (e : S → I → L) + (v : S → Y → L → K) (g : S → Y → L → X) + (h : ∀ y, B y = ∑ i, (∏ s, v s (y s) (e s i)) * A (fun s => g s (y s) (e s i))) : + array B ≤ array A * signals K e := by + let P := Raw.ofTable (fun _ => X) A + let Q := Raw.ofTable (fun _ => Y) B + let f (s : S) (y : Y) (p : X × L) := if p.1 = g s y p.2 then v s y p.2 else 0 + refine ⟨f, fun y => ?_⟩ + change S → Y at y + change Q.coeff y = ∑ t : P.term × I, ∏ s, ∑ p : X × L, f s (y s) p * + (P.factor t.1 s p.1 * if p.2 = e s t.2 then 1 else 0) + rw [show Q.coeff y = B y from Raw.coeff_ofTable _ _ _, h] + simp only [Fintype.sum_prod_type, mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', + Finset.mem_univ, ite_true, f, ite_mul, zero_mul, Finset.prod_mul_distrib] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i _ + rw [← Finset.mul_sum] + congr 1 + exact (Raw.coeff_ofTable _ A _).symm + +open Classical in +theorem array_pullback (A : (S → X) → K) (B : (S → Y) → K) (g : S → Y → X) + (h : ∀ y, B y = A (fun s => g s (y s))) : array B ≤ array A := by + apply Raw.Restricts.pullback g + intro y + exact (Raw.coeff_ofTable _ B _).trans ((h y).trans (Raw.coeff_ofTable _ A _).symm) + +open Classical in +theorem array_mul (A : (S → X) → K) (B : (S → Y) → K) : + array (fun y : S → X × Y => A (fun s => (y s).1) * B (fun s => (y s).2)) = + array A * array B := by + apply ofRaw_eq + refine Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_ + rw [Raw.coeff_mul] + change S → X × Y at x + exact (Raw.coeff_ofTable _ _ x).trans + (congrArg₂ (· * ·) (Raw.coeff_ofTable _ A _).symm (Raw.coeff_ofTable _ B _).symm) + +open Classical in +theorem array_sum (A B : (S → X) → K) : array (fun y => A y + B y) ≤ array A + array B := by + let P := Raw.ofTable (fun _ => X) A + let Q := Raw.ofTable (fun _ => X) B + let f (_ : S) (x : X) (y : X ⊕ X) := if Sum.elim id id y = x then (1 : K) else 0 + refine ⟨f, fun x => ?_⟩ + change S → X at x + change (Raw.ofTable _ _).coeff x = ∑ t : P.term ⊕ Q.term, ∏ s, + ∑ y : X ⊕ X, f s (x s) y * (P + Q).factor t s y + simp only [Raw.coeff_ofTable, Fintype.sum_sum_type] + change _ = (∑ t : P.term, ∏ s, ((∑ y, f s (x s) (.inl y) * P.factor t s y) + + ∑ y, f s (x s) (.inr y) * 0)) + + ∑ t : Q.term, ∏ s, ((∑ y, f s (x s) (.inl y) * 0) + + ∑ y, f s (x s) (.inr y) * Q.factor t s y) + have hf (z : X) (q : X → K) : (∑ y, (if y = z then (1 : K) else 0) * q y) = q z := + by simp [ite_mul] + simp only [f, Sum.elim_inl, Sum.elim_inr, id_eq, mul_zero, Finset.sum_const_zero, + add_zero, zero_add] + change _ = (∑ t : P.term, ∏ s, ∑ y : X, (if y = x s then 1 else 0) * P.factor t s y) + + ∑ t : Q.term, ∏ s, ∑ y : X, (if y = x s then 1 else 0) * Q.factor t s y + refine (congrArg₂ (· + ·) (Raw.coeff_ofTable _ A x).symm (Raw.coeff_ofTable _ B x).symm).trans ?_ + apply congrArg₂ (· + ·) <;> apply Finset.sum_congr rfl <;> intro i _ <;> + apply Finset.prod_congr rfl <;> intro s _ <;> exact (hf (x s) _).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- # Equality of marked indices as a wire -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] + +omit [DecidableEq S] [Nonempty S] in +private theorem weighted_pullback (P Q : Raw K S) (g : ∀ s, Q.leg s → P.leg s) + (v : ∀ s, Q.leg s → K) + (h : ∀ x, Q.coeff x = (∏ s, v s (x s)) * P.coeff (fun s => g s (x s))) : + ofRaw Q ≤ ofRaw P := by + classical + refine ⟨fun s x y => if y = g s x then v s x else 0, fun x => ?_⟩ + rw [h, Raw.coeff, Finset.mul_sum] + simp only [ite_mul, zero_mul, Finset.sum_ite_eq', Finset.mem_univ, ite_true, + Finset.prod_mul_distrib] + +/-- Indexes the slot by the coordinates of `X × Fin q × Fin q`. -/ +abbrev Slot (X : Type) (q : ℕ) := X × Fin q × Fin q + +/-- Inactive indices may be ignored instead of fixed to zero. -/ +def link (K : Type) [Field K] (a b : S) (q : ℕ) (x : S → Slot Unit q) : K := + if (x a).2.1 = (x b).2.2 then 1 else 0 + +theorem array_link (a b : S) (q : ℕ) : array (link K a b q) = wire K a b q := by + classical + apply le_antisymm + · let L (s : S) (x : Slot Unit q) (y : Fin q) : K := + (if s = a then if x.2.1 = y then 1 else 0 else 1) * + (if s = b then if x.2.2 = y then 1 else 0 else 1) + refine ⟨L, fun x => ?_⟩ + change S → Slot Unit q at x + rw [Raw.coeff_ofTable] + change link K a b q x = ∑ i : Fin q, ∏ s, ∑ j, L s (x s) j * + if j = Raw.port {a, b} s i then 1 else 0 + simp only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', Finset.mem_univ, ite_true] + simp only [L, Finset.prod_mul_distrib] + simp [Raw.port, link, mul_ite] + · let v (s : S) (x : Fin q) := if s = a ∨ s = b ∨ x.val = 0 then (1 : K) else 0 + apply weighted_pullback _ _ (fun _ (x : Fin q) => ((), x, x)) v + intro x + change S → Fin q at x + rw [Raw.coeff_ofTable] + change (∑ i : Fin q, ∏ s, if x s = Raw.port {a, b} s i then (1 : K) else 0) = + (∏ s, v s (x s)) * if x a = x b then 1 else 0 + rw [Fintype.sum_eq_single (x a)] + · by_cases e : x a = x b + · rw [ite_eq_left e, mul_one] + apply Finset.prod_congr rfl + intro s _ + by_cases ha : s = a + · simp [Raw.port, v, ha] + by_cases hb : s = b + · simp [Raw.port, v, hb, e] + simp [Raw.port, v, ha, hb, Fin.ext_iff] + · rw [ite_eq_right e, mul_zero] + apply Finset.prod_eq_zero (Finset.mem_univ b) + simp [Raw.port, Ne.symm e] + · intro i hi + apply Finset.prod_eq_zero (Finset.mem_univ a) + simp [Raw.port, hi.symm] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- +# Splitting an array with two marked indices + +The first index passes through a kernel, with two catalyst indices +held at the endpoints. The second index is unchanged. Each inequality +below is a local linear restriction, also when some sites coincide. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +/-- The indexing data represented by `(S → X) → Fin q → Fin q → K`. -/ +abbrev Marked (K S X : Type) (q : ℕ) := (S → X) → Fin q → Fin q → K +/-- The indexing data represented by `Fin q → Fin q → Fin H → Fin H → K`. -/ +abbrev Kernel (K : Type) (q H : ℕ) := Fin q → Fin q → Fin H → Fin H → K + +variable {K S X : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] [Fintype X] +variable {q H P : ℕ} + +/-- The indexed operation `T (fun s => (y s).1) (y c).2.1 (y j).2.2`. -/ +def placePair (T : Marked K S X q) (c j : S) (y : S → Slot X q) : K := + T (fun s => (y s).1) (y c).2.1 (y j).2.2 + +/-- Evaluates `∑ k, U i k (y a).2.1 (y b).2.2 * T (fun s => (y s).1) k j` at the input `y i j`. -/ +def child (T : Marked K S X q) (U : Kernel K q H) (a b : S) : + Marked K S (Slot X H) q := + fun y i j => ∑ k, U i k (y a).2.1 (y b).2.2 * T (fun s => (y s).1) k j + +/-- Evaluates `∑ z, L i x z * D k z y` at the input `i k x y`. -/ +def productKernel (L : Fin q → Fin H → Fin P → K) (D : Fin q → Fin P → Fin H → K) : + Kernel K q H := fun i k x y => ∑ z, L i x z * D k z y + +variable (T : Marked K S X q) (a b c j : S) + +omit [DecidableEq S] in +theorem placePair_swap : + array (placePair (fun y x z => T y z x) c j) = array (placePair T j c) := by + let g (_ : S) (u : Slot X q) := (u.1, u.2.2, u.2.1) + exact le_antisymm (array_pullback _ _ g fun _ => rfl) (array_pullback _ _ g fun _ => rfl) + +omit [DecidableEq S] in +theorem child_flip (U : Kernel K q H) : + array (placePair (child T (fun i k x y => U i k y x) a b) c j) = + array (placePair (child T U b a) c j) := by + let g (_ : S) (u : Slot (Slot X H) q) := ((u.1.1, u.1.2.2, u.1.2.1), u.2) + exact le_antisymm (array_pullback _ _ g fun _ => rfl) (array_pullback _ _ g fun _ => rfl) + +theorem child_sum (U V : Kernel K q H) + (h : ∀ i k x y, U i k x y + V i k y x = if i = k ∧ x = y then 1 else 0) : + array (placePair T c j) * wire K a b H ≤ + array (placePair (child T U a b) c j) + array (placePair (child T V b a) c j) := by + rw [← child_flip T a b c j V, ← array_link a b H, ← array_mul] + refine le_trans ?_ (array_sum _ _) + let g (_ : S) (x : Slot X q × Slot Unit H) := ((x.1.1, x.2.2), x.1.2) + apply array_pullback _ _ g + intro x + simp only [placePair, child, g, ← Finset.sum_add_distrib, ← add_mul, h, link] + simp [ite_and, ite_mul, mul_ite] + +theorem child_here (hq : 0 < q) (U : Kernel K q H) : + array (placePair (child T U a b) a j) ≤ array (placePair T a j) * wire K a b H := by + let e (s : S) (i : Fin q × Fin H) := + (Raw.port {a, a} s i.1, Raw.port {a, b} s i.2) + have he : signals K e = wire K a b H := by + rw [show signals K e = _ from signals_mul (Raw.port {a, a}) (Raw.port {a, b}), + signals_wire, signals_wire, wire_self K a hq, one_mul] + rw [← he] + let v (s : S) (y : Slot (Slot X H) q) (i : Fin q × Fin H) := + (if s = a then U y.2.1 i.1 y.1.2.1 i.2 else 1) * + (if s = b then if i.2 = y.1.2.2 then 1 else 0 else 1) + apply use_signals _ _ e v (fun _ y i => (y.1.1, i.1, y.2.2)) + intro y + simp only [Fintype.sum_prod_type, v, Finset.prod_mul_distrib] + simp [e, Raw.port, placePair, child, mul_ite, ite_mul] + +theorem child_cross (hq : 0 < q) (L : Fin q → Fin H → Fin P → K) + (D : Fin q → Fin P → Fin H → K) : + array (placePair (child T (productKernel L D) a b) c j) ≤ + array (placePair T b j) * (wire K a c H * wire K c b P) := by + let e' (s : S) (i : Fin P × Fin H) := (Raw.port {c, b} s i.1, Raw.port {a, c} s i.2) + let e (s : S) (i : Fin q × Fin P × Fin H) := (Raw.port {b, b} s i.1, e' s i.2) + have he : signals K e = wire K a c H * wire K c b P := by + rw [show signals K e = _ from signals_mul (Raw.port {b, b}) e', + show signals K e' = _ from signals_mul (Raw.port {c, b}) (Raw.port {a, c}), + signals_wire, signals_wire, signals_wire, wire_self K b hq, one_mul, mul_comm] + rw [← he] + let v (s : S) (y : Slot (Slot X H) q) (i : Fin q × Fin P × Fin H) := + (if s = c then L y.2.1 i.2.2 i.2.1 else 1) * + (if s = b then D i.1 i.2.1 y.1.2.2 else 1) * + (if s = a then if i.2.2 = y.1.2.1 then 1 else 0 else 1) + apply use_signals _ _ e v (fun _ y i => (y.1.1, i.1, y.2.2)) + intro y + simp only [Fintype.sum_prod_type, v, Finset.prod_mul_distrib] + simp [e, e', Raw.port, placePair, child, productKernel, Finset.sum_mul, mul_ite, ite_mul] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- # The wire pseudometric of a spectral point -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S : Type} [Field K] [Fintype S] [DecidableEq S] + +/-- The quantity computed by `Real.log (f (wire K a b 2)) / Real.log 2`. -/ +def dist (f : Tensor K S →+* ℝ) (a b : S) : ℝ := + Real.log (f (wire K a b 2)) / Real.log 2 + +variable (f : Tensor K S →+* ℝ) + +theorem dist_self (a : S) : dist f a a = 0 := by + simp [dist, wire_self K a (n := 2) (by decide)] + +theorem dist_comm (a b : S) : dist f a b = dist f b a := by + unfold dist + rw [wire_comm K a b] + +variable (hf : Monotone f) +include hf + +private theorem price_bounds (a b : S) {n : ℕ} (hn : 0 < n) : + 1 ≤ f (wire K a b n) ∧ f (wire K a b n) ≤ (n : ℝ) := by + refine ⟨by simpa using hf (one_le_wire K a b hn), ?_⟩ + have h : wire K a b n ≤ (n : Tensor K S) := by + rw [← shared_all K n] + exact shared_subset K (Finset.subset_univ _) n + simpa using hf h + +theorem dist_nonneg (a b : S) : 0 ≤ dist f a b := + div_nonneg (Real.log_nonneg (price_bounds f hf a b (by decide)).1) + (Real.log_nonneg (by norm_num)) + +theorem dist_le_one (a b : S) : dist f a b ≤ 1 := by + have h := price_bounds f hf a b (n := 2) (by decide) + exact (div_le_one (Real.log_pos (by norm_num))).mpr + (Real.log_le_log (zero_lt_one.trans_le h.1) (by simpa using h.2)) + +theorem price_wire (a b : S) {n : ℕ} (hn : 0 < n) : + f (wire K a b n) = (n : ℝ) ^ dist f a b := by + obtain ⟨p, _, _, hp⟩ := TensorSpectrum.exists_power_of_monotone_multiplicative + (fun k => f (wire K a b k)) + (fun m n _ _ => (congrArg f (shared_mul K {a, b} m n)).trans (f.map_mul _ _)) + (fun _ _ _ h => hf (wire_mono K a b h)) (fun _ h => price_bounds f hf a b h) + have hp2 := hp 2 (by decide) + have hd : dist f a b = p := by + unfold dist + rw [hp2, Nat.cast_ofNat, Real.log_rpow (by norm_num : (0 : ℝ) < 2), + mul_div_cancel_right₀ _ (Real.log_pos (by norm_num : (1 : ℝ) < 2)).ne'] + rw [hd] + exact hp n hn + +theorem dist_triangle (a b c : S) : dist f a c ≤ dist f a b + dist f b c := by + have h := hf (wire_triangle K a b c 2) + rw [f.map_mul] at h + simp only [price_wire f hf _ _ (n := 2) (by decide), Nat.cast_ofNat, + ← Real.rpow_add (by norm_num : (0 : ℝ) < 2)] at h + exact (Real.rpow_le_rpow_left_iff (by norm_num : (1 : ℝ) < 2)).mp h + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +section +/- # Price inequalities for a pair of marked indices -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral + +/-- `V` consists of scaled prices as functions of the two placements. +The split uses an exterior-algebra index at the endpoints `a, b`. -/ +structure Splitting {S : Type} (d : S → S → ℝ) (V : (S → S → ℝ) → Prop) : Prop where + self : ∀ a, d a a = 0 + comm : ∀ a b, d a b = d b a + triangle : ∀ a b c, d a c ≤ d a b + d b c + nonneg : ∀ a b, 0 ≤ d a b + wire : ∀ n : ℕ, 0 < n → V (fun a b => (n : ℝ) ^ d a b) + swap : ∀ f, V f → V (fun a b => f b a) + split : ∀ f, V f → ∀ a b, 0 < d a b → ∀ r : ℝ, 0 < r → + ∃ u v, V u ∧ V v ∧ + (∀ c j, f c j ≤ u c j + v c j) ∧ + (∀ j, u a j ≤ f a j ∧ v b j ≤ f b j) ∧ + (∀ c j, d a c + d c b = d a b → + u c j ≤ f b j * r ^ d c b ∧ v c j ≤ f a j * r ^ (-d a c)) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral +end + +section +/- +# Convexity of distances between points on metric intervals + +In the matrix of four endpoint exponents, keep the diagonal fixed. +On each branch of a split, updating just one off-diagonal entry halves +the difference between the two diagonal sums. All costs of splitting +are additive in base-two logarithmic units. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Splitting + +private noncomputable def E (a : ℝ) := (2 : ℝ) ^ a + +private theorem shift {x a : ℝ} (hx : x ≤ E a) (b : ℝ) : x * E b ≤ E (a + b) := by + unfold E at * + rw [Real.rpow_add (by norm_num)] + exact mul_le_mul_of_nonneg_right hx (by positivity) + +private theorem combine {x y z a : ℝ} (h : x ≤ y + z) (hy : y ≤ E a) (hz : z ≤ E a) : + x ≤ E (a + 1) := by + unfold E at * + rw [Real.rpow_add_one (by norm_num), mul_two] + exact h.trans (add_le_add hy hz) + +variable {S : Type} {d : S → S → ℝ} {V : (S → S → ℝ) → Prop} +variable (H : Splitting d V) {a b c s t x : S} {f : S → S → ℝ} {p : ℝ} + +include H + +private theorem split_shift (hf : V f) (hab : 0 < d a b) (g : ℝ) : + ∃ u v, V u ∧ V v ∧ + (∀ c j, f c j ≤ u c j + v c j) ∧ + (∀ j, u a j ≤ f a j ∧ v b j ≤ f b j) ∧ + (∀ c j p, d a c = p * d a b → d c b = (1 - p) * d a b → + u c j ≤ f b j * E ((1 - p) * g) ∧ v c j ≤ f a j * E (-p * g)) := by + let r := E (g / d a b) + obtain ⟨u, v, hu, hv, hsum, hend, hcross⟩ := H.split f hf a b hab r (by unfold r E; positivity) + have pow_eq (z : ℝ) : r ^ (z * d a b) = E (z * g) := by + unfold r E + rw [← Real.rpow_mul (by norm_num)] + congr 1 + field_simp + refine ⟨u, v, hu, hv, hsum, hend, fun c j p hc hc' => ?_⟩ + have h := hcross c j (by rw [hc, hc']; ring) + simpa only [hc, hc', ← neg_mul, pow_eq] using h + +private theorem interpolate (hf : V f) (hab : 0 < d a b) + (hc : d a c = p * d a b) (hc' : d c b = (1 - p) * d a b) + {A B : ℝ} (ha : f a x ≤ E A) (hb : f b x ≤ E B) : + f c x ≤ E ((1 - p) * A + p * B + 1) := by + obtain ⟨u, v, _, _, hsum, _, hcross⟩ := H.split_shift hf hab (A - B) + obtain ⟨hu, hv⟩ := hcross c x p hc hc' + apply combine (hsum c x) + · rw [show (1 - p) * A + p * B = B + (1 - p) * (A - B) by ring] + exact hu.trans (shift hb _) + · rw [show (1 - p) * A + p * B = A + -p * (A - B) by ring] + exact hv.trans (shift ha _) + +private theorem halve (hab : 0 < d a b) (hst : 0 < d s t) + (hc : d a c = p * d a b) (hc' : d c b = (1 - p) * d a b) + (hx : d s x = p * d s t) (hx' : d x t = (1 - p) * d s t) + (k : ℕ) (hf : V f) {A B C D : ℝ} + (hA : f a s ≤ E A) (hB : f a t ≤ E B) (hC : f b s ≤ E C) (hD : f b t ≤ E D) : + f c x ≤ E ((1 - p) * A + p * D + p * (1 - p) * (B + C - A - D) / 2 ^ k + 2 + k) := by + induction k generalizing f B C with + | zero => + have ha := H.interpolate (H.swap f hf) hst hx hx' hA hB + have hb := H.interpolate (H.swap f hf) hst hx hx' hC hD + convert H.interpolate hf hab hc hc' ha hb using 2 + ring + | succ k ih => + let g := (A - C + B - D) / 2 + obtain ⟨u, v, hu, hv, hsum, hend, hcross⟩ := H.split_shift hf hab g + have left (j : S) : u a j ≤ f b j * E g ∧ v a j ≤ f a j := by + simpa [E] using hcross a j 0 (by simp [H.self]) (by simp) + have right (j : S) : u b j ≤ f b j ∧ v b j ≤ f a j * E (-g) := by + simpa [E] using hcross b j 1 (by simp) (by simp [H.self]) + rw [Nat.cast_succ, ← add_assoc] + apply combine (hsum c x) + · have h := ih hu ((hend s).1.trans hA) ((left t).1.trans (shift hD g)) + ((right s).1.trans hC) ((right t).1.trans hD) + convert h using 2 + unfold g + rw [pow_succ] + ring + · have h := ih hv ((left s).2.trans hA) ((left t).2.trans hB) + ((right s).2.trans (shift hA (-g))) ((hend t).2.trans hD) + convert h using 2 + unfold g + rw [pow_succ] + ring + +private theorem scaled (n : ℕ) : V (fun a b => E (n * d a b)) := by + simpa only [E, Real.rpow_natCast_mul (by norm_num : (0 : ℝ) ≤ 2), Nat.cast_pow, Nat.cast_ofNat] + using H.wire (2 ^ n) (by positivity) + +omit H in +private theorem slope {A B C : ℝ} (h : ∀ n : ℕ, E (n * A) ≤ E (n * B + C)) : A ≤ B := by + by_contra! hAB + obtain ⟨n, hn⟩ := exists_nat_gt (C / (A - B)) + have hn' := (div_lt_iff₀ (sub_pos.mpr hAB)).mp hn + have he := (Real.rpow_le_rpow_left_iff (by norm_num : (1 : ℝ) < 2)).mp (h n) + linarith + +private theorem same (h : d a b = 0) (z : S) : d a z = d b z := by + linarith [H.triangle a b z, H.triangle b a z, H.comm b a] + +private theorem one_segment + (hc : d a c = p * d a b) (hc' : d c b = (1 - p) * d a b) (y : S) : + d c y ≤ (1 - p) * d a y + p * d b y := by + rcases (H.nonneg a b).eq_or_lt with hab | hab + · rw [← hab, mul_zero] at hc hc' + rw [H.same hc y, ← H.same hc' y] + exact le_of_eq (by ring) + apply slope (C := 1) + intro n + convert H.interpolate (x := y) (H.scaled n) hab hc hc' le_rfl le_rfl using 2 + ring + +/-- Points at the same fraction on two intervals satisfy Busemann convexity. +Neither existence of intermediate points nor separation of sites is required. -/ +theorem busemann + (hc : d a c = p * d a b) (hc' : d c b = (1 - p) * d a b) + (hx : d s x = p * d s t) (hx' : d x t = (1 - p) * d s t) : + d c x ≤ (1 - p) * d a s + p * d b t := by + rcases (H.nonneg a b).eq_or_lt with hab | hab + · rw [← hab, mul_zero] at hc hc' + rw [H.same hc s, ← H.same hc' t, H.comm c x, H.comm c s, H.comm c t] + exact H.one_segment hx hx' c + rcases (H.nonneg s t).eq_or_lt with hst | hst + · rw [← hst, mul_zero] at hx hx' + rw [H.comm a s, H.same hx a, H.comm x a, H.comm b t, ← H.same hx' b, H.comm x b] + exact H.one_segment hc hc' x + let A := (1 - p) * d a s + p * d b t + let R := p * (1 - p) * (d a t + d b s - d a s - d b t) + have bound (k : ℕ) : d c x ≤ A + R / 2 ^ k := by + apply slope (C := 2 + k) + intro n + convert H.halve hab hst hc hc' hx hx' k (H.scaled n) le_rfl le_rfl le_rfl le_rfl using 2 + unfold A R + ring + change d c x ≤ A + by_contra! h + obtain ⟨k, hk⟩ := exists_nat_gt (R / (d c x - A)) + have hp : (k : ℝ) < 2 ^ k := by exact_mod_cast Nat.lt_two_pow_self (n := k) + have hz := (div_lt_iff₀ (sub_pos.mpr h)).mp (hk.trans hp) + have hu := (le_div_iff₀ (by positivity : (0 : ℝ) < 2 ^ k)).mp + (show d c x - A ≤ R / 2 ^ k by linarith [bound k]) + linarith + +theorem unique_midpoint + (hc : d a c = d a b / 2) (hc' : d c b = d a b / 2) + (hx : d a x = d a b / 2) (hx' : d x b = d a b / 2) : + d c x = 0 := by + have h := H.busemann (a := a) (b := b) (c := c) (s := a) (t := b) (x := x) + (p := 1 / 2) (by linarith) (by linarith) (by linarith) (by linarith) + rw [H.self, H.self] at h + linarith [H.nonneg c x] + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Splitting +end + +/- +# Busemann comparison for spectral distances + +The exterior creation and contraction identity splits the first +marked index. Dividing both children by the price of the catalyst +gives the three inequalities needed for the halving argument. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S X : Type} [Field K] [Fintype S] [DecidableEq S] [Nonempty S] [Fintype X] +variable (f : Tensor K S →+* ℝ) (hf : Monotone f) + +private def family (p : S → S → ℝ) : Prop := + ∃ (X : Type) (_ : Fintype X) (q : ℕ) (_ : 0 < q) (T : Marked K S X q) (w : ℝ), + 0 ≤ w ∧ p = fun a b => w * f (array (placePair T a b)) + +include hf + +omit [Nonempty S] in +private theorem price_at_most (a b : S) {n : ℕ} {v : ℝ} (hn : (n : ℝ) ≤ v) : + f (wire K a b n) ≤ v ^ dist f a b := by + rcases Nat.eq_zero_or_pos n with rfl | h + · have h := hf (shared_subset K (Finset.subset_univ {a, b}) 0) + rw [shared_all, Nat.cast_zero, map_zero] at h + exact h.trans (Real.rpow_nonneg (by simpa using hn) _) + · rw [price_wire f hf a b h] + exact Real.rpow_le_rpow (Nat.cast_nonneg _) hn (dist_nonneg f hf a b) + +private theorem price_cross {q H P : ℕ} (hq : 0 < q) (hH : 0 < H) {r : ℝ} (hr : 0 < r) + (hP : (P : ℝ) ≤ H * r) (T : Marked K S X q) + (L : Fin q → Fin H → Fin P → K) (D : Fin q → Fin P → Fin H → K) + (a b c j : S) (hc : dist f a c + dist f c b = dist f a b) : + f (array (placePair (child T (productKernel L D) a b) c j)) ≤ + (H : ℝ) ^ dist f a b * (f (array (placePair T b j)) * r ^ dist f c b) := by + have ht : 0 ≤ f (array (placePair T b j)) := by + simpa only [map_zero] using hf (zero_le (array (placePair T b j))) + have h := hf (child_cross T a b c j hq L D) + rw [f.map_mul, f.map_mul, price_wire f hf a c hH] at h + refine h.trans ?_ + calc + _ ≤ f (array (placePair T b j)) * ((H : ℝ) ^ dist f a c * ((H : ℝ) * r) ^ dist f c b) := + mul_le_mul_of_nonneg_left (mul_le_mul_of_nonneg_left + (price_at_most f hf c b hP) (by positivity)) ht + _ = _ := by + rw [Real.mul_rpow (Nat.cast_nonneg H) hr.le, ← hc, + Real.rpow_add (by exact_mod_cast hH : (0 : ℝ) < H)] + ring + +private theorem splits : Splitting (dist f) (family f) where + self := dist_self f + comm := dist_comm f + triangle := dist_triangle f hf + nonneg := dist_nonneg f hf + wire n hn := by + refine ⟨Unit, inferInstance, n, hn, fun _ i k => if i = k then 1 else 0, 1, + zero_le_one, ?_⟩ + funext a b + change _ = 1 * f (array (link K a b n)) + rw [one_mul, array_link, price_wire f hf a b hn] + swap _ h := by + obtain ⟨X, _, q, hq, T, w, hw, rfl⟩ := h + refine ⟨X, inferInstance, q, hq, fun y i j => T y j i, w, hw, ?_⟩ + funext a b + rw [placePair_swap] + split _ h a b _ r hr := by + obtain ⟨X, _, q, hq, T, w, hw, rfl⟩ := h + obtain ⟨H, P, M, hH, hP, hM, L, D, A, B, he⟩ := exterior K q r hr + let U := productKernel L D + let V := productKernel (fun i y z => B i z y) (fun k z x => A k x z) + have huv : ∀ i k x y, U i k x y + V i k y x = if i = k ∧ x = y then 1 else 0 := by + intro i k x y + simpa only [U, V, productKernel, mul_comm (B _ _ _)] using he i k x y + let u := child T U a b + let v := child T V b a + let t := (H : ℝ) ^ dist f a b + have ht : 0 < t := Real.rpow_pos_of_pos (by exact_mod_cast hH) _ + let W := w / t + have hW : 0 ≤ W := div_nonneg hw ht.le + have hWt : W * t = w := div_mul_cancel₀ _ ht.ne' + have scale {x y : ℝ} (h : x ≤ t * y) : W * x ≤ w * y := by + simpa only [← mul_assoc, hWt] using mul_le_mul_of_nonneg_left h hW + refine ⟨_, _, ⟨_, inferInstance, q, hq, u, W, hW, rfl⟩, + ⟨_, inferInstance, q, hq, v, W, hW, rfl⟩, ?_, ?_, ?_⟩ + · intro c j + have h := hf (child_sum T a b c j U V huv) + rw [f.map_mul, f.map_add, price_wire f hf a b hH] at h + dsimp only + rw [← hWt, ← mul_add, mul_assoc, mul_comm t] + exact mul_le_mul_of_nonneg_left h hW + · intro j + have here (a b : S) (k : Kernel K q H) := hf (child_here T a b j hq k) + constructor + · apply scale + simpa only [f.map_mul, price_wire f hf a b hH, mul_comm, t, u] using here a b U + · apply scale + simpa only [f.map_mul, price_wire f hf b a hH, dist_comm f b a, mul_comm, t, v] + using here b a V + · intro c j hc + constructor + · rw [mul_assoc] + exact scale (price_cross f hf hq hH hr hP T L D a b c j hc) + · have hc' : dist f b c + dist f c a = dist f b a := by + rw [dist_comm f b c, dist_comm f c a, add_comm, hc, dist_comm] + have hm : (M : ℝ) ≤ (H : ℝ) * r⁻¹ := (le_div_iff₀ hr).mpr hM + have h := price_cross f hf hq hH (inv_pos.mpr hr) hm T (fun i y z => B i z y) + (fun k z x => A k x z) b a c j hc' + rw [dist_comm f b a, dist_comm f c a, Real.inv_rpow hr.le, ← Real.rpow_neg hr.le] at h + rw [mul_assoc] + exact scale h + +theorem busemann {a b c s t x : S} {u : ℝ} + (hc : dist f a c = u * dist f a b) (hc' : dist f c b = (1 - u) * dist f a b) + (hx : dist f s x = u * dist f s t) (hx' : dist f x t = (1 - u) * dist f s t) : + dist f c x ≤ (1 - u) * dist f a s + u * dist f b t := + (splits f hf).busemann hc hc' hx hx' + +theorem unique_midpoint {a b c x : S} + (hc : dist f a c = dist f a b / 2) (hc' : dist f c b = dist f a b / 2) + (hx : dist f a x = dist f a b / 2) (hx' : dist f x b = dist f a b / 2) : + dist f c x = 0 := + (splits f hf).unique_midpoint hc hc' hx hx' + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Wire.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Wire.lean new file mode 100644 index 0000000000..ee839cc847 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectral/Wire.lean @@ -0,0 +1,114 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rank + +/-! +# Shared labels and wires + +A shared label gives each site in a set the same index. The other sites +have one active coordinate, fixed to zero. Wires are the two-site case. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral +variable (K : Type) [Field K] {S : Type} [Fintype S] [DecidableEq S] + +namespace Raw + +/-- Returns `i` when `s ∈ U` holds, and `⟨0, Nat.zero_lt_of_lt i.isLt⟩` otherwise. -/ +def port {n : ℕ} (U : Finset S) (s : S) (i : Fin n) : Fin n := + if s ∈ U then i else ⟨0, Nat.zero_lt_of_lt i.isLt⟩ + +/-- Uses `⟨fun _ => Fin n, Fin n, fun i s x => if x = port U s i then 1 else 0⟩` as the +representation. -/ +def shared (U : Finset S) (n : ℕ) : Raw K S := + ⟨fun _ => Fin n, Fin n, fun i s x => if x = port U s i then 1 else 0⟩ + +/-- The value specified by `shared K {a, b} n`. -/ +abbrev wire (a b : S) (n : ℕ) : Raw K S := shared K {a, b} n + +end Raw + +namespace Tensor + +/-- Computes the shared by the application `ofRaw (Raw.shared K U n)`. -/ +def shared (U : Finset S) (n : ℕ) : Tensor K S := ofRaw (Raw.shared K U n) + +/-- The value specified by `shared K {a, b} n`. -/ +abbrev wire (a b : S) (n : ℕ) : Tensor K S := shared K {a, b} n + +theorem shared_all (n : ℕ) : shared K (Finset.univ : Finset S) n = n := by + rw [← diag_fin] + apply ofRaw_eq + exact Raw.relabel (Equiv.refl _) (fun _ => Equiv.refl _) fun i s x => by + change Fin n at x i + change (if x = Raw.port Finset.univ s i then (1 : K) else 0) = if x = i then 1 else 0 + simp [Raw.port] + +theorem shared_one (U : Finset S) : shared K U 1 = 1 := by + apply ofRaw_eq + refine Raw.relabel (Equiv.ofUnique (Fin 1) Unit) + (fun _ => Equiv.ofUnique (Fin 1) Unit) fun i s x => ?_ + change Fin 1 at i x + change (if x = Raw.port U s i then (1 : K) else 0) = 1 + rw [ite_eq_left (Subsingleton.elim _ _)] + +theorem shared_mul (U : Finset S) (n m : ℕ) : + shared K U (n * m) = shared K U n * shared K U m := by + symm + apply ofRaw_eq + refine Raw.relabel finProdFinEquiv (fun _ => finProdFinEquiv) fun i s x => ?_ + change Fin n × Fin m at i x + have he : Raw.port U s (finProdFinEquiv i) = + finProdFinEquiv (Raw.port U s i.1, Raw.port U s i.2) := by + unfold Raw.port + split + · rfl + · exact Fin.ext (by simp [finProdFinEquiv]) + change (if x.1 = Raw.port U s i.1 then (1 : K) else 0) * + (if x.2 = Raw.port U s i.2 then 1 else 0) = + if finProdFinEquiv x = Raw.port U s (finProdFinEquiv i) then 1 else 0 + simp only [he, Equiv.apply_eq_iff_eq, Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul] + +theorem shared_mono (U : Finset S) (hU : U.Nonempty) {n m : ℕ} (h : n ≤ m) : + shared K U n ≤ shared K U m := by + obtain ⟨d, rfl⟩ := Nat.exists_eq_add_of_le h + obtain ⟨s, hs⟩ := hU + apply Raw.Restricts.pullback (fun _ (x : Fin n) => Fin.castAdd d x) + intro x + change S → Fin n at x + change (∑ i : Fin n, ∏ t, if x t = Raw.port U t i then (1 : K) else 0) = + ∑ i : Fin (n + d), ∏ t, if Fin.castAdd d (x t) = Raw.port U t i then 1 else 0 + rw [Fin.sum_univ_add, Finset.sum_eq_zero (s := (Finset.univ : Finset (Fin d))), add_zero] + · apply Finset.sum_congr rfl + intro i _ + apply Finset.prod_congr rfl + intro t _ + simp only [Raw.port, Fin.ext_iff] + split <;> rfl + · intro i _ + apply Finset.prod_eq_zero (Finset.mem_univ s) + simp only [Raw.port, hs, ↓reduceIte, Fin.ext_iff] + exact ite_eq_right (by simp; omega) + +theorem wire_comm (a b : S) (n : ℕ) : wire K a b n = wire K b a n := by + unfold wire + rw [Finset.pair_comm] + +theorem wire_mono (a b : S) : Monotone (wire K a b) := + fun _ _ h => shared_mono K _ (by simp) h + +theorem one_le_wire (a b : S) {n : ℕ} (hn : 0 < n) : 1 ≤ wire K a b n := by + rw [← shared_one K {a, b}] + exact wire_mono K a b hn + +end Tensor +end MatrixMultiplicationAllFields.MatrixExponent.Spectral diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Comparison.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Comparison.lean new file mode 100644 index 0000000000..8625b91c74 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Comparison.lean @@ -0,0 +1,271 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Topology.Instances.NNReal.Lemmas +public import Mathlib.Topology.Order.Compact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Additive.Catalyst +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Encoding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Character +public import Mathlib.RingTheory.Congruence.Defs + +/-! # Pointwise compactness of the spectrum -/ + +@[expose] public section + +section + +open scoped NNReal +open Set + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectrum + +/-- Semiring homomorphisms preserving the order, in the topology of pointwise convergence. -/ +def points (T : Type*) [CommSemiring T] [PartialOrder T] : Set (T → ℝ≥0) := + {v | ∃ g : T →+* ℝ≥0, Monotone g ∧ ⇑g = v} + +variable {S T : Type*} [CommSemiring T] [PartialOrder T] + +private theorem closed_points : IsClosed (points T) := by + have heq : points T = + {v | v 0 = 0 ∧ v 1 = 1 ∧ (∀ x y, v (x + y) = v x + v y) ∧ + (∀ x y, v (x * y) = v x * v y) ∧ Monotone v} := by + ext v + constructor + · rintro ⟨g, hg, rfl⟩ + exact ⟨map_zero g, map_one g, map_add g, map_mul g, hg⟩ + · rintro ⟨hz, ho, ha, hm, hv⟩ + exact ⟨{toFun := v, map_zero' := hz, map_one' := ho, map_add' := ha, map_mul' := hm}, + hv, rfl⟩ + rw [heq] + simp only [ofPred_and, ofPred_forall] + refine (isClosed_eq (continuous_apply 0) continuous_const).inter <| + (isClosed_eq (continuous_apply 1) continuous_const).inter <| + IsClosed.inter ?_ (IsClosed.inter ?_ isClosed_monotone) + · exact isClosed_iInter fun x => isClosed_iInter fun y => + isClosed_eq (continuous_apply _) ((continuous_apply x).add (continuous_apply y)) + · exact isClosed_iInter fun x => isClosed_iInter fun y => + isClosed_eq (continuous_apply _) ((continuous_apply x).mul (continuous_apply y)) + +theorem compact_points (hbound : ∀ a : T, ∃ n : ℕ, a ≤ (n : T)) : + IsCompact (points T) := by + choose R hR using hbound + have box : IsCompact {v : T → ℝ≥0 | ∀ a, v a ∈ Icc 0 (R a : ℝ≥0)} := + isCompact_pi_infinite fun _ => isCompact_Icc + refine box.of_isClosed_subset closed_points ?_ + rintro _ ⟨g, hg, rfl⟩ a + exact ⟨zero_le, by simpa only [map_natCast] using hg (hR a)⟩ + +/-- If no spectral point realizes the observations, finitely many already +separate them from every point by a positive squared distance. -/ +theorem separated (hbound : ∀ a : T, ∃ n : ℕ, a ≤ (n : T)) (i : S → T) (f : S → ℝ≥0) + (h : ¬ ∃ g : T →+* ℝ≥0, Monotone g ∧ ∀ a, g (i a) = f a) : + ∃ (U : Finset S) (ε : ℝ), 0 < ε ∧ ∀ g : T →+* ℝ≥0, Monotone g → + ε ≤ ∑ a ∈ U, ((g (i a) : ℝ) - f a) ^ 2 := by + classical + by_cases hn : (points T).Nonempty + swap + · exact ⟨∅, 1, zero_lt_one, fun g hg => (hn ⟨g, g, hg, rfl⟩).elim⟩ + have hc := compact_points hbound + let V (a : S) := {v : T → ℝ≥0 | v (i a) ≠ f a} + have hopen (a : S) : IsOpen (V a) := isOpen_ne_fun (continuous_apply _) continuous_const + have hcover : points T ⊆ ⋃ a, V a := by + rintro _ ⟨g, hg, rfl⟩ + apply mem_iUnion.mpr + exact not_forall.mp (fun heq => h ⟨g, hg, heq⟩) + obtain ⟨U, hU⟩ := hc.elim_finite_subcover V hopen hcover + let d (v : T → ℝ≥0) := ∑ a ∈ U, ((v (i a) : ℝ) - f a) ^ 2 + have hd : Continuous d := by unfold d; fun_prop + obtain ⟨v, hv, hmin⟩ := hc.exists_isMinOn hn hd.continuousOn + refine ⟨U, d v, ?_, fun g hg => hmin ⟨g, hg, rfl⟩⟩ + obtain ⟨a, ha, hne⟩ := mem_iUnion₂.mp (hU hv) + exact Finset.sum_pos' (fun _ _ => sq_nonneg _) ⟨a, ha, + sq_pos_of_ne_zero (sub_ne_zero.mpr (fun heq => hne (Subtype.ext heq)))⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectrum +end + +section +/- # Absorbing an additive catalyst without order cancellation -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectrum + +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +/-- Repeating the strict gain pays for an extra factor `D + 1`. +The resulting multiplicative catalyst dominates the unit and works +unchanged for every power. -/ +theorem absorb + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + (hmul : ∀ a b c : S, a ≤ b → c * a ≤ c * b) + (hzero : ∀ a : S, 0 ≤ a) + (hbound : ∀ a : S, ∃ n : ℕ, a ≤ (n : S)) + {x y D s : S} (hy : 1 ≤ y) (h : D + 1 + x * s ≤ D + y * s) : + ∃ C : ℕ, ∀ r : ℕ, x ^ r ≤ (C : S) * y ^ r := by + have iterate (n : ℕ) : D + (n : S) + x * ((n : S) * s) ≤ D + y * ((n : S) * s) := by + induction n with + | zero => simp + | succ n ih => + rw [Nat.cast_succ] + calc + _ = (D + (n : S) + x * ((n : S) * s)) + (1 + x * s) := by ring + _ ≤ (D + y * ((n : S) * s)) + (1 + x * s) := hadd _ _ _ ih + _ = (D + 1 + x * s) + y * ((n : S) * s) := by ring + _ ≤ (D + y * s) + y * ((n : S) * s) := hadd _ _ _ h + _ = _ := by ring + have le_sum (a b : S) : a ≤ b + a := by + simpa only [zero_add] using hadd _ _ a (hzero b) + obtain ⟨n, hn⟩ := hbound (x * (D + 1)) + let t := (n : S) * s + (D + 1) + have ht : 1 ≤ t := (le_sum 1 D).trans (le_sum _ _) + have hD : D ≤ y * (D + 1) := calc + D ≤ 1 + D := le_sum D 1 + _ = (D + 1) * 1 := by ring + _ ≤ (D + 1) * y := hmul _ _ _ hy + _ = y * (D + 1) := mul_comm _ _ + have hcat : x * t ≤ y * t := calc + x * t = x * (D + 1) + x * ((n : S) * s) := by unfold t; ring + _ ≤ D + (n : S) + x * ((n : S) * s) := hadd _ _ _ (hn.trans (le_sum _ _)) + _ ≤ D + y * ((n : S) * s) := iterate n + _ ≤ y * (D + 1) + y * ((n : S) * s) := hadd _ _ _ hD + _ = y * t := by unfold t; ring + obtain ⟨C, hC⟩ := hbound t + refine ⟨C, fun r => ?_⟩ + calc + x ^ r = x ^ r * 1 := (mul_one _).symm + _ ≤ x ^ r * t := hmul _ _ _ ht + _ ≤ y ^ r * t := TensorSpectrum.catalytic_power_iteration hmul hcat r + _ ≤ y ^ r * (C : S) := hmul _ _ _ hC + _ = (C : S) * y ^ r := mul_comm _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Spectrum +end + +section +/- +# Strict spectral comparison + +Adjoin the reversed comparison `y ≤ x` to the order, then identify +mutually comparable elements. Any character of the resulting semiring +would contradict the assumed strict inequality. The additive-state +obstruction gives a strict gain in the quotient. Lifting that comparison +provides the catalyst needed for all powers, with one constant overhead. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectrum + +open scoped NNReal + +variable {S : Type*} [CommSemiring S] [PartialOrder S] +variable (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) +variable (hmul : ∀ a b c : S, a ≤ b → c * a ≤ c * b) +variable {x y : S} + +private def extended (x y a b : S) : Prop := + ∃ t : S, a + x * t ≤ b + y * t + +private theorem extend {a b : S} (h : a ≤ b) : extended x y a b := + ⟨0, by simpa using h⟩ + +include hadd in +private theorem chain {a b c : S} (h : extended x y a b) (k : extended x y b c) : + extended x y a c := by + obtain ⟨s, hs⟩ := h + obtain ⟨t, ht⟩ := k + refine ⟨s + t, ?_⟩ + calc + a + x * (s + t) = (a + x * s) + x * t := by ring + _ ≤ (b + y * s) + x * t := hadd _ _ _ hs + _ = (b + x * t) + y * s := by ring + _ ≤ (c + y * t) + y * s := hadd _ _ _ ht + _ = c + y * (s + t) := by ring + +include hadd in +private theorem extAdd {a b : S} (c : S) (h : extended x y a b) : + extended x y (a + c) (b + c) := by + obtain ⟨s, hs⟩ := h + exact ⟨s, by simpa only [add_right_comm _ c] using hadd _ _ c hs⟩ + +include hmul in +private theorem extMul {a b : S} (c : S) (h : extended x y a b) : + extended x y (c * a) (c * b) := by + obtain ⟨s, hs⟩ := h + exact ⟨c * s, by simpa only [mul_add, mul_left_comm c] using hmul _ _ c hs⟩ + +private def con (x y : S) : RingCon S where + r a b := extended x y a b ∧ extended x y b a + iseqv := ⟨fun _ => ⟨extend le_rfl, extend le_rfl⟩, fun h => h.symm, + fun h k => ⟨chain hadd h.1 k.1, chain hadd k.2 h.2⟩⟩ + add' := by + have f {a b c d : S} (h : extended x y a b) (k : extended x y c d) : + extended x y (a + c) (b + d) := + chain hadd (extAdd hadd c h) (by simpa only [add_comm _ b] using extAdd hadd b k) + exact fun _ _ _ _ h k => ⟨f h.1 k.1, f h.2 k.2⟩ + mul' := by + have f {a b c d : S} (h : extended x y a b) (k : extended x y c d) : + extended x y (a * c) (b * d) := + chain hadd (extMul hmul a k) (by simpa only [mul_comm d] using extMul hmul d h) + exact fun _ _ _ _ h k => ⟨f h.1 k.1, f h.2 k.2⟩ + +@[instance_reducible] +private def quotientOrder (x y : S) : PartialOrder (con hadd hmul x y).Quotient where + le := Quotient.lift₂ (extended x y) fun _ _ _ _ h k => propext + ⟨fun t => chain hadd h.2 (chain hadd t k.1), + fun t => chain hadd h.1 (chain hadd t k.2)⟩ + le_refl a := Quotient.inductionOn a fun _ => extend le_rfl + le_trans a b c := Quotient.inductionOn₃ a b c fun _ _ _ => chain hadd + le_antisymm a b := Quotient.inductionOn₂ a b fun _ _ h k => Quotient.sound ⟨h, k⟩ + +include hadd hmul in +/-- A strict inequality at all spectral points allows a single overhead +independent of the power. -/ +theorem strictComparison + (hzero : ∀ a : S, 0 ≤ a) (hunit : ∀ a : S, a ≠ 0 → 1 ≤ a) + (hbound : ∀ a : S, ∃ n : ℕ, a ≤ (n : S)) (hy : y ≠ 0) + (h : ∀ f : S →+* ℝ≥0, Monotone f → f x < f y) : + ∃ C : ℕ, ∀ r : ℕ, x ^ r ≤ (C : S) * y ^ r := by + let q := con hadd hmul x y + let : PartialOrder q.Quotient := quotientOrder hadd hmul x y + have mono : Monotone q.mk' := fun _ _ h => extend h + have rev : q.mk' y ≤ q.mk' x := ⟨1, by simp [add_comm]⟩ + have add' : ∀ a b c : q.Quotient, a ≤ b → a + c ≤ b + c := + fun a b c => Quotient.inductionOn₃ a b c fun _ _ c => extAdd hadd c + have mul' : ∀ c : q.Quotient, Monotone (fun a => c * a) := + fun c a b => Quotient.inductionOn₃ a b c fun _ _ c => extMul hmul c + have zero' : ∀ a : q.Quotient, 0 ≤ a := + fun a => Quotient.inductionOn a fun a => mono (hzero a) + have unit' : ∀ a : q.Quotient, a ≠ 0 → 1 ≤ a := by + rintro a ha + obtain ⟨a, rfl⟩ := q.mk'_surjective a + exact mono (hunit a (fun e => ha (by simp [e]))) + have bound' : ∀ a : q.Quotient, ∃ n : ℕ, a ≤ (n : q.Quotient) := by + intro a + obtain ⟨a, rfl⟩ := q.mk'_surjective a + obtain ⟨n, hn⟩ := hbound a + exact ⟨n, by simpa using mono hn⟩ + choose R hR using bound' + have hempty : TensorSpectrum.stateSet (0 : q.Quotient) 0 = ∅ := by + apply Set.not_nonempty_iff_eq_empty.mp + intro hne + obtain ⟨f, hf, _⟩ := TensorSpectrum.exists_nnreal_character_of_nonempty_stateSet + 0 0 R zero' unit' hR mul' hne + exact (h (f.comp q.mk') (hf.comp mono)).not_ge (hf rev) + obtain ⟨m, hm, D, _, hg⟩ := TensorSpectrum.catalyst_of_no_state + 0 0 R add' zero' hR hempty + simp only [Nat.cast_zero, zero_mul, add_zero] at hg + obtain ⟨d, rfl⟩ := q.mk'_surjective D + have h1 : (1 : S) ≤ (m : S) := by + obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hm.ne' + simpa [Nat.cast_succ] using hadd _ _ 1 (hzero (n : S)) + have step : q.mk' (d + 1) ≤ q.mk' d := by + refine le_trans ?_ hg + simpa [add_comm] using mono (hadd _ _ d h1) + obtain ⟨s, hs⟩ := step + exact absorb hadd hmul hzero hbound (hunit y hy) hs + +end MatrixMultiplicationAllFields.MatrixExponent.Spectrum +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Constrained.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Constrained.lean new file mode 100644 index 0000000000..0ba81a966e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Constrained.lean @@ -0,0 +1,129 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Character +public import Mathlib.Algebra.Order.Archimedean.Real.Basic + +/-! +# Multiplicative states with linear inequalities + +The inequalities hold after multiplication by every element. This +ensures invariance under normalized multiplication. In a valued +restriction semiring, nonzero elements can have price below one; +an additive multiple suffices for the fixed-point argument. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectrum + +open MatrixMultiplicationAllFields.TensorSpectrum Set + +variable {S I : Type*} [CommSemiring S] [PartialOrder S] + +theorem constrained_character + (hmul : ∀ a b c : S, a ≤ b → c * a ≤ c * b) (hzero : ∀ a : S, 0 ≤ a) + (A B : I → S) (c : I → ℝ) (fixed : Set I) + (lower : ∀ x ≠ 0, ∃ i ∈ fixed, A i = 1 ∧ B i = x) + (upper : ∀ x, ∃ i ∈ fixed, A i = x ∧ B i = 1) + (hs : ∀ J : Finset I, ∃ f : S →+ ℝ, f 1 = 1 ∧ Monotone f ∧ + ∀ i, i ∈ fixed ∨ i ∈ J → ∀ U, f (A i * U) ≤ c i * f (B i * U)) : + ∃ g : S →+* ℝ, Monotone g ∧ ∀ i, g (A i) ≤ c i * g (B i) := by + choose R hR eR h1 using upper + let C (i : I) : Set (S → ℝ) := {f | ∀ U, f (A i * U) ≤ c i * f (B i * U)} + let K := stateSet (0 : S) 0 ∩ ⋂ i, C i + let V := stateSet (0 : S) 0 ∩ ⋂ i ∈ fixed, C i + have incl : K ⊆ V := fun _ hf => ⟨hf.1, mem_iInter₂.mpr fun i _ => mem_iInter.mp hf.2 i⟩ + have closed (i : I) : IsClosed (C i) := by + unfold C + rw [ofPred_forall] + exact isClosed_iInter fun U => + isClosed_le (continuous_apply _) (continuous_const.mul (continuous_apply _)) + have bound (f : S → ℝ) (hf : f ∈ V) (x : S) : 0 ≤ f x ∧ f x ≤ c (R x) := by + refine ⟨by rw [← hf.1.1]; exact hf.1.2.2.2.1 (hzero x), ?_⟩ + simpa only [eR, h1, mul_one, hf.1.2.1] using mem_iInter₂.mp hf.2 (R x) (hR x) 1 + have hc : IsCompact V := by + have hb : IsCompact {f : S → ℝ | ∀ x, f x ∈ Icc 0 (c (R x))} := + isCompact_pi_infinite fun _ => isCompact_Icc + exact hb.of_isClosed_subset + ((stateSet_isClosed 0 0).inter (isClosed_iInter fun i => isClosed_iInter fun _ => closed i)) + bound + have compact : IsCompact K := + hc.of_isClosed_subset ((stateSet_isClosed 0 0).inter (isClosed_iInter closed)) incl + have ne : K.Nonempty := by + have hh : (V ∩ ⋂ i, C i).Nonempty := by + apply hc.inter_iInter_nonempty C closed + intro J + obtain ⟨f, h1, hf, hj⟩ := hs J + exact ⟨f, ⟨⟨f.map_zero, h1, f.map_add, hf, by simp⟩, + mem_iInter₂.mpr fun i hi => hj i (.inl hi)⟩, mem_iInter₂.mpr fun i hi => hj i (.inr hi)⟩ + exact hh.mono fun f (h : f ∈ V ∩ ⋂ i, C i) => ⟨h.1.1, h.2⟩ + have convex : Convex ℝ K := by + apply (stateSet_convex (0 : S) 0).inter + apply convex_iInter + intro i f hf g hg a b ha hb _ U + change a * f (A i * U) + b * g (A i * U) ≤ c i * (a * f (B i * U) + b * g (B i * U)) + calc + _ ≤ a * (c i * f (B i * U)) + b * (c i * g (B i * U)) := + add_le_add (mul_le_mul_of_nonneg_left (hf U) ha) (mul_le_mul_of_nonneg_left (hg U) hb) + _ = _ := by ring + have nat (f : S → ℝ) (hf : f ∈ K) (n : ℕ) (z : S) : f (n * z) = n * f z := by + let F : S →+ ℝ := { toFun := f, map_zero' := hf.1.1, map_add' := hf.1.2.2.1 } + change F _ = _ * F _ + rw [← nsmul_eq_mul, map_nsmul, nsmul_eq_mul] + have lo (z : S) (hz : z ≠ 0) : ∃ n : ℕ, 0 < n ∧ ∀ f ∈ K, 1 ≤ f (n * z) := by + obtain ⟨i, _, ha, hb⟩ := lower z hz + obtain ⟨n, hn⟩ := exists_nat_gt (max 0 (c i)) + refine ⟨n, Nat.cast_pos.mp ((le_max_left _ _).trans_lt hn), fun f hf => ?_⟩ + rw [nat f hf] + have hl := mem_iInter.mp hf.2 i 1 + simp only [mul_one, ha, hb, hf.1.2.1] at hl + exact hl.trans (mul_le_mul_of_nonneg_right ((le_max_right _ _).trans hn.le) (bound f (incl hf) + z).1) + have pos (f : S → ℝ) (hf : f ∈ K) (z : S) (hz : z ≠ 0) : 0 < f z := by + obtain ⟨n, _, hn⟩ := lo z hz + have h := zero_lt_one.trans_le (hn f hf) + rw [nat f hf] at h + exact pos_of_mul_pos_right h (Nat.cast_nonneg _) + have invariant (z : S) (hz : z ≠ 0) : MapsTo (projective z) K K := by + intro f hf + have hp := pos f hf z hz + refine ⟨⟨projective_zero z f hf.1.1, projective_one z f hp.ne', ?_, ?_, ?_⟩, ?_⟩ + · intro x y + unfold projective + rw [mul_add, hf.1.2.2.1, add_div] + · exact fun x y h => div_le_div_of_nonneg_right (hf.1.2.2.2.1 (hmul _ _ _ h)) hp.le + · simp [projective, hf.1.1] + · refine mem_iInter.mpr fun i U => ?_ + change f (z * (A i * U)) / f z ≤ c i * (f (z * (B i * U)) / f z) + rw [mul_left_comm z, mul_left_comm z, ← mul_div_assoc] + exact div_le_div_of_nonneg_right (mem_iInter.mp hf.2 i (z * U)) hp.le + have point : ∃ f ∈ K, ∀ z x, f (z * x) = f z * f x := by + apply multiplicative_of_finite_common_points K compact fun _ hf => hf.1.1 + apply finite_common_points_of_slice_fixedPoints K ne compact convex (fun _ hf => hf.1.2.1) + (fun f hf z hz => (pos f hf z hz).ne') invariant + intro L hL hn hc hv hi z hz + obtain ⟨n, hn', hl⟩ := lo z hz + have eq (f : S → ℝ) (hf : f ∈ L) : projective ((n : S) * z) f = projective z f := by + funext x + unfold projective + rw [mul_assoc, nat f (hL hf), nat f (hL hf)] + exact mul_div_mul_left _ _ (Nat.cast_ne_zero.mpr hn'.ne') + obtain ⟨f, hf, he⟩ := projective_fixedPoint_of_compact_convex L ((n : S) * z) (c ∘ R) + hn hc hv (fun f hf => (hL hf).1.2.1) (fun f hf => bound f (incl (hL hf))) + (fun f hf => hl f (hL hf)) (fun f hf => by rw [eq f hf]; exact hi z hz hf) + exact ⟨f, hf, (eq f hf).symm.trans he⟩ + obtain ⟨f, hf, hfmul⟩ := point + let g : S →+* ℝ := + { toFun := f, map_zero' := hf.1.1, map_one' := hf.1.2.1, + map_add' := hf.1.2.2.1, map_mul' := hfmul } + refine ⟨g, hf.1.2.2.2.1, fun i => ?_⟩ + change f (A i) ≤ c i * f (B i) + simpa only [mul_one] using mem_iInter.mp hf.2 i 1 + +end MatrixMultiplicationAllFields.MatrixExponent.Spectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Extension.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Extension.lean new file mode 100644 index 0000000000..d40041b7eb --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Extension.lean @@ -0,0 +1,106 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Comparison + +/-! +# Simultaneous extension of spectral points + +Strict comparison transfers inequalities from the spectrum of the target. +A point outside its image can be separated by one such inequality: round +its finitely many coordinates, then clear denominators in the squared +distance and move negative terms to the other side. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectrum + +open scoped NNReal + +theorem le_of_powers_le {x y : ℝ≥0} {C : ℕ} + (h : ∀ r : ℕ, x ^ r ≤ (C : ℝ≥0) * y ^ r) : x ≤ y := by + by_cases hy : y = 0 + · simpa [hy] using h 1 + by_contra! hxy + have hy' : 0 < y := pos_iff_ne_zero.mpr hy + obtain ⟨r, hr⟩ := pow_unbounded_of_one_lt (C : ℝ≥0) ((one_lt_div hy').mpr hxy) + rw [div_pow, lt_div_iff₀ (pow_pos hy' _)] at hr + exact hr.not_ge (h r) + +variable {S T : Type*} [CommSemiring S] [CommSemiring T] [PartialOrder T] + +/-- A single ordered pair of semiring elements distinguishes a finite +strictly positive squared-distance gap. -/ +private theorem separate_by_elements (f : S →+* ℝ≥0) (U : Finset S) {ε : ℝ} (he : 0 < ε) : + ∃ x y : S, f y < f x ∧ ∀ g : S →+* ℝ≥0, + ε ≤ ∑ a ∈ U, ((g a : ℝ) - f a) ^ 2 → g x < g y := by + obtain ⟨n, hn⟩ := exists_nat_gt (max 1 ((4 * (U.card : ℝ) + 2) / ε)) + have hn1 := (le_max_left _ _).trans_lt hn + have hn2 := (div_lt_iff₀ he).mp ((le_max_right _ _).trans_lt hn) + have hn3 : 4 * (U.card : ℝ) + 2 < (n : ℝ) ^ 2 * ε := + hn2.trans_le (mul_le_mul_of_nonneg_right (by nlinarith) he.le) + let p (a : S) := ⌊(n : ℝ) * (f a : ℝ)⌋₊ + let E (g : S →+* ℝ≥0) := ∑ a ∈ U, ((n : ℝ) * (g a : ℝ) - p a) ^ 2 + have small : E f ≤ U.card := by + calc + E f ≤ ∑ _ ∈ U, (1 : ℝ) := by + apply Finset.sum_le_sum + intro a _ + have hl : (p a : ℝ) ≤ (n : ℝ) * f a := Nat.floor_le (by positivity) + have hr : (n : ℝ) * f a < (p a : ℝ) + 1 := Nat.lt_floor_add_one _ + nlinarith + _ = U.card := by simp + let x := (U.card : S) + 1 + ∑ a ∈ U, 2 * (p a : S) * (n : S) * a + let y := ∑ a ∈ U, (((n : S) * a) ^ 2 + (p a : S) ^ 2) + have price (g : S →+* ℝ≥0) : (g y : ℝ) - g x = E g - (U.card + 1) := by + simp only [x, y, E, map_add, map_sum, map_one, map_mul, map_natCast, map_pow, map_ofNat, + NNReal.coe_add, NNReal.coe_sum, NNReal.coe_one, NNReal.coe_mul, NNReal.coe_natCast, + NNReal.coe_pow, NNReal.coe_ofNat] + rw [sub_add_eq_sub_sub_swap, ← Finset.sum_sub_distrib] + congr 1 + exact Finset.sum_congr rfl fun a _ => by ring + refine ⟨x, y, NNReal.coe_lt_coe.mp (by linarith [price f]), ?_⟩ + intro g hg + have large : (n : ℝ) ^ 2 * ε ≤ 2 * E g + 2 * E f := by + refine (mul_le_mul_of_nonneg_left hg (sq_nonneg _)).trans ?_ + simp only [E, Finset.mul_sum, ← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro a _ + nlinarith only [sq_nonneg ((n : ℝ) * ((g a : ℝ) + f a) - 2 * (p a : ℝ))] + exact NNReal.coe_lt_coe.mp (by linarith [price g]) + +/-- It suffices that the given character respects comparisons made in the +target semiring. The extension agrees at every element simultaneously. -/ +theorem extension + (hadd : ∀ a b c : T, a ≤ b → a + c ≤ b + c) + (hmul : ∀ a b c : T, a ≤ b → c * a ≤ c * b) + (hzero : ∀ a : T, 0 ≤ a) (hunit : ∀ a : T, a ≠ 0 → 1 ≤ a) + (hbound : ∀ a : T, ∃ n : ℕ, a ≤ (n : T)) + (i : S →+* T) (f : S →+* ℝ≥0) (h : ∀ a b, i a ≤ i b → f a ≤ f b) : + ∃ g : T →+* ℝ≥0, Monotone g ∧ ∀ a, g (i a) = f a := by + by_contra hn + obtain ⟨U, ε, he, hgap⟩ := separated hbound i f hn + obtain ⟨x, y, hf, hg⟩ := separate_by_elements f U he + have hy : i (y + 1) ≠ 0 := by + intro e + have := h (y + 1) 0 (by simp [e]) + simp at this + have hl (g : T →+* ℝ≥0) (hm : Monotone g) : g (i (x + 1)) < g (i (y + 1)) := by + have := hg (g.comp i) (hgap g hm) + simpa only [map_add, map_one, add_lt_add_iff_right, RingHom.comp_apply] using this + obtain ⟨C, hC⟩ := strictComparison hadd hmul hzero hunit hbound hy hl + have hxy : f (x + 1) ≤ f (y + 1) := by + apply le_of_powers_le (C := C) + intro r + simpa only [map_pow, map_mul, map_natCast] using + h ((x + 1) ^ r) ((C : S) * (y + 1) ^ r) (by + simpa only [map_pow, map_mul, map_natCast] using hC r) + exact hf.not_ge (by simpa using hxy) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Gadget.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Gadget.lean new file mode 100644 index 0000000000..70a9ee5aa2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Spectrum/Gadget.lean @@ -0,0 +1,189 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Comparison + +/-! # Uniform exponent savings on the spectrum -/ + +@[expose] public section + +section + +open scoped NNReal +open Set + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectrum + +private theorem amplify {x y z : ℝ≥0} (h : x < y) (hz : 0 < z) : + ∃ m : ℕ, x ^ m * z < y ^ m := by + have hy : 0 < y := zero_le.trans_lt h + obtain ⟨m, hm⟩ := exists_pow_lt_of_lt_one (one_div_pos.mpr hz) ((div_lt_one hy).mpr h) + rw [div_pow, div_lt_div_iff₀ (pow_pos hy m) hz, one_mul] at hm + exact ⟨m, hm⟩ + +private theorem extend_gain {x y z : ℝ≥0} {m n : ℕ} (h : x < y) + (hm : x ^ m * z < y ^ m) (hmn : m ≤ n) : x ^ n * z < y ^ n := by + obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le hmn + rw [pow_add, pow_add, mul_right_comm] + exact (mul_le_mul_of_nonneg_left (pow_le_pow_left₀ zero_le h.le k) zero_le).trans_lt + (mul_lt_mul_of_pos_right hm (pow_pos (zero_le.trans_lt h) k)) + +/-- The supplier may depend on the point. A finite subcover lets us pay +for any prescribed number of discarded copies with a common exponent. -/ +theorem uniform_margin {S I : Type*} [CommSemiring S] [PartialOrder S] + (hbound : ∀ a : S, ∃ n : ℕ, a ≤ (n : S)) (D : S) (W : I → S) (d : ℕ) (hd : 0 < d) + (hW : ∀ i, (1 : S) ≤ W i) + (hgap : ∀ g : S →+* ℝ≥0, Monotone g → ∃ i, g D < g (W i) ^ d) (L : ℕ) : + ∃ n p : ℕ, 0 < n ∧ p + L < d * n ∧ ∀ g : S →+* ℝ≥0, Monotone g → + ∃ i, g D ^ n < g (W i) ^ p := by + classical + let V (j : I × ℕ) := {v : S → ℝ≥0 | v D < v (W j.1) ^ d ∧ + v D ^ j.2 * v (W j.1) ^ (L + 1) < (v (W j.1) ^ d) ^ j.2} + have hopen (j : I × ℕ) : IsOpen (V j) := by + unfold V + rw [ofPred_and] + exact (isOpen_lt (by fun_prop) (by fun_prop)).inter (isOpen_lt (by fun_prop) (by fun_prop)) + have hcover : points S ⊆ ⋃ j, V j := by + rintro _ ⟨g, hg, rfl⟩ + obtain ⟨i, hi⟩ := hgap g hg + have hw : 1 ≤ g (W i) := by simpa only [map_one] using hg (hW i) + obtain ⟨m, hm⟩ := amplify hi (pow_pos (zero_lt_one.trans_le hw) (L + 1)) + exact mem_iUnion.mpr ⟨(i, m), hi, hm⟩ + obtain ⟨U, hU⟩ := (compact_points hbound).elim_finite_subcover V hopen hcover + let n := U.sup Prod.snd + L + 1 + have hn : L + 1 ≤ n := by unfold n; omega + have hdn := hn.trans (Nat.le_mul_of_pos_left n hd) + refine ⟨n, d * n - (L + 1), by omega, by omega, ?_⟩ + intro g hg + obtain ⟨⟨i, m⟩, hj, hi, hm⟩ := mem_iUnion₂.mp (hU ⟨g, hg, rfl⟩) + have hmn : m ≤ U.sup Prod.snd := Finset.le_sup (f := Prod.snd) hj + have h := extend_gain hi hm (show m ≤ n by unfold n; omega) + refine ⟨i, lt_of_mul_lt_mul_right (a := g (W i) ^ (L + 1)) ?_ zero_le⟩ + rw [pow_sub_mul_pow _ hdn, pow_mul] + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Spectrum +end + +section +/- +# Tensor powers with a finite menu of supply profiles + +Round the multiplicity of each supply upwards after dividing by the +power. The product of all supplies dominates two, so a fixed extra +allocation per supply can pay for all selector words. +-/ + +open scoped NNReal +open Finset + +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectrum + +variable {S I : Type*} [CommSemiring S] [PartialOrder S] [Fintype I] + +private theorem profile_bound [AddLeftMono S] [MulLeftMono S] + (hzero : ∀ a : S, 0 ≤ a) (W : I → S) (hW : ∀ i, (1 : S) ≤ W i) + (hconn : (2 : S) ≤ ∏ i, W i) (p : ℕ) : + ∃ H : Finset (I → ℕ), (∀ h ∈ H, ∑ i, h i ≤ p + Fintype.card I * (Fintype.card I + 1)) ∧ + ∀ z : ℕ, 0 < z → (∑ i, W i ^ p) ^ z ≤ ∑ h ∈ H, ∏ i, W i ^ (h i * z) := by + classical + let k := Fintype.card I + let B := p + k * (k + 1) + let H := (Fintype.piFinset (fun _ : I => range (B + 1))).filter + (fun h => (∀ i, k ≤ h i) ∧ ∑ i, h i ≤ B) + refine ⟨H, fun _ hh => (mem_filter.mp hh).2.2, fun z hz => ?_⟩ + let A := ∑ h ∈ H, ∏ i, W i ^ ((h i - k) * z) + have term (f : Fin z → I) : (∏ j, W (f j) ^ p) ≤ A := by + let count (i : I) := (univ.filter (fun j => f j = i)).card + have hc : ∑ i, count i = z := by + simpa only [card_univ, Fintype.card_fin] using + (card_eq_sum_card_fiberwise (s := univ) (t := univ) (f := f) (by simp)).symm + let h (i : I) := p * count i / z + (k + 1) + have hform (i : I) : h i = k + (p * count i / z + 1) := + Nat.add_left_comm _ _ _ + have hs : ∑ i, h i ≤ B := by + have hh : ∑ i, p * count i / z ≤ p := by + apply Nat.le_of_mul_le_mul_right _ hz + rw [sum_mul] + calc + _ ≤ ∑ i, p * count i := sum_le_sum fun _ _ => Nat.div_mul_le_self _ _ + _ = _ := by rw [← mul_sum, hc] + simpa only [h, sum_add_distrib, sum_const, card_univ, nsmul_eq_mul, Nat.cast_id, ← mul_add] + using Nat.add_le_add_right hh (k * (k + 1)) + have hh : h ∈ H := by + have hk (i : I) : k ≤ h i := by rw [hform]; exact Nat.le_add_right _ _ + refine mem_filter.mpr ⟨Fintype.mem_piFinset.mpr ?_, hk, hs⟩ + intro i + exact mem_range.mpr (Nat.lt_succ_of_le ((single_le_sum (fun _ _ => Nat.zero_le _) + (mem_univ i)).trans hs)) + calc + _ = ∏ i, W i ^ (p * count i) := by + rw [← prod_fiberwise' univ f (fun i => W i ^ p)] + simp only [prod_const, pow_mul, count] + _ ≤ ∏ i, W i ^ ((h i - k) * z) := by + apply prod_le_prod + intro i _ + apply pow_le_pow_right' (hW i) + rw [hform, Nat.add_sub_cancel_left, mul_comm _ z] + exact (Nat.lt_mul_div_succ _ hz).le + _ ≤ A := single_le_sum (f := fun h => ∏ i, W i ^ ((h i - k) * z)) + (fun _ _ => hzero _) hh + have hk : (k : S) ≤ (∏ i, W i) ^ k := by + obtain ⟨t, ht⟩ := Nat.exists_eq_add_of_le (Nat.lt_two_pow_self (n := k)).le + calc + (k : S) ≤ (k : S) + (t : S) := by simpa using add_le_add_right (hzero (t : S)) (k : S) + _ = (2 : S) ^ k := by rw [← Nat.cast_add, ← ht, Nat.cast_pow, Nat.cast_ofNat] + _ ≤ _ := pow_le_pow_left' hconn k + calc + _ = ∑ f : Fin z → I, ∏ j, W (f j) ^ p := Fintype.sum_pow _ _ + _ ≤ ∑ _f : Fin z → I, A := sum_le_sum fun f _ => term f + _ = (k : S) ^ z * A := by simp [k, nsmul_eq_mul] + _ ≤ ((∏ i, W i) ^ k) ^ z * A := mul_le_mul_left (pow_le_pow_left' hk z) A + _ = _ := by + unfold A + rw [← pow_mul, ← prod_pow, mul_sum] + apply sum_congr rfl + intro h hh + rw [← prod_mul_distrib] + apply prod_congr rfl + intro i _ + rw [← pow_add, ← Nat.add_mul, Nat.add_sub_of_le ((mem_filter.mp hh).2.1 i)] + +/-- A strict spectral advantage yields exact comparisons with a common +budget and a finite list of profiles independent of the tensor power. -/ +theorem powered_gadget [Nontrivial S] [Nonempty I] + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + (hmul : ∀ a b c : S, a ≤ b → c * a ≤ c * b) + (hzero : ∀ a : S, 0 ≤ a) (hunit : ∀ a : S, a ≠ 0 → 1 ≤ a) + (hbound : ∀ a : S, ∃ n : ℕ, a ≤ (n : S)) (D : S) (W : I → S) (d : ℕ) (hd : 0 < d) + (hW : ∀ i, (1 : S) ≤ W i) + (hgap : ∀ g : S →+* ℝ≥0, Monotone g → ∃ i, g D < g (W i) ^ d) + (hconn : (2 : S) ≤ ∏ i, W i) : + ∃ (b C : ℕ) (H : Finset (I → ℕ)), 0 < b ∧ (∀ h ∈ H, ∑ i, h i < d * b) ∧ + ∀ z : ℕ, 0 < z → D ^ (b * z) ≤ (C : S) * ∑ h ∈ H, ∏ i, W i ^ (h i * z) := by + let : AddLeftMono S := ⟨fun c a b h => by simpa only [add_comm] using hadd a b c h⟩ + let : MulLeftMono S := ⟨fun c a b h => hmul a b c h⟩ + obtain ⟨b, p, hb, hp, hprice⟩ := + uniform_margin hbound D W d hd hW hgap (Fintype.card I * (Fintype.card I + 1)) + have hy : (∑ i, W i ^ p) ≠ 0 := by + obtain ⟨i⟩ := ‹Nonempty I› + have h : (1 : S) ≤ W i ^ p := by simpa using pow_le_pow_left' (hW i) p + exact ne_of_gt ((lt_of_le_of_ne (hzero 1) zero_ne_one).trans_le + (h.trans (single_le_sum (f := fun i => W i ^ p) (fun _ _ => hzero _) (mem_univ i)))) + obtain ⟨C, hC⟩ := strictComparison hadd hmul (x := D ^ b) hzero hunit hbound hy (by + intro g hg + obtain ⟨i, hi⟩ := hprice g hg + simp only [map_pow, map_sum] + exact hi.trans_le (single_le_sum (f := fun i => g (W i) ^ p) (fun _ _ => zero_le) (mem_univ i))) + obtain ⟨H, hs, he⟩ := profile_bound hzero W hW hconn p + refine ⟨b, C, H, hb, fun h hh => (hs h hh).trans_lt hp, fun z hz => ?_⟩ + rw [pow_mul] + exact (hC z).trans (hmul _ _ _ (he z hz)) + +end MatrixMultiplicationAllFields.MatrixExponent.Spectrum +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Block.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Block.lean new file mode 100644 index 0000000000..ed7f662469 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Block.lean @@ -0,0 +1,930 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Algebra.Order.BigOperators.Group.List +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.Linarith +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Interpolation +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure +public import Mathlib.FieldTheory.IntermediateField.Adjoin.Basic +public import Mathlib.Analysis.SpecialFunctions.Exp +public import Mathlib.Algebra.Algebra.Basic + +/-! +# Weighted slot selection + +A test can pair only with its target or a strictly heavier slot. If the +available weight cannot exceed the target weight, every test in a +nonzero Wick monomial must occupy its target. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {α β R : Type*} [CommRing R] + +theorem contract_skip (f : α → R) (P : List α → R) (s : β → α) (b : List β) + (l : List α) (h : ∀ p y q, b = p ++ y :: q → f (s y) * P ((p ++ q).map s ++ l) = 0) : + contract f P (b.map s ++ l) = + (-1 : R) ^ b.length * contract f (fun xs => P (b.map s ++ xs)) l := by + induction b generalizing P with + | nil => simp + | cons y b ih => + have hz := h [] y b rfl + simp only [List.nil_append] at hz + have e := ih (fun xs => P (s y :: xs)) + (fun p z q he => h (y :: p) z q (congrArg (y :: ·) he)) + simp only [List.map_cons, List.cons_append, contract_cons, hz, zero_sub, e, + List.length_cons, pow_succ, mul_neg_one, neg_mul] + +variable [DecidableEq β] (k : α → α → R) (t s : β → α) (w : β → ℝ) (valid : β → Prop) + (hw : ∀ x, valid x → 0 < w x) (ht : ∀ x y, k (t x) (t y) = 0) + (hp : ∀ x y, valid x → valid y → w y ≤ w x → k (t x) (s y) = if x = y then 1 else 0) + +omit [DecidableEq β] in +include ht in +private theorem wick_test (x : β) (a b : List β) : + wick k ((x :: a).map t ++ b.map s) = + (-1 : R) ^ a.length * contract (k (t x)) (fun u => wick k (a.map t ++ u)) (b.map s) := by + rw [List.map_cons, List.cons_append, wick_cons] + exact contract_skip _ _ t a _ (fun _ _ _ _ => by rw [ht, zero_mul]) + +include hw ht hp in +private theorem nonzero_perm (a b : List β) (va : ∀ x ∈ a, valid x) (vb : ∀ x ∈ b, valid x) + (le : (b.map w).sum ≤ (a.map w).sum) (ne : wick k (a.map t ++ b.map s) ≠ 0) : + a.Perm b := by + induction a generalizing b with + | nil => + cases b with + | nil => rfl + | cons y b => + have hy := hw y (vb y (by simp)) + have h : 0 ≤ (b.map w).sum := List.sum_nonneg (by + simp only [List.forall_mem_map] + exact fun z hz => (hw z (vb _ (by simp [hz]))).le) + simp only [List.map_cons, List.sum_cons, List.map_nil, List.sum_nil] at le + linarith + | cons x a ih => + by_contra hn + apply ne + rw [wick_test k t s ht] + have v : ∀ p y q, b = p ++ y :: q → + k (t x) (s y) * wick k (a.map t ++ (p ++ q).map s) = 0 := by + intro p y q e + have perm : b.Perm (y :: (p ++ q)) := by rw [e]; exact List.perm_middle + have bound : w y + ((p ++ q).map w).sum ≤ w x + (a.map w).sum := by + rw [(perm.map w).sum_eq] at le + exact le + have vx := va x (by simp) + have vy := vb y (perm.mem_iff.mpr (by simp)) + by_cases h : w y < w x + · have he : x ≠ y := by rintro rfl; exact h.false + rw [hp x y vx vy h.le, ite_eq_right he, zero_mul] + by_cases h' : wick k (a.map t ++ (p ++ q).map s) = 0 + · rw [h', mul_zero] + have e' : a.Perm (p ++ q) := ih _ (fun z hz => va z (by simp [hz])) + (fun z hz => vb z (perm.mem_iff.mpr (by simp [hz]))) (by linarith) h' + have he : x ≠ y := by + rintro rfl + exact hn ((e'.cons x).trans perm.symm) + rw [hp x y vx vy (by linarith [(e'.map w).sum_eq]), ite_eq_right he, zero_mul] + have h := contract_skip (k (t x)) (fun u => wick k (a.map t ++ u)) s b [] + (by simpa only [List.append_nil] using v) + simp only [List.append_nil, contract_nil, mul_zero] at h + rw [h, mul_zero] + +include hw ht hp in +private theorem wick_diag (a : List β) (va : ∀ x ∈ a, valid x) (ha : a.Nodup) : + wick k (a.map t ++ a.reverse.map s) = 1 := by + induction a with + | nil => rfl + | cons x a ih => + rw [List.nodup_cons] at ha + rw [List.forall_mem_cons] at va + rw [wick_test k t s ht, List.reverse_cons, List.map_append, List.map_singleton] + have v : ∀ p y q, a.reverse = p ++ y :: q → + k (t x) (s y) * wick k (a.map t ++ ((p ++ q).map s ++ [s x])) = 0 := by + intro p y q e + have perm : a.Perm (y :: (p ++ q)) := by + apply (List.reverse_perm a).symm.trans + rw [e] + exact List.perm_middle + have hy : y ∈ a := perm.mem_iff.mpr (by simp) + by_cases h : w y ≤ w x + · have he : x ≠ y := fun e => ha.1 (e ▸ hy) + rw [hp x y va.1 (va.2 y hy) h, ite_eq_right he, zero_mul] + let b := (p ++ q) ++ [x] + have vb : ∀ z ∈ b, valid z := by + intro z hz + rcases List.mem_append.mp hz with h₁ | h₂ + · exact va.2 z (perm.mem_iff.mpr (.tail _ h₁)) + · exact (List.mem_singleton.mp h₂).symm ▸ va.1 + have bound : (b.map w).sum ≤ (a.map w).sum := by + rw [(perm.map w).sum_eq] + simp only [b, List.map_append, List.sum_append, List.map_cons, List.sum_cons, + List.map_nil, List.sum_nil] + linarith + have z : wick k (a.map t ++ b.map s) = 0 := by + by_contra he + have e' := nonzero_perm k t s w valid hw ht hp a b va.2 vb bound he + exact ha.1 (e'.mem_iff.mpr (by simp [b])) + simpa only [b, List.map_append, List.map_singleton, mul_zero] + using congrArg (k (t x) (s y) * ·) z + rw [contract_skip _ _ _ _ _ v, List.length_reverse, contract_cons, contract_nil, + sub_zero, List.append_nil, hp x x va.1 va.1 le_rfl, ite_eq_left rfl, ih va.2 ha.2] + simp [← mul_pow] + +include hw ht hp in +/-- Under a total weight budget, triangular pairings select precisely +the target slot list. Reversing the tests cancels the pairing signs. -/ +theorem wick_pivot (a b : List β) (va : ∀ x ∈ a, valid x) (vb : ∀ x ∈ b, valid x) + (ha : a.Nodup) (hc : a.Perm b → a = b) (le : (b.map w).sum ≤ (a.map w).sum) : + wick k (a.reverse.map t ++ b.map s) = if a = b then 1 else 0 := by + have vr : ∀ x ∈ a.reverse, valid x := by simpa using va + by_cases he : a = b + · subst b + simpa using wick_diag k t s w valid hw ht hp a.reverse vr ((List.reverse_perm a).nodup_iff.mpr + ha) + rw [ite_eq_right he] + by_contra hn + have e := nonzero_perm k t s w valid hw ht hp a.reverse b vr vb (by simpa using le) hn + exact he (hc ((List.reverse_perm a).symm.trans e)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Wedge duality + +Reversing the second list of modes gives the ordinary Kronecker pairing +on the ordered wedge basis. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {α R : Type*} [CommRing R] {r : ℕ} {k : α → α → R} + +private theorem contract_last (f : α → R) (P : List α → R) (p : List α) (y : α) + (h : ∀ z ∈ p, f z = 0) : + contract f P (p ++ [y]) = (-1 : R) ^ p.length * (f y * P p) := by + induction p generalizing P with + | nil => simp [contract_cons] + | cons x p ih => + simp only [List.forall_mem_cons] at h + rw [List.cons_append, contract_cons, h.1, zero_mul, zero_sub, ih _ h.2, + List.length_cons, pow_succ, mul_neg_one, neg_mul] + +/-- Only the last position can pair with the first. An odd residual +length contributes zero, so no sign survives. -/ +theorem wick_last (x y : α) (p : List α) (h : ∀ z ∈ p, k x z = 0) : + wick k (x :: (p ++ [y])) = k x y * wick k p := by + rw [wick_cons, contract_last _ _ _ _ h] + by_cases he : p.length % 2 = 1 + · rw [wick_odd he, mul_zero, mul_zero] + · have e : Even p.length := ⟨p.length / 2, by omega⟩ + rw [e.neg_one_pow, one_mul] + +theorem wick_unpaired (skew : ∀ x y, k y x = -k x y) + (p s : List α) (x : α) (h : ∀ y ∈ p ++ s, k x y = 0) : + wick k (p ++ x :: s) = 0 := by + have e := wick_swap_blocks skew [] p [x] s + simp only [List.nil_append, List.append_assoc, List.singleton_append] at e + rw [e, List.cons_append, wick_cons, contract_vanish _ _ _ h, mul_zero] + +theorem wick_dual (skew : ∀ x y, k y x = -k x y) (A B : Mode r → α) + (hA : ∀ x y, k (A x) (A y) = 0) (hB : ∀ x y, k (B x) (B y) = 0) + (hAB : ∀ x y, k (A x) (B y) = if x = y then 1 else 0) + (a b : Wedge r) : + wick k (a.val.map A ++ b.val.reverse.map B) = if a.val = b.val then 1 else 0 := by + have left (x : Mode r) (a b : List (Mode r)) (hx : x ∉ b) : + ∀ z ∈ a.map A ++ b.reverse.map B, k (A x) z = 0 := by + simp only [List.forall_mem_append, List.forall_mem_map, List.mem_reverse] + refine ⟨fun z _ => hA _ _, fun z hz => ?_⟩ + rw [hAB, ite_eq_right (show x ≠ z from fun e => hx (e ▸ hz))] + have right (y : Mode r) (a b : List (Mode r)) (hy : y ∉ a) : + wick k (a.map A ++ (y :: b).reverse.map B) = 0 := by + rw [List.reverse_cons, List.map_append, List.map_singleton, ← List.append_assoc] + apply wick_unpaired skew + simp only [List.append_nil, List.forall_mem_append, List.forall_mem_map, List.mem_reverse] + refine ⟨fun z hz => ?_, fun z _ => hB _ _⟩ + rw [skew, hAB, ite_eq_right (show z ≠ y from fun e => hy (e ▸ hz)), neg_zero] + obtain ⟨a, ha⟩ := a + obtain ⟨b, hb⟩ := b + change wick k (a.map A ++ b.reverse.map B) = if a = b then 1 else 0 + induction a generalizing b with + | nil => + cases b with + | nil => simp + | cons y b => rw [right _ _ _ (by simp)]; simp + | cons x a ih => + cases b with + | nil => + rw [List.map_cons, List.cons_append, wick_cons, contract_vanish _ _ _ (left _ _ _ (by simp))] + simp + | cons y b => + rw [List.pairwise_cons] at ha hb + rcases lt_trichotomy (toLex x) (toLex y) with h | h | h + · have hx : x ∉ y :: b := by + simp only [List.mem_cons, not_or] + exact ⟨fun e => h.ne (congrArg toLex e), fun e => h.asymm (hb.1 _ e)⟩ + rw [List.map_cons, List.cons_append, wick_cons, contract_vanish _ _ _ (left _ _ _ hx)] + simp [show x ≠ y from fun e => hx (by simp [e])] + · have h' := toLex.injective h + subst y + have hx : x ∉ b := fun e => (hb.1 _ e).false + rw [List.map_cons, List.cons_append, List.reverse_cons, List.map_append, + ← List.append_assoc, + List.map_singleton, wick_last _ _ _ (left _ _ _ hx), hAB, ite_eq_left rfl, one_mul, + ih ha.2 b hb.2] + simp + · have hy : y ∉ x :: a := by + simp only [List.mem_cons, not_or] + exact ⟨fun e => h.ne (congrArg toLex e), fun e => h.asymm (ha.1 _ e)⟩ + rw [right _ _ _ hy] + simp [show x ≠ y from fun e => hy (by simp [e])] + +theorem fusion_empty (R : Type*) [CommRing R] {r : ℕ} (a b : Wedge r) : + fusion R a.val [] b.val = if a.val = b.val then 1 else 0 := by + simp only [fusion, marks, List.map_nil, List.append_nil] + apply wick_dual (pairing_skew R) + · intro x y + change (if x.1 = y.1 then (0 : R) else 0) = 0 + simp + · intro x y + change (if x.1 = y.1 then (0 : R) else 0) = 0 + simp + · intro x y + change (if x.1 = y.1 then (if x.2 = y.2 then (1 : R) else 0) else 0) = _ + simp only [Prod.ext_iff, ite_and] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Auxiliary marks of bounded weight + +A probe is an even ordered subset of the auxiliary marks, with just the +lowest mode at each selected mark. Removing all probe-probe contractions +uses only shorter probe lists. Linear combinations then implement arbitrary +covectors. Kronecker covectors detect a longest nonzero word. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Finset + +/-- The subtype of `w : Wedge n` satisfying `(∀ x ∈ w.val, x.2 = 0) ∧ w.val.length ≤ d ∧ +w.val.length % 2 = 0`. -/ +abbrev Probe (n d : ℕ) := + {w : Wedge n // (∀ x ∈ w.val, x.2 = 0) ∧ w.val.length ≤ d ∧ w.val.length % 2 = 0} + +variable {F A I : Type*} [Field F] {n d : ℕ} + +/-- The value specified by `((a i).1, 0, (a i).2)`. -/ +def mark (a : A → F × ℕ) (i : A) : Site F 1 := ((a i).1, 0, (a i).2) + +/-- Concatenates the components in the order `wick fieldKernel (w.val.val.map (fun j => (z j.1, +0, j.2)) ++ xs.map (mark a))`. -/ +def probeEval (a : A → F × ℕ) (z : Fin n → F) (w : Probe n d) (xs : List A) : F := + wick fieldKernel (w.val.val.map (fun j => (z j.1, 0, j.2)) ++ xs.map (mark a)) + +private theorem ordered_mem (a : A → F × ℕ) (z : Fin n → F) (xs : I → List A) + (M : Submodule F (I → F)) (heven : ∀ i, (xs i).length % 2 = 0) + (hM : ∀ w : Probe n d, (fun i => probeEval a z w (xs i)) ∈ M) + (p : List (Fin n)) (hp : p.length ≤ d) : + (fun i => wick fieldKernel (p.map (fun j => (z j, 0, 0)) ++ (xs i).map (mark a))) ∈ M := by + classical + by_cases ho : p.length % 2 = 0 + · let q := p.map (fun j => (j, 0)) + let g (j : Mode n) : Site F 1 := (z j.1, 0, j.2) + obtain ⟨v, hv, h⟩ := normalize F q + have ok (w : Wedge n) (hw : w ∈ v.support) : + (fun i => wick fieldKernel (w.val.map g ++ (xs i).map (mark a))) ∈ M := by + have hperm := hv w hw + have hl : w.val.length = p.length := by rw [← hperm.length_eq]; simp [q] + have hz (x) (hx : x ∈ w.val) : x.2 = 0 := by + obtain ⟨j, _, rfl⟩ := List.mem_map.mp (hperm.mem_iff.mpr hx) + rfl + exact hM ⟨w, hz, hl.trans_le hp, by rw [hl, ho]⟩ + convert M.sum_mem (fun w hw => M.smul_mem (v w) (ok w hw)) using 1 + funext i + simpa [q, g, Function.comp_def, Finsupp.linearCombination_apply, Finsupp.sum, Finset.sum_apply] + using h _ (alternates_map fieldKernel_skew fieldKernel_self g ((xs i).map (mark a))) + · convert M.zero_mem using 1 + funext i + apply wick_odd + simp only [List.length_append, List.length_map] + have := heven i + omega + +private abbrev Entry (A F : Type*) := (A → F) ⊕ A + +private def test (a : A → F × ℕ) : Entry A F → Entry A F → F + | .inl _, .inl _ => 0 + | .inl f, .inr j => -f j + | .inr j, .inl f => f j + | .inr i, .inr j => fieldKernel (mark a i) (mark a j) + +private theorem test_skew (a : A → F × ℕ) (x y : Entry A F) : + test a y x = - test a x y := by + cases x <;> cases y <;> simp only [test, neg_zero, neg_neg] + exact fieldKernel_skew _ _ + +private def pole (a : A → F × ℕ) (z : F) (i : A) : F := + (z - (a i).1)⁻¹ ^ ((a i).2 + 1) + +private theorem pole_eq (a : A → F × ℕ) (z : F) (i : A) : + fieldKernel (mark a i) (z, 0, 0) = pole a z i := by + simp [fieldKernel, coeff, mark, pole] + +private theorem remove_pairs (a : A → F × ℕ) (z : Fin n → F) (xs : I → List A) + (M : Submodule F (I → F)) (heven : ∀ i, (xs i).length % 2 = 0) + (hM : ∀ w : Probe n d, (fun i => probeEval a z w (xs i)) ∈ M) + (p : List (Fin n)) (hp : p.length ≤ d) : + (fun i => wick (test a) + (p.map (fun j => .inl (pole a (z j))) ++ (xs i).map .inr)) ∈ M := by + let f : Fin n ⊕ A → Site F 1 := Sum.elim (fun j => (z j, 0, 0)) (mark a) + let g : Fin n ⊕ A → Entry A F := Sum.elim (fun j => .inl (pole a (z j))) .inr + let k x y := fieldKernel (f x) (f y) + let l x y := test a (g x) (g y) - k x y + let X (i : I) : List (Fin n ⊕ A) := (xs i).map .inr + let Y : List (Fin n ⊕ A) := p.map .inl + have skip (i : I) (x y : Fin n ⊕ A) (hy : y ∈ X i) : l x y = 0 := by + obtain ⟨s, _, rfl⟩ := List.mem_map.mp hy + cases x with + | inl j => + change -pole a (z j) s - fieldKernel (z j, 0, 0) (mark a s) = 0 + rw [fieldKernel_skew, pole_eq, sub_self] + | inr j => exact sub_self _ + have hv := partial_mem M l (fun i q => wick k (q ++ X i)) Y (by + intro q hq + obtain ⟨q, hqp, rfl⟩ := List.sublist_map_iff.mp hq + have hw := ordered_mem a z xs M heven hM q (hqp.length_le.trans hp) + convert hw using 1 + funext i + unfold k + rw [← wick_map fieldKernel f] + simp [X, f, Function.comp_def]) + convert hv using 1 + funext i + rw [← wick_add_append l k _ _ (skip i)] + simp only [l, sub_add_cancel] + rw [← wick_map (test a) g] + simp [X, Y, g, Function.comp_def] + +private theorem covectors_mem (a : A → F × ℕ) (z : Fin n → F) (xs : I → List A) + (M : Submodule F (I → F)) (heven : ∀ i, (xs i).length % 2 = 0) + (hM : ∀ w : Probe n d, (fun i => probeEval a z w (xs i)) ∈ M) + (q : List (A → F)) (hc : ∀ f ∈ q, f ∈ Submodule.span F (Set.range (fun j => pole a (z j)))) + (p : List (Fin n)) (hp : p.length + q.length ≤ d) : + (fun i => wick (test a) (p.map (fun j => .inl (pole a (z j))) ++ q.map .inl ++ + (xs i).map .inr)) ∈ M := by + classical + induction q generalizing p with + | nil => simpa using remove_pairs a z xs M heven hM p hp + | cons f q ih => + obtain ⟨hf, hq⟩ := List.forall_mem_cons.mp hc + obtain ⟨c, hc⟩ := (Submodule.mem_span_range_iff_exists_fun F).mp hf + have he (s : Entry A F) : + test a (.inl f) s = ∑ j, c j * test a (.inl (pole a (z j))) s := by + cases s with + | inl _ => simp [test] + | inr i => + simpa [test, Finset.sum_apply] using congrArg Neg.neg (congrFun hc.symm i) + have hj (j : Fin n) : (p ++ [j]).length + q.length ≤ d := by + simp only [List.length_cons, List.length_append, List.length_nil] at hp ⊢ + omega + convert M.sum_mem (fun j (_ : j ∈ univ) => M.smul_mem (c j) (ih hq _ (hj j))) using 1 + funext i + simpa [Finset.sum_apply] using wick_linear (test_skew a) he + (p.map (fun j => .inl (pole a (z j)))) (q.map .inl ++ (xs i).map .inr) + +private def delta [DecidableEq A] (i j : A) : F := if i = j then -1 else 0 + +private def dualRow [DecidableEq A] (i : A) : Entry A F := .inl (delta i) + +private theorem detect_self [DecidableEq A] (a : A → F × ℕ) (s : List A) (hs : s.Nodup) : + wick (test a) (s.map dualRow ++ s.reverse.map .inr) = 1 := by + induction s with + | nil => simp + | cons x s ih => + rw [List.nodup_cons] at hs + rw [List.map_cons, List.cons_append, List.reverse_cons, List.map_append, ← List.append_assoc, + List.map_singleton, wick_last, ih hs.2, mul_one] + · simp [test, dualRow, delta] + · simp only [List.forall_mem_append, List.forall_mem_map, List.mem_reverse] + refine ⟨fun _ _ => rfl, fun b hb => ?_⟩ + have h : x ≠ b := fun e => hs.1 (e ▸ hb) + simp [test, dualRow, delta, h] + +private theorem detect_other [DecidableEq A] (a : A → F × ℕ) (s t : List A) (h : ¬s ⊆ t) : + wick (test a) (s.reverse.map dualRow ++ t.map .inr) = 0 := by + obtain ⟨x, hx, hy⟩ : ∃ x, x ∈ s ∧ x ∉ t := by simpa [List.subset_def, not_forall] using h + obtain ⟨p, q, he⟩ := List.append_of_mem (List.mem_reverse.mpr hx) + rw [he, List.map_append, List.map_cons, List.append_assoc, List.cons_append] + apply wick_unpaired (test_skew a) + simp only [List.forall_mem_append, List.forall_mem_map] + refine ⟨fun _ _ => rfl, fun _ _ => rfl, fun b hb => ?_⟩ + have hn : x ≠ b := fun e => hy (e ▸ hb) + simp [test, dualRow, delta, hn] + +private theorem probe_span [Finite I] + (a : A → F × ℕ) (z : Fin n → F) (xs : I → List A) + (hc : Submodule.span F (Set.range (fun j => pole a (z j))) = ⊤) + (heven : ∀ i, (xs i).length % 2 = 0) (hw : ∀ i, (xs i).length ≤ d) + (hn : ∀ i, (xs i).Nodup) (hinj : ∀ i j, (xs i).Perm (xs j) → i = j) : + Submodule.span F (Set.range (fun (w : Probe n d) i => probeEval a z w (xs i))) = ⊤ := by + classical + let : Fintype I := Fintype.ofFinite I + apply span_of_separates + intro c h + by_contra hne + let s := univ.filter fun i => c i ≠ 0 + have hs : s.Nonempty := by + contrapose! hne + funext i + have : i ∉ s := by rw [hne]; simp + simpa [s] using this + obtain ⟨i, hi, hmax⟩ := s.exists_max_image (fun j => (xs j).length) hs + let L : (I → F) →ₗ[F] F := + { toFun := fun x => ∑ j, c j * x j + map_add' := by intros; simp [mul_add, sum_add_distrib] + map_smul' := by intros; simp [Finset.mul_sum, mul_left_comm] } + have hM (w : Probe n d) : (fun j => probeEval a z w (xs j)) ∈ L.ker := h w + have h' := covectors_mem a z xs L.ker heven hM ((xs i).reverse.map delta) + (by rw [hc]; simp) [] + (by simpa using hw i) + simp only [List.map_nil, List.nil_append, List.map_map, Function.comp_def] at h' + change (∑ j, c j * wick (test a) ((xs i).reverse.map dualRow ++ (xs j).map .inr)) = 0 at h' + have he : wick (test a) ((xs i).reverse.map dualRow ++ (xs i).map .inr) = 1 := by + simpa using detect_self a (xs i).reverse (List.nodup_reverse.mpr (hn i)) + rw [Fintype.sum_eq_single i, he, mul_one] at h' + · exact (mem_filter.mp hi).2 h' + · intro j hj + by_cases hz : c j = 0 + · simp [hz] + · have hnsub : ¬ xs i ⊆ xs j := fun sub => + hj (hinj i j (((hn i).subperm sub).perm_of_length_le + (hmax j (mem_filter.mpr ⟨mem_univ _, hz⟩)))).symm + rw [detect_other a _ _ hnsub, mul_zero] + +/-- One mode at each of the prescribed auxiliary positions suffices to +realize every even form on a family of distinct ordered monomials. -/ +theorem auxiliary_marks [Fintype A] [Finite I] (a : A ↪ F × ℕ) (z : Fin n ↪ F) (q : ℕ) + (ha : ∀ i, (a i).2 < q) (hz : ∀ j i, z j ≠ (a i).1) + (hcard : (1 + Fintype.card A) * q < n) + (xs : I → List A) (hw : ∀ i, (xs i).length ≤ d) + (hn : ∀ i, (xs i).Nodup) (hinj : ∀ i j, (xs i).Perm (xs j) → i = j) + (v : I → F) (hv : ∀ i, (xs i).length % 2 = 1 → v i = 0) : + ∃ c : Probe n d →₀ F, ∀ i, ∑ w ∈ c.support, c w * probeEval a z w (xs i) = v i := by + classical + let : Fintype I := Fintype.ofFinite I + let E := {i : I // (xs i).length % 2 = 0} + have hc : Submodule.span F (Set.range (fun j => pole a (z j))) = ⊤ := + cauchy_span a z q ha hz (by simpa using hcard) + let T (w : Probe n d) (j : E) := probeEval a z w (xs j.val) + have h : (fun j : E => v j.val) ∈ (Finsupp.linearCombination F T).range := by + rw [Finsupp.range_linearCombination, probe_span a z (fun j : E => xs j.val) hc + (fun j => j.property) (fun j => hw j.val) (fun j => hn j.val) + (fun i j he => Subtype.ext (hinj i.val j.val he))] + trivial + obtain ⟨c, hc⟩ := h + refine ⟨c, fun i => ?_⟩ + by_cases hi : (xs i).length % 2 = 0 + · simpa [T, Finsupp.linearCombination_apply, Finsupp.sum, Finset.sum_apply] using + congrFun hc ⟨i, hi⟩ + · rw [hv i (by omega)] + apply sum_eq_zero + intro w _ + have he : probeEval a z w (xs i) = 0 := by + apply wick_odd + simp only [List.length_append, List.length_map] + have := w.property.2.2 + omega + rw [he, mul_zero] + +/-- A triangular family of interpolated covectors detects one monomial +under a total weight budget. Values on heavier slots are unrestricted. -/ +theorem weighted_probe [DecidableEq A] (a : A → F × ℕ) (z : Fin n → F) (w : A → ℝ) + (hw : ∀ i, 0 < w i) (xs : List A) (hn : xs.Nodup) (hl : xs.length ≤ d) + (he : xs.length % 2 = 0) (row : A → A → F) + (hr : ∀ i j, w j ≤ w i → -row i j = if i = j then 1 else 0) + (hc : ∀ i ∈ xs, ∃ c : Fin n → F, ∀ j, ∑ k, c k * (z k - (a j).1)⁻¹ ^ ((a j).2 + 1) = row i j) : + ∃ c : Probe n d →₀ F, ∀ ys : List A, (xs.Perm ys → xs = ys) → + (ys.map w).sum ≤ (xs.map w).sum → + ∑ p ∈ c.support, c p * probeEval a z p ys = if xs = ys then 1 else 0 := by + classical + let E := {s : List A // s.length % 2 = 0} + let T (p : Probe n d) (ys : E) := probeEval a z p ys.val + let M := (Finsupp.linearCombination F T).range + have hM (p : Probe n d) : T p ∈ M := by + refine ⟨Finsupp.single p 1, ?_⟩ + simp + have mem : ∀ f ∈ xs.reverse.map row, f ∈ Submodule.span F (Set.range (fun j => pole a (z j))) + := by + simp only [List.forall_mem_map, List.mem_reverse] + intro i hi + obtain ⟨c, he⟩ := hc i hi + refine (Submodule.mem_span_range_iff_exists_fun F).mpr ⟨c, funext fun j => ?_⟩ + simpa only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul, pole] using he j + obtain ⟨c, h⟩ := covectors_mem a z (fun y : E => y.val) M (fun y => y.property) + hM (xs.reverse.map row) mem [] (by simpa using hl) + refine ⟨c, fun ys hp hs => ?_⟩ + by_cases hy : ys.length % 2 = 0 + · have piv := wick_pivot (test a) (fun i => .inl (row i)) .inr w (fun _ => True) + (fun i _ => hw i) (fun _ _ => rfl) (fun i j _ _ => hr i j) + xs ys (by simp) (by simp) hn hp hs + rw [← piv] + simpa [T, Finsupp.linearCombination_apply, Finsupp.sum, Finset.sum_apply, Function.comp_def] + using congrFun h ⟨ys, hy⟩ + · have ne : xs ≠ ys := fun e => hy (e ▸ he) + rw [ite_eq_right ne] + refine sum_eq_zero fun p _ => mul_eq_zero_of_right _ ?_ + apply wick_odd + simp only [List.length_append, List.length_map] + have := p.property.2.2 + omega + +universe u + +/-- A finite extension and one set of auxiliary marks work simultaneously +for all even forms and all prescribed length bounds on these modes. -/ +theorem probe_extension {F : Type u} [Field F] [Fintype A] (a : A ↪ F × ℕ) (q n : ℕ) + (ha : ∀ i, (a i).2 < q) (hcard : (1 + Fintype.card A) * q < n) : + ∃ (K : Type u) (_ : Field K) (_ : Algebra F K) (_ : Module.Finite F K) + (z : Fin n ↪ K), + (∀ j i, z j ≠ algebraMap F K (a i).1) ∧ + ∀ (I : Type*) (_ : Fintype I) (xs : I → List A) (d : ℕ), + (∀ i, (xs i).length ≤ d) → (∀ i, (xs i).Nodup) → + (∀ i j, (xs i).Perm (xs j) → i = j) → ∀ (v : I → K), + (∀ i, (xs i).length % 2 = 1 → v i = 0) → + ∃ c : Probe n d →₀ K, ∀ i, ∑ w ∈ c.support, + c w * probeEval (fun j => (algebraMap F K (a j).1, (a j).2)) z w (xs i) = v i := by + classical + let poles : Set (AlgebraicClosure F) := Set.range (fun i => algebraMap F _ (a i).1) + have h : polesᶜ.Infinite := (Set.finite_range _).infinite_compl + let y : Fin n ↪ ↥polesᶜ := Fin.valEmbedding.trans (Set.Infinite.natEmbedding _ h) + let t := Set.range (fun j => (y j).val) + let K := IntermediateField.adjoin F t + have : Finite t := Set.finite_coe_iff.mpr (Set.finite_range _) + have hK : Module.Finite F K := IntermediateField.finiteDimensional_adjoin + (fun x _ => Algebra.IsIntegral.isIntegral x) + let z : Fin n ↪ K := + ⟨fun j => ⟨(y j).val, IntermediateField.subset_adjoin F t ⟨j, rfl⟩⟩, + fun _ _ e => y.injective (Subtype.ext (congrArg (fun x : K => x.val) e))⟩ + have hz (j i) : z j ≠ algebraMap F K (a i).1 := + fun e => (y j).property ⟨i, (congrArg (fun x : K => x.val) e).symm⟩ + refine ⟨K, inferInstance, inferInstance, hK, z, hz, ?_⟩ + intro I _ xs d hw hn hinj v hv + let k : F ↪ K := ⟨algebraMap F K, (algebraMap F K).injective⟩ + exact auxiliary_marks (a.trans (k.prodMap (.refl ℕ))) z q ha hz hcard xs hw hn hinj v hv + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +/-- A pair of independent wires splits as a sum across the two other cuts. -/ +def Crossing (K : Type*) [Field K] (a b p q : ℕ) : Prop := + ∃ (A B : Fin a → Fin b → Fin p → K) (C D : Fin a → Fin b → Fin q → K), + ∀ i i' j j', (if i = i' ∧ j = j' then 1 else 0) = + (∑ z, A i j z * B i' j' z) + (∑ z, C i j' z * D i' j z) + +/-- The growth rates can trade off across the two cuts. -/ +def ShiftedCrossing (K : Type*) [Field K] : Prop := + ∀ t u α β : ℝ, 0 < t → 0 < u → 0 < α → 0 < β → 2 * (t ^ 2 + u ^ 2) < α ^ 2 + β ^ 2 → + ∀ N : ℝ, ∃ (n : ℝ) (a b p q : ℕ), + N ≤ n ∧ 0 < p ∧ 0 < q ∧ Real.exp (t * n) ≤ a ∧ Real.exp (u * n) ≤ b ∧ + (p : ℝ) ≤ Real.exp (α * n) ∧ (q : ℝ) ≤ Real.exp (β * n) ∧ Crossing K a b p q + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- Simultaneous motion of marked points about cluster centers. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {A F R : Type*} [CommRing R] [Field F] [Algebra F R] {r : ℕ} + +open Classical in +/-- The cluster kernel of type `R`, constructed using `center y.1 - center x.1`. -/ +noncomputable def clusterKernel (u : R) (N : ℕ) (center offset : A → F) + (x y : A × Mode r) : R := + let Δ := center y.1 - center x.1 + let δ := offset y.1 - offset x.1 + coeff x.2 y.2 (if Δ = 0 then algebraMap F R δ⁻¹ + else u ^ 2 * shifted u (algebraMap F R Δ⁻¹) (algebraMap F R (-δ)) N) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- +# A colliding cluster and its residual modes + +Internal contractions use the site offsets. Every uncontracted generator +is translated to its center. Pairing with a reversed output wedge gives +the coefficient at that wedge. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {F R : Type*} [Field F] [CommRing R] [Algebra F R] {r : ℕ} + +/-- Translation by the offset of a site. -/ +def translate (x : Site F r) (y : Mode r) : F := + if x.2.1 = y.1 then y.2.choose x.2.2 * x.1 ^ (y.2 - x.2.2) else 0 + +/-- In the case `.inl x, .inl y`, this construction gives `fieldKernel x y`. -/ +def blockPair : Site F r ⊕ Mode r → Site F r ⊕ Mode r → F + | .inl x, .inl y => fieldKernel x y + | .inl x, .inr y => translate x y + | .inr x, .inl y => -translate y x + | .inr _, .inr _ => 0 + +/-- Concatenates the components in the order `wick blockPair (xs.map Sum.inl ++ +b.val.reverse.map Sum.inr)`. -/ +def blockCoeff (xs : List (Site F r)) (b : Wedge r) : F := + wick blockPair (xs.map Sum.inl ++ b.val.reverse.map Sum.inr) + +namespace Cluster + +/-- A site still in motion, a fused generator, or a dual coordinate test. -/ +inductive Leg (F : Type*) (r : ℕ) where + | moving (c : F) (x : Site F r) + | fused (x : Site F r) + | test (center : F) (x : Mode r) + +/-- The quantity computed by `u ^ (2 * x.2 + 1)`. -/ +def weight (u : R) (x : Mode r) : R := u ^ (2 * x.2 + 1) + +/-- The quantity computed by `shifted u (algebraMap F R (d - c)⁻¹) (algebraMap F R (a - b)) N`. -/ +def sep (u : R) (N : ℕ) (c d a b : F) : R := + shifted u (algebraMap F R (d - c)⁻¹) (algebraMap F R (a - b)) N + +open Classical in +/-- The quantity computed by `if x.1 = c then (if x.2 = y then 1 else 0) else algebraMap F R +(translate (x.1 - c, x.2) y)`. -/ +def dualCoeff (x : Site F r) (c : F) (y : Mode r) : R := + if x.1 = c then (if x.2 = y then 1 else 0) + else algebraMap F R (translate (x.1 - c, x.2) y) + +open Classical in +/-- The moving dual of type `R` for the given inputs. -/ +def movingDual (u : R) (N : ℕ) (c : F) (x : Site F r) (d : F) (y : Mode r) : R := + if c = d then weight u y * algebraMap F R (translate x y) + else ∑ f ∈ Finset.range N, + (u ^ (2 * f + 1) * (f.choose x.2.2 : R) * algebraMap F R x.1 ^ (f - x.2.2)) * + dualCoeff (c, x.2.1, f) d y + +open Classical in +/-- The pair used in the `Cluster` construction. -/ +def pair (u : R) (N : ℕ) : Leg F r → Leg F r → R + | .moving c x, .moving d y => + if c = d then algebraMap F R (fieldKernel x y) else + weight u x.2 * weight u y.2 * coeff x.2 y.2 (sep u N c d x.1 y.1) + | .moving c x, .fused y => weight u x.2 * coeff x.2 y.2 (sep u N c y.1 x.1 0) + | .fused x, .moving d y => weight u y.2 * coeff x.2 y.2 (sep u N x.1 d 0 y.1) + | .fused x, .fused y => algebraMap F R (fieldKernel x y) + | .moving c x, .test d y => movingDual u N c x d y + | .test d x, .moving c y => -movingDual u N c y d x + | .fused x, .test d y => dualCoeff x d y + | .test d x, .fused y => -dualCoeff y d x + | .test _ _, .test _ _ => 0 + +variable (u : R) (N : ℕ) + +private theorem sep_skew (c d a b : F) : sep u N d c b a = -sep u N c d a b := by + unfold sep shifted + rw [← neg_sub d c, ← neg_sub a b, inv_neg, map_neg, map_neg] + simp only [neg_mul, mul_neg, neg_neg] + +theorem pair_skew (x y : Leg F r) : pair u N y x = -pair u N x y := by + classical + rcases x with ⟨c, x⟩|x|⟨_, x⟩ <;> rcases y with ⟨d, y⟩|y|⟨_, y⟩ <;> simp only [pair, neg_neg, + neg_zero] + · by_cases h : c = d + · simp only [ite_eq_left h, ite_eq_left h.symm, fieldKernel_skew x y, map_neg] + · rw [ite_eq_right h, ite_eq_right (Ne.symm h), sep_skew u N c d, coeff_skew, mul_neg, + mul_comm (weight u y.2)] + · rw [sep_skew u N c y.1, coeff_skew, mul_neg] + · rw [sep_skew u N x.1 d, coeff_skew, mul_neg] + · rw [fieldKernel_skew x y, map_neg] + +theorem pair_self (x : Leg F r) : pair u N x x = 0 := by + cases x <;> simp [pair, fieldKernel_self] + +private theorem field_map (x y : Site F r) : + algebraMap F R (fieldKernel x y) = coeff x.2 y.2 (algebraMap F R (y.1 - x.1)⁻¹) := by + unfold fieldKernel coeff + split_ifs <;> simp only [map_mul, map_pow, map_neg, map_one, map_natCast, map_zero] + +theorem pair_moving (c d : F) (x y : Site F r) : + pair u N (.moving c x) (.moving d y) = + clusterKernel u N Prod.fst Prod.snd ((c, x.1), x.2) ((d, y.1), y.2) := by + classical + simp only [pair, clusterKernel, sub_eq_zero, neg_sub] + by_cases h : c = d + · simp only [ite_eq_left h, ite_eq_left h.symm, field_map] + · rw [ite_eq_right h, ite_eq_right (Ne.symm h)] + unfold weight coeff sep + split_ifs + · rw [mul_pow, ← pow_mul, ← pow_add] + have he : 2 * x.2.2 + 1 + (2 * y.2.2 + 1) = 2 * (x.2.2 + y.2.2 + 1) := by omega + rw [he] + ring + · simp + +variable (c : F) + +/-- The two cases impose `c = d` and `False`, respectively. -/ +def belongs : Leg F r → Prop + | .moving d _ => c = d + | _ => False + +open Classical in +private def external (x y : Leg F r) := + if belongs c x ∧ belongs c y then 0 else pair u N x y + +private theorem external_skew (x y : Leg F r) : + external u N c y x = -external u N c x y := by + by_cases h : belongs c x ∧ belongs c y + · simp [external, h] + · have ht : ¬ (belongs c y ∧ belongs c x) := fun hy => h hy.symm + simp only [external, h, ht, ↓reduceIte, pair_skew u N x y] + +private theorem external_self (x : Leg F r) : external u N c x x = 0 := by + simp [external, pair_self] + +private theorem translate_row (hu : u ^ N = 0) (x : Site F r) (y : Leg F r) : + external u N c (.moving c x) y = ∑ f ∈ Finset.range N, + (u ^ (2 * f + 1) * (f.choose x.2.2 : R) * algebraMap F R x.1 ^ (f - x.2.2)) * + external u N c (.fused (c, x.2.1, f)) y := by + classical + cases y with + | test d y => + by_cases hd : c = d + swap + · simp only [external, belongs, and_false, ↓reduceIte, pair, movingDual, ite_eq_right hd] + subst d + obtain ⟨i, b⟩ := y + simp only [external, belongs, and_false, ↓reduceIte, pair, movingDual, dualCoeff, translate, + weight, Prod.mk.injEq] + by_cases hi : x.2.1 = i + · simp only [hi, ↓reduceIte, true_and, mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', + Finset.mem_range, map_mul, map_pow, map_natCast] + split_ifs with hb + · exact (mul_assoc _ _ _).symm + · rw [pow_eq_zero_of_le (by omega : N ≤ 2 * b + 1) hu, zero_mul] + · simp [hi] + | fused y => + simp only [external, belongs, and_false, ↓reduceIte, pair, field_map, sep, sub_zero, weight] + exact coeff_shifted _ _ _ _ hu _ _ + | moving d y => + simp only [external, belongs, true_and, false_and, ↓reduceIte, pair] + by_cases h : c = d + · subst d + simp [sep, shifted, coeff] + · simp only [ite_eq_right h] + have sep_eq : sep u N c d x.1 y.1 = + shifted u (sep u N c d 0 y.1) (algebraMap F R x.1) N := by + unfold sep + rw [shifted_add _ _ _ _ _ hu, ← map_add, zero_sub, neg_add_eq_sub] + rw [sep_eq, mul_comm (weight u x.2), mul_assoc, weight, weight, + coeff_shifted _ _ _ _ hu, Finset.mul_sum] + exact Finset.sum_congr rfl (fun _ _ => mul_left_comm _ _ _) + +private theorem weight_prod (xs : List (Mode r)) : + (xs.map (weight u)).prod = u ^ energy xs := by + induction xs with + | nil => simp [energy] + | cons x xs ih => + rw [List.map_cons, List.prod_cons, ih, weight, ← pow_add] + rfl + +private theorem probe (xs : List (Site F r)) (b : Wedge r) : + wick (pair u N) (xs.map (Leg.moving c) ++ b.val.reverse.map (Leg.test c)) = + u ^ energy b.val * algebraMap F R (blockCoeff xs b) := by + let label : Site F r ⊕ Mode r → Leg F r := Sum.elim (Leg.moving c) (Leg.test c) + let s : Site F r ⊕ Mode r → R := Sum.elim (fun _ => 1) (weight u) + have e (x y : Site F r ⊕ Mode r) : + pair u N (label x) (label y) = s x * s y * algebraMap F R (blockPair x y) := by + cases x <;> cases y <;> simp [label, pair, movingDual, s, blockPair] + let z := xs.map Sum.inl ++ b.val.reverse.map Sum.inr + have he : z.map label = xs.map (Leg.moving c) ++ b.val.reverse.map (Leg.test c) := by + simp [z, label, Function.comp_def] + rw [← he, wick_map] + simp only [e, wick_scale_rows, ← wick_hom] + congr 1 + simpa [z, s, Function.comp_def] using weight_prod u b.val + +private theorem center_probe (a b : Wedge r) : + wick (pair u N) (a.val.map (fun i => .fused (c, i)) ++ b.val.reverse.map (Leg.test c)) = + if a.val = b.val then 1 else 0 := by + apply wick_dual (pair_skew u N) + · intro x y + simp [pair, fieldKernel, coeff] + · intro x y; rfl + · intro x y; simp only [pair, dualCoeff, ↓reduceIte] + +private theorem factor (hu : u ^ N = 0) (xs : List (Site F r)) : + ∃ v : Wedge r →₀ R, + ∀ ys : List (Leg F r), (∀ y ∈ ys, ¬ belongs c y) → + wick (pair u N) (xs.map (Leg.moving c) ++ ys) = + ∑ b ∈ v.support, v b * wick (pair u N) (b.val.map (fun i => .fused (c, i)) ++ ys) := by + let internal (x y : Leg F r) := pair u N x y - external u N c x y + obtain ⟨v, hv⟩ := wick_factor internal (external_skew u N c) (external_self u N c) + (fun i => .fused (c, i)) (xs.map (Leg.moving c)) (by + simp only [List.forall_mem_map] + intro x _ + exact ⟨Finset.range N, _, _, translate_row u N c hu x⟩) + refine ⟨v, fun ys hy => ?_⟩ + have h := hv ys (fun x y h => by simp [internal, external, hy y h]) + have e (b : Wedge r) : + wick (external u N c) (b.val.map (fun i => .fused (c, i)) ++ ys) = + wick (pair u N) (b.val.map (fun i => .fused (c, i)) ++ ys) := by + apply wick_eq_on + have hm : ∀ z ∈ b.val.map (fun i => Leg.fused (c, i)) ++ ys, ¬ belongs c z := by + simp only [List.forall_mem_append, List.forall_mem_map] + exact ⟨fun _ _ => not_false, hy⟩ + exact fun x hx y _ => by simp [external, hm x hx] + simpa only [internal, sub_add_cancel, e] using h + +private theorem block_front (hu : u ^ N = 0) (xs : List (Site F r)) + (ys : List (Leg F r)) (hy : ∀ y ∈ ys, ¬ belongs c y) : + wick (pair u N) (xs.map (Leg.moving c) ++ ys) = + ∑ b : LevelLE r N, u ^ energy b.val.val * algebraMap F R (blockCoeff xs b.val) * + wick (pair u N) (b.val.val.map (fun i => .fused (c, i)) ++ ys) := by + classical + obtain ⟨v, hv⟩ := factor u N c hu xs + have val (b : Wedge r) : v b = u ^ energy b.val * algebraMap F R (blockCoeff xs b) := by + have h := hv (b.val.reverse.map (Leg.test c)) (by simp only [List.forall_mem_map, belongs, + not_false_eq_true, implies_true]) + simp only [probe, center_probe] at h + have eq (z : Wedge r) : z.val = b.val ↔ z = b := Subtype.ext_iff.symm + simp only [eq, mul_ite, mul_one, mul_zero, Finset.sum_ite_eq'] at h + by_cases hb : b ∈ v.support <;> simpa [hb, Finsupp.notMem_support_iff.mp] using h.symm + have sub : v.support ⊆ Finset.univ.image (fun b : LevelLE r N => b.val) := by + intro b hb + have he : energy b.val ≤ N := by + by_contra hn + rw [Finsupp.mem_support_iff, val, pow_eq_zero_of_le (by omega : N ≤ energy b.val) hu, + zero_mul] at hb + exact hb rfl + exact Finset.mem_image_of_mem _ (Finset.mem_univ (⟨b, he⟩ : LevelLE r N)) + rw [hv ys hy, Finset.sum_subset sub (fun b _ hb + => by rw [Finsupp.notMem_support_iff.mp hb, zero_mul]), + Finset.sum_image Subtype.val_injective.injOn] + simp only [val] + +theorem blockCoeff_parity (xs : List (Site F r)) (b : Wedge r) + (h : blockCoeff xs b ≠ 0) : xs.length % 2 = b.val.length % 2 := by + by_contra hn + apply h + apply wick_odd + simp only [List.length_append, List.length_map, List.length_reverse] + omega + +/-- Fuse one cluster in place. Only equal-parity output blocks contribute, +so moving the cluster past the preceding sites creates no net sign. -/ +theorem block (hu : u ^ N = 0) (xs : List (Site F r)) (pre post : List (Leg F r)) + (hpre : ∀ y ∈ pre, ¬ belongs c y) (hpost : ∀ y ∈ post, ¬ belongs c y) : + wick (pair u N) (pre ++ xs.map (Leg.moving c) ++ post) = + ∑ b : LevelLE r N, u ^ energy b.val.val * algebraMap F R (blockCoeff xs b.val) * + wick (pair u N) (pre ++ b.val.val.map (fun i => .fused (c, i)) ++ post) := by + classical + have move (s : List (Leg F r)) : + wick (pair u N) (pre ++ s ++ post) = + (-1 : R) ^ (s.length * pre.length) * wick (pair u N) (s ++ (pre ++ post)) := by + simpa only [List.nil_append, List.append_assoc, Nat.mul_comm] using + wick_swap_blocks (pair_skew u N) [] pre s post + rw [move, block_front u N c hu xs _ (List.forall_mem_append.mpr ⟨hpre, hpost⟩), Finset.mul_sum] + apply Finset.sum_congr rfl + intro b _ + by_cases hb : blockCoeff xs b.val = 0 + · simp [hb] + · have sign : (-1 : R) ^ xs.length = (-1 : R) ^ b.val.val.length := by + rw [neg_one_pow_eq_pow_mod_two xs.length, blockCoeff_parity xs b.val hb, + ← neg_one_pow_eq_pow_mod_two] + rw [move] + simp only [List.length_map, pow_mul, sign] + exact mul_left_comm _ _ _ + +end Cluster +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Concentration/Kits.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Concentration/Kits.lean new file mode 100644 index 0000000000..241ca5a9ac --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Concentration/Kits.lean @@ -0,0 +1,912 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Scalar.Term +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Squares +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Footprint.Load +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Ledger +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Pull +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Host +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.History +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Remnants +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting + +/-! # Initial energy estimates at the chosen public and private scales -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale.Scales +open Routing.Private + +variable {g ℓ D T m b d : ℕ} (s : Scales g ℓ D T m b d) +private theorem constants (c : ℕ) : + 200 + 1600 * (c + 1) ≤ 2000 * (c + 1) ∧ 2000 * (c + 1) + 16 ≤ 10000000 * (c + 1) := by + constructor <;> omega + +include s + +private theorem block_le : b ≤ m * size ℓ D := by + rw [s.block] + exact Nat.mul_le_mul_left m (Nat.pow_le_pow_right s.qpos (by decide)) + +theorem reserve_bound : + Input.reserve D b d (probes ℓ D) m (energy ℓ D (d * b)) ≤ + 2000 * (energyConstant + 1) * D * m * energy ℓ D (d * b) := by + let R := d * b + let A := size ℓ D + let H := R * A ^ 2 + have h₁ : m * R ≤ m * R * A := Nat.le_mul_of_pos_right _ s.apos + have h₂ : d * (energyConstant * b ^ 2) ≤ energyConstant * m * R * A := calc + _ = (energyConstant * R) * b := by unfold R; ring + _ ≤ (energyConstant * R) * (m * A) := Nat.mul_le_mul_left _ s.block_le + _ = _ := by ring + unfold Input.reserve probes + change 2 * m * H * (100 * D) + 1600 * D * A * (m * R + d * (energyConstant * b ^ 2)) ≤ _ + calc + _ ≤ 2 * m * H * (100 * D) + 1600 * D * A * (m * R * A + energyConstant * m * R * A) := + Nat.add_le_add_left (Nat.mul_le_mul_left _ (Nat.add_le_add h₁ h₂)) _ + _ = (200 + 1600 * (energyConstant + 1)) * (D * m * H) := by unfold H; ring + _ ≤ (2000 * (energyConstant + 1)) * (D * m * H) := Nat.mul_le_mul_right (D * m * H) + (constants energyConstant).1 + _ = _ := by change _ = 2000 * (energyConstant + 1) * D * m * H; ring + +private theorem square_upper : + (T : ℝ) ^ 2 ≤ 4 * (d * b : ℕ) * energy ℓ D (d * b) := by + have ht : T ^ 2 ≤ 4 * (d * b) * energy ℓ D (d * b) := calc + _ ≤ (2 * (d * b * size ℓ D)) ^ 2 := Nat.pow_le_pow_left s.upper _ + _ = _ := by unfold energy; ring + exact_mod_cast ht + +theorem initial_bound : + (1 + 4 * g : ℕ) * Input.initialEnergy D T b d (probes ℓ D) m (energy ℓ D (d * b)) ≤ + (budget g * D ^ 2 * m * energy ℓ D (d * b) : ℕ) := by + let H := energy ℓ D (d * b) + have ht : 8 * (200 * (D : ℝ) * T) ^ 2 / (d * b : ℕ) ≤ (1280000 * D ^ 2 * H : ℕ) := by + apply (div_le_iff₀ (Nat.cast_pos.mpr s.Rpos)).mpr + calc + _ = (320000 * (D : ℝ) ^ 2) * T ^ 2 := by ring + _ ≤ (320000 * (D : ℝ) ^ 2) * (4 * (d * b : ℕ) * H) := + mul_le_mul_of_nonneg_left s.square_upper (by positivity) + _ = _ := by push_cast; ring + let A := 2000 * (energyConstant + 1) + have r : Input.reserve D b d (probes ℓ D) m H ≤ A * D ^ 2 * m * H := + s.reserve_bound.trans (by gcongr; exact Nat.le_self_pow (by decide) _) + have hx : Input.initialEnergy D T b d (probes ℓ D) m H ≤ + (A * D ^ 2 * m * H + m * (1280000 * D ^ 2 * H) : ℕ) := by + rw [Input.initialEnergy, Nat.cast_add, Nat.cast_mul m] + exact add_le_add (Nat.cast_le.mpr r) (mul_le_mul_of_nonneg_left ht (Nat.cast_nonneg _)) + apply (mul_le_mul_of_nonneg_left hx (Nat.cast_nonneg _)).trans + rw [← Nat.cast_mul, Nat.cast_le] + change _ ≤ budget g * D ^ 2 * m * H + calc + _ = (A + 1280000) * ((1 + 4 * g) * D ^ 2 * m * H) := by ring + _ ≤ (10000000 * (energyConstant + 1)) * ((1 + 4 * g) * D ^ 2 * m * H) := + Nat.mul_le_mul_right _ (by unfold A; omega) + _ = _ := by unfold budget; ring + +theorem global_bound (N : ℕ) (W : ℝ) (hN : (N : ℝ) * D * T ≤ W) : + (1 + 4 * g : ℕ) * (N * (Input.reserve D b d (probes ℓ D) m (energy ℓ D (d * b)) : ℝ) + + m * (8 * W * T / (d * b : ℕ))) ≤ budget g * (m : ℝ) * size ℓ D * W := by + have hw : 0 ≤ W := le_trans (by positivity) hN + let A := size ℓ D + let Q := 2000 * (energyConstant + 1) + have hr : Input.reserve D b d (probes ℓ D) m (energy ℓ D (d * b)) ≤ Q * D * m * (T * A) := + s.reserve_bound.trans (Nat.mul_le_mul_left _ s.smallH) + have hx : N * (Input.reserve D b d (probes ℓ D) m (energy ℓ D (d * b)) : ℝ) ≤ (Q : ℝ) * m * A * W + := calc + _ ≤ (N : ℝ) * (Q * D * m * (T * A) : ℕ) := mul_le_mul_of_nonneg_left (Nat.cast_le.mpr hr) + (Nat.cast_nonneg _) + _ = (Q : ℝ) * m * A * (N * D * T) := by push_cast; ring + _ ≤ _ := mul_le_mul_of_nonneg_left hN (by positivity) + have ht : 8 * W * T / (d * b : ℕ) ≤ 16 * W * A := by + apply (div_le_iff₀ (Nat.cast_pos.mpr s.Rpos)).mpr + calc + _ ≤ 8 * W * (2 * (d * b * A) : ℕ) := mul_le_mul_of_nonneg_left (Nat.cast_le.mpr s.upper) (by + positivity) + _ = _ := by push_cast; ring + apply (mul_le_mul_of_nonneg_left (add_le_add hx (mul_le_mul_of_nonneg_left ht (Nat.cast_nonneg + m))) + (Nat.cast_nonneg _)).trans + have h : (1 + 4 * g) * (Q + 16) ≤ budget g := by + rw [budget, mul_comm 10000000, mul_assoc] + exact Nat.mul_le_mul_left (1 + 4 * g) (constants energyConstant).2 + calc + _ = ((1 + 4 * g) * (Q + 16) : ℕ) * ((m : ℝ) * A * W) := by push_cast; ring + _ ≤ (budget g : ℝ) * ((m : ℝ) * A * W) := mul_le_mul_of_nonneg_right (Nat.cast_le.mpr h) (by + positivity) + _ = _ := by unfold A; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale.Scales +end + +section +/- # Polynomial bounds for cell slots and ordinary key counts -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale + +open Sphere.Layout.Sharing +variable {g ℓ D T m b d : ℕ} (s : Scales g ℓ D T m b d) +include s + +theorem Scales.budget_le : budget g ≤ D := by have := s.large; omega + +theorem Scales.hits_le : budget g * D ^ 2 ≤ D ^ 3 := calc + _ ≤ D * D ^ 2 := Nat.mul_le_mul_right _ s.budget_le + _ = _ := by ring + +theorem Scales.room_le : room ℓ D g ≤ D ^ allocation g ℓ := by + let a := size ℓ D + have ha : 1 ≤ a := s.apos + have hD := s.bound + have hl : 100 * D + 2 * g + 1 ≤ 200 * D := by have := s.degree; omega + have hD' : 1800 * D ≤ D ^ 2 := by nlinarith + calc + _ = (100 * D + 2 * g + 1) + 1600 * D * a + budget g * D ^ 2 + := by unfold room slots probes a; ring + _ ≤ 200 * D * a + 1600 * D * a + D ^ 3 * a := Nat.add_le_add + (Nat.add_le_add_right (hl.trans (Nat.le_mul_of_pos_right _ ha)) _) + (s.hits_le.trans (Nat.le_mul_of_pos_right _ ha)) + _ = (1800 * D + D ^ 3) * a := by ring + _ ≤ D ^ 4 * a := by + apply Nat.mul_le_mul_right + have h₂ := hD'.trans (Nat.pow_le_pow_right s.Dpos (by decide : 2 ≤ 3)) + have h₃ := Nat.mul_le_mul_right (D ^ 3) (by omega : 2 ≤ D) + rw [show D * D ^ 3 = D ^ 4 by ring] at h₃ + omega + _ = D ^ (4 + (ℓ + 32) * 8) := by unfold a size q; rw [pow_add D 4, pow_mul] + _ ≤ _ := Nat.pow_le_pow_right s.Dpos (by unfold allocation; omega) + +theorem Scales.chunks_le : chunks ℓ D ≤ D ^ allocation g ℓ := by + unfold chunks q + rw [← pow_mul] + exact Nat.pow_le_pow_right s.Dpos (by unfold allocation; omega) + +theorem Scales.footprint_le : + budget g * D ^ 2 * Sphere.Surface.Stage.loadLimit (D ^ 5) (budget g * D ^ 2) + 1 ≤ D ^ 14 := by + have hd := s.bound + have h₁ := Nat.le_self_pow (by decide : 5 ≠ 0) D + have h₂ := Nat.le_self_pow (by decide : 3 ≠ 0) D + have h₃ := Nat.le_self_pow (by decide : 8 ≠ 0) D + have hp := s.hits_le + unfold Sphere.Surface.Stage.loadLimit + calc + _ ≤ D ^ 3 * ((2 * D ^ 5) * (2 * D ^ 3) + 1) + 1 := by gcongr <;> omega + _ = 4 * D ^ 11 + D ^ 3 + 1 := by ring + _ ≤ 6 * D ^ 11 := by have := Nat.pow_le_pow_right s.Dpos (by decide : 3 ≤ 11); omega + _ ≤ D ^ 3 * D ^ 11 := Nat.mul_le_mul_right _ (by omega) + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end + +/- # Energy, space, and visitation bounds throughout a motion -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset Routing.Private +open SphereScale (Scales size budget probes room depth) + +variable {F K : Type} {x y : Wire} {h D T b d g ℓ m U : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) + [Field F] [Field K] [Algebra K F] (p : P.Kits K m (probes ℓ D) ε) + (s : P.Occupied → Shape (probes ℓ D) b d) + +local notation "H" => SphereScale.energy ℓ D (d * b) +local notation "N" => depth ℓ D g m (d * b) + +variable (sc : Scales g ℓ D T m b d) + {z : Stage F (d * b) d P.diagram.V P.Occupied P.grid.Seam (P.Parameters p)} + (reach : (P.plant p s).Reach m (2 * g) (SphereScale.energy ℓ D (d * b)) U z) + +include sc + +open scoped Classical in +private theorem initial_local (c : P.Occupied) : + let a := (P.plant p s).ledger m H + (1 + 2 * (2 * g)) * (a.mobile c + a.collected c + ∑ e ∈ (P.plant p s).edges c, a.seam e) ≤ N + := by + rw [show 2 * (2 * g) = 4 * g by omega] + apply (Nat.cast_le (α := ℝ)).mp + rw [Nat.cast_mul] + exact (mul_le_mul_of_nonneg_left (P.plant_local_energy p s sc.Rpos H c) + (Nat.cast_nonneg _)).trans sc.initial_bound + +open scoped Classical in +private theorem initial_seam_bound (c : P.Occupied) : + (∑ e ∈ (P.plant p s).edges c, ((P.plant p s).ledger m H).seam e) ≤ N := + (Nat.le_add_left _ _).trans ((Nat.le_mul_of_pos_left _ (by omega)).trans + (P.initial_local p s sc c)) + +include reach + +open scoped Classical in +theorem moved_room : z.Room (room ℓ D g) N := by + refine P.plant_room p s sc.Rpos sc.pos sc.Hpos _ _ ?_ sc.initial_bound reach + let e := initialEnergy D T b d (probes ℓ D) m H + have h₀ : 0 ≤ e := by unfold e initialEnergy; positivity + have he : e ≤ (N : ℝ) := (le_mul_of_one_le_left h₀ (by norm_cast; omega)).trans sc.initial_bound + have h₁ : 2 * m * H * (100 * D + probes ℓ D + 1 + 2 * g) + N ≤ 2 * m * H * room ℓ D g := by + conv_rhs => rw [room, SphereScale.slots, mul_add] + rw [show 100 * D + 2 * g + probes ℓ D + 1 = 100 * D + probes ℓ D + 1 + 2 * g by omega] + apply Nat.add_le_add_left + change budget g * D ^ 2 * m * H ≤ _ + rw [show 2 * m * H * (budget g * D ^ 2) = 2 * (budget g * D ^ 2 * m * H) by ring] + omega + exact (add_le_add_right he _).trans (by exact_mod_cast h₁) + +open scoped Classical in +theorem moved_visits (c : P.Occupied) : z.visits c ≤ budget g * D ^ 2 := by + have ht := (reach.budget.limits (fun _ => rfl) (P.plant_zero p s H) rfl).2.2.1 c + have hb := ht.trans (P.initial_seam_bound p s sc c) + have hv : 2 * m * H * z.visits c ≤ N := by + unfold Stage.visits + rw [reach.edges_eq] + exact hb + have pos : 0 < m * H := Nat.mul_pos sc.pos sc.Hpos + apply Nat.le_of_mul_le_mul_left _ pos + exact ((Nat.mul_le_mul_right _ (show m * H ≤ 2 * m * H by + rw [mul_assoc]; omega)).trans hv).trans_eq + (by unfold depth; ring) + +open scoped Classical in +theorem moved_seam (e : P.grid.Seam) : z.scene.level e ≤ budget g * D ^ 2 * H := by + let c := e.val.1 + have he : e ∈ (P.plant p s).edges c := by + rw [P.plant_edges] + simp [Grid.ports, c] + have hi : ((P.plant p s).ledger m H).seam e ≤ N := + (single_le_sum (fun _ _ => Nat.zero_le _) he).trans (P.initial_seam_bound p s sc c) + have ht := reach.budget.edge e + change m * z.scene.level e + _ ≤ ((P.plant p s).ledger m H).seam e + 2 * m * H * 0 at ht + rw [mul_zero, add_zero] at ht + apply Nat.le_of_mul_le_mul_left _ sc.pos + exact ((Nat.le_add_right _ _).trans (ht.trans hi)).trans_eq (by unfold depth; ring) + +omit reach sc in +open scoped Classical in +private theorem item_sum (v : P.Occupied) : + (∑ i : Fin (z.scene.cell v).stations.length, energyOf m (Layout.item z.scene.cell ⟨v, i⟩)) ≤ + (z.ledger m H).mobile v + (z.ledger m H).collected v := by + refine le_trans ?_ (z.energy_le m H v) + dsimp only [Layout.item, energyOf] + rw [sum_add_distrib, ← mul_sum] + have he (f : z.St → ℕ) : ∑ i, f ((z.scene.cell v).stations.get i) = + ((z.scene.cell v).stations.map f).sum := by + rw [← List.sum_ofFn] + change (List.ofFn (f ∘ (z.scene.cell v).stations.get)).sum = _ + rw [← List.map_ofFn, List.ofFn_get] + rw [he Station.a, he Station.b] + exact le_rfl + +open scoped Classical in +theorem moved_energy (i : Layout.Place z.scene.cell) : + energyOf m (Layout.item z.scene.cell i) ≤ N := by + rcases i with ⟨v, i⟩ + have ht := (reach.budget.limits (fun _ => rfl) (P.plant_zero p s H) rfl).2.1 v + exact (single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ i)).trans + ((P.item_sum p (z := z) v).trans (ht.trans (P.initial_local p s sc v))) + +open scoped Classical in +theorem moved_total (frozen : Layout.Place z.scene.cell → Prop) : + (∑ i : {i // frozen i}, (energyOf m (Layout.item z.scene.cell i.val) : ℝ)) ≤ + budget g * (m : ℝ) * size ℓ D * W := by + let f (i : Layout.Place z.scene.cell) := energyOf m (Layout.item z.scene.cell i) + have ht := (reach.budget.limits (fun _ => rfl) (P.plant_zero p s H) rfl).1 + have hs : (∑ i : {i // frozen i}, f i.val) ≤ ∑ i, f i := by + rw [← sum_subtype (univ.filter frozen) (fun _ => mem_filter_univ _) f] + exact sum_le_sum_of_subset (subset_univ _) + rw [Fintype.sum_sigma] at hs + have h₁ := (hs.trans (sum_le_sum fun c _ => P.item_sum p (z := z) c)).trans ht + have hc : (Fintype.card P.Occupied : ℝ) * D * T ≤ W := by + rw [show Fintype.card P.Occupied = (univ.image P.place).card from Fintype.card_coe _] + exact P.occupied + rw [← Nat.cast_sum] + apply ((Nat.cast_le (α := ℝ)).mpr h₁).trans + rw [Nat.cast_mul, show 2 * (2 * g) = 4 * g by omega] + exact (mul_le_mul_of_nonneg_left (P.plant_global_energy p s sc.Rpos H) (Nat.cast_nonneg _)).trans + (sc.global_bound _ _ hc) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Expansion of one terminal surface into padded bit diagrams -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ : ℕ} {W : ℝ} (P : Input F x y h D T (d * b) g W) + +open scoped Classical in +/-- The value specified by `P.Kits K m (SphereScale.probes ℓ D) (SphereScale.rate ℓ D)`. -/ +abbrev Tools (K : Type) [Field K] [Algebra K F] (ℓ m : ℕ) := + P.Kits K m (SphereScale.probes ℓ D) (SphereScale.rate ℓ D) + +open scoped Classical in +/-- Indexes the configuration by the coordinates of `Stage F (d * b) d P.diagram.V P.Occupied +P.grid.Seam ((Val x × Val y) × Template.Keys p)`. -/ +abbrev Configuration (p : P.Tools K ℓ m) := + Stage F (d * b) d P.diagram.V P.Occupied P.grid.Seam ((Val x × Val y) × Template.Keys p) + +open scoped Classical in +/-- The terms bound used in the `Input` construction. -/ +def termsBound (ℓ m : ℕ) := + (SphereScale.depth ℓ D g m (d * b) + 1) ^ + (SphereScale.chunks ℓ D * (Fintype.card P.grid.Seam + 2 * SphereScale.room ℓ D g * + Fintype.card P.Occupied)) + +open scoped Classical in +/-- The emitted of type `Prop` for the given inputs. -/ +def Emitted (p : P.Tools K ℓ m) (z : P.Configuration p) (u C a : ℕ) : Prop := + ∃ (I : Type) (_ : Fintype I) (Q : I → LocalTerm F x y h u) (c : I → F), + Fintype.card I ≤ P.termsBound ℓ m ∧ + (∀ x y, ∑ i, c i * (Q i).diagram.eval x y = ∑ j, z.value m ((x, y), j)) ∧ + ∀ i, Concentrated P (Q i) C a ℓ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# Exterior bits stay at named collectors + +The place of each immobile station is unique, including its index +within the cell. Charging exterior bits to the original station then +preserves the initial maximum and square bounds. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset Routing.Private +open Sphere.Layout (Place item) + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ H U : ℕ} {W : ℝ} (P : Input F x y h D T (d * b) g W) + (p : P.Tools K ℓ m) (s : P.Occupied → Shape (SphereScale.probes ℓ D) b d) + {z : P.Configuration p} (hz : (P.plant p s).Reach m (2 * g) H U z) + +include hz in +open scoped Classical in +private theorem name_unique {v : P.diagram.V} (i j : Place z.scene.cell) + (hi : (item z.scene.cell i).label.name = some v) + (hj : (item z.scene.cell j).label.name = some v) : i = j := by + obtain ⟨a, i⟩ := i + obtain ⟨b, j⟩ := j + have hab : a = b := (P.reached_name p s hz (List.get_mem _ i) hi).2.symm.trans + (P.reached_name p s hz (List.get_mem _ j) hj).2 + subst b + have hn := (hz.names (P.plant_controls p s) a).nodup_iff.mpr (P.plant_nodup p s a) + have hp := List.pairwise_iff_get.mp (List.pairwise_filterMap.mp hn) + rcases lt_trichotomy i j with he | rfl | he + · exact (hp i j he _ hi _ hj rfl).elim + · rfl + · exact (hp j i he _ hj _ hi rfl).elim + +include hz in +open scoped Classical in +theorem exists_named (q : slots x ⊕ slots y) : + ∃ i : Place z.scene.cell, (item z.scene.cell i).label.name = some (Packing.portEnd P.diagram q) + := by + obtain ⟨⟨c, a⟩, ⟨hm, he⟩, _⟩ := P.reached_unique p s hz _ (P.ext q) + change a ∈ (z.scene.cell c).stations at hm + obtain ⟨j, rfl⟩ := List.get_of_mem hm + exact ⟨⟨c, j⟩, he⟩ + +open scoped Classical in +/-- The value specified by `(P.exists_named p s hz q).choose`. -/ +def draw (q : slots x ⊕ slots y) : Place z.scene.cell := (P.exists_named p s hz q).choose + +open scoped Classical in +theorem draw_name (q : slots x ⊕ slots y) : + (item z.scene.cell (P.draw p s hz q)).label.name = some (Packing.portEnd P.diagram q) := + (P.exists_named p s hz q).choose_spec + +open scoped Classical in +theorem draw_eq (q : slots x ⊕ slots y) (i : Place z.scene.cell) + (hi : (item z.scene.cell i).label.name = some (Packing.portEnd P.diagram q)) : + P.draw p s hz q = i := + P.name_unique p s hz _ _ (P.draw_name p s hz q) hi + +open scoped Classical in +theorem draw_collector (q : slots x ⊕ slots y) : + (item z.scene.cell (P.draw p s hz q)).label.role = .collector := + (hz.controls (P.plant_controls p s) _ _ (List.get_mem ..)).named + (fun h => by have := (P.draw_name p s hz q).symm.trans h; cases this) + +open scoped Classical in +/-- The quantity computed by `Fintype.card {j // P.draw p s hz (.inl j) = i} + Fintype.card {j +// P.draw p s hz (.inr j) = i}`. -/ +def drawLoad (i : Place z.scene.cell) := + Fintype.card {j // P.draw p s hz (.inl j) = i} + Fintype.card {j // P.draw p s hz (.inr j) = i} + +open scoped Classical in +private theorem draw_load (i : Place z.scene.cell) : (P.drawLoad p s hz i : ℝ) ≤ + ((item z.scene.cell i).label.name.elim 0 P.diagram.arity : ℕ) := by + have he q : P.draw p s hz q = i ↔ (item z.scene.cell i).label.name + = some (Packing.portEnd P.diagram q) := + ⟨fun h => h ▸ P.draw_name p s hz q, P.draw_eq p s hz q i⟩ + cases hn : (item z.scene.cell i).label.name with + | none => simp [drawLoad, he, hn] + | some v => + have ho : P.drawLoad p s hz i = Packing.exterior P.diagram id v := by + simp only [drawLoad, Packing.exterior, Fintype.card_subtype, he, hn, Option.some.injEq, + Packing.portEnd, Sum.elim_inl, Sum.elim_inr, id_eq, eq_comm (a := v)] + have hw := Packing.site_arity P.diagram id v + simp only [Packing.push, id_eq, sum_ite_eq', mem_univ, ite_true] at hw + simpa [ho] using (le_add_of_nonneg_right (Nat.cast_nonneg _)).trans_eq hw.symm + +open scoped Classical in +theorem draw_max (i : Place z.scene.cell) : (P.drawLoad p s hz i : ℝ) ≤ 100 * D * T := by + refine (P.draw_load p s hz i).trans ?_ + cases hn : (item z.scene.cell i).label.name with + | none => + simp only [Option.elim_none, CharP.cast_eq_zero] + positivity + | some v => + refine le_trans ?_ (P.mass (P.place v)) + unfold Packing.push + simpa using single_le_sum (s := univ) + (f := fun w => if P.place w = P.place v then (P.diagram.arity w : ℝ) else 0) + (fun _ _ => by positivity) (mem_univ v) + +open scoped Classical in +theorem draw_squares : + (∑ i : Place z.scene.cell, (P.drawLoad p s hz i : ℝ) ^ 2) ≤ W * T := by + calc + _ ≤ ∑ i : Place z.scene.cell, ∑ v, + if (item z.scene.cell i).label.name = some v then (P.diagram.arity v : ℝ) ^ 2 else 0 := by + refine sum_le_sum fun i _ => ?_ + have hd := pow_le_pow_left₀ (Nat.cast_nonneg _) (P.draw_load p s hz i) 2 + cases hn : (item z.scene.cell i).label.name <;> simpa [hn] using hd + _ ≤ ∑ v, (P.diagram.arity v : ℝ) ^ 2 := by + rw [sum_comm] + refine sum_le_sum fun v _ => ?_ + by_cases he : ∃ i, (item z.scene.cell i).label.name = some v + · obtain ⟨i, hi⟩ := he + have hq j : (item z.scene.cell j).label.name = some v ↔ j = i := + ⟨fun hj => P.name_unique p s hz j i hj hi, fun h => h ▸ hi⟩ + simp only [hq, sum_ite_eq', mem_univ, ite_true, le_refl] + · push Not at he + simp [he] + _ ≤ _ := P.squares + +open scoped Classical in +theorem draw_fixed_squares : + (∑ i : {i : Place z.scene.cell // (item z.scene.cell i).label.role = .collector}, + (P.drawLoad p s hz i.val : ℝ) ^ 2) ≤ W * T := by + refine le_trans ?_ (P.draw_squares p s hz) + rw [← sum_subtype (univ.filter fun i => (item z.scene.cell i).label.role = .collector) + (by simp) (fun i => (P.drawLoad p s hz i : ℝ) ^ 2)] + exact sum_le_sum_of_subset_of_nonneg (subset_univ _) (fun _ _ _ => sq_nonneg _) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Unchunked motion bounds for a terminal stage -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Sphere Finset Surface +open Sphere.Layout (Place item Alphabet) +open SphereScale (budget room depth size probes q) + +variable {F T X : Type} [Field F] {x y : Wire} {h D u b d g r t : ℕ} {W : ℝ} + (P : Input F x y h D u (d * b) g W) {Y : Alphabet P.Occupied} + {z : Stage F r t T P.Occupied P.grid.Seam X} (A : Layout.Key.Source Y x y z) + +open scoped Classical in +/-- The value specified by `(item z.scene.cell i).label.role = .collector`. -/ +def fixed (i : Place z.scene.cell) := (item z.scene.cell i).label.role = .collector + +open scoped Classical in +/-- The quantity computed by `Fintype.card {j // A.left j = i} + Fintype.card {j // A.right j = +i}`. -/ +def exterior (i : Place z.scene.cell) := + Fintype.card {j // A.left j = i} + Fintype.card {j // A.right j = i} + +open scoped Classical in +/-- Numerical inputs before reindexing public and private species by +chunks. All dimensions are energies or counts on the original cells. -/ +structure FinalBounds (ℓ m : ℕ) : Prop where + near : ∀ e, let v := (A.src e).val; let w := (A.dst e).val + w.2 = v.2 ∧ (w.1 = v.1 ∨ w.1 ∈ P.adj v.1) + left : ∀ i, P.fixed (A.left i) + right : ∀ i, P.fixed (A.right i) + positions : ∀ v, (z.scene.cell v).stations.length ≤ room ℓ D g + seams : ∀ v, Packing.degree (fun e => (A.src e, A.dst e)) v ≤ budget g + seamEnergy : ∀ i, z.scene.level i ≤ budget g * D ^ 2 * SphereScale.energy ℓ D (d * b) + energy : ∀ i, energyOf m (item z.scene.cell i) ≤ depth ℓ D g m (d * b) + collected : (∑ i : {i : Place z.scene.cell // P.fixed i}, + (energyOf m (item z.scene.cell i.val) : ℝ)) ≤ + budget g * (m : ℝ) * size ℓ D * W + collectors : (Fintype.card {i : Place z.scene.cell // P.fixed i} : ℝ) * D * u ≤ budget g * W + extMax : ∀ i, P.fixed i → P.exterior A i ≤ budget g * D * u + extSquare : (∑ i : {i : Place z.scene.cell // P.fixed i}, (P.exterior A i.val : ℝ) ^ 2) ≤ + budget g * W * u + light : ∀ v, Fintype.card {i : Fin (z.scene.cell v).stations.length // + thinStation (item z.scene.cell ⟨v, i⟩)} ≤ probes ℓ D + heavy : ∀ v, Fintype.card {i : Fin (z.scene.cell v).stations.length // + ¬thinStation (item z.scene.cell ⟨v, i⟩)} ≤ D ^ 5 + aux : ∀ i, thinStation (item z.scene.cell i) → + (item z.scene.cell i).a ≤ d * b ∧ (item z.scene.cell i).b + ≤ d * (Routing.Private.energyConstant * b ^ 2) + residue : ∀ i, ¬thinStation (item z.scene.cell i) → ¬P.fixed i → (item z.scene.cell i).a = 0 + keys : ∀ v, (z.footprint v).card ≤ D ^ 14 + hidden : ∀ j ∈ z.hidden, j ≤ depth ℓ D g m (d * b) + selector : ∀ i, (Y.width i : ℝ) ≤ d * b / (q ℓ D : ℝ) + +open scoped Classical in +/-- The value specified by `Layout.Fanout.exponent (Layout.Sharing.radius +(Layout.Sharing.allocation g ℓ)) ℓ`. -/ +def terminalExponent (g ℓ : ℕ) := + Layout.Fanout.exponent (Layout.Sharing.radius (Layout.Sharing.allocation g ℓ)) ℓ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Numerical bounds after the movers have stopped -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Surface +open SphereScale (q budget room depth probes) +variable {F K : Type} {x y : Wire} {h D T b d g m ℓ : ℕ} {W : ℝ} + (P : Input F x y h D T (d * b) g W) + +open scoped Classical in +private theorem seam_degree (hr : 0 < d * b) (v : P.Occupied) : + Packing.degree (fun e : P.grid.Seam => e.val) v ≤ budget g := by + have side (f : P.grid.Seam → P.Occupied) + (hf : ∀ e, f e = e.val.1 ∨ f e = e.val.2) : Fintype.card {e // f e = v} ≤ 2 * g := by + refine le_trans ?_ (P.ports_bound hr v) + rw [Fintype.card_subtype] + apply card_le_card + intro e he + have hv := (mem_filter.mp he).2 + simp only [Grid.ports, mem_filter_univ] + rcases hf e with h|h + · exact .inl (h.symm.trans hv) + · exact .inr (h.symm.trans hv) + have h₁ := side (fun e => e.val.1) (fun _ => .inl rfl) + have h₂ := side (fun e => e.val.2) (fun _ => .inr rfl) + have hh : 10000000 * (1 + 4 * g) ≤ budget g := Nat.le_mul_of_pos_right _ (by omega) + simp only [Packing.degree, ← Nat.card_eq_fintype_card] at h₁ h₂ ⊢ + omega + +variable [Field F] [Field K] [Algebra K F] (p : P.Tools K ℓ m) + (s : P.Occupied → Routing.Private.Shape (probes ℓ D) b d) + (sc : SphereScale.Scales g ℓ D T m b d) {z : P.Configuration p} + (hz : (P.plant p s).Reach m (2 * g) (SphereScale.energy ℓ D (d * b)) (D ^ 5) z) + +include sc hz in +open scoped Classical in +theorem reached_bounds (hs : z.Stopped) {Y : Layout.Alphabet P.Occupied} + (A : Layout.Key.Source Y x y z) (hsrc : ∀ e, A.src e = e.val.1) (hdst : ∀ e, A.dst e = e.val.2) + (hl : ∀ i, P.fixed (A.left i)) (hr : ∀ i, P.fixed (A.right i)) + (hm : ∀ i, P.fixed i → P.exterior A i ≤ budget g * D * T) + (he : (∑ i : {i : Layout.Place z.scene.cell // P.fixed i}, (P.exterior A i.val : ℝ) ^ 2) ≤ + budget g * W * T) + (hy : ∀ i, (Y.width i : ℝ) ≤ d * b / (q ℓ D : ℝ)) : + P.FinalBounds A ℓ m := by + have hv := P.moved_visits p s sc hz + obtain ⟨hlight, hheavy, haux, hres⟩ := P.plant_final p s sc hz hs hv + refine ⟨?_, hl, hr, ?_, ?_, P.moved_seam p s sc hz, P.moved_energy p s sc hz, + P.moved_total p s sc hz _, ?_, hm, he, hlight, hheavy, haux, hres, ?_, ?_, hy⟩ + · intro e + obtain ⟨i, hi, hj⟩ := e.property.2 + rw [hsrc, hdst, ← hi, ← hj] + exact P.contact sc.Rpos i + · intro v + have h := (P.moved_room p s sc hz v).1 + simp only [Cell.positions, List.length_append, List.length_map] at h + exact (Nat.le_add_right _ _).trans h + · simp only [hsrc, hdst, Prod.mk.eta] + exact P.seam_degree sc.Rpos + · have h : Fintype.card {i : Layout.Place z.scene.cell // P.fixed i} = z.collectors := by + refine Eq.trans ?_ (Stage.card_collectors z) + exact Fintype.card_congr (Equiv.refl _) + rw [h] + exact P.final_count p s sc hz hv + · intro v + refine (hz.footprint_bound (Stage.init_load (P.plant_controls p s) (fun _ => rfl)) + (fun _ reach => P.moved_visits p s sc reach) v).trans sc.footprint_le + · apply Stage.Reach.hidden_le hz (by simp [plant]) + intro z hz v a ha + obtain ⟨i, rfl⟩ := List.get_of_mem ha + exact (Nat.le_add_left _ _).trans (P.moved_energy p s sc hz ⟨v, i⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Enough auxiliary marks for every occupied cell -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ : ℕ} {W : ℝ} (P : Input F x y h D T (d * b) g W) + +omit [Field F] in +open scoped Classical in +theorem probe_width (sc : SphereScale.Scales g ℓ D T m b d) (v : P.Occupied) : + ∑ i, 4 * P.grid.width v i ≤ SphereScale.probes ℓ D := by + apply Nat.le_of_mul_le_mul_right _ sc.Rpos + rw [← mul_sum, mul_assoc] + calc + _ ≤ 4 * (200 * D * T) := Nat.mul_le_mul_left _ (P.grid_width v) + _ ≤ 4 * (200 * D * (2 * (d * b * SphereScale.size ℓ D))) := by gcongr; exact sc.upper + _ = _ := by unfold SphereScale.probes; ring + +open scoped Classical in +theorem tools_exist (sc : SphereScale.Scales g ℓ D T m b d) + (hK : SphereScale.Ready K ℓ D g m b d) : Nonempty (P.Tools K ℓ m) := by + refine ⟨fun v => Classical.choice ?_⟩ + exact hK F _ _ _ inferInstance inferInstance (P.grid.template K P.weight v) + (P.probe_width sc v) (P.stations_bound v) (P.ports_bound sc.Rpos v) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Binary width of the original private selectors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere SphereScale + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ : ℕ} {W : ℝ} + (P : Input F x y h D T (d * b) g W) (p : P.Tools K ℓ m) + +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev selectors : Layout.Alphabet P.Occupied where + state i := Fin (p i).program.labels + width i := Nat.clog 2 (p i).program.labels + code i := Layout.binaryCode (Fin (p i).program.labels) _ (by + rw [Fintype.card_fin] + exact Nat.le_pow_clog (by decide) _) + +/-- The species ratio makes the target width integral. -/ +theorem selector_le (hc : Scales g ℓ D T m b d) (i : P.Occupied) : + ((P.selectors p).width i : ℝ) ≤ d * b / (q ℓ D : ℝ) := by + let n := d * m * q ℓ D ^ 3 + have hn : d * b = n * q ℓ D := by unfold n; rw [hc.block]; ring + have hq : (0 : ℝ) < q ℓ D := Nat.cast_pos.mpr hc.qpos + have hd : (d : ℝ) * b = n * (q ℓ D : ℝ) := by exact_mod_cast hn + have hr : SphereScale.rate ℓ D * d * b = (n : ℝ) / 4 := by + unfold SphereScale.rate + rw [mul_assoc, hd] + field_simp + have hlog : (1 / 4 : ℝ) ≤ Real.log 2 := by + have ht := Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2⁻¹) + rw [Real.log_inv] at ht + linarith + have bound : ((p i).program.labels : ℝ) ≤ (2 : ℝ) ^ n := calc + _ ≤ Real.exp (rate ℓ D * d * b) := (p i).small + _ ≤ Real.exp ((n : ℝ) * Real.log 2) := by + rw [hr, div_eq_mul_one_div] + exact Real.exp_le_exp.mpr (mul_le_mul_of_nonneg_left hlog (Nat.cast_nonneg _)) + _ = _ := by rw [Real.exp_nat_mul, Real.exp_log (by norm_num)] + rw [hd, mul_div_cancel_right₀ _ hq.ne'] + exact Nat.cast_le.mpr (Nat.clog_le_of_le_pow (by exact_mod_cast bound)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Realizing the ordinary inputs of a reachable stage -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface SphereScale Routing.Private + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ H U : ℕ} {W : ℝ} + (P : Input F x y h D T (d * b) g W) (p : P.Tools K ℓ m) + (s : P.Occupied → Shape (probes ℓ D) b d) + {z : P.Configuration p} (hz : (P.plant p s).Reach m (2 * g) H U z) + +open scoped Classical in +/-- The original port names still determine all exterior bits. Other +information enters only through connected footprints. -/ +def shared (hR : 0 < d * b) : + Layout.Key.Source (P.selectors p) x y z where + src e := e.val.1 + dst e := e.val.2 + meets v j hj := by + apply ((P.plant_layout p s hR).incident v j.1).mp + rw [← hz.ports_eq] + exact List.mem_map_of_mem hj + tracks := hz.tracks (P.plant_layout p s hR) (P.plant_controls p s) tracks_init + left i := P.draw p s hz (.inl i) + right i := P.draw p s hz (.inr i) + init a b c := ((a, b), c) + keys := P.keyEq p + ext := P.extEq p + controls := hz.controls (P.plant_controls p s) + original := fun _ _ _ _ _ _ _ h => h + exterior i j he _ _ _ _ _ _ hl hr k hk := by + have hh := P.draw_eq p s hz k i (he.trans (congrArg some hk.symm)) + cases k with + | inl k => exact hl k hh + | inr k => exact hr k hh + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# Combining the three finite expansions + +The ordinary selector remains summed inside every surface term. The +outer choices are energy profiles, movement branches and level splits +in the final diagrams. Bounds grow exponentially only in the number +of occupied cells. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Finset Sphere Surface Routing.Private SphereScale + +variable {F K : Type} {x y : Wire} {h D T b d g m ℓ u C a : ℕ} {W : ℝ} + (P : Input F x y h D T (d * b) g W) + +open scoped Classical in +private theorem seams_bound (hr : 0 < d * b) : + Fintype.card P.grid.Seam ≤ 2 * g * Fintype.card P.Occupied := by + let f (e : P.grid.Seam) : Σ v, ↥(P.grid.ports v) := + ⟨e.val.1, e, by simp [Grid.ports]⟩ + have inj : Function.Injective f := fun i j h => congrArg (fun x : Σ v, ↥(P.grid.ports v) + => x.2.val) h + refine (Fintype.card_le_of_injective f inj).trans ?_ + rw [Fintype.card_sigma] + simpa [mul_comm] using sum_le_sum (s := univ) (fun i _ => P.ports_bound hr i) + +open scoped Classical in +private theorem terminal_bound (hr : 0 < d * b) : + P.termsBound ℓ m ≤ finalChoices g ℓ D m b d ^ Fintype.card P.Occupied := by + unfold termsBound finalChoices + rw [← pow_mul, mul_assoc (chunks ℓ D) _ (Fintype.card P.Occupied), add_mul] + exact Nat.pow_le_pow_right (by omega) + (Nat.mul_le_mul_left _ (Nat.add_le_add_right (P.seams_bound hr) _)) + +variable [Field F] [Field K] [Algebra K F] (kit : P.Tools K ℓ m) + +open scoped Classical in +private theorem potential_bound (s : P.Occupied → Shape (probes ℓ D) b d) : + (P.plant kit s).potential (D ^ 5) ≤ ((2 + 2 * D ^ 5) * (100 * D + probes ℓ D + + 1)) * Fintype.card P.Occupied := by + refine ((P.plant kit s).potential_le _).trans ?_ + rw [mul_assoc] + apply Nat.mul_le_mul_left + simpa [mul_comm] using sum_le_sum (s := univ) (fun i _ => P.plant_length kit s i) + +open scoped Classical in +/-- The sum of of type `Prop` for the given inputs. -/ +def SumOf (good : LocalTerm F x y h u → Prop) (n : ℕ) (f : Val x → Val y → F) : Prop := + ∃ (I : Type) (_ : Fintype I) (Q : I → LocalTerm F x y h u) (c : I → F), + Fintype.card I ≤ n ∧ (∀ x y, ∑ i, c i * (Q i).diagram.eval x y = f x y) ∧ + ∀ i, good (Q i) + +variable {good : LocalTerm F x y h u → Prop} + +open scoped Classical in +private theorem SumOf.mono {n n' : ℕ} {f} (hs : SumOf good n f) (hn : n ≤ n') : + SumOf good n' f := by + obtain ⟨I, fi, Q, c, hc, he, hq⟩ := hs + exact ⟨I, fi, Q, c, hc.trans hn, he, hq⟩ + +open scoped Classical in +private theorem combine {I : Type} [Fintype I] {n : ℕ} (k : I → F) + (f : I → Val x → Val y → F) (hs : ∀ i, SumOf good n (f i)) : + SumOf good (Fintype.card I * n) (fun x y => ∑ i, k i * f i x y) := by + unfold SumOf at hs ⊢ + choose J fj Q c hc he hq using hs + let _ := fj + refine ⟨Σ i, J i, inferInstance, fun i => Q i.1 i.2, fun i => k i.1 * c i.1 i.2, + ?_, fun x y => ?_, fun i => hq _ _⟩ + · rw [Fintype.card_sigma] + simpa using sum_le_sum (s := univ) (fun i _ => hc i) + · simp only [Fintype.sum_sigma, mul_assoc, ← mul_sum, he] + +open scoped Classical in +/-- The value specified by `∑ i, z.value m ((v, w), i)`. -/ +def ordinary (z : P.Configuration kit) (v : Val x) (w : Val y) := ∑ i, z.value m ((v, w), i) + +variable (sc : Scales g ℓ D T m b d) +variable (terminal : ∀ s (z : P.Configuration kit), (P.plant kit s).Reach m (2 * g) + (SphereScale.energy ℓ D (d * b)) (D ^ 5) z → z.Valid (D ^ 5) → z.Stopped → Input.SumOf good + (P.termsBound ℓ m) (P.ordinary kit z)) + +include sc terminal in +open scoped Classical in +private theorem emit_stage (s : P.Occupied → Shape (probes ℓ D) b d) + (hs : Stage.Terms m (fun z => (P.plant kit s).Reach m (2 * g) (SphereScale.energy ℓ D (d * b)) + (D ^ 5) z ∧ + z.Valid (D ^ 5) ∧ z.Stopped) (branches m (2 * g) (SphereScale.energy ℓ D (d * b)) (room ℓ D g) + (depth ℓ D g m (d * b)) ^ (P.plant kit s).potential (D ^ 5)) ((P.plant kit s).value m)) : + SumOf good ((moveChoices g ℓ D m b d * finalChoices g ℓ D m b d) ^ Fintype.card P.Occupied) + (P.ordinary kit (P.plant kit s)) := by + obtain ⟨I, fi, k, z, hc, hz, he⟩ := hs + have hc' : Fintype.card I ≤ moveChoices g ℓ D m b d ^ Fintype.card P.Occupied := by + rw [moveChoices, ← pow_mul] + exact hc.trans (Nat.pow_le_pow_right (branches_pos _ _ _ _ _) (P.potential_bound kit s)) + have emit (i : I) : SumOf good (P.termsBound ℓ m) (P.ordinary kit (z i)) := + terminal s (z i) (hz i).1 (hz i).2.1 (hz i).2.2 + have eqn : P.ordinary kit (P.plant kit s) = fun x y => ∑ i, k i * P.ordinary kit (z i) x y := by + funext v w + simp only [ordinary, he, mul_sum] + rw [sum_comm] + rw [eqn, mul_pow] + exact (combine k _ emit).mono (Nat.mul_le_mul hc' (P.terminal_bound sc.Rpos)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale + +open Finset Sphere.Surface Routing.Private + +open scoped Classical in +/-- Select the field threshold and bit-count constant before the +input width, working field and family of diagrams are specified. -/ +theorem stack_with (g ℓ D m b : ℕ) : + ∃ A : ℕ, ∀ {T d} (_ : Scales g ℓ D T m b d) (F K : Type) [Field F] [Fintype F] + [Field K] [Algebra K F] (p l : ℕ) [ExpChar F p], m = p ^ l → + A * (1 + T) ^ A ≤ Fintype.card F → + ∀ {x y h W} (P : Input F x y h D T (d * b) g W) (kit : P.Tools K ℓ m) (u : ℕ) (good : + LocalTerm F x y h u → Prop), + (∀ s (z : P.Configuration kit), (P.plant kit s).Reach m (2 * g) (energy ℓ D (d * b)) (D ^ 5) + z → + z.Valid (D ^ 5) → z.Stopped → Input.SumOf good (P.termsBound ℓ m) (P.ordinary kit z)) → + Input.SumOf good (2 ^ (A * (1 + Nat.clog 2 (T + + 1)) * (univ.image P.place).card)) P.diagram.eval := by + obtain ⟨A, hA⟩ := choice_bound g ℓ D m b + refine ⟨A, ?_⟩ + intro T d sc F K _ _ _ _ p l _ hm hF x y h W P kit u good terminal + subst m + obtain ⟨hroom, hindex⟩ := hA sc + let I := P.Occupied → Shape (probes ℓ D) b d + let n := (moveChoices g ℓ D (p ^ l) b d * finalChoices g ℓ D (p ^ l) b d) ^ Fintype.card + P.Occupied + have terms (s : I) : Input.SumOf good n (P.ordinary kit (P.plant kit s)) := by + apply P.emit_stage kit sc terminal s + exact (P.plant kit s).complete p l (P.plant_layout kit s sc.Rpos) + (P.plant_valid kit s _) (fun _ reach => P.moved_room kit s sc reach) (hroom.trans_le hF) + have total := Input.combine (fun _ : I => 1) _ terms + simp only [one_mul] at total + have eqn : (fun v w => ∑ s : I, P.ordinary kit (P.plant kit s) v w) = P.diagram.eval := + funext fun v => funext fun w => P.eval_plant kit v w + rw [eqn] at total + apply total.mono + have hI : Fintype.card I = initialChoices ℓ D b d ^ Fintype.card P.Occupied := by + unfold I + rw [Fintype.card_fun, card_shape] + rfl + unfold n + rw [hI, ← mul_pow, ← mul_assoc, pow_mul, ← Fintype.card_coe (univ.image P.place)] + exact Nat.pow_le_pow_left hindex _ + +open scoped Classical in +theorem stack (g ℓ D m b : ℕ) : + ∃ A : ℕ, ∀ {T d} (_ : Scales g ℓ D T m b d) (F K : Type) [Field F] [Fintype F] + [Field K] [Algebra K F] (p l : ℕ) [ExpChar F p], m = p ^ l → + A * (1 + T) ^ A ≤ Fintype.card F → + ∀ {x y h W} (P : Input F x y h D T (d * b) g W) (kit : P.Tools K ℓ m) (u C a : ℕ), + (∀ s (z : P.Configuration kit), (P.plant kit s).Reach m (2 * g) (energy ℓ D (d * b)) (D ^ 5) + z → + z.Valid (D ^ 5) → z.Stopped → P.Emitted kit z u C a) → + LocalExpansion P u C a ℓ A := by + obtain ⟨A, hA⟩ := stack_with g ℓ D m b + refine ⟨A, ?_⟩ + intro T d sc F K _ _ _ _ p l _ hm hF x y h W P kit u C a terminal + exact hA sc F K p l hm hF P kit u (fun Q => Concentrated P Q C a ℓ) terminal + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Depth.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Depth.lean new file mode 100644 index 0000000000..419efa499a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Depth.lean @@ -0,0 +1,934 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Footprint.Load + +/-! +# Bounding the depth of local table descriptions + +A merger consumes a station. A crossing charges the receiving cell +one visit, and advances the moving clock. The collector has priority +over all moving clocks and keeps its local budget across arrivals. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Finset Function +variable {F T V E X : Type} {r t P g H U M N K : ℕ} {s s' : Stage F r t T V E X} + +open scoped Classical in +/-- The quantity computed by `1 + (M + s.visits v - (s.scene.cell v).stations.length)`. -/ +def localDepth (s : Stage F r t T V E X) (M : ℕ) (v : V) := + 1 + (M + s.visits v - (s.scene.cell v).stations.length) + +open scoped Classical in +/-- Returns `U + 1` when `a = .collector` holds, and `min U a.clock` otherwise. -/ +def priority (U : ℕ) (a : Role) := if a = .collector then U + 1 else min U a.clock + +open scoped Classical in +/-- The quantity computed by `priority U a * (M + K + 2) + s.localDepth M v`. -/ +def labelDepth (s : Stage F r t T V E X) (U M K : ℕ) (v : V) (a : Role) := + priority U a * (M + K + 2) + s.localDepth M v + +open scoped Classical in +/-- The quantity computed by `(U + 2) * (M + K + 2)`. -/ +def depthLimit (U M K : ℕ) := (U + 2) * (M + K + 2) + +open scoped Classical in +theorem depth_pos (v : V) (a : Role) : 1 ≤ s.labelDepth U M K v a := by + unfold labelDepth localDepth + omega + +open scoped Classical in +theorem depth_le (v : V) (a : Role) (h : s.visits v ≤ K) : + s.labelDepth U M K v a ≤ depthLimit U M K := by + have hc : priority U a ≤ U + 1 := by unfold priority; split_ifs <;> omega + have := Nat.mul_le_mul_right (M + K + 2) hc + unfold labelDepth localDepth depthLimit + rw [show (U + 2) * (M + K + 2) = (U + 1) * (M + K + 2) + (M + K + 2) by ring] + omega + +open scoped Classical in +theorem Room.length (h : s.Room M N) (v : V) : (s.scene.cell v).stations.length ≤ M := by + have h₁ := (h v).1 + simp only [Cell.positions, List.length_append, List.length_map] at h₁ + omega + +open scoped Classical in +theorem Room.energies (h : s.Room M N) (v : V) (u : s.St) (hu : u ∈ (s.scene.cell v).stations) : + u.a ≤ N ∧ u.b ≤ N := by + have h₁ := (h v).2 + have e (f : s.St → ℕ) : f u ≤ ((s.scene.cell v).stations.map f).sum := + List.single_le_sum (fun _ _ => Nat.zero_le _) _ (List.mem_map_of_mem hu) + have := e Station.a + have := e Station.b + unfold Cell.bigA sumA sumB at h₁ + omega + +variable [Field F] + +open scoped Classical in +theorem Step.depth_mono (h : Step P g H U s s') (v : V) (a : Role) : + s.labelDepth U M K v a ≤ s'.labelDepth U M K v a := by + have hh := h.stations_le v + unfold labelDepth localDepth visits + rw [h.edges_eq] + omega + +omit [Field F] in +open scoped Classical in +theorem depth_freeze (v : V) (a : Role) : + s.labelDepth U M K v a ≤ s.labelDepth U M K v .collector := by + unfold labelDepth priority + simp only [↓reduceIte] + gcongr + split_ifs <;> omega + +omit [Field F] in +open scoped Classical in +theorem depth_join (v : V) (a b : Tag V T) (ha : a.role.clock = 0) + (h : s.localDepth M v < s'.localDepth M v) : + max (s.labelDepth U M K v a.role) (s.labelDepth U M K v b.role) + 1 ≤ + s'.labelDepth U M K v (a.join b).role := by + by_cases he : a.role = .collector + · have e := depth_freeze (s := s) (U := U) (M := M) (K := K) v b.role + simp only [Tag.join, he, ↓reduceIte, labelDepth] at * + omega + · simp only [Tag.join, ite_eq_right he, labelDepth] + rw [show priority U a.role = 0 by simp [priority, he, ha]] + omega + +omit [Field F] in +open scoped Classical in +theorem depth_hop (v w : V) {n : ℕ} (hn : n < U) (hv : s.visits v ≤ K) : + s.labelDepth U M K v (.active n) + 1 ≤ s'.labelDepth U M K w (.active (n + 1)) := by + simp only [labelDepth, priority, reduceCtorEq, ↓reduceIte, Role.clock, + min_eq_right hn.le, min_eq_right (show n + 1 ≤ U by omega), add_mul, one_mul, localDepth] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- +# Local station labels + +A label depends only on two local exterior strings, a list of selector +values and residual states, and the two sphere indices. Global station +and wire names occur in the layout and never in this interface. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open scoped Classical in +/-- Indexes the symbol by the coordinates of `ℕ ⊕ Wedge t`. -/ +abbrev Symbol (t : ℕ) := ℕ ⊕ Wedge t + +open scoped Classical in +/-- The indexing data represented by `List Bool → List Bool → List (Symbol t) → Wedge r → Wedge +t → F`. -/ +abbrev Label (F : Type) (r t : ℕ) := + List Bool → List Bool → List (Symbol t) → Wedge r → Wedge t → F + +variable {F T V X : Type} {r t : ℕ} (key : V → X → ℕ) + +open scoped Classical in +/-- In the case `[], .inl v, x`, this construction gives `.inl (key v x)`. -/ +def lookup : (ns : List ℕ) → V ⊕ ℕ → Stack X t ns → Symbol t + | [], .inl v, x => .inl (key v x) + | [], .inr _, _ => .inl 0 + | _ :: ns, j, x => + if j = .inr ns.length then .inr x.2.val else lookup ns j x.1 + +open scoped Classical in +theorem lookup_previous {ns : List ℕ} {m : ℕ} (j : V ⊕ ℕ) (h : available ns.length j) + (x : Stack X t (m :: ns)) : lookup key (m :: ns) j x = lookup key ns j x.1 := by + have hj : j ≠ .inr ns.length := by rintro rfl; exact Nat.lt_irrefl _ h + simp only [lookup, ite_eq_right hj] + +open scoped Classical in +theorem lookup_fresh {ns : List ℕ} {m : ℕ} (x : Stack X t (m :: ns)) : + lookup key (m :: ns) (.inr ns.length) x = .inr x.2.val := by simp [lookup] + +open scoped Classical in +/-- The describes of type `Prop` for the given inputs. -/ +def Describes (ext : Option T → X → List Bool × List Bool) (ns : List ℕ) + (S : Station F r t (Tag V T) (Stack X t ns)) (L : Label F r t) (reads : List (V ⊕ ℕ)) : Prop := + reads.toFinset = S.label.reads ∧ ∀ x a b, + S.table x a b = L (ext S.label.name (base ns x)).1 (ext S.label.name (base ns x)).2 + (reads.map fun j => lookup key ns j x) a.val b.val + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- +# A finite menu of station tables + +One operation fuses two labels, leaves a residue, or moves an +insertion. Its description includes input energies and the number +of ordinary keys to read for the first operand. No field elements +or absolute cell, edge, or wire names are needed by the operation. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Finset +variable {F : Type} [Field F] {r t N k : ℕ} + +open scoped Classical in +/-- Indexes the energies by the coordinates of `Fin (N + 1) × Fin (N + 1)`. -/ +abbrev Energies (N : ℕ) := Fin (N + 1) × Fin (N + 1) + +open scoped Classical in +/-- Evaluates `if rs = [.inr b] then 1 else 0` at the input `_ _ rs _ b`. -/ +def leaveLabel : Label F r t := + fun _ _ rs _ b => if rs = [.inr b] then 1 else 0 + +open scoped Classical in +/-- The move label of type `Label F r t` for the given inputs. -/ +def moveLabel (u : Label F r t) (a : ℕ) : Label F r t := + fun x y rs c _ => match rs with + | .inr b :: l => ∑ v : Level r a, u x y l v.val b * Motion.lowering F r (Finsupp.single v.val 1) c + | _ => 0 + +open scoped Classical in +/-- The merge label of type `Label F r t` for the given inputs. -/ +def mergeLabel (u v : Label F r t) (a b : Energies N) (n : ℕ) : Label F r t := + fun x y rs c d => + ∑ i : (Level r a.1 × Level t a.2) × (Level r b.1 × Level t b.2), + u x y (rs.take n) i.1.1.val i.1.2.val * v [] [] (rs.drop n) i.2.1.val i.2.2.val * + fusion F i.1.1.val.val i.2.1.val.val c.val * fusion F i.1.2.val.val i.2.2.val.val d.val + +open scoped Classical in +/-- Indexes the op by the coordinates of `↥A ⊕ Unit ⊕ (↥A × Fin (N + 1)) ⊕ (↥A × ↥A × Energies N +× Energies N × Fin (2 ^ k + 1))`. -/ +abbrev Op (A : Finset (Label F r t)) (N k : ℕ) := + ↥A ⊕ Unit ⊕ (↥A × Fin (N + 1)) ⊕ (↥A × ↥A × Energies N × Energies N × Fin (2 ^ k + 1)) + +open scoped Classical in +/-- In the case `.inl a`, this construction gives `a.val`. -/ +def interpret {A : Finset (Label F r t)} : Op A N k → Label F r t + | .inl a => a.val + | .inr (.inl _) => leaveLabel + | .inr (.inr (.inl (L, n))) => moveLabel L.val n.val + | .inr (.inr (.inr (L, W, a, b, j))) => mergeLabel L.val W.val a b j.val + +open scoped Classical in +/-- In the case `0`, this construction gives `A`. -/ +def menu (A : Finset (Label F r t)) (N : ℕ) : ℕ → Finset (Label F r t) + | 0 => A + | k + 1 => (univ : Finset (Op (menu A N k) N k)).image interpret + +variable {A : Finset (Label F r t)} {L W : Label F r t} + +open scoped Classical in +theorem menu_mono : Monotone (menu A N) := by + refine monotone_nat_of_le_succ fun k a ha => ?_ + exact mem_image_of_mem interpret (mem_univ (.inl ⟨a, ha⟩ : Op (menu A N k) N k)) + +open scoped Classical in +theorem menu_leave : leaveLabel ∈ menu A N (k + 1) := + mem_image_of_mem interpret (mem_univ (.inr (.inl ()) : Op (menu A N k) N k)) + +open scoped Classical in +theorem menu_move (h : L ∈ menu A N k) {a : ℕ} (ha : a ≤ N) : moveLabel L a ∈ menu A N (k + 1) := + mem_image_of_mem interpret + (mem_univ (.inr (.inr (.inl (⟨L, h⟩, ⟨a, by omega⟩))) : Op (menu A N k) N k)) + +open scoped Classical in +theorem menu_merge (h : L ∈ menu A N k) (g : W ∈ menu A N k) (a b : Energies N) + {n : ℕ} (hn : n ≤ 2 ^ k) : mergeLabel L W a b n ∈ menu A N (k + 1) := + mem_image_of_mem interpret + (mem_univ (.inr (.inr (.inr (⟨L, h⟩, ⟨W, g⟩, a, b, ⟨n, by omega⟩))) : Op (menu A N k) N k)) + +open scoped Classical in +/-- In the case `0`, this construction gives `1`. -/ +def menuPower : ℕ → ℕ + | 0 => 1 + | k + 1 => 2 * menuPower k + k + 7 + +open scoped Classical in +theorem card_menu (A : Finset (Label F r t)) (N k : ℕ) : + (menu A N k).card ≤ (A.card + N + 2) ^ (menuPower k) := by + let a := A.card + N + 2 + have ha : 2 ≤ a := by unfold a; omega + have hn : N + 1 ≤ a := by unfold a; omega + have hap : 0 < a := by omega + change _ ≤ a ^ _ + induction k with + | zero => simp [menu, menuPower, a]; omega + | succ k ih => + let b := a ^ menuPower k + let u := b * b * a ^ 4 * a ^ (k + 1) + have hb : 1 ≤ b := pow_pos hap _ + have hj : 2 ^ k + 1 ≤ a ^ (k + 1) := by + have h := Nat.pow_le_pow_left ha k + have := pow_pos hap k + rw [pow_succ] + have := Nat.mul_le_mul_left (a ^ k) ha + omega + have hba : b * a ≤ u := by + have hh : b * a ≤ (b * b) * a ^ 4 := Nat.mul_le_mul (Nat.le_mul_of_pos_right _ hb) + (by simpa using Nat.pow_le_pow_right hap (show 1 ≤ 4 by decide)) + exact hh.trans (Nat.le_mul_of_pos_right _ (pow_pos hap _)) + have hb' : b ≤ b * a := Nat.le_mul_of_pos_right _ hap + have h2 : 4 ≤ a ^ 2 := Nat.pow_le_pow_left ha 2 + calc + _ ≤ Fintype.card (Op (menu A N k) N k) := card_image_le + _ ≤ b + (1 + (b * a + u)) := by + simp only [Op, Energies, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + Fintype.card_unit, Fintype.card_coe] + rw [show u = b * (b * ((a * a) * ((a * a) * a ^ (k + 1)))) by unfold u; ring] + gcongr + _ ≤ u * 4 := by omega + _ ≤ u * a ^ 2 := Nat.mul_le_mul_left _ h2 + _ = _ := by unfold u b; rw [menuPower]; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- # Descriptions of the elementary station operations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Finset +variable {F T V X : Type} {r t N k : ℕ} + +open scoped Classical in +/-- The condition `∃ L ∈ A, ∃ q : List (V ⊕ ℕ), q.length ≤ n ∧ Describes key ext ns u L q` on +the specified data. -/ +def Tabulated (key : V → X → ℕ) (ext : Option T → X → List Bool × List Bool) (ns : List ℕ) + (u : Station F r t (Tag V T) (Stack X t ns)) (A : Finset (Label F r t)) (n : ℕ) : Prop := + ∃ L ∈ A, ∃ q : List (V ⊕ ℕ), q.length ≤ n ∧ Describes key ext ns u L q + +variable [Field F] {key : V → X → ℕ} {ext : Option T → X → List Bool × List Bool} + {A : Finset (Label F r t)} {ns : List ℕ} + {u v : Station F r t (Tag V T) (Stack X t ns)} + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- +# An intrinsic record of a region + +Station and seam identifiers are local. Ordinary keys and named +exterior interfaces may be renamed. No part of a station table +outside its label occurs in this record. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset +variable {F T V E X J L K N : Type} {r t : ℕ} + +open scoped Classical in +/-- The data for the entry construction, including `pos`, `a`, `b`, `role`, `name`. -/ +structure Entry (F : Type) (r t : ℕ) (K N : Type) where + /-- The `Entry` field of type `F`. -/ + pos : F + /-- The left component. -/ + a : ℕ + /-- The right component. -/ + b : ℕ + /-- The `Entry` component of type `Role`. -/ + role : Role + /-- The name assigned to each index of type `Option N`. -/ + name : Option N + /-- The `Entry` component of type `List K`. -/ + reads : List K + /-- The label at each coordinate of type `Stage.Label F r t`. -/ + label : Stage.Label F r t + +open scoped Classical in +/-- The data for the record construction, including `rows`, `ports`, `level`, `footprint`. -/ +structure Record (F : Type) (r t : ℕ) (J L K N : Type) where + /-- The indexed rows of type `J → List (Entry F r t K N)`. -/ + rows : J → List (Entry F r t K N) + /-- The `Record` component of type `J → List (L × F)`. -/ + ports : J → List (L × F) + /-- The level at each coordinate of type `L → ℕ`. -/ + level : L → ℕ + /-- The `Record` component of type `J → Finset K`. -/ + footprint : J → Finset K + +open scoped Classical in +/-- The data for the reference construction, including `vertex`, `edge`, `name`, `key`, `ext`. -/ +structure Reference (J L N V E T X : Type) where + /-- The placement of the vertices carried by `Reference`, with type `J ↪ V`. -/ + vertex : J ↪ V + /-- The indexed edge data carried by `Reference`, with type `L ↪ E`. -/ + edge : L ↪ E + /-- The name assigned to each index of type `T → N`. -/ + name : T → N + /-- The `Reference` component of type `V → X → ℕ`. -/ + key : V → X → ℕ + /-- The `Reference` component of type `Option T → X → List Bool × List Bool`. -/ + ext : Option T → X → List Bool × List Bool + empty : ∀ x, ext none x = ([], []) + +open scoped Classical in +/-- The data for the represents construction, including `pos`, `left`, `right`, `role`, `name`. -/ +structure Represents (R : Reference J L N V E T X) (β : V ⊕ ℕ → K) + (ns : List ℕ) (u : Station F r t (Tag V T) (Stack X t ns)) (a : Entry F r t K N) : Prop where + pos : u.pos = a.pos + left : u.a = a.a + right : u.b = a.b + role : u.label.role = a.role + name : u.label.name.map R.name = a.name + named : u.label.role ≠ .collector → u.label.name = none + known : ∀ j ∈ u.label.reads, available ns.length j + label : ∃ q : List (V ⊕ ℕ), q.map β = a.reads ∧ Stage.Describes R.key R.ext ns u a.label q + +open scoped Classical in +/-- The data for the matches construction, including `rows`, `ports`, `level`, `footprint`, +`known`. -/ +structure Matches (R : Reference J L N V E T X) (β : V ⊕ ℕ → K) + (s : Stage F r t T V E X) (a : Record F r t J L K N) : Prop where + rows : ∀ i, List.Forall₂ (Represents R β s.hidden) (s.scene.cell (R.vertex i)).stations (a.rows i) + ports : ∀ i, (s.scene.cell (R.vertex i)).ports = (a.ports i).map (Prod.map R.edge id) + level : ∀ j, s.scene.level (R.edge j) = a.level j + footprint : ∀ i, (s.footprint (R.vertex i)).image β = a.footprint i + known : ∀ i j, j ∈ s.footprint (R.vertex i) → available s.hidden.length j + +open scoped Classical in +/-- Unrelated cells keep their tables and ignore newly allocated wires. +The fresh keys and their levels are listed in order of creation. -/ +structure Outside (B : Set V) (A : Set E) (key : V → X → ℕ) + (s q : Stage F r t T V E X) (β β' : V ⊕ ℕ → K) (fresh : List (K × ℕ)) : Prop where + history : q.hidden = (fresh.map Prod.snd).reverse ++ s.hidden + old : ∀ j, available s.hidden.length j → β' j = β j + new : ∀ i : Fin fresh.length, β' (.inr (s.hidden.length + i.val)) = (fresh.get i).1 + level : ∀ j, j ∉ A → q.scene.level j = s.scene.level j + footprint : ∀ i, i ∉ B → q.footprint i = s.footprint i + project : ∃ π : Stack X t q.hidden → Stack X t s.hidden, + (∀ x, Stage.base s.hidden (π x) = Stage.base q.hidden x) ∧ + (∀ j, available s.hidden.length j → ∀ x, + Stage.lookup key s.hidden j (π x) = Stage.lookup key q.hidden j x) ∧ + ∀ i, i ∉ B → q.scene.cell i = (s.scene.cell i).pull π id + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Effects of local edits outside the affected cells -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Function +variable {F T V E X J L K N : Type} {r t P : ℕ} +variable {A : Set E} {B : Set V} {key : V → X → ℕ} + {β : V ⊕ ℕ → K} {s : Stage F r t T V E X} + +open scoped Classical in +theorem Outside.refl : Outside B A key s s β β [] := + ⟨rfl, fun _ _ => rfl, fun i => i.elim0, fun _ _ => rfl, fun _ _ => rfl, + id, fun _ => rfl, fun _ _ _ => rfl, fun _ _ => (Cell.pull_id _).symm⟩ + +open scoped Classical in +theorem Outside.edit (v : V) (hv : v ∈ B) (c : s.Ct) (n : ℕ) : + Outside B A key s {s.put v c with expired := n} β β [] := by + refine ⟨rfl, fun _ _ => rfl, fun i => i.elim0, fun _ _ => rfl, fun _ _ => rfl, + id, fun _ => rfl, fun _ _ _ => rfl, fun i hi => ?_⟩ + change update s.scene.cell v c i = (s.scene.cell i).pull id id + rw [update_of_ne (show i ≠ v from fun e => hi (e ▸ hv)), Cell.pull_id] + +open scoped Classical in +theorem Outside.put (v : V) (hv : v ∈ B) (c : s.Ct) : + Outside B A key s (s.put v c) β β [] := Outside.edit v hv c s.expired + +open scoped Classical in +/-- The value specified by `update β (.inr n) k`. -/ +def allocate (β : V ⊕ ℕ → K) (n : ℕ) (k : K) := update β (.inr n) k + +open scoped Classical in +theorem old_allocate (n : ℕ) (k : K) (j : V ⊕ ℕ) (h : available n j) : + allocate β n k j = β j := + update_of_ne (show j ≠ .inr n from fun e => by subst j; exact Nat.lt_irrefl _ h) _ _ + +open scoped Classical in +theorem Outside.advance [Field F] {u : s.St} (a : Passage P u) {v w : V} {j : E} + (hv : v ∈ B) (hw : w ∈ B) (hj : j ∈ A) (L R : s.Sock) (S : Lower F r) + (b : a.Branch) (k : K) : + Outside B A key s (s.advance a v w j L R S b) β (allocate β s.hidden.length k) [(k, u.b)] := by + refine ⟨rfl, old_allocate _ _, ?_, ?_, ?_, Prod.fst, fun _ => rfl, + fun j h x => (Stage.lookup_previous key j h x).symm, ?_⟩ + · intro i + simp [allocate] + · intro e he + exact update_of_ne (show e ≠ j from fun h => he (h ▸ hj)) _ _ + · intro i hi + have e : ¬(i = v ∨ i = w) := by grind + exact ite_eq_right e + · intro i hi + have e : i ≠ v ∧ i ≠ w := by grind + simp only [Stage.advance, Scene.crossed, update_of_ne e.1, update_of_ne e.2] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# Composition of local rewrites + +Beyond the edited vertices and seam labels, the only effect of a +rewrite is to project away its newly allocated ordinary keys. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset +variable {F T V E X J L K N : Type} {r t : ℕ} {B B' : Set V} {A A' : Set E} + {s p q : Stage F r t T V E X} {key : V → X → ℕ} + {β β' β'' : V ⊕ ℕ → K} {f g : List (K × ℕ)} + +open scoped Classical in +theorem Outside.mono (h : Outside B A key s p β β' f) (hb : B ⊆ B') (ha : A ⊆ A') : + Outside B' A' key s p β β' f := by + obtain ⟨π, h₁, h₂, h₃⟩ := h.project + exact ⟨h.history, h.old, h.new, fun i hi => h.level i (fun hh => hi (ha hh)), + fun i hi => h.footprint i (fun hh => hi (hb hh)), + π, h₁, h₂, fun i hi => h₃ i (fun hh => hi (hb hh))⟩ + +open scoped Classical in +theorem Outside.length (h : Outside B A key s p β β' f) : + p.hidden.length = s.hidden.length + f.length := by simp [h.history, add_comm] + +open scoped Classical in +theorem Outside.known (h : Outside B A key s p β β' f) (i : V ⊕ ℕ) + (hi : available s.hidden.length i) : available p.hidden.length i := by + cases i <;> simp only [available, h.length] at *; omega + +open scoped Classical in +private theorem pull_trans {Y Z : Type} (c : Cell F r t T E X) (π : Y → X) (ρ : Z → Y) : + (c.pull π id).pull ρ id = c.pull (π ∘ ρ) id := by + simp only [Cell.pull, List.map_map] + rfl + +open scoped Classical in +theorem Outside.trans (h : Outside B A key s p β β' f) (h' : Outside B A key p q β' β'' g) : + Outside B A key s q β β'' (f ++ g) := by + obtain ⟨π, hb, hk, hv⟩ := h.project + obtain ⟨ρ, hb', hk', hv'⟩ := h'.project + refine ⟨by simp [h.history, h'.history], ?_, ?_, ?_, ?_, π ∘ ρ, ?_, ?_, ?_⟩ + · intro j hj + exact (h'.old j (h.known j hj)).trans (h.old j hj) + · intro i + have hi := i.isLt + simp only [List.length_append] at hi + by_cases hi' : i.val < f.length + · have hv : available p.hidden.length (.inr (s.hidden.length + i.val) : V ⊕ ℕ) := by + simp only [available, h.length]; omega + rw [h'.old _ hv, h.new ⟨i.val, hi'⟩] + simp only [List.get_eq_getElem, List.getElem_append_left hi'] + · have hi'' : i.val - f.length < g.length := by omega + rw [show s.hidden.length + i.val = p.hidden.length + + (i.val - f.length) by rw [h.length]; omega, + h'.new ⟨_, hi''⟩] + simp only [List.get_eq_getElem, List.getElem_append_right (Nat.le_of_not_gt hi')] + · exact fun i hi => (h'.level i hi).trans (h.level i hi) + · exact fun i hi => (h'.footprint i hi).trans (h.footprint i hi) + · exact fun x => (hb _).trans (hb' x) + · exact fun j hj x => (hk j hj _).trans (hk' j (h.known j hj) x) + · intro i hi + rw [hv' i hi, hv i hi, pull_trans] + +variable {R : Reference J L N V E T X} {a : Record F r t J L K N} + +open scoped Classical in +theorem Represents.project (h : Outside B A R.key s q β β' f) + (π : Stack X t q.hidden → Stack X t s.hidden) + (hb : ∀ x, Stage.base s.hidden (π x) = Stage.base q.hidden x) + (hk : ∀ j, available s.hidden.length j → ∀ x, + Stage.lookup R.key s.hidden j (π x) = Stage.lookup R.key q.hidden j x) + {u : s.St} {v : Entry F r t K N} (e : Represents R β s.hidden u v) : + Represents R β' q.hidden (u.pull π id) v := by + obtain ⟨l, hl, hr, he⟩ := e.label + have valid j (hj : j ∈ l) := e.known j (hr ▸ List.mem_toFinset.mpr hj) + refine ⟨e.pos, e.left, e.right, e.role, e.name, e.named, fun j hj => h.known j (e.known j hj), + l, ?_, hr, fun x a b => ?_⟩ + · rw [← hl] + exact List.map_congr_left fun j hj => h.old j (valid j hj) + · have hmap : l.map (fun j => Stage.lookup R.key s.hidden j (π x)) = + l.map (fun j => Stage.lookup R.key q.hidden j x) := + List.map_congr_left fun j hj => hk j (valid j hj) x + have ht := he (π x) a b + rw [hb, hmap] at ht + exact ht + +open scoped Classical in +/-- A disjoint region keeps its entire record. -/ +theorem Matches.outside (e : Matches R β s a) (h : Outside B A R.key s q β β' f) + (hl : ∀ i, R.vertex i ∉ B) (he : ∀ i, R.edge i ∉ A) : + Matches R β' q a := by + obtain ⟨π, hb, hk, hv⟩ := h.project + refine ⟨fun i => ?_, fun i => ?_, fun i => ?_, fun i => ?_, fun i j hj => ?_⟩ + · rw [hv _ (hl i)] + change List.Forall₂ _ (List.map _ _) _ + rw [List.forall₂_map_left_iff] + exact (e.rows i).imp (fun u v h' => h'.project h π hb hk) + · rw [hv _ (hl i)]; exact e.ports i + · rw [h.level _ (he i), e.level] + · rw [h.footprint _ (hl i), ← e.footprint] + exact image_congr fun j hj => h.old j (e.known i j hj) + · rw [h.footprint _ (hl i)] at hj + exact h.known j (e.known i j hj) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Region records for individual station operations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset Function Stage +variable {F T V E X J L K N : Type} {r t : ℕ} + +open scoped Classical in +/-- Uses `{a with role := Role.collector}` as the representation. -/ +def Entry.freeze (a : Entry F r t K N) := {a with role := Role.collector} + +variable {R : Reference J L N V E T X} {β : V ⊕ ℕ → K} {ns : List ℕ} + {u v : Station F r t (Tag V T) (Stack X t ns)} {x y : Entry F r t K N} + +open scoped Classical in +theorem Represents.freeze (h : Represents R β ns u x) : + Represents R β ns {u with label := {u.label with role := .collector}} x.freeze := + ⟨h.pos, h.left, h.right, rfl, h.name, fun hn => (hn rfl).elim, h.known, h.label⟩ + +variable [Field F] + +open scoped Classical in +/-- Builds `Entry F r t K N where pos` with the specified `pos`, `role`, `name`, `reads`. -/ +def Entry.merge (x y : Entry F r t K N) (j : ℤ × ℤ) : Entry F r t K N where + pos := x.pos + a := (Motion.fusedEnergy x.a y.a j.1).toNat + b := (Motion.fusedEnergy x.b y.b j.2).toNat + role := if x.role = .collector then .collector else y.role + name := x.name + reads := x.reads ++ y.reads + label := mergeLabel (N := x.a + x.b + y.a + y.b) x.label y.label + (⟨x.a, by omega⟩, ⟨x.b, by omega⟩) (⟨y.a, by omega⟩, ⟨y.b, by omega⟩) x.reads.length + +open scoped Classical in +/-- Uses `⟨z, 0, x.b, .residue, none, [k], leaveLabel⟩` as the representation. -/ +def Entry.leaf (x : Entry F r t K N) (k : K) (z : F) : Entry F r t K N := + ⟨z, 0, x.b, .residue, none, [k], leaveLabel⟩ + +open scoped Classical in +/-- The quantity computed by `⟨z, m, 0, .active (x.role.clock + 1), x.name, k :: x.reads, +moveLabel x.label x.a⟩`. -/ +def Entry.taken (x : Entry F r t K N) (k : K) (z : F) (m : ℕ) : Entry F r t K N := + ⟨z, m, 0, .active (x.role.clock + 1), x.name, k :: x.reads, moveLabel x.label x.a⟩ + +open scoped Classical in +theorem Represents.merge (h : Represents R β ns u x) (g : Represents R β ns v y) + (hn : v.label.role ≠ .collector) (j : ℤ × ℤ) : + Represents R β ns (mergeAt u v (u.label.join v.label) j) (x.merge y j) := by + obtain ⟨q, hq, hr, hf⟩ := h.label + obtain ⟨s, hs, ht, he⟩ := g.label + have name : (u.label.join v.label).name = u.label.name := by + unfold Tag.join + split_ifs with hc + · rfl + · exact (g.named hn).trans (h.named hc).symm + have reads : (u.label.join v.label).reads = u.label.reads ∪ v.label.reads := by + unfold Tag.join; split_ifs <;> rfl + refine ⟨h.pos, ?_, ?_, ?_, ?_, ?_, ?_, q++s, by simp [Entry.merge, hq, hs], ?_, ?_⟩ + · simp [mergeAt, Surface.merge, Entry.merge, h.left, g.left] + · simp [mergeAt, Surface.merge, Entry.merge, h.right, g.right] + · by_cases hc : u.label.role = .collector <;> simp [mergeAt, Surface.merge, Entry.merge, Tag.join, + ← h.role, ← g.role, hc] + · exact (congrArg (Option.map R.name) name).trans h.name + · intro hc + exact name.trans (h.named fun hu => hc (by simp [mergeAt, Surface.merge, Tag.join, hu])) + · intro i hi + change i ∈ (u.label.join v.label).reads at hi + rw [reads, mem_union] at hi + exact hi.elim (h.known i) (g.known i) + · simp [mergeAt, Surface.merge, reads, hr, ht] + · intro z a b + have hlen : x.reads.length = q.length := by rw [← hq, List.length_map] + simp only [Entry.merge, mergeAt, Surface.merge, jointWeight, name, hf, he, g.named hn, R.empty, + mergeLabel, hlen, List.map_append, List.take_append, List.drop_append, List.length_map, + Nat.sub_self, + List.take_zero, List.drop_zero, List.append_nil] + simp only [← List.map_take, ← List.map_drop, List.take_length, List.drop_length, List.map_nil, + List.nil_append] + obtain ⟨hx, hy, hx', hy'⟩ := And.intro h.left (And.intro h.right (And.intro g.left g.right)) + cases x; cases y; dsimp only at hx hy hx' hy'; subst_vars; rfl + +open scoped Classical in +theorem Represents.leaf (h : Represents R β ns u x) (k : K) (z : F) : + Represents R (allocate β ns.length k) (u.b::ns) + (residue u (Tag.leave ns.length) z) (x.leaf k z) := by + refine ⟨rfl, rfl, h.right, rfl, rfl, fun _ => rfl, ?_, [.inr ns.length], ?_, ?_, ?_⟩ + · simp [residue, Tag.leave, available] + · simp [allocate, Entry.leaf] + · simp [residue, Tag.leave] + · intro x i j + simp only [Entry.leaf, residue, leaveLabel, List.map_cons, List.map_nil, lookup_fresh, + List.cons.injEq, + Sum.inr.injEq, and_true] + simp only [show x.2.val = j.val ↔ x.2 = j from Subtype.ext_iff.symm] + congr! + +open scoped Classical in +theorem Represents.taken (h : Represents R β ns u x) (hn : u.label.role ≠ .collector) + (k : K) (z : F) (m : ℕ) : + Represents R (allocate β ns.length k) (u.b::ns) + (transfer u (u.label.take ns.length) z (Motion.lowering F r) m) (x.taken k z m) := by + obtain ⟨q, hq, hr, he⟩ := h.label + have avail j (hj : j ∈ q) := h.known j (hr ▸ List.mem_toFinset.mpr hj) + refine ⟨rfl, rfl, rfl, ?_, h.name, fun _ => h.named hn, ?_, .inr ns.length :: q, ?_, ?_, ?_⟩ + · simp [transfer, Tag.take, h.role, Entry.taken] + · intro j hj + rcases mem_insert.mp hj with rfl|hj + · exact Nat.lt_succ_self _ + · have := h.known j hj + cases j <;> simp only [available, List.length_cons] at *; omega + · have ee : q.map (allocate β ns.length k) = q.map β := + List.map_congr_left fun j hj => old_allocate _ k j (avail j hj) + simp only [Entry.taken, List.map_cons, ee, hq] + rw [allocate, update_self] + · simp [transfer, Tag.take, hr] + · intro w i j + have ee : q.map (fun j => lookup R.key (u.b::ns) j w) = + q.map (fun j => lookup R.key ns j w.1) := + List.map_congr_left fun j hj => lookup_previous _ _ (avail j hj) _ + simp only [Entry.taken, transfer, Tag.take, base, List.map_cons, lookup_fresh, moveLabel, ee, + he] + rw [← h.left] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Updating a region without using global identifiers -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset Function +variable {F T V E X J L K N : Type} {r t P : ℕ} + {R : Reference J L N V E T X} {β : V ⊕ ℕ → K} + {s : Stage F r t T V E X} {a : Record F r t J L K N} + +open scoped Classical in +/-- Uses `{a with rows := update a.rows i rows}` as the representation. -/ +def Record.edit (a : Record F r t J L K N) (i : J) (rows : List (Entry F r t K N)) := + {a with rows := update a.rows i rows} + +open scoped Classical in +theorem Matches.edit (h : Matches R β s a) (i : J) (c : s.Ct) (rows : List (Entry F r t K N)) + (hc : c.ports = (s.scene.cell (R.vertex i)).ports) + (hr : List.Forall₂ (Represents R β s.hidden) c.stations rows) (m : ℕ) : + Matches R β {s.put (R.vertex i) c with expired := m} (a.edit i rows) := by + refine ⟨fun j => ?_, fun j => ?_, h.level, h.footprint, h.known⟩ + · change List.Forall₂ (Represents R β s.hidden) + (update s.scene.cell (R.vertex i) c (R.vertex j)).stations (update a.rows i rows j) + by_cases he : j = i + · subst j; rw [update_self, update_self]; exact hr + · rw [update_of_ne he, update_of_ne (R.vertex.injective.ne he)]; exact h.rows j + · change (update s.scene.cell (R.vertex i) c (R.vertex j)).ports = _ + by_cases he : j = i + · subst j; rw [update_self, hc]; exact h.ports i + · rw [update_of_ne (R.vertex.injective.ne he)]; exact h.ports j + +variable [Field F] + +open scoped Classical in +/-- Builds `Record F r t J L K N where rows` with the specified `rows`, `ports`, `level`, +`footprint`. -/ +def Record.cross (a : Record F r t J L K N) (i j : J) (e : L) (x : Entry F r t K N) + (k : K) (z y : F) (h m : ℕ) : Record F r t J L K N where + rows := update (update a.rows i (x.leaf k z :: (a.rows i).tail)) j (x.taken k y m :: a.rows j) + ports := a.ports + level := update a.level e h + footprint b := + if b = i ∨ b = j then insert k (a.footprint b ∪ x.reads.toFinset) else a.footprint b + +open scoped Classical in +theorem Matches.advance (h : Matches R β s a) {u : s.St} (p : Passage P u) + (i j : J) (e : L) (l d : s.Sock) (v : p.Branch) (x : Entry F r t K N) (k : K) + (hi : s.scene.cell (R.vertex i) = (l.plug (R.edge e) p.z).insert u) + (hj : s.scene.cell (R.vertex j) = d.plug (R.edge e) p.y) + (hn : i ≠ j) (hx : a.rows i = x :: (a.rows i).tail) (hc : u.label.role ≠ .collector) : + Matches R (allocate β s.hidden.length k) + (s.advance p (R.vertex i) (R.vertex j) (R.edge e) l d (Motion.lowering F r) v) + (a.cross i j e x k v.2.1.val (p.root v.2.2.2) v.height v.2.2.1.val) := by + let q := s.advance p (R.vertex i) (R.vertex j) (R.edge e) l d (Motion.lowering F r) v + let γ := allocate β s.hidden.length k + have ext : Outside Set.univ Set.univ R.key s q β γ [(k, u.b)] := + Outside.advance p (by simp) (by simp) (by simp) l d _ v k + have hu := h.rows i + rw [hi, hx] at hu + obtain ⟨hu, ht⟩ := List.forall₂_cons.mp hu + have transport (m : List s.St) (n : List (Entry F r t K N)) + (hm : List.Forall₂ (Represents R β s.hidden) m n) : + List.Forall₂ (Represents R γ (u.b::s.hidden)) (m.map (Station.pull · Prod.fst id)) n := by + rw [List.forall₂_map_left_iff] + exact hm.imp fun _ _ e => e.project ext Prod.fst (fun _ => rfl) + (fun j hh x => (Stage.lookup_previous _ _ hh x).symm) + have near := R.vertex.injective.ne hn + refine ⟨fun b => ?_, fun b => ?_, fun j => ?_, fun b => ?_, fun b y hy => ?_⟩ + · simp only [Stage.advance, Scene.crossed, Record.cross] + by_cases he : b = i + · subst b + rw [update_of_ne hn, update_of_ne near, update_self, update_self] + exact .cons (hu.leaf k _) (transport _ _ ht) + by_cases he' : b = j + · subst b + rw [update_self, update_self] + exact .cons (hu.taken hc k _ _) (transport _ _ (hj ▸ h.rows j)) + rw [update_of_ne he', update_of_ne he, update_of_ne (R.vertex.injective.ne he'), + update_of_ne (R.vertex.injective.ne he)] + exact transport _ _ (h.rows b) + · by_cases he : b = j + · subst b + simp only [Stage.advance, Scene.crossed, update_self, Passage.right, Cell.insert, Cell.pull, + Record.cross, ← hj] + exact h.ports j + by_cases he' : b = i + · subst b + have := h.ports i + rw [hi] at this + simp only [Stage.advance, Scene.crossed, update_of_ne near, update_self, Passage.left, + Cell.insert, Cell.pull, + Record.cross] + exact this + simp only [Stage.advance, Scene.crossed, update_of_ne (R.vertex.injective.ne he), + update_of_ne (R.vertex.injective.ne he'), Cell.pull, Record.cross] + exact h.ports b + · change update s.scene.level (R.edge e) v.height (R.edge j) = update a.level e v.height j + by_cases ha : j = e + · subst j; rw [update_self, update_self] + · rw [update_of_ne ha, update_of_ne (R.edge.injective.ne ha), h.level] + · have old : (s.footprint (R.vertex b)).image γ = a.footprint b := by + rw [← h.footprint]; exact image_congr fun i hi => ext.old i (h.known b i hi) + have reads : u.label.reads.image γ = x.reads.toFinset := by + obtain ⟨l, hl, hr, _⟩ := hu.label + rw [show u.label.reads.image γ = u.label.reads.image β from + image_congr fun i hi => ext.old i (hu.known i hi), ← hr, ← hl] + ext z + simp + change (q.footprint (R.vertex b)).image γ = _ + simp only [q, Stage.advance, Record.cross, R.vertex.injective.eq_iff] + split_ifs + · rw [image_insert, image_union, old, reads, show γ (.inr s.hidden.length) + = k from update_self ..] + · exact old + · simp only [Stage.advance] at hy + split_ifs at hy + · rcases mem_insert.mp hy with rfl|hy + · exact Nat.lt_succ_self _ + · exact ext.known _ ((mem_union.mp hy).elim (h.known b _) (hu.known _)) + · exact ext.known _ (h.known b y hy) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +section +/- +# Locality of keys + +A crossing always leaves a fresh key at both endpoints, and +footprints never shrink. Thus any operation preserving footprints +outside a region can only move previously available keys within it. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +open Finset Stage + +variable {F T V E X K : Type} [Field F] {r t P g H U : ℕ} + {s q : Stage F r t T V E X} {keys : V → X → X → Prop} {ext : T → X → X → Prop} + +namespace Stage + +open scoped Classical in +theorem Step.footprint_le (h : Step P g H U s q) (v : V) : + s.footprint v ⊆ q.footprint v := by + cases h with + | perm | expire | merge => exact Subset.rfl + | cross => exact carry_mono v + +open scoped Classical in +theorem Reach.footprint_le (h : s.Reach P g H U q) (v : V) : + s.footprint v ⊆ q.footprint v := by + induction h with + | refl => exact Subset.rfl + | tail _ h ih => exact ih.trans (h.footprint_le v) + +open scoped Classical in +theorem Reach.length_le (h : s.Reach P g H U q) : s.hidden.length ≤ q.hidden.length := by + induction h with + | refl => exact le_rfl + | tail _ h ih => cases h <;> first | exact ih | exact ih.trans (Nat.le_succ _) + +open scoped Classical in +private theorem Step.from_region (h : Step P g H U s q) (ctrl : s.Controls keys ext) + (B : Set V) (n : ℕ) (hn : n ≤ s.hidden.length) + (safe : ∀ v ∉ B, ∀ j ∈ q.footprint v, available n j) + (j : V ⊕ ℕ) (old : available n j) (v : V) (hv : v ∈ B) (hj : j ∈ q.footprint v) : + ∃ w ∈ B, j ∈ s.footprint w := by + cases h with + | perm | expire | merge => exact ⟨v, hv, hj⟩ + | cross x y k l u a b c i m hx => + have fresh : ¬ available n (Sum.inr s.hidden.length : V ⊕ ℕ) := Nat.not_lt.mpr hn + have region : x ∈ B := by + by_contra hh + exact fresh (safe x hh _ (by simp [advance])) + simp only [advance] at hj + split_ifs at hj + · rcases mem_insert.mp hj with rfl | hj + · exact (fresh old).elim + rcases mem_union.mp hj with hj | hj + · exact ⟨v, hv, hj⟩ + · exact ⟨x, region, (ctrl x a (by rw [hx]; exact List.mem_cons_self)).within hj⟩ + · exact ⟨v, hv, hj⟩ + +open scoped Classical in +theorem Reach.from_region (h : s.Reach P g H U q) (ctrl : s.Controls keys ext) (B : Set V) + (safe : ∀ v ∉ B, ∀ j ∈ q.footprint v, available s.hidden.length j) + (j : V ⊕ ℕ) (old : available s.hidden.length j) (v : V) (hv : v ∈ B) + (hj : j ∈ q.footprint v) : ∃ w ∈ B, j ∈ s.footprint w := by + induction h generalizing v with + | refl => exact ⟨v, hv, hj⟩ + | tail h step ih => + obtain ⟨w, hw, hj⟩ := + step.from_region (Reach.controls h ctrl) B _ (Reach.length_le h) safe j old v hv hj + exact ih (fun v hv j hj => safe v hv j (step.footprint_le _ hj)) w hw hj + +end Stage + +namespace Local +variable {B : Set V} {A : Set E} {key : V → X → ℕ} {β γ : V ⊕ ℕ → K} {f : List (K × ℕ)} + +open scoped Classical in +theorem Outside.origin (h : Outside B A key s q β γ f) (reach : s.Reach P g H U q) + (ctrl : s.Controls keys ext) (valid : ∀ v j, j ∈ s.footprint v → available s.hidden.length j) + {v : V} {j : V ⊕ ℕ} (hj : j ∈ q.footprint v) : + (∃ w, (v = w ∨ (v ∈ B ∧ w ∈ B)) ∧ j ∈ s.footprint w) ∨ + (v ∈ B ∧ ¬ available s.hidden.length j) := by + by_cases hv : v ∈ B + · by_cases hj' : available s.hidden.length j + · obtain ⟨w, hw, hi⟩ := reach.from_region ctrl B + (fun v hv j hj => valid v j (by rwa [h.footprint v hv] at hj)) j hj' v hv hj + exact .inl ⟨w, .inr ⟨hv, hw⟩, hi⟩ + · exact .inr ⟨hv, hj'⟩ + · exact .inl ⟨v, .inl rfl, by rwa [h.footprint v hv] at hj⟩ + +end Local +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Initial.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Initial.lean new file mode 100644 index 0000000000..c9a192017a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Initial.lean @@ -0,0 +1,959 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Update +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.History +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Ledger +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Reorder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Owners +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Restore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Depth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.Hub +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.View +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Concentration.Kits + +/-! +# The finite alphabet of each ordinary key + +A local catalog translates short key names to selector cardinalities +and residual energies. Updating a region requires only the incoming +catalogs, the new footprint, and the fresh keys of that region. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Finset +variable {F T V E X K N : Type} {r t P g H U M D n Q W : ℕ} + +open scoped Classical in +/-- In the case `.inl j`, this construction gives `.inl (size j)`. -/ +def kind (size : V → ℕ) (ns : List ℕ) : V ⊕ ℕ → ℕ ⊕ ℕ + | .inl j => .inl (size j) + | .inr j => .inr (degree ns (.inr j : V ⊕ ℕ)) + +open scoped Classical in +theorem degree_order (ns : List ℕ) (j : Fin ns.length) : + degree ns (.inr j.val : V ⊕ ℕ) = Layout.Key.order ns j := by + induction ns with + | nil => exact j.elim0 + | cons n ns ih => + induction j using Fin.lastCases with + | last => simp [degree, Layout.Key.order] + | cast i => + simp only [degree, Fin.val_castSucc, List.reverse_cons, Layout.Key.order, Fin.snoc_castSucc] + rw [List.getElem?_append_left (by simp)] + exact ih i + +open scoped Classical in +/-- The indexed operation `(s.footprint v).image (fun j => (β j, kind size s.hidden j))`. -/ +def catalog [DecidableEq K] (size : V → ℕ) (β : V ⊕ ℕ → K) (s : Stage F r t T V E X) (v : V) := + (s.footprint v).image (fun j => (β j, kind size s.hidden j)) + +open scoped Classical in +theorem kind_congr (size : V → ℕ) {ns ms : List ℕ} {j : V ⊕ ℕ} + (h : degree ns j = degree ms j) : kind size ns j = kind size ms j := by + cases j with + | inl => rfl + | inr => exact congrArg Sum.inr h + +namespace Wave +variable [Field F] {key : V → X → ℕ} {s q : Stage F r t T V E X} + {β γ : V ⊕ ℕ → Stamp Q W U} + {C : Fin n → Command F r t T V E X (Stamp Q W U) N P g H U M D key} {a : Index C} + +open scoped Classical in +/-- A fresh key and any preexisting key have different wave numbers. +Inside one region older names cannot collide either. -/ +theorem Origins.catalog (o : Origins C a s q β γ) (sep : Separate C) + {near : V → V → Prop} (color : V → Fin Q) (wave : Fin W) + (old : Clean near s β wave.val) + (room : ∀ v w x, Together C v w → Together C v x → near w x) + (root : Fin n → V) (fresh : ∀ i, (C i).action.Ordered (created color wave (root i)) 0 U) + (size : V → ℕ) (v : V) (j : Stamp Q W U) (w : ℕ ⊕ ℕ) : + (j, w) ∈ Local.catalog size γ q v ↔ j ∈ (q.footprint v).image γ ∧ + ((∃ x, Together C v x ∧ (j, w) ∈ Local.catalog size β s x) ∨ + ∃ i, v ∈ Set.range (C i).ref.vertex ∧ ∃ h, w = .inr h ∧ + (j, h) ∈ (C i).action.fresh (a i)) := by + classical + let possible (k : ℕ ⊕ ℕ) := + (∃ x, Together C v x ∧ (j, k) ∈ Local.catalog size β s x) ∨ + ∃ i, v ∈ Set.range (C i).ref.vertex ∧ ∃ h, k = .inr h ∧ (j, h) ∈ (C i).action.fresh (a i) + have forward (k : ℕ ⊕ ℕ) (hm : (j, k) ∈ Local.catalog size γ q v) : + j ∈ (q.footprint v).image γ ∧ possible k := by + obtain ⟨z, hz, he⟩ := mem_image.mp hm + obtain ⟨he₁, he₂⟩ := Prod.mk.inj he + refine ⟨mem_image.mpr ⟨z, hz, he₁⟩, ?_⟩ + obtain ⟨offset, ho⟩ := o + rcases ho v z hz with ⟨x, hx, hz', hj, hkind⟩|⟨i, hi, l, hl, hk⟩ + · refine .inl ⟨x, hx, mem_image.mpr ⟨z, hz', ?_⟩⟩ + exact Prod.ext (hj.symm.trans he₁) ((kind_congr size hkind).symm.trans he₂) + · refine .inr ⟨i, hi, degree q.hidden z, ?_, ?_⟩ + · rw [← he₂, hl]; rfl + · rw [← he₁, hk] + exact List.get_mem .. + have named (i) (u : ℕ) (hu : (j, u) ∈ (C i).action.fresh (a i)) : + ∃ k : Fin ((C i).action.fresh (a i)).length, + k.val < U ∧ j = created color wave (root i) k.val ∧ + u = (((C i).action.fresh (a i)).get k).2 := by + obtain ⟨k, hk⟩ := List.get_of_mem hu + obtain ⟨hl, he⟩ := fresh i (a i) + simp only [zero_add] at hl he + exact ⟨k, k.isLt.trans_le hl, (congrArg Prod.fst hk).symm.trans (he k), + (congrArg Prod.snd hk).symm⟩ + have mixed {x i l h} (hx : (j, l) ∈ Local.catalog size β s x) + (hi : (j, h) ∈ (C i).action.fresh (a i)) : False := by + obtain ⟨z, hz, he⟩ := mem_image.mp hx + obtain ⟨k, _, he', _⟩ := named i h hi + exact earlier.ne_created color wave (old.old _ _ hz) _ _ ((congrArg Prod.fst he).trans he') + have uniq {k l} (hk : possible k) (hl : possible l) : k = l := by + rcases hk with ⟨x, hx, hm⟩|⟨i, hi, u, rfl, hu⟩ <;> + rcases hl with ⟨y, hy, hn⟩|⟨i', hi', u', rfl, hu'⟩ + · obtain ⟨z, hz, he⟩ := mem_image.mp hm + obtain ⟨w, hw, he'⟩ := mem_image.mp hn + have e := old.distinct _ _ (room v x y hx hy) z hz w hw + ((congrArg Prod.fst he).trans (congrArg Prod.fst he').symm) + subst w + exact (congrArg Prod.snd he).symm.trans (congrArg Prod.snd he') + · exact (mixed hm hu').elim + · exact (mixed hn hu).elim + · have e : i = i' := by + by_contra hn + exact Set.disjoint_left.mp (sep.vertex i i' hn) hi hi' + subst i' + obtain ⟨k, hk, hj, he⟩ := named i u hu + obtain ⟨k', hk', hj', he'⟩ := named i u' hu' + have hu := congrArg (fun p => p.2.val) (Option.some.inj (congrArg Prod.snd (hj.symm.trans + hj'))) + change min k.val U = min k'.val U at hu + rw [min_eq_left hk.le, min_eq_left hk'.le] at hu + rw [he, he', Fin.ext hu] + refine ⟨forward _, fun ⟨h, hp⟩ => ?_⟩ + obtain ⟨z, hz, hj⟩ := mem_image.mp h + have hm : (j, kind size q.hidden z) ∈ Local.catalog size γ q v := + mem_image.mpr ⟨z, hz, Prod.ext hj rfl⟩ + rwa [uniq (forward _ hm).2 hp] at hm + +end Wave +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Distributing updated key catalogs after a wave -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset +variable {F T V E X K N J L : Type} {r t P g H U M D n Q W : ℕ} + +open scoped Classical in +/-- Indexes the catalog by the coordinates of `Finset (K × (ℕ ⊕ ℕ))`. -/ +abbrev Catalog (K : Type) := Finset (K × (ℕ ⊕ ℕ)) + +open scoped Classical in +/-- Only the old catalogs of the region and its own newly allocated +keys are needed to construct any output catalog. -/ +def collect [Fintype J] (seen : Finset K) (old : J → Catalog K) (fresh : List (K × ℕ)) : + Catalog K := + ((univ.biUnion old) ∪ (fresh.toFinset.image (fun k => (k.1, .inr k.2)))).filter + (fun p => p.1 ∈ seen) + +open scoped Classical in +theorem mem_collect [Fintype J] (seen : Finset K) (old : J → Catalog K) (fresh : List (K × ℕ)) + (k : K) (w : ℕ ⊕ ℕ) : + (k, w) ∈ collect seen old fresh ↔ k ∈ seen ∧ + ((∃ j, (k, w) ∈ old j) ∨ ∃ h, w = .inr h ∧ (k, h) ∈ fresh) := by + simp only [collect, mem_filter, mem_union, mem_biUnion, mem_univ, true_and, mem_image, + List.mem_toFinset, Prod.exists, Prod.mk.injEq] + aesop + +namespace Wave +variable [Field F] {key : V → X → ℕ} + {C : Fin n → Command F r t T V E X K N P g H U M D key} {a : Index C} + +open scoped Classical in +theorem Separate.index (h : Separate C) {i j : Fin n} {v : V} + (hi : v ∈ Set.range (C i).ref.vertex) (hj : v ∈ Set.range (C j).ref.vertex) : i = j := by + by_contra hn + exact Set.disjoint_left.mp (h.vertex i j hn) hi hj + +open scoped Classical in +theorem Separate.together (h : Separate C) {i : Fin n} {v w : V} (hi : v ∈ Set.range (C + i).ref.vertex) : + Together C v w ↔ w ∈ Set.range (C i).ref.vertex := by + constructor + · rintro (rfl|⟨j, hj, hj'⟩) + · exact hi + · rwa [h.index hi hj] + · exact fun hw => .inr ⟨i, hi, hw⟩ + +variable (C) [∀ i, Fintype (C i).vertices] + +open scoped Classical in +/-- The carry info of type `V → Catalog K` for the given inputs. -/ +def carryInfo (a : Index C) (q : V → Catalog K) : V → Catalog K := + write (fun i => (C i).ref.vertex) q (fun i v => + collect (((C i).action.result (a i)).footprint v) (q ∘ (C i).ref.vertex) + ((C i).action.fresh (a i))) + +end Wave +namespace Wave + +variable [Field F] {key : V → X → ℕ} {s q : Stage F r t T V E X} + {β γ : V ⊕ ℕ → Stamp Q W U} + {C : Fin n → Command F r t T V E X (Stamp Q W U) N P g H U M D key} + [∀ i, Fintype (C i).vertices] {a : Index C} + +open scoped Classical in +theorem Finish.catalog (h : Finish C s q β γ a) (sep : Separate C) (o : Origins C a s q β γ) + {near : V → V → Prop} (color : V → Fin Q) (wave : Fin W) + (old : Clean near s β wave.val) + (room : ∀ v w x, Together C v w → Together C v x → near w x) + (root : Fin n → V) (new : ∀ i, (C i).action.Ordered (created color wave (root i)) 0 U) + (valid : Known s) (size : V → ℕ) : + Local.catalog size γ q = carryInfo C a (Local.catalog size β s) := by + funext v + unfold carryInfo + by_cases hv : v ∈ vertices C + · obtain ⟨i, z, rfl⟩ := hv + let v := (C i).ref.vertex z + have hv : v ∈ Set.range (C i).ref.vertex := ⟨z, rfl⟩ + rw [write_at _ _ _ sep.vertex i z] + ext ⟨j, w⟩ + rw [mem_collect, o.catalog sep color wave old room root new size] + have e := (h.result i).footprint z + simp only [← e, mem_image, Function.comp_apply] + constructor + · rintro ⟨he, ⟨x, hx, hm⟩|⟨l, hl, hc⟩⟩ + · obtain ⟨x, rfl⟩ := (sep.together hv).mp hx + exact ⟨he, .inl ⟨x, hm⟩⟩ + · have := sep.index hv hl + subst l + exact ⟨he, .inr hc⟩ + · rintro ⟨he, ⟨x, hx⟩|hc⟩ + · exact ⟨he, .inl ⟨_, (sep.together hv).mpr ⟨x, rfl⟩, hx⟩⟩ + · exact ⟨he, .inr ⟨i, hv, hc⟩⟩ + · rw [write_away _ _ _ v hv] + unfold Local.catalog + rw [h.outside.footprint v hv] + apply image_congr + intro j hj + have hj' := valid v j hj + exact Prod.ext (h.outside.old j hj') (kind_congr size (h.outside.degree_old hj')) + +end Wave +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# A station's route through its packet coordinates + +A port needs its side and either an exterior marker or a packet and +species index. Within an ordered run, the next port is predictable +except at the last species of a packet. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Finset Sphere + +open scoped Classical in +/-- Indexes the path step by the coordinates of `Bool × Option (Fin A × Fin r)`. -/ +abbrev PathStep (A r : ℕ) := Bool × Option (Fin A × Fin r) + +open scoped Classical in +/-- Transforms the indexed data by `(p.1, p.2.map fun t => (t.1, finRotate r t.2))`. -/ +def nextStep {A r : ℕ} (p : PathStep A r) : PathStep A r := + (p.1, p.2.map fun t => (t.1, finRotate r t.2)) + +variable {F : Type} {x y : Wire} {h D T r g A : ℕ} {W : ℝ} + (P : Input F x y h D T r g W) + +open scoped Classical in +theorem packet_mem (v : P.diagram.V) (i : Fin (P.diagram.arity v)) {e : P.diagram.E} + (he : P.diagram.wireAt v i = .inr e) : (P.packets.bits e).1 ∈ P.grid.uses v := by + simp only [Grid.uses, mem_filter, mem_univ, true_and] + simpa only [grid, P.packets.left, P.packets.right] using P.diagram.wireAt_incident v i he + +variable (ha : ∀ v, (P.grid.uses v).card ≤ A) (v : P.diagram.V) + +open scoped Classical in +/-- The path of type `PathStep A r` for the given inputs. -/ +def path (i : Fin (P.diagram.arity v)) : PathStep A r := + ((P.diagram.peer v i).1, (P.diagram.wireAt v i).elim (fun _ => none) fun e => + if he : (P.packets.bits e).1 ∈ P.grid.uses v then + some (Fin.castLE (ha v) ((Grid.number P.grid.packetRank (P.grid.uses v)).symm + ⟨(P.packets.bits e).1, he⟩), + (P.packets.bits e).2) else none) + +open scoped Classical in +theorem path_internal (i : Fin (P.diagram.arity v)) {e : P.diagram.E} + (he : P.diagram.wireAt v i = .inr e) : + P.path ha v i = ((P.diagram.peer v i).1, + some (Fin.castLE (ha v) ((Grid.number P.grid.packetRank (P.grid.uses v)).symm + ⟨(P.packets.bits e).1, P.packet_mem v i he⟩), (P.packets.bits e).2)) := by + simp only [path, he, Sum.elim_inr, dite_eq_left (P.packet_mem v i he)] + +open scoped Classical in +theorem path_exterior (i : Fin (P.diagram.arity v)) {z : Transcript.Boundary x y} + (he : P.diagram.wireAt v i = .inl z) : + P.path ha v i = ((P.diagram.peer v i).1, none) := by + simp only [path, he, Sum.elim_inl] + +open scoped Classical in +private theorem runs {n R : ℕ} (f : Fin n → Fin R) (hf : Monotone f) : + ∃ s : Finset (Fin n), s.card ≤ R ∧ ∀ i j, i.val + 1 = j.val → i ∉ s → f i = f j := by + let s := univ.filter fun i => ∀ j, i < j → f i < f j + have inj : Set.InjOn f ↑s := by + intro i hi j hj he + rcases lt_trichotomy i j with h | h | h + · exact ((mem_filter.mp hi).2 j h).ne he |>.elim + · exact h + · exact ((mem_filter.mp hj).2 i h).ne he.symm |>.elim + refine ⟨s, ?_, ?_⟩ + · simpa only [card_univ, Fintype.card_fin] using + card_le_card_of_injOn f (fun _ _ => mem_univ _) inj + · intro i j hij hn + simp only [s, mem_filter_univ] at hn + push Not at hn + obtain ⟨k, hk, hk'⟩ := hn + exact le_antisymm (hf (by omega)) ((hf (by omega : j ≤ k)).trans hk') + +open scoped Classical in +private def packetEnds := univ.filter fun i : Fin (P.diagram.arity v) => + ∃ e, P.diagram.wireAt v i = .inr e ∧ (P.packets.bits e).2.val + 1 = r + +open scoped Classical in +private theorem ends_le : (P.packetEnds v).card ≤ (P.grid.uses v).card := by + let s := P.packetEnds v + choose edge wire last using fun i : s => (mem_filter.mp i.property).2 + let pkt (i : s) : P.grid.uses v := ⟨(P.packets.bits (edge i)).1, P.packet_mem v i.val (wire i)⟩ + have inj : Function.Injective pkt := by + intro i j he + have heq : edge i = edge j := P.packets.bits.injective (Prod.ext (congrArg Subtype.val he) + (Fin.ext (Nat.add_right_cancel ((last i).trans (last j).symm)))) + apply Subtype.ext + apply P.diagram.wireAt_inj P.loopless + rw [wire i, wire j, heq] + simpa only [Fintype.card_coe] using Fintype.card_le_of_injective pkt inj + +open scoped Classical in +theorem path_sparse {R : ℕ} (ho : P.diagram.PortOrder R) (v : P.diagram.V) : + Sphere.Control.Sparse nextStep (P.path ha v) (R + A) := by + obtain ⟨b, hb, hstep⟩ := ho v + obtain ⟨s, hs, same⟩ := runs b hb + refine ⟨s ∪ P.packetEnds v, (card_union_le _ _).trans + (Nat.add_le_add hs ((P.ends_le v).trans (ha v))), ?_⟩ + intro i j hij hi + have hpeer := hstep _ _ hij (same i j hij (fun hi' => hi (mem_union_left _ hi'))) + have side : (P.diagram.peer v j).1 = (P.diagram.peer v i).1 := by rw [hpeer]; rfl + rcases P.diagram.wireAt_next v hij hpeer with ⟨_, _, he, hf⟩ | ⟨e, f, he, hf, hu, hv, ht⟩ + · rw [P.path_exterior ha v i he, P.path_exterior ha v j hf, side] + rfl + · have hh : (P.packets.bits e).2.val + 1 < r := by + have hn : (P.packets.bits e).2.val + 1 ≠ r := fun eq => + hi (mem_union_right _ (mem_filter.mpr ⟨mem_univ _, e, he, eq⟩)) + have := (P.packets.bits e).2.isLt + omega + obtain ⟨ep, es⟩ := P.packets_succ hu hv ht hh + have er : finRotate r (P.packets.bits e).2 = (P.packets.bits f).2 := by + apply Fin.ext + rw [finRotate_apply, Fin.val_add] + change (_ + 1 % r) % r = _ + rw [Nat.mod_eq_of_lt (show 1 < r by omega), Nat.mod_eq_of_lt hh, es] + rw [P.path_internal ha v i he, P.path_internal ha v j hf, side] + simp only [nextStep, Option.map_some, ep, er] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Computing a sphere station weight from local packet labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Finset Sphere Plant + +variable {F : Type} {x y : Wire} {h D T r g A : ℕ} {W : ℝ} + +open scoped Classical in +/-- Returns `s i.2 ⟨i.1.val, h⟩` when `h : i.1.val < w` holds, and `false` otherwise. -/ +def packetReadFromPathLabel {w : ℕ} (s : bitsAt w r) (i : Fin A × Fin r) : Bool := + if h : i.1.val < w then s i.2 ⟨i.1.val, h⟩ else false + +open scoped Classical in +/-- The station table, local path and exterior strings suffice. A wedge +outside the range of the packet code contributes zero. -/ +def pathLabel [Field F] (w : ℕ) (S : Table F) + (p : Fin (wd S.1 + wd S.2.1) → PathStep A r) (l t : List Bool) (v : Wedge r) : F := + ∑ z : bitsAt w r, if (markCode w r z).val = v then + Diagram.fromList S (Diagram.restore (packetReadFromPathLabel z) (List.ofFn p) l t) else 0 + +variable (P : Input F x y h D T r g W) (ha : ∀ v, (P.grid.uses v).card ≤ A) + +open scoped Classical in +private theorem weight_restore (j : P.diagram.V) (s : Finset P.Edges) (hs : s = P.grid.uses j) + (q : Val x × Val y) (z : bitsAt s.card r) : + P.weight j q (fun e t => Grid.read P.grid.packetRank s (z t) e) = + Diagram.fromList (P.diagram.table j) + (Diagram.restore (packetReadFromPathLabel z) (List.ofFn (P.path ha j)) + ((P.diagram.extLeft j).map (bits x q.1)) ((P.diagram.extRight j).map (bits y q.2))) := by + subst s + apply P.diagram.vertex_restore + · intro i e he + rw [P.path_internal ha j i he] + refine ⟨_, rfl, ?_⟩ + change Grid.read P.grid.packetRank (P.grid.uses j) (z (P.packets.bits e).2) (P.packets.bits + e).1 = _ + simp [Grid.read, P.packet_mem j i he, packetReadFromPathLabel] + · intro i a he + rw [P.path_exterior ha j i he, P.diagram.exterior_side j i he] + +open scoped Classical in +theorem pathLabel_eq [Field F] (K : Type) [Field K] (v : P.Occupied) + (i : Fin (P.grid.stations v).card) (q : Val x × Val y) + (s : Level r ((P.grid.template K P.weight v).level ((P.grid.template K P.weight v).old i))) : + (P.grid.template K P.weight v).stationWeight q i s = + pathLabel (P.grid.uses (P.grid.label v i)).card (P.diagram.table (P.grid.label v i)) + (P.path ha (P.grid.label v i)) ((P.diagram.extLeft (P.grid.label v i)).map (bits x q.1)) + ((P.diagram.extRight (P.grid.label v i)).map (bits y q.2)) s.val := by + rw [← P.grid.mark_label v i] + unfold Template.stationWeight pathLabel + apply sum_congr rfl + intro z _ + apply if_congr Subtype.ext_iff _ rfl + exact P.weight_restore ha _ _ (P.grid.mark_label v i) q z + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # The symbolic alphabet of a named ordinary key -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Key + +open Surface.Stage + +variable {V X : Type} {t : ℕ} + +open scoped Classical in +private theorem copy_val {k j : ℕ} (h : k = j) (x : Level t k) : + (Equiv.cast (congrArg (Level t) h) x).val = x.val := by subst j; rfl + +open scoped Classical in +private theorem left_nest (key : V → X → ℕ) (x : X) (v : V) (ns : List ℕ) (z : Values t ns) : + lookup key ns (.inl v) (nest x ns z) = .inl (key v x) := by + induction ns with + | nil => rfl + | cons n ns ih => rw [lookup_previous key (ns := ns) (.inl v) trivial]; exact ih _ + +open scoped Classical in +private theorem right_nest (key : V → X → ℕ) (x : X) (ns : List ℕ) + (z : Values t ns) (j : Fin ns.length) : + lookup key ns (.inr j.val) (nest x ns z) = .inr (z j).val := by + induction ns with + | nil => exact j.elim0 + | cons n ns ih => + induction j using Fin.lastCases with + | last => + rw [Fin.val_last, lookup_fresh] + exact congrArg Sum.inr (copy_val (by simp [order]) (z (Fin.last ns.length))) + | cast j => + rw [Fin.val_castSucc, lookup_previous key (ns := ns) (.inr j.val) j.isLt] + change lookup key ns (.inr j.val) (nest x ns (cut n ns z).1) = _ + rw [ih] + exact congrArg Sum.inr (copy_val (by simp [order]) (z j.castSucc)) + +variable {Y : Alphabet V} (index : ∀ v, Y.state v ↪ ℕ) (t : ℕ) (ns : List ℕ) + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `(index v).trans ⟨.inl, Sum.inl_injective⟩`. -/ +def symbol : (k : Key V ns) → (alphabet Y t ns).state k ↪ Symbol t + | .inl v => (index v).trans ⟨.inl, Sum.inl_injective⟩ + | .inr _ => ⟨fun x => .inr x.val, Sum.inr_injective.comp Subtype.val_injective⟩ + +open scoped Classical in +theorem lookup_stack (key : V → X → ℕ) (init : Y.State → X) + (hi : ∀ v a, key v (init a) = index v (a v)) (z : (alphabet Y t ns).State) (k : Key V ns) : + lookup key ns (name ns k) (stack Y t ns init z) = symbol index t ns k (z k) := by + cases k with + | inl i => + exact (left_nest key _ i ns _).trans (congrArg Sum.inl (hi i (old Y t ns z))) + | inr j => exact right_nest key _ ns _ j + +open scoped Classical in +/-- The indexed operation `Order.decode (Level t k) (Chunk.width t k) (binaryCode _ _ +(Chunk.card_le _ _)) (fun x => .inr x.val)`. -/ +def residueDecoder (k : ℕ) : Order.Decoder (Symbol t) := + Order.decode (Level t k) (Chunk.width t k) + (binaryCode _ _ (Chunk.card_le _ _)) (fun x => .inr x.val) + +open scoped Classical in +/-- Transforms the indexed data by `D.image (.map Sum.inl ·) ∪ (Finset.range (N + 1)).image +(residueDecoder t)`. -/ +def decoders (N : ℕ) (D : Finset (Order.Decoder ℕ)) : Finset (Order.Decoder (Symbol t)) := + D.image (.map Sum.inl ·) ∪ (Finset.range (N + 1)).image (residueDecoder t) + +open scoped Classical in +theorem card_decoders (N : ℕ) (D : Finset (Order.Decoder ℕ)) : + (decoders t N D).card ≤ D.card + (N + 1) := by + refine (Finset.card_union_le _ _).trans (Nat.add_le_add Finset.card_image_le ?_) + exact Finset.card_image_le.trans_eq (Finset.card_range _) + +open scoped Classical in +theorem decode_symbol (N : ℕ) (D : Finset (Order.Decoder ℕ)) + (hd : ∀ i, Order.decode _ _ (Y.code i) (index i) ∈ D) (hk : ∀ i ∈ ns, i ≤ N) + (k : Key V ns) : + Order.decode _ _ ((alphabet Y t ns).code k) (symbol index t ns k) ∈ decoders t N D := by + cases k with + | inl v => + apply Finset.mem_union_left + change Order.decode _ _ (Y.code v) (Sum.inl ∘ index v) ∈ _ + rw [Order.decode_comp] + exact Finset.mem_image_of_mem _ (hd v) + | inr i => + apply Finset.mem_union_right + exact Finset.mem_image_of_mem _ (Finset.mem_range.mpr (Nat.lt_succ_of_le (hk _ (order_mem ns + i)))) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Key +end + +/- # Translating station descriptions into local wire-reading rules -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Key + +open Surface Stage +variable {V X E T F : Type} {r t M : ℕ} {a b : Wire} {Y : Alphabet V} + +open scoped Classical in +private theorem lift_names (ns : List ℕ) (u : List (V ⊕ ℕ)) + (h : ∀ j ∈ u, Surface.available ns.length j) : + ∃ q : List (Key V ns), q.map (name ns) = u := by + induction u with + | nil => exact ⟨[], rfl⟩ + | cons j u ih => + obtain ⟨i, hi⟩ := exists_name ns j (h _ (by simp)) + obtain ⟨l, hl⟩ := ih (fun k hk => h k (.tail _ hk)) + exact ⟨i::l, by simp [hi, hl]⟩ + +variable [Fintype V] {s : Stage F (M * r) (M * t) T V E X} {Q : Source Y a b s} + {labels : Finset (Label F (M * r) (M * t))} {dec : Finset (Order.Decoder ℕ)} {n N : ℕ} + +open scoped Classical in +theorem rules_of_describes (left : Order.Exterior Q.left) (right : Order.Exterior Q.right) + (key : V → X → ℕ) (ext : Option T → X → List Bool × List Bool) + (index : ∀ v, Y.state v ↪ ℕ) (key_init : ∀ v x y z, key v (Q.init x y z) = index v (z v)) + (ext_init : ∀ i x y z, ext (item s.scene.cell i).label.name (Q.init x y z) = + ((left.ports i).map (bits a x), (right.ports i).map (bits b y))) + (f : Place s.scene.cell → Label F (M * r) (M * t)) (u : Place s.scene.cell → List (V ⊕ ℕ)) + (hd : ∀ i, Describes key ext s.hidden (item s.scene.cell i) (f i) (u i)) : + ∃ W : Order.Rules (share s Q), W.left = left ∧ W.right = right ∧ + W.tag = symbol index (M * t) s.hidden ∧ W.label = f ∧ + ∀ i, (W.reads i).map (name s.hidden) = u i := by + have valid (i : Place s.scene.cell) (j) (hj : j ∈ u i) : Surface.available s.hidden.length j := by + have hv := (Q.controls i.1 _ (List.get_mem _ i.2)).within + apply (Q.tracks.present _).mp + exact ⟨_, hv ((hd i).1 ▸ List.mem_toFinset.mpr hj)⟩ + choose k hk using fun i => lift_names s.hidden (u i) (valid i) + let W : Order.Rules (share s Q) := + { left := left, right := right, tag := symbol index (M * t) s.hidden, label := f + reads := k + seen := by + intro i j hj + apply mem_filter.mpr + rw [← (hd i).1, ← hk i, List.mem_toFinset] + exact List.mem_map_of_mem hj + run := by + intro i x y z a' b' + change (item s.scene.cell i).table (stack Y (M * t) s.hidden (Q.init x y) z) a' b' = _ + rw [(hd i).2, base_stack, ext_init, ← hk i, List.map_map] + simp only [Function.comp_def, lookup_stack index (M * t) s.hidden key (Q.init x y) + (fun j w => key_init j x y w)] } + exact ⟨W, rfl, rfl, rfl, rfl, hk⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Key +end + +/- # Emitting the specific labels selected by a local script -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Surface Surface.Stage Surface.Local +variable {F T V E X J L K N : Type} {r t M : ℕ} + {R : Reference J L N V E T X} {β : V ⊕ ℕ → K} + +namespace Surface.Local.Matches + +variable {G : Record F r t V E K N} {s : Stage F r t T V E X} + (h : Matches R.world β s G) + +open scoped Classical in +/-- The value specified by `(G.rows i.1).get ⟨i.2.val, (h.rows i.1).length_eq ▸ i.2.isLt⟩`. -/ +def row (i : Layout.Place s.scene.cell) : Entry F r t K N := + (G.rows i.1).get ⟨i.2.val, (h.rows i.1).length_eq ▸ i.2.isLt⟩ + +open scoped Classical in +theorem represents (i : Layout.Place s.scene.cell) : + Represents R.world β s.hidden (Layout.item s.scene.cell i) (h.row i) := + (h.rows i.1).get i.2.isLt _ + +end Surface.Local.Matches +namespace Layout.Key + +variable {Y : Alphabet V} (index : ∀ v, Y.state v ↪ ℕ) + +open scoped Classical in +/-- Alphabet width and exact decoder determined by the key's kind. -/ +def info (t : ℕ) : ℕ ⊕ ℕ → ℕ × Order.Decoder (Symbol t) + | .inl n => (Nat.clog 2 n, Order.decode (Fin n) (Nat.clog 2 n) + (binaryCode _ _ (by rw [Fintype.card_fin]; exact Nat.le_pow_clog (by decide) n)) + (fun v => .inl v.val)) + | .inr n => (Chunk.width t n, residueDecoder t n) + +open scoped Classical in +theorem symbol_info (size : V → ℕ) + (sel : ∀ v, (Y.width v, Order.decode _ _ (Y.code v) (Sum.inl ∘ index v)) = + info t (.inl (size v))) + (ns : List ℕ) (j : Key V ns) : + ((alphabet Y t ns).width j, Order.decode _ _ ((alphabet Y t ns).code j) (symbol index t ns j)) = + info t (kind size ns (name ns j)) := by + cases j with + | inl v => exact sel v + | inr i => + change _ = info t (.inr (Local.degree ns (.inr i.val : V ⊕ ℕ))) + rw [degree_order] + rfl + +variable [Fintype V] {a b : Wire} {G : Record F (M * r) (M * t) V E K N} + {s : Stage F (M * r) (M * t) T V E X} {A : Source Y a b s} + +open scoped Classical in +theorem intrinsic (h : Matches R.world β s G) + (left : Order.Exterior A.left) (right : Order.Exterior A.right) + (hi : ∀ v x y z, R.key v (A.init x y z) = index v (z v)) + (he : ∀ i x y z, R.ext (item s.scene.cell i).label.name (A.init x y z) = + ((left.ports i).map (bits a x), (right.ports i).map (bits b y))) : + ∃ W : Order.Rules (share s A), W.left = left ∧ W.right = right ∧ + W.tag = symbol index (M * t) s.hidden ∧ ∀ i, W.label i = (h.row i).label ∧ + (W.reads i).map (β ∘ name s.hidden) = (h.row i).reads := by + choose u hu hv using fun i => (h.represents i).label + obtain ⟨W, hw, hw', hk, hl, hr⟩ := rules_of_describes left right R.key R.ext index hi he _ _ hv + exact ⟨W, hw, hw', hk, fun i => ⟨congrFun hl i, by rw [← List.map_map, hr, hu]⟩⟩ + +end Layout.Key +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- # Labels of auxiliary insertion tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Finset Sphere Surface Routing.Private + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ n : ℕ} {W : ℝ} {ε : ℝ} (P : Input F x y h D T (d * b) g W) + +open scoped Classical in +/-- The indexed operation `fun v => SphereScale.canonical hK (P.grid.template K P.weight v) +(P.probe_width sc v) (P.stations_bound v) (P.ports_bound sc.Rpos v)`. -/ +def kit (sc : SphereScale.Scales g ℓ D T m b d) + (hK : SphereScale.Ready K ℓ D g m b d) : P.Tools K ℓ m := + fun v => SphereScale.canonical hK (P.grid.template K P.weight v) + (P.probe_width sc v) (P.stations_bound v) (P.ports_bound sc.Rpos v) + +open scoped Classical in +theorem kit_mem [Fintype K] (sc : SphereScale.Scales g ℓ D T m b d) + (hK : SphereScale.Ready K ℓ D g m b d) (v : P.Occupied) : + (P.kit sc hK v).program ∈ SphereScale.pool F hK := + mem_image_of_mem _ (mem_univ (SphereScale.pattern (P.grid.template K P.weight v) + (P.probe_width sc v) (P.stations_bound v) (P.ports_bound sc.Rpos v))) + +variable (p : P.Kits K m n ε) + +open scoped Classical in +/-- The value specified by `(s.2 v).val`. -/ +def key (v : P.Occupied) (s : P.Parameters p) := (s.2 v).val + +open scoped Classical in +/-- In the case `none`, this construction gives `([], [])`. -/ +def external (v : Option P.diagram.V) (s : P.Parameters p) : List Bool × List Bool := + match v with + | none => ([], []) + | some v => ((P.diagram.extLeft v).map (bits x s.1.1), (P.diagram.extRight v).map (bits y s.1.2)) + +open scoped Classical in +/-- The aux label of type `Stage.Label F (d * b) d` for the given inputs. -/ +def auxLabel (q : Program F n b d) (s : Shape n b d) (j : Option (Fin n)) : + Stage.Label F (d * b) d := fun _ _ u a b => + match u with + | [.inl i] => + if h : i < q.labels then + match j with + | none => q.scalar s ⟨i, h⟩ + | some j => + if he : Sphere.energy a.val = (s.1 j).val ∧ Sphere.energy b.val = (s.2 j).val then + q.table s ⟨i, h⟩ j ⟨a, he.1⟩ ⟨b, he.2⟩ + else 0 + else 0 + | _ => 0 + +open scoped Classical in +/-- Indexes the aux menu by the coordinates of `univ.image fun i : ↥S × Shape n b d × Option +(Fin n) => auxLabel i.1.val i.2.1 i.2.2`. -/ +def auxMenu (S : Finset (Program F n b d)) : Finset (Stage.Label F (d * b) d) := + univ.image fun i : ↥S × Shape n b d × Option (Fin n) => auxLabel i.1.val i.2.1 i.2.2 + +open scoped Classical in +theorem card_auxMenu (S : Finset (Program F n b d)) : + (auxMenu S).card ≤ S.card * (((d * b + 1) * (d * (energyConstant * b ^ 2) + 1)) ^ n * (n + 1)) + := by + unfold auxMenu + refine card_image_le.trans_eq ?_ + simp only [card_univ, Fintype.card_prod, Fintype.card_coe, Fintype.card_option, + Fintype.card_fun, Fintype.card_fin, mul_pow] + +open scoped Classical in +theorem mem_auxMenu (S : Finset (Program F n b d)) (q : Program F n b d) (hq : q ∈ S) + (e : Shape n b d) (i : Option (Fin n)) : auxLabel q e i ∈ auxMenu S := + mem_image_of_mem _ (mem_univ ((⟨q, hq⟩ : ↥S), e, i)) + +variable (s : P.Occupied → Shape n b d) (v : P.Occupied) + +open scoped Classical in +theorem collector_label : + Stage.Describes (P.key p) (P.external p) [] (Template.collectorAt p P.tag s v) + (auxLabel (p v).program (s v) none) [.inl v] := by + refine ⟨by simp; rfl, fun a u w => ?_⟩ + change (p v).program.scalar (s v) (a.2 v) = + auxLabel (p v).program (s v) none [] [] [.inl (a.2 v).val] u.val w.val + simp [auxLabel] + +open scoped Classical in +theorem auxiliary_label (j : Fin n) : + Stage.Describes (P.key p) (P.external p) [] (Template.auxAt p P.tag s v j) + (auxLabel (p v).program (s v) (some j)) [.inl v] := by + refine ⟨by simp; rfl, fun a u w => ?_⟩ + change Level (d * b) ((s v).1 j).val at u + change Level d ((s v).2 j).val at w + change (p v).program.table (s v) (a.2 v) j u w = + auxLabel (p v).program (s v) (some j) [] [] [.inl (a.2 v).val] u.val w.val + simp [auxLabel, u.property, w.property] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# Exterior port order at the terminal collectors + +Each named station retains its two original lists of exterior bits +in local port order. Unnamed stations carry no exterior bits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Routing.Private +open Sphere.Layout (Place item) + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ H U : ℕ} {W : ℝ} (P : Input F x y h D T (d * b) g W) + (p : P.Tools K ℓ m) (s : P.Occupied → Shape (SphereScale.probes ℓ D) b d) + {z : P.Configuration p} (hz : (P.plant p s).Reach m (2 * g) H U z) + +/-- Builds `Order.Exterior (P.draw p s hz ∘ side) where ports i` with the specified `ports`, +`nodup`, `mem`. -/ +def collectPorts {X : Type} (side : X → slots x ⊕ slots y) + (l : P.diagram.V → List X) (nd : ∀ v, (l v).Nodup) + (hm : ∀ v i, i ∈ l v ↔ Packing.portEnd P.diagram (side i) = v) : + Order.Exterior (P.draw p s hz ∘ side) where + ports i := (item z.scene.cell i).label.name.elim [] l + nodup i := by cases (item z.scene.cell i).label.name <;> simp [nd] + mem i j := by + have hd : P.draw p s hz (side j) = i ↔ + (item z.scene.cell i).label.name = some (Packing.portEnd P.diagram (side j)) := + ⟨fun h => h ▸ P.draw_name p s hz (side j), P.draw_eq p s hz (side j) i⟩ + rw [Function.comp_apply, hd] + cases (item z.scene.cell i).label.name <;> simp [hm, eq_comm] + +/-- Computes the input ports by the application `P.collectPorts p s hz Sum.inl P.diagram.extLeft +P.diagram.extLeft_nodup P.diagram.mem_extLeft`. -/ +def inputPorts : Order.Exterior (P.draw p s hz ∘ Sum.inl) := + P.collectPorts p s hz Sum.inl P.diagram.extLeft P.diagram.extLeft_nodup P.diagram.mem_extLeft + +/-- Computes the output ports by the application `P.collectPorts p s hz Sum.inr +P.diagram.extRight P.diagram.extRight_nodup P.diagram.mem_extRight`. -/ +def outputPorts : Order.Exterior (P.draw p s hz ∘ Sum.inr) := + P.collectPorts p s hz Sum.inr P.diagram.extRight P.diagram.extRight_nodup P.diagram.mem_extRight + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # A finite menu for the original station insertions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Surface +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ n : ℕ} {W ε : ℝ} + +open scoped Classical in +/-- The subtype of `p : Fin (wd L.1 + wd L.2.1) → PathStep n r` satisfying `Control.Sparse +nextStep p (R + n)`. -/ +abbrev Route (L : Table F) (r n R : ℕ) := + {p : Fin (wd L.1 + wd L.2.1) → PathStep n r // Control.Sparse nextStep p (R + n)} + +open scoped Classical in +/-- Evaluates `pathLabel v.1.val L v.2.val x y a` at the input `x y _ a _`. -/ +def fromPath (L : Table F) (r t n R : ℕ) (v : Fin (n + 1) × Route L r n R) : + Stage.Label F r t := + fun x y _ a _ => pathLabel v.1.val L v.2.val x y a + +open scoped Classical in +/-- Only tables below the cell arity bound are needed. Each can use +any ordered route with a bounded number of interruptions. -/ +def oldMenu (S : Finset (Table F)) (r t n R Z : ℕ) : Finset (Stage.Label F r t) := + (S.filter fun L => wd L.1 + wd L.2.1 ≤ Z).biUnion fun L => univ.image (fromPath L r t n R) + +open scoped Classical in +theorem card_oldMenu (S : Finset (Table F)) (r t n R Z : ℕ) : + (oldMenu S r t n R Z).card ≤ S.card * ((n + 1) * (Z * (2 * (n * r + 1)) + 1) ^ (R + n + 1)) + := by + let a := S.filter fun L => wd L.1 + wd L.2.1 ≤ Z + unfold oldMenu + calc + _ ≤ ∑ L ∈ a, (univ.image (fromPath L r t n R)).card := card_biUnion_le + _ ≤ ∑ _ ∈ a, (n + 1) * (Z * (2 * (n * r + 1)) + 1) ^ (R + n + 1) := by + apply sum_le_sum + intro L hL + have h := Control.card_sparse (@nextStep n r) (wd L.1 + wd L.2.1) (R + n) + have hz := (mem_filter.mp hL).2 + have he : Fintype.card (PathStep n r) = 2 * (n * r + 1) := by simp [PathStep] + rw [he] at h + refine card_image_le.trans ?_ + rw [card_univ, Fintype.card_prod, Fintype.card_fin] + exact Nat.mul_le_mul_left _ (h.trans (by gcongr)) + _ ≤ _ := by + rw [sum_const, Nat.nsmul_eq_mul] + exact Nat.mul_le_mul_right _ (card_filter_le ..) + +variable (P : Input F x y h D T (d * b) g W) (p : P.Kits K m n ε) + +open scoped Classical in +theorem external_original (v : P.Occupied) (j : P.diagram.V) (s : P.Parameters p) : + P.external p (P.tag (n := n) v (.inl j)).name s = + ((P.diagram.extLeft j).map (bits x s.1.1), (P.diagram.extRight j).map (bits y s.1.2)) := by + by_cases hm : P.mobile j + · have hl : P.diagram.extLeft j = [] := by + apply List.eq_nil_iff_forall_not_mem.mpr + exact fun i hi => P.ext (.inl i) ((P.diagram.mem_extLeft _ _).mp hi ▸ hm) + have hr : P.diagram.extRight j = [] := by + apply List.eq_nil_iff_forall_not_mem.mpr + exact fun i hi => P.ext (.inr i) ((P.diagram.mem_extRight _ _).mp hi ▸ hm) + simp [tag, hm, external, hl, hr] + · simp [tag, hm, external] + +open scoped Classical in +theorem original_label (ha : ∀ v, (P.grid.uses v).card ≤ n) (S : Finset (Table F)) + (hS : ∀ v, P.diagram.table v ∈ S) {R Z : ℕ} (ho : P.diagram.PortOrder R) + (hZ : ∀ v, P.diagram.arity v ≤ Z) (c : P.Occupied) (i : Fin (P.grid.stations c).card) : + ∃ L ∈ oldMenu S (d * b) d n R Z, + Stage.Describes (P.key p) (P.external p) [] (Template.originalAt p P.tag c i) L [] := by + let j := P.grid.label c i + let t := P.diagram.table j + let v : Fin (n + 1) × Route t (d * b) n R := + (⟨_, Nat.lt_succ_of_le (ha j)⟩, ⟨P.path ha j, P.path_sparse ha ho j⟩) + refine ⟨fromPath t (d * b) d n R v, ?_, ?_, ?_⟩ + · apply mem_biUnion.mpr + exact ⟨t, mem_filter.mpr ⟨hS j, hZ j⟩, mem_image_of_mem _ (mem_univ v)⟩ + · change ∅ = (P.tag (n := n) c (.inl j)).reads + by_cases hm : P.mobile j <;> simp [tag, hm] + · intro x a b + change (P.grid.template K P.weight c).stationWeight x.1 i a = + pathLabel (P.grid.uses j).card t (P.path ha j) + (P.external p (P.tag (n := n) c (.inl j)).name x).1 + (P.external p (P.tag (n := n) c (.inl j)).name x).2 a.val + rw [external_original] + exact P.pathLabel_eq ha K c i _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Initial table descriptions uniform across all ordered input diagrams -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Surface SphereScale + +variable {F K : Type} [Field F] [Field K] [Algebra K F] [Fintype K] {x y : Wire} + {h D T b d g m ℓ R : ℕ} {W : ℝ} + +open scoped Classical in +/-- The quantity computed by `oldMenu S (d * b) d (probes ℓ D) R (100 * D * T) ∪ auxMenu (pool F +hK)`. -/ +def initialMenu (hK : Ready K ℓ D g m b d) (S : Finset (Table F)) (T R : ℕ) := + oldMenu S (d * b) d (probes ℓ D) R (100 * D * T) ∪ auxMenu (pool F hK) + +open scoped Classical in +theorem card_initialMenu (hK : Ready K ℓ D g m b d) (S : Finset (Table F)) (T R : ℕ) : + let n := probes ℓ D + (initialMenu hK S T R).card ≤ + S.card * ((n + 1) * (100 * D * T * (2 * (n * (d * b) + 1)) + 1) ^ (R + n + 1)) + + Fintype.card (Pattern K D g n) * + (((d * b + 1) * (d * (Routing.Private.energyConstant * b ^ 2) + 1)) ^ n * (n + 1)) := by + apply (card_union_le _ _).trans + apply Nat.add_le_add (card_oldMenu ..) + exact (card_auxMenu _).trans (Nat.mul_le_mul_right _ (pool_bound F hK)) + +variable (P : Input F x y h D T (d * b) g W) (sc : Scales g ℓ D T m b d) + +omit [Field F] in +open scoped Classical in +theorem maxArity (v : P.diagram.V) : P.diagram.arity v ≤ 100 * D * T := by + have hb : (P.diagram.arity v : ℝ) ≤ 100 * D * T := by + refine le_trans ?_ (P.mass (P.place v)) + unfold Packing.push + simpa using single_le_sum (s := univ) + (f := fun w => if P.place w = P.place v then (P.diagram.arity w : ℝ) else 0) + (fun _ _ => by positivity) (mem_univ v) + exact_mod_cast hb + +omit [Field F] in +open scoped Classical in +theorem maxPackets (sc : Scales g ℓ D T m b d) (v : P.diagram.V) : + (P.grid.uses v).card ≤ probes ℓ D := by + apply Nat.le_of_mul_le_mul_left _ sc.Rpos + calc + _ ≤ P.diagram.arity v := P.uses_card v + _ ≤ 100 * D * T := P.maxArity v + _ ≤ 100 * D * (2 * (d * b * size ℓ D)) := Nat.mul_le_mul_left _ sc.upper + _ = d * b * (200 * D * size ℓ D) := by ring + _ ≤ _ := by unfold probes; gcongr; decide + +open scoped Classical in +theorem plant_tabulated (hK : Ready K ℓ D g m b d) (S : Finset (Table F)) + (hS : ∀ v, P.diagram.table v ∈ S) (ho : P.diagram.PortOrder R) + (s : P.Occupied → Routing.Private.Shape (probes ℓ D) b d) : + let p := P.kit sc hK + ∀ c, ∀ u ∈ ((P.plant p s).scene.cell c).stations, + Stage.Tabulated (P.key p) (P.external p) [] u (initialMenu hK S T R) 1 := by + intro p c u hu + have aux (i : Option (Fin (probes ℓ D))) : + auxLabel (p c).program (s c) i ∈ initialMenu hK S T R := + mem_union_right _ (mem_auxMenu _ _ (P.kit_mem sc hK c) (s c) i) + rcases P.plant_cases p s c u hu with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩ + · exact ⟨_, aux none, _, le_rfl, P.collector_label p s c⟩ + · exact ⟨_, aux (some i), _, le_rfl, P.auxiliary_label p s c i⟩ + · obtain ⟨L, hL, h⟩ := P.original_label p (P.maxPackets sc) S hS ho P.maxArity c i + exact ⟨L, mem_union_left _ hL, [], Nat.zero_le _, h⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Reorder.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Reorder.lean new file mode 100644 index 0000000000..312eaca2bd --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Reorder.lean @@ -0,0 +1,1121 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Data.Fin.Tuple.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Depth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality + +/-! +# Recording a sequence with few interruptions + +It suffices to name the first entry and the position and value just +after each interruption of the deterministic successor rule. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Control +open Finset +variable {α : Type} {n k : ℕ} (next : α → α) + +open scoped Classical in +/-- The condition `∃ s : Finset (Fin n), s.card ≤ k ∧ ∀ i j : Fin n, i.val + 1 = j.val → i ∉ s → +f j = next (f i)` on the specified data. -/ +def Sparse (f : Fin n → α) (k : ℕ) : Prop := + ∃ s : Finset (Fin n), s.card ≤ k ∧ + ∀ i j : Fin n, i.val + 1 = j.val → i ∉ s → f j = next (f i) + +open scoped Classical in +private abbrev Log (α : Type) (n k : ℕ) := Fin (k + 1) → Option (Fin n × α) + +open scoped Classical in +private def Encodes (a : Log α n k) (f : Fin n → α) : Prop := + (∀ s i v, a s = some (i, v) → f i = v) ∧ + ∀ i : Fin n, (∃ s v, a s = some (i, v)) ∨ + ∃ j : Fin n, j.val + 1 = i.val ∧ f i = next (f j) + +open scoped Classical in +private theorem Encodes.unique {a : Log α n k} {f g : Fin n → α} + (h : Encodes next a f) (e : Encodes next a g) : f = g := by + funext i + induction hn : i.val using Nat.strong_induction_on generalizing i with + | ind n ih => + by_cases named : ∃ s v, a s = some (i, v) + · obtain ⟨s, v, hv⟩ := named + exact (h.1 s i v hv).trans (e.1 s i v hv).symm + obtain ⟨j, hj, hu⟩ := (h.2 i).resolve_left named + obtain ⟨l, hl, hv⟩ := (e.2 i).resolve_left named + rw [hu, hv, show l = j from Fin.ext (by omega), ih j.val (by omega) j rfl] + +open scoped Classical in +private theorem Sparse.encodes {f : Fin n → α} (h : Sparse next f k) : + ∃ a : Log α n k, Encodes next a f := by + obtain ⟨s, hk, h⟩ := h + let e := s.equivFin + let pos (i : Fin n) := if hi : i.val + 1 < n then (⟨i.val + 1, hi⟩ : Fin n) else i + let first := if hn : 0 < n then some (⟨0, hn⟩ : Fin n) else none + let rest (i : Fin k) := + if hi : i.val < s.card then some (pos (e.symm ⟨i.val, hi⟩).val) else none + let p : Fin (k + 1) → Option (Fin n) := Fin.cons first rest + refine ⟨fun i => (p i).map (fun j => (j, f j)), ?_, ?_⟩ + · intro a i v ha + obtain ⟨j, _, h⟩ := Option.map_eq_some_iff.mp ha + obtain ⟨rfl, rfl⟩ := Prod.mk.inj h + rfl + intro i + have named (j) (hj : p j = some i) : + ∃ s v, (p s).map (fun j => (j, f j)) = some (i, v) := ⟨j, f i, by simp [hj]⟩ + by_cases hi : i.val = 0 + · apply Or.inl (named 0 ?_) + simp only [p, Fin.cons_zero, first, dite_eq_left (by omega : 0 < n)] + exact congrArg some (Fin.ext hi.symm) + let j : Fin n := ⟨i.val - 1, by omega⟩ + have hj : j.val + 1 = i.val := by dsimp [j]; omega + by_cases hs : j ∈ s + · let q := e ⟨j, hs⟩ + refine .inl (named (Fin.castLE hk q).succ ?_) + have he : pos j = i := by simp [pos, hj] + simp [p, rest, q, he] + · exact .inr ⟨j, hj, h j i hj hs⟩ + +open scoped Classical in +theorem card_sparse [Fintype α] (n k : ℕ) : + Fintype.card {f : Fin n → α // Sparse next f k} ≤ (n * Fintype.card α + 1) ^ (k + 1) := by + choose g hg using fun f : {f : Fin n → α // Sparse next f k} => Sparse.encodes next f.property + have hh : Function.Injective g := by + intro i j h + exact Subtype.ext (Encodes.unique next (h ▸ hg i) (hg j)) + simpa [Log] using Fintype.card_le_of_injective g hh + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Control +end + +/- +# A uniform local script + +The index set and coefficient of each branch are chosen from a region +record. They must work in every larger graph realizing that record. +The domain of hidden-state indices can differ among those graphs. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset +variable {F T V E X J L K N : Type} {r t P g H U M D : ℕ} + +open scoped Classical in +/-- Uses `{q | ∃ u ∈ (s.scene.cell q.1).stations, u.pos = q.2 ∧ ∃ n, u.label.role = .active n}` +as the representation. -/ +def pending (s : Stage F r t T V E X) : Set (V × F) := + {q | ∃ u ∈ (s.scene.cell q.1).stations, u.pos = q.2 ∧ ∃ n, u.label.role = .active n} + +open scoped Classical in +/-- The condition `∀ v u, u ∈ (s.scene.cell v).stations → u.label.role.clock = 0` on the +specified data. -/ +def Calm (s : Stage F r t T V E X) : Prop := + ∀ v u, u ∈ (s.scene.cell v).stations → u.label.role.clock = 0 + +open scoped Classical in +/-- Every seam traversable within the crossing allowance has its +other endpoint in the region. -/ +def Covers (ports : J → List (L × F)) (v : J) : ℕ → Prop + | 0 => True + | n + 1 => ∀ p ∈ ports v, ∃ w y, w ≠ v ∧ (p.1, y) ∈ ports w ∧ Covers ports w n + +open scoped Classical in +/-- The data for the script construction, including `I`, `[finite`, `weight`, `result`, `fresh`. -/ +structure Script (F : Type) (r t : ℕ) (J L K N : Type) where + /-- The `Script` component of type `Type`. -/ + I : Type + [finite : Fintype I] + /-- The weight function carried by `Script`, with type `I → F`. -/ + weight : I → F + /-- The `Script` component of type `I → Record F r t J L K N`. -/ + result : I → Record F r t J L K N + /-- The `Script` component of type `I → List (K × ℕ)`. -/ + fresh : I → List (K × ℕ) + +attribute [instance] Script.finite + +open scoped Classical in +/-- The condition `∀ i, n + (h.fresh i).length ≤ U ∧ ∀ j : Fin (h.fresh i).length, ((h.fresh +i).get j).1 = ν (n + j.val)` on the specified data. -/ +def Script.Ordered (h : Script F r t J L K N) (ν : ℕ → K) (n U : ℕ) := + ∀ i, n + (h.fresh i).length ≤ U ∧ ∀ j : Fin (h.fresh i).length, ((h.fresh i).get j).1 = ν (n + + j.val) + +variable [Field F] + +open scoped Classical in +/-- The data for the update construction, including `reach`, `valid`, `match'`, `outside`. -/ +structure Update (P g H U : ℕ) (R : Reference J L N V E T X) (β β' : V ⊕ ℕ → K) + (s q : Stage F r t T V E X) (a : Record F r t J L K N) (fresh : List (K × ℕ)) : Prop where + reach : s.Reach P g H U q + valid : q.Valid U + match' : Matches R β' q a + outside : Outside (Set.range R.vertex) (Set.range R.edge) R.key s q β β' fresh + +open scoped Classical in +/-- The executes of type `Prop` for the given inputs. -/ +def Script.Executes [Fintype V] [Fintype E] (script : Script F r t J L K N) (P g H U : ℕ) + (R : Reference J L N V E T X) (β : V ⊕ ℕ → K) (s : Stage F r t T V E X) + (allowed : Set (V × F)) (f : X → F) : Prop := + ∃ (q : script.I → Stage F r t T V E X) (γ : script.I → V ⊕ ℕ → K), + (∀ i, Update P g H U R β (γ i) s (q i) (script.result i) (script.fresh i) ∧ + Calm (q i) ∧ pending (q i) ⊆ allowed) ∧ + ∀ x, f x = ∑ i, script.weight i * (q i).value P x + +open scoped Classical in +/-- The runs of type `Prop` for the given inputs. -/ +def Script.Runs (script : Script F r t J L K N) (a : Record F r t J L K N) + (P g H U M D : ℕ) (v : J) (z : F) : Prop := + ∀ {V E T X : Type} [Fintype V] [Fintype E] (R : Reference J L N V E T X) + (β : V ⊕ ℕ → K) (s : Stage F r t T V E X) (src dst : E → V), + Matches R β s a → s.Layout src dst g → s.Valid U → + (∀ y, s.Reach P g H U y → y.Room M D) → Calm s → + script.Executes P g H U R β s (pending s \ {(R.vertex v, z)}) (s.value P) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Composition of uniform region scripts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset +variable {F T V E X J L K N : Type} [Field F] [Fintype E] [Fintype V] + {r t P g H U M D : ℕ} +variable {R : Reference J L N V E T X} {β β' : V ⊕ ℕ → K} + {s q : Stage F r t T V E X} {a : Record F r t J L K N} + {f : X → F} {A : Set (V × F)} {ν : ℕ → K} {n : ℕ} + +omit [Fintype V] [Fintype E] in +open scoped Classical in +theorem Update.refl (h : Matches R β s a) (hv : s.Valid U) : Update P g H U R β β s s a [] := + ⟨.refl, hv, h, .refl⟩ + +namespace Script + +open scoped Classical in +/-- Uses `⟨Unit, fun _ => 1, fun _ => a, fun _ => []⟩` as the representation. -/ +def pure (a : Record F r t J L K N) : Script F r t J L K N := + ⟨Unit, fun _ => 1, fun _ => a, fun _ => []⟩ + +open scoped Classical in +theorem ordered_pure (a : Record F r t J L K N) (h : n ≤ U) : (pure a).Ordered ν n U := + fun _ => ⟨h, fun i => i.elim0⟩ + +open scoped Classical in +theorem executes_pure (h : Update P g H U R β β' s q a []) (hc : Calm q) (hp : pending q ⊆ A) : + (pure a).Executes P g H U R β s A (q.value P) := + ⟨fun _ => q, fun _ => β', fun _ => ⟨h, hc, hp⟩, fun x + => by change _ = ∑ _ : Unit, (1 : F) * q.value P x; simp⟩ + +variable {w : Script F r t J L K N} + +open scoped Classical in +/-- The quantity computed by `{w with weight := fun i => k * w.weight i}`. -/ +def times (w : Script F r t J L K N) (k : F) := {w with weight := fun i => k * w.weight i} + +open scoped Classical in +theorem Executes.times (h : w.Executes P g H U R β s A f) (k : F) : + (w.times k).Executes P g H U R β s A (fun x => k * f x) := by + obtain ⟨q, γ, hg, he⟩ := h + refine ⟨q, γ, hg, fun x => ?_⟩ + change k * f x = ∑ i, (k * w.weight i) * (q i).value P x + rw [he, mul_sum] + simp only [mul_assoc] + +open scoped Classical in +/-- Concatenates the components in the order `{s with fresh := fun i => v ++ s.fresh i}`. -/ +def prepend (s : Script F r t J L K N) (v : List (K × ℕ)) := + {s with fresh := fun i => v ++ s.fresh i} + +omit [Field F] in +open scoped Classical in +theorem Ordered.emit (h : w.Ordered ν (n + 1) U) (m : ℕ) : + (w.prepend [(ν n, m)]).Ordered ν n U := by + intro i + obtain ⟨h, he⟩ := h i + change n + ((ν n, m) :: w.fresh i).length ≤ U ∧ _ + refine ⟨by simp only [List.length_cons]; omega, ?_⟩ + change ∀ j : Fin ((w.fresh i).length + 1), (( (ν n, m) :: w.fresh i).get j).1 = ν (n + j.val) + intro j + refine Fin.cases rfl (fun j => ?_) j + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using he j + +open scoped Classical in +theorem Executes.before {l} (h : w.Executes P g H U R β' q A f) + (step : Update P g H U R β β' s q a l) : + (w.prepend l).Executes P g H U R β s A f := by + obtain ⟨z, γ, hg, he⟩ := h + refine ⟨z, γ, fun i => ?_, he⟩ + obtain ⟨hr, hc, hp⟩ := hg i + exact ⟨⟨step.reach.trans hr.reach, hr.valid, hr.match', step.outside.trans hr.outside⟩, hc, hp⟩ + +open scoped Classical in +theorem Executes.prior (h : w.Executes P g H U R β' q A f) + (step : Update P g H U R β β' s q a []) : w.Executes P g H U R β s A f := + h.before step + +variable {I : Type} [Fintype I] (k : I → F) (u : I → Script F r t J L K N) + +open scoped Classical in +/-- Indexes the sum by the coordinates of `Σ i, (u i).I weight i := k i.1 * (u i.1).weight i.2 +result i := (u i.1).result i.2 fresh i := (u i.1).fresh i.2`. -/ +def sum : Script F r t J L K N where + I := Σ i, (u i).I + weight i := k i.1 * (u i.1).weight i.2 + result i := (u i.1).result i.2 + fresh i := (u i.1).fresh i.2 + +open scoped Classical in +theorem ordered_sum (h : ∀ i, (u i).Ordered ν n U) : (sum k u).Ordered ν n U := + fun i => h i.1 i.2 + +open scoped Classical in +theorem executes_sum (f : I → X → F) (h : ∀ i, (u i).Executes P g H U R β s A (f i)) : + (sum k u).Executes P g H U R β s A (fun x => ∑ i, k i * f i x) := by + unfold Executes at h + choose q γ hq he using h + refine ⟨fun i => q i.1 i.2, fun i => γ i.1 i.2, fun i => hq i.1 i.2, fun x => ?_⟩ + change _ = ∑ i : Σ i, (u i).I, _ + simp only [he, mul_sum, Fintype.sum_sigma, sum, mul_assoc] + +end Script +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Running one mover uniformly in all ambient graphs -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset + +open scoped Classical in +/-- The data for the params construction, including `P`, `g`, `H`, `U`, `M`. -/ +structure Params where + /-- The `Params` field of type `ℕ`. -/ + P : ℕ + /-- The `Params` field of type `ℕ`. -/ + g : ℕ + /-- The `Params` field of type `ℕ`. -/ + H : ℕ + /-- The `Params` field of type `ℕ`. -/ + U : ℕ + /-- The `Params` field of type `ℕ`. -/ + M : ℕ + /-- The `Params` field of type `ℕ`. -/ + D : ℕ + +open scoped Classical in +/-- The data for the job construction, including `a`, `v`, `x`, `tail`, `n`. -/ +structure Job (F : Type) (r t : ℕ) (J L K N : Type) where + /-- The left component of type `Record F r t J L K N`. -/ + a : Record F r t J L K N + /-- The `Job` field of type `J`. -/ + v : J + /-- The `Job` component of type `Entry F r t K N`. -/ + x : Entry F r t K N + /-- The `Job` component of type `List (Entry F r t K N)`. -/ + tail : List (Entry F r t K N) + /-- The `Job` field of type `ℕ`. -/ + n : ℕ + row : a.rows v = x :: tail + active : x.role = .active n + +variable {F T V E X J L K N : Type} {r t : ℕ} + +open scoped Classical in +/-- The indexing data represented by `u.label.role.clock = 0 ∧ (∀ n, u.label.role = .active n → +(v, u.pos) ∈ A)`. -/ +def idle (A : Set (V × F)) (v : V) (u : Station F r t (Tag V T) X) := + u.label.role.clock = 0 ∧ (∀ n, u.label.role = .active n → (v, u.pos) ∈ A) + +open scoped Classical in +theorem idle_done {s : Stage F r t T V E X} {A : Set (V × F)} + (h : ∀ v u, u ∈ (s.scene.cell v).stations → idle A v u) : + Calm s ∧ pending s ⊆ A := by + refine ⟨fun v u hu => (h v u hu).1, ?_⟩ + rintro ⟨v, z⟩ ⟨u, hu, he, n, hn⟩ + change u.pos = z at he + exact he ▸ (h v u hu).2 n hn + +variable [Field F] + +open scoped Classical in +/-- An ambient graph and arbitrary input functions interpreting a +given region record. Moving outside the region is excluded by Covers. -/ +structure World (p : Params) (a : Record F r t J L K N) where + /-- The `World` component of type `Type`. -/ + T : Type + /-- The `World` component of type `Type`. -/ + X : Type + /-- The type of vertices. -/ + V : Type + /-- The type of edges. -/ + E : Type + [fv : Fintype V] + [fe : Fintype E] + /-- The `World` component of type `Reference J L N V E T X`. -/ + R : Reference J L N V E T X + /-- The `World` component of type `V ⊕ ℕ → K`. -/ + β : V ⊕ ℕ → K + /-- The `World` component of type `Stage F r t T V E X`. -/ + s : Stage F r t T V E X + /-- Assigns the source of each connection. -/ + src : E → V + /-- Assigns the destination of each connection. -/ + dst : E → V + /-- The `World` component of type `Set (V × F)`. -/ + allowed : Set (V × F) + match' : Matches R β s a + layout : s.Layout src dst p.g + valid : s.Valid p.U + room : ∀ y, s.Reach p.P p.g p.H p.U y → y.Room p.M p.D + +attribute [instance] World.fv World.fe +variable {p : Params} {a a' : Record F r t J L K N} + +open scoped Classical in +/-- Builds `World p a' where T` with the specified `World`, `src`, `dst`, `allowed`. -/ +def World.next (w : World p a) {q γ h} (u : Update p.P p.g p.H p.U w.R w.β γ w.s q a' h) : + World p a' where + T := w.T + X := w.X + V := w.V + E := w.E + R := w.R + β := γ + s := q + src := w.src + dst := w.dst + allowed := w.allowed + match' := u.match' + layout := by + have layout {q} (h : w.s.Reach p.P p.g p.H p.U q) : q.Layout w.src w.dst p.g := by + induction h with + | refl => exact w.layout + | tail _ h ih => exact h.layout ih + exact layout u.reach + valid := u.valid + room _ h := w.room _ (u.reach.trans h) + +variable (m : Job F r t J L K N) + +open scoped Classical in +/-- The data for the task construction, including `rest`, `raw`, `located`, `others`, `away`. -/ +structure Task (p : Params) extends World p m.a where + /-- The `Task` component of type `s.Ct`. -/ + rest : s.Ct + /-- The `Task` component of type `s.St`. -/ + raw : s.St + located : s.scene.cell (R.vertex m.v) = rest.insert raw + others : ∀ u ∈ rest.stations, idle allowed (R.vertex m.v) u + away : ∀ k, k ≠ R.vertex m.v → ∀ u ∈ (s.scene.cell k).stations, idle allowed k u + +namespace Task +variable {m} (q : Task m p) + +open scoped Classical in +theorem aligned : Represents q.R q.β q.s.hidden q.raw m.x ∧ + List.Forall₂ (Represents q.R q.β q.s.hidden) q.rest.stations m.tail := by + have e := q.match'.rows m.v + rw [q.located, m.row] at e + exact List.forall₂_cons.mp e + +open scoped Classical in +/-- Uses `⟨x, a, b, u.label, fun x i j => u.table x (h.symm ▸ i) (g.symm ▸ j)⟩` as the +representation. -/ +def recast (u : Station F r t T X) (x : F) (a b : ℕ) (h : u.a = a) (g : u.b = b) : + Station F r t T X := + ⟨x, a, b, u.label, fun x i j => u.table x (h.symm ▸ i) (g.symm ▸ j)⟩ + +omit [Field F] in +open scoped Classical in +private theorem recast_eq (u : Station F r t T X) (x : F) (a b : ℕ) + (h : u.a = a) (g : u.b = b) (e : u.pos = x) : recast u x a b h g = u := by + subst_vars + rfl + +open scoped Classical in +/-- Present the ambient station with the dimensions of the intrinsic record. -/ +def mover := recast q.raw m.x.pos m.x.a m.x.b q.aligned.1.left q.aligned.1.right + +open scoped Classical in +theorem mover_eq : q.mover = q.raw := recast_eq _ _ _ _ _ _ q.aligned.1.pos + +open scoped Classical in +theorem here : q.s.scene.cell (q.R.vertex m.v) = q.rest.insert q.mover := by + rw [mover_eq, q.located] + +open scoped Classical in +theorem rows : Represents q.R q.β q.s.hidden q.mover m.x ∧ + List.Forall₂ (Represents q.R q.β q.s.hidden) q.rest.stations m.tail := by + rw [mover_eq] + exact q.aligned + +open scoped Classical in +/-- The move of type `Move q.s` for the given inputs. -/ +def move : Move q.s := + ⟨q.R.vertex m.v, q.rest, q.mover, m.n, q.here, q.rows.1.role.trans m.active, + fun u h => (q.others u h).1, fun v h u h' => (q.away v h u h').1⟩ + +open scoped Classical in +/-- Uses `x.Executes p.P p.g p.H p.U q.R q.β q.s q.allowed f` as the representation. -/ +def executes (x : Script F r t J L K N) (f : q.X → F) := + x.Executes p.P p.g p.H p.U q.R q.β q.s q.allowed f + +end Task + +open scoped Classical in +/-- The quantity computed by `(p.U - m.n) * (p.M + 1) + m.tail.length`. -/ +def Job.fuel (p : Params) := (p.U - m.n) * (p.M + 1) + m.tail.length + +open scoped Classical in +/-- The quantity computed by `breadth p.P p.g p.H p.M p.D (Nat.card F + 1)`. -/ +def Params.limit (p : Params) (F : Type) := breadth p.P p.g p.H p.M p.D (Nat.card F + 1) + +open scoped Classical in +/-- The quantity computed by `width p.P p.g p.H p.D (Nat.card F + 1)`. -/ +def Params.fan (p : Params) (F : Type) := width p.P p.g p.H p.D (Nat.card F + 1) + +omit [Field F] in +open scoped Classical in +theorem Params.limit_pos (p : Params) (F : Type) : 0 < p.limit F := by + unfold limit breadth window; positivity + +omit [Field F] in +open scoped Classical in +theorem Params.fan_pos (p : Params) (F : Type) : 0 < p.fan F := by + unfold fan width window; positivity + +open scoped Classical in +/-- The condition `∃ s : Script F r t J L K N, s.Ordered ν m.n p.U ∧ Fintype.card s.I ≤ b ∧ ∀ q +: Task m p, q.executes s (f q)` on the specified data. -/ +def Job.Bounded (p : Params) (ν : ℕ → K) (b : ℕ) (f : ∀ q : Task m p, q.X → F) := + ∃ s : Script F r t J L K N, s.Ordered ν m.n p.U ∧ + Fintype.card s.I ≤ b ∧ ∀ q : Task m p, q.executes s (f q) + +open scoped Classical in +/-- The quantity computed by `m.Bounded p ν (p.fan F * p.limit F ^ (m.fuel p - 1))`. -/ +def Job.Solvable (p : Params) (ν : ℕ → K) := + m.Bounded p ν (p.fan F * p.limit F ^ (m.fuel p - 1)) + +open scoped Classical in +/-- The quantity computed by `m.Bounded p ν (p.limit F ^ m.fuel p) (fun q => q.s.value p.P)`. -/ +def Job.Solves (p : Params) (ν : ℕ → K) := + m.Bounded p ν (p.limit F ^ m.fuel p) (fun q => q.s.value p.P) + +open scoped Classical in +/-- The condition `∀ l : Job F r t J L K N, l.fuel p < m.fuel p → l.n ≤ p.U → Covers l.a.ports +l.v (p.U - l.n) → l.Solves p ν` on the specified data. -/ +def Job.Subtasks (p : Params) (ν : ℕ → K) := + ∀ l : Job F r t J L K N, l.fuel p < m.fuel p → l.n ≤ p.U → + Covers l.a.ports l.v (p.U - l.n) → l.Solves p ν + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Intrinsic energies, marks and order signs -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset +variable {F J L K N T E V X : Type} {r t : ℕ} + +open scoped Classical in +theorem split_match {A B : Type} {R : A → B → Prop} {xs : List A} + {p q : List B} {x : B} (h : List.Forall₂ R xs (p ++ x :: q)) : + ∃ a b u, xs = a ++ u :: b ∧ List.Forall₂ R a p ∧ R u x ∧ List.Forall₂ R b q := by + induction p generalizing xs with + | nil => + cases h with + | cons hu hx => exact ⟨[], _, _, rfl, .nil, hu, hx⟩ + | cons y p ih => + cases h with + | @cons i _ _ _ hu he => + obtain ⟨a, b, u, eq, hp, hq, hz⟩ := ih he + exact ⟨i::a, b, u, congrArg (i :: ·) eq, .cons hu hp, hq, hz⟩ + +open scoped Classical in +theorem image_match {A B C : Type} {R : A → B → Prop} {xs : List A} {ys : List B} + {f : A → C} {g : B → C} (h : List.Forall₂ R xs ys) (he : ∀ a b, R a b → f a = g b) : + xs.map f = ys.map g := by + induction h with + | nil => rfl + | cons h _ ih => simp only [List.map_cons, he _ _ h, ih] + +open scoped Classical in +/-- Transforms the indexed data by `(us.map Entry.a).sum`. -/ +def eA (us : List (Entry F r t K N)) := (us.map Entry.a).sum +open scoped Classical in +/-- Transforms the indexed data by `(us.map Entry.b).sum`. -/ +def eB (us : List (Entry F r t K N)) := (us.map Entry.b).sum + +variable {R : Reference J L N V E T X} {β : V ⊕ ℕ → K} {ns : List ℕ} + {xs : List (Station F r t (Tag V T) (Stack X t ns))} {ys : List (Entry F r t K N)} + +open scoped Classical in +theorem match_a (h : List.Forall₂ (Represents R β ns) xs ys) : sumA xs = eA ys := + congrArg List.sum (image_match h fun _ _ h => h.left) + +open scoped Classical in +theorem match_b (h : List.Forall₂ (Represents R β ns) xs ys) : sumB xs = eB ys := + congrArg List.sum (image_match h fun _ _ h => h.right) + +open scoped Classical in +theorem match_pos (h : List.Forall₂ (Represents R β ns) xs ys) : + xs.map Station.pos = ys.map Entry.pos := image_match h fun _ _ h => h.pos + +open scoped Classical in +theorem match_role (h : List.Forall₂ (Represents R β ns) xs ys) : + xs.map (fun u => (u.pos, u.label.role)) = ys.map (fun u => (u.pos, u.role)) := + image_match h fun _ _ h => Prod.ext h.pos h.role + +variable {s : Stage F r t T V E X} {a : Record F r t J L K N} + +open scoped Classical in +theorem Matches.portWeight (h : Matches R β s a) (l : List (L × F)) : + Surface.portWeight s.scene.level (l.map (Prod.map R.edge id)) = Surface.portWeight a.level l + := by + simp [Surface.portWeight, Function.comp_def, h.level] + +open scoped Classical in +/-- Concatenates the components in the order `((a.rows v).map Entry.pos ++ (a.ports v).map +Prod.snd).toFinset`. -/ +def Record.sites (a : Record F r t J L K N) (v : J) := + ((a.rows v).map Entry.pos ++ (a.ports v).map Prod.snd).toFinset + +open scoped Classical in +theorem Matches.sites (h : Matches R β s a) (i : J) : (s.scene.cell (R.vertex i)).sites = a.sites i + := by + simp [Cell.sites, Cell.positions, Record.sites, match_pos (h.rows i), h.ports, Function.comp_def] + +namespace Job + +variable (m : Job F r t J L K N) + +open scoped Classical in +/-- Transforms the indexed data by `(m.tail.map Entry.pos).toFinset`. -/ +def B := (m.tail.map Entry.pos).toFinset +open scoped Classical in +/-- Transforms the indexed data by `((m.a.ports m.v).map Prod.snd).toFinset`. -/ +def seams := ((m.a.ports m.v).map Prod.snd).toFinset +open scoped Classical in +/-- The value specified by `m.B ∪ m.seams`. -/ +def A := m.B ∪ m.seams +open scoped Classical in +/-- The quantity computed by `(m.x.a + eA m.tail + portWeight m.a.level (m.a.ports m.v)) / 2`. -/ +def d := (m.x.a + eA m.tail + portWeight m.a.level (m.a.ports m.v)) / 2 +open scoped Classical in +/-- The quantity computed by `(m.x.b + eB m.tail) / 2`. -/ +def e := (m.x.b + eB m.tail) / 2 +open scoped Classical in +/-- Computes the order by the application `Motion.poleOrder P m.d m.e m.B`. -/ +def order (P : ℕ) := Motion.poleOrder P m.d m.e m.B +open scoped Classical in +/-- The quantity computed by `p.P * m.x.a + m.x.b + 2 * p.P * p.H`. -/ +def threshold (p : Params) := p.P * m.x.a + m.x.b + 2 * p.P * p.H + +end Job + +namespace Task + +variable [Field F] {p : Params} {m : Job F r t J L K N} (q : Task m p) + +open scoped Classical in +theorem ports : q.rest.ports = (m.a.ports m.v).map (Prod.map q.R.edge id) := by + have h := q.match'.ports m.v + rw [q.here] at h + exact h + +open scoped Classical in +theorem inserts : q.rest.inserts = m.B := congrArg List.toFinset (match_pos q.rows.2) + +open scoped Classical in +theorem seams : q.rest.seams = m.seams := by + simp [Cell.seams, Job.seams, q.ports, Function.comp_def] + +open scoped Classical in +theorem sites : q.rest.sites = m.A := by rw [Cell.sites_eq, q.inserts, q.seams]; rfl + +open scoped Classical in +theorem orderA : (q.s.scene.cell (q.R.vertex m.v)).orderA q.s.scene.level = m.d := by + rw [q.here] + change (m.x.a + sumA q.rest.stations + portWeight q.s.scene.level q.rest.ports) / 2 = _ + rw [match_a q.rows.2, q.ports, q.match'.portWeight] + rfl + +open scoped Classical in +theorem orderB : (q.s.scene.cell (q.R.vertex m.v)).orderB = m.e := by + rw [q.here] + change (m.x.b + sumB q.rest.stations) / 2 = _ + rw [match_b q.rows.2]; rfl + +end Task +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Uniform scalar combinations and expiration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset Function +variable {F J L K N : Type} [Field F] {r t : ℕ} {p : Params} + {m : Job F r t J L K N} {ν : ℕ → K} + +open scoped Classical in +theorem Script.card_pure (a : Record F r t J L K N) : Fintype.card (Script.pure a).I = 1 := + Fintype.card_unit + +open scoped Classical in +theorem Script.card_sum {I : Type} [Fintype I] (w : I → F) (f : I → Script F r t J L K N) + {k : ℕ} (h : ∀ i, Fintype.card (f i).I ≤ k) : + Fintype.card (Script.sum w f).I ≤ Fintype.card I * k := by + change Fintype.card (Σ i, (f i).I) ≤ _ + rw [Fintype.card_sigma] + simpa using sum_le_sum (s := univ) (fun i _ => h i) + +open scoped Classical in +theorem Job.vacuous {b : ℕ} (hb : 0 < b) (hn : m.n ≤ p.U) (h : ¬ Nonempty (Task m p)) (f) : + m.Bounded p ν b f := + ⟨Script.pure m.a, Script.ordered_pure _ hn, by rwa [Script.card_pure], fun q => (h ⟨q⟩).elim⟩ + +open scoped Classical in +theorem Job.combine {I : Type} [Fintype I] (w : I → F) (f : I → ∀ q : Task m p, q.X → F) + (h : ∀ i, m.Solvable p ν (f i)) (fuel : 0 < m.fuel p) + (count : Fintype.card I ≤ p.M * window p.P p.g p.H p.D) : + m.Bounded p ν (p.limit F ^ m.fuel p) (fun q x => ∑ i, w i * f i q x) := by + unfold Solvable Bounded at h + choose s hs hc he using h + refine ⟨Script.sum w s, Script.ordered_sum w s hs, ?_, fun q => Script.executes_sum w s _ (fun i + => he i q)⟩ + calc + _ ≤ Fintype.card I * (p.fan F * p.limit F ^ (m.fuel p - 1)) := Script.card_sum w s hc + _ ≤ (p.M + 1) * window p.P p.g p.H p.D * (p.fan F * p.limit F ^ (m.fuel p - 1)) := + Nat.mul_le_mul_right _ (count.trans (Nat.mul_le_mul_right _ (Nat.le_succ _))) + _ = p.limit F * p.limit F ^ (m.fuel p - 1) := by + rw [← mul_assoc] + congr 1 + unfold Params.limit Params.fan breadth width; ring + _ = _ := by rw [← pow_succ', Nat.sub_add_cancel fuel] + +open scoped Classical in +theorem Task.finished (q : Task m p) (c : q.s.Ct) (n : ℕ) + (hc : ∀ a ∈ c.stations, idle q.allowed (q.R.vertex m.v) a) : + let s := {q.s.put (q.R.vertex m.v) c with expired := n} + Calm s ∧ pending s ⊆ q.allowed := by + apply idle_done + intro v a ha + change a ∈ (update q.s.scene.cell (q.R.vertex m.v) c v).stations at ha + by_cases hv : v = q.R.vertex m.v + · subst v; rw [update_self] at ha; exact hc a ha + · rw [update_of_ne hv] at ha; exact q.away v hv a ha + +open scoped Classical in +theorem Job.expire (he : m.n = p.U) : m.Solves p ν := by + let r := m.a.edit m.v (m.x.freeze :: m.tail) + refine ⟨Script.pure r, Script.ordered_pure r he.le, + by rw [Script.card_pure]; exact pow_pos (p.limit_pos F) _, fun q => ?_⟩ + let v := q.R.vertex m.v + let u := {q.mover with label := {q.mover.label with role := Role.collector}} + let c := q.rest.insert u + let s := q.s.freeze v q.rest q.mover + have hstep : q.s.Step p.P p.g p.H p.U s := + .expire _ _ _ _ q.here (q.rows.1.role.trans (m.active.trans (congrArg Role.active he))) + q.move.ready + have hu : Update p.P p.g p.H p.U q.R q.β q.β q.s s r [] := + ⟨.single hstep, q.valid.freeze _ _ _ q.here q.move.ready, + q.match'.edit m.v c _ (by rw [q.here]; rfl) (.cons q.rows.1.freeze q.rows.2) _, + Outside.edit v (Set.mem_range_self m.v) c _⟩ + obtain ⟨hc, hp⟩ := q.finished c (q.s.expired + 1) (by + intro a ha + rcases List.mem_cons.mp ha with rfl|ha + · simp [idle, u, Role.clock] + · exact q.others _ ha) + change q.executes (Script.pure r) (q.s.value p.P) + rw [Stage.freeze_value _ _ _ q.here] + exact Script.executes_pure hu hc hp + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Two locally identified seam sockets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset Motion Stage +variable {F J L K N : Type} {r t : ℕ} {p : Params} {m : Job F r t J L K N} + +open scoped Classical in +/-- The data for the gate construction, including `i`, `w`, `z`, `y`, `left₁`. -/ +structure Gate (m : Job F r t J L K N) where + /-- The `Gate` field of type `L`. -/ + i : L + /-- The `Gate` field of type `J`. -/ + w : J + /-- The `Gate` field of type `F`. -/ + z : F + /-- The `Gate` field of type `F`. -/ + y : F + /-- The `Gate` component of type `List (L × F)`. -/ + left₁ : List (L × F) + /-- The `Gate` component of type `List (L × F)`. -/ + left₂ : List (L × F) + /-- The `Gate` component of type `List (L × F)`. -/ + right₁ : List (L × F) + /-- The `Gate` component of type `List (L × F)`. -/ + right₂ : List (L × F) + ne : m.v ≠ w + left : m.a.ports m.v = left₁ ++ (i, z) :: left₂ + right : m.a.ports w = right₁ ++ (i, y) :: right₂ + +namespace Gate + +variable (G : Gate m) + +open scoped Classical in +theorem of_cover (hc : Covers m.a.ports m.v (p.U - m.n)) (hn : m.n < p.U) {z : F} + (hz : z ∈ m.seams) : ∃ G : Gate m, G.z = z ∧ Covers m.a.ports G.w (p.U - (m.n + 1)) := by + obtain ⟨⟨i, y⟩, hi, hy⟩ := List.mem_map.mp (List.mem_toFinset.mp hz) + change y = z at hy + subst y + rw [show p.U - m.n = (p.U - (m.n + 1)) + 1 by omega] at hc + obtain ⟨w, y, ne, hw, ht⟩ := hc (i, z) hi + obtain ⟨l, k, hl⟩ := List.append_of_mem hi + obtain ⟨a, b, hr⟩ := List.append_of_mem hw + exact ⟨⟨i, w, z, y, l, k, a, b, ne.symm, hl, hr⟩, rfl, ht⟩ + +open scoped Classical in +/-- Uses `m.a.level G.i` as the representation. -/ +def level := m.a.level G.i +open scoped Classical in +/-- Concatenates the components in the order `eA m.tail + portWeight m.a.level (G.left₁ ++ +G.left₂)`. -/ +def na := eA m.tail + portWeight m.a.level (G.left₁ ++ G.left₂) +open scoped Classical in +/-- Computes the nb by the application `eB m.tail`. -/ +def nb (_ : Gate m) := eB m.tail +open scoped Classical in +/-- Concatenates the components in the order `eA (m.a.rows G.w) + portWeight m.a.level (G.right₁ +++ G.right₂)`. -/ +def fa := eA (m.a.rows G.w) + portWeight m.a.level (G.right₁ ++ G.right₂) +open scoped Classical in +/-- Computes the c by the application `m.a.sites G.w`. -/ +def C := m.a.sites G.w + +variable [Field F] (q : Task m p) + +open scoped Classical in +/-- Transforms the indexed data by `⟨G.left₁.map (Prod.map q.R.edge id), G.left₂.map (Prod.map +q.R.edge id), q.rest.stations⟩`. -/ +def near : q.s.Sock := ⟨G.left₁.map (Prod.map q.R.edge id), G.left₂.map (Prod.map q.R.edge id), + q.rest.stations⟩ +open scoped Classical in +/-- The value specified by `⟨G.right₁.map (Prod.map q.R.edge id), G.right₂.map (Prod.map +q.R.edge id), (q.s.scene.cell (q.R.vertex G.w)).stations⟩`. -/ +def far : q.s.Sock := ⟨G.right₁.map (Prod.map q.R.edge id), G.right₂.map (Prod.map q.R.edge id), + (q.s.scene.cell (q.R.vertex G.w)).stations⟩ + +open scoped Classical in +theorem near_eq : (G.near q).plug (q.R.edge G.i) G.z = q.rest := by + have h := q.ports + rw [G.left, List.map_append, List.map_cons] at h + change (⟨_, q.rest.stations⟩ : q.s.Ct) = _ + rw [show (G.near q).before ++ (q.R.edge G.i, G.z) :: (G.near q).after = q.rest.ports from h.symm] + +open scoped Classical in +theorem far_eq : (G.far q).plug (q.R.edge G.i) G.y = q.s.scene.cell (q.R.vertex G.w) := by + have h := q.match'.ports G.w + rw [G.right, List.map_append, List.map_cons] at h + change (⟨_, (q.s.scene.cell (q.R.vertex G.w)).stations⟩ : q.s.Ct) = _ + rw [show (G.far q).before ++ (q.R.edge G.i, G.y) :: (G.far q).after = _ from h.symm] + +open scoped Classical in +theorem nearA : (G.near q).base.bigA q.s.scene.level = G.na := by + unfold na near Socket.base Cell.bigA + dsimp only + rw [match_a q.rows.2, ← List.map_append, q.match'.portWeight] + +open scoped Classical in +theorem nearB : sumB (G.near q).stations = G.nb := match_b q.rows.2 + +open scoped Classical in +theorem farA : (G.far q).base.bigA q.s.scene.level = G.fa := by + unfold fa far Socket.base Cell.bigA + dsimp only + rw [match_a (q.match'.rows G.w), ← List.map_append, q.match'.portWeight] + +open scoped Classical in +theorem available_ports : + Unused (q.R.edge G.i) (G.near q).base.ports ∧ Unused (q.R.edge G.i) (G.far q).base.ports ∧ + ∀ k, k ≠ q.R.vertex m.v → k ≠ q.R.vertex G.w → Unused (q.R.edge G.i) (q.s.ports k) := by + let v := q.R.vertex m.v + let w := q.R.vertex G.w + let i := q.R.edge G.i + have l : ((G.near q).plug i G.z).ports = q.s.ports v := by + unfold Stage.ports; rw [q.here, G.near_eq]; rfl + have r : ((G.far q).plug i G.y).ports = q.s.ports w := congrArg Cell.ports (G.far_eq q) + refine ⟨(G.near q).unused i G.z (by rw [l]; exact q.layout.unique _), + (G.far q).unused i G.y (by rw [r]; exact q.layout.unique _), fun k hv hw a ha e => ?_⟩ + have hl := (q.layout.incident v i).mp (List.mem_map.mpr ⟨_, l ▸ (G.near q).mem i G.z, rfl⟩) + have hr := (q.layout.incident w i).mp (List.mem_map.mpr ⟨_, r ▸ (G.far q).mem i G.y, rfl⟩) + have ht := (q.layout.incident k i).mp (List.mem_map.mpr ⟨a, ha, e⟩) + have ne : v ≠ w := q.R.vertex.injective.ne G.ne + grind + +include q in +open scoped Classical in +theorem room : + m.A.card ≤ p.M ∧ G.C.card ≤ p.M ∧ + m.x.a + m.x.b + (G.level + G.na) + G.nb ≤ p.D ∧ G.level + G.fa ≤ p.D ∧ + (m.a.rows G.w).length ≤ p.M := by + have h := q.room _ .refl + obtain ⟨h₁, h₂⟩ := q.move.room h + change q.rest.sites.card ≤ _ at h₁ + rw [q.sites] at h₁ + change m.x.a + m.x.b + q.rest.bigA _ + sumB q.rest.stations ≤ _ at h₂ + have e : q.rest.bigA q.s.scene.level = G.level + G.na := by + rw [← G.near_eq q, Socket.bigA, q.match'.level, G.nearA]; rfl + rw [e, match_b q.rows.2] at h₂ + obtain ⟨h₃, h₄⟩ := h (q.R.vertex G.w) + have size := (q.s.scene.cell (q.R.vertex G.w)).sizes h₃ + rw [q.match'.sites] at size + have ee := (q.match'.rows G.w).length_eq + simp only [Cell.positions, List.length_append, List.length_map] at h₃ + rw [← G.far_eq q, Socket.bigA, q.match'.level, G.farA] at h₄ + exact ⟨h₁, size, h₂, (Nat.le_add_right _ _).trans h₄, by omega⟩ + +end Gate +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Choosing the same seam expansion in every ambient graph -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Gate + +open Finset Motion Stage +variable {F J L K N : Type} [Field F] [Fintype F] {r t : ℕ} {p : Params} {m : Job F r t J L K N} + +variable (G : Gate m) + +open scoped Classical in +/-- Computes the near set by the application `fresh m.A`. -/ +def nearSet (_ : Gate m) := fresh m.A +open scoped Classical in +/-- Computes the far set by the application `powered P (fresh G.C)`. -/ +def farSet (P : ℕ) := powered P (fresh G.C) + +open scoped Classical in +/-- The value specified by `(mem_image.mp i.property).choose`. -/ +def root (P : ℕ) (i : G.farSet P) : F := (mem_image.mp i.property).choose + +open scoped Classical in +/-- The quantity computed by `Hop P ((G.level + m.x.a + G.na) / 2) G.level m.x.a j G.nearSet +(G.farSet P)`. -/ +abbrev indices (P : ℕ) (j : ℤ) := Hop P ((G.level + m.x.a + + G.na) / 2) G.level m.x.a j G.nearSet (G.farSet P) + +variable (d l : ℕ) [ExpChar F d] (hP : p.P = d ^ l) (hF : p.M * (2 * p.D + 1) < Fintype.card F) + (j : ℤ) (hj : m.threshold p ≤ -j) + +open scoped Classical in +/-- Builds `Passage p.P q.mover where z` with the specified `root`, `hroot`, `hz`, `apply`. -/ +def path (q : Task m p) : Passage p.P q.mover where + z := G.z + y := G.y + A := powered p.P m.A + B := m.B + C := powered p.P G.C + U := G.nearSet + V := G.farSet p.P + root := G.root p.P + hroot i := (mem_image.mp i.property).choose_spec.2 + hz := by + apply mem_image_of_mem + rw [← q.sites, ← G.near_eq q, Socket.sites] + exact mem_insert_self .. + hy := by + apply mem_image_of_mem + unfold C + rw [← q.match'.sites, ← G.far_eq q, Socket.sites] + exact mem_insert_self .. + hb := by + rw [← q.inserts] + exact disjoint_right.mp (q.rest.disjoint (q.move.distinct q.valid).1) + (q.rest.mem_seams (G.near_eq q ▸ (G.near q).mem (q.R.edge G.i) G.z)) + hu := by rw [hP, powered_iff, ← q.sites]; exact (q.move.distinct q.valid).2 + hu' := by rw [← q.inserts]; exact fun e => (q.move.distinct q.valid).2 (q.rest.inserts_sub e) + hU := disjoint_left.mpr (fun _ h e => (mem_sdiff.mp h).2 (mem_union_left _ e)) + hV := disjoint_left.mpr (by + intro x hx he + obtain ⟨y, hy, rfl⟩ := mem_image.mp hx + rw [hP, powered_iff] at he + exact (mem_sdiff.mp hy).2 he) + e := G.level + a := G.na + b := G.nb + c := G.fa + sizeU := by + obtain ⟨hA, _, h, _, _⟩ := G.room q + have hB := (card_le_card (show m.B ⊆ m.A from subset_union_left)).trans hA + exact (Nat.mul_le_mul hB (by change (m.x.b + G.nb) / 2 ≤ _; omega)).trans_lt (fresh_size hA hF) + sizeV := by + obtain ⟨_, hC, h, h', _⟩ := G.room q + have hs : (G.farSet p.P).card = (fresh G.C).card := by + rw [farSet, powered, hP, card_image_of_injective _ (power_injective d l)] + rw [hs] + refine (Nat.mul_le_mul (card_image_le.trans hC) ?_).trans_lt (fresh_size hC hF) + change (G.level + m.x.a + G.fa) / 2 ≤ _ + omega + H := p.H + j := j + low := hj + +open scoped Classical in +theorem fits (q : Task m p) : + (G.path d l hP hF j hj q).Fits (G.near q).base (G.far q).base q.s.scene.level := by + refine ⟨?_, ⟨(G.far q).base.inserts, ?_⟩, G.nearA q, G.nearB q, G.farA q⟩ + · have he := G.near_eq q + have hs : m.A = insert G.z (G.near q).base.sites := by rw [← q.sites, ← he, Socket.sites] + have hn := (G.near q).avoids _ _ (by rw [he]; exact (q.move.distinct q.valid).1) + change Cell.Fixed p.P _ ((powered p.P m.A).erase (G.z ^ p.P)) m.B + rw [hP] + exact (G.near q).base.fixed_erase d l _ hn _ _ (by rw [hs]; exact subset_insert ..) + (by rw [← q.inserts, ← he]; rfl) + · have he := G.far_eq q + have hs : G.C = insert G.y (G.far q).base.sites + := by unfold C; rw [← q.match'.sites, ← he, Socket.sites] + have hn := (G.far q).avoids _ _ (he.symm ▸ q.valid.distinct (q.R.vertex G.w)) + change Cell.Fixed p.P _ ((powered p.P G.C).erase (G.y ^ p.P)) _ + rw [hP] + exact (G.far q).base.fixed_erase d l _ hn _ _ (by rw [hs]; exact subset_insert ..) Subset.rfl + +open scoped Classical in +theorem uniform (q v : Task m p) (i : G.indices p.P j) : + (G.path d l hP hF j hj q).signed q.s.scene.level (G.near q) (G.far q) d l hP i = + (G.path d l hP hF j hj v).signed v.s.scene.level (G.near v) (G.far v) d l hP i := by + have left (q : Task m p) (e k : ℕ) : (G.near q).sign q.s.scene.level e k = + (-1 : F) ^ ((k + eA m.tail + portWeight m.a.level G.left₁) * e) := by + simp only [Socket.sign, near, match_a q.rows.2, q.match'.portWeight] + have right (q : Task m p) (e k : ℕ) : (G.far q).sign q.s.scene.level e k = + (-1 : F) ^ ((k + eA (m.a.rows G.w) + portWeight m.a.level G.right₁) * e) := by + simp only [Socket.sign, far, match_a (q.match'.rows G.w), q.match'.portWeight] + simp only [Passage.signed, left, right] + rcases p with ⟨P, g, H, U, M, D⟩ + change P = d ^ l at hP + subst P + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Gate +end + +/- # Rotating one recorded station to the front of a cell -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset Function Stage +variable {F J L K N V E T X : Type} [Field F] [Fintype V] [Fintype E] {r t : ℕ} + {p : Params} {a : Record F r t J L K N} {s : Stage F r t T V E X} + {R : Reference J L N V E T X} {β : V ⊕ ℕ → K} + +open scoped Classical in +/-- The quantity computed by `(-1) ^ (eA ls * u.a + eB ls * u.b)`. -/ +def rotSign (ls : List (Entry F r t K N)) (u : Entry F r t K N) : F := + (-1) ^ (eA ls * u.a + eB ls * u.b) + +open scoped Classical in +theorem Matches.rotate (h : Matches R β s a) (valid : s.Valid p.U) (j : J) + (l rest : List s.St) (u : s.St) (ls ts : List (Entry F r t K N)) (v : Entry F r t K N) + (here : (s.scene.cell (R.vertex j)).stations = l ++ u :: rest) + (hl : List.Forall₂ (Represents R β s.hidden) l ls) + (ht : List.Forall₂ (Represents R β s.hidden) rest ts) (hu : Represents R β s.hidden u v) : + let s' := s.reord (R.vertex j) l [u] rest + Update p.P p.g p.H p.U R β β s s' (a.edit j (v :: (ls ++ ts))) [] ∧ + ∀ f : Test F r t, Signed f → s.observe p.P (R.vertex j) f = + fun x => rotSign ls v * s'.observe p.P (R.vertex j) f x := by + intro s' + have perm : (s.scene.cell (R.vertex j)).stations.Perm ([u] ++ l ++ rest) := by + rw [here] + exact List.perm_middle + refine ⟨⟨.single (.perm _ _ _ perm), valid.perm _ _ perm, ?_, + Outside.put _ (Set.mem_range_self j) _⟩, ?_⟩ + · exact h.edit j ⟨(s.scene.cell (R.vertex j)).ports, u :: (l ++ rest)⟩ + _ rfl (.cons hu (List.rel_append hl ht)) s.expired + · intro f hf + have e := s.scene.rotate (P := p.P) (R.vertex j) f hf l [u] rest (by simpa using here) + have ha : sumA [u] = v.a := by simp [sumA, hu.left] + have hb : sumB [u] = v.b := by simp [sumB, hu.right] + rw [match_a hl, match_b hl, ha, hb] at e + funext x + unfold observe + rw [funext e, trace_mul] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Resuming a move or stopping at a collector -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +variable {F J L K N : Type} [Field F] {r t : ℕ} {m : Job F r t J L K N} {p : Params} {ν : ℕ → K} + +open scoped Classical in +/-- The resumes of type `Prop` for the given inputs. -/ +def Script.Resumes (f : Script F r t J L K N) (p : Params) (a : Record F r t J L K N) (v : J) : + Prop := + ∀ (w : World p a) (c : w.s.Ct) (u : w.s.St), w.s.scene.cell (w.R.vertex v) = c.insert u → + (∀ z ∈ c.stations, idle w.allowed (w.R.vertex v) z) → + (∀ k, k ≠ w.R.vertex v → ∀ z ∈ (w.s.scene.cell k).stations, idle w.allowed k z) → + f.Executes p.P p.g p.H p.U w.R w.β w.s w.allowed (w.s.value p.P) + +open scoped Classical in +theorem Job.Subtasks.resume (rec : m.Subtasks p ν) (a : Record F r t J L K N) (v : J) + (x : Entry F r t K N) (xs : List (Entry F r t K N)) (n : ℕ) + (row : a.rows v = x::xs) (role : x.role = .active n ∨ x.role = .collector) (hn : n ≤ p.U) + (safe : Covers a.ports v (p.U - n)) (decr : (p.U - n) * (p.M + 1) + xs.length < m.fuel p) : + ∃ f : Script F r t J L K N, f.Ordered ν n p.U ∧ + Fintype.card f.I ≤ p.limit F ^ (m.fuel p - 1) ∧ f.Resumes p a v := by + rcases role with ha|hc + · let j : Job F r t J L K N := ⟨a, v, x, xs, n, row, ha⟩ + obtain ⟨f, hf, hc, he⟩ := rec j decr hn safe + have hd : j.fuel p ≤ m.fuel p - 1 := Nat.le_pred_of_lt decr + exact ⟨f, hf, hc.trans (Nat.pow_le_pow_right (p.limit_pos F) hd), fun w c u hv h₁ h₂ => he ⟨w, + c, u, hv, h₁, h₂⟩⟩ + refine ⟨Script.pure a, Script.ordered_pure _ hn, + by rw [Script.card_pure]; exact pow_pos (p.limit_pos F) _, fun w c u hv h₁ h₂ => ?_⟩ + have h := w.match'.rows v + rw [hv, row] at h + have hrole := (List.forall₂_cons.mp h).1.role.trans hc + have closed : Calm w.s ∧ pending w.s ⊆ w.allowed := by + apply idle_done + intro i z hz + by_cases e : i = w.R.vertex v + · subst i; rw [hv] at hz + rcases List.mem_cons.mp hz with rfl|hz + · simp [idle, hrole, Role.clock] + · exact h₁ z hz + · exact h₂ i e z hz + exact Script.executes_pure (.refl w.match' w.valid) closed.1 closed.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Update.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Update.lean new file mode 100644 index 0000000000..578e6d6efd --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/Update.lean @@ -0,0 +1,303 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.View +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality + +/-! +# Reusing short key names + +Each private selector starts with the color of its home cell. Fresh +residue names include a wave number and a crossing ordinal. An +available separation radius shrinks by twice the region diameter per +wave. Global uniqueness of the short names is unnecessary. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +variable {F T V E X K N : Type} {r t P g H U M D n Q W : ℕ} + +open scoped Classical in +/-- Indexes the stamp by the coordinates of `Fin Q × Option (Fin W × Fin (U + 1))`. -/ +abbrev Stamp (Q W U : ℕ) := Fin Q × Option (Fin W × Fin (U + 1)) + +open scoped Classical in +/-- The value specified by `(color v, some (i, ⟨min k U, by omega⟩))`. -/ +def created (color : V → Fin Q) (i : Fin W) (v : V) (k : ℕ) : Stamp Q W U := + (color v, some (i, ⟨min k U, by omega⟩)) + +open scoped Classical in +/-- The condition `∀ i, a.2 = some i → i.1.val < n` on the specified data. -/ +def earlier (n : ℕ) (a : Stamp Q W U) : Prop := + ∀ i, a.2 = some i → i.1.val < n + +open scoped Classical in +theorem earlier.created (color : V → Fin Q) (i : Fin W) (v : V) (k : ℕ) : + earlier (i.val + 1) (Local.created (U := U) color i v k) := by + rintro _ h + cases Option.some.inj h + exact Nat.lt_succ_self _ + +open scoped Classical in +theorem earlier.ne_created (color : V → Fin Q) (i : Fin W) {s : Stamp Q W U} + (h : earlier i.val s) (v : V) (k : ℕ) : s ≠ Local.created color i v k := by + rintro rfl + exact Nat.lt_irrefl _ (h _ rfl) + +open scoped Classical in +/-- The condition `∀ v w, near v w → ∀ j ∈ s.footprint v, ∀ k ∈ s.footprint w, β j = β k → j = +k` on the specified data. -/ +def Distinct (near : V → V → Prop) (s : Stage F r t T V E X) (β : V ⊕ ℕ → K) : Prop := + ∀ v w, near v w → ∀ j ∈ s.footprint v, ∀ k ∈ s.footprint w, β j = β k → j = k + +open scoped Classical in +/-- The data for the clean construction, including `distinct`, `old`. -/ +structure Clean (near : V → V → Prop) (s : Stage F r t T V E X) + (β : V ⊕ ℕ → Stamp Q W U) (i : ℕ) : Prop where + distinct : Distinct near s β + old : ∀ v j, j ∈ s.footprint v → earlier i (β j) + +namespace Wave +variable [Field F] {key : V → X → ℕ} {s q : Stage F r t T V E X} + {β γ : V ⊕ ℕ → Stamp Q W U} + {C : Fin n → Command F r t T V E X (Stamp Q W U) N P g H U M D key} {a : Index C} + +open scoped Classical in +theorem Origins.clean (h : Origins C a s q β γ) + {outer inner : V → V → Prop} (color : V → Fin Q) (wave : Fin W) + (old : Clean outer s β wave.val) + (unique : ∀ v w, outer v w → color v = color w → v = w) + (room : ∀ v w v' w', inner v w → Together C v v' → Together C w w' → outer v' w') + (root : Fin n ↪ V) (home : ∀ i, root i ∈ Set.range (C i).ref.vertex) + (fresh : ∀ i, (C i).action.Ordered (created color wave (root i)) 0 U) : + Clean inner q γ (wave.val + 1) := by + obtain ⟨o, ho⟩ := h + have from_key (v j) (hj : j ∈ q.footprint v) : + (∃ w, Together C v w ∧ j ∈ s.footprint w ∧ γ j = β j) ∨ + ∃ i k, Together C v (root i) ∧ k < U ∧ j = .inr (o i + k) ∧ + γ j = created color wave (root i) k := by + rcases ho v j hj with ⟨w, hw, hm, hg, _⟩ | ⟨i, hi, k, hk, hg⟩ + · exact .inl ⟨w, hw, hm, hg⟩ + · obtain ⟨hb, he⟩ := fresh i (a i) + simp only [zero_add] at hb he + exact .inr ⟨i, k.val, .inr ⟨i, hi, home i⟩, k.isLt.trans_le hb, hk, + (congrArg Prod.fst hg).trans (he k)⟩ + constructor + · intro v w hw j hj k hk he + rcases from_key v j hj with ⟨a, ha, hb, hc⟩ | ⟨i, l, ha, hb, hi, hc⟩ <;> + rcases from_key w k hk with ⟨b, ha', hb', hc'⟩ | ⟨i', l', ha', hb', hi', hc'⟩ + · exact old.distinct _ _ (room _ _ _ _ hw ha ha') _ hb _ hb' (hc.symm.trans (he.trans hc')) + · exact (earlier.ne_created color wave (old.old _ _ hb) _ _ (hc.symm.trans (he.trans hc'))).elim + · exact (earlier.ne_created color wave (old.old _ _ hb') _ _ (hc'.symm.trans (he.symm.trans + hc))).elim + · have e := hc.symm.trans (he.trans hc') + have root_eq := unique _ _ (room _ _ _ _ hw ha ha') (congrArg Prod.fst e) + have eq := root.injective root_eq + have hval := congrArg (fun x => x.2.val) (Option.some.inj (congrArg Prod.snd e)) + change min l U = min l' U at hval + rw [min_eq_left hb.le, min_eq_left hb'.le] at hval + rw [hi, hi', eq, hval] + · intro v j hj + rcases from_key v j hj with ⟨w, _, hm, hg⟩ | ⟨i, k, _, _, _, hg⟩ + · rw [hg] + exact fun _ he => Nat.lt_succ_of_lt (old.old _ _ hm _ he) + · rw [hg] + exact earlier.created _ _ _ _ + +end Wave +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# Updating a global record by disjoint regional scripts + +A touched vertex or seam takes the data returned by its unique +region. The port list never changes. All other records pass through. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Wave + +variable {I V A : Type} {J : I → Type} + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def write (addr : ∀ i, J i ↪ V) (old : V → A) (data : ∀ i, J i → A) : V → A := + Function.extend (fun t : Σ i, J i => addr t.1 t.2) (fun t => data t.1 t.2) old + +open scoped Classical in +theorem write_at (addr : ∀ i, J i ↪ V) (old : V → A) (data : ∀ i, J i → A) + (h : ∀ i j, i ≠ j → Disjoint (Set.range (addr i)) (Set.range (addr j))) + (i : I) (v : J i) : write addr old data (addr i v) = data i v := by + have hinj : Function.Injective (fun t : Σ i, J i => addr t.1 t.2) := by + rintro ⟨i, v⟩ ⟨j, w⟩ eq + have he : i = j := by + by_contra hn + exact Set.disjoint_left.mp (h i j hn) ⟨v, rfl⟩ ⟨w, eq.symm⟩ + subst j + rw [show v = w from (addr i).injective eq] + exact hinj.extend_apply _ _ ⟨i, v⟩ + +open scoped Classical in +theorem write_away (addr : ∀ i, J i ↪ V) (old : V → A) (data : ∀ i, J i → A) + (v : V) (h : ¬ ∃ i, v ∈ Set.range (addr i)) : write addr old data v = old v := by + apply Function.extend_apply' + rintro ⟨⟨i, j⟩, e⟩ + exact h ⟨i, j, e⟩ + +variable {F T E X K N : Type} [Field F] {r t P g H U M D n : ℕ} {key : V → X → ℕ} + (C : Fin n → Command F r t T V E X K N P g H U M D key) + (G : Record F r t V E K N) + +open scoped Classical in +/-- Builds `Record F r t V E K N where rows` with the specified `rows`, `ports`, `level`, +`footprint`. -/ +def update (i : Index C) : Record F r t V E K N where + rows := write (fun j => (C j).ref.vertex) G.rows (fun j => ((C j).action.result (i j)).rows) + ports := G.ports + level := write (fun j => (C j).ref.edge) G.level (fun j => ((C j).action.result (i j)).level) + footprint := write (fun j => (C j).ref.vertex) G.footprint + (fun j => ((C j).action.result (i j)).footprint) + +variable {J' L' : Type} (R : Reference J' L' N V E T X) + +open scoped Classical in +/-- The data for the prepared construction, including `separate`, `views`. -/ +structure Prepared : Prop where + separate : Separate C + key_eq : R.key = key + name_eq : ∀ i, (C i).ref.name = R.name + ext_eq : ∀ i, (C i).ref.ext = R.ext + views : ∀ i, View G (C i).ref.vertex (C i).ref.edge (C i).input + +variable {C G R} {s q : Stage F r t T V E X} {β γ : V ⊕ ℕ → K} {a : Index C} + +open scoped Classical in +theorem Prepared.inputs (h : Prepared C G R) (e : Matches R.world β s G) : + ∀ i, Matches (C i).ref β s (C i).input := + fun i => e.view (h.views i) (h.key_eq.trans (C i).shared.symm) (h.name_eq i).symm (h.ext_eq + i).symm + +open scoped Classical in +theorem Prepared.outputs (h : Prepared C G R) (e : Matches R.world β s G) + (done : Finish C s q β γ a) : Matches R.world γ q (update C G a) := by + have out := done.outside.rekey h.key_eq.symm + obtain ⟨π, hb, hk, hw⟩ := out.project + have vertex (v : V) : + List.Forall₂ (Represents R.world γ q.hidden) (q.scene.cell v).stations ((update C G a).rows + v) ∧ + (q.footprint v).image γ = (update C G a).footprint v ∧ + ∀ j ∈ q.footprint v, available q.hidden.length j := by + by_cases hv : v ∈ vertices C + · obtain ⟨i, j, rfl⟩ := hv + unfold update + simp only [write_at _ _ _ h.separate.vertex i j] + refine ⟨?_, (done.result i).footprint j, (done.result i).known j⟩ + exact ((done.result i).rows j).imp fun _ _ hx => + hx.change (s := q) ((C i).shared.trans h.key_eq.symm) (h.name_eq i) (h.ext_eq i) + · unfold update + simp only [write_away _ _ _ v hv] + rw [hw v hv, out.footprint v hv] + refine ⟨?_, ?_, fun j hj => out.known j (e.known v j hj)⟩ + · change List.Forall₂ _ (List.map _ _) _ + rw [List.forall₂_map_left_iff] + exact (e.rows v).imp (fun _ _ h' => Represents.project (R := R.world) out π hb hk h') + · rw [← e.footprint] + exact Finset.image_congr fun j hj => out.old j (e.known v j hj) + refine ⟨fun v => (vertex v).1, ?_, ?_, fun v => (vertex v).2.1, fun v => (vertex v).2.2⟩ + · intro v + exact (congrFun done.reach.ports_eq v).trans (e.ports v) + · intro j + change q.scene.level j = (update C G a).level j + simp only [update] + by_cases hj : j ∈ edges C + · obtain ⟨i, k, rfl⟩ := hj + rw [write_at _ _ _ h.separate.edge i k] + exact (done.result i).level k + · rw [write_away _ _ _ j hj, out.level j hj] + exact e.level j + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Wave +end + +/- +# Wiring programs independent of station tables + +A program is selected using the sizes of the marks and the local +one-species wiring rule. These are bounded independently of the +number of species and of the working field. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale + +open Sphere Routing.Private Finset +variable {F K T E X : Type} [Field F] [Field K] [Algebra K F] {ℓ D g b d m : ℕ} + +open scoped Classical in +/-- Information on which the two-sphere program is allowed to depend. -/ +abbrev Pattern (K : Type) (D g n : ℕ) := + Σ s : Fin (100 * D + 1), Σ p : Fin (2 * g + 1), + Σ w : {u : Fin (s.val + p.val) → Fin (n + 1) // (∑ i, 4 * (u i).val) ≤ n}, + Plant.Bits (fun i => (w.val i).val) → K + +open scoped Classical in +/-- Builds `Template K F Unit Unit Unit r where stations` with the specified `Template`, +`ports`, `label`, `seam`. -/ +def Pattern.template (p : Pattern K D g (probes ℓ D)) (F : Type) [Field F] (r : ℕ) : + Template K F Unit Unit Unit r where + stations := p.1.val + ports := p.2.1.val + label _ := () + seam _ := () + width i := (p.2.2.1.val i).val + weight _ _ _ := 0 + rule := p.2.2.2 + +open scoped Classical in +/-- The value specified by `(h F _ _ _ inferInstance inferInstance _ p.2.2.1.2 +(Nat.le_of_lt_succ p.1.isLt) (Nat.le_of_lt_succ p.2.1.isLt)).some`. -/ +def Pattern.patch (p : Pattern K D g (probes ℓ D)) (h : Ready K ℓ D g m b d) : + (p.template F (d * b)).Patch m (probes ℓ D) (rate ℓ D) := + (h F _ _ _ inferInstance inferInstance _ p.2.2.1.2 + (Nat.le_of_lt_succ p.1.isLt) (Nat.le_of_lt_succ p.2.1.isLt)).some + +open scoped Classical in +/-- The pattern of type `Pattern K D g (probes ℓ D)` for the given inputs. -/ +def pattern (u : Template K F T E X (d * b)) (hw : (∑ i, 4 * u.width i) ≤ probes ℓ D) + (hs : u.stations ≤ 100 * D) (hp : u.ports ≤ 2 * g) : Pattern K D g (probes ℓ D) := + ⟨⟨_, Nat.lt_succ_of_le hs⟩, ⟨_, Nat.lt_succ_of_le hp⟩, ⟨fun i => ⟨u.width i, by + have := (single_le_sum (fun j _ => Nat.zero_le (4 * u.width j)) (mem_univ i)).trans hw + omega⟩, hw⟩, u.rule⟩ + +open scoped Classical in +/-- The canonical of type `u.Patch m (probes ℓ D) (rate ℓ D)`, constructed using `(pattern u hw +hs hp).patch (F := F) h`. -/ +def canonical (h : Ready K ℓ D g m b d) (u : Template K F T E X (d * b)) + (hw : (∑ i, 4 * u.width i) ≤ probes ℓ D) (hs : u.stations ≤ 100 * D) (hp : u.ports ≤ 2 * g) : + u.Patch m (probes ℓ D) (rate ℓ D) := + let v := (pattern u hw hs hp).patch (F := F) h + ⟨v.pos, v.program, v.small, v.sound⟩ + +variable [Fintype K] (F) + +open scoped Classical in +/-- The pool has bounded cardinality even when the working extension +changes. Its entries can be arbitrary field tables. -/ +def pool (h : Ready K ℓ D g m b d) : Finset (Program F (probes ℓ D) b d) := + univ.image (fun i : Pattern K D g (probes ℓ D) => (i.patch (F := F) h).program) + +open scoped Classical in +theorem pool_bound (h : Ready K ℓ D g m b d) : + (pool F h).card ≤ Fintype.card (Pattern K D g (probes ℓ D)) := card_image_le + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/View.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/View.lean new file mode 100644 index 0000000000..b4b574e37c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Control/View.lean @@ -0,0 +1,959 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Reorder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Depth +public import Mathlib.Data.Fin.Tuple.Basic + +/-! # A uniform fusion script -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset Motion Stage +variable {F J L K N : Type} [Field F] {r t : ℕ} {p : Params} + {m : Job F r t J L K N} {ν : ℕ → K} + +open scoped Classical in +/-- Computes the test by the application `coefficient P (powered P m.A) m.B z j`. -/ +def Job.test (m : Job F r t J L K N) (P : ℕ) (z : F) (j : ℤ) : Test F r t := + coefficient P (powered P m.A) m.B z j + +open scoped Classical in +/-- Computes the eval at by the application `q.s.observe p.P (q.R.vertex m.v) (m.test p.P z j)`. -/ +def Job.evalAt (m : Job F r t J L K N) (p : Params) (z : F) (j : ℤ) (q : Task m p) := + q.s.observe p.P (q.R.vertex m.v) (m.test p.P z j) + +open scoped Classical in +/-- Selects the elements of `(Motion.pairs P m.d m.e j)` satisfying `(fun i => 0 ≤ fusedEnergy +u.a m.x.a i.1 ∧ 0 ≤ fusedEnergy u.b m.x.b i.2)`. -/ +def Job.pairs (m : Job F r t J L K N) (P : ℕ) (u : Entry F r t K N) (j : ℤ) := + (Motion.pairs P m.d m.e j).filter + (fun i => 0 ≤ fusedEnergy u.a m.x.a i.1 ∧ 0 ≤ fusedEnergy u.b m.x.b i.2) + +open scoped Classical in +private theorem Task.prepare (q : Task m p) (a : q.s.St) (c : q.s.Ct) + (ha : a ∈ q.rest.stations) (he : q.rest.positions.Perm (a.pos :: c.positions)) + (hc : c.inserts ⊆ q.rest.inserts) (d l : ℕ) [ExpChar F d] (hP : p.P = d ^ l) : + let A := powered p.P m.A + let B := m.B + a.pos ^ p.P ∈ A ∧ a.pos ∈ B ∧ q.mover.pos ^ p.P ∉ A ∧ q.mover.pos ∉ B ∧ + c.Fixed p.P (A.erase (a.pos ^ p.P)) (B.erase a.pos) := by + rw [← q.sites, ← q.inserts, hP] + have hv := q.move.distinct q.valid + have ht : a.pos ∉ c.sites := fun h => + (List.nodup_cons.mp (he.nodup_iff.mp hv.1)).1 (List.mem_toFinset.mp h) + have hs : c.sites ⊆ q.rest.sites := fun i hi => + List.mem_toFinset.mpr (he.mem_iff.mpr (.tail _ (List.mem_toFinset.mp hi))) + have hb := q.rest.mem_inserts ha + exact ⟨mem_image_of_mem _ (q.rest.inserts_sub hb), hb, (powered_iff _ _ _ _).not.mpr hv.2, + fun h => hv.2 (q.rest.inserts_sub h), c.fixed_erase d l a.pos ht _ _ hs + (fun i hi => mem_erase.mpr ⟨fun h => ht (h ▸ c.inserts_sub hi), hc hi⟩)⟩ + +open scoped Classical in +theorem Job.absorb (q₀ : Task m p) (rec : m.Subtasks p ν) (hn : m.n + ≤ p.U) (safe : Covers m.a.ports m.v (p.U - m.n)) + (a : Entry F r t K N) (ha : a ∈ m.tail) (d l : ℕ) [ExpChar F d] (hP : p.P = d ^ l) + (j : ℤ) (hj : j ≤ if a.role = .collector then (p.g * m.threshold p : ℕ) else 0) : + m.Solvable p ν (m.evalAt p a.pos j) := by + obtain ⟨ls, rs, hxs⟩ := List.append_of_mem ha + let I := m.pairs p.P a j + let M (i : I) := m.a.edit m.v (a.merge m.x i.val :: (ls ++ rs)) + have cont (i : I) : ∃ f : Script F r t J L K N, f.Ordered ν m.n p.U ∧ + Fintype.card f.I ≤ p.limit F ^ (m.fuel p - 1) ∧ f.Resumes p (M i) m.v := by + refine rec.resume _ _ (a.merge m.x i.val) (ls ++ rs) _ (by simp [M, Record.edit]) ?_ hn safe ?_ + · simp only [Entry.merge, m.active]; split_ifs <;> simp + · simp only [fuel, hxs, List.length_append, List.length_cons]; omega + choose f hf hc hg using cont + have size : Fintype.card I ≤ p.fan F := by + have bound : j ≤ (p.g * (p.P * p.D + p.D + 2 * p.P * p.H) : ℕ) := by + have ht := q₀.move.threshold_le (H := p.H) (P := p.P) (q₀.room _ .refl) + change m.threshold p ≤ _ at ht + have := Nat.mul_le_mul_left p.g ht + split_ifs at hj <;> omega + obtain ⟨hA, hB⟩ := (q₀.s.scene.cell (q₀.R.vertex m.v)).order_bounds q₀.s.scene.level + (q₀.room _ .refl _).2 + rw [q₀.orderA] at hA + rw [q₀.orderB] at hB + rw [Fintype.card_coe] + refine (card_filter_le _ _).trans ((pairs_card hA hB bound).trans ?_) + unfold Params.fan width + exact (Nat.le_mul_of_pos_right _ (by omega)).trans (Nat.le_mul_of_pos_right _ (by positivity)) + let sig := rotSign (m.x::ls) a + let res := Script.sum (fun _ : I => (1 : F)) f + refine ⟨res.times sig, Script.ordered_sum (fun _ : I => (1 : F)) f hf, + (Script.card_sum (fun _ : I => (1 : F)) f hc).trans (Nat.mul_le_mul_right _ size), fun q => ?_⟩ + let v := q.R.vertex m.v + let b := q.mover + obtain ⟨xs, ys, u, er, hl, hu, hr⟩ := split_match (hxs ▸ q.rows.2) + let c : q.s.Ct := ⟨q.rest.ports, xs++ys⟩ + let s := q.s.reord v (b::xs) [u] ys + have here : (q.s.scene.cell v).stations = (b::xs) ++ u :: ys + := by simp [v, b, q.here, Cell.insert, er] + obtain ⟨upd, eqn⟩ := q.match'.rotate (p := p) q.valid m.v (b::xs) ys u (m.x::ls) rs a here + (.cons q.rows.1 hl) hr hu + have loc : s.scene.cell v = (c.insert b).insert u + := by simp [s, reord, put, Scene.put, v, q.here, Cell.insert, c] + have moved : b.label.role = .active m.n := q.rows.1.role.trans m.active + have other (w) (h : w ≠ v) : s.scene.cell w = q.s.scene.cell w := by + simp [s, reord, put, Scene.put, h] + have idle' : ∀ w ∈ u :: c.stations, idle q.allowed v w := by + intro w hw + apply q.others + rw [er]; exact List.perm_middle.mem_iff.mpr hw + have ready : s.Ready v (u :: c.stations) := by + refine ⟨fun w h => (idle' w h).1, fun w hw z hz => ?_⟩ + rw [other _ hw] at hz + exact (q.away _ hw _ hz).1 + have hperm : q.rest.positions.Perm (u.pos :: c.positions) := by + simp only [Cell.positions, er, c, List.map_append, List.map_cons, List.append_assoc, + List.cons_append] + exact List.perm_middle + have hm : u ∈ q.rest.stations := by rw [er]; simp + have hc : c.inserts ⊆ q.rest.inserts := by + simp only [Cell.inserts, c, er, List.map_append, List.map_cons, List.toFinset_append, + List.toFinset_cons] + exact union_subset_union Subset.rfl (subset_insert _ _) + obtain ⟨HA, HB, HA', HB', fixed⟩ := q.prepare _ _ hm hperm hc d l hP + have eA : (s.scene.cell v).orderA s.scene.level = m.d := by + rw [← q.orderA, loc, q.here] + simp only [Cell.orderA, s, reord, put, Scene.put, Cell.insert, c, er, sumA, List.map_cons, + List.sum_cons, + List.map_append, List.sum_append, b] + omega + have eB : (s.scene.cell v).orderB = m.e := by + rw [← q.orderB, loc, q.here] + simp only [Cell.orderB, s, reord, put, Scene.put, Cell.insert, c, er, sumB, List.map_cons, + List.sum_cons, List.map_append, List.sum_append, b] + omega + let U (i : I) := mergeAt u b (u.label.join b.label) i.val + let Q (i : I) := s.put v (c.insert (U i)) + have pairs : merges p.P u b ((s.scene.cell v).orderA s.scene.level) (s.scene.cell v).orderB j = I + := by + rw [eA, eB] + simp only [I, merges, Job.pairs, hu.left, hu.right, b, q.rows.1.left, q.rows.1.right] + have update (i : I) : Update p.P p.g p.H p.U q.R q.β q.β s (Q i) (M i) [] := by + have hb : j ≤ if u.label.role = .collector then (p.g * (energyOf p.P b + + 2 * p.P * p.H) : ℕ) else 0 := by + rw [hu.role]; exact hj + have hstep : s.Step p.P p.g p.H p.U (Q i) := + .merge _ _ _ _ _ _ loc moved ready _ _ (by erw [pairs]; exact i.property) hb + refine ⟨.single hstep, upd.valid.merge v c u b _ loc moved ready i.val, ?_, + Outside.put _ (Set.mem_range_self m.v) _⟩ + have huMerge := hu.merge q.rows.1 (by rw [moved]; simp) i.val + have step := upd.match'.edit m.v (c.insert (U i)) (a.merge m.x i.val :: (ls ++ rs)) + (by rw [loc]; rfl) (.cons huMerge (List.rel_append hl hr)) s.expired + simp only [Record.edit, Function.update_idem] at step + exact step + have branch (i : I) : (f i).Executes p.P p.g p.H p.U q.R q.β s q.allowed ((Q i).value p.P) := by + let w := (q.toWorld.next upd).next (update i) + have e : (Q i).scene.cell v = c.insert (U i) := by + simp only [Q, put, Scene.put] + erw [Function.update_self] + have away z (hz : z ≠ v) : (Q i).scene.cell z = q.s.scene.cell z := by + exact (Function.update_of_ne hz (c.insert (U i)) s.scene.cell).trans (other z hz) + have h := hg i w c (U i) e (fun x hx => idle' x (.tail _ hx)) (by + intro z hz y hy + change y ∈ ((Q i).scene.cell z).stations at hy + rw [away z hz] at hy + exact q.away _ hz _ hy) + exact h.prior (update i) + have value : s.observe p.P v (m.test p.P a.pos j) = fun x => ∑ i : I, (1 : F) * (Q i).value p.P x + := by + have e := s.scene.merge d l v c u b loc (u.label.join b.label) _ _ + (by rwa [← hP]) HB (by rwa [← hP]) HB' (by rwa [← hP]) j + rw [← hP] at e + dsimp only at e + erw [pairs, hu.pos] at e + funext x + unfold observe Job.test + rw [funext e, trace_sum] + simp only [one_mul] + rfl + have h := Script.executes_sum (fun _ : I => (1 : F)) f _ branch + rw [← value] at h + change (res.times sig).Executes _ _ _ _ _ _ _ _ (q.s.observe _ _ _) + rw [eqn (m.test p.P a.pos j) (coefficient_signed _ _ _ _ _)] + exact (h.prior upd).times _ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Crossing a seam inside a common local script -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Gate + +open Finset Motion Stage Function +variable {F J L K N : Type} [Field F] [Fintype F] {r t : ℕ} {p : Params} + {m : Job F r t J L K N} {ν : ℕ → K} + +variable (G : Gate m) + +open scoped Classical in +/-- Computes the result by the application `m.a.cross m.v G.w G.i m.x key i.2.1.val (G.root P +i.2.2.2) i.height i.2.2.1.val`. -/ +def result (P : ℕ) (key : K) (j : ℤ) (i : G.indices P j) := + m.a.cross m.v G.w G.i m.x key i.2.1.val (G.root P i.2.2.2) i.height i.2.2.1.val + +variable (d l : ℕ) [ExpChar F d] (hP : p.P = d ^ l) (hF : p.M * (2 * p.D + 1) < Fintype.card F) + (j : ℤ) (hj : m.threshold p ≤ -j) + +open scoped Classical in +/-- Computes the out by the application `q.s.advance (G.path d l hP hF j hj q) (q.R.vertex m.v) +(q.R.vertex G.w) (q.R.edge G.i) (G.near q) (G.far q) (lowering F r) i`. -/ +def out (q : Task m p) (i : G.indices p.P j) := q.s.advance (G.path d l hP hF j hj q) + (q.R.vertex m.v) (q.R.vertex G.w) (q.R.edge G.i) (G.near q) (G.far q) (lowering F r) i + +open scoped Classical in +theorem enact (q : Task m p) (hn : m.n < p.U) (k : K) (i : G.indices p.P j) : + Update p.P p.g p.H p.U q.R q.β (allocate q.β q.s.hidden.length k) q.s + (G.out d l hP hF j hj q i) (G.result p.P k j i) [(k, m.x.b)] := by + let a := G.path d l hP hF j hj q + have ha : q.mover.label.role = .active m.n := q.rows.1.role.trans m.active + have hv : q.s.scene.cell (q.R.vertex m.v) = ((G.near q).plug (q.R.edge G.i) a.z).insert q.mover + := by + change _ = ((G.near q).plug _ G.z).insert _ + rw [G.near_eq, q.here] + have hw := (G.far_eq q).symm + have ne := q.R.vertex.injective.ne G.ne + have step : q.s.Step p.P p.g p.H p.U (G.out d l hP hF j hj q i) := + .cross _ _ _ _ _ _ _ a _ i m.n hv hw ne (q.match'.level G.i) rfl ha hn q.move.ready rfl + have fresh₁ : i.2.1.val ∉ ((G.near q).plug (q.R.edge G.i) G.z).positions := by + rw [G.near_eq] + intro h + have h' : i.2.1.val ∈ q.rest.sites := List.mem_toFinset.mpr h + rw [q.sites] at h' + exact (mem_sdiff.mp i.2.1.property).2 h' + have fresh₂ : G.root p.P i.2.2.2 ∉ ((G.far q).plug (q.R.edge G.i) G.y).positions := by + rw [G.far_eq] + intro h + have h' : G.root p.P i.2.2.2 ∈ (q.s.scene.cell (q.R.vertex G.w)).sites + := List.mem_toFinset.mpr h + rw [q.match'.sites] at h' + exact (mem_sdiff.mp (mem_image.mp i.2.2.2.property).choose_spec.1).2 h' + exact ⟨.single step, + q.valid.advance _ _ _ _ _ _ a _ i m.n hv hw ne ha hn q.move.ready fresh₁ fresh₂, + q.match'.advance a _ _ _ _ _ i m.x k hv hw G.ne (by rw [m.row]; rfl) (by rw [ha]; simp), + Outside.advance a (Set.mem_range_self m.v) (Set.mem_range_self G.w) (Set.mem_range_self G.i) + _ _ _ i k⟩ + +open scoped Classical in +theorem follows (q : Task m p) (hn : m.n < p.U) (k : K) (i : G.indices p.P j) + (S : Script F r t J L K N) (hS : S.Resumes p (G.result p.P k j i) G.w) : + q.executes (S.prepend [(k, m.x.b)]) ((G.out d l hP hF j hj q i).value p.P) := by + let a := G.path d l hP hF j hj q + let u := G.enact d l hP hF j hj q hn k i + let w := q.toWorld.next u + let z := G.out d l hP hF j hj q i + let v := q.R.vertex G.w + let c : z.Ct := (q.s.scene.cell v).pull Prod.fst id + let arrives := a.arrives (q.mover.label.take q.s.hidden.length) (lowering F r) i + have he : z.scene.cell v = c.insert arrives := by + simp only [z, out, v, Stage.advance, Scene.crossed, update_self, Passage.right] + change (((G.far q).plug _ G.y).pull Prod.fst id).insert _ = _ + rw [G.far_eq]; rfl + have hi : ∀ x ∈ c.stations, idle q.allowed v x := by + intro x hx + obtain ⟨x, hxin, rfl⟩ := List.mem_map.mp hx + exact q.away _ (q.R.vertex.injective.ne G.ne.symm) x hxin + have other : ∀ j, j ≠ v → ∀ x ∈ (z.scene.cell j).stations, idle q.allowed j x := by + intro y hy x hx + change y ≠ q.R.vertex G.w at hy + simp only [z, out, Stage.advance, Scene.crossed, update_of_ne hy] at hx + by_cases h : y = q.R.vertex m.v + · subst y + rw [update_self] at hx + rcases List.mem_cons.mp hx with rfl|hx + · exact ⟨rfl, fun _ h => by cases h⟩ + · obtain ⟨x, hxin, rfl⟩ := List.mem_map.mp hx + exact q.others x hxin + rw [update_of_ne h] at hx + obtain ⟨x, hxin, rfl⟩ := List.mem_map.mp hx + exact q.away y h x hxin + exact (hS w c arrives he hi other).before u + +open scoped Classical in +theorem value (q w : Task m p) : + m.evalAt p G.z j q = fun x => + ∑ i : G.indices p.P j, (G.path d l hP hF j hj w).signed w.s.scene.level (G.near w) (G.far w) + d l hP i * + (G.out d l hP hF j hj q i).value p.P x := by + let a := G.path d l hP hF j hj q + have hv : q.s.scene.cell (q.R.vertex m.v) = ((G.near q).plug (q.R.edge G.i) a.z).insert q.mover + := by + change _ = ((G.near q).plug _ G.z).insert _ + rw [G.near_eq, q.here] + obtain ⟨hl, hr, other⟩ := G.available_ports q + have h := q.s.scene.cross a _ _ _ _ _ (Tag.leave q.s.hidden.length) (q.mover.label.take + q.s.hidden.length) + d l hP (G.fits d l hP hF j hj q) (q.R.vertex.injective.ne G.ne) + (q.match'.level G.i) hv (G.far_eq q).symm hl hr other + funext x + change traceStack t x q.s.hidden (q.s.scene.observe p.P (q.R.vertex m.v) a.coeff) = _ + rw [funext h, trace_sum] + refine sum_congr rfl fun i _ => ?_ + rw [trace_mul, G.uniform d l hP hF j hj q w i] + rfl + +include hP hF hj in +open scoped Classical in +theorem exit (w : Task m p) (rec : m.Subtasks p ν) (hn : m.n < p.U) + (safe : Covers m.a.ports G.w (p.U - (m.n + 1))) : + m.Solvable p ν (m.evalAt p G.z j) := by + let I := G.indices p.P j + let k := ν m.n + let f (i : I) := (G.path d l hP hF j hj w).signed w.s.scene.level (G.near w) (G.far w) d l hP i + obtain ⟨_, _, hnear, _, hlen⟩ := G.room w + have decr : (p.U - (m.n + 1)) * (p.M + 1) + (m.a.rows G.w).length < m.fuel p := by + unfold Job.fuel + rw [show p.U - m.n = (p.U - (m.n + 1)) + 1 by omega, add_mul] + omega + have size : Fintype.card I ≤ p.fan F := by + have card (s : Finset F) : s.card ≤ Nat.card F + 1 := by + rw [Nat.card_eq_fintype_card]; exact (card_le_univ s).trans (by omega) + apply hop_card _ _ _ _ _ _ _ (card _) (card _) + · omega + · omega + · omega + have cont (i : I) : ∃ S : Script F r t J L K N, S.Ordered ν (m.n + 1) p.U ∧ + Fintype.card S.I ≤ p.limit F ^ (m.fuel p - 1) ∧ S.Resumes p (G.result p.P k j i) G.w := by + let x := m.x.taken k (G.root p.P i.2.2.2) i.2.2.1.val + refine rec.resume _ _ x (m.a.rows G.w) _ ?_ ?_ (by omega) safe decr + · simp [result, Record.cross, x] + · exact .inl (by simp [x, Entry.taken, m.active, Role.clock]) + choose S hS hc hf using cont + let prog i := (S i).prepend [(k, m.x.b)] + have order (i) : (prog i).Ordered ν m.n p.U := (hS i).emit _ + refine ⟨Script.sum f prog, Script.ordered_sum f prog order, + (Script.card_sum f prog hc).trans (Nat.mul_le_mul_right _ size), fun q => ?_⟩ + rw [G.value d l hP hF j hj q w] + exact Script.executes_sum f prog _ (fun i => G.follows d l hP hF j hj q hn k i (S i) (hf i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Gate +end + +/- # Selecting a dormant original mark by position -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset Function Stage +variable {F J L K N : Type} [Field F] {r t : ℕ} {p : Params} {ν : ℕ → K} + +open scoped Classical in +theorem Record.select (a : Record F r t J L K N) (v : J) (z : F) (safe : Covers a.ports v p.U) + (complete : ∀ m : Job F r t J L K N, m.n = 0 → Covers m.a.ports m.v p.U → m.Solves p ν) : + ∃ f : Script F r t J L K N, f.Ordered ν 0 p.U ∧ f.Runs a p.P p.g p.H p.U p.M p.D v z ∧ + Fintype.card f.I ≤ p.limit F ^ ((p.U + 1) * (p.M + 1)) := by + by_cases h : (z, Role.active 0) ∈ (a.rows v).map (fun u => (u.pos, u.role)) + swap + · refine ⟨Script.pure a, Script.ordered_pure _ (Nat.zero_le _), ?_, + by rw [Script.card_pure]; exact pow_pos (p.limit_pos F) _⟩ + intro V E T X _ _ R β s src dst match' _ valid _ calm + apply Script.executes_pure (.refl match' valid) calm + intro j hj + refine ⟨hj, ?_⟩ + rintro rfl + obtain ⟨u, hu, he, n, hn⟩ := hj + have hn' := calm _ u hu + rw [hn] at hn' + change n = 0 at hn' + apply h + rw [← match_role (match'.rows v)] + exact List.mem_map.mpr ⟨u, hu, Prod.ext he (hn.trans (by rw [hn']))⟩ + obtain ⟨e, he, hz, hn⟩ : ∃ e ∈ a.rows v, e.pos = z ∧ e.role = .active 0 := by + simpa only [List.mem_map, Prod.mk.injEq] using h + obtain ⟨l, b, hs⟩ := List.append_of_mem he + let m : Job F r t J L K N := + ⟨a.edit v (e::(l++b)), v, e, l++b, 0, by simp [edit], hn⟩ + have bounded : m.Bounded p ν (p.limit F ^ ((p.U + 1) * (p.M + 1))) (fun q => q.s.value p.P) := by + by_cases h : Nonempty (Task m p) + · obtain ⟨q⟩ := h + have e := (q.match'.rows m.v).length_eq + rw [m.row, List.length_cons] at e + have len := ((q.room _ .refl) (q.R.vertex m.v)).1 + simp only [Cell.positions, List.length_append, List.length_map] at len + have lim : m.fuel p ≤ (p.U + 1) * (p.M + 1) := by + unfold Job.fuel + rw [show m.n = 0 from rfl, Nat.sub_zero, add_mul] + omega + obtain ⟨f, hf, hc, ht⟩ := complete m rfl safe + exact ⟨f, hf, hc.trans (Nat.pow_le_pow_right (p.limit_pos F) lim), ht⟩ + · exact Job.vacuous (pow_pos (p.limit_pos F) _) (Nat.zero_le _) h _ + obtain ⟨f, hf, hh, ht⟩ := bounded + refine ⟨f.times (rotSign l e), hf, ?_, hh⟩ + intro V E T X _ _ R β s src dst hm hl hv hroom calm + let A := pending s \ {(R.vertex v, z)} + let world : World p a := ⟨T, X, V, E, R, β, s, src, dst, A, hm, hl, hv, hroom⟩ + obtain ⟨xs, ys, u, here, hxs, hu, hys⟩ := split_match (hs ▸ hm.rows v) + obtain ⟨upd, eqn⟩ := hm.rotate (p := p) hv v xs ys u l b e here hxs hys hu + let s' := s.reord (R.vertex v) xs [u] ys + let c : s.Ct := ⟨(s.scene.cell (R.vertex v)).ports, xs++ys⟩ + have loc : s'.scene.cell (R.vertex v) = c.insert u + := by simp [s', reord, put, Scene.put, c, Cell.insert] + have old (j : V) (x : s.St) (hx : x ∈ (s.scene.cell j).stations) (h : (j, x.pos) ≠ (R.vertex v, + z)) : + idle A j x := ⟨calm _ _ hx, fun n hn => ⟨⟨x, hx, rfl, n, hn⟩, h⟩⟩ + have rest : ∀ x ∈ c.stations, idle A (R.vertex v) x := by + intro x hx + apply old + · rw [here]; exact List.perm_middle.mem_iff.mpr (.tail _ hx) + · have hh := upd.valid.distinct (R.vertex v) + erw [loc, Cell.positions_insert, List.nodup_cons] at hh + intro h + have he := (congrArg Prod.snd h).trans (hu.pos.trans hz).symm + exact hh.1 (List.mem_append_left _ (List.mem_map.mpr ⟨x, hx, he⟩)) + have away : ∀ j, j ≠ R.vertex v → ∀ x ∈ (s'.scene.cell j).stations, idle A j x := by + intro j hj x hx + simp only [s', reord, put, Scene.put, update_of_ne hj] at hx + exact old j x hx (fun h => hj (congrArg Prod.fst h)) + let q : Task m p := ⟨world.next upd, c, u, loc, rest, away⟩ + have lower : f.Executes p.P p.g p.H p.U R β s' A (s'.value p.P) := ht q + have he := eqn forms forms_signed + rw [observe_forms, observe_forms] at he + rw [he] + exact (lower.prior upd).times _ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# A bounded-radius motion script + +Only a crossing changes the current cell. Every such change decreases +the remaining radius. A continued fusion consumes a stationary mark. +Together these give a bound on the number of steps independent of the +size of the ambient graph. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset Motion Stage +variable {F J L K N : Type} [Field F] {r t : ℕ} {p : Params} + {m : Job F r t J L K N} {ν : ℕ → K} + +open scoped Classical in +/-- Indexes the choices by the coordinates of `Σ z : m.A, Fin (orders m.seams c (m.order p.P) +p.g (m.threshold p) z.val)`. -/ +abbrev Job.choices (m : Job F r t J L K N) (p : Params) (c : F) := + Σ z : m.A, Fin (orders m.seams c (m.order p.P) p.g (m.threshold p) z.val) + +open scoped Classical in +/-- The quantity computed by `(i.2.val : ℤ) - m.order p.P i.1.val`. -/ +def Job.degree (m : Job F r t J L K N) (p : Params) (c : F) (i : m.choices p c) : ℤ := + (i.2.val : ℤ) - m.order p.P i.1.val + +open scoped Classical in +private theorem Task.collector (q : Task m p) : + ∃ a ∈ m.tail, a.role = .collector := by + obtain ⟨c, hc, h⟩ := q.move.collector q.valid + have he : (c.pos, Role.collector) ∈ m.tail.map (fun a => (a.pos, a.role)) := by + rw [← match_role q.rows.2] + exact List.mem_map.mpr ⟨c, hc, by rw [h]⟩ + obtain ⟨a, ha, h⟩ := List.mem_map.mp he + exact ⟨a, ha, congrArg Prod.snd h⟩ + +open scoped Classical in +private theorem Task.choices_le (q : Task m p) (c : F) : + Fintype.card (m.choices p c) ≤ p.M * window p.P p.g p.H p.D := by + have room := q.room _ .refl + have hd : ∀ i, m.order p.P i ≤ p.P * p.D + p.D := by + intro i + have e := q.move.order_le (P := p.P) room i + change poleOrder _ ((q.s.scene.cell (q.R.vertex m.v)).orderA q.s.scene.level) + (q.s.scene.cell (q.R.vertex m.v)).orderB q.rest.inserts i ≤ _ at e + rw [q.orderA, q.orderB, q.inserts] at e + exact e + exact orders_card hd (q.move.threshold_le room) (q.sites ▸ (q.move.room room).1) + +open scoped Classical in +private theorem Job.interpolate (q₀ : Task m p) (d l : ℕ) [ExpChar F d] (hP : p.P = d ^ l) + (c : Entry F r t K N) (hc : c ∈ m.tail) : + ∃ f : m.choices p c.pos → F, ∀ q : Task m p, ∀ x : q.X, + q.s.value p.P x = ∑ i, f i * m.evalAt p i.1.val (m.degree p c.pos i) q x := by + rcases p with ⟨P, g, H, U, M, D⟩ + change P = d ^ l at hP + subst P + let p : Params := ⟨d ^ l, g, H, U, M, D⟩ + have hc' : c.pos ∈ m.B := List.mem_toFinset.mpr (List.mem_map_of_mem hc) + have hd : c.pos ∉ m.seams := by + rw [← q₀.seams] + exact disjoint_left.mp (q₀.rest.disjoint (q₀.move.distinct q₀.valid).1) (q₀.inserts.symm ▸ hc') + have hg : m.seams.card ≤ g := by + have e := q₀.layout.degree (q₀.R.vertex m.v) + rw [Stage.ports, q₀.here] at e + rw [← q₀.seams] + exact (List.toFinset_card_le _).trans ((List.length_map _).le.trans e) + have hz : m.x.pos ∉ m.A := by rw [← q₀.sites]; exact (q₀.move.distinct q₀.valid).2 + obtain ⟨f, hf⟩ := reconstruct_cells (r := r) (t := t) d l m.d m.e m.A m.B m.seams + subset_union_left subset_union_right c.pos (mem_union_left _ hc') hd g (m.threshold p) hg + m.x.pos hz + refine ⟨f, fun q x => ?_⟩ + let v := q.R.vertex m.v + have st : ∀ a ∈ (q.s.scene.cell v).stations, a.pos = m.x.pos ∨ a.pos ∈ m.B := by + rw [q.here, ← q.inserts] + exact List.forall_mem_cons.mpr ⟨.inl rfl, fun _ h => .inr (q.rest.mem_inserts h)⟩ + have pt : ∀ i ∈ (q.s.scene.cell v).ports, i.2 ∈ m.A := by + rw [q.here, ← q.sites] + exact fun i h => q.rest.seams_sub (q.rest.mem_seams h) + have e (x : Stack q.X t q.s.hidden) : q.s.scene.value p.P x = ∑ i : m.choices p c.pos, + f i * q.s.scene.observe p.P v (m.test p.P i.1.val (m.degree p c.pos i)) x := + contractGraph_replace _ _ v f _ (fun h hh => hf _ _ q.orderA q.orderB st pt x h (fun i _ + => hh _)) + change traceStack t x q.s.hidden (q.s.scene.value p.P) = _ + rw [funext e, trace_sum] + exact sum_congr rfl fun i _ => trace_mul _ _ _ _ _ + +variable [Fintype F] + +open scoped Classical in +private theorem Job.next (d l : ℕ) [ExpChar F d] (hP : p.P = d ^ l) + (hF : p.M * (2 * p.D + 1) < Fintype.card F) (hn : m.n < p.U) + (safe : Covers m.a.ports m.v (p.U - m.n)) (rec : m.Subtasks p ν) : m.Solves p ν := by + by_cases real : Nonempty (Task m p) + swap + · exact Job.vacuous (pow_pos (p.limit_pos F) _) hn.le real _ + obtain ⟨q⟩ := real + obtain ⟨c, hc, hc'⟩ := q.collector + obtain ⟨f, hf⟩ := Job.interpolate q d l hP c hc + have solve (i : m.choices p c.pos) : + m.Solvable p ν (m.evalAt p i.1.val (m.degree p c.pos i)) := by + let z := i.1.val + let j := m.degree p c.pos i + have hi : i.2.val < orders m.seams c.pos (m.order p.P) p.g (m.threshold p) z := i.2.isLt + change m.Solvable p ν (m.evalAt p z j) + by_cases hs : z ∈ m.seams + · have he : (m.threshold p : ℤ) ≤ -j := by + conv at hi => rhs; rw [orders, ite_eq_left hs] + dsimp only [j, z, degree] at * + omega + obtain ⟨G, hg, h'⟩ := Gate.of_cover safe hn hs + rw [← hg] + exact G.exit d l hP hF _ he q rec hn h' + conv at hi => rhs; rw [orders, ite_eq_right hs] + by_cases ht : z = c.pos + · rw [ite_eq_left ht] at hi + have he : j ≤ (p.g * m.threshold p : ℕ) := by dsimp only [j, z, degree] at *; omega + rw [ht] + exact Job.absorb q rec hn.le safe c hc d l hP j (by rw [ite_eq_left hc']; exact he) + rw [ite_eq_right ht] at hi + have he : j ≤ 0 := by dsimp only [j, z, degree] at *; omega + have hz : z ∈ m.B := (mem_union.mp i.1.property).resolve_right hs + obtain ⟨u, hu, heq⟩ := List.mem_map.mp (List.mem_toFinset.mp hz) + rw [← heq] + exact Job.absorb q rec hn.le safe u hu d l hP j (by split_ifs <;> omega) + have fuel : 0 < m.fuel p := by + have : 0 < p.U - m.n := by omega + unfold Job.fuel + positivity + obtain ⟨z, hz, hb, h⟩ := Job.combine f _ solve fuel (q.choices_le c.pos) + exact ⟨z, hz, hb, fun q => by change q.executes z (q.s.value p.P); rw [funext (hf q)]; exact h q⟩ + +open scoped Classical in +/-- Complete the designated move, or leave the region unchanged if its +original station was already absorbed. The script and weights do not +depend on the interpretation of local indices in the ambient graph. -/ +theorem Record.run (a : Record F r t J L K N) (p l : ℕ) [ExpChar F p] (g H U M D : ℕ) + (hF : M * (2 * D + 1) < Fintype.card F) (v : J) (z : F) (ν : ℕ → K) (safe : Covers a.ports v U) + : + ∃ q : Script F r t J L K N, q.Ordered ν 0 U ∧ q.Runs a (p ^ l) g H U M D v z ∧ + Fintype.card q.I ≤ breadth (p ^ l) g H M D (Nat.card F + 1) ^ ((U + 1) * (M + 1)) := by + let P : Params := ⟨p ^ l, g, H, U, M, D⟩ + have go (m : Job F r t J L K N) (hn : m.n ≤ U) (hc : Covers m.a.ports m.v (U - m.n)) : + m.Solves P ν := by + induction h : m.fuel P using Nat.strong_induction_on generalizing m with + | ind n ih => + by_cases he : m.n = U + · exact Job.expire he + apply Job.next p l rfl hF (lt_of_le_of_ne hn he) hc + intro q he hn' safe' + exact ih _ (he.trans_eq h) q hn' safe' rfl + exact a.select (p := P) v z safe (fun m he h => go m (by omega) (by simpa [he] using h)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Restricting a named surface record to a local region -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +variable {F T V E X J L K N J' L' : Type} {r t : ℕ} + (R : Reference J L N V E T X) + +open scoped Classical in +/-- Uses `⟨vertex, edge, R.name, R.key, R.ext, R.empty⟩` as the representation. -/ +def Reference.region (vertex : J' ↪ V) (edge : L' ↪ E) : Reference J' L' N V E T X := + ⟨vertex, edge, R.name, R.key, R.ext, R.empty⟩ + +open scoped Classical in +/-- Computes the world by the application `R.region (.refl V) (.refl E)`. -/ +def Reference.world := R.region (.refl V) (.refl E) + +variable {R} {R' : Reference J' L' N V E T X} {β : V ⊕ ℕ → K} + {s : Stage F r t T V E X} + +open scoped Classical in +theorem Represents.change {u : s.St} {a : Entry F r t K N} + (h : Represents R β s.hidden u a) + (hk : R.key = R'.key) (hn : R.name = R'.name) (he : R.ext = R'.ext) : + Represents R' β s.hidden u a := + ⟨h.pos, h.left, h.right, h.role, hn ▸ h.name, h.named, h.known, he ▸ hk ▸ h.label⟩ + +open scoped Classical in +/-- The data for the view construction, including `rows`, `ports`, `level`, `footprint`. -/ +structure View (G : Record F r t V E K N) (f : J ↪ V) (g : L ↪ E) + (a : Record F r t J L K N) : Prop where + rows : ∀ i, G.rows (f i) = a.rows i + ports : ∀ i, G.ports (f i) = (a.ports i).map (Prod.map g id) + level : ∀ j, G.level (g j) = a.level j + footprint : ∀ i, G.footprint (f i) = a.footprint i + +variable {G : Record F r t V E K N} {a : Record F r t J L K N} + +open scoped Classical in +theorem Matches.view (h : Matches R'.world β s G) + (v : View G R.vertex R.edge a) + (hk : R'.key = R.key) (hn : R'.name = R.name) (he : R'.ext = R.ext) : + Matches R β s a := by + refine ⟨fun i => ?_, fun i => ?_, fun i => ?_, fun i => ?_, fun i => h.known (R.vertex i)⟩ + · rw [← v.rows] + exact (h.rows (R.vertex i)).imp fun u _ h => h.change (s := s) hk hn he + · rw [← v.ports] + have hc := h.ports (R.vertex i) + change _ = (G.ports (R.vertex i)).map id at hc + rwa [List.map_id] at hc + · exact (h.level _).trans (v.level _) + · exact (h.footprint _).trans (v.footprint _) + +open scoped Classical in +theorem View.unique {f : J ↪ V} {g : L ↪ E} {b : Record F r t J L K N} + (h : View G f g a) (i : View G f g b) : a = b := by + obtain ⟨ar, ap, al, af⟩ := a + obtain ⟨br, bp, bl, bf⟩ := b + congr 1 + · exact funext fun j => (h.rows j).symm.trans (i.rows j) + · funext j + exact (g.injective.prodMap Function.injective_id).list_map ((h.ports j).symm.trans (i.ports j)) + · exact funext fun j => (h.level j).symm.trans (i.level j) + · exact funext fun j => (h.footprint j).symm.trans (i.footprint j) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# Independent scripts on disjoint regions + +A wave of local scripts acts by a product of its kernels. Sequential +execution proves this identity, allocating fresh keys in command order. +Each command's output is unaffected by the other commands. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Finset + +open scoped Classical in +/-- The data for the command construction, including `vertices`, `edges`, `ref`, `shared`, +`input`. -/ +structure Command (F : Type) [Field F] (r t : ℕ) (T V E X K N : Type) + (P g H U M D : ℕ) (key : V → X → ℕ) where + /-- The indexed vertices carried by `Command`, with type `Type`. -/ + vertices : Type + /-- The finite set of connections carried by `Command`, with type `Type`. -/ + edges : Type + /-- The `Command` component of type `Reference vertices edges N V E T X`. -/ + ref : Reference vertices edges N V E T X + shared : ref.key = key + /-- The input data carried by `Command`, with type `Record F r t vertices edges K N`. -/ + input : Record F r t vertices edges K N + /-- The `Command` component of type `Script F r t vertices edges K N`. -/ + action : Script F r t vertices edges K N + /-- The initial point of type `vertices`. -/ + start : vertices + /-- The `Command` field of type `F`. -/ + pos : F + runs : action.Runs input P g H U M D start pos + +variable {F T V E X K N : Type} [Field F] {r t P g H U M D n : ℕ} + {key : V → X → ℕ} {src dst : E → V} + +local notation "Cmd" => Command F r t T V E X K N P g H U M D key +local notation "St" => Stage F r t T V E X + +open scoped Classical in +/-- The value specified by `(c.ref.vertex c.start, c.pos)`. -/ +def Command.target (c : Cmd) := (c.ref.vertex c.start, c.pos) + +omit [Field F] in +open scoped Classical in +theorem Outside.rekey {B : Set V} {A : Set E} {a b : St} {β γ : V ⊕ ℕ → K} + {add : List (K × ℕ)} {left right : V → X → ℕ} + (h : Outside B A left a b β γ add) (he : left = right) : Outside B A right a b β γ add := + he ▸ h + +namespace Wave + +variable (C : Fin n → Command F r t T V E X K N P g H U M D key) + +open scoped Classical in +/-- Uses `{v | ∃ i, v ∈ Set.range (C i).ref.vertex}` as the representation. -/ +def vertices : Set V := {v | ∃ i, v ∈ Set.range (C i).ref.vertex} +open scoped Classical in +/-- Uses `{v | ∃ i, v ∈ Set.range (C i).ref.edge}` as the representation. -/ +def edges : Set E := {v | ∃ i, v ∈ Set.range (C i).ref.edge} + +open scoped Classical in +/-- The data for the separate construction, including `vertex`, `edge`. -/ +structure Separate : Prop where + vertex : ∀ i j, i ≠ j → Disjoint (Set.range (C i).ref.vertex) (Set.range (C j).ref.vertex) + edge : ∀ i j, i ≠ j → Disjoint (Set.range (C i).ref.edge) (Set.range (C j).ref.edge) + +open scoped Classical in +/-- The condition `∀ i, (C i).action.I` on the specified data. -/ +abbrev Index : Type := ∀ i, (C i).action.I + +open scoped Classical in +/-- The indexed operation `(List.ofFn fun i => (C i).action.fresh (a i)).flatten`. -/ +def fresh (a : Index C) := (List.ofFn fun i => (C i).action.fresh (a i)).flatten + +open scoped Classical in +/-- Witnesses where each fresh key was created, in command order. -/ +def Execution : {n : ℕ} → (C : Fin n → Cmd) → Index C → + St → St → (V ⊕ ℕ → K) → (V ⊕ ℕ → K) → Prop + | 0, _, _, s, q, β, γ => s = q ∧ β = γ + | _ + 1, C, a, s, q, β, γ => + ∃ p β', Update P g H U (C 0).ref β β' s p ((C 0).action.result (a 0)) + ((C 0).action.fresh (a 0)) ∧ Execution (Fin.tail C) (Fin.tail a) p q β' γ + +open scoped Classical in +/-- The data for the finish construction, including `history`, `reach`, `valid`, `calm`, +`pending`. -/ +structure Finish (s q : St) (β γ : V ⊕ ℕ → K) (a : Index C) : Prop where + history : Execution C a s q β γ + reach : s.Reach P g H U q + valid : q.Valid U + calm : Calm q + pending : Local.pending q ⊆ Local.pending s \ Set.range (Command.target ∘ C) + outside : Outside (vertices C) (edges C) key s q β γ (fresh C a) + result : ∀ i, Matches (C i).ref γ q ((C i).action.result (a i)) + +open scoped Classical in +private theorem layout_of_reach {s q : St} (h : s.Reach P g H U q) (hl : s.Layout src dst g) : + q.Layout src dst g := by + induction h with + | refl => exact hl + | tail _ step ih => exact step.layout ih + +variable [Fintype V] [Fintype E] + +open scoped Classical in +/-- Local results, scalar weights and independently chosen indices work +simultaneously for all values of the ordinary parameters. -/ +theorem execute (h : Separate C) (s : St) (β : V ⊕ ℕ → K) + (hin : ∀ i, Matches (C i).ref β s (C i).input) (hl : s.Layout src dst g) + (hv : s.Valid U) (hr : ∀ q, s.Reach P g H U q → q.Room M D) (hc : Calm s) : + ∃ (q : Index C → St) (γ : Index C → V ⊕ ℕ → K), + (∀ a, Finish C s (q a) β (γ a) a) ∧ + ∀ x, s.value P x = ∑ a, (∏ i, (C i).action.weight (a i)) * (q a).value P x := by + induction n generalizing s β with + | zero => + refine ⟨fun _ => s, fun _ => β, fun a => ?_, by simp⟩ + refine ⟨⟨rfl, rfl⟩, .refl, hv, hc, by simp, ?_, fun i => i.elim0⟩ + simp only [fresh, List.ofFn_zero, List.flatten_nil] + exact ⟨rfl, fun _ _ => rfl, fun i => i.elim0, fun _ _ => rfl, fun _ _ => rfl, + id, fun _ => rfl, fun _ _ _ => rfl, fun i _ => ((s.scene.cell i).pull_id).symm⟩ + | succ n ih => + let B := C 0 + let R := Fin.tail C + obtain ⟨p, γ, hp, eq⟩ := B.runs B.ref β s src dst (hin 0) hl hv hr hc + have hs : Separate R := + ⟨fun i j hn => h.vertex _ _ (Fin.succ_injective _ |>.ne hn), + fun i j hn => h.edge _ _ (Fin.succ_injective _ |>.ne hn)⟩ + have he (j : B.action.I) (i : Fin n) : Matches (R i).ref (γ j) (p j) (R i).input := by + have out := (hp j).1.outside.rekey (B.shared.trans (R i).shared.symm) + apply (hin i.succ).outside out + · exact fun v => Set.disjoint_left.mp (h.vertex i.succ 0 (Fin.succ_ne_zero _)) ⟨v, rfl⟩ + · exact fun e => Set.disjoint_left.mp (h.edge i.succ 0 (Fin.succ_ne_zero _)) ⟨e, rfl⟩ + have run (j : B.action.I) := + ih R hs (p j) (γ j) (he j) (layout_of_reach (hp j).1.reach hl) (hp j).1.valid + (fun y hy => hr y ((hp j).1.reach.trans hy)) (hp j).2.1 + choose q δ hq hval using run + refine ⟨fun a => q (a 0) (Fin.tail a), fun a => δ (a 0) (Fin.tail a), ?_, ?_⟩ + · intro a + obtain ⟨h₁, _, pending₁⟩ := hp (a 0) + have h₂ := hq (a 0) (Fin.tail a) + refine ⟨⟨_, _, h₁, h₂.history⟩, h₁.reach.trans h₂.reach, h₂.valid, h₂.calm, ?_, ?_, ?_⟩ + · intro x hx + obtain ⟨hx, hrest⟩ := h₂.pending hx + obtain ⟨hx, hhead⟩ := pending₁ hx + refine ⟨hx, ?_⟩ + rintro ⟨i, rfl⟩ + induction i using Fin.cases with + | zero => exact hhead rfl + | succ i => exact hrest ⟨i, rfl⟩ + · have a₁ := h₁.outside.mono (B' := vertices C) (A' := edges C) + (fun _ h => ⟨0, h⟩) (fun _ h => ⟨0, h⟩) + rw [B.shared] at a₁ + have a₂ := h₂.outside.mono (B' := vertices C) (A' := edges C) + (fun _ ⟨i, h⟩ => ⟨i.succ, h⟩) (fun _ ⟨i, h⟩ => ⟨i.succ, h⟩) + rw [fresh, List.ofFn_succ, List.flatten_cons] + exact a₁.trans a₂ + · intro i + induction i using Fin.cases with + | zero => + have out := h₂.outside.rekey B.shared.symm + apply h₁.match'.outside out + · rintro v ⟨i, hi⟩ + exact Set.disjoint_left.mp (h.vertex i.succ 0 (Fin.succ_ne_zero _)) hi ⟨v, rfl⟩ + · rintro e ⟨i, hi⟩ + exact Set.disjoint_left.mp (h.edge i.succ 0 (Fin.succ_ne_zero _)) hi ⟨e, rfl⟩ + | succ i => exact h₂.result i + · intro x + rw [eq x, ← (Fin.consEquiv (fun i => (C i).action.I)).sum_comp, Fintype.sum_prod_type] + apply sum_congr rfl + intro j _ + rw [hval, mul_sum] + apply sum_congr rfl + intro l _ + simp only [show Fin.consEquiv (fun i => (C i).action.I) (j, l) = Fin.cons j l from rfl, + Fin.prod_univ_succ, mul_assoc] + rfl + +end Wave +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +section +/- +# A key stays local in a wave + +Every ordinary key seen after a wave was either already present +within the same region or created there. New addresses in each +script correspond to a consecutive interval in the global stack. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +variable {F T V E X K N J L : Type} [Field F] {r t P g H U M D n : ℕ} + {key : V → X → ℕ} {β γ : V ⊕ ℕ → K} + {s q : Stage F r t T V E X} {R : Reference J L N V E T X} {a : Record F r t J L K N} + {f : List (K × ℕ)} {B : Set V} {A : Set E} + +open scoped Classical in +/-- The condition `∀ v j, j ∈ s.footprint v → available s.hidden.length j` on the specified +data. -/ +def Known (s : Stage F r t T V E X) := ∀ v j, j ∈ s.footprint v → available s.hidden.length j + +open scoped Classical in +private theorem Update.known (h : Update P g H U R β γ s q a f) (hs : Known s) : Known q := by + intro v j hj + by_cases hv : v ∈ Set.range R.vertex + · obtain ⟨i, rfl⟩ := hv + exact h.match'.known i j hj + · exact h.outside.known j (hs v j (by rwa [h.outside.footprint v hv] at hj)) + +open scoped Classical in +/-- The energy stored at a natural-number key. -/ +def degree (ns : List ℕ) : V ⊕ ℕ → ℕ + | .inl _ => 0 + | .inr i => (ns.reverse[i]?).getD 0 + +omit [Field F] in +open scoped Classical in +theorem Outside.degree_old (h : Outside B A key s q β γ f) {j : V ⊕ ℕ} + (hj : available s.hidden.length j) : degree q.hidden j = degree s.hidden j := by + cases j with + | inl => rfl + | inr i => + change i < s.hidden.length at hj + simp only [degree, h.history, List.reverse_append, List.reverse_reverse] + rw [List.getElem?_append_left (by simpa using hj)] + +omit [Field F] in +open scoped Classical in +private theorem Outside.degree_new (h : Outside B A key s q β γ f) (i : Fin f.length) : + degree q.hidden (.inr (s.hidden.length + i.val) : V ⊕ ℕ) = (f.get i).2 := by + simp only [degree, h.history, List.reverse_append, List.reverse_reverse] + rw [List.getElem?_append_right (by simp)] + simp + +open scoped Classical in +private theorem Update.fresh {j : V ⊕ ℕ} (h : Update P g H U R β γ s q a f) + (hold : ¬ available s.hidden.length j) (hnew : available q.hidden.length j) : + ∃ i : Fin f.length, j = .inr (s.hidden.length + i.val) ∧ + (γ j, degree q.hidden j) = f.get i := by + cases j with + | inl => exact (hold trivial).elim + | inr j => + simp only [available, h.outside.length] at hold hnew + let i : Fin f.length := ⟨j - s.hidden.length, by omega⟩ + have hi : j = s.hidden.length + i.val := by dsimp [i]; omega + refine ⟨i, congrArg _ hi, ?_⟩ + rw [hi, h.outside.new, h.outside.degree_new] + +namespace Wave + +variable {C : Fin n → Command F r t T V E X K N P g H U M D key} {a : Index C} + +open scoped Classical in +/-- The value specified by `v = w ∨ ∃ i, v ∈ Set.range (C i).ref.vertex ∧ w ∈ Set.range (C +i).ref.vertex`. -/ +def Together (C : Fin n → Command F r t T V E X K N P g H U M D key) (v w : V) := + v = w ∨ ∃ i, v ∈ Set.range (C i).ref.vertex ∧ w ∈ Set.range (C i).ref.vertex + +open scoped Classical in +/-- Each key present in a region has an old origin in that same region +or a fresh origin in the script for it. The offset is common to all +keys introduced by any one script. -/ +def Origins (C : Fin n → Command F r t T V E X K N P g H U M D key) (a : Index C) + (s q : Stage F r t T V E X) (β γ : V ⊕ ℕ → K) : Prop := + ∃ offset : Fin n → ℕ, ∀ v j, j ∈ q.footprint v → + (∃ w, Together C v w ∧ j ∈ s.footprint w ∧ γ j = β j ∧ degree q.hidden j = degree s.hidden j) ∨ + ∃ i, v ∈ Set.range (C i).ref.vertex ∧ ∃ k : Fin ((C i).action.fresh (a i)).length, + j = .inr (offset i + k.val) ∧ (γ j, degree q.hidden j) = ((C i).action.fresh (a i)).get k + +open scoped Classical in +theorem Execution.origins {keys : V → X → X → Prop} {ext : T → X → X → Prop} + (h : Execution C a s q β γ) (sep : Separate C) (ctrl : s.Controls keys ext) + (known : Known s) : Origins C a s q β γ := by + induction n generalizing s β with + | zero => + obtain ⟨rfl, rfl⟩ := h + exact ⟨Fin.elim0, fun v j hj => .inl ⟨v, .inl rfl, hj, rfl, rfl⟩⟩ + | succ n ih => + obtain ⟨p, δ, head, tail⟩ := h + have sep' : Separate (Fin.tail C) := + ⟨fun i j hn => sep.vertex _ _ ((Fin.succ_injective _).ne hn), + fun i j hn => sep.edge _ _ ((Fin.succ_injective _).ne hn)⟩ + obtain ⟨offset, h₁⟩ := ih tail sep' (head.reach.controls ctrl) (head.known known) + refine ⟨Fin.cons s.hidden.length offset, fun v j hj => ?_⟩ + rcases h₁ v j hj with ⟨w, hvw, hw, hγ, he⟩|⟨i, hv, k, hj, hγ⟩ + · rcases hvw with rfl|⟨i, hv, hw'⟩ + · rcases head.outside.origin head.reach ctrl known hw with ⟨w, hv, hj⟩|⟨hv, hj⟩ + · have ho := known w _ hj + refine .inl ⟨w, ?_, hj, hγ.trans (head.outside.old _ ho), + he.trans (head.outside.degree_old ho)⟩ + exact hv.imp_right (fun h => ⟨0, h⟩) + · obtain ⟨k, hk, heq⟩ := head.fresh hj (head.known known _ _ hw) + refine .inr ⟨0, hv, k, ?_, ?_⟩ + · simpa only [Fin.cons_zero] using hk + · rw [hγ, he]; exact heq + · have out := Set.disjoint_left.mp (sep.vertex i.succ 0 (Fin.succ_ne_zero i)) hw' + rw [head.outside.footprint w out] at hw + have ho := known w _ hw + exact .inl ⟨w, .inr ⟨i.succ, hv, hw'⟩, hw, hγ.trans (head.outside.old _ ho), + he.trans (head.outside.degree_old ho)⟩ + · exact .inr ⟨i.succ, hv, k, by simpa only [Fin.cons_succ] using hj, hγ⟩ + +end Wave +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Coupled.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Coupled.lean new file mode 100644 index 0000000000..6e52dde2d1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Coupled.lean @@ -0,0 +1,887 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Polynomial.Roots +public import Mathlib.Algebra.Polynomial.Taylor +public import Mathlib.LinearAlgebra.Basis.VectorSpace +public import Mathlib.RingTheory.Polynomial.Basic +public import Mathlib.RingTheory.LaurentSeries +public import Mathlib.RingTheory.PowerSeries.Expand +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Block +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryJets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation + +/-! +# Laurent reconstruction for moving insertions + +Use a common denominator. At a point with pole bound `d`, remove +`(X-z)^d` from the denominator. Coefficient `i` of the resulting regular +quotient is Laurent coefficient `i-d`. The reconstruction weights do not +depend on the numerator, so they act simultaneously on every tensor entry. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +open Polynomial +variable {K : Type*} [Field K] + +/-- Polynomial denominator for the specified bounds at distinct marks. -/ +def poles (s : Finset K) (d : K → ℕ) : K[X] := ∏ z ∈ s, (X - C z) ^ d z + +theorem degree_poles (s : Finset K) (d : K → ℕ) : + (poles s d).natDegree = ∑ z ∈ s, d z := by + unfold poles + rw [natDegree_prod_of_monic _ _ (fun z _ => (monic_X_sub_C z).pow _)] + simp + +theorem poles_eval {s : Finset K} {z : K} (d : K → ℕ) (h : z ∉ s) : + (poles s d).eval z ≠ 0 := by + rw [poles, eval_prod] + apply Finset.prod_ne_zero_iff.mpr + intro t ht + simp only [eval_pow, eval_sub, eval_X, eval_C] + exact pow_ne_zero _ (sub_ne_zero.mpr (fun he => h (he ▸ ht))) + +theorem poles_split [DecidableEq K] {s : Finset K} {z : K} (d : K → ℕ) (h : z ∈ s) : + poles s d = (X - C z) ^ d z * poles (s.erase z) d := + (Finset.mul_prod_erase _ _ h).symm + +/-- Coefficient of degree `i` in the regular quotient `p(z + X) / q(z + X)`. -/ +def jet (z : K) (q : K[X]) (i : ℕ) : K[X] →ₗ[K] K where + toFun p := PowerSeries.coeff i ((taylor z p : PowerSeries K) * (taylor z q : PowerSeries K)⁻¹) + map_add' p p' := by simp only [map_add, Polynomial.coe_add, add_mul] + map_smul' c p := by simp only [map_smul, Polynomial.coe_smul, smul_mul_assoc, RingHom.id_apply] + +theorem jet_zero (z : K) (q p : K[X]) : jet z q 0 p = p.eval z / q.eval z := by + unfold jet + simp [PowerSeries.coeff_zero_eq_constantCoeff_apply, taylor_coeff_zero, div_eq_mul_inv] + +/-- Formal expansion of the quotient `p/q` at `z`. -/ +def laurent (z : K) (p q : K[X]) : LaurentSeries K := + HahnSeries.ofPowerSeries ℤ K (taylor z p) / HahnSeries.ofPowerSeries ℤ K (taylor z q) + +private theorem shifted_laurent (z : K) (p q : K[X]) (d : ℕ) (hq : q.eval z ≠ 0) : + laurent z p ((X - C z) ^ d * q) = HahnSeries.single (-(d : ℤ)) 1 * + HahnSeries.ofPowerSeries ℤ K ((taylor z p : PowerSeries K) * (taylor z q : PowerSeries K)⁻¹) + := by + let f := HahnSeries.ofPowerSeries ℤ K + let a : PowerSeries K := taylor z p + let b : PowerSeries K := taylor z q + have hb : PowerSeries.constantCoeff b ≠ 0 := by simpa [b, taylor_coeff_zero] using hq + have inv : f b⁻¹ = (f b)⁻¹ := + eq_inv_of_mul_eq_one_left (by rw [← map_mul, PowerSeries.inv_mul_cancel b hb, map_one]) + have den : (taylor z ((X - C z) ^ d * q) : PowerSeries K) = PowerSeries.X ^ d * b := by + simp [b] + change laurent z p _ = _ * f (a * b⁻¹) + unfold laurent + rw [den, map_mul, HahnSeries.ofPowerSeries_X_pow, div_eq_mul_inv, mul_inv_rev, + HahnSeries.inv_single, inv_one, map_mul, inv] + change f a * ((f b)⁻¹ * _) = _ + ac_rfl + +theorem coeff_below (z : K) (p q : K[X]) (d : ℕ) (hq : q.eval z ≠ 0) (j : ℤ) (hj : j < -(d : ℤ)) : + (laurent z p ((X - C z) ^ d * q)).coeff j = 0 := by + rw [shifted_laurent _ _ _ _ hq, HahnSeries.coeff_single_mul, one_mul, + PowerSeries.coeff_coe, ite_eq_left (by omega)] + +theorem coeff_laurent (z : K) (p q : K[X]) (d : ℕ) (hq : q.eval z ≠ 0) (i : ℕ) : + (laurent z p ((X - C z) ^ d * q)).coeff ((i : ℤ) - d) = jet z q i p := by + rw [shifted_laurent _ _ _ _ hq, sub_eq_add_neg, HahnSeries.coeff_single_mul_add, one_mul, + HahnSeries.ofPowerSeries_apply_coeff] + rfl + +/-- Multiplying by the invertible regular denominator preserves vanishing +of the first `n` coefficients. -/ +theorem dvd_of_jet {z : K} {p q : K[X]} (hq : q.eval z ≠ 0) {n : ℕ} + (hv : ∀ i < n, jet z q i p = 0) : (X - C z) ^ n ∣ p := by + let a : PowerSeries K := taylor z p + let b : PowerSeries K := taylor z q + have hb : PowerSeries.constantCoeff b ≠ 0 := by simpa [b, taylor_coeff_zero] using hq + have h : PowerSeries.X ^ n ∣ a * b⁻¹ := PowerSeries.X_pow_dvd_iff.mpr hv + have ha : PowerSeries.X ^ n ∣ a := by + simpa only [mul_assoc, PowerSeries.inv_mul_cancel b hb, mul_one] using dvd_mul_of_dvd_left h b + have hp : X ^ n ∣ taylor z p := by + simpa only [X_pow_dvd_iff, PowerSeries.X_pow_dvd_iff, a, coeff_coe] using ha + obtain ⟨w, hw⟩ := hp + refine ⟨taylor (-z) w, ?_⟩ + simpa [taylor_taylor, sub_eq_add_neg] using congrArg (taylor (-z)) hw + +theorem zero_of_jets (s : Finset K) (n : K → ℕ) (q : K → K[X]) (hq : ∀ z ∈ s, (q z).eval z ≠ 0) + {p : K[X]} (hp : p.natDegree < ∑ z ∈ s, n z) + (hv : ∀ z ∈ s, ∀ i < n z, jet z (q z) i p = 0) : p = 0 := by + by_contra h + have hd : poles s n ∣ p := by + apply Finset.prod_dvd_of_coprime + · exact fun _ _ _ _ he => (pairwise_coprime_X_sub_C Function.injective_id he).pow + · exact fun z hz => dvd_of_jet (hq z hz) (hv z hz) + exact (hp.not_ge (by simpa only [degree_poles] using natDegree_le_of_dvd hd h)) + +private theorem reconstruct {ι : Type*} [Fintype ι] (f : ι → K[X] →ₗ[K] K) (D : ℕ) + (h : ∀ p : K[X], p.natDegree ≤ D → (∀ i, f i p = 0) → p = 0) (l : K[X] →ₗ[K] K) : + ∃ c : ι → K, ∀ p : K[X], p.natDegree ≤ D → l p = ∑ i, c i * f i p := by + classical + let V := degreeLE K (D : WithBot ℕ) + let e := LinearMap.pi (fun i => (f i).comp V.subtype) + have hi : e.ker = ⊥ := by + apply LinearMap.ker_eq_bot'.mpr + intro x hx + apply Subtype.ext + exact h x (natDegree_le_iff_degree_le.mpr (mem_degreeLE.mp x.property)) (congrFun hx) + obtain ⟨g, hg⟩ := e.exists_leftInverse_of_injective hi + let a := (l.comp V.subtype).comp g + refine ⟨fun i => a (Pi.single i 1), fun p hp => ?_⟩ + let x : V := ⟨p, mem_degreeLE.mpr (natDegree_le_iff_degree_le.mp hp)⟩ + have hx : g (e x) = x := DFunLike.congr_fun hg x + calc + l p = a (e x) := by change l p = l (g (e x)); rw [hx] + _ = ∑ i, a (Pi.single i (e x i)) := by rw [← map_sum, Finset.univ_sum_single] + _ = _ := by + apply Finset.sum_congr rfl + intro i _ + have eqn : Pi.single i (e x i) = f i p • (Pi.single i (1 : K) : ι → K) := by + ext j + simp [Pi.single_apply, e, x, mul_ite] + rw [eqn, map_smul, smul_eq_mul, mul_comm] + +/-- More regular evaluations than the numerator degree suffice to recover +every linear coefficient, including every Laurent jet. -/ +theorem reconstruct_regular (s : Finset K) (q : K[X]) (hq : ∀ z ∈ s, q.eval z ≠ 0) + (D : ℕ) (hD : D < s.card) (l : K[X] →ₗ[K] K) : + ∃ c : s → K, ∀ p : K[X], p.natDegree ≤ D → + l p = ∑ z : s, c z * (p.eval z.val / q.eval z.val) := by + have h (p : K[X]) (hp : p.natDegree ≤ D) (hv : ∀ z : s, jet z.val q 0 p = 0) : p = 0 := by + apply zero_of_jets s (fun _ => 1) (fun _ => q) hq (by simpa using hp.trans_lt hD) + intro z hz i hi + have : i = 0 := by omega + subst i + exact hv ⟨z, hz⟩ + simpa only [jet_zero] using reconstruct (fun z : s => jet z.val q 0) D h l + +/-- Regular evaluations recover even a specified coefficient at a pole. -/ +theorem recover_coefficient (s : Finset K) (q : K[X]) (hq : ∀ z ∈ s, q.eval z ≠ 0) + (D : ℕ) (hD : D < s.card) (y : K) (i : ℤ) : + ∃ c : s → K, ∀ p : K[X], p.natDegree ≤ D → + (laurent y p q).coeff i = ∑ z : s, c z * (p.eval z.val / q.eval z.val) := by + let l : K[X] →ₗ[K] K := + { toFun := fun p => (laurent y p q).coeff i + map_add' := by intros; simp [laurent, add_div] + map_smul' := by + intro c p + simp only [laurent, taylor_mul, taylor_C, Polynomial.smul_eq_C_mul, Polynomial.coe_mul, + Polynomial.coe_C, map_mul, HahnSeries.ofPowerSeries_C, HahnSeries.C_apply, mul_div_assoc, + HahnSeries.coeff_single_mul, sub_zero, smul_eq_mul, RingHom.id_apply] } + exact reconstruct_regular s q hq D hD l + +/-- The initial jets jointly determine any bounded-degree numerator +when their total length exceeds the degree bound. -/ +theorem reconstruct_jets (s : Finset K) (n : K → ℕ) (q : K → K[X]) + (hq : ∀ z ∈ s, (q z).eval z ≠ 0) (D : ℕ) (hD : D < ∑ z ∈ s, n z) (l : K[X] →ₗ[K] K) : + ∃ c : (Σ z : s, Fin (n z.val)) → K, ∀ p : K[X], p.natDegree ≤ D → + l p = ∑ i, c i * jet i.1.val (q i.1.val) i.2.val p := by + apply reconstruct + intro p hp hv + exact zero_of_jets s n q hq (hp.trans_lt hD) (fun z hz i hi => hv ⟨⟨z, hz⟩, ⟨i, hi⟩⟩) + +/-- At seams keep orders through `-L`, at insertion marks through `-1`, +and at the designated collector through `g*L`. -/ +def orders [DecidableEq K] (seams : Finset K) (collector : K) (d : K → ℕ) (g L : ℕ) + (z : K) : ℕ := + if z ∈ seams then d z + 1 - L else d z + if z = collector then g * L + 1 else 0 + +omit [Field K] in +private theorem enough_orders [DecidableEq K] {s seams : Finset K} (hs : seams ⊆ s) + {collector : K} (hc : collector ∈ s) (hc' : collector ∉ seams) (d : K → ℕ) + {g : ℕ} (hg : seams.card ≤ g) (L : ℕ) : + ∑ z ∈ s, d z < ∑ z ∈ s, orders seams collector d g L z := by + have step (z : K) : d z + (if z = collector then g * L + 1 else 0) ≤ + orders seams collector d g L z + (if z ∈ seams then L else 0) := by + unfold orders + by_cases h : z ∈ seams + · have hz : z ≠ collector := fun e => hc' (e ▸ h) + simp only [ite_eq_left h, ite_eq_right hz, add_zero] + omega + · simp [h] + have h := Finset.sum_le_sum (s := s) (fun z _ => step z) + have he : s.filter (· ∈ seams) = seams := by ext z; simp [and_iff_right_of_imp (hs ·)] + rw [Finset.sum_add_distrib, Finset.sum_add_distrib, Finset.sum_ite_eq', ite_eq_left hc, + ← Finset.sum_filter, he, Finset.sum_const, nsmul_eq_mul, Nat.cast_id] at h + have := Nat.mul_le_mul_right L hg + omega + +/-- The same Laurent reconstruction weights work for all numerators bounded +at infinity after division by the common denominator. -/ +theorem reconstruct_motion [DecidableEq K] {s seams : Finset K} (hs : seams ⊆ s) + {collector : K} (hc : collector ∈ s) (hc' : collector ∉ seams) (d : K → ℕ) + {g : ℕ} (hg : seams.card ≤ g) (L : ℕ) (x : K) : + ∃ c : (Σ z : s, Fin (orders seams collector d g L z.val)) → K, ∀ p : K[X], + p.natDegree ≤ (poles s d).natDegree → + p.eval x / (poles s d).eval x = + ∑ i, c i * (laurent i.1.val p (poles s d)).coeff ((i.2.val : ℤ) - d i.1.val) := by + have hD := enough_orders hs hc hc' d hg L + rw [← degree_poles] at hD + obtain ⟨c, he⟩ := reconstruct_jets s _ (fun z => poles (s.erase z) d) + (fun z _ => poles_eval d (Finset.notMem_erase z s)) _ hD (jet x (poles s d) 0) + refine ⟨c, fun p hp => ?_⟩ + rw [← jet_zero, he p hp] + apply Finset.sum_congr rfl + intro i _ + rw [poles_split d i.1.property, coeff_laurent _ _ _ _ (poles_eval d (Finset.notMem_erase _ _))] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end + +/- # Reading Laurent coefficients in the doubled collision coordinate -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +open Polynomial +variable {K : Type*} [Field K] + +theorem expand_taylor (P : ℕ) (hP : P ≠ 0) (z : K) (p : K[X]) : + PowerSeries.expand P hP (taylor z p : PowerSeries K) = + (p.comp (X ^ P + C z) : PowerSeries K) := by + induction p using Polynomial.induction_on' with + | add p q hp hq => simp [hp, hq, add_comp] + | monomial n c => + rw [← C_mul_X_pow_eq_monomial] + simp [PowerSeries.expand_C] + +theorem jet_of_dvd (z : K) (p q w : K[X]) (hq : q.eval z ≠ 0) (N i : ℕ) (hi : 2 * i < N) + (he : X ^ N ∣ p.comp (X ^ 2 + C z) - q.comp (X ^ 2 + C z) * w) : + jet z q i p = w.coeff (2 * i) := by + let f := PowerSeries.expand (R := K) 2 (by decide) + let a : PowerSeries K := taylor z p + let b : PowerSeries K := taylor z q + have hb : PowerSeries.constantCoeff b ≠ 0 := by simpa [b, taylor_coeff_zero] using hq + have inv : f b * f b⁻¹ = 1 := by rw [← map_mul, PowerSeries.mul_inv_cancel b hb, map_one] + have dvd : PowerSeries.X ^ N ∣ f a - f b * (w : PowerSeries K) := by + obtain ⟨v, hv⟩ := he + refine ⟨v, ?_⟩ + simpa only [a, b, f, expand_taylor, Polynomial.coe_sub, Polynomial.coe_mul, + Polynomial.coe_pow, Polynomial.coe_X] using congrArg (fun t : K[X] => (t : PowerSeries K)) hv + have dvd' : PowerSeries.X ^ N ∣ f (a * b⁻¹) - (w : PowerSeries K) := by + have e := dvd_mul_of_dvd_left dvd (f b⁻¹) + rwa [sub_mul, mul_right_comm (f b), inv, one_mul, ← map_mul] at e + have h := PowerSeries.X_pow_dvd_iff.mp dvd' (2 * i) hi + change PowerSeries.coeff i (a * b⁻¹) = _ + simpa only [map_sub, sub_eq_zero, f, PowerSeries.coeff_expand_mul, coeff_coe] using h + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end + +/- +# Coupled motion in two coordinates + +The two parameters are `z^P` and `z`, with `P` a characteristic +power. Pole bounds make the convolution at each order a finite sum. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +open Polynomial +variable {K : Type*} [Field K] + +/-- The quantity computed by `a.comp (X ^ P) * b`. -/ +def coupled (P : ℕ) (a b : K[X]) : K[X] := a.comp (X ^ P) * b + +/-- The pairs of type `Finset (ℤ × ℤ)`, constructed using `j + P * d + e`. -/ +def pairs (P d e : ℕ) (j : ℤ) : Finset (ℤ × ℤ) := + let n := j + P * d + e + if n < 0 then ∅ else + ((Finset.range (n.toNat + 1)).filter (P ∣ ·)).image + (fun i => (((i / P : ℕ) : ℤ) - d, n - i - e)) + +theorem mem_pairs {P d e : ℕ} {j : ℤ} {x : ℤ × ℤ} (h : x ∈ pairs P d e j) : + P * x.1 + x.2 = j ∧ -(d : ℤ) ≤ x.1 ∧ -(e : ℤ) ≤ x.2 := by + unfold pairs at h + dsimp only at h + split_ifs at h with he + · simp at h + obtain ⟨i, hi, rfl⟩ := Finset.mem_image.mp h + simp only [Finset.mem_filter, Finset.mem_range] at hi + have he' : (P : ℤ) * ((i / P : ℕ) : ℤ) = i := by + exact_mod_cast Nat.mul_div_cancel' hi.2 + simp only [mul_sub, he'] + have : 0 ≤ ((i / P : ℕ) : ℤ) := Int.natCast_nonneg _ + omega + +/-- The quantity computed by `(taylor z a : PowerSeries K) * (taylor z b : PowerSeries K)⁻¹`. -/ +def regular (z : K) (a b : K[X]) : PowerSeries K := + (taylor z a : PowerSeries K) * (taylor z b : PowerSeries K)⁻¹ + +theorem regular_mul (z : K) (a b : K[X]) (h : b.eval z ≠ 0) : + regular z a b * (taylor z b : PowerSeries K) = taylor z a := by + rw [regular, mul_assoc, PowerSeries.inv_mul_cancel, mul_one] + simpa [taylor_coeff_zero] using h + +variable (p l : ℕ) [ExpChar K p] + +private theorem taylor_coupled (z : K) (a b : K[X]) : + (taylor z (coupled (p ^ l) a b) : PowerSeries K) = + PowerSeries.expand (p ^ l) (expChar_pow_pos K p l).ne' + (taylor (z ^ (p ^ l)) a : PowerSeries K) * (taylor z b : PowerSeries K) := by + rw [expand_taylor, coupled, taylor_mul, Polynomial.coe_mul, taylor_apply, comp_assoc, + pow_comp, X_comp, add_pow_expChar_pow, map_pow] + +private theorem regular_coupled (z : K) (a b c d : K[X]) + (hb : b.eval (z ^ (p ^ l)) ≠ 0) (hd : d.eval z ≠ 0) : + regular z (coupled (p ^ l) a c) (coupled (p ^ l) b d) = + PowerSeries.expand (p ^ l) (expChar_pow_pos K p l).ne' (regular (z ^ (p ^ l)) a b) * + regular z c d := by + have he : (coupled (p ^ l) b d).eval z ≠ 0 := by simp [coupled, hb, hd] + have ht : (taylor z (coupled (p ^ l) b d) : PowerSeries K) ≠ 0 := by + intro hh + apply he + simpa only [constantCoeff_coe, taylor_coeff_zero, map_zero] + using congrArg PowerSeries.constantCoeff hh + apply mul_right_cancel₀ ht + rw [regular_mul _ _ _ he, taylor_coupled p l, taylor_coupled p l, + mul_mul_mul_comm, ← map_mul, regular_mul _ _ _ hb, regular_mul _ _ _ hd] + +theorem coupled_poles (z : K) (q₁ q₂ : K[X]) (d e : ℕ) : + coupled (p ^ l) ((X - C (z ^ (p ^ l))) ^ d * q₁) ((X - C z) ^ e * q₂) = + (X - C z) ^ (p ^ l * d + e) * coupled (p ^ l) q₁ q₂ := by + unfold coupled + rw [mul_comp, pow_comp, sub_comp, X_comp, C_comp, map_pow, ← sub_pow_expChar_pow, + ← pow_mul, mul_mul_mul_comm, ← pow_add] + +/-- Convolve the two Laurent expansions. The first coordinate moves at +`p^l` times the order of the second. No choice of numerator enters the +summation range. -/ +theorem coupled_coeff (z : K) (a b q₁ q₂ : K[X]) (d e : ℕ) + (h₁ : q₁.eval (z ^ (p ^ l)) ≠ 0) (h₂ : q₂.eval z ≠ 0) (j : ℤ) : + let P := p ^ l + let Q₁ := (X - C (z ^ P)) ^ d * q₁ + let Q₂ := (X - C z) ^ e * q₂ + (laurent z (coupled P a b) (coupled P Q₁ Q₂)).coeff j = + ∑ v ∈ pairs P d e j, (laurent (z ^ P) a Q₁).coeff v.1 * (laurent z b Q₂).coeff v.2 := by + intro P Q₁ Q₂ + have hq : (coupled P q₁ q₂).eval z ≠ 0 := by simp [coupled, P, h₁, h₂] + have eqn : coupled P Q₁ Q₂ = (X - C z) ^ (P * d + e) * coupled P q₁ q₂ := + coupled_poles p l z q₁ q₂ d e + rw [eqn] + let n : ℤ := j + P * d + e + by_cases low : n < 0 + · rw [coeff_below _ _ _ _ hq _ (by unfold n at low; push_cast; omega)] + rw [pairs, ite_eq_left low, Finset.sum_empty] + have hn : ((n.toNat : ℕ) : ℤ) - (P * d + e : ℕ) = j := by dsimp [n] at *; omega + have hl := coeff_laurent z (coupled P a b) (coupled P q₁ q₂) (P * d + e) hq n.toNat + rw [hn] at hl + rw [hl] + change PowerSeries.coeff n.toNat (regular z (coupled P a b) (coupled P q₁ q₂)) = _ + rw [regular_coupled p l z a q₁ b q₂ h₁ h₂, PowerSeries.coeff_mul, + Finset.Nat.sum_antidiagonal_eq_sum_range_succ_mk] + simp only [PowerSeries.coeff_expand, ite_mul, zero_mul, ← Finset.sum_filter] + have he : Function.Injective (fun i : ℕ => (((i / P : ℕ) : ℤ) - d, n - i - e)) := by + intro x y h + have h' := congrArg Prod.snd h + dsimp only at h' + omega + rw [pairs, ite_eq_right low, Finset.sum_image he.injOn] + apply Finset.sum_congr rfl + intro i hi + simp only [Finset.mem_filter, Finset.mem_range] at hi + change _ = (laurent _ a Q₁).coeff (((i / P : ℕ) : ℤ) - d) * (laurent z b Q₂).coeff (n - i - e) + have hi' : n - i = ((n.toNat - i : ℕ) : ℤ) := by omega + rw [hi', coeff_laurent _ _ _ _ h₁, coeff_laurent _ _ _ _ h₂] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end + +/- +# Two-site fusion + +Specialize the cluster expansion to offsets zero and one. Pairing the +translated modes with the reversed output wedge gives the matrix entry +used in transposition at a seam. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {F R : Type*} [Field F] [CommRing R] [Algebra F R] {r : ℕ} + +/-- Concatenates the components in the order `a.map (0, ·) ++ x.map (1, ·)`. -/ +def offsets (F : Type*) [Field F] (a x : List (Mode r)) : List (Site F r) := + a.map (0, ·) ++ x.map (1, ·) + +private def place (F : Type*) [Field F] : Mark r → Site F r ⊕ Mode r + | (.origin, x) => .inl (0, x) + | (.middle, x) => .inl (1, x) + | (_, x) => .inr x + +theorem translate_zero (x y : Mode r) : + translate ((0 : F), x) y = if x = y then 1 else 0 := by + unfold translate + by_cases hs : x.1 = y.1 + · simp only [Prod.ext_iff, hs, true_and, ↓reduceIte] + rcases lt_trichotomy x.2 y.2 with h | h | h + · simp [h.ne, zero_pow (Nat.sub_ne_zero_of_lt h)] + · simp [h] + · simp [h.ne', Nat.choose_eq_zero_of_lt h] + · simp [Prod.ext_iff, hs] + +private theorem block_place (x y : Mark r) (hx : x.1 ≠ .dual) (hy : y.1 ≠ .dual) : + blockPair (place F x) (place F y) = pairing F x y := by + obtain ⟨s, x⟩ := x + obtain ⟨t, y⟩ := y + cases s <;> cases t <;> try contradiction + all_goals + simp only [place, blockPair, translate_zero] + case middle.origin => + rw [fieldKernel_skew (0, y) (1, x), pairing_skew F (.origin, y) (.middle, x)] + simp [fieldKernel, coeff, pairing] + rfl + all_goals + by_cases h : x.1 = y.1 <;> + simp [fieldKernel, coeff, translate, pairing, Prod.ext_iff, h, eq_comm, pow_succ] + all_goals rfl + +theorem blockCoeff_offsets (a x : List (Mode r)) (b : Wedge r) : + blockCoeff (offsets F a x) b = fusion F a x b.val := by + let xs := marks .origin a ++ marks .middle x ++ marks .infinity b.val.reverse + have h : ∀ z ∈ xs, z.1 ≠ .dual := by + simp only [xs, marks, List.forall_mem_append, List.forall_mem_map] + simp + have e : (offsets F a x).map Sum.inl ++ b.val.reverse.map Sum.inr = xs.map (place F) := by + simp [xs, marks, offsets, List.map_map, Function.comp_def, place] + unfold blockCoeff fusion + rw [e, wick_map] + exact wick_eq_on _ _ _ (fun z hz t ht => block_place z t (h z hz) (h t ht)) + +/-- Two sites at `c` and `c + u²`, scaled by `u` to their doubled +energies to remove the pole. Spectators stay at fixed positions. -/ +def collision (c : F) (u : R) (N : ℕ) (a x : List (Mode r)) (ys : List (Site F r)) : R := + wick (Cluster.pair u N) ((offsets F a x).map (.moving c) ++ ys.map .fused) + +/-- Exact through degree `N-1`, with no invertibility assumption on two. -/ +theorem fusion_expansion (c : F) (u : R) (N : ℕ) (hu : u ^ N = 0) + (a x : List (Mode r)) (ys : List (Site F r)) : + collision c u N a x ys = + ∑ b : LevelLE r N, u ^ energy b.val.val * algebraMap F R (fusion F a x b.val.val) * + algebraMap F R (wick fieldKernel (b.val.val.map (c, ·) ++ ys)) := by + have h := Cluster.block u N c hu (offsets F a x) [] (ys.map .fused) + (by simp) (by simp only [List.forall_mem_map, Cluster.belongs, not_false_eq_true, implies_true]) + simp only [List.nil_append, blockCoeff_offsets] at h + rw [collision, h] + apply Finset.sum_congr rfl + intro b _ + have e := wick_map (Cluster.pair u N) Cluster.Leg.fused (b.val.val.map (c, ·) ++ ys) + simpa only [List.map_append, List.map_map, Function.comp_def, Cluster.pair, wick_hom] + using congrArg (fun t => u ^ energy b.val.val * algebraMap F R (fusion F a x b.val.val) * t) e + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- +# Moving one insertion on a sphere + +The affine trajectories consist of the identity and the constant maps +to the stationary marks. Clearing the finite collisions gives a numerator +whose degree does not exceed the denominator degree. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +open Polynomial Routing +variable {F : Type} {R : Type*} [Field F] [CommRing R] [Algebra F R] {r : ℕ} + +open scoped Classical in +/-- In the case `none`, this construction gives `![1, 0]`. -/ +def trajectories (s : Finset F) : Option s → Fin 2 → F + | none => ![1, 0] + | some z => ![0, z.val] + +open scoped Classical in +/-- The value specified by `some (-z)`. -/ +def direction (z : F) := some (-z) + +open scoped Classical in +private theorem injective_direction : Function.Injective (direction (F := F)) := + fun _ _ h => neg_injective (Option.some.inj h) + +open scoped Classical in +theorem directions_eq (s : Finset F) : + directions (trajectories s) = insert none (s.image direction) := by + ext d + constructor + · intro h + rcases Finset.mem_insert.mp h with he | h + · exact Finset.mem_insert.mpr (.inl he) + obtain ⟨_, hl, rfl⟩ := Finset.mem_image.mp h + obtain ⟨⟨i, j⟩, _, rfl⟩ := Finset.mem_image.mp hl + cases i <;> cases j <;> simp [trajectories, through, direction, div_neg] + · intro h + rcases Finset.mem_insert.mp h with he | h + · simp [he, directions] + obtain ⟨z, hz, rfl⟩ := Finset.mem_image.mp h + simpa [pole, through, trajectories, direction] using + pole_mem (trajectories s) none (some ⟨z, hz⟩) + +open scoped Classical in +private theorem none_not_mem (s : Finset F) : none ∉ s.image direction := by + simp [direction] + +open scoped Classical in +theorem denominator_eq (s : Finset F) (x : R) : + denominator (directions (trajectories s)) x 1 = + ∏ z ∈ s, (x - algebraMap F R z) := by + rw [directions_eq, denominator, Finset.prod_insert (none_not_mem s), + Finset.prod_image injective_direction.injOn] + simp [linearFactor, direction, sub_eq_add_neg] + +open scoped Classical in +theorem erase_direction (s : Finset F) (x : F) : + (directions (trajectories s)).erase (some (-x)) = directions (trajectories (s.erase x)) := by + rw [directions_eq, directions_eq] + ext y + simp [direction] + grind + +open scoped Classical in +/-- Computes the numerator by the application `correlatorPoly (trajectories s) X 1 xs`. -/ +def numerator (s : Finset F) (xs : List (Option s × Mode r)) : F[X] := + correlatorPoly (trajectories s) X 1 xs + +open scoped Classical in +/-- The quantity computed by `poles s (fun _ => weight xs / 2)`. -/ +def denominatorPoly (s : Finset F) (xs : List (Option s × Mode r)) : F[X] := + poles s (fun _ => weight xs / 2) + +open scoped Classical in +theorem degree_numerator (s : Finset F) (xs : List (Option s × Mode r)) : + (numerator s xs).natDegree ≤ (denominatorPoly s xs).natDegree := by + have h := (correlator_form (trajectories s) xs).1 + rw [directions_eq, Finset.card_insert_of_notMem (none_not_mem s), + Finset.card_image_of_injective _ injective_direction] at h + simpa [numerator, denominatorPoly, degree_poles] using h + +open scoped Classical in +theorem aeval_poles (s : Finset F) (e : ℕ) (x : R) : + aeval x (poles s (fun _ => e)) = denominator (directions (trajectories s)) x 1 ^ e := by + simp only [poles, map_prod, map_pow, map_sub, aeval_X, aeval_C, denominator_eq, Finset.prod_pow] + +open scoped Classical in +/-- Place the moving insertion at an arbitrary extension-field point. -/ +def atPoint {E : Type*} [Field E] [Algebra F E] {s : Finset F} + (x : E) (j : Option s × Mode r) : Site E r := + (j.1.elim x (fun z => algebraMap F E z.val), j.2) + +open scoped Classical in +/-- This specialization is valid even at a transcendental point over a +finite field. -/ +theorem eval_sphere_over {E : Type*} [Field E] [Algebra F E] (s : Finset F) + (xs : List (Option s × Mode r)) (x : E) (hx : ∀ z ∈ s, x ≠ algebraMap F E z) : + aeval x (numerator s xs) / aeval x (denominatorPoly s xs) = + wick fieldKernel (xs.map (atPoint x)) := by + have hd : denominator (directions (trajectories s)) x 1 ≠ 0 := by + rw [denominator_eq] + exact Finset.prod_ne_zero_iff.mpr fun z hz => sub_ne_zero.mpr (hx z hz) + have hp (z : Option s) : position (trajectories s z) x 1 = + z.elim x (fun t => algebraMap F E t.val) := by + cases z <;> simp [position, trajectories] + rw [wick_map, numerator, denominatorPoly, aeval_poles, correlator_map, aeval_X, map_one, + correlator_specialize _ _ _ hd, mul_div_cancel_left₀ _ (pow_ne_zero _ hd)] + simp only [hp, atPoint] + +open scoped Classical in +theorem eval_sphere (s : Finset F) (xs : List (Option s × Mode r)) (x : F) (hx : x ∉ s) : + (numerator s xs).eval x / (denominatorPoly s xs).eval x = + wick fieldKernel (xs.map (atPoint x)) := by + have hr : ∀ z ∈ s, x ≠ algebraMap F F z := by + intro z hz h + exact hx (h ▸ hz) + simpa only [coe_aeval_eq_eval] using eval_sphere_over s xs x hr + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end + +/- +# Laurent coefficients of a moving insertion + +At a collision with a stationary mark only the two incident blocks are +fused. All other marks are spectators. Remove their weight and the +regular denominator from the truncated polynomial identity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +open Polynomial Routing +variable {F R : Type} [Field F] [CommRing R] [Algebra F R] {r : ℕ} {s : Finset F} + +open scoped Classical in +/-- Stationary modes, moving modes, then spectators. -/ +def triple (c : s) (a x : List (Mode r)) (ys : List (s × Mode r)) : + List (Option s × Mode r) := + a.map (some c, ·) ++ x.map (none, ·) ++ ys.map (fun y => (some y.1, y.2)) + +open scoped Classical in +/-- Transforms the indexed data by `ys.map (fun y => (y.1.val, y.2))`. -/ +def spectators (ys : List (s × Mode r)) : List (Site F r) := ys.map (fun y => (y.1.val, y.2)) + +open scoped Classical in +private def leg (c : s) : Option s × Mode r → Cluster.Leg F r + | (none, i) => .moving c.val (1, i) + | (some d, i) => if d = c then .moving c.val (0, i) else .fused (d.val, i) + +open scoped Classical in +private def scale (u : R) (c : s) : Option s × Mode r → R + | (none, _) => 1 + | (some d, i) => if d = c then 1 else Cluster.weight u i + +open scoped Classical in +private theorem moving_fixed (u : R) (N : ℕ) (c d : F) (x : Site F r) (y : Mode r) + (h : c ≠ d) : + Cluster.pair u N (.moving c x) (.moving d (0, y)) = + Cluster.weight u y * Cluster.pair u N (.moving c x) (.fused (d, y)) := by + simp only [Cluster.pair, h, ↓reduceIte, mul_assoc, mul_left_comm] + +open scoped Classical in +private theorem fixed_moving (u : R) (N : ℕ) (c d : F) (x : Site F r) (y : Mode r) + (h : c ≠ d) : + Cluster.pair u N (.moving d (0, y)) (.moving c x) = + Cluster.weight u y * Cluster.pair u N (.fused (d, y)) (.moving c x) := by + rw [Cluster.pair_skew u N (.moving c x), moving_fixed _ _ _ _ _ _ h, + Cluster.pair_skew u N (.moving c x), mul_neg] + +open scoped Classical in +private theorem both_fixed (u : R) (N : ℕ) (hu : u ^ N = 0) (c d : F) (x y : Mode r) : + Cluster.pair u N (.moving c (0, x)) (.moving d (0, y)) = + Cluster.weight u x * Cluster.weight u y * Cluster.pair u N (.fused (c, x)) (.fused (d, y)) + := by + by_cases h : c = d + · simp [Cluster.pair, h, fieldKernel, Sphere.coeff] + · have hs (z : R) : shifted u z 0 N = z := by simpa using shifted_mul u z 0 N hu + simp only [Cluster.pair, h, ↓reduceIte, Cluster.sep, sub_self, map_zero, hs, fieldKernel] + unfold Sphere.coeff + split <;> simp only [map_pow, map_mul, map_natCast, map_zero, map_one, map_neg] + +open scoped Classical in +private theorem normalized_kernel (u : R) (N : ℕ) (hu : u ^ N = 0) (c : s) + (x y : Option s × Mode r) : + clusterKernel u N (fun i => projection (trajectories s i) (some (-c.val))) + (fun i => collisionOffset (trajectories s i) (some (-c.val))) x y = + scale u c x * scale u c y * Cluster.pair u N (leg c x) (leg c y) := by + have eq (x y : Option s × Mode r) : + clusterKernel u N (fun i => projection (trajectories s i) (some (-c.val))) + (fun i => collisionOffset (trajectories s i) (some (-c.val))) x y = + Cluster.pair u N + (.moving (projection (trajectories s x.1) (some (-c.val))) + (collisionOffset (trajectories s x.1) (some (-c.val)), x.2)) + (.moving (projection (trajectories s y.1) (some (-c.val))) + (collisionOffset (trajectories s y.1) (some (-c.val)), y.2)) := + by rw [Cluster.pair_moving]; rfl + rw [eq] + rcases x with ⟨_|d, x⟩ <;> rcases y with ⟨_|e, y⟩ <;> + simp only [collisionOffset, projection, trajectories, leg, scale, Matrix.cons_val_zero, + Matrix.cons_val_one, smul_eq_mul, mul_zero, sub_zero, zero_sub, neg_neg, one_mul, mul_one] + · split_ifs with he + · simp [he] + · exact moving_fixed u N _ _ _ _ (Subtype.val_injective.ne (Ne.symm he)) + · split_ifs with hd + · simp [hd] + · exact fixed_moving u N _ _ _ _ (Subtype.val_injective.ne (Ne.symm hd)) + · by_cases hd : d = c <;> by_cases he : e = c <;> + simp only [hd, he, ite_true, ite_false, mul_one, one_mul] + · exact moving_fixed u N _ _ _ _ (Subtype.val_injective.ne (Ne.symm he)) + · exact fixed_moving u N _ _ _ _ (Subtype.val_injective.ne (Ne.symm hd)) + · exact both_fixed u N hu _ _ _ _ + +open scoped Classical in +private theorem normalized_wick (u : R) (N : ℕ) (hu : u ^ N = 0) (c : s) + (a x : List (Mode r)) (ys : List (s × Mode r)) (hy : ∀ y ∈ ys, y.1 ≠ c) : + wick (clusterKernel u N (fun i => projection (trajectories s i) (some (-c.val))) + (fun i => collisionOffset (trajectories s i) (some (-c.val)))) (triple c a x ys) = + u ^ weight ys * collision c.val u N a x (spectators ys) := by + have fixed : + (ys.map (fun y => scale u c (some y.1, y.2))).prod = u ^ weight ys ∧ + ys.map (fun y => leg c (some y.1, y.2)) = (spectators ys).map .fused := by + induction ys with + | nil => simp [weight, energy, spectators] + | cons y ys ih => + simp only [List.forall_mem_cons] at hy + obtain ⟨e, t⟩ := ih hy.2 + simp only [List.map_cons, List.prod_cons, weight_cons, pow_add, e, t] + simp [leg, scale, hy.1, spectators, Cluster.weight, pow_add] + rw [wick_eq_on _ _ _ (fun z _ t _ => normalized_kernel u N hu c z t), wick_scale_rows, + ← wick_map] + simp only [triple, List.map_append, List.map_map, List.prod_append, Function.comp_def, fixed.1, + fixed.2] + simp [leg, scale, collision, offsets, List.map_map, Function.comp_def] + +open scoped Classical in +private theorem local_numerator (u : R) (N : ℕ) (hu : u ^ N = 0) (c : s) + (a x : List (Mode r)) (ys : List (s × Mode r)) (hy : ∀ y ∈ ys, y.1 ≠ c) : + let xs := triple c a x ys + let z := u ^ 2 + algebraMap F R c.val + aeval z (numerator s xs) = + aeval z (poles (s.erase c.val) (fun _ => weight xs / 2)) * + (u ^ weight ys * collision c.val u N a x (spectators ys)) := by + intro xs z + have hd : some (-c.val) ∈ directions (trajectories s) := by + rw [directions_eq] + exact Finset.mem_insert_of_mem (Finset.mem_image_of_mem _ c.property) + have h := local_correlator (trajectories s) _ hd u N hu (triple c a x ys) + simp only [localX, localY, map_neg, sub_neg_eq_add, erase_direction, + normalized_wick u N hu c a x ys hy] at h + rw [numerator, correlator_map, aeval_X, map_one, aeval_poles] + exact h + +open scoped Classical in +/-- Concatenates the components in the order `fusion F a x b.val * wick fieldKernel (b.val.map +(c, ·) ++ ys)`. -/ +def outcome (c : F) (a x : List (Mode r)) (ys : List (Site F r)) (b : Wedge r) : F := + fusion F a x b.val * wick fieldKernel (b.val.map (c, ·) ++ ys) + +open scoped Classical in +private def series (c : s) (a x : List (Mode r)) (ys : List (s × Mode r)) (N : ℕ) : F[X] := + ∑ b : LevelLE r N, X ^ (weight ys + energy b.val.val) * C (outcome c.val a x (spectators ys) + b.val) + +open scoped Classical in +private theorem local_dvd (c : s) (a x : List (Mode r)) (ys : List (s × Mode r)) + (hy : ∀ y ∈ ys, y.1 ≠ c) (N : ℕ) : + let xs := triple c a x ys + let z := X ^ 2 + C c.val + X ^ N ∣ (numerator s xs).comp z - + (poles (s.erase c.val) (fun _ => weight xs / 2)).comp z * series c a x ys N := by + intro xs z + let u := jetVar F N + have hu : u ^ N = 0 := jetVar_pow F N + have em : AdjoinRoot.mkₐ (X ^ N : F[X]) = aeval u := by ext; simp [u, jetVar] + apply AdjoinRoot.mk_eq_mk.mp + change AdjoinRoot.mkₐ (X ^ N) _ = AdjoinRoot.mkₐ (X ^ N) _ + rw [em, map_mul, aeval_comp, aeval_comp] + simp only [z, map_add, map_pow, aeval_X, aeval_C] + rw [local_numerator u N hu c a x ys hy, fusion_expansion _ _ _ hu] + congr 1 + simp only [series, map_sum, map_mul, map_pow, aeval_X, aeval_C, outcome, Finset.mul_sum, pow_add, + mul_assoc] + +open scoped Classical in +/-- Laurent coefficient at order `i - H`, with common pole bound `H`. +The degree `2*i` includes the fixed weight of the spectators. -/ +private theorem coeff_fusion_truncated (c : s) (a x : List (Mode r)) (ys : List (s × Mode r)) + (hy : ∀ y ∈ ys, y.1 ≠ c) (i N : ℕ) (hi : 2 * i < N) : + let xs := triple c a x ys + (laurent c.val (numerator s xs) (denominatorPoly s xs)).coeff + ((i : ℤ) - (weight xs / 2 : ℕ)) = + ∑ b : LevelLE r N, if weight ys + energy b.val.val = 2 * i + then outcome c.val a x (spectators ys) b.val else 0 := by + intro xs + let d : F → ℕ := fun _ => weight xs / 2 + have hq : (poles (s.erase c.val) d).eval c.val ≠ 0 := + poles_eval d (Finset.notMem_erase _ _) + rw [denominatorPoly, poles_split d c.property, coeff_laurent _ _ _ _ hq, + jet_of_dvd _ _ _ _ hq N i hi (local_dvd c a x ys hy N)] + simp [series, eq_comm] + +omit [Field F] in +open scoped Classical in +theorem weight_triple (c : s) (a x : List (Mode r)) (ys : List (s × Mode r)) : + weight (triple c a x ys) = energy a + energy x + weight ys := by + simp [triple, weight, energy, List.map_map, Function.comp_def, add_assoc] + +open scoped Classical in +private theorem outcome_odd (c : s) (a x : List (Mode r)) (ys : List (s × Mode r)) + (h : weight (triple c a x ys) % 2 = 1) (b : Wedge r) : + outcome c.val a x (spectators ys) b = 0 := by + have e := energy_mod_two ((triple c a x ys).map Prod.snd) + change weight (triple c a x ys) % 2 = _ at e + rw [h] at e + simp only [triple, List.length_append, List.length_map] at e + unfold outcome + by_cases hb : (a.length + x.length + b.val.length) % 2 = 1 + · have : fusion F a x b.val = 0 := by + apply wick_odd + simpa only [marks, List.length_append, List.length_map, List.length_reverse] using hb + rw [this, zero_mul] + · have : wick fieldKernel (b.val.map (c.val, ·) ++ spectators ys) = 0 := by + apply wick_odd + simp only [spectators, List.length_append, List.length_map] + omega + rw [this, mul_zero] + +open scoped Classical in +private theorem sum_level (e N : ℕ) (he : e ≤ N) (f : Wedge r → F) : + (∑ b : LevelLE r N, if energy b.val.val = e then f b.val else 0) = + ∑ b : Level r e, f b.val := by + rw [← Finset.sum_filter] + refine Finset.sum_bij (fun b hb => ⟨b.val, (Finset.mem_filter.mp hb).2⟩) + (fun _ _ => Finset.mem_univ _) ?_ ?_ (fun _ _ => rfl) + · intro b _ d _ h + exact Subtype.ext (congrArg (fun b : Level r e => b.val) h) + · intro b _ + exact ⟨⟨b.val, b.property.le.trans he⟩, Finset.mem_filter.mpr ⟨Finset.mem_univ _, b.property⟩, + rfl⟩ + +open scoped Classical in +/-- At Laurent order `j` the two colliding states fuse through precisely +doubled energy `energy a + energy x + 2*j`, independently of the spectators. -/ +theorem coeff_fusion (c : s) (a x : List (Mode r)) (ys : List (s × Mode r)) + (hy : ∀ y ∈ ys, y.1 ≠ c) (j : ℤ) : + let xs := triple c a x ys + let e := (energy a : ℤ) + energy x + 2 * j + (laurent c.val (numerator s xs) (denominatorPoly s xs)).coeff j = + if e < 0 then 0 else ∑ b : Level r e.toNat, outcome c.val a x (spectators ys) b.val := by + intro xs e + have hw : weight xs = energy a + energy x + weight ys := weight_triple c a x ys + let d := weight xs / 2 + by_cases low : j < -(d : ℤ) + · have he : e < 0 := by dsimp [e, d] at *; omega + rw [ite_eq_left he, denominatorPoly, poles_split _ c.property] + exact coeff_below _ _ _ _ (poles_eval _ (Finset.notMem_erase _ _)) _ low + let i := (j + d).toNat + let N := 2 * i + 1 + have hj : j = (i : ℤ) - (weight xs / 2 : ℕ) := by unfold i d at *; omega + rw [hj, coeff_fusion_truncated c a x ys hy i N (by omega)] + by_cases odd : weight xs % 2 = 1 + · simp only [outcome_odd c a x ys odd, ite_self, Finset.sum_const_zero] + have hE : e + weight ys = 2 * i := by unfold e; omega + by_cases neg : e < 0 + · rw [ite_eq_left neg] + exact Finset.sum_eq_zero (fun b _ => ite_eq_right (by omega)) + rw [ite_eq_right neg, ← sum_level _ N (by omega)] + apply Finset.sum_congr rfl + intro b _ + simp only [show weight ys + energy b.val.val = 2 * i ↔ energy b.val.val = e.toNat by omega] + +open scoped Classical in +/-- Reconstruct the fusion coefficient from regular evaluations. The +weights depend only on the marks, pole bound, and coefficient index. -/ +theorem recover_fusion (c : s) (T : Finset F) (hT : Disjoint T s) (H : ℕ) + (hH : s.card * H < T.card) (j : ℤ) : + ∃ f : T → F, ∀ (a x : List (Mode r)) (ys : List (s × Mode r)), + (∀ y ∈ ys, y.1 ≠ c) → weight (triple c a x ys) / 2 = H → + let e := (energy a : ℤ) + energy x + 2 * j + (if e < 0 then 0 else ∑ b : Level r e.toNat, outcome c.val a x (spectators ys) b.val) = + ∑ z : T, f z * wick fieldKernel ((triple c a x ys).map (atPoint z.val)) := by + let q := poles s (fun _ => H) + have hq (z : F) (hz : z ∈ T) : q.eval z ≠ 0 := + poles_eval _ (Finset.disjoint_left.mp hT hz) + obtain ⟨f, hf⟩ := recover_coefficient T q hq q.natDegree (by simpa [q, degree_poles] using hH) + c.val j + refine ⟨f, fun a x ys hy he => ?_⟩ + let xs := triple c a x ys + have e : denominatorPoly s xs = q := by unfold denominatorPoly; rw [he] + rw [← e] at hf + dsimp only + rw [← coeff_fusion c a x ys hy j, hf _ (degree_numerator s xs)] + exact Finset.sum_congr rfl fun z _ => + congrArg (f z * ·) (eval_sphere s xs z.val (Finset.disjoint_left.mp hT z.property)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Crossing/Form.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Crossing/Form.lean new file mode 100644 index 0000000000..904bb41a85 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Crossing/Form.lean @@ -0,0 +1,913 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import Mathlib.Algebra.BigOperators.Intervals +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Interpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Block +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Width +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Coupled +public import Mathlib.RingTheory.AdjoinRoot + +/-! # Splitting a binary form between its two affine charts -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Polynomial Finset + +variable {R α : Type*} [CommRing R] + +namespace BinaryForm + +theorem x (R : Type*) [CommRing R] : BinaryForm 1 (X : R[X]) 1 := by + refine ⟨natDegree_X_le, ?_⟩ + simp + +theorem y (R : Type*) [CommRing R] : BinaryForm 1 (1 : R[X]) X := by + simp [BinaryForm, reflect_one] + +theorem sub {d : ℕ} {p q a b : R[X]} (h : BinaryForm d p q) (g : BinaryForm d a b) : + BinaryForm d (p - a) (q - b) := + ⟨(natDegree_sub_le _ _).trans (max_le h.1 g.1), by rw [reflect_sub, h.2, g.2]⟩ + +theorem neg {d : ℕ} {p q : R[X]} (h : BinaryForm d p q) : BinaryForm d (-p) (-q) := by + simpa using (BinaryForm.zero d).sub h + +theorem nat (R : Type*) [CommRing R] (m : ℕ) : BinaryForm 0 (m : R[X]) (m : R[X]) := by + simpa using BinaryForm.const (m : R) + +theorem sign (R : Type*) [CommRing R] (m : ℕ) : BinaryForm 0 ((-1 : R[X]) ^ m) ((-1 : R[X]) ^ m) + := by + simpa using BinaryForm.const ((-1 : R) ^ m) + +/-- Evaluate at the common diagonal by taking complementary initial jets. -/ +theorem split {d : ℕ} {p q : R[X]} (h : BinaryForm d p q) (m : ℕ) : + p.eval 1 = (∑ i ∈ range m, p.coeff i) + ∑ i ∈ range (d + 1 - m), q.coeff i := by + have hd := h.1 + rw [eval_eq_sum_range' (by omega : p.natDegree < m + (d + 1 - m))] + simp only [one_pow, mul_one, sum_range_add] + congr 1 + rw [← sum_range_reflect q.coeff] + refine sum_congr rfl fun i hi => ?_ + rw [mem_range] at hi + rw [← h.2, coeff_reflect, revAt_le (by omega)] + congr 1 + omega + +end BinaryForm + +theorem wick_form_standard (w : α → ℕ) (k l : α → α → R[X]) + (h : ∀ x y, BinaryForm (w x + w y) (k x y) (l x y)) (xs : List α) : + BinaryForm (xs.map w).sum (wick k xs) (wick l xs) := by + have aux (x : α) (ys : List α) (d : ℕ) (P Q : List α → R[X]) + (hp : ∀ zs : List α, zs.length + 1 = ys.length → BinaryForm (d + + (zs.map w).sum) (P zs) (Q zs)) : + BinaryForm (d + w x + (ys.map w).sum) (contract (k x) P ys) (contract (l x) Q ys) := by + induction ys generalizing d P Q with + | nil => exact BinaryForm.zero _ + | cons y ys ih => + rw [contract_cons, contract_cons, List.map_cons, List.sum_cons] + apply BinaryForm.sub + · rw [show d + w x + (w y + (ys.map w).sum) = w x + w y + (d + (ys.map w).sum) by omega] + exact (h x y).mul (hp ys rfl) + · rw [show d + w x + (w y + (ys.map w).sum) = d + w y + w x + (ys.map w).sum by omega] + refine ih _ _ _ fun zs hz => ?_ + simpa only [List.map_cons, List.sum_cons, add_assoc] using hp (y :: zs) (by simp [hz]) + induction hn : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => simpa using BinaryForm.const (1 : R) + | cons x xs => + rw [wick_cons, wick_cons, List.map_cons, List.sum_cons, ← zero_add (w x)] + refine aux x xs 0 _ _ fun ys hy => ?_ + rw [zero_add] + exact ih ys.length (by simp only [List.length_cons] at hn; omega) ys rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# A polynomial four-site sphere + +Place the four marks at zero, X², Y² and infinity. Remove the poles +at zero by scaling every incident generator by its doubled energy. +At X² = Y² share the pole between the two middle marks asymmetrically, +charging mode m by m+1 on one side and by m on the other. On blocks +of equal length these two corrections to total degree cancel. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Crossing + +/-- The corner used in the `Crossing` construction. -/ +inductive Corner where + | a | b | c | d + deriving DecidableEq + +/-- Indexes the label by the coordinates of `Corner × Mode 1`. -/ +abbrev Label := Corner × Mode 1 + +/-- Transforms the indexed data by `xs.map (t, ·)`. -/ +def tag (t : Corner) (xs : List (Mode 1)) : List Label := xs.map (t, ·) + +/-- Concatenates the components in the order `tag .a a ++ tag .b b ++ tag .c c ++ tag .d +d.reverse`. -/ +def labels (a b c d : List (Mode 1)) : List Label := + tag .a a ++ tag .b b ++ tag .c c ++ tag .d d.reverse + +variable {R : Type*} [CommRing R] + +/-- The quantity computed by `2 * x.2 + 1`. -/ +def wt (x : Mode 1) := 2 * x.2 + 1 + +/-- Returns `x.2` when `flip` holds, and `x.2 + 1` otherwise. -/ +def exponent (flip : Bool) (x : Mode 1) := if flip then x.2 else x.2 + 1 + +/-- Returns `X ^ 2 - Y ^ 2` when `flip` holds, and `Y ^ 2 - X ^ 2` otherwise. -/ +def gap (flip : Bool) (X Y : R) := if flip then X ^ 2 - Y ^ 2 else Y ^ 2 - X ^ 2 + +/-- The quantity computed by `(-1) ^ y.2 * (x.2 + y.2).choose y.2`. -/ +def near (R : Type*) [CommRing R] (x y : Mode 1) : R := (-1) ^ y.2 * (x.2 + y.2).choose y.2 + +/-- In the case `(.a, x), (.b, y)`, this construction gives `Y ^ wt x * gap flip X Y ^ exponent +flip y * near R x y`. -/ +def upper (flip : Bool) (X Y : R) : Label → Label → R + | (.a, x), (.b, y) => Y ^ wt x * gap flip X Y ^ exponent flip y * near R x y + | (.a, x), (.c, y) => X ^ wt x * gap flip X Y ^ exponent (!flip) y * near R x y + | (.a, x), (.d, y) => if x = y then (X * Y) ^ wt x else 0 + | (.b, x), (.c, y) => X ^ wt x * Y ^ wt y * (if flip then -near R y x else near R x y) + | (.b, x), (.d, y) => X ^ wt y * gap flip X Y ^ exponent flip x * y.2.choose x.2 + | (.c, x), (.d, y) => Y ^ wt y * gap flip X Y ^ exponent (!flip) x * y.2.choose x.2 + | _, _ => 0 + +/-- The quantity computed by `upper flip X Y x y - upper flip X Y y x`. -/ +def kernel (flip : Bool) (X Y : R) (x y : Label) := upper flip X Y x y - upper flip X Y y x + +/-- Computes the form by the application `wick (kernel flip X Y) (labels a b c d)`. -/ +def form (flip : Bool) (X Y : R) (a b c d : List (Mode 1)) := + wick (kernel flip X Y) (labels a b c d) + +theorem skew (flip : Bool) (X Y : R) (x y : Label) : kernel flip X Y y x = -kernel flip X Y x y := + (neg_sub _ _).symm + +private def swap : Label → Label + | (.b, x) => (.c, x) + | (.c, x) => (.b, x) + | x => x + +private theorem swap_pair (X Y : R) (x y : Label) : + kernel true Y X (swap x) (swap y) = kernel false X Y x y := by + obtain ⟨s, x⟩ := x + obtain ⟨t, y⟩ := y + cases s <;> cases t <;> simp [kernel, upper, swap, gap, mul_comm] + +theorem swap_form (X Y : R) (a b c d : List (Mode 1)) : + form false X Y a b c d = (-1 : R) ^ (b.length * c.length) * form true Y X a c b d := by + have he : (labels a b c d).map swap = tag .a a ++ tag .c b ++ tag .b c ++ tag .d d.reverse := by + simp [labels, tag, swap, Function.comp_def] + have e := wick_swap_blocks (skew true Y X) (tag .a a) (tag .c b) (tag .b c) (tag .d d.reverse) + rw [← he, wick_map] at e + simpa only [swap_pair, form, labels, tag, List.length_map] using e + +variable {S : Type*} [CommRing S] (f : R →+* S) + +private theorem map_upper (flip : Bool) (X Y : R) (x y : Label) : + f (upper flip X Y x y) = upper flip (f X) (f Y) x y := by + obtain ⟨s, x⟩ := x + obtain ⟨t, y⟩ := y + cases s <;> cases t <;> simp [upper, near, gap, apply_ite f] + +theorem map_form (flip : Bool) (X Y : R) (a b c d : List (Mode 1)) : + f (form flip X Y a b c d) = form flip (f X) (f Y) a b c d := by + unfold form + rw [wick_hom] + simp only [kernel, map_sub, map_upper] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Crossing +end + +section +/- # Degree of the four-site crossing form -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Crossing + +open Polynomial + +variable (R : Type*) [CommRing R] + +private def degree : Label → ℕ + | (.b, x) => 2 * (x.2 + 1) + | (.c, x) => 2 * x.2 + | (_, x) => wt x + +private theorem upper_form (u v : Label) : + BinaryForm (degree u + degree v) (upper false (X : R[X]) 1 u v) (upper false 1 X u v) := by + obtain ⟨s, x⟩ := u + obtain ⟨t, y⟩ := v + have hx := BinaryForm.x R + have hy := BinaryForm.y R + have hg := (hy.pow 2).sub (hx.pow 2) + have hnear : BinaryForm 0 (near R[X] x y) (near R[X] x y) := + (BinaryForm.sign R y.2).mul (BinaryForm.nat R _) + cases s <;> cases t + case a.b => + simpa [degree, upper, gap, exponent] using ((hy.pow (wt x)).mul (hg.pow (y.2 + 1))).mul hnear + case a.c => + simpa [degree, upper, gap, exponent] using ((hx.pow (wt x)).mul (hg.pow y.2)).mul hnear + case a.d => + by_cases h : x = y + · simpa [degree, upper, h, two_mul] using (hx.mul hy).pow (wt x) + · simp only [upper, ite_eq_right h] + exact BinaryForm.zero _ + case b.c => + have h : degree (.b, x) + degree (.c, y) = wt x + wt y := by simp [degree, wt]; omega + rw [h] + simpa [upper] using ((hx.pow (wt x)).mul (hy.pow (wt y))).mul hnear + case b.d => + simpa [degree, upper, gap, exponent, add_comm] using + ((hx.pow (wt y)).mul (hg.pow (x.2 + 1))).mul (BinaryForm.nat R (y.2.choose x.2)) + case c.d => + simpa [degree, upper, gap, exponent, add_comm] using + ((hy.pow (wt y)).mul (hg.pow x.2)).mul (BinaryForm.nat R (y.2.choose x.2)) + all_goals exact BinaryForm.zero _ + +private theorem tag_degree (s : Corner) (xs : List (Mode 1)) : + ((tag s xs).map degree).sum + (if s = .c then xs.length else 0) = + energy xs + (if s = .b then xs.length else 0) := by + induction xs with + | nil => simp [tag, energy] + | cons x xs ih => + cases s <;> simp [tag, energy, degree, wt, Function.comp_def] at ih ⊢ <;> omega + +theorem form_degree (a b c d : List (Mode 1)) (he : b.length = c.length) : + BinaryForm (energy a + energy b + energy c + energy d) + (form false (X : R[X]) 1 a b c d) (form false 1 X a b c d) := by + have h : ((labels a b c d).map degree).sum = energy a + energy b + energy c + energy d := by + have ha := tag_degree .a a + have hb := tag_degree .b b + have hc := tag_degree .c c + have hd := tag_degree .d d.reverse + simp only [labels, List.map_append, List.sum_append] + have : energy d.reverse = energy d := by simp [energy] + simp [this] at ha hb hc hd + omega + rw [← h] + apply wick_form_standard + intro x y + exact (upper_form R x y).sub (add_comm (degree y) (degree x) ▸ upper_form R y x) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Crossing +end + +section +/- +# The diagonal specialization + +At the collision the second corner can pair only with the third. Equal +lengths force those two corners to pair fully with each other, leaving +the ordinary Kronecker pairing of the two remaining wedges. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {R α β : Type*} [CommRing R] + +private theorem isolate (k : α → α → R) (f : β → α) (h : ∀ i j, k (f i) (f j) = 0) + (xs : List β) (ys zs : List α) (hl : xs.length = ys.length) + (hz : ∀ i z, z ∈ zs → k (f i) z = 0) : + wick k (xs.map f ++ ys ++ zs) = wick k (xs.map f ++ ys) * wick k zs := by + have front (x : β) (u : List β) (v : List α) : + wick k ((x :: u).map f ++ v) = + (-1 : R) ^ u.length * contract (k (f x)) (fun l => wick k (u.map f ++ l)) v := by + rw [List.map_cons, List.cons_append, wick_cons] + exact contract_skip _ _ _ _ _ (fun _ _ _ _ => by rw [h, zero_mul]) + induction xs generalizing ys with + | nil => + have : ys = [] := List.length_eq_zero_iff.mp hl.symm + simp [this] + | cons x xs ih => + rw [List.append_assoc, front, front, contract_append _ _ _ _ (hz x)] + have eq : contract (k (f x)) (fun l => wick k (xs.map f ++ (l ++ zs))) ys = + contract (k (f x)) (fun l => wick k zs * wick k (xs.map f ++ l)) ys := by + apply contract_congr + intro l he + rw [← List.append_assoc, ih l (by simp only [List.length_cons] at hl; omega), mul_comm] + rw [eq, contract_scale] + ring + +namespace Crossing + +variable (R) + +private def chart : Label → Mark 1 + | (.b, x) => (.origin, x) + | (_, x) => (.middle, x) + +private theorem middle (b c : List (Mode 1)) : + wick (kernel false (1 : R) 1) (tag .b b ++ tag .c c) = fusion R b c [] := by + have h : marks .origin b ++ marks .middle c = (tag .b b ++ tag .c c).map chart := by + simp [marks, tag, chart, Function.comp_def] + simp only [fusion, List.reverse_nil, show marks .infinity ([] : List (Mode 1)) = [] from rfl, + List.append_nil, h, wick_map] + apply wick_eq_on + simp only [tag, List.forall_mem_append, List.forall_mem_map] + constructor <;> intro x _ <;> constructor <;> intro y _ + all_goals simp [kernel, upper, chart, pairing, Subsingleton.elim x.1 y.1] + all_goals rfl + +private theorem outside (a d : Wedge 1) : + wick (kernel false (1 : R) 1) (tag .a a.val ++ tag .d d.val.reverse) = + if a.val = d.val then 1 else 0 := by + apply wick_dual (skew false 1 1) <;> intros <;> simp [kernel, upper] + +theorem diagonal (a b c d : Wedge 1) (he : b.val.length = c.val.length) : + form false (1 : R) 1 a.val b.val c.val d.val = + (if a.val = d.val then 1 else 0) * fusion R b.val c.val [] := by + let A := tag .a a.val + let B := tag .b b.val + let C := tag .c c.val + let D := tag .d d.val.reverse + let k := kernel false (1 : R) 1 + have heven : Even (A.length * (B ++ C).length) := by + simp only [B, C, List.length_append, tag, List.length_map, he] + exact ⟨A.length * c.val.length, mul_add _ _ _⟩ + have swap := wick_swap_blocks (skew false (1 : R) 1) [] A (B ++ C) D + have hi : wick k (B ++ C ++ (A ++ D)) = wick k (B ++ C) * wick k (A ++ D) := by + apply isolate k (fun i => (.b, i)) (by simp [k, kernel, upper]) b.val C (A ++ D) + · simpa [C, tag] using he + · intro i + simp only [A, D, tag, List.forall_mem_append, List.forall_mem_map] + simp [k, kernel, upper, gap, exponent, pow_succ] + calc + _ = wick k (B ++ C ++ (A ++ D)) := by + change wick k (A ++ B ++ C ++ D) = _ + simpa only [List.nil_append, heven.neg_one_pow, one_mul, List.append_assoc] using swap + _ = _ := by rw [hi, middle, outside, mul_comm] + +end Crossing +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +/-- A four-site pairing split at fixed levels. The middle two ordered +wedges have the same length. -/ +def CrossingSlice (K : Type*) [Field K] : Prop := + ∀ a b c l M N : ℕ, 2 * a + b + c < M + N → + ∃ (P Q : Wedge 1 → Wedge 1 → LevelLE 1 M → K) + (S T : Wedge 1 → Wedge 1 → LevelLE 1 N → K), + ∀ x y z w : Wedge 1, energy x.val = a → energy y.val = b → energy z.val = c → + energy w.val = a → y.val.length = l → z.val.length = l → + (if x.val = w.val then 1 else 0) * fusion K y.val z.val [] = + (∑ i, P x y i * Q w z i) + (∑ i, S x z i * T w y i) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +/-- Finite-energy bounds on the two alternative factorizations. -/ +def FiniteCrossing (K : Type*) [Field K] : Prop := + ∀ a b H M N : ℕ, width b 0 ≤ H → 2 * a + b + H < M + N → + Crossing K (Fintype.card (Level 1 a)) (Fintype.card (Level 1 b)) + ((H + 1) ^ 2 * Fintype.card (LevelLE 1 M)) ((H + 1) ^ 2 * Fintype.card (LevelLE 1 N)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- +# Crossing independent wires + +At the second corner use the fusion preimage of each matrix unit with +vacuum output. Record the energy and length of the preimage on each cut. +The length filter makes unequal-length input pairs vanish. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere +open Finset + +variable {K : Type*} [Field K] + +open Classical in +private theorem crossing_of_fintype {X Y U V : Type} [Fintype X] [Fintype Y] [Fintype U] [Fintype V] + (A B : X → Y → U → K) (C D : X → Y → V → K) + (h : ∀ i i' j j', (if i = i' ∧ j = j' then 1 else 0) = + (∑ z, A i j z * B i' j' z) + (∑ z, C i j' z * D i' j z)) : + Crossing K (Fintype.card X) (Fintype.card Y) (Fintype.card U) (Fintype.card V) := by + let x := (Fintype.equivFin X).symm + let y := (Fintype.equivFin Y).symm + let u := (Fintype.equivFin U).symm + let v := (Fintype.equivFin V).symm + refine ⟨fun i j k => A (x i) (y j) (u k), fun i j k => B (x i) (y j) (u k), + fun i j k => C (x i) (y j) (v k), fun i j k => D (x i) (y j) (v k), ?_⟩ + intro i i' j j' + have e := h (x i) (x i') (y j) (y j') + rw [← u.sum_comp, ← v.sum_comp] at e + simpa only [x.injective.eq_iff, y.injective.eq_iff] using e + +open Classical in +private abbrev Tag (H : ℕ) := Fin (H + 1) × Fin (H + 1) +open Classical in +private abbrev Cut (H M : ℕ) := Tag H × LevelLE 1 M + +open Classical in +private def key (H : ℕ) (t : Wedge 1) : Tag H := + (⟨min (energy t.val) H, by omega⟩, ⟨min t.val.length H, by omega⟩) + +open Classical in +private theorem key_ok {H : ℕ} (t : Wedge 1) (ht : energy t.val ≤ H) : + (key H t).1.val = energy t.val ∧ (key H t).2.val = t.val.length := by + have hn := t.length_sq_le + have hl : t.val.length ≤ H := by nlinarith + simp [key, ht, hl] + +open Classical in +private abbrev Slice (K : Type*) (H M : ℕ) := Tag H → Wedge 1 → Wedge 1 → LevelLE 1 M → K + +open Classical in +private def weighted {H M : ℕ} (P : Slice K H M) (x : Wedge 1) + (v : Wedge 1 →₀ K) (s : Cut H M) : K := + ∑ t ∈ v.support, if key H t = s.1 then v t * P s.1 x t s.2 else 0 + +open Classical in +private def plain {H M : ℕ} (Q : Slice K H M) (w z : Wedge 1) (s : Cut H M) : K := + if z.val.length = s.1.2.val then Q s.1 w z s.2 else 0 + +open Classical in +private theorem collect {H M : ℕ} (P Q : Slice K H M) (x w z : Wedge 1) + (v : Wedge 1 →₀ K) : + ∑ s, weighted P x v s * plain Q w z s = + ∑ t ∈ v.support, if z.val.length = (key H t).2.val then + v t * ∑ j, P (key H t) x t j * Q (key H t) w z j else 0 := by + unfold weighted + simp_rw [sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro t _ + rw [Fintype.sum_prod_type, sum_comm] + simp only [ite_mul, zero_mul, sum_ite_eq, mem_univ, ite_true, plain] + split_ifs <;> simp [mul_sum, mul_assoc] + +open Classical in +theorem finite_of_slice (K : Type*) [Field K] (h : CrossingSlice K) : FiniteCrossing K := by + intro a b H M N hH hMN + let vac : Wedge 1 := ⟨[], by simp⟩ + choose v hv he using fun y : Level 1 b => fusion_width_length K y.val vac + have bound (y : Level 1 b) (t : Wedge 1) (ht : t ∈ (v y).support) : + energy t.val ≤ H ∧ t.val.length = y.val.val.length := by + obtain ⟨hl, hl'⟩ := hv y t ht + rw [y.property, show energy vac.val = 0 from rfl] at hl + exact ⟨Nat.cast_le.mp (hl.trans hH), hl'⟩ + choose P Q S T hp using fun i : Tag H => + h a i.1.val b i.2.val M N (by have := i.1.isLt; omega) + have size (L : ℕ) : Fintype.card (Cut H L) = (H + 1) ^ 2 * Fintype.card (LevelLE 1 L) := by + simp [Cut, Tag, pow_two] + rw [← size M, ← size N] + apply crossing_of_fintype + (fun x y => weighted P x.val (v y)) (fun w z => plain Q w.val z.val) + (fun x z => plain S x.val z.val) (fun w y => weighted T w.val (v y)) + intro x w y z + have eqy : y.val = z.val ↔ y = z := Subtype.ext_iff.symm + have eqx : x.val.val = w.val.val ↔ x = w := Subtype.ext_iff.symm.trans Subtype.ext_iff.symm + have ey : (∑ t ∈ (v y).support, v y t * fusion K t.val z.val.val []) = + if y = z then 1 else 0 := by + simpa [Finsupp.linearCombination_apply, Finsupp.sum, eqy] using + he y z.val vac (z.property.trans y.property.symm) rfl + simp_rw [mul_comm (plain S _ _ _)] + rw [collect, collect, ← sum_add_distrib] + by_cases hl : y.val.val.length = z.val.val.length + · calc + _ = (if x = w then 1 else 0) * + (∑ t ∈ (v y).support, v y t * fusion K t.val z.val.val []) := by + simp only [ey, ite_and, ite_mul, one_mul, zero_mul] + split_ifs <;> rfl + _ = _ := by + rw [mul_sum] + apply sum_congr rfl + intro t ht + obtain ⟨hb, hy⟩ := bound y t ht + obtain ⟨h₁, h₂⟩ := key_ok t hb + have hz := (h₂.trans (hy.trans hl)).symm + have hi := hp (key H t) x.val t z.val w.val x.property h₁.symm z.property w.property + h₂.symm hz + simp only [eqx] at hi + rw [ite_eq_left hz, ite_eq_left hz, mul_left_comm, hi, mul_add] + simp only [mul_comm] + · have hyz : y ≠ z := by rintro rfl; exact hl rfl + rw [ite_eq_right (fun h => hyz h.2)] + symm + apply sum_eq_zero + intro t ht + obtain ⟨hb, hy⟩ := bound y t ht + have hz : z.val.val.length ≠ (key H t).2.val := by + rw [(key_ok t hb).2, hy] + exact Ne.symm hl + rw [ite_eq_right hz, ite_eq_right hz, zero_add] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Shifted crossings from finite energies + +Take the input levels just under two quadratic energy budgets. Shrinking +the output budgets slightly leaves room for the polynomial factors in the +finite crossing and for the loss in level selection. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere +open Real Filter + +private theorem level_exists {v c : ℝ} (hv : 0 < v) (hc : 0 < c) (hc' : c < entropy) : + ∀ᶠ x : ℝ in atTop, ∃ e : ℕ, (e : ℝ) ≤ (v * x) ^ 2 ∧ exp (v * (c * x)) + ≤ Fintype.card (Level 1 e) := by + have h := (tendsto_id.const_mul_atTop hv).eventually (entropy_attained (sub_pos.mpr hc')) + filter_upwards [h, eventually_gt_atTop 0] with x hx hpos + obtain ⟨e, he, hb⟩ := hx + rw [sub_sub_cancel, id_eq, mul_left_comm] at hb + have hcard : 0 < (Fintype.card (Level 1 e) : ℝ) := by + have hlog := (show 0 < v * (c * x) by positivity).trans_le hb + by_contra! h + have : (Fintype.card (Level 1 e) : ℝ) = 0 := le_antisymm h (by positivity) + simp [this] at hlog + exact ⟨e, he, (le_log_iff_exp_le hcard).mp hb⟩ + +private theorem cut_cost {u v A : ℝ} (hu : 0 < u) (hv : 0 < v) (hA : entropy * v < A) : + ∀ᶠ x : ℝ in atTop, ∀ H M : ℕ, (H : ℝ) ≤ (u * x) ^ 2 + u * x + 1 → (M : ℝ) ≤ (v * x) ^ 2 → + (((H + 1) ^ 2 * Fintype.card (LevelLE 1 M) : ℕ) : ℝ) ≤ exp (A * x) := by + let C := (u ^ 2 + u + 2) ^ 2 * (v ^ 2 + 1) + have hC : 0 ≤ C := by unfold C; positivity + have h := (isLittleO_pow_exp_pos_mul_atTop 6 (sub_pos.mpr hA)).const_mul_left C + filter_upwards [eventually_ge_atTop 1, h.bound zero_lt_one] with x hx hl + intro H M hH hM + have hxx : x ≤ x ^ 2 := by nlinarith + have h₁ : (H : ℝ) + 1 ≤ (u ^ 2 + u + 2) * x ^ 2 := by + nlinarith only [hH, mul_le_mul_of_nonneg_left hxx hu.le, hxx, hx] + have h₂ : (M : ℝ) + 1 ≤ (v ^ 2 + 1) * x ^ 2 := by nlinarith only [hM, hx, hxx] + have h₃ : sqrt (M : ℝ) ≤ v * x := sqrt_le_iff.mpr ⟨by positivity, hM⟩ + have h₄ : C * x ^ 6 ≤ exp ((A - entropy * v) * x) := by + simpa [norm_eq_abs, abs_of_nonneg hC, abs_of_nonneg (by linarith : 0 ≤ x)] using hl + have := entropy_pos + push_cast + calc + _ ≤ ((H : ℝ) + 1) ^ 2 * (((M : ℝ) + 1) * exp (entropy * sqrt M)) := by + gcongr; exact card_levelLE_exp M + _ ≤ ((u ^ 2 + u + 2) * x ^ 2) ^ 2 * (((v ^ 2 + 1) * x ^ 2) * exp (entropy * (v * x))) + := by gcongr + _ = C * x ^ 6 * exp (entropy * (v * x)) := by unfold C; ring + _ ≤ exp ((A - entropy * v) * x) * exp (entropy * (v * x)) := by gcongr + _ = _ := by rw [← exp_add]; congr 1; ring + +private theorem levelLE_pos (e : ℕ) : 0 < Fintype.card (LevelLE 1 e) := + Fintype.card_pos_iff.mpr ⟨⟨⟨[], by simp⟩, by simp [energy]⟩⟩ + +theorem shifted_of_finite (K : Type*) [Field K] (h : FiniteCrossing K) : ShiftedCrossing K := by + intro t u α β ht hu hα hβ gap N + obtain ⟨w, hw, hw'⟩ := exists_between gap + let s := sqrt (w / (α ^ 2 + β ^ 2)) + have hw₀ : 0 < w := (show 0 < 2 * (t ^ 2 + u ^ 2) by positivity).trans hw + have hs : 0 < s := by unfold s; positivity + have hs₂ : s ^ 2 * (α ^ 2 + β ^ 2) = w := by + rw [show s ^ 2 = w / (α ^ 2 + β ^ 2) from sq_sqrt (by positivity)] + exact div_mul_cancel₀ _ (by positivity) + have hs' : s < 1 := by + have : s ^ 2 < 1 := (mul_lt_mul_iff_left₀ (show 0 < α ^ 2 + β ^ 2 by positivity)).mp + (by simpa [hs₂] using hw') + nlinarith + obtain ⟨c, hc, hc'⟩ := exists_between (mul_lt_of_lt_one_right entropy_pos hs') + have hc₀ : 0 < c := (mul_pos entropy_pos hs).trans hc + let Δ := w - 2 * (t ^ 2 + u ^ 2) + have hΔ : 0 < Δ := sub_pos.mpr hw + have hcut (v : ℝ) (hv : 0 < v) : entropy * (s * v) < v * c := by + rw [← mul_assoc, mul_comm v] + exact mul_lt_mul_of_pos_right hc hv + obtain ⟨x, hx, hN, hd, ⟨a, ha, ha'⟩, ⟨b, hb, hb'⟩, hM, hL⟩ := + ((eventually_ge_atTop 1).and ((eventually_ge_atTop (N / c)).and + ((eventually_gt_atTop ((u + 3) / Δ)).and ((level_exists ht hc₀ hc').and + ((level_exists hu hc₀ hc').and ((cut_cost hu (mul_pos hs hα) (hcut α hα)).and + (cut_cost hu (mul_pos hs hβ) (hcut β hβ)))))))).exists + let H := ⌈width b 0⌉₊ + let M := ⌊(s * α * x) ^ 2⌋₊ + let L := ⌊(s * β * x) ^ 2⌋₊ + have hH : (H : ℝ) ≤ (u * x) ^ 2 + u * x + 1 := by + have he : width b 0 = b + sqrt (b : ℝ) := by simp [width] + have hk : sqrt (b : ℝ) ≤ u * x := sqrt_le_iff.mpr ⟨by positivity, hb⟩ + unfold H + rw [he] + linarith only [Nat.ceil_lt_add_one (show 0 ≤ (b : ℝ) + sqrt b by positivity), hk, hb] + have hin : 2 * a + b + H < M + L := by + have step := mul_lt_mul_of_pos_right ((div_lt_iff₀ hΔ).mp hd) (by linarith : 0 < x) + have he : (s * α * x) ^ 2 + (s * β * x) ^ 2 = w * x ^ 2 := by rw [← hs₂]; ring + have hm : (s * α * x) ^ 2 < (M : ℝ) + 1 := Nat.lt_floor_add_one _ + have hl : (s * β * x) ^ 2 < (L : ℝ) + 1 := Nat.lt_floor_add_one _ + unfold Δ at step + have : 2 * (a : ℝ) + b + H < M + L := by linarith only [step, hx, he, hm, hl, ha, hb, hH] + exact_mod_cast this + have cross := h a b H M L (Nat.le_ceil _) hin + refine ⟨c * x, _, _, _, _, ?_, Nat.mul_pos (by positivity) (levelLE_pos _), + Nat.mul_pos (by positivity) (levelLE_pos _), ha', hb', ?_, ?_, cross⟩ + · rw [mul_comm]; exact (div_le_iff₀ hc₀).mp hN + · rw [← mul_assoc] + exact hM H M hH (Nat.floor_le (sq_nonneg _)) + · rw [← mul_assoc] + exact hL H L hH (Nat.floor_le (sq_nonneg _)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- +# The two local charts of the crossing + +At zero, fuse the first two finite sites. Interchanging the middle +blocks gives the expansion at infinity. In either chart the cleared +pole contributes one common polynomial factor at fixed energies. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Crossing + +variable (F : Type*) [Field F] {R : Type*} [CommRing R] [Algebra F R] + +private def point : Label → Cluster.Leg F 1 + | (.a, x) => .moving 0 (0, x) + | (.b, x) => .moving 0 (1, x) + | (.c, x) => .fused (1, x) + | (.d, x) => .test 0 x + +private def charge (f : Bool) : Label → ℕ + | (.b, x) => exponent f x + | (.c, x) => exponent (!f) x + | _ => 0 + +private theorem coeff_eq (x y : Mode 1) (z : R) : + coeff x y z = near R x y * z ^ (x.2 + y.2 + 1) := by + simp only [coeff, near, ite_eq_left (Subsingleton.elim x.1 y.1)] + +private theorem translate_one (x y : Mode 1) : translate ((1 : F), x) y = y.2.choose x.2 := by + simp [translate, Subsingleton.elim x.1 y.1] + +private theorem near_swap (x y : Mode 1) : + (-1 : R) ^ (x.2 + y.2 + 1) * near R x y = -near R y x := by + simpa only [coeff_eq, one_pow, mul_one, one_mul, mul_comm] using coeff_skew y x (1 : R) + +variable (u : R) (N : ℕ) (f : Bool) + +private theorem gap_cancel (hu : u ^ N = 0) (x y : Mode 1) : + gap f u 1 ^ exponent f x * gap f u 1 ^ exponent (!f) y * + coeff x y (shifted u 1 1 N) = if f then -near R y x else near R x y := by + have e : exponent f x + exponent (!f) y = x.2 + y.2 + 1 := by + cases f <;> simp [exponent] <;> omega + have h : (1 - u ^ 2) * shifted u 1 1 N = 1 := by + simpa [mul_comm] using shifted_mul u 1 1 N hu + rw [coeff_eq, ← pow_add, e, mul_comm (near R x y), ← mul_assoc, ← mul_pow] + cases f with + | false => simp [gap, h] + | true => + have ht : gap true u 1 * shifted u 1 1 N = -1 := by + simp only [gap, ↓reduceIte, one_pow, ← neg_sub (1 : R), neg_mul, h] + simp only [ht, ↓reduceIte, near_swap] + +private theorem local_pair (hu : u ^ N = 0) (x y : Label) : + kernel f u 1 x y = gap f u 1 ^ charge f x * gap f u 1 ^ charge f y * + Cluster.pair u N (point F x) (point F y) := by + let P (i j : Corner) := ∀ x y : Mode 1, kernel f u 1 (i, x) (j, y) = + gap f u 1 ^ charge f (i, x) * gap f u 1 ^ charge f (j, y) * + Cluster.pair u N (point F (i, x)) (point F (j, y)) + have symm {i j} (h : P i j) : P j i := by + intro x y + rw [skew f u 1 (i, y), h, Cluster.pair_skew u N (point F (i, y)), mul_neg] + ac_rfl + have hh (i : Corner) : P i i := by + intro x y + cases i <;> simp [kernel, upper, Cluster.pair, point, fieldKernel, coeff] + have ab : P .a .b := by + intro x y + simp [kernel, upper, charge, point, Cluster.pair, fieldKernel, coeff_eq, near] + have ac : P .a .c := by + intro x y + have h : shifted u 1 0 N = 1 := by simpa using shifted_mul u 1 0 N hu + simp [kernel, upper, charge, point, Cluster.pair, Cluster.sep, Cluster.weight, wt, h, coeff_eq] + ring + have ad : P .a .d := by + intro x y + simp only [kernel, upper, sub_zero, charge, point, Cluster.pair, Cluster.movingDual, + ↓reduceIte, pow_zero, one_mul, mul_one, translate_zero] + by_cases h : x = y <;> simp [h, wt, Cluster.weight] + have bc : P .b .c := by + intro x y + simp only [kernel, upper, sub_zero, charge, point, Cluster.pair, Cluster.sep, Cluster.weight, + wt, sub_zero, inv_one, map_one, one_pow, mul_one] + rw [← gap_cancel u N f hu] + ring + have bd : P .b .d := by + intro x y + simp [kernel, upper, charge, point, Cluster.pair, Cluster.movingDual, + Cluster.weight, wt, translate_one] + ring + have cd : P .c .d := by + intro x y + simp [kernel, upper, charge, point, Cluster.pair, Cluster.dualCoeff, translate_one] + obtain ⟨i, x⟩ := x + obtain ⟨j, y⟩ := y + suffices P i j from this x y + cases i <;> cases j <;> first | exact hh _ | assumption | apply symm; assumption + +private theorem charge_sum (a b c d : List (Mode 1)) (he : b.length = c.length) : + ((labels a b c d).map (charge f)).sum = (energy b + energy c) / 2 := by + have hi (b : List (Mode 1)) : + 2 * (b.map (exponent true)).sum + b.length = energy b ∧ + 2 * (b.map (exponent false)).sum = energy b + b.length := by + induction b with + | nil => simp [energy] + | cons x xs ih => + simp only [List.map_cons, List.sum_cons, exponent, Bool.false_eq_true, ↓reduceIte, + List.length_cons, energy] at * + omega + have hb := hi b + have hc := hi c + cases f + · have h : (b.map (exponent false)).sum + (c.map (exponent true)).sum = + (energy b + energy c) / 2 := by omega + simpa [labels, tag, charge, Function.comp_def] using h + · have h : (b.map (exponent true)).sum + (c.map (exponent false)).sum = + (energy b + energy c) / 2 := by omega + simpa [labels, tag, charge, Function.comp_def] using h + +private theorem prod_pow (q : R) (xs : List Label) : + (xs.map (fun x => q ^ charge f x)).prod = q ^ (xs.map (charge f)).sum := by + induction xs with + | nil => simp + | cons x xs ih => simp only [List.map_cons, List.sum_cons, List.prod_cons, ih, pow_add] + +private theorem dualCoeff_eq (x : Site F 1) (y : Mode 1) : + Cluster.dualCoeff x 0 y = algebraMap F R (translate x y) := by + obtain ⟨c, i⟩ := x + by_cases h : c = 0 + · subst c + rw [translate_zero] + simp [Cluster.dualCoeff, apply_ite (algebraMap F R)] + · simp [Cluster.dualCoeff, h] + +private theorem after_fusion (b c : List (Mode 1)) (d : Wedge 1) : + wick (Cluster.pair u N) + (b.map (fun i => .fused ((0 : F), i)) ++ c.map (fun i => .fused (1, i)) ++ + d.val.reverse.map (Cluster.Leg.test 0)) = algebraMap F R (fusion F b c d.val) := by + let place : Site F 1 ⊕ Mode 1 → Cluster.Leg F 1 := Sum.elim .fused (.test 0) + have hp (x y : Site F 1 ⊕ Mode 1) : + Cluster.pair u N (place x) (place y) = algebraMap F R (blockPair x y) := by + cases x <;> cases y <;> simp [place, Cluster.pair, dualCoeff_eq, blockPair] + have h := wick_map (Cluster.pair u N) place + ((offsets F b c).map Sum.inl ++ d.val.reverse.map Sum.inr) + simp only [hp, ← wick_hom] at h + rw [← blockCoeff_offsets] + simpa [blockCoeff, offsets, Function.comp_def, place] using h + +/-- In a nilpotent chart the four-site form factors through one mode +space. The shared pole factor depends only on the incident energies. -/ +theorem local_chart (hu : u ^ N = 0) (a b c d : Wedge 1) (he : b.val.length = c.val.length) : + form f u 1 a.val b.val c.val d.val = + gap f u 1 ^ ((energy b.val + energy c.val) / 2) * + ∑ z : LevelLE 1 N, u ^ energy z.val.val * + algebraMap F R (fusion F a.val b.val z.val.val * fusion F z.val.val c.val d.val) := by + unfold form + rw [funext fun x => funext (local_pair F u N f hu x), wick_scale_rows, + prod_pow, charge_sum f _ _ _ _ he, ← wick_map] + congr 1 + let ys := c.val.map (fun i => Cluster.Leg.fused ((1 : F), i)) ++ + d.val.reverse.map (Cluster.Leg.test (0 : F)) + have ha : (labels a.val b.val c.val d.val).map (point F) = + (offsets F a.val b.val).map (Cluster.Leg.moving 0) ++ ys := by + simp [labels, tag, point, offsets, ys, Function.comp_def] + rw [ha] + have h := Cluster.block u N (0 : F) hu (offsets F a.val b.val) [] ys (by simp) (by + simp only [ys, List.forall_mem_append, List.forall_mem_map, Cluster.belongs, + not_false_eq_true, implies_true, and_self]) + simp only [List.nil_append, blockCoeff_offsets] at h + rw [h] + apply Finset.sum_congr rfl + intro z _ + rw [map_mul, ← mul_assoc, ← after_fusion F u N z.val.val c.val d] + simp only [ys, List.append_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Crossing +end + +/- # Factoring the low-degree coefficients in either chart -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Crossing + +open Polynomial +variable (F : Type*) [Field F] + +/-- The sum of `(gap f (X : F[X]) 1 ^ t * X ^ e).coeff i` indexed by `i ∈ Finset.range m`. -/ +def cutWeight (f : Bool) (m t e : ℕ) : F := + ∑ i ∈ Finset.range m, (gap f (X : F[X]) 1 ^ t * X ^ e).coeff i + +private theorem truncated (f : Bool) (a b c d : Wedge 1) (he : b.val.length = c.val.length) + (N : ℕ) : X ^ N ∣ form f (X : F[X]) 1 a.val b.val c.val d.val - + gap f X 1 ^ ((energy b.val + energy c.val) / 2) * + ∑ z : LevelLE 1 N, X ^ energy z.val.val * + C (fusion F a.val b.val z.val.val * fusion F z.val.val c.val d.val) := by + let q := AdjoinRoot.mk (X ^ N : F[X]) + have hu : q X ^ N = 0 := by rw [← map_pow, AdjoinRoot.mk_eq_zero] + apply AdjoinRoot.mk_eq_mk.mp + change q _ = q _ + have hg : q (gap f X 1) = gap f (q X) 1 := by cases f <;> simp [gap] + have hc (z : F) : q (C z) = algebraMap F (AdjoinRoot (X ^ N : F[X])) z := rfl + simp only [map_form, map_one, map_mul, map_sum, map_pow, hg, hc] + simpa only [map_mul] using local_chart F (q X) N f hu a b c d he + +theorem cut (f : Bool) (a b c d : Wedge 1) (he : b.val.length = c.val.length) + (m N : ℕ) (hm : m ≤ N) : + (∑ i ∈ Finset.range m, (form f (X : F[X]) 1 a.val b.val c.val d.val).coeff i) = + ∑ z : LevelLE 1 N, cutWeight F f m ((energy b.val + energy c.val) / 2) (energy z.val.val) * + (fusion F a.val b.val z.val.val * fusion F z.val.val c.val d.val) := by + have h := X_pow_dvd_iff.mp (truncated F f a b c d he N) + unfold cutWeight + simp_rw [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i hi + specialize h i ((Finset.mem_range.mp hi).trans_le hm) + rw [coeff_sub, sub_eq_zero, Finset.mul_sum, finsetSum_coeff] at h + simpa only [← mul_assoc, coeff_mul_C] using h + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Crossing +end + +/- +# Shifted crossing by splitting a binary form + +At equal coordinates the four-site polynomial is a product of two +pairings. The first coefficients factor across one cut. Read the +remaining coefficients backwards in the other chart for the other +cut. Fusion with vacuum output converts the middle pairing to a wire. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Polynomial + +namespace Crossing + +variable (F : Type*) [Field F] + +private theorem eval_one (x y z w : List (Mode 1)) : + (form false (X : F[X]) 1 x y z w).eval 1 = form false (1 : F) 1 x y z w := by + simpa using map_form (evalRingHom (1 : F)) false X 1 x y z w + +private theorem other (x y z w : Wedge 1) (he : y.val.length = z.val.length) + (m N : ℕ) (hm : m ≤ N) : + (∑ i ∈ Finset.range m, (form false 1 (X : F[X]) x.val y.val z.val w.val).coeff i) = + (-1 : F) ^ (y.val.length * z.val.length) * + ∑ b : LevelLE 1 N, cutWeight F true m ((energy z.val + + energy y.val) / 2) (energy b.val.val) * + (fusion F x.val z.val b.val.val * fusion F b.val.val y.val w.val) := by + rw [← cut F true x z y w he.symm m N hm, swap_form, Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + rw [show (-1 : F[X]) ^ (y.val.length * z.val.length) = + C ((-1 : F) ^ (y.val.length * z.val.length)) by simp, coeff_C_mul] + +theorem slice : CrossingSlice F := by + intro a b c l M N h + let m := 2 * a + b + c + 1 - M + refine ⟨fun x y i => cutWeight F false M ((b + c) / 2) (energy i.val.val) * fusion F x.val y.val + i.val.val, + fun w z i => fusion F i.val.val z.val w.val, + fun x z i => (-1 : F) ^ (l * l) * cutWeight F true m ((c + b) / 2) (energy i.val.val) * + fusion F x.val z.val i.val.val, + fun w y i => fusion F i.val.val y.val w.val, ?_⟩ + intro x y z w hx hy hz hw hyl hzl + have he := hyl.trans hzl.symm + have eq := (form_degree F x.val y.val z.val w.val he).split M + rw [eval_one, diagonal F x y z w he, hx, hy, hz, hw, + show a + b + c + a + 1 - M = m by unfold m; omega, + cut F false x y z w he M M le_rfl, other F x y z w he m N (by unfold m; omega)] at eq + simpa only [hy, hz, hyl, hzl, Finset.mul_sum, mul_assoc] using eq + +end Crossing + +theorem shifted_crossing (K : Type*) [Field K] : ShiftedCrossing K := + shifted_of_finite K (finite_of_slice K (Crossing.slice K)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Debit/Legs.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Debit/Legs.lean new file mode 100644 index 0000000000..b6dc812c58 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Debit/Legs.lean @@ -0,0 +1,457 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Squares +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.History +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Pins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Host +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows + +/-! # Charges of all chunk and station positions at one cell -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +open Finset Packing Rounds + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) {h D T R g k : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + +omit [Field F] [Fintype E] [Fintype K] in +open Classical in +theorem push_home (f : S.Position → ℝ) (v : V) : + push S.home f v = (∑ i, f (.inl (.inl ⟨v, i⟩))) + + (f (.inl (.inr (.inl v))) + f (.inl (.inr (.inr v)))) + + ((∑ i, f (.inr (.inl (v, i)))) + ∑ i, f (.inr (.inr (v, i)))) := by + unfold push + simp only [Fintype.sum_sum_type, home, Grid.point] + change (∑ i : Place C, if i.1 = v then f (.inl (.inl i)) else 0) + + ((∑ x, if x = v then f (.inl (.inr (.inl x))) else 0) + + (∑ x, if x = v then f (.inl (.inr (.inr x))) else 0)) + + (push Prod.fst (fun x => f (.inr (.inl x))) v + push Prod.fst (fun x => f (.inr (.inr x))) v) + = _ + rw [sum_place, push_fst, push_fst] + simp + +omit [Fintype V] in +open Classical in +private theorem distribute {I : Type} [Fintype I] (v : V) (f : I → V) (y : I → Fin M → ℕ) + (x : I → ℝ) (hb : ∀ i, (∑ j, (y i j : ℝ)) ≤ x i) : + (∑ j, ((∑ i, if f i = v then y i j else 0 : ℕ) : ℝ)) ≤ push f x v := by + simp only [Nat.cast_sum, Nat.cast_ite, Nat.cast_zero] + rw [sum_comm] + apply sum_le_sum + intro i _ + by_cases h : f i = v <;> simp [h, hb] + +variable {e : E → ℕ} (p : Profile C e) (L : ℕ) (v : V) +local notation "Z" => (S.backdrop.emitted p L) + +open Classical in +private theorem chambers : + (∑ j, ((Z).arity (.inr (.inl (v, j))) : ℝ)) + (∑ j, ((Z).arity (.inr (.inr (v, j))) : ℝ)) ≤ + S.backdrop.chamberLoad e v := by + have hm (f : E → V) := distribute v f (fun i j => p.widths.seam (i, j)) (seamWidth C e) + (fun i => Chunk.total_width r (p.1 (.inl i))) + have ha := distribute v Sigma.fst (fun i j => p.widths.leg (.inl (i, j))) + (fun i => proxy M r (item C i).a) (fun i => Chunk.total_width r (p.1 (.inr i))) + have hb := distribute v Sigma.fst (fun i j => p.widths.leg (.inr (i, j))) + (fun i => proxy M t (item C i).b) (fun i => Chunk.total_width t (p.2 i)) + have he : push Sigma.fst (legWidth C) v = push Sigma.fst (fun i => proxy M r (item C i).a) v + + push Sigma.fst (fun i => proxy M t (item C i).b) v := by + simp only [push, legWidth, ← sum_add_distrib, ite_add_ite, add_zero] + simp only [S.backdrop.chamberA p L v, S.backdrop.chamberB p L v, Nat.cast_add, sum_add_distrib, + Backdrop.chamberLoad, he] + rw [add_assoc] + exact add_le_add (add_le_add (hm _) (hm _)) (add_le_add ha hb) + +open Classical in +theorem cell_emitted : + push S.home (fun i => ((Z).arity i : ℝ)) v ≤ 3 * S.ordinaryLoad v + + (∑ i, S.stationLoad ⟨v, i⟩) + S.backdrop.chamberLoad e v := by + have ar (i : Place C) : ((Z).arity (.inl (.inl i)) : ℝ) ≤ + S.stationLoad i + (∑ k ∈ S.reads i, Y.width k : ℕ) := by + have h := S.backdrop.station_le p L (.inl i) + have hp : push S.backdrop.owner (legWidth C) (.inl i) = legWidth C i := by simp [push] + rw [hp, arity_item] at h + unfold stationLoad exteriorLoad + push_cast at h ⊢ + linarith only [h] + have hi := sum_le_sum (s:=univ) (fun i _ => ar ⟨v, i⟩) + rw [sum_add_distrib] at hi + have hg : (∑ i, ∑ k ∈ S.reads ⟨v, i⟩, Y.width k) ≤ S.ordinaryLoad v := by + unfold ordinaryLoad + rw [sum_place] + exact Nat.le_add_left .. + have hg' := (Nat.cast_le (α:=ℝ)).mpr hg + rw [Nat.cast_sum] at hg' + have ht := S.hubs_load p L (.inl v) + have hu := S.hubs_load p L (.inr v) + simp only [Sum.elim_inl, Sum.elim_inr, id_eq] at ht hu + rw [push_home] + linarith only [hi, hg', ht, hu, S.chambers p L v] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +end + +/- # Local charges of collector and residue legs -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +open Finset Packing Rounds + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) {h D T R g k : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + +variable {S} (G : S.Geo P k) + +open Classical in +/-- Counts the elements of `{i : Fin (C v).stations.length // G.frozen ⟨v, i⟩}`. -/ +def Geo.collectorCount (v : V) := Fintype.card {i : Fin (C v).stations.length // G.frozen ⟨v, i⟩} + +omit [Field F] [Fintype E] [Fintype K] in +open Classical in +theorem Geo.sum_collectorCount : ∑ v, G.collectorCount v = Fintype.card {i // G.frozen i} := by + simp only [collectorCount, Fintype.card_subtype, card_eq_sum_ones, sum_filter, Fintype.sum_sigma] + +namespace Geo.Raw +open SphereScale (Scales size budget q) + +variable {G} {e : E → ℕ} {thin : Place C → Prop} {selector : K → Prop} {ℓ L B m : ℕ} + (hr : G.Raw ℓ L B m e thin selector) (s : Scales g ℓ D T L B m) + (ha : M * r = m * B) (hb : M * t = m) (hM : M = SphereScale.chunks ℓ D) + +include hr s ha hb hM + +omit [Field F] [Fintype K] in +open Classical in +private theorem mobile_legs (v : V) : + (∑ j, if G.frozen ⟨v, j⟩ then 0 else legWidth C ⟨v, j⟩) ≤ 2 * (budget g : ℝ) ^ 2 * D * T := by + let f (i : Place C) := if G.frozen i then 0 else legWidth C i + have hf (i : Place C) : f i ≤ legWidth C i := by + unfold f + split_ifs <;> first | exact legWidth_nonneg .. | rfl + have hh := site_load hr s ha hb hM v f hf ((D : ℝ) ^ 3 * (T / (q ℓ D : ℝ))) (by positivity) + (fun i _ => by + unfold f + split_ifs with hi + · positivity + · exact hr.residue_le s ha hb hM i hi) + have he : (D : ℝ) ^ 5 * ((D : ℝ) ^ 3 * (T / (q ℓ D : ℝ))) ≤ T := by + rw [← mul_assoc, ← pow_add] + exact (room s.Dpos (by decide)).trans + (div_le_self (by positivity) (one_le_pow₀ (by exact_mod_cast s.Dpos))) + have hp : 1 ≤ (budget g : ℝ) ^ 2 * D := by + have : 1 ≤ budget g ^ 2 * D := + Nat.mul_pos (pow_pos (by have := SphereScale.budget_large g; omega) _) s.Dpos + exact_mod_cast this + change (∑ j, f ⟨v, j⟩) ≤ _ + linarith only [hh, he, mul_le_mul_of_nonneg_right hp (Nat.cast_nonneg T)] + +open Classical in +theorem cell_legs (v : V) : + (∑ i, S.stationLoad ⟨v, i⟩) + S.backdrop.chamberLoad e v ≤ + (9 * (budget g : ℝ) ^ 2 + 21 * budget g * G.collectorCount v) * D * T := by + let cost : ℝ := 21 * budget g * D * T + have single (i : Place C) : S.stationLoad i + legWidth C i ≤ + 2 * (if G.frozen i then 0 else legWidth C i) + if G.frozen i then cost else 0 := by + unfold stationLoad + by_cases hi : G.frozen i + · have ht : (S.exteriorLoad i : ℝ) ≤ budget g * (D : ℝ) * T + := by exact_mod_cast hr.exterior i hi + rw [ite_eq_left hi, ite_eq_left hi] + unfold cost + linarith only [ht, hr.leg_le s ha hb hM i] + · have hl j : S.left j ≠ i := fun he => hi (he ▸ G.left j) + have hh j : S.right j ≠ i := fun he => hi (he ▸ G.right j) + simp [hi, exteriorLoad, hl, hh, two_mul] + have hi := sum_le_sum (s:=univ) (fun i _ => single ⟨v, i⟩) + rw [sum_add_distrib, sum_add_distrib, ← mul_sum] at hi + have cnt : (∑ j, if G.frozen ⟨v, j⟩ then cost else 0) = G.collectorCount v * cost := by + simp [collectorCount, Fintype.card_subtype, ← sum_filter] + rw [cnt] at hi + unfold cost at hi + change _ + (push S.src _ v + push S.dst _ v + push Sigma.fst (legWidth C) v) ≤ _ + rw [show push Sigma.fst (legWidth C) v = ∑ i, legWidth C ⟨v, i⟩ from sum_place _ _] + linarith only [hi, seam_load hr s ha hM v, hr.mobile_legs s ha hb hM v] + +end Geo.Raw +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +end + +/- # Total relay cost over one original station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +open Packing Finset + +variable {F V I : Type} [Field F] {a b : Wire} {d : ℕ} + {G : Bundled F a b} {T : Trie V d} (H : Fanout G T I) + +open scoped Classical in +private theorem per_depth (v : G.V) (j : Fin (d + 1)) : + (∑ t : Address d, H.route.net.arity (.inr (v, j, t))) ≤ 2 * G.arity v := by + have side (f g : G.E → G.V) : + (∑ t : Address d, ∑ e, if H.side (f e) (g e) j = (v, j, t) then G.width e else 0) = + ∑ e, if f e = v then G.width e else 0 := by + rw [sum_comm] + apply sum_congr rfl + intro e _ + by_cases he : f e = v <;> simp [Fanout.side, he] + simp_rw [Routes.relay_arity, hits] + rw [← mul_sum, sum_add_distrib, side, side] + unfold Bundled.arity + omega + +open scoped Classical in +theorem push_root {X : Type} [Fintype X] (f : Node X d → ℝ) (x : X) : + push Print.root f x = f (.inl x) + ∑ j, ∑ t, f (.inr (x, j, t)) := by + unfold push Print.root + rw [Fintype.sum_sum_type] + change (∑ j, if j = x then f (.inl j) else 0) + push Prod.fst (fun i => f (.inr i)) x = _ + rw [push_fst, Fintype.sum_prod_type] + simp + +open scoped Classical in +theorem charge_at_root (u : ℕ) (v : G.V) : + push Print.root (fun z => (H.route.net.arity z : ℝ) + u) v ≤ + (2 * (d + 1) + 1 : ℕ) * (G.arity v : ℝ) + (1 + (d + 1) * 2 ^ d : ℕ) * (u : ℝ) := by + rw [push_root, Routes.old_arity] + have hd (j : Fin (d + 1)) : + (∑ t : Address d, ((H.route.net.arity (.inr (v, j, t)) : ℝ) + u)) ≤ 2 * G.arity v + 2 ^ d * u + := by + have hh : (∑ t : Address d, (H.route.net.arity (.inr (v, j, t)) : ℝ)) ≤ 2 * G.arity v := by + exact_mod_cast H.per_depth v j + rw [sum_add_distrib] + simpa only [sum_const, card_univ, Address, Fintype.card_fun, Fintype.card_fin, + Fintype.card_bool, + nsmul_eq_mul, Nat.cast_pow, Nat.cast_ofNat] using add_le_add_left hh ((2 : ℝ) ^ d * u) + have ht := sum_le_sum (s:=univ) (fun j _ => hd j) + simp only [sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul] at ht + push_cast at ht ⊢ + linarith only [ht] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +end + +/- # Padding and routing the stations over a single cell -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +open Packing Finset + +variable {F V I X : Type} [Field F] {a b : Wire} {c d D T u : ℕ} + {G : Bundled F a b} {J : Trie V (c * d)} (H : Fanout G J I) + +open scoped Classical in +private theorem affine_sum {Y : Type} [Fintype Y] (f : Y → X) (g : Y → ℝ) (A B : ℝ) (x : X) : + push f (fun v => A * (g v + B)) x = A * (push f g x + push f (fun _ => 1) x * B) := by + simp only [push, sum_mul, ← sum_add_distrib, mul_sum] + apply sum_congr rfl + intro v _ + by_cases h : f v = x <;> simp [h] + +open scoped Classical in +theorem charge_cell (hD : D = 2 ^ d) (home : G.V → X) (x : X) (M : ℝ) + (count : push home (fun _ => 1) x ≤ (D : ℝ) ^ c) + (mass : push home (fun t => (G.arity t : ℝ)) x ≤ M) + (deg : ∀ v, G.degree v ≤ D ^ c) (pad : (u : ℝ) * ((D : ℝ) ^ c) ^ 3 ≤ T) : + push (home ∘ Print.root) (fun v => ((H.pad u).route.net.arity v : ℝ) + u) x ≤ + (2 * ((c : ℝ) * d + 1) + 1) * (M + 2 * T) := by + let B := (D : ℝ) ^ c + let A := 2 * ((c : ℝ) * d + 1) + 1 + have b : 1 ≤ B := one_le_pow₀ (by rw [hD]; exact_mod_cast (Nat.two_pow_pos d)) + have eq : (2 : ℝ) ^ (c * d) = B := by + unfold B + rw [hD, Nat.cast_pow, Nat.cast_ofNat, ← pow_mul, mul_comm] + have slots : 1 + ((c : ℝ) * d + 1) * B ≤ A * B := by + unfold A + linarith only [b, show 0 ≤ (c : ℝ) * d * B by positivity] + have atRoot (i : G.V) : + push Print.root (fun v => ((H.pad u).route.net.arity v : ℝ) + u) i ≤ A * ((G.arity i : ℝ) + + 2 * u * B) := by + have hb := (H.pad u).charge_at_root u i + push_cast at hb + rw [eq] at hb + have ht : ((G.pad u).arity i : ℝ) ≤ G.arity i + u * B := by + have hn := (G.arity_pad u i).trans (Nat.add_le_add_left (Nat.mul_le_mul_left u (deg i)) _) + unfold B + exact_mod_cast hn + calc + _ ≤ A * (G.arity i + u * B) + A * B * u := hb.trans (add_le_add + (mul_le_mul_of_nonneg_left ht (by positivity)) + (mul_le_mul_of_nonneg_right slots (by positivity))) + _ = _ := by ring + rw [← push_comp] + refine (push_le_push home atRoot x).trans ?_ + rw [affine_sum] + have cheap : (u : ℝ) * B ^ 2 ≤ T := (mul_le_mul_of_nonneg_left + (pow_le_pow_right₀ b (by decide : 2 ≤ 3)) (by positivity)).trans pad + apply mul_le_mul_of_nonneg_left _ (by positivity) + exact add_le_add mass ((mul_le_mul_of_nonneg_right count (by positivity)).trans (by + change B * (2 * u * B) ≤ _ + linarith only [cheap])) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +end + +/- # A uniform per-cell debit for every possible profile -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +open Finset Packing Rounds + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) {h D T R g k : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + +variable {S} (G : S.Geo P k) + +omit [Field F] [Fintype E] [Fintype K] in +include G in +open Classical in +theorem Geo.home_count (hd : 4 ≤ D) (v : V) : + push S.home (fun _ => 1) v ≤ (D : ℝ) ^ radius k := by + rw [push_home] + simp only [sum_const, card_univ, nsmul_eq_mul, mul_one, Fintype.card_fin] + have hc : (C v).stations.length + (1 + 1) + (M + M) ≤ 6 * D ^ k := by + have := G.count v + have := G.chunks + have := pow_pos (show 0 < D by omega) k + omega + have hh : 6 * D ^ k ≤ D ^ radius k := (Nat.mul_le_mul (by decide : 6 ≤ 64) + (Nat.le_self_pow (by decide : 3 ≠ 0) _)).trans (Geo.polynomial hd k) + exact_mod_cast hc.trans hh + +namespace Geo.Raw +open SphereScale (Scales budget) +variable {G} {e : E → ℕ} {thin : Place C → Prop} {selector : K → Prop} {ℓ L B m d u : ℕ} + (hr : G.Raw ℓ L B m e thin selector) (s : Scales g ℓ D T L B m) + (ha : M * r = m * B) (hb : M * t = m) (hM : M = SphereScale.chunks ℓ D) (hk : k + = allocation g ℓ) + (hD : D = 2 ^ d) (hd : 4 ≤ D) (p : Profile C e) (v : V) +local notation "H" => G.layout hD hd p L +local notation "c" => radius k +local notation "Z" => (S.backdrop.emitted p L) +local notation "N" => Fanout.exponent c ℓ + +include hr s ha hb hM hk in +open Classical in +private theorem before_routing : + push S.home (fun i => ((Z).arity i : ℝ)) v + 2 * T ≤ (c : ℝ) * (1 + G.collectorCount v) * D * T + := by + have ordinary : (S.ordinaryLoad v : ℝ) ≤ T := + (hr.ordinary_small s v).trans (div_le_self (by positivity) (one_le_pow₀ (by exact_mod_cast + s.Dpos))) + have leg := hr.cell_legs s ha hb hM v + have total := S.cell_emitted p L v + let f := (G.collectorCount v : ℝ) + have coef : 5 + 9 * (budget g : ℝ) ^ 2 + 21 * budget g * f ≤ (c : ℝ) * (1 + f) := by + simp only [hk, radius, allocation, Nat.cast_mul, Nat.cast_add, Nat.cast_pow, Nat.cast_ofNat, + Nat.cast_one] + apply sub_nonneg.mp + ring_nf + positivity + have hcoef := mul_le_mul_of_nonneg_right coef (show 0 ≤ (D : ℝ) * T by positivity) + have hscale : (T : ℝ) ≤ D * T := le_mul_of_one_le_left (by positivity) (by exact_mod_cast s.Dpos) + unfold f at hcoef + linarith only [hcoef, hscale, leg, total, ordinary] + +include hr s ha hb hM hk in +open Classical in +theorem routed_cell (hu : u * D ^ N ≤ T) : + push (S.home ∘ Print.root) (fun i => (((H).pad u).route.net.arity i : ℝ) + u) v ≤ + (N : ℝ) * (1 + G.collectorCount v) * D * T * (1 + (d : ℝ)) ^ 2 := by + have deg := (G.caps hD hd (hr.budgets s ha hb hM hk.ge d) p L).degree + have hp := (Fanout.padding_budget hd le_rfl hu).1 + have hs := (H).charge_cell hD S.home v _ (G.home_count hd v) le_rfl deg hp + refine hs.trans ?_ + have coef : (2 * ((c : ℝ) * d + 1) + 1) * c ≤ (N : ℝ) * (1 + (d : ℝ)) ^ 2 := by + simp only [Fanout.exponent, Nat.cast_mul, Nat.cast_add, Nat.cast_pow, Nat.cast_ofNat, + Nat.cast_one] + apply sub_nonneg.mp + ring_nf + positivity + calc + _ ≤ (2 * ((c : ℝ) * d + 1) + 1) * ((c : ℝ) * (1 + G.collectorCount v) * D * T) := + mul_le_mul_of_nonneg_left (hr.before_routing s ha hb hM hk p v) (by positivity) + _ = ((2 * ((c : ℝ) * d + 1) + 1) * c) * ((1 + G.collectorCount v) * D * T) := by ring + _ ≤ ((N : ℝ) * (1 + (d : ℝ)) ^ 2) * ((1 + G.collectorCount v) * D * T) := + mul_le_mul_of_nonneg_right coef (by positivity) + _ = _ := by ring + +end Geo.Raw +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +end + +/- # Local charges of a printed term, including all its relay slots -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer + +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Node Sharing) + +variable {F K N X Z : Type} [Field F] [Finite K] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} (U : Printer F K N m d h ℓ M r t q D k n u j z) + (G : (Key.share s Q).Geo P k) {a : Atlas P.Occupied P.grid.Seam m d h} (π : Palette a w q) + (old : P.V ↪ B m) (data : U.rows.obj) (status : (Children.Header m d).obj) + +namespace Physical +variable {U G π old data status} (B : U.Physical G π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "S" => Key.share s Q +local notation "H" => G.layout U.dyadic U.large p j +local notation "V" => Node (Sharing.Position S) (Sharing.radius k * n) + +open Packing +variable {σ b c : ℕ} {thin : Layout.Place s.scene.cell → Prop} {selector : Key P.Occupied s.hidden + → Prop} + +omit [Finite K] in +open scoped Classical in +theorem cell_charge (hh : G.Raw σ j b c s.scene.level thin selector) (sc : SphereScale.Scales g σ D + T j b c) + (ha : M * r = c * b) (hb : M * t = c) (hM : M = SphereScale.chunks σ D) (hk : k + = Sharing.allocation g σ) + (hu : u * D ^ (Input.terminalExponent g σ) ≤ T) (v : P.Occupied) : + push ((S).home ∘ Print.root) (B.term p).charge v ≤ + (Input.terminalExponent g σ : ℝ) * (1 + G.collectorCount v) * D * T * (1 + (n : ℝ)) ^ 2 := by + subst k + exact hh.routed_cell sc ha hb hM rfl U.dyadic U.large p v hu + +omit [Finite K] in +open scoped Classical in +theorem collectorCount_eq (v : P.Occupied) : + G.collectorCount v = Fintype.card {i : (B.term p).freeze.Fixed // (S).home (Print.root i.val) + = v} := by + let C := {i : Fin (s.scene.cell v).stations.length // G.frozen ⟨v, i⟩} + let I := {i : (B.term p).freeze.Fixed // (S).home (Print.root i.val) = v} + let f : C → I := fun i => + ⟨⟨.inl (.inl (.inl ⟨v, i.val⟩)), (G.fixed_item U.dyadic U.large p j _).mpr i.property⟩, rfl⟩ + refine Fintype.card_congr (Equiv.ofBijective f ⟨?_, ?_⟩) + · intro a b he + have e := congrArg (fun x : I => x.val.val) he + exact Subtype.ext (eq_of_heq (Sigma.mk.inj (Sum.inl.inj (Sum.inl.inj (Sum.inl.inj e)))).2) + · rintro ⟨⟨i|r, hi⟩, hv⟩ + · rcases i with ((⟨a, z⟩|s|s)|s|s) + · change a = v at hv + subst a + exact ⟨⟨z, (G.fixed_item U.dyadic U.large p j _).mp hi⟩, rfl⟩ + all_goals exact False.elim hi + · exact False.elim hi + +end Physical +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Footprint/Load.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Footprint/Load.lean new file mode 100644 index 0000000000..1500eeeea0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Footprint/Load.lean @@ -0,0 +1,795 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Logic.Relation +public import Mathlib.Data.Finset.Union +public import Mathlib.Data.Nat.Pairing +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Fintype.Prod +public import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +public import Mathlib.Data.Fintype.Sort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting + +/-! +# Connectivity of the ordinary information carried by moving stations + +Selectors are indexed by their cell, and the fresh wire created by a +crossing is indexed by the current stack length. Carrying information +to the neighboring cell extends each footprint along a seam. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +open Relation +variable {V E : Type} + +open scoped Classical in +/-- Indexes the trace set by the coordinates of `V → Finset (V ⊕ ℕ)`. -/ +abbrev TraceSet (V : Type) := V → Finset (V ⊕ ℕ) + +open scoped Classical in +/-- The two cases impose `True` and `j < n`, respectively. -/ +def available (n : ℕ) : V ⊕ ℕ → Prop + | .inl _ => True + | .inr j => j < n + +open scoped Classical in +/-- The indexed operation `EqvGen (fun a b => j ∈ u a ∧ j ∈ u b ∧ ∃ e, src e = a ∧ dst e = b)`. -/ +def path (src dst : E → V) (u : TraceSet V) (j : V ⊕ ℕ) := + EqvGen (fun a b => j ∈ u a ∧ j ∈ u b ∧ ∃ e, src e = a ∧ dst e = b) + +open scoped Classical in +/-- The data for the tracks construction, including `present`, `connected`. -/ +structure Tracks (src dst : E → V) (u : TraceSet V) (n : ℕ) : Prop where + present : ∀ j, (∃ v, j ∈ u v) ↔ available n j + connected : ∀ j v w, j ∈ u v → j ∈ u w → path src dst u j v w + +open scoped Classical in +/-- Evaluates `if z = v ∨ z = w then insert (.inr n) (u z ∪ s) else u z` at the input `z`. -/ +def carry (u : TraceSet V) (n : ℕ) (s : Finset (V ⊕ ℕ)) (v w : V) : TraceSet V := + fun z => if z = v ∨ z = w then insert (.inr n) (u z ∪ s) else u z + +variable {src dst : E → V} {u : TraceSet V} {n : ℕ} {s : Finset (V ⊕ ℕ)} {v w : V} + +open scoped Classical in +theorem carry_mono (z : V) : u z ⊆ carry u n s v w z := by + unfold carry + split_ifs + · exact fun _ h => Finset.mem_insert_of_mem (Finset.mem_union_left _ h) + · exact Finset.Subset.refl _ + +open scoped Classical in +theorem tracks_init : Tracks src dst (fun v => {Sum.inl v}) 0 := by + constructor + · rintro (v|j) + · exact ⟨fun _ => trivial, fun _ => ⟨v, by simp⟩⟩ + · simp [available] + · intro j v w hv hw + have : v = w := Sum.inl_injective ((Finset.mem_singleton.mp hv).symm.trans + (Finset.mem_singleton.mp hw)) + subst w + exact .refl _ + +open scoped Classical in +theorem Tracks.carry (h : Tracks src dst u n) (hs : s ⊆ u v) (e : E) + (adj : (src e = v ∧ dst e = w) ∨ (src e = w ∧ dst e = v)) : + Tracks src dst (carry u n s v w) (n + 1) := by + let u' := Surface.carry u n s v w + have entered (j : V ⊕ ℕ) (z : V) (hz : j ∈ u' z) : + j ∈ u z ∨ (z = v ∨ z = w) ∧ (j = .inr n ∨ j ∈ s) := by + unfold u' Surface.carry at hz + split_ifs at hz with ht + · simp only [Finset.mem_insert, Finset.mem_union] at hz + tauto + · exact Or.inl hz + have both (j : V ⊕ ℕ) (hj : j = .inr n ∨ j ∈ s) : j ∈ u' v ∧ j ∈ u' w := by + simp only [u', Surface.carry, true_or, or_true, ↓reduceIte, Finset.mem_insert, Finset.mem_union] + tauto + have along (j : V ⊕ ℕ) (hj : j = .inr n ∨ j ∈ s) (z : V) (hz : z = v ∨ z = w) : + path src dst u' j z v := by + rcases hz with rfl|rfl + · exact .refl _ + · obtain ⟨hv, hw⟩ := both j hj + rcases adj with f|f + · exact .symm _ _ (.rel _ _ ⟨hv, hw, e, f⟩) + · exact .rel _ _ ⟨hw, hv, e, f⟩ + have earlier (j : V ⊕ ℕ) (x y : V) (hx : j ∈ u x) (hy : j ∈ u y) : + path src dst u' j x y := + EqvGen.mono (fun a b h => ⟨carry_mono _ h.1, carry_mono _ h.2.1, h.2.2⟩) _ _ + (h.connected j x y hx hy) + have fresh (z : V) : Sum.inr n ∉ u z := fun hj => + Nat.lt_irrefl n ((h.present _).mp ⟨z, hj⟩) + constructor + · intro j + have hc : available (n + 1) j ↔ available n j ∨ j = .inr n := by + cases j <;> simp [available]; omega + rw [hc, ← h.present] + constructor + · rintro ⟨z, hz⟩ + rcases entered j z hz with hh|⟨_, hh|hh⟩ + · exact .inl ⟨z, hh⟩ + · exact .inr hh + · exact .inl ⟨v, hs hh⟩ + · rintro (⟨z, hz⟩|hj) + · exact ⟨z, carry_mono z hz⟩ + · exact ⟨v, (both _ (.inl hj)).1⟩ + · intro j x y hx hy + by_cases hj : j = .inr n ∨ j ∈ s + · have toSource (z : V) (hz : j ∈ u' z) : path src dst u' j z v := by + rcases entered j z hz with hh|⟨hh, _⟩ + · rcases hj with rfl|hj + · exact (fresh z hh).elim + · exact earlier _ _ _ hh (hs hj) + · exact along _ hj _ hh + exact .trans _ _ _ (toSource x hx) (.symm _ _ (toSource y hy)) + · exact earlier _ _ _ ((entered _ _ hx).resolve_right (fun h => hj h.2)) + ((entered _ _ hy).resolve_right (fun h => hj h.2)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Cells of a network and their nonempty oriented seams -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +/-- The data for the grid construction, including `src`, `dst`, `cell`, `stationRank`, +`cellRank`. -/ +structure Grid (V E C : Type) where + /-- Assigns the source of each connection. -/ + src : E → V + /-- Assigns the destination of each connection. -/ + dst : E → V + /-- The `Grid` component of type `V → C`. -/ + cell : V → C + /-- The `Grid` component of type `V → ℕ`. -/ + stationRank : V → ℕ := fun _ => 0 + /-- The `Grid` component of type `C → ℕ`. -/ + cellRank : C → ℕ := fun _ => 0 + /-- The `Grid` component of type `E → ℕ`. -/ + packetRank : E → ℕ := fun _ => 0 + +namespace Grid +open Finset + +variable {V E C : Type} (g : Grid V E C) + +open scoped Classical in +/-- The subtype of `p : C × C` satisfying `p.1 ≠ p.2 ∧ ∃ e, g.cell (g.src e) = p.1 ∧ g.cell +(g.dst e) = p.2`. -/ +abbrev Seam := {p : C × C // p.1 ≠ p.2 ∧ ∃ e, g.cell (g.src e) = p.1 ∧ g.cell (g.dst e) = p.2} + +open scoped Classical in +/-- Computes the seam rank by the application `Nat.pair (g.cellRank v.val.1) (g.cellRank +v.val.2)`. -/ +def seamRank (v : g.Seam) := Nat.pair (g.cellRank v.val.1) (g.cellRank v.val.2) + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun v => g.cell v = c`. -/ +def stations [Fintype V] (c : C) := univ.filter fun v => g.cell v = c + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun s : g.Seam => s.val.1 = c ∨ s.val.2 = +c`. -/ +def ports [Fintype C] (c : C) := univ.filter fun s : g.Seam => s.val.1 = c ∨ s.val.2 = c + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun e => g.src e = v ∨ g.dst e = v`. -/ +def uses [Fintype E] (v : V) := univ.filter fun e => g.src e = v ∨ g.dst e = v + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun e => g.cell (g.src e) = s.val.1 ∧ g.cell +(g.dst e) = s.val.2`. -/ +def carries [Fintype E] (s : g.Seam) := + univ.filter fun e => g.cell (g.src e) = s.val.1 ∧ g.cell (g.dst e) = s.val.2 + +end Grid +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- # Counting port incidences in a grid of stations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +open Finset + +variable {V E C : Type} [Fintype C] (g : Grid V E C) + +open scoped Classical in +/-- Each crossing wire along a port charges its unique endpoint in this cell. -/ +theorem carries_le_uses [Fintype V] [Fintype E] (c : C) : + ∑ s ∈ g.ports c, (g.carries s).card ≤ ∑ v ∈ g.stations c, (g.uses v).card := by + rw [← card_sigma, ← card_sigma] + let charge (p : Σ _ : g.Seam, E) : Σ _ : V, E := + ⟨if p.1.val.1 = c then g.src p.2 else g.dst p.2, p.2⟩ + apply card_le_card_of_injOn charge + · rintro ⟨s, e⟩ he + obtain ⟨hs, ha, hb⟩ : (s.val.1 = c ∨ s.val.2 = c) ∧ + g.cell (g.src e) = s.val.1 ∧ g.cell (g.dst e) = s.val.2 := by + simpa only [mem_coe, mem_sigma, ports, carries, mem_filter_univ] using he + by_cases hd : s.val.1 = c + · simp [charge, hd, stations, uses, ha] + · simp [charge, hd, stations, uses, hb, hs.resolve_left hd] + · rintro ⟨s, e⟩ he ⟨t, a⟩ ha eq + have ee : e = a := congrArg (fun p => p.2) eq + subst a + have hs := (mem_filter.mp (mem_sigma.mp he).2).2 + have ht := (mem_filter.mp (mem_sigma.mp ha).2).2 + have st : s = t := Subtype.ext (Prod.ext (hs.1.symm.trans ht.1) (hs.2.symm.trans ht.2)) + cases st + rfl + +open scoped Classical in +/-- Each neighboring cell contributes at most two oriented ports. -/ +theorem ports_bound (N : C → Finset C) (sym : ∀ c d, d ∈ N c → c ∈ N d) + (adj : ∀ e, g.cell (g.src e) ≠ g.cell (g.dst e) → g.cell (g.dst e) ∈ N (g.cell (g.src e))) + (c : C) : (g.ports c).card ≤ 2 * (N c).card := by + calc + _ ≤ (({c} ×ˢ N c) ∪ (N c ×ˢ {c})).card := by + apply card_le_card_of_injOn Subtype.val _ Subtype.val_injective.injOn + intro s hs + obtain ⟨hne, e, ha, hb⟩ := s.property + have hn : s.val.2 ∈ N s.val.1 := by rw [← ha, ← hb] at hne ⊢; exact adj e hne + rcases (mem_filter.mp hs).2 with rfl | rfl + · exact mem_union_left _ (mem_product.mpr ⟨mem_singleton_self _, hn⟩) + · exact mem_union_right _ (mem_product.mpr ⟨sym _ _ hn, mem_singleton_self _⟩) + _ ≤ _ := by simpa [Nat.two_mul] using card_union_le ({c} ×ˢ N c) (N c ×ˢ {c}) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +end + +/- # Numbering a finite set by a local key -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid + +open Finset +variable {A B : Type} + +open scoped Classical in +/-- Use increasing key order where the keys distinguish the elements. +Unordered inputs still admit the same contraction proofs. -/ +def number (f : A → ℕ) (s : Finset A) : Fin s.card ≃ ↥s := + if h : Function.Injective (fun v : s => f v.val) then + letI := LinearOrder.lift' (fun v : s => f v.val) h + (Fintype.orderIsoFinOfCardEq s (by simp)).toEquiv + else Fintype.equivOfCardEq (by simp) + +open scoped Classical in +theorem number_lt {f : A → ℕ} {s : Finset A} (hf : Set.InjOn f s) (i j : Fin s.card) : + f (number f s i).val < f (number f s j).val ↔ i < j := by + have h : Function.Injective (fun v : s => f v.val) := + fun i j e => Subtype.ext (hf i.property j.property e) + unfold number + rw [dite_eq_left h] + let _ := LinearOrder.lift' (fun v : s => f v.val) h + exact (Fintype.orderIsoFinOfCardEq s (by simp)).lt_iff_lt + +open scoped Classical in +/-- Absolute element names disappear after numbering. The ordered +list of keys depends only on the unordered set of keys. -/ +theorem number_keys {f : A → ℕ} {s : Finset A} (hf : Set.InjOn f s) : + List.ofFn (fun i => f (number f s i).val) = (s.image f).sort (· ≤ ·) := by + apply List.Perm.eq_of_pairwise (le := (· ≤ ·)) (fun _ _ _ _ => le_antisymm) + · rw [List.pairwise_ofFn] + intro i j h + exact ((number_lt hf i j).mpr h).le + · exact pairwise_sort _ _ + · apply (List.perm_ext_iff_of_nodup ?_ (sort_nodup _ _)).mpr + · intro k + simp only [List.mem_ofFn, mem_sort, mem_image] + constructor + · rintro ⟨i, rfl⟩; exact ⟨_, (number f s i).property, rfl⟩ + · rintro ⟨x, hx, rfl⟩; exact ⟨(number f s).symm ⟨x, hx⟩, by simp⟩ + exact List.nodup_ofFn.mpr fun i j h => (number f s).injective + (Subtype.ext (hf (number f s i).property (number f s j).property h)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +end + +section +/- # Transporting stationwise properties through a scene update -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Function +variable {F T V E X : Type} [Field F] {r t P : ℕ} {s : Stage F r t T V E X} + +omit [Field F] in +open scoped Classical in +theorem all_put {v : V} {c : s.Ct} {Q : V → s.St → Prop} + (old : ∀ z, ∀ x ∈ (s.scene.cell z).stations, Q z x) + (new : ∀ x ∈ c.stations, Q v x) : + ∀ z, ∀ x ∈ ((s.put v c).scene.cell z).stations, Q z x := by + intro z + change ∀ x ∈ (update s.scene.cell v c z).stations, Q z x + by_cases h : z = v + · subst z; rw [update_self]; exact new + · rw [update_of_ne h]; exact old z + +open scoped Classical in +theorem all_advance {u : s.St} {a : Passage P u} {v w : V} {j : E} {L R : s.Sock} + {S : Lower F r} {i : a.Branch} + (hv : s.scene.cell v = (L.plug j a.z).insert u) (hw : s.scene.cell w = R.plug j a.y) + {Q : V → Station F r t (Tag V T) (Stack X t s.hidden × Level t u.b) → Prop} + (old : ∀ z, ∀ x ∈ (s.scene.cell z).stations, Q z (x.pull Prod.fst id)) + (leave : Q v (a.leaves (Tag.leave s.hidden.length) i)) + (take : Q w (a.arrives (u.label.take s.hidden.length) S i)) : + ∀ z, ∀ x ∈ ((s.advance a v w j L R S i).scene.cell z).stations, Q z x := by + intro z + change ∀ x ∈ (update (update (fun z => (s.scene.cell z).pull Prod.fst id) v + (a.left L j (Tag.leave s.hidden.length) i)) w + (a.right R j (u.label.take s.hidden.length) S i) z).stations, Q z x + by_cases h : z = w + · subst z + rw [update_self] + simp only [Passage.right, Cell.insert, Cell.pull, List.forall_mem_cons, List.forall_mem_map] + exact ⟨take, fun x hx => old w x (by rwa [hw])⟩ + rw [update_of_ne h] + by_cases h' : z = v + · subst z + rw [update_self] + simp only [Passage.left, Cell.insert, Cell.pull, List.forall_mem_cons, List.forall_mem_map] + exact ⟨leave, fun x hx => old v x (by rw [hv]; exact List.mem_cons_of_mem _ hx)⟩ + simp only [update_of_ne h', Cell.pull, List.forall_mem_map] + exact old z + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- # Information that a station may read -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Finset +variable {F T V E X : Type} {r t : ℕ} + +open scoped Classical in +/-- In the case `[], x`, this construction gives `x`. -/ +def base : (ns : List ℕ) → Stack X t ns → X + | [], x => x + | _ :: ns, x => base ns x.1 + +open scoped Classical in +/-- Agreement on one ordinary key. Natural-number keys are introduced +sequentially and their values are homogeneous states. -/ +def Observe (keys : V → X → X → Prop) : + (ns : List ℕ) → V ⊕ ℕ → Stack X t ns → Stack X t ns → Prop + | [], .inl i, x, y => keys i x y + | [], .inr _, _, _ => True + | _ :: ns, j, x, y => Observe keys ns j x.1 y.1 ∧ (j = .inr ns.length → x.2 = y.2) + +open scoped Classical in +/-- The data for the reads construction, including `named`, `within`, `respects`. -/ +structure Reads (keys : V → X → X → Prop) (ext : T → X → X → Prop) + (l : List ℕ) (seen : Finset (V ⊕ ℕ)) (a : Station F r t (Tag V T) (Stack X t l)) : Prop where + named : a.label.name ≠ none → a.label.role = .collector + within : a.label.reads ⊆ seen + respects : ∀ x y, (∀ j ∈ a.label.reads, Observe keys l j x y) → + (∀ i, a.label.name = some i → ext i (base l x) (base l y)) → a.table x = a.table y + +open scoped Classical in +/-- The condition `∀ v, ∀ a ∈ (s.scene.cell v).stations, Reads keys ext s.hidden (s.footprint v) +a` on the specified data. -/ +def Controls (s : Stage F r t T V E X) (keys : V → X → X → Prop) (ext : T → X → X → Prop) : Prop := + ∀ v, ∀ a ∈ (s.scene.cell v).stations, Reads keys ext s.hidden (s.footprint v) a + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- +# Propagation of ordinary information + +Merging takes the union of the reads. A crossing transfers those reads +and creates one independent key for the mover's former private state. +The near-side residue needs only that new key. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Finset +variable {F T V E X : Type} [Field F] {r t P g H U : ℕ} + {s s' : Stage F r t T V E X} {keys : V → X → X → Prop} {ext : T → X → X → Prop} + {l : List ℕ} {u v : Station F r t (Tag V T) (Stack X t l)} {seen : Finset (V ⊕ ℕ)} + +omit [Field F] in +open scoped Classical in +theorem Reads.unnamed (h : Reads keys ext l seen u) (h' : u.label.role ≠ .collector) : + u.label.name = none := by + by_contra hn + exact h' (h.named hn) + +omit [Field F] in +open scoped Classical in +theorem Reads.join_name (h : Reads keys ext l seen u) (k : Reads keys ext l seen v) + (hv : v.label.role ≠ .collector) : (u.label.join v.label).name = u.label.name := by + unfold Tag.join + split_ifs with hu + · rfl + · exact (k.unnamed hv).trans (h.unnamed hu).symm + +open scoped Classical in +theorem Reads.merge (h : Reads keys ext l seen u) (k : Reads keys ext l seen v) + (hv : v.label.role ≠ .collector) (q : ℤ × ℤ) : + Reads keys ext l seen (mergeAt u v (u.label.join v.label) q) := by + have join := h.join_name k hv + have union : (u.label.join v.label).reads = u.label.reads ∪ v.label.reads := by + unfold Tag.join; split_ifs <;> rfl + refine ⟨?_, ?_, ?_⟩ + · change (u.label.join v.label).name ≠ none → (u.label.join v.label).role = .collector + rw [join] + intro hn + simp [Tag.join, h.named hn] + · change (u.label.join v.label).reads ⊆ seen + rw [union] + exact union_subset h.within k.within + · intro x y hr he + change ∀ j ∈ (u.label.join v.label).reads, _ at hr + rw [union] at hr + change ∀ i, (u.label.join v.label).name = some i → _ at he + rw [join] at he + have h₁ := h.respects x y (fun j hj => hr j (mem_union_left _ hj)) he + have h₂ := k.respects x y (fun j hj => hr j (mem_union_right _ hj)) + (by simp [k.unnamed hv]) + unfold mergeAt Surface.merge + simp only [jointWeight, h₁, h₂] + +open scoped Classical in +theorem Step.controls (h : Step P g H U s s') (hc : s.Controls keys ext) : + s'.Controls keys ext := by + cases h with + | perm v ls hv => exact all_put hc (fun a ha => hc v a (hv.mem_iff.mpr ha)) + | expire v c u hv ha ready => + refine all_put (Q := fun z => Reads keys ext s.hidden (s.footprint z)) (c + := c.insert {u with label := {u.label with role := .collector}}) hc ?_ + have h := hc v + rw [hv] at h + simp only [Cell.insert, List.forall_mem_cons] at h ⊢ + exact ⟨⟨fun _ => rfl, h.1.within, h.1.respects⟩, h.2⟩ + | merge v c a b n hv ha ready j q hq bound => + refine all_put (Q := fun z => Reads keys ext s.hidden (s.footprint z)) hc ?_ + have h := hc v + rw [hv] at h + simp only [Cell.insert, List.forall_mem_cons] at h ⊢ + exact ⟨h.1.merge h.2.1 (by simp [ha]) q, h.2.2⟩ + | cross v w j L R u a S i n hv hw ne he hh ha hn ready => + let f := carry s.footprint s.hidden.length u.label.reads v w + have hu := hc v u (by simp [hv, Cell.insert]) + have hn' := hu.unnamed (by simp [ha]) + refine all_advance hv hw (Q := fun z => Reads keys ext (u.b :: s.hidden) (f z)) ?_ ?_ ?_ + · intro z b hb + have h := hc z b hb + refine ⟨h.named, h.within.trans (carry_mono z), ?_⟩ + intro x y hr he + exact h.respects x.1 y.1 (fun j hj => (hr j hj).1) he + · refine ⟨fun h => (h rfl).elim, ?_, ?_⟩ + · change {Sum.inr s.hidden.length} ⊆ f v + simp [f, carry] + · intro x y hr _ + have e := (hr (.inr s.hidden.length) (mem_singleton_self _)).2 rfl + unfold Passage.leaves residue + simp only [e] + · refine ⟨fun h => (h hn').elim, ?_, ?_⟩ + · change insert (.inr s.hidden.length) u.label.reads ⊆ f w + simp [f, carry] + · intro x y hr he + have e := (hr (.inr s.hidden.length) (mem_insert_self _ _)).2 rfl + have e' := hu.respects x.1 y.1 (fun j hj => (hr j (mem_insert_of_mem hj)).1) he + unfold Passage.arrives transfer + simp only [e, e'] + +open scoped Classical in +theorem Step.tracks {src dst : E → V} (h : Step P g H U s s') + (hs : s.Layout src dst g) (hc : s.Controls keys ext) + (hp : Tracks src dst s.footprint s.hidden.length) : + Tracks src dst s'.footprint s'.hidden.length := by + cases h with + | perm => exact hp + | expire => exact hp + | merge => exact hp + | cross v w j L R u a S i n hv hw ne he hh ha hn ready => + have hu := hc v u (by simp [hv, Cell.insert]) + apply hp.carry hu.within j + have hl := (hs.incident v j).mp (by simp [ports, hv, Cell.insert, Socket.plug]) + have hr := (hs.incident w j).mp (by simp [ports, hw, Socket.plug]) + grind + +open scoped Classical in +theorem Reach.controls (h : s.Reach P g H U s') (hc : s.Controls keys ext) : + s'.Controls keys ext := by + induction h with + | refl => exact hc + | tail _ step ih => exact step.controls ih + +open scoped Classical in +theorem Reach.tracks {src dst : E → V} (h : s.Reach P g H U s') (hs : s.Layout src dst g) + (hc : s.Controls keys ext) (hp : Tracks src dst s.footprint s.hidden.length) : + Tracks src dst s'.footprint s'.hidden.length := by + suffices s'.Layout src dst g ∧ Tracks src dst s'.footprint s'.hidden.length from this.2 + induction h with + | refl => exact ⟨hs, hp⟩ + | tail h step ih => exact ⟨step.layout ih.1, step.tracks ih.1 (Reach.controls h hc) ih.2⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- +# Bounding the number of ordinary keys at a cell + +A fresh private state becomes local to the departure cell. The only +non-collector allowed to carry keys from elsewhere is the current +mover. Its number of nonlocal keys grows linearly in its crossing +count, independently of the number of untouched auxiliary marks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Finset Function +variable {F T V E X : Type} {r t P g H U L : ℕ} + {s s' : Stage F r t T V E X} + +open scoped Classical in +/-- The sum of `s.hits e` indexed by `e ∈ s.edges v`. -/ +def visits (s : Stage F r t T V E X) (v : V) := ∑ e ∈ s.edges v, s.hits e + +open scoped Classical in +/-- The quantity computed by `(U + 1) * (L + 2) + 1`. -/ +def loadLimit (U L : ℕ) := (U + 1) * (L + 2) + 1 + +open scoped Classical in +/-- The quantity computed by `tag.role ≠ .collector → (tag.reads \ home).card ≤ tag.role.clock * +(L + 2)`. -/ +def Watch (L : ℕ) (home : Finset (V ⊕ ℕ)) (tag : Tag V T) := + tag.role ≠ .collector → (tag.reads \ home).card ≤ tag.role.clock * (L + 2) + +open scoped Classical in +/-- The load of type `Prop` for the given inputs. -/ +def Load (s : Stage F r t T V E X) (U L : ℕ) : Prop := + ∃ home : TraceSet V, + (∀ v, (home v).card ≤ s.visits v + 1) ∧ + (∀ v, (s.footprint v).card ≤ s.visits v * loadLimit U L + 1) ∧ + ∀ v, ∀ a ∈ (s.scene.cell v).stations, Watch L (home v) a.label + +variable {home home' : Finset (V ⊕ ℕ)} {a b : Tag V T} + +open scoped Classical in +private theorem Watch.mono (h : Watch L home a) (hh : home ⊆ home') : Watch L home' a := + fun hn => (card_le_card (sdiff_subset_sdiff (Subset.refl _) hh)).trans (h hn) + +open scoped Classical in +private theorem Watch.merge (ha : Watch L home a) (hb : Watch L home b) + (h : a.role.clock = 0) : Watch L home (a.join b) := by + by_cases hn : a.role = .collector + · simp [Watch, Tag.join, hn] + have he : a.reads \ home = ∅ := card_eq_zero.mp (by simpa [h] using ha hn) + have hs : (a.reads ∪ b.reads) \ home = b.reads \ home := by + ext x + have h := sdiff_eq_empty_iff_subset.mp he + simp only [mem_sdiff, mem_union] + grind + simpa only [Watch, Tag.join, hn, ↓reduceIte, hs] using hb + +open scoped Classical in +private theorem Watch.size (h : Watch L home a) (hn : a.role ≠ .collector) + (hh : home.card ≤ L + 1) : a.reads.card + 1 ≤ (a.role.clock + 1) * (L + 2) := by + have he : a.reads ⊆ (a.reads \ home) ∪ home := by intro x hx; simp [hx] + have := (card_le_card he).trans (card_union_le _ _) + have := h hn + rw [add_mul, one_mul] + omega + +open scoped Classical in +theorem init_load {keys : V → X → X → Prop} {ext : T → X → X → Prop} + (hc : s.Controls keys ext) (hi : ∀ v, s.footprint v = {Sum.inl v}) : s.Load U L := by + refine ⟨s.footprint, fun v => ?_, fun v => ?_, fun v a ha _ => ?_⟩ + · simp [hi] + · simp [hi] + · simp [sdiff_eq_empty_iff_subset.mpr (hc v a ha).within] + +variable [Field F] + +open scoped Classical in +theorem Step.load (h : Step P g H U s s') (hc : s.Load U L) + (hvis : ∀ v, s.visits v ≤ L) : s'.Load U L := by + obtain ⟨pool, hp, hseen, hw⟩ := hc + have visits' (v) : s'.visits v = ∑ e ∈ s.edges v, s'.hits e := by rw [visits, h.edges_eq] + cases h with + | perm v ls hs => + refine ⟨pool, fun z => ?_, fun z => ?_, all_put hw (fun a ha => hw v a (hs.mem_iff.mpr ha))⟩ + · rw [visits']; exact hp z + · rw [visits']; exact hseen z + | expire v c u hv => + refine ⟨pool, fun z => ?_, fun z => ?_, ?_⟩ + · rw [visits']; exact hp z + · rw [visits']; exact hseen z + · refine all_put (Q := fun z a => Watch L (pool z) a.label) + (c := c.insert {u with label := {u.label with role := .collector}}) hw ?_ + have h := hw v + rw [hv] at h + simp only [Cell.insert, List.forall_mem_cons] at h ⊢ + exact ⟨fun hn => (hn rfl).elim, h.2⟩ + | merge v c a b n hv ha ready j q hq bound => + refine ⟨pool, fun z => ?_, fun z => ?_, ?_⟩ + · rw [visits']; exact hp z + · rw [visits']; exact hseen z + · refine all_put (Q := fun z a => Watch L (pool z) a.label) hw ?_ + have h := hw v + rw [hv] at h + simp only [Cell.insert, List.forall_mem_cons] at h ⊢ + exact ⟨h.1.merge h.2.1 (ready.1 a (by simp)), h.2.2⟩ + | cross v w j A B u a S i n hv hw' ne he hh ha hn ready => + let s₁ := s.advance a v w j A B S i + let next := update pool v (insert (.inr s.hidden.length) (pool v)) + have inc (z : V) : s₁.visits z = s.visits z + if j ∈ s.edges z then 1 else 0 := by + rw [visits'] + have e (k) : s₁.hits k = s.hits k + if k = j then 1 else 0 := by + by_cases h : k = j <;> simp [s₁, advance, h] + change (∑ k ∈ s.edges z, s₁.hits k) = _ + simp only [e, sum_add_distrib, sum_ite_eq', visits] + have near (z : V) (hz : z = v ∨ z = w) : s₁.visits z = s.visits z + 1 := by + rw [inc, ite_eq_left] + rcases hz with rfl|rfl + · simp [edges, hv, Socket.plug, Cell.insert] + · simp [edges, hw', Socket.plug] + have mono (z : V) : s.visits z ≤ s₁.visits z := by rw [inc]; omega + have hu := (hw v u (by simp [hv, Cell.insert])).size (by simp [ha]) + ((hp v).trans (Nat.add_le_add_right (hvis v) 1)) + have hu' : u.label.reads.card + 1 ≤ loadLimit U L := by + rw [ha, Role.clock] at hu + unfold loadLimit + exact hu.trans ((Nat.mul_le_mul_right _ (Nat.succ_le_succ hn.le)).trans (Nat.le_succ _)) + change s₁.Load U L + refine ⟨next, ?_, ?_, ?_⟩ + · intro z + by_cases hz : z = v + · subst z; dsimp only [next]; rw [update_self, near v (.inl rfl)] + exact (card_insert_le _ _).trans (Nat.add_le_add_right (hp v) 1) + · dsimp only [next]; rw [update_of_ne hz] + exact (hp z).trans (Nat.add_le_add_right (mono z) 1) + · intro z + change (carry _ _ _ v w z).card ≤ _ + unfold carry + split_ifs with hz + · rw [near z hz, add_mul, one_mul] + have h₀ := card_insert_le (Sum.inr s.hidden.length) (s.footprint z ∪ u.label.reads) + have h₁ := card_union_le (s.footprint z) u.label.reads + have h₂ := hseen z + omega + · exact (hseen z).trans (by gcongr; exact mono z) + · refine all_advance hv hw' (Q := fun z x => Watch L (next z) x.label) ?_ ?_ ?_ + · intro z x hx + refine (hw z x hx).mono ?_ + by_cases h : z = v <;> simp [next, h] + · change Watch L (next v) (Tag.leave _) + have he : {Sum.inr s.hidden.length} ⊆ next v := by simp [next] + simp [Watch, Tag.leave, sdiff_eq_empty_iff_subset.mpr he] + · intro _ + change ((insert (Sum.inr s.hidden.length) u.label.reads) \ next w).card ≤ _ + exact ((card_le_card sdiff_subset).trans (card_insert_le _ _)).trans hu + +open scoped Classical in +theorem Reach.footprint_bound (h : s.Reach P g H U s') (hc : s.Load U L) + (hvis : ∀ a, s.Reach P g H U a → ∀ v, a.visits v ≤ L) (v : V) : + (s'.footprint v).card ≤ L * loadLimit U L + 1 := by + have hs : s'.Load U L := by + induction h with + | refl => exact hc + | tail h step ih => exact step.load ih (hvis _ h) + exact (hs.choose_spec.2.1 v).trans (by gcongr; exact hvis _ h _) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- +# Station names stay in their original cells + +Only collectors carry names. Moving a station can therefore neither +displace a name nor duplicate one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Function + +variable {F T V E X Y : Type} {r t P g H U : ℕ} + +open scoped Classical in +/-- The indexed operation `c.stations.filterMap (fun a => a.label.name)`. -/ +def labels (c : Cell F r t (Tag V T) E X) := + c.stations.filterMap (fun a => a.label.name) + +open scoped Classical in +private theorem labels_insert (c : Cell F r t (Tag V T) E X) (a : Station F r t (Tag V T) X) : + labels (c.insert a) = a.label.name.toList ++ labels c := by + unfold labels Cell.insert + simp only [List.filterMap_cons] + cases a.label.name <;> rfl + +open scoped Classical in +private theorem labels_pull (c : Cell F r t (Tag V T) E X) (π : Y → X) : + labels (c.pull π id) = labels c := by + simp only [labels, Cell.pull, List.filterMap_map] + rfl + +open scoped Classical in +/-- Computes the names by the application `labels (s.scene.cell v)`. -/ +def names (s : Stage F r t T V E X) (v : V) := labels (s.scene.cell v) + +open scoped Classical in +theorem mem_names (s : Stage F r t T V E X) (v : V) (i : T) : + i ∈ s.names v ↔ ∃ a ∈ (s.scene.cell v).stations, a.label.name = some i := + List.mem_filterMap + +variable {s s' : Stage F r t T V E X} {keys : V → X → X → Prop} {ext : T → X → X → Prop} + +open scoped Classical in +private theorem names_put {v : V} {c : s.Ct} (z : V) + (h : (labels c).Perm (s.names v)) : ((s.put v c).names z).Perm (s.names z) := by + change (labels (update s.scene.cell v c z)).Perm _ + by_cases e : z = v + · subst z; rwa [update_self] + · rw [update_of_ne e]; exact .refl _ + +variable [Field F] + +open scoped Classical in +theorem Step.names (h : s.Step P g H U s') (hc : s.Controls keys ext) (z : V) : + (s'.names z).Perm (s.names z) := by + cases h with + | perm v ls hl => + apply names_put + exact hl.symm.filterMap _ + | expire v c u hv ha ready => + change ((s.put v _).names z).Perm _ + apply names_put + rw [Stage.names, hv, labels_insert, labels_insert] + | merge v c a b n hv ha ready j q hq bound => + have h := hc v + rw [hv] at h + simp only [Cell.insert, List.forall_mem_cons] at h + have hn := h.2.1.unnamed (by simp [ha]) + have hj := h.1.join_name h.2.1 (by simp [ha]) + apply names_put + rw [Stage.names, hv, labels_insert, labels_insert, labels_insert] + change ((a.label.join b.label).name.toList ++ _).Perm _ + rw [hj, hn] + rfl + | cross v w j L R u a S i n hv hw ne he hh ha hn ready => + have hu := hc v u (by simp [hv, Cell.insert]) + have hn := hu.unnamed (by simp [ha]) + change (labels (update (update (fun z => (s.scene.cell z).pull Prod.fst id) v + (a.left L j (Tag.leave s.hidden.length) i)) w + (a.right R j (u.label.take s.hidden.length) S i) z)).Perm (labels (s.scene.cell z)) + by_cases h : z = w + · subst z + rw [update_self, hw, Passage.right, labels_insert, labels_pull] + change (u.label.name.toList ++ _).Perm _ + rw [hn] + rfl + rw [update_of_ne h] + by_cases h' : z = v + · subst z + rw [update_self, hv, Passage.left, labels_insert, labels_insert, labels_pull, hn] + rfl + · rw [update_of_ne h', labels_pull] + +open scoped Classical in +theorem Reach.names (h : s.Reach P g H U s') (hc : s.Controls keys ext) (z : V) : + (s'.names z).Perm (s.names z) := by + induction h with + | refl => exact .refl _ + | tail h step ih => exact (step.names (Reach.controls h hc) z).trans ih + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/FusedTerms.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/FusedTerms.lean new file mode 100644 index 0000000000..1c5c942543 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/FusedTerms.lean @@ -0,0 +1,108 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.TableMotion + +/-! +# Fusion terms of definite energy + +The candidate count depends polynomially on the truncation order. +Each candidate separates across a chosen block through a single +intermediate energy space. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Finset + +variable {A F R : Type*} [Fintype A] [Field F] [CommRing R] [Algebra F R] {r n : ℕ} + +open scoped Classical in +/-- The quantity computed by `Fin n → Fin (N + 1)`. -/ +abbrev Pattern (n N : ℕ) := Fin n → Fin (N + 1) + +open scoped Classical in +private def regroup (r n N : ℕ) : + (Σ t : Pattern n N, States r (fun i => (t i).val)) ≃ (Fin n → LevelLE r N) := by + let f (z : Σ t : Pattern n N, States r (fun i => (t i).val)) (j : Fin n) : LevelLE r N := + ⟨(z.2 j).val, (z.2 j).2.le.trans (Nat.le_of_lt_succ (z.1 j).isLt)⟩ + refine Equiv.ofBijective f ⟨?_, ?_⟩ + · rintro ⟨t, x⟩ ⟨s, y⟩ h + have he (j) : (x j).val = (y j).val := congrArg Subtype.val (congrFun h j) + have hts : t = s := by + funext j + apply Fin.ext + exact (x j).2.symm.trans ((congrArg (fun w : Wedge r => energy w.val) (he j)).trans (y j).2) + subst s + have : x = y := funext fun j => Subtype.ext (he j) + rw [this] + · intro y + let t (j : Fin n) : Fin (N + 1) := ⟨energy (y j).val.val, Nat.lt_succ_of_le (y j).2⟩ + exact ⟨⟨t, fun j => ⟨(y j).val, rfl⟩⟩, rfl⟩ + +open scoped Classical in +/-- Transforms the indexed data by `wick fieldKernel (List.ofFn (fun j => (b j).val.val.map (c +j, ·))).flatten`. -/ +def outerForm (c : Fin n → F) {g : Fin n → ℕ} (b : States r g) : F := + wick fieldKernel (List.ofFn (fun j => (b j).val.val.map (c j, ·))).flatten + +open scoped Classical in +/-- The quantity computed by `∑ b : States r g, (∏ j, blockCoeff (blockInputs f o x j) (b +j).val) * outerForm c b`. -/ +def fusedTerm {e : A → ℕ} (c : Fin n → F) (f : A → Fin n) (o : A → F) (g : Fin n → ℕ) + (x : States r e) : F := + ∑ b : States r g, (∏ j, blockCoeff (blockInputs f o x j) (b j).val) * outerForm c b + +open scoped Classical in +theorem fusion_terms {e : A → ℕ} (c : Fin n → F) (hc : Function.Injective c) + (f : A → Fin n) (o : A → F) (u : R) (N : ℕ) (hu : u ^ N = 0) : + ∃ s : F, ∀ x : States r e, wick (clusterKernel u N (c ∘ f) o) (inputs x) = + ∑ t : Pattern n N, u ^ (∑ j, (t j).val) * + algebraMap F R (s * fusedTerm c f o (fun j => (t j).val) x) := by + obtain ⟨s, hs⟩ := grouped_fusion (r := r) (e := e) c hc f o u N hu + refine ⟨s, fun x => ?_⟩ + rw [hs, ← (regroup r n N).sum_comp, Fintype.sum_sigma, mul_sum] + refine sum_congr rfl fun t _ => ?_ + simp only [fusedTerm, mul_sum, map_sum, map_mul] + refine sum_congr rfl fun b _ => ?_ + have hh (j : Fin n) : ((regroup r n N ⟨t, b⟩) j).val = (b j).val := rfl + simp only [hh, outerForm, show ∀ j, energy (b j).val.val = (t j).val from fun j => (b j).2] + ring + +open scoped Classical in +theorem fused_separates {e : A → ℕ} (c : Fin n → F) + (f : A → Fin n) (o : A → F) (g : Fin n → ℕ) (j : Fin n) : + ∃ L R : Level r (g j) → States r e → F, + (∀ x, fusedTerm c f o g x = ∑ t, L t x * R t x) ∧ + (∀ t x y, (∀ i, f i = j → x i = y i) → L t x = L t y) ∧ + (∀ t x y, (∀ i, f i ≠ j → x i = y i) → R t x = R t y) := by + let fac (i : Fin n) (w : Level r (g i)) (x : States r e) := blockCoeff (blockInputs f o x i) w.val + let rest (b : States r g) (x : States r e) := + (∏ i ∈ univ.erase j, fac i (b i) x) * outerForm c b + refine ⟨fac j, fun t x => ∑ b with b j = t, rest b x, ?_, ?_, ?_⟩ + · intro x + rw [fusedTerm, ← sum_fiberwise univ (fun b : States r g => b j)] + refine sum_congr rfl fun t _ => ?_ + rw [mul_sum] + refine sum_congr rfl fun b hb => ?_ + rw [← (mem_filter.mp hb).2, ← mul_prod_erase _ _ (mem_univ j), mul_assoc] + · intro t x y h + unfold fac + rw [blockInputs_eq f o x y j h] + · intro t x y h + refine sum_congr rfl fun b _ => ?_ + unfold rest + congr 1 + refine prod_congr rfl fun i hi => ?_ + unfold fac + rw [blockInputs_eq f o x y i (fun a ha => h a (ha ▸ (mem_erase.mp hi).1))] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/General/Ballot.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/General/Ballot.lean new file mode 100644 index 0000000000..c58fceeb86 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/General/Ballot.lean @@ -0,0 +1,310 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Scenario +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Reciprocal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Parcel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Price + +/-! # Indexing selectors on occupied occurrences -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Sparse +open Coloring Finset Transcript + +variable {J I : Type} {m h k : ℕ} (loc : J ↪ B m × B h) (pad : B k) + +open scoped Classical in +/-- The condition `∀ v ∉ Set.range loc, c v.1 v.2 = pad` on the specified data. -/ +def Supported (c : B m → B h → B k) : Prop := + ∀ v ∉ Set.range loc, c v.1 v.2 = pad + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def pack (c : J → B k) (i : B m) (j : B h) := + Function.extend loc c (fun _ => pad) (i, j) + +open scoped Classical in +/-- Computes the sample by the application `c (loc j).1 (loc j).2`. -/ +def sample (c : B m → B h → B k) (j : J) := c (loc j).1 (loc j).2 + +open scoped Classical in +@[simp] theorem sample_pack (c : J → B k) : sample loc (pack loc pad c) = c := + funext fun j => loc.injective.extend_apply c (fun _ => pad) j + +open scoped Classical in +theorem pack_supported (c : J → B k) : Supported loc pad (pack loc pad c) := + fun _ hv => Function.extend_apply' _ _ _ hv + +open scoped Classical in +theorem pack_sample {c : B m → B h → B k} (hc : Supported loc pad c) : + pack loc pad (sample loc c) = c := by + have he (v : B m × B h) : pack loc pad (sample loc c) v.1 v.2 = c v.1 v.2 := by + by_cases hv : v ∈ Set.range loc + · obtain ⟨i, rfl⟩ := hv + exact congrFun (sample_pack loc pad (sample loc c)) i + · rw [pack_supported loc pad _ v hv, hc v hv] + exact funext fun i => funext fun j => he (i, j) + +open scoped Classical in +/-- Compression preserves the unique code of every supported branch. -/ +def compress (s : Selector I (B m → B h → B k)) + (ok : ∀ i, Supported loc pad (s.write i)) : Selector I (J → B k) where + write i := sample loc (s.write i) + read x := s.read (pack loc pad x) + valid x i := by + rw [s.valid] + exact ⟨fun e => (sample_pack loc pad x).symm.trans (congrArg (sample loc) e), + fun e => e ▸ pack_sample loc pad (ok i)⟩ + +open scoped Classical in +theorem of_weight {F : Type} [Zero F] (s : Selector I (B m → B h → B k)) + (ok : ∀ i, Supported loc pad (s.write i)) {w : I → F} {c : B m → B h → B k} + (hc : (s.read c).elim 0 w ≠ 0) : Supported loc pad c := by + cases e : s.read c with + | none => simp [e] at hc + | some i => rw [(s.valid c i).mp e]; exact ok i + +variable [Fintype J] + +open scoped Classical in +theorem card_le [Fintype I] (s : Selector I (J → B k)) : + Fintype.card I ≤ 2 ^ (k * Fintype.card J) := by + have h := Fintype.card_le_of_injective s.write s.injective + simpa only [Fintype.card_fun, Fintype.card_fin, pow_mul] using h + +open scoped Classical in +/-- Padded occurrences do not count toward the number of choices. -/ +theorem sum_pack {F : Type} [CommSemiring F] (weight f : (B m → B h → B k) → F) + (support : ∀ c, weight c ≠ 0 → Supported loc pad c) : + (∑ c, weight c * f c) = ∑ x, weight (pack loc pad x) * f (pack loc pad x) := by + have inj : Function.Injective (pack loc pad) := + Function.LeftInverse.injective (sample_pack loc pad) + let active := univ.image (pack loc pad) + calc + _ = ∑ c ∈ active, weight c * f c := (sum_subset (subset_univ _) (by + intro c _ hc + have hw : weight c = 0 := by + by_contra h + exact hc (mem_image.mpr ⟨sample loc c, mem_univ _, pack_sample loc pad (support c h)⟩) + rw [hw, zero_mul])).symm + _ = _ := sum_image inj.injOn + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Sparse +end + +/- # The unique ballot at a vacant occurrence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly Finset + +variable {F K N : Type} {m d h e M r t q D k n u j z : ℕ} + (U : Printer F K N m d h e M r t q D k n u j z) + +open scoped Classical in +/-- The ordinal coding the ballot whose digits are all zero. -/ +def pad : B U.digits := U.ballot (fun _ _ => 0) + +variable [Field F] (data : U.rows.obj) (c : U.selectors.obj) + +open scoped Classical in +theorem score_away (hn : U.score data c ≠ 0) (v : B m × B h) + (hv : U.menu ((data v.1).2 v.2) = none) : c v.1 v.2 = U.pad := by + let w := U.view (((U.around data c) v.1).2 v.2) + have he : w 0 0 = (none, U.ballot.symm (c v.1 v.2)) := by + simp only [w, view, around, Fmt.around, Fmt.expand, Fmt.zip, Neighborhood.origin, hv] + have hw : w.valid U.positive := by + by_contra ho + apply hn + unfold score Fmt.weight + apply prod_eq_zero (mem_univ v.1) + apply prod_eq_zero (mem_univ v.2) + exact ite_eq_right ho + apply U.ballot.symm.injective + rw [pad, U.ballot.symm_apply_apply] + funext i j + have hz : tally (U.ballot.symm (c v.1 v.2) i) = 0 := by + simpa [Lens.ask, he, quota] using hw i + have le : (U.ballot.symm (c v.1 v.2) i j).val ≤ tally (U.ballot.symm (c v.1 v.2) i) := + single_le_sum (fun l _ => Nat.zero_le (U.ballot.symm (c v.1 v.2) i l).val) (mem_univ j) + exact Fin.ext (Nat.eq_zero_of_le_zero (le.trans_eq hz)) + +open scoped Classical in +theorem supported {J : Type} (loc : J ↪ B m × B h) + (vacant : ∀ v ∉ Set.range loc, U.menu ((data v.1).2 v.2) = none) + (hn : U.score data c ≠ 0) : Sparse.Supported loc U.pad c := + fun v h => U.score_away data c hn v (vacant v h) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Reading a whole motion history from its selector words -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Assembly Coloring + +namespace Design + +variable (a : Design) {e k : ℕ} (start : (a.port e).obj) + +/-- The metadata tape, computed independently of the weights. -/ +def path : (i : ℕ) → (Fin i → (a.selectors k).obj) → (a.port (a.widthAt e k i)).obj + | 0, _ => start + | i + 1, c => a.update (path i (Fin.init c)) (c (Fin.last i)) + +theorem path_snoc {i : ℕ} (c : Fin i → (a.selectors k).obj) (t : (a.selectors k).obj) : + a.path start (i + 1) (Fin.snoc c t) = a.update (a.path start i c) t := by + rw [path, Fin.init_snoc, Fin.snoc_last] + +variable {F N A : Type} [Field F] [Fintype F] [ExpChar F a.p] + (hF : a.M * (2 * a.D + 1) < Fintype.card F) (menu : a.Menu F N A e) + +/-- In the case `0, _, _`, this construction gives `1`. -/ +def totalCharge : (i : ℕ) → i ≤ a.waves → (Fin i → (a.selectors k).obj) → F + | 0, _, _ => 1 + | i + 1, hi, c => + let j : Fin a.waves := ⟨i, hi⟩ + let p := a.path start i (Fin.init c) + totalCharge i j.isLt.le (Fin.init c) * + Fmt.weight (a.tariff hF j (a.menuAt hF menu k i j.isLt.le) k) (a.around p (c (Fin.last i))) + +theorem charge_snoc {i : ℕ} (hi : i < a.waves) (c : Fin i → (a.selectors k).obj) + (t : (a.selectors k).obj) : + a.totalCharge start hF menu (i + 1) hi (Fin.snoc c t) = + a.totalCharge start hF menu i hi.le c * + Fmt.weight (a.tariff hF ⟨i, hi⟩ (a.menuAt hF menu k i hi.le) k) (a.around (a.path start i + c) t) := by + rw [totalCharge, Fin.init_snoc, Fin.snoc_last] + +end Design + +namespace Scenario + +variable {F N A : Type} [Field F] {x y : Wire} {a : Design} (w : Scenario F N A a x y) + {k i : ℕ} + +/-- The indexing data represented by `Fin i → w.V → B k`. -/ +abbrev History (k i : ℕ) := Fin i → w.V → B k + +/-- Evaluates `Sparse.pack w.atlas.coord 0 (c j)` at the input `j`. -/ +def tapes (c : w.History k i) : Fin i → (a.selectors k).obj := + fun j => Sparse.pack w.atlas.coord 0 (c j) + +theorem tapes_snoc (c : w.History k i) (t : w.V → B k) : + w.tapes (Fin.snoc c t) = Fin.snoc (w.tapes c) (Sparse.pack w.atlas.coord 0 t) := by + funext j + refine Fin.lastCases ?_ (fun l => ?_) j <;> simp [tapes] + +end Scenario +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Factoring the charge of a history over its occupied cells -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Sparse +open Coloring Finset + +open scoped Classical in +theorem prod_occupied {V F : Type} [Fintype V] [CommMonoid F] {m h : ℕ} + (loc : V ↪ B m × B h) (f : B m × B h → F) (off : ∀ x ∉ Set.range loc, f x = 1) : + (∏ i, ∏ j, f (i, j)) = ∏ v, f (loc v) := by + rw [← Fintype.prod_prod_type, ← prod_image loc.injective.injOn] + symm + apply prod_subset (subset_univ _) + intro i _ hi + exact off i (by simpa using hi) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Sparse + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Design +open Assembly Coloring Finset + +variable (a : Design) {e k : ℕ} {F N A : Type} [Field F] [Fintype F] [ExpChar F a.p] + (start : (a.port e).obj) (hF : a.M * (2 * a.D + 1) < Fintype.card F) (menu : a.Menu F N A e) + +open scoped Classical in +/-- In the case `0, _, _, _`, this construction gives `1`. -/ +def localCharge : (i : ℕ) → i ≤ a.waves → (Fin i → (a.selectors k).obj) → B a.m × B a.h → F + | 0, _, _, _ => 1 + | i + 1, hi, c, v => + let j : Fin a.waves := ⟨i, hi⟩ + let p := a.path start i (Fin.init c) + localCharge i j.isLt.le (Fin.init c) v * + a.tariff hF j (a.menuAt hF menu k i j.isLt.le) k (((a.around p (c (Fin.last i))) v.1).2 v.2) + +open scoped Classical in +theorem total_eq_prod (i : ℕ) (hi : i ≤ a.waves) (c : Fin i → (a.selectors k).obj) : + a.totalCharge start hF menu i hi c = ∏ v, ∏ w, a.localCharge start hF menu i hi c (v, w) := by + induction i with + | zero => simp [totalCharge, localCharge] + | succ i ih => + simp only [totalCharge, localCharge, Fmt.weight, prod_mul_distrib] + rw [ih] + +open scoped Classical in +theorem vacant_step (j : Fin a.waves) (c : (a.selectors k).obj) (v : B a.m × B a.h) + (hv : (menu ((start v.1).2 v.2)).2 = none) (hc : c v.1 v.2 = 0) : + (a.nextMenu hF j menu k (((a.update start c) v.1).2 v.2)).2 = none ∧ + a.tariff hF j menu k (((a.around start c) v.1).2 v.2) = 1 := by + have origin : ((a.around start c) v.1).2 v.2 0 0 = ((start v.1).2 v.2, 0) := by + simp only [around, Fmt.around, Fmt.expand, Fmt.zip, Neighborhood.origin, hc] + simp [nextMenu, update, Fmt.update, tariff, route, charge, selected, origin, hv] + +open scoped Classical in +theorem vacant_path (v : B a.m × B a.h) (hv : (menu ((start v.1).2 v.2)).2 = none) + (i : ℕ) (hi : i ≤ a.waves) (c : Fin i → (a.selectors k).obj) (hc : ∀ j, c j v.1 v.2 = 0) : + (a.menuAt hF menu k i hi (((a.path start i c) v.1).2 v.2)).2 = none ∧ + a.localCharge start hF menu i hi c v = 1 := by + induction i with + | zero => exact ⟨hv, rfl⟩ + | succ i ih => + obtain ⟨empty, unit⟩ := ih (Nat.le_of_succ_le hi) (Fin.init c) (fun j => hc j.castSucc) + obtain ⟨hm, ht⟩ := a.vacant_step _ hF _ ⟨i, hi⟩ _ v empty (hc (Fin.last i)) + exact ⟨hm, by rw [localCharge, unit, ht, one_mul]⟩ + +open scoped Classical in +theorem total_occupied {V : Type} [Fintype V] (loc : V ↪ B a.m × B a.h) + (hv : ∀ v ∉ Set.range loc, (menu ((start v.1).2 v.2)).2 = none) + (i : ℕ) (hi : i ≤ a.waves) (c : Fin i → (a.selectors k).obj) + (hc : ∀ j, Sparse.Supported loc 0 (c j)) : + a.totalCharge start hF menu i hi c = ∏ v, a.localCharge start hF menu i hi c (loc v) := by + rw [total_eq_prod] + exact Sparse.prod_occupied loc _ (fun v h => + (a.vacant_path start hF menu v (hv v h) i hi c (fun j => hc j v h)).2) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Design +end + +/- # Wave selectors vanish outside the occupied occurrences -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Scenario +open Coloring Transcript + +variable {F A N : Type} [Field F] [Fintype F] {a : Design} [ExpChar F a.p] + {e k : ℕ} {x y : Wire} {menu : a.Menu F N A e} + (w : Scenario F N A a x y) (hF : a.M * (2 * a.D + 1) < Fintype.card F) + (j : Fin a.waves) (s : w.Code j.val menu) + (hk : Frame.budget F a.chart a.g a.H a.M a.D a.U ≤ 2 ^ k) + +theorem selector_away (i : Branch w hF j s) (v : B a.m × B a.h) (hv : v ∉ Set.range w.atlas.coord) : + (w.selector hF j s hk).write i v.1 v.2 = 0 := by + apply Selector.scatter_away + rintro ⟨t, ht⟩ + exact hv ⟨_, ht⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Scenario +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/General/Pruned.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/General/Pruned.lean new file mode 100644 index 0000000000..c42fe0c5c5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/General/Pruned.lean @@ -0,0 +1,368 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Normalize +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Restore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Encode +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Restore.Spans +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad + +/-! # Endpoints retained by loop removal -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +/-- The subtype of `e : G.E` satisfying `G.source e = v ∧ G.target e = v`. -/ +abbrev LocalLoop (v : G.V) := {e : G.E // G.source e = v ∧ G.target e = v} + +variable [Field F] + +/-- Embeds `G.removeLoops.End` into `G.End`. -/ +def embedEnd : G.removeLoops.End ↪ G.End := + let c : G.removeLoops.E ↪ G.E := ⟨Subtype.val, Subtype.val_injective⟩ + ((Function.Embedding.refl (slots a)).sumMap c).sumMap ((Function.Embedding.refl (slots b)).sumMap + c) + +theorem station_embedEnd (p : G.removeLoops.End) : + G.station (G.embedEnd p) = G.removeLoops.station p := by + rcases p with (p|p)|(p|p) <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- +# The local order of a station's ports + +Each side begins with its exterior bits. Named internal bundles follow +in the chosen order, with ascending offsets inside each bundle. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open Transcript Finset + +/-- Indexes the view by the coordinates of `List Bool × List (List Bool)`. -/ +abbrev View := List Bool × List (List Bool) +/-- The indexing data represented by `View → View → F`. -/ +abbrev Recipe (F : Type) := View → View → F + +/-- The data for the panel construction, including `ext`, `count`, `width`. -/ +structure Panel where + /-- Stores the ext associated with this `Panel`. -/ + ext : ℕ + /-- The number of entries. -/ + count : ℕ + /-- The width parameter carried by `Panel`, with type `Fin count → ℕ`. -/ + width : Fin count → ℕ + +namespace Panel +variable (P : Panel) + +/-- The sum of `P.width i` indexed by `i`. -/ +def size := ∑ i, P.width i +/-- Indexes the inner by the coordinates of `Σ i, Fin (P.width i)`. -/ +abbrev Inner := Σ i, Fin (P.width i) +/-- Indexes the port by the coordinates of `Fin P.ext ⊕ P.Inner`. -/ +abbrev Port := Fin P.ext ⊕ P.Inner + +/-- Computes the wire by the application `Wire.pair (word P.ext) (word P.size)`. -/ +def wire := Wire.pair (word P.ext) (word P.size) + +theorem wd_wire : wd P.wire = P.ext + P.size := by simp [wire, wd, wd_word] + +/-- The value specified by `(positions (word n)).trans (finCongr (wd_word n))`. -/ +def bitOrder (n : ℕ) := (positions (word n)).trans (finCongr (wd_word n)) + +/-- Reindexes `Fin P.size` and `P.Inner` by an equivalence. -/ +def serial : Fin P.size ≃ P.Inner := + (Fintype.orderIsoFinOfCardEq (Lex P.Inner) (by simp [size, Inner])).toEquiv.trans ofLex + +/-- Reindexes `slots P.wire` and `P.Port` by an equivalence. -/ +def port : slots P.wire ≃ P.Port := + (bitOrder P.ext).sumCongr ((bitOrder P.size).trans P.serial) + +/-- The value specified by `((positions P.wire) (P.port.symm i)).val`. -/ +def number (i : P.Port) := ((positions P.wire) (P.port.symm i)).val + +/-- Chooses the operation for the left or right summand. -/ +def block : P.Port → ℕ := Sum.elim (fun _ => 0) (fun i => i.1.val + 1) + +theorem block_le (i : P.Port) : P.block i ≤ P.count := by + cases i with + | inl _ => exact Nat.zero_le _ + | inr i => exact i.1.isLt + +private theorem bitOrder_val (n : ℕ) (i : Fin n) : + ((positions (word n)) ((bitOrder n).symm i)).val = i.val := by + simp [bitOrder] + +theorem number_ext (i : Fin P.ext) : P.number (.inl i) = i.val := by + change ((positions (word P.ext)) ((bitOrder P.ext).symm i)).val = _ + exact bitOrder_val _ _ + +theorem number_inner (i : P.Inner) : + P.number (.inr i) = P.ext + Processor.start P.width i.1 + i.2.val := by + change wd (word P.ext) + ((positions (word P.size)) ((bitOrder P.size).symm (P.serial.symm + i))).val = _ + rw [wd_word, bitOrder_val, Nat.add_assoc] + congr 1 + exact Processor.serial_rank _ _ (toLex i) + +theorem monotone (i j : P.Port) (h : P.number i ≤ P.number j) : P.block i ≤ P.block j := by + cases i with + | inl _ => exact Nat.zero_le _ + | inr i => + rw [number_inner] at h + cases j with + | inl j => rw [number_ext] at h; have := j.isLt; omega + | inr j => + rw [number_inner] at h + change i.1.val + 1 ≤ j.1.val + 1 + by_contra! he + have hj : j.1 < i.1 := Fin.lt_def.mpr (by omega) + have hh := Processor.start_left P.width _ _ hj + have := j.2.isLt + omega + +/-- The view of type `View` for the given inputs. -/ +def view (x : Val P.wire) : View := + (List.ofFn fun i => bits P.wire x (P.port.symm (.inl i)), + List.ofFn fun j : Fin P.count => List.ofFn fun i => bits P.wire x (P.port.symm (.inr ⟨j, i⟩))) + +/-- Uses `⟨P.wire, Q.wire, fun x y => f (P.view x) (Q.view y)⟩` as the representation. -/ +def table {F : Type} (Q : Panel) (f : Recipe F) : Table F := + ⟨P.wire, Q.wire, fun x y => f (P.view x) (Q.view y)⟩ + +end Panel +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- Incidence bijections with independently prescribed local orders. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open Transcript Finset + +variable {X V E : Type} {f : X → V} + +open Classical in +/-- The data for the enum construction, including `count`, `elem`. -/ +structure Enum (f : X → V) where + /-- The number of entries of type `V → ℕ`. -/ + count : V → ℕ + /-- Reindexes the data using `∀ v, Fin (count v) ≃ {x // f x = v}`. -/ + elem : ∀ v, Fin (count v) ≃ {x // f x = v} + +namespace Enum +open Classical in +/-- Uses `⟨fun v => Fintype.card {x // f x = v}, fun _ => (Fintype.equivFin _).symm⟩` as the +representation. -/ +def any [Fintype X] (f : X → V) : Enum f := + ⟨fun v => Fintype.card {x // f x = v}, fun _ => (Fintype.equivFin _).symm⟩ + +variable (B : Enum f) + +open Classical in +/-- Reindexes `(Σ v, Fin (B.count v))` and `X` by an equivalence. -/ +def full : (Σ v, Fin (B.count v)) ≃ X := + (Equiv.sigmaCongrRight B.elem).trans (Equiv.sigmaFiberEquiv f) + +open Classical in +/-- The value specified by `B.full ⟨v, i⟩`. -/ +abbrev get (v : V) (i : Fin (B.count v)) := B.full ⟨v, i⟩ + +open Classical in +/-- The value specified by `(B.elem (f x)).symm ⟨x, rfl⟩`. -/ +def index (x : X) := (B.elem (f x)).symm ⟨x, rfl⟩ + +open Classical in +theorem owner (v : V) (i : Fin (B.count v)) : f (B.get v i) = v := (B.elem v i).property + +open Classical in +@[simp] theorem get_index (x : X) : B.get (f x) (B.index x) = x := + congrArg Subtype.val ((B.elem (f x)).apply_symm_apply ⟨x, rfl⟩) + +open Classical in +theorem count_eq [Fintype X] (v : V) : B.count v = Fintype.card {x // f x = v} := + (Fintype.card_fin _).symm.trans (Fintype.card_congr (B.elem v)) + +end Enum + +open Classical in +/-- The data for the side construction, including `ext`, `inner`. -/ +structure Side (f : X → V) (g : E → V) where + /-- The `Side` component of type `Enum f`. -/ + ext : Enum f + /-- The internal data of type `Enum g`. -/ + inner : Enum g + +namespace Side + +variable {g : E → V} (S : Side f g) (w : E → ℕ) + +open Classical in +/-- Uses `⟨S.ext.count v, S.inner.count v, fun j => w (S.inner.get v j)⟩` as the representation. -/ +abbrev panel (v : V) : Panel := + ⟨S.ext.count v, S.inner.count v, fun j => w (S.inner.get v j)⟩ + +open Classical in +/-- Indexes the bit by the coordinates of `Σ e, Fin (w e)`. -/ +abbrev Bit := Σ e, Fin (w e) + +open Classical in +/-- Reindexes `(Σ v, slots (S.panel w v).wire)` and `X ⊕ Bit w` by an equivalence. -/ +def ports : (Σ v, slots (S.panel w v).wire) ≃ X ⊕ Bit w := + (Equiv.sigmaCongrRight fun v => (S.panel w v).port).trans <| + (Equiv.sigmaSumDistrib _ _).trans <| + S.ext.full.sumCongr ((Equiv.sigmaAssoc fun v j => Fin (w (S.inner.get v j))).symm.trans + (Equiv.sigmaCongrLeft (β := fun e => Fin (w e)) S.inner.full)) + +open Classical in +theorem ports_ext (v : V) (i : Fin (S.ext.count v)) : + S.ports w ⟨v, (S.panel w v).port.symm (.inl i)⟩ = .inl (S.ext.get v i) := by + simp [ports, Enum.get, Equiv.sigmaAssoc] + +open Classical in +theorem ports_inner (v : V) (i : Fin (S.inner.count v)) (k : Fin (w (S.inner.get v i))) : + S.ports w ⟨v, (S.panel w v).port.symm (.inr ⟨i, k⟩)⟩ = .inr ⟨S.inner.get v i, k⟩ := by + simp [ports, Enum.get, Equiv.sigmaAssoc] + +open Classical in +theorem owner (i : X ⊕ Bit w) : + ((S.ports w).symm i).1 = Sum.elim f (fun e => g e.1) i := by + obtain ⟨⟨v, k⟩, rfl⟩ := (S.ports w).surjective i + rw [Equiv.symm_apply_apply] + obtain ⟨j|⟨j, l⟩, rfl⟩ := (S.panel w v).port.symm.surjective k + · rw [S.ports_ext w v j]; exact (S.ext.owner _ _).symm + · rw [S.ports_inner w v j l]; exact (S.inner.owner _ _).symm + +open Classical in +/-- The peer of type `V × ℕ`, constructed using `(S.ports w).symm (.inr i)`. -/ +def peer (i : Bit w) : V × ℕ := + let s := (S.ports w).symm (.inr i) + (s.1, (positions (S.panel w s.1).wire s.2).val) + +open Classical in +theorem peer_offset (e : E) : ∃ n : ℕ, ∀ k, S.peer w ⟨e, k⟩ = (g e, n + k.val) := by + obtain ⟨⟨v, i⟩, rfl⟩ := S.inner.full.surjective e + refine ⟨S.ext.count v + Processor.start (S.panel w v).width i, fun k => ?_⟩ + change S.peer w ⟨S.inner.get v i, k⟩ = (g (S.inner.get v i), _) + unfold peer + rw [← ports_inner, Equiv.symm_apply_apply, S.inner.owner] + exact congrArg (fun n => (v, n)) ((S.panel w v).number_inner ⟨i, k⟩) + +open Classical in +/-- The indexed operation `(List.ofFn (fun i => x (S.ext.get v i)), List.ofFn (fun i => +List.ofFn (fun k => y ⟨S.inner.get v i, k⟩)))`. -/ +def view (v : V) (x : X → Bool) (y : Bit w → Bool) : View := + (List.ofFn (fun i => x (S.ext.get v i)), + List.ofFn (fun i => List.ofFn (fun k => y ⟨S.inner.get v i, k⟩))) + +open Classical in +theorem read (v : V) (x : X → Bool) (z : Bit w → Bool) : + (S.panel w v).view ((bits (S.panel w v).wire).symm (fun i => Sum.elim x z (S.ports w ⟨v, i⟩))) = + S.view w v x z := by + simp only [Panel.view, Equiv.apply_symm_apply, view] + refine Prod.ext (congrArg List.ofFn (funext fun i => ?_)) + (congrArg List.ofFn (funext fun i => congrArg List.ofFn (funext fun j => ?_))) + · rw [S.ports_ext w v i]; rfl + · rw [S.ports_inner w v i j]; rfl + +open Classical in +theorem wd_panel [Fintype X] [Fintype E] (v : V) : + wd (S.panel w v).wire = Fintype.card {x // f x = v} + ∑ e, if g e = v then w e else 0 := by + rw [Panel.wd_wire] + change S.ext.count v + (∑ i, w (S.inner.get v i)) = _ + rw [S.ext.count_eq, ← sum_filter, sum_subtype _ (by simp : ∀ e, e ∈ univ.filter (fun e => g e + = v) ↔ g e = v) w] + exact congrArg _ ((S.inner.elem v).sum_comp (fun j => w j.val)) + +end Side +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- # Local table values after contracting self-loops -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +open Assembly.Restore + +variable {F : Type} {a b : Wire} (G : Diagram F a b) [Field F] + +open scoped Classical in +private def extendSide {I : Type} (v : G.V) (x : I ⊕ G.removeLoops.E → Bool) + (z : G.LocalLoop v → Bool) : I ⊕ G.E → Bool + | .inl i => x (.inl i) + | .inr e => if h : G.source e ≠ G.target e then x (.inr ⟨e, h⟩) + else if hv : G.source e = v ∧ G.target e = v then z ⟨e, hv⟩ else false + +open scoped Classical in +private theorem weight_remove (v : G.V) (x : slots a ⊕ G.removeLoops.E → Bool) + (y : slots b ⊕ G.removeLoops.E → Bool) : + G.removeLoops.weight v x y = ∑ z : G.LocalLoop v → Bool, + G.weight v (G.extendSide v x z) (G.extendSide v y z) := by + unfold removeLoops + rw [weight_ofLocal] + · rfl + · intro w x₁ y₁ x₂ y₂ hx hy + change (∑ z : G.LocalLoop w → Bool, G.weight w (G.extendSide w x₁ z) (G.extendSide w y₁ z)) = + ∑ z : G.LocalLoop w → Bool, G.weight w (G.extendSide w x₂ z) (G.extendSide w y₂ z) + apply Finset.sum_congr rfl + intro z _ + apply G.local_weight + · rintro (p|e) hp + · exact hx (.inl p) hp + · by_cases h : G.source e ≠ G.target e + · simpa only [extendSide, dite_eq_left h] using hx (.inr ⟨e, h⟩) hp + · simp only [extendSide, dite_eq_right h] + · rintro (p|e) hp + · exact hy (.inl p) hp + · by_cases h : G.source e ≠ G.target e + · simpa only [extendSide, dite_eq_left h] using hy (.inr ⟨e, h⟩) hp + · simp only [extendSide, dite_eq_right h] + +open scoped Classical in +/-- Values on ports at other stations are immaterial. The two ends of +each removed loop share one summation bit. -/ +theorem loopTable (v : G.V) (x : G.removeLoops.End → Bool) + (y : (G.LocalLoop v → Bool) → G.End → Bool) + (retained : ∀ z p, G.removeLoops.station p = v → y z (G.embedEnd p) = x p) + (removed : ∀ z (e : G.LocalLoop v) d, y z (tip G e.val d) = z e) : + Transcript.sample (G.removeLoops.table v) (fun p => x (G.removeLoops.portEquiv ⟨v, p⟩)) = + ∑ z, Transcript.sample (G.table v) (fun p => y z (G.portEquiv ⟨v, p⟩)) := by + change G.removeLoops.weight v (x ∘ Sum.inl) (x ∘ Sum.inr) = + ∑ z, G.weight v (y z ∘ Sum.inl) (y z ∘ Sum.inr) + rw [weight_remove] + apply Finset.sum_congr rfl + intro z _ + apply G.local_weight + · rintro (p|e) hp + · exact (retained z (.inl (.inl p)) hp).symm + · by_cases h : G.source e ≠ G.target e + · rw [extendSide, dite_eq_left h] + exact (retained z (.inl (.inr ⟨e, h⟩)) hp).symm + · have hv : G.source e = v ∧ G.target e = v := ⟨hp, (not_ne_iff.mp h).symm.trans hp⟩ + rw [extendSide, dite_eq_right h, dite_eq_left hv] + exact (removed z ⟨e, hv⟩ false).symm + · rintro (p|e) hp + · exact (retained z (.inr (.inl p)) hp).symm + · by_cases h : G.source e ≠ G.target e + · rw [extendSide, dite_eq_left h] + exact (retained z (.inr (.inr ⟨e, h⟩)) hp).symm + · have hv : G.source e = v ∧ G.target e = v := ⟨(not_ne_iff.mp h).trans hp, hp⟩ + rw [extendSide, dite_eq_right h, dite_eq_left hv] + exact (removed z ⟨e, hv⟩ true).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/General/Scales.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/General/Scales.lean new file mode 100644 index 0000000000..cad883fbd7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/General/Scales.lean @@ -0,0 +1,410 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Squares +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Initial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Correct +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Matching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Parcel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Status +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Shapes + +/-! # Number of directed bundles at an input station -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Coloring Packing Finset + +variable {F : Type} {a b : Wire} {h D T R g : ℕ} {W : ℝ} (P : Input F a b h D T R g W) + +open scoped Classical in +/-- Only these stations can meet `v` at an internal wire. -/ +abbrev region (v : P.diagram.V) := + {w : P.diagram.V // (P.place w).2 = (P.place v).2 ∧ + (P.place w).1 ∈ insert (P.place v).1 (P.adj (P.place v).1)} + +open scoped Classical in +theorem region_bound (v : P.diagram.V) : Fintype.card (P.region v) ≤ (g + 1) * (100 * D) := by + let N := insert (P.place v).1 (P.adj (P.place v).1) + have hn : N.card ≤ g + 1 := (card_insert_le _ _).trans (Nat.add_le_add_right (P.degree _) _) + let fiber (j : N) := {w // P.place w = (j.val, (P.place v).2)} + let f (w : P.region v) : Σ j, fiber j := + ⟨⟨(P.place w.val).1, w.property.2⟩, w.val, Prod.ext rfl w.property.1⟩ + have hf : Function.Injective f := fun _ _ he => Subtype.ext (congrArg (fun x => x.2.val) he) + calc + _ ≤ Fintype.card (Σ j, fiber j) := Fintype.card_le_of_injective f hf + _ = ∑ j, Fintype.card (fiber j) := Fintype.card_sigma + _ ≤ ∑ _ : N, 100 * D := sum_le_sum fun _ _ => P.count _ + _ ≤ _ := by simpa using Nat.mul_le_mul_right (100 * D) hn + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def inputBits (g D : ℕ) := Nat.clog 2 (2 * ((g + 1) * (100 * D) + 1)) + +open scoped Classical in +/-- Reserve a direction bit and one additional remote name for the exterior. -/ +theorem bundleCount (v : P.diagram.V) : + Nonempty (Bool × Option (P.region v) ↪ B (inputBits g D)) := by + apply Function.Embedding.nonempty_of_card_le + rw [Fintype.card_prod, Fintype.card_bool, Fintype.card_option, Fintype.card_fin] + exact (Nat.mul_le_mul_left 2 (Nat.add_le_add_right (P.region_bound v) 1)).trans + (Nat.le_pow_clog (by decide) _) + +open scoped Classical in +theorem width_cap (v : P.diagram.V) : P.diagram.arity v < 2 ^ (Nat.clog 2 (100 * D * T + 1)) := by + have hv : (P.diagram.arity v : ℝ) ≤ (100 : ℝ) * D * T := by + refine le_trans ?_ (P.mass (P.place v)) + unfold push + simpa only [ite_true] using single_le_sum + (f := fun w => if P.place w = P.place v then (P.diagram.arity w : ℝ) else 0) + (fun _ _ => by positivity) (mem_univ v) + have hh : P.diagram.arity v ≤ 100 * D * T := by exact_mod_cast hv + exact (Nat.lt_succ_of_le hh).trans_le (Nat.le_pow_clog (by decide) _) + +open scoped Classical in +theorem channel_cap {ℓ : ℕ} (hD : 2 * SphereScale.budget g ≤ D) : + 2 ^ (Nat.clog 2 (g + 1) + 1) ≤ D ^ (Sphere.Layout.Sharing.allocation g ℓ) + 1 := by + have hb : 4 * (g + 1) ≤ D := by + have h := Nat.le_mul_of_pos_right (10000000 * (1 + 4 * g)) (by omega : 0 + < Routing.Private.energyConstant + 1) + unfold SphereScale.budget at hD + omega + calc + _ ≤ 4 * (g + 1) := by + rw [pow_succ] + have := Transcript.pow_clog_le_twice (by omega : 0 < g + 1) + omega + _ ≤ D := hb + _ ≤ _ := (Nat.le_self_pow (by unfold Sphere.Layout.Sharing.allocation; omega) _).trans + (Nat.le_add_right _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # The empty host needs no movement, labels or selectors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Packing Finset + +variable {F : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} + (P : Input F x y h D T r g W) [IsEmpty P.V] + +open scoped Classical in +theorem noStations : IsEmpty P.diagram.V := ⟨fun v => isEmptyElim (P.place v).1⟩ +open scoped Classical in +theorem noWires : IsEmpty P.diagram.E := ⟨fun e => isEmptyElim (P.place (P.diagram.source e)).1⟩ + +include P in +open scoped Classical in +theorem noExterior : IsEmpty (slots x ⊕ slots y) := + ⟨fun i => isEmptyElim (P.place (portEnd P.diagram i)).1⟩ + +open scoped Classical in +/-- Builds `LocalTerm F x y h u where V` with the specified `diagram`, `freeze`, `frame`, +`place`. -/ +abbrev emptyTerm (u : ℕ) : LocalTerm F x y h u where + V := P.V + diagram := P.diagram + freeze := ⟨fun _ => True, fun _ => trivial, fun e => isEmptyElim (P.place (P.diagram.source e)).1⟩ + frame := { + place := P.place, frozen := fun _ => True, keep := fun _ => Iff.rfl + N := P.adj, C := P.adj, ns := P.sym, cs := P.sym, sub := fun _ => Finset.Subset.refl _ + group := fun e => (P.edge e).1.symm + edge := fun e => isEmptyElim (P.place (P.diagram.source e.val)).1 + full := fun e => isEmptyElim (P.place (P.diagram.source e)).1 } + one v := isEmptyElim (P.place v).1 + width v := isEmptyElim (P.place v).1 + charge _ := 0 + cover v := isEmptyElim (P.place v).1 + floor v := isEmptyElim (P.place v).1 + +open scoped Classical in +theorem emptyConcentrated (u C d ℓ : ℕ) : Concentrated P (P.emptyTerm u) C d ℓ := by + have hW := (show 0 ≤ (univ.image P.place).card * (D : ℝ) * T by positivity).trans P.occupied + let _ : IsEmpty (P.emptyTerm u).freeze.Fixed := ⟨fun t => isEmptyElim (P.place t.val).1⟩ + let _ : IsEmpty (P.emptyTerm u).freeze.Core := ⟨fun t => isEmptyElim (P.place t.val).1⟩ + refine ⟨?_, fun v => isEmptyElim v, fun v => isEmptyElim v, ?_, ?_, ?_, ?_, ?_⟩ + · change Fintype.card P.V ≤ _; simp + · simp only [Fintype.card_eq_zero, Nat.cast_zero, zero_mul]; positivity + · exact fun v => isEmptyElim v + · simp only [univ_eq_empty, sum_empty]; positivity + · exact fun v => isEmptyElim v + · simp only [univ_eq_empty, sum_empty]; positivity + +open scoped Classical in +theorem emptyExpansion [Field F] (u C d ℓ A : ℕ) : LocalExpansion P u C d ℓ A := + ⟨Unit, inferInstance, fun _ => P.emptyTerm u, fun _ => 1, + by simpa using Nat.one_le_pow _ 2 (by decide), + fun _ _ => by simp, fun _ => P.emptyConcentrated ..⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Locating a frozen collector by its short station name -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Coloring Assembly Sphere Surface Surface.Local Routing.Private +open Sphere.Layout (Place item) + +variable {F K J : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ H U : ℕ} {W : ℝ} (P : Input F x y h D T (d * b) g W) + (p : P.Tools K ℓ m) (s : P.Occupied → Shape (SphereScale.probes ℓ D) b d) + {z : P.Configuration p} (hz : (P.plant p s).Reach m (2 * g) H U z) + {S : Scheme F} {r : S.format.obj} {portal : S.Presentation r P.diagram} + {loc : P.Occupied ↪ B S.m × B S.h} {tone : B S.m → ℕ} {mobile : S.Vtx → Bool} + (placed : P.Placed portal loc tone mobile) + {β : P.Occupied ⊕ ℕ → J} {G : Record F (d * b) d P.Occupied P.grid.Seam J (B S.k)} + (hm : Matches (P.reference p (finiteName S.k ∘ P.stationRank)).world β z G) +include placed + +theorem namedKeeps (e : slots x ⊕ slots y) : + let v := Packing.portEnd P.diagram e + ∃ i : Place z.scene.cell, loc i.1 = ((portal.vertex v).1, (portal.vertex v).2.1) ∧ + (P.inputPorts p s hz).ports i = P.diagram.extLeft v ∧ + (P.outputPorts p s hz).ports i = P.diagram.extRight v ∧ + (hm.row i).name = some (portal.vertex v).2.2 ∧ + ∀ j, j.1 = i.1 → (hm.row j).name = (hm.row i).name → j = i := by + intro v + let i := P.draw p s hz e + have pos (j : Place z.scene.cell) (w : P.diagram.V) + (hn : (item z.scene.cell j).label.name = some w) : + loc j.1 = ((portal.vertex w).1, (portal.vertex w).2.1) := by + rw [← (P.reached_name p s hz (List.get_mem _ j.2) hn).2, placed.location] + have row (j : Place z.scene.cell) : + (hm.row j).name = (item z.scene.cell j).label.name.map (fun w => (portal.vertex w).2.2) := by + have name : finiteName S.k ∘ P.stationRank = fun w => (portal.vertex w).2.2 := by + funext w + rw [Function.comp_apply, placed.name] + exact Fin.ext (Nat.mod_eq_of_lt (portal.vertex w).2.2.isLt) + rw [← name] + exact (hm.represents j).name.symm + have hn : (item z.scene.cell i).label.name = some v := P.draw_name p s hz e + have hi : (hm.row i).name = some (portal.vertex v).2.2 := by rw [row, hn]; rfl + refine ⟨i, pos i v hn, ?_, ?_, hi, ?_⟩ + · exact congrArg (fun a => a.elim [] P.diagram.extLeft) hn + · exact congrArg (fun a => a.elim [] P.diagram.extRight) hn + · intro j eq he + rw [row j, hi] at he + obtain ⟨w, hw, hs⟩ := Option.map_eq_some_iff.mp he + have hl := (pos j w hw).symm.trans ((congrArg loc eq).trans (pos i v hn)) + obtain ⟨ha, hb⟩ := Prod.mk.inj hl + have hv : w = v := portal.vertex.injective (Prod.ext ha (Prod.ext hb hs)) + exact (P.draw_eq p s hz e j (hw.trans (congrArg some hv))).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Address widths for ordered input dictionaries -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +/-- The least binary width whose power of two reaches `100 * D + 1`. -/ +abbrev stationBits (D : ℕ) := Nat.clog 2 (100 * D + 1) + +/-- The least binary width whose power of two reaches `g + 1`. -/ +abbrev channelBits (g : ℕ) := Nat.clog 2 (g + 1) + +/-- The least binary width whose power of two reaches `100 * D * T + 1`. -/ +abbrev widthBits (D T : ℕ) := Nat.clog 2 (100 * D * T + 1) + +theorem widthBits_le (D T : ℕ) : widthBits D T ≤ stationBits D + Nat.clog 2 (T + 1) := by + apply Nat.clog_le_of_le_pow + rw [pow_add] + exact (show 100 * D * T + 1 ≤ (100 * D + 1) * (T + 1) by ring_nf; omega).trans + (Nat.mul_le_mul (Nat.le_pow_clog (by decide) _) (Nat.le_pow_clog (by decide) _)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +/- # Dyadic and packet scales of the binary controller -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open SphereScale + +/-- Rounds the size up to the least power of two. -/ +abbrev rounded (D : ℕ) := 2 ^ Nat.clog 2 D +/-- The quantity computed by `(2 * T) / (rounded D) ^ terminalExponent g (ℓ + 1)`. -/ +abbrev unitSize (g ℓ D T : ℕ) := (2 * T) / (rounded D) ^ terminalExponent g (ℓ + 1) + +/-- The quantity computed by `2 * budget g + 400 * (g + 1)`. -/ +def threshold (g : ℕ) := 2 * budget g + 400 * (g + 1) + +variable {D T g : ℕ} + +theorem threshold_large (hD : threshold g ≤ D) : 2 ≤ D := by + unfold threshold at hD + omega + +theorem threshold_packet (hD : threshold g ≤ D) : 400 * (g + 1) ≤ rounded D := + (Nat.le_add_left ..).trans (hD.trans (Nat.le_pow_clog (by decide) D)) + +theorem threshold_scales (hD : threshold g ≤ D) : 2 * budget g ≤ rounded D := + (Nat.le_add_right ..).trans (hD.trans (Nat.le_pow_clog (by decide) D)) + +theorem inputBits_round (g D : ℕ) : inputBits g D ≤ inputBits g (rounded D) := by + unfold inputBits + gcongr + exact Nat.le_pow_clog (by decide) _ + +theorem doubled_log (T a B : ℕ) : + B * (1 + a + Nat.clog 2 (2 * T + 1)) ≤ (2 * B) * (1 + a + Nat.clog 2 (T + 1)) := by + have he : Nat.clog 2 (2 * T + 1) ≤ Nat.clog 2 (T + 1) + 1 := by + apply Nat.clog_le_of_le_pow + rw [pow_succ] + have := Nat.le_pow_clog (by decide : 1 < 2) (T + 1) + omega + rw [mul_comm 2 B, mul_assoc] + exact Nat.mul_le_mul_left _ (by omega) + +theorem packet_unit {ℓ : ℕ} (hD : 2 ≤ D) (hT : (rounded D) ^ terminalExponent g (ℓ + 1) ≤ 2 * T) : + 0 < unitSize g ℓ D T ∧ T ≤ unitSize g ℓ D T * D ^ (2 * terminalExponent g (ℓ + 1)) := by + let C := terminalExponent g (ℓ + 1) + let a := (rounded D) ^ C + let u := unitSize g ℓ D T + obtain ⟨hu, _, ht⟩ := floor_units (B := a) (pow_pos (by unfold rounded; positivity) _) hT + have hd : rounded D ≤ D ^ 2 := (Transcript.pow_clog_le_twice (by omega : 0 < D)).trans + (by rw [pow_two]; exact Nat.mul_le_mul_right _ hD) + have ha : a ≤ D ^ (2 * C) := by rw [pow_mul]; exact Nat.pow_le_pow_left hd C + have hb : 2 * T ≤ 2 * (u * a) := ht.trans_eq (mul_assoc ..) + exact ⟨hu, (show T ≤ u * a by omega).trans (Nat.mul_le_mul_left _ ha)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Agreement between the terminal records and the printer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Assembly Coloring Routing.Private Sphere SphereScale Surface Surface.Local + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {g ℓ D T b d p l j : ℕ} {W : ℝ} {S : Scheme F} + (P : Input F x y S.h D T (d * b) g W) + {z : S.format.obj} (A : P.HostChart S z) + (sc : Scales g ℓ D T (p ^ l) b d) (hK : Ready K ℓ D g (p ^ l) b d) + (s : P.Occupied → Shape (probes ℓ D) b d) + +local notation "kit" => P.kit sc hK +local notation "world" => P.localWorld A sc hK s +local notation "Cfg" => design S g ℓ D b d p l + +open scoped Classical in +theorem printSignal (pres : S.Presentation z P.diagram) {tone : B S.m → ℕ} {mobile : S.Vtx → Bool} + (h : P.Placed pres A.coord tone mobile) (hd : pres.Directed) + {menu : (Cfg).Menu F (B S.k) (B S.ℓ) j} (c : (world).Code (Cfg).waves menu) + {M r t k n u j' e : ℕ} + (U : Print.Printer F (panelKeys Cfg) (B S.k) S.m S.d S.h j M r t (Cfg).R D k n u j' e) + (ha : d * b = M * r) (hb : d = M * t) (hm : U.menu = printMenu S menu ha hb) + (status : (Print.Children.Header S.m S.d).obj) + (loc : ∀ v, A.coord v = (A.host v.val.1, cellIndex S.h v.val.2)) + (parents : Print.Children.Shows P.adj A.host (A.graph, status)) : + let f := c.frame + let Q := P.finalSource A sc hK s f + let left := P.inputPorts kit s f.reach + let right := P.outputPorts kit s f.reach + U.Signal Q left right (world).atlas (world).π f.address (world).ref f.record f.match' + (P.panelIndex sc hK) (world).size (P.panelExt A) A.host c.tape status ∧ + Print.Keeps Q left right pres A.coord := by + intro f Q left right + refine ⟨?_, P.keeps kit s f.reach h⟩ + refine ⟨Nat.le_add_left _ _, rfl, rfl, ⟨_, f.layout⟩, ?_, loc, parents, c.host, ?_, ?_, + fun _ _ _ _ => rfl, ?_, fun _ => rfl⟩ + · have he := f.clean.distinct + change Distinct ((world).atlas.near (horizon _ (Cfg).waves (Cfg).waves)) _ _ at he + simp only [horizon, Nat.sub_self, mul_zero, zero_add] at he + exact he + · intro i + rw [hm] + apply HEq.trans (cast_heq _ _) + apply heq_of_eq + refine (P.panel_read A sc hK s c i).trans ?_ + refine congrArg (fun z => (world).atlas.fill z i) (funext fun v => ?_) + simp only [panelFace, Print.Printer.faces, Frame.info, f] + congr 4 + exact Subsingleton.elim _ _ + · intro i w + erw [← (f.match'.represents i).name] + exact P.portsWidth kit s f.reach h hd i w + · intro i a b w + let j := (Layout.item f.stage.scene.cell i).label.name + change P.external kit j ((a, b), w) = + ((j.elim [] P.diagram.extLeft).map (bits x a), (j.elim [] P.diagram.extRight).map (bits y b)) + cases j <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Trial +open Sphere.Print + +variable {F : Type} [Field F] {x y : Wire} {D : Template F} + {a H T R : ℕ} {θ L : ℝ} {b : D.Binning a H T R θ} + {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} {p : D.Presents r P} + (t : b.Trial p L) (q : ℕ) + +theorem parents : Children.Shows (t.normal q).adj (t.atlas q).host ((t.atlas q).graph, b.status r) + := + ⟨t.live_status q, t.closed q, (t.atlas q).reciprocal, t.edge_status q⟩ + +theorem directed_order : t.order.Directed := by + unfold Scheme.Presentation.Directed + rw [t.post.ordered_ends] + exact t.directed + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Template.Binning.Trial +end + +/- # Common dimensions of the printer for a grouped layer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Sphere SphereScale +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {s : Rounds.Plan} {a T b d : ℕ} {θ L : ℝ} + (P : Layer F x y) (B : P.template.Binning a s.D T (d * b) θ) + +local notation "g" => ((4 * 5) ^ 300 : ℕ) + +open scoped Classical in +/-- The construction uses `Input.design B.target g 10 s.D b d p l` for its intermediate `cfg`. -/ +abbrev motionWidth (p l k : ℕ) := + let cfg := Input.design B.target g 10 s.D b d p l + cfg.widthAt (Input.panelQuery B.target g 10 s.D b d p l k).width k cfg.waves + +open scoped Classical in +/-- The construction uses `Input.design B.target g 10 s.D b d p l` for its intermediate `cfg`. -/ +abbrev Printer (p l k r t z f : ℕ) := + let cfg := Input.design B.target g 10 s.D b d p l + Print.Printer F (Input.panelKeys cfg) (Coloring.B B.target.k) B.target.m B.target.d B.target.h + (P.motionWidth B p l k) (chunks 10 s.D) r t cfg.R s.D + (Sphere.Layout.Sharing.allocation g 10) s.d (s.b * z) (p ^ l) f + +variable [Fintype F] {p l k r t z f : ℕ} [ExpChar F p] + (trials : ∀ i, B.Trial (P.presents i) L) + (sc : Scales g 10 s.D T (p ^ l) b d) (hK : SphereScale.Ready K 10 s.D g (p ^ l) b d) + (hF : room 10 s.D g * (2 * depth 10 s.D g (p ^ l) (d * b) + 1) < Fintype.card F) + (U : P.Printer B p l k r t z f) + +open scoped Classical in +/-- The releases used in the `Layer` construction. -/ +abbrev Releases := ∀ i : (P.moved B trials sc hK hF k).state, + U.Release (P := (trials i.1.1).normal (panelRadius s.D)) (trials i.1.1).order + i.2.tape (B.status (P.data i.1.1)) ((P.moved B trials sc hK hF k).eval i) 10 + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Boundary.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Boundary.lean new file mode 100644 index 0000000000..8540b1b771 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Boundary.lean @@ -0,0 +1,1063 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Tactic.Linarith +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting +public import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.View +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Parcel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Terminal + +/-! # Fan-in two formulas on a finite alphabet -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Finset + +open scoped Classical in +/-- The bit formula used in the `Geometry` construction. -/ +inductive BitFormula (X : Type) + | const (v : Bool) + | pin (i : X) + | not (a : BitFormula X) + | and (a b : BitFormula X) + | or (a b : BitFormula X) + +variable {X S : Type} + +open scoped Classical in +/-- In the case `.const b, _`, this construction gives `b`. -/ +def BitFormula.eval : BitFormula X → (X → Bool) → Bool + | .const b, _ => b + | .pin i, x => x i + | .not a, x => !(a.eval x) + | .and a b, x => a.eval x && b.eval x + | .or a b, x => a.eval x || b.eval x + +open scoped Classical in +/-- In the case `.const _ | .pin _`, this construction gives `1`. -/ +def BitFormula.cost : BitFormula X → ℕ + | .const _ | .pin _ => 1 + | .not a => a.cost + 1 + | .and a b | .or a b => a.cost + b.cost + 1 + +open scoped Classical in +theorem pattern (x : X → Bool) (t : Finset X) : ∃ a : BitFormula X, + (∀ y, a.eval y = true ↔ ∀ i ∈ t, y i = x i) ∧ a.cost ≤ 3 * t.card + 1 := by + induction t using Finset.induction_on with + | empty => exact ⟨.const true, by simp [BitFormula.eval], by simp [BitFormula.cost]⟩ + | @insert i t hi ih => + obtain ⟨a, ha, hc⟩ := ih + let b : BitFormula X := if x i then .pin i else .not (.pin i) + have hb (y : X → Bool) : b.eval y = true ↔ y i = x i := by + cases h : x i <;> simp [b, h, BitFormula.eval] + have hk : b.cost ≤ 2 := by unfold b; split <;> simp [BitFormula.cost] + refine ⟨.and b a, ?_, ?_⟩ + · simp [BitFormula.eval, ha, hb] + · rw [BitFormula.cost, card_insert_of_notMem hi] + omega + +variable [Fintype X] + +open scoped Classical in +/-- Charge every node including inputs and constants. A disjunction +of exact patterns suffices on the image of the encoding. -/ +theorem finite_formula [Fintype S] (emb : S ↪ (X → Bool)) (f : S → Bool) : + ∃ a : BitFormula X, (∀ s, a.eval (emb s) = f s) ∧ + a.cost ≤ (3 * Fintype.card X + 2) * Fintype.card S + 1 := by + have go (t : Finset S) : ∃ a : BitFormula X, (∀ s, a.eval (emb s) = true ↔ s ∈ t) ∧ + a.cost ≤ (3 * Fintype.card X + 2) * t.card + 1 := by + induction t using Finset.induction_on with + | empty => exact ⟨.const false, by simp [BitFormula.eval], by simp [BitFormula.cost]⟩ + | @insert i t hi ih => + obtain ⟨a, ha, hc⟩ := ih + obtain ⟨b, hb, hk⟩ := pattern (emb i) univ + refine ⟨.or b a, ?_, ?_⟩ + · simp [BitFormula.eval, ha, hb, ← funext_iff, emb.injective.eq_iff] + · rw [card_univ] at hk + rw [BitFormula.cost, card_insert_of_notMem hi, Nat.mul_succ] + omega + let t : Finset S := {s | f s = true} + obtain ⟨a, ha, hc⟩ := go t + refine ⟨a, fun s => ?_, hc.trans (by gcongr; exact card_le_univ _)⟩ + exact Bool.eq_iff_iff.mpr (by simpa [t] using ha s) + +open scoped Classical in +theorem bool_formula (f : (X → Bool) → Bool) : ∃ a : BitFormula X, + a.eval = f ∧ a.cost ≤ (3 * Fintype.card X + 2) * 2 ^ Fintype.card X + 1 := by + obtain ⟨a, ha, hc⟩ := finite_formula (Function.Embedding.refl _) f + exact ⟨a, funext ha, by simpa using hc⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +/- +# A finite description of a station's geometry + +Internal spans have unit width. The two exterior widths are copied +from the old station named by the collector. They need no space in +the proposed description. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Assembly Coloring Finset + +open scoped Classical in +/-- The data for the outline construction, including `live`, `peer`, `direction`, `name`. -/ +structure Outline (d e k : ℕ) where + /-- The `Outline` component of type `Bool`. -/ + live : Bool + /-- The `Outline` component of type `B e → Option (B d × B 0 × B e)`. -/ + peer : B e → Option (B d × B 0 × B e) + /-- The `Outline` component of type `B e → Bool`. -/ + direction : B e → Bool + /-- The name assigned to each index of type `Option (B k) deriving Fintype`. -/ + name : Option (B k) + deriving Fintype + +open scoped Classical in +/-- The indexing data represented by `B w → Outline d e k`. -/ +abbrev Blueprint (w d e k : ℕ) := B w → Outline d e k + +variable {F : Type} {d e k w : ℕ} + +namespace Outline +variable (a : Outline d e k) (u : ℕ) (outer : Bool ↪ B e) (size : Option (B k) → Bool → ℕ) + +open scoped Classical in +/-- Uses `⟨false, fun _ => none, fun _ => false, none⟩` as the representation. -/ +def empty : Outline d e k := ⟨false, fun _ => none, fun _ => false, none⟩ + +open scoped Classical in +/-- The value specified by `#{i : B e | (a.peer i).isSome}`. -/ +def links := #{i : B e | (a.peer i).isSome} + +open scoped Classical in +/-- Returns `1 + a.links` when `a.live` holds, and `0` otherwise. -/ +def toll := if a.live then 1 + a.links else 0 + +open scoped Classical in +/-- Selects the appropriate branch of `if (a.peer i).isSome then u else if i = outer false then +size a.name false else if i = outer true then size a.name true else 0`. -/ +def width (i : B e) := + if (a.peer i).isSome then u else + if i = outer false then size a.name false else if i = outer true then size a.name true else 0 + +open scoped Classical in +/-- The data for the matches construction, including `peer`, `direction`, `width`. -/ +structure Matches (x : Pattern F d 0 e) : Prop where + peer : a.peer = x.peer 0 + direction : a.direction = x.direction 0 + width : a.width u outer size = x.width 0 + +open scoped Classical in +/-- Uses `⟨live, x.peer 0, x.direction 0, name⟩` as the representation. -/ +def read (live : Bool) (name : Option (B k)) (x : Pattern F d 0 e) : Outline d e k := + ⟨live, x.peer 0, x.direction 0, name⟩ + +end Outline +namespace Blueprint +variable (a : Blueprint w d e k) (fixed : B w → Bool) + +open scoped Classical in +/-- The value specified by `#{i | (a i).live = true ∧ fixed i = true}`. -/ +def count := #{i | (a i).live = true ∧ fixed i = true} +open scoped Classical in +/-- The sum of `if fixed i then (a i).toll ^ 2 else 0` indexed by `i`. -/ +def square := ∑ i, if fixed i then (a i).toll ^ 2 else 0 +open scoped Classical in +/-- The sum of `if fixed i then 0 else (a i).toll` indexed by `i`. -/ +def mobile := ∑ i, if fixed i then 0 else (a i).toll + +end Blueprint +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +section +/- # Reading a bounded number of bits at fixed addresses -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry.BitFormula +variable {X Y : Type} + +/-- In the case `.const b`, this construction gives `.const b`. -/ +def rename (a : BitFormula X) (f : X → Y) : BitFormula Y := + match a with + | .const b => .const b + | .pin i => .pin (f i) + | .not b => .not (b.rename f) + | .and b c => .and (b.rename f) (c.rename f) + | .or b c => .or (b.rename f) (c.rename f) + +@[simp] theorem eval_rename (a : BitFormula X) (f : X → Y) (v : Y → Bool) : + (a.rename f).eval v = a.eval (v ∘ f) := by + induction a <;> simp_all [rename, eval] + +@[simp] theorem cost_rename (a : BitFormula X) (f : X → Y) : + (a.rename f).cost = a.cost := by + induction a <;> simp_all [rename, cost] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry.BitFormula +end + +/- # Local energy and crossing credits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +variable {F T E V X : Type} {r t : ℕ} [Fintype V] + +open scoped Classical in +/-- Computes the collector unit by the application `r.collected 1`. -/ +abbrev collectorUnit (r : Role) (_ : ℕ) := r.collected 1 + +open scoped Classical in +/-- The value specified by `(s.ledger P H).cost g v`. -/ +def energyCre (s : Stage F r t T V E X) (P H g : ℕ) (v : V) := + (s.ledger P H).cost g v + +open scoped Classical in +/-- A remaining seam crossing is reserved at both endpoints. -/ +def timeCre (s : Stage F r t T V E X) (P H U : ℕ) (v : V) := + U * s.tally P collectorUnit v + s.tally P (fun c _ => c.clock) v + + ∑ e ∈ s.edges v, (s.ledger P H).seam e / (2 * P * H) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- # Counting the time credits of a stage -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +open Finset + +variable {F T E V X : Type} {r t P H U g : ℕ} {s s' : Stage F r t T V E X} + {src dst : E → V} + +open scoped Classical in +private theorem hits_mono [Field F] (h : s.Reach P g H U s') (e : E) : + s.hits e ≤ s'.hits e := by + induction h with + | refl => rfl + | tail _ a ih => + apply ih.trans + cases a with + | perm | expire | merge => rfl + | cross v w j => by_cases he : e = j <;> simp [advance, he] + +variable [Fintype V] [Fintype E] + +open scoped Classical in +private theorem endpoints (hl : s.Layout src dst g) (c : E → ℕ) : + (∑ v, ∑ e ∈ s.edges v, c e) = 2 * ∑ e, c e := by + calc + _ = ∑ e, ∑ _ ∈ {src e, dst e}, c e := sum_comm' (by + intro v e + simp only [mem_univ, true_and, and_true, mem_insert, mem_singleton, edges, List.mem_toFinset] + simpa only [eq_comm, ports] using hl.incident v e) + _ = _ := by simp [hl.loopless, mul_sum] + +open scoped Classical in +omit [Fintype E] in +/-- Each new crossing is paid for by at least one unit of seam credit. +Expirations exchange elapsed clock ticks for collector credit. -/ +theorem Reach.timeCre [Finite E] [Field F] (h : s.Reach P g H U s') (hP : 0 < P) (hH : 0 < H) + (hl : s.Layout src dst g) : (∑ v, s'.timeCre P H U v) ≤ ∑ v, s.timeCre P H U v := by + let : Fintype E := Fintype.ofFinite E + let M := 2 * P * H + have hm : 0 < M := by unfold M; positivity + let A := s.ledger P H + let B := s'.ledger P H + have edge (e : E) : B.seam e / M + B.hits e ≤ A.seam e / M + A.hits e := by + rw [← Nat.add_mul_div_left _ _ hm, ← Nat.add_mul_div_left _ _ hm] + exact Nat.div_le_div_right (h.budget.edge e) + have seam := sum_le_sum (fun e (_ : e ∈ univ) => edge e) + rw [sum_add_distrib, sum_add_distrib] at seam + have hits : (∑ e, A.hits e) ≤ ∑ e, B.hits e := sum_le_sum fun e _ => hits_mono h e + have time : U * s'.expired + B.clock + (∑ e, A.hits e) ≤ + U * s.expired + A.clock + ∑ e, B.hits e := h.budget.time + have count := congrArg (U * ·) h.collectors + rw [mul_add, mul_add] at count + simp only [Stage.timeCre, sum_add_distrib, ← mul_sum, h.edges_eq, endpoints hl] + change U * s'.collectors + B.clock + 2 * (∑ e, B.seam e / M) ≤ + U * s.collectors + A.clock + 2 * (∑ e, A.seam e / M) + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- # Localizing the global ledger inequalities along a wave execution -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Finset + +variable {F T V E X K N : Type} [Field F] [Fintype V] [Fintype E] {r t P g H U M D n : ℕ} + {key : V → X → ℕ} {src dst : E → V} + +local notation "Cmd" => Command F r t T V E X K N P g H U M D key +local notation "St" => Stage F r t T V E X + +open scoped Classical in +/-- Requires `v ∈ Set.range c.ref.vertex ∨ ∃ e ∈ Set.range c.ref.edge, src e = v ∨ dst e = v`. -/ +def Command.affected (c : Cmd) (src dst : E → V) (v : V) : Prop := + v ∈ Set.range c.ref.vertex ∨ ∃ e ∈ Set.range c.ref.edge, src e = v ∨ dst e = v + +omit [Fintype E] in +open scoped Classical in +private theorem off {s q : St} {β γ : V ⊕ ℕ → K} {c : Cmd} + {G : Record F r t c.vertices c.edges K N} {fresh : List (K × ℕ)} + (h : Update P g H U c.ref β γ s q G fresh) (hL : s.Layout src dst g) {v : V} + (hv : ¬ c.affected src dst v) : + q.energyCre P H g v = s.energyCre P H g v ∧ q.timeCre P H U v = s.timeCre P H U v := by + obtain ⟨π, _, _, hp⟩ := h.outside.project + have he := hp v (fun hi => hv (.inl hi)) + have ht (f : Role → ℕ → ℕ) : q.tally P f v = s.tally P f v := by + simp [Stage.tally, he, Cell.pull, Station.pull, energyOf, Function.comp_def] + simp only [Stage.energyCre, Stage.timeCre, Ledger.cost, Stage.ledger, ht, h.reach.edges_eq, + true_and] + congr 1 + apply sum_congr rfl + intro e hi + rw [h.outside.level e (fun hj => hv (.inr ⟨e, hj, + (hL.incident v e).mp (List.mem_toFinset.mp hi)⟩))] + +open scoped Classical in +/-- If only one fiber changes, a global inequality holds on each +fiber separately. -/ +private theorem localize {a b : V → ℕ} (p : V → V) (j : V) + (h : ∑ v, b v ≤ ∑ v, a v) (fixed : ∀ v, p v ≠ j → b v = a v) (i : V) : + (∑ v ∈ univ.filter (fun v => p v = i), b v) ≤ ∑ v ∈ univ.filter (fun v => p v = i), a v := by + let S := univ.filter (fun v => p v = i) + by_cases hi : i = j + · have he : ∑ v ∈ univ \ S, b v = ∑ v ∈ univ \ S, a v := + sum_congr rfl (fun v hv => fixed v (by simpa [S, hi] using (mem_sdiff.mp hv).2)) + rw [← sum_sdiff (subset_univ S) (f := a), ← sum_sdiff (subset_univ S) (f := b), he] at h + exact Nat.le_of_add_le_add_left h + · exact sum_le_sum (fun v hv => (fixed v ((mem_filter.mp hv).2.trans_ne hi)).le) + +open scoped Classical in +omit [Fintype E] in +theorem Wave.Execution.regional [Finite E] {C : Fin n → Cmd} {i : Wave.Index C} + {s q : St} {β γ : V ⊕ ℕ → K} (h : Wave.Execution C i s q β γ) + (hP : 0 < P) (hH : 0 < H) (hL : s.Layout src dst g) (p : V → V) + (hpart : ∀ a, ∃ u, ∀ v, (C a).affected src dst v → p v = u) : + (∀ a, (∑ v ∈ univ.filter (fun v => p v = a), q.energyCre P H g v) ≤ + ∑ v ∈ univ.filter (fun v => p v = a), s.energyCre P H g v) ∧ + (∀ a, (∑ v ∈ univ.filter (fun v => p v = a), q.timeCre P H U v) ≤ + ∑ v ∈ univ.filter (fun v => p v = a), s.timeCre P H U v) ∧ + (∀ v, (∀ a, ¬ (C a).affected src dst v) → + q.energyCre P H g v = s.energyCre P H g v ∧ q.timeCre P H U v = s.timeCre P H U v) := by + let : Fintype E := Fintype.ofFinite E + induction n generalizing s β with + | zero => rw [h.1]; simp + | succ n ih => + obtain ⟨m, δ, hm, ht⟩ := h + have hL' : m.Layout src dst g := ⟨hL.loopless, hm.reach.ports_eq.symm ▸ hL.incident, + hm.reach.ports_eq.symm ▸ hL.unique, hm.reach.ports_eq.symm ▸ hL.degree⟩ + obtain ⟨he, hc, ho⟩ := ih ht hL' (fun a => hpart a.succ) + obtain ⟨u, hu⟩ := hpart 0 + have hfix v (hv : p v ≠ u) := off hm hL (fun h => hv (hu v h)) + refine ⟨fun a => (he a).trans ?_, fun a => (hc a).trans ?_, fun v hv => ?_⟩ + · exact localize p u hm.reach.budget.total (fun v h => (hfix v h).1) a + · exact localize p u (hm.reach.timeCre hP hH hL) (fun v h => (hfix v h).2) a + · have h₁ := off hm hL (hv 0) + have h₂ := ho v (fun a => hv a.succ) + exact ⟨h₂.1.trans h₁.1, h₂.2.trans h₁.2⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Constructing a directed diagram from reciprocal span data -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +open Transcript + +variable {F : Type} [Field F] + +open scoped Classical in +/-- The locations to include in the diagram, with a direction-preserving +enumeration of all exposed bits. Inactive locations are neutral. -/ +structure Realization (S : Scheme F) (r : S.format.obj) (x y : Wire) where + proper : S.Proper r + /-- The active indices of type `S.Vtx → Prop`. -/ + active : S.Vtx → Prop + vacant : ∀ v, ¬active v → (∀ i, S.width r (v, i) = 0) ∧ ∀ t, S.table r v t = 1 + /-- Reindexes the data using `slots x ⊕ slots y ≃ S.exposed r`. -/ + boundary : slots x ⊕ slots y ≃ S.exposed r + side : ∀ i, S.direction r (boundary i).val.1 = i.isRight + +namespace Realization +variable {S : Scheme F} {r : S.format.obj} {x y : Wire} (R : S.Realization r x y) + +open scoped Classical in +/-- The subtype of `v` satisfying `R.active v`. -/ +abbrev V := {v // R.active v} +open scoped Classical in +/-- The subtype of `p : S.Pin r` satisfying `S.peer r p.1 ≠ none ∧ S.direction r p.1 = false`. -/ +abbrev E (_ : S.Realization r x y) := {p : S.Pin r // S.peer r p.1 ≠ none ∧ S.direction r p.1 + = false} +open scoped Classical in +/-- Indexes the end by the coordinates of `(slots x ⊕ R.E) ⊕ slots y ⊕ R.E`. -/ +abbrev End := (slots x ⊕ R.E) ⊕ slots y ⊕ R.E + +include R in +open scoped Classical in +theorem paired (p : S.Pin r) (h : S.peer r p.1 ≠ none) : ∃ q, S.Joins r p q := by + obtain ⟨t, ht⟩ := Option.ne_none_iff_exists'.mp h + exact ⟨⟨t, p.2.cast (R.proper _ _ ht).2.1⟩, ht, rfl⟩ + +open scoped Classical in +/-- The value specified by `(R.paired e.val e.property.1).choose`. -/ +def mate (e : R.E) := (R.paired e.val e.property.1).choose + +open scoped Classical in +theorem paired_mate (e : R.E) : S.Joins r e.val (R.mate e) := + (R.paired e.val e.property.1).choose_spec + +open scoped Classical in +/-- In the case `.inl (.inl v)`, this construction gives `(R.boundary (.inl v)).val`. -/ +def dest : R.End → S.Pin r + | .inl (.inl v) => (R.boundary (.inl v)).val + | .inl (.inr e) => e.val + | .inr (.inl v) => (R.boundary (.inr v)).val + | .inr (.inr e) => R.mate e + +open scoped Classical in +private theorem dest_side (i : R.End) : S.direction r (R.dest i).1 = i.isRight := by + rcases i with (i|e)|(i|e) + · exact R.side _ + · exact e.property.2 + · exact R.side _ + · have h := (R.proper _ _ (R.paired_mate e).1).2.2 + rw [e.property.2] at h + cases hd : S.direction r (R.mate e).1 <;> simp_all [dest] + +open scoped Classical in +private theorem dest_inner (i : R.End) : + (S.peer r (R.dest i).1).isSome = Sum.elim Sum.isRight Sum.isRight i := by + rcases i with (i|e)|(i|e) + · simp [dest, (R.boundary (.inl i)).property] + · exact Option.isSome_iff_exists.mpr ⟨_, (R.paired_mate e).1⟩ + · simp [dest, (R.boundary (.inr i)).property] + · exact Option.isSome_iff_exists.mpr ⟨_, ((R.paired_mate e).symm R.proper).1⟩ + +open scoped Classical in +theorem dest_bijective : Function.Bijective R.dest := by + constructor + · intro i j h + have hs : i.isRight = j.isRight := by rw [← R.dest_side, ← R.dest_side, h] + have ht : Sum.elim Sum.isRight Sum.isRight i = Sum.elim Sum.isRight Sum.isRight j := by + rw [← R.dest_inner, ← R.dest_inner, h] + rcases i with (i|e)|(i|e) <;> rcases j with (j|f)|(j|f) <;> try contradiction + · rw [Sum.inl.inj (R.boundary.injective (Subtype.ext h))] + · rw [show e = f from Subtype.ext h] + · rw [Sum.inr.inj (R.boundary.injective (Subtype.ext h))] + · change R.mate e = R.mate f at h + have he := (R.paired_mate e).symm R.proper + rw [h] at he + rw [show e = f from Subtype.ext (he.unique ((R.paired_mate f).symm R.proper))] + · intro p + by_cases hp : S.peer r p.1 = none + · obtain ⟨i|i, hi⟩ := R.boundary.surjective ⟨p, hp⟩ + · exact ⟨.inl (.inl i), congrArg Subtype.val hi⟩ + · exact ⟨.inr (.inl i), congrArg Subtype.val hi⟩ + cases hd : S.direction r p.1 + · exact ⟨.inl (.inr ⟨p, hp, hd⟩), rfl⟩ + · obtain ⟨w, hw⟩ := R.paired p hp + have hj := hw.symm R.proper + have hd' := (R.proper _ _ hw.1).2.2 + rw [hd] at hd' + let e : R.E := ⟨w, by simp [hj.1], by cases h : S.direction r w.1 <;> simp_all⟩ + exact ⟨.inr (.inr e), (R.paired_mate e).unique hj⟩ + +open scoped Classical in +theorem active_at (p : S.Pin r) : R.active p.1.1 := by + by_contra h + have he : S.width r p.1 = 0 := (R.vacant _ h).1 p.1.2 + exact (Nat.ne_of_gt (Nat.zero_lt_of_lt p.2.isLt)) he + +open scoped Classical in +/-- The value specified by `(S.pattern r v.val).orderedTable v.val.2.2`. -/ +def table (v : R.V) := (S.pattern r v.val).orderedTable v.val.2.2 +open scoped Classical in +/-- Reindexes `Ports (R.table v)` and `S.LocalPin r v.val` by an equivalence. -/ +def pin (v : R.V) : Ports (R.table v) ≃ S.LocalPin r v.val := + (S.pattern r v.val).orderedPin v.val.2.2 + +open scoped Classical in +/-- Computes the attach by the application `S.port r i.1.val (R.pin i.1 i.2)`. -/ +def attach (i : Σ v, Ports (R.table v)) := S.port r i.1.val (R.pin i.1 i.2) + +open scoped Classical in +theorem attach_bijective : Function.Bijective R.attach := by + constructor + · rintro ⟨v, i⟩ ⟨w, j⟩ h + have hv : v = w := Subtype.ext (congrArg (fun p => p.1.1) h) + subst w + have hs : (R.pin v i).1 = (R.pin v j).1 := congrArg (fun p => p.1.2) h + have hn : (R.pin v i).2.val = (R.pin v j).2.val := congrArg (fun p => p.2.val) h + have ht := Sigma.ext hs ((Fin.heq_ext_iff (congrArg (fun z => S.width r (v.val, z)) hs)).mpr hn) + rw [(R.pin v).injective ht] + · rintro ⟨⟨v, j⟩, i⟩ + let u : R.V := ⟨v, R.active_at ⟨(v, j), i⟩⟩ + refine ⟨⟨u, (R.pin u).symm ⟨j, i⟩⟩, ?_⟩ + simp only [attach, Equiv.apply_symm_apply] + rfl + +open scoped Classical in +/-- Indexes the left by the coordinates of `Σ v, slots (R.table v).1`. -/ +abbrev Left := Σ v, slots (R.table v).1 +open scoped Classical in +/-- Indexes the right by the coordinates of `Σ v, slots (R.table v).2.1`. -/ +abbrev Right := Σ v, slots (R.table v).2.1 + +open scoped Classical in +/-- Reindexes `R.Left ⊕ R.Right` and `R.End` by an equivalence. -/ +def ends : R.Left ⊕ R.Right ≃ R.End := + ((Equiv.sigmaSumDistrib _ _).symm.trans (Equiv.ofBijective R.attach R.attach_bijective)).trans + (Equiv.ofBijective R.dest R.dest_bijective).symm + +open scoped Classical in +private theorem ends_spec (z : R.Left ⊕ R.Right) : + R.dest (R.ends z) = R.attach ((Equiv.sigmaSumDistrib _ _).symm z) := + (Equiv.ofBijective R.dest R.dest_bijective).apply_symm_apply _ + +open scoped Classical in +private theorem ends_side (z : R.Left ⊕ R.Right) : (R.ends z).isRight = z.isRight := by + rw [← R.dest_side, R.ends_spec] + rcases z with ⟨v, i⟩|⟨v, i⟩ + · exact (S.pattern r v.val).pin_side _ (.inl i) + · exact (S.pattern r v.val).pin_side _ (.inr i) + +open scoped Classical in +theorem wiring : + ∃ f : R.Left ≃ slots x ⊕ R.E, ∃ g : R.Right ≃ slots y ⊕ R.E, f.sumCongr g = R.ends := by + have l (a : R.Left) : ∃ c, R.ends (.inl a) = .inl c := by + have hi := R.ends_side (.inl a) + cases he : R.ends (.inl a) <;> simp_all + have t (b : R.Right) : ∃ d, R.ends (.inr b) = .inr d := by + have hi := R.ends_side (.inr b) + cases he : R.ends (.inr b) <;> simp_all + choose f hf using l + choose g hg using t + have he : Sum.map f g = R.ends := by funext i; cases i <;> simp [hf, hg] + obtain ⟨h₁, h₂⟩ := Sum.map_bijective.mp (he.symm ▸ R.ends.bijective) + exact ⟨Equiv.ofBijective f h₁, Equiv.ofBijective g h₂, Equiv.ext (congrFun he)⟩ + +open scoped Classical in +/-- One vertex per active station, and one internal edge per source-side bit. -/ +abbrev diagram : Diagram F x y where + V := R.V + E := R.E + table := R.table + src := R.wiring.choose + dst := R.wiring.choose_spec.choose + +open scoped Classical in +/-- Builds `S.Seating r R.diagram where vertex` with the specified `vertex`, `pin`, `cover`, +`sample`. -/ +def seat : S.Seating r R.diagram where + vertex := Function.Embedding.subtype _ + pin := R.pin + cover q := ⟨⟨_, R.active_at q⟩, rfl⟩ + sample v t := ((S.pattern r v.val).sample_ordered v.val.2.2 t).symm + vacant v hv := (R.vacant v (fun h => hv ⟨⟨v, h⟩, rfl⟩)).2 + +open scoped Classical in +theorem seat_ends (e : R.diagram.End) : R.seat.ends e = R.dest e := by + obtain ⟨⟨v, i⟩, rfl⟩ := R.diagram.portEquiv.surjective e + rw [Seating.ends_at] + change R.attach ⟨v, i⟩ = R.dest ((R.diagram.src.sumCongr R.diagram.dst) ((Equiv.sigmaSumDistrib _ + _) ⟨v, i⟩)) + rw [show R.diagram.src.sumCongr R.diagram.dst = R.ends from R.wiring.choose_spec.choose_spec, + R.ends_spec, Equiv.symm_apply_apply] + +open scoped Classical in +/-- Builds `S.Presentation r R.diagram where toSeating` with the specified `toSeating`, +`proper`, `internal`, `input`. -/ +def pres : S.Presentation r R.diagram where + toSeating := R.seat + proper := R.proper + internal e := by rw [R.seat_ends, R.seat_ends]; exact R.paired_mate e + input i := by rw [R.seat_ends]; exact (R.boundary (.inl i)).property + output i := by rw [R.seat_ends]; exact (R.boundary (.inr i)).property + +open scoped Classical in +theorem vertex_eq (v : R.V) : R.pres.vertex v = v.val := rfl + +open scoped Classical in +theorem boundary_eq : R.pres.boundary = R.boundary := by + apply Equiv.ext + intro i + apply Subtype.ext + cases i <;> exact R.seat_ends _ + +open scoped Classical in +theorem directed : R.pres.Directed := by + intro i + change S.direction r (R.seat.ends i).1 = i.isRight + rw [R.seat_ends, R.dest_side] + +end Realization +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- # Reading a local term from a single-station record and its host graph -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry + +open Assembly Coloring Packing Rounds +variable {F : Type} [Field F] + +open scoped Classical in +/-- A realization together with the graph and counters in its header. -/ +structure Board (D : Assembly.Template F) (r : D.format.obj) (x y : Wire) (u : ℕ) where + /-- The `Board` component of type `D.scheme.Realization r.1 x y`. -/ + realization : D.scheme.Realization r.1 x y + single : D.scheme.k = 0 + /-- The type of vertices. -/ + V : Type + [finite : Fintype V] + /-- Embeds the coordinates as `V ↪ B D.scheme.m`. -/ + host : V ↪ B D.scheme.m + /-- The neighbors of each vertex of type `V → Finset V`. -/ + adj : V → Finset V + /-- The `Board` component of type `V → Prop`. -/ + frozen : V → Prop + /-- The identification of the indices of type `V → V → B D.scheme.d`. -/ + index : V → V → B D.scheme.d + /-- The owner assigned to each element of type `realization.V → V`. -/ + owner : realization.V → V + owns : ∀ v, host (owner v) = v.val.1 + sym : ∀ v w, w ∈ adj v → v ∈ adj w + exterior : ∀ p : D.scheme.exposed r.1, D.frozen r p.val.1.1.1 = true + linked : ∀ (v w : realization.V) i j, D.scheme.peer r.1 (v.val, i) = some (w.val, j) → + 0 < D.scheme.width r.1 (v.val, i) → + owner w ∈ adj (owner v) ∧ ¬(frozen (owner v) ∧ frozen (owner w)) ∧ + D.scheme.width r.1 (v.val, i) = u + neighbor : ∀ (v w : realization.V) i j, D.scheme.peer r.1 (v.val, i) = some (w.val, j) → + (D.scheme.pattern r.1 v.val).peer 0 i = some (index (owner v) (owner w), 0, j) + live : ∀ i, D.live r i = true ↔ i ∈ Set.range host + fixed : ∀ v, D.frozen r (host v) = true ↔ frozen v + closed : ∀ v j, D.nav r (host v) j ∈ Set.range host + reciprocal : Fmt.Reciprocal (.vec D.scheme.h (.addr D.scheme.ℓ)) r.1 + edge : ∀ v w, w ∈ adj v ↔ ∃ j, D.nav r (host v) j = host w ∧ (D.flags r (host v) j).1 = true + core : ∀ v w, (w ∈ adj v ∧ ¬frozen v ∧ ¬frozen w) ↔ + ∃ j, D.nav r (host v) j = host w ∧ (D.flags r (host v) j).2 = true + load : ∀ i j, D.load (D.counter r i j) = if realization.active (i, j, 0) then + ((∑ t, D.scheme.width r.1 ((i, j, 0), t) : ℕ) : ℝ) + u else 0 + +attribute [instance] Board.finite + +namespace Board +variable {D : Assembly.Template F} {r : D.format.obj} {x y : Wire} {u : ℕ} (A : Board D r x y u) + +local notation "G" => A.realization.diagram +local notation "P" => A.realization.pres + +open scoped Classical in +/-- The value specified by `(A.owner v, (cellIndex _).symm v.val.2.1)`. -/ +abbrev place (v : (G).V) := (A.owner v, (cellIndex _).symm v.val.2.1) +open scoped Classical in +/-- Selects the elements of `(A.adj v)` satisfying `(fun w => ¬A.frozen v ∧ ¬A.frozen w)`. -/ +abbrev mobileAdj (v : A.V) := (A.adj v).filter (fun w => ¬A.frozen v ∧ ¬A.frozen w) + +include A in +open scoped Classical in +private theorem lane (i : B D.scheme.k) : i = 0 := by + apply Fin.ext + have hi : i.val < 1 := lt_of_lt_of_le i.isLt (by simp [A.single]) + simpa using Nat.lt_one_iff.mp hi + +open scoped Classical in +theorem vertex (v : (G).V) : + (P).vertex v = (A.host (A.place v).1, cellIndex _ (A.place v).2, 0) := by + simp only [A.owns, Equiv.apply_symm_apply] + exact Prod.ext rfl (Prod.ext rfl (A.lane _)) + +open scoped Classical in +theorem link (e : (G).E) : + let v := (G).source e + let w := (G).target e + A.owner w ∈ A.adj (A.owner v) ∧ ¬(A.frozen (A.owner v) ∧ A.frozen (A.owner w)) ∧ + D.scheme.width r.1 ((P).wirePin e false).1 = u ∧ (A.place v).2 = (A.place w).2 := by + let v := (G).source e + let w := (G).target e + let a := (P).wirePin e false + let b := (P).wirePin e true + have ha : a.1 = (v.val, a.1.2) := Prod.ext ((P).wirePin_at e false) rfl + have hb : b.1 = (w.val, b.1.2) := Prod.ext ((P).wirePin_at e true) rfl + have hp : D.scheme.peer r.1 a.1 = some b.1 := (P).wirePin_peer e false + rw [ha, hb] at hp + have ht : 0 < D.scheme.width r.1 a.1 := Nat.zero_lt_of_lt a.2.isLt + obtain ⟨had, hfr, hwd⟩ := A.linked v w _ _ hp (ha ▸ ht) + refine ⟨had, hfr, (congrArg (D.scheme.width r.1) ha).trans hwd, ?_⟩ + unfold Scheme.peer at hp + obtain ⟨_, _, he⟩ := Option.map_eq_some_iff.mp hp + exact congrArg (fun t : D.scheme.Span => (cellIndex _).symm t.1.2.1) he + +open scoped Classical in +theorem uniform : (P).Uniform u := fun e => (A.link e).2.2.1 + +open scoped Classical in +/-- Builds `Freeze G where frozen v` with the specified `frozen`, `exterior`, `have`, `rw`. -/ +abbrev freeze : Freeze G where + frozen v := A.frozen (A.owner v) + exterior i := by + apply (A.fixed _).mp + rw [A.owns] + have he : ((P).boundary i).val.1.1 = (P).vertex (portEnd G i) := by + cases i <;> exact (P).end_station _ + have hh := A.exterior ((P).boundary i) + rw [he] at hh + exact hh + separate e := (A.link e).2.1 + +open scoped Classical in +/-- Builds `A.freeze.Frame A.V D.scheme.h where place` with the specified `place`, `frozen`, +`keep`, `ns`. -/ +abbrev frame : A.freeze.Frame A.V D.scheme.h where + place := A.place + frozen := A.frozen + keep _ := Iff.rfl + N := A.adj + C := A.mobileAdj + ns := A.sym + cs v w h := by + obtain ⟨he, h₁, h₂⟩ := Finset.mem_filter.mp h + exact Finset.mem_filter.mpr ⟨A.sym v w he, h₂, h₁⟩ + sub _ := Finset.filter_subset _ _ + group e := (A.link e).2.2.2 + edge e := Finset.mem_filter.mpr ⟨(A.link e.val).1, e.property⟩ + full e := (A.link e).1 + +omit [Field F] in +open scoped Classical in +theorem divisible {X : Diagram F x y} (q : Packets X u) (v w : X.V) : + u ∣ Fintype.card {e // X.source e = v ∧ X.target e = w} := by + let J := {i // q.src i = v ∧ q.dst i = w} + let eq : {e // X.source e = v ∧ X.target e = w} ≃ J × Fin u := + (q.bits.subtypeEquiv (q := fun z => q.src z.1 = v ∧ q.dst z.1 = w) + (by intro z; rw [q.left, q.right])).trans + { toFun := fun z => (⟨z.val.1, z.property⟩, z.val.2) + invFun := fun z => ⟨(z.1.val, z.2), z.1.property⟩ + left_inv _ := rfl, right_inv _ := rfl } + rw [Fintype.card_congr eq, Fintype.card_prod, Fintype.card_fin] + exact dvd_mul_left _ _ + +open scoped Classical in +/-- Each active station is charged its arity plus one packet. -/ +abbrev term : LocalTerm F x y D.scheme.h u where + V := A.V + diagram := G + freeze := A.freeze + frame := A.frame + one v w he := by + apply (P).vertex.injective + change A.place v = A.place w at he + rw [A.vertex, A.vertex, he] + width := divisible ((P).packets A.realization.directed A.uniform) + charge v := (G).arity v + (u : ℝ) + cover _ := le_add_of_nonneg_right (Nat.cast_nonneg _) + floor _ := le_add_of_nonneg_left (Nat.cast_nonneg _) + +open scoped Classical in +theorem arity (v : (G).V) : (G).arity v = ∑ t, D.scheme.width r.1 (v.val, t) := by + have hc := Fintype.card_congr ((P).pin v) + simp only [Diagram.Port, Scheme.LocalPin, Fintype.card_sigma, Fintype.card_sum, card_slots, + Fintype.card_fin] at hc + exact hc + +open scoped Classical in +theorem amount (i j) : D.load (D.counter r i j) = + ∑ v : (G).V, if v.val.1 = i ∧ v.val.2.1 = j then A.term.charge v else 0 := by + have he (v : (G).V) (h : v.val.1 = i ∧ v.val.2.1 = j) : v.val = (i, j, 0) := + Prod.ext h.1 (Prod.ext h.2 (A.lane _)) + rw [A.load] + by_cases h : A.realization.active (i, j, 0) + · let v : (G).V := ⟨(i, j, 0), h⟩ + rw [ite_eq_left h, Finset.sum_eq_single v] + · rw [ite_eq_left ⟨rfl, rfl⟩] + exact congrArg (fun n : ℕ => (n : ℝ) + u) (A.arity v).symm + · intro w _ hw + exact ite_eq_right (fun hh => hw (Subtype.ext (he w hh))) + · simp + · rw [ite_eq_right h] + symm + refine Finset.sum_eq_zero fun w _ => ite_eq_right fun hh => ?_ + exact h (he w hh ▸ w.property) + +open scoped Classical in +/-- The original record displays the local term with precisely the given boundary and host. -/ +def shows : D.Shows r A.term where + pres := P + host := A.host + vertex := A.vertex + directed := A.realization.directed + uniform := A.uniform + index := A.index + neighbor := A.neighbor + live := A.live + frozen := A.fixed + closed := A.closed + reciprocal := A.reciprocal + edge := A.edge + core v w := Finset.mem_filter.trans (A.core v w) + charge _ := rfl + amount := A.amount + +open scoped Classical in +theorem boundary : A.shows.pres.boundary = A.realization.boundary := A.realization.boundary_eq + +end Board +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +/- +# Matching an ordered exterior to a geometric blueprint + +Count exterior positions at each pair of a station and span. When different +exterior vertices have different owners, the original list indices give +distinct offsets. Equality of the counts then exhausts the entire boundary. +-/ + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Coloring Packing + +variable {F : Type} {x y : Wire} + +open scoped Classical in +theorem Assembly.Scheme.Presentation.extWidth_ne_zero [Field F] {S : Scheme F} {G : Diagram F x y} + {r : S.format.obj} (p : S.Presentation r G) (hd : p.Directed) (v : S.Vtx) (b : Bool) : + S.extWidth ((r v.1).2 v.2.1) (some v.2.2) b ≠ 0 ↔ + ∃ i, (p.boundary i).val.1.1 = v ∧ i.isRight = b := by + have dir (i : slots x ⊕ slots y) : S.direction r (p.boundary i).val.1 = i.isRight := by + cases i <;> exact hd _ + change Fintype.card {j : S.LocalPin r v // (S.pattern r v).peer v.2.2 j.1 = none ∧ + (S.pattern r v).direction v.2.2 j.1 = b} ≠ 0 ↔ _ + rw [← Nat.pos_iff_ne_zero, Fintype.card_pos_iff] + constructor + · rintro ⟨⟨j, hp, hb⟩⟩ + obtain ⟨i, he⟩ := p.boundary.surjective ⟨S.port r v j, by simp [Scheme.peer, Scheme.port, hp]⟩ + refine ⟨i, ?_, ?_⟩ + · rw [he]; rfl + · rw [← dir, he]; exact hb + · rintro ⟨i, rfl, hb⟩ + let j := (p.boundary i).val + refine ⟨⟨⟨j.1.2, j.2⟩, ?_, (dir i).trans hb⟩⟩ + simpa [Scheme.peer] using (p.boundary i).property + +namespace Sphere.Geometry +variable (G : Diagram F x y) (S : Scheme F) (r : S.format.obj) + (owner : G.V → S.Vtx) (outer : Bool ↪ B S.e) + +open scoped Classical in +/-- The widths used in the `Geometry` construction. -/ +def Widths := ∀ v s, S.borderLen r (v, s) = ∑ i : G.V, if owner i = v then + if s = outer false then (G.extLeft i).length else + if s = outer true then (G.extRight i).length else 0 else 0 + +open scoped Classical in +/-- The condition `∀ i j, owner (portEnd G i) = owner (portEnd G j) → portEnd G i = portEnd G j` +on the specified data. -/ +def Separate := ∀ i j, owner (portEnd G i) = owner (portEnd G j) → portEnd G i = portEnd G j + +open scoped Classical in +/-- Computes the len by the application `cond b (G.extRight v).length (G.extLeft v).length`. -/ +def len (v : G.V) (b : Bool) := cond b (G.extRight v).length (G.extLeft v).length +open scoped Classical in +/-- Indexes the addr by the coordinates of `Σ v : G.V, Σ b : Bool, Fin (len G v b)`. -/ +abbrev Addr := Σ v : G.V, Σ b : Bool, Fin (len G v b) + +open scoped Classical in +/-- In the case `⟨v, false, i⟩`, this construction gives `.inl ((G.extLeft v).get i)`. -/ +def wire : Addr G → slots x ⊕ slots y + | ⟨v, false, i⟩ => .inl ((G.extLeft v).get i) + | ⟨v, true, i⟩ => .inr ((G.extRight v).get i) + +open scoped Classical in +theorem wire_end (a : Addr G) : portEnd G (wire G a) = a.1 := by + rcases a with ⟨v, _|_, i⟩ + · exact (G.mem_extLeft v _).mp (List.get_mem _ i) + · exact (G.mem_extRight v _).mp (List.get_mem _ i) + +open scoped Classical in +theorem wire_side (a : Addr G) : (wire G a).isRight = a.2.1 := by + rcases a with ⟨v, _|_, i⟩ <;> rfl + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def wires : Addr G ≃ slots x ⊕ slots y := Equiv.ofBijective (wire G) (by + constructor + · rintro ⟨u, b, i⟩ ⟨v, c, j⟩ he + have ha : u = v := (wire_end G _).symm.trans ((congrArg (portEnd G) he).trans (wire_end G _)) + have hb : b = c := (wire_side G _).symm.trans ((congrArg Sum.isRight he).trans (wire_side G _)) + subst v + subst c + have h : i = j := by + cases b + · exact (G.extLeft_nodup u).get_inj_iff.mp (Sum.inl.inj he) + · exact (G.extRight_nodup u).get_inj_iff.mp (Sum.inr.inj he) + rw [h] + · rintro (i|j) + · obtain ⟨k, hk⟩ := List.get_of_mem ((G.mem_extLeft _ i).mpr rfl) + exact ⟨⟨_, false, k⟩, congrArg Sum.inl hk⟩ + · obtain ⟨k, hk⟩ := List.get_of_mem ((G.mem_extRight _ j).mpr rfl) + exact ⟨⟨_, true, k⟩, congrArg Sum.inr hk⟩) + +open scoped Classical in +/-- The value specified by `(owner a.1, outer a.2.1)`. -/ +def dest (a : Addr G) : S.Span := (owner a.1, outer a.2.1) + +open scoped Classical in +private theorem width_sum (v : S.Vtx) (s : B S.e) : + (∑ a : Addr G, if dest G S owner outer a = (v, s) then 1 else 0) = + ∑ i : G.V, if owner i = v then if s = outer false then (G.extLeft i).length else + if s = outer true then (G.extRight i).length else 0 else 0 := by + rw [Fintype.sum_sigma] + apply Finset.sum_congr rfl + intro i _ + rw [Fintype.sum_sigma, Fintype.sum_bool] + have he : outer false ≠ outer true := outer.injective.ne Bool.false_ne_true + by_cases hv : owner i = v + · by_cases hl : s = outer false + · simp [dest, hv, hl, he.symm]; rfl + · by_cases hr : s = outer true + · simp [dest, hv, hr, he, he.symm]; rfl + · simp [dest, hv, hl, hr, Ne.symm hl, Ne.symm hr] + · simp [dest, hv] + +open scoped Classical in +/-- The place of type `S.exposed r` for the given inputs. -/ +def place (t : S.Span) (i : Fin (S.borderLen r t)) : S.exposed r := + have hp : S.peer r t = none := by + by_contra h + simpa [Scheme.borderLen, h] using i.isLt + ⟨⟨t, ⟨i.val, by simpa [Scheme.borderLen, hp] using i.isLt⟩⟩, hp⟩ + +open scoped Classical in +theorem border_sum (t : S.Span) : + S.borderLen r t = ∑ a : S.exposed r, if a.val.1 = t then 1 else 0 := by + let f (i : Fin (S.borderLen r t)) : {a : S.exposed r // a.val.1 = t} := ⟨place S r t i, rfl⟩ + have hf : Function.Bijective f := by + constructor + · exact fun _ _ h => Fin.ext (congrArg (fun a => a.val.val.2.val) h) + · rintro ⟨⟨⟨t', j⟩, hp⟩, h⟩ + change t' = t at h + subst t' + change S.peer r t = none at hp + exact ⟨⟨j.val, by simpa only [Scheme.borderLen, ite_eq_left hp] using j.isLt⟩, rfl⟩ + rw [← Fintype.card_fin (S.borderLen r t), Fintype.card_congr (Equiv.ofBijective f hf), + Fintype.card_subtype, Finset.card_filter] + +variable {G S r owner outer} (hw : Widths G S r owner outer) (hi : Separate G S owner) + +open scoped Classical in +/-- The image of type `S.exposed r` for the given inputs. -/ +def image (a : Addr G) : S.exposed r := place S r (dest G S owner outer a) ⟨a.2.2.val, by + refine lt_of_lt_of_le a.2.2.isLt ?_ + change len G a.1 a.2.1 ≤ S.borderLen r (owner a.1, outer a.2.1) + rw [hw] + refine le_trans ?_ (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ a.1)) + cases a.2.1 <;> simp [len, outer.injective.eq_iff]⟩ + +include hi in +open scoped Classical in +theorem bijective : Function.Bijective (image hw) := by + apply (Fintype.bijective_iff_injective_and_card _).mpr + constructor + · intro a b he + have ht : dest G S owner outer a = dest G S owner outer b := + congrArg (fun z : S.exposed r => z.val.1) he + have hv : a.1 = b.1 := by + rw [← wire_end G a, ← wire_end G b] + apply hi + simpa only [wire_end] using (Prod.mk.inj ht).1 + have hb := outer.injective (Prod.mk.inj ht).2 + have hj : a.2.2.val = b.2.2.val := congrArg (fun z : S.exposed r => z.val.2.val) he + rcases a with ⟨u, p, i⟩ + rcases b with ⟨v, q, j⟩ + change u = v at hv + change p = q at hb + subst v + subst q + rw [show i = j from Fin.ext hj] + · have count (T : Type) [Fintype T] (f : T → S.Span) : + (∑ t, ∑ a, if f a = t then 1 else 0) = Fintype.card T := by + rw [Finset.sum_comm] + simp + rw [← count _ (dest G S owner outer), ← count _ (fun a : S.exposed r => a.val.1)] + apply Finset.sum_congr rfl + rintro ⟨v, s⟩ _ + rw [width_sum, ← hw, border_sum] + +open scoped Classical in +/-- Reindexes `slots x ⊕ slots y` and `S.exposed r` by an equivalence. -/ +def boundary : slots x ⊕ slots y ≃ S.exposed r := + (wires G).symm.trans (Equiv.ofBijective (image hw) (bijective hw hi)) + +open scoped Classical in +private theorem boundary_wire (a : Addr G) : boundary hw hi (wire G a) = image hw a := by + change image hw ((wires G).symm (wires G a)) = _ + rw [Equiv.symm_apply_apply] + +open scoped Classical in +theorem boundary_span (i : slots x ⊕ slots y) : + (boundary hw hi i).val.1 = (owner (portEnd G i), outer i.isRight) := by + obtain ⟨a, rfl⟩ := (wires G).surjective i + change (boundary hw hi (wire G a)).val.1 = (owner (portEnd G (wire G a)), + outer (wire G a).isRight) + rw [boundary_wire, wire_end, wire_side] + rfl + +open scoped Classical in +theorem boundary_left (v : G.V) (j : Fin (G.extLeft v).length) : + let a := (boundary hw hi (.inl ((G.extLeft v).get j))).val + a.1 = (owner v, outer false) ∧ a.2.val = j.val := by + rw [show Sum.inl ((G.extLeft v).get j) = wire G ⟨v, false, j⟩ from rfl, boundary_wire] + exact ⟨rfl, rfl⟩ + +open scoped Classical in +theorem boundary_right (v : G.V) (j : Fin (G.extRight v).length) : + let a := (boundary hw hi (.inr ((G.extRight v).get j))).val + a.1 = (owner v, outer true) ∧ a.2.val = j.val := by + rw [show Sum.inr ((G.extRight v).get j) = wire G ⟨v, true, j⟩ from rfl, boundary_wire] + exact ⟨rfl, rfl⟩ + +open scoped Classical in +theorem widths_of_retains [Field F] {T : Scheme F} {a : T.format.obj} {p : T.Presentation a G} + {H : Diagram F x y} {q : S.Presentation r H} {z : ℕ} {child : B S.m ≃ B T.m × B z} + (f : Payload.Retains p q child outer) + (he : ∀ i, (q.boundary i).val.1.1 = owner (portEnd G i)) : Widths G S r owner outer := by + intro v s + rw [border_sum, ← width_sum G S owner outer, ← Equiv.sum_comp ((wires G).trans q.boundary)] + apply Finset.sum_congr rfl + intro a _ + have hl : (q.boundary (wire G a)).val.1 = dest G S owner outer a := by + obtain ⟨w, c⟩ := f (wire G a) + exact Prod.ext ((he _).trans (congrArg owner (wire_end G a))) + ((congrArg Prod.snd (c.owns _ rfl)).trans (congrArg outer (wire_side G a))) + change (if (q.boundary (wire G a)).val.1 = (v, s) then 1 else 0) = _ + rw [hl] + +end Sphere.Geometry +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Decoding.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Decoding.lean new file mode 100644 index 0000000000..9bc7d26cf4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Decoding.lean @@ -0,0 +1,229 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Exterior +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Origin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Verifier.Caps + +/-! +# Reading the geometry from a finite tag and length words + +Each output width digit uses the tag and just one digit of each length. +Thus the cost is linear in the length of a word for fixed tag, station and +span alphabets. The digit convention is arbitrary. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry.Blueprint +open Coloring + +variable {T X Y : Type} {w d e k : ℕ} + +open scoped Classical in +/-- The distinguished word holds the common internal width. -/ +abbrev LengthKey (k : ℕ) := Option (B k × Bool) +open scoped Classical in +/-- Indexes the read in by the coordinates of `X ⊕ (LengthKey k × Fin b)`. -/ +abbrev ReadIn (X : Type) (k b : ℕ) := X ⊕ (LengthKey k × Fin b) +open scoped Classical in +/-- Indexes the read out by the coordinates of `Y ⊕ (B w × B e × Fin b)`. -/ +abbrev ReadOut (Y : Type) (w e b : ℕ) := Y ⊕ (B w × B e × Fin b) + +open scoped Classical in +/-- In the case `none`, this construction gives `u`. -/ +def lengths (u : ℕ) (size : Option (B k) → Bool → ℕ) : LengthKey k → ℕ + | none => u + | some (v, s) => size (some v) s + +variable (emb : T ↪ (X → Bool)) (blue : T → Blueprint w d e k) + (info : T → Y → Bool) (outer : Bool ↪ B e) (b : ℕ) (bit : ℕ → Fin b → Bool) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def readIn (t : T) (u : ℕ) (size : Option (B k) → Bool → ℕ) : ReadIn X k b → Bool := + Sum.elim (emb t) (fun h => bit (lengths u size h.1) h.2) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def readOut (t : T) (u : ℕ) (size : Option (B k) → Bool → ℕ) : ReadOut Y w e b → Bool := + Sum.elim (info t) (fun h => bit ((blue t h.1).width u outer size h.2.1) h.2.2) + +open scoped Classical in +private def sliceCode : T × (LengthKey k → Bool) ↪ (X ⊕ LengthKey k → Bool) where + toFun p := Sum.elim (emb p.1) p.2 + inj' _ _ h := Prod.ext (emb.injective (funext fun i => congrFun h (.inl i))) + (funext fun i => congrFun h (.inr i)) + +open scoped Classical in +private def digit (v : B w) (s : B e) (j : Fin b) (t : T × (LengthKey k → Bool)) := + let o := blue t.1 v + let side h := o.name.elim (bit 0 j) fun i => t.2 (some (i, h)) + if (o.peer s).isSome then t.2 none else + if s = outer false then side false else if s = outer true then side true else bit 0 j + +open scoped Classical in +private theorem digit_eq (v : B w) (s : B e) (j : Fin b) + (t : T) (u : ℕ) (size : Option (B k) → Bool → ℕ) (hzero : ∀ h, size none h = 0) : + digit blue outer b bit v s j (t, fun l => bit (lengths u size l) j) = + bit ((blue t v).width u outer size s) j := by + unfold digit Outline.width + dsimp only + split_ifs <;> cases hn : (blue t v).name <;> simp [lengths, hzero] + +variable [Fintype T] [Fintype X] + +open scoped Classical in +/-- Uniform work bound for one metadata bit or width digit. -/ +def readCost (T X : Type) [Fintype T] [Fintype X] (k : ℕ) := + (3 * Fintype.card X + 2) * Fintype.card T + 1 + + ((3 * Fintype.card (X ⊕ LengthKey k) + 2) * Fintype.card (T × (LengthKey k → Bool)) + 1) + +open scoped Classical in +theorem read_bit (i : ReadOut Y w e b) : + ∃ g : BitFormula (ReadIn X k b), g.cost ≤ readCost T X k ∧ + ∀ t u (size : Option (B k) → Bool → ℕ), (∀ h, size none h = 0) → + g.eval (readIn emb b bit t u size) = readOut blue info outer b bit t u size i := by + rcases i with i|⟨v, s, j⟩ + · obtain ⟨g, hg, hc⟩ := finite_formula emb (fun t => info t i) + refine ⟨g.rename Sum.inl, ?_, ?_⟩ + · rw [BitFormula.cost_rename] + exact hc.trans (Nat.le_add_right _ _) + · intro t u size _ + rw [BitFormula.eval_rename] + exact hg t + · obtain ⟨g, hg, hc⟩ := finite_formula (sliceCode emb) (digit blue outer b bit v s j) + let f : X ⊕ LengthKey k → ReadIn X k b := Sum.map id (fun l => (l, j)) + refine ⟨g.rename f, ?_, ?_⟩ + · rw [BitFormula.cost_rename] + exact hc.trans (Nat.le_add_left _ _) + · intro t u size hz + have hf : readIn emb b bit t u size ∘ f = + sliceCode emb (t, fun l => bit (lengths u size l) j) := by + funext x + cases x <;> rfl + rw [BitFormula.eval_rename, hf, hg] + exact digit_eq blue outer b bit v s j t u size hz + +open scoped Classical in +/-- The same family of formulas works for all tags and all length words. -/ +theorem read_net [Fintype Y] : + ∃ g : ReadOut Y w e b → BitFormula (ReadIn X k b), + (∀ t u size, (∀ h, size none h = 0) → ∀ i, + (g i).eval (readIn emb b bit t u size) = readOut blue info outer b bit t u size i) ∧ + (∀ i, (g i).cost ≤ readCost T X k) ∧ + (∑ i, (g i).cost) ≤ readCost T X k * (Fintype.card Y + 2 ^ w * 2 ^ e) * (b + 1) := by + choose g hg he using read_bit emb blue info outer b bit + refine ⟨g, fun t u size h i => he i t u size h, hg, ?_⟩ + calc + _ ≤ ∑ _ : ReadOut Y w e b, readCost T X k := Finset.sum_le_sum fun i _ => hg i + _ = readCost T X k * (Fintype.card Y + 2 ^ w * 2 ^ e * b) := by + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, Nat.cast_id, ReadOut, + Fintype.card_sum, Fintype.card_prod, B, Fintype.card_fin] + ring + _ ≤ _ := by + rw [mul_assoc (readCost T X k)] + gcongr + rw [add_mul] + exact add_le_add (Nat.le_mul_of_pos_right _ (by omega)) (Nat.mul_le_mul_left _ (by omega)) + +open scoped Classical in +/-- One-hot peer indices and holder locations accompany the role and direction bits. -/ +abbrev Flags (w d e k : ℕ) := + B w ⊕ (B w × Option (B k)) ⊕ (B w × B e) ⊕ + (B w × B e × Option (B d × B 0 × B e)) ⊕ (B k × B w) + +open scoped Classical in +/-- In the case `.inl i`, this construction gives `(a i).live`. -/ +def flags (a : Blueprint w d e k) : Flags w d e k → Bool + | .inl i => (a i).live + | .inr (.inl (i, h)) => decide ((a i).name = h) + | .inr (.inr (.inl (i, j))) => (a i).direction j + | .inr (.inr (.inr (.inl (i, j, h)))) => decide ((a i).peer j = h) + | .inr (.inr (.inr (.inr (h, i)))) => decide (a.find h = i) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry.Blueprint +end + +/- +# Concentration for every accepted geometric proposal + +The bounds apply even if a proposal fails the coefficient check. +Only the short quotas and the unchanged exterior wires enter. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly Rounds +variable {F K : Type} [Field F] [Finite K] {S : Scheme F} + {d ℓ M r t q D k n u j z T R g σ ν : ℕ} {x y : Wire} {W : ℝ} {P : Input F x y S.h D T R g W} + (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + {old : P.V ↪ B S.m} {data : U.rows.obj} {status : (Children.Header S.m d).obj} + {nav : B S.m → B d → B S.m} (A : Children.Shows P.adj old (nav, status)) + (hdata : ∀ i, (data i).1 = nav i) (hg : g ≤ D ^ k) (c : U.selectors.obj) + {x₀ : S.format.obj} (p : S.Presentation x₀ P.diagram) (hd : p.Directed) + {loc : P.Occupied ↪ B S.m × B S.h} {part : Fin ν → P.Occupied → P.Occupied} + {E H : P.Occupied → ℕ} (a : P.Occupied → U.Tag S g σ ν) + +local notation "Y" => U.advance data status c +local notation "C" => Input.terminalExponent g σ +local notation "plan" => U.complete S loc (fun i => Prod.fst (a i)) +local notation "net" => U.graph A hdata hg c + +open scoped Classical in +private def coverage {I V : Type} [Fintype V] + (rows : U.template.format.obj) (G : U.Graph S rows V) + (b : U.Matrix S) (hv : U.Valid S x₀ rows b) (loc : I ↪ B S.m × B S.h) + (hc : ∀ v : U.Actors S, (U.localAt S b v).live = true → ((U.split v.1).1, + v.2.1) ∈ Set.range loc) + (hf : ∀ v, U.template.frozen rows v = U.fixedChild (U.split v).2) : + Geometry.Support I (fun i => b (loc i).1 (loc i).2) (fun _ => U.fixedChild) + (U.admitted S x₀ rows b hv G p hd).term := by + have eq : U.board S x₀ rows b hv G (U.materialize S x₀ rows b hv p hd) (fun _ => Iff.rfl) = + U.admitted S x₀ rows b hv G p hd := rfl + let sup := U.boardSupport S x₀ rows b hv G (U.materialize S x₀ rows b hv p hd) (fun _ => Iff.rfl) + loc hc U.fixedChild (fun v _ => hf v.1) + exact Eq.mp (congrArg (fun E : Geometry.Board (U.revised S) (U.overlay S x₀ rows b) x y u => + Geometry.Support I (fun i => b (loc i).1 (loc i).2) (fun _ => U.fixedChild) E.term) eq) sup + +open scoped Classical in +private theorem admitted_concentrated {V : Type} [Fintype V] + (rows : U.template.format.obj) (G : U.Graph S rows V) + (pass : U.passes S loc part E H (T / u) x₀ rows a) + (fixed : ∀ v, U.template.frozen rows v = U.fixedChild (U.split v).2) + (cells : Fintype.card V ≤ D ^ C * Fintype.card P.V) + (full : ∀ v, (G.adj v).card ≤ D ^ C) + (core : ∀ v, ((G.adj v).filter (fun w => ¬G.frozen v ∧ ¬G.frozen w)).card ≤ 3) + (he : (∑ v, (E v : ℝ)) * T ≤ 2 * SphereScale.budget g * ((ν : ℝ) + 1) * W) + (hh : (∑ v, (H v : ℝ)) * D * T ≤ 3 * (D : ℝ) ^ 5 * W) : + Concentrated P (U.admitted S x₀ rows plan pass.1 G p hd).term (Geometry.overhead g C) n σ := by + have support := coverage U p hd rows G plan pass.1 loc (U.complete_support S loc _) fixed + rw [funext (U.complete_here S loc (fun i => (a i).1))] at support + have hD : 0 < D := lt_of_lt_of_le (by decide) U.large + have hv : (Fintype.card P.Occupied : ℝ) * D * T ≤ W := by + simpa only [Input.Occupied, Fintype.card_coe] using P.occupied + have totals := Geometry.totals (fun v => (a v).1) (fun _ + => U.fixedChild) hD hv he hh pass.2.1 pass.2.2 + exact support.concentrated (P := P) («C» := Input.terminalExponent g σ) (U.admitted_fibers S x₀ + rows plan pass.1 G p hd) hD cells core full totals pass.2.2 + +open scoped Classical in +theorem approved_term (ok : U.passes S loc part E H (T / u) x₀ (U.advance data status c) a) + (hk : k = Layout.Sharing.allocation g σ) + (he : (∑ v, (E v : ℝ)) * T ≤ 2 * SphereScale.budget g * ((ν : ℝ) + 1) * W) + (hh : (∑ v, (H v : ℝ)) * D * T ≤ 3 * (D : ℝ) ^ 5 * W) : + Concentrated P (U.admitted S x₀ Y plan ok.1 net p hd).term (Geometry.overhead g C) n σ := by + exact admitted_concentrated U p hd a Y net ok (fun _ => rfl) + (U.graph_cells A hg hk) (U.graph_fullDegree A hdata hg c hk) (U.graph_coreDegree A hdata hg c) + he hh + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Exterior.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Exterior.lean new file mode 100644 index 0000000000..0d407b4a99 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Exterior.lean @@ -0,0 +1,990 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Correct +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary + +/-! # Locating an exterior collector by its original station name -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place) + +variable {F K N X Z J I : Type} [Field F] {x y : Wire} {S : Scheme F} + {m d h ℓ M r t q D k n u j z T R g r₀ t₀ : ℕ} {W : ℝ} + {P : Input F x y S.h D T R g W} {Y : Alphabet P.Occupied} + {s : Stage F r₀ t₀ Z P.Occupied P.grid.Seam X} + {β : P.Occupied ⊕ ℕ → K} {R₀ : Reference J I (B S.k) P.Occupied P.grid.Seam Z X} + {G : Record F r₀ t₀ P.Occupied P.grid.Seam K (B S.k)} {tape : S.format.obj} + +open scoped Classical in +/-- The named keeps of type `Prop` for the given inputs. -/ +def NamedKeeps (Q : Key.Source Y x y s) (left : Order.Exterior Q.left) (right : Order.Exterior + Q.right) + (hm : Matches R₀.world β s G) (p : S.Presentation tape P.diagram) + (loc : P.Occupied ↪ B S.m × B S.h) : Prop := + ∀ e : slots x ⊕ slots y, let v := Packing.portEnd P.diagram e + ∃ i : Place s.scene.cell, loc i.1 = ((p.vertex v).1, (p.vertex v).2.1) ∧ + left.ports i = P.diagram.extLeft v ∧ right.ports i = P.diagram.extRight v ∧ + (hm.row i).name = some (p.vertex v).2.2 ∧ + ∀ l, l.1 = i.1 → (hm.row l).name = (hm.row i).name → l = i + +open scoped Classical in +theorem NamedKeeps.keeps {Q : Key.Source Y x y s} {left : Order.Exterior Q.left} {right : + Order.Exterior Q.right} + {hm : Matches R₀.world β s G} {p : S.Presentation tape P.diagram} + {loc : P.Occupied ↪ B S.m × B S.h} (hp : NamedKeeps Q left right hm p loc) : + Keeps Q left right p loc := by + intro e + obtain ⟨i, hl, h₁, h₂, _⟩ := hp e + exact ⟨i, hl, h₁, h₂⟩ + +namespace Printer +variable (U : Printer F K N m d h ℓ M r t q D k n u j z) + +open scoped Classical in +/-- Transforms the indexed data by `(U.menu x).elim [] (fun c => c.tile.rows.map Entry.name)`. -/ +def namesAt (x : B ℓ) := + (U.menu x).elim [] (fun c => c.tile.rows.map Entry.name) + +open scoped Classical in +/-- Returns `h.choose.val` when `h : ∃ i : Fin names.length, names.get i = some name` holds, and +`0` otherwise. -/ +def namedIndex (names : List (Option N)) (name : N) : ℕ := + if h : ∃ i : Fin names.length, names.get i = some name then h.choose.val else 0 + +open scoped Classical in +/-- The quantity computed by `U.slot (.inl (.inl (true, ⟨namedIndex (U.namesAt x) name % D ^ k, +Nat.mod_lt _ U.positive⟩)))`. -/ +def childFor (x : B ℓ) (name : N) : B U.childBits := + U.slot (.inl (.inl (true, ⟨namedIndex (U.namesAt x) name % D ^ k, Nat.mod_lt _ U.positive⟩))) + +end Printer +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Decoding proposed geometry and terminal coefficients + +Each address carries the original label, the printer window and one +bounded outline. Port widths and peer addresses read only the original +exterior lengths and the outline. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Coloring Assembly + +variable {F : Type} [One F] {d e k : ℕ} (a : Outline d e k) (u : ℕ) + (outer : Bool ↪ B e) (size : Option (B k) → Bool → ℕ) (x : Pattern F d 0 e) + +open scoped Classical in +/-- Builds `Pattern F d 0 e where width _` with the specified `width`, `peer`, `direction`, +`value`. -/ +def Outline.revise : Pattern F d 0 e where + width _ := a.width u outer size + peer _ := a.peer + direction _ := a.direction + value _ v := if h : a.live = true ∧ a.width u outer size = x.width 0 then + x.value 0 (fun j i => v j (Fin.cast (congrFun h.2.symm j) i)) else 1 + +open scoped Classical in +theorem Outline.revise_eq (h : a.Matches u outer size x) (hu : a.live = false → ∀ t, x.value 0 t + = 1) : + a.revise u outer size x = x := by + obtain ⟨w, o, p, v⟩ := x + have he (f : B 0 → B e → ℕ) : f = fun _ => f 0 := + funext fun i => congrArg f (Fin.eq_zero i) + have ew : w = fun _ => a.width u outer size := (he w).trans (congrArg (fun g _ => g) h.width.symm) + have ed : o = fun _ => a.direction := funext fun i + => by rw [Fin.eq_zero i]; exact h.direction.symm + have ep : p = fun _ => a.peer := funext fun i => by rw [Fin.eq_zero i]; exact h.peer.symm + subst w o p + unfold revise + congr 1 + funext i t + rw [Fin.eq_zero i] + by_cases hl : a.live = true + · simp [hl] + · simpa [hl] using (hu (Bool.eq_false_iff.mpr hl) t).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly Geometry + +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + +open scoped Classical in +/-- The value specified by `Geometry.Outline (Children.degree d U.childBits) U.spanBits S.k`. -/ +abbrev Outline := Geometry.Outline (Children.degree d U.childBits) U.spanBits S.k +open scoped Classical in +/-- The indexing data represented by `B U.childBits → U.Outline S`. -/ +abbrev Blueprint := B U.childBits → U.Outline S +open scoped Classical in +/-- Computes the plan bits by the application `indexBits (U.Outline S)`. -/ +abbrev planBits := indexBits (U.Outline S) +open scoped Classical in +/-- The quantity computed by `S.ℓ + (U.labelBits + U.planBits S)`. -/ +abbrev addressBits := S.ℓ + (U.labelBits + U.planBits S) +open scoped Classical in +/-- Indexes the ticket by the coordinates of `B S.ℓ × B U.labelBits × U.Outline S`. -/ +abbrev Ticket := B S.ℓ × B U.labelBits × U.Outline S + +open scoped Classical in +/-- Embeds `U.Ticket S` into `B (U.addressBits S)`. -/ +def ticket : U.Ticket S ↪ B (U.addressBits S) := + ((Function.Embedding.refl _).prodMap + (((Function.Embedding.refl _).prodMap (indexCode (U.Outline S))).trans + (Match.rowIndex _ _).symm.toEmbedding)).trans (Match.rowIndex _ _).symm.toEmbedding + +open scoped Classical in +/-- Computes the decode ticket by the application `i.2.2.revise u U.outer (S.extWidth i.1) +(U.engine.decode i.2.1)`. -/ +def decodeTicket (i : U.Ticket S) := + i.2.2.revise u U.outer (S.extWidth i.1) (U.engine.decode i.2.1) + +open scoped Classical in +/-- Returns `(∑ s, i.2.2.width u U.outer (S.extWidth i.1) s : ℕ) + (u : ℝ)` when `i.2.2.live` +holds, and `0` otherwise. -/ +def chargeTicket (i : U.Ticket S) : ℝ := + if i.2.2.live then (∑ s, i.2.2.width u U.outer (S.extWidth i.1) s : ℕ) + (u : ℝ) else 0 + +open scoped Classical in +/-- Builds `Assembly.Template F where scheme` with the specified `scheme`, `decode`, `count`, +`load`. -/ +abbrev revised : Assembly.Template F where + scheme := {U.engine.scheme with + ℓ := U.addressBits S + decode := Function.extend (U.ticket S) (U.decodeTicket S) (fun _ => Star.vacant)} + count := U.addressBits S + load := Function.extend (U.ticket S) (U.chargeTicket S) (fun _ => 0) + park _ := 0 + past _ := 0 + order := Equiv.refl _ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # The child carrying each individual exterior wire -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer + +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Node Sharing) + +variable {F K N X Z : Type} [Field F] [Finite K] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} (U : Printer F K N m d h ℓ M r t q D k n u j z) + (G : (Key.share s Q).Geo P k) {a : Atlas P.Occupied P.grid.Seam m d h} (π : Palette a w q) + (old : P.V ↪ B m) (data : U.rows.obj) (status : (Children.Header m d).obj) + +namespace Physical +variable {U G π old data status} (B : U.Physical G π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "S" => Key.share s Q +local notation "H" => G.layout U.dyadic U.large p j +local notation "V" => Node (Sharing.Position S) (Sharing.radius k * n) +variable (hw : open scoped Classical in + ∀ i, Diagram.padWidth u (((Key.share s Q).backdrop.emitted p j).width i) / u ≤ U.cap) + +open scoped Classical in +theorem boundary_child (e : slots x ⊕ slots y) (i : Layout.Place s.scene.cell) + (he : Sum.elim Q.left Q.right e = i) : + (U.split ((B.shows p hw).pres.boundary e).val.1.1.1).2 = + U.slot (.inl (.inl (true, Fin.castLE (G.count i.1) i.2))) := by + let v : V := .inl (.inl (.inl i)) + have hf : G.frozen i := by + rw [← he]; cases e with + | inl e => exact G.left e + | inr e => exact G.right e + have hp : Packing.portEnd (B.term p).diagram e = v := by + refine (((H).routed (B.rules.script p j) u).drawing.exterior e).trans ?_ + rw [show v = .inl (.inl (.inl (Sum.elim Q.left Q.right e))) by rw [he]] + cases e <;> rfl + rw [Payload.owner, hp] + change (U.split (B.vertex p v).1).2 = _ + rw [(B.address p v).1] + change U.slot (.inl (.inl (decide (G.frozen i), _))) = _ + rw [decide_eq_true hf] + +end Physical +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # The host certificate is shared by all geometry choices -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (y : U.template.format.obj) + +local notation "L" => U.template + +open scoped Classical in +/-- The data for the graph construction, including `host`, `adj`, `frozen`, `index`, `sym`. -/ +structure Graph (V : Type) where + /-- Embeds the coordinates as `V ↪ B (L).scheme.m`. -/ + host : V ↪ B (L).scheme.m + /-- The neighbors of each vertex of type `V → Finset V`. -/ + adj : V → Finset V + /-- The `Graph` component of type `V → Prop`. -/ + frozen : V → Prop + /-- The identification of the indices of type `V → V → B (L).scheme.d`. -/ + index : V → V → B (L).scheme.d + sym : ∀ v w, w ∈ adj v → v ∈ adj w + separate : ∀ v w, w ∈ adj v → ¬(frozen v ∧ frozen w) + live : ∀ i, (L).live y i = true ↔ i ∈ Set.range host + fixed : ∀ v, (L).frozen y (host v) = true ↔ frozen v + closed : ∀ v j, (L).nav y (host v) j ∈ Set.range host + reciprocal : Fmt.Reciprocal (.vec (L).scheme.h (.addr (L).scheme.ℓ)) y.1 + edge : ∀ v w, w ∈ adj v ↔ ∃ j, (L).nav y (host v) j = host w ∧ ((L).flags y (host v) j).1 = true + core : ∀ v w, (w ∈ adj v ∧ ¬frozen v ∧ ¬frozen w) ↔ + ∃ j, (L).nav y (host v) j = host w ∧ ((L).flags y (host v) j).2 = true + indexed : ∀ v w j, (L).nav y (host v) j = host w → ((L).flags y (host v) j).1 = true → j + = index v w + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- +# A profile-independent trie host + +The trie uses only the parent contacts, the steering columns and +the common slot shapes. An empty seam list with one placeholder +at each parent suffices to apply the geometric routing lemmas. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Rounds +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Sharing Trie) +variable {F K : Type} [Field F] [Finite K] {S : Scheme F} + {d ℓ M r t q D k n u j z T R g : ℕ} {x y : Wire} {W : ℝ} {P : Input F x y S.h D T R g W} + (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + {old : P.V ↪ B S.m} {data : U.rows.obj} {status : (Children.Header S.m d).obj} + {nav : B S.m → B d → B S.m} (A : Children.Shows P.adj old (nav, status)) + (hdata : ∀ i, (data i).1 = nav i) (hg : g ≤ D ^ k) (c : U.selectors.obj) + +open scoped Classical in +/-- Builds `Alphabet Empty where state _` with the specified `state`, `width`, `code`. -/ +def blank : Alphabet Empty where + state _ := Unit + width _ := 0 + code i := i.elim + +open scoped Classical in +/-- Evaluates `⟨[], [⟨0, 0, 0, (), fun _ _ _ => 1⟩]⟩` at the input `_`. -/ +def places (M : ℕ) (P : Input F x y S.h D T R g W) : + P.V → Surface.Cell F (M * 0) (M * 0) Unit Empty Unit := + fun _ => ⟨[], [⟨0, 0, 0, (), fun _ _ _ => 1⟩]⟩ + +open scoped Classical in +/-- Builds `Sharing (places M P) x y blank where src i` with the specified `src`, `dst`, +`meets`, `seen`. -/ +def site (M : ℕ) (P : Input F x y S.h D T R g W) : Sharing (places M P) x y blank where + src i := i.elim + dst i := i.elim + meets _ i := i.1.elim + seen _ := ∅ + reads _ := ∅ + within _ := Finset.Subset.rfl + present i := i.elim + connected i := i.elim + left i := ⟨(P.place (Packing.portEnd P.diagram (.inl i))).1, ⟨0, by simp [places]⟩⟩ + right i := ⟨(P.place (Packing.portEnd P.diagram (.inr i))).1, ⟨0, by simp [places]⟩⟩ + param _ _ _ := () + locality _ _ _ _ _ _ _ _ _ _ := rfl + +open scoped Classical in +/-- Builds `(site M P).Geo P k where site` with the specified `site`, `near`, `count`, `chunks`. -/ +def layout : (site M P).Geo P k where + site := ⟨fun i => (i, 0), fun _ _ e => congrArg Prod.fst e⟩ + near i := i.elim + count _ := U.positive + chunks := U.chunks + degree := hg + frozen _ := True + left _ := trivial + right _ := trivial + steer := A.steer U.degree + +open scoped Classical in +/-- The value specified by `(Printer.layout U A hg).tree U.dyadic U.large`. -/ +abbrev graphTree : Trie (Bench P.V M D k) (Sharing.radius k * n) := + (Printer.layout U A hg).tree U.dyadic U.large + +local notation "net" => Children.graph U.slot U.dyadic U.large U.chunks U.degree (nav, status) +local notation "tree" => graphTree U A hg +local notation "N" => U.template +local notation "rows" => U.advance data status c +local notation "H" => Host P.V M D k n + +include hdata in +open scoped Classical in +theorem header : + ((N).nav rows, fun i => (((N).live rows i, (N).frozen rows i), (N).flags rows i)) = net := by + change Children.graph _ _ _ _ _ (Children.tape (U.update data status c)) = _ + have eq : Children.tape (U.update data status c) = (nav, status) := Prod.ext (funext hdata) rfl + rw [eq] + +local notation "L" => (layout U A hg) +local notation "addr" => Children.host old U.slot +local notation "idx" => Children.idx old U.slot nav + +include A hg in +omit [Finite K] in +open scoped Classical in +theorem indexed (v w : H) (i : B (Children.degree d U.childBits)) + (he : (net).1 (addr v) i = addr w) (hf : (((net).2 (addr v)).2 i).1 = true) : + i = idx v w := by + have h : Children.used U.slot U.dyadic U.large U.chunks U.degree (u:=(nav, status)) (addr v) i + := by + by_contra hn + rw [(Children.spare U.slot U.dyadic U.large U.chunks U.degree _ _ hn).2] at hf + cases hf + obtain ⟨z, hz, rfl⟩ := (Children.columns U.slot U.dyadic U.large U.chunks U.degree L A rfl v + i).mp h + have h' := (Children.used_column U.slot U.dyadic U.large U.chunks U.degree L A rfl v z hz).1 + exact congrArg (idx v) ((addr).injective (h'.symm.trans he)) + +open scoped Classical in +/-- Builds `Graph S U rows H where host` with the specified `host`, `adj`, `frozen`, `index`. -/ +def graph : Graph S U rows H where + host := addr + adj := (tree).adj + frozen := (tree).fixed + index := idx + sym _ _ := (tree).adj_symm + separate _ _ := (tree).separate + live i := by + have he := Children.live U.slot U.dyadic U.large U.chunks U.degree A i + rw [← header U hdata c] at he + exact he + fixed v := by + have he := Children.fixed_slot U.slot U.dyadic U.large U.chunks U.degree + (old:=old) (u:=(nav, status)) v + rw [← header U hdata c] at he + exact he.trans (Children.fixed_iff U.dyadic U.large L v) + closed v j := by + have he := Children.closed U.slot U.dyadic U.large U.chunks U.degree L A rfl v j + rw [← header U hdata c] at he + exact he + reciprocal := by + have he := Children.reciprocal U.slot U.dyadic U.large U.chunks U.degree L A rfl + rw [← header U hdata c] at he + exact he + edge v w := by + have he := Children.edge U.slot U.dyadic U.large U.chunks U.degree L A rfl v w + rw [← header U hdata c] at he + exact he + core v w := by + have he := Children.core U.slot U.dyadic U.large U.chunks U.degree L A rfl v w + rw [← header U hdata c] at he + exact Finset.mem_filter.symm.trans he + indexed v w i := by + have he := indexed U A hg v w i + rw [← header U hdata c] at he + exact he + +variable {σ : ℕ} (hk : k = Sharing.allocation g σ) + +include U A hg hk in +omit [Finite K] in +open scoped Classical in +theorem graph_cells : Fintype.card H ≤ D ^ (Input.terminalExponent g σ) * Fintype.card P.V := by + have hi := (L).host_count U.large + have hb := (Layout.Fanout.host_bound (c:=Sharing.radius k) (ℓ:=σ) + (C:=Input.terminalExponent g σ) U.dyadic U.large (by rw [hk]; rfl)).1 + unfold Host + rw [Layout.node_count] + exact (Nat.mul_le_mul_left _ hi).trans (by rw [← mul_assoc]; exact Nat.mul_le_mul_right _ hb) + +local notation "Q" => (graph U A hdata hg c) + +include hk in +open scoped Classical in +theorem graph_fullDegree (v : H) : ((Q).adj v).card ≤ D ^ (Input.terminalExponent g σ) := + ((tree).degree v).trans (Layout.Fanout.host_bound (ℓ:=σ) U.dyadic U.large (by rw [hk]; rfl)).2.2 + +open scoped Classical in +theorem graph_coreDegree (v : H) : + (((Q).adj v).filter (fun w => ¬(Q).frozen v ∧ ¬(Q).frozen w)).card ≤ 3 := + (tree).core_degree v + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Reading the index of a unique name in a local record -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Surface Surface.Local Coloring + +variable {F K N X Z J I V E : Type} {r t : ℕ} {β : V ⊕ ℕ → K} + {R₀ : Reference J I N V E Z X} {G : Record F r t V E K N} + {s : Stage F r t Z V E X} (hm : Matches R₀.world β s G) + +open scoped Classical in +theorem named_index (i : Layout.Place s.scene.cell) (n : N) (hn : (hm.row i).name = some n) + (hu : ∀ l, l.1 = i.1 → (hm.row l).name = (hm.row i).name → l = i) : + namedIndex ((G.rows i.1).map Entry.name) n = i.2.val := by + let names := (G.rows i.1).map Entry.name + have len : names.length = (s.scene.cell i.1).stations.length := + (List.length_map ..).trans (hm.rows i.1).length_eq.symm + have he (j : Fin names.length) : names.get j = (hm.row ⟨i.1, Fin.cast len j⟩).name := by + simp only [names, List.get_eq_getElem, List.getElem_map, Matches.row, Fin.val_cast] + have hex : ∃ j : Fin names.length, names.get j = some n := by + exact ⟨Fin.cast len.symm i.2, (he _).trans hn⟩ + change namedIndex names n = _ + rw [namedIndex, dite_eq_left hex] + exact congrArg (fun l : Layout.Place s.scene.cell => l.2.val) + (hu ⟨i.1, Fin.cast len hex.choose⟩ rfl ((he _).symm.trans (hex.choose_spec.trans hn.symm))) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Recording a short blueprint alongside each printed label -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + +open scoped Classical in +/-- The indexing data represented by `B S.m → B S.h → U.Blueprint S`. -/ +abbrev Matrix := B S.m → B S.h → U.Blueprint S +open scoped Classical in +/-- Uses `U.template.scheme.Vtx` as the representation. -/ +abbrev Actors := U.template.scheme.Vtx + +open scoped Classical in +/-- Computes the local at by the application `A (U.split v.1).1 v.2.1 (U.split v.1).2`. -/ +def localAt (A : U.Matrix S) (v : U.Actors S) := A (U.split v.1).1 v.2.1 (U.split v.1).2 +open scoped Classical in +/-- The value specified by `(x (U.split v.1).1).2 v.2.1`. -/ +def originalAt (x : S.format.obj) (v : U.Actors S) := (x (U.split v.1).1).2 v.2.1 +open scoped Classical in +/-- The value specified by `(y.1 v.1).2 v.2.1`. -/ +def printedAt (y : U.template.format.obj) (v : U.Actors S) := (y.1 v.1).2 v.2.1 + +open scoped Classical in +/-- Tests whether `∃ b, S.extWidth x (some i) b ≠ 0` holds. -/ +def held (x : B S.ℓ) (i : B S.k) : Bool := + decide (∃ b, S.extWidth x (some i) b ≠ 0) + +open scoped Classical in +/-- Returns `some h.choose` when `h : ∃ i, held S x i = true ∧ U.childFor data i = child` holds, +and `none` otherwise. -/ +def nameOf (x : B S.ℓ) (data : B ℓ) (child : B U.childBits) : Option (B S.k) := + if h : ∃ i, held S x i = true ∧ U.childFor data i = child then some h.choose else none + +open scoped Classical in +/-- The value specified by `((Surface.Local.Design.number U.window).symm ((Match.rowIndex +U.window.width U.childBits) v).1 0 0).1`. -/ +def centerLabel (v : B U.labelBits) := + ((Surface.Local.Design.number U.window).symm ((Match.rowIndex U.window.width U.childBits) v).1 0 + 0).1 + +open scoped Classical in +/-- Computes the original by the application `Geometry.Outline.read (U.read y).isSome (U.nameOf +S x (U.centerLabel S y) ((Match.rowIndex _ _) y).2) (U.engine.decode y)`. -/ +def original (x : B S.ℓ) (y : B U.labelBits) : U.Outline S := + Geometry.Outline.read (U.read y).isSome + (U.nameOf S x (U.centerLabel S y) ((Match.rowIndex _ _) y).2) (U.engine.decode y) + +open scoped Classical in +/-- The value specified by `(U.split.symm (i, c), t, 0)`. -/ +def centerAt (i : B S.m) (t : B S.h) (c : B U.childBits) : U.Actors S := + (U.split.symm (i, c), t, 0) + +variable (x : S.format.obj) (y : U.template.format.obj) + +open scoped Classical in +/-- Evaluates `U.original S ((x i).2 t) (U.printedAt S y (U.centerAt S i t c))` at the input `i +t c`. -/ +def canonical : U.Matrix S := + fun i t c => U.original S ((x i).2 t) (U.printedAt S y (U.centerAt S i t c)) + +open scoped Classical in +/-- The value specified by `(U.originalAt S x v, U.printedAt S y v, U.localAt S A v)`. -/ +def atTicket (A : U.Matrix S) (v : U.Actors S) : U.Ticket S := + (U.originalAt S x v, U.printedAt S y v, U.localAt S A v) + +open scoped Classical in +/-- The overlay of type `(U.revised S).format.obj`, constructed using `U.ticket S (U.atTicket S +x y A (i, j, 0))`. -/ +def overlay (A : U.Matrix S) : (U.revised S).format.obj := + let label i j := U.ticket S (U.atTicket S x y A (i, j, 0)) + (fun i => ((y.1 i).1, label i), fun i => ((y.2 i).1, (y.2 i).2.1, label i)) + +variable (A : U.Matrix S) (v : U.Actors S) + +open scoped Classical in +theorem pattern_overlay : + (U.revised S).scheme.pattern (U.overlay S x y A).1 v = U.decodeTicket S (U.atTicket S x y A v) + := + (U.ticket S).injective.extend_apply (U.decodeTicket S) (fun _ + => Star.vacant) (U.atTicket S x y A v) + +open scoped Classical in +theorem load_overlay : + (U.revised S).load ((U.revised S).counter (U.overlay S x y A) v.1 v.2.1) = + U.chargeTicket S (U.atTicket S x y A v) := + (U.ticket S).injective.extend_apply (U.chargeTicket S) (fun _ => 0) (U.atTicket S x y A v) + +open scoped Classical in +theorem local_center (i t c) : U.localAt S A (U.centerAt S i t c) = A i t c := by + simp only [localAt, centerAt, Equiv.apply_symm_apply] + +open scoped Classical in +theorem original_center (i t c) : U.originalAt S x (U.centerAt S i t c) = (x i).2 t := by + simp only [originalAt, centerAt, Equiv.apply_symm_apply] + +open scoped Classical in +theorem local_canonical : + U.localAt S (U.canonical S x y) v = U.original S (U.originalAt S x v) (U.printedAt S y v) := by + simp only [localAt, canonical, originalAt, printedAt, centerAt, Prod.mk.eta, + Equiv.symm_apply_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Changing the label alphabet preserves equal patterns and their ordered contraction -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Coloring Assembly + +variable {F : Type} [Field F] {m h k d e : ℕ} + +open scoped Classical in +private abbrev Vertex (m h k : ℕ) := B m × B h × B k +open scoped Classical in +private abbrev PinFromBoardEval (P : Vertex m h k → Pattern F d k e) := + Σ t : Vertex m h k × B e, Fin ((P t.1).width t.1.2.2 t.2) + +open scoped Classical in +/-- Spell the contraction in terms of the decoded patterns, ignoring the label alphabet. -/ +private def contraction {I : Type} (P : Vertex m h k → Pattern F d k e) + (nav : B m → B d → B m) (bd : I → PinFromBoardEval P) (input : I → Bool) : F := + let peer (t : Vertex m h k × B e) := ((P t.1).peer t.1.2.2 t.2).map + fun z => ((nav t.1.1 z.1, t.1.2.1, z.2.1), z.2.2) + ∑ a : PinFromBoardEval P → Bool, if (∀ i, a (bd i) = input i) ∧ + (∀ t s : PinFromBoardEval P, peer t.1 = some s.1 ∧ t.2.val = s.2.val → a t = a s) + then ∏ v, (P v).value v.2.2 (fun i j => a ⟨(v, i), j⟩) else 0 + +open scoped Classical in +private theorem presented {x y : Wire} {S : Scheme F} {r : S.format.obj} + {G : Diagram F x y} (p : S.Presentation r G) (a : Val x) (b : Val y) : + G.eval a b = contraction (S.pattern r) (fun i => (r i).1) + (fun i => (p.boundary i).val) (Sum.elim (bits x a) (bits y b)) := by + rw [← p.eval] + have hc (z : S.Pin r → Bool) : + (∀ t : S.exposed r, z t.val = p.exterior a b t) ↔ + ∀ i, z (p.boundary i).val = Sum.elim (bits x a) (bits y b) i := by + constructor + · intro h i + exact (h _).trans (p.exterior_boundary a b i) + · intro h q + obtain ⟨i, rfl⟩ := p.boundary.surjective q + exact (h i).trans (p.exterior_boundary a b i).symm + simp only [Scheme.eval, Scheme.Agrees, hc, contraction, Scheme.Joins, Scheme.peer, + Scheme.table, Scheme.port, Function.comp_apply] + apply Finset.sum_congr rfl + intro z _ + congr + +open scoped Classical in +private theorem invariant {I : Type} {P Q : Vertex m h k → Pattern F d k e} + (nav : B m → B d → B m) (f : I → PinFromBoardEval P) (g : I → PinFromBoardEval Q) (input : I → + Bool) + (hp : P = Q) (hs : ∀ i, (f i).1 = (g i).1) (hi : ∀ i, (f i).2.val = (g i).2.val) : + contraction P nav f input = contraction Q nav g input := by + subst Q + have he : f = g := by + funext i + refine Sigma.ext (hs i) ((Fin.heq_ext_iff ?_).mpr (hi i)) + rw [hs i] + rw [he] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) (A : U.Matrix S) + {a b : Wire} {G G' : Diagram F a b} + +theorem eval_overlay (p : U.template.scheme.Presentation y.1 G) + (p' : (U.revised S).scheme.Presentation (U.overlay S x y A).1 G') + (hp : ∀ v, U.template.scheme.pattern y.1 v = + (U.revised S).scheme.pattern (U.overlay S x y A).1 v) + (hs : ∀ i, (p.boundary i).val.1 = (p'.boundary i).val.1) + (hi : ∀ i, (p.boundary i).val.2.val = (p'.boundary i).val.2.val) : + G.eval = G'.eval := by + funext c d + rw [Geometry.presented p, Geometry.presented p'] + exact Geometry.invariant _ _ _ _ (funext hp) hs hi + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Matching outlines recover the original tables without changing a coefficient -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly + +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) + +open scoped Classical in +theorem pattern_canonical (v : U.Actors S) + (h : (U.localAt S (U.canonical S x y) v).Matches u U.outer (S.extWidth (U.originalAt S x v)) + (U.engine.decode (U.printedAt S y v))) : + U.template.scheme.pattern y.1 v = + (U.revised S).scheme.pattern (U.overlay S x y (U.canonical S x y)).1 v := by + rw [U.pattern_overlay] + symm + apply Geometry.Outline.revise_eq _ _ _ _ _ h + intro hh + rw [U.local_canonical] at hh + have he : U.read (U.printedAt S y v) = none := by + cases hp : U.read (U.printedAt S y v) <;> simp [original, Geometry.Outline.read, hp] at hh ⊢ + have hd : U.engine.decode (U.printedAt S y v) = Star.vacant := by simp [engine, he] + rw [hd] + exact fun _ => rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Distinct exterior holders have distinct child addresses -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Signal +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place Sharing item) + +variable {F K X Z J I : Type} [Field F] [Finite K] + {x y : Wire} {S : Scheme F} {d ℓ M r t q D k n u j z : ℕ} + {T b c g w σ r₀ t₀ : ℕ} {W : ℝ} {P : Input F x y S.h D T (c * b) g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} {left : Order.Exterior Q.left} {right : Order.Exterior Q.right} + {U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z} + {a : Atlas P.Occupied P.grid.Seam S.m d S.h} {π : Palette a w q} + {β : P.Occupied ⊕ ℕ → K} {R₀ : Reference J I (B S.k) P.Occupied P.grid.Seam Z X} + {G : Record F (M * r) (M * t) P.Occupied P.grid.Seam K (B S.k)} + {hm : Matches R₀.world β s G} {index : ∀ v, Y.state v ↪ ℕ} {size : P.Occupied → ℕ} + {ext : P.Occupied → Option (B S.k) → Bool → ℕ} {old : P.V ↪ B S.m} + {data : U.rows.obj} {status : (Children.Header S.m d).obj} + (H : U.Signal Q left right a π β R₀ G hm index size ext old data status) + +open SphereScale (Scales depth) + +variable {tape : S.format.obj} {pres : S.Presentation tape P.diagram} + +omit [Finite K] in +include H in +open scoped Classical in +theorem injection (keeps : NamedKeeps Q left right hm pres a.coord) (hd : pres.Directed) + (count : ∀ i, (s.scene.cell i).stations.length ≤ D ^ k) (v : B S.m) (w : B S.h) : + Set.InjOn (U.childFor ((data v).2 w)) {i | held S ((tape v).2 w) i = true} := by + have witness (i) (hi : held S ((tape v).2 w) i = true) : + ∃ l : Place s.scene.cell, a.coord l.1 = (v, w) ∧ (hm.row l).name = some i ∧ + U.childFor ((data v).2 w) i = U.slot (.inl (.inl (true, Fin.castLE (count l.1) l.2))) := by + obtain ⟨b, hb⟩ := of_decide_eq_true hi + obtain ⟨e, he, _⟩ := (pres.extWidth_ne_zero hd (v, w, i) b).mp hb + obtain ⟨l, hc, _, _, hn, hu⟩ := keeps e + rw [Payload.owner] at he + rw [he] at hc hn + refine ⟨l, hc, hn, ?_⟩ + have hs := eq_of_heq (H.read (a.coord l.1)) + rw [Atlas.fill_at, hc] at hs + have hx : namedIndex (U.namesAt ((data v).2 w)) i = l.2.val := by + rw [namesAt, hs, Option.elim_some] + exact named_index hm l i hn hu + unfold childFor + exact congrArg (fun j => U.slot (.inl (.inl (true, j)))) + (Fin.ext (by simp only [Fin.val_castLE, hx, + Nat.mod_eq_of_lt (l.2.isLt.trans_le (count l.1))])) + intro i hi j hj he + obtain ⟨⟨p, x⟩, hp, hx, h⟩ := witness i hi + obtain ⟨⟨l, y⟩, hl, hy, h'⟩ := witness j hj + have eq : p = l := a.coord.injective (hp.trans hl.symm) + subst l + have eq := U.slot.injective (h.symm.trans (he.trans h')) + have hu : x = y := Fin.castLE_injective (count p) (Prod.mk.inj (Sum.inl.inj (Sum.inl.inj eq))).2 + subst y + exact Option.some.inj (hx.symm.trans hy) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Signal +end + +/- +# Checks using bounded local data + +A register names each old exterior holder exactly once. Reciprocal +contacts use only short neighbor indices and one bit per reverse index. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Coloring Assembly + +variable {d e k w : ℕ} +open scoped Classical in +/-- The data for the register construction, including `live`, `vacant`, `cover`, `named`, +`outer`. -/ +structure Blueprint.Register (a : Blueprint w d e k) (outer : Bool ↪ B e) + (eligible : B k → Bool) (live fixed : B w → Bool) : Prop where + live : ∀ i, (a i).live = true → live i = true + vacant : ∀ i, (a i).live = false → a i = Outline.empty + cover : ∀ j, eligible j = true → ∃! i, (a i).name = some j + named : ∀ i j, (a i).name = some j → eligible j = true ∧ fixed i = true ∧ (a i).live = true + outer : ∀ i, (a i).name.isSome → ∀ b, (a i).peer (outer b) = none ∧ (a i).direction (outer b) = b + +open scoped Classical in +/-- The contact of type `Prop` for the given inputs. -/ +def Outline.Contact (a b : Outline d e k) (j : B d) (flag : Bool) (reverse : B d → Bool) : Prop := + ∀ i l, a.peer i = some (j, 0, l) → flag = true ∧ a.live = true ∧ b.live = true ∧ + a.direction i ≠ b.direction l ∧ ∃ t, reverse t = true ∧ b.peer l = some (t, 0, i) + +open scoped Classical in +/-- Returns `h.choose` when `h : ∃ i, (a i).name = some name` holds, and `0` otherwise. -/ +def Blueprint.find (a : Blueprint w d e k) (name : B k) : B w := + if h : ∃ i, (a i).name = some name then h.choose else 0 + +open scoped Classical in +theorem Blueprint.Register.find {a : Blueprint w d e k} {outer elig live fixed} + (h : a.Register outer elig live fixed) {j i} (hi : (a i).name = some j) : a.find j = i := by + obtain ⟨w, _, hu⟩ := h.cover j (h.named i j hi).1 + have he : ∃ i, (a i).name = some j := ⟨i, hi⟩ + rw [Blueprint.find, dite_eq_left he] + exact (hu _ he.choose_spec).trans (hu _ hi).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) (A : U.Matrix S) + +open scoped Classical in +/-- The value specified by `U.template.live y (U.split.symm (i, c))`. -/ +def childLive (i : B S.m) (c : B U.childBits) := U.template.live y (U.split.symm (i, c)) +open scoped Classical in +/-- The value specified by `U.template.frozen y (U.split.symm (i, c))`. -/ +def childFixed (i : B S.m) (c : B U.childBits) := U.template.frozen y (U.split.symm (i, c)) + +open scoped Classical in +/-- The condition `∀ i t, Geometry.Blueprint.Register (A i t) U.outer (held S ((x i).2 t)) +(U.childLive S y i) (U.childFixed S y i)` on the specified data. -/ +def registered := ∀ i t, Geometry.Blueprint.Register (A i t) U.outer (held S ((x i).2 t)) + (U.childLive S y i) (U.childFixed S y i) + +open scoped Classical in +/-- The construction uses `U.template.nav y v i` for its intermediate `w`. -/ +def linked := ∀ v b i, + let w := U.template.nav y v i + Geometry.Outline.Contact (U.localAt S A (v, b, 0)) (U.localAt S A (w, b, 0)) i + (U.template.flags y v i).1 (fun j => decide (U.template.nav y w j = v)) + +open scoped Classical in +/-- The value specified by `U.registered S x y A ∧ U.linked S y A`. -/ +def Valid := U.registered S x y A ∧ U.linked S y A + +open scoped Classical in +/-- Computes the destination by the application `U.centerAt S v.1 v.2.1 (Geometry.Blueprint.find +(A v.1 v.2.1) v.2.2)`. -/ +def destination (v : S.Vtx) : U.Actors S := + U.centerAt S v.1 v.2.1 (Geometry.Blueprint.find (A v.1 v.2.1) v.2.2) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Reciprocal local contacts give a proper global scheme -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly + +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) (A : U.Matrix S) + +local notation "T" => Template.scheme (U.revised S) +local notation "R" => Prod.fst (U.overlay S x y A) + +open scoped Classical in +theorem width_overlay (v : U.Actors S) (i : B U.spanBits) : + (T).width R (v, i) = (U.localAt S A v).width u U.outer (S.extWidth (U.originalAt S x v)) i := by + unfold Scheme.width + rw [U.pattern_overlay] + rfl + +open scoped Classical in +theorem direction_overlay (v : U.Actors S) (i : B U.spanBits) : + (T).direction R (v, i) = (U.localAt S A v).direction i := by + unfold Scheme.direction + rw [U.pattern_overlay] + rfl + +open scoped Classical in +theorem peer_overlay (v : U.Actors S) (i : B U.spanBits) : + (T).peer R (v, i) = ((U.localAt S A v).peer i).map + (fun a => ((U.template.nav y v.1 a.1, v.2.1, a.2.1), a.2.2)) := by + unfold Scheme.peer + rw [U.pattern_overlay] + rfl + +open scoped Classical in +theorem overlay_link (hl : U.linked S y A) (v w : U.Actors S) (i l : B U.spanBits) + (he : (T).peer R (v, i) = some (w, l)) : + ∃ a, (U.localAt S A v).peer i = some (a, 0, l) ∧ + U.template.nav y v.1 a = w.1 ∧ (U.template.flags y v.1 a).1 = true ∧ + (T).peer R (w, l) = some (v, i) ∧ (T).width R (v, i) = u ∧ (T).width R (w, l) = u ∧ + (T).direction R (v, i) ≠ (T).direction R (w, l) := by + rcases v with ⟨v, b, s⟩ + have hs : s = 0 := Fin.eq_zero s + subst s + rw [U.peer_overlay] at he + obtain ⟨⟨a, c, j'⟩, hp, hw⟩ := Option.map_eq_some_iff.mp he + have hc : c = 0 := Fin.eq_zero c + subst c + obtain ⟨hww, hh⟩ := Prod.mk.inj hw + change j' = l at hh + subst l + change (U.template.nav y v a, b, 0) = w at hww + subst w + obtain ⟨hf, _, _, hd, e, he, hb⟩ := hl v b a i j' hp + refine ⟨a, hp, rfl, hf, ?_, ?_, ?_, ?_⟩ + · rw [U.peer_overlay, hb, Option.map_some] + exact congrArg (fun z => some ((z, b, 0), i)) (of_decide_eq_true he) + · exact (U.width_overlay S x y A _ i).trans (ite_eq_left (Option.isSome_iff_exists.mpr ⟨_, hp⟩)) + · exact (U.width_overlay S x y A _ j').trans (ite_eq_left (Option.isSome_iff_exists.mpr ⟨_, hb⟩)) + · rw [U.direction_overlay, U.direction_overlay] + exact hd + +open scoped Classical in +theorem overlay_proper (hl : U.linked S y A) : (T).Proper R := by + rintro ⟨v, i⟩ ⟨w, l⟩ he + obtain ⟨_, _, _, _, hr, hv, hw, hd⟩ := U.overlay_link S x y A hl v w i l he + exact ⟨hr, hv.trans hw.symm, hd⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # A valid geometry overlay displays its realized local term -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly + +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) (A : U.Matrix S) (hv : U.Valid S x y A) + +local notation "T" => Template.scheme (U.revised S) +local notation "rows" => Prod.fst (U.overlay S x y A) + +include hv in +open scoped Classical in +private theorem registered_live (v : U.Actors S) (h : (U.localAt S A v).live = true) : + U.template.live y v.1 = true := by + have hh := (hv.1 (U.split v.1).1 v.2.1).live (U.split v.1).2 h + simpa only [childLive, Prod.mk.eta, Equiv.symm_apply_apply] using hh + +include hv in +open scoped Classical in +theorem registered_exterior (p : (T).exposed rows) : + U.template.frozen y p.val.1.1.1 = true := by + rcases p with ⟨⟨⟨v, i⟩, z⟩, hp⟩ + have hm : (U.localAt S A v).peer i = none := by + exact Option.map_eq_none_iff.mp ((U.peer_overlay S x y A v i).symm.trans hp) + have hn : (U.localAt S A v).name ≠ none := by + intro he + have ht : 0 < (T).width rows (v, i) := Nat.zero_lt_of_lt z.isLt + have hh := (U.width_overlay S x y A v i) ▸ ht + unfold Geometry.Outline.width at hh + simp [hm, he, Scheme.extWidth] at hh + obtain ⟨l, hl⟩ := Option.ne_none_iff_exists'.mp hn + have hh := ((hv.1 (U.split v.1).1 v.2.1).named (U.split v.1).2 l hl).2.1 + simpa only [childFixed, Prod.mk.eta, Equiv.symm_apply_apply] using hh + +variable {V : Type} [Fintype V] (H : U.Graph S y V) {a b : Wire} + (R : (U.revised S).scheme.Realization (U.overlay S x y A).1 a b) (ha : ∀ v, R.active v + ↔ (U.localAt S A v).live = true) + +include hv ha in +omit [Fintype V] in +open scoped Classical in +theorem owner_exists (v : R.V) : ∃ w, H.host w = v.val.1 := + (H.live _).mp (U.registered_live S x y A hv _ ((ha _).mp v.property)) + +open scoped Classical in +/-- The original graph is retained, while the outline supplies the diagram and counters. -/ +abbrev board : Geometry.Board (U.revised S) (U.overlay S x y A) a b u where + realization := R + single := rfl + V := V + host := H.host + adj := H.adj + frozen := H.frozen + index := H.index + owner v := (U.owner_exists S x y A hv H R ha v).choose + owns v := (U.owner_exists S x y A hv H R ha v).choose_spec + sym := H.sym + exterior := U.registered_exterior S x y A hv + linked v w i l he _ := by + obtain ⟨c, _, hn, hf, _, hw, _⟩ := U.overlay_link S x y A hv.2 _ _ _ _ he + let ov := (U.owner_exists S x y A hv H R ha v) + let ow := (U.owner_exists S x y A hv H R ha w) + have had : ow.choose ∈ H.adj ov.choose := by + apply (H.edge _ _).mpr + rw [ov.choose_spec, ow.choose_spec] + exact ⟨c, hn, hf⟩ + exact ⟨had, H.separate _ _ had, hw⟩ + neighbor v w i l he := by + obtain ⟨c, hp, hn, hf, _⟩ := U.overlay_link S x y A hv.2 _ _ _ _ he + let ov := (U.owner_exists S x y A hv H R ha v) + let ow := (U.owner_exists S x y A hv H R ha w) + have hi : c = H.index ov.choose ow.choose := by + apply H.indexed + · rwa [ov.choose_spec, ow.choose_spec] + · rwa [ov.choose_spec] + rw [U.pattern_overlay, ← hi] + exact hp + live := H.live + fixed := H.fixed + closed := H.closed + reciprocal := H.reciprocal + edge := H.edge + core := H.core + load i l := by + rw [U.load_overlay S x y A (i, l, 0)] + simp only [ha, chargeTicket, atTicket] + exact congrArg (fun n : ℕ => if (U.localAt S A (i, l, 0)).live then (n : ℝ) + u else 0) + (Finset.sum_congr rfl fun s _ => (U.width_overlay S x y A (i, l, 0) s).symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Origin.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Origin.lean new file mode 100644 index 0000000000..1b9a650933 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Geometry/Origin.lean @@ -0,0 +1,678 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Exterior +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Proof.Initial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows + +/-! # Exterior load is invariant under relabeling the occupied fibers -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry + +open Packing Finset Rounds +variable {F : Type} {x y : Wire} (G : Diagram F x y) + +open scoped Classical in +/-- Counts the elements of `{i // portEnd G i = v}`. -/ +def extLoad (v : G.V) := Fintype.card {i // portEnd G i = v} + +open scoped Classical in +theorem extLoad_eq (v : G.V) : extLoad G v = exterior G id v := by + simp only [extLoad, exterior, Fintype.card_subtype, card_eq_sum_ones, sum_filter, + Fintype.sum_sum_type] + rfl + +open scoped Classical in +theorem extLoad_le (v : G.V) : (extLoad G v : ℝ) ≤ G.arity v := by + have h := site_arity G id v + simp only [push, id_eq, sum_ite_eq', mem_univ, ite_true] at h + rw [extLoad_eq, h] + exact le_add_of_nonneg_right (Nat.cast_nonneg _) + +open scoped Classical in +private theorem square_sum : + (∑ v, (extLoad G v : ℝ) ^ 2) = ∑ i, (extLoad G (portEnd G i) : ℝ) := by + have h (v : G.V) : (extLoad G v : ℝ) ^ 2 = + ∑ i, if portEnd G i = v then (extLoad G v : ℝ) else 0 := by + rw [← sum_filter, sum_const, nsmul_eq_mul, pow_two, extLoad, Fintype.card_subtype] + simp_rw [h] + rw [sum_comm] + simp + +variable {h D T r g : ℕ} {W : ℝ} (P : Input F x y h D T r g W) (Q : Diagram F x y) + (he : ∀ i j, portEnd Q i = portEnd Q j ↔ portEnd P.diagram i = portEnd P.diagram j) + +include he + +open scoped Classical in +private theorem load_at (i : slots x ⊕ slots y) : + extLoad Q (portEnd Q i) = extLoad P.diagram (portEnd P.diagram i) := + Fintype.card_congr (Equiv.subtypeEquivRight (fun j => he j i)) + +open scoped Classical in +theorem extLoad_max (v : Q.V) : (extLoad Q v : ℝ) ≤ 100 * D * T := by + by_cases hz : extLoad Q v = 0 + · rw [hz, Nat.cast_zero]; positivity + obtain ⟨⟨j, hj⟩⟩ := Fintype.card_pos_iff.mp (Nat.pos_of_ne_zero hz) + rw [← hj, load_at P Q he] + let i := portEnd P.diagram j + refine (extLoad_le _ i).trans (le_trans ?_ (P.mass (P.place i))) + unfold push + simpa using single_le_sum (s := univ) + (f := fun w => if P.place w = P.place i then (P.diagram.arity w : ℝ) else 0) + (fun _ _ => by positivity) (mem_univ i) + +open scoped Classical in +theorem extLoad_squares : (∑ v, (extLoad Q v : ℝ) ^ 2) ≤ W * T := by + rw [square_sum] + simp_rw [load_at P Q he] + rw [← square_sum] + exact (sum_le_sum (fun i _ => pow_le_pow_left₀ (Nat.cast_nonneg _) (extLoad_le _ i) 2)).trans + P.squares + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +/- # Charging an active board by its internal spans and its exterior bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Coloring Finset Packing + +namespace Sphere.Geometry +variable {F : Type} [Field F] {a b : Wire} {G : Diagram F a b} + {S : Scheme F} {x : S.format.obj} + +open scoped Classical in +theorem extLoad_spans (p : S.Presentation x G) (v : G.V) : + extLoad G v = ∑ i, S.borderLen x (p.vertex v, i) := by + simp_rw [border_sum] + rw [sum_comm, ← Equiv.sum_comp p.boundary] + simp only [extLoad, Fintype.card_subtype, card_eq_sum_ones, sum_filter] + apply sum_congr rfl + intro j _ + have he : (p.boundary j).val.1 = (p.vertex (portEnd G j), (p.boundary j).val.1.2) := + Prod.ext (Payload.owner p j) rfl + rw [he] + simp only [Prod.mk.injEq, p.vertex.injective.eq_iff] + by_cases h : portEnd G j = v <;> simp [h] + +end Sphere.Geometry + +namespace Sphere.Print.Printer +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) (A : U.Matrix S) (hv : U.Valid S x y A) + +local notation "T" => Template.scheme (U.revised S) +local notation "rows" => Prod.fst (U.overlay S x y A) + +open scoped Classical in +private theorem partition_width (v : U.Actors S) : + (∑ i : B U.spanBits, (T).width rows (v, i)) = + (U.localAt S A v).links * u + ∑ i : B U.spanBits, (T).borderLen rows (v, i) := by + have he (i : B U.spanBits) : (T).width rows (v, i) = + (if ((U.localAt S A v).peer i).isSome then u else 0) + (T).borderLen rows (v, i) := by + rw [Scheme.borderLen, U.peer_overlay S x y A v i, U.width_overlay S x y A v i] + cases h : (U.localAt S A v).peer i with + | none => + simp only [Geometry.Outline.width, h, Option.isSome_none, Bool.false_eq_true, + ↓reduceIte, Option.map_none, zero_add, left_eq_ite_iff] + exact fun h => (h rfl).elim + | some peer => simp [Geometry.Outline.width, h] + simp_rw [he] + rw [sum_add_distrib, ← sum_filter, sum_const, Nat.nsmul_eq_mul] + rfl + +variable {V : Type} [Fintype V] (H : U.Graph S y V) {a b : Wire} + (R : (U.revised S).scheme.Realization (U.overlay S x y A).1 a b) + (ha : ∀ v, R.active v ↔ (U.localAt S A v).live = true) +local notation "board₀" => U.board S x y A hv H R ha + +include hv H ha in +open scoped Classical in +omit [Fintype V] in +private theorem arity_partition [Finite V] (v : R.V) : + R.diagram.arity v = (U.localAt S A v.val).links * u + Geometry.extLoad R.diagram v := by + let : Fintype V := Fintype.ofFinite V + have he := (board₀).arity v + have hl := Geometry.extLoad_spans R.pres v + change R.diagram.arity v = ∑ i : B U.spanBits, (T).width rows (v.val, i) at he + change Geometry.extLoad R.diagram v = ∑ i : B U.spanBits, (T).borderLen rows (v.val, i) at hl + rw [U.partition_width S x y A, ←hl] at he + exact he + +open scoped Classical in +theorem board_charge (v : R.V) : + (board₀).term.charge v = ((U.localAt S A v.val).toll : ℝ) * u + Geometry.extLoad R.diagram v + := by + have he := U.arity_partition S x y A hv H R ha v + change (R.diagram.arity v : ℝ) + (u : ℝ) = ((U.localAt S A v.val).toll : ℝ) * u + + Geometry.extLoad R.diagram v + rw [he, Geometry.Outline.toll, ite_eq_left ((ha _).mp v.property)] + push_cast + ring + +open scoped Classical in +/-- The board support of type `Geometry.Support I (fun i => A (loc i).1 (loc i).2) (fun _ => +fixed) (board₀).term`, constructed using `(cell v, (U.split v.val.1).2)`. -/ +def boardSupport {I : Type} (loc : I ↪ B S.m × B S.h) + (occupied : ∀ v : U.Actors S, (U.localAt S A v).live = true → ((U.split v.1).1, + v.2.1) ∈ Set.range loc) + (fixed : B U.childBits → Bool) + (hf : ∀ v : U.Actors S, (U.localAt S A v).live = true → U.template.frozen y v.1 + = fixed (U.split v.1).2) : + Geometry.Support I (fun i => A (loc i).1 (loc i).2) (fun _ => fixed) (board₀).term := by + have live (v : R.V) := (ha _).mp v.property + choose cell hc using fun v : R.V => occupied v.val (live v) + let f (v : R.V) := (cell v, (U.split v.val.1).2) + have inj : Function.Injective f := by + intro v w eq + obtain ⟨h₁, h₂⟩ := Prod.mk.inj eq + have he := (hc v).symm.trans ((congrArg loc h₁).trans (hc w)) + obtain ⟨hp, hb⟩ := Prod.mk.inj he + exact Subtype.ext (Prod.ext (U.split.injective (Prod.ext hp h₂)) + (Prod.ext hb ((Fin.eq_zero _).trans (Fin.eq_zero _).symm))) + have view (v : R.V) : A (loc (f v).1).1 (loc (f v).1).2 (f v).2 = U.localAt S A v.val := by + simp only [f, hc] + rfl + refine ⟨⟨f, inj⟩, ?_, ?_, ?_⟩ + · intro v + exact (congrArg Geometry.Outline.live (view v)).trans (live v) + · intro v + change (board₀).frozen ((board₀).owner v) ↔ _ + rw [← (board₀).fixed, (board₀).owns] + change U.template.frozen y v.val.1 = true ↔ fixed (U.split v.val.1).2 = true + rw [hf _ (live v)] + · intro v + change (board₀).term.charge v = ((A (loc (f v).1).1 (loc (f v).1).2 (f v).2).toll : ℝ) * u + + Geometry.extLoad R.diagram v + rw [view] + exact U.board_charge S x y A hv H R ha v + +end Sphere.Print.Printer +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- # Each printed peer follows a flagged column of the child graph -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer + +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Node Sharing) + +variable {F K N X Z : Type} [Field F] [Finite K] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} (U : Printer F K N m d h ℓ M r t q D k n u j z) + (G : (Key.share s Q).Geo P k) {a : Atlas P.Occupied P.grid.Seam m d h} (π : Palette a w q) + (old : P.V ↪ B m) (data : U.rows.obj) (status : (Children.Header m d).obj) + +namespace Physical +variable {U G π old data status} (B : U.Physical G π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "S" => Key.share s Q +local notation "H" => G.layout U.dyadic U.large p j +local notation "V" => Node (Sharing.Position S) (Sharing.radius k * n) +local notation "A" => U.template +local notation "rows" => B.record p +local notation "node" => (B.term p) +local notation "tree" => (G.tree U.dyadic U.large) +local notation "graph" => Children.graph U.slot U.dyadic U.large U.chunks U.degree (a.graph, status) + +variable (hw : open scoped Classical in + ∀ i, Diagram.padWidth u (((Key.share s Q).backdrop.emitted p j).width i) / u ≤ U.cap) + +open scoped Classical in +theorem presentAt (v : U.engine.scheme.Vtx) : + (U.read (((rows).1 v.1).2 v.2.1)).isSome = true ↔ v ∈ Set.range (B.vertex p) := by + by_cases he : v ∈ Set.range (B.vertex p) + · obtain ⟨t, rfl⟩ := he + simp only [B.read_active, Option.isSome_some, true_iff] + exact ⟨_, rfl⟩ + · simp [B.read_inactive p v he, he] + +include hw in +open scoped Classical in +theorem flagged (v : U.engine.scheme.Vtx) (s t : Coloring.B U.spanBits) + (i : Coloring.B U.engine.d) + (h : ((A).scheme.pattern (rows).1 v).peer 0 s = some (i, 0, t)) : + ((A).flags rows v.1 i).1 = true := by + let w : U.engine.scheme.Vtx := ((A).nav rows v.1 i, v.2.1, 0) + have he : (A).scheme.peer (rows).1 (v, s) = some (w, t) := by + unfold Scheme.peer + rw [Fin.eq_zero v.2.2] + exact congrArg _ h + let frame := B.frame p hw + obtain ⟨b, l, j', hj, hx, hy⟩ := frame.peer_spec _ _ he + let x := (H).place (side ((H).pad u).route.net b l) + let y := (H).place (side ((H).pad u).route.net (!b) l) + have hv : v.1 = B.host x.1 := congrArg (fun s => s.1.1) hx + have hi : i = B.idx x.1 y.1 := by + have ht := frame.unit_local b l j' hj + have hh := congrArg (fun z : U.engine.scheme.Span => + (U.engine.scheme.pattern (rows).1 z.1).peer 0 z.2) hx + exact congrArg Prod.fst (Option.some.inj (h.symm.trans (hh.trans ht))) + have hp : y.1 ∈ (tree).adj x.1 := by + have hl := ((H).pad u).edges l + have eq (i : V) : ((H).pad u).place i = (H).place i := by cases i <;> rfl + simp only [Layout.Fanout.linked, eq] at hl + unfold x y + cases b + · exact hl.2 + · exact (tree).adj_symm hl.2 + have ht := (Children.used_column U.slot U.dyadic U.large U.chunks U.degree G B.parents B.steer _ + _ hp).2 + rw [← B.record_header p] at ht + rw [hv, hi] + exact congrArg Prod.fst ht + +end Physical +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Recovering exterior owners from a registered blueprint -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Packing Finset + +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) (A : U.Matrix S) + (ok : U.registered S x y A) {a b : Wire} {G : Diagram F a b} + (p : S.Presentation x G) (hd : p.Directed) + +open scoped Classical in +/-- Computes the holder by the application `U.destination S A (p.vertex v)`. -/ +abbrev holder (v : G.V) := U.destination S A (p.vertex v) + +include ok in +open scoped Classical in +theorem destination_name (v : S.Vtx) (hv : held S ((x v.1).2 v.2.1) v.2.2 = true) : + (U.localAt S A (U.destination S A v)).name = some v.2.2 := by + have reg := ok v.1 v.2.1 + obtain ⟨i, hi, _⟩ := reg.cover _ hv + rw [destination, local_center, reg.find hi] + exact hi + +include hd in +open scoped Classical in +private theorem eligible (i : slots a ⊕ slots b) : + let v := p.vertex (portEnd G i) + held S ((x v.1).2 v.2.1) v.2.2 = true := by + intro v + apply decide_eq_true + exact ⟨i.isRight, (p.extWidth_ne_zero hd v _).mpr ⟨i, Payload.owner p i, rfl⟩⟩ + +include ok hd in +open scoped Classical in +theorem holder_name (i : slots a ⊕ slots b) : + (U.localAt S A (U.holder S x A p (portEnd G i))).name = some (p.vertex (portEnd G i)).2.2 := + U.destination_name S x y A ok _ (eligible S x p hd i) + +open scoped Classical in +theorem holder_coords (i : G.V) : + (U.split (U.holder S x A p i).1).1 = (p.vertex i).1 ∧ + (U.holder S x A p i).2.1 = (p.vertex i).2.1 := by + constructor + · simp only [holder, destination, centerAt, Equiv.apply_symm_apply] + · rfl + +include ok hd in +open scoped Classical in +theorem holder_separate : Geometry.Separate G (U.revised S).scheme (U.holder S x A p) := by + intro i l h + have hm := U.holder_name S x y A ok p hd i + have hc := U.holder_coords S x A p (portEnd G i) + rw [h, U.holder_name S x y A ok p hd l] at hm + rw [h] at hc + obtain ⟨h₁, h₂⟩ := U.holder_coords S x A p (portEnd G l) + exact p.vertex.injective (Prod.ext (hc.1.symm.trans h₁) + (Prod.ext (hc.2.symm.trans h₂) (Option.some.inj hm.symm))) + +include ok hd in +open scoped Classical in +theorem named_holder (v : U.Actors S) {i : B S.k} (hv : (U.localAt S A v).name = some i) : + ∃ e, U.holder S x A p (portEnd G e) = v := by + let w : S.Vtx := ((U.split v.1).1, v.2.1, i) + have reg := ok (U.split v.1).1 v.2.1 + have eligible : held S ((x w.1).2 w.2.1) w.2.2 = true := (reg.named _ _ hv).1 + obtain ⟨side, hside⟩ := of_decide_eq_true eligible + obtain ⟨e, he, _⟩ := (p.extWidth_ne_zero hd w side).mp hside + rw [Payload.owner] at he + refine ⟨e, ?_⟩ + rw [holder, he, destination] + dsimp only [w] + rw [reg.find hv] + exact Prod.ext (U.split.symm_apply_apply _) (Prod.ext rfl (Fin.eq_zero _).symm) + +include ok hd in +open scoped Classical in +theorem holder_width (v : U.Actors S) (side : Bool) : + S.extWidth (U.originalAt S x v) (U.localAt S A v).name side = + ∑ i : G.V, if U.holder S x A p i = v then cond side (G.extRight i).length (G.extLeft + i).length else 0 := by + have support (i : G.V) (hi : cond side (G.extRight i).length (G.extLeft i).length ≠ 0) : + ∃ e, portEnd G e = i := by + rw [p.exterior_width hd] at hi + obtain ⟨e, he, _⟩ := (p.extWidth_ne_zero hd (p.vertex i) side).mp hi + rw [Payload.owner] at he + exact ⟨e, p.vertex.injective he⟩ + by_cases h : ∃ e, U.holder S x A p (portEnd G e) = v + · obtain ⟨e, rfl⟩ := h + rw [sum_eq_single (portEnd G e), ite_eq_left rfl, U.holder_name S x y A ok p hd, holder, + destination, original_center] + · exact (p.exterior_width hd _ side).symm + · intro i _ hi + split_ifs with he + · by_contra hn + obtain ⟨l, rfl⟩ := support i hn + exact hi (U.holder_separate S x y A ok p hd l e he) + · rfl + · simp + · have hn : (U.localAt S A v).name = none := by + cases he : (U.localAt S A v).name with + | none => rfl + | some i => exact (h (U.named_holder S x y A ok p hd v he)).elim + rw [hn] + symm + apply sum_eq_zero + intro i _ + split_ifs with he + · by_contra hi + obtain ⟨e, rfl⟩ := support i hi + exact h ⟨e, he⟩ + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # The directed diagram determined by a valid blueprint -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Packing + +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) (A : U.Matrix S) + {a b : Wire} {G : Diagram F a b} + +local notation "T" => Template.scheme (U.revised S) +local notation "tape" => Prod.fst (U.overlay S x y A) +section +variable (ok : U.registered S x y A) (p : S.Presentation x G) (hd : p.Directed) +include ok + +open scoped Classical in +theorem vacant_overlay (v : U.Actors S) (hv : ¬ (U.localAt S A v).live = true) : + (∀ i, (T).width tape (v, i) = 0) ∧ ∀ t, (T).table tape v t = 1 := by + have empty : U.localAt S A v = Geometry.Outline.empty := + (ok _ _).vacant _ (Bool.eq_false_iff.mpr hv) + constructor + · intro i + rw [U.width_overlay S x y A v i, empty] + simp [Geometry.Outline.width, Geometry.Outline.empty, Scheme.extWidth] + · have value : ∀ j t, ((T).pattern tape v).value j t = 1 := by + rw [pattern_overlay] + simp [decodeTicket, atTicket, Geometry.Outline.revise, hv] + exact fun _ => value _ _ + +open scoped Classical in +private theorem border_overlay (v : (T).Vtx) (i : B (T).e) : + (T).borderLen tape (v, i) = + if i = U.outer false then S.extWidth (U.originalAt S x v) (U.localAt S A v).name false else + if i = U.outer true then S.extWidth (U.originalAt S x v) (U.localAt S A v).name true else 0 + := by + have eq : (T).peer tape (v, i) = none ↔ (U.localAt S A v).peer i = none := by + rw [U.peer_overlay S x y A v i] + exact Option.map_eq_none_iff + rw [Scheme.borderLen, U.width_overlay S x y A v i] + by_cases free : (U.localAt S A v).peer i = none + · rw [ite_eq_left (eq.mpr free)] + unfold Geometry.Outline.width + rw [free] + rfl + rw [ite_eq_right (mt eq.mp free)] + cases he : (U.localAt S A v).name with + | none => simp [Scheme.extWidth] + | some w => + have hn : (U.localAt S A v).name.isSome := by rw [he]; rfl + have ne (b) : i ≠ U.outer b := by + intro eq + apply free + rw [eq] + exact ((ok _ _).outer _ hn b).1 + simp [ne] + +include hd + +open scoped Classical in +theorem overlay_widths : Geometry.Widths G T tape (U.holder S x A p) U.outer := by + intro v i + rw [U.border_overlay S x y A ok v i] + by_cases l : i = U.outer false + · simp only [l, ite_true] + exact U.holder_width S x y A ok p hd v false + simp only [l, ite_false] + by_cases r : i = U.outer true + · simp only [r, ite_true] + exact U.holder_width S x y A ok p hd v true + simp only [r, ite_false, ite_self, Finset.sum_const_zero] + +end + +variable (ok : U.Valid S x y A) (p : S.Presentation x G) (hd : p.Directed) + +local notation "hw" => U.overlay_widths S x y A (And.left ok) p hd +local notation "hi" => U.holder_separate S x y A (And.left ok) p hd + +open scoped Classical in +/-- Each live outline gives one station. Named collectors receive the +original station's exterior lists in their original order. -/ +def materialize : (T).Realization tape a b where + proper := U.overlay_proper S x y A ok.2 + active v := (U.localAt S A v).live = true + vacant := U.vacant_overlay S x y A ok.1 + boundary := Geometry.boundary hw hi + side i := by + rw [Geometry.boundary_span, U.direction_overlay S x y A (U.holder S x A p (portEnd G i)) + (U.outer i.isRight)] + have hn : (U.localAt S A (U.holder S x A p (portEnd G i))).name.isSome := by + rw [U.holder_name S x y A ok.1 p hd]; rfl + exact ((ok.1 _ _).outer _ hn _).2 + +local notation "R" => U.materialize S x y A ok p hd + +open scoped Classical in +private theorem materialize_boundary : (R).pres.boundary = Geometry.boundary hw hi := + (R).boundary_eq + +open scoped Classical in +theorem materialize_address (i : slots a ⊕ slots b) : + ((R).pres.boundary i).val.1.1 = U.destination S A (p.boundary i).val.1.1 := by + rw [materialize_boundary, Geometry.boundary_span, Payload.owner] + +open scoped Classical in +theorem materialize_fibers (i j : slots a ⊕ slots b) : + portEnd (R).diagram i = portEnd (R).diagram j ↔ portEnd G i = portEnd G j := by + have addr (i : slots a ⊕ slots b) : (R).pres.vertex (portEnd (R).diagram i) = + U.holder S x A p (portEnd G i) := + (Payload.owner (R).pres i).symm.trans ((U.materialize_address S x y A ok p hd i).trans + (congrArg (U.destination S A) (Payload.owner p i))) + rw [← (R).pres.vertex.injective.eq_iff, addr, addr] + exact ⟨(hi) i j, congrArg _⟩ + +open scoped Classical in +theorem materialize_retains : Payload.Retains p (R).pres U.split U.outer := by + intro e + let v := portEnd G e + let w := U.holder S x A p v + have live : (U.localAt S A w).live = true := + ((ok.1 _ _).named _ _ (U.holder_name S x y A ok.1 p hd e)).2.2 + have coords := U.holder_coords S x A p v + refine ⟨⟨w, live⟩, coords.1, congrArg Fin.val coords.2, Fin.eq_zero _, ?_, ?_⟩ + · intro i + rw [materialize_boundary] + exact Geometry.boundary_left hw hi v i + · intro i + rw [materialize_boundary] + exact Geometry.boundary_right hw hi v i + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Displaying the materialized diagram and its ordered exterior -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Packing + +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) (A : U.Matrix S) (hv : U.Valid S x y A) + {V : Type} [Fintype V] (H : U.Graph S y V) + {a b : Wire} {G : Diagram F a b} (p : S.Presentation x G) (hd : p.Directed) + +open scoped Classical in +/-- The indexed operation `U.board S x y A hv H (U.materialize S x y A hv p hd) (fun _ => +Iff.rfl)`. -/ +abbrev admitted : Geometry.Board (U.revised S) (U.overlay S x y A) a b u := + U.board S x y A hv H (U.materialize S x y A hv p hd) (fun _ => Iff.rfl) + +local notation "L" => U.admitted S x y A hv H p hd + +open scoped Classical in +theorem admitted_address (i : slots a ⊕ slots b) : + ((L).shows.pres.boundary i).val.1.1 = U.destination S A (p.boundary i).val.1.1 := + U.materialize_address S x y A hv p hd i + +open scoped Classical in +theorem admitted_retains : Payload.Retains p (L).shows.pres U.split U.outer := + U.materialize_retains S x y A hv p hd + +open scoped Classical in +theorem admitted_fibers (i j : slots a ⊕ slots b) : + portEnd (L).term.diagram i = portEnd (L).term.diagram j ↔ portEnd G i = portEnd G j := + U.materialize_fibers S x y A hv p hd i j + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Frozen child slots of the printer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly + +variable {F K : Type} [Field F] [Finite K] {S : Scheme F} + {d ℓ M r t q D k n u j z : ℕ} + (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + +open scoped Classical in +/-- Tests whether `Children.frozen U.slot i` holds. -/ +def fixedChild (i : B U.childBits) : Bool := decide (Children.frozen U.slot i) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # The genuine plan passes all two-ended checks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly +variable {F K : Type} [Field F] [Finite K] (S : Scheme F) + {d ℓ M r t q D k n u j z : ℕ} (U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z) + (x : S.format.obj) (y : U.template.format.obj) + +local notation "A" => U.canonical S x y +local notation "V" => U.Actors S +local notation "L" => U.template + +open scoped Classical in +theorem canonical_linked (hp : (L).scheme.Proper y.1) + (hf : ∀ (v : V) s t i, ((L).scheme.pattern y.1 v).peer 0 s = some (i, 0, t) → + ((L).flags y v.1 i).1 = true) : U.linked S y A := by + intro v b i w s t he + have hu (v : V) s (h : ((L).scheme.pattern y.1 v).peer 0 s ≠ none) : + (U.localAt S A v).live = true := by + rw [U.local_canonical] + change (U.read (U.printedAt S y v)).isSome = true + apply Option.isSome_iff_ne_none.mpr + intro hn + change (U.engine.decode (U.printedAt S y v)).peer 0 s ≠ none at h + simp [engine, hn, Star.vacant] at h + have step (v : V) : (U.localAt S A v).peer = ((L).scheme.pattern y.1 v).peer 0 := + congrArg Geometry.Outline.peer (U.local_canonical S x y v) + have dir (v : V) : (U.localAt S A v).direction = ((L).scheme.pattern y.1 v).direction 0 := + congrArg Geometry.Outline.direction (U.local_canonical S x y v) + rw [step] at he + have ht : (L).scheme.peer y.1 ((v, b, 0), s) = some ((w, b, 0), t) := by + unfold Scheme.peer + rw [he] + rfl + obtain ⟨hr, _, hd⟩ := hp _ _ ht + unfold Scheme.peer at hr + obtain ⟨⟨i', o, l⟩, hl, hi⟩ := Option.map_eq_some_iff.mp hr + have hv : (L).nav y w i' = v := congrArg (fun x => x.1.1) hi + have hs : l = s := congrArg Prod.snd hi + subst l + rw [Fin.eq_zero o] at hl + have huₛ := hu _ s (by rw [he]; exact Option.some_ne_none _) + have huₜ := hu _ t (by rw [hl]; exact Option.some_ne_none _) + refine ⟨hf _ _ _ _ he, huₛ, huₜ, ?_, i', ?_, ?_⟩ + · rw [dir, dir]; exact hd + · exact decide_eq_true hv + · rw [step]; exact hl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Linking every live station of a canonical plan -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Physical +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place Sharing item) + +variable {F K X Z J I : Type} [Field F] [Finite K] + {x y : Wire} {S : Scheme F} {d ℓ M r t q D k n u j z : ℕ} + {T b c g w σ r₀ t₀ : ℕ} {W : ℝ} {P : Input F x y S.h D T (c * b) g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} {left : Order.Exterior Q.left} {right : Order.Exterior Q.right} + {U : Printer F K (B S.k) S.m d S.h ℓ M r t q D k n u j z} + {a : Atlas P.Occupied P.grid.Seam S.m d S.h} {π : Palette a w q} + {β : P.Occupied ⊕ ℕ → K} {R₀ : Reference J I (B S.k) P.Occupied P.grid.Seam Z X} + {G : Record F (M * r) (M * t) P.Occupied P.grid.Seam K (B S.k)} + {hm : Matches R₀.world β s G} {index : ∀ v, Y.state v ↪ ℕ} {size : P.Occupied → ℕ} + {ext : P.Occupied → Option (B S.k) → Bool → ℕ} {old : P.V ↪ B S.m} + {data : U.rows.obj} {status : (Children.Header S.m d).obj} + {tape : S.format.obj} {pres : S.Presentation tape P.diagram} + {G₀ : (Key.share s Q).Geo P k} (B : U.Physical G₀ π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "A" => U.canonical S tape (B.record p) + +open scoped Classical in +theorem linked (hw : ∀ i, Diagram.padWidth u (((Key.share s Q).backdrop.emitted p j).width i) / u + ≤ U.cap) : + U.linked S (B.record p) A := + U.canonical_linked S tape (B.record p) (B.frame p hw).proper (B.flagged p hw) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Physical +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Install/Ledger.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Install/Ledger.lean new file mode 100644 index 0000000000..43fecab79f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Install/Ledger.lean @@ -0,0 +1,902 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Owners +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Footprint.Load +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Remnants +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Pull +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality + +/-! # Turning a diagram of packet wires into local sphere templates -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Packing + +variable {F : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} + (P : Input F x y h D T r g W) + +open scoped Classical in +/-- The selected finite family `↥(univ.image P.place)`. -/ +abbrev Occupied := ↥(univ.image P.place) + +open scoped Classical in +/-- The value specified by `(ordered_packets P.diagram r P.width).choose`. -/ +def packets := (ordered_packets P.diagram r P.width).choose + +open scoped Classical in +theorem packets_succ : P.packets.Ordered := (ordered_packets P.diagram r P.width).choose_spec.1 + +open scoped Classical in +theorem packets_numbered : P.packets.Numbered := (ordered_packets P.diagram r P.width).choose_spec.2 + +open scoped Classical in +/-- Uses `P.packets.E` as the representation. -/ +abbrev Edges := P.packets.E + +open scoped Classical in +/-- The indexed operation `P.ranks.elim (fun _ => 0) Prod.fst`. -/ +def stationRank : P.diagram.V → ℕ := P.ranks.elim (fun _ => 0) Prod.fst +open scoped Classical in +/-- The indexed operation `P.ranks.elim (fun _ => 0) Prod.snd`. -/ +def hostRank : P.V → ℕ := P.ranks.elim (fun _ => 0) Prod.snd +open scoped Classical in +/-- Computes the node rank by the application `Nat.pair (P.hostRank (P.place v).1) +(P.stationRank v)`. -/ +def nodeRank (v : P.diagram.V) := Nat.pair (P.hostRank (P.place v).1) (P.stationRank v) + +open scoped Classical in +/-- The packet rank of type `ℕ`, constructed using `P.packets.bits.symm (e, ⟨0, h.2⟩)`. -/ +def packetRank (e : P.Edges) : ℕ := + if h : P.ranks.isSome ∧ 0 < r then + let u := P.packets.bits.symm (e, ⟨0, h.2⟩) + Nat.pair (P.nodeRank (P.packets.src e)) + (Nat.pair (P.nodeRank (P.packets.dst e)) (ordinal P.diagram u / r)) + else 0 + +open scoped Classical in +/-- Builds `Grid P.diagram.V P.Edges P.Occupied where stationRank` with the specified +`stationRank`, `cellRank`, `packetRank`, `src`. -/ +def grid : Grid P.diagram.V P.Edges P.Occupied where + stationRank := P.stationRank + cellRank c := P.hostRank c.val.1 + packetRank := P.packetRank + src := P.packets.src + dst := P.packets.dst + cell v := ⟨P.place v, mem_image_of_mem _ (mem_univ _)⟩ + +open scoped Classical in +theorem station_place (v : P.diagram.V) : (P.grid.cell v).val = P.place v := rfl + +open scoped Classical in +theorem contact (hr : 0 < r) (e : P.Edges) : + let q := P.place (P.grid.src e) + let p := P.place (P.grid.dst e) + p.2 = q.2 ∧ (p.1 = q.1 ∨ p.1 ∈ P.adj q.1) := by + obtain ⟨i, hi⟩ := P.packets.bits.surjective (e, ⟨0, hr⟩) + have hs := P.packets.left i + have ht := P.packets.right i + rw [hi] at hs ht + simpa only [grid, hs, ht] using P.edge i + +open scoped Classical in +theorem uses_card (v : P.diagram.V) : r * (P.grid.uses v).card ≤ P.diagram.arity v := by + let A := ↥(P.grid.uses v) × Fin r + let bit (p : A) := P.packets.bits.symm (p.1.val, p.2) + let endpoint (p : A) : P.diagram.End := + if P.grid.src p.1.val = v then .inl (.inr (bit p)) else .inr (.inr (bit p)) + have hv (p : A) : P.diagram.station (endpoint p) = v := by + have hs := P.packets.left (bit p) + have ht := P.packets.right (bit p) + simp only [bit, Equiv.apply_symm_apply] at hs ht + unfold endpoint + split_ifs with he + · exact hs.symm.trans he + · exact ht.symm.trans ((mem_filter.mp p.1.property).2.resolve_left he) + let f (p : A) : {e // P.diagram.station e = v} := ⟨endpoint p, hv p⟩ + have hi : Function.Injective f := by + intro p q he + have eq : endpoint p = endpoint q := congrArg Subtype.val he + have hb : bit p = bit q := by unfold endpoint at eq; split_ifs at eq <;> simpa using eq + obtain ⟨hp, hq⟩ := Prod.mk.inj (P.packets.bits.symm.injective hb) + exact Prod.ext (Subtype.ext hp) hq + simpa only [A, Fintype.card_prod, Fintype.card_coe, Fintype.card_fin, P.diagram.degree, + mul_comm] using Fintype.card_le_of_injective f hi + +open scoped Classical in +/-- Reindexes `(P.Edges → Fin r → Bool)` and `(P.diagram.E → Bool)` by an equivalence. -/ +def unpack : (P.Edges → Fin r → Bool) ≃ (P.diagram.E → Bool) := + (Equiv.curry _ _ _).symm.trans (P.packets.bits.symm.arrowCongr (Equiv.refl _)) + +open scoped Classical in +/-- Computes the weight by the application `P.diagram.vertex p.1 p.2 (P.unpack z) v`. -/ +def weight (v : P.diagram.V) (p : Val x × Val y) (z : P.Edges → Fin r → Bool) := + P.diagram.vertex p.1 p.2 (P.unpack z) v + +open scoped Classical in +theorem local_weight : P.grid.LocalWeight P.weight := by + intro v p s t he + have hb (e : P.diagram.E) (h : P.diagram.source e = v ∨ P.diagram.target e = v) : + P.unpack s e = P.unpack t e := by + have hh : (P.packets.bits e).1 ∈ P.grid.uses v := by + refine mem_filter.mpr ⟨mem_univ _, ?_⟩ + simpa only [grid, P.packets.left, P.packets.right] using h + exact congrFun (he _ hh) (P.packets.bits e).2 + unfold weight Diagram.vertex + apply congrArg₂ (P.diagram.table v).2.2 + · apply congrArg (bits (P.diagram.table v).1).symm + funext i + cases eq : P.diagram.src ⟨v, i⟩ with + | inl _ => rfl + | inr e => exact hb e (.inl (congrArg Sigma.fst (P.diagram.src.symm_apply_eq.mpr eq.symm))) + · apply congrArg (bits (P.diagram.table v).2.1).symm + funext i + cases eq : P.diagram.dst ⟨v, i⟩ with + | inl _ => rfl + | inr e => exact hb e (.inr (congrArg Sigma.fst (P.diagram.dst.symm_apply_eq.mpr eq.symm))) + +variable [Field F] (K : Type) [Field K] [Algebra K F] + +open scoped Classical in +theorem sew (s : Val x) (t : Val y) : + (∑ z : P.grid.State r, ∏ c, (P.grid.template K P.weight c).eval (s, t) (fun e => (z e).val)) = + P.diagram.eval s t := by + refine (P.grid.sew K P.weight P.local_weight (s, t)).trans ?_ + exact Equiv.sum_comp P.unpack (fun z => ∏ v, P.diagram.vertex s t z v) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# Size and energy of the installed templates + +A cell's seam widths charge incident station widths. For a global bound +on station energy, each original vertex contributes its squared arity once. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Packing + +variable {F : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} + (P : Input F x y h D T r g W) + +open scoped Classical in +private theorem stations_eq (c : P.Occupied) : + P.grid.stations c = univ.filter fun v => P.place v = c.val := by + ext v + simp only [Grid.stations, mem_filter_univ, Subtype.ext_iff, station_place] + +open scoped Classical in +theorem stations_bound (c : P.Occupied) : (P.grid.stations c).card ≤ 100 * D := by + simpa only [P.stations_eq, Fintype.card_subtype] using P.count c.val + +open scoped Classical in +theorem ports_bound (hr : 0 < r) (c : P.Occupied) : (P.grid.ports c).card ≤ 2 * g := by + let N (p : P.Occupied) := univ.filter fun q : P.Occupied => + q.val.2 = p.val.2 ∧ q.val.1 ∈ P.adj p.val.1 + have sym p q (hq : q ∈ N p) : p ∈ N q := by + obtain ⟨_, hx, ha⟩ := mem_filter.mp hq + exact mem_filter.mpr ⟨mem_univ _, hx.symm, P.sym _ _ ha⟩ + have adj e (hne : P.grid.cell (P.grid.src e) ≠ P.grid.cell (P.grid.dst e)) : + P.grid.cell (P.grid.dst e) ∈ N (P.grid.cell (P.grid.src e)) := by + obtain ⟨hx, he | he⟩ := P.contact hr e + · exact (hne (Subtype.ext (Prod.ext he.symm hx.symm))).elim + · exact mem_filter.mpr ⟨mem_univ _, hx, he⟩ + have le : (N c).card ≤ (P.adj c.val.1).card := by + apply card_le_card_of_injOn (fun p : P.Occupied => p.val.1) + · exact fun p hp => (mem_filter.mp hp).2.2 + · intro p hp q hq he + exact Subtype.ext (Prod.ext he ((mem_filter.mp hp).2.1.trans (mem_filter.mp hq).2.1.symm)) + exact (P.grid.ports_bound N sym adj c).trans (Nat.mul_le_mul_left 2 (le.trans (P.degree _))) + +open scoped Classical in +private theorem sum_number {I : Type} {rank : I → ℕ} (s : Finset I) (f : I → ℕ) : + (∑ i, f (Grid.number rank s i).val) = ∑ i ∈ s, f i := by + rw [Equiv.sum_comp (Grid.number rank s) (fun a => f a.val), sum_coe_sort] + +open scoped Classical in +theorem grid_width (c : P.Occupied) : + (∑ i, P.grid.width c i) * r ≤ 200 * D * T := by + let a := ∑ v ∈ P.grid.stations c, (P.grid.uses v).card + have H : ∑ i, P.grid.width c i ≤ 2 * a := by + rw [Fin.sum_univ_add] + simp only [Grid.width, Grid.mark_label, Grid.mark_seam, Grid.label, Grid.seam] + rw [sum_number _ (fun v => (P.grid.uses v).card), + sum_number _ (fun s => (P.grid.carries s).card)] + exact (Nat.add_le_add_left (P.grid.carries_le_uses c) _).trans_eq (two_mul a).symm + have ha : r * a ≤ ∑ v ∈ P.grid.stations c, P.diagram.arity v := by + dsimp only [a] + rw [mul_sum] + exact sum_le_sum fun v _ => P.uses_card v + have hm : (∑ v ∈ P.grid.stations c, P.diagram.arity v) ≤ 100 * D * T := by + have hm : (∑ v ∈ P.grid.stations c, (P.diagram.arity v : ℝ)) ≤ 100 * (D : ℝ) * T := by + refine le_trans ?_ (P.mass c.val) + rw [stations_eq, sum_filter, push] + apply sum_le_sum + intro v _ + by_cases hv : P.place v = c.val <;> simp [hv] + exact_mod_cast hm + calc + _ ≤ (2 * a) * r := Nat.mul_le_mul_right _ H + _ = 2 * (r * a) := by ac_rfl + _ ≤ 2 * (100 * D * T) := Nat.mul_le_mul_left _ (ha.trans hm) + _ = _ := by ring + +open scoped Classical in +private theorem scale_energy {I : Type} [Fintype I] (m : I → ℕ) (r : ℕ) : + (∑ i, (↑(r * (8 * (m i) ^ 2) : ℕ) : ℝ)) * r = 8 * ∑ i, ((m i : ℝ) * r) ^ 2 := by + rw [sum_mul, mul_sum] + apply sum_congr rfl + intro i _ + push_cast + ring + +open scoped Classical in +theorem grid_energy (hr : 0 < r) (c : P.Occupied) : + (∑ i, (↑(r * (8 * (P.grid.width c i) ^ 2) : ℕ) : ℝ)) ≤ 8 * (200 * (D : ℝ) * T) ^ 2 / r := by + apply (le_div_iff₀ (Nat.cast_pos.mpr hr)).mpr + rw [scale_energy] + apply mul_le_mul_of_nonneg_left _ (by norm_num) + apply le_trans (sum_sq_le_sq_sum_of_nonneg (fun i _ => by positivity)) + rw [← sum_mul] + apply pow_le_pow_left₀ (by positivity) + exact_mod_cast P.grid_width c + +open scoped Classical in +theorem station_energy (hr : 0 < r) : + (∑ c, ∑ i : Fin (P.grid.stations c).card, + (↑(r * (8 * (P.grid.width c (Fin.castAdd _ i)) ^ 2) : ℕ) : ℝ)) ≤ 8 * W * T / r := by + let m (v : P.diagram.V) := (P.grid.uses v).card + let cost (v : P.diagram.V) : ℝ := ↑(r * (8 * (m v) ^ 2) : ℕ) + have he : (∑ c, ∑ i : Fin (P.grid.stations c).card, cost (P.grid.label c i)) = + ∑ v, cost v := by + rw [← Equiv.sum_comp P.grid.labelEquiv cost, Fintype.sum_sigma] + rfl + simp only [Grid.width, Grid.mark_label] + change (∑ c, ∑ i, cost (P.grid.label c i)) ≤ _ + rw [he] + apply (le_div_iff₀ (Nat.cast_pos.mpr hr)).mpr + unfold cost + rw [scale_energy, mul_assoc] + apply mul_le_mul_of_nonneg_left _ (by norm_num) + refine le_trans ?_ P.squares + apply sum_le_sum + intro v _ + apply pow_le_pow_left₀ (by positivity) + rw [mul_comm] + exact_mod_cast P.uses_card v + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Planting the wiring rule of each occupied input cell -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Finset Routing.Private + +variable {F K : Type} {x y : Wire} {h D T b d g n m : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) + +open scoped Classical in +/-- Computes the external bit by the application `Sum.elim (bits x p.1) (bits y p.2)`. -/ +def externalBit (p : Val x × Val y) : slots x ⊕ slots y → Bool := + Sum.elim (bits x p.1) (bits y p.2) + +open scoped Classical in +theorem weight_external (v : P.diagram.V) (p q : Val x × Val y) (s : P.Edges → Fin (d * b) → Bool) + (H : ∀ i, Packing.portEnd P.diagram i = v → externalBit p i = externalBit q i) : + P.weight v p s = P.weight v q s := by + unfold weight Diagram.vertex + apply congrArg₂ (P.diagram.table v).2.2 + · apply congrArg (bits (P.diagram.table v).1).symm + funext i + cases eq : P.diagram.src ⟨v, i⟩ with + | inr _ => rfl + | inl j => exact H (.inl j) (congrArg Sigma.fst (P.diagram.src.symm_apply_eq.mpr eq.symm)) + · apply congrArg (bits (P.diagram.table v).2.1).symm + funext i + cases eq : P.diagram.dst ⟨v, i⟩ with + | inr _ => rfl + | inl j => exact H (.inr j) (congrArg Sigma.fst (P.diagram.dst.symm_apply_eq.mpr eq.symm)) + +variable [Field F] [Field K] [Algebra K F] + +open scoped Classical in +/-- The value specified by `Template.Kits (P.grid.template K P.weight) m n ε`. -/ +abbrev Kits (K : Type) [Field K] [Algebra K F] (m n : ℕ) (ε : ℝ) := + Template.Kits (P.grid.template K P.weight) m n ε + +variable {L : Type} (p : P.Kits K m n ε) (tag : P.Occupied → Template.Name P.diagram.V n → L) + +open scoped Classical in +/-- The quantity computed by `⟨Template.cells p tag s, P.grid.energy (d * b)⟩`. -/ +def initial (s : P.Occupied → Shape n b d) : + Surface.Scene F (d * b) d L P.Occupied P.grid.Seam ((Val x × Val y) × Template.Keys p) := + ⟨Template.cells p tag s, P.grid.energy (d * b)⟩ + +open scoped Classical in +private theorem sum_instances {I J S : Type} [i : Fintype I] [j : Fintype J] [s : Fintype S] + {i' : Fintype I} {j' : Fintype J} {s' : Fintype S} {f : I → J → F} {r : S → F} + (h : (∑ x ∈ @univ I i', ∑ y ∈ @univ J j', f x y) = ∑ z ∈ @univ S s', r z) : + (∑ x ∈ @univ I i, ∑ y ∈ @univ J j, f x y) = ∑ z ∈ @univ S s, r z := by + rwa [Subsingleton.elim i' i, Subsingleton.elim j' j, Subsingleton.elim s' s] at h + +open scoped Classical in +theorem eval_initial (x' : Val x) (y' : Val y) : + ∑ s, ∑ z, (P.initial p tag s).value m ((x', y'), z) = P.diagram.eval x' y' := by + have he (i : P.Occupied) (j : Fin (P.grid.ports i).card) : + P.grid.energy (d * b) (P.grid.seam i j) = + (P.grid.template K P.weight i).level (Fin.natAdd _ j) := by + exact congrArg (fun v : Finset P.Edges => (d * b) * (8 * v.card ^ 2)) (P.grid.mark_seam i + j).symm + have H := Template.eval_cells p tag (P.grid.energy (d * b)) he (x', y') + refine Eq.trans ?_ (P.sew K x' y') + exact sum_instances (I := P.Occupied → Shape n b d) (J := Template.Keys p) (S + := P.grid.State (d * b)) H + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# Initial motion stage + +Every occupied cell has a vacuum collector. Original immobile stations +are named collectors. The only initial selector reads occur at the +auxiliary marks and the vacuum collector of the same cell. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset Routing.Private + +variable {F K : Type} {x y : Wire} {h D T b d g n m : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `if P.mobile v then ⟨.active 0, none, ∅⟩ else +⟨.collector, some v, ∅⟩`. -/ +def tag (c : P.Occupied) : Template.Name P.diagram.V n → Tag P.Occupied P.diagram.V + | .inl v => if P.mobile v then ⟨.active 0, none, ∅⟩ else ⟨.collector, some v, ∅⟩ + | .inr none => ⟨.collector, none, {Sum.inl c}⟩ + | .inr (some _) => ⟨.residue, none, {Sum.inl c}⟩ + +variable [Field F] [Field K] [Algebra K F] (p : P.Kits K m n ε) (s : P.Occupied → Shape n b d) + +open scoped Classical in +/-- Builds `Stage F (d * b) d P.diagram.V P.Occupied P.grid.Seam ((Val x × Val y) × +Template.Keys p) where hidden` with the specified `hidden`, `scene`, `hits`, `expired`. -/ +def plant : Stage F (d * b) d P.diagram.V P.Occupied P.grid.Seam ((Val x × Val y) × Template.Keys + p) where + hidden := [] + scene := P.initial p P.tag s + hits _ := 0 + expired := 0 + footprint c := {Sum.inl c} + +open scoped Classical in +theorem eval_plant (v : Val x) (w : Val y) : + ∑ s, ∑ z, (P.plant p s).value m ((v, w), z) = P.diagram.eval v w := + P.eval_initial p P.tag v w + +variable (c : P.Occupied) + +open scoped Classical in +theorem plant_stations : ((P.plant p s).scene.cell c).stations = + Template.collectorAt p P.tag s c :: + (List.ofFn (Template.auxAt p P.tag s c) ++ List.ofFn (Template.originalAt p P.tag c)) := + Template.cells_stations p P.tag s c + +open scoped Classical in +theorem plant_ports : ((P.plant p s).ports c).map Prod.fst = List.ofFn (P.grid.seam c) := by + change ((Template.cells p P.tag s c).ports.map Prod.fst) = _ + rw [Template.cells_ports, List.map_ofFn] + rfl + +open scoped Classical in +theorem plant_edges : (P.plant p s).edges c = P.grid.ports c := by + change (((P.plant p s).ports c).map Prod.fst).toFinset = _ + rw [plant_ports] + ext e + rw [List.mem_toFinset, List.mem_ofFn] + constructor + · rintro ⟨i, rfl⟩ + exact (Grid.number P.grid.seamRank (P.grid.ports c) i).property + · intro he + exact P.grid.seam_installed c e (by simpa only [Grid.ports, mem_filter, mem_univ, true_and] + using he) + +open scoped Classical in +theorem plant_layout (hr : 0 < d * b) : + (P.plant p s).Layout (fun e => e.val.1) (fun e => e.val.2) (2 * g) where + loopless e := e.property.1 + incident c e := by + have he := P.plant_edges p s c + rw [← List.mem_toFinset] + change e ∈ (P.plant p s).edges c ↔ _ + rw [he] + simp only [Grid.ports, mem_filter, mem_univ, true_and] + unique c := by + rw [plant_ports, List.nodup_ofFn] + exact Subtype.val_injective.comp (Grid.number P.grid.seamRank (P.grid.ports c)).injective + degree c := by + rw [← List.length_map (f := Prod.fst), plant_ports, List.length_ofFn] + exact P.ports_bound hr c + +open scoped Classical in +theorem plant_cases (u : (P.plant p s).St) (hu : u ∈ ((P.plant p s).scene.cell c).stations) : + u = Template.collectorAt p P.tag s c ∨ + (∃ i, Template.auxAt p P.tag s c i = u) ∨ ∃ i, Template.originalAt p P.tag c i = u := by + unfold Stage.St plant at u hu + change u ∈ (Template.cells p P.tag s c).stations at hu + rwa [Template.cells_stations, List.mem_cons, List.mem_append, List.mem_ofFn, List.mem_ofFn] at hu + +open scoped Classical in +theorem plant_clock (u : (P.plant p s).St) (hu : u ∈ ((P.plant p s).scene.cell c).stations) : + u.label.role.clock = 0 := by + rcases P.plant_cases p s c u hu with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩ + · rfl + · rfl + · change (P.tag (n := n) c (.inl (P.grid.label c i))).role.clock = 0 + by_cases h : P.mobile (P.grid.label c i) <;> simp [tag, h, Role.clock] + +open scoped Classical in +theorem plant_valid (U : ℕ) : (P.plant p s).Valid U where + distinct c := Template.cells_positions p P.tag s c + collector c := ⟨Template.collectorAt p P.tag s c, + by rw [P.plant_stations]; exact List.mem_cons_self .., rfl⟩ + bound c u h := by rw [P.plant_clock p s c u h]; exact Nat.zero_le _ + focus c u h hn := (hn (P.plant_clock p s c u h)).elim + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Initial motion budgets, including the reserve of every active station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset Routing.Private + +variable {F K : Type} {x y : Wire} {h D T b d g n m : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) + [Field F] [Field K] [Algebra K F] (p : P.Kits K m n ε) (s : P.Occupied → Shape n b d) + +open scoped Classical in +/-- The quantity computed by `(2 * m * H) * (100 * D) + n * (m * (d * b) + d * (energyConstant * +b ^ 2))`. -/ +def reserve (D b d n m H : ℕ) := (2 * m * H) * (100 * D) + n * (m * (d * b) + + d * (energyConstant * b ^ 2)) + +open scoped Classical in +theorem plant_length (c : P.Occupied) : + ((P.plant p s).scene.cell c).stations.length ≤ 100 * D + n + 1 := by + change (Template.cells p P.tag s c).stations.length ≤ _ + rw [Template.cells_stations, List.length_cons, List.length_append, List.length_ofFn, + List.length_ofFn] + have h := P.stations_bound c + change n + (P.grid.stations c).card + 1 ≤ _ + omega + +open scoped Classical in +theorem plant_zero (H : ℕ) : ((P.plant p s).ledger m H).clock = 0 := by + apply sum_eq_zero + intro c _ + unfold Stage.tally + apply List.sum_eq_zero + rintro i hi + obtain ⟨u, hu, rfl⟩ := List.mem_map.mp hi + exact P.plant_clock p s c u hu + +open scoped Classical in +private theorem tally (f : Role → ℕ → ℕ) (c : P.Occupied) : + (P.plant p s).tally m f c = f .collector 0 + + ((∑ i, f .residue (m * ((s c).1 i).val + ((s c).2 i).val)) + + ∑ i : Fin (P.grid.stations c).card, + f (P.tag (n := n) c (.inl (P.grid.label c i))).role + (m * ((d * b) * (8 * P.grid.width c (Fin.castAdd _ i) ^ 2)))) := by + unfold Stage.tally + change ((Template.cells p P.tag s c).stations.map (fun v => f v.label.role (energyOf m v))).sum + = _ + rw [Template.cells_stations] + simp only [List.map_cons, List.map_append, List.map_ofFn, List.sum_cons, List.sum_append, + List.sum_ofFn] + rfl + +open scoped Classical in +theorem initial_sum (H : ℕ) (c : P.Occupied) : + let a := (P.plant p s).ledger m H + a.mobile c + a.collected c ≤ reserve D b d n m H + m * + ∑ i : Fin (P.grid.stations c).card, (d * b) * (8 * P.grid.width c (Fin.castAdd _ i) ^ 2) := by + let role i := (P.tag (n := n) c (.inl (P.grid.label c i))).role + let E (i : Fin (P.grid.stations c).card) := m * ((d * b) * (8 * P.grid.width c (Fin.castAdd _ i) + ^ 2)) + let B i := m * ((s c).1 i).val + ((s c).2 i).val + have aux : (∑ i, B i) ≤ n * (m * (d * b) + d * (energyConstant * b ^ 2)) := calc + _ ≤ ∑ _ : Fin n, (m * (d * b) + d * (energyConstant * b ^ 2)) := + sum_le_sum fun i _ => Nat.add_le_add + (Nat.mul_le_mul_left m (Nat.le_of_lt_succ ((s c).1 i).isLt)) + (Nat.le_of_lt_succ ((s c).2 i).isLt) + _ = _ := by simp + have old : (∑ i, Role.mobile (2 * m * H) (role i) (E i)) + (∑ i, Role.collected (role i) (E i)) ≤ + (2 * m * H) * (100 * D) + ∑ i, E i := calc + _ ≤ ∑ i, (2 * m * H + E i) := by + rw [← sum_add_distrib] + apply sum_le_sum + intro i _ + cases role i <;> simp [Role.mobile, Role.collected, add_comm] + _ ≤ _ := by + rw [sum_add_distrib, sum_const, card_univ, Fintype.card_fin, Nat.nsmul_eq_mul, + mul_comm _ (2 * m * H)] + exact Nat.add_le_add_right (Nat.mul_le_mul_left _ (P.stations_bound c)) _ + dsimp only [Stage.ledger] + rw [tally, tally, mul_sum] + change (0 + ((∑ i, B i) + ∑ i, Role.mobile (2 * m * H) (role i) (E i))) + + (0 + ((∑ _i : Fin n, 0) + ∑ i, Role.collected (role i) (E i))) ≤ + reserve D b d n m H + ∑ i, E i + simp only [sum_const_zero, zero_add, reserve] + omega + +open scoped Classical in +private theorem initial_seams (H : ℕ) (c : P.Occupied) : + (∑ e ∈ (P.plant p s).edges c, ((P.plant p s).ledger m H).seam e) = + m * ∑ i : Fin (P.grid.ports c).card, (d * b) * (8 * P.grid.width c (Fin.natAdd _ i) ^ 2) := by + rw [P.plant_edges] + change (∑ e ∈ P.grid.ports c, m * P.grid.energy (d * b) e) = _ + rw [← mul_sum, ← sum_coe_sort, ← Equiv.sum_comp (Grid.number P.grid.seamRank (P.grid.ports c))] + congr 1 + apply sum_congr rfl + intro i _ + exact congrArg (fun a : Finset P.Edges => (d * b) * (8 * a.card ^ 2)) (P.grid.mark_seam c i).symm + +open scoped Classical in +theorem plant_local_energy (hr : 0 < d * b) (H : ℕ) (c : P.Occupied) : + let A := (P.plant p s).ledger m H + ((A.mobile c + A.collected c + ∑ e ∈ (P.plant p s).edges c, A.seam e : ℕ) : ℝ) ≤ + reserve D b d n m H + m * (8 * (200 * (D : ℝ) * T) ^ 2 / (d * b : ℕ)) := by + let A := (P.plant p s).ledger m H + have he : A.mobile c + A.collected c + (∑ e ∈ (P.plant p s).edges c, A.seam e) ≤ + reserve D b d n m H + m * ∑ i, (d * b) * (8 * P.grid.width c i ^ 2) := by + rw [Fin.sum_univ_add, mul_add, ← add_assoc, ← P.initial_seams p s H c] + exact Nat.add_le_add_right (P.initial_sum p s H c) _ + refine ((Nat.cast_le (α := ℝ)).mpr he).trans ?_ + rw [Nat.cast_add, Nat.cast_mul, Nat.cast_sum] + exact add_le_add_right (mul_le_mul_of_nonneg_left (P.grid_energy hr c) (Nat.cast_nonneg _)) _ + +open scoped Classical in +theorem plant_global_energy (hr : 0 < d * b) (H : ℕ) : + let A := (P.plant p s).ledger m H + ((∑ c, (A.mobile c + A.collected c) : ℕ) : ℝ) ≤ + Fintype.card P.Occupied * (reserve D b d n m H : ℝ) + m * (8 * W * T / (d * b : ℕ)) := by + have he := sum_le_sum (s := univ) fun c _ => P.initial_sum p s H c + simp only [sum_add_distrib, sum_const, Nat.nsmul_eq_mul, card_univ] at he + rw [← mul_sum] at he + dsimp only + rw [sum_add_distrib] + refine ((Nat.cast_le (α := ℝ)).mpr he).trans ?_ + rw [Nat.cast_add, Nat.cast_mul, Nat.cast_mul] + simp only [Nat.cast_sum] + exact add_le_add_right (mul_le_mul_of_nonneg_left (P.station_energy hr) (Nat.cast_nonneg _)) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Read sets of the initial station tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset Routing.Private + +variable {F K : Type} {x y : Wire} {h D T b d g n m : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) + [Field F] [Field K] [Algebra K F] (p : P.Kits K m n ε) (s : P.Occupied → Shape n b d) + +variable (c : P.Occupied) (u : (P.plant p s).St) (hu : u ∈ ((P.plant p s).scene.cell c).stations) + +include hu + +open scoped Classical in +theorem plant_reads : u.label.reads ⊆ {Sum.inl c} := by + rcases P.plant_cases p s c u hu with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩ + · exact Subset.rfl + · exact Subset.rfl + · change (P.tag (n := n) c (.inl (P.grid.label c i))).reads ⊆ _ + by_cases h : P.mobile (P.grid.label c i) <;> simp [tag, h] + +open scoped Classical in +theorem plant_collector (hn : u.label.name ≠ none) : u.label.role = .collector := by + rcases P.plant_cases p s c u hu with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩ + · rfl + · exact (hn rfl).elim + · change (P.tag (n := n) c (.inl (P.grid.label c i))).role = _ + change (P.tag (n := n) c (.inl (P.grid.label c i))).name ≠ none at hn + by_cases h : P.mobile (P.grid.label c i) + · simp [tag, h] at hn + · simp [tag, h] + +open scoped Classical in +theorem plant_local (v w : (Val x × Val y) × Template.Keys p) + (he : ∀ i, u.label.name = some (Packing.portEnd P.diagram i) → externalBit v.1 i + = externalBit w.1 i) + (hk : ∀ t, Sum.inl t ∈ u.label.reads → v.2 t = w.2 t) : u.table v = u.table w := by + rcases P.plant_cases p s c u hu with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩ + · have eq := hk c (mem_singleton_self _) + funext a b + exact congrArg ((p c).program.scalar (s c)) eq + · have eq := hk c (mem_singleton_self _) + exact congrArg (fun j => (p c).program.table (s c) j i) eq + · let t := P.grid.label c i + have ext (j) (hj : Packing.portEnd P.diagram j = t) : + externalBit v.1 j = externalBit w.1 j := by + apply he j + change (P.tag (n := n) c (.inl t)).name = _ + have ht : ¬P.mobile t := hj ▸ P.ext j + simp [tag, ht, hj] + let u := P.grid.template K P.weight c + have H (z : Level (d * b) (u.level (u.old i))) : u.stationWeight v.1 i z + = u.stationWeight w.1 i z := by + unfold Template.stationWeight + apply sum_congr rfl + intro t' _ + split_ifs + · exact P.weight_external t _ _ _ ext + · rfl + exact funext fun z => funext fun _ => H z + +open scoped Classical in +theorem plant_name (v : P.diagram.V) (hv : u.label.name = some v) : + ¬P.mobile v ∧ ∃ i, P.grid.label c i = v ∧ u = Template.originalAt p P.tag c i := by + rcases P.plant_cases p s c u hu with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩ + · cases hv + · cases hv + · change (P.tag (n := n) c (.inl (P.grid.label c i))).name = some v at hv + by_cases h : P.mobile (P.grid.label c i) + · simp [tag, h] at hv + · simp only [tag, ite_eq_right h, Option.some.injEq] at hv + exact ⟨hv ▸ h, i, hv, rfl⟩ + +omit hu in +open scoped Classical in +theorem plant_unique (v : P.diagram.V) (hv : ¬P.mobile v) : + ∃! q : P.Occupied × (P.plant p s).St, + q.2 ∈ ((P.plant p s).scene.cell q.1).stations ∧ q.2.label.name = some v := by + obtain ⟨⟨c, i⟩, hi⟩ := P.grid.labelEquiv.surjective v + change P.grid.label c i = v at hi + let u := Template.originalAt p P.tag c i + refine ⟨(c, u), ⟨?_, ?_⟩, ?_⟩ + · rw [P.plant_stations] + exact List.mem_cons_of_mem _ (List.mem_append_right _ (List.mem_ofFn.mpr ⟨i, rfl⟩)) + · change (P.tag (n := n) c (.inl (P.grid.label c i))).name = some v + simp [tag, hi, hv] + · rintro ⟨z, t⟩ ⟨ht, hn⟩ + obtain ⟨_, j, hj, rfl⟩ := P.plant_name p s z t ht v hn + have eq : (⟨z, j⟩ : Σ z, Fin (P.grid.stations z).card) = ⟨c, i⟩ := + P.grid.labelEquiv.injective (hj.trans hi.symm) + cases eq + rfl + +omit hu + +open scoped Classical in +/-- Indexes the parameters by the coordinates of `(Val x × Val y) × Template.Keys p`. -/ +abbrev Parameters := (Val x × Val y) × Template.Keys p + +open scoped Classical in +/-- The value specified by `a.2 i = b.2 i`. -/ +def keyEq (i : P.Occupied) (a b : P.Parameters p) := a.2 i = b.2 i + +open scoped Classical in +/-- The condition `∀ i, Packing.portEnd P.diagram i = v → externalBit a.1 i = externalBit b.1 i` +on the specified data. -/ +def extEq (v : P.diagram.V) (a b : P.Parameters p) := + ∀ i, Packing.portEnd P.diagram i = v → externalBit a.1 i = externalBit b.1 i + +open scoped Classical in +theorem plant_controls : (P.plant p s).Controls (P.keyEq p) (P.extEq p) := by + intro c u hu + refine ⟨P.plant_collector p s c u hu, P.plant_reads p s c u hu, ?_⟩ + intro a b keys ext + apply P.plant_local p s c u hu + · exact fun i hi => ext _ hi i rfl + · exact fun t ht => keys (.inl t) ht + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Original immobile labels after any motion sequence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset Routing.Private + +open scoped Classical in +private theorem nodup_names {A B : Type} (f : A → Option B) (l : List A) (hl : l.Nodup) + (hi : ∀ x ∈ l, ∀ y ∈ l, ∀ b, f x = some b → f y = some b → x = y) : + (l.filterMap f).Nodup := by + induction l with + | nil => simp + | cons a l ih => + obtain ⟨ha, hl⟩ := List.nodup_cons.mp hl + have ht := ih hl (fun x hx y hy => hi x (by simp [hx]) y (by simp [hy])) + cases h : f a with + | none => simpa [h] using ht + | some b => + simp only [List.filterMap_cons, h, List.nodup_cons] + refine ⟨?_, ht⟩ + intro hb + obtain ⟨x, hx, hf⟩ := List.mem_filterMap.mp hb + exact ha ((hi x (by simp [hx]) a (by simp) b hf h) ▸ hx) + +open scoped Classical in +private theorem unique_name {A B : Type} (f : A → Option B) {l : List A} (h : (l.filterMap f).Nodup) + {x y : A} (hx : x ∈ l) (hy : y ∈ l) {b : B} (h₁ : f x = some b) (h₂ : f y = some b) : x = y + := by + induction l with + | nil => simp at hx + | cons a l ih => + have hn (ha : f a = some b) : b ∉ l.filterMap f := by + rw [List.filterMap_cons, ha, List.nodup_cons] at h + exact h.1 + rcases List.mem_cons.mp hx with rfl | hx' <;> rcases List.mem_cons.mp hy with rfl | hy' + · rfl + · exact (hn h₁ (List.mem_filterMap.mpr ⟨y, hy', h₂⟩)).elim + · exact (hn h₂ (List.mem_filterMap.mpr ⟨x, hx', h₁⟩)).elim + · apply ih _ hx' hy' + cases he : f a with + | none => simpa [he] using h + | some b => rw [List.filterMap_cons, he, List.nodup_cons] at h; exact h.2 + +variable {F K : Type} {x y : Wire} {h D T b d g n m H U : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) [Field F] [Field K] [Algebra K F] + (p : P.Kits K m n ε) (s : P.Occupied → Shape n b d) + {z : Stage F (d * b) d P.diagram.V P.Occupied P.grid.Seam (P.Parameters p)} + +open scoped Classical in +theorem plant_nodup (c : P.Occupied) : ((P.plant p s).names c).Nodup := by + apply nodup_names + · exact List.Nodup.of_map Station.pos (List.nodup_append.mp ((P.plant_valid p s 0).distinct c)).1 + · intro a ha b hb v hv hw + obtain ⟨hn, _⟩ := P.plant_name p s c a ha v hv + obtain ⟨_, _, hu⟩ := P.plant_unique p s v hn + exact congrArg Prod.snd ((hu (c, a) ⟨ha, hv⟩).trans (hu (c, b) ⟨hb, hw⟩).symm) + +variable (hz : (P.plant p s).Reach m (2 * g) H U z) +include hz + +open scoped Classical in +theorem reached_name {c : P.Occupied} {a : z.St} (ha : a ∈ (z.scene.cell c).stations) + {v : P.diagram.V} (hv : a.label.name = some v) : ¬P.mobile v ∧ P.grid.cell v = c := by + have h := (hz.names (P.plant_controls p s) c).mem_iff.mp ((z.mem_names c v).mpr ⟨a, ha, hv⟩) + obtain ⟨u, hu, he⟩ := ((P.plant p s).mem_names c v).mp h + obtain ⟨hn, i, hi, _⟩ := P.plant_name p s c u hu v he + exact ⟨hn, hi ▸ P.grid.label_cell c i⟩ + +open scoped Classical in +theorem reached_unique (v : P.diagram.V) (hv : ¬P.mobile v) : + ∃! q : P.Occupied × z.St, q.2 ∈ (z.scene.cell q.1).stations ∧ q.2.label.name = some v := by + obtain ⟨⟨c, i⟩, ⟨hi, he⟩, _⟩ := P.plant_unique p s v hv + have perm := hz.names (P.plant_controls p s) c + have hm := perm.mem_iff.mpr (((P.plant p s).mem_names c v).mpr ⟨i, hi, he⟩) + obtain ⟨u, hu, he⟩ := (z.mem_names c v).mp hm + refine ⟨(c, u), ⟨hu, he⟩, ?_⟩ + rintro ⟨c', u'⟩ ⟨hu', he'⟩ + have eq : c' = c := (P.reached_name p s hz hu' he').2.symm.trans (P.reached_name p s hz hu he).2 + subst c' + refine Prod.ext rfl ?_ + exact unique_name _ (perm.nodup_iff.mpr (P.plant_nodup p s c)) hu' hu he' he + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Counts and energies of the final residues of a planted surface -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset Routing.Private + +variable {F K : Type} {x y : Wire} {h D T b d g n m : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) + [Field F] [Field K] [Algebra K F] (p : P.Kits K m n ε) (s : P.Occupied → Shape n b d) + +open scoped Classical in +private theorem aux_thin (c : P.Occupied) (i : Fin n) : thinStation (Template.auxAt p P.tag s c i) + := by + refine ⟨rfl, ?_⟩ + change ∀ k ∈ ({.inl c} : Finset (P.Occupied ⊕ ℕ)), k.isLeft + simp + +open scoped Classical in +private theorem original_role (c : P.Occupied) (i : Fin (P.grid.stations c).card) : + (Template.originalAt p P.tag c i).label.role ≠ .residue := by + change (P.tag (n := n) c (.inl (P.grid.label c i))).role ≠ _ + by_cases h : P.mobile (P.grid.label c i) <;> simp [tag, h] + +open scoped Classical in +theorem plant_residues : (P.plant p s).Residues (d * b) (d * (energyConstant * b ^ 2)) := by + intro c u hu hr + rcases P.plant_cases p s c u hu with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩ + · cases hr + · change if thinStation (Template.auxAt p P.tag s c i) then _ else _ + rw [ite_eq_left (P.aux_thin p s c i)] + exact ⟨Nat.le_of_lt_succ ((s c).1 i).isLt, Nat.le_of_lt_succ ((s c).2 i).isLt⟩ + · exact (P.original_role p c i hr).elim + +open scoped Classical in +theorem plant_counts (c : P.Occupied) : + thinCount ((P.plant p s).scene.cell c).stations = n ∧ + heavyCount ((P.plant p s).scene.cell c).stations ≤ 100 * D + 1 := by + have ha := P.aux_thin p s c + have hc : ¬thinStation (Template.collectorAt p P.tag s c) := by intro h; cases h.1 + have ho (i) : ¬thinStation (Template.originalAt p P.tag c i) := + fun h => P.original_role p c i h.1 + change thinCount (Template.cells p P.tag s c).stations = n ∧ + heavyCount (Template.cells p P.tag s c).stations ≤ 100 * D + 1 + rw [Template.cells_stations] + simp only [thinCount, heavyCount, List.map_cons, List.map_append, List.map_ofFn, List.sum_cons, + List.sum_append, List.sum_ofFn, Function.comp_apply, ha, hc, ho, ite_true, ite_false, sum_const, + Nat.nsmul_eq_mul, card_univ, Fintype.card_fin, mul_zero, mul_one, zero_add, add_zero] + have := P.stations_bound c + change True ∧ 1 + (P.grid.stations c).card ≤ 100 * D + 1 + exact ⟨True.intro, by omega⟩ + +open scoped Classical in +private theorem count_get {A : Type} (l : List A) (f : A → Prop) [DecidablePred f] : + Fintype.card {i : Fin l.length // f (l.get i)} = (l.map (fun a => if f a then 1 else 0)).sum + := by + rw [Fintype.card_subtype, card_eq_sum_ones, sum_filter, ←List.sum_ofFn] + change (List.ofFn ((fun a => if f a then 1 else 0) ∘ l.get)).sum = _ + rw [← List.map_ofFn, List.ofFn_get] + +open scoped Classical in +theorem plant_final {ℓ g' H U : ℕ} (sc : SphereScale.Scales g ℓ D T m b d) + {t : Stage F (d * b) d P.diagram.V P.Occupied P.grid.Seam ((Val x × Val y) × Template.Keys p)} + (reach : (P.plant p s).Reach m g' H U t) (stop : t.Stopped) + (visits : ∀ v, t.visits v ≤ SphereScale.budget g * D ^ 2) : + let C := t.scene.cell + let thin := fun i => thinStation (Sphere.Layout.item C i) + (∀ v, Fintype.card {i : Fin (C v).stations.length // thin ⟨v, i⟩} ≤ n) ∧ + (∀ v, Fintype.card {i : Fin (C v).stations.length // ¬thin ⟨v, i⟩} ≤ D ^ 5) ∧ + (∀ i, thin i → (Sphere.Layout.item C i).a ≤ d * b ∧ + (Sphere.Layout.item C i).b ≤ d * (energyConstant * b ^ 2)) ∧ + (∀ i, ¬thin i → (Sphere.Layout.item C i).label.role ≠ .collector → + (Sphere.Layout.item C i).a = 0) := by + intro C thin + have hres := reach.residues (P.plant_residues p s) + refine ⟨?_, ?_, fun i => (hres.classify stop _ _ (List.get_mem ..)).1, + fun i => (hres.classify stop _ _ (List.get_mem ..)).2⟩ + · intro v + exact (count_get (C v).stations thinStation).le.trans + ((reach.counts v).1.trans_eq (P.plant_counts p s v).1) + · intro v + have hcount := (reach.counts v).2 + have hv := visits v + rw [Stage.visits, reach.edges_eq] at hv + have hb := (P.plant_counts p s v).2 + have he : heavyCount (C v).stations ≤ 100 * D + 1 + SphereScale.budget g * D ^ 2 := by + unfold C; omega + have hl := sc.large + have hD := sc.bound + have hd := Nat.le_self_pow (by decide : 2 ≠ 0) D + calc + _ = heavyCount (C v).stations := by + have hc := count_get (C v).stations (fun a => ¬ thinStation a) + simp only [ite_not] at hc + exact hc + _ ≤ 100 * D + 1 + SphereScale.budget g * D ^ 2 := he + _ ≤ (101 + SphereScale.budget g) * D ^ 2 := by rw [add_mul]; omega + _ ≤ D * D ^ 2 := Nat.mul_le_mul_right _ (by omega) + _ ≤ _ := by rw [← pow_succ']; exact Nat.pow_le_pow_right sc.Dpos (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Install/Owners.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Install/Owners.lean new file mode 100644 index 0000000000..229dc95b5c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Install/Owners.lean @@ -0,0 +1,1055 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Plant.Decoded +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Footprint.Load +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Pull +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Restore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame + +/-! +# One cell with station and seam marks + +The local rule describes one bit in each packet. Different species +use independent assignments to these bits. Table entries can already +lie in an extension of the field of definition of the wiring rule. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Plant + +open scoped Classical in +/-- The data for the template construction, including `stations`, `ports`, `label`, `seam`, +`width`. -/ +structure Template (F B T E X : Type) (r : ℕ) where + /-- Stores the stations associated with this `Template`. -/ + stations : ℕ + /-- Stores the ports associated with this `Template`. -/ + ports : ℕ + /-- The label at each coordinate of type `Fin stations → T`. -/ + label : Fin stations → T + /-- The `Template` component of type `Fin ports → E`. -/ + seam : Fin ports → E + /-- The width parameter carried by `Template`, with type `Fin (stations + ports) → ℕ`. -/ + width : Fin (stations + ports) → ℕ + /-- The weight function carried by `Template`, with type `(i : Fin stations) → X → bitsAt + (width (Fin.castAdd ports i)) r → B`. -/ + weight : (i : Fin stations) → X → bitsAt (width (Fin.castAdd ports i)) r → B + /-- The `Template` component of type `Bits width → F`. -/ + rule : Bits width → F + +namespace Template + +variable {F B T E X : Type} [Field F] [Field B] [Algebra F B] {r : ℕ} + (u : Template F B T E X r) + +open scoped Classical in +/-- The eval of type `B` for the given inputs. -/ +def eval (x : X) (h : E → Wedge r) : B := + ∑ σ : (i : Fin (u.stations + u.ports)) → bitsAt (u.width i) r, + (∏ j, algebraMap F B (u.rule (fun i => σ i j))) * + (∏ i, u.weight i x (σ (Fin.castAdd u.ports i))) * + (if ∀ i, (markCode (u.width (Fin.natAdd u.stations i)) r + (σ (Fin.natAdd u.stations i))).val = h (u.seam i) then 1 else 0) + +end Template +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- +# Local packet coordinates + +Each mark carries all packets incident to a station or crossing a +seam, in the same fixed order at both ends. The local rule equates +every occurrence of an individual wire, independently in each species. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid + +open Finset Plant + +variable {V E C : Type} {r : ℕ} + +open scoped Classical in +/-- Returns `x ((number rank s).symm ⟨e, h⟩)` when `h : e ∈ s` holds, and `false` otherwise. -/ +def read (rank : E → ℕ) (s : Finset E) (x : Fin s.card → Bool) (e : E) : Bool := + if h : e ∈ s then x ((number rank s).symm ⟨e, h⟩) else false + +open scoped Classical in +/-- Evaluates `x (number rank s i).val j` at the input `j i`. -/ +def write (rank : E → ℕ) (s : Finset E) (x : E → Fin r → Bool) : bitsAt s.card r := + fun j i => x (number rank s i).val j + +open scoped Classical in +theorem read_write (rank : E → ℕ) {s : Finset E} (x : E → Fin r → Bool) (j : Fin r) {e : E} (he : e + ∈ s) : + read rank s (write rank s x j) e = x e j := by simp [read, write, he] + +open scoped Classical in +theorem read_ext {rank : E → ℕ} {s : Finset E} {x y : Fin s.card → Bool} + (h : ∀ e ∈ s, read rank s x e = read rank s y e) : x = y := by + funext i + let e := number rank s i + have he := h e.val e.property + simpa [read, e, (number rank s i).property] using he + +variable [Fintype V] [Fintype E] [Fintype C] (g : Grid V E C) + +open scoped Classical in +/-- The quantity computed by `Fin ((g.stations c).card + (g.ports c).card)`. -/ +abbrev Index (c : C) := Fin ((g.stations c).card + (g.ports c).card) + +open scoped Classical in +/-- The value specified by `(number g.stationRank (g.stations c) i).val`. -/ +def label (c : C) (i : Fin (g.stations c).card) : V := (number g.stationRank (g.stations c) i).val + +open scoped Classical in +/-- The value specified by `(number g.seamRank (g.ports c) i).val`. -/ +def seam (c : C) (i : Fin (g.ports c).card) : g.Seam := (number g.seamRank (g.ports c) i).val + +open scoped Classical in +/-- The value specified by `Fin.append (g.uses ∘ g.label c) (g.carries ∘ g.seam c)`. -/ +def mark (c : C) : g.Index c → Finset E := + Fin.append (g.uses ∘ g.label c) (g.carries ∘ g.seam c) + +open scoped Classical in +@[simp] theorem mark_label (c : C) (i : Fin (g.stations c).card) : + g.mark c (Fin.castAdd _ i) = g.uses (g.label c i) := Fin.append_left _ _ _ + +open scoped Classical in +@[simp] theorem mark_seam (c : C) (i : Fin (g.ports c).card) : + g.mark c (Fin.natAdd _ i) = g.carries (g.seam c i) := Fin.append_right _ _ _ + +omit [Fintype E] [Fintype C] in +open scoped Classical in +theorem label_cell (c : C) (i : Fin (g.stations c).card) : g.cell (g.label c i) = c := + (mem_filter.mp (number g.stationRank (g.stations c) i).property).2 + +omit [Fintype V] [Fintype E] in +open scoped Classical in +theorem seam_installed (c : C) (s : g.Seam) (hs : s.val.1 = c ∨ s.val.2 = c) : + ∃ i, g.seam c i = s := by + have h : s ∈ g.ports c := mem_filter.mpr ⟨mem_univ _, hs⟩ + exact ⟨(number g.seamRank (g.ports c)).symm ⟨s, h⟩, by simp [seam]⟩ + +open scoped Classical in +theorem appears (e : E) : ∃ i, e ∈ g.mark (g.cell (g.src e)) i := by + let c := g.cell (g.src e) + have h : g.src e ∈ g.stations c := by simp [stations, c] + refine ⟨Fin.castAdd _ ((number g.stationRank (g.stations c)).symm ⟨g.src e, h⟩), ?_⟩ + simp [c, label, uses] + +open scoped Classical in +theorem touches (c : C) (i : g.Index c) {e : E} (he : e ∈ g.mark c i) : + g.cell (g.src e) = c ∨ g.cell (g.dst e) = c := by + induction i using Fin.addCases with + | left i => + rw [mark_label] at he + rcases (mem_filter.mp he).2 with hs | hd + · exact .inl (hs ▸ g.label_cell _ i) + · exact .inr (hd ▸ g.label_cell _ i) + | right i => + rw [mark_seam] at he + obtain ⟨hs, hd⟩ := (mem_filter.mp he).2 + rw [hs, hd] + exact (mem_filter.mp (number g.seamRank (g.ports c) i).property).2 + +open scoped Classical in +/-- The value specified by `(g.mark c i).card`. -/ +def width (c : C) (i : g.Index c) := (g.mark c i).card + +open scoped Classical in +/-- The condition `∀ i, bitsAt (g.width c i) r` on the specified data. -/ +abbrev Local (r : ℕ) (c : C) := ∀ i, bitsAt (g.width c i) r + +open scoped Classical in +/-- The condition `∀ i j e, e ∈ g.mark c i → e ∈ g.mark c j → read g.packetRank (g.mark c i) (x +i) e = read g.packetRank (g.mark c j) (x j) e` on the specified data. -/ +def Agree (c : C) (x : Bits (g.width c)) : Prop := + ∀ i j e, e ∈ g.mark c i → e ∈ g.mark c j → + read g.packetRank (g.mark c i) (x i) e = read g.packetRank (g.mark c j) (x j) e + +open scoped Classical in +/-- Builds `Template F B V g.Seam X r where stations` with the specified `stations`, `ports`, +`label`, `seam`. -/ +def template (F : Type) [Field F] {B X : Type} + (weight : V → X → (E → Fin r → Bool) → B) (c : C) : Template F B V g.Seam X r where + stations := (g.stations c).card + ports := (g.ports c).card + label := g.label c + seam := g.seam c + width := g.width c + weight i x z := weight (g.label c i) x (fun e j + => read g.packetRank (g.mark c (Fin.castAdd _ i)) (z j) e) + rule p := if g.Agree c p then 1 else 0 + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +end + +/- # Each original station has one mark and each seam has its two ends -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +open Finset + +variable {V E C : Type} (g : Grid V E C) + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def labelEquiv [Fintype V] : (Σ c, Fin (g.stations c).card) ≃ V := + Equiv.ofBijective (fun p => g.label p.1 p.2) (by + constructor + · rintro ⟨c, i⟩ ⟨d, j⟩ he + have eq : c = d := (g.label_cell c i).symm.trans + ((congrArg g.cell he).trans (g.label_cell d j)) + subst d + have h : i = j := (number g.stationRank (g.stations c)).injective (Subtype.ext he) + subst j + rfl + · intro v + have h : v ∈ g.stations (g.cell v) := by simp [stations] + exact ⟨⟨g.cell v, (number g.stationRank _).symm ⟨v, h⟩⟩, by simp [label]⟩) + +open scoped Classical in +/-- Computes the end cell by the application `cond t s.val.2 s.val.1`. -/ +def endCell (s : g.Seam) (t : Bool) := cond t s.val.2 s.val.1 + +variable [Fintype C] + +open scoped Classical in +/-- Tests whether `(g.seam c i).val.2 = c` holds. -/ +def side (c : C) (i : Fin (g.ports c).card) := decide ((g.seam c i).val.2 = c) + +open scoped Classical in +theorem endCell_side (c : C) (i : Fin (g.ports c).card) : + g.endCell (g.seam c i) (g.side c i) = c := by + have hs : (g.seam c i).val.1 = c ∨ (g.seam c i).val.2 = c := + (mem_filter.mp (number g.seamRank (g.ports c) i).property).2 + by_cases h : (g.seam c i).val.2 = c + · simp [endCell, side, h] + · simp [endCell, side, h, hs.resolve_right h] + +open scoped Classical in +/-- Bundles the indexing function as an equivalence. -/ +def seamEquiv : (Σ c, Fin (g.ports c).card) ≃ g.Seam × Bool := + Equiv.ofBijective (fun p => (g.seam p.1 p.2, g.side p.1 p.2)) (by + constructor + · rintro ⟨c, i⟩ ⟨d, j⟩ he + obtain ⟨hs, ht⟩ := Prod.mk.inj he + have eq : c = d := (g.endCell_side c i).symm.trans + ((congrArg₂ g.endCell hs ht).trans (g.endCell_side d j)) + subst d + have h : i = j := (number g.seamRank (g.ports c)).injective (Subtype.ext hs) + subst j + rfl + · rintro ⟨q, _|_⟩ + · obtain ⟨i, hi⟩ := g.seam_installed q.val.1 q (.inl rfl) + exact ⟨⟨_, i⟩, Prod.ext hi (by simp [side, hi, q.property.1.symm])⟩ + · obtain ⟨i, hi⟩ := g.seam_installed q.val.2 q (.inr rfl) + exact ⟨⟨_, i⟩, Prod.ext hi (by simp [side, hi])⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +end + +/- +# Globally consistent seam assignments + +The support of the product of the wiring rules is in bijection with +the original independent packet bits. Both directions of this +bijection matter in positive characteristic. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +open Finset Plant + +variable {V E C : Type} {r : ℕ} + +open scoped Classical in +private theorem code_read {rank : E → ℕ} {s t : Finset E} (x : bitsAt s.card r) (y : bitsAt t.card + r) + (h : s = t) (he : (markCode _ r x).val = (markCode _ r y).val) (j : Fin r) (e : E) : + read rank s (x j) e = read rank t (y j) e := by + subst t + rw [(markCode _ r).injective (Subtype.ext he)] + +variable [Fintype V] [Fintype E] [Fintype C] (g : Grid V E C) + +open scoped Classical in +/-- The quantity computed by `r * (8 * (g.carries s).card ^ 2)`. -/ +def energy (r : ℕ) (s : g.Seam) := r * (8 * (g.carries s).card ^ 2) + +open scoped Classical in +/-- The condition `∀ s, Level r (g.energy r s)` on the specified data. -/ +abbrev State (r : ℕ) := ∀ s, Level r (g.energy r s) +open scoped Classical in +/-- Indexes the profile by the coordinates of `g.State r × (∀ c, g.Local r c)`. -/ +abbrev Profile (r : ℕ) := g.State r × (∀ c, g.Local r c) + +open scoped Classical in +/-- The condition `∀ i, (markCode (g.width c (Fin.natAdd _ i)) r (x (Fin.natAdd _ i))).val = (h +(g.seam c i)).val` on the specified data. -/ +def Fits (h : g.State r) (c : C) (x : g.Local r c) : Prop := + ∀ i, (markCode (g.width c (Fin.natAdd _ i)) r (x (Fin.natAdd _ i))).val = (h (g.seam c i)).val + +open scoped Classical in +/-- The condition `∀ c, (∀ j, g.Agree c (fun i => z.2 c i j)) ∧ g.Fits z.1 c (z.2 c)` on the +specified data. -/ +def Valid (z : g.Profile r) : Prop := + ∀ c, (∀ j, g.Agree c (fun i => z.2 c i j)) ∧ g.Fits z.1 c (z.2 c) + +open scoped Classical in +/-- The indexed operation `(fun s => markCode _ r (write g.packetRank (g.carries s) x), fun c i +=> write g.packetRank (g.mark c i) x)`. -/ +def record (x : E → Fin r → Bool) : g.Profile r := + (fun s => markCode _ r (write g.packetRank (g.carries s) x), fun c i + => write g.packetRank (g.mark c i) x) + +open scoped Classical in +theorem valid_record (x : E → Fin r → Bool) : g.Valid (g.record x) := by + intro c + constructor + · intro j i i' e hi hi' + exact (read_write g.packetRank x j hi).trans (read_write g.packetRank x j hi').symm + · intro i + exact congrArg (fun s : Finset E => (markCode _ r (write g.packetRank s x)).val) (g.mark_seam c + i) + +open scoped Classical in +theorem record_injective : Function.Injective (g.record (r := r)) := by + intro x y he + funext e j + let c := g.cell (g.src e) + obtain ⟨i, hi⟩ := g.appears e + rw [← read_write g.packetRank x j hi, ← read_write g.packetRank y j hi] + exact congrArg (fun z : g.Profile r => read g.packetRank (g.mark c i) (z.2 c i j) e) he + +open scoped Classical in +private theorem across {z : g.Profile r} (hz : g.Valid z) (e : E) (j : Fin r) + (i : g.Index (g.cell (g.src e))) (i' : g.Index (g.cell (g.dst e))) + (hi : e ∈ g.mark _ i) (hi' : e ∈ g.mark _ i') + (hne : g.cell (g.src e) ≠ g.cell (g.dst e)) : + read g.packetRank (g.mark _ i) (z.2 _ i j) e = read g.packetRank (g.mark _ i') (z.2 _ i' j) e + := by + let c := g.cell (g.src e) + let d := g.cell (g.dst e) + let s : g.Seam := ⟨(c, d), hne, e, rfl, rfl⟩ + obtain ⟨u, hu⟩ := g.seam_installed c s (.inl rfl) + obtain ⟨v, hv⟩ := g.seam_installed d s (.inr rfl) + let k := Fin.natAdd (g.stations c).card u + let l := Fin.natAdd (g.stations d).card v + have hk : g.mark c k = g.carries s := by rw [mark_seam, hu] + have hl : g.mark d l = g.carries s := by rw [mark_seam, hv] + have he : e ∈ g.carries s := mem_filter.mpr ⟨mem_univ _, rfl, rfl⟩ + have eq := ((hz c).2 u).trans + ((congrArg (fun s => (z.1 s).val) (hu.trans hv.symm)).trans ((hz d).2 v).symm) + exact ((hz c).1 j i k e hi (hk.symm ▸ he)).trans + ((code_read _ _ (hk.trans hl.symm) eq j e).trans ((hz d).1 j l i' e (hl.symm ▸ he) hi')) + +open scoped Classical in +theorem valid_range {z : g.Profile r} (hz : g.Valid z) : ∃ x, g.record x = z := by + choose i hi using g.appears + let x e j := read g.packetRank (g.mark _ (i e)) (z.2 _ (i e) j) e + have hx c k j e (he : e ∈ g.mark c k) : x e j = read g.packetRank (g.mark c k) (z.2 c k j) e := by + by_cases h : g.cell (g.src e) = c + · subst c + exact (hz _).1 j _ k e (hi e) he + · have ht := (g.touches c k he).resolve_left h + subst c + exact g.across hz e j _ _ (hi e) he h + have local_eq : (g.record x).2 = z.2 := by + funext c k j + exact read_ext fun e he => (read_write g.packetRank x j he).trans (hx c k j e he) + refine ⟨x, Prod.ext ?_ local_eq⟩ + funext s + obtain ⟨p, hp⟩ := g.seam_installed s.val.1 s (.inl rfl) + have h₁ := (g.valid_record x s.val.1).2 p + have h₂ := (hz s.val.1).2 p + rw [local_eq] at h₁ + exact Subtype.ext ((congrArg (fun t => ((g.record x).1 t).val) hp.symm).trans + ((h₁.symm.trans h₂).trans (congrArg (fun t => (z.1 t).val) hp))) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +end + +/- # Sewing a grid of local wiring rules -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +open Finset Plant + +variable {V E C X B : Type} [Fintype V] [Fintype E] [Fintype C] {r : ℕ} + (g : Grid V E C) (F : Type) [Field F] [Field B] [Algebra F B] + (w : V → X → (E → Fin r → Bool) → B) + +open scoped Classical in +instance stateFintype : Fintype (g.State r) := inferInstance + +open scoped Classical in +/-- The condition `∀ v x s t, (∀ e ∈ g.uses v, s e = t e) → w v x s = w v x t` on the specified +data. -/ +def LocalWeight := ∀ v x s t, (∀ e ∈ g.uses v, s e = t e) → w v x s = w v x t + +open scoped Classical in +private def term (x : X) (s : g.State r) (c : C) (t : g.Local r c) : B := + (∏ j, algebraMap F B ((g.template F w c).rule (fun i => t i j))) * + (∏ i, (g.template F w c).weight i x (t (Fin.castAdd _ i))) * + if g.Fits s c t then 1 else 0 + +open scoped Classical in +private theorem term_valid {z : g.Profile r} (x : X) + (h : (∏ c, g.term F w x z.1 c (z.2 c)) ≠ 0) : g.Valid z := by + intro c + have hc := prod_ne_zero_iff.mp h c (mem_univ _) + unfold term at hc + refine ⟨?_, ?_⟩ + · intro j + have hj := prod_ne_zero_iff.mp (mul_ne_zero_iff.mp (mul_ne_zero_iff.mp hc).1).1 j (mem_univ _) + by_contra hn + simp [template, hn] at hj + · by_contra hn + rw [ite_eq_right hn, mul_zero] at hc + exact hc rfl + +open scoped Classical in +private theorem term_record (hw : g.LocalWeight w) (x : X) (s : E → Fin r → Bool) (c : C) : + g.term F w x (g.record s).1 c ((g.record s).2 c) = ∏ v ∈ g.stations c, w v x s := by + have hv := g.valid_record s c + unfold term + rw [ite_eq_left hv.2, mul_one] + have he (j : Fin r) : (g.template F w c).rule (fun i => (g.record s).2 c i j) = 1 := + ite_eq_left (hv.1 j) + simp_rw [he, map_one] + rw [prod_const_one, one_mul] + trans ∏ i : Fin (g.stations c).card, w (g.label c i) x s + · refine prod_congr rfl fun i _ => ?_ + apply hw + intro e he + funext j + exact read_write g.packetRank s j ((g.mark_label c i).symm ▸ he) + · rw [prod_subtype (g.stations c) (fun _ => Iff.rfl)] + exact Equiv.prod_comp (number g.stationRank (g.stations c)) (fun v => w v.val x s) + +open scoped Classical in +theorem sew (hw : g.LocalWeight w) (x : X) : + (∑ s : g.State r, ∏ c, (g.template F w c).eval x (fun e => (s e).val)) = + ∑ t : E → Fin r → Bool, ∏ v, w v x t := by + let value (p : g.Profile r) := ∏ c, g.term F w x p.1 c (p.2 c) + trans ∑ p, value p + · rw [Fintype.sum_prod_type] + apply sum_congr rfl + intro s _ + trans ∏ c, ∑ t, g.term F w x s c t + · apply prod_congr rfl + intro c _ + unfold Template.eval term + apply sum_congr rfl + intro t _ + congr! 2 + · rw [Fintype.prod_sum] + · rw [← sum_subset (subset_univ (univ.image (g.record (r := r)))) (by + intro p _ hp + by_contra h + obtain ⟨t, ht⟩ := g.valid_range (g.term_valid F w x h) + exact hp (mem_image.mpr ⟨t, mem_univ _, ht⟩)), + sum_image g.record_injective.injOn] + apply sum_congr rfl + intro t _ + simp only [value, term_record g F w hw] + exact prod_fiberwise _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +end + +/- # Using a fixed wiring program over a larger field -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Sphere Plant Finset +variable {F B : Type} [Field F] [Field B] [Algebra F B] {m n b d r : ℕ} + +/-- Builds `Program B n b d where labels` with the specified `Program`, `scalar`, `table`. -/ +def Program.lift (B : Type) [Field B] [Algebra F B] (p : Program F n b d) : + Program B n b d where + labels := p.labels + scalar e i := algebraMap F B (p.scalar e i) + table e i j x y := algebraMap F B (p.table e i j x y) + +private def push (u : Site F r) : Site B r := (algebraMap F B u.1, u.2) + +private theorem push_bundle (z : Fin m → F) (V : Fin m → Wedge r) (l : List (Fin m)) : + (bundle z V l).map push = bundle (algebraMap F B ∘ z) V l := by + simp [bundle, List.map_flatMap, Function.comp_def, push] + +private theorem push_sphere (xs : List (Site F r)) : + algebraMap F B (wick fieldKernel xs) = wick fieldKernel (xs.map push) := by + rw [wick_hom, wick_map] + simp only [map_kernel, push] + +theorem lift_eval (p : Program F n b d) (z : Fin m → F) (y q : Fin n → F) + {w : Fin m → ℕ} (X : Marks w (d * b)) : + algebraMap F B (p.eval q (marked z y X)) = + (p.lift B).eval (algebraMap F B ∘ q) (marked (algebraMap F B ∘ z) (algebraMap F B ∘ y) X) + := by + simp only [Program.eval, Program.lift, term, marked, map_sum, map_prod, map_mul, + push_sphere, List.map_append, push_bundle] + rfl + +theorem lift_demand (w : Fin m → ℕ) (L : Bits w → F) (X : Marks w r) : + algebraMap F B (demand w L X) = demand w (algebraMap F B ∘ L) X := by + simp only [demand, map_sum, apply_ite (algebraMap F B), map_prod, map_zero, Function.comp_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end + +/- # Applying the station tables to the implanted rule -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template + +open Plant Routing.Private Finset + +variable {F B T E X : Type} [Field F] [Field B] [Algebra F B] {r : ℕ} + (u : Template F B T E X r) + +open scoped Classical in +/-- Computes the old by the application `Fin.castAdd u.ports i`. -/ +abbrev old (i : Fin u.stations) := Fin.castAdd u.ports i +open scoped Classical in +/-- Computes the edge by the application `Fin.natAdd u.stations i`. -/ +abbrev edge (i : Fin u.ports) := Fin.natAdd u.stations i + +open scoped Classical in +/-- The quantity computed by `r * (8 * (u.width i) ^ 2)`. -/ +abbrev level (i : Fin (u.stations + u.ports)) := r * (8 * (u.width i) ^ 2) + +open scoped Classical in +/-- The condition `∀ i, Level r (u.level (u.old i))` on the specified data. -/ +abbrev Local := ∀ i, Level r (u.level (u.old i)) + +open scoped Classical in +/-- The indexed operation `Fin.addCases a (fun j => ⟨h (u.seam j), he j⟩)`. -/ +def complete (a : u.Local) (h : E → Wedge r) (he : ∀ j, energy (h (u.seam j)).val + = u.level (u.edge j)) : + Marks u.width r := + Fin.addCases a (fun j => ⟨h (u.seam j), he j⟩) + +open scoped Classical in +/-- The sum of `if markCode _ r y = w then u.weight i x y else 0` indexed by `y`. -/ +def stationWeight (x : X) (i : Fin u.stations) (w : Level r (u.level (u.old i))) : B := + ∑ y, if markCode _ r y = w then u.weight i x y else 0 + +omit [Field F] [Algebra F B] in +open scoped Classical in +theorem stationWeight_code (x : X) (i : Fin u.stations) (y : bitsAt (u.width (u.old i)) r) : + u.stationWeight x i (markCode _ r y) = u.weight i x y := by + simp [stationWeight, (markCode (u.width (u.old i)) r).injective.eq_iff] + +open scoped Classical in +theorem eval_demand (x : X) (h : E → Wedge r) + (he : ∀ j, energy (h (u.seam j)).val = u.level (u.edge j)) : + u.eval x h = ∑ a : u.Local, (∏ i, u.stationWeight x i (a i)) * + demand u.width (algebraMap F B ∘ u.rule) (u.complete a h he) := by + unfold eval demand + simp_rw [mul_sum] + rw [sum_comm] + apply sum_congr rfl + intro σ _ + let y : u.Local := fun i => markCode _ r (σ (u.old i)) + have agree (v : u.Local) : + (∀ i, markCode (u.width i) r (σ i) = u.complete v h he i) ↔ + y = v ∧ ∀ i, (markCode (u.width (u.edge i)) r (σ (u.edge i))).val = h (u.seam i) := by + rw [Fin.forall_fin_add] + simp only [old, edge, complete, Fin.addCases_left, Fin.addCases_right, funext_iff, y, + Subtype.ext_iff] + simp only [agree, ite_and, mul_ite, mul_zero, sum_ite_eq, mem_univ, ite_true, y, old, edge, + stationWeight_code, Function.comp_apply, mul_one] + split_ifs + · exact mul_comm _ _ + · rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template +end + +/- # One surface cell from a wiring template and a private program -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template + +open Plant Surface Routing.Private Finset + +variable {F B T E X : Type} [Field B] {n b d : ℕ} + (u : Template F B T E X (d * b)) + +open scoped Classical in +/-- The original labels, a vacuum collector, and auxiliary slots. -/ +abbrev Name (T : Type) (n : ℕ) := T ⊕ Option (Fin n) + +variable (p : Program B n b d) + +open scoped Classical in +/-- Indexes the atom by the coordinates of `Station B (d * b) d (Name T n) (X × Fin p.labels)`. -/ +abbrev Atom := Station B (d * b) d (Name T n) (X × Fin p.labels) + +variable (s : Shape n b d) (z : Fin (u.stations + u.ports) → B) (y : Fin n → B) (w : B) + +open scoped Classical in +/-- The value specified by `z (u.old i) label := .inl (u.label i) a := u.level (u.old i) b := 0 +table x a _ := u.stationWeight x.1 i a`. -/ +def original (i : Fin u.stations) : Atom (T := T) (X := X) p where + pos := z (u.old i) + label := .inl (u.label i) + a := u.level (u.old i) + b := 0 + table x a _ := u.stationWeight x.1 i a + +open scoped Classical in +/-- The value specified by `y i label := .inr (some i) a := (s.1 i).val b := (s.2 i).val table x +:= p.table s x.2 i`. -/ +def aux (i : Fin n) : Atom (T := T) (X := X) p where + pos := y i + label := .inr (some i) + a := (s.1 i).val + b := (s.2 i).val + table x := p.table s x.2 i + +open scoped Classical in +/-- The value specified by `w label := .inr none a := 0 b := 0 table x _ _ := p.scalar s x.2`. -/ +def collector : Atom (T := T) (X := X) p where + pos := w + label := .inr none + a := 0 + b := 0 + table x _ _ := p.scalar s x.2 + +open scoped Classical in +/-- Lists the values in order of their bounded index. -/ +def cell : Cell B (d * b) d (Name T n) E (X × Fin p.labels) where + ports := List.ofFn fun i => (u.seam i, z (u.edge i)) + stations := collector p s w :: (List.ofFn (aux p s y) ++ List.ofFn (u.original p z)) + +variable (P : ℕ) (x : X) (v : Fin p.labels) + +open scoped Classical in +private theorem batch_original (f : Test B (d * b) d) : + batch P (x, v) (List.ofFn (u.original p z)) f = + ∑ a : u.Local, (∏ i, u.stationWeight x i (a i)) * + f (bundle (fun i => z (u.old i) ^ P) (fun i => (a i).val) (List.finRange _)) [] := by + rw [batch_ofFn] + change (∑ a : u.Local, ∑ a' : Fin u.stations → Level d 0, + (∏ i, u.stationWeight x i (a i)) * + f (bundle (fun i => z (u.old i) ^ P) (fun i => (a i).val) (List.finRange _)) + (bundle (fun i => z (u.old i)) (fun i => (a' i).val) (List.finRange _))) = _ + refine sum_congr rfl fun a _ => ?_ + rw [Fintype.sum_unique] + have hempty : bundle (fun i => z (u.old i)) (fun _ => (vac d).val) + (List.finRange u.stations) = [] := by simp [bundle, vac] + rw [show (default : Fin u.stations → Level d 0) = fun _ => vac d from Subsingleton.elim _ _, + hempty] + +open scoped Classical in +private theorem bundle_complete (a : u.Local) (h : E → Wedge (d * b)) + (he : ∀ j, energy (h (u.seam j)).val = u.level (u.edge j)) : + bundle (fun i => z i ^ P) (fun i => (u.complete a h he i).val) (List.finRange _) = + bundle (fun i => z (u.old i) ^ P) (fun i => (a i).val) (List.finRange _) ++ + ends P h (List.ofFn fun i => (u.seam i, z (u.edge i))) := by + unfold bundle ends Surface.modes + rw [show List.finRange (u.stations + u.ports) = + (List.finRange u.stations).map u.old ++ (List.finRange u.ports).map u.edge by + rw [← List.ofFn_id, List.ofFn_add] + simp only [List.ofFn_eq_map, id_eq]; rfl] + simp only [List.ofFn_eq_map, List.flatMap_append, List.flatMap_map, + complete, old, edge, Fin.addCases_left, Fin.addCases_right] + +open scoped Classical in +private theorem reverse_sums {I J K : Type} [Fintype I] [Fintype J] [Fintype K] + (f : I → J → K → B) : (∑ i, ∑ j, ∑ k, f i j k) = ∑ k, ∑ j, ∑ i, f i j k := by + simp_rw [sum_comm (s := univ (α := J)) (t := univ (α := K))] + rw [sum_comm] + exact sum_congr rfl fun _ _ => sum_comm + +open scoped Classical in +private theorem eval_cell (h : E → Wedge (d * b)) + (he : ∀ j, energy (h (u.seam j)).val = u.level (u.edge j)) : + (u.cell p s z y w).eval P (x, v) h = + ∑ a : u.Local, (∏ i, u.stationWeight x i (a i)) * p.scalar s v * + term y s (p.table s v) (marked (fun i => z i ^ P) (fun i => y i ^ P) (u.complete a h he)) + := by + simp only [Cell.eval, cell, batch, collector] + rw [Fintype.sum_unique, Fintype.sum_unique] + change p.scalar s v * batch P (x, v) _ (fun l m => forms (l ++ _) m) = _ + rw [batch_append, batch_ofFn] + simp_rw [batch_original] + unfold term marked + simp only [bundle_complete, mul_sum, forms, List.append_nil, List.append_assoc] + rw [reverse_sums] + apply sum_congr rfl + intro a _ + apply sum_congr rfl + intro l _ + apply sum_congr rfl + intro m _ + simp only [aux, Surface.modes, bundle] + ring + +open scoped Classical in +/-- Summing the public shapes and internal selectors recovers the +template for every compatible seam assignment. -/ +theorem eval_install [Field F] [Algebra F B] (h : E → Wedge (d * b)) + (he : ∀ j, energy (h (u.seam j)).val = u.level (u.edge j)) + (hp : ∀ a : Marks u.width (d * b), + p.eval y (marked (fun i => z i ^ P) (fun i => y i ^ P) a) = + demand u.width (algebraMap F B ∘ u.rule) a) : + (∑ s, ∑ v, (u.cell p s z y w).eval P (x, v) h) = u.eval x h := by + rw [eval_demand u x h he] + simp_rw [← hp, Program.eval, mul_sum, eval_cell u _ _ _ _ _ _ _ _ _ he, mul_assoc] + simp_rw [sum_comm (s := univ (α := Fin p.labels)) (t := univ (α := u.Local))] + rw [sum_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template +end + +/- +# Uniform planting in a cell + +Choose regular marks in a fixed finite field. Both the scalar selector +and the local coupling tables then work in every extension, including +one chosen later for the motion procedure. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template + +open Filter +open Routing.Private + +variable {F K B T E X : Type} [Field F] [Field B] [Algebra F B] {m n b d P : ℕ} + +open scoped Classical in +/-- Three disjoint sets of positions on the private sphere. -/ +abbrev MarksAt (B : Type) (n m : ℕ) := Fin m ⊕ Option (Fin n) ↪ B + +open scoped Classical in +/-- Embeds `Fin m` into `B`. -/ +def oldPos (q : MarksAt B n m) : Fin m ↪ B := ⟨fun i => q (.inl i), + q.injective.comp Sum.inl_injective⟩ + +open scoped Classical in +/-- Embeds `Fin n` into `B`. -/ +def auxPos (q : MarksAt B n m) : Fin n ↪ B := + ⟨fun i => q (.inr (some i)), q.injective.comp (Sum.inr_injective.comp (Option.some_injective _))⟩ + +open scoped Classical in +/-- The data for the patch construction, including `pos`, `program`, `small`, `sound`. -/ +structure Patch (u : Template F B T E X (d * b)) (P n : ℕ) (ε : ℝ) where + /-- The `Patch` component of type `MarksAt B n (u.stations + u.ports)`. -/ + pos : MarksAt B n (u.stations + u.ports) + /-- The `Patch` component of type `Program B n b d`. -/ + program : Program B n b d + small : (program.labels : ℝ) ≤ Real.exp (ε * d * b) + sound : ∀ a : Marks u.width (d * b), + program.eval (auxPos pos) (marked (fun i => oldPos pos i ^ P) (fun i => auxPos pos i ^ P) a) = + demand u.width (algebraMap F B ∘ u.rule) a + +open scoped Classical in +/-- The value specified by `u.cell p.program s (oldPos p.pos) (auxPos p.pos) (p.pos (.inr +none))`. -/ +def Patch.cell {u : Template F B T E X (d * b)} {ε : ℝ} (p : u.Patch P n ε) (s : Shape n b d) := + u.cell p.program s (oldPos p.pos) (auxPos p.pos) (p.pos (.inr none)) + +open scoped Classical in +theorem Patch.eval {u : Template F B T E X (d * b)} {ε : ℝ} (p : u.Patch P n ε) + (x : X) (h : E → Wedge (d * b)) (he : ∀ j, energy (h (u.seam j)).val = u.level (u.edge j)) : + (∑ s, ∑ v, (p.cell s).eval P (x, v) h) = u.eval x h := + u.eval_install _ _ _ _ _ _ _ he p.sound + +open scoped Classical in +/-- Block thresholds are fixed before choosing the working extension, +the Frobenius power, or the template. -/ +theorem patches [Fintype F] [Field K] [Infinite K] [Algebra F K] [NeZero n] + (sync : Prices.SharedPrice K) {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ b : ℕ in atTop, ∀ᶠ d : ℕ in atTop, + ∀ (P : ℕ), Function.Injective (fun x : F => x ^ P) → + ∀ (B T E X : Type) (_ : Field B) (_ : Algebra F B) (u : Template F B T E X (d * b)), + (∑ i, 4 * u.width i) ≤ n → u.stations + u.ports + n + 1 ≤ Fintype.card F → + Nonempty (u.Patch P n ε) := by + filter_upwards [install (n := n) (F := F) sync hε] with b hb + filter_upwards [hb] with d hd + intro P hP B T E X _ _ u hw hcard + let q : MarksAt F n (u.stations + u.ports) := Classical.choice + (Function.Embedding.nonempty_of_card_le (by simpa [add_assoc] using hcard)) + let f : F ↪ F := ⟨fun x => x ^ P, hP⟩ + let z := (oldPos q).trans f + let y := (auxPos q).trans f + have distinct (i j) : y j ≠ z i := by + intro h + have he := q.injective (f.injective h) + contradiction + obtain ⟨p, hp, he⟩ := hd _ z y (auxPos q) distinct u.width hw u.rule + let g : F ↪ B := ⟨algebraMap F B, (algebraMap F B).injective⟩ + refine ⟨⟨q.trans g, p.lift B, hp, fun a => ?_⟩⟩ + have h := congrArg (algebraMap F B) (he a) + rw [lift_eval, lift_demand] at h + have hz : algebraMap F B ∘ z = fun i => oldPos (q.trans g) i ^ P := + funext fun _ => map_pow _ _ _ + have hy : algebraMap F B ∘ y = fun i => auxPos (q.trans g) i ^ P := + funext fun _ => map_pow _ _ _ + rw [hz, hy] at h + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template +end + +/- # Contracting a family of implanted cells along their common seams -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template + +open Finset Routing.Private + +variable {F B T E X V L : Type} [Field F] [Field B] [Algebra F B] + {n b d P : ℕ} {ε : ℝ} {u : V → Template F B T E X (d * b)} + +open scoped Classical in +/-- The condition `∀ i, (u i).Patch P n ε` on the specified data. -/ +abbrev Kits (u : V → Template F B T E X (d * b)) (P n : ℕ) (ε : ℝ) := + ∀ i, (u i).Patch P n ε + +open scoped Classical in +/-- The condition `∀ i, Fin (p i).program.labels` on the specified data. -/ +abbrev Keys (p : Kits u P n ε) := ∀ i, Fin (p i).program.labels + +open scoped Classical in +/-- Each auxiliary table sees the private selector of its own cell. -/ +def cells (p : Kits u P n ε) (tag : V → Name T n → L) (s : V → Shape n b d) (i : V) : + Surface.Cell B (d * b) d L E (X × Keys p) := + ((p i).cell (s i)).pull (fun x => (x.1, x.2 i)) (tag i) + +variable [Fintype V] [Fintype E] + +open scoped Classical in +theorem eval_cells (p : Kits u P n ε) (tag : V → Name T n → L) (D : E → ℕ) + (he : ∀ i j, D ((u i).seam j) = (u i).level ((u i).edge j)) (x : X) : + (∑ s, ∑ v, Surface.eval P (cells p tag s) D (x, v)) = + ∑ h : ∀ e, Level (d * b) (D e), ∏ i, (u i).eval x (fun e => (h e).val) := by + unfold Surface.eval + simp_rw [sum_comm (s := univ (α := Keys p)) (t := univ (α := ∀ e, Level (d * b) (D e)))] + rw [sum_comm] + apply sum_congr rfl + intro h _ + have each (i : V) := (p i).eval x (fun e => (h e).val) + (fun j => (h ((u i).seam j)).property.trans (he i j)) + simp only [cells, Surface.Cell.eval_pull, ← each] + rw [Fintype.prod_sum] + apply sum_congr rfl + intro a _ + rw [Fintype.prod_sum] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template +end + +/- # The planted marks and their distinct positions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template +open Routing.Private Surface + +variable {F B T E X C L : Type} [Field F] [Field B] [Algebra F B] + {n d b m : ℕ} {ε : ℝ} {u : C → Template F B T E X (d * b)} + (p : Kits u m n ε) (tag : C → Name T n → L) (s : C → Shape n b d) (c : C) + +/-- Indexes the place by the coordinates of `T) (X := X) (p c).program) : Station B (d * b) d L +(X × Keys p) := v.pull (fun x => (x.1, x.2 c)) (tag c)`. -/ +def place (v : Atom (T := T) (X := X) (p c).program) : + Station B (d * b) d L (X × Keys p) := + v.pull (fun x => (x.1, x.2 c)) (tag c) + +/-- Computes the original at by the application `place p tag c ((u c).original (p c).program +(oldPos (p c).pos) i)`. -/ +def originalAt (i : Fin (u c).stations) := + place p tag c ((u c).original (p c).program (oldPos (p c).pos) i) + +/-- Computes the aux at by the application `place p tag c (aux (p c).program (s c) (auxPos (p +c).pos) i)`. -/ +def auxAt (i : Fin n) := + place p tag c (aux (p c).program (s c) (auxPos (p c).pos) i) + +/-- Computes the collector at by the application `place p tag c (collector (p c).program (s c) +((p c).pos (.inr none)))`. -/ +def collectorAt := + place p tag c (collector (p c).program (s c) ((p c).pos (.inr none))) + +theorem cells_stations : + (cells p tag s c).stations = collectorAt p tag s c :: + (List.ofFn (auxAt p tag s c) ++ List.ofFn (originalAt p tag c)) := by + simp only [cells, Cell.pull, Patch.cell, cell, List.map_cons, List.map_append, List.map_ofFn] + rfl + +theorem cells_ports : (cells p tag s c).ports = + List.ofFn (fun j => ((u c).seam j, oldPos (p c).pos ((u c).edge j))) := rfl + +private theorem marks_nodup {B : Type} {k n : ℕ} (q : MarksAt B n k) : + (q (.inr none) :: (List.ofFn (auxPos q) ++ List.ofFn (oldPos q))).Nodup := by + simp only [List.nodup_cons, List.mem_append, List.mem_ofFn, List.nodup_append, + List.nodup_ofFn] + refine ⟨?_, (auxPos q).injective, (oldPos q).injective, ?_⟩ + · rintro (⟨i, h⟩ | ⟨i, h⟩) <;> cases q.injective h + · rintro _ ⟨i, rfl⟩ _ ⟨j, rfl⟩ h + cases q.injective h + +theorem cells_positions : + ((cells p tag s c).stations.map Station.pos ++ (cells p tag s c).ports.map Prod.snd).Nodup := by + rw [cells_stations, cells_ports] + simp only [List.map_cons, List.map_append, List.map_ofFn, List.cons_append, List.append_assoc] + have h := marks_nodup (p c).pos + rw [List.ofFn_add (f := ⇑(oldPos (p c).pos))] at h + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Template +end + +/- +# Consecutive packets of parallel wires + +Within each ordered pair of endpoints, enumerate the wires by source +offset. Consecutive offsets in this fiber are consecutive species unless +the first wire is at a packet boundary. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Packing + +open scoped Classical in +private theorem ordered_index {A : Type} [Fintype A] (t : A → ℕ) (ht : Function.Injective t) + (n r : ℕ) (hcard : Fintype.card A = n * r) : + ∃ f : A ≃ Fin n × Fin r, + (∀ i, (finProdFinEquiv (f i)).val = (Finset.univ.filter (fun j => t j < t i)).card) ∧ + ∀ i j, t i + 1 = t j → (f i).2.val + 1 < r → + (f i).1 = (f j).1 ∧ (f i).2.val + 1 = (f j).2.val := by + let : LinearOrder A := LinearOrder.lift' t ht + let g := (Fintype.orderIsoFinOfCardEq A hcard).symm + let f := g.toEquiv.trans finProdFinEquiv.symm + have index (a : A) : finProdFinEquiv (f a) = g a := finProdFinEquiv.apply_symm_apply _ + refine ⟨f, fun i => ?_, fun i j hij hi => ?_⟩ + · have eq : (Finset.univ.filter (fun j => t j < t i)).image g = Finset.Iio (g i) := by + ext j + simp only [Finset.mem_image, Finset.mem_filter, Finset.mem_univ, true_and, Finset.mem_Iio] + constructor + · rintro ⟨x, h, rfl⟩ + exact g.lt_iff_lt.mpr h + · exact fun h => ⟨g.symm j, g.symm_apply_lt.mpr h, g.apply_symm_apply _⟩ + rw [index, ← Fin.card_Iio, ← eq, Finset.card_image_of_injective _ g.injective] + have hlt : g i < g j := g.strictMono (show t i < t j by omega) + have hstep : (g i).val + 1 = (g j).val := by + by_contra hn + let k : Fin (n * r) := ⟨(g i).val + 1, by omega⟩ + have h₁ : t i < t (g.symm k) := g.lt_symm_apply.mpr (show (g i).val < k.val by simp [k]) + have h₂ : t (g.symm k) < t j := g.symm_apply_lt.mpr (show k.val < (g j).val by dsimp [k]; omega) + omega + have he : ((f i).1, ⟨(f i).2.val + 1, hi⟩) = f j := by + apply finProdFinEquiv.injective + apply Fin.ext + rw [index, finProdFinEquiv_apply_val, ← hstep, ← index, finProdFinEquiv_apply_val] + exact Nat.add_right_comm _ _ _ + have h₁ := congrArg Prod.fst he + have h₂ := congrArg (fun p => p.2.val) he + exact ⟨h₁, h₂⟩ + +variable {F : Type} {a b : Wire} {G : Diagram F a b} {r : ℕ} + +open scoped Classical in +/-- The ordered of type `Prop` for the given inputs. -/ +def Packets.Ordered (p : Packets G r) : Prop := + ∀ {e f}, G.source e = G.source f → G.target e = G.target f → + G.srcOffset e + 1 = G.srcOffset f → (p.bits e).2.val + 1 < r → + (p.bits e).1 = (p.bits f).1 ∧ (p.bits e).2.val + 1 = (p.bits f).2.val + +open scoped Classical in +/-- Position in the ordered bundle, ignoring wires to other destinations. -/ +def ordinal (G : Diagram F a b) (i : G.E) := + (Finset.univ.filter fun j => (G.source j, G.target j) = (G.source i, G.target i) ∧ + G.srcOffset j < G.srcOffset i).card + +open scoped Classical in +/-- The numbered of type `Prop` for the given inputs. -/ +def Packets.Numbered (p : Packets G r) : Prop := + (∀ i, (p.bits i).2.val = ordinal G i % r) ∧ + ∀ i j, G.source i = G.source j → G.target i = G.target j → + ((p.bits i).1 = (p.bits j).1 ↔ ordinal G i / r = ordinal G j / r) + +open scoped Classical in +theorem ordered_packets (G : Diagram F a b) (r : ℕ) + (hw : ∀ v w, r ∣ Fintype.card {e // G.source e = v ∧ G.target e = w}) : + ∃ p : Packets G r, p.Ordered ∧ p.Numbered := by + let edge e := (G.source e, G.target e) + let fiber q := {e // edge e = q} + have div (q : G.V × G.V) : r ∣ Fintype.card (fiber q) := by + obtain ⟨v, w⟩ := q + simpa [fiber, edge, Fintype.card_subtype] using hw v w + choose n hn using div + let off q (e : fiber q) := G.srcOffset e.val + have inj q : Function.Injective (off q) := fun i j he => + Subtype.ext (G.srcOffset_inj (congrArg Prod.fst (i.property.trans j.property.symm)) he) + choose idx hrank hidx using fun q => ordered_index (off q) (inj q) (n q) r (by rw [hn, mul_comm]) + let E := Σ q, Fin (n q) + let flat : (Σ q, Fin (n q) × Fin r) ≃ E × Fin r := + { toFun := fun p => (⟨p.1, p.2.1⟩, p.2.2) + invFun := fun p => ⟨p.1.1, p.1.2, p.2⟩ + left_inv _ := rfl, right_inv _ := rfl } + let p : Packets G r := + { E := E + src := fun i => i.1.1 + dst := fun i => i.1.2 + bits := (Equiv.sigmaFiberEquiv edge).symm.trans ((Equiv.sigmaCongrRight idx).trans flat) + left _ := rfl + right _ := rfl } + have read (q) (e) (he : edge e = q) : + p.bits e = (⟨q, (idx q ⟨e, he⟩).1⟩, (idx q ⟨e, he⟩).2) := by subst q; rfl + have rank (q) (e : G.E) (he : edge e = q) : + (finProdFinEquiv (idx q ⟨e, he⟩)).val = ordinal G e := by + rw [hrank] + unfold ordinal + apply Finset.card_bij (fun x _ => x.val) + · intro x hx + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, x.2.trans he.symm, + (Finset.mem_filter.mp hx).2⟩ + · exact fun _ _ _ _ h => Subtype.ext h + · intro x hx + obtain ⟨_, h, ho⟩ := Finset.mem_filter.mp hx + exact ⟨⟨x, h.trans he⟩, Finset.mem_filter.mpr ⟨Finset.mem_univ _, ho⟩, rfl⟩ + have val (q) (e : G.E) (he : edge e = q) : + (idx q ⟨e, he⟩).1.val = ordinal G e / r ∧ (idx q ⟨e, he⟩).2.val = ordinal G e % r := by + rw [← rank q e he] + have h := finProdFinEquiv.symm_apply_apply (idx q ⟨e, he⟩) + rw [finProdFinEquiv_symm_apply] at h + exact ⟨congrArg (fun x => x.1.val) h.symm, congrArg (fun x => x.2.val) h.symm⟩ + refine ⟨p, ?_, ?_, ?_⟩ + · intro e f hs ht ho hm + have eq : edge f = edge e := Prod.ext hs.symm ht.symm + rw [read _ e rfl] at hm ⊢ + rw [read _ f eq] + obtain ⟨he, hi⟩ := hidx (edge e) ⟨e, rfl⟩ ⟨f, eq⟩ ho hm + exact ⟨congrArg (Sigma.mk (edge e)) he, hi⟩ + · intro e + rw [read _ e rfl] + exact (val _ e rfl).2 + · intro e f hs ht + have eq : edge f = edge e := Prod.ext hs.symm ht.symm + rw [read _ e rfl, read _ f eq, ← (val _ e rfl).1, ← (val _ f eq).1] + exact ⟨congrArg (fun x : E => x.2.val), fun h => congrArg (Sigma.mk _) (Fin.ext h)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Packing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Interpolation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Interpolation.lean new file mode 100644 index 0000000000..65dd71ef72 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Interpolation.lean @@ -0,0 +1,511 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Ring.GeomSum +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Data.Nat.Choose.Basic +public import Mathlib.Tactic.Ring +public import Mathlib.Data.Nat.Choose.Sum +public import Mathlib.Data.Nat.Choose.Vandermonde +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Algebra.Field.Basic +public import Mathlib.Algebra.Polynomial.Roots +public import Mathlib.LinearAlgebra.Dual.Lemmas + +/-! +# Translation of a contraction at a nilpotent parameter + +The negative binomial expansion truncates because the parameter is nilpotent. +All coefficients are integral and the proof uses no division. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Finset + +variable {R : Type*} [CommRing R] + +private theorem negative_binomial (x : R) (N : ℕ) (hx : x ^ N = 0) (q : ℕ) : + (∑ j ∈ range N, x ^ j * (j + q).choose q) * (1 - x) ^ (q + 1) = 1 := by + induction q with + | zero => simpa [hx] using geom_sum_mul_neg x N + | succ q ih => + let h (j : ℕ) := x ^ j * (j + q).choose (q + 1) + have recu : (∑ j ∈ range N, x ^ j * (j + (q + 1)).choose (q + 1)) * (1 - x) = + ∑ j ∈ range N, x ^ j * (j + q).choose q := by + apply sub_eq_zero.mp + rw [sum_mul, ← sum_sub_distrib] + calc + _ = ∑ j ∈ range N, (h j - h (j + 1)) := by + apply sum_congr rfl + intro j _ + unfold h + rw [show j + 1 + q = j + (q + 1) by omega, ← Nat.add_assoc, + Nat.choose_succ_succ, Nat.cast_add, pow_succ] + ring + _ = h 0 - h N := sum_range_sub' _ _ + _ = 0 := by simp [h, hx] + rw [pow_succ', ← mul_assoc, recu, ih] + +/-- Translation of the mode at the moving point against one fixed spectator. -/ +theorem kernel_translate (u z a : R) (N m n : ℕ) (hu : u ^ N = 0) : + (∑ f ∈ range N, u ^ (2 * f + 1) * (f.choose m : R) * ((f + n).choose n : R) * z ^ (f + n + + 1) * a ^ (f - m)) * + (1 - a * u ^ 2 * z) ^ (m + n + 1) = u ^ (2 * m + 1) * ((m + n).choose n : R) * z ^ (m + n + + 1) := by + let g (f : ℕ) := u ^ (2 * f + 1) * (f.choose m : R) * ((f + n).choose n : R) * z ^ (f + n + + 1) * a ^ (f - m) + have head : ∑ f ∈ range m, g f = 0 := by + apply sum_eq_zero + intro f hf + simp [g, Nat.choose_eq_zero_of_lt (mem_range.mp hf)] + have tail : ∑ j ∈ range m, g (N + j) = 0 := by + apply sum_eq_zero + intro j _ + unfold g + rw [pow_eq_zero_of_le (by omega : N ≤ 2 * (N + j) + 1) hu] + simp + have shift : ∑ f ∈ range N, g f = ∑ j ∈ range N, g (m + j) := by + rw [← add_zero (∑ f ∈ range N, g f), ← tail, ← sum_range_add, Nat.add_comm N m, + sum_range_add, head, zero_add] + let c := u ^ (2 * m + 1) * ((m + n).choose n : R) * z ^ (m + n + 1) + have term (j : ℕ) : g (m + j) = c * ((a * u ^ 2 * z) ^ j * (j + (m + n)).choose (m + n)) := by + have hc : (m + j).choose m * (m + j + n).choose n = + (m + n).choose n * (j + (m + n)).choose (m + n) := by + rw [show j + (m + n) = m + j + n by omega, Nat.mul_comm ((m + n).choose n), + Nat.choose_mul (Nat.le_add_left n m)] + simp [Nat.mul_comm] + unfold g c + rw [mul_assoc (u ^ _), ← Nat.cast_mul, hc, Nat.cast_mul, + show 2 * (m + j) + 1 = 2 * m + 1 + 2 * j by + omega, show m + j + n + 1 = m + n + 1 + j by omega, + pow_add u (2 * m + 1), pow_add z (m + n + 1), mul_pow, mul_pow, pow_mul, + Nat.add_sub_cancel_left] + ring + have hx : (a * u ^ 2 * z) ^ N = 0 := by + rw [mul_pow, mul_pow, ← pow_mul, pow_eq_zero_of_le (by omega : N ≤ 2 * N) hu, mul_zero, + zero_mul] + change (∑ f ∈ range N, g f) * _ = c + rw [shift] + simp_rw [term] + rw [← mul_sum, mul_assoc, negative_binomial _ _ hx, mul_one] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# The two binomial transforms at the middle site + +Vandermonde's identity and a finite difference of a row of Pascal's +triangle give integral identities, valid also after reduction modulo two. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Finset + +theorem binom_forward (K : Type*) [CommRing K] (m b : ℕ) : + (∑ f ∈ range (m + 1), (m.choose f : K) * b.choose f) = (b + m).choose m := by + rw [Nat.add_choose_eq, Finset.Nat.sum_antidiagonal_eq_sum_range_succ_mk, Nat.cast_sum] + apply sum_congr rfl + intro f hf + rw [Nat.choose_symm (mem_range_succ_iff.mp hf), Nat.cast_mul, mul_comm] + +/-- A signed difference raises the offset of the lower binomial index by one. -/ +theorem binom_difference (K : Type*) [CommRing K] (m b d : ℕ) : + (∑ f ∈ range (m + 1), (m.choose f : K) * ((-1) ^ f * (b + f).choose (f + d))) = + (-1 : K) ^ m * b.choose (m + d) := by + induction m generalizing d with + | zero => simp + | succ m ih => + rw [sum_choose_succ_mul (fun f _ => (-1 : K) ^ f * (b + f).choose (f + d)) m, + ← sum_add_distrib] + calc + _ = -(∑ f ∈ range (m + 1), (m.choose f : K) * ((-1) ^ f * (b + f).choose (f + (d + 1)))) := by + rw [← sum_neg_distrib] + apply sum_congr rfl + intro f _ + rw [show f + 1 + d = (f + d) + 1 by omega, ← Nat.add_assoc b f 1, Nat.choose_succ_succ, + Nat.cast_add, pow_succ, ← Nat.add_assoc f d 1] + ring + _ = _ := by rw [ih, pow_succ, show m + 1 + d = m + (d + 1) by omega]; ring + +theorem binom_backward (K : Type*) [CommRing K] (m b : ℕ) : + (∑ f ∈ range (m + 1), (-1 : K) ^ f * m.choose f * (b + f).choose f) = + (-1 : K) ^ m * b.choose m := by + simpa only [Nat.add_zero, mul_left_comm, mul_assoc] using binom_difference K m b 0 + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# The three-point fermion kernel + +The points are zero, one and infinity. The infinity pairing uses the +ordinary dual basis, with no factor of a square root of minus one. +`dual` denotes a triangular change of modes at the middle point. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +/-- Indexes the mode by the coordinates of `Fin r × ℕ`. -/ +abbrev Mode (r : ℕ) := Fin r × ℕ + +/-- Twice the energy of a word of generators. -/ +def energy {r : ℕ} (x : List (Mode r)) : ℕ := + (x.map fun i => 2 * i.2 + 1).sum + +/-- The chart used in the `Sphere` construction. -/ +inductive Chart + | origin | middle | dual | infinity + deriving DecidableEq + +/-- In the case `.origin`, this construction gives `.infinity`. -/ +def Chart.reflect : Chart → Chart + | .origin => .infinity + | .middle => .dual + | .dual => .middle + | .infinity => .origin + +/-- Indexes the mark by the coordinates of `Chart × Mode r`. -/ +abbrev Mark (r : ℕ) := Chart × Mode r + +variable (R : Type*) [CommRing R] {r : ℕ} + +/-- The quantity computed by `(-1) ^ m * (l + m).choose m`. -/ +def near (l m : ℕ) : R := (-1) ^ m * (l + m).choose m + +/-- In the case `.origin, .middle`, this construction gives `near R l m`. -/ +def kernel (s t : Chart) (l m : ℕ) : R := + match s, t with + | .origin, .middle => near R l m + | .middle, .origin => -near R m l + | .origin, .infinity => if l = m then 1 else 0 + | .infinity, .origin => -(if l = m then 1 else 0) + | .middle, .infinity => m.choose l + | .infinity, .middle => -(l.choose m : R) + | .origin, .dual => l.choose m + | .dual, .origin => -(m.choose l : R) + | .dual, .infinity => near R m l + | .infinity, .dual => -near R l m + | _, _ => 0 + +/-- Returns `kernel R x.1 y.1 x.2.2 y.2.2` when `x.2.1 = y.2.1` holds, and `0` otherwise. -/ +def pairing (x y : Mark r) : R := + if x.2.1 = y.2.1 then kernel R x.1 y.1 x.2.2 y.2.2 else 0 + +theorem pairing_self (x : Mark r) : pairing R x x = 0 := by + obtain ⟨s, x⟩ := x + cases s <;> simp [pairing, kernel] + +theorem pairing_skew (x y : Mark r) : pairing R y x = -pairing R x y := by + obtain ⟨s, i, l⟩ := x + obtain ⟨t, j, m⟩ := y + by_cases h : i = j + · subst j + cases s <;> cases t <;> simp [pairing, kernel, eq_comm] + · simp [pairing, h, Ne.symm h] + +/-- The value specified by `(x.1.reflect, x.2)`. -/ +def reflect (x : Mark r) : Mark r := (x.1.reflect, x.2) + +theorem pairing_reflect (x y : Mark r) : + pairing R (reflect x) (reflect y) = -pairing R x y := by + obtain ⟨s, i, l⟩ := x + obtain ⟨t, j, m⟩ := y + by_cases h : i = j + · subst j + cases s <;> cases t <;> simp [pairing, kernel, reflect, Chart.reflect] <;> rfl + · simp [pairing, reflect, h] + +/-- The quantity computed by `(-1) ^ m * m.choose f`. -/ +def lower (m f : ℕ) : R := (-1) ^ m * m.choose f + +/-- The reflected modes are integral combinations of modes of no greater +energy. Both binomial identities hold after reduction in any characteristic. -/ +theorem pairing_lower (x : Mode r) (y : Mark r) : + pairing R (.dual, x) y = ∑ f ∈ Finset.range (x.2 + 1), + lower R x.2 f * pairing R (.middle, x.1, f) y := by + obtain ⟨i, m⟩ := x + obtain ⟨t, j, b⟩ := y + by_cases h : i = j + · subst j + cases t <;> simp only [pairing, kernel, ↓reduceIte, mul_zero, Finset.sum_const_zero] + · simp only [near, lower] + have he (f : ℕ) : + (-1 : R) ^ m * m.choose f * -((-1) ^ f * (b + f).choose f) = + -((-1) ^ m) * ((-1) ^ f * m.choose f * (b + f).choose f) := by ring + simp_rw [he] + rw [← Finset.mul_sum, binom_backward, neg_mul, ← mul_assoc, ← mul_pow] + simp + · simp only [near, lower, mul_assoc, ← Finset.mul_sum, binom_forward] + · simp [pairing, h] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# The sphere kernel and motion of one site + +A mode contraction is polynomial in the reciprocal separation. For a +nilpotent displacement `u²`, the translated separation can be inverted +exactly by a finite geometric sum. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Finset + +variable {R : Type*} [CommRing R] {F : Type*} [Field F] {r : ℕ} + +/-- Returns `(-1) ^ y.2 * (x.2 + y.2).choose y.2 * z ^ (x.2 + y.2 + 1)` when `x.1 = y.1` holds, +and `0` otherwise. -/ +def coeff (x y : Mode r) (z : R) : R := + if x.1 = y.1 then (-1) ^ y.2 * (x.2 + y.2).choose y.2 * z ^ (x.2 + y.2 + 1) else 0 + +/-- The quantity computed by `z * ∑ i ∈ range N, (u ^ 2 * z) ^ i`. -/ +def shift (u z : R) (N : ℕ) := z * ∑ i ∈ range N, (u ^ 2 * z) ^ i + +/-- The quantity computed by `z * ∑ i ∈ range N, (a * u ^ 2 * z) ^ i`. -/ +def shifted (u z a : R) (N : ℕ) := z * ∑ i ∈ range N, (a * u ^ 2 * z) ^ i + +/-- Indexes the site by the coordinates of `F × Mode r`. -/ +abbrev Site (F : Type*) (r : ℕ) := F × Mode r + +/-- The quantity computed by `coeff x.2 y.2 (y.1 - x.1)⁻¹`. -/ +def fieldKernel (x y : Site F r) : F := coeff x.2 y.2 (y.1 - x.1)⁻¹ + +theorem coeff_skew (x y : Mode r) (z : R) : coeff y x (-z) = -coeff x y z := by + unfold coeff + by_cases h : x.1 = y.1 + · rw [ite_eq_left h.symm, ite_eq_left h, Nat.add_comm y.2 x.2, Nat.choose_symm_add, neg_pow z] + have hs : (-1 : R) ^ x.2 * (-1) ^ (x.2 + y.2 + 1) = -(-1) ^ y.2 := by + rw [pow_succ, pow_add, ← mul_assoc, ← mul_assoc, ← mul_pow] + simp + rw [mul_mul_mul_comm, hs, neg_mul, mul_assoc] + · rw [ite_eq_right (Ne.symm h), ite_eq_right h, neg_zero] + +theorem fieldKernel_skew (x y : Site F r) : fieldKernel y x = -fieldKernel x y := by + unfold fieldKernel + rw [← neg_sub y.1 x.1, inv_neg, coeff_skew] + +theorem fieldKernel_self (x : Site F r) : fieldKernel x x = 0 := by + simp [fieldKernel, coeff, pow_succ] + +private theorem geom_inv (u z a : R) (N : ℕ) (hu : u ^ N = 0) : + (∑ i ∈ range N, (a * u ^ 2 * z) ^ i) * (1 - a * u ^ 2 * z) = 1 := by + rw [geom_sum_mul_neg, mul_pow, mul_pow, ← pow_mul, pow_eq_zero_of_le (by omega : N ≤ 2 * N) hu, + mul_zero, zero_mul, sub_zero] + +theorem shifted_mul (u z a : R) (N : ℕ) (hu : u ^ N = 0) : shifted u z a N * (1 - a * u ^ 2 * z) + = z := by + rw [shifted, mul_assoc, geom_inv u z a N hu, mul_one] + +/-- Expand the moving mode at the center, with its doubled-energy weight. -/ +theorem coeff_shifted (u z a : R) (N : ℕ) (hu : u ^ N = 0) (x y : Mode r) : + u ^ (2 * x.2 + 1) * coeff x y (shifted u z a N) = + ∑ f ∈ range N, u ^ (2 * f + 1) * (f.choose x.2 : R) * a ^ (f - x.2) * coeff (x.1, f) y z := by + by_cases h : x.1 = y.1 + · let G := ∑ i ∈ range N, (a * u ^ 2 * z) ^ i + let d := x.2 + y.2 + 1 + have hi : (1 - a * u ^ 2 * z) ^ d * G ^ d = 1 := by + rw [← mul_pow, mul_comm, geom_inv u z a N hu, one_pow] + let T := ∑ f ∈ range N, u ^ (2 * f + 1) * (f.choose x.2 : R) * (f + y.2).choose y.2 * z ^ (f + + y.2 + 1) * a ^ (f - x.2) + have ht : T * (1 - a * u ^ 2 * z) ^ d = u ^ (2 * x.2 + 1) * ((x.2 + + y.2).choose y.2 : R) * z ^ d := + kernel_translate u z a N x.2 y.2 hu + simp only [coeff, ite_eq_left h] + calc + _ = (-1) ^ y.2 * ((u ^ (2 * x.2 + 1) * ((x.2 + y.2).choose y.2 : R) * z ^ d) * G ^ d) := by + unfold shifted G d + rw [mul_pow] + ring + _ = (-1) ^ y.2 * T := by rw [← ht, mul_assoc T, hi, mul_one] + _ = _ := by + unfold T + rw [mul_sum] + apply sum_congr rfl + intro f _ + ring + · simp [coeff, h] + +theorem coeff_shift (u z : R) (N : ℕ) (hu : u ^ N = 0) (x y : Mode r) : + u ^ (2 * x.2 + 1) * coeff x y (shift u z N) = + ∑ f ∈ range N, (u ^ (2 * f + 1) * (f.choose x.2 : R)) * coeff (x.1, f) y z := by + simpa only [shift, shifted, one_mul, one_pow, mul_one] using coeff_shifted u z 1 N hu x y + +theorem shift_mul (u z : R) (N : ℕ) (hu : u ^ N = 0) : shift u z N * (1 - u ^ 2 * z) = z := by + simpa only [shift, shifted, one_mul] using shifted_mul u z 1 N hu + +/-- Composing displacements of the reciprocal separation adds their offsets. -/ +theorem shifted_add (u z a b : R) (N : ℕ) (hu : u ^ N = 0) : + shifted u (shifted u z a N) b N = shifted u z (a + b) N := by + let z' := shifted u z a N + have ha : z' * (1 - a * u ^ 2 * z) = z := shifted_mul _ _ _ _ hu + have hprod : (1 - b * u ^ 2 * z') * (1 - a * u ^ 2 * z) = 1 - (a + b) * u ^ 2 * z := by + rw [sub_mul, one_mul, mul_assoc (b * u ^ 2), ha] + ring + have hab : shifted u z' b N * (1 - (a + b) * u ^ 2 * z) = z := by + rw [← hprod, ← mul_assoc, shifted_mul _ _ _ _ hu, ha] + let G := ∑ i ∈ range N, ((a + b) * u ^ 2 * z) ^ i + change shifted u z' b N = z * G + rw [← hab, mul_assoc, mul_comm (1 - _) G, geom_inv u z (a + b) N hu, mul_one] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Interpolation at auxiliary marks + +Clearing common denominators converts vanishing at the auxiliary marks to +a polynomial identity. Evaluating it at a pole of maximal order isolates +one coefficient. This argument works in every characteristic. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Finset Polynomial + +variable {F A B : Type*} [Field F] [Fintype A] + +theorem span_of_separates (v : B → A → F) + (h : ∀ c : A → F, (∀ b, ∑ i, c i * v b i = 0) → c = 0) : + Submodule.span F (Set.range v) = ⊤ := by + classical + by_contra hn + obtain ⟨φ, hφ, hz⟩ := Submodule.exists_dual_map_eq_bot_of_lt_top (lt_top_iff_ne_top.mpr hn) + inferInstance + let c i := φ (Pi.basisFun F A i) + have he (x : A → F) : ∑ i, c i * x i = φ x := by + conv_rhs => rw [← (Pi.basisFun F A).sum_repr x, map_sum] + simp only [map_smul, Pi.basisFun_repr, smul_eq_mul, mul_comm, c] + have hc : c = 0 := h c fun b => by + rw [he, ← Submodule.mem_bot F, ← hz] + exact ⟨v b, Submodule.subset_span ⟨b, rfl⟩, rfl⟩ + apply hφ + apply LinearMap.ext + intro x + simp [← he, hc] + +omit [Fintype A] in +/-- The total pole order suffices, even if the bound varies by site. -/ +theorem cauchy_span_degrees [Finite A] [Fintype B] (a : A ↪ F × ℕ) (z : B ↪ F) + (V : Finset F) (q : F → ℕ) (hV : ∀ i, (a i).1 ∈ V) (ha : ∀ i, (a i).2 < q (a i).1) + (hz : ∀ j i, z j ≠ (a i).1) (hcard : (∑ x ∈ V, q x) ≤ Fintype.card B) : + Submodule.span F (Set.range (fun j i => (z j - (a i).1)⁻¹ ^ ((a i).2 + 1))) = ⊤ := by + classical + let : Fintype A := Fintype.ofFinite A + apply span_of_separates + intro c hc + by_contra hne + let s := univ.filter fun i => c i ≠ 0 + have hs : s.Nonempty := by + contrapose! hne + funext i + have : i ∉ s := by rw [hne]; simp + simpa [s] using this + obtain ⟨i, hi, hmax⟩ := s.exists_max_image (fun t => (a t).2) hs + let d := Function.update q (a i).1 ((a i).2 + 1) + have hdi : d (a i).1 = (a i).2 + 1 := Function.update_self _ _ _ + have hdq (x : F) : d x ≤ q x := by + by_cases h : x = (a i).1 + · subst x; rw [hdi]; exact ha i + · simp [d, h] + let m j := d (a j).1 - ((a j).2 + 1) + have hm (j : A) (hj : j ∈ s) : (a j).2 + 1 + m j = d (a j).1 := by + apply Nat.add_sub_of_le + by_cases h : (a j).1 = (a i).1 + · rw [h, hdi]; exact Nat.succ_le_succ (hmax j hj) + · rw [show d (a j).1 = q (a j).1 from Function.update_of_ne h _ _]; exact ha j + let p (j : A) := C (c j) * (X - C (a j).1) ^ (m j) * + ∏ x ∈ V.erase (a j).1, (X - C x) ^ d x + let P := ∑ j ∈ s, p j + have hdeg (x : F) (k : ℕ) : ((X - C x) ^ k).natDegree = k := by + rw [Polynomial.natDegree_pow, natDegree_X_sub_C, mul_one] + have hpdeg (j : A) (hj : j ∈ s) : (p j).natDegree < ∑ x ∈ V, q x := calc + _ ≤ m j + ∑ x ∈ V.erase (a j).1, d x := by + apply natDegree_mul_le.trans + apply Nat.add_le_add + · exact (natDegree_C_mul_le _ _).trans_eq (hdeg _ _) + · refine (natDegree_prod_le _ _).trans_eq ?_ + simp only [hdeg] + _ < ∑ x ∈ V, d x := by + rw [← add_sum_erase V d (hV j)] + have := hm j hj + omega + _ ≤ _ := sum_le_sum fun x _ => hdq x + have hd : P.natDegree < ∑ x ∈ V, q x := by + have hb : P.natDegree ≤ (∑ x ∈ V, q x) - 1 := + natDegree_sum_le_of_forall_le _ _ (fun j hj => Nat.le_sub_one_of_lt (hpdeg j hj)) + have := hpdeg i hi + omega + have ev (x : F) (j : A) : + (p j).eval x = c j * (x - (a j).1) ^ (m j) * + ∏ y ∈ V.erase (a j).1, (x - y) ^ d y := by + simp [p, eval_prod] + have he (b : B) : P.eval (z b) = 0 := by + have hc' : ∑ j ∈ s, c j * (z b - (a j).1)⁻¹ ^ ((a j).2 + 1) = 0 := by + rw [← hc b] + apply sum_subset (subset_univ _) + intro j _ hj + have : c j = 0 := by simpa [s] using hj + simp [this] + rw [show P = ∑ j ∈ s, p j from rfl, eval_finsetSum] + calc + _ = (∑ j ∈ s, c j * (z b - (a j).1)⁻¹ ^ ((a j).2 + 1)) * + ∏ x ∈ V, (z b - x) ^ d x := by + rw [sum_mul] + apply sum_congr rfl + intro j hj + have hp : (z b - (a j).1) ^ d (a j).1 = + (z b - (a j).1) ^ ((a j).2 + 1) * (z b - (a j).1) ^ (m j) := by + rw [← pow_add, hm j hj] + rw [ev, ← mul_prod_erase V (fun x => (z b - x) ^ d x) (hV j), hp, inv_pow] + simp only [mul_assoc, inv_mul_cancel_left₀ (pow_ne_zero _ (sub_ne_zero.mpr (hz b j)))] + _ = 0 := by rw [hc', zero_mul] + have hp := eq_zero_of_natDegree_lt_card_of_eval_eq_zero P z.injective he (hd.trans_le hcard) + have hv : P.eval (a i).1 = (p i).eval (a i).1 := by + rw [show P = ∑ j ∈ s, p j from rfl, eval_finsetSum] + apply sum_eq_single_of_mem i hi + intro j hj hji + rw [ev] + by_cases h : (a j).1 = (a i).1 + · have hn : (a j).2 ≠ (a i).2 := fun he => hji (a.injective (Prod.ext h he)) + have hmj : m j ≠ 0 := by have := hm j hj; rw [h, hdi] at this; omega + simp [h, hmj] + · rw [prod_eq_zero (mem_erase.mpr ⟨Ne.symm h, hV i⟩) (by simp [hdi]), mul_zero] + have hn : (p i).eval (a i).1 ≠ 0 := by + rw [ev, show m i = 0 by simp [m, hdi], pow_zero, mul_one] + refine mul_ne_zero (mem_filter.mp hi).2 (prod_ne_zero_iff.mpr ?_) + intro x hx + exact pow_ne_zero _ (sub_ne_zero.mpr (mem_erase.mp hx).1.symm) + exact hn (by rw [← hv, hp, eval_zero]) + +/-- Sufficiently many pole-free evaluations span all covectors on distinct +pairs of a pole and a mode. The bound on the number of points is polynomial. -/ +theorem cauchy_span [Fintype B] (a : A ↪ F × ℕ) (z : B ↪ F) (q : ℕ) + (ha : ∀ i, (a i).2 < q) (hz : ∀ j i, z j ≠ (a i).1) + (hcard : (1 + Fintype.card A) * q < Fintype.card B) : + Submodule.span F (Set.range (fun j i => (z j - (a i).1)⁻¹ ^ ((a i).2 + 1))) = ⊤ := by + classical + let V := univ.image (fun i => (a i).1) + apply cauchy_span_degrees a z V (fun _ => q) (fun j => mem_image_of_mem _ (mem_univ j)) ha hz + simp only [sum_const, Nat.nsmul_eq_mul] + exact (Nat.mul_le_mul_right q (card_image_le.trans (Nat.le_add_left _ _))).trans hcard.le + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Angular.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Angular.lean new file mode 100644 index 0000000000..3e6ebb2886 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Angular.lean @@ -0,0 +1,148 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Squares + +/-! +# Summing widths at cells and throughout the surface + +The many untouched auxiliaries use their individual level bounds. +Charge all other residues by the private-species estimate, and use +the global number of collectors for the remaining legs. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo.Raw +open Finset Rounds Real Packing +open SphereScale (Scales size budget probes q) + +variable {F U X E V K : Type} [Fintype E] [Fintype V] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k ℓ L B m : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + {G : S.Geo P k} {e : E → ℕ} {thin : Place C → Prop} {selector : K → Prop} + (hr : G.Raw ℓ L B m e thin selector) (s : Scales g ℓ D T L B m) + (ha : M * r = m * B) (hb : M * t = m) (hM : M = SphereScale.chunks ℓ D) + +include hr s ha hM in +open Classical in +theorem seam_load (v : V) : + push S.src (seamWidth C e) v + push S.dst (seamWidth C e) v ≤ 5 * (budget g : ℝ) ^ 2 * D * T + := by + let c := 5 * (budget g : ℝ) * D * T + have hc : 0 ≤ c := by unfold c; positivity + calc + _ ≤ (S.seamDegree v : ℝ) * c := by + simp only [push, seamDegree, Packing.degree_sum, Packing.arityCost, + ← sum_add_distrib, Nat.cast_sum, sum_mul, Nat.cast_add, add_mul, Nat.cast_ite, + Nat.cast_one, Nat.cast_zero, ite_mul, one_mul, zero_mul] + apply sum_le_sum + intro i _ + have hh : seamWidth C e i ≤ c := hr.seam_le s ha hM i + split_ifs <;> linarith only [hh] + _ ≤ budget g * c := mul_le_mul_of_nonneg_right (Nat.cast_le.mpr (hr.seams v)) hc + _ = _ := by unfold c; ring + +include hr s ha hb hM + +open Classical in +theorem site_load (v : V) (f : Place C → ℝ) (hf : ∀ i, f i ≤ legWidth C i) + (A : ℝ) (hA : 0 ≤ A) (h : ∀ i, ¬thin i → f i ≤ A) : + ∑ j, f ⟨v, j⟩ ≤ (budget g : ℝ) ^ 2 * D * T + (D : ℝ) ^ 5 * A := by + have h₁ := hr.station_sum v (10 * (budget g : ℝ) * ((m : ℝ) * B)) A (by positivity) hA f + (fun i hi => (hf i).trans (hr.thin_le s ha hb hM i hi)) h + refine h₁.trans (add_le_add_left ?_ _) + have hlarge : 16000 ≤ (budget g : ℝ) := by + exact_mod_cast (show 16000 ≤ budget g by have := SphereScale.budget_large g; omega) + calc + _ = 16000 * (budget g : ℝ) * D * ((m : ℝ) * B * size ℓ D) := by unfold probes; push_cast; ring + _ ≤ (budget g : ℝ) * budget g * D * T := by gcongr; exact_mod_cast s.lower + _ = _ := by ring + +open Classical in +theorem total_load : (∑ i, legWidth C i) + (∑ j, seamWidth C e j) ≤ 17 * (budget g : ℝ) ^ 2 * W + := by + have hW : 0 ≤ W := le_trans (by positivity) hr.occupied + have sum_cell (f : V → ℝ) (A : ℝ) (hA : 0 ≤ A) (hf : ∀ v, f v ≤ A * D * T) : + ∑ v, f v ≤ A * W := by + have he := sum_le_card_nsmul univ f _ (fun i _ => hf i) + simp only [card_univ, nsmul_eq_mul] at he + linarith only [he, mul_le_mul_of_nonneg_left hr.occupied hA] + have hseam : ∑ j, seamWidth C e j ≤ 5 * (budget g : ℝ) ^ 2 * W := by + rw [← sum_push S.src] + apply sum_cell _ _ (by positivity) + intro v + exact (le_add_of_nonneg_right (push_nonneg S.dst _ (fun _ => proxy_nonneg ..) _)).trans + (hr.seam_load s ha hM v) + let f (i : Place C) := if G.frozen i then 0 else legWidth C i + have hmob : ∑ i, f i ≤ 2 * (budget g : ℝ) ^ 2 * W := by + rw [Fintype.sum_sigma] + apply sum_cell _ _ (by positivity) + intro v + have hf (i : Place C) : f i ≤ legWidth C i := by + unfold f + split_ifs <;> first | exact legWidth_nonneg .. | rfl + have hh := hr.site_load s ha hb hM v f hf ((D : ℝ) ^ 3 * (T / (q ℓ D : ℝ))) (by positivity) + (fun i _ => by + unfold f + split_ifs with hi + · positivity + · exact hr.residue_le s ha hb hM i hi) + have he : (D : ℝ) ^ 5 * ((D : ℝ) ^ 3 * (T / (q ℓ D : ℝ))) ≤ T := by + rw [← mul_assoc, ← pow_add] + exact (room s.Dpos (by decide)).trans + (div_le_self (by positivity) (one_le_pow₀ (by exact_mod_cast s.Dpos))) + have hp : 1 ≤ (budget g : ℝ) ^ 2 * D := by + have : 1 ≤ budget g ^ 2 * D := + Nat.mul_pos (pow_pos (by have := SphereScale.budget_large g; omega) _) s.Dpos + exact_mod_cast this + linarith only [hh, he, mul_le_mul_of_nonneg_right hp (Nat.cast_nonneg T)] + have hfix : ∑ i : {i // G.frozen i}, legWidth C i.val ≤ 10 * (budget g : ℝ) ^ 2 * W := by + have hh := sum_le_card_nsmul univ _ _ (fun (i : {i // G.frozen i}) _ + => hr.leg_le s ha hb hM i.val) + simp only [card_univ, nsmul_eq_mul] at hh + linarith only [hh, mul_le_mul_of_nonneg_left hr.collectors (Nat.cast_nonneg (budget g))] + have hsplit : (∑ i, legWidth C i) = ∑ i : {i // G.frozen i}, legWidth C i.val + ∑ i, f i := by + rw [← sum_subtype (univ.filter G.frozen) (by simp) (legWidth C), sum_filter, ← sum_add_distrib] + apply sum_congr rfl + intro i _ + unfold f + split_ifs <;> simp + linarith only [hsplit, hmob, hfix, hseam] + +variable [Field F] [Fintype K] + +open Classical in +theorem chamber_load (v : V) : S.backdrop.chamberLoad e v ≤ T / (D : ℝ) ^ (ℓ + 2) * sqrt M := by + have hs := hr.seam_load s ha hM v + have hl := hr.site_load s ha hb hM v (legWidth C) (fun _ => le_rfl) + (10 * (budget g : ℝ) * D * T) (by positivity) (fun i _ => hr.leg_le s ha hb hM i) + have hD : 16 ≤ (D : ℝ) := by exact_mod_cast (show 16 ≤ D by have := s.bound; omega) + have hD' : 1 ≤ (D : ℝ) := by linarith + have hg : (budget g : ℝ) ≤ D := by exact_mod_cast (show budget g ≤ D by have := s.large; omega) + have hs' : S.backdrop.chamberLoad e v ≤ 6 * (budget g : ℝ) ^ 2 * D * T + + (D : ℝ) ^ 5 * (10 * budget g * D * T) := by + change push S.src _ v + push S.dst _ v + push Sigma.fst (legWidth C) v ≤ _ + rw [show push Sigma.fst (legWidth C) v = ∑ j, legWidth C ⟨v, j⟩ from sum_place _ _] + linarith only [hs, hl] + have hm : sqrt (M : ℝ) = q ℓ D := by + rw [hM, SphereScale.chunks, Nat.cast_pow, sqrt_sq (by positivity)] + calc + _ ≤ _ := hs' + _ ≤ 6 * (D : ℝ) ^ 2 * D * T + (D : ℝ) ^ 5 * (10 * D * D * T) := by gcongr + _ ≤ 16 * (D : ℝ) ^ 7 * T := by + linarith only [mul_le_mul_of_nonneg_right (pow_le_pow_right₀ hD' (by decide : 3 ≤ 7)) + (Nat.cast_nonneg T)] + _ ≤ (D : ℝ) ^ 8 * T := by rw [pow_succ' (D : ℝ) 7]; gcongr + _ ≤ _ := by + rw [hm, div_mul_eq_mul_div, le_div_iff₀ (by positivity), mul_comm ((D : ℝ) ^ 8), + mul_assoc, ← pow_add, q, Nat.cast_pow] + exact mul_le_mul_of_nonneg_left (pow_le_pow_right₀ hD' (by omega)) (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo.Raw diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Encode.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Encode.lean new file mode 100644 index 0000000000..76be634496 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Encode.lean @@ -0,0 +1,232 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement + +/-! +# Encoding finite internal states + +A bundle has its own finite alphabet and an injective binary code. +The local table gives zero to invalid codes. This preserves the +contraction even when an alphabet is empty or a bundle has width zero. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +open Classical in +/-- Computes the binary code by the application `Classical.choice +(Function.Embedding.nonempty_of_card_le (by simpa using h))`. -/ +def binaryCode (X : Type) [Fintype X] (n : ℕ) (h : Fintype.card X ≤ 2 ^ n) : + X ↪ (Fin n → Bool) := Classical.choice (Function.Embedding.nonempty_of_card_le (by simpa using + h)) + +open Classical in +/-- The data for the bundled construction, including `V`, `E`, `[fv`, `[fe`, `state`. -/ +structure Bundled (F : Type) (a b : Wire) where + /-- The type of vertices. -/ + V : Type + /-- The type of edges. -/ + E : Type + [fv : Fintype V] + [fe : Fintype E] + /-- The `Bundled` component of type `E → Type`. -/ + state : E → Type + [fs : ∀ e, Fintype (state e)] + /-- The width parameter carried by `Bundled`, with type `E → ℕ`. -/ + width : E → ℕ + /-- The encoding map carried by `Bundled`, with type `∀ e, state e ↪ (Fin (width e) → Bool)`. -/ + code : ∀ e, state e ↪ (Fin (width e) → Bool) + /-- Assigns the source of each connection. -/ + src : E → V + /-- Assigns the destination of each connection. -/ + dst : E → V + /-- The left-side data carried by `Bundled`, with type `slots a → V`. -/ + left : slots a → V + /-- The right-side data carried by `Bundled`, with type `slots b → V`. -/ + right : slots b → V + /-- The `Bundled` component of type `V → Val a → Val b → (∀ e, state e) → F`. -/ + station : V → Val a → Val b → (∀ e, state e) → F + locality : ∀ v x y z x' y' z', + (∀ i, left i = v → bits a x i = bits a x' i) → + (∀ i, right i = v → bits b y i = bits b y' i) → + (∀ e, src e = v ∨ dst e = v → z e = z' e) → + station v x y z = station v x' y' z' + +attribute [instance] Bundled.fv Bundled.fe Bundled.fs + +namespace Bundled +variable {F : Type} {a b : Wire} (G : Bundled F a b) + +open Classical in +/-- Indexes the bit by the coordinates of `Σ e, Fin (G.width e)`. -/ +abbrev Bit := Σ e, Fin (G.width e) +open Classical in +/-- The condition `∀ e, G.state e` on the specified data. -/ +abbrev State := ∀ e, G.state e + +open Classical in +/-- Computes the pack by the application `G.code i.1 (s i.1) i.2`. -/ +def pack (s : G.State) (i : G.Bit) : Bool := G.code i.1 (s i.1) i.2 + +open Classical in +theorem pack_injective : Function.Injective G.pack := by + intro x y h + funext e + exact (G.code e).injective (funext fun k => congrFun h ⟨e, k⟩) + +open Classical in +/-- The value specified by `∑ s : G.State, ∏ v, G.station v x y s`. -/ +def eval [Field F] (x : Val a) (y : Val b) := ∑ s : G.State, ∏ v, G.station v x y s + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def incoming : slots a ⊕ G.Bit → G.V := Sum.elim G.left (fun i => G.src i.1) +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def outgoing : slots b ⊕ G.Bit → G.V := Sum.elim G.right (fun i => G.dst i.1) + +open Classical in +/-- Requires `(∀ i, G.src i.1 = v → G.pack s i = x (.inr i)) ∧ (∀ i, G.dst i.1 = v → G.pack s i += y (.inr i))`. -/ +def Valid (v : G.V) (x : slots a ⊕ G.Bit → Bool) (y : slots b ⊕ G.Bit → Bool) + (s : G.State) : Prop := + (∀ i, G.src i.1 = v → G.pack s i = x (.inr i)) ∧ + (∀ i, G.dst i.1 = v → G.pack s i = y (.inr i)) + +variable [Field F] + +open Classical in +/-- Selects the appropriate branch of `if h : ∃ s, G.Valid v x y s then G.station v ((bits +a).symm (x ∘ .inl)) ((bits b).symm (y ∘ .inl)) h.choose else 0`. -/ +def weight (v : G.V) (x : slots a ⊕ G.Bit → Bool) (y : slots b ⊕ G.Bit → Bool) : F := + if h : ∃ s, G.Valid v x y s then + G.station v ((bits a).symm (x ∘ .inl)) ((bits b).symm (y ∘ .inl)) h.choose + else 0 + +open Classical in +private theorem weight_read (v : G.V) {x y} {s : G.State} (h : G.Valid v x y s) : + G.weight v x y = G.station v ((bits a).symm (x ∘ .inl)) ((bits b).symm (y ∘ .inl)) s := by + have hs : ∃ s, G.Valid v x y s := ⟨s, h⟩ + rw [weight, dite_eq_left hs] + apply G.locality _ _ _ _ _ _ _ (fun _ _ => rfl) (fun _ _ => rfl) + intro e he + apply (G.code e).injective + funext i + rcases he with he | he + · exact (hs.choose_spec.1 ⟨e, i⟩ he).trans (h.1 ⟨e, i⟩ he).symm + · exact (hs.choose_spec.2 ⟨e, i⟩ he).trans (h.2 ⟨e, i⟩ he).symm + +open Classical in +theorem local_weight : Diagram.Local G.incoming G.outgoing G.weight := by + intro v x y x' y' hx hy + have he (s : G.State) : G.Valid v x y s ↔ G.Valid v x' y' s := by + constructor + · exact fun h => ⟨fun i hi => (h.1 i hi).trans (hx (.inr i) hi), + fun i hi => (h.2 i hi).trans (hy (.inr i) hi)⟩ + · exact fun h => ⟨fun i hi => (h.1 i hi).trans (hx (.inr i) hi).symm, + fun i hi => (h.2 i hi).trans (hy (.inr i) hi).symm⟩ + by_cases h : ∃ s, G.Valid v x y s + · obtain ⟨s, hs⟩ := h + rw [G.weight_read v hs, G.weight_read v ((he s).mp hs)] + apply G.locality + · simpa [incoming] using fun i hi => hx (.inl i) hi + · simpa [outgoing] using fun i hi => hy (.inl i) hi + · exact fun _ _ => rfl + · simp only [weight, ← he, dite_eq_right h] + +open Classical in +/-- Computes the diagram by the application `Diagram.ofLocal G.incoming G.outgoing G.weight`. -/ +abbrev diagram := Diagram.ofLocal G.incoming G.outgoing G.weight + +open Classical in +theorem source (e : G.Bit) : G.diagram.source e = G.src e.1 := rfl + +open Classical in +theorem target (e : G.Bit) : G.diagram.target e = G.dst e.1 := rfl + +open Classical in +theorem vertex (x : Val a) (y : Val b) (s : G.State) (v : G.V) : + G.diagram.vertex x y (G.pack s) v = G.station v x y s := by + rw [Diagram.vertex_ofLocal _ _ _ G.local_weight, G.weight_read v (s := s)] + · simp [Function.comp_def] + · exact ⟨fun _ _ => rfl, fun _ _ => rfl⟩ + +open Classical in +theorem invalid (x : Val a) (y : Val b) (z : G.Bit → Bool) (h : z ∉ Set.range G.pack) : + ∏ v : G.V, G.diagram.vertex x y z v = 0 := by + by_contra! hn + have he (e : G.E) : ∃ t, ∀ k, G.code e t k = z ⟨e, k⟩ := by + have hv := prod_ne_zero_iff.mp hn (G.src e) (mem_univ _) + rw [Diagram.vertex_ofLocal _ _ _ G.local_weight, weight] at hv + split_ifs at hv with hs + · exact ⟨hs.choose e, fun k => hs.choose_spec.1 ⟨e, k⟩ rfl⟩ + · contradiction + choose s hs using he + exact h ⟨s, funext fun i => hs i.1 i.2⟩ + +open Classical in +theorem eval_diagram : G.diagram.eval = G.eval := by + funext x y + unfold Diagram.eval + symm + calc + G.eval x y = ∑ z ∈ univ.image G.pack, ∏ v : G.V, G.diagram.vertex x y z v := by + rw [sum_image G.pack_injective.injOn] + simp only [vertex, eval] + _ = _ := sum_subset (subset_univ _) (fun z _ hz => G.invalid x y z (by simpa using hz)) + _ = _ := by congr! + +omit [Field F] in +open Classical in +theorem card_bits (p : G.E → Prop) [DecidablePred p] : + Fintype.card {i : G.Bit // p i.1} = ∑ e, if p e then G.width e else 0 := by + rw [Fintype.card_subtype, card_filter, Fintype.sum_sigma] + apply sum_congr rfl + intro e _ + by_cases he : p e <;> simp [he] + +omit [Field F] in +open Classical in +private theorem card_end {I : Type} [Fintype I] (p : I → G.V) (q : G.E → G.V) (v : G.V) : + Fintype.card {i : I ⊕ G.Bit // Sum.elim p (fun j => q j.1) i = v} = + Fintype.card {i // p i = v} + ∑ e, if q e = v then G.width e else 0 := by + rw [← G.card_bits (fun e => q e = v)] + simp only [Fintype.card_subtype, card_filter, Fintype.sum_sum_type, Sum.elim_inl, Sum.elim_inr] + congr! + +open Classical in +/-- The arity of type `ℕ` for the given inputs. -/ +def arity (v : G.V) : ℕ := + Fintype.card {i // G.left i = v} + Fintype.card {i // G.right i = v} + + (∑ e, if G.src e = v then G.width e else 0) + (∑ e, if G.dst e = v then G.width e else 0) + +open Classical in +theorem arity_diagram (v : G.V) : G.diagram.arity v = G.arity v := by + rw [Diagram.arity_ofLocal] + unfold incoming outgoing arity + rw [G.card_end, G.card_end] + omega + +open Classical in +theorem divisible (v w : G.V) (u : ℕ) (h : ∀ e, G.src e = v → G.dst e = w → u ∣ G.width e) : + u ∣ Fintype.card {i : G.diagram.E // G.diagram.source i = v ∧ G.diagram.target i = w} := by + rw [show Fintype.card {i : G.diagram.E // G.diagram.source i = v ∧ G.diagram.target i = w} = + ∑ e, if G.src e = v ∧ G.dst e = w then G.width e else 0 from + G.card_bits (fun e => G.src e = v ∧ G.dst e = w)] + apply dvd_sum + intro e _ + split_ifs with he + · exact h e he.1 he.2 + · exact dvd_zero _ + +end Bundled +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Host.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Host.lean new file mode 100644 index 0000000000..eb2d09f3d9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Host.lean @@ -0,0 +1,1013 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Load +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Sharing + +/-! # Placing a bit-encoded, degree-reduced network on a block host -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +open Finset Packing + +variable {F V : Type} [Field F] [Fintype V] {a b : Wire} {d h u : ℕ} + {G : Bundled F a b} {T : Trie V d} (H : Fanout G T (Cell h)) + +open Classical in +/-- Computes the fixed by the application `T.frozen (H.site v).1`. -/ +def fixed (v : G.V) := T.frozen (H.site v).1 + +open Classical in +/-- The value specified by `(∀ i, H.fixed (G.left i)) ∧ (∀ i, H.fixed (G.right i))`. -/ +def exterior := (∀ i, H.fixed (G.left i)) ∧ (∀ i, H.fixed (G.right i)) + +open Classical in +/-- Builds `Freeze H.route.net.diagram where frozen j` with the specified `frozen`, `exterior`, +`rintro`. -/ +abbrev freeze (he : H.exterior) : Freeze H.route.net.diagram where + frozen j := T.fixed (H.place j).1 + exterior := by + rintro (q|q) + · exact he.1 q + · exact he.2 q + separate i := T.separate (H.edges i.1).2 + +open Classical in +/-- Builds `(H.freeze he).Frame (Node V d) h where place` with the specified `place`, `frozen`, +`keep`, `ns`. -/ +abbrev frame (he : H.exterior) : (H.freeze he).Frame (Node V d) h where + place := H.place + frozen := T.fixed + keep _ := Iff.rfl + N := T.adj + C := T.core + ns _ _ := T.adj_symm + cs _ _ := T.core_symm + sub _ := filter_subset _ _ + group i := (H.edges i.1).1 + edge i := mem_filter.mpr ⟨(H.edges i.val.1).2, i.property⟩ + full i := (H.edges i.1).2 + +open Classical in +/-- The floor charge is paid once even for unused relay positions. -/ +abbrev term (he : H.exterior) (hw : ∀ e, u ∣ G.width e) : Rounds.LocalTerm F a b h u where + V := Node V d + diagram := H.route.net.diagram + freeze := H.freeze he + frame := H.frame he + one := H.injective + width v w := H.route.net.divisible v w u (fun e _ _ => hw e.1) + charge v := H.route.net.arity v + (u : ℝ) + cover v := by rw [Bundled.arity_diagram]; exact le_add_of_nonneg_right (by positivity) + floor v := le_add_of_nonneg_left (by positivity) + +variable (he : H.exterior) (hw : ∀ e, u ∣ G.width e) + +open Classical in +theorem eval_term : (H.term he hw).diagram.eval = G.eval := by + rw [Bundled.eval_diagram, Routes.eval_net] + +open Classical in +/-- The subtype of `v` satisfying `H.fixed v`. -/ +abbrev Frozen := {v // H.fixed v} +open Classical in +/-- The subtype of `v` satisfying `¬ H.fixed v`. -/ +abbrev Mobile := {v // ¬ H.fixed v} + +open Classical in +/-- Reindexes `H.Frozen` and `(H.freeze he).Fixed where toFun v` by an equivalence. -/ +def fixedEquiv : H.Frozen ≃ (H.freeze he).Fixed where + toFun v := ⟨.inl v.val, v.property⟩ + invFun + | ⟨.inl v, hv⟩ => ⟨v, hv⟩ + | ⟨.inr _, hv⟩ => False.elim hv + left_inv _ := rfl + right_inv := by + rintro ⟨v | v, hv⟩ + · rfl + · exact False.elim hv + +open Classical in +/-- In the case `.inl v`, this construction gives `⟨.inl v.val, v.property⟩`. -/ +def coreEquiv : H.Mobile ⊕ Relay G.V d ≃ (H.freeze he).Core where + toFun + | .inl v => ⟨.inl v.val, v.property⟩ + | .inr v => ⟨.inr v, fun h => h⟩ + invFun + | ⟨.inl v, hv⟩ => .inl ⟨v, hv⟩ + | ⟨.inr v, _⟩ => .inr v + left_inv := by rintro (v | v) <;> rfl + right_inv := by rintro ⟨v | v, _⟩ <;> rfl + +open Classical in +theorem old_charge (v : G.V) : (H.term he hw).charge (.inl v) = G.arity v + (u : ℝ) := by + change (H.route.net.arity (.inl v) : ℝ) + u = _ + rw [Routes.old_arity] + +open Classical in +theorem core_max {B : ℝ} (hB : 0 ≤ B) (hcore : ∀ v : H.Mobile, G.arity v.val ≤ B) + (hties : ∀ v w : H.Frozen, G.ties v.val w.val ≤ B) (v : (H.freeze he).Core) : + (H.term he hw).charge v.val ≤ 2 * B + u := by + obtain ⟨v|v, hv⟩ := v + · rw [old_charge] + have := hcore ⟨v, hv⟩ + change (G.arity v : ℝ) ≤ B at this + linarith + · have hh : (H.route.net.arity (.inr v) : ℝ) ≤ 2 * B := by + by_cases h : H.fixed v.1 + · obtain ⟨w, hw⟩ := H.frozen_relay v h + have hb : (G.ties v.1 w : ℝ) ≤ B := by + by_cases ht : H.fixed w + · exact hties ⟨v.1, h⟩ ⟨w, ht⟩ + · exact (Nat.cast_le.mpr (G.ties_le _ w)).trans (hcore ⟨w, ht⟩) + exact (show (H.route.net.arity (.inr v) : ℝ) + ≤ 2 * (G.ties v.1 w : ℝ) by exact_mod_cast hw).trans + (by gcongr) + · exact (show (H.route.net.arity (.inr v) : ℝ) ≤ 2 * (G.arity v.1 : ℝ) by + exact_mod_cast H.relay_le v).trans (mul_le_mul_of_nonneg_left (hcore ⟨v.1, + h⟩) (by norm_num)) + exact add_le_add_left hh _ + +open Classical in +theorem core_sum : + (∑ v : (H.freeze he).Core, (H.term he hw).charge v.val) = + (∑ v : H.Mobile, ((G.arity v.val : ℝ) + u)) + + 4 * (d + 1) * (∑ e, (G.width e : ℝ)) + Fintype.card (Relay G.V d) * (u : ℝ) := by + rw [← (H.coreEquiv he).sum_comp, Fintype.sum_sum_type] + change (∑ v : H.Mobile, (H.term he hw).charge (.inl v.val)) + + (∑ v : Relay G.V d, ((H.route.net.arity (.inr v) : ℝ) + u)) = _ + have ht : (∑ v, (H.route.net.arity (.inr v) : ℝ)) = 4 * (d + 1) * (∑ e, (G.width e : ℝ)) := by + exact_mod_cast H.total + simp only [Routes.old_arity, sum_add_distrib, sum_const, card_univ, nsmul_eq_mul, ht, add_assoc] + +open Classical in +theorem frozen_sum (f : ℝ → ℝ) : + (∑ v : (H.freeze he).Fixed, f ((H.term he hw).charge v.val)) = + ∑ v : H.Frozen, f (G.arity v.val + (u : ℝ)) := by + rw [← (H.fixedEquiv he).sum_comp] + exact sum_congr rfl (fun v _ => congrArg f (old_charge H he hw v.val)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +end + +/- +# Padding before routing + +Round each bundle once. Routing afterwards preserves divisibility, +including when several bundles share a tree edge. The rounding cost is +bounded in terms of the number of incident bundles. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +variable {F V I : Type} {a b : Wire} + +namespace Bundled +variable (G : Bundled F a b) (u : ℕ) + +open Classical in +/-- Embeds `G.state e` into `(Fin (Diagram.padWidth u (G.width e)) → Bool) where toFun s i`. -/ +def paddedCode (e : G.E) : G.state e ↪ (Fin (Diagram.padWidth u (G.width e)) → Bool) where + toFun s i := if h : i.val < G.width e then G.code e s ⟨i.val, h⟩ else false + inj' x y h := by + apply (G.code e).injective + funext i + simpa using congrFun h (Fin.castLE (Diagram.le_padWidth u (G.width e)) i) + +open Classical in +/-- Uses `{ G with width := fun e => Diagram.padWidth u (G.width e), code := G.paddedCode u }` +as the representation. -/ +abbrev pad : Bundled F a b := + { G with width := fun e => Diagram.padWidth u (G.width e), code := G.paddedCode u } + +open Classical in +theorem eval_pad [Field F] : (G.pad u).eval = G.eval := rfl + +open Classical in +theorem divisible_pad (hu : 0 < u) (e : G.E) : u ∣ (G.pad u).width e := + Diagram.dvd_padWidth hu _ + +open Classical in +/-- The quantity computed by `(∑ e, if G.src e = v then 1 else 0) + (∑ e, if G.dst e = v then 1 +else 0)`. -/ +def degree (v : G.V) := + (∑ e, if G.src e = v then 1 else 0) + (∑ e, if G.dst e = v then 1 else 0) + +open Classical in +private theorem round_le (p q : G.E → Prop) [DecidablePred p] [DecidablePred q] + (h : ∀ e, p e → q e) : + (∑ e, if p e then Diagram.padWidth u (G.width e) else 0) ≤ + (∑ e, if p e then G.width e else 0) + u * ∑ e, if q e then 1 else 0 := by + rw [mul_sum, ← sum_add_distrib] + apply sum_le_sum + intro e _ + by_cases he : p e + · simpa [he, h e he] using Diagram.padWidth_le u (G.width e) + · simp [he] + +open Classical in +theorem arity_pad (v : G.V) : (G.pad u).arity v ≤ G.arity v + u * G.degree v := by + have hs := G.round_le u (fun e => G.src e = v) _ (fun _ h => h) + have ht := G.round_le u (fun e => G.dst e = v) _ (fun _ h => h) + simp only [arity, pad, degree, mul_add] + omega + +open Classical in +theorem ties_pad (v w : G.V) : (G.pad u).ties v w ≤ G.ties v w + u * G.degree v := by + have hs := G.round_le u (fun e => G.src e = v ∧ G.dst e = w) (fun e => G.src e = v) + (fun _ h => h.1) + have ht := G.round_le u (fun e => G.dst e = v ∧ G.src e = w) (fun e => G.dst e = v) + (fun _ h => h.1) + simp only [ties, pad, degree, mul_add] + omega + +open Classical in +theorem total_pad : ∑ e, (G.pad u).width e ≤ (∑ e, G.width e) + Fintype.card G.E * u := by + simpa [sum_add_distrib] using sum_le_sum (fun e (_ : e ∈ univ) + => Diagram.padWidth_le u (G.width e)) + +end Bundled + +namespace Fanout +variable {G : Bundled F a b} {d : ℕ} {T : Trie V d} + +open Classical in +/-- Uses `⟨H.site, H.one, H.near, H.group⟩` as the representation. -/ +abbrev pad (H : Fanout G T I) (u : ℕ) : Fanout (G.pad u) T I := + ⟨H.site, H.one, H.near, H.group⟩ + +variable [Field F] [Fintype V] {h u : ℕ} (H : Fanout G T (Packing.Cell h)) + +open Classical in +/-- The value specified by `(H.pad u).term he (G.divisible_pad u hu)`. -/ +abbrev finish (he : H.exterior) (hu : 0 < u) : Rounds.LocalTerm F a b h u := + (H.pad u).term he (G.divisible_pad u hu) + +open Classical in +theorem eval_finish (he : H.exterior) (hu : 0 < u) : (H.finish he hu).diagram.eval = G.eval := + ((H.pad u).eval_term he _).trans (G.eval_pad u) + +end Fanout +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- Pre-routing estimates and the final common power of the scale. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +open Finset Rounds Packing + +variable {F V : Type} [Field F] [Fintype V] {a b : Wire} {c d h D T R g : ℕ} {W : ℝ} + {G : Bundled F a b} {S : Trie V (c * d)} (H : Fanout G S (Cell h)) + +open Classical in +/-- The quantity computed by `64 * (c + ℓ + 1) ^ 2`. -/ +def exponent (c ℓ : ℕ) := 64 * (c + ℓ + 1) ^ 2 + +open Classical in +/-- All charges before routing and rounding. Only direct contacts between +frozen stations need a bound beyond the individual core arities. -/ +structure Caps (P : Input F a b h D T R g W) (ℓ : ℕ) : Prop where + cells : Fintype.card V ≤ D ^ c * Fintype.card P.V + size : ((Fintype.card G.V : ℝ) + Fintype.card G.E) * T ≤ (D : ℝ) ^ c * W + degree : ∀ v, G.degree v ≤ D ^ c + frozenCount : (Fintype.card H.Frozen : ℝ) * D * T ≤ c * W + frozenMax : ∀ v : H.Frozen, (G.arity v.val : ℝ) ≤ c * (D : ℝ) * T + frozenSquare : (∑ v : H.Frozen, (G.arity v.val : ℝ) ^ 2) ≤ c * W * T + coreMax : ∀ v : H.Mobile, (G.arity v.val : ℝ) ≤ T / (D : ℝ) ^ (ℓ + 2) + ties : ∀ v w : H.Frozen, (G.ties v.val w.val : ℝ) ≤ T / (D : ℝ) ^ (ℓ + 2) + coreSum : (∑ v : H.Mobile, (G.arity v.val : ℝ)) ≤ c * W * (1 + (d : ℝ)) + edges : (∑ e, (G.width e : ℝ)) ≤ c * W * (1 + (d : ℝ)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +end + +/- # Counting incidences and bundle widths -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Bundled +open Finset + +variable {F V E : Type} {a b : Wire} + +open Classical in +private theorem push_total [Fintype V] [Fintype E] (f : E → V) (w : E → ℕ) : + (∑ v, ∑ e, if f e = v then w e else 0) = ∑ e, w e := by + rw [sum_comm] + simp + +variable (G : Bundled F a b) + +open Classical in +theorem degree_total : ∑ v, G.degree v = 2 * Fintype.card G.E := by + unfold degree + rw [sum_add_distrib, push_total, push_total] + simp [two_mul] + +open Classical in +theorem arity_total : ∑ v, G.arity v = wd a + wd b + 2 * ∑ e, G.width e := by + unfold arity + simp only [Fintype.card_subtype, card_filter, sum_add_distrib, push_total, sum_const, card_univ, + card_slots, smul_eq_mul, mul_one] + ring + +open Classical in +/-- Counting the arities just at source hubs covers all wires. -/ +theorem width_le_source [Fintype V] (f : V → G.V) (h : ∀ e, G.src e ∈ Set.range f) : + ∑ e, G.width e ≤ ∑ v, G.arity (f v) := by + choose j hj using h + rw [← push_total j G.width] + apply sum_le_sum + intro v _ + calc + _ ≤ ∑ e, if G.src e = f v then G.width e else 0 := by + apply sum_le_sum + intro e _ + by_cases he : j e = v + · rw [← hj e, he, ite_eq_left rfl, ite_eq_left rfl] + · rw [ite_eq_right he]; exact Nat.zero_le _ + _ ≤ G.arity (f v) := by unfold arity; omega + +open Classical in +theorem count_le_source [Fintype V] (f : V → G.V) (h : ∀ e, G.src e ∈ Set.range f) : + Fintype.card G.E ≤ ∑ v, G.degree (f v) := by + choose j hj using h + rw [show Fintype.card G.E = ∑ _ : G.E, 1 by simp, ← push_total j (fun _ => 1)] + apply sum_le_sum + intro v _ + calc + _ ≤ ∑ e, if G.src e = f v then 1 else 0 := by + apply sum_le_sum + intro e _ + by_cases he : j e = v + · rw [← hj e, he, ite_eq_left rfl, ite_eq_left rfl] + · rw [ite_eq_right he]; exact Nat.zero_le _ + _ ≤ G.degree (f v) := Nat.le_add_right _ _ + +open Classical in +theorem sum_mobile (p : G.V → Prop) [DecidablePred p] (hl : ∀ i, ¬ p (G.left i)) + (hr : ∀ i, ¬ p (G.right i)) : ∑ v : {v // p v}, G.arity v.val ≤ 2 * ∑ e, G.width e := by + let cost (v : G.V) := (∑ e, if G.src e = v then G.width e else 0) + + (∑ e, if G.dst e = v then G.width e else 0) + have he (v : {v // p v}) : G.arity v.val = cost v.val := by + have h₁ (i) : G.left i ≠ v.val := fun h => hl i (h.symm ▸ v.property) + have h₂ (i) : G.right i ≠ v.val := fun h => hr i (h.symm ▸ v.property) + simp [arity, cost, h₁, h₂] + simp_rw [he] + calc + _ = ∑ v ∈ univ.filter p, cost v := (sum_subtype _ (by simp) cost).symm + _ ≤ ∑ v, cost v := sum_le_sum_of_subset (subset_univ _) + _ = _ := by rw [show (∑ v, cost v) = _ from sum_add_distrib, push_total, push_total, two_mul] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Bundled +end + +/- # Loads of station legs and seams after splitting into chunks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset Packing Real + +open Classical in +/-- The quantity computed by `4 * sqrt ((M : ℝ) * r * e) + M`. -/ +def proxy (M r e : ℕ) := 4 * sqrt ((M : ℝ) * r * e) + M + +open Classical in +theorem proxy_nonneg (M r e : ℕ) : 0 ≤ proxy M r e := by unfold proxy; positivity + +open Classical in +theorem chunk_le {M e : ℕ} (r : ℕ) (s : Chunk.Shape M e) (j : Fin M) : + Chunk.width r (s.val j).val * sqrt M ≤ proxy M r e := by + have h : (s.val j).val ≤ e := Nat.le_of_lt_succ (s.val j).isLt + have hM : 1 ≤ (M : ℝ) := by exact_mod_cast (show 1 ≤ M by have := j.isLt; omega) + have hm : sqrt (M : ℝ) ≤ M := sqrt_le_iff.mpr ⟨by positivity, by nlinarith⟩ + calc + _ ≤ (4 * sqrt ((r : ℝ) * e) + 1) * sqrt M := by + gcongr + refine (Chunk.width_le _ _).trans ?_ + gcongr + _ ≤ _ := by + unfold proxy + rw [mul_assoc (M : ℝ), sqrt_mul (by positivity : (0 : ℝ) ≤ M)] + linarith + +variable {F T X E V : Type} [Field F] [Fintype E] [Fintype V] {M r t : ℕ} + (C : V → Surface.Cell F (M * r) (M * t) T E X) (d : E → ℕ) {a b : Wire} + +open Classical in +/-- Computes the seam width by the application `proxy M r (d e)`. -/ +def seamWidth (_ : V → Surface.Cell F (M * r) (M * t) T E X) (d : E → ℕ) (e : E) := + proxy M r (d e) + +open Classical in +/-- The quantity computed by `proxy M r (item C i).a + proxy M t (item C i).b`. -/ +def legWidth (i : Place C) := proxy M r (item C i).a + proxy M t (item C i).b + +omit [Field F] [Fintype E] [Fintype V] in +open Classical in +theorem legWidth_nonneg (i : Place C) : 0 ≤ legWidth C i := + add_nonneg (proxy_nonneg ..) (proxy_nonneg ..) + +namespace Backdrop + +variable {C d} (B : Backdrop C a b) (p : Profile C d) (P : ℕ) + +open Classical in +/-- The value specified by `(B.emit p P p.widths).net`. -/ +abbrev emitted := (B.emit p P p.widths).net + +open Classical in +/-- The quantity computed by `push B.src (seamWidth C d) v + push B.dst (seamWidth C d) v + push +Sigma.fst (legWidth C) v`. -/ +def chamberLoad (d : E → ℕ) (v : V) := + push B.src (seamWidth C d) v + push B.dst (seamWidth C d) v + + push Sigma.fst (legWidth C) v + +open Classical in +theorem chamberA (v : V) (j : Fin M) : + (B.emitted p P).arity (.inr (.inl (v, j))) = + (∑ e, if B.src e = v then p.widths.seam (e, j) else 0) + + (∑ e, if B.dst e = v then p.widths.seam (e, j) else 0) + + ∑ i, if i.1 = v then p.widths.leg (.inl (i, j)) else 0 := by + rw [Attach.right_arity] + simp [Bundled.arity, chambers, seamEnd, socket, Grid.map, Fintype.sum_sum_type, + Fintype.sum_prod_type, ite_and] + +open Classical in +theorem chamberB (v : V) (j : Fin M) : + (B.emitted p P).arity (.inr (.inr (v, j))) = + ∑ i, if i.1 = v then p.widths.leg (.inr (i, j)) else 0 := by + rw [Attach.right_arity] + simp [Bundled.arity, chambers, seamEnd, socket, Grid.map, Fintype.sum_sum_type, + Fintype.sum_prod_type, ite_and] + +open Classical in +theorem station (v : B.base.V) : + (B.emitted p P).arity (.inl v) = B.base.arity v + + ∑ i, if B.owner i = v then + (∑ j, p.widths.leg (.inl (i, j))) + (∑ j, p.widths.leg (.inr (i, j))) else 0 := by + rw [Attach.left_arity] + simp only [arm, Grid.point, Fintype.sum_sum_type, Fintype.sum_prod_type, Sum.elim_inl, + Sum.elim_inr] + rw [← sum_add_distrib] + congr 1 + apply sum_congr rfl + intro i _ + by_cases h : B.owner i = v <;> simp [h] + +open Classical in +private theorem push_est {Y Z : Type} [Fintype Y] (loc : Y → Z) (v : Z) (w : Y → ℕ) + (cost : Y → ℝ) (x : ℝ) (hw : ∀ i, w i * x ≤ cost i) : + (∑ i, if loc i = v then w i else 0 : ℕ) * x ≤ push loc cost v := by + rw [Nat.cast_sum, sum_mul] + apply sum_le_sum + intro i _ + by_cases h : loc i = v <;> simp [h, hw i] + +open Classical in +theorem station_le (v : B.base.V) : ((B.emitted p P).arity (.inl v) : ℝ) ≤ + B.base.arity v + push B.owner (legWidth C) v := by + rw [station, Nat.cast_add] + gcongr + rw [← mul_one (↑(∑ i, if B.owner i = v then + (∑ j, p.widths.leg (.inl (i, j))) + (∑ j, p.widths.leg (.inr (i, j))) else 0) : ℝ)] + apply push_est + intro i + rw [mul_one, Nat.cast_add, Nat.cast_sum, Nat.cast_sum] + exact add_le_add (Chunk.total_width r (p.1 (.inr i))) (Chunk.total_width t (p.2 i)) + +open Classical in +theorem chamber_le (s : Grid M V) : + (B.emitted p P).arity (.inr s) * sqrt M ≤ B.chamberLoad d (Grid.point s) := by + have h (v : V) (j : Fin M) (f : E → V) := + push_est f v (fun e => p.widths.seam (e, j)) (seamWidth C d) (sqrt M) + (fun e => chunk_le r (p.1 (.inl e)) j) + rcases s with ⟨v, j⟩ | ⟨v, j⟩ + · rw [chamberA, Nat.cast_add, Nat.cast_add, add_mul, add_mul] + refine add_le_add (add_le_add (h v j B.src) (h v j B.dst)) ?_ + apply push_est + intro i + exact (chunk_le r (p.1 (.inr i)) j).trans (le_add_of_nonneg_right (proxy_nonneg ..)) + · rw [chamberB] + have hn (f : E → V) := push_nonneg f (seamWidth C d) (fun _ => proxy_nonneg ..) v + refine le_trans ?_ (le_add_of_nonneg_left (add_nonneg (hn B.src) (hn B.dst))) + apply push_est + intro i + exact (chunk_le t (p.2 i) j).trans (le_add_of_nonneg_left (proxy_nonneg ..)) + +open Classical in +theorem emitted_width : + (∑ e, ((B.emitted p P).width e : ℝ)) ≤ + (∑ e, (B.base.width e : ℝ)) + (∑ e, seamWidth C d e) + ∑ i, legWidth C i := by + simp only [emitted, Attach.net, Fintype.sum_sum_type, Sum.elim_inl, Sum.elim_inr, + Fintype.sum_prod_type] + rw [← sum_add_distrib, ← add_assoc] + refine add_le_add (add_le_add le_rfl (sum_le_sum ?_)) (sum_le_sum ?_) + · exact fun e _ => Chunk.total_width r (p.1 (.inl e)) + · exact fun i _ => add_le_add (Chunk.total_width r (p.1 (.inr i))) (Chunk.total_width t (p.2 i)) + +open Classical in +theorem emitted_total : (∑ v, ((B.emitted p P).arity v : ℝ)) ≤ + (∑ v, (B.base.arity v : ℝ)) + 2 * ((∑ e, seamWidth C d e) + ∑ i, legWidth C i) := by + rw [← Nat.cast_sum, ← Nat.cast_sum, Bundled.arity_total, Bundled.arity_total] + push_cast + linarith only [B.emitted_width p P] + +end Backdrop +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- +# Host slots for a sphere expansion + +Within each occupied cell reserve slots for stations of either status, +two ordinary hubs, and the two forms in each chunk. The larger host is +independent of the profile or the active station list. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +open Finset Packing Rounds + +variable {F U X E V K : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) {h D T R g : ℕ} {W : ℝ} (P : Input F a b h D T R g W) + +open Classical in +/-- Shared across the independent block occurrences of a host. -/ +structure Steering {V : Type} (adj : V → Finset V) (n : ℕ) where + /-- The rank of type `V → V → Fin (n + 1)`. -/ + rank : V → V → Fin (n + 1) + inject : ∀ v, Set.InjOn (rank v) (insert v (adj v) : Finset V) + +open Classical in +/-- The any of type `Steering adj n` for the given inputs. -/ +def Steering.any {V : Type} (adj : V → Finset V) (n : ℕ) (h : ∀ v, (adj v).card ≤ n) : + Steering adj n := by + let f (v : V) : ↥(insert v (adj v)) ↪ Fin (n + 1) := + Classical.choice (Function.Embedding.nonempty_of_card_le (by + rw [Fintype.card_coe, Fintype.card_fin] + exact (card_insert_le ..).trans (Nat.add_le_add_right (h v) 1))) + refine ⟨fun v w => if h : w ∈ insert v (adj v) then f v ⟨w, h⟩ else 0, ?_⟩ + intro v x hx y hy he + change x ∈ insert v (adj v) at hx + change y ∈ insert v (adj v) at hy + simp only [dite_eq_left hx, dite_eq_left hy] at he + exact congrArg Subtype.val ((f v).injective he) + +open Classical in +/-- The seam contacts respect the input blocks. -/ +structure Geo (k : ℕ) where + /-- Embeds the coordinates as `V ↪ P.V × Cell h`. -/ + site : V ↪ P.V × Cell h + near : ∀ e, let p := site (S.src e); let q := site (S.dst e) + p.2 = q.2 ∧ (q.1 = p.1 ∨ q.1 ∈ P.adj p.1) + count : ∀ v, (C v).stations.length ≤ D ^ k + chunks : M ≤ D ^ k + degree : g ≤ D ^ k + /-- The `Geo` component of type `Place C → Prop`. -/ + frozen : Place C → Prop + left : ∀ i, frozen (S.left i) + right : ∀ i, frozen (S.right i) + /-- The `Geo` component of type `Steering P.adj (D ^ k)`. -/ + steer : Steering P.adj (D ^ k) := Steering.any _ _ (fun i => (P.degree i).trans degree) + +open Classical in +/-- Indexes the position by the coordinates of `S.Vertex ⊕ Grid M V`. -/ +abbrev Position := S.Vertex ⊕ Grid M V + +open Classical in +/-- In the case `.inl (.inl i)`, this construction gives `i.1`. -/ +def home : S.Position → V + | .inl (.inl i) => i.1 + | .inl (.inr (.inl v)) | .inl (.inr (.inr v)) => v + | .inr s => Grid.point s + +open Classical in +/-- Indexes the slot by the coordinates of `(Bool × Fin (D ^ k)) ⊕ (Bool ⊕ (Fin M ⊕ Fin M))`. -/ +abbrev Slot (M D k : ℕ) := (Bool × Fin (D ^ k)) ⊕ (Bool ⊕ (Fin M ⊕ Fin M)) + +open Classical in +/-- The two cases impose `i.1 = true` and `False`, respectively. -/ +def frozenSlot {M D k : ℕ} : Slot M D k → Prop + | .inl i => i.1 = true + | .inr _ => False + +open Classical in +/-- The quantity computed by `8 * (k + 1)`. -/ +def radius (k : ℕ) := 8 * (k + 1) + +namespace Geo + +variable {S P} {k : ℕ} (G : S.Geo P k) + +open Classical in +/-- In the case `.inl (.inl i)`, this construction gives `.inl (decide (G.frozen i), Fin.castLE +(G.count i.1) i.2)`. -/ +def slot : S.Position → Slot M D k + | .inl (.inl i) => .inl (decide (G.frozen i), Fin.castLE (G.count i.1) i.2) + | .inl (.inr (.inl _)) => .inr (.inl false) + | .inl (.inr (.inr _)) => .inr (.inl true) + | .inr (.inl p) => .inr (.inr (.inl p.2)) + | .inr (.inr p) => .inr (.inr (.inr p.2)) + +open Classical in +/-- The value specified by `(((G.site (S.home x)).1, G.slot x), (G.site (S.home x)).2)`. -/ +def place (x : S.Position) : (P.V × Slot M D k) × Cell h := + (((G.site (S.home x)).1, G.slot x), (G.site (S.home x)).2) + +open Classical in +theorem one : Function.Injective G.place := by + intro x y h + have he : S.home x = S.home y := G.site.injective (congrArg (fun p => (p.1.1, p.2)) h) + have hf : G.slot x = G.slot y := congrArg (fun p => p.1.2) h + rcases x with ((⟨v, i⟩ | v | v) | (⟨v, i⟩ | ⟨v, i⟩)) <;> + rcases y with ((⟨u, j⟩ | u | u) | (⟨u, j⟩ | ⟨u, j⟩)) + all_goals simp only [slot, Sum.inl.injEq, Sum.inr.injEq, Prod.mk.injEq, reduceCtorEq] at hf + all_goals change v = u at he + all_goals subst u + · have : i = j := Fin.ext (congrArg (fun x : Fin (D ^ k) => x.val) hf.2) + rw [this] + · rfl + · rfl + · rw [hf] + · rw [hf] + +open Classical in +/-- The value specified by `insert p.1 (P.adj p.1) ×ˢ (univ : Finset (Slot M D k))`. -/ +def neighbors (_ : S.Geo P k) (p : P.V × Slot M D k) := + insert p.1 (P.adj p.1) ×ˢ (univ : Finset (Slot M D k)) + +open Classical in +theorem symmetric (x y : P.V × Slot M D k) (h : x ∈ G.neighbors y) : y ∈ G.neighbors x := by + simp only [neighbors, mem_product, mem_univ, and_true, mem_insert] at h ⊢ + exact h.imp Eq.symm (P.sym _ _) + +include G in +open Classical in +theorem slot_count (hD : 4 ≤ D) : Fintype.card (Slot M D k) ≤ 6 * D ^ k := by + simp only [Slot, Fintype.card_prod, Fintype.card_sum, Fintype.card_fin, Fintype.card_bool] + have := G.chunks + have : 1 ≤ D ^ k := Nat.one_le_pow _ _ (by omega) + omega + +open Classical in +theorem polynomial (hD : 4 ≤ D) (k : ℕ) : 64 * (D ^ k) ^ 3 ≤ D ^ radius k := by + calc + _ ≤ D ^ 3 * (D ^ k) ^ 3 := Nat.mul_le_mul_right _ (Nat.pow_le_pow_left hD 3) + _ = D ^ (3 + k * 3) := by rw [pow_add, pow_mul] + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by unfold radius; omega) + +include G in +open Classical in +theorem host_count (hD : 4 ≤ D) : + Fintype.card (P.V × Slot M D k) ≤ D ^ radius k * Fintype.card P.V := by + rw [Fintype.card_prod, mul_comm] + apply Nat.mul_le_mul_right + exact ((G.slot_count hD).trans (Nat.mul_le_mul (by decide : 6 + ≤ 64) (Nat.le_self_pow (by decide : 3 ≠ 0) _))).trans + (polynomial hD k) + +open Classical in +theorem neighbor_count (hD : 4 ≤ D) (v : P.V × Slot M D k) : + (G.neighbors v).card ≤ D ^ radius k := by + rw [neighbors, card_product, card_univ] + have h₁ := (card_insert_le v.1 (P.adj v.1)).trans (Nat.add_le_add_right ((P.degree _).trans + G.degree) 1) + have hp : 1 ≤ D ^ k := Nat.one_le_pow _ _ (by omega) + calc + _ ≤ (D ^ k + 1) * (6 * D ^ k) := Nat.mul_le_mul h₁ (G.slot_count hD) + _ ≤ 64 * (D ^ k) ^ 3 := by nlinarith [Nat.pow_le_pow_right hp (by decide : 2 ≤ 3)] + _ ≤ _ := polynomial hD k + +variable {d : ℕ} (hD : D = 2 ^ d) (hD' : 4 ≤ D) + +open Classical in +/-- Embeds `Fin (D ^ k + 1) × Slot M D k` into `Address (radius k * d)`. -/ +def steeringCode (hc : M ≤ D ^ k) : Fin (D ^ k + 1) × Slot M D k ↪ Address (radius k * d) := by + apply binaryCode + simp only [Slot, Fintype.card_prod, Fintype.card_sum, Fintype.card_fin, Fintype.card_bool] + rw [mul_comm (radius k), pow_mul, ←hD] + have hp : 1 ≤ D ^ k := Nat.one_le_pow _ _ (by omega) + calc + _ ≤ (D ^ k + 1) * (6 * D ^ k) := Nat.mul_le_mul_left _ (by omega) + _ ≤ 64 * (D ^ k) ^ 3 := by nlinarith [Nat.pow_le_pow_right hp (by decide : 2 ≤ 3)] + _ ≤ _ := polynomial hD' k + +open Classical in +/-- Builds `Trie (P.V × Slot M D k) (radius k * d) where near` with the specified `near`, +`symm`, `frozen`, `code`. -/ +abbrev tree : Trie (P.V × Slot M D k) (radius k * d) where + near := G.neighbors + symm := G.symmetric + frozen v := frozenSlot v.2 + code v w := steeringCode hD hD' G.chunks (G.steer.rank v.1 w.1, w.2) + inject v x hx y hy he := by + obtain ⟨he, hs⟩ := Prod.mk.inj ((steeringCode hD hD' G.chunks).injective he) + exact Prod.ext (G.steer.inject _ (mem_product.mp hx).1 (mem_product.mp hy).1 he) hs + +variable [Field F] [Fintype E] [Fintype V] [Fintype K] {e : E → ℕ} (p : Profile C e) (L : ℕ) + +open Classical in +theorem contacts (i : (S.backdrop.emitted p L).E) : + let s := G.place ((S.backdrop.emitted p L).src i) + let t := G.place ((S.backdrop.emitted p L).dst i) + s.2 = t.2 ∧ (t.1.1 = s.1.1 ∨ t.1.1 ∈ P.adj s.1.1) := by + rcases i with ⟨i, j|j|j⟩ | ⟨i, x⟩ | ⟨i, x⟩ | ⟨i, x⟩ + · exact ⟨rfl, .inl rfl⟩ + · exact G.near j.val + · exact ⟨rfl, .inl rfl⟩ + · exact G.near i + · exact ⟨rfl, .inl rfl⟩ + · exact ⟨rfl, .inl rfl⟩ + +open Classical in +/-- Builds `Fanout (S.backdrop.emitted p L) (G.tree hD hD') (Cell h) where site` with the +specified `site`, `one`, `group`, `near`. -/ +abbrev layout : Fanout (S.backdrop.emitted p L) (G.tree hD hD') (Cell h) where + site := G.place + one := G.one + group i := (G.contacts p L i).1 + near i := mem_product.mpr ⟨mem_insert.mpr (G.contacts p L i).2, mem_univ _⟩ + +open Classical in +theorem fixed_item (i : Place C) : + (G.layout hD hD' p L).fixed (.inl (.inl i)) ↔ G.frozen i := by + change decide (G.frozen i) = true ↔ _ + simp + +open Classical in +theorem external : (G.layout hD hD' p L).exterior := + ⟨fun i => (G.fixed_item hD hD' p L _).mpr (G.left i), + fun i => (G.fixed_item hD hD' p L _).mpr (G.right i)⟩ + +open Classical in +/-- Reindexes `{i // G.frozen i}` and `(G.layout hD hD' p L).Frozen where toFun i` by an +equivalence. -/ +def frozenEquiv : {i // G.frozen i} ≃ (G.layout hD hD' p L).Frozen where + toFun i := ⟨.inl (.inl i.val), (G.fixed_item hD hD' p L _).mpr i.property⟩ + invFun + | ⟨.inl (.inl i), hi⟩ => ⟨i, (G.fixed_item hD hD' p L _).mp hi⟩ + | ⟨.inl (.inr (.inl _)), hi⟩ | ⟨.inl (.inr (.inr _)), hi⟩ + | ⟨.inr (.inl _), hi⟩ | ⟨.inr (.inr _), hi⟩ => False.elim hi + left_inv _ := rfl + right_inv := by + rintro ⟨((i | v | v) | (v|v)), hi⟩ + · rfl + all_goals exact False.elim hi + +end Geo +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +end + +section +/- # Scale inequalities for the common routing host -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +open Finset + +variable {c d D T u ℓ C : ℕ} + +theorem exponent_bounds (hC : exponent c ℓ ≤ C) : + 3 * c + ℓ + 2 ≤ C ∧ 8 * (c + 1) ^ 2 ≤ C := by + unfold exponent at hC + constructor <;> nlinarith [Nat.zero_le (c * ℓ)] + +theorem host_bound (hD : D = 2 ^ d) (hD' : 4 ≤ D) (hC : exponent c ℓ ≤ C) : + (1 + (c * d + 1) * 2 ^ (c * d)) * D ^ c ≤ D ^ C ∧ (c * d + 1) * 2 ^ (c * d) ≤ (D ^ c) ^ 2 ∧ + max 3 (2 ^ (c * d)) ≤ D ^ C := by + have hc := (exponent_bounds hC).1 + have he : 2 ^ (c * d) = D ^ c := by rw [hD, ← pow_mul, mul_comm c] + have hp : 1 ≤ D ^ c := Nat.one_le_pow _ _ (by omega) + have hq : c * d + 1 ≤ D ^ c := by rw [← he]; exact Nat.lt_two_pow_self + have hr : (c * d + 1) * 2 ^ (c * d) ≤ (D ^ c) ^ 2 := by rw [he, pow_two]; gcongr + have h := Nat.pow_le_pow_right (by omega : 0 < D) (show 3 * c + 1 ≤ C by omega) + refine ⟨?_, hr, max_le ?_ ?_⟩ + · refine le_trans ?_ h + rw [pow_succ, mul_comm 3 c, pow_mul D c 3] + calc + _ ≤ (1 + (D ^ c) ^ 2) * D ^ c := by gcongr + _ ≤ (D ^ c) ^ 3 * 2 := by nlinarith [Nat.le_self_pow (by decide : 3 ≠ 0) (D ^ c)] + _ ≤ _ := Nat.mul_le_mul_left _ (by omega) + · exact (show 3 ≤ D by omega).trans (Nat.le_self_pow (by omega) _) + · rw [he] + exact Nat.pow_le_pow_right (by omega) (by omega) + +theorem padding_budget (hD : 4 ≤ D) (hC : exponent c ℓ ≤ C) (hs : u * D ^ C ≤ T) : + (u : ℝ) * ((D : ℝ) ^ c) ^ 3 ≤ T ∧ + ((u : ℝ) * ((D : ℝ) ^ c + 1)) * (4 * (D : ℝ) ^ ℓ) ≤ T := by + have hc := (exponent_bounds hC).1 + have hp : 1 ≤ D ^ c := Nat.one_le_pow _ _ (by omega) + have hb (n) (hn : n ≤ C) : u * D ^ n ≤ T := + (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) hn)).trans hs + have h₁ := hb (c * 3) (by omega) + rw [pow_mul] at h₁ + have h₂ : u * (D ^ c + 1) * (4 * D ^ ℓ) ≤ T := calc + _ ≤ u * (D ^ c * 2) * (4 * D ^ ℓ) := by gcongr; omega + _ = u * D ^ c * D ^ ℓ * 8 := by ring + _ ≤ u * D ^ c * D ^ ℓ * D ^ 2 := Nat.mul_le_mul_left _ (by nlinarith) + _ = u * D ^ (c + ℓ + 2) := by simp [pow_add, mul_assoc] + _ ≤ T := hb _ (by omega) + exact ⟨by exact_mod_cast h₁, by exact_mod_cast h₂⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +end + +/- +# Concentration after binary routing + +The square budget covers frozen charges. A logarithmic routing depth +multiplies the total core width; rounding every bundle and charging +unused slots consume only the allowed polynomial padding margin. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +open Finset Rounds Packing + +variable {F V : Type} [Field F] [Fintype V] {a b : Wire} {c d h D T R g u C ℓ : ℕ} {W : ℝ} + {G : Bundled F a b} {S : Trie V (c * d)} (H : Fanout G S (Cell h)) + (P : Input F a b h D T R g W) + +omit [Field F] in +open Classical in +private theorem charge_pad (h : H.Caps P ℓ) (u : ℕ) (v : G.V) : + ((G.pad u).arity v : ℝ) + u ≤ G.arity v + (u : ℝ) * ((D : ℝ) ^ c + 1) := by + have hh : (G.pad u).arity v ≤ G.arity v + u * D ^ c := + (G.arity_pad u v).trans (by gcongr; exact h.degree v) + have ht : ((G.pad u).arity v : ℝ) ≤ G.arity v + u * (D : ℝ) ^ c := by exact_mod_cast hh + linarith + +omit [Field F] in +open Classical in +private theorem size_pad (h : H.Caps P ℓ) (hD : 4 ≤ D) (hC : exponent c ℓ ≤ C) + (hs : u * D ^ C ≤ T) : + ((Fintype.card G.V : ℝ) + Fintype.card G.E) * u * ((D : ℝ) ^ c) ^ 2 ≤ W := by + have hp : 0 < (D : ℝ) ^ c := by positivity + apply (mul_le_mul_iff_left₀ hp).mp + calc + _ = ((Fintype.card G.V : ℝ) + Fintype.card G.E) * (u * ((D : ℝ) ^ c) ^ 3) := by ring + _ ≤ ((Fintype.card G.V : ℝ) + Fintype.card G.E) * T := by + gcongr + exact (padding_budget hD hC hs).1 + _ ≤ _ := h.size.trans_eq (mul_comm _ _) + +open Classical in +private theorem sum_finish (hcap : H.Caps P ℓ) (hD : D = 2 ^ d) (hD' : 4 ≤ D) (hc : 1 ≤ c) + (hC : exponent c ℓ ≤ C) (hu : 0 < u) (hs : u * D ^ C ≤ T) (he : H.exterior) : + (∑ v : (H.finish he hu).freeze.Core, (H.finish he hu).charge v.val) ≤ C * W * (1 + (d : ℝ)) ^ 2 + := by + let p := (D : ℝ) ^ c + have hp : 1 ≤ p := one_le_pow₀ (by exact_mod_cast (show 1 ≤ D by omega)) + have ht := H.size_pad P hcap hD' hC hs + have hW : 0 ≤ W := le_trans (by positivity) ht + have hv : (Fintype.card G.V : ℝ) * u * p ^ 2 ≤ W := le_trans (by gcongr; simp) ht + have hj : (Fintype.card G.E : ℝ) * u ≤ W := calc + _ ≤ (Fintype.card G.E : ℝ) * u * p ^ 2 := le_mul_of_one_le_right (by positivity) (one_le_pow₀ + hp) + _ ≤ _ := le_trans (by gcongr; simp) ht + have hrelay : (Fintype.card (Relay G.V (c * d)) : ℝ) * u ≤ W := by + have hh : Fintype.card (Relay G.V (c * d)) ≤ Fintype.card G.V * (D ^ c) ^ 2 := by + simp only [Relay, Address, Fintype.card_prod, Fintype.card_fun, Fintype.card_fin, + Fintype.card_bool] + exact Nat.mul_le_mul_left _ (host_bound hD hD' hC).2.1 + calc + _ ≤ (Fintype.card G.V : ℝ) * p ^ 2 * u := by gcongr; unfold p; exact_mod_cast hh + _ = (Fintype.card G.V : ℝ) * u * p ^ 2 := by ring + _ ≤ _ := hv + have hold : (∑ v : H.Mobile, (((G.pad u).arity v.val : ℝ) + u)) ≤ + c * W * (1 + (d : ℝ)) + 2 * W := by + have hb : (Fintype.card H.Mobile : ℝ) ≤ Fintype.card G.V := + Nat.cast_le.mpr (Fintype.card_subtype_le _) + calc + _ ≤ ∑ v : H.Mobile, ((G.arity v.val : ℝ) + u * (p + 1)) := + sum_le_sum fun v _ => H.charge_pad P hcap u v.val + _ = (∑ v : H.Mobile, (G.arity v.val : ℝ)) + Fintype.card H.Mobile * (u * (p + 1)) := by + simp [sum_add_distrib] + _ ≤ c * W * (1 + (d : ℝ)) + Fintype.card G.V * (u * (2 * p ^ 2)) := by + gcongr + · exact hcap.coreSum + · nlinarith only [hp] + _ ≤ _ := by linarith only [hv] + have hsum : (∑ e, ((G.pad u).width e : ℝ)) ≤ c * W * (1 + (d : ℝ)) + W := by + have hb := G.total_pad u + have hh : (∑ e, ((G.pad u).width e : ℝ)) ≤ (∑ e, (G.width e : ℝ)) + Fintype.card G.E * (u : ℝ) + := by + exact_mod_cast hb + exact hh.trans (add_le_add hcap.edges hj) + have hh := (H.pad u).core_sum he (G.divisible_pad u hu) + refine hh.trans_le ?_ + push_cast + calc + _ ≤ (c * W * (1 + (d : ℝ)) + 2 * W) + 4 * (c * d + 1) * (c * W * (1 + d) + W) + W := by + exact add_le_add (add_le_add hold (mul_le_mul_of_nonneg_left hsum (by positivity))) hrelay + _ ≤ 8 * ((c : ℝ) + 1) ^ 2 * W * (1 + d) ^ 2 := by + apply sub_nonneg.mp + ring_nf + positivity + _ ≤ _ := by gcongr; exact_mod_cast (exponent_bounds hC).2 + +open Classical in +private theorem max_finish (hcap : H.Caps P ℓ) (hD : 4 ≤ D) + (hC : exponent c ℓ ≤ C) (hu : 0 < u) (hs : u * D ^ C ≤ T) (he : H.exterior) + (v : (H.finish he hu).freeze.Core) : + (H.finish he hu).charge v.val * (D : ℝ) ^ ℓ ≤ T := by + let B := (T : ℝ) / (D : ℝ) ^ (ℓ + 2) + let p := (D : ℝ) ^ c + have hh := (H.pad u).core_max he (G.divisible_pad u hu) (B := B + u * p) + (by unfold B p; positivity) (by + intro w + exact (show ((G.pad u).arity w.val : ℝ) ≤ G.arity w.val + (u : ℝ) * p by + have := H.charge_pad P hcap u w.val + unfold p; linarith).trans (add_le_add_left (hcap.coreMax w) _)) (by + intro w w' + have h₁ := (G.ties_pad u w.val w'.val).trans + (Nat.add_le_add_left (Nat.mul_le_mul_left u (hcap.degree w.val)) _) + exact (show ((G.pad u).ties w.val w'.val : ℝ) ≤ G.ties w.val w'.val + (u : ℝ) * p by + unfold p; exact_mod_cast h₁).trans (add_le_add_left (hcap.ties w w') _)) v + have hD' : 4 ≤ (D : ℝ) := by exact_mod_cast hD + have h₁ : B * (D : ℝ) ^ ℓ ≤ T / 4 := by + have h : B * (D : ℝ) ^ ℓ = T / (D : ℝ) ^ 2 := by + unfold B + rw [pow_add] + field_simp + rw [h] + gcongr + nlinarith + have h₂ : (u : ℝ) * (p + 1) * (4 * (D : ℝ) ^ ℓ) ≤ T := (padding_budget hD hC hs).2 + refine (mul_le_mul_of_nonneg_right hh (by positivity)).trans ?_ + linarith only [h₁, h₂, show 0 ≤ (u : ℝ) * (D : ℝ) ^ ℓ by positivity] + +open Classical in +theorem concentrated (hD : D = 2 ^ d) (hD' : 4 ≤ D) (hc : 1 ≤ c) (hC : exponent c ℓ ≤ C) + (hu : 0 < u) (hs : u * D ^ C ≤ T) (he : H.exterior) (hcap : H.Caps P ℓ) : + Concentrated P (H.finish he hu) C d ℓ := by + have hC₄ : 4 * c ≤ C := by have := (exponent_bounds hC).2; nlinarith + have hCc : c ≤ C := by omega + have hW : 0 ≤ W := le_trans (by positivity) (H.size_pad P hcap hD' hC hs) + have hscale : 1 ≤ (D : ℝ) := by exact_mod_cast (show 1 ≤ D by omega) + have hp : (u : ℝ) * ((D : ℝ) ^ c + 1) ≤ T := by + refine (le_mul_of_one_le_right (by positivity) ?_).trans (padding_budget hD' hC hs).2 + have : 1 ≤ (D : ℝ) ^ ℓ := one_le_pow₀ hscale + linarith + have charge (v : G.V) : ((G.pad u).arity v : ℝ) + u ≤ G.arity v + (T : ℝ) := + (H.charge_pad P hcap u v).trans (add_le_add_right hp _) + have host := host_bound hD hD' hC + let H' := H.pad u + have hw := G.divisible_pad u hu + refine ⟨?_, ?_, ?_, ?_, ?_, ?_, H.max_finish P hcap hD' hC hu hs he, + H.sum_finish P hcap hD hD' hc hC hu hs he⟩ + · change Fintype.card (Node V (c * d)) ≤ _ + rw [node_count] + calc + _ ≤ (1 + (c * d + 1) * 2 ^ (c * d)) * (D ^ c * Fintype.card P.V) + := Nat.mul_le_mul_left _ hcap.cells + _ ≤ _ := by rw [← mul_assoc]; exact Nat.mul_le_mul_right _ host.1 + · intro v + exact (S.core_degree v).trans (by omega) + · intro v + exact (S.degree v).trans host.2.2 + · rw [← Fintype.card_congr (H'.fixedEquiv he)] + exact hcap.frozenCount.trans (by gcongr) + · intro v + obtain ⟨w, rfl⟩ := (H'.fixedEquiv he).surjective v + change (H'.term he hw).charge (.inl w.val) ≤ _ + rw [H'.old_charge he hw] + calc + _ ≤ G.arity w.val + (T : ℝ) := charge w.val + _ ≤ (c : ℝ) * D * T + D * T := add_le_add (hcap.frozenMax w) + (le_mul_of_one_le_left (by positivity) hscale) + _ = ((c : ℝ) + 1) * D * T := by ring + _ ≤ _ := by gcongr; exact_mod_cast (show c + 1 ≤ C by omega) + · refine (H'.frozen_sum he hw (fun t => t ^ 2)).trans_le ?_ + have hsum : (Fintype.card H.Frozen : ℝ) * T ≤ c * W := calc + _ ≤ Fintype.card H.Frozen * (D : ℝ) * T := by + gcongr + exact le_mul_of_one_le_right (by positivity) hscale + _ ≤ _ := hcap.frozenCount + calc + _ ≤ ∑ v : H.Frozen, (2 * (G.arity v.val : ℝ) ^ 2 + 2 * (T : ℝ) ^ 2) := by + apply sum_le_sum + intro v _ + have hb := pow_le_pow_left₀ (by positivity) (charge v.val) 2 + nlinarith only [hb, sq_nonneg ((G.arity v.val : ℝ) - T)] + _ = 2 * (∑ v : H.Frozen, (G.arity v.val : ℝ) ^ 2) + 2 * (Fintype.card H.Frozen * T) * T := by + rw [sum_add_distrib, ← mul_sum, sum_const, card_univ, nsmul_eq_mul] + ring + _ ≤ 4 * (c : ℝ) * W * T := by + linarith only [hcap.frozenSquare, mul_le_mul_of_nonneg_right hsum (Nat.cast_nonneg T)] + _ ≤ _ := by gcongr; exact_mod_cast hC₄ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Load.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Load.lean new file mode 100644 index 0000000000..c5cbdf41bf --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Load.lean @@ -0,0 +1,117 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Sharing + +/-! # Arity charges for tree routing -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +variable {F V I : Type} {a b : Wire} {d : ℕ} (G : Bundled F a b) + +open Classical in +/-- The total width from one station to another, in both orientations. -/ +def Bundled.ties (u v : G.V) := + (∑ e, if G.src e = u ∧ G.dst e = v then G.width e else 0) + + (∑ e, if G.dst e = u ∧ G.src e = v then G.width e else 0) + +open Classical in +theorem Bundled.ties_le (u v : G.V) : G.ties u v ≤ G.arity v := by + unfold ties arity + rw [add_comm (∑ e, if G.src e = u ∧ G.dst e = v then G.width e else 0)] + apply Nat.add_le_add + · apply le_trans _ (Nat.le_add_left _ _) + exact sum_le_sum (fun e _ => by split_ifs <;> simp_all) + · exact sum_le_sum (fun e _ => by split_ifs <;> simp_all) + +namespace Fanout +variable {G} {T : Trie V d} (H : Fanout G T I) + +open Classical in +private theorem side_count (u v : G.V) (s : Relay G.V d) (w : ℕ) : + (∑ j, if H.side u v j = s then w else 0) = + if H.side u v s.2.1 = s then w else 0 := by + apply Fintype.sum_eq_single s.2.1 + intro j hj + exact ite_eq_right (fun h => hj (congrArg (fun x => x.2.1) h)) + +open Classical in +theorem hits (s : Relay G.V d) : + H.route.hits (.inr s) = + (∑ e, if H.side (G.src e) (G.dst e) s.2.1 = s then G.width e else 0) + + (∑ e, if H.side (G.dst e) (G.src e) s.2.1 = s then G.width e else 0) := by + unfold Routes.hits + rw [← sum_add_distrib] + apply sum_congr rfl + intro e _ + simp only [Sum.inr.injEq] + rw [Fin.sum_univ_add] + simp only [Fin.append_left, Fin.append_right] + have hr := Equiv.sum_comp Fin.revPerm + (fun j => if H.side (G.dst e) (G.src e) j = s then G.width e else 0) + simp only [Fin.revPerm_apply] at hr + rw [hr, side_count, side_count] + +open Classical in +theorem total [Field F] : ∑ s, H.route.net.arity (.inr s) = 4 * (d + 1)*∑ e, G.width e := by + rw [Routes.total_relay] + change 2 * (∑ e, ((d + 1) + (d + 1)) * G.width e) = _ + rw [← mul_sum] + ring + +open Classical in +private theorem sides_le (s : Relay G.V d) (L R : G.E → G.V) (p : G.E → Prop) + [DecidablePred p] (h : ∀ e, H.side (L e) (R e) s.2.1 = s → p e) : + (∑ e, if H.side (L e) (R e) s.2.1 = s then G.width e else 0) ≤ + ∑ e, if p e then G.width e else 0 := by + apply sum_le_sum + intro e _ + by_cases he : H.side (L e) (R e) s.2.1 = s + · rw [ite_eq_left he, ite_eq_left (h e he)] + · rw [ite_eq_right he]; exact Nat.zero_le _ + +open Classical in +theorem relay_le [Field F] (s : Relay G.V d) : + H.route.net.arity (.inr s) ≤ 2 * G.arity s.1 := by + rw [Routes.relay_arity, hits, Bundled.arity] + have bound (L R : G.E → G.V) := H.sides_le s L R (fun e => L e = s.1) + (fun _ he => congrArg Prod.fst he) + have h := bound G.src G.dst + have i := bound G.dst G.src + omega + +open Classical in +/-- On a frozen branch the address identifies one opposite station. -/ +theorem frozen_relay [Field F] (s : Relay G.V d) (hf : T.frozen (H.site s.1).1) : + ∃ v, H.route.net.arity (.inr s) ≤ 2 * G.ties s.1 v := by + let p := (T.peer (H.site s.1).1 s.2.2, (H.site s.1).2) + let v := if h : ∃ v, H.site v = p then h.choose else s.1 + have unique (u w : G.V) (h : H.side u w s.2.1 = s) + (hn : (H.site w).1 ∈ T.near (H.site u).1) (hg : (H.site u).2 = (H.site w).2) : + u = s.1 ∧ w = v := by + have hu : u = s.1 := congrArg Prod.fst h + subst u + have he := congrArg (fun x => x.2.2) h + simp only [side, Trie.address, ite_eq_left hf] at he + have hw : H.site w = p := Prod.ext (by unfold p; rw [← he, T.peer_code hn]) hg.symm + have hx : ∃ v, H.site v = p := ⟨w, hw⟩ + exact ⟨rfl, by unfold v; rw [dite_eq_left hx]; exact H.one (hw.trans hx.choose_spec.symm)⟩ + refine ⟨v, ?_⟩ + rw [Routes.relay_arity, hits, Bundled.ties] + have hl := H.sides_le s G.src G.dst (fun e => G.src e = s.1 ∧ G.dst e = v) + (fun e he => unique _ _ he (H.near e) (H.group e)) + have hr := H.sides_le s G.dst G.src (fun e => G.dst e = s.1 ∧ G.src e = v) + (fun e he => unique _ _ he (T.symm _ _ (H.near e)) (H.group e).symm) + omega + +end Fanout +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Sharing.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Sharing.lean new file mode 100644 index 0000000000..e47d1a214d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Sharing.lean @@ -0,0 +1,1080 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Encode +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Pull +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Trie +public import Mathlib.Data.Fin.Tuple.Basic + +/-! +# Attaching insertion tables to sphere forms + +The ordinary network contains exterior bits and any private selectors. +The closed network contains the seams. A link joins one station of each +network. All three kinds of internal states are summed independently. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +open Classical in +/-- The data for the alphabet construction, including `state`, `[fs`, `width`, `code`. -/ +structure Alphabet (I : Type) where + /-- The `Alphabet` component of type `I → Type`. -/ + state : I → Type + [fs : ∀ i, Fintype (state i)] + /-- The width parameter carried by `Alphabet`, with type `I → ℕ`. -/ + width : I → ℕ + /-- The encoding map carried by `Alphabet`, with type `∀ i, state i ↪ (Fin (width i) → Bool)`. -/ + code : ∀ i, state i ↪ (Fin (width i) → Bool) + +attribute [instance] Alphabet.fs + +open Classical in +/-- The condition `∀ i, A.state i` on the specified data. -/ +abbrev Alphabet.State {I : Type} (A : Alphabet I) := ∀ i, A.state i + +variable {F I : Type} [Fintype I] {a b : Wire} (A : Alphabet I) + +open Classical in +/-- The data for the attach construction, including `left`, `right`, `left_local`, +`right_local`. -/ +structure Attach (L : Bundled (A.State → F) a b) (R : Bundled (A.State → F) .unit .unit) where + /-- The left-side data carried by `Attach`, with type `I → L.V`. -/ + left : I → L.V + /-- The right-side data carried by `Attach`, with type `I → R.V`. -/ + right : I → R.V + left_local : ∀ v x y z s t, (∀ i, left i = v → s i = t i) → + L.station v x y z s = L.station v x y z t + right_local : ∀ v z s t, (∀ i, right i = v → s i = t i) → + R.station v () () z s = R.station v () () z t + +open Classical in +theorem Bundled.eval_equiv [Field F] {Y : Type} [Fintype Y] (G : Bundled F a b) + (x : Val a) (y : Val b) (e : G.State ≃ Y) (f : Y → F) + (h : ∀ s, ∏ v, G.station v x y s = f (e s)) : G.eval x y = ∑ t, f t := + Fintype.sum_equiv e _ _ h + +namespace Attach + +variable {A} {L : Bundled (A.State → F) a b} {R : Bundled (A.State → F) .unit .unit} + (H : Attach A L R) + +open Classical in +/-- Builds `Bundled F a b where V` with the specified `src`, `dst`, `left`, `right`. -/ +abbrev net : Bundled F a b where + V := L.V ⊕ R.V + E := L.E ⊕ (R.E ⊕ I) + src := Sum.elim (.inl ∘ L.src) (Sum.elim (.inr ∘ R.src) (.inl ∘ H.left)) + dst := Sum.elim (.inl ∘ L.dst) (Sum.elim (.inr ∘ R.dst) (.inr ∘ H.right)) + left := .inl ∘ L.left + right := .inl ∘ L.right + state := Sum.elim L.state (Sum.elim R.state A.state) + fs := Sum.rec L.fs (Sum.rec R.fs A.fs) + width := Sum.elim L.width (Sum.elim R.width A.width) + code := Sum.rec L.code (Sum.rec R.code A.code) + station v x y z := Sum.elim + (fun u => L.station u x y (fun i => z (.inl i)) (fun i => z (.inr (.inr i)))) + (fun u => R.station u () () (fun i => z (.inr (.inl i))) (fun i => z (.inr (.inr i)))) v + locality := by + intro v x y z x' y' z' hx hy hz + cases v with + | inl v => + have h := L.locality v x y (fun i => z (.inl i)) x' y' (fun i => z' (.inl i)) + (fun i hi => hx i (congrArg Sum.inl hi)) (fun i hi => hy i (congrArg Sum.inl hi)) + (fun i hi => hz (.inl i) (hi.imp (congrArg Sum.inl) (congrArg Sum.inl))) + exact (congrFun h _).trans (H.left_local _ _ _ _ _ _ fun i hi => + hz (.inr (.inr i)) (.inl (congrArg Sum.inl hi))) + | inr v => + have h := R.locality v () () (fun i => z (.inr (.inl i))) () () (fun i => z' (.inr (.inl i))) + (fun _ _ => rfl) (fun _ _ => rfl) + (fun i hi => hz (.inr (.inl i)) (hi.imp (congrArg Sum.inr) (congrArg Sum.inr))) + exact (congrFun h _).trans (H.right_local _ _ _ _ fun i hi => + hz (.inr (.inr i)) (.inr (congrArg Sum.inr hi))) + +open Classical in +/-- Reindexes `H.net.State` and `L.State × R.State × A.State` by an equivalence. -/ +def split : H.net.State ≃ L.State × R.State × A.State := + (Equiv.sumPiEquivProdPi _).trans ((Equiv.refl _).prodCongr (Equiv.sumPiEquivProdPi _)) + +open Classical in +theorem eval_net [Field F] (x : Val a) (y : Val b) : + H.net.eval x y = ∑ s : L.State, ∑ t : R.State, ∑ u : A.State, + (∏ v, L.station v x y s u) * ∏ v, R.station v () () t u := by + let f (w : L.State × R.State × A.State) := + (∏ v, L.station v x y w.1 w.2.2) * ∏ v, R.station v () () w.2.1 w.2.2 + calc + _ = ∑ w, f w := by + apply H.net.eval_equiv x y H.split f + intro s + exact Fintype.prod_sum_type _ + _ = _ := by simp only [Fintype.sum_prod_type, f] + +open Classical in +theorem left_arity (v : L.V) : + H.net.arity (.inl v) = L.arity v + ∑ i, if H.left i = v then A.width i else 0 := by + simp [Bundled.arity, net, Fintype.card_subtype, Fintype.sum_sum_type, add_assoc, add_comm, + add_left_comm] + +open Classical in +theorem right_arity (v : R.V) : + H.net.arity (.inr v) = R.arity v + ∑ i, if H.right i = v then A.width i else 0 := by + simp [Bundled.arity, net, Fintype.sum_sum_type, add_assoc] + +end Attach +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- Assignment spaces for the two forms at every cell and chunk. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +variable {F T X E V : Type} [Field F] [Fintype E] [Fintype V] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) T E X} {d : E → ℕ} + +open Classical in +/-- The parameters may include ordinary selector bits. A table must read +only the ordinary ports at its assigned station. -/ +structure Backdrop (C : V → Surface.Cell F (M * r) (M * t) T E X) (a b : Wire) where + /-- The `Backdrop` component of type `Bundled F a b`. -/ + base : Bundled F a b + /-- The owner assigned to each element of type `Place C → base.V`. -/ + owner : Place C → base.V + /-- The `Backdrop` component of type `Val a → Val b → base.State → X`. -/ + param : Val a → Val b → base.State → X + /-- The `Backdrop` component of type `Place C → Val a → Val b → base.State → X`. -/ + paramAt : Place C → Val a → Val b → base.State → X + compatible : ∀ x y z, (∏ v, base.station v x y z) ≠ 0 → ∀ i, + (item C i).table (paramAt i x y z) = (item C i).table (param x y z) + local_param : ∀ i x y z x' y' z', + (∀ j, base.left j = owner i → bits a x j = bits a x' j) → + (∀ j, base.right j = owner i → bits b y j = bits b y' j) → + (∀ e, base.src e = owner i ∨ base.dst e = owner i → z e = z' e) → + (item C i).table (paramAt i x y z) = (item C i).table (paramAt i x' y' z') + /-- Assigns the source of each connection. -/ + src : E → V + /-- Assigns the destination of each connection. -/ + dst : E → V + meets : ∀ v j, j ∈ (C v).ports → src j.1 = v ∨ dst j.1 = v + +open Classical in +/-- Indexes the grid by the coordinates of `(I × Fin M) ⊕ (I × Fin M)`. -/ +abbrev Grid (M : ℕ) (I : Type) := (I × Fin M) ⊕ (I × Fin M) + +open Classical in +/-- Computes the point by the application `Sum.elim Prod.fst Prod.fst`. -/ +def Grid.point {I : Type} : Grid M I → I := Sum.elim Prod.fst Prod.fst + +open Classical in +/-- Transforms the indexed data by `Sum.map (Prod.map f id) (Prod.map f id)`. -/ +def Grid.map {I J : Type} (f : I → J) : Grid M I → Grid M J := + Sum.map (Prod.map f id) (Prod.map f id) + +namespace Profile +variable (p : Profile C d) + +open Classical in +/-- Computes the seam by the application `Level r ((p.1 (.inl i.1)).val i.2).val`. -/ +abbrev seam (i : E × Fin M) := Level r ((p.1 (.inl i.1)).val i.2).val + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +abbrev leg : Grid M (Place C) → Type := + Sum.elim (fun i => Level r ((p.1 (.inr i.1)).val i.2).val) + (fun i => Level t ((p.2 i.1).val i.2).val) + +open Classical in +instance (i : Grid M (Place C)) : Fintype (p.leg i) := + match i with + | .inl _ => inferInstanceAs (Fintype (Level r _)) + | .inr _ => inferInstanceAs (Fintype (Level t _)) + +open Classical in +/-- The condition `∀ i, p.seam i` on the specified data. -/ +abbrev Seams := ∀ i, p.seam i +open Classical in +/-- The condition `∀ i, p.leg i` on the specified data. -/ +abbrev Legs := ∀ i, p.leg i + +open Classical in +/-- In the case `.inl i, j`, this construction gives `y (i, j)`. -/ +def first (y : p.Seams) (z : p.Legs) : p.AState + | .inl i, j => y (i, j) + | .inr i, j => z (.inl (i, j)) + +open Classical in +/-- Evaluates `z (.inr (i, j))` at the input `i j`. -/ +def second (z : p.Legs) : p.BState := fun i j => z (.inr (i, j)) + +open Classical in +/-- Reindexes `p.Seams × p.Legs` and `p.AState × p.BState where toFun s` by an equivalence. -/ +def assignments : p.Seams × p.Legs ≃ p.AState × p.BState where + toFun s := (p.first s.1 s.2, p.second s.2) + invFun s := (fun i => s.1 (.inl i.1) i.2, + Sum.rec (fun i => s.1 (.inr i.1) i.2) (fun i => s.2 i.1 i.2)) + left_inv s := by + apply Prod.ext + · rfl + · funext i; cases i <;> rfl + right_inv s := by + apply Prod.ext + · funext i j; cases i <;> rfl + · rfl + +open Classical in +/-- The data for the widths construction, including `seam`, `leg`, `seam_bound`, `leg_bound`. -/ +structure Widths where + /-- The `Widths` component of type `E × Fin M → ℕ`. -/ + seam : E × Fin M → ℕ + /-- The `Widths` component of type `Grid M (Place C) → ℕ`. -/ + leg : Grid M (Place C) → ℕ + seam_bound : ∀ i, Fintype.card (p.seam i) ≤ 2 ^ (seam i) + leg_bound : ∀ i, Fintype.card (p.leg i) ≤ 2 ^ (leg i) + +open Classical in +/-- Builds `p.Widths where seam i` with the specified `seam`, `leg`, `seam_bound`, `leg_bound`. -/ +def widths : p.Widths where + seam i := Chunk.width r ((p.1 (.inl i.1)).val i.2).val + leg := Sum.elim (fun i => Chunk.width r ((p.1 (.inr i.1)).val i.2).val) + (fun i => Chunk.width t ((p.2 i.1).val i.2).val) + seam_bound _ := Chunk.card_le _ _ + leg_bound := by rintro (i | i) <;> exact Chunk.card_le _ _ + +open Classical in +/-- Builds `Alphabet (Grid M (Place C)) where state` with the specified `state`, `width`, +`code`. -/ +abbrev Widths.alphabet {p : Profile C d} (w : p.Widths) : Alphabet (Grid M (Place C)) where + state := p.leg + width := w.leg + code i := binaryCode _ _ (w.leg_bound i) + +open Classical in +/-- The indexed operation `(item C i).table x (Chunk.states M r _ ⟨p.1 (.inr i), fun j => z +(.inl (i, j))⟩) (p.joinB (p.second z) i)`. -/ +def insertion (z : p.Legs) (x : X) (i : Place C) := + (item C i).table x (Chunk.states M r _ ⟨p.1 (.inr i), fun j => z (.inl (i, j))⟩) + (p.joinB (p.second z) i) + +open Classical in +/-- The form used in the `Profile` construction. -/ +def form (P : ℕ) (y : p.Seams) (z : p.Legs) : Grid M V → F + | .inl (v, j) => read (firstPoint C P) (fun i => (p.first y z (source C i) j).val) (firstList C v) + | .inr (v, j) => read (secondPoint C) (fun i => (p.second z i j).val) (secondList C v) + +end Profile +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- The scalar from reordering generators is fixed by the energy profile. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Profile +open Finset + +variable {F T X E V : Type} [Field F] [Fintype E] [Fintype V] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) T E X} {d : E → ℕ} (p : Profile C d) + +open Classical in +/-- The quantity computed by `(-1) ^ Plant.shuffle (fun i j => ((p.1 (source C i)).val j).val) +(List.finRange M) (firstList C v)`. -/ +def signA (v : V) : F := + (-1) ^ Plant.shuffle (fun i j => ((p.1 (source C i)).val j).val) + (List.finRange M) (firstList C v) + +open Classical in +/-- The quantity computed by `(-1) ^ Plant.shuffle (fun i j => ((p.2 i).val j).val) +(List.finRange M) (secondList C v)`. -/ +def signB (v : V) : F := + (-1) ^ Plant.shuffle (fun i j => ((p.2 i).val j).val) + (List.finRange M) (secondList C v) + +open Classical in +/-- The quantity computed by `(∏ v, p.signA v) * ∏ v, p.signB v`. -/ +def sign : F := (∏ v, p.signA v) * ∏ v, p.signB v + +omit [Fintype E] in +open Classical in +theorem factors_split (P : ℕ) (x : X) (y : p.Seams) (z : p.Legs) : + factors C P d x (p.joinA (p.first y z)) (p.joinB (p.second z)) = + p.sign * ((∏ i, p.insertion z x i) * ∏ v, p.form P y z v) := by + have ha (v : V) : + read (firstPoint C P) (fun i => (p.joinA (p.first y z) (source C i)).val) (firstList C v) = + p.signA v * ∏ j, p.form P y z (.inl (v, j)) := + Chunk.wick_chunks (firstPoint C P) (fun i => firstEnergy C d (source C i)) + (fun i => p.1 (source C i)) (fun i => p.first y z (source C i)) (firstList C v) + have hb (v : V) : + read (secondPoint C) (fun i => (p.joinB (p.second z) i).val) (secondList C v) = + p.signB v * ∏ j, p.form P y z (.inr (v, j)) := + Chunk.wick_chunks (secondPoint C) (secondEnergy C) p.2 (p.second z) (secondList C v) + have he (i : Place C) : (item C i).table x (p.joinA (p.first y z) (.inr i)) (p.joinB (p.second z) + i) = + p.insertion z x i := rfl + rw [Fintype.prod_sum_type (p.form P y z), Fintype.prod_prod_type, Fintype.prod_prod_type] + simp only [factors, he, ha, hb, prod_mul_distrib, sign] + ring + +open Classical in +theorem value_split (P : ℕ) (x : X) : + p.value P x = p.sign * ∑ y : p.Seams, ∑ z : p.Legs, + (∏ i, p.insertion z x i) * ∏ v, p.form P y z v := by + let f (s : p.AState × p.BState) := factors C P d x (p.joinA s.1) (p.joinB s.2) + calc + _ = ∑ s, f s := (Fintype.sum_prod_type f).symm + _ = ∑ s, f (p.assignments s) := (p.assignments.sum_comp _).symm + _ = _ := by + rw [Fintype.sum_prod_type] + change ∑ y, ∑ z, factors C P d x (p.joinA (p.first y z)) (p.joinB (p.second z)) = _ + simp only [factors_split, mul_sum] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Profile +end + +/- +# Emitting a network at fixed chunk energies + +A form has its own station in each cell and chunk on each sphere. +Insertion vertices retain the original exterior bits and selector wires. +Each seam state is shared by its two ends. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +variable {F T X E V : Type} [Field F] [Fintype E] [Fintype V] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) T E X} {d : E → ℕ} {a b : Wire} + +open Classical in +private theorem read_ext {I : Type} {q : ℕ} {f g : I → Wedge q} (l : List I) (z : I → F) + (h : ∀ i ∈ l, f i = g i) : read z f l = read z g l := by + unfold read + congr 1 + exact List.flatMap_congr fun i hi => congrArg (Surface.modes (z i)) (h i hi) + +namespace Backdrop + +variable (B : Backdrop C a b) (p : Profile C d) + +open Classical in +/-- Computes the arm by the application `B.owner (Grid.point i)`. -/ +def arm (i : Grid M (Place C)) := B.owner (Grid.point i) + +open Classical in +/-- Computes the socket by the application `Grid.map Sigma.fst i`. -/ +def socket (i : Grid M (Place C)) : Grid M V := Grid.map Sigma.fst i + +open Classical in +/-- The value specified by `.inl (s i.1, i.2)`. -/ +def seamEnd (s : E → V) (i : E × Fin M) : Grid M V := .inl (s i.1, i.2) + +omit [Fintype E] [Fintype V] in +open Classical in +theorem form_eq (P : ℕ) (v : Grid M V) (s s' : p.Seams) (z z' : p.Legs) + (hs : ∀ e, seamEnd B.src e = v ∨ seamEnd B.dst e = v → s e = s' e) + (hz : ∀ i, socket i = v → z i = z' i) : + p.form P s z v = p.form P s' z' v := by + rcases v with ⟨v, j⟩ | ⟨v, j⟩ + · apply read_ext + simp only [firstList, secondList, List.forall_mem_append, List.forall_mem_map] + constructor + · intro k _ + exact congrArg Subtype.val (hz (.inl (⟨v, k⟩, j)) rfl) + · intro k hk + apply congrArg Subtype.val + apply hs (k.1, j) + simpa [seamEnd] using B.meets v k hk + · apply read_ext + simp only [secondList, List.forall_mem_map] + intro k _ + exact congrArg Subtype.val (hz (.inr (⟨v, k⟩, j)) rfl) + +open Classical in +/-- Builds `Bundled (p.Legs → F) a b where V` with the specified `state`, `width`, `code`, +`left`. -/ +abbrev ordinary : Bundled (p.Legs → F) a b where + V := B.base.V + E := B.base.E + state := B.base.state + width := B.base.width + code := B.base.code + left := B.base.left + right := B.base.right + src := B.base.src + dst := B.base.dst + station v x y s z := B.base.station v x y s * + ∏ i, if B.owner i = v then p.insertion z (B.paramAt i x y s) i else 1 + locality := by + intro v x y s x' y' s' hx hy hs + funext z + rw [B.base.locality _ _ _ _ _ _ _ hx hy hs] + congr 1 + apply prod_congr rfl + intro i _ + split_ifs with h + · unfold Profile.insertion + subst v + rw [B.local_param _ _ _ _ _ _ _ hx hy hs] + · rfl + +open Classical in +/-- Indexes the chambers by the coordinates of `Grid M V E := E × Fin M state := p.seam width := +w.seam code i := binaryCode _ _ (w.seam_bound i)`. -/ +abbrev chambers (P : ℕ) (w : p.Widths) : Bundled (p.Legs → F) .unit .unit where + V := Grid M V + E := E × Fin M + state := p.seam + width := w.seam + code i := binaryCode _ _ (w.seam_bound i) + left := Empty.elim + right := Empty.elim + src := seamEnd B.src + dst := seamEnd B.dst + station v _ _ s z := p.form P s z v + locality := by + intro v _ _ s _ _ s' _ _ hs + funext z + exact B.form_eq p P v s s' z z hs (fun _ _ => rfl) + +open Classical in +/-- Builds `Attach w.alphabet (B.ordinary p) (B.chambers p P w) where left` with the specified +`left`, `right`, `left_local`, `right_local`. -/ +abbrev emit (P : ℕ) (w : p.Widths) : Attach w.alphabet (B.ordinary p) (B.chambers p P w) where + left := B.arm + right := socket + left_local := by + intro v x y s z z' h + change _ * ∏ i, (if B.owner i = v then p.insertion z (B.paramAt i x y s) i else 1) = + _ * ∏ i, (if B.owner i = v then p.insertion z' (B.paramAt i x y s) i else 1) + congr 1 + apply prod_congr rfl + intro i _ + split_ifs with hi + · have ha : (fun j => z (.inl (i, j))) = fun j => z' (.inl (i, j)) := + funext fun j => h (.inl (i, j)) hi + have hb : (fun j => z (.inr (i, j))) = fun j => z' (.inr (i, j)) := + funext fun j => h (.inr (i, j)) hi + unfold Profile.insertion + change _ = (item C i).table _ _ (Chunk.states M t _ ⟨p.2 i, fun j => z' (.inr (i, j))⟩) + rw [← ha, ← hb] + rfl + · rfl + right_local v s z z' h := B.form_eq p P v s s z z' (fun _ _ => rfl) h + +omit [Fintype E] in +open Classical in +private theorem ordinary_prod (x : Val a) (y : Val b) (s : B.base.State) (z : p.Legs) : + (∏ v, (B.ordinary p).station v x y s z) = + (∏ v, B.base.station v x y s) * ∏ i, p.insertion z (B.param x y s) i := by + unfold ordinary + rw [prod_mul_distrib, prod_comm] + by_cases h : (∏ v, B.base.station v x y s) = 0 + · simp [h] + · have eq (i : Place C) : p.insertion z (B.paramAt i x y s) i = p.insertion z (B.param x y s) i + := by + unfold Profile.insertion + rw [B.compatible x y s h i] + simp [eq] + +open Classical in +theorem profile_eval (P : ℕ) (w : p.Widths) (x : Val a) (y : Val b) : + p.sign * (B.emit p P w).net.eval x y = + ∑ s : B.base.State, (∏ v, B.base.station v x y s) * p.value P (B.param x y s) := by + rw [Attach.eval_net, mul_sum] + apply sum_congr rfl + intro s _ + rw [Profile.value_split] + simp only [mul_sum] + refine sum_congr (by ext; simp) ?_ + intro t _ + refine sum_congr (by ext; simp) ?_ + intro u _ + change p.sign * ((∏ v, (B.ordinary p).station v x y s u) * ∏ v, p.form P t u v) = _ + rw [B.ordinary_prod] + ring + +open Classical in +/-- Expand over public energy profiles, keeping all ordinary selectors +inside each contraction. Each profile has one scalar sign. -/ +theorem expansion (P : ℕ) (w : ∀ p : Profile C d, p.Widths) (x : Val a) (y : Val b) : + (∑ p : Profile C d, p.sign * (B.emit p P (w p)).net.diagram.eval x y) = + ∑ s : B.base.State, (∏ v, B.base.station v x y s) * Surface.eval P C d (B.param x y s) := by + simp only [Bundled.eval_diagram, profile_eval, eval_shapes, mul_sum] + rw [sum_comm] + +end Backdrop +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- +# Routing whole bundles through relay stations + +Every old bundle follows its own path. A relay table is the product +of the equality constraints for paths passing through it. Each old +assignment consequently has exactly one consistent extension. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +variable {F Y : Type} {a b : Wire} (G : Bundled F a b) + +open Classical in +/-- The internal vertices of a directed path for each bundle. -/ +structure Routes (Y : Type) where + /-- The length of the indexed record carried by `Routes`, with type `G.E → ℕ`. -/ + length : G.E → ℕ + /-- The `Routes` component of type `∀ e, Fin (length e) → Y`. -/ + via : ∀ e, Fin (length e) → Y + +namespace Routes +variable {G} (R : Routes G Y) + +open Classical in +/-- Indexes the hop by the coordinates of `Σ e, Fin (R.length e + 1)`. -/ +abbrev Hop := Σ e, Fin (R.length e + 1) +open Classical in +/-- The condition `∀ i : R.Hop, G.state i.1` on the specified data. -/ +abbrev Data := ∀ i : R.Hop, G.state i.1 + +open Classical in +/-- The indexed operation `Fin.cases (.inl (G.src i.1)) (fun j => .inr (R.via i.1 j)) i.2`. -/ +def src (i : R.Hop) : G.V ⊕ Y := + Fin.cases (.inl (G.src i.1)) (fun j => .inr (R.via i.1 j)) i.2 + +open Classical in +/-- The indexed operation `Fin.lastCases (.inl (G.dst i.1)) (fun j => .inr (R.via i.1 j)) i.2`. -/ +def dst (i : R.Hop) : G.V ⊕ Y := + Fin.lastCases (.inl (G.dst i.1)) (fun j => .inr (R.via i.1 j)) i.2 + +open Classical in +/-- Maps the coordinate `e` to `if G.src e = v then z ⟨e, 0⟩ else z ⟨e, Fin.last _⟩`. -/ +def read (v : G.V) (z : R.Data) : G.State := fun e => + if G.src e = v then z ⟨e, 0⟩ else z ⟨e, Fin.last _⟩ + +open Classical in +/-- The condition `∀ e j, R.via e j = v → z ⟨e, j.castSucc⟩ = z ⟨e, j.succ⟩` on the specified +data. -/ +def Valid (v : Y) (z : R.Data) : Prop := + ∀ e j, R.via e j = v → z ⟨e, j.castSucc⟩ = z ⟨e, j.succ⟩ + +open Classical in +/-- Evaluates `z i.1` at the input `i`. -/ +def copy (z : G.State) : R.Data := fun i => z i.1 + +open Classical in +theorem copy_injective : Function.Injective R.copy := by + intro x y h + exact funext fun i => congrFun h ⟨i, 0⟩ + +open Classical in +private theorem copy_of_valid {z : R.Data} (h : ∀ v, R.Valid v z) : + ∃ s, R.copy s = z := by + refine ⟨fun e => z ⟨e, 0⟩, ?_⟩ + funext i + obtain ⟨e, j⟩ := i + change z ⟨e, 0⟩ = z ⟨e, j⟩ + induction j using Fin.induction with + | zero => rfl + | succ j ih => exact ih.trans (h _ e j rfl) + +variable [Fintype Y] [Field F] + +open Classical in +/-- Indexes the net by the coordinates of `G.V ⊕ Y E := R.Hop src := R.src dst := R.dst state i +:= G.state i.1`. -/ +abbrev net : Bundled F a b where + V := G.V ⊕ Y + E := R.Hop + src := R.src + dst := R.dst + state i := G.state i.1 + width i := G.width i.1 + code i := G.code i.1 + left := .inl ∘ G.left + right := .inl ∘ G.right + station v x y z := Sum.elim (fun u => G.station u x y (R.read u z)) + (fun u => if R.Valid u z then 1 else 0) v + locality := by + intro v x y z x' y' z' hx hy hz + cases v with + | inl v => + apply G.locality _ _ _ _ _ _ _ (fun i hi => hx i (congrArg Sum.inl hi)) + (fun i hi => hy i (congrArg Sum.inl hi)) + intro e he + unfold read + split_ifs with hs + · exact hz ⟨e, 0⟩ (.inl (by simp [src, hs])) + · exact hz ⟨e, Fin.last _⟩ (.inr (by simp [dst, he.resolve_left hs])) + | inr v => + have hh : R.Valid v z ↔ R.Valid v z' := by + unfold Valid + apply forall_congr' + intro e + apply forall_congr' + intro j + apply imp_congr_right + intro hj + rw [hz ⟨e, j.castSucc⟩ (.inr (by simp [dst, hj])), hz ⟨e, j.succ⟩ (.inl (by simp [src, + hj]))] + simp only [Sum.elim_inr, hh] + +open Classical in +theorem copy_prod (x : Val a) (y : Val b) (s : G.State) : + ∏ v, R.net.station v x y (R.copy s) = ∏ v, G.station v x y s := by + rw [Fintype.prod_sum_type] + have hv (v : Y) : R.Valid v (R.copy s) := fun _ _ _ => rfl + have he (v : G.V) : R.read v (R.copy s) = s := by funext e; simp [read, copy] + simp [he, hv] + +open Classical in +theorem eval_net : R.net.eval = G.eval := by + funext x y + symm + unfold Bundled.eval + calc + _ = ∑ z ∈ univ.image R.copy, ∏ v, R.net.station v x y z := by + rw [sum_image R.copy_injective.injOn] + exact sum_congr rfl fun s _ => (R.copy_prod x y s).symm + _ = ∑ z : R.Data, ∏ v, R.net.station v x y z := by + apply sum_subset (subset_univ _) + intro z _ hz + have : ¬∀ v, R.Valid v z := fun h => hz (by + obtain ⟨s, rfl⟩ := R.copy_of_valid h + exact mem_image_of_mem _ (mem_univ _)) + obtain ⟨v, hv⟩ := not_forall.mp this + exact prod_eq_zero (mem_univ (Sum.inr v : G.V ⊕ Y)) (ite_eq_right hv) + _ = _ := by congr! + +open Classical in +/-- The value specified by `∑ e, ∑ j : Fin (R.length e), if .inr (R.via e j) = v then G.width e +else 0`. -/ +def hits (v : G.V ⊕ Y) := ∑ e, ∑ j : Fin (R.length e), if .inr (R.via e j) = v then G.width e else 0 + +omit [Field F] [Fintype Y] in +open Classical in +private theorem count_src (v : G.V ⊕ Y) : + (∑ s, if R.src s = v then G.width s.1 else 0) = + (∑ e, if .inl (G.src e) = v then G.width e else 0) + R.hits v := by + unfold hits + rw [Fintype.sum_sigma, ← sum_add_distrib] + apply sum_congr rfl + intro e _ + rw [Fin.sum_univ_succ] + simp only [src, Fin.cases_zero, Fin.cases_succ] + congr! + +omit [Field F] [Fintype Y] in +open Classical in +private theorem count_dst (v : G.V ⊕ Y) : + (∑ s, if R.dst s = v then G.width s.1 else 0) = + (∑ e, if .inl (G.dst e) = v then G.width e else 0) + R.hits v := by + unfold hits + rw [Fintype.sum_sigma, ← sum_add_distrib] + apply sum_congr rfl + intro e _ + rw [Fin.sum_univ_castSucc, add_comm] + simp only [dst, Fin.lastCases_last, Fin.lastCases_castSucc] + +open Classical in +theorem old_arity (v : G.V) : R.net.arity (.inl v) = G.arity v := by + simp only [Bundled.arity, net] + rw [count_src, count_dst] + simp [hits, Fintype.card_subtype] + +open Classical in +theorem relay_arity (v : Y) : R.net.arity (.inr v) = 2 * R.hits (.inr v) := by + simp only [Bundled.arity, net] + rw [count_src, count_dst] + simp [two_mul] + +open Classical in +theorem total_relay : ∑ v : Y, R.net.arity (.inr v) = 2 * ∑ e, R.length e * G.width e := by + simp_rw [relay_arity] + rw [← mul_sum] + unfold hits + rw [sum_comm] + congr 1 + apply sum_congr rfl + intro e _ + rw [sum_comm] + simp + +end Routes +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- +# Ordinary values shared across cells + +A key has a connected footprint in the seam graph. Link its storage +at each visited cell to the local readers and to the neighboring hubs. +The local factors enforce equality at each hub, even on cycles. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +variable {F T X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + +open scoped Classical in +/-- The data for the sharing construction, including `src`, `dst`, `meets`, `seen`, `reads`. -/ +structure Sharing (C : V → Surface.Cell F (M * r) (M * t) T E X) (a b : Wire) (Y : Alphabet K) where + /-- Assigns the source of each connection. -/ + src : E → V + /-- Assigns the destination of each connection. -/ + dst : E → V + meets : ∀ v j, j ∈ (C v).ports → src j.1 = v ∨ dst j.1 = v + /-- The `Sharing` component of type `V → Finset K`. -/ + seen : V → Finset K + /-- The `Sharing` component of type `Place C → Finset K`. -/ + reads : Place C → Finset K + within : ∀ i, reads i ⊆ seen i.1 + present : ∀ k, ∃ v, k ∈ seen v + connected : ∀ k v w, k ∈ seen v → k ∈ seen w → + Relation.EqvGen (fun p q => k ∈ seen p ∧ k ∈ seen q ∧ ∃ e, src e = p ∧ dst e = q) v w + /-- The left-side data carried by `Sharing`, with type `slots a → Place C`. -/ + left : slots a → Place C + /-- The right-side data carried by `Sharing`, with type `slots b → Place C`. -/ + right : slots b → Place C + /-- The `Sharing` component of type `Val a → Val b → Y.State → X`. -/ + param : Val a → Val b → Y.State → X + locality : ∀ i x y z x' y' z', + (∀ j, left j = i → bits a x j = bits a x' j) → + (∀ j, right j = i → bits b y j = bits b y' j) → + (∀ k ∈ reads i, z k = z' k) → + (item C i).table (param x y z) = (item C i).table (param x' y' z') + +namespace Sharing +variable {C : V → Surface.Cell F (M * r) (M * t) T E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) + +open scoped Classical in +/-- Indexes the vertex by the coordinates of `Place C ⊕ V ⊕ V`. -/ +abbrev Vertex (_ : Sharing C a b Y) := Place C ⊕ V ⊕ V +open scoped Classical in +/-- The subtype of `v` satisfying `k ∈ S.seen v`. -/ +abbrev Stores (k : K) := {v // k ∈ S.seen v} +open scoped Classical in +/-- The subtype of `e` satisfying `k ∈ S.seen (S.src e) ∧ k ∈ S.seen (S.dst e)`. -/ +abbrev Links (k : K) := {e // k ∈ S.seen (S.src e) ∧ k ∈ S.seen (S.dst e)} +open scoped Classical in +/-- The subtype of `i` satisfying `k ∈ S.reads i`. -/ +abbrev Readers (k : K) := {i // k ∈ S.reads i} +open scoped Classical in +/-- Indexes the line by the coordinates of `S.Stores k ⊕ S.Links k ⊕ S.Readers k`. -/ +abbrev Line (k : K) := S.Stores k ⊕ S.Links k ⊕ S.Readers k +open scoped Classical in +/-- Indexes the edge by the coordinates of `Σ k, S.Line k`. -/ +abbrev Edge := Σ k, S.Line k +open scoped Classical in +/-- The condition `∀ e : S.Edge, Y.state e.1` on the specified data. -/ +abbrev State := ∀ e : S.Edge, Y.state e.1 + +open scoped Classical in +instance : Fintype S.State := + @Pi.instFintype S.Edge (fun e => Y.state e.1) (Classical.typeDecidableEq _) _ (fun e => Y.fs e.1) + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `v`. -/ +def start {k : K} : S.Line k → S.Stores k + | .inl v => v + | .inr (.inl e) => ⟨S.src e.val, e.property.1⟩ + | .inr (.inr i) => ⟨i.val.1, S.within i.val i.property⟩ + +open scoped Classical in +/-- The value specified by `.inr (.inl (S.start e.2).val)`. -/ +def source (e : S.Edge) : S.Vertex := .inr (.inl (S.start e.2).val) + +open scoped Classical in +/-- In the case `⟨_, .inl v⟩`, this construction gives `.inr (.inr v.val)`. -/ +def target : S.Edge → S.Vertex + | ⟨_, .inl v⟩ => .inr (.inr v.val) + | ⟨_, .inr (.inl e)⟩ => .inr (.inl (S.dst e.val)) + | ⟨_, .inr (.inr i)⟩ => .inl i.val + +open scoped Classical in +/-- The defining condition `∀ k (v : S.Stores k), p = .inr (.inl v.val) → ∀ e : S.Line k, +S.source ⟨k, e⟩ = p ∨ S.target ⟨k, e⟩ = p → z ⟨k, e⟩ = z ⟨k, .inl v⟩`. -/ +def checks (p : S.Vertex) (z : S.State) : Prop := + ∀ k (v : S.Stores k), p = .inr (.inl v.val) → ∀ e : S.Line k, + S.source ⟨k, e⟩ = p ∨ S.target ⟨k, e⟩ = p → z ⟨k, e⟩ = z ⟨k, .inl v⟩ + +open scoped Classical in +/-- Builds `Bundled F a b where V` with the specified `state`, `width`, `code`, `src`. -/ +abbrev base : Bundled F a b where + V := S.Vertex + E := S.Edge + state e := Y.state e.1 + width e := Y.width e.1 + code e := Y.code e.1 + src := S.source + dst := S.target + left j := .inl (S.left j) + right j := .inl (S.right j) + station p _ _ z := if S.checks p z then 1 else 0 + locality p _ _ z _ _ z' _ _ hz := by + have same : S.checks p z ↔ S.checks p z' := by + unfold checks + refine forall_congr' fun k => forall_congr' fun v => imp_congr_right fun hp => + forall_congr' fun e => imp_congr_right fun he => ?_ + rw [hz _ he, hz ⟨k, .inl v⟩ (.inl hp.symm)] + simp only [same] + +open scoped Classical in +/-- Uses `⟨(S.present k).choose, (S.present k).choose_spec⟩` as the representation. -/ +def store (k : K) : S.Stores k := ⟨(S.present k).choose, (S.present k).choose_spec⟩ + +open scoped Classical in +/-- Maps the coordinate `k` to `z ⟨k, .inl (S.store k)⟩`. -/ +def decode (z : S.State) : Y.State := fun k => z ⟨k, .inl (S.store k)⟩ + +open scoped Classical in +/-- Maps the coordinate `e` to `x e.1`. -/ +def encode (x : Y.State) : S.State := fun e => x e.1 + +omit [Field F] [Fintype K] [Fintype V] [Fintype E] in +open scoped Classical in +private theorem consistent (z : S.State) (ok : ∀ p, S.checks p z) : + S.encode (S.decode z) = z := by + have same (k : K) (p q : S.Stores k) : z ⟨k, .inl p⟩ = z ⟨k, .inl q⟩ := by + let value (v : V) := if h : k ∈ S.seen v then z ⟨k, .inl ⟨v, h⟩⟩ else S.decode z k + have link (v w : V) (h : Relation.EqvGen + (fun i j => k ∈ S.seen i ∧ k ∈ S.seen j ∧ ∃ e, S.src e = i ∧ S.dst e = j) v w) : + value v = value w := by + induction h with + | refl => rfl + | symm _ _ _ ih => exact ih.symm + | trans _ _ _ _ _ i j => exact i.trans j + | rel v w he => + obtain ⟨hv, hw, e, rfl, rfl⟩ := he + let l : S.Line k := .inr (.inl ⟨e, hv, hw⟩) + simp only [value, dite_eq_left hv, dite_eq_left hw] + exact (ok _ k ⟨_, hv⟩ rfl l (.inl rfl)).symm.trans (ok _ k ⟨_, hw⟩ rfl l (.inr rfl)) + simpa only [value, dite_eq_left p.property, dite_eq_left q.property] using + link _ _ (S.connected k _ _ p.property q.property) + funext ⟨k, e⟩ + exact (same k (S.store k) (S.start e)).trans (ok _ k (S.start e) rfl e (.inl rfl)).symm + +open scoped Classical in +/-- Evaluates `if h : k ∈ S.reads i then z ⟨k, .inr (.inr ⟨i, h⟩)⟩ else S.decode z k` at the +input `k`. -/ +def localState (i : Place C) (z : S.State) : Y.State := + fun k => if h : k ∈ S.reads i then z ⟨k, .inr (.inr ⟨i, h⟩)⟩ else S.decode z k + +open scoped Classical in +theorem valid (x : Val a) (y : Val b) (z : S.State) + (hp : (∏ v, S.base.station v x y z) ≠ 0) : S.encode (S.decode z) = z := by + apply S.consistent + intro v + by_contra h + exact hp (prod_eq_zero (mem_univ v) (ite_eq_right h)) + +open scoped Classical in +/-- Builds `Backdrop C a b where base` with the specified `base`, `owner`, `param`, `paramAt`. -/ +abbrev backdrop : Backdrop C a b where + base := S.base + owner := .inl + param x y z := S.param x y (S.decode z) + paramAt i x y z := S.param x y (S.localState i z) + compatible x y z hp i := by + refine S.locality i x y _ x y _ (fun _ _ => rfl) (fun _ _ => rfl) ?_ + intro k hk + rw [localState, dite_eq_left hk] + exact (congrFun (S.valid x y z hp) ⟨k, .inr (.inr ⟨i, hk⟩)⟩).symm + local_param i x y z x' y' z' hx hy hz := by + apply S.locality _ _ _ _ _ _ _ (fun j hj => hx j (congrArg Sum.inl hj)) + (fun j hj => hy j (congrArg Sum.inl hj)) + intro k hk + simp only [localState, dite_eq_left hk] + exact hz _ (.inr rfl) + src := S.src + dst := S.dst + meets := S.meets + +open scoped Classical in +/-- Each shared assignment contributes once. Inconsistent assignments +contribute zero. -/ +theorem eval (x : Val a) (y : Val b) (f : X → F) : + ∑ z : S.State, (∏ v, S.backdrop.base.station v x y z) * f (S.backdrop.param x y z) = + ∑ a, f (S.param x y a) := by + let g (z : S.State) := (∏ v, S.base.station v x y z) * f (S.param x y (S.decode z)) + have hinj : Function.Injective S.encode := Function.LeftInverse.injective (g := S.decode) (fun _ + => rfl) + have hgood (a : Y.State) : g (S.encode a) = f (S.param x y a) := by + have h (v : S.Vertex) : S.checks v (S.encode a) := fun _ _ _ _ _ => rfl + change (∏ v, if S.checks v (S.encode a) then (1 : F) else 0) * f (S.param x y a) = _ + simp [h] + trans ∑ z ∈ univ.image S.encode, g z + · symm + refine sum_subset (subset_univ _) fun z _ hz => ?_ + have he : (∏ v, S.base.station v x y z) = 0 := by + by_contra hp + exact hz (mem_image.mpr ⟨S.decode z, mem_univ _, S.valid x y z hp⟩) + exact mul_eq_zero_of_left he _ + · rw [sum_image hinj.injOn] + exact sum_congr rfl (fun z _ => hgood z) + +end Sharing +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- +# Routing on the common host + +Independent blocks have distinct physical vertices but use the same +host slots. Every subbundle follows a source branch, crosses to the +peer's leaf, and follows the target branch backwards. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +variable {F V I : Type} {a b : Wire} {d : ℕ} {G : Bundled F a b} + +open Classical in +private theorem Routes.connect {Y : Type} (R : Routes G Y) (rel : G.V ⊕ Y → G.V ⊕ Y → Prop) + (pos : ∀ e, 0 < R.length e) + (first : ∀ e j, j.val = 0 → rel (.inl (G.src e)) (.inr (R.via e j))) + (last : ∀ e j, j.val + 1 = R.length e → rel (.inr (R.via e j)) (.inl (G.dst e))) + (mid : ∀ e j k, j.val + 1 = k.val → rel (.inr (R.via e j)) (.inr (R.via e k))) : + ∀ h, rel (R.src h) (R.dst h) := by + rintro ⟨e, i⟩ + have h := pos e + have hs (j : Fin (R.length e + 1)) : + (j.val = 0 ∧ R.src ⟨e, j⟩ = .inl (G.src e)) ∨ + ∃ k, k.val + 1 = j.val ∧ R.src ⟨e, j⟩ = .inr (R.via e k) := by + induction j using Fin.cases with + | zero => exact .inl ⟨rfl, rfl⟩ + | succ k => exact .inr ⟨k, rfl, rfl⟩ + have ht (j : Fin (R.length e + 1)) : + (j.val = R.length e ∧ R.dst ⟨e, j⟩ = .inl (G.dst e)) ∨ + ∃ k, k.val = j.val ∧ R.dst ⟨e, j⟩ = .inr (R.via e k) := by + induction j using Fin.lastCases with + | last => exact .inl ⟨rfl, by simp [dst]⟩ + | cast k => exact .inr ⟨k, rfl, by simp [dst]⟩ + rcases hs i with ⟨hs, es⟩ | ⟨j, hs, es⟩ <;> rcases ht i with ⟨ht, et⟩ | ⟨k, ht, et⟩ + · omega + · rw [es, et]; exact first e k (by omega) + · rw [es, et]; exact last e j (by omega) + · rw [es, et]; exact mid e j k (by omega) + +open Classical in +/-- One station per host slot per independent block. -/ +structure Fanout (G : Bundled F a b) (T : Trie V d) (I : Type) where + /-- The `Fanout` component of type `G.V → V × I`. -/ + site : G.V → V × I + one : Function.Injective site + near : ∀ e, (site (G.dst e)).1 ∈ T.near (site (G.src e)).1 + group : ∀ e, (site (G.src e)).2 = (site (G.dst e)).2 + +namespace Fanout +variable {T : Trie V d} (H : Fanout G T I) + +open Classical in +/-- In the case `.inl v`, this construction gives `(.inl (H.site v).1, (H.site v).2)`. -/ +def place : Node G.V d → Node V d × I + | .inl v => (.inl (H.site v).1, (H.site v).2) + | .inr u => (.inr ((H.site u.1).1, u.2), (H.site u.1).2) + +open Classical in +theorem injective : Function.Injective H.place := by + rintro (v|⟨v, i⟩) (w|⟨w, j⟩) h + all_goals simp only [place, Prod.mk.injEq, Sum.inl.injEq, Sum.inr.injEq, reduceCtorEq, + false_and] at h + · rw [H.one (Prod.ext h.1 h.2)] + · rw [H.one (Prod.ext h.1.1 h.2), h.1.2] + +open Classical in +/-- The value specified by `(v, i, T.address (H.site v).1 (H.site w).1 i)`. -/ +def side (v w : G.V) (i : Fin (d + 1)) : Relay G.V d := + (v, i, T.address (H.site v).1 (H.site w).1 i) + +open Classical in +/-- Builds `Routes G (Relay G.V d) where length _` with the specified `length`, `via`. -/ +abbrev route : Routes G (Relay G.V d) where + length _ := (d + 1) + (d + 1) + via e := Fin.append (H.side (G.src e) (G.dst e)) + (fun j => H.side (G.dst e) (G.src e) j.rev) + +open Classical in +/-- Requires `(H.place x).2 = (H.place y).2 ∧ (H.place y).1 ∈ T.adj (H.place x).1`. -/ +def linked (x y : Node G.V d) : Prop := + (H.place x).2 = (H.place y).2 ∧ (H.place y).1 ∈ T.adj (H.place x).1 + +open Classical in +private theorem reverse {x y} (h : H.linked x y) : H.linked y x := + ⟨h.1.symm, T.adj_symm h.2⟩ + +open Classical in +theorem arm (v w : G.V) : H.linked (.inl v) (.inr (H.side v w 0)) := + ⟨rfl, T.root _ _⟩ + +open Classical in +private theorem next (v w : G.V) (j k : Fin (d + 1)) (hj : j.val + 1 = k.val) : + H.linked (.inr (H.side v w j)) (.inr (H.side v w k)) := by + let s : Fin d := ⟨j.val, by have := k.isLt; omega⟩ + have h₁ : j = s.castSucc := Fin.ext rfl + have h₂ : k = s.succ := Fin.ext hj.symm + rw [h₁, h₂] + exact ⟨rfl, T.edge _ _ _⟩ + +open Classical in +private theorem bridge (e : G.E) : + H.linked (.inr (H.side (G.src e) (G.dst e) (Fin.last d))) + (.inr (H.side (G.dst e) (G.src e) (Fin.last d))) := + ⟨H.group e, T.join (H.near e)⟩ + +open Classical in +theorem edges (i : H.route.Hop) : H.linked (H.route.src i) (H.route.dst i) := by + apply Routes.connect H.route H.linked (fun _ => by change 0 < (d + 1) + (d + 1); omega) + · intro e j hj + have he : j = Fin.castAdd (d + 1) (0 : Fin (d + 1)) := Fin.ext hj + simp only [he, Fin.append_left] + exact H.arm _ _ + · intro e j hj + have he : j = Fin.natAdd (d + 1) (Fin.last d) := Fin.ext (by + change j.val + 1 = (d + 1) + (d + 1) at hj + change j.val = d + 1 + d + omega) + simp only [he, Fin.append_right, Fin.rev_last] + exact H.reverse (H.arm _ _) + · intro e j k hjk + change Fin ((d + 1) + (d + 1)) at j k + induction j using Fin.addCases <;> induction k using Fin.addCases + all_goals simp only [Fin.append_left, Fin.append_right] + · exact H.next _ _ _ _ hjk + · rename_i j k + change j.val + 1 = d + 1 + k.val at hjk + have hj : j = Fin.last d := Fin.ext (by have := j.isLt; simp; omega) + have hk : k = 0 := Fin.ext (by change k.val = 0; have := j.isLt; omega) + rw [hj, hk, Fin.rev_zero] + exact H.bridge e + · rename_i j k + change d + 1 + j.val + 1 = k.val at hjk + have := k.isLt + omega + · rename_i j k + apply H.reverse + apply H.next + change d + 1 + j.val + 1 = d + 1 + k.val at hjk + change (d + 1 - (k.val + 1)) + 1 = d + 1 - (j.val + 1) + have := k.isLt + omega + +end Fanout +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Squares.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Squares.lean new file mode 100644 index 0000000000..662edb8eca --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Squares.lean @@ -0,0 +1,985 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Sharing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Host +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Occupancy +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality + +/-! # Width and incident bundle counts for ordinary keys -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +open Finset + +variable {K : Type} [Fintype K] + +open scoped Classical in +private theorem by_key {A : Type} [Fintype A] (p : K → A → Prop) [∀ k, DecidablePred (p k)] + (keys : A → Finset K) (he : ∀ k i, p k i ↔ k ∈ keys i) (f : K → ℕ) (g : A → ℕ) : + (∑ k, ∑ i : {a // p k a}, g i.val * f k) = ∑ i, g i * (∑ k ∈ keys i, f k) := by + have row k : (∑ i : {a // p k a}, g i.val * f k) = + ∑ i, if k ∈ keys i then g i * f k else 0 := by + rw [← sum_subtype (univ.filter (p k)) (fun _ => mem_filter_univ _) (fun i => g i * f k), + sum_filter] + simp only [he] + simp_rw [row] + rw [sum_comm] + simp [mul_sum] + +variable {F T X E V : Type} [Field F] [Fintype E] [Fintype V] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) T E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) + +open scoped Classical in +private def traffic (f : K → ℕ) (v : S.Vertex) := + ∑ e : S.Edge, Packing.arityCost v (S.source e, S.target e) * f e.1 + +omit [Field F] in +open scoped Classical in +private theorem expanded (f : K → ℕ) (v : S.Vertex) : + S.traffic f v = + (∑ a, Packing.arityCost v (.inr (.inl a), .inr (.inr a)) * (∑ k ∈ S.seen a, f k)) + + (∑ e, Packing.arityCost v (.inr (.inl (S.src e)), .inr (.inl (S.dst e))) * + (∑ k ∈ S.seen (S.src e) ∩ S.seen (S.dst e), f k)) + + (∑ i : Place C, Packing.arityCost v (.inr (.inl i.1), .inl i) * (∑ k ∈ S.reads i, f k)) := by + rw [traffic, Fintype.sum_sigma] + simp only [Fintype.sum_sum_type, source, start, target, sum_add_distrib, + ← add_assoc] + refine congrArg₂ (·+·) (congrArg₂ (·+·) ?_ ?_) ?_ + · exact by_key (fun k a => k ∈ S.seen a) S.seen (fun _ _ => Iff.rfl) f + (fun a => Packing.arityCost v (.inr (.inl a), .inr (.inr a))) + · exact by_key (fun k e => k ∈ S.seen (S.src e) ∧ k ∈ S.seen (S.dst e)) + (fun e => S.seen (S.src e) ∩ S.seen (S.dst e)) (fun _ _ => mem_inter.symm) f + (fun e => Packing.arityCost v (.inr (.inl (S.src e)), .inr (.inl (S.dst e)))) + · exact by_key (fun k i => k ∈ S.reads i) S.reads (fun _ _ => Iff.rfl) f + (fun i => Packing.arityCost v (.inr (.inl i.1), .inl i)) + +omit [Field F] in +open scoped Classical in +private theorem traffic_item (f : K → ℕ) (i : Place C) : + S.traffic f (.inl i) = ∑ k ∈ S.reads i, f k := by + rw [expanded] + simp [Packing.arityCost, ite_mul] + +omit [Field F] in +open scoped Classical in +private theorem traffic_storage (f : K → ℕ) (v : V) : + S.traffic f (.inr (.inr v)) = ∑ k ∈ S.seen v, f k := by + rw [expanded] + simp [Packing.arityCost, ite_mul] + +omit [Field F] in +open scoped Classical in +private theorem traffic_hub (f : K → ℕ) (v : V) : + S.traffic f (.inr (.inl v)) ≤ + (1 + Packing.degree (fun e => (S.src e, S.dst e)) v) * (∑ k ∈ S.seen v, f k) + + ∑ i : Place C, if i.1 = v then ∑ k ∈ S.reads i, f k else 0 := by + rw [expanded, Packing.degree_sum, add_mul, one_mul, sum_mul] + refine Nat.add_le_add (Nat.add_le_add ?_ ?_) ?_ + · simp [Packing.arityCost, ite_mul] + · apply sum_le_sum + intro e _ + simp only [Packing.arityCost, Sum.inr.injEq, Sum.inl.injEq] + by_cases hi : S.src e = v + · rw [hi]; exact Nat.mul_le_mul_left _ (sum_le_sum_of_subset inter_subset_left) + by_cases hj : S.dst e = v + · rw [hj]; exact Nat.mul_le_mul_left _ (sum_le_sum_of_subset inter_subset_right) + simp [hi, hj] + · simp [Packing.arityCost, ite_mul] + +open scoped Classical in +private theorem arity_eq (v : S.Vertex) : + S.backdrop.base.arity v = + Fintype.card {i // Sum.inl (S.left i) = v} + Fintype.card {i // Sum.inl (S.right i) = v} + + S.traffic Y.width v := by + simp only [Bundled.arity, traffic, Packing.arityCost, add_mul, sum_add_distrib, ite_mul, + one_mul, zero_mul, add_assoc] + congr! 4 + +open scoped Classical in +private theorem degree_eq (v : S.Vertex) : + S.backdrop.base.degree v = S.traffic (fun _ => 1) v := by + simp only [Bundled.degree, traffic, Packing.arityCost, mul_one, sum_add_distrib] + +open scoped Classical in +theorem arity_item (i : Place C) : + S.backdrop.base.arity (.inl i) = Fintype.card {j // S.left j = i} + + Fintype.card {j // S.right j = i} + ∑ k ∈ S.reads i, Y.width k := by + rw [arity_eq, traffic_item] + simp [Fintype.card_subtype] + +open scoped Classical in +theorem arity_storage (v : V) : S.backdrop.base.arity (.inr (.inr v)) = ∑ k ∈ S.seen v, Y.width k + := by + rw [arity_eq, traffic_storage] + simp + +open scoped Classical in +theorem arity_hub (v : V) : S.backdrop.base.arity (.inr (.inl v)) ≤ + (1 + Packing.degree (fun e => (S.src e, S.dst e)) v) * (∑ k ∈ S.seen v, Y.width k) + + ∑ i : Place C, if i.1 = v then ∑ k ∈ S.reads i, Y.width k else 0 := by + rw [arity_eq] + simpa [Fintype.card_subtype] using S.traffic_hub Y.width v + +open scoped Classical in +theorem degree_item (i : Place C) : S.backdrop.base.degree (.inl i) = (S.reads i).card := by + rw [degree_eq, traffic_item] + simp + +open scoped Classical in +theorem degree_storage (v : V) : S.backdrop.base.degree (.inr (.inr v)) = (S.seen v).card := by + rw [degree_eq, traffic_storage] + simp + +open scoped Classical in +theorem degree_hub (v : V) : S.backdrop.base.degree (.inr (.inl v)) ≤ + (1 + Packing.degree (fun e => (S.src e, S.dst e)) v) * (S.seen v).card + + ∑ i : Place C, if i.1 = v then (S.reads i).card else 0 := by + rw [degree_eq] + simpa using S.traffic_hub (fun _ => 1) v + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +end + +/- Raw numerical inputs to the layout estimates. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +open Finset Packing Rounds + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) {h D T R g k : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + +open Classical in +/-- The indexed operation `Packing.degree (fun e => (S.src e, S.dst e)) v`. -/ +def seamDegree (v : V) := Packing.degree (fun e => (S.src e, S.dst e)) v + +open Classical in +/-- The value specified by `(1 + S.seamDegree v) * (∑ k ∈ S.seen v, Y.width k) + ∑ i : Place C, +if i.1 = v then ∑ k ∈ S.reads i, Y.width k else 0`. -/ +def ordinaryLoad (v : V) := + (1 + S.seamDegree v) * (∑ k ∈ S.seen v, Y.width k) + + ∑ i : Place C, if i.1 = v then ∑ k ∈ S.reads i, Y.width k else 0 + +open Classical in +/-- Counts the elements of `{j // S.left j = i} + Fintype.card {j // S.right j`. -/ +def exteriorLoad (i : Place C) := Fintype.card {j // S.left j = i} + Fintype.card {j // S.right j + = i} + +open Classical in +/-- The quantity computed by `S.exteriorLoad i + legWidth C i`. -/ +def stationLoad (i : Place C) := S.exteriorLoad i + legWidth C i + +variable {S} (G : S.Geo P k) + +open Classical in +/-- The data for the budgets construction, including `occupied`, `keys`, `seams`, `ordinary`, +`collectors`. -/ +structure Geo.Budgets (d ℓ : ℕ) (e : E → ℕ) : Prop where + occupied : (Fintype.card V : ℝ) * T ≤ W + keys : ∀ v, (S.seen v).card ≤ D ^ k + seams : ∀ v, S.seamDegree v ≤ D ^ k + ordinary : ∀ v, (S.ordinaryLoad v : ℝ) ≤ T / (D : ℝ) ^ (ℓ + 3) + collectors : (Fintype.card {i // G.frozen i} : ℝ) * D * T ≤ k * W + max : ∀ i, G.frozen i → S.stationLoad i ≤ k * (D : ℝ) * T + square : (∑ i : {i // G.frozen i}, (S.stationLoad i.val) ^ 2) ≤ k * W * T + residue : ∀ i, ¬ G.frozen i → legWidth C i ≤ T / (D : ℝ) ^ (ℓ + 3) + chambers : ∀ v, S.backdrop.chamberLoad e v ≤ (T / (D : ℝ) ^ (ℓ + 2)) * Real.sqrt M + total : (∑ i, legWidth C i) + (∑ j, seamWidth C e j) ≤ k * W * (1 + (d : ℝ)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +end + +/- # Contact counts in a profile -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset Packing Rounds + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} {e : E → ℕ} + +omit [Field F] [Fintype E] in +open Classical in +theorem sum_place {R : Type*} [AddCommMonoid R] (f : Place C → R) (v : V) : + (∑ i, if i.1 = v then f i else 0) = ∑ j, f ⟨v, j⟩ := by + rw [Fintype.sum_sigma, Fintype.sum_eq_single v (fun x hx => by simp [hx])] + simp + +namespace Backdrop +variable (B : Backdrop C a b) (p : Profile C e) (L : ℕ) + +open Classical in +theorem base_degree (v : B.base.V) : + (B.emitted p L).degree (.inl v) = + B.base.degree v + ∑ i, if B.owner i = v then 2 * M else 0 := by + simp only [Bundled.degree, emitted, Attach.net, Fintype.sum_sum_type, + Fintype.sum_prod_type, Sum.elim_inl, Sum.elim_inr, Function.comp_apply, + Sum.inl.injEq, reduceCtorEq, ite_false, sum_const_zero, add_zero, zero_add, + arm, Grid.point] + rw [← sum_add_distrib] + change (_ + ∑ i : Place C, + ((∑ _ : Fin M, if B.owner i = v then (1 : ℕ) else 0) + + ∑ _ : Fin M, if B.owner i = v then (1 : ℕ) else 0)) + _ = _ + have line (i : Place C) : + (∑ _ : Fin M, if B.owner i = v then (1 : ℕ) else 0) = if B.owner i = v then M else 0 := by + by_cases hi : B.owner i = v <;> simp [hi] + simp_rw [line] + have arms : (∑ i : Place C, ((if B.owner i = v then M else 0) + + (if B.owner i = v then M else 0))) = ∑ i : Place C, if B.owner i = v then 2 * M else 0 := by + apply sum_congr rfl + intro i _ + by_cases h : B.owner i = v <;> simp [h, two_mul] + rw [arms] + ac_rfl + +open Classical in +theorem degree_a (v : V) (j : Fin M) : + (B.emitted p L).degree (.inr (.inl (v, j))) = + Packing.degree (fun e => (B.src e, B.dst e)) v + (C v).stations.length := by + rw [degree_sum] + simp [-sum_boole, Bundled.degree, emitted, Attach.net, chambers, seamEnd, socket, Grid.map, + Fintype.sum_sum_type, Fintype.sum_prod_type, ite_and, arityCost, sum_add_distrib, + sum_place, add_assoc] + +open Classical in +theorem degree_b (v : V) (j : Fin M) : + (B.emitted p L).degree (.inr (.inr (v, j))) = (C v).stations.length := by + simp [-sum_boole, Bundled.degree, emitted, Attach.net, chambers, seamEnd, socket, Grid.map, + Fintype.sum_sum_type, Fintype.sum_prod_type, ite_and, sum_place] + +end Backdrop +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- Numerical data of one terminal configuration, before chunk encoding. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +open Finset Rounds +open SphereScale (q size budget probes) + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + +open Classical in +/-- The quantity computed by `64 * (budget g + 1) ^ 2 + 8 * (ℓ + 32) + 10`. -/ +def allocation (g ℓ : ℕ) := 64 * (budget g + 1) ^ 2 + 8 * (ℓ + 32) + 10 + +open Classical in +/-- The quantity computed by `L * (item C i).a + (item C i).b`. -/ +def energyAt (C : V → Surface.Cell F (M * r) (M * t) U E X) (L : ℕ) (i : Place C) := + L * (item C i).a + (item C i).b + +open Classical in +/-- Here `L` is the Frobenius power, `B` the block size and `m` +the number of private species. -/ +structure Geo.Raw (G : S.Geo P k) (ℓ L B m : ℕ) (e : E → ℕ) + (thin : Place C → Prop) (selector : K → Prop) : Prop where + occupied : (Fintype.card V : ℝ) * D * T ≤ W + seams : ∀ v, S.seamDegree v ≤ budget g + seamEnergy : ∀ i, e i ≤ budget g * D ^ 2 * SphereScale.energy ℓ D (m * B) + energy : ∀ i, energyAt C L i ≤ budget g * D ^ 2 * L * SphereScale.energy ℓ D (m * B) + collected : (∑ i : {i // G.frozen i}, (energyAt C L i.val : ℝ)) ≤ + budget g * (L : ℝ) * size ℓ D * W + collectors : (Fintype.card {i // G.frozen i} : ℝ) * D * T ≤ budget g * W + exterior : ∀ i, G.frozen i → S.exteriorLoad i ≤ budget g * D * T + square : (∑ i : {i // G.frozen i}, (S.exteriorLoad i.val : ℝ) ^ 2) ≤ budget g * W * T + light : ∀ v, Fintype.card {i : Fin (C v).stations.length // thin ⟨v, i⟩} ≤ probes ℓ D + heavy : ∀ v, Fintype.card {i : Fin (C v).stations.length // ¬thin ⟨v, i⟩} ≤ D ^ 5 + auxiliary : ∀ i, thin i → (item C i).a ≤ m * B ∧ (item C i).b + ≤ m * (Routing.Private.energyConstant * B ^ 2) + residue : ∀ i, ¬thin i → ¬G.frozen i → (item C i).a = 0 + keys : ∀ v, (S.seen v).card ≤ D ^ 14 + keyWidth : ∀ j, (Y.width j : ℝ) ≤ T / (q ℓ D : ℝ) + selectorWidth : ∀ j, selector j → (Y.width j : ℝ) ≤ m * B / (q ℓ D : ℝ) + reads : ∀ i, thin i → ∀ j ∈ S.reads i, selector j + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +end + +/- # Converting the two sphere energies to bit widths -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale.Scales +open Real Sphere.Layout + +variable {g ℓ D T L B m M r t : ℕ} (s : Scales g ℓ D T L B m) +include s + +private theorem root_bound {x : ℕ} (h : x ≤ budget g * D ^ 2 * (m * B * size ℓ D) ^ 2) : + sqrt (x : ℝ) ≤ budget g * (D : ℝ) * T := by + refine sqrt_le_iff.mpr ⟨by positivity, ?_⟩ + have hx : x ≤ (budget g * D * T) ^ 2 := calc + _ ≤ budget g * D ^ 2 * (m * B * size ℓ D) ^ 2 := h + _ ≤ (budget g) ^ 2 * D ^ 2 * T ^ 2 := by + gcongr + · exact Nat.le_self_pow (by decide) _ + · exact s.lower + _ = _ := by ring + exact_mod_cast hx + +theorem public_root (a : ℕ) (h : a ≤ budget g * D ^ 2 * energy ℓ D (m * B)) : + sqrt ((m : ℝ) * B * a) ≤ budget g * (D : ℝ) * T := by + rw [← Nat.cast_mul, ← Nat.cast_mul] + apply s.root_bound + exact (Nat.mul_le_mul_left (m * B) h).trans_eq (by unfold energy; ring) + +theorem private_root (a : ℕ) (h : a ≤ budget g * D ^ 2 * L * energy ℓ D (m * B)) : + sqrt ((m : ℝ) * a) * (q ℓ D : ℝ) ^ 2 ≤ budget g * (D : ℝ) * T := by + have hh : (m * a) * (q ℓ D) ^ 4 ≤ budget g * D ^ 2 * (m * B * size ℓ D) ^ 2 := calc + _ ≤ m * (budget g * D ^ 2 * L * energy ℓ D (m * B)) * (q ℓ D) ^ 4 := by gcongr + _ = _ := by unfold energy; rw [s.block]; ring + have hk := s.root_bound hh + push_cast at hk + rw [show (q ℓ D : ℝ) ^ 4 = ((q ℓ D : ℝ) ^ 2) ^ 2 by ring, + sqrt_mul (by positivity), sqrt_sq (by positivity)] at hk + exact hk + +omit s in +theorem auxiliary_root (a : ℕ) (h : a ≤ m * (Routing.Private.energyConstant * B ^ 2)) : + sqrt ((m : ℝ) * a) ≤ budget g * ((m : ℝ) * B) := by + have hg : Routing.Private.energyConstant ≤ (budget g) ^ 2 := + (show Routing.Private.energyConstant ≤ budget g by have := overhead (g := g); omega).trans + (Nat.le_self_pow (by decide) _) + have hh : m * a ≤ (budget g * (m * B)) ^ 2 := calc + _ ≤ m * (m * (Routing.Private.energyConstant * B ^ 2)) := Nat.mul_le_mul_left _ h + _ ≤ m * (m * ((budget g) ^ 2 * B ^ 2)) := by gcongr + _ = _ := by ring + exact sqrt_le_iff.mpr ⟨by positivity, by exact_mod_cast hh⟩ + +theorem small_species : (m : ℝ) * B ≤ T / (q ℓ D : ℝ) := by + rw [le_div_iff₀ (by exact_mod_cast s.qpos)] + exact_mod_cast (Nat.mul_le_mul_left (m * B) (Nat.le_self_pow (by decide : 8 ≠ 0) _)).trans s.lower + +theorem small_chunks : (chunks ℓ D : ℝ) ≤ T / (q ℓ D : ℝ) := + (show (chunks ℓ D : ℝ) ≤ m * B by exact_mod_cast s.smallM).trans s.small_species + +/-- A record of the private state left by a crossing is a thin wire. -/ +theorem hidden_width (j : ℕ) (hj : j ≤ budget g * D ^ 2 * L * energy ℓ D (m * B)) : + (Sphere.Chunk.width m j : ℝ) ≤ T / (q ℓ D : ℝ) := by + have hq : (0 : ℝ) < q ℓ D := by exact_mod_cast s.qpos + have he : 8 * (budget g : ℝ) * D ≤ q ℓ D := by + have hz : 8 * budget g * D ≤ q ℓ D := calc + _ ≤ D * D * D := by gcongr <;> have := s.bound <;> have := s.large <;> omega + _ = D ^ 3 := by ring + _ ≤ _ := Nat.pow_le_pow_right s.Dpos (by omega) + exact_mod_cast hz + have hT : 2 * (q ℓ D : ℝ) ≤ T := by + have hz : 2 * q ℓ D ≤ T := calc + _ ≤ q ℓ D * q ℓ D := Nat.mul_le_mul_right _ (by have := s.bound; have := s.Dle; omega) + _ = chunks ℓ D := (pow_two _).symm + _ ≤ T := s.smallM.trans ((Nat.le_mul_of_pos_right _ s.apos).trans s.lower) + exact_mod_cast hz + have hs : 8 * sqrt ((m : ℝ) * j) * q ℓ D ≤ T := by + apply (mul_le_mul_iff_left₀ hq).mp + linarith only [s.private_root j hj, mul_le_mul_of_nonneg_right he (Nat.cast_nonneg T)] + refine (Sphere.Chunk.width_le m j).trans ((le_div_iff₀ hq).mpr ?_) + linarith only [hs, hT] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale.Scales +end + +/- # Polynomial bounds on the physical vertex and bundle counts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo +open Finset Packing Rounds + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k d ℓ : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + {G : S.Geo P k} {e : E → ℕ} (hb : G.Budgets d ℓ e) (p : Profile C e) (L : ℕ) + +include hb + +open Classical in +private theorem hub_degree (v : V) (hD : 4 ≤ D) : + S.backdrop.base.degree (.inr (.inl v)) ≤ 3 * (D ^ k) ^ 2 := by + have hr (i : Place C) := (card_le_card (S.within i)).trans (hb.keys i.1) + have h := S.degree_hub v + rw [sum_place] at h + have hsum : (∑ j, (S.reads ⟨v, j⟩).card) ≤ D ^ k * D ^ k := calc + _ ≤ (C v).stations.length * D ^ k := by + simpa using sum_le_card_nsmul univ (fun j => (S.reads ⟨v, j⟩).card) (D ^ k) (fun i _ => hr _) + _ ≤ _ := Nat.mul_le_mul_right _ (G.count v) + calc + _ ≤ (1 + D ^ k) * D ^ k + D ^ k * D ^ k := h.trans + (Nat.add_le_add (Nat.mul_le_mul (Nat.add_le_add_left (hb.seams v) 1) (hb.keys v)) hsum) + _ ≤ _ := by + have hp : 1 ≤ D ^ k := Nat.one_le_pow _ _ (by omega) + nlinarith + +open Classical in +theorem contacts_bound (hD : 4 ≤ D) (v : S.Position) : + (S.backdrop.emitted p L).degree v ≤ 8 * (D ^ k) ^ 2 := by + have h : 1 ≤ D ^ k := Nat.one_le_pow _ _ (by omega) + rcases v with v | ⟨v, j⟩ | ⟨v, j⟩ + · rw [Backdrop.base_degree] + rcases v with i | v | v + · rw [degree_item] + simp + have hr := (card_le_card (S.within i)).trans (hb.keys i.1) + nlinarith only [hr, h, G.chunks] + · simp only [reduceCtorEq, ↓reduceIte, sum_const_zero, add_zero, ge_iff_le] + exact (hub_degree hb v hD).trans (Nat.mul_le_mul_right _ (by decide : 3 ≤ 8)) + · rw [degree_storage] + simp + nlinarith only [hb.keys v, h] + · rw [Backdrop.degree_a] + change S.seamDegree v + (C v).stations.length ≤ _ + nlinarith only [hb.seams v, G.count v, h] + · rw [Backdrop.degree_b] + nlinarith only [G.count v, h] + +open Classical in +theorem size_bound (hD : 4 ≤ D) : + ((Fintype.card (S.backdrop.emitted p L).V : ℝ) + Fintype.card (S.backdrop.emitted p L).E) * T ≤ + (D : ℝ) ^ radius k * W := by + let Z := S.backdrop.emitted p L + have hp : 1 ≤ D ^ k := Nat.one_le_pow _ _ (by omega) + have hc : Fintype.card (Place C) ≤ Fintype.card V * D ^ k := by + rw [Fintype.card_sigma] + simpa using sum_le_card_nsmul univ (fun v => (C v).stations.length) (D ^ k) + (fun v _ => G.count v) + have hv : Fintype.card Z.V ≤ Fintype.card V * (5 * D ^ k) := by + change Fintype.card S.Position ≤ _ + simp only [Position, Vertex, Grid, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] + nlinarith only [hc, Nat.mul_le_mul_left (Fintype.card V) hp, + Nat.mul_le_mul_left (Fintype.card V) G.chunks] + have he : Fintype.card Z.E ≤ Fintype.card Z.V * (8 * (D ^ k) ^ 2) := by + have hsum := sum_le_card_nsmul univ Z.degree (8 * (D ^ k) ^ 2) (fun v _ + => contacts_bound hb p L hD v) + rw [Bundled.degree_total, card_univ, smul_eq_mul] at hsum + omega + have h : Fintype.card Z.V + Fintype.card Z.E ≤ Fintype.card V * D ^ radius k := calc + _ ≤ Fintype.card Z.V * (1 + 8 * (D ^ k) ^ 2) := by rw [mul_add, mul_one]; omega + _ ≤ Fintype.card V * (5 * D ^ k) * (1 + 8 * (D ^ k) ^ 2) := Nat.mul_le_mul_right _ hv + _ ≤ Fintype.card V * (64 * (D ^ k) ^ 3) := by + rw [mul_assoc] + apply Nat.mul_le_mul_left + nlinarith [Nat.le_self_pow (by decide : 3 ≠ 0) (D ^ k)] + _ ≤ _ := Nat.mul_le_mul_left _ (polynomial hD k) + calc + _ ≤ ((Fintype.card V : ℝ) * (D : ℝ) ^ radius k) * T := by + apply mul_le_mul_of_nonneg_right _ (by positivity) + exact_mod_cast h + _ = (D : ℝ) ^ radius k * (Fintype.card V * T) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left hb.occupied (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo +end + +/- # The ordinary selector and residue wires fit the small budget -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +open Finset Rounds +open SphereScale (Scales q size budget probes) + +open Classical in +private theorem part_bound {I : Type} [Fintype I] (p : I → Prop) (a b : ℝ) (f : I → ℝ) + (ha : ∀ i, p i → f i ≤ a) (hb : ∀ i, ¬ p i → f i ≤ b) : + ∑ i, f i ≤ Fintype.card {i // p i} * a + Fintype.card {i // ¬p i} * b := by + calc + _ ≤ ∑ i, if p i then a else b := sum_le_sum (fun i _ => by + split_ifs with h + · exact ha i h + · exact hb i h) + _ = _ := by simp [sum_ite, Fintype.card_subtype] + +variable {F U X E V K : Type} [Fintype E] [Fintype V] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k ℓ L B m : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + {G : S.Geo P k} {e : E → ℕ} {thin : Place C → Prop} {selector : K → Prop} + +namespace Geo.Raw + +variable (hr : G.Raw ℓ L B m e thin selector) (s : Scales g ℓ D T L B m) + +include hr in +open Classical in +theorem station_sum (v : V) (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (f : Place C → ℝ) + (hf : ∀ i, thin i → f i ≤ a) (hg : ∀ i, ¬ thin i → f i ≤ b) : + ∑ j, f ⟨v, j⟩ ≤ (probes ℓ D : ℝ) * a + (D : ℝ) ^ 5 * b := by + refine (part_bound (fun j => thin ⟨v, j⟩) a b (fun j => f ⟨v, j⟩) + (fun j => hf ⟨v, j⟩) (fun j => hg ⟨v, j⟩)).trans ?_ + gcongr + · exact_mod_cast hr.light v + · exact_mod_cast hr.heavy v + +open Classical in +theorem room (hD : 1 ≤ D) {z : ℕ} (hz : z ≤ 29) : + (D : ℝ) ^ z * (T / (q ℓ D : ℝ)) ≤ T / (D : ℝ) ^ (ℓ + 3) := by + have h : 1 ≤ (D : ℝ) := by exact_mod_cast hD + unfold q + rw [Nat.cast_pow, ← mul_div_assoc, div_le_div_iff₀ (by positivity) (by positivity), + mul_comm ((D : ℝ) ^ z), mul_assoc, ← pow_add] + exact mul_le_mul_of_nonneg_left (pow_le_pow_right₀ h (by omega)) (by positivity) + +include hr s in +open Classical in +theorem ordinary_small (v : V) : (S.ordinaryLoad v : ℝ) ≤ T / (D : ℝ) ^ (ℓ + 3) := by + have hD : 1600 ≤ (D : ℝ) := by exact_mod_cast (show 1600 ≤ D by have := s.bound; omega) + have hD' : 1 ≤ (D : ℝ) := by linarith + let x := T / (q ℓ D : ℝ) + let y := (m : ℝ) * B / (q ℓ D : ℝ) + have hx : 0 ≤ x := by unfold x; positivity + have hy : 0 ≤ y := by unfold y; positivity + have hxy : size ℓ D * y ≤ x := by + unfold x y + rw [← mul_div_assoc, mul_comm (size ℓ D : ℝ)] + gcongr + exact_mod_cast s.lower + have per (u : V) (l : Finset K) (hl : l ⊆ S.seen u) (z : ℝ) (hz : 0 ≤ z) + (hw : ∀ i ∈ l, (Y.width i : ℝ) ≤ z) : ∑ i ∈ l, (Y.width i : ℝ) ≤ (D : ℝ) ^ 14 * z := by + calc + _ ≤ l.card * z := by simpa using sum_le_card_nsmul l _ z hw + _ ≤ _ := by gcongr; exact_mod_cast (card_le_card hl).trans (hr.keys u) + have hv := per v (S.seen v) Subset.rfl x hx (fun k _ => hr.keyWidth k) + let f (i : Place C) := ∑ j ∈ S.reads i, (Y.width j : ℝ) + have hh := hr.station_sum v ((D : ℝ) ^ 14 * y) ((D : ℝ) ^ 14 * x) (by positivity) (by positivity) + f + (fun i hi => per i.1 _ (S.within i) y hy (fun j hj => hr.selectorWidth j (hr.reads i hi j hj))) + (fun i _ => per i.1 _ (S.within i) x hx (fun j _ => hr.keyWidth j)) + have hd : (1 : ℝ) + S.seamDegree v ≤ (D : ℝ) ^ 2 := by + have : (S.seamDegree v : ℝ) ≤ D := by + exact_mod_cast (hr.seams v).trans (by have := s.large; omega) + nlinarith + have hl : (probes ℓ D : ℝ) * ((D : ℝ) ^ 14 * y) ≤ (D : ℝ) ^ 16 * x := by + calc + _ = 1600 * (D : ℝ) ^ 15 * (size ℓ D * y) := by unfold probes; push_cast; ring + _ ≤ D * (D : ℝ) ^ 15 * x := by gcongr + _ = _ := by ring + have hsum : (S.ordinaryLoad v : ℝ) ≤ 2 * (D : ℝ) ^ 16 * x + (D : ℝ) ^ 19 * x := by + unfold ordinaryLoad + rw [sum_place] + push_cast + have := mul_le_mul hd hv (by positivity) (by positivity) + unfold f at hh + linarith only [this, hh, hl] + refine hsum.trans (le_trans ?_ (room s.Dpos (show 20 ≤ 29 by decide))) + change _ ≤ (D : ℝ) ^ 20 * x + have h₁ := mul_le_mul_of_nonneg_right (pow_le_pow_right₀ hD' (by decide : 16 ≤ 19)) hx + have h₂ := mul_le_mul_of_nonneg_right (show (3 : ℝ) + ≤ D by linarith) (show 0 ≤ (D : ℝ) ^ 19 * x by positivity) + linarith only [h₁, h₂] + +end Geo.Raw +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +end + +/- +# Three kinds of legs + +A public seam and a collector can use the full local energy budget. +A private residue gains the square root of the species ratio. An +untouched auxiliary has the smaller, per-block energy bounds. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo.Raw +open Finset Rounds Real +open SphereScale (Scales q size budget chunks) + +variable {F U X E V K : Type} [Fintype E] [Fintype V] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k ℓ L B m : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + {G : S.Geo P k} {e : E → ℕ} {thin : Place C → Prop} {selector : K → Prop} + (hr : G.Raw ℓ L B m e thin selector) (s : Scales g ℓ D T L B m) + (ha : M * r = m * B) (hb : M * t = m) (hM : M = SphereScale.chunks ℓ D) + +include hr s + +open Classical in +private theorem first_bound (i : Place C) : + (item C i).a ≤ budget g * D ^ 2 * SphereScale.energy ℓ D (m * B) := by + apply Nat.le_of_mul_le_mul_left _ s.pos + calc + _ ≤ energyAt C L i := Nat.le_add_right _ _ + _ ≤ _ := (hr.energy i).trans_eq (by ring) + +omit s in +open Classical in +private theorem second_bound (i : Place C) : + (item C i).b ≤ budget g * D ^ 2 * L * SphereScale.energy ℓ D (m * B) := + (Nat.le_add_left _ _).trans (hr.energy i) + +omit hr in +open Classical in +private theorem rounds_le : (SphereScale.chunks ℓ D : ℝ) ≤ budget g * (D : ℝ) * T := by + have hk : 1 ≤ budget g * D := Nat.mul_pos (by have := SphereScale.budget_large g; omega) s.Dpos + have h := (s.smallM.trans ((Nat.le_mul_of_pos_right _ s.apos).trans s.lower)).trans + (Nat.le_mul_of_pos_left T hk) + exact_mod_cast h + +include ha hM in +open Classical in +theorem seam_le (i : E) : seamWidth C e i ≤ 5 * (budget g : ℝ) * D * T := by + unfold seamWidth proxy + have he : (M : ℝ) * r = m * B := by exact_mod_cast ha + rw [he, hM] + linarith only [s.public_root _ (hr.seamEnergy i), rounds_le s] + +include ha hb hM + +omit hr s hM [Fintype E] [Fintype V] in +open Classical in +theorem leg_eq (i : Place C) : + legWidth C i = 4 * sqrt ((m : ℝ) * B * (item C i).a) + + 4 * sqrt ((m : ℝ) * (item C i).b) + 2 * M := by + have he : (M : ℝ) * r = m * B := by exact_mod_cast ha + have hf : (M : ℝ) * t = m := by exact_mod_cast hb + unfold legWidth proxy + rw [he, hf] + ring + +open Classical in +theorem leg_le (i : Place C) : legWidth C i ≤ 10 * (budget g : ℝ) * D * T := by + have h₁ := s.public_root _ (first_bound hr s i) + have h₂ := s.private_root _ (second_bound hr i) + have hq : 1 ≤ (q ℓ D : ℝ) ^ 2 := one_le_pow₀ (by exact_mod_cast s.qpos) + have hh := (le_mul_of_one_le_right (sqrt_nonneg _) hq).trans h₂ + rw [leg_eq ha hb, show (M : ℝ) = SphereScale.chunks ℓ D by rw [hM]] + linarith only [h₁, hh, rounds_le s] + +open Classical in +theorem thin_le (i : Place C) (hi : thin i) : legWidth C i ≤ 10 * (budget g : ℝ) * ((m : ℝ) * B) + := by + obtain ⟨h₁, h₂⟩ := hr.auxiliary i hi + have hm : (M : ℝ) ≤ m * B := by rw [hM]; exact_mod_cast s.smallM + have h₃ : sqrt ((m : ℝ) * B * (item C i).a) ≤ m * B := by + refine sqrt_le_iff.mpr ⟨by positivity, ?_⟩ + rw [pow_two] + gcongr + exact_mod_cast h₁ + have h₄ : (m : ℝ) * B ≤ budget g * ((m : ℝ) * B) := + le_mul_of_one_le_left (by positivity) (by exact_mod_cast (show 1 ≤ budget g by + have := SphereScale.budget_large g; omega)) + rw [leg_eq ha hb] + linarith only [h₃, h₄, hm, SphereScale.Scales.auxiliary_root (g := g) _ h₂] + +open Classical in +theorem residue_le (i : Place C) (hi : ¬G.frozen i) : + legWidth C i ≤ (D : ℝ) ^ 3 * (T / (q ℓ D : ℝ)) := by + have hD : 16 ≤ (D : ℝ) := by exact_mod_cast (show 16 ≤ D by have := s.bound; omega) + have hg : (budget g : ℝ) ≤ D := by exact_mod_cast (show budget g ≤ D by have := s.large; omega) + have hq : 1 ≤ (q ℓ D : ℝ) := by exact_mod_cast s.qpos + have hv : 10 * (budget g : ℝ) ≤ (D : ℝ) ^ 3 := by nlinarith [sq_nonneg ((D : ℝ) - 4)] + by_cases hthin : thin i + · exact (hr.thin_le s ha hb hM i hthin).trans (mul_le_mul hv s.small_species (by positivity) (by + positivity)) + · have hk := s.private_root _ (second_bound hr i) + have hh : sqrt ((m : ℝ) * (item C i).b) * (q ℓ D : ℝ) ≤ (budget g : ℝ) * D * T := + (mul_le_mul_of_nonneg_left (by nlinarith : (q ℓ D : ℝ) + ≤ (q ℓ D : ℝ) ^ 2) (sqrt_nonneg _)).trans hk + have hm : (M : ℝ) * (q ℓ D : ℝ) ≤ T := (le_div_iff₀ (by positivity)).mp (hM ▸ s.small_chunks) + have hd : 4 * (budget g : ℝ) * D + 2 ≤ (D : ℝ) ^ 3 := by + nlinarith [mul_le_mul_of_nonneg_right hg (Nat.cast_nonneg D), + mul_le_mul_of_nonneg_right hD (sq_nonneg (D : ℝ))] + rw [leg_eq ha hb, hr.residue i hthin hi, Nat.cast_zero, mul_zero, sqrt_zero, mul_zero, + zero_add, ← mul_div_assoc, le_div_iff₀ (by positivity)] + linarith only [hh, hm, mul_le_mul_of_nonneg_right hd (Nat.cast_nonneg T)] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo.Raw +end + +/- # The frozen square budget after chunk encoding -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo.Raw +open Finset Rounds Real +open SphereScale (Scales size budget) + +variable {F U X E V K : Type} [Fintype E] [Fintype V] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k ℓ L B m : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + {G : S.Geo P k} {e : E → ℕ} {thin : Place C → Prop} {selector : K → Prop} + (hr : G.Raw ℓ L B m e thin selector) (s : Scales g ℓ D T L B m) + (ha : M * r = m * B) (hb : M * t = m) (hM : M = SphereScale.chunks ℓ D) + +open Classical in +private theorem three_sq (x y z : ℝ) : + (4 * x + 4 * y + 2 * z) ^ 2 ≤ 48 * (x ^ 2 + y ^ 2) + 12 * z ^ 2 := by + nlinarith only [sq_nonneg (2 * x - 2 * y), sq_nonneg (2 * x - z), sq_nonneg (2 * y - z)] + +include s ha hb +omit [Fintype E] [Fintype V] in +open Classical in +private theorem leg_square (i : Place C) : + legWidth C i ^ 2 ≤ 48 * ((m : ℝ) * B / L) * energyAt C L i + 12 * (M : ℝ) ^ 2 := by + have hL : (0 : ℝ) < L := by exact_mod_cast s.pos + have hB : (L : ℝ) ≤ B := by + exact_mod_cast (s.block ▸ Nat.le_mul_of_pos_right L (pow_pos s.qpos 4)) + have h : (m : ℝ) * B * (item C i).a + m * (item C i).b ≤ (m : ℝ) * B / L * energyAt C L i := by + unfold energyAt + push_cast + rw [div_mul_eq_mul_div, le_div_iff₀ hL] + linarith only [mul_le_mul_of_nonneg_left hB (show 0 ≤ (m : ℝ) * (item C i).b by positivity)] + rw [leg_eq ha hb] + refine (three_sq _ _ _).trans ?_ + rw [sq_sqrt (by positivity), sq_sqrt (by positivity)] + linarith only [h] + +include hr hM + +open Classical in +theorem frozen_square : + (∑ i : {i // G.frozen i}, (S.stationLoad i.val) ^ 2) ≤ 122 * (budget g : ℝ) * W * T := by + have hW : 0 ≤ W := le_trans (by positivity) hr.occupied + have hL : (0 : ℝ) < L := by exact_mod_cast s.pos + have hm : M ≤ T := hM ▸ s.smallM.trans ((Nat.le_mul_of_pos_right _ s.apos).trans s.lower) + let N := Fintype.card {i // G.frozen i} + have hm' : (N : ℝ) * M ^ 2 ≤ (budget g : ℝ) * W * T := calc + _ ≤ (N : ℝ) * T ^ 2 := by gcongr + _ ≤ N * (D : ℝ) * T * T := by + rw [pow_two, ← mul_assoc] + gcongr + exact le_mul_of_one_le_right (by positivity) (by exact_mod_cast s.Dpos) + _ ≤ _ := mul_le_mul_of_nonneg_right hr.collectors (by positivity) + let c := (m : ℝ) * B / L + have hc : c * (∑ i : {i // G.frozen i}, (energyAt C L i.val : ℝ)) ≤ + (budget g : ℝ) * W * T := calc + _ ≤ c * ((budget g : ℝ) * L * size ℓ D * W) := + mul_le_mul_of_nonneg_left hr.collected (by unfold c; positivity) + _ = (budget g : ℝ) * W * ((m : ℝ) * B * size ℓ D) := by unfold c; field_simp + _ ≤ _ := mul_le_mul_of_nonneg_left (by exact_mod_cast s.lower) (by positivity) + have hp (i : {i // G.frozen i}) : S.stationLoad i.val ^ 2 ≤ + 2 * (S.exteriorLoad i.val : ℝ) ^ 2 + 96 * c * energyAt C L i.val + 24 * (M : ℝ) ^ 2 := by + unfold stationLoad c + nlinarith only [leg_square s ha hb i.val, sq_nonneg ((S.exteriorLoad i.val : ℝ) - legWidth C + i.val)] + have := sum_le_sum (fun i (_ : i ∈ univ) => hp i) + simp only [sum_add_distrib, ← mul_sum, sum_const, card_univ, nsmul_eq_mul] at this + unfold N at hm' + linarith only [this, hc, hm', hr.square] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo.Raw +end + +/- # Charges of insertion tables, hubs, and storage positions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +open Finset Packing Rounds + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) {e : E → ℕ} (p : Profile C e) (L : ℕ) + +omit [Field F] [Fintype K] in +open Classical in +theorem seen_load (v : V) : ∑ i ∈ S.seen v, Y.width i ≤ S.ordinaryLoad v := by + unfold ordinaryLoad + exact (Nat.le_mul_of_pos_left _ (by omega)).trans (Nat.le_add_right _ _) + +open Classical in +theorem item_load (i : Place C) : + ((S.backdrop.emitted p L).arity (.inl (.inl i)) : ℝ) ≤ S.stationLoad i + S.ordinaryLoad i.1 + := by + have hs := S.backdrop.station_le p L (.inl i) + have hu := (sum_le_sum_of_subset (f := Y.width) (S.within i)).trans (S.seen_load i.1) + have hp : push S.backdrop.owner (legWidth C) (.inl i) = legWidth C i := by + simp [push] + rw [hp, arity_item] at hs + unfold stationLoad exteriorLoad + have hv : ((∑ k ∈ S.reads i, Y.width k : ℕ) : ℝ) ≤ S.ordinaryLoad i.1 := Nat.cast_le.mpr hu + push_cast at hs hv ⊢ + linarith only [hs, hv] + +open Classical in +theorem hubs_load (v : V ⊕ V) : + ((S.backdrop.emitted p L).arity (.inl (.inr v)) : ℝ) ≤ S.ordinaryLoad (Sum.elim id id v) := by + have hs := S.backdrop.station_le p L (.inr v) + have hp : push S.backdrop.owner (legWidth C) (.inr v) = 0 := by simp [push] + rw [hp, add_zero] at hs + refine hs.trans (Nat.cast_le.mpr ?_) + cases v with + | inl v => exact S.arity_hub v + | inr v => rw [arity_storage]; exact S.seen_load v + +open Classical in +theorem total_base : ∑ i, S.backdrop.base.width i ≤ ∑ v, S.ordinaryLoad v := by + have h := S.backdrop.base.width_le_source (fun v : V => .inr (.inl v)) + (fun e => ⟨(S.start e.2).val, rfl⟩) + exact h.trans (sum_le_sum (fun v _ => S.arity_hub v)) + +open Classical in +theorem ties_zero (i j : Place C) : + (S.backdrop.emitted p L).ties (.inl (.inl i)) (.inl (.inl j)) = 0 := by + have he (e : (S.backdrop.emitted p L).E) : + (∀ w, (S.backdrop.emitted p L).src e ≠ .inl (.inl w)) ∨ + (∀ w, (S.backdrop.emitted p L).dst e ≠ .inl (.inl w)) := by + rcases e with e | e | e + · left; intro w h; cases h + · left; intro w h; cases h + · right; intro w h; cases h + unfold Bundled.ties + rw [← sum_add_distrib] + apply sum_eq_zero + intro e _ + rcases he e with hs | ht + · rw [ite_eq_right (fun h => hs i h.1), ite_eq_right (fun h => hs j h.2), zero_add] + · rw [ite_eq_right (fun h => ht j h.2), ite_eq_right (fun h => ht i h.1), zero_add] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing +end + +/- # Concentration estimates for an emitted profile -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo +open Finset Packing Rounds + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k d ℓ : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + (G : S.Geo P k) (hD : D = 2 ^ d) (hd : 4 ≤ D) + {e : E → ℕ} (hb : G.Budgets d ℓ e) (p : Profile C e) (L : ℕ) + +include hd hb + +open Classical in +private theorem ordinary_le (v : V) : (S.ordinaryLoad v : ℝ) ≤ T := + (hb.ordinary v).trans (div_le_self (by positivity) + (one_le_pow₀ (by exact_mod_cast (show 1 ≤ D by omega)))) + +open Classical in +private theorem sum_width : (∑ i, ((S.backdrop.emitted p L).width i : ℝ)) ≤ + (k + 1) * W * (1 + (d : ℝ)) := by + have hp : (∑ i, (S.backdrop.base.width i : ℝ)) ≤ W := calc + _ ≤ ∑ v, (S.ordinaryLoad v : ℝ) := by exact_mod_cast S.total_base + _ ≤ (Fintype.card V : ℝ) * T := by + simpa using sum_le_card_nsmul univ _ _ (fun v _ => G.ordinary_le hd hb v) + _ ≤ _ := hb.occupied + have hw : 0 ≤ W := (by positivity : 0 ≤ (Fintype.card V : ℝ) * T) |>.trans hb.occupied + linarith only [S.backdrop.emitted_width p L, hp, hb.total, mul_nonneg hw (Nat.cast_nonneg d)] + +open Classical in +private theorem max_core (v : (G.layout hD hd p L).Mobile) : + ((S.backdrop.emitted p L).arity v.val : ℝ) ≤ T / (D : ℝ) ^ (ℓ + 2) := by + let B := (T : ℝ) / (D : ℝ) ^ (ℓ + 3) + have h₀ : 0 ≤ B := by unfold B; positivity + have hcap : 2 * B ≤ T / (D : ℝ) ^ (ℓ + 2) := by + unfold B + rw [show ℓ + 3 = (ℓ + 2) + 1 by omega, pow_succ, ← mul_div_assoc, + div_le_div_iff₀ (by positivity) (by positivity)] + have h : (2 : ℝ) ≤ D := by exact_mod_cast (show 2 ≤ D by omega) + linarith only [mul_le_mul_of_nonneg_right h (show 0 ≤ (T : ℝ) * (D : ℝ) ^ (ℓ + + 2) by positivity)] + obtain ⟨(i | v) | s, hv⟩ := v + · have hi : ¬ G.frozen i := fun h => hv ((G.fixed_item hD hd p L _).mpr h) + have hl (j) : S.left j ≠ i := fun h => hi (h ▸ G.left j) + have hr (j) : S.right j ≠ i := fun h => hi (h ▸ G.right j) + have hload := S.item_load p L i + simp [stationLoad, exteriorLoad, hl, hr] at hload + have hi' := (add_le_add (hb.residue i hi) (hb.ordinary i.1)) + exact (hload.trans hi').trans (by rw [← two_mul]; exact hcap) + · exact ((S.hubs_load p L v).trans (hb.ordinary _)).trans ((le_mul_of_one_le_left h₀ (by + norm_num)).trans hcap) + · have hm : 0 < M := by + rcases s with ⟨_, j⟩ | ⟨_, j⟩ <;> exact Nat.zero_lt_of_lt j.isLt + exact (mul_le_mul_iff_left₀ (by positivity : 0 < Real.sqrt M)).mp + ((S.backdrop.chamber_le p L s).trans (hb.chambers _)) + +open Classical in +private theorem square_frozen : + (∑ v : (G.layout hD hd p L).Frozen, ((S.backdrop.emitted p L).arity v.val : ℝ) ^ 2) ≤ + radius k * W * T := by + have hW : 0 ≤ W := le_trans (by positivity) hb.occupied + have hcount : (Fintype.card {i // G.frozen i} : ℝ) * T ≤ k * W := calc + _ ≤ Fintype.card {i // G.frozen i} * (D : ℝ) * T := by + gcongr + exact le_mul_of_one_le_right (by positivity) (by exact_mod_cast (show 1 ≤ D by omega)) + _ ≤ _ := hb.collectors + rw [← (G.frozenEquiv hD hd p L).sum_comp] + calc + _ ≤ ∑ i : {i // G.frozen i}, (2 * (S.stationLoad i.val) ^ 2 + 2 * (T : ℝ) ^ 2) := by + apply sum_le_sum + intro i _ + have ht := (S.item_load p L i.val).trans (add_le_add_right (G.ordinary_le hd hb i.val.1) _) + have h₁ := pow_le_pow_left₀ (by positivity) ht 2 + change ((S.backdrop.emitted p L).arity (.inl (.inl i.val)) : ℝ) ^ 2 ≤ _ + nlinarith only [h₁, sq_nonneg (S.stationLoad i.val - T)] + _ = 2 * (∑ i : {i // G.frozen i}, (S.stationLoad i.val) ^ 2) + + 2 * (Fintype.card {i // G.frozen i} * T) * T := by + rw [sum_add_distrib, ← mul_sum, sum_const, card_univ, nsmul_eq_mul] + ring + _ ≤ 4 * (k : ℝ) * W * T := by + linarith only [hb.square, mul_le_mul_of_nonneg_right hcount (Nat.cast_nonneg T)] + _ ≤ _ := by gcongr; exact_mod_cast (show 4 * k ≤ radius k by unfold radius; omega) + +open Classical in +theorem caps : (G.layout hD hd p L).Caps P ℓ := by + have hW : 0 ≤ W := le_trans (by positivity) hb.occupied + have hrad : 2 * (k + 1) ≤ radius k := by unfold radius; omega + refine ⟨G.host_count hd, size_bound hb p L hd, ?_, ?_, ?_, G.square_frozen hD hd hb p L, + G.max_core hD hd hb p L, ?_, ?_, ?_⟩ + · intro v + refine ((contacts_bound hb p L hd v).trans ?_).trans (polynomial hd k) + exact Nat.mul_le_mul (by decide) (Nat.pow_le_pow_right (by positivity) (by decide)) + · rw [← Fintype.card_congr (G.frozenEquiv hD hd p L)] + exact hb.collectors.trans (by gcongr; omega) + · intro v + obtain ⟨i, rfl⟩ := (G.frozenEquiv hD hd p L).surjective v + calc + _ ≤ S.stationLoad i.val + S.ordinaryLoad i.val.1 := S.item_load p L i.val + _ ≤ (k : ℝ) * D * T + T := add_le_add (hb.max _ i.property) (G.ordinary_le hd hb _) + _ ≤ ((k : ℝ) + 1) * D * T := by + have hh : 1 ≤ (D : ℝ) := by exact_mod_cast (show 1 ≤ D by omega) + linarith only [le_mul_of_one_le_left (Nat.cast_nonneg T) hh] + _ ≤ _ := by gcongr; exact_mod_cast (show k + 1 ≤ radius k by omega) + · intro v w + obtain ⟨i, rfl⟩ := (G.frozenEquiv hD hd p L).surjective v + obtain ⟨j, rfl⟩ := (G.frozenEquiv hD hd p L).surjective w + change ((S.backdrop.emitted p L).ties (.inl (.inl i.val)) (.inl (.inl j.val)) : ℝ) ≤ _ + rw [ties_zero, Nat.cast_zero] + positivity + · have hx := G.external hD hd p L + have hh := (S.backdrop.emitted p L).sum_mobile (fun v => ¬ (G.layout hD hd p L).fixed v) + (fun i he => he (hx.1 i)) (fun i he => he (hx.2 i)) + calc + _ ≤ 2 * (∑ i, ((S.backdrop.emitted p L).width i : ℝ)) := by exact_mod_cast hh + _ ≤ 2 * ((k + 1) * W * (1 + (d : ℝ))) := mul_le_mul_of_nonneg_left (G.sum_width hd hb p L) + (by positivity) + _ = (2 * ((k : ℝ) + 1)) * W * (1 + d) := by ring + _ ≤ _ := by gcongr; exact_mod_cast hrad + · exact (G.sum_width hd hb p L).trans (by gcongr; exact_mod_cast (show k + 1 ≤ radius k by omega)) + +variable {u : ℕ} (hu : 0 < u) + +open Classical in +/-- The value specified by `(G.layout hD hd p L).finish (G.external hD hd p L) hu`. -/ +abbrev output := (G.layout hD hd p L).finish (G.external hD hd p L) hu + +omit hb in +open Classical in +theorem sum_output (x : Val a) (y : Val b) : + ∑ p : Profile C e, p.sign * (G.output hD hd p L hu).diagram.eval x y = + ∑ s, Surface.eval L C e (S.param x y s) := by + rw [← S.eval x y (Surface.eval L C e)] + have ht := S.backdrop.expansion (d := e) L Profile.widths x y + refine Eq.trans ?_ (ht.trans ?_) + · apply sum_congr rfl + intro p _ + rw [output, Fanout.eval_finish, Bundled.eval_diagram] + · congr! + +open Classical in +theorem concentrated {N : ℕ} (hN : Fanout.exponent (radius k) ℓ ≤ N) (hs : u * D ^ N ≤ T) : + Concentrated P (G.output hD hd p L hu) N d ℓ := + (G.layout hD hd p L).concentrated P hD hd (by unfold radius; omega) hN hu hs _ + (G.caps hD hd hb p L) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Trie.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Trie.lean new file mode 100644 index 0000000000..714430bf74 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Layout/Trie.lean @@ -0,0 +1,254 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Encode + +/-! +# A common binary tree for each host position + +At a core position edges for different neighbors share a prefix tree. +At a frozen position each neighbor has a separate path from the root. +Thus a frozen station of large arity need not send all its bits through +one core relay. All potential relay positions are fixed by the host. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +open Classical in +/-- The indexing data represented by `Fin d → Bool`. -/ +abbrev Address (d : ℕ) := Fin d → Bool +open Classical in +/-- Indexes the relay by the coordinates of `V × Fin (d + 1) × Address d`. -/ +abbrev Relay (V : Type) (d : ℕ) := V × Fin (d + 1) × Address d +open Classical in +/-- Indexes the node by the coordinates of `V ⊕ Relay V d`. -/ +abbrev Node (V : Type) (d : ℕ) := V ⊕ Relay V d + +open Classical in +theorem node_count (V : Type) [Fintype V] (d : ℕ) : + Fintype.card (Node V d) = (1 + (d + 1) * 2 ^ d) * Fintype.card V := by + simp [Node, Relay, Address] + ring + +open Classical in +/-- Each potential neighbor gets its own address. -/ +structure Trie (V : Type) (d : ℕ) where + /-- The `Trie` component of type `V → Prop`. -/ + frozen : V → Prop + /-- The `Trie` component of type `V → Finset V`. -/ + near : V → Finset V + symm : ∀ u v, u ∈ near v → v ∈ near u + /-- The encoding map carried by `Trie`, with type `V → V → Address d`. -/ + code : V → V → Address d + inject : ∀ v, Set.InjOn (code v) (near v) + +namespace Trie +variable {V : Type} {d : ℕ} + +open Classical in +/-- Builds `Trie V d where frozen` with the specified `frozen`, `near`, `symm`, `code`. -/ +def make (frozen : V → Prop) (near : V → Finset V) + (hs : ∀ u v, u ∈ near v → v ∈ near u) (hd : ∀ v, (near v).card ≤ 2 ^ d) : Trie V d where + frozen := frozen + near := near + symm := hs + code v u := if h : u ∈ near v then + binaryCode ↥(near v) d (by simpa using hd v) ⟨u, h⟩ else fun _ => false + inject v u hu w hw he := by + change u ∈ near v at hu + change w ∈ near v at hw + simp only [dite_eq_left hu, dite_eq_left hw] at he + exact congrArg Subtype.val ((binaryCode _ _ _).injective he) + +variable (T : Trie V d) + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def fixed : Node V d → Prop := Sum.elim T.frozen (fun _ => False) + +open Classical in +/-- Returns `h.choose` when `h : ∃ w ∈ T.near v, T.code v w = c` holds, and `v` otherwise. -/ +def peer (v : V) (c : Address d) : V := + if h : ∃ w ∈ T.near v, T.code v w = c then h.choose else v + +open Classical in +theorem peer_code {v w : V} (hw : w ∈ T.near v) : T.peer v (T.code v w) = w := by + have h : ∃ u ∈ T.near v, T.code v u = T.code v w := ⟨w, hw, rfl⟩ + rw [peer, dite_eq_left h] + exact T.inject v h.choose_spec.1 hw h.choose_spec.2 + +open Classical in +/-- Evaluates `if i.val < j then c i else false` at the input `i`. -/ +def mask (c : Address d) (j : ℕ) : Address d := + fun i => if i.val < j then c i else false + +open Classical in +/-- Returns `T.code v w` when `T.frozen v` holds, and `mask (T.code v w) j` otherwise. -/ +def address (v w : V) (j : Fin (d + 1)) := + if T.frozen v then T.code v w else mask (T.code v w) j + +open Classical in +/-- The value specified by `(v, j, T.address v w j)`. -/ +def branch (v w : V) (j : Fin (d + 1)) : Relay V d := (v, j, T.address v w j) + +open Classical in +theorem address_last (v w : V) : T.address v w (Fin.last d) = T.code v w := by + have h : mask (T.code v w) d = T.code v w := funext fun i => ite_eq_left i.isLt + simp [address, h] + +open Classical in +/-- The value specified by `Fin.cases (.inl v) (fun i => .inr (v, i.castSucc, if T.frozen v then +c else mask c i)) j`. -/ +def up (v : V) (j : Fin (d + 1)) (c : Address d) : Node V d := + Fin.cases (.inl v) (fun i => .inr (v, i.castSucc, if T.frozen v then c else mask c i)) j + +open Classical in +/-- The down of type `Node V d` for the given inputs. -/ +def down (v : V) (j : Fin (d + 1)) (c : Address d) (b : Bool) : Node V d := + Fin.lastCases (.inr (T.branch (T.peer v c) v (Fin.last d))) + (fun i => .inr (v, i.succ, if T.frozen v then c else Function.update c i b)) j + +open Classical in +private theorem up_branch (v w : V) (j : Fin d) : + T.up v j.succ (T.address v w j.succ) = .inr (T.branch v w j.castSucc) := by + simp only [up, Fin.cases_succ, branch, address] + by_cases h : T.frozen v + · simp [h] + · simp only [ite_eq_right h] + congr 3 + funext i + simp only [mask, Fin.val_succ, Fin.val_castSucc] + split_ifs <;> first | rfl | omega + +open Classical in +private theorem down_branch (v w : V) (j : Fin d) : + T.down v j.castSucc (T.address v w j.castSucc) (T.code v w j) = .inr (T.branch v w j.succ) := by + simp only [down, Fin.lastCases_castSucc, branch, address] + by_cases h : T.frozen v + · simp [h] + · simp only [ite_eq_right h] + congr 3 + funext i + by_cases he : i = j + · subst i; simp [mask] + · rw [Function.update_of_ne he] + simp only [mask, Fin.val_succ, Fin.val_castSucc] + split_ifs <;> first | rfl | omega + +open Classical in +/-- The possible used in the `Trie` construction. -/ +def possible : Node V d → Finset (Node V d) + | .inl v => if T.frozen v then univ.image (fun c : Address d => .inr (v, 0, c)) + else {.inr (v, 0, fun _ => false)} + | .inr (v, j, c) => {T.up v j c, T.down v j c false, T.down v j c true} + +open Classical in +/-- Selects the elements of `(T.possible x)` satisfying `(fun y => x ∈ T.possible y)`. -/ +def adj (x : Node V d) := (T.possible x).filter (fun y => x ∈ T.possible y) + +open Classical in +/-- Selects the elements of `(T.adj x)` satisfying `(fun y => ¬ T.fixed x ∧ ¬ T.fixed y)`. -/ +def core (x : Node V d) := (T.adj x).filter (fun y => ¬ T.fixed x ∧ ¬ T.fixed y) + +open Classical in +theorem adj_symm {x y : Node V d} : y ∈ T.adj x → x ∈ T.adj y := by + simp [adj, and_comm] + +open Classical in +theorem core_symm {x y : Node V d} (h : y ∈ T.core x) : x ∈ T.core y := by + obtain ⟨h, hx, hy⟩ := mem_filter.mp h + exact mem_filter.mpr ⟨T.adj_symm h, hy, hx⟩ + +open Classical in +theorem separate {v w : Node V d} (h : w ∈ T.adj v) : ¬ (T.fixed v ∧ T.fixed w) := by + rintro ⟨hv, hw⟩ + cases v with + | inr _ => exact hv + | inl v => + cases w with + | inr _ => exact hw + | inl w => + change T.frozen v at hv + have := (mem_filter.mp h).1 + simp [possible, hv] at this + +open Classical in +theorem relay_degree (v : Relay V d) : (T.adj (.inr v)).card ≤ 3 := by + obtain ⟨u, j, c⟩ := v + refine (card_filter_le _ _).trans ?_ + unfold possible + have hh := card_insert_le (T.down u j c false) {T.down u j c true} + simp only [card_singleton] at hh + exact (card_insert_le _ _).trans (by omega) + +open Classical in +theorem degree (v : Node V d) : (T.adj v).card ≤ max 3 (2 ^ d) := by + cases v with + | inl v => + refine (card_filter_le _ _).trans ?_ + simp only [possible] + split_ifs + · apply le_trans card_image_le + simp [Address] + · simp + | inr v => exact (T.relay_degree v).trans (le_max_left _ _) + +open Classical in +theorem core_degree (v : Node V d) : (T.core v).card ≤ 3 := by + cases v with + | inl v => + by_cases h : T.frozen v + · simp [core, fixed, h] + · refine (card_filter_le _ _).trans ((card_filter_le _ _).trans ?_) + simp [possible, h] + | inr v => exact (card_filter_le _ _).trans (T.relay_degree v) + +open Classical in +private theorem mem_up (v : V) (j : Fin (d + 1)) (c : Address d) : + T.up v j c ∈ T.possible (.inr (v, j, c)) := mem_insert_self _ _ + +open Classical in +private theorem mem_down (v : V) (j : Fin (d + 1)) (c : Address d) (b : Bool) : + T.down v j c b ∈ T.possible (.inr (v, j, c)) := by cases b <;> simp [possible] + +open Classical in +theorem root (v w : V) : .inr (T.branch v w 0) ∈ T.adj (.inl v) := by + apply mem_filter.mpr + refine ⟨?_, T.mem_up v 0 (T.address v w 0)⟩ + by_cases h : T.frozen v + · simp [possible, h, branch] + · have he : mask (T.code v w) 0 = fun _ => false := by funext i; simp [mask] + simp [possible, h, branch, address, he] + +open Classical in +theorem edge (v w : V) (j : Fin d) : + .inr (T.branch v w j.succ) ∈ T.adj (.inr (T.branch v w j.castSucc)) := by + apply mem_filter.mpr + constructor + · rw [← T.down_branch] + exact T.mem_down _ _ _ _ + · rw [← T.up_branch] + exact T.mem_up _ _ _ + +open Classical in +private theorem end_mem {v w : V} (h : w ∈ T.near v) : + .inr (T.branch w v (Fin.last d)) ∈ T.possible (.inr (T.branch v w (Fin.last d))) := by + have he := T.mem_down v (Fin.last d) (T.address v w (Fin.last d)) false + simpa only [down, Fin.lastCases_last, branch, address_last, T.peer_code h] using he + +open Classical in +theorem join {v w : V} (h : w ∈ T.near v) : + .inr (T.branch w v (Fin.last d)) ∈ T.adj (.inr (T.branch v w (Fin.last d))) := + mem_filter.mpr ⟨T.end_mem h, T.end_mem (T.symm w v h)⟩ + +end Trie +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Ledger/Quota.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Ledger/Quota.lean new file mode 100644 index 0000000000..1cba67ce95 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Ledger/Quota.lean @@ -0,0 +1,477 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.History +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Squares +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Debit.Legs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Proof.Initial + +/-! # Counting linked spans and exterior pins at one station -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Coloring Finset + +variable {F : Type} [Field F] {S : Scheme F} {r : S.format.obj} + {x y : Wire} {G : Diagram F x y} (p : S.Presentation r G) + +open scoped Classical in +/-- Count exposed ends in two ways, first in diagram order and then +by the local pin numbering. -/ +private theorem exterior_sum (v : G.V) : + Packing.exterior G id v = ∑ s : B S.e, + if S.peer r (p.vertex v, s) = none then S.width r (p.vertex v, s) else 0 := by + let f (e : G.End) := if G.station e = v ∧ S.peer r (p.toSeating.ends e).1 = none then 1 else 0 + have hin (e : G.E) : S.peer r (p.toSeating.ends (.inl (.inr e))).1 ≠ none := by + rw [(p.internal e).1]; simp + have hout (e : G.E) : S.peer r (p.toSeating.ends (.inr (.inr e))).1 ≠ none := by + rw [(p.proper _ _ (p.internal e).1).1]; simp + have h : ∑ e, f e = Packing.exterior G id v := by + simp only [Diagram.End, Fintype.sum_sum_type, f, p.input, p.output, hin, hout, and_true, + and_false, ↓reduceIte, sum_const_zero, add_zero] + simp only [Diagram.station, Packing.exterior, Fintype.card_subtype, card_filter, id_eq] + rfl + rw [← h, ← G.portEquiv.sum_comp, Fintype.sum_sigma, Fintype.sum_eq_single v] + · let c (t : S.LocalPin r (p.vertex v)) := if S.peer r (p.vertex v, t.1) = none then 1 else 0 + have hc (t : G.Port v) : f (G.portEquiv ⟨v, t⟩) = c (p.pin v t) := by + simp only [f, G.station_port, true_and, p.toSeating.ends_at] + rfl + simp only [hc] + rw [(p.pin v).sum_comp c, Fintype.sum_sigma] + refine sum_congr rfl fun s _ => ?_ + by_cases h : S.peer r (p.vertex v, s) = none <;> simp [c, h] + · intro u hu + exact sum_eq_zero fun t _ => by simp [f, G.station_port, hu] + +open scoped Classical in +/-- Each linked span contributes its full width, independently of +direction. This counts both ends of a loop at the same station. -/ +theorem arity_links (u : ℕ) (v : G.V) + (uniform : ∀ i : S.Span, (S.peer r i).isSome → S.width r i = u) : + (univ.filter fun s : B S.e => (S.peer r (p.vertex v, s)).isSome).card * u + + Packing.exterior G id v = G.arity v := by + have h : G.arity v = ∑ s : B S.e, S.width r (p.vertex v, s) := by + simpa only [Diagram.arity, Diagram.Port, Fintype.card_sum, card_slots, Fintype.card_sigma, + Fintype.card_fin] using Fintype.card_congr (p.pin v) + rw [h, p.exterior_sum, ← Nat.nsmul_eq_mul, ← sum_const, sum_filter, ← sum_add_distrib] + refine sum_congr rfl fun s _ => ?_ + cases he : S.peer r (p.vertex v, s) with + | none => simp + | some q => simp [uniform _ (by rw [he]; rfl)] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- +# The square budget after subtracting exterior wires + +Rounding and routing cost at most a multiple of T/D² per +station. Squaring this error leaves an O(D T²) term even when +an occupied cell retains D⁵ frozen stations. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo +open Finset Rounds +open SphereScale (Scales size chunks) + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k σ L B m u n : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + {G : S.Geo P k} {e : E → ℕ} (sc : Scales g σ D T L B m) + (ha : M * r = m * B) (hb : M * t = m) (hM : M = SphereScale.chunks σ D) + +open scoped Classical in +private theorem squares (x y z : ℝ) : (4 * x + 4 * y + 4 * z) ^ 2 ≤ 48 * (x ^ 2 + y ^ 2 + z ^ 2) + := by + nlinarith only [sq_nonneg (x - y), sq_nonneg (x - z), sq_nonneg (y - z)] + +include sc in +open scoped Classical in +private theorem rate (x y : ℕ) : + (m : ℝ) * B * x + m * y ≤ T / ((L : ℝ) * size σ D) * (L * x + y) := by + have hL : (0 : ℝ) < L := Nat.cast_pos.mpr sc.pos + have hs : (0 : ℝ) < size σ D := Nat.cast_pos.mpr sc.apos + have hl : (L : ℝ) ≤ B := by + exact_mod_cast (sc.block ▸ Nat.le_mul_of_pos_right L (pow_pos sc.qpos 4)) + have ht : (m : ℝ) * B * size σ D ≤ T := by exact_mod_cast sc.lower + calc + _ ≤ ((m : ℝ) * B / L) * (L * x + y) := by + rw [div_mul_eq_mul_div, le_div_iff₀ hL] + linarith only [mul_le_mul_of_nonneg_left hl (show (0 : ℝ) ≤ m * y by positivity)] + _ ≤ _ := by + apply mul_le_mul_of_nonneg_right _ (by positivity) + rw [div_le_div_iff₀ hL (mul_pos hL hs)] + linarith only [mul_le_mul_of_nonneg_right ht hL.le] + +open scoped Classical in +private theorem margin (D c σ u T : ℕ) (hd : 4 ≤ D) + (hs : u * D ^ (Fanout.exponent c σ) ≤ T) : (u : ℝ) * ((D : ℝ) ^ c + 1) ≤ T / (D : ℝ) ^ 2 := by + have hh : c + 3 ≤ Fanout.exponent c σ := by + have h := Nat.le_self_pow (by decide : 2 ≠ 0) (c + σ + 1) + unfold Fanout.exponent; omega + have ht : u * D ^ (c + 3) ≤ T := (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) + hh)).trans hs + have hp : (1 : ℝ) ≤ (D : ℝ) ^ c := one_le_pow₀ (by exact_mod_cast (show 1 ≤ D by omega)) + refine (le_div_iff₀ (by positivity)).mpr (le_trans ?_ (show (u : ℝ) * D ^ (c + 3) + ≤ T by exact_mod_cast ht)) + have hd' : (2 : ℝ) ≤ D := by exact_mod_cast (show 2 ≤ D by omega) + have he : (D : ℝ) ^ c + 1 ≤ (D : ℝ) ^ c * D := by + linarith only [hp, mul_le_mul_of_nonneg_left hd' (zero_le_one.trans hp)] + rw [show c + 3 = (c + 1) + 2 by omega, pow_add, pow_succ (D : ℝ) c, ← mul_assoc] + gcongr + +include sc ha hb hM in +open scoped Classical in +theorem internal_square (hD : D = 2 ^ n) (hd : 4 ≤ D) (hbud : G.Budgets n σ e) (p : Profile C e) + (hs : u * D ^ (Fanout.exponent (radius k) σ) ≤ T) (i : Place C) {x : ℝ} (hx : 0 ≤ x) + (he : x + S.exteriorLoad i ≤ (((S.backdrop.emitted p L).pad u).arity (.inl (.inl i)) : ℝ) + u) : + x ^ 2 ≤ 48 * (T / ((L : ℝ) * size σ D) * (energyAt C L i : ℝ) + ((T : ℝ) / D ^ 2) ^ 2) := by + let E := S.backdrop.emitted p L + let j : E.V := .inl (.inl i) + have hp : (E.pad u).arity j ≤ E.arity j + u * D ^ (radius k) := + (E.arity_pad u j).trans (Nat.add_le_add_left (Nat.mul_le_mul_left _ ((G.caps hD hd hbud p + L).degree j)) _) + have ht : ((E.pad u).arity j : ℝ) + u ≤ E.arity j + T / (D : ℝ) ^ 2 := by + have he' : ((E.pad u).arity j : ℝ) ≤ E.arity j + u * (D : ℝ) ^ (radius k) + := by exact_mod_cast hp + linarith only [he', margin D _ _ _ _ hd hs] + have ho : (S.ordinaryLoad i.1 : ℝ) ≤ T / (D : ℝ) ^ 2 := (hbud.ordinary _).trans (by + gcongr + · exact_mod_cast (show 1 ≤ D by omega) + · omega) + have hc : (M : ℝ) ≤ T / (D : ℝ) ^ 2 := by + rw [le_div_iff₀ (by positivity)] + exact_mod_cast (Nat.mul_le_mul_right _ (hM ▸ sc.smallM)).trans sc.smallR + have hload : (E.arity j : ℝ) ≤ S.exteriorLoad i + legWidth C i + S.ordinaryLoad i.1 + := S.item_load p L i + rw [Raw.leg_eq ha hb] at hload + let A := Real.sqrt ((m : ℝ) * B * (item C i).a) + let B' := Real.sqrt ((m : ℝ) * (item C i).b) + have hi : x ≤ 4 * A + 4 * B' + 4 * (T / (D : ℝ) ^ 2) := by + change x + S.exteriorLoad i ≤ ((E.pad u).arity j : ℝ) + u at he + unfold A B'; linarith only [he, ht, hload, hc, ho] + refine ((pow_le_pow_left₀ hx hi 2).trans (squares ..)).trans ?_ + unfold A B' energyAt + rw [Real.sq_sqrt (by positivity), Real.sq_sqrt (by positivity), Nat.cast_add, Nat.cast_mul] + exact mul_le_mul_of_nonneg_left (add_le_add_left (rate sc _ _) _) (by norm_num) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo +end + +/- # Restricting the collected energy to one occupied cell -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Ledger +open Finset Surface + +variable {V : Type} [Fintype V] {I : V → Type} [∀ v, Fintype (I v)] + +open scoped Classical in +theorem fiber {A : Type} [AddCommMonoid A] (frozen : Sigma I → Prop) + [DecidablePred frozen] (f : {i // frozen i} → A) (v : V) : + (∑ i, if i.val.1 = v then f i else 0) = + ∑ j : {j : I v // frozen ⟨v, j⟩}, f ⟨⟨v, j.val⟩, j.property⟩ := by + let eq : (Σ v, {j : I v // frozen ⟨v, j⟩}) ≃ {i // frozen i} := { + toFun := fun t => ⟨⟨t.1, t.2.val⟩, t.2.property⟩ + invFun := fun t => ⟨t.val.1, ⟨t.val.2, t.property⟩⟩ + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + rw [← eq.sum_comp, Fintype.sum_sigma, sum_eq_single v] + · exact sum_congr rfl fun _ _ => ite_eq_left rfl + · intro i _ hi + exact sum_eq_zero fun _ _ => ite_eq_right hi + · simp + +variable {F Z E X : Type} {r t : ℕ} (s : Stage F r t Z V E X) (j : ℕ) + (frozen : Layout.Place s.scene.cell → Prop) + +omit [Fintype V] in +open scoped Classical in +theorem collected (v : V) (hf : ∀ i, frozen i → (Layout.item s.scene.cell i).label.role + = .collector) : + (∑ i : {i : Fin (s.scene.cell v).stations.length // frozen ⟨v, i⟩}, + energyOf j (Layout.item s.scene.cell ⟨v, i.val⟩)) ≤ s.tally j Role.collected v := by + let f (a : s.St) := a.label.role.collected (energyOf j a) + have he : s.tally j Role.collected v = ∑ i, f ((s.scene.cell v).stations.get i) := by + rw [← List.sum_ofFn] + change _ = (List.ofFn (f ∘ (s.scene.cell v).stations.get)).sum + rw [← List.map_ofFn, List.ofFn_get] + rfl + rw [he] + let t := univ.filter (fun i => frozen ⟨v, i⟩) + refine le_trans ?_ (sum_le_sum_of_subset (subset_univ t)) + rw [sum_subtype t (fun _ => mem_filter_univ _) (fun i => f ((s.scene.cell v).stations.get i))] + apply sum_le_sum + intro i _ + change _ ≤ (Layout.item s.scene.cell ⟨v, i.val⟩).label.role.collected _ + rw [hf _ i.property]; rfl + +open scoped Classical in +theorem charges {A : Type} [Fintype A] (f E : A → ℝ) (T D L x : ℝ) + (hT : 0 ≤ T) (hD : 0 < D) (hL : 0 < L) (hx : 0 ≤ x) + (hc : (Fintype.card A : ℝ) ≤ D ^ 5) (he : ∑ i, E i ≤ x) + (h : ∀ i, (f i) ^ 2 ≤ 48 * (T / L * E i + (T / D ^ 2) ^ 2)) : + ∑ i, (f i) ^ 2 ≤ 128 * (T * x / L + D * T ^ 2) := by + have hh := sum_le_sum (s := univ) (fun i _ => h i) + simp only [← mul_sum, sum_add_distrib, sum_const, card_univ, nsmul_eq_mul] at hh + calc + _ ≤ _ := hh + _ ≤ 48 * (T / L * x + D ^ 5 * (T / D ^ 2) ^ 2) := by gcongr + _ = 48 * (T * x / L + D * T ^ 2) := by field_simp + _ ≤ _ := by gcongr; norm_num + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Ledger +end + +/- # Aggregating squared collector charges in one cell -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Ledger +open Finset Rounds Surface + +variable {F Z V E X : Type} [Fintype V] {r t : ℕ} + +open scoped Classical in +theorem sq_cell (s : Stage F r t Z V E X) (j : ℕ) (fixed : Layout.Place s.scene.cell → Prop) + (f : {i // fixed i} → ℝ) (v : V) {σ D T : ℕ} + (hcard : Fintype.card {i : Fin (s.scene.cell v).stations.length // fixed ⟨v, i⟩} ≤ D ^ 5) + (hf : ∀ i, fixed i → (Layout.item s.scene.cell i).label.role = .collector) + (hD : 0 < D) (hL : 0 < (j : ℝ) * SphereScale.size σ D) + (hsq : ∀ i, (f i) ^ 2 ≤ 48 * ((T : ℝ) / ((j : ℝ) * SphereScale.size σ D) * + energyOf j (Layout.item s.scene.cell i.val) + ((T : ℝ) / D ^ 2) ^ 2)) : + (∑ i, if i.val.1 = v then (f i) ^ 2 else 0) ≤ + 128 * ((T : ℝ) * s.tally j Role.collected v / ((j : ℝ) * SphereScale.size σ D) + + D * (T : ℝ) ^ 2) := by + let I := {i : Fin (s.scene.cell v).stations.length // fixed ⟨v, i⟩} + let x (i : I) : {j // fixed j} := ⟨⟨v, i.val⟩, i.property⟩ + let e (i : I) := energyOf j (Layout.item s.scene.cell (x i).val) + have he : (∑ i, e i) ≤ s.tally j Role.collected v := collected s j fixed v hf + refine (fiber fixed (fun i => (f i) ^ 2) v).le.trans ?_ + exact charges (f ∘ x) (fun i => (e i : ℝ)) _ _ _ _ (Nat.cast_nonneg _) + (Nat.cast_pos.mpr hD) hL (Nat.cast_nonneg _) (by exact_mod_cast hcard) + (by exact_mod_cast he) (fun i => hsq (x i)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Ledger +end + +/- # Aligning live child slots with the vertices of their parent -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer + +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Node Sharing) + +variable {F K N X Z : Type} [Field F] [Finite K] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} (U : Printer F K N m d h ℓ M r t q D k n u j z) + (G : (Key.share s Q).Geo P k) {a : Atlas P.Occupied P.grid.Seam m d h} (π : Palette a w q) + (old : P.V ↪ B m) (data : U.rows.obj) (status : (Children.Header m d).obj) + +namespace Physical +variable {U G π old data status} (B : U.Physical G π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "S" => Key.share s Q +local notation "V" => Node (Sharing.Position S) (Sharing.radius k * n) + +omit [Finite K] in +open scoped Classical in +theorem child_frozen (i : V) : Children.frozen U.slot (U.slot (B.child p i)) ↔ + (B.term p).freeze.frozen i := by + rw [Children.frozen_slot] + refine (Children.fixed_iff U.dyadic U.large G ((G.layout U.dyadic U.large p j).place i).1).trans + ?_ + cases i <;> rfl + +open scoped Classical in +/-- A live child at these coordinates arises from exactly one vertex based +at this parent. The equality applies to weights in any additive monoid. -/ +theorem sum_child (live : Coloring.B m → Coloring.B h → Coloring.B U.childBits → Bool) + (hl : ∀ i : U.template.scheme.Vtx, live (U.split i.1).1 i.2.1 (U.split i.1).2 = true ↔ + i ∈ Set.range (B.vertex p)) + (v : P.Occupied) {α : Type*} [AddCommMonoid α] (f : Coloring.B U.childBits → α) : + (∑ i, if live (a.coord v).1 (a.coord v).2 i then f i else 0) = + ∑ j : V, if (S).home (root j) = v then f (U.slot (B.child p j)) else 0 := by + let loc (i : Coloring.B U.childBits) : U.template.scheme.Vtx := + (U.split.symm ((a.coord v).1, i), (a.coord v).2, 0) + have lv (i) : live (a.coord v).1 (a.coord v).2 i = true ↔ loc i ∈ Set.range (B.vertex p) := by + simpa only [loc, Equiv.apply_symm_apply] using hl (loc i) + have spot (j : V) (hj : (S).home (root j) = v) : B.vertex p j = loc (U.slot (B.child p j)) := by + obtain ⟨h₁, h₂⟩ := B.address p j + rw [hj] at h₁ h₂ + exact Prod.ext (U.split.eq_symm_apply.mpr h₁) (Prod.ext h₂ (Fin.eq_zero _)) + symm + rw [← Finset.sum_filter, ← Finset.sum_filter] + refine Finset.sum_bij (fun j _ => U.slot (B.child p j)) ?_ ?_ ?_ (fun _ _ => rfl) + · intro j hj + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, (lv _).mpr ⟨j, + spot j (Finset.mem_filter.mp hj).2⟩⟩ + · intro i hi j hj e + apply (B.vertex p).injective + rw [spot i (Finset.mem_filter.mp hi).2, spot j (Finset.mem_filter.mp hj).2, e] + · intro i hi + obtain ⟨j, hj⟩ := (lv _).mp (Finset.mem_filter.mp hi).2 + obtain ⟨h₁, h₂⟩ := B.address p j + rw [hj] at h₁ h₂ + simp only [loc, Equiv.apply_symm_apply, Prod.mk.injEq] at h₁ + have hv := a.coord.injective (Prod.ext h₁.1.symm h₂.symm) + exact ⟨j, Finset.mem_filter.mpr ⟨Finset.mem_univ _, hv⟩, h₁.2.symm⟩ + +end Physical +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer + +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Node Sharing) + +variable {F K N X Z : Type} [Field F] [Finite K] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} (U : Printer F K N m d h ℓ M r t q D k n u j z) + (G : (Key.share s Q).Geo P k) {a : Atlas P.Occupied P.grid.Seam m d h} (π : Palette a w q) + (old : P.V ↪ B m) (data : U.rows.obj) (status : (Children.Header m d).obj) + +namespace Physical +variable {U G π old data status} (B : U.Physical G π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "S" => Key.share s Q +local notation "H" => G.layout U.dyadic U.large p j +local notation "V" => Node (Sharing.Position S) (Sharing.radius k * n) +local notation "Q'" => B.term p + +/- # Frozen station charges in the ordered diagram -/ + + +section +open Finset + +open scoped Classical in +/-- Reindexes `{i // G.frozen i}` and `(Q').freeze.Fixed` by an equivalence. -/ +def frozenPlaces : {i // G.frozen i} ≃ (Q').freeze.Fixed := + (G.frozenEquiv U.dyadic U.large p j).trans + (((H).pad u).fixedEquiv (G.external U.dyadic U.large p j)) + +omit [Finite K] in +open scoped Classical in +theorem home_frozen (i : {i // G.frozen i}) : + (S).home (root (B.frozenPlaces p i).val) = i.val.1 := rfl + +omit [Finite K] in +open scoped Classical in +theorem charge_frozen (i : {i // G.frozen i}) : + (Q').charge (B.frozenPlaces p i).val = ((((S).backdrop.emitted p j).pad u).arity (.inl (.inl + i.val)) : ℝ) + u := + ((H).pad u).old_charge (G.external U.dyadic U.large p j) (((S).backdrop.emitted p + j).divisible_pad u U.pos) _ + +omit [Finite K] in +open scoped Classical in +theorem exterior_frozen (i : {i // G.frozen i}) : + Packing.exterior (Q').diagram id (B.frozenPlaces p i).val = (S).exteriorLoad i.val := by + let D := ((H).routed (B.rules.script p j) u).drawing + have eq (q : slots x ⊕ slots y) : + Packing.portEnd (Q').diagram q = .inl (.inl (.inl (Sum.elim (S).left (S).right q))) := by + change Packing.portEnd D.diagram q = _ + rw [D.exterior] + cases q <;> rfl + have he (q : slots x ⊕ slots y) : + Packing.portEnd (Q').diagram q = (B.frozenPlaces p i).val ↔ Sum.elim (S).left (S).right q + = i.val := by + rw [eq] + change Sum.inl (Sum.inl (Sum.inl _)) = Sum.inl (Sum.inl (Sum.inl _)) ↔ _ + simp only [Sum.inl.injEq] + unfold Packing.exterior Sharing.exteriorLoad + simp only [Fintype.card_eq_nat_card] + exact congrArg₂ (· + ·) (Nat.card_congr (Equiv.subtypeEquivRight (fun a => he (.inl a)))) + (Nat.card_congr (Equiv.subtypeEquivRight (fun b => he (.inr b)))) + +open scoped Classical in +private theorem arity_cover {F : Type} {x y : Wire} (G : Diagram F x y) (v : G.V) : + (Packing.exterior G id v : ℝ) ≤ G.arity v := by + have h := Packing.site_arity G id v + have hh : Packing.push id (fun i => (G.arity i : ℝ)) v = G.arity v := by simp [Packing.push] + rw [hh] at h + exact h.symm ▸ le_add_of_nonneg_right (Nat.cast_nonneg _) + +open scoped Classical in +/-- The quantity computed by `(Q').charge i - (Packing.exterior (Q').diagram id i : ℝ)`. -/ +def internalCharge (i : (Q').diagram.V) := (Q').charge i - (Packing.exterior (Q').diagram id i : ℝ) + +omit [Finite K] in +open scoped Classical in +theorem internal_nonneg (i : (Q').diagram.V) : 0 ≤ B.internalCharge p i := + sub_nonneg.mpr ((arity_cover _ i).trans ((Q').cover i)) + +omit [Finite K] in +open scoped Classical in +theorem square_place {σ b l : ℕ} (hbud : G.Budgets n σ s.scene.level) + (sc : SphereScale.Scales g σ D T j b l) (ha : M * r = l * b) (hb : M * t = l) (hM : M + = SphereScale.chunks σ D) + (hs : u * D ^ (Layout.Fanout.exponent (Sharing.radius k) σ) ≤ T) (i : {i // G.frozen i}) : + (B.internalCharge p (B.frozenPlaces p i).val) ^ 2 ≤ + 48 * (T / ((j : ℝ) * SphereScale.size σ D) * (energyOf j (Layout.item s.scene.cell i.val) : + ℝ) + ((T : ℝ) / D ^ 2) ^ 2) := by + refine Sharing.Geo.internal_square sc ha hb hM U.dyadic U.large hbud p hs i.val + (B.internal_nonneg p _) ?_ + rw [internalCharge, charge_frozen, exterior_frozen, sub_add_cancel] + +end + +/- # Frozen square bound for a single occupied cell -/ + + +section +open Finset + +omit [Finite K] in +open scoped Classical in +theorem cell_square {σ b l : ℕ} {thin : Layout.Place s.scene.cell → Prop} {selector : _ → Prop} + (hr : G.Raw σ j b l s.scene.level thin selector) (sc : SphereScale.Scales g σ D T j b l) + (ha : M * r = l * b) (hb : M * t = l) (hM : M + = SphereScale.chunks σ D) (hk : Sharing.allocation g σ ≤ k) + (hu : u * D ^ (Layout.Fanout.exponent (Sharing.radius k) σ) ≤ T) + (hf : ∀ i, G.frozen i → (Layout.item s.scene.cell i).label.role = .collector ∧ ¬thin i) + (v : P.Occupied) : + (∑ i : (Q').freeze.Fixed, if (S).home (root i.val) + = v then (B.internalCharge p i.val) ^ 2 else 0) ≤ + 128 * ((T : ℝ) * s.tally j Role.collected v / ((j : ℝ) * SphereScale.size σ D) + + D * (T : ℝ) ^ 2) := by + let Z := {i // G.frozen i} + let I := {i : Fin (s.scene.cell v).stations.length // G.frozen ⟨v, i⟩} + let f := fun i : Z => B.internalCharge p (B.frozenPlaces p i).val + have hcard : Fintype.card I ≤ D ^ 5 := + (Fintype.card_subtype_mono _ _ fun i hi => (hf ⟨v, i⟩ hi).2).trans (hr.heavy v) + have hbud := hr.budgets sc ha hb hM hk n + have hsq (i : Z) := B.square_place p hbud sc ha hb hM hu i + have hc := Sphere.Ledger.sq_cell s j G.frozen f v hcard (fun i hi => (hf i hi).1) sc.Dpos + (mul_pos (Nat.cast_pos.mpr sc.pos) (Nat.cast_pos.mpr sc.apos)) hsq + refine le_trans ?_ hc + rw [← (B.frozenPlaces p).sum_comp] + exact sum_le_sum fun i _ => by + rw [home_frozen] + split_ifs <;> rfl + +end + +end Physical +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Order/History.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Order/History.lean new file mode 100644 index 0000000000..d2b6c1ca1b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Order/History.lean @@ -0,0 +1,920 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Sharing +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Footprint.Load +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.Hub +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Pull +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Angular +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Squares + +/-! +# Finite keys for the motion history + +A cell's private selector has its original name. Each new ordinary +residue wire is numbered by the previous stack length. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset Surface + +open scoped Classical in +/-- Indexes the key by the coordinates of `V ⊕ Fin ns.length`. -/ +abbrev Key (V : Type) (ns : List ℕ) := V ⊕ Fin ns.length + +namespace Key +variable {V : Type} + +open scoped Classical in +/-- Embeds `Key V ns` into `V ⊕ ℕ`. -/ +def name (ns : List ℕ) : Key V ns ↪ V ⊕ ℕ := + (Function.Embedding.refl _).sumMap ⟨Fin.val, Fin.val_injective⟩ + +open scoped Classical in +theorem available (ns : List ℕ) (i : Key V ns) : Surface.available ns.length (name ns i) := by + cases i with + | inl _ => exact trivial + | inr i => exact i.isLt + +open scoped Classical in +theorem exists_name (ns : List ℕ) (i : V ⊕ ℕ) (hi : Surface.available ns.length i) : + ∃ j, name ns j = i := by + cases i with + | inl i => exact ⟨.inl i, rfl⟩ + | inr i => exact ⟨.inr ⟨i, hi⟩, rfl⟩ + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun i => name ns i ∈ s`. -/ +def filter [Fintype V] (ns : List ℕ) (s : Finset (V ⊕ ℕ)) : Finset (Key V ns) := + univ.filter fun i => name ns i ∈ s + +open scoped Classical in +@[simp] theorem mem_filter [Fintype V] {ns : List ℕ} {s : Finset (V ⊕ ℕ)} {i : Key V ns} : + i ∈ filter ns s ↔ name ns i ∈ s := by simp [filter] + +open scoped Classical in +theorem card_filter [Fintype V] (ns : List ℕ) (s : Finset (V ⊕ ℕ)) : + (filter ns s).card ≤ s.card := by + rw [← card_map (name ns)] + apply card_le_card + rintro _ he + obtain ⟨i, hi, rfl⟩ := mem_map.mp he + exact mem_filter.mp hi + +open scoped Classical in +/-- In the case `[]`, this construction gives `Fin.elim0`. -/ +def order : (ns : List ℕ) → Fin ns.length → ℕ + | [] => Fin.elim0 + | n :: ns => Fin.snoc (order ns) n + +open scoped Classical in +theorem order_mem (ns : List ℕ) (i : Fin ns.length) : order ns i ∈ ns := by + induction ns with + | nil => exact i.elim0 + | cons n ns ih => + induction i using Fin.lastCases with + | last => simp [order] + | cast i => simp [order, ih i] + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def alphabet (Y : Alphabet V) (t : ℕ) (ns : List ℕ) : Alphabet (Key V ns) where + state := Sum.elim Y.state fun j => Level t (order ns j) + fs := Sum.rec Y.fs (fun j => inferInstanceAs (Fintype (Level t (order ns j)))) + width := Sum.elim Y.width fun j => Chunk.width t (order ns j) + code := Sum.rec Y.code (fun j => binaryCode (Level t (order ns j)) _ (Chunk.card_le t (order ns + j))) + +open scoped Classical in +@[simp] theorem width_inl (Y : Alphabet V) (t : ℕ) (ns : List ℕ) (v : V) : + (alphabet Y t ns).width (.inl v) = Y.width v := rfl + +open scoped Classical in +@[simp] theorem width_inr (Y : Alphabet V) (t : ℕ) (ns : List ℕ) (j : Fin ns.length) : + (alphabet Y t ns).width (.inr j) = Chunk.width t (order ns j) := rfl + +open scoped Classical in +theorem width_le (Y : Alphabet V) (t : ℕ) (ns : List ℕ) (J : ℝ) + (original : ∀ v, (Y.width v : ℝ) ≤ J) + (residue : ∀ b ∈ ns, (Chunk.width t b : ℝ) ≤ J) (i : Key V ns) : + ((alphabet Y t ns).width i : ℝ) ≤ J := by + cases i with + | inl v => exact original v + | inr j => exact residue _ (order_mem ns j) + +end Key +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- # Identifying the motion stack with independently named ordinary wires -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Key +open Surface + +variable {V X F : Type} {t : ℕ} + +open scoped Classical in +/-- The condition `∀ i : Fin ns.length, Level t (order ns i)` on the specified data. -/ +abbrev Values (t : ℕ) (ns : List ℕ) := ∀ i : Fin ns.length, Level t (order ns i) + +open scoped Classical in +/-- Reindexes `Values t (n::ns)` and `Values t ns × Level t n` by an equivalence. -/ +def cut (n : ℕ) (ns : List ℕ) : Values t (n::ns) ≃ Values t ns × Level t n := + (Fin.snocEquiv (fun i => Level t (order (n::ns) i))).symm.trans + ((Equiv.prodComm _ _).trans ((Equiv.piCongrRight fun i + => Equiv.cast (by simp [order])).prodCongr + (Equiv.cast (by simp [order])))) + +open scoped Classical in +/-- In the case `[], _`, this construction gives `x`. -/ +def nest (x : X) : (ns : List ℕ) → Values t ns → Stack X t ns + | [], _ => x + | n::ns, z => (nest x ns (cut n ns z).1, (cut n ns z).2) + +open scoped Classical in +private theorem trace_nest [Field F] (x : X) (ns : List ℕ) (f : Stack X t ns → F) : + traceStack t x ns f = ∑ z, f (nest x ns z) := by + induction ns with + | nil => simp [traceStack, nest, Values] + | cons n ns ih => + rw [traceStack, ih, ← (cut (t := t) n ns).symm.sum_comp, Fintype.sum_prod_type] + simp only [nest, Equiv.apply_symm_apply] + +open scoped Classical in +private theorem observe_nest (keys : V → X → X → Prop) (x y : X) (ns : List ℕ) + (u : V ⊕ ℕ) (z z' : Values t ns) + (orig : ∀ i, u = .inl i → keys i x y) + (fresh : ∀ i : Fin ns.length, u = .inr i.val → z i = z' i) : + Stage.Observe keys ns u (nest x ns z) (nest y ns z') := by + induction ns with + | nil => cases u with + | inl i => exact orig i rfl + | inr _ => exact trivial + | cons n ns ih => + refine ⟨ih _ _ ?_, ?_⟩ + · intro i hi + exact congrArg (Equiv.cast (by simp [order]) : Level t (order (n::ns) i.castSucc) ≃ _) + (fresh i.castSucc hi) + · intro hi + exact congrArg (Equiv.cast (by simp [order]) : Level t (order (n::ns) (Fin.last ns.length)) ≃ + _) + (fresh (Fin.last ns.length) hi) + +open scoped Classical in +private theorem base_nest (x : X) (ns : List ℕ) (z : Values t ns) : + Stage.base ns (nest x ns z) = x := by + induction ns with + | nil => rfl + | cons n ns ih => exact ih _ + +variable (Y : Alphabet V) (t : ℕ) (ns : List ℕ) + +open scoped Classical in +/-- Evaluates `z (.inl i)` at the input `i`. -/ +def old (z : (alphabet Y t ns).State) : Y.State := fun i => z (.inl i) + +open scoped Classical in +/-- Fill the original parameters and unwind the numbered residue states +into the order in which the motion procedure produced them. -/ +def stack (init : Y.State → X) (z : (alphabet Y t ns).State) : Stack X t ns := + nest (init (old Y t ns z)) ns (fun i => z (.inr i)) + +open scoped Classical in +@[simp] theorem base_stack (init : Y.State → X) (z : (alphabet Y t ns).State) : + Stage.base ns (stack Y t ns init z) = init (old Y t ns z) := base_nest _ _ _ + +open scoped Classical in +theorem observe_stack (keys : V → X → X → Prop) (init init' : Y.State → X) + (old_keys : ∀ v x y, x v = y v → keys v (init x) (init' y)) + (z z' : (alphabet Y t ns).State) (k : Key V ns) (hz : z k = z' k) : + Stage.Observe keys ns (name ns k) (stack Y t ns init z) (stack Y t ns init' z') := by + refine observe_nest _ _ _ _ _ _ _ ?_ ?_ + · intro i hi + have he : k = .inl i := (name ns).injective hi + subst k + exact old_keys i _ _ hz + · intro i hi + have he : k = .inr i := (name ns).injective hi + subst k + exact hz + +open scoped Classical in +theorem sum_stack [Field F] [Fintype V] (init : Y.State → X) (f : Stack X t ns → F) : + (∑ z, f (stack Y t ns init z)) = ∑ x : Y.State, traceStack t (init x) ns f := by + let e : (alphabet Y t ns).State ≃ Y.State × Values t ns := + Equiv.sumPiEquivProdPi (alphabet Y t ns).state + rw [← e.symm.sum_comp, Fintype.sum_prod_type] + refine Finset.sum_congr rfl fun x _ => ?_ + rw [trace_nest] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Key +end + +/- # From terminal stages to ordinary shared values -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Key +open Surface Finset + +variable {V E T F X : Type} {r t M : ℕ} + +open scoped Classical in +/-- Input data for the ordinary network before choosing a chunk layout. -/ +structure Source (Y : Alphabet V) (a b : Wire) (S : Stage F r t T V E X) where + /-- Assigns the source of each connection. -/ + src : E → V + /-- Assigns the destination of each connection. -/ + dst : E → V + meets : ∀ v j, j ∈ (S.scene.cell v).ports → src j.1 = v ∨ dst j.1 = v + tracks : Tracks src dst S.footprint S.hidden.length + /-- The left-side data carried by `Source`, with type `slots a → Place S.scene.cell`. -/ + left : slots a → Place S.scene.cell + /-- The right-side data carried by `Source`, with type `slots b → Place S.scene.cell`. -/ + right : slots b → Place S.scene.cell + /-- The `Source` component of type `Val a → Val b → Y.State → X`. -/ + init : Val a → Val b → Y.State → X + /-- The `Source` component of type `V → X → X → Prop`. -/ + keys : V → X → X → Prop + /-- The `Source` component of type `T → X → X → Prop`. -/ + ext : T → X → X → Prop + controls : S.Controls keys ext + original : ∀ i x y z x' y' z', z i = z' i → keys i (init x y z) (init x' y' z') + exterior : ∀ i j, (item S.scene.cell i).label.name = some j → ∀ x y z x' y' z', + (∀ k, left k = i → bits a x k = bits a x' k) → + (∀ k, right k = i → bits b y k = bits b y' k) → ext j (init x y z) (init x' y' z') + +variable {Y : Alphabet V} {a b : Wire} [Fintype V] + (S : Stage F (M * r) (M * t) T V E X) (A : Source Y a b S) + +open scoped Classical in +/-- Read only ordinary wires belonging to the station's footprint. -/ +def share : Sharing S.scene.cell a b (alphabet Y (M * t) S.hidden) where + src := A.src + dst := A.dst + meets := A.meets + seen v := filter S.hidden (S.footprint v) + reads i := filter S.hidden (item S.scene.cell i).label.reads + within i _ h := mem_filter.mpr + ((A.controls i.1 _ (List.get_mem _ i.2)).within (mem_filter.mp h)) + present k := by + obtain ⟨v, hv⟩ := (A.tracks.present _).mpr (available S.hidden k) + exact ⟨v, mem_filter.mpr hv⟩ + connected k v w hv hw := by + simp only [mem_filter] + exact A.tracks.connected _ _ _ (mem_filter.mp hv) (mem_filter.mp hw) + left := A.left + right := A.right + param x y := stack Y (M * t) S.hidden (A.init x y) + locality i x y z x' y' z' hx hy hz := by + have ctrl := A.controls i.1 _ (List.get_mem _ i.2) + apply ctrl.respects + · intro j hj + have hav := (A.tracks.present j).mp ⟨_, ctrl.within hj⟩ + obtain ⟨k, rfl⟩ := exists_name S.hidden j hav + exact observe_stack Y (M * t) S.hidden A.keys _ _ + (fun v a b => A.original v x y a x' y' b) z z' k (hz k (mem_filter.mpr hj)) + · intro j hj + rw [base_stack, base_stack] + exact A.exterior i j hj _ _ _ _ _ _ hx hy + +open scoped Classical in +/-- Contracting the ordinary network sums all private keys and +residual wires, each with multiplicity one. -/ +theorem eval_share [Field F] [Fintype E] (P : ℕ) (x : Val a) (y : Val b) : + let B := (share S A).backdrop + (∑ z : (share S A).State, (∏ v, B.base.station v x y z) * S.scene.value P (B.param x y z)) = + ∑ i : Y.State, S.value P (A.init x y i) := by + refine ((share S A).eval x y (S.scene.value P)).trans ?_ + refine Eq.trans ?_ (sum_stack Y (M * t) S.hidden (A.init x y) (S.scene.value P)) + exact sum_congr (by ext; simp) (fun _ _ => rfl) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Key +end + +/- # Local operands of the emitted tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order.Rules +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Finset + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} (L : Rules S) {d : E → ℕ} (p : Profile C d) (P : ℕ) + +open Classical in +/-- Indexes the line by the coordinates of `S.Edge ⊕ (E × Fin M) ⊕ Layout.Grid M (Place C)`. -/ +abbrev Line (S : Sharing C a b Y) := S.Edge ⊕ (E × Fin M) ⊕ Layout.Grid M (Place C) +open Classical in +/-- Indexes the vertex by the coordinates of `S.Vertex ⊕ Layout.Grid M V`. -/ +abbrev Vertex (S : Sharing C a b Y) := S.Vertex ⊕ Layout.Grid M V + +open Classical in +/-- Embeds `Y.state k` into `Signal M r t`. -/ +def keyTag (k : K) : Y.state k ↪ Signal M r t := + (L.tag k).trans ⟨.key, fun _ _ h => Signal.key.inj h⟩ + +open Classical in +/-- Embeds `Level r e` into `Signal M r t`. -/ +def frontTag (e : ℕ) : Level r e ↪ Signal M r t := + ⟨fun x => .front x.val, fun _ _ h => Subtype.ext (Signal.front.inj h)⟩ + +open Classical in +/-- Embeds `Level t e` into `Signal M r t`. -/ +def backTag (e : ℕ) : Level t e ↪ Signal M r t := + ⟨fun x => .back x.val, fun _ _ h => Subtype.ext (Signal.back.inj h)⟩ + +open Classical in +/-- In the case `.inl e`, this construction gives `L.keyTag e.1`. -/ +def tagAt : (i : Line S) → (S.backdrop.emitted p P).state i ↪ Signal M r t + | .inl e => L.keyTag e.1 + | .inr (.inl _) | .inr (.inr (.inl _)) => frontTag _ + | .inr (.inr (.inr _)) => backTag _ + +open Classical in +/-- In the case `.inl (.inl i)`, this construction gives `load (L.label i)`. -/ +def program : Vertex S → Program F (Signal M r t) + | .inl (.inl i) => load (L.label i) + | .inl (.inr (.inl _)) => checkPairs + | .inl (.inr (.inr _)) => fun _ _ _ => 1 + | .inr (.inl (v, _)) => chamber Signal.first ((firstList C v).map (firstPoint C P)) + | .inr (.inr (v, _)) => chamber Signal.second ((secondList C v).map (secondPoint C)) + +open Classical in +/-- The value specified by `.inl ⟨j.val, .inr (.inr ⟨i, L.seen i j.val j.property⟩)⟩`. -/ +def reader (i : Place C) (j : {k // k ∈ L.reads i}) : Line S := + .inl ⟨j.val, .inr (.inr ⟨i, L.seen i j.val j.property⟩)⟩ + +open Classical in +/-- The value specified by `.inr (.inr (.inl (i, j)))`. -/ +def front (i : Place C) (j : Fin M) : Line S := .inr (.inr (.inl (i, j))) +open Classical in +/-- The value specified by `.inr (.inr (.inr (i, j)))`. -/ +def back (i : Place C) (j : Fin M) : Line S := .inr (.inr (.inr (i, j))) + +open Classical in +/-- In the case `.inl i`, this construction gives `.inr (.inl (i.1, j))`. -/ +def first (j : Fin M) : Marked C → Line S + | .inl i => .inr (.inl (i.1, j)) + | .inr i => front i j + +open Classical in +/-- In the case `.inl (.inl i)`, this construction gives `(L.reads i).attach.map (L.reader i) ++ +List.ofFn (front i)`. -/ +def operands : Vertex S → List (Line S) + | .inl (.inl i) => (L.reads i).attach.map (L.reader i) ++ List.ofFn (front i) + ++ List.ofFn (back i) + | .inl (.inr (.inl v)) => (hubReads S v).map .inl + | .inl (.inr (.inr _)) => [] + | .inr (.inl (v, j)) => (firstList C v).map (first j) + | .inr (.inr (v, j)) => (secondList C v).map (fun i => back i j) + +open Classical in +theorem incident (v : Vertex S) : ∀ i ∈ L.operands v, + (S.backdrop.emitted p P).src i = v ∨ (S.backdrop.emitted p P).dst i = v := by + rcases v with ((i|v|v) | (⟨v, j⟩|⟨v, j⟩)) + · simp only [operands, List.forall_mem_append, List.forall_mem_map, List.forall_mem_ofFn_iff] + exact ⟨⟨fun _ _ => .inr rfl, fun _ => .inl rfl⟩, fun _ => .inl rfl⟩ + · simp only [operands, List.forall_mem_map] + exact fun i hi => (hub_meets S v i hi).imp (congrArg Sum.inl) (congrArg Sum.inl) + · simp [operands] + · simp only [operands, firstList, secondList, List.forall_mem_map, List.forall_mem_append] + refine ⟨fun _ _ => .inr rfl, fun k hk => ?_⟩ + let f (v : V) : Vertex S := .inr (.inl (v, j)) + exact (S.meets v k hk).imp (congrArg f) (congrArg f) + · simp only [operands, secondList, List.forall_mem_map] + exact fun _ _ => .inr rfl + +variable (z : (S.backdrop.emitted p P).State) + +open Classical in +/-- Computes the value by the application `L.tagAt p P j (z j)`. -/ +def value (j : Line S) := L.tagAt p P j (z j) + +open Classical in +/-- Evaluates `z (.inl i)` at the input `i`. -/ +def ordinary : S.State := fun i => z (.inl i) + +open Classical in +/-- Evaluates `z (.inr (.inr i))` at the input `i`. -/ +def links : p.Legs := fun i => z (.inr (.inr i)) + +open Classical in +/-- Evaluates `z (.inr (.inl i))` at the input `i`. -/ +def seam : p.Seams := fun i => z (.inr (.inl i)) + +open Classical in +/-- The args of type `Args M r t` for the given inputs. -/ +def args (i : Place C) : Args M r t := + ((L.reads i).map (fun k => L.tag k (S.localState i (ordinary p P z) k)), + fun j => ((links p P z) (.inl (i, j))).val, fun j => ((links p P z) (.inr (i, j))).val) + +open Classical in +theorem operands_item (i : Place C) : + (L.operands (.inl (.inl i))).map (L.value p P z) = symbols (L.args p P z i) := by + simp only [operands, symbols, args, List.map_append, List.map_map, List.map_ofFn] + congr 2 + rw [← List.attach_map_val (l := L.reads i)] + apply List.map_congr_left + intro k _ + simp only [Function.comp_apply, Sharing.localState, dite_eq_left (L.seen i k.val k.property)] + rfl + +open Classical in +theorem insert_eq (i : Place C) (x : Val a) (y : Val b) : + p.insertion (links p P z) (S.param x y (S.localState i (ordinary p P z))) i = + load (L.label i) ((L.left.ports i).map (bits a x)) ((L.right.ports i).map (bits b y)) + (symbols (L.args p P z i)) := by + rw [load_symbols] + exact L.run i x y (S.localState i (ordinary p P z)) + (p.joinA (p.first (seam p P z) (links p P z)) (.inr i)) (p.joinB (p.second (links p P z)) i) + +open Classical in +/-- Builds `Script (S.backdrop.emitted p P) (Signal M r t) where left` with the specified +`left`, `right`, `tag`, `program`. -/ +abbrev script : Script (S.backdrop.emitted p P) (Signal M r t) where + left := (L.left.lift (V ⊕ V)).lift (Layout.Grid M V) + right := (L.right.lift (V ⊕ V)).lift (Layout.Grid M V) + tag := L.tagAt p P + program := L.program P + reads := L.operands + incident := L.incident p P + run := by + rintro ((i|v|v)|(⟨v, j⟩|⟨v, j⟩)) x y z + · have he : (S.backdrop.emitted p P).station (.inl (.inl i)) x y z = + p.insertion (links p P z) (S.param x y (S.localState i (ordinary p P z))) i := by + simp [Sharing.checks] + rfl + rw [he, L.insert_eq] + exact congrArg (load (L.label i) _ _) (L.operands_item p P z i).symm + · have he : (S.backdrop.emitted p P).station (.inl (.inr (.inl v))) x y z = + if S.checks (.inr (.inl v)) (ordinary p P z) then 1 else 0 := by + simp + rfl + rw [he] + change _ = checkPairs [] [] (((hubReads S v).map Sum.inl).map (L.value p P z)) + rw [List.map_map] + exact (hub_eval S v L.keyTag (ordinary p P z) [] []).symm + · change (S.backdrop.emitted p P).station (.inl (.inr (.inr v))) x y z = 1 + simp [Sharing.checks] + · change p.form P (seam p P z) (links p P z) (.inl (v, j)) = + chamber Signal.first ((firstList C v).map (firstPoint C P)) [] [] + (((firstList C v).map (first j)).map (L.value p P z)) + rw [List.map_map, chamber_eval] + simp only [Profile.form] + congr 1 + funext h + cases h <;> rfl + · change p.form P (seam p P z) (links p P z) (.inr (v, j)) = + chamber Signal.second ((secondList C v).map (secondPoint C)) [] [] + (((secondList C v).map (fun i => back i j)).map (L.value p P z)) + rw [List.map_map, chamber_eval] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order.Rules +end + +/- +# One physical dictionary for all emitted configurations + +The operations use the input book, the two families of marked sphere +forms, and equality. The decoders depend only on the supplied ordinary +alphabet or one chunk energy, and on the unpadded width. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open Finset Surface.Stage MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage.Layout + +variable {F : Type} [Field F] [Fintype F] {M r t : ℕ} + +open Classical in +/-- The operations of type `Finset (Program F (Signal M r t))` for the given inputs. -/ +def operations (book : Finset (Label F (M * r) (M * t))) (k : ℕ) : + Finset (Program F (Signal M r t)) := + (book.image load) ∪ {checkPairs, fun _ _ _ => 1} ∪ + ((strings univ k).image (chamber Signal.first)) ∪ + ((strings univ k).image (chamber Signal.second)) + +open Classical in +/-- Computes the front decode by the application `decode _ _ (binaryCode _ _ (Chunk.card_le r +e)) (Rules.frontTag e)`. -/ +def frontDecode (M r t e : ℕ) : Decoder (Signal M r t) := + decode _ _ (binaryCode _ _ (Chunk.card_le r e)) (Rules.frontTag e) + +open Classical in +/-- Computes the back decode by the application `decode _ _ (binaryCode _ _ (Chunk.card_le t e)) +(Rules.backTag e)`. -/ +def backDecode (M r t e : ℕ) : Decoder (Signal M r t) := + decode _ _ (binaryCode _ _ (Chunk.card_le t e)) (Rules.backTag e) + +open Classical in +/-- The selected finite family `(codes.image (Decoder.map Signal.key)) ∪ ((range (N + 1)).image +(frontDecode M r t)) ∪ ((range (N + 1)).image (backDecode M r t))`. -/ +def signals (r : ℕ) (codes : Finset (Decoder (Symbol (M * t)))) (N : ℕ) : + Finset (Decoder (Signal M r t)) := + (codes.image (Decoder.map Signal.key)) ∪ ((range (N + 1)).image (frontDecode M r t)) ∪ + ((range (N + 1)).image (backDecode M r t)) + +open Classical in +/-- The quantity computed by `((range (N + 1)) ×ˢ signals r codes N).image fun i => Decoder.pad +u i.1 i.2`. -/ +def paddedSignals (r : ℕ) (codes : Finset (Decoder (Symbol (M * t)))) (N u : ℕ) := + ((range (N + 1)) ×ˢ signals r codes N).image fun i => Decoder.pad u i.1 i.2 + +open Classical in +/-- Computes the dictionary by the application `menu (operations book k) (paddedSignals r codes +N u) k N`. -/ +def dictionary (book : Finset (Label F (M * r) (M * t))) (codes : Finset (Decoder (Symbol (M * t)))) + (k N u : ℕ) : Finset (Table F) := + menu (operations book k) (paddedSignals r codes N u) k N + +open Classical in +theorem count_operations (book : Finset (Label F (M * r) (M * t))) (k : ℕ) : + (operations book k).card ≤ book.card + 2 + 2 * (Fintype.card F + 1) ^ k := by + unfold operations + have hh := card_strings (univ : Finset F) k + simp only [card_univ] at hh + rw [two_mul, ← add_assoc] + refine (card_union_le _ _).trans (Nat.add_le_add ?_ (card_image_le.trans hh)) + refine (card_union_le _ _).trans (Nat.add_le_add ?_ (card_image_le.trans hh)) + refine (card_union_le _ _).trans (Nat.add_le_add card_image_le ?_) + exact (card_insert_le _ _).trans_eq (by rw [card_singleton]) + +open Classical in +theorem count_signals (r : ℕ) (codes : Finset (Decoder (Symbol (M * t)))) (N u : ℕ) : + (paddedSignals r codes N u).card ≤ (N + 1) * (codes.card + 2 * (N + 1)) := by + refine card_image_le.trans ?_ + rw [card_product, card_range] + apply Nat.mul_le_mul_left + unfold signals + rw [two_mul, ← add_assoc] + refine (card_union_le _ _).trans (Nat.add_le_add ?_ (card_image_le.trans_eq (card_range _))) + exact (card_union_le _ _).trans (Nat.add_le_add card_image_le (card_image_le.trans_eq (card_range + _))) + +open Classical in +private theorem polynomial (B N k A S H : ℕ) (hB : 4 ≤ B) + (hN : N + 2 ≤ B) (hA : A ≤ B) (hS : S ≤ B) (hH : H + 1 ≤ B) : + ((N + 1) * (N + 2) ^ k) ^ 2 * (A + 2 + 2 * (H + 1) ^ k) * ((2 * k * ((N + 1) * (S + 2 * (N + + 1))) + 1) ^ k) ^ 2 ≤ + B ^ ((k + 12) ^ 3) := by + have hb : 0 < B := by omega + have he : 1 ≤ B ^ k := Nat.one_le_pow _ _ hb + have hk : k ≤ B ^ k := Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left (by omega) _) + have h₁ : (N + 1) * (N + 2) ^ k ≤ B ^ (k + 1) := by rw [pow_succ']; gcongr; omega + have h₂ : A + 2 + 2 * (H + 1) ^ k ≤ B ^ (k + 2) := by + have := Nat.pow_le_pow_left hH k + rw [pow_add] + nlinarith [Nat.mul_le_mul_left (B ^ k) (show 4 * B ≤ B ^ 2 by nlinarith)] + have h₃ : (N + 1) * (S + 2 * (N + 1)) ≤ B ^ 3 := calc + _ ≤ B * (B + 2 * B) := by gcongr <;> omega + _ ≤ B ^ 3 := by nlinarith [Nat.mul_le_mul_right (B ^ 2) hB] + have h₄ : 2 * k * ((N + 1) * (S + 2 * (N + 1))) + 1 ≤ B ^ (k + 4) := calc + _ ≤ 2 * B ^ k * B ^ 3 + 1 := by gcongr + _ ≤ B ^ (k + 4) := by + rw [pow_add] + nlinarith [Nat.mul_le_mul_right (B ^ k * B ^ 3) hB, Nat.one_le_pow 3 B hb] + calc + _ ≤ (B ^ (k + 1)) ^ 2 * B ^ (k + 2) * ((B ^ (k + 4)) ^ k) ^ 2 := by gcongr + _ = B ^ ((k + 1) * 2 + (k + 2) + (k + 4) * (k * 2)) + := by rw [← pow_mul, ← pow_mul, ← pow_mul, ← pow_add, ← pow_add] + _ ≤ _ := Nat.pow_le_pow_right hb (by nlinarith [Nat.zero_le (k ^ 3)]) + +open Classical in +theorem dictionary_count (book : Finset (Label F (M * r) (M * t))) + (codes : Finset (Decoder (Symbol (M * t)))) (k N u : ℕ) : + (dictionary book codes k N u).card ≤ + (N + 2 + Fintype.card F + book.card + codes.card) ^ ((k + 12) ^ 3) := by + have hf : 1 < Fintype.card F := Fintype.one_lt_card + refine (menu_count _ _ _ _).trans (le_trans ?_ (polynomial _ N k book.card codes.card + (Fintype.card F) (by omega) (by omega) (by omega) (by omega) (by omega))) + gcongr + · exact count_operations _ _ + · exact count_signals _ _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- # Ordered tables preserve all host, placement and charge information -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order Finset Packing Rounds + +variable {F V α : Type} [Field F] [Fintype V] {a b : Wire} {d h u : ℕ} + {G : Bundled F a b} {T : Trie V d} (H : Fanout G T (Cell h)) + (he : H.exterior) (hw : ∀ e, u ∣ G.width e) (D : Drawing H.route.net) + +open Classical in +/-- Builds `Freeze D.diagram where frozen v` with the specified `frozen`, `exterior`, +`separate`. -/ +abbrev drawnFreeze : Freeze D.diagram where + frozen v := T.fixed (H.place v).1 + exterior i := by rw [D.exterior]; cases i with + | inl i => exact he.1 i + | inr i => exact he.2 i + separate i := by rw [D.source, D.target]; exact T.separate (H.edges i.1).2 + +open Classical in +/-- Builds `(drawnFreeze H he D).Frame (Node V d) h where place` with the specified `place`, +`frozen`, `keep`, `ns`. -/ +abbrev drawnFrame : (drawnFreeze H he D).Frame (Node V d) h where + place := H.place + frozen := T.fixed + keep _ := Iff.rfl + N := T.adj + C := T.core + ns _ _ := T.adj_symm + cs _ _ := T.core_symm + sub _ := filter_subset _ _ + group i := by rw [D.source, D.target]; exact (H.edges i.1).1 + edge i := mem_filter.mpr ⟨by rw [D.source, D.target]; exact (H.edges i.val.1).2, i.property⟩ + full i := by rw [D.source, D.target]; exact (H.edges i.1).2 + +open Classical in +/-- Builds `LocalTerm F a b h u where V` with the specified `diagram`, `freeze`, `frame`, `one`. -/ +abbrev drawn : LocalTerm F a b h u where + V := Node V d + diagram := D.diagram + freeze := drawnFreeze H he D + frame := drawnFrame H he D + one := H.injective + width v w := by + have h := H.route.net.divisible v w u (fun e _ _ => hw e.1) + convert h using 1 + refine @Fintype.card_congr _ _ ?_ ?_ ?_ + exact Equiv.subtypeEquivRight fun i => by rw [D.source, D.target]; rfl + charge := (H.term he hw).charge + cover v := by rw [D.arity]; exact le_add_of_nonneg_right (by positivity) + floor := (H.term he hw).floor + +open Classical in +theorem drawn_concentrated {n c K A R g ℓ : ℕ} {W : ℝ} (P : Input F a b h n A R g W) + (hP : Concentrated P (H.term he hw) K c ℓ) : Concentrated P (H.drawn he hw D) K c ℓ := + ⟨hP.cells, hP.coreDegree, hP.fullDegree, hP.frozenCount, hP.frozenMax, hP.frozenSquare, + hP.coreMax, hP.coreSum⟩ + +open Classical in +/-- The value specified by `(s.pad u).route (H.pad u).route`. -/ +abbrev routed (s : Script G α) (u : ℕ) := (s.pad u).route (H.pad u).route + +open Classical in +/-- The value specified by `(H.pad u).drawn he (G.divisible_pad u hu) (H.routed s u).drawing`. -/ +abbrev ordered (hu : 0 < u) (s : Script G α) : LocalTerm F a b h u := + (H.pad u).drawn he (G.divisible_pad u hu) (H.routed s u).drawing + +open Classical in +theorem eval_ordered (hu : 0 < u) (s : Script G α) : (H.ordered he hu s).diagram.eval = G.eval := + (H.routed s u).eval.trans ((H.pad u).route.eval_net.trans (G.eval_pad u)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +end + +/- # Numerical hypotheses for emitting a terminal configuration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo.Raw +open Finset Rounds +open SphereScale (Scales size budget q) + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k ℓ L B m : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + {G : S.Geo P k} {e : E → ℕ} {thin : Place C → Prop} {selector : K → Prop} + (hr : G.Raw ℓ L B m e thin selector) (s : Scales g ℓ D T L B m) + (ha : M * r = m * B) (hb : M * t = m) (hM : M = SphereScale.chunks ℓ D) + (hk : allocation g ℓ ≤ k) + +include s hk in +open Classical in +theorem slots_fit : SphereScale.probes ℓ D + D ^ 5 ≤ D ^ k ∧ + SphereScale.chunks ℓ D ≤ D ^ k ∧ g ≤ D ^ k := by + have h := s.bound + have hpos := s.Dpos + have he : 8 * (ℓ + 32) + 10 ≤ k := + (Nat.add_le_add_right (Nat.le_add_left _ _) 10).trans hk + have hx : 1600 * D ≤ D ^ 2 := by nlinarith + have hn : SphereScale.probes ℓ D ≤ D ^ (2 + (ℓ + 32) * 8) := by + rw [SphereScale.probes, size, q, pow_add D 2, pow_mul] + exact Nat.mul_le_mul_right _ hx + refine ⟨?_, ?_, ?_⟩ + · calc + _ ≤ 2 * D ^ (2 + (ℓ + 32) * 8) := by + rw [two_mul] + exact Nat.add_le_add hn (Nat.pow_le_pow_right hpos (by omega)) + _ ≤ D ^ (2 + (ℓ + 32) * 8 + 1) := by rw [pow_succ']; gcongr; omega + _ ≤ _ := Nat.pow_le_pow_right hpos (by omega) + · rw [SphereScale.chunks, q, ← pow_mul] + exact Nat.pow_le_pow_right hpos (by omega) + · exact (show g ≤ D by have := s.degree; omega).trans (Nat.le_self_pow (by omega) _) + +include hr s hM in +omit [Field F] [Fintype K] in +open Classical in +theorem term_count (hroom : ∀ v, (C v).stations.length ≤ SphereScale.room ℓ D g) : + Fintype.card (Profile C e) ≤ (SphereScale.depth ℓ D g L (m * B) + 1) ^ + (SphereScale.chunks ℓ D * (Fintype.card E + 2 * SphereScale.room ℓ D g * Fintype.card V)) + := by + let N := SphereScale.depth ℓ D g L (m * B) + have he (i : E) : e i ≤ N := (hr.seamEnergy i).trans (by + unfold N SphereScale.depth + exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ s.pos)) + have h₁ (i : Place C) : (item C i).a ≤ N := + ((Nat.le_mul_of_pos_left _ s.pos).trans (Nat.le_add_right _ _)).trans (hr.energy i) + have h₂ (i : Place C) : (item C i).b ≤ N := (Nat.le_add_left _ _).trans (hr.energy i) + refine (card_profile C e N he h₁ h₂).trans (Nat.pow_le_pow_right (Nat.zero_lt_succ _) ?_) + have hc : Fintype.card (Place C) ≤ SphereScale.room ℓ D g * Fintype.card V := by + rw [Fintype.card_sigma, mul_comm (SphereScale.room ℓ D g)] + simpa using sum_le_card_nsmul univ (fun v => (C v).stations.length) _ (fun v _ => hroom v) + rw [← hM, mul_assoc] + gcongr + +include hr s ha hb hM hk + +open Classical in +theorem budgets (d : ℕ) : G.Budgets d ℓ e := by + have hW : 0 ≤ W := le_trans (by positivity) hr.occupied + have hD := s.Dpos + have hbig : 122 * budget g ≤ k ∧ 17 * (budget g) ^ 2 ≤ k ∧ 14 ≤ k := by + unfold allocation at hk + refine ⟨?_, ?_, ?_⟩ <;> nlinarith only [hk] + have hk' : budget g ≤ k := by omega + refine ⟨?_, ?_, ?_, hr.ordinary_small s, ?_, ?_, ?_, ?_, hr.chamber_load s ha hb hM, ?_⟩ + · refine le_trans ?_ hr.occupied + gcongr + exact le_mul_of_one_le_right (by positivity) (by exact_mod_cast hD) + · exact fun v => (hr.keys v).trans (Nat.pow_le_pow_right s.Dpos hbig.2.2) + · exact fun v => ((hr.seams v).trans (show budget g ≤ D by have := s.large; omega)).trans + (Nat.le_self_pow (by omega) _) + · exact hr.collectors.trans (by gcongr) + · intro i hi + have hx : (S.exteriorLoad i : ℝ) ≤ budget g * (D : ℝ) * T := by exact_mod_cast hr.exterior i hi + calc + _ ≤ 11 * (budget g : ℝ) * D * T := by + unfold stationLoad + linarith only [hx, hr.leg_le s ha hb hM i] + _ ≤ _ := by gcongr; exact_mod_cast (show 11 * budget g ≤ k by omega) + · refine (hr.frozen_square s ha hb hM).trans ?_ + gcongr + exact_mod_cast hbig.1 + · exact fun i hi => (hr.residue_le s ha hb hM i hi).trans (room hD (by decide)) + · refine (hr.total_load s ha hb hM).trans ?_ + calc + _ ≤ (k : ℝ) * W := by gcongr; exact_mod_cast hbig.2.1 + _ ≤ _ := le_mul_of_one_le_right (by positivity) (by simp) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo.Raw +end + +/- # Coverage of all vertices and decoders by the same dictionaries -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order.Rules +open Finset MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Surface.Stage + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} (L : Rules S) {d : E → ℕ} (p : Profile C d) (P : ℕ) + (book : Finset (Label F (M * r) (M * t))) (codes : Finset (Decoder (Symbol (M * t)))) (k N : ℕ) + +open Classical in +theorem signal_mem (h : ∀ i, L.signal i ∈ codes) + (hd : ∀ i, d i ≤ N) (ha : ∀ i, (item C i).a ≤ N) (hb : ∀ i, (item C i).b ≤ N) + (e : Line S) : (L.script p P).signal e ∈ signals r codes N := by + have ma (j : ℕ) (hj : j ≤ N) : frontDecode M r t j ∈ signals r codes N := + mem_union_left _ (mem_union_right _ (mem_image_of_mem _ (mem_range.mpr (Nat.lt_succ_of_le hj)))) + have mb (j : ℕ) (hj : j ≤ N) : backDecode M r t j ∈ signals r codes N := + mem_union_right _ (mem_image_of_mem _ (mem_range.mpr (Nat.lt_succ_of_le hj))) + rcases e with e | ⟨i, j⟩ | ⟨i, j⟩ | ⟨i, j⟩ + · change decode _ _ (Y.code e.1) (Signal.key ∘ L.tag e.1) ∈ _ + rw [decode_comp] + exact mem_union_left _ (mem_union_left _ (mem_image_of_mem _ (h e.1))) + · exact ma _ ((Nat.le_of_lt_succ ((p.1 (.inl i)).val j).isLt).trans (hd i)) + · exact ma _ ((Nat.le_of_lt_succ ((p.1 (.inr i)).val j).isLt).trans (ha i)) + · exact mb _ ((Nat.le_of_lt_succ ((p.2 i).val j).isLt).trans (hb i)) + +variable (hl : ∀ v, (C v).stations.length + (C v).ports.length ≤ k) +include hl + +open Classical in +theorem program_mem [Fintype F] (h : ∀ i, L.label i ∈ book) (v : Vertex S) : + (L.script p P).program v ∈ operations book k := by + have hm (l : List F) (hn : l.length ≤ k) : l ∈ strings univ k := + mem_strings _ _ _ hn (fun _ _ => mem_univ _) + rcases v with ((i|v|v)|(⟨v, j⟩|⟨v, j⟩)) + · exact mem_union_left _ (mem_union_left _ (mem_union_left _ (mem_image_of_mem _ (h i)))) + · simp [operations, program] + · simp [operations, program] + · apply mem_union_left + apply mem_union_right + apply mem_image_of_mem + apply hm + simpa [firstList, secondList] using hl v + · apply mem_union_right + apply mem_image_of_mem + apply hm + simpa [secondList] using (Nat.le_add_right _ _).trans (hl v) + +open Classical in +theorem reads_bound (h : ∀ i, (L.reads i).length + 2 * M ≤ k) + (hg : ∀ v, 2 * (S.backdrop.emitted p P).degree v ≤ k) (v : Vertex S) : + ((L.script p P).reads v).length ≤ k := by + rcases v with ((i|v|v)|(⟨v, j⟩|⟨v, j⟩)) + · simpa [operands, two_mul, add_assoc] using h i + · have hh := hg (.inl (.inr (.inl v))) + rw [Backdrop.base_degree] at hh + have hle : 2 * S.base.degree (.inr (.inl v)) ≤ k + := (Nat.mul_le_mul_left _ (Nat.le_add_right ..)).trans hh + simpa [operands] using (length_hubReads S v).trans hle + · simp [operands] + · simpa [operands, firstList, secondList] using hl v + · simpa [operands, secondList] using (Nat.le_add_right _ _).trans (hl v) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order.Rules +end + +/- # The dictionary and port-order bounds survive routing and padding -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order Packing Rounds Finset + +variable {F V α : Type} [Field F] [Fintype V] {a b : Wire} {d h u : ℕ} + {G : Bundled F a b} {T : Trie V d} (H : Fanout G T (Cell h)) + (he : H.exterior) (hu : 0 < u) + +omit [Fintype V] [Field F] in +open Classical in +theorem source_arity (G : Bundled F a b) (e : G.E) : G.width e ≤ G.arity (G.src e) := by + have h := single_le_sum (f := fun j => if G.src j = G.src e then G.width j else 0) + (fun _ (_ : _ ∈ univ) => Nat.zero_le _) (mem_univ e) + rw [ite_eq_left rfl] at h + unfold Bundled.arity + omega + +variable {D W₀ R g C z ℓ : ℕ} {W : ℝ} {P : Input F a b h D W₀ R g W} + (hc : Concentrated P (H.finish he hu) C z ℓ) (hD : 1 ≤ D) (hC : 1 ≤ C) + +include hc hD hC in +open Classical in +theorem arity_max (v : Node G.V d) : (H.pad u).route.net.arity v ≤ C * D * W₀ := by + have hl : ((H.pad u).route.net.arity v : ℝ) ≤ (H.finish he hu).charge v := + le_add_of_nonneg_right (by positivity) + apply (Nat.cast_le (α := ℝ)).mp + push_cast + refine hl.trans ?_ + by_cases hv : (H.finish he hu).freeze.frozen v + · exact hc.frozenMax ⟨v, hv⟩ + · calc + _ ≤ (H.finish he hu).charge v * (D : ℝ) ^ ℓ := le_mul_of_one_le_right + ((Nat.cast_nonneg _).trans hl) (one_le_pow₀ (by exact_mod_cast hD)) + _ ≤ W₀ := hc.coreMax ⟨v, hv⟩ + _ ≤ _ := le_mul_of_one_le_left (by positivity) (by exact_mod_cast Nat.mul_pos hC hD) + +include hc hD hC in +open Classical in +theorem ordered_properties (s : Script G α) (k N K : ℕ) + (ops : Finset (Program F α)) (signals : Finset (Decoder α)) + (h₀ : checkPairs ∈ ops) (hop : ∀ v, s.program v ∈ ops) + (hs : ∀ e, s.signal e ∈ signals) (hr : ∀ v, (s.reads v).length ≤ k) + (hk : ∀ v, G.degree v ≤ K) (hR : 4 * K ≤ k) (hN : C * D * W₀ ≤ N) : + Concentrated P (H.ordered he hu s) C z ℓ ∧ + (H.ordered he hu s).diagram.PortOrder (k + 2) ∧ + ∀ v, (H.ordered he hu s).diagram.table v ∈ menu ops + (((range (N + 1)) ×ˢ signals).image fun i => Decoder.pad u i.1 i.2) k N := by + let q := H.routed s u + have ha (v) := (H.arity_max he hu hc hD hC v).trans hN + have hd (v) : (H.pad u).route.net.degree v ≤ 2 * K := (H.pad u).fan_degree hk v + have hdeg (v) : (H.pad u).route.net.degree v ≤ k := (hd v).trans (by omega) + refine ⟨(H.pad u).drawn_concentrated he _ _ P hc, q.drawing.order (fun v + => Nat.add_le_add_right (hdeg v) 2), ?_⟩ + apply q.menu_mem _ _ _ _ _ _ ha hdeg + · rintro (v|v) + · simpa [q] using hr v + · exact ((s.pad u).length_route (H.pad u).route v).trans (by have := hd (.inr v); omega) + · rintro (v|v) + · exact hop v + · exact h₀ + · intro e + have hh : G.width e.1 ≤ N := calc + _ ≤ (G.pad u).width e.1 := Diagram.le_padWidth _ _ + _ ≤ (G.pad u).arity (G.src e.1) := source_arity (G.pad u) _ + _ = (H.pad u).route.net.arity (.inl (G.src e.1)) := (Routes.old_arity _ _).symm + _ ≤ N := ha _ + exact mem_image.mpr ⟨(G.width e.1, s.signal e.1), mem_product.mpr ⟨mem_range.mpr (by omega), + hs e.1⟩, + (s.signal_pad u e.1).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Fanout +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Order/Hub.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Order/Hub.lean new file mode 100644 index 0000000000..37455ea805 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Order/Hub.lean @@ -0,0 +1,1090 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Host +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.General.Pruned +public import Mathlib.Data.List.NodupEquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Depth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Sharing + +/-! # Number of bundle incidences after routing -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset +variable {F V I : Type} [Field F] {a b : Wire} {d : ℕ} + +open Classical in +/-- A unit width on every bundle specializes the arity estimates to degree. -/ +private abbrev thin (G : Bundled F a b) : Bundled F .unit .unit where + V := G.V + E := G.E + state _ := Unit + width _ := 1 + code _ := binaryCode _ _ (by simp) + src := G.src + dst := G.dst + left := Empty.elim + right := Empty.elim + station _ _ _ _ := 1 + locality _ _ _ _ _ _ _ _ _ _ := rfl + +open Classical in +private theorem thin_arity (G : Bundled F a b) (v : G.V) : (thin G).arity v = G.degree v := by + simp [Bundled.arity, Bundled.degree, thin] + +namespace Fanout +variable {G : Bundled F a b} {T : Trie V d} (H : Fanout G T I) + +open Classical in +private abbrev unitFan : Fanout (thin G) T I := + ⟨H.site, H.one, H.near, H.group⟩ + +open Classical in +private theorem fan_arity (v : Node G.V d) : H.route.net.degree v = H.unitFan.route.net.arity v + := by + rw [← thin_arity] + unfold Bundled.arity + rfl + +open Classical in +theorem fan_degree {k : ℕ} (hk : ∀ v, G.degree v ≤ k) (v : Node G.V d) : + H.route.net.degree v ≤ 2 * k := by + rw [fan_arity] + cases v with + | inl v => rw [Routes.old_arity, thin_arity]; have := hk v; omega + | inr v => + refine (H.unitFan.relay_le v).trans ?_ + rw [thin_arity] + exact Nat.mul_le_mul_left 2 (hk _) + +end Fanout +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- +# Diagrams with prescribed ordered station tables + +Local recipes see only the two exterior strings and two lists of bundle +words. The incidence bijections preserve bundle offsets at both ends. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open Transcript Finset MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +variable {F : Type} {a b : Wire} + +open Classical in +/-- The data for the drawing construction, including `left`, `right`, `recipe`. -/ +structure Drawing (G : Bundled F a b) where + /-- The left-side data carried by `Drawing`, with type `Side G.left G.src`. -/ + left : Side G.left G.src + /-- The right-side data carried by `Drawing`, with type `Side G.right G.dst`. -/ + right : Side G.right G.dst + /-- The `Drawing` component of type `G.V → Recipe F`. -/ + recipe : G.V → Recipe F + +namespace Drawing +variable {G : Bundled F a b} (D : Drawing G) + +open Classical in +/-- Computes the front by the application `D.left.panel G.width v`. -/ +abbrev front (v : G.V) := D.left.panel G.width v +open Classical in +/-- Computes the back by the application `D.right.panel G.width v`. -/ +abbrev back (v : G.V) := D.right.panel G.width v + +open Classical in +/-- Builds `Diagram F a b where V` with the specified `table`, `src`, `dst`. -/ +abbrev diagram : Diagram F a b where + V := G.V + E := G.Bit + table v := (D.front v).table (D.back v) (D.recipe v) + src := D.left.ports G.width + dst := D.right.ports G.width + +open Classical in +theorem source (e : G.Bit) : D.diagram.source e = G.src e.1 := D.left.owner G.width (.inr e) +open Classical in +theorem target (e : G.Bit) : D.diagram.target e = G.dst e.1 := D.right.owner G.width (.inr e) + +open Classical in +theorem exterior (q : slots a ⊕ slots b) : + Packing.portEnd D.diagram q = Sum.elim G.left G.right q := by + cases q with + | inl i => exact D.left.owner G.width (.inl i) + | inr i => exact D.right.owner G.width (.inl i) + +open Classical in +theorem arity (v : G.V) : D.diagram.arity v = G.arity v := by + change wd (D.left.panel G.width v).wire + wd (D.right.panel G.width v).wire = _ + rw [Side.wd_panel, Side.wd_panel, Bundled.arity] + omega + +open Classical in +theorem count (v : G.V) : (D.front v).count + (D.back v).count = G.degree v := by + change D.left.inner.count v + D.right.inner.count v = _ + simp only [Enum.count_eq, Fintype.card_subtype, card_filter, Bundled.degree] + +open Classical in +theorem vertex (x : Val a) (y : Val b) (z : G.Bit → Bool) (v : G.V) : + D.diagram.vertex x y z v = + D.recipe v (D.left.view G.width v (bits a x) z) (D.right.view G.width v (bits b y) z) := + congrArg₂ (D.recipe v) (D.left.read G.width v (bits a x) z) (D.right.read G.width v (bits b y) z) + +variable [Field F] + +open Classical in +theorem eval + (valid : ∀ x y s v, D.diagram.vertex x y (G.pack s) v = G.station v x y s) + (invalid : ∀ x y z, z ∉ Set.range G.pack → ∃ v, D.diagram.vertex x y z v = 0) : + D.diagram.eval = G.eval := by + rw [← Bundled.eval_diagram] + funext x y + apply sum_congr rfl + intro z _ + by_cases h : z ∈ Set.range G.pack + · obtain ⟨s, rfl⟩ := h + exact prod_congr rfl fun v _ => (valid x y s v).trans (G.vertex x y s v).symm + · obtain ⟨v, hv⟩ := invalid x y z h + exact (prod_eq_zero (mem_univ v) hv).trans (G.invalid x y z h).symm + +end Drawing +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- # Consecutive blocks on both sides of each physical station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open Transcript Finset MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +namespace Side +variable {X Y V E : Type} {f : X → V} {g : Y → V} {u v : E → V} + (P : Side f u) (Q : Side g v) (w : E → ℕ) (a : V) (b : Bool) + +open Classical in +/-- In the case `.inl _`, this construction gives `(b, none)`. -/ +def remote : (P.panel w a).Port → Bool × Option (V × ℕ) + | .inl _ => (b, none) + | .inr ⟨i, j⟩ => (b, some (Q.peer w ⟨P.inner.get a i, j⟩)) + +open Classical in +theorem adjacent (i j : (P.panel w a).Port) + (h : (P.panel w a).number i + 1 = (P.panel w a).number j) + (he : (P.panel w a).block i = (P.panel w a).block j) : + P.remote Q w a b j = Diagram.advance (P.remote Q w a b i) := by + rcases i with i | ⟨i, k⟩ <;> rcases j with j | ⟨j, l⟩ + · rfl + · simp [Panel.block] at he + · simp [Panel.block] at he + · have hij : i = j := Fin.ext (Nat.succ.inj he) + subst j + rw [Panel.number_inner, Panel.number_inner] at h + have hl : k.val + 1 = l.val := by dsimp only at h; omega + obtain ⟨s, hs⟩ := Q.peer_offset w (P.inner.get a i) + unfold remote + simp only [hs, Diagram.advance, Option.map_some, Nat.add_assoc, hl] + +end Side + +namespace Drawing +variable {F : Type} {a b : Wire} {G : Bundled F a b} (D : Drawing G) (v : G.V) + +open Classical in +/-- Indexes the both by the coordinates of `(D.front v).Port ⊕ (D.back v).Port`. -/ +abbrev Both := (D.front v).Port ⊕ (D.back v).Port + +open Classical in +private def place : D.Both v ≃ Fin (D.diagram.arity v) := + ((D.front v).port.symm.sumCongr (D.back v).port.symm).trans + (positions (.pair (D.front v).wire (D.back v).wire)) + +open Classical in +private theorem left_val (i : (D.front v).Port) : + (D.place v (.inl i)).val = (D.front v).number i := rfl + +open Classical in +private theorem right_val (i : (D.back v).Port) : + (D.place v (.inr i)).val = wd (D.front v).wire + (D.back v).number i := rfl + +open Classical in +private theorem left_peer (i : (D.front v).Port) : + D.diagram.peer v (D.place v (.inl i)) = D.left.remote D.right G.width v false i := by + let e := positions (.pair (D.front v).wire (D.back v).wire) + change D.diagram.portPeer v (e.symm (e (.inl ((D.front v).port.symm i)))) = _ + rw [Equiv.symm_apply_apply] + change (false, (D.left.ports G.width ⟨v, (D.front v).port.symm i⟩).elim (fun _ => none) + (fun j => some (D.right.peer G.width j))) = _ + rcases i with i | ⟨i, k⟩ + · rw [D.left.ports_ext G.width v i]; rfl + · rw [D.left.ports_inner G.width v i k]; rfl + +open Classical in +private theorem right_peer (i : (D.back v).Port) : + D.diagram.peer v (D.place v (.inr i)) = D.right.remote D.left G.width v true i := by + let e := positions (.pair (D.front v).wire (D.back v).wire) + change D.diagram.portPeer v (e.symm (e (.inr ((D.back v).port.symm i)))) = _ + rw [Equiv.symm_apply_apply] + change (true, (D.right.ports G.width ⟨v, (D.back v).port.symm i⟩).elim (fun _ => none) + (fun j => some (D.left.peer G.width j))) = _ + rcases i with i | ⟨i, k⟩ + · rw [D.right.ports_ext G.width v i]; rfl + · rw [D.right.ports_inner G.width v i k]; rfl + +open Classical in +/-- In the case `.inl i`, this construction gives `(D.front v).block i`. -/ +def block : D.Both v → ℕ + | .inl i => (D.front v).block i + | .inr i => (D.front v).count + 1 + (D.back v).block i + +open Classical in +private theorem block_lt (i : D.Both v) : D.block v i < G.degree v + 2 := by + have hc := D.count v + have ef : (D.front v).count = D.left.inner.count v := rfl + cases i with + | inl i => have := (D.front v).block_le i; unfold block; dsimp only; omega + | inr i => have := (D.back v).block_le i; unfold block; dsimp only; omega + +open Classical in +private theorem block_mono (i j : D.Both v) (h : (D.place v i).val ≤ (D.place v j).val) : + D.block v i ≤ D.block v j := by + have ef : (D.front v).count = D.left.inner.count v := rfl + rcases i with i | i <;> rcases j with j | j + all_goals simp only [left_val, right_val] at h + all_goals simp only [block] + · exact (D.front v).monotone i j h + · have := (D.front v).block_le i; omega + · have : (D.front v).number j < wd (D.front v).wire := Fin.isLt _ + omega + · exact Nat.add_le_add_left ((D.back v).monotone i j (by omega)) _ + +open Classical in +private theorem block_next (i j : D.Both v) + (h : (D.place v i).val + 1 = (D.place v j).val) (he : D.block v i = D.block v j) : + D.diagram.peer v (D.place v j) = Diagram.advance (D.diagram.peer v (D.place v i)) := by + have ef : (D.front v).count = D.left.inner.count v := rfl + rcases i with i | i <;> rcases j with j | j + all_goals simp only [block] at he + · rw [left_peer, left_peer] + exact D.left.adjacent D.right _ _ _ i j h he + · have := (D.front v).block_le i; omega + · have := (D.front v).block_le j; omega + · rw [right_peer, right_peer] + rw [right_val, right_val] at h + apply D.right.adjacent D.left + · exact Nat.add_left_cancel (by rwa [Nat.add_assoc] at h) + · exact Nat.add_left_cancel he + +open Classical in +theorem order {R : ℕ} (hR : ∀ v, G.degree v + 2 ≤ R) : D.diagram.PortOrder R := by + intro v + let block (i : Fin (D.diagram.arity v)) : Fin R := + ⟨D.block v ((D.place v).symm i), (D.block_lt v _).trans_le (hR v)⟩ + refine ⟨block, ?_, ?_⟩ + · intro i j h + apply D.block_mono + simpa only [Equiv.apply_symm_apply] using (show i.val ≤ j.val from h) + · intro i j h he + obtain ⟨i, rfl⟩ := (D.place v).surjective i + obtain ⟨j, rfl⟩ := (D.place v).surjective j + exact D.block_next v i j h (by simpa [block] using congrArg Fin.val he) + +end Drawing +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- # Decoding a bundle with its own finite alphabet -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +open Classical in +/-- The indexing data represented by `List Bool → Option α`. -/ +abbrev Decoder (α : Type) := List Bool → Option α + +variable {α β : Type} + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def decode (X : Type) (n : ℕ) (c : X ↪ (Fin n → Bool)) (tag : X → α) : Decoder α := + Function.extend (fun x => List.ofFn (c x)) (fun x => some (tag x)) (fun _ => none) + +variable {X : Type} {n : ℕ} (c : X ↪ (Fin n → Bool)) (tag : X → α) + +open Classical in +theorem decode_good (x : X) : decode X n c tag (List.ofFn (c x)) = some (tag x) := + Function.Injective.extend_apply + (show Function.Injective (fun x => List.ofFn (c x)) from List.ofFn_injective.comp c.injective) + _ _ x + +open Classical in +theorem decode_none (x : List Bool) (h : ¬ ∃ j, List.ofFn (c j) = x) : + decode X n c tag x = none := by simp [decode, Function.extend, h] + +open Classical in +/-- Evaluates `(D x).map f` at the input `x`. -/ +def Decoder.map (f : α → β) (D : Decoder α) : Decoder β := fun x => (D x).map f + +open Classical in +theorem decode_comp (f : α → β) : decode X n c (f ∘ tag) = (decode X n c tag).map f := by + funext x + by_cases h : ∃ j, List.ofFn (c j) = x + · obtain ⟨j, rfl⟩ := h + simp [Decoder.map, decode_good] + · simp [Decoder.map, decode_none _ _ _ h] + +open Classical in +/-- Evaluates `if h : i.val < n then x ⟨i.val, h⟩ else false` at the input `i`. -/ +def padBits (u n : ℕ) (x : Fin n → Bool) : Fin (Diagram.padWidth u n) → Bool := + fun i => if h : i.val < n then x ⟨i.val, h⟩ else false + +open Classical in +theorem padBits_injective (u n : ℕ) : Function.Injective (padBits u n) := by + intro x y h + funext i + simpa [padBits] using congrFun h (Fin.castLE (Diagram.le_padWidth u n) i) + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def Decoder.pad (u n : ℕ) (D : Decoder α) : Decoder α := + Function.extend (fun x => List.ofFn (padBits u n x)) (fun x => D (List.ofFn x)) (fun _ => none) + +open Classical in +theorem decode_pad {F : Type} {a b : Wire} (G : Bundled F a b) (e : G.E) (u : ℕ) + (tag : G.state e → α) : + decode _ _ ((G.pad u).code e) tag = Decoder.pad u (G.width e) (decode _ _ (G.code e) tag) := by + let w := G.width e + have hp (s : G.state e) : (G.pad u).code e s = padBits u w (G.code e s) := rfl + have hi : Function.Injective (fun z => List.ofFn (padBits u w z)) := + List.ofFn_injective.comp (padBits_injective u w) + funext x + by_cases h : ∃ z, List.ofFn (padBits u w z) = x + · obtain ⟨z, rfl⟩ := h + rw [Decoder.pad, hi.extend_apply] + by_cases hz : ∃ s, G.code e s = z + · obtain ⟨s, rfl⟩ := hz + rw [← hp, decode_good, decode_good] + · rw [decode_none, decode_none] + · rintro ⟨s, hs⟩; exact hz ⟨s, List.ofFn_injective hs⟩ + · rintro ⟨s, hs⟩; exact hz ⟨s, hi hs⟩ + · rw [decode_none _ _ _ (fun ⟨s, hs⟩ => h ⟨G.code e s, hs⟩)] + simp [Decoder.pad, Function.extend, show ¬ ∃ z, List.ofFn (padBits u (G.width e) z) = x from h] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- +# Local scripts + +A script supplies the exterior order, a list of incident operands and +an operation on their decoded symbols. The rendered recipe names +operands by local bundle offsets only. Every source checks its own +bundle words, including those omitted by the operation. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open Finset MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +open Classical in +/-- The indexing data represented by `List Bool → List Bool → List α → F`. -/ +abbrev Program (F α : Type) := List Bool → List Bool → List α → F +open Classical in +/-- Indexes the call by the coordinates of `Bool × ℕ × Decoder α`. -/ +abbrev Call (α : Type) := Bool × ℕ × Decoder α + +variable {F α V X : Type} {a b : Wire} {G : Bundled F a b} + +open Classical in +/-- The data for the exterior construction, including `ports`, `nodup`, `mem`. -/ +structure Exterior (f : X → V) where + /-- The `Exterior` component of type `V → List X`. -/ + ports : V → List X + nodup : ∀ v, (ports v).Nodup + mem : ∀ v i, i ∈ ports v ↔ f i = v + +variable {f : X → V} + +open Classical in +/-- Builds `Enum f where count v` with the specified `count`, `elem`. -/ +def Exterior.enum (B : Exterior f) : Enum f where + count v := (B.ports v).length + elem v := (List.Nodup.getEquiv _ (B.nodup v)).trans (Equiv.subtypeEquivRight (B.mem v)) + +open Classical in +theorem Exterior.values (B : Exterior f) (v : V) (x : X → Bool) : + List.ofFn (fun i => x (B.enum.get v i)) = (B.ports v).map x := by + change List.ofFn (x ∘ (B.ports v).get) = _ + rw [← List.map_ofFn, List.ofFn_get] + +open Classical in +/-- The data for the script construction, including `left`, `right`, `tag`, `program`, `reads`. -/ +structure Script (G : Bundled F a b) (α : Type) where + /-- The left-side data carried by `Script`, with type `Exterior G.left`. -/ + left : Exterior G.left + /-- The right-side data carried by `Script`, with type `Exterior G.right`. -/ + right : Exterior G.right + /-- Embeds the coordinates as `∀ e, G.state e ↪ α`. -/ + tag : ∀ e, G.state e ↪ α + /-- The `Script` component of type `G.V → Program F α`. -/ + program : G.V → Program F α + /-- The `Script` component of type `G.V → List G.E`. -/ + reads : G.V → List G.E + incident : ∀ v e, e ∈ reads v → G.src e = v ∨ G.dst e = v + run : ∀ v x y z, G.station v x y z = + program v ((left.ports v).map (bits a x)) ((right.ports v).map (bits b y)) + ((reads v).map fun e => tag e (z e)) + +open Classical in +/-- The value specified by `t.2.2 (((if t.1 then y else x).2[t.2.1]?).getD [])`. -/ +def Call.read (t : Call α) (x y : View) : Option α := + t.2.2 (((if t.1 then y else x).2[t.2.1]?).getD []) + +open Classical in +/-- The selected finite family `fun x y => if ∀ c ∈ checks ++ reads, c.read x y ≠ none then f +x.1 y.1 (reads.filterMap (fun c => c.read x y)) else 0`. -/ +def render [Zero F] (f : Program F α) (reads checks : List (Call α)) : Recipe F := + fun x y => if ∀ c ∈ checks ++ reads, c.read x y ≠ none then + f x.1 y.1 (reads.filterMap (fun c => c.read x y)) else 0 + +namespace Script +variable (p : Script G α) + +open Classical in +/-- Uses `⟨p.left.enum, Enum.any G.src⟩` as the representation. -/ +abbrev source : Side G.left G.src := ⟨p.left.enum, Enum.any G.src⟩ +open Classical in +/-- Uses `⟨p.right.enum, Enum.any G.dst⟩` as the representation. -/ +abbrev target : Side G.right G.dst := ⟨p.right.enum, Enum.any G.dst⟩ + +open Classical in +/-- Computes the signal by the application `decode _ _ (G.code e) (p.tag e)`. -/ +def signal (e : G.E) := decode _ _ (G.code e) (p.tag e) + +open Classical in +/-- Returns `(false, (p.source.inner.index e).val, p.signal e)` when `G.src e = v` holds, and +`(true, (p.target.inner.index e).val, p.signal e)` otherwise. -/ +def call (v : G.V) (e : G.E) : Call α := + if G.src e = v then (false, (p.source.inner.index e).val, p.signal e) + else (true, (p.target.inner.index e).val, p.signal e) + +open Classical in +/-- The indexed operation `(univ.filter fun e => G.src e = v).toList`. -/ +def checks (v : G.V) := (univ.filter fun e => G.src e = v).toList + +open Classical in +/-- Builds `Drawing G where left` with the specified `left`, `right`, `recipe`. -/ +abbrev drawing [Field F] : Drawing G where + left := p.source + right := p.target + recipe v := render (p.program v) ((p.reads v).map (p.call v)) + ((checks (G := G) v).map (p.call v)) + +open Classical in +theorem read_side {X E V : Type} {l : X → V} {f : E → V} (S : Side l f) + (w : E → ℕ) (x : X → Bool) (s : Side.Bit w → Bool) (e : E) : + (((S.view w (f e) x s).2[(S.inner.index e).val]?).getD []) = + List.ofFn (fun i => s ⟨e, i⟩) := by + let q (e : E) := List.ofFn (fun i => s ⟨e, i⟩) + change ((List.ofFn (fun j => q (S.inner.get (f e) j)))[(S.inner.index e).val]?).getD [] = q e + simp + +open Classical in +theorem read_call (v : G.V) (e : G.E) (h : G.src e = v ∨ G.dst e = v) + (x : Val a) (y : Val b) (z : G.Bit → Bool) : + (p.call v e).read (p.source.view G.width v (bits a x) z) (p.target.view G.width v (bits b y) z) + = + p.signal e (List.ofFn fun i => z ⟨e, i⟩) := by + by_cases hs : G.src e = v + · subst v + simp only [call, ite_true, Call.read, Bool.false_eq_true, ite_false] + rw [read_side] + · have he := h.resolve_left hs + subst v + simp only [call, ite_eq_right hs, Call.read, ite_true] + rw [read_side] + +variable [Field F] + +open Classical in +theorem valid (x : Val a) (y : Val b) (s : G.State) (v : G.V) : + p.drawing.diagram.vertex x y (G.pack s) v = G.station v x y s := by + rw [Drawing.vertex, p.run] + let l := p.source.view G.width v (bits a x) (G.pack s) + let r := p.target.view G.width v (bits b y) (G.pack s) + have h (e : G.E) (he : G.src e = v ∨ G.dst e = v) : + (p.call v e).read l r = some (p.tag e (s e)) := + (p.read_call v e he _ _ _).trans (decode_good (G.code e) (p.tag e) (s e)) + have hv : ∀ c ∈ (checks (G := G) v).map (p.call v), c.read l r ≠ none := by + simp only [List.forall_mem_map, checks, mem_toList, mem_filter, mem_univ, true_and] + intro e he + rw [h e (.inl he)] + exact Option.some_ne_none _ + have hr (es : List G.E) (hs : es ⊆ p.reads v) : + (es.map (p.call v)).filterMap (fun c => c.read l r) = es.map (fun e => p.tag e (s e)) := by + induction es with + | nil => rfl + | cons e es ih => + rw [List.map_cons, List.filterMap_cons, h e (p.incident _ _ (hs (by simp)))] + exact congrArg _ (ih (fun _ ht => hs (List.mem_cons_of_mem _ ht))) + change render _ _ _ l r = _ + have ha : ∀ c ∈ (p.reads v).map (p.call v), c.read l r ≠ none := by + rw [List.forall_mem_map] + intro e he + rw [h e (p.incident _ _ he)] + exact Option.some_ne_none _ + rw [render, ite_eq_left (List.forall_mem_append.mpr ⟨hv, ha⟩), hr _ (fun _ he => he)] + exact congrArg₂ (fun a b => p.program v a b _) (p.left.values _ _) (p.right.values _ _) + +open Classical in +theorem invalid (x : Val a) (y : Val b) (z : G.Bit → Bool) (h : z ∉ Set.range G.pack) : + ∃ v, p.drawing.diagram.vertex x y z v = 0 := by + have he : ∃ e, ¬ ∃ t, List.ofFn (G.code e t) = List.ofFn (fun i => z ⟨e, i⟩) := by + by_contra! hh + choose s hs using hh + exact h ⟨s, funext fun j => congrFun (List.ofFn_injective (hs j.1)) j.2⟩ + obtain ⟨e, he⟩ := he + refine ⟨G.src e, ?_⟩ + rw [Drawing.vertex] + apply ite_eq_right + intro h' + have hx := h' (p.call (G.src e) e) (List.mem_append_left _ (List.mem_map_of_mem (by simp + [checks]))) + exact hx ((p.read_call (G.src e) e (.inl rfl) _ _ _).trans (decode_none _ _ _ he)) + +open Classical in +theorem eval : p.drawing.diagram.eval = G.eval := p.drawing.eval p.valid p.invalid + +end Script +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- +# Counting physical table names + +Boundedly many whole records are selected from finite dictionaries. +The exponent depends on the number of bundles read, never on their bit +width. The bound is uniform over all global station and edge names. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open Finset MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +variable {α F : Type} + +open Classical in +/-- In the case `0`, this construction gives `{[]}`. -/ +def strings (s : Finset α) : ℕ → Finset (List α) + | 0 => {[]} + | n + 1 => insert [] ((s ×ˢ strings s n).image fun p => p.1 :: p.2) + +open Classical in +theorem mem_strings (s : Finset α) (n : ℕ) (l : List α) + (hl : l.length ≤ n) (h : ∀ x ∈ l, x ∈ s) : l ∈ strings s n := by + induction n generalizing l with + | zero => simp [strings, List.length_eq_zero_iff.mp (by omega : l.length = 0)] + | succ n ih => + cases l with + | nil => exact mem_insert_self _ _ + | cons x l => + apply mem_insert_of_mem + refine mem_image.mpr ⟨(x, l), mem_product.mpr ⟨h x (by simp), ?_⟩, rfl⟩ + exact ih _ (Nat.succ_le_succ_iff.mp hl) (fun y hy => h _ (List.mem_cons_of_mem _ hy)) + +open Classical in +theorem card_strings (s : Finset α) (n : ℕ) : (strings s n).card ≤ (s.card + 1) ^ n := by + induction n with + | zero => simp [strings] + | succ n ih => + refine (card_insert_le _ _).trans ((Nat.add_le_add_right card_image_le _).trans ?_) + rw [card_product, pow_succ', add_mul, one_mul] + exact Nat.add_le_add (Nat.mul_le_mul_left _ ih) (Nat.one_le_pow _ _ (by omega)) + +open Classical in +/-- Uses `⟨e, xs.length, xs.get⟩` as the representation. -/ +def Panel.ofList (e : ℕ) (xs : List ℕ) : Panel := ⟨e, xs.length, xs.get⟩ + +open Classical in +private theorem panel_roundtrip (p : Panel) : Panel.ofList p.ext (List.ofFn p.width) = p := by + cases p with + | mk e n f => + simp only [Panel.ofList, Panel.mk.injEq, true_and, List.length_ofFn] + exact Function.hfunext (by simp) (fun i j h => by simp [Fin.val_eq_val_of_heq h]) + +open Classical in +/-- The quantity computed by `((range (u + 1)) ×ˢ strings (range (u + 1)) k).image fun p => +Panel.ofList p.1 p.2`. -/ +def panels (k u : ℕ) : Finset Panel := + ((range (u + 1)) ×ˢ strings (range (u + 1)) k).image fun p => Panel.ofList p.1 p.2 + +open Classical in +theorem panel_mem (p : Panel) {k u : ℕ} (hk : p.count ≤ k) (hu : wd p.wire ≤ u) : + p ∈ panels k u := by + rw [Panel.wd_wire] at hu + refine mem_image.mpr ⟨(p.ext, List.ofFn p.width), mem_product.mpr ⟨mem_range.mpr (by omega), + mem_strings _ _ _ (by simpa using hk) ?_⟩, panel_roundtrip p⟩ + rintro _ hx + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hx + have h : p.width i ≤ p.size := single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ i) + exact mem_range.mpr (by omega) + +open Classical in +theorem panel_count (k u : ℕ) : (panels k u).card ≤ (u + 1) * (u + 2) ^ k := by + refine card_image_le.trans ?_ + rw [card_product, card_range] + exact Nat.mul_le_mul_left _ (by simpa only [card_range] using card_strings (range (u + 1)) k) + +open Classical in +/-- The value specified by `univ ×ˢ (range k ×ˢ d)`. -/ +def calls (d : Finset (Decoder α)) (k : ℕ) : Finset (Call α) := + univ ×ˢ (range k ×ˢ d) + +open Classical in +/-- The menu of type `Finset (Table F)`, constructed using `panels k u`. -/ +def menu [Zero F] (ops : Finset (Program F α)) (dec : Finset (Decoder α)) (k u : ℕ) : Finset (Table + F) := + let side := panels k u + let args := strings (calls dec k) k + ((side ×ˢ side) ×ˢ (ops ×ˢ (args ×ˢ args))).image fun s => + s.1.1.table s.1.2 (render s.2.1 s.2.2.1 s.2.2.2) + +open Classical in +theorem menu_count [Zero F] (ops : Finset (Program F α)) (dec : Finset (Decoder α)) (k u : ℕ) : + (menu ops dec k u).card ≤ ((u + 1) * (u + 2) ^ k) ^ 2 * ops.card * ((2 * k * dec.card + + 1) ^ k) ^ 2 := by + have ha : (strings (calls dec k) k).card ≤ (2 * k * dec.card + 1) ^ k := by + simpa [calls, mul_assoc] using card_strings (calls dec k) k + refine card_image_le.trans ?_ + rw [card_product, card_product, card_product, card_product, ← pow_two, ← pow_two, ← mul_assoc] + gcongr + exact panel_count _ _ + +namespace Script +variable [Field F] {a b : Wire} {G : Bundled F a b} (s : Script G α) + (ops : Finset (Program F α)) (dec : Finset (Decoder α)) (k u : ℕ) + +open Classical in +theorem menu_mem (ho : ∀ v, s.program v ∈ ops) (hc : ∀ e, s.signal e ∈ dec) + (hw : ∀ v, G.arity v ≤ u) (hv : ∀ v, G.degree v ≤ k) (hr : ∀ v, (s.reads v).length ≤ k) + (v : G.V) : s.drawing.diagram.table v ∈ menu ops dec k u := by + let L := s.drawing.front v + let R := s.drawing.back v + have hdeg : L.count + R.count ≤ k := (s.drawing.count v).trans_le (hv v) + have hwidth : wd L.wire + wd R.wire ≤ u := (s.drawing.arity v).trans_le (hw v) + have hm (e : G.E) (he : G.src e = v ∨ G.dst e = v) : s.call v e ∈ calls dec k := by + unfold call calls + split_ifs with h + · have h' : (s.source.inner.index e).val < L.count := by + change _ < s.source.inner.count v + rw [← h] + exact Fin.isLt _ + exact mem_product.mpr ⟨mem_univ _, mem_product.mpr ⟨mem_range.mpr (h'.trans_le (show L.count + ≤ k by omega)), hc e⟩⟩ + · have h' : (s.target.inner.index e).val < R.count := by + change _ < s.target.inner.count v + rw [← he.resolve_left h] + exact Fin.isLt _ + exact mem_product.mpr ⟨mem_univ _, mem_product.mpr ⟨mem_range.mpr (h'.trans_le (show R.count + ≤ k by omega)), hc e⟩⟩ + have hl (l : List G.E) (hn : l.length ≤ k) (hi : ∀ e ∈ l, G.src e = v ∨ G.dst e = v) : + l.map (s.call v) ∈ strings (calls dec k) k := by + refine mem_strings _ _ _ (by simpa using hn) ?_ + rintro _ h + obtain ⟨e, he, rfl⟩ := List.mem_map.mp h + exact hm e (hi e he) + let c := checks (G := G) v + have hn : c.length ≤ k := by + have : c.length = L.count := by + change (univ.filter fun e => G.src e = v).toList.length = s.source.inner.count v + rw [Enum.count_eq, Fintype.card_subtype, length_toList] + omega + refine mem_image.mpr ⟨((L, R), s.program v, (s.reads v).map (s.call v), c.map (s.call v)), ?_, + rfl⟩ + simp only [mem_product] + refine ⟨⟨panel_mem _ (by omega) (by omega), panel_mem _ (by omega) (by omega)⟩, + ho v, hl _ (hr v) (s.incident v), hl _ hn ?_⟩ + simp only [c, checks, mem_toList, mem_filter, mem_univ, true_and] + exact fun _ h => .inl h + +end Script +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- # One equality program suffices for all relay and hub tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Finset + +variable {F α V E X Y : Type} {a b : Wire} {G : Bundled F a b} + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def Exterior.lift {f : X → V} (P : Exterior f) (Y : Type) : + Exterior (Sum.inl ∘ f : X → V ⊕ Y) where + ports := Sum.elim P.ports (fun _ => []) + nodup := by + rintro (v|v) + · exact P.nodup v + · exact List.nodup_nil + mem := by rintro (v|v) i <;> simp [P.mem] + +open Classical in +/-- The indexed operation `l.flatMap (fun p => [p.1, p.2])`. -/ +def pairs (l : List (E × E)) : List E := l.flatMap (fun p => [p.1, p.2]) + +open Classical in +theorem length_pairs (l : List (E × E)) : (pairs l).length = 2 * l.length := by + induction l with + | nil => rfl + | cons p l ih => change (p.1 :: p.2 :: pairs l).length = _; simp [ih]; omega + +open Classical in +theorem pairs_forall (l : List (E × E)) (p : E → Prop) : + (∀ e ∈ pairs l, p e) ↔ ∀ t ∈ l, p t.1 ∧ p t.2 := by + simp [pairs] + grind + +open Classical in +/-- In the case `[]`, this construction gives `True`. -/ +def equalPairs : List α → Prop + | [] => True + | [_] => False + | x :: y :: l => x = y ∧ equalPairs l + +open Classical in +/-- Evaluates `if equalPairs l then 1 else 0` at the input `_ _ l`. -/ +def checkPairs [Field F] : Program F α := fun _ _ l => if equalPairs l then 1 else 0 + +open Classical in +theorem checkPairs_eq [Field F] (f : E → α) (l : List (E × E)) (x y : List Bool) : + checkPairs x y ((pairs l).map f) = if ∀ p ∈ l, f p.1 = f p.2 then (1 : F) else 0 := by + have h : equalPairs ((pairs l).map f) ↔ ∀ p ∈ l, f p.1 = f p.2 := by + induction l with + | nil => simp [pairs, equalPairs] + | cons p l ih => + change (f p.1 = f p.2 ∧ equalPairs ((pairs l).map f)) ↔ _ + rw [List.forall_mem_cons, ih] + simp only [checkPairs, h] + +namespace Script +variable (p : Script G α) + +open Classical in +/-- Uses `⟨p.left, p.right, p.tag, p.program, p.reads, p.incident, p.run⟩` as the +representation. -/ +abbrev pad (u : ℕ) : Script (G.pad u) α := + ⟨p.left, p.right, p.tag, p.program, p.reads, p.incident, p.run⟩ + +open Classical in +theorem signal_pad (u : ℕ) (e : G.E) : + (p.pad u).signal e = Decoder.pad u (G.width e) (p.signal e) := decode_pad _ _ _ _ + +variable (R : Routes G Y) + +open Classical in +/-- Returns `⟨e, 0⟩` when `G.src e = v` holds, and `⟨e, Fin.last _⟩` otherwise. -/ +def endpoint (v : G.V) (e : G.E) : R.Hop := + if G.src e = v then ⟨e, 0⟩ else ⟨e, Fin.last _⟩ + +open Classical in +theorem endpoint_incident (v : G.V) (e : G.E) (he : G.src e = v ∨ G.dst e = v) : + R.src (endpoint R v e) = .inl v ∨ R.dst (endpoint R v e) = .inl v := by + unfold endpoint + split_ifs with h + · exact .inl (by simp [Routes.src, h]) + · exact .inr (by simp [Routes.dst, he.resolve_left h]) + +open Classical in +/-- Computes the route tag by the application `p.tag i.1`. -/ +def routeTag (i : R.Hop) := p.tag i.1 + +open Classical in +theorem endpoint_tag (v : G.V) (s : R.Data) (e : G.E) : + p.routeTag R (endpoint R v e) (s (endpoint R v e)) = p.tag e (R.read v s e) := by + unfold Routes.read + by_cases h : G.src e = v + · rw [ite_eq_left h, show endpoint R v e = ⟨e, 0⟩ from ite_eq_left h] + rfl + · rw [ite_eq_right h, show endpoint R v e = ⟨e, Fin.last _⟩ from ite_eq_right h] + rfl + +open Classical in +/-- Indexes the visit by the coordinates of `Σ e, Fin (R.length e)`. -/ +abbrev Visit := Σ e, Fin (R.length e) +open Classical in +/-- Selects the elements of all indices satisfying `(fun i : Visit R => R.via i.1 i.2 = v)`. -/ +def visits (v : Y) := univ.filter (fun i : Visit R => R.via i.1 i.2 = v) +open Classical in +/-- The value specified by `(⟨i.1, i.2.castSucc⟩, ⟨i.1, i.2.succ⟩)`. -/ +def ends (i : Visit R) : R.Hop × R.Hop := (⟨i.1, i.2.castSucc⟩, ⟨i.1, i.2.succ⟩) +open Classical in +/-- Transforms the indexed data by `(visits R v).toList.map (ends R)`. -/ +def matched (v : Y) := (visits R v).toList.map (ends R) + +variable [Field F] [Fintype Y] + +open Classical in +/-- Builds `Script R.net α where left` with the specified `left`, `right`, `tag`, `program`. -/ +abbrev route : Script R.net α where + left := p.left.lift Y + right := p.right.lift Y + tag := p.routeTag R + program := Sum.elim p.program (fun _ => checkPairs) + reads := Sum.elim (fun v => (p.reads v).map (endpoint R v)) (fun v => pairs (matched R v)) + incident := by + rintro (v|v) e he + · obtain ⟨i, hi, rfl⟩ := List.mem_map.mp he + exact endpoint_incident R v i (p.incident v i hi) + · have h : ∀ e ∈ pairs (matched R v), R.src e = .inr v ∨ R.dst e = .inr v := by + rw [pairs_forall] + rintro _ hs + obtain ⟨⟨i, j⟩, hi, rfl⟩ := List.mem_map.mp hs + have hj := (mem_filter.mp (mem_toList.mp hi)).2 + exact ⟨.inr (by simp [ends, Routes.dst, hj]), .inl (by simp [ends, Routes.src, hj])⟩ + exact h e he + run := by + rintro (v|v) x y z + · change G.station v x y (R.read v z) = + p.program v _ _ (((p.reads v).map (endpoint R v)).map (fun e => p.routeTag R e (z e))) + rw [p.run, List.map_map] + simp only [Function.comp_def, endpoint_tag] + rfl + · change (if R.Valid v z then 1 else 0) = + checkPairs [] [] ((pairs (matched R v)).map (fun e => p.routeTag R e (z e))) + rw [checkPairs_eq (F := F)] + have he : (∀ i ∈ matched R v, + p.routeTag R i.1 (z i.1) = p.routeTag R i.2 (z i.2)) ↔ R.Valid v z := by + simp only [matched, List.forall_mem_map, mem_toList, visits, mem_filter, mem_univ, true_and, + ends, routeTag, Routes.Valid, Sigma.forall] + constructor + · exact fun h e j hj => (p.tag e).injective (h e j hj) + · exact fun h e j hj => congrArg (p.tag e) (h e j hj) + simp only [he] + +open Classical in +private theorem visit_count (v : Y) : (visits R v).card ≤ R.net.degree (.inr v) := by + unfold visits Bundled.degree + refine le_trans ?_ (Nat.le_add_right _ _) + rw [card_filter, Fintype.sum_sigma, Fintype.sum_sigma] + apply sum_le_sum + intro e _ + rw [Fin.sum_univ_succ] + simp [Routes.src] + +open Classical in +theorem length_route (v : Y) : ((p.route R).reads (.inr v)).length ≤ 2 * R.net.degree (.inr v) := by + change (pairs (matched R v)).length ≤ _ + rw [length_pairs, matched, List.length_map, length_toList] + exact Nat.mul_le_mul_left _ (visit_count R v) + +end Script +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- A station reads a list of ordinary keys; repeated reads are allowed. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Surface.Stage + +variable {F U X E V K : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + +/-- The data for the rules construction, including `left`, `right`, `tag`, `label`, `reads`. -/ +structure Rules (S : Sharing C a b Y) where + /-- The left-side data carried by `Rules`, with type `Exterior S.left`. -/ + left : Exterior S.left + /-- The right-side data carried by `Rules`, with type `Exterior S.right`. -/ + right : Exterior S.right + /-- Embeds the coordinates as `∀ k, Y.state k ↪ Symbol (M * t)`. -/ + tag : ∀ k, Y.state k ↪ Symbol (M * t) + /-- The label at each coordinate of type `Place C → Label F (M * r) (M * t)`. -/ + label : Place C → Label F (M * r) (M * t) + /-- The `Rules` component of type `Place C → List K`. -/ + reads : Place C → List K + seen : ∀ i k, k ∈ reads i → k ∈ S.reads i + run : ∀ i x y s a' b', (item C i).table (S.param x y s) a' b' = + label i ((left.ports i).map (bits a x)) ((right.ports i).map (bits b y)) + ((reads i).map fun k => tag k (s k)) a'.val b'.val + +namespace Rules +variable {S : Sharing C a b Y} (L : Rules S) +/-- Computes the signal by the application `decode _ _ (Y.code k) (L.tag k)`. -/ +def signal (k : K) := decode _ _ (Y.code k) (L.tag k) +end Rules + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- An ordinary hub compares each visible key with its local storage copy. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Finset + +variable {F U X E V K : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) (v : V) + +open Classical in +/-- The indexed operation `univ.filter fun e => e.1 ∈ S.seen v ∧ (S.source e = .inr (.inl v) ∨ +S.target e = .inr (.inl v))`. -/ +def contacts : Finset S.Edge := + univ.filter fun e => e.1 ∈ S.seen v ∧ (S.source e = .inr (.inl v) ∨ S.target e = .inr (.inl v)) + +open Classical in +/-- The value specified by `(i.val, ⟨i.val.1, .inl ⟨v, (mem_filter.mp i.property).2.1⟩⟩)`. -/ +def mates (i : ↥(contacts S v)) : S.Edge × S.Edge := + (i.val, ⟨i.val.1, .inl ⟨v, (mem_filter.mp i.property).2.1⟩⟩) + +open Classical in +/-- Computes the hub reads by the application `pairs ((contacts S v).attach.toList.map (mates S +v))`. -/ +def hubReads : List S.Edge := pairs ((contacts S v).attach.toList.map (mates S v)) + +omit [Field F] in +open Classical in +theorem hub_meets : ∀ e ∈ hubReads S v, S.source e = .inr (.inl v) ∨ S.target e = .inr (.inl v) + := by + unfold hubReads + rw [pairs_forall] + rintro _ he + obtain ⟨i, _, rfl⟩ := List.mem_map.mp he + exact ⟨(mem_filter.mp i.property).2.2, .inl rfl⟩ + +open Classical in +theorem hub_eval {α : Type} (tag : ∀ k, Y.state k ↪ α) (z : S.State) (x y : List Bool) : + checkPairs x y ((hubReads S v).map (fun e => tag e.1 (z e))) = + if S.checks (.inr (.inl v)) z then (1 : F) else 0 := by + rw [hubReads, checkPairs_eq] + simp only [List.forall_mem_map, mem_toList, mem_attach, true_implies] + congr 1 + apply propext + constructor + · intro h k j hj e he + have hj' : v = j.val := Sum.inl.inj (Sum.inr.inj hj) + subst v + let i : ↥(contacts S j.val) := ⟨⟨k, e⟩, mem_filter.mpr ⟨mem_univ _, j.property, he⟩⟩ + exact (tag k).injective (h i) + · intro h i + obtain ⟨_, hs, he⟩ := mem_filter.mp i.property + exact congrArg (tag i.val.1) (h _ ⟨v, hs⟩ rfl i.val.2 he) + +open Classical in +theorem length_hubReads : (hubReads S v).length ≤ 2 * S.base.degree (.inr (.inl v)) := by + rw [hubReads, length_pairs, List.length_map, length_toList, card_attach] + apply Nat.mul_le_mul_left + simp only [contacts, card_filter, Bundled.degree, ← sum_add_distrib] + apply sum_le_sum + intro i _ + split_ifs <;> grind + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end + +/- Local operations for reassembling chunk states and evaluating sphere forms. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Surface.Stage + +open Classical in +/-- The signal of type `Symbol (M * t) → Signal M r t | front : Wedge r → Signal M r t | back : +Wedge t → Signal M r t` for the given inputs. -/ +inductive Signal (M r t : ℕ) where + | key : Symbol (M * t) → Signal M r t + | front : Wedge r → Signal M r t + | back : Wedge t → Signal M r t + +variable {M r t : ℕ} + +open Classical in +/-- Indexes the args by the coordinates of `List (Symbol (M * t)) × (Fin M → Wedge r) × (Fin M → +Wedge t)`. -/ +abbrev Args (M r t : ℕ) := List (Symbol (M * t)) × (Fin M → Wedge r) × (Fin M → Wedge t) + +open Classical in +/-- Concatenates the components in the order `u.1.map .key ++ List.ofFn (fun j => .front (u.2.1 +j)) ++ List.ofFn (fun j => .back (u.2.2 j))`. -/ +def symbols (u : Args M r t) : List (Signal M r t) := + u.1.map .key ++ List.ofFn (fun j => .front (u.2.1 j)) ++ List.ofFn (fun j => .back (u.2.2 j)) + +open Classical in +private theorem symbols_injective : Function.Injective (symbols (M := M) (r := r) (t := t)) := by + rintro ⟨x, a, b⟩ ⟨x', a', b'⟩ h + unfold symbols at h + have hl := congrArg List.length h + simp only [List.length_append, List.length_ofFn, List.length_map] at hl + have hl₁ : (x.map (Signal.key (r := r)) ++ List.ofFn (fun i => Signal.front (a i))).length = + (x'.map Signal.key ++ List.ofFn (fun i => Signal.front (a' i))).length := by + simp only [List.length_append, List.length_ofFn, List.length_map] + omega + obtain ⟨h, hb⟩ := List.append_inj h hl₁ + let key : Symbol (M * t) → Signal M r t := Signal.key + have hl₂ : (x.map key).length = (x'.map key).length := by + simp only [List.length_map] + omega + obtain ⟨hx, ha⟩ := List.append_inj h hl₂ + have hx' := Function.Injective.list_map (fun _ _ he => Signal.key.inj he) hx + have ha' : a = a' := funext fun i => Signal.front.inj (congrFun (List.ofFn_injective ha) i) + have hb' : b = b' := funext fun i => Signal.back.inj (congrFun (List.ofFn_injective hb) i) + exact Prod.ext hx' (Prod.ext ha' hb') + +variable {F : Type} [Field F] + +open Classical in +/-- The indexed operation `fun x y => Function.extend symbols (fun u => f x y u.1 (Chunk.join +u.2.1) (Chunk.join u.2.2)) (fun _ => 0)`. -/ +def load (f : Label F (M * r) (M * t)) : Program F (Signal M r t) := + fun x y => Function.extend symbols + (fun u => f x y u.1 (Chunk.join u.2.1) (Chunk.join u.2.2)) (fun _ => 0) + +open Classical in +theorem load_symbols (f : Label F (M * r) (M * t)) (x y : List Bool) (u : Args M r t) : + load f x y (symbols u) = f x y u.1 (Chunk.join u.2.1) (Chunk.join u.2.2) := + symbols_injective.extend_apply _ _ u + +open Classical in +/-- In the case `.front a`, this construction gives `a`. -/ +def Signal.first : Signal M r t → Wedge r + | .front a => a + | _ => ⟨[], by simp⟩ + +open Classical in +/-- In the case `.back a`, this construction gives `a`. -/ +def Signal.second : Signal M r t → Wedge t + | .back a => a + | _ => ⟨[], by simp⟩ + +open Classical in +/-- Evaluates `wick fieldKernel (z.zipWith (fun v s => Surface.modes v (g s)) u).flatten` at the +input `_ _ u`. -/ +def chamber {α : Type} (g : α → Wedge r) (z : List F) : Program F α := + fun _ _ u => wick fieldKernel (z.zipWith (fun v s => Surface.modes v (g s)) u).flatten + +open Classical in +theorem chamber_eval {α I : Type} (g : α → Wedge r) (h : I → α) (z : I → F) + (l : List I) (x y : List Bool) : + chamber g (l.map z) x y (l.map h) = Layout.read z (g ∘ h) l := by + unfold chamber Layout.read + congr 1 + induction l with + | nil => rfl + | cons i l ih => + simp only [List.map_cons, List.zipWith_cons_cons, List.flatten_cons, List.flatMap_cons, ih, + Function.comp_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Border.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Border.lean new file mode 100644 index 0000000000..199409b715 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Border.lean @@ -0,0 +1,852 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Pad +public import Mathlib.Order.Interval.Finset.Fin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Parcel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Restore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Shapes + +/-! +# Adding binary lanes and comparing the result with fixed thresholds + +Read columns from the least significant end. A differing bit overrides +the previous comparison. The carry never exceeds the number of lanes. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Scan +open Finset + +/-- Indexes the carry by the coordinates of `Fin (Fintype.card I + 1) × (J → Bool)`. -/ +abbrev Carry (I J : Type) [Fintype I] := Fin (Fintype.card I + 1) × (J → Bool) + +/-- The indexed operation `(0, fun _ => false)`. -/ +def initial (I J : Type) [Fintype I] : Carry I J := (0, fun _ => false) + +variable {I J : Type} [Fintype I] + +/-- The step of type `Bool × Carry I J`, constructed using `s.1.val + ∑ i, (d i).toNat`. -/ +def step (s : Carry I J) (d : I → Bool) (c : J → Bool) : Bool × Carry I J := + let n := s.1.val + ∑ i, (d i).toNat + let b := decide (n % 2 = 1) + (b, ⟨n / 2, by + have h : (∑ i, (d i).toNat) ≤ Fintype.card I := by + simpa using sum_le_sum (fun i (_ : i ∈ univ) => show (d i).toNat ≤ 1 by cases d i <;> decide) + have := s.1.isLt + unfold n + omega⟩, fun j => if b = c j then s.2 j else b) + +/-- Evaluates `(l i).testBit t` at the input `i`. -/ +def column {A : Type} (l : A → ℕ) (t : ℕ) := fun i => (l i).testBit t + +/-- In the case `0`, this construction gives `initial I J`. -/ +def run (l : I → ℕ) (c : J → ℕ) : ℕ → Carry I J + | 0 => initial I J + | t + 1 => (step (run l c t) (column l t) (column c t)).2 + +private theorem bitFromScan (x t : ℕ) : x.testBit t = decide (x / 2 ^ t % 2 = 1) := by + simpa only [zero_add, Nat.testBit_zero] using Nat.testBit_add x 0 t + +private theorem value (x t : ℕ) : (x.testBit t).toNat = x / 2 ^ t % 2 := by + rw [bitFromScan] + by_cases h : x / 2 ^ t % 2 = 1 + · simp [h] + · have : x / 2 ^ t % 2 = 0 := by omega + simp [this] + +variable (l : I → ℕ) (c : J → ℕ) + +private theorem split_sum (t : ℕ) : + (∑ i, l i / 2 ^ t) = (∑ i, (column l t i).toNat) + 2 * (∑ i, l i / 2 ^ (t + 1)) := by + rw [mul_sum, ←sum_add_distrib] + refine sum_congr rfl fun i _ => ?_ + rw [column, value, pow_succ, ←Nat.div_div_eq_div_mul] + omega + +/-- The unread portion of the sum includes the carry from the last column. -/ +theorem carry_eq (t : ℕ) : (∑ i, l i) / 2 ^ t = (run l c t).1.val + ∑ i, l i / 2 ^ t := by + induction t with + | zero => simp [run, initial] + | succ t ih => + have hs := split_sum l t + change (∑ i, l i) / 2 ^ (t + 1) = + ((run l c t).1.val + ∑ i, (column l t i).toNat) / 2 + ∑ i, l i / 2 ^ (t + 1) + conv_lhs => rw [pow_succ, ←Nat.div_div_eq_div_mul, ih, hs] + omega + +theorem digit (t : ℕ) : + (step (run l c t) (column l t) (column c t)).1 = (∑ i, l i).testBit t := by + rw [bitFromScan, carry_eq l c, split_sum l] + unfold step + dsimp only + congr 2 + omega + +private theorem extend (x y t : ℕ) : + (if x.testBit t = y.testBit t then decide (y % 2 ^ t < x % 2 ^ t) else x.testBit t) = + decide (y % 2 ^ (t + 1) < x % 2 ^ (t + 1)) := by + have hx := Nat.mod_lt x (Nat.two_pow_pos t) + have hy := Nat.mod_lt y (Nat.two_pow_pos t) + rw [pow_succ, Nat.mod_mul, Nat.mod_mul, ←value x, ←value y] + cases x.testBit t <;> cases y.testBit t <;> simp <;> omega + +theorem compared (w : ℕ) (j : J) : + (run l c w).2 j = decide (c j % 2 ^ w < (∑ i, l i) % 2 ^ w) := by + induction w with + | zero => simp [run, initial, Nat.mod_one] + | succ t ih => + let b := (step (run l c t) (column l t) (column c t)).1 + change (if b = (c j).testBit t then (run l c t).2 j else b) = _ + rw [show b = (∑ i, l i).testBit t from digit l c t, ih] + exact extend _ _ _ + +theorem greater (w : ℕ) (j : J) (h : ∑ i, l i < 2 ^ w) (h' : c j < 2 ^ w) : + (run l c w).2 j = decide (c j < ∑ i, l i) := by + rw [compared, Nat.mod_eq_of_lt h, Nat.mod_eq_of_lt h'] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Scan +end + +section +/- # Counting packets by threshold tests on unpadded lengths -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Scan +open Finset Diagram + +theorem packets {I : Type} [Fintype I] (n : I → ℕ) (R Q M : ℕ) (hp : 0 < R) + (he : R * Q = ∑ i, padWidth R (n i)) (hQ : Q ≤ M) : + (∑ i, (univ.filter fun t : Fin (M + 1) => t.val * R < n i).card) = Q := by + choose k hk using fun i => dvd_padWidth hp (n i) + have total : (∑ i, k i) = Q := by + simp_rw [hk] at he + rw [←mul_sum] at he + exact Nat.eq_of_mul_eq_mul_left hp he.symm + refine Eq.trans (sum_congr rfl fun i _ => ?_) total + have hi : k i ≤ M := + (single_le_sum (fun j _ => Nat.zero_le (k j)) (mem_univ i)).trans (total.le.trans hQ) + let b : Fin (M + 1) := ⟨k i, Nat.lt_succ_of_le hi⟩ + have lo := (le_padWidth R (n i)).trans_eq (hk i) + have lt : R * k i < n i + R := by + rw [←hk, padWidth] + split_ifs with h + · omega + · have hn : n i % R ≠ 0 := fun hz => h (Nat.dvd_of_mod_eq_zero hz) + omega + rw [show (univ.filter fun t : Fin (M + 1) => t.val * R < n i) = Iio b by + ext t + simp only [mem_filter, mem_univ, true_and, mem_Iio] + change t.val * R < n i ↔ t.val < k i + rw [mul_comm t.val] + constructor + · exact fun h => Nat.lt_of_mul_lt_mul_left (h.trans_le lo) + · intro h + have hs := Nat.mul_le_mul_left R (Nat.succ_le_of_lt h) + rw [Nat.mul_succ] at hs + omega] + simp [b] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Scan +end + +/- # The exterior rank of a pin in span order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme + +open Coloring Finset +variable {F : Type} (S : Scheme F) (r : S.format.obj) + +open scoped Classical in +/-- Exterior width preceding the given span on its station and side. -/ +def skip (t : S.Span) := + ∑ i : B S.e with i < t.2 ∧ S.direction r (t.1, i) = S.direction r t, S.borderLen r (t.1, i) + +open scoped Classical in +theorem skip_gap {t u : S.Span} (hv : t.1 = u.1) (hd : S.direction r t = S.direction r u) + (hlt : t.2 < u.2) : S.skip r t + S.borderLen r t ≤ S.skip r u := by + obtain ⟨v, i⟩ := t + obtain ⟨w, j⟩ := u + change v = w at hv + subst w + change i < j at hlt + let a (t : B S.e) := univ.filter (fun k => k < t ∧ S.direction r (v, k) = S.direction r (v, t)) + change (∑ k ∈ a i, S.borderLen r (v, k)) + S.borderLen r (v, i) ≤ ∑ k ∈ a j, S.borderLen r (v, k) + rw [add_comm, ← sum_insert (f := fun k => S.borderLen r (v, k)) (show i ∉ a i by simp [a])] + apply sum_le_sum_of_subset + simp only [a, insert_subset_iff, mem_filter, mem_univ, true_and] + refine ⟨⟨hlt, hd⟩, ?_⟩ + intro k hk + simp only [mem_filter, mem_univ, true_and] at hk ⊢ + exact ⟨hk.1.trans hlt, hk.2.trans hd⟩ + +open scoped Classical in +/-- The quantity computed by `(S.pattern r z.1.1).start z.1.1.2.2 z.1.2 + z.2.val`. -/ +abbrev portIndex (z : S.Pin r) := (S.pattern r z.1.1).start z.1.1.2.2 z.1.2 + z.2.val + +open scoped Classical in +private theorem pin_lt {v : S.Vtx} {i j : B S.e} (hi : Fin (S.width r (v, i))) + (hj : Fin (S.width r (v, j))) (h : S.direction r (v, i) = S.direction r (v, j)) (lt : i < j) : + S.portIndex r ⟨(v, i), hi⟩ < S.portIndex r ⟨(v, j), hj⟩ := by + have he := (S.pattern r v).start_left v.2.2 h lt + exact ((Nat.add_lt_add_left hi.isLt _).trans_le he).trans_le (Nat.le_add_right ..) + +open scoped Classical in +private theorem sum_before {n : ℕ} (z : Fin n) : + (∑ i : Fin n, if i.val < z.val then 1 else 0) = z.val := by + rw [← sum_filter, ← card_eq_sum_ones, ← Fin.card_Iio z] + congr 1 + ext i + simp + +open scoped Classical in +private theorem count_span (v : S.Vtx) (j : B S.e) (t : Fin (S.width r (v, j))) + (hj : S.peer r (v, j) = none) (i : B S.e) : + (∑ k : Fin (S.width r (v, i)), if S.peer r (v, i) = none then + if S.direction r (v, i) = S.direction r (v, j) ∧ S.portIndex r ⟨(v, i), k⟩ + < S.portIndex r ⟨(v, j), t⟩ + then 1 else 0 else 0) = + (if i < j ∧ S.direction r (v, i) = S.direction r (v, j) then S.borderLen r (v, i) else 0) + + (if i = j then t.val else 0) := by + rcases lt_trichotomy i j with ht|rfl|ht + · by_cases hd : S.direction r (v, i) = S.direction r (v, j) + · simp [ht, ht.ne, hd, S.pin_lt r _ t hd ht, borderLen] + · simp [ht.ne, hd] + · simp only [hj, ite_true, lt_self_iff_false, false_and, ite_false, zero_add, true_and, portIndex, + Nat.add_lt_add_iff_left] + exact sum_before t + · by_cases hd : S.direction r (v, i) = S.direction r (v, j) + · have hn (k) := (S.pin_lt r t k hd.symm ht).not_gt + simp [ht.not_gt, ht.ne', hn] + · simp [ht.ne', hd] + +open scoped Classical in +theorem skip_eq_card (z : S.exposed r) : + Fintype.card {w : S.exposed r // w.val.1.1 = z.val.1.1 ∧ S.direction r w.val.1 + = S.direction r z.val.1 ∧ + S.portIndex r w.val < S.portIndex r z.val} = S.skip r z.val.1 + z.val.2.val := by + obtain ⟨⟨⟨v, j⟩, t⟩, hj⟩ := z + let f (w : S.Pin r) := if w.1.1 = v ∧ S.direction r w.1 = S.direction r (v, j) ∧ + S.portIndex r w < S.portIndex r ⟨(v, j), t⟩ then 1 else 0 + rw [Fintype.card_subtype, card_eq_sum_ones, sum_filter] + change (∑ w : S.exposed r, f w.val) = S.skip r (v, j) + t.val + rw [← sum_subtype (univ.filter (fun w : S.Pin r => S.peer r w.1 = none)) mem_filter_univ f, + sum_filter, Fintype.sum_sigma, Fintype.sum_prod_type, sum_eq_single v] + · simp only [f, true_and, S.count_span r v j t hj, sum_add_distrib, sum_ite_eq', mem_univ, + ite_true, + skip, sum_filter] + · intro w _ hw + simp [f, hw] + · simp + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme +end + +/- # Exterior wire offsets in an ordered presentation -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +open Packing Transcript + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {r : S.format.obj} + {G : Diagram F x y} (p : S.Presentation r G) (h : p.Directed) + +open scoped Classical in +private theorem boundary_place (j : slots x ⊕ slots y) : + (p.boundary j).val.1.1 = p.vertex (portEnd G j) := by + cases j with + | inl i => exact p.end_station (.inl (.inl i)) + | inr i => exact p.end_station (.inr (.inl i)) + +local notation "q" => p.toOrdered h +local notation "H" => p.ordered h + +open scoped Classical in +private theorem boundary_side (j : slots x ⊕ slots y) : + S.direction r ((q).boundary j).val.1 = j.isRight := by + have hh : (q).Directed := by unfold Directed; rw [p.ordered_ends h]; exact h + cases j with + | inl i => exact hh (.inl (.inl i)) + | inr i => exact hh (.inr (.inl i)) + +open scoped Classical in +private theorem wire_index (v : (H).V) (i : Fin ((H).arity v)) : + let e := (H).endAt ⟨v, i⟩ + i.val = (if e.isRight then wd ((H).table v).1 else 0) + + S.portIndex r ((q).ends e) := by + let pos : (H).Port v ≃ Fin ((H).arity v) := positions (.pair ((H).table v).1 ((H).table v).2.1) + obtain ⟨j, rfl⟩ := pos.surjective i + have ht : (H).endAt ⟨v, pos j⟩ = (H).portEquiv ⟨v, j⟩ := by + change (H).portEquiv ⟨v, pos.symm (pos j)⟩ = _ + rw [pos.symm_apply_apply] + dsimp only + rw [ht, (q).toSeating.ends_at] + let A := S.pattern r (p.vertex v) + cases j with + | inl t => + change _ = 0 + _ + rw [Nat.zero_add] + exact A.position_left _ t + | inr t => + exact congrArg (wd ((H).table v).1 + ·) (A.position_right _ t) + +open scoped Classical in +private theorem exterior_increasing {B : Type} (v : (H).V) (d : Bool) + (pick : Boundary x y ⊕ (H).E → Option B) (f : B → (H).End) + (spec : ∀ e b, pick ((H).endWire e) = some b → e = f b) (side : ∀ b, (f b).isRight = d) : + List.Pairwise (fun a b => S.portIndex r ((q).ends (f a)) < S.portIndex r ((q).ends (f b))) + ((List.ofFn ((H).wireAt v)).filterMap pick) := by + rw [List.pairwise_filterMap, List.pairwise_ofFn] + intro i j hij a ha b hb + rw [Diagram.wireAt_eq] at ha hb + have hi := p.wire_index h v i + have hj := p.wire_index h v j + dsimp only at hi hj + rw [spec _ _ ha, side] at hi + rw [spec _ _ hb, side] at hj + omega + +omit [Field F] in +open scoped Classical in +private theorem rank_index {n : ℕ} (f : Fin n → S.exposed r) (v : S.Vtx) (d : Bool) + (here : ∀ j, (f j).val.1.1 = v) (dir : ∀ j, S.direction r (f j).val.1 = d) + (onto : ∀ w : S.exposed r, w.val.1.1 = v → S.direction r w.val.1 = d → ∃ j, f j = w) + (mono : StrictMono (fun j => S.portIndex r (f j).val)) (i : Fin n) : + i.val = S.skip r (f i).val.1 + (f i).val.2.val := by + let A := {w : S.exposed r // w.val.1.1 = (f i).val.1.1 ∧ + S.direction r w.val.1 = S.direction r (f i).val.1 ∧ S.portIndex r w.val + < S.portIndex r (f i).val} + let cast (j : Fin i.val) := Fin.castLE i.isLt.le j + let g (j : Fin i.val) : A := + ⟨f (cast j), (here _).trans (here i).symm, (dir _).trans (dir i).symm, mono (show cast j + < i from j.isLt)⟩ + have bij : Function.Bijective g := by + constructor + · intro a b he + have e : f (cast a) = f (cast b) := congrArg Subtype.val he + have eq : cast a = cast b := by apply mono.injective; dsimp only; rw [e] + exact Fin.ext (congrArg (fun i : Fin n => i.val) eq) + · rintro ⟨w, hv, hd, ht⟩ + obtain ⟨j, rfl⟩ := onto w (hv.trans (here i)) (hd.trans (dir i)) + have lt : j < i := mono.lt_iff_lt.mp ht + exact ⟨⟨j.val, lt⟩, Subtype.ext rfl⟩ + exact (Fintype.card_fin _).symm.trans ((Fintype.card_congr (Equiv.ofBijective g bij)).trans + (S.skip_eq_card r (f i))) + +open scoped Classical in +private theorem exterior_skip {B : Type} (v : (H).V) (d : Bool) + (push : B → slots x ⊕ slots y) (rows : List B) + (side : ∀ b, (push b).isRight = d) + (onto : ∀ c, c.isRight = d → ∃ b, push b = c) + (mem : ∀ b, b ∈ rows ↔ portEnd (H) (push b) = v) + (incr : rows.Pairwise (fun a b => S.portIndex r ((q).boundary (push a)).val < + S.portIndex r ((q).boundary (push b)).val)) (i : Fin rows.length) : + let e := ((q).boundary (push (rows.get i))).val + e.1.1 = p.vertex v ∧ S.direction r e.1 = d ∧ i.val = S.skip r e.1 + e.2.val := by + let f (j : Fin rows.length) := (q).boundary (push (rows.get j)) + have here (j : Fin rows.length) : (f j).val.1.1 = (q).vertex v := by + unfold f + rw [boundary_place, (mem _).mp (rows.get_mem j)] + have dir (j : Fin rows.length) : S.direction r (f j).val.1 = d := + (p.boundary_side h _).trans (side _) + have mono : StrictMono (fun j => S.portIndex r (f j).val) := + fun _ _ h => (List.pairwise_iff_get.mp incr) _ _ h + refine ⟨here i, dir i, rank_index f _ _ here dir ?_ mono i⟩ + intro w hv hd + obtain ⟨c, rfl⟩ := (q).boundary.surjective w + obtain ⟨b, rfl⟩ := onto c ((p.boundary_side h c).symm.trans hd) + have hb : b ∈ rows := (mem b).mpr ((q).vertex.injective ((boundary_place (q) _).symm.trans hv)) + obtain ⟨j, rfl⟩ := List.get_of_mem hb + exact ⟨j, rfl⟩ + +open scoped Classical in +theorem skipLeft (v : (H).V) (i : Fin ((H).extLeft v).length) : + let e := ((q).boundary (.inl (((H).extLeft v).get i))).val + e.1.1 = p.vertex v ∧ S.direction r e.1 = false ∧ i.val = S.skip r e.1 + e.2.val := by + refine p.exterior_skip h v false Sum.inl _ (fun _ => rfl) ?_ ((H).mem_extLeft v) ?_ i + · rintro (a|b) <;> simp + · apply p.exterior_increasing h v false Diagram.pickLeft (fun a => .inl (.inl a)) _ (fun _ => rfl) + rintro ((a|e)|(b|e)) t <;> simp [Diagram.endWire, Diagram.pickLeft] + +open scoped Classical in +theorem skipRight (v : (H).V) (i : Fin ((H).extRight v).length) : + let e := ((q).boundary (.inr (((H).extRight v).get i))).val + e.1.1 = p.vertex v ∧ S.direction r e.1 = true ∧ i.val = S.skip r e.1 + e.2.val := by + refine p.exterior_skip h v true Sum.inr _ (fun _ => rfl) ?_ ((H).mem_extRight v) ?_ i + · rintro (a|b) <;> simp + · apply p.exterior_increasing h v true Diagram.pickRight (fun a => .inr (.inl a)) _ (fun _ => rfl) + rintro ((a|e)|(b|e)) t <;> simp [Diagram.endWire, Diagram.pickRight] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation +end + +/- # Reading internal packet counts and exterior lengths from a station's spans -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Assembly Coloring Finset + +open scoped Classical in +theorem Assembly.Scheme.exteriorRead {F : Type} (S : Scheme F) (l : B S.ℓ) (i : B S.k) (b : Bool) : + S.extWidth l (some i) b = ∑ j : B S.e, + if (S.decode l).peer i j = none ∧ (S.decode l).direction i j + = b then (S.decode l).width i j else 0 := by + simp only [Scheme.extWidth, Option.elim_some, Fintype.card_subtype, card_filter, + Fintype.sum_sigma] + refine sum_congr rfl fun j _ => ?_ + by_cases h : (S.decode l).peer i j = none ∧ (S.decode l).direction i j = b <;> simp [h] + +namespace Rounds.Input +variable {F : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} + +open scoped Classical in +private theorem incident_bits (P : Input F x y h D T r g W) (v : P.diagram.V) : + r * (P.grid.uses v).card = (∑ e, if P.diagram.source e = v then 1 else 0) + + ∑ e, if P.diagram.target e = v then 1 else 0 := by + let hit (p : P.Edges × Fin r) := if P.grid.src p.1 = v ∨ P.grid.dst p.1 = v then 1 else 0 + have count : r * (P.grid.uses v).card = ∑ p, hit p := by + rw [Fintype.sum_prod_type, Sphere.Grid.uses, card_filter, mul_sum] + refine sum_congr rfl fun e _ => ?_ + by_cases h : P.grid.src e = v ∨ P.grid.dst e = v <;> simp [hit, h] + rw [count, ← P.packets.bits.sum_comp, ← sum_add_distrib] + refine sum_congr rfl fun e _ => ?_ + simp only [hit, grid, P.packets.left, P.packets.right] + by_cases he : P.diagram.source e = v + · have ht : P.diagram.target e ≠ v := fun hh => P.loopless e (he.trans hh.symm) + simp [he, ht] + · simp [he] + +variable [Field F] {S : Scheme F} {row : S.format.obj} (P : Input F x y S.h D T r g W) + (pres : S.Presentation row P.diagram) +local notation "G" => P.diagram + +open scoped Classical in +/-- Counting both ends is valid because packets in an input have distinct endpoints. -/ +theorem packetRead (v : (G).V) : + r * (P.grid.uses v).card = ∑ j : B S.e, + if ((S.pattern row (pres.vertex v)).peer (pres.vertex v).2.2 j).isSome + then S.width row (pres.vertex v, j) else 0 := by + let f (i : (G).End) := if (G).station i = v ∧ (S.peer row (pres.toSeating.ends i).1).isSome then + 1 else 0 + have hin (e : (G).E) : (S.peer row (pres.toSeating.ends (.inl (.inr e))).1).isSome := by + rw [(pres.internal e).1]; rfl + have hout (e : (G).E) : (S.peer row (pres.toSeating.ends (.inr (.inr e))).1).isSome := by + rw [(pres.proper _ _ (pres.internal e).1).1]; rfl + have ht : r * (P.grid.uses v).card = ∑ i, f i := by + rw [incident_bits] + simp only [Diagram.End, Fintype.sum_sum_type, f, pres.input, pres.output, hin, hout, + Option.isSome_none, Bool.false_eq_true, and_false, and_true, ↓reduceIte, sum_const_zero, + zero_add] + rfl + rw [ht, ← (G).portEquiv.sum_comp, Fintype.sum_sigma, Fintype.sum_eq_single v] + · let c (t : S.LocalPin row (pres.vertex v)) := if (S.peer row (pres.vertex v, + t.1)).isSome then 1 else 0 + have hc (t : (G).Port v) : f ((G).portEquiv ⟨v, t⟩) = c (pres.pin v t) := by + simp only [f, Diagram.station_port, true_and, pres.toSeating.ends_at] + rfl + simp only [hc] + rw [(pres.pin v).sum_comp c, Fintype.sum_sigma] + refine sum_congr rfl fun j _ => ?_ + cases hp : (S.pattern row (pres.vertex v)).peer (pres.vertex v).2.2 j <;> + simp [c, Scheme.peer, hp] + · intro u hu + exact sum_eq_zero fun t _ => by simp [f, Diagram.station_port, hu] + +end Rounds.Input +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- +# Recovering the number of padded bits from an unpadded record + +Sum lengths by direction and remote address. The padding rule assigns +the shortfall in each nonempty group to exactly one of its spans. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly +open Coloring Finset + +namespace Pattern +variable {F : Type} {d k e : ℕ} (A : Pattern F d k e) (i : B k) +local notation "Group" => Bool × B d × B k + +open scoped Classical in +/-- The value specified by `∑ j, if A.target i j = some b.2 ∧ A.direction i j = b.1 then A.width +i j else 0`. -/ +def total (b : Group) := ∑ j, if A.target i j = some b.2 ∧ A.direction i j + = b.1 then A.width i j else 0 + +open scoped Classical in +private abbrev hit (b : Group) (j : B e) := A.target i j = some b.2 ∧ A.direction i j = b.1 + +open scoped Classical in +private theorem slice_total {b : Group} {j : B e} (h : A.hit i b j) : + Fintype.card (A.Slice i j) = A.total i b := by + simp only [Slice, Fintype.card_subtype, card_filter, Fintype.sum_sigma, total, h.1, h.2] + refine sum_congr rfl fun s _ => ?_ + by_cases hs : A.target i s = some b.2 ∧ A.direction i s = b.1 <;> simp [hs] + +open scoped Classical in +private def groupMarks (b : Group) := + (univ.filter fun s => 0 < A.width i s ∧ A.hit i b s).image (A.mark i) + +open scoped Classical in +private theorem marks_eq {b : Group} {j : B e} (h : A.hit i b j) : + A.marks i j = A.groupMarks i b := by + ext a + simp only [marks, groupMarks, mem_image, mem_univ, mem_filter, true_and] + constructor + · rintro ⟨⟨⟨s, n⟩, ht, hd⟩, he⟩ + exact ⟨s, ⟨n.pos, ht.trans h.1, hd.trans h.2⟩, he⟩ + · rintro ⟨s, ⟨hs, ht, hd⟩, he⟩ + exact ⟨⟨⟨s, ⟨0, hs⟩⟩, ht.trans h.1.symm, hd.trans h.2.symm⟩, he⟩ + +open scoped Classical in +private theorem mark_unique {s t : B e} (hd : A.direction i s = A.direction i t) + (hm : A.mark i s = A.mark i t) : s = t := by + unfold mark at hm + rw [hd] at hm + split_ifs at hm + · exact congrArg Prod.snd hm + · exact congrArg Prod.fst hm + +open scoped Classical in +private theorem extra_total (R : ℕ) (b : Group) : + (∑ j, if A.hit i b j then A.extra i j R else 0) + = Diagram.padWidth R (A.total i b) - A.total i b := by + by_cases hb : (A.groupMarks i b).Nonempty + · have hp : pick (A.groupMarks i b) ∈ A.groupMarks i b + := by rw [pick, dite_eq_left hb]; exact hb.choose_spec + obtain ⟨j, hj, he⟩ := mem_image.mp hp + obtain ⟨hw, hj⟩ := (mem_filter.mp hj).2 + rw [Fintype.sum_eq_single j] + · rw [ite_eq_left hj, extra, marks_eq A i hj, ite_eq_left ⟨hw, + by rw [hj.1]; rfl, he⟩, slice_total A i hj] + · intro s hs + by_cases ht : A.hit i b s + · have hn : A.mark i s ≠ pick (A.marks i s) := by + rw [marks_eq A i ht, ← he] + exact fun hu => hs (mark_unique A i (ht.2.trans hj.2.symm) hu) + simp [ht, extra, hn] + · exact ite_eq_right ht + · have zero {s} (hs : A.hit i b s) : A.width i s = 0 := Nat.eq_zero_of_not_pos fun hw => + hb ⟨_, mem_image_of_mem (A.mark i) (mem_filter.mpr ⟨mem_univ s, hw, hs⟩)⟩ + have ht : A.total i b = 0 := by + unfold total + exact sum_eq_zero fun j _ => by + split_ifs with hj + · exact zero hj + · rfl + rw [ht, Diagram.padWidth_zero, Nat.sub_self] + refine sum_eq_zero fun j _ => ?_ + split_ifs with hj + · simp [extra, zero hj] + · rfl + +open scoped Classical in +private theorem regroup (f : B e → ℕ) : + (∑ j, if (A.peer i j).isSome then f j else 0) = ∑ b : Group, ∑ j, + if A.hit i b j then f j else 0 := by + rw [sum_comm] + refine sum_congr rfl fun j _ => ?_ + cases ht : A.peer i j with + | none => simp [hit, target, ht] + | some p => + let b : Group := (A.direction i j, p.1, p.2.1) + have hb : A.hit i b j := by simp [hit, target, ht, b] + rw [Fintype.sum_eq_single b] + · rw [ite_eq_left hb]; rfl + · intro c hc + exact ite_eq_right fun he => hc (Prod.ext he.2.symm (Option.some.inj (he.1.symm.trans hb.1))) + +variable [Zero F] + +open scoped Classical in +private theorem expanded (R : ℕ) : + (∑ j, if ((A.padded R).peer i j).isSome then (A.padded R).width i j else 0) = + ∑ j, if (A.peer i j).isSome then A.width i j + A.extra i j R else 0 := by + rw [← (tag e).sum_comp, Fintype.sum_prod_type, sum_comm] + refine sum_congr rfl fun j _ => ?_ + rw [Fintype.sum_bool] + cases hp : A.peer i j <;> simp [padded, length, hp, add_comm] + +open scoped Classical in +/-- The padded internal volume is determined by the original directed group totals. -/ +theorem packetCount (A : Pattern F d k e) (R : ℕ) (i : B k) : + (∑ j, if ((A.padded R).peer i j).isSome then (A.padded R).width i j else 0) = + ∑ b : Group, Diagram.padWidth R (A.total i b) := by + rw [expanded, regroup] + refine sum_congr rfl fun b _ => ?_ + calc + _ = A.total i b + ∑ j, if A.hit i b j then A.extra i j R else 0 := by + rw [total, ← sum_add_distrib] + refine sum_congr rfl fun j _ => ?_ + by_cases h : A.hit i b j <;> simp only [h, hit, and_self, ↓reduceIte, add_zero] + _ = _ := by rw [extra_total, Nat.add_sub_of_le (Diagram.le_padWidth R _)] + +open scoped Classical in +private theorem exterior (R : ℕ) (b : Bool) : + (∑ j, if (A.padded R).peer i j = none ∧ (A.padded R).direction i j = b + then (A.padded R).width i j else 0) = + ∑ j, if A.peer i j = none ∧ A.direction i j = b then A.width i j else 0 := by + rw [← (tag e).sum_comp, Fintype.sum_prod_type, sum_comm] + refine sum_congr rfl fun j _ => ?_ + rw [Fintype.sum_bool] + cases hp : A.peer i j <;> simp [padded, length, extra, target, hp] + +end Pattern + +open scoped Classical in +theorem Scheme.padded_extWidth {F : Type} [Field F] (S : Scheme F) (R : ℕ) (l : B S.ℓ) + (i : Option (B S.k)) (b : Bool) : (S.padded R).extWidth l i b = S.extWidth l i b := by + cases i with + | none => rfl + | some i => + rw [Scheme.exteriorRead, Scheme.exteriorRead] + exact (S.decode l).exterior i R b + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly +end + +/- # Computing the bounded local view of a grouped host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Boot +open Coloring Neighborhood +variable {F : Type} [Field F] {I : Type*} {u m d h r s e k v n : ℕ} {L : Set (Table F)} + +local notation "P" => source m d h e k +local notation "A" => own d r s e k +local notation "O" => Fmt.rows m d h A +local notation "Q" => query d r s e k +local notation "Y" => Fmt.rows m d h Q + +private theorem map_colored (hu : 3 ≤ u) (hr : 0 < r) (hs : 0 < s) : + Map F u L P O (colored r s) (paintCost m d r + paintCost m d s + 100 * (O).width) := by + let X := (P).pair ((Neighborhood.Rows m d).pair (Neighborhood.Rows m d)) + let Z := (P).pair ((Colors m ((d + 1) * r)).pair (Colors m ((d + 1) * s))) + let start : (P).obj → X.obj := fun z => (z, fun i => (z.1 i).1, fun i => (z.1 i).1) + let pin : X.pins → (P).pins + | .inl j => j + | .inr (.inl (i, j)) => .inl (i, .inl j) + | .inr (.inr (i, j)) => .inl (i, .inl j) + have pre : Circuit F P X start ((P).width + 2 * X.width) := + Circuit.project pin (by rintro x (j|⟨i, j⟩|⟨i, j⟩) <;> rfl) + let finish : Z.obj → (O).obj := fun z i => + ((z.1.1 i).1, fun j => ((z.1.1 i).2 j, z.2.1 i, z.2.2 i, z.1.2 i j)) + let out : (O).pins → Z.pins + | (i, .inl j) => .inl (.inl (i, .inl j)) + | (i, .inr (j, .inl k)) => .inl (.inl (i, .inr (j, k))) + | (i, .inr (_, .inr (.inl k))) => .inr (.inl (i, k)) + | (i, .inr (_, .inr (.inr (.inl k)))) => .inr (.inr (i, k)) + | (i, .inr (j, .inr (.inr (.inr k)))) => .inl (.inr (i, j, k)) + have post : Circuit F Z O finish (Z.width + 2 * (O).width) := + Circuit.project out (by rintro x ⟨i, j|⟨j, k|k|k|k⟩⟩ <;> rfl) + have pair := (paint (L := L) m d r hr hu).par (paint m d s hs hu) + have mid := (Map.circuit hu (Circuit.id F P)).par pair + have comp := ((Map.circuit hu pre).comp mid).comp (Map.circuit hu post) + have hw : (P).width ≤ (O).width := by + simp only [source, Fmt.rows, selectors, own, Format.width_pair, Format.width_vec, mul_add] + omega + have hx : X.width ≤ 3 * (O).width := by + simp only [X, Format.width_pair] at hw ⊢ + have hp : (Neighborhood.Rows m d).width ≤ (O).width := by + simp only [Neighborhood.Rows, Fmt.rows, Format.width_vec, Format.width_pair, mul_add]; omega + omega + have hz : Z.width ≤ 3 * (O).width := by + have w (q : ℕ) : (Colors m q).width ≤ (Format.vec m (.vec h (.addr (q + 1)))).width := by + simp only [Colors, Format.width_vec] + exact Nat.mul_le_mul_left _ (Nat.le_mul_of_pos_left _ (by positivity)) + have h₁ := w ((d + 1) * r) + have h₂ := w ((d + 1) * s) + simp only [Z, Fmt.rows, own, Format.width_pair, Format.width_vec, mul_add] at * + omega + exact comp.mono (by omega) + +private theorem computes_around (hu : 3 ≤ u) (hr : 0 < r) (hs : 0 < s) + (ht : Access F u L (m + d) v n) (hv : 2 ^ h * (A).width ≤ v) + (z : I → (P).obj) (sym : ∀ i, Fmt.Reciprocal (.vec h (.addr e)) (z i).1) : + Computes F u L P Y z (around r s ∘ z) (fun _ => 1) + (paintCost m d r + paintCost m d s + gatherCost m d v n + 200 * (Y).width) := by + let G := Format.vec h A + let V := Format.vec m (.vec d G) + let X := (O).pair V + let y := colored r s ∘ z + have pre := Computes.of_map (x := z) (y := y) (map_colored (L := L) hu hr hs) (fun _ => rfl) + have get := gather_neighbors G hu ht ((Format.width_vec _ _).le.trans hv) y (fun i => sym i) + have stay := Computes.of_map (x := y) (Map.circuit (L := L) hu (Circuit.id F O)) (fun _ => rfl) + have mid := pre.comp (Computes.pair hu stay get) + let f : X.obj → (Y).obj := fun x i => ((x.1 i).1, fun j => ((x.1 i).2 j, fun l => x.2 i l j)) + let pin : (Y).pins → X.pins + | (i, .inl j) => .inl (i, .inl j) + | (i, .inr (j, .inl k)) => .inl (i, .inr (j, k)) + | (i, .inr (j, .inr (l, k))) => .inr (i, l, j, k) + have hp : Circuit F X Y f (X.width + 2 * (Y).width) := + Circuit.project pin (by rintro x ⟨i, j|⟨j, k|⟨l, k⟩⟩⟩ <;> rfl) + have all := mid.comp (Computes.of_map (y := around r s ∘ z) (Map.circuit hu hp) (fun _ => rfl)) + simp only [mul_one] at all + have hw : X.width = (Y).width := by + simp only [X, V, G, Fmt.rows, query, Format.width_pair, Format.width_vec] + ring + have hw' : (O).width ≤ X.width := by simp only [X, Format.width_pair]; omega + exact all.mono (by omega) + +/-- Include room for contracting the selectors and keeping the exterior +payload. The host address is exchanged only once per neighbor. -/ +theorem computes (hu : 3 ≤ u) (hr : 0 < r) (hs : 0 < s) + (ht : Access F u L (m + d) v n) (hv : 2 ^ h * (A).width ≤ v) + (z : I → (P).obj) (sym : ∀ i, Fmt.Reciprocal (.vec h (.addr e)) (z i).1) + (f : (Q).obj → (Format.addr (Q).width).obj) (w : (Q).obj → F) + (hw : 2 * (Q).width ≤ u) (hg : weightTable f w ∈ L) (Z : Format) : + ∃ a, Computes F u L P (Fmt.rows m d h (.addr (Q).width)) + z (Fmt.update f ∘ around r s ∘ z) (Fmt.weight w ∘ around r s ∘ z) a ∧ + a + 4 * (selectors m h k).width + 4 * Z.width ≤ cost m d h r s e k v n Z := by + have he := computes_around hu hr hs ht hv z sym + have width : (Q).width + (Format.addr (Q).width).width ≤ u := by + rwa [Format.width_addr, ← two_mul] + have call := computes_update f w hu width hg (around r s ∘ z) + have hh := he.comp call + simp only [one_mul] at hh + refine ⟨_, hh, ?_⟩ + have hk : k + 1 ≤ (Q).width := by + simp only [query, own, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_addr] + omega + have hk' := Nat.mul_le_mul_left (2 ^ m) (Nat.mul_le_mul_left (2 ^ h) hk) + simp only [cost, updateCost, Fmt.rows, selectors, Format.width_pair, Format.width_vec, + Format.width_addr, + mul_add, mul_one] at hk' ⊢ + rw [mul_left_comm (2 ^ m) 4] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Boot +end + +/- # From a grouped layer to the first wave -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Routing.Private Sphere.Surface.Local SphereScale +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {a D T b d ℓ p l : ℕ} {θ L : ℝ} + (P : Layer F x y) (B : P.template.Binning a D T (d * b) θ) + (t : ∀ i, B.Trial (P.presents i) L) + (sc : Scales ((4 * 5) ^ 300) ℓ D T (p ^ l) b d) + (hK : SphereScale.Ready K ℓ D ((4 * 5) ^ 300) + (p ^ l) b d) + {k u v n : ℕ} {labels : Set (Table F)} + +open scoped Classical in +private theorem selector_sum {I : Type} [Fintype I] {A C Z : Format} [Fintype C.obj] + (sel : Transcript.Selector I C.obj) (z : Z.obj) (fn : C.obj → A.obj → F) + (out : C.obj → A.obj) (weight : C.obj → F) + (he : ∀ c v, fn c v = if out c = v then weight c else 0) + (hw : ∀ c, weight c = (sel.read c).elim 0 (fun _ => 1)) (u : (A.pair Z).obj) : + (∑ c, fn c u.1) * (if z = u.2 then 1 else 0) = + ∑ i, @ite F ((out (sel.write i), z) = u) (Classical.propDecidable _) 1 0 := by + obtain ⟨q, w⟩ := u + have term (c : C.obj) : fn c q = + (sel.read c).elim 0 (fun i => if out (sel.write i) = q then 1 else 0) := by + rw [he, hw] + cases h : sel.read c with + | none => simp + | some i => rw [(sel.valid c i).mp h]; rfl + simp only [term, Transcript.Selector.sum, Prod.mk.injEq] + by_cases h : z = w <;> simp [h] + +section Kernel +variable {g : ℕ} (S : Scheme F) (sc' : Scales g ℓ D T (p ^ l) b d) (Z : Format) +local notation "Cfg" => Input.design S g ℓ D b d p l +local notation "R" => panelRadius D +local notation "Q" => horizon (D ^ 5) (Design.waves Cfg) 0 +local notation "Query" => Input.panelQuery S g ℓ D b d p l k +local notation "Out" => Design.port Cfg (Format.width Query) + +open scoped Classical in +private theorem panel_kernel {J : Type*} (inp : J → S.format.obj) + (recip : ∀ j, Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) (inp j)) + (choices : J → Type) [∀ i, Fintype (choices i)] + (sel : ∀ i, Transcript.Selector (choices i) (Boot.selectors S.m S.h k).obj) + (valid : ∀ i c, Fmt.weight (Input.panelGuard S sc' k) (Input.panelAround S sc' (inp i) c) = + ((sel i).read c).elim 0 (fun _ => 1)) + (hu : 3 ≤ u) (ht : Access F u labels (S.m + S.d) v n) + (hv : 2 ^ S.h * (Boot.own S.d R Q S.ℓ k).width ≤ v) + (hw : 2 * (Query).width ≤ u) (hg : Input.panelTable S sc' k ∈ labels) : + ∃ f, Kernel F u labels (S.format.pair Z) ((Out).pair Z) f + (Boot.cost S.m S.d S.h R Q S.ℓ k v n Z) ∧ + ∀ i w q, f (inp i, w) q = ∑ j, @ite F ((Input.panelTape S sc' (inp i) ((sel i).write j), w) + = q) + (Classical.propDecidable _) 1 0 := by + let C := Boot.selectors S.m S.h k + let z : J × C.obj → (Boot.source S.m S.d S.h S.ℓ k).obj := fun i => (inp i.1, i.2) + have hr : 0 < R := Nat.succ_pos _ + have hs : 0 < Q := Nat.succ_pos _ + obtain ⟨_, ⟨f, hf, he⟩, hc⟩ := Boot.computes hu hr hs ht hv z + (fun i => recip i.1) (Design.number Query) (Input.panelGuard S sc' k) hw hg Z + let _ := Fintype.ofFinite C.obj + have ker := (Kernel.sum_hidden (C := C) hu hf).par (Map.circuit hu (Circuit.id F Z)) + refine ⟨_, ker.mono hc, fun i w q => ?_⟩ + exact selector_sum (A := Out) (Z := Z) (C := C) (sel i) + w (fun c => f (z (i, c))) (Input.panelTape S sc' (inp i)) + (fun c => Fmt.weight (Input.panelGuard S sc' k) (Input.panelAround S sc' (inp i) c)) + (fun c v => he (i, c) v) (valid i) q + +end Kernel + +local notation "S" => B.target +local notation "Cfg" => Input.design S ((4 * 5) ^ 300) ℓ D b d p l +local notation "R" => panelRadius D +local notation "Q" => horizon (D ^ 5) (Design.waves Cfg) 0 +local notation "Query" => Input.panelQuery S ((4 * 5) ^ 300) ℓ D b d p l k +local notation "Z" => P.panelPort B + +open scoped Classical in +/-- One exact expansion for all states of a grouped layer, without +inspecting or rearranging their exterior payload. -/ +theorem installPanel (hk : initialChoices ℓ D b d ≤ 2 ^ k) (hu : 3 ≤ u) + (ht : Access F u labels ((S).m + (S).d) v n) (hv : 2 ^ (S).h * (Boot.own (S).d R Q (S).ℓ + k).width ≤ v) + (hw : 2 * (Query).width ≤ u) (hg : Input.panelTable S sc k ∈ labels) : + Transforms F u labels (P.masked B t R) + (Sphere.Surface.Local.snapshot (P.panelWorld B t sc hK) Z (P.panelPayload B t) 0 + (Input.panelMenu S hK k)) + (Boot.cost (S).m (S).d (S).h R Q (S).ℓ k v n Z) := by + have hr : 2 ≤ R := Nat.le_add_left _ _ + let choices (i : P.State) := ((t i).normal R).Occupied → Shape (probes ℓ D) b d + let sel (i : P.State) := ((t i).normal R).panelSelector ((t i).atlas R) hk + obtain ⟨f, hf, he⟩ := panel_kernel S sc Z (fun i => B.data (P.data i)) + (fun i => ((t i).atlas R).reciprocal) choices sel + (fun i c => ((t i).normal R).panelWeight ((t i).atlas R) sc ((t i).placed R) hk c) + hu ht hv hw hg + refine ⟨f, hf, fun i => ?_⟩ + let I := (t i).normal R + let H := (t i).atlas R + let next (s : I.Occupied → Shape (probes ℓ D) b d) := + I.panelCode H sc hK s ((t i).placed R) ((t i).ranks R hr) hk + refine ⟨_, inferInstance, fun s => ⟨⟨i, s⟩, next s⟩, fun _ => 1, ?_, ?_⟩ + · intro z w + simp only [one_mul] + exact I.start_sum H sc hK z w + · intro r w q + refine (he i ((P.masked B t R).encode i r w).2 q).trans ?_ + refine Finset.sum_congr rfl fun s _ => ?_ + simp only [Sphere.Surface.Local.snapshot, panelPayload, next, Input.panelCode] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Pattern.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Pattern.lean new file mode 100644 index 0000000000..4f083f3034 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Pattern.lean @@ -0,0 +1,948 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Ledger +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Owners +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Initial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.View + +/-! +# Ordering initial data by local keys + +Station numbers only need to distinguish one occupied cell, and host +numbers one closed neighborhood. A packet is then identified by its +two endpoint keys and its quotient index in the parallel bundle. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Packing +variable {F : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} + (P : Input F x y h D T r g W) + +open scoped Classical in +/-- The data for the local ranks construction, including `supplied`, `stations`, `hosts`. -/ +structure LocalRanks : Prop where + supplied : P.ranks.isSome + stations : ∀ a b, P.place a = P.place b → P.stationRank a = P.stationRank b → a = b + hosts : ∀ u, Set.InjOn P.hostRank (insert u (P.adj u) : Finset P.V) + +open scoped Classical in +/-- The value specified by `(P.place v).2 = c.val.2 ∧ (P.place v).1 ∈ insert c.val.1 (P.adj +c.val.1)`. -/ +def atHost (c : P.Occupied) (v : P.diagram.V) := + (P.place v).2 = c.val.2 ∧ (P.place v).1 ∈ insert c.val.1 (P.adj c.val.1) + +open scoped Classical in +/-- The value specified by `P.grid.cell (P.grid.src e) = c ∨ P.grid.cell (P.grid.dst e) = c`. -/ +def incidentPacket (c : P.Occupied) (e : P.Edges) := + P.grid.cell (P.grid.src e) = c ∨ P.grid.cell (P.grid.dst e) = c + +open scoped Classical in +theorem endpoints_atHost (hr : 0 < r) (c : P.Occupied) (e : P.Edges) (he : P.incidentPacket c e) : + P.atHost c (P.grid.src e) ∧ P.atHost c (P.grid.dst e) := by + obtain ⟨block, edge⟩ := P.contact hr e + rcases he with h|h + · have h' : P.place (P.grid.src e) = c.val := congrArg Subtype.val h + rw [h'] at edge block + simp only [atHost, h', mem_insert] + exact ⟨⟨True.intro, .inl True.intro⟩, block, edge⟩ + · have h' : P.place (P.grid.dst e) = c.val := congrArg Subtype.val h + rw [h'] at edge block + simp only [atHost, h', mem_insert] + exact ⟨⟨block.symm, edge.imp Eq.symm (P.sym _ _)⟩, True.intro, .inl True.intro⟩ + +variable {P} + +open scoped Classical in +theorem LocalRanks.node (H : P.LocalRanks) {c : P.Occupied} {a b : P.diagram.V} + (ha : P.atHost c a) (hb : P.atHost c b) (he : P.nodeRank a = P.nodeRank b) : a = b := by + obtain ⟨h₁, h₂⟩ := Nat.pair_eq_pair.mp he + exact H.stations a b (Prod.ext (H.hosts _ ha.2 hb.2 h₁) (ha.1.trans hb.1.symm)) h₂ + +open scoped Classical in +theorem LocalRanks.station (H : P.LocalRanks) (c : P.Occupied) : + Set.InjOn P.grid.stationRank (P.grid.stations c) := by + intro a ha b hb h + simp only [Grid.stations, mem_coe, mem_filter, mem_univ, true_and] at ha hb + exact H.stations a b (congrArg Subtype.val (ha.trans hb.symm)) h + +variable (P) + +open scoped Classical in +private def first (hr : 0 < r) (e : P.Edges) := P.packets.bits.symm (e, ⟨0, hr⟩) + +open scoped Classical in +private theorem first_eq (hr : 0 < r) (e : P.Edges) : (P.packets.bits (P.first hr e)).1 = e := + congrArg Prod.fst (P.packets.bits.apply_symm_apply _) + +open scoped Classical in +theorem packetRank_eq (hr : 0 < r) (hs : P.ranks.isSome) (e : P.diagram.E) : + P.packetRank (P.packets.bits e).1 = Nat.pair (P.nodeRank (P.diagram.source e)) + (Nat.pair (P.nodeRank (P.diagram.target e)) (ordinal P.diagram e / r)) := by + let u := P.first hr (P.packets.bits e).1 + have hp : (P.packets.bits u).1 = (P.packets.bits e).1 := P.first_eq hr _ + have h₁ : P.diagram.source u = P.diagram.source e := by rw [← P.packets.left, hp, P.packets.left] + have h₂ : P.diagram.target u = P.diagram.target e + := by rw [← P.packets.right, hp, P.packets.right] + have he := (P.packets_numbered.2 u e h₁ h₂).mp hp + unfold packetRank + rw [dite_eq_left (And.intro hs hr)] + dsimp only + rw [P.packets.left, P.packets.right, ← he] + rfl + +variable {P} + +open scoped Classical in +theorem LocalRanks.packet (H : P.LocalRanks) (hr : 0 < r) (c : P.Occupied) : + Set.InjOn P.grid.packetRank {e | P.incidentPacket c e} := by + intro i hi j hj he + obtain ⟨a, b⟩ := P.endpoints_atHost hr c i hi + obtain ⟨a', b'⟩ := P.endpoints_atHost hr c j hj + change P.packetRank i = P.packetRank j at he + unfold packetRank at he + simp only [dite_eq_left (And.intro H.supplied hr), Nat.pair_eq_pair] at he + have hs := H.node a a' he.1 + have ht := H.node b b' he.2.1 + let u := P.first hr i + let v := P.first hr j + have h₁ : P.diagram.source u = P.diagram.source v := by + rw [← P.packets.left u, ← P.packets.left v, P.first_eq, P.first_eq] + exact hs + have h₂ : P.diagram.target u = P.diagram.target v := by + rw [← P.packets.right u, ← P.packets.right v, P.first_eq, P.first_eq] + exact ht + have hh := (P.packets_numbered.2 u v h₁ h₂).mpr he.2.2 + simpa only [u, v, first_eq] using hh + +open scoped Classical in +theorem LocalRanks.mark (H : P.LocalRanks) (hr : 0 < r) (c : P.Occupied) (i : P.grid.Index c) : + Set.InjOn P.grid.packetRank (P.grid.mark c i) := + (H.packet hr c).mono (fun _ h => P.grid.touches c i h) + +open scoped Classical in +theorem LocalRanks.seam (H : P.LocalRanks) (hr : 0 < r) (c : P.Occupied) : + Set.InjOn P.grid.seamRank (P.grid.ports c) := by + let next (v : P.Occupied) := v.val.2 = c.val.2 ∧ v.val.1 ∈ insert c.val.1 (P.adj c.val.1) + have eq {u v : P.Occupied} (hu : next u) (hv : next v) (h : P.grid.cellRank u + = P.grid.cellRank v) : + u = v := Subtype.ext (Prod.ext (H.hosts _ hu.2 hv.2 h) (hu.1.trans hv.1.symm)) + have inside (i : P.grid.Seam) (hi : i ∈ P.grid.ports c) : next i.val.1 ∧ next i.val.2 := by + obtain ⟨e, he, he'⟩ := i.property.2 + simp only [Grid.ports, mem_filter, mem_univ, true_and, ← he, ← he'] at hi + rw [← he, ← he'] + exact P.endpoints_atHost hr c e hi + intro i hi j hj e + obtain ⟨a, b⟩ := inside i hi + obtain ⟨a', b'⟩ := inside j hj + obtain ⟨e, e'⟩ := Nat.pair_eq_pair.mp e + exact Subtype.ext (Prod.ext (eq a a' e) (eq b b' e')) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +open Finset +open scoped Classical in +theorem number_idxOf {A : Type} {s : Finset A} {f : A → ℕ} (hf : Set.InjOn f s) (x : s) : + ((number f s).symm x).val = ((s.image f).sort (· ≤ ·)).idxOf (f x.val) := by + let g i := f (number f s i).val + have h : (List.ofFn g).Nodup := by rw [number_keys hf]; exact Finset.sort_nodup _ _ + have h' := h.idxOf_getElem ((number f s).symm x).val + (by simp : ((number f s).symm x).val < (List.ofFn g).length) + simp only [List.getElem_ofFn] at h' + rw [← number_keys hf] + simpa [g] using h'.symm + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Grid +end + +/- # Reading a parallel bundle using only its endpoint keys and offsets -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Packing + +open scoped Classical in +/-- Indexes the peer by the coordinates of `Bool × Option (ℕ × ℕ)`. -/ +abbrev Peer := Bool × Option (ℕ × ℕ) +open scoped Classical in +/-- Indexes the line by the coordinates of `(ℕ × ℕ) × ℕ`. -/ +abbrev Line := (ℕ × ℕ) × ℕ + +open scoped Classical in +/-- Transforms the indexed data by `p.2.map fun t => if p.1 then ((t.1, v), t.2) else ((v, t.1), +i)`. -/ +def line (v i : ℕ) (p : Peer) : Option Line := + p.2.map fun t => if p.1 then ((t.1, v), t.2) else ((v, t.1), i) + +open scoped Classical in +/-- The data for the station view construction, including `table`, `mobile`, `route`. -/ +structure StationView (F : Type) where + /-- The local table at each indexed position carried by `StationView`, with type `Table F`. -/ + table : Table F + /-- The `StationView` component of type `Bool`. -/ + mobile : Bool + /-- The routing data of type `List Peer`. -/ + route : List Peer + +open scoped Classical in +/-- The value specified by `v.route[i]?.getD (false, none)`. -/ +def StationView.pin {F : Type} (v : StationView F) (i : ℕ) : Peer := + v.route[i]?.getD (false, none) + +open scoped Classical in +/-- The value specified by `Input.line k i (v.pin i)`. -/ +def StationView.line {F : Type} (v : StationView F) (k i : ℕ) := Input.line k i (v.pin i) + +open scoped Classical in +/-- Computes the rank edge by the application `Nat.pair i.1.1 (Nat.pair i.1.2 i.2)`. -/ +def rankEdge (i : Line) := Nat.pair i.1.1 (Nat.pair i.1.2 i.2) + +variable {F : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} (P : Input F x y h D T r g W) + +open scoped Classical in +/-- Builds `StationView F where table` with the specified `table`, `mobile`, `route`. -/ +def inspect (v : P.diagram.V) : StationView F where + table := P.diagram.table v + mobile := decide (P.mobile v) + route := List.ofFn (fun i => ((P.diagram.peer v i).1, + (P.diagram.peer v i).2.map (Prod.map P.nodeRank id))) + +open scoped Classical in +theorem inspect_pin (v : P.diagram.V) (i : Fin (P.diagram.arity v)) : + (P.inspect v).pin i = ((P.diagram.peer v i).1, + (P.diagram.peer v i).2.map (Prod.map P.nodeRank id)) := by + simp [inspect, StationView.pin] + +open scoped Classical in +/-- The value specified by `((P.nodeRank (P.diagram.source e), P.nodeRank (P.diagram.target e)), +P.diagram.srcOffset e)`. -/ +def wireKey (e : P.diagram.E) : Line := + ((P.nodeRank (P.diagram.source e), P.nodeRank (P.diagram.target e)), P.diagram.srcOffset e) + +open scoped Classical in +private theorem at_port (v : P.diagram.V) (j : Transcript.Ports (P.diagram.table v)) : + let G := P.diagram + let i := Transcript.positions (.pair (G.table v).1 (G.table v).2.1) j + (P.inspect v).line (P.nodeRank v) i.val = + (Transcript.wires G v j).elim (fun _ => none) (fun e => some (P.wireKey e)) := by + intro G i + unfold StationView.line + rw [inspect_pin P v i] + have h : G.peer v i = G.portPeer v j := by simp [Diagram.peer, i] + rw [h] + cases j with + | inl j => + cases he : G.src ⟨v, j⟩ with + | inl a => simp [Diagram.portPeer, Transcript.wires, he, line] + | inr e => + have h : G.src.symm (.inr e) = ⟨v, j⟩ := G.src.symm_apply_eq.mpr he.symm + simp only [Diagram.portPeer, Transcript.wires, he, line, Sum.map_inr, Sum.elim_inr, + Option.map_some, + Bool.false_eq_true, ↓reduceIte, id_eq] + unfold wireKey Diagram.source Diagram.srcOffset + rw [h] + rfl + | inr j => + cases he : G.dst ⟨v, j⟩ with + | inl a => simp [Diagram.portPeer, Transcript.wires, he, line] + | inr e => + have h : G.dst.symm (.inr e) = ⟨v, j⟩ := G.dst.symm_apply_eq.mpr he.symm + simp only [Diagram.portPeer, Transcript.wires, he, line, Sum.map_inr, Sum.elim_inr, + Option.map_some, + ↓reduceIte, id_eq] + unfold wireKey Diagram.target + rw [h] + rfl + +open scoped Classical in +theorem inspect_line (v : P.diagram.V) (i : Fin (P.diagram.arity v)) : + (P.inspect v).line (P.nodeRank v) i = + (P.diagram.wireAt v i).elim (fun _ => none) (fun e => some (P.wireKey e)) := by + let a := Transcript.positions (.pair (P.diagram.table v).1 (P.diagram.table v).2.1) + have h := P.at_port v (a.symm i) + dsimp only at h + rw [show Transcript.positions (.pair (P.diagram.table v).1 (P.diagram.table v).2.1) (a.symm i) + = i from a.apply_symm_apply i] at h + exact h + +open scoped Classical in +theorem has_slot (v : P.diagram.V) (e : P.diagram.E) + (he : P.diagram.source e = v ∨ P.diagram.target e = v) : + ∃ i, P.diagram.wireAt v i = .inr e := by + have go (z : P.diagram.End) (h : P.diagram.station z = v) (hz : P.diagram.endWire z = .inr e) : + ∃ i, P.diagram.wireAt v i = .inr e := by + obtain ⟨⟨w, i⟩, hi⟩ := P.diagram.endAt.surjective z + rw [← hi, P.diagram.station_endAt] at h + change w = v at h + subst w + exact ⟨i, by rw [Diagram.wireAt_eq, hi, hz]⟩ + exact he.elim (fun h => go (.inl (.inr e)) h rfl) (fun h => go (.inr (.inr e)) h rfl) + +open scoped Classical in +/-- The condition `∃ i j, a = some i ∧ b = some j ∧ i.1 = j.1 ∧ i.2 < j.2` on the specified +data. -/ +def earlier (a b : Option Line) : Prop := + ∃ i j, a = some i ∧ b = some j ∧ i.1 = j.1 ∧ i.2 < j.2 + +open scoped Classical in +/-- The quantity computed by `wd v.table.1 + wd v.table.2.1`. -/ +def StationView.arity (v : StationView F) := wd v.table.1 + wd v.table.2.1 + +open scoped Classical in +/-- The indexed operation `(univ.filter (fun j : Fin v.arity => earlier (v.line k j.val) (v.line +k i))).card`. -/ +def StationView.ord (v : StationView F) (k i : ℕ) := + (univ.filter (fun j : Fin v.arity => earlier (v.line k j.val) (v.line k i))).card + +open scoped Classical in +theorem inspect_ord (H : P.LocalRanks) (hr : 0 < r) (v : P.diagram.V) (i : Fin (P.diagram.arity v)) + {e : P.diagram.E} (he : P.diagram.wireAt v i = .inr e) : + (P.inspect v).ord (P.nodeRank v) i = ordinal P.diagram e := by + let earlier' (j : Fin (P.diagram.arity v)) := + earlier ((P.inspect v).line (P.nodeRank v) j) ((P.inspect v).line (P.nodeRank v) i) + let before (f : P.diagram.E) := (P.diagram.source f, P.diagram.target f) = + (P.diagram.source e, P.diagram.target e) ∧ P.diagram.srcOffset f < P.diagram.srcOffset e + have inside (t : Fin (P.diagram.arity v)) (f : P.diagram.E) (hf : P.diagram.wireAt v t = .inr f) : + P.atHost (P.grid.cell v) (P.diagram.source f) ∧ P.atHost (P.grid.cell v) (P.diagram.target f) + := by + have h := P.endpoints_atHost hr (P.grid.cell v) (P.packets.bits f).1 + (by simpa [incidentPacket, grid, P.packets.left, P.packets.right] using + (P.diagram.wireAt_incident v t hf).imp (congrArg P.grid.cell) (congrArg P.grid.cell)) + simpa only [grid, P.packets.left, P.packets.right] using h + have iff' (j) : earlier' j ↔ ∃ f, P.diagram.wireAt v j = .inr f ∧ before f := by + unfold earlier' + rw [inspect_line, inspect_line, he] + cases hf : P.diagram.wireAt v j with + | inl _ => simp [earlier] + | inr f => + have h₁ := inside _ _ he + have h₂ := inside _ _ hf + have hk : (P.wireKey f).1 = (P.wireKey e).1 ↔ + (P.diagram.source f, P.diagram.target f) = (P.diagram.source e, P.diagram.target e) := by + constructor + · intro h + exact Prod.ext (H.node h₂.1 h₁.1 (congrArg Prod.fst h)) (H.node h₂.2 h₁.2 (congrArg + Prod.snd h)) + · exact fun h => congrArg (Prod.map P.nodeRank P.nodeRank) h + simp only [earlier, before, Sum.elim_inr, Sum.inr.injEq, Option.some.injEq, + exists_eq_left'] + constructor + · rintro ⟨_, _, rfl, rfl, same, lt⟩ + exact ⟨hk.mp same, lt⟩ + · rintro ⟨same, lt⟩ + exact ⟨_, _, rfl, rfl, hk.mpr same, lt⟩ + change (univ.filter earlier').card = (univ.filter before).card + let f (j) (h : j ∈ univ.filter earlier') := ((iff' j).mp (mem_filter.mp h).2).choose + have spec j h : P.diagram.wireAt v j = .inr (f j h) ∧ before (f j h) := + ((iff' j).mp (mem_filter.mp h).2).choose_spec + refine card_bij f (fun j h => mem_filter.mpr ⟨mem_univ _, (spec j h).2⟩) ?_ ?_ + · intro a ha b hb h + apply P.diagram.wireAt_inj P.loopless + rw [(spec a ha).1, (spec b hb).1, h] + · intro z hz + have h := (mem_filter.mp hz).2 + obtain ⟨j, hj⟩ := P.has_slot v z (by + obtain ⟨a, b⟩ := Prod.mk.inj h.1 + rw [a, b]; exact P.diagram.wireAt_incident _ _ he) + have hm : j ∈ univ.filter earlier' := mem_filter.mpr ⟨mem_univ _, (iff' j).mpr ⟨z, hj, h⟩⟩ + exact ⟨j, hm, Sum.inr.inj ((spec j hm).1.symm.trans hj)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # An explicit initial record of a planted surface -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Surface Surface.Local Routing.Private +variable {F K B A : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m n : ℕ} {W ε : ℝ} (P : Input F x y h D T (d * b) g W) (p : P.Kits K m n ε) + +open scoped Classical in +/-- Uses `⟨.refl _, .refl _, name, P.key p, P.external p, fun _ => rfl⟩` as the representation. -/ +def reference (name : P.diagram.V → A) : + Reference P.Occupied P.grid.Seam A P.Occupied P.grid.Seam P.diagram.V (P.Parameters p) := + ⟨.refl _, .refl _, name, P.key p, P.external p, fun _ => rfl⟩ + +variable (ha : ∀ v, (P.grid.uses v).card ≤ n) + +open scoped Classical in +/-- Evaluates `pathLabel (P.grid.uses j).card (P.diagram.table j) (P.path ha j) x y a` at the +input `x y _ a _`. -/ +def stationLabel (j : P.diagram.V) : Stage.Label F (d * b) d := + fun x y _ a _ => pathLabel (P.grid.uses j).card (P.diagram.table j) (P.path ha j) x y a + +open scoped Classical in +private theorem stationLabel_spec (c : P.Occupied) (i : Fin (P.grid.stations c).card) : + Stage.Describes (P.key p) (P.external p) [] (Template.originalAt p P.tag c i) + (P.stationLabel ha (P.grid.label c i)) [] := by + let j := P.grid.label c i + constructor + · change ∅ = (P.tag (n := n) c (.inl j)).reads + by_cases hm : P.mobile j <;> simp [tag, hm] + · intro x a _ + change (P.grid.template K P.weight c).stationWeight x.1 i a = + pathLabel (P.grid.uses j).card (P.diagram.table j) (P.path ha j) + (P.external p (P.tag (n := n) c (.inl j)).name x).1 + (P.external p (P.tag (n := n) c (.inl j)).name x).2 a.val + rw [external_original] + exact P.pathLabel_eq ha K c i _ _ + +variable (name : P.diagram.V → A) (code : P.Occupied → B) (s : P.Occupied → Shape n b d) + +open scoped Classical in +/-- The initial copy of type `Entry F (d * b) d B A`, constructed using `P.grid.label c i`. -/ +def initialCopy (c : P.Occupied) (i : Fin (P.grid.stations c).card) : Entry F (d * b) d B A := + let j := P.grid.label c i + let u := Template.originalAt p P.tag c i + ⟨u.pos, u.a, 0, u.label.role, u.label.name.map name, [], P.stationLabel ha j⟩ + +open scoped Classical in +/-- The initial aux of type `Entry F (d * b) d B A` for the given inputs. -/ +def initialAux (c : P.Occupied) (i : Option (Fin n)) : Entry F (d * b) d B A := + match i with + | none => ⟨(p c).pos (.inr none), 0, 0, .collector, none, [code c], + auxLabel (p c).program (s c) none⟩ + | some j => ⟨(p c).pos (.inr (some j)), ((s c).1 j).val, ((s c).2 j).val, .residue, none, + [code c], + auxLabel (p c).program (s c) (some j)⟩ + +open scoped Classical in +/-- Builds `Record F (d * b) d P.Occupied P.grid.Seam B A where rows c` with the specified +`rows`, `ports`, `level`, `footprint`. -/ +def originRecord : Record F (d * b) d P.Occupied P.grid.Seam B A where + rows c := P.initialAux p code s c none :: + (List.ofFn (fun i => P.initialAux p code s c (some i)) ++ List.ofFn (P.initialCopy p ha name c)) + ports := (P.plant p s).ports + level := (P.plant p s).scene.level + footprint c := {code c} + +open scoped Classical in +private theorem rel_ofFn {α β : Type} {R : α → β → Prop} {n : ℕ} {f : Fin n → α} {g : Fin n → β} + (h : ∀ i, R (f i) (g i)) : List.Forall₂ R (List.ofFn f) (List.ofFn g) := by + simp only [List.forall₂_iff_get, List.length_ofFn, List.get_ofFn, true_and] + exact fun i _ _ => h ⟨i, by assumption⟩ + +open scoped Classical in +theorem matches_origin (β : P.Occupied ⊕ ℕ → B) (hb : ∀ c, β (.inl c) = code c) : + Matches (P.reference p name).world β (P.plant p s) (P.originRecord p ha name code s) := by + let R := (P.reference p name).world + let G := P.originRecord p ha name code s + refine ⟨fun v => ?_, fun v => ?_, fun _ => rfl, fun v => ?_, fun v j hj => ?_⟩ + · change List.Forall₂ (Represents R β []) ((P.plant p s).scene.cell v).stations (G.rows v) + rw [plant_stations] + refine .cons ?_ (List.rel_append (rel_ofFn fun i => ?_) (rel_ofFn fun i => ?_)) + · exact ⟨rfl, rfl, rfl, rfl, rfl, fun _ => rfl, fun j hj => by + change j ∈ {Sum.inl v} at hj; rw [mem_singleton.mp hj]; trivial, + [.inl v], by simp [hb, initialAux], P.collector_label p s v⟩ + · exact ⟨rfl, rfl, rfl, rfl, rfl, fun _ => rfl, fun j hj => by + change j ∈ {Sum.inl v} at hj; rw [mem_singleton.mp hj]; trivial, + [.inl v], by simp [hb, initialAux], P.auxiliary_label p s v i⟩ + · have e := P.stationLabel_spec p ha v i + refine ⟨rfl, rfl, rfl, rfl, rfl, ?_, ?_, [], rfl, e⟩ + · change (P.tag (n := n) v (.inl (P.grid.label v i))).role ≠ .collector → + (P.tag (n := n) v (.inl (P.grid.label v i))).name = none + by_cases h : P.mobile (P.grid.label v i) <;> simp [tag, h] + · intro j hj + rw [← e.1] at hj + simp at hj + · change (P.plant p s).ports v = ((P.plant p s).ports v).map id + rw [List.map_id] + · change ({.inl v} : Finset _).image β = {code v} + rw [image_singleton, hb] + · change j ∈ {Sum.inl v} at hj + rw [mem_singleton.mp hj]; trivial + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Recovering packet names and station labels from a local port sequence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Packing +variable {F : Type} {x y : Wire} {h D T r g n : ℕ} {W : ℝ} + (P : Input F x y h D T r g W) + +open scoped Classical in +/-- Transforms the indexed data by `(s.line k i).map fun p => (rankEdge (p.1, s.ord k i / r), +s.ord k i % r)`. -/ +def StationView.address (s : StationView F) (r k i : ℕ) : Option (ℕ × ℕ) := + (s.line k i).map fun p => (rankEdge (p.1, s.ord k i / r), s.ord k i % r) + +open scoped Classical in +/-- Transforms the indexed data by `((List.finRange s.arity).filterMap fun i => (s.address r k +i.val).map Prod.fst).toFinset`. -/ +def StationView.packets (s : StationView F) (r k : ℕ) : Finset ℕ := + ((List.finRange s.arity).filterMap fun i => (s.address r k i.val).map Prod.fst).toFinset + +open scoped Classical in +/-- The step of type `PathStep n r`, constructed using `((s.packets r k).sort (· ≤ ·)).idxOf +p.1`. -/ +def StationView.step (s : StationView F) (r k n i : ℕ) : PathStep n r := + ((s.pin i).1, (s.address r k i).bind fun p => + let j := ((s.packets r k).sort (· ≤ ·)).idxOf p.1 + if h : j < n ∧ p.2 < r then some (⟨j, h.1⟩, ⟨p.2, h.2⟩) else none) + +variable (H : P.LocalRanks) (hr : 0 < r) (v : P.diagram.V) +include H hr + +open scoped Classical in +theorem inspect_address (i : Fin (P.diagram.arity v)) : + (P.inspect v).address r (P.nodeRank v) i = + (P.diagram.wireAt v i).elim (fun _ => none) + (fun e => some (P.packetRank (P.packets.bits e).1, (P.packets.bits e).2.val)) := by + unfold StationView.address + rw [inspect_line] + cases he : P.diagram.wireAt v i with + | inl _ => rfl + | inr e => + simp only [Sum.elim_inr, Option.map_some, P.inspect_ord H hr _ _ he, + P.packets_numbered.1, P.packetRank_eq hr H.supplied, rankEdge, wireKey] + +open scoped Classical in +theorem inspect_packets : + (P.inspect v).packets r (P.nodeRank v) = (P.grid.uses v).image P.packetRank := by + ext k + simp only [StationView.packets, List.mem_toFinset, List.mem_filterMap, List.mem_finRange, + true_and, mem_image] + constructor + · rintro ⟨i, hi⟩ + change Fin (P.diagram.arity v) at i + rw [P.inspect_address H hr v i] at hi + cases he : P.diagram.wireAt v i with + | inl x => simp [he] at hi + | inr e => + exact ⟨_, P.packet_mem v i he, by simpa [he] using hi⟩ + · rintro ⟨p, hp, rfl⟩ + let e := P.packets.bits.symm (p, ⟨0, hr⟩) + have he : (P.packets.bits e).1 = p := congrArg Prod.fst (P.packets.bits.apply_symm_apply _) + obtain ⟨i, hi⟩ := P.has_slot v e (by + rw [← P.packets.left, ← P.packets.right, he] + exact (mem_filter.mp hp).2) + exact ⟨i, by rw [P.inspect_address H hr, hi, Sum.elim_inr, Option.map_some, he]⟩ + +open scoped Classical in +theorem LocalRanks.uses : Set.InjOn P.packetRank (P.grid.uses v) := by + apply (H.packet hr (P.grid.cell v)).mono + intro i hi + exact ((mem_filter.mp hi).2).imp (congrArg P.grid.cell) (congrArg P.grid.cell) + +open scoped Classical in +theorem inspect_step (ha : ∀ v, (P.grid.uses v).card ≤ n) (i : Fin (P.diagram.arity v)) : + (P.inspect v).step r (P.nodeRank v) n i = P.path ha v i := by + unfold StationView.step + simp only [inspect_pin, inspect_address P H hr, inspect_packets P H hr] + cases he : P.diagram.wireAt v i with + | inl _ => rw [P.path_exterior _ _ _ he]; rfl + | inr e => + rw [P.path_internal _ _ _ he] + have key := Grid.number_idxOf (H.uses P hr v) ⟨_, P.packet_mem v i he⟩ + have bound := ((Grid.number P.packetRank (P.grid.uses v)).symm ⟨_, P.packet_mem v i he⟩).isLt + simp only [Sum.elim_inr, Option.bind_some, ← key, + dite_eq_left (And.intro (bound.trans_le (ha v)) + (P.packets.bits e).2.isLt)] + rfl + +omit H hr +variable [Field F] + +open scoped Classical in +/-- Evaluates `pathLabel (s.packets r k).card s.table (fun i => s.step r k n i.val) x y a` at +the input `x y _ a _`. -/ +def StationView.label (s : StationView F) (r t n k : ℕ) : Surface.Stage.Label F r t := + fun x y _ a _ => pathLabel (s.packets r k).card s.table (fun i => s.step r k n i.val) x y a + +open scoped Classical in +theorem inspect_label {b d : ℕ} (P : Input F x y h D T (d * b) g W) + (H : P.LocalRanks) (hr : 0 < d * b) (ha : ∀ v, (P.grid.uses v).card ≤ n) (v : P.diagram.V) : + (P.inspect v).label (d * b) d n (P.nodeRank v) = P.stationLabel ha v := by + have step : (fun i : Fin (P.diagram.arity v) => (P.inspect v).step (d * b) (P.nodeRank v) n + i.val) = + P.path ha v := funext (P.inspect_step H hr _ ha) + unfold StationView.label + rw [P.inspect_packets H hr, card_image_iff.mpr (H.uses P hr v)] + change (fun x y _ a _ => pathLabel _ (P.diagram.table v) + (fun i : Fin (P.diagram.arity v) => (P.inspect v).step (d * b) (P.nodeRank v) n i.val) x y a) + = _ + rw [step] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Recovering every seam and its ordered packets from a cell's stations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere +variable {F : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} + +open scoped Classical in +/-- The data for the seed construction, including `color`, `rows`. -/ +structure Seed (F : Type) where + /-- Stores the color associated with this `Seed`. -/ + color : ℕ + /-- The indexed rows of type `List (ℕ × StationView F)`. -/ + rows : List (ℕ × StationView F) + +open scoped Classical in +/-- Computes the use by the application `v.2.packets r (Nat.pair s.color v.1)`. -/ +def Seed.use (s : Seed F) (r : ℕ) (v : ℕ × StationView F) := + v.2.packets r (Nat.pair s.color v.1) + +open scoped Classical in +/-- Computes the pool by the application `s.rows.toFinset.biUnion (s.use r)`. -/ +def Seed.pool (s : Seed F) (r : ℕ) := s.rows.toFinset.biUnion (s.use r) + +open scoped Classical in +/-- The value specified by `(e.unpair.1.unpair.1, e.unpair.2.unpair.1.unpair.1)`. -/ +def homes (e : ℕ) := (e.unpair.1.unpair.1, e.unpair.2.unpair.1.unpair.1) + +open scoped Classical in +/-- Computes the seam key by the application `Nat.pair (homes e).1 (homes e).2`. -/ +def seamKey (e : ℕ) := Nat.pair (homes e).1 (homes e).2 + +open scoped Classical in +/-- The indexed operation `((s.pool r).filter fun e => (homes e).1 ≠ (homes e).2).image +seamKey`. -/ +def Seed.seams (s : Seed F) (r : ℕ) := + ((s.pool r).filter fun e => (homes e).1 ≠ (homes e).2).image seamKey + +open scoped Classical in +/-- Selects the elements of `(s.pool r)` satisfying `fun e => seamKey e = i`. -/ +def Seed.carry (s : Seed F) (r i : ℕ) := (s.pool r).filter fun e => seamKey e = i + +variable (P : Input F x y h D T r g W) + +open scoped Classical in +/-- The value specified by `(P.stationRank v, P.inspect v)`. -/ +def entry (v : P.diagram.V) := (P.stationRank v, P.inspect v) + +open scoped Classical in +/-- Uses `⟨P.hostRank c.val.1, List.ofFn fun i => P.entry (P.grid.label c i)⟩` as the +representation. -/ +def seed (c : P.Occupied) : Seed F := + ⟨P.hostRank c.val.1, List.ofFn fun i => P.entry (P.grid.label c i)⟩ + +open scoped Classical in +theorem seed_rows (c : P.Occupied) : (P.seed c).rows.toFinset = (P.grid.stations c).image P.entry + := by + ext v + simp only [seed, List.mem_toFinset, List.mem_ofFn, mem_image] + constructor + · rintro ⟨i, rfl⟩; exact ⟨_, (Grid.number _ _ i).property, rfl⟩ + · rintro ⟨i, hi, rfl⟩ + exact ⟨(Grid.number P.grid.stationRank _).symm ⟨i, hi⟩, by simp [Grid.label]⟩ + +open scoped Classical in +private theorem carried (e : P.Edges) (j : P.grid.Seam) : e ∈ P.grid.carries j ↔ + P.grid.cell (P.grid.src e) = j.val.1 ∧ P.grid.cell (P.grid.dst e) = j.val.2 := by + simp [Grid.carries] + +open scoped Classical in +private theorem belongs (e : P.grid.Seam) (c : P.Occupied) : + e ∈ P.grid.ports c ↔ e.val.1 = c ∨ e.val.2 = c := by simp [Grid.ports] + +variable (H : P.LocalRanks) (hr : 0 < r) (c : P.Occupied) +include H hr + +open scoped Classical in +theorem seed_use (v : P.diagram.V) (hv : P.grid.cell v = c) : + (P.seed c).use r (P.entry v) = (P.grid.uses v).image P.packetRank := by + subst c + exact P.inspect_packets H hr v + +open scoped Classical in +theorem seed_pool (e : ℕ) : + e ∈ (P.seed c).pool r ↔ ∃ i, P.incidentPacket c i ∧ P.packetRank i = e := by + simp only [Seed.pool, seed_rows, mem_biUnion, mem_image] + constructor + · rintro ⟨_, ⟨v, hv, rfl⟩, he⟩ + have eq : P.grid.cell v = c := by simpa [Grid.stations] using hv + rw [P.seed_use H hr c v eq] at he + obtain ⟨i, hi, rfl⟩ := mem_image.mp he + refine ⟨i, ?_, rfl⟩ + rcases (mem_filter.mp hi).2 with ht|ht + · exact .inl ((congrArg P.grid.cell ht).trans eq) + · exact .inr ((congrArg P.grid.cell ht).trans eq) + · rintro ⟨i, hi, rfl⟩ + have go (v : P.diagram.V) (hv : P.grid.cell v = c) (ht : i ∈ P.grid.uses v) : + ∃ z, (∃ j ∈ P.grid.stations c, P.entry j = z) ∧ P.packetRank i ∈ (P.seed c).use r z := by + refine ⟨P.entry v, ⟨v, by simp [Grid.stations, hv], rfl⟩, ?_⟩ + rw [P.seed_use H hr _ _ hv]; exact mem_image_of_mem _ ht + exact hi.elim (fun h => go _ h (by simp [Grid.uses])) (fun h => go _ h (by simp [Grid.uses])) + +open scoped Classical in +theorem packet_homes (e : P.Edges) : homes (P.packetRank e) = + (P.grid.cellRank (P.grid.cell (P.grid.src e)), P.grid.cellRank (P.grid.cell (P.grid.dst e))) + := by + simp [homes, packetRank, nodeRank, H.supplied, hr, grid] + +open scoped Classical in +private theorem seam_nodes {i j : P.Edges} (hi : P.incidentPacket c i) (hj : P.incidentPacket c j) + (e : seamKey (P.packetRank i) = seamKey (P.packetRank j)) : + P.grid.cell (P.grid.src i) = P.grid.cell (P.grid.src j) ∧ P.grid.cell (P.grid.dst i) + = P.grid.cell (P.grid.dst j) := by + simp only [seamKey, P.packet_homes H hr, Nat.pair_eq_pair] at e + obtain ⟨a, b⟩ := P.endpoints_atHost hr c i hi + obtain ⟨a', b'⟩ := P.endpoints_atHost hr c j hj + exact ⟨Subtype.ext (Prod.ext (H.hosts _ a.2 a'.2 e.1) (a.1.trans a'.1.symm)), + Subtype.ext (Prod.ext (H.hosts _ b.2 b'.2 e.2) (b.1.trans b'.1.symm))⟩ + +open scoped Classical in +theorem packet_seam {i : P.Edges} {e : P.grid.Seam} (hi : i ∈ P.grid.carries e) : + seamKey (P.packetRank i) = P.grid.seamRank e := by + obtain ⟨h₁, h₂⟩ := ((P.carried _ _).mp hi) + simp only [seamKey, P.packet_homes H hr, h₁, h₂, Grid.seamRank] + +open scoped Classical in +theorem seed_seams : (P.seed c).seams r = (P.grid.ports c).image P.grid.seamRank := by + ext i + simp only [Seed.seams, mem_image, mem_filter, seed_pool P H hr c] + constructor + · rintro ⟨_, ⟨⟨e, he, rfl⟩, ne⟩, rfl⟩ + rw [P.packet_homes H hr] at ne + let v := P.grid.cell (P.grid.src e) + let w := P.grid.cell (P.grid.dst e) + let j : P.grid.Seam := ⟨(v, w), fun eq => ne (congrArg P.grid.cellRank eq), e, rfl, rfl⟩ + exact ⟨j, (P.belongs _ _).mpr he, (P.packet_seam H hr ((P.carried _ _).mpr ⟨rfl, rfl⟩)).symm⟩ + · rintro ⟨e, he, rfl⟩ + obtain ⟨j, hj, hj'⟩ := e.property.2 + have use : P.incidentPacket c j := by + unfold incidentPacket; rw [hj, hj']; exact (P.belongs _ _).mp he + refine ⟨_, ⟨⟨j, use, rfl⟩, ?_⟩, P.packet_seam H hr ((P.carried _ _).mpr ⟨hj, hj'⟩)⟩ + obtain ⟨a, b⟩ := P.endpoints_atHost hr c j use + rw [P.packet_homes H hr] + intro eq + apply e.property.1 + rw [← hj, ← hj'] + exact Subtype.ext (Prod.ext (H.hosts _ a.2 b.2 eq) (a.1.trans b.1.symm)) + +open scoped Classical in +theorem seed_carry (e : P.grid.Seam) (he : e ∈ P.grid.ports c) : + (P.seed c).carry r (P.grid.seamRank e) = (P.grid.carries e).image P.packetRank := by + have hit (i : P.Edges) (hi : i ∈ P.grid.carries e) : P.incidentPacket c i := by + unfold incidentPacket + rw [((P.carried _ _).mp hi).1, ((P.carried _ _).mp hi).2] + exact (P.belongs _ _).mp he + ext x + simp only [Seed.carry, mem_filter, seed_pool P H hr c, mem_image] + constructor + · rintro ⟨⟨i, hi, rfl⟩, h⟩ + obtain ⟨j, hj, hj'⟩ := e.property.2 + have hm : j ∈ P.grid.carries e := (P.carried _ _).mpr ⟨hj, hj'⟩ + obtain ⟨a, b⟩ := P.seam_nodes H hr c hi (hit j hm) (h.trans (P.packet_seam H hr hm).symm) + exact ⟨i, (P.carried _ _).mpr ⟨a.trans hj, b.trans hj'⟩, rfl⟩ + · rintro ⟨i, hi, rfl⟩ + exact ⟨⟨i, hit i hi, rfl⟩, P.packet_seam H hr hi⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Canonical station order from an unordered set of local records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Sphere Finset +variable {F : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} + +open scoped Classical in +/-- Uses `⟨color, List.ofFn fun i => (Grid.number Prod.fst rows i).val⟩` as the representation. -/ +def arrange (color : ℕ) (rows : Finset (ℕ × StationView F)) : Seed F := + ⟨color, List.ofFn fun i => (Grid.number Prod.fst rows i).val⟩ + +open scoped Classical in +theorem seed_arrange (P : Input F x y h D T r g W) (H : P.LocalRanks) (c : P.Occupied) : + P.seed c = arrange (P.hostRank c.val.1) ((P.grid.stations c).image P.entry) := by + let A := (P.grid.stations c).image P.entry + let f := Grid.number Prod.fst A + have inj : Set.InjOn Prod.fst (↑A : Set (ℕ × StationView F)) := by + intro x hx y hy e + obtain ⟨i, hi, rfl⟩ := mem_image.mp hx + obtain ⟨j, hj, rfl⟩ := mem_image.mp hy + exact congrArg P.entry (H.station c hi hj e) + have h₁ : (P.seed c).rows.Pairwise (fun x y => x.1 < y.1) := by + apply List.pairwise_ofFn.mpr + exact fun _ _ h => (Grid.number_lt (H.station c) _ _).mpr h + have h₂ : (List.ofFn fun i => (f i).val).Pairwise (fun x y => x.1 < y.1) := + List.pairwise_ofFn.mpr fun _ _ h => (Grid.number_lt inj _ _).mpr h + have eqn : (P.seed c).rows = List.ofFn (fun i => (f i).val) := by + apply List.Perm.eq_of_pairwise (fun _ _ _ _ h k => (h.asymm k).elim) h₁ h₂ + apply (List.perm_ext_iff_of_nodup h₁.nodup h₂.nodup).mpr + intro x + rw [← List.mem_toFinset, seed_rows, List.mem_ofFn] + exact ⟨fun h => ⟨f.symm ⟨x, h⟩, by simp⟩, by rintro ⟨i, rfl⟩; exact (f i).property⟩ + exact congrArg (Seed.mk _) eqn + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Deterministic recovery of the one-species wiring pattern -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Finset Sphere SphereScale +variable {F K : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} + +open scoped Classical in +/-- The value specified by `(s.seams r).sort (· ≤ ·)`. -/ +def Seed.ordered (s : Seed F) (r : ℕ) := (s.seams r).sort (· ≤ ·) + +open scoped Classical in +/-- Concatenates the components in the order `s.rows.map (s.use r) ++ (s.ordered r).map (s.carry +r)`. -/ +def Seed.lists (s : Seed F) (r : ℕ) := + s.rows.map (s.use r) ++ (s.ordered r).map (s.carry r) + +open scoped Classical in +/-- The value specified by `((s.lists r).getD i ∅).sort (· ≤ ·)`. -/ +def Seed.names (s : Seed F) (r i : ℕ) := ((s.lists r).getD i ∅).sort (· ≤ ·) + +open scoped Classical in +/-- The condition `∀ i j (u : Fin (w i)) (v : Fin (w j)), (s.names r i).getD u 0 = (s.names r +j).getD v 0 → f i u = f j v` on the specified data. -/ +def Seed.agree (s : Seed F) (r : ℕ) {k : ℕ} (w : Fin k → ℕ) (f : Plant.Bits w) : Prop := + ∀ i j (u : Fin (w i)) (v : Fin (w j)), + (s.names r i).getD u 0 = (s.names r j).getD v 0 → f i u = f j v + +variable (P : Input F x y h D T r g W) (H : P.LocalRanks) (hr : 0 < r) (c : P.Occupied) +include H hr + +open scoped Classical in +theorem ordered_seams : (P.seed c).ordered r = List.ofFn (fun i + => P.grid.seamRank (P.grid.seam c i)) := by + rw [Seed.ordered, P.seed_seams H hr c, ← Grid.number_keys (H.seam hr c)] + rfl + +open scoped Classical in +private theorem seed_lists : (P.seed c).lists r = List.ofFn (fun i + => (P.grid.mark c i).image P.packetRank) := by + unfold Seed.lists + rw [P.ordered_seams H hr c] + simp only [seed, List.map_ofFn, ← List.ofFn_fin_append] + congr 1 + funext i + induction i using Fin.addCases with + | left i => + rw [Fin.append_left, Grid.mark_label] + exact P.seed_use H hr c _ (P.grid.label_cell c i) + | right i => + rw [Fin.append_right, Grid.mark_seam] + exact P.seed_carry H hr c _ (Grid.number _ _ i).property + +open scoped Classical in +theorem seed_names (i : P.grid.Index c) : + (P.seed c).names r i = List.ofFn (fun j => P.packetRank (Grid.number P.packetRank (P.grid.mark + c i) j).val) := by + rw [Seed.names, P.seed_lists H hr, List.getD_eq_getElem?_getD, List.getElem?_ofFn, + dite_eq_left i.isLt, + Option.getD_some] + exact (Grid.number_keys (H.mark hr c i)).symm + +open scoped Classical in +theorem seed_width (i : P.grid.Index c) : + ((P.seed c).names r i).length = P.grid.width c i := by + rw [P.seed_names H hr, List.length_ofFn]; rfl + +open scoped Classical in +theorem seed_agree (f : Plant.Bits (P.grid.width c)) : + P.grid.Agree c f ↔ (P.seed c).agree r (P.grid.width c) f := by + let n (i : P.grid.Index c) := Grid.number P.grid.packetRank (P.grid.mark c i) + have key (i : P.grid.Index c) (u : Fin (P.grid.width c i)) : + ((P.seed c).names r i).getD u 0 = P.grid.packetRank (n i u).val := by + have he : u.val < (P.grid.mark c i).card := u.isLt + rw [P.seed_names H hr, List.getD_eq_getElem?_getD, List.getElem?_ofFn, dite_eq_left he, + Option.getD_some] + rfl + have read (i : P.grid.Index c) (u : Fin (P.grid.width c i)) : + Grid.read P.grid.packetRank (P.grid.mark c i) (f i) (n i u).val = f i u := by + unfold Grid.read + erw [dite_eq_left (n i u).property] + exact congrArg (f i) ((n i).symm_apply_apply u) + constructor + · intro h i j u v e + rw [key, key] at e + have eq : (n i u).val = (n j v).val := H.packet hr c + (P.grid.touches c i (n i u).property) (P.grid.touches c j (n j v).property) e + rw [← read i u, ← read j v, ← eq] + exact h _ _ _ (n i u).property (eq.symm ▸ (n j v).property) + · intro h i j e he hf + simp only [Grid.read, dite_eq_left he, dite_eq_left hf] + apply h + erw [key, key] + simp [n] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Choosing a planting program from local data -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere SphereScale +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g ℓ n m : ℕ} {W : ℝ} + +open scoped Classical in +/-- The data for the identifies construction, including `stations`, `ports`, `width`, `rule`. -/ +structure Seed.Identifies (s : Seed F) (r : ℕ) (p : Pattern K D g n) : Prop where + stations : p.1.val = s.rows.length + ports : p.2.1.val = (s.ordered r).length + width : ∀ i, (p.2.2.1.val i).val = (s.names r i.val).length + rule : ∀ x, p.2.2.2 x = if s.agree r _ x then 1 else 0 + +omit [Field F] [Algebra K F] in +open scoped Classical in +theorem Seed.Identifies.unique {s : Seed F} {r : ℕ} {p q : Pattern K D g n} + (a : s.Identifies r p) (c : s.Identifies r q) : p = q := by + obtain ⟨i, j, u, f⟩ := p + obtain ⟨k, l, v, h⟩ := q + have e : i = k := Fin.ext (a.stations.trans c.stations.symm) + subst k + have e : j = l := Fin.ext (a.ports.trans c.ports.symm) + subst l + have e : u = v := Subtype.ext (funext fun i => Fin.ext ((a.width i).trans (c.width i).symm)) + subst v + have e : f = h := funext fun x => (a.rule x).trans (c.rule x).symm + rw [e] + +variable (P : Input F x y h D T (d * b) g W) (sc : Scales g ℓ D T m b d) + +open scoped Classical in +/-- Computes the plan at by the application `pattern (P.grid.template K P.weight c) +(P.probe_width sc c) (P.stations_bound c) (P.ports_bound sc.Rpos c)`. -/ +def planAt (K : Type) [Field K] (c : P.Occupied) : Pattern K D g (probes ℓ D) := + pattern (P.grid.template K P.weight c) (P.probe_width sc c) + (P.stations_bound c) (P.ports_bound sc.Rpos c) + +omit [Field F] [Algebra K F] in +open scoped Classical in +theorem seed_identifies (hc : P.LocalRanks) (c : P.Occupied) : + (P.seed c).Identifies (d * b) (P.planAt sc K c) := by + refine ⟨?_, ?_, fun i => (P.seed_width hc sc.Rpos c i).symm, ?_⟩ + · exact List.length_ofFn.symm + · rw [P.ordered_seams hc sc.Rpos, List.length_ofFn]; rfl + · intro f + change (if P.grid.Agree c f then (1 : K) else 0) = _ + simp only [P.seed_agree hc sc.Rpos c f] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Shapes.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Shapes.lean new file mode 100644 index 0000000000..531d262055 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Shapes.lean @@ -0,0 +1,478 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Scenario + +/-! # Short records for initial concentration -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Boot +open Coloring Neighborhood + +/-- The quantity computed by `Format.pair (.addr e) (.pair (.addr ((d + 1) * r + 1)) (.pair +(.addr ((d + 1) * s + 1)) (.addr k)))`. -/ +abbrev own (d r s e k : ℕ) := Format.pair (.addr e) + (.pair (.addr ((d + 1) * r + 1)) (.pair (.addr ((d + 1) * s + 1)) (.addr k))) +/-- The value specified by `(own d r s e k).pair (.vec d (own d r s e k))`. -/ +abbrev query (d r s e k : ℕ) := (own d r s e k).pair (.vec d (own d r s e k)) +/-- Computes the selectors by the application `Format.vec m (.vec h (.addr k))`. -/ +abbrev selectors (m h k : ℕ) := Format.vec m (.vec h (.addr k)) +/-- The value specified by `(Fmt.rows m d h (.addr e)).pair (selectors m h k)`. -/ +abbrev source (m d h e k : ℕ) := (Fmt.rows m d h (.addr e)).pair (selectors m h k) + +/-- The value specified by `paintCost m d r + paintCost m d s + gatherCost m d v n + 500 * +(Fmt.rows m d h (query d r s e k)).width + 4 * Z.width`. -/ +def cost (m d h r s e k v n : ℕ) (Z : Format) := + paintCost m d r + paintCost m d s + gatherCost m d v n + + 500 * (Fmt.rows m d h (query d r s e k)).width + 4 * Z.width + +variable {m d h e k : ℕ} (r s : ℕ) + +/-- The colored of type `(Fmt.rows m d h (own d r s e k)).obj`, constructed using `(z.1 i).1`. -/ +def colored (z : (source m d h e k).obj) : (Fmt.rows m d h (own d r s e k)).obj := + let g i := (z.1 i).1 + fun i => (g i, fun j => ((z.1 i).2 j, tone g r i, tone g s i, z.2 i j)) + +/-- The around of type `(Fmt.rows m d h (query d r s e k)).obj`, constructed using `colored r s +z`. -/ +def around (z : (source m d h e k).obj) : (Fmt.rows m d h (query d r s e k)).obj := + let b := colored r s z + fun i => ((b i).1, fun j => ((b i).2 j, fun l => (b ((b i).1 l)).2 j)) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Boot +end + +/- # The initial dictionary and its single validity test -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Assembly Coloring Routing.Private Sphere.Surface.Local SphereScale + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {g ℓ D T b d p l : ℕ} + (S : Scheme F) + +local notation "Cfg" => design S g ℓ D b d p l +local notation "R" => 2 * D ^ 5 + 2 +local notation "Q" => horizon (D ^ 5) (Design.waves Cfg) 0 + +open scoped Classical in +/-- The quantity computed by `Boot.query S.d (2 * D ^ 5 + 2) (horizon (D ^ 5) (design S g ℓ D b +d p l).waves 0) S.ℓ k`. -/ +abbrev panelQuery (g ℓ D b d p l k : ℕ) := + Boot.query S.d (2 * D ^ 5 + 2) (horizon (D ^ 5) (design S g ℓ D b d p l).waves 0) S.ℓ k + +local notation "Query" => panelQuery S g ℓ D b d p l + +open scoped Classical in +/-- The panel menu of type `(Cfg).Menu F (B S.k) (B S.ℓ) (Query k).width`, constructed using +`(Design.number (Query k)).symm j`. -/ +def panelMenu (hK : Ready K ℓ D g (p ^ l) b d) (k : ℕ) : + (Cfg).Menu F (B S.k) (B S.ℓ) (Query k).width := fun j => + let v := (Design.number (Query k)).symm j + if live S v.1.1 then + if h : v.1.2.2.2.val < Fintype.card (Shape (probes ℓ D) b d) then + viewStart S hK v.1.1 v.1.2.1 v.1.2.2.1 (fun i => (v.2 i).1) (fun i => (v.2 i).2.1) + (fun j => decide (j ≠ 0)) ((Fintype.equivFin _).symm ⟨_, h⟩) + else (v.1.1, none) + else (v.1.1, none) + +open scoped Classical in +/-- Selects the appropriate branch of `if live S v.1.1 then if v.1.2.2.2.val < Fintype.card +(Shape (probes ℓ D) b d) then 1 else 0 else if v.1.2.2.2 = 0 then 1 else 0`. -/ +def panelGuard (_sc : Scales g ℓ D T (p ^ l) b d) (k : ℕ) (v : (Query k).obj) : F := + if live S v.1.1 then + if v.1.2.2.2.val < Fintype.card (Shape (probes ℓ D) b d) then 1 else 0 + else if v.1.2.2.2 = 0 then 1 else 0 + +open scoped Classical in +/-- The value specified by `weightTable (D := .addr (Query k).width) (Design.number (Query k)) +(panelGuard S sc k)`. -/ +def panelTable (sc : Scales g ℓ D T (p ^ l) b d) (k : ℕ) : Table F := + weightTable (D := .addr (Query k).width) (Design.number (Query k)) (panelGuard S sc k) + +open scoped Classical in +/-- The value specified by `Boot.around R Q (z, c)`. -/ +def panelAround (_sc : Scales g ℓ D T (p ^ l) b d) {k : ℕ} (z : S.format.obj) + (c : (Boot.selectors S.m S.h k).obj) : (Fmt.rows S.m S.d S.h (Query k)).obj := + Boot.around R Q (z, c) + +open scoped Classical in +/-- The value specified by `Fmt.update (D := .addr (Query k).width) (Design.number (Query k)) +(panelAround S sc z c)`. -/ +def panelTape (sc : Scales g ℓ D T (p ^ l) b d) {k : ℕ} (z : S.format.obj) + (c : (Boot.selectors S.m S.h k).obj) := + Fmt.update (D := .addr (Query k).width) (Design.number (Query k)) (panelAround S sc z c) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Choosing an initial shape once at each occupied occurrence -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Assembly Coloring Routing.Private Sphere.Surface.Local SphereScale Transcript Finset + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h g ℓ D T b d p l k : ℕ} {W : ℝ} + (P : Input F x y h D T (d * b) g W) {S : Scheme F} {z : S.format.obj} + (A : P.HostChart S z) + +local notation "Sh" => Shape (probes ℓ D) b d + +open scoped Classical in +theorem fits (hk : initialChoices ℓ D b d ≤ 2 ^ k) : Fintype.card Sh ≤ 2 ^ k := by + rw [card_shape] + exact hk + +open scoped Classical in +/-- The indexed operation `(Selector.scattered A.coord (fun _ => Sh) (fun _ => fits hk)).relabel +(Equiv.curry _ _ _)`. -/ +def panelSelector (hk : initialChoices ℓ D b d ≤ 2 ^ k) : + Selector (P.Occupied → Sh) (Boot.selectors S.m S.h k).obj := + (Selector.scattered A.coord (fun _ => Sh) (fun _ => fits hk)).relabel (Equiv.curry _ _ _) + +omit [Field F] in +open scoped Classical in +theorem panelSelector_at (hk : initialChoices ℓ D b d + ≤ 2 ^ k) (s : P.Occupied → Sh) (v : P.Occupied) : + (((P.panelSelector A hk).write s) (A.coord v).1 (A.coord v).2).val = + (Fintype.equivFin Sh (s v)).val := + Selector.scatter_at A.coord (fun _ => Sh) (fun _ => fits hk) s v + +variable (sc : Scales g ℓ D T (p ^ l) b d) (hK : Ready K ℓ D g (p ^ l) b d) + (s : P.Occupied → Shape (probes ℓ D) b d) {t : S.Presentation z P.diagram} + (H : P.Placed t A.coord (fun i => (A.tone (2 * D ^ 5 + 2) i).val) (fun v => decide (v.2.2 ≠ 0))) +include H + +open scoped Classical in +theorem panelWeight (hk : initialChoices ℓ D b d ≤ 2 ^ k) (c : (Boot.selectors S.m S.h k).obj) : + Fmt.weight (panelGuard S sc k) (panelAround S sc z c) = + ((P.panelSelector A hk).read c).elim 0 (fun _ => 1) := by + let w (v : B S.m × B S.h) := panelGuard S sc k (((panelAround S sc z c) v.1).2 v.2) + have hw := Selector.scattered_weight A.coord (fun _ => Sh) (fun _ => fits hk) + (Function.uncurry c) (fun _ _ => (1 : F)) w (by + intro j + have hj := (H.live_iff (A.coord j)).mpr ⟨j, rfl⟩ + simp only [w, panelGuard, panelAround, Boot.around, Boot.colored, hj, ite_true, + Function.uncurry] + split_ifs <;> rfl) + (by + intro v hv + have hv' := mt (H.live_iff v).mp hv + simp only [w, panelGuard, panelAround, Boot.around, Boot.colored, hv', ite_false, + Function.uncurry] + split_ifs <;> rfl) + simp only [prod_const_one, Fintype.prod_prod_type] at hw + exact hw + +open scoped Classical in +/-- The physical tape and the initial frame agree at every host, including vacant slots. -/ +def panelCode (hr : P.LocalRanks) (hk : initialChoices ℓ D b d ≤ 2 ^ k) : + (P.localWorld A sc hK s).Code 0 (panelMenu S hK k) where + frame := P.start A sc hK s + tape := panelTape S sc z ((P.panelSelector A hk).write s) + host _ := rfl + read := by + intro i + simp only [panelTape, Fmt.update, panelMenu, Equiv.symm_apply_apply, panelAround, Boot.around, + Boot.colored] + by_cases hi : i ∈ Set.range A.coord + · obtain ⟨j, rfl⟩ := hi + have hj := (H.live_iff (A.coord j)).mpr ⟨j, rfl⟩ + simp only [hj, ite_true, P.panelSelector_at, Fin.is_lt, ↓reduceDIte, Fin.eta, + Equiv.symm_apply_apply] + exact (P.start_at A sc hK s H hr j).symm + · rw [ite_eq_right (mt (H.live_iff i).mp hi)] + exact (P.start_away A sc hK s i hi).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Pricing the two colorings and the initial shape lookup -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Assembly Coloring Rounds.Contraction + +namespace Rates +variable (a : Rates) + +/-- The construction uses `(d + 1) * r` for its intermediate `q`. -/ +def paintSize (d r : ℕ) := + let q := (d + 1) * r + 2 ^ ((Neighborhood.Check q).width + q + 1) + +theorem paint (d r : ℕ) (hs : paintSize d r ≤ a.Y) : + a.Host 213 (Neighborhood.paintCost a.m d r) := by + let q := (d + 1) * r + have ht : 2 ^ q ≤ a.Y := + (Nat.pow_le_pow_right (by decide) (by omega : q ≤ (Neighborhood.Check q).width + q + + 1)).trans hs + have hl := a.long + have hx : 100 + (a.m + 2 ^ q) ≤ a.X := by omega + have h₁ := Row.hosts (high (Nat.pow_le_pow_left hx 210)) + have h₂ := Row.hosts (Paid.scale (big (hs.trans a.incl)) 32) + have h₃ : a.Host 1 (Neighborhood.Colors a.m q).width := by + rw [Neighborhood.Colors, Format.width_vec, Format.width_addr] + exact Row.hosts (big ((Nat.lt_two_pow_self (n := q)).trans_le (ht.trans a.incl))) + exact ((h₁.scale 4).plus h₂).plus (h₃.scale 4) + +end Rates + +namespace Design +variable (a : Design) {F : Type} [Field F] (p : Prices F) + +/-- The quantity computed by `2 * a.U + 2`. -/ +abbrev radius := 2 * a.U + 2 +/-- Computes the range by the application `horizon a.U a.waves 0`. -/ +abbrev range := horizon a.U a.waves 0 +/-- Uses `Boot.own a.d a.radius a.range e k` as the representation. -/ +abbrev own (e k : ℕ) := Boot.own a.d a.radius a.range e k +/-- The value specified by `(Boot.query a.d a.radius a.range e k).width`. -/ +abbrev entryWidth (e k : ℕ) := (Boot.query a.d a.radius a.range e k).width +/-- The quantity computed by `2 ^ a.h * (a.own e k).width`. -/ +def entryCap (e k : ℕ) := 2 ^ a.h * (a.own e k).width +/-- The quantity computed by `Boot.cost a.m a.d a.h a.radius a.range e k (a.entryCap e k) (p.fee +(a.m + a.d) (a.entryCap e k))`. -/ +def entryCost (e k : ℕ) := Boot.cost a.m a.d a.h a.radius a.range e k + (a.entryCap e k) (p.fee (a.m + a.d) (a.entryCap e k)) + +/-- The quantity computed by `Rates.paintSize a.d a.radius + Rates.paintSize a.d a.range`. -/ +def coloringSize := Rates.paintSize a.d a.radius + Rates.paintSize a.d a.range + +theorem entry_bound (e k : ℕ) (Z : Format) (X Y : ℕ) + (hs : 10000 ≤ Y) (hl : 1000 + 10 * a.m + 10 * Y ≤ X) + (hW : 1 + p.W ≤ Y) (hw : 1 + p.w ^ p.power ≤ X) (ht : 2 ^ a.d ≤ Y) + (hb : a.entryWidth e k ≤ Y) (hc : a.coloringSize ≤ Y) : + a.entryCost p e k Z ≤ 2 ^ a.m * X ^ 217 + (2 ^ (a.m + a.h) + Z.width) * Y ^ 217 := by + let c : Rates := ⟨a.m, a.h, X, Y, hs, hl⟩ + let v := a.entryCap e k + have he : a.entryWidth e k ≤ c.Y ^ 4 := hb.trans (Nat.le_self_pow (by decide) _) + have hv : c.Row 4 v := by + apply Rates.low + refine le_trans ?_ he + conv_rhs => rw [entryWidth, Boot.query, Format.width_pair] + exact Nat.le_add_right .. + have hf := c.fee p a.d v ht hW hw hv + have hg := c.gather a.d v _ ht hv hf + have hr := c.paint a.d a.radius ((Nat.le_add_right ..).trans hc) + have hu := c.paint a.d a.range ((Nat.le_add_left ..).trans hc) + have hrow := (c.rows a.d _ ht he).scale 500 + have h := Rates.Host.carry (z := Z.width) (((hr.plus hu).plus hg).plus hrow) + rw [pow_add] + refine le_trans ?_ (h.scale 4) + unfold entryCost Boot.cost + change _ + 4 * Z.width ≤ 4 * (_ + Z.width) + rw [mul_add] + exact Nat.add_le_add_right (Nat.le_mul_of_pos_left _ (by decide)) _ + +end Design +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# Concentration up to the final split + +The pass-through register has an exact linear charge independent +of the old label width. The latter can grow when rounds repeat. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Design +open Assembly Coloring Rounds.Contraction +variable (a : Design) {F : Type} [Field F] (p : Prices F) (e k : ℕ) + +/-- Computes the last width by the application `a.widthAt (a.entryWidth e k) k a.waves`. -/ +abbrev lastWidth := a.widthAt (a.entryWidth e k) k a.waves + +/-- The quantity computed by `3 + 2 * a.maxWidth (a.entryWidth e k) k`. -/ +def arity := 3 + 2 * a.maxWidth (a.entryWidth e k) k + +theorem entry_fits : 2 * a.entryWidth e k ≤ a.arity e k := by + have h : a.entryWidth e k + k ≤ a.maxWidth (a.entryWidth e k) k := a.fits_width (Nat.zero_le _) + unfold arity + omega + +theorem last_fits : a.lastWidth e k ≤ a.arity e k := by + have h : a.lastWidth e k + k ≤ a.maxWidth (a.entryWidth e k) k := a.fits_width le_rfl + unfold arity + omega + +/-- This multiplier depends only on the local geometric bounds. -/ +def inflation := 10000 + a.coloringSize + 2 ^ a.hops + a.waves+ + 2 * a.factor ^ a.waves * ((1 + 2 ^ a.d) * ((a.d + 1) * a.radius + (a.d + 1) * a.range + 2) + 1) + +theorem arity_bound : a.arity e k ≤ a.inflation * (1 + e + k) := by + have h₀ : a.entryWidth e k = + (1 + 2 ^ a.d) * (e + (a.d + 1) * a.radius + (a.d + 1) * a.range + 2 + k) := by + simp only [entryWidth, Boot.query, Boot.own, Format.width_pair, Format.width_vec, + Format.width_addr] + rw [Format.width_addr, Format.width_addr] + ring + have est (b c f x : ℕ) : 3 + 2 * (f * (b * (e + c + 2 + k) + k)) ≤ + (10000 + x + 2 * f * (b * (c + 2) + 1)) * (1 + e + k) := by ring_nf; omega + unfold arity maxWidth inflation + rw [h₀] + simpa only [add_assoc] using est (1 + 2 ^ a.d) ((a.d + 1) * a.radius + (a.d + 1) * a.range) + (a.factor ^ a.waves) (a.coloringSize + 2 ^ a.hops + a.waves) + +/-- The quantity computed by `a.entryCost p e k Z + a.price p (a.entryWidth e k) k Z`. -/ +def work (Z : Format) := a.entryCost p e k Z + a.price p (a.entryWidth e k) k Z + +theorem work_split (Z : Format) : + a.work p e k Z = a.work p e k (.addr 0) + (8 + 4 * a.waves) * Z.width := by + simp only [work, entryCost, Boot.cost, price, totalCost, cost, Format.width_pair, + Finset.sum_add_distrib, Finset.sum_const, Finset.card_range, nsmul_eq_mul, Nat.cast_id] + rw [Format.width_addr 0] + ring + +theorem work_bound (Z : Format) (X Y : ℕ) (hl : 1000 + 10 * a.m + 10 * Y ≤ X) + (hW : 1 + p.W ≤ Y) (hw : 1 + p.w ^ p.power ≤ X) (hY : a.inflation * (1 + e + k) ≤ Y) : + a.work p e k Z ≤ 2 ^ a.m * X ^ 218 + 2 ^ (a.m + a.h) * Y ^ 218 + (8 + 4 * a.waves) * Z.width + := by + rw [work_split] + apply Nat.add_le_add_right + have hi : a.inflation ≤ Y := (Nat.le_mul_of_pos_right _ (by omega)).trans hY + have ha := (a.arity_bound e k).trans hY + have h₀ := (a.entry_fits e k).trans ha + have hs : 10000 ≤ Y ∧ a.coloringSize ≤ Y ∧ 2 ^ a.hops ≤ Y ∧ a.waves ≤ Y := by + unfold inflation at hi + generalize 2 ^ a.hops = z at hi ⊢ + omega + let c : Rates := ⟨a.m, a.h, X, Y, hs.1, hl⟩ + have ht := (Nat.pow_le_pow_right (by decide : 0 < 2) a.degree_le_hops).trans hs.2.2.1 + have h₁ := a.entry_bound p e k (.addr 0) X Y hs.1 hl hW hw ht (by omega) hs.2.1 + have h₂ := a.price_bound p (a.entryWidth e k) k (.addr 0) X Y hs.1 hl hW hw hs.2.2.1 + (by unfold arity at ha; omega) hs.2.2.2 + rw [Format.width_addr, add_zero, pow_add] at h₁ h₂ + rw [pow_add] + exact Rates.Paid.plus (show c.Host 217 _ from h₁) (show c.Host 215 _ from h₂) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Design +end + +/- # Initial shapes and scenarios for a grouped layer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Routing.Private Sphere.Surface.Local SphereScale +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {a D T b d ℓ p l : ℕ} {θ L : ℝ} + (P : Layer F x y) (B : P.template.Binning a D T (d * b) θ) + (t : ∀ i, B.Trial (P.presents i) L) + (sc : Scales ((4 * 5) ^ 300) ℓ D T (p ^ l) b d) + (hK : SphereScale.Ready K ℓ D ((4 * 5) ^ 300) + (p ^ l) b d) + +/-- The quantity computed by `2 * D ^ 5 + 2`. -/ +abbrev panelRadius (D : ℕ) := 2 * D ^ 5 + 2 + +/-- Indexes the panel states by the coordinates of `Σ i, ((t i).normal (panelRadius D)).Occupied +→ Shape (probes ℓ D) b d`. -/ +abbrev panelStates (ℓ : ℕ) := Σ i, ((t i).normal (panelRadius D)).Occupied → Shape (probes ℓ D) b d + +/-- The value specified by `((t i.1).normal (panelRadius D)).localWorld ((t i.1).atlas _) sc hK +i.2`. -/ +abbrev panelWorld (i : P.panelStates B t ℓ) := + ((t i.1).normal (panelRadius D)).localWorld ((t i.1).atlas _) sc hK i.2 + +/-- Computes the panel port by the application `B.Flags.pair (Fmt.payload B.target.m +(P.groupedVolume B) P.height)`. -/ +abbrev panelPort := B.Flags.pair (Fmt.payload B.target.m (P.groupedVolume B) P.height) + +/-- The value specified by `((P.masked B t (panelRadius D)).encode i.1 z w).2`. -/ +abbrev panelPayload (i : P.panelStates B t ℓ) (z : Val x) (w : Val y) : (P.panelPort B).obj := + ((P.masked B t (panelRadius D)).encode i.1 z w).2 + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # Movement schedules for a grouped layer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer + +open Assembly Coloring Sphere.Surface.Local SphereScale +variable {F K : Type} [Field F] [Fintype F] [Field K] [Algebra K F] {x y : Wire} + {a D T b d ℓ p l : ℕ} [ExpChar F p] {θ L : ℝ} + (P : Layer F x y) (B : P.template.Binning a D T (d * b) θ) + (t : ∀ i, B.Trial (P.presents i) L) + +local notation "g" => ((4 * 5) ^ 300 : ℕ) +local notation "Cfg" => Input.design B.target g ℓ D b d p l +variable (sc : Scales g ℓ D T (p ^ l) b d) (hK : SphereScale.Ready K ℓ D g (p ^ l) b d) + (hF : room ℓ D g * (2 * depth ℓ D g (p ^ l) (d * b) + 1) < Fintype.card F) (k : ℕ) + +open scoped Classical in +/-- The value specified by `(Cfg).menuAt hF (Input.panelMenu B.target hK k) k (Cfg).waves +le_rfl`. -/ +abbrev movedMenu := (Cfg).menuAt hF (Input.panelMenu B.target hK k) k (Cfg).waves le_rfl + +open scoped Classical in +/-- The moved of type `Snapshot.{1} F x y` for the given inputs. -/ +abbrev moved : Snapshot.{1} F x y := + Sphere.Surface.Local.snapshot (P.panelWorld B t sc hK) (P.panelPort B) (P.panelPayload B t) + (Cfg).waves (P.movedMenu B hK hF k) + +open scoped Classical in +/-- Computes the motion calls by the application `insert (Input.panelTable B.target sc k) +((Cfg).calls hF (Input.panelMenu B.target hK k) k)`. -/ +def motionCalls := insert (Input.panelTable B.target sc k) ((Cfg).calls hF (Input.panelMenu + B.target hK k) k) + +open scoped Classical in +theorem card_motionCalls : (P.motionCalls B sc hK hF k).card ≤ (Cfg).waves + 1 := + (Finset.card_insert_le ..).trans (Nat.succ_le_succ ((Cfg).card_calls ..)) + +variable {k} (q : Contraction.Prices F) {u : ℕ} {labels : Set (Table F)} + +omit [Fintype F] [ExpChar F p] in +open scoped Classical in +private theorem panelCity (i : P.panelStates B t ℓ) (v : Coloring.B B.target.m) (j : Coloring.B + B.target.d) : + (P.panelWorld B t sc hK i).atlas.graph v j ≠ v → ∃! l, + (P.panelWorld B t sc hK i).atlas.graph ((P.panelWorld B t sc hK i).atlas.graph v j) l = v := + ((t i.1).atlas (panelRadius D)).reciprocal v j + +omit [Field F] [Fintype F] [ExpChar F p] in +open scoped Classical in +theorem panelWidth_eq (S : Scheme F) (G ℓ' D' b' d' p' l' k' : ℕ) : + (Input.panelQuery S G ℓ' D' b' d' p' l' k').width = + (Input.design S G ℓ' D' b' d' p' l').entryWidth S.ℓ k' := rfl + +open scoped Classical in +theorem movePanel (hk : Frame.budget F (Cfg).chart (Cfg).g (Cfg).H (Cfg).M (Cfg).D (Cfg).U ≤ 2 ^ k) + (hw : B.target.m + (Cfg).hops ≤ q.w) (hu : (Cfg).arity B.target.ℓ k ≤ u) + (ht : ↑(P.motionCalls B sc hK hF k) ⊆ labels) : + Transforms F u labels + (Sphere.Surface.Local.snapshot (P.panelWorld B t sc hK) (P.panelPort B) (P.panelPayload B t) 0 + (Input.panelMenu B.target hK k)) + (P.moved B t sc hK hF k) ((Cfg).price q ((Input.panelQuery B.target g ℓ D b d p l k).width) k + (P.panelPort B)) := by + have ha : 3 ≤ u := (Nat.le_add_right ..).trans hu + have hb : 2 * (Cfg).maxWidth ((Input.panelQuery B.target g ℓ D b d p l k).width) k ≤ u := by + rw [panelWidth_eq] + exact (Nat.le_add_left ..).trans hu + have ht' : ↑((Cfg).calls hF (Input.panelMenu B.target hK k) k) ⊆ labels := fun _ h + => ht (Finset.mem_insert_of_mem h) + have hu' : 0 < (Cfg).U := pow_pos sc.Dpos 5 + have h := priced_waves (a := Cfg) (e := (Input.panelQuery B.target g ℓ D b d p l k).width) (k + := k) (P.panelWorld B t sc hK) (P.panelPort B) (P.panelPayload B t) + hF (Input.panelMenu B.target hK k) q hk (P.panelCity B t sc hK) + ha hu' hw hb ht' + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Terminal.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Terminal.lean new file mode 100644 index 0000000000..90df9e385c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Terminal.lean @@ -0,0 +1,966 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Parcel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Serial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Restore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Pattern +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Window +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Depth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Scenario +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Concentration.Kits +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Initial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Wiring + +/-! +# Carrying the two exterior lists to a frozen collector + +Concentration moves the exterior of each input station as two +ordered lists, within the same block of a child of the old host. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +open Assembly Coloring Packing +variable {F : Type} [Field F] {x y : Wire} {G H : Diagram F x y} + {S U : Scheme F} {r : S.format.obj} {t : U.format.obj} + (p : S.Presentation r G) (q : U.Presentation t H) {z : ℕ} + (child : B U.m ≃ B S.m × B z) (outer : Bool ↪ B U.e) + +open scoped Classical in +/-- The data for the carrier construction, including `parent`, `block`, `seat`, `left`, `right`. -/ +structure Carrier (v : G.V) (w : H.V) : Prop where + parent : (child (q.vertex w).1).1 = (p.vertex v).1 + block : (q.vertex w).2.1.val = (p.vertex v).2.1.val + seat : (q.vertex w).2.2 = 0 + left : ∀ j : Fin (G.extLeft v).length, let a := (q.boundary (.inl ((G.extLeft v).get j))).val + a.1 = (q.vertex w, outer false) ∧ a.2.val = j.val + right : ∀ j : Fin (G.extRight v).length, let a := (q.boundary (.inr ((G.extRight v).get j))).val + a.1 = (q.vertex w, outer true) ∧ a.2.val = j.val + +open scoped Classical in +/-- The condition `∀ i : slots x ⊕ slots y, ∃ w, Carrier p q child outer (portEnd G i) w` on the +specified data. -/ +def Retains := ∀ i : slots x ⊕ slots y, ∃ w, Carrier p q child outer (portEnd G i) w + +open scoped Classical in +theorem owner (i : slots x ⊕ slots y) : (p.boundary i).val.1.1 = p.vertex (portEnd G i) := by + cases i <;> exact p.end_station _ + +variable {p q child outer} {v : G.V} {w : H.V} + +open scoped Classical in +theorem Carrier.owns (c : Carrier p q child outer v w) (i : slots x ⊕ slots y) (h : portEnd G i + = v) : + (q.boundary i).val.1 = (q.vertex w, outer i.isRight) := by + cases i with + | inl i => + obtain ⟨j, rfl⟩ := List.mem_iff_get.mp ((G.mem_extLeft v i).mpr h) + exact (c.left _).1 + | inr i => + obtain ⟨j, rfl⟩ := List.mem_iff_get.mp ((G.mem_extRight v i).mpr h) + exact (c.right _).1 + +namespace Retains +variable (f : Retains p q child outer) +include f + +open scoped Classical in +theorem parent (i : slots x ⊕ slots y) : + (child (q.boundary i).val.1.1.1).1 = (p.boundary i).val.1.1.1 := by + obtain ⟨w, c⟩ := f i + rw [c.owns i rfl, owner] + exact c.parent + +open scoped Classical in +theorem load_le (i : B U.m) : U.load t i ≤ S.load r (child i).1 := by + let e := q.boundary.symm.trans p.boundary + have he (j : U.exposed t) : S.owner r (e j) = (child (U.owner t j)).1 := by + obtain ⟨s, rfl⟩ := q.boundary.surjective j + have hs : e (q.boundary s) = p.boundary s := by + simp only [e, Equiv.trans_apply, Equiv.symm_apply_apply] + rw [hs] + exact (f.parent s).symm + let g (x : U.fiber t i) : S.fiber r (child i).1 := ⟨e x.val, by rw [he, x.property]⟩ + exact Fintype.card_le_of_injective g fun _ _ h => Subtype.ext (e.injective (congrArg Subtype.val + h)) + +open scoped Classical in +theorem fits {k V : ℕ} (h : S.Fits r V k) : U.Fits t (2 ^ U.m + wd x + wd y) k := + q.fits le_rfl (fun i => (f.load_le i).trans (h.2 _)) + +end Retains +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +end + +/- # The initial tile as a function of the occupied cell's ordered ports -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Surface Surface.Local Routing.Private SphereScale +variable {F K A B : Type} [Field F] [Field K] [Algebra K F] + {x y : Wire} {q h ℓ D T b d g m : ℕ} {W : ℝ} + +open scoped Classical in +/-- The value specified by `(color k.unpair.1, color k.unpair.2)`. -/ +def seamName (color : ℕ → Fin q) (k : ℕ) := (color k.unpair.1, color k.unpair.2) + +namespace Seed + +open scoped Classical in +/-- The draw row of type `Entry F (d * b) d B A`, constructed using `s.rows.getD i (0, ⟨⟨.unit, +.unit, fun _ _ => 0⟩, false, []⟩)`. -/ +def drawRow (s : Seed F) (names : ℕ → A) (n i : ℕ) (pos : F) (e : ℕ) : + Entry F (d * b) d B A := + let row := s.rows.getD i (0, ⟨⟨.unit, .unit, fun _ _ => 0⟩, false, []⟩) + ⟨pos, e, 0, if row.2.mobile then .active 0 else .collector, + if row.2.mobile then none else some (names row.1), [], + row.2.label (d * b) d n (Nat.pair s.color row.1)⟩ + +open scoped Classical in +/-- The draw of type `Tile F (d * b) d q B A`, constructed using `p.template F (d * b)`. -/ +def draw (s : Seed F) (p : Pattern K D g (probes ℓ D)) (hK : Ready K ℓ D g m b d) + (name : ℕ → A) (color : ℕ → Fin q) (stamp : B) (shape : Shape (probes ℓ D) b d) : + Tile F (d * b) d q B A := + let u := p.template F (d * b) + let w := p.patch (F := F) hK + let head : Entry F (d * b) d B A := + ⟨w.pos (.inr none), 0, 0, .collector, none, [stamp], auxLabel w.program shape none⟩ + let aux : Fin (probes ℓ D) → Entry F (d * b) d B A := fun j => + ⟨w.pos (.inr (some j)), (shape.1 j).val, (shape.2 j).val, .residue, none, [stamp], + auxLabel w.program shape (some j)⟩ + let rows := List.ofFn fun i : Fin u.stations => + s.drawRow name (probes ℓ D) i.val (w.pos (.inl (u.old i))) (u.level (u.old i)) + let ports := List.ofFn fun i : Fin u.ports => + (seamName color ((s.ordered (d * b)).getD i.val 0), w.pos (.inl (u.edge i)), u.level (u.edge i)) + ⟨⟨head :: (List.ofFn aux ++ rows), ports, {stamp}⟩, {(stamp, .inl w.program.labels)}⟩ + +open scoped Classical in +/-- Every quantity used to construct the tile is local. The default +on malformed data is irrelevant to the contraction. -/ +def tile (s : Seed F) (hK : Ready K ℓ D g m b d) + (name : ℕ → A) (color : ℕ → Fin q) (stamp : B) (shape : Shape (probes ℓ D) b d) : + Tile F (d * b) d q B A := + if h : ∃ p : Pattern K D g (probes ℓ D), s.Identifies (d * b) p then + s.draw h.choose hK name color stamp shape + else ⟨⟨[], [], ∅⟩, ∅⟩ + +end Seed + +variable (P : Input F x y h D T (d * b) g W) (sc : Scales g ℓ D T m b d) (hK : Ready K ℓ D g m b d) + (H : P.LocalRanks) (name : ℕ → A) (color : ℕ → Fin q) (stamp : P.Occupied → B) + (shape : P.Occupied → Shape (probes ℓ D) b d) (c : P.Occupied) +include H + +open scoped Classical in +private theorem row_eq (i : Fin (P.grid.stations c).card) : + let p := P.kit sc hK + let a := Template.originalAt p P.tag c i + (P.seed c).drawRow (B := B) name (probes ℓ D) i.val a.pos a.a = + P.initialCopy p (P.maxPackets sc) (name ∘ P.stationRank) c i := by + intro p a + let v := P.grid.label c i + have key : Nat.pair (P.seed c).color (P.stationRank v) = P.nodeRank v := by + have h := congrArg (fun c : P.Occupied => c.val.1) (P.grid.label_cell c i) + unfold nodeRank + exact congrArg (fun x => Nat.pair (P.hostRank x) _) h.symm + have hrow (w) : (P.seed c).rows.getD i.val w = P.entry v := by + simp [seed, List.getD_eq_getElem?_getD, v] + unfold Seed.drawRow + rw [hrow] + simp only [entry, key, P.inspect_label H sc.Rpos (P.maxPackets sc)] + have hr : a.label = P.tag (n := probes ℓ D) c (.inl v) := rfl + change _ = (⟨a.pos, a.a, 0, a.label.role, a.label.name.map _, [], _⟩ : Entry F (d * b) d B A) + rw [hr] + by_cases h : P.mobile v <;> simp [inspect, tag, h, v] + +open scoped Classical in +/-- The initial tile of type `Tile F (d * b) d q B A`, constructed using `P.kit sc hK`. -/ +def initialTile : Tile F (d * b) d q B A := + let p := P.kit sc hK + let row := P.originRecord p (P.maxPackets sc) (name ∘ P.stationRank) stamp shape + ⟨row.body (seamName color ∘ P.grid.seamRank) c, {(stamp c, .inl (p c).program.labels)}⟩ + +open scoped Classical in +theorem initial_tile : + (P.seed c).tile hK name color (stamp c) (shape c) + = P.initialTile sc hK name color stamp shape c := by + let p := P.kit sc hK + let u := P.grid.template K P.weight c + let a := P.planAt sc K c + have ha := P.seed_identifies (K := K) sc H c + have he : ∃ q : Pattern K D g (probes ℓ D), (P.seed c).Identifies (d * b) q := ⟨a, ha⟩ + rw [Seed.tile, dite_eq_left he, he.choose_spec.unique ha] + have rows (i : Fin (P.grid.stations c).card) : + (P.seed c).drawRow (B := B) name (probes ℓ D) i.val ((p c).pos (.inl (u.old i))) (u.level + (u.old i)) = + P.initialCopy p (P.maxPackets sc) (name ∘ P.stationRank) c i := P.row_eq sc hK H name c i + have ports (i : Fin (P.grid.ports c).card) : + (seamName color (((P.seed c).ordered (d * b)).getD i.val 0), (p c).pos (.inl (u.edge i)), + u.level (u.edge i)) = + (seamName color (P.grid.seamRank (P.grid.seam c i)), (p c).pos (.inl (u.edge i)), + P.grid.energy (d * b) (P.grid.seam c i)) := by + rw [P.ordered_seams H sc.Rpos, List.getD_eq_getElem?_getD, List.getElem?_ofFn, + dite_eq_left i.isLt, Option.getD_some] + change (_, _, (d * b) * (8 * (P.grid.mark c (Fin.natAdd _ i)).card ^ 2)) = _ + rw [Grid.mark_seam] + rfl + dsimp only [Seed.draw, initialTile, Record.body, originRecord] + congr 2 + · change P.initialAux p stamp shape c none :: (List.ofFn (fun i + => P.initialAux p stamp shape c (some i)) ++ + List.ofFn (fun i : Fin (P.grid.stations c).card => (P.seed c).drawRow name (probes ℓ D) i.val + ((p c).pos (.inl (u.old i))) (u.level (u.old i)))) = _ + rw [funext rows] + · change List.ofFn (fun i : Fin (P.grid.ports c).card => + (seamName color (((P.seed c).ordered (d * b)).getD i.val 0), (p c).pos (.inl (u.edge i)), + u.level (u.edge i))) = + (List.ofFn (fun i => (P.grid.seam c i, (p c).pos (.inl (u.edge i))))).map _ + rw [funext ports, List.map_ofFn] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# Local initialization on a common host + +An occurrence reads its own pattern and the patterns at its neighbors. +The mobile flags and short colors are additional local data. Vacant +slots can be detected because every actual station has positive arity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Assembly Coloring Sphere + +variable {F : Type} [Field F] {m d k e : ℕ} + +open scoped Classical in +/-- The route may specify arbitrarily wide bundles. It is a function +of the pattern labels, not a separate tape of individual bit addresses. -/ +def localView (p : Pattern F d k e) (near : B d → Pattern F d k e) (tone : B d → ℕ) + (mobile : B k → Bool) (j : B k) : StationView F := + ⟨p.orderedTable j, mobile j, Scheme.Presentation.route p j near (fun i j + => Nat.pair (tone i) j.val)⟩ + +open scoped Classical in +/-- The indexed operation `arrange color ((univ.filter fun j => Nonempty (p.Pin j)).image fun j +=> (j.val, localView p near tone mobile j))`. -/ +def localSeed (p : Pattern F d k e) (color : ℕ) (near : B d → Pattern F d k e) (tone : B d → ℕ) + (mobile : B k → Bool) : Seed F := + arrange color ((univ.filter fun j => Nonempty (p.Pin j)).image fun j => + (j.val, localView p near tone mobile j)) + +variable {x y : Wire} {h D T r g : ℕ} {W : ℝ} (P : Input F x y h D T r g W) + {S : Scheme F} {s : S.format.obj} (p : S.Presentation s P.diagram) + +open scoped Classical in +/-- Relation between the diagram placement and its ordered presentation. -/ +structure Placed (addr : P.Occupied ↪ B S.m × B S.h) (tone : B S.m → ℕ) + (mobile : S.Vtx → Bool) : Prop where + standard : p.Canonical + location : ∀ v, ((p.vertex v).1, (p.vertex v).2.1) = addr (P.grid.cell v) + color : ∀ c, P.hostRank c.val.1 = tone (addr c).1 + name : ∀ v, P.stationRank v = (p.vertex v).2.2.val + flag : ∀ v, decide (P.mobile v) = mobile (p.vertex v) + +open scoped Classical in +theorem occupied_slot (v : S.Vtx) : Nonempty (S.LocalPin s v) ↔ v ∈ Set.range p.vertex := by + constructor + · rintro ⟨x⟩ + exact p.cover (S.port s v x) + · rintro ⟨i, rfl⟩ + let l := P.diagram.table i + let j := (Transcript.positions (.pair l.1 l.2.1)).symm ⟨0, P.positive i⟩ + exact ⟨p.pin i j⟩ + +variable {P p} {addr : P.Occupied ↪ B S.m × B S.h} {tone : B S.m → ℕ} + {mobile : S.Vtx → Bool} (H : P.Placed p addr tone mobile) +include H + +open scoped Classical in +theorem Placed.inspect (v : P.diagram.V) : + let i := p.vertex v + P.inspect v = localView (S.pattern s i) (fun j => S.pattern s ((s i.1).1 j, i.2.1, i.2.2)) + (fun j => tone ((s i.1).1 j)) (fun j => mobile (i.1, i.2.1, j)) i.2.2 := by + intro i + let f (j : S.Vtx) := Nat.pair (tone j.1) j.2.2.val + have key : P.nodeRank = f ∘ p.vertex := by + funext v + unfold nodeRank + have := H.color (P.grid.cell v) + rw [← H.location] at this + change P.hostRank (P.place v).1 = tone (p.vertex v).1 at this + rw [this, H.name]; rfl + unfold Input.inspect localView + rw [key, (H.standard v).2 f, H.flag] + congr 1 + exact (H.standard v).1 + +open scoped Classical in +/-- Initial data depend only on local pattern records and short colors. -/ +theorem Placed.seed_eq (hr : P.LocalRanks) (c : P.Occupied) : + let i := addr c + P.seed c = localSeed (S.decode ((s i.1).2 i.2)) (tone i.1) + (fun j => S.decode ((s ((s i.1).1 j)).2 i.2)) (fun j => tone ((s i.1).1 j)) + (fun j => mobile (i.1, i.2, j)) := by + intro i + let A := S.decode ((s i.1).2 i.2) + let row := localView A (fun j => S.decode ((s ((s i.1).1 j)).2 i.2)) + (fun j => tone ((s i.1).1 j)) (fun j => mobile (i.1, i.2, j)) + have e (v : P.diagram.V) (k : B S.k) (h : p.vertex v = (i.1, i.2, k)) : + P.entry v = (k.val, row k) := by + rw [entry, H.name, H.inspect, h] + rfl + have eq : (P.grid.stations c).image P.entry = + (univ.filter fun j => Nonempty (A.Pin j)).image (fun k => (k.val, row k)) := by + ext x + simp only [mem_image, mem_filter, mem_univ, true_and] + constructor + · rintro ⟨v, hv, rfl⟩ + have hv' : P.grid.cell v = c := by simpa [Grid.stations] using hv + let k := (p.vertex v).2.2 + have he : p.vertex v = (i.1, i.2, k) := by + have := H.location v + rw [hv'] at this + change ((p.vertex v).1, (p.vertex v).2.1) = (i.1, i.2) at this + obtain ⟨h₁, h₂⟩ := Prod.mk.inj this + exact Prod.ext h₁ (Prod.ext h₂ rfl) + exact ⟨k, (P.occupied_slot p _).mpr ⟨v, he⟩, (e v k he).symm⟩ + · rintro ⟨k, hk, rfl⟩ + obtain ⟨v, hv⟩ := (P.occupied_slot p (i.1, i.2, k)).mp hk + have he : P.grid.cell v = c := by + apply addr.injective + rw [← H.location v, hv] + exact ⟨v, by simp [Grid.stations, he], e v k hv⟩ + rw [P.seed_arrange hr, H.color, eq] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Putting a presented local input in canonical order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {s : S.format.obj} {G : Diagram F x y} + (p : S.Presentation s G) (h : p.Directed) + +theorem ordered_source : (p.ordered h).source = G.source := rfl +theorem ordered_target : (p.ordered h).target = G.target := rfl +theorem ordered_portEnd : Packing.portEnd (p.ordered h) = Packing.portEnd G := rfl + +theorem ordered_arity : (p.ordered h).arity = G.arity := by + funext v + have e := Fintype.card_congr ((p.stationPin v).trans (p.pin v).symm) + simp only [Transcript.Ports, Fintype.card_sum, card_slots] at e + exact e + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Scheme.Presentation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Assembly Coloring Sphere +variable {F : Type} [Field F] {S : Scheme F} {s : S.format.obj} + {x y : Wire} {h D T r g : ℕ} {W : ℝ} (P : Input F x y h D T r g W) + (p : S.Presentation s P.diagram) (direct : p.Directed) (host : P.V → ℕ) + +open scoped Classical in +/-- Retain every port endpoint, station and host position. -/ +def normalize : Input F x y h D T r g W where + V := P.V + diagram := p.ordered direct + place := P.place + adj := P.adj + sym := P.sym + degree := P.degree + edge := P.edge + loopless := P.loopless + positive := by rw [p.ordered_arity direct]; exact P.positive + width := P.width + mobile := P.mobile + ext := P.ext + occupied := P.occupied + immobile := P.immobile + count := P.count + mass := by rw [p.ordered_arity direct]; exact P.mass + squares := by rw [p.ordered_arity direct]; exact P.squares + ranks := some (fun v => (p.vertex v).2.2.val, host) + +open scoped Classical in +theorem normalize_eval : (P.normalize p direct host).diagram.eval = P.diagram.eval := + funext fun x => funext fun y => p.ordered_eval direct x y + +open scoped Classical in +theorem normalize_order : (P.normalize p direct host).diagram.PortOrder (2 ^ (S.e + 1)) := + p.ordered_order direct + +open scoped Classical in +theorem normalize_placed (addr : P.Occupied ↪ B S.m × B S.h) (tone : B S.m → ℕ) + (mobile : S.Vtx → Bool) + (loc : ∀ v, ((p.vertex v).1, (p.vertex v).2.1) = addr (P.grid.cell v)) + (color : ∀ c, host c.val.1 = tone (addr c).1) + (mob : ∀ v, decide (P.mobile v) = mobile (p.vertex v)) : + (P.normalize p direct host).Placed (p.toOrdered direct) addr tone mobile := + ⟨p.canonical_ordered direct, loc, color, fun _ => rfl, mob⟩ + +variable {P p} +open scoped Classical in +theorem Placed.ranks {addr : P.Occupied ↪ B S.m × B S.h} {tone : B S.m → ℕ} + {mobile : S.Vtx → Bool} (hp : P.Placed p addr tone mobile) + (supplied : P.ranks.isSome) (inj : ∀ u, Set.InjOn P.hostRank (insert u (P.adj u) : Finset P.V)) + : + P.LocalRanks := by + refine ⟨supplied, ?_, inj⟩ + intro u v h₁ h₂ + have cell : P.grid.cell u = P.grid.cell v := Subtype.ext h₁ + have eq := (hp.location u).trans ((congrArg addr cell).trans (hp.location v).symm) + obtain ⟨ha, hb⟩ := Prod.mk.inj eq + rw [hp.name, hp.name] at h₂ + exact p.vertex.injective (Prod.ext ha (Prod.ext hb (Fin.ext h₂))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # A common host chart for the initial sphere layout -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Assembly Coloring Sphere.Surface.Local + +variable {F : Type} {x y : Wire} {h D T r g : ℕ} {W : ℝ} + (P : Input F x y h D T r g W) (S : Scheme F) (s : S.format.obj) + +open scoped Classical in +/-- The data for the host chart construction, including `host`, `block`, `adjacent`, +`reciprocal`. -/ +structure HostChart where + /-- Embeds the coordinates as `P.V ↪ B S.m`. -/ + host : P.V ↪ B S.m + /-- Embeds the coordinates as `Packing.Cell h ↪ B S.h`. -/ + block : Packing.Cell h ↪ B S.h + adjacent : ∀ i j, j ∈ P.adj i → i ≠ j → ∃ k, (s (host i)).1 k = host j + reciprocal : Fmt.Reciprocal (.vec S.h (.addr S.ℓ)) s + +namespace HostChart +variable {P S s} (A : P.HostChart S s) + +open scoped Classical in +/-- Embeds `P.Occupied` into `B S.m × B S.h`. -/ +def coord : P.Occupied ↪ B S.m × B S.h := + ⟨fun c => (A.host c.val.1, A.block c.val.2), fun _ _ e => + Subtype.ext (Prod.ext (A.host.injective (congrArg Prod.fst e)) (A.block.injective (congrArg + Prod.snd e)))⟩ + +open scoped Classical in +/-- The value specified by `(s v).1`. -/ +def graph (_ : P.HostChart S s) (v : B S.m) := (s v).1 + +open scoped Classical in +theorem sym : ∀ i j, A.graph i j ≠ i → ∃ k, A.graph (A.graph i j) k = i := + fun i j h => (A.reciprocal i j h).exists + +open scoped Classical in +/-- Builds `Atlas P.Occupied P.grid.Seam S.m S.d S.h where coord` with the specified `coord`, +`graph`, `reciprocal`, `src`. -/ +def atlas (hr : 0 < r) : Atlas P.Occupied P.grid.Seam S.m S.d S.h where + coord := A.coord + graph := A.graph + reciprocal := A.sym + src j := j.val.1 + dst j := j.val.2 + links := Subtype.val_injective + adjacent j := by + obtain ⟨n, hn, hm⟩ := j.property.2 + have ne := j.property.1 + rw [← hn, ← hm] at ne ⊢ + obtain ⟨eq, hadj⟩ := P.contact hr n + have dif : (P.place (P.grid.src n)).1 ≠ (P.place (P.grid.dst n)).1 := + fun he => ne (Subtype.ext (Prod.ext he eq.symm)) + exact ⟨congrArg A.block eq.symm, A.adjacent _ _ (hadj.resolve_left dif.symm) dif⟩ + +open scoped Classical in +/-- Uses `Neighborhood.tone A.graph R` as the representation. -/ +def tone (R : ℕ) := Neighborhood.tone A.graph R + +open scoped Classical in +/-- Uses `⟨A.tone R, Neighborhood.tone_separates _ R A.sym⟩` as the representation. -/ +def palette (hr : 0 < r) (R : ℕ) : Palette (A.atlas hr) R (Neighborhood.paletteSize S.d R) := + ⟨A.tone R, Neighborhood.tone_separates _ R A.sym⟩ + +open scoped Classical in +/-- The value specified by `(A.tone R (A.host v)).val`. -/ +def rank (R : ℕ) (v : P.V) := (A.tone R (A.host v)).val + +open scoped Classical in +theorem distinguishes (R : ℕ) (hR : 2 ≤ R) (v : P.V) : + Set.InjOn (A.rank R) (insert v (P.adj v) : Finset P.V) := by + have one (w : P.V) (h : w ∈ insert v (P.adj v)) : Neighborhood.Reach A.graph 1 (A.host v) (A.host + w) := by + by_cases e : w = v + · subst w; exact .refl .. + exact ⟨_, .inr (A.adjacent _ _ ((mem_insert.mp h).resolve_left e) (Ne.symm e)), rfl⟩ + intro i hi j hj he + have two := ((one i hi).symm A.sym).join (one j hj) + have e := two.join (Neighborhood.Reach.refl A.graph (R - 2) (A.host j)) + rw [show 1 + 1 + (R - 2) = R by omega] at e + exact A.host.injective (Neighborhood.tone_separates _ _ A.sym _ _ e (Fin.ext he)) + +variable [Field F] (p : S.Presentation s P.diagram) (dir : p.Directed) (R : ℕ) + +open scoped Classical in +/-- Add short local ranks after putting the stations in span order. -/ +def normalized := P.normalize p dir (A.rank R) + +open scoped Classical in +/-- Uses `⟨A.host, A.block, A.adjacent, A.reciprocal⟩` as the representation. -/ +def next : (A.normalized p dir R).HostChart S s := + ⟨A.host, A.block, A.adjacent, A.reciprocal⟩ + +open scoped Classical in +theorem normalized_placed (mobile : S.Vtx → Bool) + (loc : ∀ v, ((p.vertex v).1, (p.vertex v).2.1) = A.coord (P.grid.cell v)) + (mob : ∀ v, decide (P.mobile v) = mobile (p.vertex v)) : + (A.normalized p dir R).Placed (p.toOrdered dir) (A.next p dir R).coord (fun i + => (A.tone R i).val) mobile := + P.normalize_placed p dir (A.rank R) A.coord _ mobile loc (fun _ => rfl) mob + +open scoped Classical in +theorem normalized_ranks (hR : 2 ≤ R) (mobile : S.Vtx → Bool) + (loc : ∀ v, ((p.vertex v).1, (p.vertex v).2.1) = A.coord (P.grid.cell v)) + (mob : ∀ v, decide (P.mobile v) = mobile (p.vertex v)) : (A.normalized p dir R).LocalRanks := + (A.normalized_placed p dir R mobile loc mob).ranks rfl (A.distinguishes R hR) + +end HostChart +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # The initial frame of a colored, planted local concentration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Finset Sphere Surface Surface.Local Assembly Coloring Routing.Private SphereScale + +variable {F K : Type} + +open scoped Classical in +/-- Parameters shared across host records and all initial energy shapes. -/ +abbrev design (S : Scheme F) (g ℓ D b d p l : ℕ) : Surface.Local.Design := + let U := D ^ 5 + let M := room ℓ D g + let R := Neighborhood.paletteSize S.d (2 * U + 2) + let Q := Neighborhood.paletteSize S.d (horizon U (R * M) 0) + ⟨d * b, d, S.m, S.d, S.h, U, R, Q, M, 2 * g, SphereScale.energy ℓ D (d * b), + depth ℓ D g (p ^ l) (d * b), p, l⟩ + +open scoped Classical in +/-- Computes the finite name by the application `Fin.ofNat _ v`. -/ +abbrev finiteName (j : ℕ) (v : ℕ) : B j := Fin.ofNat _ v + +variable [Field F] [Field K] [Algebra K F] {x y : Wire} {h g ℓ D T b d p l : ℕ} {W : ℝ} + (P : Input F x y h D T (d * b) g W) {S : Scheme F} {z : S.format.obj} + (A : P.HostChart S z) (sc : Scales g ℓ D T (p ^ l) b d) (hK : Ready K ℓ D g (p ^ l) b d) + (s : P.Occupied → Shape (probes ℓ D) b d) + +local notation "Cfg" => design S g ℓ D b d p l +local notation "kit" => P.kit sc hK + +open scoped Classical in +/-- The quantity computed by `A.palette sc.Rpos (2 * (Cfg).U + 2)`. -/ +def scheduling := A.palette sc.Rpos (2 * (Cfg).U + 2) +open scoped Classical in +/-- Computes the aliases by the application `A.palette sc.Rpos (horizon (Cfg).U (Cfg).waves 0)`. -/ +def aliases := A.palette sc.Rpos (horizon (Cfg).U (Cfg).waves 0) + +open scoped Classical in +/-- The value specified by `((P.aliases A sc).mark v, none)`. -/ +def bootMark (v : P.Occupied) : Stamp (Cfg).Q (Cfg).waves (Cfg).U := + ((P.aliases A sc).mark v, none) + +open scoped Classical in +/-- The value specified by `P.originRecord kit (P.maxPackets sc) (finiteName S.k ∘ +P.stationRank) (P.bootMark A sc) s`. -/ +def bootRecord := P.originRecord kit (P.maxPackets sc) (finiteName S.k ∘ P.stationRank) + (P.bootMark A sc) s + +open scoped Classical in +/-- Builds `Scenario F (B S.k) (B S.ℓ) Cfg x y where V` with the specified `atlas`, `ref`, +`origin`, `pos`. -/ +def localWorld : Scenario F (B S.k) (B S.ℓ) Cfg x y where + V := P.Occupied + E := P.grid.Seam + T := P.diagram.V + X := P.Parameters kit + J := P.Occupied + L := P.grid.Seam + atlas := A.atlas sc.Rpos + π := P.scheduling A sc + c := P.aliases A sc + ref := P.reference kit (finiteName S.k ∘ P.stationRank) + origin := P.plant kit s + pos := (P.bootRecord A sc hK s).positions + size v := (kit v).program.labels + header j := (z j.1).2 j.2 + controls := ⟨_, _, P.plant_controls kit s⟩ + room _ reach := P.moved_room kit s sc reach + close a b := + { toFun := fun f => ∑ k, f ((a, b), k) + map_add' := by intros; simp [sum_add_distrib] + map_smul' := by intros; simp [mul_sum] } + +open scoped Classical in +/-- The start of type `(P.localWorld A sc hK s).At 0` for the given inputs. -/ +def start : (P.localWorld A sc hK s).At 0 := by + have : NeZero (Cfg).Q := ⟨by unfold design Neighborhood.paletteSize; positivity⟩ + have mat := P.matches_origin kit (P.maxPackets sc) (finiteName S.k ∘ P.stationRank) + (P.bootMark A sc) s (startName (P.aliases A sc)) (fun _ => rfl) + refine Frame.initial (P.scheduling A sc) (P.aliases A sc) mat (fun _ => rfl) + ?_ (P.plant_layout kit s sc.Rpos) (P.plant_valid kit s _) (P.plant_clock kit s) + intro v + exact ((P.moved_room kit s sc (U := D ^ 5) .refl).length v) + +open scoped Classical in +theorem start_sum (a : Val x) (b : Val y) : + P.diagram.eval a b = ∑ s, (P.localWorld A sc hK s).eval (P.start A sc hK s) a b := + (P.eval_plant kit a b).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Reading the initial wave records from the local input -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Finset Sphere Surface Surface.Local Assembly Coloring Routing.Private SphereScale + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h g ℓ D T b d p l : ℕ} {W : ℝ} + +open scoped Classical in +/-- The condition `∃ j, Nonempty ((S.decode own).Pin j)` on the specified data. -/ +def live (S : Scheme F) (own : B S.ℓ) : Prop := ∃ j, Nonempty ((S.decode own).Pin j) + +open scoped Classical in +theorem Placed.live_iff {r : ℕ} {P : Input F x y h D T r g W} + {S : Scheme F} {z : S.format.obj} {t : S.Presentation z P.diagram} + {addr : P.Occupied ↪ B S.m × B S.h} {tone : B S.m → ℕ} {mobile : S.Vtx → Bool} + (H : P.Placed t addr tone mobile) (w : B S.m × B S.h) : + live S ((z w.1).2 w.2) ↔ w ∈ Set.range addr := by + constructor + · rintro ⟨j, hj⟩ + obtain ⟨v, hv⟩ := (P.occupied_slot t (w.1, w.2, j)).mp hj + exact ⟨P.grid.cell v, by rw [← H.location v, hv]⟩ + · rintro ⟨c, rfl⟩ + obtain ⟨v, _, hv⟩ := mem_image.mp c.property + have he : P.grid.cell v = c := Subtype.ext hv + rw [← he, ← H.location v] + exact ⟨(t.vertex v).2.2, (P.occupied_slot t _).mpr ⟨v, rfl⟩⟩ + +variable (S : Scheme F) + +local notation "Cfg" => design S g ℓ D b d p l +local notation "colorAt" => finiteName ((S.d + 1) * (2 * (Surface.Local.Design.U Cfg) + 2) + 1) + +open scoped Classical in +/-- The data of an occupied occurrence, using only its own pattern, +short colors, and the patterns at neighboring hosts. -/ +def viewStart (hK : Ready K ℓ D g (p ^ l) b d) (own : B S.ℓ) + (tone : Fin (Cfg).R) (keyTone : Fin (Cfg).Q) (near : B S.d → B S.ℓ) + (colors : B S.d → Fin (Cfg).R) (mobile : B S.k → Bool) + (shape : Shape (probes ℓ D) b d) : B S.ℓ × (Cfg).row F (B S.k) := + let v := localSeed (S.decode own) tone.val (fun j => S.decode (near j)) + (fun j => (colors j).val) mobile + let stamp : Stamp (Cfg).Q (Cfg).waves (Cfg).U := (keyTone, none) + let tile := v.tile hK (finiteName S.k) colorAt stamp shape + (own, some (tone, keyTone, (fun i : Fin (Cfg).M => (tile.rows[i.val]?.map Entry.pos).getD 0), + tile)) + +variable {S} (P : Input F x y h D T (d * b) g W) {z : S.format.obj} + (A : P.HostChart S z) (sc : Scales g ℓ D T (p ^ l) b d) (hK : Ready K ℓ D g (p ^ l) b d) + (s : P.Occupied → Shape (probes ℓ D) b d) + +local notation "world" => P.localWorld A sc hK s +local notation "frame" => P.start A sc hK s +local notation "schedulingTone" => A.tone (2 * (Surface.Local.Design.U Cfg) + 2) +local notation "aliasTone" => + A.tone (horizon (Surface.Local.Design.U Cfg) (Surface.Local.Design.waves Cfg) 0) + +open scoped Classical in +theorem start_away (w : B S.m × B S.h) (hw : w ∉ Set.range A.coord) : + (world).stored frame w = ((z w.1).2 w.2, none) := by + unfold Scenario.stored + rw [Palette.records_away _ _ _ _ _ hw] + rfl + +variable {t : S.Presentation z P.diagram} {mobile : S.Vtx → Bool} + (H : P.Placed t A.coord (fun i => (A.tone (2 * D ^ 5 + 2) i).val) mobile) +include H + +open scoped Classical in +private theorem edge_start : + seamName colorAt ∘ P.grid.seamRank = (P.scheduling A sc).edge := by + have h (v : P.Occupied) : colorAt (P.grid.cellRank v) = (P.scheduling A sc).mark v := by + change colorAt (P.hostRank v.val.1) = schedulingTone (A.coord v).1 + rw [H.color] + exact Fin.ext (Nat.mod_eq_of_lt (schedulingTone (A.coord v).1).isLt) + funext j + simp only [Function.comp_apply, Grid.seamRank, seamName, Nat.unpair_pair, h] + rfl + +open scoped Classical in +theorem start_at (hr : P.LocalRanks) (c : P.Occupied) : + let i := A.coord c + (world).stored frame i = viewStart S hK ((z i.1).2 i.2) + (schedulingTone i.1) (aliasTone i.1) (fun j => (z ((z i.1).1 j)).2 i.2) + (fun j => schedulingTone ((z i.1).1 j)) (fun j => mobile (i.1, i.2, j)) (s c) := by + intro i + have info : (frame).info (world).size c = {(P.bootMark A sc c, + .inl ((P.kit sc hK c).program.labels))} := by + unfold Frame.info catalog + rw [show (frame).stage.footprint c = {.inl c} from rfl, image_singleton] + rfl + have tile := P.initial_tile sc hK hr (finiteName S.k) colorAt (P.bootMark A sc) s c + rw [H.seed_eq hr c, initialTile, P.edge_start A sc H] at tile + unfold Scenario.stored + erw [(world).π.records_at (world).c (world).pos (frame).record ((frame).info (world).size) c] + unfold Record.tile + rw [info] + dsimp only [viewStart] + erw [tile] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Exterior widths and port order at the named collectors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Coloring Assembly Sphere + +namespace Assembly.Scheme +variable {F : Type} (S : Scheme F) + +open scoped Classical in +/-- Width of the exposed part of a requested station and side. -/ +def extWidth (own : B S.ℓ) (slot : Option (B S.k)) (b : Bool) := + slot.elim 0 fun j => Fintype.card {i : (S.decode own).Pin j // + (S.decode own).peer j i.1 = none ∧ (S.decode own).direction j i.1 = b} + +open scoped Classical in +private abbrev Outside (r : S.format.obj) (v : S.Vtx) (b : Bool) := + {w : S.exposed r // w.val.1.1 = v ∧ S.direction r w.val.1 = b} + +open scoped Classical in +private theorem extWidth_eq (r : S.format.obj) (v : S.Vtx) (b : Bool) : + S.extWidth ((r v.1).2 v.2.1) (some v.2.2) b = Fintype.card (S.Outside r v b) := by + let Y := {i : S.LocalPin r v // (S.pattern r v).peer v.2.2 i.1 = none ∧ + (S.pattern r v).direction v.2.2 i.1 = b} + let f (i : Y) : S.Outside r v b := + ⟨⟨S.port r v i.val, by simp [port, peer, i.property.1]⟩, rfl, i.property.2⟩ + have bij : Function.Bijective f := by + constructor + · intro i j he + have h₁ : i.val.1 = j.val.1 := congrArg (fun w : S.Outside r v b => w.val.val.1.2) he + have h₂ : i.val.2.val = j.val.2.val := congrArg (fun w : S.Outside r v b + => w.val.val.2.val) he + exact Subtype.ext (Sigma.ext h₁ ((Fin.heq_ext_iff (congrArg _ h₁)).mpr h₂)) + · rintro ⟨⟨⟨⟨u, i⟩, j⟩, he⟩, hv, hd⟩ + change u = v at hv + subst u + have hp : (S.pattern r v).peer v.2.2 i = none := by simpa [peer] using he + exact ⟨⟨⟨i, j⟩, hp, hd⟩, rfl⟩ + exact Fintype.card_congr (Equiv.ofBijective f bij) + +namespace Presentation +variable {S} [Field F] {x y : Wire} {G : Diagram F x y} {r : S.format.obj} + (p : S.Presentation r G) (hd : p.Directed) +include hd + +open scoped Classical in +private theorem side_length {α : Type} (v : G.V) (b : Bool) (lift : α → slots x ⊕ slots y) + (l : List α) (hi : Function.Injective lift) (side : ∀ a, (lift a).isRight = b) + (onto : ∀ j, j.isRight = b → ∃ a, lift a = j) + (hn : l.Nodup) (hm : ∀ a, a ∈ l ↔ Packing.portEnd G (lift a) = v) : + l.length = Fintype.card (S.Outside r (p.vertex v) b) := by + have dir (i : slots x ⊕ slots y) : S.direction r (p.boundary i).val.1 = i.isRight := by + cases i <;> exact hd _ + let f (i : Fin l.length) : S.Outside r (p.vertex v) b := + ⟨p.boundary (lift (l.get i)), by rw [Sphere.Payload.owner, (hm _).mp (l.get_mem i)], + (dir _).trans (side _)⟩ + have bij : Function.Bijective f := by + constructor + · intro i j he + have eq : l.get i = l.get j := hi (p.boundary.injective (congrArg Subtype.val he)) + rcases lt_trichotomy i j with lt|rfl|gt + · exact ((List.pairwise_iff_get.mp hn) i j lt eq).elim + · rfl + · exact ((List.pairwise_iff_get.mp hn) j i gt eq.symm).elim + · rintro ⟨w, hv, hb⟩ + obtain ⟨j, rfl⟩ := p.boundary.surjective w + obtain ⟨a, rfl⟩ := onto j ((dir j).symm.trans hb) + rw [Sphere.Payload.owner] at hv + obtain ⟨i, rfl⟩ := List.get_of_mem ((hm a).mpr (p.vertex.injective hv)) + exact ⟨i, rfl⟩ + exact (Fintype.card_fin _).symm.trans (Fintype.card_congr (Equiv.ofBijective f bij)) + +open scoped Classical in +theorem exterior_width (v : G.V) (b : Bool) : + cond b (G.extRight v).length (G.extLeft v).length = + S.extWidth ((r (p.vertex v).1).2 (p.vertex v).2.1) (some (p.vertex v).2.2) b := by + rw [S.extWidth_eq] + cases b + · exact p.side_length hd v false Sum.inl _ Sum.inl_injective (fun _ => rfl) + (by rintro (a|b) <;> simp) (G.extLeft_nodup v) (G.mem_extLeft v) + · exact p.side_length hd v true Sum.inr _ Sum.inr_injective (fun _ => rfl) + (by rintro (a|b) <;> simp) (G.extRight_nodup v) (G.mem_extRight v) + +end Presentation +end Assembly.Scheme + +namespace Rounds.Input +open Surface Routing.Private +open Sphere.Layout (Place item) + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ H U : ℕ} {W : ℝ} (P : Input F x y h D T (d * b) g W) + (p : P.Tools K ℓ m) (s : P.Occupied → Shape (SphereScale.probes ℓ D) b d) + {z : P.Configuration p} (hz : (P.plant p s).Reach m (2 * g) H U z) + {S : Scheme F} {r : S.format.obj} {portal : S.Presentation r P.diagram} + {loc : P.Occupied ↪ B S.m × B S.h} {tone : B S.m → ℕ} {mobile : S.Vtx → Bool} + (placed : P.Placed portal loc tone mobile) +include placed + +open scoped Classical in +/-- An exterior wire stays with both of its station's ordered lists in the same cell. -/ +theorem keeps (e : slots x ⊕ slots y) : + let v := Packing.portEnd P.diagram e + ∃ i : Place z.scene.cell, loc i.1 = ((portal.vertex v).1, (portal.vertex v).2.1) ∧ + (P.inputPorts p s hz).ports i = P.diagram.extLeft v ∧ + (P.outputPorts p s hz).ports i = P.diagram.extRight v := by + intro v + let i := P.draw p s hz e + have name : (item z.scene.cell i).label.name = some v := P.draw_name p s hz e + have pos : P.grid.cell v = i.1 := (P.reached_name p s hz (List.get_mem _ i.2) name).2 + refine ⟨i, by rw [← pos, placed.location], ?_⟩ + change (item z.scene.cell i).label.name.elim [] P.diagram.extLeft = _ ∧ + (item z.scene.cell i).label.name.elim [] P.diagram.extRight = _ + simp only [name, Option.elim_some, and_self] + +open scoped Classical in +theorem portsWidth (hd : portal.Directed) (i : Place z.scene.cell) (bit : Bool) : + cond bit ((P.outputPorts p s hz).ports i).length ((P.inputPorts p s hz).ports i).length = + S.extWidth ((r (loc i.1).1).2 (loc i.1).2) + ((item z.scene.cell i).label.name.map (finiteName S.k ∘ P.stationRank)) bit := by + let n := (item z.scene.cell i).label.name + change cond bit (n.elim [] P.diagram.extRight).length (n.elim [] P.diagram.extLeft).length = + S.extWidth _ (n.map _) bit + cases he : n with + | none => cases bit <;> rfl + | some v => + have pos : P.grid.cell v = i.1 := (P.reached_name p s hz (List.get_mem _ i.2) he).2 + have name : finiteName S.k (P.stationRank v) = (portal.vertex v).2.2 := by + rw [placed.name] + exact Fin.ext (Nat.mod_eq_of_lt (portal.vertex v).2.2.isLt) + simp only [Option.elim_some, Option.map_some, Function.comp_apply, name, ← pos, + ← placed.location] + exact portal.exterior_width hd v bit + +end Rounds.Input +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- # The records consumed by the printer at the end of the waves -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Assembly Coloring Routing.Private Sphere SphereScale Surface Surface.Local + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h g ℓ D T b d p l j : ℕ} {W : ℝ} (S : Scheme F) + +local notation "Cfg" => design S g ℓ D b d p l + +open scoped Classical in +/-- Computes the panel keys by the application `Stamp a.Q a.waves a.U`. -/ +abbrev panelKeys (a : Surface.Local.Design) := Stamp a.Q a.waves a.U + +open scoped Classical in +/-- Retain the initial exterior widths and the final station and seam data. -/ +def panelFaces (menu : (Cfg).Menu F (B S.k) (B S.ℓ) j) (i : B j) : + Option (Print.Face F (d * b) d (Cfg).R (panelKeys Cfg) (B S.k)) := + (menu i).2.map fun v => ⟨S.extWidth (menu i).1, v.1, v.2.2.2⟩ + +open scoped Classical in +/-- The indexed operation `cast (congrArg₂ (fun v w => Option (Print.Face F v w (Cfg).R +(panelKeys Cfg) (B S.k))) ha hb) (panelFaces S menu i)`. -/ +def printMenu (menu : (Cfg).Menu F (B S.k) (B S.ℓ) j) {M r t : ℕ} + (ha : d * b = M * r) (hb : d = M * t) (i : B j) : + Option (Print.Face F (M * r) (M * t) (Cfg).R (panelKeys Cfg) (B S.k)) := + cast (congrArg₂ (fun v w => Option (Print.Face F v w (Cfg).R (panelKeys Cfg) (B S.k))) ha hb) + (panelFaces S menu i) + +variable {S} (P : Input F x y h D T (d * b) g W) + {z : S.format.obj} (A : P.HostChart S z) + (sc : Scales g ℓ D T (p ^ l) b d) (hK : Ready K ℓ D g (p ^ l) b d) + (s : P.Occupied → Shape (probes ℓ D) b d) + +local notation "kit" => P.kit sc hK +local notation "world" => P.localWorld A sc hK s + +open scoped Classical in +/-- Computes the final source by the application `P.shared kit s f.reach sc.Rpos`. -/ +abbrev finalSource (f : (world).At (Cfg).waves) := P.shared kit s f.reach sc.Rpos + +open scoped Classical in +theorem panelBounds (f : (world).At (Cfg).waves) : + P.FinalBounds (P.finalSource A sc hK s f) ℓ (p ^ l) := + P.final_bounds kit sc s f.stage f.reach f.stopped + +open scoped Classical in +/-- Computes the panel ext by the application `S.extWidth ((z (A.coord i).1).2 (A.coord i).2)`. -/ +def panelExt (i : P.Occupied) := S.extWidth ((z (A.coord i).1).2 (A.coord i).2) + +open scoped Classical in +/-- Embeds `(P.selectors kit).state v` into `ℕ`. -/ +def panelIndex (v : P.Occupied) : (P.selectors kit).state v ↪ ℕ := ⟨Fin.val, Fin.val_injective⟩ + +open scoped Classical in +/-- Uses `⟨P.panelExt A i, (world).π.mark i, f.record.tile (world).π.edge (f.info (world).size) +i⟩` as the representation. -/ +def panelFace (f : (world).At (Cfg).waves) (i : (world).V) : + Print.Face F (d * b) d (Cfg).R (panelKeys Cfg) (B S.k) := + ⟨P.panelExt A i, (world).π.mark i, f.record.tile (world).π.edge (f.info (world).size) i⟩ + +open scoped Classical in +theorem panel_read {menu : (Cfg).Menu F (B S.k) (B S.ℓ) j} + (f : (world).Code (Cfg).waves menu) (i : B S.m × B S.h) : + panelFaces S menu ((f.tape i.1).2 i.2) = (world).atlas.fill (P.panelFace A sc hK s f.frame) i + := by + unfold panelFaces + rw [f.read] + unfold Scenario.stored + by_cases hi : i ∈ Set.range (world).atlas.coord + · obtain ⟨v, rfl⟩ := hi + erw [Palette.records_at, Atlas.fill_at] + rfl + · erw [Palette.records_away _ _ _ _ _ hi, Atlas.fill_away _ _ hi] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Wave.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Wave.lean new file mode 100644 index 0000000000..243ae47157 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Panel/Wave.lean @@ -0,0 +1,1012 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Concentration.Kits +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.History +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import Mathlib.Data.Fintype.Card +public import Mathlib.Data.Finset.Card +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Compute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.View +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Reorder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Update + +/-! +# Emission of a terminal configuration + +Reindex the species into equally sized chunks, retain the selector and +motion wires inside each diagram, then pad and route the resulting +bundles on a common block host. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input.FinalBounds +open Sphere Surface Finset +open SphereScale (Scales chunks budget q) +open Sphere.Layout (Key Sharing Alphabet Place item) + +variable {F Z X : Type} [Field F] {x y : Wire} {H D T b d g r t ℓ m : ℕ} {W : ℝ} + {P : Input F x y H D T (d * b) g W} {Y : Alphabet P.Occupied} + +section Chunked +variable {z : Stage F (chunks ℓ D * r) (chunks ℓ D * t) Z P.Occupied P.grid.Seam X} + {A : Key.Source Y x y z} (h : P.FinalBounds A ℓ m) (sc : Scales g ℓ D T m b d) + +open scoped Classical in +/-- Builds `(Key.share z A).Geo P (Sharing.allocation g ℓ) where site` with the specified +`site`, `near`, `count`, `chunks`. -/ +abbrev geometry : (Key.share z A).Geo P (Sharing.allocation g ℓ) where + site := Function.Embedding.subtype _ + near e := ⟨(h.near e).1.symm, (h.near e).2⟩ + count v := (h.positions v).trans sc.room_le + chunks := sc.chunks_le + degree := (Sharing.Geo.Raw.slots_fit sc le_rfl).2.2 + frozen := P.fixed (z := z) + left := h.left + right := h.right + +omit [Field F] in +open scoped Classical in +theorem raw (ht : chunks ℓ D * t = d) : + (geometry h sc).Raw ℓ m b d z.scene.level + (fun i => thinStation (item z.scene.cell i)) (fun k => k.isLeft) := by + have hex (i : Place z.scene.cell) : (Key.share z A).exteriorLoad i = P.exterior A i := by + unfold Sharing.exteriorLoad exterior + congr! + refine ⟨?_, h.seams, h.seamEnergy, h.energy, h.collected, h.collectors, ?_, ?_, + h.light, h.heavy, h.aux, h.residue, ?_, ?_, ?_, ?_⟩ + · simpa only [Occupied, Fintype.card_coe] using P.occupied + · simpa only [hex] using h.extMax + · simpa only [hex] using h.extSquare + · exact fun v => (Key.card_filter _ _).trans (h.keys v) + · apply Key.width_le + · intro i + refine (h.selector i).trans (div_le_div_of_nonneg_right ?_ (by positivity)) + exact_mod_cast (Nat.le_mul_of_pos_right (d * b) sc.apos).trans sc.lower + · intro j hj + rw [ht] + exact sc.hidden_width j (h.hidden j hj) + · rintro (v | j) hj + · exact h.selector v + · contradiction + · intro i hi j hj + have hh := hi.2 _ (Key.mem_filter.mp hj) + cases j <;> exact hh + +end Chunked + +variable {z : Stage F r t Z P.Occupied P.grid.Seam X} {A : Key.Source Y x y z} + +open scoped Classical in +/-- Uses `inferInstance` as the representation. -/ +abbrev profileType {E V : Type} [Fintype E] [Fintype V] {M r t : ℕ} + (C : V → Surface.Cell F (M * r) (M * t) Z E X) (e : E → ℕ) : + Fintype (Layout.Profile C e) := inferInstance + +open scoped Classical in +theorem emit (h : P.FinalBounds A ℓ m) (sc : Scales g ℓ D T m b d) + {r' t' a u : ℕ} (hr : r = chunks ℓ D * r') (ht : t = chunks ℓ D * t') + (ha : r = d * b) (hb : t = d) (hD : D = 2 ^ a) (hu : 0 < u) + (hu' : u * D ^ (terminalExponent g ℓ) ≤ T) : + ∃ (I : Type) (_ : Fintype I) (Q : I → LocalTerm F x y H u) (c : I → F), + Fintype.card I ≤ P.termsBound ℓ m ∧ + (∀ x y, ∑ i, c i * (Q i).diagram.eval x y = ∑ j, z.value m (A.init x y j)) ∧ + ∀ i, Concentrated P (Q i) (terminalExponent g ℓ) a ℓ := by + subst r t + have hD' : 4 ≤ D := le_trans (by decide) sc.bound + let G := geometry h sc + have hraw := raw h sc hb + have hc := hraw.budgets sc ha hb rfl le_rfl a + let I := Layout.Profile z.scene.cell z.scene.level + refine ⟨I, profileType _ _, fun p => G.output hD hD' p m hu, Layout.Profile.sign, + hraw.term_count sc rfl h.positions, ?_, ?_⟩ + · intro x y + have he := G.sum_output hD hD' (e := z.scene.level) m hu x y + refine he.trans ?_ + have ht := Key.sum_stack Y (chunks ℓ D * t') z.hidden (A.init x y) (z.scene.value m) + refine Eq.trans ?_ (ht.trans ?_) + · exact sum_congr (by ext; simp) (fun _ _ => rfl) + · exact sum_congr (by ext; simp) (fun _ _ => rfl) + · exact fun p => G.concentrated hD hD' hc p m hu le_rfl hu' + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input.FinalBounds +end + +/- # The terminal diagrams of a local expansion -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +open Sphere Surface SphereScale Finset + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {h D T b d g m ℓ : ℕ} {W : ℝ} (P : Input F x y h D T (d * b) g W) + (p : P.Tools K ℓ m) (sc : Scales g ℓ D T m b d) + +open scoped Classical in +theorem final_bounds (s : P.Occupied → Routing.Private.Shape (probes ℓ D) b d) + (z : P.Configuration p) + (hz : (P.plant p s).Reach m (2 * g) (SphereScale.energy ℓ D (d * b)) (D ^ 5) z) + (hs : z.Stopped) : P.FinalBounds (P.shared p s hz sc.Rpos) ℓ m := by + let A := P.shared p s hz sc.Rpos + have hlarge : 100 ≤ budget g := (by have := budget_large g; omega) + have hW : 0 ≤ W := le_trans (by positivity) P.occupied + have hb : P.FinalBounds A ℓ m := by + refine P.reached_bounds p s sc hz hs A (fun _ => rfl) (fun _ => rfl) + (fun i => P.draw_collector p s hz (.inl i)) (fun i => P.draw_collector p s hz (.inr i)) + ?_ ?_ (P.selector_le p sc) + · intro i _ + have he : P.drawLoad p s hz i ≤ 100 * D * T := by exact_mod_cast P.draw_max p s hz i + exact he.trans (by gcongr) + · have he := P.draw_fixed_squares p s hz + refine le_trans ?_ (show W * T ≤ budget g * W * T by + gcongr + exact le_mul_of_one_le_left hW (by exact_mod_cast (show 1 ≤ budget g by omega))) + refine le_trans (le_of_eq ?_) he + let e : {i : Layout.Place z.scene.cell // P.fixed i} ≃ + {i : Layout.Place z.scene.cell // (Layout.item z.scene.cell i).label.role = .collector} := + Equiv.refl _ + exact Fintype.sum_equiv e (fun i => (P.exterior A i.val : ℝ) ^ 2) + (fun i => (P.drawLoad p s hz i.val : ℝ) ^ 2) (fun _ => rfl) + exact hb + +include sc in +open scoped Classical in +theorem terminal {a : ℕ} (hD : D = 2 ^ a) {u : ℕ} (hu : 0 < u) + (hu' : u * D ^ (terminalExponent g ℓ) ≤ T) : + ∀ s (z : P.Configuration p), + (P.plant p s).Reach m (2 * g) (SphereScale.energy ℓ D (d * b)) (D ^ 5) z → + z.Stopped → P.Emitted p z u (terminalExponent g ℓ) a := by + intro s z hz hs + have hb := P.final_bounds p sc s z hz hs + obtain ⟨j, hj⟩ := sc.divides + have hdb : d * b = chunks ℓ D * (j * b) := by rw [hj, mul_assoc] + exact hb.emit sc hdb hj rfl rfl hD hu hu' + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Uniform local concentration from the sphere price -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds + +open Filter + +/-- The host bound is chosen before the subdivision, the field threshold +before the scale, and the packet width before the diagram. -/ +theorem local_law {k : Type} [Field k] [Finite k] + (sync : Prices.SharedPrice (AlgebraicClosure k)) (ℓ : ℕ) : LocalLaw k ℓ := by + intro g _ + refine ⟨Input.terminalExponent g ℓ, ?_⟩ + filter_upwards [eventually_ge_atTop (2 * SphereScale.budget g)] with a ha + let D := 2 ^ a + have hD : 2 * SphereScale.budget g ≤ D := ha.trans Nat.lt_two_pow_self.le + obtain ⟨K, _, _, _, p, l, b, _, _, hc⟩ := SphereScale.choose (ℓ := ℓ) k sync hD + obtain ⟨A, hA⟩ := SphereScale.stack g ℓ D (p ^ l) b + refine ⟨A, K, inferInstance, inferInstance, inferInstance, ?_⟩ + filter_upwards [hc] with T hT + obtain ⟨d, sc, hK⟩ := hT + refine ⟨d * b, sc.Rpos, sc.smallR, ?_⟩ + intro F _ _ _ hF u hu hu' x y h W P + have : CharP F p := charP_of_injective_algebraMap' K p + obtain ⟨kit⟩ := P.tools_exist sc hK + exact hA sc F K p l rfl hF P kit u _ a + (fun s z reaches _ stopped => P.terminal kit sc rfl hu hu' s z reaches stopped) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Finset Function + +variable {V : Type} [Fintype V] + +open scoped Classical in +omit [Fintype V] in +/-- A symmetric family of closed neighborhoods admits a coloring +with one color per possible neighbor. -/ +theorem distinguish [Finite V] (B : V → Finset V) (d : ℕ) (hd : ∀ i, (B i).card ≤ d) + (sym : ∀ i j, j ∈ B i → i ∈ B j) : + ∃ color : V → Fin (d + 1), ∀ i j, j ∈ B i → color i = color j → i = j := by + let : Fintype V := Fintype.ofFinite V + have h (s : Finset V) : ∃ color : V → Fin (d + 1), + ∀ i ∈ s, ∀ j ∈ s, j ∈ B i → color i = color j → i = j := by + induction s using Finset.induction_on with + | empty => exact ⟨fun _ => 0, by simp⟩ + | @insert a s ha ih => + obtain ⟨f, hf⟩ := ih + have bound : ((B a).image f).card < (univ : Finset (Fin (d + 1))).card := by + rw [card_univ, Fintype.card_fin] + exact Nat.lt_succ_of_le (card_image_le.trans (hd a)) + obtain ⟨c, _, hc⟩ := exists_mem_notMem_of_card_lt_card bound + refine ⟨update f a c, fun i hi j hj hm h => ?_⟩ + by_cases h₁ : i = a + · subst i + by_contra ne + rw [update_self, update_of_ne (Ne.symm ne)] at h + exact hc (h.symm ▸ mem_image_of_mem f hm) + by_cases h₂ : j = a + · subst j + rw [update_self, update_of_ne h₁] at h + exact (hc (h ▸ mem_image_of_mem f (sym i a hm))).elim + rw [update_of_ne h₁, update_of_ne h₂] at h + exact hf i ((mem_insert.mp hi).resolve_left h₁) j ((mem_insert.mp hj).resolve_left h₂) hm h + obtain ⟨f, hf⟩ := h univ + exact ⟨f, fun i j => hf i (mem_univ i) j (mem_univ j)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +open Coloring Finset +variable {m d : ℕ} (g : B m → B d → B m) + +open scoped Classical in +/-- Computes the ball by the application `univ.image (expand r g x)`. -/ +def ball (r : ℕ) (x : B m) := univ.image (expand r g x) + +open scoped Classical in +theorem mem_ball (r : ℕ) (x y : B m) : y ∈ ball g r x ↔ Reach g r x y := by + simp only [ball, mem_image, mem_univ, true_and, mem] + +open scoped Classical in +theorem card_ball (r : ℕ) (x : B m) : (ball g r x).card ≤ 2 ^ ((d + 1) * r) := by + exact card_image_le.trans_eq (by simp) + +open scoped Classical in +theorem color (r : ℕ) (hg : ∀ i j, g i j ≠ i → ∃ l, g (g i j) l = i) : + ∃ c : B m → Fin (2 ^ ((d + 1) * r) + 1), ∀ i j, Reach g r i j → c i = c j → i = j := by + have h := Sphere.Surface.Local.distinguish (ball g r) _ (card_ball g r) + (fun i j h => (mem_ball _ _ _ _).mpr (((mem_ball _ _ _ _).mp h).symm hg)) + simpa only [mem_ball] using h + +open scoped Classical in +theorem Reach.join {g : B m → B d → B m} {x y z : B m} {r t : ℕ} + (h : Reach g r x y) (h' : Reach g t y z) : Reach g (r + t) x z := by + induction r generalizing x with + | zero => simpa [show x = y from h] using h' + | succ r ih => + obtain ⟨u, hx, hu⟩ := h + rw [Nat.succ_add] + exact ⟨u, hx, ih hu⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +end + +section +/- +# Local coordinates on a host shared by independent networks + +An occupied vertex is a host position and a block number. Different +blocks never share a seam. Colors distinguish the bounded neighborhood +of each host position independently of the number of blocks. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Coloring Assembly + +/-- The data for the atlas construction, including `coord`, `graph`, `reciprocal`, `src`, `dst`. -/ +structure Atlas (V E : Type) (m d h : ℕ) where + /-- Embeds the coordinates as `V ↪ B m × B h`. -/ + coord : V ↪ B m × B h + /-- The `Atlas` component of type `B m → B d → B m`. -/ + graph : B m → B d → B m + reciprocal : ∀ i j, graph i j ≠ i → ∃ l, graph (graph i j) l = i + /-- Assigns the source of each connection. -/ + src : E → V + /-- Assigns the destination of each connection. -/ + dst : E → V + links : Function.Injective (fun i => (src i, dst i)) + adjacent : ∀ i, (coord (src i)).2 = (coord (dst i)).2 ∧ + ∃ j, graph (coord (src i)).1 j = (coord (dst i)).1 + +variable {V E : Type} {m d h q R : ℕ} + +namespace Atlas + +variable (a : Atlas V E m d h) + +/-- Requires `(a.coord x).2 = (a.coord y).2 ∧ Neighborhood.Reach a.graph R (a.coord x).1 +(a.coord y).1`. -/ +def near (R : ℕ) (x y : V) : Prop := + (a.coord x).2 = (a.coord y).2 ∧ Neighborhood.Reach a.graph R (a.coord x).1 (a.coord y).1 + +theorem near.refl (R : ℕ) (x : V) : a.near R x x := + ⟨rfl, Neighborhood.Reach.refl _ _ _⟩ + +theorem near_edge (i : E) : a.near 1 (a.src i) (a.dst i) := + ⟨(a.adjacent i).1, _, .inr (a.adjacent i).2, rfl⟩ + +variable {a} {x y z : V} {r s : ℕ} + +theorem near.symm (e : a.near r x y) : a.near r y x := + ⟨e.1.symm, e.2.symm a.reciprocal⟩ + +theorem near.join (e : a.near r x y) (f : a.near s y z) : a.near (r + s) x z := + ⟨e.1.trans f.1, e.2.join f.2⟩ + +theorem near.mono (e : a.near r x y) (h : r ≤ s) : a.near s x y := by + obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le h + exact e.join (.refl a k y) + +end Atlas + +/-- The data for the palette construction, including `color`, `valid`. -/ +structure Palette (a : Atlas V E m d h) (R q : ℕ) where + /-- The `Palette` component of type `B m → Fin q`. -/ + color : B m → Fin q + valid : ∀ x y, Neighborhood.Reach a.graph R x y → color x = color y → x = y + +theorem Atlas.palette (a : Atlas V E m d h) (R : ℕ) : + Nonempty (Palette a R (2 ^ ((d + 1) * R) + 1)) := by + obtain ⟨c, h⟩ := Neighborhood.color a.graph R a.reciprocal + exact ⟨c, h⟩ + +namespace Palette +variable {a : Atlas V E m d h} (c : Palette a R q) + +/-- Computes the mark by the application `c.color (a.coord v).1`. -/ +def mark (v : V) := c.color (a.coord v).1 + +/-- The value specified by `(c.mark (a.src i), c.mark (a.dst i))`. -/ +def edge (i : E) := (c.mark (a.src i), c.mark (a.dst i)) + +theorem distinguish {x y : V} (h : a.near R x y) (e : c.mark x = c.mark y) : x = y := + a.coord.injective (Prod.ext (c.valid _ _ h.2 e) h.1) + +theorem injective_at {x u v : V} {r : ℕ} (h : r + r ≤ R) + (hu : a.near r x u) (hv : a.near r x v) (e : c.mark u = c.mark v) : u = v := + c.distinguish ((hu.symm.join hv).mono h) e + +end Palette +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# A unique coloring certified by local predecessor checks + +At each host the choice of a fresh color depends only on colors +at smaller neighboring addresses. Uniqueness avoids a multiplicity +factor when the certificate is summed in positive characteristic. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood + +open Finset Coloring + +variable {m d q : ℕ} + +theorem free (f : B q → Option (B (q + 1))) : ∃ c, ∀ j, f j ≠ some c := by + let v j := (f j).getD 0 + have bound : (univ.image v).card < (univ : Finset (B (q + 1))).card := by + apply card_image_le.trans_lt + simp [pow_succ] + obtain ⟨c, _, h⟩ := exists_mem_notMem_of_card_lt_card bound + refine ⟨c, fun j e => h (mem_image.mpr ⟨j, mem_univ _, ?_⟩)⟩ + simp only [v, e, Option.getD_some] + +/-- The value specified by `(free f).choose`. -/ +def choose (f : B q → Option (B (q + 1))) : B (q + 1) := (free f).choose + +/-- The quantity computed by `2 ^ ((d + 1) * r + 1)`. -/ +abbrev paletteSize (d r : ℕ) := 2 ^ ((d + 1) * r + 1) + +variable (g : B m → B d → B m) (r : ℕ) + +/-- The value specified by `choose fun j => if _h : expand r g i j < i then some (tone (expand r +g i j)) else none`. -/ +def tone (i : B m) : Fin (paletteSize d r) := + choose fun j => if _h : expand r g i j < i then some (tone (expand r g i j)) else none +termination_by i.val + +/-- Requires `t i = choose fun j => if expand r g i j < i then some (t (expand r g i j)) else +none`. -/ +def correct (t : B m → Fin (paletteSize d r)) (i : B m) : Prop := + t i = choose fun j => if expand r g i j < i then some (t (expand r g i j)) else none + +theorem tone_correct (i : B m) : correct g r (tone g r) i := by + unfold correct + conv_lhs => rw [tone] + rfl + +theorem correct_iff (t : B m → Fin (paletteSize d r)) : + (∀ i, correct g r t i) ↔ t = tone g r := by + constructor + · intro h + funext i + induction i using WellFoundedLT.induction with + | ind i ih => + rw [show t i = _ from h i, show tone g r i = _ from tone_correct g r i] + congr 1 + funext j + split_ifs with he + · rw [ih _ he] + · rfl + · rintro rfl; exact tone_correct g r + +theorem tone_separates (reciprocal : ∀ i j, g i j ≠ i → ∃ k, g (g i j) k = i) (i j : B m) + (edge : Reach g r i j) (he : tone g r i = tone g r j) : i = j := by + have diff (i j : B m) (h : Reach g r i j) (lt : j < i) : tone g r i ≠ tone g r j := by + obtain ⟨k, hk⟩ := mem.mpr h + let f l := if expand r g i l < i then some (tone g r (expand r g i l)) else none + intro eq + have bad := (free f).choose_spec k + change f k ≠ some (choose f) at bad + apply bad + rw [show choose f = tone g r i from (tone_correct g r i).symm, eq] + simp [f, hk, lt] + rcases lt_trichotomy i j with h|h|h + · exact (diff j i (edge.symm reciprocal) h he.symm).elim + · exact h + · exact (diff i j edge h he).elim + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +end + +/- # Preparing the local checks of a guessed host coloring -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +open Coloring +variable {m q d t : ℕ} (F : Type) [Field F] + +/-- The quantity computed by `Format.vec m (.addr (q + 1))`. -/ +abbrev Colors (m q : ℕ) := Format.vec m (.addr (q + 1)) +/-- The quantity computed by `Format.pair .bit (.addr (q + 1))`. -/ +abbrev Entry (q : ℕ) := Format.pair .bit (.addr (q + 1)) +/-- Computes the check by the application `Format.vec q (Entry q)`. -/ +abbrev Check (q : ℕ) := Format.vec q (Entry q) +/-- Computes the checks by the application `Format.vec m (Check q)`. -/ +abbrev Checks (m q : ℕ) := Format.vec m (Check q) + +/-- Evaluates `(decide (x.1 i j < x.1 i 0), x.2 (x.1 i j))` at the input `i j`. -/ +def previous (x : (Rows m q).obj × (Colors m q).obj) : (Checks m q).obj := + fun i j => (decide (x.1 i j < x.1 i 0), x.2 (x.1 i j)) + +private theorem cheap_previous (hm : m ≤ t) (hq : 2 ^ q ≤ t) : + Cheap F m t (.pair (Rows m q) (Colors m q)) (Checks m q) previous 22 := by + let A := Format.pair (Rows m q) (Colors m q) + have hq' : q + 1 ≤ t := Nat.lt_two_pow_self.trans_le hq + have hw : A.width ≤ 2 ^ m * (100 + t) ^ 3 := by + simp only [A, Rows, Colors, Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add] + rw [Format.width_addr] + refine Nat.mul_le_mul_left _ ((Nat.add_le_add (Nat.mul_le_mul hq hm) hq').trans ?_) + ring_nf; omega + have base := Cheap.id F hw + have col (i : B q) := base.fst.comp (column F hm hq i) + have get := Cheap.lookup F m t (.addr (q + 1)) hm (by rw [Format.width_addr]; exact hq') + have lt : Cheap F 0 t (.pair (.addr m) (.addr m)) .bit (fun z => decide (z.1 < z.2)) 3 := by + refine ⟨_, numeric_lt F m, ?_⟩ + rw [Format.width_pair, Format.width_addr, Format.width_bit] + ring_nf; omega + have bit (i : B q) : Cheap F m t A (.vec m (Entry q)) (fun x j => previous x j i) 16 := by + have read := (base.snd.pair (col i)).comp get + have test := ((col i).pair (col 0)).zip.comp (Cheap.map _ fun _ => lt) + exact (test.pair read).zip.mono (by decide) + have all := Cheap.share _ bit hq + let B := Format.vec q (.vec m (Entry q)) + have bounds : (Checks m q).width ≤ 2 ^ m * (100 + t) ^ 3 := by + simp only [Checks, Check, Entry, Format.width_vec, Format.width_pair] + rw [Format.width_bit, Format.width_addr] + apply Nat.mul_le_mul_left + refine (Nat.mul_le_mul hq (Nat.add_le_add_left hq' 1)).trans ?_ + ring_nf; omega + have hb : B.width = (Checks m q).width := by simp only [B, Checks, Check, Format.width_vec]; ring + have flip : Cheap F m t B (Checks m q) (fun a i j => a j i) 4 := + Cheap.project F (hb.le.trans bounds) bounds (fun z => (z.2.1, z.1, z.2.2)) (fun _ _ => rfl) + exact (all.comp flip).mono (by decide) + +/-- The value specified by `previous (expand r x.1, x.2)`. -/ +def prepareColor (r : ℕ) (x : (Rows m d).obj × (Colors m ((d + 1) * r)).obj) := + previous (expand r x.1, x.2) + +theorem cheap_color (m d r : ℕ) (hr : 0 < r) : + Cheap F m (m + 2 ^ ((d + 1) * r)) (.pair (Rows m d) (Colors m ((d + 1) * r))) + (Checks m ((d + 1) * r)) (prepareColor r) 210 := by + let q := (d + 1) * r + let t := m + 2 ^ q + have hm : m ≤ t := Nat.le_add_right _ _ + have hq : 2 ^ q ≤ t := Nat.le_add_left _ _ + have hd : 2 ^ d ≤ t := (Nat.pow_le_pow_right (by decide) (show d ≤ q from + (Nat.le_succ d).trans (Nat.le_mul_of_pos_right _ hr))).trans hq + have hw : (Format.pair (Rows m d) (Colors m q)).width ≤ 2 ^ m * (100 + t) ^ 3 := by + simp only [Rows, Colors, Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add] + rw [Format.width_addr] + refine Nat.mul_le_mul_left _ ((Nat.add_le_add (Nat.mul_le_mul hd hm) + (Nat.lt_two_pow_self.trans_le hq)).trans ?_) + ring_nf; omega + have base := Cheap.id F hw + have h := ((base.fst.comp (cheap F m d r hr)).pair base.snd).comp (cheap_previous F hm hq) + exact h.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +end + +/- # An exact host-coloring network with no high-arity labels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +open Coloring Finset + +variable {F : Type} [Field F] {u m d q r : ℕ} {L : Set (Table F)} + +open scoped Classical in +private def colorOf (a : (Check q).obj) : (Format.addr (q + 1)).obj := (a 0).2 + +open scoped Classical in +private def weight (a : (Check q).obj) : F := + if colorOf a = choose (fun i => if (a i).1 then some (a i).2 else none) then 1 else 0 + +open scoped Classical in +private theorem weight_spec (g : (Rows m d).obj) (t : (Colors m ((d + 1) * r)).obj) (i : B m) : + weight (F := F) (prepareColor r (g, t) i) = if correct g r t i then 1 else 0 := by + by_cases h : correct g r t i + · rw [ite_eq_left h, weight, ite_eq_left] + simp only [colorOf, prepareColor, previous, origin, decide_eq_true_eq] + exact h + · rw [ite_eq_right h, weight, ite_eq_right] + simp only [colorOf, prepareColor, previous, origin, decide_eq_true_eq] + exact h + +open scoped Classical in +private theorem weights (g : (Rows m d).obj) (t : (Colors m ((d + 1) * r)).obj) : + ∏ i, weight (F := F) (prepareColor r (g, t) i) = if t = tone g r then 1 else 0 := by + simp only [weight_spec (F := F) g t] + by_cases h : t = tone g r + · simp [h, tone_correct] + rw [ite_eq_right h, ← correct_iff] at * + push Not at h + obtain ⟨i, hi⟩ := h + exact prod_eq_zero (mem_univ i) (ite_eq_right hi) + +open scoped Classical in +private theorem small {A B : Format} (hu : 3 ≤ u) (f : A.obj → B.obj → F) : + Kernel F u L A B f (32 * 2 ^ (A.width + B.width)) := by + intro a b i j + obtain ⟨v, h, hv⟩ := Net.dense a b (fun x y => f (view A i x) (view B j y)) + obtain ⟨s, hs, h⟩ := h.includeWide (L := L) hu + have ha := (Fintype.card_congr i).trans (card_slots a) + have hb := (Fintype.card_congr j).trans (card_slots b) + exact ⟨s, by rw [← ha, ← hb] at hv; unfold Format.width; omega, h⟩ + +open scoped Classical in +private theorem small_action {A B : Format} (hu : 3 ≤ u) (f : A.obj → B.obj) (w : A.obj → F) : + Action F u L A B f w (32 * 2 ^ (A.width + B.width)) := small hu _ + +open scoped Classical in +private theorem collapse {A C : Format} (hu : 3 ≤ u) (f : A.obj → C.obj) + {a : (A.pair C).obj → C.obj} {w : (A.pair C).obj → F} {n : ℕ} + (h : Action F u L (A.pair C) C a w n) + (ha : ∀ x y, a (x, y) = y) (hw : ∀ x y, w (x, y) = if y = f x then 1 else 0) : + Map F u L A C f (n + 4 * C.width) := by + let _ := Fintype.ofFinite C.obj + have hs := Kernel.sum_hidden hu h + simp only [ha, hw, sum_ite_eq', mem_univ, ite_true] at hs + simpa only [Map, eq_comm] using hs + +open scoped Classical in +/-- The bound obtained by adding the component charges `let q := (d + 1) * r 4 * (2 ^ m * (100 + +(m + 2 ^ q)) ^ 210) + 2 ^ m * (32 * 2 ^ ((Check q).width + q + 1)) + 4 * (Colors m +q).width`. -/ +def paintCost (m d r : ℕ) := + let q := (d + 1) * r + 4 * (2 ^ m * (100 + (m + 2 ^ q)) ^ 210) + 2 ^ m * (32 * 2 ^ ((Check q).width + q + 1)) + + 4 * (Colors m q).width + +open scoped Classical in +/-- Only the host count, not the number of blocks, multiplies the +long-address work. Invalid colorings have weight zero. -/ +theorem paint (m d r : ℕ) (hr : 0 < r) (hu : 3 ≤ u) : + Map F u L (Rows m d) (Colors m ((d + 1) * r)) (fun g => tone g r) (paintCost m d r) := by + let q := (d + 1) * r + let A := Rows m d + let C := Colors m q + let D := Format.addr (q + 1) + let B := Check q + obtain ⟨n, h, hn⟩ := cheap_color F m d r hr + have step : Action F u L B D colorOf weight (32 * 2 ^ (B.width + q + 1)) := by + rw [Nat.add_assoc, ← show D.width = q + 1 from Format.width_addr _] + exact small_action hu _ _ + have cells := Action.vec (A := B) (B := D) (fun _ : Coloring.B m => colorOf) + (fun _ => weight) (fun _ => step) + have both := cells.pre (Map.circuit (L := L) hu h) + have size : 4 * n + 2 ^ m * (32 * 2 ^ (B.width + q + 1)) + 4 * C.width ≤ paintCost m d r := by + unfold paintCost; dsimp only [B, C, q]; omega + apply Map.mono (collapse (A := A) (C := C) hu (fun g => tone g r) both ?_ ?_) size + · intro g t + funext i + simp only [Function.comp_apply, colorOf, prepareColor, previous, origin] + · intro g t + simp only [Function.comp_apply, weights] + by_cases h : t = tone g r + · rw [ite_eq_left h, ite_eq_left h] + · rw [ite_eq_right h, ite_eq_right h] + +end MatrixMultiplicationAllFields.MatrixExponent.Assembly.Neighborhood +end + +/- # Naming occupied vertices and their incident seams by local colors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset +variable {V E : Type} {m d h q R U : ℕ} {a : Atlas V E m d h} + +open scoped Classical in +/-- The value specified by `a.near U v (a.src i) ∨ a.near U v (a.dst i)`. -/ +def Atlas.touches (a : Atlas V E m d h) (U : ℕ) (v : V) (i : E) := + a.near U v (a.src i) ∨ a.near U v (a.dst i) + +open scoped Classical in +theorem Atlas.touches.near {v : V} {i : E} (h : a.touches U v i) : + a.near (U + 1) v (a.src i) ∧ a.near (U + 1) v (a.dst i) := by + rcases h with h | h + · exact ⟨h.mono (by omega), h.join (a.near_edge i)⟩ + · exact ⟨h.join (a.near_edge i).symm, h.mono (by omega)⟩ + +variable [Fintype V] [Fintype E] + +open scoped Classical in +/-- The selected finite family `(univ.filter p).image f`. -/ +def names {B : Type} (f : V → B) (p : V → Prop) := (univ.filter p).image f + +open scoped Classical in +theorem mem_names {B : Type} {f : V → B} {p : V → Prop} {b : B} : + b ∈ names f p ↔ ∃ x, p x ∧ f x = b := by simp [names] + +open scoped Classical in +/-- Embeds `↥(names f p)` into `V where toFun i`. -/ +def address {B : Type} (f : V → B) (p : V → Prop) : ↥(names f p) ↪ V where + toFun i := (mem_names.mp i.property).choose + inj' i j h := Subtype.ext ((mem_names.mp i.property).choose_spec.2.symm.trans + ((congrArg f h).trans (mem_names.mp j.property).choose_spec.2)) + +open scoped Classical in +private theorem addr_spec {B : Type} (f : V → B) (p : V → Prop) (i : names f p) : + p (address f p i) ∧ f (address f p i) = i.val := (mem_names.mp i.property).choose_spec + +namespace Palette + +variable (c : Palette a R q) (U : ℕ) (v : V) + +open scoped Classical in +/-- Computes the vertices by the application `names c.mark (a.near U v)`. -/ +def vertices := names c.mark (a.near U v) +open scoped Classical in +/-- Computes the labels by the application `names c.edge (a.touches U v)`. -/ +def labels := names c.edge (a.touches U v) +open scoped Classical in +/-- Computes the vertex by the application `address c.mark (a.near U v)`. -/ +def vertex : ↥(c.vertices U v) ↪ V := address c.mark (a.near U v) +open scoped Classical in +/-- Computes the seam by the application `address c.edge (a.touches U v)`. -/ +def seam : ↥(c.labels U v) ↪ E := address c.edge (a.touches U v) + +open scoped Classical in +/-- Uses `⟨c.mark v, mem_names.mpr ⟨v, .refl _ _ _, rfl⟩⟩` as the representation. -/ +def center : c.vertices U v := ⟨c.mark v, mem_names.mpr ⟨v, .refl _ _ _, rfl⟩⟩ + +omit [Fintype E] in +open scoped Classical in +theorem vertex_spec (j : c.vertices U v) : + a.near U v (c.vertex U v j) ∧ c.mark (c.vertex U v j) = j.val := addr_spec _ _ j + +omit [Fintype V] in +open scoped Classical in +theorem seam_spec (j : c.labels U v) : + a.touches U v (c.seam U v j) ∧ c.edge (c.seam U v j) = j.val := addr_spec _ _ j + +variable {U v} (hr : 2 * U + 2 ≤ R) +include hr + +omit [Fintype E] in +open scoped Classical in +theorem center_eq : c.vertex U v (c.center U v) = v := + c.injective_at (by omega) (c.vertex_spec ..).1 (.refl _ _ _) (c.vertex_spec ..).2 + +omit [Fintype E] in +open scoped Classical in +theorem vertex_range {w : V} : w ∈ Set.range (c.vertex U v) ↔ a.near U v w := by + constructor + · rintro ⟨i, rfl⟩; exact (c.vertex_spec ..).1 + · intro hw + let j : c.vertices U v := ⟨c.mark w, mem_names.mpr ⟨w, hw, rfl⟩⟩ + exact ⟨j, c.injective_at (by omega) (c.vertex_spec ..).1 hw (c.vertex_spec ..).2⟩ + +omit [Fintype V] in +open scoped Classical in +theorem seam_range {i : E} : i ∈ Set.range (c.seam U v) ↔ a.touches U v i := by + constructor + · rintro ⟨j, rfl⟩; exact (c.seam_spec ..).1 + · intro hi + let j : c.labels U v := ⟨c.edge i, mem_names.mpr ⟨i, hi, rfl⟩⟩ + obtain ⟨hj, he⟩ := c.seam_spec U v j + refine ⟨j, a.links (Prod.ext ?_ ?_)⟩ + · exact c.injective_at (by omega) hj.near.1 hi.near.1 (congrArg Prod.fst he) + · exact c.injective_at (by omega) hj.near.2 hi.near.2 (congrArg Prod.snd he) + +open scoped Classical in +/-- Initiators of the same color have no shared vertex or incident seam. -/ +theorem separate {w : V} (hn : v ≠ w) (he : c.mark v = c.mark w) : + Disjoint (Set.range (c.vertex U v)) (Set.range (c.vertex U w)) ∧ + Disjoint (Set.range (c.seam U v)) (Set.range (c.seam U w)) := by + have no (z : V) (h : a.near (U + 1) v z) (k : a.near (U + 1) w z) : False := + hn (c.distinguish ((h.join k.symm).mono (by omega)) he) + refine ⟨Set.disjoint_left.mpr (fun z h k => ?_), Set.disjoint_left.mpr (fun j h k => ?_)⟩ + · exact no z (((c.vertex_range hr).mp h).mono (by omega)) (((c.vertex_range hr).mp k).mono (by + omega)) + · exact no _ ((c.seam_range hr).mp h).near.1 ((c.seam_range hr).mp k).near.1 + +end Palette +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Restricting the motion data to a colored neighborhood -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset +variable {F V E K N T X J L : Type} {r t m d h q R U g : ℕ} + {a : Atlas V E m d h} + +open scoped Classical in +/-- The data for the incident construction, including `loopless`, `endpoints`. -/ +structure Incident (G : Record F r t V E K N) (a : Atlas V E m d h) : Prop where + loopless : ∀ e, a.src e ≠ a.dst e + endpoints : ∀ v e, e ∈ (G.ports v).map Prod.fst ↔ a.src e = v ∨ a.dst e = v + +open scoped Classical in +theorem Matches.incident {G : Record F r t V E K N} {ref : Reference J L N V E T X} + {β : V ⊕ ℕ → K} {s : Stage F r t T V E X} (h : Matches ref.world β s G) + (hl : s.Layout a.src a.dst g) : Incident G a := by + refine ⟨hl.loopless, fun v e => ?_⟩ + have he := h.ports v + change s.ports v = (G.ports v).map id at he + rw [List.map_id] at he + rw [← he] + exact hl.incident v e + +namespace Palette + +variable [Fintype V] [Fintype E] (c : Palette a R q) (U : ℕ) (v : V) + +open scoped Classical in +/-- The value specified by `Record F r t ↥(c.vertices U v) ↥(c.labels U v) K N`. -/ +abbrev Region (F : Type) (r t : ℕ) (K N : Type) := + Record F r t ↥(c.vertices U v) ↥(c.labels U v) K N + +open scoped Classical in +/-- The selected finite family `l.filterMap (fun y => if h : c.edge y.1 ∈ c.labels U v then some +(⟨c.edge y.1, h⟩, y.2) else none)`. -/ +def localPorts (l : List (E × F)) : List (↥(c.labels U v) × F) := + l.filterMap (fun y => if h : c.edge y.1 ∈ c.labels U v then some (⟨c.edge y.1, h⟩, y.2) else none) + +open scoped Classical in +/-- Builds `c.Region U v F r t K N where rows i` with the specified `rows`, `ports`, `level`, +`footprint`. -/ +def extract (G : Record F r t V E K N) : c.Region U v F r t K N where + rows i := G.rows (c.vertex U v i) + ports i := c.localPorts U v (G.ports (c.vertex U v i)) + level i := G.level (c.seam U v i) + footprint i := G.footprint (c.vertex U v i) + +variable {U v} (hr : 2 * U + 2 ≤ R) +include hr + +omit [Fintype V] in +open scoped Classical in +private theorem ports_eq (l : List (E × F)) (hl : ∀ x ∈ l, a.touches U v x.1) : + (c.localPorts U v l).map (Prod.map (c.seam U v) id) = l := by + induction l with + | nil => rfl + | cons x l ih => + obtain ⟨i, hi⟩ := (c.seam_range hr).mpr (hl x (by simp)) + have e : c.edge x.1 = i.val := by rw [← hi, (c.seam_spec U v i).2] + rw [localPorts, List.filterMap_cons] + simp only [e, i.property, ↓reduceDIte, List.map_cons] + change (c.seam U v i, x.2) :: (c.localPorts U v l).map _ = x :: l + rw [hi, ih (fun y hy => hl y (.tail _ hy))] + +variable {G : Record F r t V E K N} + +open scoped Classical in +theorem view (hl : Incident G a) : View G (c.vertex U v) (c.seam U v) (c.extract U v G) := by + refine ⟨fun _ => rfl, fun i => ?_, fun _ => rfl, fun _ => rfl⟩ + symm + apply c.ports_eq hr + intro x hx + have near := (c.vertex_spec U v i).1 + rcases (hl.endpoints _ _).mp (List.mem_map_of_mem hx) with e|e + · exact .inl (e.symm ▸ near) + · exact .inr (e.symm ▸ near) + +open scoped Classical in +theorem covers (hl : Incident G a) : Covers (c.extract U v G).ports (c.center U v) U := by + let f := c.vertex U v + let k := c.seam U v + let H := c.extract U v G + have e := c.view hr (v := v) hl + have go (n b : ℕ) (i : c.vertices U v) (hb : b + n ≤ U) (hi : a.near b v (f i)) : + Covers H.ports i n := by + induction n generalizing b i with + | zero => trivial + | succ n ih => + intro x hx + have h' : (k x.1, x.2) ∈ G.ports (f i) := by + rw [e.ports] + exact List.mem_map.mpr ⟨x, hx, rfl⟩ + obtain ⟨w, ne, edge, other⟩ : ∃ w, w ≠ f i ∧ a.near 1 (f i) w ∧ + k x.1 ∈ (G.ports w).map Prod.fst := by + let j := k x.1 + rcases (hl.endpoints _ _).mp (List.mem_map.mpr ⟨_, h', rfl⟩) with hp|hp + · rw [← hp] + exact ⟨a.dst j, (hl.loopless j).symm, a.near_edge j, (hl.endpoints _ _).mpr (.inr rfl)⟩ + · rw [← hp] + exact ⟨a.src j, hl.loopless j, (a.near_edge j).symm, (hl.endpoints _ _).mpr (.inl rfl)⟩ + obtain ⟨i', he⟩ := (c.vertex_range hr).mpr ((hi.join edge).mono (by omega : b + 1 ≤ U)) + subst w + rw [e.ports] at other + obtain ⟨_, hmem, he⟩ := List.mem_map.mp other + obtain ⟨⟨u, y⟩, hmem', rfl⟩ := List.mem_map.mp hmem + have hsame := k.injective he + subst u + exact ⟨i', y, fun eq => ne (congrArg f eq), hmem', ih (b + 1) i' (by omega) (hi.join edge)⟩ + exact go U 0 (c.center U v) (by omega) (by unfold f; rw [c.center_eq hr]; exact .refl a 0 v) + +end Palette +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# A deterministic wave lookup on colored regions + +The complete input to the local kernel is a panel indexed by host +colors and ordered pairs of colors. A panel does not contain the +ambient graph or the interpretation of its local names. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +variable {F V E X T J L K N : Type} {m d h q R U r t n : ℕ} + +open scoped Classical in +/-- The data for the panel construction, including `vertices`, `edges`, `center`, `input`, +`pos`. -/ +structure Panel (F : Type) (r t q U : ℕ) (K N : Type) where + /-- The indexed vertices carried by `Panel`, with type `Finset (Fin q)`. -/ + vertices : Finset (Fin q) + /-- The finite set of connections carried by `Panel`, with type `Finset (Fin q × Fin q)`. -/ + edges : Finset (Fin q × Fin q) + /-- The `Panel` component of type `vertices`. -/ + center : vertices + /-- The input data carried by `Panel`, with type `Record F r t vertices edges K N`. -/ + input : Record F r t vertices edges K N + /-- The `Panel` field of type `F`. -/ + pos : F + /-- The `Panel` component of type `Fin (U + 1) → K`. -/ + fresh : Fin (U + 1) → K + +namespace Panel + +variable (a : Panel F r t q U K N) + +open scoped Classical in +/-- The value specified by `a.fresh ⟨min j U, by omega⟩`. -/ +def key (j : ℕ) := a.fresh ⟨min j U, by omega⟩ +open scoped Classical in +/-- Computes the safe by the application `Covers a.input.ports a.center U`. -/ +def safe := Covers a.input.ports a.center U + +variable [Field F] [Fintype F] (p l g H M D : ℕ) [ExpChar F p] (hF : M * (2 * D + 1) + < Fintype.card F) + +open scoped Classical in +/-- Returns `(a.input.run p l g H U M D hF a.center a.pos a.key e).choose` when `e : a.safe` +holds, and `Script.pure a.input` otherwise. -/ +def action : Script F r t a.vertices a.edges K N := + if e : a.safe then (a.input.run p l g H U M D hF a.center a.pos a.key e).choose + else Script.pure a.input + +open scoped Classical in +theorem spec (e : a.safe) : + let s := a.action p l g H M D hF + s.Ordered a.key 0 U ∧ s.Runs a.input (p ^ l) g H U M D a.center a.pos ∧ + Fintype.card s.I ≤ breadth (p ^ l) g H M D (Nat.card F + 1) ^ ((U + 1) * (M + 1)) := by + rw [action, dite_eq_left e] + exact (a.input.run p l g H U M D hF a.center a.pos a.key e).choose_spec + +open scoped Classical in +/-- Indexes the kernel by the coordinates of `Σ (v : Finset (Fin q)) (e : Finset (Fin q × Fin +q)), Script F r t v e K N`. -/ +abbrev Kernel (F : Type) (r t q : ℕ) (K N : Type) := + Σ (v : Finset (Fin q)) (e : Finset (Fin q × Fin q)), Script F r t v e K N + +open scoped Classical in +/-- Uses `⟨a.vertices, a.edges, a.action p l g H M D hF⟩` as the representation. -/ +def kernel : Kernel F r t q K N := + ⟨a.vertices, a.edges, a.action p l g H M D hF⟩ + +end Panel + +namespace Palette +variable [Fintype V] [Fintype E] {a : Atlas V E m d h} (c : Palette a R q) + +open scoped Classical in +/-- Uses `⟨c.vertices U v, c.labels U v, c.center U v, c.extract U v G, z, fun i => ν i.val⟩` as +the representation. -/ +def panel (U : ℕ) (G : Record F r t V E K N) (v : V) (z : F) (ν : ℕ → K) : Panel F r t q U K N := + ⟨c.vertices U v, c.labels U v, c.center U v, c.extract U v G, z, fun i => ν i.val⟩ + +variable [Field F] [Fintype F] (hr : 2 * U + 2 ≤ R) (G : Record F r t V E K N) (hG : Incident G a) + (ref : Reference J L N V E T X) (p l g H M D : ℕ) [ExpChar F p] + (hF : M * (2 * D + 1) < Fintype.card F) (v : Fin n ↪ V) (z : Fin n → F) (ν : V → ℕ → K) + +open scoped Classical in +/-- Builds `Command F r t T V E X K N (p ^ l) g H U M D ref.key where vertices` with the +specified `vertices`, `edges`, `ref`, `shared`. -/ +def wave (i : Fin n) : Command F r t T V E X K N (p ^ l) g H U M D ref.key where + vertices := c.vertices U (v i) + edges := c.labels U (v i) + ref := ref.region (c.vertex U (v i)) (c.seam U (v i)) + shared := rfl + input := c.extract U (v i) G + action := (c.panel U G (v i) (z i) (ν (v i))).action p l g H M D hF + start := c.center U (v i) + pos := z i + runs := ((c.panel U G (v i) (z i) (ν (v i))).spec p l g H M D hF (c.covers hr hG)).2.1 + +local notation "C" => c.wave hr G hG ref p l g H M D hF v z ν + +open scoped Classical in +theorem prepared (color : ∀ i j, c.mark (v i) = c.mark (v j)) : Wave.Prepared C G ref := + ⟨⟨fun i j h => (c.separate hr (v.injective.ne h) (color i j)).1, + fun i j h => (c.separate hr (v.injective.ne h) (color i j)).2⟩, + rfl, fun _ => rfl, fun _ => rfl, fun i => c.view hr (v := v i) hG⟩ + +open scoped Classical in +theorem wave_target (i : Fin n) : (C i).target = (v i, z i) := by + exact Prod.ext (c.center_eq hr) rfl + +open scoped Classical in +theorem wave_ordered (i : Fin n) : (C i).action.Ordered (ν (v i)) 0 U := by + have hh := ((c.panel U G (v i) (z i) (ν (v i))).spec p l g H M D hF (c.covers hr hG)).1 + intro j + obtain ⟨bound, h⟩ := hh j + refine ⟨bound, fun k => ?_⟩ + rw [zero_add] at bound + have hk : k.val ≤ U := k.isLt.le.trans bound + have e := h k + simp only [Panel.key, panel, zero_add, min_eq_left hk] at e + rw [zero_add] + exact e + +open scoped Classical in +theorem wave_bound (i : Fin n) : Fintype.card (C i).action.I ≤ + breadth (p ^ l) g H M D (Nat.card F + 1) ^ ((U + 1) * (M + 1)) := + ((c.panel U G (v i) (z i) (ν (v i))).spec p l g H M D hF (c.covers hr hG)).2.2 + +open scoped Classical in +/-- Includes the index type, multiplicities, coefficients, output +records and allocation order. Equal panels have identical kernels. -/ +theorem wave_kernel (i : Fin n) : + (⟨c.vertices U (v i), c.labels U (v i), (C i).action⟩ : Panel.Kernel F r t q K N) = + (c.panel U G (v i) (z i) (ν (v i))).kernel p l g H M D hF := rfl + +end Palette +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Payload/Price.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Payload/Price.lean new file mode 100644 index 0000000000..577d908c9f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Payload/Price.lean @@ -0,0 +1,1082 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Pass +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanTiles +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Border +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.SpanSupplies +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Shipment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Scenario +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Shapes +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Shipment.Bound + +/-! +# Detecting the child that carries the exterior + +Only seat zero of each grouped input can carry exterior bits. If +even one exterior bit survives, the two lists identify a unique +child. The controller needs only short labels to find that child. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +open Assembly Coloring Packing +variable {F : Type} [Field F] {x y : Wire} {G H : Diagram F x y} + {S U : Scheme F} {r : S.format.obj} {t : U.format.obj} + (p : S.Presentation r G) (q : U.Presentation t H) {z : ℕ} + (child : B U.m ≃ B S.m × B z) (outer : Bool ↪ B U.e) + +open scoped Classical in +/-- Returns `(S.decode a).width j s` when `(S.decode a).peer j s = none` holds, and `0` +otherwise. -/ +def border (S : Scheme F) (a : B S.ℓ) (j : B S.k) (s : B S.e) := + if (S.decode a).peer j s = none then (S.decode a).width j s else 0 + +omit [Field F] in +open scoped Classical in +theorem border_eq (S : Scheme F) (r : S.format.obj) (s : S.Span) : + border S ((r s.1.1).2 s.1.2.1) s.1.2.2 s.2 = S.borderLen r s := by + simp only [border, Scheme.borderLen, Scheme.width, Scheme.pattern, Scheme.peer, + Option.map_eq_none_iff] + +open scoped Classical in +/-- The condition `∀ i : slots x ⊕ slots y, (p.vertex (portEnd G i)).2.2 = 0` on the specified +data. -/ +def Centered := ∀ i : slots x ⊕ slots y, (p.vertex (portEnd G i)).2.2 = 0 + +open scoped Classical in +/-- The data for the family construction, including `child`, `outer`, `height`. -/ +structure Family (S U : Scheme F) (z : ℕ) where + /-- Reindexes the data using `B U.m ≃ B S.m × B z`. -/ + child : B U.m ≃ B S.m × B z + /-- The external data of type `Bool ↪ B U.e`. -/ + outer : Bool ↪ B U.e + height : S.h = U.h + +namespace Family +variable (A : Family S U z) + +open scoped Classical in +/-- Transports an index across an equality of bounds. -/ +abbrev block (i : B S.h) : B U.h := Fin.cast (congrArg (2^·) A.height) i + +open scoped Classical in +/-- The value specified by `(t (A.child.symm (v, j))).2 (A.block i)`. -/ +def labels (t : U.format.obj) (v : B S.m) (i : B S.h) (j : B z) : B U.ℓ := + (t (A.child.symm (v, j))).2 (A.block i) + +open scoped Classical in +/-- Returns `h.choose` when `h : ∃ j s, 0 < border U (b j) 0 (A.outer s)` holds, and `0` +otherwise. -/ +def pick (b : B z → B U.ℓ) : B z := + if h : ∃ j s, 0 < border U (b j) 0 (A.outer s) then h.choose else 0 + +open scoped Classical in +/-- The value specified by `((A.child.symm (i.1.1, A.pick (A.labels t i.1.1 i.1.2.1)), A.block +i.1.2.1, 0), A.outer (S.direction r i))`. -/ +def shift (r : S.format.obj) (t : U.format.obj) (i : S.Span) : U.Span := + ((A.child.symm (i.1.1, A.pick (A.labels t i.1.1 i.1.2.1)), A.block i.1.2.1, 0), + A.outer (S.direction r i)) + +end Family + +variable {p q child outer} {A : Family S U z} (f : Retains p q A.child A.outer) (hc : Centered p) + +include f + +open scoped Classical in +theorem Retains.block (i : slots x ⊕ slots y) : + (q.boundary i).val.1.1.2.1 = A.block (p.boundary i).val.1.1.2.1 := by + obtain ⟨w, c⟩ := f i + rw [c.owns i rfl, owner] + exact Fin.ext c.block + +include hc + +open scoped Classical in +theorem Retains.station (i j : slots x ⊕ slots y) + (hm : (A.child (q.boundary i).val.1.1.1).1 = (A.child (q.boundary j).val.1.1.1).1) + (hb : (q.boundary i).val.1.1.2.1 = (q.boundary j).val.1.1.2.1) : + (q.boundary i).val.1.1 = (q.boundary j).val.1.1 := by + rw [f.parent, f.parent, owner, owner] at hm + rw [f.block, f.block, owner, owner] at hb + have he : portEnd G i = portEnd G j := + p.vertex.injective (Prod.ext hm (Prod.ext (Fin.ext (congrArg (fun j : B U.h + => j.val) hb)) ((hc i).trans (hc j).symm))) + obtain ⟨w, c⟩ := f j + rw [c.owns j rfl, c.owns i he] + +open scoped Classical in +theorem Retains.channel (i : slots x ⊕ slots y) : + let u := (p.boundary i).val.1.1 + A.pick (A.labels t u.1 u.2.1) = (A.child (q.boundary i).val.1.1.1).2 := by + intro u + let I := (q.boundary i).val.1 + let v := I.1.1 + let J (j : B z) (s : Bool) : U.Span := ((A.child.symm (u.1, j), A.block u.2.1, 0), A.outer s) + have hit : J (A.child v).2 i.isRight = I := by + have eq : (u.1, (A.child v).2) = A.child v := Prod.ext (f.parent i).symm rfl + obtain ⟨w, c⟩ := f i + unfold J + rw [eq, Equiv.symm_apply_apply] + change ((I.1.1, A.block u.2.1, 0), _) = I + have ht := c.owns i rfl + change I = _ at ht + have hb : I.1.2.1 = A.block u.2.1 := f.block i + rw [← hb, ht, ← c.seat] + have len (j s) : border U (A.labels t u.1 u.2.1 j) 0 (A.outer s) = U.borderLen t (J j s) := + border_eq U t (J j s) + have any : ∃ j s, 0 < border U (A.labels t u.1 u.2.1 j) 0 (A.outer s) := + ⟨_, _, by rw [len, hit]; exact (q.border_pos _).mpr ⟨i, rfl⟩⟩ + rw [Family.pick, dite_eq_left any] + obtain ⟨s, hs⟩ := any.choose_spec + rw [len] at hs + obtain ⟨j, hj⟩ := (q.border_pos _).mp hs + have eq := f.station hc j i (by + rw [hj, f.parent i] + exact congrArg Prod.fst (A.child.apply_symm_apply _)) (by rw [hj, f.block i]) + have h := congrArg (fun v : U.Vtx => (A.child v.1).2) eq + rw [hj] at h + simpa only [J, Equiv.apply_symm_apply] using h + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +end + +/- # Transporting the payload after printing a concentrated diagram -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +open Assembly Coloring Rounds + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {U : Assembly.Template F} + {c e : ℕ} (A : Family S U.scheme c) (old : B e → B S.ℓ) + (s : Plan) (T : ℕ) (L : ℝ) (z height : ℕ) + +/-- Both tapes are present, with the exterior bits still on the source side. -/ +structure Pending where + /-- The `Pending` component of type `Contraction.Publication (x := x) (y := y) U s T L z + height`. -/ + out : Contraction.Publication (x := x) (y := y) U s T L z height + /-- The `Pending` component of type `Diagram F x y`. -/ + G : Diagram F x y + /-- The carried data of type `S.format.obj`. -/ + data : S.format.obj + /-- The `Pending` component of type `S.Presentation data G`. -/ + initial : S.Presentation data G + dir : initial.Directed + /-- The `Pending` component of type `(Fmt.rows S.m S.d S.h (.addr e)).obj`. -/ + tape : (Fmt.rows S.m S.d S.h (.addr e)).obj + read : ∀ v j, old ((tape v).2 j) = (data v).2 j + fits : S.Fits data (2 ^ S.m + wd x + wd y) height + center : Centered (initial.toOrdered dir) + retains : Retains (initial.toOrdered dir) out.showing.pres A.child A.outer + +/-- The value specified by `(Fmt.rows S.m S.d S.h (.addr e)).pair U.format`. -/ +abbrev sourcePort (S : Scheme F) (U : Assembly.Template F) (e : ℕ) + := (Fmt.rows S.m S.d S.h (.addr e)).pair U.format + +/-- Builds `Snapshot.{1} F x y where state` with the specified `state`, `eval`, `port`, +`encode`. -/ +def pending : Snapshot.{1} F x y where + state := Pending (x := x) (y := y) A old s T L z height + eval i := i.out.Q.diagram.eval + port := (sourcePort S U e).pair (Fmt.payload S.m (2 ^ S.m + wd x + wd y) height) + encode i a b := ((i.tape, i.out.r), S.store _ i.fits ((i.initial.toOrdered i.dir).exterior a b)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +end + +/- # Source and destination rows for exterior payload shipment -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload.Family +open Assembly Coloring +variable {F : Type} {S U : Scheme F} {z : ℕ} (A : Family S U z) + +open scoped Classical in +/-- Sort by block, destination span (zero on the source side), +then original span. All original exterior bits belong to seat zero. -/ +abbrev depth (_ : Family S U z) := S.h + (U.e + S.e) + +open scoped Classical in +/-- Reindexes `B A.depth` and `B S.h × B U.e × B S.e` by an equivalence. -/ +def positions : B A.depth ≃ B S.h × B U.e × B S.e := + (Match.rowIndex S.h (U.e + S.e)).trans ((Equiv.refl _).prodCongr (Match.rowIndex U.e S.e)) + +open scoped Classical in +/-- The value specified by `A.positions.symm (b, a, s)`. -/ +def rank (b : B S.h) (a : B U.e) (s : B S.e) := A.positions.symm (b, a, s) +open scoped Classical in +/-- Computes the left by the application `A.rank s.1.2.1 0 s.2`. -/ +def left (s : S.Span) := A.rank s.1.2.1 0 s.2 +open scoped Classical in +/-- Computes the right by the application `A.rank s.1.2.1 (A.outer (S.direction r s)) s.2`. -/ +def right (r : S.format.obj) (s : S.Span) := A.rank s.1.2.1 (A.outer (S.direction r s)) s.2 + +open scoped Classical in +/-- The value specified by `((v, (A.positions i).1, 0), (A.positions i).2.2)`. -/ +def line (v : B S.m) (i : B A.depth) : S.Span := ((v, (A.positions i).1, 0), (A.positions i).2.2) + +open scoped Classical in +/-- The quantity computed by `⟨x % 2 ^ w, Nat.mod_lt _ (by positivity)⟩`. -/ +def put (w x : ℕ) : B w := ⟨x % 2 ^ w, Nat.mod_lt _ (by positivity)⟩ + +open scoped Classical in +/-- The value specified by `Format.pair (.addr e) (.pair (.vec z (.addr U.ℓ)) (.pair (.addr +A.depth) (.pair .bit (.addr z))))`. -/ +abbrev Question (e : ℕ) := Format.pair (.addr e) (.pair (.vec z (.addr U.ℓ)) (.pair (.addr A.depth) + (.pair .bit (.addr z)))) +open scoped Classical in +/-- Computes the reply by the application `SpanPlan.header w z A.depth`. -/ +abbrev Reply (w : ℕ) := SpanPlan.header w z A.depth + +open scoped Classical in +/-- The respond of type `(A.Reply w).obj`, constructed using `A.positions v.2.2.1`. -/ +def respond (w : ℕ) {e : ℕ} (old : B e → B S.ℓ) (v : (A.Question e).obj) : (A.Reply w).obj := + let i := A.positions v.2.2.1 + let j := A.pick v.2.1 + let l := old v.1 + let size := put w (border S l 0 i.2.2) + let key := A.rank i.1 0 i.2.2 + if v.2.2.2.1 then + if v.2.2.2.2 = j ∧ i.2.1 = A.outer ((S.decode l).direction 0 i.2.2) then (0, size, + key) else (0, 0, 0) + else if i.2.1 = 0 then (j, size, key) else (0, 0, 0) + +variable (r : S.format.obj) (t : U.format.obj) (w : ℕ) + +open scoped Classical in +/-- Computes the channel by the application `A.pick (A.labels t s.1.1 s.1.2.1)`. -/ +def channel (s : S.Span) := A.pick (A.labels t s.1.1 s.1.2.1) +open scoped Classical in +/-- The send of type `SpanPlan.Entries S.m w z A.depth`, constructed using `A.line v i`. -/ +def send : SpanPlan.Entries S.m w z A.depth := fun v i => + let s := A.line v i + if (A.positions i).2.1 = 0 then (A.channel t s, put w (S.borderLen r s), A.left s) else (0, 0, 0) +open scoped Classical in +/-- The take of type `SpanPlan.Entries U.m w z A.depth`, constructed using `A.line (A.child v).1 +i`. -/ +def take : SpanPlan.Entries U.m w z A.depth := fun v i => + let s := A.line (A.child v).1 i + if (A.child v).2 = A.channel t s ∧ (A.positions i).2.1 = A.outer (S.direction r s) + then (0, put w (S.borderLen r s), A.left s) else (0, 0, 0) + +open scoped Classical in +theorem line_rank (s : S.Span) (a : B U.e) (h : s.1.2.2 = 0) : + A.line s.1.1 (A.rank s.1.2.1 a s.2) = s := by + simp only [line, rank, Equiv.apply_symm_apply, ←h] + +open scoped Classical in +theorem send_at (s : S.Span) (hs : s.1.2.2 = 0) : + A.send r t w s.1.1 (A.left s) = (A.channel t s, put w (S.borderLen r s), A.left s) := by + unfold send + rw [show A.line s.1.1 (A.left s) = s from A.line_rank s 0 hs] + simp only [left, rank, Equiv.apply_symm_apply, ↓reduceIte] + +open scoped Classical in +theorem take_at (s : S.Span) (hs : s.1.2.2 = 0) : + A.take r t w (A.shift r t s).1.1 (A.right r s) = (0, put w (S.borderLen r s), A.left s) := by + have he : A.child (A.shift r t s).1.1 = (s.1.1, A.channel t s) := A.child.apply_symm_apply _ + unfold take + rw [he, show A.line s.1.1 (A.right r s) = s from A.line_rank s _ hs] + simp only [right, rank, Equiv.apply_symm_apply, and_self, ↓reduceIte] + +open scoped Classical in +theorem put_pos {w n : ℕ} (h : 0 < (put w n).val) : 0 < n := + h.trans_le (Nat.mod_le ..) + +open scoped Classical in +theorem send_cover (v : B S.m) (i : B A.depth) (hi : 0 < (A.send r t w v i).2.1.val) : + ∃ s, 0 < S.borderLen r s ∧ s.1.1 = v ∧ A.left s = i := by + dsimp only [send] at hi + split_ifs at hi with hp + · refine ⟨_, put_pos hi, rfl, ?_⟩ + apply A.positions.injective + simp only [left, line, rank, Equiv.apply_symm_apply, ←hp] + · exact (Nat.lt_irrefl _ hi).elim + +open scoped Classical in +theorem take_cover (v : B U.m) (i : B A.depth) (hi : 0 < (A.take r t w v i).2.1.val) : + ∃ s, 0 < S.borderLen r s ∧ (A.shift r t s).1.1 = v ∧ A.right r s = i := by + dsimp only [take] at hi + split_ifs at hi with hp + · let s := A.line (A.child v).1 i + refine ⟨s, put_pos hi, ?_, ?_⟩ + · change A.child.symm ((A.child v).1, A.channel t s) = v + rw [←hp.1, Equiv.symm_apply_apply] + · apply A.positions.injective + simp only [right, rank, Equiv.apply_symm_apply] + rw [←hp.2] + rfl + · exact (Nat.lt_irrefl _ hi).elim + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload.Family +end + +/- # Compatibility of the two shipment orders -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +open Assembly Coloring +variable {F : Type} {S U : Scheme F} {r : S.format.obj} {t : U.format.obj} + {z : ℕ} (A : Family S U z) + +open scoped Classical in +private theorem span_lt (i j : S.Span) : + S.spanOrd i < S.spanOrd j ↔ + i.1.2.1 < j.1.2.1 ∨ i.1.2.1 = j.1.2.1 ∧ + (i.1.2.2 < j.1.2.2 ∨ i.1.2.2 = j.1.2.2 ∧ i.2 < j.2) := by + simp [Scheme.spanOrd, Scheme.row, Scheme.rowIndex_lt] + +namespace Family +open scoped Classical in +theorem rank_lt (a b : B S.h) (u v : B U.e) (i j : B S.e) : + A.rank a u i < A.rank b v j ↔ a < b ∨ a = b ∧ (u < v ∨ u = v ∧ i < j) := by + unfold rank positions + simp [Scheme.rowIndex_lt] + +open scoped Classical in +theorem ordered (i j : S.Span) (hi : i.1.2.2 = 0) (hj : j.1.2.2 = 0) (h : S.spanOrd i + < S.spanOrd j) : + A.left i < A.left j := by + rw [span_lt, hi, hj] at h + simpa [left, rank_lt] using h + +open scoped Classical in +theorem route (i : S.Span) : A.child (A.shift r t i).1.1 = (i.1.1, A.channel t i) := + A.child.apply_symm_apply _ + +open scoped Classical in +theorem merged (i j : S.Span) (hi : i.1.2.2 = 0) (hj : j.1.2.2 = 0) + (hs : (A.shift r t i).1.1 = (A.shift r t j).1.1) (hr : A.right r i < A.right r j) : + U.spanOrd (A.shift r t i) < U.spanOrd (A.shift r t j) ∨ + (A.shift r t i = A.shift r t j ∧ S.skip r i + S.borderLen r i ≤ S.skip r j) := by + rw [right, right, rank_lt] at hr + rcases hr with hb|⟨hb, hd|⟨hd, hlt⟩⟩ + · exact .inl ((span_lt ..).mpr (.inl hb)) + · exact .inl ((span_lt ..).mpr (.inr ⟨congrArg A.block hb, .inr ⟨rfl, hd⟩⟩)) + · have hh := congrArg (fun a => (A.child a).1) hs + simp only [route] at hh + have hv : i.1 = j.1 := Prod.ext hh (Prod.ext hb (hi.trans hj.symm)) + exact .inr ⟨Prod.ext (Prod.ext hs (Prod.ext (congrArg A.block hb) rfl)) hd, + S.skip_gap r hv (A.outer.injective hd) hlt⟩ + +end Family +variable [Field F] {x y : Wire} {G H : Diagram F x y} {p : S.Presentation r G} + {q : U.Presentation t H} (hc : Centered p) + +include hc in +open scoped Classical in +theorem Centered.seat (i : S.Span) (hi : 0 < S.borderLen r i) : i.1.2.2 = 0 := by + obtain ⟨k, rfl⟩ := (p.border_pos _).mp hi + rw [owner] + exact hc _ + +open scoped Classical in +theorem Family.spec {V k w : ℕ} (hf : S.Fits r V k) (hw : k < w) + (hb : ∀ i, let a := (p.boundary i).val; let b := (q.boundary i).val + b.1 = A.shift r t a.1 ∧ b.2.val = S.skip r a.1 + a.2.val) + (hc : Centered p) : + SpanPlan.Spec p q A.child (A.shift r t) (S.skip r) A.left (A.right r) (A.send r t w) (A.take r + t w) := by + have he (i : S.Span) : (Family.put w (S.borderLen r i)).val = S.borderLen r i := + Nat.mod_eq_of_lt (((S.border_le ..).trans (hf.2 _)).trans_lt (Nat.pow_lt_pow_right (by decide) + hw)) + refine ⟨fun i _ => congrArg Prod.fst (A.route i), hb, fun i j hi hj _ + => A.ordered i j (hc.seat i hi) (hc.seat j hj), + fun i j hi hj => A.merged i j (hc.seat i hi) (hc.seat j hj), ?_, ?_, A.send_cover r t w, + A.take_cover r t w⟩ + · intro i hi + rw [A.send_at _ _ _ i (hc.seat i hi), A.route] + exact ⟨rfl, he i, rfl⟩ + · intro i hi + rw [A.take_at _ _ _ i (hc.seat i hi)] + exact ⟨rfl, he i, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +end + +/- +# One shared dictionary gate to issue all shipment instructions + +The first input label encodes a terminal wave record and still +contains its original header. The other labels belong to the +children of the same host, in the same block. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload.Family +open Assembly Coloring +variable {F : Type} {S U : Scheme F} {z e : ℕ} (A : Family S U z) (w : ℕ) + (old : B e → B S.ℓ) + +open scoped Classical in +/-- Computes the stage rows by the application `Fmt.rows S.m S.d S.h (.addr e)`. -/ +abbrev StageRows (_ : Family S U z) (e : ℕ) := Fmt.rows S.m S.d S.h (.addr e) +open scoped Classical in +/-- The value specified by `(A.StageRows e).pair U.format`. -/ +abbrev Data (e : ℕ) := (A.StageRows e).pair U.format + +open scoped Classical in +/-- The value specified by `(Match.rowIndex U.m z).symm (A.child.symm (Match.rowIndex S.m z i), +0)`. -/ +def peer (i : B (S.m + z)) : B (U.m + z) := + (Match.rowIndex U.m z).symm (A.child.symm (Match.rowIndex S.m z i), 0) + +open scoped Classical in +/-- Uses `Assembly.Payload.Script S.m U.m z w A.depth` as the representation. -/ +abbrev Script := Assembly.Payload.Script S.m U.m z w A.depth + +open scoped Classical in +/-- The value specified by `SpanPlan.emit A.peer (A.send r t w, A.take r t w)`. -/ +def script (r : S.format.obj) (t : U.format.obj) : (A.Script w).obj := + SpanPlan.emit A.peer (A.send r t w, A.take r t w) + +open scoped Classical in +/-- The value specified by `((x.1 v).2 (A.positions i).1, A.labels x.2 v (A.positions i).1, i, +b, c)`. -/ +def ask (x : (A.Data e).obj) (v : B S.m) (i : B A.depth) (b : Bool) (c : B z) : + (A.Question e).obj := + ((x.1 v).2 (A.positions i).1, A.labels x.2 v (A.positions i).1, i, b, c) + +open scoped Classical in +/-- Computes the grid by the application `SpanPlan.Ports S.m U.m (.vec A.depth C) (.vec A.depth +C)`. -/ +abbrev Grid (C : Format) := SpanPlan.Ports S.m U.m (.vec A.depth C) (.vec A.depth C) +open scoped Classical in +/-- Computes the jobs by the application `A.Grid (A.Question e)`. -/ +abbrev Jobs (e : ℕ) := A.Grid (A.Question e) +open scoped Classical in +/-- Computes the results by the application `A.Grid (A.Reply w)`. -/ +abbrev Results := A.Grid (A.Reply w) + +open scoped Classical in +/-- The indexed operation `(fun v i => A.ask x v i false 0, fun v i => A.ask x (A.child v).1 i +true (A.child v).2)`. -/ +def jobs (x : (A.Data e).obj) : (A.Jobs e).obj := + (fun v i => A.ask x v i false 0, fun v i => A.ask x (A.child v).1 i true (A.child v).2) + +open scoped Classical in +/-- The indexed operation `(fun v i => A.respond w old (x.1 v i), fun v i => A.respond w old +(x.2 v i))`. -/ +def answers (x : (A.Jobs e).obj) : (A.Results w).obj := + (fun v i => A.respond w old (x.1 v i), fun v i => A.respond w old (x.2 v i)) + +open scoped Classical in +/-- The value specified by `SpanPlan.emit A.peer ∘ A.answers w old ∘ A.jobs`. -/ +def issue : (A.Data e).obj → (A.Script w).obj := SpanPlan.emit A.peer ∘ A.answers w old ∘ A.jobs + +open scoped Classical in +theorem issue_eq (r : S.format.obj) (x : (A.Data e).obj) (hr : ∀ v j, old ((x.1 v).2 j) + = (r v).2 j) : + A.issue w old x = A.script w r x.2 := by + have hf (v : B S.m) (i : B A.depth) : + border S ((r v).2 (A.positions i).1) 0 (A.positions i).2.2 = S.borderLen r (A.line v i) := + border_eq S r (A.line v i) + unfold issue script Function.comp + apply congrArg (SpanPlan.emit A.peer) + refine Prod.ext ?_ ?_ <;> funext v i + · simp only [answers, jobs, ask, respond, Bool.false_eq_true, ↓reduceIte, hr, hf] + rfl + · simp only [answers, jobs, ask, respond, ↓reduceIte, hr, hf] + rfl + +open scoped Classical in +private theorem bit_ask (v : B S.m) (i : B A.depth) (b : Bool) (c : B z) (j : (A.Question e).pins) : + (∃ l, ∀ x, (A.Question e).code (A.ask x v i b c) j = (A.Data e).code x l) ∨ + ∃ u, ∀ x, (A.Question e).code (A.ask x v i b c) j = u := by + rcases j with j | ⟨k, j⟩ | j + · exact .inl ⟨.inl (v, .inr ((A.positions i).1, j)), fun _ => rfl⟩ + · exact .inl ⟨.inr (A.child.symm (v, k), .inr (A.block (A.positions i).1, j)), fun _ => rfl⟩ + · exact .inr ⟨((Format.addr A.depth).pair (.pair .bit (.addr z))).code (i, b, c) j, fun _ => rfl⟩ + +variable [Field F] + +open scoped Classical in +private theorem jobs_net : Circuit F (A.Data e) (A.Jobs e) A.jobs ((A.Data e).width + + 34 * (A.Jobs e).width) := by + apply Window.Tile.project_const + rintro (⟨v, i, j⟩|⟨v, i, j⟩) + · exact A.bit_ask v i false 0 j + · exact A.bit_ask (A.child v).1 i true (A.child v).2 j + +open scoped Classical in +/-- The indexed operation `weightTable (A.respond w old) (fun _ => 1)`. -/ +def gate : Table F := weightTable (A.respond w old) (fun _ => 1) +open scoped Classical in +/-- The quantity computed by `(A.Question e).width + (A.Reply w).width`. -/ +def arity (e : ℕ) := (A.Question e).width + (A.Reply w).width + +open scoped Classical in +/-- The bound obtained by adding the component charges `4 * ((A.Data e).width + 34 * (A.Jobs +e).width) + (2 ^ S.m + 2 ^ U.m) * (2 ^ A.depth * (1 + A.arity w e)) + 4 * SpanPlan.emitCost +S.m U.m w z A.depth`. -/ +def issueCost (e : ℕ) := + 4 * ((A.Data e).width + 34 * (A.Jobs e).width) + (2 ^ S.m + 2 ^ U.m) * (2 ^ A.depth * (1 + + A.arity w e)) + + 4 * SpanPlan.emitCost S.m U.m w z A.depth + +open scoped Classical in +theorem program {u : ℕ} {L : Set (Table F)} (hu : 3 ≤ u) (ha : A.arity w e + ≤ u) (ht : A.gate w old ∈ L) : + Map F u L (A.Data e) (A.Script w) (A.issue w old) (A.issueCost w e) := by + have one : Map F u L (A.Question e) (A.Reply w) (A.respond w old) (1 + A.arity w e) := by + rw [arity, ←add_assoc] + exact Kernel.lookup ha ht + have many (m : ℕ) := Map.vec _ fun _ : B m => Map.vec _ fun _ : B A.depth => one + unfold issueCost + rw [add_mul (2 ^ S.m)] + exact ((Map.circuit hu A.jobs_net).comp ((many S.m).par (many U.m))).comp (Map.circuit hu + (SpanPlan.emit_net A.peer F)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload.Family +end + +/- # Retaining the printed template while issuing transfer instructions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +open Assembly Coloring Rounds + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {U : Assembly.Template F} + {c e : ℕ} (A : Family S U.scheme c) (old : B e → B S.ℓ) + (s : Plan) (T : ℕ) (L : ℝ) (z height : ℕ) + +local notation "W" => height + 1 +local notation "X" => sourcePort S U e +local notation "J" => Pending (x := x) (y := y) A old s T L z height + +open scoped Classical in +/-- The quantity computed by `28 * (sourcePort S U e).width + 8 * U.format.width + 8 * (A.Data +e).width + A.issueCost W e`. -/ +def controlCost (e : ℕ) := 28 * (sourcePort S U e).width + 8 * U.format.width + + 8 * (A.Data e).width + A.issueCost W e + +open scoped Classical in +theorem commands {u : ℕ} {labels : Set (Table F)} (hu : 3 ≤ u) (ha : A.arity W e ≤ u) + (ht : A.gate W old ∈ labels) : + Computes F u labels X (U.format.pair (A.Script W)) (fun i : J => (i.tape, i.out.r)) + (fun i => (i.out.r, A.script W i.data i.out.r.1)) (fun _ => 1) (controlCost A height e) := by + let y (i : J) : (X).obj := (i.tape, i.out.r) + let pr : (X).obj → (A.Data e).obj := fun i => (i.1, i.2.1) + have keep : Circuit F X U.format Prod.snd ((X).width + 2 * U.format.width) := + Circuit.project Sum.inr (fun _ _ => rfl) + have pick : Circuit F X (A.Data e) pr ((X).width + 2 * (A.Data e).width) := + Circuit.project (Sum.map id Sum.inl) (by rintro _ (i|j) <;> rfl) + have hold := Computes.of_map (L := labels) (x := y) (y := fun i => i.out.r) (Map.circuit hu keep) + (fun _ => rfl) + have send := Computes.of_map (x := y) (y := fun i => A.script W i.data i.out.r.1) + ((Map.circuit hu pick).comp (A.program W old hu ha ht)) + (fun i => A.issue_eq W old i.data (pr (y i)) i.read) + have h := hold.pair hu send + simp only [one_mul] at h + exact h.mono (by unfold controlCost; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +end + +/- # Widths of the shipment instructions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload.Family +open Assembly Coloring +open Surface.Local (Rates) +variable {F : Type} {S U : Scheme F} {c : ℕ} (A : Family S U c) (w e : ℕ) + +include A in +theorem dimensions : 2 ^ U.m = 2 ^ S.m * 2 ^ c := by + simpa only [B, Fintype.card_prod, Fintype.card_fin] using Fintype.card_congr A.child + +include A in +theorem host : U.m = S.m + c := by + have h := A.dimensions + rw [← pow_add] at h + exact Nat.pow_right_injective (by decide : 2 ≤ 2) h + +theorem questionWidth : (A.Question e).width = e + 2 ^ c * U.ℓ + A.depth + 1 + c := by + simp only [Question, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit] + ring + +theorem width : A.arity w e = e + 2 ^ c * U.ℓ + 2 * A.depth + 1 + 2 * c + w := by + rw [arity, questionWidth] + simp only [Reply, SpanPlan.header, Format.width_pair, Format.width_addr] + ring + +theorem jobWidth : (A.Jobs e).width = (2 ^ S.m + 2 ^ U.m) * (2 ^ A.depth * (A.Question e).width) + := by + rw [Jobs, Grid, SpanPlan.Ports, Format.width_pair, Format.width_vec, Format.width_vec, + Format.width_vec, Format.width_vec] + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload.Family +end + +/- # Every exterior bit arrives at its prescribed position -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +open Assembly Coloring Packing +variable {F : Type} [Field F] {x y : Wire} {G H : Diagram F x y} + {S U : Scheme F} {r : S.format.obj} {t : U.format.obj} + {p : S.Presentation r G} {q : U.Presentation t H} {z : ℕ} + {A : Family S U z} {h : p.Directed} + +local notation "P" => p.toOrdered h +local notation "D" => p.ordered h + +open scoped Classical in +private theorem offset {v : (D).V} {w : H.V} (c : Carrier P q A.child A.outer v w) + (i : slots x ⊕ slots y) (hi : portEnd D i = v) : + S.direction r ((P).boundary i).val.1 = i.isRight ∧ + (q.boundary i).val.2.val = S.skip r ((P).boundary i).val.1 + ((P).boundary i).val.2.val := by + cases i with + | inl i => + obtain ⟨j, rfl⟩ := List.mem_iff_get.mp (((D).mem_extLeft v i).mpr hi) + exact ⟨(p.skipLeft h v j).2.1, (c.left j).2.trans (p.skipLeft h v j).2.2⟩ + | inr i => + obtain ⟨j, rfl⟩ := List.mem_iff_get.mp (((D).mem_extRight v i).mpr hi) + exact ⟨(p.skipRight h v j).2.1, (c.right j).2.trans (p.skipRight h v j).2.2⟩ + +open scoped Classical in +private theorem captured (f : Retains p q A.child A.outer) (hc : Centered p) (i : slots x ⊕ slots y) + (hd : S.direction r (p.boundary i).val.1 = i.isRight) : + (q.boundary i).val.1 = A.shift r t (p.boundary i).val.1 := by + obtain ⟨w, c⟩ := f i + have hb := Retains.block (A := A) f i + have hu := Retains.channel (A := A) f hc i + have hv : (q.boundary i).val.1.1.1 = (A.shift r t (p.boundary i).val.1).1.1 := by + apply A.child.injective + rw [A.route] + exact Prod.ext (f.parent i) hu.symm + have hz : (q.boundary i).val.1.1.2.2 = 0 := by rw [c.owns i rfl]; exact c.seat + have hs : (q.boundary i).val.1.2 = A.outer (S.direction r (p.boundary i).val.1) := by + rw [hd, c.owns i rfl] + exact Prod.ext (Prod.ext hv (Prod.ext hb hz)) hs + +variable (f : Retains (p.toOrdered h) q A.child A.outer) (hc : Centered (p.toOrdered h)) +include f hc + +open scoped Classical in +theorem Retains.bits (i : slots x ⊕ slots y) : + let a := ((P).boundary i).val + let b := (q.boundary i).val + b.1 = A.shift r t a.1 ∧ b.2.val = S.skip r a.1 + a.2.val := by + obtain ⟨w, c⟩ := f i + have he := offset (p := p) (h := h) (q := q) (A := A) c i rfl + exact ⟨captured (p := P) (q := q) (A := A) f hc i he.1, he.2⟩ + +open scoped Classical in +theorem Retains.supplies {V V' k w : ℕ} (hx : S.Fits r V k) (hy : U.Fits t V' k) (hw : k < w) : + (P).Supplies q hx hy (A.script w r t) := + by + have t := A.spec (p := p.toOrdered h) (q := q) hx hw (Retains.bits (p := p) (q := q) (h + := h) (A := A) f hc) hc + exact t.supplies hx hy hw hw + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +end + +/- # Completing the concentration step with its exterior assignments -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +open Assembly Coloring Rounds + +variable {F : Type} [Field F] {x y : Wire} {S : Scheme F} {U : Assembly.Template F} + {c e : ℕ} (A : Family S U.scheme c) (old : B e → B S.ℓ) + (s : Plan) (T : ℕ) (L : ℝ) (z height : ℕ) (q : Contraction.Prices F) + +local notation "m" => S.m +local notation "m'" => U.scheme.m +local notation "W" => height + 1 +local notation "J" => Pending (x := x) (y := y) A old s T L z height + +/-- The value specified by `controlCost A height e + q.shipment U.format.width m (2 ^ m + N) +height m' (2 ^ m' + N) height c W A.depth`. -/ +def price (e N : ℕ) := + controlCost A height e + q.shipment U.format.width m (2 ^ m + N) height m' (2 ^ m' + + N) height c W A.depth + +private theorem room (h : m ≤ m') (hw : m' + c + height + 2 ≤ q.w) : + 2 ^ c * ((max height height + 1) * (2 ^ m + 2 ^ m')) < 2 ^ q.w := by + rw [max_self] + have hp : height + 1 ≤ 2 ^ height := Nat.lt_two_pow_self + calc + _ ≤ 2 ^ c * (2 ^ height * (2 ^ m' + 2 ^ m')) := by gcongr + _ = 2 ^ (c + height + (m' + 1)) := by rw [pow_add, pow_add, pow_succ]; ring + _ < _ := Nat.pow_lt_pow_right (by decide) (by omega) + +theorem transfer {u : ℕ} {labels : Set (Table F)} (hu : 3 ≤ u) (ha : A.arity W e ≤ u) + (ht : A.gate W old ∈ labels) (hm : 1 ≤ m) (hn : m ≤ m') (hw : m' + c + height + 2 ≤ q.w) : + Transforms F u labels (pending (x := x) (y := y) A old s T L z height) + (Contraction.publication U s T L z height) (price A height q e (wd x + wd y)) := by + let X := J × Val x × Val y + let src (i : X) := ((pending A old s T L z height).encode i.1 i.2.1 i.2.2).2 + let dst (i : X) := ((Contraction.publication U s T L z height).encode i.1.out i.2.1 i.2.2).2 + have ok (i : J) : (i.initial.toOrdered i.dir).Supplies i.out.showing.pres i.fits i.out.fits + (A.script W i.data i.out.r.1) := + Retains.supplies (p := i.initial) (h := i.dir) (A + := A) i.retains i.center i.fits i.out.fits (Nat.lt_succ_self _) + have h := commands (x := x) (y := y) A old s T L z height hu ha ht + have run := q.ship (f := src) (g := dst) hu hm (hm.trans hn) (room height q hn hw) + (h.restrict (fun i : X => i.1)) (fun i v => (ok i.1).carries _ _ v) + unfold price + rw [← add_assoc (2 ^ m), ← add_assoc (2 ^ m')] + exact Transforms.deterministic (fun i => i.out) (fun _ => rfl) run + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +end + +/- +# Bounds for the uniformly controlled local expansion + +The constants are chosen before the scale, the working field and +the input layer. The output labels grow at most linearly in the +grouped label width and the logarithms of the scale and field size. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +open Assembly +variable {F : Type} [Field F] + +/-- The quantity computed by `1000 + S.h + S.e + height + q.W`. -/ +def portBase (S : Scheme F) (q : Contraction.Prices F) (height : ℕ) := + 1000 + S.h + S.e + height + q.W + +/-- The quantity computed by `portBase S q height + 2 ^ S.e + S.ℓ + f`. -/ +def rowBase (S : Scheme F) (q : Contraction.Prices F) (height f : ℕ) := + portBase S q height + 2 ^ S.e + S.ℓ + f + +/-- The quantity computed by `rowBase S q height f + S.m + q.w + q.w ^ q.power`. -/ +def hostBase (S : Scheme F) (q : Contraction.Prices F) (height f : ℕ) := + rowBase S q height f + S.m + q.w + q.w ^ q.power + +/-- The bound obtained by adding the component charges `2 ^ S.m * (hostBase S q height f) ^ J + +2 ^ (S.m + S.h) * (rowBase S q height f) ^ J + N * (portBase S q height) ^ J`. -/ +def fullCost (S : Scheme F) (q : Contraction.Prices F) (height f N J : ℕ) := + 2 ^ S.m * (hostBase S q height f) ^ J + 2 ^ (S.m + S.h) * (rowBase S q height f) ^ J + + N * (portBase S q height) ^ J + +/-- The quantity computed by `J * (1 + S.ℓ + S.e + S.h + height + f)`. -/ +def fullArity (S : Scheme F) (height f J : ℕ) := J * (1 + S.ℓ + S.e + S.h + height + f) + +/-- The controlled of type `Prop` for the given inputs. -/ +def Controlled (K : Type) [Field K] (s : Plan) (p l b A J : ℕ) : Prop := + ∀ (F : Type) [Field F] [Fintype F] [Algebra K F] [ExpChar F p] + (T d f z : ℕ), Scales ((4 * 5) ^ 300) 10 s.D T (p ^ l) b d → Ready K 10 s.D ((4 * 5) ^ 300) (p + ^ l) b d → + A * (1 + T) ^ A ≤ Fintype.card F → T ≤ 2 ^ f → Fintype.card F ≤ 2 ^ f → + 0 < s.b * z → (s.b * z) * s.D ^ s.C ≤ T → T ≤ (s.b * z) * s.M → + ∀ (x y : Wire) (P : Layer F x y) (a : ℕ) (θ L : ℝ) (B : P.template.Binning a s.D T (d * b) θ) + (t : ∀ i, B.Trial (P.presents i) L) (q : Contraction.Prices F), + (∀ i, Nonempty (P.board i).V) → P.template.scheme.d ≤ 4 → B.target.m + P.height + J ≤ q.w → + ∃ (U : Assembly.Template F) (labels : Finset (Table F)), + U.scheme.h = a ∧ B.target.m ≤ U.scheme.m ∧ U.scheme.m ≤ B.target.m + J ∧ U.scheme.k = 0 ∧ + U.scheme.d ≤ J ∧ 2 ^ U.scheme.e ≤ J ∧ U.scheme.ℓ + U.count ≤ J * (B.target.ℓ + 1 + f) + ∧ labels.card ≤ J ∧ + Transforms F (fullArity B.target P.height f J) (↑labels) + (P.masked B t (Layer.panelRadius s.D)) (Contraction.publication U s T L z P.height) + (fullCost B.target q P.height f (wd x + wd y) J) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end + +/- # From grouped labels to the terminal motion records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer + +open Assembly Coloring Sphere.Surface.Local SphereScale +variable {F K : Type} [Field F] [Fintype F] [Field K] [Algebra K F] {x y : Wire} + {a D T b d ℓ p l : ℕ} [ExpChar F p] {θ L : ℝ} + (P : Layer F x y) (B : P.template.Binning a D T (d * b) θ) + (t : ∀ i, B.Trial (P.presents i) L) + +local notation "g" => ((4 * 5) ^ 300 : ℕ) +local notation "Cfg" => Input.design B.target g ℓ D b d p l +variable (sc : Scales g ℓ D T (p ^ l) b d) (hK : SphereScale.Ready K ℓ D g (p ^ l) b d) + (hF : room ℓ D g * (2 * depth ℓ D g (p ^ l) (d * b) + 1) < Fintype.card F) (k : ℕ) + +variable {k} (q : Contraction.Prices F) {u : ℕ} {labels : Set (Table F)} + +omit [Fintype F] [ExpChar F p] in +open scoped Classical in +private theorem pricesEq (S : Scheme F) (n i j r t p l k : ℕ) (Z : Format) : + let C := Input.design S n i j r t p l + let v := C.entryCap S.ℓ k + 2 ^ S.h * (Boot.own S.d (panelRadius j) (horizon (j ^ 5) C.waves 0) S.ℓ k).width ≤ v ∧ + Boot.cost S.m S.d S.h (panelRadius j) (horizon (j ^ 5) C.waves 0) S.ℓ k v (q.fee (S.m + + S.d) v) Z + + C.price q (Input.panelQuery S n i j r t p l k).width k Z ≤ C.work q S.ℓ k Z := + ⟨le_rfl, le_rfl⟩ + +open scoped Classical in +theorem moveLayer (ha : initialChoices ℓ D b d ≤ 2 ^ k) + (hk : Frame.budget F (Cfg).chart (Cfg).g (Cfg).H (Cfg).M (Cfg).D (Cfg).U ≤ 2 ^ k) + (hw : B.target.m + (Cfg).hops ≤ q.w) (hu : (Cfg).arity B.target.ℓ k ≤ u) + (ht : ↑(P.motionCalls B sc hK hF k) ⊆ labels) : + Transforms F u labels (P.masked B t (panelRadius D)) (P.moved B t sc hK hF k) + ((Cfg).work q B.target.ℓ k (P.panelPort B)) := by + have small : 3 ≤ u := (Nat.le_add_right ..).trans hu + have hm : 1 ≤ B.target.m + B.target.d := by + change 1 ≤ P.template.scheme.m + (P.template.scheme.h - a + 1) + _ + omega + have hd : B.target.d ≤ (Cfg).hops := (Cfg).degree_le_hops + have tag := q.access (L := labels) small hm ((Nat.add_le_add_left hd _).trans hw) + ((Cfg).entryCap B.target.ℓ k) + have fits : 2 * (Input.panelQuery B.target g ℓ D b d p l k).width ≤ u := by + rw [panelWidth_eq] + exact ((Cfg).entry_fits _ _).trans hu + have he := pricesEq q B.target g ℓ D b d p l k (P.panelPort B) + have h₀ := P.installPanel B t sc hK ha small tag he.1 fits (ht (Finset.mem_insert_self ..)) + have h₁ := P.movePanel B t sc hK hF q hk hw hu ht + exact (h₀.comp h₁).mono he.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- +# Cost of shipping the payload through concentration + +Factor out the number of hosts and blocks before bounding the +coefficients. Only the exterior-bit term uses the port base. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +open Assembly Rounds Coloring BatchDescent.Phase + +namespace Price + +/-- The data for the input construction, including `F`, `[field`, `S`, `U`, `c`. -/ +structure Input (J : ℕ) where + /-- The `Input` component of type `Type`. -/ + F : Type + [field : Field F] + /-- The `Input` component of type `Scheme F`. -/ + S : Scheme F + /-- The `Input` component of type `Assembly.Template F`. -/ + U : Assembly.Template F + /-- The remaining component. -/ + c : ℕ + /-- The `Input` field of type `ℕ`. -/ + e : ℕ + /-- The `Input` field of type `ℕ`. -/ + f : ℕ + /-- The `Input` field of type `ℕ`. -/ + k : ℕ + /-- The `Input` component of type `Family S U.scheme c`. -/ + A : Family S U.scheme c + /-- The `Input` component of type `Contraction.Prices F`. -/ + q : Contraction.Prices F + src : 2 ^ S.d ≤ J + dst : 2 ^ U.scheme.d ≤ J + fan : 2 ^ c ≤ J + spans : 2 ^ U.scheme.e ≤ J + labels : U.scheme.ℓ + U.count + e ≤ J * (1 + S.ℓ + f) + +attribute [instance] Input.field + +namespace Input +variable {J : ℕ} (i : Input J) +/-- The quantity computed by `i.k + 1`. -/ +abbrev w := i.k + 1 +/-- Uses `i.A.depth` as the representation. -/ +abbrev d := i.A.depth +/-- The quantity computed by `2 ^ i.c`. -/ +abbrev links := 2 ^ i.c +/-- The quantity computed by `1 + i.links`. -/ +abbrev hosts := 1 + i.links +/-- The quantity computed by `2 ^ (i.U.scheme.e + i.S.e)`. -/ +abbrev slots := 2 ^ (i.U.scheme.e + i.S.e) +/-- The quantity computed by `1000 + i.q.W + i.k + i.k`. -/ +abbrev bits := 1000 + i.q.W + i.k + i.k +/-- The quantity computed by `i.bits + i.c + i.w + i.d`. -/ +abbrev short := i.bits + i.c + i.w + i.d +/-- The quantity computed by `i.short + i.S.m + i.U.scheme.m + i.q.w + i.q.w ^ i.q.power`. -/ +abbrev long := i.short + i.S.m + i.U.scheme.m + i.q.w + i.q.w ^ i.q.power + +/-- The host charge used in the `Input` construction. -/ +def hostCharge (K : ℕ) := + 40 * (2 ^ i.S.d * i.S.m) + 52 * i.links * (2 ^ i.U.scheme.d * (i.U.scheme.m + 2) + 2) + + 4 * (i.hosts * 35 * (i.w + i.links * i.w) + 34 * i.links * (i.U.scheme.m + i.c)) + + i.hosts * i.links * i.long ^ K + i.hosts * i.bits ^ K + +/-- The row charge used in the `Input` construction. -/ +def rowCharge (K : ℕ) := + 40 * i.e + 52 * i.links * (i.U.scheme.ℓ + i.U.count) + + i.hosts * i.slots * (136 * (i.A.Question i.e).width + 1 + i.A.arity i.w i.e+ + 4 * (i.links * (100 + (2 * i.d + i.c + i.w)) ^ 140 + 35 * (i.c + 3 * i.w)) + + i.links * i.short ^ K) + +private theorem format_bound : i.U.scheme.format.width ≤ i.U.format.width := by + rw [Assembly.Template.format, Format.width_pair] + exact Nat.le_add_right .. + +theorem price_split : ∃ K : ℕ, ∀ (J : ℕ) (i : Input J) (N : ℕ), + price i.A i.k i.q i.e N ≤ 2 ^ i.S.m * i.hostCharge K + + 2 ^ (i.S.m + i.S.h) * i.rowCharge K + N * (2 * i.bits ^ K) := by + obtain ⟨K, h⟩ := Contraction.Prices.shipment_le + refine ⟨K, fun J i N => ?_⟩ + have h₁ := h i.F i.q i.U.format.width i.S.m (2 ^ i.S.m + N) i.k + i.U.scheme.m (2 ^ i.U.scheme.m + N) i.k i.c i.w i.d + have h₂ : (i.A.Data i.e).width ≤ (sourcePort i.S i.U i.e).width := by + rw [Family.Data, sourcePort, Format.width_pair, Format.width_pair] + exact Nat.add_le_add_left i.format_bound _ + have h₃ : controlCost i.A i.k i.e ≤ + 40 * (sourcePort i.S i.U i.e).width + 8 * i.U.format.width + 136 * (i.A.Jobs i.e).width+ + (2 ^ i.S.m + 2 ^ i.U.scheme.m) * (2 ^ i.d * (1 + i.A.arity i.w i.e))+ + 4 * SpanPlan.emitCost i.S.m i.U.scheme.m i.w i.c i.d := by + unfold controlCost Family.issueCost w d + omega + refine (Nat.add_le_add h₃ h₁).trans_eq ?_ + unfold hostCharge rowCharge + rw [sourcePort, Format.width_pair, Fmt.width_rows, Format.width_addr, Assembly.Template.width, + i.A.jobWidth, SpanPlan.emit_price] + simp only [w, d, short, long, bits, hosts, links, slots, Family.depth, ← i.A.height, pow_add, + i.A.dimensions] + generalize (100 + (2 * (i.S.h + (i.U.scheme.e + i.S.e)) + i.c + (i.k + 1))) ^ 140 = a + ring + +/-- Computes the port by the application `SphereScale.portBase i.S i.q i.k`. -/ +abbrev port := SphereScale.portBase i.S i.q i.k +/-- Computes the row by the application `SphereScale.rowBase i.S i.q i.k i.f`. -/ +abbrev row := SphereScale.rowBase i.S i.q i.k i.f +/-- Computes the host by the application `SphereScale.hostBase i.S i.q i.k i.f`. -/ +abbrev host := SphereScale.hostBase i.S i.q i.k i.f + +theorem port_two : 2 ≤ i.port := by unfold port SphereScale.portBase; omega +theorem port_row : i.port ≤ i.row := le_trans (le_trans (Nat.le_add_right ..) (Nat.le_add_right + ..)) (Nat.le_add_right ..) +theorem row_host : i.row ≤ i.host := by unfold row host SphereScale.hostBase; omega +theorem row_two : 2 ≤ i.row := i.port_two.trans i.port_row +theorem host_two : 2 ≤ i.host := i.row_two.trans i.row_host + +end Input +variable {J : ℕ} +local notation "I" => Input J +local notation "Port" => Poly (Input.port (J := J)) +local notation "Row" => Poly (Input.row (J := J)) +local notation "Host" => Poly (Input.host (J := J)) + +private theorem bits : Port (fun i => i.bits) := + ((Poly.const Input.port_two 2).mul (Poly.of_le Input.port_two (fun _ => le_rfl))).mono + (fun i => by unfold Input.bits Input.port SphereScale.portBase; omega) + +private theorem row_num (a : ℕ) : Row (fun _ => a) := Poly.const Input.row_two a +private theorem host_num (a : ℕ) : Host (fun _ => a) := Poly.const Input.host_two a + +private theorem fan : Row (fun i => 2 ^ i.c) := (row_num J).mono Input.fan +private theorem spans : Row (fun i => 2 ^ i.U.scheme.e) := (row_num J).mono Input.spans + +private theorem old : Row (fun i => 2 ^ i.S.e) := + Poly.of_le Input.row_two (fun i => by unfold Input.row SphereScale.rowBase; omega) + +private theorem labels : Row (fun i => i.U.scheme.ℓ + i.U.count + i.e) := by + refine ((row_num J).mul (Poly.of_le Input.row_two fun _ => le_rfl)).mono fun i => ?_ + refine i.labels.trans (Nat.mul_le_mul_left _ ?_) + change _ ≤ i.port + 2 ^ i.S.e + i.S.ℓ + i.f + have := i.port_two + generalize 2 ^ i.S.e = n + omega + +private theorem depth : Row (fun i => i.d) := by + have h : Port (fun i => i.S.h) := Poly.of_le Input.port_two + (fun i => by unfold Input.port SphereScale.portBase; omega) + exact (h.grow Input.port_row).add (spans.of_exp.add old.of_exp) + +private theorem length : Row (fun i => i.w) := by + have h : Port (fun i => i.w) := Poly.of_le Input.port_two + (fun i => by unfold Input.w Input.port SphereScale.portBase; omega) + exact h.grow Input.port_row + +private theorem short : Row (fun i => i.short) := + (((bits.grow Input.port_row).add fan.of_exp).add length).add depth + +private theorem rowCharge (K : ℕ) : Row (fun i => i.rowCharge K) := by + have hl : Row (fun i => i.U.scheme.ℓ + i.U.count) := labels.mono (fun _ => Nat.le_add_right ..) + have hd : Row (fun i => i.U.scheme.ℓ) := hl.mono (fun _ => Nat.le_add_right ..) + have he : Row (fun i => i.e) := labels.mono (fun _ => Nat.le_add_left ..) + have hh : Row (fun i => (i.A.Question i.e).width) := + ((((he.add (fan.mul hd)).add depth).add (row_num 1)).add fan.of_exp).mono + (fun i => (i.A.questionWidth i.e).le) + have ha : Row (fun i => i.A.arity i.w i.e) := + (((((he.add (fan.mul hd)).add ((row_num 2).mul depth)).add (row_num 1)).add + ((row_num 2).mul fan.of_exp)).add length).mono (fun i => (i.A.width i.w i.e).le) + have hpow := ((row_num (J := J) 100).add ((((row_num 2).mul depth).add fan.of_exp).add + length)).pow 140 + have htail := (row_num 4).mul ((fan.mul hpow).add + ((row_num 35).mul (fan.of_exp.add ((row_num 3).mul length)))) + have hctrl := ((((row_num 136).mul hh).add (row_num 1)).add ha).add htail + have htotal := ((row_num (J := J) 1).add fan).mul (spans.exp_add old) + exact (((row_num 40).mul he).add (((row_num 52).mul fan).mul hl)).add + (htotal.mul (hctrl.add (fan.mul (short.pow K)))) + +private theorem hostCharge (K : ℕ) : Host (fun i => i.hostCharge K) := by + have hm : Host (fun i => i.S.m) := + Poly.of_le Input.host_two (fun i => by unfold Input.host SphereScale.hostBase; omega) + have hw : Host (fun i => i.q.w) := + Poly.of_le Input.host_two (fun i => by unfold Input.host SphereScale.hostBase; omega) + have hv : Host (fun i => i.q.w ^ i.q.power) := + Poly.of_le Input.host_two (fun _ => Nat.le_add_left ..) + have hL : Host (fun i => 2 ^ i.c) := fan.grow Input.row_host + have hc := hL.of_exp + have hH := (host_num 1).add hL + have hM : Host (fun i => i.U.scheme.m) := (hm.add hc).mono (fun i => i.A.host.le) + have hl : Host (fun i => i.long) := ((((short.grow Input.row_host).add hm).add hM).add hw).add hv + have h₁ : Host (fun i => 2 ^ i.S.d) := (host_num J).mono Input.src + have h₂ : Host (fun i => 2 ^ i.U.scheme.d) := (host_num J).mono Input.dst + have hu := (host_num 40).mul (h₁.mul hm) + have ht := ((host_num 52).mul hL).mul ((h₂.mul (hM.add (host_num 2))).add (host_num 2)) + have ha := (length (J := J)).grow Input.row_host + have hd := ((hH.mul (host_num 35)).mul (ha.add (hL.mul ha))).add + (((host_num 34).mul hL).mul (hM.add hc)) + exact (((hu.add ht).add ((host_num 4).mul hd)).add ((hH.mul hL).mul (hl.pow K))).add + (hH.mul (((bits.grow Input.port_row).grow Input.row_host).pow K)) + +theorem uniform (J : ℕ) : ∃ k : ℕ, ∀ (i : Input J) (N : ℕ), + price i.A i.k i.q i.e N ≤ SphereScale.fullCost i.S i.q i.k i.f N k := by + obtain ⟨K, hK⟩ := Input.price_split + obtain ⟨a, ha⟩ := (hostCharge (J := J) K).bound + obtain ⟨b, hb⟩ := (rowCharge (J := J) K).bound + obtain ⟨c, hc⟩ := ((Poly.const Input.port_two 2).mul ((bits (J := J)).pow K)).bound + let n := max a (max b c) + refine ⟨n, fun i N => (hK J i N).trans ?_⟩ + have inc {z k : ℕ} (hz : 2 ≤ z) (hk : k ≤ n) : z ^ k ≤ z ^ n := + Nat.pow_le_pow_right (by omega) hk + exact Nat.add_le_add (Nat.add_le_add + (Nat.mul_le_mul_left _ ((ha i).trans (inc i.host_two (le_max_left ..)))) + (Nat.mul_le_mul_left _ ((hb i).trans (inc i.row_two ((le_max_left ..).trans (le_max_right + ..)))))) + (Nat.mul_le_mul_left _ ((hc i).trans (inc i.port_two ((le_max_right ..).trans (le_max_right + ..))))) + +end Price + +/-- At bounded degree the same exponent works for every field and payload size. -/ +theorem price_bound (J : ℕ) : ∃ K : ℕ, ∀ (F : Type) [Field F] + (S : Scheme F) (U : Assembly.Template F) (c e f height N : ℕ) + (A : Family S U.scheme c) (q : Contraction.Prices F), + 2 ^ S.d ≤ J → 2 ^ U.scheme.d ≤ J → 2 ^ c ≤ J → 2 ^ U.scheme.e ≤ J → + U.scheme.ℓ + U.count + e ≤ J * (1 + S.ℓ + f) → + price A height q e N ≤ SphereScale.fullCost S q height f N K := by + obtain ⟨k, hk⟩ := Price.uniform J + exact ⟨k, fun F _ S U c e f h N A q hd hd' hc he hl => + hk ⟨F, S, U, c, e, f, h, A, q, hd, hd', hc, he, hl⟩ N⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Payload +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Plant/Decoded.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Plant/Decoded.lean new file mode 100644 index 0000000000..b5cef9fcdf --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Plant/Decoded.lean @@ -0,0 +1,907 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import Mathlib.Data.Nat.ModEq +public import Mathlib.Algebra.BigOperators.Group.List.Basic +public import Mathlib.Data.List.OfFn +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Logic.Equiv.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Interpolation +public import Mathlib.LinearAlgebra.Finsupp.LinearCombination +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam +public import Mathlib.Data.List.FinRange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Block +public import Mathlib.Tactic.Positivity + +/-! +# Signs in the transposition of a matrix of generator blocks + +Reordering blocks uses only their lengths modulo two. The formula +therefore also applies with doubled energies in place of lengths. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant + +variable {R α β γ : Type*} [CommRing R] {k : α → α → R} + +private theorem contract_tail (f : α → R) (P Q : List α → R) (xs ys : List α) + (h : ∀ y ∈ ys, f y = 0) + (e : ∀ zs : List α, zs.Sublist xs → zs.length + 1 = xs.length → P (zs ++ ys) = Q zs) : + contract f P (xs ++ ys) = contract f Q xs := by + induction xs generalizing P Q with + | nil => exact contract_vanish f P ys h + | cons x xs ih => + rw [List.cons_append, contract_cons, contract_cons, e xs (by simp) rfl] + congr 1 + exact ih _ _ (fun zs hz he => e (x :: zs) (hz.cons_cons x) (by simp [he])) + +/-- If no pair crosses a boundary, the perfect matching sum factors. -/ +theorem wick_append (xs ys : List α) (h : ∀ x ∈ xs, ∀ y ∈ ys, k x y = 0) : + wick k (xs ++ ys) = wick k xs * wick k ys := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => simp + | cons x xs => + simp only [List.length_cons] at hn + simp only [List.forall_mem_cons] at h + rw [List.cons_append, wick_cons, wick_cons, mul_comm, ← contract_scale] + exact contract_tail _ _ _ _ _ h.1 fun zs hz he => + (ih zs.length (by omega) zs (fun z ht => h.2 z (hz.subset ht)) rfl).trans (mul_comm _ _) + +private theorem parity_length (l : List β) (f : β → List α) (a : β → ℕ) + (h : ∀ i, (f i).length % 2 = a i % 2) : + (l.flatMap f).length % 2 = (l.map a).sum % 2 := by + induction l with + | nil => rfl + | cons x l ih => + rw [List.flatMap_cons, List.length_append, List.map_cons, List.sum_cons] + exact Nat.ModEq.add (h x) ih + +/-- Number of transpositions when interleaving two rows of blocks. -/ +def interlace (a b : β → ℕ) : List β → ℕ + | [] => 0 + | j :: js => (js.map a).sum * b j + interlace a b js + +theorem wick_interlace (sk : ∀ x y, k y x = -k x y) (f g : β → List α) (a b : β → ℕ) + (hf : ∀ i, (f i).length % 2 = a i % 2) (hg : ∀ i, (g i).length % 2 = b i % 2) + (l : List β) (p q : List α) : + wick k (p ++ l.flatMap f ++ l.flatMap g ++ q) = (-1 : R) ^ interlace a b l * + wick k (p ++ l.flatMap (fun i => f i ++ g i) ++ q) := by + induction l generalizing p with + | nil => simp [interlace] + | cons j js ih => + have e := wick_swap_blocks sk (p ++ f j) (js.flatMap f) (g j) (js.flatMap g ++ q) + have t := ih (p ++ f j ++ g j) + have hs : (-1 : R) ^ ((js.flatMap f).length * (g j).length) = (-1) ^ ((js.map a).sum * b j) + := by + rw [neg_one_pow_eq_pow_mod_two, neg_one_pow_eq_pow_mod_two ((js.map a).sum * b j)] + congr 1 + exact Nat.ModEq.mul (parity_length js f a hf) (hg j) + rw [hs] at e + simp only [List.flatMap_cons, List.append_assoc, interlace, pow_add, mul_assoc] at e t ⊢ + rw [e, t] + +/-- Transpositions in changing from site order to species order. -/ +def shuffle (a : β → γ → ℕ) (cols : List γ) : List β → ℕ + | [] => 0 + | i :: is => shuffle a cols is + interlace (a i) (fun j => (is.map (a · j)).sum) cols + +theorem wick_shuffle (sk : ∀ x y, k y x = -k x y) (f : β → γ → List α) (a : β → γ → ℕ) + (h : ∀ i j, (f i j).length % 2 = a i j % 2) + (rows : List β) (cols : List γ) (p q : List α) : + wick k (p ++ rows.flatMap (fun i => cols.flatMap (f i)) ++ q) = + (-1 : R) ^ shuffle a cols rows * + wick k (p ++ cols.flatMap (fun j => rows.flatMap (f · j)) ++ q) := by + induction rows generalizing p with + | nil => + have e : cols.flatMap (fun _ => ([] : List α)) = [] := by + induction cols with + | nil => rfl + | cons _ _ ih => simp [ih] + simp [shuffle, e] + | cons i is ih => + have e := ih (p ++ cols.flatMap (f i)) + have t := wick_interlace sk (f i) (fun j => is.flatMap (f · j)) + (a i) (fun j => (is.map (a · j)).sum) (h i) + (fun j => parity_length is _ _ (fun s => h s j)) cols p q + simp only [List.flatMap_cons, List.append_assoc, shuffle, pow_add, mul_assoc] at e t ⊢ + rw [e, t] + +@[simp] theorem interlace_zero (b : β → ℕ) (l : List β) : interlace (fun _ => 0) b l = 0 := by + induction l with + | nil => rfl + | cons x l ih => simp [interlace, ih] + +@[simp] theorem shuffle_zero (rows : List β) (cols : List γ) : shuffle (fun _ _ => 0) cols rows = 0 + := by + induction rows with + | nil => rfl + | cons x xs ih => simp [shuffle, ih] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant +end + +section +/- # Signs within and between blocks of species -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant + +variable {A B D : Type*} + +private theorem interlace_append (a b : A → ℕ) (x y : List A) : + interlace a b (x ++ y) = interlace a b x + interlace a b y + + (y.map a).sum * (x.map b).sum := by + induction x with + | nil => simp [interlace] + | cons i x ih => simp [interlace, ih]; ring + +private theorem interlace_map (a b : A → ℕ) (f : B → A) (x : List B) : + interlace a b (x.map f) = interlace (a ∘ f) (b ∘ f) x := by + induction x with + | nil => rfl + | cons i x ih => simp [interlace, ih] + +private theorem interlace_blocks (d k : ℕ) (a b : Fin (d * k) → ℕ) : + interlace a b (List.finRange (d * k)) = + interlace (fun i => ∑ j, a (finProdFinEquiv (i, j))) (fun i => ∑ j, b (finProdFinEquiv (i, + j))) + (List.finRange d) + + ∑ i, interlace (fun j => a (finProdFinEquiv (i, j))) (fun j => b (finProdFinEquiv (i, j))) + (List.finRange k) := by + let f (i : Fin d) (j : Fin k) := finProdFinEquiv (i, j) + let v (i : Fin d) := (List.finRange k).map (f i) + have hv : List.finRange (d * k) = (List.finRange d).flatMap v := by + have h := List.ofFn_mul (id : Fin (d * k) → Fin (d * k)) + simp only [List.ofFn_eq_map, List.map_id, id_eq] at h + rw [h] + congr 2 + funext i + apply List.map_congr_left + intro j _ + apply Fin.ext + simp [f, mul_comm, add_comm] + have hs (u : Fin (d * k) → ℕ) (i : Fin d) : ((v i).map u).sum = ∑ j, u (f i j) := by + simp only [v, List.map_map, Function.comp_def] + rw [← List.ofFn_eq_map, List.sum_ofFn] + have ht (l : List (Fin d)) : ((l.flatMap v).map a).sum = (l.map (fun i => ∑ j, a (f i j))).sum + := by + induction l with + | nil => rfl + | cons i l ih => simp [ih, hs] + have he (l : List (Fin d)) : + interlace a b (l.flatMap v) = + interlace (fun i => ∑ j, a (f i j)) (fun i => ∑ j, b (f i j)) l + + (l.map (fun i => interlace (a ∘ f i) (b ∘ f i) (List.finRange k))).sum := by + induction l with + | nil => rfl + | cons i l ih => + rw [List.flatMap_cons, interlace_append, ih, ht, hs] + simp only [interlace, List.map_cons, List.sum_cons, v, interlace_map] + omega + rw [hv, he] + simp only [← List.ofFn_eq_map, List.sum_ofFn, Function.comp_def, f] + +/-- Once the intra-block signs are known, the remaining sign only +uses the total occupancy of each block at each mark. -/ +theorem shuffle_blocks (d b : ℕ) (ε : A → Fin (d * b) → ℕ) (rows : List A) : + shuffle ε (List.finRange (d * b)) rows = + shuffle (fun i c => ∑ j : Fin b, ε i (finProdFinEquiv (c, j))) (List.finRange d) rows + + ∑ c : Fin d, shuffle (fun i j => ε i (finProdFinEquiv (c, j))) (List.finRange b) rows := by + have commute (f : A → Fin b → ℕ) (l : List A) : + (∑ j, (l.map (f · j)).sum) = (l.map (fun i => ∑ j, f i j)).sum := by + induction l with + | nil => simp + | cons i l ih => simp only [List.map_cons, List.sum_cons, Finset.sum_add_distrib, ih] + induction rows with + | nil => simp [shuffle] + | cons i rows ih => + simp only [shuffle, ih, interlace_blocks d b, Finset.sum_add_distrib] + have h (c : Fin d) := commute (fun i j => ε i (finProdFinEquiv (c, j))) rows + simp only [h] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant +end + +section +/- +# One auxiliary probe per coded mode + +The covectors are prescribed only on the mode prefixes used in the +fixed-energy codes. The remaining modes have higher normalized weight. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant + +open Finset + +theorem probe_basis {F : Type*} [Field F] {m n : ℕ} (z : Fin m ↪ F) (y : Fin n ↪ F) + (hz : ∀ i j, y j ≠ z i) (b : Fin m → ℕ) (hn : (∑ i, 4 * b i) ≤ n) (v : Mode m → F) : + ∃ c : Fin n → F, ∀ i : Mode m, i.2 < 4 * b i.1 → + (∑ j, c j * (y j - z i.1)⁻¹ ^ (i.2 + 1)) = v i := by + classical + let T := Σ i, Fin (4 * b i) + let h : T ↪ F × ℕ := ⟨fun x => (z x.1, x.2.val), by + rintro ⟨i, k⟩ ⟨j, l⟩ e + have : i = j := z.injective (congrArg Prod.fst e) + subst j + rw [show k = l from Fin.ext (congrArg Prod.snd e)]⟩ + let q (x : F) := ∑ i, if z i = x then 4 * b i else 0 + have hq (i) : q (z i) = 4 * b i := by simp [q, z.injective.eq_iff] + have hd : ∑ x ∈ univ.image z, q x ≤ Fintype.card (Fin n) := by + simpa only [sum_image z.injective.injOn, hq, Fintype.card_fin] using hn + let p (j : Fin n) (x : T) := (y j - z x.1)⁻¹ ^ (x.2.val + 1) + have he : Submodule.span F (Set.range p) = ⊤ := + cauchy_span_degrees h y (univ.image z) q + (fun i => mem_image_of_mem _ (mem_univ i.1)) + (fun i => by change i.2.val < q (z i.1); rw [hq]; exact i.2.isLt) + (fun j i => hz i.1 j) hd + have hm : (fun x : T => v (x.1, x.2.val)) ∈ Submodule.span F (Set.range p) := by simp [he] + obtain ⟨c, hc⟩ := (Submodule.mem_span_range_iff_exists_fun F).mp hm + refine ⟨c, fun i hi => ?_⟩ + simpa [p, Finset.sum_apply] using congrFun hc ⟨i.1, ⟨i.2, hi⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant +end + +section +/- # Ordered wedges and their single-species components -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant + +variable {r : ℕ} + +/-- The value specified by `(i, x.2)`. -/ +def place (i : Fin r) (x : Mode 1) : Mode r := (i, x.2) + +theorem lt_one {x y : Mode 1} : toLex x < toLex y ↔ x.2 < y.2 := by + rw [Prod.Lex.toLex_lt_toLex, Subsingleton.elim x.1 y.1] + simp + +/-- The pack of type `Wedge r` for the given inputs. -/ +def pack (u : Fin r → Wedge 1) : Wedge r := by + refine ⟨(List.finRange r).flatMap (fun i => (u i).val.map (place i)), ?_⟩ + rw [List.pairwise_flatMap] + constructor + · intro i _ + apply List.pairwise_map.mpr + refine (u i).property.imp ?_ + intro x y h + exact Prod.Lex.toLex_lt_toLex.mpr (.inr ⟨rfl, lt_one.mp h⟩) + · refine (List.sortedLT_finRange r).pairwise.imp ?_ + intro i j h x hx y hy + obtain ⟨_, _, rfl⟩ := List.mem_map.mp hx + obtain ⟨_, _, rfl⟩ := List.mem_map.mp hy + exact Prod.Lex.toLex_lt_toLex.mpr (.inl h) + +/-- The slice of type `Wedge 1` for the given inputs. -/ +def slice (u : Wedge r) (i : Fin r) : Wedge 1 := by + refine ⟨(u.val.filter (fun x => x.1 = i)).map (fun x => (0, x.2)), ?_⟩ + rw [List.pairwise_map] + apply List.Pairwise.imp_of_mem _ (u.property.filter _) + intro x y hx hy h + apply lt_one.mpr + simp only [List.mem_filter, decide_eq_true_eq] at hx hy + simpa [Prod.Lex.toLex_lt_toLex, hx.2, hy.2] using h + +theorem wedge_perm {u v : Wedge r} (h : u.val.Perm v.val) : u = v := + Subtype.ext (h.eq_of_pairwise (fun _ _ _ _ h ht => (h.asymm ht).elim) u.property v.property) + +theorem mem_pack (u : Fin r → Wedge 1) (i : Fin r) (m : ℕ) : + (i, m) ∈ (pack u).val ↔ (0, m) ∈ (u i).val := by + simp only [pack, List.mem_flatMap, List.mem_finRange, true_and, List.mem_map] + constructor + · rintro ⟨j, ⟨k, n⟩, h, eq⟩ + obtain ⟨rfl, rfl⟩ := Prod.mk.inj eq + exact Subsingleton.elim k 0 ▸ h + · exact fun h => ⟨i, (0, m), h, rfl⟩ + +theorem mem_slice (u : Wedge r) (i : Fin r) (m : ℕ) : + (0, m) ∈ (slice u i).val ↔ (i, m) ∈ u.val := by + simp [slice] + +@[simp] theorem pack_slice (u : Wedge r) : pack (slice u) = u := by + apply wedge_perm + apply (List.perm_ext_iff_of_nodup (pack _).nodup u.nodup).mpr + rintro ⟨i, m⟩ + rw [mem_pack, mem_slice] + +@[simp] theorem slice_pack (u : Fin r → Wedge 1) (i : Fin r) : slice (pack u) i = u i := by + apply wedge_perm + apply (List.perm_ext_iff_of_nodup (slice _ _).nodup (u i).nodup).mpr + rintro ⟨j, m⟩ + rw [Subsingleton.elim j 0, mem_slice, mem_pack] + +theorem sum_pack {M : Type*} [AddCommMonoid M] (f : Mode r → M) (u : Fin r → Wedge 1) : + ((pack u).val.map f).sum = ∑ i, ((u i).val.map (fun x => f (place i x))).sum := by + have h (l : List (Fin r)) : + ((l.flatMap (fun i => (u i).val.map (place i))).map f).sum = + (l.map (fun i => ((u i).val.map (fun x => f (place i x))).sum)).sum := by + induction l with + | nil => rfl + | cons j l ih => simp [List.map_map, Function.comp_def, ih] + simp only [pack, h, ← List.ofFn_eq_map, List.sum_ofFn] + +theorem energy_pack (u : Fin r → Wedge 1) : energy (pack u).val = ∑ i, energy (u i).val := by + unfold energy + rw [sum_pack] + rfl + +theorem length_pack (u : Fin r → Wedge 1) : (pack u).val.length = ∑ i, (u i).val.length := by + simp [pack, List.length_flatMap, ← List.ofFn_eq_map, List.sum_ofFn] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant +end + +section +/- # Factorization of the sphere form into independent species -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant + +variable {F A : Type*} [Field F] {r : ℕ} + +/-- The value specified by `(x.1, place j x.2)`. -/ +def put (j : Fin r) (x : Site F 1) : Site F r := (x.1, place j x.2) + +private theorem kernel_put (j : Fin r) (x y : Site F 1) : + fieldKernel (put j x) (put j y) = fieldKernel x y := by + simp [fieldKernel, coeff, put, place, Subsingleton.elim x.2.1 y.2.1] + +private theorem columns (xs : Fin r → List (Site F 1)) : + wick fieldKernel ((List.finRange r).flatMap (fun j => (xs j).map (put j))) = + ∏ j, wick fieldKernel (xs j) := by + have aux (l : List (Fin r)) (h : l.Nodup) : + wick fieldKernel (l.flatMap (fun j => (xs j).map (put j))) = + (l.map (fun j => wick fieldKernel (xs j))).prod := by + induction l with + | nil => simp + | cons j l ih => + rw [List.flatMap_cons, wick_append, ih (List.nodup_cons.mp h).2, wick_map] + · simp only [kernel_put, List.map_cons, List.prod_cons] + · intro x hx y hy + obtain ⟨x, _, rfl⟩ := List.mem_map.mp hx + obtain ⟨i, hi, hy⟩ := List.mem_flatMap.mp hy + obtain ⟨y, _, rfl⟩ := List.mem_map.mp hy + have hn : j ≠ i := fun e => (List.nodup_cons.mp h).1 (e ▸ hi) + simp [put, place, fieldKernel, coeff, hn] + simpa only [← List.ofFn_eq_map, List.prod_ofFn] using aux _ (List.nodup_finRange r) + +/-- Transforms the indexed data by `l.flatMap (fun i => (X i).val.map (z i, ·))`. -/ +def bundle (z : A → F) (X : A → Wedge r) (l : List A) : List (Site F r) := + l.flatMap (fun i => (X i).val.map (z i, ·)) + +private theorem bundle_shuffle (z : A → F) (X : A → Fin r → Wedge 1) (e : A → Fin r → ℕ) + (h : ∀ i j, (X i j).val.length % 2 = e i j % 2) (l : List A) (p q : List (Site F r)) : + wick fieldKernel (p ++ bundle z (fun i => pack (X i)) l ++ q) = + (-1 : F) ^ shuffle e (List.finRange r) l * + wick fieldKernel (p ++ (List.finRange r).flatMap + (fun j => (bundle z (X · j) l).map (put j)) ++ q) := by + let f i j := (X i j).val.map (fun x => (z i, place j x)) + have hm (i j) : (f i j).length % 2 = e i j % 2 := by simpa [f] using h i j + simpa [bundle, pack, f, put, List.map_flatMap, List.map_map, Function.comp_def] using + wick_shuffle fieldKernel_skew f e hm l (List.finRange r) p q + +/-- The sign only uses the parities of the individual wedges. -/ +theorem wick_species (z : A → F) (X : A → Fin r → Wedge 1) (e : A → Fin r → ℕ) + (h : ∀ i j, (X i j).val.length % 2 = e i j % 2) (l : List A) : + wick fieldKernel (l.flatMap (fun i => (pack (X i)).val.map (z i, ·))) = + (-1 : F) ^ shuffle e (List.finRange r) l * + ∏ j, wick fieldKernel (l.flatMap (fun i => (X i j).val.map (z i, ·))) := by + have he := bundle_shuffle z X e h l [] [] + simp only [List.nil_append, List.append_nil, columns] at he + exact he + +/-- When the first group has even length in every species, its +shuffle sign and the second group's shuffle sign are independent. -/ +theorem wick_two_groups {B : Type*} (z : A → F) (y : B → F) + (X : A → Fin r → Wedge 1) (Y : B → Fin r → Wedge 1) (l : List A) (m : List B) + (a : A → Fin r → ℕ) (b : B → Fin r → ℕ) + (ha : ∀ i j, (X i j).val.length % 2 = a i j % 2) + (hb : ∀ i j, (Y i j).val.length % 2 = b i j % 2) + (he : ∀ j, (bundle z (X · j) l).length % 2 = 0) : + wick fieldKernel (bundle z (fun i => pack (X i)) l ++ bundle y (fun i => pack (Y i)) m) = + (-1 : F) ^ shuffle a (List.finRange r) l * (-1) ^ shuffle b (List.finRange r) m * + ∏ j, wick fieldKernel (bundle z (X · j) l ++ bundle y (Y · j) m) := by + let f j := (bundle z (X · j) l).map (put j) + let g j := (bundle y (Y · j) m).map (put j) + have h₁ := bundle_shuffle z X a ha l [] (bundle y (fun i => pack (Y i)) m) + have h₂ := bundle_shuffle y Y b hb m ((List.finRange r).flatMap f) [] + have h₃ := wick_interlace fieldKernel_skew f g (fun _ => 0) (fun j => (g j).length) + (fun j => by simp [f, he]) (fun _ => rfl) (List.finRange r) [] [] + simp only [List.nil_append, List.append_nil, interlace_zero, pow_zero, one_mul] at h₁ h₂ h₃ + rw [h₁, h₂, h₃, mul_assoc] + simp only [f, g, ← List.map_append, columns] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant +end + +/- +# Planting one species with linearly many auxiliary marks + +Site `i` carries `b i` coded bits, using the first `4 * b i` modes. +After rescaling weights at each site, all tested modes cost at most +eight and every untested mode costs strictly more. Thus interpolation +of just the tested modes suffices under a total weighted budget. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant + +open Finset +variable {F : Type*} [Field F] {m n d : ℕ} + +open scoped Classical in +instance : Fintype (Probe n d) := by + refine Fintype.ofInjective (fun x : Probe n d => (x.val.val.map Prod.fst).toFinset) ?_ + intro x y h + apply Subtype.ext + apply wedge_perm + apply (List.perm_ext_iff_of_nodup x.val.nodup y.val.nodup).mpr + have he (x : Probe n d) (i : Fin n) (j : ℕ) : + (i, j) ∈ x.val.val ↔ i ∈ (x.val.val.map Prod.fst).toFinset ∧ j = 0 := by + simp only [List.mem_toFinset, List.mem_map] + constructor + · exact fun h => ⟨⟨_, h, rfl⟩, x.property.1 _ h⟩ + · rintro ⟨⟨⟨k, j⟩, h, rfl⟩, rfl⟩ + exact (show j = 0 from x.property.1 _ h) ▸ h + rintro ⟨i, j⟩ + dsimp only at h + rw [he, he, h] + +open scoped Classical in +/-- The condition `∀ i, Fin (b i) → Bool` on the specified data. -/ +abbrev Bits (b : Fin m → ℕ) := ∀ i, Fin (b i) → Bool + +open scoped Classical in +/-- The indexed operation `pack (fun i => (bitCode (b i) (x i)).val)`. -/ +def coded (b : Fin m → ℕ) (x : Bits b) : Wedge m := + pack (fun i => (bitCode (b i) (x i)).val) + +open scoped Classical in +/-- Assigns cost nine to the zero mode and reciprocal cost to each positive mode. -/ +def unitCost (n : ℕ) : ℝ := if n = 0 then 9 else (n : ℝ)⁻¹ + +open scoped Classical in +/-- The quantity computed by `(2 * x.2 + 1) * unitCost (b x.1)`. -/ +def price (b : Fin m → ℕ) (x : Mode m) : ℝ := (2 * x.2 + 1) * unitCost (b x.1) + +open scoped Classical in +/-- Transforms the indexed data by `(x.val.map (price b)).sum`. -/ +def cost (b : Fin m → ℕ) (x : Wedge m) : ℝ := (x.val.map (price b)).sum + +open scoped Classical in +/-- The sum of `(8 * b i ^ 2 : ℕ) * unitCost (b i)` indexed by `i`. -/ +def budget (b : Fin m → ℕ) : ℝ := ∑ i, (8 * b i ^ 2 : ℕ) * unitCost (b i) + +open scoped Classical in +private theorem price_pos (b : Fin m → ℕ) (x : Mode m) : 0 < price b x := by + unfold price unitCost + split_ifs <;> positivity + +open scoped Classical in +private theorem small (b : Fin m → ℕ) (x : Mode m) : price b x ≤ 8 ↔ x.2 < 4 * b x.1 := by + unfold price unitCost + split_ifs with h + · have := Nat.cast_nonneg (α := ℝ) x.2 + simp only [h, mul_zero, Nat.not_lt_zero, iff_false] + linarith + · rw [← div_eq_mul_inv, div_le_iff₀ (by positivity)] + have : 2 * x.2 + 1 ≤ 8 * b x.1 ↔ x.2 < 4 * b x.1 := by omega + exact_mod_cast this + +open scoped Classical in +theorem cost_pack (b : Fin m → ℕ) (x : Fin m → Wedge 1) : + cost b (pack x) = ∑ i, energy (x i).val * unitCost (b i) := by + unfold cost + rw [sum_pack] + refine sum_congr rfl fun i _ => ?_ + induction (x i).val with + | nil => simp [energy] + | cons a l ih => + simp only [List.map_cons, List.sum_cons, ih] + simp [energy, place, price, add_mul] + +open scoped Classical in +theorem cost_coded (b : Fin m → ℕ) (x : Bits b) : cost b (coded b x) = budget b := by + rw [coded, cost_pack] + exact sum_congr rfl fun i _ => by rw [(bitCode _ (x i)).property] + +open scoped Classical in +/-- The value specified by `(z i.1, i.2)`. -/ +def slots (z : Fin m → F) (i : Mode m) : F × ℕ := (z i.1, i.2) + +variable (z : Fin m ↪ F) (y : Fin n ↪ F) (hz : ∀ i j, y j ≠ z i) +variable (b : Fin m → ℕ) (hn : (∑ i, 4 * b i) ≤ n) + +include hz hn in +open scoped Classical in +theorem selector (x : Bits b) : + ∃ c : Probe n (∑ i, 2 * b i) → F, ∀ w : Wedge m, cost b w ≤ budget b → + ∑ p, c p * probeEval (slots z) y p w.val = if coded b x = w then 1 else 0 := by + let delta (i j : Mode m) : F := if i = j then -1 else 0 + choose t ht using fun i => probe_basis z y hz b hn (delta i) + let row (i j : Mode m) := if price b i ≤ 8 then + ∑ k, t i k * (y k - z j.1)⁻¹ ^ (j.2 + 1) else delta i j + have tri (i j) (h : price b j ≤ price b i) : -row i j = if i = j then 1 else 0 := by + have he : row i j = delta i j := by + unfold row + split_ifs with hi + · exact ht i j ((small b j).mp (h.trans hi)) + · rfl + rw [he] + simp only [delta, neg_ite, neg_neg, neg_zero] + let u := coded b x + have len : u.val.length = ∑ i, 2 * b i := by simp [u, coded, length_pack, bitCode_length] + have even : u.val.length % 2 = 0 := by rw [len, ← mul_sum]; omega + have hc (i : Mode m) (hi : i ∈ u.val) : ∃ c : Fin n → F, + ∀ j, ∑ k, c k * (y k - (slots z j).1)⁻¹ ^ ((slots z j).2 + 1) = row i j := by + have hp : price b i ≤ 8 := by + apply (small b i).mpr + rcases i with ⟨l, j⟩ + exact bitCode_support (x l) (0, j) ((mem_pack _ l j).mp hi) + exact ⟨t i, fun j => (ite_eq_left hp).symm⟩ + obtain ⟨c, he⟩ := weighted_probe (slots z) y (price b) (price_pos b) _ u.nodup len.le even row + tri hc + refine ⟨c, fun w hw => ?_⟩ + have h : cost b w ≤ cost b u := by rw [cost_coded]; exact hw + have key := he w.val (fun h => congrArg Subtype.val (wedge_perm h)) h + rw [sum_subset (subset_univ _) (fun p _ hp => by + rw [Finsupp.notMem_support_iff.mp hp, zero_mul])] at key + simpa only [show u.val = w.val ↔ u = w from Subtype.ext_iff.symm] using key + +open scoped Classical in +/-- Extend a bit table by zero to all unrecognized words. -/ +def decoded (L : Bits b → F) (w : Wedge m) : F := + ∑ x, if coded b x = w then L x else 0 + +open scoped Classical in +theorem coded_injective : Function.Injective (coded b) := by + intro x y h + funext i + apply (bitCode _).injective + apply Subtype.ext + simpa only [coded, slice_pack] using congrArg (fun z => slice z i) h + +open scoped Classical in +@[simp] theorem decoded_coded (L : Bits b → F) (x : Bits b) : + decoded b L (coded b x) = L x := by + simp [decoded, (coded_injective b).eq_iff] + +open scoped Classical in +theorem exists_code {L : Bits b → F} {w : Wedge m} (h : decoded b L w ≠ 0) : + ∃ x, coded b x = w := by + by_contra! hn + simp [decoded, hn] at h + +include hz hn in +open scoped Classical in +theorem plant_one (L : Bits b → F) : + ∃ c : Probe n (∑ i, 2 * b i) → F, ∀ w : Wedge m, cost b w ≤ budget b → + ∑ p, c p * probeEval (slots z) y p w.val = decoded b L w := by + choose t ht using selector z y hz b hn + refine ⟨fun p => ∑ x, L x * t x p, fun w hw => ?_⟩ + simp only [sum_mul, mul_assoc] + rw [sum_comm] + simp only [← mul_sum, ht _ w hw, mul_ite, mul_one, mul_zero, decoded] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant +end + +/- # Occupancy words for the auxiliary marks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant + +open Finset +variable {m n d r : ℕ} {F : Type*} [Field F] + +open scoped Classical in +/-- In the case `false`, this construction gives `⟨[], by simp⟩`. -/ +def lowest : Bool → Wedge 1 + | false => ⟨[], by simp⟩ + | true => ⟨[(0, 0)], by simp⟩ + +open scoped Classical in +@[simp] theorem energy_lowest (x : Bool) : energy (lowest x).val = x.toNat := by cases x <;> rfl +open scoped Classical in +@[simp] theorem length_lowest (x : Bool) : (lowest x).val.length = x.toNat := by cases x <;> rfl + +open scoped Classical in +/-- The indexed operation `pack (fun j => lowest (x j))`. -/ +def occupancy (x : Fin r → Bool) : Wedge r := pack (fun j => lowest (x j)) + +open scoped Classical in +theorem energy_occupancy (x : Fin r → Bool) : energy (occupancy x).val = ∑ j, (x j).toNat := by + rw [occupancy, energy_pack] + simp only [energy_lowest] + +open scoped Classical in +theorem length_occupancy (x : Fin r → Bool) : (occupancy x).val.length = ∑ j, (x j).toNat := by + rw [occupancy, length_pack] + simp only [length_lowest] + +open scoped Classical in +theorem occupancy_injective : Function.Injective (occupancy (r := r)) := by + intro x y h + funext j + have he := congrArg (fun p => (slice p j).val.length) h + simp only [occupancy, slice_pack, length_lowest] at he + cases hx : x j <;> cases hy : y j <;> simp_all + +open scoped Classical in +/-- Tests whether `(i, 0) ∈ p.val.val` holds. -/ +def probeBit (p : Probe n d) (i : Fin n) := decide ((i, 0) ∈ p.val.val) + +open scoped Classical in +theorem occupancy_probe (p : Probe n d) : occupancy (probeBit p) = p.val := by + apply wedge_perm + apply (List.perm_ext_iff_of_nodup (occupancy _).nodup p.val.nodup).mpr + rintro ⟨i, j⟩ + rw [occupancy, mem_pack] + by_cases h : (i, 0) ∈ p.val.val + · simpa [probeBit, h, lowest] using + (show j = 0 ↔ (i, j) ∈ p.val.val from ⟨fun he => he ▸ h, fun he => p.property.1 _ he⟩) + · simpa [probeBit, h, lowest] using + (show (i, j) ∉ p.val.val from fun he => h ((show j = 0 from p.property.1 _ he) ▸ he)) + +omit [Field F] in +open scoped Classical in +theorem bundle_pack (z : Fin m → F) (x : Fin m → Wedge 1) : + bundle z x (List.finRange m) = (pack x).val.map (mark (slots z)) := by + simp only [bundle, pack, List.map_flatMap, List.map_map, Function.comp_def, mark, slots, place] + congr 1 + funext i + refine List.map_congr_left fun j _ => ?_ + exact congrArg (z i, ·) (Prod.ext (Subsingleton.elim _ _) rfl) + +open scoped Classical in +/-- The contribution of one species of the auxiliary state. -/ +def response (z : Fin m → F) (y : Fin n → F) (J : (Fin n → Bool) → F) (w : Wedge m) : F := + ∑ x, J x * wick fieldKernel + ((occupancy x).val.map (mark (slots y)) ++ w.val.map (mark (slots z))) + +open scoped Classical in +theorem plant_bits (z : Fin m ↪ F) (y : Fin n ↪ F) (hz : ∀ i j, y j ≠ z i) + (b : Fin m → ℕ) (hn : (∑ i, 4 * b i) ≤ n) (L : Bits b → F) : + ∃ J : (Fin n → Bool) → F, + (∀ x, J x ≠ 0 → (∑ j, (x j).toNat) ≤ (∑ i, 2 * b i) ∧ (∑ j, (x j).toNat) % 2 = 0) ∧ + ∀ w, cost b w ≤ budget b → response z y J w = decoded b L w := by + obtain ⟨c, hc⟩ := plant_one z y hz b hn L + let J x := ∑ p, if x = probeBit p then c p else 0 + refine ⟨J, ?_, fun w hw => ?_⟩ + · intro x hx + obtain ⟨p, _, h⟩ := exists_ne_zero_of_sum_ne_zero hx + have : x = probeBit p := by by_contra hn; simp [hn] at h + rw [← length_occupancy, this, occupancy_probe] + exact p.property.2 + unfold response J + simp only [sum_mul, ite_mul, zero_mul] + rw [sum_comm] + simp only [sum_ite_eq', mem_univ, ite_true, occupancy_probe] + exact hc w hw + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant +end + +/- +# Planting across independent species + +Only the total energy at each original mark is fixed. This fixes the +total weight across species. If one species exceeds its budget, a +second is under budget and its selector vanishes. Thus exact levels +at every mark in every species follow without a separate check on +each seam. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant + +open Finset +variable {F : Type*} [Field F] {r m n : ℕ} + +open scoped Classical in +/-- The indexed operation `pack (fun i => slice (X i) j)`. -/ +def column (X : Fin m → Wedge r) (j : Fin r) := pack (fun i => slice (X i) j) + +open scoped Classical in +private theorem total_cost (b : Fin m → ℕ) (X : Fin m → Wedge r) + (hX : ∀ i, energy (X i).val = r * (8 * b i ^ 2)) : + ∑ j, cost b (column X j) = ∑ _ : Fin r, budget b := by + simp only [column, cost_pack] + rw [sum_comm] + simp only [← sum_mul, ← Nat.cast_sum, ← energy_pack, pack_slice, hX, Nat.cast_mul, budget, + sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul, mul_sum, mul_assoc] + +open scoped Classical in +private theorem budget_guard (b : Fin m → ℕ) (L : Bits b → F) (f : Wedge m → F) + (hf : ∀ x, cost b x ≤ budget b → f x = decoded b L x) + (X : Fin m → Wedge r) (hX : ∀ i, energy (X i).val = r * (8 * b i ^ 2)) : + ∏ j, f (column X j) = ∏ j, decoded b L (column X j) := by + by_cases he : ∀ j, cost b (column X j) ≤ budget b + · exact prod_congr rfl fun j _ => hf _ (he j) + push Not at he + obtain ⟨j, hj⟩ := he + obtain ⟨i, hi⟩ : ∃ i, cost b (column X i) < budget b := by + by_contra! nh + have h := sum_lt_sum (s := univ) (fun i _ => nh i) ⟨j, mem_univ j, hj⟩ + exact (total_cost b X hX).not_gt h + have z : decoded b L (column X i) = 0 := by + by_contra hn + obtain ⟨v, hv⟩ := exists_code b hn + rw [← hv, cost_coded] at hi + exact hi.false + rw [prod_eq_zero (mem_univ i) ((hf _ hi.le).trans z), prod_eq_zero (mem_univ i) z] + +open scoped Classical in +/-- Sign exponent of the auxiliary occupancy table. -/ +def auxSign (x : Fin n → Fin r → Bool) := + shuffle (fun i j => (x i j).toNat) (List.finRange r) (List.finRange n) + +open scoped Classical in +private def originalSign (X : Fin m → Wedge r) := + shuffle (fun i j => (slice (X i) j).val.length % 2) (List.finRange r) (List.finRange m) + +open scoped Classical in +private theorem on_codes (b : Fin m → ℕ) (L : Bits b → F) (X : Fin m → Wedge r) + (h : ∏ j, decoded b L (column X j) ≠ 0) : originalSign X = 0 := by + have e (i j) : (slice (X i) j).val.length % 2 = 0 := by + obtain ⟨v, hv⟩ := exists_code b (prod_ne_zero_iff.mp h j (mem_univ _)) + have ht := congrArg (fun x => slice x i) hv + simp only [coded, column, slice_pack] at ht + rw [← ht, bitCode_length] + omega + simp only [originalSign, e, shuffle_zero] + +open scoped Classical in +/-- A joint state on auxiliary sites. Each coefficient factors over +species, apart from the known shuffle sign. -/ +def joint (J : (Fin n → Bool) → F) (x : Fin n → Fin r → Bool) : F := + (-1) ^ auxSign x * ∏ j, J (x · j) + +open scoped Classical in +private theorem joint_sphere (J : (Fin n → Bool) → F) + (hJ : ∀ x, J x ≠ 0 → (∑ i, (x i).toNat) % 2 = 0) + (z : Fin m → F) (y : Fin n → F) (X : Fin m → Wedge r) : + (∑ x : Fin n → Fin r → Bool, joint J x * wick fieldKernel + (bundle y (fun i => occupancy (x i)) (List.finRange n) ++ bundle z X (List.finRange m))) = + (-1 : F) ^ originalSign X * ∏ j, response z y J (column X j) := by + let k (j : Fin r) (v : Fin n → Bool) := wick fieldKernel + ((occupancy v).val.map (mark (slots y)) ++ (column X j).val.map (mark (slots z))) + have term (x : Fin n → Fin r → Bool) : + joint J x * wick fieldKernel + (bundle y (fun i => occupancy (x i)) (List.finRange n) ++ bundle z X (List.finRange m)) = + (-1 : F) ^ originalSign X * ∏ j, J (x · j) * k j (x · j) := by + rw [joint, prod_mul_distrib] + by_cases h : ∏ j, J (x · j) = 0 + · simp [h] + let U i j := lowest (x i j) + let V i j := slice (X i) j + have even (j) : (bundle y (U · j) (List.finRange n)).length % 2 = 0 := by + rw [bundle_pack, List.length_map, length_pack] + simp only [U, length_lowest] + exact hJ (x · j) (prod_ne_zero_iff.mp h j (mem_univ _)) + have he := wick_two_groups y z U V (List.finRange n) (List.finRange m) + (fun i j => (x i j).toNat) (fun i j => (slice (X i) j).val.length % 2) + (fun i j => by simp [U]) (fun i j => by simp [V]) even + simp only [V, pack_slice, bundle_pack] at he + change wick fieldKernel + (bundle y (fun i => occupancy (x i)) (List.finRange n) ++ bundle z X (List.finRange m)) = + (-1 : F) ^ auxSign x * (-1) ^ originalSign X * ∏ j, k j (x · j) at he + rw [he, mul_mul_mul_comm, ← mul_assoc ((-1 : F) ^ auxSign x) ((-1 : F) ^ auxSign x), + ← mul_pow, neg_one_mul, neg_neg, one_pow, one_mul] + simp only [term, ← mul_sum] + congr 1 + change _ = ∏ j, ∑ v, J v * k j v + rw [Fintype.prod_sum] + let E : (Fin n → Fin r → Bool) ≃ (Fin r → Fin n → Bool) := ⟨fun x j i => x i j, + fun x i j => x j i, fun _ => rfl, fun _ => rfl⟩ + exact E.sum_comp (fun x => ∏ j, J (x j) * k j (x j)) + +open scoped Classical in +/-- Linear-size auxiliary positions and a product state enforce the +prescribed bit table on each species, given only total leg energies. +The same one-species state works for every replication count. -/ +theorem plant_joint (z : Fin m ↪ F) (y : Fin n ↪ F) (hz : ∀ i j, y j ≠ z i) + (b : Fin m → ℕ) (hn : (∑ i, 4 * b i) ≤ n) (L : Bits b → F) : + ∃ J : (Fin n → Bool) → F, + (∀ x, J x ≠ 0 → (∑ j, (x j).toNat) ≤ (∑ i, 2 * b i) ∧ (∑ j, (x j).toNat) % 2 = 0) ∧ + ∀ (r : ℕ) (X : Fin m → Wedge r), (∀ i, energy (X i).val = r * (8 * b i ^ 2)) → + (∑ x : Fin n → Fin r → Bool, joint J x * wick fieldKernel + (bundle y (fun i => occupancy (x i)) (List.finRange n) ++ bundle z X (List.finRange m))) = + ∏ j, decoded b L (column X j) := by + obtain ⟨J, hJ, he⟩ := plant_bits z y hz b hn L + refine ⟨J, hJ, fun r X hX => ?_⟩ + rw [joint_sphere J (fun x hx => (hJ x hx).2), budget_guard b L _ he X hX] + by_cases h : ∏ j, decoded b L (column X j) = 0 + · rw [h, mul_zero] + · rw [on_codes b L X h, pow_zero, one_mul] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant +end + +/- # Wiring coordinates on the original marks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant + +open Finset +variable {F : Type*} [Field F] {m n r : ℕ} + +open scoped Classical in +/-- The indexing data represented by `Fin r → Fin n → Bool`. -/ +abbrev bitsAt (n r : ℕ) := Fin r → Fin n → Bool + +open scoped Classical in +/-- Encode one packet for every species at a fixed total energy. -/ +def markCode (n r : ℕ) : bitsAt n r ↪ Level r (r * (8 * n ^ 2)) where + toFun x := ⟨pack (fun j => (bitCode n (x j)).val), by + rw [energy_pack] + have h (j : Fin r) := (bitCode n (x j)).property + simp [h]⟩ + inj' x y h := coded_injective (fun _ => n) (congrArg Subtype.val h) + +open scoped Classical in +private theorem eq_pack (u : Fin r → Wedge 1) (w : Wedge r) : + pack u = w ↔ ∀ i, u i = slice w i := by + constructor + · rintro rfl i + exact (slice_pack u i).symm + · intro h + rw [funext h, pack_slice] + +open scoped Classical in +private theorem code_iff (b : Fin m → ℕ) (X : ∀ i, Level r (r * (8 * b i ^ 2))) + (σ : ∀ i, bitsAt (b i) r) : + (∀ i, markCode (b i) r (σ i) = X i) ↔ + ∀ j, coded b (fun i => σ i j) = column (fun i => (X i).val) j := by + have e (i) : markCode (b i) r (σ i) = X i ↔ + ∀ j, (bitCode (b i) (σ i j)).val = slice (X i).val j := by + rw [Subtype.ext_iff] + exact eq_pack _ _ + simp only [e, coded, eq_pack, column, slice_pack] + exact forall_comm + +open scoped Classical in +/-- Sum over all coded, independently addressable packets. Any assignment +that disagrees with any original mark contributes zero. -/ +theorem joint_decoded (z : Fin m ↪ F) (y : Fin n ↪ F) (hz : ∀ i j, y j ≠ z i) + (b : Fin m → ℕ) (hn : (∑ i, 4 * b i) ≤ n) (L : Bits b → F) : + ∃ J : (Fin n → Bool) → F, + (∀ x, J x ≠ 0 → (∑ j, (x j).toNat) ≤ (∑ i, 2 * b i) ∧ (∑ j, (x j).toNat) % 2 = 0) ∧ + ∀ (r : ℕ) (X : ∀ i, Level r (r * (8 * b i ^ 2))), + (∑ x : Fin n → Fin r → Bool, joint J x * wick fieldKernel + (bundle y (fun i => occupancy (x i)) (List.finRange n) ++ + bundle z (fun i => (X i).val) (List.finRange m))) = + ∑ σ : (i : Fin m) → bitsAt (b i) r, + if ∀ i, markCode (b i) r (σ i) = X i then ∏ j, L (fun i => σ i j) else 0 := by + obtain ⟨J, hJ, h⟩ := plant_joint z y hz b hn L + refine ⟨J, hJ, fun r X => ?_⟩ + rw [h _ _ (fun i => (X i).property)] + unfold decoded + rw [Fintype.prod_sum] + let E : (∀ i, bitsAt (b i) r) ≃ (Fin r → Bits b) := + ⟨fun x j i => x i j, fun x i j => x j i, fun _ => rfl, fun _ => rfl⟩ + rw [← E.sum_comp] + refine sum_congr rfl fun σ _ => ?_ + simp only [code_iff b X σ] + change (∏ j, if coded b (fun i => σ i j) = column (fun i => (X i).val) j + then L (fun i => σ i j) else 0) = _ + split_ifs with hσ + · exact prod_congr rfl fun j _ => ite_eq_left (hσ j) + · push Not at hσ + obtain ⟨j, hj⟩ := hσ + exact prod_eq_zero (mem_univ j) (ite_eq_right hj) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Plant +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Price/Allowance.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Price/Allowance.lean new file mode 100644 index 0000000000..c5d5bafc09 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Price/Allowance.lean @@ -0,0 +1,205 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.General.Scales +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Scenario +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Status + +/-! # Per-cell credit certificates for every term of the expansion -/ + +@[expose] public section + +/- +# Constants for one controlled expansion + +Only the width of the neighbor index affects the sizes of the +colorings and local lookups. This width ranges over a fixed finite +set, independently of the number of hosts and blocks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +open Assembly Sphere Surface.Local + +/-- The quantity computed by `(4 * 5) ^ 300`. -/ +abbrev groupedDegree := (4 * 5) ^ 300 +/-- Computes the allot by the application `Layout.Sharing.allocation groupedDegree 10`. -/ +abbrev allot := Layout.Sharing.allocation groupedDegree 10 +/-- The quantity computed by `s.C * s.D * s.M`. -/ +def cap (s : Plan) := s.C * s.D * s.M + +/-- The quantity computed by `(2 * A + 2) * ((D ^ 5 + 1) * (M + 1))`. -/ +def slope (A D M : ℕ) := (2 * A + 2) * ((D ^ 5 + 1) * (M + 1)) + +theorem selector_width (A D M T Q f : ℕ) (hT : T ≤ 2 ^ f) (hQ : Q ≤ 2 ^ f) : + selectorBits A D M T Q ≤ slope A D M * (1 + f) := by + have h (X : ℕ) (hx : X ≤ 2 ^ f) : Nat.clog 2 (X + 1) ≤ f + 1 := by + apply (Nat.clog_le_iff_le_pow (by decide)).mpr + rw [pow_succ] + have := Nat.two_pow_pos f + omega + unfold selectorBits slope + rw [mul_right_comm (2 * A + 2)] + apply Nat.mul_le_mul_right + refine (Nat.add_le_add (Nat.mul_le_mul_left A (Nat.add_le_add_left (h _ hT) _)) + (Nat.mul_le_mul_right 2 (h _ hQ))).trans ?_ + ring_nf + omega + +/-- Constant multipliers for the two dictionaries. -/ +structure Reserve where + /-- Stores the deg associated with this `Reserve`. -/ + deg : ℕ + /-- The number of transitions. -/ + steps : ℕ + /-- Stores the waves associated with this `Reserve`. -/ + waves : ℕ + /-- Stores the inflation associated with this `Reserve`. -/ + inflation : ℕ + /-- Stores the slope associated with this `Reserve`. -/ + slope : ℕ + /-- Stores the digits associated with this `Reserve`. -/ + digits : ℕ + /-- Stores the child associated with this `Reserve`. -/ + child : ℕ + /-- Stores the span associated with this `Reserve`. -/ + span : ℕ + +namespace Reserve +variable (r : Reserve) + +/-- The quantity computed by `r.inflation * (1 + r.slope)`. -/ +def motion := r.inflation * (1 + r.slope) +/-- The quantity computed by `2 ^ (r.deg + 1) * (2 ^ (r.deg + 1) * (r.motion + r.digits))`. -/ +def window := 2 ^ (r.deg + 1) * (2 ^ (r.deg + 1) * (r.motion + r.digits)) +/-- The quantity computed by `r.window + r.child`. -/ +def label := r.window + r.child +/-- Uses `Print.Children.degree r.deg r.child` as the representation. -/ +def degree := Print.Children.degree r.deg r.child +/-- The value specified by `10001 + 2 ^ (r.deg + 1) + 2 ^ r.child + 2 ^ r.degree + 2 ^ (1 + 2 ^ +r.deg + 12 * (2 ^ r.deg) ^ 3 + 2 ^ r.child)`. -/ +def overhead := 10001 + 2 ^ (r.deg + 1) + 2 ^ r.child + 2 ^ r.degree + 2 ^ (1 + 2 ^ r.deg + + 12 * (2 ^ r.deg) ^ 3 + 2 ^ r.child) +/-- The scale used in the `Reserve` construction. -/ +def scale := r.overhead + 2 ^ r.span + 8 + 4 * r.waves + r.steps + 2 * r.child + r.motion + + 2 * r.label + + 2 ^ r.child * r.label + 2 * r.span + +end Reserve + +/-- The reserve of type `Reserve`, constructed using `chunks 10 s.D`. -/ +def reserve (s : Plan) (A : ℕ) (a : Sphere.Surface.Local.Design) : Reserve := + let M := chunks 10 s.D + let slot := Print.Children.Part M s.D allot s.d + let lane := Print.Compass.FinalLane (Fin a.R) (Input.panelKeys a) M s.D allot s.d + ⟨a.d, a.hops, a.waves, a.inflation, slope A s.D a.M, M * (a.R + 2 * (2 * s.D ^ allot)), + Print.indexBits slot, Print.indexBits (Print.Band lane (cap s))⟩ + +/-- Uses `⟨0, d, 0, 0, 0, 0, fun _ => ⟨fun _ _ => 0, fun _ _ => false, fun _ _ => none, fun _ _ +=> 1⟩⟩` as the representation. -/ +def skeleton (d : ℕ) : Scheme ℕ := + ⟨0, d, 0, 0, 0, 0, fun _ => ⟨fun _ _ => 0, fun _ _ => false, fun _ _ => none, fun _ _ => 1⟩⟩ + +/-- The value specified by `(reserve s A (Input.design (skeleton t) groupedDegree 10 s.D 0 0 0 +0)).scale`. -/ +def profile (s : Plan) (A t : ℕ) := + (reserve s A (Input.design (skeleton t) groupedDegree 10 s.D 0 0 0 0)).scale + +private theorem fixedShape {F : Type} (S : Scheme F) (s : Plan) (A b d p l : ℕ) : + (reserve s A (Input.design S groupedDegree 10 s.D b d p l)).scale = profile s A S.d := by + unfold profile + congr 1 + +/-- The quantity computed by `(Finset.range (s.D ^ 10 + 1)).sup (profile s A)`. -/ +def upper (s : Plan) (A : ℕ) := (Finset.range (s.D ^ 10 + 1)).sup (profile s A) + +theorem reserve_le {F : Type} (S : Scheme F) (s : Plan) (A b d p l : ℕ) (h : 2 ^ (S.d + 1) + ≤ s.D ^ 10) : + (reserve s A (Input.design S groupedDegree 10 s.D b d p l)).scale ≤ upper s A := by + rw [fixedShape] + have hh := (Nat.lt_two_pow_self (n := S.d + 1)).trans_le h + exact Finset.le_sup (Finset.mem_range.mpr (by omega)) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end + +/- # Linear bounds for the widths of the three control dictionaries -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale.Reserve +variable (r : Reserve) + +/-- The data for the fits construction, including `common`, `hops`, `child`, `parent`, +`contacts`. -/ +structure Fits (J : ℕ) : Prop where + common : 10001 + 4 * r.waves + 2 ^ r.deg ≤ J + hops : r.steps ≤ J + child : 2 * r.child + 2 ≤ J + parent : 2 ^ r.deg ≤ J + contacts : 2 ^ r.child ≤ J + degree : 2 ^ r.degree ≤ J + span : 2 ^ r.span ≤ J + motion : r.motion ≤ J + labels : r.motion + 2 * r.label ≤ J + price : r.overhead + 2 * r.label ≤ J + station : r.motion + 2 ^ r.child * r.label + 2 * r.span + 2 * r.child + 4 ≤ J + +theorem fits {J : ℕ} (h : r.scale ≤ J) : r.Fits J := by + have ht := Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.le_succ r.deg) + unfold scale overhead at h + constructor <;> (try unfold overhead) + <;> generalize 2 ^ (1 + 2 ^ r.deg + 12 * (2 ^ r.deg) ^ 3 + 2 ^ r.child) = c at * + <;> generalize 2 ^ r.degree = y, 2 ^ r.span = x, 2 ^ r.child = t, 2 ^ (r.deg + 1) = i, + 2 ^ r.deg = j at * + <;> omega + +theorem motion_bound {k e f : ℕ} (hk : k ≤ r.slope * (1 + f)) : + r.inflation * (1 + e + k) ≤ r.motion * (1 + e + f) := by + rw [motion, mul_assoc] + gcongr + rw [add_mul, one_mul] + have h := hk.trans (Nat.mul_le_mul_left _ (by omega : 1 + f ≤ 1 + e + f)) + omega + +theorem window_bound {w x f : ℕ} (hw : w ≤ r.motion * x) (hf : f ≤ x) : + 2 ^ (r.deg + 1) * (2 ^ (r.deg + 1) * (w + f * r.digits)) ≤ r.window * x := by + unfold window + rw [mul_assoc, mul_assoc, add_mul, mul_comm f] + gcongr + +variable {J i j x h e w : ℕ} + +theorem Fits.priced {r : Reserve} (hr : r.Fits J) (hx : 0 < x) + (hi : i ≤ r.motion * x) (hj : j ≤ r.window * x) : + i + 2 * (j + r.child) ≤ J * x ∧ r.overhead + j + (j + r.child) ≤ J * x := by + have h₁ := Nat.le_mul_of_pos_right r.child hx + have h₂ := Nat.le_mul_of_pos_right r.overhead hx + have h₃ := Nat.mul_le_mul_right x hr.labels + have h₄ := Nat.mul_le_mul_right x hr.price + unfold label at h₃ h₄ + rw [add_mul, mul_assoc, add_mul] at h₃ h₄ + omega + +theorem Fits.transferred {r : Reserve} (hr : r.Fits J) (hx : 0 < x) + (hi : i ≤ r.motion * x) (hj : j ≤ r.window * x) : + i + 2 ^ r.child * (j + r.child) + 2 * (h + (r.span + e)) + 1 + 2 * r.child + (w + 1) ≤ J * (x + + h + e + w) := by + have hc : j + r.child ≤ r.label * x := by + unfold label + rw [add_mul] + exact Nat.add_le_add hj (Nat.le_mul_of_pos_right _ hx) + have hm := Nat.mul_le_mul_left (2 ^ r.child) hc + have he := Nat.le_mul_of_pos_right (2 * r.span + 2 * r.child + 4) hx + have hd := Nat.mul_le_mul_right x hr.station + have hh := Nat.mul_le_mul_right (h + e + w) (show 2 ≤ J by have := hr.child; omega) + generalize 2 ^ r.child = c at * + simp only [mul_add, add_mul, mul_assoc] at hm he hd hh ⊢ + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale.Reserve +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Price/Run.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Price/Run.lean new file mode 100644 index 0000000000..293ab2ae0e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Price/Run.lean @@ -0,0 +1,754 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Payload.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Prepare.Status +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.General.Scales +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Work +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Price.Allowance + +/-! # Publishing a term of the printed expansion -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent +open Sphere Assembly Coloring Rounds + +namespace Assembly.Template.Binning.Trial +variable {F : Type} [Field F] {x y : Wire} {D : Template F} {a H T R : ℕ} {θ L : ℝ} + {b : D.Binning a H T R θ} {r : D.format.obj} {P : Rounds.Board F x y D.scheme.h} + {p : D.Presents r P} + +open scoped Classical in +theorem centered (t : b.Trial p L) : Payload.Centered t.order := by + intro i + let v := Packing.portEnd t.input.diagram i + have he := t.flag v + have hv : ¬t.input.mobile v := t.input.ext i + simp only [mobile, decide_eq_decide] at he + exact not_not.mp (mt he.mpr hv) + +end Assembly.Template.Binning.Trial + +namespace Sphere.Print.Printer +variable {F K N : Type} [Field F] [Finite K] {x y : Wire} {S : Scheme F} + {d ℓ M r t q D k n u j z' : ℕ} + +open scoped Classical in +/-- Uses `⟨U.split, U.outer, rfl⟩` as the representation. -/ +def family (U : Printer F K N S.m d S.h ℓ M r t q D k n u j z') : + Payload.Family S U.template.scheme U.childBits := ⟨U.split, U.outer, rfl⟩ + +variable {s : Rounds.Plan} {T R g e z height : ℕ} {L : ℝ} + (U : Printer F K N S.m d S.h ℓ M r t q s.D k s.d (s.b * z) j z') + {P : Input F x y S.h s.D T R g (10000 * L)} {tape : S.format.obj} + {pres : S.Presentation tape P.diagram} {dir : pres.Directed} + {data : U.rows.obj} {status : (Children.Header S.m d).obj} {f : Val x → Val y → F} + +open scoped Classical in +/-- The old selector tape stays with the new term until its exterior +payload has been transferred to the child hosts. -/ +def publish (A : P.HostChart S tape) (radius : ℕ) (hC : Input.terminalExponent g 10 = s.C) + (center : Payload.Centered (pres.toOrdered dir)) (old : B e → B S.ℓ) + (metadata : (Fmt.rows S.m S.d S.h (.addr e)).obj) + (read : ∀ v j, old ((metadata v).2 j) = (tape v).2 j) + (fits : S.Fits tape (2 ^ S.m + wd x + wd y) height) + (out : U.Release (P := A.normalized pres dir radius) (pres.toOrdered dir) data status f 10) + (i : out.I) : Payload.Pending (x := x) (y := y) (U.family (S := S)) old s T L z height where + out := { + R := R, g := g, P := A.normalized pres dir radius, Q := out.term i + ready := by rw [← hC]; exact out.bound i + live := out.populated i + r := U.advance data status (out.select.write i) + showing := out.shows i + fits := (out.retains i).fits fits } + G := P.diagram + data := tape + initial := pres + dir := dir + tape := metadata + read := read + fits := fits + center := center + retains := out.retains i + +end Sphere.Print.Printer +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- +# Combining host, block and exterior costs + +Fixed factors are absorbed by increasing the common exponent. +The base in the last term is independent of the label width. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +open Assembly +open BatchDescent.Phase.Poly (pow_sum) +variable {F : Type} [Field F] (S : Scheme F) (q : Contraction.Prices F) (h f N : ℕ) + +local notation "P" => portBase S q h +local notation "R" => rowBase S q h f +local notation "H" => hostBase S q h f +local notation "C" => fullCost S q h f N + +theorem layers : 1000 + h + q.W ≤ P ∧ P + S.ℓ + f ≤ R ∧ R + S.m + q.w ^ q.power ≤ H := by + unfold hostBase rowBase portBase + have := Nat.zero_le (2 ^ S.e) + omega + +theorem cost_mono {i j : ℕ} (he : i ≤ j) : C i ≤ C j := by + have hb := layers S q h f + have ht := Nat.zero_le (q.w ^ q.power) + unfold fullCost + gcongr <;> omega + +theorem cost_add (i j : ℕ) : C i + C j ≤ C (max i j + 1) := by + have hb := layers S q h f + have ht := Nat.zero_le (q.w ^ q.power) + have aux (x y : ℕ) (hy : 2 ≤ y) := Nat.mul_le_mul_left x (pow_sum hy i j) + have a := aux (2 ^ S.m) H (by omega) + have b := aux (2 ^ (S.m + S.h)) R (by omega) + have c := aux N P (by omega) + simp only [mul_add] at a b c + unfold fullCost + omega + +/-- The quantity computed by `J * R`. -/ +def shortRate (J : ℕ) := J * R +/-- The quantity computed by `(20 * (J + 1)) * H`. -/ +def longRate (J : ℕ) := (20 * (J + 1)) * H + +theorem rates_fit (J : ℕ) : + 1000 + 10 * S.m + 10 * shortRate S q h f J ≤ longRate S q h f J ∧ + 1 + q.w ^ q.power ≤ longRate S q h f J := by + have hb := layers S q h f + have ht := Nat.zero_le (q.w ^ q.power) + have hi := Nat.mul_le_mul_left J (show R ≤ H by omega) + unfold shortRate longRate + rw [mul_assoc 20, add_mul, one_mul] + omega + +private theorem inflate {n : ℕ} (h : 2 ≤ n) (c i : ℕ) : (c * n) ^ i ≤ n ^ ((c + 1) * i) := by + rw [pow_mul n, pow_succ n c] + exact Nat.pow_le_pow_left (Nat.mul_le_mul_right n + (Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left h c))) _ + +/-- The maximum of the quantities in `((20 * (J + 1) + 1) * i) (J * (J + 2) + 1) + 1`. -/ +def exponent (J i : ℕ) := max ((20 * (J + 1) + 1) * i) (J * (J + 2) + 1) + 1 + +theorem price_into_cost (J i : ℕ) (v : ℕ) + (hv : v ≤ 2 ^ S.m * J + (h + 1) * (2 * (2 ^ S.m + N))) : + 2 ^ S.m * (longRate S q h f J) ^ i + 2 ^ (S.m + S.h) * (shortRate S q h f J) ^ i + J * v ≤ + C (exponent J i) := by + have hb := layers S q h f + have ht := Nat.zero_le (q.w ^ q.power) + let k := (20 * (J + 1) + 1) * i + let j := J * (J + 2) + 1 + have hw : 2 ^ S.m * (longRate S q h f J) ^ i + 2 ^ (S.m + S.h) * (shortRate S q h f J) ^ i ≤ C k + := by + refine (Nat.add_le_add (Nat.mul_le_mul_left _ (inflate (by omega : 2 ≤ H) _ i)) + (Nat.mul_le_mul_left _ ((inflate (by omega : 2 + ≤ R) J i).trans ?_))).trans (Nat.le_add_right ..) + apply Nat.pow_le_pow_right (by omega) + exact Nat.mul_le_mul_right i (by omega) + have hc (n : ℕ) (hn : P ≤ n) : J * (J + 2 * (h + 1)) ≤ n ^ j := by + have hy : h + 1 ≤ n := by omega + have he : J + 2 * (h + 1) ≤ (J + 2) * n := by + rw [add_mul] + exact Nat.add_le_add (Nat.le_mul_of_pos_right _ (by omega)) (Nat.mul_le_mul_left _ hy) + have hj : J * (J + 2) * n ≤ n ^ (J * (J + 2) + 1) := by + simpa only [pow_one, mul_one] using inflate (by omega : 2 ≤ n) (J * (J + 2)) 1 + rw [mul_assoc] at hj + exact (Nat.mul_le_mul_left J he).trans hj + have he : J * v ≤ C j := calc + _ ≤ J * (2 ^ S.m * J + (h + 1) * (2 * (2 ^ S.m + N))) := Nat.mul_le_mul_left _ hv + _ = 2 ^ S.m * (J * (J + 2 * (h + 1))) + N * (J * (2 * (h + 1))) := by ring + _ ≤ 2 ^ S.m * H ^ j + N * P ^ j := Nat.add_le_add (Nat.mul_le_mul_left _ (hc H (by omega))) + (Nat.mul_le_mul_left _ ((Nat.mul_le_mul_left _ (Nat.le_add_left ..)).trans (hc P le_rfl))) + _ ≤ _ := Nat.add_le_add_right (Nat.le_add_right ..) _ + exact (Nat.add_le_add hw he).trans (cost_add S q h f N k j) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end + +/- # Applying a family of controlled emissions to a moved layer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Sphere SphereScale +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {s : Rounds.Plan} {a T b d : ℕ} {θ L : ℝ} + (P : Layer F x y) (B : P.template.Binning a s.D T (d * b) θ) + +local notation "deg" => ((4 * 5) ^ 300 : ℕ) + +section + +-- Work at an arbitrary tape width to avoid expanding the recursive bound +-- on all the preceding waves when comparing input and output formats. +open scoped Classical in +/-- A printer with the tape width supplied independently of the selected wave. -/ +abbrev Flexible (p l k r t z f : ℕ) := + let cfg := Input.design B.target deg 10 s.D b d p l + Print.Printer F (Input.panelKeys cfg) (Coloring.B B.target.k) B.target.m B.target.d B.target.h + k (chunks 10 s.D) r t cfg.R s.D + (Sphere.Layout.Sharing.allocation deg 10) s.d (s.b * z) (p ^ l) f + +variable {p l k r t z f : ℕ} + (trials : ∀ i, B.Trial (P.presents i) L) + (sc : Scales deg 10 s.D T (p ^ l) b d) + (hK : SphereScale.Ready K 10 s.D deg (p ^ l) b d) + (U : P.Flexible B p l k r t z f) + +variable (menu : (Input.design B.target ((4 * 5) ^ 300) 10 s.D b d p l).Menu F (Coloring.B + B.target.k) (Coloring.B B.target.ℓ) k) +open scoped Classical in +/-- The layer snapshot after the prescribed sequence of panel waves. -/ +abbrev finished : Snapshot.{1} F x y := + Sphere.Surface.Local.snapshot (P.panelWorld B trials sc hK) (P.panelPort B) + (P.panelPayload B trials) (Input.design B.target deg 10 s.D b d p l).waves menu + +open scoped Classical in +/-- The selected output terms and their weights for each final panel state. -/ +abbrev Emissions : Type 1 := ∀ i : (P.finished B trials sc hK menu).state, + Print.Printer.Release (K := Input.panelKeys (Input.design B.target deg 10 s.D b d p l)) + (U := U) (P := (trials i.1.1).normal (panelRadius s.D)) (trials i.1.1).order + i.2.tape (B.status (P.data i.1.1)) ((P.finished B trials sc hK menu).eval i) 10 + +variable + (releases : P.Emissions B trials sc hK U menu) + (hC : Input.terminalExponent deg 10 = s.C) + +local notation "srcPort" => P.finished B trials sc hK menu +local notation "old" => fun i => Prod.fst (menu i) +local notation "dstPort" => + Payload.pending (x := x) (y := y) (U.family (S := B.target)) (old) s T L z P.height +local notation "bitsPort" => Fmt.payload B.target.m (P.groupedVolume B) P.height + +open scoped Classical in +private def chosen : Selected (srcPort) (dstPort) U.selectors where + choice i := (releases i).I + finite i := (releases i).finite + index i := (releases i).select + next i j := U.publish (s := s) (S := B.target) (trials i.1.1).chart (panelRadius s.D) + hC (trials i.1.1).centered (old) i.2.tape + (fun v w => congrArg Prod.fst (i.2.read (v, w))) ((trials i.1.1).fits (P.fits i.1.1)) + (releases i) j + scalar i := (releases i).coeff + expands i v w := ((releases i).value v w).symm + +include releases hC in +open scoped Classical in +private theorem printFin (q : Contraction.Prices F) {u : ℕ} {labels : Set (Table F)} + (hu : 3 ≤ u) (hw : 2 * U.window.width ≤ u) (hm : B.target.m + (B.target.d + 1) * 1 ≤ q.w) + (hk : U.gate ∈ labels) : + Transforms F u labels (srcPort) (dstPort) (U.price q bitsPort) := by + let sel := P.chosen B trials sc hK U menu releases hC + refine U.transfer q (Z := bitsPort) (I := (srcPort).state) (J := (dstPort).state) + (f := (srcPort).eval) (g := (dstPort).eval) (X := (srcPort).encode) (Y + := (dstPort).encode) sel hu hw hm hk ?_ ?_ ?_ + · intro i a b + exact (releases i).reciprocal + · intro i a b + exact (releases i).valid + · intro i a b j + rfl + +end + +variable [Fintype F] {p l k r t z f : ℕ} [ExpChar F p] + (trials : ∀ i, B.Trial (P.presents i) L) + (sc : Scales deg 10 s.D T (p ^ l) b d) + (hK : SphereScale.Ready K 10 s.D deg (p ^ l) b d) + (hF : room 10 s.D deg * (2 * depth 10 s.D deg (p ^ l) (d * b) + 1) < Fintype.card F) + (U : P.Printer B p l k r t z f) + (releases : P.Releases B trials sc hK hF U) + (hC : Input.terminalExponent deg 10 = s.C) + +local notation "srcPort" => P.moved B trials sc hK hF k +local notation "old" => fun i => Prod.fst (P.movedMenu B hK hF k i) +local notation "dstPort" => + Payload.pending (x := x) (y := y) (U.family (S := B.target)) (old) s T L z P.height +local notation "bitsPort" => Fmt.payload B.target.m (P.groupedVolume B) P.height + +include releases hC in +open scoped Classical in +theorem printReleases (q : Contraction.Prices F) {u : ℕ} {labels : Set (Table F)} + (hu : 3 ≤ u) (hw : 2 * U.window.width ≤ u) (hm : B.target.m + (B.target.d + 1) * 1 ≤ q.w) + (hk : U.gate ∈ labels) : + Transforms F u labels (srcPort) (dstPort) (U.price q bitsPort) := + P.printFin B trials sc hK U (P.movedMenu B hK hF k) releases hC q hu hw hm hk + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # Printing all the states of the completed movement schedule -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Assembly Coloring Routing.Private Sphere SphereScale Surface Surface.Local + +variable {F K : Type} [Field F] [Field K] [Algebra K F] {x y : Wire} + {g ℓ D T b d p l j : ℕ} {W : ℝ} {S : Scheme F} + (P : Input F x y S.h D T (d * b) g W) + {z : S.format.obj} (A : P.HostChart S z) + (sc : Scales g ℓ D T (p ^ l) b d) (hK : Ready K ℓ D g (p ^ l) b d) + (s : P.Occupied → Shape (probes ℓ D) b d) + +local notation "world" => P.localWorld A sc hK s +local notation "Cfg" => design S g ℓ D b d p l + +open scoped Classical in +private def releaseCode (pres : S.Presentation z P.diagram) {tone : B S.m → ℕ} {mobile : S.Vtx → + Bool} + (h : P.Placed pres A.coord tone mobile) (hd : pres.Directed) + {menu : (Cfg).Menu F (B S.k) (B S.ℓ) j} (c : (world).Code (Cfg).waves menu) + {M r t k n u e : ℕ} + (U : Print.Printer F (panelKeys Cfg) (B S.k) S.m S.d S.h j M r t (Cfg).R D k n u (p ^ l) e) + (ha : d * b = M * r) (hb : d = M * t) (hm : U.menu = printMenu S menu ha hb) + (status : (Print.Children.Header S.m S.d).obj) + (loc : ∀ v, A.coord v = (A.host v.val.1, cellIndex S.h v.val.2)) + (parents : Print.Children.Shows P.adj A.host (A.graph, status)) (hn : Nonempty P.V) + (hM : M = chunks ℓ D) (hk : k = Sphere.Layout.Sharing.allocation g ℓ) + (hu : u * D ^ (terminalExponent g ℓ) ≤ T) + (hc : terminalExponent g ℓ * D * T ≤ u * U.cap) (hz : depth ℓ D g (p ^ l) (d * b) < 2 ^ e) : + U.Release pres c.tape status ((world).eval c.frame) ℓ := by + have sig := P.printSignal A sc hK s pres h hd c U ha hb hm status loc parents + have bd := P.panelBounds A sc hK s c.frame + exact sig.1.release sig.2 hn bd sc ha hb rfl rfl hM hk hu hc hz + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Sphere SphereScale + +variable {F K : Type} [Field F] [Fintype F] [Field K] [Algebra K F] {x y : Wire} + {s : Rounds.Plan} {a T b d : ℕ} {θ L : ℝ} {p l k r t z f : ℕ} [ExpChar F p] + (P : Layer F x y) (B : P.template.Binning a s.D T (d * b) θ) + +local notation "g" => ((4 * 5) ^ 300 : ℕ) + +variable (trials : ∀ i, B.Trial (P.presents i) L) + (sc : Scales g 10 s.D T (p ^ l) b d) + (hK : SphereScale.Ready K 10 s.D g (p ^ l) b d) + (hF : room 10 s.D g * (2 * depth 10 s.D g (p ^ l) (d * b) + 1) < Fintype.card F) + (U : P.Printer B p l k r t z f) + (ha : d * b = chunks 10 s.D * r) (hb : d = chunks 10 s.D * t) + (hm : U.menu = Input.printMenu B.target (P.movedMenu B hK hF k) ha hb) + (hC : Input.terminalExponent g 10 = s.C) + (hLive : ∀ i, Nonempty (P.board i).V) + (hUnits : (s.b * z) * s.D ^ s.C ≤ T) + (hCap : s.C * s.D * T ≤ (s.b * z) * U.cap) + (hDepth : depth 10 s.D g (p ^ l) (d * b) < 2 ^ f) + +include ha hb hm hC hLive hUnits hCap hDepth + +open scoped Classical in +private def releases : P.Releases B trials sc hK hF U := by + rintro ⟨⟨i, shape⟩, code⟩ + let rad := panelRadius s.D + let tr := trials i + let A := tr.atlas rad + let input := tr.normal rad + rw [← hC] at hUnits hCap + exact input.releaseCode A sc hK shape tr.order (tr.placed rad) tr.directed_order code U ha hb hm + (B.status (P.data i)) (fun _ => rfl) (tr.parents rad) (tr.nonempty rad (hLive i)) + rfl rfl hUnits hCap hDepth + +open scoped Classical in +/-- The printed diagrams carry their old exterior payload until its +transfer to the children. -/ +theorem printLayer (q : Contraction.Prices F) {u : ℕ} {labels : Set (Table F)} + (hu : 3 ≤ u) (hw : 2 * U.window.width ≤ u) (hm' : B.target.m + (B.target.d + 1) * 1 ≤ q.w) + (hk : U.gate ∈ labels) : + Transforms F u labels (P.moved B trials sc hK hF k) + (Payload.pending (U.family (S := B.target)) (fun i + => (P.movedMenu B hK hF k i).1) s T L z P.height) + (U.price q (Fmt.payload B.target.m (P.groupedVolume B) P.height)) := by + let out := P.releases B trials sc hK hF U ha hb hm hC hLive hUnits hCap hDepth + exact P.printReleases B trials sc hK hF U out hC q hu hw hm' hk + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # Movement and printing costs of a grouped concentration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Assembly Coloring SphereScale + +/-- The maximum of the quantities in `(exponent (J + 1) 218) (exponent (J + 1) 225) + 1`. -/ +def SphereScale.costExponent (J : ℕ) := max (exponent (J + 1) 218) (exponent (J + 1) 225) + 1 + +namespace Layer +variable {F : Type} [Field F] {x y : Wire} {s : Plan} {a T b d p l k r t z f J : ℕ} {θ : ℝ} + (P : Layer F x y) (B : P.template.Binning a s.D T (d * b) θ) + (q : Contraction.Prices F) (U : P.Printer B p l k r t z f) +local notation "S" => B.target +local notation "Cfg" => Input.design (S) ((4 * 5) ^ 300) 10 s.D b d p l +local notation "Z" => Fmt.payload B.target.m (P.groupedVolume B) P.height + +theorem programCost_bound (hJ : 10001 + 4 * (Cfg).waves + 2 ^ (S).d ≤ J) + (hC : (Cfg).inflation * (1 + (S).ℓ + k) ≤ J * (1 + (S).ℓ + f)) + (hU : 10000 + 1 + U.window.width + U.labelBits + 2 ^ ((S).d + 1) + 2 ^ U.childBits + + 2 ^ U.template.scheme.d + 2 ^ (1 + 2 ^ (S).d + 12 * (2 ^ (S).d) ^ 3 + 2 ^ U.childBits) + ≤ J * (1 + (S).ℓ + f)) : + (Cfg).work q (S).ℓ k (P.panelPort B) + U.price q Z ≤ + fullCost (S) q P.height f (wd x + wd y) (costExponent J) := by + let n := J + 1 + let X := longRate (S) q P.height f n + let Y := shortRate (S) q P.height f n + obtain ⟨hx, hw⟩ := rates_fit (S) q P.height f n + obtain ⟨hp, hr, _⟩ := layers (S) q P.height f + have hy : 1 + q.W + J * (1 + (S).ℓ + f) ≤ Y := by + have he := Nat.mul_le_mul_left J (show 1 + (S).ℓ + f ≤ rowBase (S) q P.height f by omega) + unfold Y shortRate n + rw [add_mul, one_mul] + omega + have hb : 8 + 4 * (Cfg).waves ≤ n ∧ 1 + 2 ^ (S).d ≤ n ∧ 100 ≤ n := by + generalize 2 ^ (S).d = v at hJ ⊢ + unfold n + omega + let w := (P.height + 1) * (2 * (2 ^ (S).m + (wd x + wd y))) + have hz : (Z).width ≤ w := by + unfold w groupedVolume + rw [← add_assoc (2 ^ (S).m)] + exact Fmt.width_payload .. + have hp' : (P.panelPort B).width ≤ 2 ^ (S).m * n + w := by + rw [panelPort, Format.width_pair, Template.Binning.Flags, Format.width_vec, + Format.width_pair, Format.width_vec, Format.width_bit, mul_one] + exact Nat.add_le_add (Nat.mul_le_mul_left _ hb.2.1) hz + have hmove := (Cfg).work_bound q (S).ℓ k (P.panelPort B) X Y hx + ((Nat.le_add_right ..).trans hy) hw (hC.trans ((Nat.le_add_left ..).trans hy)) + have hprint := U.work_bound q Z X Y hx hw (by omega) + have hh (i v c) (hv : v ≤ 2 ^ (S).m * n + w) (hc : c ≤ n) : + 2 ^ (S).m * X ^ i + 2 ^ ((S).m + (S).h) * Y ^ i + c * v ≤ + fullCost (S) q P.height f (wd x + wd y) (exponent n i) := + (Nat.add_le_add_left (Nat.mul_le_mul_right _ hc) _).trans + (price_into_cost (S) q P.height f (wd x + wd y) n i v hv) + exact (Nat.add_le_add (hmove.trans (hh 218 _ _ hp' hb.1)) + (hprint.trans (hh 225 _ _ (hz.trans (Nat.le_add_left ..)) hb.2.2))).trans + (cost_add (S) q P.height f (wd x + wd y) _ _) + +end Layer +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end + +/- # Executing a local concentration with one shared dictionary -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Sphere SphereScale +variable {F K : Type} [Field F] [Fintype F] [Field K] [Algebra K F] {x y : Wire} + {s : Rounds.Plan} {a T b d : ℕ} {θ L : ℝ} {p l k r t z f : ℕ} [ExpChar F p] + (P : Layer F x y) (B : P.template.Binning a s.D T (d * b) θ) + +local notation "g" => ((4 * 5) ^ 300 : ℕ) +local notation "Cfg" => Input.design B.target g 10 s.D b d p l +variable (trials : ∀ i, B.Trial (P.presents i) L) + (sc : Scales g 10 s.D T (p ^ l) b d) + (hK : SphereScale.Ready K 10 s.D g (p ^ l) b d) + (hF : room 10 s.D g * (2 * depth 10 s.D g (p ^ l) (d * b) + 1) < Fintype.card F) + (U : P.Printer B p l k r t z f) (q : Contraction.Prices F) +local notation "A" => U.family (S := B.target) + +open scoped Classical in +/-- The indexed operation `insert ((A).gate (P.height + 1) (fun i => (P.movedMenu B hK hF k +i).1)) (insert U.gate (P.motionCalls B sc hK hF k))`. -/ +def sphereCalls := insert ((A).gate (P.height + 1) (fun i => (P.movedMenu B hK hF k i).1)) + (insert U.gate (P.motionCalls B sc hK hF k)) + +open scoped Classical in +theorem card_sphereCalls : (P.sphereCalls B sc hK hF U).card ≤ (Cfg).waves + 3 := + (Finset.card_insert_le ..).trans (Nat.succ_le_succ + ((Finset.card_insert_le ..).trans (Nat.succ_le_succ (P.card_motionCalls B sc hK hF k)))) + +open scoped Classical in +/-- The sphere cost used in the `Layer` construction. -/ +def sphereCost := (Cfg).work q B.target.ℓ k (P.panelPort B) + + U.price q (Fmt.payload B.target.m (P.groupedVolume B) P.height) + + Payload.price A P.height q (P.motionWidth B p l k) (wd x + wd y) + +open scoped Classical in +theorem executeSphere (ha : d * b = chunks 10 s.D * r) (hb : d = chunks 10 s.D * t) + (hm : U.menu = Input.printMenu B.target (P.movedMenu B hK hF k) ha hb) + (hC : Input.terminalExponent g 10 = s.C) + (hLive : ∀ i, Nonempty (P.board i).V) + (hUnits : (s.b * z) * s.D ^ s.C ≤ T) + (hCap : s.C * s.D * T ≤ (s.b * z) * U.cap) + (hDepth : depth 10 s.D g (p ^ l) (d * b) < 2 ^ f) + (hi : initialChoices 10 s.D b d ≤ 2 ^ k) + (hk : Surface.Local.Frame.budget F (Cfg).chart (Cfg).g (Cfg).H (Cfg).M (Cfg).D (Cfg).U ≤ 2 ^ k) + (w : ℕ) (hw : (Cfg).arity B.target.ℓ k ≤ w) (hw' : 2 * U.window.width ≤ w) + (hw'' : (A).arity (P.height + 1) (P.motionWidth B p l k) ≤ w) + (hp : B.target.m + (Cfg).hops ≤ q.w) + (hp' : U.template.scheme.m + U.childBits + P.height + 2 ≤ q.w) : + Transforms F w (↑(P.sphereCalls B sc hK hF U)) (P.masked B trials (panelRadius s.D)) + (Contraction.publication U.template s T L z P.height) (P.sphereCost B U q) := by + let W : Set (Table F) := P.sphereCalls B sc hK hF U + have hu : 3 ≤ w := (Nat.le_add_right ..).trans hw + have hq : B.target.m + (B.target.d + 1) * 1 ≤ q.w := + (Nat.add_le_add_left (Nat.mul_le_mul_left _ (Nat.succ_le_succ (Nat.zero_le _))) _).trans hp + have pos : 1 ≤ B.target.m := by + change 1 ≤ P.template.scheme.m + (P.template.scheme.h - a + 1) + omega + have h₀ := P.moveLayer B trials sc hK hF q (labels := W) hi hk hp hw + (fun _ h => Finset.mem_insert_of_mem (Finset.mem_insert_of_mem h)) + have h₁ := P.printLayer B trials sc hK hF U ha hb hm hC hLive hUnits hCap hDepth q (labels := W) + hu hw' hq (Finset.mem_insert_of_mem (Finset.mem_insert_self ..)) + have h₂ := Payload.transfer (x := x) (y := y) A (fun i + => (P.movedMenu B hK hF k i).1) s T L z P.height q + (labels := W) hu hw'' (Finset.mem_insert_self ..) pos (Nat.le_add_right ..) hp' + exact (h₀.comp h₁).comp h₂ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # Common bounds for every reachable diagram in a layer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Coloring Sphere SphereScale +variable {F : Type} [Field F] {x y : Wire} {s : Rounds.Plan} {a T b d : ℕ} {θ : ℝ} + (P : Layer F x y) (B : P.template.Binning a s.D T (d * b) θ) + {p l k r t z f : ℕ} (U : P.Printer B p l k r t z f) +local notation "S" => B.target +local notation "e" => P.motionWidth B p l k +local notation "Cfg" => Input.design B.target ((4 * 5) ^ 300) 10 s.D b d p l + +open scoped Classical in +/-- The data for the limits construction, including `common`, `hops`, `child`, `parent`, +`contacts`. -/ +structure Limits (J : ℕ) : Prop where + common : 10001 + 4 * (Cfg).waves + 2 ^ (S).d ≤ J + hops : (Cfg).hops ≤ J + child : 2 * U.childBits + 2 ≤ J + parent : 2 ^ (S).d ≤ J + contacts : 2 ^ U.childBits ≤ J + degree : 2 ^ U.template.scheme.d ≤ J + span : 2 ^ U.template.scheme.e ≤ J + labels : U.template.scheme.ℓ + U.template.count + e ≤ J * (1 + (S).ℓ + f) + move : (Cfg).inflation * (1 + (S).ℓ + k) ≤ J * (1 + (S).ℓ + f) + print : 10000 + 1 + U.window.width + U.labelBits + 2 ^ ((S).d + 1) + 2 ^ U.childBits + + 2 ^ U.template.scheme.d + 2 ^ (1 + 2 ^ (S).d + 12 * (2 ^ (S).d) ^ 3 + 2 ^ U.childBits) ≤ J * (1 + + (S).ℓ + f) + ship : (U.family («S» := S)).arity (P.height + 1) e ≤ fullArity S P.height f J + +open scoped Classical in +private theorem budgeted (cfg : Sphere.Surface.Local.Design) (label sel start finish : ℕ) + (begin : start = cfg.entryWidth label sel) + (fits : cfg.inflation * (1 + label + sel) ≤ finish) : + cfg.widthAt start sel cfg.waves ≤ finish := by + rw [begin] + exact (cfg.last_fits label sel).trans ((cfg.arity_bound label sel).trans fits) + +open scoped Classical in +theorem limits {A J : ℕ} (hd : P.template.scheme.d ≤ 4) (hJ : upper s A ≤ J) + (hc : U.cap = cap s) (hk : k ≤ slope A s.D (Cfg).M * (1 + f)) : P.Limits B U J := by + let R := reserve s A Cfg + have reserveBound := (reserve_le S s A b d p l (B.nav_bound hd)).trans hJ + have h : R.Fits J := by + simpa only [R, groupedDegree] using + (reserve s A (Input.design S groupedDegree 10 s.D b d p l)).fits reserveBound + let X := 1 + (S).ℓ + f + have hX : 0 < X := by unfold X; omega + have hm : (Cfg).inflation * (1 + (S).ℓ + k) ≤ R.motion * X := R.motion_bound hk + have hw : e ≤ R.motion * X := + budgeted Cfg (S).ℓ k (Input.panelQuery S ((4 * 5) ^ 300) 10 s.D b d p l k).width + (R.motion * X) + (panelWidth_eq S _ _ _ _ _ _ _ _) hm + have hw' : U.window.width ≤ R.window * X := by + rw [U.window_width, mul_one] + have he : U.digits = f * R.digits := mul_assoc .. + rw [he] + exact R.window_bound hw (by unfold X; omega) + obtain ⟨hlabel, hprice⟩ := h.priced hX hw hw' + have hspan : U.template.scheme.e = R.span := by + change Print.indexBits (Print.Band U.lane U.cap) = _ + rw [hc] + rfl + refine ⟨h.common, h.hops, h.child, h.parent, h.contacts, h.degree, hspan.symm ▸ h.span, + ?_, hm.trans (Nat.mul_le_mul_right X h.motion), ?_, ?_⟩ + · change U.labelBits + U.labelBits + e ≤ J * X + rw [←two_mul, add_comm] + exact hlabel + · have rearrange (v w x y g h i : ℕ) : + 10000 + 1 + v + w + x + y + g + h ≤ i ↔ 10001 + x + y + g + h + v + w ≤ i := by omega + rw [rearrange] + exact hprice + · rw [Payload.Family.width] + have hs := h.transferred (h := (S).h) («e» := (S).e) (w := P.height) hX hw hw' + unfold Payload.Family.depth + rw [hspan, fullArity, show 1 + (S).ℓ + (S).e + (S).h + P.height + f = X + (S).h + (S).e + + P.height by unfold X; omega] + exact hs + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # Total cost of running the three parts of the controller -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Sphere SphereScale +variable {F K : Type} [Field F] [Fintype F] [Field K] [Algebra K F] {x y : Wire} + {s : Rounds.Plan} {a T b d : ℕ} {θ L : ℝ} {p l k r t z f : ℕ} [ExpChar F p] + (P : Layer F x y) (B : P.template.Binning a s.D T (d * b) θ) + +local notation "g" => ((4 * 5) ^ 300 : ℕ) +local notation "Cfg" => Input.design B.target g 10 s.D b d p l +variable (trials : ∀ i, B.Trial (P.presents i) L) + (sc : Scales g 10 s.D T (p ^ l) b d) + (hK : SphereScale.Ready K 10 s.D g (p ^ l) b d) + (hF : room 10 s.D g * (2 * depth 10 s.D g (p ^ l) (d * b) + 1) < Fintype.card F) + (U : P.Printer B p l k r t z f) (q : Contraction.Prices F) +local notation "A" => U.family (S := B.target) +local notation "v" => fullCost B.target q P.height f (wd x + wd y) + +open scoped Classical in +theorem executePriced (ha : d * b = chunks 10 s.D * r) (hb : d = chunks 10 s.D * t) + (hm : U.menu = Input.printMenu B.target (P.movedMenu B hK hF k) ha hb) + (hC : Input.terminalExponent g 10 = s.C) + (hLive : ∀ i, Nonempty (P.board i).V) + (hUnits : (s.b * z) * s.D ^ s.C ≤ T) + (hCap : s.C * s.D * T ≤ (s.b * z) * U.cap) + (hDepth : depth 10 s.D g (p ^ l) (d * b) < 2 ^ f) + (hi : initialChoices 10 s.D b d ≤ 2 ^ k) + (hk : Surface.Local.Frame.budget F (Cfg).chart (Cfg).g (Cfg).H (Cfg).M (Cfg).D (Cfg).U ≤ 2 ^ k) + {J J' E : ℕ} (h : P.Limits B U J) + (hp : Payload.price A P.height q (P.motionWidth B p l k) (wd x + wd y) ≤ v E) + (hsize : max (costExponent J) E + 1 ≤ J') (hJ : J ≤ J') (hw : B.target.m + P.height + J' + ≤ q.w) : + Transforms F (fullArity B.target P.height f J') (↑(P.sphereCalls B sc hK hF U)) + (P.masked B trials (panelRadius s.D)) (Contraction.publication U.template s T L z P.height) + (v J') := by + let w := fullArity B.target P.height f J' + have ht : J * (1 + B.target.ℓ + f) ≤ w := Nat.mul_le_mul hJ (by omega) + have h₀ := ((Cfg).arity_bound B.target.ℓ k).trans (h.move.trans ht) + have h₁ : 2 * U.window.width ≤ w := by + have he := h.labels.trans ht + change U.window.width + U.childBits + (U.window.width + U.childBits) + P.motionWidth B p l k + ≤ w at he + omega + have h₂ := h.ship.trans (show fullArity B.target P.height f J ≤ w from Nat.mul_le_mul_right _ hJ) + have hg : B.target.m + (Cfg).hops ≤ q.w := + (Nat.add_le_add (Nat.le_add_right ..) (h.hops.trans hJ)).trans hw + have hf : U.template.scheme.m + U.childBits + P.height + 2 ≤ q.w := by + have := h.child + change B.target.m + U.childBits + U.childBits + P.height + 2 ≤ q.w + omega + have exec := P.executeSphere B trials sc hK hF U q ha hb hm hC hLive hUnits hCap hDepth hi hk w + h₀ h₁ h₂ hg hf + have hc := P.programCost_bound B q U h.common h.move h.print + exact exec.mono ((Nat.add_le_add hc hp).trans ((cost_add ..).trans (cost_mono _ _ _ _ _ hsize))) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- # Building the common template before selecting a branch -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +open Assembly Sphere SphereScale +variable {F K : Type} [Field F] [Field K] [Fintype F] [Algebra K F] {x y : Wire} + {s : Rounds.Plan} {a T b d p l k r t z f : ℕ} [ExpChar F p] {θ : ℝ} + (P : Layer F x y) (B : P.template.Binning a s.D T (d * b) θ) + (sc : Scales ((4 * 5) ^ 300) 10 s.D T (p ^ l) b d) + (hK : SphereScale.Ready K 10 s.D ((4 * 5) ^ 300) (p ^ l) b d) + (hF : room 10 s.D ((4 * 5) ^ 300) * + (2 * depth 10 s.D ((4 * 5) ^ 300) (p ^ l) (d * b) + 1) < Fintype.card F) + +include sc in +theorem setupPrinter (ha : d * b = chunks 10 s.D * r) (hb : d = chunks 10 s.D * t) + (hd : P.template.scheme.d ≤ 4) (hz : 0 < s.b * z) : + ∃ U : P.Printer B p l k r t z f, U.cap = cap s ∧ + U.menu = Input.printMenu B.target (P.movedMenu B hK hF k) ha hb := by + have hlarge : 4 ≤ s.D := (by decide : 4 ≤ 10000000).trans sc.bound + have aux (g S : ℕ) : 10 ≤ Layout.Sharing.allocation g S + := by as_aux_lemma => exact Nat.le_add_left .. + have he : 10 ≤ allot := aux _ _ + have hn : 2 ^ ((B.target.d + 1) * 1) ≤ s.D ^ allot + 1 := by + rw [mul_one] + exact ((B.nav_bound hd).trans (Nat.pow_le_pow_right sc.Dpos he)).trans (Nat.le_succ _) + exact ⟨⟨Input.printMenu B.target (P.movedMenu B hK hF k) ha hb, rfl, hlarge, sc.chunks_le, hn, + cap s, hz⟩, rfl, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Layer +end + +/- +# Uniform controlled concentration + +One template and one finite dictionary suffice simultaneously for +all branches of the grouped layer. Their growth bounds are independent +of the number of hosts or blocks. The only use of the field size +in the address width is through its binary logarithm. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +open Assembly Sphere +local notation "g" => ((4 * 5) ^ 300 : ℕ) + +open scoped Classical in +private theorem depth_le (ℓ D n t : ℕ) : t ≤ room ℓ D n * (2 * t + 1) := by + have hr : 0 < room ℓ D n := by unfold room slots; positivity + exact (show t ≤ 2 * t + 1 by omega).trans (Nat.le_mul_of_pos_left _ hr) + +open scoped Classical in +private theorem card_capacity (n d : ℕ) : n + 3 ≤ 10001 + 4 * n + d := by omega + +open scoped Classical in +theorem controlled (K : Type) [Field K] (s : Plan) + (hC : s.C = Input.terminalExponent g 10) (p l b : ℕ) : + ∃ A J, Controlled K s p l b A J := by + obtain ⟨A, hA⟩ := selector_bound g 10 s.D (p ^ l) b + let M := upper s A + obtain ⟨E, hE⟩ := Payload.price_bound M + let J := max M (max (costExponent M) E + 1) + have hJ : M ≤ J := le_max_left .. + refine ⟨A, J, ?_⟩ + intro F _ _ _ _ T d f z sc hK hF₀ hT hF₁ hz hUnits hT' x y P a θ L B trials q hLive hd hw + obtain ⟨hr, hi, hk, _⟩ := hA sc F + let k := selectorBits A s.D (room 10 s.D g) T (Nat.card F) + have hF := hr.trans_le hF₀ + have hDepth : depth 10 s.D g (p ^ l) (d * b) < 2 ^ f := + (depth_le _ _ _ _).trans_lt (hF.trans_le hF₁) + have slopeBound : k ≤ slope A s.D (room 10 s.D g) * (1 + f) := + selector_width _ _ _ _ _ _ hT (Nat.card_eq_fintype_card.trans_le hF₁) + obtain ⟨t, hb⟩ := sc.divides + have ha : d * b = chunks 10 s.D * (t * b) := by rw [hb, mul_assoc] + obtain ⟨U, hcap, hm⟩ := P.setupPrinter B sc hK hF (k := k) (f := f) ha hb hd hz + have hc : s.C * s.D * T ≤ (s.b * z) * U.cap := by + rw [hcap, cap, mul_left_comm (s.b * z)] + exact Nat.mul_le_mul_left _ hT' + have bounds := P.limits B U hd (le_refl M) hcap slopeBound + let names := P.sphereCalls B sc hK hF U + have priced := hE F B.target U.template U.childBits (P.motionWidth B p l k) f P.height (wd x + + wd y) + (U.family (S := B.target)) q bounds.parent bounds.degree bounds.contacts bounds.span + bounds.labels + have exec := P.executePriced B trials sc hK hF U q ha hb hm hC.symm hLive hUnits hc hDepth + hi hk bounds priced (le_max_right ..) hJ hw + refine ⟨U.template, names, rfl, Nat.le_add_right B.target.m U.childBits, ?_, rfl, ?_, + bounds.span.trans hJ, ?_, ?_, exec⟩ + · exact Nat.add_le_add_left ((Nat.lt_two_pow_self.le.trans bounds.contacts).trans hJ) _ + · exact (Nat.lt_two_pow_self.le.trans bounds.degree).trans hJ + · rw [add_comm B.target.ℓ 1] + exact ((Nat.le_add_right ..).trans bounds.labels).trans (Nat.mul_le_mul_right _ hJ) + · have ht := card_capacity (Input.design B.target g 10 s.D b d p l).waves (2 ^ B.target.d) + exact ((P.card_sphereCalls B sc hK hF U).trans (ht.trans bounds.common)).trans hJ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Capacity.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Capacity.lean new file mode 100644 index 0000000000..c3c47dc67f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Capacity.lean @@ -0,0 +1,63 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows + +/-! # Uniform bounds for a printer with one physical state -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Signal +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place Sharing item) + +variable {F K N X Z J I : Type} [Field F] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T b c g w σ : ℕ} {W : ℝ} {P : Input F x y h D T (c * b) g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} {left : Order.Exterior Q.left} {right : Order.Exterior Q.right} + {U : Printer F K N m d h ℓ M r t q D k n u j z} + {a : Atlas P.Occupied P.grid.Seam m d h} {π : Palette a w q} + {β : P.Occupied ⊕ ℕ → K} {R₀ : Reference J I N P.Occupied P.grid.Seam Z X} + {G : Record F (M * r) (M * t) P.Occupied P.grid.Seam K N} + {hm : Matches R₀.world β s G} {index : ∀ v, Y.state v ↪ ℕ} {size : P.Occupied → ℕ} + {ext : P.Occupied → Option N → Bool → ℕ} {old : P.V ↪ B m} + {data : U.rows.obj} {status : (Children.Header m d).obj} + (H : U.Signal Q left right a π β R₀ G hm index size ext old data status) + +open SphereScale (Scales depth) + +include H in +open scoped Classical in +theorem capacity (bound : P.FinalBounds Q σ j) (sc : Scales g σ D T j b c) + (ha : M * r = c * b) (hb : M * t = c) (hM : M = SphereScale.chunks σ D) (hk : k + = Sharing.allocation g σ) + (hu : u * D ^ (Input.terminalExponent g σ) ≤ T) + (hc : Input.terminalExponent g σ * D * T ≤ u * U.cap) (hz : depth σ D g j (c * b) < 2 ^ z) : + ∃ (G₀ : (Key.share s Q).Geo P k) (B : U.Physical G₀ π old data status), + B.rules.left = left ∧ B.rules.right = right ∧ + ∀ p : Layout.Profile s.scene.cell s.scene.level, + Concentrated P (B.term p) (Input.terminalExponent g σ) n σ ∧ + ∀ i, Diagram.padWidth u (((Key.share s Q).backdrop.emitted p j).width i) / u ≤ U.cap := by + subst M k + let steer := H.parents.steer U.degree + let G₀ := {bound.geometry sc with steer := steer} + have hr := (bound.raw sc hb).with_steer steer + have hs := hr.budgets sc ha hb rfl le_rfl n + obtain ⟨B, hl, hr⟩ := H.physical G₀ (fun _ => rfl) rfl rfl (fun i + => (bound.shape_bound sc i).trans_lt hz) + refine ⟨G₀, B, hl, hr, fun p => ?_⟩ + have hC : 1 ≤ Input.terminalExponent g σ := by + have := (Layout.Fanout.exponent_bounds (c := Sharing.radius (Sharing.allocation g σ)) (ℓ + := σ) le_rfl).1 + exact le_trans (by omega) this + have he := G₀.concentrated U.dyadic U.large hs p j U.pos le_rfl hu + exact ⟨B.concentrated p he, Sharing.Geo.capacity U.dyadic U.large U.pos p he hC hc⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Signal +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Children/Correct.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Children/Correct.lean new file mode 100644 index 0000000000..65aebc872a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Children/Correct.lean @@ -0,0 +1,683 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Presentation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Neighborhood +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Traces +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Initial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting + +/-! # Addressing child hosts by a parent and a fixed trie slot -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +open scoped Classical in +/-- Computes the header by the application `Format.vec m (.pair .bit (.vec e .bit))`. -/ +abbrev Header (m e : ℕ) := Format.vec m (.pair .bit (.vec e .bit)) +open scoped Classical in +/-- The value specified by `(Neighborhood.Rows m e).pair (Header m e)`. -/ +abbrev Tape (m e : ℕ) := (Neighborhood.Rows m e).pair (Header m e) +open scoped Classical in +/-- The quantity computed by `Node (Sharing.Slot M D k) (Sharing.radius k * d)`. -/ +abbrev Part (M D k d : ℕ) := Node (Sharing.Slot M D k) (Sharing.radius k * d) +open scoped Classical in +/-- The quantity computed by `(e + 1) * 1 + w`. -/ +abbrev degree (e w : ℕ) := (e + 1) * 1 + w + +open scoped Classical in +/-- Reindexes `Host V M D k d` and `V × Part M D k d where toFun v` by an equivalence. -/ +def parts (V : Type) (M D k d : ℕ) : Host V M D k d ≃ V × Part M D k d where + toFun v := ((root v).1, lift Prod.snd v) + invFun j := lift (Prod.mk j.1) j.2 + left_inv v := by cases v <;> rfl + right_inv j := by rcases j with ⟨v, s|s⟩ <;> rfl + +variable {V : Type} {M D k d m e w : ℕ} + +open scoped Classical in +/-- Selects the appropriate branch of `if i = j then 0 else if h : ∃ z, Neighborhood.expand 1 g +i z = j then h.choose else 0`. -/ +def hop (g : B m → B e → B m) (i j : B m) : B ((e + 1) * 1) := + if i = j then 0 else if h : ∃ z, Neighborhood.expand 1 g i z = j then h.choose else 0 + +open scoped Classical in +@[simp] theorem hop_self (g : B m → B e → B m) (i : B m) : hop g i i = 0 := ite_eq_left rfl + +open scoped Classical in +theorem expand_hop {g : B m → B e → B m} {i j : B m} (h : Neighborhood.Reach g 1 i j) : + Neighborhood.expand 1 g i (hop g i j) = j := by + by_cases he : i = j + · subst j + rw [hop_self, Neighborhood.origin] + obtain hh := Neighborhood.mem.mpr h + rw [hop, ite_eq_right he, dite_eq_left hh] + exact hh.choose_spec + +open scoped Classical in +/-- The data for the shows construction, including `live`, `closed`, `reciprocal`, `edge`. -/ +structure Shows (adj : V → Finset V) (old : V ↪ B m) (r : (Tape m e).obj) : Prop where + live : ∀ i, (r.2 i).1 = true ↔ i ∈ Set.range old + closed : ∀ v j, r.1 (old v) j ∈ Set.range old + reciprocal : ∀ v j, r.1 v j ≠ v → ∃! i, r.1 (r.1 v j) i = v + edge : ∀ v z, v ≠ z → (z ∈ adj v ↔ ∃ j, r.1 (old v) j = old z ∧ (r.2 (old v)).2 j = true) + +variable (old : V ↪ B m) (slot : Part M D k d ↪ B w) + +open scoped Classical in +/-- Embeds `Host V M D k d` into `B (m + w)`. -/ +def host : Host V M D k d ↪ B (m + w) := + (parts V M D k d).toEmbedding.trans ((old.prodMap slot).trans (Match.rowIndex m + w).symm.toEmbedding) + +open scoped Classical in +/-- The value specified by `(Match.rowIndex _ w).symm (hop g (old (root x).1) (old (root y).1), +slot (lift Prod.snd y))`. -/ +def idx (g : B m → B e → B m) (x y : Host V M D k d) : B (degree e w) := + (Match.rowIndex _ w).symm (hop g (old (root x).1) (old (root y).1), slot (lift Prod.snd y)) + +open scoped Classical in +@[simp] theorem host_split (x : Host V M D k d) : + Match.rowIndex m w (host old slot x) = (old (root x).1, slot (lift Prod.snd x)) := + (Match.rowIndex _ _).apply_symm_apply _ + +open scoped Classical in +@[simp] theorem idx_split (g : B m → B e → B m) (x y : Host V M D k d) : + Match.rowIndex ((e + 1) * 1) w (idx old slot g x y) = + (hop g (old (root x).1) (old (root y).1), slot (lift Prod.snd y)) := + (Match.rowIndex _ _).apply_symm_apply _ + +variable {old} {adj : V → Finset V} {r : (Tape m e).obj} (p : Shows adj old r) + +include p in +open scoped Classical in +theorem Shows.reach {v z : V} (he : z ∈ insert v (adj v)) : Neighborhood.Reach r.1 1 (old v) (old + z) := by + rcases Finset.mem_insert.mp he with rfl | he + · exact Neighborhood.Reach.refl .. + by_cases h : v = z + · subst z; exact Neighborhood.Reach.refl .. + obtain ⟨j, hj, _⟩ := (p.edge _ _ h).mp he + exact ⟨_, Or.inr ⟨j, hj⟩, rfl⟩ + +open scoped Classical in +/-- Builds `Sharing.Steering adj (D ^ k) where rank v z` with the specified `rank`, `inject`. -/ +def Shows.steer (hb : 2 ^ ((e + 1) * 1) ≤ D ^ k + 1) : Sharing.Steering adj (D ^ k) where + rank v z := (hop r.1 (old v) (old z)).castLE hb + inject v x hx y hy eq := by + have hh : hop r.1 (old v) (old x) = hop r.1 (old v) (old y) := Fin.castLE_injective hb eq + exact old.injective ((expand_hop (p.reach hx)).symm.trans (hh ▸ expand_hop (p.reach hy))) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- # Reading one-hop contacts and their return columns from short masks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +variable {V : Type} {M D k d m e w : ℕ} + +open scoped Classical in +/-- The quantity computed by `(e + 1) * 1`. -/ +abbrev hops (e : ℕ) := (e + 1) * 1 +open scoped Classical in +/-- Computes the comparisons by the application `Format.vec a (.vec b (.vec a .bit))`. -/ +abbrev comparisons (a b : ℕ) := Format.vec a (.vec b (.vec a .bit)) +open scoped Classical in +/-- Computes the info by the application `Format.pair (.pair .bit (.vec e .bit)) (.pair +(comparisons (hops e) e) (comparisons (hops e) (hops e)))`. -/ +abbrev Info (e : ℕ) := Format.pair (.pair .bit (.vec e .bit)) + (.pair (comparisons (hops e) e) (comparisons (hops e) (hops e))) +open scoped Classical in +/-- The value specified by `(Neighborhood.Rows m (hops e)).pair (.vec m (Info e))`. -/ +abbrev Query (m e : ℕ) := (Neighborhood.Rows m (hops e)).pair (.vec m (Info e)) + +open scoped Classical in +/-- The prepare of type `(Query m e).obj`, constructed using `Neighborhood.expand 1 r.1`. -/ +def prepare (r : (Tape m e).obj) : (Query m e).obj := + let g := Neighborhood.expand 1 r.1 + (g, fun v => (r.2 v, Neighborhood.maskRows g r.1 v, Neighborhood.maskRows g g v)) + +open scoped Classical in +/-- Requires `i = 0 ∨ (x.2.2 0 0 i = false ∧ ∃ j, x.2.1 0 j i = true ∧ x.1.2 j = true)`. -/ +def contact (x : (Info e).obj) (i : B (hops e)) : Prop := + i = 0 ∨ (x.2.2 0 0 i = false ∧ ∃ j, x.2.1 0 j i = true ∧ x.1.2 j = true) + +open scoped Classical in +/-- Selects the appropriate branch of `if x.2.2 i 0 0 then 0 else if h : ∃ j, x.2.2 i j 0 = true +then h.choose else 0`. -/ +def back (x : (Info e).obj) (i : B (hops e)) : B (hops e) := + if x.2.2 i 0 0 then 0 else if h : ∃ j, x.2.2 i j 0 = true then h.choose else 0 + +variable {adj : V → Finset V} {old : V ↪ B m} {r : (Tape m e).obj} (p : Shows adj old r) + {v z : V} {i : B (hops e)} + +include p in +open scoped Classical in +theorem Shows.closed_expand (v : V) (i : B (hops e)) : + Neighborhood.expand 1 r.1 (old v) i ∈ Set.range old := by + obtain ⟨y, he, hy⟩ := (Neighborhood.mem + (g := r.1) (r := 1) (x := old v)).mp ⟨i, rfl⟩ + change y = Neighborhood.expand 1 r.1 (old v) i at hy + rw [← hy] + rcases he with rfl|⟨j, rfl⟩ + · exact ⟨v, rfl⟩ + · exact p.closed v j + +include p in +open scoped Classical in +theorem Shows.contact_eq (he : Neighborhood.expand 1 r.1 (old v) i = old z) : + contact ((prepare r).2 (old v)) i ↔ + z ∈ insert v (adj v) ∧ i = hop r.1 (old v) (old z) := by + simp only [contact, prepare, Neighborhood.maskRows, Neighborhood.origin, he, decide_eq_true_eq, + decide_eq_false_iff_not, old.injective.eq_iff] + by_cases h : v = z + · subst z + simp + have hi : i ≠ 0 := by + rintro rfl + exact h (old.injective (Neighborhood.origin.symm.trans he)) + have hk : i = hop r.1 (old v) (old z) := + Neighborhood.unique he (expand_hop (Neighborhood.mem.mp ⟨i, he⟩)) + (fun e => h (old.injective e.symm)) + rw [← p.edge _ _ h, Finset.mem_insert] + exact ⟨fun he => ⟨.inr (he.resolve_left hi).2, hk⟩, + fun he => .inr ⟨h, he.1.resolve_left (Ne.symm h)⟩⟩ + +open scoped Classical in +theorem back_eq (v : B m) (i : B (hops e)) : + back ((prepare r).2 v) i = hop r.1 (Neighborhood.expand 1 r.1 v i) v := by + simp only [back, prepare, Neighborhood.maskRows, Neighborhood.origin, decide_eq_true_eq, hop] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- # Testing a trie edge from two slots and a pair of short hop codes -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +variable {V : Type} {M D k d m e w : ℕ} + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +def fixed : Part M D k d → Prop := Sum.elim Sharing.frozenSlot (fun _ => False) + +variable (hD : D = 2 ^ d) (hd : 4 ≤ D) (hc : M ≤ D ^ k) (hb : 2 ^ (hops e) ≤ D ^ k + 1) + +open scoped Classical in +/-- The link of type `Prop` for the given inputs. -/ +def link (f : (Info e).obj) (j : B (hops e)) (x y : Part M D k d) : Prop := + contact f j ∧ traceAdj (j = 0 ∧ root x = root y) + (Sharing.frozenSlot (root x)) (Sharing.frozenSlot (root y)) + (Sharing.Geo.steeringCode hD hd hc (j.castLE hb, root y)) + (Sharing.Geo.steeringCode hD hd hc ((back f j).castLE hb, root x)) + (lift (fun _ => ()) x) (lift (fun _ => ()) y) + +open scoped Classical in +theorem root_part (x : Host V M D k d) : root (lift Prod.snd x) = (root x).2 := by + cases x <;> rfl + +open scoped Classical in +theorem shape_part (x : Host V M D k d) : + lift (fun _ => ()) (lift Prod.snd x) = lift (fun _ => ()) x := by cases x <;> rfl + +variable {F T X E Z K : Type} {r t : ℕ} + {C : Z → Surface.Cell F (M * r) (M * t) T E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h W₀ R g : ℕ} {W : ℝ} {P : Rounds.Input F a b h D W₀ R g W} + {old : P.V ↪ B m} {u : (Tape m e).obj} (G : S.Geo P k) + (p : Shows P.adj old u) (hs : G.steer = p.steer hb) +local notation "T₀" => (G.tree hD hd) +local notation "H" => Host P.V M D k d + +open scoped Classical in +theorem fixed_iff (x : H) : fixed (lift Prod.snd x) ↔ (T₀).fixed x := by + cases x <;> rfl + +open scoped Classical in +theorem adj_root {x y : H} (he : y ∈ (T₀).adj x) : (root y).1 ∈ insert (root x).1 (P.adj (root + x).1) := + (Finset.mem_product.mp (adj_near T₀ (fun _ => Finset.mem_product.mpr + ⟨Finset.mem_insert_self .., Finset.mem_univ _⟩) he)).1 + +include hs in +open scoped Classical in +theorem link_iff (x y : H) (i : B (hops e)) + (he : Neighborhood.expand 1 u.1 (old (root x).1) i = old (root y).1) : + link hD hd hc hb ((prepare u).2 (old (root x).1)) i (lift Prod.snd x) (lift Prod.snd y) ↔ + y ∈ (T₀).adj x ∧ i = hop u.1 (old (root x).1) (old (root y).1) := by + unfold link + rw [p.contact_eq he, back_eq, he, root_part, root_part, shape_part, shape_part] + have near (h : (root y).1 ∈ insert (root x).1 (P.adj (root x).1)) + (hi : i = hop u.1 (old (root x).1) (old (root y).1)) : + y ∈ (T₀).adj x ↔ traceAdj (i = 0 ∧ (root x).2 = (root y).2) + (Sharing.frozenSlot (root x).2) (Sharing.frozenSlot (root y).2) + (Sharing.Geo.steeringCode hD hd hc (i.castLE hb, (root y).2)) + (Sharing.Geo.steeringCode hD hd hc ((hop u.1 (old (root y).1) (old (root x).1)).castLE hb, + (root x).2)) + (lift (fun _ => ()) x) (lift (fun _ => ()) y) := by + have hsame : (root x = root y) ↔ i = 0 ∧ (root x).2 = (root y).2 := by + constructor + · intro eq + rw [hi, eq, hop_self] + exact ⟨rfl, rfl⟩ + · rintro ⟨rfl, hz⟩ + exact Prod.ext (old.injective (Neighborhood.origin.symm.trans he)) hz + have code (a b : Bench P.V M D k) : + (T₀).code a b = Sharing.Geo.steeringCode hD hd hc + ((hop u.1 (old a.1) (old b.1)).castLE hb, b.2) := by + change Sharing.Geo.steeringCode hD hd hc (G.steer.rank a.1 b.1, b.2) = _ + rw [hs]; rfl + rw [adj_iff T₀ (Finset.mem_product.mpr ⟨h, Finset.mem_univ _⟩), hsame, code, code, hi] + constructor + · rintro ⟨⟨h, hi⟩, eq⟩ + exact ⟨(near h hi).mpr eq, hi⟩ + · rintro ⟨h, hi⟩ + have hr := adj_root hD hd G h + exact ⟨⟨hr, hi⟩, (near hr hi).mp h⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- # Graph headers of the expanded trie -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +variable {V : Type} {M D k d m e w : ℕ} +open Assembly.History.Reset +variable (slot : Part M D k d ↪ B w) + (hD : D = 2 ^ d) (hd : 4 ≤ D) (hc : M ≤ D ^ k) (hb : 2 ^ (hops e) ≤ D ^ k + 1) + +open scoped Classical in +/-- Requires `f.1.1 = true ∧ s ∈ Set.range slot`. -/ +def valid (f : (Info e).obj) (s : B w) : Prop := f.1.1 = true ∧ s ∈ Set.range slot + +open scoped Classical in +/-- The condition `∃ z, slot z = s ∧ fixed z` on the specified data. -/ +def frozen (s : B w) : Prop := ∃ z, slot z = s ∧ fixed z + +open scoped Classical in +@[simp] theorem frozen_slot (x : Part M D k d) : frozen slot (slot x) ↔ fixed x := by + simp [frozen, slot.injective.eq_iff] + +open scoped Classical in +/-- Requires `let v := Match.rowIndex (hops e) w j f.1.1 = true ∧ ∃ x y, slot x = s ∧ slot y = +v.2 ∧ link hD hd hc hb f v.1 x y`. -/ +def enabled (f : (Info e).obj) (s : B w) (j : B (degree e w)) : Prop := + let v := Match.rowIndex (hops e) w j + f.1.1 = true ∧ ∃ x y, slot x = s ∧ slot y = v.2 ∧ link hD hd hc hb f v.1 x y + +open scoped Classical in +/-- The record of type `(Child.Suffix (hops e) w (degree e w)).obj`, constructed using +`Match.rowIndex (hops e) w j`. -/ +def record (f : (Info e).obj) (s : B w) : (Child.Suffix (hops e) w (degree e w)).obj := + ((decide (valid slot f s), decide (frozen slot s)), fun j => + let v := Match.rowIndex (hops e) w j + if enabled slot hD hd hc hb f s j then + ((true, decide (¬frozen slot s ∧ ¬frozen slot v.2)), BatchDescent.Trail.hop _ (some v.1), v.2) + else ((false, false), BatchDescent.Trail.hop _ none, s)) + +open scoped Classical in +/-- The indexed operation `((prepare u).1, fun i => record slot hD hd hc hb ((prepare u).2 +(Match.rowIndex m w i).1) (Match.rowIndex m w i).2)`. -/ +def entries (u : (Tape m e).obj) : (Child.Input m (hops e) w (degree e w)).obj := + ((prepare u).1, fun i => record slot hD hd hc hb + ((prepare u).2 (Match.rowIndex m w i).1) (Match.rowIndex m w i).2) + +open scoped Classical in +/-- Computes the graph by the application `Child.build _ _ _ _ (entries slot hD hd hc hb u)`. -/ +def graph (u : (Tape m e).obj) : (Child.Graph (m + w) (degree e w)).obj := + Child.build _ _ _ _ (entries slot hD hd hc hb u) + +variable {old : V ↪ B m} {u : (Tape m e).obj} {adj : V → Finset V} (p : Shows adj old u) +local notation "net" => graph slot hD hd hc hb u +local notation "entry" => entries slot hD hd hc hb u +local notation "split" => Match.rowIndex m w +local notation "addr" => host old slot + +include p in +open scoped Classical in +theorem valid_iff (x : B (m + w)) : + valid slot ((prepare u).2 (split x).1) (split x).2 ↔ x ∈ Set.range addr := by + change (u.2 _).1 = true ∧ _ ↔ _ + rw [p.live] + constructor + · rintro ⟨⟨v, hv⟩, ⟨s, hs⟩⟩ + refine ⟨(parts V M D k d).symm (v, s), (split).injective ?_⟩ + have eq := (parts V M D k d).apply_symm_apply (v, s) + rw [host_split] + exact (congrArg (Prod.map old slot) eq).trans (Prod.ext hv hs) + · rintro ⟨i, rfl⟩ + rw [host_split] + exact ⟨⟨_, rfl⟩, ⟨_, rfl⟩⟩ + +include p in +open scoped Classical in +theorem live (x : B (m + w)) : ((net).2 x).1.1 = true ↔ x ∈ Set.range addr := by + change decide (valid slot ((prepare u).2 (split x).1) (split x).2) = true ↔ _ + rw [decide_eq_true_eq, valid_iff slot p] + +open scoped Classical in +theorem fixed_slot (x : Host V M D k d) : + ((net).2 (addr x)).1.2 = true ↔ fixed (lift Prod.snd x) := by + change decide (frozen slot (split (addr x)).2) = true ↔ _ + rw [decide_eq_true_eq, host_split, frozen_slot] + +open scoped Classical in +/-- Computes the used by the application `enabled slot hD hd hc hb ((prepare u).2 (split x).1) +(split x).2 j`. -/ +def used (x : B (m + w)) (j : B (degree e w)) := + enabled slot hD hd hc hb ((prepare u).2 (split x).1) (split x).2 j + +open scoped Classical in +theorem spare (x : B (m + w)) (j : B (degree e w)) (hj : ¬used slot hD hd hc hb (u:=u) x j) : + (net).1 x j = x ∧ ((net).2 x).2 j = (false, false) := by + have he : ((entry).2 x).2 j = ((false, false), BatchDescent.Trail.hop _ none, (split x).2) := + ite_eq_right hj + exact ⟨Child.build_stay entry x j (congrArg Prod.snd he), congrArg Prod.fst he⟩ + +include p in +open scoped Classical in +theorem idle (x : B (m + w)) (hx : x ∉ Set.range addr) (j : B (degree e w)) : + (net).1 x j = x := by + refine (spare slot hD hd hc hb x j ?_).1 + rintro ⟨hv, s, t, he, _⟩ + exact hx ((valid_iff slot p x).mp ⟨hv, s, he⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- # The enabled columns are exactly the incident trie edges -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +variable {V : Type} {M D k d m e w : ℕ} +open Assembly.History.Reset +variable (slot : Part M D k d ↪ B w) + (hD : D = 2 ^ d) (hd : 4 ≤ D) (hc : M ≤ D ^ k) (hb : 2 ^ (hops e) ≤ D ^ k + 1) +variable {F T X E Z K : Type} {r t : ℕ} + {C : Z → Surface.Cell F (M * r) (M * t) T E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h W₀ R g : ℕ} {W : ℝ} {P : Rounds.Input F a b h D W₀ R g W} + {old : P.V ↪ B m} {u : (Tape m e).obj} (G : S.Geo P k) + (p : Shows P.adj old u) (hs : G.steer = p.steer hb) +local notation "T₀" => (G.tree hD hd) +local notation "H" => Host P.V M D k d +local notation "net" => graph slot hD hd hc hb u +local notation "entry" => entries slot hD hd hc hb u +local notation "split" => Match.rowIndex m w +local notation "col" => Match.rowIndex (hops e) w +local notation "addr" => host old slot +local notation "ix" => idx old slot (Prod.fst u) +local notation "test" => used slot hD hd hc hb (u:=u) + +include hs in +open scoped Classical in +theorem columns (x : H) (j : B (degree e w)) : + test (addr x) j ↔ ∃ y ∈ (T₀).adj x, ix x y = j := by + unfold used enabled + rw [host_split] + have live := (p.live _).mpr ⟨(root x).1, rfl⟩ + constructor + · rintro ⟨_, v, z, hv, hz, hl⟩ + have eq : v = lift Prod.snd x := slot.injective hv + subst v + obtain ⟨i, hi⟩ := p.closed_expand (root x).1 (col j).1 + let y := (parts P.V M D k d).symm (i, z) + have hr : ((root y).1, lift Prod.snd y) = (i, z) := (parts P.V M D k d).apply_symm_apply _ + obtain ⟨h₁, h₂⟩ := Prod.mk.inj hr + have he : Neighborhood.expand 1 u.1 (old (root x).1) (col j).1 = old (root y).1 + := by rw [h₁, hi] + obtain ⟨hadj, hh⟩ := (link_iff hD hd hc hb G p hs x y (col j).1 he).mp (h₂.symm ▸ hl) + refine ⟨y, hadj, (col).injective ?_⟩ + rw [idx_split, h₂, hz, ← hh] + · rintro ⟨y, hy, rfl⟩ + rw [idx_split] + have he := expand_hop (p.reach (adj_root hD hd G hy)) + exact ⟨live, _, _, rfl, rfl, (link_iff hD hd hc hb G p hs x y _ he).mpr ⟨hy, rfl⟩⟩ + +include hs in +open scoped Classical in +theorem used_column (x y : H) (hy : y ∈ (T₀).adj x) : + (net).1 (addr x) (ix x y) = addr y ∧ + ((net).2 (addr x)).2 (ix x y) = (true, decide (y ∈ (T₀).core x)) := by + have used := (columns slot hD hd hc hb G p hs x _).mpr ⟨y, hy, rfl⟩ + have he : ((entry).2 (addr x)).2 (ix x y) = + ((true, decide (¬frozen slot (split (addr x)).2 ∧ ¬frozen slot (col (ix x y)).2)), + BatchDescent.Trail.hop _ (some (col (ix x y)).1), (col (ix x y)).2) := ite_eq_left used + rw [host_split, idx_split] at he + constructor + · have hx := Child.build_hop entry (addr x) (ix x y) _ _ (congrArg Prod.snd he) + dsimp only [Option.elim] at hx + rw [host_split] at hx + refine hx.trans ?_ + apply (split).symm_apply_eq.mpr + rw [host_split] + exact Prod.ext (expand_hop (p.reach (adj_root hD hd G hy))) rfl + · refine (congrArg Prod.fst he).trans ?_ + simp only [frozen_slot, fixed_iff hD hd G, Trie.core, Finset.mem_filter, hy, true_and] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- # Replicating each block label with its static child address -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +variable {V : Type} {M D k d m e w : ℕ} +open Assembly.History.Reset +variable (slot : Part M D k d ↪ B w) + (hD : D = 2 ^ d) (hd : 4 ≤ D) (hc : M ≤ D ^ k) (hb : 2 ^ (hops e) ≤ D ^ k + 1) + +open scoped Classical in +/-- Computes the input by the application `Format.pair (Fmt.rows m e h (.addr l)) (Header m e)`. -/ +abbrev input (m e h l : ℕ) := Format.pair (Fmt.rows m e h (.addr l)) (Header m e) +open scoped Classical in +/-- The quantity computed by `Format.vec (m + w) (.vec h (.addr (l + w)))`. -/ +abbrev labels (m h l w : ℕ) := Format.vec (m + w) (.vec h (.addr (l + w))) + +open scoped Classical in +/-- The output used in the `Children` construction. -/ +abbrev output (m e h l w : ℕ) := Format.pair (Fmt.rows (m + w) (degree e w) h (.addr (l + w))) + (.vec (m + w) (.pair (.pair .bit .bit) (.pair (Group.Flags (degree e w)) (.vec h (.addr (l + + w)))))) + +variable {h l : ℕ} + +open scoped Classical in +/-- The indexed operation `(fun i => (r.1 i).1, r.2)`. -/ +def tape (r : (input m e h l).obj) : (Tape m e).obj := (fun i => (r.1 i).1, r.2) + +open scoped Classical in +/-- Evaluates `let v := Match.rowIndex m w i (Match.rowIndex l w).symm ((r.1 v.1).2 j, v.2)` at +the input `i j`. -/ +def label (w : ℕ) (r : (input m e h l).obj) : (labels m h l w).obj := + fun i j => let v := Match.rowIndex m w i + (Match.rowIndex l w).symm ((r.1 v.1).2 j, v.2) + +open scoped Classical in +/-- The indexed operation `(fun i => (x.1.1 i, x.2 i), fun i => ((x.1.2 i).1, (x.1.2 i).2, x.2 +i))`. -/ +def join (x : (Format.pair (Child.Graph (m + w) (degree e w)) (labels m h l w)).obj) : + (output m e h l w).obj := + (fun i => (x.1.1 i, x.2 i), fun i => ((x.1.2 i).1, (x.1.2 i).2, x.2 i)) + +open scoped Classical in +/-- The value specified by `join (graph slot hD hd hc hb (tape r), label w r)`. -/ +def write (r : (input m e h l).obj) : (output m e h l w).obj := + join (graph slot hD hd hc hb (tape r), label w r) + +open scoped Classical in +theorem label_at (r : (input m e h l).obj) (i : B (m + w)) (j : B h) : + Match.rowIndex l w (label w r i j) = + ((r.1 (Match.rowIndex m w i).1).2 j, (Match.rowIndex m w i).2) := + (Match.rowIndex l w).apply_symm_apply _ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- # Correctness of the printed host graph -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +variable {V : Type} {M D k d m e w : ℕ} +open Assembly.History.Reset +variable (slot : Part M D k d ↪ B w) + (hD : D = 2 ^ d) (hd : 4 ≤ D) (hc : M ≤ D ^ k) (hb : 2 ^ (hops e) ≤ D ^ k + 1) +variable {F T X E Z K : Type} {r t : ℕ} + {C : Z → Surface.Cell F (M * r) (M * t) T E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h W₀ R g : ℕ} {W : ℝ} {P : Rounds.Input F a b h D W₀ R g W} + {old : P.V ↪ B m} {u : (Tape m e).obj} (G : S.Geo P k) + (p : Shows P.adj old u) (hs : G.steer = p.steer hb) +local notation "T₀" => (G.tree hD hd) +local notation "H" => Host P.V M D k d +local notation "net" => graph slot hD hd hc hb u +local notation "addr" => host old slot +local notation "ix" => idx old slot (Prod.fst u) +local notation "test" => used slot hD hd hc hb (u:=u) + +include hs + +open scoped Classical in +private theorem classify (x : H) (j : B (degree e w)) : + (∃ y ∈ (T₀).adj x, ix x y = j) ∨ + ((net).1 (addr x) j = addr x ∧ ((net).2 (addr x)).2 j = (false, false)) := by + by_cases h : test (addr x) j + · exact .inl ((columns slot hD hd hc hb G p hs _ _).mp h) + · exact .inr (spare slot hD hd hc hb _ _ h) + +local notation "data" => used_column slot hD hd hc hb G p hs +local notation "inspect" => classify slot hD hd hc hb G p hs + +open scoped Classical in +theorem closed (v : H) (j : B (degree e w)) : (net).1 (addr v) j ∈ Set.range addr := by + rcases inspect v j with ⟨z, hz, rfl⟩|⟨he, _⟩ + · exact ⟨z, (data _ _ hz).1.symm⟩ + · exact ⟨v, he.symm⟩ + +open scoped Classical in +theorem reciprocal (i : B (m + w)) (j : B (degree e w)) (hn : (net).1 i j ≠ i) : + ∃! t, (net).1 ((net).1 i j) t = i := by + by_cases hi : i ∈ Set.range addr + swap + · exact (hn (idle slot hD hd hc hb p i hi j)).elim + obtain ⟨v, rfl⟩ := hi + rcases inspect v j with ⟨z, hz, rfl⟩|⟨he, _⟩ + swap + · exact (hn he).elim + rw [(data _ _ hz).1] at hn ⊢ + refine ⟨ix z v, (data _ _ ((T₀).adj_symm hz)).1, fun j he => ?_⟩ + rcases inspect z j with ⟨t, ht, rfl⟩|⟨hh, _⟩ + · exact congrArg (ix z) ((addr).injective ((data _ _ ht).1.symm.trans he)) + · exact (hn (hh.symm.trans he)).elim + +open scoped Classical in +theorem edge (v z : H) : + z ∈ (T₀).adj v ↔ ∃ j, (net).1 (addr v) j = addr z ∧ (((net).2 (addr v)).2 j).1 = true := by + constructor + · intro h + exact ⟨ix v z, (data _ _ h).1, congrArg Prod.fst (data _ _ h).2⟩ + rintro ⟨j, he, h⟩ + rcases inspect v j with ⟨t, ht, rfl⟩|⟨_, hh⟩ + · exact (addr).injective ((data _ _ ht).1.symm.trans he) ▸ ht + · rw [hh] at h; cases h + +open scoped Classical in +theorem core (v z : H) : + z ∈ (T₀).core v ↔ ∃ j, (net).1 (addr v) j = addr z ∧ (((net).2 (addr v)).2 j).2 = true := by + constructor + · intro h + have hd := data _ _ (Finset.mem_filter.mp h).1 + exact ⟨ix v z, hd.1, by rw [hd.2]; exact decide_eq_true h⟩ + rintro ⟨j, he, h⟩ + rcases inspect v j with ⟨t, ht, rfl⟩|⟨_, hh⟩ + · have e := (addr).injective ((data _ _ ht).1.symm.trans he) + subst z + rw [(data _ _ ht).2] at h + exact of_decide_eq_true h + · rw [hh] at h; cases h + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- # Short bundle names from a colored atlas and local key aliases -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place item) + +variable {F T V E X K : Type} [Fintype V] {r t M n B d h R q g : ℕ} + {Y : Alphabet V} {a b : Wire} (s : Stage F (M * r) (M * t) T V E X) (A : Key.Source Y a b s) + (c : Atlas V E B d h) (π : Palette c R q) (β : V ⊕ ℕ → K) + +open scoped Classical in +/-- The value specified by `(decide ((item s.scene.cell i).label.role = .collector), Fin.castLE +(hc i.1) i.2)`. -/ +def coordinate (hc : ∀ v, (s.scene.cell v).stations.length ≤ n) (i : Place s.scene.cell) : + Bool × Fin n := (decide ((item s.scene.cell i).label.role = .collector), + Fin.castLE (hc i.1) i.2) + +open scoped Classical in +/-- Builds `Marking (Key.share s A) (Fin q) (Bool × Fin n) K where mark` with the specified +`mark`, `number`, `key`, `atCell`. -/ +def marking (hc : ∀ v, (s.scene.cell v).stations.length ≤ n) + (hs : A.src = c.src) (ht : A.dst = c.dst) (hR : 2 ≤ R) (hl : s.Layout c.src c.dst g) + (hd : Distinct (c.near 1) s β) : Marking (Key.share s A) (Fin q) (Bool × Fin n) K where + mark := π.mark + number := coordinate s hc + key := β ∘ Key.name s.hidden + atCell i j h he := by + obtain ⟨v, i⟩ := i + obtain ⟨w, j⟩ := j + change v = w at h + subst w + have eq : i = j := Fin.ext (congrArg (fun p : Bool × Fin n => p.2.val) he) + rw [eq] + atKey v j hj k hk he := (Key.name s.hidden).injective <| + hd v v (.refl ..) _ (Key.mem_filter.mp hj) _ (Key.mem_filter.mp hk) he + across e i j hi hj he := by + apply (Key.name s.hidden).injective + have h' : c.near 1 (A.src e) (A.dst e) := by rw [hs, ht]; exact c.near_edge e + exact hd _ _ h' _ (Key.mem_filter.mp hi) _ (Key.mem_filter.mp hj) he + marks e he := by + apply π.distinguish _ he + change c.near R (A.src e) (A.dst e) + rw [hs, ht] + exact (c.near_edge e).mono (by omega) + seams v e f he hf eq := by + have pair (j : E) (hj : uses (Key.share s A) v j) : + c.near 1 v (A.src j) ∧ c.near 1 v (A.dst j) := by + change A.src j = v ∨ A.dst j = v at hj + rw [hs, ht] at hj ⊢ + rcases hj with rfl|rfl + · exact ⟨.refl .., c.near_edge _⟩ + · exact ⟨(c.near_edge _).symm, .refl ..⟩ + have h₁ := π.injective_at hR (pair e he).1 (pair f hf).1 (Prod.mk.inj eq).1 + have h₂ := π.injective_at hR (pair e he).2 (pair f hf).2 (Prod.mk.inj eq).2 + rw [hs] at h₁ + rw [ht] at h₂ + exact c.links (Prod.ext h₁ h₂) + ports v e he := by + change A.src e = v ∨ A.dst e = v at he + rw [hs, ht] at he + obtain ⟨⟨j, z⟩, hj, rfl⟩ := List.mem_map.mp ((hl.incident v e).mpr he) + exact ⟨z, hj⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Children/Traces.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Children/Traces.lean new file mode 100644 index 0000000000..f5a2e2f33d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Children/Traces.lean @@ -0,0 +1,1105 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Pins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.History +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Host +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave + +/-! Recover adjacency from the two node addresses and data local to their roots. -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +variable {V : Type} {d : ℕ} + +open Classical in +private abbrev shape (x : Node V d) := lift (fun _ => ()) x + +open Classical in +/-- The value specified by `.inr (v, Fin.last d, c)`. -/ +abbrev tip (v : V) (c : Address d) : Node V d := .inr (v, Fin.last d, c) + +open Classical in +/-- The value specified by `Fin.cases (.inl ()) (fun i => .inr ((), i.castSucc, if f then c else +Trie.mask c i)) j`. -/ +def prev (f : Prop) (j : Fin (d + 1)) (c : Address d) : Node Unit d := + Fin.cases (.inl ()) (fun i => .inr ((), i.castSucc, if f then c else Trie.mask c i)) j + +open Classical in +/-- The internal used in the `Children` construction. -/ +def internal (f : Prop) : Node Unit d → Node Unit d → Prop + | .inl _, y => ∃ c, y = .inr ((), 0, c) ∧ (f ∨ c = fun _ => false) + | .inr (_, j, c), y => y = prev f j c ∨ + ∃ (i : Fin d) (b : Bool), j = i.castSucc ∧ + y = .inr ((), i.succ, if f then c else Function.update c i b) + +open Classical in +/-- Endpoints either lie on the same tree or join two fully addressed leaves. -/ +def traceAdj (same fx fy : Prop) (xy yx : Address d) (x y : Node Unit d) : Prop := + (same ∧ internal fx x y ∧ internal fy y x) ∨ (x = tip () xy ∧ y = tip () yx) + +open Classical in +private theorem split_node (x y : Node V d) : + x = y ↔ root y = root x ∧ shape x = shape y := + ⟨fun h => h ▸ ⟨rfl, rfl⟩, fun ⟨h, k⟩ => lift_eq (fun _ => h.symm) k⟩ + +open Classical in +private theorem tip_eq (x : Node V d) {c : Address d} (h : shape x = tip () c) : + x = tip (root x) c := + (split_node _ _).mpr ⟨rfl, h⟩ + +open Classical in +private theorem no_tip (f : Prop) (c e : Address d) : + ¬ internal f (tip () c) (tip () e) := by + rintro (h | ⟨i, b, h, _⟩) + · have aux (j : Fin (d + 1)) : tip () e ≠ prev f j c := by + induction j using Fin.cases with + | zero => simp [prev, tip] + | succ i => + intro h + simp only [prev, Fin.cases_succ] at h + exact Fin.castSucc_ne_last i (congrArg (fun t => t.2.1) (Sum.inr.inj h)).symm + exact aux _ h + · exact Fin.castSucc_ne_last i h.symm + +variable (T : Trie V d) + +open Classical in +private theorem eq_up (v : V) (j : Fin (d + 1)) (c : Address d) (y : Node V d) : + y = Trie.up T v j c ↔ v = root y ∧ shape y = prev (T.frozen v) j c := by + rw [split_node] + induction j using Fin.cases with + | zero => rfl + | succ i => simp only [Trie.up, prev, Fin.cases_succ]; rfl + +open Classical in +private theorem at_root (v : V) (y : Node V d) : + y ∈ Trie.possible T (.inl v) ↔ v = root y ∧ internal (T.frozen v) (.inl ()) (shape y) := by + have he (c : Address d) : + y = .inr (v, 0, c) ↔ v = root y ∧ shape y = .inr ((), 0, c) := split_node _ _ + by_cases hf : T.frozen v + · simp only [Trie.possible, hf, ite_true, Finset.mem_image, Finset.mem_univ, true_and, + internal, true_or, and_true, eq_comm (b := y), he, exists_and_left] + · simp only [Trie.possible, hf, ite_false, Finset.mem_singleton, he, internal, false_or, + exists_eq_right] + +open Classical in +private theorem of_internal {x y : Node V d} (h : root x = root y) + (hi : internal (T.frozen (root x)) (shape x) (shape y)) : y ∈ Trie.possible T x := by + rcases x with v | ⟨v, j, c⟩ + · exact (at_root T v y).mpr ⟨h, hi⟩ + simp only [Trie.possible, Finset.mem_insert, Finset.mem_singleton] + rcases hi with hu | ⟨i, b, rfl, he⟩ + · exact .inl ((eq_up T _ _ _ _).mpr ⟨h, hu⟩) + have hd : y = Trie.down T v i.castSucc c b := by + rw [Trie.down, Fin.lastCases_castSucc, split_node] + exact ⟨h, he⟩ + cases b + · exact .inr (.inl hd) + · exact .inr (.inr hd) + +open Classical in +/-- A one-way candidate ending at another leaf always has the target +address. Its source may have been an unused address. -/ +private theorem cases_possible {x y : Node V d} (h : y ∈ Trie.possible T x) : + (root x = root y ∧ internal (T.frozen (root x)) (shape x) (shape y)) ∨ + ∃ c, shape x = tip () c ∧ shape y = tip () (T.code (root y) (root x)) ∧ + root y = T.peer (root x) c := by + rcases x with v | ⟨v, j, c⟩ + · exact .inl ((at_root T v y).mp h) + simp only [Trie.possible, Finset.mem_insert, Finset.mem_singleton] at h + rcases h with hu | hd + · obtain ⟨hr, he⟩ := (eq_up T _ _ _ _).mp hu + exact .inl ⟨hr, .inl he⟩ + obtain ⟨b, rfl⟩ : ∃ b, y = Trie.down T v j c b := hd.elim (fun e => ⟨false, e⟩) (fun e => ⟨true, + e⟩) + induction j using Fin.lastCases with + | last => + simp only [Trie.down, Fin.lastCases_last, Trie.branch, Trie.address_last] + exact .inr ⟨c, rfl, rfl, rfl⟩ + | cast i => + simp only [Trie.down, Fin.lastCases_castSucc] + exact .inl ⟨rfl, .inr ⟨i, b, rfl, rfl⟩⟩ + +open Classical in +theorem adj_near (hs : ∀ v, v ∈ T.near v) {x y : Node V d} (h : y ∈ T.adj x) : + root y ∈ T.near (root x) := by + rcases cases_possible T (Finset.mem_filter.mp h).1 with ⟨hr, _⟩ | ⟨c, _, _, he⟩ + · rw [hr]; exact hs _ + · rw [he, Trie.peer] + split + · rename_i he + exact he.choose_spec.1 + · exact hs _ + +open Classical in +theorem adj_iff {x y : Node V d} (h : root y ∈ T.near (root x)) : + y ∈ T.adj x ↔ traceAdj (root x = root y) (T.frozen (root x)) (T.frozen (root y)) + (T.code (root x) (root y)) (T.code (root y) (root x)) + (lift (fun _ => ()) x) (lift (fun _ => ()) y) := by + constructor + · intro he + obtain ⟨hx, hy⟩ := Finset.mem_filter.mp he + rcases cases_possible T hx with ⟨e, hx⟩ | ⟨c, hx, hy', _⟩ <;> + rcases cases_possible T hy with ⟨_, hy⟩ | ⟨b, hy, hx', _⟩ + · exact .inl ⟨e, hx, hy⟩ + · rw [hx', hy] at hx + exact (no_tip _ _ _ hx).elim + · rw [hy', hx] at hy + exact (no_tip _ _ _ hy).elim + · exact .inr ⟨hx', hy'⟩ + · rintro (⟨e, hx, hy⟩ | ⟨hx, hy⟩) + · exact Finset.mem_filter.mpr ⟨of_internal T e hx, of_internal T e.symm hy⟩ + · have he := T.join h + simp only [Trie.branch, Trie.address_last] at he + exact (tip_eq x hx).symm ▸ (tip_eq y hy).symm ▸ he + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- +# Short intrinsic names for bundles + +A key alias can be reused in distant footprints. Seam and station +names need only distinguish the contacts of a single cell. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order (Rules Signal) + +variable {F U X E V K J Z A : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + (S : Sharing C a b Y) + +open Classical in +/-- The value specified by `S.src e = v ∨ S.dst e = v`. -/ +def uses (v : V) (e : E) := S.src e = v ∨ S.dst e = v + +open Classical in +/-- The data for the marking construction, including `mark`, `number`, `key`, `atCell`, `atKey`. -/ +structure Marking (J Z A : Type) where + /-- The `Marking` component of type `V → J`. -/ + mark : V → J + /-- The `Marking` component of type `Place C → Z`. -/ + number : Place C → Z + /-- The `Marking` component of type `K → A`. -/ + key : K → A + atCell : ∀ i j, i.1 = j.1 → number i = number j → i = j + atKey : ∀ v, Set.InjOn key (S.seen v) + across : ∀ e i j, i ∈ S.seen (S.src e) → j ∈ S.seen (S.dst e) → key i = key j → i = j + marks : ∀ e, mark (S.src e) = mark (S.dst e) → S.src e = S.dst e + seams : ∀ v e f, uses S v e → uses S v f → + (mark (S.src e), mark (S.dst e)) = (mark (S.src f), mark (S.dst f)) → e = f + ports : ∀ v e, uses S v e → ∃ z, (e, z) ∈ (C v).ports + +open Classical in +/-- Indexes the spot by the coordinates of `J × (Z ⊕ (Bool ⊕ (Fin M ⊕ Fin M)))`. -/ +abbrev Spot (J Z : Type) (M : ℕ) := J × (Z ⊕ (Bool ⊕ (Fin M ⊕ Fin M))) +open Classical in +/-- Indexes the lane by the coordinates of `(A × (J ⊕ (J × J) ⊕ (J × Z))) ⊕ ((J × J) × Fin M) ⊕ +Layout.Grid M (J × Z)`. -/ +abbrev Lane (J Z A : Type) (M : ℕ) := + (A × (J ⊕ (J × J) ⊕ (J × Z))) ⊕ ((J × J) × Fin M) ⊕ Layout.Grid M (J × Z) + +namespace Marking +variable {S} (m : Marking S J Z A) + +open Classical in +/-- The value specified by `(m.mark (S.src e), m.mark (S.dst e))`. -/ +def edge (e : E) := (m.mark (S.src e), m.mark (S.dst e)) +open Classical in +/-- The value specified by `(m.mark i.1, m.number i)`. -/ +def row (i : Place C) := (m.mark i.1, m.number i) + +open Classical in +/-- In the case `.inl (.inl i)`, this construction gives `(m.mark i.1, .inl (m.number i))`. -/ +def spot : S.Position → Spot J Z M + | .inl (.inl i) => (m.mark i.1, .inl (m.number i)) + | .inl (.inr (.inl v)) => (m.mark v, .inr (.inl false)) + | .inl (.inr (.inr v)) => (m.mark v, .inr (.inl true)) + | .inr (.inl (v, j)) => (m.mark v, .inr (.inr (.inl j))) + | .inr (.inr (v, j)) => (m.mark v, .inr (.inr (.inr j))) + +open Classical in +/-- In the case `.inl v`, this construction gives `.inl (m.mark v.val)`. -/ +def ordinary {k : K} : S.Line k → J ⊕ (J × J) ⊕ (J × Z) + | .inl v => .inl (m.mark v.val) + | .inr (.inl e) => .inr (.inl (m.edge e.val)) + | .inr (.inr i) => .inr (.inr (m.row i.val)) + +open Classical in +/-- In the case `.inl ⟨k, v⟩`, this construction gives `.inl (m.key k, m.ordinary v)`. -/ +def lane : Rules.Line S → Lane J Z A M + | .inl ⟨k, v⟩ => .inl (m.key k, m.ordinary v) + | .inr (.inl (e, j)) => .inr (.inl (m.edge e, j)) + | .inr (.inr i) => .inr (.inr (Layout.Grid.map m.row i)) + +open Classical in +/-- In the case `.inl ⟨_, .inl i⟩`, this construction gives `i.val = v`. -/ +def contains (v : V) : Rules.Line S → Prop + | .inl ⟨_, .inl i⟩ => i.val = v + | .inl ⟨_, .inr (.inl i)⟩ => uses S v i.val + | .inl ⟨_, .inr (.inr i)⟩ => i.val.1 = v + | .inr (.inl (e, _)) => uses S v e + | .inr (.inr i) => (Layout.Grid.point i).1 = v + +open Classical in +theorem known (v : V) (k : K) (i : S.Line k) (h : contains v (.inl ⟨k, i⟩)) : k ∈ S.seen v := by + rcases i with i|i|i + · exact h ▸ i.property + · rcases h with h|h + · exact h ▸ i.property.1 + · exact h ▸ i.property.2 + · exact h ▸ S.within i.val i.property + +open Classical in +private theorem same_row {v : V} {i j : Place C} (hi : i.1 = v) (hj : j.1 = v) + (h : m.row i = m.row j) : i = j := + m.atCell _ _ (hi.trans hj.symm) (congrArg Prod.snd h) + +open Classical in +theorem lane_inj (v : V) (e f : Rules.Line S) (he : contains v e) (hf : contains v f) + (eq : m.lane e = m.lane f) : e = f := by + rcases e with ⟨k, e⟩|⟨i, j⟩|i <;> rcases f with ⟨l, f⟩|⟨u, v'⟩|u + all_goals simp only [lane, Sum.inl.injEq, Sum.inr.injEq, Prod.mk.injEq, reduceCtorEq] at eq + · have hk : k = l := m.atKey v (known v k e he) (known v l f hf) eq.1 + subst l + have h := eq.2 + rcases e with i|i|i <;> rcases f with j|j|j + all_goals simp only [ordinary, Sum.inl.injEq, Sum.inr.injEq, reduceCtorEq] at h + · rw [Subtype.ext (he.trans hf.symm)] + · rw [Subtype.ext (m.seams v _ _ he hf h)] + · rw [Subtype.ext (m.same_row he hf h)] + · rw [m.seams v _ _ he hf eq.1, eq.2] + · rcases i with ⟨i, j⟩|⟨i, j⟩ <;> rcases u with ⟨u, w⟩|⟨u, w⟩ + · have pair : (m.row i, j) = (m.row u, w) := Sum.inl.inj eq + have slot : j = w := congrArg Prod.snd pair + rw [m.same_row (i := i) (j := u) he hf (congrArg Prod.fst pair), slot] + · exact (Sum.inl_ne_inr eq).elim + · exact (Sum.inr_ne_inl eq).elim + · have pair : (m.row i, j) = (m.row u, w) := Sum.inr.inj eq + have slot : j = w := congrArg Prod.snd pair + rw [m.same_row (i := i) (j := u) he hf (congrArg Prod.fst pair), slot] + +open Classical in +theorem home_mark (v : S.Position) : (m.spot v).1 = m.mark (S.home v) := by + rcases v with ((i|i|i)|(i|i)) <;> rfl + +open Classical in +theorem spot_inj {v w : S.Position} (hv : S.home v = S.home w) (he : m.spot v = m.spot w) : v = w + := by + rcases v with ((v|v|v)|(⟨v, i⟩|⟨v, i⟩)) <;> rcases w with ((w|w|w)|(⟨w, j⟩|⟨w, j⟩)) + all_goals simp only [spot, Prod.mk.injEq, Sum.inl.injEq, Sum.inr.injEq, reduceCtorEq, and_false] + at he + · rw [m.atCell _ _ hv he.2] + · exact congrArg (fun z => Sum.inl (Sum.inr (Sum.inl z))) hv + · exact congrArg (fun z => Sum.inl (Sum.inr (Sum.inr z))) hv + · change v = w at hv + rw [hv, he.2] + · change v = w at hv + rw [hv, he.2] + +variable [Field F] [Fintype E] [Fintype V] [Fintype K] {e : E → ℕ} (p : Profile C e) (P : ℕ) + +open Classical in +theorem contains_iff (v : V) (i : Rules.Line S) : + contains v i ↔ S.home ((S.backdrop.emitted p P).src i) = v ∨ + S.home ((S.backdrop.emitted p P).dst i) = v := by + rcases i with ⟨k, j|j|j⟩ | ⟨i, x⟩ | ⟨i, x⟩ | ⟨i, x⟩ + · exact ⟨Or.inl, fun h => h.elim id id⟩ + · rfl + · exact ⟨Or.inl, fun h => h.elim id id⟩ + · rfl + · exact ⟨Or.inl, fun h => h.elim id id⟩ + · exact ⟨Or.inl, fun h => h.elim id id⟩ + +open Classical in +theorem of_touch (v : S.Position) (i : Rules.Line S) (h : touches (S.backdrop.emitted p P) v i) : + contains (S.home v) i := + (contains_iff p P _ _).mpr (h.imp (congrArg S.home) (congrArg S.home)) + +open Classical in +theorem unique : Unique (S.backdrop.emitted p P) m.lane := + fun v i j hi hj => m.lane_inj (S.home v) i j (of_touch p P v i hi) (of_touch p P v j hj) + +open Classical in +private theorem ends_mark (i : Rules.Line S) : + m.mark (S.home ((S.backdrop.emitted p P).src i)) + = m.mark (S.home ((S.backdrop.emitted p P).dst i)) → + S.home ((S.backdrop.emitted p P).src i) = S.home ((S.backdrop.emitted p P).dst i) := by + rcases i with ⟨k, j|j|j⟩ | ⟨i, x⟩ | ⟨i, x⟩ | ⟨i, x⟩ + · exact fun _ => rfl + · exact m.marks _ + · exact fun _ => rfl + · exact m.marks _ + · exact fun _ => rfl + · exact fun _ => rfl + +open Classical in +theorem reflect (v : S.Position) (i : Rules.Line S) (hi : contains (S.home v) i) (s : Bool) + (he : m.spot (side (S.backdrop.emitted p P) s i) = m.spot v) : + side (S.backdrop.emitted p P) s i = v := by + refine m.spot_inj ?_ he + have hh := congrArg Prod.fst he + rw [home_mark, home_mark] at hh + rcases (contains_iff p P _ _).mp hi with hi|hi <;> cases s + · exact hi + · exact (m.ends_mark p P i ((congrArg m.mark hi).trans hh.symm)).symm.trans hi + · exact (m.ends_mark p P i (hh.trans (congrArg m.mark hi).symm)).trans hi + · exact hi + +open Classical in +theorem same (v : S.Position) : Same (G := S.backdrop.emitted p P) m.spot v := + fun i hi => m.reflect p P v i (of_touch p P v i hi) + +end Marking +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- Both endpoints of a logical bundle are encoded in its short name. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order + +variable {F U X E V K J Z A : Type} {M r t : ℕ} + +namespace Spot +open Classical in +/-- The value specified by `(j, .inl z)`. -/ +def station (j : J) (z : Z) : Spot J Z M := (j, .inl z) +open Classical in +/-- The value specified by `(j, .inr (.inl false))`. -/ +def hub (j : J) : Spot J Z M := (j, .inr (.inl false)) +open Classical in +/-- The value specified by `(j, .inr (.inl true))`. -/ +def storage (j : J) : Spot J Z M := (j, .inr (.inl true)) +open Classical in +/-- The value specified by `(j, .inr (.inr (.inl k)))`. -/ +def first (j : J) (k : Fin M) : Spot J Z M := (j, .inr (.inr (.inl k))) +open Classical in +/-- The value specified by `(j, .inr (.inr (.inr k)))`. -/ +def second (j : J) (k : Fin M) : Spot J Z M := (j, .inr (.inr (.inr k))) +end Spot + +namespace Lane +open Classical in +/-- The value specified by `.inl (k, .inl v)`. -/ +def store (k : A) (v : J) : Lane J Z A M := .inl (k, .inl v) +open Classical in +/-- The value specified by `.inl (k, .inr (.inl e))`. -/ +def relay (k : A) (e : J × J) : Lane J Z A M := .inl (k, .inr (.inl e)) +open Classical in +/-- The value specified by `.inl (k, .inr (.inr (v, i)))`. -/ +def reader (k : A) (v : J) (i : Z) : Lane J Z A M := .inl (k, .inr (.inr (v, i))) +open Classical in +/-- The value specified by `.inr (.inl (e, j))`. -/ +def seam (e : J × J) (j : Fin M) : Lane J Z A M := .inr (.inl (e, j)) +open Classical in +/-- The value specified by `.inr (.inr (.inl ((v, i), j)))`. -/ +def left (v : J) (i : Z) (j : Fin M) : Lane J Z A M := .inr (.inr (.inl ((v, i), j))) +open Classical in +/-- The value specified by `.inr (.inr (.inr ((v, i), j)))`. -/ +def right (v : J) (i : Z) (j : Fin M) : Lane J Z A M := .inr (.inr (.inr ((v, i), j))) + +open Classical in +/-- In the case `.inl (_, .inl v)`, this construction gives `(.hub v, .storage v)`. -/ +def ends : Lane J Z A M → Spot J Z M × Spot J Z M + | .inl (_, .inl v) => (.hub v, .storage v) + | .inl (_, .inr (.inl (v, w))) => (.hub v, .hub w) + | .inl (_, .inr (.inr (v, i))) => (.hub v, .station v i) + | .inr (.inl ((v, w), j)) => (.first v j, .first w j) + | .inr (.inr (.inl ((v, i), j))) => (.station v i, .first v j) + | .inr (.inr (.inr ((v, i), j))) => (.station v i, .second v j) + +open Classical in +/-- Computes the side by the application `cond b l.ends.2 l.ends.1`. -/ +def side (l : Lane J Z A M) (b : Bool) := cond b l.ends.2 l.ends.1 + +end Lane + +open Classical in +/-- Indexes the details by the coordinates of `ℕ × Decoder α`. -/ +abbrev Details (α : Type) := ℕ × Decoder α +open Classical in +/-- Indexes the item by the coordinates of `Lane J Z A M × Details (Signal M r t)`. -/ +abbrev Item (M r t : ℕ) (J Z A : Type) := Lane J Z A M × Details (Signal M r t) + +open Classical in +/-- Uses `⟨i.1, i.1.side, i.2.1, i.2.2⟩` as the representation. -/ +def Item.arc (i : Item M r t J Z A) : Arc (Signal M r t) (Lane J Z A M) (Spot J Z M) := + ⟨i.1, i.1.side, i.2.1, i.2.2⟩ + +open Classical in +/-- Transforms the indexed data by `(k.1, k.2.map Signal.key)`. -/ +def keyInfo (k : Details (Surface.Stage.Symbol (M * t))) : Details (Signal M r t) := + (k.1, k.2.map Signal.key) + +open Classical in +/-- The value specified by `(Chunk.width r e, frontDecode M r t e)`. -/ +def frontInfo (e : ℕ) : Details (Signal M r t) := (Chunk.width r e, frontDecode M r t e) +open Classical in +/-- The value specified by `(Chunk.width t e, backDecode M r t e)`. -/ +def backInfo (e : ℕ) : Details (Signal M r t) := (Chunk.width t e, backDecode M r t e) + +namespace Marking +variable {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} (m : Marking S J Z A) (L : Rules S) {e : E → ℕ} (p : Profile C e) (P : ℕ) + +open Classical in +/-- In the case `.inl i`, this construction gives `keyInfo (Y.width i.1, L.signal i.1)`. -/ +def info : Rules.Line S → Details (Signal M r t) + | .inl i => keyInfo (Y.width i.1, L.signal i.1) + | .inr (.inl (i, j)) => frontInfo ((p.1 (.inl i)).val j) + | .inr (.inr (.inl (i, j))) => frontInfo ((p.1 (.inr i)).val j) + | .inr (.inr (.inr (i, j))) => backInfo ((p.2 i).val j) + +open Classical in +/-- The value specified by `(m.lane i, info L p i)`. -/ +def record (i : Rules.Line S) : Item M r t J Z A := (m.lane i, info L p i) + +variable [Field F] [Fintype E] [Fintype V] [Fintype K] + +open Classical in +theorem side_eq (i : Rules.Line S) (b : Bool) : + (m.lane i).side b = m.spot (side (S.backdrop.emitted p P) b i) := by + rcases i with ⟨k, j|j|j⟩ | ⟨i, x⟩ | ⟨i, x⟩ | ⟨i, x⟩ <;> cases b <;> rfl + +open Classical in +theorem arc_eq (i : Rules.Line S) : + (m.record L p i).arc = arc (L.script p P) m.lane m.spot i := by + have h : info L p i = ((S.backdrop.emitted p P).width i, (L.script p P).signal i) := by + rcases i with i | ⟨i, j⟩ | ⟨i, j⟩ | ⟨i, j⟩ + · exact Prod.ext rfl (decode_comp (Y.code i.1) (L.tag i.1) Signal.key).symm + all_goals rfl + unfold record Item.arc + rw [h] + exact congrArg (fun f => Arc.mk _ f _ _) (funext (m.side_eq p P i)) + +end Marking +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Terminal cell data + +One cell's station and seam lists are in their original order. The +only extra variable information from outside that cell is membership +of key aliases in the footprints of neighboring cells. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order + +open Classical in +/-- The data for the row construction, including `number`, `point`, `ext`, `reads`, `visible`. -/ +structure Row (F Z A : Type) (M r t : ℕ) where + /-- The `Row` field of type `Z`. -/ + number : Z + /-- The `Row` field of type `F`. -/ + point : F + /-- The `Row` component of type `Bool → ℕ`. -/ + ext : Bool → ℕ + /-- The `Row` component of type `List A`. -/ + reads : List A + /-- The visible coordinates at each index of type `Finset A`. -/ + visible : Finset A + /-- The label at each coordinate of type `Surface.Stage.Label F (M * r) (M * t)`. -/ + label : Surface.Stage.Label F (M * r) (M * t) + /-- The `Row` component of type `Fin M → ℕ`. -/ + first : Fin M → ℕ + /-- The `Row` component of type `Fin M → ℕ`. -/ + second : Fin M → ℕ + +open Classical in +/-- The data for the port construction, including `edge`, `point`, `energy`. -/ +structure Port (F J : Type) (M : ℕ) where + /-- The indexed edge data carried by `Port`, with type `J × J`. -/ + edge : J × J + /-- The `Port` field of type `F`. -/ + point : F + /-- The energy assigned to each index of type `Fin M → ℕ`. -/ + energy : Fin M → ℕ + +open Classical in +/-- The data for the sheet construction, including `mark`, `rows`, `ports`, `catalog`. -/ +structure Sheet (F J Z A : Type) (M r t : ℕ) where + /-- The `Sheet` field of type `J`. -/ + mark : J + /-- The indexed rows of type `List (Row F Z A M r t)`. -/ + rows : List (Row F Z A M r t) + /-- The `Sheet` component of type `List (Port F J M)`. -/ + ports : List (Port F J M) + /-- The `Sheet` component of type `Finset (A × Details (Surface.Stage.Symbol (M * t)))`. -/ + catalog : Finset (A × Details (Surface.Stage.Symbol (M * t))) + +variable {F U X E V K J Z A : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} + +namespace Marking +variable (m : Marking S J Z A) (L : Rules S) {e : E → ℕ} (p : Profile C e) + +open Classical in +/-- The row data of type `Row F Z A M r t` for the given inputs. -/ +def rowData (i : Place C) : Row F Z A M r t := + ⟨m.number i, (item C i).pos, fun s => cond s (L.right.ports i).length (L.left.ports i).length, + (L.reads i).map m.key, (S.reads i).image m.key, L.label i, + fun j => ((p.1 (.inr i)).val j).val, fun j => ((p.2 i).val j).val⟩ + +open Classical in +/-- Uses `⟨m.edge i.1, i.2, fun j => ((p.1 (.inl i.1)).val j).val⟩` as the representation. -/ +def portData (i : E × F) : Port F J M := + ⟨m.edge i.1, i.2, fun j => ((p.1 (.inl i.1)).val j).val⟩ + +open Classical in +/-- The value specified by `(m.key k, Y.width k, L.signal k)`. -/ +def entry (k : K) := (m.key k, Y.width k, L.signal k) + +open Classical in +/-- The selected finite family `⟨m.mark v, (secondList C v).map (m.rowData L p), (C v).ports.map +(m.portData p), (S.seen v).image (m.entry L)⟩`. -/ +def sheet (v : V) : Sheet F J Z A M r t := + ⟨m.mark v, (secondList C v).map (m.rowData L p), (C v).ports.map (m.portData p), + (S.seen v).image (m.entry L)⟩ + +open Classical in +theorem row_mem (i : Place C) : m.rowData L p i ∈ (m.sheet L p i.1).rows := by + apply List.mem_map_of_mem + exact List.mem_map.mpr ⟨i.2, List.mem_finRange _, rfl⟩ + +open Classical in +theorem row_spec {v} {i : Row F Z A M r t} (h : i ∈ (m.sheet L p v).rows) : + ∃ j, j.1 = v ∧ m.rowData L p j = i := by + obtain ⟨j, hj, rfl⟩ := List.mem_map.mp h + obtain ⟨i, _, rfl⟩ := List.mem_map.mp hj + exact ⟨_, rfl, rfl⟩ + +open Classical in +/-- The observes of type `Prop` for the given inputs. -/ +def Observes (v : V) (known : J → A → Prop) : Prop := + ∀ i, uses S v i → ∀ k ∈ S.seen v, + (known (m.mark (S.src i)) (m.key k) ↔ k ∈ S.seen (S.src i)) ∧ + (known (m.mark (S.dst i)) (m.key k) ↔ k ∈ S.seen (S.dst i)) + +open Classical in +theorem observes (v : V) (known : J → A → Prop) + (h : ∀ i, uses S v i → ∀ u, uses S u i → ∀ x, known (m.mark u) x ↔ x ∈ (S.seen u).image m.key) : + m.Observes v known := by + intro i hi k hk + have one (u : V) (hu : uses S u i) : known (m.mark u) (m.key k) ↔ k ∈ S.seen u := by + rw [h i hi u hu, Finset.mem_image] + refine ⟨fun ⟨j, hj, he⟩ => ?_, fun h => ⟨k, h, rfl⟩⟩ + have hx : k = j := by + rcases hi with rfl | rfl <;> rcases hu with rfl | rfl + · exact m.atKey _ hk hj he.symm + · exact m.across i _ _ hk hj he.symm + · exact (m.across i _ _ hj hk he).symm + · exact m.atKey _ hk hj he.symm + rwa [hx] + exact ⟨one _ (.inl rfl), one _ (.inr rfl)⟩ + +end Marking + +namespace Sheet +variable (c : Sheet F J Z A M r t) (known : J → A → Prop) + +open Classical in +/-- The holds used in the `Sheet` construction. -/ +inductive Holds : Item M r t J Z A → Prop + | store (k) : k ∈ c.catalog → Holds (.store k.1 c.mark, keyInfo k.2) + | relay (k z) : k ∈ c.catalog → z ∈ c.ports → known z.edge.1 k.1 → known z.edge.2 k.1 → + Holds (.relay k.1 z.edge, keyInfo k.2) + | reader (k i) : k ∈ c.catalog → i ∈ c.rows → k.1 ∈ i.visible → + Holds (.reader k.1 c.mark i.number, keyInfo k.2) + | seam (z j) : z ∈ c.ports → Holds (.seam z.edge j, frontInfo (z.energy j)) + | left (i j) : i ∈ c.rows → Holds (.left c.mark i.number j, frontInfo (i.first j)) + | right (i j) : i ∈ c.rows → Holds (.right c.mark i.number j, backInfo (i.second j)) + +end Sheet +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Exact coverage of the incident logical wires by the cell data -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order + +variable {F U X E V K J Z A : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} + +open Classical in +/-- Uses `{w | ∃ i, c.Holds known i ∧ i.arc = w ∧ (w.side false = s ∨ w.side true = s)}` as the +representation. -/ +def Sheet.lines (c : Sheet F J Z A M r t) (known : J → A → Prop) (s : Spot J Z M) := + {w | ∃ i, c.Holds known i ∧ i.arc = w ∧ (w.side false = s ∨ w.side true = s)} + +namespace Marking +variable (m : Marking S J Z A) (L : Rules S) {e : E → ℕ} (p : Profile C e) + (v : V) (known : J → A → Prop) (hk : m.Observes v known) + +include hk + +open Classical in +private theorem holds_of_contains (i : Rules.Line S) (he : contains v i) : + (m.sheet L p v).Holds known (m.record L p i) := by + have km (k : K) (h : k ∈ S.seen v) : m.entry L k ∈ (m.sheet L p v).catalog := + Finset.mem_image_of_mem _ h + have pm (i : E) (h : uses S v i) : ∃ z, m.portData p (i, z) ∈ (m.sheet L p v).ports := by + obtain ⟨z, hz⟩ := m.ports v i h + exact ⟨z, List.mem_map_of_mem hz⟩ + rcases i with ⟨k, j⟩ | ⟨i, x⟩ | ⟨i, x⟩ | ⟨i, x⟩ + · have hu := Marking.known v k j he + rcases j with j | j | j + · change j.val = v at he + subst v + exact .store (m.entry L k) (km k hu) + · obtain ⟨z, hz⟩ := pm _ he + obtain ⟨hs, ht⟩ := hk _ he k hu + exact .relay (m.entry L k) (m.portData p (j.val, z)) (km k hu) hz + (hs.mpr j.property.1) (ht.mpr j.property.2) + · change j.val.1 = v at he + subst v + exact .reader (m.entry L k) (m.rowData L p j.val) (km k hu) (m.row_mem L p j.val) + (Finset.mem_image_of_mem m.key j.property) + · obtain ⟨z, hz⟩ := pm _ he + exact .seam (m.portData p (i, z)) x hz + · change i.1 = v at he + subst v + exact .left (m.rowData L p i) x (m.row_mem L p i) + · change i.1 = v at he + subst v + exact .right (m.rowData L p i) x (m.row_mem L p i) + +open Classical in +theorem holds (i : Item M r t J Z A) : + (m.sheet L p v).Holds known i ↔ ∃ j, contains v j ∧ m.record L p j = i := by + refine ⟨fun h => ?_, fun ⟨j, hj, he⟩ => he ▸ m.holds_of_contains L p v known hk j hj⟩ + cases h with + | store k hm => + obtain ⟨i, hi, rfl⟩ := Finset.mem_image.mp hm + exact ⟨.inl ⟨i, .inl ⟨v, hi⟩⟩, rfl, rfl⟩ + | relay k z hm hz h₁ h₂ => + obtain ⟨i, hi, rfl⟩ := Finset.mem_image.mp hm + obtain ⟨j, hj, rfl⟩ := List.mem_map.mp hz + have hs := S.meets v j hj + obtain ⟨hs', ht'⟩ := hk _ hs i hi + exact ⟨.inl ⟨i, .inr (.inl ⟨j.1, hs'.mp h₁, ht'.mp h₂⟩)⟩, hs, rfl⟩ + | reader k x hm hx hr => + obtain ⟨i, hi, rfl⟩ := Finset.mem_image.mp hm + obtain ⟨j, rfl, rfl⟩ := m.row_spec L p hx + obtain ⟨l, hl, hli⟩ := Finset.mem_image.mp hr + have he : l = i := m.atKey _ (S.within j hl) hi hli + subst l + exact ⟨.inl ⟨i, .inr (.inr ⟨j, hl⟩)⟩, rfl, rfl⟩ + | seam z k hz => + obtain ⟨j, hj, rfl⟩ := List.mem_map.mp hz + exact ⟨.inr (.inl (j.1, k)), S.meets v j hj, rfl⟩ + | left x k hx => + obtain ⟨j, rfl, rfl⟩ := m.row_spec L p hx + exact ⟨.inr (.inr (.inl (j, k))), rfl, rfl⟩ + | right x k hx => + obtain ⟨j, rfl, rfl⟩ := m.row_spec L p hx + exact ⟨.inr (.inr (.inr (j, k))), rfl, rfl⟩ + +omit hk +variable [Field F] [Fintype E] [Fintype V] [Fintype K] + +open Classical in +theorem lines (P : ℕ) (z : S.Position) (hz : m.Observes (S.home z) known) : + (m.sheet L p (S.home z)).lines known (m.spot z) = cloud (L.script p P) m.lane m.spot z := by + ext c + constructor + · rintro ⟨i, hi, rfl, h⟩ + obtain ⟨j, hj, rfl⟩ := (m.holds L p _ _ hz _).mp hi + rw [m.arc_eq L p P] at h ⊢ + exact ⟨j, h.imp (m.reflect p P z j hj false) (m.reflect p P z j hj true), rfl⟩ + · rintro ⟨i, h, rfl⟩ + exact ⟨_, m.holds_of_contains L p _ _ hz _ (of_touch p P _ _ h), m.arc_eq L p P i, + h.imp (congrArg m.spot) (congrArg m.spot)⟩ + +end Marking +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Printing equality constraints on all the hub's ordinary wires -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order + +variable {F U X E V K J Z A : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} + +open Classical in +/-- Uses `{p | ∃ k j data, c.Holds known (.inl (k, j), data) ∧ p = (.inl (k, j), Lane.store k +c.mark)}` as the representation. -/ +def Sheet.hub (c : Sheet F J Z A M r t) (known : J → A → Prop) : + Set (Lane J Z A M × Lane J Z A M) := + {p | ∃ k j data, c.Holds known (.inl (k, j), data) ∧ p = (.inl (k, j), Lane.store k c.mark)} + +namespace Marking +variable [Fintype E] [Fintype V] [Fintype K] + +open Classical in +private theorem contacts_iff (v : V) (i : S.Edge) : + i ∈ contacts S v ↔ contains v (.inl i : Rules.Line S) := by + simp only [contacts, Finset.mem_filter, Finset.mem_univ, true_and] + have eq : S.source i = .inr (.inl v) ∨ S.target i = .inr (.inl v) ↔ + contains v (.inl i : Rules.Line S) := by + rcases i with ⟨k, j|j|j⟩ <;> simp [Sharing.source, Sharing.start, Sharing.target, contains, + uses] + rw [eq] + exact ⟨And.right, fun h => ⟨known v i.1 i.2 h, h⟩⟩ + +variable (m : Marking S J Z A) (L : Rules S) {e : E → ℕ} (p : Profile C e) + (v : V) (seen : J → A → Prop) (hk : m.Observes v seen) + +open Classical in +private def keyLane (i : S.Edge) := m.lane (.inl i) + +include hk in +open Classical in +private theorem pairs_eq : + {i | ∃ j ∈ (contacts S v).attach.toList.map (mates S v), Prod.map m.keyLane m.keyLane j = i} = + (m.sheet L p v).hub seen := by + ext i + constructor + · rintro ⟨_, h, rfl⟩ + obtain ⟨⟨⟨k, j⟩, hj⟩, _, rfl⟩ := List.mem_map.mp h + refine ⟨m.key k, m.ordinary j, keyInfo (Y.width k, L.signal k), ?_, rfl⟩ + exact (m.holds L p _ _ hk _).mpr ⟨.inl ⟨k, j⟩, (contacts_iff v _).mp hj, rfl⟩ + · rintro ⟨k, j, data, he, rfl⟩ + obtain ⟨e, hc, eq⟩ := (m.holds L p _ _ hk _).mp he + have h : m.lane e = .inl (k, j) := congrArg Prod.fst eq + rcases e with ⟨a, e⟩ | ⟨i, j'⟩ | i + · obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Sum.inl.inj h) + let t : ↥(contacts S v) := ⟨⟨a, e⟩, (contacts_iff v _).mpr hc⟩ + exact ⟨mates S v t, List.mem_map_of_mem (by simp), rfl⟩ + all_goals cases h + +include hk in +open Classical in +theorem hub_eq [Field F] (P : ℕ) : + policy (L.script p P) m.lane (.inl (.inr (.inl v))) = tests ((m.sheet L p v).hub seen) := by + change operation checkPairs (((hubReads S v).map Sum.inl).map m.lane) = _ + rw [List.map_map] + change operation checkPairs ((pairs _).map m.keyLane) = _ + rw [reindex_pairs, m.pairs_eq L p v seen hk] + +end Marking +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Shape ownership + +Store the two station shapes at the station's cell. A seam shape +belongs to its source cell and is indexed by its destination color. +The other end reads this same value. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +open Classical in +/-- Indexes the axis by the coordinates of `J ⊕ (Bool × Z)`. -/ +abbrev Axis (J Z : Type) := J ⊕ (Bool × Z) + +variable {F U X E V K J Z A I : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} + +open Classical in +/-- Indexes the shape id by the coordinates of `First C ⊕ Place C`. -/ +abbrev ShapeID (C : V → Surface.Cell F (M * r) (M * t) U E X) := First C ⊕ Place C + +open Classical in +/-- Computes the cost by the application `Sum.elim (firstEnergy C e) (secondEnergy C)`. -/ +def cost (C : V → Surface.Cell F (M * r) (M * t) U E X) (e : E → ℕ) : ShapeID C → ℕ := + Sum.elim (firstEnergy C e) (secondEnergy C) + +open Classical in +/-- The equivalence obtained by `Equiv.sumPiEquivProdPi _`. -/ +def halves (C : V → Surface.Cell F (M * r) (M * t) U E X) (e : E → ℕ) : + Layout.Shapes M (cost C e) ≃ Profile C e := Equiv.sumPiEquivProdPi _ + +namespace Marking +variable (m : Marking S J Z A) + +open Classical in +/-- In the case `.inl (.inl i)`, this construction gives `(S.src i, .inl (m.mark (S.dst i)))`. -/ +def address : ShapeID C → V × Axis J Z + | .inl (.inl i) => (S.src i, .inl (m.mark (S.dst i))) + | .inl (.inr i) => (i.1, .inr (false, m.number i)) + | .inr i => (i.1, .inr (true, m.number i)) + +open Classical in +theorem address_injective : Function.Injective m.address := by + rintro ((i|i)|i) ((j|j)|j) h + all_goals simp only [address, Prod.mk.injEq, Sum.inl.injEq, Sum.inr.injEq, reduceCtorEq, + true_and, false_and, and_false] at h + · have := m.seams (S.src j) i j (.inl h.1) (.inl rfl) (Prod.ext (congrArg m.mark h.1) h.2) + rw [this] + · rw [m.atCell _ _ h.1 h.2] + · rw [m.atCell _ _ h.1 h.2] + +variable (loc : V ↪ I) (e : E → ℕ) {z : ℕ} (hz : ∀ j, cost C e j < 2 ^ z) + +open Classical in +/-- Indexes the shape seat by the coordinates of `(show ShapeID C ↪ V × Axis J Z from +⟨m.address, m.address_injective⟩).trans (loc.prodMap (.refl _))`. -/ +def shapeSeat : ShapeID C ↪ I × Axis J Z := + (show ShapeID C ↪ V × Axis J Z from ⟨m.address, m.address_injective⟩).trans + (loc.prodMap (.refl _)) + +open Classical in +/-- Builds `Transcript.Selector (Profile C e) (I × Axis J Z → Digits M z) where write p` with +the specified `write`, `read`, `valid`. -/ +def select : Transcript.Selector (Profile C e) (I × Axis J Z → Digits M z) where + write p := Pick.write (m.shapeSeat loc) _ hz ((halves C e).symm p) + read c := ((Pick.selector (m.shapeSeat loc) _ hz).read c).map (halves C e) + valid c p := by + simp only [Option.map_eq_some_iff, Transcript.Selector.valid, ← Equiv.eq_symm_apply] + simp [Pick.selector] + +open Classical in +theorem select_some (c : I × Axis J Z → Digits M z) : + ((m.select loc e hz).read c).isSome ↔ Pick.accepts (m.shapeSeat loc) (cost C e) c := by + simp [select, Pick.selector] + +open Classical in +theorem select_seam (p : Profile C e) (i : E) (j : Fin M) : + ((m.select loc e hz).write p (loc (S.src i), .inl (m.mark (S.dst i))) j).val = + ((p.1 (.inl i)).val j).val := + Pick.write_at (m.shapeSeat loc) _ hz ((halves C e).symm p) (.inl (.inl i)) j + +open Classical in +theorem select_first (p : Profile C e) (i : Place C) (j : Fin M) : + ((m.select loc e hz).write p (loc i.1, .inr (false, m.number i)) j).val = + ((p.1 (.inr i)).val j).val := + Pick.write_at (m.shapeSeat loc) _ hz ((halves C e).symm p) (.inl (.inr i)) j + +open Classical in +theorem select_second (p : Profile C e) (i : Place C) (j : Fin M) : + ((m.select loc e hz).write p (loc i.1, .inr (true, m.number i)) j).val = + ((p.2 i).val j).val := + Pick.write_at (m.shapeSeat loc) _ hz ((halves C e).symm p) (.inr i) j + +end Marking +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Matching the printed pattern to an ordered physical table -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Frame +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Coloring Assembly + +variable {F α A : Type} [Field F] {a b : Wire} {u : ℕ} {G : Bundled F a b} + {U : Engine F A} {r : U.scheme.format.obj} {N : Names G A U.d} {p : Order.Script G α} + (H : Frame U r N p u) + +open Classical in +private def applyBits (q : Pattern F U.d 0 U.e) (j : B 0) (f : B U.e → ℕ → Bool) := + q.value j (fun s i => f s i.val) + +open Classical in +private def tape (z : U.scheme.Pin r → Bool) (v : G.V) (s : B U.e) (k : ℕ) := + if h : k < U.scheme.width r (H.vertex v, s) then z ⟨(H.vertex v, s), ⟨k, h⟩⟩ else false + +open Classical in +private theorem table_output (z : U.scheme.Pin r → Bool) (v : G.V) : + U.scheme.table r (H.vertex v) (z ∘ U.scheme.port r (H.vertex v)) = + (N.star p v).output U.ix u (H.tape z v) := by + have h : U.scheme.table r (H.vertex v) (z ∘ U.scheme.port r (H.vertex v)) = + applyBits (U := U) (U.scheme.pattern r (H.vertex v)) (H.vertex v).2.2 (H.tape z v) := by + unfold Scheme.table applyBits + congr 1 + funext s i + unfold tape + rw [dite_eq_left (show i.val < U.scheme.width r (H.vertex v, s) from i.isLt)] + rfl + rw [h, H.active] + simp only [applyBits, Star.pattern] + apply congrArg ((N.star p v).output U.ix u) + funext s i + have he : U.scheme.width r (H.vertex v, s) = ((N.star p v).desc U.ix u s).1 := by + unfold Scheme.width; rw [H.active]; rfl + unfold tape + split_ifs <;> first | rfl | omega + +open Classical in +theorem left (v : G.V) (j : Fin (p.left.ports v).length) : + H.ends (.inl (.inl (p.left.enum.get v j))) = H.outer v false j := + H.at_end ⟨false, .inl ⟨v, j⟩⟩ + +open Classical in +theorem right (v : G.V) (j : Fin (p.right.ports v).length) : + H.ends (.inr (.inl (p.right.enum.get v j))) = H.outer v true j := + H.at_end ⟨true, .inl ⟨v, j⟩⟩ + +open Classical in +theorem lbit (t : G.Bit) : H.ends (.inl (.inr t)) = H.inner false t.1 t.2 := + H.at_end ⟨false, .inr t⟩ + +open Classical in +theorem rbit (t : G.Bit) : H.ends (.inr (.inr t)) = H.inner true t.1 t.2 := + H.at_end ⟨true, .inr t⟩ + +open Classical in +private theorem read_out (z : U.scheme.Pin r → Bool) (v : G.V) (s : Bool) : + (List.ofFn fun i : Fin ((N.star p v).ext s) => H.tape z v (U.ix (s, none)) i) = + List.ofFn (fun i => z (H.outer v s i)) := by + apply congrArg List.ofFn + funext i + rw [tape, dite_eq_left (show i.val < U.scheme.width r (H.exterior v s) by + rw [(H.exterior_info v s).1]; exact i.isLt)] + rfl + +open Classical in +private def contents (z : U.scheme.Pin r → Bool) (v : G.V) := + (N.star p v).body U.ix u (H.tape z v) + +open Classical in +private theorem contents_at (z : U.scheme.Pin r → Bool) (s : Bool) (e : G.E) : + H.contents z (side G s e) s (N.lane e) = List.ofFn (fun i => z (H.inner s e i)) := by + unfold contents Star.body + rw [N.link_at] + apply congrArg List.ofFn + funext i + rw [dite_eq_left ((H.unit_lt e i).trans_le (H.bound e))] + change H.tape z _ (H.unit s e (H.unitIndex e i)).2 _ = _ + have hj := (H.inner s e i).2.isLt + unfold tape + split_ifs with hh + swap + · exact (hh hj).elim + rfl + +open Classical in +private theorem local_congr (s : Order.Script G α) (v : G.V) (x y : List Bool) (f g : G.E → Option + α) + (h : ∀ e, G.src e = v ∨ G.dst e = v → f e = g e) : + s.localValue v x y f = s.localValue v x y g := by + have hc : (∀ e, G.src e = v → f e ≠ none) ↔ ∀ e, G.src e = v → g e ≠ none := + forall₂_congr fun e he => by rw [h e (.inl he)] + have hr : (∀ e ∈ s.reads v, f e ≠ none) ↔ ∀ e ∈ s.reads v, g e ≠ none := + forall₂_congr fun e he => by rw [h e (s.incident _ _ he)] + have hv : (s.reads v).filterMap f = (s.reads v).filterMap g := + List.filterMap_congr fun e he => h e (s.incident _ _ he) + simp only [Order.Script.localValue, hc, hr, hv] + +open Classical in +theorem value (z : U.scheme.Pin r → Bool) (v : G.V) : + U.scheme.table r (H.vertex v) (z ∘ U.scheme.port r (H.vertex v)) = + p.drawing.diagram.weight v ((z ∘ H.ends) ∘ .inl) ((z ∘ H.ends) ∘ .inr) := by + rw [H.table_output, p.weight_eq] + unfold Star.output + simp only [H.read_out] + have hl : List.ofFn (fun i => z (H.outer v false i)) = + (p.left.ports v).map (fun i => z (H.ends (.inl (.inl i)))) := by + rw [← p.left.values] + exact congrArg List.ofFn (funext fun i => congrArg z (H.left v i).symm) + have hr : List.ofFn (fun i => z (H.outer v true i)) = + (p.right.ports v).map (fun i => z (H.ends (.inr (.inl i)))) := by + rw [← p.right.values] + exact congrArg List.ofFn (funext fun i => congrArg z (H.right v i).symm) + rw [hl, hr] + apply local_congr + intro e he + change p.signal e (H.contents z v (decide (G.src e ≠ v)) (N.lane e)) = _ + by_cases h : G.src e = v + · subst v + have hh := H.contents_at z false e + change H.contents z (G.src e) false _ = _ at hh + simp only [Order.Script.token, ne_eq, not_true_eq_false, decide_false, ite_true, hh, + Function.comp_apply, H.lbit] + · have hv := he.resolve_left h + subst v + have hh := H.contents_at z true e + change H.contents z (G.dst e) true _ = _ at hh + simp only [Order.Script.token, ne_eq, h, not_false_eq_true, decide_true, ite_false, hh, + Function.comp_apply, H.rbit] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Frame +end + +/- # Capacity and energy bounds for indexed station tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input.FinalBounds +open Sphere SphereScale Surface +open Sphere.Layout (Alphabet Key Sharing Place) + +variable {F Z X : Type} [Field F] {x y : Wire} {h D T b d g M r t σ j : ℕ} {W : ℝ} + {P : Input F x y h D T (d * b) g W} {Y : Alphabet P.Occupied} + {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} {Q : Key.Source Y x y s} + (bound : P.FinalBounds Q σ j) (sc : Scales g σ D T j b d) + +omit [Field F] in +include bound sc in +open scoped Classical in +theorem shape_bound (i : Print.ShapeID s.scene.cell) : Print.cost s.scene.cell s.scene.level i ≤ + depth σ D g j (d * b) := by + rcases i with ((i|i)|i) + · exact (bound.seamEnergy i).trans (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ sc.pos)) + · exact ((Nat.le_mul_of_pos_left _ sc.pos).trans (Nat.le_add_right _ _)).trans (bound.energy i) + · exact (Nat.le_add_left _ _).trans (bound.energy i) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input.FinalBounds + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo +open Rounds +variable {F U X E V K : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k σ j B m : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + {G : S.Geo P k} {e : E → ℕ} {thin : Place C → Prop} {selector : K → Prop} + [Fintype E] [Fintype V] [Fintype K] + +omit [Fintype K] in +open Classical in +theorem Raw.with_steer (hr : G.Raw σ j B m e thin selector) (s : Steering P.adj (D ^ k)) : + ({G with steer := s} : S.Geo P k).Raw σ j B m e thin selector := + ⟨hr.occupied, hr.seams, hr.seamEnergy, hr.energy, hr.collected, hr.collectors, hr.exterior, + hr.square, + hr.light, hr.heavy, hr.auxiliary, hr.residue, hr.keys, hr.keyWidth, hr.selectorWidth, hr.reads⟩ + +variable [Field F] {n u A : ℕ} (hD : D = 2 ^ n) (hd : 4 ≤ D) (hu : 0 < u) + (p : Profile C e) (hs : Concentrated P (G.output hD hd p j hu) A n σ) + +include hs in +open Classical in +theorem capacity (hA : 1 ≤ A) {cap : ℕ} (hc : A * D * T + ≤ u * cap) (i : (S.backdrop.emitted p j).E) : + Diagram.padWidth u ((S.backdrop.emitted p j).width i) / u ≤ cap := by + let H := G.layout hD hd p j + let B := S.backdrop.emitted p j + have he := H.arity_max (G.external hD hd p j) hu hs (by omega) hA (.inl (B.src i)) + have h₁ := Fanout.source_arity (B.pad u) i + have h₂ := Routes.old_arity (H.pad u).route (B.src i) + have hw : Diagram.padWidth u (B.width i) ≤ u * cap := h₁.trans (h₂.ge.trans (he.trans hc)) + exact (Nat.div_le_div_right hw).trans_eq (Nat.mul_div_cancel_left _ hu) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout.Sharing.Geo +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Pins.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Pins.lean new file mode 100644 index 0000000000..26ce5a1a6b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Pins.lean @@ -0,0 +1,1108 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Pull +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Choices +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.Hub +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Seating + +/-! +# One selector word per global profile + +Each independent shape is written once. Its coordinates sum to the +specified energy. Empty seats have energy zero, which forces zero padding. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Finset Transcript Coloring + +open Classical in +/-- The indexing data represented by `Fin M → B z`. -/ +abbrev Digits (M z : ℕ) := Fin M → B z + +open Classical in +/-- The sum of `(p i).val` indexed by `i`. -/ +def tally {M z : ℕ} (p : Digits M z) := ∑ i, (p i).val + +namespace Pick +variable {M z : ℕ} {J X : Type} (seat : J ↪ X) (cost : J → ℕ) + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def target := Function.extend seat cost (fun _ => 0) + +open Classical in +/-- The condition `∀ x, tally (p x) = target seat cost x` on the specified data. -/ +def accepts (p : X → Digits M z) := ∀ x, tally (p x) = target seat cost x + +variable (h : ∀ i, cost i < 2 ^ z) + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def write (w : Layout.Shapes M cost) : X → Digits M z := + Function.extend seat (fun i j => ⟨((w i).val j).val, + (Nat.le_of_lt_succ ((w i).val j).isLt).trans_lt (h i)⟩) (fun _ _ => 0) + +open Classical in +theorem write_at (w : Layout.Shapes M cost) (i : J) (j : Fin M) : + (write seat cost h w (seat i) j).val = ((w i).val j).val := by + unfold write + rw [seat.injective.extend_apply] + +open Classical in +theorem accepts_write (w : Layout.Shapes M cost) : accepts seat cost (write seat cost h w) := by + intro x + by_cases hx : ∃ j, seat j = x + · obtain ⟨j, rfl⟩ := hx + unfold target tally + rw [seat.injective.extend_apply] + simp only [write_at] + exact (w j).property + · simp [write, target, Function.extend, hx, tally] + +open Classical in +/-- The read of type `Layout.Shapes M cost` for the given inputs. -/ +def read (p : X → Digits M z) (hp : accepts seat cost p) : Layout.Shapes M cost := + fun i => + have he : tally (p (seat i)) = cost i := (hp _).trans (seat.injective.extend_apply _ _ i) + ⟨fun j => ⟨(p (seat i) j).val, Nat.lt_succ_of_le ((single_le_sum + (fun k _ => Nat.zero_le (p (seat i) k).val) (mem_univ j)).trans_eq he)⟩, he⟩ + +open Classical in +theorem write_read (p : X → Digits M z) (hp : accepts seat cost p) : + write seat cost h (read seat cost p hp) = p := by + funext x j + by_cases hx : ∃ k, seat k = x + · obtain ⟨k, rfl⟩ := hx + exact Fin.ext (write_at _ _ _ _ _ _) + · have he : tally (p x) = 0 := (hp _).trans (Function.extend_apply' _ _ _ hx) + have hj : (p x j).val ≤ tally (p x) := single_le_sum (fun i _ + => Nat.zero_le (p x i).val) (mem_univ j) + have hz : p x j = 0 := Fin.ext (by change (p x j).val = 0; omega) + simp [write, Function.extend, hx, hz] + +open Classical in +/-- Builds `Selector (Layout.Shapes M cost) (X → Digits M z) where write` with the specified +`write`, `read`, `valid`. -/ +def selector : Selector (Layout.Shapes M cost) (X → Digits M z) where + write := write seat cost h + read p := if hp : accepts seat cost p then some (read seat cost p hp) else none + valid p w := by + constructor + · split_ifs with hp + · intro e; rw [← Option.some.inj e, write_read] + · simp + · rintro rfl + rw [dite_eq_left (accepts_write _ _ _ _), Option.some.injEq] + funext i + apply Subtype.ext + funext j + exact Fin.ext (write_at _ _ _ _ _ _) + +end Pick +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Reading station data without ambient wire names + +Operand order determines the raw argument list. The bundle numbering +internal to the diagram need not be observed by a local processor. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order.Script +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Transcript Finset + +variable {F α : Type} [Field F] {a b : Wire} {G : Bundled F a b} + (p : Script G α) (v : G.V) + +open Classical in +/-- Returns `p.program v x y ((p.reads v).filterMap f)` when `(∀ e, G.src e = v → f e ≠ none) ∧ +(∀ e ∈ p.reads v, f e ≠ none)` holds, and `0` otherwise. -/ +def localValue (x y : List Bool) (f : G.E → Option α) : F := + if (∀ e, G.src e = v → f e ≠ none) ∧ (∀ e ∈ p.reads v, f e ≠ none) then + p.program v x y ((p.reads v).filterMap f) else 0 + +open Classical in +theorem recipe_eq (x y : View) (f : G.E → Option α) + (h : ∀ e, G.src e = v ∨ G.dst e = v → (p.call v e).read x y = f e) : + p.drawing.recipe v x y = p.localValue v x.1 y.1 f := by + let q := p.call v + have ag (es : List G.E) (he : ∀ e ∈ es, G.src e = v ∨ G.dst e = v) : + (∀ c ∈ es.map q, c.read x y ≠ none) ↔ ∀ e ∈ es, f e ≠ none := by + rw [List.forall_mem_map] + exact forall₂_congr fun e hi => by rw [h e (he _ hi)] + have he : ((p.reads v).map q).filterMap (fun c => c.read x y) = (p.reads v).filterMap f := by + rw [List.filterMap_map] + exact List.filterMap_congr fun i hi => h i (p.incident _ _ hi) + change render _ _ _ x y = _ + unfold render localValue + have hc := ag (checks v) (fun i hi => .inl (mem_filter.mp (mem_toList.mp hi)).2) + have hr := ag _ (p.incident v) + unfold q at hc hr he + simp only [List.forall_mem_append, hc, hr, he] + simp only [checks, mem_toList, mem_filter, mem_univ, true_and] + +open Classical in +/-- The value specified by `p.signal e (List.ofFn (fun i => if G.src e = v then w (.inl (.inr +⟨e, i⟩)) else w (.inr (.inr ⟨e, i⟩))))`. -/ +def token (w : p.drawing.diagram.End → Bool) (e : G.E) := + p.signal e (List.ofFn (fun i => if G.src e = v then w (.inl (.inr ⟨e, i⟩)) + else w (.inr (.inr ⟨e, i⟩)))) + +open Classical in +theorem weight_eq (w : p.drawing.diagram.End → Bool) : + p.drawing.diagram.weight v (w ∘ .inl) (w ∘ .inr) = + p.localValue v ((p.left.ports v).map fun i => w (.inl (.inl i))) + ((p.right.ports v).map fun i => w (.inr (.inl i))) (p.token v w) := by + let l₀ := fun i => w (.inl (.inl i)) + let r₀ := fun i => w (.inr (.inl i)) + let l₁ := fun i => w (.inl (.inr i)) + let r₁ := fun i => w (.inr (.inr i)) + let l := p.source.view G.width v l₀ l₁ + let r := p.target.view G.width v r₀ r₁ + have hl : w ∘ Sum.inl = Sum.elim l₀ l₁ := funext fun i => by cases i <;> rfl + have hr : w ∘ Sum.inr = Sum.elim r₀ r₁ := funext fun i => by cases i <;> rfl + have he (e : G.E) (he : G.src e = v ∨ G.dst e = v) : + (p.call v e).read l r = p.token v w e := by + unfold l r token + by_cases h : G.src e = v + · subst v + simp only [call, ite_true, Call.read, Bool.false_eq_true, ite_false] + rw [read_side] + · have ht := he.resolve_left h + subst v + simp only [call, ite_eq_right h, Call.read, ite_true] + rw [read_side] + rw [hl, hr] + calc + _ = p.drawing.recipe v l r := congrArg₂ (p.drawing.recipe v) + (p.source.read G.width v l₀ l₁) (p.target.read G.width v r₀ r₁) + _ = p.localValue v l.1 r.1 (p.token v w) := p.recipe_eq v l r _ he + _ = _ := congrArg₂ (fun a b => p.localValue v a b _) (p.left.values v l₀) (p.right.values v r₀) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order.Script +end + +/- # Printing the star of a labeled network -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Coloring + +variable {F α A : Type} {a b : Wire} {d : ℕ} + +open Classical in +/-- Computes the side by the application `cond s G.dst G.src`. -/ +def side (G : Bundled F a b) (s : Bool) : G.E → G.V := cond s G.dst G.src + +open Classical in +/-- The data for the names construction, including `lane`, `unique`, `near`. -/ +structure Names (G : Bundled F a b) (A : Type) (d : ℕ) where + /-- The `Names` component of type `G.E → A`. -/ + lane : G.E → A + unique : ∀ s i j, side G s i = side G s j → lane i = lane j → i = j + /-- The `Names` component of type `G.V → G.V → B d`. -/ + near : G.V → G.V → B d + +namespace Names +variable {G : Bundled F a b} (N : Names G A d) + +open Classical in +/-- Returns `some h.choose` when `h : ∃ i, side G s i = v ∧ N.lane i = k` holds, and `none` +otherwise. -/ +def resident (v : G.V) (s : Bool) (k : A) : Option G.E := + if h : ∃ i, side G s i = v ∧ N.lane i = k then some h.choose else none + +open Classical in +theorem resident_at (s : Bool) (i : G.E) : + N.resident (side G s i) s (N.lane i) = some i := by + have h : ∃ j, side G s j = side G s i ∧ N.lane j = N.lane i := ⟨i, rfl, rfl⟩ + rw [resident, dite_eq_left h, N.unique s _ _ h.choose_spec.1 h.choose_spec.2] + +open Classical in +theorem resident_spec {v : G.V} {s : Bool} {k : A} {i : G.E} + (he : N.resident v s k = some i) : side G s i = v ∧ N.lane i = k := by + unfold resident at he + split_ifs at he with h + exact (Option.some.inj he) ▸ h.choose_spec + +open Classical in +/-- The value specified by `N.near (side G s i) (side G (!s) i)`. -/ +def target (s : Bool) (i : G.E) := N.near (side G s i) (side G (!s) i) + +variable [Field F] (p : Order.Script G α) + +open Classical in +/-- Computes the ext size by the application `cond s (p.right.ports v).length (p.left.ports +v).length`. -/ +def extSize (v : G.V) (s : Bool) := cond s (p.right.ports v).length (p.left.ports v).length + +open Classical in +/-- Builds `Star F A d where ext` with the specified `ext`, `link`, `value`. -/ +def star (v : G.V) : Star F A d where + ext := extSize p v + link s k := (N.resident v s k).map (fun i => (N.target s i, G.width i)) + value x y r := p.localValue v x y (fun e => p.signal e (r (decide (G.src e ≠ v)) (N.lane e))) + +open Classical in +theorem link_at (s : Bool) (i : G.E) : + (N.star p (side G s i)).link s (N.lane i) = some (N.target s i, G.width i) := by + simp only [star, N.resident_at, Option.map_some] + +open Classical in +theorem link_spec {v s k w n} (h : (N.star p v).link s k = some (w, n)) : + ∃ i, side G s i = v ∧ N.lane i = k ∧ N.target s i = w ∧ G.width i = n := by + obtain ⟨i, hi, he⟩ := Option.map_eq_some_iff.mp h + exact ⟨i, (N.resident_spec hi).1, (N.resident_spec hi).2, Prod.mk.inj he⟩ + +end Names +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Uniform-width span metadata of the printed occurrence records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Coloring Assembly + +open Classical in +/-- The data for the engine construction, including `m`, `d`, `h`, `e`, `ℓ`. -/ +structure Engine (F A : Type) where + /-- The `Engine` field of type `ℕ`. -/ + m : ℕ + /-- The `Engine` field of type `ℕ`. -/ + d : ℕ + /-- The `Engine` field of type `ℕ`. -/ + h : ℕ + /-- The `Engine` field of type `ℕ`. -/ + e : ℕ + /-- The `Engine` field of type `ℕ`. -/ + ℓ : ℕ + /-- The capacity bound. -/ + cap : ℕ + /-- Embeds the coordinates as `Band A cap ↪ B e`. -/ + ix : Band A cap ↪ B e + /-- The `Engine` component of type `B ℓ → Pattern F d 0 e`. -/ + decode : B ℓ → Pattern F d 0 e + +variable {F α A : Type} [Field F] {a b : Wire} {u : ℕ} {G : Bundled F a b} + +open Classical in +/-- Uses `⟨U.m, U.d, U.h, 0, U.e, U.ℓ, U.decode⟩` as the representation. -/ +abbrev Engine.scheme (U : Engine F A) : Scheme F := + ⟨U.m, U.d, U.h, 0, U.e, U.ℓ, U.decode⟩ + +open Classical in +/-- A single host slot per occurrence and a shared navigation table. -/ +structure Frame (U : Engine F A) (r : U.scheme.format.obj) (N : Names G A U.d) + (p : Order.Script G α) (u : ℕ) where + /-- The placement of the vertices carried by `Frame`, with type `G.V ↪ U.scheme.Vtx`. -/ + vertex : G.V ↪ U.scheme.Vtx + pos : 0 < u + width : ∀ i, u ∣ G.width i + bound : ∀ i, G.width i / u ≤ U.cap + active : ∀ v, U.scheme.pattern r (vertex v) = (N.star p v).pattern U.ix u + inactive : ∀ v ∉ Set.range vertex, U.scheme.pattern r v = Star.vacant + address : ∀ s i, let v := vertex (side G s i) + ((r v.1).1 (N.target s i), v.2.1, (0 : B 0)) = vertex (side G (!s) i) + +namespace Frame + +variable {U : Engine F A} {r : U.scheme.format.obj} {N : Names G A U.d} {p : Order.Script G α} + (H : Frame U r N p u) + +open Classical in +/-- The value specified by `(H.vertex v, U.ix (s, none))`. -/ +abbrev exterior (v : G.V) (s : Bool) : U.scheme.Span := (H.vertex v, U.ix (s, none)) +open Classical in +/-- The value specified by `(H.vertex (side G s i), U.ix (s, some (N.lane i, j)))`. -/ +abbrev unit (s : Bool) (i : G.E) (j : Fin U.cap) : U.scheme.Span := + (H.vertex (side G s i), U.ix (s, some (N.lane i, j))) + +open Classical in +theorem exterior_info (v : G.V) (s : Bool) : + U.scheme.width r (H.exterior v s) = Names.extSize p v s ∧ + U.scheme.direction r (H.exterior v s) = s ∧ U.scheme.peer r (H.exterior v s) = none := by + simp only [Scheme.width, Scheme.direction, Scheme.peer, H.active, Star.pattern, Star.desc_ext, + Option.map_none, and_true] + rfl + +open Classical in +theorem unit_info (s : Bool) (i : G.E) (j : Fin U.cap) (hj : j.val < G.width i / u) : + U.scheme.width r (H.unit s i j) = u ∧ U.scheme.direction r (H.unit s i j) = s ∧ + U.scheme.peer r (H.unit s i j) = some (H.unit (!s) i j) := by + have h := Star.desc_link _ U.ix u (N.link_at p s i) j hj + simp only [Scheme.width, Scheme.direction, Scheme.peer, H.active, Star.pattern, h, + true_and, Option.map_some, H.address] + +open Classical in +theorem unit_local (s : Bool) (i : G.E) (j : Fin U.cap) (hj : j.val < G.width i / u) : + (U.scheme.pattern r (H.vertex (side G s i))).peer 0 (H.unit s i j).2 = + some (N.target s i, 0, (H.unit (!s) i j).2) := by + rw [H.active] + exact congrArg (fun a => a.2.2) (Star.desc_link _ U.ix u (N.link_at p s i) j hj) + +open Classical in +theorem classify (q : U.scheme.Span) + (h : 0 < U.scheme.width r q ∨ U.scheme.peer r q ≠ none) : + (∃ v s, q = H.exterior v s) ∨ ∃ s i j, j.val < G.width i / u ∧ q = H.unit s i j := by + obtain ⟨v, q⟩ := q + by_cases hv : v ∈ Set.range H.vertex + swap + · simp [Scheme.width, Scheme.peer, H.inactive v hv, Star.vacant] at h + obtain ⟨v, rfl⟩ := hv + have hh : 0 < ((N.star p v).desc U.ix u q).1 ∨ ((N.star p v).desc U.ix u q).2.2 ≠ none := by + simpa only [Scheme.width, Scheme.peer, H.active, Star.pattern, ne_eq, Option.map_eq_none_iff] + using h + rcases Star.active _ _ _ hh with ⟨s, rfl⟩|⟨s, l, j, k, w, rfl, he, hj⟩ + · exact .inl ⟨v, s, rfl⟩ + · obtain ⟨i, rfl, rfl, _, rfl⟩ := N.link_spec p he + exact .inr ⟨s, i, j, hj, rfl⟩ + +open Classical in +theorem peer_spec (a b : U.scheme.Span) (h : U.scheme.peer r a = some b) : + ∃ s i j, j.val < G.width i / u ∧ a = H.unit s i j ∧ b = H.unit (!s) i j := by + rcases H.classify a (.inr (by rw [h]; simp)) with ⟨v, s, rfl⟩ | ⟨s, i, j, hj, rfl⟩ + · rw [(H.exterior_info v s).2.2] at h; cases h + · exact ⟨s, i, j, hj, rfl, Option.some.inj (h.symm.trans (H.unit_info s i j hj).2.2)⟩ + +include H in +open Classical in +theorem proper : U.scheme.Proper r := by + intro a b h + obtain ⟨s, i, j, hj, rfl, rfl⟩ := H.peer_spec a b h + obtain ⟨h₁, h₂, _⟩ := H.unit_info s i j hj + obtain ⟨h₃, h₄, h₅⟩ := H.unit_info (!s) i j hj + refine ⟨by simpa using h₅, h₁.trans h₃.symm, ?_⟩ + rw [h₂, h₄] + cases s <;> decide + +end Frame +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Ordered physical bit offsets in unit spans -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Frame +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Coloring Assembly + +variable {F α A : Type} [Field F] {a b : Wire} {u : ℕ} {G : Bundled F a b} + {U : Engine F A} {r : U.scheme.format.obj} {N : Names G A U.d} {p : Order.Script G α} + (H : Frame U r N p u) + +open Classical in +/-- Indexes the side pin by the coordinates of `(Σ v, Fin (Names.extSize p v s)) ⊕ G.Bit`. -/ +abbrev SidePin (p : Order.Script G α) (s : Bool) := (Σ v, Fin (Names.extSize p v s)) ⊕ G.Bit +open Classical in +/-- Indexes the source pin by the coordinates of `Σ s : Bool, SidePin p s`. -/ +abbrev SourcePin (p : Order.Script G α) := Σ s : Bool, SidePin p s + +open Classical in +/-- In the case `⟨false, x⟩`, this construction gives `.inl x`. -/ +def boolIndex (X : Bool → Type) : (Σ s, X s) ≃ X false ⊕ X true where + toFun + | ⟨false, x⟩ => .inl x + | ⟨true, x⟩ => .inr x + invFun + | .inl x => ⟨false, x⟩ + | .inr x => ⟨true, x⟩ + left_inv := by rintro ⟨_|_, _⟩ <;> rfl + right_inv := by rintro (_|_) <;> rfl + +open Classical in +/-- Reindexes `SourcePin p` and `p.drawing.diagram.End` by an equivalence. -/ +def toEnds (p : Order.Script G α) : SourcePin p ≃ p.drawing.diagram.End := + (boolIndex (SidePin p)).trans ((p.left.enum.full.sumCongr (.refl _)).sumCongr + (p.right.enum.full.sumCongr (.refl _))) + +include H in +open Classical in +theorem unit_lt (e : G.E) (j : Fin (G.width e)) : j.val / u < G.width e / u := by + apply (Nat.div_lt_iff_lt_mul H.pos).mpr + rw [Nat.div_mul_cancel (H.width e)] + exact j.isLt + +open Classical in +/-- The quantity computed by `⟨j.val / u, (H.unit_lt e j).trans_le (H.bound e)⟩`. -/ +def unitIndex (e : G.E) (j : Fin (G.width e)) : Fin U.cap := + ⟨j.val / u, (H.unit_lt e j).trans_le (H.bound e)⟩ + +open Classical in +/-- Uses `⟨H.exterior v s, ⟨j.val, by rw [(H.exterior_info v s).1]; exact j.isLt⟩⟩` as the +representation. -/ +def outer (v : G.V) (s : Bool) (j : Fin (Names.extSize p v s)) : U.scheme.Pin r := + ⟨H.exterior v s, ⟨j.val, by rw [(H.exterior_info v s).1]; exact j.isLt⟩⟩ + +open Classical in +/-- The inner of type `U.scheme.Pin r` for the given inputs. -/ +def inner (s : Bool) (e : G.E) (j : Fin (G.width e)) : U.scheme.Pin r := + ⟨H.unit s e (H.unitIndex e j), ⟨j.val % u, by + rw [(H.unit_info s e (H.unitIndex e j) (H.unit_lt e j)).1] + exact Nat.mod_lt _ H.pos⟩⟩ + +open Classical in +/-- In the case `⟨s, .inl ⟨v, j⟩⟩`, this construction gives `H.outer v s j`. -/ +def put : SourcePin p → U.scheme.Pin r + | ⟨s, .inl ⟨v, j⟩⟩ => H.outer v s j + | ⟨s, .inr ⟨e, j⟩⟩ => H.inner s e j + +open Classical in +theorem put_dir (q : SourcePin p) : U.scheme.direction r (H.put q).1 = q.1 := by + rcases q with ⟨s, ⟨v, j⟩ | ⟨e, j⟩⟩ + · exact (H.exterior_info v s).2.1 + · exact (H.unit_info s e _ (H.unit_lt e j)).2.1 + +open Classical in +theorem injective : Function.Injective H.put := by + rintro ⟨s, i⟩ ⟨t, j⟩ h + have ht : s = t := (H.put_dir ⟨s, i⟩).symm.trans (h ▸ H.put_dir ⟨t, j⟩) + subst t + have hv := congrArg (fun p => p.1.1) h + have hk := congrArg (fun p => p.1.2) h + have ho := congrArg (fun p => p.2.val) h + rcases i with ⟨v, i⟩|⟨e, i⟩ <;> rcases j with ⟨w, j⟩|⟨f, j⟩ + · have he : v = w := H.vertex.injective hv + subst w + have hi : i = j := Fin.ext ho + rw [hi] + · cases U.ix.injective hk + · cases U.ix.injective hk + · have hkey := Prod.mk.inj (Option.some.inj (Prod.mk.inj (U.ix.injective hk)).2) + have he : e = f := N.unique s _ _ (H.vertex.injective hv) hkey.1 + subst f + have hdiv : i.val / u = j.val / u := congrArg Fin.val hkey.2 + change i.val % u = j.val % u at ho + have hij : i = j := Fin.ext (by + rw [← Nat.mod_add_div i.val u, ho, hdiv, Nat.mod_add_div]) + rw [hij] + +omit [Field F] in +open Classical in +private theorem pin_ext {x y : U.scheme.Pin r} (h : x.1 = y.1) (hv : x.2.val = y.2.val) : x = y := + Sigma.ext h ((Fin.heq_ext_iff (congrArg (U.scheme.width r) h)).mpr hv) + +open Classical in +theorem surjective : Function.Surjective H.put := by + rintro ⟨q, j⟩ + rcases H.classify q (.inl (Nat.zero_lt_of_lt j.isLt)) with ⟨v, s, rfl⟩|⟨s, e, i, hi, rfl⟩ + · let k : Fin (Names.extSize p v s) := ⟨j.val, lt_of_lt_of_eq j.isLt (H.exterior_info v s).1⟩ + exact ⟨⟨s, .inl ⟨v, k⟩⟩, pin_ext rfl rfl⟩ + · have hj : j.val < u := lt_of_lt_of_eq j.isLt (H.unit_info s e i hi).1 + let k : Fin (G.width e) := ⟨u * i.val + j.val, by + have h := Nat.mul_le_mul_right u hi + rw [Nat.div_mul_cancel (H.width e), Nat.succ_mul, mul_comm i.val] at h + omega⟩ + have hk : H.unitIndex e k = i := Fin.ext (by + change (u * i.val + j.val) / u = i.val + rw [Nat.mul_add_div H.pos, Nat.div_eq_of_lt hj, add_zero]) + refine ⟨⟨s, .inr ⟨e, k⟩⟩, pin_ext (congrArg (H.unit s e) hk) ?_⟩ + change (u * i.val + j.val) % u = j.val + rw [Nat.mul_add_mod, Nat.mod_eq_of_lt hj] + +open Classical in +/-- Reindexes `p.drawing.diagram.End` and `U.scheme.Pin r` by an equivalence. -/ +def ends : p.drawing.diagram.End ≃ U.scheme.Pin r := + (toEnds p).symm.trans (Equiv.ofBijective _ ⟨H.injective, H.surjective⟩) + +open Classical in +theorem at_end (q : SourcePin p) : H.ends (toEnds p q) = H.put q := by + rw [ends, Equiv.trans_apply, Equiv.symm_apply_apply] + rfl + +open Classical in +theorem directed_end (q : p.drawing.diagram.End) : U.scheme.direction r (H.ends q).1 = q.isRight + := by + obtain ⟨⟨s, v⟩, rfl⟩ := (toEnds p).surjective q + rw [H.at_end, H.put_dir] + cases s <;> rfl + +open Classical in +theorem owner (q : p.drawing.diagram.End) : (H.ends q).1.1 = H.vertex (p.drawing.diagram.station q) + := by + obtain ⟨⟨s, q⟩, rfl⟩ := (toEnds p).surjective q + rw [H.at_end] + rcases q with ⟨v, j⟩|⟨e, j⟩ + · cases s + · exact congrArg H.vertex ((p.source.owner G.width (.inl (p.left.enum.get v j))).trans + (p.left.enum.owner v j)).symm + · exact congrArg H.vertex ((p.target.owner G.width (.inl (p.right.enum.get v j))).trans + (p.right.enum.owner v j)).symm + · cases s + · exact congrArg H.vertex (p.drawing.source ⟨e, j⟩).symm + · exact congrArg H.vertex (p.drawing.target ⟨e, j⟩).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Frame +end + +/- +# Intrinsic operand programs + +Ordinary operations observe a list in order. Equality tests observe +only the set of compared pairs, even on invalid codes. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order + +open Classical in +/-- The indexing data represented by `List Bool → List Bool → (A → Option α) → F`. -/ +abbrev Policy (F α A : Type) := List Bool → List Bool → (A → Option α) → F +variable {F α A B : Type} [Field F] + +open Classical in +/-- Evaluates `if ∀ i ∈ xs, f i ≠ none then p x y (xs.filterMap f) else 0` at the input `x y f`. -/ +def operation (p : Program F α) (xs : List A) : Policy F α A := + fun x y f => if ∀ i ∈ xs, f i ≠ none then p x y (xs.filterMap f) else 0 + +open Classical in +/-- Evaluates `if ∀ i ∈ s, f i.1 ≠ none ∧ f i.1 = f i.2 then 1 else 0` at the input `_ _ f`. -/ +def tests (s : Set (A × A)) : Policy F α A := + fun _ _ f => if ∀ i ∈ s, f i.1 ≠ none ∧ f i.1 = f i.2 then 1 else 0 + +open Classical in +theorem operation_reindex (p : Program F α) (xs : List A) (g : A → B) (f : B → Option α) + (x y : List Bool) : + operation p (xs.map g) x y f = operation p xs x y (f ∘ g) := by + simp only [operation, List.forall_mem_map, List.filterMap_map, Function.comp_apply] + +open Classical in +theorem operation_congr (p : Program F α) (xs : List A) (x y : List Bool) + (f g : A → Option α) (h : ∀ i ∈ xs, f i = g i) : + operation p xs x y f = operation p xs x y g := by + have ht : (∀ i ∈ xs, f i ≠ none) ↔ ∀ i ∈ xs, g i ≠ none := + forall₂_congr fun i hi => by rw [h i hi] + simp only [operation, ht, List.filterMap_congr h] + +open Classical in +private theorem test_cons (a b : α) (l : List α) (x y : List Bool) : + checkPairs x y (a :: b :: l) = if a = b then checkPairs (F := F) x y l else 0 := by + by_cases h : a = b <;> simp [checkPairs, equalPairs, h] + +open Classical in +private theorem op_cons (a b : A) (l : List A) (x y : List Bool) (f : A → Option α) : + operation checkPairs (a :: b :: l) x y f = + if f a ≠ none ∧ f a = f b then operation (F := F) checkPairs l x y f else 0 := by + unfold operation + simp only [List.forall_mem_cons, List.filterMap_cons] + cases f a <;> cases f b <;> simp [test_cons] + split_ifs <;> simp_all + +open Classical in +theorem operation_pairs (l : List (A × A)) : + operation (F := F) (α := α) checkPairs (pairs l) = tests {i | i ∈ l} := by + funext x y f + induction l with + | nil => simp [pairs, operation, tests, checkPairs, equalPairs] + | cons p l ih => + change operation checkPairs (p.1 :: p.2 :: pairs l) x y f = _ + rw [op_cons, ih] + simp only [tests, Set.mem_ofPred_eq, List.forall_mem_cons, ite_and] + congr! + +open Classical in +theorem reindex_pairs (l : List (A × A)) (id : A → B) : + operation (F := F) (α := α) checkPairs ((pairs l).map id) = + tests {i | ∃ j ∈ l, Prod.map id id j = i} := by + have h : (pairs l).map id = pairs (l.map (Prod.map id id)) := by + induction l with + | nil => rfl + | cons a l ih => exact congrArg (fun xs => id a.1 :: id a.2 :: xs) ih + rw [h, operation_pairs] + simp only [List.mem_map] + +open Classical in +/-- Computes the policy by the application `operation (p.program v) ((p.reads v).map lane)`. -/ +def policy {a b : Wire} {G : Bundled F a b} (p : Script G α) (lane : G.E → A) (v : G.V) := + operation (p.program v) ((p.reads v).map lane) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Locality of a printed star + +The set of incident channels, their local endpoint names and the local +operand program determine the output. Absolute vertex and channel IDs +are absent from the arguments of `printStar`. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Coloring +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order + +open Classical in +/-- The data for the arc construction, including `key`, `side`, `width`, `decoder`. -/ +structure Arc (α A X : Type) where + /-- The `Arc` field of type `A`. -/ + key : A + /-- The `Arc` component of type `Bool → X`. -/ + side : Bool → X + /-- The width parameter carried by `Arc`, with type `ℕ`. -/ + width : ℕ + /-- The `Arc` component of type `Decoder α`. -/ + decoder : Decoder α + +variable {F α A X : Type} [Field F] {a b : Wire} {G : Bundled F a b} {d : ℕ} + +open Classical in +/-- Requires `G.src e = v ∨ G.dst e = v`. -/ +def touches (G : Bundled F a b) (v : G.V) (e : G.E) : Prop := G.src e = v ∨ G.dst e = v + +omit [Field F] in +open Classical in +theorem touches_side (G : Bundled F a b) (s : Bool) (e : G.E) : touches G (side G s e) e := by + cases s <;> simp [touches, side] + +open Classical in +/-- The condition `∀ v e f, touches G v e → touches G v f → lane e = lane f → e = f` on the +specified data. -/ +def Unique (G : Bundled F a b) (lane : G.E → A) := + ∀ v e f, touches G v e → touches G v f → lane e = lane f → e = f + +open Classical in +/-- Uses `⟨lane, fun s i j he => h _ i j (touches_side _ s i) (he ▸ touches_side _ s j), near⟩` +as the representation. -/ +def Unique.names (lane : G.E → A) (h : Unique G lane) (near : G.V → G.V → B d) : Names G A d := + ⟨lane, fun s i j he => h _ i j (touches_side _ s i) (he ▸ touches_side _ s j), near⟩ + +open Classical in +/-- Uses `⟨lane e, fun s => name (side G s e), G.width e, p.signal e⟩` as the representation. -/ +def arc (p : Script G α) (lane : G.E → A) (name : G.V → X) (e : G.E) : Arc α A X := + ⟨lane e, fun s => name (side G s e), G.width e, p.signal e⟩ + +open Classical in +/-- The value specified by `arc p lane name '' {e | touches G v e}`. -/ +def cloud (p : Script G α) (lane : G.E → A) (name : G.V → X) (v : G.V) := + arc p lane name '' {e | touches G v e} + +open Classical in +/-- Returns `some h.choose` when `h : ∃ c ∈ s, c.key = k` holds, and `none` otherwise. -/ +def lookup (s : Set (Arc α A X)) (k : A) := + if h : ∃ c ∈ s, c.key = k then some h.choose else none + +open Classical in +theorem lookup_at {s : Set (Arc α A X)} (h : Set.InjOn Arc.key s) {c : Arc α A X} (hc : c ∈ s) : + lookup s c.key = some c := by + have he : ∃ a ∈ s, a.key = c.key := ⟨c, hc, rfl⟩ + rw [lookup, dite_eq_left he, h he.choose_spec.1 hc he.choose_spec.2] + +open Classical in +theorem lookup_mem {s : Set (Arc α A X)} {c : Arc α A X} {k} (h : lookup s k = some c) : + c ∈ s ∧ c.key = k := by + unfold lookup at h + split_ifs at h with he + exact Option.some.inj h ▸ he.choose_spec + +open Classical in +/-- Builds `Star F A d where ext` with the specified `ext`, `link`, `if`, `let`. -/ +def printStar (v : X) (s : Set (Arc α A X)) (near : X → X → B d) + (ext : Bool → ℕ) (policy : Policy F α A) : Star F A d where + ext := ext + link b k := (lookup s k).bind fun c => + if c.side b = v then some (near v (c.side (!b)), c.width) else none + value x y r := + let f k := (lookup s k).bind fun c => c.decoder (r (decide (c.side false ≠ v)) k) + if ∀ c ∈ s, c.side false = v → f c.key ≠ none then policy x y f else 0 + +open Classical in +theorem star_eq (N : Names G A d) (p : Script G α) (v : G.V) (name : G.V → X) + (hu : Unique G N.lane) + (hd : ∀ e, touches G v e → ∀ b, name (side G b e) = name v → side G b e = v) + (near : X → X → B d) + (hn : ∀ b e, side G b e = v → near (name v) (name (side G (!b) e)) = N.target b e) : + N.star p v = printStar (name v) (cloud p N.lane name v) near + (Names.extSize p v) (policy p N.lane v) := by + let s := cloud p N.lane name v + let t := arc p N.lane name + have inj : Set.InjOn Arc.key s := by + rintro _ ⟨e, he, rfl⟩ _ ⟨f, hf, rfl⟩ h + rw [hu v e f he hf h] + have atKey (e) (he : touches G v e) : lookup s (N.lane e) = some (t e) := + lookup_at inj ⟨e, he, rfl⟩ + have side_eq (e) (he : touches G v e) (b) : (t e).side b = name v ↔ side G b e = v := + ⟨hd e he b, congrArg name⟩ + unfold Names.star printStar + congr 1 + · funext b k + change (N.resident v b k).map _ = (lookup s k).bind _ + cases he : N.resident v b k with + | some e => + obtain ⟨hq, rfl⟩ := N.resident_spec he + have hv : touches G v e := hq ▸ touches_side G b e + rw [atKey _ hv, Option.bind_some, ite_eq_left ((side_eq _ hv b).mpr hq)] + simp only [Option.map_some, t, arc, hn b e hq] + | none => + cases hk : lookup s k with + | none => rfl + | some q => + obtain ⟨⟨e, hv, rfl⟩, rfl⟩ := lookup_mem hk + have hx : (t e).side b ≠ name v := by + intro h + have hv' := (side_eq _ hv _).mp h + have := N.resident_at b e + change N.resident v b (N.lane e) = none at he + rw [hv', he] at this + contradiction + exact (ite_eq_right hx).symm + · funext x y r + let f k := (lookup s k).bind fun c => c.decoder (r (decide (c.side false ≠ name v)) k) + let g e := p.signal e (r (decide (G.src e ≠ v)) (N.lane e)) + have hf (e) (he : touches G v e) : f (N.lane e) = g e := by + unfold f + rw [atKey _ he, Option.bind_some] + simp only [ne_eq, side_eq e he] + rfl + have hc : (∀ c ∈ s, c.side false = name v → f c.key ≠ none) ↔ + ∀ e, G.src e = v → g e ≠ none := by + constructor + · intro h e he + rw [← hf e (.inl he)] + exact h (t e) ⟨e, .inl he, rfl⟩ (congrArg name he) + · rintro h _ ⟨e, he, rfl⟩ ht + exact (hf e he).symm ▸ h e (hd e he _ ht) + change p.localValue v x y g = + if ∀ c ∈ s, c.side false = name v → f c.key ≠ none then policy p N.lane v x y f else 0 + have hv := operation_congr (p.program v) (p.reads v) x y (f ∘ N.lane) g + (fun i hi => hf i (p.incident _ _ hi)) + simp only [hc, policy, operation_reindex, hv] + simp only [Script.localValue, operation, ite_and] + congr! + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Local paths in a typed channel inventory + +A path follows the two host branches of the old channel. Its short +name contains the old name and a hop index. Only the incident part of +the old host's branch map is needed. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +variable {F X Y A α I V : Type} {a b : Wire} {d : ℕ} {G : Bundled F a b} {T : Trie V d} + +open Classical in +/-- The quantity computed by `(d + 1) + (d + 1)`. -/ +abbrev legs (d : ℕ) := (d + 1) + (d + 1) +open Classical in +/-- Indexes the layer by the coordinates of `A × Fin (legs d + 1)`. -/ +abbrev Layer (A : Type) (d : ℕ) := A × Fin (legs d + 1) +open Classical in +/-- The quantity computed by `X → X → Fin (d + 1) → Address d`. -/ +abbrev Branch (X : Type) (d : ℕ) := X → X → Fin (d + 1) → Address d + +open Classical in +/-- Computes the root by the application `Sum.elim id Prod.fst`. -/ +def root : Node X d → X := Sum.elim id Prod.fst + +open Classical in +/-- Computes the lift by the application `Sum.map f (Prod.map f id)`. -/ +def lift (f : X → Y) : Node X d → Node Y d := Sum.map f (Prod.map f id) + +open Classical in +theorem lift_eq {f : X → Y} {u v : Node X d} (h : f (root u) = f (root v) → root u = root v) + (he : lift f u = lift f v) : u = v := by + rcases u with u|⟨u, i⟩ <;> rcases v with v|⟨v, j⟩ + · exact congrArg Sum.inl (h (Sum.inl.inj he)) + · cases he + · cases he + · obtain ⟨hu, hi⟩ := Prod.mk.inj (Sum.inr.inj he) + exact congrArg Sum.inr (Prod.ext (h hu) hi) + +namespace Arc +variable (c : Arc α A X) (w : Branch X d) + +open Classical in +/-- The value specified by `(c.side s, j, w (c.side s) (c.side (!s)) j)`. -/ +def branch (s : Bool) (j : Fin (d + 1)) : Relay X d := + (c.side s, j, w (c.side s) (c.side (!s)) j) + +open Classical in +/-- The indexed operation `Fin.append (c.branch w false) (fun j => c.branch w true j.rev)`. -/ +def via := Fin.append (c.branch w false) (fun j => c.branch w true j.rev) + +open Classical in +/-- The end at used in the `Arc` construction. -/ +def endAt (i : Fin (legs d + 1)) : Bool → Node X d + | false => Fin.cases (.inl (c.side false)) (fun j => .inr (c.via w j)) i + | true => Fin.lastCases (.inl (c.side true)) (fun j => .inr (c.via w j)) i + +open Classical in +/-- Uses `⟨(c.key, i), c.endAt w i, Diagram.padWidth u c.width, Order.Decoder.pad u c.width +c.decoder⟩` as the representation. -/ +def hop (u : ℕ) (i : Fin (legs d + 1)) : Arc α (Layer A d) (Node X d) := + ⟨(c.key, i), c.endAt w i, Diagram.padWidth u c.width, Order.Decoder.pad u c.width c.decoder⟩ + +end Arc + +variable (H : Fanout G T I) (u : ℕ) (lane : G.E → A) + +open Classical in +/-- The value specified by `(lane i.1, i.2)`. -/ +def layer (i : (H.pad u).route.Hop) : Layer A d := (lane i.1, i.2) + +open Classical in +theorem via_root (e : G.E) (i : Fin (legs d)) : + touches G ((H.pad u).route.via e i).1 e := by + induction i using Fin.addCases + · simp only [Fin.append_left]; exact .inl rfl + · simp only [Fin.append_right]; exact .inr rfl + +variable [Field F] + +open Classical in +theorem end_root (s : Bool) (i : (H.pad u).route.Hop) : + touches G (root (side (H.pad u).route.net s i)) i.1 := by + obtain ⟨e, j⟩ := i + cases s + · induction j using Fin.cases with + | zero => exact .inl rfl + | succ j => exact via_root H u e j + · change touches G (root ((H.pad u).route.dst ⟨e, j⟩)) e + induction j using Fin.lastCases with + | last => simp only [Routes.dst, Fin.lastCases_last]; exact .inr rfl + | cast j => simp only [Routes.dst, Fin.lastCases_castSucc]; exact via_root H u e j + +open Classical in +theorem contact_root {v : Node G.V d} {i : (H.pad u).route.Hop} + (h : touches (H.pad u).route.net v i) : touches G (root v) i.1 := by + rcases h with rfl | rfl + · exact end_root H u false i + · exact end_root H u true i + +open Classical in +theorem unique_layer (hu : Unique G lane) : Unique (H.pad u).route.net (layer H u lane) := by + rintro v ⟨e, i⟩ ⟨f, j⟩ he hf eq + obtain ⟨h₁, h₂⟩ := Prod.mk.inj eq + have heq : e = f := hu _ _ _ (contact_root H u he) (contact_root H u hf) h₁ + subst f + exact congrArg (Sigma.mk e) h₂ + +variable (p : Order.Script G α) (name : G.V → X) (w : Branch X d) + +open Classical in +/-- The condition `∀ s, w (name (side G s e)) (name (side G (!s) e)) = T.address (H.site (side G +s e)).1 (H.site (side G (!s) e)).1` on the specified data. -/ +def Follows (e : G.E) : Prop := + ∀ s, w (name (side G s e)) (name (side G (!s) e)) = + T.address (H.site (side G s e)).1 (H.site (side G (!s) e)).1 + +omit [Field F] in +open Classical in +theorem map_via (e : G.E) (h : Follows H name w e) (i : Fin (legs d)) : + Prod.map name id ((H.pad u).route.via e i) = (arc p lane name e).via w i := by + unfold Follows at h + induction i using Fin.addCases + all_goals simp only [Arc.via, Fin.append_left, Fin.append_right, Arc.branch, arc, h] + all_goals rfl + +open Classical in +theorem map_end (e : G.E) (h : Follows H name w e) (i : Fin (legs d + 1)) (s : Bool) : + lift name (side (H.pad u).route.net s ⟨e, i⟩) = (arc p lane name e).endAt w i s := by + cases s + · induction i using Fin.cases with + | zero => rfl + | succ j => exact congrArg Sum.inr (map_via H u lane p name w e h j) + · change lift name ((H.pad u).route.dst ⟨e, i⟩) = _ + induction i using Fin.lastCases with + | last => simp only [Routes.dst, Fin.lastCases_last, Arc.endAt]; rfl + | cast j => + simp only [Routes.dst, Fin.lastCases_castSucc, Arc.endAt] + exact congrArg Sum.inr (map_via H u lane p name w e h j) + +open Classical in +theorem map_arc (e : G.E) (h : Follows H name w e) (i : Fin (legs d + 1)) : + arc ((p.pad u).route (H.pad u).route) (layer H u lane) (lift name) ⟨e, i⟩ = + (arc p lane name e).hop w u i := by + apply congrArg₂ (fun side dec => Arc.mk (lane e, i) side (Diagram.padWidth u (G.width e)) dec) + · exact funext (map_end H u lane p name w e h i) + · exact p.signal_pad u e + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # The incident routed channels are determined by the original star -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout + +variable {F X A α I V : Type} [Field F] {a b : Wire} {d : ℕ} {G : Bundled F a b} + {T : Trie V d} + +open Classical in +/-- The condition `∀ e, touches G v e → ∀ s, name (side G s e) = name v → side G s e = v` on the +specified data. -/ +def Same (name : G.V → X) (v : G.V) := + ∀ e, touches G v e → ∀ s, name (side G s e) = name v → side G s e = v + +omit [Field F] in +open Classical in +theorem Same.ends {name : G.V → X} {v q : G.V} (h : Same name v) + (e : G.E) (hv : touches G v e) (hq : touches G q e) (he : name q = name v) : q = v := by + rcases hq with rfl | rfl + · exact h e hv false he + · exact h e hv true he + +open Classical in +/-- Uses `{c | ∃ a ∈ s, ∃ i, a.hop w u i = c ∧ (c.side false = z ∨ c.side true = z)}` as the +representation. -/ +def channels (z : Node X d) (w : Branch X d) (u : ℕ) (s : Set (Arc α A X)) := + {c | ∃ a ∈ s, ∃ i, a.hop w u i = c ∧ (c.side false = z ∨ c.side true = z)} + +variable (H : Fanout G T I) (u : ℕ) (lane : G.E → A) + (p : Order.Script G α) (name : G.V → X) (w : Branch X d) + +open Classical in +theorem reflect_end (v : Node G.V d) (hs : Same name (root v)) + (e : G.E) (he : touches G (root v) e) (i : Fin (legs d + 1)) (b : Bool) + (hh : lift name (side (H.pad u).route.net b ⟨e, i⟩) = lift name v) : + side (H.pad u).route.net b ⟨e, i⟩ = v := + lift_eq (hs.ends e he (end_root H u b ⟨e, i⟩)) hh + +open Classical in +theorem same_layer (v : Node G.V d) (hs : Same name (root v)) : + Same (G := (H.pad u).route.net) (lift name) v := by + rintro ⟨e, i⟩ he b hh + exact reflect_end H u name v hs e (contact_root H u he) i b hh + +open Classical in +theorem routed_cloud (v : Node G.V d) (hs : Same name (root v)) + (hf : ∀ e, touches G (root v) e → Follows H name w e) : + cloud ((p.pad u).route (H.pad u).route) (layer H u lane) (lift name) v = + channels (lift name v) w u (cloud p lane name (root v)) := by + ext c + constructor + · rintro ⟨⟨e, i⟩, he, rfl⟩ + have h := contact_root H u he + refine ⟨_, ⟨e, h, rfl⟩, i, (map_arc H u lane p name w e (hf e h) i).symm, ?_⟩ + exact he.imp (congrArg (lift name)) (congrArg (lift name)) + · rintro ⟨_, ⟨e, he, rfl⟩, i, rfl, h⟩ + have heq := map_arc H u lane p name w e (hf e he) i + refine ⟨⟨e, i⟩, ?_, heq⟩ + rw [← heq] at h + exact h.imp (reflect_end H u name v hs e he i false) (reflect_end H u name v hs e he i true) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Reading the original operands or comparing the two hops at a relay -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order + +variable {F X A α I V : Type} [Field F] {a b : Wire} {d : ℕ} {G : Bundled F a b} + {T : Trie V d} + +open Classical in +/-- The value specified by `(i, if ∃ c ∈ s, c.key = i ∧ c.side false = x then 0 else Fin.last +_)`. -/ +def endpoint (x : X) (s : Set (Arc α A X)) (i : A) : Layer A d := + (i, if ∃ c ∈ s, c.key = i ∧ c.side false = x then 0 else Fin.last _) + +open Classical in +/-- Uses `{p | ∃ c ∈ s, ∃ i, c.via w i = x ∧ ((c.key, i.castSucc), (c.key, i.succ)) = p}` as the +representation. -/ +def through (x : Relay X d) (w : Branch X d) (s : Set (Arc α A X)) : + Set (Layer A d × Layer A d) := + {p | ∃ c ∈ s, ∃ i, c.via w i = x ∧ ((c.key, i.castSucc), (c.key, i.succ)) = p} + +open Classical in +/-- In the case `.inl v => fun l r f`, this construction gives `p l r (f ∘ endpoint v s)`. -/ +def routePolicy (x : Node X d) (w : Branch X d) (s : Set (Arc α A X)) + (p : Policy F α A) : Policy F α (Layer A d) := + match x with + | .inl v => fun l r f => p l r (f ∘ endpoint v s) + | .inr v => tests (through v w s) + +variable (H : Fanout G T I) (u : ℕ) (lane : G.E → A) + (p : Order.Script G α) (name : G.V → X) (w : Branch X d) + +omit [Field F] in +open Classical in +private theorem endpoint_eq (hu : Unique G lane) (v : G.V) (hs : Same name v) + (e : G.E) (he : touches G v e) : + layer H u lane (Script.endpoint (H.pad u).route v e) = + endpoint (name v) (cloud p lane name v) (lane e) := by + have eq : (∃ c ∈ cloud p lane name v, c.key = lane e ∧ c.side false = name v) ↔ G.src e = v := by + constructor + · rintro ⟨_, ⟨i, hi, rfl⟩, hk, hp⟩ + rw [hu _ _ _ hi he hk] at hp + exact hs e he false hp + · intro h + exact ⟨_, ⟨e, he, rfl⟩, rfl, congrArg name h⟩ + unfold endpoint Script.endpoint + simp only [eq] + split_ifs <;> rfl + +omit [Field F] in +open Classical in +private theorem through_eq (v : Relay G.V d) (hs : Same name v.1) + (hf : ∀ e, touches G v.1 e → Follows H name w e) : + {i | ∃ j ∈ Script.matched (H.pad u).route v, Prod.map (layer H u lane) (layer H u lane) j = i} = + through (Prod.map name id v) w (cloud p lane name v.1) := by + ext i + constructor + · rintro ⟨_, hh, rfl⟩ + obtain ⟨⟨e, j⟩, hj, rfl⟩ := List.mem_map.mp hh + have he : (H.pad u).route.via e j = v := by + simpa only [Finset.mem_toList, Script.visits, Finset.mem_filter, Finset.mem_univ, true_and] + using hj + have hv : touches G v.1 e := by rw [← he]; apply via_root + exact ⟨_, ⟨e, hv, rfl⟩, j, (map_via H u lane p name w e (hf e hv) j).symm.trans + (congrArg (Prod.map name id) he), rfl⟩ + · rintro ⟨_, ⟨e, he, rfl⟩, j, hj, rfl⟩ + have e' := (map_via H u lane p name w e (hf e he) j).trans hj + have eq : (H.pad u).route.via e j = v := Prod.ext + (hs.ends e he (via_root H u e j) (congrArg Prod.fst e')) (congrArg (fun t : Relay X d + => t.2) e') + refine ⟨Script.ends (H.pad u).route ⟨e, j⟩, List.mem_map_of_mem ?_, rfl⟩ + simpa only [Finset.mem_toList, Script.visits, Finset.mem_filter, Finset.mem_univ, true_and] + using eq + +open Classical in +theorem policy_routed (hu : Unique G lane) (v : Node G.V d) (hs : Same name (root v)) + (hf : ∀ e, touches G (root v) e → Follows H name w e) : + policy ((p.pad u).route (H.pad u).route) (layer H u lane) v = + routePolicy (lift name v) w (cloud p lane name (root v)) (policy p lane (root v)) := by + cases v with + | inl v => + have eq : ((p.reads v).map (Script.endpoint (H.pad u).route v)).map (layer H u lane) = + ((p.reads v).map lane).map (endpoint (name v) (cloud p lane name v)) := by + rw [List.map_map, List.map_map] + exact List.map_congr_left (fun i hi => endpoint_eq H u lane p name hu v hs i (p.incident _ _ + hi)) + funext x y f + change operation (p.program v) (((p.reads v).map (Script.endpoint (H.pad u).route v)).map _) x + y f = _ + rw [eq, operation_reindex] + rfl + | inr v => + change operation checkPairs ((pairs (Script.matched (H.pad u).route v)).map (layer H u lane)) + = _ + rw [reindex_pairs, through_eq H u lane p name w v hs hf] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Presentation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Presentation.lean new file mode 100644 index 0000000000..016cb42fc4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Presentation.lean @@ -0,0 +1,608 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Traces +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Pins +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Order.History + +/-! # A directed, unit-width presentation of the full ordered diagram -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Frame +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Coloring Assembly + +variable {F α A : Type} [Field F] {a b : Wire} {u : ℕ} {G : Bundled F a b} + {U : Engine F A} {r : U.scheme.format.obj} {N : Names G A U.d} {p : Order.Script G α} + (H : Frame U r N p u) + +open Classical in +/-- Builds `Seating U.scheme r p.drawing.diagram where vertex` with the specified `vertex`, +`ends`, `station`, `value`. -/ +def seating : Seating U.scheme r p.drawing.diagram where + vertex := H.vertex + ends := H.ends + station := H.owner + value := H.value + empty v hv t := by + have he (q : Pattern F U.d 0 U.e) (h : q = Star.vacant) + (x : ∀ s, Fin (q.width v.2.2 s) → Bool) : q.value v.2.2 x = 1 := by subst q; rfl + exact he _ (H.inactive v hv) _ + +open Classical in +/-- Builds `U.scheme.Presentation r p.drawing.diagram where toSeating` with the specified +`toSeating`, `proper`, `internal`, `rw`. -/ +def presentation : U.scheme.Presentation r p.drawing.diagram where + toSeating := H.seating.seat + proper := H.proper + internal e := by + rw [H.seating.ends_eq] + change U.scheme.Joins r (H.ends (.inl (.inr e))) (H.ends (.inr (.inr e))) + rw [H.lbit, H.rbit] + exact ⟨(H.unit_info false e.1 _ (H.unit_lt _ e.2)).2.2, rfl⟩ + input i := by + obtain ⟨⟨v, j⟩, rfl⟩ := p.left.enum.full.surjective i + rw [H.seating.ends_eq] + change U.scheme.peer r (H.ends (.inl (.inl (p.left.enum.get v j)))).1 = none + rw [H.left v j] + exact (H.exterior_info v false).2.2 + output i := by + obtain ⟨⟨v, j⟩, rfl⟩ := p.right.enum.full.surjective i + rw [H.seating.ends_eq] + change U.scheme.peer r (H.ends (.inr (.inl (p.right.enum.get v j)))).1 = none + rw [H.right v j] + exact (H.exterior_info v true).2.2 + +open Classical in +theorem vertex_eq : H.presentation.vertex = H.vertex := rfl + +open Classical in +theorem ends_eq : H.presentation.toSeating.ends = H.ends := H.seating.ends_eq + +open Classical in +theorem directed : H.presentation.Directed := by + intro q + rw [H.ends_eq] + exact H.directed_end q + +include H in +open Classical in +theorem uniform (i : U.scheme.Span) (hi : (U.scheme.peer r i).isSome) : U.scheme.width r i = u := by + obtain ⟨j, hj⟩ := Option.isSome_iff_exists.mp hi + obtain ⟨s, e, t, ht, rfl, _⟩ := H.peer_spec _ _ hj + exact (H.unit_info s e t ht).1 + +open Classical in +theorem neighbor (v w : G.V) (i j : B U.e) + (h : U.scheme.peer r (H.vertex v, i) = some (H.vertex w, j)) : + (U.scheme.pattern r (H.vertex v)).peer 0 i = some (N.near v w, 0, j) := by + obtain ⟨s, e, l, hl, hi, hj⟩ := H.peer_spec _ _ h + obtain ⟨hv, rfl⟩ := Prod.mk.inj hi + obtain ⟨hw, rfl⟩ := Prod.mk.inj hj + rw [H.vertex.injective hv, H.vertex.injective hw] + exact H.unit_local s e l hl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Frame +end + +/- # A local printer for all the physical descendants of a station -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Coloring + +open Classical in +/-- The data for the inventory construction, including `ext`, `lines`, `command`. -/ +structure Inventory (F α A X : Type) where + /-- The `Inventory` component of type `Bool → ℕ`. -/ + ext : Bool → ℕ + /-- The `Inventory` component of type `Set (Arc α A X)`. -/ + lines : Set (Arc α A X) + /-- The `Inventory` component of type `Policy F α A`. -/ + command : Policy F α A + +variable {F X A α I V : Type} [Field F] {a b : Wire} {d z : ℕ} {G : Bundled F a b} + {T : Trie V d} + +open Classical in +/-- Uses `⟨Names.extSize p v, cloud p lane name v, policy p lane v⟩` as the representation. -/ +def describe (p : Order.Script G α) (lane : G.E → A) (name : G.V → X) (v : G.V) : + Inventory F α A X := ⟨Names.extSize p v, cloud p lane name v, policy p lane v⟩ + +open Classical in +/-- The value specified by `printStar x (channels x w u c.lines) near (if x.isLeft then c.ext +else fun _ => 0) (routePolicy x w c.lines c.command)`. -/ +def Inventory.star (c : Inventory F α A X) (x : Node X d) (u : ℕ) (w : Branch X d) + (near : Node X d → Node X d → B z) : Star F (Layer A d) z := + printStar x (channels x w u c.lines) near (if x.isLeft then c.ext else fun _ => 0) + (routePolicy x w c.lines c.command) + +variable (H : Fanout G T I) (u : ℕ) (lane : G.E → A) (hu : Unique G lane) + (idx : Node G.V d → Node G.V d → B z) + +open Classical in +/-- Computes the route names by the application `Unique.names (layer H u lane) (unique_layer H u +lane hu) idx`. -/ +abbrev routeNames : Names (H.pad u).route.net (Layer A d) z + := Unique.names (layer H u lane) (unique_layer H u lane hu) idx + +open Classical in +/-- The inventory, branch assignments on its endpoints and neighbor +indices suffice for the whole star on any of the station's host slots. -/ +theorem printed (p : Order.Script G α) (name : G.V → X) (v : Node G.V d) + (hs : Same name (root v)) (w : Branch X d) + (hf : ∀ e, touches G (root v) e → Follows H name w e) + (near : Node X d → Node X d → B z) + (hn : ∀ b e, side (H.pad u).route.net b e = v → + near (lift name v) (lift name (side (H.pad u).route.net (!b) e)) = + idx v (side (H.pad u).route.net (!b) e)) : + (routeNames H u lane hu idx).star ((p.pad u).route (H.pad u).route) v = + (describe p lane name (root v)).star (lift name v) u w near := by + let N := routeNames H u lane hu idx + let q := (p.pad u).route (H.pad u).route + have h : Names.extSize q v = if (lift name v).isLeft then Names.extSize p (root v) else fun _ + => 0 := by + cases v <;> funext s <;> cases s <;> rfl + calc + _ = printStar (lift name v) (cloud q (layer H u lane) (lift name) v) near + (Names.extSize q v) (policy q (layer H u lane) v) := by + apply star_eq N q v (lift name) (unique_layer H u lane hu) (same_layer H u name v hs) + intro b e he + change _ = idx (side _ b e) (side _ (!b) e) + rw [he] + exact hn b e he + _ = _ := by + rw [h] + unfold q + rw [routed_cloud H u lane p name w v hs hf, policy_routed H u lane p name w hu v hs hf] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Static local navigation + +A guide remembers no long host names. It stores the short branch +addresses and neighbor indices between the possible slots of a cell +and its neighbors. These functions are shared across all blocks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Coloring + +variable {F V X Y I α A : Type} {d z : ℕ} + +open Classical in +/-- The data for the guide construction, including `branch`, `next`. -/ +structure Guide (X : Type) (d z : ℕ) where + /-- The `Guide` component of type `Branch X d`. -/ + branch : Branch X d + /-- The successor of each choice of type `Node X d → Node X d → B z`. -/ + next : Node X d → Node X d → B z + +open Classical in +/-- Builds `Guide X d z where branch x y` with the specified `Guide`, `next`. -/ +def Guide.make (T : Trie V d) (index : Node V d → Node V d → B z) (find : X → V) : + Guide X d z where + branch x y := T.address (find x) (find y) + next x y := index (lift find x) (lift find y) + +open Classical in +/-- Transforms the indexed data by `p.map (fun s => s.star v u W.branch W.next)`. -/ +def Guide.emit [Field F] (W : Guide X d z) (v : Node X d) (u : ℕ) + (p : Option (Inventory F α A X)) : Option (Star F (Layer A d) z) := + p.map (fun s => s.star v u W.branch W.next) + +variable {a b : Wire} {G : Bundled F a b} {T : Trie V d} (H : Fanout G T I) + (idx : Node V d → Node V d → B z) + +open Classical in +/-- Computes the pointer by the application `idx (H.place v).1 (H.place w).1`. -/ +def pointer (v w : Node G.V d) := idx (H.place v).1 (H.place w).1 + +open Classical in +/-- The condition `∀ w, (w = v ∨ ∃ e, touches G v e ∧ touches G w e) → find (name w) = (H.site +w).1` on the specified data. -/ +def Locates (name : G.V → X) (find : X → V) (v : G.V) := + ∀ w, (w = v ∨ ∃ e, touches G v e ∧ touches G w e) → find (name w) = (H.site w).1 + +open Classical in +private theorem lift_name (name : G.V → X) (find : X → V) (v : Node G.V d) + (h : find (name (root v)) = (H.site (root v)).1) : + lift find (lift name v) = (H.place v).1 := by + cases v with + | inl v => exact congrArg Sum.inl h + | inr v => exact congrArg (fun x => Sum.inr (x, v.2)) h + +variable [Field F] + +open Classical in +theorem print_local (u : ℕ) (lane : G.E → A) (hu : Unique G lane) (p : Order.Script G α) + (name : G.V → X) (v : Node G.V d) (hs : Same name (root v)) + (find : X → V) (hf : Locates H name find (root v)) : + (Guide.make T idx find).emit (lift name v) u (some (describe p lane name (root v))) = + some ((routeNames H u lane hu (pointer H idx)).star ((p.pad u).route (H.pad u).route) v) := by + let W := Guide.make T idx find + have follows (e : G.E) (he : touches G (root v) e) : Follows H name W.branch e := by + intro s + change T.address (find (name _)) (find (name _)) = _ + have ht (s : Bool) := hf _ (.inr ⟨e, he, touches_side _ s e⟩) + rw [ht, ht] + have step b i (h : side (H.pad u).route.net b i = v) : + W.next (lift name v) (lift name (side (H.pad u).route.net (!b) i)) = + pointer H idx v (side (H.pad u).route.net (!b) i) := by + let w := side (H.pad u).route.net (!b) i + have hv : touches G (root v) i.1 := h ▸ end_root H u b i + change idx (lift find (lift name v)) (lift find (lift name w)) = _ + rw [lift_name H name find v (hf _ (.inl rfl)), + lift_name H name find w (hf _ (.inr ⟨i.1, hv, end_root H u (!b) i⟩))] + rfl + exact congrArg some (printed H u lane hu (pointer H idx) p name v hs W.branch follows W.next + step).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- Local programs, including the order of all station and sphere operands. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Order + +variable {F U X E V K J Z A : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} + +open Classical in +/-- Returns `some h.choose` when `h : ∃ i ∈ c.rows, i.number = z` holds, and `none` otherwise. -/ +def Sheet.get (c : Sheet F J Z A M r t) (z : Z) := + if h : ∃ i ∈ c.rows, i.number = z then some h.choose else none + +open Classical in +theorem Sheet.get_spec (c : Sheet F J Z A M r t) {z : Z} {i} (h : c.get z = some i) : + i ∈ c.rows ∧ i.number = z := by + unfold get at h + split_ifs at h with he + exact Option.some.inj h ▸ he.choose_spec + +open Classical in +/-- The indexed operation `i.reads.map (fun k => .reader k v i.number) ++ List.ofFn (Lane.left v +i.number) ++ List.ofFn (Lane.right v i.number)`. -/ +def Row.operands (i : Row F Z A M r t) (v : J) : List (Lane J Z A M) := + i.reads.map (fun k => .reader k v i.number) ++ List.ofFn (Lane.left v i.number) ++ + List.ofFn (Lane.right v i.number) + +namespace Sheet +variable [Field F] (c : Sheet F J Z A M r t) (P : ℕ) + +open Classical in +/-- The first of type `Policy F (Signal M r t) (Lane J Z A M)` for the given inputs. -/ +def first (j : Fin M) : Policy F (Signal M r t) (Lane J Z A M) := + operation (chamber Signal.first + (c.rows.map (fun i => i.point ^ P) ++ c.ports.map (fun i => i.point ^ P))) + (c.rows.map (fun i => Lane.left c.mark i.number j) ++ c.ports.map (fun i => Lane.seam i.edge j)) + +open Classical in +/-- The indexed operation `operation (chamber Signal.second (c.rows.map Row.point)) (c.rows.map +(fun i => Lane.right c.mark i.number j))`. -/ +def second (j : Fin M) : Policy F (Signal M r t) (Lane J Z A M) := + operation (chamber Signal.second (c.rows.map Row.point)) + (c.rows.map (fun i => Lane.right c.mark i.number j)) + +open Classical in +/-- The job of type `Option ((Bool → ℕ) × Policy F (Signal M r t) (Lane J Z A M))` for the given +inputs. -/ +def job (known : J → A → Prop) (z : Spot J Z M) : + Option ((Bool → ℕ) × Policy F (Signal M r t) (Lane J Z A M)) := + match z.2 with + | .inl i => (c.get i).map (fun j => (j.ext, operation (load j.label) (j.operands c.mark))) + | .inr (.inl false) => some (fun _ => 0, tests (c.hub known)) + | .inr (.inl true) => some (fun _ => 0, operation (fun _ _ _ => 1) []) + | .inr (.inr (.inl j)) => some (fun _ => 0, c.first P j) + | .inr (.inr (.inr j)) => some (fun _ => 0, c.second j) + +open Classical in +/-- Returns `(c.job P known z).map (fun x => ⟨x.1, c.lines known z, x.2⟩)` when `z.1 = c.mark` +holds, and `none` otherwise. -/ +def inventory (known : J → A → Prop) (z : Spot J Z M) : + Option (Inventory F (Signal M r t) (Lane J Z A M) (Spot J Z M)) := + if z.1 = c.mark then (c.job P known z).map (fun x => ⟨x.1, c.lines known z, x.2⟩) else none + +end Sheet + +namespace Marking +variable (m : Marking S J Z A) (L : Rules S) {e : E → ℕ} (p : Profile C e) + +open Classical in +theorem get_eq (i : Place C) : + (m.sheet L p i.1).get (m.number i) = some (m.rowData L p i) := by + have h : ∃ j ∈ (m.sheet L p i.1).rows, j.number = m.number i := + ⟨_, m.row_mem L p i, rfl⟩ + rw [Sheet.get, dite_eq_left h] + obtain ⟨j, hj, he⟩ := m.row_spec L p h.choose_spec.1 + have hn := h.choose_spec.2 + rw [← he] at hn ⊢ + rw [m.atCell j i hj hn] + +variable [Field F] [Fintype E] [Fintype V] [Fintype K] (P : ℕ) + +omit [Field F] in +open Classical in +private theorem row_operands (i : Place C) : + (L.operands (.inl (.inl i))).map m.lane = (m.rowData L p i).operands (m.mark i.1) := by + simp only [Rules.operands, Row.operands, rowData, List.map_append, List.map_map, List.map_ofFn] + congr 2 + rw [← List.attach_map_val (l := L.reads i)] + rfl + +open Classical in +theorem first_eq (v : V) (j : Fin M) : + policy (L.script p P) m.lane (.inr (.inl (v, j))) = (m.sheet L p v).first P j := by + change operation (chamber Signal.first ((firstList C v).map (firstPoint C P))) + (((firstList C v).map (Rules.first j)).map m.lane) = _ + unfold Sheet.first sheet + simp only [firstList, secondList, List.map_append, List.map_map] + rfl + +open Classical in +theorem second_eq (v : V) (j : Fin M) : + policy (L.script p P) m.lane (.inr (.inr (v, j))) = (m.sheet L p v).second j := by + change operation (chamber Signal.second ((secondList C v).map (secondPoint C))) + (((secondList C v).map (fun i => Rules.back i j)).map m.lane) = _ + unfold Sheet.second sheet + simp only [secondList, List.map_map] + rfl + +open Classical in +private theorem job_eq (known : J → A → Prop) (s : S.Position) (h : m.Observes (S.home s) known) : + (m.sheet L p (S.home s)).job P known (m.spot s) = + some (Names.extSize (L.script p P) s, policy (L.script p P) m.lane s) := by + rcases s with ((i|v|v)|(⟨v, j⟩|⟨v, j⟩)) + · change ((m.sheet L p i.1).get (m.number i)).map _ = _ + rw [m.get_eq, Option.map_some] + change some ((m.rowData L p i).ext, operation (load (L.label i)) + ((m.rowData L p i).operands (m.mark i.1))) = _ + rw [← m.row_operands] + rfl + · rw [m.hub_eq L p v known h] + refine congrArg some (Prod.ext ?_ rfl) + funext b; cases b <;> rfl + · refine congrArg some (Prod.ext ?_ rfl) + funext b; cases b <;> rfl + · rw [m.first_eq] + refine congrArg some (Prod.ext ?_ rfl) + funext b; cases b <;> rfl + · rw [m.second_eq] + refine congrArg some (Prod.ext ?_ rfl) + funext b; cases b <;> rfl + +open Classical in +theorem inventory_eq (known : J → A → Prop) (s : S.Position) (h : m.Observes (S.home s) known) : + (m.sheet L p (S.home s)).inventory P known (m.spot s) = + some (describe (L.script p P) m.lane m.spot s) := by + have he : (m.spot s).1 = (m.sheet L p (S.home s)).mark := m.home_mark s + rw [Sheet.inventory, ite_eq_left he, m.job_eq L p P known s h, Option.map_some] + rw [m.lines L p known P s h] + rfl + +omit [Fintype E] [Fintype V] [Fintype K] in +open Classical in +theorem inventory_live (known : J → A → Prop) (v : V) (s : Spot J Z M) + (h : ((m.sheet L p v).inventory P known s).isSome) : + ∃ z, S.home z = v ∧ m.spot z = s := by + unfold Sheet.inventory at h + split_ifs at h with he + swap + · contradiction + obtain ⟨j, i | (_ | _) | i | i⟩ := s + all_goals change j = m.mark v at he + all_goals subst j + · change ((m.sheet L p v).get i |>.map _ |>.map _).isSome at h + obtain ⟨u, hu⟩ : ∃ u, (m.sheet L p v).get i = some u := by + cases eq : (m.sheet L p v).get i + · simp [eq] at h + · exact ⟨_, rfl⟩ + obtain ⟨hm, hn⟩ := (m.sheet L p v).get_spec hu + obtain ⟨z, hz, rfl⟩ := m.row_spec L p hm + exact ⟨.inl (.inl z), hz, Prod.ext (congrArg m.mark hz) (congrArg Sum.inl hn)⟩ + · exact ⟨.inl (.inr (.inl v)), rfl, rfl⟩ + · exact ⟨.inl (.inr (.inr v)), rfl, rfl⟩ + · exact ⟨.inr (.inl (v, i)), rfl, rfl⟩ + · exact ⟨.inr (.inr (v, i)), rfl, rfl⟩ + +end Marking +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Local requests for printed patterns + +A cell has one sheet for all its descendants. Footprints of neighbor +cells are addressed by color rather than by absolute position. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Coloring Assembly + +open Classical in +/-- The data for the request construction, including `sheet`, `footprint`, `guide`, `seat`. -/ +structure Request (F J Z A : Type) (M r t d z : ℕ) where + /-- The `Request` component of type `Sheet F J Z A M r t`. -/ + sheet : Sheet F J Z A M r t + /-- The `Request` component of type `Finset (J × A)`. -/ + footprint : Finset (J × A) + /-- The `Request` component of type `Guide (Spot J Z M) d z`. -/ + guide : Guide (Spot J Z M) d z + /-- The `Request` component of type `Node (Spot J Z M) d`. -/ + seat : Node (Spot J Z M) d + +variable {F J Z A : Type} [Field F] {M r t d z c s : ℕ} + +open Classical in +/-- The value specified by `(v, k) ∈ q.footprint`. -/ +def Request.known (q : Request F J Z A M r t d z) (v : J) (k : A) := (v, k) ∈ q.footprint + +open Classical in +/-- The value specified by `q.guide.emit q.seat u (q.sheet.inventory P q.known (root q.seat))`. -/ +def Request.emit (q : Request F J Z A M r t d z) (P u : ℕ) := + q.guide.emit q.seat u (q.sheet.inventory P q.known (root q.seat)) + +open Classical in +/-- Transforms the indexed data by `((x.bind fun q => q.emit P u).map fun b => b.pattern ix +u).getD Star.vacant`. -/ +def pattern (x : Option (Request F J Z A M r t d z)) (P u : ℕ) + (ix : Band (Layer (Lane J Z A M) d) c ↪ B s) := + ((x.bind fun q => q.emit P u).map fun b => b.pattern ix u).getD Star.vacant + +open Classical in +theorem root_lift {V X : Type} (f : V → X) (v : Node V d) : root (lift f v) = f (root v) := by + cases v <;> rfl + +namespace Marking +variable {U X E V K : Type} [Fintype E] [Fintype V] [Fintype K] + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} (m : Marking S J Z A) (L : Order.Rules S) {e : E → ℕ} (p : Profile C e) + (P u : ℕ) {I V' : Type} {T : Trie V' d} (H : Fanout (S.backdrop.emitted p P) T I) + (idx : Node V' d → Node V' d → B z) + +open Classical in +/-- Computes the names by the application `routeNames H u m.lane (m.unique p P) (pointer H +idx)`. -/ +abbrev names := routeNames H u m.lane (m.unique p P) (pointer H idx) + +open Classical in +theorem emit_eq (v : Node S.Position d) (x : Request F J Z A M r t d z) + (h : x.sheet = m.sheet L p (S.home (root v))) + (hobs : m.Observes (S.home (root v)) x.known) (hseat : x.seat = lift m.spot v) + (find : Spot J Z M → V') (hloc : Locates H m.spot find (root v)) + (hg : x.guide = Guide.make T idx find) : + x.emit P u = some ((m.names p P u H idx).star (((L.script p P).pad u).route (H.pad u).route) v) + := by + rw [Request.emit, hseat, hg, h, root_lift, m.inventory_eq L p P _ _ hobs] + exact print_local H idx u m.lane (m.unique p P) (L.script p P) m.spot v (m.same p P _) find hloc + +omit [Fintype E] [Fintype V] [Fintype K] in +open Classical in +theorem emit_live (v : V) (x : Request F J Z A M r t d z) (h : x.sheet = m.sheet L p v) + (hx : (x.emit P u).isSome) : + ∃ w : Node S.Position d, S.home (root w) = v ∧ lift m.spot w = x.seat := by + have hr : ((m.sheet L p v).inventory P x.known (root x.seat)).isSome := by + simpa [Request.emit, Guide.emit, h] using hx + obtain ⟨w, hw, he⟩ := m.inventory_live L p P _ _ _ hr + cases eq : x.seat with + | inl s => + rw [eq] at he + exact ⟨.inl w, hw, congrArg Sum.inl he⟩ + | inr s => + rw [eq] at he + exact ⟨.inr (w, s.2), hw, congrArg (fun t => Sum.inr (t, s.2)) he⟩ + +end Marking +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Static host information for one colored cell -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Coloring Rounds +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Sharing Place Profile Alphabet + Node) + +open Classical in +/-- Indexes the number by the coordinates of `Bool × Fin (D ^ k)`. -/ +abbrev Number (D k : ℕ) := Bool × Fin (D ^ k) +open Classical in +/-- Indexes the bench by the coordinates of `V × Sharing.Slot M D k`. -/ +abbrev Bench (V : Type) (M D k : ℕ) := V × Sharing.Slot M D k +open Classical in +/-- The quantity computed by `Node (Bench V M D k) (Sharing.radius k * d)`. -/ +abbrev Host (V : Type) (M D k d : ℕ) := Node (Bench V M D k) (Sharing.radius k * d) + +namespace Compass + +variable {F U X E V K : Type} {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D T R g k d : ℕ} {W : ℝ} {P : Input F a b h D T R g W} + {G : S.Geo P k} (hD : D = 2 ^ d) (hd : 4 ≤ D) + [Field F] [Fintype E] [Fintype V] [Fintype K] + {e : E → ℕ} (p : Profile C e) (L : ℕ) + +open Classical in +theorem home_eq (v : Node S.Position (Sharing.radius k * d)) : + ((root ((G.layout hD hd p L).place v).1).1, ((G.layout hD hd p L).place v).2) = + G.site (S.home (root v)) := by cases v <;> rfl + +end Compass +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Active and vacant slots in a local emission -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Rounds +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Sharing Place Profile Alphabet + Node) + +open Classical in +/-- Indexes the page by the coordinates of `Sheet F J Z A M r t × Finset (J × A)`. -/ +abbrev Page (F J Z A : Type) (M r t : ℕ) := Sheet F J Z A M r t × Finset (J × A) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Building a directed presentation from printed occurrence rows -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Rounds Coloring +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Sharing Place Profile Alphabet + Node) + +open Classical in +/-- Embeds `V × I` into `U.scheme.Vtx`. -/ +def Engine.seat {F A V I : Type} (U : Engine F A) (host : V ↪ B U.m) (block : I ↪ B U.h) : + V × I ↪ U.scheme.Vtx := + ⟨fun x => (host x.1, block x.2, 0), fun _ _ h => + Prod.ext (host.injective (congrArg Prod.fst h)) (block.injective (congrArg (fun y => y.2.1) h))⟩ + +namespace Compass +variable {F T X E V K J A : Type} [Field F] [Fintype E] [Fintype V] [Fintype K] {M r t : ℕ} + {C : V → Surface.Cell F (M * r) (M * t) T E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} {h D W₀ R g k d : ℕ} {W : ℝ} {P : Input F a b h D W₀ R g W} + {G : S.Geo P k} + (hD : D = 2 ^ d) (hd : 4 ≤ D) {e : E → ℕ} (p : Profile C e) (L u : ℕ) (q : Order.Rules S) + +open Classical in +/-- The quantity computed by `Layer (Lane J (Number D k) A M) (Sharing.radius k * d)`. -/ +abbrev FinalLane (J A : Type) (M D k d : ℕ) := Layer (Lane J (Number D k) A M) (Sharing.radius k * + d) + +variable {U : Engine F (FinalLane J A M D k d)} + (host : Host P.V M D k d ↪ B U.m) (block : Packing.Cell h ↪ B U.h) + (idx : Host P.V M D k d → Host P.V M D k d → B U.d) + (rows : U.scheme.format.obj) + (pages : P.V × Packing.Cell h → Option (Page F J (Number D k) A M r t)) + +local notation "H" => G.layout hD hd p L + +open Classical in +/-- Embeds `Node S.Position (Sharing.radius k * d)` into `U.scheme.Vtx`. -/ +def vertex : Node S.Position (Sharing.radius k * d) ↪ U.scheme.Vtx := + (show Node S.Position (Sharing.radius k * d) ↪ _ from ⟨(H).place, (H).injective⟩).trans + (U.seat host block) + +end Compass +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Seating.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Seating.lean new file mode 100644 index 0000000000..37f1ceb0f7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Seating.lean @@ -0,0 +1,873 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Coupled +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Span +public import Mathlib.Data.Fin.Tuple.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.WireRecovery +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam + +/-! +# Products with one shared rational parameter + +Principal parts and constant terms suffice to reconstruct the whole +product. The convolution uses only nonpositive total Laurent orders, +even though an individual factor may contribute a regular term. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +open Polynomial Finset +variable {K ι D : Type*} [Field K] + +open scoped Classical in +private theorem regular_prod (s : Finset ι) (z : K) (a b : ι → K[X]) + (hb : ∀ i ∈ s, (b i).eval z ≠ 0) : + regular z (∏ i ∈ s, a i) (∏ i ∈ s, b i) = ∏ i ∈ s, regular z (a i) (b i) := by + have ht (f : ι → K[X]) : (taylor z (∏ i ∈ s, f i) : PowerSeries K) = + ∏ i ∈ s, (taylor z (f i) : PowerSeries K) := by + clear hb + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi ih => simp only [prod_insert hi, taylor_mul, Polynomial.coe_mul, ih] + have he : (∏ i ∈ s, b i).eval z ≠ 0 := by rw [eval_prod]; exact prod_ne_zero_iff.mpr hb + have hn : (taylor z (∏ i ∈ s, b i) : PowerSeries K) ≠ 0 := by + intro h + apply he + simpa only [constantCoeff_coe, taylor_coeff_zero, map_zero] + using congrArg PowerSeries.constantCoeff h + apply mul_right_cancel₀ hn + rw [regular_mul _ _ _ he, ht, ht, ← prod_mul_distrib] + exact prod_congr rfl fun i hi => (regular_mul _ _ _ (hb i hi)).symm + +variable [Fintype ι] + +open scoped Classical in +private theorem prod_poles (s : Finset K) (d : ι → ℕ) : + ∏ i, poles s (fun _ => d i) = poles s (fun _ => ∑ i, d i) := by + unfold poles + rw [prod_comm] + simp only [prod_pow_eq_pow_sum] + +open scoped Classical in +/-- An entrywise statement for a subspace of tables. The summation +indices in the hypothesis are Laurent orders shifted by the pole bounds. -/ +theorem product_mem (W : Submodule K (D → K)) (s : Finset K) (hs : s.Nonempty) + (a : ι → D → K[X]) (d : ι → ℕ) (hd : ∀ i y, (a i y).natDegree ≤ s.card * d i) + (h : ∀ z ∈ s, ∀ u : ι → ℕ, (∑ i, u i) ≤ ∑ i, d i → + (fun y => ∏ i, jet z (poles (s.erase z) (fun _ => d i)) (u i) (a i y)) ∈ W) (x : K) : + (fun y => ∏ i, (a i y).eval x / (poles s (fun _ => d i)).eval x) ∈ W := by + let H := ∑ i, d i + let q := poles s (fun _ => H) + let u (z : K) := poles (s.erase z) (fun _ => H) + let P (y : D) := ∏ i, a i y + have deg (y : D) : (P y).natDegree ≤ s.card * H := calc + _ ≤ ∑ i, (a i y).natDegree := natDegree_prod_le _ _ + _ ≤ ∑ i, s.card * d i := sum_le_sum fun i _ => hd i y + _ = _ := (mul_sum _ _ _).symm + have size : s.card * H < ∑ _ ∈ s, (H + 1) := by + simpa using Nat.mul_lt_mul_of_pos_left (Nat.lt_succ_self H) hs.card_pos + obtain ⟨c, hc⟩ := reconstruct_jets s (fun _ => H + 1) u (fun z _ + => poles_eval _ (notMem_erase z s)) + _ size (jet x q 0) + have he : (fun y => ∏ i, (a i y).eval x / (poles s (fun _ => d i)).eval x) = + ∑ v, c v • (fun y => jet v.1.val (u v.1.val) v.2.val (P y)) := by + funext y + rw [prod_div_distrib, ← eval_prod, ← eval_prod, prod_poles, ← jet_zero, hc _ (deg y)] + simp only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul] + rw [he] + refine W.sum_mem (fun v _ => W.smul_mem _ ?_) + let z := v.1.val + let n := v.2.val + have eqn : (fun y => jet z (u z) n (P y)) = + ∑ l ∈ finsuppAntidiag univ n, + (fun y => ∏ i, jet z (poles (s.erase z) (fun _ => d i)) (l i) (a i y)) := by + funext y + rw [Finset.sum_apply] + change PowerSeries.coeff n (regular z _ _) = _ + unfold u H P + rw [← prod_poles, regular_prod _ _ _ _ (fun i _ => poles_eval _ (notMem_erase z s)), + PowerSeries.coeff_prod] + rfl + rw [eqn] + exact W.sum_mem fun l hl => h z v.1.property l (by + rw [(mem_finsuppAntidiag.mp hl).1]; exact Nat.lt_succ_iff.mp v.2.isLt) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end + +/- # Products of arrays and bounds after closing an auxiliary leg -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {K S : Type} [Field K] [Fintype S] [Nonempty S] {n : ℕ} + +theorem product_tables (X : Fin n → S → Type) [∀ i s, Fintype (X i s)] + (V : ∀ i, (∀ s, X i s) → K) : + (∏ i, ofRaw (Raw.ofTable (X i) (V i))) = ofRaw (Raw.ofTable (fun s => ∀ i, X i s) + (fun x => ∏ i, V i (fun s => x s i))) := by + classical + induction n with + | zero => + rw [Finset.prod_of_isEmpty] + apply ofRaw_eq + refine Raw.equiv_coeff (fun s => Equiv.ofUnique Unit (∀ i, X i s)) fun x => ?_ + erw [Raw.coeff_ofTable] + change (∑ _ : Unit, ∏ _ : S, (1 : K)) = _ + simp + | succ n ih => + rw [Fin.prod_univ_succ, ih (fun i => X i.succ), ← ofRaw_mul] + apply ofRaw_eq + refine Raw.equiv_coeff (fun s => Fin.consEquiv (fun i => X i s)) fun x => ?_ + rw [Raw.coeff_mul] + erw [Raw.coeff_ofTable, Raw.coeff_ofTable, Raw.coeff_ofTable] + change (∀ s, X 0 s × (∀ i : Fin n, X i.succ s)) at x + change _ = ∏ i, V i (fun s => Fin.cons (α := fun k => X k s) (x s).1 (x s).2 i) + simp only [Fin.prod_univ_succ, + Fin.cons_zero, Fin.cons_succ] + +variable {I : Type} [Fintype I] + +theorem product_span_le (X : Fin n → S → Type) [∀ i s, Fintype (X i s)] + (V : ∀ i, (∀ s, X i s) → K) (L : I → ∀ i, (∀ s, X i s) → K) + (c : I → K) (h : ∀ x : ∀ i s, X i s, (∏ i, V i (x i)) = ∑ j, c j * ∏ i, L j i (x i)) : + ∏ i, ofRaw (Raw.ofTable (X i) (V i)) ≤ ∑ j, ∏ i, ofRaw (Raw.ofTable (X i) (L j i)) := by + simp_rw [product_tables] + exact span_le _ _ _ c (fun x => h (fun i s => x s i)) + +variable [DecidableEq S] + +/-- The auxiliary site can be placed at a different old site in each +summand without increasing the cost of any closed restriction. -/ +theorem padded_sum_le (P : I → Tensor K (S ⊕ Unit)) (loc : I → S) (T : Tensor K S) + (h : pad Unit T ≤ ∑ j, P j) : + T ≤ ∑ j, place (Sum.elim id (fun _ => loc j)) (P j) := by + classical + suffices ∀ s : Finset I, ∀ T : Tensor K S, pad Unit T ≤ ∑ j ∈ s, P j → + T ≤ ∑ j ∈ s, place (Sum.elim id (fun _ => loc j)) (P j) from this _ _ h + intro s + induction s using Finset.induction_on with + | empty => + intro U hU + rw [Finset.sum_empty, ← (padding Unit).zero] at hU + rw [Finset.sum_empty] + exact ((padding Unit).le_iff _ _).mp hU + | insert j s hj ih => + intro U hU + rw [Finset.sum_insert hj] at hU ⊢ + obtain ⟨A, B, hA, hB, hAB⟩ := (padding Unit).split hU + let g : S ⊕ Unit → S := Sum.elim id (fun _ => loc j) + have ht := place_mono g hA + rw [← place_inl, ← place_comp, show g ∘ Sum.inl = id from rfl, place_id] at ht + refine hAB.trans ((add_le_add_right A _ B ht).trans ?_) + have h := add_le_add_right _ _ (place g (P j)) (ih B hB) + rw [add_comm B, add_comm _ (place g (P j))] at h + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end + +/- +# Printing one station from its intrinsic star + +Each internal bundle has a short name shared by its two ends. Split +it into equal units, preserving the order of the bits. Two additional +spans contain all exterior bits, one per side of the station. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Coloring Assembly + +open Classical in +/-- Indexes the band by the coordinates of `Bool × Option (A × Fin c)`. -/ +abbrev Band (A : Type) (c : ℕ) := Bool × Option (A × Fin c) + +open Classical in +/-- The data for the star construction, including `ext`, `link`, `value`. -/ +structure Star (F A : Type) (d : ℕ) where + /-- The `Star` component of type `Bool → ℕ`. -/ + ext : Bool → ℕ + /-- The `Star` component of type `Bool → A → Option (B d × ℕ)`. -/ + link : Bool → A → Option (B d × ℕ) + /-- The evaluation map carried by `Star`, with type `List Bool → List Bool → (Bool → A → List + Bool) → F`. -/ + value : List Bool → List Bool → (Bool → A → List Bool) → F + +variable {F A : Type} {d c e : ℕ} + +namespace Star +variable (S : Star F A d) (ix : Band A c ↪ B e) (u : ℕ) + +open Classical in +/-- Indexes the port by the coordinates of `ℕ × Bool × Option (B d × B 0 × B e)`. -/ +abbrev Port (d e : ℕ) := ℕ × Bool × Option (B d × B 0 × B e) + +open Classical in +/-- In the case `(b, none)`, this construction gives `(S.ext b, b, none)`. -/ +def spec (s : Band A c) : Port d e := + match s with + | (b, none) => (S.ext b, b, none) + | (b, some (i, j)) => match S.link b i with + | some (q, n) => if j.val < n / u then (u, b, some (q, 0, ix (!b, some (i, j)))) else (0, b, + none) + | none => (0, b, none) + +open Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def desc : B e → Port d e := Function.extend ix (S.spec ix u) (fun _ => (0, false, none)) + +open Classical in +theorem desc_band (s : Band A c) : S.desc ix u (ix s) = S.spec ix u s := + ix.injective.extend_apply _ _ _ + +open Classical in +theorem desc_ext (b : Bool) : S.desc ix u (ix (b, none)) = (S.ext b, b, none) := S.desc_band ix u _ + +open Classical in +theorem desc_link {b : Bool} {i : A} {q : B d} {n : ℕ} + (h : S.link b i = some (q, n)) (j : Fin c) (hj : j.val < n / u) : + S.desc ix u (ix (b, some (i, j))) = (u, b, some (q, 0, ix (!b, some (i, j)))) := by + rw [desc_band]; simp only [spec, h, ite_eq_left hj] + +open Classical in +/-- In the case `none`, this construction gives `[]`. -/ +def body (f : B e → ℕ → Bool) (b : Bool) (l : A) : List Bool := + match S.link b l with + | none => [] + | some (_, n) => List.ofFn fun i : Fin n => + if h : i.val / u < c then f (ix (b, some (l, ⟨i.val / u, h⟩))) (i.val % u) else false + +open Classical in +/-- The output of type `F`, constructed using `List.ofFn fun i : Fin (S.ext b) => f (ix (b, +none)) i`. -/ +def output (f : B e → ℕ → Bool) : F := + let ext b := List.ofFn fun i : Fin (S.ext b) => f (ix (b, none)) i + S.value (ext false) (ext true) (S.body ix u f) + +open Classical in +/-- Builds `Pattern F d 0 e where width _ s` with the specified `width`, `direction`, `peer`, +`value`. -/ +def pattern : Pattern F d 0 e where + width _ s := (S.desc ix u s).1 + direction _ s := (S.desc ix u s).2.1 + peer _ s := (S.desc ix u s).2.2 + value _ t := S.output ix u (fun j k => if h : k < (S.desc ix u j).1 then t j ⟨k, h⟩ else false) + +open Classical in +/-- The indexed operation `{width := fun _ _ => 0, direction := fun _ _ => false, peer := fun _ +_ => none, value := fun _ _ => 1}`. -/ +def vacant [One F] : Pattern F d 0 e := + {width := fun _ _ => 0, direction := fun _ _ => false, peer := fun _ _ => none, value := fun _ _ + => 1} + +open Classical in +theorem active {i : B e} (h : 0 < (S.desc ix u i).1 ∨ (S.desc ix u i).2.2 ≠ none) : + (∃ b, i = ix (b, none)) ∨ + ∃ b l j q n, i = ix (b, some (l, j)) ∧ S.link b l = some (q, n) ∧ j.val < n / u := by + by_cases hi : ∃ s, ix s = i + swap + · simp [desc, Function.extend, hi] at h + obtain ⟨⟨b, _ | ⟨l, j⟩⟩, rfl⟩ := hi + · exact .inl ⟨b, rfl⟩ + · right + rw [desc_band] at h + cases hn : S.link b l with + | none => simp [spec, hn] at h + | some p => + refine ⟨b, l, j, p.1, p.2, rfl, hn, ?_⟩ + by_contra hg + simp [spec, hn, hg] at h + +end Star +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- Construct a seating by assigning addresses to global wire ends. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Assembly + +variable {F : Type} [Field F] {a b : Wire} + (S : Scheme F) (r : S.format.obj) (G : Diagram F a b) + +open Classical in +/-- The data for the seating construction, including `vertex`, `ends`, `station`, `value`, +`empty`. -/ +structure Seating where + /-- The placement of the vertices carried by `Seating`, with type `G.V ↪ S.Vtx`. -/ + vertex : G.V ↪ S.Vtx + /-- The two endpoints of a connection carried by `Seating`, with type `G.End ≃ S.Pin r`. -/ + ends : G.End ≃ S.Pin r + station : ∀ p, (ends p).1.1 = vertex (G.station p) + value : ∀ (t : S.Pin r → Bool) (v : G.V), + S.table r (vertex v) (t ∘ S.port r (vertex v)) = + G.weight v (t ∘ ends ∘ .inl) (t ∘ ends ∘ .inr) + empty : ∀ v ∉ Set.range vertex, ∀ t, S.table r v t = 1 + +namespace Seating +variable {S r G} (H : Seating S r G) (v : G.V) + +omit [Field F] in +open Classical in +theorem port_injective (u : S.Vtx) : Function.Injective (S.port r u) := by + rintro ⟨s, i⟩ ⟨t, j⟩ h + have hs : s = t := congrArg (fun p => p.1.2) h + subst t + have : i = j := Fin.ext (congrArg (fun p => p.2.val) h) + rw [this] + +open Classical in +/-- Bundles the indexing function as an equivalence. -/ +def localSlots : S.LocalPin r (H.vertex v) ≃ {i : S.Pin r // i.1.1 = H.vertex v} := + Equiv.ofBijective (fun i => ⟨S.port r (H.vertex v) i, rfl⟩) + ⟨fun _ _ h => port_injective _ (congrArg Subtype.val h), by + rintro ⟨⟨⟨u, j⟩, l⟩, he⟩ + change u = H.vertex v at he + subst u + exact ⟨⟨j, l⟩, rfl⟩⟩ + +open Classical in +/-- Reindexes `G.Port v` and `S.LocalPin r (H.vertex v)` by an equivalence. -/ +def pin : G.Port v ≃ S.LocalPin r (H.vertex v) := + (G.incident v).trans <| (H.ends.subtypeEquiv (fun _ => by + rw [H.station, H.vertex.injective.eq_iff])).trans (H.localSlots v).symm + +open Classical in +theorem pin_eq (i : G.Port v) : + S.port r (H.vertex v) (H.pin v i) = H.ends (G.portEquiv ⟨v, i⟩) := + congrArg Subtype.val ((H.localSlots v).apply_symm_apply _) + +open Classical in +/-- Builds `S.Seating r G where vertex` with the specified `vertex`, `pin`, `cover`, `obtain`. -/ +def seat : S.Seating r G where + vertex := H.vertex + pin := H.pin + cover j := by + obtain ⟨t, rfl⟩ := H.ends.surjective j + exact ⟨_, (H.station t).symm⟩ + vacant := H.empty + sample v t := by + let f := Function.extend (S.port r (H.vertex v)) t (fun _ => false) + have hf : f ∘ S.port r (H.vertex v) = t := + funext fun i => (port_injective (S := S) (r := r) (H.vertex v)).extend_apply t (fun _ + => false) i + have h := H.value f v + rw [hf] at h + rw [h] + change Transcript.sample (G.table v) (fun i => f (H.ends (G.portEquiv ⟨v, i⟩))) = _ + congr 1 + funext i + rw [← H.pin_eq] + exact congrFun hf _ + +open Classical in +theorem ends_eq : H.seat.ends = H.ends := by + apply Equiv.ext + intro t + obtain ⟨⟨v, i⟩, rfl⟩ := G.portEquiv.surjective t + exact (H.seat.ends_at v i).trans (H.pin_eq v i) + +end Seating +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Terms in the shared-parameter expansion of a product -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Added + +open Sphere + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] {n : ℕ} + +/-- A pole and a list of output energies. Only nonpositive total +Laurent orders are needed. -/ +abbrev Choice (e : Fin n → A ⊕ Unit → ℕ) (M : ℕ) := + {v : A × (Fin n → Fin (2 * n * M + 1)) // + (∑ j, (v.2 j).val) ≤ ∑ j, (e j (.inl v.1) + e j (.inr ()))} + +/-- Contract the two incident inputs with a fusion map and place its +output at the pole. -/ +def term (z : A → F) (e : A ⊕ Unit → ℕ) (i : A) (g : ℕ) (x : States 1 e) : F := + ∑ y : Level 1 g, fusion F (x (.inl i)).val.val (x (.inr ())).val.val y.val.val * + sphereForm z (Function.update (fun j => e (.inl j)) i g) + (Insertion.changeAt i (fun j => x (.inl j)) y) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Added +end + +/- +# Counting nonpositive-order choices + +Weight each output energy geometrically. On the budgeted lists the +product weight is at least one half per factor, while summing over all +energies costs only a linear factor in the average energy budget. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Added + +open Finset + +variable {A : Type} [Fintype A] {n : ℕ} + +private theorem count (q H : ℕ) (ok : A × (Fin n → Fin q) → Prop) [DecidablePred ok] + (budget : ∀ x, ok x → (∑ j, (x.2 j).val) ≤ H * n) : + (Fintype.card {x // ok x} : ℝ) ≤ Fintype.card A * (4 * ((H : ℝ) + 1)) ^ n := by + classical + let b := 2 * ((H : ℝ) + 1) + have hb : 2 ≤ b := by dsimp [b]; linarith + have hb' : 0 < b := by linarith + let r := 1 - b⁻¹ + have h_inv : b⁻¹ ≤ 1 := inv_le_one_of_one_le₀ (by linarith) + have hr : 0 ≤ r := sub_nonneg.mpr h_inv + have hr' : r ≤ 1 := sub_le_self _ (inv_nonneg.mpr hb'.le) + have small : (1 / 2 : ℝ) ≤ r ^ H := by + have e := one_add_mul_le_pow (by linarith : -2 ≤ -b⁻¹) H + have hdiv : (H : ℝ) / b ≤ 1 / 2 := (div_le_iff₀ hb').mpr (by dsimp [b]; linarith) + rw [div_eq_mul_inv] at hdiv + change _ ≤ (1 + -b⁻¹) ^ H + linarith + have series : (∑ j : Fin q, r ^ j.val) ≤ b := by + rw [Fin.sum_univ_eq_sum_range] + have e := geom_sum_mul_neg r q + have h : 1 - r = b⁻¹ := by unfold r; ring + rw [h, ← div_eq_mul_inv] at e + exact (div_le_one hb').mp (by rw [e]; exact sub_le_self _ (pow_nonneg hr _)) + let w (x : A × (Fin n → Fin q)) := r ^ (∑ j, (x.2 j).val) + have low (x) (hx : ok x) : (1 / 2 : ℝ) ^ n ≤ w x := calc + _ ≤ (r ^ H) ^ n := pow_le_pow_left₀ (by norm_num) small _ + _ ≤ w x := by rw [← pow_mul]; exact pow_le_pow_of_le_one hr hr' (budget x hx) + have high : (∑ x, w x) ≤ (Fintype.card A : ℝ) * b ^ n := by + simp only [Fintype.sum_prod_type, w, ← prod_pow_eq_pow_sum] + rw [← Fintype.prod_sum (fun (_ : Fin n) (i : Fin q) => r ^ i.val)] + simp only [sum_const, prod_const, card_univ, Fintype.card_fin, nsmul_eq_mul] + exact mul_le_mul_of_nonneg_left + (pow_le_pow_left₀ (sum_nonneg fun _ _ => pow_nonneg hr _) series _) (Nat.cast_nonneg _) + let S := univ.filter ok + have h : (Fintype.card {x // ok x} : ℝ) * (1 / 2 : ℝ) ^ n ≤ (Fintype.card A : ℝ) * b ^ n := calc + _ = ∑ _ ∈ S, (1 / 2 : ℝ) ^ n := by simp [S, Fintype.card_subtype] + _ ≤ ∑ x ∈ S, w x := sum_le_sum fun x hx => low x (mem_filter.mp hx).2 + _ ≤ ∑ x, w x := sum_le_sum_of_subset_of_nonneg (subset_univ _) fun _ _ _ => pow_nonneg hr _ + _ ≤ _ := high + calc + _ ≤ ((Fintype.card A : ℝ) * b ^ n) / (1 / 2 : ℝ) ^ n := (le_div_iff₀ (by positivity)).mpr h + _ = _ := by rw [mul_div_assoc, ← div_pow]; congr 2; unfold b; ring + +theorem card_choice (e : Fin n → A ⊕ Unit → ℕ) (M : ℕ) (hn : 0 < n) (he : ∀ j i, e j i ≤ M) : + (Fintype.card (Choice e M) : ℝ) ≤ (((M : ℝ) + 2) ^ (Fintype.card A + 8)) ^ n := by + have h : (Fintype.card (Choice e M) : ℝ) ≤ Fintype.card A * (4 * ((2 * M : ℕ) + 1 : ℝ)) ^ n := by + apply count + intro x hx + apply hx.trans + calc + _ ≤ ∑ _ : Fin n, 2 * M := sum_le_sum fun j _ => by + have h₁ := he j (.inl x.1) + have h₂ := he j (.inr ()) + omega + _ = _ := by simp [mul_comm] + let t := (M : ℝ) + 2 + have ht : 2 ≤ t := by unfold t; linarith + have ht' : 1 ≤ t := by linarith + have h₁ : (Fintype.card A : ℝ) ≤ t ^ Fintype.card A := + le_trans (by exact_mod_cast (Nat.lt_two_pow_self (n := Fintype.card A)).le) + (pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 2) ht _) + have h₂ : 4 * ((2 * M : ℕ) + 1 : ℝ) ≤ t ^ 8 := calc + _ ≤ t * 2 ^ 7 := by dsimp [t]; push_cast; linarith + _ ≤ t * t ^ 7 := mul_le_mul_of_nonneg_left (pow_le_pow_left₀ (by norm_num) ht _) (by linarith) + _ = _ := by ring + rw [pow_add, mul_pow] + refine h.trans (mul_le_mul ?_ (pow_le_pow_left₀ (by positivity) h₂ _) (by positivity) (by + positivity)) + exact h₁.trans (le_self_pow₀ (one_le_pow₀ ht') hn.ne') + +variable [DecidableEq A] {e : Fin n → A ⊕ Unit → ℕ} {M : ℕ} + +/-- Replaces the value at one index and retains all other entries. -/ +def reassigned (v : Choice e M) (j : Fin n) : A → ℕ := + Function.update (fun i => e j (.inl i)) v.val.1 (v.val.2 j).val + +/-- A common collision site allows the energy of one factor to pay for +another, even with different penalties at the different sites. -/ +theorem penalty (B : ℝ) (t : A ⊕ Unit → ℝ) + (ht : ∀ i, 0 ≤ t i ∧ t i ≤ t (.inr ())) (v : Choice e M) : + (∑ j, (B + ∑ i, t (.inl i) * (reassigned v j i : ℝ))) ≤ + ∑ j, (B + ∑ i, t i * (e j i : ℝ)) := by + let a := v.val.1 + let rest j := B + ∑ i ∈ univ.erase a, t (.inl i) * (e j (.inl i) : ℝ) + have left (j : Fin n) : B + ∑ i, t (.inl i) * (reassigned v j i : ℝ) = + rest j + t (.inl a) * (v.val.2 j).val := by + rw [← sum_erase_add _ _ (mem_univ a), ← add_assoc] + have h : reassigned v j a = (v.val.2 j).val := Function.update_self _ _ _ + rw [h] + congr 2 + apply sum_congr rfl + intro i hi + rw [reassigned, Function.update_of_ne (mem_erase.mp hi).1] + have right (j : Fin n) : + rest j + t (.inl a) * ((e j (.inl a) + e j (.inr ()) : ℕ) : ℝ) ≤ + B + ∑ i, t i * (e j i : ℝ) := by + rw [Fintype.sum_sum_type, Fintype.sum_unique (ι := Unit), ← sum_erase_add _ _ (mem_univ a)] + unfold rest + have h := mul_le_mul_of_nonneg_right (ht (.inl a)).2 (Nat.cast_nonneg (α := ℝ) (e j (.inr ()))) + push_cast + linarith + simp_rw [left] + refine le_trans ?_ (sum_le_sum (fun j _ => right j)) + simp only [sum_add_distrib, ← mul_sum, ← Nat.cast_sum] + exact add_le_add le_rfl (mul_le_mul_of_nonneg_left (Nat.cast_le.mpr (by simpa only + [sum_add_distrib] using v.property)) (ht _).1) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Added +end + +/- # Locating a fusion map at the site of the collision -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Added + +open Finset Sphere Spectral + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + +omit [DecidableEq A] in +/-- A sum ranging over one site's internal states is a local restriction +when the other sites' input coordinates are independent of that state. -/ +private theorem local_sum {I : Type} [Fintype I] (U V : Raw F A) (i : A) + (c : V.leg i → I → F) (f : ∀ j, V.leg j → I → U.leg j) + (hi : ∀ j ≠ i, ∀ x a b, f j x a = f j x b) + (he : ∀ x, V.coeff x = ∑ a, c (x i) a * U.coeff (fun j => f j (x j) a)) : + U.Restricts V := by + classical + cases isEmpty_or_nonempty I with + | inl h => + exact (Raw.Restricts.zero U).trans ((Raw.zero_restricts_iff _).mpr (by simp [he])) + | inr h => + let b := Classical.arbitrary I + let L (j : A) : V.leg j → U.leg j → F := + Function.update (fun j x y => if y = f j x b then (1 : F) else 0) i + (fun x y => ∑ a, if y = f i x a then c x a else 0) j + refine ⟨L, fun x => ?_⟩ + have cent (t : U.term) : + (∑ y, L i (x i) y * U.factor t i y) = ∑ a, c (x i) a * U.factor t i (f i (x i) a) := by + simp only [L, Function.update_self, sum_mul] + rw [sum_comm] + simp [ite_mul] + have tail (t : U.term) (a : I) : + (∏ j ∈ univ.erase i, ∑ y, L j (x j) y * U.factor t j y) = + ∏ j ∈ univ.erase i, U.factor t j (f j (x j) a) := by + apply prod_congr rfl + intro j hj + have hn := (mem_erase.mp hj).1 + simp [L, hn, ite_mul, hi j hn (x j) b a] + rw [he] + simp only [Raw.coeff, mul_sum] + rw [sum_comm] + apply sum_congr rfl + intro t _ + rw [← mul_prod_erase _ _ (mem_univ i), cent, sum_mul] + apply sum_congr rfl + intro a _ + rw [tail t a, ← mul_prod_erase _ _ (mem_univ i), mul_assoc] + +theorem place_term (z : A → F) (e : A ⊕ Unit → ℕ) (i : A) (g : ℕ) : + Tensor.place (Sum.elim id (fun _ => i)) + (Tensor.ofRaw (Raw.ofTable (fun j => Level 1 (e j)) (term z e i g))) ≤ + sphereTensor z (Function.update (fun j => e (.inl j)) i g) := by + classical + let loc : A ⊕ Unit → A := Sum.elim id (fun _ => i) + let e' := Function.update (fun j => e (.inl j)) i g + let U := Raw.ofTable (fun j => Level 1 (e' j)) (sphereForm z e') + let V := (Raw.ofTable (fun j => Level 1 (e j)) (term z e i g)).group loc + let fromOld (j : A) (x : V.leg j) : Level 1 (e (.inl j)) := x ⟨.inl j, rfl⟩ + let fromNew (x : V.leg i) : Level 1 (e (.inr ())) := x ⟨.inr (), rfl⟩ + let c (x : V.leg i) (w : Level 1 g) := + fusion F (fromOld i x).val.val (fromNew x).val.val w.val.val + let f (j : A) (x : V.leg j) (w : Level 1 g) : Level 1 (e' j) := + ⟨if j = i then w.val else (fromOld j x).val, by + by_cases h : j = i + · subst j; simpa [e'] using w.2 + · simpa [h, e'] using (fromOld j x).2⟩ + change U.Restricts V + apply local_sum U V i c f + · intro j hj x a b + exact Subtype.ext (by simp [f, hj]) + · intro x + unfold V U + erw [Raw.coeff_group, Raw.coeff_ofTable] + unfold term + apply sum_congr rfl + intro y _ + erw [Raw.coeff_ofTable] + congr 2 + funext j + exact Subtype.ext (Insertion.changeAt_val i (fun l => fromOld l (x l)) y j) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Added +end + +/- +# Principal parts of a product of sphere forms + +All factors use one moving position. Nonpositive total Laurent order +at one pole implies an additive bound on the sum of fused energies. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Added + +open Finset Polynomial Sphere Sphere.Motion +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] + +open scoped Classical in +private def word (z : A → F) (i : A) {e : A ⊕ Unit → ℕ} (x : States 1 e) := + triple (Insertion.mark z i) (x (.inl i)).val.val (x (.inr ())).val.val + (Insertion.rest z i (fun j => x (.inl j))) + +open scoped Classical in +private def bound (e : A ⊕ Unit → ℕ) := ((∑ i, e (.inl i)) + e (.inr ())) / 2 + +omit [Field F] in +open scoped Classical in +private theorem weight_word (z : A → F) (i : A) {e : A ⊕ Unit → ℕ} (x : States 1 e) : + weight (word z i x) / 2 = bound e := by + rw [word, weight_triple, (x (.inl i)).property, (x (.inr ())).property, Insertion.weight_rest] + unfold bound + have := Finset.sum_erase_add univ (fun j => e (.inl j)) (mem_univ i) + omega + +open scoped Classical in +private theorem value_word (z : A → F) (i : A) (e : A ⊕ Unit → ℕ) : + ∃ c : F, ∀ s x, sphereForm (Sum.elim z (fun _ => s)) e x = + c * wick fieldKernel ((word z i x).map (atPoint s)) := by + obtain ⟨b, m, rfl⟩ : ∃ b m, e = Insertion.energy b m := by + refine ⟨fun i => e (.inl i), e (.inr ()), funext ?_⟩ + rintro (j|⟨⟩) <;> rfl + obtain ⟨c, _, hc⟩ := Insertion.order_added z i b m + refine ⟨c, fun s x => ?_⟩ + have he : Insertion.add (e := b) (g := m) (fun j => x (.inl j)) (x (.inr ())) = x := by + funext j + rcases j with j|⟨⟩ <;> rfl + have h := hc s (fun j => x (.inl j)) (x (.inr ())) + rw [he] at h + exact h + +open scoped Classical in +private def level (e : A ⊕ Unit → ℕ) (i : A) (u : ℕ) : ℤ := + e (.inl i) + e (.inr ()) + 2 * ((u : ℤ) - bound e) + +open scoped Classical in +private theorem jet_term (z : A → F) (hz : Function.Injective z) (i : A) + (e : A ⊕ Unit → ℕ) (u : ℕ) : + let g := level e i u + let Z := Insertion.marks z + ∃ c : F, ∀ x : States 1 e, + jet (z i) (poles (Z.erase (z i)) (fun _ => bound e)) u (numerator Z (word z i x)) = + if g < 0 then 0 else c * term z e i g.toNat x := by + intro g Z + obtain ⟨c, hc, hf⟩ := Insertion.order_base z i (Function.update (fun j => e (.inl j)) i g.toNat) + refine ⟨c⁻¹, fun x => ?_⟩ + have h := coeff_fusion (Insertion.mark z i) (x (.inl i)).val.val (x (.inr ())).val.val + (Insertion.rest z i (fun j => x (.inl j))) (Insertion.rest_avoids z hz i _) ((u : ℤ) - bound e) + dsimp only at h + rw [(x (.inl i)).property, (x (.inr ())).property] at h + change (laurent (z i) (numerator Z (word z i x)) (denominatorPoly Z (word z i x))).coeff _ = + if g < 0 then 0 else _ at h + rw [denominatorPoly, weight_word, poles_split _ (show z i ∈ Z from (Insertion.mark z i).property), + coeff_laurent _ _ _ _ (poles_eval _ (notMem_erase _ _))] at h + rw [h] + split_ifs + · rfl + unfold term + rw [Finset.mul_sum] + refine Finset.sum_congr rfl fun y _ => ?_ + erw [hf, Insertion.changeAt_val, ite_eq_left rfl, Insertion.rest_changeAt] + unfold outcome + rw [mul_left_comm, ← mul_assoc c⁻¹, inv_mul_cancel₀ hc, one_mul] + rfl + +variable {n : ℕ} + +omit [DecidableEq A] in +open scoped Classical in +private theorem choose_levels (e : Fin n → A ⊕ Unit → ℕ) (M : ℕ) (he : ∀ j i, e j i ≤ M) + (i : A) (v : Fin n → ℕ) (hv : (∑ j, v j) ≤ ∑ j, bound (e j)) + (h : ∀ j, 0 ≤ level (e j) i (v j)) : + ∃ y : Choice e M, y.val.1 = i ∧ ∀ j, (y.val.2 j).val = (level (e j) i (v j)).toNat := by + let g j := (level (e j) i (v j)).toNat + let k j := e j (.inl i) + e j (.inr ()) + have eqn (j) : (g j : ℤ) = k j + 2 * ((v j : ℤ) - bound (e j)) := by + dsimp only [g] + rw [Int.toNat_of_nonneg (h j)] + simp only [k, level, Nat.cast_add] + have lim : (∑ j, g j) ≤ ∑ j, k j := by + have hh : (∑ j, (g j : ℤ)) ≤ ∑ j, (k j : ℤ) := by + simp only [eqn, sum_add_distrib, ← mul_sum, sum_sub_distrib, ← Nat.cast_sum] + omega + exact_mod_cast hh + have total : (∑ j, k j) ≤ 2 * n * M := calc + _ ≤ ∑ _ : Fin n, (M + M) := sum_le_sum fun j _ => Nat.add_le_add (he j _) (he j _) + _ = _ := by simp; ring + have each (j) : g j ≤ 2 * n * M := + (single_le_sum (fun i _ => Nat.zero_le (g i)) (mem_univ j)).trans (lim.trans total) + exact ⟨⟨(i, fun j => ⟨g j, Nat.lt_succ_of_le (each j)⟩), lim⟩, rfl, fun _ => rfl⟩ + +open scoped Classical in +/-- Expand a product at one common moving position, with coefficients +independent of all basis states. -/ +theorem principal [Nonempty A] (z : A → F) (hz : Function.Injective z) (s : F) (hs : s ∉ Set.range + z) + (e : Fin n → A ⊕ Unit → ℕ) (M : ℕ) (he : ∀ j i, e j i ≤ M) : + ∃ coeff : Choice e M → F, ∀ x : (j : Fin n) → States 1 (e j), + (∏ j, sphereForm (Sum.elim z (fun _ => s)) (e j) (x j)) = + ∑ v, coeff v * ∏ j, term z (e j) v.val.1 (v.val.2 j).val (x j) := by + let Z := Insertion.marks z + have hs' : s ∉ Z := by simpa [Z, Insertion.marks, Set.mem_range] using hs + let i₀ : A := Classical.arbitrary A + choose P hP using fun j => Insertion.order_polynomial z (e j) + choose t ht hp using hP + have pn (j i x) : P j x = C (t j i) * numerator Z (word z i x) := hp j i x + let X := (j : Fin n) → States 1 (e j) + let val (v : Choice e M) (x : X) := ∏ j, term z (e j) v.val.1 (v.val.2 j).val (x j) + let W := Submodule.span F (Set.range val) + have mem : (fun x : X => ∏ j, (P j (x j)).eval s / (poles Z (fun _ => bound (e j))).eval s) ∈ W + := by + apply product_mem W Z ⟨_, (Insertion.mark z i₀).property⟩ + · intro j x + rw [pn j i₀, natDegree_C_mul (ht j i₀)] + rw [← weight_word z i₀ (x j)] + simpa [denominatorPoly, degree_poles] using degree_numerator Z (word z i₀ (x j)) + intro y hy u hu + obtain ⟨i, _, rfl⟩ := mem_image.mp hy + choose b hb using fun j => jet_term z hz i (e j) (u j) + let Q j := poles (Z.erase (z i)) (fun _ => bound (e j)) + have key (j) (x : X) : jet (z i) (Q j) (u j) (P j (x j)) = + if level (e j) i (u j) < 0 then 0 + else t j i * b j * term z (e j) i (level (e j) i (u j)).toNat (x j) := by + rw [pn j i, ← Polynomial.smul_eq_C_mul, map_smul, hb j (x j)] + simp only [smul_eq_mul, mul_ite, mul_zero, mul_assoc] + change (fun x : X => ∏ j, jet (z i) (Q j) (u j) (P j (x j))) ∈ W + by_cases pos : ∀ j, 0 ≤ level (e j) i (u j) + · obtain ⟨v, hv, hv'⟩ := choose_levels e M he i u hu pos + have hval : val v ∈ W := Submodule.subset_span ⟨v, rfl⟩ + convert W.smul_mem (∏ j, t j i * b j) hval using 1 + funext x + simp only [key, not_lt.mpr (pos _), ite_false, Pi.smul_apply, smul_eq_mul, val, hv, hv', + prod_mul_distrib] + · push Not at pos + obtain ⟨j, hj⟩ := pos + convert W.zero_mem using 1 + funext x + exact prod_eq_zero (mem_univ j) (by rw [key, ite_eq_left hj]) + choose c hc using fun j => value_word z i₀ (e j) + have target : (fun x : X => ∏ j, sphereForm (Sum.elim z (fun _ => s)) (e j) (x j)) ∈ W := by + convert W.smul_mem (∏ j, c j / t j i₀) mem using 1 + funext x + simp only [Pi.smul_apply, smul_eq_mul, ← prod_mul_distrib] + apply prod_congr rfl + intro j _ + rw [hc j s (x j), ← eval_sphere Z _ s hs', pn j i₀, eval_mul, eval_C, denominatorPoly, + weight_word] + rw [mul_div_assoc, ← mul_assoc, div_mul_cancel₀ _ (ht j i₀)] + obtain ⟨k, hk⟩ := (Submodule.mem_span_range_iff_exists_fun F).mp target + refine ⟨k, fun x => ?_⟩ + simpa only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul, val] using (congrFun hk x).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Added +end + +/- +# Closing a product of spheres at a shared insertion + +Expand the product in nonpositive Laurent orders at one of the original +marks. For each term, any closed restriction costs at most the product +with updated energies at that single site. The number of terms costs +only a polynomial factor per sphere. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing +open Sphere Spectral Finset + +namespace Added + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] {n : ℕ} + +private theorem price_product (f : Tensor F A →+* ℝ) (hf : Monotone f) (z : A → F) + (B : ℝ) (t : A ⊕ Unit → ℝ) (ht : ∀ i, 0 ≤ t i ∧ t i ≤ t (.inr ())) + (hbase : ∀ e, f (sphereTensor z e) ≤ Real.exp (B + ∑ i, t (.inl i) * (e i : ℝ))) + (s : F) (M : ℕ) (e : Fin n → A ⊕ Unit → ℕ) (hn : 0 < n) (he : ∀ j i, e j i ≤ M) + (T : Tensor F A) + (hT : Tensor.pad Unit T ≤ ∏ j, sphereTensor (Sum.elim z (fun _ => s)) (e j)) + (c : Choice e M → F) + (hc : ∀ x : (j : Fin n) → States 1 (e j), + (∏ j, sphereForm (Sum.elim z (fun _ => s)) (e j) (x j)) = + ∑ v, c v * ∏ j, term z (e j) v.val.1 (v.val.2 j).val (x j)) : + f T ≤ ∏ j, (((M : ℝ) + 2) ^ (Fintype.card A + 8) * Real.exp (B + ∑ i, t i * (e j i : ℝ))) := by + classical + let J := Choice e M + let X (j : Fin n) i := Level 1 (e j i) + let U (v : J) (j : Fin n) := + Tensor.ofRaw (Raw.ofTable (X j) (term z (e j) v.val.1 (v.val.2 j).val)) + let loc (v : J) : A ⊕ Unit → A := Sum.elim id (fun _ => v.val.1) + have hp : Tensor.pad Unit T ≤ ∑ v, ∏ j, U v j := + hT.trans (Tensor.product_span_le X _ _ c hc) + have bound := Tensor.padded_sum_le (fun v => ∏ j, U v j) (fun v => v.val.1) T hp + let E := Real.exp (∑ j, (B + ∑ i, t i * (e j i : ℝ))) + have each (v : J) : f (Tensor.place (loc v) (∏ j, U v j)) ≤ E := by + have hs : Function.Surjective (loc v) := fun i => ⟨.inl i, rfl⟩ + rw [Tensor.place_eq_group _ hs, map_prod, map_prod] + calc + _ ≤ ∏ j, Real.exp (B + ∑ i, t (.inl i) * (reassigned v j i : ℝ)) := by + apply prod_le_prod₀ + · intro j _ + rw [← map_zero f] + exact hf (Tensor.zero_le _) + · intro j _ + rw [← Tensor.place_eq_group] + exact (hf (place_term z (e j) _ _)).trans (hbase _) + _ ≤ E := by rw [← Real.exp_sum]; exact Real.exp_le_exp.mpr (penalty B t ht v) + calc + f T ≤ ∑ v, f (Tensor.place (loc v) (∏ j, U v j)) := by rw [← map_sum]; exact hf bound + _ ≤ (Fintype.card J : ℝ) * E := by + simpa using sum_le_sum (s := univ) (fun v _ => each v) + _ ≤ (((M : ℝ) + 2) ^ (Fintype.card A + 8)) ^ n * E := + mul_le_mul_of_nonneg_right (card_choice e M hn he) (Real.exp_pos _).le + _ = _ := by + simp only [prod_mul_distrib, prod_const, card_univ, Fintype.card_fin, E, Real.exp_sum] + +end Added + +/-- Joint closure of an arbitrary list of sphere forms at one shared +parameter. The polynomial surcharge depends only on the old site count +and the maximum incident energy. -/ +theorem bounded_forms (F : Type) [Field F] : BoundedForms F := by + intro A _ _ _ f hf z hz B t ht hbase s hs M w hw T hT + by_cases hempty : w = [] + · subst w + simp only [List.map_nil, List.prod_nil] at hT ⊢ + rw [← (Tensor.padding Unit).one] at hT + rw [← map_one f] + exact hf (((Tensor.padding Unit).le_iff _ _).mp hT) + have hn := List.length_pos_of_ne_nil hempty + have he : ∀ j i, w.get j i ≤ M := fun j => hw _ (w.get_mem j) + obtain ⟨c, hc⟩ := Added.principal z hz s hs w.get M he + rw [← List.ofFn_get w, List.map_ofFn] at hT ⊢ + erw [List.prod_ofFn] at hT ⊢ + exact Added.price_product f hf z B t ht hbase s M w.get hn he T hT c hc + +end MatrixMultiplicationAllFields.MatrixExponent.Routing +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Shows.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Shows.lean new file mode 100644 index 0000000000..9a75736576 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Shows.lean @@ -0,0 +1,996 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Wiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Presentation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Template.Presents +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Correct +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Terminal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Traces + +/-! # A uniform dictionary for terminal station and relay tables -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Coloring Assembly Surface.Local + +open scoped Classical in +/-- The data for the printer construction, including `menu`, `dyadic`, `large`, `chunks`, +`degree`. -/ +structure Printer (F K N : Type) (m d h ℓ M r t q D k n u j z : ℕ) where + /-- The `Printer` component of type `B ℓ → Option (Face F (M * r) (M * t) q K N)`. -/ + menu : B ℓ → Option (Face F (M * r) (M * t) q K N) + dyadic : D = 2 ^ n + large : 4 ≤ D + chunks : M ≤ D ^ k + degree : 2 ^ ((d + 1) * 1) ≤ D ^ k + 1 + /-- The capacity bound. -/ + cap : ℕ + pos : 0 < u + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def indexBits (A : Type) := Nat.clog 2 (Nat.card A) + +open scoped Classical in +/-- Embeds `A` into `B (indexBits A)`. -/ +def indexCode (A : Type) [Finite A] : A ↪ B (indexBits A) := by + letI := Fintype.ofFinite A + apply Classical.choice + apply Function.Embedding.nonempty_of_card_le + simp only [B, indexBits, Fintype.card_fin, Nat.card_eq_fintype_card] + exact Nat.le_pow_clog (by decide) _ + +namespace Printer +variable {F K N : Type} {m d h ℓ M r t q D k n u j z : ℕ} + (P : Printer F K N m d h ℓ M r t q D k n u j z) + +open scoped Classical in +/-- The quantity computed by `z * M * (q + 2 * (2 * D ^ k))`. -/ +abbrev digits (_ : Printer F K N m d h ℓ M r t q D k n u j z) := z * M * (q + 2 * (2 * D ^ k)) +open scoped Classical in +/-- Computes the part by the application `Children.Part M D k n`. -/ +abbrev part (_ : Printer F K N m d h ℓ M r t q D k n u j z) := Children.Part M D k n +open scoped Classical in +/-- Computes the lane by the application `Compass.FinalLane (Fin q) K M D k n`. -/ +abbrev lane (_ : Printer F K N m d h ℓ M r t q D k n u j z) := Compass.FinalLane (Fin q) K M D k n +open scoped Classical in +/-- Computes the child bits by the application `indexBits P.part`. -/ +abbrev childBits := indexBits P.part +open scoped Classical in +/-- Computes the span bits by the application `indexBits (Band P.lane P.cap)`. -/ +abbrev spanBits := indexBits (Band P.lane P.cap) +open scoped Classical in +/-- The value specified by `Fmt.wave d 1 1 (.addr ℓ) (.addr P.digits)`. -/ +abbrev window := Fmt.wave d 1 1 (.addr ℓ) (.addr P.digits) +open scoped Classical in +/-- The quantity computed by `P.window.width + P.childBits`. -/ +abbrev labelBits := P.window.width + P.childBits +open scoped Classical in +/-- Computes the selectors by the application `Format.vec m (.vec h (.addr P.digits))`. -/ +abbrev selectors := Format.vec m (.vec h (.addr P.digits)) +open scoped Classical in +/-- The value specified by `Fmt.rows m d h (.addr ℓ)`. -/ +abbrev rows (_ : Printer F K N m d h ℓ M r t q D k n u j z) := Fmt.rows m d h (.addr ℓ) + +open scoped Classical in +theorem window_width : P.window.width = 2 ^ ((d + 1) * 1) * (2 ^ ((d + 1) * 1) * (ℓ + P.digits)) + := by + simp only [window, Fmt.wave, Fmt.view, Format.width_vec, Format.width_pair, Format.width_addr] + +include P in +open scoped Classical in +theorem positive : 0 < D ^ k := pow_pos (lt_of_lt_of_le (by decide) P.large) k + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def ballot : Ballot M q D k z ≃ B P.digits := + Fintype.equivOfCardEq (by simp [B, Ballot, Axis, Number, Digits, digits, pow_mul]) + +open scoped Classical in +/-- Computes the slot by the application `indexCode P.part`. -/ +abbrev slot := indexCode P.part +open scoped Classical in +/-- Computes the ix by the application `indexCode (Band P.lane P.cap)`. -/ +abbrev ix [Finite K] := indexCode (Band P.lane P.cap) + +open scoped Classical in +/-- Evaluates `(P.menu (v a b).1, P.ballot.symm (v a b).2)` at the input `a b`. -/ +def view (v : P.window.obj) : Lens F K N M r t q D k z d := + fun a b => (P.menu (v a b).1, P.ballot.symm (v a b).2) + +open scoped Classical in +/-- The value specified by `(P.view v).score P.positive`. -/ +def tariff [Field F] (v : P.window.obj) : F := (P.view v).score P.positive + +open scoped Classical in +/-- Uses `⟨p.1, p.2, wiring P.dyadic P.large P.chunks P.degree P.slot v.tone, lift (Prod.mk +p.1.mark) c⟩` as the representation. -/ +def request (v : Lens F K N M r t q D k z d) (c : P.part) + (p : Page F (Fin q) (Number D k) K M r t) : + Request F (Fin q) (Number D k) K M r t (Layout.Sharing.radius k * n) (Children.degree d + P.childBits) := + ⟨p.1, p.2, wiring P.dyadic P.large P.chunks P.degree P.slot v.tone, lift (Prod.mk p.1.mark) c⟩ + +open scoped Classical in +/-- The indexed operation `(v.page P.positive).bind fun s => (P.request v c s).emit j u`. -/ +def send [Field F] (v : Lens F K N M r t q D k z d) (c : P.part) := + (v.page P.positive).bind fun s => (P.request v c s).emit j u + +open scoped Classical in +/-- The read of type `Option (Star F P.lane (Children.degree d P.childBits))`, constructed using +`Match.rowIndex _ _ v`. -/ +def read [Field F] (v : B P.labelBits) : Option (Star F P.lane (Children.degree d P.childBits)) := + let p := Match.rowIndex _ _ v + Function.extend P.slot (P.send (P.view ((Design.number P.window).symm p.1))) (fun _ => none) p.2 + +variable [Field F] [Finite K] + +open scoped Classical in +/-- The quantity computed by `m + P.childBits d := Children.degree d P.childBits h := h e := +P.spanBits ℓ := P.labelBits`. -/ +def engine : Engine F P.lane where + m := m + P.childBits + d := Children.degree d P.childBits + h := h + e := P.spanBits + ℓ := P.labelBits + cap := P.cap + ix := P.ix + decode x := ((P.read x).map fun a => a.pattern P.ix u).getD Star.vacant + +open scoped Classical in +/-- Builds `Assembly.Template F where scheme` with the specified `scheme`, `count`, `load`, +`park`. -/ +abbrev template : Assembly.Template F where + scheme := P.engine.scheme + count := P.labelBits + load x := if (P.read x).isSome then (∑ i, (P.engine.decode x).width 0 i : ℕ) + (u : ℝ) else 0 + park _ := 0 + past _ := 0 + order := Equiv.refl _ + +open scoped Classical in +/-- Computes the split by the application `Match.rowIndex _ _`. -/ +abbrev split : B P.template.scheme.m ≃ B m × B P.childBits := Match.rowIndex _ _ + +open scoped Classical in +/-- Embeds `Bool` into `B P.template.scheme.e`. -/ +def outer : Bool ↪ B P.template.scheme.e := + ⟨fun b => P.ix (b, none), fun _ _ h => congrArg Prod.fst (P.ix.injective h)⟩ + +end Printer +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # The counter records exactly the charge of an occupied site -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Rounds + +variable {F K N : Type} [Field F] [Finite K] {m d h ℓ M r t q D k n u j z : ℕ} + (U : Printer F K N m d h ℓ M r t q D k n u j z) + +variable {x y : Wire} {G : Diagram F x y} {r' : U.template.format.obj} + (p : U.template.scheme.Presentation r'.1 G) + +open scoped Classical in +private theorem load_arity (v : G.V) (hv : (U.read ((r'.1 (p.vertex v).1).2 (p.vertex + v).2.1)).isSome) : + U.template.load ((r'.1 (p.vertex v).1).2 (p.vertex v).2.1) = G.arity v + (u : ℝ) := by + have hh := Fintype.card_congr (p.pin v) + simp only [Diagram.Port, Scheme.LocalPin, Fintype.card_sigma, Fintype.card_sum, card_slots, + Fintype.card_fin] at hh + change G.arity v = ∑ s, U.template.scheme.width r'.1 (p.vertex v, s) at hh + have hz : (p.vertex v).2.2 = 0 := Fin.eq_zero _ + rw [hh] + change (if (U.read _).isSome then _ else 0) = _ + rw [ite_eq_left hv] + simp only [Scheme.width, hz] + rfl + +open scoped Classical in +theorem amount (charge : G.V → ℝ) (hc : ∀ v, charge v = G.arity v + (u : ℝ)) + (copy : ∀ i j, U.template.counter r' i j = (r'.1 i).2 j) + (live : ∀ v, (U.read ((r'.1 (p.vertex v).1).2 (p.vertex v).2.1)).isSome) + (idle : ∀ v ∉ Set.range p.vertex, U.read ((r'.1 v.1).2 v.2.1) = none) + (i : B U.template.scheme.m) (j : B U.template.scheme.h) : + U.template.load (U.template.counter r' i j) = + ∑ v, if (p.vertex v).1 = i ∧ (p.vertex v).2.1 = j then charge v else 0 := by + rw [copy] + let q : U.template.scheme.Vtx := (i, j, 0) + have he (v : G.V) : (p.vertex v).1 = i ∧ (p.vertex v).2.1 = j ↔ p.vertex v = q := + ⟨fun hx => Prod.ext hx.1 (Prod.ext hx.2 (Fin.eq_zero _)), fun h => by rw [h]; exact ⟨rfl, rfl⟩⟩ + simp only [he] + by_cases hq : q ∈ Set.range p.vertex + · obtain ⟨v, hv⟩ := hq + have h := U.load_arity p v (live v) + rw [hv] at h + simp only [← hv, p.vertex.injective.eq_iff, Finset.sum_ite_eq', Finset.mem_univ, ite_true, hc] + exact h + · have hv : U.read ((r'.1 i).2 j) = none := idle q hq + change (if (U.read _).isSome then _ else 0) = _ + rw [hv] + symm + exact Finset.sum_eq_zero (fun v _ => ite_eq_right (fun he => hq ⟨v, he⟩)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # The record and scalar computed by a printer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Coloring Assembly Surface.Local + +variable {F K N : Type} {m d h ℓ M r t q D k n u j z : ℕ} + (U : Printer F K N m d h ℓ M r t q D k n u j z) + (data : U.rows.obj) (status : (Children.Header m d).obj) (choice : U.selectors.obj) + +open scoped Classical in +/-- The value specified by `Fmt.around 1 1 (show (Fmt.waveIn m d h (.addr ℓ) (.addr +U.digits)).obj from (data, choice))`. -/ +def around := + Fmt.around 1 1 (show (Fmt.waveIn m d h (.addr ℓ) (.addr U.digits)).obj from (data, choice)) + +open scoped Classical in +/-- The value specified by `(Fmt.update (D := .addr U.window.width) (Design.number U.window) +(U.around data choice), status)`. -/ +def update : (Children.input m d h U.window.width).obj := + (Fmt.update (D := .addr U.window.width) (Design.number U.window) (U.around data choice), status) + +open scoped Classical in +/-- Computes the score by the application `Fmt.weight U.tariff (U.around data choice)`. -/ +def score [Field F] : F := Fmt.weight U.tariff (U.around data choice) + +open scoped Classical in +/-- Computes the advance by the application `Children.write U.slot U.dyadic U.large U.chunks +U.degree (U.update data status choice)`. -/ +def advance [Field F] [Finite K] : U.template.format.obj := + Children.write U.slot U.dyadic U.large U.chunks U.degree (U.update data status choice) + +open scoped Classical in +/-- The value specified by `weightTable (D := .addr U.window.width) (Design.number U.window) +U.tariff`. -/ +def gate [Field F] := weightTable (D := .addr U.window.width) (Design.number U.window) U.tariff + +open scoped Classical in +/-- Reindexes `((B m × B h) × Axis (Fin q) (Number D k) → Digits M z)` and `U.selectors.obj +where toFun v i l` by an equivalence. -/ +def pack : ((B m × B h) × Axis (Fin q) (Number D k) → Digits M z) ≃ U.selectors.obj where + toFun v i l := U.ballot (fun x => v ((i, l), x)) + invFun v i := U.ballot.symm (v i.1.1 i.1.2) i.2 + left_inv v := funext fun i => congrFun (U.ballot.symm_apply_apply (fun x => v (i.1, x))) i.2 + right_inv v := funext fun i => funext fun l => U.ballot.apply_symm_apply (v i l) + +open scoped Classical in +/-- Computes the ballots by the application `U.ballot.symm (choice i.1 i.2)`. -/ +def ballots (i : B m × B h) := U.ballot.symm (choice i.1 i.2) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # From the indexed input tape to colored local views -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Surface.Local + +variable {F K N V E : Type} {m d h ℓ M r t q D k n u j z : ℕ} + (U : Printer F K N m d h ℓ M r t q D k n u j z) + (data : U.rows.obj) (a : Atlas V E m d h) (f : V → Face F (M * r) (M * t) q K N) + +open scoped Classical in +/-- The data for the receives construction, including `graph`, `labels`. -/ +structure Receives : Prop where + graph : ∀ i, (data i).1 = a.graph i + labels : ∀ i, U.menu ((data i.1).2 i.2) = a.fill f i + +namespace Receives +variable {U data a f} (H : U.Receives data a f) + (status : (Children.Header m d).obj) (c : U.selectors.obj) +include H + +open scoped Classical in +theorem tape : Children.tape (U.update data status c) = (a.graph, status) := by + refine Prod.ext ?_ rfl + exact funext H.graph + +open scoped Classical in +theorem view (v : B m × B h) : + U.view (((U.around data c) v.1).2 v.2) = lens a f (U.ballots c) v := by + funext i l + let w := a.around 1 (a.around 1 v i) l + have eq : ((U.around data c) v.1).2 v.2 i l = ((data w.1).2 w.2, c w.1 w.2) := by + unfold Printer.around Fmt.around Fmt.expand Fmt.zip w Atlas.around + simp only [H.graph] + unfold Printer.view + rw [eq, H.labels w] + rfl + +open scoped Classical in +theorem score [Field F] : + U.score data c = ∏ i, (lens a f (U.ballots c) i).score U.positive := by + rw [Fintype.prod_prod_type] + unfold Printer.score Fmt.weight tariff + exact Finset.prod_congr rfl fun i _ => Finset.prod_congr rfl fun l _ => + congrArg (fun v => v.score U.positive) (H.view c (i, l)) + +variable [Field F] [Finite K] +local notation "O" => U.advance data status c + +open scoped Classical in +theorem read_at (i : B (m + U.childBits)) (l : B h) : + U.read (((O).1 i).2 l) = Function.extend U.slot + (U.send (lens a f (U.ballots c) ((U.split i).1, l))) (fun _ => none) (U.split i).2 := by + change U.read (Children.label _ (U.update data status c) i l) = _ + unfold Printer.read + rw [Children.label_at (U.update data status c) i l] + simp only [Printer.update, Fmt.update, Equiv.symm_apply_apply] + exact congrArg (fun v => Function.extend U.slot (U.send v) (fun _ => none) (U.split i).2) + (H.view c ((U.split i).1, l)) + +end Receives +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- +# The intrinsic data needed to print one terminal state + +Species counts are kept abstract here so that the caller can work +with the original unchunked records and station orders. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place) + +variable {F K N X Z J I : Type} [Field F] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g r₀ t₀ w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F r₀ t₀ Z P.Occupied P.grid.Seam X} + (Q : Key.Source Y x y s) (left : Order.Exterior Q.left) (right : Order.Exterior Q.right) + +open scoped Classical in +/-- The keeps of type `Prop` for the given inputs. -/ +def Keeps {S : Scheme F} {s₀ : S.format.obj} (p : S.Presentation s₀ P.diagram) + (loc : P.Occupied ↪ B S.m × B S.h) : Prop := + ∀ e : slots x ⊕ slots y, let v := Packing.portEnd P.diagram e + ∃ i : Place s.scene.cell, loc i.1 = ((p.vertex v).1, (p.vertex v).2.1) ∧ + left.ports i = P.diagram.extLeft v ∧ right.ports i = P.diagram.extRight v + +namespace Printer +variable (U : Printer F K N m d h ℓ M r t q D k n u j z) + (a : Atlas P.Occupied P.grid.Seam m d h) (π : Palette a w q) + (β : P.Occupied ⊕ ℕ → K) (R₀ : Reference J I N P.Occupied P.grid.Seam Z X) + (G : Record F r₀ t₀ P.Occupied P.grid.Seam K N) + (hm : Matches R₀.world β s G) (index : ∀ v, Y.state v ↪ ℕ) (size : P.Occupied → ℕ) + (ext : P.Occupied → Option N → Bool → ℕ) (old : P.V ↪ B m) + (data : U.rows.obj) (status : (Children.Header m d).obj) + +open scoped Classical in +/-- Uses `⟨ext v, π.mark v, G.tile π.edge (catalog size β s) v⟩` as the representation. -/ +def faces (v : P.Occupied) : Face F r₀ t₀ q K N := + ⟨ext v, π.mark v, G.tile π.edge (catalog size β s) v⟩ + +open scoped Classical in +/-- The data for the signal construction, including `radius`, `source`, `target`, `layout`, +`distinct`. -/ +structure Signal : Prop where + radius : 2 ≤ w + source : Q.src = a.src + target : Q.dst = a.dst + layout : ∃ c, s.Layout a.src a.dst c + distinct : Distinct (a.near 1) s β + location : ∀ v, a.coord v = (old v.val.1, cellIndex h v.val.2) + parents : Children.Shows P.adj old (a.graph, status) + graph : ∀ i, (data i).1 = a.graph i + read : ∀ i, HEq (U.menu ((data i.1).2 i.2)) (a.fill (faces (s := s) a π β G size ext) i) + exterior : ∀ i b, cond b (right.ports i).length (left.ports i).length = ext i.1 (hm.row i).name b + hi : ∀ v x y z, R₀.key v (Q.init x y z) = index v (z v) + he : ∀ i b c z, R₀.ext (Layout.item s.scene.cell i).label.name (Q.init b c z) = + ((left.ports i).map (bits x b), (right.ports i).map (bits y c)) + sel : ∀ v, (Y.width v, Order.decode _ _ (Y.code v) (Sum.inl ∘ index v)) = + Key.info t₀ (.inl (size v)) + +end Printer +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Physical locations of live stations and relay nodes -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer + +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Node Sharing) + +variable {F K N X Z : Type} [Field F] [Finite K] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} (U : Printer F K N m d h ℓ M r t q D k n u j z) + (G : (Key.share s Q).Geo P k) {a : Atlas P.Occupied P.grid.Seam m d h} (π : Palette a w q) + (old : P.V ↪ B m) (data : U.rows.obj) (status : (Children.Header m d).obj) + +open scoped Classical in +/-- The data for the physical construction, including `labels`, `rules`, `face`, `aligned`, +`wire`. -/ +structure Physical where + /-- The label data of type `Marking (Key.share s Q) (Fin q) (Number D k) K`. -/ + labels : Marking (Key.share s Q) (Fin q) (Number D k) K + /-- The `Physical` component of type `Order.Rules (Key.share s Q)`. -/ + rules : Order.Rules (Key.share s Q) + /-- The `Physical` component of type `P.Occupied → Face F (M * r) (M * t) q K N`. -/ + face : P.Occupied → Face F (M * r) (M * t) q K N + aligned : Aligned π U.positive labels rules face + wire : CircuitMap π G labels old U.degree + location : ∀ i, a.coord i = (old (G.site i).1, cellIndex h (G.site i).2) + parents : Children.Shows P.adj old (a.graph, status) + steer : G.steer = parents.steer U.degree + received : U.Receives data a face + range : ∀ i, cost s.scene.cell s.scene.level i < 2 ^ z + +namespace Physical +variable {U G π old data status} (B : U.Physical G π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "S" => Key.share s Q +local notation "H" => G.layout U.dyadic U.large p j +local notation "V" => Node (Sharing.Position S) (Sharing.radius k * n) + +open scoped Classical in +/-- The value specified by `(H).ordered (G.external U.dyadic U.large p j) U.pos (B.rules.script +p j)`. -/ +abbrev term := (H).ordered (G.external U.dyadic U.large p j) U.pos (B.rules.script p j) +open scoped Classical in +/-- The value specified by `(B.labels.select a.coord _ B.range).relabel U.pack`. -/ +def select := (B.labels.select a.coord _ B.range).relabel U.pack +open scoped Classical in +/-- Computes the record by the application `U.advance data status (B.select.write p)`. -/ +abbrev record := U.advance data status (B.select.write p) +open scoped Classical in +/-- Uses `Children.host old U.slot` as the representation. -/ +abbrev host (_ : U.Physical G π old data status) := Children.host old U.slot +open scoped Classical in +/-- Uses `Children.idx old U.slot a.graph` as the representation. -/ +abbrev idx (_ : U.Physical G π old data status) := Children.idx old U.slot a.graph +open scoped Classical in +/-- The value specified by `Compass.vertex (U := U.engine) (G := G) U.dyadic U.large p j B.host +(cellIndex h).toEmbedding`. -/ +abbrev vertex := Compass.vertex (U := U.engine) (G + := G) U.dyadic U.large p j B.host (cellIndex h).toEmbedding +open scoped Classical in +/-- Computes the child by the application `lift Prod.snd ((H).place v).1`. -/ +abbrev child (_ : U.Physical G π old data status) (v : V) := lift Prod.snd ((H).place v).1 +open scoped Classical in +/-- Computes the lens at by the application `lens a B.face (B.aligned.ballots B.range p) i`. -/ +abbrev lensAt (i : Coloring.B m × Coloring.B h) := lens a B.face (B.aligned.ballots B.range p) i + +omit [Finite K] in +open scoped Classical in +theorem score (c : U.selectors.obj) : U.score data c = (B.select.read c).elim 0 Layout.Profile.sign + := + (B.received.score c).trans (B.aligned.score B.range (U.ballots c)) + +omit [Field F] [Finite K] in +open scoped Classical in +theorem ballots : U.ballots (B.select.write p) = B.aligned.ballots B.range p := + funext fun _ => U.ballot.symm_apply_apply _ + +open scoped Classical in +theorem address (v : V) : + U.split (B.vertex p v).1 = ((a.coord ((S).home (root v))).1, U.slot (B.child p v)) ∧ + (B.vertex p v).2.1 = (a.coord ((S).home (root v))).2 := by + have e := Compass.home_eq (G := G) U.dyadic U.large p j v + rw [B.location, ← e] + exact ⟨Children.host_split old U.slot _, rfl⟩ + +omit [Finite K] in +open scoped Classical in +theorem color (v : V) : lift (Prod.mk (π.mark ((S).home (root v)))) (B.child p v) = + lift B.labels.spot v := by + cases v with + | inl v => exact congrArg Sum.inl (B.wire.slot v).symm + | inr v => exact congrArg (fun w => Sum.inr (w, v.2)) (B.wire.slot v.1).symm + +omit [Finite K] in +open scoped Classical in +theorem active (v : V) : + U.send (B.lensAt p (a.coord ((S).home (root v)))) (B.child p v) = + some ((B.labels.names p j u H B.idx).star ((H).routed (B.rules.script p j) u) v) := by + let x := (S).home (root v) + rw [send, B.aligned.page, Option.bind_some] + refine B.wire.emit U.dyadic U.large U.slot p j u B.rules v _ rfl ?_ ?_ ?_ + · exact B.aligned.observes (B.aligned.ballots B.range p) x + · change lift (Prod.mk (B.labels.mark x)) _ = _ + rw [B.aligned.mark] + exact B.color p v + · exact congrArg (wiring U.dyadic U.large U.chunks U.degree U.slot) + (tones π B.face _ B.aligned.color x) + +omit [Finite K] in +open scoped Classical in +theorem active_only (i : Coloring.B m × Coloring.B h) (c : U.part) (h : (U.send (B.lensAt p i) + c).isSome) : + ∃ v : V, a.coord ((S).home (root v)) = i ∧ B.child p v = c := by + by_cases hi : i ∈ Set.range a.coord + swap + · simp [send, lensAt, Lens.page, center, a.fill_away _ hi] at h + obtain ⟨v, rfl⟩ := hi + rw [send, B.aligned.page, Option.bind_some] at h + obtain ⟨w, hw, hc⟩ := B.labels.emit_live B.rules p j u v _ rfl h + refine ⟨w, congrArg a.coord hw, ?_⟩ + rw [← B.color p w] at hc + have ee (i : Fin q) (x : U.part) : lift Prod.snd (lift (Prod.mk i) x) = x := by cases x <;> rfl + exact (ee _ _).symm.trans ((congrArg (lift Prod.snd) hc).trans (ee _ _)) + +end Physical +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Constructing the physical labels from terminal records -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Signal +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place Sharing item) + +variable {F K N X Z J I : Type} [Field F] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} {left : Order.Exterior Q.left} {right : Order.Exterior Q.right} + {U : Printer F K N m d h ℓ M r t q D k n u j z} + {a : Atlas P.Occupied P.grid.Seam m d h} {π : Palette a w q} + {β : P.Occupied ⊕ ℕ → K} {R₀ : Reference J I N P.Occupied P.grid.Seam Z X} + {G : Record F (M * r) (M * t) P.Occupied P.grid.Seam K N} + {hm : Matches R₀.world β s G} {index : ∀ v, Y.state v ↪ ℕ} {size : P.Occupied → ℕ} + {ext : P.Occupied → Option N → Bool → ℕ} {old : P.V ↪ B m} + {data : U.rows.obj} {status : (Children.Header m d).obj} + (H : U.Signal Q left right a π β R₀ G hm index size ext old data status) + +omit [Field F] in +open scoped Classical in +theorem physical (G₀ : (Key.share s Q).Geo P k) (hs : ∀ i, G₀.site i = i.val) + (hf : G₀.frozen = (fun i => (item s.scene.cell i).label.role = .collector)) (hg : G₀.steer + = H.parents.steer U.degree) + (hz : ∀ i, cost s.scene.cell s.scene.level i < 2 ^ z) : + ∃ B : U.Physical G₀ π old data status, B.rules.left = left ∧ B.rules.right = right := by + obtain ⟨c, hc⟩ := H.layout + obtain ⟨L, hl, hr, ht, he⟩ := Key.intrinsic index hm left right H.hi H.he + let W := marking s Q a π β G₀.count H.source H.target H.radius hc H.distinct + let f := faces (s := s) a π β G size ext + have ep : W.edge = π.edge := by + funext i + change (π.mark (Q.src i), π.mark (Q.dst i)) = _ + rw [H.source, H.target]; rfl + have hn (i : Place s.scene.cell) : W.number i = number U.positive i.2.val (hm.row i).role := by + have e := (hm.represents i).role + change (decide ((item s.scene.cell i).label.role = .collector), _) = _ + unfold number + refine Prod.ext ?_ (Fin.ext (Nat.mod_eq_of_lt (i.2.isLt.trans_le (G₀.count i.1))).symm) + rw [e] + have near (i) : a.near 1 (Q.src i) (Q.dst i) := by rw [H.source, H.target]; exact a.near_edge i + have ha : Aligned π U.positive W L f := by + refine ⟨H.radius, rfl, fun _ => rfl, near, ?_, ?_, ?_⟩ + · intro i + change ofBody (G.body π.edge i) (W.mark i) _ = _ + rw [← ep] + exact ofBody_eq hm W _ hn i + · intro i; exact (footprint hm W rfl i).symm + · intro p i + change ofTile ⟨G.body π.edge i, catalog size β s i⟩ (W.mark i) _ _ _ = _ + rw [← ep] + apply ofTile_eq hm W rfl L size _ ext p hn + · rw [hl, hr]; exact H.exterior + · exact he + · unfold Order.Rules.signal + rw [ht] + exact Key.symbol_info index size H.sel _ + have loc (i) : a.coord i = (old (G₀.site i).1, cellIndex h (G₀.site i).2) + := by rw [hs, H.location] + have ac : CircuitMap π G₀ W old U.degree := by + refine ⟨fun i => congrArg Prod.fst (loc i), ?_, ?_, near, H.radius⟩ + · rintro ((i|v|v)|(v|v)) + · change (_, Sum.inl _) = (_, Sum.inl (decide (G₀.frozen i), _)) + rw [hf] + dsimp only [W, marking, coordinate, Sharing.home] + congr! + all_goals rfl + · intro v l; rw [hg]; rfl + exact ⟨⟨W, L, f, ha, ac, loc, H.parents, hg, ⟨H.graph, fun i => eq_of_heq (H.read i)⟩, hz⟩, hl, + hr⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Signal +end + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer + +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Node Sharing) + +variable {F K N X Z : Type} [Field F] [Finite K] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} (U : Printer F K N m d h ℓ M r t q D k n u j z) + (G : (Key.share s Q).Geo P k) {a : Atlas P.Occupied P.grid.Seam m d h} (π : Palette a w q) + (old : P.V ↪ B m) (data : U.rows.obj) (status : (Children.Header m d).obj) + +namespace Physical +variable {U G π old data status} (B : U.Physical G π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "S" => Key.share s Q +local notation "H" => G.layout U.dyadic U.large p j +local notation "V" => Node (Sharing.Position S) (Sharing.radius k * n) + +/- # Exact support of the printed station dictionary -/ + + +section + +open scoped Classical in +theorem read_eq (i : U.engine.scheme.Vtx) : + U.read (((B.record p).1 i.1).2 i.2.1) = Function.extend U.slot + (U.send (B.lensAt p ((U.split i.1).1, i.2.1))) (fun _ => none) (U.split i.1).2 := by + have he := B.received.read_at status (B.select.write p) i.1 i.2.1 + rw [B.ballots] at he + exact he + +open scoped Classical in +theorem read_active (v : V) : U.read (((B.record p).1 (B.vertex p v).1).2 (B.vertex p v).2.1) = + some ((B.labels.names p j u H B.idx).star ((H).routed (B.rules.script p j) u) v) := by + rw [B.read_eq, (B.address p v).1, (B.address p v).2, U.slot.injective.extend_apply] + exact B.active p v + +open scoped Classical in +theorem read_inactive (i : U.engine.scheme.Vtx) (hi : i ∉ Set.range (B.vertex p)) : + U.read (((B.record p).1 i.1).2 i.2.1) = none := by + rw [B.read_eq] + by_cases he : (U.split i.1).2 ∈ Set.range U.slot + swap + · exact Function.extend_apply' _ _ _ he + obtain ⟨c, hc⟩ := he + rw [← hc, U.slot.injective.extend_apply] + by_contra hne + obtain ⟨v, hv, ht⟩ := B.active_only p _ _ (Option.isSome_iff_ne_none.mpr hne) + obtain ⟨h₁, h₂⟩ := B.address p v + rw [hv, ht, hc] at h₁ + rw [hv] at h₂ + refine hi ⟨v, Prod.ext (U.split.injective h₁) (Prod.ext h₂ ?_)⟩ + exact Fin.eq_zero i.2.2 |>.symm + +end + +/- # A presentation of the diagram selected by a physical printer -/ + + +section +local notation "A" => U.template +local notation "rows" => B.record p +local notation "node" => (B.term p) +local notation "tree" => (G.tree U.dyadic U.large) +local notation "graph" => Children.graph U.slot U.dyadic U.large U.chunks U.degree (a.graph, status) + +open scoped Classical in +theorem record_header : + ((A).nav rows, fun i => (((A).live rows i, (A).frozen rows i), (A).flags rows i)) = graph := by + change Children.graph U.slot U.dyadic U.large U.chunks U.degree + (Children.tape (U.update data status (B.select.write p))) = _ + rw [B.received.tape] + +open scoped Classical in +theorem nav_at (x y : Host P.V M D k n) (hy : y ∈ (tree).adj x) : + (A).nav rows (B.host x) (B.idx x y) = B.host y := by + have he := congrArg Prod.fst (B.record_header p) + change (A).nav rows = (graph).1 at he + rw [he] + exact (Children.used_column U.slot U.dyadic U.large U.chunks U.degree G B.parents B.steer x y + hy).1 + +omit [Finite K] in +open scoped Classical in +theorem charge (v : V) : (node).charge v = (node).diagram.arity v + (u : ℝ) := by + have h := ((H).routed (B.rules.script p j) u).drawing.arity v + exact congrArg (fun i : ℕ => (i : ℝ) + u) h.symm + +variable (hw : open scoped Classical in + ∀ i, Diagram.padWidth u (((Key.share s Q).backdrop.emitted p j).width i) / u ≤ U.cap) + +open scoped Classical in +/-- The frame of type `Frame U.engine (rows).1 (B.labels.names p j u H B.idx) ((H).routed +(B.rules.script p j) u) u where vertex`, constructed using `(H).place (side ((H).pad +u).route.net t i)`. -/ +def frame : Frame U.engine (rows).1 (B.labels.names p j u H B.idx) ((H).routed (B.rules.script p j) + u) u where + vertex := B.vertex p + pos := U.pos + width i := Diagram.dvd_padWidth U.pos _ + bound i := hw i.1 + active v := by + change ((U.read _).map _).getD _ = _ + rw [B.read_active] + rfl + inactive v hv := by + change ((U.read _).map _).getD _ = _ + rw [B.read_inactive p v hv] + rfl + address t i := by + let x := (H).place (side ((H).pad u).route.net t i) + let y := (H).place (side ((H).pad u).route.net (!t) i) + have he : x.2 = y.2 ∧ y.1 ∈ (tree).adj x.1 := by + have hi := ((H).pad u).edges i + have hp (v : V) : ((H).pad u).place v = (H).place v := by cases v <;> rfl + simp only [Layout.Fanout.linked, hp] at hi + unfold x y + cases t + · exact hi + · exact ⟨hi.1.symm, (tree).adj_symm hi.2⟩ + change ((A).nav rows (B.host x.1) (B.idx x.1 y.1), cellIndex h x.2, (0 : Coloring.B 0)) = + (B.host y.1, cellIndex h y.2, 0) + rw [B.nav_at p _ _ he.2, he.1] + rfl + +end + +end Physical +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # The family of terms carried by one controlled emission -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Rounds + +variable {F K N : Type} [Field F] [Finite K] {x y : Wire} {S : Scheme F} + {d ℓ M r t q D k n u j z T R g : ℕ} {W : ℝ} {P : Input F x y S.h D T R g W} + {tape : S.format.obj} (U : Printer F K N S.m d S.h ℓ M r t q D k n u j z) + (pres : S.Presentation tape P.diagram) (data : U.rows.obj) (status : (Children.Header S.m d).obj) + (f : Val x → Val y → F) (σ : ℕ) + +open scoped Classical in +/-- The data for the release construction, including `I`, `[finite`, `select`, `coeff`, `term`. -/ +structure Release where + /-- The `Release` component of type `Type`. -/ + I : Type + [finite : Fintype I] + /-- The `Release` component of type `Transcript.Selector I U.selectors.obj`. -/ + select : Transcript.Selector I U.selectors.obj + /-- The `Release` component of type `I → F`. -/ + coeff : I → F + /-- The `Release` component of type `I → LocalTerm F x y S.h u`. -/ + term : I → LocalTerm F x y S.h u + value : ∀ x y, ∑ i, coeff i * (term i).diagram.eval x y = f x y + bound : ∀ i, Concentrated P (term i) (Input.terminalExponent g σ) n σ + populated : ∀ i, Nonempty (term i).V + valid : ∀ c, U.score data c = (select.read c).elim 0 coeff + /-- The `Release` component of type `∀ i, U.template.Shows (U.advance data status + (select.write i)) (term i)`. -/ + shows : ∀ i, U.template.Shows (U.advance data status (select.write i)) (term i) + retains : ∀ i, Payload.Retains pres (shows i).pres U.split U.outer + reciprocal : Fmt.Reciprocal (.vec S.h (.addr ℓ)) data + +attribute [instance] Release.finite + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Reading a named collector's exterior wires after printing -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Frame +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout Assembly +variable {F α A : Type} [Field F] {a b : Wire} {u : ℕ} {G : Bundled F a b} + {U : Engine F A} {r : U.scheme.format.obj} {N : Names G A U.d} {p : Order.Script G α} + (H : Frame U r N p u) + +open scoped Classical in +private theorem exterior_left (v : G.V) (l : List (slots a)) + (hl : p.left.ports v = l) (i : Fin l.length) : + let e := (H.presentation.boundary (.inl (l.get i))).val + e.1 = H.exterior v false ∧ e.2.val = i.val := by + subst l + change let e := H.presentation.toSeating.ends (.inl (.inl (p.left.enum.get v i))) + e.1 = H.exterior v false ∧ e.2.val = i.val + rw [H.ends_eq, H.left] + exact ⟨rfl, rfl⟩ + +open scoped Classical in +private theorem exterior_right (v : G.V) (l : List (slots b)) + (hl : p.right.ports v = l) (i : Fin l.length) : + let e := (H.presentation.boundary (.inr (l.get i))).val + e.1 = H.exterior v true ∧ e.2.val = i.val := by + subst l + change let e := H.presentation.toSeating.ends (.inr (.inl (p.right.enum.get v i))) + e.1 = H.exterior v true ∧ e.2.val = i.val + rw [H.ends_eq, H.right] + exact ⟨rfl, rfl⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Frame + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer + +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Node Sharing) + +variable {F K N X Z : Type} [Field F] [Finite K] {x y : Wire} {S : Scheme F} {d ℓ M r t q D k n u j + z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y S.h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} (U : Printer F K N S.m d S.h ℓ M r t q D k n u j z) + (G : (Key.share s Q).Geo P k) {a : Atlas P.Occupied P.grid.Seam S.m d S.h} (π : Palette a w q) + (old : P.V ↪ B S.m) (data : U.rows.obj) (status : (Children.Header S.m d).obj) + +namespace Physical +variable {U G π old data status} (B : U.Physical G π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "Lyt" => G.layout U.dyadic U.large p j + +open scoped Classical in +theorem retains + {record : U.engine.scheme.format.obj} + {names : Names _ U.lane U.engine.d} + (H : Frame U.engine record names ((Lyt).routed (B.rules.script p j) u) u) + (hv : H.vertex = B.vertex p) + {r₀ : S.format.obj} (portal : S.Presentation r₀ P.diagram) + (keeps : Keeps Q B.rules.left B.rules.right portal a.coord) : + Payload.Retains portal H.presentation U.split U.outer := by + intro e + obtain ⟨i, hloc, hleft, hright⟩ := keeps e + let v : Node (Key.share s Q).Position (Sharing.radius k * n) := .inl (.inl (.inl i)) + have addr := B.address p v + change U.split (B.vertex p v).1 = ((a.coord i.1).1, _) ∧ (B.vertex p v).2.1 + = (a.coord i.1).2 at addr + rw [hloc] at addr + refine ⟨v, ?_, ?_, ?_, ?_, ?_⟩ + · rw [H.vertex_eq, hv, addr.1] + · rw [H.vertex_eq, hv, addr.2] + · exact Fin.eq_zero _ + · exact H.exterior_left v _ hleft + · exact H.exterior_right v _ hright + +end Physical +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer + +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Node Sharing) + +variable {F K N X Z : Type} [Field F] [Finite K] {x y : Wire} {m d h ℓ M r t q D k n u j z : ℕ} + {T R g w : ℕ} {W : ℝ} {P : Input F x y h D T R g W} + {Y : Alphabet P.Occupied} {s : Stage F (M * r) (M * t) Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} (U : Printer F K N m d h ℓ M r t q D k n u j z) + (G : (Key.share s Q).Geo P k) {a : Atlas P.Occupied P.grid.Seam m d h} (π : Palette a w q) + (old : P.V ↪ B m) (data : U.rows.obj) (status : (Children.Header m d).obj) + +namespace Physical +variable {U G π old data status} (B : U.Physical G π old data status) + (p : Layout.Profile s.scene.cell s.scene.level) + +local notation "S" => Key.share s Q +local notation "H" => G.layout U.dyadic U.large p j +local notation "V" => Node (Sharing.Position S) (Sharing.radius k * n) + +/- # A printed record displays its weighted local term -/ + + +section +local notation "A" => U.template +local notation "rows" => B.record p +local notation "node" => (B.term p) +local notation "tree" => (G.tree U.dyadic U.large) +local notation "graph" => Children.graph U.slot U.dyadic U.large U.chunks U.degree (a.graph, status) + +variable (hw : open scoped Classical in + ∀ i, Diagram.padWidth u (((Key.share s Q).backdrop.emitted p j).width i) / u ≤ U.cap) + +open scoped Classical in +/-- Builds `(A).Shows rows node where pres` with the specified `pres`, `host`, `vertex`, +`directed`. -/ +def shows : (A).Shows rows node where + pres := (B.frame p hw).presentation + host := B.host + vertex v := by cases v <;> rfl + directed := (B.frame p hw).directed + uniform := by + intro i + apply (B.frame p hw).uniform + rw [(B.frame p hw).presentation.wirePin_peer] + rfl + index := B.idx + neighbor v z i l he := by + refine ((B.frame p hw).neighbor v z i l he).trans ?_ + have hp (i : V) : (node).frame.place i = (H).place i := by cases i <;> rfl + rw [hp, hp] + rfl + live i := by + have ht := Children.live U.slot U.dyadic U.large U.chunks U.degree B.parents i + rw [← B.record_header p] at ht + exact ht + frozen v := by + have ht := Children.fixed_slot U.slot U.dyadic U.large U.chunks U.degree + (old:=old) (u:=(a.graph, status)) v + rw [← B.record_header p] at ht + exact ht.trans (Children.fixed_iff U.dyadic U.large G v) + closed v j := by + have ht := Children.closed U.slot U.dyadic U.large U.chunks U.degree G B.parents B.steer v j + rw [← B.record_header p] at ht + exact ht + reciprocal := by + have ht := Children.reciprocal U.slot U.dyadic U.large U.chunks U.degree G B.parents B.steer + rw [← B.record_header p] at ht + exact ht + edge v z := by + have ht := Children.edge U.slot U.dyadic U.large U.chunks U.degree G B.parents B.steer v z + rw [← B.record_header p] at ht + exact ht + core v z := by + have ht := Children.core U.slot U.dyadic U.large U.chunks U.degree G B.parents B.steer v z + rw [← B.record_header p] at ht + exact ht + charge := B.charge p + amount := by + refine U.amount (r':=rows) (B.frame p hw).presentation _ (B.charge p) (fun _ _ => rfl) + ?_ (B.read_inactive p) + intro v + exact Option.isSome_iff_exists.mpr ⟨_, B.read_active p v⟩ + +end + +/- # Values and charges of the selected diagrams -/ + + +section + +open Finset + +omit [Finite K] in +open scoped Classical in +theorem populated (hn : Nonempty P.V) : Nonempty (B.term p).V := by + obtain ⟨v⟩ := hn + exact ⟨.inl (v, .inr (.inl false))⟩ + +omit [Finite K] in +open scoped Classical in +theorem value (a : Val x) (b : Val y) : + ∑ p ∈ @Finset.univ _ (Input.FinalBounds.profileType s.scene.cell s.scene.level), + p.sign * (B.term p).diagram.eval a b = ∑ i, s.value j (Q.init a b i) := by + have he := G.sum_output U.dyadic U.large (e := s.scene.level) j U.pos a b + refine Eq.trans ?_ (he.trans ?_) + · apply sum_congr rfl + intro p _ + have h₀ := (G.layout U.dyadic U.large p j).eval_ordered (G.external U.dyadic U.large p j) U.pos + (B.rules.script p j) + have h₁ := (G.layout U.dyadic U.large p j).eval_finish (G.external U.dyadic U.large p j) U.pos + exact congrArg (fun f => p.sign * f a b) (h₀.trans h₁.symm) + · have ht := Key.sum_stack Y (M * t) s.hidden (Q.init a b) (s.scene.value j) + refine Eq.trans ?_ (ht.trans ?_) + · exact sum_congr (by ext; simp) (fun _ _ => rfl) + · exact sum_congr (by ext; simp) (fun _ _ => rfl) + +omit [Finite K] in +open scoped Classical in +theorem concentrated {σ A : ℕ} (hc : Concentrated P (G.output U.dyadic U.large p j U.pos) A n σ) : + Concentrated P (B.term p) A n σ := + ((H).pad u).drawn_concentrated (G.external U.dyadic U.large p j) _ _ P hc + +end + +end Physical +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Wiring.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Wiring.lean new file mode 100644 index 0000000000..1415cc7658 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Wiring.lean @@ -0,0 +1,844 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Window +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Correct +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Presentation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Traces + +/-! +# Reading a short neighbor address from colors + +Only occupied cells have a color. Colors can repeat between blocks +and outside the neighborhood of a cell. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print + +open Coloring Assembly Surface.Local + +open scoped Classical in +/-- The quantity computed by `B ((d + 1) * 1)`. -/ +abbrev Step (d : ℕ) := B ((d + 1) * 1) +open scoped Classical in +/-- The indexing data represented by `Step d → Step d → X`. -/ +abbrev Sight (d : ℕ) (X : Type) := Step d → Step d → X + +variable {d m h q R : ℕ} {X V E : Type} + +open scoped Classical in +/-- Selects the appropriate branch of `if f 0 = some x then 0 else if H : ∃ i, f i = some x then +H.choose else 0`. -/ +def search (f : Step d → Option X) (x : X) : Step d := + if f 0 = some x then 0 else if H : ∃ i, f i = some x then H.choose else 0 + +open scoped Classical in +theorem search_hit (f : Step d → Option X) (x : X) (h : ∃ i, f i = some x) : + f (search f x) = some x := by + unfold search + rw [dite_eq_left h] + split_ifs with h' + · exact h' + · exact h.choose_spec + +open scoped Classical in +/-- Computes the turn by the application `search (o (search (o 0) x)) y`. -/ +def Sight.turn (o : Sight d (Option X)) (x y : X) : Step d := + search (o (search (o 0) x)) y + +open scoped Classical in +/-- Evaluates `f (a.around 1 (a.around 1 x i) j)` at the input `i j`. -/ +def scan (a : Atlas V E m d h) (f : B m × B h → X) (x : B m × B h) : Sight d X := + fun i j => f (a.around 1 (a.around 1 x i) j) + +variable {a : Atlas V E m d h} (π : Palette a R q) (hR : 2 ≤ R) + +open scoped Classical in +/-- The value specified by `scan a (a.fill π.mark) (a.coord v)`. -/ +def colors (v : V) := scan a (a.fill π.mark) (a.coord v) + +include hR in +open scoped Classical in +theorem recognized {v w : V} (h : a.near 1 v w) (i : Step d) : + a.fill π.mark (a.around 1 (a.coord v) i) = some (π.mark w) ↔ + a.around 1 (a.coord v) i = a.coord w := by + constructor + · intro e + by_cases hi : a.around 1 (a.coord v) i ∈ Set.range a.coord + · obtain ⟨z, hz⟩ := hi + rw [← hz, a.fill_at] at e + exact hz.symm.trans (congrArg a.coord (π.injective_at hR + ((a.around_iff 1 v z).mp ⟨i, hz.symm⟩) h (Option.some.inj e))) + · simp [a.fill_away _ hi] at e + · intro e; rw [e, a.fill_at] + +include hR in +open scoped Classical in +theorem located {v w : V} (h : a.near 1 v w) : + a.around 1 (a.coord v) (search (colors π v 0) (π.mark w)) = a.coord w := by + have hf (i) : colors π v 0 i = some (π.mark w) ↔ a.around 1 (a.coord v) i = a.coord w := by + simpa only [colors, scan, Atlas.around_zero] using recognized π hR h i + exact (hf _).mp (search_hit _ _ (by + obtain ⟨i, hi⟩ := (a.around_iff 1 v w).mpr h + exact ⟨i, (hf i).mpr hi⟩)) + +include hR in +open scoped Classical in +theorem turn_eq {v w : V} (h : a.near 1 v w) (x : Fin q) : + (colors π v).turn (π.mark w) x = search (colors π w 0) x := by + unfold Sight.turn + congr 1 + funext i + change a.fill π.mark (a.around 1 (a.around 1 (a.coord v) _) i) = _ + rw [located π hR h] + simp [colors, scan] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Cell data recovered from the terminal motion record + +The exterior widths are read at the original immobile marks. The +new information consists of two chunk shapes per station and one per +seam end. Absolute motion-history indices are replaced by aliases. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place item Profile + secondList) + +open Classical in +/-- The indexing data represented by `Fin M → ℕ`. -/ +abbrev Vector (M : ℕ) := Fin M → ℕ + +open Classical in +/-- The data for the shapes construction, including `rows`, `ports`. -/ +structure Shapes (M : ℕ) where + /-- The indexed rows of type `List (Vector M × Vector M)`. -/ + rows : List (Vector M × Vector M) + /-- The `Shapes` component of type `List (Vector M)`. -/ + ports : List (Vector M) + +variable {F T V E X J I K N Z : Type} {r t M n q : ℕ} + {s : Stage F (M * r) (M * t) T V E X} + +open Classical in +/-- Builds `Shapes M where rows` with the specified `Shapes`, `ports`. -/ +def shapeStamp (s : Stage F (M * r) (M * t) T V E X) (p : Profile s.scene.cell s.scene.level) (v : + V) : + Shapes M where + rows := (secondList s.scene.cell v).map fun i => + (fun j => ((p.1 (.inr i)).val j).val, fun j => ((p.2 i).val j).val) + ports := (s.scene.cell v).ports.map fun i j => ((p.1 (.inl i.1)).val j).val + +open Classical in +/-- Lists the values in order of their bounded index. -/ +def indexed {A : Type} (l : List A) := List.ofFn fun i : Fin l.length => (i.val, l.get i) + +open Classical in +/-- Builds `Sheet F (Fin q) Z K M r t where mark` with the specified `mark`, `rows`, `ports`, +`catalog`. -/ +def ofTile (u : Tile F (M * r) (M * t) q K N) (mark : Fin q) (number : ℕ → Role → Z) + (ext : Option N → Bool → ℕ) (b : Shapes M) : Sheet F (Fin q) Z K M r t where + mark := mark + rows := (indexed u.rows).zipWith (fun ⟨j, x⟩ d => + ⟨number j x.role, x.pos, ext x.name, x.reads, x.reads.toFinset, x.label, d.1, d.2⟩) b.rows + ports := u.ports.zipWith (fun j d => ⟨j.1, j.2.1, d⟩) b.ports + catalog := u.catalog.image (fun j => (j.1, Key.info (M * t) j.2)) + +variable {R : Reference J I N V E T X} {β : V ⊕ ℕ → K} + {B : Record F (M * r) (M * t) V E K N} (h : Matches R.world β s B) + +open Classical in +theorem indexed_rows (v : V) : + indexed (B.rows v) = (secondList s.scene.cell v).map (fun i => (i.2.val, h.row i)) := by + have he : (s.scene.cell v).stations.length = (B.rows v).length := (h.rows v).length_eq + unfold indexed secondList + rw [List.map_map, ← List.ofFn_eq_map] + apply List.ext_get + · simp [he] + · intro i hi hj + rw [List.get_ofFn, List.get_ofFn] + rfl + +variable [Fintype V] {Y : Alphabet V} {a b : Wire} {Q : Key.Source Y a b s} + (m : Marking (Key.share s Q) (Fin q) Z K) (hkey : m.key = β ∘ Key.name s.hidden) + +include h hkey + +open Classical in +theorem footprint (v : V) : ((Key.share s Q).seen v).image m.key = B.footprint v := by + rw [← h.footprint v] + ext i + simp only [Finset.mem_image, hkey, Function.comp_apply] + constructor + · rintro ⟨j, hj, rfl⟩; exact ⟨_, Key.mem_filter.mp hj, rfl⟩ + · rintro ⟨j, hj, rfl⟩ + obtain ⟨k, rfl⟩ := Key.exists_name _ _ (h.known v j hj) + exact ⟨k, Key.mem_filter.mpr hj, rfl⟩ + +open Classical in +private theorem visible (i : Place s.scene.cell) : + ((Key.share s Q).reads i).image m.key = (h.row i).reads.toFinset := by + obtain ⟨u, hu, hd⟩ := (h.represents i).label + rw [← hu] + ext j + simp only [Finset.mem_image, hkey, Function.comp_apply, List.mem_toFinset, List.mem_map] + constructor + · rintro ⟨k, hk, rfl⟩ + exact ⟨_, List.mem_toFinset.mp (hd.1.symm ▸ Key.mem_filter.mp hk), rfl⟩ + · rintro ⟨k, hk, rfl⟩ + have ht := hd.1 ▸ List.mem_toFinset.mpr hk + obtain ⟨j, rfl⟩ := Key.exists_name _ _ ((h.represents i).known k ht) + exact ⟨j, Key.mem_filter.mpr ht, rfl⟩ + +open Classical in +theorem ofTile_eq (L : Order.Rules (Key.share s Q)) (size : V → ℕ) (number : ℕ → Role → Z) + (ext : V → Option N → Bool → ℕ) (p : Profile s.scene.cell s.scene.level) + (hnum : ∀ i, m.number i = number i.2.val (h.row i).role) + (hext : ∀ i b, cond b (L.right.ports i).length (L.left.ports i).length + = ext i.1 (h.row i).name b) + (hlabel : ∀ i, L.label i = (h.row i).label ∧ (L.reads i).map m.key = (h.row i).reads) + (hinfo : ∀ k, ((Key.alphabet Y (M * t) s.hidden).width k, L.signal k) = + Key.info (M * t) (kind size s.hidden (Key.name s.hidden k))) (v : V) : + ofTile ⟨B.body m.edge v, catalog size β s v⟩ (m.mark v) number (ext v) (shapeStamp s p v) = + m.sheet L p v := by + have hp : (s.scene.cell v).ports = B.ports v := by + have hh := h.ports v + change (s.scene.cell v).ports = (B.ports v).map id at hh + simpa using hh + unfold ofTile Marking.sheet + congr 1 + · change (indexed (B.rows v)).zipWith _ (shapeStamp s p v).rows = _ + rw [indexed_rows h] + simp only [shapeStamp, List.zipWith_map_left, List.zipWith_map_right, List.zipWith_self] + apply List.map_congr_left + intro i hi + obtain ⟨l, _, heq⟩ := List.mem_map.mp hi + have hj : i.1 = v := congrArg Sigma.fst heq.symm + have hl := hlabel i + have hv := visible h m hkey i + have he := (h.represents i).pos + simp only [Marking.rowData, hnum i, he, hl.1, hl.2, hv, hext, hj] + · change ((B.ports v).map _).zipWith _ (shapeStamp s p v).ports = _ + rw [← hp] + simp only [shapeStamp, List.zipWith_map_left, List.zipWith_map_right, List.zipWith_self] + rfl + · change (catalog size β s v).image _ = ((Key.share s Q).seen v).image _ + have hi (j : Key V s.hidden) : + m.entry L j = (β (Key.name s.hidden j), Key.info (M * t) (kind size s.hidden (Key.name + s.hidden j))) := + Prod.ext (congrFun hkey j) (hinfo j) + ext x + simp only [catalog, Finset.image_image, Finset.mem_image, Function.comp_apply, hi] + constructor + · rintro ⟨j, hj, hx⟩ + obtain ⟨k, rfl⟩ := Key.exists_name _ _ (h.known v _ hj) + exact ⟨k, Key.mem_filter.mpr hj, hx⟩ + · rintro ⟨k, hk, hx⟩ + exact ⟨_, Key.mem_filter.mp hk, hx⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Local tests for a global profile + +Only the source records the shape of a seam. Unused selector fields +have quota zero, so their only possible assignment is zero. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Sharing Profile Place + secondList item) + +open Classical in +/-- The data for the quotas construction, including `mark`, `rows`, `ports`. -/ +structure Quotas (J Z : Type) where + /-- The `Quotas` field of type `J`. -/ + mark : J + /-- The indexed rows of type `List (Z × ℕ × ℕ)`. -/ + rows : List (Z × ℕ × ℕ) + /-- The `Quotas` component of type `List ((J × J) × ℕ)`. -/ + ports : List ((J × J) × ℕ) + +variable {F U X E V K J Z A I : Type} {M r t : ℕ} + +open Classical in +/-- The items of type `Set (Axis J Z × ℕ)` for the given inputs. -/ +def Quotas.items (q : Quotas J Z) : Set (Axis J Z × ℕ) := + {k | (∃ p ∈ q.ports, p.1.1 = q.mark ∧ k = (.inl p.1.2, p.2)) ∨ + (∃ i ∈ q.rows, k = (.inr (false, i.1), i.2.1) ∨ k = (.inr (true, i.1), i.2.2))} + +open Classical in +/-- Returns `h.choose` when `h : ∃ n, ∃ t ∈ q, (i, n) ∈ t.items` holds, and `0` otherwise. -/ +def quota (q : Option (Quotas J Z)) (i : Axis J Z) : ℕ := + if h : ∃ n, ∃ t ∈ q, (i, n) ∈ t.items then h.choose else 0 + +open Classical in +/-- Builds `Shapes M where rows` with the specified `rows`, `ports`. -/ +def Quotas.stamp (q : Quotas J Z) (f : J → Axis J Z → Vector M) : Shapes M where + rows := q.rows.map fun i => (f q.mark (.inr (false, i.1)), f q.mark (.inr (true, i.1))) + ports := q.ports.map fun p => f p.1.1 (.inl p.1.2) + +namespace Marking +variable {C : V → Surface.Cell F (M * r) (M * t) U E X} {a b : Wire} {Y : Alphabet K} + {S : Sharing C a b Y} (m : Marking S J Z A) (e : E → ℕ) + +open Classical in +/-- The indexed operation `⟨m.mark v, (secondList C v).map fun i => (m.number i, (item C i).a, +(item C i).b), (C v).ports.map fun p => (m.edge p.1, e p.1)⟩`. -/ +def quotas (v : V) : Quotas J Z := + ⟨m.mark v, (secondList C v).map fun i => (m.number i, (item C i).a, (item C i).b), + (C v).ports.map fun p => (m.edge p.1, e p.1)⟩ + +open Classical in +theorem row_here (v : V) (i : Place C) : i ∈ secondList C v ↔ i.1 = v := by + constructor + · rintro hi + obtain ⟨_, _, rfl⟩ := List.mem_map.mp hi + rfl + · rintro rfl + exact List.mem_map.mpr ⟨i.2, List.mem_finRange _, rfl⟩ + +open Classical in +theorem items (v : V) (i : Axis J Z) (n : ℕ) : + (i, n) ∈ (m.quotas e v).items ↔ ∃ j, m.address j = (v, i) ∧ cost C e j = n := by + constructor + · rintro (⟨_, hp, he, hi⟩|⟨_, hx, hi⟩) + · obtain ⟨⟨j, w⟩, hj, rfl⟩ := List.mem_map.mp hp + have hs : S.src j = v := by + rcases S.meets v (j, w) hj with h|h + · exact h + · exact (m.marks j (he.trans (congrArg m.mark h.symm))).trans h + obtain ⟨rfl, rfl⟩ := Prod.mk.inj hi + exact ⟨.inl (.inl j), Prod.ext hs rfl, rfl⟩ + · obtain ⟨j, hj, rfl⟩ := List.mem_map.mp hx + have he := (row_here v j).mp hj + rcases hi with hi|hi <;> obtain ⟨rfl, rfl⟩ := Prod.mk.inj hi + · exact ⟨.inl (.inr j), Prod.ext he rfl, rfl⟩ + · exact ⟨.inr j, Prod.ext he rfl, rfl⟩ + · rintro ⟨(j|j)|j, hj, rfl⟩ <;> obtain ⟨rfl, rfl⟩ := Prod.mk.inj hj + · obtain ⟨w, hw⟩ := m.ports (S.src j) j (.inl rfl) + exact .inl ⟨_, List.mem_map_of_mem hw, rfl, rfl⟩ + · exact .inr ⟨_, List.mem_map_of_mem ((row_here _ j).mpr rfl), .inl rfl⟩ + · exact .inr ⟨_, List.mem_map_of_mem ((row_here _ j).mpr rfl), .inr rfl⟩ + +variable (loc : V ↪ I) (qs : I → Option (Quotas J Z)) + (hl : ∀ v, qs (loc v) = some (m.quotas e v)) (hv : ∀ i ∉ Set.range loc, qs i = none) + +include hl hv in +open Classical in +theorem target_eq (i : I) (j : Axis J Z) : + quota (qs i) j = Pick.target (m.shapeSeat loc) (cost C e) (i, j) := by + have he (n : ℕ) : (∃ t ∈ qs i, (j, n) ∈ t.items) ↔ + ∃ k, m.shapeSeat loc k = (i, j) ∧ cost C e k = n := by + constructor + · rintro ⟨t, ht, hj⟩ + by_cases hi : i ∈ Set.range loc + · obtain ⟨v, rfl⟩ := hi + rw [hl] at ht + cases Option.some.inj ht + obtain ⟨k, hk, rfl⟩ := (m.items e v j n).mp hj + exact ⟨k, congrArg (Prod.map loc id) hk, rfl⟩ + · simp [hv i hi] at ht + · rintro ⟨k, hk, rfl⟩ + change (loc (m.address k).1, (m.address k).2) = (i, j) at hk + obtain ⟨rfl, rfl⟩ := Prod.mk.inj hk + exact ⟨_, hl _, (m.items ..).mpr ⟨k, rfl, rfl⟩⟩ + unfold quota Pick.target + split_ifs with ht + · obtain ⟨k, hk, he⟩ := (he _).mp ht.choose_spec + exact he.symm.trans ((m.shapeSeat loc).injective.extend_apply _ _ _).symm |>.trans + (congrArg _ hk) + · symm + apply Function.extend_apply' + rintro ⟨k, hk⟩ + exact ht ⟨_, (he _).mpr ⟨k, hk, rfl⟩⟩ + +end Marking +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Extracting shape budgets, shapes and their scalar signs locally -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Surface Surface.Local Finset +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place item Profile + secondList) + +variable {F T V E X J I K N Z : Type} {r t M q : ℕ} + {s : Stage F (M * r) (M * t) T V E X} + +open Classical in +/-- The indexed operation `⟨mark, (indexed b.rows).map fun ⟨i, x⟩ => (number i x.role, x.a, +x.b), b.ports.map fun j => (j.1, j.2.2)⟩`. -/ +def ofBody (b : Body F r t q K N) (mark : Fin q) (number : ℕ → Role → Z) : Quotas (Fin q) Z := + ⟨mark, (indexed b.rows).map fun ⟨i, x⟩ => (number i x.role, x.a, x.b), + b.ports.map fun j => (j.1, j.2.2)⟩ + +variable [Fintype V] {Y : Alphabet V} {a b : Wire} {Q : Key.Source Y a b s} + {R : Reference J I N V E T X} {β : V ⊕ ℕ → K} + {B : Record F (M * r) (M * t) V E K N} (h : Matches R.world β s B) + (m : Marking (Key.share s Q) (Fin q) Z K) + +open Classical in +theorem ofBody_eq (number : ℕ → Role → Z) (hnum : ∀ i, m.number i = number i.2.val (h.row i).role) + (v : V) : ofBody (B.body m.edge v) (m.mark v) number = m.quotas s.scene.level v := by + have hp : (s.scene.cell v).ports = B.ports v := by + have hh := h.ports v + change (s.scene.cell v).ports = (B.ports v).map id at hh + simpa using hh + have he (i : E) : s.scene.level i = B.level i := h.level i + simp only [ofBody, Record.body, Marking.quotas, indexed_rows h, ← hp, List.map_map] + congr 1 + · apply List.map_congr_left + intro i _ + exact Prod.ext (hnum i).symm (Prod.ext (h.represents i).left.symm (h.represents i).right.symm) + · apply List.map_congr_left + intro i _ + exact Prod.ext rfl (he i.1).symm + +open Classical in +theorem stamp_eq {I : Type} (loc : V ↪ I) (p : Profile s.scene.cell s.scene.level) + {z : ℕ} (hz : ∀ j, cost s.scene.cell s.scene.level j < 2 ^ z) (v : V) + (read : Fin q → Axis (Fin q) Z → Vector M) + (ha : ∀ w, (w = v ∨ ∃ e, uses (Key.share s Q) v e ∧ Q.src e = w) → ∀ i j, + read (m.mark w) i j = ((m.select loc _ hz).write p (loc w, i) j).val) : + (m.quotas s.scene.level v).stamp read = shapeStamp s p v := by + simp only [Marking.quotas, Quotas.stamp, shapeStamp, List.map_map] + congr 1 + · apply List.map_congr_left + intro i hi + have hh := (Marking.row_here _ _).mp hi + subst v + refine Prod.ext (funext fun j => ?_) (funext fun j => ?_) + · exact (ha _ (.inl rfl) _ _).trans (m.select_first loc _ hz p i j) + · exact (ha _ (.inl rfl) _ _).trans (m.select_second loc _ hz p i j) + · apply List.map_congr_left + intro i hi + exact funext fun j => (ha _ (.inr ⟨i.1, Q.meets v i hi, rfl⟩) _ _).trans + (m.select_seam loc _ hz p i.1 j) + +open Classical in +private theorem shuffle_map {A B : Type} (f : A → B) (g : B → Vector M) (l : List A) : + Plant.shuffle g (List.finRange M) (l.map f) = Plant.shuffle (g ∘ f) (List.finRange M) l := by + induction l with + | nil => rfl + | cons a l ih => + simp only [List.map_cons, Plant.shuffle, ih, Function.comp_apply, List.map_map, + Function.comp_def] + +open Classical in +/-- The sign of type `F` for the given inputs. -/ +def Shapes.sign (F : Type) [Field F] (p : Shapes M) : F := + (-1) ^ Plant.shuffle id (List.finRange M) (p.rows.map Prod.fst ++ p.ports) * + (-1) ^ Plant.shuffle id (List.finRange M) (p.rows.map Prod.snd) + +open Classical in +theorem sign_stamp [Field F] (p : Profile s.scene.cell s.scene.level) : + ∏ v, (shapeStamp s p v).sign F = p.sign := by + unfold Layout.Profile.sign + rw [← prod_mul_distrib] + apply prod_congr rfl + intro v _ + let f (i : Layout.Marked s.scene.cell) (j : Fin M) + := ((p.1 (Layout.source s.scene.cell i)).val j).val + let g (i : Place s.scene.cell) (j : Fin M) := ((p.2 i).val j).val + have ha : (shapeStamp s p v).rows.map Prod.fst ++ (shapeStamp s p v).ports = + (Layout.firstList s.scene.cell v).map f := by + simp only [Layout.firstList, shapeStamp, List.map_append, List.map_map] + rfl + have hb : (shapeStamp s p v).rows.map Prod.snd = (secondList s.scene.cell v).map g := by + simp only [shapeStamp, List.map_map]; rfl + rw [Shapes.sign, ha, hb, shuffle_map, shuffle_map] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# A single window for the final shape selection + +A window contains the indicated station widths, the terminal records +and the proposed shape digits. Its score rejects invalid digits. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Surface Surface.Local Coloring + +open Classical in +/-- The data for the face construction, including `ext`, `color`, `tile`. -/ +structure Face (F : Type) (r t q : ℕ) (K N : Type) where + /-- The `Face` component of type `Option N → Bool → ℕ`. -/ + ext : Option N → Bool → ℕ + /-- The `Face` component of type `Fin q`. -/ + color : Fin q + /-- The `Face` component of type `Tile F r t q K N`. -/ + tile : Tile F r t q K N + +open Classical in +/-- The indexing data represented by `Axis (Fin q) (Number D k) → Digits M z`. -/ +abbrev Ballot (M q D k z : ℕ) := Axis (Fin q) (Number D k) → Digits M z + +open Classical in +/-- Indexes the lens by the coordinates of `Sight d (Option (Face F (M * r) (M * t) q K N) × +Ballot M q D k z)`. -/ +abbrev Lens (F K N : Type) (M r t q D k z d : ℕ) := + Sight d (Option (Face F (M * r) (M * t) q K N) × Ballot M q D k z) + +variable {F K N : Type} {M r t q D k z d : ℕ} + +open Classical in +/-- The quantity computed by `(decide (j = .collector), ⟨i % D ^ k, Nat.mod_lt _ h⟩)`. -/ +def number (h : 0 < D ^ k) (i : ℕ) (j : Role) : Number D k := + (decide (j = .collector), ⟨i % D ^ k, Nat.mod_lt _ h⟩) + +namespace Lens +variable (v : Lens F K N M r t q D k z d) (h : 0 < D ^ k) + +open Classical in +/-- Evaluates `(v i j).1.map Face.color` at the input `i j`. -/ +def tone : Sight d (Option (Fin q)) := fun i j => (v i j).1.map Face.color + +open Classical in +/-- Computes the nearby by the application `v 0 (search (v.tone 0) j)`. -/ +def nearby (j : Fin q) := v 0 (search (v.tone 0) j) +open Classical in +/-- Maps the coordinate `i` to `((v.nearby x).2 j i).val`. -/ +def read (x : Fin q) (j : Axis (Fin q) (Number D k)) : Vector M := + fun i => ((v.nearby x).2 j i).val + +open Classical in +/-- Transforms the indexed data by `(v 0 0).1.map fun x => ofBody x.tile.toBody x.color (number +h)`. -/ +def ask := (v 0 0).1.map fun x => ofBody x.tile.toBody x.color (number h) + +open Classical in +/-- The condition `∀ i, tally ((v 0 0).2 i) = quota (v.ask h) i` on the specified data. -/ +def valid := ∀ i, tally ((v 0 0).2 i) = quota (v.ask h) i + +open Classical in +/-- The value specified by `(ofBody x.tile.toBody x.color (number h)).stamp v.read`. -/ +def plan (x : Face F (M * r) (M * t) q K N) : Shapes M := + (ofBody x.tile.toBody x.color (number h)).stamp v.read + +open Classical in +/-- Returns `(v 0 0).1.elim 1 (fun x => (v.plan h x).sign F)` when `v.valid h` holds, and `0` +otherwise. -/ +def score [Field F] : F := + if v.valid h then (v 0 0).1.elim 1 (fun x => (v.plan h x).sign F) else 0 + +open Classical in +/-- The indexed operation `Finset.univ.biUnion fun j => ((v.nearby j).1.elim ∅ (fun x => +x.tile.footprint)).image (j, ·)`. -/ +def keys : Finset (Fin q × K) := + Finset.univ.biUnion fun j => ((v.nearby j).1.elim ∅ (fun x => x.tile.footprint)).image (j, ·) + +open Classical in +theorem keys_at (j : Fin q) (a : K) : + (j, a) ∈ v.keys ↔ a ∈ (v.nearby j).1.elim ∅ (fun x => x.tile.footprint) := by + simp [keys] + +open Classical in +/-- Transforms the indexed data by `(v 0 0).1.map (fun x => (ofTile x.tile x.color (number h) +x.ext (v.plan h x), v.keys))`. -/ +def page : Option (Page F (Fin q) (Number D k) K M r t) := + (v 0 0).1.map (fun x => (ofTile x.tile x.color (number h) x.ext (v.plan h x), v.keys)) + +end Lens + +variable {V E : Type} {m b R : ℕ} {a : Atlas V E m d b} (π : Palette a R q) + (f : V → Face F (M * r) (M * t) q K N) (sel : B m × B b → Ballot M q D k z) + +open Classical in +/-- The indexed operation `scan a (fun i => (a.fill f i, sel i)) x`. -/ +def lens (a : Atlas V E m d b) (f : V → Face F (M * r) (M * t) q K N) + (sel : B m × B b → Ballot M q D k z) (x : B m × B b) : Lens F K N M r t q D k z d := + scan a (fun i => (a.fill f i, sel i)) x + +open Classical in +theorem center (x : B m × B b) : lens a f sel x 0 0 = (a.fill f x, sel x) := by + simp [lens, scan] + +variable (hf : ∀ i, (f i).color = π.mark i) +include hf + +open Classical in +theorem tones (v : V) : (lens a f sel (a.coord v)).tone = colors π v := by + have e (i) : (a.fill f i).map Face.color = a.fill π.mark i := by + by_cases h : i ∈ Set.range a.coord + · obtain ⟨w, rfl⟩ := h + simp [a.fill_at, hf] + · simp [a.fill_away _ h] + exact funext fun i => funext fun j => e _ + +open Classical in +theorem close_by (hR : 2 ≤ R) {v w : V} (h : a.near 1 v w) : + (lens a f sel (a.coord v)).nearby (π.mark w) = (some (f w), sel (a.coord w)) := by + rw [Lens.nearby, tones π f sel hf] + simp only [lens, scan, Atlas.around_zero, located π hR h, Atlas.fill_at] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- # Agreement between terminal labels and the physical drawing -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print + +open Surface Surface.Local Coloring Finset +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Profile) + +variable {F T V E X K N : Type} [Fintype V] {r t M q D k m d b R z : ℕ} + {s : Stage F (M * r) (M * t) T V E X} {Y : Alphabet V} {x y : Wire} {Q : Key.Source Y x y s} + {a : Atlas V E m d b} (π : Palette a R q) (hp : 0 < D ^ k) + (W : Marking (Key.share s Q) (Fin q) (Number D k) K) (rules : Order.Rules (Key.share s Q)) + (f : V → Face F (M * r) (M * t) q K N) + +open scoped Classical in +/-- The data for the aligned construction, including `radius`, `mark`, `color`, `near`, +`quotas`. -/ +structure Aligned : Prop where + radius : 2 ≤ R + mark : W.mark = π.mark + color : ∀ i, (f i).color = π.mark i + near : ∀ i, a.near 1 (Q.src i) (Q.dst i) + quotas : ∀ i, ofBody (f i).tile.toBody (f i).color (number hp) = W.quotas s.scene.level i + keys : ∀ i, (f i).tile.footprint = ((Key.share s Q).seen i).image W.key + sheet : ∀ p i, ofTile (f i).tile (f i).color (number hp) (f i).ext (shapeStamp s p i) = + W.sheet rules p i + +namespace Aligned +variable {π hp W rules f} (A : Aligned π hp W rules f) + (hz : ∀ j, cost s.scene.cell s.scene.level j < 2 ^ z) + (p : Profile s.scene.cell s.scene.level) (sel : B m × B b → Ballot M q D k z) + +open scoped Classical in +/-- Evaluates `(W.select a.coord _ hz).write p (v, i)` at the input `v i`. -/ +abbrev ballots (_ : Aligned π hp W rules f) (hz : ∀ j, cost s.scene.cell s.scene.level j < 2 ^ z) + (p : Profile s.scene.cell s.scene.level) : B m × B b → Ballot M q D k z := + fun v i => (W.select a.coord _ hz).write p (v, i) + +include A + +open scoped Classical in +theorem connected {e : E} {v w : V} (hv : uses (Key.share s Q) v e) (hw : uses (Key.share s Q) w e) + : + a.near 1 v w := by + rcases hv with rfl|rfl <;> rcases hw with rfl|rfl + · exact .refl .. + · exact A.near _ + · exact (A.near _).symm + · exact .refl .. + +open scoped Classical in +theorem observes (v : V) : + W.Observes v (fun j k => (j, k) ∈ (lens a f sel (a.coord v)).keys) := by + apply W.observes + intro i hi w hw e + rw [Lens.keys_at, A.mark, close_by π f sel A.color A.radius (A.connected hi hw)] + simp only [Option.elim_some, A.keys] + +open scoped Classical in +theorem plan (v : V) : (lens a f (A.ballots hz p) (a.coord v)).plan hp (f v) = shapeStamp s p v + := by + rw [Lens.plan, A.quotas] + apply stamp_eq W a.coord p hz + intro w hw i j + have hn : a.near 1 v w := by + rcases hw with rfl|⟨e, he, rfl⟩ + · exact .refl .. + · exact A.connected he (.inl rfl) + rw [Lens.read, A.mark, close_by π f _ A.color A.radius hn] + +open scoped Classical in +theorem page (v : V) : + (lens a f (A.ballots hz p) (a.coord v)).page hp = + some (W.sheet rules p v, (lens a f (A.ballots hz p) (a.coord v)).keys) := by + rw [Lens.page, center, Atlas.fill_at, Option.map_some, A.plan hz p v, A.sheet] + +open scoped Classical in +theorem valid_iff : + (∀ i, (lens a f sel i).valid hp) ↔ + ((W.select a.coord _ hz).read (fun i => sel i.1 i.2)).isSome := by + let qs i := (lens a f sel i).ask hp + have ha (v) : qs (a.coord v) = some (W.quotas s.scene.level v) := by + simp [qs, Lens.ask, center, Atlas.fill_at, A.quotas] + have hv (i) (h : i ∉ Set.range a.coord) : qs i = none := by + simp [qs, Lens.ask, center, a.fill_away _ h] + rw [W.select_some] + change (∀ i j, _ = quota (qs i) j) ↔ _ + simp only [W.target_eq s.scene.level a.coord qs ha hv, center, Pick.accepts, Prod.forall] + +open scoped Classical in +theorem score [Field F] : + ∏ i, (lens a f sel i).score hp = + ((W.select a.coord _ hz).read (fun i => sel i.1 i.2)).elim 0 Layout.Profile.sign := by + cases he : (W.select a.coord _ hz).read (fun i => sel i.1 i.2) with + | none => + have hf : ¬ ∀ i, (lens a f sel i).valid hp := by rw [A.valid_iff hz sel, he]; simp + obtain ⟨i, hi⟩ := not_forall.mp hf + exact prod_eq_zero (mem_univ i) (ite_eq_right hi) + | some p => + have hw := ((W.select a.coord _ hz).valid _ _).mp he + have ht : sel = A.ballots hz p := funext fun i => funext fun j => congrFun hw (i, j) + have hv : ∀ i, (lens a f sel i).valid hp := (A.valid_iff hz sel).mpr (by simp [he]) + subst sel + simp only [Option.elim_some, Lens.score, hv, ite_true, center] + rw [← sign_stamp p, ← prod_subset (subset_univ (univ.map a.coord)), prod_map] + · simp [Atlas.fill_at, A.plan] + · intro i _ hi + have ha : i ∉ Set.range a.coord := by simpa [Set.mem_range] using hi + simp [a.fill_away _ ha] + +end Aligned +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end + +/- +# Recovering relay addresses from a two-step view + +The origin has index zero. Every other neighboring host occurs +once after deduplication. This determines both orientations of a link. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +open Coloring Assembly Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Sharing Node) + +variable {V E : Type} {m d h R q : ℕ} {a : Atlas V E m d h} (π : Palette a R q) + +open Classical in +theorem turn_hop (hR : 2 ≤ R) {v w u : V} (hv : a.near 1 v w) (hu : a.near 1 w u) : + (colors π v).turn (π.mark w) (π.mark u) = Children.hop a.graph (a.coord w).1 (a.coord u).1 := by + rw [turn_eq π hR hv] + by_cases e : (a.coord w).1 = (a.coord u).1 + · have := a.coord.injective (Prod.ext e hu.1) + subst u + simp [search, colors, scan, Atlas.fill_at] + · exact Neighborhood.unique (congrArg Prod.fst (located π hR hu)) + (Children.expand_hop hu.2) (Ne.symm e) + +variable {D k n M b : ℕ} + +open Classical in +/-- Builds `Guide (Spot (Fin q) (Number D k) M) (Sharing.radius k * n) (Children.degree d b) +where branch x y j` with the specified `Guide`, `let`, `if`. -/ +def wiring (hD : D = 2 ^ n) (hd : 4 ≤ D) (hc : M ≤ D ^ k) (hb : 2 ^ ((d + 1) * 1) ≤ D ^ k + 1) + (slot : Children.Part M D k n ↪ B b) (o : Sight d (Option (Fin q))) : + Guide (Spot (Fin q) (Number D k) M) (Sharing.radius k * n) (Children.degree d b) where + branch x y j := + let code := Sharing.Geo.steeringCode hD hd hc ((o.turn x.1 y.1).castLE hb, y.2) + if Sharing.frozenSlot x.2 then code else fun i => if i.val < j.val then code i else false + next x y := (Match.rowIndex _ b).symm (o.turn (root x).1 (root y).1, slot (lift Prod.snd y)) + +variable {F T X K Z : Type} [Field F] [Fintype V] [Fintype E] [Fintype K] + {r t : ℕ} {C : V → Surface.Cell F (M * r) (M * t) T E X} {x y : Wire} {Y : Layout.Alphabet K} + {S : Sharing C x y Y} {T₀ R₀ g : ℕ} {W : ℝ} {P : Rounds.Input F x y h D T₀ R₀ g W} + (G : S.Geo P k) (L : Marking S (Fin q) (Number D k) Z) (old : P.V ↪ B m) + (hb : 2 ^ ((d + 1) * 1) ≤ D ^ k + 1) + +open Classical in +/-- The data for the circuit map construction, including `coord`, `slot`, `rank`, `near`, +`radius`. -/ +structure CircuitMap : Prop where + coord : ∀ i, (a.coord i).1 = old (G.site i).1 + slot : ∀ i, L.spot i = (π.mark (S.home i), G.slot i) + rank : ∀ v w, G.steer.rank v w = (Children.hop a.graph (old v) (old w)).castLE hb + near : ∀ e, a.near 1 (S.src e) (S.dst e) + radius : 2 ≤ R + +namespace CircuitMap +variable {π G L old hb} (A : CircuitMap π G L old hb) + (hD : D = 2 ^ n) (hd : 4 ≤ D) (slot : Children.Part M D k n ↪ B b) + {e : E → ℕ} (p : Layout.Profile C e) (j u : ℕ) + +local notation "H" => G.layout hD hd p j +local notation "net" => S.backdrop.emitted p j +local notation "guide" => wiring hD hd G.chunks hb slot +local notation "idx" => Children.idx old slot a.graph + +include A + +open Classical in +theorem contact (i : (net).E) : a.near 1 (S.home ((net).src i)) (S.home ((net).dst i)) := by + rcases i with ⟨i, z|z|z⟩|⟨i, z⟩|⟨i, z⟩|⟨i, z⟩ + · exact .refl .. + · exact A.near _ + · exact .refl .. + · exact A.near _ + · exact .refl .. + · exact .refl .. + +open Classical in +theorem linked {i : (net).E} {v w : S.Position} (hv : touches net v i) (hw : touches net w i) : + a.near 1 (S.home v) (S.home w) := by + rcases hv with rfl|rfl <;> rcases hw with rfl|rfl + · exact .refl .. + · exact A.contact p j i + · exact (A.contact p j i).symm + · exact .refl .. + +open Classical in +theorem follows {v : S.Position} (i : (net).E) (hi : touches net v i) : + Follows H L.spot (guide (colors π (S.home v))).branch i := by + intro s + have he := turn_hop π A.radius (A.linked p j hi (touches_side net s i)) + (A.linked p j (touches_side net s i) (touches_side net (!s) i)) + rw [A.slot, A.slot] + funext l + simp only [wiring, he, A.coord] + unfold Layout.Trie.address + simp only [Sharing.Geo.place, A.rank] + rfl + +open Classical in +theorem go (v w : Node S.Position (Sharing.radius k * n)) + (hnear : a.near 1 (S.home (root v)) (S.home (root w))) : + (guide (colors π (S.home (root v)))).next (lift L.spot v) (lift L.spot w) = pointer H idx v w + := by + have he := turn_hop π A.radius (.refl a 1 _) hnear + have hs (z : Node S.Position (Sharing.radius k * n)) : + lift Prod.snd (lift L.spot z) = lift Prod.snd ((H).place z).1 := by + cases z with + | inl i => exact congrArg (fun z => Sum.inl z.2) (A.slot i) + | inr i => exact congrArg (fun z => Sum.inr (z.2, i.2)) (A.slot i.1) + have ht (z : Node S.Position (Sharing.radius k * n)) : + (root ((H).place z).1).1 = (G.site (S.home (root z))).1 := by cases z <;> rfl + simp only [wiring, root_lift, A.slot, he, A.coord, hs, pointer, Children.idx, ht] + +open Classical in +theorem emit (rules : Order.Rules S) (v : Node S.Position (Sharing.radius k * n)) + (req : Request F (Fin q) (Number D k) Z M r t (Sharing.radius k * n) (Children.degree d b)) + (hs : req.sheet = L.sheet rules p (S.home (root v))) + (ho : L.Observes (S.home (root v)) req.known) (hv : req.seat = lift L.spot v) + (hg : req.guide = guide (colors π (S.home (root v)))) : + req.emit j u = some ((L.names p j u H idx).star ((H).routed (rules.script p j) u) v) := by + rw [Request.emit, hv, hg, hs, root_lift, L.inventory_eq rules p j _ _ ho] + apply congrArg some + symm + apply printed H u L.lane (L.unique p j) (pointer H idx) (rules.script p j) L.spot v (L.same p j _) + _ (fun i hi => A.follows hD hd slot p j i hi) + intro s i hi + apply A.go hD hd slot p j + exact A.linked p j (hi ▸ end_root H u s i) (end_root H u (!s) i) + +end CircuitMap +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Work.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Work.lean new file mode 100644 index 0000000000..3f22a97b03 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Print/Work.lean @@ -0,0 +1,596 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Children.Correct +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Follow +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Reset.Child.Headers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Capacity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Shows +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Processor.Labels +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Price + +/-! Build the next host graph from a rule reading only short per-host data. -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring History.Reset + +/-- The indexing data represented by `(Info e).obj → B w → (Child.Suffix (hops e) w (degree e +w)).obj`. -/ +abbrev Rule (e w : ℕ) := (Info e).obj → B w → (Child.Suffix (hops e) w (degree e w)).obj + +/-- The indexed operation `Child.build m (hops e) w (degree e w) ((prepare r).1, fun i => f +((prepare r).2 (Match.rowIndex m w i).1) (Match.rowIndex m w i).2)`. -/ +def build {m e : ℕ} (w : ℕ) (f : Rule e w) (r : (Tape m e).obj) : + (Child.Graph (m + w) (degree e w)).obj := + Child.build m (hops e) w (degree e w) + ((prepare r).1, fun i => f ((prepare r).2 (Match.rowIndex m w i).1) (Match.rowIndex m w i).2) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- Construct the short masks in parallel, apply an arbitrary rule locally, +then recover full child addresses using the parent navigation rows. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring History.Reset +variable (F : Type) [Field F] {m e w t : ℕ} + +open scoped Classical in +/-- The quantity computed by `2 ^ m * (100 + m + 2 ^ (1 + 2 ^ e + 12 * (2 ^ e) ^ 3 + 2 ^ w)) ^ +220`. -/ +def cost (m e w : ℕ) := 2 ^ m * (100 + m + 2 ^ (1 + 2 ^ e + 12 * (2 ^ e) ^ 3 + 2 ^ w)) ^ 220 + +open scoped Classical in +private theorem prepare_net (ht : m + 2 ^ (hops e) ≤ t) : + Cheap F m t (Tape m e) (Query m e) prepare 210 := by + have hm : m ≤ t := (Nat.le_add_right _ _).trans ht + have hq : 2 ^ (hops e) ≤ t := by omega + have he : 2 ^ e ≤ t := (Nat.pow_le_pow_right (by decide) (by simp [hops])).trans hq + have ha : (Tape m e).width ≤ 2 ^ m * (100 + t) ^ 2 := by + simp only [Tape, Header, Neighborhood.Rows, Format.width_pair, Format.width_vec, + Format.width_addr, + ← mul_add] + rw [Format.width_bit, mul_one] + apply Nat.mul_le_mul_left + have h := Nat.mul_le_mul he hm + ring_nf at h ⊢ + omega + have src := Cheap.id F ha + have g := src.fst.comp ((Neighborhood.cheap F m e 1 (by decide)).widen ht) + have one := (g.pair src.fst).comp (Neighborhood.cheap_maskRows F hm hq he) + have two := (g.pair g).comp (Neighborhood.cheap_maskRows F hm hq hq) + exact (g.pair (src.snd.pair (one.pair two).zip).zip).mono (by decide) + +open scoped Classical in +private abbrev Suffix (e w : ℕ) := Child.Suffix (hops e) w (degree e w) + +open scoped Classical in +private def suffixes (f : Rule e w) (x : (Format.vec m (Info e)).obj) : + (Format.vec (m + w) (Suffix e w)).obj := + fun i => f (x (Match.rowIndex m w i).1) (Match.rowIndex m w i).2 + +open scoped Classical in +private theorem suffixes_local (f : Rule e w) : + Install.Depends ((Format.vec (m + w) (Suffix e w)).code ∘ suffixes f ∘ + (Format.vec m (Info e)).code.symm) (Info e).width := by + rintro ⟨i, j⟩ + let p := (Match.rowIndex m w i).1 + refine ⟨Finset.univ.image (Prod.mk p), Finset.card_image_le, fun x y he => ?_⟩ + have h : (Format.vec m (Info e)).code.symm x p = (Format.vec m (Info e)).code.symm y p := by + apply (Info e).code.injective + funext a + exact (congrFun ((Format.vec m (Info e)).code.apply_symm_apply x) (p, a)).trans + ((he (p, a) (Finset.mem_image_of_mem _ (Finset.mem_univ a))).trans + (congrFun ((Format.vec m (Info e)).code.apply_symm_apply y) (p, a)).symm) + exact congrArg (fun v => (Suffix e w).code (f v (Match.rowIndex m w i).2) j) h + +open scoped Classical in +private theorem suffixes_net (hi : 2 ^ (Info e).width ≤ t) (hd : 2 ^ (degree e w) ≤ t) + (f : Rule e w) : + Cheap F m t (.vec m (Info e)) (.vec (m + w) (Suffix e w)) (suffixes f) 6 := by + let I := (Info e).width + let D := 2 ^ w * (Suffix e w).width + have hI : I ≤ t := (Nat.lt_pow_self (by decide : 1 < 2)).le.trans hi + have hL : Install.localCost I ≤ 18 * t := by + change 2 ^ I ≤ t at hi + rw [Install.localCost, pow_succ] + omega + have hl : hops e + w ≤ t := (Nat.lt_pow_self (by decide : 1 < 2)).le.trans hd + have hw : 2 ^ w ≤ t := + (Nat.pow_le_pow_right (by decide) (Nat.le_add_left w (hops e))).trans hd + have hD : D ≤ t * (2 + t * (3 + t)) := by + apply Nat.mul_le_mul hw + simp only [Suffix, Child.Suffix, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit, Format.width_addr (hops e + 1)] + exact Nat.add_le_add_left (Nat.mul_le_mul hd (by omega)) _ + refine ⟨_, (suffixes_local f).bnet F, ?_⟩ + let A := Format.vec m (Info e) + let B := Format.vec (m + w) (Suffix e w) + change A.width + B.width + (A.width + Install.localCost I * B.width) ≤ _ + have hb : B.width = 2 ^ m * D := by rw [Format.width_vec, pow_add, mul_assoc] + rw [hb, show A.width = 2 ^ m * I from Format.width_vec _ _] + calc + _ = 2 ^ m * (I + D + (I + Install.localCost I * D)) := by ring + _ ≤ 2 ^ m * (t + t * (2 + t * (3 + t)) + (t + 18 * t * (t * (2 + t * (3 + t))))) := by gcongr + _ ≤ _ := by apply Nat.mul_le_mul_left; ring_nf; omega + +open scoped Classical in +private theorem assemble_cost (hm : m ≤ t) (hd : 2 ^ (degree e w) ≤ t) : + Child.buildCost m (hops e) w (degree e w) ≤ 2 ^ m * (100 + t) ^ 6 := by + have hl : hops e + w ≤ t := (Nat.lt_pow_self (by decide : 1 < 2)).le.trans hd + have he : m + w + degree e w + hops e = m + (degree e w + degree e w) + := by unfold degree hops; omega + rw [Child.buildCost, he, pow_add, pow_add] + calc + _ ≤ 1000 * (2 ^ m * (t * t)) * (2 + t) * (4 + t + t) := by gcongr <;> omega + _ ≤ _ := by ring_nf; omega + +open scoped Classical in +theorem build_net {m e : ℕ} (w : ℕ) (f : Rule e w) : + Circuit F (Tape m e) (Child.Graph (m + w) (degree e w)) (build w f) (cost m e w) := by + let b := 1 + 2 ^ e + 12 * (2 ^ e) ^ 3 + 2 ^ w + let t := m + 2 ^ b + have hi : (Info e).width ≤ b := by + refine (le_of_eq ?_).trans (Nat.le_add_right (1 + 2 ^ e + 12 * (2 ^ e) ^ 3) (2 ^ w)) + simp only [Info, comparisons, Format.width_pair, Format.width_vec, hops, mul_one, pow_succ] + rw [Format.width_bit] + ring + have hd : degree e w ≤ b := by + have := Nat.lt_pow_self (n := e) (by decide : 1 < 2) + have := Nat.lt_pow_self (n := w) (by decide : 1 < 2) + unfold degree b + omega + have grow {a : ℕ} (h : a ≤ b) : 2 ^ a ≤ t := + (Nat.pow_le_pow_right (by decide) h).trans (Nat.le_add_left _ _) + have ht : m + 2 ^ (hops e) ≤ t := Nat.add_le_add_left + (Nat.pow_le_pow_right (by decide) ((Nat.le_add_right _ _).trans hd)) m + have prep := prepare_net F ht + have args := prep.fst.pair (prep.snd.comp (suffixes_net F (grow hi) (grow hd) f)) + obtain ⟨n, hnet, hn⟩ := args.mono (d := 219) (by decide) + have net := hnet.comp (Child.build_net F m (hops e) w (degree e w)) + apply net.mono + have hh := (assemble_cost (m := m) (Nat.le_add_right m (2 ^ b)) (grow hd)).trans + (Nat.mul_le_mul_left (2 ^ m) (Nat.pow_le_pow_right (by positivity : 0 < 100 + t) (by decide : 6 + ≤ 219))) + unfold cost + rw [add_assoc 100] + change n + _ ≤ 2 ^ m * (100 + t) ^ 220 + rw [show 220 = 219 + 1 from rfl, pow_succ, ← mul_assoc] + exact (show n + _ ≤ (2 ^ m * (100 + t) ^ 219) * 2 by omega).trans + (Nat.mul_le_mul_left _ ((by decide : 2 ≤ 100).trans (Nat.le_add_right _ _))) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- # Writing replicated trie records and their graph on one circuit -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +open Assembly Coloring MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +variable {V : Type} {M D k d m e w : ℕ} +open Assembly.History.Reset +variable (slot : Part M D k d ↪ B w) + (hD : D = 2 ^ d) (hd : 4 ≤ D) (hc : M ≤ D ^ k) (hb : 2 ^ (hops e) ≤ D ^ k + 1) + +open scoped Classical in +/-- The quantity computed by `Child.Graph (m + w) (degree e w)`. -/ +abbrev graphFmt (m e w : ℕ) := Child.Graph (m + w) (degree e w) + +open scoped Classical in +/-- The bound obtained by adding the component charges `cost m e w + 100 * ((input m e h +l).width + (output m e h l w).width + (labels m h l w).width + (Tape m e).width + (graphFmt +m e w).width)`. -/ +def writeCost (m e h l w : ℕ) := cost m e w + + 100 * ((input m e h l).width + (output m e h l w).width + (labels m h l w).width + + (Tape m e).width + (graphFmt m e w).width) + +variable {h l : ℕ} +local notation "A" => input m e h l +local notation "D₁" => output m e h l w +local notation "L" => labels m h l w +local notation "G" => graphFmt m e w + +open scoped Classical in +private theorem label_depends : + Install.Depends ((L).code ∘ label w ∘ (A).code.symm) 1 := by + rintro ⟨i, j, s⟩ + obtain ⟨q, hq⟩ := Match.append_pin l w s + let p := Match.rowIndex m w i + have eq (x : (A).pins → Bool) : + ((L).code ∘ label w ∘ (A).code.symm) x (i, j, s) = + Sum.elim (fun v => x (.inl (p.1, .inr (j, v)))) ((Format.addr w).code p.2) q := by + refine (hq _ _).trans ?_ + cases q with + | inl v => exact congrFun ((A).code.apply_symm_apply x) (.inl (p.1, .inr (j, v))) + | inr _ => rfl + cases q with + | inl v => + refine ⟨{.inl (p.1, .inr (j, v))}, by simp, fun x y he => ?_⟩ + rw [eq, eq] + exact he _ (by simp) + | inr _ => exact ⟨∅, by simp, fun x y _ => (eq x).trans (eq y).symm⟩ + +variable (F : Type) [Field F] + +open scoped Classical in +private theorem join_net : + Circuit F (.pair G L) D₁ join ((Format.pair G L).width + 2 * (D₁).width) := by + let i : (D₁).pins → (Format.pair G L).pins + | .inl (v, .inl j) => .inl (.inl (v, j)) + | .inl (v, .inr j) => .inr (v, j) + | .inr (v, .inl j) => .inl (.inr (v, .inl j)) + | .inr (v, .inr (.inl j)) => .inl (.inr (v, .inr j)) + | .inr (v, .inr (.inr j)) => .inr (v, j) + exact Circuit.project i (by rintro r (⟨v, j|j⟩ | ⟨v, j|j|j⟩) <;> rfl) + +open scoped Classical in +theorem write_net : Circuit F A D₁ (write slot hD hd hc hb) (writeCost m e h l w) := by + have prep : Circuit F A (Tape m e) tape ((A).width + 2 * (Tape m e).width) := by + apply Circuit.project («A»:=A) (D:=Tape m e) (Sum.map (fun p => (p.1, .inl p.2)) id) + rintro r (i|i) <;> rfl + have head : Circuit F (Tape m e) G (graph slot hD hd hc hb) (cost m e w) := + build_net F w (record slot hD hd hc hb) + have body : Circuit F A L (label w) ((A).width + 34 * (L).width) := label_depends.bnet F + exact (((prep.comp head).pair body).comp (join_net F)).mono (by + unfold writeCost + rw [Format.width_pair (graphFmt m e w)] + omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Children +end + +/- # Controlled expansion of a terminal sphere configuration -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Signal +open Coloring Assembly Rounds Surface Surface.Local +open MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout (Alphabet Key Place Sharing item) + +variable {F K N X Z J I : Type} [Field F] [Finite K] + {x y : Wire} {S : Scheme F} {d ℓ M r t q D k n u j z : ℕ} + {T b c g w σ r₀ t₀ : ℕ} {W : ℝ} {P : Input F x y S.h D T (c * b) g W} + {Y : Alphabet P.Occupied} {s : Stage F r₀ t₀ Z P.Occupied P.grid.Seam X} + {Q : Key.Source Y x y s} {left : Order.Exterior Q.left} {right : Order.Exterior Q.right} + {U : Printer F K N S.m d S.h ℓ M r t q D k n u j z} + {a : Atlas P.Occupied P.grid.Seam S.m d S.h} {π : Palette a w q} + {β : P.Occupied ⊕ ℕ → K} {R₀ : Reference J I N P.Occupied P.grid.Seam Z X} + {G : Record F r₀ t₀ P.Occupied P.grid.Seam K N} + {hm : Matches R₀.world β s G} {index : ∀ v, Y.state v ↪ ℕ} {size : P.Occupied → ℕ} + {ext : P.Occupied → Option N → Bool → ℕ} {old : P.V ↪ B S.m} + {data : U.rows.obj} {status : (Children.Header S.m d).obj} + (H : U.Signal Q left right a π β R₀ G hm index size ext old data status) + +open SphereScale (Scales depth) + +variable {tape : S.format.obj} {pres : S.Presentation tape P.diagram} + +open scoped Classical in +/-- All profiles share the same decoder. Their scalar, term and exact +physical presentation are drawn from a single terminal tape. -/ +def release (keeps : Keeps Q left right pres a.coord) (hn : Nonempty P.V) + (bound : P.FinalBounds Q σ j) (sc : Scales g σ D T j b c) + (hr : r₀ = M * r) (ht : t₀ = M * t) (ha : r₀ = c * b) (hb : t₀ = c) + (hM : M = SphereScale.chunks σ D) (hk : k = Sharing.allocation g σ) + (hu : u * D ^ (Input.terminalExponent g σ) ≤ T) + (hc : Input.terminalExponent g σ * D * T ≤ u * U.cap) (hz : depth σ D g j (c * b) < 2 ^ z) : + U.Release pres data status (fun x y => ∑ i, s.value j (Q.init x y i)) σ := by + apply Classical.choice + subst r₀ t₀ + obtain ⟨G₀, B, hl, hr, cap⟩ := H.capacity bound sc ha hb hM hk hu hc hz + have ke : Keeps Q B.rules.left B.rules.right pres a.coord := by rw [hl, hr]; exact keeps + exact ⟨{ + I := Layout.Profile s.scene.cell s.scene.level + finite := Input.FinalBounds.profileType _ _ + select := B.select + coeff := Layout.Profile.sign + term := B.term + value := B.value + bound := fun i => (cap i).1 + populated := fun i => B.populated i hn + valid := B.score + shows := fun i => B.shows i (cap i).2 + retains := fun i => B.retains i (B.frame i (cap i).2) rfl pres ke + reciprocal := by + intro v i hi + simp only [H.graph] at hi ⊢ + exact H.parents.reciprocal v i hi + }⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer.Signal +end + +/- # Ports and price of the weighted printer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Rounds + +variable {F K N : Type} [Field F] [Finite K] {m d h ℓ M r t q D k n u j z : ℕ} + (U : Printer F K N m d h ℓ M r t q D k n u j z) + +open scoped Classical in +/-- Computes the before by the application `U.rows.pair ((Children.Header m d).pair Z)`. -/ +abbrev before (Z : Format) := U.rows.pair ((Children.Header m d).pair Z) +open scoped Classical in +/-- The value specified by `(U.rows.pair U.template.format).pair Z`. -/ +abbrev after (Z : Format) := (U.rows.pair U.template.format).pair Z +open scoped Classical in +/-- The quantity computed by `2 ^ h * (2 ^ ((d + 1) * 1) * (ℓ + U.digits))`. -/ +abbrev volume := 2 ^ h * (2 ^ ((d + 1) * 1) * (ℓ + U.digits)) + +open scoped Classical in +/-- The construction uses `p.fee (m + (d + 1) * 1) U.volume` for its intermediate `a`. -/ +def printCost (p : Contraction.Prices F) (Z : Format) := + let a := p.fee (m + (d + 1) * 1) U.volume + waveCost m d h 1 1 U.volume a U.volume a (.addr ℓ) (.addr U.digits) (.addr U.window.width) + + 4 * Children.writeCost m d h U.window.width U.childBits + + 100 * (U.rows.width + U.selectors.width + (Children.Header m d).width + Z.width + + U.template.format.width) + +open scoped Classical in +/-- The quantity computed by `U.printCost p Z + 4 * U.selectors.width`. -/ +def price (p : Contraction.Prices F) (Z : Format) := U.printCost p Z + 4 * U.selectors.width + +open scoped Classical in +/-- The value specified by `((x.1, U.advance x.1 x.2.1 c), x.2.2)`. -/ +def next {Z : Format} (x : (U.before Z).obj) (c : U.selectors.obj) : (U.after Z).obj := + ((x.1, U.advance x.1 x.2.1 c), x.2.2) + +omit [Finite K] in +open scoped Classical in +theorem arity : Processor.arity U.gate = 2 * U.window.width := by + simp only [Processor.arity, gate, weightTable, Assembly.lookup, wd_word, Format.width_addr, + two_mul] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Checking a selector tape and printing its term with its weight -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Rounds + +variable {F K N : Type} [Field F] [Finite K] {m d h ℓ M r t q D k n u j z : ℕ} + (U : Printer F K N m d h ℓ M r t q D k n u j z) + {Z : Format} (p : Contraction.Prices F) {s : ℕ} {L : Set (Table F)} + (hu : 3 ≤ s) (hw : 2 * U.window.width ≤ s) (hm : m + (d + 1) * 1 ≤ p.w) (hk : U.gate ∈ L) + +open scoped Classical in +private abbrev A (Z : Format) := (U.before Z).pair U.selectors +open scoped Classical in +private abbrev Header := Children.Header m d +open scoped Classical in +private abbrev Wave := Fmt.waveIn m d h (.addr ℓ) (.addr U.digits) +open scoped Classical in +private abbrev Saved (Z : Format) := U.rows.pair Z +open scoped Classical in +private abbrev B₁ (Z : Format) := ((Wave U).pair (Header (m:=m) (d:=d))).pair (Saved U Z) +open scoped Classical in +private abbrev B₂ (Z : Format) := U.template.format.pair (Saved U Z) + +open scoped Classical in +private def divide (x : (A U Z).obj) : (B₁ U Z).obj := (((x.1.1, x.2), x.1.2.1), x.1.1, x.1.2.2) +open scoped Classical in +private def packTerm (x : (B₂ U Z).obj) : (U.after Z).obj := ((x.2.1, x.1), x.2.2) + +omit [Finite K] in +open scoped Classical in +private theorem divide_net : Circuit F (A U Z) (B₁ U Z) (divide U) + ((A U Z).width + 2 * (B₁ U Z).width) := by + let addr : (B₁ U Z).pins → (A U Z).pins + | .inl (.inl (.inl i)) => .inl (.inl i) + | .inl (.inl (.inr i)) => .inr i + | .inl (.inr i) => .inl (.inr (.inl i)) + | .inr (.inl i) => .inl (.inl i) + | .inr (.inr i) => .inl (.inr (.inr i)) + exact Circuit.project addr (by rintro x (((i|i)|i)|(i|i)) <;> rfl) + +open scoped Classical in +private theorem pack_net : Circuit F (B₂ U Z) (U.after Z) (packTerm U) + ((B₂ U Z).width + 2 * (U.after Z).width) := by + let addr : (U.after Z).pins → (B₂ U Z).pins + | .inl (.inl i) => .inr (.inl i) + | .inl (.inr i) => .inl i + | .inr i => .inr (.inr i) + exact Circuit.project addr (by rintro x ((i|i)|i) <;> rfl) + +include hu hw hm hk in +open scoped Classical in +theorem computes {I : Type*} (x : I → (U.before Z).obj) (c : I → U.selectors.obj) + (hr : ∀ i, Fmt.Reciprocal (.vec h (.addr ℓ)) (x i).1) : + Computes F s L ((U.before Z).pair U.selectors) (U.after Z) + (fun i => (x i, c i)) (fun i => U.next (x i) (c i)) (fun i => U.score (x i).1 (c i)) + (U.printCost p Z) := by + let src (i : I) : (A U Z).obj := (x i, c i) + have ha := p.access (L:=L) hu (by omega) hm U.volume + have h₁ : (Format.vec h (Format.pair (.addr ℓ) (.addr U.digits))).width ≤ U.volume := by + simp only [Format.width_vec, Format.width_pair, Format.width_addr] + exact Nat.mul_le_mul_left _ (Nat.le_mul_of_pos_left _ (Nat.two_pow_pos _)) + have h₂ : (Format.vec h (Fmt.view d 1 (.pair (.addr ℓ) (.addr U.digits)))).width ≤ U.volume := by + simp only [Fmt.view, Format.width_vec, Format.width_pair, Format.width_addr] + exact le_rfl + have hf : U.window.width + (Format.addr U.window.width).width ≤ s := by + rw [Format.width_addr, ← two_mul]; exact hw + have wave := computes_wave (D:=.addr U.window.width) hu (by decide : 0 < 1) (by decide : 0 < 1) + ha ha h₁ h₂ (Surface.Local.Design.number U.window) U.tariff hf hk + (fun i => ((x i).1, c i)) hr + have start := Computes.of_map (L:=L) (x:=src) (Map.circuit hu (divide_net U)) (fun _ => rfl) + have hdr := Computes.of_map (L:=L) (x:=fun i => (x i).2.1) + (Map.circuit hu (Circuit.id F (Children.Header m d))) (fun _ => rfl) + have keep := Computes.of_map (L:=L) (x:=fun i => ((x i).1, (x i).2.2)) + (Map.circuit hu (Circuit.id F (Saved U Z))) (fun _ => rfl) + have draw := Map.circuit (L:=L) hu (Children.write_net (m:=m) (h:=h) (l:=U.window.width) + U.slot U.dyadic U.large U.chunks U.degree F) + have print := (wave.par hdr).comp (Computes.of_map draw (fun _ => rfl)) + have together := start.comp (print.par keep) + have net := together.comp (Computes.of_map (Map.circuit hu (pack_net U)) (fun _ => rfl)) + simp only [one_mul, mul_one] at net + refine net.mono ?_ + unfold printCost + simp only [A, B₁, B₂, Wave, Saved, Header, before, after, Fmt.waveIn, rows, selectors, childBits, + Nat.mul_one, Format.width_pair] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- # Summing the terms emitted by a shared printer -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Rounds + +variable {F K N : Type} [Field F] [Finite K] {m d h ℓ M r t q D k n u j z : ℕ} + (U : Printer F K N m d h ℓ M r t q D k n u j z) + {Z : Format} (p : Contraction.Prices F) {s : ℕ} {L : Set (Table F)} + +universe v +variable {x y : Wire} {I J : Type v} + {f : I → Val x → Val y → F} {g : J → Val x → Val y → F} + {X : I → Val x → Val y → (U.before Z).obj} {Y : J → Val x → Val y → (U.after Z).obj} + +open scoped Classical in +theorem transfer (A : Selected ⟨I, f, U.before Z, X⟩ ⟨J, g, U.after Z, Y⟩ U.selectors) + (hu : 3 ≤ s) (hw : 2 * U.window.width ≤ s) (hm : m + (d + 1) * 1 ≤ p.w) (hk : U.gate ∈ L) + (hr : ∀ i a b, Fmt.Reciprocal (.vec h (.addr ℓ)) (X i a b).1) + (hv : ∀ i a b c, U.score (X i a b).1 c = ((A.index i).read c).elim 0 (A.scalar i)) + (he : ∀ i a b c, U.next (X i a b) ((A.index i).write c) = Y (A.next i c) a b) : + Transforms F s L ⟨I, f, U.before Z, X⟩ ⟨J, g, U.after Z, Y⟩ (U.price p Z) := by + let B := I × Val x × Val y × U.selectors.obj + let data : B → (U.before Z).obj := fun i => X i.1 i.2.1 i.2.2.1 + let choice : B → U.selectors.obj := fun i => i.2.2.2 + obtain ⟨k, hk, eval⟩ := U.computes p hu hw hm hk data choice (fun i => hr i.1 i.2.1 i.2.2.1) + refine Transforms.of_selector hu A hk fun i a b c t => ?_ + have eq := eval (i, a, b, c) t + dsimp only [data, choice] at eq + change k (X i a b, c) t = _ + rw [eq, hv] + cases h : (A.index i).read c with + | none => simp + | some j => + rw [(A.index i).valid _ _ |>.mp h] + exact congrArg (fun v => @ite F (v = t) (Classical.propDecidable _) (A.scalar i j) 0) (he i a b + j) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- Separate the cost of addressing hosts from the cost paid in every block. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Rounds Surface.Local + +private theorem spare (a : Rates) : 1 + a.Y + a.Y ≤ a.Y ^ 4 := by + have hh := a.short + calc + _ ≤ a.Y ^ 2 := by nlinarith + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide) + +private theorem write_bound (a : Rates) (d l w : ℕ) + (hd : 2 ^ d ≤ a.Y) (hl : l + w ≤ a.Y) (hw : 2 ^ w ≤ a.Y) + (hg : 2 ^ (Children.degree d w) ≤ a.Y) (hc : 2 ^ (1 + 2 ^ d + 12 * (2 ^ d) ^ 3 + 2 ^ w) ≤ a.Y) : + a.Host 221 (Children.writeCost a.m d a.h l w) ∧ + a.Host 10 (Children.output a.m d a.h l w).width ∧ a.Host 2 (Children.Header a.m d).width := by + have big := a.long + have room := spare a + have hr : a.Host 2 (Children.Header a.m d).width := by + simp only [Children.Header, Format.width_vec, Format.width_pair] + rw [Format.width_bit, mul_one] + exact (Rates.Row.hosts (Rates.big (by omega : 1 + 2 ^ d ≤ a.X))).up (by decide) + have hin : a.Host 6 (Children.input a.m d a.h l).width := by + rw [Format.width_pair] + exact (a.rows d (.addr l) hd (by rw [Format.width_addr]; omega)).plus hr + have ht : a.Host 6 (Children.Tape a.m d).width := by + apply le_trans _ hin + simp only [Children.Tape, Children.input, Format.width_pair, Neighborhood.Rows, + Format.width_vec, Format.width_addr] + gcongr + exact Nat.le_add_right .. + have ht' : a.Host 5 (Children.labels a.m a.h l w).width := by + simp only [Children.labels, Format.width_vec] + rw [Format.width_addr] + exact Rates.Row.fan (Rates.low (by omega : l + w ≤ a.Y ^ 4)) hw + have graph : a.Host 4 (Children.graphFmt a.m d w).width := by + have h := Rates.Row.fan ((Rates.big (a := a) (by omega : 2 ≤ a.X)).plus + ((Rates.big (a := a) (by omega : a.m + w + 2 ≤ a.X)).times hg)) hw + apply le_trans _ h + simp only [Children.graphFmt, History.Reset.Child.Graph, Neighborhood.Rows, Group.Flags, + Format.width_pair, Format.width_vec] + rw [Format.width_bit, Format.width_addr] + exact le_of_eq (by ring) + have hout : a.Host 10 (Children.output a.m d a.h l w).width := by + have h := (graph.plus (ht'.scale 2)).up (by decide : 7 ≤ 10) + apply le_trans _ h + simp only [Children.output, Children.graphFmt, History.Reset.Child.Graph, Children.labels, + Neighborhood.Rows, Format.width_pair, Format.width_vec, Format.width_addr] + exact le_of_eq (by ring) + have hcost : a.Host 220 (Children.cost a.m d w) := + Rates.Row.hosts (Rates.high (Nat.pow_le_pow_left (by omega) _)) + exact ⟨hcost.plus (((((hin.plus hout).plus ht').plus ht).plus graph).scale 100), hout, hr⟩ + +variable {F K N : Type} [Field F] [Finite K] {m d h ℓ M r t q D k n u j z : ℕ} + (U : Printer F K N m d h ℓ M r t q D k n u j z) + +/-- The untouched register has an additive charge independent of both width budgets. -/ +theorem work_bound (p : Contraction.Prices F) (Z : Format) (X Y : ℕ) + (hl : 1000 + 10 * m + 10 * Y ≤ X) (hw : 1 + p.w ^ p.power ≤ X) + (hY : 10000 + 1 + p.W + U.window.width + U.labelBits + 2 ^ (d + 1) + 2 ^ U.childBits + + 2 ^ U.template.scheme.d + 2 ^ (1 + 2 ^ d + 12 * (2 ^ d) ^ 3 + 2 ^ U.childBits) ≤ Y) : + U.price p Z ≤ 2 ^ m * X ^ 225 + 2 ^ (m + h) * Y ^ 225 + 100 * Z.width := by + obtain ⟨hy, hW, hv, hL, hd, hc, hg, he⟩ : + 10000 ≤ Y ∧ 1 + p.W ≤ Y ∧ U.window.width ≤ Y ∧ U.labelBits ≤ Y ∧ + 2 ^ (d + 1) ≤ Y ∧ 2 ^ U.childBits ≤ Y ∧ 2 ^ U.template.scheme.d ≤ Y ∧ + 2 ^ (1 + 2 ^ d + 12 * (2 ^ d) ^ 3 + 2 ^ U.childBits) ≤ Y := by + generalize 2 ^ (1 + 2 ^ d + 12 * (2 ^ d) ^ 3 + 2 ^ U.childBits) = b at hY ⊢ + generalize 2 ^ U.template.scheme.d = g, + 2 ^ U.childBits = c, 2 ^ (d + 1) = e at hY ⊢ + omega + let a : Rates := ⟨m, h, X, Y, hy, hl⟩ + have room : 1 + Y + Y ≤ Y ^ 4 := spare a + have hd' : 2 ^ d ≤ Y := (Nat.pow_le_pow_right (by decide) (Nat.le_succ d)).trans hd + have hn : 2 ^ ((d + 1) * 1) ≤ Y := by simpa using hd + have hh : 2 ^ ((d + 1) * 1) * (ℓ + U.digits) ≤ Y := by + rw [window_width] at hv + exact (Nat.le_mul_of_pos_left _ (by positivity)).trans hv + have hh' : ℓ + U.digits ≤ Y := (Nat.le_mul_of_pos_left _ (by positivity)).trans hh + have vol : a.Row 4 U.volume := Rates.low (show 2 ^ ((d + 1) * 1) * (ℓ + U.digits) + ≤ Y ^ 4 by omega) + have fee := a.fee p _ _ hn hW hw vol + have wave := a.wave d 1 1 _ _ _ _ (.addr ℓ) (.addr U.digits) (.addr U.window.width) + hd' hn hn vol fee vol fee (by + rw [Format.width_addr] + change 1 + U.window.width + U.window.width ≤ Y ^ 4 + omega) + obtain ⟨write, out, header⟩ := write_bound a d U.window.width U.childBits hd' hL hc hg he + have rows := a.rows d (.addr ℓ) hd' (by rw [Format.width_addr]; change ℓ ≤ Y ^ 4; omega) + have sel : a.Host 4 U.selectors.width := by + rw [selectors, Format.width_vec, Format.width_vec, Format.width_addr] + exact Rates.Row.hosts (Rates.low (show U.digits ≤ Y ^ 4 by omega)) + have parts := (((rows.plus sel).plus header).plus out).scale 100 + have total := ((wave.plus (write.scale 4)).plus parts).plus (sel.scale 4) + rw [pow_add] + refine le_trans ?_ (Nat.add_le_add_right total (100 * Z.width)) + simp only [price, printCost] + change _ ≤ _ + 4 * Children.writeCost m d h U.window.width U.childBits + + 100 * (U.rows.width + U.selectors.width + (Children.Header m d).width + + U.template.format.width) + + 4 * U.selectors.width + 100 * Z.width + dsimp only [a] + exact le_of_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Private/Install.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Private/Install.lean new file mode 100644 index 0000000000..48280c205f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Private/Install.lean @@ -0,0 +1,955 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Plant.Decoded +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam +public import Mathlib.Data.Fin.Tuple.Basic +public import Mathlib.Algebra.Order.Chebyshev +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Fields +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.MovingForms +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectrum.Comparison +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Print.Seating +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.WireRecovery +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics + +/-! # Splitting a homogeneous state into consecutive groups of species -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Chunk + +open Finset Plant +variable {M d e : ℕ} + +/-- The subtype of `b : Fin M → Fin (e + 1)` satisfying `∑ i, (b i).val = e`. -/ +abbrev Shape (M e : ℕ) := {b : Fin M → Fin (e + 1) // ∑ i, (b i).val = e} + +/-- The condition `∀ i, Level d (b.val i).val` on the specified data. -/ +abbrev Cells (d : ℕ) (b : Shape M e) := ∀ i, Level d (b.val i).val + +/-- The indexed operation `pack (fun i => slice (u (finProdFinEquiv.symm i).1) +(finProdFinEquiv.symm i).2)`. -/ +def join (u : Fin M → Wedge d) : Wedge (M * d) := + pack (fun i => slice (u (finProdFinEquiv.symm i).1) (finProdFinEquiv.symm i).2) + +/-- The indexed operation `pack (fun j => slice u (finProdFinEquiv (i, j)))`. -/ +def split (u : Wedge (M * d)) (i : Fin M) : Wedge d := + pack (fun j => slice u (finProdFinEquiv (i, j))) + +@[simp] theorem split_join (u : Fin M → Wedge d) (i : Fin M) : split (join u) i = u i := by + simp only [split, join, slice_pack, Equiv.symm_apply_apply, pack_slice] + +@[simp] theorem join_split (u : Wedge (M * d)) : join (split u) = u := by + simp only [join, split, slice_pack, Prod.mk.eta, Equiv.apply_symm_apply, pack_slice] + +theorem energy_join (u : Fin M → Wedge d) : energy (join u).val = ∑ i, energy (u i).val := by + rw [join, energy_pack, ← finProdFinEquiv.sum_comp, Fintype.sum_prod_type] + simp only [Equiv.symm_apply_apply, ← energy_pack, pack_slice] + +/-- The indexed operation `⟨join (fun i => (v.2 i).val), by rw [energy_join] exact (sum_congr +rfl fun i _ => (v.2 i).property).trans v.1.property⟩`. -/ +def put (v : Σ b : Shape M e, Cells d b) : Level (M * d) e := + ⟨join (fun i => (v.2 i).val), by + rw [energy_join] + exact (sum_congr rfl fun i _ => (v.2 i).property).trans v.1.property⟩ + +/-- Reindexes `(Σ b : Shape M e, Cells d b)` and `Level (M * d) e` by an equivalence. -/ +def states (M d e : ℕ) : (Σ b : Shape M e, Cells d b) ≃ Level (M * d) e := by + refine Equiv.ofBijective put ⟨?_, ?_⟩ + · rintro ⟨b, x⟩ ⟨c, y⟩ h + have he (i) : (x i).val = (y i).val := by + simpa only [put, split_join] using congrArg (fun u => split u.val i) h + have : b = c := Subtype.ext (funext fun i => Fin.ext <| + (x i).property.symm.trans ((congrArg (fun t => energy t.val) (he i)).trans (y i).property)) + subst c + rw [show x = y from funext fun i => Subtype.ext (he i)] + · intro u + have he : ∑ i, energy (split u.val i).val = e := by rw [← energy_join, join_split, u.property] + let b : Shape M e := ⟨fun i => ⟨energy (split u.val i).val, Nat.lt_succ_of_le (by + exact (single_le_sum (fun i _ => Nat.zero_le (energy (split u.val i).val)) (mem_univ + i)).trans_eq he)⟩, he⟩ + exact ⟨⟨b, fun i => ⟨split u.val i, rfl⟩⟩, Subtype.ext (join_split _)⟩ + +theorem states_val (b : Shape M e) (x : Cells d b) : + (states M d e ⟨b, x⟩).val = join (fun i => (x i).val) := rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Chunk +end + +section +/- # Splitting a sphere into smaller spheres at prescribed chunk energies -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Chunk + +open Finset Plant +variable {A F : Type*} [Field F] {M d : ℕ} + +private theorem expand (z : A → F) (xs : A → Wedge d) (l : List A) : + wick fieldKernel (bundle z xs l) = + (-1 : F) ^ shuffle (fun i j => energy (slice (xs i) j).val) (List.finRange d) l * + ∏ j, wick fieldKernel (bundle z (fun i => slice (xs i) j) l) := by + have h := wick_species z (fun i j => slice (xs i) j) (fun i j => energy (slice (xs i) j).val) + (fun i j => (energy_mod_two _).symm) l + simp only [pack_slice] at h + exact h + +private theorem energy_slices (x : Wedge d) : ∑ j, energy (slice x j).val = energy x.val := by + rw [← energy_pack, pack_slice] + +/-- The sign is determined by the outer index of chunk energies. -/ +theorem wick_chunks (z : A → F) (e : A → ℕ) (b : ∀ i, Shape M (e i)) + (u : ∀ i, Cells d (b i)) (l : List A) : + wick fieldKernel (bundle z (fun i => (states M d (e i) ⟨b i, u i⟩).val) l) = + (-1 : F) ^ shuffle (fun i j => ((b i).val j).val) (List.finRange M) l * + ∏ j, wick fieldKernel (bundle z (fun i => (u i j).val) l) := by + let xs (i : A) := join (fun j => (u i j).val) + have he (i j k) : slice (xs i) (finProdFinEquiv (j, k)) = slice (u i j).val k := by + simp only [xs, join, slice_pack, Equiv.symm_apply_apply] + exact congrArg (fun j => slice (u i j).val k) (congrArg Prod.fst + (finProdFinEquiv.symm_apply_apply (j, k))) + simp only [states_val] + change wick fieldKernel (bundle z xs l) = _ + rw [expand, shuffle_blocks, ← finProdFinEquiv.prod_comp, Fintype.prod_prod_type] + simp only [he, energy_slices, show ∀ i j, energy (u i j).val.val = ((b i).val j).val + from fun i j => (u i j).property, pow_add, ← prod_pow_eq_pow_sum, mul_assoc, ← prod_mul_distrib] + congr 1 + exact prod_congr rfl fun j _ => (expand z (fun i => (u i j).val) l).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Chunk +end + +/- # Binary widths of a homogeneous leg and its chunks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Chunk + +open Finset Real + +/-- The quantity computed by `⌈4 * sqrt ((d : ℝ) * e)⌉₊`. -/ +def width (d e : ℕ) := ⌈4 * sqrt ((d : ℝ) * e)⌉₊ + +theorem width_le (d e : ℕ) : (width d e : ℝ) ≤ 4 * sqrt ((d : ℝ) * e) + 1 := + (Nat.ceil_lt_add_one (by positivity)).le + +theorem card_le (d e : ℕ) : Fintype.card (Level d e) ≤ 2 ^ width d e := by + have hlog : (1 / 2 : ℝ) ≤ log 2 := by + have h := log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2⁻¹) + rw [log_inv] at h + linarith + have hcost : 2 * sqrt ((d : ℝ) * e) ≤ width d e * log 2 := by + have h := mul_le_mul (Nat.le_ceil (4 * sqrt ((d : ℝ) * e))) hlog (by norm_num) (by positivity) + unfold width + linarith + have h := (card_level d e).trans (exp_le_exp.mpr hcost) + rw [exp_nat_mul, exp_log (by norm_num)] at h + exact_mod_cast h + +theorem total_width {M e : ℕ} (d : ℕ) (b : Shape M e) : + (∑ i, (width d (b.val i).val : ℝ)) ≤ 4 * sqrt ((M : ℝ) * d * e) + M := by + let f i := sqrt ((d : ℝ) * (b.val i).val) + have hs : ∑ i, f i ≤ sqrt ((M : ℝ) * d * e) := by + apply (le_sqrt (by unfold f; positivity) (by positivity)).mpr + refine sq_sum_le_card_mul_sum_sq.trans_eq ?_ + have h (i) : f i ^ 2 = (d : ℝ) * (b.val i).val := sq_sqrt (by positivity) + rw [card_univ, Fintype.card_fin] + simp only [h, ← mul_sum, ← Nat.cast_sum, b.2, mul_assoc] + calc + _ ≤ ∑ i, (4 * f i + 1) := sum_le_sum fun i _ => width_le d _ + _ = 4 * (∑ i, f i) + M := by simp [sum_add_distrib, mul_sum] + _ ≤ _ := by linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Chunk +end + +/- +# Private spheres as universal tensors + +Give each leg twice the target width. A spectral point can transmit +the target from the same auxiliary position used in the sphere lower +bound. The cost of transmitting a binary common label shows that the +extra width supplies a strict margin, uniform in the spectral point. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Sphere Spectral Finset Filter + +variable {F K A : Type} [Field F] [Field K] [Algebra F K] + [Fintype A] [DecidableEq A] [Nonempty A] + +theorem map_kernel {r : ℕ} (x y : Site F r) : + algebraMap F K (fieldKernel x y) = + fieldKernel (algebraMap F K x.1, x.2) (algebraMap F K y.1, y.2) := by + simp [fieldKernel, Sphere.coeff, apply_ite (algebraMap F K)] + +omit [DecidableEq A] in +theorem map_sphere (z : A → F) (e : A → ℕ) : + Tensor.map (algebraMap F K) (sphereTensor z e) = + sphereTensor (algebraMap F K ∘ z) e := by + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_ + erw [Raw.coeff_map, Raw.coeff_ofTable, Raw.coeff_ofTable] + change algebraMap F K (sphereForm z e x) = sphereForm (algebraMap F K ∘ z) e x + change States 1 e at x + unfold sphereForm + rw [wick_hom] + simp only [map_kernel, Function.comp_apply] + +/-- The largest doubled energy of a leg at the given width cap. -/ +def cap (t : ℝ) : ℕ := ⌊(t / entropy) ^ 2⌋₊ + +theorem cap_iff {t : ℝ} (ht : 0 ≤ t) (e : ℕ) : e ≤ cap t ↔ width e ≤ t := by + unfold cap width + rw [Nat.le_floor_iff (sq_nonneg _), mul_comm, ← le_div_iff₀ entropy_pos, + Real.sqrt_le_iff, and_iff_right (div_nonneg ht entropy_pos.le)] + +/-- The quantity computed by `(i : A) → Fin (cap (a i) + 1)`. -/ +abbrev Bounds (a : A → ℝ) := (i : A) → Fin (cap (a i) + 1) + +/-- The direct sum over the allowed energy profiles. -/ +def universalSphere (z : A → F) (a : A → ℝ) : Tensor F A := + ∑ e : Bounds a, sphereTensor z (fun i => (e i).val) + +private theorem universal_contains (z : A → F) (a : A → ℝ) (e : A → ℕ) + (h : ∀ i, e i ≤ cap (a i)) : sphereTensor z e ≤ universalSphere z a := by + classical + let j : Bounds a := fun i => ⟨e i, Nat.lt_succ_of_le (h i)⟩ + unfold universalSphere + rw [← sum_erase_add _ _ (mem_univ j)] + have he := Tensor.add_le_add_right 0 + (∑ t ∈ univ.erase j, sphereTensor z (fun i => (t i).val)) (sphereTensor z e) (Tensor.zero_le _) + rwa [zero_add] at he + +private theorem universal_nonzero (z : A → F) (a : A → ℝ) : universalSphere z a ≠ 0 := by + intro hz + have he := universal_contains z a (fun _ => 0) (fun _ => Nat.zero_le _) + rw [hz] at he + have hv := le_antisymm he (Tensor.zero_le _) + apply sphereForm_vacuum z + funext x + exact (Raw.coeff_ofTable _ _ x).symm.trans ((Tensor.ofRaw_eq_zero _).mp hv x) + +theorem of_prices (z : A → F) (n : ℕ) (hn : 0 < n) (a : A → ℝ) (ε : ℝ) + (hε : 0 < ε) (ha : ∀ i, 2 * ε ≤ a i) + (price : ∀ f : Tensor K A →+* ℝ, Monotone f → + ∃ g : Tensor K (A ⊕ Unit) →+* ℝ, Monotone g ∧ (∀ T, g (Tensor.pad Unit T) = f T) ∧ + ∃ e : A → ℕ, (∀ i, width (e i) ≤ n * (2 * a i)) ∧ + n * ((∑ i, 2 * a i * Tensor.dist g (.inl i) (.inr ())) - ε) ≤ + Real.log (f (sphereTensor (algebraMap F K ∘ z) e))) + (U : Raw F A) (hU : ∀ i, Real.log (Fintype.card (U.leg i)) ≤ n * a i) : + ∃ C : ℕ, ∀ d : ℕ, (Tensor.ofRaw U) ^ d ≤ + (C : Tensor F A) * (universalSphere z (fun i => n * (2 * a i))) ^ d := by + classical + let V := universalSphere z (fun i => n * (2 * a i)) + have hv : V ≠ 0 := universal_nonzero _ _ + apply Spectrum.strictComparison Tensor.add_le_add_right Tensor.mul_le_mul_left + Tensor.zero_le Tensor.one_le Tensor.exists_bound hv + intro f hf + let p := NNReal.toRealHom.comp f + have hp : Monotone p := fun _ _ h => hf h + change p (Tensor.ofRaw U) < p V + have hv' : 0 < p V := zero_lt_one.trans_le (Tensor.value_one_le hp hv) + by_cases hz : Tensor.ofRaw U = 0 + · simpa [hz] using hv' + have hu' : 0 < p (Tensor.ofRaw U) := zero_lt_one.trans_le (Tensor.value_one_le hp hz) + obtain ⟨p', hp', he⟩ := Tensor.extend_field_real (L := K) p hp + obtain ⟨g, hg, he', e, hw, hl⟩ := price p' hp' + let v i := Tensor.dist g (.inl i) (.inr ()) + have hb (i) : 0 ≤ v i := Tensor.dist_nonneg g hg _ _ + let E := ∑ i, a i * v i + have energy_low : 2 * ε ≤ E := calc + _ ≤ 2 * ε * ∑ i, v i := + le_mul_of_one_le_right (by positivity) (Tensor.preparation_lower hg he') + _ = ∑ i, 2 * ε * v i := mul_sum _ _ _ + _ ≤ E := sum_le_sum fun i _ => mul_le_mul_of_nonneg_right (ha i) (hb i) + have hprep := Tensor.preparation hg (U.map (algebraMap F K)) + rw [he', ← Tensor.map_ofRaw, he] at hprep + have upper : Real.log (p (Tensor.ofRaw U)) ≤ n * E := hprep.trans (by + unfold E + rw [mul_sum] + refine sum_le_sum fun i _ => ?_ + change v i * Real.log (Fintype.card (U.leg i)) ≤ _ + calc + _ ≤ v i * (n * a i) := mul_le_mul_of_nonneg_left (hU i) (hb i) + _ = _ := by ring) + have hmul : (∑ i, 2 * a i * v i) = 2 * E := by simp only [E, mul_sum, mul_assoc] + change (n : ℝ) * ((∑ i, 2 * a i * v i) - ε) ≤ _ at hl + rw [hmul, ← map_sphere, he] at hl + have hgap : (n : ℝ) * E < Real.log (p (sphereTensor z e)) := + (mul_lt_mul_of_pos_left (by linarith) (Nat.cast_pos.mpr hn)).trans_le hl + have hcap : sphereTensor z e ≤ V := universal_contains _ _ e fun i => + (cap_iff ((width_nonneg (e i)).trans (hw i)) _).mpr (hw i) + have hpos : 0 < p (sphereTensor z e) := by + by_cases h : sphereTensor z e = 0 + · simp only [h, map_zero, Real.log_zero] at hgap + exact (not_lt_of_ge (mul_nonneg (Nat.cast_nonneg n) (by linarith)) hgap).elim + · exact zero_lt_one.trans_le (Tensor.value_one_le hp h) + exact (Real.log_lt_log_iff hu' hv').mp + ((upper.trans_lt hgap).trans_le (Real.log_le_log hpos (hp hcap))) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end + +/- # Local matrices implementing a private state on each chosen profile -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Finset Spectral Sphere + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + +/-- Indexes the selector by the coordinates of `Fin C × (Fin d → Bounds widths)`. -/ +abbrev Selector (widths : A → ℝ) (C d : ℕ) := Fin C × (Fin d → Bounds widths) + +/-- The condition `∀ j, Level 1 (v.2 j i).val` on the specified data. -/ +abbrev leg {widths : A → ℝ} {C d : ℕ} (v : Selector widths C d) (i : A) := + ∀ j, Level 1 (v.2 j i).val + +/-- The product of `sphereForm z (fun i => (v.2 j i).val) (fun i => x i j)` indexed by `j`. -/ +def sources (z : A → F) {widths : A → ℝ} {C d : ℕ} (v : Selector widths C d) + (x : ∀ i, leg v i) : F := + ∏ j, sphereForm z (fun i => (v.2 j i).val) (fun i => x i j) + +private theorem expand_source (z : A → F) (widths : A → ℝ) (C d : ℕ) : + (C : Tensor F A) * universalSphere z widths ^ d = + ∑ v : Selector widths C d, Tensor.ofRaw (Raw.ofTable (leg v) (sources z v)) := by + classical + let T (e : Bounds widths) := sphereTensor z (fun i => (e i).val) + have hd : universalSphere z widths ^ d = ∑ w : Fin d → Bounds widths, ∏ j, T (w j) := by + rw [← Fintype.prod_sum (fun (_ : Fin d) (w : Bounds widths) => T w)] + simp [T, universalSphere] + rw [hd, Fintype.sum_prod_type] + have he (i : Fin C) (v : Fin d → Bounds widths) : + Tensor.ofRaw (Raw.ofTable (leg (i, v)) (sources z (i, v))) = ∏ j, T (v j) := + (Tensor.product_tables (fun j a => Level 1 (v j a).val) + (fun j => sphereForm z (fun a => (v j a).val))).symm + simp only [he, sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul] + +/-- The common selector is internal. Once it is fixed, each map can +read only the state at its own site across the selected blocks. -/ +theorem local_matrices (z : A → F) (widths : A → ℝ) (C d : ℕ) + (X : A → Type) [∀ i, Fintype (X i)] (J : (∀ i, X i) → F) + (h : (Tensor.ofRaw (Raw.ofTable X J)) ^ d ≤ (C : Tensor F A) * universalSphere z widths ^ d) : + ∃ L : (v : Selector widths C d) → (i : A) → (Fin d → X i) → leg v i → F, + ∀ x : (i : A) → Fin d → X i, (∏ j, J (fun i => x i j)) = + ∑ v, ∑ y : ∀ i, leg v i, (∏ i, L v i (x i) (y i)) * sources z v y := by + classical + have target := Tensor.product_tables (fun _ : Fin d => X) (fun _ => J) + simp only [prod_const, card_univ, Fintype.card_fin] at target + rw [target, expand_source] at h + obtain ⟨L, hL⟩ := (Raw.restriction_sum_iff _ _ _).mp h + refine ⟨L, fun x => ?_⟩ + have e := hL x + erw [Raw.coeff_ofTable] at e + rw [e] + refine sum_congr rfl fun v _ => ?_ + unfold Raw.applyLocal + rw [Raw.expand] + refine sum_congr rfl fun y _ => ?_ + erw [Raw.coeff_ofTable] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end + +/- # Uniform comparison with the direct sum of bounded sphere levels -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Sphere Spectral Filter + +variable {F K A : Type} [Field F] [Field K] [Algebra F K] [Infinite K] + [Fintype A] [DecidableEq A] [Nonempty A] + +/-- Under shared-parameter pricing over an infinite extension, all the +restrictions are over the original field. Their multiplicative overhead +can depend on the target, but not on the tensor power. -/ +theorem universal (sync : Prices.SharedPrice K) (z : A → F) (hz : Function.Injective z) + (a : A → ℝ) (ha : ∀ i, 0 < a i) : + ∀ᶠ n : ℕ in atTop, ∀ U : Raw F A, (∀ i, Real.log (Fintype.card (U.leg i)) ≤ n * a i) → + ∃ C : ℕ, ∀ d : ℕ, (Tensor.ofRaw U) ^ d ≤ + (C : Tensor F A) * (universalSphere z (fun i => n * (2 * a i))) ^ d := by + classical + obtain ⟨i, _, hi⟩ := Finset.univ.exists_min_image a Finset.univ_nonempty + have he := (bounded_forms K).weighted sync + have hz' : Function.Injective (algebraMap F K ∘ z) := (algebraMap F K).injective.comp hz + have hw := prescribed_widths he (wireProbe K) _ hz' (fun j => 2 * a j) + (fun j => mul_pos (by norm_num) (ha j)) (half_pos (ha i)) + filter_upwards [hw, eventually_gt_atTop 0] with n hn hpos + exact of_prices z n hpos a _ (half_pos (ha i)) + (fun j => by linarith [hi j (Finset.mem_univ j)]) hn + +/-- The same width at every mark suffices for a block of binary rows. -/ +theorem binary_matrices (sync : Prices.SharedPrice K) (z : A → F) (hz : Function.Injective z) : + ∀ᶠ b : ℕ in atTop, ∀ J : (A → Fin b → Bool) → F, + ∃ C : ℕ, ∀ d : ℕ, ∃ L : (v : Selector (fun _ : A => 2 * (b : ℝ)) C d) → + (i : A) → (Fin d → Fin b → Bool) → leg v i → F, + ∀ x : A → Fin d → Fin b → Bool, (∏ j, J (fun i => x i j)) = + ∑ v, ∑ y : ∀ i, leg v i, (∏ i, L v i (x i) (y i)) * sources z v y := by + filter_upwards [universal sync z hz (fun _ => 1) (by simp)] with b h + intro J + obtain ⟨C, hC⟩ := h (Raw.ofTable (fun _ => Fin b → Bool) J) (by + intro i + change Real.log (Fintype.card (Fin b → Bool)) ≤ (b : ℝ) * 1 + rw [Fintype.card_fun, Fintype.card_bool, Fintype.card_fin, Nat.cast_pow, Real.log_pow] + have hl : Real.log 2 ≤ 1 := by linarith [Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2)] + exact mul_le_mul_of_nonneg_left hl (Nat.cast_nonneg _)) + refine ⟨C, fun d => local_matrices z _ C d _ J ?_⟩ + simpa only [mul_one, mul_comm (b : ℝ)] using hC d + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end + +/- # A private sphere on the packed species -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Finset Sphere Plant +variable {A F : Type} [Fintype A] [DecidableEq A] [Field F] + +open scoped Classical in +/-- Push independent finite sums forward along site maps. Different +preimages of one local label contribute additively. -/ +theorem local_push {X Y : A → Type} [∀ i, Fintype (X i)] [∀ i, Fintype (Y i)] [∀ i, + DecidableEq (Y i)] + (f : ∀ i, X i → Y i) (w : ∀ i, X i → F) (T : (∀ i, Y i) → F) : + (∑ y : ∀ i, Y i, (∏ i, ∑ x, if f i x = y i then w i x else 0) * T y) = + ∑ x : ∀ i, X i, (∏ i, w i (x i)) * T (fun i => f i (x i)) := by + simp_rw [Fintype.prod_sum, sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro x _ + rw [Fintype.sum_eq_single (fun i => f i (x i))] + · simp + · intro y hy + obtain ⟨i, hi⟩ := Function.ne_iff.mp hy + rw [prod_eq_zero (mem_univ i) (ite_eq_right (Ne.symm hi)), zero_mul] + +variable {a : A → ℝ} {C d : ℕ} + +open scoped Classical in +/-- The sum of `(v.2 j i).val` indexed by `j`. -/ +def profile (v : Selector a C d) (i : A) : ℕ := ∑ j, (v.2 j i).val + +open scoped Classical in +/-- Uses `⟨pack (fun j => (x j).val), by rw [energy_pack]; exact sum_congr rfl (fun j _ => (x +j).2)⟩` as the representation. -/ +def packed (v : Selector a C d) (i : A) (x : leg v i) : Level d (profile v i) := + ⟨pack (fun j => (x j).val), by rw [energy_pack]; exact sum_congr rfl (fun j _ => (x j).2)⟩ + +open scoped Classical in +/-- The indexed operation `wick fieldKernel (bundle z (fun i => (x i).val) univ.toList)`. -/ +def value {r : ℕ} (z : A → F) {e : A → ℕ} (x : States r e) : F := + wick fieldKernel (bundle z (fun i => (x i).val) univ.toList) + +omit [DecidableEq A] in +open scoped Classical in +private theorem one_species (z : A → F) (e : A → ℕ) (x : States 1 e) : + value z x = sphereForm z e x := by + unfold sphereForm + rw [← wick_map fieldKernel (fun i : A × Mode 1 => (z i.1, i.2))] + simp [value, bundle, Sphere.inputs, Sphere.marksAt, List.map_flatMap, Function.comp_def] + +open scoped Classical in +/-- The indexed operation `shuffle (fun i j => (v.2 j i).val) (List.finRange d) univ.toList`. -/ +def parity (v : Selector a C d) : ℕ := + shuffle (fun i j => (v.2 j i).val) (List.finRange d) univ.toList + +omit [DecidableEq A] in +open scoped Classical in +theorem packed_value (z : A → F) (v : Selector a C d) (x : ∀ i, leg v i) : + sources z v x = (-1 : F) ^ parity v * value z (fun i => packed v i (x i)) := by + have hp (i j) : (x i j).val.val.length % 2 = (v.2 j i).val % 2 := + (energy_mod_two _).symm.trans (congrArg (· % 2) (x i j).2) + have h := wick_species z (fun i j => (x i j).val) (fun i j => (v.2 j i).val) hp univ.toList + change value z (fun i => packed v i (x i)) = (-1 : F) ^ parity v * + ∏ j, value z (fun i => x i j) at h + rw [h, ← mul_assoc, ← mul_pow] + simp only [neg_mul_neg, one_mul, one_pow, sources, one_species] + +open scoped Classical in +/-- Pack the product of selected one-species spaces into prescribed +levels of a single private sphere. The order sign is fixed by the selector. -/ +theorem local_packed (z : A → F) (v : Selector a C d) (L : ∀ i, leg v i → F) : + (∑ y : ∀ i, leg v i, (∏ i, L i (y i)) * sources z v y) = + (-1 : F) ^ parity v * ∑ y : States d (profile v), + (∏ i, ∑ x, if packed v i x = y i then L i x else 0) * value z y := by + refine Eq.trans ?_ (congrArg ((-1 : F) ^ parity v * ·) (local_push (packed v) L (value z)).symm) + rw [mul_sum] + apply sum_congr rfl + intro y _ + rw [packed_value, mul_left_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end + +/- +# Realizing the signed joint state + +The signature exchanging blocks depends only on their occupancy counts +at each mark. Include these counts in the common selector and check +them locally. The signature within a block is part of its input table. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Finset Sphere Plant Filter +variable {F K A : Type} [Field F] [Fintype A] [DecidableEq A] {n d b C : ℕ} + +open scoped Classical in +/-- The coefficient across all species after ordering by marks. -/ +def signed (rows : List A) (J : (A → Bool) → F) (x : A → Fin n → Bool) := + (-1 : F) ^ shuffle (fun i j => (x i j).toNat) (List.finRange n) rows * + ∏ j, J (fun i => x i j) + +open scoped Classical in +/-- The value specified by `x (finProdFinEquiv (j, k))`. -/ +def blocks (x : Fin (d * b) → Bool) (j : Fin d) (k : Fin b) := x (finProdFinEquiv (j, k)) + +open scoped Classical in +/-- The counts of type `Fin (b + 1)` for the given inputs. -/ +def counts (x : Fin (d * b) → Bool) (j : Fin d) : Fin (b + 1) := + ⟨∑ k, (blocks x j k).toNat, Nat.lt_succ_of_le (calc + _ ≤ ∑ _ : Fin b, 1 := sum_le_sum fun k _ => by cases blocks x j k <;> decide + _ = b := by simp)⟩ + +open scoped Classical in +theorem sum_counts (x : Fin (d * b) → Bool) : + ∑ j, (counts x j).val = energy (occupancy x).val := by + rw [energy_occupancy, ← finProdFinEquiv.sum_comp, Fintype.sum_prod_type] + rfl + +open scoped Classical in +/-- The quantity computed by `A → Fin d → Fin (b + 1)`. -/ +abbrev Counts (A : Type) (b d : ℕ) := A → Fin d → Fin (b + 1) + +open scoped Classical in +/-- The indexed operation `shuffle (fun i j => (m i j).val) (List.finRange d) rows`. -/ +def inter (rows : List A) (m : Counts A b d) := + shuffle (fun i j => (m i j).val) (List.finRange d) rows + +omit [Fintype A] [DecidableEq A] in +open scoped Classical in +theorem signed_blocks (rows : List A) (J : (A → Bool) → F) (x : A → Fin (d * b) → Bool) : + signed rows J x = (-1 : F) ^ inter rows (fun i => counts (x i)) * + ∏ j, signed rows J (fun i => blocks (x i) j) := by + rw [signed, shuffle_blocks, pow_add, ← finProdFinEquiv.prod_comp, Fintype.prod_prod_type] + simp only [signed, prod_mul_distrib, prod_pow_eq_pow_sum, mul_assoc, inter, counts, blocks] + +open scoped Classical in +/-- Indexes the selection by the coordinates of `Counts A b d × Selector (fun _ : A => 2 * (b : +ℝ)) C d`. -/ +abbrev Selection (A : Type) (b C d : ℕ) := + Counts A b d × Selector (fun _ : A => 2 * (b : ℝ)) C d + +open scoped Classical in +/-- The sum of `(v.1 i j).val` indexed by `j`. -/ +def energyA (v : Selection A b C d) (i : A) := ∑ j, (v.1 i j).val + +open scoped Classical in +/-- Computes the energy b by the application `profile v.2`. -/ +abbrev energyB (v : Selection A b C d) := profile v.2 + +open scoped Classical in +/-- The quantity computed by `inter rows v.1 + parity v.2`. -/ +def sign (rows : List A) (v : Selection A b C d) := inter rows v.1 + parity v.2 + +open scoped Classical in +/-- The only coupling between distinct marks, beyond the private sphere +itself, is the common selection. Both energies are known from it. -/ +theorem private_joint [Field K] [Infinite K] [Algebra F K] [Nonempty A] + (sync : Prices.SharedPrice K) (z : A → F) (hz : Function.Injective z) : + ∀ᶠ b : ℕ in atTop, ∀ (rows : List A) (J : (A → Bool) → F), + ∃ C : ℕ, ∀ d : ℕ, + ∃ L : (v : Selection A b C d) → (i : A) → (Fin (d * b) → Bool) → Level d (energyB v i) → F, + (∀ v i x y, L v i x y ≠ 0 → energy (occupancy x).val = energyA v i) ∧ + ∀ x : A → Fin (d * b) → Bool, signed rows J x = + ∑ v, (-1 : F) ^ sign rows v * + ∑ y : States d (energyB v), (∏ i, L v i (x i) (y i)) * value z y := by + filter_upwards [binary_matrices sync z hz] with b hb + intro rows J + obtain ⟨C, hC⟩ := hb (signed rows J) + refine ⟨C, fun d => ?_⟩ + obtain ⟨L, hL⟩ := hC d + let W (v : Selection A b C d) (i : A) (x : Fin (d * b) → Bool) (y : Level d (energyB v i)) : F := + if v.1 i = counts x then ∑ k, if packed v.2 i k = y then L v.2 i (blocks x) k else 0 else 0 + refine ⟨W, ?_, ?_⟩ + · intro v i x y h + have e : v.1 i = counts x := by by_contra! h'; simp [W, h'] at h + rw [energyA, e, sum_counts] + intro x + let m i := counts (x i) + rw [signed_blocks, hL, mul_sum, Fintype.sum_prod_type (α₁ := Counts A b d), + Fintype.sum_eq_single m] + · refine sum_congr rfl fun v _ => ?_ + rw [local_packed z v (fun i => L v i (blocks (x i)))] + simp only [sign, m, W, ↓reduceIte, pow_add, mul_assoc] + · intro k hk + obtain ⟨i, hi⟩ := Function.ne_iff.mp hk + apply sum_eq_zero + intro v _ + apply mul_eq_zero_of_right + apply sum_eq_zero + intro y _ + rw [prod_eq_zero (mem_univ i) ?_, zero_mul] + have hi' : k i ≠ counts (x i) := hi + simp [W, hi'] + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end + +/- # Energy and selector costs of the private sphere -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Finset Sphere Filter +variable {A : Type} {b C d : ℕ} + +/-- Absolute constant for the private energy bound. -/ +def energyConstant := ⌈(2 / entropy) ^ 2⌉₊ + +theorem cap_le (b : ℕ) : cap (2 * (b : ℝ)) ≤ energyConstant * b ^ 2 := by + have ht := Nat.floor_le (sq_nonneg (2 * (b : ℝ) / entropy)) + change (cap (2 * (b : ℝ)) : ℝ) ≤ _ at ht + apply (Nat.cast_le (α := ℝ)).mp + rw [Nat.cast_mul, Nat.cast_pow] + refine ht.trans ?_ + rw [mul_div_right_comm, mul_pow] + exact mul_le_mul_of_nonneg_right (Nat.le_ceil _) (sq_nonneg _) + +theorem energyA_le (v : Selection A b C d) (i : A) : energyA v i ≤ d * b := by + unfold energyA + calc + _ ≤ ∑ _ : Fin d, b := sum_le_sum fun j _ => Nat.le_of_lt_succ (v.1 i j).isLt + _ = _ := by simp + +theorem energyB_le (v : Selection A b C d) (i : A) : + energyB v i ≤ d * (energyConstant * b ^ 2) := by + unfold energyB profile + calc + _ ≤ ∑ _ : Fin d, energyConstant * b ^ 2 := sum_le_sum fun j _ => + (Nat.le_of_lt_succ (v.2.2 j i).isLt).trans (cap_le b) + _ = _ := by simp + +variable (A) [Fintype A] [DecidableEq A] + +private theorem card_selection (b C d : ℕ) : + Fintype.card (Selection A b C d) = + C * (((b + 1) * (cap (2 * (b : ℝ)) + 1)) ^ Fintype.card A) ^ d := by + simp only [Selection, Selector, Counts, Bounds, Fintype.card_prod, Fintype.card_fun, + Fintype.card_fin, mul_pow, ← pow_mul] + ac_rfl + +omit [DecidableEq A] in +private theorem selector_rate {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ b : ℕ in atTop, + (((b + 1) * (cap (2 * (b : ℝ)) + 1) : ℕ) : ℝ) ^ Fintype.card A ≤ Real.exp (ε * b) := by + let m := Fintype.card A + let t := 2 * ((energyConstant : ℝ) + 1) + have ht : 0 ≤ t := by unfold t; positivity + have h := (isLittleO_pow_exp_pos_mul_atTop (3 * m) hε).const_mul_left (t ^ m) + filter_upwards [eventually_ge_atTop 1, tendsto_natCast_atTop_atTop.eventually (h.bound + zero_lt_one)] + with b hb h + have hb' : 1 ≤ (b : ℝ) := Nat.one_le_cast.mpr hb + have hcap : (cap (2 * (b : ℝ)) : ℝ) ≤ energyConstant * (b : ℝ) ^ 2 := by exact_mod_cast cap_le b + have h' : t ^ m * (b : ℝ) ^ (3 * m) ≤ Real.exp (ε * b) := by + simpa [Real.norm_eq_abs, abs_of_nonneg ht] using h + push_cast + calc + _ ≤ ((2 * (b : ℝ)) * (((energyConstant : ℝ) + 1) * b ^ 2)) ^ m := by + gcongr + · linarith + · nlinarith + _ = t ^ m * (b : ℝ) ^ (3 * m) := by rw [pow_mul, ← mul_pow]; congr 1; unfold t; ring + _ ≤ _ := h' + +/-- Any prescribed selector rate is available by choosing the block +size first and then the number of blocks. -/ +theorem selector_small {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ b : ℕ in atTop, ∀ C : ℕ, ∀ᶠ d : ℕ in atTop, + (Fintype.card (Selection A b C d) : ℝ) ≤ Real.exp (ε * d * b) := by + filter_upwards [selector_rate A (half_pos hε), eventually_gt_atTop 0] with b h hb + intro C + let v := ε / 2 * (b : ℝ) + have hv : 0 < v := mul_pos (half_pos hε) (Nat.cast_pos.mpr hb) + have hd := Real.tendsto_exp_atTop.comp + ((tendsto_natCast_atTop_atTop (R := ℝ)).const_mul_atTop hv) + filter_upwards [hd.eventually_ge_atTop (C : ℝ)] with d hd + rw [card_selection, Nat.cast_mul, Nat.cast_pow, Nat.cast_pow] + calc + _ ≤ Real.exp (v * d) * (Real.exp v) ^ d := + mul_le_mul hd (pow_le_pow_left₀ (by positivity) h _) (by positivity) (by positivity) + _ = _ := by rw [← Real.exp_nat_mul, ← Real.exp_add]; congr 1; unfold v; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end + +/- # Both spheres have prescribed total energies at every auxiliary mark -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Finset Sphere Plant Filter + +variable {F K A : Type} [Field F] [Fintype A] [DecidableEq A] {r b C d : ℕ} + +open scoped Classical in +/-- Push the supported occupancy assignments onto the prescribed energy +level. The equality check is on the full ordered wedge. -/ +private theorem push_level (e : A → ℕ) (c : A → (Fin r → Bool) → F) + (hc : ∀ i x, c i x ≠ 0 → energy (occupancy x).val = e i) (T : (A → Wedge r) → F) : + (∑ y : States r e, (∏ i, ∑ x, if occupancy x = (y i).val then c i x else 0) * + T (fun i => (y i).val)) = + ∑ x : A → Fin r → Bool, (∏ i, c i (x i)) * T (fun i => occupancy (x i)) := by + simp_rw [Fintype.prod_sum, sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro x _ + by_cases h : ∀ i, c i (x i) ≠ 0 + · let y : States r e := fun i => ⟨occupancy (x i), hc i _ (h i)⟩ + rw [Fintype.sum_eq_single y] + · simp [y] + · intro z hz + obtain ⟨i, hi⟩ := Function.ne_iff.mp hz + have ne : occupancy (x i) ≠ (z i).val := fun eq => hi (Subtype.ext eq.symm) + rw [prod_eq_zero (mem_univ i) (ite_eq_right ne), zero_mul] + · push Not at h + obtain ⟨i, hi⟩ := h + rw [prod_eq_zero (mem_univ i) hi, zero_mul] + apply sum_eq_zero + intro y _ + rw [prod_eq_zero (mem_univ i) (by simp [hi]), zero_mul] + +open scoped Classical in +/-- One local coupling matrix per auxiliary mark. -/ +abbrev Coupling (F : Type) (v : Selection A b C d) := + ∀ i, Level (d * b) (energyA v i) → Level d (energyB v i) → F + +open scoped Classical in +/-- The indexed operation `∑ y : States d (energyB v), ∑ x : States (d * b) (energyA v), (∏ i, L +i (x i) (y i)) * T (fun i => (x i).val) * value z y`. -/ +def couple (z : A → F) (v : Selection A b C d) (L : Coupling F v) + (T : (A → Wedge (d * b)) → F) := + ∑ y : States d (energyB v), ∑ x : States (d * b) (energyA v), + (∏ i, L i (x i) (y i)) * T (fun i => (x i).val) * value z y + +open scoped Classical in +theorem private_levels [Field K] [Infinite K] [Algebra F K] [Nonempty A] + (sync : Prices.SharedPrice K) (z : A → F) (hz : Function.Injective z) : + ∀ᶠ b : ℕ in atTop, ∀ (rows : List A) (J : (A → Bool) → F), + ∃ C : ℕ, ∀ d : ℕ, + ∃ L : (v : Selection A b C d) → Coupling F v, + ∀ T : (A → Wedge (d * b)) → F, + (∑ x : A → Fin (d * b) → Bool, signed rows J x * T (fun i => occupancy (x i))) = + ∑ v, (-1 : F) ^ sign rows v * couple z v (L v) T := by + filter_upwards [private_joint sync z hz] with b hb + intro rows J + obtain ⟨C, hC⟩ := hb rows J + refine ⟨C, fun d => ?_⟩ + obtain ⟨L, hL, he⟩ := hC d + let W (v : Selection A b C d) : Coupling F v := + fun i a b => ∑ x, if occupancy x = a.val then L v i x b else 0 + refine ⟨W, fun T => ?_⟩ + simp_rw [he, sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro v _ + simp only [mul_assoc, ← mul_sum] + congr 1 + simp_rw [sum_mul] + rw [sum_comm] + unfold couple + apply sum_congr rfl + intro y _ + have h := push_level (energyA v) (fun i x => L v i x (y i)) (fun i x => hL v i x _) T + rw [← sum_mul] + rw [show (∑ x : States (d * b) (energyA v), (∏ i, W v i (x i) (y i)) * + T (fun i => (x i).val)) = _ from h, sum_mul] + exact sum_congr rfl (fun _ _ => mul_right_comm _ _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end + +/- +# Public energies and a private selector + +The outer index records just the total energy at each auxiliary mark +of each sphere. Its size is polynomial in the number of species. +The short private selector is summed internally. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Finset Sphere Plant Filter + +variable {F K : Type} [Field F] {n b d : ℕ} + +open scoped Classical in +/-- The two total doubled energies at each auxiliary mark. -/ +abbrev Shape (n b d : ℕ) := + (Fin n → Fin (d * b + 1)) × (Fin n → Fin (d * (energyConstant * b ^ 2) + 1)) + +open scoped Classical in +/-- The indexed operation `(fun i => ⟨energyA v i, Nat.lt_succ_of_le (energyA_le v i)⟩, fun i => +⟨energyB v i, Nat.lt_succ_of_le (energyB_le v i)⟩)`. -/ +def shape {C : ℕ} (v : Selection (Fin n) b C d) : Shape n b d := + (fun i => ⟨energyA v i, Nat.lt_succ_of_le (energyA_le v i)⟩, + fun i => ⟨energyB v i, Nat.lt_succ_of_le (energyB_le v i)⟩) + +open scoped Classical in +theorem card_shape (n b d : ℕ) : Fintype.card (Shape n b d) = + ((d * b + 1) * (d * (energyConstant * b ^ 2) + 1)) ^ n := by + simp only [Shape, Fintype.card_prod, Fintype.card_fun, Fintype.card_fin, mul_pow] + +open scoped Classical in +/-- The condition `∀ i : Fin n, Level (d * b) (p.1 i).val → Level d (p.2 i).val → F` on the +specified data. -/ +abbrev Tables (F : Type) (p : Shape n b d) := + ∀ i : Fin n, Level (d * b) (p.1 i).val → Level d (p.2 i).val → F + +open scoped Classical in +/-- The term used in the `Private` construction. -/ +def term (z : Fin n → F) (p : Shape n b d) (U : Tables F p) + (T : (Fin n → Wedge (d * b)) → F) := + ∑ y : States d (fun i => (p.2 i).val), ∑ x : States (d * b) (fun i => (p.1 i).val), + (∏ i, U i (x i) (y i)) * T (fun i => (x i).val) * + wick fieldKernel (bundle z (fun i => (y i).val) (List.finRange n)) + +open scoped Classical in +private theorem ordered (z : Fin n → F) (e : Fin n → ℕ) : + ∃ k : F, ∀ y : States d e, + value z y = k * wick fieldKernel (bundle z (fun i => (y i).val) (List.finRange n)) := by + have perm : (univ : Finset (Fin n)).toList.Perm (List.finRange n) := + (List.perm_ext_iff_of_nodup (nodup_toList _) (List.nodup_finRange _)).mpr (by simp) + obtain ⟨q, hq⟩ := wick_perm_sites (R := F) (r := d) e perm + let f (i : Fin n × Mode d) := (z i.1, i.2) + refine ⟨(-1) ^ q, fun y => ?_⟩ + have h := hq (fun i j => fieldKernel (f i) (f j)) (fun i j => fieldKernel_skew _ _) y [] + simp only [List.nil_append, ← wick_map] at h + simpa [value, bundle, List.map_flatMap, marksAt, Function.comp_def, f] using h + +open scoped Classical in +private theorem move_sign {C : ℕ} (z : Fin n → F) (v : Selection (Fin n) b C d) (L : Coupling F v) : + ∃ k : F, ∀ T, couple z v L T = k * term z (shape v) L T := by + obtain ⟨k, hk⟩ := ordered (d := d) z (energyB v) + refine ⟨k, fun T => ?_⟩ + unfold couple term + simp only [shape, hk, mul_sum, mul_left_comm _ k, mul_assoc] + rfl + +open scoped Classical in +/-- One selector and one family of local tables per public shape. +The scalar weight can enforce consistency of the private choice. -/ +structure Program (F : Type) (n b d : ℕ) where + /-- The label data. -/ + labels : ℕ + /-- The scalar prefactor of type `Shape n b d → Fin labels → F`. -/ + scalar : Shape n b d → Fin labels → F + /-- The local table at each indexed position carried by `Program`, with type `(p : Shape n b + d) → Fin labels → Tables F p`. -/ + table : (p : Shape n b d) → Fin labels → Tables F p + +open scoped Classical in +/-- The quantity computed by `∑ e, ∑ i, p.scalar e i * term z e (p.table e i) T`. -/ +def Program.eval (p : Program F n b d) (z : Fin n → F) (T : (Fin n → Wedge (d * b)) → F) : F := + ∑ e, ∑ i, p.scalar e i * term z e (p.table e i) T + +open scoped Classical in +private theorem compile (z : Fin n → F) {C : ℕ} (L : (v : Selection (Fin n) b C d) → Coupling F v) : + ∃ p : Program F n b d, p.labels = Fintype.card (Selection (Fin n) b C d) ∧ ∀ T, + p.eval z T = ∑ v, (-1 : F) ^ sign (List.finRange n) v * couple z v (L v) T := by + choose k hk using fun v => move_sign z v (L v) + let e := (Fintype.equivFin (Selection (Fin n) b C d)).symm + let W (v : Selection (Fin n) b C d) (s : Shape n b d) : Tables F s := + if h : shape v = s then h ▸ (show Tables F (shape v) from L v) else fun _ _ _ => 0 + let g (v : Selection (Fin n) b C d) (s : Shape n b d) : F := + if s = shape v then (-1 : F) ^ sign (List.finRange n) v * k v else 0 + refine ⟨⟨_, fun s j => g (e j) s, fun s j => W (e j) s⟩, rfl, fun T => ?_⟩ + rw [Program.eval, sum_comm, ← e.sum_comp] + refine sum_congr rfl fun j _ => ?_ + simp only [g, W, ite_mul, zero_mul, sum_ite_eq', mem_univ, ite_true, ↓reduceDIte, hk, mul_assoc] + +open scoped Classical in +theorem private_program [Field K] [Algebra F K] [Infinite K] [NeZero n] + (sync : Prices.SharedPrice K) (z : Fin n ↪ F) {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ b : ℕ in atTop, ∀ J : (Fin n → Bool) → F, ∀ᶠ d : ℕ in atTop, + ∃ p : Program F n b d, (p.labels : ℝ) ≤ Real.exp (ε * d * b) ∧ + ∀ T, p.eval z T = ∑ x, signed (List.finRange n) J x * T (fun i => occupancy (x i)) := by + filter_upwards [private_levels sync z z.injective, selector_small (Fin n) hε] with b hb hs + intro J + obtain ⟨C, hC⟩ := hb (List.finRange n) J + filter_upwards [hs C] with d hd + obtain ⟨L, h⟩ := hC d + obtain ⟨p, he, hp⟩ := compile z L + exact ⟨p, he ▸ hd, fun T => (hp T).trans (h T).symm⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end + +/- +# Implanting a wiring table using two spheres + +The original marks carry fixed-energy codes, independently for each +species. This includes seam labels. Only the total energy is checked +there, so the rule applies to an arbitrary summation over seam states. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Routing.Private + +open Finset Sphere Plant Filter +variable {F K : Type} [Field F] {m n r b d : ℕ} + +open scoped Classical in +/-- The condition `∀ i, Level r (r * (8 * w i ^ 2))` on the specified data. -/ +abbrev Marks (w : Fin m → ℕ) (r : ℕ) := ∀ i, Level r (r * (8 * w i ^ 2)) + +open scoped Classical in +/-- The value specified by `∑ σ : (i : Fin m) → bitsAt (w i) r, if ∀ i, markCode (w i) r (σ i) = +X i then ∏ j, L (fun i => σ i j) else 0`. -/ +def demand (w : Fin m → ℕ) (L : Bits w → F) (X : Marks w r) : F := + ∑ σ : (i : Fin m) → bitsAt (w i) r, + if ∀ i, markCode (w i) r (σ i) = X i then ∏ j, L (fun i => σ i j) else 0 + +open scoped Classical in +/-- Concatenates the components in the order `wick fieldKernel (bundle y Y (List.finRange n) ++ +bundle z (fun i => (X i).val) (List.finRange m))`. -/ +def marked (z : Fin m → F) (y : Fin n → F) {w : Fin m → ℕ} + (X : Marks w r) (Y : Fin n → Wedge r) : F := + wick fieldKernel (bundle y Y (List.finRange n) ++ bundle z (fun i => (X i).val) (List.finRange m)) + +open scoped Classical in +/-- The thresholds for the block size and number of blocks are uniform +in all three sets of positions, the individual widths and the wiring table. -/ +theorem install [Finite F] [Field K] [Algebra F K] [Infinite K] [NeZero n] + (sync : Prices.SharedPrice K) {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ b : ℕ in atTop, ∀ᶠ d : ℕ in atTop, + ∀ (m : ℕ) (z : Fin m ↪ F) (y q : Fin n ↪ F), (∀ i j, y j ≠ z i) → + ∀ w : Fin m → ℕ, (∑ i, 4 * w i) ≤ n → ∀ L : Bits w → F, + ∃ p : Program F n b d, (p.labels : ℝ) ≤ Real.exp (ε * d * b) ∧ + ∀ X : Marks w (d * b), p.eval q (marked z y X) = demand w L X := by + have hm := Filter.eventually_all.mpr (fun q : Fin n ↪ F => private_program sync q hε) + filter_upwards [hm] with b hb + have hd := Filter.eventually_all.mpr fun q => Filter.eventually_all.mpr (hb q) + filter_upwards [hd] with d hp + intro m z y q he w hn L + obtain ⟨J, _, hJ⟩ := joint_decoded z y he w hn L + obtain ⟨p, hy, h⟩ := hp q J + exact ⟨p, hy, fun X => (h (marked z y X)).trans (hJ _ X)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Routing.Private +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Private/Preparation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Private/Preparation.lean new file mode 100644 index 0000000000..2bc862bc5f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Private/Preparation.lean @@ -0,0 +1,919 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Tactic.Ring +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Interpolation +public import Mathlib.Algebra.Polynomial.Reverse +public import Mathlib.Data.List.Sort +public import Mathlib.Order.Prod.Lex.Basic +public import Mathlib.LinearAlgebra.Finsupp.LinearCombination +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements + +/-! +# Fermionic pairing sums + +The recursion pairs the first generator with one of the remaining ones. +Moving the partner left by one position changes its sign. Cancellation +of repeated generators uses a square-zero contraction, even in characteristic two. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {α R : Type*} [CommRing R] + +/-- Sum over deletions of one generator, with alternating signs. -/ +def contract (f : α → R) (P : List α → R) : List α → R + | [] => 0 + | x :: xs => f x * P xs - contract f (fun ys => P (x :: ys)) xs + +@[simp] theorem contract_nil (f : α → R) (P : List α → R) : contract f P [] = 0 := rfl + +theorem contract_cons (f : α → R) (P : List α → R) (x : α) (xs : List α) : + contract f P (x :: xs) = f x * P xs - contract f (fun ys => P (x :: ys)) xs := rfl + +theorem contract_congr {P Q : List α → R} (f : α → R) (xs : List α) + (h : ∀ ys : List α, ys.length + 1 = xs.length → P ys = Q ys) : + contract f P xs = contract f Q xs := by + induction xs generalizing P Q with + | nil => rfl + | cons x xs ih => + rw [contract_cons, contract_cons, h xs rfl] + congr 1 + apply ih + intro ys hy + exact h _ (by simp [hy]) + +/-- In the case `_, []`, this construction gives `1`. -/ +def wickAux (k : α → α → R) : ℕ → List α → R + | _, [] => 1 + | 0, _ :: _ => 0 + | n + 1, x :: xs => contract (k x) (wickAux k n) xs + +/-- The signed perfect matching sum in list order. -/ +def wick (k : α → α → R) (xs : List α) : R := wickAux k xs.length xs + +private theorem wickAux_eq (k : α → α → R) (n : ℕ) (xs : List α) (hn : xs.length ≤ n) : + wickAux k n xs = wick k xs := by + induction n using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => simp [wickAux, wick] + | cons x xs => + cases n with + | zero => simp at hn + | succ n => + simp only [wick, List.length_cons, wickAux] + apply contract_congr + intro ys hy + simp only [List.length_cons] at hn + rw [ih n (by omega) ys (by omega), ih xs.length (by omega) ys (by omega)] + +@[simp] theorem wick_nil (k : α → α → R) : wick k [] = 1 := rfl + +theorem wick_cons (k : α → α → R) (x : α) (xs : List α) : + wick k (x :: xs) = contract (k x) (wick k) xs := by + change contract (k x) (wickAux k xs.length) xs = _ + exact contract_congr _ _ fun ys hy => wickAux_eq k _ ys (by omega) + +@[simp] theorem contract_zero (f : α → R) (xs : List α) : + contract f (fun _ => 0) xs = 0 := by + induction xs with + | nil => rfl + | cons x xs ih => simp [contract_cons, ih] + +theorem contract_scale (f : α → R) (P : List α → R) (c : R) (xs : List α) : + contract f (fun ys => c * P ys) xs = c * contract f P xs := by + induction xs generalizing P with + | nil => simp + | cons x xs ih => + rw [contract_cons, contract_cons, ih (fun ys => P (x :: ys))] + ring + +theorem contract_sub (f : α → R) (P Q : List α → R) (xs : List α) : + contract f (fun ys => P ys - Q ys) xs = contract f P xs - contract f Q xs := by + induction xs generalizing P Q with + | nil => simp + | cons x xs ih => + rw [contract_cons, contract_cons, contract_cons, ih (fun ys => P (x :: ys)) (fun ys + => Q (x :: ys))] + ring + +private theorem contract_neg (f : α → R) (P : List α → R) (xs : List α) : + contract f (fun ys => -P ys) xs = -contract f P xs := by + simpa using contract_scale f P (-1) xs + +private theorem contract_twice (f g : α → R) (P : List α → R) (x : α) (xs : List α) : + contract f (contract g P) (x :: xs) = + f x * contract g P xs - g x * contract f P xs + + contract f (contract g (fun ys => P (x :: ys))) xs := by + simp only [contract_cons, contract_sub, contract_scale] + ring + +theorem contract_square (f : α → R) (P : List α → R) (xs : List α) : + contract f (contract f P) xs = 0 := by + induction xs generalizing P with + | nil => rfl + | cons x xs ih => simp only [contract_twice, ih, sub_self, add_zero] + +theorem contract_anticomm (f g : α → R) (P : List α → R) (xs : List α) : + contract f (contract g P) xs = -contract g (contract f P) xs := by + induction xs generalizing P with + | nil => simp + | cons x xs ih => rw [contract_twice, contract_twice, ih]; ring + +variable {k : α → α → R} + +theorem wick_odd {xs : List α} (h : xs.length % 2 = 1) : wick k xs = 0 := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => simp at h + | cons x xs => + rw [wick_cons, ← contract_zero (k x) xs] + apply contract_congr + intro ys hy + simp only [List.length_cons] at h hn + exact ih ys.length (by omega) (by omega) rfl + +private theorem wick_two (x y : α) (xs : List α) : + wick k (x :: y :: xs) = + k x y * wick k xs - contract (k x) (contract (k y) (wick k)) xs := by + rw [wick_cons, contract_cons, show (fun ys => wick k (y :: ys)) = _ from funext (wick_cons k y)] + +private theorem contract_swap (f : α → R) (P : List α → R) (x y : α) (p s : List α) + (h : ∀ q : List α, q.length ≤ p.length → ∀ t, P (q ++ y :: x :: t) = -P (q ++ x :: y :: t)) : + contract f P (p ++ y :: x :: s) = -contract f P (p ++ x :: y :: s) := by + induction p generalizing P with + | nil => + have e : (fun t => P (y :: x :: t)) = (fun t => -P (x :: y :: t)) := + funext (h [] le_rfl) + simp only [List.nil_append, contract_cons, e, contract_neg] + ring + | cons z p ih => + have e := ih (fun t => P (z :: t)) (fun q hq t => h (z :: q) (by simpa using hq) t) + simp only [List.cons_append, contract_cons, h p (by simp), e] + ring + +theorem wick_swap (skew : ∀ x y, k y x = -k x y) (p s : List α) (x y : α) : + wick k (p ++ y :: x :: s) = -wick k (p ++ x :: y :: s) := by + induction hn : p.length using Nat.strong_induction_on generalizing p s with + | ind n ih => + cases p with + | nil => + simp only [List.nil_append, wick_two] + rw [skew x y, contract_anticomm] + ring + | cons z p => + simp only [List.cons_append, wick_cons] + apply contract_swap + intro q hq t + exact ih q.length (by simp only [List.length_cons] at hn; omega) q t rfl + +private theorem contract_repeat (f : α → R) (P : List α → R) (x : α) (p s : List α) + (h : ∀ q : List α, q.length ≤ p.length → ∀ t, P (q ++ x :: x :: t) = 0) : + contract f P (p ++ x :: x :: s) = 0 := by + induction p generalizing P with + | nil => + have e : (fun t => P (x :: x :: t)) = (fun _ => 0) := funext (h [] le_rfl) + simp only [List.nil_append, contract_cons, e, contract_zero, sub_zero, sub_self] + | cons z p ih => + have e := ih (fun t => P (z :: t)) (fun q hq t => h (z :: q) (by simpa using hq) t) + simp only [List.cons_append, contract_cons, h p (by simp), e, mul_zero, sub_self] + +private theorem wick_adjacent_repeat (diag : ∀ x, k x x = 0) (p s : List α) (x : α) : + wick k (p ++ x :: x :: s) = 0 := by + induction hn : p.length using Nat.strong_induction_on generalizing p s with + | ind n ih => + cases p with + | nil => simp only [List.nil_append, wick_two, diag, zero_mul, contract_square, sub_self] + | cons z p => + simp only [List.cons_append, wick_cons] + apply contract_repeat + intro q hq t + exact ih q.length (by simp only [List.length_cons] at hn; omega) q t rfl + +private theorem wick_move (skew : ∀ x y, k y x = -k x y) (p q s : List α) (x : α) : + wick k (p ++ x :: (q ++ s)) = (-1 : R) ^ q.length * wick k (p ++ (q ++ x :: s)) := by + induction q generalizing p with + | nil => simp + | cons y q ih => + have e := ih (p ++ [y]) + simp only [List.append_assoc, List.singleton_append] at e + rw [List.cons_append, wick_swap skew, e, List.length_cons, pow_succ, List.cons_append] + ring + +theorem wick_repeat (skew : ∀ x y, k y x = -k x y) (diag : ∀ x, k x x = 0) + (p q s : List α) (x : α) : + wick k (p ++ x :: (q ++ x :: s)) = 0 := by + rw [wick_move skew, ← List.append_assoc, wick_adjacent_repeat diag, mul_zero] + +theorem wick_swap_blocks (skew : ∀ x y, k y x = -k x y) (p a b s : List α) : + wick k (p ++ a ++ b ++ s) = + (-1 : R) ^ (a.length * b.length) * wick k (p ++ b ++ a ++ s) := by + induction a generalizing p with + | nil => simp + | cons x a ih => + have e := ih (p ++ [x]) + simp only [List.append_assoc, List.singleton_append] at e + simp only [List.cons_append] at e + simp only [List.append_assoc, List.cons_append, List.length_cons, Nat.add_mul, one_mul, pow_add] + rw [e, wick_move skew, mul_assoc] + +/-- Reversing a list exchanges its first and last element, then its second +and penultimate element, and so on. -/ +theorem wick_reverse_sign (skew : ∀ x y, k y x = -k x y) (p xs s : List α) : + wick k (p ++ xs.reverse ++ s) = (-1 : R) ^ (xs.length / 2) * wick k (p ++ xs ++ s) := by + match xs with + | [] => simp + | [_] => simp + | x :: y :: zs => + have e := wick_swap_blocks skew p zs.reverse [y, x] s + have t := wick_reverse_sign skew (p ++ [y, x]) zs s + have signo : (-1 : R) ^ (zs.reverse.length * [y, x].length) = 1 := by + change (-1 : R) ^ (zs.reverse.length * 2) = _ + rw [Nat.mul_comm, pow_mul, neg_one_sq, one_pow] + rw [signo, one_mul, t] at e + simp only [List.append_assoc, List.cons_append, List.nil_append] at e + simp only [List.reverse_cons, List.append_assoc, List.cons_append, List.nil_append, + List.length_cons, show (zs.length + 1 + 1) / 2 = zs.length / 2 + 1 by omega, pow_succ] + rw [e, wick_swap skew] + ring + +private theorem contract_scale_left (f : α → R) (P : List α → R) (c : R) (xs : List α) : + contract (fun y => c * f y) P xs = c * contract f P xs := by + induction xs generalizing P with + | nil => simp + | cons x xs ih => rw [contract_cons, contract_cons, ih]; ring + +theorem wick_scale_kernel (k : α → α → R) (c : R) (xs : List α) : + wick (fun x y => c * k x y) xs = c ^ (xs.length / 2) * wick k xs := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + match xs with + | [] => subst n; simp + | [x] => simp [wick_cons] + | x :: y :: zs => + simp only [List.length_cons] at hn + rw [wick_cons, wick_cons, contract_scale_left] + have e : contract (k x) (wick (fun x y => c * k x y)) (y :: zs) = + contract (k x) (fun us => c ^ (zs.length / 2) * wick k us) (y :: zs) := by + apply contract_congr + intro us hu + simp only [List.length_cons] at hu + exact ih zs.length (by omega) us (by omega) + rw [e, contract_scale, show n / 2 = zs.length / 2 + 1 by omega, pow_succ', mul_assoc] + +theorem wick_reverse (skew : ∀ x y, k y x = -k x y) (xs : List α) : + wick k xs.reverse = wick (fun x y => -k x y) xs := by + simpa using (wick_reverse_sign skew [] xs []).trans (by + simpa using (wick_scale_kernel k (-1) xs).symm) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Splitting a Wick pairing sum + +A partial matching contracts some pairs and applies a residual weight to +the unmatched generators in their original order. The decomposition only +uses commutative ring operations. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {α R : Type*} [CommRing R] + +/-- In the case `0, P, xs`, this construction gives `P xs`. -/ +def partialAux (k : α → α → R) : ℕ → (List α → R) → List α → R + | 0, P, xs => P xs + | _ + 1, P, [] => P [] + | n + 1, P, x :: xs => partialAux k n (fun ys => P (x :: ys)) xs + + contract (k x) (partialAux k n P) xs + +/-- Signed sum over partial matchings, weighted by the residual list. -/ +def partialWick (k : α → α → R) (P : List α → R) (xs : List α) : R := + partialAux k xs.length P xs + +private theorem partialAux_eq (k : α → α → R) (P : List α → R) + (n : ℕ) (xs : List α) (hn : xs.length ≤ n) : + partialAux k n P xs = partialWick k P xs := by + induction n using Nat.strong_induction_on generalizing xs P with + | ind n ih => + cases xs with + | nil => cases n <;> rfl + | cons x xs => + cases n with + | zero => simp at hn + | succ n => + simp only [List.length_cons] at hn + simp only [partialWick, List.length_cons, partialAux] + rw [ih n (by omega) _ xs (by omega)] + congr 1 + apply contract_congr + intro ys hy + rw [ih n (by omega) P ys (by omega), ih xs.length (by omega) P ys (by omega)] + +@[simp] theorem partialWick_nil (k : α → α → R) (P : List α → R) : + partialWick k P [] = P [] := rfl + +theorem partialWick_cons (k : α → α → R) (P : List α → R) (x : α) (xs : List α) : + partialWick k P (x :: xs) = partialWick k (fun ys => P (x :: ys)) xs + + contract (k x) (partialWick k P) xs := by + change partialWick k _ xs + contract (k x) (partialAux k xs.length P) xs = _ + congr 1 + exact contract_congr _ _ fun ys hy => partialAux_eq k _ _ ys (by omega) + +private theorem contract_add (f : α → R) (P Q : List α → R) (xs : List α) : + contract f (fun ys => P ys + Q ys) xs = contract f P xs + contract f Q xs := by + induction xs generalizing P Q with + | nil => simp + | cons x xs ih => + rw [contract_cons, contract_cons, contract_cons, + ih (fun ys => P (x :: ys)) (fun ys => Q (x :: ys))] + ring + +private theorem contract_add_left (f g : α → R) (P : List α → R) (xs : List α) : + contract (fun x => f x + g x) P xs = contract f P xs + contract g P xs := by + induction xs generalizing P with + | nil => simp + | cons x xs ih => + rw [contract_cons, contract_cons, contract_cons, ih] + ring + +theorem partialWick_linear (k : α → α → R) (P Q : List α → R) (c : R) (xs : List α) : + partialWick k (fun t => c * P t - Q t) xs = + c * partialWick k P xs - partialWick k Q xs := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs P Q with + | ind n ih => + cases xs with + | nil => rfl + | cons x xs => + simp only [List.length_cons] at hn + have e := ih xs.length (by omega) (fun t => P (x :: t)) (fun t => Q (x :: t)) xs rfl + have h : contract (k x) (partialWick k (fun t => c * P t - Q t)) xs = + contract (k x) (fun t => c * partialWick k P t - partialWick k Q t) xs := + contract_congr _ _ fun t ht => ih t.length (by omega) P Q t rfl + simp only [partialWick_cons, e, h, contract_sub, contract_scale] + ring + +/-- Deletion commutes with the partial matching sum because each contracted +pair crosses an unmatched generator with sign one. -/ +theorem partialWick_contract (k : α → α → R) (f : α → R) (P : List α → R) (xs : List α) : + partialWick k (contract f P) xs = contract f (partialWick k P) xs := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs P with + | ind n ih => + cases xs with + | nil => rfl + | cons x xs => + simp only [List.length_cons] at hn + have e := ih xs.length (by omega) (fun t => P (x :: t)) xs rfl + have h : contract (k x) (partialWick k (contract f P)) xs = + contract (k x) (contract f (partialWick k P)) xs := + contract_congr _ _ fun t ht => ih t.length (by omega) P t rfl + simp only [partialWick_cons, contract_cons, partialWick_linear, e, h, contract_add] + rw [contract_anticomm] + ring + +/-- Choose which pairs use the first kernel. All other pairs use the second. -/ +theorem wick_add (k l : α → α → R) (xs : List α) : + wick (fun x y => k x y + l x y) xs = partialWick k (wick l) xs := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => rfl + | cons x xs => + simp only [List.length_cons] at hn + have e (f : α → R) : contract f (wick (fun x y => k x y + l x y)) xs = + contract f (partialWick k (wick l)) xs := + contract_congr _ _ fun t ht => ih t.length (by omega) t rfl + rw [wick_cons, partialWick_cons, contract_add_left, e, e, + show (fun t => wick l (x :: t)) = _ from funext (wick_cons l x), partialWick_contract, + add_comm] + +theorem contract_vanish (f : α → R) (P : List α → R) (xs : List α) + (h : ∀ x ∈ xs, f x = 0) : contract f P xs = 0 := by + induction xs generalizing P with + | nil => rfl + | cons x xs ih => + simp only [List.forall_mem_cons] at h + rw [contract_cons, h.1, zero_mul, ih _ h.2, sub_self] + +theorem contract_append (f : α → R) (P : List α → R) (xs ys : List α) + (h : ∀ y ∈ ys, f y = 0) : + contract f P (xs ++ ys) = contract f (fun t => P (t ++ ys)) xs := by + induction xs generalizing P with + | nil => exact contract_vanish f P ys h + | cons x xs ih => rw [List.cons_append, contract_cons, contract_cons, ih]; rfl + +theorem contract_sublist_congr {P Q : List α → R} (f : α → R) (xs : List α) + (h : ∀ ys : List α, ys.Sublist xs → ys.length + 1 = xs.length → P ys = Q ys) : + contract f P xs = contract f Q xs := by + induction xs generalizing P Q with + | nil => rfl + | cons x xs ih => + rw [contract_cons, contract_cons, h xs (by simp) rfl] + congr 1 + apply ih + intro ys hy he + exact h _ (hy.cons_cons x) (by simp [he]) + +/-- When no contraction crosses a boundary, the two partial matchings +can be chosen independently. The remaining generators stay in site order. -/ +theorem partialWick_append (k : α → α → R) (P : List α → R) (xs ys : List α) + (h : ∀ x ∈ xs, ∀ y ∈ ys, k x y = 0) : + partialWick k P (xs ++ ys) = + partialWick k (fun s => partialWick k (fun t => P (s ++ t)) ys) xs := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs P with + | ind n ih => + cases xs with + | nil => rfl + | cons x xs => + simp only [List.length_cons] at hn + simp only [List.forall_mem_cons] at h + rw [List.cons_append, partialWick_cons, partialWick_cons, + ih xs.length (by omega) _ xs h.2 rfl, contract_append _ _ _ _ h.1] + congr 1 + apply contract_sublist_congr + intro t ht he + exact ih t.length (by omega) P t (fun z hz => h.2 z (ht.subset hz)) rfl + +theorem partialWick_vanish (k : α → α → R) (P : List α → R) (xs : List α) + (h : ∀ x ∈ xs, ∀ y ∈ xs, k x y = 0) : partialWick k P xs = P xs := by + induction xs generalizing P with + | nil => rfl + | cons x xs ih => + rw [partialWick_cons, contract_vanish, add_zero, ih] + · exact fun z hz y hy => h z (by simp [hz]) y (by simp [hy]) + · exact fun y hy => h x (by simp) y (by simp [hy]) + +/-- Expand only the internal contractions of a single cluster. -/ +theorem wick_add_append (k l : α → α → R) (xs ys : List α) (h : ∀ x y, y ∈ ys → k x y = 0) : + wick (fun x y => k x y + l x y) (xs ++ ys) = partialWick k (fun s => wick l (s ++ ys)) xs := by + rw [wick_add, partialWick_append _ _ _ _ (fun x _ => h x)] + simp_rw [partialWick_vanish k _ ys (fun x _ => h x)] + +/-- The residual generator list always has the original parity. -/ +theorem partialWick_congr (k : α → α → R) {P Q : List α → R} (xs : List α) + (h : ∀ ys : List α, ys.Sublist xs → ys.length % 2 = xs.length % 2 → P ys = Q ys) : + partialWick k P xs = partialWick k Q xs := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs P Q with + | ind n ih => + cases xs with + | nil => exact h [] (by simp) rfl + | cons x xs => + simp only [List.length_cons] at hn + rw [partialWick_cons, partialWick_cons] + congr 1 + · apply ih xs.length (by omega) xs _ rfl + intro ys hy he + exact h _ (hy.cons_cons x) (by simp only [List.length_cons]; omega) + · apply contract_sublist_congr + intro ys hy he + apply ih ys.length (by omega) ys _ rfl + intro zs hz ht + exact h zs ((hz.trans hy).cons x) (by simp only [List.length_cons]; omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {α β ι R : Type*} [CommRing R] + +private theorem contract_map (f : α → β) (q : β → R) (P : List β → R) (xs : List α) : + contract q P (xs.map f) = + contract (fun x => q (f x)) (fun ys => P (ys.map f)) xs := by + induction xs generalizing P with + | nil => rfl + | cons x xs ih => + rw [List.map_cons, contract_cons, contract_cons, ih] + rfl + +theorem wick_map (k : β → β → R) (f : α → β) (xs : List α) : + wick k (xs.map f) = wick (fun x y => k (f x) (f y)) xs := by + induction h : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => rfl + | cons x xs => + rw [List.map_cons, wick_cons, wick_cons, contract_map] + apply contract_congr + intro ys hy + exact ih ys.length (by simp only [List.length_cons] at h; omega) ys rfl + +private theorem contract_linear (s : Finset ι) (c : ι → R) (g : ι → α → R) + (P : List α → R) (xs : List α) : + contract (fun x => ∑ i ∈ s, c i * g i x) P xs = + ∑ i ∈ s, c i * contract (g i) P xs := by + induction xs generalizing P with + | nil => simp + | cons x xs ih => + simp only [contract_cons, ih, Finset.sum_mul, mul_sub, Finset.sum_sub_distrib, mul_assoc] + +/-- Linearity in one row and its corresponding column. -/ +theorem wick_linear {k : α → α → R} (skew : ∀ x y, k y x = -k x y) + {x : α} {s : Finset ι} {c : ι → R} {g : ι → α} + (hx : ∀ y, k x y = ∑ i ∈ s, c i * k (g i) y) (p q : List α) : + wick k (p ++ x :: q) = ∑ i ∈ s, c i * wick k (p ++ g i :: q) := by + have front (y : α) : wick k (p ++ y :: q) = + (-1 : R) ^ p.length * wick k (y :: (p ++ q)) := by + simpa using wick_swap_blocks skew [] p [y] q + simp only [front, wick_cons] + rw [funext hx, contract_linear, Finset.mul_sum] + exact Finset.sum_congr rfl (fun _ _ => mul_left_comm _ _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- Additive degrees of perfect pairing monomials. -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {A R S : Type*} [CommRing R] [CommRing S] {r : ℕ} + +/-- Computes the weight by the application `energy (xs.map Prod.snd)`. -/ +abbrev weight (xs : List (A × Mode r)) := energy (xs.map Prod.snd) + +theorem weight_cons (x : A × Mode r) (xs : List (A × Mode r)) : + weight (x :: xs) = 2 * x.2.2 + 1 + weight xs := rfl + +private theorem wick_graded (D : ℕ → R → S → Prop) + (h₀ : ∀ n, D n 0 0) (h₁ : D 0 1 1) + (hsub : ∀ {n x y z w}, D n x y → D n z w → D n (x - z) (y - w)) + (hmul : ∀ {n m x y z w}, D n x y → D m z w → D (n + m) (x * z) (y * w)) + (k : A × Mode r → A × Mode r → R) (l : A × Mode r → A × Mode r → S) + (h : ∀ x y, D (x.2.2 + y.2.2 + 1) (k x y) (l x y)) (xs : List (A × Mode r)) : + D (weight xs / 2) (wick k xs) (wick l xs) := by + have recu (x : A × Mode r) (ys : List (A × Mode r)) (d : ℕ) + (P : List (A × Mode r) → R) (Q : List (A × Mode r) → S) + (hp : ∀ zs : List (A × Mode r), zs.length + 1 = ys.length → + D ((d + weight zs) / 2) (P zs) (Q zs)) : + D ((d + weight (x :: ys)) / 2) (contract (k x) P ys) (contract (l x) Q ys) := by + induction ys generalizing d P Q with + | nil => exact h₀ _ + | cons y ys ih => + rw [contract_cons, contract_cons] + apply hsub + · rw [show (d + weight (x :: y :: ys)) / 2 = + x.2.2 + y.2.2 + 1 + (d + weight ys) / 2 by rw [weight_cons, weight_cons]; omega] + exact hmul (h x y) (hp ys rfl) + · rw [show d + weight (x :: y :: ys) = d + (2 * y.2.2 + 1) + weight (x :: ys) by + simp only [weight_cons]; omega] + refine ih _ _ _ fun zs hz => ?_ + simpa only [weight_cons, add_assoc] using hp (y :: zs) (by simp [hz]) + induction hn : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => simpa [weight, energy] using h₁ + | cons x xs => + rw [wick_cons, wick_cons, ← zero_add (weight (x :: xs))] + refine recu _ _ _ _ _ fun ys hy => ?_ + rw [zero_add] + exact ih ys.length (by simp only [List.length_cons] at hn; omega) ys rfl + +theorem wick_scale_energy (k : A × Mode r → A × Mode r → R) (c : R) (xs : List (A × Mode r)) : + wick (fun x y => c ^ (x.2.2 + y.2.2 + 1) * k x y) xs = + c ^ (weight xs / 2) * wick k xs := by + refine wick_graded (fun n a b => a = c ^ n * b) (by simp) (by simp) ?_ ?_ _ k + (fun _ _ => rfl) xs + · rintro n _ _ _ _ rfl rfl + rw [mul_sub] + · rintro n m _ _ _ _ rfl rfl + rw [pow_add, mul_mul_mul_comm] + +open Polynomial + +/-- Two charts of a homogeneous binary form of degree `n`. -/ +def BinaryForm (n : ℕ) (p q : R[X]) : Prop := p.natDegree ≤ n ∧ p.reflect n = q + +theorem BinaryForm.zero (n : ℕ) : BinaryForm n (0 : R[X]) 0 := by + simp [BinaryForm] + +theorem BinaryForm.const (a : R) : BinaryForm 0 (C a) (C a) := by + simp [BinaryForm, reflect_C] + +theorem BinaryForm.mul {n m : ℕ} {a b p q : R[X]} (h : BinaryForm n a b) + (h' : BinaryForm m p q) : BinaryForm (n + m) (a * p) (b * q) := + ⟨natDegree_mul_le.trans (Nat.add_le_add h.1 h'.1), + by rw [reflect_mul a p h.1 h'.1, h.2, h'.2]⟩ + +theorem BinaryForm.pow {n : ℕ} {a b : R[X]} (h : BinaryForm n a b) (k : ℕ) : + BinaryForm (n * k) (a ^ k) (b ^ k) := by + induction k with + | zero => simpa using BinaryForm.const (1 : R) + | succ k ih => simpa [mul_add, pow_succ] using ih.mul h + +theorem wick_form (k l : A × Mode r → A × Mode r → R[X]) (m : ℕ) + (h : ∀ x y, BinaryForm (m * (x.2.2 + y.2.2 + 1)) (k x y) (l x y)) (xs : List (A × Mode r)) : + BinaryForm (m * (weight xs / 2)) (wick k xs) (wick l xs) := by + refine wick_graded (fun n => BinaryForm (m * n)) (fun _ => BinaryForm.zero _) + (by simpa using BinaryForm.const (1 : R)) ?_ ?_ k l h xs + · intro n x y z w h₁ h₂ + exact ⟨(natDegree_sub_le x z).trans (max_le h₁.1 h₂.1), + by rw [reflect_sub, h₁.2, h₂.2]⟩ + · intro n p x y z w h₁ h₂ + rw [mul_add] + exact h₁.mul h₂ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Ordered wedge coordinates + +Adjacent swaps contribute minus signs. Vanishing on repeated generators is a +separate condition so normalization is valid also in characteristic two. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +/-- The subtype of `x : List (Mode r)` satisfying `x.Pairwise (fun a b => toLex a < toLex b)`. -/ +def Wedge (r : ℕ) := {x : List (Mode r) // x.Pairwise (fun a b => toLex a < toLex b)} + +variable {R : Type*} [CommRing R] {r : ℕ} + +/-- Every mode contributes an odd amount of doubled energy. -/ +theorem energy_mod_two (x : List (Mode r)) : energy x % 2 = x.length % 2 := by + induction x with + | nil => rfl + | cons a x ih => + change (2 * a.2 + 1 + energy x) % 2 = (x.length + 1) % 2 + omega + +theorem Wedge.nodup (w : Wedge r) : w.val.Nodup := + w.property.imp (fun h h' => (ne_of_lt h) (congrArg toLex h')) + +/-- Requires `(∀ p x y s, φ (p ++ x :: y :: s) = -φ (p ++ y :: x :: s)) ∧ (∀ p q s x, φ (p ++ x +:: (q ++ x :: s)) = 0)`. -/ +def Alternates (φ : List (Mode r) → R) : Prop := + (∀ p x y s, φ (p ++ x :: y :: s) = -φ (p ++ y :: x :: s)) ∧ + (∀ p q s x, φ (p ++ x :: (q ++ x :: s)) = 0) + +private theorem Alternates.repeat {φ : List (Mode r) → R} (h : Alternates φ) + (x : List (Mode r)) (hx : ¬x.Nodup) (p : List (Mode r)) : φ (p ++ x) = 0 := by + induction x generalizing p with + | nil => exact (hx List.nodup_nil).elim + | cons a x ih => + by_cases ha : a ∈ x + · obtain ⟨q, s, rfl⟩ := List.append_of_mem ha + exact h.2 p q s a + · simpa using ih (fun ht => hx (ht.cons ha)) (p ++ [a]) + +private theorem perm_sign {x y : List (Mode r)} (h : x.Perm y) : + ∃ c : R, ∀ φ : List (Mode r) → R, Alternates φ → ∀ p, φ (p ++ x) = c * φ (p ++ y) := by + induction h with + | nil => exact ⟨1, fun _ _ _ => (one_mul _).symm⟩ + | cons a _ ih => + obtain ⟨c, hc⟩ := ih + exact ⟨c, fun φ hφ p => by simpa using hc φ hφ (p ++ [a])⟩ + | swap a b s => + exact ⟨-1, fun φ hφ p => by rw [neg_one_mul, hφ.1 p b a s]⟩ + | trans _ _ ih ij => + obtain ⟨c, hc⟩ := ih + obtain ⟨d, hd⟩ := ij + exact ⟨c * d, fun φ hφ p => by rw [hc φ hφ, hd φ hφ, mul_assoc]⟩ + +/-- The same ordered basis coordinates work for every alternating evaluation. -/ +theorem normalize (R : Type*) [CommRing R] {r : ℕ} (x : List (Mode r)) : + ∃ A : Wedge r →₀ R, (∀ y ∈ A.support, x.Perm y.val) ∧ + ∀ φ : List (Mode r) → R, Alternates φ → + φ x = Finsupp.linearCombination R (fun y : Wedge r => φ y.val) A := by + classical + by_cases hx : x.Nodup + · let rel (a b : Mode r) := toLex a ≤ toLex b + have : Std.Total rel := ⟨fun _ _ => le_total _ _⟩ + have : IsTrans _ rel := ⟨fun _ _ _ => le_trans⟩ + have hp := (List.perm_insertionSort rel x).symm + let w : Wedge r := ⟨_, ((List.pairwise_insertionSort rel x).and (hp.nodup_iff.mp hx)).imp + (fun h => lt_of_le_of_ne h.1 (toLex.injective.ne h.2))⟩ + obtain ⟨c, hc⟩ := perm_sign (R := R) hp + refine ⟨Finsupp.single w c, ?_, ?_⟩ + · intro y hy + rw [Finset.mem_singleton.mp (Finsupp.support_single_subset hy)] + exact hp + · intro φ hφ + rw [Finsupp.linearCombination_single, smul_eq_mul] + exact hc φ hφ [] + · refine ⟨0, by simp, ?_⟩ + intro φ hφ + rw [map_zero] + exact hφ.repeat x hx [] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Factoring a Wick sum through an ordered wedge basis + +After contracting a partial matching inside a cluster, each remaining +row is a finite linear combination of the center rows. The coefficients +of the resulting ordered wedges are uniform in the exterior list. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {R α ι : Type*} [CommRing R] {r : ℕ} + +private theorem contract_mem (M : Submodule R (ι → R)) (f : α → R) (P : ι → List α → R) + (xs : List α) (h : ∀ ys : List α, ys.Sublist xs → ys.length + 1 = xs.length → + (fun i => P i ys) ∈ M) : + (fun i => contract f (P i) xs) ∈ M := by + induction xs generalizing P with + | nil => exact M.zero_mem + | cons x xs ih => + have hc := ih (fun i s => P i (x :: s)) + (fun ys hy he => h (x :: ys) (hy.cons_cons x) (by simp [he])) + exact M.sub_mem (M.smul_mem (f x) (h xs (by simp) rfl)) hc + +theorem partial_mem (M : Submodule R (ι → R)) (k : α → α → R) (P : ι → List α → R) + (xs : List α) (h : ∀ ys : List α, ys.Sublist xs → (fun i => P i ys) ∈ M) : + (fun i => partialWick k (P i) xs) ∈ M := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs P with + | ind n ih => + cases xs with + | nil => exact h [] (by simp) + | cons x xs => + simp only [List.length_cons] at hn + have hu := ih xs.length (by omega) (fun i s => P i (x :: s)) xs + (fun ys hy => h (x :: ys) (hy.cons_cons x)) rfl + have hc := contract_mem M (k x) (fun i => partialWick k (P i)) xs + (fun ys hy he => ih ys.length (by omega) P ys + (fun zs hz => h zs ((hz.trans hy).cons x)) rfl) + simp only [partialWick_cons] + exact M.add_mem hu hc + +variable {l : α → α → R} + +theorem alternates_map (skew : ∀ x y, l y x = -l x y) (diag : ∀ x, l x x = 0) + (c : Mode r → α) (ys : List α) : + Alternates (fun xs => wick l (xs.map c ++ ys)) := by + constructor + · intro p x y s + simpa using wick_swap skew (p.map c) (s.map c ++ ys) (c y) (c x) + · intro p q s x + simpa using wick_repeat skew diag (p.map c) (q.map c) (s.map c ++ ys) (c x) + +/-- A cluster in a kernel with an internal and a residual part factors +through finitely many basis wedges. Each spectator list may be chosen +after the coefficients have been fixed. -/ +theorem wick_factor (k : α → α → R) (skew : ∀ x y, l y x = -l x y) + (diag : ∀ x, l x x = 0) (c : Mode r → α) (xs : List α) + (rows : ∀ x ∈ xs, ∃ (s : Finset ℕ) (q : ℕ → R) (g : ℕ → Mode r), + ∀ y, l x y = ∑ i ∈ s, q i * l (c (g i)) y) : + ∃ v : Wedge r →₀ R, ∀ ys : List α, (∀ x y, y ∈ ys → k x y = 0) → + wick (fun x y => k x y + l x y) (xs ++ ys) = + ∑ z ∈ v.support, v z * wick l (z.val.map c ++ ys) := by + classical + let W (u : Wedge r) (ys : List α) := wick l (u.val.map c ++ ys) + let M := (Finsupp.linearCombination R W).range + have residual (s : List α) (hs : s ⊆ xs) (p : List (Mode r)) : + (fun ys => wick l (p.map c ++ s ++ ys)) ∈ M := by + induction s generalizing p with + | nil => + obtain ⟨v, _, hv⟩ := normalize R p + refine ⟨v, funext fun ys => ?_⟩ + simpa [W, Finsupp.linearCombination_apply, Finsupp.sum, Finset.sum_apply] + using (hv _ (alternates_map skew diag c ys)).symm + | cons x s ih => + obtain ⟨t, q, g, he⟩ := rows x (hs (by simp)) + have hs' : s ⊆ xs := fun y hy => hs (by simp [hy]) + have hv := M.sum_mem (fun i (_ : i ∈ t) => M.smul_mem (q i) (ih hs' (p ++ [g i]))) + convert hv using 1 + funext ys + simpa [Finset.sum_apply] using wick_linear skew he (p.map c) (s ++ ys) + obtain ⟨v, hv⟩ := partial_mem M k (fun ys s => wick l (s ++ ys)) xs + (fun s hs => residual s hs.subset []) + refine ⟨v, fun ys h => ?_⟩ + rw [wick_add_append k l xs ys h] + simpa [W, Finsupp.linearCombination_apply, Finsupp.sum, Finset.sum_apply] using + (congrFun hv ys).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Changing generators in a wedge + +The expansion in the ordered basis is independent of all spectator +insertions. It preserves length and respects additive energy bounds. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {R α β : Type*} [CommRing R] {r : ℕ} {k : α → α → R} + +theorem wick_alternates (skew : ∀ x y, k y x = -k x y) (diag : ∀ x, k x x = 0) + (label : Mode r → α) (a b : List α) : + Alternates (fun xs => wick k (a ++ xs.map label ++ b)) := by + constructor + · intro p x y s + simpa using wick_swap skew (a ++ p.map label) (s.map label ++ b) (label y) (label x) + · intro p q s x + simpa using wick_repeat skew diag (a ++ p.map label) (q.map label) (s.map label ++ b) (label x) + +theorem substitute_modes (skew : ∀ x y, k y x = -k x y) (diag : ∀ x, k x x = 0) + (source : β → α) (target : Mode r → α) (bound : β → ℕ) + (rows : ∀ x, ∃ (s : Finset ℕ) (q : ℕ → R) (g : ℕ → Mode r), + (∀ i ∈ s, 2 * (g i).2 + 1 ≤ bound x) ∧ + ∀ y, k (source x) y = ∑ i ∈ s, q i * k (target (g i)) y) + (xs : List β) (p : List (Mode r)) : + ∃ v : Wedge r →₀ R, + (∀ y ∈ v.support, energy y.val ≤ energy p + (xs.map bound).sum ∧ + y.val.length = p.length + xs.length) ∧ + ∀ a b : List α, wick k (a ++ p.map target ++ xs.map source ++ b) = + Finsupp.linearCombination R (fun y : Wedge r => wick k (a ++ y.val.map target ++ b)) v := by + classical + induction xs generalizing p with + | nil => + obtain ⟨v, hv, he⟩ := normalize R p + refine ⟨v, ?_, fun a b => ?_⟩ + · intro y hy + have h := (hv y hy).symm + exact ⟨(h.map (fun i => 2 * i.2 + 1)).sum_eq.le, h.length_eq⟩ + · simpa using he _ (wick_alternates skew diag target a b) + | cons x xs ih => + obtain ⟨s, q, g, hb, hrow⟩ := rows x + choose v hv he using fun i => ih (p ++ [g i]) + refine ⟨∑ i ∈ s, q i • v i, ?_, ?_⟩ + · intro y hy + rw [Finsupp.mem_support_iff, Finsupp.finsetSum_apply] at hy + obtain ⟨i, hi, hy⟩ := Finset.exists_ne_zero_of_sum_ne_zero hy + have hiy : y ∈ (v i).support := by + rw [Finsupp.mem_support_iff] + intro hy' + simp [hy'] at hy + obtain ⟨h₁, h₂⟩ := hv i y hiy + have := hb i hi + simp only [energy, List.map_append, List.sum_append, List.map_cons, List.map_nil, + List.sum_cons, List.sum_nil, List.length_append, List.length_cons, List.length_nil] + at h₁ h₂ ⊢ + omega + · intro a b + have hl := wick_linear skew hrow (a ++ p.map target) (xs.map source ++ b) + simp only [map_sum, map_smul, smul_eq_mul, ← he] + simpa using hl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- # Preparing a coefficient tensor at one auxiliary site -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor + +variable {F A : Type} [Field F] [Fintype A] [DecidableEq A] [Nonempty A] + +private theorem place_single (U : Tensor F A) (s : A ⊕ Unit) : + place (fun _ => s) U ≤ 1 := by + obtain ⟨n, hn⟩ := exists_bound U + have bound := place_mono (fun _ : A => s) (hn.trans (natCast_le (Nat.le_succ n))) + have hs : Finset.univ.image (fun _ : A => s) = {s, s} := by + ext t + simp [eq_comm] + rw [← shared_all F (n + 1), place_shared, hs, ← wire, wire_self F s (Nat.succ_pos n)] at bound + exact bound + +variable {g : Tensor F (A ⊕ Unit) →+* ℝ} + +theorem preparation (hg : Monotone g) (U : Raw F A) : + Real.log (g (pad Unit (ofRaw U))) ≤ + ∑ i, dist g (.inl i) (.inr ()) * Real.log (Fintype.card (U.leg i)) := by + by_cases h : ofRaw U = 0 + · rw [h, (padding Unit).zero, map_zero, Real.log_zero] + exact Finset.sum_nonneg fun i _ => mul_nonneg (dist_nonneg g hg _ _) (by positivity) + let p : A → A ⊕ Unit := fun _ => .inr () + have h0 := hg (place_single (ofRaw U) (.inr ())) + have hcost : Real.log (g (place p (ofRaw U))) ≤ 0 := + Real.log_nonpos (price_place_pos g hg p h).le (by simpa using h0) + have hs := (abs_sub_le_iff.mp (price_transport g hg U h Sum.inl p)).1 + rw [place_inl] at hs + exact (le_sub_iff_add_le.mpr (add_le_of_nonpos_right hcost)).trans hs + +/-- Sending all legs of a common binary label costs at least one bit. -/ +theorem preparation_lower (hg : Monotone g) {f : Tensor F A →+* ℝ} + (he : ∀ T, g (pad Unit T) = f T) : + 1 ≤ ∑ i, dist g (.inl i) (.inr ()) := by + have h := preparation hg (Raw.diag F A (Fin 2)) + rw [he, diag_fin, map_natCast] at h + change Real.log (2 : ℕ) ≤ ∑ i, dist g (.inl i) (.inr ()) * Real.log (Fintype.card (Fin 2)) at h + rw [Fintype.card_fin, ← Finset.sum_mul] at h + exact (le_mul_iff_one_le_left (Real.log_pos (by norm_num))).mp h + +end MatrixMultiplicationAllFields.MatrixExponent.Spectral.Tensor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Proof/Initial.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Proof/Initial.lean new file mode 100644 index 0000000000..8d33a52ae9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Proof/Initial.lean @@ -0,0 +1,853 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Group.Finset.Basic +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Data.Fintype.Sigma +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Choices +public import Mathlib.Algebra.BigOperators.GroupWithZero.Finset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Depth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Concentration.Kits +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Scalar.Term +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Local + +/-! +# Checking regional budgets using a bounded alphabet + +At every step a disjoint set of regions is active. We verify the +sum over each region separately. Truncating each energy to an integer +can cost one unit per cell per step. Choosing the precision one +greater than the number of steps absorbs the resulting error. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Finset + +variable {V : Type} [Fintype V] + +open scoped Classical in +/-- Selects the elements of all indices satisfying `fun w => p w = v`. -/ +def region (p : V → V) (v : V) := univ.filter fun w => p w = v + +open scoped Classical in +/-- The condition `∀ v, (∑ w ∈ region p v, b w) ≤ ∑ w ∈ region p v, (a w + loss)` on the +specified data. -/ +def Balanced (p : V → V) (loss : ℕ) (a b : V → ℕ) := + ∀ v, (∑ w ∈ region p v, b w) ≤ ∑ w ∈ region p v, (a w + loss) + +open scoped Classical in +theorem Balanced.total {p : V → V} {loss : ℕ} {a b : V → ℕ} (h : Balanced p loss a b) : + (∑ v, b v) ≤ (∑ v, a v) + Fintype.card V * loss := by + have he (f : V → ℕ) : (∑ v, ∑ w ∈ region p v, f w) = ∑ w, f w := by + simp only [region, sum_filter] + rw [sum_comm] + simp + have hr := sum_le_sum (fun v (_ : v ∈ univ) => h v) + rw [he, he, sum_add_distrib, sum_const, card_univ, Nat.nsmul_eq_mul] at hr + exact hr + +open scoped Classical in +/-- The quantity computed by `(n + 1) * x / unit`. -/ +def clip (n unit x : ℕ) := (n + 1) * x / unit + +open scoped Classical in +theorem clip_low (n u a : ℕ) : clip n u a * u ≤ (n + 1) * a := Nat.div_mul_le_self .. + +open scoped Classical in +theorem clip_high (n a : ℕ) {u : ℕ} (hu : 0 < u) : (n + 1) * a ≤ (clip n u a + 1) * u := + (Nat.lt_mul_div_succ _ hu).le.trans_eq (mul_comm ..) + +open scoped Classical in +theorem clip_mono (n u : ℕ) {a b : ℕ} (h : a ≤ b) : clip n u a ≤ clip n u b := + Nat.div_le_div_right (Nat.mul_le_mul_left _ h) + +open scoped Classical in +theorem clip_bound (n u x B : ℕ) (hu : 0 < u) (hx : x ≤ B * u) : clip n u x ≤ (n + 1) * B := by + apply Nat.le_of_mul_le_mul_right _ hu + rw [mul_assoc] + exact (clip_low n u x).trans (Nat.mul_le_mul_left _ hx) + +open scoped Classical in +theorem Balanced.clip {p : V → V} {a b : V → ℕ} (h : Balanced p 0 a b) + (n : ℕ) {u : ℕ} (hu : 0 < u) : Balanced p 1 (clip n u ∘ a) (clip n u ∘ b) := by + intro v + apply Nat.le_of_mul_le_mul_right _ hu + rw [sum_mul, sum_mul] + calc + _ ≤ ∑ w ∈ region p v, (n + 1) * b w := sum_le_sum (fun i _ => clip_low n u (b i)) + _ ≤ ∑ w ∈ region p v, (n + 1) * a w := by + rw [←mul_sum, ←mul_sum] + exact Nat.mul_le_mul_left _ (h v) + _ ≤ _ := sum_le_sum (fun i _ => clip_high n (a i) hu) + +open scoped Classical in +/-- The condition `∀ i : Fin n, Balanced (p i) loss (f i.castSucc) (f i.succ)` on the specified +data. -/ +def Admitted {n : ℕ} (p : Fin n → V → V) (loss : ℕ) (f : Fin (n + 1) → V → ℕ) := + ∀ i : Fin n, Balanced (p i) loss (f i.castSucc) (f i.succ) + +open scoped Classical in +theorem Admitted.total {n : ℕ} {p : Fin n → V → V} {loss : ℕ} {f : Fin (n + 1) → V → ℕ} + (h : Admitted p loss f) : + (∑ v, f (Fin.last n) v) ≤ (∑ v, f 0 v) + n * (Fintype.card V * loss) := by + suffices ∀ i : Fin (n + 1), (∑ v, f i v) ≤ (∑ v, f 0 v) + + i.val * (Fintype.card V * loss) from this _ + intro i + induction i using Fin.induction with + | zero => simp + | succ i ih => + rw [Fin.val_succ, Nat.succ_mul, ←add_assoc] + exact (h i).total.trans (Nat.add_le_add_right ih _) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +/- +# Adding a unique certificate without division + +The visible check can admit more than one certificate. The dictionary +assigns weight zero at a cell where its guessed data differ from the +actual local data. Consequently a genuine term occurs exactly once. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Finset Transcript +variable {I J V C F : Type} [Fintype I] [Fintype J] [Fintype V] [Fintype C] + +open scoped Classical in +/-- Indexes the candidate by the coordinates of `Σ j, {c // ok j c}`. -/ +abbrev Candidate (ok : J → (V → C) → Prop) := Σ j, {c // ok j c} + +variable (s : Selector I J) (actual : J → V → C) (ok : J → (V → C) → Prop) + (valid : ∀ i, ok (s.write i) (actual (s.write i))) + +open scoped Classical in +/-- Uses `⟨s.write i, actual (s.write i), valid i⟩` as the representation. -/ +def genuine (i : I) : Candidate ok := ⟨s.write i, actual (s.write i), valid i⟩ + +open scoped Classical in +/-- Builds `Selector I (Candidate ok) where write` with the specified `write`, `read`, `valid`, +`obtain`. -/ +def checkedSelector : Selector I (Candidate ok) where + write := genuine s actual ok valid + read v := if v.2.val = actual v.1 then s.read v.1 else none + valid v i := by + obtain ⟨j, c, h⟩ := v + constructor + · split_ifs with he + · intro h' + change c = actual j at he + have eq : j = s.write i := (s.valid _ _).mp h' + subst j c + rfl + · simp + · intro eq + have hj := congrArg Sigma.fst eq + have hc := congrArg (fun x : Candidate ok => x.2.val) eq + change j = s.write i at hj + change c = actual (s.write i) at hc + subst j c + exact (ite_eq_left rfl).trans ((s.valid _ i).mpr rfl) + +variable [CommSemiring F] (weight : J → V → F) (coeff : I → F) + (hw : ∀ j, ∏ v, weight j v = (s.read j).elim 0 coeff) + +open scoped Classical in +/-- Returns `weight x.1 v` when `x.2.val v = actual x.1 v` holds, and `0` otherwise. -/ +def factor (x : Candidate ok) (v : V) := if x.2.val v = actual x.1 v then weight x.1 v else 0 + +omit [Fintype I] [Fintype J] [Fintype C] in +include hw in +open scoped Classical in +theorem checked_weight (x : Candidate ok) : + (∏ v, factor actual ok weight x v) = ((checkedSelector s actual ok valid).read x).elim 0 coeff + := by + by_cases he : x.2.val = actual x.1 + · simp only [factor, checkedSelector, he, ↓reduceIte, hw] + · simp only [checkedSelector, ite_eq_right he, Option.elim_none] + obtain ⟨i, hi⟩ := Function.ne_iff.mp he + exact prod_eq_zero (mem_univ i) (ite_eq_right hi) + +include hw in +open scoped Classical in +theorem checked_sum (eval : Candidate ok → F) (src : I → F) + (he : ∀ i, eval (genuine s actual ok valid i) = src i) : + ∑ x : Candidate ok, (∏ v, factor actual ok weight x v) * eval x = ∑ i, coeff i * src i := by + let t := checkedSelector s actual ok valid + rw [←t.sum (fun i => coeff i * src i)] + apply sum_congr rfl + intro x _ + rw [checked_weight s actual ok valid weight coeff hw x] + change (t.read x).elim 0 coeff * eval x = _ + cases h : t.read x with + | none => simp + | some i => + have hx : x = genuine s actual ok valid i := (t.valid x i).mp h + rw [hx, he] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +/- # Bounded integers for the per-cell energy and motion accounts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset SphereScale Routing.Private + +variable {F K : Type} [Field F] [Field K] [Algebra K F] + {x y : Wire} {h D T b d g ℓ m : ℕ} {W ε : ℝ} (P : Input F x y h D T (d * b) g W) + (p : P.Kits K m (probes ℓ D) ε) (s : P.Occupied → Shape (probes ℓ D) b d) + (sc : Scales g ℓ D T m b d) + {z : Stage F (d * b) d P.diagram.V P.Occupied P.grid.Seam (P.Parameters p)} + (hz : (P.plant p s).Reach m (2 * g) (SphereScale.energy ℓ D (d * b)) (D ^ 5) z) + +local notation "H" => SphereScale.energy ℓ D (d * b) +local notation "N" => depth ℓ D g m (d * b) +local notation "M" => room ℓ D g + +include sc hz in +open scoped Classical in +theorem credit_site (v : P.Occupied) : + z.energyCre m H (2 * g) v + (∑ e ∈ z.edges v, (z.ledger m H).seam e) ≤ N := by + have h := hz.budget.site v + have hi := (mul_le_mul_of_nonneg_left (P.plant_local_energy p s sc.Rpos H v) + (Nat.cast_nonneg (1 + 4 * g))).trans sc.initial_bound + let I := (P.plant p s).ledger m H + have ht : (1 + 4 * g) * (I.mobile v + I.collected v + ∑ e ∈ (P.plant p s).edges v, I.seam e) ≤ N + := + (Nat.cast_le (α := ℝ)).mp (by rw [Nat.cast_mul]; exact hi) + have aux (a b c k : ℕ) : (1 + k) * a + b + (1 + k) * c ≤ (1 + k) * (a + b + c) + := by ring_nf; omega + rw [show 4 * g = 2 * (2 * g) by omega] at ht + rw [hz.edges_eq] + exact (Nat.add_le_add_left (Nat.le_mul_of_pos_left _ (by omega : 0 < 1 + 2 * (2 * g))) _).trans + (h.trans ((aux ..).trans ht)) + +include sc hz in +open scoped Classical in +theorem seam_credit (v : P.Occupied) : + (∑ e ∈ z.edges v, (z.ledger m H).seam e / (2 * m * H)) ≤ budget g * D ^ 2 := by + have hm := sc.pos + have hH := sc.Hpos + apply Nat.le_of_mul_le_mul_right _ (by positivity : 0 < 2 * m * H) + rw [sum_mul] + refine (sum_le_sum (fun i _ => Nat.div_mul_le_self ..)).trans ?_ + have h := P.credit_site p s sc hz v + refine (Nat.le_add_left ..).trans (h.trans ?_) + unfold depth + rw [mul_assoc (budget g * D ^ 2)] + gcongr + omega + +open scoped Classical in +private theorem tally_limit {α : Type} (ls : List α) (f : α → ℕ) (b : ℕ) + (h : ∀ v ∈ ls, f v ≤ b) : (ls.map f).sum ≤ ls.length * b := by + induction ls with + | nil => simp + | cons a l ih => + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.succ_mul] + have tail : ∀ v ∈ l, f v ≤ b := fun v hv => h v (.tail _ hv) + exact (Nat.add_le_add (h _ (by simp)) (ih tail)).trans_eq (add_comm ..) + +open scoped Classical in +/-- The quantity computed by `(n + 1) * (budget g * D ^ 2)`. -/ +def energyLimit (g D n : ℕ) := (n + 1) * (budget g * D ^ 2) +open scoped Classical in +/-- The quantity computed by `2 * room ℓ D g * D ^ 5 + budget g * D ^ 2`. -/ +def timeLimit (g ℓ D : ℕ) := 2 * room ℓ D g * D ^ 5 + budget g * D ^ 2 + +include sc hz in +open scoped Classical in +theorem credit_limits (hv : z.Valid (D ^ 5)) (n : ℕ) (v : P.Occupied) : + Geometry.clip n (m * H) (z.energyCre m H (2 * g) v) ≤ energyLimit g D n ∧ + z.timeCre m H (D ^ 5) v ≤ timeLimit g ℓ D := by + have he := P.credit_site p s sc hz v + have hlen := (P.moved_room p s sc hz).length v + refine ⟨Geometry.clip_bound _ _ _ _ (Nat.mul_pos sc.pos sc.Hpos) ?_, ?_⟩ + · rw [←mul_assoc] + exact (Nat.le_add_right ..).trans he + · have ht : z.tally m (fun c _ => c.clock) v ≤ M * D ^ 5 := + (tally_limit _ _ _ (hv.bound v)).trans (Nat.mul_le_mul_right _ hlen) + have hc : z.tally m Stage.collectorUnit v ≤ M := by + have h : ∀ a : Role, a.collected 1 ≤ 1 := by intro a; cases a <;> simp [Role.collected] + exact (tally_limit _ _ 1 (fun i _ => h i.label.role)).trans ((mul_one _).le.trans hlen) + unfold Stage.timeCre timeLimit + rw [two_mul M, add_mul M M, mul_comm (D ^ 5)] + exact Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_right _ hc) ht) (P.seam_credit p s sc hz v) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# Integer checks for a proposed layout + +The spectrum argument supplies true branches with potentially +complicated weights. The structural checks below take only integer +data of bounded size. The number of steps sets the precision. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Rounds Finset +variable {V : Type} [Fintype V] {g ℓ D n : ℕ} + +open scoped Classical in +/-- Indexes the credits by the coordinates of `Fin (n + 1) → Fin (Input.energyLimit g D n + 1) × +Fin (Input.timeLimit g ℓ D + 1)`. -/ +abbrev Credits (g ℓ D n : ℕ) := + Fin (n + 1) → Fin (Input.energyLimit g D n + 1) × Fin (Input.timeLimit g ℓ D + 1) + +namespace Credits + +open scoped Classical in +/-- The value specified by `(z i).1.val`. -/ +def power (z : Credits g ℓ D n) (i : Fin (n + 1)) := (z i).1.val +open scoped Classical in +/-- The value specified by `(z i).2.val`. -/ +def time (z : Credits g ℓ D n) (i : Fin (n + 1)) := (z i).2.val + +open scoped Classical in +/-- The canonical choice. A value out of range is interpreted modulo +the alphabet size, which matters only off the support of an expansion. -/ +def issue (g ℓ D n : ℕ) (unit : ℕ) (a b : Fin (n + 1) → ℕ) : Credits g ℓ D n := fun i => + (Fin.ofNat _ (clip n unit (a i)), Fin.ofNat _ (b i)) + +open scoped Classical in +theorem issue_power (unit : ℕ) (a b : Fin (n + 1) → ℕ) (i : Fin (n + 1)) + (h : clip n unit (a i) ≤ Input.energyLimit g D n) : + (issue g ℓ D n unit a b).power i = clip n unit (a i) := Nat.mod_eq_of_lt (Nat.lt_succ_of_le h) + +open scoped Classical in +theorem issue_time (unit : ℕ) (a b : Fin (n + 1) → ℕ) (i : Fin (n + 1)) + (h : b i ≤ Input.timeLimit g ℓ D) : + (issue g ℓ D n unit a b).time i = b i := Nat.mod_eq_of_lt (Nat.lt_succ_of_le h) + +open scoped Classical in +/-- The data for the check construction, including `initial`, `power`, `time`. -/ +structure Check (p : Fin n → V → V) (z : V → Credits g ℓ D n) (E M : V → ℕ) : Prop where + initial : ∀ v, (z v).power 0 ≤ E v ∧ (z v).time 0 ≤ M v + power : Admitted p 1 (fun i v => (z v).power i) + time : Admitted p 0 (fun i v => (z v).time i) + +open scoped Classical in +theorem check_issue {p : Fin n → V → V} {a b : V → Fin (n + 1) → ℕ} {E M : V → ℕ} + (unit : ℕ) (hu : 0 < unit) (start : ∀ v, clip n unit (a v 0) ≤ E v ∧ b v 0 ≤ M v) + (ha : Admitted p 0 fun i v => a v i) (hb : Admitted p 0 fun i v => b v i) + (h : ∀ v i, clip n unit (a v i) ≤ Input.energyLimit g D n ∧ b v i ≤ Input.timeLimit g ℓ D) : + Check p (fun v => issue g ℓ D n unit (a v) (b v)) E M := by + have hx v i := issue_power (ℓ := ℓ) unit (a v) (b v) i (h v i).1 + have hy v i := issue_time unit (a v) (b v) i (h v i).2 + constructor + · simpa only [hx, hy] using start + · simp only [hx] + exact fun i => (ha i).clip n hu + · simpa only [hy] using hb + +open scoped Classical in +theorem Check.final {p : Fin n → V → V} {z : V → Credits g ℓ D n} {E M : V → ℕ} + (h : Check p z E M) : + (∑ v, (z v).power (Fin.last n)) ≤ (∑ v, E v) + n * Fintype.card V ∧ + (∑ v, (z v).time (Fin.last n)) ≤ ∑ v, M v := by + have ha := h.power.total + have hb := h.time.total + simp only [mul_one, mul_zero, add_zero] at ha hb + exact ⟨ha.trans (Nat.add_le_add_right (sum_le_sum fun i _ => (h.initial i).1) _), + hb.trans (sum_le_sum fun i _ => (h.initial i).2)⟩ + +end Credits +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +/- +# Initial credits computed from packet sizes and immobility + +The allowance is independent of the shape chosen by a selector. The +global bounds charge the possible initial station energies to their +squared packet widths and each collector to its occupied cell. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface SphereScale Finset Routing.Private + +variable {F K : Type} [Field F] [Field K] [Algebra K F] + {x y : Wire} {h D T b d g ℓ m : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) + +local notation "H" => SphereScale.energy ℓ D (d * b) +local notation "A" => SphereScale.size ℓ D + +open scoped Classical in +/-- The sum of `(d * b) * (8 * P.grid.width v (Fin.castAdd _ j) ^ 2)` indexed by `j : Fin +(P.grid.stations v).card`. -/ +def packetEnergy (v : P.Occupied) := + ∑ j : Fin (P.grid.stations v).card, (d * b) * (8 * P.grid.width v (Fin.castAdd _ j) ^ 2) + +open scoped Classical in +/-- The quantity computed by `(1 + 4 * g) * (reserve D b d (probes ℓ D) m (SphereScale.energy ℓ +D (d * b)) + m * P.packetEnergy v)`. -/ +def initialPacketCredit (ℓ m : ℕ) (v : P.Occupied) := + (1 + 4 * g) * (reserve D b d (probes ℓ D) m (SphereScale.energy ℓ D (d * b)) + + m * P.packetEnergy v) + +open scoped Classical in +/-- The quantity computed by `Geometry.clip n (m * SphereScale.energy ℓ D (d * b)) +(P.initialPacketCredit ℓ m v)`. -/ +def initialEnergyTokens (ℓ m n : ℕ) (v : P.Occupied) := + Geometry.clip n (m * SphereScale.energy ℓ D (d * b)) (P.initialPacketCredit ℓ m v) + +open scoped Classical in +/-- The quantity computed by `D ^ 5 * P.collectorCount v + budget g * D ^ 2`. -/ +def initialTimeTokens (v : P.Occupied) := + D ^ 5 * P.collectorCount v + budget g * D ^ 2 + +variable (p : P.Kits K m (probes ℓ D) ε) (s : P.Occupied → Shape (probes ℓ D) b d) + (sc : Scales g ℓ D T m b d) + +open scoped Classical in +theorem initial_energy_fits (n : ℕ) (v : P.Occupied) : + Geometry.clip n (m * H) ((P.plant p s).energyCre m H (2 * g) v) ≤ + P.initialEnergyTokens ℓ m n v := by + let z := (P.plant p s).ledger m H + have hsum : z.mobile v + z.collected v ≤ reserve D b d (probes ℓ D) m H + m * P.packetEnergy v := + P.initial_sum p s H v + have h : (P.plant p s).energyCre m H (2 * g) v ≤ P.initialPacketCredit ℓ m v := calc + _ = (1 + 4 * g) * z.mobile v + z.collected v := by + unfold Stage.energyCre Ledger.cost z + ring_nf + _ ≤ (1 + 4 * g) * (z.mobile v + z.collected v) := by + rw [mul_add] + exact Nat.add_le_add_left (Nat.le_mul_of_pos_left _ (by omega)) _ + _ ≤ _ := Nat.mul_le_mul_left _ hsum + unfold initialEnergyTokens Geometry.clip + exact Nat.div_le_div_right (Nat.mul_le_mul_left _ h) + +include sc in +open scoped Classical in +theorem initial_time_fits (v : P.Occupied) : + (P.plant p s).timeCre m H (D ^ 5) v ≤ P.initialTimeTokens v := by + let z := P.plant p s + have hz : z.tally m (fun c _ => c.clock) v = 0 := by + apply Nat.eq_zero_of_le_zero + calc + _ ≤ (z.ledger m H).clock := single_le_sum (fun a _ => Nat.zero_le _) (mem_univ v) + _ = 0 := P.plant_zero p s H + have hs : (∑ e ∈ z.edges v, (z.ledger m H).seam e) ≤ budget g * D ^ 2 * m * H := by + have h := P.plant_local_energy p s sc.Rpos H v + have hr := sc.initial_bound + have ha : ((∑ e ∈ z.edges v, (z.ledger m H).seam e : ℕ) : ℝ) ≤ + Input.initialEnergy D T b d (probes ℓ D) m H := by + exact (Nat.cast_le.mpr (Nat.le_add_left ..)).trans h + have hb : (1 : ℝ) ≤ (1 + 4 * g : ℕ) := by exact_mod_cast (show 1 ≤ 1 + 4 * g by omega) + have hb' := le_mul_of_one_le_left + (show 0 ≤ Input.initialEnergy D T b d (probes ℓ D) m H by + unfold Input.initialEnergy; positivity) hb + exact_mod_cast ha.trans (hb'.trans hr) + have hm : 0 < m * H := Nat.mul_pos sc.pos sc.Hpos + have he : (∑ e ∈ z.edges v, (z.ledger m H).seam e / (2 * m * H)) ≤ budget g * D ^ 2 := by + apply Nat.le_of_mul_le_mul_right _ hm + rw [sum_mul] + have aux (e : P.grid.Seam) : + (z.ledger m H).seam e / (2 * m * H) * (m * H) ≤ (z.ledger m H).seam e := + (Nat.mul_le_mul_left _ (by rw [mul_assoc]; exact Nat.le_mul_of_pos_left _ (by decide))).trans + (Nat.div_mul_le_self ..) + exact (sum_le_sum fun e _ => aux e).trans (hs.trans_eq (mul_assoc ..)) + unfold Stage.timeCre initialTimeTokens + change D ^ 5 * z.tally m (fun c _ => c.collected 1) v + z.tally m (fun c _ => c.clock) v + + (∑ e ∈ z.edges v, (z.ledger m H).seam e / (2 * m * H)) ≤ _ + rw [P.plant_collector_cell p s m, hz, add_zero] + exact Nat.add_le_add_left he _ + +include sc in +omit [Field F] in +open scoped Classical in +theorem initial_energy_total (n : ℕ) : + ((∑ v, P.initialEnergyTokens ℓ m n v : ℕ) : ℝ) * T ≤ 2 * budget g * ((n : ℝ) + 1) * W := by + let E := P.initialEnergyTokens ℓ m n + let raw := P.initialPacketCredit ℓ m + have hn : (Fintype.card P.Occupied : ℝ) * D * T ≤ W := by + simpa only [Occupied, Fintype.card_coe] using P.occupied + have hW := (by positivity : (0 : ℝ) ≤ (Fintype.card P.Occupied : ℝ) * D * T).trans hn + have hsum : (∑ v, raw v) = + (1 + 4 * g) * (Fintype.card P.Occupied * reserve D b d (probes ℓ D) m H + m*∑ v, + P.packetEnergy v) := by + simp only [raw, initialPacketCredit, ←mul_sum, sum_add_distrib, sum_const, card_univ, + Nat.nsmul_eq_mul] + have hraw : ((∑ v, raw v : ℕ) : ℝ) ≤ budget g * (m : ℝ) * A * W := calc + _ = ((1 + 4 * g : ℕ) : ℝ) * ((Fintype.card P.Occupied : ℝ) * reserve D b d (probes ℓ D) m H + + (m : ℝ) * (∑ v, (P.packetEnergy v : ℝ))) := by rw [hsum]; push_cast; ring + _ ≤ ((1 + 4 * g : ℕ) : ℝ) * ((Fintype.card P.Occupied : ℝ) * reserve D b d (probes ℓ D) m H + + (m : ℝ) * (8 * W * T / (d * b : ℕ))) := by + apply mul_le_mul_of_nonneg_left _ (by positivity) + apply add_le_add le_rfl + apply mul_le_mul_of_nonneg_left _ (by positivity) + simpa only [packetEnergy, Nat.cast_sum] using P.station_energy sc.Rpos + _ ≤ _ := sc.global_bound _ W hn + have round : (∑ v, E v) * (m * H) ≤ (n + 1) * (∑ v, raw v) := by + rw [sum_mul, mul_sum] + exact sum_le_sum fun v _ => Geometry.clip_low n (m * H) (raw v) + have hdv : ((∑ v, E v : ℕ) : ℝ) * ((m : ℝ) * H) ≤ ((n : ℝ) + 1) * ((∑ v, raw v : ℕ) : ℝ) := by + exact_mod_cast round + have hclip := hdv.trans (mul_le_mul_of_nonneg_left hraw (show (0 : ℝ) ≤ (n : ℝ) + + 1 by positivity)) + have ht : (A : ℝ) * T ≤ 2 * (H : ℝ) := calc + _ ≤ (A : ℝ) * (2 * (d * b * A) : ℕ) := + mul_le_mul_of_nonneg_left (Nat.cast_le.mpr sc.upper) (by positivity) + _ = _ := by unfold SphereScale.energy; push_cast; ring + apply le_of_mul_le_mul_right _ (mul_pos (Nat.cast_pos.mpr sc.pos) (Nat.cast_pos.mpr sc.Hpos)) + calc + _ = (((∑ v, E v : ℕ) : ℝ) * ((m : ℝ) * H)) * T := by ring + _ ≤ (((n : ℝ) + 1) * (budget g * (m : ℝ) * A * W)) * T := + mul_le_mul_of_nonneg_right hclip (by positivity) + _ = (budget g * ((n : ℝ) + 1) * W * (m : ℝ)) * ((A : ℝ) * T) := by ring + _ ≤ (budget g * ((n : ℝ) + 1) * W * (m : ℝ)) * (2 * H) := + mul_le_mul_of_nonneg_left ht (by positivity) + _ = _ := by ring + +include p s sc in +open scoped Classical in +theorem initial_time_total : + ((∑ v, P.initialTimeTokens v : ℕ) : ℝ) * D * T ≤ 3 * (D : ℝ) ^ 5 * W := by + have ht : budget g * D ^ 2 ≤ D ^ 5 := calc + _ ≤ D * D ^ 2 := Nat.mul_le_mul_right _ (by have := sc.large; omega) + _ = D ^ 3 := (pow_succ' D 2).symm + _ ≤ _ := Nat.pow_le_pow_right sc.Dpos (by decide) + have hn : (Fintype.card P.Occupied : ℝ) * D * T ≤ W := by + simpa only [Occupied, Fintype.card_coe] using P.occupied + have hc : (∑ v, P.collectorCount v) = (P.plant p s).collectors := by + unfold Stage.collectors + apply sum_congr rfl + intro v _ + exact (P.plant_collector_cell p s 0 v).symm + have htotal : (∑ v, P.initialTimeTokens v) ≤ + D ^ 5 * (2 * Fintype.card P.Occupied + Fintype.card {v // ¬P.mobile v}) := calc + _ ≤ ∑ v : P.Occupied, (D ^ 5 * P.collectorCount v + D ^ 5) := by + unfold initialTimeTokens + exact sum_le_sum fun v _ => Nat.add_le_add_left ht _ + _ = _ := by + rw [sum_add_distrib, ←mul_sum, hc, P.plant_collectors] + simp only [sum_const, card_univ, Nat.nsmul_eq_mul] + ring + calc + _ ≤ ((D ^ 5 * (2 * Fintype.card P.Occupied + Fintype.card {v // ¬P.mobile v}) : ℕ) : ℝ) * D * T + := + mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right (Nat.cast_le.mpr htotal) (by + positivity)) (by positivity) + _ = (D : ℝ) ^ 5 * (2 * ((Fintype.card P.Occupied : ℝ) * D * T)+ + (Fintype.card {v // ¬P.mobile v} : ℝ) * D * T) := by push_cast; ring + _ ≤ (D : ℝ) ^ 5 * (2 * W + W) := mul_le_mul_of_nonneg_left + (add_le_add (mul_le_mul_of_nonneg_left hn (by norm_num)) P.immobile) (by positivity) + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# A finite local check for output arities + +Internal span lengths are multiples of a common unit. The integer +threshold is the scale divided by this unit, rounded down. It stays +bounded when the scale grows. Exterior lengths pass through unchanged. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Rounds Coloring Finset + +variable {g ℓ D n w d e k : ℕ} + +open scoped Classical in +/-- The data for the quota construction, including `count`, `square`, `mobile`, `large`, +`small`. -/ +structure Quota (C h K : ℕ) (fixed : B w → Bool) (a : Blueprint w d e k) (c : Credits g ℓ D n) : + Prop where + count : D ^ 5 * a.count fixed ≤ c.time (Fin.last n) + square : (n + 1) * a.square fixed ≤ 512 * (D * (n + 1) + c.power (Fin.last n) + 1) * K ^ 2 + mobile : a.mobile fixed ≤ 2 * C * (1 + a.count fixed) * D * (1 + h) ^ 2 * K + large : ∀ i, fixed i = true → (a i).toll ≤ 2 * C * D * K + small : ∀ i, fixed i = false → (a i).toll * D ^ ℓ ≤ K + +open scoped Classical in +private theorem scale_le (u T : ℕ) (hu : 0 < u) (h : u ≤ T) : T ≤ 2 * (T / u) * u := by + have pos : 0 < T / u := Nat.div_pos h hu + have he := Nat.lt_mul_div_succ T hu + exact he.le.trans ((Nat.mul_le_mul_left u (show T / u + 1 + ≤ 2 * (T / u) by omega)).trans_eq (mul_comm ..)) + +open scoped Classical in +private theorem square_high (R f u K T n D y E : ℝ) + (hf : 0 < f) (hT : 0 ≤ T) (hu : 0 < u) (hn : 0 ≤ n) (hD : 0 ≤ D) (hy : 0 ≤ y) + (hK : T ≤ 2 * K * u) (he : (n + 1) * E ≤ (y + 1) * (f * T)) + (hs : R * u ^ 2 ≤ 128 * (T * E / f + D * T ^ 2)) : + (n + 1) * R ≤ 512 * (D * (n + 1) + y + 1) * K ^ 2 := by + have ha : (n + 1) * (T * E / f) ≤ (y + 1) * T ^ 2 := by + rw [← mul_div_assoc, div_le_iff₀ hf] + convert mul_le_mul_of_nonneg_left he hT using 1 <;> ring + apply le_of_mul_le_mul_right _ (sq_pos_of_pos hu) + calc + _ ≤ (n + 1) * (128 * (T * E / f + D * T ^ 2)) := by rw [mul_assoc]; gcongr + _ ≤ 128 * (D * (n + 1) + y + 1) * T ^ 2 := by linarith only [ha] + _ ≤ 128 * (D * (n + 1) + y + 1) * (2 * K * u) ^ 2 := by gcongr + _ = _ := by ring + +open scoped Classical in +theorem Quota.make {T b l m u C h E : ℕ} (sc : SphereScale.Scales g ℓ D T m b l) + (fixed : B w → Bool) (a : Blueprint w d e k) (c : Credits g ℓ D n) + (hu : 0 < u) (ht : u ≤ T) (hE : clip n (m * SphereScale.energy ℓ D (l * b)) E + ≤ c.power (Fin.last n)) + (count : D ^ 5 * a.count fixed ≤ c.time (Fin.last n)) + (square : (a.square fixed : ℝ) * u ^ 2 ≤ 128 * ((T : ℝ) * E / ((m : ℝ) * SphereScale.size ℓ D) + + D * (T : ℝ) ^ 2)) + (mobile : a.mobile fixed * u ≤ C * (1 + a.count fixed) * D * T * (1 + h) ^ 2) + (large : ∀ i, fixed i = true → (a i).toll * u ≤ C * D * T) + (small : ∀ i, fixed i = false → (a i).toll * u * D ^ ℓ ≤ T) : + Quota C h (T / u) fixed a c := by + let K := T / u + have hh : T ≤ 2 * K * u := scale_le u T hu ht + have he : (n + 1) * E ≤ (c.power (Fin.last n) + 1) * ((m * SphereScale.size ℓ D) * T) := by + refine (clip_high n E (Nat.mul_pos sc.pos sc.Hpos)).trans (Nat.mul_le_mul (Nat.succ_le_succ hE) + ?_) + rw [mul_assoc, mul_comm (SphereScale.size ℓ D)] + exact Nat.mul_le_mul_left _ sc.smallH + refine ⟨count, ?_, ?_, ?_, ?_⟩ + · have hf : 0 < (m : ℝ) * SphereScale.size ℓ D := + mul_pos (Nat.cast_pos.mpr sc.pos) (Nat.cast_pos.mpr sc.apos) + change (n + 1) * a.square fixed ≤ 512 * (D * (n + 1) + c.power (Fin.last n) + 1) * K ^ 2 + exact_mod_cast square_high (a.square fixed) _ u K T n D (c.power (Fin.last n)) E + hf (by positivity) (Nat.cast_pos.mpr hu) (by positivity) (by positivity) (by positivity) + (by exact_mod_cast hh) (by exact_mod_cast he) square + · apply Nat.le_of_mul_le_mul_right _ hu + apply mobile.trans + refine (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ hh)).trans_eq ?_ + unfold K + ring + · intro i hi + apply Nat.le_of_mul_le_mul_right _ hu + exact (large i hi).trans ((Nat.mul_le_mul_left _ hh).trans_eq (by unfold K; ring)) + · intro i hi + rw [Nat.le_div_iff_mul_le hu, mul_right_comm] + exact small i hi + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +/- # Charging active positions of an independently proposed layout -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Rounds Coloring Packing +variable {F : Type} {x y : Wire} {h w d e k u : ℕ} + +open scoped Classical in +/-- The data for the support construction, including `addr`, `live`, `frozen`, `charge`. -/ +structure Support (V : Type) (a : V → Blueprint w d e k) (fixed : V → B w → Bool) + (Q : LocalTerm F x y h u) where + /-- Embeds the coordinates as `Q.diagram.V ↪ V × B w`. -/ + addr : Q.diagram.V ↪ V × B w + live : ∀ i, (a (addr i).1 (addr i).2).live = true + frozen : ∀ i, Q.freeze.frozen i ↔ fixed (addr i).1 (addr i).2 = true + charge : ∀ i, Q.charge i = ((a (addr i).1 (addr i).2).toll : ℝ) * u + + Fintype.card {q // portEnd Q.diagram q = i} + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +/- # Pushing the counts and internal arities to the proposed slots -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry.Support +open Rounds Coloring Packing Finset + +open scoped Classical in +private theorem sum_injection {A B : Type} [Fintype A] [Fintype B] + (f : A ↪ B) (g : B → ℝ) (h : ∀ i, 0 ≤ g i) : + (∑ i, g (f i)) ≤ ∑ j, g j := by + rw [← sum_map univ f g] + exact sum_le_sum_of_subset_of_nonneg (subset_univ _) (fun i _ _ => h i) + +variable {F V : Type} [Fintype V] {x y : Wire} {h w d e k u : ℕ} + {a : V → Blueprint w d e k} {fixed : V → B w → Bool} {Q : LocalTerm F x y h u} + (H : Support V a fixed Q) + +open scoped Classical in +/-- Computes the cell tag by the application `a (H.addr v).1 (H.addr v).2`. -/ +abbrev cellTag (v : Q.diagram.V) := a (H.addr v).1 (H.addr v).2 + +open scoped Classical in +private theorem lift (p : Q.diagram.V → Prop) [DecidablePred p] (b : Bool) + (h : ∀ i, p i → fixed (H.addr i).1 (H.addr i).2 = b) + (f : Outline d e k → ℝ) (hf : ∀ i, 0 ≤ f i) : + (∑ i : {v // p v}, f (H.cellTag i.val)) ≤ + ∑ v, ∑ j, if fixed v j = b then f (a v j) else 0 := by + let e := (Function.Embedding.subtype p).trans H.addr + let r (i : V × B w) := if fixed i.1 i.2 = b then f (a i.1 i.2) else 0 + have h' (i : {v // p v}) : r (e i) = f (H.cellTag i.val) := ite_eq_left (h _ i.property) + have ht := sum_injection e r (fun i => by + unfold r + split + · exact hf _ + · exact le_rfl) + simp only [h', Fintype.sum_prod_type] at ht + exact ht + +include H in +open scoped Classical in +theorem count : (Fintype.card Q.freeze.Fixed : ℝ) ≤ ∑ v, ((a v).count (fixed v) : ℝ) := by + have h := H.lift Q.freeze.frozen true (fun i => (H.frozen i).mp) + (fun i => if i.live then 1 else 0) (by intro i; positivity) + have ha (i : Q.freeze.Fixed) : (H.cellTag i.val).live = true := H.live _ + simp only [ha, ite_true, sum_const, card_univ, nsmul_eq_mul, mul_one] at h + refine h.trans_eq (sum_congr rfl fun v _ => ?_) + unfold Blueprint.count + rw [card_filter, Nat.cast_sum] + apply sum_congr rfl + intro j _ + cases (a v j).live <;> cases fixed v j <;> simp + +open scoped Classical in +theorem square : (∑ i : Q.freeze.Fixed, ((H.cellTag i.val).toll : ℝ) ^ 2) ≤ + ∑ v, ((a v).square (fixed v) : ℝ) := by + have h := H.lift Q.freeze.frozen true (fun i => (H.frozen i).mp) + (fun i => (i.toll : ℝ) ^ 2) (fun _ => sq_nonneg _) + simpa only [Blueprint.square, Nat.cast_sum, Nat.cast_ite, Nat.cast_pow, Nat.cast_zero] using h + +open scoped Classical in +theorem mobile : (∑ i : Q.freeze.Core, ((H.cellTag i.val).toll : ℝ)) ≤ + ∑ v, ((a v).mobile (fixed v) : ℝ) := by + have h := H.lift (fun v => ¬ Q.freeze.frozen v) false + (fun i hi => Bool.eq_false_iff.mpr (mt (H.frozen i).mpr hi)) + (fun i => (i.toll : ℝ)) (fun _ => Nat.cast_nonneg _) + refine h.trans_eq (sum_congr rfl fun v _ => ?_) + simp only [Blueprint.mobile, Nat.cast_sum, Nat.cast_ite, Nat.cast_zero] + apply sum_congr rfl + intro j _ + cases fixed v j <;> simp + +open scoped Classical in +theorem partial_square (f : Q.diagram.V → ℝ) : + (∑ i : Q.freeze.Fixed, f i.val ^ 2) ≤ ∑ i, f i ^ 2 := + sum_injection (Function.Embedding.subtype _) (fun i => f i ^ 2) (fun _ => sq_nonneg _) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry.Support +end + +/- +# Every geometrically admitted branch has bounded charges + +These estimates use neither the weight nor the hidden selector of a +station. Thus even a spurious but geometrically valid branch with +weight zero has the required arities. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Coloring Finset Rounds +variable {V : Type} [Fintype V] {g ℓ D n w d e k C h T u : ℕ} {W : ℝ} + +open scoped Classical in +private theorem square_sum (T u W D b n K x y s r : ℝ) + (ht : 0 ≤ T) (hu : 0 ≤ u) (hn : 0 ≤ n) (hd : 1 ≤ D) (hk : 0 ≤ K) + (hx : 0 ≤ x) (hy : 0 ≤ y) (hT : K * u ≤ T) + (hocc : x * D * T ≤ W) (hp : r * T ≤ 2 * b * (n + 1) * W) (hterm : y ≤ r + n * x) + (hc : (n + 1) * s ≤ 512 * (x * (D * (n + 1)) + y + x) * K ^ 2) : + s * u ^ 2 ≤ 512 * (2 * b + 2) * W * T := by + have hsimple : x * T ≤ W := by + simpa using (mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hd hx) ht).trans hocc + have hs : (x * (D * (n + 1)) + y + x) * T ≤ (n + 1) * (2 * b + 2) * W := by + linarith only [mul_le_mul_of_nonneg_right hterm ht, hp, + mul_le_mul_of_nonneg_left hocc (show 0 ≤ n + 1 by linarith), + mul_le_mul_of_nonneg_left hsimple (show 0 ≤ n + 1 by linarith)] + apply le_of_mul_le_mul_left _ (by linarith : 0 < n + 1) + calc + _ ≤ 512 * (x * (D * (n + 1)) + y + x) * (K * u) ^ 2 := by + linarith only [mul_le_mul_of_nonneg_right hc (sq_nonneg u)] + _ ≤ 512 * (x * (D * (n + 1)) + y + x) * T ^ 2 := by gcongr + _ ≤ _ := by linarith only [mul_le_mul_of_nonneg_right hs ht] + +open scoped Classical in +private theorem count_sum (x y t D T W : ℝ) (hD : 0 < D) (hT : 0 ≤ T) + (h : D ^ 5 * x ≤ y) (ht : y ≤ t) (hw : t * D * T ≤ 3 * D ^ 5 * W) : x * D * T ≤ 3 * W := by + apply le_of_mul_le_mul_left _ (pow_pos hD 5) + linarith only [mul_le_mul_of_nonneg_right (h.trans ht) (mul_nonneg hD.le hT), hw] + +open scoped Classical in +private theorem mobile_sum (m u c n k x y D T W : ℝ) (hD : 0 ≤ D) (hu : 0 ≤ u) + (hc : 0 ≤ c) (hx : 0 ≤ x) (hy : 0 ≤ y) (ht : k * u ≤ T) + (h₁ : x * D * T ≤ W) (h₂ : y * D * T ≤ 3 * W) (h₃ : m ≤ 2 * c * (x + y) * D * (1 + n) ^ 2 * k) : + m * u ≤ 8 * c * W * (1 + n) ^ 2 := calc + _ ≤ 2 * c * (x + y) * D * (1 + n) ^ 2 * k * u := mul_le_mul_of_nonneg_right h₃ hu + _ = 2 * c * (1 + n) ^ 2 * ((x + y) * D * (k * u)) := by ring + _ ≤ 2 * c * (1 + n) ^ 2 * ((x + y) * D * T) := by gcongr + _ ≤ 2 * c * (1 + n) ^ 2 * (4 * W) := by + exact mul_le_mul_of_nonneg_left (by linarith only [h₁, h₂]) (by positivity) + _ = _ := by ring + +open scoped Classical in +/-- The quantity computed by `512 * (2 * SphereScale.budget g + 2)`. -/ +def squareConstant (g : ℕ) := 512 * (2 * SphereScale.budget g + 2) + +variable (a : V → Blueprint w d e k) (fixed : V → B w → Bool) + +open scoped Classical in +/-- The data for the totals construction, including `count`, `square`, `mobile`. -/ +structure Totals (D T u C h g : ℕ) (W : ℝ) : Prop where + count : (∑ v, ((a v).count (fixed v) : ℝ)) * D * T ≤ 3 * W + square : (∑ v, ((a v).square (fixed v) : ℝ)) * u ^ 2 ≤ squareConstant g * W * T + mobile : (∑ v, ((a v).mobile (fixed v) : ℝ)) * u ≤ 8 * C * W * (1 + (h : ℝ)) ^ 2 + +open scoped Classical in +theorem totals {p : Fin n → V → V} {z : V → Credits g ℓ D n} {E M : V → ℕ} + (hD : 0 < D) (hv : (Fintype.card V : ℝ) * D * T ≤ W) + (hE : (∑ v, (E v : ℝ)) * T ≤ 2 * SphereScale.budget g * ((n : ℝ) + 1) * W) + (hM : (∑ v, (M v : ℝ)) * D * T ≤ 3 * (D : ℝ) ^ 5 * W) + (hcheck : Credits.Check p z E M) (hq : ∀ v, Quota C h (T / u) (fixed v) (a v) (z v)) : + Totals a fixed D T u C h g W := by + let K := T / u + have ht : (K : ℝ) * u ≤ T := by exact_mod_cast Nat.div_mul_le_self T u + let c v := (a v).count (fixed v) + let s v := (a v).square (fixed v) + let m v := (a v).mobile (fixed v) + let t v := (z v).time (Fin.last n) + let b v := (z v).power (Fin.last n) + have hx : D ^ 5 * (∑ v, c v) ≤ ∑ v, t v := by + rw [mul_sum] + exact sum_le_sum fun i _ => (hq i).count + have hy : (n + 1) * (∑ v, s v) ≤ 512 * (Fintype.card V * (D * (n + 1)) + (∑ v, b v) + + Fintype.card V) * K ^ 2 := by + rw [←mul_assoc (Fintype.card V)] + have hh := sum_le_sum fun v (_ : v ∈ univ) => (hq v).square + simpa only [←sum_mul, ←mul_sum, sum_add_distrib, sum_const, card_univ, Nat.nsmul_eq_mul, + mul_one] using hh + have hm : (∑ v, m v) ≤ 2 * C * (Fintype.card V+∑ v, c v) * D * (1 + h) ^ 2 * K := by + have hh := sum_le_sum fun v (_ : v ∈ univ) => (hq v).mobile + simpa only [←sum_mul, ←mul_sum, sum_add_distrib, sum_const, card_univ, Nat.nsmul_eq_mul, + mul_one] using hh + have hc : (∑ v, (c v : ℝ)) * D * T ≤ 3 * W := + count_sum _ (∑ v, (t v : ℝ)) _ _ _ _ (Nat.cast_pos.mpr hD) (by positivity) + (by exact_mod_cast hx) (by exact_mod_cast hcheck.final.2) hM + refine ⟨hc, ?_, ?_⟩ + · unfold squareConstant + push_cast + apply square_sum T u W D _ n K (Fintype.card V) (∑ v, (b v : ℝ)) _ (∑ v, (E v : ℝ)) + (by positivity) (by positivity) (by positivity) (by exact_mod_cast hD) (by positivity) + (by positivity) (by positivity) ht hv hE + · exact_mod_cast hcheck.final.1 + · exact_mod_cast hy + · apply mobile_sum _ _ _ _ K _ _ _ _ _ (Nat.cast_nonneg D) (by positivity) + (by positivity) (by positivity) (by positivity) ht hv hc + exact_mod_cast hm + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Scalar/Term.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Scalar/Term.lean new file mode 100644 index 0000000000..4709bc6a35 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Scalar/Term.lean @@ -0,0 +1,467 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Ledger +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Remnants + +/-! # Inserting a finite family of isolated scalar tables -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram +open Packing + +open scoped Classical in +/-- Reindexes `(Σ j, X j)` and `Σ j, X (.inl j) where toFun | ⟨.inl v, p⟩ => ⟨v, p⟩ | ⟨.inr i, +p⟩ => (empty i p).elim invFun t` by an equivalence. -/ +def discard {V I : Type} (X : V ⊕ I → Type) (empty : ∀ i, X (.inr i) → False) : + (Σ j, X j) ≃ Σ j, X (.inl j) where + toFun + | ⟨.inl v, p⟩ => ⟨v, p⟩ + | ⟨.inr i, p⟩ => (empty i p).elim + invFun t := ⟨.inl t.1, t.2⟩ + left_inv := by + rintro ⟨v|i, p⟩ + · rfl + · exact (empty i p).elim + right_inv _ := rfl + +variable {F I : Type} [Fintype I] {x y : Wire} (G : Diagram F x y) (c : I → F) + +open scoped Classical in +/-- Uses `⟨.unit, .unit, fun _ _ => v⟩` as the representation. -/ +abbrev scalarTable (v : F) : Table F := ⟨.unit, .unit, fun _ _ => v⟩ + +open scoped Classical in +/-- Builds `Diagram F x y where V` with the specified `table`, `src`, `dst`. -/ +abbrev withScalars : Diagram F x y where + V := G.V ⊕ I + E := G.E + table := Sum.elim G.table (scalarTable ∘ c) + src := (Diagram.discard (fun j => slots ((Sum.elim G.table (scalarTable ∘ c)) j).1) (fun _ + => Empty.elim)).trans G.src + dst := (Diagram.discard (fun j => slots ((Sum.elim G.table (scalarTable ∘ c)) j).2.1) (fun _ + => Empty.elim)).trans G.dst + +open scoped Classical in +theorem scalar_portEnd (i : slots x ⊕ slots y) : portEnd (G.withScalars c) i = .inl (portEnd G i) + := by + cases i <;> rfl + +open scoped Classical in +theorem scalar_source (i : G.E) : (G.withScalars c).source i = .inl (G.source i) := rfl +open scoped Classical in +theorem scalar_target (i : G.E) : (G.withScalars c).target i = .inl (G.target i) := rfl + +open scoped Classical in +theorem eval_scalars [Field F] (a : Val x) (b : Val y) : + (G.withScalars c).eval a b = (∏ i, c i) * G.eval a b := by + unfold eval + rw [Finset.mul_sum] + refine Finset.sum_congr rfl fun z _ => ?_ + change (∏ i : G.V ⊕ I, (G.withScalars c).vertex a b z i) = _ + rw [Fintype.prod_sum_type, mul_comm] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +/- +# Counting terminal collectors + +Each occupied cell starts with one extra vacuum collector. A new +collector can only be created by using a full movement allowance. +Charge its crossings to incidences at occupied cells. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +open Finset +variable {F T V E X : Type} {r t : ℕ} [Fintype V] (s : Stage F r t T V E X) + +open scoped Classical in +theorem card_collectors : + Fintype.card {i : Sphere.Layout.Place s.scene.cell // + (Sphere.Layout.item s.scene.cell i).label.role = .collector} = s.collectors := by + have eq (r : Role) : (if r = .collector then 1 else 0) = r.collected 1 := by + cases r <;> simp [Role.collected] + rw [Fintype.card_subtype, card_eq_sum_ones, sum_filter, Fintype.sum_sigma] + unfold collectors + apply sum_congr rfl + intro v _ + simp only [Sphere.Layout.item, tally] + let l := (s.scene.cell v).stations + let f := fun a : s.St => a.label.role.collected 1 + trans ∑ i : Fin l.length, f (l.get i) + · exact sum_congr rfl fun i _ => eq _ + change _ = (l.map f).sum + rw [←List.sum_ofFn] + change (List.ofFn (f ∘ l.get)).sum = _ + rw [←List.map_ofFn, List.ofFn_get] + +open scoped Classical in +theorem hits_le_visits [Fintype E] (src : E → V) (incident : ∀ e, e ∈ s.edges (src e)) : + (∑ e, s.hits e) ≤ ∑ v, s.visits v := by + rw [← sum_fiberwise univ src] + apply sum_le_sum + intro v _ + apply sum_le_sum_of_subset + intro e he + rw [← (mem_filter.mp he).2] + exact incident e + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset Routing.Private SphereScale + +variable {F K : Type} {x y : Wire} {h D T b d g n m : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) + [Field F] [Field K] [Algebra K F] (p : P.Kits K m n ε) (s : P.Occupied → Shape n b d) + +open scoped Classical in +/-- The quantity computed by `1 + ∑ v ∈ P.grid.stations c, if ¬P.mobile v then 1 else 0`. -/ +def collectorCount (c : P.Occupied) : ℕ := + 1 + ∑ v ∈ P.grid.stations c, if ¬P.mobile v then 1 else 0 + +open scoped Classical in +theorem plant_collector_cell (t : ℕ) (c : P.Occupied) : + (P.plant p s).tally t (fun r _ => r.collected 1) c = P.collectorCount c := by + let wt := fun v => if ¬P.mobile v then 1 else 0 + unfold Stage.tally collectorCount + change ((Template.cells p P.tag s c).stations.map (fun u => u.label.role.collected 1)).sum = + 1 + ∑ v ∈ P.grid.stations c, wt v + rw [Template.cells_stations, ←sum_coe_sort, ←(Grid.number P.grid.stationRank (P.grid.stations + c)).sum_comp] + simp only [List.map_cons, List.map_append, List.map_ofFn, List.sum_cons, List.sum_append, + List.sum_ofFn] + change 1 + ((∑ _ : Fin n, 0) + ∑ i, (P.tag (n := n) c (.inl (P.grid.label c i))).role.collected 1) + = 1 + ∑ i, wt (P.grid.label c i) + simp only [sum_const_zero, zero_add] + congr 1 + apply sum_congr rfl + intro i _ + by_cases h : P.mobile (P.grid.label c i) <;> simp [wt, tag, h, Role.collected] + +open scoped Classical in +theorem plant_collectors : + (P.plant p s).collectors = Fintype.card P.Occupied + Fintype.card {v // ¬P.mobile v} := by + let wt := fun v => if ¬P.mobile v then 1 else 0 + have each c : (P.plant p s).tally 0 (fun r _ => r.collected 1) c = + 1 + ∑ v ∈ P.grid.stations c, wt v := P.plant_collector_cell p s 0 c + unfold Stage.collectors + simp only [each, sum_add_distrib, sum_const, card_univ, Nat.nsmul_eq_mul, mul_one] + simp only [Grid.stations, sum_filter] + rw [sum_comm] + simp only [sum_ite_eq, mem_univ, ite_true, wt, sum_boole, Nat.cast_id, Fintype.card_subtype] + +open scoped Classical in +theorem final_count {ℓ : ℕ} (sc : Scales g ℓ D T m b d) + {t : Stage F (d * b) d P.diagram.V P.Occupied P.grid.Seam ((Val x × Val y) × Template.Keys p)} + (reach : (P.plant p s).Reach m (2 * g) (SphereScale.energy ℓ D (d * b)) (D ^ 5) t) + (visits : ∀ v, t.visits v ≤ budget g * D ^ 2) : + (t.collectors : ℝ) * D * T ≤ budget g * W := by + have total : D ^ 5 * t.expired ≤ ∑ v, t.visits v := by + have ht := (reach.budget.limits (fun _ => rfl) (P.plant_zero p s _) rfl).2.2.2.1 + refine ht.trans (t.hits_le_visits (fun e => e.val.1) ?_) + intro e + rw [reach.edges_eq, Stage.edges, List.mem_toFinset] + exact ((P.plant_layout p s sc.Rpos).incident _ e).mpr (Or.inl rfl) + have hb : budget g * D ^ 2 ≤ D ^ 5 := calc + _ ≤ D * D ^ 2 := Nat.mul_le_mul_right _ (by have := sc.large; omega) + _ ≤ _ := by rw [←pow_succ']; exact Nat.pow_le_pow_right sc.Dpos (by decide) + have exp : t.expired ≤ Fintype.card P.Occupied := by + apply Nat.le_of_mul_le_mul_left _ (pow_pos sc.Dpos 5) + apply total.trans + simpa [mul_comm] using sum_le_sum (fun v (_ : v ∈ univ) => (visits v).trans hb) + have cnt := reach.collectors + rw [P.plant_collectors] at cnt + have bnd : t.collectors ≤ 2 * Fintype.card P.Occupied + Fintype.card {v // ¬P.mobile v} + := by omega + have occ : (Fintype.card P.Occupied : ℝ) * D * T ≤ W := by + simpa only [Occupied, Fintype.card_coe] using P.occupied + calc + _ ≤ (2 * Fintype.card P.Occupied + Fintype.card {v // ¬P.mobile v} : ℝ) * D * T := by + gcongr + exact_mod_cast bnd + _ ≤ 3 * W := by linarith only [occ, P.immobile] + _ ≤ budget g * W := mul_le_mul_of_nonneg_right + (by exact_mod_cast (show 3 ≤ budget g by have := budget_large g; omega)) + (le_trans (by positivity) occ) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Uniform room for the motion of planted stations -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Surface Finset Routing.Private + +variable {F K : Type} {x y : Wire} {h D T b d g n m H U : ℕ} {W ε : ℝ} + (P : Input F x y h D T (d * b) g W) + [Field F] [Field K] [Algebra K F] (p : P.Kits K m n ε) (s : P.Occupied → Shape n b d) + +open scoped Classical in +/-- The quantity computed by `reserve D b d n m H + m * (8 * (200 * (D : ℝ) * T) ^ 2 / (d * b : +ℕ))`. -/ +def initialEnergy (D T b d n m H : ℕ) : ℝ := + reserve D b d n m H + m * (8 * (200 * (D : ℝ) * T) ^ 2 / (d * b : ℕ)) + +open scoped Classical in +theorem plant_room (hr : 0 < d * b) (hm : 0 < m) (hh : 0 < H) (M N : ℕ) + (size : (2 * m * H * (100 * D + n + 1 + 2 * g) : ℕ) + initialEnergy D T b d n m H + ≤ (2 * m * H * M : ℕ)) + (en : (1 + 4 * g : ℕ) * initialEnergy D T b d n m H ≤ N) + {z : Stage F (d * b) d P.diagram.V P.Occupied P.grid.Seam ((Val x × Val y) × Template.Keys p)} + (hz : (P.plant p s).Reach m (2 * g) H U z) : z.Room M N := by + let S := P.plant p s + let A := S.ledger m H + let seam c := ∑ e ∈ S.edges c, A.seam e + let total c := A.mobile c + A.collected c + seam c + have ht c : (total c : ℝ) ≤ initialEnergy D T b d n m H := P.plant_local_energy p s hr H c + apply hz.room hm hh (P.plant_layout p s hr).unique M N + · intro c + have pos : (S.scene.cell c).positions.length ≤ 100 * D + n + 1 + 2 * g := by + rw [Cell.positions, List.length_append, List.length_map, List.length_map] + exact Nat.add_le_add (P.plant_length p s c) ((P.plant_layout p s hr).degree c) + have hs : (seam c : ℝ) ≤ initialEnergy D T b d n m H := + ((Nat.cast_le (α := ℝ)).mpr (Nat.le_add_left _ _)).trans (ht c) + change (2 * m * H) * (S.scene.cell c).positions.length + seam c ≤ 2 * m * H * M + apply (Nat.cast_le (α := ℝ)).mp + rw [Nat.cast_add] + exact (add_le_add ((Nat.cast_le (α := ℝ)).mpr (Nat.mul_le_mul_left _ pos)) hs).trans size + · intro c + change A.cost (2 * g) c + (1 + 2 * (2 * g)) * (seam c) ≤ N + calc + _ ≤ (1 + 4 * g) * (total c) := by + dsimp only [total, Ledger.cost] + rw [show 2 * (2 * g) = 4 * g by omega, mul_add, mul_add] + exact Nat.add_le_add_right (Nat.add_le_add_left (Nat.le_mul_of_pos_left _ (by omega)) _) _ + _ ≤ N := by + apply (Nat.cast_le (α := ℝ)).mp + rw [Nat.cast_mul] + exact (mul_le_mul_of_nonneg_left (ht c) (Nat.cast_nonneg _)).trans en + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# A separate bank of scalar stations + +The new bank uses the input host and block indices. All new +stations are mobile, have no edges, and pay the unit floor charge. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Packing Finset + +variable {F : Type} {x y : Wire} {h D T R g u : ℕ} {W : ℝ} + (P : Input F x y h D T R g W) (Q : LocalTerm F x y h u) (c : P.Occupied → F) + +local notation "G" => Q.diagram.withScalars c + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `(.inl (Q.frame.place v).1, (Q.frame.place +v).2)`. -/ +def scalarPlace : Q.diagram.V ⊕ P.Occupied → (Q.V ⊕ P.V) × Cell h + | .inl v => (.inl (Q.frame.place v).1, (Q.frame.place v).2) + | .inr i => (.inr i.val.1, i.val.2) + +open scoped Classical in +theorem scalar_one : Function.Injective (P.scalarPlace Q) := by + rintro (a|a) (b|b) e + · exact congrArg Sum.inl (Q.one (Prod.ext (Sum.inl.inj (Prod.mk.inj e).1) (Prod.mk.inj e).2)) + · cases (Prod.mk.inj e).1 + · cases (Prod.mk.inj e).1 + · exact congrArg Sum.inr (Subtype.ext (Prod.ext (Sum.inr.inj (Prod.mk.inj e).1) (Prod.mk.inj + e).2)) + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +abbrev scalarAdj (N : Q.V → Finset Q.V) : Q.V ⊕ P.V → Finset (Q.V ⊕ P.V) := + Sum.elim (fun v => (N v).map Function.Embedding.inl) (fun _ => ∅) + +open scoped Classical in +theorem scalar_sym {N : Q.V → Finset Q.V} (hn : ∀ v w, w ∈ N v → v ∈ N w) : + ∀ v w, w ∈ P.scalarAdj Q N v → v ∈ P.scalarAdj Q N w := by + rintro (v|v) w hw + · obtain ⟨z, hz, rfl⟩ := mem_map.mp hw + exact mem_map_of_mem _ (hn v z hz) + · exact (notMem_empty w hw).elim + +open scoped Classical in +/-- Chooses the operation for the left or right summand. -/ +abbrev scalarFreeze : Freeze (G) where + frozen := Sum.elim Q.freeze.frozen (fun _ => False) + exterior i := by rw [Diagram.scalar_portEnd]; exact Q.freeze.exterior i + separate i := Q.freeze.separate i + +open scoped Classical in +/-- Builds `(P.scalarFreeze Q c).Frame (Q.V ⊕ P.V) h where place` with the specified `place`, +`frozen`, `keep`, `ns`. -/ +abbrev scalarFrame : (P.scalarFreeze Q c).Frame (Q.V ⊕ P.V) h where + place := P.scalarPlace Q + frozen := Sum.elim Q.frame.frozen (fun _ => False) + keep v := by cases v with | inl v => exact Q.frame.keep v | inr _ => rfl + N := P.scalarAdj Q Q.frame.N + C := P.scalarAdj Q Q.frame.C + ns := P.scalar_sym Q Q.frame.ns + cs := P.scalar_sym Q Q.frame.cs + sub v := by + cases v with + | inl v => exact map_subset_map.mpr (Q.frame.sub v) + | inr _ => exact Subset.rfl + group e := Q.frame.group e + edge e := mem_map_of_mem _ (Q.frame.edge ⟨e.val, e.property⟩) + full e := mem_map_of_mem _ (Q.frame.full e) + +open scoped Classical in +theorem scalar_width (v w : (G).V) : + u ∣ Fintype.card {e // (G).source e = v ∧ (G).target e = w} := by + rcases v with v|v <;> rcases w with w|w <;> + simp only [Fintype.card_subtype, Diagram.scalar_source, Diagram.scalar_target, Sum.inl.injEq, + reduceCtorEq, false_and, and_false, filter_false, card_empty, dvd_zero] + simpa only [Fintype.card_subtype] using Q.width v w + +open scoped Classical in +/-- Indexes the weighted by the coordinates of `Q.V ⊕ P.V diagram := G freeze := P.scalarFreeze +Q c frame := P.scalarFrame Q c one := P.scalar_one Q`. -/ +abbrev weighted : LocalTerm F x y h u where + V := Q.V ⊕ P.V + diagram := G + freeze := P.scalarFreeze Q c + frame := P.scalarFrame Q c + one := P.scalar_one Q + width v w := by simpa only [Fintype.card_eq_nat_card] using P.scalar_width Q c v w + charge := Sum.elim Q.charge (fun _ => (u : ℝ)) + cover v := by + cases v with + | inl v => exact Q.cover v + | inr _ => exact Nat.cast_le.mpr (Nat.zero_le _) + floor v := by cases v with | inl v => exact Q.floor v | inr _ => rfl + +open scoped Classical in +theorem weighted_eval [Field F] (a : Val x) (b : Val y) : + (P.weighted Q c).diagram.eval a b = (∏ v, c v) * Q.diagram.eval a b := + Q.diagram.eval_scalars c a b + +open scoped Classical in +theorem weighted_portEnd (i : slots x ⊕ slots y) : + portEnd (P.weighted Q c).diagram i = .inl (portEnd Q.diagram i) := + Q.diagram.scalar_portEnd c i + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- +# Concentration after incorporating the scalar weights + +Each occupied cell pays the floor charge once. The input bound +on occupied cells covers these charges without a factor growing +with the number of blocks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds +open Packing Finset + +variable {F : Type} {x y : Wire} {h D T R g u C d ℓ : ℕ} {W : ℝ} + (P : Input F x y h D T R g W) (Q : LocalTerm F x y h u) (c : P.Occupied → F) + +local notation "A" => P.weighted Q c + +namespace Input + +open scoped Classical in +/-- Reindexes `Q.freeze.Fixed` and `(A).freeze.Fixed where toFun v` by an equivalence. -/ +def scalarFixed : Q.freeze.Fixed ≃ (A).freeze.Fixed where + toFun v := ⟨.inl v.val, v.property⟩ + invFun + | ⟨.inl v, h⟩ => ⟨v, h⟩ + | ⟨.inr _, h⟩ => False.elim h + left_inv _ := rfl + right_inv := by + rintro ⟨v|i, h⟩ + · rfl + · exact False.elim h + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `⟨.inl v.val, v.property⟩`. -/ +def scalarCore : Q.freeze.Core ⊕ P.Occupied ≃ (A).freeze.Core where + toFun + | .inl v => ⟨.inl v.val, v.property⟩ + | .inr i => ⟨.inr i, fun h => h⟩ + invFun + | ⟨.inl v, h⟩ => .inl ⟨v, h⟩ + | ⟨.inr i, _⟩ => .inr i + left_inv := by rintro (_|_) <;> rfl + right_inv := by rintro ⟨_|_, _⟩ <;> rfl + +open scoped Classical in +theorem scalar_sum : + (∑ v : (A).freeze.Core, (A).charge v.val) = + (∑ v : Q.freeze.Core, Q.charge v.val) + Fintype.card P.Occupied * u := by + rw [← (P.scalarCore Q c).sum_comp, Fintype.sum_sum_type] + change (∑ v : Q.freeze.Core, Q.charge v.val) + (∑ _ : P.Occupied, (u : ℝ)) = _ + simp only [sum_const, card_univ, nsmul_eq_mul] + +end Input + +variable {P Q} + +open scoped Classical in +theorem Concentrated.weighted (hc : Concentrated P Q C d ℓ) (c : P.Occupied → F) + (hD : 2 ≤ D) (hu : u * D ^ ℓ ≤ T) : Concentrated P (P.weighted Q c) (C + 2) d ℓ := by + have hd : 0 < D := by omega + have hw : 0 ≤ W := (by positivity : (0 : ℝ) ≤ (univ.image P.place).card * D * T) |>.trans + P.occupied + have he : D ^ C + 1 ≤ D ^ (C + 2) := Nat.pow_lt_pow_right (by omega) (by omega) + have hpow : D ^ C ≤ D ^ (C + 2) := (Nat.le_add_right ..).trans he + have hC : (C : ℝ) ≤ (C + 2 : ℕ) := Nat.cast_le.mpr (by omega) + refine ⟨?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · change Fintype.card (Q.V ⊕ P.V) ≤ _ + rw [Fintype.card_sum] + calc + _ ≤ D ^ C * Fintype.card P.V + Fintype.card P.V := Nat.add_le_add_right hc.cells _ + _ = (D ^ C + 1) * Fintype.card P.V := by rw [add_mul, one_mul] + _ ≤ _ := Nat.mul_le_mul_right _ he + · rintro (v|v) + · exact (card_map _).le.trans ((hc.coreDegree v).trans (by omega)) + · exact Nat.zero_le _ + · rintro (v|v) + · exact (card_map _).le.trans ((hc.fullDegree v).trans hpow) + · exact Nat.zero_le _ + · rw [← Fintype.card_congr (P.scalarFixed Q c)] + exact hc.frozenCount.trans (mul_le_mul_of_nonneg_right hC hw) + · intro i + obtain ⟨v, rfl⟩ := (P.scalarFixed Q c).surjective i + exact (hc.frozenMax v).trans (by gcongr) + · rw [← (P.scalarFixed Q c).sum_comp] + exact hc.frozenSquare.trans (by gcongr) + · rintro ⟨v|j, hv⟩ + · exact hc.coreMax ⟨v, hv⟩ + · change (u : ℝ) * D ^ ℓ ≤ T + exact_mod_cast hu + · rw [P.scalar_sum] + have hu' : u ≤ D * T := ((Nat.le_mul_of_pos_right _ (pow_pos hd _)).trans hu).trans + (Nat.le_mul_of_pos_left _ hd) + have cost : (Fintype.card P.Occupied : ℝ) * u ≤ W := calc + _ ≤ (Fintype.card P.Occupied : ℝ) * (D * T) + := mul_le_mul_of_nonneg_left (by exact_mod_cast hu') (by positivity) + _ ≤ _ := by simpa only [Input.Occupied, Fintype.card_coe, mul_assoc] using P.occupied + refine (add_le_add hc.coreSum cost).trans ?_ + have hh : (1 : ℝ) ≤ (1 + (d : ℝ)) ^ 2 := one_le_pow₀ (by simp) + rw [Nat.cast_add, Nat.cast_ofNat] + linarith only [mul_le_mul_of_nonneg_left hh hw, hw] + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Seam.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Seam.lean new file mode 100644 index 0000000000..6ffc88659c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Seam.lean @@ -0,0 +1,923 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import Mathlib.Algebra.BigOperators.Group.List.Basic +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Data.Finset.Sort +public import Mathlib.Tactic.NormNum +public import Mathlib.Analysis.Real.Sqrt + +/-! # Scaling, restriction and change of coefficients for pairing sums -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {α R S : Type*} [CommRing R] [CommRing S] + +private theorem contract_scale_rows (c : R) (f g : α → R) (P : List α → R) (xs : List α) : + contract (fun x => c * f x * g x) (fun t => (t.map f).prod * P t) xs = + c * (xs.map f).prod * contract g P xs := by + induction xs generalizing P with + | nil => simp + | cons x xs ih => + simp only [contract_cons, List.map_cons, List.prod_cons] + simp only [mul_assoc (f x)] + rw [contract_scale, ih (fun t => P (x :: t))] + ring + +/-- Every generator occurs exactly once in each Wick monomial. -/ +theorem wick_scale_rows (k : α → α → R) (f : α → R) (xs : List α) : + wick (fun x y => f x * f y * k x y) xs = (xs.map f).prod * wick k xs := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => simp + | cons x xs => + simp only [List.length_cons] at hn + rw [wick_cons, wick_cons, List.map_cons, List.prod_cons, ← contract_scale_rows] + apply contract_congr + intro ys hy + exact ih ys.length (by omega) ys rfl + +private theorem contract_eq_on (f g : α → R) (P : List α → R) (xs : List α) + (h : ∀ x ∈ xs, f x = g x) : contract f P xs = contract g P xs := by + induction xs generalizing P with + | nil => rfl + | cons x xs ih => + simp only [List.forall_mem_cons] at h + rw [contract_cons, contract_cons, h.1, ih _ h.2] + +theorem wick_eq_on (k l : α → α → R) (xs : List α) + (h : ∀ x ∈ xs, ∀ y ∈ xs, k x y = l x y) : wick k xs = wick l xs := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => rfl + | cons x xs => + simp only [List.length_cons] at hn + have head (z : α) (hz : z ∈ xs) : k x z = l x z := h x (by simp) z (by simp [hz]) + rw [wick_cons, wick_cons, contract_eq_on _ _ _ _ head] + apply contract_sublist_congr + intro ys hy he + apply ih ys.length (by omega) ys _ rfl + intro y h₁ z h₂ + exact h y (List.mem_cons_of_mem _ (hy.subset h₁)) z (List.mem_cons_of_mem _ (hy.subset h₂)) + +private theorem contract_hom (f : R →+* S) (g : α → R) (P : List α → R) (xs : List α) : + f (contract g P xs) = contract (fun x => f (g x)) (fun t => f (P t)) xs := by + induction xs generalizing P with + | nil => simp + | cons x xs ih => rw [contract_cons, contract_cons, map_sub, map_mul, ih] + +theorem wick_hom (f : R →+* S) (k : α → α → R) (xs : List α) : + f (wick k xs) = wick (fun x y => f (k x y)) xs := by + induction hn : xs.length using Nat.strong_induction_on generalizing xs with + | ind n ih => + cases xs with + | nil => simp + | cons x xs => + simp only [List.length_cons] at hn + rw [wick_cons, wick_cons, contract_hom] + apply contract_congr + intro ys hy + exact ih ys.length (by omega) ys rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Number of states at bounded energy + +Energy is doubled. Distinct modes give a finite subset of a rectangle. +Bounding the generating function of its powerset avoids infinite products. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Finset Real + +/-- The subtype of `w : Wedge r` satisfying `energy w.val ≤ e`. -/ +abbrev LevelLE (r e : ℕ) := {w : Wedge r // energy w.val ≤ e} + +variable {r e : ℕ} + +/-- The value specified by `univ ×ˢ range e`. -/ +def modes (r e : ℕ) : Finset (Mode r) := univ ×ˢ range e + +/-- Uses `w.val.val.toFinset` as the representation. -/ +def used (w : LevelLE r e) := w.val.val.toFinset + +theorem used_mem (w : LevelLE r e) : used w ∈ (modes r e).powerset := by + rw [mem_powerset] + intro i hi + have h : 2 * i.2 + 1 ≤ energy w.val.val := + List.le_sum_of_mem (List.mem_map_of_mem (List.mem_toFinset.mp hi)) + have := w.property + simp only [modes, mem_product, mem_univ, true_and, mem_range] + omega + +theorem Wedge.toFinset_injective : Function.Injective (fun w : Wedge r => w.val.toFinset) := by + intro x y h + apply Subtype.ext + apply List.Perm.eq_of_pairwise (fun _ _ _ _ h₁ h₂ => (asymm h₁ h₂).elim) x.property y.property + apply (List.perm_ext_iff_of_nodup x.nodup y.nodup).mpr + intro i + exact List.mem_toFinset.symm.trans ((congrArg (i ∈ ·) h).to_iff.trans List.mem_toFinset) + +theorem used_inj : Function.Injective (used (r := r) (e := e)) := + fun _ _ h => Subtype.ext (Wedge.toFinset_injective h) + +noncomputable instance (r e : ℕ) : Fintype (LevelLE r e) := + Fintype.ofInjective (fun w => (⟨used w, used_mem w⟩ : ↥(modes r e).powerset)) + (fun _ _ h => used_inj (congrArg Subtype.val h)) + +private noncomputable def weightFromDimension (t : ℝ) (j : ℕ) := exp (-t * (2 * j + 1)) + +private theorem weight_prod (t : ℝ) (w : LevelLE r e) : + ∏ i ∈ used w, weightFromDimension t i.2 = exp (-t * energy w.val.val) := by + unfold weightFromDimension + rw [← exp_sum, ← mul_sum] + have he := List.sum_toFinset (fun i : Mode r => 2 * i.2 + 1) w.val.nodup + change ∑ i ∈ used w, (2 * i.2 + 1) = energy w.val.val at he + rw [← he] + push_cast + rfl + +private theorem partition_bound (r e : ℕ) {t : ℝ} (ht : 0 ≤ t) : + Fintype.card (LevelLE r e) * exp (-t * e) ≤ + ∏ i ∈ modes r e, (1 + weightFromDimension t i.2) := by + classical + let g (a : Finset (Mode r)) := ∏ i ∈ a, weightFromDimension t i.2 + calc + _ = ∑ _w : LevelLE r e, exp (-t * e) := by simp + _ ≤ ∑ w : LevelLE r e, g (used w) := by + apply sum_le_sum + intro w _ + rw [show g (used w) = _ from weight_prod t w] + exact exp_le_exp.mpr (mul_le_mul_of_nonpos_left (Nat.cast_le.mpr w.property) (neg_nonpos.mpr + ht)) + _ = ∑ a ∈ (univ : Finset (LevelLE r e)).image used, g a := + (sum_image used_inj.injOn).symm + _ ≤ ∑ a ∈ (modes r e).powerset, g a := by + apply sum_le_sum_of_subset_of_nonneg + · rintro _ ha + obtain ⟨w, _, rfl⟩ := mem_image.mp ha + exact used_mem w + · intro a _ _ + exact prod_nonneg (fun _ _ => exp_nonneg _) + _ = _ := (prod_one_add _).symm + +/-- The exponential weights for one species are bounded by a telescoping sum. -/ +private theorem sum_weight (e : ℕ) {t : ℝ} (ht : 0 < t) : + ∑ j ∈ range e, weightFromDimension t j ≤ 1 / t := by + apply (le_div_iff₀ ht).mpr + rw [sum_mul] + let f (j : ℕ) := exp (-t * j) + calc + _ ≤ ∑ j ∈ range e, (f j - f (j + 1)) := by + apply sum_le_sum + intro j _ + have h₁ : weightFromDimension t j ≤ f (j + 1) := by + apply exp_le_exp.mpr + apply mul_le_mul_of_nonpos_left _ (neg_nonpos.mpr ht.le) + push_cast + linarith + have h₂ : f (j + 1) * exp t = f j := by + unfold f + rw [← exp_add] + congr 1 + push_cast + ring + calc + _ ≤ f (j + 1) * t := mul_le_mul_of_nonneg_right h₁ ht.le + _ ≤ f (j + 1) * (exp t - 1) := + mul_le_mul_of_nonneg_left (le_sub_iff_add_le.mpr (add_one_le_exp t)) (exp_nonneg _) + _ = _ := by rw [mul_sub, h₂, mul_one] + _ = f 0 - f e := sum_range_sub' _ _ + _ ≤ 1 := by simp [f, exp_nonneg] + +private theorem card_bound (r e : ℕ) {t : ℝ} (ht : 0 < t) : + Fintype.card (LevelLE r e) ≤ exp (r / t + t * e) := by + rw [exp_add, ← div_le_iff₀ (exp_pos _), div_eq_mul_inv, ← exp_neg, ← neg_mul] + calc + _ ≤ ∏ i ∈ modes r e, (1 + weightFromDimension t i.2) := partition_bound r e ht.le + _ ≤ exp (∑ i ∈ modes r e, weightFromDimension t i.2) := by + rw [exp_sum] + apply prod_le_prod₀ + · intro i _; unfold weightFromDimension; positivity + · intro i _; rw [add_comm]; exact add_one_le_exp _ + _ ≤ _ := by + apply exp_le_exp.mpr + rw [modes, sum_product] + simpa [div_eq_mul_inv] using + mul_le_mul_of_nonneg_left (sum_weight e ht) (Nat.cast_nonneg (α := ℝ) r) + +/-- A uniform dimension bound for the direct sum through doubled energy `e`. -/ +theorem card_levelLE (r e : ℕ) : + Fintype.card (LevelLE r e) ≤ exp (2 * sqrt ((r : ℝ) * e)) := by + rcases eq_or_ne r 0 with rfl | hr + · simpa [modes] using partition_bound 0 e (le_refl 0) + rcases eq_or_ne e 0 with rfl | he + · simpa [modes] using partition_bound r 0 (le_refl 0) + let z := sqrt ((r : ℝ) * e) + have hz : 0 < z := by unfold z; positivity + have he' : (0 : ℝ) < e := by positivity + have hsq : z ^ 2 = (r : ℝ) * e := sq_sqrt (by positivity) + have h : (r : ℝ) / (z / e) = z := by + rw [div_div_eq_mul_div, ← hsq, pow_two, mul_div_cancel_right₀ _ hz.ne'] + simpa only [h, div_mul_cancel₀ _ he'.ne', ← two_mul] using + card_bound r e (div_pos hz he') + +/-- The subtype of `w : Wedge r` satisfying `energy w.val = e`. -/ +abbrev Level (r e : ℕ) := {w : Wedge r // energy w.val = e} + +/-- Embeds `Level r e` into `LevelLE r e`. -/ +def Level.include (r e : ℕ) : Level r e ↪ LevelLE r e := + ⟨fun w => ⟨w.val, w.property.le⟩, + fun _ _ h => Subtype.ext (congrArg (fun x : LevelLE r e => x.val) h)⟩ + +noncomputable instance (r e : ℕ) : Fintype (Level r e) := + Fintype.ofInjective (Level.include r e) (Level.include r e).injective + +theorem card_level (r e : ℕ) : + Fintype.card (Level r e) ≤ exp (2 * sqrt ((r : ℝ) * e)) := + (Nat.cast_le.mpr (Fintype.card_le_of_injective _ (Level.include r e).injective)).trans + (card_levelLE r e) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Interleaving copies of one level + +Put the modes of each copy in their own residue class. Reversing the +class assignment makes the two total energies add to twice the target. +Keeping the lower one and one orientation bit is an injective encoding. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere +open Finset + +private def ordered (s : Finset ℕ) : Wedge 1 := + ⟨(s.sort (· ≤ ·)).map (fun k => (0, k)), by + rw [List.pairwise_map] + simpa only [Prod.Lex.toLex_lt_toLex, lt_self_iff_false, true_and, false_or] using + s.sortedLT_sort.pairwise⟩ + +private theorem ordered_injective : Function.Injective ordered := by + intro x y h + simpa [ordered, Function.comp_def] using + congrArg (fun w : Wedge 1 => (w.val.map Prod.snd).toFinset) h + +private theorem energy_ordered (s : Finset ℕ) : energy (ordered s).val = ∑ i ∈ s, (2 * i + 1) := by + simp only [energy, ordered, List.map_map, Function.comp_def] + rw [← List.sum_toFinset _ (s.sort_nodup _), sort_toFinset] + +variable {m e : ℕ} + +private abbrev Index (m : ℕ) := Sigma (fun _ : Fin m => Mode 1) + +private def code (π : Equiv.Perm (Fin m)) (i : Index m) := m * i.2.2 + (π i.1).val + +private theorem code_injective (π : Equiv.Perm (Fin m)) : Function.Injective (code π) := by + rintro ⟨i, k⟩ ⟨j, l⟩ h + change m * k.2 + (π i).val = m * l.2 + (π j).val at h + have hi := (π i).isLt + have hj := (π j).isLt + have hij : i = j := π.injective (Fin.ext (by + simpa only [Nat.mul_add_mod, Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt hj] using + congrArg (· % m) h)) + have hkl : k = l := Prod.ext (Subsingleton.elim _ _) (by + simpa only [Nat.mul_add_div (by omega : 0 < m), Nat.div_eq_of_lt hi, Nat.div_eq_of_lt hj, + add_zero] using congrArg (· / m) h) + rw [hij, hkl] + +private def positions (x : Fin m → Level 1 e) : Finset (Index m) := + univ.sigma fun i => (x i).val.val.toFinset + +private def pack (π : Equiv.Perm (Fin m)) (x : Fin m → Level 1 e) : Wedge 1 := + ordered ((positions x).image (code π)) + +private theorem pack_injective (π : Equiv.Perm (Fin m)) : Function.Injective (pack (e := e) π) := by + intro x y h + have hp := image_injective (code_injective π) (ordered_injective h) + funext i + apply Subtype.ext + apply Wedge.toFinset_injective + ext k + simpa only [positions, mem_sigma, mem_univ, true_and] using + (congrArg (fun s : Finset (Index m) => ⟨i, k⟩ ∈ s) hp).to_iff + +private theorem energy_pack (x : Fin m → Level 1 e) : + energy (pack (.refl _) x).val + energy (pack Fin.revPerm x).val = 2 * (m ^ 2 * e) := by + simp only [pack, energy_ordered, sum_image (code_injective _).injOn, ← sum_add_distrib] + have he (j : Index m) : 2 * code (.refl _) j + 1 + (2 * code Fin.revPerm j + 1) = + 2 * m * (2 * j.2.2 + 1) := by + have h : j.1.val + (Fin.revPerm j.1).val + 1 = m := by + change j.1.val + (m - (j.1.val + 1)) + 1 = m + have := j.1.isLt + omega + unfold code + simp only [Equiv.refl_apply] + nlinarith only [h] + simp_rw [he] + rw [← mul_sum, positions, sum_sigma] + have h (i : Fin m) : ∑ k ∈ (x i).val.val.toFinset, (2 * k.2 + 1) = e := by + rw [List.sum_toFinset _ (x i).val.nodup] + exact (x i).property + simp only [h, sum_const, card_univ, Fintype.card_fin, nsmul_eq_mul, Nat.cast_id] + ring + +private def store (x : Fin m → Level 1 e) : Bool × LevelLE 1 (m ^ 2 * e) := + if h : energy (pack (.refl _) x).val ≤ m ^ 2 * e then (false, ⟨pack (.refl _) x, h⟩) + else (true, ⟨pack Fin.revPerm x, by have := energy_pack x; omega⟩) + +private theorem store_injective : Function.Injective (store (m := m) (e := e)) := by + intro x y h + unfold store at h + split_ifs at h + · exact pack_injective _ (congrArg (fun s => s.2.val) h) + · cases congrArg Prod.fst h + · cases congrArg Prod.fst h + · exact pack_injective _ (congrArg (fun s => s.2.val) h) + +theorem largest_level (b : ℕ) : + ∃ g ≤ b, Fintype.card (LevelLE 1 b) ≤ (b + 1) * Fintype.card (Level 1 g) := by + let f : LevelLE 1 b → (Σ i : Fin (b + 1), Level 1 i) := + fun x => ⟨⟨energy x.val.val, Nat.lt_succ_of_le x.property⟩, ⟨x.val, rfl⟩⟩ + have hf : Function.Injective f := + fun _ _ h => Subtype.ext (congrArg (fun x : (Σ i : Fin (b + 1), Level 1 i) => x.2.val) h) + obtain ⟨j, _, hj⟩ := univ.exists_max_image (fun i : Fin (b + 1) => Fintype.card (Level 1 i)) + univ_nonempty + refine ⟨j.val, by have := j.isLt; omega, (Fintype.card_le_of_injective f hf).trans ?_⟩ + rw [Fintype.card_sigma] + simpa using sum_le_card_nsmul univ _ _ hj + +/-- Amplification with a loss polynomial in the target energy. -/ +theorem interleave_level (m e : ℕ) : + ∃ g ≤ m ^ 2 * e, Fintype.card (Level 1 e) ^ m ≤ 2 * (m ^ 2 * e + 1) * Fintype.card (Level 1 g) + := by + obtain ⟨g, hg, hb⟩ := largest_level (m ^ 2 * e) + refine ⟨g, hg, ?_⟩ + have hs := Fintype.card_le_of_injective _ (store_injective (m := m) (e := e)) + rw [Fintype.card_fun, Fintype.card_fin, Fintype.card_prod, Fintype.card_bool] at hs + rw [mul_assoc] + exact hs.trans (Nat.mul_le_mul_left 2 hb) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +/- +# Fixed-energy codes for station bits + +For each bit use either the inner or outer pair of four consecutive modes. +The two choices have equal energy. This gives a quadratic energy bound at +a single integer level without partition asymptotics. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +private theorem lex_one (a b : Mode 1) : toLex a < toLex b ↔ a.2 < b.2 := by + rw [Prod.Lex.toLex_lt_toLex, Subsingleton.elim a.1 b.1] + simp + +private theorem length_bound (xs : List (Mode 1)) (n : ℕ) + (h : xs.Pairwise fun a b => toLex a < toLex b) (hn : ∀ a ∈ xs, n ≤ a.2) : + xs.length ^ 2 + 2 * n * xs.length ≤ energy xs := by + induction xs generalizing n with + | nil => simp [energy] + | cons a l ih => + obtain ⟨ha, hl⟩ := List.pairwise_cons.mp h + have h₀ := hn a (by simp) + have h₁ := ih (n + 1) hl (fun b hb => Nat.succ_le_of_lt + (lt_of_le_of_lt h₀ ((lex_one a b).mp (ha b hb)))) + change (l.length + 1) ^ 2 + 2 * n * (l.length + 1) ≤ 2 * a.2 + 1 + energy l + nlinarith only [h₀, h₁] + +theorem Wedge.length_sq_le (w : Wedge 1) : w.val.length ^ 2 ≤ energy w.val := by + simpa using length_bound w.val 0 w.property (by simp) + +/-- In the case `_, []`, this construction gives `[]`. -/ +def encode : ℕ → List Bool → List (Mode 1) + | _, [] => [] + | j, b :: l => + (0, 4 * j + b.toNat) :: (0, 4 * j + 2 + (!b).toNat) :: encode (j + 1) l + +theorem encode_order (j : ℕ) (l : List Bool) : + (∀ a ∈ encode j l, 4 * j ≤ a.2) ∧ (encode j l).Pairwise (fun a b => toLex a < toLex b) := by + induction l generalizing j with + | nil => simp [encode] + | cons b l ih => + obtain ⟨hl, hp⟩ := ih (j + 1) + have h₁ : b.toNat ≤ 1 := by cases b <;> decide + have h₂ : (!b).toNat ≤ 1 := by cases b <;> decide + simp only [encode, List.forall_mem_cons, List.pairwise_cons] + refine ⟨⟨by omega, by omega, fun a ha => ?_⟩, + ⟨by rw [lex_one]; omega, fun a ha => ?_⟩, fun a ha => ?_, hp⟩ + all_goals have := hl a ha + · omega + · rw [lex_one]; omega + · rw [lex_one]; omega + +theorem encode_energy (j : ℕ) (l : List Bool) : + energy (encode j l) = 8 * l.length ^ 2 + 16 * j * l.length := by + induction l generalizing j with + | nil => simp [encode, energy] + | cons b l ih => + change 2 * (4 * j + b.toNat) + 1 + (2 * (4 * j + 2 + (!b).toNat) + 1 + energy (encode (j + + 1) l)) = _ + rw [ih, List.length_cons] + cases b <;> simp <;> ring + +theorem encode_injective (j : ℕ) : Function.Injective (encode j) := by + intro l l' he + induction l generalizing j l' with + | nil => cases l' <;> simp_all [encode] + | cons b l ih => + cases l' with + | nil => simp [encode] at he + | cons c l' => + simp only [encode, List.cons.injEq, Prod.mk.injEq, true_and] at he + have : b = c := by cases b <;> cases c <;> simp_all + rw [this, ih _ he.2.2] + +/-- An explicit injection of `n` bits into a single-species level of +physical energy `4n²` (doubled energy `8n²`). -/ +def bitCode (n : ℕ) : (Fin n → Bool) ↪ {w : Wedge 1 // energy w.val = 8 * n ^ 2} where + toFun x := ⟨⟨encode 0 (List.ofFn x), (encode_order _ _).2⟩, by simp [encode_energy]⟩ + inj' _ _ h := List.ofFn_inj.mp (encode_injective 0 (congrArg (fun x => x.val.val) h)) + +private theorem encode_length (k : ℕ) (xs : List Bool) : (encode k xs).length = 2 * xs.length := by + induction xs generalizing k with + | nil => rfl + | cons x xs ih => simp only [encode, List.length_cons, ih]; omega + +theorem bitCode_length {n : ℕ} (x : Fin n → Bool) : (bitCode n x).val.val.length = 2 * n := by + change (encode 0 (List.ofFn x)).length = _ + rw [encode_length, List.length_ofFn] + +private theorem encode_support (k : ℕ) (xs : List Bool) (j : Mode 1) (h : j ∈ encode k xs) : + j.2 < 4 * (k + xs.length) := by + induction xs generalizing k with + | nil => simp [encode] at h + | cons x xs ih => + simp only [encode, List.mem_cons] at h + rcases h with rfl | rfl | h + · cases x <;> simp; omega + · cases x <;> simp <;> omega + · have := ih _ h + simp only [List.length_cons] + omega + +theorem bitCode_support {n : ℕ} (x : Fin n → Bool) (j : Mode 1) (h : j ∈ (bitCode n x).val.val) : + j.2 < 4 * n := by + simpa using encode_support 0 (List.ofFn x) j h + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- +# Weighted input and output positions for two-site fusion + +At doubled energies `e,g` the positions have total weight +`√e + √g`. A slot of weight `t` can be isolated with a test +of doubled energy at most `(√e + √g) * t + 1`. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Width + +/-- Indexes the slot by the coordinates of `Bool × Mode 1`. -/ +abbrev Slot := Bool × Mode 1 + +/-- Input in wedge order, output in dual order. -/ +def slots (a b : Wedge 1) : List Slot := + a.val.map (false, ·) ++ b.val.reverse.map (true, ·) + +private theorem eq_wedge {a b : Wedge 1} (h : ∀ i, i ∈ a.val ↔ i ∈ b.val) : a = b := by + apply Subtype.ext + apply List.Perm.eq_of_pairwise (fun _ _ _ _ h₁ h₂ => (asymm h₁ h₂).elim) a.property b.property + exact (List.perm_ext_iff_of_nodup a.nodup b.nodup).mpr h + +theorem slots_inj {a b a' b' : Wedge 1} (h : (slots a b).Perm (slots a' b')) : + a = a' ∧ b = b' := by + constructor + · apply eq_wedge + intro i + simpa [slots] using h.mem_iff (a := (false, i)) + · apply eq_wedge + intro i + simpa [slots] using h.mem_iff (a := (true, i)) + +theorem slots_nodup (a b : Wedge 1) : (slots a b).Nodup := by + apply List.nodup_append.mpr + refine ⟨a.nodup.map (fun _ _ h => congrArg Prod.snd h), + (List.nodup_reverse.mpr b.nodup).map (fun _ _ h => congrArg Prod.snd h), ?_⟩ + simp + +variable (w : Bool → ℝ) + +/-- The quantity computed by `(2 * (x.2.2 : ℝ) + 1) / w x.1`. -/ +def weight (x : Slot) : ℝ := (2 * (x.2.2 : ℝ) + 1) / w x.1 + +/-- The quantity computed by `⌊(weight w x * w (!x.1) + 1) / 2⌋₊`. -/ +def other (x : Slot) := ⌊(weight w x * w (!x.1) + 1) / 2⌋₊ + +/-- Returns `x.2.2` when `x.1` holds, and `other w x` otherwise. -/ +def start (x : Slot) := if x.1 then x.2.2 else other w x + +/-- Returns `other w x` when `x.1` holds, and `x.2.2` otherwise. -/ +def order (x : Slot) := if x.1 then other w x else x.2.2 + +/-- The quantity computed by `2 * (start w x + order w x) + 1`. -/ +def cost (x : Slot) := 2 * (start w x + order w x) + 1 + +theorem weight_pos {x : Slot} (h : 0 < w x.1) : 0 < weight w x := + div_pos (by positivity) h + +private theorem weight_mul {x : Slot} (h : 0 < w x.1) : + weight w x * w x.1 = 2 * (x.2.2 : ℝ) + 1 := div_mul_cancel₀ _ h.ne' + +theorem same {x y : Slot} (hx : 0 < w x.1) (hs : y.1 = x.1) (h : weight w y ≤ weight w x) : + y.2.2 ≤ x.2.2 := by + simp only [weight, hs, div_le_div_iff_of_pos_right hx] at h + exact_mod_cast (show (y.2.2 : ℝ) ≤ x.2.2 by linarith) + +theorem different {x y : Slot} (hy : 0 < w y.1) (hs : y.1 = !x.1) + (h : weight w y ≤ weight w x) : y.2.2 < other w x := by + have hl := mul_le_mul_of_nonneg_right h hy.le + rw [weight_mul w hy, hs] at hl + have hu := Nat.lt_floor_add_one ((weight w x * w (!x.1) + 1) / 2) + unfold other + exact_mod_cast (show (y.2.2 : ℝ) < ⌊(weight w x * w (!x.1) + 1) / 2⌋₊ by linarith) + +private theorem cost_le (hw : ∀ i, 0 ≤ w i) {x : Slot} (hx : 0 < w x.1) : + (cost w x : ℝ) ≤ (w false + w true) * weight w x + 1 := by + have hother : (other w x : ℝ) ≤ (weight w x * w (!x.1) + 1) / 2 := + Nat.floor_le (by have := hw (!x.1); have := weight_pos w hx; positivity) + have h := weight_mul w hx + obtain ⟨_ | _, x⟩ := x <;> simp [cost, start, order] at * <;> linarith + +private theorem cost_sum (hw : ∀ i, 0 ≤ w i) (xs : List Slot) (hx : ∀ x ∈ xs, 0 < w x.1) : + ((xs.map (cost w)).sum : ℝ) ≤ (w false + w true) * (xs.map (weight w)).sum + xs.length := by + induction xs with + | nil => simp + | cons x xs ih => + simp only [List.forall_mem_cons] at hx + have h := add_le_add (cost_le w hw hx.1) (ih hx.2) + simp only [List.map_cons, List.sum_cons, Nat.cast_add, List.length_cons, Nat.cast_one, mul_add] + linarith + +private theorem side_sum (i : Bool) (xs : List (Mode 1)) : + ((xs.map (i, ·)).map (weight w)).sum = energy xs / w i := by + induction xs with + | nil => simp [energy] + | cons x xs ih => + rw [List.map_cons, List.map_cons, List.sum_cons, ih] + simp [weight, energy, add_div] + +variable (a b : Wedge 1) (ha : w false = Real.sqrt (energy a.val)) + (hb : w true = Real.sqrt (energy b.val)) + +include ha hb + +theorem slots_valid (x : Slot) (hx : x ∈ slots a b) : 0 < w x.1 := by + have pos (s : List (Mode 1)) (i : Mode 1) (hi : i ∈ s) : 0 < Real.sqrt (energy s) := by + have hm : 2 * i.2 + 1 ≤ energy s := List.le_sum_of_mem (List.mem_map_of_mem hi) + exact Real.sqrt_pos.mpr (Nat.cast_pos.mpr (by omega)) + simp only [slots, List.mem_append, List.mem_map, List.mem_reverse] at hx + rcases hx with ⟨i, hi, rfl⟩ | ⟨i, hi, rfl⟩ + · rw [ha]; exact pos _ _ hi + · rw [hb]; exact pos _ _ hi + +theorem slots_weight : ((slots a b).map (weight w)).sum = w false + w true := by + have he (x : ℕ) : (x : ℝ) / Real.sqrt x = Real.sqrt x := by + by_cases h : x = 0 + · simp [h] + · rw [div_eq_iff (by positivity)] + exact (Real.mul_self_sqrt (by positivity)).symm + simp only [slots, List.map_append, List.sum_append, side_sum, ha, hb, + show energy b.val.reverse = energy b.val by simp [energy], he] + +theorem slots_cost : (((slots a b).map (cost w)).sum : ℝ) ≤ + (w false + w true) ^ 2 + (w false + w true) := by + have hp (i : Bool) : 0 ≤ w i := by cases i <;> simp [ha, hb] + have h := cost_sum w hp _ (slots_valid w a b ha hb) + rw [slots_weight w a b ha hb, ← pow_two] at h + refine h.trans (add_le_add_right ?_ _) + have len (z : Wedge 1) : (z.val.length : ℝ) ≤ Real.sqrt (energy z.val) := by + apply (Real.le_sqrt (by positivity) (by positivity)).mpr + exact_mod_cast z.length_sq_le + simpa [slots, ha, hb] using add_le_add (len a) (len b) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Width +end + +section +/- +# Sharp common growth rate for one-species levels + +The supremum of the normalized log dimensions is finite and positive. +Interleaving a fixed level approaching this supremum works at every +sufficiently large target width, with only logarithmic loss. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere +open Real Filter + +/-- The quantity computed by `log (Fintype.card (Level 1 e)) / sqrt e`. -/ +noncomputable def rate (e : ℕ) : ℝ := log (Fintype.card (Level 1 e)) / sqrt e + +/-- The supremum of `(Set.range rate)`. -/ +noncomputable def entropy : ℝ := sSup (Set.range rate) + +private theorem coarse (e : ℕ) : log (Fintype.card (Level 1 e)) ≤ 2 * sqrt e := by + by_cases h : Fintype.card (Level 1 e) = 0 + · simp [h] + · apply (log_le_iff_le_exp (by exact_mod_cast Nat.pos_of_ne_zero h)).mpr + simpa using card_level 1 e + +private theorem rate_bdd : BddAbove (Set.range rate) := by + refine ⟨2, ?_⟩ + rintro _ ⟨e, rfl⟩ + by_cases h : e = 0 + · simp [rate, h] + · exact (div_le_iff₀ (by positivity)).mpr (coarse e) + +theorem entropy_pos : 0 < entropy := by + have h : 1 < Fintype.card (Level 1 8) := by + have hb := Fintype.card_le_of_injective (bitCode 1) (bitCode 1).injective + change 2 ≤ Fintype.card (Level 1 8) + simpa [Fintype.card_fun] using hb + have hr : 0 < rate 8 := div_pos (log_pos (by exact_mod_cast h)) (by positivity) + exact hr.trans_le (le_csSup rate_bdd (Set.mem_range_self 8)) + +theorem entropy_bound (e : ℕ) : log (Fintype.card (Level 1 e)) ≤ entropy * sqrt e := by + by_cases h : e = 0 + · simpa [h] using coarse e + · exact (div_le_iff₀ (by positivity)).mp (le_csSup rate_bdd (Set.mem_range_self e)) + +theorem card_levelLE_exp (e : ℕ) : + (Fintype.card (LevelLE 1 e) : ℝ) ≤ (e + 1) * exp (entropy * sqrt e) := by + obtain ⟨g, hg, hb⟩ := largest_level e + calc + _ ≤ ((e : ℝ) + 1) * Fintype.card (Level 1 g) := by exact_mod_cast hb + _ ≤ ((e : ℝ) + 1) * exp (entropy * sqrt g) := by + gcongr + exact le_exp_of_log_le (entropy_bound g) + _ ≤ _ := by have := entropy_pos; gcongr + +private theorem negligible (C ε : ℝ) (hε : 0 < ε) : + ∀ᶠ t : ℝ in atTop, C + log (2 * (t ^ 2 + 1)) ≤ ε * t := by + filter_upwards [eventually_ge_atTop 1, eventually_ge_atTop (2 * (C + log 4) / ε), + isLittleO_log_id_atTop.bound (by positivity : 0 < ε / 4)] with t ht hc hl + rw [div_le_iff₀ hε] at hc + have h : log (2 * (t ^ 2 + 1)) ≤ log 4 + 2 * log t := by + calc + _ ≤ log (4 * t ^ 2) := log_le_log (by positivity) (by nlinarith) + _ = _ := by rw [log_mul (by norm_num) (by positivity), log_pow]; norm_num + simp only [id_eq, norm_eq_abs, abs_of_nonneg (log_nonneg ht), abs_of_nonneg (by linarith : 0 ≤ t)] + at hl + linarith + +private theorem entropy_reaches {a : ℝ} (ha : 0 < a) (ha' : a < entropy) : + ∀ᶠ t : ℝ in atTop, ∃ e : ℕ, (e : ℝ) ≤ t ^ 2 ∧ a * t ≤ log (Fintype.card (Level 1 e)) := by + obtain ⟨_, ⟨e, rfl⟩, he⟩ := exists_lt_of_lt_csSup (Set.range_nonempty rate) ha' + have hpos : 0 < rate e := ha.trans he + have he0 : e ≠ 0 := by rintro rfl; simp [rate] at hpos + have hs : 0 < sqrt (e : ℝ) := by positivity + have hrate : rate e * sqrt e = log (Fintype.card (Level 1 e)) := div_mul_cancel₀ _ hs.ne' + have hn : 0 < Fintype.card (Level 1 e) := by + by_contra! h + have : Fintype.card (Level 1 e) = 0 := by omega + simp [rate, this] at hpos + filter_upwards [eventually_ge_atTop 0, + negligible (log (Fintype.card (Level 1 e))) (rate e - a) (sub_pos.mpr he)] with t ht hl + let m := ⌊t / sqrt e⌋₊ + have hu : (m : ℝ) * sqrt e ≤ t := (le_div_iff₀ hs).mp (Nat.floor_le (by positivity)) + have hv : t ≤ ((m : ℝ) + 1) * sqrt e := (div_le_iff₀ hs).mp (Nat.lt_floor_add_one _).le + have hb : (m : ℝ) ^ 2 * e ≤ t ^ 2 := by + rw [← sq_sqrt (Nat.cast_nonneg e), ← mul_pow] + exact pow_le_pow_left₀ (by positivity) hu _ + obtain ⟨g, hg, hdim⟩ := interleave_level m e + refine ⟨g, le_trans (by exact_mod_cast hg) hb, ?_⟩ + have hng : 0 < Fintype.card (Level 1 g) := by + have := (pow_pos hn m).trans_le hdim + exact Nat.pos_of_mul_pos_left this + have hd : (Fintype.card (Level 1 e) : ℝ) ^ m ≤ 2 * (t ^ 2 + 1) * Fintype.card (Level 1 g) := by + calc + _ ≤ 2 * ((m : ℝ) ^ 2 * e + 1) * Fintype.card (Level 1 g) := by exact_mod_cast hdim + _ ≤ _ := by gcongr + have hlog := log_le_log (by positivity) hd + rw [log_pow, log_mul (by positivity) (by positivity)] at hlog + have hlow : rate e * t ≤ ((m : ℝ) + 1) * log (Fintype.card (Level 1 e)) := by + rw [← hrate, mul_left_comm] + exact mul_le_mul_of_nonneg_left hv hpos.le + linarith + +/-- One level below any sufficiently large quadratic cutoff nearly attains +the common log-dimension bound at the scale of the cutoff. -/ +theorem entropy_attained {δ : ℝ} (hδ : 0 < δ) : + ∀ᶠ t : ℝ in atTop, ∃ e : ℕ, (e : ℝ) ≤ t ^ 2 ∧ + (entropy - δ) * t ≤ log (Fintype.card (Level 1 e)) := by + let a := max (entropy - δ) (entropy / 2) + have ha : 0 < a := (half_pos entropy_pos).trans_le (le_max_right _ _) + have hb : a < entropy := max_lt (sub_lt_self _ hδ) (half_lt_self entropy_pos) + filter_upwards [eventually_ge_atTop 0, entropy_reaches ha hb] with t ht h + obtain ⟨e, he, hd⟩ := h + exact ⟨e, he, (mul_le_mul_of_nonneg_right (le_max_left _ _) ht).trans hd⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- +# Integral tests for the two-site fusion map + +The test with parameters `a,d` represents the Laurent polynomial +`X^(-a-1) (1-X⁻¹)^d`. Its leading positions at zero and one have +indices `a` and `d` respectively. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Width + +variable (R : Type*) [CommRing R] + +/-- The quantity computed by `∑ f ∈ Finset.range (d + 1), (-1 : R) ^ f * d.choose f * pairing R +(.origin, 0, a + f) y`. -/ +def test (a d : ℕ) (y : Mark 1) : R := + ∑ f ∈ Finset.range (d + 1), (-1 : R) ^ f * d.choose f * pairing R (.origin, 0, a + f) y + +theorem test_origin (a d : ℕ) (y : Mode 1) : test R a d (.origin, y) = 0 := by + have he (m : ℕ) : pairing R (.origin, 0, m) (.origin, y) = 0 := by + change (if 0 = y.1 then (0 : R) else 0) = _ + simp + simp [test, he] + +private theorem test_infinity (a d : ℕ) (y : Mode 1) (hy : y.2 ≤ a) : + test R a d (.infinity, y) = if a = y.2 then 1 else 0 := by + have he (m : ℕ) : pairing R (.origin, 0, m) (.infinity, y) = + if m = y.2 then 1 else 0 := by + change (if 0 = y.1 then (if m = y.2 then (1 : R) else 0) else 0) = _ + rw [ite_eq_left (Subsingleton.elim _ _)] + unfold test + rw [Finset.sum_eq_single 0] + · simp [he] + · intro b _ hb + rw [he, ite_eq_right (by omega), mul_zero] + · simp + +private theorem test_middle (a d : ℕ) (y : Mode 1) (hy : y.2 ≤ d) : + test R a d (.middle, y) = if d = y.2 then 1 else 0 := by + have he (m : ℕ) : pairing R (.origin, 0, m) (.middle, y) = + (-1 : R) ^ y.2 * (m + y.2).choose y.2 := by + change (if 0 = y.1 then (-1 : R) ^ y.2 * (m + y.2).choose y.2 else 0) = _ + rw [ite_eq_left (Subsingleton.elim _ _)] + have e : test R a d (.middle, y) = (-1 : R) ^ y.2 * ((-1) ^ d * (a + y.2).choose (d + a)) := by + unfold test + rw [← binom_difference, Finset.mul_sum] + apply Finset.sum_congr rfl + intro f _ + have h : (a + f + y.2).choose y.2 = (a + y.2 + f).choose (f + a) := by + rw [← Nat.choose_symm (by omega : y.2 ≤ a + f + y.2)] + congr 1 <;> omega + rw [he, h] + ring + rw [e] + by_cases h : d = y.2 + · rw [h, Nat.add_comm y.2 a, Nat.choose_self, Nat.cast_one, mul_one, ← mul_pow] + simp + · rw [ite_eq_right h, Nat.choose_eq_zero_of_lt (by omega : a + y.2 < d + a)] + simp + +/-- The value specified by `(if x.1 then .infinity else .middle, x.2)`. -/ +def mark (x : Slot) : Mark 1 := (if x.1 then .infinity else .middle, x.2) + +private theorem mode_eq (x y : Mode 1) : x = y ↔ x.2 = y.2 := + ⟨fun h => congrArg _ h, fun h => Prod.ext (Subsingleton.elim _ _) h⟩ + +/-- At equal or smaller weight only the designated slot survives. -/ +theorem test_pivot (w : Bool → ℝ) (x y : Slot) (hx : 0 < w x.1) (hy : 0 < w y.1) + (h : weight w y ≤ weight w x) : + test R (start w x) (order w x) (mark y) = if x = y then 1 else 0 := by + obtain ⟨_ | _, i⟩ := x <;> obtain ⟨_ | _, j⟩ := y + · have := same w (y := (false, j)) hx rfl h + simp [start, order, mark, test_middle _ _ _ _ this, mode_eq] + · have hl := different w hy rfl h + simp [start, order, mark, test_infinity _ _ _ _ hl.le, ne_of_gt hl] + · have hl := different w hy rfl h + simp [start, order, mark, test_middle _ _ _ _ hl.le, ne_of_gt hl] + · have := same w (y := (true, j)) hx rfl h + simp [start, order, mark, test_infinity _ _ _ _ this, mode_eq] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Width +end + +/- +# Transposition at a seam + +Evaluate fusion in the ordinary wedge basis by placing the output modes +last, in reverse order. Inversion negates each pairing. Reversing the +entire Wick list then cancels the signs pair by pair. This gives a single +integral lowering operator, with scalar one in every characteristic. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable (R : Type*) [CommRing R] {r : ℕ} + +/-- Transforms the indexed data by `x.map (c, ·)`. -/ +def marks (c : Chart) (x : List (Mode r)) : List (Mark r) := x.map (c, ·) + +/-- Matrix entry of the two-site fusion at offsets zero and one. +Contractions to the output block are the two translation coefficients. +Its reversed order gives the ordinary dual wedge pairing. -/ +def fusion (a x b : List (Mode r)) : R := + wick (pairing R) (marks .origin a ++ marks .middle x ++ marks .infinity b.reverse) + +theorem fusion_reflect (a x b : List (Mode r)) : + fusion R a x b = + wick (pairing R) (marks .origin b ++ marks .dual x.reverse ++ marks .infinity a.reverse) := by + let l := marks .origin a ++ marks .middle x ++ marks .infinity b.reverse + have he : (l.map reflect).reverse = + marks .origin b ++ marks .dual x.reverse ++ marks .infinity a.reverse := by + simp [l, marks, List.map_map, Function.comp_def, reflect, Chart.reflect] + rw [← he, wick_reverse (pairing_skew R), wick_map] + simp only [pairing_reflect, neg_neg] + rfl + +private theorem transform (x p : List (Mode r)) : + ∃ g : Wedge r →₀ R, + (∀ y ∈ g.support, energy y.val ≤ energy p + energy x ∧ + y.val.length = p.length + x.length) ∧ + ∀ a b : List (Mark r), + wick (pairing R) (a ++ marks .middle p ++ marks .dual x ++ b) = + Finsupp.linearCombination R + (fun y : Wedge r => wick (pairing R) (a ++ marks .middle y.val ++ b)) g := by + refine substitute_modes (pairing_skew R) (pairing_self R) + (fun i => (.dual, i)) (fun i => (.middle, i)) (fun i => 2 * i.2 + 1) ?_ x p + intro z + refine ⟨Finset.range (z.2 + 1), lower R z.2, fun f => (z.1, f), ?_, pairing_lower R z⟩ + simp only [Finset.mem_range] + omega + +/-- Matrix coefficient with a superposition of middle states. -/ +def entry (a b : Wedge r) : (Wedge r →₀ R) →ₗ[R] R := + Finsupp.linearCombination R (fun x => fusion R a.val x.val b.val) + +/-- The same operator transposes every fusion matrix. Each output of a +basis input preserves exterior degree and weakly lowers energy. -/ +theorem seam (r : ℕ) : + ∃ S : (Wedge r →₀ R) →ₗ[R] (Wedge r →₀ R), + (∀ x y : Wedge r, y ∈ (S (Finsupp.single x 1)).support → + energy y.val ≤ energy x.val ∧ y.val.length = x.val.length) ∧ + ∀ a b : Wedge r, entry R a b = (entry R b a).comp S := by + choose g hg he using fun x : Wedge r => transform R x.val.reverse [] + refine ⟨Finsupp.linearCombination R g, ?_, ?_⟩ + · intro x y hy + simp only [Finsupp.linearCombination_single, one_smul] at hy + simpa [energy] using hg x y hy + · intro a b + apply Finsupp.lhom_ext + intro x t + simp only [entry, LinearMap.comp_apply, Finsupp.linearCombination_single, map_smul] + rw [fusion_reflect] + simpa only [marks, List.map_nil, List.append_nil, fusion] using + congrArg (t • ·) (he x (marks .origin b.val) (marks .infinity a.val.reverse)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +/-- The empty wedge is the only state at zero energy. -/ +def vac (r : ℕ) : Level r 0 := ⟨⟨[], by simp⟩, rfl⟩ + +theorem eq_vac {r : ℕ} (x : Level r 0) : x = vac r := by + apply Subtype.ext + apply Subtype.ext + have h := x.2 + cases e : x.val.val with + | nil => rfl + | cons i s => simp [e, energy] at h + +instance (r : ℕ) : Unique (Level r 0) where + default := vac r + uniq := eq_vac + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Accounting.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Accounting.lean new file mode 100644 index 0000000000..f2675b639f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Accounting.lean @@ -0,0 +1,1047 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Pull +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Ledger + +/-! # A crossing in two adjacent cells -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion +variable {F T X Y E : Type} [Field F] {r t P : ℕ} + +open scoped Classical in +theorem Cell.test_mul_left (P : ℕ) (x : X) (c : Cell F r t T E X) (h : E → Wedge r) + (k : F) (f : Test F r t) : + c.test P x h (fun a b => k * f a b) = k * c.test P x h f := + batch_mul_left _ _ _ _ _ + +open scoped Classical in +theorem Cell.test_mul_right (P : ℕ) (x : X) (c : Cell F r t T E X) (h : E → Wedge r) + (k : F) (f : Test F r t) : + c.test P x h (fun a b => f a b * k) = c.test P x h f * k := + batch_mul_right _ _ _ _ _ + +open scoped Classical in +/-- The condition `∀ j ∈ l, j.1 ≠ i` on the specified data. -/ +def Unused (i : E) (l : List (E × F)) : Prop := ∀ j ∈ l, j.1 ≠ i + +open scoped Classical in +theorem ends_update (i : E) (h : E → Wedge r) (v : Wedge r) (l : List (E × F)) (he : Unused i l) : + ends P (Function.update h i v) l = ends P h l := by + apply List.flatMap_congr + intro j hj + rw [Function.update_of_ne (he j hj)] + +open scoped Classical in +theorem Cell.eval_update (c : Cell F r t T E X) (x : X) (i : E) (h : E → Wedge r) + (v : Wedge r) (he : Unused i c.ports) : + c.eval P x (Function.update h i v) = c.eval P x h := by + simp only [Cell.eval, ends_update _ _ _ _ he] + +open scoped Classical in +/-- A cell with one designated seam temporarily removed. -/ +structure Socket (F : Type) (r t : ℕ) (T E X : Type) where + /-- The `Socket` component of type `List (E × F)`. -/ + before : List (E × F) + /-- The `Socket` component of type `List (E × F)`. -/ + after : List (E × F) + /-- The `Socket` component of type `List (Station F r t T X)`. -/ + stations : List (Station F r t T X) + +namespace Socket + +variable (v : Socket F r t T E X) + +open scoped Classical in +/-- Concatenates the components in the order `⟨v.before ++ v.after, v.stations⟩`. -/ +def base : Cell F r t T E X := ⟨v.before ++ v.after, v.stations⟩ +open scoped Classical in +/-- Concatenates the components in the order `⟨v.before ++ (i, z) :: v.after, v.stations⟩`. -/ +def plug (i : E) (z : F) : Cell F r t T E X := ⟨v.before ++ (i, z) :: v.after, v.stations⟩ + +open scoped Classical in +/-- The quantity computed by `(-1) ^ ((m + sumA v.stations + portWeight d v.before) * e)`. -/ +def sign (d : E → ℕ) (e m : ℕ) : F := + (-1) ^ ((m + sumA v.stations + portWeight d v.before) * e) + +open scoped Classical in +theorem plugged {e : ℕ} (x : X) (d : E → ℕ) (i : E) (z : F) (h : E → Wedge r) + (hh : ∀ j, j ≠ i → energy (h j).val = d j) (hi : Unused i v.base.ports) + (a : Level r e) (f : Test F r t) (hf : Signed f) : + (v.plug i z).test P x (Function.update h i a.val) f = + v.sign d e 0 * v.base.test P x h (lead (z ^ P) a.val f) := by + change Unused i (v.before ++ v.after) at hi + have hpre : Unused i v.before := fun j hj => hi j (List.mem_append_left _ hj) + have eq := port_front P x v.stations (Function.update h i a.val) v.before v.after (i, z) f hf + rw [ends_update _ _ _ _ hpre, ends_update _ _ _ _ hi, Function.update_self, + a.property, weight_ends P d h v.before (fun j hj => hh _ (hpre j hj))] at eq + simpa only [plug, sign, base, Cell.test, lead, zero_add, List.append_assoc] using eq + +open scoped Classical in +theorem plugged_insert {e : ℕ} (x : Y) (π : Y → X) (u : Station F r t T Y) + (d : E → ℕ) (i : E) (z : F) (h : E → Wedge r) + (hh : ∀ j, j ≠ i → energy (h j).val = d j) (hi : Unused i v.base.ports) + (a : Level r e) (f : Test F r t) (hf : Signed f) : + (((v.plug i z).pull π id).insert u).test P x (Function.update h i a.val) f = + v.sign d e u.a * v.base.test P (π x) h (frontOne P x u (lead (z ^ P) a.val f)) := by + let w : Socket F r t T E Y := ⟨v.before, v.after, u :: v.stations.map (Station.pull · π id)⟩ + have eq := w.plugged x d i z h hh hi a f hf (P := P) + have es : w.sign d e 0 = v.sign d e u.a := by + simp [sign, w, sumA, Station.pull, Function.comp_def] + have eb : w.base = (v.base.pull π id).insert u := rfl + rw [es, eb, Cell.test_insert, Cell.test_pull] at eq + exact eq + +end Socket +namespace Passage + +variable {u : Station F r t T X} (s : Passage P u) +variable (v w : Cell F r t T E X) (d : E → ℕ) + +open scoped Classical in +/-- The data for the fits construction, including `near`, `far`, `a`, `b`, `c`. -/ +structure Fits : Prop where + near : v.Fixed P (s.A.erase (s.z ^ P)) s.B + far : ∃ D, w.Fixed P (s.C.erase (s.y ^ P)) D + a : v.bigA d = s.a + b : sumB v.stations = s.b + c : w.bigA d = s.c + +open scoped Classical in +private theorem advance_cells (p l : ℕ) [ExpChar F p] (hP : P = p ^ l) (hs : s.Fits v w d) + (k k' : T) : + let S := lowering F r + let f := s.weights p l hP + ∀ (x : X) (h : E → Wedge r), + (∀ j ∈ v.ports, energy (h j.1).val = d j.1) → (∀ j ∈ w.ports, energy (h j.1).val = d j.1) → + (∑ b : Level r s.e, v.test P x h (frontOne P x u (lead (s.z ^ P) b.val s.coeff)) * + w.test P x h (lead (s.y ^ P) b.val forms)) = + ∑ i : s.Branch, f i * ∑ y : Level t u.b, ∑ b : Level r i.height, + v.test P x h (frontOne P (x, y) (s.leaves k i) (lead (s.z ^ P) b.val forms)) * + w.test P x h (frontOne P (x, y) (s.arrives k' S i) (lead (s.y ^ P) b.val forms)) := by + intro S f + have hf := s.advance p l hP k k' + obtain ⟨D, hD⟩ := hs.far + intro x h hv hw + have e := v.test_congr P x d h hv hs.near (fun a b ha hb wa wb => + w.test_congr P x d h hw hD (fun c d hc _ wc _ => + hf x a b c d ha hb hc (wa.trans hs.a) (wb.trans hs.b) (wc.trans hs.c))) + simpa only [Cell.test_sum, Cell.test_mul_left, Cell.test_mul_right] using e + +variable (L R : Socket F r t T E X) (j : E) + +open scoped Classical in +/-- The value specified by `((L.plug j s.z).pull Prod.fst id).insert (s.leaves k i)`. -/ +def left (k : T) (i : s.Branch) := + ((L.plug j s.z).pull Prod.fst id).insert (s.leaves k i) + +open scoped Classical in +/-- The value specified by `((R.plug j s.y).pull Prod.fst id).insert (s.arrives k S i)`. -/ +def right (k : T) (S : Lower F r) (i : s.Branch) := + ((R.plug j s.y).pull Prod.fst id).insert (s.arrives k S i) + +open scoped Classical in +/-- The value specified by `L.sign d s.e u.a * R.sign d s.e 0 * s.weights p l hP i / (L.sign d +i.height 0 * R.sign d i.height i.2.2.1.val)`. -/ +def signed (p l : ℕ) [ExpChar F p] (hP : P = p ^ l) (i : s.Branch) : F := + L.sign d s.e u.a * R.sign d s.e 0 * s.weights p l hP i / + (L.sign d i.height 0 * R.sign d i.height i.2.2.1.val) + +open scoped Classical in +/-- Both endpoints keep their original seam order. The signs are +absorbed into the scalar weight of the branch. -/ +theorem crossing (p l : ℕ) [ExpChar F p] (hP : P = p ^ l) (hs : s.Fits L.base R.base d) + (hl : Unused j L.base.ports) (hr : Unused j R.base.ports) (k k' : T) : + let S := lowering F r + let f := s.signed d L R p l hP + ∀ (x : X) (h : E → Wedge r), + (∀ i, i ≠ j → energy (h i).val = d i) → + (∑ a : Level r s.e, + ((L.plug j s.z).insert u).test P x (Function.update h j a.val) s.coeff * + (R.plug j s.y).eval P x (Function.update h j a.val)) = + ∑ i : s.Branch, f i * ∑ y : Level t u.b, ∑ a : Level r i.height, + (s.left L j k i).eval P (x, y) (Function.update h j a.val) * + (s.right R j k' S i).eval P (x, y) (Function.update h j a.val) := by + intro S coeff + let f := s.weights p l hP + have hf := s.advance_cells L.base R.base d p l hP hs k k' + let c := L.sign d s.e u.a * R.sign d s.e 0 + let b (i : s.Branch) := L.sign d i.height (s.leaves k i).a * R.sign d i.height (s.arrives k' S + i).a + have hb (i) : b i ≠ 0 := by simp [b, Socket.sign] + intro x h he + rw [show coeff = (fun i => c * f i / b i) from rfl] + have a (v : Level r s.e) : + ((L.plug j s.z).insert u).test P x (Function.update h j v.val) s.coeff * + (R.plug j s.y).eval P x (Function.update h j v.val) = c * + (L.base.test P x h (frontOne P x u (lead (s.z ^ P) v.val s.coeff)) * + R.base.test P x h (lead (s.y ^ P) v.val forms)) := by + have hx := L.plugged_insert x id u d j s.z h he hl v s.coeff (coefficient_signed _ _ _ _ _) (P + := P) + rw [Cell.pull_id] at hx + have hy := R.plugged x d j s.y h he hr v forms forms_signed (P := P) + change _ * (R.plug j s.y).test P x _ forms = _ + rw [hx, hy, mul_mul_mul_comm] + rfl + have b' (i : s.Branch) (y : Level t u.b) (v : Level r i.height) : + (s.left L j k i).eval P (x, y) (Function.update h j v.val) * + (s.right R j k' S i).eval P (x, y) (Function.update h j v.val) = b i * + (L.base.test P x h (frontOne P (x, y) (s.leaves k i) (lead (s.z ^ P) v.val forms)) * + R.base.test P x h (frontOne P (x, y) (s.arrives k' S i) (lead (s.y ^ P) v.val forms))) + := by + have hx := L.plugged_insert (x, y) Prod.fst (s.leaves k i) d j s.z h he hl v forms forms_signed + (P := P) + have hy := R.plugged_insert (x, y) Prod.fst (s.arrives k' S i) d j s.y h he hr v forms + forms_signed (P := P) + change (s.left L j k i).test P (x, y) _ forms * (s.right R j k' S i).test P (x, y) _ forms = _ + rw [left, right, hx, hy, mul_mul_mul_comm] + simp only [a, b', ← mul_sum] + rw [hf x h (fun i hi => he _ (hl i hi)) (fun i hi => he _ (hr i hi)), mul_sum] + exact sum_congr rfl fun i _ => by rw [← mul_assoc, ← mul_assoc, div_mul_cancel₀ _ (hb i)] + +end Passage +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Exact local transformations inside a closed sewn surface -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Function Motion + +open scoped Classical in +/-- The data for the scene construction, including `cell`, `level`. -/ +structure Scene (F : Type) (r t : ℕ) (T V E X : Type) where + /-- The `Scene` component of type `V → Cell F r t T E X`. -/ + cell : V → Cell F r t T E X + /-- The level at each coordinate of type `E → ℕ`. -/ + level : E → ℕ + +variable {F T V E X : Type} [Field F] [Fintype V] [Fintype E] {r t P : ℕ} + +namespace Scene + +variable (C : Scene F r t T V E X) + +open scoped Classical in +/-- Computes the value by the application `eval P C.cell C.level x`. -/ +def value (P : ℕ) (x : X) : F := eval P C.cell C.level x + +open scoped Classical in +/-- The indexed operation `contractGraph (update (fun i => (C.cell i).eval P x) v (fun h => +(C.cell v).test P x h f)) C.level`. -/ +def observe (P : ℕ) (v : V) (f : Test F r t) (x : X) : F := + contractGraph (update (fun i => (C.cell i).eval P x) v (fun h => (C.cell v).test P x h f)) C.level + +open scoped Classical in +/-- Uses `⟨update C.cell v c, C.level⟩` as the representation. -/ +def put (v : V) (c : Cell F r t T E X) : Scene F r t T V E X := ⟨update C.cell v c, C.level⟩ + +open scoped Classical in +theorem observe_forms (v : V) (x : X) : C.observe P v forms x = C.value P x := by + unfold observe + change contractGraph (update _ _ ((C.cell v).eval P x)) _ = _ + rw [update_eq_self] + rfl + +open scoped Classical in +/-- Change the local contraction while leaving all shared levels fixed. -/ +theorem replace {I : Type} [Fintype I] (v : V) (f : Test F r t) + (w : I → F) (c : I → Cell F r t T E X) (g : I → Test F r t) + (h : ∀ (x : X) (a : E → Wedge r), (∀ e, energy (a e).val = C.level e) → + (C.cell v).test P x a f = ∑ i, w i * (c i).test P x a (g i)) (x : X) : + C.observe P v f x = ∑ i, w i * (C.put v (c i)).observe P v (g i) x := by + unfold observe + rw [contractGraph_replace _ _ v w (fun i a => (c i).test P x a (g i)) (by simpa using h x)] + refine sum_congr rfl fun i _ => congrArg (w i * ·) ?_ + unfold put + simp only [update_self, update_idem] + congr 1 + funext y + by_cases hy : y = v + · subst y; simp + · simp [hy] + +open scoped Classical in +/-- Interpolate a cell simultaneously for all exterior assignments. -/ +theorem reconstruct (p l : ℕ) [ExpChar F p] (v : V) + (S B seams : Finset F) (hB : B ⊆ S) (hs : seams ⊆ S) (collector : F) + (hc : collector ∈ S) (hc' : collector ∉ seams) (g L : ℕ) (hg : seams.card ≤ g) + (z : F) (hz : z ∉ S) (st : ∀ a ∈ (C.cell v).stations, a.pos = z ∨ a.pos ∈ B) + (pt : ∀ i ∈ (C.cell v).ports, i.2 ∈ S) : + let P := p ^ l + let D := poleOrder P ((C.cell v).orderA C.level) (C.cell v).orderB B + ∃ w : (Σ y : S, Fin (orders seams collector D g L y.val)) → F, ∀ x, + C.value P x = ∑ j, w j * C.observe P v + (coefficient P (powered P S) B j.1.val ((j.2.val : ℤ) - D j.1.val)) x := by + intro P D + obtain ⟨w, hw⟩ := reconstruct_cells (r := r) (t := t) p l ((C.cell v).orderA C.level) + (C.cell v).orderB S B seams hB hs collector hc hc' g L hg z hz + refine ⟨w, fun x => ?_⟩ + exact contractGraph_replace _ _ v w _ (fun h hh => hw _ _ rfl rfl st pt x h (fun j _ => hh _)) + +open scoped Classical in +/-- Rotate two blocks of stations into position for fusion. -/ +theorem rotate (v : V) (f : Test F r t) (hf : Signed f) + (a b c : List (Station F r t T X)) (h : (C.cell v).stations = a ++ b ++ c) (x : X) : + C.observe P v f x = (-1 : F) ^ (sumA a * sumA b + sumB a * sumB b) * + (C.put v ⟨(C.cell v).ports, b ++ a ++ c⟩).observe P v f x := by + have e := C.replace (P := P) v f (fun _ : Unit => (-1 : F) ^ (sumA a * sumA b + sumB a * sumB b)) + (fun _ => ⟨(C.cell v).ports, b ++ a ++ c⟩) (fun _ => f) (by + intro x h' _ + rw [Fintype.sum_unique, show C.cell v = ⟨(C.cell v).ports, a ++ b ++ c⟩ by rw [← h]] + exact Surface.rotate P x a b c _ _ _ hf) x + simpa using e + +open scoped Classical in +theorem merge (p l : ℕ) [ExpChar F p] (v : V) (c : Cell F r t T E X) + (a b : Station F r t T X) (h : C.cell v = (c.insert b).insert a) (k : T) + (A B : Finset F) (ha : a.pos ^ (p ^ l) ∈ A) (ha' : a.pos ∈ B) (hb : b.pos ^ (p ^ l) ∉ A) + (hb' : b.pos ∉ B) (hc : c.Fixed (p ^ l) (A.erase (a.pos ^ (p ^ l))) (B.erase a.pos)) + (j : ℤ) (x : X) : + let P := p ^ l + C.observe P v (coefficient P A B a.pos j) x = + ∑ q : merges P a b ((C.cell v).orderA C.level) (C.cell v).orderB j, + (C.put v (c.insert (mergeAt a b k q))).value P x := by + intro P + let I := merges P a b ((C.cell v).orderA C.level) (C.cell v).orderB j + have e := C.replace (P := P) v (coefficient P A B a.pos j) (fun _ : I => 1) + (fun q => c.insert (mergeAt a b k q)) (fun _ => forms) (by + intro x u hu + have e := c.merge p l C.level a b k A B ha ha' hb hb' hc j x u (fun _ _ => hu _) + rw [← h] at e + dsimp only at e + rw [← sum_attach] at e + simp only [one_mul] + exact e) x + simpa only [one_mul, observe_forms] using e + +variable {u : Station F r t T X} (s : Passage P u) (v w : V) (j : E) +variable (L R : Socket F r t T E X) (k k' : T) + +open scoped Classical in +/-- Replace both ends of one seam. Other cells ignore the new private wire. -/ +def crossed (S : Lower F r) (i : s.Branch) : Scene F r t T V E (X × Level t u.b) where + cell := update (update (fun z => (C.cell z).pull Prod.fst id) v (s.left L j k i)) w + (s.right R j k' S i) + level := update C.level j i.height + +open scoped Classical in +/-- The outside sum indexes orders, levels and regular evaluations. The +residue state is an ordinary wire inside each resulting network. -/ +theorem cross (p l : ℕ) [ExpChar F p] (hP : P = p ^ l) (hs : s.Fits L.base R.base C.level) + (hvw : v ≠ w) (he : C.level j = s.e) (hv : C.cell v = (L.plug j s.z).insert u) + (hw : C.cell w = R.plug j s.y) (hl : Unused j L.base.ports) (hr : Unused j R.base.ports) + (other : ∀ z, z ≠ v → z ≠ w → Unused j (C.cell z).ports) : + let S := lowering F r + let f := s.signed C.level L R p l hP + ∀ x, + C.observe P v s.coeff x = ∑ i, f i * ∑ y : Level t u.b, + (C.crossed s v w j L R k k' S i).value P (x, y) := by + intro S f + have hf := s.crossing C.level L R j p l hP hs hl hr k k' + intro x + let g := update (fun i => (C.cell i).eval P x) v (fun h => (C.cell v).test P x h s.coeff) + have hg (z) (hz : z ≠ v) (hz' : z ≠ w) (h : E → Wedge r) (a) : + g z (update h j a) = g z h := by + simp only [g, update_of_ne hz, Cell.eval_update _ _ _ _ _ (other z hz hz')] + let I := s.Branch × Level t u.b + let left (i : I) := (s.left L j k i.1).eval P (x, i.2) + let right (i : I) := (s.right R j k' S i.1).eval P (x, i.2) + have move := contractGraph_seam g C.level v w hvw j hg + (fun i : I => f i.1) (fun i => i.1.height) left right (by + intro h hh + rw [he, Fintype.sum_prod_type] + simp only [g, update_self, update_of_ne hvw.symm, hv, hw, left, right, ← mul_sum] + exact hf x h hh) + change contractGraph g _ = _ + rw [move, Fintype.sum_prod_type] + refine sum_congr rfl fun i _ => ?_ + rw [mul_sum] + refine sum_congr rfl fun y _ => congrArg (f i * ·) ?_ + let C' := C.crossed s v w j L R k k' S i + change _ = contractGraph (fun z => (C'.cell z).eval P (x, y)) C'.level + congr 1 + funext z h + unfold C' crossed + by_cases hz : z = w + · subst z; simp [right] + by_cases hz' : z = v + · subst z; simp [left, hvw] + simp [g, hz, hz', Cell.eval_pull] + +end Scene +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- +# States of the motion procedure + +An active station carries its crossing count. A residue, including an +original auxiliary mark, is passive. A collector keeps its name and +position. Ordinary wires created on crossing are numbered in order +of creation and contracted separately from the seam indices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Function + +open scoped Classical in +/-- The role used in the `Surface` construction. -/ +inductive Role where + | active (count : ℕ) + | residue + | collector + deriving DecidableEq + +open scoped Classical in +/-- In the case `.active n`, this construction gives `n`. -/ +def Role.clock : Role → ℕ + | .active n => n + | _ => 0 + +open scoped Classical in +/-- The data for the tag construction, including `role`, `name`, `reads`. -/ +structure Tag (V T : Type) where + /-- The `Tag` component of type `Role`. -/ + role : Role + /-- The name assigned to each index of type `Option T`. -/ + name : Option T + /-- The `Tag` component of type `Finset (V ⊕ ℕ)`. -/ + reads : Finset (V ⊕ ℕ) + +variable {F T V E X : Type} [Field F] {r t : ℕ} + +open scoped Classical in +/-- Returns `{u with reads := u.reads ∪ v.reads}` when `u.role = .collector` holds, and `{v with +reads := u.reads ∪ v.reads}` otherwise. -/ +def Tag.join (u v : Tag V T) : Tag V T := + if u.role = .collector then {u with reads := u.reads ∪ v.reads} + else {v with reads := u.reads ∪ v.reads} + +open scoped Classical in +/-- Uses `⟨.residue, none, {.inr j}⟩` as the representation. -/ +def Tag.leave (j : ℕ) : Tag V T := ⟨.residue, none, {.inr j}⟩ + +open scoped Classical in +/-- The quantity computed by `⟨.active (v.role.clock + 1), v.name, insert (.inr j) v.reads⟩`. -/ +def Tag.take (v : Tag V T) (j : ℕ) : Tag V T := + ⟨.active (v.role.clock + 1), v.name, insert (.inr j) v.reads⟩ + +open scoped Classical in +/-- In the case `[]`, this construction gives `X`. -/ +abbrev Stack (X : Type) (t : ℕ) : List ℕ → Type + | [] => X + | n :: l => Stack X t l × Level t n + +open scoped Classical in +/-- In the case `[], f`, this construction gives `f x`. -/ +def traceStack (t : ℕ) (x : X) : (l : List ℕ) → (Stack X t l → F) → F + | [], f => f x + | n :: ns, f => traceStack t x ns (fun y => ∑ h : Level t n, f (y, h)) + +open scoped Classical in +/-- The data for the stage construction, including `hidden`, `scene`, `hits`, `expired`, +`footprint`. -/ +structure Stage (F : Type) (r t : ℕ) (T V E X : Type) where + /-- The private coordinates at each index of type `List ℕ`. -/ + hidden : List ℕ + /-- The `Stage` component of type `Scene F r t (Tag V T) V E (Stack X t hidden)`. -/ + scene : Scene F r t (Tag V T) V E (Stack X t hidden) + /-- The `Stage` component of type `E → ℕ`. -/ + hits : E → ℕ + /-- Stores the expired associated with this `Stage`. -/ + expired : ℕ + /-- The `Stage` component of type `V → Finset (V ⊕ ℕ)`. -/ + footprint : V → Finset (V ⊕ ℕ) + +namespace Stage + +variable (s : Stage F r t T V E X) + +open scoped Classical in +/-- Computes the st by the application `Station F r t (Tag V T) (Stack X t s.hidden)`. -/ +abbrev St := Station F r t (Tag V T) (Stack X t s.hidden) +open scoped Classical in +/-- Computes the ct by the application `Cell F r t (Tag V T) E (Stack X t s.hidden)`. -/ +abbrev Ct := Cell F r t (Tag V T) E (Stack X t s.hidden) +open scoped Classical in +/-- Computes the sock by the application `Socket F r t (Tag V T) E (Stack X t s.hidden)`. -/ +abbrev Sock := Socket F r t (Tag V T) E (Stack X t s.hidden) + +open scoped Classical in +/-- Transforms the indexed data by `((s.scene.cell v).ports.map Prod.fst).toFinset`. -/ +def edges (v : V) := ((s.scene.cell v).ports.map Prod.fst).toFinset + +open scoped Classical in +/-- Computes the value by the application `traceStack t x s.hidden (s.scene.value P)`. -/ +def value [Fintype V] [Fintype E] (P : ℕ) (x : X) := + traceStack t x s.hidden (s.scene.value P) + +open scoped Classical in +/-- Uses `{s with scene := s.scene.put v c}` as the representation. -/ +def put (v : V) (c : s.Ct) : Stage F r t T V E X := + {s with scene := s.scene.put v c} + +open scoped Classical in +/-- The value specified by `{s.put v (c.insert {u with label := {u.label with role := +.collector}}) with expired := s.expired + 1}`. -/ +def freeze (v : V) (c : s.Ct) (u : s.St) : Stage F r t T V E X := + {s.put v (c.insert {u with label := {u.label with role := .collector}}) with expired := s.expired + + 1} + +open scoped Classical in +/-- Builds `Stage F r t T V E X where hidden` with the specified `hidden`, `scene`, `hits`, +`expired`. -/ +def advance {P : ℕ} {u : s.St} (a : Passage P u) (v w : V) (j : E) (L R : s.Sock) + (S : Lower F r) (i : a.Branch) : Stage F r t T V E X where + hidden := u.b :: s.hidden + scene := s.scene.crossed a v w j L R (Tag.leave s.hidden.length) (u.label.take s.hidden.length) S + i + hits := update s.hits j (s.hits j + 1) + expired := s.expired + footprint k := if k = v ∨ k = w then insert (.inr s.hidden.length) (s.footprint k ∪ u.label.reads) + else s.footprint k + +open scoped Classical in +/-- At most one mover is away from its initial cell. -/ +def Ready (v : V) (rest : List s.St) : Prop := + (∀ u ∈ rest, u.label.role.clock = 0) ∧ + ∀ w, w ≠ v → ∀ u ∈ (s.scene.cell w).stations, u.label.role.clock = 0 + +open scoped Classical in +/-- Support of one expansion step. Branch weights are separate from +the transition, so the same invariants apply to all linear combinations. -/ +inductive Step (P g H U : ℕ) : Stage F r t T V E X → Stage F r t T V E X → Prop where + | perm (s : Stage F r t T V E X) (v : V) (ls : List s.St) (hs : (s.scene.cell v).stations.Perm + ls) : + Step P g H U s (s.put v ⟨(s.scene.cell v).ports, ls⟩) + | expire (s : Stage F r t T V E X) (v : V) (c : s.Ct) (u : s.St) (hv : s.scene.cell v + = c.insert u) + (ha : u.label.role = .active U) (ready : s.Ready v c.stations) : + Step P g H U s (s.freeze v c u) + | merge (s : Stage F r t T V E X) (v : V) (c : s.Ct) (a b : s.St) (n : ℕ) + (hv : s.scene.cell v = (c.insert b).insert a) (ha : b.label.role = .active n) + (ready : s.Ready v (a :: c.stations)) (j : ℤ) (q : ℤ × ℤ) + (hq : q ∈ merges P a b ((s.scene.cell v).orderA s.scene.level) (s.scene.cell v).orderB j) + (bound : j ≤ if a.label.role = .collector then (g * (energyOf P b + 2 * P * H) : ℕ) else 0) : + Step P g H U s (s.put v (c.insert (mergeAt a b (a.label.join b.label) q))) + | cross (s : Stage F r t T V E X) (v w : V) (j : E) (L R : s.Sock) (u : s.St) (a : Passage P u) + (S : Lower F r) (i : a.Branch) (n : ℕ) (hv : s.scene.cell v = (L.plug j a.z).insert u) + (hw : s.scene.cell w = R.plug j a.y) (ne : v ≠ w) + (he : s.scene.level j = a.e) (hh : a.H = H) + (ha : u.label.role = .active n) (hn : n < U) (ready : s.Ready v L.stations) + (fixed : S = Motion.lowering F r) : + Step P g H U s (s.advance a v w j L R S i) + +end Stage +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Incidence, stationary positions, and selection of the next mover -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Function +variable {F T V E X : Type} {r t P g H U : ℕ} + +open scoped Classical in +/-- Concatenates the components in the order `c.stations.map Station.pos ++ c.ports.map +Prod.snd`. -/ +def Cell.positions (c : Cell F r t T E X) := c.stations.map Station.pos ++ c.ports.map Prod.snd + +namespace Stage + +variable (s : Stage F r t T V E X) + +open scoped Classical in +/-- The value specified by `(s.scene.cell v).ports`. -/ +def ports (v : V) := (s.scene.cell v).ports + +open scoped Classical in +/-- A static, loopless seam incidence pattern. -/ +structure Layout (src dst : E → V) (g : ℕ) : Prop where + loopless : ∀ i, src i ≠ dst i + incident : ∀ v i, i ∈ (s.ports v).map Prod.fst ↔ src i = v ∨ dst i = v + unique : ∀ v, ((s.ports v).map Prod.fst).Nodup + degree : ∀ v, (s.ports v).length ≤ g + +open scoped Classical in +/-- Dynamic invariants of the motion procedure. -/ +structure Valid (U : ℕ) : Prop where + distinct : ∀ v, (s.scene.cell v).positions.Nodup + collector : ∀ v, ∃ u ∈ (s.scene.cell v).stations, u.label.role = .collector + bound : ∀ v u, u ∈ (s.scene.cell v).stations → u.label.role.clock ≤ U + focus : ∀ v u, u ∈ (s.scene.cell v).stations → u.label.role.clock ≠ 0 → + ∀ w b, b ∈ (s.scene.cell w).stations → b.label.role.clock ≠ 0 → w = v ∧ b = u + +open scoped Classical in +/-- The condition `∀ v u, u ∈ (s.scene.cell v).stations → ∀ n, u.label.role ≠ .active n` on the +specified data. -/ +def Stopped : Prop := ∀ v u, u ∈ (s.scene.cell v).stations → ∀ n, u.label.role ≠ .active n + +open scoped Classical in +/-- The condition `∀ v, (s.scene.cell v).positions.length ≤ M ∧ (s.scene.cell v).bigA +s.scene.level + sumB (s.scene.cell v).stations ≤ N` on the specified data. -/ +def Room (M N : ℕ) : Prop := ∀ v, (s.scene.cell v).positions.length ≤ M ∧ + (s.scene.cell v).bigA s.scene.level + sumB (s.scene.cell v).stations ≤ N + +open scoped Classical in +/-- Computes the reach by the application `Relation.ReflTransGen (Step P g H U) s y`. -/ +abbrev Reach [Field F] (P g H U : ℕ) (y : Stage F r t T V E X) := + Relation.ReflTransGen (Step P g H U) s y + +variable [Field F] {s} {s' : Stage F r t T V E X} + +open scoped Classical in +theorem Step.ports_eq (h : Step P g H U s s') : s'.ports = s.ports := by + funext i + cases h with + | perm v ls hs => + by_cases hi : i = v <;> simp [ports, put, Scene.put, hi] + | expire v c u hv => + by_cases hi : i = v <;> simp [ports, freeze, put, Scene.put, hi, hv, Cell.insert] + | merge v c a b n hv => + by_cases hi : i = v <;> simp [ports, put, Scene.put, hi, hv, Cell.insert] + | cross v w j L R u a S k n hv hw ne => + by_cases hi : i = w + · simp [ports, advance, Scene.crossed, hi, hw, Passage.right, Cell.insert, Cell.pull] + by_cases hi' : i = v + · simp [ports, advance, Scene.crossed, hi', ne, hv, Passage.left, Cell.insert, Cell.pull] + simp [ports, advance, Scene.crossed, hi, hi', Cell.pull] + +open scoped Classical in +theorem Step.edges_eq (h : Step P g H U s s') : s'.edges = s.edges := + congrArg (fun f => fun v => ((f v).map Prod.fst).toFinset) h.ports_eq + +open scoped Classical in +theorem Step.layout {src dst : E → V} (h : Step P g H U s s') (a : s.Layout src dst g) : + s'.Layout src dst g := + ⟨a.loopless, h.ports_eq.symm ▸ a.incident, h.ports_eq.symm ▸ a.unique, h.ports_eq.symm ▸ a.degree⟩ + +end Stage +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- +# Energy and progress of the motion procedure + +Each active mark keeps one reserve; a stationary residue has no reserve. +All energies use units of `1 / (2P)`. In particular the public seam +energy is multiplied by `P`. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +open Finset Function + +variable {F T E V X : Type} {r t P H g U : ℕ} + +open scoped Classical in +/-- In the case `.active _, e`, this construction gives `e + M`. -/ +def Role.mobile (M : ℕ) : Role → ℕ → ℕ + | .active _, e => e + M + | .residue, e => e + | .collector, _ => 0 + +open scoped Classical in +/-- In the case `.collector, e`, this construction gives `e`. -/ +def Role.collected : Role → ℕ → ℕ + | .collector, e => e + | _, _ => 0 + +open scoped Classical in +/-- In the case `.active i`, this construction gives `2 + 2 * (U - i)`. -/ +def Role.fuel (U : ℕ) : Role → ℕ + | .active i => 2 + 2 * (U - i) + | _ => 1 + +namespace Stage +variable (s : Stage F r t T V E X) + +open scoped Classical in +/-- A local sum over the marks, independent of their order and tables. -/ +def tally (P : ℕ) (f : Role → ℕ → ℕ) (v : V) := + ((s.scene.cell v).stations.map (fun u => f u.label.role (energyOf P u))).sum + +open scoped Classical in +/-- Builds `Ledger V E where mobile` with the specified `mobile`, `collected`, `seam`, `hits`. -/ +def ledger [Fintype V] (P H : ℕ) : Ledger V E where + mobile := s.tally P (Role.mobile (2 * P * H)) + collected := s.tally P Role.collected + seam e := P * s.scene.level e + hits := s.hits + clock := ∑ v, s.tally P (fun r _ => r.clock) v + expired := s.expired + +open scoped Classical in +/-- Each remaining hop pays for the new residue and one step of progress. -/ +def potential [Fintype V] (U : ℕ) := ∑ v, s.tally 0 (fun r _ => r.fuel U) v + +open scoped Classical in +private theorem tally_perm (v : V) (ls : List s.St) (hs : (s.scene.cell v).stations.Perm ls) + (f : Role → ℕ → ℕ) (w : V) : + (s.put v ⟨(s.scene.cell v).ports, ls⟩).tally P f w = s.tally P f w := by + by_cases he : w = v + · subst w + simp only [tally, put, Scene.put, update_self] + exact (hs.symm.map _).sum_eq + · simp [tally, put, Scene.put, he] + +open scoped Classical in +private theorem tally_freeze (v : V) (c : s.Ct) (u : s.St) + (hv : s.scene.cell v = c.insert u) (f : Role → ℕ → ℕ) (w : V) : + (s.freeze v c u).tally P f w + (if w = v then f u.label.role (energyOf P u) else 0) = + s.tally P f w + (if w = v then f .collector (energyOf P u) else 0) := by + by_cases he : w = v + · subst w + simp [tally, freeze, put, Scene.put, hv, Cell.insert, energyOf, add_comm, add_left_comm] + · simp [tally, freeze, put, Scene.put, he] + +open scoped Classical in +private theorem tally_merge (v : V) (c : s.Ct) (a b u : s.St) + (hv : s.scene.cell v = (c.insert b).insert a) (f : Role → ℕ → ℕ) (w : V) : + (s.put v (c.insert u)).tally P f w + + (if w = v then f a.label.role (energyOf P a) + f b.label.role (energyOf P b) else 0) = + s.tally P f w + (if w = v then f u.label.role (energyOf P u) else 0) := by + by_cases he : w = v + · subst w + simp [tally, put, Scene.put, hv, Cell.insert, add_comm, add_left_comm, add_assoc] + · simp [tally, put, Scene.put, he] + +variable [Field F] + +open scoped Classical in +private theorem tally_cross (P' : ℕ) (v w : V) (j : E) (L R : s.Sock) (u : s.St) (a : Passage P u) + (S : Lower F r) (i : a.Branch) + (hv : s.scene.cell v = (L.plug j a.z).insert u) (hw : s.scene.cell w = R.plug j a.y) + (ne : v ≠ w) (f : Role → ℕ → ℕ) (z : V) : + (s.advance a v w j L R S i).tally P' f z + + (if z = v then f u.label.role (energyOf P' u) else 0) = + s.tally P' f z + + (if z = v then f .residue (energyOf P' (a.leaves (Tag.leave s.hidden.length) i)) else 0) + + (if z = w then f (.active (u.label.role.clock + 1)) + (energyOf P' (a.arrives (u.label.take s.hidden.length) S i)) else 0) := by + by_cases h : z = w + · simp [tally, advance, Scene.crossed, h, hw, ne.symm, Passage.right, Cell.insert, Cell.pull, + Station.pull, + Passage.arrives, transfer, Tag.take, energyOf, Function.comp_def, add_comm] + by_cases h' : z = v + · simp [tally, advance, Scene.crossed, h', hv, ne, Passage.left, Cell.insert, Cell.pull, + Station.pull, + Passage.leaves, residue, Tag.leave, energyOf, Function.comp_def, add_comm, add_left_comm] + simp [tally, advance, Scene.crossed, h, h', Cell.pull, Station.pull, energyOf, Function.comp_def] + +variable [Fintype V] + +omit [Field F] in +open scoped Classical in +theorem potential_perm (v : V) (ls : List s.St) (hs : (s.scene.cell v).stations.Perm ls) : + (s.put v ⟨(s.scene.cell v).ports, ls⟩).potential U = s.potential U := by + simp only [potential, s.tally_perm v ls hs] + +omit [Field F] in +open scoped Classical in +theorem potential_expire (v : V) (c : s.Ct) (u : s.St) + (hv : s.scene.cell v = c.insert u) (ha : u.label.role = .active U) : + (s.freeze v c u).potential U < s.potential U := by + have h := sum_congr rfl fun z (_ : z ∈ univ) => + s.tally_freeze (P := 0) v c u hv (fun r _ => r.fuel U) z + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true, ha] at h + change (s.freeze v c u).potential U + (2 + 2 * (U - U)) = s.potential U + 1 at h + omega + +omit [Field F] in +open scoped Classical in +theorem potential_merge (v : V) (c : s.Ct) (a b u : s.St) {n : ℕ} + (hv : s.scene.cell v = (c.insert b).insert a) (ha : b.label.role = .active n) + (hj : u.label = a.label.join b.label) : + (s.put v (c.insert u)).potential U < s.potential U := by + have h := sum_congr rfl fun z (_ : z ∈ univ) => + s.tally_merge (P := 0) v c a b u hv (fun r _ => r.fuel U) z + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true] at h + change (s.put v (c.insert u)).potential U + (a.label.role.fuel U + b.label.role.fuel U) = + s.potential U + u.label.role.fuel U at h + have ht : u.label.role.fuel U < a.label.role.fuel U + b.label.role.fuel U := by + cases he : a.label.role <;> simp [hj, Tag.join, he, ha, Role.fuel] + omega + +open scoped Classical in +theorem potential_advance (v w : V) (j : E) (L R : s.Sock) (u : s.St) (a : Passage P u) + (S : Lower F r) (i : a.Branch) {n : ℕ} + (hv : s.scene.cell v = (L.plug j a.z).insert u) (hw : s.scene.cell w = R.plug j a.y) + (ne : v ≠ w) (ha : u.label.role = .active n) (hn : n < U) : + (s.advance a v w j L R S i).potential U < s.potential U := by + have h := sum_congr rfl fun z (_ : z ∈ univ) => + s.tally_cross 0 v w j L R u a S i hv hw ne (fun r _ => r.fuel U) z + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true, ha] at h + change (s.advance a v w j L R S i).potential U + (2 + 2 * (U - n)) = + s.potential U + 1 + (2 + 2 * (U - (n + 1))) at h + omega + +omit [Field F] in +open scoped Classical in +theorem potential_le (U : ℕ) : + s.potential U ≤ (2 + 2 * U) * ∑ v, (s.scene.cell v).stations.length := by + rw [mul_sum] + apply sum_le_sum + intro v _ + unfold tally + generalize (s.scene.cell v).stations = us + induction us with + | nil => simp + | cons a as ih => + have h : a.label.role.fuel U ≤ 2 + 2 * U := by cases a.label.role <;> simp [Role.fuel] <;> omega + simpa [mul_add, add_comm] using Nat.add_le_add h ih + +variable [Fintype E] {s} {s' : Stage F r t T V E X} + +omit [Fintype V] [Fintype E] in +open scoped Classical in +/-- At a continued fusion the total mobile energy does not grow. +Only terminal fusion is allowed a positive Laurent order. -/ +private theorem merge_bounds (a b : s.St) {n k l : ℕ} {j : ℤ} {q : ℤ × ℤ} + (ha : b.label.role = .active n) (hq : q ∈ merges P a b k l j) + (bound : j ≤ if a.label.role = .collector then (g * (energyOf P b + 2 * P * H) : ℕ) else 0) : + let c := mergeAt a b (a.label.join b.label) q + let μ := if a.label.role = .collector then energyOf P b + 2 * P * H else 0 + let mob := Role.mobile (2 * P * H) + mob c.label.role (energyOf P c) + μ ≤ + mob a.label.role (energyOf P a) + mob b.label.role (energyOf P b) ∧ + Role.collected c.label.role (energyOf P c) ≤ + Role.collected a.label.role (energyOf P a) + Role.collected b.label.role (energyOf P b) + + (1 + 2 * g) * μ ∧ + c.label.role.clock ≤ a.label.role.clock + b.label.role.clock := by + intro c μ mob + have hc : c.label = a.label.join b.label := rfl + have he : (energyOf P c : ℤ) = energyOf P a + energyOf P b + 2 * j := + energy_merge P a b _ hq + cases hr : a.label.role <;> + simp only [hc, Tag.join, ha, hr, mob, Role.mobile, Role.collected, Role.clock, μ, + reduceCtorEq, ite_false, ite_true] at bound ⊢ + · omega + · omega + · refine ⟨le_rfl, ?_, Nat.zero_le _⟩ + have nonneg : (0 : ℤ) ≤ (2 * P * H : ℕ) := by positivity + rw [← Nat.cast_le (α := ℤ)] + push_cast at bound nonneg ⊢ + nlinarith only [he, bound, nonneg] + +open scoped Classical in +theorem Step.budget (h : Step P g H U s s') : + Ledger.Budget s.edges g (2 * P * H) U (s.ledger P H) (s'.ledger P H) := by + let M := 2 * P * H + let mob := Role.mobile M + let col := Role.collected + let clk := fun (r : Role) (_ : ℕ) => r.clock + cases h with + | perm v ls hs => + have he : (s.put v ⟨(s.scene.cell v).ports, ls⟩).ledger P H = s.ledger P H := by + have ht (f) := funext (s.tally_perm (P := P) v ls hs f) + simp only [ledger, ht] + rfl + rw [he] + exact .refl + | expire v c u hv ha => + let q := s.freeze v c u + refine Ledger.Budget.collect (fun w => if w = v then energyOf P u else 0) ?_ ?_ rfl rfl ?_ + · intro w + have h := s.tally_freeze (P := P) v c u hv mob w + change q.tally P mob w + (if w = v then energyOf P u else 0) ≤ s.tally P mob w + rw [ha] at h + change q.tally P mob w + (if w = v then energyOf P u + M else 0) = + s.tally P mob w + (if w = v then 0 else 0) at h + split_ifs at h ⊢ <;> omega + · intro w + have h := s.tally_freeze (P := P) v c u hv col w + change q.tally P col w ≤ s.tally P col w + (1 + 2 * g) * (if w = v then energyOf P u else 0) + rw [ha] at h + change q.tally P col w + (if w = v then 0 else 0) = + s.tally P col w + (if w = v then energyOf P u else 0) at h + have := Nat.le_mul_of_pos_left (energyOf P u) (show 0 < 1 + 2 * g by omega) + split_ifs at h ⊢ <;> omega + · have h := sum_congr rfl fun w (_ : w ∈ univ) => s.tally_freeze (P := P) v c u hv clk w + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true, ha] at h + change (q.ledger P H).clock + U = (s.ledger P H).clock + 0 at h + change U * (s.expired + 1) + (q.ledger P H).clock ≤ U * s.expired + (s.ledger P H).clock + rw [mul_add] + omega + | merge v c a b n hv ha _ j q hq bound => + let u := mergeAt a b (a.label.join b.label) q + let y := s.put v (c.insert u) + let μ := if a.label.role = .collector then energyOf P b + M else 0 + obtain ⟨h₁, h₂, h₃⟩ := merge_bounds a b ha hq bound + change mob u.label.role (energyOf P u) + μ ≤ + mob a.label.role (energyOf P a) + mob b.label.role (energyOf P b) at h₁ + change col u.label.role (energyOf P u) ≤ + col a.label.role (energyOf P a) + col b.label.role (energyOf P b) + (1 + 2 * g) * μ at h₂ + refine Ledger.Budget.collect (fun w => if w = v then μ else 0) ?_ ?_ rfl rfl ?_ + · intro w + have h := s.tally_merge (P := P) v c a b u hv mob w + change (s.put v (c.insert u)).tally P mob w + (if w = v then μ else 0) ≤ s.tally P mob w + split_ifs at h ⊢ <;> omega + · intro w + have h := s.tally_merge (P := P) v c a b u hv col w + change (s.put v (c.insert u)).tally P col w ≤ s.tally P col w + (1 + 2 * g) * (if w + = v then μ else 0) + split_ifs at h ⊢ <;> omega + · have h := sum_congr rfl fun w (_ : w ∈ univ) => s.tally_merge (P := P) v c a b u hv clk w + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true] at h + change (y.ledger P H).clock + (a.label.role.clock + b.label.role.clock) = + (s.ledger P H).clock + u.label.role.clock at h + change u.label.role.clock ≤ a.label.role.clock + b.label.role.clock at h₃ + change U * s.expired + (y.ledger P H).clock ≤ U * s.expired + (s.ledger P H).clock + omega + | cross v w j L R u a S i n hv hw ne he hh ha => + let q := s.advance a v w j L R S i + let l := energyOf P (a.leaves (Tag.leave s.hidden.length) i) + let r := energyOf P (a.arrives (u.label.take s.hidden.length) S i) + have hl := a.energy_step (Tag.leave s.hidden.length) (u.label.take s.hidden.length) S i + rw [hh] at hl + change l + r ≤ energyOf P u ∧ P * i.height + (energyOf P u + M) ≤ P * a.e at hl + have hw' : j ∈ s.edges w := by simp [edges, hw, Socket.plug] + refine Ledger.Budget.cross v w j hw' (energyOf P u + M) (r + M) (by omega) + (by omega) ?_ ?_ ?_ ?_ ?_ + · intro z + have h := s.tally_cross P v w j L R u a S i hv hw ne mob z + rw [ha] at h + change q.tally P mob z + (if z = v then energyOf P u + M else 0) = + s.tally P mob z + (if z = v then l else 0) + (if z = w then r + M else 0) at h + change q.tally P mob z + (if z = v then r + M else 0) ≤ + s.tally P mob z + (if z = w then r + M else 0) + split_ifs at h ⊢ <;> omega + · funext z + have h := s.tally_cross P v w j L R u a S i hv hw ne col z + rw [ha] at h + change q.tally P col z + (if z = v then 0 else 0) = + s.tally P col z + (if z = v then 0 else 0) + (if z = w then 0 else 0) at h + change q.tally P col z = s.tally P col z + simpa only [ite_self, add_zero] using h + · intro k + by_cases hk : k = j + · simpa [ledger, advance, Scene.crossed, hk, he] using hl.2 + · simp [ledger, advance, Scene.crossed, hk] + · intro k + by_cases hk : k = j <;> simp [ledger, advance, hk] + · have h := sum_congr rfl fun z (_ : z ∈ univ) + => s.tally_cross P v w j L R u a S i hv hw ne clk z + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true, ha] at h + change (q.ledger P H).clock + n = (s.ledger P H).clock + 0 + (n + 1) at h + change U * s.expired + (q.ledger P H).clock ≤ U * s.expired + (s.ledger P H).clock + 1 + omega + +omit [Fintype V] [Fintype E] in +open scoped Classical in +theorem Step.stations_le (h : Step P g H U s s') (z : V) : + (s'.scene.cell z).stations.length + (∑ e ∈ s.edges z, s.hits e) ≤ + (s.scene.cell z).stations.length + ∑ e ∈ s.edges z, s'.hits e := by + cases h with + | perm v ls hs => + by_cases h : z = v <;> simp [put, Scene.put, h, hs.length_eq] + | expire v c u hv => + by_cases h : z = v <;> simp [freeze, put, Scene.put, h, hv, Cell.insert] + | merge v c a b n hv => + by_cases h : z = v <;> simp [put, Scene.put, h, hv, Cell.insert] + | cross v w j L R u a S i n hv hw ne => + have hu e : (s.advance a v w j L R S i).hits e = s.hits e + if e = j then 1 else 0 := by + by_cases h : e = j <;> simp [advance, h] + simp_rw [hu, sum_add_distrib, sum_ite_eq'] + by_cases hz : z = w + · have hj : j ∈ s.edges w := by simp [edges, hw, Socket.plug] + simp [hz, hj, advance, Scene.crossed, hw, Passage.right, Cell.insert, Cell.pull] + omega + by_cases hz' : z = v + · simp [hz', ne, advance, Scene.crossed, hv, Passage.left, Cell.insert, Cell.pull] + simp [hz, hz', advance, Scene.crossed, Cell.pull] + +open scoped Classical in +/-- The sum of `s.tally 0 (fun r _ => r.collected 1) v` indexed by `v`. -/ +def collectors (s : Stage F r t T V E X) := ∑ v, s.tally 0 (fun r _ => r.collected 1) v + +omit [Fintype E] in +open scoped Classical in +theorem Step.collectors (h : Step P g H U s s') : + s'.collectors + s.expired = s.collectors + s'.expired := by + let f := fun (r : Role) (_ : ℕ) => r.collected 1 + cases h with + | perm v ls hs => + simp only [Stage.collectors, s.tally_perm v ls hs] + rfl + | expire v c u hv ha => + have h := sum_congr rfl fun z (_ : z ∈ univ) => s.tally_freeze (P := 0) v c u hv f z + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true, ha] at h + change (s.freeze v c u).collectors + 0 = s.collectors + 1 at h + change _ = s.collectors + (s.expired + 1) + omega + | merge v c a b n hv ha _ j q => + let u := mergeAt a b (a.label.join b.label) q + have h := sum_congr rfl fun z (_ : z ∈ univ) => s.tally_merge (P := 0) v c a b u hv f z + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true, ha] at h + change (s.put v (c.insert u)).collectors + (a.label.role.collected 1 + 0) = + s.collectors + (a.label.join b.label).role.collected 1 at h + have he : (a.label.join b.label).role.collected 1 = a.label.role.collected 1 := by + cases hz : a.label.role <;> simp [Tag.join, hz, ha, Role.collected] + rw [he] at h + change (s.put v (c.insert u)).collectors + s.expired = s.collectors + s.expired + omega + | cross v w j L R u a S i n hv hw ne he hh ha => + have h := sum_congr rfl fun z (_ : z ∈ univ) => s.tally_cross 0 v w j L R u a S i hv hw ne f z + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true, ha] at h + change (s.advance a v w j L R S i).collectors + 0 = s.collectors + 0 + 0 at h + exact congrArg (· + s.expired) (by simpa using h) + +omit [Fintype V] [Fintype E] in +open scoped Classical in +theorem Reach.ports_eq (h : s.Reach P g H U s') : s'.ports = s.ports := by + induction h with + | refl => rfl + | tail _ q ih => exact q.ports_eq.trans ih + +omit [Fintype V] [Fintype E] in +open scoped Classical in +theorem Reach.edges_eq (h : s.Reach P g H U s') : s'.edges = s.edges := + congrArg (fun f => fun v => ((f v).map Prod.fst).toFinset) h.ports_eq + +open scoped Classical in +theorem Reach.budget (h : s.Reach P g H U s') : + Ledger.Budget s.edges g (2 * P * H) U (s.ledger P H) (s'.ledger P H) := by + induction h with + | refl => exact .refl + | tail v q ih => exact ih.trans ((Reach.edges_eq v) ▸ q.budget) + +omit [Fintype V] [Fintype E] in +open scoped Classical in +theorem Reach.stations_le (h : s.Reach P g H U s') (v : V) : + (s'.scene.cell v).stations.length + (∑ e ∈ s.edges v, s.hits e) ≤ + (s.scene.cell v).stations.length + ∑ e ∈ s.edges v, s'.hits e := by + induction h with + | refl => rfl + | tail w q ih => + have hz := q.stations_le v + rw [Reach.edges_eq w] at hz + omega + +omit [Fintype E] in +open scoped Classical in +theorem Reach.collectors (h : s.Reach P g H U s') : + s'.collectors + s.expired = s.collectors + s'.expired := by + induction h with + | refl => rfl + | tail _ q ih => have := q.collectors; omega +end Stage +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Cardinality.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Cardinality.lean new file mode 100644 index 0000000000..94cafee9de --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Cardinality.lean @@ -0,0 +1,777 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Tactic.GCongr +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Remnants +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Install +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Install.Owners +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure +public import Mathlib.FieldTheory.Finite.Basic + +/-! # Polynomial cardinality estimates for local data -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +/-- The condition `∃ k : ℕ, ∀ d, f d ≤ (d + 2) ^ k` on the specified data. -/ +def Poly (f : ℕ → ℕ) := ∃ k : ℕ, ∀ d, f d ≤ (d + 2) ^ k + +theorem Poly.const (a : ℕ) : Poly (fun _ => a) := + ⟨a, fun _ => Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left (by omega) a)⟩ + +theorem Poly.var : Poly (fun d => d) := ⟨1, by simp⟩ + +theorem Poly.add {f g : ℕ → ℕ} (a : Poly f) (b : Poly g) : Poly (fun d => f d + g d) := by + obtain ⟨i, hi⟩ := a + obtain ⟨j, hj⟩ := b + refine ⟨max i j + 1, fun d => ?_⟩ + have hf := (hi d).trans (Nat.pow_le_pow_right (by omega) (le_max_left i j)) + have hg := (hj d).trans (Nat.pow_le_pow_right (by omega) (le_max_right i j)) + rw [pow_succ] + exact (Nat.add_le_add hf hg).trans (by rw [← Nat.mul_two]; gcongr; omega) + +theorem Poly.mul {f g : ℕ → ℕ} (a : Poly f) (b : Poly g) : Poly (fun d => f d * g d) := by + obtain ⟨i, hi⟩ := a + obtain ⟨j, hj⟩ := b + exact ⟨i + j, fun d => by rw [pow_add]; exact Nat.mul_le_mul (hi d) (hj d)⟩ + +theorem Poly.pow {f : ℕ → ℕ} (a : Poly f) (n : ℕ) : Poly (fun d => f d ^ n) := by + obtain ⟨i, hi⟩ := a + exact ⟨i * n, fun d => by rw [pow_mul]; exact Nat.pow_le_pow_left (hi d) _⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end + +/- # A designated active insertion and its stationary marks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion +variable {F T V E X : Type} {r t P g H U M N : ℕ} + +open scoped Classical in +/-- The quantity computed by `window P g H N * (N + 1) * K ^ 2`. -/ +def width (P g H N K : ℕ) := window P g H N * (N + 1) * K ^ 2 + +open scoped Classical in +/-- The data for the move construction, including `atCell`, `rest`, `mover`, `clock`, `cell`. -/ +structure Move (s : Stage F r t T V E X) where + /-- The `Move` field of type `V`. -/ + atCell : V + /-- The `Move` component of type `s.Ct`. -/ + rest : s.Ct + /-- The `Move` component of type `s.St`. -/ + mover : s.St + /-- Stores the clock associated with this `Move`. -/ + clock : ℕ + cell : s.scene.cell atCell = rest.insert mover + role : mover.label.role = .active clock + ready : s.Ready atCell rest.stations + +namespace Move + +variable {s : Stage F r t T V E X} (u : Move s) + +open scoped Classical in +theorem distinct (hv : s.Valid U) : u.rest.positions.Nodup ∧ u.mover.pos ∉ u.rest.sites := by + have h := hv.distinct u.atCell + rw [u.cell, Cell.positions_insert, List.nodup_cons] at h + exact ⟨h.2, fun e => h.1 (List.mem_toFinset.mp e)⟩ + +open scoped Classical in +theorem collector (hv : s.Valid U) : ∃ a ∈ u.rest.stations, a.label.role = .collector := by + obtain ⟨a, ha, h⟩ := hv.collector u.atCell + rw [u.cell] at ha + rcases List.mem_cons.mp ha with rfl|ha + · simp [u.role] at h + · exact ⟨a, ha, h⟩ + +open scoped Classical in +theorem room (hr : s.Room M N) : + u.rest.sites.card ≤ M ∧ u.mover.a + u.mover.b + u.rest.bigA s.scene.level + + sumB u.rest.stations ≤ N := by + obtain ⟨h, k⟩ := hr u.atCell + rw [u.cell, Cell.positions_insert, List.length_cons] at h + refine ⟨u.rest.sizes (by omega), ?_⟩ + rw [u.cell] at k + simp only [Cell.bigA, Cell.insert, sumA, sumB, List.map_cons, List.sum_cons] at k ⊢ + omega + +open scoped Classical in +/-- The quantity computed by `energyOf P u.mover + 2 * P * H`. -/ +def threshold (P H : ℕ) := energyOf P u.mover + 2 * P * H + +open scoped Classical in +theorem threshold_le (hr : s.Room M N) : u.threshold P H ≤ P * N + N + 2 * P * H := by + have h := (u.room hr).2 + have e := Nat.mul_le_mul_left P (by omega : u.mover.a ≤ N) + unfold threshold energyOf + omega + +variable [Field F] + +open scoped Classical in +/-- Computes the order by the application `poleOrder P ((s.scene.cell u.atCell).orderA +s.scene.level) (s.scene.cell u.atCell).orderB u.rest.inserts`. -/ +def order (P : ℕ) := poleOrder P ((s.scene.cell u.atCell).orderA s.scene.level) + (s.scene.cell u.atCell).orderB u.rest.inserts + +omit [Field F] in +open scoped Classical in +theorem order_le (hr : s.Room M N) (z : F) : u.order P z ≤ P * N + N := by + obtain ⟨h₁, h₂⟩ := (s.scene.cell u.atCell).order_bounds s.scene.level (hr u.atCell).2 + have h := Nat.mul_le_mul_left P h₁ + unfold order poleOrder + split_ifs <;> omega + +open scoped Classical in +/-- Computes the test by the application `coefficient P (powered P u.rest.sites) u.rest.inserts +z j`. -/ +def test (P : ℕ) (z : F) (j : ℤ) : Test F r t := coefficient P (powered P u.rest.sites) + u.rest.inserts z j + +end Move +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Selecting the destination of an insertion collision -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Function Motion Stage +variable {F T V E X : Type} {r t P g H U M N : ℕ} {s : Stage F r t T V E X} + +open scoped Classical in +theorem Stage.Room.perm (h : s.Room M N) (v : V) (ls : List s.St) (hl : (s.scene.cell + v).stations.Perm ls) : + (s.put v ⟨(s.scene.cell v).ports, ls⟩).Room M N := by + intro w + by_cases hv : w = v + · subst w + have hA := (hl.map Station.a).sum_eq + have hB := (hl.map Station.b).sum_eq + have hn := hl.length_eq + simpa only [put, Scene.put, update_self, Cell.positions, List.length_append, List.length_map, + Cell.bigA, sumA, sumB, hA, hB, hn] using h v + · simpa only [put, Scene.put, update_of_ne hv] using h w + +variable [Field F] [Fintype V] [Fintype E] + +open scoped Classical in +theorem Move.absorb (u : Move s) (p l : ℕ) [ExpChar F p] + (hv : s.Valid U) (hr : s.Room M N) (a : s.St) (ha : a ∈ u.rest.stations) (j : ℤ) + (hj : j ≤ if a.label.role = .collector then (g * u.threshold (p ^ l) H : ℕ) else 0) : + Terms (p ^ l) (s.Gain (p ^ l) g H U) (width (p ^ l) g H N (M * (2 * N) + 1)) + (s.observe (p ^ l) u.atCell (u.test (p ^ l) a.pos j)) := by + let P := p ^ l + obtain ⟨ls, rs, hc⟩ := List.append_of_mem ha + let c : s.Ct := ⟨u.rest.ports, ls ++ rs⟩ + let n := s.reord u.atCell (u.mover :: ls) [a] rs + have hk : (s.scene.cell u.atCell).stations = (u.mover :: ls) ++ [a] ++ rs := by + simp [u.cell, Cell.insert, hc] + have perm : (s.scene.cell u.atCell).stations.Perm ([a] ++ (u.mover :: ls) ++ rs) := by + rw [hk] + exact List.perm_append_comm.append_right rs + have hv' : n.Valid U := hv.perm _ _ perm + have hr' : n.Room M N := hr.perm _ _ perm + have e : n.scene.cell u.atCell = (c.insert u.mover).insert a := by + simp [n, reord, put, Scene.put, u.cell, c, Cell.insert] + have ready : n.Ready u.atCell (a :: c.stations) := by + constructor + · intro b hb + apply u.ready.1 + rw [hc] + exact List.perm_middle.mem_iff.mpr hb + · intro w hw b hb + apply u.ready.2 w hw + simp only [n, reord, put, Scene.put, update_of_ne hw] at hb + exact hb + have he : u.rest.positions.Perm (a.pos :: c.positions) := by + simp only [Cell.positions, hc, c, List.map_append, List.map_cons, List.append_assoc, + List.cons_append] + exact List.perm_middle + have h₁ : a.pos ∉ c.sites := fun h => + (List.nodup_cons.mp (he.nodup_iff.mp (u.distinct hv).1)).1 (List.mem_toFinset.mp h) + have h₂ : c.sites ⊆ u.rest.sites := fun i hi => + List.mem_toFinset.mpr (he.mem_iff.mpr (.tail _ (List.mem_toFinset.mp hi))) + have h₃ : c.inserts ⊆ u.rest.inserts.erase a.pos := by + intro z hz + refine mem_erase.mpr ⟨fun h => h₁ (h ▸ c.inserts_sub hz), ?_⟩ + obtain ⟨i, hi, rfl⟩ := List.mem_map.mp (List.mem_toFinset.mp hz) + apply u.rest.mem_inserts + rw [hc] + exact List.perm_middle.mem_iff.mpr (.tail _ hi) + let A := powered P u.rest.sites + let B := u.rest.inserts + have aB : a.pos ∈ B := u.rest.mem_inserts ha + have old := merge_terms p l rfl hv' u.atCell c a u.mover u.clock e u.role ready A B + (mem_image_of_mem _ (u.rest.inserts_sub aB)) aB + ((powered_iff p l _ _).not.mpr (u.distinct hv).2) + (fun h => (u.distinct hv).2 (u.rest.inserts_sub h)) + (c.fixed_erase p l a.pos h₁ _ _ h₂ h₃) j hj + refine rotate_terms u.atCell _ (coefficient_signed _ _ _ _ _) _ _ _ hk (old.mono ?_) + have bound : j ≤ (g * (P * N + N + 2 * P * H) : ℕ) := by + have ht := Nat.mul_le_mul_left g (u.threshold_le (P := P) (H := H) hr) + unfold P at * + split_ifs at hj <;> omega + obtain ⟨hA, hB⟩ := (n.scene.cell u.atCell).order_bounds n.scene.level (hr' u.atCell).2 + refine (card_filter_le _ _).trans ((pairs_card hA hB bound).trans ?_) + unfold width + exact (Nat.le_mul_of_pos_right _ (by omega)).trans (Nat.le_mul_of_pos_right _ (by positivity)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Availability and size of a seam crossing -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion Stage +variable {F T V E X : Type} [Field F] [Fintype F] [Fintype E] [Fintype V] + {r t P g H U M N : ℕ} {s : Stage F r t T V E X} + +omit [Field F] [Fintype F] in +open scoped Classical in +theorem hop_card (d e m : ℕ) (j : ℤ) (A B : Finset F) (K : ℕ) + (ha : A.card ≤ K) (hb : B.card ≤ K) (hd : d ≤ N) (hm : m ≤ N) (hj : j ≤ 0) : + Fintype.card (Hop P d e m j A B) ≤ width P g H N K := by + have h : (crossings P d e m j).card ≤ window P g H N := + (card_filter_le _ _).trans (pairs_card hd (Nat.zero_le _) (hj.trans (Int.natCast_nonneg _))) + simp only [Hop, Fintype.card_prod, Fintype.card_coe, Fintype.card_fin] + calc + _ ≤ window P g H N * (K * ((N + 1) * K)) := + Nat.mul_le_mul h (Nat.mul_le_mul ha (Nat.mul_le_mul (Nat.succ_le_succ hm) hb)) + _ = _ := by unfold width; ring + +open scoped Classical in +theorem Move.exit (u : Move s) (p l : ℕ) [ExpChar F p] {src dst : E → V} + (hl : s.Layout src dst g) (hv : s.Valid U) (hr : s.Room M N) (hc : u.clock < U) + (hs : M * (2 * N + 1) < Fintype.card F) (i : E) (z : F) (hi : (i, z) ∈ u.rest.ports) + (j : ℤ) (hj : u.threshold (p ^ l) H ≤ -j) : + Terms (p ^ l) (s.Gain (p ^ l) g H U) (width (p ^ l) g H N (M * (2 * N) + 1)) + (s.observe (p ^ l) u.atCell (u.test (p ^ l) z j)) := by + let P := p ^ l + have hi' : (i, z) ∈ s.ports u.atCell := by unfold ports; rw [u.cell]; exact hi + obtain ⟨w, y, R, ne, hw, other⟩ := hl.partner hi' + obtain ⟨L, hL⟩ := Socket.exists_of_mem hi + let A := u.rest.sites + let B := u.rest.inserts + let C := (s.scene.cell w).sites + have vz : z ∈ u.rest.seams := u.rest.mem_seams hi + have vy : y ∈ C := by unfold C; rw [hw, Socket.sites]; exact mem_insert_self _ _ + have hz : z ∉ B := disjoint_right.mp (u.rest.disjoint (u.distinct hv).1) vz + have hA : A.card ≤ M := (u.room hr).1 + have hB : B.card ≤ M := (card_le_card u.rest.inserts_sub).trans hA + have hC : C.card ≤ M := (s.scene.cell w).sizes (hr w).1 + obtain ⟨U', hu', hcu⟩ := exists_subset_card_eq (Nat.succ_le_of_lt (fresh_size hA hs)) + obtain ⟨W', hw', hcw⟩ := exists_subset_card_eq (Nat.succ_le_of_lt (fresh_size hC hs)) + let V' := powered P W' + have hcv : V'.card = M * (2 * N) + 1 := (card_image_of_injective _ (power_injective p l)).trans + hcw + have hAf : M * (2 * N) < U'.card := by omega + have hCf : M * (2 * N) < V'.card := by omega + have bound₁ : u.mover.a + u.mover.b + (s.scene.level i + L.base.bigA s.scene.level) + + sumB L.stations ≤ N := by + have h := (u.room hr).2 + rw [← hL, Socket.bigA] at h + exact h + have bound₂ : s.scene.level i + R.base.bigA s.scene.level ≤ N := by + have h := (hr w).2 + rw [hw, Socket.bigA] at h + omega + choose f hf hf' using fun j : V' => mem_image.mp j.property + let a : Passage P u.mover := + { z := z, y := y, A := powered P A, B := B, C := powered P C, U := U', V := V' + root := f, hroot := hf' + hz := mem_image_of_mem _ (u.rest.seams_sub vz) + hy := mem_image_of_mem _ vy + hb := hz + hu := (powered_iff p l A _).not.mpr (u.distinct hv).2 + hu' := fun h => (u.distinct hv).2 (u.rest.inserts_sub h) + hU := disjoint_left.mpr fun k hk e => (mem_sdiff.mp (hu' hk)).2 (u.rest.inserts_sub e) + hV := disjoint_left.mpr (by + intro k hk e + obtain ⟨y, hy, rfl⟩ := mem_image.mp hk + exact (mem_sdiff.mp (hw' hy)).2 ((powered_iff p l C y).mp e)) + e := s.scene.level i, a := L.base.bigA s.scene.level, b := sumB L.stations + c := R.base.bigA s.scene.level + sizeU := (Nat.mul_le_mul hB (by omega)).trans_lt hAf + sizeV := (Nat.mul_le_mul (card_image_le.trans hC) (by omega)).trans_lt hCf + H := H, j := j, low := hj } + have fits : a.Fits L.base R.base s.scene.level := by + refine ⟨?_, ⟨R.base.inserts, ?_⟩, rfl, rfl, rfl⟩ + · have e : A = insert z L.base.sites := by unfold A; rw [← hL, Socket.sites] + have hz := L.avoids i z (hL.symm ▸ (u.distinct hv).1) + exact L.base.fixed_erase p l z hz A B (by rw [e]; exact subset_insert _ _) + (by unfold B; rw [← hL]; rfl) + · have e : C = insert y R.base.sites := by unfold C; rw [hw, Socket.sites] + have hy := R.avoids i y (hw ▸ hv.distinct w) + have hC : R.base.sites ⊆ C := by + rw [e] + exact subset_insert _ _ + exact R.base.fixed_erase p l y hy C R.base.inserts hC Subset.rfl + have vhere : s.scene.cell u.atCell = (L.plug i z).insert u.mover := by rw [hL, u.cell] + have vl : Unused i L.base.ports := L.unused i z (by + have h := hl.unique u.atCell; rw [ports, vhere] at h; exact h) + have vr : Unused i R.base.ports := R.unused i y (by + have h := hl.unique w; rw [ports, hw] at h; exact h) + have ready : s.Ready u.atCell L.stations := by + have h := u.ready; rw [← hL] at h; exact h + have old := cross_terms (g := g) p l rfl hv u.atCell w i L R u.mover a u.clock + vhere hw ne rfl rfl u.role hc ready fits vl vr other + (fun k hk => (mem_sdiff.mp (hu' k.2)).2 (List.mem_toFinset.mpr (hL ▸ hk))) + (fun k hk => (mem_sdiff.mp (hw' (hf k))).2 (List.mem_toFinset.mpr (hw.symm ▸ hk))) + apply old.mono + exact hop_card ((s.scene.level i + u.mover.a + L.base.bigA s.scene.level) / 2) + (s.scene.level i) u.mover.a j U' V' _ hcu.le hcv.le (by omega) (by omega) (by omega) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # One productive step at any active insertion -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion Stage +variable {F T V E X : Type} [Field F] [Fintype F] [Fintype E] [Fintype V] + {r t g H U M N : ℕ} {s : Stage F r t T V E X} {src dst : E → V} + +open scoped Classical in +/-- The number of branches in one step is bounded independently of the +actual field cardinality. -/ +def branches (P g H M N : ℕ) := breadth P g H M N (M * (2 * N) + 1) + +open scoped Classical in +theorem branches_pos (P g H M N : ℕ) : 0 < branches P g H M N := by + unfold branches breadth window + positivity + +open scoped Classical in +theorem Move.run (u : Move s) (p l : ℕ) [ExpChar F p] (hl : s.Layout src dst g) + (hv : s.Valid U) (hr : s.Room M N) (hs : M * (2 * N + 1) < Fintype.card F) : + Terms (p ^ l) (s.Gain (p ^ l) g H U) (branches (p ^ l) g H M N) (s.value (p ^ l)) := by + let P := p ^ l + let K := M * (2 * N) + 1 + by_cases old : u.clock = U + · exact (freeze_terms hv u.atCell u.rest u.mover u.cell (u.role.trans (by rw [old])) u.ready).mono + (branches_pos _ _ _ _ _) + have ht : u.clock < U := by + have he := hv.bound u.atCell u.mover (by rw [u.cell]; exact List.mem_cons_self) + rw [u.role] at he + exact lt_of_le_of_ne he old + obtain ⟨c, hc, hc'⟩ := u.collector hv + let Z := u.rest.sites + let B := u.rest.inserts + let D := u.rest.seams + have cz : c.pos ∈ Z := u.rest.inserts_sub (u.rest.mem_inserts hc) + have cd : c.pos ∉ D := disjoint_left.mp (u.rest.disjoint (u.distinct hv).1) (u.rest.mem_inserts + hc) + have hd : D.card ≤ g := by + have e := hl.degree u.atCell + rw [ports, u.cell] at e + exact (List.toFinset_card_le _).trans ((List.length_map _).le.trans e) + let L := u.threshold P H + obtain ⟨w, hw⟩ := s.scene.reconstruct p l u.atCell Z B D u.rest.inserts_sub u.rest.seams_sub + c.pos cz cd g L hd u.mover.pos (u.distinct hv).2 (by + rw [u.cell]; intro a ha + rcases List.mem_cons.mp ha with rfl|ha + · exact .inl rfl + · exact .inr (u.rest.mem_inserts ha)) (by + rw [u.cell]; exact fun _ h => u.rest.seams_sub (u.rest.mem_seams h)) + let I := Σ y : Z, Fin (orders D c.pos (u.order P) g L y.val) + let order (i : I) : ℤ := (i.2.val : ℤ) - u.order P i.1.val + let term (i : I) := s.observe P u.atCell (u.test P i.1.val (order i)) + have eqn : s.value P = fun x => ∑ i : I, w i * term i x := by + funext x + unfold value + rw [funext hw, trace_sum] + exact sum_congr rfl fun i _ => trace_mul _ _ _ _ _ + have inter (i : I) : Terms P (s.Gain P g H U) (width P g H N K) (term i) := by + let z := i.1.val + have hi : i.2.val < orders D c.pos (u.order P) g L z := i.2.isLt + change Terms _ _ _ (s.observe P u.atCell (u.test P z (order i))) + by_cases seam : z ∈ D + · have he : (L : ℤ) ≤ -(order i) := by + conv at hi => rhs; rw [orders, ite_eq_left seam] + dsimp only [order, z] at * + omega + obtain ⟨⟨j, y⟩, hj, hy⟩ := List.mem_map.mp (List.mem_toFinset.mp seam) + exact u.exit p l hl hv hr ht hs j z (hy ▸ hj) _ he + conv at hi => rhs; rw [orders, ite_eq_right seam] + by_cases dest : z = c.pos + · rw [ite_eq_left dest] at hi + have he : order i ≤ (g * L : ℕ) := by dsimp only [order, z] at *; omega + rw [dest] + exact u.absorb p l hv hr c hc _ (by rw [ite_eq_left hc']; exact he) + rw [ite_eq_right dest] at hi + have he : order i ≤ 0 := by dsimp only [order, z] at *; omega + have hz : z ∈ B := by + have hz : z ∈ u.rest.sites := i.1.property + rw [Cell.sites_eq] at hz + exact (mem_union.mp hz).resolve_right seam + obtain ⟨a, ha, heq⟩ := List.mem_map.mp (List.mem_toFinset.mp hz) + rw [← heq] + exact u.absorb p l hv hr a ha _ (by split_ifs <;> omega) + have bound : Fintype.card I ≤ M * window P g H N := + orders_card (u.order_le hr) (u.threshold_le hr) (u.room hr).1 + rw [eqn] + refine (Terms.combine w term inter).mono ?_ + calc + _ ≤ (M + 1) * window P g H N * width P g H N K := + Nat.mul_le_mul_right _ (bound.trans (Nat.mul_le_mul_right _ (Nat.le_succ M))) + _ = _ := by unfold branches breadth width K P; ring + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- +# Elimination of all active insertions + +Each productive step lowers an integer potential. The bound counts +only outer choices. All seam states and ordinary residue indices +remain inside the terms. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Finset +variable {F T V E X : Type} [Field F] [Fintype F] [Fintype V] [Fintype E] + {r t g H U M N : ℕ} {src dst : E → V} (s : Stage F r t T V E X) + +open scoped Classical in +private theorem one_step (p l : ℕ) [ExpChar F p] (hl : s.Layout src dst g) + (hv : s.Valid U) (hr : s.Room M N) (hs : M * (2 * N + 1) < Fintype.card F) + (active : ¬s.Stopped) : + Terms (p ^ l) (s.Gain (p ^ l) g H U) (branches (p ^ l) g H M N) (s.value (p ^ l)) := by + obtain ⟨v, a, b, u, n, hc, ha, _, hk⟩ := hv.choose active + let y := s.reord v a [u] b + have perm : (s.scene.cell v).stations.Perm ([u] ++ a ++ b) := by + rw [hc] + exact List.perm_middle + have step : s.Step (p ^ l) g H U y := .perm s v _ perm + have valid : y.Valid U := hv.perm v _ perm + have room : y.Room M N := hr.perm v _ perm + let c : y.Ct := ⟨(s.scene.cell v).ports, a ++ b⟩ + have he : y.scene.cell v = c.insert u := by simp [y, reord, put, Scene.put, Cell.insert, c] + have ready : y.Ready v c.stations := by + refine ⟨hk.1, fun w hw t ht => hk.2 w hw t ?_⟩ + simp only [y, reord, put, Scene.put, Function.update_of_ne hw] at ht + exact ht + let m : Move y := ⟨v, c, u, n, he, ha, ready⟩ + have go := m.run (H := H) p l (step.layout hl) valid room hs + rw [← observe_forms y v] at go + rw [← observe_forms s v] + exact rotate_terms v forms forms_signed a [u] b (by simpa using hc) go + +open scoped Classical in +/-- Eliminate every mover, uniformly over ordinary inputs. The local +room requirement follows from the initial bounds in `Reach.room`. -/ +theorem complete (p l : ℕ) [ExpChar F p] (hl : s.Layout src dst g) (hv : s.Valid U) + (room : ∀ y, s.Reach (p ^ l) g H U y → y.Room M N) (hF : M * (2 * N + 1) < Fintype.card F) : + Terms (p ^ l) (fun y => s.Reach (p ^ l) g H U y ∧ y.Valid U ∧ y.Stopped) + (branches (p ^ l) g H M N ^ s.potential U) (s.value (p ^ l)) := by + let P := p ^ l + let good (y) := s.Reach P g H U y ∧ y.Valid U ∧ y.Stopped + let k := branches P g H M N + have hk : 0 < k := branches_pos _ _ _ _ _ + have layout (y) (h : s.Reach P g H U y) : y.Layout src dst g := by + induction h with + | refl => exact hl + | tail _ h ih => exact h.layout ih + have go (n : ℕ) (y : Stage F r t T V E X) (hy : s.Reach P g H U y) (valid : y.Valid U) + (hdecr : y.potential U ≤ n) : Terms P good (k ^ n) (y.value P) := by + induction n using Nat.strong_induction_on generalizing y with + | ind n ih => + by_cases stop : y.Stopped + · exact (Terms.one (good := good) ⟨hy, valid, stop⟩).mono (pow_pos hk _) + obtain ⟨I, fi, c, z, hc, hz, he⟩ := + y.one_step (H := H) p l (layout y hy) valid (room y hy) hF stop + cases n with + | zero => + have e (i : I) : False := by have := (hz i).2.2; omega + have : IsEmpty I := ⟨e⟩ + exact ⟨I, fi, c, z, by simp, fun i => (e i).elim, he⟩ + | succ n => + have h (i : I) : Terms P good (k ^ n) ((z i).value P) := by + obtain ⟨reach, hv, lt⟩ := hz i + exact ih n (by omega) (z i) (hy.trans reach) hv (by omega) + rw [funext he, pow_succ'] + exact (Terms.combine c _ h).mono (Nat.mul_le_mul_right _ hc) + exact go _ s .refl hv le_rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- +# Scales of one local concentration + +The accuracy parameter `q` sets the private-wire rate. There are `d*b` +public species and `d` private ones. Their ratio `b` equals the +Frobenius power `P` times `q^4`. Only the number of blocks `d` +grows with the input scale `T`. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale + +open Routing.Private + +/-- The quantity computed by `D ^ (ℓ + 32)`. -/ +def q (ℓ D : ℕ) := D ^ (ℓ + 32) +/-- The quantity computed by `q ℓ D ^ 8`. -/ +def size (ℓ D : ℕ) := q ℓ D ^ 8 +/-- The quantity computed by `q ℓ D ^ 2`. -/ +def chunks (ℓ D : ℕ) := q ℓ D ^ 2 +/-- The quantity computed by `1600 * D * size ℓ D`. -/ +def probes (ℓ D : ℕ) := 1600 * D * size ℓ D +/-- The quantity computed by `R * size ℓ D ^ 2`. -/ +def energy (ℓ D R : ℕ) := R * size ℓ D ^ 2 +/-- The quantity computed by `10000000 * (1 + 4 * g) * (energyConstant + 1)`. -/ +def budget (g : ℕ) := 10000000 * (1 + 4 * g) * (energyConstant + 1) +/-- The quantity computed by `1 / (4 * (q ℓ D : ℝ))`. -/ +def rate (ℓ D : ℕ) := 1 / (4 * (q ℓ D : ℝ)) + +/-- Enough distinct points for all original and auxiliary marks. -/ +def slots (ℓ D g : ℕ) := 100 * D + 2 * g + probes ℓ D + 1 + +/-- The quantity computed by `slots ℓ D g + budget g * D ^ 2`. -/ +def room (ℓ D g : ℕ) := slots ℓ D g + budget g * D ^ 2 +/-- The quantity computed by `budget g * D ^ 2 * m * energy ℓ D R`. -/ +def depth (ℓ D g m R : ℕ) := budget g * D ^ 2 * m * energy ℓ D R + +/-- The data for the scales construction, including `large`, `pos`, `block`, `divides`, `many`. -/ +structure Scales (g ℓ D T P b d : ℕ) : Prop where + large : 2 * budget g ≤ D + pos : 0 < P + block : b = P * q ℓ D ^ 4 + divides : chunks ℓ D ∣ d + many : q ℓ D ^ 4 ≤ d * b + lower : d * b * size ℓ D ≤ T + upper : T ≤ 2 * (d * b * size ℓ D) + +theorem budget_large (g : ℕ) : 10000000 ≤ budget g := by + unfold budget + calc + 10000000 = 10000000 * 1 * 1 := by norm_num + _ ≤ _ := by gcongr <;> omega + +namespace Scales +variable {g ℓ D T P b d : ℕ} (h : Scales g ℓ D T P b d) +include h + +theorem bound : 10000000 ≤ D := (budget_large _).trans ((Nat.le_mul_of_pos_left _ (by + decide)).trans h.large) +theorem Dpos : 0 < D := lt_of_lt_of_le (by decide) h.bound +theorem Dle : D ≤ q ℓ D := by + simpa only [q, pow_one] using Nat.pow_le_pow_right h.Dpos (by omega : 1 ≤ ℓ + 32) +theorem qpos : 0 < q ℓ D := h.Dpos.trans_le h.Dle +theorem apos : 0 < size ℓ D := pow_pos h.qpos _ +theorem Mpos : 0 < chunks ℓ D := pow_pos h.qpos _ +theorem Rpos : 0 < d * b := (pow_pos h.qpos _).trans_le h.many +theorem Tpos : 0 < T := (Nat.mul_pos h.Rpos h.apos).trans_le h.lower +theorem Hpos : 0 < energy ℓ D (d * b) := Nat.mul_pos h.Rpos (pow_pos h.apos _) +theorem rate_pos : 0 < rate ℓ D := by have := h.qpos; unfold rate; positivity + +theorem smallR : d * b * D ^ 2 ≤ T := by + refine (Nat.mul_le_mul_left _ ?_).trans h.lower + exact (Nat.pow_le_pow_left h.Dle 2).trans (Nat.pow_le_pow_right h.qpos (by decide)) + +theorem smallH : energy ℓ D (d * b) ≤ T * size ℓ D := by + simpa only [energy, pow_two, mul_assoc] using Nat.mul_le_mul_right (size ℓ D) h.lower + +theorem smallM : chunks ℓ D ≤ d * b := + (Nat.pow_le_pow_right h.qpos (by decide : 2 ≤ 4)).trans h.many + +omit h in +theorem overhead : energyConstant + 1 ≤ budget g := by + unfold budget + apply Nat.le_mul_of_pos_left + positivity + +theorem degree : 2 * g ≤ D := by + have hl := h.large + have : 10000000 * (1 + 4 * g) ≤ budget g := Nat.le_mul_of_pos_right _ (by omega) + omega + +end Scales +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end + +/- # Polynomial bounds for the local expansion at one occupied cell -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale + +open Sphere.Surface Routing.Private + +/-- The quantity computed by `((d * b + 1) * (d * (energyConstant * b ^ 2) + 1)) ^ probes ℓ D`. -/ +def initialChoices (ℓ D b d : ℕ) := ((d * b + 1) * (d * (energyConstant * b ^ 2) + 1)) ^ probes ℓ D +/-- The value specified by `branches m (2 * g) (energy ℓ D (d * b)) (room ℓ D g) (depth ℓ D g m +(d * b)) ^ ((2 + 2 * D ^ 5) * (100 * D + probes ℓ D + 1))`. -/ +def moveChoices (g ℓ D m b d : ℕ) := + branches m (2 * g) (energy ℓ D (d * b)) (room ℓ D g) (depth ℓ D g m (d * b)) ^ + ((2 + 2 * D ^ 5) * (100 * D + probes ℓ D + 1)) +/-- The quantity computed by `(depth ℓ D g m (d * b) + 1) ^ (chunks ℓ D * (2 * g + 2 * room ℓ D +g))`. -/ +def finalChoices (g ℓ D m b d : ℕ) := + (depth ℓ D g m (d * b) + 1) ^ (chunks ℓ D * (2 * g + 2 * room ℓ D g)) + +private theorem polynomial (g ℓ D m b : ℕ) : + Poly (fun d => room ℓ D g * (2 * depth ℓ D g m (d * b) + 1) + 1 + + initialChoices ℓ D b d * moveChoices g ℓ D m b d * finalChoices g ℓ D m b d) := by + let M := room ℓ D g + let H d := energy ℓ D (d * b) + let N d := depth ℓ D g m (d * b) + have he : Poly H := (Poly.var.mul (.const b)).mul (.const _) + have hd : Poly N := (Poly.const _).mul he + have hf : Poly (fun d => M * (2 * N d + 1) + 1) := + ((Poly.const M).mul (((Poly.const 2).mul hd).add (.const 1))).add (.const 1) + have h₁ : Poly (initialChoices ℓ D b) := + (((Poly.var.mul (.const b)).add (.const 1)).mul + ((Poly.var.mul (.const _)).add (.const 1))).pow _ + have hr : Poly (fun d => m * N d + N d) := ((Poly.const m).mul hd).add hd + have hw : Poly (fun d => window m (2 * g) (H d) (N d)) := + (hr.add ((Poly.const _).mul (hr.add ((Poly.const _).mul he)))).add (.const 1) + have hk : Poly (fun d => M * (2 * N d) + 1) := + ((Poly.const M).mul ((Poly.const 2).mul hd)).add (.const 1) + have h₂ : Poly (moveChoices g ℓ D m b) := + ((((Poly.const (M + 1)).mul (hw.pow 2)).mul (hd.add (.const 1))).mul (hk.pow 2)).pow _ + have h₃ : Poly (finalChoices g ℓ D m b) := (hd.add (.const 1)).pow _ + exact hf.add ((h₁.mul h₂).mul h₃) + +theorem choice_bound (g ℓ D m b : ℕ) : + ∃ A : ℕ, ∀ {T d : ℕ}, Scales g ℓ D T m b d → + room ℓ D g * (2 * depth ℓ D g m (d * b) + 1) < A * (1 + T) ^ A ∧ + initialChoices ℓ D b d * moveChoices g ℓ D m b d * finalChoices g ℓ D m b d ≤ + 2 ^ (A * (1 + Nat.clog 2 (T + 1))) := by + obtain ⟨k, hk⟩ := polynomial g ℓ D m b + refine ⟨2 ^ k, fun {T d} sc => ?_⟩ + have ht : d ≤ T := by + have := sc.Rpos + exact (Nat.le_mul_of_pos_right d (Nat.pos_of_mul_pos_left sc.Rpos)).trans + ((Nat.le_mul_of_pos_right _ sc.apos).trans sc.lower) + have ub := (hk d).trans (Nat.pow_le_pow_left (by omega : d + 2 ≤ 2 * (1 + T)) k) + have hb : k ≤ 2 ^ k := Nat.lt_two_pow_self.le + constructor + · have h : (2 * (1 + T)) ^ k ≤ 2 ^ k * (1 + T) ^ (2 ^ k) := by + rw [mul_pow] + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) hb) + exact (Nat.lt_of_succ_le (Nat.le_add_right _ _)).trans_le (ub.trans h) + · refine (Nat.le_add_left _ _).trans (ub.trans ?_) + calc + _ ≤ (2 ^ (1 + Nat.clog 2 (T + 1))) ^ k := by + apply Nat.pow_le_pow_left + rw [pow_add, pow_one, Nat.add_comm 1 T] + exact Nat.mul_le_mul_left _ (Nat.le_pow_clog (by decide) _) + _ ≤ _ := by + rw [← pow_mul, Nat.mul_comm] + exact Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ hb) + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end + +/- +# Choosing a field and block sizes + +The planting field, positions, Frobenius power and block size can all +be fixed before the width tends to infinity. Rounding the number of +blocks to a multiple of the chunk count loses at most half the width. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale + +open Filter Finset Sphere + +private theorem large_subfield (k : Type) [Field k] [Finite k] (M : ℕ) : + ∃ (F : Type) (_ : Field F) (_ : Fintype F) (_ : Algebra k F) + (_ : Algebra F (AlgebraicClosure k)), M ≤ Fintype.card F := by + classical + let x : Fin M ↪ AlgebraicClosure k := Fin.valEmbedding.trans (Infinite.natEmbedding _) + let K := IntermediateField.adjoin k (Set.range x) + have : Finite (Set.range x) := Set.finite_range _ |>.to_subtype + have : Module.Finite k K := IntermediateField.finiteDimensional_adjoin + (fun x _ => Algebra.IsIntegral.isIntegral x) + have : Finite K := Module.finite_of_finite k + let _ : Fintype K := Fintype.ofFinite K + let f (i : Fin M) : K := ⟨x i, IntermediateField.subset_adjoin k _ ⟨i, rfl⟩⟩ + refine ⟨K, inferInstance, inferInstance, inferInstance, inferInstance, ?_⟩ + simpa using Fintype.card_le_of_injective f (fun _ _ h => x.injective (congrArg Subtype.val h)) + +variable {g ℓ D : ℕ} + +private theorem scales_eventual (large : 2 * budget g ≤ D) + (P b : ℕ) (hp : 0 < P) (hb : b = P * q ℓ D ^ 4) (d₀ : ℕ) : + ∀ᶠ T : ℕ in atTop, ∃ d ≥ d₀, Scales g ℓ D T P b d := by + have hd : 0 < D := by have := budget_large g; omega + have hq : 0 < q ℓ D := pow_pos hd _ + have ha : 0 < size ℓ D := pow_pos hq _ + have hm : 0 < chunks ℓ D := pow_pos hq _ + have hb' : 0 < b := by rw [hb]; positivity + let v := chunks ℓ D * b * size ℓ D + have hv : 0 < v := by unfold v; positivity + filter_upwards [eventually_ge_atTop ((d₀ + 1) * v)] with T hT + have h : d₀ + 1 ≤ T / v := (Nat.le_div_iff_mul_le hv).mpr hT + let d := chunks ℓ D * (T / v) + have h₀ : d₀ + 1 ≤ d := h.trans (Nat.le_mul_of_pos_left _ hm) + have he : d * b * size ℓ D = T / v * v := by unfold d v; ring + refine ⟨d, by omega, large, hp, hb, ⟨T / v, rfl⟩, ?_, ?_, ?_⟩ + · exact (show q ℓ D ^ 4 ≤ b by rw [hb]; exact Nat.le_mul_of_pos_left _ hp).trans + (Nat.le_mul_of_pos_left b (by omega)) + · rw [he]; exact Nat.div_mul_le_self _ _ + · rw [he] + have hh := Nat.le_mul_of_pos_left v (by omega : 0 < T / v) + have := Nat.div_add_mod' T v + have := Nat.mod_lt T hv + omega + +/-- The ready of type `Prop` for the given inputs. -/ +def Ready (F : Type) [Field F] (ℓ D g P b d : ℕ) : Prop := + ∀ (B T E X : Type) (_ : Field B) (_ : Algebra F B) (u : Template F B T E X (d * b)), + (∑ i, 4 * u.width i) ≤ probes ℓ D → u.stations ≤ 100 * D → u.ports ≤ 2 * g → + Nonempty (u.Patch P (probes ℓ D) (rate ℓ D)) + +theorem choose (k : Type) [Field k] [Finite k] (sync : Prices.SharedPrice (AlgebraicClosure k)) + (large : 2 * budget g ≤ D) : + ∃ (F : Type) (_ : Field F) (_ : Fintype F) (_ : Algebra k F) + (p l b : ℕ) (_ : CharP F p) (_ : Fact p.Prime), + ∀ᶠ T : ℕ in atTop, ∃ d, Scales g ℓ D T (p ^ l) b d ∧ Ready F ℓ D g (p ^ l) b d := by + have hd : 0 < D := by have := budget_large g; omega + have hq : 0 < q ℓ D := pow_pos hd _ + have ha : 0 < size ℓ D := pow_pos hq _ + have : NeZero (probes ℓ D) := ⟨by unfold probes; positivity⟩ + obtain ⟨F, _, _, _, _, hF⟩ := large_subfield k (slots ℓ D g) + obtain ⟨p, hp⟩ := CharP.exists F + have : Fact p.Prime := ⟨CharP.char_is_prime F p⟩ + obtain ⟨b₀, hb⟩ := eventually_atTop.mp + (Template.patches (F := F) (n := probes ℓ D) sync (show 0 + < rate ℓ D by unfold rate; positivity)) + let b := p ^ b₀ * q ℓ D ^ 4 + have hp' : 0 < p := (Fact.out : p.Prime).pos + have big : b₀ ≤ b := (Nat.lt_two_pow_self.le.trans + (Nat.pow_le_pow_left (Fact.out : p.Prime).two_le _)).trans (Nat.le_mul_of_pos_right _ (pow_pos + hq _)) + obtain ⟨d₀, hd₀⟩ := eventually_atTop.mp (hb b big) + refine ⟨F, inferInstance, inferInstance, inferInstance, p, b₀, b, hp, inferInstance, ?_⟩ + filter_upwards [scales_eventual large _ b (pow_pos hp' b₀) rfl d₀] with T hT + obtain ⟨d, hd, hs⟩ := hT + refine ⟨d, hs, ?_⟩ + intro B V E X _ _ u hw hu hv + apply hd₀ d hd _ ?_ B V E X inferInstance inferInstance u hw (by unfold slots at hF; omega) + exact (iterateFrobenius F p b₀).injective + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Ledger.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Ledger.lean new file mode 100644 index 0000000000..5b07046f3f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Ledger.lean @@ -0,0 +1,1020 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Tactic.Linarith +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Pull +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.TableMotion +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam + +/-! +# Energy accounting during motion + +Work in integral units. Mobile energy includes one reserve per mover. +At terminal fusion the increase in collector energy may be as large +as `1+2g` times the departing budget. Weight mobile energy by that +factor throughout. The local balance includes incident seam energy, +whereas the global balance does not. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +open Finset + +open scoped Classical in +/-- The data for the ledger construction, including `mobile`, `collected`, `seam`, `hits`, +`clock`. -/ +structure Ledger (V E : Type) where + /-- The `Ledger` component of type `V → ℕ`. -/ + mobile : V → ℕ + /-- The `Ledger` component of type `V → ℕ`. -/ + collected : V → ℕ + /-- The `Ledger` component of type `E → ℕ`. -/ + seam : E → ℕ + /-- The `Ledger` component of type `E → ℕ`. -/ + hits : E → ℕ + /-- Stores the clock associated with this `Ledger`. -/ + clock : ℕ + /-- Stores the expired associated with this `Ledger`. -/ + expired : ℕ + +namespace Ledger +variable {V E : Type} [Fintype V] [Fintype E] + +open scoped Classical in +/-- The quantity computed by `(1 + 2 * g) * A.mobile v + A.collected v`. -/ +def cost (A : Ledger V E) (g : ℕ) (v : V) := (1 + 2 * g) * A.mobile v + A.collected v + +open scoped Classical in +/-- Telescoping bounds between two states, independent of the number +of intermediate fusions, crossings or expirations. -/ +structure Budget (N : V → Finset E) (g H U : ℕ) (A B : Ledger V E) : Prop where + total : (∑ v, B.cost g v) ≤ ∑ v, A.cost g v + site : ∀ v, B.cost g v + (1 + 2 * g) * (∑ e ∈ N v, B.seam e) ≤ + A.cost g v + (1 + 2 * g) * (∑ e ∈ N v, A.seam e) + edge : ∀ e, B.seam e + H * B.hits e ≤ A.seam e + H * A.hits e + time : U * B.expired + B.clock + (∑ e, A.hits e) ≤ U * A.expired + A.clock + ∑ e, B.hits e + +namespace Budget +variable {N : V → Finset E} {g H U : ℕ} {A B C : Ledger V E} + +open scoped Classical in +theorem refl : Budget N g H U A A := ⟨le_rfl, fun _ => le_rfl, fun _ => le_rfl, le_rfl⟩ + +open scoped Classical in +theorem trans (a : Budget N g H U A B) (b : Budget N g H U B C) : Budget N g H U A C := + ⟨b.total.trans a.total, fun v => (b.site v).trans (a.site v), + fun e => (b.edge e).trans (a.edge e), by have := a.time; have := b.time; omega⟩ + +open scoped Classical in +/-- Covers terminal fusion, continued fusion (`μ = 0`) and expiration. -/ +theorem collect (μ : V → ℕ) + (mob : ∀ v, B.mobile v + μ v ≤ A.mobile v) + (col : ∀ v, B.collected v ≤ A.collected v + (1 + 2 * g) * μ v) + (seam : B.seam = A.seam) (hits : B.hits = A.hits) + (time : U * B.expired + B.clock ≤ U * A.expired + A.clock) : Budget N g H U A B := by + have each (v : V) : B.cost g v ≤ A.cost g v := by + have h := Nat.mul_le_mul_left (1 + 2 * g) (mob v) + rw [mul_add] at h + have := col v + unfold cost + omega + exact ⟨sum_le_sum fun v _ => each v, fun v => by rw [seam]; exact Nat.add_le_add_right (each v) _, + fun _ => by rw [seam, hits], by rw [hits]; exact Nat.add_le_add_right time _⟩ + +open scoped Classical in +/-- A crossing transfers `γ` units between cells and spends at least +`μ` units of seam energy. Only the receiving cell needs the debit. -/ +theorem cross (v z : V) (e : E) (he : e ∈ N z) (μ γ : ℕ) (hh : H ≤ μ) (hg : γ ≤ μ) + (mob : ∀ a, B.mobile a + (if a = v then γ else 0) ≤ A.mobile a + (if a = z then γ else 0)) + (col : B.collected = A.collected) + (seam : ∀ i, B.seam i + (if i = e then μ else 0) ≤ A.seam i) + (hits : ∀ i, B.hits i = A.hits i + if i = e then 1 else 0) + (time : U * B.expired + B.clock ≤ U * A.expired + A.clock + 1) : Budget N g H U A B := by + have hm := sum_le_sum (fun a (_ : a ∈ univ) => mob a) + simp only [sum_add_distrib, sum_ite_eq', mem_univ, ite_true, Nat.add_le_add_iff_right] at hm + constructor + · simp only [cost, col, sum_add_distrib, ← mul_sum] + exact Nat.add_le_add_right (Nat.mul_le_mul_left _ hm) _ + · intro a + have h := sum_le_sum (fun i (_ : i ∈ N a) => seam i) + rw [sum_add_distrib, sum_ite_eq'] at h + have ha := mob a + have ht : B.mobile a + (∑ i ∈ N a, B.seam i) ≤ A.mobile a + ∑ i ∈ N a, A.seam i := by + by_cases ha' : a = z + · subst a + rw [ite_eq_left he] at h + rw [ite_eq_left rfl] at ha + omega + · rw [ite_eq_right ha'] at ha + omega + have hmul := Nat.mul_le_mul_left (1 + 2 * g) ht + simp only [mul_add] at hmul + simp only [cost, col] + omega + · intro i + have h := seam i + rw [hits, mul_add] + split_ifs at h ⊢ <;> omega + · simp_rw [hits, sum_add_distrib, sum_ite_eq', mem_univ, ite_true] + omega + +open scoped Classical in +/-- Current energy and crossing counts at any point of the procedure. -/ +theorem limits (h : Budget N g H U A B) (hits : ∀ e, A.hits e = 0) + (clock : A.clock = 0) (expired : A.expired = 0) : + (∑ v, (B.mobile v + B.collected v)) ≤ (1 + 2 * g) * (∑ v, (A.mobile v + A.collected v)) ∧ + (∀ v, B.mobile v + B.collected v ≤ (1 + 2 * g) * (A.mobile v + A.collected v + ∑ e ∈ N v, + A.seam e)) ∧ + (∀ v, H * (∑ e ∈ N v, B.hits e) ≤ ∑ e ∈ N v, A.seam e) ∧ + U * B.expired ≤ (∑ e, B.hits e) ∧ H * (∑ e, B.hits e) ≤ ∑ e, A.seam e := by + have lower v : B.mobile v + B.collected v ≤ B.cost g v := + Nat.add_le_add_right (Nat.le_mul_of_pos_left _ (by omega)) _ + have upper v : A.cost g v ≤ (1 + 2 * g) * (A.mobile v + A.collected v) := by + rw [mul_add] + exact Nat.add_le_add_left (Nat.le_mul_of_pos_left _ (by omega)) _ + have count (s : Finset E) : H * (∑ e ∈ s, B.hits e) ≤ ∑ e ∈ s, A.seam e := by + rw [mul_sum] + refine sum_le_sum fun e _ => ?_ + have := h.edge e + rw [hits] at this + omega + refine ⟨?_, ?_, fun v => count (N v), ?_, count univ⟩ + · rw [mul_sum] + exact (sum_le_sum fun v _ => lower v).trans (h.total.trans (sum_le_sum fun v _ => upper v)) + · intro v + have := h.site v + have := lower v + have := upper v + rw [mul_add] + omega + · have := h.time + simp only [hits, clock, expired, sum_const_zero, mul_zero, add_zero, zero_add] at this + omega + +end Budget +end Ledger +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Interpolating a cell in the common moving parameter -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion +variable {F T X E : Type} [Field F] {r t : ℕ} + +open scoped Classical in +/-- Any argument not at a stationary position uses the moving parameter. -/ +def token (S : Finset F) (x : Site F r) : Option S × Mode r := + (if h : x.1 ∈ S then some ⟨x.1, h⟩ else none, x.2) + +open scoped Classical in +/-- The value specified by `(if h : x.1 ∈ S then ⟨x.1, h⟩ else c, x.2)`. -/ +def fixed {S : Finset F} (c : S) (x : Site F r) : S × Mode r := + (if h : x.1 ∈ S then ⟨x.1, h⟩ else c, x.2) + +omit [Field F] in +open scoped Classical in +@[simp] theorem weight_token (S : Finset F) (l : List (Site F r)) : + weight (l.map (token S)) = weight l := by simp [weight, token, Function.comp_def] + +omit [Field F] in +open scoped Classical in +@[simp] theorem weight_fixed {S : Finset F} (c : S) (l : List (Site F r)) : + weight (l.map (fixed c)) = weight l := by simp [weight, fixed, Function.comp_def] + +omit [Field F] in +open scoped Classical in +theorem read_fixed {S : Finset F} (c : S) (l : List (Site F r)) (hl : ∀ x ∈ l, x.1 ∈ S) : + spectators (l.map (fixed c)) = l := by + simp only [spectators, List.map_map] + conv_rhs => rw [← List.map_id l] + exact List.map_congr_left fun x hx => by simp [fixed, hl x hx] + +omit [Field F] in +open scoped Classical in +theorem fixed_avoids {S : Finset F} (c : S) (l : List (Site F r)) (hl : ∀ x ∈ l, x.1 ∈ S) + (hn : ∀ x ∈ l, x.1 ≠ c.val) : ∀ y ∈ l.map (fixed c), y.1 ≠ c := by + simp only [List.forall_mem_map] + intro x hx + simp only [fixed, dite_eq_left (hl x hx)] + exact fun h => hn x hx (congrArg Subtype.val h) + +open scoped Classical in +theorem read_tokens (S : Finset F) (l : List (Site F r)) (z : F) + (h : ∀ x ∈ l, x.1 = z ∨ x.1 ∈ S) : (l.map (token S)).map (atPoint z) = l := by + rw [List.map_map] + conv_rhs => rw [← List.map_id l] + refine List.map_congr_left fun x hx => ?_ + by_cases ht : x.1 ∈ S + · simp [token, atPoint, ht] + · simp [token, atPoint, ht, ← (h x hx).resolve_right ht] + +omit [Field F] in +open scoped Classical in +theorem triple_tokens {S : Finset F} (c : S) (z : F) (hz : z ∉ S) (a x : Wedge r) + (l : List (Site F r)) (hl : ∀ y ∈ l, y.1 ∈ S) : + (modes c.val a ++ modes z x ++ l).map (token S) = triple c a.val x.val (l.map (fixed c)) := by + simp only [triple, modes, List.map_append, List.map_map, Function.comp_def, token, fixed, + dite_eq_left c.property, dite_eq_right hz] + congr 1 + exact List.map_congr_left fun y hy => by simp [token, hl y hy] + +open scoped Classical in +/-- Evaluates `pairedCoeff P z (l.map (token A)) (m.map (token B)) j` at the input `l m`. -/ +def coefficient (P : ℕ) (A B : Finset F) (z : F) (j : ℤ) : Test F r t := + fun l m => pairedCoeff P z (l.map (token A)) (m.map (token B)) j + +open scoped Classical in +/-- The quantity computed by `(sumA c.stations + portWeight d c.ports) / 2`. -/ +def Cell.orderA (c : Cell F r t T E X) (d : E → ℕ) := (sumA c.stations + portWeight d c.ports) / 2 +open scoped Classical in +/-- The quantity computed by `sumB c.stations / 2`. -/ +def Cell.orderB (c : Cell F r t T E X) := sumB c.stations / 2 + +open scoped Classical in +/-- The interpolation weights are independent of station tables, external +assignments, and the states being summed on all incident seams. -/ +theorem reconstruct_cells (p l : ℕ) [ExpChar F p] (da db : ℕ) + (S B seams : Finset F) (hB : B ⊆ S) (hs : seams ⊆ S) (collector : F) + (hc : collector ∈ S) (hc' : collector ∉ seams) (g L : ℕ) (hg : seams.card ≤ g) + (z : F) (hz : z ∉ S) : + let P := p ^ l + let D := poleOrder P da db B + ∃ v : (Σ y : S, Fin (orders seams collector D g L y.val)) → F, + ∀ {T E X : Type} (c : Cell F r t T E X) (d : E → ℕ), + c.orderA d = da → c.orderB = db → + (∀ a ∈ c.stations, a.pos = z ∨ a.pos ∈ B) → (∀ i ∈ c.ports, i.2 ∈ S) → + ∀ (x : X) (h : E → Wedge r), (∀ i ∈ c.ports, energy (h i.1).val = d i.1) → + c.eval P x h = ∑ j, v j * c.test P x h + (coefficient P (powered P S) B j.1.val ((j.2.val : ℤ) - D j.1.val)) := by + intro P D + obtain ⟨v, hv⟩ := paired_reconstruction (r := r) (t := t) p l hB hs hc hc' g L hg + da db z hz + refine ⟨v, ?_⟩ + intro T E X c d ha hb st pt x h hh + subst da; subst db + simp only [Cell.eval, Cell.test, ← batch_mul_left, ← batch_sum] + apply batch_congr + intro u w hw + let a := u ++ ends P h c.ports + have ha : ∀ i ∈ a, i.1 = z ^ P ∨ i.1 ∈ powered P S := by + intro i hi + rcases List.mem_append.mp hi with hi|hi + · obtain ⟨j, hj, he⟩ := hw.left i hi + rw [he] + rcases st j hj with h₁|h₁ + · exact Or.inl (by rw [h₁]) + · exact Or.inr (mem_image_of_mem _ (hB h₁)) + · obtain ⟨j, hj, he⟩ := mem_ends P h _ _ hi + rw [he] + exact Or.inr (mem_image_of_mem _ (pt j hj)) + have hb : ∀ i ∈ w, i.1 = z ∨ i.1 ∈ B := by + intro i hi + obtain ⟨j, hj, he⟩ := hw.right i hi + rw [he] + exact st j hj + have e := hv (a.map (token (powered P S))) (w.map (token B)) + (by simp only [a, weight_token, weight_append, hw.wa, weight_ends _ _ _ _ hh, Cell.orderA]) + (by simp only [weight_token, hw.wb, Cell.orderB]) + rw [read_tokens _ _ _ ha, read_tokens _ _ _ hb] at e + exact e + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Changing the station order, including in a Laurent coefficient -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion +variable {F T X E : Type} [Field F] {r t : ℕ} + +open scoped Classical in +/-- The defining condition `∀ a b c u v w, f (a ++ b ++ c) (u ++ v ++ w) = (-1 : F) ^ (weight a +* weight b + weight u * weight v) * f (b ++ a ++ c) (v ++ u ++ w)`. -/ +def Signed (f : Test F r t) : Prop := + ∀ a b c u v w, f (a ++ b ++ c) (u ++ v ++ w) = + (-1 : F) ^ (weight a * weight b + weight u * weight v) * f (b ++ a ++ c) (v ++ u ++ w) + +open scoped Classical in +private theorem swap {A R : Type*} [CommRing R] {k : (A × Mode r) → (A × Mode r) → R} + (sk : ∀ x y, k y x = -k x y) (a b c : List (A × Mode r)) : + wick k (a ++ b ++ c) = (-1 : R) ^ (weight a * weight b) * wick k (b ++ a ++ c) := by + have par (a : List (A × Mode r)) : weight a % 2 = a.length % 2 := by + simpa only [List.length_map] using energy_mod_two (a.map Prod.snd) + have hs : (-1 : R) ^ (weight a * weight b) = (-1 : R) ^ (a.length * b.length) := by + rw [neg_one_pow_eq_pow_mod_two, neg_one_pow_eq_pow_mod_two (a.length * b.length)] + congr 1 + exact Nat.ModEq.mul (par a) (par b) + rw [hs] + exact wick_swap_blocks sk [] a b c + +open scoped Classical in +theorem forms_signed : Signed (forms (F := F) (r := r) (t := t)) := by + intro a b c u v w + unfold forms + rw [swap fieldKernel_skew a b c, swap fieldKernel_skew u v w, pow_add, mul_mul_mul_comm] + +open scoped Classical in +private theorem num_swap (S : Finset F) (a b c : List (Site F r)) : + numerator S ((a ++ b ++ c).map (token S)) = + Polynomial.C ((-1 : F) ^ (weight a * weight b)) * numerator S ((b ++ a ++ c).map (token S)) + := by + have h := swap (Routing.polynomial_skew (trajectories S)) + (a.map (token S)) (b.map (token S)) (c.map (token S)) + simpa only [numerator, Routing.correlatorPoly, List.map_append, weight_token, map_pow, map_neg, + map_one] + using h + +open scoped Classical in +theorem coefficient_signed (P : ℕ) (A B : Finset F) (z : F) (j : ℤ) : + Signed (coefficient (r := r) (t := t) P A B z j) := by + intro a b c u v w + unfold coefficient pairedCoeff denominatorPoly + simp only [weight_token, weight_append] + rw [num_swap A a b c, num_swap B u v w, Nat.add_comm (weight a), Nat.add_comm (weight u)] + unfold coupled + rw [Polynomial.mul_comp, Polynomial.C_comp, mul_mul_mul_comm, ← map_mul, ← pow_add, coeff_scale] + +variable (P : ℕ) (x : X) (us vs : List (Station F r t T X)) + +open scoped Classical in +theorem batch_comm (f : List (Site F r) → List (Site F t) → Test F r t) : + batch P x us (fun a b => batch P x vs (f a b)) = + batch P x vs (fun c d => batch P x us (fun a b => f a b c d)) := by + induction us generalizing f with + | nil => rfl + | cons s us ih => + simp only [batch, batch_sum, batch_mul_left] + refine sum_congr rfl fun a _ => sum_congr rfl fun b _ => congrArg (s.table x a b * ·) ?_ + exact ih _ + +open scoped Classical in +theorem rotate (ws : List (Station F r t T X)) (h : E → Wedge r) + (ports : List (E × F)) (f : Test F r t) (hf : Signed f) : + Cell.test P x ⟨ports, us ++ vs ++ ws⟩ h f = + (-1 : F) ^ (sumA us * sumA vs + sumB us * sumB vs) * + Cell.test P x ⟨ports, vs ++ us ++ ws⟩ h f := by + simp only [Cell.test, batch_append, ← batch_mul_left] + rw [batch_comm] + apply batch_congr + intro a b hv + apply batch_congr + intro c d hu + apply batch_congr + intro i j _ + simpa only [hu.wa, hu.wb, hv.wa, hv.wb, List.append_assoc] using + hf c a (i ++ ends P h ports) d b j + +open scoped Classical in +theorem port_front (h : E → Wedge r) (l k : List (E × F)) (c : E × F) + (f : Test F r t) (hf : Signed f) : + Cell.test P x ⟨l ++ c :: k, us⟩ h f = + (-1 : F) ^ ((sumA us + weight (ends P h l)) * energy (h c.1).val) * + batch P x us (fun a b => f (modes (c.2 ^ P) (h c.1) ++ a ++ ends P h (l ++ k)) b) := by + rw [Cell.test, ← batch_mul_left] + apply batch_congr + intro a b ht + have h' := hf (a ++ ends P h l) (modes (c.2 ^ P) (h c.1)) (ends P h k) [] [] b + simp only [weight_append, ht.wa, weight_modes, show weight ([] : List (Site F t)) = 0 from rfl, + mul_zero, add_zero, List.nil_append] at h' + simpa only [ends, List.flatMap_cons, List.flatMap_append, List.append_assoc] using h' + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Merging two insertion tables at a collision -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion +variable {F T X E : Type} [Field F] {r t : ℕ} + +open scoped Classical in +/-- Indexes the index by the coordinates of `Level r v.a × Level t v.b`. -/ +abbrev Station.Index (v : Station F r t T X) := Level r v.a × Level t v.b + +open scoped Classical in +/-- Evaluates `∑ a, ∑ b, u.table x a b * f (modes (u.pos ^ P) a.val ++ l) (modes u.pos b.val ++ +m)` at the input `l m`. -/ +def frontOne (P : ℕ) (x : X) (u : Station F r t T X) (f : Test F r t) : Test F r t := + fun l m => ∑ a, ∑ b, u.table x a b * f (modes (u.pos ^ P) a.val ++ l) (modes u.pos b.val ++ m) + +open scoped Classical in +theorem batch_front (P : ℕ) (x : X) (us : List (Station F r t T X)) (u : Station F r t T X) + (f : Test F r t) : batch P x (u::us) f = batch P x us (frontOne P x u f) := by + unfold frontOne + simp only [batch, batch_sum, batch_mul_left] + +open scoped Classical in +/-- The quantity computed by `u.table x i.1.1 i.1.2 * v.table x i.2.1 i.2.2`. -/ +def jointWeight (u v : Station F r t T X) (x : X) (i : u.Index × v.Index) := + u.table x i.1.1 i.1.2 * v.table x i.2.1 i.2.2 + +open scoped Classical in +/-- The front two of type `Test F r t` for the given inputs. -/ +def frontTwo (P : ℕ) (x : X) (u v : Station F r t T X) (f : Test F r t) : Test F r t := + fun l m => ∑ i : u.Index × v.Index, jointWeight u v x i * + f (modes (u.pos ^ P) i.1.1.val ++ modes (v.pos ^ P) i.2.1.val ++ l) + (modes u.pos i.1.2.val ++ modes v.pos i.2.2.val ++ m) + +open scoped Classical in +theorem batch_pair (P : ℕ) (x : X) (us : List (Station F r t T X)) (u v : Station F r t T X) + (f : Test F r t) : + batch P x (u::v::us) f = batch P x us (frontTwo P x u v f) := by + unfold frontTwo + simp only [batch, Fintype.sum_prod_type, batch_sum, batch_mul_left, mul_sum, + jointWeight, mul_assoc, List.append_assoc] + +open scoped Classical in +/-- Indexes the merge by the coordinates of `u.pos a := a b := b label := label table x y z := ∑ +i : u.Index × v.Index, jointWeight u v x i *`. -/ +def merge (u v : Station F r t T X) (label : T) (a b : ℕ) : Station F r t T X where + pos := u.pos + a := a + b := b + label := label + table x y z := ∑ i : u.Index × v.Index, jointWeight u v x i * + fusion F i.1.1.val.val i.2.1.val.val y.val.val * + fusion F i.1.2.val.val i.2.2.val.val z.val.val + +open scoped Classical in +/-- Computes the merge at by the application `merge u v label (fusedEnergy u.a v.a q.1).toNat +(fusedEnergy u.b v.b q.2).toNat`. -/ +def mergeAt (u v : Station F r t T X) (label : T) (q : ℤ × ℤ) : Station F r t T X := + merge u v label (fusedEnergy u.a v.a q.1).toNat (fusedEnergy u.b v.b q.2).toNat + +open scoped Classical in +/-- Selects the elements of `(pairs P a b j)` satisfying `(fun q => 0 ≤ fusedEnergy u.a v.a q.1 +∧ 0 ≤ fusedEnergy u.b v.b q.2)`. -/ +def merges (P : ℕ) (u v : Station F r t T X) (a b : ℕ) (j : ℤ) := + (pairs P a b j).filter (fun q => 0 ≤ fusedEnergy u.a v.a q.1 ∧ 0 ≤ fusedEnergy u.b v.b q.2) + +open scoped Classical in +/-- The quantity computed by `P * u.a + u.b`. -/ +def energyOf (P : ℕ) (u : Station F r t T X) := P * u.a + u.b + +open scoped Classical in +theorem energy_merge (P : ℕ) (u v : Station F r t T X) (l : T) {a b j q} + (h : q ∈ merges P u v a b j) : + (energyOf P (mergeAt u v l q) : ℤ) = energyOf P u + energyOf P v + 2 * j := by + obtain ⟨h, h₁, h₂⟩ := mem_filter.mp h + unfold energyOf mergeAt merge + simp only [Nat.cast_add, Nat.cast_mul, Int.toNat_of_nonneg h₁, Int.toNat_of_nonneg h₂] + exact_mod_cast insertion_energy P u.a u.b v.a v.b a b j q h + +open scoped Classical in +private theorem through {I A B : Type} [Fintype I] [Fintype A] [Fintype B] + (w : I → F) (u : I → A → F) (v : I → B → F) (f : A → F) (g : B → F) : + (∑ i, w i * ((∑ a, u i a * f a) * (∑ b, v i b * g b))) = + ∑ a, ∑ b, (∑ i, w i * u i a * v i b) * (f a * g b) := by + simp only [Finset.sum_mul_sum] + simp only [mul_sum, sum_mul] + rw [sum_comm] + refine sum_congr rfl fun a _ => ?_ + rw [sum_comm] + exact sum_congr rfl fun b _ => sum_congr rfl fun i _ => by ring + +open scoped Classical in +private theorem merged (P : ℕ) (x : X) (u v : Station F r t T X) (k : T) + (l : List (Site F r)) (m : List (Site F t)) (q : ℤ × ℤ) : + (∑ i : u.Index × v.Index, jointWeight u v x i * + (sew r (fusedEnergy u.a v.a q.1) (fun y => fusion F i.1.1.val.val i.2.1.val.val y.val) + (fun y => wick fieldKernel (modes (u.pos ^ P) y ++ l)) * + sew t (fusedEnergy u.b v.b q.2) (fun y => fusion F i.1.2.val.val i.2.2.val.val y.val) + (fun y => wick fieldKernel (modes u.pos y ++ m)))) = + if 0 ≤ fusedEnergy u.a v.a q.1 ∧ 0 ≤ fusedEnergy u.b v.b q.2 + then frontOne P x (mergeAt u v k q) forms l m else 0 := by + by_cases ha : 0 ≤ fusedEnergy u.a v.a q.1 + · by_cases hb : 0 ≤ fusedEnergy u.b v.b q.2 + · simp only [ite_eq_left (And.intro ha hb), sew, ite_eq_right ha.not_gt, ite_eq_right hb.not_gt] + exact through _ _ _ _ _ + · simp [hb, lt_of_not_ge hb, sew] + · simp [ha, lt_of_not_ge ha, sew] + +open scoped Classical in +private theorem fuse_front (p l : ℕ) [ExpChar F p] (x : X) (u v : Station F r t T X) (k : T) + (A B : Finset F) (hu : u.pos ^ (p ^ l) ∈ A) (hu' : u.pos ∈ B) + (hv : v.pos ^ (p ^ l) ∉ A) (hv' : v.pos ∉ B) + (y : List (Site F r)) (z : List (Site F t)) + (hy : ∀ i ∈ y, i.1 ∈ A.erase (u.pos ^ (p ^ l))) (hz : ∀ i ∈ z, i.1 ∈ B.erase u.pos) + (j : ℤ) : + let P := p ^ l + frontTwo P x u v (coefficient P A B u.pos j) y z = + ∑ q ∈ merges P u v ((u.a + v.a + weight y) / 2) ((u.b + v.b + weight z) / 2) j, + frontOne P x (mergeAt u v k q) forms y z := by + intro P + let a : A := ⟨u.pos ^ P, hu⟩ + let b : B := ⟨u.pos, hu'⟩ + have hy' := fun i hi => (mem_erase.mp (hy i hi)).2 + have hz' := fun i hi => (mem_erase.mp (hz i hi)).2 + have ev (i : u.Index × v.Index) := + insertion_step p l u.pos hu hu' i.1.1.val i.2.1.val i.1.2.val i.2.2.val _ _ + (fixed_avoids a y hy' (fun i hi => (mem_erase.mp (hy i hi)).1)) + (fixed_avoids b z hz' (fun i hi => (mem_erase.mp (hz i hi)).1)) j + let I := pairs P ((u.a + v.a + weight y) / 2) ((u.b + v.b + weight z) / 2) j + let term (i : u.Index × v.Index) (q : ℤ × ℤ) := + sew r (fusedEnergy u.a v.a q.1) (fun h => fusion F i.1.1.val.val i.2.1.val.val h.val) + (fun h => wick fieldKernel (modes (u.pos ^ P) h ++ y)) * + sew t (fusedEnergy u.b v.b q.2) (fun h => fusion F i.1.2.val.val i.2.2.val.val h.val) + (fun h => wick fieldKernel (modes u.pos h ++ z)) + have eq (i : u.Index × v.Index) : + coefficient P A B u.pos j + (modes (u.pos ^ P) i.1.1.val ++ modes (v.pos ^ P) i.2.1.val ++ y) + (modes u.pos i.1.2.val ++ modes v.pos i.2.2.val ++ z) = ∑ q ∈ I, term i q := by + unfold coefficient + rw [triple_tokens a _ hv _ _ _ hy', triple_tokens b _ hv' _ _ _ hz'] + have h := ev i + dsimp only at h + simp only [weight_triple, weight_fixed, fusedAt, stationary, + i.1.1.property, i.2.1.property, i.1.2.property, i.2.2.property, + read_fixed a y hy', read_fixed b z hz'] at h + exact h + unfold frontTwo + simp only [eq, mul_sum] + rw [sum_comm, merges, sum_filter] + exact sum_congr rfl fun q _ => merged P x u v k y z q + +open scoped Classical in +/-- Uses `⟨c.ports, v :: c.stations⟩` as the representation. -/ +def Cell.insert (c : Cell F r t T E X) (v : Station F r t T X) : Cell F r t T E X := + ⟨c.ports, v :: c.stations⟩ + +open scoped Classical in +/-- The quantity computed by `sumA c.stations + portWeight d c.ports`. -/ +def Cell.bigA (c : Cell F r t T E X) (d : E → ℕ) := sumA c.stations + portWeight d c.ports + +open scoped Classical in +/-- The data for the fixed construction, including `ports`, `stations`. -/ +structure Cell.Fixed (P : ℕ) (c : Cell F r t T E X) (A B : Finset F) : Prop where + ports : ∀ v ∈ c.ports, v.2 ^ P ∈ A + stations : ∀ u ∈ c.stations, u.pos ^ P ∈ A ∧ u.pos ∈ B + +open scoped Classical in +theorem Cell.test_congr (P : ℕ) (x : X) (c : Cell F r t T E X) (d : E → ℕ) (h : E → Wedge r) + (he : ∀ i ∈ c.ports, energy (h i.1).val = d i.1) {A B : Finset F} (hc : c.Fixed P A B) + {f g : Test F r t} (hf : ∀ a b, (∀ i ∈ a, i.1 ∈ A) → (∀ i ∈ b, i.1 ∈ B) → + weight a = c.bigA d → weight b = sumB c.stations → f a b = g a b) : + c.test P x h f = c.test P x h g := by + apply batch_congr + intro a b hw + refine hf _ _ ?_ ?_ ?_ hw.wb + · intro i hi + rcases List.mem_append.mp hi with hi|hi + · obtain ⟨s, hs, h⟩ := hw.left i hi + rw [h] + exact (hc.stations s hs).1 + · obtain ⟨s, hs, h⟩ := mem_ends _ _ _ _ hi + rw [h] + exact hc.ports s hs + · intro i hi + obtain ⟨s, hs, h⟩ := hw.right i hi + rw [h] + exact (hc.stations s hs).2 + · rw [weight_append, weight_ends P d _ _ he, hw.wa]; rfl + +open scoped Classical in +theorem Cell.test_sum {I : Type*} (P : ℕ) (x : X) (c : Cell F r t T E X) (h : E → Wedge r) + (s : Finset I) (f : I → Test F r t) : + c.test P x h (fun a b => ∑ i ∈ s, f i a b) = ∑ i ∈ s, c.test P x h (f i) := + batch_sum _ _ _ _ _ + +open scoped Classical in +theorem Cell.test_insert (P : ℕ) (x : X) (c : Cell F r t T E X) (h : E → Wedge r) + (u : Station F r t T X) (f : Test F r t) : + (c.insert u).test P x h f = c.test P x h (frontOne P x u f) := by + simp only [Cell.test, Cell.insert, batch_front] + unfold frontOne + simp only [List.append_assoc] + +open scoped Classical in +private theorem Cell.test_pair (P : ℕ) (x : X) (c : Cell F r t T E X) (h : E → Wedge r) + (u v : Station F r t T X) (f : Test F r t) : + ((c.insert v).insert u).test P x h f = c.test P x h (frontTwo P x u v f) := by + simp only [Cell.test, Cell.insert, batch_pair] + unfold frontTwo + simp only [List.append_assoc] + +open scoped Classical in +/-- Evaluation at a collision is a finite sum of cells, with unchanged +ordinary parameters and no change to any seam. -/ +theorem Cell.merge (p l : ℕ) [ExpChar F p] (c : Cell F r t T E X) (d : E → ℕ) + (u v : Station F r t T X) (k : T) (A B : Finset F) (hu : u.pos ^ (p ^ l) ∈ A) + (hu' : u.pos ∈ B) (hv : v.pos ^ (p ^ l) ∉ A) (hv' : v.pos ∉ B) + (hc : c.Fixed (p ^ l) (A.erase (u.pos ^ (p ^ l))) (B.erase u.pos)) + (j : ℤ) (x : X) (h : E → Wedge r) (he : ∀ i ∈ c.ports, energy (h i.1).val = d i.1) : + let P := p ^ l + let C := (c.insert v).insert u + C.test P x h (coefficient P A B u.pos j) = + ∑ q ∈ merges P u v (C.orderA d) C.orderB j, (c.insert (mergeAt u v k q)).eval P x h := by + intro P C + have hcell (a : Station F r t T X) : + (c.insert a).eval P x h = c.test P x h (frontOne P x a forms) := + Cell.test_insert _ _ _ _ _ _ + rw [Cell.test_pair] + simp only [hcell, ← Cell.test_sum] + refine c.test_congr P x d h he hc (fun y z hy hz ey ez => ?_) + rw [fuse_front p l x u v k A B hu hu' hv hv' y z hy hz j, ey, ez] + simp only [P, C, orderA, orderB, bigA, Cell.insert, sumA, sumB, List.map_cons, List.sum_cons, + Nat.add_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- +# The ordinary wire left by crossing a seam + +Group the lowering operator by output energy. Each term replaces the +shared seam and creates an ordinary wire indexed by a private basis +state. The latter is summed inside the contraction. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion +variable {F T X : Type} [Field F] {r t : ℕ} + +open scoped Classical in +/-- The value specified by `(Wedge r →₀ F) →ₗ[F] (Wedge r →₀ F)`. -/ +abbrev Lower (F : Type) [Field F] (r : ℕ) := (Wedge r →₀ F) →ₗ[F] (Wedge r →₀ F) + +open scoped Classical in +private theorem byEnergy (m : ℕ) (a : Wedge r →₀ F) (ha : ∀ i ∈ a.support, energy i.val ≤ m) + (f : Wedge r → F) : + a.sum (fun i v => v * f i) = + ∑ n : Fin (m + 1), ∑ v : Level r n, a v.val * f v.val := by + let g (i : Σ n : Fin (m + 1), Level r n) := i.2.val + have hi : Function.Injective g := by + rintro ⟨n, v⟩ ⟨n', v'⟩ h + change v.val = v'.val at h + have e : n = n' := Fin.ext (v.2.symm.trans (h ▸ v'.2)) + subst n' + rw [Subtype.ext h] + have sub : a.support ⊆ univ.image g := by + intro i h + exact mem_image_of_mem g (mem_univ ⟨⟨_, Nat.lt_succ_of_le (ha i h)⟩, i, rfl⟩) + rw [Finsupp.sum, sum_subset sub (fun i _ h => by rw [Finsupp.notMem_support_iff.mp h, zero_mul]), + sum_image hi.injOn, Fintype.sum_sigma] + +open scoped Classical in +private theorem move_expand {C : Finset F} (c : C) (V : Finset F) (S : Lower F r) + (f : ℕ → V → F) {m : ℕ} (x : Level r m) (ys : List (C × Mode r)) (b : Wedge r) + (he : ∀ i ∈ (S (Finsupp.single x.val 1)).support, energy i.val ≤ m) : + transported c V S f x.val ys b = + ∑ v : Fin (m + 1) × V, f v.1 v.2 * ∑ a : Level r v.1, + S (Finsupp.single x.val 1) a.val * moving c b a.val ys v.2.val := by + rw [transported, byEnergy _ _ he, Fintype.sum_prod_type] + refine sum_congr rfl fun n _ => ?_ + simp only [mul_sum] + rw [sum_comm] + refine sum_congr rfl fun y _ => sum_congr rfl fun k _ => ?_ + rw [k.property, mul_left_comm] + +open scoped Classical in +private theorem read_mover (A : Finset F) (z y : F) (hz : z ∉ A) (u : Wedge r) + (l : List (Site F r)) (hl : ∀ i ∈ l, i.1 ∈ A) : + ((modes z u ++ l).map (token A)).map (atPoint y) = modes y u ++ l := by + simp only [List.map_append, read_tokens A l y (fun i h => .inr (hl i h))] + simp [modes, token, atPoint, hz, List.map_map, Function.comp_def] + +open scoped Classical in +private theorem moving_at {A : Finset F} (c : A) (u v : Wedge r) + (l : List (Site F r)) (hl : ∀ i ∈ l, i.1 ∈ A) (z : F) : + moving c u v (l.map (fixed c)) z = wick fieldKernel (modes c.val u ++ modes z v ++ l) := by + have eq (ys : List (A × Mode r)) : + (triple c u.val v.val ys).map (atPoint z) = modes c.val u ++ modes z v ++ spectators ys := by + simp [triple, modes, atPoint, spectators, List.map_map, Function.comp_def] + rw [moving, eq, read_fixed c l hl] + +open scoped Classical in +/-- Only collisions with a nonnegative seam level contribute. -/ +def crossings (P d e m : ℕ) (j : ℤ) := + (pairs P d 0 j).filter (fun q => 0 ≤ fusedEnergy e m q.1) + +open scoped Classical in +/-- Indexes the hop by the coordinates of `↥(crossings P d e m j) × U × Fin (m + 1) × V`. -/ +abbrev Hop (P d e m : ℕ) (j : ℤ) (U V : Finset F) := + ↥(crossings P d e m j) × U × Fin (m + 1) × V + +open scoped Classical in +/-- The value specified by `(fusedEnergy e m i.1.val.1).toNat`. -/ +def Hop.height {P d e m : ℕ} {j : ℤ} {U V : Finset F} (i : Hop P d e m j U V) := + (fusedEnergy e m i.1.val.1).toNat + +omit [Field F] in +open scoped Classical in +theorem Hop.drop {P d e m n H : ℕ} {j : ℤ} {U V : Finset F} + (i : Hop P d e m j U V) (hj : (P * m + n + 2 * P * H : ℕ) ≤ -j) : + P * i.height + (P * m + n + 2 * P * H) ≤ P * e := by + obtain ⟨h, h'⟩ := mem_filter.mp i.1.property + have e := seam_drop P e m n H d j _ h hj + rw [← Int.toNat_of_nonneg h'] at e + exact_mod_cast e + +open scoped Classical in +private theorem distribute {I A B : Type} [Fintype I] [Fintype A] [Fintype B] + (u : I → F) (v : I → B → F) (g : B → F) (f k : A → F) : + (∑ i, u i * ∑ b, g b * v i b) * (∑ a, f a * k a) = + ∑ a, ∑ b, f a * g b * ∑ i, u i * k a * v i b := by + rw [mul_sum] + refine sum_congr rfl fun a _ => ?_ + simp only [mul_sum, sum_mul] + rw [sum_comm] + exact sum_congr rfl fun b _ => sum_congr rfl fun i _ => by ring + +open scoped Classical in +private theorem to_hops (P d e m : ℕ) (j : ℤ) (U V : Finset F) + (f : ℕ → ℕ → V → F) (g : ℤ → U → F) (u : Wedge r → F) + (k : U → F) (h : Wedge r → Fin (m + 1) × V → F) : + (∑ q ∈ pairs P d 0 j, + let n := fusedEnergy e m q.1 + sew r n u (fun b => ∑ i, f n.toNat i.1 i.2 * h b i) * ∑ y, g q.2 y * k y) = + ∑ i : Hop P d e m j U V, g i.1.val.2 i.2.1 * f i.height i.2.2.1 i.2.2.2 * + ∑ b : Level r i.height, u b.val * k i.2.1 * h b.val i.2.2 := by + let T (q : ℤ × ℤ) := + let n := fusedEnergy e m q.1 + sew r n u (fun b => ∑ i, f n.toNat i.1 i.2 * h b i) * ∑ y, g q.2 y * k y + change ∑ q ∈ pairs P d 0 j, T q = _ + have zero (q) (hq : q ∈ pairs P d 0 j) (hn : q ∉ crossings P d e m j) : T q = 0 := by + have hn' : fusedEnergy e m q.1 < 0 := lt_of_not_ge fun he => hn (mem_filter.mpr ⟨hq, he⟩) + simp only [T, sew, ite_eq_left hn', zero_mul] + rw [← sum_subset (filter_subset _ _) zero, ← sum_attach, Fintype.sum_prod_type] + refine sum_congr rfl fun q _ => ?_ + simp only [T, sew, ite_eq_right (mem_filter.mp q.property).2.not_gt] + rw [Fintype.sum_prod_type] + exact distribute _ _ _ _ _ + +open scoped Classical in +/-- Crossing on basis states after resolving the lowered mover energy. -/ +theorem hop_basis (p l : ℕ) [ExpChar F p] (A B C U V : Finset F) + (z z' s : F) (hz : z ^ (p ^ l) ∈ A) (hz' : z' ^ (p ^ l) ∈ C) (hb : z ∉ B) + (hs : s ^ (p ^ l) ∉ A) (hs' : s ∉ B) + (hU : Disjoint U B) (hV : Disjoint V C) + (e m n H u v w : ℕ) (hB : B.card * ((n + v) / 2) < U.card) + (hC : C.card * ((e + m + w) / 2) < V.card) (j : ℤ) (hj : (p ^ l * m + n + 2 * p ^ l * H : ℕ) + ≤ -j) : + let P := p ^ l + let I := Hop P ((e + m + u) / 2) e m j U V + let S := lowering F r + ∃ k : I → F, + ∀ (x : Level r m) (y : Level t n) + (a : List (Site F r)) (b : List (Site F t)) (c : List (Site F r)), + (∀ i ∈ a, i.1 ∈ A.erase (z ^ P)) → (∀ i ∈ b, i.1 ∈ B) → + (∀ i ∈ c, i.1 ∈ C.erase (z' ^ P)) → weight a = u → weight b = v → weight c = w → + (∑ f : Level r e, coefficient P A B z j + (modes (z ^ P) f.val ++ modes (s ^ P) x.val ++ a) (modes s y.val ++ b) * + wick fieldKernel (modes (z' ^ P) f.val ++ c)) = + ∑ i : I, k i * ∑ f : Level r i.height, + forms (modes (z ^ P) f.val ++ a) (modes i.2.1.val y.val ++ b) * + ∑ x' : Level r i.2.2.1, S (Finsupp.single x.val 1) x'.val * + wick fieldKernel (modes (z' ^ P) f.val ++ modes i.2.2.2.val x'.val ++ c) := by + intro P I S + let o : A := ⟨z ^ P, hz⟩ + let o' : C := ⟨z' ^ P, hz'⟩ + obtain ⟨f, g, hS, h⟩ := seam_step (r := r) (t := t) p l z hz hb o' U V hU hV e m n H u v w hB hC + refine ⟨fun i => g i.1.val.2 i.2.1 * f i.height i.2.2.1 i.2.2.2, ?_⟩ + intro x y a b c ha hb hc ea eb ec + have ha' := fun i hi => (mem_erase.mp (ha i hi)).2 + have hc' := fun i hi => (mem_erase.mp (hc i hi)).2 + let a' := a.map (fixed o) + let b' := (modes s y.val ++ b).map (token B) + let c' := c.map (fixed o') + have h' := h j hj x a' b' c' + (fixed_avoids o a ha' (fun i hi => (mem_erase.mp (ha i hi)).1)) + (fixed_avoids o' c hc' (fun i hi => (mem_erase.mp (hc i hi)).1)) + (by simpa [a'] using ea) (by simp only [b', weight_token, weight_append, weight_modes, + y.property, eb]) + (by simpa [c'] using ec) + have hx : ∀ i ∈ (S (Finsupp.single x.val 1)).support, energy i.val ≤ m := + fun i hi => (hS x.val i hi).1.trans_eq x.property + have htr (n : ℕ) : transported o' V S (f n) x.val c' = fun b => + ∑ v : Fin (m + 1) × V, f n v.1 v.2 * ∑ a : Level r v.1, + S (Finsupp.single x.val 1) a.val * moving o' b a.val c' v.2.val := + funext fun b => move_expand _ _ _ _ _ _ _ hx + unfold S at htr + simp only [sew_nat, htr] at h' + rw [to_hops] at h' + simp only [a', b', c', stationary, read_fixed _ _ ha', read_fixed _ _ hc', + read_mover B s _ hs' y.val b hb, moving_at _ _ _ _ hc'] at h' + unfold coefficient + have et (i : Wedge r) : + (modes (z ^ P) i ++ modes (s ^ P) x.val ++ a).map (token A) = + triple o i.val x.val.val (a.map (fixed o)) := triple_tokens o _ hs _ _ _ ha' + simp only [et] + exact h' + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Lifting a seam crossing from modes to insertion tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion +variable {F T X E : Type} [Field F] {r t : ℕ} + +open scoped Classical in +/-- Evaluates `f (modes z a ++ l) m` at the input `l m`. -/ +def lead (z : F) (a : Wedge r) (f : Test F r t) : Test F r t := + fun l m => f (modes z a ++ l) m + +open scoped Classical in +/-- The newly created ordinary wire carries a basis state of the +mover's private leg. -/ +def residue (u : Station F r t T X) (label : T) (z : F) : Station F r t T (X × Level t u.b) where + pos := z + a := 0 + b := u.b + label := label + table x _ y := if x.2 = y then 1 else 0 + +open scoped Classical in +/-- Preserve the mover's ordinary wires and add the new private wire. +Project the transformed state to its selected energy. -/ +def transfer (u : Station F r t T X) (label : T) (z : F) (S : Lower F r) (n : ℕ) : + Station F r t T (X × Level t u.b) where + pos := z + a := n + b := 0 + label := label + table x i _ := ∑ a, u.table x.1 a x.2 * S (Finsupp.single a.val 1) i.val + +open scoped Classical in +private theorem front_residue (P : ℕ) (u : Station F r t T X) (k : T) (z : F) + (x : X) (y : Level t u.b) (f : Test F r t) (a b) : + frontOne P (x, y) (residue u k z) f a b = f a (modes z y.val ++ b) := by + unfold frontOne residue + rw [Fintype.sum_unique] + simp only [ite_mul, one_mul, zero_mul, sum_ite_eq, mem_univ, ite_true] + rfl + +open scoped Classical in +private theorem front_transfer (P : ℕ) (u : Station F r t T X) (k : T) (z : F) + (S : Lower F r) (n : ℕ) (x : X) (y : Level t u.b) (f : Test F r t) (a b) : + frontOne P (x, y) (transfer u k z S n) f a b = + ∑ i : Level r n, (∑ j, u.table x j y * S (Finsupp.single j.val 1) i.val) * + f (modes (z ^ P) i.val ++ a) b := by + unfold frontOne transfer + refine sum_congr rfl fun i _ => ?_ + rw [Fintype.sum_unique] + rfl + +open scoped Classical in +private theorem lift_basis {I A Y Z : Type} {D G : I → Type} [Fintype I] [Fintype A] + [Fintype Y] [Fintype Z] [∀ i, Fintype (D i)] [∀ i, Fintype (G i)] + (k : I → F) (K : A → Y → Z → F) (L : A → F) (N : ∀ i, D i → Z → F) + (M : ∀ i, Y → G i → F) (O : ∀ i, D i → G i → F) (W : Y → Z → F) (H : F) + (h : ∀ y z, (∑ a, K a y z * L a) = + ∑ i, k i * ∑ d, N i d z * ∑ g, M i y g * O i d g) : + (∑ a, (∑ y, ∑ z, W y z * K a y z) * (L a * H)) = + ∑ i, k i * ∑ z, ∑ d, N i d z * ∑ g, (∑ y, W y z * M i y g) * (O i d g * H) := by + have e : (∑ a, (∑ y, ∑ z, W y z * K a y z) * (L a * H)) = + ∑ y, ∑ z, (W y z * H) * (∑ a, K a y z * L a) := by + simp only [sum_mul, mul_sum] + rw [sum_comm] + refine sum_congr rfl fun y _ => ?_ + rw [sum_comm] + exact sum_congr rfl fun z _ => sum_congr rfl fun a _ => by ring + rw [e, sum_comm] + simp only [h, sum_mul, mul_sum] + conv_rhs => rw [sum_comm] + refine sum_congr rfl fun z _ => ?_ + rw [sum_comm] + refine sum_congr rfl fun i _ => ?_ + rw [sum_comm] + refine sum_congr rfl fun d _ => ?_ + rw [sum_comm] + exact sum_congr rfl fun g _ => sum_congr rfl fun y _ => by ring + +open scoped Classical in +/-- Local data for a Laurent coefficient crossing a specified seam. -/ +structure Passage (P : ℕ) (u : Station F r t T X) where + /-- The `Passage` field of type `F`. -/ + z : F + /-- The `Passage` field of type `F`. -/ + y : F + /-- The `Passage` component of type `Finset F`. -/ + A : Finset F + /-- The `Passage` component of type `Finset F`. -/ + B : Finset F + /-- The `Passage` component of type `Finset F`. -/ + C : Finset F + /-- The `Passage` component of type `Finset F`. -/ + U : Finset F + /-- The `Passage` component of type `Finset F`. -/ + V : Finset F + /-- The root of type `V → F`. -/ + root : V → F + hroot : ∀ i, (root i) ^ P = i.val + hz : z ^ P ∈ A + hy : y ^ P ∈ C + hb : z ∉ B + hu : u.pos ^ P ∉ A + hu' : u.pos ∉ B + hU : Disjoint U B + hV : Disjoint V C + /-- The `Passage` field of type `ℕ`. -/ + e : ℕ + /-- The left component. -/ + a : ℕ + /-- The right component. -/ + b : ℕ + /-- The remaining component. -/ + c : ℕ + sizeU : B.card * ((u.b + b) / 2) < U.card + sizeV : C.card * ((e + u.a + c) / 2) < V.card + /-- The `Passage` field of type `ℕ`. -/ + H : ℕ + /-- The `Passage` field of type `ℤ`. -/ + j : ℤ + low : (P * u.a + u.b + 2 * P * H : ℕ) ≤ -j + +namespace Passage +variable {P : ℕ} {u : Station F r t T X} (s : Passage P u) + +open scoped Classical in +/-- The quantity computed by `Hop P ((s.e + u.a + s.a) / 2) s.e u.a s.j s.U s.V`. -/ +abbrev Branch := Hop P ((s.e + u.a + s.a) / 2) s.e u.a s.j s.U s.V + +open scoped Classical in +/-- Computes the leaves by the application `residue u k i.2.1.val`. -/ +def leaves (k : T) (i : s.Branch) := residue u k i.2.1.val + +open scoped Classical in +/-- Computes the arrives by the application `transfer u k (s.root i.2.2.2) S i.2.2.1`. -/ +def arrives (k : T) (S : Lower F r) (i : s.Branch) := + transfer u k (s.root i.2.2.2) S i.2.2.1 + +open scoped Classical in +/-- Computes the coeff by the application `coefficient P s.A s.B s.z s.j`. -/ +def coeff : Test F r t := coefficient P s.A s.B s.z s.j + +open scoped Classical in +theorem energy_step (k k' : T) (S : Lower F r) (i : s.Branch) : + energyOf P (s.leaves k i) + energyOf P (s.arrives k' S i) ≤ energyOf P u ∧ + P * i.height + (energyOf P u + 2 * P * s.H) ≤ P * s.e := by + refine ⟨?_, Hop.drop i s.low⟩ + have h : i.2.2.1.val ≤ u.a := Nat.le_of_lt_succ i.2.2.1.isLt + have := Nat.mul_le_mul_left P h + simp only [energyOf, leaves, residue, arrives, transfer, mul_zero, zero_add, add_zero] + omega + +open scoped Classical in +/-- The coefficients use only the local energies and positions. -/ +def weights (p l : ℕ) [ExpChar F p] (hP : P = p ^ l) : s.Branch → F := by + subst P + exact (hop_basis (r := r) (t := t) p l s.A s.B s.C s.U s.V s.z s.y u.pos + s.hz s.hy s.hb s.hu s.hu' s.hU s.hV s.e u.a u.b s.H s.a s.b s.c s.sizeU s.sizeV s.j + s.low).choose + +open scoped Classical in +theorem advance (p l : ℕ) [ExpChar F p] (hP : P = p ^ l) (k k' : T) : + let S := lowering F r + let f := s.weights p l hP + ∀ x : X, ∀ (a : List (Site F r)) (b : List (Site F t)) + (c : List (Site F r)) (d : List (Site F t)), + (∀ i ∈ a, i.1 ∈ s.A.erase (s.z ^ P)) → (∀ i ∈ b, i.1 ∈ s.B) → + (∀ i ∈ c, i.1 ∈ s.C.erase (s.y ^ P)) → weight a = s.a → weight b = s.b → weight c = s.c → + (∑ h : Level r s.e, + frontOne P x u (lead (s.z ^ P) h.val s.coeff) a b * lead (s.y ^ P) h.val forms c d) = + ∑ i : s.Branch, f i * ∑ y : Level t u.b, ∑ h : Level r i.height, + frontOne P (x, y) (s.leaves k i) (lead (s.z ^ P) h.val forms) a b * + frontOne P (x, y) (s.arrives k' S i) (lead (s.y ^ P) h.val forms) c d := by + subst P + intro S f + have h := (hop_basis (r := r) (t := t) p l s.A s.B s.C s.U s.V s.z s.y u.pos + s.hz s.hy s.hb s.hu s.hu' s.hU s.hV s.e u.a u.b s.H s.a s.b s.c s.sizeU s.sizeV s.j + s.low).choose_spec + intro x a b c d ha hb hc ea eb ec + have eqn := lift_basis f + (fun (v : Level r s.e) (x : Level r u.a) (y : Level t u.b) => + s.coeff (modes (s.z ^ (p ^ l)) v.val ++ modes (u.pos ^ (p ^ l)) x.val + ++ a) (modes u.pos y.val ++ b)) + (fun v => wick fieldKernel (modes (s.y ^ (p ^ l)) v.val ++ c)) + (fun i (v : Level r i.height) y => + forms (modes (s.z ^ (p ^ l)) v.val ++ a) (modes i.2.1.val y.val ++ b)) + (fun i x (y : Level r i.2.2.1) => S (Finsupp.single x.val 1) y.val) + (fun i v y => wick fieldKernel (modes (s.y ^ (p ^ l)) v.val ++ modes i.2.2.2.val y.val ++ c)) + (u.table x) (wick fieldKernel d) (fun x y => h x y a b c ha hb hc ea eb ec) + simp only [leaves, arrives, front_residue, front_transfer, s.hroot, lead] + simpa only [frontOne, lead, forms, List.append_assoc] using eqn + +end Passage +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Pull.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Pull.lean new file mode 100644 index 0000000000..9eb5514720 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Pull.lean @@ -0,0 +1,659 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Interpolation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import Mathlib.Data.Fin.Tuple.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Install + +/-! +# Sewn pairs of sphere forms + +An ordinary assignment is a parameter of the insertion tables. Only +the shared sphere states are summed here. The label can record which +ordinary bits a station reads and its role in the movement procedure. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset + +variable {F T X E V : Type} [Field F] {r t : ℕ} + +open scoped Classical in +/-- The data for the station construction, including `pos`, `a`, `b`, `label`, `table`. -/ +structure Station (F : Type) (r t : ℕ) (T X : Type) where + /-- The `Station` field of type `F`. -/ + pos : F + /-- The left component. -/ + a : ℕ + /-- The right component. -/ + b : ℕ + /-- The label at each coordinate of type `T`. -/ + label : T + /-- The local table at each indexed position carried by `Station`, with type `X → Level r a → + Level t b → F`. -/ + table : X → Level r a → Level t b → F + +open scoped Classical in +/-- The data for the cell construction, including `ports`, `stations`. -/ +structure Cell (F : Type) (r t : ℕ) (T E X : Type) where + /-- The `Cell` component of type `List (E × F)`. -/ + ports : List (E × F) + /-- The `Cell` component of type `List (Station F r t T X)`. -/ + stations : List (Station F r t T X) + +open scoped Classical in +/-- Transforms the indexed data by `w.val.map (z, ·)`. -/ +def modes (z : F) (w : Wedge r) : List (Site F r) := w.val.map (z, ·) + +open scoped Classical in +/-- The quantity computed by `l.flatMap (fun j => modes (j.2 ^ P) (h j.1))`. -/ +def ends (P : ℕ) (h : E → Wedge r) (l : List (E × F)) : List (Site F r) := + l.flatMap (fun j => modes (j.2 ^ P) (h j.1)) + +open scoped Classical in +/-- The indexing data represented by `List (Site F r) → List (Site F t) → F`. -/ +abbrev Test (F : Type) (r t : ℕ) := List (Site F r) → List (Site F t) → F + +open scoped Classical in +/-- Evaluates `wick fieldKernel a * wick fieldKernel b` at the input `a b`. -/ +def forms : Test F r t := fun a b => wick fieldKernel a * wick fieldKernel b + +open scoped Classical in +/-- Expand all insertion tables, passing the ordered sites to a test. -/ +def batch (P : ℕ) (x : X) : List (Station F r t T X) → Test F r t → F + | [], f => f [] [] + | u :: us, f => ∑ a, ∑ b, u.table x a b * batch P x us + (fun l m => f (modes (u.pos ^ P) a.val ++ l) (modes u.pos b.val ++ m)) + +open scoped Classical in +/-- Concatenates the components in the order `batch P x c.stations fun l m => forms (l ++ ends P +h c.ports) m`. -/ +def Cell.eval (P : ℕ) (c : Cell F r t T E X) (x : X) (h : E → Wedge r) : F := + batch P x c.stations fun l m => forms (l ++ ends P h c.ports) m + +open scoped Classical in +/-- Contract every seam at a fixed energy by ordinary basis equality. -/ +def eval [Fintype E] [Fintype V] (P : ℕ) (C : V → Cell F r t T E X) + (d : E → ℕ) (x : X) : F := + ∑ a : ∀ e, Level r (d e), ∏ v, Cell.eval P (C v) x (fun e => (a e).val) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Linear operations on insertion tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset +variable {F T X E : Type} [Field F] {r t : ℕ} (P : ℕ) (x : X) +variable (u : List (Station F r t T X)) + +open scoped Classical in +theorem batch_mul_left (c : F) (f : Test F r t) : + batch P x u (fun p q => c * f p q) = c * batch P x u f := by + induction u generalizing f with + | nil => rfl + | cons a l ih => + simp only [batch, mul_sum] + refine sum_congr rfl fun j _ => sum_congr rfl fun k _ => ?_ + rw [ih, mul_left_comm] + +open scoped Classical in +theorem batch_mul_right (c : F) (f : Test F r t) : + batch P x u (fun p q => f p q * c) = batch P x u f * c := by + simpa only [mul_comm c] using batch_mul_left P x u c f + +open scoped Classical in +theorem batch_sum {I : Type*} (s : Finset I) (f : I → Test F r t) : + batch P x u (fun p q => ∑ i ∈ s, f i p q) = ∑ i ∈ s, batch P x u (f i) := by + induction u generalizing f with + | nil => rfl + | cons a l ih => + simp only [batch] + rw [sum_comm (s := s)] + refine sum_congr rfl fun j _ => ?_ + rw [sum_comm (s := s)] + refine sum_congr rfl fun k _ => ?_ + rw [ih, mul_sum] + +open scoped Classical in +@[simp] theorem batch_zero : batch P x u (fun _ _ => 0) = 0 := by + simpa only [zero_mul] using batch_mul_left P x u 0 (fun _ _ => 1) + +open scoped Classical in +/-- Transforms the indexed data by `(u.map Station.a).sum`. -/ +def sumA := (u.map Station.a).sum +open scoped Classical in +/-- Transforms the indexed data by `(u.map Station.b).sum`. -/ +def sumB := (u.map Station.b).sum + +omit [Field F] in +open scoped Classical in +@[simp] theorem weight_modes (z : F) (a : Wedge r) : weight (modes z a) = energy a.val := by + simp [weight, modes, Function.comp_def] + +omit [Field F] in +open scoped Classical in +@[simp] theorem weight_append (p q : List (Site F r)) : + weight (p ++ q) = weight p + weight q := by simp [weight, energy] + +open scoped Classical in +/-- Only these pairs of words can occur in the given batch. -/ +structure Within (p : List (Site F r)) (q : List (Site F t)) : Prop where + left : ∀ y ∈ p, ∃ s ∈ u, y.1 = s.pos ^ P + right : ∀ y ∈ q, ∃ s ∈ u, y.1 = s.pos + wa : weight p = sumA u + wb : weight q = sumB u + +open scoped Classical in +theorem batch_congr {f g : Test F r t} (h : ∀ p q, Within P u p q → f p q = g p q) : + batch P x u f = batch P x u g := by + induction u generalizing f g with + | nil => exact h [] [] ⟨by simp, by simp, rfl, rfl⟩ + | cons s u ih => + simp only [batch] + refine sum_congr rfl fun a _ => sum_congr rfl fun b _ => congrArg (s.table x a b * ·) ?_ + apply ih + intro p q hw + apply h + constructor + · intro y hy + rcases List.mem_append.mp hy with hy|hy + · obtain ⟨_, _, rfl⟩ := List.mem_map.mp hy + exact ⟨s, by simp, rfl⟩ + · obtain ⟨v, hv, he⟩ := hw.left y hy + exact ⟨v, .tail _ hv, he⟩ + · intro y hy + rcases List.mem_append.mp hy with hy|hy + · obtain ⟨_, _, rfl⟩ := List.mem_map.mp hy + exact ⟨s, by simp, rfl⟩ + · obtain ⟨v, hv, he⟩ := hw.right y hy + exact ⟨v, .tail _ hv, he⟩ + · simp only [weight_append, weight_modes, a.property, hw.wa, sumA, List.map_cons, List.sum_cons] + · simp only [weight_append, weight_modes, b.property, hw.wb, sumB, List.map_cons, List.sum_cons] + +open scoped Classical in +/-- Transforms the indexed data by `(l.map fun p => d p.1).sum`. -/ +def portWeight (d : E → ℕ) (l : List (E × F)) := (l.map fun p => d p.1).sum + +open scoped Classical in +theorem weight_ends (d : E → ℕ) (h : E → Wedge r) (l : List (E × F)) + (hh : ∀ i ∈ l, energy (h i.1).val = d i.1) : weight (ends P h l) = portWeight d l := by + induction l with + | nil => rfl + | cons i l ih => + change weight (modes (i.2 ^ P) (h i.1) ++ ends P h l) = d i.1 + portWeight d l + rw [weight_append, weight_modes, hh i (by simp), ih (fun j hj => hh j (.tail _ hj))] + +open scoped Classical in +theorem mem_ends (h : E → Wedge r) (l : List (E × F)) (y : Site F r) + (hy : y ∈ ends P h l) : ∃ j ∈ l, y.1 = j.2 ^ P := by + obtain ⟨j, hj, h⟩ := List.mem_flatMap.mp hy + obtain ⟨_, _, rfl⟩ := List.mem_map.mp h + exact ⟨j, hj, rfl⟩ + +open scoped Classical in +/-- Concatenates the components in the order `batch P x c.stations fun l m => f (l ++ ends P h +c.ports) m`. -/ +def Cell.test (c : Cell F r t T E X) (h : E → Wedge r) (f : Test F r t) : F := + batch P x c.stations fun l m => f (l ++ ends P h c.ports) m + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Ordered sums of insertion tables -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset +variable {F X T : Type} [Field F] {r t : ℕ} (P : ℕ) (x : X) + +theorem batch_append (us vs : List (Station F r t T X)) (test : Test F r t) : + batch P x (us ++ vs) test = batch P x us (fun a b => + batch P x vs (fun a' b' => test (a ++ a') (b ++ b'))) := by + induction us generalizing test with + | nil => rfl + | cons u us ih => + simp only [List.cons_append, batch, ih, List.append_assoc] + +private theorem sum_tail {n : ℕ} (Y : Fin (n + 1) → Type) [∀ i, Fintype (Y i)] + (g : (∀ i, Y i) → F) : + ∑ x, g x = ∑ y : Y 0, ∑ z : (i : Fin n) → Y i.succ, g (Fin.cons y z) := by + rw [← (Fin.consEquiv Y).sum_comp, Fintype.sum_prod_type] + rfl + +theorem batch_ofFn {n : ℕ} (s : Fin n → Station F r t T X) (test : Test F r t) : + batch P x (List.ofFn s) test = + ∑ a : (i : Fin n) → Level r (s i).a, ∑ b : (i : Fin n) → Level t (s i).b, + (∏ i, (s i).table x (a i) (b i)) * + test ((List.finRange n).flatMap fun i => modes ((s i).pos ^ P) (a i).val) + ((List.finRange n).flatMap fun i => modes (s i).pos (b i).val) := by + induction n generalizing test with + | zero => simp [batch] + | succ n ih => + rw [List.ofFn_succ, batch, sum_tail] + apply sum_congr rfl + intro a _ + simp_rw [sum_tail (fun i => Level t (s i).b)] + rw [sum_comm] + apply sum_congr rfl + intro b _ + rw [ih, mul_sum] + simp only [mul_sum, Fin.prod_univ_succ, Fin.cons_zero, Fin.cons_succ, + List.finRange_succ, List.flatMap_cons, List.flatMap_map, mul_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- +# Replacing local forms in a closed contraction + +Sum over all assignments away from the chosen seam first. The energy +of that seam may change in each summand of the local identity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +open Finset Function + +variable {V E I F : Type} [Field F] [Fintype V] [Fintype E] [Fintype I] {r : ℕ} + +open scoped Classical in +/-- The indexed operation `∑ a : ∀ e, Level r (d e), ∏ v, f v (fun e => (a e).val)`. -/ +def contractGraph (f : V → (E → Wedge r) → F) (d : E → ℕ) : F := + ∑ a : ∀ e, Level r (d e), ∏ v, f v (fun e => (a e).val) + +open scoped Classical in +theorem contractGraph_replace (f : V → (E → Wedge r) → F) (d : E → ℕ) + (v : V) (W : I → F) (g : I → (E → Wedge r) → F) + (step : ∀ h, (∀ e, energy (h e).val = d e) → f v h = ∑ i, W i * g i h) : + contractGraph f d = ∑ i, W i * contractGraph (update f v (g i)) d := by + unfold contractGraph + simp_rw [mul_sum] + rw [sum_comm] + refine sum_congr rfl fun a _ => ?_ + let h := fun e => (a e).val + change (∏ k, f k h) = ∑ i, W i * ∏ k, update f v (g i) k h + rw [← mul_prod_erase _ _ (mem_univ v), step h (fun e => (a e).property), sum_mul] + refine sum_congr rfl fun i _ => ?_ + rw [← mul_prod_erase _ _ (mem_univ v), update_self, mul_assoc] + congr 2 + exact prod_congr rfl fun k hk => by rw [update_of_ne (ne_of_mem_erase hk)] + +open scoped Classical in +private abbrev Rest (r : ℕ) (d : E → ℕ) (e : E) := + (j : {j // j ≠ e}) → Level r (d j.val) + +open scoped Classical in +private def emptyState (r : ℕ) : Wedge r := ⟨[], by simp⟩ + +open scoped Classical in +private def fill {d : E → ℕ} {e : E} (a : Rest r d e) (j : E) : Wedge r := + if hj : j = e then emptyState r else (a ⟨j, hj⟩).val + +omit [Fintype E] in +open scoped Classical in +private theorem fill_energy {d : E → ℕ} {e : E} (a : Rest r d e) (j : E) (hj : j ≠ e) : + energy (fill a j).val = d j := by + simpa only [fill, dite_eq_right hj] using (a ⟨j, hj⟩).property + +open scoped Classical in +private def assemble (d : E → ℕ) (e : E) (n : ℕ) : + Rest r d e × Level r n ≃ ((j : E) → Level r (update d e n j)) where + toFun a j := ⟨update (fill a.1) e a.2.val j, by + by_cases he : j = e + · subst j; simpa only [update_self] using a.2.property + · rw [update_of_ne he, update_of_ne he]; exact fill_energy a.1 j he⟩ + invFun a := (fun j => ⟨(a j.val).val, by simpa [j.property] using (a j.val).property⟩, + ⟨(a e).val, by simpa using (a e).property⟩) + left_inv a := by + apply Prod.ext + · funext j + apply Subtype.ext + simp [fill, j.property] + · apply Subtype.ext; simp + right_inv a := by + funext j + apply Subtype.ext + by_cases he : j = e + · subst j; simp + · simp [fill, he] + +open scoped Classical in +/-- Local identities on an internal edge can be inserted into the full +contraction. All other vertices must ignore that edge. -/ +theorem contractGraph_seam (f : V → (E → Wedge r) → F) (d : E → ℕ) + (u v : V) (huv : u ≠ v) (e : E) + (other : ∀ z, z ≠ u → z ≠ v → ∀ h a, f z (update h e a) = f z h) + (W : I → F) (d' : I → ℕ) (g k : I → (E → Wedge r) → F) + (step : ∀ h, (∀ j, j ≠ e → energy (h j).val = d j) → + (∑ a : Level r (d e), f u (update h e a.val) * f v (update h e a.val)) = + ∑ i, W i * ∑ b : Level r (d' i), g i (update h e b.val) * k i (update h e b.val)) : + contractGraph f d = + ∑ i, W i * contractGraph (update (update f u (g i)) v (k i)) (update d e (d' i)) := by + let rem (h : E → Wedge r) := ∏ z ∈ (univ.erase u).erase v, f z h + have expand (p q : (E → Wedge r) → F) (n : ℕ) : + contractGraph (update (update f u p) v q) (update d e n) = + ∑ t : Rest r d e, rem (fill t) * + ∑ a : Level r n, p (update (fill t) e a.val) * q (update (fill t) e a.val) := by + rw [contractGraph, ← (assemble (r := r) d e n).sum_comp, Fintype.sum_prod_type] + refine sum_congr rfl fun t _ => ?_ + rw [mul_sum] + refine sum_congr rfl fun a _ => ?_ + let h := update (fill t) e a.val + change (∏ z, update (update f u p) v q z h) = rem (fill t) * (p h * q h) + rw [← prod_erase_mul _ _ (mem_univ u), ← prod_erase_mul _ _ (mem_erase.mpr ⟨huv.symm, + mem_univ _⟩), + update_of_ne huv, update_self, update_self, mul_assoc, mul_comm (q h)] + congr 1 + refine prod_congr rfl fun z hz => ?_ + have hv := ne_of_mem_erase hz + have hu := ne_of_mem_erase (mem_of_mem_erase hz) + rw [update_of_ne hv, update_of_ne hu] + exact other z hu hv _ _ + have first := expand (f u) (f v) (d e) + simp only [update_eq_self] at first + rw [first] + simp_rw [expand, step _ (fill_energy _), mul_sum] + rw [sum_comm] + simp only [mul_left_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +section +/- # Renaming stations and pulling back their ordinary parameters -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +variable {F T L X Y E : Type} [Field F] {r t P : ℕ} + +/-- Uses `⟨u.pos, u.a, u.b, tag u.label, fun y => u.table (π y)⟩` as the representation. -/ +def Station.pull (u : Station F r t T X) (π : Y → X) (tag : T → L) : Station F r t L Y := + ⟨u.pos, u.a, u.b, tag u.label, fun y => u.table (π y)⟩ + +/-- Transforms the indexed data by `⟨c.ports, c.stations.map (Station.pull · π tag)⟩`. -/ +def Cell.pull (c : Cell F r t T E X) (π : Y → X) (tag : T → L) : Cell F r t L E Y := + ⟨c.ports, c.stations.map (Station.pull · π tag)⟩ + +theorem batch_pull (x : Y) (u : List (Station F r t T X)) (π : Y → X) (f : Test F r t) + (tag : T → L) : + batch P x (u.map (Station.pull · π tag)) f = batch P (π x) u f := by + induction u generalizing f with + | nil => rfl + | cons a l ih => simp only [List.map_cons, batch, ih]; rfl + +theorem Cell.test_pull (x : Y) (c : Cell F r t T E X) (h : E → Wedge r) + (π : Y → X) (f : Test F r t) (tag : T → L) : + (c.pull π tag).test P x h f = c.test P (π x) h f := batch_pull _ _ _ _ _ + +theorem Cell.eval_pull (x : Y) (c : Cell F r t T E X) (h : E → Wedge r) + (π : Y → X) (tag : T → L) : + (c.pull π tag).eval P x h = c.eval P (π x) h := batch_pull _ _ _ _ _ + +omit [Field F] in +theorem Cell.pull_id (c : Cell F r t T E X) : c.pull id id = c := by + unfold pull + rw [show (fun s : Station F r t T X => s.pull id id) = id from rfl, List.map_id] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- +# Making all insertion states explicit + +First-sphere labels include seams as well as station legs. Seam ends +can occur at different positions, but always read the same wedge. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset Surface + +variable {F T X E V : Type} [Field F] [Fintype E] [Fintype V] {r t : ℕ} + (C : V → Surface.Cell F r t T E X) + +open Classical in +/-- Indexes the place by the coordinates of `Σ v, Fin (C v).stations.length`. -/ +abbrev Place := Σ v, Fin (C v).stations.length + +open Classical in +/-- The value specified by `(C i.1).stations.get i.2`. -/ +def item (i : Place C) := (C i.1).stations.get i.2 + +open Classical in +/-- Indexes the first by the coordinates of `E ⊕ Place C`. -/ +abbrev First := E ⊕ Place C +open Classical in +/-- Indexes the marked by the coordinates of `(E × F) ⊕ Place C`. -/ +abbrev Marked := (E × F) ⊕ Place C + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def source : Marked C → First C := Sum.elim (.inl ∘ Prod.fst) .inr + +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def firstEnergy (d : E → ℕ) : First C → ℕ := Sum.elim d (fun i => (item C i).a) +open Classical in +/-- The value specified by `(item C i).b`. -/ +def secondEnergy (i : Place C) := (item C i).b + +open Classical in +/-- The value specified by `(item C i).pos`. -/ +def secondPoint (i : Place C) := (item C i).pos +open Classical in +/-- Chooses the operation for the left or right summand. -/ +def firstPoint (P : ℕ) (i : Marked C) := Sum.elim Prod.snd (secondPoint C) i ^ P + +open Classical in +/-- Transforms the indexed data by `(List.finRange (C v).stations.length).map (fun i => ⟨v, +i⟩)`. -/ +def secondList (v : V) : List (Place C) := + (List.finRange (C v).stations.length).map (fun i => ⟨v, i⟩) +open Classical in +/-- Concatenates the components in the order `(secondList C v).map .inr ++ (C v).ports.map +.inl`. -/ +def firstList (v : V) : List (Marked C) := + (secondList C v).map .inr ++ (C v).ports.map .inl + +open Classical in +/-- The condition `∀ i, Level r (e i)` on the specified data. -/ +abbrev Family (r : ℕ) {I : Type} (e : I → ℕ) := ∀ i, Level r (e i) + +open Classical in +/-- The indexed operation `wick fieldKernel (l.flatMap fun i => Surface.modes (z i) (s i))`. -/ +def read {I : Type} {r : ℕ} (z : I → F) (s : I → Wedge r) (l : List I) : F := + wick fieldKernel (l.flatMap fun i => Surface.modes (z i) (s i)) + +open Classical in +/-- The factors of type `F` for the given inputs. -/ +def factors (P : ℕ) (d : E → ℕ) (x : X) + (a : Family r (firstEnergy C d)) (b : Family t (secondEnergy C)) : F := + (∏ i, (item C i).table x (a (.inr i)) (b i)) * + (∏ v, read (firstPoint C P) (fun i => (a (source C i)).val) (firstList C v)) * + ∏ v, read (secondPoint C) (fun i => (b i).val) (secondList C v) + +open Classical in +private abbrev SA (v : V) := ∀ i, Level r ((C v).stations.get i).a +open Classical in +private abbrev SB (v : V) := ∀ i, Level t ((C v).stations.get i).b + +open Classical in +private def term (P : ℕ) (x : X) (h : E → Wedge r) (v : V) (a : SA C v) (b : SB C v) := + (∏ i, ((C v).stations.get i).table x (a i) (b i)) * + forms (((List.finRange _).flatMap fun i => + Surface.modes (((C v).stations.get i).pos ^ P) (a i).val) ++ ends P h (C v).ports) + ((List.finRange _).flatMap fun i => Surface.modes ((C v).stations.get i).pos (b i).val) + +omit [Fintype E] [Fintype V] in +open Classical in +private theorem expand_cell (P : ℕ) (x : X) (h : E → Wedge r) (v : V) : + (C v).eval P x h = ∑ a : SA C v, ∑ b : SB C v, term C P x h v a b := by + have he := batch_ofFn P x (C v).stations.get + (fun l m => forms (l ++ ends P h (C v).ports) m) + rw [List.ofFn_get] at he + exact he + +open Classical in +private def splitFirst (d : E → ℕ) : Family r (firstEnergy C d) ≃ Family r d × (∀ v, SA C v) := + (Equiv.sumPiEquivProdPi _).trans ((Equiv.refl _).prodCongr + (Equiv.piCurry fun v i => Level r ((C v).stations.get i).a)) + +open Classical in +private def splitSecond : Family t (secondEnergy C) ≃ (∀ v, SB C v) := + Equiv.piCurry fun v i => Level t ((C v).stations.get i).b + +omit [Fintype E] in +open Classical in +private theorem factors_eq (P : ℕ) (d : E → ℕ) (x : X) + (a : Family r (firstEnergy C d)) (b : Family t (secondEnergy C)) : + factors C P d x a b = ∏ v, term C P x (fun e => (a (.inl e)).val) v + (fun i => a (.inr ⟨v, i⟩)) (fun i => b ⟨v, i⟩) := by + unfold factors + rw [Fintype.prod_sigma, mul_assoc, ← prod_mul_distrib, ← prod_mul_distrib] + apply prod_congr rfl + intro v _ + simp [term, read, firstPoint, firstList, secondPoint, secondList, source, item, + Surface.ends, forms, List.flatMap_map, Function.comp_def] + +open Classical in +theorem eval_factors (P : ℕ) (d : E → ℕ) (x : X) : + Surface.eval P C d x = ∑ a, ∑ b, factors C P d x a b := by + let f (p : Family r d × (∀ v, SA C v)) (b : ∀ v, SB C v) := + ∏ v, term C P x (fun e => (p.1 e).val) v (p.2 v) (b v) + have he (a b) : factors C P d x a b = f (splitFirst C d a) (splitSecond C b) := + factors_eq C P d x a b + simp only [he, (splitSecond C).sum_comp] + rw [(splitFirst C d).sum_comp (fun p => ∑ b, f p b), Fintype.sum_prod_type] + unfold Surface.eval f + simp only [expand_cell, Fintype.prod_sum] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- Outer branching on the energy of each chunk of every leg. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +open Classical in +/-- The condition `∀ i, Chunk.Shape M (e i)` on the specified data. -/ +abbrev Shapes (M : ℕ) {I : Type} (e : I → ℕ) := ∀ i, Chunk.Shape M (e i) +open Classical in +/-- The condition `∀ i, Chunk.Cells d (p i)` on the specified data. -/ +abbrev Block (d : ℕ) {I : Type} {M : ℕ} {e : I → ℕ} (p : Shapes M e) := ∀ i, Chunk.Cells d (p i) + +open Classical in +/-- Reindexes `(Σ p : Shapes M e, Block d p)` and `Family (M * d) e` by an equivalence. -/ +def families {I : Type} (M d : ℕ) (e : I → ℕ) : + (Σ p : Shapes M e, Block d p) ≃ Family (M * d) e := + (show (Σ p : Shapes M e, Block d p) ≃ (∀ i, Σ b : Chunk.Shape M (e i), Chunk.Cells d b) from + { toFun := fun a i => ⟨a.1 i, a.2 i⟩ + invFun := fun x => ⟨fun i => (x i).1, fun i => (x i).2⟩ + left_inv := fun _ => rfl + right_inv := fun _ => rfl }).trans (Equiv.piCongrRight fun i => Chunk.states M d (e i)) + +variable {F T X E V : Type} [Field F] [Fintype E] [Fintype V] {M r t : ℕ} + (C : V → Surface.Cell F (M * r) (M * t) T E X) (d : E → ℕ) + +open Classical in +/-- Indexes the profile by the coordinates of `Shapes M (firstEnergy C d) × Shapes M +(secondEnergy C)`. -/ +abbrev Profile := Shapes M (firstEnergy C d) × Shapes M (secondEnergy C) + +namespace Profile +variable {C d} (p : Profile C d) + +open Classical in +/-- Computes the astate by the application `Block r p.1`. -/ +abbrev AState := Block r p.1 +open Classical in +/-- Computes the bstate by the application `Block t p.2`. -/ +abbrev BState := Block t p.2 + +open Classical in +/-- The value specified by `families M r _ ⟨p.1, s⟩`. -/ +def joinA (s : p.AState) : Family (M * r) (firstEnergy C d) := families M r _ ⟨p.1, s⟩ +open Classical in +/-- The value specified by `families M t _ ⟨p.2, s⟩`. -/ +def joinB (s : p.BState) : Family (M * t) (secondEnergy C) := families M t _ ⟨p.2, s⟩ + +open Classical in +/-- The value specified by `∑ s : p.AState, ∑ t : p.BState, factors C P d x (p.joinA s) (p.joinB +t)`. -/ +def value (P : ℕ) (x : X) := + ∑ s : p.AState, ∑ t : p.BState, factors C P d x (p.joinA s) (p.joinB t) + +end Profile + +open Classical in +theorem eval_shapes (P : ℕ) (x : X) : Surface.eval P C d x = ∑ p : Profile C d, p.value P x := by + rw [eval_factors, Fintype.sum_prod_type, ← (families M r (firstEnergy C d)).sum_comp, + Fintype.sum_sigma] + apply sum_congr rfl + intro p _ + simp_rw [← (families M t (secondEnergy C)).sum_comp, Fintype.sum_sigma] + rw [sum_comm] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end + +/- # Number of public chunk-energy choices -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +open Finset + +open Classical in +private theorem card_shapes {I : Type} [Fintype I] [DecidableEq I] (M L : ℕ) + (e : I → ℕ) (he : ∀ i, e i ≤ L) : + Fintype.card (Shapes M e) ≤ (L + 1) ^ (M * Fintype.card I) := by + let f (p : Shapes M e) (i : I) (j : Fin M) : Fin (L + 1) := + Fin.castLE (Nat.succ_le_succ (he i)) ((p i).val j) + have hinj : Function.Injective f := by + intro p q h + funext i + apply Subtype.ext + funext j + apply Fin.ext + exact congrArg (fun a => (a i j).val) h + simpa [Fintype.card_fun, pow_mul] using Fintype.card_le_of_injective f hinj + +variable {F T X E V : Type} [Field F] [Fintype E] [Fintype V] {M r t : ℕ} + (C : V → Surface.Cell F (M * r) (M * t) T E X) (d : E → ℕ) + +omit [Field F] in +open Classical in +theorem card_profile (L : ℕ) (hd : ∀ i, d i ≤ L) + (ha : ∀ i, (item C i).a ≤ L) (hb : ∀ i, (item C i).b ≤ L) : + Fintype.card (Profile C d) ≤ (L + 1) ^ (M * (Fintype.card E + 2 * Fintype.card (Place C))) := by + have h₁ := card_shapes M L (firstEnergy C d) (by + rintro (i | i) + · exact hd i + · exact ha i) + have h₂ := card_shapes M L (secondEnergy C) hb + have he := Nat.mul_le_mul h₁ h₂ + rw [← pow_add, Fintype.card_sum] at he + rw [Fintype.card_prod] + convert he using 1 + congr 1 + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Layout +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Remnants.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Remnants.lean new file mode 100644 index 0000000000..31af0fdeb5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Surface/Remnants.lean @@ -0,0 +1,940 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Accounting +public import Mathlib.Data.Fintype.EquivFin + +/-! +# Interpolation space along a motion + +Use the seam-energy debit to count new marks. Added to the insertion +energies, the remaining seam energies pay for the pole degrees. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +open Finset + +variable {F T E V X : Type} {r t P g H U : ℕ} (s : Stage F r t T V E X) + +open scoped Classical in +theorem portWeight_eq_sum (v : V) (h : ((s.ports v).map Prod.fst).Nodup) : + portWeight s.scene.level (s.scene.cell v).ports = ∑ e ∈ s.edges v, s.scene.level e := by + unfold ports at h + rw [edges, List.sum_toFinset _ h, List.map_map] + rfl + +variable [Fintype V] + +open scoped Classical in +theorem energy_le (P H : ℕ) (v : V) : + P * sumA (s.scene.cell v).stations + sumB (s.scene.cell v).stations ≤ + (s.ledger P H).mobile v + (s.ledger P H).collected v := by + simp only [ledger, tally, sumA, sumB] + generalize (s.scene.cell v).stations = us + induction us with + | nil => simp + | cons a as ih => + have ha : P * a.a + a.b ≤ a.label.role.mobile (2 * P * H) (energyOf P a) + + a.label.role.collected (energyOf P a) := by + cases a.label.role <;> simp [Role.mobile, Role.collected, energyOf] + simp only [List.map_cons, List.sum_cons, mul_add] + omega + +variable [Field F] [Fintype E] {s} {s' : Stage F r t T V E X} + +open scoped Classical in +omit [Fintype E] in +theorem Reach.room [Finite E] (h : s.Reach P g H U s') (hp : 0 < P) (hh : 0 < H) + (unique : ∀ v, ((s.ports v).map Prod.fst).Nodup) (M N : ℕ) + (hm : ∀ v, (2 * P * H) * (s.scene.cell v).positions.length + + (∑ e ∈ s.edges v, P * s.scene.level e) ≤ (2 * P * H) * M) + (hn : ∀ v, (s.ledger P H).cost g v + + (1 + 2 * g) * (∑ e ∈ s.edges v, P * s.scene.level e) ≤ N) : s'.Room M N := by + let : Fintype E := Fintype.ofFinite E + intro v + have he := h.budget + have pt := congrFun h.ports_eq v + change (s'.scene.cell v).ports = (s.scene.cell v).ports at pt + constructor + · have hs : (s'.scene.cell v).positions.length + (∑ e ∈ s.edges v, s.hits e) ≤ + (s.scene.cell v).positions.length + (∑ e ∈ s.edges v, s'.hits e) := by + have := h.stations_le v + simp only [Cell.positions, List.length_append, List.length_map, pt] + omega + have hsum : (2 * P * H) * (∑ e ∈ s.edges v, s'.hits e) ≤ + (∑ e ∈ s.edges v, P * s.scene.level e) + (2 * P * H) * (∑ e ∈ s.edges v, s.hits e) := by + rw [mul_sum, mul_sum, ←sum_add_distrib] + exact sum_le_sum fun e _ => le_trans (Nat.le_add_left _ _) (he.edge e) + have hs' := Nat.mul_le_mul_left (2 * P * H) hs + simp only [mul_add] at hs' + have := hm v + apply Nat.le_of_mul_le_mul_left _ (show 0 < 2 * P * H by positivity) + omega + · have ht := (he.site v).trans (hn v) + have hcost := s'.energy_le P H v + have ha := Nat.le_mul_of_pos_left (sumA (s'.scene.cell v).stations) hp + have hb := Nat.le_mul_of_pos_left ((s'.ledger P H).mobile v) (show 0 < 1 + 2 * g by omega) + have huniq : ((s'.ports v).map Prod.fst).Nodup := by rw [h.ports_eq]; exact unique v + have hw : portWeight s'.scene.level (s'.scene.cell v).ports ≤ + (1 + 2 * g) * ∑ e ∈ s.edges v, (s'.ledger P H).seam e := by + rw [s'.portWeight_eq_sum v huniq, h.edges_eq] + refine le_trans ?_ (Nat.le_mul_of_pos_left _ (by omega)) + exact sum_le_sum fun e _ => Nat.le_mul_of_pos_left _ hp + unfold Ledger.cost at ht + unfold Cell.bigA + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end + +/- +# Distinguishing private residues from untouched auxiliary marks + +A fresh residue reads the numbered wire created by a crossing. It has +zero first-sphere energy. Residues without a numbered wire have never +been moved or fused, so retain their original bounds on both energies. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +open Finset Function + +variable {F T V E X : Type} {r t P g H U : ℕ} + +open scoped Classical in +/-- Requires `u.label.role = .residue ∧ ∀ k ∈ u.label.reads, k.isLeft`. -/ +def thinStation (u : Station F r t (Tag V T) X) : Prop := + u.label.role = .residue ∧ ∀ k ∈ u.label.reads, k.isLeft + +open scoped Classical in +/-- Transforms the indexed data by `(us.map fun u => if thinStation u then 1 else 0).sum`. -/ +def thinCount (us : List (Station F r t (Tag V T) X)) := + (us.map fun u => if thinStation u then 1 else 0).sum + +open scoped Classical in +/-- Transforms the indexed data by `(us.map fun u => if thinStation u then 0 else 1).sum`. -/ +def heavyCount (us : List (Station F r t (Tag V T) X)) := + (us.map fun u => if thinStation u then 0 else 1).sum + +open scoped Classical in +private theorem parts (us : List (Station F r t (Tag V T) X)) : + thinCount us + heavyCount us = us.length := by + induction us with + | nil => rfl + | cons a as ih => + unfold thinCount heavyCount at ih ⊢ + simp only [List.map_cons, List.sum_cons, List.length_cons] + split_ifs <;> omega + +namespace Stage +variable [Field F] {s s' : Stage F r t T V E X} + +open scoped Classical in +theorem Step.counts (h : Step P g H U s s') (z : V) : + thinCount (s'.scene.cell z).stations ≤ thinCount (s.scene.cell z).stations ∧ + heavyCount (s'.scene.cell z).stations + (∑ e ∈ s.edges z, s.hits e) ≤ + heavyCount (s.scene.cell z).stations + ∑ e ∈ s.edges z, s'.hits e := by + have hsize := h.stations_le z + have hp := parts (s.scene.cell z).stations + have hp' := parts (s'.scene.cell z).stations + suffices ht : thinCount (s'.scene.cell z).stations = thinCount (s.scene.cell z).stations ∨ + (thinCount (s'.scene.cell z).stations + 1 = thinCount (s.scene.cell z).stations ∧ + (s'.scene.cell z).stations.length < (s.scene.cell z).stations.length ∧ s'.hits = s.hits) by + rcases ht with ht | ⟨ht, hl, he⟩ + · omega + · rw [he]; omega + cases h with + | perm v ls hs => + left + by_cases he : z = v + · subst z + simp only [put, Scene.put, update_self, thinCount] + exact (hs.symm.map _).sum_eq + · simp [put, Scene.put, he] + | expire v c u hv ha => + left + by_cases he : z = v <;> simp [freeze, put, Scene.put, he, hv, Cell.insert, thinCount, + thinStation, ha] + | merge v c a b n hv ha _ j q => + by_cases he : z = v + · subst z + have hb : ¬thinStation b := by simp [thinStation, ha] + have hm : ¬thinStation (mergeAt a b (a.label.join b.label) q) := by + by_cases h : a.label.role = .collector <;> simp [thinStation, mergeAt, Surface.merge, + Tag.join, ha, h] + by_cases ha' : thinStation a + · right + simp [put, Scene.put, hv, Cell.insert, thinCount, hb, hm, ha', add_comm] + rfl + · left + simp [put, Scene.put, hv, Cell.insert, thinCount, hb, hm, ha'] + rfl + · left + simp [put, Scene.put, he] + | cross v w j L R u a S i n hv hw ne _ _ ha => + left + by_cases h : z = w + · simp [advance, Scene.crossed, h, hw, Passage.right, Cell.insert, Cell.pull, Station.pull, + Passage.arrives, transfer, Tag.take, thinCount, thinStation, Function.comp_def] + by_cases h' : z = v + · simp [advance, Scene.crossed, h', ne, hv, ha, Passage.left, Cell.insert, Cell.pull, + Station.pull, + Passage.leaves, residue, Tag.leave, thinCount, thinStation, Function.comp_def] + simp [advance, Scene.crossed, h, h', Cell.pull, Station.pull, thinCount, thinStation, + Function.comp_def] + +open scoped Classical in +theorem Reach.counts (h : s.Reach P g H U s') (v : V) : + thinCount (s'.scene.cell v).stations ≤ thinCount (s.scene.cell v).stations ∧ + heavyCount (s'.scene.cell v).stations + (∑ e ∈ s.edges v, s.hits e) ≤ + heavyCount (s.scene.cell v).stations + ∑ e ∈ s.edges v, s'.hits e := by + induction h with + | refl => exact ⟨le_rfl, le_rfl⟩ + | tail r q ih => + have hs := q.counts v + rw [Reach.edges_eq r] at hs + omega + +open scoped Classical in +theorem Reach.hidden_le (h : s.Reach P g H U s') {M : ℕ} (init : ∀ k ∈ s.hidden, k ≤ M) + (bnd : ∀ y, s.Reach P g H U y → ∀ v a, a ∈ (y.scene.cell v).stations → a.b ≤ M) : + ∀ k ∈ s'.hidden, k ≤ M := by + induction h with + | refl => exact init + | tail r q ih => + cases q with + | perm => exact ih + | expire => exact ih + | merge => exact ih + | cross v w j L R u a S i n hv => + intro k hk + rcases List.mem_cons.mp hk with he|he + · rw [he]; exact bnd _ r v u (by simp [hv, Cell.insert]) + · exact ih k he + +open scoped Classical in +/-- A residue either has the initial auxiliary energy bounds or has +zero first-sphere energy. The numbered-wire read distinguishes them. -/ +def Residues (s : Stage F r t T V E X) (A B : ℕ) : Prop := + ∀ v u, u ∈ (s.scene.cell v).stations → u.label.role = .residue → + if thinStation u then u.a ≤ A ∧ u.b ≤ B else u.a = 0 + +open scoped Classical in +theorem Step.residues (h : Step P g H U s s') {A B : ℕ} (initial : s.Residues A B) : + s'.Residues A B := by + cases h with + | perm v ls hs => + intro z (b : s.St) hb hr + apply initial z b _ hr + by_cases he : z = v + · subst z + simp only [put, Scene.put, update_self] at hb + exact hs.mem_iff.mpr hb + · simp only [put, Scene.put, update_of_ne he] at hb + exact hb + | expire v c u hv => + intro z (b : s.St) hb hr + apply initial z b _ hr + by_cases he : z = v + · subst z + simp only [freeze, put, Scene.put, update_self, Cell.insert] at hb + rcases List.mem_cons.mp hb with rfl | hm + · cases hr + · rw [hv]; exact List.mem_cons_of_mem _ hm + · simp only [freeze, put, Scene.put, update_of_ne he] at hb + exact hb + | merge v c a u n hv ha _ j q => + intro z (b : s.St) hb hr + apply initial z b _ hr + by_cases he : z = v + · subst z + simp only [put, Scene.put, update_self, Cell.insert] at hb + rcases List.mem_cons.mp hb with rfl | hm + · by_cases h : a.label.role = .collector <;> + simp [mergeAt, Surface.merge, Tag.join, h, ha] at hr + · rw [hv]; exact List.mem_cons_of_mem _ (List.mem_cons_of_mem _ hm) + · simp only [put, Scene.put, update_of_ne he] at hb + exact hb + | cross v w j L R u a S i n hv hw ne => + intro z (b : Station F r t (Tag V T) (Stack X t s.hidden × Level t u.b)) hb hr + by_cases hz : z = w + · subst z + simp only [advance, Scene.crossed, update_self, Passage.right, Cell.insert, Cell.pull] at hb + rcases List.mem_cons.mp hb with rfl | hm + · cases hr + · obtain ⟨q, hq, rfl⟩ := List.mem_map.mp hm + exact initial w q (by rw [hw]; exact hq) hr + by_cases hz' : z = v + · subst z + simp only [advance, Scene.crossed, update_of_ne ne, update_self, Passage.left, Cell.insert, + Cell.pull] at hb + rcases List.mem_cons.mp hb with rfl | hm + · simp [thinStation, Passage.leaves, residue, Tag.leave] + · obtain ⟨q, hq, rfl⟩ := List.mem_map.mp hm + exact initial v q (by rw [hv]; exact List.mem_cons_of_mem _ hq) hr + simp only [advance, Scene.crossed, update_of_ne hz, update_of_ne hz', Cell.pull] at hb + obtain ⟨q, hq, rfl⟩ := List.mem_map.mp hb + exact initial z q hq hr + +open scoped Classical in +theorem Reach.residues (h : s.Reach P g H U s') {A B : ℕ} (initial : s.Residues A B) : + s'.Residues A B := by + induction h with + | refl => exact initial + | tail _ q ih => exact q.residues ih + +omit [Field F] in +open scoped Classical in +theorem Residues.classify {A B : ℕ} (h : s.Residues A B) (stop : s.Stopped) (v : V) + (u : s.St) (hu : u ∈ (s.scene.cell v).stations) : + (thinStation u → u.a ≤ A ∧ u.b ≤ B) ∧ + (¬thinStation u → u.label.role ≠ .collector → u.a = 0) := by + refine ⟨fun ht => by simpa [ht] using h v u hu ht.1, fun ht hc => ?_⟩ + cases hr : u.label.role with + | active i => exact (stop v u hu i hr).elim + | collector => exact (hc hr).elim + | residue => simpa [ht] using h v u hu hr + +end Stage +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Finite expansions with a common scalar for all exterior assignments -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset +variable {F T V E X : Type} [Field F] [Fintype V] [Fintype E] {r t P : ℕ} + +open scoped Classical in +theorem trace_mul (t : ℕ) (x : X) (l : List ℕ) (a : F) (f : Stack X t l → F) : + traceStack t x l (fun y => a * f y) = a * traceStack t x l f := by + induction l with + | nil => rfl + | cons n l ih => simp only [traceStack, ← mul_sum, ih] + +open scoped Classical in +theorem trace_sum {I : Type} [Fintype I] (t : ℕ) (x : X) (l : List ℕ) + (f : I → Stack X t l → F) : + traceStack t x l (fun y => ∑ i, f i y) = ∑ i, traceStack t x l (f i) := by + induction l with + | nil => rfl + | cons n l ih => + simp only [traceStack, ← ih] + congr 1 + funext y + exact sum_comm + +namespace Stage + +open scoped Classical in +/-- Computes the observe by the application `traceStack t x s.hidden (s.scene.observe P v f)`. -/ +def observe (s : Stage F r t T V E X) (P : ℕ) (v : V) (f : Test F r t) (x : X) := + traceStack t x s.hidden (s.scene.observe P v f) + +open scoped Classical in +theorem observe_forms (s : Stage F r t T V E X) (v : V) : s.observe P v forms = s.value P := by + unfold observe value + rw [funext (s.scene.observe_forms v)] + +open scoped Classical in +/-- A bounded linear combination of stages, valid as a table identity. -/ +def Terms (P : ℕ) (good : Stage F r t T V E X → Prop) (n : ℕ) (f : X → F) : Prop := + ∃ (I : Type) (_ : Fintype I) (c : I → F) (y : I → Stage F r t T V E X), + Fintype.card I ≤ n ∧ (∀ i, good (y i)) ∧ ∀ x, f x = ∑ i, c i * (y i).value P x + +namespace Terms +variable {good : Stage F r t T V E X → Prop} {n m : ℕ} {f : X → F} + +open scoped Classical in +theorem mono (h : Terms P good n f) (e : n ≤ m) : Terms P good m f := by + obtain ⟨I, fi, c, y, hc, hy, hf⟩ := h + exact ⟨I, fi, c, y, hc.trans e, hy, hf⟩ + +open scoped Classical in +theorem one {s : Stage F r t T V E X} (h : good s) : Terms P good 1 (s.value P) := + ⟨Unit, inferInstance, fun _ => 1, fun _ => s, by simp, fun _ => h, by simp⟩ + +open scoped Classical in +theorem scale (h : Terms P good n f) (a : F) : Terms P good n (fun x => a * f x) := by + obtain ⟨I, fi, c, y, hc, hy, hf⟩ := h + exact ⟨I, fi, fun i => a * c i, y, hc, hy, fun x => by simp only [hf, mul_sum, mul_assoc]⟩ + +open scoped Classical in +theorem combine {I : Type} [Fintype I] (c : I → F) (u : I → X → F) + (hu : ∀ i, Terms P good n (u i)) : Terms P good (Fintype.card I * n) (fun x => ∑ i, + c i * u i x) := by + unfold Terms at hu ⊢ + choose A hA k y hk hy he using hu + let _ := hA + refine ⟨Σ i, A i, inferInstance, fun i => c i.1 * k i.1 i.2, fun i => y i.1 i.2, + ?_, fun i => hy i.1 i.2, fun x => ?_⟩ + · rw [Fintype.card_sigma] + simpa using sum_le_sum (s := univ) (fun i _ => hk i) + · simp only [he, mul_sum, Fintype.sum_sigma, mul_assoc] + +end Terms +end Stage +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Preservation of positions and the moving clock -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Function +variable {F T V E X : Type} {r t P g H U : ℕ} + +open scoped Classical in +@[simp] theorem Cell.positions_insert (c : Cell F r t T E X) (u : Station F r t T X) : + (c.insert u).positions = u.pos :: c.positions := rfl + +open scoped Classical in +@[simp] theorem Cell.positions_pull {Y K : Type} (c : Cell F r t T E X) (f : Y → X) (q : T → K) : + (c.pull f q).positions = c.positions := by + simp [Cell.positions, Cell.pull, Station.pull, Function.comp_def] + +namespace Stage + +variable {s : Stage F r t T V E X} + +open scoped Classical in +private theorem valid_of_one (hd : ∀ v, (s.scene.cell v).positions.Nodup) + (hc : ∀ v, ∃ u ∈ (s.scene.cell v).stations, u.label.role = .collector) + (v : V) (u : s.St) (hu : u.label.role.clock ≤ U) + (h : ∀ w b, b ∈ (s.scene.cell w).stations → b.label.role.clock ≠ 0 → w = v ∧ b = u) : + s.Valid U := by + refine ⟨hd, hc, ?_, ?_⟩ + · intro w b hb + by_cases hz : b.label.role.clock = 0 + · simp [hz] + rw [(h w b hb hz).2] + exact hu + · intro w b hb hb' w' a ha ha' + obtain ⟨rfl, rfl⟩ := h w b hb hb' + exact h w' a ha ha' + +open scoped Classical in +theorem Valid.choose (h : s.Valid U) (hs : ¬ s.Stopped) : + ∃ (v : V) (a b : List s.St) (u : s.St) (n : ℕ), + (s.scene.cell v).stations = a ++ u :: b ∧ u.label.role = .active n ∧ + n ≤ U ∧ s.Ready v (a ++ b) := by + have pick : ∃ v u, u ∈ (s.scene.cell v).stations ∧ (∃ n, u.label.role = .active n) ∧ + (∀ w t, t ∈ (s.scene.cell w).stations → t.label.role.clock ≠ 0 → w = v ∧ t = u) := by + by_cases pos : ∃ v u, u ∈ (s.scene.cell v).stations ∧ u.label.role.clock ≠ 0 + · obtain ⟨v, u, hu, hc⟩ := pos + refine ⟨v, u, hu, ?_, h.focus v u hu hc⟩ + cases e : u.label.role <;> simp_all [Role.clock] + · push Not at pos + unfold Stopped at hs + push Not at hs + obtain ⟨v, u, hu, n, hn⟩ := hs + exact ⟨v, u, hu, ⟨n, hn⟩, fun w t ht hc => (hc (pos w t ht)).elim⟩ + obtain ⟨v, u, hu, ⟨n, hn⟩, hp⟩ := pick + obtain ⟨a, b, hb⟩ := List.append_of_mem hu + have hnd : u ∉ a ++ b := by + have h' := (List.nodup_append.mp (h.distinct v)).1.of_map Station.pos + rw [hb] at h' + exact (List.nodup_cons.mp (List.perm_middle.nodup_iff.mp h')).1 + refine ⟨v, a, b, u, n, hb, hn, by simpa [hn, Role.clock] using h.bound v u hu, ?_, ?_⟩ + · intro t ht + by_contra h' + have he : t ∈ (s.scene.cell v).stations := by + rw [hb]; exact List.perm_middle.mem_iff.mpr (.tail _ ht) + exact hnd ((hp v t he h').2 ▸ ht) + · intro w hw t ht + by_contra h' + exact hw (hp w t ht h').1 + +open scoped Classical in +theorem Valid.perm (h : s.Valid U) (v : V) (ls : List s.St) (hl : (s.scene.cell v).stations.Perm + ls) : + (s.put v ⟨(s.scene.cell v).ports, ls⟩).Valid U := by + let s' := s.put v ⟨(s.scene.cell v).ports, ls⟩ + have mem (w : V) (u : s.St) : u ∈ (s'.scene.cell w).stations ↔ u ∈ (s.scene.cell w).stations := by + change u ∈ (update s.scene.cell v ⟨(s.scene.cell v).ports, ls⟩ w).stations ↔ _ + by_cases hv : w = v + · subst w; simpa using hl.mem_iff.symm + · simp [hv] + change s'.Valid U + refine ⟨?_, ?_, fun w u hu => h.bound w u ((mem w u).mp hu), ?_⟩ + · intro w + by_cases hv : w = v + · subst w + simpa [s', put, Scene.put, Cell.positions] using + ((hl.map Station.pos).append_right ((s.scene.cell v).ports.map Prod.snd)).nodup_iff.mp + (h.distinct v) + · simpa [s', put, Scene.put, hv] using h.distinct w + · intro w + obtain ⟨u, hu, he⟩ := h.collector w + exact ⟨u, (mem w u).mpr hu, he⟩ + · exact fun w u hu hc w' b hb hb' => h.focus w u ((mem w u).mp hu) hc w' b ((mem w' b).mp hb) hb' + +open scoped Classical in +private theorem Valid.place (hs : s.Valid U) (v : V) (c : s.Ct) (u : s.St) (n : ℕ) + (hr : s.Ready v c.stations) (hc : ∃ a ∈ (c.insert u).stations, a.label.role = .collector) + (hd : (c.insert u).positions.Nodup) (hu : u.label.role.clock ≤ U) : + ({s.put v (c.insert u) with expired := n}).Valid U := by + refine valid_of_one ?_ ?_ v u hu ?_ + · intro w + change (update s.scene.cell v (c.insert u) w).positions.Nodup + by_cases e : w = v + · subst w; simpa using hd + · rw [update_of_ne e]; exact hs.distinct w + · intro w + change ∃ a ∈ (update s.scene.cell v (c.insert u) w).stations, a.label.role = .collector + by_cases e : w = v + · subst w; rw [update_self]; exact hc + · rw [update_of_ne e]; exact hs.collector w + · intro w b hb hn + change b ∈ (update s.scene.cell v (c.insert u) w).stations at hb + by_cases e : w = v + · subst w + rw [update_self] at hb + rcases List.mem_cons.mp hb with h|h + · exact ⟨rfl, h⟩ + · exact (hn (hr.1 _ h)).elim + · rw [update_of_ne e] at hb + exact (hn (hr.2 w e _ hb)).elim + +open scoped Classical in +theorem Valid.freeze (hs : s.Valid U) (v : V) (c : s.Ct) (u : s.St) + (hv : s.scene.cell v = c.insert u) (hr : s.Ready v c.stations) : + (s.freeze v c u).Valid U := by + unfold Stage.freeze + apply hs.place v c _ _ hr + · exact ⟨_, List.mem_cons_self, rfl⟩ + · simpa only [hv, Cell.positions_insert] using hs.distinct v + · exact Nat.zero_le U + +variable [Field F] + +open scoped Classical in +theorem Valid.merge (hs : s.Valid U) (v : V) (c : s.Ct) (a b : s.St) (n : ℕ) + (hv : s.scene.cell v = (c.insert b).insert a) (ha : b.label.role = .active n) + (hr : s.Ready v (a :: c.stations)) (q : ℤ × ℤ) : + (s.put v (c.insert (mergeAt a b (a.label.join b.label) q))).Valid U := by + let y := mergeAt a b (a.label.join b.label) q + have ready : s.Ready v c.stations := ⟨fun t ht => hr.1 t (.tail _ ht), hr.2⟩ + apply hs.place v c y s.expired ready + · by_cases h : a.label.role = .collector + · exact ⟨y, List.mem_cons_self, by simp [y, mergeAt, Surface.merge, Tag.join, h]⟩ + obtain ⟨u, hu, hc⟩ := hs.collector v + rw [hv] at hu + rcases List.mem_cons.mp hu with rfl|hu + · exact (h hc).elim + rcases List.mem_cons.mp hu with rfl|hu + · simp [ha] at hc + · exact ⟨u, .tail _ hu, hc⟩ + · have h := hs.distinct v + rw [hv, Cell.positions_insert, Cell.positions_insert] at h + exact ((List.Sublist.refl _).cons b.pos |>.cons_cons a.pos).nodup h + · have h := hs.bound v b (by rw [hv]; exact List.mem_cons_of_mem _ List.mem_cons_self) + change (a.label.join b.label).role.clock ≤ U + unfold Tag.join + split_ifs with he + · simp [he, Role.clock] + · exact h + +open scoped Classical in +theorem Valid.advance (hs : s.Valid U) (v w : V) (j : E) (L R : s.Sock) + (u : s.St) (a : Passage P u) (S : Lower F r) (i : a.Branch) (n : ℕ) + (hv : s.scene.cell v = (L.plug j a.z).insert u) (hw : s.scene.cell w = R.plug j a.y) + (ne : v ≠ w) (ha : u.label.role = .active n) (hn : n < U) (ready : s.Ready v L.stations) + (hl : i.2.1.val ∉ (L.plug j a.z).positions) (hr : a.root i.2.2.2 ∉ (R.plug j a.y).positions) : + (s.advance a v w j L R S i).Valid U := by + let s' := s.advance a v w j L R S i + let l : s'.St := a.leaves (Tag.leave s.hidden.length) i + let z : s'.St := a.arrives (u.label.take s.hidden.length) S i + let f : Stack X t s'.hidden → Stack X t s.hidden := Prod.fst + let c (i : V) := if i = v then L.plug j a.z else s.scene.cell i + have old (k) : (c k).positions.Nodup ∧ + (∃ u ∈ (c k).stations, u.label.role = .collector) ∧ ∀ u ∈ (c k).stations, u.label.role.clock + = 0 := by + by_cases e : k = v + · subst k + unfold c; rw [ite_eq_left rfl] + have h := hs.distinct v + obtain ⟨p, hp, ht⟩ := hs.collector v + rw [hv, Cell.positions_insert] at h + rw [hv] at hp + rcases List.mem_cons.mp hp with rfl|hp + · simp [ha] at ht + · exact ⟨(List.nodup_cons.mp h).2, ⟨p, hp, ht⟩, ready.1⟩ + · unfold c; rw [ite_eq_right e] + exact ⟨hs.distinct k, hs.collector k, ready.2 k e⟩ + let add (k : V) : List s'.St := if k = v then [l] else if k = w then [z] else [] + have eqn (k : V) : s'.scene.cell k = + ⟨(c k).ports, add k ++ (c k).stations.map (Station.pull · f id)⟩ := by + by_cases e : k = v + · subst k + simp only [s', Stage.advance, Scene.crossed, update_of_ne ne, update_self, c, add, ↓reduceIte] + rfl + by_cases e' : k = w + · subst k + simp only [s', Stage.advance, Scene.crossed, update_self, c, add, ite_eq_right e, ↓reduceIte, + hw] + rfl + simp only [s', Stage.advance, Scene.crossed, update_of_ne e', update_of_ne e, c, add, + ite_eq_right e, ite_eq_right e'] + rfl + change s'.Valid U + refine valid_of_one ?_ ?_ w z ?_ ?_ + · intro k + rw [eqn] + have h := (old k).1 + simp only [Cell.positions, List.map_append, List.map_map, Function.comp_def, Station.pull, + List.append_assoc] + change ((add k).map Station.pos ++ (c k).positions).Nodup + by_cases e : k = v + · subst k + rw [show add v = [l] by simp [add]] + change (i.2.1.val :: (c v).positions).Nodup + exact h.cons (by simpa [c] using hl) + by_cases e' : k = w + · subst k + rw [show add w = [z] by simp [add, e]] + change (a.root i.2.2.2 :: (c w).positions).Nodup + exact h.cons (by simpa [c, e, hw] using hr) + simpa [add, e, e'] using h + · intro k + obtain ⟨u, hu, hr⟩ := (old k).2.1 + rw [eqn] + exact ⟨u.pull f id, List.mem_append_right _ (List.mem_map_of_mem hu), hr⟩ + · change u.label.role.clock + 1 ≤ U + simpa [ha, Role.clock] using hn + · intro k b hb hb' + rw [eqn] at hb + rcases List.mem_append.mp hb with hm|hm + · unfold add at hm + split_ifs at hm with hv' hw' + · rw [List.mem_singleton.mp hm] at hb' + exact (hb' rfl).elim + · exact ⟨hw', List.mem_singleton.mp hm⟩ + · contradiction + · obtain ⟨u, hu, rfl⟩ := List.mem_map.mp hm + exact (hb' ((old k).2.2 u hu)).elim + +end Stage +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Finite choices for interpolation and fresh marks -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion +variable {F T V E X : Type} {r t P g H U M N : ℕ} + +open scoped Classical in +/-- The quantity computed by `P * N + N + g * (P * N + N + 2 * P * H) + 1`. -/ +def window (P g H N : ℕ) := P * N + N + g * (P * N + N + 2 * P * H) + 1 + +open scoped Classical in +theorem pairs_card {a b : ℕ} (ha : a ≤ N) (hb : b ≤ N) {j : ℤ} + (hj : j ≤ (g * (P * N + N + 2 * P * H) : ℕ)) : + (pairs P a b j).card ≤ window P g H N := by + unfold pairs + dsimp only + split_ifs with he + · simp + apply card_image_le.trans + apply (card_filter_le _ _).trans + rw [card_range] + have e := Nat.mul_le_mul_left P ha + unfold window + omega + +open scoped Classical in +theorem orders_card {D : F → ℕ} {seams S : Finset F} {collector : F} {L : ℕ} + (hD : ∀ i, D i ≤ P * N + N) (hL : L ≤ P * N + N + 2 * P * H) (hS : S.card ≤ M) : + Fintype.card (Σ i : S, Fin (orders seams collector D g L i.val)) ≤ M * window P g H N := by + rw [Fintype.card_sigma] + calc + _ ≤ ∑ _ : S, window P g H N := by + refine sum_le_sum fun i _ => ?_ + rw [Fintype.card_fin] + have := hD i.val + have := Nat.mul_le_mul_left g hL + unfold orders window + split_ifs <;> omega + _ ≤ _ := by simpa using Nat.mul_le_mul_right (window P g H N) hS + +namespace Cell + +variable (c : Cell F r t T E X) + +open scoped Classical in +/-- Uses `c.positions.toFinset` as the representation. -/ +def sites := c.positions.toFinset +open scoped Classical in +/-- Transforms the indexed data by `(c.stations.map Station.pos).toFinset`. -/ +def inserts := (c.stations.map Station.pos).toFinset +open scoped Classical in +/-- Transforms the indexed data by `(c.ports.map Prod.snd).toFinset`. -/ +def seams := (c.ports.map Prod.snd).toFinset + +open scoped Classical in +@[simp] theorem sites_eq : c.sites = c.inserts ∪ c.seams + := by simp [sites, inserts, seams, positions] +open scoped Classical in +theorem inserts_sub : c.inserts ⊆ c.sites := by rw [sites_eq]; exact subset_union_left +open scoped Classical in +theorem seams_sub : c.seams ⊆ c.sites := by rw [sites_eq]; exact subset_union_right +open scoped Classical in +theorem mem_inserts {u} (h : u ∈ c.stations) : u.pos ∈ c.inserts := + List.mem_toFinset.mpr (List.mem_map_of_mem h) +open scoped Classical in +theorem mem_seams {i} (h : i ∈ c.ports) : i.2 ∈ c.seams := + List.mem_toFinset.mpr (List.mem_map_of_mem h) +open scoped Classical in +theorem disjoint (h : c.positions.Nodup) : Disjoint c.inserts c.seams := by + apply Finset.disjoint_left.mpr + intro x hx hy + exact (List.nodup_append.mp h).2.2 x (List.mem_toFinset.mp hx) x (List.mem_toFinset.mp hy) rfl + +open scoped Classical in +theorem order_bounds (d : E → ℕ) (h : c.bigA d + sumB c.stations ≤ N) : + c.orderA d ≤ N ∧ c.orderB ≤ N := by + unfold orderA orderB bigA at * + omega + +open scoped Classical in +theorem sizes (h : c.positions.length ≤ M) : c.sites.card ≤ M := + (List.toFinset_card_le _).trans h + +end Cell + +variable [Field F] +open scoped Classical in +theorem powered_iff (p l : ℕ) [ExpChar F p] (A : Finset F) (x : F) : + x ^ (p ^ l) ∈ powered (p ^ l) A ↔ x ∈ A := by + simp only [powered, mem_image, (power_injective p l).eq_iff, exists_eq_right] + +open scoped Classical in +/-- Positions for a fresh evaluation exclude the full cell, even +stationary positions that are regular for the particular sphere. -/ +def fresh [Fintype F] (s : Finset F) := univ \ s + +omit [Field F] in +open scoped Classical in +theorem fresh_size [Fintype F] {s : Finset F} (hs : s.card ≤ M) (h : M * (2 * N + 1) + < Fintype.card F) : + M * (2 * N) < (fresh s).card := by + rw [fresh, card_sdiff_of_subset (subset_univ s), card_univ] + rw [mul_add, mul_one] at h + omega + +open scoped Classical in +/-- The quantity computed by `(M + 1) * window P g H N ^ 2 * (N + 1) * K ^ 2`. -/ +def breadth (P g H M N K : ℕ) := (M + 1) * window P g H N ^ 2 * (N + 1) * K ^ 2 + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Isolating a seam in a fixed loopless layout -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface + +open Finset Motion +variable {F T V E X : Type} {r t g : ℕ} + +namespace Socket + +open scoped Classical in +theorem exists_of_mem {c : Cell F r t T E X} {j : E} {z : F} (h : (j, z) ∈ c.ports) : + ∃ L : Socket F r t T E X, L.plug j z = c := by + obtain ⟨a, b, e⟩ := List.append_of_mem h + exact ⟨⟨a, b, c.stations⟩, by simp [plug, ← e]⟩ + +variable (L : Socket F r t T E X) (j : E) (z : F) + +open scoped Classical in +theorem mem : (j, z) ∈ (L.plug j z).ports := by simp [plug] + +open scoped Classical in +theorem unused (h : ((L.plug j z).ports.map Prod.fst).Nodup) : Unused j L.base.ports := by + have e := (List.perm_middle.map Prod.fst).nodup_iff.mp h + intro k hk h' + exact (List.nodup_cons.mp e).1 (List.mem_map.mpr ⟨k, hk, h'⟩) + +open scoped Classical in +theorem bigA (d : E → ℕ) : (L.plug j z).bigA d = d j + L.base.bigA d := by + simp only [plug, base, Cell.bigA, portWeight, List.map_append, List.sum_append, + List.map_cons, List.sum_cons] + omega + +open scoped Classical in +theorem sites : (L.plug j z).sites = insert z L.base.sites := by + ext k + simp [plug, base, Cell.sites, Cell.positions] + +open scoped Classical in +theorem avoids (hd : (L.plug j z).positions.Nodup) : z ∉ L.base.sites := by + have h : (L.plug j z).positions.Perm (z :: L.base.positions) := by + simp only [Cell.positions, plug, base, List.map_append, List.map_cons, ← List.append_assoc] + exact List.perm_middle + exact fun h' => (List.nodup_cons.mp (h.nodup_iff.mp hd)).1 (List.mem_toFinset.mp h') + +end Socket + +open scoped Classical in +theorem Stage.Layout.partner {s : Stage F r t T V E X} {src dst : E → V} + (hl : s.Layout src dst g) {v : V} {i : E} {z : F} (h : (i, z) ∈ s.ports v) : + ∃ (w : V) (y : F) (R : s.Sock), v ≠ w ∧ s.scene.cell w = R.plug i y ∧ + (∀ k, k ≠ v → k ≠ w → Unused i (s.ports k)) := by + have h₁ := (hl.incident v i).mp (List.mem_map.mpr ⟨_, h, rfl⟩) + let w := if src i = v then dst i else src i + have e (k : V) : i ∈ (s.ports k).map Prod.fst ↔ k = v ∨ k = w := by + rw [hl.incident] + unfold w + grind + have ne : v ≠ w := by have := hl.loopless i; unfold w; grind + obtain ⟨⟨_, y⟩, hy, rfl⟩ := List.mem_map.mp ((e w).mpr (.inr rfl)) + obtain ⟨R, hr⟩ := Socket.exists_of_mem hy + refine ⟨w, y, R, ne, hr.symm, fun k hv hw a ha he => ?_⟩ + exact ((e k).mp (List.mem_map.mpr ⟨a, ha, he⟩)).elim hv hw + +variable [Field F] + +open scoped Classical in +theorem Cell.fixed_erase (c : Cell F r t T E X) (p l : ℕ) [ExpChar F p] (z : F) + (hz : z ∉ c.sites) (S B : Finset F) (hS : c.sites ⊆ S) (hB : c.inserts ⊆ B) : + c.Fixed (p ^ l) ((powered (p ^ l) S).erase (z ^ (p ^ l))) B := by + have h (y : F) (hy : y ∈ c.sites) : y ^ (p ^ l) ∈ (powered (p ^ l) S).erase (z ^ (p ^ l)) := + mem_erase.mpr ⟨(power_injective p l).ne (fun e => hz (e ▸ hy)), mem_image_of_mem _ (hS hy)⟩ + exact ⟨fun _ hx => h _ (c.seams_sub (c.mem_seams hx)), fun _ hx => + ⟨h _ (c.inserts_sub (c.mem_inserts hx)), hB (c.mem_inserts hx)⟩⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface +end + +/- # Productive local changes under the trace on ordinary wires -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage + +open Finset Function Motion +variable {F T V E X : Type} [Field F] [Fintype V] [Fintype E] {r t P g H U M N : ℕ} +variable {s q : Stage F r t T V E X} + +open scoped Classical in +/-- Requires `s.Reach P g H U q ∧ q.Valid U ∧ q.potential U < s.potential U`. -/ +def Gain (s : Stage F r t T V E X) (P g H U : ℕ) (q : Stage F r t T V E X) : Prop := + s.Reach P g H U q ∧ q.Valid U ∧ q.potential U < s.potential U + +open scoped Classical in +theorem Terms.transfer {f : X → F} {k : ℕ} (h : Terms P (q.Gain P g H U) k f) + (he : Step P g H U s q) (hle : q.potential U = s.potential U) : + Terms P (s.Gain P g H U) k f := by + obtain ⟨I, fi, w, y, hc, hy, hf⟩ := h + exact ⟨I, fi, w, y, hc, fun i => ⟨(hy i).1.head he, (hy i).2.1, (hy i).2.2.trans_eq hle⟩, hf⟩ + +open scoped Classical in +theorem freeze_value (v : V) (c : s.Ct) (u : s.St) + (he : s.scene.cell v = c.insert u) : s.value P = (s.freeze v c u).value P := by + have e (x : Stack X t s.hidden) : s.scene.value P x = (s.freeze v c u).scene.value P x := by + unfold Scene.value eval + apply sum_congr rfl + intro y _ + refine prod_congr rfl fun k _ => ?_ + by_cases h : k = v + · subst k + simp only [freeze, put, Scene.put, update_self, he] + rfl + · simp only [freeze, put, Scene.put, update_of_ne h] + unfold value + rw [funext e] + rfl + +open scoped Classical in +theorem freeze_terms (hv : s.Valid U) (v : V) (c : s.Ct) (u : s.St) + (he : s.scene.cell v = c.insert u) (ha : u.label.role = .active U) + (hr : s.Ready v c.stations) : Terms P (s.Gain P g H U) 1 (s.value P) := by + rw [freeze_value v c u he] + exact Terms.one ⟨.single (.expire _ _ _ _ he ha hr), hv.freeze v c u he hr, + s.potential_expire v c u he ha⟩ + +open scoped Classical in +/-- Concatenates the components in the order `s.put v ⟨(s.scene.cell v).ports, b ++ a ++ c⟩`. -/ +def reord (s : Stage F r t T V E X) (v : V) (a b c : List s.St) := + s.put v ⟨(s.scene.cell v).ports, b ++ a ++ c⟩ + +open scoped Classical in +theorem rotate_terms (v : V) (f : Test F r t) (hf : Signed f) (a b c : List s.St) + (hs : (s.scene.cell v).stations = a ++ b ++ c) {k : ℕ} + (ht : Terms P ((s.reord v a b c).Gain P g H U) k ((s.reord v a b c).observe P v f)) : + Terms P (s.Gain P g H U) k (s.observe P v f) := by + have e : s.observe P v f = fun x => (-1 : F) ^ (sumA a * sumA b + sumB a * sumB b) * + (s.reord v a b c).observe P v f x := by + funext x + unfold observe + rw [funext (s.scene.rotate v f hf a b c hs), trace_mul] + rfl + rw [e] + have perm : (s.scene.cell v).stations.Perm (b ++ a ++ c) := by + rw [hs] + exact List.perm_append_comm.append_right c + exact (ht.transfer (.perm _ _ _ perm) (s.potential_perm v _ perm)).scale _ + +open scoped Classical in +theorem merge_terms (p l : ℕ) [ExpChar F p] (hP : P = p ^ l) (hvalid : s.Valid U) + (v : V) (c : s.Ct) (a b : s.St) (n : ℕ) (hv : s.scene.cell v = (c.insert b).insert a) + (ha : b.label.role = .active n) (hr : s.Ready v (a :: c.stations)) + (A B : Finset F) (ha' : a.pos ^ P ∈ A) (hb' : a.pos ∈ B) (hm : b.pos ^ P ∉ A) (hm' : b.pos ∉ B) + (hc : c.Fixed P (A.erase (a.pos ^ P)) (B.erase a.pos)) (j : ℤ) + (hj : j ≤ if a.label.role = .collector then (g * (energyOf P b + 2 * P * H) : ℕ) else 0) : + Terms P (s.Gain P g H U) (merges P a b ((s.scene.cell v).orderA s.scene.level) + (s.scene.cell v).orderB j).card (s.observe P v (coefficient P A B a.pos j)) := by + subst P + let I := merges (p ^ l) a b ((s.scene.cell v).orderA s.scene.level) (s.scene.cell v).orderB j + let z (q : I) := mergeAt a b (a.label.join b.label) q.val + refine ⟨I, inferInstance, fun _ => 1, fun q => s.put v (c.insert (z q)), by simp [I], ?_, ?_⟩ + · intro q + exact ⟨.single (.merge _ _ _ _ _ n hv ha hr j _ q.property hj), + hvalid.merge v c a b n hv ha hr q.val, s.potential_merge _ _ _ _ _ hv ha rfl⟩ + · intro x + unfold observe + have h := s.scene.merge p l v c a b hv (a.label.join b.label) A B ha' hb' hm hm' hc j + rw [funext h, trace_sum] + simp only [one_mul] + rfl + +open scoped Classical in +theorem cross_terms (p l : ℕ) [ExpChar F p] (hP : P = p ^ l) (hvalid : s.Valid U) + (v w : V) (j : E) (L R : s.Sock) (u : s.St) (a : Passage P u) (n : ℕ) + (hv : s.scene.cell v = (L.plug j a.z).insert u) (hw : s.scene.cell w = R.plug j a.y) + (ne : v ≠ w) (he : s.scene.level j = a.e) (hH : a.H = H) (ha : u.label.role = .active n) + (hn : n < U) (hr : s.Ready v L.stations) + (fits : a.Fits L.base R.base s.scene.level) (hl : Unused j L.base.ports) (hr' : Unused j + R.base.ports) + (other : ∀ z, z ≠ v → z ≠ w → Unused j (s.scene.cell z).ports) + (freshL : ∀ i : a.U, i.val ∉ (L.plug j a.z).positions) + (freshR : ∀ i : a.V, a.root i ∉ (R.plug j a.y).positions) : + Terms P (s.Gain P g H U) (Fintype.card a.Branch) (s.observe P v a.coeff) := by + let S := lowering F r + let f := a.signed s.scene.level L R p l hP + have hf := s.scene.cross a v w j L R (Tag.leave s.hidden.length) + (u.label.take s.hidden.length) p l hP fits ne he hv hw hl hr' other + refine ⟨a.Branch, inferInstance, f, s.advance a v w j L R S, le_rfl, fun i => ?_, fun x => ?_⟩ + · exact ⟨.single (.cross _ _ _ _ _ _ _ _ _ _ n hv hw ne he hH ha hn hr rfl), + hvalid.advance v w j L R u a S i n hv hw ne ha hn hr (freshL _) (freshR _), + s.potential_advance _ _ _ _ _ _ _ _ _ hv hw ne ha hn⟩ + · unfold observe + rw [funext hf, trace_sum] + exact sum_congr rfl fun i _ => trace_mul _ _ _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Stage +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/TableMotion.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/TableMotion.lean new file mode 100644 index 0000000000..c02dd1ca5c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/TableMotion.lean @@ -0,0 +1,874 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Block +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Private.Preparation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Coupled + +/-! +# Fusion of simultaneous collisions + +Groups are in cluster order. Their offsets determine the independent +fusion coefficients, leaving a Wick sum at the cluster centers. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable {F R : Type*} {n r : ℕ} + +namespace Cluster + +private def active (c : Fin n → F) (xs : Fin n → List (Site F r)) : List (Leg F r) := + (List.ofFn (fun i => (xs i).map (Leg.moving (c i)))).flatten + +private def ready {N : ℕ} (c : Fin n → F) (b : Fin n → LevelLE r N) : List (Site F r) := + (List.ofFn (fun i => (b i).val.val.map (c i, ·))).flatten + +private theorem active_succ (c : Fin (n + 1) → F) (xs : Fin (n + 1) → List (Site F r)) : + active c xs = (xs 0).map (Leg.moving (c 0)) ++ active (Fin.tail c) (Fin.tail xs) := by + rw [active, List.ofFn_succ, List.flatten_cons] + rfl + +private theorem ready_succ {N : ℕ} (c : Fin (n + 1) → F) (b : Fin (n + 1) → LevelLE r N) : + ready c b = (b 0).val.val.map (c 0, ·) ++ ready (Fin.tail c) (Fin.tail b) := by + rw [ready, List.ofFn_succ, List.flatten_cons] + rfl + +variable [Field F] [CommRing R] [Algebra F R] + +private theorem all_fused (u : R) (N : ℕ) (ys : List (Site F r)) : + wick (pair u N) (ys.map Leg.fused) = algebraMap F R (wick fieldKernel ys) := by + rw [wick_map, wick_hom] + rfl + +private theorem all_blocks (u : R) (N : ℕ) (hu : u ^ N = 0) + (c : Fin n → F) (hc : Function.Injective c) (xs : Fin n → List (Site F r)) + (pre : List (Site F r)) : + wick (pair u N) (pre.map Leg.fused ++ active c xs) = + ∑ b : Fin n → LevelLE r N, u ^ (∑ i, energy (b i).val.val) * + algebraMap F R ((∏ i, blockCoeff (xs i) (b i).val) * + wick fieldKernel (pre ++ ready c b)) := by + classical + induction n generalizing pre with + | zero => simp [active, ready, all_fused] + | succ n ih => + have htail : Function.Injective (Fin.tail c) := hc.comp (Fin.succ_injective _) + have ha : ∀ y ∈ active (Fin.tail c) (Fin.tail xs), ¬ belongs (c 0) y := by + simp only [active, List.mem_flatten, List.mem_ofFn] + rintro y ⟨_, ⟨i, rfl⟩, hy⟩ + obtain ⟨z, _, rfl⟩ := List.mem_map.mp hy + exact fun e => Fin.succ_ne_zero i (hc e).symm + let e := Fin.consEquiv (fun _ : Fin (n + 1) => LevelLE r N) + rw [active_succ, ← List.append_assoc, block u N (c 0) hu _ _ _ (by simp only + [List.forall_mem_map, belongs, not_false_eq_true, implies_true]) ha, + ← e.sum_comp, Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro z _ + have he : pre.map Leg.fused ++ z.val.val.map (fun i => Leg.fused (c 0, i)) = + (pre ++ z.val.val.map (c 0, ·)).map Leg.fused := by + simp [Function.comp_def] + rw [he, ih _ htail, Finset.mul_sum] + apply Finset.sum_congr rfl + intro b _ + simp only [show e (z, b) = Fin.cons z b from rfl, Fin.sum_univ_succ, Fin.prod_univ_succ, + ready_succ, + Fin.cons_zero, Fin.cons_succ, Fin.tail_cons, List.append_assoc, pow_add, map_mul] + dsimp only [Fin.tail] + ring + +end Cluster + +open Cluster + +/-- The normalized generator pairing sums agree over every nilpotent +extension. Taking the parameter modulo its Nth power recovers any desired +finite precision of the expansion. -/ +theorem multifusion [Field F] [CommRing R] [Algebra F R] + (c : Fin n → F) (xs : Fin n → List (Site F r)) + (hc : Function.Injective c) (u : R) (N : ℕ) (hu : u ^ N = 0) : + wick (clusterKernel u N (Prod.fst : F × F → F) Prod.snd) + (List.ofFn (fun i => (xs i).map (fun z => ((c i, z.1), z.2)))).flatten = + ∑ b : Fin n → LevelLE r N, u ^ (∑ i, energy (b i).val.val) * + algebraMap F R ((∏ i, blockCoeff (xs i) (b i).val) * + wick fieldKernel (List.ofFn (fun i => (b i).val.val.map (c i, ·))).flatten) := by + let lab (p : (F × F) × Mode r) := Leg.moving p.1.1 (p.1.2, p.2) + have he : active c xs = + ((List.ofFn (fun i => (xs i).map (fun z => ((c i, z.1), z.2)))).flatten).map lab := by + simp [active, List.map_flatten, List.map_ofFn, Function.comp_def, lab] + have h := all_blocks u N hu c hc xs [] + simp only [List.map_nil, List.nil_append, he, wick_map, lab, pair_moving, ready] at h + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- +# Sphere forms on fixed-energy legs + +Permuting the marked sites contributes a sign independent of the +chosen basis words because each word's parity equals its energy parity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +open Finset + +variable {A F R : Type*} [Field F] [CommRing R] [Algebra F R] {r n : ℕ} + +open scoped Classical in +/-- The condition `∀ i, Level r (e i)` on the specified data. -/ +abbrev States (r : ℕ) (e : A → ℕ) := ∀ i, Level r (e i) + +open scoped Classical in +/-- Transforms the indexed data by `(x i).val.val.map (i, ·)`. -/ +def marksAt {e : A → ℕ} (x : States r e) (i : A) : List (A × Mode r) := + (x i).val.val.map (i, ·) + +open scoped Classical in +theorem weight_list {e : A → ℕ} (x : States r e) (l : List A) : + weight (l.flatMap (marksAt x)) = (l.map e).sum := by + induction l with + | nil => rfl + | cons i l ih => + have h : weight (marksAt x i) = e i := by + simpa [weight, marksAt, Function.comp_def] using (x i).2 + simpa [weight, energy] using congrArg₂ (· + ·) h ih + +open scoped Classical in +private theorem sign_weight {e : A → ℕ} (x : States r e) (i j : A) : + (-1 : R) ^ ((marksAt x i).length * (marksAt x j).length) = (-1) ^ (e i * e j) := by + have he (a : A) : (marksAt x a).length % 2 = e a % 2 := by + rw [marksAt, List.length_map, ← energy_mod_two, (x a).2] + rw [neg_one_pow_eq_pow_mod_two, neg_one_pow_eq_pow_mod_two (e i * e j), Nat.mul_mod, + he, he, ← Nat.mul_mod] + +open scoped Classical in +theorem wick_perm_sites (e : A → ℕ) {l l' : List A} (h : l.Perm l') : + ∃ c : ℕ, ∀ (k : A × Mode r → A × Mode r → R), (∀ i j, k j i = -k i j) → + ∀ (x : States r e) (p : List (A × Mode r)), + wick k (p ++ l.flatMap (marksAt x)) = + (-1) ^ c * wick k (p ++ l'.flatMap (marksAt x)) := by + induction h with + | nil => exact ⟨0, by simp⟩ + | cons i _ ih => + obtain ⟨c, hc⟩ := ih + exact ⟨c, fun k hk x p => by simpa [List.append_assoc] using hc k hk x (p ++ marksAt x i)⟩ + | swap i j l => + refine ⟨e j * e i, fun k hk x p => ?_⟩ + simpa only [List.flatMap_cons, List.append_assoc, sign_weight] + using wick_swap_blocks hk p (marksAt x j) (marksAt x i) (l.flatMap (marksAt x)) + | trans _ _ ih₁ ih₂ => + obtain ⟨c, hc⟩ := ih₁ + obtain ⟨d, hd⟩ := ih₂ + exact ⟨c + d, fun k hk x p => by rw [hc k hk, hd k hk, pow_add, mul_assoc]⟩ + +variable [Fintype A] + +open scoped Classical in +/-- Computes the inputs by the application `univ.toList.flatMap (marksAt x)`. -/ +def inputs {e : A → ℕ} (x : States r e) : List (A × Mode r) := + univ.toList.flatMap (marksAt x) + +open scoped Classical in +theorem weight_inputs {e : A → ℕ} (x : States r e) : weight (inputs x) = ∑ i, e i := by + rw [inputs, weight_list, ← List.sum_toFinset e (nodup_toList _)] + simp + +open scoped Classical in +/-- The value specified by `({i | f i = j} : Finset _).toList`. -/ +def fiberList (f : A → Fin n) (j : Fin n) := + ({i | f i = j} : Finset _).toList + +open scoped Classical in +private theorem group_perm (f : A → Fin n) : + univ.toList.Perm ((List.finRange n).flatMap (fiberList f)) := by + have hd : ((List.finRange n).flatMap (fiberList f)).Nodup := by + refine List.nodup_flatMap.mpr ⟨fun _ _ => nodup_toList _, (List.nodup_finRange n).imp ?_⟩ + intro i j h + apply List.disjoint_left.mpr + simp only [fiberList, mem_toList, mem_filter, mem_univ, true_and] + exact fun _ hi hj => h (hi.symm.trans hj) + apply (List.perm_ext_iff_of_nodup (nodup_toList _) hd).mpr + simp [fiberList] + +open scoped Classical in +/-- Transforms the indexed data by `(fiberList f j).flatMap fun i => (x i).val.val.map (o i, +·)`. -/ +def blockInputs {e : A → ℕ} (f : A → Fin n) (o : A → F) (x : States r e) (j : Fin n) : + List (Site F r) := + (fiberList f j).flatMap fun i => (x i).val.val.map (o i, ·) + +omit [Field F] in +open scoped Classical in +theorem blockInputs_eq {e : A → ℕ} (f : A → Fin n) (o : A → F) (x y : States r e) + (j : Fin n) (h : ∀ i, f i = j → x i = y i) : + blockInputs f o x j = blockInputs f o y j := by + apply List.flatMap_congr + intro i hi + rw [h i (by simpa [fiberList] using hi)] + +open scoped Classical in +theorem grouped_fusion {e : A → ℕ} (c : Fin n → F) (hc : Function.Injective c) + (f : A → Fin n) (o : A → F) (u : R) (N : ℕ) (hu : u ^ N = 0) : + ∃ s : F, ∀ x : States r e, wick (clusterKernel u N (c ∘ f) o) (inputs x) = + algebraMap F R s * ∑ b : Fin n → LevelLE r N, u ^ (∑ j, energy (b j).val.val) * + algebraMap F R ((∏ j, blockCoeff (blockInputs f o x j) (b j).val) * + wick fieldKernel (List.ofFn (fun j => (b j).val.val.map (c j, ·))).flatten) := by + let k := clusterKernel (r := r) u N (c ∘ f) o + have skew (i j : A × Mode r) : k j i = - k i j := by + have h := Cluster.pair_skew u N (.moving (c (f i.1)) (o i.1, i.2)) + (.moving (c (f j.1)) (o j.1, j.2)) + rw [Cluster.pair_moving, Cluster.pair_moving] at h + exact h + obtain ⟨s, hs⟩ := wick_perm_sites (R := R) (r := r) e (group_perm f) + refine ⟨(-1) ^ s, fun x => ?_⟩ + have h := hs k skew x [] + rw [map_pow, map_neg, map_one] + simp only [List.nil_append, List.flatMap_assoc] at h + rw [inputs, h, ← multifusion c (blockInputs f o x) hc u N hu] + let move (i : A × Mode r) := ((c (f i.1), o i.1), i.2) + have he : (List.ofFn (fun j => + (blockInputs f o x j).map (fun z => ((c j, z.1), z.2)))).flatten = + ((List.finRange n).flatMap (fun j => (fiberList f j).flatMap (marksAt x))).map move := by + rw [List.ofFn_eq_map, List.map_flatMap] + apply List.flatMap_congr + intro j _ + simp only [blockInputs, List.map_flatMap] + apply List.flatMap_congr + intro i hi + have hij : f i = j := by simpa [fiberList] using hi + simp [marksAt, move, Function.comp_def, hij] + rw [he, wick_map] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- +# Passing an insertion through a seam + +After fusing on the near side, sum the old seam state against the far +sphere. The transposed fusion map can be recovered there by regular +evaluations. The interpolation weights are independent of all states. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +variable {F : Type} [Field F] {r : ℕ} {s : Finset F} + +open scoped Classical in +/-- Concatenates the components in the order `wick fieldKernel (a.val.map (c.val, ·) ++ +spectators ys)`. -/ +def stationary (c : s) (a : Wedge r) (ys : List (s × Mode r)) : F := + wick fieldKernel (a.val.map (c.val, ·) ++ spectators ys) + +open scoped Classical in +/-- Computes the moving by the application `wick fieldKernel ((triple c a.val x.val ys).map +(atPoint z))`. -/ +def moving (c : s) (a x : Wedge r) (ys : List (s × Mode r)) (z : F) : F := + wick fieldKernel ((triple c a.val x.val ys).map (atPoint z)) + +open scoped Classical in +private theorem fusion_odd (a x b : Wedge r) (h : (energy a.val + energy x.val + energy b.val) % 2 + = 1) : + fusion F a.val x.val b.val = 0 := by + apply wick_odd + simp only [marks, List.length_append, List.length_map, List.length_reverse] + have := energy_mod_two a.val + have := energy_mod_two x.val + have := energy_mod_two b.val + omega + +open scoped Classical in +theorem recover_level (c : s) (T : Finset F) (hT : Disjoint T s) (e m e' w : ℕ) + (bound : s.card * ((e + m + w) / 2) < T.card) : + ∃ f : T → F, ∀ (a : Level r e) (x : Wedge r) (ys : List (s × Mode r)), + energy x.val = m → (∀ y ∈ ys, y.1 ≠ c) → weight ys = w → + (∑ b : Level r e', fusion F a.val.val x.val b.val.val * stationary c b.val ys) = + ∑ z : T, f z * moving c a.val x ys z := by + by_cases h : (e + m + e') % 2 = 1 + · refine ⟨0, fun a x ys hx _ _ => ?_⟩ + have hb (b : Level r e') : fusion F a.val.val x.val b.val.val = 0 := + fusion_odd _ _ _ (by rw [a.property, hx, b.property]; exact h) + simp [hb] + let j : ℤ := ((e' : ℤ) - e - m) / 2 + let H := (e + m + w) / 2 + obtain ⟨f, hf⟩ := recover_fusion (r := r) c T hT H bound j + refine ⟨f, fun a x ys hx hy hw => ?_⟩ + have eqn := hf a.val.val x.val ys hy (by rw [weight_triple, a.property, hx, hw]) + have he : (energy a.val.val : ℤ) + energy x.val + 2 * j = e' := by + rw [a.property, hx] + unfold j + omega + dsimp only at eqn + rw [he, ite_eq_right (by omega), Int.toNat_natCast] at eqn + exact eqn + +open scoped Classical in +/-- A fixed lowering map for the whole construction. -/ +def lowering (F : Type) [Field F] (r : ℕ) : (Wedge r →₀ F) →ₗ[F] (Wedge r →₀ F) := + (seam F r).choose + +open scoped Classical in +/-- Transpose the near-side fusion coefficient through the old seam. +One choice of lowering operator works for every position and energy. +The regular evaluation weights depend only on energies and marks. -/ +theorem cross_seam (r : ℕ) : + let S := lowering F r; + (∀ x y : Wedge r, y ∈ (S (Finsupp.single x 1)).support → + energy y.val ≤ energy x.val ∧ y.val.length = x.val.length) ∧ + ∀ (s : Finset F) (c : s) (T : Finset F), Disjoint T s → + ∀ e m e' w : ℕ, s.card * ((e' + m + w) / 2) < T.card → + ∃ f : ℕ → T → F, ∀ (b : Level r e') (x : Level r m) (ys : List (s × Mode r)), + (∀ y ∈ ys, y.1 ≠ c) → weight ys = w → + (∑ a : Level r e, fusion F a.val.val x.val.val b.val.val * stationary c a.val ys) = + (S (Finsupp.single x.val 1)).sum (fun y q => + q * ∑ z : T, f (energy y.val) z * moving c b.val y ys z) := by + intro S + obtain ⟨hs, he⟩ := (seam F r).choose_spec + refine ⟨hs, ?_⟩ + intro s c T hd e m e' w hw + have hb (t : ℕ) : s.card * ((e' + min t m + w) / 2) < T.card := + lt_of_le_of_lt (Nat.mul_le_mul_left _ (by omega)) hw + choose f hf using fun t => recover_level (r := r) c T hd e' (min t m) e w (hb t) + refine ⟨f, fun b x ys hy hw' => ?_⟩ + let u := S (Finsupp.single x.val 1) + have e₁ (a : Level r e) : fusion F a.val.val x.val.val b.val.val = + ∑ y ∈ u.support, u y * fusion F b.val.val y.val a.val.val := by + have ht := DFunLike.congr_fun (he a.val b.val) (Finsupp.single x.val 1) + simp only [entry, Finsupp.linearCombination_single, one_smul, LinearMap.comp_apply] at ht + exact ht + simp only [e₁, Finset.sum_mul, mul_assoc, Finsupp.sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro y hym + have hle := (hs x.val y hym).1.trans_eq x.property + rw [← Finset.mul_sum, hf (energy y.val) b y ys (min_eq_left hle).symm hy hw'] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end + +/- +# A single seam crossing + +The near sphere has the first coordinate, its private sphere the second. +At a seam the private sphere is regular. Negative Laurent orders therefore +force a drop on the shared seam. Only regular evaluations of the private +sphere and the far sphere are needed to reconstruct the crossing. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +open Polynomial +variable {F : Type} [Field F] {r t : ℕ} {A B C : Finset F} + +open scoped Classical in +/-- New doubled energy after an order-`i` collision. -/ +def fusedEnergy (e m : ℕ) (i : ℤ) : ℤ := (e : ℤ) + m + 2 * i + +open scoped Classical in +/-- Multiply the weighted energies by `2P` to use integral units. +The loss covers the insertion and its reserve. -/ +theorem seam_drop (P e m n H d : ℕ) (j : ℤ) (v : ℤ × ℤ) (hv : v ∈ pairs P d 0 j) + (hj : (P * m + n + 2 * P * H : ℕ) ≤ -j) : + P * fusedEnergy e m v.1 + (P * m + n + 2 * P * H : ℕ) ≤ (P : ℤ) * e := by + obtain ⟨eq, _, pos⟩ := mem_pairs hv + unfold fusedEnergy + push_cast at hj pos ⊢ + have h : (0 : ℤ) ≤ (2 : ℤ) * P * H := by positivity + linarith only [eq, pos, hj, h, Int.natCast_nonneg n] + +open scoped Classical in +/-- The value specified by `(laurent z (numerator A xs) (denominatorPoly A xs)).coeff i`. -/ +def sphereCoeff (z : F) (xs : List (Option A × Mode r)) (i : ℤ) : F := + (laurent z (numerator A xs) (denominatorPoly A xs)).coeff i + +open scoped Classical in +/-- The value specified by `(laurent z (coupled P (numerator A xs) (numerator B ys)) (coupled P +(denominatorPoly A xs) (denominatorPoly B ys))).coeff j`. -/ +def pairedCoeff (P : ℕ) (z : F) (xs : List (Option A × Mode r)) (ys : List (Option B × Mode t)) + (j : ℤ) : F := + (laurent z (coupled P (numerator A xs) (numerator B ys)) + (coupled P (denominatorPoly A xs) (denominatorPoly B ys))).coeff j + +open scoped Classical in +/-- At a seam the second coordinate has no principal part. -/ +theorem coeff_at_seam (p l : ℕ) [ExpChar F p] (z : F) (ha : z ^ (p ^ l) ∈ A) (hb : z ∉ B) + (xs : List (Option A × Mode r)) (ys : List (Option B × Mode t)) (j : ℤ) : + pairedCoeff (p ^ l) z xs ys j = + ∑ v ∈ pairs (p ^ l) (weight xs / 2) 0 j, + sphereCoeff (z ^ (p ^ l)) xs v.1 * sphereCoeff z ys v.2 := by + let q := poles (A.erase (z ^ (p ^ l))) (fun _ => weight xs / 2) + have hq : q.eval (z ^ (p ^ l)) ≠ 0 := poles_eval _ (Finset.notMem_erase _ _) + have hB : (denominatorPoly B ys).eval z ≠ 0 := poles_eval _ hb + have h := coupled_coeff p l z (numerator A xs) (numerator B ys) q (denominatorPoly B ys) + (weight xs / 2) 0 hq hB j + have hA : (X - Polynomial.C (z ^ (p ^ l))) ^ (weight xs / 2) * q = denominatorPoly A xs := + (poles_split (fun _ => weight xs / 2) ha).symm + simpa only [hA, pow_zero, one_mul, pairedCoeff, sphereCoeff] using h + +open scoped Classical in +theorem recover_sphere (V : Finset F) (hV : Disjoint V B) (d : ℕ) + (bound : B.card * d < V.card) (z : F) (i : ℤ) : + ∃ g : V → F, ∀ ys : List (Option B × Mode t), weight ys / 2 = d → + sphereCoeff z ys i = ∑ y : V, g y * wick fieldKernel (ys.map (atPoint y.val)) := by + let q := poles B (fun _ => d) + obtain ⟨g, hg⟩ := recover_coefficient V q (fun _ hy + => poles_eval _ (Finset.disjoint_left.mp hV hy)) + q.natDegree (by simpa [q, degree_poles] using bound) z i + refine ⟨g, fun ys he => ?_⟩ + have h : denominatorPoly B ys = q := by unfold denominatorPoly; rw [he] + rw [← h] at hg + rw [sphereCoeff, hg _ (degree_numerator B ys)] + exact Finset.sum_congr rfl fun y _ => + congrArg (g y * ·) (eval_sphere B ys y.val (Finset.disjoint_left.mp hV y.property)) + +open scoped Classical in +/-- Contract two spheres by equality on the indicated level. Negative +levels carry no states. -/ +def sew (r : ℕ) (e : ℤ) (left right : Wedge r → F) : F := + if e < 0 then 0 else ∑ a : Level r e.toNat, left a.val * right a.val + +open scoped Classical in +theorem sew_nat (e : ℕ) (left right : Wedge r → F) : + sew r (e : ℤ) left right = ∑ a : Level r e, left a.val * right a.val := by + simp [sew] + +open scoped Classical in +private theorem sew_fusion {m : ℕ} (c : A) (ys : List (A × Mode r)) (hy : ∀ y ∈ ys, y.1 ≠ c) + (x : Level r m) (e : ℕ) (i : ℤ) (right moved : Wedge r → F) + (h : ∀ b : Level r (fusedEnergy e m i).toNat, + (∑ a : Level r e, fusion F a.val.val x.val.val b.val.val * right a.val) = moved b.val) : + sew r e (fun a => sphereCoeff c.val (triple c a.val x.val.val ys) i) right = + sew r (fusedEnergy e m i) (fun b => stationary c b ys) moved := by + let t := fusedEnergy e m i + have hc (a : Level r e) : + sphereCoeff c.val (triple c a.val.val x.val.val ys) i = + if t < 0 then 0 else ∑ b : Level r t.toNat, + fusion F a.val.val x.val.val b.val.val * stationary c b.val ys := by + rw [sphereCoeff, coeff_fusion c _ _ _ hy, a.property, x.property] + rfl + rw [sew_nat] + simp only [hc] + change _ = sew r t _ _ + by_cases neg : t < 0 + · simp [sew, neg] + simp only [sew, ite_eq_right neg, Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro b _ + rw [← h b, Finset.mul_sum] + exact Finset.sum_congr rfl fun _ _ => by ring + +open scoped Classical in +/-- Value on the far sphere with the transformed insertion. -/ +def transported (c : C) (V : Finset F) (S : (Wedge r →₀ F) →ₗ[F] (Wedge r →₀ F)) + (f : ℕ → V → F) (x : Wedge r) (ys : List (C × Mode r)) (b : Wedge r) : F := + (S (Finsupp.single x 1)).sum (fun y q => + q * ∑ z : V, f (energy y.val) z * moving c b y ys z) + +open scoped Classical in +/-- Reconstruct a seam coefficient by regular evaluations on the far +and private spheres, sewing at the lower level. The near and far spectator +energies are `u,w`. The private sphere has total doubled energy `n+v`, +including `n` from the mover. All weights are uniform in the basis entries. -/ +theorem seam_step (p l : ℕ) [ExpChar F p] (z : F) (ha : z ^ (p ^ l) ∈ A) (hb : z ∉ B) + (c : C) (U V : Finset F) (hU : Disjoint U B) (hV : Disjoint V C) + (e m n H u v w : ℕ) (hB : B.card * ((n + v) / 2) < U.card) + (hC : C.card * ((e + m + w) / 2) < V.card) : + let P := p ^ l + let d : A := ⟨z ^ P, ha⟩ + let S := lowering F r + ∃ (f : ℕ → ℕ → V → F) (g : ℤ → U → F), + (∀ x y : Wedge r, y ∈ (S (Finsupp.single x 1)).support → + energy y.val ≤ energy x.val ∧ y.val.length = x.val.length) ∧ + ∀ (j : ℤ), (P * m + n + 2 * P * H : ℕ) ≤ -j → + ∀ (x : Level r m) (ys : List (A × Mode r)) (bs : List (Option B × Mode t)) + (fs : List (C × Mode r)), (∀ y ∈ ys, y.1 ≠ d) → (∀ y ∈ fs, y.1 ≠ c) → + weight ys = u → weight bs = n + v → weight fs = w → + sew r e (fun a => pairedCoeff P z (triple d a.val x.val.val ys) bs j) + (fun a => stationary c a fs) = + ∑ q ∈ pairs P ((e + m + u) / 2) 0 j, + let E := fusedEnergy e m q.1 + sew r E (fun b => stationary d b ys) (transported c V S (f E.toNat) x.val fs) * + ∑ y : U, g q.2 y * wick fieldKernel (bs.map (atPoint y.val)) := by + intro P d S + obtain ⟨hs, ht⟩ := cross_seam (F := F) r + have hx (E : ℕ) (he : E ≤ e) : C.card * ((E + m + w) / 2) < V.card := + lt_of_le_of_lt (Nat.mul_le_mul_left _ (by omega)) hC + choose! f hf using fun E he => ht C c V hV e m E w (hx E he) + choose g hg using fun j => recover_sphere (t := t) U hU ((n + v) / 2) hB z j + refine ⟨f, g, hs, ?_⟩ + intro j hj x ys bs fs hy hfs hu hv hw + let left (a : Wedge r) := triple d a.val x.val.val ys + let I := pairs P ((e + m + u) / 2) 0 j + have h (a : Level r e) : pairedCoeff P z (left a.val) bs j = + ∑ q ∈ I, sphereCoeff d.val (left a.val) q.1 * sphereCoeff z bs q.2 := by + rw [coeff_at_seam p l z ha hb, weight_triple, a.property, x.property, hu] + rw [sew_nat] + change (∑ a : Level r e, pairedCoeff P z (left a.val) bs j * stationary c a.val fs) = _ + simp only [h, Finset.sum_mul] + rw [Finset.sum_comm] + refine Finset.sum_congr rfl fun q hq => ?_ + have he : (fusedEnergy e m q.1).toNat ≤ e := by + have drop := seam_drop P e m n H _ j q hq hj + have hp : (0 : ℤ) < P := by exact_mod_cast expChar_pow_pos F p l + have le : (P : ℤ) * fusedEnergy e m q.1 ≤ P * e := by omega + have := le_of_mul_le_mul_left le hp + omega + have eqn := sew_fusion d ys hy x e q.1 (fun a => stationary c a fs) + (transported c V S (f _) x.val fs) (fun b => hf _ he b x fs hfs hw) + rw [sew_nat] at eqn + rw [← eqn, ← hg q.2 bs (by rw [hv]), Finset.sum_mul] + exact Finset.sum_congr rfl fun _ _ => mul_right_comm _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end + +/- +# Motion on paired spheres + +In the shared coordinate, the powers in the first sphere's denominator +are multiplied by the characteristic power. Reconstruct from the +prescribed Laurent orders and fuse each insertion coefficient. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +open Polynomial Finset +variable {F : Type} [Field F] {r t : ℕ} {A B : Finset F} + +open scoped Classical in +/-- The quantity computed by `s.image (· ^ P)`. -/ +def powered (P : ℕ) (s : Finset F) : Finset F := s.image (· ^ P) + +open scoped Classical in +/-- The quantity computed by `P * d + if z ∈ B then e else 0`. -/ +def poleOrder (P d e : ℕ) (B : Finset F) (z : F) : ℕ := + P * d + if z ∈ B then e else 0 + +variable (p l : ℕ) [ExpChar F p] + +open scoped Classical in +theorem power_injective : Function.Injective (fun z : F => z ^ (p ^ l)) := by + intro x y h + dsimp only at h + apply sub_eq_zero.mp + by_contra ne + apply pow_ne_zero (p ^ l) ne + rw [sub_pow_expChar_pow, h, sub_self] + +open scoped Classical in +theorem paired_poles (S B : Finset F) (h : B ⊆ S) (d e : ℕ) : + coupled (p ^ l) (poles (powered (p ^ l) S) (fun _ => d)) (poles B (fun _ => e)) = + poles S (poleOrder (p ^ l) d e B) := by + have hA : (poles (powered (p ^ l) S) (fun _ => d)).comp (X ^ (p ^ l)) = + poles S (fun _ => p ^ l * d) := by + unfold poles powered + rw [prod_image (power_injective p l).injOn, Polynomial.prod_comp] + refine prod_congr rfl fun z _ => ?_ + rw [pow_comp, sub_comp, X_comp, C_comp, map_pow, ← sub_pow_expChar_pow, pow_mul] + have hB : poles B (fun _ => e) = poles S (fun z => if z ∈ B then e else 0) := by + unfold poles + rw [← prod_subset h (fun z _ hz => by simp [hz])] + exact prod_congr rfl fun z hz => by simp [hz] + rw [coupled, hA, hB] + unfold poles poleOrder + simp only [pow_add, prod_mul_distrib] + +open scoped Classical in +private theorem degree_pair (P : ℕ) (hP : P ≠ 0) (xs : List (Option A × Mode r)) + (ys : List (Option B × Mode t)) : + (coupled P (numerator A xs) (numerator B ys)).natDegree ≤ + (coupled P (denominatorPoly A xs) (denominatorPoly B ys)).natDegree := by + have monic (S : Finset F) (H : ℕ) : (poles S (fun _ => H)).Monic := + monic_prod_of_monic _ _ fun z _ => (monic_X_sub_C z).pow H + have hA : ((denominatorPoly A xs).comp (X ^ P)).Monic := + (monic A _).comp (monic_X.pow P) (by simp [hP]) + have hB : (denominatorPoly B ys).Monic := monic B _ + unfold coupled + rw [natDegree_mul hA.ne_zero hB.ne_zero] + refine natDegree_mul_le.trans ?_ + rw [natDegree_comp, natDegree_comp] + exact Nat.add_le_add (Nat.mul_le_mul_right _ (degree_numerator A xs)) (degree_numerator B ys) + +open scoped Classical in +/-- The interpolation weights are independent of every basis mode. +The private sphere may omit stationary marks, including the seams. -/ +theorem paired_reconstruction {S seams : Finset F} (hB : B ⊆ S) (hs : seams ⊆ S) + {collector : F} (hc : collector ∈ S) (hc' : collector ∉ seams) + (g L : ℕ) (hg : seams.card ≤ g) (d e : ℕ) (z : F) (hz : z ∉ S) : + let P := p ^ l + let D := poleOrder P d e B + ∃ c : (Σ y : S, Fin (orders seams collector D g L y.val)) → F, + ∀ (xs : List (Option (powered P S) × Mode r)) (ys : List (Option B × Mode t)), + weight xs / 2 = d → weight ys / 2 = e → + wick fieldKernel (xs.map (atPoint (z ^ P))) * wick fieldKernel (ys.map (atPoint z)) = + ∑ i, c i * pairedCoeff P i.1.val xs ys ((i.2.val : ℤ) - D i.1.val) := by + intro P D + obtain ⟨c, h⟩ := reconstruct_motion hs hc hc' D hg L z + refine ⟨c, fun xs ys hd he => ?_⟩ + let A := powered P S + have hA : z ^ P ∉ A := by + intro h + obtain ⟨x, hx, he⟩ := mem_image.mp h + exact hz (power_injective p l he ▸ hx) + have eqn : coupled P (denominatorPoly A xs) (denominatorPoly B ys) = poles S D := by + rw [denominatorPoly, denominatorPoly, hd, he] + exact paired_poles p l S B hB d e + rw [← eqn] at h + have key := h _ (degree_pair P (expChar_pow_pos F p l).ne' xs ys) + rw [← eval_sphere _ _ _ hA, ← eval_sphere _ _ _ (fun h => hz (hB h))] + simpa only [pairedCoeff, coupled, eval_mul, eval_comp, eval_pow, eval_X, + div_mul_div_comm] using key + +open scoped Classical in +/-- The weighted energy after fusion is the sum of the two incident +energies plus the Laurent order, in units of `2P`. -/ +theorem insertion_energy (P a b x y d e : ℕ) (j : ℤ) (v : ℤ × ℤ) (hv : v ∈ pairs P d e j) : + (P : ℤ) * fusedEnergy a x v.1 + fusedEnergy b y v.2 = + (P * a + b : ℕ) + (P * x + y : ℕ) + 2 * j := by + unfold fusedEnergy + push_cast + linear_combination 2 * (mem_pairs hv).1 + +open scoped Classical in +/-- Fusion through one specified level, or zero at a negative level. -/ +def fusedAt (c : A) (a x : Wedge r) (ys : List (A × Mode r)) (i : ℤ) : F := + sew r (fusedEnergy (energy a.val) (energy x.val) i) + (fun b => fusion F a.val x.val b.val) (fun b => stationary c b ys) + +open scoped Classical in +private theorem sphereCoeff_eq (c : A) (a x : Wedge r) (ys : List (A × Mode r)) + (hy : ∀ y ∈ ys, y.1 ≠ c) (i : ℤ) : + sphereCoeff c.val (triple c a.val x.val ys) i = fusedAt c a x ys i := + coeff_fusion c a.val x.val ys hy i + +open scoped Classical in +/-- At an insertion mark each term fuses both incident legs. -/ +theorem insertion_step (z : F) (hA : z ^ (p ^ l) ∈ A) (hB : z ∈ B) + (a x : Wedge r) (b y : Wedge t) (ys : List (A × Mode r)) (ws : List (B × Mode t)) + (hy : ∀ i ∈ ys, i.1 ≠ ⟨z ^ (p ^ l), hA⟩) (hw : ∀ i ∈ ws, i.1 ≠ ⟨z, hB⟩) (j : ℤ) : + let c : A := ⟨z ^ (p ^ l), hA⟩ + let f : B := ⟨z, hB⟩ + let u := triple c a.val x.val ys + let v := triple f b.val y.val ws + pairedCoeff (p ^ l) z u v j = + ∑ q ∈ pairs (p ^ l) (weight u / 2) (weight v / 2) j, + fusedAt c a x ys q.1 * fusedAt f b y ws q.2 := by + intro c f u v + let d := weight u / 2 + let e := weight v / 2 + let q₁ := poles (A.erase (z ^ (p ^ l))) (fun _ => d) + let q₂ := poles (B.erase z) (fun _ => e) + have h₁ : q₁.eval (z ^ (p ^ l)) ≠ 0 := poles_eval _ (notMem_erase _ _) + have h₂ : q₂.eval z ≠ 0 := poles_eval _ (notMem_erase _ _) + have h := coupled_coeff p l z (numerator A u) (numerator B v) q₁ q₂ d e h₁ h₂ j + have ha : (X - C (z ^ (p ^ l))) ^ d * q₁ = denominatorPoly A u := + (poles_split (fun _ => d) hA).symm + have hb : (X - C z) ^ e * q₂ = denominatorPoly B v := + (poles_split (fun _ => e) hB).symm + dsimp only at h + rw [ha, hb] at h + unfold pairedCoeff + rw [h] + exact sum_congr rfl fun q _ => + congrArg₂ (· * ·) (sphereCoeff_eq c a x ys hy q.1) (sphereCoeff_eq f b y ws hw q.2) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end + +/- +# Fixed-energy tables in paired motion + +The order of the exterior arguments is fixed before interpolating. A +collision can take place at any stationary mark. Bringing that mark +and the moving site to the front contributes a scalar depending only +on the energy labels and the mark. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion + +open Finset Polynomial +variable {F : Type} [Field F] {S T : Finset F} {r t : ℕ} +variable {a : Option S → ℕ} {b : Option T → ℕ} + +open scoped Classical in +/-- The indexed operation `(univ.erase z).toList.flatMap (marksAt (fun j => x (some j)))`. -/ +def rest (z : S) (x : States r a) : List (S × Mode r) := + (univ.erase z).toList.flatMap (marksAt (fun j => x (some j))) + +open scoped Classical in +/-- The sum of `a (some j)` indexed by `j ∈ univ.erase z`. -/ +def restWeight (z : S) (a : Option S → ℕ) := ∑ j ∈ univ.erase z, a (some j) + +omit [Field F] in +open scoped Classical in +theorem weight_rest (z : S) (x : States r a) : weight (rest z x) = restWeight z a := by + rw [rest, weight_list, ← List.sum_toFinset _ (nodup_toList _), toList_toFinset] + rfl + +omit [Field F] in +open scoped Classical in +theorem rest_avoids (z : S) (x : States r a) : ∀ y ∈ rest z x, y.1 ≠ z := by + intro y hy + obtain ⟨i, hi, h⟩ := List.mem_flatMap.mp hy + obtain ⟨_, _, rfl⟩ := List.mem_map.mp h + exact (mem_erase.mp (mem_toList.mp hi)).1 + +open scoped Classical in +/-- Computes the front by the application `triple z (x (some z)).val.val (x none).val.val (rest +z x)`. -/ +def front (z : S) (x : States r a) : List (Option S × Mode r) := + triple z (x (some z)).val.val (x none).val.val (rest z x) + +omit [Field F] in +open scoped Classical in +theorem weight_front (z : S) (x : States r a) : weight (front z x) = weight (inputs x) := by + rw [front, weight_triple, (x (some z)).property, (x none).property, weight_rest, + weight_inputs, Fintype.sum_option] + unfold restWeight + have := sum_erase_add univ (fun i => a (some i)) (mem_univ z) + omega + +omit [Field F] in +open scoped Classical in +theorem front_update (z : S) (x : States r a) (v : Level r (a (some z))) : + front z (Function.update x (some z) v) = triple z v.val.val (x none).val.val (rest z x) := by + have he : rest z (Function.update x (some z) v) = rest z x := by + apply List.flatMap_congr + intro i hi + have hn : some i ≠ some z := by simpa using (mem_erase.mp (mem_toList.mp hi)).1 + simp [marksAt, hn] + rw [front, he, Function.update_self, Function.update_of_ne (by simp : none ≠ some z)] + +open scoped Classical in +private theorem ordered (z : S) (a : Option S → ℕ) : + ∃ c : F, c ≠ 0 ∧ ∀ x : States r a, numerator S (inputs x) = C c * numerator S (front z x) := by + let l := some z :: none :: (univ.erase z).toList.map some + have h : univ.toList.Perm l := by + have hl : l.Nodup := by simp [l, List.nodup_map_iff (Option.some_injective _), nodup_toList] + apply (List.perm_ext_iff_of_nodup (nodup_toList _) hl).mpr + rintro (_ | i) <;> simp [l, eq_or_ne] + obtain ⟨n, hn⟩ := wick_perm_sites (R := F[X]) (r := r) a h + refine ⟨(-1) ^ n, by simp, fun x => ?_⟩ + have hh := hn _ (Routing.polynomial_skew (trajectories S)) x [] + simpa [l, numerator, Routing.correlatorPoly, front, triple, inputs, marksAt, rest, + List.flatMap_map, List.map_flatMap, Function.comp_def] using hh + +open scoped Classical in +theorem coeff_scale (z c : F) (p q : F[X]) (j : ℤ) : + (laurent z (C c * p) q).coeff j = c * (laurent z p q).coeff j := by + simp only [laurent, taylor_mul, taylor_C, Polynomial.coe_mul, Polynomial.coe_C, map_mul, + HahnSeries.ofPowerSeries_C, HahnSeries.C_apply, mul_div_assoc, HahnSeries.coeff_single_mul, + sub_zero] + +open scoped Classical in +theorem reorder_left (z : S) (a : Option S → ℕ) : + ∃ c : F, c ≠ 0 ∧ ∀ (x : States r a) (P : ℕ) (u : F) (ys : List (Option T × Mode t)) (j : ℤ), + pairedCoeff P u (inputs x) ys j = c * pairedCoeff P u (front z x) ys j := by + obtain ⟨c, hc, he⟩ := ordered (r := r) z a + refine ⟨c, hc, fun x P u ys j => ?_⟩ + simp only [pairedCoeff, he, denominatorPoly, weight_front, coupled, mul_comp, C_comp, mul_assoc, + coeff_scale] + +open scoped Classical in +theorem reorder_right (z : T) (b : Option T → ℕ) : + ∃ c : F, c ≠ 0 ∧ ∀ (y : States t b) (P : ℕ) (u : F) (xs : List (Option S × Mode r)) (j : ℤ), + pairedCoeff P u xs (inputs y) j = c * pairedCoeff P u xs (front z y) j := by + obtain ⟨c, hc, he⟩ := ordered (r := t) z b + refine ⟨c, hc, fun y P u xs j => ?_⟩ + simp only [pairedCoeff, he, denominatorPoly, weight_front, coupled] + rw [mul_left_comm _ (C c), coeff_scale] + +open scoped Classical in +/-- Sum an arbitrary joint table on the two movers and all spectators. +Its entries are independent of the internal seam index. -/ +theorem table_seam {B : Finset F} (p l : ℕ) [ExpChar F p] (z : F) (hz : z ^ (p ^ l) ∈ S) + (hz' : z ∉ T) (c : B) (U V : Finset F) (hU : Disjoint U T) (hV : Disjoint V B) + (a : Option S → ℕ) (b : Option T → ℕ) (H w : ℕ) + (ht : T.card * ((∑ i, b i) / 2) < U.card) + (hb : B.card * ((a (some ⟨z ^ (p ^ l), hz⟩) + a none + w) / 2) < V.card) : + let P := p ^ l + let d : S := ⟨z ^ P, hz⟩ + let e := a (some d) + let m := a none + ∃ (q : F) (L : (Wedge r →₀ F) →ₗ[F] (Wedge r →₀ F)) (f : ℕ → ℕ → V → F) (g : ℤ → U → F), + q ≠ 0 ∧ (∀ x y : Wedge r, y ∈ (L (Finsupp.single x 1)).support → + energy y.val ≤ energy x.val ∧ y.val.length = x.val.length) ∧ + ∀ (j : ℤ), (P * m + b none + 2 * P * H : ℕ) ≤ -j → + ∀ (I : Type) (_ : Fintype I) (W : I → F) (x : I → States r a) (y : I → States t b) + (fs : I → List (B × Mode r)), (∀ i k, k ∈ fs i → k.1 ≠ c) → (∀ i, weight (fs i) = w) → + (∑ i, W i * ∑ h : Level r e, + pairedCoeff P z (inputs (Function.update (x i) (some d) h)) (inputs (y i)) j * + stationary c h.val (fs i)) = + q * ∑ v ∈ pairs P ((e + m + restWeight d a) / 2) 0 j, + let E := fusedEnergy e m v.1 + ∑ i, W i * (sew r E (fun h => stationary d h (rest d (x i))) + (transported c V L (f E.toNat) (x i none).val (fs i)) * + ∑ s : U, g v.2 s * wick fieldKernel ((inputs (y i)).map (atPoint s.val))) := by + intro P d e m + obtain ⟨q, hq, hr⟩ := reorder_left (r := r) (T := T) (t := t) d a + rw [Fintype.sum_option] at ht + let L := lowering F r + obtain ⟨f, g, hL, h⟩ := seam_step (r := r) (t := t) p l z hz hz' c U V hU hV + e m (b none) H (restWeight d a) _ w ht hb + refine ⟨q, L, f, g, hq, hL, ?_⟩ + intro j hj I _ W x y fs hf hw + have hv (i : I) := h j hj (x i none) (rest d (x i)) (inputs (y i)) (fs i) + (rest_avoids d (x i)) (hf i) (weight_rest d (x i)) + (by rw [weight_inputs, Fintype.sum_option]) (hw i) + simp only [hr, front_update, mul_assoc q, ← mul_sum] + have eval (i : I) := (sew_nat e (fun a => pairedCoeff P z + (triple d a.val (x i none).val.val (rest d (x i))) (inputs (y i)) j) + (fun a => stationary c a (fs i))).symm.trans (hv i) + simp only [eval, mul_left_comm _ q, ← mul_sum] + congr 1 + simp only [mul_sum] + rw [sum_comm] + +open scoped Classical in +/-- Simultaneous fusion at an insertion for any joint table of inputs. -/ +theorem table_insertion (p l : ℕ) [ExpChar F p] (z : F) (hz : z ^ (p ^ l) ∈ S) (hz' : z ∈ T) + (a : Option S → ℕ) (b : Option T → ℕ) : + let P := p ^ l + let c : S := ⟨z ^ P, hz⟩ + let d : T := ⟨z, hz'⟩ + ∃ q : F, q ≠ 0 ∧ ∀ (j : ℤ) (I : Type) (_ : Fintype I) (W : I → F) + (x : I → States r a) (y : I → States t b), + (∑ i, W i * pairedCoeff P z (inputs (x i)) (inputs (y i)) j) = + q * ∑ v ∈ pairs P ((∑ i, a i) / 2) ((∑ i, b i) / 2) j, ∑ i, W i * + (fusedAt c (x i (some c)).val (x i none).val (rest c (x i)) v.1 * + fusedAt d (y i (some d)).val (y i none).val (rest d (y i)) v.2) := by + intro P c d + obtain ⟨q, hq, hr⟩ := reorder_left (r := r) (T := T) (t := t) c a + obtain ⟨u, hu, hs⟩ := reorder_right (r := r) (S := S) (t := t) d b + refine ⟨q * u, mul_ne_zero hq hu, ?_⟩ + intro j I _ W x y + have H (i : I) : pairedCoeff P z (front c (x i)) (front d (y i)) j = + ∑ v ∈ pairs P ((∑ i, a i) / 2) ((∑ i, b i) / 2) j, + fusedAt c (x i (some c)).val (x i none).val (rest c (x i)) v.1 * + fusedAt d (y i (some d)).val (y i none).val (rest d (y i)) v.2 := by + rw [← weight_inputs (x i), ← weight_inputs (y i), ← weight_front c, ← weight_front d] + exact insertion_step p l z hz hz' _ _ _ _ _ _ (rest_avoids c _) (rest_avoids d _) j + simp only [hr, hs, H, ← mul_assoc q u, mul_left_comm _ (q * u), ← mul_sum] + congr 1 + simp only [mul_sum] + rw [sum_comm] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Motion +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Verifier/Caps.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Verifier/Caps.lean new file mode 100644 index 0000000000..0d609ca5dc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Verifier/Caps.lean @@ -0,0 +1,744 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Proof.Initial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Origin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Price +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.General.Ballot +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Layout.Encode +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Initial + +/-! # Passing from checked integer quotas to physical diagram bounds -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Rounds Packing Coloring Finset +variable {F V : Type} [Fintype V] {x y : Wire} {w d e k h T D u g R C ℓ n f : ℕ} {W : ℝ} + {P : Input F x y h D T R g W} {Q : LocalTerm F x y h u} + {a : V → Blueprint w d e k} {fixed : V → B w → Bool} (H : Support V a fixed Q) + (he : ∀ i j, portEnd Q.diagram i = portEnd Q.diagram j ↔ portEnd P.diagram i + = portEnd P.diagram j) + +omit [Fintype V] in +open scoped Classical in +theorem Support.amount (v : Q.diagram.V) : + Q.charge v = (H.cellTag v).toll * u + (extLoad Q.diagram v : ℝ) := H.charge v + +omit [Fintype V] in +open scoped Classical in +theorem Support.core (v : Q.freeze.Core) : Q.charge v.val = ((H.cellTag v.val).toll : ℝ) * u := by + have h : extLoad Q.diagram v.val = 0 := by + unfold extLoad + let : IsEmpty {i // portEnd Q.diagram i = v.val} := + ⟨fun i => v.property (i.property ▸ Q.freeze.exterior i.val)⟩ + exact Fintype.card_eq_zero + rw [H.amount, h, Nat.cast_zero, add_zero] + +open scoped Classical in +/-- The quantity computed by `103 + 8 * C + 2 * squareConstant g`. -/ +def overhead (g C : ℕ) := 103 + 8 * C + 2 * squareConstant g + +include H he in +open scoped Classical in +theorem Support.concentrated (hD : 0 < D) + (hc : Fintype.card Q.V ≤ D ^ C * Fintype.card P.V) + (hd : ∀ i, (Q.frame.C i).card ≤ 3) (hf : ∀ i, (Q.frame.N i).card ≤ D ^ C) + (hl : Totals a fixed D T u C n g W) {credits : V → Credits g ℓ D f} + (hq : ∀ v, Quota C n (T / u) (fixed v) (a v) (credits v)) : + Concentrated P Q (overhead g C) n ℓ := by + let E := overhead g C + have hW : 0 ≤ W := le_trans (by positivity) P.occupied + have hpow : D ^ C ≤ D ^ E := Nat.pow_le_pow_right hD (by unfold E overhead; omega) + have hc₀ : (3 : ℝ) ≤ E := by exact_mod_cast (show 3 ≤ E by unfold E overhead; omega) + have hc₁ : (100 : ℝ) + 2 * C ≤ E := by + exact_mod_cast (show 100 + 2 * C ≤ E by unfold E overhead; omega) + have hc₂ : (2 : ℝ) * (squareConstant g + 1) ≤ E := by + exact_mod_cast (show 2 * (squareConstant g + 1) ≤ E by unfold E overhead; omega) + have hc₃ : (8 : ℝ) * C ≤ E := by exact_mod_cast (show 8 * C ≤ E by unfold E overhead; omega) + refine ⟨hc.trans (Nat.mul_le_mul_right _ hpow), fun i => (hd i).trans (by exact_mod_cast hc₀), + fun i => (hf i).trans hpow, ?_, ?_, ?_, ?_, ?_⟩ + · refine le_trans ?_ (hl.count.trans (mul_le_mul_of_nonneg_right hc₀ hW)) + gcongr + exact H.count + · intro v + have hv := (hq (H.addr v.val).1).large _ ((H.frozen _).mp v.property) + have aux (k : ℕ) : k * (T / u) * u ≤ k * T := by + rw [mul_assoc]; gcongr; exact Nat.div_mul_le_self .. + have ha : ((H.cellTag v.val).toll : ℝ) * u ≤ 2 * C * D * T := by + exact_mod_cast (Nat.mul_le_mul_right u hv).trans (aux _) + rw [H.amount] + calc + _ ≤ (2 : ℝ) * C * D * T + (100 : ℝ) * D * T + := add_le_add ha (extLoad_max P Q.diagram he v.val) + _ = (100 + 2 * (C : ℝ)) * D * T := by ring + _ ≤ _ := by gcongr + · have s : (∑ i : Q.freeze.Fixed, ((H.cellTag i.val).toll : ℝ) ^ 2) * (u : ℝ) ^ 2 + ≤ squareConstant g * W * T := + (mul_le_mul_of_nonneg_right H.square (sq_nonneg _)).trans hl.square + have r := (Support.partial_square (Q := Q) (fun i => (extLoad Q.diagram i : ℝ))).trans + (extLoad_squares P Q.diagram he) + have aux (x y : ℝ) : (x + y) ^ 2 ≤ 2 * (x ^ 2 + y ^ 2) := by nlinarith only [sq_nonneg (x - y)] + calc + _ ≤ ∑ i : Q.freeze.Fixed, 2 * ((((H.cellTag i.val).toll : ℝ) * u) ^ 2 + + (extLoad Q.diagram i.val : ℝ) ^ 2) := by + apply sum_le_sum + intro i _ + rw [H.amount] + exact aux .. + _ ≤ 2 * ((squareConstant g : ℝ) * W * T + W * T) := by + simp only [←mul_sum, sum_add_distrib, mul_pow, ←sum_mul] + exact mul_le_mul_of_nonneg_left (add_le_add s r) (by norm_num) + _ = 2 * ((squareConstant g : ℝ) + 1) * W * T := by ring + _ ≤ _ := by gcongr + · intro v + have hm := (hq (H.addr v.val).1).small _ (Bool.eq_false_iff.mpr (mt (H.frozen _).mpr + v.property)) + have ht := (Nat.mul_le_mul_right u hm).trans (Nat.div_mul_le_self T u) + rw [H.core v, mul_right_comm] + exact_mod_cast ht + · simp only [H.core, ←sum_mul] + exact ((mul_le_mul_of_nonneg_right H.mobile (Nat.cast_nonneg _)).trans hl.mobile).trans (by + gcongr) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +end + +/- +# Proposed geometry on the occupied cells + +The proposal contains no field coordinates, bit addresses or table +entries. Missing occurrences have an empty array of child slots. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Geometry Rounds +variable {F Z V : Type} [Field F] [Finite Z] (S : Scheme F) + {d e M r t q D k n u j z : ℕ} (U : Printer F Z (B S.k) S.m d S.h e M r t q D k n u j z) + (loc : V ↪ B S.m × B S.h) + +open scoped Classical in +/-- Evaluates `Function.extend loc a (fun _ _ => Geometry.Outline.empty) (i, b)` at the input `i +b`. -/ +def complete (a : V → U.Blueprint S) : U.Matrix S := + fun i b => Function.extend loc a (fun _ _ => Geometry.Outline.empty) (i, b) + +omit [Field F] [Finite Z] in +open scoped Classical in +theorem complete_here (a : V → U.Blueprint S) (i : V) : + U.complete S loc a (loc i).1 (loc i).2 = a i := loc.injective.extend_apply _ _ _ + +omit [Field F] [Finite Z] in +open scoped Classical in +theorem complete_vacant (a : V → U.Blueprint S) {i b} (h : (i, b) ∉ Set.range loc) : + U.complete S loc a i b = fun _ => Geometry.Outline.empty := Function.extend_apply' _ _ _ h + +omit [Field F] [Finite Z] in +open scoped Classical in +theorem complete_of_vacant (a : U.Matrix S) + (h : ∀ i b, (i, b) ∉ Set.range loc → a i b = fun _ => Geometry.Outline.empty) : + U.complete S loc (fun i => a (loc i).1 (loc i).2) = a := by + let r := fun i => a (loc i).1 (loc i).2 + have he (v : B S.m × B S.h) : U.complete S loc r v.1 v.2 = a v.1 v.2 := by + by_cases hv : v ∈ Set.range loc + · obtain ⟨w, rfl⟩ := hv + exact U.complete_here S loc r w + · rw [U.complete_vacant S loc _ hv, h _ _ hv] + exact funext fun i => funext fun t => he (i, t) + +open scoped Classical in +theorem complete_support (a : V → U.Blueprint S) (v : U.Actors S) + (h : (U.localAt S (U.complete S loc a) v).live = true) : + ((U.split v.1).1, v.2.1) ∈ Set.range loc := by + by_contra he + unfold localAt at h + rw [U.complete_vacant S loc _ he] at h + cases h + +open scoped Classical in +/-- Indexes the tag by the coordinates of `U.Blueprint S × Credits g σ D p`. -/ +abbrev Tag (g σ p : ℕ) := U.Blueprint S × Credits g σ D p + +variable {g σ p : ℕ} [Fintype V] + +open scoped Classical in +/-- All tests are on the short geometry fields. -/ +def passes (part : Fin p → V → V) (E H : V → ℕ) (K : ℕ) + (x : S.format.obj) (y : U.template.format.obj) (a : V → U.Tag S g σ p) : Prop := + U.Valid S x y (U.complete S loc (fun i => (a i).1)) ∧ + Credits.Check part (fun i => (a i).2) E H ∧ + ∀ i, Quota (Input.terminalExponent g σ) n K U.fixedChild (a i).1 (a i).2 + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- Recover the entire credit history from the final local address. +Each updated address encodes its predecessor at the center of the view. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Design +open Assembly Coloring +variable (a : Design) {F N A : Type} {e k : ℕ} + +/-- The value specified by `((number (a.observed e k)).symm x 0 0).1`. -/ +def previous (x : B (a.nextWidth e k)) : B e := + ((number (a.observed e k)).symm x 0 0).1 + +theorem previous_update (p : (a.port e).obj) (c : (a.selectors k).obj) (v : B a.m × B a.h) : + a.previous (((a.update p c) v.1).2 v.2) = (p v.1).2 v.2 := by + simp only [previous, update, Fmt.update, Equiv.symm_apply_apply, around, Fmt.around, Fmt.expand, + Fmt.zip, Neighborhood.origin] + +variable [Field F] [Fintype F] [ExpChar F a.p] (hF : a.M * (2 * a.D + 1) < Fintype.card F) + (menu : a.Menu F N A e) (k : ℕ) + +/-- In the case `0, _, x => fun _`, this construction gives `(menu x).2`. -/ +def historyRow : (i : ℕ) → i ≤ a.waves → B (a.widthAt e k i) → Fin (i + 1) → a.row F N + | 0, _, x => fun _ => (menu x).2 + | i + 1, hi, x => Fin.snoc (historyRow i (Nat.le_of_succ_le hi) (a.previous x)) + (a.menuAt hF menu k (i + 1) hi x).2 + +theorem historyRow_last {i : ℕ} (hi : i ≤ a.waves) (x : B (a.widthAt e k i)) : + a.historyRow hF menu k i hi x (Fin.last i) = (a.menuAt hF menu k i hi x).2 := by + cases i with + | zero => rfl + | succ i => exact Fin.snoc_last .. + +theorem historyRow_path (p : (a.port e).obj) {i : ℕ} (hi : i ≤ a.waves) + (c : Fin i → (a.selectors k).obj) (v : B a.m × B a.h) (j : Fin (i + 1)) : + a.historyRow hF menu k i hi ((a.path p i c v.1).2 v.2) j = + (a.menuAt hF menu k j.val ((Nat.le_of_lt_succ j.isLt).trans hi) + ((a.path p j.val (c ∘ Fin.castLE (Nat.le_of_lt_succ j.isLt)) v.1).2 v.2)).2 := by + induction i with + | zero => rw [Fin.eq_zero j]; rfl + | succ i ih => + induction j using Fin.lastCases with + | last => exact a.historyRow_last hF menu k hi _ + | cast j => + simp only [historyRow, Fin.snoc_castSucc, path, previous_update] + exact ih (Nat.le_of_succ_le hi) (Fin.init c) j + +/-- Defined on every possible label, independently of branch membership. -/ +def credits (g ℓ D : ℕ) (raw : B (a.widthAt e k a.waves)) : Geometry.Credits g ℓ D a.waves := + let row := a.historyRow hF menu k a.waves le_rfl raw + Geometry.Credits.issue g ℓ D a.waves (a.chart * a.H) + (fun i => Metadata.energyCre (row i) a.chart a.H a.g) + (fun i => Metadata.timeCre (row i) a.chart a.H a.U) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Design +end + +/- # Binary inputs for a local verifier -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry +open Coloring + +/-- The least binary width whose power of two reaches the stated size. -/ +abbrev indexWidth (X : Type) := Nat.clog 2 (Nat.card X) + +/-- Embeds `X` into `(Fin (indexWidth X) → Bool)`. -/ +def labelCode (X : Type) [Fintype X] : X ↪ (Fin (indexWidth X) → Bool) := + Layout.binaryCode X _ (by + rw [← Nat.card_eq_fintype_card] + exact Nat.le_pow_clog (by decide) _) + +/-- Eligibility bits, a central record and one tag per sampled cell. -/ +abbrev Pin (k : ℕ) (A I W : Type) := B k ⊕ Fin (indexWidth A) ⊕ (I × W) + +variable {k : ℕ} {A I T W : Type} [Fintype A] (tcode : T ↪ (W → Bool)) + +/-- In the case `.inl i`, this construction gives `e i`. -/ +def encode (e : B k → Bool) (a : A) (t : I → T) : Pin k A I W → Bool + | .inl i => e i + | .inr (.inl j) => labelCode A a j + | .inr (.inr (i, j)) => tcode (t i) j + +/-- A truth table on the encoded inputs has cost bounded in terms of the pin count alone. -/ +theorem exists_formula [Fintype I] [Fintype W] (pred : (B k → Bool) → A → (I → T) → Prop) + {n : ℕ} (hn : Fintype.card (Pin k A I W) ≤ n) : + ∃ p : BitFormula (Pin k A I W), p.cost ≤ (3 * n + 2) * 2 ^ n + 1 ∧ + ∀ e a t, p.eval (encode tcode e a t) = true ↔ pred e a t := by + classical + obtain ⟨p, hp, hc⟩ := bool_formula fun x => + decide (∃ e a t, encode tcode e a t = x ∧ pred e a t) + refine ⟨p, hc.trans (by gcongr), fun e a t => ?_⟩ + simp only [hp, decide_eq_true_eq] + refine ⟨?_, fun h => ⟨e, a, t, rfl, h⟩⟩ + rintro ⟨e', a', t', h, h'⟩ + have he : e' = e := funext fun i => congrFun h (.inl i) + have ha : a' = a := (labelCode A).injective (funext fun j => congrFun h (.inr (.inl j))) + have ht : t' = t := funext fun i => + tcode.injective (funext fun j => congrFun h (.inr (.inr (i, j)))) + simpa only [he, ha, ht] using h' + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Geometry +variable {F Z : Type} (S : Scheme F) + {d e M r t q D k n u j z : ℕ} (U : Printer F Z (B S.k) S.m d S.h e M r t q D k n u j z) + +/-- Indexes the blue pins by the coordinates of `B U.childBits × slots (word (U.planBits S))`. -/ +abbrev bluePins := B U.childBits × slots (word (U.planBits S)) + +/-- Store each child's outline verbatim as its own address bits. -/ +def blueCode : U.Blueprint S ↪ (U.bluePins S → Bool) where + toFun a i := (Format.addr (U.planBits S)).code (indexCode (U.Outline S) (a i.1)) i.2 + inj' _ _ h := funext fun c => (indexCode (U.Outline S)).injective + ((Format.addr (U.planBits S)).code.injective (funext fun i => congrFun h (c, i))) + +variable (g σ p : ℕ) + +/-- Indexes the tag pins by the coordinates of `U.bluePins S ⊕ Fin (indexWidth (Credits g σ D +p))`. -/ +abbrev tagPins := U.bluePins S ⊕ Fin (indexWidth (Credits g σ D p)) + +/-- The quantity computed by `2 ^ U.childBits * U.planBits S + indexWidth (Credits g σ D p)`. -/ +def tagWidth := 2 ^ U.childBits * U.planBits S + indexWidth (Credits g σ D p) + +theorem tagSize : Fintype.card (U.tagPins S g σ p) = U.tagWidth S g σ p := by + simp only [tagPins, bluePins, tagWidth, B, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, + card_slots, wd_word] + +/-- Chooses the operation for the left or right summand. -/ +def tagCode : U.Tag S g σ p ↪ (U.tagPins S g σ p → Bool) where + toFun a := Sum.elim (U.blueCode S a.1) (labelCode _ a.2) + inj' _ _ h := Prod.ext + ((U.blueCode S).injective (funext fun i => congrFun h (.inl i))) + ((labelCode _).injective (funext fun i => congrFun h (.inr i))) + +theorem tagCode_blue (a : U.Tag S g σ p) : + U.tagCode S g σ p a ∘ Sum.inl = U.blueCode S a.1 := rfl + +/-- Reject bit strings that are not the encoding of a tag. -/ +theorem valid_formula : + let b := U.tagWidth S g σ p + ∃ f : BitFormula (U.tagPins S g σ p), f.cost ≤ (3 * b + 2) * 2 ^ b + 1 ∧ + ∀ t, f.eval t = true ↔ ∃ u, U.tagCode S g σ p u = t := by + classical + obtain ⟨f, hf, hc⟩ := bool_formula fun t => decide (∃ u, U.tagCode S g σ p u = t) + rw [tagSize] at hc + exact ⟨f, hc, fun t => by simp only [hf, decide_eq_true_eq]⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- Test a padded proposal using only the occupied cells. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Geometry +variable {F Z V : Type} [Field F] [Finite Z] (S : Scheme F) + {d e M r t q D k n u j z : ℕ} (U : Printer F Z (B S.k) S.m d S.h e M r t q D k n u j z) + (loc : V ↪ B S.m × B S.h) (y : U.template.format.obj) + +open scoped Classical in +/-- Indexes the contacts by the coordinates of `B U.childBits × B U.template.scheme.d`. -/ +abbrev Contacts := B U.childBits × B U.template.scheme.d + +open scoped Classical in +/-- The parent of the child reached by this navigation column. -/ +def targetCell (v : V) (i : U.Contacts S) : B S.m × B S.h := + ((U.split (U.template.nav y (U.split.symm ((loc v).1, i.1)) i.2)).1, (loc v).2) + +open scoped Classical in +/-- The links at of type `Prop`, constructed using `U.split.symm ((loc v).1, c)`. -/ +def linksAt (v : V) (a : U.Blueprint S) (next : U.Contacts S → U.Blueprint S) : Prop := + ∀ c j, + let v' := U.split.symm ((loc v).1, c) + let w := U.template.nav y v' j + Geometry.Outline.Contact (a c) (next (c, j) (U.split w).2) j (U.template.flags y v' j).1 + (fun k => decide (U.template.nav y w k = v')) + +open scoped Classical in +/-- A local register and a reciprocal contact test. -/ +def validAt (v : V) (eligible : B S.k → Bool) (a : U.Blueprint S) + (next : U.Contacts S → U.Blueprint S) : Prop := + Geometry.Blueprint.Register a U.outer eligible (U.childLive S y (loc v).1) (U.childFixed S y (loc + v).1) ∧ + U.linksAt S loc y v a next + +open scoped Classical in +/-- The condition `∀ i b, (i, b) ∉ Set.range loc → ∀ l, held S ((x i).2 b) l = false` on the +specified data. -/ +def vacantHeld (x : S.format.obj) : Prop := + ∀ i b, (i, b) ∉ Set.range loc → ∀ l, held S ((x i).2 b) l = false + +open scoped Classical in +theorem valid_complete (x : S.format.obj) (hv : vacantHeld S loc x) (a : V → U.Blueprint S) : + U.Valid S x y (U.complete S loc a) ↔ ∀ v, + U.validAt S loc y v (held S ((x (loc v).1).2 (loc v).2)) (a v) + (fun i => let w := U.targetCell S loc y v i; U.complete S loc a w.1 w.2) := by + let A := U.complete S loc a + have here (v : V) (c : B U.childBits) : + U.localAt S A (U.split.symm ((loc v).1, c), (loc v).2, 0) = a v c := by + rw [localAt, Equiv.apply_symm_apply] + exact congrFun (U.complete_here S loc a v) c + constructor + · intro h v + have hr := h.1 (loc v).1 (loc v).2 + rw [U.complete_here] at hr + refine ⟨hr, fun c i => ?_⟩ + have hj := h.2 (U.split.symm ((loc v).1, c)) (loc v).2 i + rw [← here v c] + exact hj + · intro h + constructor + · intro i b + by_cases he : (i, b) ∈ Set.range loc + · obtain ⟨v, he⟩ := he + have hr := (h v).1 + rw [← U.complete_here S loc a v, he] at hr + exact hr + rw [U.complete_vacant S loc _ he] + constructor <;> simp [Geometry.Outline.empty, hv i b he] + · intro p b i + by_cases he : ((U.split p).1, b) ∈ Set.range loc + · obtain ⟨v, he⟩ := he + let c := (U.split p).2 + have hj := (h v).2 c i + rw [← here v c] at hj + simp only [targetCell, he, c, Prod.mk.eta, Equiv.symm_apply_apply] at hj + exact hj + change Geometry.Outline.Contact (U.complete S loc a (U.split p).1 b (U.split p).2) _ _ _ _ + rw [U.complete_vacant S loc _ he] + simp [Geometry.Outline.Contact, Geometry.Outline.empty] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- The checks at a cell use bounded initial caps, eligibility bits, +and tags read at a fixed set of addresses. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry.Credits +open Rounds.Input +variable {g σ D p : ℕ} + +/-- Indexes the caps by the coordinates of `Fin (energyLimit g D p + 1) × Fin (timeLimit g σ D + +1)`. -/ +abbrev Caps (g σ D p : ℕ) := Fin (energyLimit g D p + 1) × Fin (timeLimit g σ D + 1) + +/-- The value specified by `(⟨min E _, Nat.lt_succ_of_le (min_le_right E _)⟩, ⟨min H _, +Nat.lt_succ_of_le (min_le_right H _)⟩)`. -/ +def caps (g σ D p E H : ℕ) : Caps g σ D p := + (⟨min E _, Nat.lt_succ_of_le (min_le_right E _)⟩, + ⟨min H _, Nat.lt_succ_of_le (min_le_right H _)⟩) + +theorem le_caps (z : Credits g σ D p) (E H : ℕ) : + (z.power 0 ≤ (caps g σ D p E H).1.val ∧ z.time 0 ≤ (caps g σ D p E H).2.val) ↔ + z.power 0 ≤ E ∧ z.time 0 ≤ H := by + have he := Nat.le_of_lt_succ (z 0).1.isLt + have ht := Nat.le_of_lt_succ (z 0).2.isLt + simp only [caps, power, time, le_min_iff, he, ht, and_true] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Geometry.Credits + +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Geometry Surface.Local Rounds +variable {F Z N A : Type} [Field F] [Finite Z] (S : Scheme F) + {d e M r t q D k n u j z g σ : ℕ} (U : Printer F Z (B S.k) S.m d S.h e M r t q D k n u j z) + {cfg : Design} {x₀ y₀ : Wire} (w : Scenario F N A cfg x₀ y₀) + (loc : w.V ↪ B S.m × B S.h) (y : U.template.format.obj) + +open scoped Classical in +/-- Indexes the queries by the coordinates of `Unit ⊕ U.Contacts S ⊕ w.Ball v`. -/ +abbrev Queries (v : w.V) := Unit ⊕ U.Contacts S ⊕ w.Ball v + +open scoped Classical in +/-- No tag is requested when the target cell is vacant. -/ +def query (v : w.V) : U.Queries S w v → Option w.V + | .inl _ => some v + | .inr (.inl i) => Function.extend loc some (fun _ => none) (U.targetCell S loc y v i) + | .inr (.inr i) => some i.val + +open scoped Classical in +/-- The indexed operation `(fun _ => Outline.empty, fun _ => (0, 0))`. -/ +abbrev blankTag (g σ p : ℕ) : U.Tag S g σ p := (fun _ => Outline.empty, fun _ => (0, 0)) + +open scoped Classical in +/-- The value specified by `(U.query S w loc y v i).elim (U.blankTag S g σ cfg.waves) a`. -/ +def samples (a : w.V → U.Tag S g σ cfg.waves) (v : w.V) (i : U.Queries S w v) := + (U.query S w loc y v i).elim (U.blankTag S g σ cfg.waves) a + +open scoped Classical in +private theorem sample_next (a : w.V → U.Tag S g σ cfg.waves) (v : w.V) (i : U.Contacts S) : + (U.samples S w loc y a v (.inr (.inl i))).1 = + let x := U.targetCell S loc y v i + U.complete S loc (fun j => (a j).1) x.1 x.2 := by + simp only [samples, query] + generalize U.targetCell S loc y v i = x + by_cases hx : x ∈ Set.range loc + · obtain ⟨j, rfl⟩ := hx + rw [loc.injective.extend_apply, U.complete_here] + rfl + · rw [Function.extend_apply' _ _ _ hx, U.complete_vacant S loc _ hx] + rfl + +open scoped Classical in +/-- The examine of type `Prop` for the given inputs. -/ +def examine (K : ℕ) (v : w.V) (eligible : B S.k → Bool) (c : Credits.Caps g σ D cfg.waves) + (a : U.Queries S w v → U.Tag S g σ cfg.waves) : Prop := + U.validAt S loc y v eligible (a (.inl ())).1 (fun i => (a (.inr (.inl i))).1) ∧ + w.checkAt v (fun i => (a (.inr (.inr i))).2) c.1.val c.2.val ∧ + Quota (Input.terminalExponent g σ) n K U.fixedChild (a (.inl ())).1 (a (.inl ())).2 + +open scoped Classical in +theorem passes_iff (K : ℕ) (E H : w.V → ℕ) (x : S.format.obj) (hv : vacantHeld S loc x) + (a : w.V → U.Tag S g σ cfg.waves) : + U.passes S loc w.loc E H K x y a ↔ ∀ v, U.examine S w loc y K v + (held S ((x (loc v).1).2 (loc v).2)) (Credits.caps g σ D cfg.waves (E v) (H v)) + (U.samples S w loc y a v) := by + unfold passes + rw [U.valid_complete S loc y x hv, w.check_iff] + simp only [examine, sample_next] + simp only [samples, query, Option.elim_some, Scenario.checkAt, Credits.localCheck, + Credits.le_caps, + forall_and] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- +# Computing the initial caps from bounded seat data + +A seat provides its number of packets and one immobility bit. +Absent seats contribute neither packets nor collectors. The +arithmetic defining the caps is tabulated on this finite alphabet. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +open Sphere Geometry SphereScale Finset + +open scoped Classical in +/-- Indexes the cap seat by the coordinates of `Fin (probes ℓ D + 1) × Bool`. -/ +abbrev CapSeat (ℓ D : ℕ) := Fin (probes ℓ D + 1) × Bool +open scoped Classical in +/-- The quantity computed by `Fin (100 * D) → CapSeat ℓ D`. -/ +abbrev CapData (ℓ D : ℕ) := Fin (100 * D) → CapSeat ℓ D +open scoped Classical in +/-- Indexes the cap pins by the coordinates of `Fin (100 * D) × Fin (indexWidth (CapSeat ℓ D))`. -/ +abbrev CapPins (ℓ D : ℕ) := Fin (100 * D) × Fin (indexWidth (CapSeat ℓ D)) + +open scoped Classical in +/-- Embeds `CapData ℓ D` into `(CapPins ℓ D → Bool) where toFun s i`. -/ +def capCode {ℓ D : ℕ} : CapData ℓ D ↪ (CapPins ℓ D → Bool) where + toFun s i := labelCode _ (s i.1) i.2 + inj' _ _ h := funext fun i => (labelCode _).injective (funext fun j => congrFun h (i, j)) + +open scoped Classical in +/-- Returns `s ⟨i.val, h⟩` when `h : i.val < n` holds, and `z` otherwise. -/ +def pad {α : Type} {n k : ℕ} (z : α) (s : Fin n → α) (i : Fin k) := + if h : i.val < n then s ⟨i.val, h⟩ else z + +open scoped Classical in +private theorem sum_pad {α : Type} {n k : ℕ} (h : n ≤ k) (z : α) (s : Fin n → α) + (f : α → ℕ) (hf : f z = 0) : ∑ i : Fin k, f (pad z s i) = ∑ i, f (s i) := by + obtain ⟨l, rfl⟩ := Nat.exists_eq_add_of_le h + rw [Fin.sum_univ_add] + simp [pad, hf] + +variable {F : Type} {x y : Wire} {h D T b d g ℓ m : ℕ} {W : ℝ} + (P : Input F x y h D T (d * b) g W) (sc : Scales g ℓ D T m b d) + +open scoped Classical in +/-- The seat data of type `CapSeat ℓ D`, constructed using `P.grid.label v i`. -/ +def seatData (v : P.Occupied) (i : Fin (P.grid.stations v).card) : CapSeat ℓ D := + let u := P.grid.label v i + (⟨(P.grid.uses u).card, Nat.lt_succ_of_le (P.maxPackets sc u)⟩, decide (¬ P.mobile u)) + +open scoped Classical in +/-- The value specified by `pad (0, false) (P.seatData sc v)`. -/ +def capData (v : P.Occupied) : CapData ℓ D := pad (0, false) (P.seatData sc v) + +open scoped Classical in +/-- The cap energy of type `ℕ`, constructed using `SphereScale.energy ℓ D (d * b)`. -/ +def capEnergy (g m b d waves : ℕ) (z : CapData ℓ D) : ℕ := + let H := SphereScale.energy ℓ D (d * b) + let packets := ∑ i, (d * b) * (8 * (z i).1.val ^ 2) + clip waves (m * H) ((1 + 4 * g) * (reserve D b d (probes ℓ D) m H + m * packets)) + +open scoped Classical in +/-- The quantity computed by `D ^ 5 * (1 + ∑ i, if (z i).2 then 1 else 0) + budget g * D ^ 2`. -/ +def capTime (g : ℕ) (z : CapData ℓ D) : ℕ := + D ^ 5 * (1 + ∑ i, if (z i).2 then 1 else 0) + budget g * D ^ 2 + +open scoped Classical in +theorem cap_energy (v : P.Occupied) (waves : ℕ) : + capEnergy g m b d waves (P.capData sc v) = P.initialEnergyTokens ℓ m waves v := by + let f (s : CapSeat ℓ D) := (d * b) * (8 * s.1.val ^ 2) + have he : (∑ i, f (P.capData sc v i)) = + ∑ i : Fin (P.grid.stations v).card, (d * b) * (8 * (P.grid.width v (Fin.castAdd _ i)) ^ 2) + := by + unfold capData + rw [sum_pad (P.stations_bound v) _ _ _ (by simp [f])] + simp only [f, seatData, Grid.width, Grid.mark_label] + exact congrArg (fun e => clip waves (m * SphereScale.energy ℓ D (d * b)) + ((1 + 4 * g) * (reserve D b d (probes ℓ D) m (SphereScale.energy ℓ D (d * b)) + m * e))) he + +open scoped Classical in +theorem cap_time (v : P.Occupied) : + capTime g (P.capData sc v) = P.initialTimeTokens v := by + let f (s : CapSeat ℓ D) := if s.2 then 1 else 0 + have he : (∑ i, f (P.capData sc v i)) = ∑ u ∈ P.grid.stations v, if ¬ P.mobile u then 1 else 0 + := by + unfold capData + rw [sum_pad (P.stations_bound v) _ _ _ (by simp [f]), ← sum_coe_sort (P.grid.stations v), + ← (Grid.number P.grid.stationRank (P.grid.stations v)).sum_comp] + apply sum_congr rfl + intro i _ + change (if decide (¬P.mobile (P.grid.label v i)) then 1 else 0) = + (if ¬P.mobile (P.grid.label v i) then 1 else 0) + by_cases hi : P.mobile (P.grid.label v i) <;> simp [hi] + exact congrArg (fun t => D ^ 5 * (1 + t) + budget g * D ^ 2) he + +open scoped Classical in +/-- The bound obtained by adding the component charges `indexWidth (Credits.Caps g ℓ D waves) * +((3 * Fintype.card (CapPins ℓ D) + 2) * Fintype.card (CapData ℓ D) + 1)`. -/ +def capCost (g ℓ D waves : ℕ) : ℕ := + indexWidth (Credits.Caps g ℓ D waves) * + ((3 * Fintype.card (CapPins ℓ D) + 2) * Fintype.card (CapData ℓ D) + 1) + +open scoped Classical in +/-- The same formulas work for all fields and cells. Only the +bounded seat and credit alphabets enter their total size. -/ +theorem cap_formulas (g ℓ D m b d waves : ℕ) : + ∃ f : Fin (indexWidth (Credits.Caps g ℓ D waves)) → BitFormula (CapPins ℓ D), + (∑ i, (f i).cost) ≤ capCost g ℓ D waves ∧ + ∀ {F : Type} {x y : Wire} {h T : ℕ} {W : ℝ} + (P : Input F x y h D T (d * b) g W) (sc : Scales g ℓ D T m b d) (v : P.Occupied) i, + (f i).eval (capCode (P.capData sc v)) = labelCode _ (Credits.caps g ℓ D waves + (P.initialEnergyTokens ℓ m waves v) (P.initialTimeTokens v)) i := by + let out (z : CapData ℓ D) := labelCode _ (Credits.caps g ℓ D waves (capEnergy g m b d waves z) + (capTime g z)) + choose f hf hc using fun i => finite_formula capCode (fun z => out z i) + refine ⟨f, ?_, fun P sc v i => ?_⟩ + · simpa only [capCost, sum_const, card_fin, Nat.nsmul_eq_mul] using sum_le_sum (s + := univ) (fun i _ => hc i) + · rw [hf] + unfold out + rw [cap_energy, cap_time] + +open scoped Classical in +theorem local_caps (waves : ℕ) : + ∃ f : Fin (indexWidth (Credits.Caps g ℓ D waves)) → BitFormula (CapPins ℓ D), + (∑ i, (f i).cost) ≤ capCost g ℓ D waves ∧ + ∀ (v : P.Occupied) i, (f i).eval (capCode (P.capData sc v)) = + labelCode _ (Credits.caps g ℓ D waves (P.initialEnergyTokens ℓ m waves v) + (P.initialTimeTokens v)) i := by + obtain ⟨f, hf, h⟩ := cap_formulas g ℓ D m b d waves + exact ⟨f, hf, h P sc⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.Input +end + +/- # Boolean checks with one bounded formula per occupied cell -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring Geometry Surface.Local +variable {F Z N A : Type} [Field F] [Finite Z] (S : Scheme F) + {d e M r t q D k n u j z : ℕ} (U : Printer F Z (B S.k) S.m d S.h e M r t q D k n u j z) + +open scoped Classical in +/-- The check width used in the `Printer` construction. -/ +def checkWidth (g σ : ℕ) (cfg : Design) := + 2 ^ S.k + indexWidth (Credits.Caps g σ D cfg.waves) + + (1 + 2 ^ U.childBits * 2 ^ U.template.scheme.d + 2 ^ ((cfg.d + 1) * (cfg.U + + 1))) * U.tagWidth S g σ cfg.waves + +variable {cfg : Design} {x₀ y₀ : Wire} (w : Scenario F N A cfg x₀ y₀) (g σ : ℕ) + +open scoped Classical in +/-- The value specified by `Geometry.Pin S.k (Credits.Caps g σ D cfg.waves) (U.Queries S w v) +(U.tagPins S g σ cfg.waves)`. -/ +abbrev checkPins (v : w.V) := + Geometry.Pin S.k (Credits.Caps g σ D cfg.waves) (U.Queries S w v) (U.tagPins S g σ cfg.waves) + +open scoped Classical in +theorem check_size (v : w.V) : Fintype.card (U.checkPins S w g σ v) ≤ U.checkWidth S g σ cfg := by + rw [checkWidth, ← U.tagSize] + simp only [checkPins, Geometry.Pin, Queries, Contacts, B, Fintype.card_sum, Fintype.card_prod, + Fintype.card_unit, Fintype.card_fin, add_assoc] + gcongr + exact w.card_ball v + +variable {g σ} (loc : w.V ↪ B S.m × B S.h) (y : U.template.format.obj) + +open scoped Classical in +/-- The check inputs of type `U.checkPins S w g σ v → Bool` for the given inputs. -/ +def checkInputs (E H : w.V → ℕ) (x : S.format.obj) (a : w.V → U.Tag S g σ cfg.waves) + (v : w.V) : U.checkPins S w g σ v → Bool := + Geometry.encode (U.tagCode S g σ cfg.waves) (held S ((x (loc v).1).2 (loc v).2)) (Credits.caps g + σ D cfg.waves (E v) (H v)) + (U.samples S w loc y a v) + +open scoped Classical in +/-- The formulas are fixed before seeing the eligibility bits, the initial +caps, or the proposed blueprints and credits. -/ +theorem passes_binary (K : ℕ) : + let b := U.checkWidth S g σ cfg + ∃ f : ∀ v, BitFormula (U.checkPins S w g σ v), + (∀ v, (f v).cost ≤ (3 * b + 2) * 2 ^ b + 1) ∧ + ∀ (E H : w.V → ℕ) (x : S.format.obj), vacantHeld S loc x → ∀ a : w.V → U.Tag S g σ cfg.waves, + U.passes S loc w.loc E H K x y a ↔ ∀ v, (f v).eval (U.checkInputs S w loc y E H x a v) + = true := by + choose f hf he using fun v => Geometry.exists_formula (U.tagCode S g σ cfg.waves) + (U.examine S w loc y K v) (U.check_size S w g σ v) + refine ⟨f, hf, fun E H x hv a => ?_⟩ + rw [U.passes_iff S w loc y K E H x hv] + exact forall_congr' fun v => (he v _ _ _).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end + +/- The printer's geometry checks depend only on the common navigation and status. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +open Assembly Coloring +variable {F Z V : Type} [Field F] [Finite Z] (S : Scheme F) + {d e M r t q D k n u j z : ℕ} (U : Printer F Z (B S.k) S.m d S.h e M r t q D k n u j z) + +/-- Changing block labels or printer selectors preserves the geometry checks. -/ +theorem passes_advance [Fintype V] (loc : V ↪ B S.m × B S.h) {g σ p : ℕ} + (part : Fin p → V → V) (E H : V → ℕ) (K : ℕ) (x : S.format.obj) + (a : V → U.Tag S g σ p) {data data' : U.rows.obj} + (status : (Children.Header S.m d).obj) (c c' : U.selectors.obj) + (h : ∀ i, (data i).1 = (data' i).1) : + U.passes S loc part E H K x (U.advance data status c) a ↔ + U.passes S loc part E H K x (U.advance data' status c') a := by + have he : Children.tape (U.update data status c) = Children.tape (U.update data' status c') := + Prod.ext (funext h) rfl + unfold advance Children.write + erw [he] + rfl + +/-- Each printed neighbor lies over the same parent or one of its neighbors. -/ +theorem nav_reach (data : U.rows.obj) (status : (Children.Header S.m d).obj) + (c : U.selectors.obj) (v : B U.template.scheme.m) (i : B U.template.scheme.d) : + Neighborhood.Reach (fun j => (data j).1) 1 (U.split v).1 + (U.split (U.template.nav (U.advance data status c) v i)).1 := by + let r := Children.entries U.slot U.dyadic U.large U.chunks U.degree + (Children.tape (U.update data status c)) + let p := ((r.2 v).2 i).2 + change Neighborhood.Reach _ 1 _ (U.split (U.split.symm + (History.Reset.Child.follow r.1 (U.split v).1 p.1, p.2))).1 + rw [Equiv.apply_symm_apply] + unfold History.Reset.Child.follow + split + · exact Neighborhood.mem.mp ⟨_, rfl⟩ + · exact Neighborhood.Reach.refl .. + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Print.Printer +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Waves/Price.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Waves/Price.lean new file mode 100644 index 0000000000..28c17e01a6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Waves/Price.lean @@ -0,0 +1,919 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Geometry.Boundary +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Scenario +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Proof.Initial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.AppendAddress +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rounds.Contraction.Access +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BatchDescent.Trail.Compact + +/-! +# A fixed partition for an entire wave + +Enlarge each radius by one to include both ends of every incident +seam. The coloring still separates the enlarged neighborhoods. +Vertices outside them have singleton parts. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Scenario +open Finset +variable {F N A : Type} [Field F] {a : Design} {x y : Wire} + (w : Scenario F N A a x y) (j : Fin a.waves) + +open scoped Classical in +/-- Requires `w.π.mark u = (finProdFinEquiv.symm j).1 ∧ w.atlas.near (a.U + 1) u v`. -/ +def leader (v u : w.V) : Prop := + w.π.mark u = (finProdFinEquiv.symm j).1 ∧ w.atlas.near (a.U + 1) u v + +open scoped Classical in +/-- Returns `h.choose` when `h : ∃ u, w.leader j v u` holds, and `v` otherwise. -/ +def loc (v : w.V) := if h : ∃ u, w.leader j v u then h.choose else v + +open scoped Classical in +theorem loc_of_leader {v u : w.V} (h : w.leader j v u) : w.loc j v = u := by + have he : ∃ u, w.leader j v u := ⟨u, h⟩ + rw [loc, dite_eq_left he] + exact w.π.injective_at (by omega) he.choose_spec.2.symm h.2.symm (he.choose_spec.1.trans h.1.symm) + +open scoped Classical in +theorem loc_near (v : w.V) : w.atlas.near (a.U + 1) (w.loc j v) v := by + unfold loc + split + · rename_i h + exact h.choose_spec.2 + · exact .refl _ _ _ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Scenario +end + +/- # Checking a wave certificate in bounded neighborhoods -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere +open Surface.Local Finset Coloring + +namespace Geometry.Credits + +variable {I : Type} [Fintype I] {g ℓ D : ℕ} {a : Design} + +open scoped Classical in +/-- At a root, check the whole neighborhood. A nonroot belongs +to another region unless its neighborhood contains no root. -/ +def part (color : I → Fin a.R) (center : I) (j : Fin a.waves) : Finset I := + univ.filter fun i => color center = (finProdFinEquiv.symm j).1 ∨ + (i = center ∧ ∀ t, color t ≠ (finProdFinEquiv.symm j).1) + +open scoped Classical in +/-- The check uses only colors, the central caps and the +certificates at the occupied addresses in the neighborhood. -/ +def localCheck (color : I → Fin a.R) (center : I) + (z : I → Credits g ℓ D a.waves) (E M : ℕ) : Prop := + ((z center).power 0 ≤ E ∧ (z center).time 0 ≤ M) ∧ + ∀ j : Fin a.waves, + (∑ i ∈ part color center j, (z i).power j.succ) ≤ ∑ i ∈ part color center j, + ((z i).power j.castSucc + 1) ∧ + (∑ i ∈ part color center j, (z i).time j.succ) ≤ ∑ i ∈ part color center j, + (z i).time j.castSucc + +end Geometry.Credits + +namespace Surface.Local.Scenario +open Geometry + +variable {F N A : Type} [Field F] {a : Design} {x y : Wire} + (w : Scenario F N A a x y) (v : w.V) {g ℓ D : ℕ} + +open scoped Classical in +/-- The quantity computed by `↥(w.atlas.ball (a.U + 1) v)`. -/ +abbrev Ball := ↥(w.atlas.ball (a.U + 1) v) + +open scoped Classical in +/-- Uses `⟨v, mem_filter_univ _ |>.mpr (.refl _ _ _)⟩` as the representation. -/ +def central : w.Ball v := ⟨v, mem_filter_univ _ |>.mpr (.refl _ _ _)⟩ + +open scoped Classical in +theorem card_ball : Fintype.card (w.Ball v) ≤ 2 ^ ((a.d + 1) * (a.U + 1)) := by + have h (t : w.Ball v) := (w.atlas.around_iff _ _ _).mpr (mem_filter.mp t.property).2 + choose f hf using h + have hi : Function.Injective f := by + intro i j he + exact Subtype.ext (w.atlas.coord.injective ((hf i).symm.trans (he ▸ hf j))) + simpa [B] using Fintype.card_le_of_injective f hi + +open scoped Classical in +/-- The indexed operation `Credits.localCheck (a := a) (fun t => w.π.mark t.val) (w.central v) z +E M`. -/ +def checkAt (z : w.Ball v → Credits g ℓ D a.waves) (E M : ℕ) := + Credits.localCheck (a := a) (fun t => w.π.mark t.val) (w.central v) z E M + +open scoped Classical in +private theorem part_eq (j : Fin a.waves) : + (Credits.part (a := a) (fun t : w.Ball v => w.π.mark t.val) (w.central v) j).image Subtype.val = + region (w.loc j) v := by + let color := (finProdFinEquiv.symm j).1 + have none : (∀ t : w.Ball v, w.π.mark t.val ≠ color) ↔ ¬ ∃ u, w.leader j v u := by + constructor + · rintro h ⟨u, hu, he⟩ + exact h ⟨u, mem_filter.mpr ⟨mem_univ _, he.symm⟩⟩ hu + · exact fun h t ht => h ⟨t.val, ht, (mem_filter.mp t.property).2.symm⟩ + ext u + simp only [mem_image, Credits.part, region, mem_filter_univ] + constructor + · rintro ⟨t, h|⟨rfl, h⟩, rfl⟩ + · exact w.loc_of_leader j ⟨h, (mem_filter.mp t.property).2⟩ + · exact dite_eq_right (none.mp h) + · intro he + have hnear := w.loc_near j u + rw [he] at hnear + let t : w.Ball v := ⟨u, mem_filter.mpr ⟨mem_univ _, hnear⟩⟩ + refine ⟨t, ?_, rfl⟩ + by_cases h : ∃ z, w.leader j u z + · obtain ⟨z, hz⟩ := h + have hz' : z = v := (w.loc_of_leader j hz).symm.trans he + left + exact hz' ▸ hz.1 + · have hu : u = v := by simpa [loc, h] using he + right + exact ⟨Subtype.ext hu, none.mpr (hu ▸ h)⟩ + +open scoped Classical in +theorem check_iff (z : w.V → Credits g ℓ D a.waves) (E M : w.V → ℕ) : + Credits.Check w.loc z E M ↔ ∀ v, w.checkAt v (fun t => z t.val) (E v) (M v) := by + have he (v : w.V) (j : Fin a.waves) (f : w.V → ℕ) : + (∑ t ∈ region (w.loc j) v, f t) = + ∑ t ∈ Credits.part (a := a) (fun t : w.Ball v => w.π.mark t.val) (w.central v) j, f t.val + := by + rw [← part_eq, sum_image Subtype.val_injective.injOn] + constructor + · intro h v + refine ⟨h.initial v, fun j => ?_⟩ + have hp := h.power j v + have ht := h.time j v + simp only [he, add_zero] at hp ht + exact ⟨hp, ht⟩ + · intro h + refine ⟨fun v => (h v).1, fun j v => ?_, fun j v => ?_⟩ + · simp only [he]; exact ((h v).2 j).1 + · simp only [he, add_zero]; exact ((h v).2 j).2 + +end Surface.Local.Scenario +end MatrixMultiplicationAllFields.MatrixExponent.Sphere +end + +/- Recover the energy and time credits directly from a printed row. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Finset + +variable {F K N J L V E T X : Type} {r t q : ℕ} + +open scoped Classical in +/-- Transforms the indexed data by `(b.rows.map fun u => f u.role (P * u.a + u.b)).sum`. -/ +def Body.tally (b : Body F r t q K N) (P : ℕ) (f : Role → ℕ → ℕ) := + (b.rows.map fun u => f u.role (P * u.a + u.b)).sum + +open scoped Classical in +/-- The quantity computed by `(1 + 2 * g) * b.tally P (Role.mobile (2 * P * H)) + b.tally P +Role.collected`. -/ +def Body.energyCre (b : Body F r t q K N) (P H g : ℕ) := + (1 + 2 * g) * b.tally P (Role.mobile (2 * P * H)) + b.tally P Role.collected + +open scoped Classical in +/-- The indexed operation `U * b.tally P Stage.collectorUnit + b.tally P (fun c _ => c.clock) + +(b.ports.map fun e => P * e.2.2 / (2 * P * H)).sum`. -/ +def Body.timeCre (b : Body F r t q K N) (P H U : ℕ) := + U * b.tally P Stage.collectorUnit + b.tally P (fun c _ => c.clock) + + (b.ports.map fun e => P * e.2.2 / (2 * P * H)).sum + +namespace Matches +variable {R : Reference J L N V E T X} {β : V ⊕ ℕ → K} + {s : Stage F r t T V E X} {G : Record F r t V E K N} (h : Matches R.world β s G) +include h + +open scoped Classical in +theorem tally (tag : E → Fin q × Fin q) (P : ℕ) (f : Role → ℕ → ℕ) (v : V) : + (G.body tag v).tally P f = s.tally P f v := by + symm + apply congrArg List.sum + exact image_match (h.rows v) fun _ _ ha => by simp only [energyOf, ha.left, ha.right, ha.role] + +variable [Fintype V] + +open scoped Classical in +theorem energyCre (tag : E → Fin q × Fin q) (P H g : ℕ) (v : V) : + (G.body tag v).energyCre P H g = s.energyCre P H g v := by + rw [Body.energyCre, h.tally, h.tally] + rfl + +open scoped Classical in +theorem timeCre {src dst : E → V} {g : ℕ} (hl : s.Layout src dst g) + (tag : E → Fin q × Fin q) (P H U : ℕ) (v : V) : + (G.body tag v).timeCre P H U = s.timeCre P H U v := by + rw [Body.timeCre, Stage.timeCre, h.tally, h.tally] + have hp : (s.scene.cell v).ports = G.ports v := by + exact (h.ports v).trans (List.map_id _) + have he : s.scene.level = G.level := funext h.level + have hn := hl.unique v + unfold Stage.ports at hn + rw [Stage.edges, List.sum_toFinset _ hn, hp] + simp only [Record.body, Stage.ledger, List.map_map, Function.comp_def, he] + +end Matches + +variable {R Q U M : ℕ} + +open scoped Classical in +/-- The indexed operation `b.elim 0 (fun z => z.2.2.2.toBody.energyCre P H g)`. -/ +def Metadata.energyCre (b : Metadata F r t R Q U M N) (P H g : ℕ) := + b.elim 0 (fun z => z.2.2.2.toBody.energyCre P H g) + +open scoped Classical in +/-- The indexed operation `b.elim 0 (fun z => z.2.2.2.toBody.timeCre P H U')`. -/ +def Metadata.timeCre (b : Metadata F r t R Q U M N) (P H U' : ℕ) := + b.elim 0 (fun z => z.2.2.2.toBody.timeCre P H U') + +namespace Scenario +variable {A : Type} [Field F] {a : Design} {x y : Wire} + (w : Scenario F N A a x y) {i j : ℕ} + +open scoped Classical in +theorem stored_energyCre (s : w.At i) (v : w.V) : + Metadata.energyCre (w.stored s (w.atlas.coord v)).2 a.chart a.H a.g = + s.stage.energyCre a.chart a.H a.g v := by + rw [stored, Palette.records_at] + exact s.match'.energyCre w.π.edge _ _ _ v + +open scoped Classical in +theorem stored_timeCre (s : w.At i) (v : w.V) : + Metadata.timeCre (w.stored s (w.atlas.coord v)).2 a.chart a.H a.U = + s.stage.timeCre a.chart a.H a.U v := by + rw [stored, Palette.records_at] + exact s.match'.timeCre s.layout w.π.edge _ _ _ v + +variable {w} {menu : a.Menu F N A j} (c : w.Code i menu) (v : w.V) + +open scoped Classical in +theorem Code.energyCre : + Metadata.energyCre (menu ((c.tape (w.atlas.coord v).1).2 (w.atlas.coord v).2)).2 + a.chart a.H a.g = c.frame.stage.energyCre a.chart a.H a.g v := by + rw [c.read, w.stored_energyCre] + +open scoped Classical in +theorem Code.timeCre : + Metadata.timeCre (menu ((c.tape (w.atlas.coord v).1).2 (w.atlas.coord v).2)).2 + a.chart a.H a.U = c.frame.stage.timeCre a.chart a.H a.U v := by + rw [c.read, w.stored_timeCre] + +end Scenario +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# Addressing the local metadata + +One can use the entire bounded-radius input view as the next +dictionary address. This pays a constant factor per wave, avoiding +any need to encode station functions themselves. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Assembly Coloring + +namespace Design +variable (a : Design) {F N A : Type} {e k : ℕ} + +open scoped Classical in +/-- Computes the selectors by the application `Format.vec a.m (.vec a.h (.addr k))`. -/ +abbrev selectors (k : ℕ) := Format.vec a.m (.vec a.h (.addr k)) +open scoped Classical in +/-- The quantity computed by `Fmt.wave a.d a.U (a.U + 1) (.addr e) (.addr k)`. -/ +abbrev observed (e k : ℕ) := Fmt.wave a.d a.U (a.U + 1) (.addr e) (.addr k) +open scoped Classical in +/-- The value specified by `(a.observed e k).width`. -/ +abbrev nextWidth (e k : ℕ) := (a.observed e k).width + +open scoped Classical in +theorem nextWidth_eq (e k : ℕ) : + a.nextWidth e k = 2 ^ ((a.d + 1) * (a.U + 1)) * (2 ^ ((a.d + 1) * a.U) * (e + k)) := by + simp only [nextWidth, observed, Fmt.wave, Fmt.view, Format.width_vec, Format.width_pair, + Format.width_addr] + +open scoped Classical in +/-- Reindexes `S.obj` and `B S.width` by an equivalence. -/ +def number (S : Format) : S.obj ≃ B S.width := + S.code.trans (Fintype.equivOfCardEq (by simp [Format.width])) + +variable [Field F] [Fintype F] [ExpChar F a.p] +variable (hF : a.M * (2 * a.D + 1) < Fintype.card F) (j : Fin a.waves) (menu : a.Menu F N A e) + +open scoped Classical in +/-- The next menu of type `a.Menu F N A (a.nextWidth e k)`, constructed using `(number +(a.observed e k)).symm v`. -/ +def nextMenu (k : ℕ) : a.Menu F N A (a.nextWidth e k) := fun v => + let w := (number (a.observed e k)).symm v + ((menu (w 0 0).1).1, route a.p a.l hF j a.g a.H (fun i u => (menu (w i u).1).2) + (fun i => (w i 0).2.val)) + +open scoped Classical in +/-- The indexed operation `charge a.p a.l hF j a.g a.H (fun i => (menu (w 0 i).1).2) (w 0 +0).2.val`. -/ +def tariff (k : ℕ) (w : (a.observed e k).obj) := + charge a.p a.l hF j a.g a.H (fun i => (menu (w 0 i).1).2) (w 0 0).2.val + +open scoped Classical in +/-- The quantity computed by `Fmt.around a.U (a.U + 1) (show (Fmt.waveIn a.m a.d a.h (.addr e) +(.addr k)).obj from (v, z))`. -/ +def around (v : (a.port e).obj) (z : (a.selectors k).obj) := + Fmt.around a.U (a.U + 1) (show (Fmt.waveIn a.m a.d a.h (.addr e) (.addr k)).obj from (v, z)) + +open scoped Classical in +/-- The value specified by `Fmt.update (D := .addr (a.nextWidth e k)) (number (a.observed e k)) +(a.around v z)`. -/ +def update (v : (a.port e).obj) (z : (a.selectors k).obj) := + Fmt.update (D := .addr (a.nextWidth e k)) (number (a.observed e k)) (a.around v z) + +end Design +namespace Scenario +variable {F N A : Type} [Field F] {a : Design} {e k i : ℕ} {x y : Wire} + {menu : a.Menu F N A e} (w : Scenario F N A a x y) + +open scoped Classical in +theorem Code.around (s : w.Code i menu) (tape : (a.selectors k).obj) (v : B a.m × B a.h) + (j : B ((a.d + 1) * (a.U + 1))) (l : B ((a.d + 1) * a.U)) : + let u := w.atlas.around a.U (w.atlas.around (a.U + 1) v j) l + ((a.around s.tape tape) v.1).2 v.2 j l = ((s.tape u.1).2 u.2, tape u.1 u.2) := by + unfold Design.around Fmt.around Fmt.expand Fmt.zip Atlas.around + simp only [s.host] + +end Scenario +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # The deterministic address update implements the semantic expansion -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Scenario +open Assembly Coloring Transcript + +variable {F A N : Type} [Field F] [Fintype F] {a : Design} [ExpChar F a.p] + {e k : ℕ} {x y : Wire} {menu : a.Menu F N A e} + (w : Scenario F N A a x y) (hF : a.M * (2 * a.D + 1) < Fintype.card F) + (j : Fin a.waves) (s : w.Code j.val menu) + +open scoped Classical in +/-- Computes the actions by the application `Frame.commands w.c a.p a.l hF j s.frame`. -/ +abbrev actions := Frame.commands w.c a.p a.l hF j s.frame + +open scoped Classical in +/-- Computes the branch by the application `Wave.Index (actions w hF j s)`. -/ +abbrev Branch := Wave.Index (actions w hF j s) + +open scoped Classical in +/-- The product of `(actions w hF j s v).action.weight (i v)` indexed by `v`. -/ +def scalar (i : Branch w hF j s) := ∏ v, (actions w hF j s v).action.weight (i v) + +variable (hk : Frame.budget F a.chart a.g a.H a.M a.D a.U ≤ 2 ^ k) + +open scoped Classical in +/-- The value specified by `(Frame.code w.c a.p a.l hF j s.frame hk).relabel (Equiv.curry _ _ +_)`. -/ +def selector : Selector (Branch w hF j s) (a.selectors k).obj := + (Frame.code w.c a.p a.l hF j s.frame hk).relabel (Equiv.curry _ _ _) + +local notation "C" => selector w hF j s hk +local notation "Rec" => w.π.records w.c w.pos s.frame.record (Frame.info w.size s.frame) + +open scoped Classical in +theorem weighted (tape : (a.selectors k).obj) : + Fmt.weight (a.tariff hF j menu k) (a.around s.tape tape) = + ((C).read tape).elim 0 (scalar w hF j s) := by + have h := Frame.charge_prod w.c a.p a.l hF j s.frame w.size hk (Function.uncurry tape) + change _ = ((C).read tape).elim 0 (scalar w hF j s) at h + rw [← h, Fintype.prod_prod_type] + refine Finset.prod_congr rfl fun v _ => Finset.prod_congr rfl fun u _ => ?_ + have ha := s.around w tape (v, u) + unfold Design.tariff + simp only [ha, Atlas.around_zero, s.read, stored] + rfl + +open scoped Classical in +private theorem read_next (i : Branch w hF j s) (v : B a.m × B a.h) : + a.nextMenu hF j menu k (((a.update s.tape ((C).write i)) v.1).2 v.2) = + (w.header v, w.π.records w.c w.pos (Wave.update (actions w hF j s) s.frame.record i) + (Wave.carryInfo (actions w hF j s) i (Frame.info w.size s.frame)) v) := by + have hr := Frame.routed a.p a.l hF j w.c s.frame w.size hk i v + have ha := s.around w ((C).write i) v + simp only [Design.nextMenu, Design.update, Fmt.update, Equiv.symm_apply_apply, ha, + Atlas.around_zero, s.read, stored] + exact congrArg (w.header v, ·) hr + +open scoped Classical in +/-- The update and its weights use only the common menu and the +physical tapes, independently of the world realizing the tapes. -/ +theorem step : + ∃ q : Branch w hF j s → w.Code (j.val + 1) (a.nextMenu hF j menu k), + (∀ i, (q i).tape = a.update s.tape ((C).write i)) ∧ + ∀ u v, w.eval s.frame u v = ∑ i, scalar w hF j s i * w.eval (q i).frame u v := by + obtain ⟨keys, ext, hkeys⟩ := w.controls + obtain ⟨q, hq, hinfo, he⟩ := Frame.advance w.c a.p a.l hF j s.frame hkeys w.room + let out (i : Branch w hF j s) : w.Code (j.val + 1) (a.nextMenu hF j menu k) := + { frame := q i + tape := a.update s.tape ((C).write i) + host := s.host + read := by + intro v + rw [stored, hq, hinfo] + exact read_next w hF j s hk i v } + refine ⟨out, fun _ => rfl, fun u v => ?_⟩ + have h : s.frame.stage.value a.chart = ∑ i, scalar w hF j s i • (q i).stage.value a.chart := by + funext x + simp only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul] + exact he x + unfold eval + simp only [h, map_sum, map_smul, smul_eq_mul] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Scenario +end + +/- # The physical control kernel for one wave -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Assembly Coloring +universe w +variable {F N A : Type} [Field F] [Fintype F] {a : Design} [ExpChar F a.p] + {I : Type w} {e k u v n v' n' : ℕ} {x y : Wire} {L : Set (Table F)} + +namespace Design +variable (a : Design) [ExpChar F a.p] (hF : a.M * (2 * a.D + 1) < Fintype.card F) + (j : Fin a.waves) (menu : a.Menu F N A e) (k : ℕ) + +open scoped Classical in +/-- One dictionary call for the product of local scalar weights and +the new metadata addresses. -/ +def table := weightTable (D := .addr (a.nextWidth e k)) + (number (a.observed e k)) (a.tariff hF j menu k) + +open scoped Classical in +/-- The cost used in the `Design` construction. -/ +def cost (e k v n v' n' : ℕ) (Z : Format) := + waveCost a.m a.d a.h a.U (a.U + 1) v n v' n' (.addr e) (.addr k) (.addr (a.nextWidth e k)) + + 4 * (a.selectors k).width + 4 * Z.width + +end Design + +variable (family : I → Scenario F N A a x y) (Z : Format) (payload : I → Val x → Val y → Z.obj) + (hF : a.M * (2 * a.D + 1) < Fintype.card F) (j : Fin a.waves) (menu : a.Menu F N A e) + +open scoped Classical in +theorem one_wave (hk : Frame.budget F a.chart a.g a.H a.M a.D a.U ≤ 2 ^ k) + (unique : ∀ s i j, (family s).atlas.graph i j ≠ i → + ∃! l, (family s).atlas.graph ((family s).atlas.graph i j) l = i) + (hu : 3 ≤ u) (hU : 0 < a.U) + (h₁ : Access F u L (a.m + (a.d + 1) * a.U) v n) + (h₂ : Access F u L (a.m + (a.d + 1) * (a.U + 1)) v' n') + (hv : 2 ^ a.h * (e + k) ≤ v) (hv' : 2 ^ a.h * (2 ^ ((a.d + 1) * a.U) * (e + k)) ≤ v') + (hw : 2 * a.nextWidth e k ≤ u) (ht : a.table hF j menu k ∈ L) : + Transforms F u L (snapshot family Z payload j.val menu) + (snapshot family Z payload (j.val + 1) (a.nextMenu hF j menu k)) (a.cost e k v n v' n' Z) + := by + let X := snapshot family Z payload j.val menu + let data (z : X.state × (a.selectors k).obj) : + (Fmt.waveIn a.m a.d a.h (.addr e) (.addr k)).obj := (z.1.2.tape, z.2) + have hs := computes_wave (D := .addr (a.nextWidth e k)) hu hU (Nat.succ_pos _) h₁ h₂ + (by simpa using hv) (by simpa [Fmt.view] using hv') (Design.number (a.observed e k)) + (a.tariff hF j menu k) (by simpa only [Format.width_addr, two_mul] using hw) ht data (by + intro z + change ∀ i j, _ → _ + simp only [data, z.1.2.host] + exact unique z.1.1) + obtain ⟨fn, hfn, he⟩ := hs + let _ := Fintype.ofFinite (a.selectors k).obj + have kernels := (Kernel.sum_hidden hu hfn).par (Map.circuit hu (Circuit.id F Z)) + refine ⟨_, kernels, ?_⟩ + rintro ⟨i, s⟩ + let w := family i + let sel := w.selector hF j s hk + obtain ⟨q, hq, hv⟩ := w.step hF j s hk + refine ⟨w.Branch hF j s, inferInstance, fun z => ⟨i, q z⟩, w.scalar hF j s, hv, ?_⟩ + rintro a' b' ⟨v, z⟩ + have term (c : (a.selectors k).obj) : fn (s.tape, c) v = + (sel.read c).elim 0 (fun k => if (q k).tape = v then w.scalar hF j s k else 0) := by + have eq := he (⟨i, s⟩, c) v + change fn (s.tape, c) v = @ite F (a.update s.tape c = v) (Classical.propDecidable _) + (Fmt.weight (a.tariff hF j menu k) (a.around s.tape c)) 0 at eq + rw [w.weighted hF j s hk] at eq + change fn (s.tape, c) v = @ite F (a.update s.tape c = v) (Classical.propDecidable _) + ((sel.read c).elim 0 _) 0 at eq + cases h : sel.read c with + | none => simpa only [h, Option.elim_none, ite_self] using eq + | some k => + have hk := (sel.valid _ _).mp h + simp only [h, Option.elim_some] at eq + simp only [Option.elim_some] + have et : (q k).tape = a.update s.tape c := by rw [hk]; exact hq k + rw [et] + by_cases he : a.update s.tape c = v <;> simpa [he] using eq + change (∑ c, fn (s.tape, c) v) * (if payload i a' b' = z then 1 else 0) = + ∑ k, @ite F (((q k).tape, payload i a' b') = (v, z)) + (Classical.propDecidable _) (w.scalar hF j s k) 0 + simp only [term, Transcript.Selector.sum, Finset.sum_mul, Prod.mk.injEq] + by_cases h : payload i a' b' = z <;> simp [h] + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# Composition across all waves + +The number of calls, the address-width inflation, and the dictionary +are independent of the number of hosts and blocks in the family. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Assembly Coloring + +namespace Design +variable (a : Design) {F N A : Type} {e k : ℕ} + +open scoped Classical in +/-- In the case `0`, this construction gives `e`. -/ +def widthAt (e k : ℕ) : ℕ → ℕ + | 0 => e + | i + 1 => a.nextWidth (widthAt e k i) k + +open scoped Classical in +/-- The quantity computed by `2 ^ ((a.d + 1) * (a.U + 1)) * 2 ^ ((a.d + 1) * a.U) + 1`. -/ +def factor := 2 ^ ((a.d + 1) * (a.U + 1)) * 2 ^ ((a.d + 1) * a.U) + 1 + +open scoped Classical in +theorem width_bound (e k i : ℕ) : a.widthAt e k i + k ≤ a.factor ^ i * (e + k) := by + induction i with + | zero => simp [widthAt] + | succ i ih => + rw [widthAt, nextWidth_eq, pow_succ', mul_assoc] + refine le_trans ?_ (Nat.mul_le_mul_left a.factor ih) + conv_rhs => rw [factor, add_mul, one_mul, mul_assoc] + omega + +open scoped Classical in +/-- The quantity computed by `a.factor ^ a.waves * (e + k)`. -/ +def maxWidth (e k : ℕ) := a.factor ^ a.waves * (e + k) + +open scoped Classical in +theorem fits_width {i : ℕ} (h : i ≤ a.waves) : a.widthAt e k i + k ≤ a.maxWidth e k := by + have positive : 0 < a.factor := by + unfold factor + omega + exact (a.width_bound _ _ _).trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right positive h)) + +open scoped Classical in +/-- The quantity computed by `4 * ((a.port e).pair Z).width + ∑ i ∈ Finset.range a.waves, a.cost +(a.widthAt e k i) k v n v' n' Z`. -/ +def totalCost (e k v n v' n' : ℕ) (Z : Format) := + 4 * ((a.port e).pair Z).width + ∑ i ∈ Finset.range a.waves, a.cost (a.widthAt e k i) k v n v' n' Z + +variable [Field F] [Fintype F] [ExpChar F a.p] (hF : a.M * (2 * a.D + 1) < Fintype.card F) + (menu : a.Menu F N A e) (k : ℕ) + +open scoped Classical in +/-- In the case `0, _`, this construction gives `menu`. -/ +def menuAt : (i : ℕ) → i ≤ a.waves → a.Menu F N A (a.widthAt e k i) + | 0, _ => menu + | i + 1, h => a.nextMenu hF ⟨i, h⟩ (menuAt i (Nat.le_of_succ_le h)) k + +open scoped Classical in +/-- The indexed operation `Finset.univ.image (fun j : Fin a.waves => a.table hF j (a.menuAt hF +menu k j.val j.isLt.le) k)`. -/ +def calls := Finset.univ.image (fun j : Fin a.waves + => a.table hF j (a.menuAt hF menu k j.val j.isLt.le) k) + +open scoped Classical in +theorem card_calls : (a.calls hF menu k).card ≤ a.waves := by + exact Finset.card_image_le.trans_eq (Fintype.card_fin _) + +end Design + +universe w +variable {F N A : Type} [Field F] [Fintype F] {a : Design} [ExpChar F a.p] + {I : Type w} {e k u v n v' n' : ℕ} {x y : Wire} {L : Set (Table F)} + (family : I → Scenario F N A a x y) (Z : Format) (payload : I → Val x → Val y → Z.obj) + (hF : a.M * (2 * a.D + 1) < Fintype.card F) (menu : a.Menu F N A e) + +open scoped Classical in +theorem all_waves (hk : Frame.budget F a.chart a.g a.H a.M a.D a.U ≤ 2 ^ k) + (unique : ∀ s i j, (family s).atlas.graph i j ≠ i → + ∃! l, (family s).atlas.graph ((family s).atlas.graph i j) l = i) + (hu : 3 ≤ u) (hU : 0 < a.U) + (h₁ : Access F u L (a.m + (a.d + 1) * a.U) v n) + (h₂ : Access F u L (a.m + (a.d + 1) * (a.U + 1)) v' n') + (hv : 2 ^ a.h * a.maxWidth e k ≤ v) + (hv' : 2 ^ a.h * (2 ^ ((a.d + 1) * a.U) * a.maxWidth e k) ≤ v') + (hw : 2 * a.maxWidth e k ≤ u) (ht : ↑(a.calls hF menu k) ⊆ L) : + Transforms F u L (snapshot family Z payload 0 menu) + (snapshot family Z payload a.waves (a.menuAt hF menu k a.waves le_rfl)) + (a.totalCost e k v n v' n' Z) := by + suffices ∀ i (hi : i ≤ a.waves), + Transforms F u L (snapshot family Z payload 0 menu) + (snapshot family Z payload i (a.menuAt hF menu k i hi)) + (4 * ((a.port e).pair Z).width + ∑ j ∈ Finset.range i, + a.cost (a.widthAt e k j) k v n v' n' Z) + from this _ le_rfl + intro i + induction i with + | zero => + intro _ + simp only [Finset.range_zero, Finset.sum_empty, add_zero] + exact Transforms.refl hu _ + | succ i ih => + intro hi + have he := a.fits_width (e := e) (k := k) (Nat.le_of_succ_le hi) + have hn : a.nextWidth (a.widthAt e k i) k ≤ a.maxWidth e k := + (Nat.le_add_right (a.widthAt e k (i + 1)) k).trans (a.fits_width hi) + have call := ht (Finset.mem_image_of_mem _ (Finset.mem_univ (⟨i, hi⟩ : Fin a.waves))) + rw [Finset.sum_range_succ, ← add_assoc] + exact (ih (Nat.le_of_succ_le hi)).comp (one_wave family Z payload hF ⟨i, hi⟩ + _ hk unique hu hU h₁ h₂ + ((Nat.mul_le_mul_left _ he).trans hv) + ((Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ he)).trans hv') + ((Nat.mul_le_mul_left _ hn).trans hw) call) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# The two costs of reading a bounded neighborhood + +Only work done once per host pays for global addresses. Work repeated +in each of its blocks depends on the short labels and on the price +per bit, independently of the threshold of the permutation theorem. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Assembly Coloring Rounds.Contraction +open BatchDescent.Phase.Poly (pow_sum) + +/-- The data for the rates construction, including `m`, `h`, `X`, `Y`, `short`. -/ +structure Rates where + /-- The `Rates` field of type `ℕ`. -/ + m : ℕ + /-- The `Rates` field of type `ℕ`. -/ + h : ℕ + /-- The `Rates` field of type `ℕ`. -/ + X : ℕ + /-- The `Rates` field of type `ℕ`. -/ + Y : ℕ + short : 10000 ≤ Y + long : 1000 + 10 * m + 10 * Y ≤ X + +namespace Rates +variable (a : Rates) +theorem incl : a.Y ≤ a.X := by have := a.long; omega +theorem two : 2 ≤ a.Y := by have := a.short; omega +theorem two' : 2 ≤ a.X := a.two.trans a.incl + +/-- The quantity computed by `b * a.X ^ i + (b * 2 ^ a.h + z) * a.Y ^ i`. -/ +def bound (b z i : ℕ) := b * a.X ^ i + (b * 2 ^ a.h + z) * a.Y ^ i +/-- The value specified by `n ≤ a.bound b z i`. -/ +abbrev Paid (b z i n : ℕ) := n ≤ a.bound b z i +/-- Computes the row by the application `a.Paid 1 0`. -/ +abbrev Row := a.Paid 1 0 +/-- The quantity computed by `a.Paid (2 ^ a.m) 0`. -/ +abbrev Host := a.Paid (2 ^ a.m) 0 + +variable {a} {b z i j n l : ℕ} + +theorem Paid.up (h : a.Paid b z i n) (e : i ≤ j) : a.Paid b z j n := by + refine h.trans (Nat.add_le_add (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right ?_ e)) + (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right ?_ e))) + · exact lt_of_lt_of_le (by decide) a.two' + · exact lt_of_lt_of_le (by decide) a.two + +theorem Paid.plus (h : a.Paid b z i n) (e : a.Paid b z j l) : + a.Paid b z (max i j + 1) (n + l) := by + refine (Nat.add_le_add h e).trans ?_ + unfold bound + rw [add_add_add_comm, ←mul_add, ←mul_add] + exact Nat.add_le_add (Nat.mul_le_mul_left _ (pow_sum a.two' ..)) (Nat.mul_le_mul_left _ (pow_sum + a.two ..)) + +theorem Paid.times (h : a.Paid b z i n) (e : l ≤ a.Y) : a.Paid b z (i + 1) (l * n) := by + refine (Nat.mul_le_mul e h).trans ?_ + unfold bound + rw [mul_comm a.Y, add_mul, mul_assoc, mul_assoc, pow_succ, pow_succ] + exact Nat.add_le_add_right (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ a.incl)) _ + +theorem Paid.scale (h : a.Paid b z i n) (l : ℕ) (e : l ≤ 10000 := by decide) : + a.Paid b z (i + 1) (l * n) := h.times (e.trans a.short) + +theorem high (h : n ≤ a.X ^ i) : a.Row i n := by + simpa only [Row, Paid, bound, one_mul, add_zero] + using h.trans (Nat.le_add_right _ (2 ^ a.h * a.Y ^ i)) + +theorem low (h : n ≤ a.Y ^ i) : a.Row i (2 ^ a.h * n) := by + simpa only [Row, Paid, bound, one_mul, add_zero] using + (Nat.mul_le_mul_left (2 ^ a.h) h).trans (Nat.le_add_left _ (a.X ^ i)) + +theorem big (h : n ≤ a.X) : a.Row 1 n := high (by simpa using h) + +theorem Row.hosts (h : a.Row i n) : a.Host i (2 ^ a.m * n) := by + simpa only [Host, Paid, bound, one_mul, add_zero, mul_add, mul_assoc] + using Nat.mul_le_mul_left (2 ^ a.m) h + +theorem Row.fan (h : a.Row i n) (e : 2 ^ l ≤ a.Y) : a.Host (i + 1) (2 ^ (a.m + l) * n) := by + simpa only [pow_add, mul_assoc] using Row.hosts (Paid.times h e) + +theorem Host.carry (h : a.Host i n) : a.Paid (2 ^ a.m) z i (n + z) := by + refine (Nat.add_le_add h (Nat.le_mul_of_pos_right z (pow_pos (lt_of_lt_of_le (by decide) a.two) + i))).trans_eq ?_ + unfold bound + rw [add_zero, add_mul, add_assoc] + +variable (a) {F : Type} [Field F] (p : Prices F) + +theorem fee (s v : ℕ) (hs : 2 ^ s ≤ a.Y) (hW : 1 + p.W ≤ a.Y) (hw : 1 + p.w ^ p.power ≤ a.X) + (hv : a.Row i v) : a.Host (max i 1 + 4) (p.fee (a.m + s) v) := by + have h := (((Row.fan (Paid.plus hv (big hw)) hs).times hW).scale 1000) + unfold Prices.fee + rw [mul_assoc, mul_assoc, add_assoc v] + exact h + +theorem gather (s v n : ℕ) (hs : 2 ^ s ≤ a.Y) (hv : a.Row 4 v) (hn : a.Host 8 n) : + a.Host 205 (gatherCost a.m s v n) := by + have lt := (Nat.lt_two_pow_self (n := s)).le.trans hs + have hl := a.long + have h₁ := Row.fan (high (Nat.pow_le_pow_left (show 100 + (a.m + s + 3 * a.m + 1) + ≤ a.X by omega) 200)) hs + have h₂ := Row.fan (Paid.plus (big (show a.m + s + 1 ≤ a.X by omega)) hv) hs + have e := ((hn.scale 4).plus (h₁.scale 4)).plus (h₂.scale 1100) + unfold gatherCost + rw [mul_assoc 1100, add_right_comm (a.m + s) v 1] + exact e.up (by decide) + +theorem rows (d : ℕ) (A : Format) (hd : 2 ^ d ≤ a.Y) (hA : A.width ≤ a.Y ^ 4) : + a.Host 5 (Fmt.rows a.m d a.h A).width := by + rw [Fmt.width_rows] + have hm := big (show a.m ≤ a.X by have := a.long; omega) + exact Row.hosts ((Paid.times hm hd).plus (low hA)) + +theorem expand (d r v n : ℕ) (A : Format) (hd : 2 ^ d ≤ a.Y) (hs : 2 ^ ((d + 1) * r) ≤ a.Y) + (hv : a.Row 4 v) (hn : a.Host 8 n) (hA : A.width ≤ a.Y ^ 4) + (hB : (Fmt.view d r A).width ≤ a.Y ^ 4) : + a.Host 206 (expandCost a.m d a.h r v n A) := by + have ht : 100 + (a.m + 2 ^ ((d + 1) * r)) ≤ a.X := by have := a.long; omega + have hb := Row.hosts (high (Nat.pow_le_pow_left ht 200)) + have hh := (a.rows d A hd hA).plus (a.rows d _ hd hB) + exact ((hh.plus hb).scale 200).plus (a.gather _ _ _ hs hv hn) + +theorem update (d : ℕ) (A D : Format) (hd : 2 ^ d ≤ a.Y) + (hw : 1 + A.width + D.width ≤ a.Y ^ 4) : a.Host 5 (updateCost a.m d a.h A D) := by + have hm := big (show a.m ≤ a.X by have := a.long; omega) + exact Row.hosts (((Paid.times hm hd).scale 4).plus (low hw)) + +theorem wave (d r t v n v' n' : ℕ) (A C D : Format) + (hd : 2 ^ d ≤ a.Y) (hr : 2 ^ ((d + 1) * r) ≤ a.Y) (ht : 2 ^ ((d + 1) * t) ≤ a.Y) + (hv : a.Row 4 v) (hn : a.Host 8 n) (hv' : a.Row 4 v') (hn' : a.Host 8 n') + (hw : 1 + (Fmt.wave d r t A C).width + D.width ≤ a.Y ^ 4) : + a.Host 209 (waveCost a.m d a.h r t v n v' n' A C D) := by + have h₂ : (Fmt.wave d r t A C).width ≤ a.Y ^ 4 := by omega + have mono (s : ℕ) (B : Format) : B.width ≤ (Fmt.view d s B).width := by + rw [Fmt.view, Format.width_vec] + exact Nat.le_mul_of_pos_left _ (by positivity) + have h₁ := (mono t (Fmt.view d r (A.pair C))).trans h₂ + have h₀ := (mono r (A.pair C)).trans h₁ + have hc := ((a.rows d _ hd h₀).scale 12).plus (a.expand d r _ _ _ hd hr hv hn h₀ h₁) + exact (hc.plus (a.expand d t _ _ _ hd ht hv' hn' h₁ h₂)).plus (a.update d _ _ hd hw) + +end Rates +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # A uniform price for a complete movement schedule -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Assembly Coloring Rounds.Contraction +namespace Design +variable (a : Design) {F : Type} [Field F] (p : Prices F) (e k : ℕ) + +open scoped Classical in +/-- The quantity computed by `(a.d + 1) * (a.U + 1)`. -/ +abbrev hops := (a.d + 1) * (a.U + 1) +open scoped Classical in +/-- The quantity computed by `2 ^ a.h * (2 ^ a.hops * a.maxWidth e k)`. -/ +def payloadCap := 2 ^ a.h * (2 ^ a.hops * a.maxWidth e k) +open scoped Classical in +/-- The quantity computed by `p.fee (a.m + r) (a.payloadCap e k)`. -/ +def fees (r : ℕ) := p.fee (a.m + r) (a.payloadCap e k) +open scoped Classical in +/-- The value specified by `a.totalCost e k (a.payloadCap e k) (a.fees p e k ((a.d + 1) * a.U)) +(a.payloadCap e k) (a.fees p e k a.hops)`. -/ +def price := a.totalCost e k (a.payloadCap e k) (a.fees p e k ((a.d + 1) * a.U)) + (a.payloadCap e k) (a.fees p e k a.hops) + +open scoped Classical in +theorem le_hops : (a.d + 1) * a.U ≤ a.hops := Nat.mul_le_mul_left _ (Nat.le_succ _) +open scoped Classical in +theorem degree_le_hops : a.d ≤ a.hops := + (Nat.le_succ _).trans (Nat.le_mul_of_pos_right _ (Nat.succ_pos _)) + +open scoped Classical in +/-- A common pair of budgets may be used for all three parts of +concentration. The exterior register is only carried here. -/ +theorem price_bound (Z : Format) (X Y : ℕ) (hs : 10000 ≤ Y) (hl : 1000 + 10 * a.m + 10 * Y ≤ X) + (hW : 1 + p.W ≤ Y) (hw : 1 + p.w ^ p.power ≤ X) (ht : 2 ^ a.hops ≤ Y) + (hb : 1 + 2 * a.maxWidth e k ≤ Y) (hN : a.waves ≤ Y) : + a.price p e k Z ≤ 2 ^ a.m * X ^ 215 + (2 ^ (a.m + a.h) + Z.width) * Y ^ 215 := by + let c : Rates := ⟨a.m, a.h, X, Y, hs, hl⟩ + let v := a.payloadCap e k + let j := (a.d + 1) * a.U + let n := a.fees p e k j + let n' := a.fees p e k a.hops + have hd := (Nat.pow_le_pow_right (by decide : 0 < 2) a.degree_le_hops).trans ht + have hj := (Nat.pow_le_pow_right (by decide : 0 < 2) a.le_hops).trans ht + have w₀ : e + k ≤ a.maxWidth e k := a.fits_width (Nat.zero_le _) + have w₁ : Y ≤ Y ^ 4 := Nat.le_self_pow (by decide) _ + have hv : c.Row 4 v := by + apply Rates.low + change 2 ^ a.hops * a.maxWidth e k ≤ Y ^ 4 + refine (Nat.mul_le_mul ht (by omega : a.maxWidth e k ≤ Y)).trans ?_ + rw [← pow_two] + exact Nat.pow_le_pow_right (by omega) (by decide) + have hn : c.Host 8 n := c.fee p _ _ hj hW hw hv + have hn' : c.Host 8 n' := c.fee p _ _ ht hW hw hv + have hz : c.Host 4 (a.selectors k).width := by + rw [selectors, Format.width_vec, Format.width_vec, Format.width_addr] + exact Rates.Row.hosts (Rates.low (by change k ≤ Y ^ 4; omega)) + have start : c.Paid (2 ^ a.m) Z.width 6 (4 * ((a.port e).pair Z).width) := by + rw [Format.width_pair] + have he := c.rows a.d (.addr e) hd (by rw [Format.width_addr]; change e ≤ Y ^ 4; omega) + exact (Rates.Host.carry he).scale 4 + have one (i : ℕ) (hi : i ∈ Finset.range a.waves) : + c.Paid (2 ^ a.m) Z.width 212 (a.cost (a.widthAt e k i) k v n v n' Z) := by + let q := a.widthAt e k i + let l := a.nextWidth q k + have hq : l + k ≤ a.maxWidth e k := a.fits_width (Nat.succ_le_of_lt (Finset.mem_range.mp hi)) + have hr : 1 + (a.observed q k).width + (Format.addr l).width ≤ c.Y ^ 4 := by + rw [Format.width_addr] + change 1 + l + l ≤ Y ^ 4 + omega + have he := c.wave a.d a.U (a.U + 1) v n v n' (.addr q) (.addr k) (.addr l) + hd hj ht hv hn hv hn' hr + have h' := Rates.Host.carry (z := Z.width) (he.plus (hz.scale 4)) + refine le_trans ?_ ((h'.scale 4).up (by decide)) + unfold cost + change _ + 4 * Z.width ≤ 4 * (_ + Z.width) + rw [mul_add] + exact Nat.add_le_add_right (Nat.le_mul_of_pos_left _ (by decide)) _ + have sum := Finset.sum_le_sum one + rw [Finset.sum_const, Finset.card_range, nsmul_eq_mul] at sum + have hh : c.Paid (2 ^ a.m) Z.width 213 + (∑ i ∈ Finset.range a.waves, a.cost (a.widthAt e k i) k v n v n' Z) := + sum.trans (Rates.Paid.times (show c.Paid _ _ _ _ from le_rfl) hN) + rw [pow_add] + exact (start.plus hh).up (by decide) + +end Design + +universe w +variable {F N A : Type} [Field F] [Fintype F] {a : Design} [ExpChar F a.p] + {I : Type w} {e k u : ℕ} {x y : Wire} {L : Set (Table F)} + (family : I → Scenario F N A a x y) (Z : Format) (payload : I → Val x → Val y → Z.obj) + (hF : a.M * (2 * a.D + 1) < Fintype.card F) (menu : a.Menu F N A e) (p : Prices F) + +open scoped Classical in +theorem priced_waves (hk : Frame.budget F a.chart a.g a.H a.M a.D a.U ≤ 2 ^ k) + (unique : ∀ s i j, (family s).atlas.graph i j ≠ i → + ∃! l, (family s).atlas.graph ((family s).atlas.graph i j) l = i) + (hu : 3 ≤ u) (hU : 0 < a.U) (hw : a.m + a.hops ≤ p.w) + (hb : 2 * a.maxWidth e k ≤ u) (ht : ↑(a.calls hF menu k) ⊆ L) : + Transforms F u L (snapshot family Z payload 0 menu) + (snapshot family Z payload a.waves (a.menuAt hF menu k a.waves le_rfl)) + (a.price p e k Z) := by + have h₀ : 0 < a.m + (a.d + 1) * a.U := by positivity + have h₁ := Nat.add_le_add_left a.le_hops a.m + refine all_waves family Z payload hF menu hk unique hu hU + (p.access hu h₀ (h₁.trans hw) _) (p.access hu (h₀.trans_le h₁) hw _) ?_ ?_ hb ht + · exact Nat.mul_le_mul_left _ (Nat.le_mul_of_pos_left _ (by positivity)) + · exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) + a.le_hops)) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Waves/Scenario.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Waves/Scenario.lean new file mode 100644 index 0000000000..47695e7ffb --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Waves/Scenario.lean @@ -0,0 +1,601 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.GroupWithZero.Finset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Choices +public import Mathlib.Data.Finset.Image +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Waves.Window +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Surface.Cardinality +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Assembly.Select + +/-! +# One selector per occurrence + +Active cells select a local branch by its ordinal. The unused +positions have one valid word, zero, so they do not multiply the +contraction in small characteristic. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.Selector +open Finset +variable {V J : Type} {L : ℕ} [NeZero L] (addr : J ↪ V) + (S : J → Type) [∀ j, Fintype (S j)] (fits : ∀ j, Fintype.card (S j) ≤ L) + +open scoped Classical in +/-- Extends the specified values along the indexing map, using a default elsewhere. -/ +def scatter (x : ∀ j, S j) : V → Fin L := + Function.extend addr (fun j => Fin.castLE (fits j) (Fintype.equivFin _ (x j))) (fun _ => 0) + +open scoped Classical in +theorem scatter_at (x : ∀ j, S j) (j : J) : + (scatter addr S fits x (addr j)).val = (Fintype.equivFin (S j) (x j)).val := by + rw [scatter, addr.injective.extend_apply] + rfl + +open scoped Classical in +theorem scatter_away (x : ∀ j, S j) (v : V) (h : v ∉ Set.range addr) : + scatter addr S fits x v = 0 := Function.extend_apply' _ _ _ h + +open scoped Classical in +/-- Builds `Selector (∀ j, S j) (V → Fin L) where write` with the specified `write`, `read`, +`valid`. -/ +def scattered : Selector (∀ j, S j) (V → Fin L) where + write := scatter addr S fits + read t := if h : ∃ x, t = scatter addr S fits x then some h.choose else none + valid t x := by + split_ifs with h + · constructor + · intro he; rw [← Option.some.inj he]; exact h.choose_spec + · intro he + congr 1 + funext j + apply (Fintype.equivFin _).injective + apply Fin.ext + rw [← scatter_at addr S fits, ← scatter_at addr S fits, ← h.choose_spec, ← he] + · exact iff_of_false (by simp) (fun e => h ⟨x, e⟩) + +open scoped Classical in +theorem scattered_present (t : V → Fin L) (on : ∀ j, (t (addr j)).val < Fintype.card (S j)) + (off : ∀ v ∉ Set.range addr, t v = 0) : ∃ x, t = scatter addr S fits x := by + let x j := (Fintype.equivFin (S j)).symm ⟨_, on j⟩ + refine ⟨x, funext fun v => ?_⟩ + by_cases h : v ∈ Set.range addr + · obtain ⟨j, rfl⟩ := h + apply Fin.ext + rw [scatter_at] + exact (congrArg Fin.val ((Fintype.equivFin (S j)).apply_symm_apply ⟨_, on j⟩)).symm + · rw [off v h, scatter_away _ _ _ _ _ h] + +variable [Fintype V] [Fintype J] {F : Type} [CommMonoidWithZero F] + +open scoped Classical in +theorem scattered_weight (t : V → Fin L) (weight : (j : J) → S j → F) (w : V → F) + (on : ∀ j, w (addr j) = if h : (t (addr j)).val < Fintype.card (S j) + then weight j ((Fintype.equivFin _).symm ⟨_, h⟩) else 0) + (off : ∀ v ∉ Set.range addr, w v = if t v = 0 then 1 else 0) : + (∏ v, w v) = ((scattered addr S fits).read t).elim 0 (fun x => ∏ j, weight j (x j)) := by + cases h : (scattered addr S fits).read t with + | none => + by_contra! hn + have live (v : V) : w v ≠ 0 := fun e => hn (prod_eq_zero (mem_univ v) e) + obtain ⟨x, hx⟩ := scattered_present addr S fits t + (fun j => by by_contra! hn; exact live (addr j) (by rw [on, dite_eq_right (not_lt.mpr hn)])) + (fun v hv => by by_contra! hn; exact live v (by rw [off v hv, ite_eq_right hn])) + rw [((scattered addr S fits).valid t x).mpr hx] at h + contradiction + | some x => + have he : t = scatter addr S fits x := ((scattered addr S fits).valid _ _).mp h + let active := univ.image addr + have hw : (∏ v ∈ active, w v) = ∏ v, w v := prod_subset (subset_univ _) (by + intro v _ hv + have hi : v ∉ Set.range addr := by simpa [active] using hv + rw [off v hi, he, scatter_away _ _ _ _ _ hi, ite_eq_left rfl]) + rw [← hw, show active = univ.image addr from rfl, prod_image addr.injective.injOn] + apply prod_congr rfl + intro j _ + simp only [on, he, scatter_at, Fin.is_lt, ↓reduceDIte, Fin.eta, Equiv.symm_apply_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.Selector +end + +/- +# A local weighted lookup at the initiator + +The lookup receives records indexed by a fixed neighborhood walk. +The origin is always entry zero. Repeated addresses are erased before +reconstructing the intrinsic panel. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Coloring + +variable {F V E T X J L N : Type} [Field F] [Fintype F] + {r t m d h U R Q M g H D : ℕ} (p l : ℕ) [ExpChar F p] + (hF : M * (2 * D + 1) < Fintype.card F) (j : Fin (R * M)) + +local notation "Meta" => Metadata F r t R Q U M N +local notation "Msg" => Reply F r t R (Stamp Q (R * M) U) N + +open scoped Classical in +/-- Transforms the indexed data by `u.map Prod.fst = some (finProdFinEquiv.symm j).1`. -/ +def selected (u : Meta) := u.map Prod.fst = some (finProdFinEquiv.symm j).1 + +open scoped Classical in +/-- In the case `none`, this construction gives `none`. -/ +def send (g H : ℕ) (s : B ((d + 1) * U) → Meta) (i : ℕ) : Option Msg := + match s 0 with + | none => none + | some (v, k, pos, _) => + if v = (finProdFinEquiv.symm j).1 then + (visible s).get p l g H M D hF v (pos (finProdFinEquiv.symm j).2) + (fun i : Fin (U + 1) => created (fun _ : Unit => k) j () i.val) i + else none + +open scoped Classical in +theorem send_off (s : B ((d + 1) * U) → Meta) (i : ℕ) (e : ¬selected j (s 0)) : + send p l hF j g H s i = none := by + unfold send selected at * + cases e' : s 0 with + | none => rfl + | some y => + obtain ⟨v, k, pos, w⟩ := y + simp only [e', Option.map_some, Option.some.injEq] at e + simp only [ite_eq_right e] + +open scoped Classical in +/-- Selects the appropriate branch of `if selected j (s 0) then (send p l hF j g H s i).elim 0 +Reply.weight else if i = 0 then 1 else 0`. -/ +def charge (g H : ℕ) (s : B ((d + 1) * U) → Meta) (i : ℕ) : F := + if selected j (s 0) then (send p l hF j g H s i).elim 0 Reply.weight + else if i = 0 then 1 else 0 + +namespace Frame +variable [Fintype V] [Fintype E] {a : Atlas V E m d h} + {π : Palette a (2 * U + 2) R} {ref : Reference J L N V E T X} {pos : V → Fin M → F} + {origin : Stage F r t T V E X} (c : Palette a (horizon U (R * M) 0) Q) + (x : Frame (π.plan pos) ref origin (p ^ l) g H Q j.val) (size : V → ℕ) + +local notation "C" => commands c p l hF j x +local notation "I" => Fin (Plan.count (π.plan pos) j) +local notation "root" => Plan.root (π.plan pos) j +local notation "A" => π.records c pos x.record (info size x) + +omit [Fintype F] [Fintype E] [ExpChar F p] in +open scoped Classical in +theorem selected_iff (v : B m × B h) : + selected j (A v) ↔ v ∈ Set.range ((root).trans a.coord) := by + by_cases h : v ∈ Set.range a.coord + · obtain ⟨w, rfl⟩ := h + simp only [selected, Palette.records_at, Option.map_some, Option.some.injEq] + rw [← π.mem_roots] + exact ⟨fun ⟨i, hi⟩ => ⟨i, congrArg a.coord hi⟩, fun ⟨i, hi⟩ => ⟨i, a.coord.injective hi⟩⟩ + · rw [Palette.records_away _ _ _ _ _ h] + exact iff_of_false (by simp [selected]) (fun ⟨i, e⟩ => h ⟨_, e⟩) + +open scoped Classical in +theorem send_at (i : I) (z : ℕ) : + send p l hF j g H (A ∘ a.around U (a.coord (root i))) z = + if h : z < Fintype.card (C i).action.I then + some ((panel c p l j x i).reply (C i).action ((Fintype.equivFin _).symm ⟨z, h⟩) + (π.tiles x.record (info size x) (root i))) else none := by + let v := root i + have eq : π.mark v = (finProdFinEquiv.symm j).1 := (π.mem_roots _ _).mp ⟨i, rfl⟩ + unfold send + simp only [Function.comp_apply, Atlas.around_zero, Palette.records_at, Palette.window] + rw [ite_eq_left eq] + let y := panel c p l j x i + have he := (π.tiles x.record (info size x) v).get_spec p l g H M D hF y + (π.panel_complete _ (x.match'.incident x.layout) _ _ _) + (π.bodies _ _ _ (x.match'.incident x.layout) _ _) z + exact he + +end Frame +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Charging and broadcasting regional scripts on the fixed host -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Frame +open Coloring Transcript + +variable {F V E T X J L N : Type} [Field F] [Fintype F] [Fintype V] [Fintype E] + {r t m d h U R Q M g H D k : ℕ} {a : Atlas V E m d h} + {π : Palette a (2 * U + 2) R} {ref : Reference J L N V E T X} {pos : V → Fin M → F} + {origin : Stage F r t T V E X} (c : Palette a (horizon U (R * M) 0) Q) + (p l : ℕ) [ExpChar F p] (hF : M * (2 * D + 1) < Fintype.card F) (j : Fin (R * M)) + (x : Frame (π.plan pos) ref origin (p ^ l) g H Q j.val) (size : V → ℕ) + +local notation "C" => commands c p l hF j x +local notation "I" => Fin (Plan.count (π.plan pos) j) +local notation "root" => Plan.root (π.plan pos) j +local notation "A" => π.records c pos x.record (info size x) + +open scoped Classical in +/-- The quantity computed by `breadth P g H M D (Nat.card F + 1) ^ ((U + 1) * (M + 1))`. -/ +def budget (F : Type) (P g H M D U : ℕ) : ℕ := breadth P g H M D (Nat.card F + 1) ^ ((U + 1) * (M + + 1)) + +variable (bk : budget F (p ^ l) g H M D U ≤ 2 ^ k) + +include bk in +open scoped Classical in +theorem fits (i : I) : Fintype.card (C i).action.I ≤ 2 ^ k := + (π.wave_bound _ _ _ _ _ _ _ _ _ _ _ _ _ _ _).trans bk + +open scoped Classical in +/-- Computes the code by the application `Selector.scattered ((root).trans a.coord) _ (fits c p +l hF j x bk)`. -/ +def code : Selector (Wave.Index C) (B m × B h → B k) := + Selector.scattered ((root).trans a.coord) _ (fits c p l hF j x bk) + +local notation "S" => code c p l hF j x bk + +open scoped Classical in +/-- The value specified by `send p l hF j g H (A ∘ a.around U v) (tape v).val`. -/ +def issue (tape : B m × B h → B k) (v : B m × B h) := + send p l hF j g H (A ∘ a.around U v) (tape v).val + +open scoped Classical in +theorem charge_prod (tape : B m × B h → B k) : + (∏ v, charge p l hF j g H (A ∘ a.around U v) (tape v).val) = + ((S).read tape).elim 0 (fun i => ∏ v, (C v).action.weight (i v)) := by + apply Selector.scattered_weight + · intro i + have h := (selected_iff p l j c x size _).mpr (Set.mem_range_self i) + change selected j (A (a.coord (root i))) at h + change charge p l hF j g H (A ∘ a.around U (a.coord (root i))) _ = _ + simp only [charge, Function.comp_apply, Atlas.around_zero, h, ↓reduceIte, send_at] + split_ifs <;> rfl + · intro v hv + have h := mt (selected_iff p l j c x size v).mp hv + simp only [charge, Function.comp_apply, Atlas.around_zero, ite_eq_right h, Fin.val_eq_zero_iff] + +open scoped Classical in +theorem issue_at (i : I) (z : Wave.Index C) : + issue c p l hF j x size ((S).write z) (a.coord (root i)) = + some (reply c p l hF j x z size i) := by + have eq := Selector.scatter_at ((root).trans a.coord) _ (fits c p l hF j x bk) z i + change (((S).write z) (a.coord (root i))).val = _ at eq + unfold issue + rw [send_at, eq] + simp only [Fin.is_lt, ↓reduceDIte, Fin.eta, Equiv.symm_apply_apply, reply] + +omit [Fintype E] in +open scoped Classical in +theorem issue_away (tape : B m × B h → B k) {v : B m × B h} (hv : v ∉ Set.range ((root).trans + a.coord)) : + issue c p l hF j x size tape v = none := by + apply send_off + rw [Function.comp_apply, Atlas.around_zero, selected_iff] + exact hv + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Frame +end + +/- # Short selectors in finite extensions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +open Sphere.Surface + +/-- The common selector budget includes the field elements used by a +movement step. Their contribution grows logarithmically with the field. -/ +def selectorBits (A D M T Q : ℕ) := + (A * (1 + Nat.clog 2 (T + 1)) + Nat.clog 2 (Q + 1) * 2) * ((D ^ 5 + 1) * (M + 1)) + +theorem selector_bound (g ℓ D P b : ℕ) : + ∃ A : ℕ, ∀ {T d : ℕ}, Scales g ℓ D T P b d → ∀ F : Type, + let M := room ℓ D g + let H := energy ℓ D (d * b) + let N := depth ℓ D g P (d * b) + let k := selectorBits A D M T (Nat.card F) + M * (2 * N + 1) < A * (1 + T) ^ A ∧ + initialChoices ℓ D b d ≤ 2 ^ k ∧ Local.Frame.budget F P (2 * g) H M N (D ^ 5) ≤ 2 ^ k ∧ + finalChoices g ℓ D P b d ≤ 2 ^ k := by + obtain ⟨A, hA⟩ := choice_bound g ℓ D P b + refine ⟨A, ?_⟩ + intro T d sc F M H N k + obtain ⟨hr, hv⟩ := hA sc + let a := initialChoices ℓ D b d + let x := moveChoices g ℓ D P b d + let c := finalChoices g ℓ D P b d + let L := (D ^ 5 + 1) * (M + 1) + let t := 1 + Nat.clog 2 (T + 1) + let q := Nat.clog 2 (Nat.card F + 1) + change a * x * c ≤ 2 ^ (A * t) at hv + have ha : 0 < a := by unfold a initialChoices; positivity + have hc : 0 < c := by unfold c finalChoices; positivity + have hx : 0 < x := by unfold x moveChoices branches breadth window; positivity + have hb : branches P (2 * g) H M N ≤ x := Nat.le_self_pow (by positivity) _ + have h₀ : A * t ≤ k := (Nat.le_add_right _ _).trans (Nat.le_mul_of_pos_right _ (show 0 + < L by unfold L; positivity)) + have hall : a * x * c ≤ 2 ^ k := hv.trans (Nat.pow_le_pow_right (by decide) h₀) + refine ⟨hr, (Nat.le_mul_of_pos_right a hx).trans ((Nat.le_mul_of_pos_right _ hc).trans hall), + ?_, (Nat.le_mul_of_pos_left c (Nat.mul_pos ha hx)).trans hall⟩ + have hcore : (M + 1) * window P (2 * g) H N ^ 2 * (N + 1) ≤ 2 ^ (A * t) := + (Nat.le_mul_of_pos_right _ (by positivity : 0 < (M * (2 * N) + 1) ^ 2)).trans + (hb.trans ((Nat.le_mul_of_pos_left x ha).trans ((Nat.le_mul_of_pos_right _ hc).trans hv))) + change ((M + 1) * window P (2 * g) H N ^ 2 * (N + 1) * (Nat.card F + 1) ^ 2) ^ L ≤ 2 ^ ((A * t + + q * 2) * L) + conv_rhs => rw [pow_mul (2 : ℕ) (A * t + q * 2), pow_add (2 : ℕ) (A * t), pow_mul (2 : ℕ) q] + exact Nat.pow_le_pow_left (Nat.mul_le_mul hcore (Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) + _) _)) _ + +end MatrixMultiplicationAllFields.MatrixExponent.Rounds.SphereScale +end + +/- +# Routing the reply by a second neighborhood lookup + +Repeated addresses at the origin carry identical replies. At an +occupied site, all replies come from the same initiator. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Coloring +variable {F V E T X J L N : Type} [Field F] [Fintype F] + {r t m d h U R Q M g H D b : ℕ} (p l : ℕ) [ExpChar F p] + (hF : M * (2 * D + 1) < Fintype.card F) (j : Fin (R * M)) + +local notation "Meta" => Metadata F r t R Q U M N + +open scoped Classical in +/-- Returns `some h.choose_spec.choose` when `h : ∃ i v, f i = some v` holds, and `none` +otherwise. -/ +def chooseReply {α β : Type} (f : α → Option β) := + if h : ∃ i v, f i = some v then some h.choose_spec.choose else none + +open scoped Classical in +private theorem choose_some {α β : Type} (f : α → Option β) (v : β) + (h : ∃ i, f i = some v) (hu : ∀ i w, f i = some w → w = v) : + chooseReply f = some v := by + have e : ∃ i v, f i = some v := ⟨h.choose, v, h.choose_spec⟩ + rw [chooseReply, dite_eq_left e, hu _ _ e.choose_spec.choose_spec] + +open scoped Classical in +private theorem choose_none {α β : Type} (f : α → Option β) (h : ∀ i, f i = none) : + chooseReply f = none := by simp [chooseReply, h] + +open scoped Classical in +/-- The route of type `Meta`, constructed using `chooseReply (fun i => send p l hF j g H (data +i) (index i))`. -/ +def route (g H : ℕ) (data : B ((d + 1) * (U + 1)) → B ((d + 1) * U) → Meta) + (index : B ((d + 1) * (U + 1)) → ℕ) : Meta := + let msg := chooseReply (fun i => send p l hF j g H (data i) (index i)) + (data 0 0).map fun u => (u.1, u.2.1, u.2.2.1, msg.elim u.2.2.2 (fun m => m.apply u.1 u.2.2.2)) + +namespace Frame +variable [Fintype V] [Fintype E] {a : Atlas V E m d h} + {π : Palette a (2 * U + 2) R} {ref : Reference J L N V E T X} {pos : V → Fin M → F} + {origin : Stage F r t T V E X} (c : Palette a (horizon U (R * M) 0) Q) + (x : Frame (π.plan pos) ref origin (p ^ l) g H Q j.val) (size : V → ℕ) + (bk : budget F (p ^ l) g H M D U ≤ 2 ^ b) + (sel : Wave.Index (commands c p l hF j x)) + +local notation "C" => commands c p l hF j x +local notation "I" => Fin (Plan.count (π.plan pos) j) +local notation "root" => Plan.root (π.plan pos) j +local notation "A" => π.records c pos x.record (info size x) +local notation "S" => code c p l hF j x bk +local notation "A'" => + π.records c pos (Wave.update C x.record sel) (Wave.carryInfo C sel (info size x)) + +open scoped Classical in +theorem routed (v : B m × B h) : + route p l hF j g H (fun i => A ∘ a.around U (a.around (U + 1) v i)) + (fun i => ((S).write sel (a.around (U + 1) v i)).val) = A' v := by + let recv i := issue c p l hF j x size ((S).write sel) (a.around (U + 1) v i) + unfold route + simp only [Function.comp_apply, Atlas.around_zero] + change (A v).map (fun u => (u.1, u.2.1, u.2.2.1, + (chooseReply recv).elim u.2.2.2 (fun m => m.apply u.1 u.2.2.2))) = _ + by_cases e : v ∈ Set.range a.coord + swap + · rw [Palette.records_away _ _ _ _ _ e, Palette.records_away _ _ _ _ _ e] + rfl + obtain ⟨w, rfl⟩ := e + rw [Palette.records_at, Palette.records_at] + have cand (i u) (hu : recv i = some u) : + ∃ k : I, a.near (U + 1) (root k) w ∧ u = reply c p l hF j x sel size k := by + let v := a.around (U + 1) (a.coord w) i + have hc : v ∈ Set.range ((root).trans a.coord) := by + by_contra hn + have h := issue_away c p l hF j x size ((S).write sel) hn + exact Option.some_ne_none u (hu.symm.trans h) + obtain ⟨k, hk⟩ := hc + change a.coord (root k) = v at hk + refine ⟨k, ((a.around_iff _ _ _).mp ⟨i, hk.symm⟩).symm, ?_⟩ + change issue c p l hF j x size ((S).write sel) v = some u at hu + rw [← hk, issue_at] at hu + exact Option.some.inj hu.symm + by_cases h : ∃ k : I, a.near (U + 1) (root k) w + · obtain ⟨k, hk⟩ := h + have hm : chooseReply recv = some (reply c p l hF j x sel size k) := by + apply choose_some + · obtain ⟨i, hi⟩ := (a.around_iff _ _ _).mpr hk.symm + exact ⟨i, by unfold recv; rw [hi, issue_at]⟩ + · intro i u hu + obtain ⟨k', hk', rfl⟩ := cand i u hu + rw [sole j hk' hk] + rw [hm, receive c p l hF j x sel size w k hk] + rfl + · push Not at h + have hm : chooseReply recv = none := choose_none _ (by + intro i + cases e : recv i with + | none => rfl + | some u => + obtain ⟨k, hk, _⟩ := cand i u e + exact (h k hk).elim) + rw [hm, untouched c p l hF j x sel size w h] + rfl + +end Frame +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# Common format of an entire wave schedule + +The fields of a world may vary with the preceding expansion choices. +Only short metadata records are materialized. Exterior bits pass +through unchanged, in a separate format. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Assembly Coloring + +open scoped Classical in +/-- Common numerical parameters across the family of input states. -/ +structure Design where + /-- The `Design` field of type `ℕ`. -/ + r : ℕ + /-- The `Design` field of type `ℕ`. -/ + t : ℕ + /-- The `Design` field of type `ℕ`. -/ + m : ℕ + /-- The `Design` field of type `ℕ`. -/ + d : ℕ + /-- The `Design` field of type `ℕ`. -/ + h : ℕ + /-- The `Design` field of type `ℕ`. -/ + U : ℕ + /-- The `Design` field of type `ℕ`. -/ + R : ℕ + /-- The `Design` field of type `ℕ`. -/ + Q : ℕ + /-- The `Design` field of type `ℕ`. -/ + M : ℕ + /-- The `Design` field of type `ℕ`. -/ + g : ℕ + /-- The `Design` field of type `ℕ`. -/ + H : ℕ + /-- The `Design` field of type `ℕ`. -/ + D : ℕ + /-- The `Design` field of type `ℕ`. -/ + p : ℕ + /-- The `Design` field of type `ℕ`. -/ + l : ℕ + +namespace Design +variable (a : Design) + +open scoped Classical in +/-- Computes the row by the application `Metadata F a.r a.t a.R a.Q a.U a.M N`. -/ +abbrev row (F N : Type) := Metadata F a.r a.t a.R a.Q a.U a.M N +open scoped Classical in +/-- The quantity computed by `a.R * a.M`. -/ +abbrev waves := a.R * a.M +open scoped Classical in +/-- The quantity computed by `a.p ^ a.l`. -/ +abbrev chart := a.p ^ a.l +open scoped Classical in +/-- Computes the port by the application `Fmt.rows a.m a.d a.h (.addr j)`. -/ +abbrev port (j : ℕ) := Fmt.rows a.m a.d a.h (.addr j) +open scoped Classical in +/-- Indexes the menu by the coordinates of `B j → A × a.row F N`. -/ +abbrev Menu (F N A : Type) (j : ℕ) := B j → A × a.row F N + +end Design + +open scoped Classical in +/-- A scenario supplies the interpretation of the records and a linear +closure, which may sum over the private selectors of all its cells. -/ +structure Scenario (F N A : Type) [Field F] (a : Design) (x y : Wire) where + /-- The type of vertices. -/ + V : Type + /-- The type of edges. -/ + E : Type + /-- The `Scenario` component of type `Type`. -/ + T : Type + /-- The `Scenario` component of type `Type`. -/ + X : Type + /-- The `Scenario` component of type `Type`. -/ + J : Type + /-- The `Scenario` component of type `Type`. -/ + L : Type + [fv : Fintype V] + [fe : Fintype E] + /-- The `Scenario` component of type `Atlas V E a.m a.d a.h`. -/ + atlas : Atlas V E a.m a.d a.h + /-- The `Scenario` component of type `Palette atlas (2 * a.U + 2) a.R`. -/ + π : Palette atlas (2 * a.U + 2) a.R + /-- The remaining component of type `Palette atlas (horizon a.U a.waves 0) a.Q`. -/ + c : Palette atlas (horizon a.U a.waves 0) a.Q + /-- The `Scenario` component of type `Reference J L N V E T X`. -/ + ref : Reference J L N V E T X + /-- The starting coordinate of type `Stage F a.r a.t T V E X`. -/ + origin : Stage F a.r a.t T V E X + /-- The `Scenario` component of type `V → Fin a.M → F`. -/ + pos : V → Fin a.M → F + /-- The size parameter carried by `Scenario`, with type `V → ℕ`. -/ + size : V → ℕ + /-- The `Scenario` component of type `B a.m × B a.h → A`. -/ + header : B a.m × B a.h → A + controls : ∃ keys ext, origin.Controls keys ext + room : ∀ z, origin.Reach a.chart a.g a.H a.U z → z.Room a.M a.D + /-- The `Scenario` component of type `Val x → Val y → (X → F) →ₗ[F] F`. -/ + close : Val x → Val y → (X → F) →ₗ[F] F + +attribute [instance] Scenario.fv Scenario.fe + +namespace Scenario + +variable {F N A : Type} [Field F] {a : Design} {x y : Wire} (w : Scenario F N A a x y) + {j : ℕ} + +open scoped Classical in +/-- The value specified by `Frame (w.π.plan w.pos) w.ref w.origin a.chart a.g a.H a.Q i`. -/ +abbrev At (i : ℕ) := Frame (w.π.plan w.pos) w.ref w.origin a.chart a.g a.H a.Q i + +open scoped Classical in +/-- The value specified by `(w.header v, w.π.records w.c w.pos s.record (s.info w.size) v)`. -/ +def stored {i : ℕ} (s : w.At i) (v : B a.m × B a.h) : A × a.row F N := + (w.header v, w.π.records w.c w.pos s.record (s.info w.size) v) + +open scoped Classical in +/-- The data for the code construction, including `frame`, `tape`, `host`, `read`. -/ +structure Code (i : ℕ) (menu : a.Menu F N A j) where + /-- The `Code` component of type `w.At i`. -/ + frame : w.At i + /-- The `Code` component of type `(a.port j).obj`. -/ + tape : (a.port j).obj + host : ∀ v, (tape v).1 = w.atlas.graph v + read : ∀ v, menu ((tape v.1).2 v.2) = w.stored frame v + +open scoped Classical in +/-- Computes the eval by the application `w.close z u (s.stage.value a.chart)`. -/ +def eval {i : ℕ} (s : w.At i) (z : Val x) (u : Val y) : F := + w.close z u (s.stage.value a.chart) + +end Scenario + +universe v +variable {F N A : Type} [Field F] {x y : Wire} {a : Design} {I : Type v} {j : ℕ} + +open scoped Classical in +/-- Indexes the snapshot by the coordinates of `Σ s, (w s).Code i menu eval s := (w s.1).eval +s.2.frame port := (a.port j).pair Z encode s p q := (s.2.tape, payload s.1 p q)`. -/ +def snapshot (w : I → Scenario F N A a x y) (Z : Format) (payload : I → Val x → Val y → Z.obj) + (i : ℕ) (menu : a.Menu F N A j) : Snapshot.{v} F x y where + state := Σ s, (w s).Code i menu + eval s := (w s.1).eval s.2.frame + port := (a.port j).pair Z + encode s p q := (s.2.tape, payload s.1 p q) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Waves/Window.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Waves/Window.lean new file mode 100644 index 0000000000..df789aa229 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Waves/Window.lean @@ -0,0 +1,951 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Panel.Wave +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Update +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Control.Initial + +/-! +# A fixed number of waves independent of the host size + +The first coloring schedules disjoint motion regions. A second +coloring separates key names over the entire propagation radius. +An absent station slot is harmless. Motion never creates a pending +station at a new position between waves. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +variable {F V E : Type} {m d h U q W : ℕ} {a : Atlas V E m d h} + +open scoped Classical in +/-- Separation still needed after `i` waves. -/ +def horizon (U W i : ℕ) := 4 * U * (W - i) + 1 + +open scoped Classical in +theorem horizon_one (U W i : ℕ) : 1 ≤ horizon U W i := by unfold horizon; omega + +open scoped Classical in +theorem horizon_step (U : ℕ) (i : Fin W) : + 2 * U + horizon U W (i.val + 1) + 2 * U = horizon U W i.val := by + unfold horizon + rw [show W - i.val = (W - (i.val + 1)) + 1 by omega] + ring + +open scoped Classical in +/-- The data for the plan construction, including `count`, `root`, `pos`, `same`. -/ +structure Plan (F : Type) (π : Palette a (2 * U + 2) q) (W : ℕ) where + /-- The number of entries of type `Fin W → ℕ`. -/ + count : Fin W → ℕ + /-- The root of type `∀ i, Fin (count i) ↪ V`. -/ + root : ∀ i, Fin (count i) ↪ V + /-- The `Plan` component of type `∀ i, Fin (count i) → F`. -/ + pos : ∀ i, Fin (count i) → F + same : ∀ i j k, π.mark (root i j) = π.mark (root i k) + +namespace Plan + +variable {π : Palette a (2 * U + 2) q} (p : Plan F π W) + +open scoped Classical in +/-- The set of values attained by `(fun j => (p.root i j, p.pos i j))`. -/ +def targets (i : Fin W) : Set (V × F) := Set.range (fun j => (p.root i j, p.pos i j)) + +open scoped Classical in +/-- Uses `{x | ∃ i : Fin W, j ≤ i.val ∧ x ∈ p.targets i}` as the representation. -/ +def remaining (j : ℕ) : Set (V × F) := {x | ∃ i : Fin W, j ≤ i.val ∧ x ∈ p.targets i} + +open scoped Classical in +theorem exhausted : p.remaining W = ∅ := by + ext x + simp only [remaining, Set.mem_ofPred_eq, Set.mem_empty_iff_false, iff_false] + rintro ⟨i, h, _⟩ + exact Nat.not_le_of_gt i.isLt h + +open scoped Classical in +theorem remove (i : Fin W) : p.remaining i.val \ p.targets i ⊆ p.remaining (i.val + 1) := by + rintro x ⟨⟨j, h, hx⟩, hi⟩ + have hn : j ≠ i := by rintro rfl; exact hi hx + exact ⟨j, by have := Fin.val_injective.ne hn; omega, hx⟩ + +end Plan + +namespace Palette + +variable [Fintype V] (π : Palette a (2 * U + 2) q) {M : ℕ} + +open scoped Classical in +/-- The subtype of `v` satisfying `π.mark v = i`. -/ +abbrev group (i : Fin q) := {v // π.mark v = i} + +open scoped Classical in +/-- Embeds `Fin (Fintype.card (π.group i))` into `V`. -/ +def roots (i : Fin q) : Fin (Fintype.card (π.group i)) ↪ V := + (Fintype.equivFin (π.group i)).symm.toEmbedding.trans (Function.Embedding.subtype _) + +open scoped Classical in +theorem mem_roots (i : Fin q) (v : V) : v ∈ Set.range (π.roots i) ↔ π.mark v = i := by + constructor + · rintro ⟨j, rfl⟩ + exact ((Fintype.equivFin (π.group i)).symm j).2 + · intro h + exact ⟨Fintype.equivFin (π.group i) ⟨v, h⟩, by simp [roots]⟩ + +open scoped Classical in +/-- One phase per color and initial local slot. -/ +def plan (name : V → Fin M → F) : Plan F π (q * M) where + count i := Fintype.card (π.group (finProdFinEquiv.symm i).1) + root i := π.roots (finProdFinEquiv.symm i).1 + pos i j := name (π.roots (finProdFinEquiv.symm i).1 j) (finProdFinEquiv.symm i).2 + same _ j k := ((π.mem_roots _ _).mp ⟨j, rfl⟩).trans ((π.mem_roots _ _).mp ⟨k, rfl⟩).symm + +open scoped Classical in +theorem plan_covers (name : V → Fin M → F) (v : V) (i : Fin M) : + (v, name v i) ∈ (π.plan name).remaining 0 := by + let j := finProdFinEquiv (π.mark v, i) + have he : finProdFinEquiv.symm j = (π.mark v, i) := finProdFinEquiv.symm_apply_apply _ + obtain ⟨k, hk⟩ := (π.mem_roots (finProdFinEquiv.symm j).1 v).mpr (by rw [he]) + refine ⟨j, Nat.zero_le _, k, ?_⟩ + change (_, name _ _) = _ + exact Prod.ext hk (congrArg₂ name hk (congrArg Prod.snd he)) + +end Palette +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# One phase of a localized surface expansion + +A frame carries the mathematical stage as well as a short-name record. +Only the record, catalogs and choice indices are used to compute the +next record. The actual stage witnesses the contraction identity. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +variable {F V E T X N J L : Type} [Field F] {r t m d h U R Q W : ℕ} + {a : Atlas V E m d h} {π : Palette a (2 * U + 2) R} + +open scoped Classical in +/-- The data for the frame construction, including `stage`, `address`, `record`, `match'`, +`clean`. -/ +structure Frame (plan : Plan F π W) (ref : Reference J L N V E T X) + (origin : Stage F r t T V E X) (P g H Q i : ℕ) where + /-- The `Frame` component of type `Stage F r t T V E X`. -/ + stage : Stage F r t T V E X + /-- The address of each position carried by `Frame`, with type `V ⊕ ℕ → Stamp Q W U`. -/ + address : V ⊕ ℕ → Stamp Q W U + /-- The `Frame` component of type `Record F r t V E (Stamp Q W U) N`. -/ + record : Record F r t V E (Stamp Q W U) N + match' : Matches ref.world address stage record + clean : Clean (a.near (horizon U W i)) stage address i + reach : origin.Reach P g H U stage + layout : stage.Layout a.src a.dst g + valid : stage.Valid U + calm : Calm stage + todo : pending stage ⊆ plan.remaining i + +namespace Frame + +variable {plan : Plan F π W} {ref : Reference J L N V E T X} + {origin : Stage F r t T V E X} {P g H i : ℕ} + +open scoped Classical in +theorem stopped (x : Frame plan ref origin P g H Q W) : x.stage.Stopped := by + intro v s hs n hn + have he := x.todo (show (v, s.pos) ∈ pending x.stage from ⟨s, hs, rfl, n, hn⟩) + rw [plan.exhausted] at he + exact he + +open scoped Classical in +/-- Computes the info by the application `catalog size x.address x.stage`. -/ +def info (size : V → ℕ) (x : Frame plan ref origin P g H Q i) := catalog size x.address x.stage + +variable [Fintype V] [Fintype E] [Fintype F] + (c : Palette a (horizon U W 0) Q) (p l : ℕ) [ExpChar F p] {M D : ℕ} + (hF : M * (2 * D + 1) < Fintype.card F) (j : Fin W) + (x : Frame plan ref origin (p ^ l) g H Q j.val) + +open scoped Classical in +/-- The value specified by `π.wave le_rfl x.record (x.match'.incident x.layout) ref p l g H M D +hF (plan.root j) (plan.pos j) (created c.mark j)`. -/ +def commands := π.wave le_rfl x.record (x.match'.incident x.layout) + ref p l g H M D hF (plan.root j) (plan.pos j) (created c.mark j) + +local notation "C" => commands c p l hF j x + +open scoped Classical in +instance (i : Fin (plan.count j)) : Fintype (C i).vertices := + inferInstanceAs (Fintype (π.vertices U (plan.root j i))) + +open scoped Classical in +theorem prepared : Wave.Prepared C x.record ref := + π.prepared _ _ _ _ _ _ _ _ _ _ _ _ _ _ (plan.same j) + +open scoped Classical in +theorem extent (v w : V) (h : Wave.Together C v w) : a.near (2 * U) v w := by + rcases h with rfl|⟨i, hv, hw⟩ + · exact .refl _ _ _ + · have he := (π.vertex_range le_rfl).mp hv + have hf := (π.vertex_range le_rfl).mp hw + simpa [two_mul] using he.symm.join hf + +open scoped Classical in +theorem space (v w s t : V) (e : a.near (horizon U W (j.val + 1)) v w) + (hv : Wave.Together C v s) (hw : Wave.Together C w t) : + a.near (horizon U W j.val) s t := by + rw [← horizon_step U j] + exact ((extent c p l hF j x _ _ hv).symm.join e).join (extent c p l hF j x _ _ hw) + +open scoped Classical in +theorem weight_ordered (i : Fin (plan.count j)) : + (C i).action.Ordered (created c.mark j (plan.root j i)) 0 U := + π.wave_ordered _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +open scoped Classical in +theorem targets : Set.range (Command.target ∘ C) = plan.targets j := by + unfold Plan.targets + congr 1 + funext i + exact π.wave_target _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +end Frame +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Advancing a clean frame by independent local scripts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Frame + +variable {F V E T X N J L : Type} [Field F] {r t m d h U R Q W : ℕ} + {a : Atlas V E m d h} {π : Palette a (2 * U + 2) R} + {plan : Plan F π W} {ref : Reference J L N V E T X} + {origin : Stage F r t T V E X} {g H : ℕ} + +variable [Fintype V] [Fintype E] [Fintype F] + (c : Palette a (horizon U W 0) Q) (p l : ℕ) [ExpChar F p] {M D : ℕ} + (hF : M * (2 * D + 1) < Fintype.card F) (j : Fin W) + (x : Frame plan ref origin (p ^ l) g H Q j.val) + +local notation "C" => commands c p l hF j x + +omit [Fintype V] [Fintype E] [Fintype F] [ExpChar F p] in +open scoped Classical in +private theorem known : Known x.stage := fun v k h => x.match'.known v k h + +open scoped Classical in +private theorem advance_clean {s : Stage F r t T V E X} {β : V ⊕ ℕ → Stamp Q W U} + {i : Wave.Index C} (ho : Wave.Origins C i x.stage s x.address β) : + Clean (a.near (horizon U W (j.val + 1))) s β (j.val + 1) := by + apply ho.clean c.mark j x.clean ?_ (space c p l hF j x) + (plan.root j) ?_ (weight_ordered c p l hF j x) + · intro v w e + apply c.distinguish (e.mono ?_) + unfold horizon + gcongr + omega + · intro i + exact (π.vertex_range le_rfl).mpr (.refl _ _ _) + +open scoped Classical in +private theorem advance_todo {s : Stage F r t T V E X} {β : V ⊕ ℕ → Stamp Q W U} + {i : Wave.Index C} (h : Wave.Finish C x.stage s x.address β i) : + pending s ⊆ plan.remaining (j.val + 1) := by + apply Set.Subset.trans _ (plan.remove j) + intro v hv + obtain ⟨hp, hn⟩ := h.pending hv + rw [targets] at hn + exact ⟨x.todo hp, hn⟩ + +open scoped Classical in +/-- For each tuple of regional choices, the next frame has a record +and key catalogs computed by independent updates. Its contraction +has the product of the local branch weights. -/ +theorem advance {keys : V → X → X → Prop} {ext : T → X → X → Prop} + (ctrl : origin.Controls keys ext) (room : ∀ y, origin.Reach (p ^ l) g H U y → y.Room M D) : + ∃ f : Wave.Index C → Frame plan ref origin (p ^ l) g H Q (j.val + 1), + (∀ i, (f i).record = Wave.update C x.record i) ∧ + (∀ i size, info size (f i) = Wave.carryInfo C i (info size x)) ∧ + ∀ y, x.stage.value (p ^ l) y = ∑ i, (∏ v, (C v).action.weight (i v)) * (f i).stage.value (p ^ + l) y := by + have hp := prepared c p l hF j x + obtain ⟨s, β, h, he⟩ := Wave.execute C hp.separate x.stage x.address (hp.inputs x.match') + x.layout x.valid (fun y hy => room _ (x.reach.trans hy)) x.calm + have o i := (h i).history.origins hp.separate (x.reach.controls ctrl) (known p l j x) + let f (i : Wave.Index C) : Frame plan ref origin (p ^ l) g H Q (j.val + 1) := + { stage := s i, address := β i, record := Wave.update C x.record i + match' := hp.outputs x.match' (h i) + clean := advance_clean c p l hF j x (o i) + reach := x.reach.trans (h i).reach + layout := ⟨x.layout.loopless, (h i).reach.ports_eq.symm ▸ x.layout.incident, + (h i).reach.ports_eq.symm ▸ x.layout.unique, (h i).reach.ports_eq.symm ▸ x.layout.degree⟩ + valid := (h i).valid, calm := (h i).calm, todo := advance_todo c p l hF j x (h i) } + refine ⟨f, fun _ => rfl, fun i size => ?_, he⟩ + exact (h i).catalog hp.separate (o i) c.mark j x.clean + (fun v a b => space c p l hF j x _ _ _ _ (.refl _ _ v)) (plan.root j) + (weight_ordered c p l hF j x) (known p l j x) size + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Frame +end + +/- # Initializing a wave schedule from the original positions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +variable {F V E T X N K J L : Type} [Field F] {r t m d h U R Q M P g H : ℕ} + {a : Atlas V E m d h} (π : Palette a (2 * U + 2) R) + (c : Palette a (horizon U (R * M) 0) Q) + +open scoped Classical in +/-- In the case `.inl v`, this construction gives `(c.mark v, none)`. -/ +def startName [NeZero Q] : V ⊕ ℕ → Stamp Q (R * M) U + | .inl v => (c.mark v, none) + | .inr _ => (0, none) + +open scoped Classical in +/-- Transforms the indexed data by `(((G.rows v)[i.val]?).map Entry.pos).getD 0`. -/ +def Record.positions (G : Record F r t V E K N) (v : V) (i : Fin M) : F := + (((G.rows v)[i.val]?).map Entry.pos).getD 0 + +variable {ref : Reference J L N V E T X} {origin : Stage F r t T V E X} + {G : Record F r t V E (Stamp Q (R * M) U) N} + +open scoped Classical in +/-- The plan tries every original slot once. Matching the metadata +ensures that all initial active positions are covered. -/ +def Frame.initial [Fintype V] [NeZero Q] (h : Matches ref.world (startName c) origin G) + (single : ∀ v, origin.footprint v = {.inl v}) (hcount : ∀ v, + (origin.scene.cell v).stations.length ≤ M) + (layout : origin.Layout a.src a.dst g) (hv : origin.Valid U) (hc : Calm origin) : + Frame (π.plan (G.positions (M := M))) ref origin P g H Q 0 where + stage := origin + address := startName c + record := G + match' := h + clean := by + constructor + · intro v w hv j hj k hk he + simp only [single, Finset.mem_singleton] at hj hk + subst j k + exact congrArg Sum.inl (c.distinguish hv (congrArg Prod.fst he)) + · intro v j hj + have e : j = .inl v := by simpa [single] using hj + simp [e, earlier, startName] + reach := .refl + layout := layout + valid := hv + calm := hc + todo := by + rintro ⟨v, z⟩ ⟨b, hb, eq, hact⟩ + obtain ⟨i, hi⟩ := List.get_of_mem hb + let j : Fin M := ⟨i.val, i.isLt.trans_le (hcount v)⟩ + have hlen : i.val < (G.rows v).length := (h.rows v).length_eq ▸ i.isLt + have pos := ((h.rows v).get i.isLt hlen).pos + change ((origin.scene.cell v).stations.get i).pos = _ at pos + rw [hi, eq] at pos + have he : G.positions v j = z := by + simp only [Record.positions, j, List.getElem?_eq_getElem hlen, Option.map_some, + Option.getD_some] + exact pos.symm + rw [← he] + exact π.plan_covers (G.positions (M := M)) v j + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# Printing a regional script input + +Each end of a seam carries its pair of colors and energy. A panel +can be recovered uniquely from the set of colored cell records, +even if a neighborhood enumeration visits a cell repeatedly. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Finset +variable {F K N J L V E : Type} {r t q U : ℕ} + +open scoped Classical in +/-- The data for the body construction, including `rows`, `ports`, `footprint`. -/ +structure Body (F : Type) (r t q : ℕ) (K N : Type) where + /-- The indexed rows of type `List (Entry F r t K N)`. -/ + rows : List (Entry F r t K N) + /-- The `Body` component of type `List ((Fin q × Fin q) × F × ℕ)`. -/ + ports : List ((Fin q × Fin q) × F × ℕ) + /-- The `Body` component of type `Finset K`. -/ + footprint : Finset K + +open scoped Classical in +/-- The tile of type `Catalog K` for the given inputs. -/ +structure Tile (F : Type) (r t q : ℕ) (K N : Type) extends Body F r t q K N where + /-- The `Tile` component of type `Catalog K`. -/ + catalog : Catalog K + +open scoped Classical in +/-- Transforms the indexed data by `⟨a.rows i, (a.ports i).map fun v => (tag v.1, v.2, a.level +v.1), a.footprint i⟩`. -/ +def Record.body (a : Record F r t J L K N) (tag : L → Fin q × Fin q) (i : J) : Body F r t q K N := + ⟨a.rows i, (a.ports i).map fun v => (tag v.1, v.2, a.level v.1), a.footprint i⟩ + +namespace View +variable {a : Record F r t J L K N} {b : Record F r t V E K N} {f : J ↪ V} {g : L ↪ E} + +open scoped Classical in +theorem body (h : View b f g a) (tag : E → Fin q × Fin q) (i : J) : + b.body tag (f i) = a.body (tag ∘ g) i := by + simp [Record.body, h.rows, h.footprint, h.ports, h.level, Function.comp_def] + +end View +namespace Panel + +variable (p : Panel F r t q U K N) + +open scoped Classical in +/-- The indexed operation `univ.image (fun i : p.vertices => (i.val, p.input.body Subtype.val +i))`. -/ +def printed := univ.image (fun i : p.vertices => (i.val, p.input.body Subtype.val i)) + +open scoped Classical in +/-- Every edge in the panel occurs in a port list. -/ +def complete : Prop := ∀ j : p.edges, ∃ i u, (j, u) ∈ p.input.ports i + +open scoped Classical in +theorem colors : p.printed.image Prod.fst = p.vertices := by + ext i + simp [printed] + +open scoped Classical in +theorem endpoints (hc : p.complete) (j : Fin q × Fin q) : + j ∈ p.edges ↔ ∃ i ∈ p.printed, ∃ x ∈ i.2.ports, x.1 = j := by + constructor + · intro hj + obtain ⟨i, u, hu⟩ := hc ⟨j, hj⟩ + refine ⟨_, mem_image_of_mem _ (mem_univ i), _, List.mem_map_of_mem hu, rfl⟩ + · rintro ⟨i, hi, x, hx, rfl⟩ + obtain ⟨i, _, rfl⟩ := mem_image.mp hi + obtain ⟨⟨j, z⟩, _, rfl⟩ := List.mem_map.mp hx + exact j.property + +open scoped Classical in +private theorem input_eq {S : Finset (Fin q)} {T : Finset (Fin q × Fin q)} + (a b : Record F r t ↥S ↥T K N) (eq : ∀ i, a.body Subtype.val i = b.body Subtype.val i) + (hc : ∀ j : T, ∃ i x, (j, x) ∈ a.ports i) : a = b := by + obtain ⟨ar, ap, al, af⟩ := a + obtain ⟨br, bp, bl, bf⟩ := b + have hp (i : S) := congrArg Body.ports (eq i) + change ∀ i : S, (ap i).map (fun x => (x.1.val, x.2, al x.1)) = + (bp i).map (fun x => (x.1.val, x.2, bl x.1)) at hp + congr 1 + · exact funext fun i => congrArg Body.rows (eq i) + · funext i + have he := congrArg (List.map (fun t => (t.1, t.2.1))) (hp i) + apply (Subtype.val_injective.prodMap Function.injective_id).list_map + simp only [List.map_map, Function.comp_def] at he + exact he + · funext j + obtain ⟨i, z, h⟩ := hc j + have hi : (j.val, z, al j) ∈ (bp i).map (fun x => (x.1.val, x.2, bl x.1)) := by + rw [← hp]; exact List.mem_map_of_mem h + obtain ⟨⟨k, y⟩, _, he⟩ := List.mem_map.mp hi + have hk : k = j := Subtype.ext (congrArg Prod.fst he) + subst k + exact (congrArg (fun u => u.2.2) he).symm + · exact funext fun i => congrArg Body.footprint (eq i) + +open scoped Classical in +/-- Printing loses no information on complete panels. -/ +theorem unique (v : Panel F r t q U K N) (hc : p.complete) (hc' : v.complete) + (hv : p.printed = v.printed) (h₁ : p.center.val = v.center.val) + (h₂ : p.pos = v.pos) (h₃ : p.fresh = v.fresh) : p = v := by + have ha : p.vertices = v.vertices := by rw [← p.colors, ← v.colors, hv] + have hb : p.edges = v.edges := by ext j; rw [p.endpoints hc, v.endpoints hc', hv] + obtain ⟨A, B, c, a, y, g⟩ := p + obtain ⟨A', B', c', a', y', g'⟩ := v + dsimp only at ha hb h₁ h₂ h₃ + subst A' B' y' g' + have eq : c = c' := Subtype.ext h₁ + subst c' + congr 1 + apply input_eq a a' _ hc + intro i + have h : (i.val, a.body Subtype.val i) ∈ (Panel.mk A B c a' y g).printed := by + rw [← hv]; exact mem_image_of_mem _ (mem_univ i) + obtain ⟨j, _, he⟩ := mem_image.mp h + have hj : j = i := Subtype.ext (congrArg Prod.fst he) + subst j + exact (congrArg Prod.snd he).symm + +end Panel +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # Reading the geometric neighborhood in short colors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Finset +variable {F V E K N : Type} {r t m d h U q : ℕ} [Fintype V] [Fintype E] + +open scoped Classical in +/-- Computes the ball by the application `univ.filter (a.near U v)`. -/ +def Atlas.ball (a : Atlas V E m d h) (U : ℕ) (v : V) := univ.filter (a.near U v) + +namespace Palette +variable {a : Atlas V E m d h} (π : Palette a (2 * U + 2) q) + (G : Record F r t V E K N) (hG : Incident G a) (v : V) (z : F) (ν : ℕ → K) + +include hG in +open scoped Classical in +theorem panel_complete : (π.panel U G v z ν).complete := by + intro j + let e := π.seam U v j + have inc : ∃ w, a.near U v w ∧ e ∈ (G.ports w).map Prod.fst := by + rcases (π.seam_spec U v j).1 with h|h + · exact ⟨a.src e, h, (hG.endpoints _ _).mpr (.inl rfl)⟩ + · exact ⟨a.dst e, h, (hG.endpoints _ _).mpr (.inr rfl)⟩ + obtain ⟨w, hw, he⟩ := inc + obtain ⟨i, rfl⟩ := (π.vertex_range le_rfl).mpr hw + rw [(π.view le_rfl hG).ports i, List.map_map] at he + obtain ⟨⟨k, l⟩, hk, eq⟩ := List.mem_map.mp he + have : k = j := (π.seam U v).injective eq + subst k + exact ⟨i, l, hk⟩ + +include hG in +open scoped Classical in +theorem panel_printed : (π.panel U G v z ν).printed = + (a.ball U v).image (fun i => (π.mark i, G.body π.edge i)) := by + have eq : π.edge ∘ π.seam U v = Subtype.val := funext fun i => (π.seam_spec U v i).2 + have body (i : π.vertices U v) : + (π.extract U v G).body Subtype.val i = G.body π.edge (π.vertex U v i) := by + rw [(π.view le_rfl hG).body, eq] + change univ.image (fun i : π.vertices U v => (i.val, (π.extract U v G).body Subtype.val i)) = _ + ext p + simp only [mem_image, mem_univ, true_and, Atlas.ball, mem_filter_univ] + constructor + · rintro ⟨i, rfl⟩ + exact ⟨π.vertex U v i, (π.vertex_spec U v i).1, + Prod.ext (π.vertex_spec U v i).2 (body i).symm⟩ + · rintro ⟨w, hw, rfl⟩ + obtain ⟨i, rfl⟩ := (π.vertex_range le_rfl).mpr hw + exact ⟨i, Prod.ext (π.vertex_spec U v i).2.symm (body i)⟩ + +omit [Fintype E] in +open scoped Classical in +theorem vertex_at {w : V} (hv : a.near (U + 1) v w) (i : π.vertices U v) : + π.mark w = i.val ↔ w = π.vertex U v i := by + refine ⟨fun e => ?_, fun e => e ▸ (π.vertex_spec U v i).2⟩ + apply π.injective_at (by omega) hv ((π.vertex_spec U v i).1.mono (by omega)) + exact e.trans (π.vertex_spec U v i).2.symm + +omit [Fintype V] in +open scoped Classical in +theorem seam_at {w : V} (hv : a.near (U + 1) v w) (e : E) (he : a.src e = w ∨ a.dst e = w) + (i : π.labels U v) : π.edge e = i.val ↔ e = π.seam U v i := by + let j := π.seam U v i + have ht := (π.seam_spec U v i).1.near + refine ⟨fun h => ?_, fun e => e ▸ (π.seam_spec U v i).2⟩ + have both : π.edge e = π.edge j := h.trans (π.seam_spec U v i).2.symm + obtain ⟨hs, hd⟩ := Prod.mk.inj both + apply a.links + rcases he with rfl|rfl + · have hu : a.src e = a.src j := π.injective_at (by omega) hv ht.1 hs + have hnear : a.near 1 (a.src e) (a.dst j) := by rw [hu]; exact a.near_edge j + exact Prod.ext hu (π.injective_at (by omega) (a.near_edge e) hnear hd) + · have hu : a.dst e = a.dst j := π.injective_at (by omega) hv ht.2 hd + have hnear : a.near 1 (a.dst e) (a.src j) := by rw [hu]; exact (a.near_edge j).symm + exact Prod.ext (π.injective_at (by omega) (a.near_edge e).symm hnear hs) hu + +end Palette +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- +# Replies from one local lookup + +The reply lists the changed station rows, key catalogs and seam +levels by color. Receivers keep their original port order. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +open Finset +variable {F K N J L V E : Type} {r t m d h U q : ℕ} + +open scoped Classical in +/-- Indexes the tile set by the coordinates of `Finset (Fin q × Tile F r t q K N)`. -/ +abbrev TileSet (F : Type) (r t q : ℕ) (K N : Type) := Finset (Fin q × Tile F r t q K N) + +open scoped Classical in +/-- Uses `⟨G.body tag v, info v⟩` as the representation. -/ +def Record.tile (G : Record F r t V E K N) (tag : E → Fin q × Fin q) + (info : V → Catalog K) (v : V) : Tile F r t q K N := ⟨G.body tag v, info v⟩ + +open scoped Classical in +/-- The data for the reply construction, including `weight`, `cell`, `level`. -/ +structure Reply (F : Type) (r t q : ℕ) (K N : Type) where + /-- The weight function carried by `Reply`, with type `F`. -/ + weight : F + /-- The `Reply` component of type `Fin q → Option (List (Entry F r t K N) × Finset K × Catalog + K)`. -/ + cell : Fin q → Option (List (Entry F r t K N) × Finset K × Catalog K) + /-- The level at each coordinate of type `Fin q × Fin q → Option ℕ`. -/ + level : Fin q × Fin q → Option ℕ + +open scoped Classical in +/-- The apply of type `Tile F r t q K N`, constructed using `(x.cell v).getD (y.rows, +y.footprint, y.catalog)`. -/ +def Reply.apply (x : Reply F r t q K N) (v : Fin q) (y : Tile F r t q K N) : Tile F r t q K N := + let data := (x.cell v).getD (y.rows, y.footprint, y.catalog) + ⟨⟨data.1, y.ports.map (fun i => (i.1, i.2.1, (x.level i.1).getD i.2.2)), data.2.1⟩, data.2.2⟩ + +open scoped Classical in +/-- Builds `Reply F r t q K N where weight` with the specified `weight`, `cell`, `else`. -/ +def Panel.reply (x : Panel F r t q U K N) (action : Script F r t x.vertices x.edges K N) + (choice : action.I) (input : TileSet F r t q K N) : Reply F r t q K N where + weight := action.weight choice + cell v := if hv : v ∈ x.vertices then + let i := ⟨v, hv⟩ + let seen := (action.result choice).footprint i + some ((action.result choice).rows i, seen, + collect seen (fun j : input => j.val.2.catalog) (action.fresh choice)) + else none + level v := if hv : v ∈ x.edges then some ((action.result choice).level ⟨v, hv⟩) else none + +open scoped Classical in +/-- The indexed operation `s.image (fun i => (i.1, i.2.toBody))`. -/ +def TileSet.bodies (s : TileSet F r t q K N) := + s.image (fun i => (i.1, i.2.toBody)) + +open scoped Classical in +/-- The lookup is defined on arbitrary inputs. A malformed description +or an out-of-range selector gives no reply. -/ +def TileSet.get [Field F] [Fintype F] (s : TileSet F r t q K N) + (p l g H M D : ℕ) [ExpChar F p] (hF : M * (2 * D + 1) < Fintype.card F) + (i : Fin q) (z : F) (f : Fin (U + 1) → K) (j : ℕ) : Option (Reply F r t q K N) := + if h : ∃ a : Panel F r t q U K N, + a.complete ∧ a.printed = s.bodies ∧ a.center.val = i ∧ a.pos = z ∧ a.fresh = f then + let a := h.choose + let u := a.action p l g H M D hF + if hj : j < Fintype.card u.I then + some (a.reply u ((Fintype.equivFin u.I).symm ⟨j, hj⟩) s) else none + else none + +open scoped Classical in +theorem TileSet.get_spec [Field F] [Fintype F] (s : TileSet F r t q K N) + (p l g H M D : ℕ) [ExpChar F p] (hF : M * (2 * D + 1) < Fintype.card F) + (x : Panel F r t q U K N) (hc : x.complete) (he : x.printed = s.bodies) (j : ℕ) : + let u := x.action p l g H M D hF + s.get p l g H M D hF x.center.val x.pos x.fresh j = + if hj : j < Fintype.card u.I then + some (x.reply u ((Fintype.equivFin u.I).symm ⟨j, hj⟩) s) else none := by + have ex : ∃ a : Panel F r t q U K N, + a.complete ∧ a.printed = s.bodies ∧ a.center.val = x.center.val ∧ a.pos = x.pos ∧ a.fresh + = x.fresh := + ⟨x, hc, he, rfl, rfl, rfl⟩ + obtain ⟨h₁, h₂, h₃, h₄, h₅⟩ := ex.choose_spec + have eq := ex.choose.unique x h₁ hc (h₂.trans he.symm) h₃ h₄ h₅ + rw [TileSet.get, dite_eq_left ex, eq] + +namespace Palette +variable [Fintype V] {a : Atlas V E m d h} (π : Palette a (2 * U + 2) q) + (G : Record F r t V E K N) (info : V → Catalog K) (v : V) + +open scoped Classical in +/-- The indexed operation `(a.ball U v).image fun i => (π.mark i, G.tile π.edge info i)`. -/ +def tiles : TileSet F r t q K N := + (a.ball U v).image fun i => (π.mark i, G.tile π.edge info i) + +open scoped Classical in +theorem bodies [Fintype E] (hG : Incident G a) (z : F) (ν : ℕ → K) : + (π.panel U G v z ν).printed = (π.tiles G info v).bodies := by + rw [panel_printed π G hG, TileSet.bodies, tiles, image_image] + rfl + +open scoped Classical in +theorem collect_eq (seen : Finset K) (fresh : List (K × ℕ)) : + collect seen (fun i : π.tiles G info v => i.val.2.catalog) fresh = + collect seen (info ∘ π.vertex U v) fresh := by + ext ⟨k, d⟩ + simp only [mem_collect] + have eq : (∃ i : π.tiles G info v, (k, d) ∈ i.val.2.catalog) ↔ + (∃ i, (k, d) ∈ (info ∘ π.vertex U v) i) := by + constructor + · rintro ⟨⟨_, h⟩, he⟩ + obtain ⟨w, hw, rfl⟩ := mem_image.mp h + obtain ⟨j, rfl⟩ := (π.vertex_range le_rfl).mpr (mem_filter.mp hw).2 + exact ⟨j, he⟩ + · rintro ⟨j, h⟩ + let w := π.vertex U v j + have hw : w ∈ a.ball U v := mem_filter_univ _ |>.mpr (π.vertex_spec U v j).1 + exact ⟨⟨_, mem_image_of_mem _ hw⟩, h⟩ + rw [eq] + +end Palette +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end + +/- # A cell receives at most one reply in a wave -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Frame +variable {F V E T X N J L : Type} [Field F] {r t m d h U R Q W : ℕ} + {a : Atlas V E m d h} {π : Palette a (2 * U + 2) R} + {plan : Plan F π W} {ref : Reference J L N V E T X} + {origin : Stage F r t T V E X} {g H : ℕ} + [Fintype V] [Fintype E] [Fintype F] + (c : Palette a (horizon U W 0) Q) (p l : ℕ) [ExpChar F p] {M D : ℕ} + (hF : M * (2 * D + 1) < Fintype.card F) (j : Fin W) + (x : Frame plan ref origin (p ^ l) g H Q j.val) + +local notation "C" => commands c p l hF j x +local notation "root" => plan.root j +variable (sel : Wave.Index (commands c p l hF j x)) (size : V → ℕ) + +open scoped Classical in +/-- The value specified by `π.panel U x.record (root i) (plan.pos j i) (created (U := U) c.mark +j (root i))`. -/ +def panel (i : Fin (plan.count j)) := + π.panel U x.record (root i) (plan.pos j i) (created (U := U) c.mark j (root i)) + +open scoped Classical in +/-- The value specified by `(panel c p l j x i).reply (C i).action (sel i) (π.tiles x.record +(info size x) (root i))`. -/ +def reply (i : Fin (plan.count j)) := + (panel c p l j x i).reply (C i).action (sel i) (π.tiles x.record (info size x) (root i)) + +local notation "ans" => reply c p l hF j x sel size +local notation "G" => Wave.update C x.record sel +local notation "Q'" => Wave.carryInfo C sel (info size x) + +omit [Field F] [Fintype V] [Fintype E] [Fintype F] in +open scoped Classical in +theorem sole {i k : Fin (plan.count j)} {v : V} + (hi : a.near (U + 1) (root i) v) (hk : a.near (U + 1) (root k) v) : i = k := + (plan.root j).injective (π.distinguish ((hi.join hk.symm).mono (by omega)) (plan.same j i k)) + +open scoped Classical in +private theorem no_vertex {v : V} (h : ∀ i, ¬a.near U (root i) v) : + v ∉ Wave.vertices C := by + rintro ⟨i, hi⟩ + exact h i ((π.vertex_range le_rfl).mp hi) + +open scoped Classical in +private theorem no_seam {e : E} (h : ∀ i, ¬a.touches U (root i) e) : + e ∉ Wave.edges C := by + rintro ⟨i, hi⟩ + exact h i ((π.seam_range le_rfl).mp hi) + +open scoped Classical in +private theorem local_data (v : V) (i : Fin (plan.count j)) (hv : a.near (U + 1) (root i) v) : + ((G).rows v, (G).footprint v, Q' v) = + ((ans i).cell (π.mark v)).getD (x.record.rows v, x.record.footprint v, info size x v) := by + have sep := (prepared c p l hF j x).separate.vertex + let u := root i + by_cases h : π.mark v ∈ π.vertices U u + · let w : (C i).vertices := ⟨π.mark v, h⟩ + have he : v = (C i).ref.vertex w := (π.vertex_at u hv w).mp rfl + simp only [Wave.update, Wave.carryInfo] + conv_lhs => rw [he] + simp only [Wave.write_at _ _ _ sep i w] + unfold reply Panel.reply + simp only [panel, Palette.panel, show π.mark v ∈ π.vertices U (root i) from h, + ↓reduceDIte, Option.getD_some, Palette.collect_eq] + rfl + · have hn : v ∉ Wave.vertices C := by + apply no_vertex + intro k hk + have e := sole j hv (hk.mono (by omega)) + subst k + obtain ⟨w, hw⟩ := (π.vertex_range le_rfl).mpr hk + exact h (hw ▸ (π.vertex_spec U _ w).2.symm ▸ w.property) + simp only [Wave.update, Wave.carryInfo, Wave.write_away _ _ _ v hn] + simp only [reply, Panel.reply, panel, Palette.panel, + show π.mark v ∉ π.vertices U (root i) from h, + ↓reduceDIte, Option.getD_none] + +open scoped Classical in +private theorem local_level (v : V) (i : Fin (plan.count j)) (hv : a.near (U + 1) (root i) v) + (e : E) (he : a.src e = v ∨ a.dst e = v) : + (G).level e = ((ans i).level (π.edge e)).getD (x.record.level e) := by + let u := root i + by_cases h : π.edge e ∈ π.labels U u + · let w : (C i).edges := ⟨π.edge e, h⟩ + have hw : e = (C i).ref.edge w := (π.seam_at u hv e he w).mp rfl + simp only [Wave.update] + conv_lhs => rw [hw] + rw [Wave.write_at _ _ _ (prepared c p l hF j x).separate.edge i w] + simp only [reply, Panel.reply, panel, Palette.panel, show π.edge e ∈ π.labels U (root i) from h, + ↓reduceDIte, Option.getD_some] + rfl + · have hn : e ∉ Wave.edges C := by + apply no_seam + intro k hk + have near : a.near (U + 1) (root k) v := he.elim (fun t => t ▸ hk.near.1) (fun t + => t ▸ hk.near.2) + have eq := sole j hv near + subst k + obtain ⟨w, hw⟩ := (π.seam_range le_rfl).mpr hk + exact h (hw ▸ (π.seam_spec U _ w).2.symm ▸ w.property) + simp only [Wave.update, Wave.write_away _ _ _ e hn] + simp only [reply, Panel.reply, panel, Palette.panel, show π.edge e ∉ π.labels U (root i) from h, + ↓reduceDIte, Option.getD_none] + +omit [Fintype V] [Fintype E] [Fintype F] [ExpChar F p] in +open scoped Classical in +private theorem incidents (v : V) (k : E × F) (hk : k ∈ x.record.ports v) : + a.src k.1 = v ∨ a.dst k.1 = v := + ((x.match'.incident x.layout).endpoints _ _).mp (List.mem_map_of_mem hk) + +open scoped Classical in +theorem receive (v : V) (i : Fin (plan.count j)) (hv : a.near (U + 1) (root i) v) : + (G).tile π.edge Q' v = (ans i).apply (π.mark v) (x.record.tile π.edge (info size x) v) := by + have h := local_data c p l hF j x sel size v i hv + unfold Record.tile Record.body Reply.apply + dsimp only + rw [← h] + congr 2 + rw [List.map_map] + apply List.map_congr_left + intro k hk + have e := local_level c p l hF j x sel size v i hv k.1 (incidents p l j x v k hk) + exact congrArg (fun n => (π.edge k.1, k.2, n)) e + +open scoped Classical in +theorem untouched (v : V) (hv : ∀ i, ¬a.near (U + 1) (root i) v) : + (G).tile π.edge Q' v = x.record.tile π.edge (info size x) v := by + have hn : v ∉ Wave.vertices C := + no_vertex c p l hF j x (fun i h => hv i (h.mono (by omega))) + have level (k : E × F) (hk : k ∈ x.record.ports v) : (G).level k.1 = x.record.level k.1 := by + simp only [Wave.update] + apply Wave.write_away + apply no_seam c p l hF j x + intro i hit + rcases incidents p l j x v k hk with hl|hr + · exact hv i (hl ▸ hit.near.1) + · exact hv i (hr ▸ hit.near.2) + simp only [Record.tile, Record.body, Wave.update, Wave.carryInfo, Wave.write_away _ _ _ v hn] + congr 2 + apply List.map_congr_left + intro k hk + exact congrArg (fun n => (π.edge k.1, k.2, n)) (level k hk) + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local.Frame +end + +/- +# A wave on short records + +There is one record per host and block. The two colors and the +original positions never change. Vacant cells have no tile. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local + +open Finset Coloring Assembly +variable {F V E T X J L N : Type} {m d h r t U R Q M : ℕ} + +open scoped Classical in +/-- Indexes the metadata by the coordinates of `Option (Fin R × Fin Q × (Fin M → F) × Tile F r t +R (Stamp Q (R * M) U) N)`. -/ +abbrev Metadata (F : Type) (r t R Q U M : ℕ) (N : Type) := + Option (Fin R × Fin Q × (Fin M → F) × Tile F r t R (Stamp Q (R * M) U) N) + +namespace Atlas +variable (a : Atlas V E m d h) + +open scoped Classical in +/-- An unoccupied address is explicitly vacant. -/ +def fill {α : Type} (f : V → α) : B m × B h → Option α := + Function.extend a.coord (some ∘ f) (fun _ => none) + +open scoped Classical in +theorem fill_at {α : Type} (f : V → α) (i : V) : a.fill f (a.coord i) = some (f i) := + a.coord.injective.extend_apply _ _ _ + +open scoped Classical in +theorem fill_away {α : Type} (f : V → α) {i : B m × B h} (hi : i ∉ Set.range a.coord) : + a.fill f i = none := Function.extend_apply' _ _ _ hi + +open scoped Classical in +/-- The value specified by `(Neighborhood.expand k a.graph v.1 i, v.2)`. -/ +def around (k : ℕ) (v : B m × B h) (i : B ((d + 1) * k)) : B m × B h := + (Neighborhood.expand k a.graph v.1 i, v.2) + +open scoped Classical in +@[simp] theorem around_zero (k : ℕ) (v : B m × B h) : a.around k v 0 = v := + Prod.ext (Neighborhood.origin) rfl + +open scoped Classical in +theorem around_iff (k : ℕ) (x y : V) : + (∃ i, a.around k (a.coord x) i = a.coord y) ↔ a.near k x y := by + constructor + · rintro ⟨i, e⟩ + have hb := congrArg Prod.snd e + have hc := congrArg Prod.fst e + exact ⟨hb, Neighborhood.mem.mp ⟨i, hc⟩⟩ + · rintro ⟨hb, hh⟩ + obtain ⟨i, hi⟩ := Neighborhood.mem.mpr hh + exact ⟨i, Prod.ext hi hb⟩ + +end Atlas + +open scoped Classical in +/-- Erase the extra fields before looking up a panel. -/ +def visible {I : Type} [Fintype I] (f : I → Metadata F r t R Q U M N) : + TileSet F r t R (Stamp Q (R * M) U) N := + univ.biUnion fun i => (f i).elim ∅ (fun v => {(v.1, v.2.2.2)}) + +namespace Palette + +variable {a : Atlas V E m d h} (π : Palette a (2 * U + 2) R) + (c : Palette a (horizon U (R * M) 0) Q) (pos : V → Fin M → F) + (G : Record F r t V E (Stamp Q (R * M) U) N) (info : V → Catalog (Stamp Q (R * M) U)) + +open scoped Classical in +/-- The indexed operation `a.fill (fun v => (π.mark v, c.mark v, pos v, G.tile π.edge info v))`. -/ +def records : B m × B h → Metadata F r t R Q U M N := + a.fill (fun v => (π.mark v, c.mark v, pos v, G.tile π.edge info v)) + +open scoped Classical in +theorem records_at (v : V) : + π.records c pos G info (a.coord v) = some (π.mark v, c.mark v, pos v, G.tile π.edge info v) := + a.fill_at _ _ + +open scoped Classical in +theorem records_away {i : B m × B h} (hi : i ∉ Set.range a.coord) : + π.records c pos G info i = none := a.fill_away _ hi + +open scoped Classical in +theorem window [Fintype V] (v : V) : + visible (π.records c pos G info ∘ a.around U (a.coord v)) = π.tiles G info v := by + ext z + simp only [visible, mem_biUnion, mem_univ, true_and, Function.comp_apply, tiles, mem_image, + Atlas.ball, mem_filter_univ] + constructor + · rintro ⟨i, hi⟩ + by_cases he : a.around U (a.coord v) i ∈ Set.range a.coord + · obtain ⟨w, hw⟩ := he + rw [← hw, records_at] at hi + exact ⟨w, (a.around_iff U v w).mp ⟨i, hw.symm⟩, (mem_singleton.mp hi).symm⟩ + · rw [records_away _ _ _ _ _ he] at hi + simp at hi + · rintro ⟨w, hw, rfl⟩ + obtain ⟨i, hi⟩ := (a.around_iff U v w).mpr hw + exact ⟨i, by rw [hi, records_at]; simp⟩ + +end Palette +end MatrixMultiplicationAllFields.MatrixExponent.Sphere.Surface.Local +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Width.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Width.lean new file mode 100644 index 0000000000..bae9dc5f09 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Sphere/Width.lean @@ -0,0 +1,130 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Block +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Sphere.Seam + +/-! +# Fusion width + +At fixed input and output energies, a bounded-energy combination of +states at the first site realizes each matrix unit. The proof works +over the integers and over every field. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Sphere + +variable (R : Type*) [CommRing R] + +/-- Twice the single-species cutoff at doubled energies `e,g`. -/ +def width (e g : ℕ) : ℝ := (Real.sqrt e + Real.sqrt g) ^ 2 + (Real.sqrt e + Real.sqrt g) + +namespace Width + +variable (w : Bool → ℝ) + +private abbrev Label := Slot ⊕ Mark 1 + +private def K : Label → Label → R + | .inl _, .inl _ => 0 + | .inl x, .inr y => test R (start w x) (order w x) y + | .inr x, .inl y => -test R (start w y) (order w y) x + | .inr x, .inr y => pairing R x y + +private theorem skew (x y : Label) : K R w y x = -K R w x y := by + cases x <;> cases y <;> simp only [K, neg_zero, neg_neg] + exact pairing_skew R _ _ + +private theorem diag (x : Label) : K R w x x = 0 := by + cases x <;> simp [K, pairing_self] + +private def source (i : Mode 1) : Label := .inr (.origin, i) + +private def dest (i : Slot) : Label := .inr (mark i) + +private theorem evaluate (c a b : Wedge 1) : + wick (K R w) (c.val.map source ++ (slots a b).map dest) = + fusion R c.val a.val b.val := by + have he : c.val.map source ++ (slots a b).map dest = + (marks .origin c.val ++ marks .middle a.val ++ marks .infinity b.val.reverse).map Sum.inr + := by + simp [slots, source, dest, mark, marks, Function.comp_def] + rw [he, wick_map] + rfl + +private theorem tests (xs : List Slot) : + ∃ v : Wedge 1 →₀ R, (∀ y ∈ v.support, energy y.val ≤ (xs.map (cost w)).sum ∧ + y.val.length = xs.length) ∧ + ∀ a b : Wedge 1, + Finsupp.linearCombination R (fun t => fusion R t.val a.val b.val) v = + wick (K R w) (xs.map Sum.inl ++ (slots a b).map dest) := by + obtain ⟨v, hv, he⟩ := substitute_modes (skew R w) (diag R w) Sum.inl source (cost w) (by + intro x + refine ⟨Finset.range (order w x + 1), fun i => (-1) ^ i * (order w x).choose i, + fun i => (0, start w x + i), ?_, ?_⟩ + · simp only [Finset.mem_range, cost] + omega + · rintro (y | y) + · simp [K, source, test_origin] + · rfl) xs [] + refine ⟨v, fun y hy => ?_, fun a b => ?_⟩ + · simpa [energy] using hv y hy + · simpa only [List.nil_append, List.map_nil, evaluate] using + (he [] ((slots a b).map dest)).symm + +end Width + +open Width + +open Classical in +/-- Matrix units can be realized keeping the total number of generators. -/ +theorem fusion_width_length (a b : Wedge 1) : + ∃ v : Wedge 1 →₀ R, + (∀ t ∈ v.support, (energy t.val : ℝ) ≤ width (energy a.val) (energy b.val) ∧ + t.val.length = a.val.length + b.val.length) ∧ + ∀ a' b' : Wedge 1, energy a'.val = energy a.val → energy b'.val = energy b.val → + Finsupp.linearCombination R (fun t => fusion R t.val a'.val b'.val) v = + if a = a' ∧ b = b' then 1 else 0 := by + let w (s : Bool) := if s then Real.sqrt (energy b.val) else Real.sqrt (energy a.val) + obtain ⟨v, hv, he⟩ := tests R w (slots a b).reverse + refine ⟨v, ?_, ?_⟩ + · intro t ht + obtain ⟨h, hlen⟩ := hv t ht + rw [List.map_reverse, List.sum_reverse] at h + exact ⟨(Nat.cast_le.mpr h).trans (slots_cost w a b rfl rfl), + by simpa [slots, Nat.add_comm] using hlen⟩ + · intro a' b' ha hb + have wa : w false = Real.sqrt (energy a'.val) := by rw [ha]; rfl + have wb : w true = Real.sqrt (energy b'.val) := by rw [hb]; rfl + have hp (h : (slots a b).Perm (slots a' b')) := slots_inj h + have hc : slots a b = slots a' b' ↔ a = a' ∧ b = b' := + ⟨fun h => hp (by rw [h]), fun ⟨h, i⟩ => by rw [h, i]⟩ + rw [he] + have h := wick_pivot (K R w) Sum.inl dest (Width.weight w) (fun x => 0 < w x.1) + (fun _ hx => weight_pos w hx) (fun _ _ => rfl) (test_pivot R w) + (slots a b) (slots a' b') (slots_valid w a b rfl rfl) (slots_valid w a' b' wa wb) + (slots_nodup a b) (fun h => hc.mpr (hp h)) + (by rw [slots_weight w a b rfl rfl, slots_weight w a' b' wa wb]) + simpa only [hc] using h + +open Classical in +/-- The input and output basis indices of the desired matrix unit are +`a,b`. A single state realizes it on the entire pair of levels. -/ +theorem fusion_width (a b : Wedge 1) : + ∃ v : Wedge 1 →₀ R, + (∀ t ∈ v.support, (energy t.val : ℝ) ≤ width (energy a.val) (energy b.val)) ∧ + ∀ a' b' : Wedge 1, energy a'.val = energy a.val → energy b'.val = energy b.val → + Finsupp.linearCombination R (fun t => fusion R t.val a'.val b'.val) v = + if a = a' ∧ b = b' then 1 else 0 := by + obtain ⟨v, hv, he⟩ := fusion_width_length R a b + exact ⟨v, fun t ht => (hv t ht).1, he⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Sphere diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Array.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Array.lean new file mode 100644 index 0000000000..670f376692 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Array.lean @@ -0,0 +1,643 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.AdjacentDuplicates +public import Mathlib.Order.Prod.Lex.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BitonicMerge +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Wide +public import Mathlib.Data.Fin.Tuple.Sort +public import Mathlib.Logic.Equiv.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Substitute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Tags +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange + +/-! +# Checking sorted order with linear overhead + +Each subtree reports its first and last rows and a bit saying whether +it is sorted. A join compares just the two adjacent endpoints. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {a : Wire} [LinearOrder (Val a)] + +private abbrev Frame (a : Wire) := Wire.pair (.pair a a) .bit + +private def join (x : Val (.pair (Frame a) (Frame a))) : Val (Frame a) := + ((x.1.1.1, x.2.1.2), (x.1.2 && x.2.2) && !decide (x.2.1.1 < x.1.1.2)) + +private def frame : (w : ℕ) → Val (tree w a) → Val (Frame a) + | 0, x => ((x, x), true) + | w + 1, x => join (frame w x.1, frame w x.2) + +private theorem frame_correct (w : ℕ) (x : Val (tree w a)) : + let q := frame w x + let L := flatten w x + q.1.1 ∈ L ∧ q.1.2 ∈ L ∧ (q.2 = true ↔ L.Pairwise (· ≤ ·)) ∧ + (q.2 = true → ∀ z ∈ L, q.1.1 ≤ z ∧ z ≤ q.1.2) := by + induction w with + | zero => simp [frame, flatten] + | succ w ih => + obtain ⟨h₁, h₂, hl, bl⟩ := ih x.1 + obtain ⟨h₃, h₄, hr, br⟩ := ih x.2 + simp only [frame, join, flatten, Bool.and_eq_true, Bool.not_eq_true', decide_eq_false_iff_not, + not_lt, List.pairwise_append] + refine ⟨List.mem_append_left _ h₁, List.mem_append_right _ h₄, ?_, ?_⟩ + · constructor + · rintro ⟨⟨l, r⟩, q⟩ + exact ⟨hl.mp l, hr.mp r, fun y hy z hz => ((bl l y hy).2.trans q).trans (br r z hz).1⟩ + · rintro ⟨l, r, q⟩ + exact ⟨⟨hl.mpr l, hr.mpr r⟩, q _ h₂ _ h₃⟩ + · rintro ⟨⟨l, r⟩, q⟩ z hz + rcases List.mem_append.mp hz with h | h + · exact ⟨(bl l z h).1, ((bl l z h).2.trans q).trans (br r _ h₃).2⟩ + · exact ⟨((bl l _ h₂).1.trans q).trans (br r z h).1, (br r z h).2⟩ + +variable {k : ℕ} (p : DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) k) + +include p in +private theorem join_net : DNet F (.pair (Frame a) (Frame a)) (Frame a) join (2 * wd a + k + 2) + := by + let e := Wire.pair a a + let b := Wire.pair .bit .bit + have ends := (((Rewire.id e).par (.swap a a)).comp (.middle a a a a)).comp + ((Rewire.id e).par (.swap a a)) + have r := ((Rewire.middle e .bit e .bit).comp (ends.par (.id b))).comp (.assoc e e b) + have both := DNet.table F b .bit (fun x => x.1 && x.2) (by decide) + have ok := DNet.table F b .bit (fun x => x.2 && !x.1) (by decide) + exact (((DNet.id F e).par ((p.par both).comp ok)).pre r).mono (by simp [e, wd]; omega) + +include p in +private theorem frame_net (w : ℕ) : + ∃ m, DNet F (tree w a) (Frame a) (frame w) m ∧ + m + (2 * wd a + k + 2) ≤ 2 ^ w * (3 * wd a + k + 3) := by + induction w with + | zero => + have yes := DNet.table F .unit .bit (fun _ => true) (by decide) + exact ⟨_, ((DNet.dup F a).par yes).pre (.unit' a), by simp; omega⟩ + | succ w ih => + obtain ⟨m, h, hm⟩ := ih + refine ⟨_, (h.par h).comp (join_net p), ?_⟩ + rw [pow_succ, mul_two, add_mul] + omega + +include p in +theorem check_order (w : ℕ) : + DNet F (tree w a) .bit (fun x => decide ((flatten w x).Pairwise (· ≤ ·))) + (2 ^ w * (3 * wd a + k + 3)) := by + obtain ⟨m, h, hm⟩ := frame_net p w + have net := h.comp (DNet.snd F (.pair a a) .bit) + have eq (x : Val (tree w a)) : (frame w x).2 = decide ((flatten w x).Pairwise (· ≤ ·)) := by + rw [Bool.eq_iff_iff, decide_eq_true_eq] + exact (frame_correct w x).2.2.1 + simpa only [eq] using net.mono (n := 2 ^ w * (3 * wd a + k + 3)) (by simp only [wd]; omega) + +include p in +/-- Two comparisons of the first component and one of the second suffice. -/ +theorem lex_compare {b : Wire} [LinearOrder (Val b)] {l : ℕ} + (q : DNet F (.pair b b) .bit (fun x => decide (x.1 < x.2)) l) : + DNet F (.pair (.pair a b) (.pair a b)) .bit (fun x => decide (toLex x.1 < toLex x.2)) + (2 * wd a + 2 * k + l + 3) := by + have cmp := ((p.pair (p.pre (.swap a a))).par q).pre (.middle a b a b) + have h := DNet.table F (.pair .bit .bit) .bit (fun x => !x.1 && x.2) (by decide) + have g := DNet.table F (.pair .bit .bit) .bit (fun x => x.1 || x.2) (by decide) + have net := (cmp.post (.assoc .bit .bit .bit)).comp (((DNet.id F .bit).par h).comp g) + convert net.mono (n := 2 * wd a + 2 * k + l + 3) (by simp only [wd]; omega) using 1 + funext ⟨x, y⟩ + clear cmp h g net p q + rw [Bool.eq_iff_iff] + simp only [Bool.or_eq_true, Bool.and_eq_true, Bool.not_eq_true', decide_eq_false_iff_not, + decide_eq_true_eq, Prod.Lex.toLex_lt_toLex] + grind + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- +# Array layouts on bundles of bits + +A layout partitions the exterior positions into disjoint copies of a +record. Any permutation of records induces a free bit permutation. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- Reindexes `I × slots a` and `slots b` by an equivalence. -/ +structure Layout (a b : Wire) (I : Type) where + /-- Reindexes the data using `I × slots a ≃ slots b`. -/ + positions : I × slots a ≃ slots b + +namespace Layout + +variable {a b c : Wire} {I J : Type} {m n : ℕ} + +/-- The indexed operation `(bits a).symm (fun k => bits b x (L.positions (i, k)))`. -/ +def read (L : Layout a b I) (x : Val b) (i : I) : Val a := + (bits a).symm (fun k => bits b x (L.positions (i, k))) + +theorem injective (L : Layout a b I) : Function.Injective L.read := by + intro x y h + apply (bits b).injective + funext j + obtain ⟨⟨i, k⟩, rfl⟩ := L.positions.surjective j + exact congrFun ((bits a).symm.injective (congrFun h i)) k + +theorem rewire (L : Layout a b I) (M : Layout a c J) (e : J ≃ I) : + ∃ f, Rewire b c f ∧ ∀ x, M.read (f x) = L.read x ∘ e := by + let p := M.positions.symm.trans ((e.prodCongr (.refl _)).trans L.positions) + refine ⟨reindex p, rewire_reindex p, fun x => ?_⟩ + funext i + simp [read, p] + +/-- Uses `⟨(Equiv.prodAssoc _ _ _).trans (((Equiv.refl I).prodCongr M.positions).trans +L.positions)⟩` as the representation. -/ +def nest (L : Layout b c I) (M : Layout a b J) : Layout a c (I × J) := + ⟨(Equiv.prodAssoc _ _ _).trans (((Equiv.refl I).prodCongr M.positions).trans L.positions)⟩ + +theorem read_nest (L : Layout b c I) (M : Layout a b J) (x : Val c) (i : I) (j : J) : + (L.nest M).read x (i, j) = M.read (L.read x i) j := by + simp [read, nest] + +private def one (a : Wire) : Layout a a (Fin 1) := ⟨Equiv.uniqueProd _ _⟩ + +private theorem read_one (x : Val a) (i : Fin 1) : (one a).read x i = x := + (bits a).symm_apply_apply x + +private def pair (L : Layout a b (Fin m)) (M : Layout a c (Fin n)) : + Layout a (.pair b c) (Fin (m + n)) := + ⟨(finSumFinEquiv.symm.prodCongr (.refl _)).trans + ((Equiv.sumProdDistrib _ _ _).trans (L.positions.sumCongr M.positions))⟩ + +private theorem read_pair_left (L : Layout a b (Fin m)) (M : Layout a c (Fin n)) + (x : Val (.pair b c)) (i : Fin m) : + (L.pair M).read x (i.castAdd n) = L.read x.1 i := by + unfold read + apply congrArg + funext k + change bits (.pair b c) x ((L.pair M).positions (finSumFinEquiv (.inl i), k)) = _ + simp only [pair, Equiv.trans_apply, Equiv.prodCongr_apply, Prod.map, + Equiv.symm_apply_apply] + rfl + +private theorem read_pair_right (L : Layout a b (Fin m)) (M : Layout a c (Fin n)) + (x : Val (.pair b c)) (i : Fin n) : + (L.pair M).read x (i.natAdd m) = M.read x.2 i := by + unfold read + apply congrArg + funext k + change bits (.pair b c) x ((L.pair M).positions (finSumFinEquiv (.inr i), k)) = _ + simp only [pair, Equiv.trans_apply, Equiv.prodCongr_apply, Prod.map, + Equiv.symm_apply_apply] + rfl + +theorem exists_tree (a : Wire) (w : ℕ) : + ∃ L : Layout a (tree w a) (Fin (2 ^ w)), ∀ x, List.ofFn (L.read x) = flatten w x := by + induction w with + | zero => + refine ⟨one a, fun x => ?_⟩ + change List.ofFn ((one a).read x) = [x] + simp [read_one] + | succ w ih => + obtain ⟨L, hL⟩ := ih + rw [pow_succ, mul_two] + refine ⟨L.pair L, fun x => ?_⟩ + rw [List.ofFn_add] + change List.ofFn (fun i => (L.pair L).read x (Fin.castAdd _ i)) ++ + List.ofFn (fun i => (L.pair L).read x (Fin.natAdd _ i)) = _ + simp only [read_pair_left, read_pair_right, hL, flatten] + +theorem read_sort [LinearOrder (Val a)] {w : ℕ} (L : Layout a (tree w a) (Fin n)) + (hL : ∀ x, List.ofFn (L.read x) = flatten w x) (x : Val (tree w a)) : + L.read (sortTree w x) = L.read x ∘ Tuple.sort (L.read x) := by + apply List.ofFn_injective + rw [hL] + apply List.Perm.eq_of_pairwise' (sortTree_sorted ..) + (Tuple.monotone_sort _).sortedLE_ofFn.pairwise + exact (sortTree_perm ..).trans (by rw [← hL]; exact (Equiv.Perm.ofFn_comp_perm ..).symm) + +theorem exists_copies (a : Wire) (n : ℕ) : + ∃ L : Layout a (copies a n) (Fin n), + ∀ (f : Val a → Val a) x, L.read (mapCopies f n x) = f ∘ L.read x := by + induction n with + | zero => exact ⟨⟨Equiv.equivEmpty _⟩, fun _ _ => funext fun i => i.elim0⟩ + | succ n ih => + obtain ⟨L, hL⟩ := ih + have h : ∃ K : Layout a (copies a (n + 1)) (Fin (1 + n)), + ∀ (f : Val a → Val a) x, K.read (mapCopies f (n + 1) x) = f ∘ K.read x := by + refine ⟨(one a).pair L, fun f x => ?_⟩ + funext i + induction i using Fin.addCases with + | left i => simp only [Function.comp_apply, mapCopies, read_pair_left, read_one] + | right i => simp only [Function.comp_apply, mapCopies, read_pair_right, hL] + rwa [Nat.add_comm 1 n] at h + +end Layout +end MatrixMultiplicationAllFields.MatrixExponent +end + +section +/- # Substituting a batch of independent queries -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {a b c d : Wire} + +/-- Batch size counts vertices only. Powers have disjoint exterior bits. -/ +def Batch (k : Val a → Val b → F) (t m : ℕ) : Prop := + ∃ v ≤ m, Net F (copies a t) (copies b t) (power k t) v + +namespace Batch + +variable {k : Val a → Val b → F} {m n t : ℕ} + +theorem mono (h : Batch k t m) (hm : m ≤ n) : Batch k t n := by + obtain ⟨v, hv, h⟩ := h + exact ⟨v, hv.trans hm, h⟩ + +theorem of_net (h : Net F a b k m) (t : ℕ) : Batch k t (t * m) := + ⟨_, le_rfl, h.power t⟩ + +theorem comp {l : Val b → Val c → F} (h : Batch k t m) (g : Batch l t n) : + Batch (fun x z => ∑ y, k x y * l y z) t (m + n) := by + obtain ⟨v, hv, h⟩ := h + obtain ⟨u, hu, g⟩ := g + exact ⟨v + u, Nat.add_le_add hv hu, by simpa only [← power_comp] using h.comp g⟩ + +theorem par {l : Val c → Val d → F} (h : Batch k t m) (g : Batch l t n) : + Batch (a := .pair a c) (b := .pair b d) (fun x y => k x.1 y.1 * l x.2 y.2) t (m + n) := by + obtain ⟨v, hv, h⟩ := h + obtain ⟨u, hu, g⟩ := g + exact ⟨v + u, Nat.add_le_add hv hu, + (h.par g).rewire (.zipCopies _ _ _) (.zipCopies _ _ _) (power_zip k l t)⟩ + +theorem pullback {f : Val c → Val a} (h : Batch k t m) (g : DNet F c a f n) : + Batch (fun x y => k (f x) y) t (t * n + m) := by + obtain ⟨u, hu, g⟩ := g + have h' := ((of_net g t).mono (Nat.mul_le_mul_left t hu)).comp h + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] using h' + +theorem par_pred {k : Val a → Val .unit → F} {l : Val b → Val .unit → F} + (h : Batch k t m) (g : Batch l t n) : + Batch (a := .pair a b) (b := .unit) (fun x y => k x.1 y * l x.2 y) t (m + n) := by + obtain ⟨v, hv, h⟩ := h.par g + exact ⟨v, hv, h.rewire ((Rewire.id _).mapCopies t) ((Rewire.unit .unit).mapCopies t) + (power_map (fun _ _ => rfl) t)⟩ + +end Batch +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- +# Preparing distinctness queries + +The input and proposed output each occupy half a list. A real record has +flag zero. When excluded from the signed subset, a record changes only +its flag. Its position tag still distinguishes it from every other dummy. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {a b c : Wire} {m : ℕ} + +theorem literal_net (F : Type) [Field F] (a : Wire) (x : Val a) : + DNet F .unit a (fun _ => x) (wd a) := by + induction a with + | bit => exact .table F .unit .bit _ (by decide) + | unit => exact DNet.id F .unit + | pair a b ha hb => exact ((ha x.1).par (hb x.2)).pre (.unit' _) + +theorem mapRows_net {f : Val a → Val b} (h : DNet F a b f m) (w : ℕ) : + DNet F (tree w a) (tree w b) (mapRows f w) (2 ^ w * m) := by + induction w with + | zero => rw [pow_zero, one_mul]; exact h + | succ w ih => + rw [pow_succ, mul_two, add_mul] + exact ih.par ih + +theorem zipRows_net {f : Val a → Val b → Val c} (h : DNet F (.pair a b) c (Function.uncurry f) m) + (w : ℕ) : DNet F (.pair (tree w a) (tree w b)) (tree w c) + (fun x => zipRows f w x.1 x.2) (2 ^ w * m) := by + induction w with + | zero => rw [pow_zero, one_mul]; exact h + | succ w ih => + rw [pow_succ, mul_two, add_mul] + exact (ih.par ih).pre (.middle _ _ _ _) + +theorem label_net (F : Type) [Field F] (w : ℕ) (a : Wire) : + DNet F (tree w a) (tree w (row w a)) (label w) (2 ^ w * (2 * (w + wd a))) := by + have h := ((DNet.id F (tree w a)).par (literal_net F _ (indices w))).pre (.unit' _) + have k := (DNet.id F (.pair a (word w))).post (.swap _ _) + refine (h.comp (zipRows_net (c := row w a) (f := fun y i => (i, y)) k w)).mono ?_ + simp only [wd_tree, wd_word, wd] + exact le_of_eq (by ring) + +theorem sign_net (F : Type) [Field F] (w : ℕ) : + Net F .unit (tree w .bit) (fun _ z => sign F w z) (2 ^ w) := by + induction w with + | zero => exact .table _ _ _ (by decide) + | succ w ih => + rw [pow_succ, mul_two] + exact (ih.par ih).pre (.unit' _) + +variable {w : ℕ} (E : Val .bit → Val (row w a) → Val b) + +private theorem test_net (h : Rewire (.pair .bit (row w a)) b (Function.uncurry E)) : + DNet F (.pair (tree w .bit) (inputs w a)) (tree (w + 1) b) + (fun y => tested E w (label w y.2.1) y.2.2 y.1) + (2 ^ w * (4 * (w + wd a) + 3)) := by + have mark := (DNet.id F _).post h + have zero := (literal_net F .bit false).par (DNet.id F (row w a)) + have real := (zero.pre ((Rewire.unit' _).comp (.swap _ _))).post h + have left := mapRows_net real w + have right := ((DNet.id F (tree w .bit)).par (label_net F w a)).comp (zipRows_net mark w) + refine ((left.par right).pre ((Rewire.assoc' _ _ _).comp (.swap _ _))).mono ?_ + simp only [wd_tree, wd, wd_word] + exact le_of_eq (by ring) + +/-- A linear map inserting the signed choice of flags. -/ +def prepare (F : Type) [Field F] (x : Val (inputs w a)) (y : Val (tree (w + 1) b)) : F := + ∑ z : Val (tree w .bit), sign F w z * if tested E w (label w x.1) x.2 z = y then 1 else 0 + +theorem prepare_net (h : Rewire (.pair .bit (row w a)) b (Function.uncurry E)) : + ∃ v ≤ 2 ^ w * (5 * w + 6 * wd a + 4), Net F (inputs w a) (tree (w + 1) b) (prepare E F) v := by + obtain ⟨m, hm, ht⟩ := test_net (F := F) E h + obtain ⟨v, hv, hid⟩ := DNet.id F (inputs w a) + have k := ((sign_net F w).par hid).pre ((Rewire.unit' _).comp (.swap _ _)) + refine ⟨2 ^ w + v + m, ?_, ?_⟩ + · refine (Nat.add_le_add (Nat.add_le_add_left hv (2 ^ w)) hm).trans ?_ + simp only [wd, wd_tree, row, wd_word] + exact le_of_eq (by ring) + · convert k.comp ht using 1 + funext x y + rw [Fintype.sum_prod_type] + unfold prepare + apply Finset.sum_congr rfl + intro z _ + rw [Fintype.sum_eq_single x] + · simp + · intro x2 hne; simp [hne.symm] + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- +# Sorting with a permutation verifier + +Sum over proposed tagged outputs, retaining their payloads. Checking +order by payload and then by tag leaves exactly one witness, even when +some payloads coincide. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {a b : Wire} {t m w k : ℕ} + +private theorem cup (b : Wire) : + Net F .unit (.pair b b) (fun _ y => if y.1 = y.2 then 1 else 0) (wd b) := by + induction b with + | bit => exact .table _ _ _ (by decide) + | unit => exact Net.empty.post (.unit _) + | pair b c ih ij => + have h := ((ih.par ij).pre (.unit' _)).post (.middle b c b c) + simpa only [wd, Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul] using h + +/-- Move the second block of exterior inputs to the output side. -/ +theorem Batch.openInput {l : Val (.pair a b) → Val .unit → F} (h : Batch l t m) : + Batch (a := a) (b := b) (fun x y => l (x, y) ()) t (m + t * wd b) := by + obtain ⟨v, hv, h⟩ := h + have e (d : ℕ) (x : Val (copies a d)) (y : Val (copies b d)) : + power l d (zipCopies a b d (x, y)) (unitCopies d) = + power (a := a) (b := b) (fun u z => l (u, z) ()) d x y := by + induction d with + | zero => rfl + | succ d ih => simp only [power, zipCopies, unitCopies, ih] + have h₁ := (h.pre (.zipCopies a b t)).post (.unitCopies t) + have h₂ := (h₁.par (cup (F := F) (copies b t))).pre (.unit' _) + have h₃ := (h₂.post ((Rewire.unit' _).comp (.swap _ _))).trace + refine ⟨v + wd (copies b t), by rw [wd_copies]; omega, ?_⟩ + simpa only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true, e] using h₃ + +private theorem Batch.graph {f : Val a → Val b} + (h : Batch (fun x y => if f x = y then (1 : F) else 0) t m) : + DNet F (copies a t) (copies b t) (mapCopies f t) m := by + obtain ⟨v, hv, h⟩ := h + have e (d : ℕ) (x : Val (copies a d)) (y : Val (copies b d)) : + power (fun s u => if f s = u then (1 : F) else 0) d x y = + if mapCopies f d x = y then 1 else 0 := by + induction d with + | zero => rfl + | succ d ih => simp only [power, mapCopies, Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul, + ih] + exact ⟨v, hv, by convert h using 1; funext x y; exact (e ..).symm⟩ + +theorem flatten_inj (w : ℕ) : Function.Injective (flatten (a := a) w) := by + induction w with + | zero => intro x y h; simpa [flatten] using h + | succ w ih => + intro x y h + obtain ⟨hl, hr⟩ := List.append_inj h (by rw [length_flatten, length_flatten]) + exact Prod.ext (ih hl) (ih hr) + +variable [LinearOrder (Val a)] + +theorem unique_sort (w : ℕ) (x y : Val (tree w a)) + (h : (flatten w y).Perm (flatten w x)) (hs : (flatten w y).Pairwise (· ≤ ·)) : + y = sortTree w x := + flatten_inj w (List.Perm.eq_of_pairwise' hs (sortTree_sorted ..) (h.trans (sortTree_perm + ..).symm)) + +private local instance rowOrder (w : ℕ) : LinearOrder (Val (row w a)) := + LinearOrder.lift' (fun z => toLex (z.2, z.1)) Prod.swap_injective + +private local instance rowLT (w : ℕ) : LT (Val (row w a)) := (rowOrder w).toLT +private local instance rowLE (w : ℕ) : LE (Val (row w a)) := (rowOrder w).toLE + +private theorem payload_le (x y : Val (row w a)) (h : x ≤ y) : x.2 ≤ y.2 := by + rcases (Prod.Lex.toLex_le_toLex (x := x.swap) (y := y.swap)).mp h with h | h + · exact h.le + · exact h.1.le + +private theorem row_compare (p : DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) k) + (w : ℕ) : DNet F (.pair (row w a) (row w a)) .bit (fun x => decide (x.1 < x.2)) + (2 * wd a + 2 * k + 100 * (w + 1) + 3) := by + exact (lex_compare p (compare_lt F w)).pre ((Rewire.swap _ _).par (.swap _ _)) + +/-- The value specified by `mapRows (a := row w a) Prod.snd w`. -/ +def payloads (w : ℕ) : Val (tree w (row w a)) → Val (tree w a) := + mapRows (a := row w a) Prod.snd w + +omit [LinearOrder (Val a)] in +theorem label_payloads (w : ℕ) (x : Val (tree w a)) : payloads w (label w x) = x := by + have aux (n : ℕ) (y : Val (tree n a)) (i : Val (tree n (word w))) : + mapRows (a := row w a) (b := a) Prod.snd n + (zipRows (c := row w a) (fun u v => (v, u)) n y i) = y := by + induction n with + | zero => rfl + | succ n ih => exact Prod.ext (ih _ _) (ih _ _) + exact aux w x (indices w) + +private theorem sorted_payloads (w : ℕ) (x : Val (tree w a)) : + payloads w (sortTree w (label w x)) = sortTree w x := by + apply unique_sort + · have h := (sortTree_perm w (label w x)).map Prod.snd + simp only [payloads, flatten_mapRows] + have he := congrArg (flatten w) (label_payloads w x) + simp only [payloads, flatten_mapRows] at he + rwa [he] at h + · simp only [payloads, flatten_mapRows] + exact (sortTree_sorted w (label w x)).map Prod.snd payload_le + +private def keep (F : Type) [Field F] (w : ℕ) (a : Wire) [LinearOrder (Val a)] + (x : Val (tree w (row w a))) (y : Val (tree w a)) : F := + if (flatten w x).Pairwise (· ≤ ·) ∧ payloads w x = y then 1 else 0 + +private theorem sort_sum (x y : Val (tree w a)) : + (∑ z, tag F w a (x, z) () * keep F w a z y) = if sortTree w x = y then 1 else 0 := by + rw [Fintype.sum_eq_single (sortTree w (label w x))] + · simp only [tag, permuted, sortTree_perm w (label w x), ite_true, one_mul, keep, + sortTree_sorted w (label w x), true_and, + sorted_payloads] + · intro z hz + by_cases hp : (flatten w z).Perm (flatten w (label w x)) + · have hs : ¬ (flatten w z).Pairwise (· ≤ ·) := + fun hs => hz (unique_sort w _ z hp hs) + simp [keep, hs] + · simp [tag, permuted, hp] + +private theorem keep_net (p : DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) k) + (w : ℕ) : + ∃ v ≤ 500 * 2 ^ w * (wd a + w + k + 1), Net F (tree w (row w a)) (tree w a) (keep F w a) v := by + have test := check_order (row_compare p w) w + have proj := mapRows_net (DNet.snd F (word w) a) w + obtain ⟨v, hv, h⟩ := proj.pair test + have pin := Net.table (F := F) .bit .unit (fun x _ => if x = true then 1 else 0) (by decide) + obtain ⟨u, hu, hid⟩ := DNet.id F (tree w a) + have net := h.comp ((hid.par pin).post (.unit' _)) + refine ⟨v + (u + 1), ?_, ?_⟩ + · simp only [wd_tree, wd, wd_word] at hv hu + have hp := Nat.one_le_pow w 2 (by decide) + nlinarith + · convert net using 1 + funext x y + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + simp only [decide_eq_true_eq, keep, payloads, ← ite_and, and_comm] + rfl + +/-- A batch of tagged permutation verifiers supplies the same number +of independent sorts with linear overhead in the cost of a comparison. -/ +theorem sort_of_tag (h : Batch (tag F w a) t m) + (p : DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) k) : + DNet F (copies (tree w a) t) (copies (tree w a) t) (mapCopies (sortTree w) t) + (m + 1000 * t * 2 ^ w * (wd a + w + k + 1)) := by + obtain ⟨v, hv, hkeep⟩ := keep_net p w + have hh := h.openInput.comp (Batch.of_net hkeep t) + simp only [sort_sum] at hh + apply hh.graph.mono + simp only [wd_tree, wd, wd_word] + calc + _ = m + t * (2 ^ w * (w + wd a) + v) := by ring + _ ≤ m + t * (2 ^ w * (w + wd a) + 500 * 2 ^ w * (wd a + w + k + 1)) := by gcongr + _ = m + t * 2 ^ w * ((w + wd a) + 500 * (wd a + w + k + 1)) := by ring + _ ≤ m + t * 2 ^ w * (1000 * (wd a + w + k + 1)) := by gcongr; omega + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- +# Verifying a permutation in payload slices + +The positional tags are distinct, so two checks that agree on the tag +necessarily refer to the same input row. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {a b : Wire} + +/-- Apply a function to both sets of payloads, preserving all tags. -/ +def project (w : ℕ) (f : Val a → Val b) (x : Val (inputs w a)) : Val (inputs w b) := + (mapRows f w x.1, + mapRows (a := row w a) (b := row w b) (Prod.map id f) w x.2) + +private theorem flatten_label_map (w : ℕ) (f : Val a → Val b) (x : Val (tree w a)) : + flatten w (label w (mapRows f w x)) = + (flatten w (label w x)).map (Prod.map id f) := by + have aux (n : ℕ) (y : Val (tree n a)) (i : Val (tree n (word w))) : + flatten n (zipRows (c := row w b) (fun u v => (v, u)) n (mapRows f n y) i) = + (flatten n (zipRows (c := row w a) (fun u v => (v, u)) n y i)).map (Prod.map id f) := by + induction n with + | zero => rfl + | succ n ih => simp only [flatten, zipRows, mapRows, List.map_append, ih] + exact aux w x (indices w) + +theorem label_tags (w : ℕ) (x : Val (tree w a)) : + (flatten w (label w x)).map Prod.fst = flatten w (indices w) := by + have aux (n : ℕ) (y : Val (tree n a)) (i : Val (tree n (word w))) : + (flatten n (zipRows (c := row w a) (fun u v => (v, u)) n y i)).map Prod.fst = + flatten n i := by + induction n with + | zero => rfl + | succ n ih => simp only [flatten, zipRows, List.map_append, ih] + exact aux w x (indices w) + +private theorem perm_slices {ι α β : Type} (A B : List (ι × α × β)) + (hA : (A.map Prod.fst).Nodup) : + B.Perm A ↔ + (B.map (Prod.map id Prod.fst)).Perm (A.map (Prod.map id Prod.fst)) ∧ + (B.map (Prod.map id Prod.snd)).Perm (A.map (Prod.map id Prod.snd)) := by + constructor + · exact fun h => ⟨h.map _, h.map _⟩ + rintro ⟨hl, hr⟩ + have hp : (B.map Prod.fst).Perm (A.map Prod.fst) := by + simpa [List.map_map, Function.comp_def] using hl.map Prod.fst + have hb := List.Nodup.of_map Prod.fst (hp.symm.nodup hA) + have hi := (List.nodup_map_iff_inj_on (List.Nodup.of_map Prod.fst hA)).mp hA + have sub : B ⊆ A := by + intro x hx + obtain ⟨y, hy, hxy⟩ := List.mem_map.mp (hl.subset (List.mem_map_of_mem hx)) + obtain ⟨z, hz, hxz⟩ := List.mem_map.mp (hr.subset (List.mem_map_of_mem hx)) + simp only [Prod.map, id_eq, Prod.mk.injEq] at hxy hxz + have h : y = z := hi y hy z hz (hxy.1.trans hxz.1.symm) + subst z + have h : y = x := Prod.ext hxy.1 (Prod.ext hxy.2 hxz.2) + exact h ▸ hy + exact (hb.subperm sub).perm_of_length_le (by simpa using hl.length_eq.ge) + +variable (F : Type) [Field F] (w : ℕ) + +theorem tag_project (f : Val a → Val b) (hf : Function.Injective f) + (x : Val (inputs w a)) (u : Val .unit) : + tag F w b (project w f x) u = tag F w a x u := by + have h : Function.Injective (Prod.map (id : Val (word w) → _) f) := by + intro p q he + simp only [Prod.map, id_eq, Prod.mk.injEq] at he + exact Prod.ext he.1 (hf he.2) + simp only [tag, permuted, project, flatten_mapRows, flatten_label_map, List.map_perm_map_iff h] + +theorem tag_pair (a b : Wire) (x : Val (inputs w (.pair a b))) (u : Val .unit) : + tag F w (.pair a b) x u = + tag F w a (project (a := .pair a b) w Prod.fst x) u * + tag F w b (project (a := .pair a b) w Prod.snd x) u := by + have h := perm_slices (flatten w (label w x.1)) (flatten w x.2) + (by rw [label_tags w x.1]; exact indices_nodup w) + simp only [tag, permuted, project, flatten_mapRows, flatten_label_map, h, ite_and, + ite_mul, one_mul, zero_mul] + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/ColumnNetwork.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/ColumnNetwork.lean new file mode 100644 index 0000000000..55d7f99fff --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/ColumnNetwork.lean @@ -0,0 +1,519 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Fin.Tuple.Sort +public import Mathlib.Logic.Equiv.Fin.Basic +public import Mathlib.Data.Fintype.Prod +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array + +/-! +# Lifting short sorts by four parallel passes + +In a grid with `c` columns of height `2*r*c`, where `c ≤ r`, four +passes of independent column sorts suffice. Between passes the wiring is +fixed. Grouping the first and last half-columns together in the final +pass avoids sentinels. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Columns + +variable {α : Type*} [LinearOrder α] {c n : ℕ} + +/-- Column number first, position within the column second. -/ +abbrev Grid (c n : ℕ) := Fin c × Fin n + +/-- The indexed operation `x (z.1, Tuple.sort (fun i => x (z.1, i)) z.2)`. -/ +def pass (x : Grid c n → α) (z : Grid c n) : α := + x (z.1, Tuple.sort (fun i => x (z.1, i)) z.2) + +private theorem sorted (x : Grid c n → α) (a : Fin c) : + Monotone (fun i => pass x (a, i)) := + Tuple.monotone_sort (fun i => x (a, i)) + +theorem pass_perm (x : Grid c n → α) : + ∃ e : Equiv.Perm (Grid c n), pass x = x ∘ e := + ⟨Equiv.prodCongrRight (fun a => Tuple.sort (fun i => x (a, i))), rfl⟩ + +private theorem reaches (f : Fin n → ℕ) (hf : Function.Injective f) (i : Fin n) : + ∃ j ≤ i, i.val ≤ f j := by + by_contra! h + let g (j : Fin (i.val + 1)) : Fin i.val := + ⟨f ⟨j, by omega⟩, h _ (by change j.val ≤ i.val; omega)⟩ + have hg : Function.Injective g := by + intro j k e + apply Fin.ext + exact congrArg (fun u : Fin n => u.val) (hf (Fin.val_eq_of_eq e)) + have := Fintype.card_le_of_injective _ hg + simp only [Fintype.card_fin] at this + omega + +/-- A large entry after sorting has a witness to its left before sorting. +Dually, a small entry has a witness to its right. -/ +private theorem witnesses (x : Grid c n → α) (a : Fin c) (i : Fin n) : + (∃ j ≤ i, pass x (a, i) ≤ x (a, j)) ∧ (∃ j ≥ i, x (a, j) ≤ pass x (a, i)) := by + let σ := Tuple.sort (fun k => x (a, k)) + constructor + · obtain ⟨j, hj, hj'⟩ := reaches _ (Fin.val_injective.comp σ.symm.injective) i + refine ⟨j, hj, (sorted x a (show i ≤ σ.symm j from hj')).trans_eq ?_⟩ + exact congrArg (fun k => x (a, k)) (σ.apply_symm_apply j) + · obtain ⟨j, hj, hj'⟩ := reaches _ (Fin.val_injective.comp σ.injective) i + exact ⟨σ j, hj', sorted x a hj⟩ + +/-- Move an index back by a fixed number of entries. -/ +def back (d : ℕ) (i : Fin n) : Fin n := ⟨i.val - d, by omega⟩ + +/-- Sorting two sequences which interlace with displacement `d` preserves +that displacement. At most `d` inputs are unmatched. -/ +private theorem interlace (x : Grid c n → α) (a b : Fin c) (d : ℕ) + (h : ∀ k : Fin n, d ≤ k.val → x (a, back d k) ≤ x (b, k)) + (i j : Fin n) (hij : i.val + d ≤ j.val) : pass x (a, i) ≤ pass x (b, j) := by + let σ := Tuple.sort (fun k => x (a, k)) + let τ := Tuple.sort (fun k => x (b, k)) + let f (k : Fin n) := if k.val < d then k.val else (σ.symm (back d k)).val + d + have hf : Function.Injective f := by + intro k l e + unfold f at e + split at e <;> split at e + · exact Fin.ext e + · omega + · omega + · have hb := σ.symm.injective (Fin.ext (Nat.add_right_cancel e)) + simp only [back, Fin.mk.injEq] at hb + omega + obtain ⟨k, hkj, hk⟩ := reaches _ (hf.comp τ.injective) j + change j.val ≤ f (τ k) at hk + have hdk : d ≤ (τ k).val := by unfold f at hk; split at hk <;> omega + dsimp only [f] at hk + rw [ite_eq_right (by omega : ¬ (τ k).val < d)] at hk + calc + pass x (a, i) ≤ pass x (a, σ.symm (back d (τ k))) := sorted x a (by omega) + _ = x (a, back d (τ k)) := congrArg (fun l => x (a, l)) (σ.apply_symm_apply _) + _ ≤ pass x (b, k) := h _ hdk + _ ≤ pass x (b, j) := sorted x b hkj + +/-- Pack two column indices into a single column index. -/ +def pack (c d : ℕ) : Fin c × Fin d × Fin c ≃ Grid c (d * c) := + Equiv.prodCongr (.refl _) finProdFinEquiv + +/-- Exchange the first and last coordinates of a packed column. -/ +def swapEnds (c d : ℕ) : Equiv.Perm (Fin c × Fin d × Fin c) where + toFun z := (z.2.2, z.2.1, z.1) + invFun z := (z.2.2, z.2.1, z.1) + left_inv _ := rfl + right_inv _ := rfl + +/-- Deal entries cyclically from each old column into the new ones. +Indices map from the new layout back into the old. -/ +def deal (c d : ℕ) : Equiv.Perm (Grid c (d * c)) := + (pack c d).symm.trans ((swapEnds c d).trans (pack c d)) + +/-- Read the sorted columns in row-major order into aligned blocks. -/ +def align (c d : ℕ) : Equiv.Perm (Grid c (d * c)) := + (pack c d).symm.trans <| (swapEnds c d).trans <| + Equiv.prodCongr (.refl _) ((Equiv.prodComm _ _).trans + (finProdFinEquiv.trans (finCongr (Nat.mul_comm c d)))) + +private theorem deal_at {d : ℕ} (a b : Fin c) (k : Fin d) : + deal c d (a, finProdFinEquiv (k, b)) = (b, finProdFinEquiv (k, a)) := by + change pack c d (swapEnds c d ((pack c d).symm (pack c d (a, k, b)))) = _ + rw [Equiv.symm_apply_apply] + rfl + +private theorem align_at {d : ℕ} (a b : Fin c) (k : Fin d) : + align c d (a, finProdFinEquiv (k, b)) = + (b, Fin.cast (Nat.mul_comm c d) (finProdFinEquiv (a, k))) := by + unfold align + simp [pack, swapEnds] + +private theorem spread {d : ℕ} (x : Grid c (d * c) → α) (a b : Fin c) + (i j : Fin (d * c)) (hij : i.val + c ≤ j.val) : + pass (pass x ∘ deal c d) (a, i) ≤ pass (pass x ∘ deal c d) (b, j) := by + refine interlace _ _ _ _ ?_ _ _ hij + intro k hk + obtain ⟨⟨u, v⟩, rfl⟩ := finProdFinEquiv.surjective k + have hu : 0 < u.val := by + change c ≤ v.val + c * u.val at hk + by_contra! h + rw [show u.val = 0 by omega, Nat.mul_zero, Nat.add_zero] at hk + omega + have hm : c * u.val = c * (u.val - 1) + c := by + rw [← Nat.mul_succ, Nat.succ_eq_add_one, Nat.sub_add_cancel hu] + have he : back c (finProdFinEquiv (u, v)) = finProdFinEquiv (back 1 u, v) := by + apply Fin.ext + change v.val + c * u.val - c = v.val + c * (u.val - 1) + omega + simp only [Function.comp_apply, he, deal_at] + apply sorted + change a.val + c * (u.val - 1) ≤ b.val + c * u.val + omega + +variable {r : ℕ} + +private def firstTwo (x : Grid c (2 * r * c) → α) := + pass (pass x ∘ deal c (2 * r)) ∘ align c (2 * r) + +/-- Between distinct aligned blocks, an inversion must cross from the +second half of one block to the first half of its immediate successor. -/ +private theorem crossing (hc : c ≤ r) (x : Grid c (2 * r * c) → α) + {a b : Fin c} {i j : Fin (2 * r * c)} (hab : a < b) + (h : firstTwo x (b, j) < firstTwo x (a, i)) : + a.val + 1 = b.val ∧ r * c ≤ i.val ∧ j.val < r * c := by + obtain ⟨⟨u, v⟩, rfl⟩ := finProdFinEquiv.surjective i + obtain ⟨⟨y, z⟩, rfl⟩ := finProdFinEquiv.surjective j + simp only [firstTwo, Function.comp_apply, align_at] at h + have near : y.val + 2 * r * b.val < u.val + 2 * r * a.val + c := by + by_contra! hh + exact h.not_ge (spread x _ _ _ _ hh) + have reach (k : ℕ) (hk : a.val + k ≤ b.val) : + 2 * r * a.val + 2 * r * k ≤ 2 * r * b.val := by + rw [← Nat.mul_add] + exact Nat.mul_le_mul_left _ hk + have hnext : a.val + 1 = b.val := by + by_contra! hh + have := reach 2 (by omega) + omega + have := reach 1 hnext.le + have hu : r ≤ u.val := by omega + have hy : y.val + 1 ≤ r := by omega + change _ ∧ r * c ≤ v.val + c * u.val ∧ z.val + c * y.val < r * c + have hlo := Nat.mul_le_mul_left c hu + have hhi := Nat.mul_le_mul_left c hy + rw [Nat.mul_add] at hhi + rw [Nat.mul_comm r c] + omega + +/-- Reindex an entry from the alternating halves of consecutive columns. -/ +def staggerAt (z : Grid c (2 * r * c)) : Grid c (2 * r * c) := + if h : z.2.val < r * c then + if z.1.val = 0 then z else + (z.1, ⟨z.2.val + r * c, by have := Nat.mul_assoc 2 r c; omega⟩) + else if k : z.1.val + 1 < c then + (⟨z.1.val + 1, k⟩, back (r * c) z.2) + else (⟨0, by have := z.1.isLt; omega⟩, z.2) + +/-- Within each staggered block the two layouts give the same order. -/ +private theorem stagger_le (u v : Grid c (2 * r * c)) + (h : (staggerAt u).1 = (staggerAt v).1) : + (staggerAt u).2 ≤ (staggerAt v).2 ↔ toLex u ≤ toLex v := by + have he : 2 * r * c = 2 * (r * c) := Nat.mul_assoc .. + rw [Prod.Lex.toLex_le_toLex] + simp only [staggerAt, back] at h ⊢ + split_ifs at * <;> simp only [Fin.ext_iff, Fin.le_def, Fin.lt_def] at h ⊢ <;> omega + +/-- Map aligned positions to their slots in the final pass. Block zero +contains the two end halves in their original order. -/ +noncomputable def stagger (c r : ℕ) : Equiv.Perm (Grid c (2 * r * c)) := + Equiv.ofBijective staggerAt <| (Fintype.bijective_iff_injective_and_card _).mpr ⟨by + intro u v h + have e := congrArg Prod.fst h + exact toLex.injective (le_antisymm ((stagger_le _ _ e).1 (by rw [h])) + ((stagger_le _ _ e.symm).1 (by rw [h]))), rfl⟩ + +/-- All remaining inversions after pass three lie in one staggered block +per inversion. Sorting that block then resolves the inversion. -/ +private theorem afterThree (hc : c ≤ r) (x : Grid c (2 * r * c) → α) + (u v : Grid c (2 * r * c)) (hle : toLex u ≤ toLex v) + (hne : (staggerAt u).1 ≠ (staggerAt v).1) : + pass (firstTwo x) u ≤ pass (firstTwo x) v := by + obtain ⟨a, i⟩ := u + obtain ⟨b, j⟩ := v + rcases Prod.Lex.toLex_le_toLex.mp hle with hab | ⟨he, hij⟩ + · by_contra! inv + obtain ⟨k, hk, hk'⟩ := (witnesses (firstTwo x) a i).1 + obtain ⟨l, hl, hl'⟩ := (witnesses (firstTwo x) b j).2 + obtain ⟨he, hhi, hlo⟩ := crossing hc x hab ((hl'.trans_lt inv).trans_le hk') + change a.val + 1 = b.val at he + apply hne + simp only [staggerAt, dite_eq_left (by omega : j.val < r * c), + dite_eq_right (by omega : ¬ i.val < r * c), dite_eq_left (by omega : a.val + 1 < c), + ite_eq_right (by omega : ¬ b.val = 0)] + exact Fin.ext he + · change a = b at he + subst b + exact sorted _ _ hij + +private theorem cleanup (y : Grid c n → α) (g : Equiv.Perm (Grid c n)) + (hg : ∀ u v, (g u).1 = (g v).1 → ((g u).2 ≤ (g v).2 ↔ toLex u ≤ toLex v)) + (hy : ∀ u v, toLex u ≤ toLex v → (g u).1 ≠ (g v).1 → y u ≤ y v) + (u v : Grid c n) (h : toLex u ≤ toLex v) : + pass (y ∘ g.symm) (g u) ≤ pass (y ∘ g.symm) (g v) := by + by_cases he : (g u).1 = (g v).1 + · have := sorted (y ∘ g.symm) (g u).1 ((hg u v he).2 h) + change pass _ (g u) ≤ pass _ ((g u).1, (g v).2) at this + rwa [he] at this + · obtain ⟨i, hi, hi'⟩ := (witnesses (y ∘ g.symm) (g u).1 (g u).2).1 + obtain ⟨j, hj, hj'⟩ := (witnesses (y ∘ g.symm) (g v).1 (g v).2).2 + let a := g.symm ((g u).1, i) + let b := g.symm ((g v).1, j) + have ha : g a = ((g u).1, i) := g.apply_symm_apply _ + have hb : g b = ((g v).1, j) := g.apply_symm_apply _ + have ha' := (hg a u (by rw [ha])).1 (by rwa [ha]) + have hb' := (hg v b (by rw [hb])).1 (by rwa [hb]) + exact hi'.trans ((hy a b (ha'.trans (h.trans hb')) (by rwa [ha, hb])).trans hj') + +/-- Each pass invokes one short sorter per column. -/ +noncomputable def fourPass (x : Grid c (2 * r * c) → α) : Grid c (2 * r * c) → α := + pass (pass (pass (pass x ∘ deal c (2 * r)) ∘ align c (2 * r)) ∘ (stagger c r).symm) ∘ + stagger c r + +theorem fourPass_sorted (hc : c ≤ r) (x : Grid c (2 * r * c) → α) + (u v : Grid c (2 * r * c)) (h : toLex u ≤ toLex v) : fourPass x u ≤ fourPass x v := + cleanup _ (stagger c r) stagger_le (afterThree hc x) u v h + +theorem fourPass_perm (x : Grid c (2 * r * c) → α) : + ∃ e : Equiv.Perm (Grid c (2 * r * c)), fourPass x = x ∘ e := by + obtain ⟨e₁, h₁⟩ := pass_perm x + obtain ⟨e₂, h₂⟩ := pass_perm (pass x ∘ deal c (2 * r)) + obtain ⟨e₃, h₃⟩ := pass_perm (firstTwo x) + obtain ⟨e₄, h₄⟩ := pass_perm (pass (firstTwo x) ∘ (stagger c r).symm) + refine ⟨(stagger c r).trans (e₄.trans ((stagger c r).symm.trans + (e₃.trans ((align c (2 * r)).trans (e₂.trans ((deal c (2 * r)).trans e₁)))))), ?_⟩ + change pass (pass (firstTwo x) ∘ (stagger c r).symm) ∘ stagger c r = _ + rw [h₄, h₃, firstTwo, h₂, h₁] + rfl + +private theorem unpack_monotone {i j : Fin (c * n)} (h : i ≤ j) : + toLex (finProdFinEquiv.symm i) ≤ toLex (finProdFinEquiv.symm j) := by + obtain ⟨⟨a, u⟩, rfl⟩ := finProdFinEquiv.surjective i + obtain ⟨⟨b, v⟩, rfl⟩ := finProdFinEquiv.surjective j + change u.val + n * a.val ≤ v.val + n * b.val at h + rw [Equiv.symm_apply_apply, Equiv.symm_apply_apply, Prod.Lex.toLex_le_toLex] + rcases lt_trichotomy a b with hab | rfl | hab + · exact .inl hab + · exact .inr ⟨rfl, by change u ≤ v; omega⟩ + · have := Nat.mul_le_mul_left n (show b.val + 1 ≤ a.val by omega) + rw [Nat.mul_add] at this + omega + +private theorem tuple_eq (x : Fin (c * n) → α) (y : Grid c n → α) + (hs : ∀ u v, toLex u ≤ toLex v → y u ≤ y v) + (he : ∃ e : Equiv.Perm (Grid c n), y = (x ∘ finProdFinEquiv) ∘ e) : + y = (x ∘ Tuple.sort x) ∘ finProdFinEquiv := by + let p := @finProdFinEquiv c n + have hm : Monotone (y ∘ p.symm) := + fun i j h => hs _ _ (unpack_monotone h) + obtain ⟨e, he⟩ := he + rw [he] at hm ⊢ + change Monotone (x ∘ (p.symm.trans (e.trans p))) at hm + have h := Tuple.unique_monotone hm (Tuple.monotone_sort x) + funext z + simpa only [Function.comp_apply, Equiv.trans_apply, Equiv.symm_apply_apply] + using congrFun h (p z) + +/-- A full tuple sort factors through four calls to the parallel short +sorter. The three permutations are fixed before the input is given. -/ +theorem factor (hc : c ≤ r) (hn : n = 2 * r * c) : + ∃ D A S : Equiv.Perm (Grid c n), ∀ x : Fin (c * n) → α, + pass (pass (pass (pass (x ∘ finProdFinEquiv) ∘ D) ∘ A) ∘ S.symm) ∘ S = + (x ∘ Tuple.sort x) ∘ finProdFinEquiv := by + subst n + refine ⟨deal c (2 * r), align c (2 * r), stagger c r, fun x => ?_⟩ + let p := @finProdFinEquiv c (2 * r * c) + change fourPass (x ∘ p) = (x ∘ Tuple.sort x) ∘ p + exact tuple_eq x _ (fourPass_sorted hc _) (fourPass_perm _) + +end MatrixMultiplicationAllFields.MatrixExponent.Columns +end + +section +/- # Wiring four layers of parallel short sorting networks -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Columns + +/-- Column lifting uses only composition and reordering. The same proof +works for trivalent gates and high-arity sorting gates. -/ +structure Model where + /-- The `Model` field of type `(a b : Wire) → (Val a → Val b) → ℕ → Prop`. -/ + Runs : (a b : Wire) → (Val a → Val b) → ℕ → Prop + pre {a b c f g m} : Runs b c g m → Rewire a b f → Runs a c (fun x => g (f x)) m + post {a b c f g m} : Runs a b f m → Rewire b c g → Runs a c (fun x => g (f x)) m + comp {a b c f g m n} : Runs a b f m → Runs b c g n → Runs a c (fun x => g (f x)) (m + n) + mono {a b f m n} : Runs a b f m → m ≤ n → Runs a b f n + +/-- Uses `⟨DNet F, DNet.pre, DNet.post, DNet.comp, DNet.mono⟩` as the representation. -/ +def trivalent (F : Type) [Field F] : Model := + ⟨DNet F, DNet.pre, DNet.post, DNet.comp, DNet.mono⟩ + +namespace Model + +variable (M : Model) {a b u : Wire} [LinearOrder (Val a)] {c n m t : ℕ} + +private theorem assemble (B : Layout a b (Grid c n)) (U : Layout a u (Fin (c * n))) + {f : Val b → Val b} {g : Val u → Val u} (h : M.Runs (copies b t) (copies b t) (mapCopies f t) m) + (hf : ∀ x, B.read (f x) = pass (B.read x)) + (hg : ∀ x, U.read (g x) = U.read x ∘ Tuple.sort (U.read x)) + {r : ℕ} (hc : c ≤ r) (hn : n = 2 * r * c) : + M.Runs (copies u t) (copies u t) (mapCopies g t) (4 * m) := by + obtain ⟨D, A, S, he⟩ := factor (α := Val a) hc hn + obtain ⟨pre, hpre, epre⟩ := U.rewire B finProdFinEquiv + obtain ⟨d, hd, ed⟩ := B.rewire B D + obtain ⟨j, hj, ej⟩ := B.rewire B A + obtain ⟨s, hs, es⟩ := B.rewire B S.symm + obtain ⟨post, hpost, epost⟩ := B.rewire U (finProdFinEquiv.symm.trans S) + have eqn : (fun x => post (f (s (f (j (f (d (f (pre x))))))))) = g := by + funext x + apply U.injective + rw [epost, hf, es, hf, ej, hf, ed, hf, epre, hg] + funext i + simpa only [Function.comp_apply, Equiv.trans_apply, Equiv.apply_symm_apply] + using congrFun (he (U.read x)) (finProdFinEquiv.symm i) + have lifted (k : ℕ) (x : Val (copies u k)) : + mapCopies post k (mapCopies f k (mapCopies s k (mapCopies f k + (mapCopies j k (mapCopies f k (mapCopies d k (mapCopies f k (mapCopies pre k x)))))))) = + mapCopies g k x := by + induction k with + | zero => rfl + | succ k ih => exact Prod.ext (congrFun eqn x.1) (ih x.2) + rw [← funext (lifted t), show 4 * m = ((m + m) + m) + m by omega] + have h₁ := M.pre h (hpre.mapCopies t) + have h₂ := M.comp h₁ (M.pre h (hd.mapCopies t)) + have h₃ := M.comp h₂ (M.pre h (hj.mapCopies t)) + have hr := M.post (M.comp h₃ (M.pre h (hs.mapCopies t))) (hpost.mapCopies t) + exact hr + +private theorem read_parallel {w : ℕ} (L : Layout (tree w a) (copies (tree w a) c) (Fin c)) + (T : Layout a (tree w a) (Fin n)) + (hL : ∀ (f : Val (tree w a) → Val (tree w a)) x, L.read (mapCopies f c x) = f ∘ L.read x) + (hT : ∀ x, List.ofFn (T.read x) = flatten w x) (x : Val (copies (tree w a) c)) : + (L.nest T).read (mapCopies (sortTree w) c x) = pass ((L.nest T).read x) := by + funext ⟨i, j⟩ + simp only [pass, Layout.read_nest, hL, Function.comp_apply, T.read_sort hT] + +private theorem map_append (f : Val b → Val b) (d n : ℕ) + (x : Val (copies b d)) (y : Val (copies b n)) : + mapCopies f (n + d) (appendCopies b d n (x, y)) = + appendCopies b d n (mapCopies f d x, mapCopies f n y) := by + induction d with + | zero => rfl + | succ d ih => exact Prod.ext rfl (ih x.2) + +private theorem map_join (f : Val b → Val b) (d t : ℕ) (x : Val (copies (copies b d) t)) : + mapCopies f (d * t) (joinCopies b d t x) = + joinCopies b d t (mapCopies (mapCopies f d) t x) := by + induction t with + | zero => rfl + | succ t ih => + change mapCopies f (d * t + d) (appendCopies b d (d * t) _) = _ + rw [map_append, ih] + rfl + +private theorem regroup {f : Val b → Val b} {d : ℕ} + (h : M.Runs (copies b (d * t)) (copies b (d * t)) (mapCopies f (d * t)) m) : + M.Runs (copies (copies b d) t) (copies (copies b d) t) + (mapCopies (mapCopies f d) t) m := by + have j := Rewire.joinCopies b d t + obtain ⟨s, hs, he⟩ := j.inverse + have eqn : (fun x => s (mapCopies f (d * t) (joinCopies b d t x))) = + mapCopies (mapCopies f d) t := by + funext x + exact ((he _ _).mp (map_join f d t x).symm).symm + rw [← eqn] + exact M.post (M.pre h j) hs + +/-- Combine groups of `2^v` short sorts, preserving independence between +the `t` resulting long sorts. No factorization of the input network is needed. -/ +theorem sort_lift_batch {v w : ℕ} (hw : 2 * v + 1 ≤ w) + (h : M.Runs (copies (tree w a) (2 ^ v * t)) (copies (tree w a) (2 ^ v * t)) + (mapCopies (sortTree w) (2 ^ v * t)) m) : + M.Runs (copies (tree (w + v) a) t) (copies (tree (w + v) a) t) + (mapCopies (sortTree (w + v)) t) (4 * m) := by + let r := 2 ^ (w - v - 1) + have hc : 2 ^ v ≤ r := Nat.pow_le_pow_right (by decide) (by omega) + have hn : 2 ^ w = 2 * r * 2 ^ v := by + unfold r + rw [← pow_succ', ← pow_add, show w - v - 1 + 1 + v = w by omega] + have hU := Layout.exists_tree a (w + v) + rw [pow_add, Nat.mul_comm (2 ^ w)] at hU + obtain ⟨U, hU⟩ := hU + obtain ⟨T, hT⟩ := Layout.exists_tree a w + obtain ⟨L, hL⟩ := Layout.exists_copies (tree w a) (2 ^ v) + exact M.assemble (L.nest T) U (M.regroup h) (read_parallel L T hL hT) (U.read_sort hU) hc hn + +private theorem single {f : Val b → Val b} + (h : M.Runs (copies b 1) (copies b 1) (mapCopies f 1) m) : M.Runs b b f m := + by + have he := M.post (M.pre h (.unit' _)) (.unit _) + exact he + +theorem sort_lift {v w : ℕ} (hw : 2 * v + 1 ≤ w) + (h : M.Runs (copies (tree w a) (2 ^ v)) (copies (tree w a) (2 ^ v)) + (mapCopies (sortTree w) (2 ^ v)) m) : + M.Runs (tree (w + v) a) (tree (w + v) a) (sortTree (w + v)) (4 * m) := by + apply M.single + apply M.sort_lift_batch hw + rwa [mul_one] + +/-- Each full lift multiplies the address length minus two by at least 3/2. +The cost of `k` lifts is at most `4^k` times the initial batch size. -/ +theorem sort_lift_iterate {v w : ℕ} (hw : 2 ≤ w) (k : ℕ) + (hv : 2 ^ k * (w + v - 2) ≤ 3 ^ k * (w - 2)) + (h : M.Runs (copies (tree w a) (2 ^ v)) (copies (tree w a) (2 ^ v)) + (mapCopies (sortTree w) (2 ^ v)) m) : + M.Runs (tree (w + v) a) (tree (w + v) a) (sortTree (w + v)) (4 ^ k * m) := by + induction k generalizing v w m with + | zero => + have : v = 0 := by simp only [pow_zero, one_mul] at hv; omega + subst v + simpa using M.single h + | succ k ih => + by_cases small : 2 * v + 1 ≤ w + · apply M.mono (M.sort_lift small h) + exact Nat.mul_le_mul_right m (by rw [pow_succ]; have := Nat.one_le_pow k 4 (by decide); omega) + let d := (w - 1) / 2 + have hi : 2 * d + 1 ≤ w := by omega + have he : d + (v - d) = v := by omega + have ha : w + d + (v - d) = w + v := by omega + have hb : 3 * (w - 2) ≤ 2 * (w + d - 2) := by omega + have hbound : 2 ^ k * (w + d + (v - d) - 2) ≤ 3 ^ k * (w + d - 2) := by + rw [ha, ← Nat.mul_le_mul_left_iff (by decide : 0 < 2)] + calc + _ = 2 ^ (k + 1) * (w + v - 2) := by rw [pow_succ', mul_assoc] + _ ≤ 3 ^ (k + 1) * (w - 2) := hv + _ ≤ 3 ^ k * (2 * (w + d - 2)) := by rw [pow_succ, mul_assoc]; exact Nat.mul_le_mul_left _ hb + _ = _ := by rw [mul_left_comm] + have h₁ := sort_lift_batch (t := 2 ^ (v - d)) (M := M) (a := a) (m := m) hi (by + rwa [← pow_add, he]) + have h₂ := ih (by omega : 2 ≤ w + d) hbound h₁ + rwa [ha, ← mul_assoc, ← pow_succ] at h₂ + +end Model + +variable {F : Type} [Field F] {a : Wire} [LinearOrder (Val a)] {m t : ℕ} + +theorem sort_lift_batch {v w : ℕ} (hw : 2 * v + 1 ≤ w) + (h : DNet F (copies (tree w a) (2 ^ v * t)) (copies (tree w a) (2 ^ v * t)) + (mapCopies (sortTree w) (2 ^ v * t)) m) : + DNet F (copies (tree (w + v) a) t) (copies (tree (w + v) a) t) + (mapCopies (sortTree (w + v)) t) (4 * m) := + (trivalent F).sort_lift_batch hw h + +theorem sort_lift {v w : ℕ} (hw : 2 * v + 1 ≤ w) + (h : DNet F (copies (tree w a) (2 ^ v)) (copies (tree w a) (2 ^ v)) + (mapCopies (sortTree w) (2 ^ v)) m) : + DNet F (tree (w + v) a) (tree (w + v) a) (sortTree (w + v)) (4 * m) := + (trivalent F).sort_lift hw h + +theorem sort_lift_iterate {v w : ℕ} (hw : 2 ≤ w) (k : ℕ) + (hv : 2 ^ k * (w + v - 2) ≤ 3 ^ k * (w - 2)) + (h : DNet F (copies (tree w a) (2 ^ v)) (copies (tree w a) (2 ^ v)) + (mapCopies (sortTree w) (2 ^ v)) m) : + DNet F (tree (w + v) a) (tree (w + v) a) (sortTree (w + v)) (4 ^ k * m) := + (trivalent F).sort_lift_iterate hw k hv h + +theorem sort_lift_three {v w : ℕ} (hw : 40 ≤ w) (hv : v ≤ 3 * w / 2) + (h : DNet F (copies (tree w a) (2 ^ v)) (copies (tree w a) (2 ^ v)) + (mapCopies (sortTree w) (2 ^ v)) m) : + DNet F (tree (w + v) a) (tree (w + v) a) (sortTree (w + v)) (64 * m) := + sort_lift_iterate (by omega) 3 (by omega) h + +end MatrixMultiplicationAllFields.MatrixExponent.Columns +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Hard.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Hard.lean new file mode 100644 index 0000000000..d3807dbe0a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Hard.lean @@ -0,0 +1,26 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Tags + +/-! # Power-of-logarithm lower bound for verifying one permutation -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged +open Filter + +/-- Only square payloads at powers of two are required. Count vertices +of exact trivalent networks. Any constant in the lower bound can be +absorbed by decreasing the positive exponent. -/ +def Hard (F : Type) [Field F] : Prop := + ∃ σ : ℝ, 0 < σ ∧ ∀ᶠ w : ℕ in atTop, ∀ m, + Net F (inputs w (word w)) .unit (tag F w (word w)) m → + (2 : ℝ) ^ w * w * (w : ℝ) ^ σ ≤ m + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Reduction.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Reduction.lean new file mode 100644 index 0000000000..68c6c0f936 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Reduction.lean @@ -0,0 +1,425 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Tags +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.ColumnNetwork +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortOne +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortBack +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Hard + +/-! # Width and sorting costs for many independent lists -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +open Filter + +/-- Two sorting lifts pay for each doubling of the record width. -/ +private theorem lift_range {w v k : ℕ} (hw : 5 ≤ w) (h : 2 * (w + v) ≤ 2 ^ k * (w + 1)) : + 2 ^ (2 * k) * (w + v - 2) ≤ 3 ^ (2 * k) * (w - 2) := by + have hb : w + v - 2 ≤ 2 ^ k * (w - 2) := by + have hm := h.trans (Nat.mul_le_mul_left (2 ^ k) (show w + 1 ≤ 2 * (w - 2) by omega)) + rw [mul_left_comm (2 ^ k)] at hm + omega + calc + _ ≤ 2 ^ (2 * k) * (2 ^ k * (w - 2)) := Nat.mul_le_mul_left _ hb + _ = 8 ^ k * (w - 2) := by rw [pow_mul, ← mul_assoc, ← mul_pow]; rfl + _ ≤ 3 ^ (2 * k) * (w - 2) := by rw [pow_mul]; gcongr; decide + +/-- Reserve enough exponent slack to absorb both width doubling and +parallel sort lifting, uniformly in the logarithm `v` of the batch size. -/ +theorem parameters {s : ℝ} (hs : 0 < s) : + ∃ η : ℝ, 0 < η ∧ ∀ᶠ w : ℕ in atTop, ∀ v : ℕ, + (v : ℝ) ≤ ((w + 1 : ℕ) : ℝ) ^ (1 + η) → + ∃ k j : ℕ, 2 * (w + v) ≤ 2 ^ k * (w + 1) ∧ 2 ^ j * (w + v - 2) ≤ 3 ^ j * (w - 2) ∧ + (4 : ℝ) ^ k * 4 ^ j * 100000000 * ((w + 1 : ℕ) : ℝ) ^ η ≤ (w : ℝ) ^ s := by + let η := s / 15 + have hη : 0 < η := by positivity + refine ⟨η, hη, ?_⟩ + have ht : Tendsto (fun w : ℕ => (w : ℝ) ^ η) atTop atTop := + (tendsto_rpow_atTop hη).comp tendsto_natCast_atTop_atTop + filter_upwards [eventually_ge_atTop 5, ht.eventually_ge_atTop (8 ^ 6 * 100000000)] + with w hw hlarge + intro v hv + have hw' : 5 ≤ (w : ℝ) := by exact_mod_cast hw + let A := ((w + 1 : ℕ) : ℝ) ^ η + let z := (w : ℝ) ^ η + have hA : 1 ≤ A := Real.one_le_rpow (by exact_mod_cast (by omega : 1 ≤ w + 1)) hη.le + have hAz : A ≤ z ^ 2 := by + calc + A ≤ ((w : ℝ) ^ 2) ^ η := Real.rpow_le_rpow (by positivity) (by push_cast; nlinarith) hη.le + _ = z ^ 2 := by + rw [← Real.rpow_natCast_mul (by positivity), mul_comm, + Real.rpow_mul_natCast (by positivity)] + obtain ⟨l, hlo, hhi⟩ := exists_nat_pow_near (by linarith : 1 ≤ 4 * A) (by norm_num : 1 < (2 : ℝ)) + let k := l + 1 + have hk : (2 : ℝ) ^ k ≤ 8 * A := by unfold k; rw [pow_succ]; linarith + have hwidth : 2 * (w + v) ≤ 2 ^ k * (w + 1) := by + rw [Real.rpow_add (by positivity), Real.rpow_one] at hv + change (v : ℝ) ≤ ((w + 1 : ℕ) : ℝ) * A at hv + have hp := mul_le_mul_of_nonneg_right hhi.le (by positivity : (0 : ℝ) ≤ w + 1) + have : (2 : ℝ) * (w + v) ≤ (2 : ℝ) ^ k * (w + 1) := by + push_cast at hv + unfold k + nlinarith only [hw', hv, hp, hA] + exact_mod_cast this + refine ⟨k, 2 * k, hwidth, lift_range hw hwidth, ?_⟩ + calc + _ = ((2 : ℝ) ^ k) ^ 6 * 100000000 * A := by + rw [pow_mul, ← mul_pow, pow_right_comm] + norm_num [A] + _ ≤ (8 * z ^ 2) ^ 6 * 100000000 * z ^ 2 := by + gcongr + exact hk.trans (by gcongr) + _ = (8 ^ 6 * 100000000) * z ^ 14 := by ring + _ ≤ z * z ^ 14 := mul_le_mul_of_nonneg_right hlarge (by positivity) + _ = (w : ℝ) ^ s := by + rw [← pow_succ', ← Real.rpow_mul_natCast (by positivity : 0 ≤ (w : ℝ))] + congr 1 + unfold η + ring + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- +# Signed distinctness and permutation verification + +Each row of the first list either remains real (weight `-1`) or +receives a dummy flag (weight `1`). If a row is absent from the +second list, summing over its flag gives zero in every characteristic. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable (F : Type) [Field F] {a b : Wire} (E : Val .bit → Val a → Val b) + (hE : Function.Injective (Function.uncurry E)) + +include hE in +private theorem enc_eq (p q : Bool) (x y : Val a) : + E p x = E q y ↔ p = q ∧ x = y := by + exact (hE.eq_iff (a := (p, x)) (b := (q, y))).trans Prod.ext_iff + +open Classical in +private noncomputable def term (B : List (Val a)) (w : ℕ) (A : Val (tree w a)) (z : Val (tree w + .bit)) : F := + sign F w z * if (B.map (E false)).Disjoint (flatten w (zipRows E w z A)) then 1 else 0 + +open Classical in +include hE in +private theorem sum_term (B : List (Val a)) (w : ℕ) (A : Val (tree w a)) : + (∑ z, term F E B w A z) = if flatten w A ⊆ B then 1 else 0 := by + induction w with + | zero => + rw [Fintype.sum_bool] + by_cases h : A ∈ B <;> + simp [term, sign, flatten, zipRows, List.disjoint_singleton, enc_eq E hE, h] + | succ w ih => + have split (z : Val (tree (w + 1) .bit)) : + term F E B (w + 1) A z = term F E B w A.1 z.1 * term F E B w A.2 z.2 := by + simp only [term, sign, flatten, zipRows, List.disjoint_append_right, ite_and, + mul_ite, ite_mul, mul_one, mul_zero, zero_mul] + simp only [← ite_and, and_comm] + simp_rw [split] + rw [Fintype.sum_prod_type, ← Fintype.sum_mul_sum, ih, ih] + simp only [flatten, List.append_subset, ite_and, ite_mul, one_mul, zero_mul] + +include hE in +/-- A signed test of distinctness on twice as many rows checks a permutation. +The first list must have distinct rows, as it does when tagged by position. -/ +theorem cancel (w : ℕ) (A B : Val (tree w a)) (hA : (flatten w A).Nodup) : + (∑ z : Val (tree w .bit), sign F w z * + (if (flatten (w + 1) (tested E w A B z)).Nodup then 1 else 0)) = permuted F w A B := by + classical + have row (p q : Bool) (x y : Val a) (h : E p x = E q y) : x = y := + ((enc_eq E hE p q x y).mp h).2 + have inj : Function.Injective (E false) := row false false + have hd (z : Val (tree w .bit)) := nodup_zipRows E row w z A hA + simp only [tested, flatten, flatten_mapRows, List.nodup_append', List.nodup_map_iff inj, + hd, true_and, permuted] + by_cases hB : (flatten w B).Nodup + · have hp : (flatten w B).Perm (flatten w A) ↔ flatten w A ⊆ flatten w B := + ⟨fun h => h.symm.subset, + fun h => ((hA.subperm h).perm_of_length_le (by simp [length_flatten])).symm⟩ + simpa only [hB, true_and, hp, term] using sum_term F E hE (flatten w B) w A + · have hp : ¬ (flatten w B).Perm (flatten w A) := fun h => hB (h.symm.nodup hA) + simp [hB, hp] + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- # Tagged permutation queries from element distinctness -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {a b : Wire} {w t m : ℕ} + +private def distinct (F : Type) [Field F] (w : ℕ) (a : Wire) (x : Val (tree w a)) + (_ : Val .unit) : F := + if (flatten w x).Nodup then 1 else 0 + +private theorem batch_distinct (h : Realizes F w t m) : + Batch (distinct F w (word (2 * w))) t m := by + obtain ⟨v, hv, rfl⟩ := h + refine ⟨v, Nat.le_add_right _ _, hv.rewire (.listCopies w t) (.unitCopies t) ?_⟩ + intro x y + exact power_distinct F w t x _ + +private theorem prepare_comp (E : Val .bit → Val (row w a) → Val b) + (h : Function.Injective (Function.uncurry E)) : + (fun x y => ∑ z, prepare E F x z * distinct F (w + 1) b z y) = tag F w a := by + funext x y + simp only [prepare, Finset.sum_mul] + rw [Finset.sum_comm] + simp only [mul_assoc, ite_mul, one_mul, zero_mul, ← Finset.mul_sum, Finset.sum_ite_eq, + Finset.mem_univ, ite_true] + exact cancel F E h w _ _ (label_nodup w x.1) + +/-- A network testing `t` lists on independent inputs gives one checking +`t` independently specified permutations. The extra cost is linear in +the total input length and does not depend on the coefficient field. -/ +theorem tag_of_distinct (h : Realizes F (w + 1) t m) : + Batch (tag F w (word (w + 1))) t (m + 3 * t * listBits (w + 1)) := by + obtain ⟨f, hf, hi⟩ := Rewire.exists_of_width + (a := .pair .bit (row w (word (w + 1)))) (b := word (2 * (w + 1))) + (by simp only [wd, wd_word]; omega) + let E : Val .bit → Val (row w (word (w + 1))) → Val (word (2 * (w + 1))) := fun i x => f (i, x) + obtain ⟨v, hv, hg⟩ := prepare_net (F := F) E hf + have hp := (Batch.of_net hg t).comp (batch_distinct h) + rw [prepare_comp E hi] at hp + apply hp.mono + calc + t * v + m ≤ t * (2 ^ w * (5 * w + 6 * wd (word (w + 1)) + 4)) + m := + Nat.add_le_add_right (Nat.mul_le_mul_left t hv) m + _ ≤ m + 3 * t * listBits (w + 1) := by + rw [wd_word, listBits, pow_succ] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- # Restricting a batch by fixing extra inputs to accepting constants -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {a : Wire} {s t m : ℕ} + +private def repeatRow (x : Val a) : (n : ℕ) → Val (copies a n) + | 0 => () + | n + 1 => (x, repeatRow x n) + +private theorem repeat_ok {k : Val a → Val .unit → F} {x : Val a} (h : k x () = 1) + (n : ℕ) : power k n (repeatRow x n) (unitCopies n) = 1 := by + induction n with + | zero => rfl + | succ n ih => simp only [power, repeatRow, unitCopies, h, ih, mul_one] + +theorem Batch.truncate {k : Val a → Val .unit → F} (h : Batch k t m) (hst : s ≤ t) + (x : Val a) (hx : k x () = 1) : Batch k s (m + t * wd a) := by + obtain ⟨u, rfl⟩ := Nat.exists_eq_add_of_le hst + obtain ⟨v, hv, h⟩ := h + let z := repeatRow x u + have p := ((literal_net F _ z).par (DNet.id F (copies a s))).pre + ((Rewire.unit' _).comp (.swap _ _)) + obtain ⟨n, hn, g⟩ := p.post (.appendCopies a u s) + have out := (Rewire.copiesUnit s).comp (Rewire.unitCopies (s + u)) + refine ⟨n + v, ?_, ?_⟩ + · simp only [wd_copies, add_mul] at hn ⊢ + omega + · convert g.comp (h.post out) using 1 + funext y r + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + rw [← eq_unitCopies _ (appendCopies .unit u s (unitCopies u, r)), power_append] + rw [repeat_ok hx, one_mul] + +theorem tag_truncate {w : ℕ} (h : Batch (tag F w a) t m) (hst : s ≤ t) : + Batch (tag F w a) s (m + t * 2 ^ w * (w + 2 * wd a)) := by + let A := (bits (tree w a)).symm (fun _ => false) + have h' := h.truncate hst (A, label w A) (by simp [tag, permuted]) + apply h'.mono + simp only [wd, wd_tree, row, wd_word] + exact le_of_eq (by ring) + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- # Transferring a distinctness batch to one large permutation verifier -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {w t m v k j : ℕ} + +private theorem bit_cost (h : Realizes F (w + 1) t m) : + t * 2 ^ w * (w + 1) ≤ m := by + obtain ⟨z, _, rfl⟩ := h + rw [listBits, pow_succ] + ring_nf + omega + +private theorem small_tags (h : Realizes F (w + 1) t m) (ht : 2 ^ v ≤ t) : + Batch (tag F w (word (w + 1))) (2 ^ v) (5 * m) := by + apply (tag_truncate (tag_of_distinct h) ht).mono + obtain ⟨z, _, rfl⟩ := h + rw [wd_word, listBits, pow_succ] + ring_nf + omega + +private theorem slice_cost (k : ℕ) : (6 * k + 2) * 2 ^ k ≤ 8 * 4 ^ k := by + have hk : k < 2 ^ k := Nat.lt_two_pow_self + calc + _ ≤ (8 * 2 ^ k) * 2 ^ k := by gcongr; omega + _ = _ := by rw [mul_assoc, ← mul_pow]; rfl + +/-- The replication exponent is `v`. Using `2^k` slices and `j` column +lifts costs at most a constant times `4^k 4^j` times the initial size. -/ +theorem transfer (h : Realizes F (w + 1) t m) (hw : 2 ≤ w) (ht : 2 ^ v ≤ t) + (hk : 2 * (w + v) ≤ 2 ^ k * (w + 1)) (hj : 2 ^ j * (w + v - 2) ≤ 3 ^ j * (w - 2)) : + ∃ l ≤ 1000000 * 4 ^ k * 4 ^ j * m, + Net F (inputs (w + v) (word (w + v))) .unit (tag F (w + v) (word (w + v))) l := by + let a := row (w + v) (word (w + v)) + have hwidth : wd a = 2 * (w + v) := by simp only [a, wd, wd_word]; omega + have hpow : 2 ^ k ≤ 4 ^ k := Nat.pow_le_pow_left (by decide) _ + have hunit : w + 1 ≤ 4 ^ k * (w + 1) := Nat.le_mul_of_pos_left _ (by positivity) + have hwide : wd a ≤ 4 ^ k * (w + 1) := hwidth.le.trans + (hk.trans (Nat.mul_le_mul_right _ hpow)) + have hbits : 2 ^ v * 2 ^ w * (w + 1) ≤ m := + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ ht)).trans (bit_cost h) + have htag : Batch (tag F w a) (2 ^ v) (21 * 4 ^ k * m) := by + refine (tag_slices (small_tags h ht) k (by rw [wd_word, hwidth]; exact hk)).mono ?_ + rw [wd_word] + calc + _ ≤ 4 ^ k * (5 * m) + (8 * 4 ^ k) * 2 ^ v * 2 ^ w * (2 * (w + 1)) := by + have := slice_cost k + gcongr + omega + _ = 4 ^ k * (5 * m) + 16 * 4 ^ k * (2 ^ v * 2 ^ w * (w + 1)) := by ring + _ ≤ 4 ^ k * (5 * m) + 16 * 4 ^ k * m := by gcongr + _ = _ := by ring + obtain ⟨o, cmp⟩ := exists_comparator F a + let : LinearOrder (Val a) := o + have hs := Columns.sort_lift_iterate hw j hj (sort_of_tag htag cmp) + have H : wd a + w + 100 * (wd a + 1) + 1 ≤ 203 * (4 ^ k * (w + 1)) := by omega + have hs' := hs.mono (n := 203021 * 4 ^ k * 4 ^ j * m) (by + calc + _ ≤ 4 ^ j * (21 * 4 ^ k * m + 1000 * 2 ^ v * 2 ^ w * (203 * (4 ^ k * (w + 1)))) := by gcongr + _ = 4 ^ j * (21 * 4 ^ k * m + 203000 * 4 ^ k * (2 ^ v * 2 ^ w * (w + 1))) := by ring + _ ≤ 4 ^ j * (21 * 4 ^ k * m + 203000 * 4 ^ k * m) := by gcongr + _ = _ := by ring) + obtain ⟨l, hl, hl'⟩ := tag_of_sort hs' + refine ⟨l, hl.trans ?_, hl'⟩ + have he : w + v + wd (word (w + v)) ≤ 4 ^ k * (w + 1) := by rw [wd_word]; omega + calc + _ ≤ 2 * (203021 * 4 ^ k * 4 ^ j * m) + 3 * 2 ^ (w + v) * (4 ^ k * (w + 1)) := by gcongr + _ = 2 * (203021 * 4 ^ k * 4 ^ j * m) + 3 * 4 ^ k * (2 ^ v * 2 ^ w * (w + 1)) + := by rw [pow_add]; ring + _ ≤ 2 * (203021 * 4 ^ k * 4 ^ j * m) + 3 * 4 ^ k * (4 ^ j * m) := by + have : m ≤ 4 ^ j * m := Nat.le_mul_of_pos_left _ (by positivity) + exact Nat.add_le_add_left (Nat.mul_le_mul_left _ (hbits.trans this)) _ + _ ≤ _ := by ring_nf; omega + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- +# From tagged permutations to independent lists + +A batch of size `t` gives one permutation verifier on +`2^(w + floor (log₂ t))` rows at list width `w+1`. The cost of +lifting the sort and slicing the payload is absorbed by the assumed +power-of-logarithm lower bound. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +open Filter + +private theorem space {w v t : ℕ} (hw : 2 ≤ w) (ht : t < 2 ^ (v + 1)) : + t * listBits (w + 1) < 100 * 2 ^ (w + v) * (w + v) := by + calc + _ < 2 ^ (v + 1) * listBits (w + 1) := Nat.mul_lt_mul_of_pos_right ht (by + unfold listBits + positivity) + _ = 2 ^ (w + v) * (8 * (w + 1)) := by unfold listBits; rw [pow_add, pow_add, pow_add]; ring + _ ≤ 2 ^ (w + v) * (100 * (w + v)) := Nat.mul_le_mul_left _ (by omega) + _ = _ := by ring + +variable {F : Type} [Field F] + +/-- The exact-network lower bound with a superpolynomial range of batch sizes. -/ +theorem manyList_full (h : Hard F) : + ∃ η : ℝ, 0 < η ∧ ∀ᶠ w : ℕ in atTop, ∀ t m : ℕ, + 1 ≤ t → (t : ℝ) ≤ (2 : ℝ) ^ ((w : ℝ) ^ (1 + η)) → Realizes F w t m → + (t : ℝ) * listBits w * (w : ℝ) ^ η < m := by + obtain ⟨σ, hs, hlower⟩ := h + obtain ⟨η, hη, hparam⟩ := parameters hs + obtain ⟨W, hW⟩ := eventually_atTop.mp (hlower.and hparam) + refine ⟨η, hη, ?_⟩ + filter_upwards [eventually_ge_atTop (W + 3)] with n hn t m ht hmax hnet + obtain ⟨w, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : n ≠ 0) + let v := Nat.log 2 t + have hv : 2 ^ v ≤ t := Nat.pow_log_le_self _ (by omega) + have hv' : (v : ℝ) ≤ ((w + 1 : ℕ) : ℝ) ^ (1 + η) := by + apply (Real.rpow_le_rpow_left_iff (by norm_num : (1 : ℝ) < 2)).mp + rw [Real.rpow_natCast] + exact (show (2 : ℝ) ^ v ≤ t by exact_mod_cast hv).trans hmax + obtain ⟨k, j, hk, hj, he⟩ := (hW w (by omega)).2 v hv' + obtain ⟨l, hl, hperm⟩ := transfer hnet (by omega) hv hk hj + have hsize : (t : ℝ) * listBits (w + 1) < 100 * (2 : ℝ) ^ (w + v) * (w + v : ℕ) := by + exact_mod_cast space (by omega : 2 ≤ w) (Nat.lt_pow_succ_log_self (by decide : 1 < 2) t) + let C := 1000000 * (4 : ℝ) ^ k * 4 ^ j + have hC : 0 < C := by unfold C; positivity + apply (mul_lt_mul_iff_right₀ hC).mp + calc + _ < C * (100 * (2 : ℝ) ^ (w + v) * (w + v : ℕ) * ((w + 1 : ℕ) : ℝ) ^ η) := by gcongr + _ = (2 : ℝ) ^ (w + v) * (w + v : ℕ) * + ((4 : ℝ) ^ k * 4 ^ j * 100000000 * ((w + 1 : ℕ) : ℝ) ^ η) := by unfold C; ring + _ ≤ (2 : ℝ) ^ (w + v) * (w + v : ℕ) * (w : ℝ) ^ σ := by gcongr + _ ≤ (2 : ℝ) ^ (w + v) * (w + v : ℕ) * ((w + v : ℕ) : ℝ) ^ σ := by gcongr; omega + _ ≤ l := (hW (w + v) (by omega)).1 l hperm + _ ≤ C * m := by unfold C; exact_mod_cast hl + +/-- Restrict the batch sizes to those needed by the compression iteration. -/ +theorem manyList_of_tag (h : Hard F) : ManyList (Realizes F) := by + obtain ⟨η, he, hl⟩ := manyList_full h + refine ⟨η, he, ?_⟩ + have grow := (tendsto_rpow_atTop he).comp tendsto_natCast_atTop_atTop + filter_upwards [hl, eventually_ge_atTop 1, grow.eventually_ge_atTop 3] + with w hlow hw hg t m ht hi hr + have hw' : 0 < (w : ℝ) := by exact_mod_cast hw + have ht' : t ≤ 2 ^ (w + w + w) := by + apply hi.trans + unfold listBits + rw [pow_add, pow_add] + gcongr + · exact Nat.le_pow hw + · exact Nat.lt_two_pow_self.le + have hmax : (t : ℝ) ≤ (2 : ℝ) ^ ((w : ℝ) ^ (1 + η)) := by + calc + _ ≤ (2 : ℝ) ^ (w + w + w) := by exact_mod_cast ht' + _ ≤ _ := by + rw [← Real.rpow_natCast, Real.rpow_add hw', Real.rpow_one] + apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + push_cast + change 3 ≤ (w : ℝ) ^ η at hg + nlinarith + exact (hlow t m ht hmax hr).trans_le (by linarith) + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/SortBack.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/SortBack.lean new file mode 100644 index 0000000000..77dcdcb35c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/SortBack.lean @@ -0,0 +1,92 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Batcher +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.BitonicMerge +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.CompareExchange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.AdjacentDuplicates + +/-! # Verifying a large permutation by sorting both lists -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {a : Wire} {w m : ℕ} + +theorem cap (a : Wire) : + Net F (.pair a a) .unit (fun x _ => if x.1 = x.2 then 1 else 0) (wd a) := by + induction a with + | bit => exact .table _ _ _ (by decide) + | unit => exact Net.empty.pre (.unit _) + | pair a b ha hb => + have h := ((ha.par hb).pre (.middle a b a b)).post (.unit' _) + simpa only [wd, Prod.ext_iff, ite_and, ite_mul, one_mul, zero_mul] using h + +private theorem sort_eq_iff [LinearOrder (Val a)] (x y : Val (tree w a)) : + sortTree w x = sortTree w y ↔ (flatten w y).Perm (flatten w x) := by + constructor + · intro h + exact (sortTree_perm w y).symm.trans (h ▸ sortTree_perm w x) + · intro h + apply flatten_inj w + exact List.Perm.eq_of_pairwise' (sortTree_sorted w x) (sortTree_sorted w y) + ((sortTree_perm w x).trans (h.symm.trans (sortTree_perm w y).symm)) + +/-- The order used by the sorter is immaterial for this permutation test. -/ +theorem tag_of_sort [LinearOrder (Val (row w a))] + (h : DNet F (tree w (row w a)) (tree w (row w a)) (sortTree w) m) : + ∃ v ≤ 2 * m + 3 * 2 ^ w * (w + wd a), Net F (inputs w a) .unit (tag F w a) v := by + obtain ⟨v, hv, g⟩ := ((label_net F w a).comp h).par h + refine ⟨v + wd (tree w (row w a)), ?_, ?_⟩ + · refine (Nat.add_le_add_right hv _).trans ?_ + rw [wd_tree, wd, wd_word] + exact le_of_eq (by ring) + · convert g.comp (cap _) using 1 + funext x y + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, + sort_eq_iff, tag, permuted] + +/-- Any bit bundle can be ordered by permuting its bits into a word. -/ +theorem exists_comparator (F : Type) [Field F] (a : Wire) : + ∃ o : LinearOrder (Val a), + DNet F (.pair a a) .bit (fun x => decide (@LT.lt _ o.toLT x.1 x.2)) (100 * (wd a + 1)) := by + obtain ⟨f, hf, hi⟩ := Rewire.exists_of_width (wd_word (wd a)).symm + refine ⟨LinearOrder.lift' f hi, ?_⟩ + exact (compare_lt F _).pre (hf.par hf) + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- # Testing distinctness at independent list and word lengths -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem nodup_net (F : Type) [Field F] (j n : ℕ) : + DNet F (tree j (word n)) .bit (fun x => decide (flatten j x).Nodup) + (400 * 2 ^ j * (j + 1) ^ 2 * (n + 1)) := by + have sort := sortTree_net (compare_exchange F n) j + have test := adjacent_net (compare_lt F n) j + have ok (x : Val (tree j (word n))) : + adjacent j (sortTree j x) = decide (flatten j x).Nodup := by + apply Bool.eq_iff_iff.mpr + rw [decide_eq_true_eq, adjacent_iff _ _ (sortTree_sorted j x), (sortTree_perm j x).nodup_iff] + have hn := sort.comp test + simp only [ok] at hn + apply hn.mono + rw [wd_word] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/SortOne.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/SortOne.lean new file mode 100644 index 0000000000..3842376ccf --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/SortOne.lean @@ -0,0 +1,100 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Permute + +/-! # Checking wider payloads against the same tags -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {a b : Wire} {w t m : ℕ} + +private theorem project_net {f : Val a → Val b} (h : DNet F a b f m) (w : ℕ) : + DNet F (inputs w a) (inputs w b) (project w f) (2 ^ w * (w + 2 * m)) := by + have htag := (DNet.id F (word w)).par h + refine ((mapRows_net h w).par (mapRows_net htag w)).mono ?_ + rw [wd_word] + exact le_of_eq (by ring) + +private theorem pad_net (F : Type) [Field F] (ha : wd b ≤ wd a) : + ∃ f, DNet F b a f (wd a) ∧ Function.Injective f := by + let p := word (wd a - wd b) + have hw : wd (.pair b p) = wd a := by simp [p, wd, ha] + obtain ⟨f, hf, hi⟩ := Rewire.exists_of_width hw + let z := (bits p).symm (fun _ => false) + have h := ((DNet.id F b).par (literal_net F p z)).pre (.unit' _) + refine ⟨fun x => f (x, z), (h.post hf).mono hw.le, ?_⟩ + exact fun _ _ he => congrArg Prod.fst (hi he) + +theorem tag_shrink (h : Batch (tag F w a) t m) (ha : wd b ≤ wd a) : + Batch (tag F w b) t (m + t * 2 ^ w * (w + 2 * wd a)) := by + obtain ⟨f, hf, hi⟩ := pad_net F ha + have k := h.pullback (project_net hf w) + simp only [tag_project F w f hi] at k + exact k.mono (le_of_eq (by ring)) + +private theorem tag_double (h : Batch (tag F w a) t m) : + Batch (tag F w (.pair a a)) t (2 * m + t * 2 ^ w * (3 * w + 12 * wd a)) := by + have k := (h.par_pred h).pullback + ((project_net (DNet.fst F a a) w).pair (project_net (DNet.snd F a a) w)) + simp only [← tag_pair] at k + refine k.mono ?_ + simp only [wd, wd_tree, row, wd_word] + exact le_of_eq (by ring) + +/-- The overhead for `2^k` slices is linear in the total number of rows, +including all copies. The same tag appears on each slice. -/ +theorem tag_slices (h : Batch (tag F w a) t m) (k : ℕ) (ha : wd b ≤ 2 ^ k * wd a) : + Batch (tag F w b) t (2 ^ k * m + (6 * k + 2) * 2 ^ k * t * 2 ^ w * (w + wd a)) := by + have aux (j : ℕ) : Batch (tag F w (tree j a)) t (2 ^ j * m + 6 * j * 2 ^ j * t * 2 ^ w * (w + + wd a)) := by + induction j with + | zero => simpa using h + | succ j ih => + apply (tag_double ih).mono + rw [wd_tree, pow_succ] + have hw := Nat.mul_le_mul_right (t * 2 ^ w * w) (Nat.one_le_pow j 2 (by decide)) + ring_nf at hw ⊢ + omega + refine (tag_shrink (aux k) (by simpa [wd_tree] using ha)).mono ?_ + rw [wd_tree] + have hw := Nat.mul_le_mul_right (t * 2 ^ w * w) (Nat.one_le_pow k 2 (by decide)) + ring_nf at hw ⊢ + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- # Sorting ordinary records with a tagged permutation verifier -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {F : Type} [Field F] {a : Wire} {w m k : ℕ} + +/-- A verifier for logarithmic-width payloads can sort records up to four +times as wide. The comparison cost is charged separately. -/ +theorem sort_one [LinearOrder (Val a)] + (h : Net F (inputs w (word w)) .unit (tag F w (word w)) m) (hw : wd a ≤ 4 * w) + (comp : DNet F (.pair a a) .bit (fun x => decide (x.1 < x.2)) k) : + DNet F (tree w a) (tree w a) (sortTree w) (4 * m + 10000 * 2 ^ w * (w + k + 1)) := by + have ha := tag_slices (b := a) (Batch.of_net h 1) 2 (by simpa using hw) + have hs := sort_of_tag ha comp + apply ((hs.pre (.unit' _)).post (.unit _)).mono + rw [wd_word] + have he := Nat.mul_le_mul_left (2 ^ w) hw + ring_nf at he ⊢ + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Tags.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Tags.lean new file mode 100644 index 0000000000..050e934944 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Tagged/Tags.lean @@ -0,0 +1,132 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Network + +/-! # Independent flags on a binary tree of records -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +variable {a b c : Wire} + +/-- In the case `0, x`, this construction gives `f x`. -/ +def mapRows (f : Val a → Val b) : (w : ℕ) → Val (tree w a) → Val (tree w b) + | 0, x => f x + | w + 1, x => (mapRows f w x.1, mapRows f w x.2) + +/-- In the case `0, x, y`, this construction gives `f x y`. -/ +def zipRows (f : Val a → Val b → Val c) : + (w : ℕ) → Val (tree w a) → Val (tree w b) → Val (tree w c) + | 0, x, y => f x y + | w + 1, x, y => (zipRows f w x.1 y.1, zipRows f w x.2 y.2) + +/-- A false flag retains a real record with weight minus one. +A true flag marks it as a dummy with weight one. -/ +def sign (F : Type) [Field F] : (w : ℕ) → Val (tree w .bit) → F + | 0, z => if z = true then 1 else -1 + | w + 1, z => sign F w z.1 * sign F w z.2 + +/-- The value specified by `(mapRows (E false) w B, zipRows E w z A)`. -/ +def tested (E : Val .bit → Val a → Val b) (w : ℕ) (A B : Val (tree w a)) + (z : Val (tree w .bit)) : Val (tree (w + 1) b) := + (mapRows (E false) w B, zipRows E w z A) + +/-- Returns `1` when `(flatten w B).Perm (flatten w A)` holds, and `0` otherwise. -/ +def permuted (F : Type) [Field F] (w : ℕ) (A B : Val (tree w a)) : F := + if (flatten w B).Perm (flatten w A) then 1 else 0 + +theorem length_flatten (w : ℕ) (x : Val (tree w a)) : (flatten w x).length = 2 ^ w := by + induction w with + | zero => rfl + | succ w ih => simp [flatten, ih, pow_succ, mul_two] + +theorem flatten_mapRows (f : Val a → Val b) (w : ℕ) (x : Val (tree w a)) : + flatten w (mapRows f w x) = (flatten w x).map f := by + induction w with + | zero => rfl + | succ w ih => simp only [flatten, mapRows, List.map_append, ih] + +theorem mem_zipRows (f : Val a → Val b → Val c) (w : ℕ) + (x : Val (tree w a)) (y : Val (tree w b)) {v : Val c} + (h : v ∈ flatten w (zipRows f w x y)) : + ∃ p ∈ flatten w x, ∃ q ∈ flatten w y, f p q = v := by + induction w with + | zero => exact ⟨x, by simp [flatten], y, by simp [flatten], (List.mem_singleton.mp h).symm⟩ + | succ w ih => + rcases List.mem_append.mp h with h | h + · obtain ⟨p, hp, q, hq, he⟩ := ih _ _ h + exact ⟨p, List.mem_append_left _ hp, q, List.mem_append_left _ hq, he⟩ + · obtain ⟨p, hp, q, hq, he⟩ := ih _ _ h + exact ⟨p, List.mem_append_right _ hp, q, List.mem_append_right _ hq, he⟩ + +theorem nodup_zipRows (f : Val a → Val b → Val c) + (hf : ∀ p q x y, f p x = f q y → x = y) (w : ℕ) + (x : Val (tree w a)) (y : Val (tree w b)) (hy : (flatten w y).Nodup) : + (flatten w (zipRows f w x y)).Nodup := by + induction w with + | zero => simp [flatten] + | succ w ih => + obtain ⟨h₁, h₂, h₃⟩ := List.nodup_append.mp hy + refine List.nodup_append.mpr ⟨ih _ _ h₁, ih _ _ h₂, ?_⟩ + intro u hu v hv he + obtain ⟨p, _, i, hi, rfl⟩ := mem_zipRows f _ _ _ hu + obtain ⟨q, _, j, hj, rfl⟩ := mem_zipRows f _ _ _ hv + exact h₃ _ hi _ hj (hf _ _ _ _ he) + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end + +section +/- # The tagged permutation tensor -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Tagged + +/-- Computes the row by the application `Wire.pair (word w) a`. -/ +abbrev row (w : ℕ) (a : Wire) := Wire.pair (word w) a + +/-- Untagged input rows and tagged proposed output rows. -/ +abbrev inputs (w : ℕ) (a : Wire) := Wire.pair (tree w a) (tree w (row w a)) + +/-- The binary addresses in order from zero to `2^w-1`. -/ +def indices : (w : ℕ) → Val (tree w (word w)) + | 0 => () + | w + 1 => + (mapRows (a := word w) (b := word (w + 1)) (fun i => (false, i)) w (indices w), + mapRows (a := word w) (b := word (w + 1)) (fun i => (true, i)) w (indices w)) + +theorem indices_nodup (w : ℕ) : (flatten w (indices w)).Nodup := by + induction w with + | zero => simp [flatten] + | succ w ih => + simp only [indices, flatten, flatten_mapRows, List.nodup_append] + refine ⟨ih.map (fun _ _ h => congrArg Prod.snd h), ih.map (fun _ _ h => congrArg Prod.snd h), + ?_⟩ + intro x hx y hy + obtain ⟨p, _, rfl⟩ := List.mem_map.mp hx + obtain ⟨q, _, rfl⟩ := List.mem_map.mp hy + exact fun h => Bool.false_ne_true (congrArg Prod.fst h) + +/-- The indexed operation `zipRows (c := row w a) (fun y i => (i, y)) w x (indices w)`. -/ +def label {a : Wire} (w : ℕ) (x : Val (tree w a)) : Val (tree w (row w a)) := + zipRows (c := row w a) (fun y i => (i, y)) w x (indices w) + +theorem label_nodup {a : Wire} (w : ℕ) (x : Val (tree w a)) : + (flatten w (label w x)).Nodup := + nodup_zipRows _ (fun _ _ _ _ h => congrArg Prod.fst h) _ _ _ (indices_nodup w) + +/-- Computes the tag by the application `permuted F w (label w x.1) x.2`. -/ +def tag (F : Type) [Field F] (w : ℕ) (a : Wire) + (x : Val (inputs w a)) (_ : Val .unit) : F := + permuted F w (label w x.1) x.2 + +end MatrixMultiplicationAllFields.MatrixExponent.Tagged +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Match/Reciprocal.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Match/Reciprocal.lean new file mode 100644 index 0000000000..2053c5216a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Match/Reciprocal.lean @@ -0,0 +1,897 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Match.Runs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Add +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix + +/-! # Sorting the two sides of a matching by source, then item or bin -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows + +variable {h k : ℕ} + +/-- The value specified by `(x.active ∘ f, x.thick ∘ f, x.src ∘ f, x.item ∘ f, x.dest ∘ f)`. -/ +def gather (x : Rows h k) (f : B h → B h) : Rows h k := + (x.active ∘ f, x.thick ∘ f, x.src ∘ f, x.item ∘ f, x.dest ∘ f) + +/-- Computes the row by the application `Format.lex (.lex .bit (.lex .bit (.addr k))) (.lex +(.addr k) (.addr h))`. -/ +abbrev row (h k : ℕ) := + Format.lex (.lex .bit (.lex .bit (.addr k))) (.lex (.addr k) (.addr h)) + +/-- The value specified by `toLex (toLex (x.active i, toLex (x.thick i, x.src i)), toLex (if +x.thick i then x.dest i else x.item i, i))`. -/ +def entry (x : Rows h k) (i : B h) : (row h k).obj := + toLex (toLex (x.active i, toLex (x.thick i, x.src i)), + toLex (if x.thick i then x.dest i else x.item i, i)) + +/-- Computes the perm by the application `Tuple.sort (entry x)`. -/ +def perm (x : Rows h k) : Equiv.Perm (B h) := Tuple.sort (entry x) + +theorem gather_sorted (x : Rows h k) : (x.gather x.perm).sorted := by + let z := x.gather x.perm + let key i := toLex (z.active i, toLex (z.thick i, z.src i)) + let val i := if z.thick i then z.dest i else z.item i + have order {i j} (hij : i ≤ j) : key i < key j ∨ (key i = key j ∧ val i ≤ val j) := by + have e := Tuple.monotone_sort (entry x) hij + rcases Prod.Lex.toLex_le_toLex.mp e with a | ⟨a, b⟩ + · exact .inl a + · exact .inr ⟨a, (Prod.Lex.toLex_le_toLex.mp b).elim LT.lt.le (fun hb => hb.1.le)⟩ + have between {i j p} (ij : i ≤ j) (jp : j ≤ p) + (ha : z.active i = z.active p) (hb : z.thick i = z.thick p) (hs : z.src i = z.src p) : + z.active j = z.active i ∧ z.thick j = z.thick i ∧ z.src j = z.src i ∧ + val i ≤ val j ∧ val j ≤ val p := by + have e : key i = key p := by unfold key; rw [ha, hb, hs] + have h₁ := order ij + have h₂ := order jp + have he : key j = key i := by grind + have h₃ : z.key j = z.key i := he + exact ⟨congrArg Prod.fst h₃, congrArg (fun t => t.2.1) h₃, + congrArg (fun t => t.2.2) h₃, by grind, by grind⟩ + change z.sorted + constructor + · intro i j p ij jp hi hp hs + obtain ⟨ha, hb, he, _⟩ := between ij jp (hi.1.trans hp.1.symm) (hi.2.trans hp.2.symm) hs + exact ⟨⟨ha.trans hi.1, hb.trans hi.2⟩, he⟩ + · intro i j p ij jp hi hp hs ht + obtain ⟨_, hb, _, lo, up⟩ := between ij jp (hi.1.trans hp.1.symm) (hi.2.trans hp.2.symm) hs + simp only [val, hb, hi.2, hp.2, ← ht] at lo up + exact le_antisymm up lo + · intro i j p ij jp hi hp hs ht + obtain ⟨_, hb, _, lo, up⟩ := between ij jp (hi.1.trans hp.1.symm) (hi.2.trans hp.2.symm) hs + simp only [val, hb, hi.2, hp.2, ← ht] at lo up + exact le_antisymm up lo + +private theorem prepared (F : Type) [Field F] (h k : ℕ) : + Circuit F (RowFmt h k) (.vec h (row h k)) entry + ((RowFmt h k).width + 134 * (Format.vec h (row h k)).width) := by + classical + let enc := (Format.vec h (row h k)).code ∘ entry ∘ (RowFmt h k).code.symm + have t : Install.Depends enc 3 := by + rintro ⟨i, (j | j | j) | (j | j)⟩ + · refine ⟨{.inl (i, j)}, by simp, fun x y e => ?_⟩ + exact e (.inl (i, j)) (by simp) + · refine ⟨{.inr (.inl (i, j))}, by simp, fun x y e => ?_⟩ + exact e (.inr (.inl (i, j))) (by simp) + · refine ⟨{.inr (.inr (.inl (i, j)))}, by simp, fun x y e => ?_⟩ + change (Format.addr k).code ((Format.addr k).code.symm _) _ = + (Format.addr k).code ((Format.addr k).code.symm _) _ + rw [Equiv.apply_symm_apply, Equiv.apply_symm_apply] + exact e (.inr (.inr (.inl (i, j)))) (by simp) + · let flag : (RowFmt h k).pins := .inr (.inl (i, ())) + let data (b : Bool) (l : (Format.addr k).pins) : (RowFmt h k).pins := + .inr (.inr (.inr (if b then .inr (i, l) else .inl (i, l)))) + have value (x : (RowFmt h k).pins → Bool) : + enc x (i, .inr (.inl j)) = x (data (x flag) j) := by + change (Format.addr k).code (if x flag then (Format.addr k).code.symm (x ∘ data true) + else (Format.addr k).code.symm (x ∘ data false)) j = _ + cases x flag <;> simp + refine ⟨{flag, data false j, data true j}, Finset.card_le_three, fun x y e => ?_⟩ + rw [value, value, e flag (by simp)] + cases y flag <;> exact e _ (by simp) + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + exact t.bnet F + +theorem cheap_perm (F : Type) [Field F] (h k : ℕ) : + Cheap F h (h + k + 1) (RowFmt h k) (Perm h) (fun x => ⇑(perm x)) 5 := by + have flag := Coloring.small (F := F) (A := .pair .bit .bit) (by simp) (fun x => decide (x.1 + < x.2)) + have cmp := lex_lt (lex_lt flag (lex_lt flag (numeric_lt F k))) (lex_lt (numeric_lt F k) + (numeric_lt F h)) + have out := Circuit.project (F := F) (A := .vec h (row h k)) (D := Perm h) + (f := fun x i => (x i).2.2) (fun z => (z.1, .inr (.inr z.2))) (fun _ _ => rfl) + have hs := cmp.sort h + have net := ((prepared F h k).comp hs).comp out + refine ⟨_, net, ?_⟩ + simp only [Format.width_pair, Format.width_lex, Format.width_addr, Format.width_vec] + rw [Format.width_bit] + ring_nf + omega + +theorem cheap_gather (F : Type) [Field F] (h k : ℕ) : + Cheap F h (h + k + 1) (.pair (RowFmt h k) (Perm h)) (RowFmt h k) + (fun x => gather x.1 x.2) 20 := by + let A := Format.pair (RowFmt h k) (Perm h) + have hw : A.width ≤ 2 ^ h * (100 + (h + k + 1)) ^ 2 := by + simp only [A, Format.width_pair, Format.width_vec, Format.width_addr] + rw [Format.width_bit] + ring_nf + omega + have x := Cheap.id F hw + have bit := Cheap.lookup F h (h + k + 1) .bit (by omega) (by simp) + have addr := Cheap.lookup F h (h + k + 1) (.addr k) (by omega) (by simp; omega) + have a := (x.fst.fst.pair x.snd).comp bit + have b := (x.fst.snd.fst.pair x.snd).comp bit + have c := (x.fst.snd.snd.fst.pair x.snd).comp addr + have d := (x.fst.snd.snd.snd.fst.pair x.snd).comp addr + have e := (x.fst.snd.snd.snd.snd.pair x.snd).comp addr + exact (a.pair (b.pair (c.pair (d.pair e)))).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +end + +section +/- # Circuits computing one rank per row with no factor for alphabet size -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable (F : Type) [Field F] {h k t : ℕ} + +/-- Computes the column by the application `Format.vec h (.addr k)`. -/ +abbrev Column (h k : ℕ) := Format.vec h (.addr k) + +theorem column_width (h : ℕ) (hk : k ≤ t) : (Column h k).width ≤ 2 ^ h * (100 + t) ^ 1 := by + simp only [Column, Format.width_vec, Format.width_addr, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + +theorem cheap_eq (hk : k ≤ t) : + Cheap F 0 t (.pair (.addr k) (.addr k)) .bit (fun z => decide (z.1 = z.2)) 2 := by + refine ⟨_, numeric_eq F k, ?_⟩ + simp only [Format.width_pair, Format.width_addr] + rw [Format.width_bit] + ring_nf + omega + +private theorem cheap_back (hh : h ≤ t) (hk : k ≤ t) : + Cheap F h t (Column h k) (Perm h) back 10 := by + let A := Format.pair (.addr k) (.addr k) + let D := Format.pair (.addr h) (.addr h) + have ha : A.width ≤ 2 ^ 0 * (100 + t) ^ 2 := by simp [A]; ring_nf; omega + have hd : D.width ≤ 2 ^ 0 * (100 + t) ^ 2 := by simp [D]; ring_nf; omega + have pick (i : B h) : Cheap F 0 t A (.addr h) + (fun z => if z.1 = z.2 then previous i else i) 6 := by + have H := ((Cheap.const F ha hd (previous i, i)).pair (cheap_eq F hk)).comp ((cheap_select F + h).widen hh) + convert H.mono (d := 6) (by decide) using 1 + funext z + simp + have hw := column_width h hk + have prev : Cheap F h t (Column h k) (Column h k) (fun f => f ∘ previous) 2 := + Cheap.project F hw hw (fun i => (previous i.1, i.2)) (fun _ _ => rfl) + exact (((prev.pair (Cheap.id F hw)).zip.comp (Cheap.map _ pick)).mono (by decide)) + +theorem cheap_leader (hh : h ≤ t) (hk : k ≤ t) : + Cheap F h t (Column h k) (Perm h) leader 15 := by + have a := Cheap.id F (column_width h hh) + have square := (a.pair a).comp (Cheap.lookup F h t (.addr h) hh (by simpa)) + exact ((cheap_back F hh hk).comp (square.iterate hh)).mono (by decide) + +private theorem cheap_offset (hh : h ≤ t) : + Cheap F h t (Perm h) (Perm h) (fun a i => i - a i) 15 := by + have width := column_width h hh + have base := Cheap.id F width + have get := Cheap.lookup F h t (.addr h) hh (by simpa) + have neg := ((Cheap.const F width width (fun i => -i)).pair base).comp get + have inp := ((Cheap.const F width width id).pair neg).zip + have add : Cheap F 0 t (.pair (.addr h) (.addr h)) (.addr h) (fun x => x.1 + x.2) 4 := by + refine ⟨_, numeric_add F h, ?_⟩ + simp only [Format.width_pair, Format.width_addr] + ring_nf + omega + convert (inp.comp (Cheap.map (fun _ => _) (fun _ => add))).mono (d := 15) (by decide) using 1 + funext a i + exact sub_eq_add_neg _ _ + +theorem cheap_order (h k : ℕ) : + Cheap F h (h + k) (Column h k) (Perm h) (fun f => ⇑(order f)) 41 := by + have ha := column_width h (Nat.le_add_left k h) + have hb : (Format.vec h .bit).width ≤ 2 ^ h * (100 + (h + k)) ^ 1 := by + rw [Format.width_vec, Format.width_bit, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have H := ((Cheap.id F ha).pair (Cheap.const F ha hb (fun _ + => true))).comp (cheap_permutation F h k) + exact H.mono (by decide) + +theorem cheap_sorted_leader (h k : ℕ) : Cheap F h (h + k) (Column h k) (Perm h) + (fun f => leader (f ∘ order f)) 44 := by + have hh := Nat.le_add_right h k + have hk := Nat.le_add_left k h + have sorted := ((Cheap.id F (column_width h hk)).pair (cheap_order F h k)).comp + (Cheap.lookup F h (h + k) (.addr k) hh (by simp)) + exact (sorted.comp (cheap_leader F hh hk)).mono (by decide) + +theorem cheap_inverse_order (h k : ℕ) : + Cheap F h (h + k) (Column h k) (Perm h) (fun f => ⇑(order f).symm) 101 := by + obtain ⟨g, hg, he⟩ := cheap_inverse F h + have H := (cheap_order F h k).comp (hg.widen (Nat.le_add_right h k)) + have eq : g ∘ (fun f : B h → B k => ⇑(order f)) = fun f => ⇑(order f).symm := funext fun f => he _ + rwa [eq] at H + +theorem cheap_groupRank (h k : ℕ) : + Cheap F h (h + k) (Column h k) (Perm h) groupRank 103 := by + have hh := Nat.le_add_right h k + have a := (cheap_sorted_leader F h k).comp (cheap_offset F hh) + have H := (a.pair (cheap_inverse_order F h k)).comp (Cheap.lookup F h (h + + k) (.addr h) hh (by simp)) + exact H.mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- # First, last and other occurrences of a key -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring +variable {h k : ℕ} (f : B h → B k) + +/-- The value specified by `order f ∘ leader (f ∘ order f) ∘ (order f).symm`. -/ +def groupFirst := order f ∘ leader (f ∘ order f) ∘ (order f).symm + +/-- The value specified by `Fin.rev ∘ groupFirst (f ∘ Fin.rev) ∘ Fin.rev`. -/ +def groupLast := Fin.rev ∘ groupFirst (f ∘ Fin.rev) ∘ Fin.rev + +/-- Returns `groupLast f i` when `groupFirst f i = i` holds, and `groupFirst f i` otherwise. -/ +def other (i : B h) := if groupFirst f i = i then groupLast f i else groupFirst f i + +theorem first_spec (i : B h) : + f (groupFirst f i) = f i ∧ ∀ j, f j = f i → groupFirst f i ≤ j := by + let e := order f + obtain ⟨he, hl⟩ := leader_spec (f ∘ e) (order_mono f) (e.symm i) + have ht : f (groupFirst f i) = f i := he.trans (congrArg f (e.apply_symm_apply i)) + refine ⟨ht, fun j hj => ?_⟩ + have hle := hl (e.symm j) (by simpa using hj) + have h := order_le f hle + change f (groupFirst f i) < f (e (e.symm j)) ∨ + f (groupFirst f i) = f (e (e.symm j)) ∧ groupFirst f i ≤ e (e.symm j) at h + rw [Equiv.apply_symm_apply, ht, hj] at h + exact (h.resolve_left (lt_irrefl _)).2 + +theorem last_spec (i : B h) : + f (groupLast f i) = f i ∧ ∀ j, f j = f i → j ≤ groupLast f i := by + obtain ⟨he, hl⟩ := first_spec (f ∘ Fin.rev) i.rev + refine ⟨by simpa [groupLast] using he, fun j hj => ?_⟩ + simpa [groupLast] using Fin.rev_le_rev.mpr (hl j.rev (by simpa using hj)) + +theorem other_spec (i : B h) : + f (other f i) = f i ∧ ∀ j, f j = f i → j ≠ i → other f i ≠ i := by + obtain ⟨he, hl⟩ := first_spec f i + obtain ⟨he', hr⟩ := last_spec f i + unfold other + split_ifs with h + · exact ⟨he', fun j hj hn h' => hn (le_antisymm ((hr j hj).trans_eq h') + (h.symm.trans_le (hl j hj)))⟩ + · exact ⟨he, fun _ _ _ => h⟩ + +/-- The value specified by `groupRank f ∘ groupLast f`. -/ +def lastRank := groupRank f ∘ groupLast f + +theorem lastRank_val (i : B h) : (lastRank f i).val + 1 = Control.histogram f (f i) none := by + obtain ⟨he, hr⟩ := last_spec f i + rw [lastRank, Function.comp_apply, groupRank_val, Control.rank, Control.histogram_some, he, + Control.histogram_none] + let S := Finset.univ.filter fun j => f j = f i + have hi : groupLast f i ∈ S := Finset.mem_filter.mpr ⟨Finset.mem_univ _, he⟩ + change _ = S.card + rw [← Finset.card_erase_add_one hi] + congr 2 + ext j + simp only [S, Finset.mem_filter, Finset.mem_univ, true_and, Finset.mem_erase] + exact ⟨fun h => ⟨h.2.ne, h.1⟩, fun h => ⟨h.2, (hr j h.2).lt_of_ne h.1⟩⟩ + +variable (F : Type) [Field F] + +theorem cheap_first (h k : ℕ) : + Cheap F h (h + k) (Column h k) (Perm h) groupFirst 103 := by + have get := Cheap.lookup F h (h + k) (.addr h) (by omega) (by simp) + have a := ((cheap_order F h k).pair (cheap_sorted_leader F h k)).comp get + exact ((a.pair (cheap_inverse_order F h k)).comp get).mono (by decide) + +theorem cheap_last (h k : ℕ) : + Cheap F h (h + k) (Column h k) (Perm h) groupLast 110 := by + have hw := column_width h (Nat.le_add_left k h) + have hi := column_width h (Nat.le_add_right h k) + have get := Cheap.lookup F h (h + k) (.addr h) (by omega) (by simp) + have rev : Cheap F h (h + k) (Column h k) (Column h k) (fun f => f ∘ Fin.rev) 2 := + Cheap.project F hw hw (fun i => (i.1.rev, i.2)) (fun _ _ => rfl) + have a := rev.comp (cheap_first F h k) + have r := Cheap.const F hw hi Fin.rev + have b := (a.pair r).comp get + exact ((r.pair b).comp get).mono (by decide) + +theorem cheap_other (h k : ℕ) : + Cheap F h (h + k) (Column h k) (Perm h) other 120 := by + have hh := Nat.le_add_right h k + have i := Cheap.const F (column_width h (Nat.le_add_left k h)) (column_width h hh) id + have a := cheap_first F h k + have b := cheap_last F h k + have eq := (a.pair i).zip.comp (Cheap.map (fun _ => _) (fun _ => cheap_eq F hh)) + have H := (((b.pair a).zip.pair eq).zip.comp (Cheap.map (fun _ => _) (fun _ + => (cheap_select F h).widen hh))) + convert H.mono (d := 120) (by decide) using 1 + funext x i + simp [other] + +theorem cheap_lastRank (h k : ℕ) : + Cheap F h (h + k) (Column h k) (Perm h) lastRank 112 := + (((cheap_groupRank F h k).pair (cheap_last F h k)).comp + (Cheap.lookup F h (h + k) (.addr h) (by omega) (by simp))).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +/- # Treating a tuple of fixed-width fields as one comparison key -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +variable {h k : ℕ} (A : Format) + +/-- Reindexes `slots (word A.width)` and `A.pins` by an equivalence. -/ +def layout : slots (word A.width) ≃ A.pins := + @Fintype.equivOfCardEq _ _ (slotsFintype _) A.finite + ((card_slots _).trans (wd_word _)) + +/-- Reindexes `A.obj` and `B A.width` by an equivalence. -/ +def Format.serial : A.obj ≃ B A.width := + (A.code.trans ((layout A).symm.arrowCongr (Equiv.refl _))).trans (Format.addr _).code.symm + +/-- The value specified by `A.serial ∘ f`. -/ +def Format.keys (f : B h → A.obj) := A.serial ∘ f + +theorem cheap_keys (F : Type) [Field F] (h : ℕ) (ha : A.width ≤ k) : + Cheap F h k (.vec h A) (Column h A.width) A.keys 2 := by + have b : (Format.vec h A).width ≤ 2 ^ h * (100 + k) ^ 1 := by + rw [Format.width_vec, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + apply Cheap.project F b (column_width h ha) (fun i => (i.1, layout A i.2)) + intro f i + change (Format.addr A.width).code (A.serial (f i.1)) i.2 = _ + rw [Format.serial, Equiv.trans_apply, Equiv.apply_symm_apply] + rfl + +theorem keys_rank [DecidableEq A.obj] (f : B h → A.obj) (i : B h) : + (groupRank (A.keys f) i).val = Control.rank f i := by + rw [groupRank_val, Control.rank, Control.rank, Control.histogram_some, Control.histogram_some] + congr 1 + ext j + simp [Format.keys] + +theorem keys_last [DecidableEq A.obj] (f : B h → A.obj) (i : B h) : + (lastRank (A.keys f) i).val + 1 = (Finset.univ.filter fun j => f j = f i).card := by + rw [lastRank_val, Control.histogram_none] + congr 1 + ext j + simp [Format.keys] + +/-- Comparing the counts in two fibers tests whether all rows in the +first fiber agree on their additional field. -/ +theorem same_group {D : Format} + (f : B h → A.obj) (g : B h → D.obj) (i : B h) : + lastRank (A.keys f) i = lastRank ((A.pair D).keys (fun j => (f j, g j))) i ↔ + ∀ j, f j = f i → g j = g i := by + classical + classical + have hl := keys_last A f i + have hr := keys_last (A.pair D) (fun j => (f j, g j)) i + let s := Finset.univ.filter fun j => f j = f i + let t := Finset.univ.filter fun j => (f j, g j) = (f i, g i) + have sub : t ⊆ s := fun j h => Finset.mem_filter.mpr + ⟨Finset.mem_univ _, congrArg Prod.fst (Finset.mem_filter.mp h).2⟩ + constructor + · intro h j he + rw [h] at hl + have eq : t = s := Finset.eq_of_subset_of_card_le sub (hl.symm.trans hr).le + have hm : j ∈ t := eq.symm ▸ Finset.mem_filter.mpr ⟨Finset.mem_univ _, he⟩ + exact congrArg Prod.snd (Finset.mem_filter.mp hm).2 + · intro h + have eq : s = t := Finset.Subset.antisymm (fun j he => by + obtain ⟨_, he⟩ := Finset.mem_filter.mp he + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, Prod.ext he (h j he)⟩) sub + exact Fin.ext (Nat.succ_inj.mp (hl.trans ((congrArg Finset.card eq).trans hr.symm))) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +/- +# Matching rows at equal rank + +The first key distinguishes the two colors. The second key erases the +color and adds its within-color rank. Every active fiber of that key +contains at most one row of each color. Comparing two group counts +then tests that a thin item lies entirely in one thick bin. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows + +variable {h k : ℕ} (x : Rows h k) + +/-- Computes the color key by the application `Format.pair .bit (.pair .bit (.addr k))`. -/ +abbrev ColorKey (k : ℕ) := Format.pair .bit (.pair .bit (.addr k)) +/-- Computes the rank key by the application `Format.pair .bit (.pair (.addr k) (.addr h))`. -/ +abbrev RankKey (h k : ℕ) := Format.pair .bit (.pair (.addr k) (.addr h)) +/-- The value specified by `(ColorKey k).pair (.addr k)`. -/ +abbrev ItemKey (k : ℕ) := (ColorKey k).pair (.addr k) +/-- Computes the bin key by the application `Format.pair .bit (.addr k)`. -/ +abbrev BinKey (k : ℕ) := Format.pair .bit (.addr k) + +/-- Computes the ordinal by the application `groupRank ((ColorKey k).keys x.key)`. -/ +def ordinal := groupRank ((ColorKey k).keys x.key) + +/-- The value specified by `(x.active i, x.src i, x.ordinal i)`. -/ +def rankKey (i : B h) : (RankKey h k).obj := (x.active i, x.src i, x.ordinal i) + +/-- Computes the friend by the application `other ((RankKey h k).keys x.rankKey)`. -/ +def friend := other ((RankKey h k).keys x.rankKey) + +theorem friend_spec : x.friends x.friend := by + intro i hi + let f := (RankKey h k).keys x.rankKey + let a := x.friend i + have ord j : (x.ordinal j).val = Control.rank x.key j := keys_rank (ColorKey k) x.key j + have eqn (j : B h) : f j = f i ↔ x.active j = true ∧ x.src j = x.src i ∧ + Control.rank x.key j = Control.rank x.key i := by + simp only [f, Format.keys, Function.comp_apply, Equiv.apply_eq_iff_eq, rankKey, + Prod.mk.injEq, hi.1, Fin.ext_iff, ord] + have ho := other_spec f i + obtain ⟨active, src, rank⟩ := (eqn a).mp ho.1 + have thick (ha : a ≠ i) : x.isThick a := by + refine ⟨active, ?_⟩ + cases h : x.thick a + · apply False.elim + apply ha + apply Control.rank_injective x.key + exact Prod.ext (Prod.ext (active.trans hi.1.symm) (Prod.ext (h.trans hi.2.symm) src)) rank + · rfl + refine ⟨?_, fun h => ⟨thick h, src, rank⟩⟩ + intro j hj hs hr + have ne : j ≠ i := by intro eq; subst j; simp [isThin, isThick] at hi hj; grind + have ha := thick (ho.2 j ((eqn _).mpr ⟨hj.1, hs, hr⟩) ne) + apply Control.rank_injective x.key + exact Prod.ext (Prod.ext (ha.1.trans hj.1.symm) (Prod.ext (ha.2.trans hj.2.symm) (src.trans + hs.symm))) + (rank.trans hr.symm) + +/-- The value specified by `(x.key i, x.item i)`. -/ +def itemKey (i : B h) : (ItemKey k).obj := (x.key i, x.item i) + +/-- The value specified by `(decide (x.friend i = i), x.dest (x.friend i))`. -/ +def binKey (i : B h) : (BinKey k).obj := (decide (x.friend i = i), x.dest (x.friend i)) + +/-- The indexed operation `decide (lastRank ((ItemKey k).keys x.itemKey) i = lastRank (((ItemKey +k).pair (BinKey k)).keys (fun j => (x.itemKey j, x.binKey j))) i)`. -/ +def sameBin (i : B h) := + decide (lastRank ((ItemKey k).keys x.itemKey) i = + lastRank (((ItemKey k).pair (BinKey k)).keys (fun j => (x.itemKey j, x.binKey j))) i) + +/-- The value specified by `x.active i && !x.thick i && !(x.binKey i).1 && x.sameBin i`. -/ +def mask (i : B h) := x.active i && !x.thick i && !(x.binKey i).1 && x.sameBin i + +theorem mask_iff (i : B h) : x.mask i = true ↔ x.passes x.friend i := by + have he : x.sameBin i = true ↔ ∀ j, x.itemKey j = x.itemKey i → x.binKey j = x.binKey i := by + rw [sameBin, decide_eq_true_eq, same_group] + simp only [mask, Bool.and_eq_true, Bool.not_eq_true', he, itemKey, key, binKey, + decide_eq_false_iff_not, Prod.mk.injEq, passes, isThin] + grind + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +end + +section +/- +# Bounded-fan-in costs for ordered matching + +Use two rank comparisons per row. The costs depend polynomially on +the address and label widths and linearly on the padded array length. +They do not depend on the number of distinct keys or the item size. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +variable (F : Type) [Field F] (h k : ℕ) + +/-- The quantity computed by `2 * h + 4 * k + 4`. -/ +def overhead (h k : ℕ) := 2 * h + 4 * k + 4 + +private theorem widths : + h + (ColorKey k).width ≤ overhead h k ∧ + h + (RankKey h k).width ≤ overhead h k ∧ + h + (ItemKey k).width ≤ overhead h k ∧ + h + ((ItemKey k).pair (BinKey k)).width ≤ overhead h k := by + simp only [ColorKey, RankKey, ItemKey, BinKey, Format.width_pair, Format.width_addr, overhead] + rw [Format.width_bit] + omega + +theorem row_width : (RowFmt h k).width ≤ 2 ^ h * (100 + overhead h k) ^ 1 := by + simp only [RowFmt, Format.width_pair, Format.width_vec, Format.width_addr, ← mul_add, pow_one] + rw [Format.width_bit] + exact Nat.mul_le_mul_left _ (by unfold overhead; omega) + +private theorem cheap_color : + Cheap F h (overhead h k) (RowFmt h k) (.vec h (ColorKey k)) key 10 := by + have x := Cheap.id F (row_width h k) + exact ((x.fst.pair (x.snd.fst.pair x.snd.snd.fst).zip).zip).mono (by decide) + +theorem cheap_friend : Cheap F h (overhead h k) (RowFmt h k) (Perm h) friend 122 := by + have hc := (widths h k).1 + have hr := (widths h k).2.1 + have x := Cheap.id F (row_width h k) + have key := (cheap_color F h k).comp (cheap_keys (ColorKey k) F h (by omega)) + have rank := key.comp ((cheap_groupRank F h _).widen hc) + have row := (x.fst.pair (x.snd.snd.fst.pair rank).zip).zip + have keys := row.comp (cheap_keys (RankKey h k) F h (by omega)) + exact (keys.comp ((cheap_other F h _).widen hr)).mono (by decide) + +private theorem cheap_missed : + Cheap F h (overhead h k) (RowFmt h k) (.vec h .bit) (fun x i => decide (friend x i = i)) 125 + := by + have hh : h ≤ overhead h k := by unfold overhead; omega + have idx := Cheap.const F (row_width h k) (column_width h hh) id + have eq := Cheap.map (h := h) (fun _ => _) (fun _ => cheap_eq F hh) + exact (((cheap_friend F h k).pair idx).zip.comp eq).mono (by decide) + +private theorem cheap_item : + Cheap F h (overhead h k) (RowFmt h k) (.vec h (ItemKey k)) itemKey 12 := by + have x := Cheap.id F (row_width h k) + exact ((cheap_color F h k).pair x.snd.snd.snd.fst).zip.mono (by decide) + +private theorem cheap_bin : + Cheap F h (overhead h k) (RowFmt h k) (.vec h (BinKey k)) binKey 127 := by + have hh : h ≤ overhead h k := by unfold overhead; omega + have hk : k ≤ overhead h k := by unfold overhead; omega + have x := Cheap.id F (row_width h k) + have addr := (x.snd.snd.snd.snd.pair (cheap_friend F h k)).comp + (Cheap.lookup F h (overhead h k) (.addr k) hh (by simpa)) + exact ((cheap_missed F h k).pair addr).zip.mono (by decide) + +private theorem cheap_sameBin : + Cheap F h (overhead h k) (RowFmt h k) (.vec h .bit) sameBin 135 := by + have hh : h ≤ overhead h k := by unfold overhead; omega + have count (A : Format) (hw : h + A.width ≤ overhead h k) := + (cheap_keys A F h (by omega)).comp ((cheap_lastRank F h _).widen hw) + have first := cheap_item F h k + have both := (first.pair (cheap_bin F h k)).zip + have a := first.comp (count _ (widths h k).2.2.1) + have b := both.comp (count _ (widths h k).2.2.2) + have eq := Cheap.map (h := h) (fun _ => _) (fun _ => cheap_eq F hh) + exact ((a.pair b).zip.comp eq).mono (by decide) + +private theorem cheap_bool (f : Bool × Bool → Bool) : + Cheap F 0 (overhead h k) (.pair .bit .bit) .bit f 2 := by + refine ⟨_, Coloring.small (A := .pair .bit .bit) (by simp) f, ?_⟩ + change 2 + 1 + 200 ≤ _ + ring_nf + omega + +theorem cheap_mask : Cheap F h (overhead h k) (RowFmt h k) (.vec h .bit) mask 140 := by + have x := Cheap.id F (row_width h k) + have notAnd := Cheap.map (h := h) (fun _ => _) (fun _ => cheap_bool F h k (fun z => z.1 && !z.2)) + have andNet := Cheap.map (h := h) (fun _ => _) (fun _ => cheap_bool F h k (fun z => z.1 && z.2)) + have thin := (x.fst.pair x.snd.fst).zip.comp notAnd + have matched := (thin.pair (cheap_missed F h k)).zip.comp notAnd + exact ((matched.pair (cheap_sameBin F h k)).zip.comp andNet).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +end + +/- # Returning the matching mask and mate addresses in the original order -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +variable {h k : ℕ} + +/-- The control of type `(B h → Bool) × (B h → B h)`, constructed using `x.gather x.perm`. -/ +def control (x : Rows h k) : (B h → Bool) × (B h → B h) := + let y := x.gather x.perm + (y.mask ∘ x.perm.symm, x.perm ∘ y.friend ∘ x.perm.symm) + +theorem cheap_control (F : Type) [Field F] (h k : ℕ) : + Cheap F h (overhead h k) (RowFmt h k) (.pair (.vec h .bit) (Perm h)) control 150 := by + have hh : h ≤ overhead h k := by unfold overhead; omega + have hk : h + k + 1 ≤ overhead h k := by unfold overhead; omega + have forward := (cheap_perm F h k).widen hk + have backward : Cheap F h (overhead h k) (RowFmt h k) (Perm h) + (fun x => ⇑(perm x).symm) 101 := by + obtain ⟨g, hg, he⟩ := cheap_inverse F h + have H := forward.comp (hg.widen hh) + have eq : g ∘ (fun x : Rows h k => ⇑(perm x)) = fun x => ⇑(perm x).symm := funext fun x => he _ + rwa [eq] at H + have sorted := ((Cheap.id F (row_width h k)).pair forward).comp ((cheap_gather F h k).widen hk) + have bit := Cheap.lookup F h (overhead h k) .bit hh (by rw [Format.width_bit]; omega) + have addr := Cheap.lookup F h (overhead h k) (.addr h) hh (by simpa) + have keep := ((sorted.comp (cheap_mask F h k)).pair backward).comp bit + have mate := ((sorted.comp (cheap_friend F h k)).pair backward).comp addr + exact (keep.pair ((forward.pair mate).comp addr)).mono (by decide) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +end + +/- +# The matching decoded from the row circuit + +The selected mask is constant on each thin item. On this mask the friend +pointer gives a distinct thick mate, with common destination for the item. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +open Packing Finset + +variable {E P : Type} {r h k : ℕ} {src dst : E → P} {ix : E → Cell r} + (x : P → Rows h k) (pos : E → B h) {tag : P → B k} + +open scoped Classical in +/-- Both the mask and the mate address are specified, for every unit. -/ +private structure SortedControls (m : Matching src dst ix) : Prop where + mask : ∀ e, (m.plan (src e) (ix e)).isSome = (x (src e)).mask (pos e) + mate : ∀ e, pos (m.mate e) = (x (src e.val)).friend (pos e.val) + +open scoped Classical in +private theorem decode {c : Color r} (enc : ∀ p, (x p).Represents src dst ix c p pos (tag p)) : + ∃ m : Matching src dst ix, m.color = c ∧ SortedControls x pos m := by + let take e := (x (src e)).passes (x (src e)).friend (pos e) + have pick (e : E) : ∃ d : E, take e → src d = src e ∧ + pos d = (x (src e)).friend (pos e) ∧ Packing.thick c (ix d) := by + by_cases he : take e + · have ht := ((x (src e)).friend_spec _ he.1).2 he.2.1 + obtain ⟨d, hd, hp⟩ := (enc _).onto _ ht.1.1 (ht.2.1.trans ((enc _).source e rfl)) + exact ⟨d, fun _ => ⟨hd, hp, ((enc _).isThick d hd).mp (hp.symm ▸ ht.1)⟩⟩ + · exact ⟨e, fun h => (he h).elim⟩ + choose mate hm using pick + have same (e d : E) (he : take e) (hs : src d = src e) (hi : ix d = ix e) : + take d ∧ dst (mate d) = dst (mate e) := by + let z := enc (src e) + have ht := (z.isThin d hs).mpr (hi.symm ▸ (z.isThin e rfl).mp he.1) + have hsrc := (z.source d hs).trans (z.source e rfl).symm + have hit := (z.item d e hs rfl).mpr hi + obtain ⟨hne, hdst⟩ := he.2.2 (pos d) ht hsrc hit + have hd : take d := by + unfold take + rw [hs] + refine ⟨ht, hne, fun j hj h₁ h₂ => ?_⟩ + obtain ⟨hn, h⟩ := he.2.2 j hj (h₁.trans hsrc) (h₂.trans hit) + exact ⟨hn, h.trans hdst.symm⟩ + refine ⟨hd, (z.dest _ _ ((hm d hd).1.trans hs) (hm e he).1).mp ?_⟩ + rw [(hm d hd).2.1, (hm e he).2.1, hs] + exact hdst + let plan p t := + if h : ∃ e, src e = p ∧ ix e = t ∧ take e then some (dst (mate h.choose)) else none + have used p t (h : (plan p t).isSome) : ∃ e, src e = p ∧ ix e = t ∧ take e := by + by_contra hn + simp only [plan, dite_eq_right hn, Option.isSome_none, Bool.false_eq_true] at h + have spec (e : E) (he : take e) : plan (src e) (ix e) = some (dst (mate e)) := by + have h : ∃ d, src d = src e ∧ ix d = ix e ∧ take d := ⟨e, rfl, rfl, he⟩ + unfold plan + rw [dite_eq_left h, (same e _ he h.choose_spec.1 h.choose_spec.2.1).2] + have selected (e : E) : (plan (src e) (ix e)).isSome ↔ take e := by + constructor + · intro h + obtain ⟨d, hs, hi, hd⟩ := used _ _ h + exact (same d e hd hs.symm hi.symm).1 + · intro he + simp [spec e he] + let f : {e // (plan (src e) (ix e)).isSome} ↪ E := ⟨fun e => mate e.val, by + rintro ⟨e, he⟩ ⟨d, hd⟩ eq + have te := (selected e).mp he + have td := (selected d).mp hd + have hs := (hm d td).1.symm.trans ((congrArg src eq.symm).trans (hm e te).1) + have hp := (hm e te).2.1.symm.trans ((congrArg pos eq).trans (hm d td).2.1) + unfold take at td + rw [hs] at hp td + exact Subtype.ext ((enc _).inj e d rfl hs ((x _).friend_injective (x _).friend_spec te td hp))⟩ + let m : Matching src dst ix := { + color := c + plan := plan + thin p t h := by + obtain ⟨e, _, rfl, he⟩ := used p t h + exact ((enc _).isThin e rfl).mp he.1 + used p t h := by + obtain ⟨e, hs, hi, _⟩ := used p t h + exact ⟨e, hs, hi⟩ + mate := f + spec e := by + have he := (selected e.val).mp e.property + exact ⟨(hm _ he).2.2, (hm _ he).1, spec _ he⟩ } + refine ⟨m, rfl, ?_, fun e => (hm _ ((selected _).mp e.property)).2.1⟩ + intro e + exact Bool.eq_iff_iff.mpr ((selected e).trans ((x _).mask_iff _).symm) + +open scoped Classical in +private theorem decoded_count [Fintype E] [Fintype P] {c : Color r} + (enc : ∀ p, (x p).Represents src dst ix c p pos (tag p)) (sorted : ∀ p, (x p).sorted) + (b K : ℕ) (size : ∀ p t, (univ.filter fun e => src e = p ∧ ix e = t).card ≤ b) + (deg : ∀ p, ((univ.filter fun e => src e = p).image dst).card ≤ K) + {m : Matching src dst ix} (hm : SortedControls x pos m) : + (∑ p, min (univ.filter fun e => src e = p ∧ ¬Packing.thick c (ix e)).card + (univ.filter fun e => src e = p ∧ Packing.thick c (ix e)).card) ≤ + m.count + b * K * Fintype.card P := by + let selected := univ.filter fun e => (m.plan (src e) (ix e)).isSome + have ht (p : P) : + (univ.filter fun e => src e = p ∧ (x p).passes (x p).friend (pos e)) = + selected.filter fun e => src e = p := by + ext e + simp only [selected, mem_filter, mem_univ, true_and, hm.mask, mask_iff] + by_cases hp : src e = p <;> simp [hp] + have h := sum_le_sum (s := univ) fun p _ => + (enc p).local_count (sorted p) (x p).friend_spec b K (size p) (deg p) + simp_rw [ht] at h + rw [sum_add_distrib, ← card_eq_sum_card_fiberwise (fun e _ => mem_univ (src e)), + sum_const, card_univ, Nat.nsmul_eq_mul, mul_comm (Fintype.card P)] at h + exact h + +open scoped Classical in +private theorem gather_enc {c : Color r} (enc : ∀ p, (x p).Represents src dst ix c p pos (tag p)) + (p : P) : ((x p).gather (x p).perm).Represents src dst ix c p + (fun e => (x (src e)).perm.symm (pos e)) (tag p) := by + let z := enc p + constructor + · intro e f he hf eq + rw [he, hf] at eq + exact z.inj e f he hf ((x p).perm.symm.injective eq) + · intro e he + simpa only [gather, active, he, Function.comp_apply, Equiv.apply_symm_apply] using z.active e he + · intro i hi ht + obtain ⟨e, he, hp⟩ := z.onto _ hi ht + exact ⟨e, he, by rw [he, hp, Equiv.symm_apply_apply]⟩ + · intro e he + simpa only [gather, Rows.src, he, Function.comp_apply, Equiv.apply_symm_apply] + using z.source e he + · intro e he + simpa only [gather, Rows.thick, he, Function.comp_apply, Equiv.apply_symm_apply] + using z.thick e he + · intro e f he hf + simpa only [gather, dest, he, hf, Function.comp_apply, Equiv.apply_symm_apply] + using z.dest e f he hf + · intro e f he hf + simpa only [gather, item, he, hf, Function.comp_apply, Equiv.apply_symm_apply] + using z.item e f he hf + +open scoped Classical in +/-- The controls in original row order determine the entire matching. -/ +structure Controls (m : Matching src dst ix) : Prop where + mask : ∀ e, (m.plan (src e) (ix e)).isSome = (x (src e)).control.1 (pos e) + mate : ∀ e, pos (m.mate e) = (x (src e.val)).control.2 (pos e.val) + +open scoped Classical in +theorem controlled_matching [Fintype E] [Fintype P] {c : Color r} + (enc : ∀ p, (x p).Represents src dst ix c p pos (tag p)) + (b K : ℕ) (size : ∀ p t, (univ.filter fun e => src e = p ∧ ix e = t).card ≤ b) + (deg : ∀ p, ((univ.filter fun e => src e = p).image dst).card ≤ K) : + ∃ m : Matching src dst ix, m.color = c ∧ Controls x pos m ∧ + (∑ p, min (univ.filter fun e => src e = p ∧ ¬Packing.thick c (ix e)).card + (univ.filter fun e => src e = p ∧ Packing.thick c (ix e)).card) ≤ + m.count + b * K * Fintype.card P := by + let row p := (x p).gather (x p).perm + let loc e := (x (src e)).perm.symm (pos e) + have rep := gather_enc x pos enc + obtain ⟨m, hc, hm⟩ := decode row loc rep + refine ⟨m, hc, ⟨hm.mask, ?_⟩, decoded_count row loc rep (fun p => (x p).gather_sorted) + b K size deg hm⟩ + intro e + have he := hm.mate e + unfold loc at he + rw [(m.spec e).2.1] at he + exact (x _).perm.symm_apply_eq.mp he + +open scoped Classical in +/-- Different colonies may share an array, with one source tag per colony. +Array positions and tags may depend on the affine coloring. -/ +theorem controlled_subround [Fintype E] [Fintype P] (src dst : E → P) (ix : E → Cell r) + (rows : Color r → P → Rows h k) (loc : Color r → E → B h) (key : Color r → P → B k) + (enc : ∀ c p, (rows c p).Represents src dst ix c p (loc c) (key c p)) + (u L : ℝ) (K : ℕ) (hu : 0 < u) (hL : 0 ≤ L) + (hs : ∀ p t, u * (univ.filter fun e => src e = p ∧ ix e = t).card ≤ L) + (hd : ∀ p, ((univ.filter fun e => src e = p).image dst).card ≤ K) : + ∃ m : Matching src dst ix, Controls (rows m.color) (loc m.color) m ∧ + u * Fintype.card E * (3 / 8) ≤ u * m.count + L * (K + 1) * Fintype.card P := by + apply subround_of_matching src dst ix u L K hu hL hs + intro c b hb + obtain ⟨m, hm, hc, hn⟩ := controlled_matching (rows c) (loc c) (enc c) b K hb hd + exact ⟨m, by rw [hm]; exact hc, hn⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +end + +section +/- +# Reading a matching in either direction + +The friend address is an involution even for an unused row. Looking +up the mask at that address therefore identifies all used thick units. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows + +variable {h k : ℕ} (x : Rows h k) + +private theorem equal_of_rankKey {i j : B h} + (eq : x.rankKey i = x.rankKey j) (he : x.thick i = x.thick j) : i = j := by + obtain ⟨ha, hs⟩ := Prod.mk.inj eq + obtain ⟨hs, hr⟩ := Prod.mk.inj hs + have ord i : (x.ordinal i).val = Control.rank x.key i := keys_rank (ColorKey k) x.key i + exact Control.rank_injective x.key (Prod.ext (Prod.ext ha (Prod.ext he hs)) + ((ord i).symm.trans ((congrArg Fin.val hr).trans (ord j)))) + +private theorem friend_key (i : B h) : x.rankKey (x.friend i) = x.rankKey i := + (RankKey h k).serial.injective (other_spec ((RankKey h k).keys x.rankKey) i).1 + +private theorem friend_involutive : Function.Involutive x.friend := by + intro i + by_cases he : x.friend i = i + · rw [he, he] + let j := x.friend i + have h₁ := x.friend_key i + have h₂ := x.friend_key j + have hn : x.friend j ≠ j := + (other_spec ((RankKey h k).keys x.rankKey) j).2 i + (congrArg (RankKey h k).serial h₁.symm) (Ne.symm he) + apply x.equal_of_rankKey (h₂.trans h₁) + have hi : x.thick j ≠ x.thick i := mt (x.equal_of_rankKey h₁) he + have hj : x.thick (x.friend j) ≠ x.thick j := mt (x.equal_of_rankKey h₂) hn + cases ha : x.thick j <;> simp [ha] at hi hj <;> exact hj.trans hi.symm + +theorem control_involutive : Function.Involutive x.control.2 := by + intro i + simp only [control, Function.comp_apply, Equiv.symm_apply_apply, + friend_involutive (x.gather x.perm) _, Equiv.apply_symm_apply] + +theorem control_source (i : B h) : + x.active (x.control.2 i) = x.active i ∧ x.src (x.control.2 i) = x.src i := by + let y := x.gather x.perm + obtain ⟨ha, hs⟩ := Prod.mk.inj (y.friend_key (x.perm.symm i)) + have h := And.intro ha (Prod.mk.inj hs).1 + simpa only [control, y, gather, active, src, Function.comp_apply, Equiv.apply_symm_apply] using h + +variable {E P : Type} {r : ℕ} {src dst : E → P} {ix : E → Packing.Cell r} + {rows : P → Rows h k} {pos : E → B h} {m : Packing.Matching src dst ix} + (ctl : Controls rows pos m) + +include ctl + +theorem Controls.back (i : {e // (m.plan (src e) (ix e)).isSome}) : + (rows (src i.val)).control.2 (pos (m.mate i)) = pos i.val := by + rw [ctl.mate] + exact (rows _).control_involutive _ + +theorem Controls.used_iff {tag : P → B k} + (enc : ∀ p, (rows p).Represents src dst ix m.color p pos (tag p)) (e : E) : + (rows (src e)).control.1 ((rows (src e)).control.2 (pos e)) = true ↔ + ∃ i, m.mate i = e := by + let x := rows (src e) + constructor + · intro h + obtain ⟨ha, hs⟩ := x.control_source (pos e) + obtain ⟨t, ht, hi⟩ := (enc _).onto _ (ha.trans ((enc _).active e rfl)) (hs.trans ((enc + _).source e rfl)) + have hp : (m.plan (src t) (ix t)).isSome := by rw [ctl.mask, ht, hi]; exact h + refine ⟨⟨t, hp⟩, (enc _).inj _ _ ((m.spec ⟨t, hp⟩).2.1.trans ht) rfl ?_⟩ + rw [ctl.mate] + change (rows (src t)).control.2 (pos t) = _ + rw [ht, hi] + exact x.control_involutive _ + · rintro ⟨i, rfl⟩ + rw [(m.spec i).2.1, ctl.back, ← ctl.mask] + exact i.property + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Match/Runs.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Match/Runs.lean new file mode 100644 index 0000000000..adde57e43b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Match/Runs.lean @@ -0,0 +1,561 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Control.BucketNet +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Suffix +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Budget +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort + +/-! # Matching by source and occurrence rank -/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring +open Finset + +open scoped Classical in +/-- Computes the row fmt by the application `Format.pair (.vec h .bit) (.pair (.vec h .bit) +(.pair (.vec h (.addr k)) (.pair (.vec h (.addr k)) (.vec h (.addr k)))))`. -/ +abbrev RowFmt (h k : ℕ) := Format.pair (.vec h .bit) (.pair (.vec h .bit) + (.pair (.vec h (.addr k)) (.pair (.vec h (.addr k)) (.vec h (.addr k))))) + +open scoped Classical in +/-- Indexes the rows by the coordinates of `(B h → Bool) × (B h → Bool) × (B h → B k) × (B h → B +k) × (B h → B k)`. -/ +abbrev Rows (h k : ℕ) := + (B h → Bool) × (B h → Bool) × (B h → B k) × (B h → B k) × (B h → B k) + +namespace Rows +variable {h k : ℕ} (x : Rows h k) + +open scoped Classical in +/-- Uses `x.1` as the representation. -/ +abbrev active := x.1 +open scoped Classical in +/-- Uses `x.2.1` as the representation. -/ +abbrev thick := x.2.1 +open scoped Classical in +/-- Uses `x.2.2.1` as the representation. -/ +abbrev src := x.2.2.1 +open scoped Classical in +/-- Uses `x.2.2.2.1` as the representation. -/ +abbrev item := x.2.2.2.1 +open scoped Classical in +/-- Uses `x.2.2.2.2` as the representation. -/ +abbrev dest := x.2.2.2.2 + +open scoped Classical in +/-- Requires `x.active i = true ∧ x.thick i = false`. -/ +def isThin (i : B h) : Prop := x.active i = true ∧ x.thick i = false +open scoped Classical in +/-- Requires `x.active i = true ∧ x.thick i = true`. -/ +def isThick (i : B h) : Prop := x.active i = true ∧ x.thick i = true + +open scoped Classical in +/-- The value specified by `(x.active i, x.thick i, x.src i)`. -/ +def key (i : B h) := (x.active i, x.thick i, x.src i) + +open scoped Classical in +/-- Only contiguity of the relevant runs matters, not the order of the runs. -/ +structure sorted : Prop where + source : ∀ i j k, i ≤ j → j ≤ k → + x.isThin i → x.isThin k → x.src i = x.src k → x.isThin j ∧ x.src j = x.src i + item : ∀ i j k, i ≤ j → j ≤ k → + x.isThin i → x.isThin k → x.src i = x.src k → x.item i = x.item k → x.item j = x.item i + bin : ∀ i j k, i ≤ j → j ≤ k → + x.isThick i → x.isThick k → x.src i = x.src k → x.dest i = x.dest k → x.dest j = x.dest i + +open scoped Classical in +/-- The friends of type `Prop` for the given inputs. -/ +def friends (friend : B h → B h) : Prop := + ∀ i, x.isThin i → + (∀ j, x.isThick j → x.src j = x.src i → Control.rank x.key j = Control.rank x.key i → + friend i = j) ∧ + (friend i ≠ i → x.isThick (friend i) ∧ x.src (friend i) = x.src i ∧ + Control.rank x.key (friend i) = Control.rank x.key i) + +open scoped Classical in +/-- The defining condition `x.isThin i ∧ friend i ≠ i ∧ ∀ j, x.isThin j → x.src j = x.src i → +x.item j = x.item i → friend j ≠ j ∧ x.dest (friend j) = x.dest (friend i)`. -/ +def passes (friend : B h → B h) (i : B h) : Prop := + x.isThin i ∧ friend i ≠ i ∧ + ∀ j, x.isThin j → x.src j = x.src i → x.item j = x.item i → + friend j ≠ j ∧ x.dest (friend j) = x.dest (friend i) + +variable {friend : B h → B h} + +open scoped Classical in +theorem eligible_iff (hf : x.friends friend) {i : B h} (hi : x.isThin i) : + friend i ≠ i ↔ Control.rank x.key i < Control.histogram x.key (true, true, x.src i) none := by + rw [← Control.rank_range] + constructor + · intro he + obtain ⟨ht, hs, hr⟩ := (hf i hi).2 he + exact ⟨friend i, Prod.ext ht.1 (Prod.ext ht.2 hs), hr⟩ + · rintro ⟨j, he, hr⟩ + obtain ⟨ha, ht, hs⟩ := by simpa only [key, Prod.mk.injEq] using he + rw [(hf i hi).1 j ⟨ha, ht⟩ hs hr] + intro e + rw [e, hi.2] at ht + cases ht + +open scoped Classical in +theorem friend_injective (hf : x.friends friend) : Set.InjOn friend {i | x.passes friend i} := by + intro i hi j hj he + obtain ⟨_, si, ri⟩ := (hf i hi.1).2 hi.2.1 + obtain ⟨_, sj, rj⟩ := (hf j hj.1).2 hj.2.1 + rw [he] at si ri + apply Control.rank_injective x.key + exact Prod.ext (Prod.ext (hi.1.1.trans hj.1.1.symm) + (Prod.ext (hi.1.2.trans hj.1.2.symm) (si.symm.trans sj))) (ri.symm.trans rj) + +open scoped Classical in +/-- The condition `∀ s t, (univ.filter fun i => x.isThin i ∧ x.src i = s ∧ x.item i = t).card ≤ +b` on the specified data. -/ +def small (b : ℕ) : Prop := + ∀ s t, (univ.filter fun i => x.isThin i ∧ x.src i = s ∧ x.item i = t).card ≤ b + +open scoped Classical in +/-- A fixed window suffices to check all occurrences of the thin item. -/ +theorem item_span (hs : x.sorted) {b : ℕ} (hb : x.small b) {i j : B h} + (hi : x.isThin i) (hj : x.isThin j) (he : x.src i = x.src j) (ht : x.item i = x.item j) : + j.val < i.val + b := by + by_cases hle : i ≤ j + · have bound : (Icc i j).card ≤ b := by + refine le_trans (card_le_card ?_) (hb (x.src i) (x.item i)) + intro p hp + obtain ⟨h₁, h₂⟩ := mem_Icc.mp hp + obtain ⟨htp, hep⟩ := hs.source _ _ _ h₁ h₂ hi hj he + exact mem_filter.mpr ⟨mem_univ _, htp, hep, hs.item _ _ _ h₁ h₂ hi hj he ht⟩ + rw [Fin.card_Icc] at bound + omega + · exact (Nat.lt_of_not_ge hle).trans_le (Nat.le_add_right _ _) + +end Rows +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +section +/- # Counting eligible rows by source -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +open Finset Control + +variable {h k : ℕ} (x : Rows h k) {friend : B h → B h} + +open scoped Classical in +/-- Within each source the eligible thin rows are in bijection with +the ranks attained by both thin and thick rows. -/ +theorem eligible_count (hf : x.friends friend) (s : B k) : + min (univ.filter (fun i => x.isThin i ∧ x.src i = s)).card + (univ.filter (fun i => x.isThick i ∧ x.src i = s)).card = + (univ.filter (fun i => (x.isThin i ∧ friend i ≠ i) ∧ x.src i = s)).card := by + let S := univ.filter fun i => (x.isThin i ∧ friend i ≠ i) ∧ x.src i = s + let n (t : Bool) := histogram x.key (true, t, s) none + have hm (i : B h) : i ∈ S ↔ x.key i = (true, false, s) ∧ rank x.key i < n true := by + simp only [S, mem_filter, mem_univ, true_and] + constructor + · rintro ⟨⟨hi, he⟩, hs⟩ + exact ⟨Prod.ext hi.1 (Prod.ext hi.2 hs), by simpa [n, hs] using (x.eligible_iff hf hi).mp he⟩ + · rintro ⟨hk, hr⟩ + obtain ⟨ha, ht, hs⟩ := by simpa only [key, Prod.mk.injEq] using hk + exact ⟨⟨⟨ha, ht⟩, (x.eligible_iff hf ⟨ha, ht⟩).mpr (by simpa [hs, n] using hr)⟩, hs⟩ + have hi : Set.InjOn (rank x.key) ↑S := by + intro i hi j hj e + exact rank_injective x.key (Prod.ext (((hm i).mp hi).1.trans ((hm j).mp hj).1.symm) e) + have he : S.image (rank x.key) = range (min (n false) (n true)) := by + ext r + simp only [mem_image, hm, mem_range, lt_min_iff] + constructor + · rintro ⟨i, ⟨hk, hb⟩, rfl⟩ + exact ⟨(rank_range _ _ _).mp ⟨i, hk, rfl⟩, hb⟩ + · rintro ⟨ha, hb⟩ + obtain ⟨i, hk, rfl⟩ := (rank_range _ _ _).mpr ha + exact ⟨i, ⟨hk, hb⟩, rfl⟩ + change _ = S.card + rw [← card_image_of_injOn hi, he, card_range] + simp only [n, histogram_none, key, Prod.mk.injEq, isThin, isThick, and_assoc] + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +end + +section +/- # A local array encoding the outgoing units of a single source tag -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +open Packing + +variable {E P : Type} {r h k : ℕ} + +/-- Tags need only distinguish items and destinations within the colony. +Other source tags may use the same array. -/ +structure Represents (x : Rows h k) (src dst : E → P) (ix : E → Cell r) + (c : Color r) (p : P) (pos : E → B h) (tag : B k) : Prop where + inj : ∀ e f, src e = p → src f = p → pos e = pos f → e = f + active : ∀ e, src e = p → x.active (pos e) = true + onto : ∀ i, x.active i = true → x.src i = tag → ∃ e, src e = p ∧ pos e = i + source : ∀ e, src e = p → x.src (pos e) = tag + thick : ∀ e, src e = p → (x.thick (pos e) = true ↔ Packing.thick c (ix e)) + dest : ∀ e f, src e = p → src f = p → (x.dest (pos e) = x.dest (pos f) ↔ dst e = dst f) + item : ∀ e f, src e = p → src f = p → (x.item (pos e) = x.item (pos f) ↔ ix e = ix f) + +namespace Represents +variable {x : Rows h k} {src dst : E → P} {ix : E → Cell r} {c : Color r} + {p : P} {pos : E → B h} {tag : B k} (z : x.Represents src dst ix c p pos tag) + +include z + +theorem isThin (e : E) (he : src e = p) : x.isThin (pos e) ↔ ¬Packing.thick c (ix e) := by + simp only [Rows.isThin, z.active e he, true_and, ← z.thick e he] + cases x.thick (pos e) <;> decide + +theorem isThick (e : E) (he : src e = p) : x.isThick (pos e) ↔ Packing.thick c (ix e) := by + simp only [Rows.isThick, z.active e he, true_and, z.thick e he] + +end Represents +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +end + +/- # Whole-item matching by an ordered list of friends -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +open Finset + +variable {h k : ℕ} (x : Rows h k) {friend : B h → B h} + +open scoped Classical in +/-- Within each thin source run, the eligible positions form a prefix, +and their friends occur in order in the thick source run. -/ +private theorem earlier (hf : x.friends friend) {i j : B h} (hij : i ≤ j) + (hi : x.isThin i) (hj : x.isThin j) (he : x.src i = x.src j) (hne : friend j ≠ j) : + friend i ≠ i ∧ friend i ≤ friend j := by + rcases hij.eq_or_lt with rfl | hlt + · exact ⟨hne, le_rfl⟩ + have hk : x.key i = x.key j := Prod.ext (hi.1.trans hj.1.symm) (Prod.ext (hi.2.trans hj.2.symm) + he) + have hr := Control.rank_mono x.key hk hlt + have hni : friend i ≠ i := by + rw [x.eligible_iff hf hi, he] + exact hr.trans ((x.eligible_iff hf hj).mp hne) + refine ⟨hni, le_of_not_gt ?_⟩ + intro hji + obtain ⟨ti, si, ri⟩ := (hf i hi).2 hni + obtain ⟨tj, sj, rj⟩ := (hf j hj).2 hne + have hfkey : x.key (friend i) = x.key (friend j) := + Prod.ext (ti.1.trans tj.1.symm) (Prod.ext (ti.2.trans tj.2.symm) (si.trans (he.trans sj.symm))) + exact (Control.rank_mono x.key hfkey.symm hji).not_ge (ri.trans_le (hr.le.trans_eq rj.symm)) + +open scoped Classical in +private abbrev Thin (s : B k) := {i // x.isThin i ∧ x.src i = s} + +variable {s : B k} + +open scoped Classical in +private def block (i : x.Thin s) := (x.src i.val, x.item i.val) + +open scoped Classical in +private def bucket (friend : B h → B h) (i : x.Thin s) := + if friend i.val ≠ i.val then some (x.src i.val, x.dest (friend i.val)) else none + +open scoped Classical in +private theorem bucket_some (i : x.Thin s) : (x.bucket friend i).isSome ↔ friend i.val ≠ i.val := by + by_cases he : friend i.val = i.val <;> simp [bucket, he] + +open scoped Classical in +private theorem bucket_interval (hs : x.sorted) (hf : x.friends friend) + (i j k : x.Thin s) (hij : i ≤ j) (hjk : j ≤ k) + (he : x.bucket friend i = x.bucket friend k) (hi : (x.bucket friend i).isSome) : + x.bucket friend j = x.bucket friend i := by + have ni := (x.bucket_some i).mp hi + have nk := (x.bucket_some k).mp (he ▸ hi) + simp only [bucket, ite_eq_left ni, ite_eq_left nk, Option.some.injEq, Prod.mk.injEq] at he + have sj := (hs.source _ _ _ hij hjk i.property.1 k.property.1 he.1).2 + obtain ⟨nj, fjk⟩ := x.earlier hf hjk j.property.1 k.property.1 (sj.trans he.1) nk + have fij := (x.earlier hf hij i.property.1 j.property.1 sj.symm nj).2 + obtain ⟨ti, si, _⟩ := (hf _ i.property.1).2 ni + obtain ⟨tk, sk, _⟩ := (hf _ k.property.1).2 nk + have d := hs.bin _ _ _ fij fjk ti tk (si.trans (he.1.trans sk.symm)) he.2 + simp only [bucket, ite_eq_left ni, ite_eq_left nj, sj, d] + +open scoped Classical in +private theorem pass_of_plan (i : x.Thin s) (hp : (Packing.plan x.block (x.bucket friend) + i).isSome) : + x.passes friend i.val := by + unfold Packing.plan at hp + split_ifs at hp with hg + · have hi := (x.bucket_some i).mp hp + refine ⟨i.property.1, hi, ?_⟩ + intro j hj hs ht + have e := hg ⟨j, hj, hs.trans i.property.2⟩ (Prod.ext hs ht) + have hn := (x.bucket_some ⟨j, hj, hs.trans i.property.2⟩).mp (e.symm ▸ hp) + simp only [bucket, ite_eq_left hi, ite_eq_left hn, Option.some.injEq, Prod.mk.injEq] at e + exact ⟨hn, e.2⟩ + · cases hp + +open scoped Classical in +theorem matching_count (hs : x.sorted) (hf : x.friends friend) (s : B k) {b : ℕ} + (hb : ∀ t, (univ.filter fun i => x.isThin i ∧ x.src i = s ∧ x.item i = t).card ≤ b) : + min (univ.filter fun i => x.isThin i ∧ x.src i = s).card + (univ.filter fun i => x.isThick i ∧ x.src i = s).card ≤ + (univ.filter fun i => x.passes friend i ∧ x.src i = s).card + + b * ((univ.filter fun i => x.isThick i ∧ x.src i = s).image + fun i => (x.src i, x.dest i)).card := by + let bins := (univ.filter fun i => x.isThick i ∧ x.src i = s).image fun i => (x.src i, x.dest i) + let eligible := univ.filter fun i : x.Thin s => (x.bucket friend i).isSome + have block_interval (i j k : x.Thin s) (hij : i ≤ j) (hjk : j ≤ k) + (he : x.block i = x.block k) : x.block j = x.block i := + Prod.ext (hs.source _ _ _ hij hjk i.property.1 k.property.1 (congrArg Prod.fst he)).2 + (hs.item _ _ _ hij hjk i.property.1 k.property.1 (congrArg Prod.fst he) (congrArg Prod.snd + he)) + have pre (i j : x.Thin s) (hij : i ≤ j) (he : x.block i = x.block j) + (hj : (x.bucket friend j).isSome) : (x.bucket friend i).isSome := + (x.bucket_some i).mpr (x.earlier hf hij i.property.1 j.property.1 + (congrArg Prod.fst he) ((x.bucket_some j).mp hj)).1 + have size (p : B k × B k) : (univ.filter fun i : x.Thin s => x.block i = p).card ≤ b := by + apply le_trans _ (hb p.2) + apply card_le_card_of_injOn Subtype.val _ Subtype.val_injective.injOn + intro i hi + have he := (mem_filter.mp hi).2 + exact mem_filter.mpr ⟨mem_univ _, i.property.1, i.property.2, congrArg Prod.snd he⟩ + have H := Packing.straddles x.block (x.bucket friend) block_interval (x.bucket_interval hs hf) + pre b size + have elig : eligible.card = (univ.filter fun i => (x.isThin i ∧ friend i ≠ i) ∧ x.src i = s).card + := by + apply card_bij (fun i _ => i.val) + · intro i hi + exact mem_filter.mpr ⟨mem_univ _, ⟨i.property.1, (x.bucket_some i).mp (mem_filter.mp hi).2⟩, + i.property.2⟩ + · exact fun _ _ _ _ he => Subtype.ext he + · intro i hi + obtain ⟨_, ⟨ht, hn⟩, hh⟩ := mem_filter.mp hi + exact ⟨⟨i, ht, hh⟩, mem_filter.mpr ⟨mem_univ _, (x.bucket_some _).mpr hn⟩, rfl⟩ + have passed : (univ.filter fun i : x.Thin s => (Packing.plan x.block (x.bucket friend) + i).isSome).card ≤ + (univ.filter fun i => x.passes friend i ∧ x.src i = s).card := by + apply card_le_card_of_injOn Subtype.val _ Subtype.val_injective.injOn + exact fun i hi => mem_filter.mpr ⟨mem_univ _, x.pass_of_plan i (mem_filter.mp hi).2, + i.property.2⟩ + have used : (eligible.image (x.bucket friend)).card ≤ bins.card := by + apply le_trans _ (card_image_le (s := bins) (f := some)) + apply card_le_card + intro p hp + obtain ⟨i, hi, rfl⟩ := mem_image.mp hp + have hn := (x.bucket_some i).mp (mem_filter.mp hi).2 + obtain ⟨ht, he, _⟩ := (hf _ i.property.1).2 hn + rw [bucket, ite_eq_left hn, ← he] + exact mem_image_of_mem _ (mem_image_of_mem _ (mem_filter.mpr ⟨mem_univ _, ht, + he.trans i.property.2⟩)) + rw [x.eligible_count hf s, ← elig] + exact H.trans (Nat.add_le_add passed (Nat.mul_le_mul_left b used)) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows +end + +section +/- # Transferring the array matching bound to one source colony -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows.Represents +open Finset Packing + +variable {E P : Type} [Fintype E] {r h k : ℕ} {src dst : E → P} + {ix : E → Cell r} {c : Color r} {p : P} {pos : E → B h} {x : Rows h k} + {tag : B k} (z : x.Represents src dst ix c p pos tag) + +include z + +open scoped Classical in +private theorem count (q : B h → Prop) (t : E → Prop) [DecidablePred q] [DecidablePred t] + (active : ∀ i, q i → x.active i = true ∧ x.src i = tag) + (spec : ∀ e, src e = p → (q (pos e) ↔ t e)) : + (univ.filter q).card = (univ.filter fun e => src e = p ∧ t e).card := by + symm + apply card_bij (fun e _ => pos e) + · intro e he + obtain ⟨_, hs, ht⟩ := mem_filter.mp he + exact mem_filter.mpr ⟨mem_univ _, (spec e hs).mpr ht⟩ + · exact fun e he f hf eq => z.inj _ _ (mem_filter.mp he).2.1 (mem_filter.mp hf).2.1 eq + · intro i hi + obtain ⟨e, he, rfl⟩ := z.onto _ (active _ (mem_filter.mp hi).2).1 + (active _ (mem_filter.mp hi).2).2 + exact ⟨e, mem_filter.mpr ⟨mem_univ _, he, (spec e he).mp (mem_filter.mp hi).2⟩, rfl⟩ + +open scoped Classical in +theorem small (b : ℕ) + (hsize : ∀ t, (univ.filter fun e => src e = p ∧ ix e = t).card ≤ b) : + ∀ t, (univ.filter fun i => x.isThin i ∧ x.src i = tag ∧ x.item i = t).card ≤ b := by + intro t + let q := fun i => x.isThin i ∧ x.src i = tag ∧ x.item i = t + change (univ.filter q).card ≤ b + rw [z.count q (q ∘ pos) (fun _ hi => ⟨hi.1.1, hi.2.1⟩) (fun _ _ => Iff.rfl)] + by_cases he : ∃ e, src e = p ∧ q (pos e) + · obtain ⟨e, he, hq⟩ := he + refine le_trans (card_le_card ?_) (hsize (ix e)) + intro f hf + obtain ⟨_, hf, hq'⟩ := mem_filter.mp hf + exact mem_filter.mpr ⟨mem_univ _, hf, (z.item _ _ hf he).mp (hq'.2.2.trans hq.2.2.symm)⟩ + · simp only [not_exists] at he + simp [he] + +open scoped Classical in +private theorem bins : + ((univ.filter fun i => x.isThick i ∧ x.src i = tag).image fun i => (x.src i, x.dest i)).card ≤ + ((univ.filter fun e => src e = p).image dst).card := by + let A := (univ.filter fun i => x.isThick i ∧ x.src i = tag).image fun i => (x.src i, x.dest i) + let D := (univ.filter fun e => src e = p).image dst + have repr (a : A) : ∃ e, src e = p ∧ (tag, x.dest (pos e)) = a.val := by + obtain ⟨i, hi, heq⟩ := mem_image.mp a.property + obtain ⟨e, he, rfl⟩ := z.onto _ (mem_filter.mp hi).2.1.1 (mem_filter.mp hi).2.2 + exact ⟨e, he, by simpa only [z.source e he] using heq⟩ + choose e he hval using repr + let f (a : A) : D := ⟨dst (e a), mem_image_of_mem dst (mem_filter.mpr ⟨mem_univ _, he a⟩)⟩ + have hinj : Function.Injective f := by + intro a b eq + apply Subtype.ext + rw [← hval a, ← hval b, (z.dest _ _ (he a) (he b)).mpr (congrArg Subtype.val eq)] + simpa only [Fintype.card_coe] using Fintype.card_le_of_injective f hinj + +open scoped Classical in +theorem local_count {fr : B h → B h} (hs : x.sorted) (hf : x.friends fr) (b K : ℕ) + (hsize : ∀ t, (univ.filter fun e => src e = p ∧ ix e = t).card ≤ b) + (hd : ((univ.filter fun e => src e = p).image dst).card ≤ K) : + min (univ.filter fun e => src e = p ∧ ¬Packing.thick c (ix e)).card + (univ.filter fun e => src e = p ∧ Packing.thick c (ix e)).card ≤ + (univ.filter fun e => src e = p ∧ x.passes fr (pos e)).card + b * K := by + have H := x.matching_count hs hf tag (z.small b hsize) + have thin := z.count (fun i => x.isThin i ∧ x.src i = tag) (fun e => ¬Packing.thick c (ix e)) + (fun _ hi => ⟨hi.1.1, hi.2⟩) (fun e he => by simp only [z.source e he, and_true, z.isThin e he]) + have thick := z.count (fun i => x.isThick i ∧ x.src i = tag) (fun e => Packing.thick c (ix e)) + (fun _ hi => ⟨hi.1.1, hi.2⟩) (fun e he => by + simp only [z.source e he, and_true, z.isThick e he]) + have passed := z.count (fun i => x.passes fr i ∧ x.src i = tag) (fun e => x.passes fr (pos e)) + (fun _ hi => ⟨hi.1.1.1, hi.2⟩) (fun e he => by simp [z.source e he]) + rw [thin, thick, passed] at H + exact H.trans (Nat.add_le_add_left (Nat.mul_le_mul_left _ (z.bins.trans hd)) _) + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring.Rows.Represents +end + +section +/- +# Occurrence ranks by stable sorting and pointer doubling + +In sorted order, each position points to its predecessor with the same +key, or to itself at a boundary. After doubling `h` times all pointers +give the start of their run. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring +open Finset + +variable {h k : ℕ} + +/-- The quantity computed by `⟨i.val - 1, by have := i.isLt; omega⟩`. -/ +def previous (i : B h) : B h := ⟨i.val - 1, by have := i.isLt; omega⟩ + +/-- Returns `previous i` when `f (previous i) = f i` holds, and `i` otherwise. -/ +def back (f : B h → B k) (i : B h) := if f (previous i) = f i then previous i else i + +/-- The indexing data represented by `(fun g : B h → B h => g ∘ g)^[h] (back f)`. -/ +def leader (f : B h → B k) : B h → B h := (fun g : B h → B h => g ∘ g)^[h] (back f) + +theorem leader_eq (f : B h → B k) : leader f = (back f)^[2 ^ h] := by + have go (n : ℕ) : (fun g : B h → B h => g ∘ g)^[n] (back f) = (back f)^[2 ^ n] := by + induction n with + | zero => simp + | succ n ih => rw [Function.iterate_succ_apply', ih, pow_succ, mul_two, Function.iterate_add] + exact go h + +theorem leader_spec (f : B h → B k) (hf : Monotone f) (i : B h) : + f (leader f i) = f i ∧ ∀ j, f j = f i → leader f i ≤ j := by + let s := univ.filter fun j => f j = f i + have hn : s.Nonempty := ⟨i, by simp [s]⟩ + let l := s.min' hn + have he : f l = f i := (mem_filter.mp (min'_mem _ hn)).2 + have hl (j : B h) (hj : f j = f i) : l ≤ j := min'_le _ _ (by simpa [s]) + have range (j : B h) (lo : l ≤ j) (hi : j ≤ i) : f j = f i := + le_antisymm (hf hi) (he ▸ hf lo) + have hb (j : B h) (lo : l ≤ j) (hi : j ≤ i) : + (back f j).val = max l.val (j.val - 1) := by + unfold back + split_ifs with hj + · have h := hl (previous j) (hj.trans (range j lo hi)) + exact (max_eq_right (show l.val ≤ j.val - 1 from h)).symm + · have h : previous j < l := by + by_contra! h + exact hj ((range (previous j) h (le_trans (show previous j + ≤ j from Nat.sub_le _ _) hi)).trans (range j lo hi).symm) + have hl : l.val ≤ j.val := lo + have ht : j.val - 1 < l.val := h + omega + have li := hl i rfl + have go (n : ℕ) : ((back f)^[n] i).val = max l.val (i.val - n) := by + induction n with + | zero => simpa using (max_eq_right (show l.val ≤ i.val from li)).symm + | succ n ih => + have h₁ : l.val ≤ ((back f)^[n] i).val := ih.symm ▸ le_max_left _ _ + have h₂ : ((back f)^[n] i).val ≤ i.val := ih.symm ▸ max_le li (Nat.sub_le _ _) + rw [Function.iterate_succ_apply', hb _ h₁ h₂, ih] + omega + have eq : leader f i = l := by + apply Fin.ext + rw [leader_eq, go] + have := i.isLt + omega + exact eq.symm ▸ ⟨he, hl⟩ + +theorem rank_sorted (f : B h → B k) (hf : Monotone f) (i : B h) : + (i - leader f i).val = Control.rank f i := by + obtain ⟨he, hl⟩ := leader_spec f hf i + have hz : (univ.filter fun j => f j = f i ∧ j < i) = Ico (leader f i) i := by + ext j + simp only [mem_filter, mem_univ, true_and, mem_Ico] + exact ⟨fun h => ⟨hl j h.1, h.2⟩, fun h => ⟨le_antisymm (hf h.2.le) (he ▸ hf h.1), h.2⟩⟩ + rw [Control.rank, Control.histogram_some, hz, Fin.card_Ico] + exact Fin.sub_val_of_le (hl _ rfl) + +/-- Stably sort all keys. -/ +abbrev order (f : B h → B k) := permutation f (fun _ => true) + +theorem order_le (f : B h → B k) {i j : B h} (h : i ≤ j) : + f (order f i) < f (order f j) ∨ (f (order f i) = f (order f j) ∧ order f i ≤ order f j) := by + have e := Tuple.monotone_sort (fun i => toLex (false, toLex (f i, i))) h + rcases Prod.Lex.toLex_le_toLex.mp e with he | ⟨_, he⟩ + · exact (lt_irrefl _ he).elim + · exact Prod.Lex.toLex_le_toLex.mp he + +theorem order_mono (f : B h → B k) : Monotone (f ∘ order f) := + fun _ _ h => (order_le f h).elim LT.lt.le (fun e => e.1.le) + +theorem rank_order (f : B h → B k) (i : B h) : + Control.rank (f ∘ order f) i = Control.rank f (order f i) := by + simp only [Control.rank, Control.histogram_some] + apply card_equiv (order f) + intro j + simp only [mem_filter, mem_univ, true_and, Function.comp_apply] + constructor + · rintro ⟨e, h⟩ + have hle := ((order_le f h.le).resolve_left (not_lt.mpr e.ge)).2 + exact ⟨e, hle.lt_of_ne ((order f).injective.ne h.ne)⟩ + · rintro ⟨e, h⟩ + refine ⟨e, lt_of_not_ge fun hj => ?_⟩ + exact h.not_ge ((order_le f hj).resolve_left (not_lt.mpr e.le)).2 + +/-- The quantity computed by `(fun i => i - leader (f ∘ order f) i) ∘ (order f).symm`. -/ +def groupRank (f : B h → B k) : B h → B h := + (fun i => i - leader (f ∘ order f) i) ∘ (order f).symm + +theorem groupRank_val (f : B h → B k) (i : B h) : (groupRank f i).val = Control.rank f i := by + simp only [groupRank, Function.comp_apply, rank_sorted _ (order_mono f), rank_order, + Equiv.apply_symm_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/RAM/Calls.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/RAM/Calls.lean new file mode 100644 index 0000000000..2524a39338 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/RAM/Calls.lean @@ -0,0 +1,492 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Vector +public import Mathlib.Data.Fin.VecNotation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats + +/-! +# Bit-addressed memory tapes + +A row specifies an address, the bit before the access and the bit +after it. Initial contents are zero. Reads can write back the same +bit, and initialization by advice can be implemented by writes. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM + +open Coloring + +/-- Computes the row by the application `Format.pair (.addr w) (.pair .bit .bit)`. -/ +abbrev Row (w : ℕ) := Format.pair (.addr w) (.pair .bit .bit) + +/-- Computes the tape by the application `Format.vec j (Row w)`. -/ +abbrev Tape (j w : ℕ) := Format.vec j (Row w) + +variable {j w : ℕ} + +/-- In the case `0 => fun _`, this construction gives `false`. -/ +def cells (x : (Tape j w).obj) : ℕ → B w → Bool + | 0 => fun _ => false + | n + 1 => if h : n < 2 ^ j then + Function.update (cells x n) (x ⟨n, h⟩).1 (x ⟨n, h⟩).2.2 + else cells x n + +/-- The condition `∀ i, (x i).2.1 = cells x i.val (x i).1` on the specified data. -/ +def Valid (x : (Tape j w).obj) : Prop := + ∀ i, (x i).2.1 = cells x i.val (x i).1 + +instance (x : (Tape j w).obj) : Decidable (Valid x) := by unfold Valid; infer_instance + +theorem written (x : (Tape j w).obj) (i : B j) : + cells x (i.val + 1) (x i).1 = (x i).2.2 := by + rw [cells, dite_eq_left i.isLt, Function.update_self] + +theorem unchanged (x : (Tape j w).obj) (a : B w) {start stop : ℕ} (h : start ≤ stop) + (hn : ∀ i : B j, start ≤ i.val → i.val < stop → (x i).1 ≠ a) : + cells x stop a = cells x start a := by + induction stop, h using Nat.le_induction with + | base => rfl + | succ n h ih => + have hh := ih (fun i h₁ h₂ => hn i h₁ (by omega)) + rw [cells] + split + · rename_i hi + rw [Function.update_of_ne (hn ⟨n, hi⟩ h (Nat.lt_succ_self n)).symm] + exact hh + · exact hh + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM +end + +section +/- # Adjacent accesses in stable address order -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM + +open Coloring + +variable {j w : ℕ} (x : (Tape j w).obj) + +/-- The indexed operation `permutation (fun i => (x i).1) (fun _ => true)`. -/ +def order : Equiv.Perm (B j) := permutation (fun i => (x i).1) (fun _ => true) + +/-- The value specified by `x ∘ order x`. -/ +def sorted : (Tape j w).obj := x ∘ order x + +private theorem earlier (i k : B j) : + i < k ↔ (sorted x i).1 < (sorted x k).1 ∨ + (sorted x i).1 = (sorted x k).1 ∧ order x i < order x k := by + let f := fun i : B j => toLex (false, toLex ((x i).1, i)) + have hi : Function.Injective f := fun _ _ h => congrArg (fun t => t.2.2) h + have hm : StrictMono (f ∘ order x) := + (Tuple.monotone_sort f).strictMono_of_injective (hi.comp (order x).injective) + rw [← hm.lt_iff_lt] + simp [f, sorted, Prod.Lex.toLex_lt_toLex] + +/-- The quantity computed by `⟨i.val - 1, (Nat.sub_le _ _).trans_lt i.isLt⟩`. -/ +def prev (i : B j) : B j := ⟨i.val - 1, (Nat.sub_le _ _).trans_lt i.isLt⟩ + +/-- Any earlier access to this address lies no later than the previous +row in sorted order, which then has the same address. -/ +private theorem previous (i k : B j) (hk : k < order x i) (he : (x k).1 = (sorted x i).1) : + 0 < i.val ∧ (sorted x (prev i)).1 = (sorted x i).1 ∧ k ≤ order x (prev i) := by + let t := (order x).symm k + have ht : order x t = k := (order x).apply_symm_apply k + have he' : (sorted x t).1 = (sorted x i).1 := by rw [sorted, Function.comp_apply, ht]; exact he + have hi : t < i := (earlier x t i).mpr (.inr ⟨he', ht.trans_lt hk⟩) + change t.val < i.val at hi + have hpos : 0 < i.val := by omega + have hpred : t ≤ prev i := by change t.val ≤ i.val - 1; omega + have hpred' : prev i < i := by change i.val - 1 < i.val; omega + have hu : (sorted x (prev i)).1 ≤ (sorted x i).1 := by + rcases (earlier x _ _).mp hpred' with h | h + · exact h.le + · exact h.1.le + refine ⟨hpos, ?_⟩ + rcases hpred.eq_or_lt with heq | hl + · rw [← heq, ht]; exact ⟨he', le_rfl⟩ + rcases (earlier x _ _).mp hl with h | h + · exact (hu.not_gt (he' ▸ h)).elim + · exact ⟨h.1.symm.trans he', ht.symm.le.trans h.2.le⟩ + +/-- Returns `(x (prev i)).2.2` when `0 < i.val ∧ (x (prev i)).1 = (x i).1` holds, and `false` +otherwise. -/ +def expected (i : B j) : Bool := + if 0 < i.val ∧ (x (prev i)).1 = (x i).1 then (x (prev i)).2.2 else false + +private theorem before (i : B j) : + cells x (order x i).val (sorted x i).1 = expected (sorted x) i := by + unfold expected + split + · rename_i h + have hp : prev i < i := by change i.val - 1 < i.val; omega + have htime := ((earlier x _ _).mp hp).resolve_left (not_lt_of_ge h.2.ge) + rw [unchanged x _ (Nat.succ_le_of_lt htime.2) (by + intro k hk hk' he + have ht : k.val ≤ (order x (prev i)).val := (previous x i k hk' he).2.2 + omega), ← h.2] + exact written x _ + · rename_i h + rw [unchanged x _ (Nat.zero_le _) (by + intro k _ hk he + obtain ⟨h₁, h₂, _⟩ := previous x i k hk he + exact h ⟨h₁, h₂⟩)] + rfl + +theorem valid_iff : Valid x ↔ ∀ i, (sorted x i).2.1 = expected (sorted x) i := by + simp_rw [← before] + constructor + · exact fun h i => h (order x i) + · intro h i + obtain ⟨k, rfl⟩ := (order x).surjective i + exact h k + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM +end + +section +/- # Computing all the local checks in stable address order -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM + +open Coloring + +variable (F : Type) [Field F] (j w : ℕ) + +private theorem tape_width : (Tape j w).width ≤ 2 ^ j * (100 + (j + w + 2)) ^ 1 := by + simp only [Tape, Row, Format.width_vec, Format.width_pair, Format.width_addr, pow_one] + rw [Format.width_bit] + exact Nat.mul_le_mul_left _ (by omega) + +private theorem cheap_sorted : Cheap F j (j + w + 2) (Tape j w) (Tape j w) sorted 43 := by + have ha : (Format.vec j (.addr w)).width ≤ 2 ^ j * (100 + (j + w + 2)) ^ 1 := by + simp only [Format.width_vec, Format.width_addr, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have hb : (Format.vec j .bit).width ≤ 2 ^ j * (100 + (j + w + 2)) ^ 1 := by + rw [Format.width_vec, Format.width_bit, pow_one] + exact Nat.mul_le_mul_left _ (by omega) + have pick : Cheap F j (j + w + 2) (Tape j w) (.vec j (.addr w)) (fun x i => (x i).1) 2 := + Cheap.project F (tape_width _ _) ha (fun i => (i.1, .inl i.2)) (fun _ _ => rfl) + have mark := Cheap.const F (tape_width j w) hb (fun _ => true) + have perm := (pick.pair mark).comp ((cheap_permutation F j w).widen (l := j + w + 2) (by omega)) + have read := Cheap.lookup F j (j + w + 2) (Row w) (by omega) (by simp [Row]) + have H := ((Cheap.id F (tape_width j w)).pair perm).comp read + simp only [Function.comp_def, id_eq] at H + exact H + +private abbrev Test := Format.pair (.pair (.addr w) (.addr w)) (.pair .bit .bit) + +private def neighbors (x : (Tape j w).obj) (i : B j) : (Test w).obj := + (((x (prev i)).1, (x i).1), ((x i).2.1, (x (prev i)).2.2)) + +private theorem test_width : (Test w).width ≤ (100 + (j + w + 2)) ^ 2 := by + simp only [Test, Format.width_pair, Format.width_addr] + rw [Format.width_bit] + ring_nf + omega + +private theorem cheap_neighbors : Cheap F j (j + w + 2) (Tape j w) (.vec j (Test w)) + (neighbors j w) 3 := by + have ha : (Tape j w).width ≤ 2 ^ j * (100 + (j + w + 2)) ^ 2 := + (tape_width _ _).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) (by decide))) + have hb : (Format.vec j (Test w)).width ≤ 2 ^ j * (100 + (j + w + 2)) ^ 2 := by + rw [Format.width_vec] + exact Nat.mul_le_mul_left _ (test_width j w) + let e : (Format.vec j (Test w)).pins → (Tape j w).pins + | (i, .inl (.inl a)) => (prev i, .inl a) + | (i, .inl (.inr a)) => (i, .inl a) + | (i, .inr (.inl a)) => (i, .inr (.inl a)) + | (i, .inr (.inr a)) => (prev i, .inr (.inr a)) + apply Cheap.project F ha hb e + rintro x ⟨i, (a | a) | (a | a)⟩ <;> rfl + +private def test (i : B j) (x : (Test w).obj) : Bool := + decide (x.2.1 = if 0 < i.val ∧ x.1.1 = x.1.2 then x.2.2 else false) + +private theorem cheap_test (i : B j) : Cheap F 0 (j + w + 2) (Test w) .bit (test j w i) 2 := by + let g := fun x : Bool × Bool × Bool => decide (x.2.1 = if 0 < i.val ∧ x.1 then x.2.2 else false) + have hc := (numeric_eq F w).par (Circuit.id F (.pair .bit .bit)) + have ho := hc.comp (small (F := F) (A := .pair .bit (.pair .bit .bit)) (by simp) g) + have he : Circuit F (Test w) .bit (test j w i) (2 * w + 1 + 2 + 200) := by + rw [Format.width_pair .bit .bit, Format.width_bit] at ho + convert ho using 1 + funext x + simp only [test, g, Function.comp_apply, Prod.map, id_eq, decide_eq_true_eq] + refine ⟨_, he, ?_⟩ + simp only [Test, Format.width_pair, Format.width_addr, pow_zero, one_mul] + rw [Format.width_bit] + ring_nf + omega + +/-- Tests whether `(sorted x i).2.1 = expected (sorted x) i` holds. -/ +def checks (x : (Tape j w).obj) (i : B j) : Bool := + decide ((sorted x i).2.1 = expected (sorted x) i) + +theorem cheap_checks : Cheap F j (j + w + 2) (Tape j w) (.vec j .bit) (checks j w) 45 := + ((cheap_sorted F j w).comp (cheap_neighbors F j w)).comp (Cheap.map _ (cheap_test F j w)) + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM +end + +section +/- # Trivalent verification of a named memory tape -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM + +open Coloring Install + +private theorem estimate (j w : ℕ) : + 2 ^ j * (100 + (j + w + 2)) ^ 45 + 2 ^ j * 16 ≤ 2 ^ j * (100 + j + w) ^ 100 := by + rw [← mul_add] + apply Nat.mul_le_mul_left + let k := 100 + j + w + have hk : 100 ≤ k := by unfold k; omega + have hh : 100 + (j + w + 2) ≤ k ^ 2 := by unfold k; ring_nf; omega + calc + _ ≤ (k ^ 2) ^ 45 + 16 := Nat.add_le_add_right (Nat.pow_le_pow_left hh _) _ + _ = k ^ 90 + 16 := by rw [← pow_mul] + _ ≤ k ^ 90 * k := by + have h : 0 < k ^ 90 := pow_pos (by omega) _ + generalize k ^ 90 = v at h ⊢ + nlinarith + _ ≤ k ^ 100 := by rw [← pow_succ]; exact Nat.pow_le_pow_right (by omega) (by decide) + +/-- One zero-one weight verifies every read against the most recent +write to the same address, with no multiplicity in any characteristic. -/ +theorem weight (F : Type) [Field F] (j w : ℕ) : + Weight F (fun b => if Valid ((Tape j w).code.symm b) then 1 else 0) + (2 ^ j * (100 + j + w) ^ 100) := by + let pin : (Unit → Bool) → F := fun x => if x () then 1 else 0 + have hp : Weight F pin 16 := Weight.dense F Unit pin + obtain ⟨m, hm, hb⟩ := cheap_checks F j w + have hn : m + 2 ^ j * 16 ≤ 2 ^ j * (100 + j + w) ^ 100 := + (Nat.add_le_add_right ((Nat.le_add_left _ _).trans hb) _).trans (estimate j w) + have h := (BNet.weight hm (hp.prod j)).mono hn + convert h using 1 + funext b + let x := (Tape j w).code.symm b + change (if Valid x then (1 : F) else 0) = ∏ i : B j, if checks j w x i then 1 else 0 + by_cases hx : Valid x + · have hc (i : B j) : checks j w x i = true := decide_eq_true ((valid_iff x).mp hx i) + simp only [hx, hc, ite_true, Finset.prod_const_one] + · obtain ⟨i, hi⟩ := not_forall.mp (mt (valid_iff x).mpr hx) + rw [ite_eq_right hx] + symm + exact Finset.prod_eq_zero (Finset.mem_univ i) (by simp [checks, hi]) + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM +end + +/- +# Dyadic dictionary seats + +The active bit distinguishes an empty call from an unused seat. +Lengths are explicit and each width uses one common table label. +Uniformity is in the choice of the dictionary as well as the slot. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM + +open Coloring Install + +open scoped Classical in +/-- The quantity computed by `Format.pair .bit (.pair (.addr (b + 1)) (.vec b .bit))`. -/ +abbrev token (b : ℕ) := Format.pair .bit (.pair (.addr (b + 1)) (.vec b .bit)) + +open scoped Classical in +/-- The token value of type `(token b).obj → F` for the given inputs. -/ +def tokenValue {F : Type} [Field F] (U : ℕ) (W : List Bool → F) (b : ℕ) : + (token b).obj → F := + fun (active, n, x) => if !active then 1 else + if n.val ≤ U ∧ n.val ≤ 2 ^ b then W ((List.ofFn x).take n.val) else 0 + +open scoped Classical in +private theorem token_width (b : ℕ) : (token b).width ≤ 4 * 2 ^ b := by + simp only [token, Format.width_pair, Format.width_vec] + rw [Format.width_bit, Format.width_addr] + have := Nat.lt_two_pow_self (n := b) + omega + +open scoped Classical in +/-- The least binary width whose power of two reaches the stated size. -/ +def ceiling (U : ℕ) := Nat.clog 2 (U + 1) +open scoped Classical in +/-- Computes the calls by the application `Slot t t (ceiling U)`. -/ +abbrev Calls (t U : ℕ) := Slot t t (ceiling U) + +variable {F : Type} [Field F] (U : ℕ) (W : List Bool → F) + +open scoped Classical in +/-- Reindexes two finite types using equality of cardinalities. -/ +def sites (b : ℕ) : (token b).pins ≃ slots (word (token b).width) := + Fintype.equivOfCardEq (by simp [Format.width]) + +open scoped Classical in +/-- The indexed operation `⟨word (token b).width, .unit, fun x _ => tokenValue U W b ((token +b).code.symm (bits (word (token b).width) x ∘ sites b))⟩`. -/ +def label (b : ℕ) : Table F := + ⟨word (token b).width, .unit, + fun x _ => tokenValue U W b ((token b).code.symm (bits (word (token b).width) x ∘ sites b))⟩ + +open scoped Classical in +/-- Computes the labels by the application `label U W '' Set.Iic (ceiling U)`. -/ +def labels : Set (Table F) := label U W '' Set.Iic (ceiling U) + +open scoped Classical in +theorem label_cost {b : ℕ} (hb : b ≤ ceiling U) : + WideWeight F (8 * (U + 1)) (labels U W) (tokenValue U W b ∘ (token b).code.symm) (5 * 2 ^ b) + := by + have h₁ : 2 ^ b ≤ 2 * (U + 1) := + (Nat.pow_le_pow_right (by decide) hb).trans (pow_clog_le_twice (by omega)) + have hw := token_width b + let a := word (token b).width + let f := fun (x : Val a) (_ : Val .unit) => + tokenValue U W b ((token b).code.symm (bits a x ∘ sites b)) + have hn : Wide F (8 * (U + 1)) (labels U W) a .unit f (1 + wd a) := by + apply Wide.table + · simp only [a, wd_word, wd, add_zero] + omega + · exact .inr ⟨b, hb, rfl⟩ + intro c e + refine ⟨1 + wd a, ?_, ?_⟩ + · show 1 + wd a ≤ 5 * 2 ^ b + rw [show wd a = (token b).width from wd_word _] + have := Nat.two_pow_pos b + omega + · simpa [f, Function.comp_def] using hn.pre (rewire_reindex ((sites b).symm.trans e)) + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM +end + +/- +# Packing variable-length calls + +Every call costs at least one bit of charge. Within each dyadic bucket +we use an initial segment of the installed seats, in issuance order. +Unused seats contribute one. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM + +variable {F : Type} [Field F] {n t U : ℕ} + +open scoped Classical in +/-- The maximum of the quantities in `1 x.length`. -/ +def callCharge (x : List Bool) := max 1 x.length + +open scoped Classical in +/-- The indexed operation `(false, 0, fun _ => false)`. -/ +def emptyToken (b : ℕ) : (token b).obj := (false, 0, fun _ => false) + +open scoped Classical in +/-- Returns `(true, ⟨x.length, h⟩, fun i => x[i.val]?.getD false)` when `h : x.length < 2 ^ (b + +1)` holds, and `emptyToken b` otherwise. -/ +def encodeToken (b : ℕ) (x : List Bool) : (token b).obj := + if h : x.length < 2 ^ (b + 1) then + (true, ⟨x.length, h⟩, fun i => x[i.val]?.getD false) + else emptyToken b + +open scoped Classical in +theorem tokenValue_encode (W : List Bool → F) (b : ℕ) (x : List Bool) + (hx : x.length ≤ U) (hb : x.length ≤ 2 ^ b) : + tokenValue U W b (encodeToken b x) = W x := by + have hn : x.length < 2 ^ (b + 1) := lt_of_le_of_lt hb (by + rw [pow_succ] + have : 0 < 2 ^ b := Nat.two_pow_pos b + omega) + simp only [encodeToken, dite_eq_left hn, tokenValue, Bool.not_true, Bool.false_eq_true, ite_false, + hx, hb, and_self, ite_true] + congr 1 + apply List.ext_getElem + · simp [hb] + · intro i h₁ h₂ + simp [h₂] + +open scoped Classical in +/-- A slot stores the ordinal of its call, or a sentinel for an unused seat. -/ +def Issuance (x : Fin n → List Bool) (p : Calls t U → Fin (n + 1)) : Prop := + ∀ b : Fin (ceiling U + 1), OrderedSeats (bucket (fun i => callCharge (x i)) b) + (fun s => p ⟨b, s⟩) + +open scoped Classical in +theorem unique_issuance (x : Fin n → List Bool) (h : ∑ i, callCharge (x i) ≤ t) : + ∃! p : Calls t U → Fin (n + 1), Issuance x p := by + have hp (i : Fin n) : 1 ≤ callCharge (x i) := le_max_left _ _ + have hn : n ≤ t := by + simpa using (Finset.sum_le_sum (s := Finset.univ) (fun i _ => hp i)).trans h + have hh (b : Fin (ceiling U + 1)) := unique_seats (n := seats t t b) + (bucket (fun i => callCharge (x i)) b.val) + ((bucket_capacity hp h b.val).trans (min_le_min_right _ hn)) + let p := fun s : Calls t U => (hh s.1).choose s.2 + refine ⟨p, fun b => (hh b).choose_spec.1, ?_⟩ + intro q hq + funext ⟨b, i⟩ + exact congrFun ((hh b).choose_spec.2 _ (hq b)) i + +variable {x : Fin n → List Bool} {p : Calls t U → Fin (n + 1)} + +open scoped Classical in +private theorem Issuance.index (h : Issuance x p) {i s} (he : p s = i.castSucc) : + Nat.clog 2 (callCharge (x i)) = s.1.val := by + have hh := ((h s.1).2.1 i).mp ⟨s.2, he⟩ + simpa [bucket] using hh + +open scoped Classical in +theorem Issuance.covers (h : Issuance x p) (hu : ∀ i, (x i).length ≤ U) (i : Fin n) : + ∃! s, p s = i.castSucc := by + have hb : Nat.clog 2 (callCharge (x i)) ≤ ceiling U := by + apply Nat.clog_mono_right + exact max_le (by omega) ((hu i).trans (Nat.le_succ _)) + let b : Fin (ceiling U + 1) := ⟨_, Nat.lt_succ_of_le hb⟩ + obtain ⟨s, hs⟩ := ((h b).2.1 i).mpr (by simp [bucket, b]) + refine ⟨⟨b, s⟩, hs, ?_⟩ + rintro ⟨d, z⟩ hz + have hd : d = b := Fin.ext (h.index hz).symm + subst d + have he : z = s := (h b).2.2 _ _ (hz.trans hs.symm) (hz.trans_ne (Fin.castSucc_ne_last i)) + rw [he] + +open scoped Classical in +/-- The indexed operation `Fin.lastCases (emptyToken _) (fun i => encodeToken _ (x i)) (p s)`. -/ +def tokens (x : Fin n → List Bool) (p : Calls t U → Fin (n + 1)) (s : Calls t U) : + (token s.1.val).obj := + Fin.lastCases (emptyToken _) (fun i => encodeToken _ (x i)) (p s) + +open scoped Classical in +theorem Issuance.product (h : Issuance x p) (hu : ∀ i, (x i).length ≤ U) (W : List Bool → F) : + (∏ s, tokenValue U W s.1.val (tokens x p s)) = ∏ i, W (x i) := by + have he (s : Calls t U) : tokenValue U W s.1.val (tokens x p s) = + ∏ i : Fin n, if p s = i.castSucc then W (x i) else 1 := by + by_cases hn : p s = Fin.last n + · simp [tokens, hn, emptyToken, tokenValue, Ne.symm (Fin.castSucc_ne_last _)] + obtain ⟨i, hi⟩ := Fin.exists_castSucc_eq.mpr hn + have hb : (x i).length ≤ 2 ^ s.1.val := by + rw [← h.index hi.symm] + exact (le_max_right _ _).trans (Nat.le_pow_clog (by decide) _) + simp [tokens, ← hi, tokenValue_encode W _ _ (hu i) hb] + simp_rw [he] + rw [Finset.prod_comm] + refine Finset.prod_congr rfl fun i _ => ?_ + obtain ⟨s, hs, hu⟩ := h.covers hu i + rw [Finset.prod_eq_single s] + · exact ite_eq_left hs + · intro z _ hz + exact ite_eq_right (mt (hu z) hz) + · simp + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Choices.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Choices.lean new file mode 100644 index 0000000000..20e857c9c4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Choices.lean @@ -0,0 +1,113 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Algebra.BigOperators.Group.Finset.Basic +public import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +public import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +public import Mathlib.Data.Fintype.Pi + +/-! +# Unique codes for expansion choices + +Dependent sums concatenate stage codes. Products assign a separate +field to each independent local choice. Out-of-range indices are +rejected and padding gives no extra multiplicity. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript + +/-- The data for the selector construction, including `write`, `read`, `valid`. -/ +structure Selector (I C : Type) where + /-- The write operation of type `I → C`. -/ + write : I → C + /-- The read operation of type `C → Option I`. -/ + read : C → Option I + valid : ∀ c i, read c = some i ↔ c = write i + +namespace Selector + +variable {I C D : Type} + +theorem injective (S : Selector I C) : Function.Injective S.write := by + intro i j he + exact Option.some.inj (((S.valid _ i).mpr rfl).symm.trans ((S.valid _ j).mpr he)) + +/-- Embeds indices into a larger range. -/ +def ordinal (n k : ℕ) (h : n ≤ k) : Selector (Fin n) (Fin k) where + write := Fin.castLE h + read c := if hc : c.val < n then some ⟨c.val, hc⟩ else none + valid c i := by + split + · simp only [Option.some.injEq, Fin.ext_iff, Fin.val_castLE] + · rename_i hc + simp only [reduceCtorEq, false_iff] + rintro rfl + exact hc i.isLt + +/-- Builds `Selector I D where write i` with the specified `write`, `read`, `valid`. -/ +def relabel (S : Selector I C) (e : C ≃ D) : Selector I D where + write i := e (S.write i) + read d := S.read (e.symm d) + valid d i := by rw [S.valid, e.symm_apply_eq] + +/-- A branch can determine the next menu. -/ +def bind {J : I → Type} (S : Selector I C) (T : ∀ i, Selector (J i) D) : + Selector (Σ i, J i) (C × D) where + write i := (S.write i.1, (T i.1).write i.2) + read c := (S.read c.1).bind fun i => ((T i).read c.2).map (Sigma.mk i) + valid c i := by + rcases c with ⟨a, b⟩ + rcases i with ⟨i, j⟩ + constructor + · intro h + obtain ⟨x, hx, hy⟩ := Option.bind_eq_some_iff.mp h + obtain ⟨y, he, hij⟩ := Option.map_eq_some_iff.mp hy + cases hij + exact Prod.ext ((S.valid _ _).mp hx) (((T i).valid _ _).mp he) + · intro h + obtain ⟨rfl, rfl⟩ := Prod.mk.inj h + rw [(S.valid _ i).mpr rfl, Option.bind_some, ((T i).valid _ j).mpr rfl] + rfl + +/-- Independent local codes may have different lengths. -/ +def family {A : Type} [Fintype A] {I C : A → Type} (S : ∀ a, Selector (I a) (C a)) : + Selector (∀ a, I a) (∀ a, C a) where + write i a := (S a).write (i a) + read c := if h : ∀ a, ((S a).read (c a)).isSome + then some (fun a => ((S a).read (c a)).get (h a)) else none + valid c i := by + constructor + · split + · rename_i h + intro eq + cases Option.some.inj eq + funext a + exact ((S a).valid _ _).mp (Option.some_get _).symm + · simp + · rintro rfl + have h (a : A) : (S a).read ((S a).write (i a)) = some (i a) := ((S a).valid _ _).mpr rfl + simp [h] + +noncomputable section + +open scoped Classical in +theorem sum [Fintype C] [Fintype I] {F : Type} [AddCommMonoid F] (S : Selector I C) + (f : I → F) : ∑ c, (S.read c).elim 0 f = ∑ i, f i := by + have he (c : C) : (S.read c).elim 0 f = ∑ i, if c = S.write i then f i else 0 := by + simp_rw [← S.valid] + cases S.read c <;> simp + simp_rw [he] + rw [Finset.sum_comm] + simp + +end +end Selector +end MatrixMultiplicationAllFields.MatrixExponent.Transcript diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Graph.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Graph.lean new file mode 100644 index 0000000000..5b27aeba85 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Graph.lean @@ -0,0 +1,84 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortBack +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Restore +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Choices +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.RAM.Calls +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Packets +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Shaving.Defs + +/-! # Verifying a deterministic controller on two named tapes -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Coloring + +open Install +variable {F : Type} [Field F] {A D : Format} {f : A.obj → D.obj} {j k c : ℕ} + +open scoped Classical in +/-- Returns `1` when `f (A.code.symm (z ∘ Sum.inl)) = D.code.symm (z ∘ Sum.inr)` holds, and `0` +otherwise. -/ +def graph (F : Type) [Field F] (A D : Format) (f : A.obj → D.obj) + (z : A.pins ⊕ D.pins → Bool) : F := + if f (A.code.symm (z ∘ Sum.inl)) = D.code.symm (z ∘ Sum.inr) then 1 else 0 + +open scoped Classical in +theorem Cheap.weight (h : Cheap F j k A D f c) : + Weight F (graph F A D f) (2 ^ j * (100 + k) ^ c) := by + obtain ⟨m, hf, hm⟩ := h + let a := word A.width + let b := word D.width + let i : A.pins ≃ slots a := Fintype.equivOfCardEq (by simp [a, Format.width]) + let l : D.pins ≃ slots b := Fintype.equivOfCardEq (by simp [b, Format.width]) + obtain ⟨v, hv, hf⟩ := hf a b i l + have hb : wd b = D.width := wd_word _ + apply Weight.of_layout (a := .pair a b) (i.sumCongr l) + refine ⟨v + wd b, by omega, ?_⟩ + have hu (k : Val a → Val b → F) (hk : Net F a b k v) : + Net F (.pair a b) .unit (fun x _ => k x.1 x.2) (v + wd b) := by + have both := (hk.par (Tagged.cap b)).pre (.assoc a b b) + simpa only [mul_ite, mul_one, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] using + (both.post (.swap _ _)).trace + convert hu _ hf using 1 + funext z _ + have he (u : D.obj) : u = D.code.symm (bits b z.2 ∘ l) ↔ + (bits b).symm (D.code u ∘ l.symm) = z.2 := by + rw [Equiv.eq_symm_apply, Equiv.symm_apply_eq] + simp only [funext_iff, Function.comp_apply] + exact ⟨fun h t => by simpa using h (l.symm t), fun h t => by simpa using h (l t)⟩ + change (if f (A.code.symm (bits a z.1 ∘ i)) = D.code.symm (bits b z.2 ∘ l) then (1 : F) else 0) + = _ + simp only [he, Function.comp_apply] + +end MatrixMultiplicationAllFields.MatrixExponent.Coloring +end + +/- # Labeled networks for a selected family of routed diagrams -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM + +open Filter + +open scoped Classical in +theorem labeled {K : Type} [Field K] {a b : Wire} {f : Val a → Val b → K} + {W : List Bool → K} {U s : ℕ} (h : Wide K (8 * (U + 1)) (labels U W) a b f s) : + Labeled f (ceiling U + 1) s (8 * (U + 1)) := by + let L := (Finset.range (ceiling U + 1)).image (label U W) + have he : (↑L : Set (Table K)) = labels U W := by + ext + simp [L, labels] + exact ⟨L, Finset.card_image_le.trans_eq (Finset.card_range _), he.symm ▸ h⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.RAM +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Packets.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Packets.lean new file mode 100644 index 0000000000..8885e8b17c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Packets.lean @@ -0,0 +1,168 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortBack +public import Mathlib.Data.List.OfFn + +/-! +# Matching uniquely addressed messages + +The active and direction bits precede the payload and identifier. +Only the two flags and the identifier are sent through the ordinary +sorting network. Reversing active directions must permute the full +records, so both ends carry identical data. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.Messages + +/-- The quantity computed by `word (H + w + 2)`. -/ +abbrev row (H w : ℕ) := word (H + w + 2) + +/-- In the case `0, x`, this construction gives `x`. -/ +def identifier (H : ℕ) : (w : ℕ) → Val (word (H + w)) → Val (word H) + | 0, x => x + | w + 1, x => identifier H w x.2 + +/-- The value specified by `(x.1, x.2.1, identifier H w x.2.2)`. -/ +def header (H w : ℕ) (x : Val (row H w)) : Val (word (H + 2)) := + (x.1, x.2.1, identifier H w x.2.2) + +/-- The value specified by `(x.1, if x.1 then !x.2.1 else x.2.1, x.2.2)`. -/ +def reverse (H w : ℕ) (x : Val (row H w)) : Val (row H w) := + (x.1, if x.1 then !x.2.1 else x.2.1, x.2.2) + +/-- Requires `((flatten j x).map (header H w)).Nodup ∧ ((flatten j x).map (reverse H w)).Perm +(flatten j x)`. -/ +def valid (j H w : ℕ) (x : Val (tree j (row H w))) : Prop := + ((flatten j x).map (header H w)).Nodup ∧ ((flatten j x).map (reverse H w)).Perm (flatten j x) + +theorem reverse_involutive (H w : ℕ) : Function.Involutive (reverse H w) := by + rintro ⟨_ | _, b, y⟩ <;> simp [reverse] + +theorem valid_iff (j H w : ℕ) (x : Val (tree j (row H w))) : + valid j H w x ↔ ((flatten j x).map (header H w)).Nodup ∧ + ∀ r ∈ flatten j x, r.1 = true → reverse H w r ∈ flatten j x := by + constructor + · exact fun h => ⟨h.1, fun _ hr _ => h.2.subset (List.mem_map_of_mem hr)⟩ + · rintro ⟨hn, hm⟩ + refine ⟨hn, ?_⟩ + have hd := (hn.of_map (header H w)).map (reverse_involutive H w).injective + apply (hd.subperm ?_).perm_of_length_le (by simp) + rintro _ h + obtain ⟨r, hr, rfl⟩ := List.mem_map.mp h + cases ha : r.1 + · have he : reverse H w r = r := by + unfold reverse + rw [ite_eq_right (by simp [ha])] + rw [he] + exact hr + · exact hm r hr ha + +variable (F : Type) [Field F] + +private theorem id_net (H w : ℕ) : + DNet F (word (H + w)) (word H) (identifier H w) (H + w) := by + induction w with + | zero => exact (DNet.id F (word H)).mono (by simp) + | succ w ih => + have t := ((DNet.discard F .bit).par ih).post ((Rewire.swap _ _).comp (.unit _)) + exact t.mono (by simp [wd]; omega) + +private theorem header_net (H w : ℕ) : + DNet F (row H w) (word (H + 2)) (header H w) (H + w + 2) := by + have bit := DNet.id F .bit + exact (bit.par (bit.par (id_net F H w))).mono (by simp [wd]; omega) + +theorem reverse_net (H w : ℕ) : DNet F (row H w) (row H w) (reverse H w) (H + w + 6) := by + have gate := DNet.table F (.pair .bit .bit) .bit + (fun x => if x.1 then !x.2 else x.2) (by decide) + have t := ((DNet.fst F .bit .bit).pair gate).par (DNet.id F (word (H + w))) + exact ((t.pre (.assoc' _ _ _)).post (.assoc _ _ _)).mono (by simp [wd]; omega) + +open Classical in +theorem net {F : Type} [Field F] {j H w m : ℕ} (ht : Radix.Tag F j (H + w + 2) m) : + ∃ v ≤ m + 10000 * 2 ^ j * (w + (1 + H) * (j + 1) ^ 2), + Net F (tree j (word (H + w + 2))) .unit (fun x _ => if valid j H w x then 1 else 0) v := by + let t := tree j (row H w) + have heads := (Tagged.mapRows_net (header_net F H w) j).comp (nodup_net F j (H + 2)) + have pair := (DNet.id F t).pair (Tagged.mapRows_net (reverse_net F H w) j) + obtain ⟨r, hr, prep⟩ := pair.pair heads + obtain ⟨k, v, hk, hv, hcheck⟩ := Install.blind ht + have pin := Net.table (F := F) .bit .unit (fun b _ => if b then 1 else 0) (by decide) + have h := prep.comp (((Install.uncurry hk).par pin).post (.unit' _)) + refine ⟨r + (v + wd t + 1), ?_, ?_⟩ + · have := Nat.two_pow_pos j + simp only [t, row, wd_tree] at hr ⊢ + rw [wd_word] at hr ⊢ + ring_nf at hr hv ⊢ + omega + · convert h using 1 + funext x _ + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, + decide_eq_true_eq, Tagged.flatten_mapRows] + by_cases hn : ((flatten j x).map (header H w)).Nodup + · rw [hcheck _ _ (hn.of_map _)] + simp [valid, Tagged.permuted, Tagged.flatten_mapRows, hn] + · simp [valid, hn] + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.Messages +end + +section +/- +# Equality links implemented by packets + +Select the headers and their pairing before reading payloads. Once +those headers are checked, the global permutation test imposes exactly +the indicated bit equalities between opposite ends of each active key. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.Messages + +/-- In the case `0, _, a`, this construction gives `a`. -/ +def appendWord (H : ℕ) : (w : ℕ) → Val (word w) → Val (word H) → Val (word (H + w)) + | 0, _, a => a + | w + 1, x, a => (x.1, appendWord H w x.2 a) + +/-- The value specified by `(a.1, a.2.1, appendWord H w v a.2.2)`. -/ +def assemble {H w : ℕ} (a : Val (word (H + 2))) (v : Val (word w)) : Val (row H w) := + (a.1, a.2.1, appendWord H w v a.2.2) + +/-- The value specified by `(a.1, if a.1 then !a.2.1 else a.2.1, a.2.2)`. -/ +def opposite {H : ℕ} (a : Val (word (H + 2))) : Val (word (H + 2)) := + (a.1, if a.1 then !a.2.1 else a.2.1, a.2.2) + +theorem header_assemble {H w : ℕ} (a : Val (word (H + 2))) (v : Val (word w)) : + header H w (assemble a v) = a := by + suffices identifier H w (appendWord H w v a.2.2) = a.2.2 by + exact Prod.ext rfl (Prod.ext rfl this) + induction w with + | zero => rfl + | succ w ih => exact ih v.2 + +theorem reverse_assemble {H w : ℕ} (a : Val (word (H + 2))) (v : Val (word w)) : + reverse H w (assemble a v) = assemble (opposite a) v := rfl + +theorem assemble_injective {H w : ℕ} (a : Val (word (H + 2))) : + Function.Injective (assemble (w := w) a) := by + suffices Function.Injective (fun x => appendWord H w x a.2.2) from + fun _ _ h => this (congrArg (fun k => k.2.2) h) + induction w with + | zero => exact fun _ _ _ => Subsingleton.elim _ _ + | succ w ih => + intro x y h + change (x.1, appendWord H w x.2 a.2.2) = (y.1, appendWord H w y.2 a.2.2) at h + exact Prod.ext (Prod.mk.inj h).1 (ih (Prod.mk.inj h).2) + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.Messages +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Restore.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Restore.lean new file mode 100644 index 0000000000..5c48de3730 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Route/Restore.lean @@ -0,0 +1,500 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Route.Choices +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transcript.Seats +public import Mathlib.Algebra.BigOperators.Group.Finset.Basic +public import Mathlib.Data.Fintype.Pi +public import Mathlib.Logic.Relation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Basic +public import Mathlib.Data.List.OfFn +public import Mathlib.Logic.Equiv.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Replacement +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Packing.Frame + +/-! +# Numbering within capacity buckets + +The decoder at a bucket first range-checks the index, then reads +the entry at that rank in the ordered list for the bucket. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript.Selector + +variable {I A C : Type} + +/-- Builds `Selector A C where write a` with the specified `write`, `read`, `valid`. -/ +def domain (S : Selector I C) (e : A ≃ I) : Selector A C where + write a := S.write (e a) + read c := (S.read c).map e.symm + valid c a := by + rw [Option.map_eq_some_iff] + simp only [e.symm_apply_eq, exists_eq_right, S.valid] + +/-- Builds `Selector I (Σ a, C a) where write i` with the specified `Selector`, `read`, `valid`, +`rcases`. -/ +def fiber {C : A → Type} (k : I → A) (S : ∀ a, Selector {i // k i = a} (C a)) : + Selector I (Σ a, C a) where + write i := ⟨k i, (S (k i)).write ⟨i, rfl⟩⟩ + read a := ((S a.1).read a.2).map Subtype.val + valid a i := by + rcases a with ⟨a, c⟩ + constructor + · intro he + obtain ⟨⟨j, hj⟩, hc, rfl⟩ := Option.map_eq_some_iff.mp he + change k j = a at hj + subst a + exact congrArg (Sigma.mk (k j)) (((S _).valid _ _).mp hc) + · intro he + cases he + rw [((S _).valid _ _).mpr rfl] + rfl + +noncomputable section +variable {P V k : ℕ} [Fintype I] [LinearOrder I] + +open scoped Classical in +/-- A deterministic ordinal per bucket. -/ +def ranked {n : ℕ} (h : Fintype.card I ≤ n) : Selector I (Fin n) := + (ordinal _ _ h).domain (Fintype.orderIsoFinOfCardEq I rfl).symm.toEquiv + +open scoped Classical in +/-- Uses `⟨Nat.clog 2 (f i), Nat.lt_succ_of_le (Nat.clog_le_of_le_pow (hk i))⟩` as the +representation. -/ +def level (f : I → ℕ) (hk : ∀ i, f i ≤ 2 ^ k) (i : I) : Fin (k + 1) := + ⟨Nat.clog 2 (f i), Nat.lt_succ_of_le (Nat.clog_le_of_le_pow (hk i))⟩ + +omit [LinearOrder I] in +open scoped Classical in +theorem fits (f : I → ℕ) (hp : ∀ i, 0 < f i) (hn : Fintype.card I ≤ P) + (hs : ∑ i, f i ≤ V) (hk : ∀ i, f i ≤ 2 ^ k) (b : Fin (k + 1)) : + Fintype.card {i // level f hk i = b} ≤ seats P V b.val := by + rw [Fintype.card_subtype] + let S := Finset.univ.filter (fun i => level f hk i = b) + have hb (i : I) (hi : i ∈ S) : 2 ^ b.val ≤ 2 * f i := by + have he := congrArg Fin.val (Finset.mem_filter.mp hi).2 + rw [← he] + exact pow_clog_le_twice (hp i) + refine le_min ((Finset.card_le_univ _).trans hn) ((Nat.le_div_iff_mul_le (by positivity)).mpr ?_) + calc + S.card * 2 ^ b.val = ∑ _ ∈ S, 2 ^ b.val := by simp + _ ≤ ∑ i ∈ S, 2 * f i := Finset.sum_le_sum hb + _ ≤ ∑ i, 2 * f i := Finset.sum_le_sum_of_subset (Finset.subset_univ _) + _ ≤ 2 * V := by rw [← Finset.mul_sum]; exact Nat.mul_le_mul_left _ hs + +open scoped Classical in +/-- The indexed operation `fiber (level f hk) (fun b => ranked (fits f hp hn hs hk b))`. -/ +def packed (f : I → ℕ) (hp : ∀ i, 0 < f i) (hn : Fintype.card I ≤ P) + (hs : ∑ i, f i ≤ V) (hk : ∀ i, f i ≤ 2 ^ k) : Selector I (Slot P V k) := + fiber (level f hk) (fun b => ranked (fits f hp hn hs hk b)) + +open scoped Classical in +theorem packed_size (f : I → ℕ) (hp : ∀ i, 0 < f i) (hn : Fintype.card I ≤ P) + (hs : ∑ i, f i ≤ V) (hk : ∀ i, f i ≤ 2 ^ k) (i : I) : + f i ≤ capacity ((packed f hp hn hs hk).write i) := + Nat.le_pow_clog (by decide) _ + +end +end MatrixMultiplicationAllFields.MatrixExponent.Transcript.Selector +end + +/- # Transporting diagram ports on a fixed private tape -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript + +variable {F : Type} {x y : Wire} + +open scoped Classical in +/-- Indexes the boundary by the coordinates of `Bool ⊕ (slots x ⊕ slots y)`. -/ +abbrev Boundary (x y : Wire) := Bool ⊕ (slots x ⊕ slots y) + +open scoped Classical in +/-- Computes the exterior by the application `Sum.elim id (Sum.elim (bits x a) (bits y b))`. -/ +def exterior (a : Val x) (b : Val y) : Boundary x y → Bool := + Sum.elim id (Sum.elim (bits x a) (bits y b)) + +open scoped Classical in +/-- Indexes the ports by the coordinates of `slots T.1 ⊕ slots T.2.1`. -/ +abbrev Ports (T : Table F) := slots T.1 ⊕ slots T.2.1 + +open scoped Classical in +/-- The value specified by `T.2.2 ((bits T.1).symm (z ∘ Sum.inl)) ((bits T.2.1).symm (z ∘ +Sum.inr))`. -/ +def sample (T : Table F) (z : Ports T → Bool) := + T.2.2 ((bits T.1).symm (z ∘ Sum.inl)) ((bits T.2.1).symm (z ∘ Sum.inr)) + +open scoped Classical in +/-- The wires used in the `Transcript` construction. -/ +def wires (G : Diagram F x y) (v : G.V) : Ports (G.table v) → Boundary x y ⊕ G.E + | .inl i => Sum.map (fun p => .inr (.inl p)) id (G.src ⟨v, i⟩) + | .inr i => Sum.map (fun p => .inr (.inr p)) id (G.dst ⟨v, i⟩) + +open scoped Classical in +theorem sample_wires (G : Diagram F x y) (v : G.V) (a : Val x) (b : Val y) (z : G.E → Bool) : + sample (G.table v) (Sum.elim (exterior a b) z ∘ wires G v) = G.vertex a b z v := by + unfold sample Diagram.vertex + apply congrArg₂ (G.table v).2.2 <;> apply congrArg <;> funext i + · simp only [Function.comp_apply, wires] + cases G.src ⟨v, i⟩ <;> rfl + · simp only [Function.comp_apply, wires] + cases G.dst ⟨v, i⟩ <;> rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript +end + +section +/- +# A single dictionary for a whole family of station tables + +Use the left-to-right order of the named bit positions. The +argument length is exactly the label length plus the station arity. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript + +/-- In the case `.unit`, this construction gives `Equiv.equivOfIsEmpty Empty (Fin 0)`. -/ +def positions : (a : Wire) → slots a ≃ Fin (wd a) + | .unit => Equiv.equivOfIsEmpty Empty (Fin 0) + | .bit => (Equiv.equivPUnit.{1, 1} Unit).trans (Equiv.equivPUnit (Fin 1)).symm + | .pair a b => ((positions a).sumCongr (positions b)).trans finSumFinEquiv + +variable {F : Type} {d : ℕ} + +/-- Lists the values in order of their bounded index. -/ +def query (name : Fin d → Bool) (T : Table F) (u : Ports T → Bool) : List Bool := + List.ofFn name ++ List.ofFn (u ∘ (positions (.pair T.1 T.2.1)).symm) + +theorem query_length (name : Fin d → Bool) (T : Table F) (u : Ports T → Bool) : + (query name T u).length = d + (wd T.1 + wd T.2.1) := by simp [query, wd] + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript +end + +section +/- +# Ordered bundles at a station + +Positions use the left-to-right order of the incoming and then +outgoing ports. An internal bundle occupies a contiguous interval +at each end. Exterior positions may have arbitrary global names. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram + +open Transcript + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +/-- Side of the local port and, for an internal edge, the remote +station and the offset on the opposite side of that station. -/ +def portPeer (v : G.V) : Ports (G.table v) → Bool × Option (G.V × ℕ) + | .inl i => (false, (G.src ⟨v, i⟩).elim (fun _ => none) fun e => + let p := G.dst.symm (.inr e) + some (p.1, (positions (G.table p.1).2.1 p.2).val)) + | .inr i => (true, (G.dst ⟨v, i⟩).elim (fun _ => none) fun e => + let p := G.src.symm (.inr e) + some (p.1, (positions (G.table p.1).1 p.2).val)) + +/-- Computes the peer by the application `G.portPeer v ((positions (.pair (G.table v).1 (G.table +v).2.1)).symm i)`. -/ +def peer (v : G.V) (i : Fin (G.arity v)) := + G.portPeer v ((positions (.pair (G.table v).1 (G.table v).2.1)).symm i) + +/-- Transforms the indexed data by `(p.1, p.2.map (fun t => (t.1, t.2 + 1)))`. -/ +def advance {V : Type} (p : Bool × Option (V × ℕ)) : Bool × Option (V × ℕ) := + (p.1, p.2.map (fun t => (t.1, t.2 + 1))) + +/-- The defining condition `∀ v, ∃ block : Fin (G.arity v) → Fin R, Monotone block ∧ ∀ i j, +i.val + 1 = j.val → block i = block j → G.peer v j = advance (G.peer v i)`. -/ +def PortOrder (R : ℕ) : Prop := + ∀ v, ∃ block : Fin (G.arity v) → Fin R, Monotone block ∧ + ∀ i j, i.val + 1 = j.val → block i = block j → G.peer v j = advance (G.peer v i) + +theorem portOrder_of_arity {R : ℕ} (h : ∀ v, G.arity v ≤ R) : G.PortOrder R := by + intro v + refine ⟨Fin.castLE (h v), fun _ _ he => he, fun i j he hh => ?_⟩ + have := congrArg Fin.val hh + change i.val = j.val at this + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- # Source offsets in ordered runs of parallel wires -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram +open Transcript + +variable {F : Type} {a b : Wire} (G : Diagram F a b) + +/-- The src offset of type `ℕ`, constructed using `G.src.symm (.inr e)`. -/ +def srcOffset (e : G.E) : ℕ := + let p := G.src.symm (.inr e) + (positions (G.table p.1).1 p.2).val + +theorem srcOffset_inj {e f : G.E} (hs : G.source e = G.source f) + (ho : G.srcOffset e = G.srcOffset f) : e = f := by + apply Sum.inr.inj + apply G.src.symm.injective + unfold source at hs + unfold srcOffset at ho + generalize G.src.symm (.inr e) = p, G.src.symm (.inr f) = q at hs ho ⊢ + rcases p with ⟨v, i⟩ + rcases q with ⟨w, j⟩ + change v = w at hs + subst w + have he : i = j := (positions (G.table v).1).injective (Fin.ext ho) + rw [he] + +/-- Computes the index at by the application `positions (.pair (G.table v).1 (G.table v).2.1)`. -/ +abbrev indexAt (v : G.V) : Ports (G.table v) ≃ Fin (G.arity v) := + positions (.pair (G.table v).1 (G.table v).2.1) + +/-- Computes the wire at by the application `wires G v ((G.indexAt v).symm i)`. -/ +def wireAt (v : G.V) (i : Fin (G.arity v)) : Boundary a b ⊕ G.E := + wires G v ((G.indexAt v).symm i) + +private theorem port_next (v : G.V) (i j : Ports (G.table v)) + (hs : (positions (.pair (G.table v).1 (G.table v).2.1) i).val + 1 = + (positions (.pair (G.table v).1 (G.table v).2.1) j).val) + (hn : G.portPeer v j = advance (G.portPeer v i)) : + (∃ x y, wires G v i = .inl x ∧ wires G v j = .inl y) ∨ + (∃ e f, wires G v i = .inr e ∧ wires G v j = .inr f ∧ + G.source e = G.source f ∧ G.target e = G.target f ∧ G.srcOffset e + 1 = G.srcOffset f) := by + rcases i with i | i <;> rcases j with j | j + · cases hi : G.src ⟨v, i⟩ <;> cases hj : G.src ⟨v, j⟩ <;> + simp only [portPeer, advance, hi, hj, Sum.elim_inl, Sum.elim_inr, Option.map_none, + Option.map_some, Prod.mk.injEq, Option.some.injEq, reduceCtorEq, true_and] at hn + · exact .inl ⟨_, _, by rw [wires, hi]; rfl, by rw [wires, hj]; rfl⟩ + · rename_i e f + refine .inr ⟨e, f, by rw [wires, hi]; rfl, by rw [wires, hj]; rfl, ?_, hn.1.symm, ?_⟩ + · simp only [source, ←hi, ←hj, Equiv.symm_apply_apply] + · unfold srcOffset + rw [←hi, ←hj, Equiv.symm_apply_apply, Equiv.symm_apply_apply] + exact hs + · cases congrArg Prod.fst hn + · cases congrArg Prod.fst hn + · cases hi : G.dst ⟨v, i⟩ <;> cases hj : G.dst ⟨v, j⟩ <;> + simp only [portPeer, advance, hi, hj, Sum.elim_inl, Sum.elim_inr, Option.map_none, + Option.map_some, Prod.mk.injEq, Option.some.injEq, reduceCtorEq, true_and] at hn + · exact .inl ⟨_, _, by rw [wires, hi]; rfl, by rw [wires, hj]; rfl⟩ + · rename_i e f + refine .inr ⟨e, f, by rw [wires, hi]; rfl, by rw [wires, hj]; rfl, hn.1.symm, ?_, hn.2.symm⟩ + simp only [target, ←hi, ←hj, Equiv.symm_apply_apply] + +/-- On adjacent ports within an ordered block, the side stays fixed +and the source offset of an internal wire advances by one. -/ +theorem wireAt_next (v : G.V) {i j : Fin (G.arity v)} + (hs : i.val + 1 = j.val) (hn : G.peer v j = advance (G.peer v i)) : + (∃ x y, G.wireAt v i = .inl x ∧ G.wireAt v j = .inl y) ∨ + (∃ e f, G.wireAt v i = .inr e ∧ G.wireAt v j = .inr f ∧ + G.source e = G.source f ∧ G.target e = G.target f ∧ G.srcOffset e + 1 = G.srcOffset f) := by + apply G.port_next _ _ _ _ hn + change (G.indexAt v ((G.indexAt v).symm i)).val + 1 = (G.indexAt v ((G.indexAt v).symm j)).val + simpa only [Equiv.apply_symm_apply] using hs + +/-- All indexed positions, including both ends of a loop, are distinct. -/ +def endAt : (Σ v, Fin (G.arity v)) ≃ G.End := + (Equiv.sigmaCongrRight (fun v => (G.indexAt v).symm)).trans G.portEquiv + +theorem station_endAt (p : Σ v, Fin (G.arity v)) : G.station (G.endAt p) = p.1 := + G.station_port _ + +/-- The end wire used in the `Diagram` construction. -/ +def endWire : G.End → Boundary a b ⊕ G.E + | .inl i => Sum.map (fun t => .inr (.inl t)) id i + | .inr j => Sum.map (fun t => .inr (.inr t)) id j + +theorem wireAt_eq (v : G.V) (i : Fin (G.arity v)) : + G.wireAt v i = G.endWire (G.endAt ⟨v, i⟩) := by + change wires G v _ = G.endWire (G.portEquiv ⟨v, (G.indexAt v).symm i⟩) + cases (G.indexAt v).symm i <;> rfl + +theorem peer_side (v : G.V) (i : Fin (G.arity v)) : + (G.peer v i).1 = (G.endAt ⟨v, i⟩).isRight := by + change (G.portPeer v ((G.indexAt v).symm i)).1 = (G.portEquiv ⟨v, (G.indexAt v).symm i⟩).isRight + cases (G.indexAt v).symm i <;> rfl + +theorem wireAt_incident (v : G.V) (i : Fin (G.arity v)) {e : G.E} (h : G.wireAt v i = .inr e) : + G.source e = v ∨ G.target e = v := by + have hv := G.station_endAt ⟨v, i⟩ + rw [wireAt_eq] at h + generalize G.endAt ⟨v, i⟩ = z at hv h + rcases z with (x|e') | (y|e') <;> cases h + · exact .inl hv + · exact .inr hv + +theorem wireAt_inj (loopless : ∀ e, G.source e ≠ G.target e) (v : G.V) : + Function.Injective (G.wireAt v) := by + intro i j h + have hi := G.station_endAt ⟨v, i⟩ + have hj := G.station_endAt ⟨v, j⟩ + rw [wireAt_eq, wireAt_eq] at h + have eq : G.endAt ⟨v, i⟩ = G.endAt ⟨v, j⟩ := by + generalize G.endAt ⟨v, i⟩ = z at hi h ⊢ + generalize G.endAt ⟨v, j⟩ = w at hj h ⊢ + rcases z with (x|e) | (y|e) <;> rcases w with (x'|e') | (y'|e') <;> cases h <;> try rfl + · exact (loopless _ (hi.trans hj.symm)).elim + · exact (loopless _ (hj.trans hi.symm)).elim + exact eq_of_heq (Sigma.mk.inj (G.endAt.injective eq)).2 + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- # Exterior names in station port order -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram +open Transcript + +variable {F E : Type} {a b : Wire} + +/-- In the case `.inl (.inr (.inl i))`, this construction gives `some i`. -/ +def pickLeft : Boundary a b ⊕ E → Option (slots a) + | .inl (.inr (.inl i)) => some i + | _ => none + +/-- In the case `.inl (.inr (.inr j))`, this construction gives `some j`. -/ +def pickRight : Boundary a b ⊕ E → Option (slots b) + | .inl (.inr (.inr j)) => some j + | _ => none + +variable (G : Diagram F a b) (v : G.V) + +/-- The selected finite family `(List.ofFn (G.wireAt v)).filterMap pickLeft`. -/ +def extLeft := (List.ofFn (G.wireAt v)).filterMap pickLeft +/-- The selected finite family `(List.ofFn (G.wireAt v)).filterMap pickRight`. -/ +def extRight := (List.ofFn (G.wireAt v)).filterMap pickRight + +private theorem exterior_spec {X : Type} (pick : Boundary a b ⊕ G.E → Option X) + (side : X → G.End) (hs : ∀ e t, pick (G.endWire e) = some t ↔ e = side t) : + ((List.ofFn (G.wireAt v)).filterMap pick).Nodup ∧ + ∀ t, t ∈ (List.ofFn (G.wireAt v)).filterMap pick ↔ G.station (side t) = v := by + have he i t : pick (G.wireAt v i) = some t ↔ G.endAt ⟨v, i⟩ = side t := by + rw [wireAt_eq, hs] + constructor + · rw [List.ofFn_eq_map, List.filterMap_map] + apply List.Nodup.filterMap _ (List.nodup_finRange _) + intro i j t hi hj + have h := G.endAt.injective (((he i t).mp hi).trans ((he j t).mp hj).symm) + exact eq_of_heq (Sigma.mk.inj h).2 + · intro t + constructor + · rintro ht + obtain ⟨w, hw, heq⟩ := List.mem_filterMap.mp ht + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hw + rw [← (he i t).mp heq, station_endAt] + · intro ht + obtain ⟨⟨w, i⟩, hi⟩ := G.endAt.surjective (side t) + have hw : w = v := (G.station_endAt ⟨w, i⟩).symm.trans (hi ▸ ht) + subst w + exact List.mem_filterMap.mpr ⟨_, List.mem_ofFn.mpr ⟨i, rfl⟩, (he i t).mpr hi⟩ + +private theorem left_spec : (G.extLeft v).Nodup ∧ + ∀ i, i ∈ G.extLeft v ↔ Packing.portEnd G (.inl i) = v := by + apply G.exterior_spec v pickLeft (fun i => .inl (.inl i)) + rintro ((i|e)|(j|e)) t <;> simp [endWire, pickLeft] + +private theorem right_spec : (G.extRight v).Nodup ∧ + ∀ j, j ∈ G.extRight v ↔ Packing.portEnd G (.inr j) = v := by + apply G.exterior_spec v pickRight (fun j => .inr (.inl j)) + rintro ((i|e)|(j|e)) t <;> simp [endWire, pickRight] + +theorem extLeft_nodup : (G.extLeft v).Nodup := (G.left_spec v).1 + +theorem extRight_nodup : (G.extRight v).Nodup := (G.right_spec v).1 + +@[simp] theorem mem_extLeft (i : slots a) : i ∈ G.extLeft v ↔ Packing.portEnd G (.inl i) = v := + (G.left_spec v).2 i + +@[simp] theorem mem_extRight (j : slots b) : j ∈ G.extRight v ↔ Packing.portEnd G (.inr j) = v := + (G.right_spec v).2 j + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end + +section +/- # Reading a table from local labels and its two exterior strings -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Diagram +open Transcript + +variable {F α : Type} {a b : Wire} + +/-- A tagged position reads an internal bit. An untagged position +consumes the next exterior bit on its side. -/ +def restore (x : α → Bool) : List (Bool × Option α) → List Bool → List Bool → List Bool + | [], _, _ => [] + | (_, some i) :: ps, l, r => x i :: restore x ps l r + | (false, none) :: ps, l, r => l.headD false :: restore x ps l.tail r + | (true, none) :: ps, l, r => r.headD false :: restore x ps l r.tail + +/-- The indexed operation `sample T (fun i => (l[(positions (.pair T.1 T.2.1) i).val]?).getD +false)`. -/ +def fromList (T : Table F) (l : List Bool) := + sample T (fun i => (l[(positions (.pair T.1 T.2.1) i).val]?).getD false) + +variable (G : Diagram F a b) (v : G.V) + +theorem exterior_side (i : Fin (G.arity v)) {k : slots a ⊕ slots b} + (he : G.wireAt v i = .inl (.inr k)) : (G.peer v i).1 = k.isRight := by + rw [peer_side] + rw [wireAt_eq] at he + generalize G.endAt ⟨v, i⟩ = j at he ⊢ + rcases j with (u|e)|(t|e) <;> cases he <;> rfl + +theorem vertex_restore (p : Fin (G.arity v) → Bool × Option α) (x : α → Bool) + (s : Val a) (t : Val b) (z : G.E → Bool) + (hp : ∀ i e, G.wireAt v i = .inr e → ∃ j, (p i).2 = some j ∧ z e = x j) + (hl : ∀ i k, G.wireAt v i = .inl (.inr k) → p i = (k.isRight, none)) : + G.vertex s t z v = fromList (G.table v) (restore x (List.ofFn p) + ((G.extLeft v).map (bits a s)) ((G.extRight v).map (bits b t))) := by + let read i := Sum.elim (exterior s t) z (G.wireAt v i) + have go (l : List (Fin (G.arity v))) : + restore x (l.map p) (((l.map (G.wireAt v)).filterMap pickLeft).map (bits a s)) + (((l.map (G.wireAt v)).filterMap pickRight).map (bits b t)) = l.map read := by + induction l with + | nil => rfl + | cons i l ih => + cases he : G.wireAt v i with + | inl k => + rcases k with c | (u | w) + · rw [wireAt_eq] at he + generalize G.endAt ⟨v, i⟩ = j at he + rcases j with (u|e)|(t|e) <;> cases he + · simpa [he, hl i _ he, restore, read, exterior, List.filterMap_cons, + pickLeft, pickRight, -List.filterMap_map] using ih + · simpa [he, hl i _ he, restore, read, exterior, List.filterMap_cons, + pickLeft, pickRight, -List.filterMap_map] using ih + | inr e => + obtain ⟨j, hj, hz⟩ := hp i e he + obtain ⟨d, hd⟩ : ∃ d, p i = (d, some j) := ⟨_, Prod.ext rfl hj⟩ + simpa [he, hd, restore, read, hz, List.filterMap_cons, pickLeft, pickRight, + -List.filterMap_map] using ih + have hr : restore x (List.ofFn p) ((G.extLeft v).map (bits a s)) + ((G.extRight v).map (bits b t)) = List.ofFn read := by + simpa only [extLeft, extRight, List.ofFn_eq_map] using go (List.finRange _) + rw [hr, ← sample_wires, fromList] + apply congrArg + funext i + let ord : Ports (G.table v) ≃ Fin (G.arity v) := positions (.pair (G.table v).1 (G.table v).2.1) + change _ = ((List.ofFn read)[(ord i).val]?).getD false + simp only [List.getElem?_ofFn, dite_eq_left (ord i).isLt, Option.getD_some] + change _ = Sum.elim (exterior s t) z (wires G v (ord.symm (ord i))) + rw [Equiv.symm_apply_apply] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Diagram +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Seats.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Seats.lean new file mode 100644 index 0000000000..68028fa20d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transcript/Seats.lean @@ -0,0 +1,338 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Nat.Log +public import Mathlib.Data.Finset.Sort +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Tactic.Positivity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Diagram.Present + +/-! +# Canonical dyadic allocation + +A slot contains a processor number or a sentinel larger than every +processor number. Ordering the slots of each capacity makes the assignment +unique. Otherwise the contraction could count a transcript several times. +-/ + +@[expose] public section + +section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript +open Finset + +/-- Bounds the seats in one width class by both the total slot count and its bit budget. -/ +def seats (P V j : ℕ) := min P (2 * V / 2 ^ j) + +/-- Indexes the slot by the coordinates of `Σ j : Fin (k + 1), Fin (seats P V j.val)`. -/ +abbrev Slot (P V k : ℕ) := Σ j : Fin (k + 1), Fin (seats P V j.val) + +/-- The quantity computed by `2 ^ s.1.val`. -/ +def capacity {P V k : ℕ} (s : Slot P V k) := 2 ^ s.1.val + +theorem card_slots (P V k : ℕ) : Fintype.card (Slot P V k) ≤ (k + 1) * P := by + rw [Fintype.card_sigma] + simp only [Fintype.card_fin] + calc + _ ≤ ∑ _ : Fin (k + 1), P := sum_le_sum fun _ _ => min_le_left _ _ + _ = _ := by simp + +theorem sum_capacity (P V k : ℕ) : ∑ s : Slot P V k, capacity s ≤ (k + 1) * (2 * V) := by + rw [Fintype.sum_sigma] + calc + _ ≤ ∑ _ : Fin (k + 1), 2 * V := by + apply sum_le_sum + intro j _ + simp only [capacity, sum_const, card_univ, Fintype.card_fin, Nat.nsmul_eq_mul] + exact (Nat.mul_le_mul_right _ (min_le_right _ _)).trans (Nat.div_mul_le_self _ _) + _ = _ := by simp + +variable {P V k : ℕ} + +/-- All processors charged in the dyadic interval ending at `2^j`. -/ +def bucket (charge : Fin P → ℕ) (j : ℕ) := univ.filter fun i => Nat.clog 2 (charge i) = j + +theorem pow_clog_le_twice {x : ℕ} (hx : 0 < x) : 2 ^ Nat.clog 2 x ≤ 2 * x := by + by_cases h : 1 < x + · have hlt := Nat.pow_pred_clog_lt_self 2 h + have hpos : 0 < Nat.clog 2 x := Nat.clog_pos (by decide) h + rw [show Nat.clog 2 x = (Nat.clog 2 x).pred + 1 from (Nat.succ_pred_eq_of_pos hpos).symm, + pow_succ'] + omega + · have : x = 1 := by omega + subst x + decide + +theorem bucket_capacity {charge : Fin P → ℕ} (hpos : ∀ i, 0 < charge i) + (hsum : ∑ i, charge i ≤ V) (j : ℕ) : (bucket charge j).card ≤ seats P V j := by + apply le_min + · simpa using (bucket charge j).card_le_univ + · apply (Nat.le_div_iff_mul_le (by positivity)).mpr + calc + _ = ∑ _ ∈ bucket charge j, 2 ^ j := by simp + _ ≤ ∑ i ∈ bucket charge j, 2 * charge i := by + refine sum_le_sum fun i hi => ?_ + rw [← (mem_filter.mp hi).2] + exact pow_clog_le_twice (hpos i) + _ ≤ ∑ i, 2 * charge i := sum_le_sum_of_subset (subset_univ _) + _ ≤ 2 * V := by simp only [two_mul, sum_add_distrib]; omega + +/-- Every listed processor occurs once, in the initial sorted segment. +The last element of `Fin (P+1)` denotes an unused slot. -/ +def OrderedSeats {n : ℕ} (s : Finset (Fin P)) (f : Fin n → Fin (P + 1)) : Prop := + Monotone f ∧ (∀ x, (∃ i, f i = x.castSucc) ↔ x ∈ s) ∧ + ∀ i j, f i = f j → f i ≠ Fin.last P → i = j + +theorem unique_seats {n : ℕ} (s : Finset (Fin P)) (hs : s.card ≤ n) : + ∃! f : Fin n → Fin (P + 1), OrderedSeats s f := by + let seq := s.orderEmbOfFin rfl + let f (i : Fin n) := if hi : i.val < s.card then (seq ⟨i, hi⟩).castSucc else Fin.last P + have good : OrderedSeats s f := by + refine ⟨?_, ?_, ?_⟩ + · intro i j hij + by_cases h : j.val < s.card + · have h' : i.val < s.card := lt_of_le_of_lt hij h + simp only [f, dite_eq_left h, dite_eq_left h'] + exact seq.monotone hij + · rw [show f j = Fin.last P by simp [f, h]]; exact Fin.le_last _ + · intro x + constructor + · rintro ⟨i, he⟩ + have hi : i.val < s.card := by + by_contra! hh + rw [show f i = Fin.last P by simp [f, hh.not_gt]] at he + exact Fin.castSucc_ne_last x he.symm + simp only [f, dite_eq_left hi, Fin.castSucc_inj] at he + exact he ▸ s.orderEmbOfFin_mem rfl _ + · intro hx + obtain ⟨j, hj⟩ := (s.orderIsoOfFin rfl).surjective ⟨x, hx⟩ + refine ⟨Fin.castLE hs j, ?_⟩ + simp only [f, Fin.val_castLE, dite_eq_left j.isLt, Fin.eta] + exact congrArg (fun p : s => p.val.castSucc) hj + · intro i j he hi + have h₁ : i.val < s.card := by by_contra! h; exact hi (dite_eq_right h.not_gt) + have h₂ : j.val < s.card := by by_contra! h; exact hi (he.trans (dite_eq_right h.not_gt)) + simp only [f, dite_eq_left h₁, dite_eq_left h₂, Fin.castSucc_inj] at he + exact Fin.ext (congrArg (fun z : Fin s.card => z.val) (seq.injective he)) + refine ⟨f, good, fun g hg => funext fun i => ?_⟩ + induction i using WellFoundedLT.induction with + | ind i ih => + have aux (a b : Fin n → Fin (P + 1)) (ha : OrderedSeats s a) (hb : OrderedSeats s b) + (prev : ∀ j, j < i → a j = b j) : ¬a i < b i := by + intro h + have hlast : a i ≠ Fin.last P := ne_of_lt (h.trans_le (Fin.le_last _)) + obtain ⟨x, hx⟩ := Fin.exists_castSucc_eq.mpr hlast + obtain ⟨j, hj⟩ := (hb.2.1 x).mpr ((ha.2.1 x).mp ⟨i, hx.symm⟩) + have hji : j < i := lt_of_not_ge (fun hle => (hb.1 hle).not_gt (hj.trans hx ▸ h)) + have eq : a i = a j := hx.symm.trans (hj.symm.trans (prev j hji).symm) + exact hji.ne' (ha.2.2 i j eq hlast) + exact le_antisymm (le_of_not_gt (aux f g good hg (fun j hj => (ih j hj).symm))) + (le_of_not_gt (aux g f hg good ih)) + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript +end + +section +/- +# Realizing a weighted sum of products + +Each factor receives its own list of argument positions from a common +tape. Positions may be repeated or unused. Summation is over all private +bits, with multiplicity, in the ground field. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent + +variable {F : Type} [Field F] {a b : Wire} {u s : ℕ} {L : Set (Table F)} + +theorem Wide.mono {k : Val a → Val b → F} (h : Wide F u L a b k s) + {v : ℕ} {T : Set (Table F)} (hu : u ≤ v) (hL : L ⊆ T) : Wide F v T a b k s := by + induction h with + | empty => exact .empty + | table _ _ _ hw h => exact .table _ _ _ (hw.trans hu) (h.imp_right fun ht => hL ht) + | par _ _ ih ig => exact ih.par ig + | comp _ _ ih ig => exact ih.comp ig + | trace _ ih => exact ih.trace + | pre _ hr ih => exact ih.pre hr + | post _ hr ih => exact ih.post hr + +theorem Net.includeWide {k : Val a → Val b → F} (h : Net F a b k s) (hu : 3 ≤ u) : + ∃ t ≤ 4 * s, Wide F u L a b k t := by + obtain ⟨t, ht, hw⟩ := h.wide + exact ⟨t, ht, hw.mono hu (Set.empty_subset _)⟩ + +theorem Wide.trivalent {k : Val a → Val b → F} (h : Wide F 3 L a b k s) : + ∃ v ≤ s, Net F a b k v := by + obtain ⟨G, he, had, hc⟩ := h.diagram + refine ⟨Fintype.card G.V, ?_, he ▸ G.net (fun v => (had v).1)⟩ + rw [← hc] + unfold Diagram.cost + simp only [Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, mul_one] + exact Nat.le_add_right _ _ + +namespace Transcript + +open Install + +variable {I : Type} [Fintype I] (A : I → Wire) (k : (i : I) → Val (A i) → F) +variable (cost : I → ℕ) + +-- Collect the factor tables first. Duplicating the tape once per factor +-- would charge the entire tape even for a local read. +private theorem collect {c : Wire} (read : (i : I) → slots (A i) → slots c) + (h : ∀ i, ∃ t ≤ cost i, Wide F u L (A i) .unit (fun x _ => k i x) t) : + ∃ (d : Wire) (r : slots d → slots c) (f : Val d → F) (t : ℕ), + Wide F u L d .unit (fun x _ => f x) t ∧ + t ≤ ∑ i, cost i ∧ ∀ x, f (project r x) = ∏ i, k i (project (read i) x) := by + classical + generalize (Finset.univ : Finset I) = S + induction S using Finset.induction_on with + | empty => exact ⟨.unit, Empty.elim, fun _ => 1, 0, .empty, by simp, by simp⟩ + | @insert i S hi ih => + obtain ⟨d, r, f, t, hf, ht, he⟩ := ih + obtain ⟨n, hn, hk⟩ := h i + refine ⟨.pair (A i) d, Sum.elim (read i) r, fun x => k i x.1 * f x.2, n + t, + (hk.par hf).post (.unit' _), by rw [Finset.sum_insert hi]; omega, ?_⟩ + intro x + rw [Finset.prod_insert hi, ← he] + rfl + +variable {c : Wire} (read : (i : I) → slots (A i) → slots (.pair (.pair a b) c)) + +/-- The value specified by `∑ z : Val c, ∏ i, k i (project (read i) ((x, y), z))`. -/ +def value (x : Val a) (y : Val b) := + ∑ z : Val c, ∏ i, k i (project (read i) ((x, y), z)) + +private theorem close (hu : 3 ≤ u) {v : ℕ} (f : Val (.pair (.pair a b) c) → F) + (hf : Wide F u L (.pair (.pair a b) c) .unit (fun x _ => f x) v) : + ∃ s ≤ v + 4 * (wd b + wd c), Wide F u L a b (fun x y => ∑ z : Val c, f ((x, y), z)) s := by + obtain ⟨t, ht, cup⟩ := (Net.cup F b).includeWide (L := L) hu + have ones (d : Wire) : Net F .unit d (fun _ _ => 1) (wd d) := by + induction d with + | bit => exact .table _ _ _ (by decide) + | unit => exact .empty + | pair _ _ ih ig => simpa only [wd, one_mul] using (ih.par ig).pre (.unit' _) + obtain ⟨q, hq, free⟩ := (ones c).includeWide (L := L) hu + have h₁ := ((hf.par free).pre (.unit' _)).trace + have h₂ := (((h₁.par cup).pre (.unit' _)).post ((Rewire.unit' _).comp (.swap _ _))).trace + refine ⟨v + q + t, by omega, ?_⟩ + simpa only [mul_one, mul_ite, mul_zero, Finset.sum_ite_eq, Finset.mem_univ, ite_true] using h₂ + +theorem wide (hu : 3 ≤ u) + (h : ∀ i, ∃ t ≤ cost i, Wide F u L (A i) .unit (fun x _ => k i x) t) : + ∃ s ≤ 8 * (wd a + wd b + wd c) + 9 * ∑ i, cost i, Wide F u L a b (value A k read) s := by + obtain ⟨d, r, f, t, hf, ht, he⟩ := collect A k cost read h + obtain ⟨n, hn, hp⟩ := project_net F r + obtain ⟨v, hv, hp⟩ := hp.includeWide (L := L) hu + have hall : Wide F u L (.pair (.pair a b) c) .unit + (fun x _ => ∏ i, k i (project (read i) x)) (v + t) := by + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, he] + using hp.comp hf + obtain ⟨s, hs, hw⟩ := close hu _ hall + have hw' := hf.width + simp only [wd] at hn hw' + exact ⟨s, by omega, hw⟩ + +theorem net (h : ∀ i, ∃ t ≤ cost i, Net F (A i) .unit (fun x _ => k i x) t) : + ∃ s ≤ 8 * (wd a + wd b + wd c) + 36 * ∑ i, cost i, Net F a b (value A k read) s := by + have hw (i : I) : ∃ n ≤ 4 * cost i, Wide F 3 ∅ (A i) .unit (fun x _ => k i x) n := by + obtain ⟨t, ht, hn⟩ := h i + obtain ⟨n, hm, hn⟩ := hn.wide + exact ⟨n, hm.trans (Nat.mul_le_mul_left _ ht), hn⟩ + obtain ⟨t, ht, hn⟩ := wide A k _ read le_rfl hw + obtain ⟨s, hs, h⟩ := hn.trivalent + rw [← Finset.mul_sum] at ht + exact ⟨s, by omega, h⟩ + +end Transcript +end MatrixMultiplicationAllFields.MatrixExponent +end + +/- # A fixed weighted transcript on named bits -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transcript +open Install + +variable {F I X Y : Type} [Field F] [Fintype I] [Fintype X] [Fintype Y] +variable {Z : I → Type} [∀ i, Fintype (Z i)] + +open Classical in +/-- A value for each possible assignment, obtained by summing over all +hidden bits. Each local factor addresses the public or the hidden tape. -/ +def weightedSum (k : (i : I) → (Z i → Bool) → F) (read : (i : I) → Z i → X ⊕ Y) + (x : X → Bool) : F := + ∑ y : Y → Bool, ∏ i, k i (Sum.elim x y ∘ read i) + +open Classical in +/-- The cost here counts all ports, including both ends of every wire. -/ +def WideWeight (F : Type) [Field F] (u : ℕ) (L : Set (Table F)) + {X : Type} (f : (X → Bool) → F) (m : ℕ) : Prop := + ∀ (a : Wire) (i : X ≃ slots a), ∃ v ≤ m, Wide F u L a .unit (fun x _ => f (bits a x ∘ i)) v + +variable {u : ℕ} {L : Set (Table F)} + +omit [Fintype X] in +open Classical in +theorem of_weight {f : (X → Bool) → F} {n : ℕ} (hu : 3 ≤ u) (h : Weight F f n) : + WideWeight F u L f (4 * n) := by + intro a i + obtain ⟨w, hw, h⟩ := h a i + obtain ⟨v, hv, h⟩ := h.includeWide (L := L) hu + exact ⟨v, hv.trans (Nat.mul_le_mul_left 4 hw), h⟩ + +variable (k : (i : I) → (Z i → Bool) → F) (read : (i : I) → Z i → X ⊕ Y) (cost : I → ℕ) + +open Classical in +omit [∀ i, Fintype (Z i)] in +theorem wide_sum [∀ i, Finite (Z i)] (hu : 3 ≤ u) (h : ∀ i, WideWeight F u L (k i) (cost i)) : + WideWeight F u L (weightedSum k read) + (8 * (Fintype.card X + Fintype.card Y) + 9 * ∑ i, cost i) := by + let : ∀ i : I, Fintype (Z i) := fun i => Fintype.ofFinite (Z i) + intro a ix + let c := word (Fintype.card Y) + let iy : Y ≃ slots (word (Fintype.card Y)) := Fintype.equivOfCardEq (by simp) + let A := fun i => word (Fintype.card (Z i)) + let iz (i : I) : Z i ≃ slots (word (Fintype.card (Z i))) := Fintype.equivOfCardEq (by simp) + let f (i : I) (x : Val (A i)) := k i (bits (A i) x ∘ iz i) + let place : X ⊕ Y → slots (.pair (.pair a .unit) c) := + Sum.elim (fun x => .inl (.inl (ix x))) (fun y => .inr (iy y)) + let r (i : I) := place ∘ read i ∘ (iz i).symm + obtain ⟨s, hs, hv⟩ := wide A f cost r hu (fun i => h i _ (iz i)) + refine ⟨s, by simpa [wd, c, Fintype.card_congr ix] using hs, ?_⟩ + have he : value (a := a) (b := .unit) (c := c) A f r = fun x _ + => weightedSum k read (bits a x ∘ ix) := by + funext x t + unfold value weightedSum + let e := (bits c).trans (iy.symm.arrowCongr (Equiv.refl Bool)) + refine @Fintype.sum_equiv (Val c) (Y → Bool) F (valFintype c) _ _ e _ _ ?_ + intro y + apply Finset.prod_congr rfl + intro i _ + apply congrArg (k i) + funext z + simp only [Function.comp_apply, bits_project, r, Equiv.symm_apply_apply] + cases read i z <;> rfl + rwa [he] at hv + +open Classical in +omit [∀ i, Fintype (Z i)] in +theorem weight_sum [∀ i, Finite (Z i)] (h : ∀ i, Weight F (k i) (cost i)) : + Weight F (weightedSum k read) (8 * (Fintype.card X + Fintype.card Y) + 36 * ∑ i, cost i) := by + intro a ix + obtain ⟨s, hs, hw⟩ := wide_sum k read (fun i => 4 * cost i) le_rfl + (fun i => of_weight (L := ∅) le_rfl (h i)) a ix + obtain ⟨t, ht, hn⟩ := hw.trivalent + rw [← Finset.mul_sum] at hs + exact ⟨t, by omega, hn⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Transcript +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transport/Scale.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transport/Scale.lean new file mode 100644 index 0000000000..26f742733a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transport/Scale.lean @@ -0,0 +1,912 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.Table +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Array +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.SortBack +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.System +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.SumOut +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.AdjacentDuplicates +public import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics +public import Mathlib.Analysis.SpecificLimits.Normed + +/-! +# Preparing the exterior records and the permutation + +Decode the proposed tags as binary addresses. A fixed permutation of +the source list reconciles enumeration order with the address coding. +Only the tags are sorted to validate the permutation. Payloads are +padded and moved by fixed wiring. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport + +open Coloring +variable {F : Type} [Field F] {h n W z : ℕ} + +private abbrev Row (h n : ℕ) := Tagged.row h (word n) +private abbrev Rows (h n : ℕ) := tree h (Row h n) +private abbrev Both (h n : ℕ) := Wire.pair (Rows h n) (Rows h n) +private abbrev Array (h n : ℕ) := B h → Val (Row h n) +private abbrev Table (h n : ℕ) := Layout (Row h n) (Rows h n) (B h) + +private def names (y : Array h n) (i : B h) := Control.index h (y i).1 + +private theorem names_iff (y : Array h n) : + ((List.ofFn y).map Prod.fst).Nodup ↔ Function.Bijective (names y) := by + rw [List.map_ofFn, List.nodup_ofFn, ← Finite.injective_iff_bijective] + constructor + · exact fun hy => (Control.index h).injective.comp hy + · exact fun hy i j he => hy (congrArg (Control.index h) he) + +private theorem indexed_perm (x y : Array h n) (π : Equiv.Perm (B h)) (hx : names x = π) : + (List.ofFn y).Perm (List.ofFn x) ↔ + ((List.ofFn y).map Prod.fst).Nodup ∧ ∀ i, (y i).2 = (x (π.symm (names y i))).2 := by + have ident (i j) : (y i).1 = (x j).1 ↔ π.symm (names y i) = j := by + rw [Equiv.symm_apply_eq, ← hx] + exact (Control.index h).injective.eq_iff.symm + constructor + · intro he + have hn := (names_iff x).mpr (hx.symm ▸ π.bijective) + refine ⟨(he.symm.map _).nodup hn, fun i => ?_⟩ + obtain ⟨j, hj⟩ := List.mem_ofFn.mp (he.subset (List.mem_ofFn.mpr ⟨i, rfl⟩)) + rw [(ident i j).mp (congrArg Prod.fst hj.symm), hj] + · rintro ⟨hn, hm⟩ + apply ((hn.of_map Prod.fst).subperm ?_).perm_of_length_le (by simp) + intro v hv + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hv + exact List.mem_ofFn.mpr ⟨_, Prod.ext ((ident i _).mpr rfl).symm (hm i).symm⟩ + +private theorem source_perm (L : Table h n) (hL : ∀ x, List.ofFn (L.read x) = flatten h x) : + ∃ π : Equiv.Perm (B h), ∀ x : Val (tree h (word n)), names (L.read (Tagged.label h x)) = π := by + have he (x : Val (tree h (word n))) : + (List.ofFn (L.read (Tagged.label h x))).map Prod.fst = flatten h (Tagged.indices h) := by + rw [hL, Tagged.label_tags] + let x₀ := (bits (tree h (word n))).symm (fun _ => false) + have hn := (names_iff (L.read (Tagged.label h x₀))).mp (by rw [he]; exact Tagged.indices_nodup _) + refine ⟨Equiv.ofBijective _ hn, fun x => ?_⟩ + have hh := (he x).trans (he x₀).symm + simp only [List.map_ofFn] at hh + exact congrArg (fun f => Control.index h ∘ f) (List.ofFn_injective hh) + +private abbrev Embed (W z n : ℕ) := slots (word n) ↪ Fin W × Fin z + +private def pad (e : Embed W z n) (x : Val (word n)) (j : Fin W × Fin z) := + if h : ∃ i, e i = j then bits (word n) x h.choose else false + +private theorem pad_injective (e : Embed W z n) : Function.Injective (pad e) := by + have atIndex (x : Val (word n)) (i : slots (word n)) : pad e x (e i) = bits (word n) x i := by + have hp : ∃ j, e j = e i := ⟨i, rfl⟩ + rw [pad, dite_eq_left hp, e.injective hp.choose_spec] + intro x y he + apply (bits (word n)).injective + funext i + rw [← atIndex, ← atIndex, he] + +private def packets (e : Embed W z n) (x : B h → Val (word n)) (i : Site h) : Data W z := + if hi : i.val < 2 ^ h then pad e (x ⟨i.val, hi⟩) else fun _ => false + +private theorem compare_packets (e : Embed W z n) (x y : B h → Val (word n)) (σ : B h → B h) : + (∀ i, packets e x i = packets e y (Routing.inflate h σ i)) ↔ ∀ i, x i = y (σ i) := by + have lo (x : B h → Val (word n)) (i : B h) : packets e x (Routing.lowerHalf h i) = pad e (x i) + := by + simp [packets, Routing.lowerHalf, i.isLt] + have lower (i : B h) : Routing.inflate h σ (Routing.lowerHalf h i) = Routing.lowerHalf h (σ i) + := by + simp [Routing.inflate, Routing.lowerHalf, i.isLt] + constructor + · intro he i + apply pad_injective e + simpa only [lower, lo] using he (Routing.lowerHalf h i) + · intro he i + by_cases hi : i.val < 2 ^ h + · rw [show i = Routing.lowerHalf h ⟨i.val, hi⟩ from rfl, lower, lo, lo, he] + · simp [Routing.inflate, packets, hi] + +private abbrev Payload (h W z : ℕ) := Format.pair (Perm h) (.pair (Packet h W z) (Packet h W z)) + +private def routeData (e : Embed W z n) (L : Table h n) (π : Equiv.Perm (B h)) + (x : Val (Both h n)) : (Payload h W z).obj := + (names (L.read x.2), packets e (fun i => (L.read x.2 i).2), + packets e (fun i => (L.read x.1 (π.symm i)).2)) + +private theorem read_bit (L : Table h n) (x : slots (Rows h n) → Bool) + (i : B h) (j : slots (Row h n)) : + bits (Row h n) (L.read ((bits (Rows h n)).symm x) i) j = x (L.positions (i, j)) := by + simp [Layout.read] + +private theorem packets_depend (e : Embed W z n) (L : Table h n) + (f : slots (Rows h n) → slots (Both h n)) (r : B h → B h) : + Install.Depends (fun x (ij : Site h × (Fin W × Fin z)) => + packets e (fun i => (L.read ((bits (Rows h n)).symm (x ∘ f)) (r i)).2) ij.1 ij.2) 1 := by + rintro ⟨i, j⟩ + by_cases hi : i.val < 2 ^ h + · by_cases hj : ∃ k, e k = j + · let k := f (L.positions (r ⟨i.val, hi⟩, .inr hj.choose)) + refine ⟨{k}, by simp, fun x y he => ?_⟩ + simp only [packets, dite_eq_left hi, pad, dite_eq_left hj] + have eq (x : slots (Both h n) → Bool) : + bits (word n) (L.read ((bits (Rows h n)).symm (x ∘ f)) (r ⟨i.val, hi⟩)).2 hj.choose = x k + := + read_bit L _ _ (.inr hj.choose) + rw [eq, eq, he k (by simp)] + · exact ⟨∅, by simp, fun _ _ _ => by simp [packets, hi, pad, hj]⟩ + · exact ⟨∅, by simp, fun _ _ _ => by simp [packets, hi]⟩ + +private theorem data_circuit (e : Embed W z n) (L : Table h n) (π : Equiv.Perm (B h)) : + Circuit F (.wire (Both h n)) (Payload h W z) (routeData e L π) + (wd (Both h n) + Install.localCost 1 * (Payload h W z).width) := by + have hc : Install.Depends ((Payload h W z).code ∘ routeData e L π ∘ (bits (Both h n)).symm) 1 + := by + rintro (⟨i, j⟩ | ij | ij) + · let k : slots (Both h n) := .inr (L.positions (i, .inl j)) + refine ⟨{k}, by simp, fun x y he => ?_⟩ + have eq (x : slots (Both h n) → Bool) : + (Format.addr h).code (names (L.read ((bits (Rows h n)).symm (x ∘ Sum.inr))) i) j = x k + := by + change ((Control.decode h).symm (Control.index h + (L.read ((bits (Rows h n)).symm (x ∘ Sum.inr)) i).1)) j = x k + simp only [Control.decode, Equiv.symm_trans_apply, Equiv.symm_apply_apply] + exact read_bit L _ _ (.inl j) + exact (eq x).trans ((he k (by simp)).trans (eq y).symm) + · exact packets_depend e L Sum.inr id ij + · exact packets_depend e L Sum.inl π.symm ij + have hn := hc.bnet F + rw [card_slots] at hn + exact hn + +private theorem wire_circuit {a b : Wire} {f : Val a → Val b} {m : ℕ} (hf : DNet F a b f m) : + Circuit F (.wire a) (.wire b) f m := by + apply Circuit.of_dnet (.refl _) (.refl _) hf + intro x + simp [Format.wire] + +private def labels (h n : ℕ) (x : Val (input h n)) : Val (Both h n) := + (Tagged.label h x.1, x.2) + +private def check (h n : ℕ) (x : Val (Both h n)) := decide (((flatten h x.2).map Prod.fst).Nodup) + +private theorem check_circuit (F : Type) [Field F] (h n : ℕ) : + Circuit F (.wire (Both h n)) .bit (check h n) + (wd (Both h n) + 2 ^ h * wd (Row h n) + 400 * 2 ^ h * (h + 1) ^ 2 * (h + 1)) := by + have tags := Tagged.mapRows_net (DNet.fst F (word h) (word n)) h + have readTags := (DNet.snd F (Rows h n) (Rows h n)).comp tags + have hc := readTags.comp (nodup_net F h h) + simp only [Tagged.flatten_mapRows] at hc + exact wire_circuit hc + +private theorem compiled (e : Embed W z n) (L : Table h n) (π : Equiv.Perm (B h)) (hv : n ≤ W * z) : + Circuit F (.wire (input h n)) (Exterior h W z) + (fun x => (check h n (labels h n x), routeData e L π (labels h n x))) + (1000000 * 2 ^ h * ((h + 1) ^ 4 + W * z)) := by + have src := wire_circuit ((Tagged.label_net F h (word n)).par (DNet.id F (Rows h n))) + have out := (check_circuit F h n).pair (data_circuit (F := F) e L π) + apply (src.comp out).mono + have hw : (Format.wire (Both h n)).width = wd (Both h n) := card_slots _ + have hp : (Payload h W z).width = 2 ^ h * h + 2 ^ (h + 1) * (W * z) + 2 ^ (h + 1) * (W * z) := by + simp only [Format.width_pair, Format.width_vec, Format.width_addr] + change 2 ^ h * h + (2 ^ (h + 1) * Fintype.card (Fin W × Fin z) + + 2 ^ (h + 1) * Fintype.card (Fin W × Fin z)) = _ + rw [Fintype.card_prod, Fintype.card_fin, Fintype.card_fin, add_assoc] + have size := Nat.mul_le_mul_left (2 ^ h) hv + simp only [hw, hp, wd_tree, wd, wd_word, Install.localCost] + ring_nf at size ⊢ + omega + +theorem prepare (F : Type) [Field F] (h n W z : ℕ) (hv : n ≤ W * z) : + ∃ f, Circuit F (.wire (input h n)) (Exterior h W z) f + (1000000 * 2 ^ h * ((h + 1) ^ 4 + W * z)) ∧ Prepared F f := by + classical + let e : Embed W z n := + ((Fintype.equivFin _).toEmbedding.trans (Fin.castLEEmb (by simpa using hv))).trans + finProdFinEquiv.symm.toEmbedding + obtain ⟨L, hL⟩ := Layout.exists_tree (Row h n) h + obtain ⟨π, hπ⟩ := source_perm L hL + refine ⟨_, compiled e L π hv, fun x => ?_⟩ + let y := L.read x.2 + let v := L.read (Tagged.label h x.1) + have hcheck : check h n (labels h n x) = true ↔ ((List.ofFn y).map Prod.fst).Nodup := by + simp only [check, labels, y, hL] + exact decide_eq_true_iff + constructor + · exact fun hc => (names_iff y).mp (hcheck.mp hc) + · have eq : (flatten h x.2).Perm (flatten h (Tagged.label h x.1)) ↔ + check h n (labels h n x) = true ∧ + ∀ i, packets e (fun j => (y j).2) i = + packets e (fun j => (v (π.symm j)).2) (Routing.inflate h (names y) i) := by + rw [compare_packets, hcheck, ← hL, ← hL] + exact indexed_perm v y π (hπ _) + unfold Tagged.tag Tagged.permuted + congr 1 + exact propext eq + +end MatrixMultiplicationAllFields.MatrixExponent.Transport +end + +/- # Naming the two endpoints of a transport -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport +open Install + +/-- The data for the book construction, including `g`, `b`, `pos`. -/ +structure Book (h p z : ℕ) where + /-- The `Book` field of type `ℕ`. -/ + g : ℕ + /-- The right component. -/ + b : ℕ + /-- Embeds the coordinates as `Port h p ↪ Idx g × Idx b`. -/ + pos : Port h p ↪ Idx g × Idx b + +namespace Book + +variable {h p z : ℕ} (B : Book h p z) + +/-- Reindexes two finite types using equality of cardinalities. -/ +def field : Unit ⊕ slots (word B.b) ⊕ Fin z ≃ Fin (1 + B.b + z) := + Fintype.equivOfCardEq (by simp [Nat.add_assoc]) + +/-- The quantity computed by `B.g b := B.b r := 1 + B.b + z orientation := B.field (.inl ()) ids +i := B.field (.inr (.inl i))`. -/ +abbrev grid : Grid where + g := B.g + b := B.b + r := 1 + B.b + z + orientation := B.field (.inl ()) + ids i := B.field (.inr (.inl i)) + disjoint _ he := Sum.inr_ne_inl (B.field.injective he) + +/-- Returns `some hit.choose` when `hit : ∃ i, B.pos i = v` holds, and `none` otherwise. -/ +def atSlot (v : Idx B.g × Idx B.b) : Option (Port h p) := + if hit : ∃ i, B.pos i = v then some hit.choose else none + +/-- The value specified by `(B.pos (if (a i).2.1 then (a i).2.2 else i)).2`. -/ +def src (a : Orders h p) (i : Port h p) : Idx B.b := + (B.pos (if (a i).2.1 then (a i).2.2 else i)).2 + +/-- Chooses the operation for the left or right summand. -/ +def data (a : Orders h p) (c : Site h → Channels p z) (i : Port h p) : + Fin (1 + B.b + z) → Bool := + Sum.elim (fun _ => (a i).2.1) + (Sum.elim ((Control.decode B.b).symm (B.src a i)) (fun t => c i.1 (i.2, t))) ∘ B.field.symm + +/-- The render used in the `Book` construction. -/ +def render (a : Orders h p) (c : Site h → Channels p z) : B.grid.Ports → Bool + | (j, .inl k) => (B.atSlot (j, k)).elim false (fun i => (a i).1) + | (j, .inr (k, v)) => (B.atSlot (j, k)).elim false (fun i => B.data a c i v) + +/-- The condition `∀ i j, f i = f j → (B.pos i).1 = (B.pos j).1` on the specified data. -/ +def compatible (f : Port h p → ℕ) : Prop := + ∀ i j, f i = f j → (B.pos i).1 = (B.pos j).1 + +end Book +end MatrixMultiplicationAllFields.MatrixExponent.Transport +end + +section +/- +# From configured wires to grouped endpoint checks + +A transport is identified by the position of its source within the +group. The two oriented ends have the same identifier, and validity +of the commands makes each oriented identifier unique. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport.Book +open Install + +variable {h p z : ℕ} (B : Book h p z) {g : Port h p → ℕ} {a : Orders h p} +variable (c : Site h → Channels p z) + +private theorem at_pos (i : Port h p) : B.atSlot (B.pos i) = some i := by + have hn : ∃ j, B.pos j = B.pos i := ⟨i, rfl⟩ + rw [atSlot, dite_eq_left hn, B.pos.injective hn.choose_spec] + +private theorem marked_iff (j : Idx B.g) (k : Idx B.b) : + k ∈ marked (B.grid.block (B.render a c) j) ↔ ∃ i ∈ Enabled a, B.pos i = (j, k) := by + rw [mem_marked] + change (B.atSlot (j, k)).elim false (fun i => (a i).1) = true ↔ _ + constructor + · unfold atSlot + split + · rename_i hk + exact fun hi => ⟨_, Finset.mem_filter.mpr ⟨Finset.mem_univ _, hi⟩, hk.choose_spec⟩ + · simp + · rintro ⟨i, hi, he⟩ + rw [← he, at_pos] + exact (Finset.mem_filter.mp hi).2 + +private theorem payload_eq {i : Port h p} {j : Idx B.g} {k : Idx B.b} (he : B.pos i = (j, k)) : + payload (B.grid.block (B.render a c) j) k = B.data a c i := by + funext t + change (B.atSlot (j, k)).elim false (fun i => B.data a c i t) = _ + rw [← he, at_pos] + rfl + +private theorem data_id (i : Port h p) : B.grid.idOf (B.data a c i) = B.src a i := by + have he : B.data a c i ∘ B.grid.ids = (Control.decode B.b).symm (B.src a i) := by + funext t + simp [grid, data, Function.comp_def] + unfold Grid.idOf + rw [he] + exact Equiv.apply_symm_apply _ _ + +private theorem data_orientation (i : Port h p) : + B.data a c i B.grid.orientation = (a i).2.1 := by simp [data] + +private theorem same_src (hv : Valid g a) {i : Port h p} (hi : i ∈ Enabled a) : + B.src a (a i).2.2 = B.src a i := by + obtain ⟨_, he, ht, _⟩ := hv i hi + simp only [src, ht, he] + cases (a i).2.1 <;> rfl + +private theorem unique_end (hc : B.compatible g) (hv : Valid g a) {i j : Port h p} + (hi : i ∈ Enabled a) (hj : j ∈ Enabled a) (he : (B.pos i).1 = (B.pos j).1) + (hd : B.src a i = B.src a j) (ho : (a i).2.1 = (a j).2.1) : i = j := by + obtain ⟨_, hi', _, hgi⟩ := hv i hi + obtain ⟨_, hj', _, hgj⟩ := hv j hj + unfold src at hd + rw [ho] at hd + cases hjf : (a j).2.1 + · simp only [hjf, Bool.false_eq_true, ite_false] at hd + exact B.pos.injective (Prod.ext he hd) + · simp only [hjf, ite_true] at hd + have hh := (hc _ _ hgi).trans (he.trans (hc _ _ hgj).symm) + rw [← hi', ← hj', B.pos.injective (Prod.ext hh hd)] + +private theorem total : + ∑ j, (marked (B.grid.block (B.render a c) j)).card = (Enabled a).card := by + have he (j) : (marked (B.grid.block (B.render a c) j)).card = + ((Enabled a).filter fun i => (B.pos i).1 = j).card := by + symm + refine Finset.card_bij (fun i _ => (B.pos i).2) ?_ ?_ ?_ + · intro i hi + obtain ⟨hi, hh⟩ := Finset.mem_filter.mp hi + exact (B.marked_iff c _ _).mpr ⟨i, hi, Prod.ext hh rfl⟩ + · intro i hi k hk e + exact B.pos.injective (Prod.ext ((Finset.mem_filter.mp hi).2.trans + (Finset.mem_filter.mp hk).2.symm) e) + · intro k hk + obtain ⟨i, hi, eq⟩ := (B.marked_iff c _ _).mp hk + exact ⟨i, Finset.mem_filter.mpr ⟨hi, congrArg Prod.fst eq⟩, congrArg Prod.snd eq⟩ + simp only [he] + exact (Finset.card_eq_sum_card_fiberwise (fun i _ => Finset.mem_univ ((B.pos i).1))).symm + +private theorem aligned (hc : B.compatible g) (hv : Valid g a) (j : Idx B.g) : + Aligned B.grid.orientation B.grid.idOf (B.grid.block (B.render a c) j) := by + constructor + · intro k hk + obtain ⟨i, hi, he⟩ := (B.marked_iff c _ _).mp hk + rw [B.payload_eq c he, data_id] + have ep : (B.pos i).1 = j := congrArg Prod.fst he + apply (B.marked_iff c _ _).mpr + unfold src + split + · obtain ⟨hm, _, _, hg⟩ := hv i hi + exact ⟨_, hm, Prod.ext ((hc _ _ hg).trans ep) rfl⟩ + · exact ⟨i, hi, Prod.ext ep rfl⟩ + · intro k hk l hl he + obtain ⟨u, hu, eu⟩ := (B.marked_iff c _ _).mp hk + obtain ⟨v, hv', ev⟩ := (B.marked_iff c _ _).mp hl + dsimp only at he + rw [B.payload_eq c eu, B.payload_eq c ev, data_id, data_id, data_orientation, + data_orientation] at he + have eq := B.unique_end hc hv hu hv' ((congrArg Prod.fst eu).trans (congrArg Prod.fst ev).symm) + (Prod.mk.inj he).1 (Prod.mk.inj he).2 + rw [eq, ev] at eu + exact (congrArg Prod.snd eu).symm + +private theorem data_flip (i j : Port h p) : + B.data a c j = flip B.grid.orientation (B.data a c i) ↔ + (a j).2.1 = !(a i).2.1 ∧ B.src a j = B.src a i ∧ + ∀ t, c i.1 (i.2, t) = c j.1 (j.2, t) := by + constructor + · intro hd + refine ⟨?_, (Control.decode B.b).symm.injective ?_, fun t => ?_⟩ + · simpa [data, Install.flip, grid] using congrFun hd (B.field (.inl ())) + · funext k + simpa [data, Install.flip, grid] using congrFun hd (B.field (.inr (.inl k))) + · simpa [data, Install.flip, grid] using (congrFun hd (B.field (.inr (.inr t)))).symm + · rintro ⟨ho, he, hc⟩ + funext k + obtain ⟨_ | _ | _, rfl⟩ := B.field.surjective k <;> simp [data, Install.flip, grid, ho, he, hc] + +private theorem joined (hc : B.compatible g) (hv : Valid g a) : + (∀ j, Closed B.grid.orientation (B.grid.block (B.render a c) j)) ↔ Joins a c := by + constructor + · intro hs i hi + have hm := (B.marked_iff c (B.pos i).1 (B.pos i).2).mpr ⟨i, hi, rfl⟩ + obtain ⟨k, hk, hh⟩ := hs _ _ hm + obtain ⟨j, hj, ej⟩ := (B.marked_iff c _ _).mp hk + rw [B.payload_eq c ej, B.payload_eq c (show B.pos i = ((B.pos i).1, (B.pos i).2) from rfl)] + at hh + obtain ⟨ho, he, hd⟩ := (B.data_flip c i j).mp hh + obtain ⟨hm, _, ho', hg⟩ := hv i hi + have eq := B.unique_end hc hv hj hm ((congrArg Prod.fst ej).trans (hc _ _ hg).symm) + (he.trans (B.same_src hv hi).symm) (ho.trans ho'.symm) + exact eq ▸ hd + · intro hs j k hk + obtain ⟨i, hi, he⟩ := (B.marked_iff c _ _).mp hk + obtain ⟨hm, _, ho, hg⟩ := hv i hi + have ep : (B.pos i).1 = j := congrArg Prod.fst he + have eq : B.pos (a i).2.2 = (j, (B.pos (a i).2.2).2) := + Prod.ext ((hc _ _ hg).trans ep) rfl + refine ⟨_, (B.marked_iff c _ _).mpr ⟨_, hm, eq⟩, ?_⟩ + rw [B.payload_eq c eq, B.payload_eq c he] + exact (B.data_flip c _ _).mpr ⟨ho, B.same_src hv hi, hs i hi⟩ + +open Classical in +theorem rendered (B : Book h p z) (F : Type) [Field F] {g : Port h p → ℕ} {a : Orders h p} + (hc : B.compatible g) (hv : Valid g a) (c : Site h → Channels p z) : + B.grid.Valid (Enabled a).card (B.render a c) ∧ + B.grid.close F (B.render a c) = if Joins a c then 1 else 0 := by + refine ⟨⟨B.aligned c hc hv, (B.total c).le⟩, ?_⟩ + unfold Grid.close + congr 1 + exact propext (B.joined c hc hv) + +end MatrixMultiplicationAllFields.MatrixExponent.Transport.Book +end + +/- +# Installing a transport record + +Look up the fixed slot numbers in parallel. Each remaining output bit +uses at most two input bits. An unused position receives only zeros. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport.Book +open Coloring Install + +variable {h p z : ℕ} (B : Book h p z) (A : Format) + +private abbrev Input (h p z : ℕ) (A : Format) := (Controls h p A).pair (Buffer h p z) +private abbrev Dest (h p : ℕ) := Format.pair (.addr (h + 1)) (.addr p) +private abbrev Work := (Input h p z A).pins ⊕ (Port h p × slots (word B.b)) + +private def pin (u : Port h p × (Dest h p).pins) : (Input h p z A).pins := + .inl (u.1.1, .inr (u.1.2, .inr (.inr u.2))) + +private def number (i : Port h p) := (Control.decode B.b).symm (B.pos i).2 + +private def mark (i : Port h p) : Work B A := .inl (.inl (i.1, .inr (i.2, .inl ()))) +private def dir (i : Port h p) : Work B A := .inl (.inl (i.1, .inr (i.2, .inr (.inl ())))) +private def channel (i : Port h p) (t : Fin z) : Work B A := .inl (.inr (i.1, i.2, t)) + +private def emit (x : Work B A → Bool) : B.grid.Ports → Bool + | (j, .inl k) => (B.atSlot (j, k)).elim false (fun i => x (mark B A i)) + | (j, .inr (k, v)) => (B.atSlot (j, k)).elim false fun i => + Sum.elim (fun _ => x (dir B A i)) + (Sum.elim (fun t => if x (dir B A i) then x (.inr (i, t)) else number B i t) + (fun t => x (channel B A i t))) (B.field.symm v) + +private theorem emit_local : Depends (emit B A) 2 := by + classical + rintro ⟨j, k | ⟨k, v⟩⟩ <;> simp only [emit] <;> cases B.atSlot (j, k) + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + · rename_i i + exact ⟨{mark B A i}, by simp, fun _ _ he => he _ (by simp)⟩ + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + · rename_i i + rcases B.field.symm v with _ | t | t + · exact ⟨{dir B A i}, by simp, fun _ _ he => he _ (by simp)⟩ + · refine ⟨{dir B A i, .inr (i, t)}, Finset.card_le_two, fun x y he => ?_⟩ + simp only [Option.elim_some, Sum.elim_inr, Sum.elim_inl] + rw [he (dir B A i) (by simp), he (.inr (i, t)) (by simp)] + · exact ⟨{channel B A i t}, by simp, fun _ _ he => he _ (by simp)⟩ + +private def prepare (x : (Input h p z A).pins → Bool) : Work B A → Bool := + Sum.elim x (fun u => number B ((Dest h p).code.symm (fun k => x (pin A (u.1, k)))) u.2) + +private theorem emit_eq (x : (Input h p z A).pins → Bool) : + emit B A (prepare B A x) = + B.render (commands ((Input h p z A).code.symm x).1) ((Input h p z A).code.symm x).2 := by + let a := commands ((Input h p z A).code.symm x).1 + let c := ((Input h p z A).code.symm x).2 + change emit B A (prepare B A x) = B.render a c + funext u + rcases u with ⟨j, k | ⟨k, v⟩⟩ + · rfl + · simp only [emit, render] + cases B.atSlot (j, k) with + | none => rfl + | some i => + simp only [Option.elim_some, data, Function.comp_apply] + rcases B.field.symm v with _ | t | t + · rfl + · change (if (a i).2.1 then number B (a i).2.2 t else number B i t) = + number B (if (a i).2.1 then (a i).2.2 else i) t + split <;> rfl + · rfl + +theorem render_net (F : Type) [Field F] : + Circuit F ((Controls h p A).pair (Buffer h p z)) (raw B.grid.Ports) + (fun x => B.render (commands x.1) x.2) + (1000000 * (2 ^ (h + 1 + p) * (1 + h + 1 + p) ^ 3 * (1 + B.b) + + ((Controls h p A).pair (Buffer h p z)).width + Fintype.card B.grid.Ports)) := by + have hi : Fintype.card (Port h p) = 2 ^ (h + 1 + p) := by simp [Fintype.card_prod, pow_add] + have hk : Fintype.card (Dest h p).pins = h + 1 + p := by + change (Dest h p).width = _ + rw [Format.width_pair, Format.width_addr, Format.width_addr] + have hj : Fintype.card (slots (word B.b)) = B.b := by simp + have get := BNet.table F (Port h p) (Dest h p).pins (slots (word B.b)) (h + 1 + p) + hi hk (fun x => number B ((Dest h p).code.symm x)) + have left := (BNet.id F (Input h p z A).pins).pair (get.pull (pin (z := z) A)) + have net := left.comp ((emit_local B A).bnet F) + unfold Circuit + convert net.mono (n := 1000000 * (2 ^ (h + 1 + p) * (1 + h + 1 + p) ^ 3 * (1 + B.b) + + (Input h p z A).width + Fintype.card B.grid.Ports)) (by + simp only [Fintype.card_sum, Fintype.card_prod, hi, hk, hj, localCost, Format.width] + ring_nf + omega) using 1 + funext x + exact (emit_eq B A x).symm + +end MatrixMultiplicationAllFields.MatrixExponent.Transport.Book +end + +section +/- # Total cost allowance for one layer before smaller transports -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport + +open Coloring + +/-- The bill of type `ℕ` for the given inputs. -/ +noncomputable def System.bill {F : Type} {h p W z : ℕ} (S : System F h p W z) (B : Book h p z) + (n m r : ℕ) : ℕ := + 10000000 * (m + wd (input h n) + S.frame.width + S.latent.width + + ((Perm h).pair S.selector).width + 2 ^ (h + 1 + p) * (1 + h + 1 + p) ^ 3 * (1 + B.b) + + Fintype.card B.grid.Ports + 2 ^ (h + 1) * (r + (h + 1) ^ 4 + W * z) + 1) + +end MatrixMultiplicationAllFields.MatrixExponent.Transport +end + +section +/- +# Joining local weighted kernels + +The selector and the core payloads are hidden variables. Invalid +permutation inputs are killed by the exterior check. On a valid input +each surviving term has well-formed endpoints, so closing the grid +implements exactly the prescribed wire equalities. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport + +open Coloring Install + +variable {F : Type} [Field F] {h p W z C n m r : ℕ} + (S : System F h p W z) (B : Book h p z) + +open Classical in +private noncomputable def output (x : S.frame.obj) : B.grid.Ports → Bool := + B.render (commands x.2.1) x.2.2 + +open Classical in +private theorem semantics (hc : B.compatible S.group) (hs : S.Correct C) + {prep : Val (input h n) → (Exterior h W z).obj} (hp : Prepared F prep) + (x : Val (input h n)) : + (∀ l, S.coeff (S.configure prep (x, l)) ≠ 0 → + B.grid.Valid (C * W * 2 ^ h) (output S B (S.configure prep (x, l)))) ∧ + Tagged.tag F h (word n) x () = + ∑ l : S.latent.obj, S.coeff (S.configure prep (x, l)) * + B.grid.close F (output S B (S.configure prep (x, l))) := by + obtain ⟨hb, he⟩ := hp x + by_cases hv : (prep x).1 = true + swap + · simp only [System.coeff, System.configure] + simp [he, hv] + let σ := Equiv.ofBijective (prep x).2.1 (hb hv) + let a := (prep x).2.2.1 + let b := (prep x).2.2.2 + obtain ⟨valid, value⟩ := hs σ a b + let run (l : S.latent.obj) := S.dispatch (σ, S.selector.code.symm l.1) + have score (l : S.latent.obj) : + S.coeff (S.configure prep (x, l)) = S.value (run l) a b l.2 := by + exact ite_eq_left hv + have showPorts (l : S.latent.obj) : + output S B (S.configure prep (x, l)) = B.render (commands (run l)) l.2 := rfl + have ok (l : S.latent.obj) (hl : S.value (run l) a b l.2 ≠ 0) : + B.grid.Valid (C * W * 2 ^ h) (B.render (commands (run l)) l.2) ∧ + B.grid.close F (B.render (commands (run l)) l.2) = + if Joins (commands (run l)) l.2 then 1 else 0 := by + obtain ⟨ht, hw⟩ := valid _ _ hl + obtain ⟨⟨hg, hs⟩, he⟩ := B.rendered F hc ht l.2 + exact ⟨⟨hg, hs.trans hw⟩, he⟩ + simp only [score, showPorts] + refine ⟨fun l hl => (ok l hl).1, ?_⟩ + simp only [hv, true_and] at he + rw [he] + trans ∑ l : S.latent.obj, S.value (run l) a b l.2 * (if Joins (commands (run l)) l.2 then 1 else + 0) + · rw [Fintype.sum_prod_type] + exact value + · apply Finset.sum_congr rfl + intro l _ + by_cases hl : S.value (run l) a b l.2 = 0 + · simp [hl] + · rw [(ok l hl).2] + +open Classical in +theorem assemble (hc : B.compatible S.group) (hv : n ≤ W * z) (hs : S.Correct C) + (hq : Circuit F ((Perm h).pair S.selector) (Controls h p S.config) S.dispatch m) + (hk : Weight F S.localWeight r) : + ∃ t ≤ S.bill B n m r, B.grid.Open F h n t (C * W * 2 ^ h) := by + obtain ⟨f, hf, hp⟩ := prepare F h n W z hv + have compute := S.configure_net hf hq + have weight := (S.coeff_net hk).pre compute + have proj := Circuit.project (F := F) (A := S.frame) (D := S.terminals) + (f := Prod.snd) Sum.inr (fun _ _ => rfl) + have output := (compute.comp proj).comp (B.render_net S.config F) + obtain ⟨t, ht, net⟩ := emit B.grid S.latent weight output + (fun x => (semantics S B hc hs hp x).1) (fun x => (semantics S B hc hs hp x).2) + refine ⟨t, ht.trans ?_, net⟩ + simp only [System.bill, Format.width_pair, pow_succ] + ring_nf + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Transport +end + +section +/- +# Installing the grouped protocol + +The slot book and the exponent in the cost bound are independent of +all input records. The height of the address and that of the payload +have separate polynomial costs. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport +open Coloring Install + +variable {F : Type} {h p W z n b m r : ℕ} + +private theorem book (f : Port h p → ℕ) (hb : 1 ≤ b) (hb' : b ≤ h) + (hs : ∀ i, (Finset.univ.filter (fun k => f k = i)).card ≤ 2 ^ (b - 1)) : + ∃ B : Book h p z, B.compatible f ∧ B.g = h + p + 2 - b ∧ B.b = b := by + have hcard : Fintype.card (Port h p) ≤ 2 ^ (h + p + 2 - b) * 2 ^ (b - 1) := by + simp only [Fintype.card_prod, Fintype.card_fin, ← pow_add] + rw [show h + p + 2 - b + (b - 1) = h + 1 + p by omega] + have hh := exists_bins f _ _ hs (Nat.two_pow_pos _) hcard + rw [← pow_succ', Nat.sub_add_cancel hb] at hh + obtain ⟨e, he⟩ := hh + exact ⟨⟨_, _, e⟩, he, rfl, rfl⟩ + +private theorem boundary (S : System F h p W z) : + S.frame.width + S.latent.width = (Controls h p S.config).width + + ((Perm h).pair S.selector).width + 1 + 2 * 2 ^ (h + 1) * (W * z + 2 ^ p * z) := by + unfold System.frame System.terminals System.latent Exterior + rw [Format.width_pair, Format.width_pair, Format.width_pair, Format.width_pair, + Format.width_pair, Format.width_pair, Format.width_pair, Format.width_bit, + Format.width_vec (h + 1) (raw _), Format.width_vec (h + 1) (raw _)] + simp only [Format.width, raw, Fintype.card_prod, Fintype.card_fin] + ring + +private theorem grid_bound (B : Book h p z) (hg : B.g + B.b = h + p + 2) : + Fintype.card B.grid.Ports = 2 ^ h * (4 * 2 ^ p) * (2 + B.b + z) := by + simp only [Book.grid, Grid.Ports, Fintype.card_prod, Fintype.card_sum, Fintype.card_fin] + rw [show 2 ^ B.b + 2 ^ B.b * (1 + B.b + z) = 2 ^ B.b * (2 + B.b + + z) by ring, ← mul_assoc, ← pow_add, hg] + ring + +private def factor (p W : ℕ) := 10000000 * (100 + 100 * W + 100 * 2 ^ p * (2 + p) ^ 3) + +private theorem bill_le (S : System F h p W z) (B : Book h p z) (hg : B.g + B.b = h + p + 2) + (hb : B.b ≤ h) (hn : n ≤ W * z) {T : ℕ} + (hT : (100 + h) ^ 4 ≤ T) (hz : z ≤ T) (hr : r ≤ T) + (hm : ((Perm h).pair S.selector).width + (Controls h p S.config).width + m ≤ 2 ^ (h + 1) * T) : + S.bill B n m r ≤ 2 ^ h * factor p W * T := by + have hp := Nat.one_le_pow h 2 (by decide) + have hu : 2 + h ≤ T := by + have := Nat.pow_le_pow_right (show 0 < 100 + h by omega) (by decide : 1 ≤ 4) + simp only [pow_one] at this + omega + have hu' : (h + 1) ^ 4 ≤ T := (Nat.pow_le_pow_left (by omega) _).trans hT + have he : wd (input h n) ≤ 2 ^ h * (2 * W + 1) * T := by + simp only [wd, wd_tree, wd_word] + calc + _ ≤ 2 ^ h * (W * T) + 2 ^ h * (T + W * T) := by + have := hn.trans (Nat.mul_le_mul_left W hz) + gcongr; omega + _ = _ := by ring + have hh : (1 + h + 1 + p) ^ 3 * (1 + B.b) ≤ (2 + p) ^ 3 * T := calc + _ ≤ ((2 + p) * (100 + h)) ^ 3 * (100 + h) := by gcongr <;> nlinarith only [hb] + _ = (2 + p) ^ 3 * (100 + h) ^ 4 := by ring + _ ≤ _ := by gcongr + have hwide := Nat.mul_le_mul_left (2 ^ (h + 1 + p)) hh + have hgrid : Fintype.card B.grid.Ports ≤ 2 ^ h * (4 * 2 ^ p) * (2 * T) := by + rw [grid_bound B hg]; gcongr; omega + have ht := Nat.mul_le_mul_left (2 * 2 ^ (h + 1)) (Nat.add_le_add + (Nat.mul_le_mul_left W hz) (Nat.mul_le_mul_left (2 ^ p) hz)) + have endpt := Nat.mul_le_mul_left (2 ^ (h + 1)) + (Nat.add_le_add (Nat.add_le_add hr hu') (Nat.mul_le_mul_left W hz)) + have hone : 1 ≤ 2 ^ h * T := Nat.mul_pos (by omega) (by omega) + have hframe := boundary S + rw [← mul_assoc] at hwide + calc + _ ≤ 10000000 * (2 * (2 ^ (h + 1) * T) + 2 * (2 ^ h * T) + 2 * 2 ^ (h + 1) * (W * T + 2 ^ p * T) + + + 2 ^ h * (2 * W + 1) * T + 2 ^ (h + 1 + p) * ((2 + p) ^ 3 * T) + + 2 ^ h * (4 * 2 ^ p) * (2 * T) + + 2 ^ (h + 1) * (T + T + W * T)) := by unfold System.bill; apply Nat.mul_le_mul_left; omega + _ ≤ _ := by unfold factor; ring_nf; omega + +private theorem absorb (K a j : ℕ) : + K * (100 + j) ^ a ≤ (100 + j) ^ (Nat.clog 2 K + a) := by + rw [pow_add] + exact Nat.mul_le_mul_right _ ((Nat.le_pow_clog (by decide : 1 < 2) K).trans + (Nat.pow_le_pow_left (by omega) _)) + +theorem realize (F : Type) [Field F] (p W D : ℕ) : + ∃ E : ℕ, ∀ (h n b j C : ℕ) (S : System F h p W (2 ^ j)), + 1 ≤ b → b ≤ h → n ≤ W * 2 ^ j → S.Correct C → + (∀ i, (Finset.univ.filter (fun k => S.group k = i)).card ≤ 2 ^ (b - 1)) → + Cheap F (h + 1) (h + 1) ((Perm h).pair S.selector) (Controls h p S.config) S.dispatch D → + Weight F S.localWeight (2 ^ j * (100 + j) ^ D) → + ∃ (G : Grid) (m : ℕ), G.g = h + p + 2 - b ∧ G.b = b ∧ G.r = 1 + b + 2 ^ j ∧ + G.Open F h n m (C * W * 2 ^ h) ∧ m ≤ 2 ^ h * ((100 + h) ^ E + 2 ^ j * (100 + j) ^ E) := by + let a := 2 * D + 4 + let K := factor p W + refine ⟨Nat.clog 2 K + a, ?_⟩ + rintro h n b j C S hb hb' hn hcor hgrp ⟨m, hm, hc⟩ hw + obtain ⟨B, hv, hg, hB⟩ := book (z := 2 ^ j) S.group hb hb' hgrp + obtain ⟨t, ht, hopen⟩ := assemble S B hv hn hcor hm hw + refine ⟨B.grid, t, hg, hB, congrArg (fun x => 1 + x + 2 ^ j) hB, hopen, ?_⟩ + let T := (100 + h) ^ a + 2 ^ j * (100 + j) ^ a + have hh : (100 + h) ^ a ≤ T := Nat.le_add_right _ _ + have hj : 2 ^ j * (100 + j) ^ a ≤ T := Nat.le_add_left _ _ + have hd : (100 + (h + 1)) ^ D ≤ T := calc + _ ≤ ((100 + h) ^ 2) ^ D := Nat.pow_le_pow_left (by nlinarith) _ + _ = (100 + h) ^ (2 * D) := (pow_mul ..).symm + _ ≤ _ := (Nat.pow_le_pow_right (by omega) (by omega)).trans hh + have h4 : (100 + h) ^ 4 ≤ T := (Nat.pow_le_pow_right (by omega) (by omega)).trans hh + have hz : 2 ^ j ≤ T := (Nat.le_mul_of_pos_right _ (by positivity)).trans hj + have hr : 2 ^ j * (100 + j) ^ D ≤ T := (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by omega) + (by omega))).trans hj + have hcost := bill_le S B (by omega) (by omega) hn h4 hz hr (hc.trans (Nat.mul_le_mul_left _ hd)) + calc + _ ≤ 2 ^ h * K * T := ht.trans hcost + _ = 2 ^ h * (K * (100 + h) ^ a + 2 ^ j * (K * (100 + j) ^ a)) := by unfold T; ring + _ ≤ _ := Nat.mul_le_mul_left _ (Nat.add_le_add (absorb K a h) + (Nat.mul_le_mul_left _ (absorb K a j))) + +end MatrixMultiplicationAllFields.MatrixExponent.Transport +end + +section +/- +# Scaling the chunk width + +Choose the first height j with W times the dyadic width at least h^A. +The padding costs at most a factor of two. A polynomial in j is +absorbed by any positive power of h at this width. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport +open Filter + +private theorem eventual_exp (E : ℕ) {r : ℝ} (hr : 1 < r) : + ∀ᶠ j : ℕ in atTop, (j : ℝ) ^ E ≤ r ^ j := by + filter_upwards [(tendsto_pow_const_div_const_pow_of_one_lt E hr).eventually + (eventually_lt_nhds (by norm_num : (0 : ℝ) < 1))] with j hj + exact ((div_lt_one (pow_pos (by linarith) j)).mp hj).le + +private theorem polynomial {j E A : ℕ} (hj : 100 ≤ j) (hA : 2 * E ≤ A) : + (100 + j) ^ E ≤ j ^ A := by + calc + _ ≤ (j ^ 2) ^ E := Nat.pow_le_pow_left (by nlinarith) _ + _ = j ^ (2 * E) := (pow_mul ..).symm + _ ≤ j ^ A := Nat.pow_le_pow_right (by omega) hA + +private theorem dyadic {W A : ℕ} (hw : 4 ≤ W) (ha : 2 ≤ A) : + ∀ᶠ h : ℕ in atTop, ∃ j ≤ h, h ^ A ≤ W * 2 ^ j ∧ W * 2 ^ j ≤ 2 * h ^ A ∧ 1 + h ≤ 2 ^ j := by + filter_upwards [eventual_exp A (by norm_num : (1 : ℝ) < 2), eventually_ge_atTop (2 * W)] + with h he hh + have hh' : h ^ A ≤ 2 ^ h := by exact_mod_cast he + have lb : W * (1 + h) ≤ h ^ A := calc + _ ≤ h ^ 2 := by nlinarith + _ ≤ _ := Nat.pow_le_pow_right (by omega) ha + have ub : h ^ A ≤ W * 2 ^ h := hh'.trans (Nat.le_mul_of_pos_left _ (by omega)) + have ex : ∃ j : ℕ, h ^ A ≤ W * 2 ^ j := ⟨h, ub⟩ + have hj := Nat.find_spec ex + refine ⟨Nat.find ex, Nat.find_min' ex ub, hj, ?_, + Nat.le_of_mul_le_mul_left (lb.trans hj) (by omega)⟩ + cases e : Nat.find ex with + | zero => simp only [pow_zero, mul_one]; nlinarith + | succ j => + have small := Nat.find_min ex (show j < Nat.find ex by omega) + rw [pow_succ, ← mul_assoc] + omega + +private theorem scales {W E A : ℕ} (hw : 4 ≤ W) (ha : max 2 (2 * E) ≤ A) + {ζ : ℝ} (hz : 0 < ζ) : + ∀ᶠ h : ℕ in atTop, ∃ j ≤ h, h ^ A ≤ W * 2 ^ j ∧ W * 2 ^ j ≤ 2 * h ^ A ∧ 1 + h ≤ 2 ^ j ∧ + (((100 + h) ^ E + 2 ^ j * (100 + j) ^ E : ℕ) : ℝ) ≤ (h : ℝ) ^ A * (h : ℝ) ^ ζ := by + have ha' : 0 < (A : ℝ) := by exact_mod_cast (show 0 < A by omega) + let r := ζ / A + have hr : 0 < r := div_pos hz ha' + have hex := eventual_exp (2 * E) (Real.one_lt_rpow (by norm_num : (1 : ℝ) < 2) hr) + obtain ⟨n, hn⟩ := eventually_atTop.mp (hex.and (eventually_ge_atTop 100)) + have ht := (tendsto_rpow_atTop hz).comp tendsto_natCast_atTop_atTop + filter_upwards [dyadic hw (le_trans (le_max_left ..) ha), eventually_ge_atTop (2 ^ n), + ht.eventually_ge_atTop 2] with h hh hbig hζ + change 2 ≤ (h : ℝ) ^ ζ at hζ + obtain ⟨j, hj, hl, hu, hlarge⟩ := hh + have hn' : n ≤ j := by + by_contra! h' + have := Nat.pow_le_pow_right (by decide : 0 < 2) h'.le + omega + obtain ⟨hsmall, h100⟩ := hn j hn' + have hhalf : 2 * 2 ^ j ≤ h ^ A := by + have := Nat.mul_le_mul_right (2 ^ j) hw + omega + have hhalf' : 2 * (2 : ℝ) ^ j ≤ (h : ℝ) ^ A := by exact_mod_cast hhalf + have hpay : ((100 + j : ℕ) : ℝ) ^ E ≤ (h : ℝ) ^ ζ := calc + _ ≤ (j : ℝ) ^ (2 * E) := by exact_mod_cast polynomial h100 (le_refl (2 * E)) + _ ≤ ((2 : ℝ) ^ r) ^ j := hsmall + _ = ((2 : ℝ) ^ j) ^ r := by + rw [← Real.rpow_mul_natCast (by norm_num), mul_comm, Real.rpow_natCast_mul (by norm_num)] + _ ≤ ((h : ℝ) ^ A) ^ r := Real.rpow_le_rpow (by positivity) + (by linarith [show 0 < (2 : ℝ) ^ j by positivity]) hr.le + _ = _ := by + rw [← Real.rpow_natCast_mul (by positivity), + show (A : ℝ) * r = ζ from mul_div_cancel₀ _ ha'.ne'] + have hctrl : ((100 + h : ℕ) : ℝ) ^ E ≤ (h : ℝ) ^ A := by + exact_mod_cast polynomial (h100.trans hj) (le_trans (le_max_right ..) ha) + refine ⟨j, hj, hl, hu, hlarge, ?_⟩ + simp only [Nat.cast_add, Nat.cast_pow, Nat.cast_mul, Nat.cast_ofNat] at hpay hctrl ⊢ + nlinarith only [hctrl, mul_le_mul_of_nonneg_left hpay (by positivity : 0 ≤ (2 : ℝ) ^ j), + mul_le_mul_of_nonneg_right hhalf' (by positivity : 0 ≤ (h : ℝ) ^ ζ), + mul_le_mul_of_nonneg_left hζ (by positivity : 0 ≤ (h : ℝ) ^ A)] + +/-- A local protocol yields grouped transports at every sufficiently +large polynomial width. The total active width is uniform in τ. -/ +theorem groups_of_local {F : Type} [Field F] (ht : LocalProtocol F) : + Install.GroupProtocol F := by + obtain ⟨C, hC⟩ := ht + refine ⟨4 * C + 1, by exact_mod_cast (show 1 ≤ 4 * C + 1 by omega), fun τ hτ => ?_⟩ + obtain ⟨p, W, D, hW, hsite⟩ := hC τ hτ + obtain ⟨E, hE⟩ := realize F p W D + have hW' : 0 < (W : ℝ) := by exact_mod_cast (show 0 < W by omega) + refine ⟨(W : ℝ)⁻¹, inv_pos.mpr hW', p + 2, max 2 (2 * E), fun A hA ζ hζ => ?_⟩ + filter_upwards [hsite, scales hW hA hζ] with h hs hj + obtain ⟨b, hpb, hbh, hb, hS⟩ := hs + obtain ⟨j, hjh, hl, hu, he, hcost⟩ := hj + obtain ⟨S, hcor, hgrp, hd, hw⟩ := hS j hjh + obtain ⟨G, m, hg, hb', hr, hopen, hm⟩ := + hE h (h ^ A) b j C S (by omega) hbh hl hcor hgrp hd hw + have hwidth : W * G.r ≤ 4 * h ^ A := calc + _ ≤ W * (2 * 2 ^ j) := Nat.mul_le_mul_left _ (by omega) + _ = 2 * (W * 2 ^ j) := by ring + _ ≤ _ := by omega + refine ⟨G, m, C * W * 2 ^ h, by rwa [hb'], by omega, by omega, ?_, by omega, ?_, ?_, ?_, hopen⟩ + · apply (inv_mul_le_iff₀ hW').mpr + exact_mod_cast hl.trans (Nat.mul_le_mul_left W (show 2 ^ j ≤ G.r by omega)) + · have := Nat.mul_le_mul_right G.r hW + omega + · have hv : C * W * 2 ^ h * G.r ≤ (4 * C + 1) * 2 ^ h * h ^ A := calc + _ = C * 2 ^ h * (W * G.r) := by ring + _ ≤ C * 2 ^ h * (4 * h ^ A) := Nat.mul_le_mul_left _ hwidth + _ ≤ _ := by ring_nf; omega + exact_mod_cast hv + · calc + (m : ℝ) ≤ (2 : ℝ) ^ h * (((100 + h) ^ E + 2 ^ j * (100 + j) ^ E : ℕ) : ℝ) + := by exact_mod_cast hm + _ ≤ (2 : ℝ) ^ h * ((h : ℝ) ^ A * (h : ℝ) ^ ζ) + := mul_le_mul_of_nonneg_left hcost (by positivity) + _ = _ := by ring + +end MatrixMultiplicationAllFields.MatrixExponent.Transport +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transport/System.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transport/System.lean new file mode 100644 index 0000000000..78a3f302a9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transport/System.lean @@ -0,0 +1,120 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.Pad +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Weight + +/-! +# Local realization of a permutation + +An input-dependent controller reads a permutation and an outer +selector. At each site it chooses a local kernel and a configuration +of the incident core slots. Every enabled slot names its opposite end. +A kernel also receives the incoming and outgoing exterior records. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport + +open Coloring + +/-- The quantity computed by `B (h + 1)`. -/ +abbrev Site (h : ℕ) := B (h + 1) +/-- Indexes the port by the coordinates of `Site h × B p`. -/ +abbrev Port (h p : ℕ) := Site h × B p +/-- Indexes the data by the coordinates of `Fin W × Fin z → Bool`. -/ +abbrev Data (W z : ℕ) := Fin W × Fin z → Bool +/-- Indexes the channels by the coordinates of `B p × Fin z → Bool`. -/ +abbrev Channels (p z : ℕ) := B p × Fin z → Bool + +/-- Enable flag, orientation bit, remote site and remote slot. -/ +abbrev Command (h p : ℕ) := Format.pair .bit (.pair .bit (.pair (.addr (h + 1)) (.addr p))) +/-- The bit format for the records and command tables at all control addresses. -/ +abbrev Controls (h p : ℕ) (A : Format) := Format.vec (h + 1) (.pair A (.vec p (Command h p))) +/-- The indexing data represented by `Port h p → (Command h p).obj`. -/ +abbrev Orders (h p : ℕ) := Port h p → (Command h p).obj + +variable {h p W z : ℕ} + +/-- Evaluates `(c i.1).2 i.2` at the input `i`. -/ +def commands {A : Format} (c : (Controls h p A).obj) : Orders h p := fun i => (c i.1).2 i.2 + +/-- The subset of all indices on which the defining predicate holds. -/ +def Enabled (a : Orders h p) : Finset (Port h p) := Finset.univ.filter (fun i => (a i).1) + +/-- The condition `∀ i ∈ Enabled a, let j := (a i).2.2 j ∈ Enabled a ∧ (a j).2.2 = i ∧ (a j).2.1 += !(a i).2.1 ∧ group j = group i` on the specified data. -/ +def Valid (group : Port h p → ℕ) (a : Orders h p) : Prop := + ∀ i ∈ Enabled a, let j := (a i).2.2 + j ∈ Enabled a ∧ (a j).2.2 = i ∧ (a j).2.1 = !(a i).2.1 ∧ group j = group i + +/-- The condition `∀ i ∈ Enabled a, let j := (a i).2.2 ∀ t, c i.1 (i.2, t) = c j.1 (j.2, t)` on +the specified data. -/ +def Joins (a : Orders h p) (c : Site h → Channels p z) : Prop := + ∀ i ∈ Enabled a, let j := (a i).2.2 + ∀ t, c i.1 (i.2, t) = c j.1 (j.2, t) + +/-- Indexes the kernel pins by the coordinates of `A.pins ⊕ (Fin W × Fin z) ⊕ (Fin W × Fin z) ⊕ +(B p × Fin z)`. -/ +abbrev KernelPins (A : Format) (p W z : ℕ) := + A.pins ⊕ (Fin W × Fin z) ⊕ (Fin W × Fin z) ⊕ (B p × Fin z) + +/-- The data for the system construction, including `selector`, `config`, `dispatch`, `group`, +`kernel`. -/ +structure System (F : Type) (h p W z : ℕ) where + /-- The `System` component of type `Format`. -/ + selector : Format + /-- The `System` component of type `Format`. -/ + config : Format + /-- Computes the local controls from the permutation and the selected program data. -/ + dispatch : ((Perm h).pair selector).obj → (Controls h p config).obj + /-- The `System` component of type `Port h p → ℕ`. -/ + group : Port h p → ℕ + /-- The `System` component of type `config.obj → Data W z → Data W z → Channels p z → F`. -/ + kernel : config.obj → Data W z → Data W z → Channels p z → F + +namespace System + +variable {F : Type} [Field F] (S : System F h p W z) + +/-- The local weight of type `F` for the given inputs. -/ +def localWeight (x : KernelPins S.config p W z → Bool) : F := + S.kernel (S.config.code.symm (x ∘ Sum.inl)) (fun i => x (.inr (.inl i))) + (fun i => x (.inr (.inr (.inl i)))) (fun i => x (.inr (.inr (.inr i)))) + +/-- The product of `S.kernel (v i).1 (x i) (y i) (c i)` indexed by `i`. -/ +def value (v : (Controls h p S.config).obj) (x y : Site h → Data W z) + (c : Site h → Channels p z) : F := + ∏ i, S.kernel (v i).1 (x i) (y i) (c i) + +open Classical in +/-- The correct of type `Prop`, constructed using `S.dispatch (σ, S.selector.code.symm t)`. -/ +def Correct (C : ℕ) : Prop := + ∀ (σ : Equiv.Perm (B h)) (x y : Site h → Data W z), + (∀ t c, let v := S.dispatch (σ, t) + S.value v x y c ≠ 0 → Valid S.group (commands v) ∧ (Enabled (commands v)).card + ≤ C * W * 2 ^ h) ∧ + (if ∀ i, x i = y (Routing.inflate h σ i) then (1 : F) else 0) = + ∑ t : S.selector.pins → Bool, ∑ c : Site h → Channels p z, + let v := S.dispatch (σ, S.selector.code.symm t) + S.value v x y c * (if Joins (commands v) c then 1 else 0) + +end System + +/-- Uniform bound on transported width; all control and local kernel +costs may depend on the chosen height ratio. -/ +def LocalProtocol (F : Type) [Field F] : Prop := + ∃ C : ℕ, ∀ τ : ℝ, 0 < τ → ∃ p W D : ℕ, 4 ≤ W ∧ ∀ᶠ h : ℕ in Filter.atTop, + ∃ b : ℕ, p + 22 ≤ b ∧ b ≤ h ∧ (b : ℝ) ≤ τ * h ∧ ∀ j : ℕ, j ≤ h → + ∃ S : System F h p W (2 ^ j), S.Correct C ∧ + (∀ i, (Finset.univ.filter (fun k => S.group k = i)).card ≤ 2 ^ (b - 1)) ∧ + Cheap F (h + 1) (h + 1) ((Perm h).pair S.selector) (Controls h p S.config) S.dispatch D ∧ + Install.Weight F S.localWeight (2 ^ j * (100 + j) ^ D) + +end MatrixMultiplicationAllFields.MatrixExponent.Transport diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transport/Table.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transport/Table.lean new file mode 100644 index 0000000000..abd4f9bde3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Transport/Table.lean @@ -0,0 +1,381 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.ControlWeight +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Protocol.Alignment +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Transport.System +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Tagged.Tags +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coloring.VectorSort +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.SumOut +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Install.Products + +/-! # A finite menu of masked local kernels -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport +open Coloring Protocol Install + +open Classical in +/-- Indexes the profile by the coordinates of `Protocol.Frame F (Fin W ⊕ Fin W) (B p)`. -/ +abbrev Profile (F : Type) (p W : ℕ) := Protocol.Frame F (Fin W ⊕ Fin W) (B p) + +variable {F : Type} {p W : ℕ} + +open Classical in +/-- Computes the apply by the application `f z (Sum.elim (Function.curry x) (Function.curry y)) +(Function.curry c)`. -/ +def Profile.apply (f : Profile F p W) (z : ℕ) (x y : Data W (2 ^ z)) (c : Channels p (2 ^ z)) : F := + f z (Sum.elim (Function.curry x) (Function.curry y)) (Function.curry c) + +variable [Field F] + +open Classical in +/-- Evaluates `if valid = true ∧ ∀ j, active j ≠ true → ∀ i, c j i = false then f z x c else 0` +at the input `z x c`. -/ +def Profile.mask (f : Profile F p W) (valid : Bool) (active : B p → Bool) : Profile F p W := + fun z x c => if valid = true ∧ ∀ j, active j ≠ true → ∀ i, c j i = false then f z x c else 0 + +open Classical in +theorem Profile.mask_fast {f : Profile F p W} (hf : Frame.Fast f) (valid : Bool) (active : B p → + Bool) : + Frame.Fast (f.mask valid active) := by + let k (_ : Fin W ⊕ Fin W → Bool) (c : B p → Bool) : F := + if valid = true ∧ ∀ j, active j ≠ true → c j = false then 1 else 0 + have eq : f.mask valid active = fun z x c => Frame.diagonal k z x c * f z x c := by + funext z x c + simp only [Profile.mask, Frame.diagonal, k, Finset.prod_boole, Finset.mem_univ, forall_const, + ite_mul, one_mul, zero_mul] + congr 1 + exact propext ⟨fun h i => ⟨h.1, fun j hj => h.2 j hj i⟩, + fun h => ⟨(h 0).1, fun j hj i => (h i).2 j hj⟩⟩ + rw [eq] + exact (Frame.fast_diagonal k).mul hf + +open Classical in +private abbrev dataPins (p W z : ℕ) := + (Fin W × Fin (2 ^ z)) ⊕ (Fin W × Fin (2 ^ z)) ⊕ (B p × Fin (2 ^ z)) + +open Classical in +private theorem apply_weight (f : Profile F p W) (z m : ℕ) (hf : Weight F (Frame.weight f z) m) : + Weight F (fun x : dataPins p W z → Bool => f.apply z (x ∘ Sum.inl) + (fun i => x (.inr (.inl i))) (fun i => x (.inr (.inr i)))) m := by + let e : ((Fin W ⊕ Fin W) ⊕ B p) × Fin (2 ^ z) ≃ dataPins p W z := + ((Equiv.sumProdDistrib _ _ _).trans + ((Equiv.sumProdDistrib _ _ _).sumCongr (.refl _))).trans (Equiv.sumAssoc _ _ _) + convert hf.rename e using 1 + funext x + unfold Profile.apply Frame.weight + congr 1 + funext i j + cases i <;> rfl + +open Classical in +private theorem absorb (C z : ℕ) : C * Binary.scale z ≤ 2 ^ z * (100 + z) ^ (C + 3) := by + rw [Binary.scale, mul_left_comm, pow_add] + apply Nat.mul_le_mul_left + exact Nat.mul_le_mul (Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_left (by omega) _)) + (Nat.pow_le_pow_left (by omega) _) + +open Classical in +theorem profile_weight {l : ℕ} (f : B l → Profile F p W) (hf : ∀ i, Frame.Fast (f i)) : + ∃ D : ℕ, ∀ z, Weight F (fun x : KernelPins (.addr l) p W (2 ^ z) → Bool => + (f ((Format.addr l).code.symm (x ∘ Sum.inl))).apply z (fun i => x (.inr (.inl i))) + (fun i => x (.inr (.inr (.inl i)))) (fun i => x (.inr (.inr (.inr i))))) + (2 ^ z * (100 + z) ^ D) := by + choose c hc using hf + let M := Finset.univ.sup c + let C := Weight.switchCost l * (W + W + 2 ^ p + M + 1) + refine ⟨C + 3, fun z => ?_⟩ + let g (y : (Format.addr l).pins → Bool) := f ((Format.addr l).code.symm y) + have hw (y) : Weight F (Frame.weight (g y) z) (M * Binary.scale z) := + (hc _ z).mono (Nat.mul_le_mul_right _ (Finset.le_sup (Finset.mem_univ _))) + have net := Weight.switch _ (fun y => apply_weight (g y) z _ (hw y)) + apply net.mono + refine le_trans ?_ (absorb C z) + have hz : 2 ^ z ≤ Binary.scale z := Nat.le_mul_of_pos_right _ (by positivity) + have pos := Nat.two_pow_pos z + have hd : Fintype.card (dataPins p W z) ≤ (W + W + 2 ^ p) * Binary.scale z := by + simp only [dataPins, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, ← add_mul, + add_assoc] + exact Nat.mul_le_mul_left _ hz + unfold C + rw [show Fintype.card (Format.addr l).pins = l from Format.width_addr l, mul_assoc] + apply Nat.mul_le_mul_left + rw [add_mul, add_mul, one_mul] + omega + +end MatrixMultiplicationAllFields.MatrixExponent.Transport +end + +section +/- # Exterior and summed-over variables of a controlled transport -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport +open Coloring + +/-- The indexing data represented by `⟨I → Bool, I, .refl _⟩`. -/ +abbrev raw (I : Type) [Fintype I] : Format := ⟨I → Bool, I, .refl _⟩ +/-- Indexes the packet by the coordinates of `Format.vec (h + 1) (raw (Fin W × Fin z))`. -/ +abbrev Packet (h W z : ℕ) := Format.vec (h + 1) (raw (Fin W × Fin z)) +/-- Indexes the buffer by the coordinates of `Format.vec (h + 1) (raw (B p × Fin z))`. -/ +abbrev Buffer (h p z : ℕ) := Format.vec (h + 1) (raw (B p × Fin z)) +/-- Computes the input by the application `Tagged.inputs h (word n)`. -/ +abbrev input (h n : ℕ) := Tagged.inputs h (word n) +/-- Computes the exterior by the application `Format.pair .bit (.pair (Perm h) (.pair (Packet h +W z) (Packet h W z)))`. -/ +abbrev Exterior (h W z : ℕ) := + Format.pair .bit (.pair (Perm h) (.pair (Packet h W z) (Packet h W z))) + +variable {F : Type} [Field F] {h n p W z : ℕ} + +open Classical in +/-- The prepared of type `Prop` for the given inputs. -/ +def Prepared (F : Type) [Field F] (f : Val (input h n) → (Exterior h W z).obj) : Prop := + ∀ x, let y := f x + (y.1 = true → Function.Bijective y.2.1) ∧ + Tagged.tag F h (word n) x () = + if y.1 = true ∧ ∀ i, y.2.2.1 i = y.2.2.2 (Routing.inflate h y.2.1 i) then 1 else 0 + +/-- Computes the latent by the application `Format.pair (raw S.selector.pins) (Buffer h p z)`. -/ +abbrev System.latent (S : System F h p W z) := + Format.pair (raw S.selector.pins) (Buffer h p z) + +end MatrixMultiplicationAllFields.MatrixExponent.Transport +end + +section +/- +# Reading a fixed address table at every slot + +The table converts a remote site and slot into its address inside its +transport group. One simultaneous indirect read suffices for each bit. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Install.BNet + +open Coloring + +theorem table (F I K J : Type) [Field F] [Fintype I] [Fintype J] [Fintype K] (n : ℕ) + (hi : Fintype.card I = 2 ^ n) (hk : Fintype.card K = n) + (f : (K → Bool) → J → Bool) : + BNet F (fun (x : I × K → Bool) (z : I × J) => f (fun k => x (z.1, k)) z.2) + (100000 * 2 ^ n * (1 + n) ^ 3 * (1 + Fintype.card J)) := by + classical + let i : B n ≃ I := Fintype.equivOfCardEq (by simp [hi]) + let k : slots (word n) ≃ K := Fintype.equivOfCardEq (by simp [hk]) + let fill (x : I × K → Bool) (z : J × (B n ⊕ (B n × slots (word n)))) := + Sum.elim (fun l => f ((Control.decode n).symm l ∘ k.symm) z.1) + (fun p => x (i p.1, k p.2)) z.2 + have dep : Depends fill 1 := by + rintro ⟨j, l | ⟨l, b⟩⟩ + · exact ⟨∅, by simp, fun _ _ _ => rfl⟩ + · exact ⟨{(i l, k b)}, by simp, fun _ _ e => e _ (by simp)⟩ + let e := (Equiv.prodComm J (B n)).trans (i.prodCongr (.refl J)) + have net := ((dep.bnet F).comp ((Control.read_net F n).copies J)).rename (.refl _) e + convert net.mono (n := 100000 * 2 ^ n * (1 + n) ^ 3 * (1 + Fintype.card J)) (by + simp only [Fintype.card_prod, Fintype.card_sum, Fintype.card_fin, card_slots, wd_word, + hi, hk, localCost] + ring_nf + omega) using 1 + funext x ⟨l, j⟩ + change f (fun t => x (l, t)) j = + f ((Control.decode n).symm (Control.decode n (fun r => x (i (i.symm l), k r))) ∘ k.symm) j + simp [Function.comp_def] + +end MatrixMultiplicationAllFields.MatrixExponent.Install.BNet +end + +section +/- +# Weighted outputs with hidden variables + +Duplicate the exterior and hidden bits for the weight and output +circuits. A trace sums over the hidden bits once. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport + +open Coloring Install + +variable {F : Type} [Field F] {m n : ℕ} + +private theorem free (a : Wire) : Net F .unit a (fun _ _ => 1) (wd a) := by + induction a with + | bit => exact .table _ _ _ (by decide) + | unit => exact .empty + | pair a b ih hj => + change Net F .unit (.pair a b) _ (wd a + wd b) + simpa only [one_mul] using (ih.par hj).pre (Rewire.unit' .unit) + +private theorem project {a b c : Wire} + {f : Val (.pair a b) → F} {g : Val (.pair a b) → Val c} + (hf : Net F (.pair a b) .unit (fun x _ => f x) m) (hg : DNet F (.pair a b) c g n) : + ∃ v ≤ wd a + 2 * wd b + m + n, + Net F a c (fun x y => ∑ z : Val b, if g (x, z) = y then f (x, z) else 0) v := by + obtain ⟨u, hu, H⟩ := DNet.dup F (.pair a b) + obtain ⟨w, hw, G⟩ := hg + have h := (H.comp (G.par hf)).post (.unit' c) + have ht := ((h.par (free (F := F) b)).pre (.unit' _)).trace + refine ⟨u + (w + m) + wd b, by simp only [wd] at hu; omega, ?_⟩ + simpa only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, + mul_one] using ht + +/-- Requires `Weight F (f ∘ A.code.symm) m`. -/ +def Weighted (F : Type) [Field F] (A : Format) (f : A.obj → F) (m : ℕ) : Prop := + Weight F (f ∘ A.code.symm) m + +theorem Weighted.pre {A D : Format} {f : A.obj → D.obj} {g : D.obj → F} + (hg : Weighted F D g n) (hf : Circuit F A D f m) : Weighted F A (g ∘ f) (m + n) := by + simpa only [Weighted, Function.comp_def, Equiv.symm_apply_apply] using BNet.weight hf hg + +private noncomputable def names (I : Type) [Fintype I] : I ≃ slots (word (Fintype.card I)) := + Fintype.equivOfCardEq (by simp) + +open Classical in +theorem emit (G : Grid) {h t s : ℕ} (L : Format) [Fintype L.obj] + {f : Val (input h t) × L.obj → F} {g : Val (input h t) × L.obj → G.Ports → Bool} + (hf : Weighted F (.pair (.wire (input h t)) L) f m) + (hg : Circuit F (.pair (.wire (input h t)) L) (raw G.Ports) g n) + (hv : ∀ x z, f (x, z) ≠ 0 → G.Valid s (g (x, z))) + (he : ∀ x, Tagged.tag F h (word t) x () = ∑ z, f (x, z) * G.close F (g (x, z))) : + ∃ v ≤ wd (input h t) + 2 * L.width + m + n, G.Open F h t v s := by + let a := input h t + let b := word L.width + let c := word (Fintype.card G.Ports) + let i : L.pins ≃ slots b := names L.pins + let j : G.Ports ≃ slots c := names G.Ports + let e : Val b ≃ L.obj := + ((bits b).trans (Equiv.arrowCongr i.symm (.refl _))).trans L.code.symm + let out (x : Val (.pair a b)) := (bits c).symm (g (x.1, e x.2) ∘ j.symm) + have ho (x : Val (.pair a b)) : bits c (out x) ∘ j = g (x.1, e x.2) := by + simp [out, Function.comp_def] + let d := (Equiv.refl (slots a)).sumCongr i + have eqn (x : Val (.pair a b)) : + (Format.pair (.wire a) L).code.symm (bits (.pair a b) x ∘ d) = (x.1, e x.2) := by + apply Prod.ext + · exact (bits a).symm_apply_apply x.1 + · rfl + obtain ⟨u, hu, H⟩ := hf (.pair a b) d + have H' : Net F (.pair a b) .unit (fun x _ => f (x.1, e x.2)) u := by + convert H using 1 + funext x _ + exact congrArg f (eqn x).symm + have V : DNet F (.pair a b) c out n := by + convert hg (.pair a b) c d j using 1 + funext x + change _ = (bits c).symm (g ((Format.pair (.wire a) L).code.symm _) ∘ j.symm) + rw [eqn] + obtain ⟨v, hle, hnet⟩ := project H' V + refine ⟨v, ?_, c, j, _, hnet, ?_, ?_⟩ + · simp only [a, b, wd_word] at hle + omega + · intro x y hy + by_contra ha + apply hy + apply Finset.sum_eq_zero + intro z _ + split + · rename_i hz + by_contra! hn + rw [← hz, ho] at ha + exact ha (hv x _ hn) + · rfl + · intro x + rw [he, ← e.sum_comp] + simp only [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro z _ + simp only [ite_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true, ho] + +end MatrixMultiplicationAllFields.MatrixExponent.Transport +end + +section +/- # Evaluating the controller and the local kernel weights -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Transport.System +open Coloring Install + +variable {F : Type} [Field F] {h p W z n m v : ℕ} (S : System F h p W z) + +/-- The value specified by `(Controls h p S.config).pair (Buffer h p z)`. -/ +abbrev terminals := (Controls h p S.config).pair (Buffer h p z) +/-- The value specified by `(Exterior h W z).pair S.terminals`. -/ +abbrev frame := (Exterior h W z).pair S.terminals +/-- The value specified by `(Format.wire (input h n)).pair S.latent`. -/ +abbrev args (n : ℕ) := (Format.wire (input h n)).pair S.latent + +/-- The value specified by `(prep a.1, S.dispatch ((prep a.1).2.1, S.selector.code.symm a.2.1), +a.2.2)`. -/ +def configure (prep : Val (input h n) → (Exterior h W z).obj) (a : (S.args n).obj) : + S.frame.obj := + (prep a.1, S.dispatch ((prep a.1).2.1, S.selector.code.symm a.2.1), a.2.2) + +/-- Returns `S.value x.2.1 x.1.2.2.1 x.1.2.2.2 x.2.2` when `x.1.1` holds, and `0` otherwise. -/ +def coeff (x : S.frame.obj) : F := + if x.1.1 then S.value x.2.1 x.1.2.2.1 x.1.2.2.2 x.2.2 else 0 + +private abbrev before := (Exterior h W z).pair S.latent +/-- The value specified by `(Perm h).pair S.selector`. -/ +abbrev call := (Perm h).pair S.selector + +theorem configure_net {prep : Val (input h n) → (Exterior h W z).obj} + (hf : Circuit F (.wire (input h n)) (Exterior h W z) prep m) + (hd : Circuit F S.call (Controls h p S.config) S.dispatch v) : + Circuit F (S.args n) S.frame (S.configure prep) + (m + v + 20 * (S.frame.width + S.latent.width + S.call.width)) := by + have init := hf.par (Circuit.id F S.latent) + have get := Circuit.project (F := F) (A := S.before) (D := S.call) + (f := fun x => (x.1.2.1, S.selector.code.symm x.2.1)) + (Sum.elim (fun i => .inl (.inr (.inl i))) (fun j => .inr (.inl j))) (by + rintro x (i | j) + · rfl + · exact congrFun (S.selector.code.apply_symm_apply x.2.1) j) + have left := Circuit.project (F := F) (A := S.before) (D := Exterior h W z) + (f := Prod.fst) Sum.inl (fun _ _ => rfl) + have right := Circuit.project (F := F) (A := S.before) (D := Buffer h p z) + (f := fun x => x.2.2) (fun i => .inr (.inr i)) (fun _ _ => rfl) + apply (init.comp (left.pair ((get.comp hd).pair right))).mono + simp only [Format.width_pair] + omega + +private abbrev Queries := Unit ⊕ (Site h × KernelPins S.config p W z) + +private def source : S.Queries → S.frame.pins + | .inl _ => .inl (.inl ()) + | .inr (i, .inl j) => .inr (.inl (i, .inl j)) + | .inr (i, .inr (.inl j)) => .inl (.inr (.inr (.inl (i, j)))) + | .inr (i, .inr (.inr (.inl j))) => .inl (.inr (.inr (.inr (i, j)))) + | .inr (i, .inr (.inr (.inr j))) => .inr (.inr (i, j)) + +omit [Field F] in +private theorem queries_le : Fintype.card S.Queries ≤ S.frame.width := by + simp only [Queries, KernelPins, Format.width, Fintype.card_sum, Fintype.card_prod, + Fintype.card_unit, Fintype.card_fin] + ring_nf + omega + +theorem coeff_net (hS : Weight F S.localWeight m) : + Weighted F S.frame S.coeff (3 * S.frame.width + 16 + 2 ^ (h + 1) * m) := by + have flag := Weight.dense F Unit (fun x => if x () then 1 else 0) + have net := (flag.parallel (hS.prod (h + 1))).pull S.source + have hw : S.frame.width + 2 * Fintype.card S.Queries + (8 * 2 ^ 1 + 2 ^ (h + 1) * m) ≤ + 3 * S.frame.width + 16 + 2 ^ (h + 1) * m := by + have := S.queries_le + omega + unfold Weighted + convert net.mono hw using 1 + funext x + simp only [ite_mul, one_mul, zero_mul, Function.comp_apply] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Transport.System +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/ChargedSeparation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/ChargedSeparation.lean new file mode 100644 index 0000000000..b907b0acfc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/ChargedSeparation.lean @@ -0,0 +1,57 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Degeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Separation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialCharacterBounds + +/-! +# The charged separation inequality for actual characters + +The output is evaluated using full direct-sum additivity. Exactly `5*M` +source copies are paid for, and the auxiliary dot product is retained. In +the equal-value case the number of output blocks cancels the factor `M` in +that source cost, but never the auxiliary dot-product factor. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +theorem Character.charged_separation (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {M : ℕ} (hM : 0 < M) (A : Fin M → Tensor Coeff X Y Z) : + (∑ h, f (ofTensor (A h))) * + f (ofTensor (Separation.dotPairingX (Fin M))) ≤ + (5 * M : ℝ≥0) * f (ofTensor (Separation.shared A)) := by + obtain ⟨P, hconstant, hdegree, heval⟩ := Separation.finite_charged_separation hM A + have h := f.polynomial_constant_le + (Tensor.directSum (fun _ : Fin (5 * M) => Separation.shared A)) + (Separation.separated A) P ((M - 1) ^ 2) hconstant hdegree heval + exact TensorSpectrum.TensorClass.Character.charged_separation f 5 A h + +/-- The block count pays the growing part of the separation cost. The +remaining factor five is fixed, and is removed only in a later power limit. -/ +theorem Character.charged_separation_equal (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {M : ℕ} (hM : 0 < M) (A : Fin M → Tensor Coeff X Y Z) + (c : ℝ≥0) (hvalue : ∀ h, f (ofTensor (A h)) = c) : + c * f (ofTensor (Separation.dotPairingX (Fin M))) ≤ + 5 * f (ofTensor (Separation.shared A)) := + TensorSpectrum.TensorClass.Character.charged_separation_equal f 5 hM A c hvalue + (f.charged_separation hM A) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Degeneration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Degeneration.lean new file mode 100644 index 0000000000..782260eaa7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Degeneration.lean @@ -0,0 +1,62 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Powers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.SeparationInterpolation +public import Mathlib.Algebra.Order.Archimedean.Basic +public import Mathlib.Algebra.Order.Ring.Pow +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Positivity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterDegeneration + +/-! +# Characters and polynomial degenerations + +Restriction monotonicity suffices for a polynomial degeneration. For each +fixed family, interpolation of its tensor powers costs only linearly many +copies. The elementary estimate below removes that overhead without any +assumed continuity of the character. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum (le_of_pow_le_linear_mul_pow) + +namespace TensorClass + +/-- Every normalized restriction-monotone character is monotone on the +constant coefficient of an actual bounded polynomial restriction family. +The degree is fixed before the tensor-power argument is applied. -/ +theorem Character.polynomial_constant_le (f : Character) + {X Y Z U V W : Type*} + [Fintype X] [Fintype Y] [Fintype Z] + [Fintype U] [Fintype V] [Fintype W] + (T : Tensor Coeff X Y Z) (D : Tensor Coeff U V W) + (P : Tensor (Polynomial Coeff) U V W) (K : ℕ) + (hconstant : ∀ u v w, (P u v w).coeff 0 = D u v w) + (hdegree : ∀ u v w, (P u v w).degree ≤ K) + (heval : ∀ t : Coeff, t ≠ 0 → + (fun u v w => (P u v w).eval t) ∈ LocalTensor.orbit T) : + f (ofTensor D) ≤ f (ofTensor T) := + TensorSpectrum.TensorClass.Character.polynomial_constant_le f T D K + (Separation.polynomial_power_mem_restrictionOrbit T D P K hconstant hdegree heval) + +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/DirectSum.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/DirectSum.lean new file mode 100644 index 0000000000..8558936132 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/DirectSum.lean @@ -0,0 +1,39 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Powers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDirectSum + +/-! +# Character values of full direct sums + +Every summand has independent coordinates on all three legs. This file does +not apply additivity to a tensor whose first leg is shared. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass (ofTensor_directSum_fin) + +theorem Character.map_directSum_fin (f : Character) {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (n : ℕ) + (A : Fin n → Tensor Coeff X Y Z) : + f (ofTensor (Tensor.directSum A)) = ∑ i, f (ofTensor (A i)) := + TensorSpectrum.TensorClass.Character.map_directSum_fin f n A + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Dots.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Dots.lean new file mode 100644 index 0000000000..4993cc73c6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Dots.lean @@ -0,0 +1,81 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.RankOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDots + +/-! +# The three auxiliary pairings as actual tensor classes + +The singleton leg is named in each pairing. Dimension comparisons select +coordinates, multiplication pairs coordinates, and the product of the three +orientations is the square matrix multiplication tensor. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper +namespace CoefficientTensor + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (dotUnitProduct dotTripleX dotTripleY dotTripleZ) + +/-- The specialization of `dotXCoeff` to these coefficients. -/ +abbrev dotXCoeff := + MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.dotXCoeff (K := Coeff) + +end CoefficientTensor + +namespace TensorClass + +/-- The specialization of `dotX` to these coefficients. -/ +abbrev dotX := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.dotX (K := Coeff) + +/-- The specialization of `dotY` to these coefficients. -/ +abbrev dotY := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.dotY (K := Coeff) + +/-- The specialization of `dotZ` to these coefficients. -/ +abbrev dotZ := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.dotZ (K := Coeff) + +theorem dotX_mul (m n : ℕ) : dotX m * dotX n = dotX (m * n) := + TensorSpectrum.TensorClass.dotX_mul m n + +theorem dotY_mul (m n : ℕ) : dotY m * dotY n = dotY (m * n) := + TensorSpectrum.TensorClass.dotY_mul m n + +theorem dotZ_mul (m n : ℕ) : dotZ m * dotZ n = dotZ (m * n) := + TensorSpectrum.TensorClass.dotZ_mul m n + +namespace Character + +/-- The specialization of `dotXValue` to this coefficient ring. -/ +abbrev dotXValue (f : Character) (n : ℕ) : ℝ := + TensorSpectrum.TensorClass.Character.dotXValue f n + +/-- The specialization of `dotYValue` to this coefficient ring. -/ +abbrev dotYValue (f : Character) (n : ℕ) : ℝ := + TensorSpectrum.TensorClass.Character.dotYValue f n + +/-- The specialization of `dotZValue` to this coefficient ring. -/ +abbrev dotZValue (f : Character) (n : ℕ) : ℝ := + TensorSpectrum.TensorClass.Character.dotZValue f n + +end Character +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/DotsPower.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/DotsPower.lean new file mode 100644 index 0000000000..cff973bdf0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/DotsPower.lean @@ -0,0 +1,60 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Dots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPowers + +/-! +# Character exponents of the auxiliary pairings + +The power laws follow from the actual coordinate restrictions and product +identities. Their exponents are constructed here, rather than supplied as +assumptions about a character. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass.Character + +/-- The specialization of `pX` to this coefficient ring. -/ +abbrev pX (f : Character) : ℝ := + TensorSpectrum.TensorClass.Character.pX f + +/-- The specialization of `pY` to this coefficient ring. -/ +abbrev pY (f : Character) : ℝ := + TensorSpectrum.TensorClass.Character.pY f + +/-- The specialization of `pZ` to this coefficient ring. -/ +abbrev pZ (f : Character) : ℝ := + TensorSpectrum.TensorClass.Character.pZ f + +theorem pX_nonneg (f : Character) : 0 ≤ f.pX := + TensorSpectrum.TensorClass.Character.pX_nonneg f + +theorem pY_nonneg (f : Character) : 0 ≤ f.pY := + TensorSpectrum.TensorClass.Character.pY_nonneg f + +theorem pZ_nonneg (f : Character) : 0 ≤ f.pZ := + TensorSpectrum.TensorClass.Character.pZ_nonneg f + +theorem pX_le_one (f : Character) : f.pX ≤ 1 := + TensorSpectrum.TensorClass.Character.pX_le_one f + +theorem pY_le_one (f : Character) : f.pY ≤ 1 := + TensorSpectrum.TensorClass.Character.pY_le_one f + +theorem pZ_le_one (f : Character) : f.pZ ≤ 1 := + TensorSpectrum.TensorClass.Character.pZ_le_one f + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass.Character diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/PermutationPowers.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/PermutationPowers.lean new file mode 100644 index 0000000000..090779a586 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/PermutationPowers.lean @@ -0,0 +1,41 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Permutations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.DotsPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPermutationPowers + +/-! +# The exponents of the six permuted characters + +The exponent identities below follow from evaluating the actual pairings at +dimension two. In particular, they do not depend on how the power-law witnesses +were chosen. Polynomial multiplication with one scalar input is identified +with the corresponding actual pairing by explicit coordinate equivalences. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +namespace Character + +theorem permuted_pX (f : Character) (i : Fin 6) : + (f.permuted i).pX = ![f.pX, f.pY, f.pX, f.pY, f.pZ, f.pZ] i := + TensorSpectrum.TensorClass.Character.permuted_pX f i + +end Character +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Permutations.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Permutations.lean new file mode 100644 index 0000000000..910a538c7e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Permutations.lean @@ -0,0 +1,81 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Dots +public import Mathlib.Data.Fin.VecNotation +public import Mathlib.Data.Multiset.AddSub +public import Mathlib.Tactic.FinCases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPermutations + +/-! +# Permuting the three actual tensor legs + +The two adjacent swaps act on coefficient arrays and on their actual local +restriction witnesses. Their quotient actions preserve the semiring operations. +The six induced characters therefore remain normalized restriction-monotone +characters; their six values form a multiset invariant under either swap. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper +namespace CoefficientTensor + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (swapXY swapYZ swapXY_blockSum swapYZ_blockSum swapXY_product swapYZ_product) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.Restricts + (swapXY swapYZ) + +end Restricts +end CoefficientTensor + +namespace TensorRep + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep + (swapXY swapYZ) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.Restricts + (swapXY swapYZ) + +end Restricts +end TensorRep + +namespace TensorClass + +/-- The specialization of `swapYZ` to these coefficients. -/ +abbrev swapYZ := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.swapYZ (K := Coeff) + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (swapXY_ofTensor swapYZ_ofTensor swapXY_swapXY swapYZ_swapYZ swap_braid swapXY_add swapYZ_add + swapXY_mul swapYZ_mul permuteSwapXY permuteSwapYZ permute_swapXY permute_swapYZ) + +namespace Character + +/-- The specialization of `permuted` to this coefficient ring. -/ +abbrev permuted (f : Character) (i : Fin 6) : Character := + TensorSpectrum.TensorClass.Character.permuted f i + +end Character +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/PolynomialDegeneration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/PolynomialDegeneration.lean new file mode 100644 index 0000000000..52b5b5ab40 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/PolynomialDegeneration.lean @@ -0,0 +1,51 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.Degeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.DotsPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialFiltrationFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialSectorFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialCharacterBounds + +/-! +# Character bounds from the two explicit polynomial families + +Both inequalities use the actual finite-degree restriction witnesses. In +the determinant case the two-dimensional pairing is explicitly charged. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +theorem binaryDotTensor_class : ofTensor binaryDotTensor = dotX 2 := + TensorSpectrum.TensorClass.binaryDotTensor_class (K := Coeff) + +theorem Character.determinant_graded_le (f : Character) (a b : ℕ) : + (f (ofTensor (determinantGradedTensor a b)) : ℝ) ≤ + (2 : ℝ) ^ f.pX * (f (ofTensor (polynomialTensor (a + 1) (b + 2))) : ℝ) := + TensorSpectrum.TensorClass.Character.determinant_graded_le_of_evaluation f + (node := fun t : Coeff => t ≠ 0) f.polynomial_constant_le a b + (fun _ ht => determinantPolynomialFamily_eval_mem_restrictionOrbit a b ht) + +theorem Character.tripling_graded_le (f : Character) (a h : ℕ) + (ha : 1 ≤ a) (hh : 1 ≤ h) : + (f (ofTensor (triplingSectorTensor a h)) : ℝ) ≤ + (f (ofTensor (polynomialTensor a (3 * h + a - 1))) : ℝ) := + TensorSpectrum.TensorClass.Character.tripling_graded_le_of_evaluation f + (node := fun t : Coeff => t ≠ 0) f.polynomial_constant_le a h ha hh + (fun _ ht => triplingPolynomialFamily_eval_mem_restrictionOrbit a h ha hh ht) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/PolynomialValues.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/PolynomialValues.lean new file mode 100644 index 0000000000..40e673580c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/PolynomialValues.lean @@ -0,0 +1,45 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.TagFinite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterDegeneration + +/-! +# Positivity and rank bounds for polynomial character values + +The constant input monomials witness nonvanishing. The upper bound uses the +actual evaluation/interpolation rank decomposition of ordinary convolution. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +namespace TensorClass + +theorem Character.polynomial_value_pos (f : Character) (a b : ℕ) + (ha : 1 ≤ a) (hb : 1 ≤ b) : + 0 < (f (ofTensor (polynomialTensor a b)) : ℝ) := + TensorSpectrum.TensorClass.Character.polynomial_value_pos f a b ha hb + +theorem Character.polynomial_value_le (f : Character) (a b : ℕ) + (ha : 1 ≤ a) (hb : 1 ≤ b) : + (f (ofTensor (polynomialTensor a b)) : ℝ) ≤ (a : ℝ) + (b : ℝ) - 1 := + TensorSpectrum.TensorClass.Character.polynomial_value_le_of_rankAtMost + f a b ha hb (polynomialTensor_rankAtMost a b) + +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Tag.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Tag.lean new file mode 100644 index 0000000000..f15daa177a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/Tag.lean @@ -0,0 +1,82 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.TagFinite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagOptimized +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagEntropy + +/-! +# Optimized tagging for actual tensor characters + +The finite count-fiber premise is discharged by the actual tensor restriction +and charged separation construction. Only then is the polynomial number of +fibers removed. No multinomial asymptotics or uncharged auxiliary tensor is +used. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +theorem Character.shared_tag_optimized_of_pos (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s : ℕ} (hs : 0 < s) (A : Fin s → Tensor Coeff X Y Z) + (hA : ∀ i, 0 < (f (ofTensor (A i)) : ℝ)) (hp : 0 < f.pX) : + (∑ i, (f (ofTensor (A i)) : ℝ) ^ (1 / f.pX)) ^ f.pX ≤ + (f (ofTensor (Separation.shared A)) : ℝ) := by + apply TensorSpectrum.tag_optimized_of_fiber_bounds 5 (by norm_num) hs f.pX hp + (fun i => (f (ofTensor (A i)) : ℝ)) hA + (f (ofTensor (Separation.shared A)) : ℝ) + (f (ofTensor (Separation.shared A))).coe_nonneg + intro N hN c hc + exact f.tag_count_fiber A c hc + +theorem Character.shared_tag_optimized (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s : ℕ} (hs : 0 < s) (A : Fin s → Tensor Coeff X Y Z) + (hA : ∀ i, A i ≠ 0) (hp : 0 < f.pX) : + (∑ i, (f (ofTensor (A i)) : ℝ) ^ (1 / f.pX)) ^ f.pX ≤ + (f (ofTensor (Separation.shared A)) : ℝ) := by + apply f.shared_tag_optimized_of_pos hs A (fun i => ?_) hp + have h := f.one_le_of_tensor_ne_zero (A i) (hA i) + have hr : (1 : ℝ) ≤ f (ofTensor (A i)) := by exact_mod_cast h + linarith + +/-- The full tag inequality, including zero probabilities and a vanishing +dot-product exponent. The two limiting steps have already been completed in +the polynomial degeneration and finite-word proofs, respectively. -/ +theorem Character.shared_tag_entropy (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s : ℕ} (hs : 0 < s) (A : Fin s → Tensor Coeff X Y Z) + (hA : ∀ i, 0 < (f (ofTensor (A i)) : ℝ)) + (q : Fin s → ℝ) (hq : ∀ i, 0 ≤ q i) (hqsum : ∑ i, q i = 1) : + Real.exp (f.pX * (-(∑ i, q i * Real.log (q i)))) * + (∏ i, (f (ofTensor (A i)) : ℝ) ^ q i) ≤ + (f (ofTensor (Separation.shared A)) : ℝ) := by + by_cases hp : f.pX = 0 + · rw [hp] + apply TensorSpectrum.tag_entropy_exp_zero_le + (fun i => (f (ofTensor (A i)) : ℝ)) q + (f (ofTensor (Separation.shared A)) : ℝ) hA hq hqsum + intro i + exact_mod_cast f.shared_branch_le A i + · have hp' : 0 < f.pX := lt_of_le_of_ne f.pX_nonneg (Ne.symm hp) + exact TensorSpectrum.tag_entropy_exp_le_of_bound f.pX + (f (ofTensor (Separation.shared A)) : ℝ) + (fun i => (f (ofTensor (A i)) : ℝ)) q hp' hA hq hqsum + (f.shared_tag_optimized_of_pos hs A hA hp') + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/TagFinite.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/TagFinite.lean new file mode 100644 index 0000000000..57d20036a7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Character/TagFinite.lean @@ -0,0 +1,66 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.ChargedSeparation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Character.DotsPower +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagFiberBounds + +/-! +# The exact finite-word character inequality + +Every count fiber is selected by actual local coordinate maps from a tensor +power of the original shared-input tensor. Charged separation is then applied +to that finite fiber. This is the tensor input to the later scalar limit; +neither the separation nor the word restriction is an assumption here. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +theorem Character.shared_branch_le (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s : ℕ} (A : Fin s → Tensor Coeff X Y Z) (i : Fin s) : + f (ofTensor (A i)) ≤ f (ofTensor (Separation.shared A)) := by + exact TensorSpectrum.TensorClass.Character.shared_branch_le f A i + +theorem Character.one_le_of_tensor_ne_zero (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor Coeff X Y Z) (hT : T ≠ 0) : 1 ≤ f (ofTensor T) := by + have h := f.monotone' (ofTensor_le + (CoefficientTensor.nonzero_restricts_natTensor_one hT)) + have hunit : ofTensor (CoefficientTensor.natTensor 1) = (1 : TensorClass) := by + simpa only [Nat.cast_one] using (natCast_eq_ofTensor_natTensor 1).symm + calc + 1 = f.toHom (ofTensor (CoefficientTensor.natTensor 1)) := by + rw [hunit] + exact f.toHom.map_one.symm + _ ≤ f.toHom (ofTensor T) := h + +/-- The original word-fiber cost, including the fixed factor five. The +polynomial number of possible count vectors has not yet been removed. -/ +theorem Character.tag_count_fiber (f : Character) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s N : ℕ} (A : Fin s → Tensor Coeff X Y Z) + (c : TagWords.CountVector s N) (hc : 0 < (TagWords.fiber c).card) : + ((TagWords.fiber c).card : ℝ) ^ f.pX * + TagWords.countWeight (fun i => (f (ofTensor (A i)) : ℝ)) c ≤ + 5 * (f (ofTensor (Separation.shared A)) : ℝ) ^ N := by + apply TensorSpectrum.TensorClass.Character.tag_count_fiber f A c hc 5 + intro M hM B C hvalue + exact f.charged_separation_equal hM B C hvalue + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialDegeneration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialDegeneration.lean new file mode 100644 index 0000000000..c41a165689 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialDegeneration.lean @@ -0,0 +1,48 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.WeightedPolynomials + +/-! +# Diagonal weight degenerations + +The terms of weight zero form the limiting tensor. Positive weights +contribute higher polynomial coefficients, and negative weights occur +only at zero entries. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (weightedLimit weightedFamily weightedFamily_zero restrict_diagonal) + +variable {X Y Z : Type*} + +/-- At every nonzero parameter, the family is witnessed by actual +local substitutions: the diagonal entries are the respective integer powers. -/ +theorem weightedFamily_mem_restrictionOrbit + [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor Coeff X Y Z) (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) + (h : ∀ x y z, T x y z ≠ 0 → 0 ≤ wx x + wy y + wz z) + {t : Coeff} (ht : t ≠ 0) : + weightedFamily T wx wy wz t ∈ LocalTensor.orbit T := + TensorSpectrum.PolynomialTensors.weightedFamily_mem_restrictionOrbit T wx wy wz h t + (fun n => t ^ n) (fun i j => zpow_add₀ ht i j) (fun n => zpow_natCast t n) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialFiltration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialFiltration.lean new file mode 100644 index 0000000000..1d23a12e25 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialFiltration.lean @@ -0,0 +1,76 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialFiltration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialDegeneration +public import Lean.Elab.Tactic.Omega + +/-! +# The explicit determinant filtration + +We use positive dimensions `a+1` and `b+2`. The two old copies are the +coefficients of `s` and `w`. The new coordinates are quotient lifts `Q` and +kernel elements `K = W_j - S_(j+1)`. The first input is unchanged throughout. +All statements below are coefficient identities over the coefficient field. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent + +noncomputable section +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (doubleIndexEquiv doubleOutputEquiv determinant_basis_change + determinantGraded_quotient determinantGraded_kernel determinantGraded_quotient_kernel + determinantGraded_kernel_quotient determinantInputWeight determinantOutputWeight + determinant_supported_weight determinant_weightedLimit) + +/-- The shared delta construction over the coefficient ring. -/ +abbrev delta {ι : Type*} [DecidableEq ι] (i j : ι) := + TensorSpectrum.PolynomialTensors.delta (K := Coeff) i j + +/-- The shared doubledPolynomialTensor construction over the coefficient ring. -/ +abbrev doubledPolynomialTensor := + TensorSpectrum.PolynomialTensors.doubledPolynomialTensor (K := Coeff) + +/-- The shared binaryDotTensor construction over the coefficient ring. -/ +abbrev binaryDotTensor := + TensorSpectrum.PolynomialTensors.binaryDotTensor (K := Coeff) + +/-- The shared determinantInputMap construction over the coefficient ring. -/ +abbrev determinantInputMap := + TensorSpectrum.PolynomialTensors.determinantInputMap (K := Coeff) + +/-- The shared determinantOutputMap construction over the coefficient ring. -/ +abbrev determinantOutputMap := + TensorSpectrum.PolynomialTensors.determinantOutputMap (K := Coeff) + +/-- The shared determinantAdaptedTensor construction over the coefficient ring. -/ +abbrev determinantAdaptedTensor := + TensorSpectrum.PolynomialTensors.determinantAdaptedTensor (K := Coeff) + +/-- The shared determinantGradedTensor construction over the coefficient ring. -/ +abbrev determinantGradedTensor := + TensorSpectrum.PolynomialTensors.determinantGradedTensor (K := Coeff) + +/-- Relabeling gives two copies of convolution with the first input shared. -/ +theorem doubledPolynomialTensor_product (a b : ℕ) : + Tensor.pullback (fun i => (i, ())) (doubleIndexEquiv (b + 2)) + (doubleOutputEquiv a b) + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) = + doubledPolynomialTensor a b := + TensorSpectrum.PolynomialTensors.doubledPolynomialTensor_product (K := Coeff) a b + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialFiltrationFamily.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialFiltrationFamily.lean new file mode 100644 index 0000000000..6e5cbcde4d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialFiltrationFamily.lean @@ -0,0 +1,63 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialFiltration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialWeightFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialFiltrationFamily + +/-! +# The finite-degree determinant family + +The constant coefficient is the two-branch graded tensor. Every nonzero +evaluation is an actual restriction of the original convolution tensor times +the two-dimensional pairing. These explicit data, rather than continuity of +an arbitrary tensor character, are the inputs to finite interpolation. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +theorem determinantAdapted_mem_restrictionOrbit (a b : ℕ) : + determinantAdaptedTensor a b ∈ LocalTensor.orbit + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) := + TensorSpectrum.PolynomialTensors.determinantAdapted_mem_restrictionOrbit a b + +/-- The determinant polynomial family over the coefficient ring. -/ +abbrev determinantPolynomialFamily := + TensorSpectrum.PolynomialTensors.determinantPolynomialFamily (K := Coeff) + +theorem determinantPolynomialFamily_coeff_zero (a b : ℕ) : + (fun i y z => (determinantPolynomialFamily a b i y z).coeff 0) = + determinantGradedTensor a b := + TensorSpectrum.PolynomialTensors.determinantPolynomialFamily_coeff_zero a b + +theorem determinantPolynomialFamily_degree_le (a b : ℕ) + (i : Fin (a + 1)) (y : Fin (b + 3) ⊕ Fin (b + 1)) + (z : Fin (a + b + 3) ⊕ Fin (a + b + 1)) : + (determinantPolynomialFamily a b i y z).degree ≤ (1 : ℕ) := + TensorSpectrum.PolynomialTensors.determinantPolynomialFamily_degree_le a b i y z + +theorem determinantPolynomialFamily_eval_mem_restrictionOrbit (a b : ℕ) + {t : Coeff} (ht : t ≠ 0) : + (fun i y z => (determinantPolynomialFamily a b i y z).eval t) ∈ + LocalTensor.orbit + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) := + TensorSpectrum.PolynomialTensors.determinantPolynomialFamily_eval_mem_restrictionOrbit a b t + (weightedPolynomial_eval_mem_restrictionOrbit + (determinantAdaptedTensor a b) (fun _ => 0) + (determinantInputWeight b) (determinantOutputWeight a b) + (determinant_supported_weight a b) ht) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialSectorFamily.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialSectorFamily.lean new file mode 100644 index 0000000000..38981f062f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialSectorFamily.lean @@ -0,0 +1,59 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialSectors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialWeightFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialSectorFamily + +/-! +# The polynomial witness for the three-sector degeneration + +Every coefficient has degree at most one. Its constant coefficient is the +entire shared-first-input sector assembly. At each nonzero parameter the +evaluated tensor is an actual restriction of the original polynomial tensor. +These explicit facts support interpolation without assuming that an arbitrary +tensor character preserves topological limits. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +/-- The tripling polynomial family over the coefficient ring. -/ +abbrev triplingPolynomialFamily := + TensorSpectrum.PolynomialTensors.triplingPolynomialFamily (K := Coeff) + +theorem triplingPolynomialFamily_coeff_zero (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (x : Fin a) (y : TriplingY a h) (z : TriplingZ a h) : + (triplingPolynomialFamily a h ha hh x y z).coeff 0 = triplingSectorTensor a h x y z := + TensorSpectrum.PolynomialTensors.triplingPolynomialFamily_coeff_zero a h ha hh x y z + +theorem triplingPolynomialFamily_degree_le (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (x : Fin a) (y : TriplingY a h) (z : TriplingZ a h) : + (triplingPolynomialFamily a h ha hh x y z).degree ≤ (1 : ℕ) := + TensorSpectrum.PolynomialTensors.triplingPolynomialFamily_degree_le a h ha hh x y z + +/-- Every nonzero evaluation is an exact restriction of the original source +tensor. The sector reindexing is one fixed pair of local maps, with identity +on the common first input, after the diagonal maps. -/ +theorem triplingPolynomialFamily_eval_mem_restrictionOrbit + (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) {t : Coeff} (ht : t ≠ 0) : + (fun x y z => (triplingPolynomialFamily a h ha hh x y z).eval t) ∈ + LocalTensor.orbit (polynomialTensor a (triplingWidth a h)) := + TensorSpectrum.PolynomialTensors.triplingPolynomialFamily_eval_mem_restrictionOrbit a h ha hh t + (weightedPolynomial_eval_mem_restrictionOrbit _ _ _ _ + (TensorSpectrum.PolynomialTensors.tripling_source_weights_nonneg a h ha) ht) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialSectors.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialSectors.lean new file mode 100644 index 0000000000..110c37e12c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialSectors.lean @@ -0,0 +1,54 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialSectors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialDegeneration +public import Lean.Elab.Tactic.Omega + +/-! +# The three-sector polynomial degeneration + +The coefficient identities describe three sectors. The first input has +weight zero throughout the degeneration. Only when identifying the individual +middle branch do we reverse its first index; its other two indices are swapped. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (triplingWidth triplingYWeight triplingZWeight triplingMatched tripling_support_left + tripling_support_right tripling_support_middle tripling_weight_nonneg + tripling_weight_zero_iff tripling_weight_one_iff triplingGraded_of_weights + triplingGraded_coefficient triplingLeftY triplingLeftZ triplingMiddleY triplingMiddleZ + triplingRightY triplingRightZ triplingReverse triplingReverse_involutive + tripling_left_weights tripling_middle_weights tripling_right_weights + tripling_left_coefficient tripling_right_coefficient tripling_middle_coefficient + tripling_second_sectors_disjoint tripling_output_sectors_disjoint TriplingY TriplingZ + triplingYMap triplingZMap triplingYMap_injective triplingZMap_injective + triplingYMap_surjective triplingZMap_surjective triplingYEquiv triplingZEquiv + triplingGraded_sector_assembly) + +/-- The shared triplingGraded construction over the coefficient ring. -/ +abbrev triplingGraded := + MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors.triplingGraded (K := Coeff) + +/-- The shared triplingSectorTensor construction over the coefficient ring. -/ +abbrev triplingSectorTensor := + MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors.triplingSectorTensor (K := Coeff) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialTensor.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialTensor.lean new file mode 100644 index 0000000000..53254ed380 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialTensor.lean @@ -0,0 +1,52 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Polynomial.ComplexPolynomialApproximation +public import Lean.Elab.Tactic.Omega +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialRank + +/-! +# The polynomial multiplication tensor + +The coefficient tensor records ordinary, untruncated polynomial multiplication. +Evaluation at `a + b - 1` distinct field elements and uniform Lagrange +interpolation give an actual rank decomposition of that size. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (polynomialTensor_apply polynomialTensor_eq_coeff polynomialTensor_swap + polynomialTensor_one_left) + +/-- The shared polynomialTensor construction over the coefficient ring. -/ +abbrev polynomialTensor := + MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors.polynomialTensor (K := Coeff) + +/-- Ordinary polynomial multiplication has an actual decomposition into +`a + b - 1` rank-one tensors. The degenerate empty-input cases are included. -/ +theorem polynomialTensor_rankAtMost (a b : ℕ) : + Tensor.RankAtMost (polynomialTensor a b) (a + b - 1) := by + classical + obtain ⟨nodes, hnodes, _⟩ := exists_nonzero_nodes (F := Coeff) (a + b - 1) + exact TensorSpectrum.PolynomialTensors.polynomialTensor_rankAtMost_of_interpolation a b nodes + (fun t d => (Lagrange.basis Finset.univ nodes t).coeff d) + (Tensor.coeff_eq_sum_eval nodes hnodes) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialWeightFamily.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialWeightFamily.lean new file mode 100644 index 0000000000..78669e8a9c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/PolynomialWeightFamily.lean @@ -0,0 +1,54 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialDegeneration +public import Mathlib.Algebra.Polynomial.Degree.Defs +public import Mathlib.Algebra.Polynomial.Eval.Coeff +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.WeightedPolynomials + +/-! +# Explicit polynomial families for diagonal weight degenerations + +The diagonal degeneration has a polynomial coefficient family, not merely a +topological limit. Its constant coefficient is the retained tensor. Its degree +is controlled by the supported total weights. At every nonzero parameter its +evaluation is an exact restriction of the source tensor. These are the inputs +needed to extract tensor powers by finite interpolation. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +variable {X Y Z : Type*} + +export MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + (weightedPolynomial weightedPolynomial_eval weightedPolynomial_coeff_zero + weightedPolynomial_natDegree_le weightedPolynomial_degree_le + weightedPolynomial_degree_le_one) + +/-- Every nonzero evaluation has actual diagonal local restriction witnesses; +the polynomial family does not assume a character or a continuity principle. -/ +theorem weightedPolynomial_eval_mem_restrictionOrbit + [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor Coeff X Y Z) (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) + (h : ∀ x y z, T x y z ≠ 0 → 0 ≤ wx x + wy y + wz z) + {t : Coeff} (ht : t ≠ 0) : + (fun x y z => (weightedPolynomial T wx wy wz x y z).eval t) ∈ + LocalTensor.orbit T := by + rw [weightedPolynomial_eval] + exact weightedFamily_mem_restrictionOrbit T wx wy wz h ht + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Separation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Separation.lean new file mode 100644 index 0000000000..d7f73a6ca7 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Separation.lean @@ -0,0 +1,141 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationWeights +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Fourier +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Polynomial.ComplexPolynomialApproximation +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Blocks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationPolynomial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationFourier + +/-! +# Charged finite separation by local Fourier maps + +The source is exactly `5 * M` full copies of the shared-first-leg tensor. +The target is the full direct sum of the sector tensors, each multiplied by +a length-`M` pairing on the second and third legs. Local variables may have +negative weights; after Fourier projection every surviving total weight is +a nonnegative square, so the resulting coefficient array is polynomial. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent + MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.TensorSpectrum.Separation + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.Separation + +variable {X Y Z : Type*} + +/-- The branch labels occur only on the last two legs of the input. -/ +abbrev shared {M : ℕ} (A : Fin M → Tensor Coeff X Y Z) : + Tensor Coeff X (Fin M × Y) (Fin M × Z) := + Tensor.sharedFirst A + +export MatrixMultiplicationAllFields.TensorSpectrum.Separation + (dotPairingX separated phase projected squareDegree separationPolynomial + squareDegree_eq_zero_iff separationPolynomial_constant separationPolynomial_degree weightX + weightY weightZ) + +export MatrixMultiplicationAllFields.TensorSpectrum.Separation + (copyLocal restrict_copies restrict_scaled) + +section Projection + +variable {M : ℕ} +variable [Fintype X] [Fintype Y] [Fintype Z] +variable [DecidableEq X] [DecidableEq Y] [DecidableEq Z] + +/-- The quantity computed by `copyLocal (fun x => x.2.1) (fun x r => ζ ^ ((r : ℤ) * (2 * (x.1 : +ℤ))))`. -/ +abbrev fourierX (ζ : Coeff) : + (Fin M × (X × Unit)) → (Fin (5 * M) × X) → Coeff := + TensorSpectrum.Separation.fourierX (M := M) (L := 5 * M) (fun e => ζ ^ e) + +/-- The quantity computed by `copyLocal (fun y => (y.1, y.2.1)) (fun y r => ζ ^ ((r : ℤ) * +((y.2.2 : ℤ) - (y.1 : ℤ))))`. -/ +abbrev fourierY (ζ : Coeff) : + (Fin M × (Y × Fin M)) → (Fin (5 * M) × (Fin M × Y)) → Coeff := + TensorSpectrum.Separation.fourierY (M := M) (L := 5 * M) (fun e => ζ ^ e) + +/-- The quantity computed by `copyLocal (fun z => (z.1, z.2.1)) (fun z r => w r * ζ ^ ((r : ℤ) * +(-(z.2.2 : ℤ) - (z.1 : ℤ))))`. -/ +abbrev fourierZ (ζ : Coeff) (w : Fin (5 * M) → Coeff) : + (Fin M × (Z × Fin M)) → (Fin (5 * M) × (Fin M × Z)) → Coeff := + TensorSpectrum.Separation.fourierZ (M := M) (L := 5 * M) (fun e => ζ ^ e) w + +/-- The actual independent local maps give exactly the projected tensor. -/ +theorem fourier_restrict (A : Fin M → Tensor Coeff X Y Z) + (ζ : Coeff) (w : Fin (5 * M) → Coeff) (hζ : ζ ≠ 0) + (haverage : ∀ e : ℤ, -(3 * (M : ℤ)) < e → e < 3 * (M : ℤ) → + (∑ r : Fin (5 * M), w r * ζ ^ ((r : ℤ) * e)) = if e = 0 then 1 else 0) : + Tensor.restrict (fourierX ζ) (fourierY ζ) (fourierZ ζ w) + (Tensor.directSum (fun _ : Fin (5 * M) => shared A)) = projected A := + TensorSpectrum.Separation.fourier_restrict A (fun e => ζ ^ e) w + (fun a b => zpow_add₀ hζ a b) haverage + +end Projection + +section Polynomial + +variable {M : ℕ} + +/-- On the complete projected support, the local weights add to the actual +polynomial degree, including all zero and mismatched coefficients. -/ +theorem separationPolynomial_eval (A : Fin M → Tensor Coeff X Y Z) + (t : Coeff) (ht : t ≠ 0) : + (fun x y z => (separationPolynomial A x y z).eval t) = + fun x y z => t ^ weightX x * t ^ weightY y * t ^ weightZ z * projected A x y z := + TensorSpectrum.Separation.separationPolynomial_eval A t (fun e => t ^ e) + (fun a b => zpow_add₀ ht a b) (fun n => zpow_natCast t n) + +end Polynomial + +section Realization + +variable {M : ℕ} +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- Every nonzero specialization comes from exactly the charged number of +source copies by three actual local linear maps. -/ +theorem separationPolynomial_specializes (hM : 0 < M) + (A : Fin M → Tensor Coeff X Y Z) (t : Coeff) (ht : t ≠ 0) : + (fun x y z => (separationPolynomial A x y z).eval t) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : Fin (5 * M) => shared A)) := by + classical + obtain ⟨ζ, w, hζ, haverage⟩ := Fourier.exists_weights hM + exact TensorSpectrum.Separation.separationPolynomial_specializes (L := 5 * M) + A (fun e => ζ ^ e) w t (fun e => t ^ e) + (fourier_restrict A ζ w hζ haverage) (separationPolynomial_eval A t ht) + +/-- The complete finite construction, without a rank or character premise. +The nonzero-evaluation witnesses are restrictions of the full source direct +sum; the constant tensor is itself a full direct sum of products. -/ +theorem finite_charged_separation (hM : 0 < M) + (A : Fin M → Tensor Coeff X Y Z) : + ∃ P : Tensor (Polynomial Coeff) (Fin M × (X × Unit)) + (Fin M × (Y × Fin M)) (Fin M × (Z × Fin M)), + (∀ x y z, (P x y z).coeff 0 = separated A x y z) ∧ + (∀ x y z, (P x y z).degree ≤ ((M - 1) ^ 2 : ℕ)) ∧ + (∀ t : Coeff, t ≠ 0 → (fun x y z => (P x y z).eval t) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : Fin (5 * M) => shared A))) := + TensorSpectrum.Separation.finite_charged_separation (L := 5 * M) A (· ≠ 0) + (separationPolynomial_specializes hM A) + +end Realization + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.Separation diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/SeparationInterpolation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/SeparationInterpolation.lean new file mode 100644 index 0000000000..ead9831937 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/SeparationInterpolation.lean @@ -0,0 +1,89 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Polynomial.ComplexPolynomialApproximation +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.RestrictionInterpolation + +/-! +# Polynomial coefficient extraction by actual restrictions + +Every coefficient of a bounded polynomial tensor is a linear combination of +evaluations at common interpolation nodes. If those evaluations are local +restrictions of one source tensor, the coefficient is a restriction of the +full direct sum of that many source copies. Applying this to tensor powers +gives the linear interpolation overhead required by restriction-monotone +characters. No continuity of a character on a Euclidean closure is assumed. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.Separation + +export MatrixMultiplicationAllFields.TensorSpectrum.RestrictionInterpolation + (restrict_directSum_sum restrict_scale_first restrict_power power_mem_restrictionOrbit + polynomial_power_constant polynomial_power_eval polynomial_power_degree) + +section Interpolation + +variable {X Y Z U V W : Type*} +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- Interpolation at any common family of distinct nonzero nodes turns actual +restriction witnesses for the evaluations into one restriction witness for the +coefficient. The full number of source copies is charged explicitly. -/ +theorem polynomial_coeff_mem_restrictionOrbit {ι : Type*} + [Fintype ι] [DecidableEq ι] + (T : Tensor Coeff X Y Z) (P : Tensor (Polynomial Coeff) U V W) + (nodes : ι → Coeff) (hinj : Function.Injective nodes) + (hnonzero : ∀ i, nodes i ≠ 0) + (heval : ∀ t : Coeff, t ≠ 0 → + (fun u v w => (P u v w).eval t) ∈ LocalTensor.orbit T) + (hdegree : ∀ u v w, (P u v w).degree < Fintype.card ι) (d : ℕ) : + (fun u v w => (P u v w).coeff d) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : ι => T)) := by + classical + refine TensorSpectrum.RestrictionInterpolation.coefficient_mem_restrictionOrbit T P + nodes (fun i => (Lagrange.basis Finset.univ nodes i).coeff d) d + (fun i => heval (nodes i) (hnonzero i)) ?_ + intro u v w + simpa only [mul_comm] using + Tensor.coeff_eq_sum_eval nodes hinj (P u v w) d (hdegree u v w) + +/-- The finite interpolation bound before applying any character. For every +power `j`, exactly `K*j+1` copies of the power of the original source suffice. +The interpolation nodes have this same cardinality. -/ +theorem polynomial_power_mem_restrictionOrbit + (T : Tensor Coeff X Y Z) (D : Tensor Coeff U V W) + (P : Tensor (Polynomial Coeff) U V W) (K : ℕ) + (hconstant : ∀ u v w, (P u v w).coeff 0 = D u v w) + (hdegree : ∀ u v w, (P u v w).degree ≤ K) + (heval : ∀ t : Coeff, t ≠ 0 → + (fun u v w => (P u v w).eval t) ∈ LocalTensor.orbit T) + (j : ℕ) : + Tensor.power D j ∈ LocalTensor.orbit + (Tensor.directSum (fun _ : Fin (K * j + 1) => Tensor.power T j)) := by + classical + apply TensorSpectrum.RestrictionInterpolation.polynomial_power_mem_restrictionOrbit + T D P K hconstant hdegree (fun t => t ≠ 0) heval j + intro hevalpower hdegreepower + obtain ⟨nodes, hinj, hnonzero⟩ := exists_nonzero_nodes (F := Coeff) (K * j + 1) + exact polynomial_coeff_mem_restrictionOrbit (Tensor.power T j) (Tensor.power P j) + nodes hinj hnonzero hevalpower hdegreepower 0 + +end Interpolation + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.Separation diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/TagHeterogeneous.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/TagHeterogeneous.lean new file mode 100644 index 0000000000..c8c5cd5287 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/TagHeterogeneous.lean @@ -0,0 +1,58 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Separation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Base +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.PolynomialSectors +public import Mathlib.Tactic.FinCases +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagHeterogeneous + +/-! +# Heterogeneous shared-first-leg tensors + +Padding a branch adds only zero coordinates. The extra uniform labels used by +the separation construction are removed by actual independent local maps. +The first leg is shared throughout; no direct-sum additivity is used here. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TagHeterogeneous + +export MatrixMultiplicationAllFields.TensorSpectrum.TagHeterogeneous + (sharedTwo padLeft padRight ofTensor_padLeft ofTensor_padRight maskedFamily + ofTensor_shared_maskedFamily twoLabel twoFamily twoFamily_eq_maskedFamily + ofTensor_shared_twoFamily ofTensor_twoFamily sharedThree threeLabel threeFamily + threeFamily_eq_maskedFamily ofTensor_shared_threeFamily ofTensor_threeFamily) + +/-- The polynomial branch with reversed first coordinate. -/ +abbrev triplingMiddleTensor := + TensorSpectrum.TagHeterogeneous.triplingMiddleTensor (K := Coeff) + +/-- The heterogeneous tensor represents the three polynomial sectors. -/ +theorem triplingSectorTensor_eq_sharedThree (a h : ℕ) : + triplingSectorTensor a h = sharedThree (polynomialTensor a h) + (triplingMiddleTensor a h) (polynomialTensor a h) := + TensorSpectrum.TagHeterogeneous.triplingSectorTensor_eq_sharedThree a h + +/-- The three sectors and their uniform-label tensor have the same restriction class. -/ +theorem ofTensor_tripling_uniform (a h : ℕ) : + TensorClass.ofTensor (Separation.shared + (threeFamily (polynomialTensor a h) (triplingMiddleTensor a h) + (polynomialTensor a h))) = TensorClass.ofTensor (triplingSectorTensor a h) := + TensorSpectrum.TagHeterogeneous.ofTensor_tripling_uniform a h + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TagHeterogeneous diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/TagTensorWords.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/TagTensorWords.lean new file mode 100644 index 0000000000..a6106fd5a8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/TagTensorWords.lean @@ -0,0 +1,43 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Separation +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Powers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagWords +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagTensorWords + +/-! +# Coefficient tensor words and matched-label restrictions + +Tensor powers of a shared-first-leg tensor have one branch for each word. +The regrouping below preserves all coefficients, including the zero +coefficients between different words. Selecting words by an injection is an +actual local restriction. Multiplicativity is then applied to the actual +tensor product represented by each word. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TagTensorWords + +export MatrixMultiplicationAllFields.TensorSpectrum.TagTensorWords + (sharedLabels tensorWord wordBranch joinCoordinates power_shared_pullback + restricts_power_shared_words ofTensor_shared_words shared_injective_pullback + restricts_shared_injective restricts_power_shared_selected restricts_power_shared_fiber + restricts_power_shared_fiber_enumeration headTailCoordinates ofTensor_tensorWord + map_wordBranch map_wordBranch_of_mem_fiber) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TagTensorWords diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Base.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Base.lean new file mode 100644 index 0000000000..37026b1db2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Base.lean @@ -0,0 +1,68 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition +public import Mathlib.Basic.NNReal.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClass + +/-! # Tensor representatives and classes for the upper bound -/ + +@[expose] public section + +noncomputable section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper + +namespace CoefficientTensor + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (Restricts) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.Restricts + (refl trans pullback rankAtMost) + +end Restricts + +end CoefficientTensor + +/-- Finite tensor representatives over the coefficient ring. -/ +abbrev TensorRep := MatrixMultiplicationAllFields.TensorSpectrum.TensorRep Coeff + +namespace TensorRep + +/-- The coefficient array of a tensor representative. -/ +abbrev coeff (T : TensorRep) := + MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.coeff T + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep + (mk ofTensor Restricts Equivalent mutualRestriction restricts_ofTensor + ofTensor_restricts equivalent_ofTensor_coeff) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.Restricts + (refl trans ofTensor) + +end Restricts + +end TensorRep + +/-- Mutual-restriction classes over the coefficient ring. -/ +abbrev TensorClass := MatrixMultiplicationAllFields.TensorSpectrum.TensorClass Coeff + +namespace TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (ofRep ofTensor ofRep_eq ofTensor_coeff ofTensor_eq ofTensor_pullback_equiv ofTensor_le) + +end TensorClass + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Blocks.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Blocks.lean new file mode 100644 index 0000000000..de9773fcb0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Blocks.lean @@ -0,0 +1,41 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Base +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Blocks + +/-! +# Heterogeneous direct sums and restrictions + +The two summands retain separate coordinates on every leg. Cross coefficients +are zero, and block diagonal local matrices give actual restriction witnesses. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.CoefficientTensor + +export MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + (blockSum blockMatrix blockSum_inl blockSum_inr restrict_blockSum pullback_blockSum) + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.Restricts + (blockSum product) + +end Restricts + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.CoefficientTensor diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Flattening.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Flattening.lean new file mode 100644 index 0000000000..7fa13a6258 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Flattening.lean @@ -0,0 +1,314 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Blocks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Rank +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexMatrixTensor +public import Mathlib.LinearAlgebra.Matrix.Rank +public import Mathlib.LinearAlgebra.Pi +public import Mathlib.LinearAlgebra.Prod +public import Mathlib.LinearAlgebra.Dimension.Constructions +public import Mathlib.Tactic.Ring + +/-! +# First-leg coefficient flattening + +The invariant is the matrix rank of the actual coefficient array, with the +second and third coordinates paired into its rows. Local tensor restrictions +act by matrix multiplication on both sides. This invariant, unlike ordinary +tensor rank, is additive on full heterogeneous direct sums. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper +namespace CoefficientTensor + +variable {X Y Z U V W : Type*} + +/-- Pair the last two legs; the first leg indexes matrix columns. -/ +def firstFlattening (T : Tensor Coeff X Y Z) : Matrix (Y × Z) X Coeff := + fun yz x => T x yz.1 yz.2 + +/-- The finite dimension of the space spanned by the first-leg slices. -/ +def flatteningRank [Fintype X] (T : Tensor Coeff X Y Z) : ℕ := + (firstFlattening T).rank + +theorem firstFlattening_restrict [Fintype X] [Fintype Y] [Fintype Z] + (a : U → X → Coeff) (b : V → Y → Coeff) (c : W → Z → Coeff) + (T : Tensor Coeff X Y Z) : + firstFlattening (Tensor.restrict a b c T) = + (show Matrix (V × W) (Y × Z) Coeff from + fun vw yz => b vw.1 yz.1 * c vw.2 yz.2) * firstFlattening T * + Matrix.transpose a := by + funext vw u + change (∑ x, ∑ y, ∑ z, a u x * b vw.1 y * c vw.2 z * T x y z) = + ∑ x, (∑ yz : Y × Z, (b vw.1 yz.1 * c vw.2 yz.2) * T x yz.1 yz.2) * a u x + simp only [Fintype.sum_prod_type, Finset.sum_mul] + apply Finset.sum_congr rfl + intro x hx + apply Finset.sum_congr rfl + intro y hy + apply Finset.sum_congr rfl + intro z hz + ring + +theorem flatteningRank_mono [Fintype X] [Fintype Y] [Fintype Z] + [Fintype U] [Finite V] [Finite W] + {T : Tensor Coeff X Y Z} {S : Tensor Coeff U V W} (h : Restricts T S) : + flatteningRank S ≤ flatteningRank T := by + let : Fintype V := Fintype.ofFinite V + let : Fintype W := Fintype.ofFinite W + rcases h with ⟨a, b, c, rfl⟩ + unfold flatteningRank + rw [firstFlattening_restrict] + exact (Matrix.rank_mul_le_left _ _).trans (Matrix.rank_mul_le_right _ _) + +@[simp] theorem flatteningRank_zero [Fintype X] : + flatteningRank (0 : Tensor Coeff X Y Z) = 0 := by + exact Matrix.rank_zero + +theorem flatteningRank_le_card [Fintype X] (T : Tensor Coeff X Y Z) : + flatteningRank T ≤ Fintype.card X := + Matrix.rank_le_card_width _ + +/-- An identity minor certifies a lower bound directly from coefficients. -/ +theorem card_le_flatteningRank_of_identity [Fintype X] + {I : Type*} [Fintype I] [DecidableEq I] + (T : Tensor Coeff X Y Z) (rows : I → Y × Z) (cols : I → X) + (hidentity : ∀ i j, T (cols j) (rows i).1 (rows i).2 = + if i = j then 1 else 0) : + Fintype.card I ≤ flatteningRank T := by + have heq : (firstFlattening T).submatrix rows cols = (1 : Matrix I I Coeff) := by + funext i j + exact hidentity i j + have h := Matrix.rank_submatrix_le (firstFlattening T) rows cols + rw [heq, Matrix.rank_one] at h + exact h + +@[simp] theorem flatteningRank_natTensor (n : ℕ) : + flatteningRank (natTensor n) = n := by + classical + apply Nat.le_antisymm + · simpa only [Fintype.card_fin] using flatteningRank_le_card (natTensor n) + · have h := card_le_flatteningRank_of_identity (natTensor n) + (fun i : Fin n => (i, i)) id (by + intro i j + simp [natTensor, TensorSpectrum.CoefficientTensor.natTensor, Tensor.diagonal, eq_comm]) + simpa only [Fintype.card_fin] using h + +/-- Flattening rank is bounded by every actual rank-one decomposition. -/ +theorem flatteningRank_le_of_rankAtMost [Fintype X] [Finite Y] [Finite Z] + {T : Tensor Coeff X Y Z} {r : ℕ} (h : Tensor.RankAtMost T r) : + flatteningRank T ≤ r := by + let : Fintype Y := Fintype.ofFinite Y + let : Fintype Z := Fintype.ofFinite Z + have h' := flatteningRank_mono ((rankAtMost_iff_natTensor_restricts T r).mp h) + simpa only [flatteningRank_natTensor] using h' + +theorem flatteningRank_le_rank [Fintype X] [Finite Y] [Finite Z] + (T : Tensor Coeff X Y Z) : flatteningRank T ≤ rank T := + flatteningRank_le_of_rankAtMost (rank_spec T) + +/-- The first-leg slices of a nonempty rectangular matrix multiplication tensor +are independent. The third matrix dimension supplies the selected common index. -/ +theorem flatteningRank_matrixCoefficients + {A B C : Type*} [Fintype A] [Fintype B] + [DecidableEq A] [DecidableEq B] [DecidableEq C] [Nonempty C] : + flatteningRank (Tensor.matrixCoefficients (K := Coeff) A B C) = + Fintype.card A * Fintype.card B := by + classical + apply Nat.le_antisymm + · simpa only [Fintype.card_prod] using + flatteningRank_le_card (Tensor.matrixCoefficients (K := Coeff) A B C) + · let c : C := Classical.choice inferInstance + have h := card_le_flatteningRank_of_identity + (Tensor.matrixCoefficients (K := Coeff) A B C) + (fun i : A × B => ((i.2, c), (c, i.1))) id (by + intro i j + simp only [Tensor.matrixCoefficients, id_eq] + split_ifs <;> simp_all [Prod.ext_iff]) + simpa only [Fintype.card_prod] using h + +theorem flatteningRank_square (n : ℕ) : + flatteningRank (Tensor.matrixCoefficients (K := Coeff) (Fin n) (Fin n) (Fin n)) = + n ^ 2 := by + by_cases hn : n = 0 + · subst n + exact Nat.eq_zero_of_le_zero (by + simpa using flatteningRank_le_card + (Tensor.matrixCoefficients (K := Coeff) (Fin 0) (Fin 0) (Fin 0))) + · let : Nonempty (Fin n) := ⟨⟨0, Nat.pos_of_ne_zero hn⟩⟩ + simpa only [Fintype.card_fin, pow_two] using + (flatteningRank_matrixCoefficients (A := Fin n) (B := Fin n) (C := Fin n)) + +/-- Rows belonging to one summand embed into the full paired row family. -/ +private def blockRows : (Y × Z) ⊕ (V × W) → (Y ⊕ V) × (Z ⊕ W) + | .inl yz => (.inl yz.1, .inl yz.2) + | .inr vw => (.inr vw.1, .inr vw.2) + +/-- Insert the two diagonal row blocks and fill both cross row families by zero. -/ +private def insertBlockRows [DecidableEq Y] [DecidableEq Z] + [DecidableEq V] [DecidableEq W] : + Matrix ((Y ⊕ V) × (Z ⊕ W)) ((Y × Z) ⊕ (V × W)) Coeff + | (.inl y, .inl z), .inl yz => if yz = (y, z) then 1 else 0 + | (.inr v, .inr w), .inr vw => if vw = (v, w) then 1 else 0 + | _, _ => 0 + +/-- Ordinary matrix rank is additive on block diagonal matrices. This is a +statement about ranges of linear maps, with no tensor rank additivity premise. -/ +theorem blockMatrix_rank {m n p q : Type*} + [Finite m] [Fintype n] [Finite p] [Fintype q] + (A : Matrix m n Coeff) (B : Matrix p q Coeff) : + Matrix.rank (blockMatrix A B) = A.rank + B.rank := by + let : Fintype m := Fintype.ofFinite m + let : Fintype p := Fintype.ofFinite p + have hblock : blockMatrix A B = Matrix.fromBlocks A 0 0 B := by + funext i j + rcases i with i | i <;> rcases j with j | j <;> rfl + rw [hblock] + let e : (m ⊕ p → Coeff) ≃ₗ[Coeff] (m → Coeff) × (p → Coeff) := + LinearEquiv.sumArrowLequivProdArrow m p Coeff Coeff + let d : (n ⊕ q → Coeff) ≃ₗ[Coeff] (n → Coeff) × (q → Coeff) := + LinearEquiv.sumArrowLequivProdArrow n q Coeff Coeff + have hcomp : + e.toLinearMap.comp (Matrix.fromBlocks A 0 0 B).mulVecLin = + (A.mulVecLin.prodMap B.mulVecLin).comp d.toLinearMap := by + apply LinearMap.ext + intro x + apply Prod.ext + · funext i + change ((Matrix.fromBlocks A 0 0 B).mulVecLin x) (Sum.inl i) = + (A.mulVecLin (x ∘ Sum.inl)) i + simp [Matrix.fromBlocks_mulVec] + · funext i + change ((Matrix.fromBlocks A 0 0 B).mulVecLin x) (Sum.inr i) = + (B.mulVecLin (x ∘ Sum.inr)) i + simp [Matrix.fromBlocks_mulVec] + have hmap : + (LinearMap.range (Matrix.fromBlocks A 0 0 B).mulVecLin).map e.toLinearMap = + (LinearMap.range A.mulVecLin).prod (LinearMap.range B.mulVecLin) := by + rw [← LinearMap.range_comp, hcomp, LinearEquiv.range_comp, LinearMap.range_prodMap] + let ep : + ((LinearMap.range A.mulVecLin).prod (LinearMap.range B.mulVecLin)) ≃ₗ[Coeff] + (LinearMap.range A.mulVecLin) × (LinearMap.range B.mulVecLin) := + { toFun := fun x => (⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩) + invFun := fun x => ⟨(x.1.1, x.2.1), ⟨x.1.2, x.2.2⟩⟩ + left_inv := fun _ => rfl + right_inv := fun _ => rfl + map_add' := fun _ _ => rfl + map_smul' := fun _ _ => rfl } + calc + (Matrix.fromBlocks A 0 0 B).rank = + Module.finrank Coeff + ((LinearMap.range A.mulVecLin).prod (LinearMap.range B.mulVecLin)) := + (e.ofSubmodules _ _ hmap).finrank_eq + _ = Module.finrank Coeff + ((LinearMap.range A.mulVecLin) × (LinearMap.range B.mulVecLin)) := + ep.finrank_eq + _ = A.rank + B.rank := Module.finrank_prod + +/-- The cross rows of a full tensor direct sum are all zero; removing exactly +these rows leaves the block diagonal matrix without changing its rank. -/ +theorem flatteningRank_blockSum_eq_blockMatrix_rank + [Fintype X] [Finite Y] [Finite Z] + [Fintype U] [Finite V] [Finite W] + (T : Tensor Coeff X Y Z) (S : Tensor Coeff U V W) : + flatteningRank (blockSum T S) = + Matrix.rank (blockMatrix (firstFlattening T) (firstFlattening S)) := by + classical + let : Fintype V := Fintype.ofFinite V + let : Fintype W := Fintype.ofFinite W + let : Fintype Y := Fintype.ofFinite Y + let : Fintype Z := Fintype.ofFinite Z + let D : Matrix ((Y × Z) ⊕ (V × W)) (X ⊕ U) Coeff := + blockMatrix (firstFlattening T) (firstFlattening S) + have hsub : (firstFlattening (blockSum T S)).submatrix blockRows id = D := by + funext yz x + rcases yz with yz | vw <;> rcases x with x | u <;> rfl + have hmul : insertBlockRows * D = firstFlattening (blockSum T S) := by + funext yz x + change (∑ j : (Y × Z) ⊕ (V × W), insertBlockRows yz j * D j x) = + blockSum T S x yz.1 yz.2 + rcases yz with ⟨y, z⟩ + rcases y with y | v <;> rcases z with z | w <;> rcases x with x | u <;> + simp [insertBlockRows, D, blockMatrix, firstFlattening, + blockSum, Fintype.sum_sum_type, ite_mul] + apply Nat.le_antisymm + · change (firstFlattening (blockSum T S)).rank ≤ D.rank + rw [← hmul] + exact Matrix.rank_mul_le_right _ _ + · have h := Matrix.rank_submatrix_le (firstFlattening (blockSum T S)) blockRows id + rw [hsub] at h + exact h + +theorem flatteningRank_blockSum [Fintype X] [Finite Y] [Finite Z] + [Fintype U] [Finite V] [Finite W] + (T : Tensor Coeff X Y Z) (S : Tensor Coeff U V W) : + flatteningRank (blockSum T S) = flatteningRank T + flatteningRank S := by + let : Fintype V := Fintype.ofFinite V + let : Fintype W := Fintype.ofFinite W + let : Fintype Y := Fintype.ofFinite Y + let : Fintype Z := Fintype.ofFinite Z + rw [flatteningRank_blockSum_eq_blockMatrix_rank] + exact blockMatrix_rank _ _ + +end CoefficientTensor + +namespace TensorRep + +/-- Uses `CoefficientTensor.flatteningRank T.coeff` as the representation. -/ +def flatteningRank (T : TensorRep) : ℕ := CoefficientTensor.flatteningRank T.coeff + +theorem Restricts.flatteningRank_le {A B : TensorRep} (h : Restricts A B) : + flatteningRank B ≤ flatteningRank A := + CoefficientTensor.flatteningRank_mono h + +theorem Equivalent.flatteningRank_eq {A B : TensorRep} (h : Equivalent A B) : + flatteningRank A = flatteningRank B := + Nat.le_antisymm (Restricts.flatteningRank_le h.2) (Restricts.flatteningRank_le h.1) + +end TensorRep + +namespace TensorClass + +/-- Actual first-leg matrix rank, invariant under mutual tensor restriction. -/ +def flatteningRank : TensorClass → ℕ := + Quotient.lift TensorRep.flatteningRank (fun _ _ h => TensorRep.Equivalent.flatteningRank_eq h) + +@[simp] theorem flatteningRank_ofRep (T : TensorRep) : + flatteningRank (ofRep T) = T.flatteningRank := rfl + +theorem flatteningRank_mono {A B : TensorClass} (h : A ≤ B) : + flatteningRank A ≤ flatteningRank B := by + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + exact TensorRep.Restricts.flatteningRank_le h + +theorem flatteningRank_ofTensor {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (T : Tensor Coeff X Y Z) : + flatteningRank (ofTensor T) = CoefficientTensor.flatteningRank T := by + apply Nat.le_antisymm + · exact CoefficientTensor.flatteningRank_mono (TensorRep.restricts_ofTensor T) + · exact CoefficientTensor.flatteningRank_mono (TensorRep.ofTensor_restricts T) + +theorem flatteningRank_le_rank (T : TensorClass) : flatteningRank T ≤ rank T := by + induction T using Quotient.inductionOn with | h T => + exact CoefficientTensor.flatteningRank_le_rank T.coeff + +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/FlatteningOrder.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/FlatteningOrder.lean new file mode 100644 index 0000000000..0d417a0c56 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/FlatteningOrder.lean @@ -0,0 +1,70 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.RankOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Flattening + +/-! The actual additive flattening invariant on the concrete tensor semiring. -/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +@[simp] theorem flatteningRank_natCast (n : ℕ) : flatteningRank (n : TensorClass) = n := by + rw [natCast_eq_ofTensor_natTensor, flatteningRank_ofTensor, + CoefficientTensor.flatteningRank_natTensor] + +@[simp] theorem flatteningRank_zero : flatteningRank (0 : TensorClass) = 0 := + flatteningRank_natCast 0 + +@[simp] theorem flatteningRank_one : flatteningRank (1 : TensorClass) = 1 := by + simpa only [Nat.cast_one] using flatteningRank_natCast 1 + +theorem flatteningRank_add (A B : TensorClass) : + flatteningRank (A + B) = flatteningRank A + flatteningRank B := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + change flatteningRank (ofRep a + ofRep b) = + flatteningRank (ofRep a) + flatteningRank (ofRep b) + rw [← ofTensor_coeff a, ← ofTensor_coeff b, ofTensor_add] + simp only [flatteningRank_ofTensor, CoefficientTensor.flatteningRank_blockSum] + +@[simp] theorem rank_natCast (n : ℕ) : rank (n : TensorClass) = n := by + apply Nat.le_antisymm + · rw [natCast_eq_ofTensor_natTensor, rank_ofTensor] + exact (CoefficientTensor.rank_le_iff _ _).mpr + (CoefficientTensor.rankAtMost_natTensor n) + · simpa only [flatteningRank_natCast] using + flatteningRank_le_rank (n : TensorClass) + +theorem natCast_le_natCast_iff (m n : ℕ) : + (m : TensorClass) ≤ (n : TensorClass) ↔ m ≤ n := by + constructor + · intro h + simpa only [rank_natCast] using rank_mono h + · intro h + rw [natCast_eq_ofTensor_natTensor, natCast_eq_ofTensor_natTensor] + exact ofTensor_le (CoefficientTensor.natTensor_restricts_of_le h) + +/-- A positive scalar cannot be absorbed by a finite catalyst. This is where +additive flattening rank is used, rather than additivity of ordinary rank. -/ +theorem not_add_positive_natCast_le (D : TensorClass) {m : ℕ} (hm : 0 < m) : + ¬ D + (m : TensorClass) ≤ D := by + intro h + have hf := flatteningRank_mono h + rw [flatteningRank_add, flatteningRank_natCast] at hf + exact (Nat.not_lt_of_ge hf) (Nat.lt_add_of_pos_right hm) + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Matrix.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Matrix.lean new file mode 100644 index 0000000000..a2f67bf6da --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Matrix.lean @@ -0,0 +1,80 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Flattening +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexMatrixTensor +public import Mathlib.Logic.Equiv.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDots + +/-! +# Square matrix tensors in the restriction semiring + +Dimension comparisons and multiplication are witnessed by the actual coordinate +maps. The cubic rank bound uses the ordinary sum over the three matrix indices. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper +namespace CoefficientTensor + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (matrixCoefficients_pullback_injective) + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor (squareProductCoordinates) + +/-- Relabeling the product coordinates gives the larger square multiplication tensor. -/ +theorem square_product_pullback (n m : ℕ) : + Tensor.pullback (squareProductCoordinates n m) (squareProductCoordinates n m) + (squareProductCoordinates n m) (Upper.matrixTensor (n * m) (n * m) (n * m)) = + Tensor.product (Upper.matrixTensor n n n) (Upper.matrixTensor m m m) := + MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.square_product_pullback + (K := Coeff) n m + +/-- Restrict a square multiplication tensor by taking the first indices of each wire. -/ +theorem square_restricts_of_le {n m : ℕ} (h : n ≤ m) : + Restricts (Upper.matrixTensor m m m) (Upper.matrixTensor n n n) := + MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.square_restricts_of_le + (K := Coeff) h + +/-- A sum over the triples of indices gives a cubic rank bound. -/ +theorem square_rankAtMost_cubic (n : ℕ) : + Tensor.RankAtMost (Upper.matrixTensor n n n) (n ^ 3) := + MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.square_rankAtMost_cubic + (K := Coeff) n + +end CoefficientTensor + +namespace TensorClass + +/-- The class of the actual `n` by `n` matrix multiplication tensor. -/ +abbrev square := MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.square (K := Coeff) + +theorem rank_square_le (n : ℕ) : rank (square n) ≤ n ^ 3 := + TensorSpectrum.TensorClass.rank_square_le n + +theorem flatteningRank_square (n : ℕ) : flatteningRank (square n) = n ^ 2 := by + rw [square, TensorSpectrum.TensorClass.square, flatteningRank_ofTensor] + exact CoefficientTensor.flatteningRank_square n + +theorem square_rank_lower (n : ℕ) : n ^ 2 ≤ rank (square n) := by + rw [← flatteningRank_square n] + exact flatteningRank_le_rank (square n) + +end TensorClass +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Powers.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Powers.lean new file mode 100644 index 0000000000..e6c5a457f5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Powers.lean @@ -0,0 +1,48 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.RankOrder +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPowers + +/-! +# Tensor powers and full repeated direct sums in the quotient + +These bridges preserve the actual coefficient tensors used by interpolation. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (ofTensor_power ofTensor_directSum_const) + +namespace Character + +theorem map_power_tensor (f : Character) {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (T : Tensor Coeff X Y Z) (n : ℕ) : + f (ofTensor (Tensor.power T n)) = (f (ofTensor T)) ^ n := + TensorSpectrum.TensorClass.Character.map_power_tensor f T n + +theorem map_directSum_const (f : Character) {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (T : Tensor Coeff X Y Z) (n : ℕ) : + f (ofTensor (Tensor.directSum (fun _ : Fin n => T))) = + (n : ℝ≥0) * f (ofTensor T) := + TensorSpectrum.TensorClass.Character.map_directSum_const f T n + +end Character + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Rank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Rank.lean new file mode 100644 index 0000000000..d8b6dfb83e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Rank.lean @@ -0,0 +1,92 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Tensor +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorBatching +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Blocks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRank + +/-! +# Actual finite tensor rank + +The natural tensor is the diagonal coefficient tensor. Its local restrictions +are exactly the tensors admitting the corresponding number of rank-one terms. +Every finite coefficient tensor has such a decomposition, obtained by expanding +its individual coefficients. Exact rank is therefore a genuine minimum. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper +namespace CoefficientTensor + +/-- The diagonal coefficient tensor for independent scalar products. -/ +abbrev natTensor := MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor.natTensor + (K := Coeff) + +export MatrixMultiplicationAllFields.TensorSpectrum.CoefficientTensor + (restrict_natTensor rankAtMost_natTensor rankAtMost_iff_natTensor_restricts + natTensor_add_pullback natTensor_add_restricts rankAtMost_blockSum natTensor_restricts_of_le + rankAtMost_mono rank rank_spec rank_le_iff rank_mono rank_product_le rank_blockSum_le + rank_eq_zero_iff) + +variable {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + +/-- A nonzero coefficient can be selected and rescaled to obtain the scalar +unit tensor. No nonzero-rank assumption replaces this actual restriction. -/ +theorem nonzero_restricts_natTensor_one {T : Tensor Coeff X Y Z} (hT : T ≠ 0) : + Restricts T (natTensor 1) := by + classical + have hex : ∃ x y z, T x y z ≠ 0 := by + by_contra h + apply hT + funext x y z + exact Classical.byContradiction (fun hn => h ⟨x, y, z, hn⟩) + obtain ⟨x, y, z, hxyz⟩ := hex + exact TensorSpectrum.CoefficientTensor.scaled_restricts_natTensor_one x y z + (T x y z)⁻¹ (inv_mul_cancel₀ hxyz) + +end CoefficientTensor + +namespace TensorRep + +/-- The rank of the tensor in its chosen coordinates. -/ +abbrev rank (T : TensorRep) := MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.rank T + +namespace Restricts + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.Restricts + (rank_le) + +end Restricts + +namespace Equivalent + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorRep.Equivalent + (rank_eq) + +end Equivalent + +end TensorRep + +namespace TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (rank rank_ofRep rank_mono rank_ofTensor) + +end TensorClass + +end MatrixMultiplicationAllFields.MatrixExponent.Upper diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/RankOrder.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/RankOrder.lean new file mode 100644 index 0000000000..ef61a6aee0 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/RankOrder.lean @@ -0,0 +1,64 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRankOrder + +/-! +# Rank bounds and the concrete tensor order + +Natural numbers in the quotient semiring are precisely the diagonal tensors. +These lemmas connect ordinary finite decompositions to the order used by states. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent.Upper.CoefficientTensor + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (ofTensor_zero natCast_eq_ofTensor_natTensor rank_add_le rank_mul_le le_rank_natCast + rank_eq_zero_iff mul_le_rank_mul) + +theorem one_le_of_ne_zero {A : TensorClass} (hA : A ≠ 0) : 1 ≤ A := by + induction A using Quotient.inductionOn with | h a => + change ofRep a ≠ 0 at hA + change 1 ≤ ofRep a + have ha : a.coeff ≠ 0 := by + intro h + apply hA + rw [← ofTensor_coeff a, h, ofTensor_zero] + rw [← ofTensor_coeff a] + have h := ofTensor_le (nonzero_restricts_natTensor_one ha) + rw [MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.ofTensor_natTensor_one] at h + exact h + + +namespace Character + +theorem map_natCast (f : Character) (n : ℕ) : f n = n := + TensorSpectrum.TensorClass.Character.map_natCast f n + +theorem le_rank (f : Character) (A : TensorClass) : f A ≤ rank A := + TensorSpectrum.TensorClass.Character.le_rank f A + +end Character + +theorem Character.one_le (f : Character) {A : TensorClass} (hA : A ≠ 0) : 1 ≤ f A := by + have h := f.monotone' (one_le_of_ne_zero hA) + simpa only [Character.map_one] using h + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Semiring.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Semiring.lean new file mode 100644 index 0000000000..747dcc770e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Upper/Tensor/Semiring.lean @@ -0,0 +1,66 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Coefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Upper.Tensor.Blocks +public import Mathlib.Logic.Equiv.Sum +public import Mathlib.Logic.Equiv.Prod +public import Mathlib.Algebra.Ring.Defs +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassSemiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassCharacter + +/-! +# The semiring of actual finite tensors + +Every law is obtained from an explicit coordinate relabeling. The quotient +identifies mutual restriction, not numerical ranks or an abstract tensor model. +-/ + +@[expose] public section + +open MatrixMultiplicationAllFields.MatrixExponent MatrixMultiplicationAllFields.TensorSpectrum + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent.Upper.CoefficientTensor +open scoped NNReal + +namespace MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + (ofTensor_add ofTensor_mul add_comm_aux add_assoc_aux zero_add_aux mul_comm_aux + mul_assoc_aux one_mul_aux zero_mul_aux left_distrib_aux add_mono mul_mono zero_le) + +/-- The empty tensor over the coefficient ring. -/ +abbrev emptyTensor := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.emptyTensor (K := Coeff) + +/-- The unit tensor over the coefficient ring. -/ +abbrev unitTensor := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.unitTensor (K := Coeff) + +/-- An order-preserving semiring homomorphism on these tensor classes. -/ +abbrev Character := MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character Coeff + +namespace Character + +/-- The semiring homomorphism underlying the character. -/ +abbrev toHom (f : Character) : TensorClass →+* ℝ≥0 := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character.toHom f + +/-- Characters preserve the restriction order. -/ +theorem monotone' (f : Character) : Monotone f.toHom := + MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character.monotone' f + +export MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character + (map_zero map_one map_add map_mul) + +end Character + +end MatrixMultiplicationAllFields.MatrixExponent.Upper.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/UpperBound.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/UpperBound.lean new file mode 100644 index 0000000000..257fccdb0d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/UpperBound.lean @@ -0,0 +1,69 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldExtension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Sparse.Degree +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Profile.Binary +public import Mathlib.Algebra.Algebra.ZMod +public import Mathlib.Algebra.Field.ZMod + +/-! +# The upper bound over every field + +First bound the exponent at shapes `(AB, AC, BC)` for positive integers +`A, B, C`. All three integers equal to one gives the square. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +theorem small_field (F : Type*) [Field F] : ∃ (K : Type) (_ : Field K), Nonempty (Algebra K F) := by + obtain ⟨p, hp⟩ := CharP.exists F + rcases CharP.char_is_prime_or_zero F p with hprime | rfl + · have : Fact p.Prime := ⟨hprime⟩ + exact ⟨ZMod p, inferInstance, ⟨ZMod.algebra F p⟩⟩ + · let : CharZero F := CharP.charP_to_charZero F + exact ⟨ℚ, inferInstance, ⟨inferInstance⟩⟩ + +theorem closed_fulfills (K : Type) [Field K] [IsAlgClosed K] : Fulfills K := + closed_laws { + discrete := coeff_discrete character_bound + density := coeff_density + cells := coeff_cells + binary := Profile.coeff_binary + degrees := Sparse.coeff_degrees + } K + +theorem discrete_bound (F : Type*) [Field F] : DiscreteBound F := by + obtain ⟨K, _, ⟨alg⟩⟩ := small_field F + intro A B C hA hB hC + have h₁ : 0 ≤ (A : ℝ) * B := by positivity + have h₂ : 0 ≤ (A : ℝ) * C := by positivity + have h₃ : 0 ≤ (B : ℝ) * C := by positivity + rw [exponent_extension K F h₁ h₂ h₃, ← exponent_extension K (AlgebraicClosure K) h₁ h₂ h₃] + exact (closed_fulfills _).discrete A B C hA hB hC + +end MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +namespace MatrixMultiplicationAllFields.MatrixExponent + +theorem upper_bound (F : Type*) [Field F] : omega F ≤ 9 / 4 := by + have h := Rectangle.discrete_bound F 1 1 1 (by decide) (by decide) (by decide) + norm_num [Rectangle.square] at h + exact h + +theorem arithmetic_bound (F : Type*) [Field F] : Admissible F (9 / 4) := by + intro ε hε + have h : omega F < 9 / 4 + ε := lt_add_of_le_of_pos (upper_bound F) hε + obtain ⟨s, hs, hlt⟩ := exists_lt_of_csInf_lt ⟨3, admissible_three F⟩ h + obtain ⟨C, hC, hprog⟩ := hs (9 / 4 + ε - s) (sub_pos.mpr hlt) + refine ⟨C, hC, ?_⟩ + simpa only [show s + (9 / 4 + ε - s) = 9 / 4 + ε by ring] using hprog + +end MatrixMultiplicationAllFields.MatrixExponent diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Continuity.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Continuity.lean new file mode 100644 index 0000000000..3de779ced1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Continuity.lean @@ -0,0 +1,964 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Extension +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Extra +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Fields +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.ScaleSlope +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Uniform +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Routing.GeometryComparison +public import Mathlib.Analysis.MeanInequalities + +/-! +# Assignments of added sites at fixed scale + +A placement preserving every old name necessarily preserves full +diagonal prices. Its multiplicative evaluation is then additive by the +binomial expansion. Assignments can consequently be restricted or +duplicated without changing the scale. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open ITensor Spectral + +variable {K S U V W : Type} [Field K] {O : Subring K} + [Fintype S] [Nonempty S] {f : ITensor O S →+* ℝ} + +/-- The data for the assignment construction, including `val`, `mono`, `old`. -/ +structure Assignment (f : ITensor O S →+* ℝ) (U : Type) [Fintype U] where + /-- The `Assignment` component of type `ITensor O (S ⊕ U) →+* ℝ`. -/ + val : ITensor O (S ⊕ U) →+* ℝ + mono : Monotone val + old : ∀ A, val (pad U A) = f A + +namespace Assignment + +variable [Fintype U] [Fintype V] [Fintype W] + +theorem exists_iff {I : Type*} (hf : Monotone f) (A : I → ITensor O (S ⊕ U)) (p : I → ℝ) : + (∃ g : Assignment f U, ∀ i, g.val (A i) ≤ p i) ↔ + ∀ w : List I, Prices.assisted (pad U) f (w.map A).prod ≤ (w.map p).prod := by + refine Iff.trans ?_ ((extensionData f hf).assisted_extension_iff A p) + exact ⟨fun ⟨g, h⟩ => ⟨g.val, g.mono, g.old, h⟩, fun ⟨g, hg, he, h⟩ => ⟨⟨g, hg, he⟩, h⟩⟩ + +theorem nonneg (g : Assignment f U) (A : ITensor O (S ⊕ U)) : 0 ≤ g.val A := by + simpa using g.mono (zero_le A) + +variable [DecidableEq S] [DecidableEq U] [DecidableEq V] [DecidableEq W] + +private theorem place_nat {X Y : Type} [Fintype X] [Nonempty X] [DecidableEq X] + [Fintype Y] [DecidableEq Y] (x : X → Y) (n : ℕ) : place x (n : ITensor O X) ≤ n := by + induction n with + | zero => rw [Nat.cast_zero, Nat.cast_zero, place_zero] + | succ n ih => + rw [Nat.cast_succ, Nat.cast_succ] + refine (place_add_le x _ _).trans ?_ + rw [place_one] + exact ITensor.add_le_add_right _ _ _ ih + +theorem place_pad (x : U → V) (A : ITensor O S) : place (Sum.map id x) (pad U A) = pad V A := by + rw [← place_inl, ← place_comp, show Sum.map (id : S → S) x ∘ Sum.inl = Sum.inl from rfl, + place_inl] + +theorem pull_add (g : Assignment f V) (x : U → V) (A B : ITensor O (S ⊕ U)) : + g.val (place (Sum.map id x) (A + B)) = + g.val (place (Sum.map id x) A) + g.val (place (Sum.map id x) B) := by + let e := Sum.map (id : S → S) x + let p : ITensor O (S ⊕ U) →* ℝ := + { toFun := fun X => g.val (place e X) + map_one' := by rw [place_one, map_one] + map_mul' := fun X Y => by rw [place_mul, map_mul] } + have hp : Monotone p := g.mono.comp (place_mono e) + have hn (n : ℕ) : p n = (n : ℝ) ^ (1 : ℝ) := by + rw [Real.rpow_one] + apply le_antisymm + · exact (g.mono (place_nat e n)).trans_eq (map_natCast g.val n) + · have h := hp (place_nat (Sum.inl : S → S ⊕ U) n) + change g.val (place (Sum.map id x) (place Sum.inl (n : ITensor O S))) ≤ p n at h + rwa [place_inl, place_pad, g.old, map_natCast] at h + obtain ⟨q, _, eq⟩ := Tensor.normalize_hom ITensor.add_le_add_right zero_le p hp + (by change g.val (place e 0) = _; rw [place_zero, map_zero]) + (fun a b => (g.mono (place_add_le _ _ _)).trans_eq (g.val.map_add _ _)) zero_lt_one hn + simp only [inv_one, Real.rpow_one] at eq + exact (eq _).symm.trans ((q.map_add A B).trans (congrArg₂ (· + ·) (eq A) (eq B))) + +/-- Builds `Assignment f U where val` with the specified `val`, `mono`, `old`. -/ +def pull (g : Assignment f V) (x : U → V) : Assignment f U where + val := + { toFun := fun A => g.val (place (Sum.map id x) A) + map_zero' := by rw [place_zero, map_zero] + map_one' := by rw [place_one, map_one] + map_mul' := fun A B => by rw [place_mul, map_mul] + map_add' := pull_add g x } + mono := g.mono.comp (place_mono _) + old A := (congrArg g.val (place_pad x A)).trans (g.old A) + +theorem pull_apply (g : Assignment f V) (x : U → V) (A : ITensor O (S ⊕ U)) : + (g.pull x).val A = g.val (place (Sum.map id x) A) := rfl + +theorem pull_comp (g : Assignment f W) (x : U → V) (y : V → W) (A : ITensor O (S ⊕ U)) : + ((g.pull y).pull x).val A = (g.pull (y ∘ x)).val A := by + simp only [pull_apply, ← place_comp] + rw [show Sum.map (id : S → S) y ∘ Sum.map id x = Sum.map id (y ∘ x) by funext z; cases z <;> rfl] + +theorem pull_id (g : Assignment f U) (A : ITensor O (S ⊕ U)) : (g.pull id).val A = g.val A := by + rw [pull_apply, show Sum.map id id = (id : S ⊕ U → S ⊕ U) by funext z; cases z <;> rfl, place_id] + +/-- The value specified by `(Equiv.sumAssoc S U V).symm`. -/ +abbrev unassoc (S U V : Type) := (Equiv.sumAssoc S U V).symm + +/-- Builds `Assignment f (U ⊕ V) where val` with the specified `val`, `mono`, `old`. -/ +def chain (g : Assignment f U) (k : Assignment g.val V) : Assignment f (U ⊕ V) where + val := k.val.comp (group (unassoc S U V) (unassoc S U V).surjective) + mono := k.mono.comp (group_mono _ _) + old A := by + change k.val (place (unassoc S U V) (pad _ A)) = _ + rw [← place_inl, ← place_comp, + show unassoc S U V ∘ Sum.inl = Sum.inl ∘ Sum.inl from rfl, place_comp, + place_inl, place_inl, k.old, g.old] + +theorem chain_left (g : Assignment f U) (k : Assignment g.val V) (A : ITensor O (S ⊕ U)) : + ((g.chain k).pull Sum.inl).val A = g.val A := by + change k.val (place (unassoc S U V) (place (Sum.map id Sum.inl) A)) = _ + rw [← place_comp, show unassoc S U V ∘ Sum.map id Sum.inl = Sum.inl by + funext z; cases z <;> rfl, place_inl, k.old] + +theorem chain_right (g : Assignment f U) (k : Assignment g.val V) (A : ITensor O (S ⊕ V)) : + ((g.chain k).pull Sum.inr).val A = k.val (place (Sum.map Sum.inl id) A) := by + change k.val (place (unassoc S U V) (place (Sum.map id Sum.inr) A)) = _ + rw [← place_comp, show unassoc S U V ∘ Sum.map id Sum.inr = Sum.map Sum.inl id by + funext z; cases z <;> rfl] + +private theorem place_prod (e : U → V) (w : List (ITensor O U)) : + place e w.prod = (w.map (place e)).prod := by + induction w with + | nil => exact place_one e + | cons i w ih => rw [List.prod_cons, place_mul, ih]; rfl + +/-- Keep one assignment, bounding every price on the added copy by +its value at the competing assignment. -/ +theorem combine (g : Assignment f U) (h : Assignment f V) : + ∃ k : Assignment f (U ⊕ V), (∀ A, (k.pull Sum.inl).val A = g.val A) ∧ + ∀ B, (k.pull Sum.inr).val B ≤ h.val B := by + let e : S ⊕ V → (S ⊕ U) ⊕ V := Sum.map Sum.inl id + have tests (w : List (ITensor O (S ⊕ V))) (A : ITensor O (S ⊕ U)) + (hA : pad V A ≤ (w.map (place e)).prod) : g.val A ≤ (w.map h.val).prod := by + rw [← place_prod] at hA + obtain ⟨B, hB, hC⟩ := close_extra hA + rw [← map_list_prod] + exact (g.mono hB).trans ((g.old B).trans_le ((h.old B).symm.trans_le (h.mono hC))) + obtain ⟨k, hk, ek, hle⟩ := (extension_iff g.val g.mono (place e) h.val).mpr tests + let k' : Assignment g.val V := ⟨k, hk, ek⟩ + exact ⟨g.chain k', g.chain_left k', fun A => (g.chain_right k' A).trans_le (hle A)⟩ + +end Assignment +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- # Geodesic interpolation of valued assignments -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.Assignment +open ITensor Spectral Routing + +variable {F K S U V W : Type} [Field F] [Field K] [Algebra F K] {O : Subring K} + [Fintype S] [DecidableEq S] [Nonempty S] + [Fintype U] [DecidableEq U] [Fintype V] [DecidableEq V] [Fintype W] [DecidableEq W] + {f : ITensor O S →+* ℝ} + +omit [DecidableEq S] [DecidableEq U] in +theorem ext {g k : Assignment f U} (h : ∀ A, g.val A = k.val A) : g = k := by + cases g + cases k + congr + exact RingHom.ext h + +theorem pull_pull (g : Assignment f W) (x : U → V) (y : V → W) : + (g.pull y).pull x = g.pull (y ∘ x) := ext (g.pull_comp x y) + +/-- The indexed operation `g.pull (fun _ => x)`. -/ +def atSite (g : Assignment f U) (x : U) : Assignment f Unit := g.pull (fun _ => x) + +theorem pull_atSite (g : Assignment f V) (x : U → V) (i : U) : + (g.pull x).atSite i = g.atSite (x i) := g.pull_pull _ _ + +theorem atUnit (g : Assignment f Unit) : g.atSite () = g := ext g.pull_id + +variable (hO : constants F K ≤ O) + +/-- Computes the point by the application `g.val.comp (fromBase hO)`. -/ +def point (g : Assignment f U) : Tensor F (S ⊕ U) →+* ℝ := g.val.comp (fromBase hO) + +omit [DecidableEq S] [DecidableEq U] in +theorem point_mono (g : Assignment f U) : Monotone (g.point hO) := g.mono.comp (fromBase_mono hO) + +/-- The value specified by `Tensor.dist (g.point hO)`. -/ +def dist (g : Assignment f U) : S ⊕ U → S ⊕ U → ℝ := Tensor.dist (g.point hO) + +/-- Computes the radius by the application `dist hO g (.inl o) (.inr ())`. -/ +def radius (o : S) (g : Assignment f Unit) : ℝ := dist hO g (.inl o) (.inr ()) + +theorem dist_pull (g : Assignment f V) (x : U → V) (i j : S ⊕ U) : + dist hO (g.pull x) i j = dist hO g (Sum.map id x i) (Sum.map id x j) := by + unfold dist Tensor.dist + change Real.log (g.val (place (Sum.map id x) (wire hO i j 2))) / _ = _ + rw [place_wire] + rfl + +theorem radius_atSite (o : S) (g : Assignment f U) (x : U) : + radius hO o (g.atSite x) = dist hO g (.inl o) (.inr x) := + dist_pull hO _ _ _ _ + +theorem dist_nonneg (g : Assignment f U) (i j) : 0 ≤ dist hO g i j := + Tensor.dist_nonneg _ (g.point_mono hO) _ _ + +theorem dist_self (g : Assignment f U) (i) : dist hO g i i = 0 := Tensor.dist_self _ _ + +theorem price_wire (g : Assignment f U) (i j : S ⊕ U) : + g.val (wire hO i j 2) = (2 : ℝ) ^ dist hO g i j := by + exact Tensor.price_wire _ (g.point_mono hO) _ _ (by decide) + +theorem pull_eq (g : Assignment f V) (x y : U → V) + (h : ∀ i, dist hO g (.inr (x i)) (.inr (y i)) = 0) : g.pull x = g.pull y := by + refine ext fun A => price_place_eq hO _ g.mono _ _ ?_ A + rintro (i | i) + · exact dist_self _ _ _ + · exact h i + +private def fold (g : Assignment f U) (a : U) : Assignment g.val Unit where + val := g.val.comp (group (Sum.elim id (fun _ : Unit => Sum.inr a)) (fun b => ⟨.inl b, rfl⟩)) + mono := g.mono.comp (group_mono _ _) + old B := congrArg g.val (group_pad _ _ (fun _ => rfl) B) + +private theorem fold_apply (g : Assignment f U) (a : U) (B : ITensor O (S ⊕ Unit)) : + (fold g a).val (place (Sum.map Sum.inl id) B) = (g.atSite a).val B := by + let e : (S ⊕ U) ⊕ Unit → S ⊕ U := Sum.elim id (fun _ => Sum.inr a) + change g.val (place e (place (Sum.map Sum.inl id) B)) = _ + rw [← place_comp, show e ∘ Sum.map Sum.inl id = Sum.map id (fun _ + => a) by funext i; cases i <;> rfl] + rfl + +/-- All evaluated tensors interpolate from above; radii satisfy the +squared-distance comparison with its strict convexity term. -/ +theorem segment (hc : SpectralComparison F) (g : Assignment f U) (o : S) (a b : U) (t : Fraction) : + ∃ p : Assignment f Unit, + (∀ B, p.val B ≤ (g.atSite a).val B ^ (1 - t.val) * (g.atSite b).val B ^ t.val) ∧ + radius hO o p ^ 2 ≤ (1 - t.val) * radius hO o (g.atSite a) ^ 2 + + t.val * radius hO o (g.atSite b) ^ 2 - + t.val * (1 - t.val) * dist hO g (.inr a) (.inr b) ^ 2 := by + let A := fold g a + let B := fold g b + obtain ⟨p, hp, ep, hu⟩ := (extensionData g.val g.mono).interpolate B.val A.val B.mono A.mono + B.old A.old t.2.1 t.2.2 + let k : Assignment g.val Unit := ⟨p, hp, ep⟩ + have hdist (i j : S ⊕ U) : dist hO k (.inl i) (.inl j) = dist hO g i j := by + unfold dist Tensor.dist + change Real.log (p (wire hO (.inl i) (.inl j) 2)) / _ = _ + rw [← place_wire hO Sum.inl, place_inl, ep] + rfl + have ev (i : S ⊕ U) (c : U) : + (fold g c).val (wire hO (.inl i) (.inr ()) 2) = g.val (wire hO i (.inr c) 2) := by + change g.val (place _ (wire hO _ _ _)) = _ + rw [place_wire] + rfl + have hd (i : S ⊕ U) : dist hO k (.inl i) (.inr ()) ≤ + (1 - t.val) * dist hO g i (.inr a) + t.val * dist hO g i (.inr b) := by + have h := hu (wire hO (.inl i) (.inr ()) 2) + change k.val _ ≤ (fold g b).val _ ^ _ * (fold g a).val _ ^ _ at h + rw [ev, ev, price_wire, price_wire, price_wire] at h + have hz : 0 < (2 : ℝ) := by norm_num + rw [← Real.rpow_mul hz.le, ← Real.rpow_mul hz.le, ← Real.rpow_add hz] at h + linarith only [(Real.rpow_le_rpow_left_iff (by norm_num : (1 : ℝ) < 2)).mp h] + have hm : Tensor.Between (k.point hO) (.inl (.inr a)) (.inr ()) (.inl (.inr b)) t := by + apply Tensor.between_of_le _ (k.point_mono hO) + · change dist hO k _ _ ≤ _ * dist hO k _ _ + simpa [hdist, dist_self] using hd (.inr a) + · rw [Tensor.dist_comm _ (Sum.inr ())] + change dist hO k _ _ ≤ _ * dist hO k _ _ + have e : dist hO g (.inr b) (.inr a) = dist hO g (.inr a) (.inr b) := Tensor.dist_comm _ _ _ + simpa [hdist, dist_self, e] using hd (.inr b) + let P := (g.chain k).pull Sum.inr + refine ⟨P, ?_, ?_⟩ + · intro X + rw [show P.val X = k.val _ from g.chain_right k X] + exact (hu _).trans_eq (by rw [mul_comm, fold_apply, fold_apply]) + · have hx : radius hO o P = dist hO k (.inl (.inl o)) (.inr ()) := by + unfold radius dist Tensor.dist + change Real.log (P.val (wire hO (.inl o) (.inr ()) 2)) / _ = _ + rw [show P.val _ = k.val _ from g.chain_right k _, place_wire] + rfl + have h := hc _ _ (k.point_mono hO) _ _ _ _ hm (.inl (.inl o)) + simp only [Tensor.dist_comm _ _ (Sum.inl (Sum.inl o))] at h + rw [hx, radius_atSite, radius_atSite, ← hdist, ← hdist, ← hdist] + exact h + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.Assignment +end + +/- +# Pinning by the distance to an anchor + +Feasibility is given by upper bounds on individual tensor evaluations. +Within a common assignment, two feasible sites minimizing the distance +to an anchor must coincide by geodesic comparison. Duplicating sites +then yields uniqueness of all joint prices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.Assignment +open ITensor Spectral Routing + +variable {F K S U V : Type} [Field F] [Field K] [Algebra F K] {O : Subring K} + [Fintype S] [Nonempty S] [DecidableEq S] [Fintype U] [DecidableEq U] + [Fintype V] [DecidableEq V] {f : ITensor O S →+* ℝ} + +/-- The condition `∀ i, g.val (A i) ≤ p i` on the specified data. -/ +def Supports {I : Type*} (g : Assignment f U) (A : I → ITensor O (S ⊕ U)) (p : I → ℝ) : Prop := + ∀ i, g.val (A i) ≤ p i + +/-- Constraints at distinct new sites can be imposed independently. -/ +theorem separate {I : Type*} (hf : Monotone f) (A : U → I → ITensor O (S ⊕ Unit)) + (p : U → I → ℝ) (hp : ∀ u, ∃ g : Assignment f Unit, g.Supports (A u) (p u)) : + ∃ g : Assignment f U, ∀ u, (g.atSite u).Supports (A u) (p u) := by + have H (t : Finset U) : ∃ g : Assignment f U, ∀ u ∈ t, (g.atSite u).Supports (A u) (p u) := by + induction t using Finset.induction_on with + | empty => + obtain ⟨g, hg, he⟩ := (extensionData (U := U) f hf).exists_extension + exact ⟨⟨g, hg, he⟩, by simp⟩ + | @insert u t hu ih => + obtain ⟨g, hg⟩ := ih + obtain ⟨k, hk⟩ := hp u + obtain ⟨q, h₁, h₂⟩ := g.combine k + let x (v : U) : U ⊕ Unit := if v = u then .inr () else .inl v + refine ⟨q.pull x, fun v hv => ?_⟩ + rw [pull_atSite] + rcases Finset.mem_insert.mp hv with hv | hv + · subst v + rw [show x u = .inr () from ite_eq_left rfl, ← pull_atSite, atUnit] + exact fun i => (h₂ _).trans (hk i) + · rw [show x v = .inl v from ite_eq_right (fun e : v = u => hu (e ▸ hv)), ← pull_atSite, + ext h₁] + exact hg v hv + obtain ⟨g, hg⟩ := H Finset.univ + exact ⟨g, fun u => hg u (Finset.mem_univ u)⟩ + +variable (hO : constants F K ≤ O) (o : S) {I : Type*} + +/-- Combine tensor constraints with an upper bound on the anchor distance. -/ +def pinned (A : I → ITensor O (S ⊕ Unit)) : Option I → ITensor O (S ⊕ Unit) + | none => wire hO (.inl o) (.inr ()) 2 + | some i => A i + +/-- In the case `none`, this construction gives `(2 : ℝ) ^ r`. -/ +def bounds (p : I → ℝ) (r : ℝ) : Option I → ℝ + | none => (2 : ℝ) ^ r + | some i => p i + +theorem pinned_iff (g : Assignment f Unit) (A : I → ITensor O (S ⊕ Unit)) (p : I → ℝ) (r : ℝ) : + g.Supports (pinned hO o A) (bounds p r) ↔ g.Supports A p ∧ radius hO o g ≤ r := by + have H : g.val (pinned hO o A none) ≤ bounds p r none ↔ radius hO o g ≤ r := by + rw [pinned, bounds, price_wire, Real.rpow_le_rpow_left_iff (by norm_num)] + rfl + exact ⟨fun h => ⟨fun i => h (some i), H.mp (h none)⟩, + fun h i => by cases i with + | none => exact H.mpr h.2 + | some i => exact h.1 i⟩ + +theorem pin_exists {J : Type*} [Nonempty J] (hf : Monotone f) + (A : J → I → ITensor O (S ⊕ Unit)) (p : I → ℝ) + (hp : ∀ j, ∃ g : Assignment f Unit, g.Supports (A j) p) : + ∃ r ∈ Set.Icc (0 : ℝ) 1, IsLeast + {v | ∀ j, ∃ g : Assignment f Unit, g.Supports (pinned hO o (A j)) (bounds p v)} r := by + let R := {v | ∀ j, ∃ g : Assignment f Unit, g.Supports (pinned hO o (A j)) (bounds p v)} + have hi : 1 ∈ R := fun j => by + obtain ⟨g, hg⟩ := hp j + exact ⟨g, (pinned_iff _ _ _ _ _ _).mpr ⟨hg, Tensor.dist_le_one _ (g.point_mono hO) _ _⟩⟩ + have lo : 0 ∈ lowerBounds R := by + intro r h + obtain ⟨g, hg⟩ := h (Classical.arbitrary J) + exact (dist_nonneg hO g _ _).trans ((pinned_iff _ _ _ _ _ _).mp hg).2 + have hb (i : Option I) : Continuous (fun v => bounds p v i) := by + cases i with + | none => simp only [bounds, Real.rpow_def_of_pos (by norm_num : (0 : ℝ) < 2)]; fun_prop + | some _ => exact continuous_const + have hw (w : List (Option I)) : Continuous (fun v => (w.map (bounds p v)).prod) := by + induction w with + | nil => exact continuous_const + | cons i w ih => exact (hb i).mul ih + have hc : IsClosed R := by + unfold R Supports + simp only [exists_iff hf, Set.ofPred_forall] + exact isClosed_iInter fun _ => isClosed_iInter fun w => isClosed_le continuous_const (hw w) + have hs := hc.isLeast_csInf ⟨1, hi⟩ ⟨0, lo⟩ + exact ⟨_, ⟨lo hs.1, hs.2 hi⟩, hs⟩ + +theorem mix_le {a b c : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (h : a ≤ c) (k : b ≤ c) + (t : Fraction) : a ^ (1 - t.val) * b ^ t.val ≤ c := by + have hc := ha.trans h + have ht := sub_nonneg.mpr t.2.2 + calc + _ ≤ c ^ (1 - t.val) * c ^ t.val := + mul_le_mul (Real.rpow_le_rpow ha h ht) (Real.rpow_le_rpow hb k t.2.1) + (Real.rpow_nonneg hb _) (Real.rpow_nonneg hc _) + _ = c := by rw [← Real.rpow_add_of_nonneg hc ht t.2.1, sub_add_cancel, Real.rpow_one] + +theorem pin_unique (hc : SpectralComparison F) (g : Assignment f U) + {A : I → ITensor O (S ⊕ Unit)} {p : I → ℝ} {r : ℝ} + (hlo : ∀ h : Assignment f Unit, h.Supports A p → r ≤ radius hO o h) + {x y : U} (hx : (g.atSite x).Supports (pinned hO o A) (bounds p r)) + (hy : (g.atSite y).Supports (pinned hO o A) (bounds p r)) : + dist hO g (.inr x) (.inr y) = 0 := by + obtain ⟨hx, hr⟩ := (pinned_iff _ _ _ _ _ _).mp hx + obtain ⟨hy, hr'⟩ := (pinned_iff _ _ _ _ _ _).mp hy + let t : Fraction := ⟨1 / 2, by norm_num⟩ + obtain ⟨k, hk, hd⟩ := segment hO hc g o x y t + have hb := hlo k fun i => (hk _).trans (mix_le ((g.atSite x).nonneg _) ((g.atSite y).nonneg _) + (hx i) (hy i) t) + rw [le_antisymm hr (hlo _ hx), le_antisymm hr' (hlo _ hy)] at hd + have hz : 0 ≤ r := (dist_nonneg hO (g.atSite x) _ _).trans hr + have hw := pow_le_pow_left₀ hz hb 2 + dsimp only [t] at hd + nlinarith only [hd, hw] + +theorem pins_equal (hc : SpectralComparison F) {g h : Assignment f U} + {A : U → I → ITensor O (S ⊕ Unit)} {p : I → ℝ} {r : ℝ} + (hlo : ∀ i (h : Assignment f Unit), h.Supports (A i) p → r ≤ radius hO o h) + (hg : ∀ i, (g.atSite i).Supports (pinned hO o (A i)) (bounds p r)) + (hh : ∀ i, (h.atSite i).Supports (pinned hO o (A i)) (bounds p r)) : g = h := by + have cmp (g h : Assignment f U) + (hg : ∀ i, (g.atSite i).Supports (pinned hO o (A i)) (bounds p r)) + (hh : ∀ i, (h.atSite i).Supports (pinned hO o (A i)) (bounds p r)) : + ∀ B, g.val B ≤ h.val B := by + obtain ⟨k, hl, hr⟩ := g.combine h + have e : k.pull Sum.inl = k.pull Sum.inr := by + apply pull_eq hO + intro i + apply pin_unique hO o hc k (hlo i) + · rw [← k.pull_atSite Sum.inl, ext hl] + exact hg i + · rw [← k.pull_atSite Sum.inr] + exact fun j => (hr _).trans (hh i j) + rw [← ext hl, e] + exact hr + exact ext fun B => le_antisymm (cmp g h hg hh B) (cmp h g hh hg B) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.Assignment +end + +/- +# Pinning a finite system of polynomial inequalities + +Use distance to an anchor as the objective. The minimal uniform +radius on the closed unit disk is also pointwise minimal at generic +parameters. We retain strict slack for continuity on smaller disks. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral Prices Motion K0 ITensor Assignment Filter + +variable (F E S I : Type) [Field F] [Field E] [Algebra F (K0 E)] + [Fintype S] [DecidableEq S] [Nonempty S] + +/-- The data for the problem construction, including `inc`, `f`, `mono`, `scal`, `o`. -/ +structure Problem where + inc : constants F (K0 E) ≤ RingOf E + /-- The `Problem` component of type `ITensor (RingOf E) S →+* ℝ`. -/ + f : ITensor (RingOf E) S →+* ℝ + mono : Monotone f + scal : ∀ (x : K0 E) (r : ℚ), val E x = ↑r → f (scalar _ _ x) = Real.exp (-(r : ℝ)) + /-- The `Problem` field of type `S`. -/ + o : S + /-- The `Problem` component of type `I → K0 E → ITensor (RingOf E) (S ⊕ Unit)`. -/ + A : I → K0 E → ITensor (RingOf E) (S ⊕ Unit) + poly : ∀ i, ∃ d, Family (A i) d + /-- The `Problem` component of type `I → ℝ`. -/ + p : I → ℝ + /-- The `Problem` component of type `I → ℝ`. -/ + q : I → ℝ + slack : ∀ i, p i < q i + feasible : ∀ x ∈ RingOf E, ∃ g : Assignment f Unit, g.Supports (fun i => A i x) p + /-- The `Problem` field of type `ℝ`. -/ + r : ℝ + bound : 0 ≤ r ∧ r ≤ 1 + least : IsLeast + {v | ∀ x ∈ RingOf E, ∃ g : Assignment f Unit, + g.Supports (pinned inc o (fun i => A i x)) (bounds q v)} r + +namespace Problem +variable {F E S I} (H : Problem F E S I) {U : Type} [Fintype U] [DecidableEq U] + +/-- The indexed operation `pinned H.inc H.o (fun i => H.A i x) j`. -/ +def pin (j : Option I) (x : K0 E) := pinned H.inc H.o (fun i => H.A i x) j + +theorem poly_pin (j : Option I) : ∃ d, Family (H.pin j) d := by + cases j with + | none => exact Family.constantValue _ + | some i => exact H.poly i + +/-- Computes the cap by the application `bounds H.q H.r`. -/ +def cap := bounds H.q H.r + +/-- The condition `∀ g : Assignment H.f Unit, g.Supports (fun i => H.A i x) H.q → H.r ≤ radius +H.inc H.o g` on the specified data. -/ +def minimal (x : K0 E) : Prop := + ∀ g : Assignment H.f Unit, g.Supports (fun i => H.A i x) H.q → H.r ≤ radius H.inc H.o g + +/-- The condition `∀ i, (g.atSite i).Supports (fun j => H.pin j (z i)) H.cap` on the specified +data. -/ +def Joint (z : U → K0 E) (g : Assignment H.f U) : Prop := + ∀ i, (g.atSite i).Supports (fun j => H.pin j (z i)) H.cap + +theorem joint_exists (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) : + ∃ g, H.Joint z g := separate H.mono _ _ (fun i => H.least.1 _ (hz i)) + +theorem joint_unique {z : U → K0 E} (hz : ∀ i, H.minimal (z i)) + {g k : Assignment H.f U} (hg : H.Joint z g) (hk : H.Joint z k) : g = k := + pins_equal H.inc H.o (Routing.spectralComparison F) hz hg hk + +theorem joint_pull {V : Type} [Fintype V] [DecidableEq V] {z : U → K0 E} + {g : Assignment H.f U} (hg : H.Joint z g) (e : V → U) : H.Joint (z ∘ e) (g.pull e) := by + intro i + rw [pull_atSite] + exact hg (e i) + +theorem generic_minimal [Finite I] (z : K0 E) (hz : z ∈ RingOf E) : + ∀ᶠ c : E in cocountable, H.minimal (z + C c) := by + let : Fintype I := Fintype.ofFinite I + have := cocountable_countable E + let A (w : List (Option I)) (x : K0 E) := (w.map (fun i => H.pin i (z + x))).prod + have hA (w : List (Option I)) : ∃ d, Family (A w) d := by + obtain ⟨d, h⟩ := Family.list_prod H.pin H.poly_pin w + simpa only [one_mul] using h.affine z 1 + have ht : ∀ᶠ c : E in cocountable, ∀ w, ∀ x ∈ RingOf E, + assisted (pad Unit) H.f (A w x) ≤ assisted (pad Unit) H.f (A w (C c)) := + eventually_countable_forall.mpr fun w => (hA w).choose_spec.assisted_max H.f H.mono + refine ht.mono fun c hc g hg => H.least.2 fun x hx => ?_ + let r := radius H.inc H.o g + have hv := (pinned_iff H.inc H.o g _ _ r).mpr ⟨hg, le_rfl⟩ + have hs := (Assignment.exists_iff H.mono _ _).mp ⟨g, hv⟩ + refine (Assignment.exists_iff H.mono _ _).mpr fun w => ?_ + have hd := hc w (x - z) ((RingOf E).sub_mem hx hz) + simp only [A, add_sub_cancel] at hd + exact hd.trans (hs w) + +end Problem +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- +# Generic joint profiles + +For each finite list of shifts, attach the original constraints at each +site and admit every ordinary tensor as a probe. There are only countably +many words of tests over the countable ground field. Outside a countable +set of translations the closed-power tests are simultaneously maximal. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +open Spectral ITensor Prices Motion K0 Assignment Filter + +variable {F E S I U V : Type} [Field F] [Field E] [Algebra F (K0 E)] + [Fintype S] [Nonempty S] [DecidableEq S] [Fintype U] [DecidableEq U] + (H : Problem F E S I) + +/-- Indexes the test by the coordinates of `(U × Option I) ⊕ Tensor F (S ⊕ U)`. -/ +abbrev Test (F S I U : Type) [Field F] [Fintype S] [Fintype U] := + (U × Option I) ⊕ Tensor F (S ⊕ U) + +/-- The test used in the `Problem` construction. -/ +def test (z : U → K0 E) : Test F S I U → ITensor (RingOf E) (S ⊕ U) + | .inl (i, j) => ITensor.place (Sum.map id (fun _ => i)) (H.pin j (z i)) + | .inr A => fromBase H.inc A + +/-- In the case `.inl (_, j)`, this construction gives `H.cap j`. -/ +def scores (p : Tensor F (S ⊕ U) → ℝ) : Test F S I U → ℝ + | .inl (_, j) => H.cap j + | .inr A => p A + +/-- Computes the measure by the application `assisted (pad U) H.f (w.map (H.test z)).prod`. -/ +def measure (z : U → K0 E) (w : List (Test F S I U)) : ℝ := + assisted (pad U) H.f (w.map (H.test z)).prod + +theorem supports_iff (z : U → K0 E) (p : Tensor F (S ⊕ U) → ℝ) : + (∃ g : Assignment H.f U, H.Joint z g ∧ ∀ A, g.point H.inc A ≤ p A) ↔ + ∀ w, H.measure z w ≤ (w.map (H.scores p)).prod := by + refine Iff.trans ?_ (Assignment.exists_iff H.mono (H.test z) (H.scores p)) + constructor + · rintro ⟨g, hg, hp⟩ + exact ⟨g, fun j => match j with + | .inl (i, j) => hg i j + | .inr A => hp A⟩ + · rintro ⟨g, hg⟩ + exact ⟨g, fun i j => hg (.inl (i, j)), fun A => hg (.inr A)⟩ + +theorem test_family (a b : U → K0 E) (w : List (Test F S I U)) : + ∃ d, Family (fun x => (w.map (H.test (fun i => a i + b i * x))).prod) d := by + refine Family.list_prod (fun j x => H.test (fun i => a i + b i * x) j) ?_ w + rintro (⟨i, j⟩|B) + · obtain ⟨d, h⟩ := H.poly_pin j + obtain ⟨e, h⟩ := h.affine (a i) (b i) + exact h.place (Sum.map id (fun _ => i)) + · exact Family.constantValue _ + +/-- Evaluates `z i + x` at the input `i`. -/ +def translate (z : U → K0 E) (x : K0 E) := fun i => z i + x + +/-- Requires `(∀ i, H.minimal (translate z x i)) ∧ ∀ w y, y ∈ RingOf E → H.measure (translate z +y) w ≤ H.measure (translate z x) w`. -/ +def Peak (z : U → K0 E) (x : K0 E) : Prop := + (∀ i, H.minimal (translate z x i)) ∧ + ∀ w y, y ∈ RingOf E → H.measure (translate z y) w ≤ H.measure (translate z x) w + +theorem controls {z : U → K0 E} {x y : K0 E} (hx : H.Peak z x) + (g : Assignment H.f U) (hg : H.Joint (translate z x) g) (hy : y ∈ RingOf E) : + ∃ h : Assignment H.f U, H.Joint (translate z y) h ∧ ∀ A, h.point H.inc A ≤ g.point H.inc A := by + refine (H.supports_iff _ _).mpr fun w => (hx.2 w y hy).trans ?_ + exact (H.supports_iff _ _).mp ⟨g, hg, fun _ => le_rfl⟩ w + +variable [Fintype I] [Countable F] + +omit [Fintype I] in +theorem generic_peak [Finite I] (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) : + ∀ᶠ c : E in cocountable, H.Peak z (C c) := by + let : Fintype I := Fintype.ofFinite I + have := cocountable_countable E + have := countable_tensor (K := F) (S := S ⊕ U) + have hmin := eventually_all.mpr (fun i => H.generic_minimal (z i) (hz i)) + have hw (w : List (Test F S I U)) : ∀ᶠ c : E in cocountable, + ∀ y ∈ RingOf E, H.measure (translate z y) w ≤ H.measure (translate z (C c)) w := by + obtain ⟨d, hd⟩ := H.test_family z (fun _ => 1) w + simp only [one_mul] at hd + exact hd.assisted_max H.f H.mono + exact hmin.and (eventually_countable_forall.mpr hw) + +variable [Uncountable E] + +omit [Fintype I] in +private theorem model_exists [Finite I] (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) : + ∃ (g : Assignment H.f U) (x : K0 E), x ∈ RingOf E ∧ H.Peak z x ∧ H.Joint (translate z x) g := by + let : Fintype I := Fintype.ofFinite I + have := cocountable_neBot E + obtain ⟨c, hc⟩ := (H.generic_peak z hz).exists + obtain ⟨g, hg⟩ := H.joint_exists _ (fun i => (RingOf E).add_mem (hz i) (C_mem c)) + exact ⟨g, C c, C_mem c, hc, hg⟩ + +/-- A chosen joint evaluation. Only integral shifts are used. -/ +def model (z : U → K0 E) : Assignment H.f U := by + have : Nonempty (Assignment H.f U) := + ⟨(H.joint_exists (fun _ => 0) (fun _ => (RingOf E).zero_mem)).choose⟩ + exact Classical.epsilon (fun g => ∃ x ∈ RingOf E, H.Peak z x ∧ H.Joint (translate z x) g) + +omit [Fintype I] in +theorem model_peak [Finite I] (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) : + ∃ x ∈ RingOf E, H.Peak z x ∧ H.Joint (translate z x) (H.model z) := + Classical.epsilon_spec (H.model_exists z hz) + +/-- The value specified by `(H.model z).point H.inc`. -/ +def price (z : U → K0 E) := (H.model z).point H.inc + +omit [Fintype I] in +theorem price_controls [Finite I] (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) {y : K0 E} + (hy : y ∈ RingOf E) : + ∃ g : Assignment H.f U, H.Joint (translate z y) g ∧ ∀ A, g.point H.inc A ≤ H.price z A := by + let : Fintype I := Fintype.ofFinite I + obtain ⟨x, _, hx, hg⟩ := H.model_peak z hz + exact H.controls hx _ hg hy + +omit [Fintype I] in +theorem price_eq [Finite I] (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) {x : K0 E} (hx : x ∈ RingOf E) + (hp : H.Peak z x) (g : Assignment H.f U) (hg : H.Joint (translate z x) g) : + H.price z = g.point H.inc := by + let : Fintype I := Fintype.ofFinite I + obtain ⟨h, hh, hb⟩ := H.price_controls z hz hx + rw [H.joint_unique hp.1 hh hg] at hb + obtain ⟨y, hy, hyp, hm⟩ := H.model_peak z hz + obtain ⟨k, hk, he⟩ := H.controls hp g hg hy + rw [H.joint_unique hyp.1 hk hm] at he + exact RingHom.ext fun A => le_antisymm (he A) (hb A) + +omit [Fintype I] in +theorem price_pull [Finite I] [Fintype V] [DecidableEq V] + (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) (e : V → U) (A : Tensor F (S ⊕ V)) : + H.price (z ∘ e) A = H.price z (Tensor.place (Sum.map id e) A) := by + let : Fintype I := Fintype.ofFinite I + have := cocountable_neBot E + have hy (i) : (z ∘ e) i ∈ RingOf E := hz _ + obtain ⟨c, h₁, h₂⟩ := ((H.generic_peak z hz).and (H.generic_peak _ hy)).exists + obtain ⟨g, hg, _⟩ := H.price_controls z hz (C_mem c) + rw [H.price_eq z hz _ h₁ g hg, H.price_eq (z ∘ e) hy _ h₂ (g.pull e) (H.joint_pull hg e)] + · exact congrArg g.val (place_fromBase H.inc _ A) + all_goals exact C_mem _ + +omit [Fintype I] in +theorem price_shift [Finite I] (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) + {x : K0 E} (hx : x ∈ RingOf E) : + H.price (translate z x) = H.price z := by + let : Fintype I := Fintype.ofFinite I + have hh i : translate z x i ∈ RingOf E := (RingOf E).add_mem (hz i) hx + obtain ⟨c, hc, hp, hg⟩ := H.model_peak z hz + have he (y : K0 E) : translate (translate z x) y = translate z (x + y) := by + funext i; exact add_assoc _ _ _ + have he' : translate (translate z x) (c - x) = translate z c := by rw [he, add_sub_cancel] + refine H.price_eq _ hh ((RingOf E).sub_mem hc hx) ?_ _ (by rw [he']; exact hg) + unfold Peak + rw [he'] + exact ⟨hp.1, fun w y hy => by rw [he]; exact hp.2 w _ ((RingOf E).add_mem hx hy)⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +end + +/- +# Submean estimates for pinned prices + +Genericity is needed uniformly over words of probes. For a given +word take the supremum over the common translation first. Rational +thresholds reduce this extra supremum to countably many comparisons. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +open Spectral ITensor Prices Motion K0 Assignment Filter + +variable {F E S I U : Type} [Field F] [Field E] [Algebra F (K0 E)] + [Fintype S] [Nonempty S] [DecidableEq S] [Fintype U] [DecidableEq U] + (H : Problem F E S I) + +/-- Evaluates `a i + b i * x` at the input `i`. -/ +def aff (a b : U → K0 E) (x : K0 E) := fun i => a i + b i * x + +theorem affine_family (a b : U → K0 E) (w : List (Test F S I U)) (y : K0 E) : + ∃ d, Family (fun x => (w.map (H.test (translate (aff a b x) y))).prod) d := by + have e (x) : translate (aff a b x) y = fun i => (a i + y) + b i * x := by + funext i + exact add_right_comm _ _ _ + simp_rw [e] + exact H.test_family _ _ w + +theorem cap_pos (j : Option I) : 0 < H.cap j := by + cases j with + | none => exact Real.rpow_pos_of_pos (by norm_num) _ + | some i => + obtain ⟨g, hg⟩ := H.feasible 0 (RingOf E).zero_mem + exact ((g.nonneg _).trans (hg i)).trans_lt (H.slack i) + +variable [Fintype I] [Countable F] [Uncountable E] + +/-- In the case `.inl (_, i)`, this construction gives `Real.log (H.cap i)`. -/ +def charge (z : U → K0 E) : Test F S I U → ℝ + | .inl (_, i) => Real.log (H.cap i) + | .inr A => Real.log (H.price z A) + +omit [Fintype I] in +private theorem word_bound [Finite I] (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) + (w : List (Test F S I U)) (y : K0 E) (hy : y ∈ RingOf E) : + H.measure (translate z y) w ≤ Real.exp (w.map (H.charge z)).sum := by + let : Fintype I := Fintype.ofFinite I + let p (A : Tensor F (S ⊕ U)) := Real.exp (Real.log (H.price z A)) + obtain ⟨g, hg, hp⟩ := H.price_controls z hz hy + have h (A) : g.point H.inc A ≤ p A := by + by_cases ha : A = 0 + · simp [ha, p] + unfold p + have hpos : 0 < H.price z A := zero_lt_one.trans_le (Tensor.value_one_le ((H.model + z).point_mono H.inc) ha) + rw [Real.exp_log hpos] + exact hp A + have he (i : Test F S I U) : H.scores p i = Real.exp (H.charge z i) := by + rcases i with ⟨j, i⟩ | A + · exact (Real.exp_log (H.cap_pos i)).symm + · rfl + refine ((H.supports_iff _ p).mp ⟨g, hg, h⟩ w).trans_eq ?_ + induction w with + | nil => simp + | cons i w ih => simp only [List.map_cons, List.sum_cons, List.prod_cons, Real.exp_add, he, ih] + +omit [Fintype I] in +private theorem generic_affine [Finite I] (a b : U → K0 E) + (hz : ∀ x ∈ RingOf E, ∀ i, aff a b x i ∈ RingOf E) : + ∀ᶠ c : E in cocountable, ∀ w, ∀ x ∈ RingOf E, ∀ y ∈ RingOf E, + H.measure (translate (aff a b x) y) w ≤ Real.exp (w.map (H.charge (aff a b (C c)))).sum := by + let : Fintype I := Fintype.ofFinite I + have := countable_tensor (K := F) (S := S ⊕ U) + let A (w : List (Test F S I U)) (y : RingOf E) (x : K0 E) := + (w.map (H.test (translate (aff a b x) y))).prod + have hA w y : ∃ d, Family (A w y) d := H.affine_family a b w y.val + refine (generic_bounds H.f H.mono A hA).mono fun c hc w x hx y hy => ?_ + exact hc w _ (fun j => H.word_bound _ (hz _ (C_mem c)) w _ j.2) ⟨y, hy⟩ x hx + +omit [Fintype I] in +private theorem profile_bound [Finite I] {J : Type} [Fintype J] (w : J → ℝ) (hw : ∑ j, w j = 1) + (z : U → K0 E) (hz : ∀ i, z i ∈ RingOf E) (v : J → U → K0 E) + (h : ∀ l, ∀ y ∈ RingOf E, H.measure (translate z y) l ≤ + Real.exp (∑ j, w j * (l.map (H.charge (v j))).sum)) (A : Tensor F (S ⊕ U)) : + Real.log (H.price z A) ≤ ∑ j, w j * Real.log (H.price (v j) A) := by + let : Fintype I := Fintype.ofFinite I + let p (A : Tensor F (S ⊕ U)) := Real.exp (∑ j, w j * Real.log (H.price (v j) A)) + have e (i : Test F S I U) : Real.exp (∑ j, w j * H.charge (v j) i) = H.scores p i := by + rcases i with ⟨j, i⟩ | B + · simp only [charge, scores, ← Finset.sum_mul, hw, one_mul, Real.exp_log (H.cap_pos i)] + · rfl + have e' (l : List (Test F S I U)) : + Real.exp (∑ j, w j * (l.map (H.charge (v j))).sum) = (l.map (H.scores p)).prod := by + induction l with + | nil => simp + | cons i l ih => + simp only [List.map_cons, List.sum_cons, List.prod_cons, mul_add, Finset.sum_add_distrib, + Real.exp_add, e, ih] + obtain ⟨x, hx, hp, _⟩ := H.model_peak z hz + obtain ⟨g, hg, he⟩ := (H.supports_iff _ _).mpr fun l => (h l x hx).trans_eq (e' l) + by_cases ha : A = 0 + · simp [ha] + rw [H.price_eq z hz hx hp g hg, Real.log_le_iff_le_exp + (zero_lt_one.trans_le (Tensor.value_one_le (g.point_mono H.inc) ha))] + exact he A + +omit [Fintype I] in +theorem star [Finite I] (a b : U → K0 E) (x : K0 E) (hx : x ∈ RingOf E) {n : ℕ} + (c : Fin n → K0 E) (r : Option (Fin n) → ℚ) + (hc : ∀ j, 0 ≤ val E (c j)) (hd : ∀ i j, i ≠ j → val E (c i - c j) = 0) + (hr : ∀ j, 0 < r j) (hz : ∀ i, aff a b x i ∈ RingOf E) + (he : ∀ j y, y ∈ RingOf E → ∀ i, aff a b (armEnd c r y j) i ∈ RingOf E) : + ∀ᶠ u : E in cocountable, ∀ A : Tensor F (S ⊕ U), + Real.log (H.price (aff a b x) A) ≤ + ∑ j, weight r j * Real.log (H.price (aff a b (armEnd c r (C u) j)) A) := by + let : Fintype I := Fintype.ofFinite I + let e j y := aff a b (armEnd c r y j) + have affine (j) : ∃ a' b', e j = aff a' b' := by + cases j with + | none => + refine ⟨a, fun i => b i * t (-r none), ?_⟩ + funext y i + simp [e, aff, armEnd, mul_assoc] + | some j => + refine ⟨(fun i => a i + b i * c j), fun i => b i * t (r (some j)), ?_⟩ + funext y i + simp [e, aff, armEnd, mul_add, mul_assoc, add_assoc] + have ends (j) : ∀ᶠ u : E in cocountable, ∀ w, + ∀ y ∈ RingOf E, ∀ z ∈ RingOf E, H.measure (translate (e j y) z) w ≤ + Real.exp (w.map (H.charge (e j (C u)))).sum := by + obtain ⟨v, w, eq⟩ := affine j + have h : ∀ y ∈ RingOf E, ∀ i, e j y i ∈ RingOf E := he j + rw [eq] at h ⊢ + exact H.generic_affine v w h + refine (eventually_all.mpr ends).mono fun u hu => H.profile_bound _ (weight_sum hr) _ hz _ ?_ + intro l y hy + obtain ⟨d, h⟩ := H.affine_family a b l y + let R j := (l.map (H.charge (e j (C u)))).sum + let μ := ∑ j, weight r j * R j + refine h.assisted_star H.f H.mono H.scal c hc hd r hr R (fun j z hz => hu j l z hz y hy) + μ ?_ x hx + have eq : (∑ j, (μ - R j) / (r j : ℝ)) = 0 := by + have hp : 0 < ∑ j, (r j : ℝ)⁻¹ := + Finset.sum_pos (fun j _ => inv_pos.mpr (Rat.cast_pos.mpr (hr j))) Finset.univ_nonempty + have h : μ * (∑ j, (r j : ℝ)⁻¹) = ∑ j, (r j : ℝ)⁻¹ * R j := by + simp only [μ, weight, div_mul_eq_mul_div, ← Finset.sum_div, div_mul_cancel₀ _ hp.ne'] + simp only [sub_mul, Finset.sum_sub_distrib, div_eq_mul_inv, ← Finset.mul_sum, h, + mul_comm (R _), sub_self] + exact eq.ge + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +end + +/- +# Continuity of minimizing sites + +The midpoint of two separated minimizers saves squared radius. A +small interpolation towards a strictly feasible site uses part of +that saving to absorb the change in the polynomial constraints. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +open Spectral Prices Motion K0 ITensor Assignment Routing + +variable {F E S I : Type} [Field F] [Field E] [Algebra F (K0 E)] + [Fintype S] [DecidableEq S] [Nonempty S] [Fintype I] (H : Problem F E S I) + +omit [Fintype I] in +private theorem absorb (x : K0 E) (hx : x ∈ RingOf E) (t : Fraction) + (k : Assignment H.f Unit) + (hk : ∀ i, k.val (H.A i x) ≤ H.q i + t.val * (H.q i - H.p i)) (h : H.minimal x) : + H.r ^ 2 ≤ radius H.inc H.o k ^ 2 + t.val := by + obtain ⟨p, hp⟩ := H.feasible x hx + obtain ⟨b, b₁, b₂⟩ := k.combine p + let q := b.atSite (.inr ()) + have hq : q.Supports (fun i => H.A i x) H.p := by + unfold q + rw [← b.pull_atSite Sum.inr, atUnit] + exact fun i => (b₂ _).trans (hp i) + obtain ⟨c, hc, hr⟩ := segment H.inc (spectralComparison F) b H.o (.inl ()) (.inr ()) t + rw [← b.pull_atSite Sum.inl, atUnit, Assignment.ext b₁] at hc hr + have ht := t.property.1 + have ht' := sub_nonneg.mpr t.property.2 + have hcost : c.Supports (fun i => H.A i x) H.q := by + intro i + let A := H.A i x + have hg := Real.geom_mean_le_arith_mean2_weighted ht' ht (k.nonneg A) (q.nonneg A) + (sub_add_cancel 1 t.val) + have h₁ := mul_le_mul_of_nonneg_left (hk i) ht' + have h₂ := mul_le_mul_of_nonneg_left (hq i) ht + have h₃ := mul_nonneg (sq_nonneg t.val) (sub_nonneg.mpr (H.slack i).le) + change c.val A ≤ H.q i + unfold A at * + linarith only [(hc _).trans hg, h₁, h₂, h₃] + have hr' := pow_le_pow_left₀ H.bound.1 (h c hcost) 2 + have h₁ : radius H.inc H.o q ≤ 1 := Tensor.dist_le_one _ (q.point_mono H.inc) _ _ + have h₂ : 0 ≤ radius H.inc H.o q := Assignment.dist_nonneg H.inc _ _ _ + have h₃ := mul_le_mul_of_nonneg_left (pow_le_pow_left₀ h₂ h₁ 2) ht + have h₄ := mul_nonneg ht (sq_nonneg (radius H.inc H.o k)) + have h₅ := mul_nonneg (mul_nonneg ht ht') + (sq_nonneg (dist H.inc b (.inr (.inl ())) (.inr (.inr ())))) + unfold q at h₃ + linarith only [hr', hr, h₃, h₄, h₅] + +omit [Fintype I] in +theorem continuity [Finite I] (ε : ℝ) (hε : 0 < ε) : + ∃ N : ℚ, 0 < N ∧ ∀ (z : Bool → K0 E) (g : Assignment H.f Bool), + (∀ i, z i ∈ RingOf E) → ↑N ≤ val E (z true - z false) → + (∀ i, H.minimal (z i)) → H.Joint z g → dist H.inc g (.inr true) (.inr false) ≤ ε := by + let : Fintype I := Fintype.ofFinite I + let t : Fraction := ⟨min (ε ^ 2 / 8) 1, le_min (by positivity) zero_le_one, min_le_right _ _⟩ + have ht : 0 < t.val := lt_min (by positivity) zero_lt_one + let δ i := t.val * (H.q i - H.p i) + have hd i : 0 < δ i := mul_pos ht (sub_pos.mpr (H.slack i)) + choose m _ hm using fun i => (H.poly i).choose_spec.uniform_continuous (hd i) + obtain ⟨N, hN⟩ := (Set.finite_range m).bddAbove + refine ⟨max N 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), fun z g hz hv hl hp => ?_⟩ + have hb (b : Bool) := (pinned_iff H.inc H.o (g.atSite b) _ _ _).mp (hp b) + have hr (b : Bool) : radius H.inc H.o (g.atSite b) = H.r := + le_antisymm (hb b).2 (hl b _ (hb b).1) + let u : Fraction := ⟨1 / 2, by norm_num⟩ + obtain ⟨k, hk, hr'⟩ := segment H.inc (spectralComparison F) g H.o true false u + rw [hr, hr] at hr' + have hq (i : I) : k.val (H.A i (z true)) ≤ H.q i + δ i := by + let j := g.atSite false + have hv' : ↑(m i) ≤ val E (z true - z false) := + (WithTop.coe_le_coe.mpr ((hN ⟨i, rfl⟩).trans (le_max_left _ _))).trans hv + have he (a : K0 E) (r : ℚ) (ha : val E a = ↑r) : + j.val (scalar (RingOf E) _ a) = Real.exp (-(r : ℝ)) := by + rw [← pad_scalar, j.old, H.scal _ _ ha] + have hdiff := (abs_sub_le_iff.mp (hm i j.val j.mono he _ _ (hz true) (hz false) hv')).1 + have h₁ := (hb true).1 i + have h₂ := (hb false).1 i + refine (hk _).trans (mix_le ((g.atSite true).nonneg _) ((g.atSite false).nonneg _) ?_ ?_ u) + · exact h₁.trans (le_add_of_nonneg_right (hd i).le) + · unfold j at hdiff + exact (sub_le_iff_le_add'.mp hdiff).trans (add_le_add_left h₂ _) + have hk' := H.absorb (z true) (hz true) t k hq (hl true) + have hh : t.val ≤ ε ^ 2 / 8 := min_le_left _ _ + dsimp only [u] at hr' + nlinarith only [hk', hr', hh, hε] + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Extension.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Extension.lean new file mode 100644 index 0000000000..cf07dc8df1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Extension.lean @@ -0,0 +1,470 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Restriction +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Semiring +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Padding +public import Mathlib.Logic.Equiv.Prod +public import Mathlib.Algebra.Order.Archimedean.Real.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Path +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Tensor + +/-! # The integral restriction semiring -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral + +section +variable {K S : Type} [CommRing K] [Fintype S] {O : Subring K} (A B C : Raw K S) + +theorem comm_add : (equiv O).r (A + B) (B + A) := + relabel_of_relabels (Raw.comm_add_relabels A B) + +theorem assoc_add : (equiv O).r ((A + B) + C) (A + (B + C)) := + relabel_of_relabels (Raw.assoc_add_relabels A B C) + +theorem nil_add : (equiv O).r (0 + A) (A) := + relabel_of_relabels (Raw.nil_add_relabels A) + +theorem comm_mul : (equiv O).r (A * B) (B * A) := + relabel_of_relabels (Raw.comm_mul_relabels A B) + +theorem assoc_mul : (equiv O).r ((A * B) * C) (A * (B * C)) := + relabel_of_relabels (Raw.assoc_mul_relabels A B C) + +theorem unit_mul : (equiv O).r (1 * A) (A) := + relabel_of_relabels (Raw.unit_mul_relabels A) + +theorem nil_mul : (equiv O).r (0 * A) (0) := + relabel_of_relabels (Raw.nil_mul_relabels A) + +theorem distrib_left : (equiv O).r (A * (B + C)) (A * B + A * C) := + relabel_of_relabels (Raw.distrib_left_relabels A B C) + +end + +/-- Coefficient tensors modulo mutual local linear restriction. -/ +def ITensor {K : Type} [CommRing K] (O : Subring K) (S : Type) [Fintype S] := + Quotient (equiv O (S := S)) + +namespace ITensor + +variable {K S : Type} [CommRing K] [Fintype S] {O : Subring K} + +/-- Sends the representative to its class in the quotient. -/ +def ofRaw (A : Raw K S) : ITensor O S := Quotient.mk _ A + +theorem ofRaw_eq {A B : Raw K S} (h : (equiv O).r A B) : ofRaw (O := O) A = ofRaw B := + Quotient.sound h + +instance : LE (ITensor O S) := + Raw.quotientLE (equiv O) (Restricts O) (fun _ _ => Iff.rfl) + (fun h g => Restricts.trans h g) + +theorem ofRaw_le (A B : Raw K S) : ofRaw (O := O) A ≤ ofRaw B ↔ Restricts O B A := Iff.rfl + +instance : PartialOrder (ITensor O S) := + Raw.quotientOrder (equiv O) (Restricts O) (fun _ _ => Iff.rfl) Restricts.refl + (fun h g => Restricts.trans h g) + +instance : Zero (ITensor O S) := ⟨ofRaw 0⟩ +instance : One (ITensor O S) := ⟨ofRaw 1⟩ + +instance : Add (ITensor O S) := + ⟨Raw.quotientOperation (equiv O) (· + ·) fun h g => ⟨h.1.add g.1, h.2.add g.2⟩⟩ + +instance : Mul (ITensor O S) := + ⟨Raw.quotientOperation (equiv O) (· * ·) fun h g => ⟨h.1.mul g.1, h.2.mul g.2⟩⟩ + +theorem ofRaw_add (A B : Raw K S) : ofRaw (O := O) (A + B) = ofRaw A + ofRaw B := rfl +theorem ofRaw_mul (A B : Raw K S) : ofRaw (O := O) (A * B) = ofRaw A * ofRaw B := rfl + +instance : CommSemiring (ITensor O S) := by + let laws : CommSemiring (ITensor O S) := + Raw.quotientSemiring (equiv O) + (fun h g => ⟨h.1.add g.1, h.2.add g.2⟩) + (fun h g => ⟨h.1.mul g.1, h.2.mul g.2⟩) relabel_of_relabels + exact { laws with + add := (· + ·) + mul := (· * ·) + zero := 0 + one := 1 } + +theorem comm_add (A B : ITensor O S) : A + B = B + A := add_comm A B + +theorem comm_mul (A B : ITensor O S) : A * B = B * A := mul_comm A B + +theorem distrib_left (A B C : ITensor O S) : A * (B + C) = A * B + A * C := + (inferInstance : CommSemiring (ITensor O S)).left_distrib A B C + +theorem add_le_add_right (A B C : ITensor O S) : A ≤ B → A + C ≤ B + C := + Quotient.inductionOn₃ A B C fun _ _ c h => Restricts.add h (.refl c) + +theorem mul_le_mul_left (A B C : ITensor O S) : A ≤ B → C * A ≤ C * B := + Quotient.inductionOn₃ A B C fun _ _ c h => Restricts.mul (.refl c) h + +end ITensor +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- # Integral restrictions to a padded tensor -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral Raw + +variable {K S U : Type} [CommRing K] [Fintype S] [Fintype U] [Nonempty S] {O : Subring K} + +/-- The condition `∀ u y, v u y ∈ O` on the specified data. -/ +def Integral {A : Raw K (S ⊕ U)} (O : Subring K) (v : A.Covectors) : Prop := + ∀ u y, v u y ∈ O + +theorem restricts_pad (A : Raw K (S ⊕ U)) (B : Raw K S) : + Restricts O A (pad U B) ↔ ∃ v : A.Covectors, Integral O v ∧ Restricts O (A.close v) B := by + constructor + · rintro ⟨L, hl, h⟩ + exact ⟨Raw.padCovectors (B := B) L, fun u y => hl (.inr u) () y, + fun s => L (.inl s), fun s => hl (.inl s), (Raw.pad_coefficients_iff A B L).mp h⟩ + · rintro ⟨v, hv, L, hl, h⟩ + refine ⟨Raw.padMaps v L, ?_, (Raw.pad_coefficients_iff A B (Raw.padMaps v L)).mpr h⟩ + rintro (s | u) x y + · exact hl s x y + · exact hv u y + +theorem pad_restricts (A B : Raw K S) : + Restricts O (pad U A) (pad U B) ↔ Restricts O A B := by + classical + rw [restricts_pad] + constructor + · rintro ⟨v, hv, h⟩ + suffices Restricts O A ((pad U A).close v) from this.trans h + refine ⟨Raw.closePadMap A v, ?_, Raw.close_pad_coefficients A v⟩ + intro s x y + have product_mem : (∏ u, v u ()) ∈ O := O.prod_mem fun u _ => hv u () + unfold Raw.closePadMap Raw.weight + split_ifs <;> simp [product_mem] + · intro h + have eq : (equiv O).r ((pad U A).close (fun _ _ => 1)) A := + relabel_of_relabels (Raw.close_pad_one_relabels (U := U) A) + exact ⟨fun _ _ => 1, fun _ _ => O.one_mem, eq.1.trans h⟩ + +theorem close_add (A B : Raw K (S ⊕ U)) (v : (A + B).Covectors) : + (equiv O).r ((A + B).close v) + (A.close (fun u x => v u (.inl x)) + B.close (fun u x => v u (.inr x))) := + relabel_of_relabels (Raw.close_add_relabels A B v) + +theorem close_mul (A : Raw K S) (B : Raw K (S ⊕ U)) (v : (pad U A * B).Covectors) : + (equiv O).r ((pad U A * B).close v) (A * B.close (fun u x => v u ((), x))) := + relabel_of_relabels (Raw.close_mul_relabels A B v) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- # Adding sites using integral restrictions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral Raw + +variable {K S : Type} [CommRing K] [Fintype S] (U : Type) [Fintype U] {O : Subring K} + +theorem pad_zero : (equiv O).r (pad U (0 : Raw K S)) 0 := by + let : IsEmpty (pad U (0 : Raw K S)).term := inferInstanceAs (IsEmpty Empty) + let : IsEmpty (0 : Raw K (S ⊕ U)).term := inferInstanceAs (IsEmpty Empty) + constructor <;> + exact ⟨fun _ _ _ => 0, fun _ _ _ => O.zero_mem, + Raw.empty_terms_restriction (fun _ _ _ => 0)⟩ + +theorem pad_one : (equiv O).r (pad U (1 : Raw K S)) 1 := + relabel_of_relabels (Raw.pad_one_relabels U) + +theorem pad_mul (A B : Raw K S) : (equiv O).r (pad U (A * B)) (pad U A * pad U B) := + relabel_of_relabels (Raw.pad_mul_relabels U A B) + +theorem pad_add (A B : Raw K S) : Restricts O (pad U A + pad U B) (pad U (A + B)) := by + classical + refine ⟨Raw.padAddMap U A B, ?_, Raw.pad_add_coeff U A B⟩ + rintro (s | u) x y + · change A.leg s ⊕ B.leg s at x y + change (if y = x then (1 : K) else 0) ∈ O + split_ifs <;> simp + · exact O.one_mem + +namespace ITensor + +variable [Nonempty S] + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def pad : ITensor O S → ITensor O (S ⊕ U) := + Quotient.map (Raw.pad U) fun _ _ h => + ⟨(pad_restricts _ _).mpr h.1, (pad_restricts _ _).mpr h.2⟩ + +theorem pad_ofRaw (A : Raw K S) : pad U (ofRaw (O := O) A) = ofRaw (Raw.pad U A) := rfl + +theorem pad_le_ofRaw_iff (s : ITensor O S) (A : Raw K (S ⊕ U)) : + pad U s ≤ ofRaw A ↔ ∃ v : A.Covectors, Integral O v ∧ s ≤ ofRaw (A.close v) := + Quotient.inductionOn s fun a => restricts_pad A a + +theorem pad_close_le (A : Raw K (S ⊕ U)) (v : A.Covectors) (h : Integral O v) : + pad U (ofRaw (O := O) (A.close v)) ≤ ofRaw A := + (pad_le_ofRaw_iff U _ A).mpr ⟨v, h, le_rfl⟩ + +theorem padding : Prices.Padding (pad (O := O) (S := S) U) where + zero := ofRaw_eq (pad_zero U) + one := ofRaw_eq (pad_one U) + le_iff s t := Quotient.inductionOn₂ s t fun a b => pad_restricts b a + mul s t := Quotient.inductionOn₂ s t fun a b => ofRaw_eq (pad_mul U a b) + add_le s t := Quotient.inductionOn₂ s t fun a b => pad_add U a b + split {s x y} := by + refine Quotient.inductionOn₂ x y fun A B h => ?_ + obtain ⟨v, hi, hv⟩ := (pad_le_ofRaw_iff U s (A + B)).mp h + rw [ofRaw_eq (close_add _ _ v), ofRaw_add] at hv + exact ⟨_, _, pad_close_le U A _ (fun t z => hi t (.inl z)), + pad_close_le U B _ (fun t z => hi t (.inr z)), hv⟩ + factor {s a x} := by + refine Quotient.inductionOn₂ a x fun A B h => ?_ + obtain ⟨v, hi, hv⟩ := (pad_le_ofRaw_iff U s (Raw.pad U A * B)).mp h + rw [ofRaw_eq (close_mul _ _ v), ofRaw_mul] at hv + exact ⟨_, pad_close_le U B _ (fun t z => hi t ((), z)), hv⟩ + +end ITensor +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- # Integral selection of coefficients and the price of a scalar -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral + +variable {K S U : Type} [Fintype S] [Nonempty S] [Fintype U] + +section +variable [CommRing K] {O : Subring K} + +theorem zero_le (A : ITensor O S) : 0 ≤ A := by + refine Quotient.inductionOn A fun a => ?_ + exact ⟨fun _ x => x.elim, fun _ x => x.elim, fun x => (x (Classical.arbitrary S)).elim⟩ + +theorem ofRaw_eq_zero (A : Raw K S) : ofRaw (O := O) A = 0 ↔ ∀ x, A.coeff x = 0 := by + constructor + · intro h + have h' : Restricts O 0 A := h.le + exact (Raw.zero_restricts_iff A).mp h'.forget + · intro h + apply le_antisymm _ (zero_le _) + refine ⟨fun _ _ _ => 0, fun _ _ _ => O.zero_mem, fun x => ?_⟩ + exact (h x).trans (Finset.sum_eq_zero fun i _ => Empty.elim i).symm + +/-- The indexed operation `ofRaw (Raw.ofTable (fun _ => Unit) (fun _ => c))`. -/ +def scalar (O : Subring K) (S : Type) [Fintype S] [Nonempty S] (c : K) : ITensor O S := + ofRaw (Raw.ofTable (fun _ => Unit) (fun _ => c)) + +theorem scalar_one : scalar O S 1 = 1 := by + apply ofRaw_eq + refine equiv_coeff (fun _ => Equiv.refl Unit) fun x => ?_ + erw [Raw.coeff_ofTable] + change 1 = ∑ _ : Unit, ∏ _ : S, (1 : K) + simp + +theorem scalar_mul (c d : K) : scalar O S (c * d) = scalar O S c * scalar O S d := by + apply ofRaw_eq + refine equiv_coeff (fun _ => (Equiv.punitProd Unit).symm) fun x => ?_ + erw [Raw.coeff_mul, Raw.coeff_ofTable, Raw.coeff_ofTable, Raw.coeff_ofTable] + +theorem pad_scalar (c : K) : pad U (scalar O S c) = scalar O (S ⊕ U) c := by + apply ofRaw_eq + let e (s : S ⊕ U) : (Raw.pad U (Raw.ofTable (fun _ : S => Unit) (fun _ => c))).leg s ≃ Unit := + match s with + | .inl _ => Equiv.refl Unit + | .inr _ => Equiv.refl Unit + refine equiv_coeff e fun x => ?_ + erw [Raw.pad_coeff, Raw.coeff_ofTable, Raw.coeff_ofTable] + +theorem scalar_coeff (A : Raw K S) (x : ∀ s, A.leg s) : + scalar O S (A.coeff x) ≤ ofRaw A := + Restricts.pullback (fun s _ => x s) (fun y => Raw.coeff_ofTable _ _ y) + +end + +variable [Field K] {O : Subring K} + +theorem positive_scalar (f : ITensor O S →+* ℝ) (hf : Monotone f) (c : K) (h : c ≠ 0) : + 0 < f (scalar O S c) := by + apply lt_of_le_of_ne + · simpa using hf (zero_le (scalar O S c)) + intro hz + have he := congrArg f (scalar_mul (S := S) (O := O) c c⁻¹) + rw [mul_inv_cancel₀ h, scalar_one, map_one, map_mul, ← hz, zero_mul] at he + exact one_ne_zero he + +theorem lower_bound (f : ITensor O S →+* ℝ) (hf : Monotone f) + (A : ITensor O (S ⊕ U)) (hA : A ≠ 0) : ∃ B, pad U B ≤ A ∧ 0 < f B := by + revert hA + refine Quotient.inductionOn A fun a ha => ?_ + obtain ⟨x, hx⟩ := not_forall.mp fun he => ha ((ofRaw_eq_zero a).mpr he) + exact ⟨scalar O S (a.coeff x), by rw [pad_scalar]; exact scalar_coeff a x, + positive_scalar f hf _ hx⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- # Coordinate expansion with integral substitutions -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral + +variable {K S : Type} [Field K] [Fintype S] [Nonempty S] + (O : Subring K) (X : S → Type) [∀ s, Fintype (X s)] + +/-- Computes the table by the application `ofRaw (Raw.ofTable X f)`. -/ +def table (f : (∀ s, X s) → K) : ITensor O S := ofRaw (Raw.ofTable X f) + +theorem table_coeff (A : Raw K S) : table O A.leg A.coeff = ofRaw A := + ofRaw_eq (equiv_coeff (fun _ => Equiv.refl _) (Raw.coeff_ofTable _ _)) + +theorem table_zero : table O X 0 = 0 := + (ofRaw_eq_zero _).mpr (fun x => Raw.coeff_ofTable _ _ x) + +theorem table_add (f g : (∀ s, X s) → K) : table O X (f + g) ≤ table O X f + table O X g := by + classical + let P := Raw.ofTable X f + let Q := Raw.ofTable X g + let R := Raw.ofTable X (f + g) + let L (s : S) (x : X s) (y : X s ⊕ X s) := if Sum.elim id id y = x then (1 : K) else 0 + refine ⟨L, ?_, fun x => ?_⟩ + · intro s x y + change X s at x + change X s ⊕ X s at y + unfold L + split_ifs <;> simp + · change ∀ s, X s at x + change R.coeff x = (P + Q).applyLocal (B := R) L x + erw [Raw.applyLocal_add, Raw.coeff_ofTable] + have hs (t : (∀ s, X s) → K) : + (Raw.ofTable X t).applyLocal (B := R) + (fun s (a b : X s) => if b = a then 1 else 0) x = t x := by + let T := Raw.ofTable X t + change (∑ i : T.term, ∏ s, ∑ y : X s, (if y = x s then (1 : K) else 0) * T.factor i s y) = _ + have step (s : S) (q : X s → K) : (∑ y, (if y = x s then (1 : K) else 0) * q y) = q (x s) + := by + simp [ite_mul] + refine (Finset.sum_congr rfl (fun i _ => Finset.prod_congr rfl (fun s _ + => step s _))).trans ?_ + exact Raw.coeff_ofTable _ t x + exact congrArg₂ (· + ·) (hs f).symm (hs g).symm + +open Classical in +theorem table_single (c : K) (a : ∀ s, X s) : + table O X (fun x => if x = a then c else 0) ≤ scalar O S c := by + classical + let C := Raw.ofTable (fun _ : S => Unit) (fun _ => c) + let L (s : S) (x : X s) (_ : Unit) : K := if x = a s then 1 else 0 + refine ⟨L, ?_, fun x => ?_⟩ + · intro s x y + change X s at x + unfold L + split_ifs <;> simp + · change ∀ s, X s at x + rw [Raw.coeff_ofTable] + change _ = ∑ i : C.term, ∏ s, ∑ y : Unit, L s (x s) y * C.factor i s y + by_cases h : x = a + · subst x + simp only [↓reduceIte, L, one_mul] + have e := (Raw.coeff_ofTable (fun _ : S => Unit) (fun _ => c) (fun _ => ())).symm + refine e.trans (Finset.sum_congr rfl fun i _ => Finset.prod_congr rfl fun s _ => ?_) + exact (Fintype.sum_unique (fun x : Unit => C.factor i s x)).symm + · obtain ⟨s, hs⟩ := Function.ne_iff.mp h + rw [ite_eq_right h] + symm + refine Finset.sum_eq_zero fun i _ => Finset.prod_eq_zero (Finset.mem_univ s) ?_ + simp [L, hs] + +theorem table_bound (f : (∀ s, X s) → K) (B : ITensor O S) (h : ∀ i, scalar O S (f i) ≤ B) : + ∃ n : ℕ, table O X f ≤ B * (n : ITensor O S) := by + classical + let part (t : Finset (∀ s, X s)) (x : ∀ s, X s) := if x ∈ t then f x else 0 + have g (t : Finset (∀ s, X s)) : table O X (part t) ≤ B * (t.card : ITensor O S) := by + induction t using Finset.induction_on with + | empty => + rw [show part ∅ = 0 by ext; simp [part], table_zero] + exact zero_le _ + | @insert i t hi ih => + let v (x : ∀ s, X s) := if x = i then f i else 0 + have he : part (insert i t) = part t + v := by + ext x + by_cases h : x = i <;> simp [part, v, h, hi] + have succ (T : Type 1) [CommSemiring T] (X : T) (n : ℕ) : + X * ((n + 1 : ℕ) : T) = X * n + X := by rw [Nat.cast_add, Nat.cast_one, mul_add, mul_one] + rw [he, Finset.card_insert_of_notMem hi, succ] + refine (table_add _ _ _ _).trans ((add_le_add_right _ _ _ ih).trans ?_) + have hv : table O X v ≤ B := (table_single O X _ _).trans (h i) + rw [add_comm _ (table O X v), add_comm _ B] + exact add_le_add_right _ _ _ hv + have hv := g Finset.univ + rw [show part Finset.univ = f by ext; simp [part]] at hv + exact ⟨_, hv⟩ + +theorem upper_bound {U : Type} [Fintype U] (A : ITensor O (S ⊕ U)) : + ∃ (s : ITensor O S) (n : ℕ), A ≤ pad U s * n := by + classical + refine Quotient.inductionOn A fun a => ?_ + let L (i : ∀ s, a.leg s) := scalar O S (a.coeff i) + let B := ∑ i, L i + have hb (i : ∀ s, a.leg s) : L i ≤ B := by + unfold B + rw [← Finset.sum_erase_add _ _ (Finset.mem_univ i)] + simpa only [zero_add] using add_le_add_right _ _ (L i) + (zero_le (∑ j ∈ Finset.univ.erase i, L j)) + have hu i : scalar O (S ⊕ U) (a.coeff i) ≤ pad U B := by + rw [← pad_scalar] + exact ((padding U).le_iff _ _).mpr (hb i) + obtain ⟨n, hn⟩ := table_bound O a.leg a.coeff (pad U B) hu + rw [table_coeff] at hn + exact ⟨B, n, hn⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +section +/- +# Extension under integral restrictions + +The linear test uses only covectors with entries in O. No rank bound +by unscaled units is needed. Selecting an entry yields a scalar lower +bound, and the coordinate expansion gives an upper bound by a sum of +scalars. These facts apply also to an arbitrary subring. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor + +variable {K S U : Type} [Field K] [Fintype S] [Nonempty S] [Fintype U] {O : Subring K} + +theorem extensionData (f : ITensor O S →+* ℝ) (hf : Monotone f) : + Prices.ExtensionData (pad U) f := + ⟨padding U, hf, add_le_add_right, mul_le_mul_left, zero_le, lower_bound f hf, upper_bound O⟩ + +theorem extension_iff {I : Type*} (f : ITensor O S →+* ℝ) (hf : Monotone f) + (X : I → ITensor O (S ⊕ U)) (p : I → ℝ) : + (∃ g : ITensor O (S ⊕ U) →+* ℝ, Monotone g ∧ + (∀ B, g (pad U B) = f B) ∧ (∀ i, g (X i) ≤ p i)) ↔ + ∀ w : List I, ∀ B, pad U B ≤ (w.map X).prod → f B ≤ (w.map p).prod := + (extensionData f hf).extension_iff X p + +theorem assisted_minimum (f : ITensor O S →+* ℝ) (hf : Monotone f) (A : ITensor O (S ⊕ U)) : + IsLeast {r | ∃ g : ITensor O (S ⊕ U) →+* ℝ, + Monotone g ∧ (∀ B, g (pad U B) = f B) ∧ g A = r} (Prices.assisted (pad U) f A) := + (extensionData f hf).assisted_minimum A + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Extra.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Extra.lean new file mode 100644 index 0000000000..796ecef634 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Extra.lean @@ -0,0 +1,91 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Uniform +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Extra + +/-! # Transport of valued prices by wires over the base field -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral + +variable {K S T E : Type} [Field K] [Field E] [Algebra E K] {O : Subring K} + [Fintype S] [Fintype T] [DecidableEq S] [DecidableEq T] (hO : constants E K ≤ O) + +theorem transport (A : Raw K T) (f g : T → S) : + place g (ofRaw A) ≤ place f (ofRaw A) * ∏ t, wire hO (f t) (g t) (Fintype.card (A.leg t)) := by + refine Tensor.move_all (fun f => place f (ofRaw A)) + (fun t i j => wire hO i j (Fintype.card (A.leg t))) mul_le_mul_left ?_ f g + intro v w t h + rw [wire_ofRaw] + exact Raw.integral_move A v w t h + +variable [Nonempty T] (p : ITensor O S →+* ℝ) (hp : Monotone p) +include hp + +theorem price_place_pos (f : T → S) {A : ITensor O T} (h : A ≠ 0) : 0 < p (place f A) := by + let _ : Nonempty S := ⟨f (Classical.arbitrary T)⟩ + revert h + refine Quotient.inductionOn A fun a ha => ?_ + obtain ⟨x, hx⟩ := not_forall.mp fun he => ha ((ofRaw_eq_zero a).mpr he) + have h := hp (place_mono f (scalar_coeff a x)) + rw [place_scalar] at h + exact (positive_scalar p hp _ hx).trans_le h + +theorem price_transport (A : Raw K T) (h : ofRaw (O := O) A ≠ 0) (f g : T → S) : + |Real.log (p (place f (ofRaw A))) - Real.log (p (place g (ofRaw A)))| ≤ + ∑ t, Tensor.dist (p.comp (fromBase hO)) (f t) (g t) * Real.log (Fintype.card (A.leg t)) := by + have dim (t : T) : 0 < Fintype.card (A.leg t) := by + obtain ⟨x, _⟩ := not_forall.mp (fun he => h ((ofRaw_eq_zero A).mpr he)) + exact Fintype.card_pos_iff.mpr ⟨x t⟩ + refine Tensor.log_transport (p.comp (fromBase hO)) (hp.comp (fromBase_mono hO)) + (fun v => p (place v (ofRaw A))) _ (fun v => price_place_pos p hp v h) dim ?_ f g + intro v w + have H := hp (transport hO A v w) + rw [p.map_mul, map_prod] at H + exact H + +theorem price_place_eq (f g : T → S) (h : ∀ t, Tensor.dist (p.comp (fromBase hO)) (f t) (g t) = 0) + (A : ITensor O T) : p (place f A) = p (place g A) := by + refine Quotient.inductionOn A fun a => ?_ + change p (place f (ofRaw a)) = p (place g (ofRaw a)) + by_cases hz : ofRaw (O := O) a = 0 + · simp only [hz, place_zero] + have he := price_transport hO p hp a hz f g + simp only [h, zero_mul, Finset.sum_const_zero, abs_nonpos_iff, sub_eq_zero] at he + exact Real.log_injOn_pos (price_place_pos p hp f hz) (price_place_pos p hp g hz) he + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- # Integral closures in the presence of additional trivial sites -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral + +variable {K S U V : Type} [Field K] {O : Subring K} [Fintype S] [Fintype U] [Fintype V] + +theorem close_extra [Nonempty S] [DecidableEq S] [DecidableEq V] [DecidableEq U] + {A : ITensor O (S ⊕ U)} {B : ITensor O (S ⊕ V)} + (h : pad U B ≤ place (Sum.map Sum.inl id) A) : + ∃ C : ITensor O S, B ≤ pad V C ∧ pad U C ≤ A := by + revert h + refine Quotient.inductionOn A fun a h => ?_ + change pad U B ≤ ofRaw (a.group _) at h + rw [ofRaw_eq (Raw.group_extra a), pad_le_ofRaw_iff] at h + obtain ⟨v, hi, hv⟩ := h + rw [ofRaw_eq (Raw.close_extra a v)] at hv + exact ⟨ofRaw (a.close v), hv, pad_close_le U a v hi⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Restriction.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Restriction.lean new file mode 100644 index 0000000000..22935dcea5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Restriction.lean @@ -0,0 +1,105 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Semiring +public import Mathlib.Algebra.Ring.Subring.Basic + +/-! +# Restrictions with entries in a subring + +The tensors themselves still have coefficients in the ambient field. +For a valuation ring this relation allows only integral substitutions. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral + +variable {K S : Type} [CommRing K] [Fintype S] (O : Subring K) +variable {A B C D : Raw K S} + +/-- The defining condition `∃ L : (s : S) → B.leg s → A.leg s → K, (∀ s x y, L s x y ∈ O) ∧ ∀ x, +B.coeff x = ∑ i : A.term, ∏ s, ∑ y : A.leg s, L s (x s) y * A.factor i s y`. -/ +def Restricts (A B : Raw K S) : Prop := + ∃ L : (s : S) → B.leg s → A.leg s → K, (∀ s x y, L s x y ∈ O) ∧ + ∀ x, B.coeff x = ∑ i : A.term, ∏ s, ∑ y : A.leg s, L s (x s) y * A.factor i s y + +variable {O} + +theorem top_restricts (h : A.Restricts B) : Restricts ⊤ A B := by + obtain ⟨L, hL⟩ := h + exact ⟨L, fun _ _ _ => trivial, hL⟩ + +theorem restricts_iff [DecidableEq S] (A B : Raw K S) : + Restricts O A B ↔ + ∃ L : (s : S) → B.leg s → A.leg s → K, (∀ s x y, L s x y ∈ O) ∧ + ∀ x, B.coeff x = ∑ y : ∀ s, A.leg s, (∏ s, L s (x s) (y s)) * A.coeff y := by + simp only [Restricts, Raw.expand] + +theorem Restricts.forget (h : Restricts O A B) : A.Restricts B := by + obtain ⟨L, _, hh⟩ := h + exact ⟨L, hh⟩ + +theorem Restricts.pullback (f : ∀ s, B.leg s → A.leg s) + (h : ∀ x, B.coeff x = A.coeff (fun s => f s (x s))) : Restricts O A B := by + classical + refine ⟨Raw.pullbackMap f, ?_, Raw.coeff_pullbackMap f h⟩ + intro s x y + by_cases equal : y = f s x <;> simp [Raw.pullbackMap, equal] + +theorem Restricts.refl (A : Raw K S) : Restricts O A A := + Restricts.pullback (fun _ x => x) (fun _ => rfl) + +theorem Restricts.trans (h : Restricts O A B) (g : Restricts O B C) : Restricts O A C := by + obtain ⟨L, hl, hL⟩ := h + obtain ⟨M, hm, hM⟩ := g + exact ⟨Raw.composeRestrictionMaps L M, + fun s x z => O.sum_mem (fun y _ => O.mul_mem (hm s x y) (hl s y z)), + Raw.coeff_composeRestrictionMaps L M hL hM⟩ + +/-- The equiv of type `Setoid (Raw K S) where r A B` for the given inputs. -/ +def equiv (O : Subring K) : Setoid (Raw K S) where + r A B := Restricts O A B ∧ Restricts O B A + iseqv := ⟨fun A => ⟨.refl A, .refl A⟩, fun h => ⟨h.2, h.1⟩, + fun h g => ⟨h.1.trans g.1, g.2.trans h.2⟩⟩ + +theorem forget_equiv (h : (equiv O).r A B) : A ≈ B := ⟨h.1.forget, h.2.forget⟩ + +theorem equiv_coeff (f : ∀ s, A.leg s ≃ B.leg s) + (h : ∀ x, A.coeff x = B.coeff (fun s => f s (x s))) : (equiv O).r A B := by + refine ⟨Restricts.pullback (fun s => (f s).symm) ?_, Restricts.pullback (fun s => f s) h⟩ + intro x + simp only [h, Equiv.apply_symm_apply] + +theorem relabel (e : A.term ≃ B.term) (f : ∀ s, A.leg s ≃ B.leg s) + (h : ∀ i s x, A.factor i s x = B.factor (e i) s (f s x)) : (equiv O).r A B := by + refine equiv_coeff f fun x => ?_ + simp only [Raw.coeff, h] + exact e.sum_comp (fun i => ∏ s, B.factor i s (f s (x s))) + +theorem relabel_of_relabels (h : Raw.Relabels A B) : (equiv O).r A B := by + obtain ⟨terms, legs, factors⟩ := h + exact relabel terms legs factors + +theorem Restricts.mul (h : Restricts O A B) (g : Restricts O C D) : + Restricts O (A * C) (B * D) := by + obtain ⟨L, hl, hL⟩ := h + obtain ⟨M, hm, hM⟩ := g + exact ⟨Raw.restrictMulMap L M, fun s x y => O.mul_mem (hl s x.1 y.1) (hm s x.2 y.2), + Raw.coeff_restrictMulMap L M hL hM⟩ + +theorem Restricts.add (h : Restricts O A B) (g : Restricts O C D) : + Restricts O (A + C) (B + D) := by + obtain ⟨L, hl, hL⟩ := h + obtain ⟨M, hm, hM⟩ := g + refine ⟨Raw.restrictAddMap L M, ?_, Raw.coeff_restrictAddMap L M hL hM⟩ + rintro s (x | x) (y | y) <;> simp [Raw.restrictAddMap, hl, hm] + +end MatrixMultiplicationAllFields.MatrixExponent.Valued diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Shared.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Shared.lean new file mode 100644 index 0000000000..ee1d83e3bd --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Shared.lean @@ -0,0 +1,660 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Uniform +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.TreePrice +public import Mathlib.Analysis.Real.Cardinality +public import Mathlib.RingTheory.Localization.FractionRing +public import Mathlib.Algebra.MvPolynomial.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Continuity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Chord +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.Rigidity +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.Tripod +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Dual +public import Mathlib.RingTheory.Algebraic.Cardinality +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure + +/-! +# Existence of a valued lift + +From a price over an infinite field, construct a price on every +rationally valued field extension trivial on the base. The discount +fixes scalar values, and power interpolation gives integral monotonicity. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral + +variable {E K S : Type} [Field E] [Field K] [Algebra E K] [Infinite E] + [Fintype S] [Nonempty S] {O : Subring K} (v : AddValuation K (WithTop ℚ)) + +theorem ITensor.scalar_pow (x : K) (n : ℕ) : + ITensor.scalar O S (x ^ n) = ITensor.scalar O S x ^ n := by + induction n with + | zero => rw [pow_zero, pow_zero, ITensor.scalar_one] + | succ n ih => rw [pow_succ, ITensor.scalar_mul, ih, pow_succ] + +private theorem scalar_values (g : ITensor O S →+* ℝ) (hg : Monotone g) (b : ℝ) + (h : ∀ (c : K) (m : ℤ), (↑(m : ℚ) : WithTop ℚ) ≤ v c → + g (ITensor.scalar _ _ c) ≤ Real.exp (-(m : ℝ) * b)) (c : K) (q : ℚ) (hq : v c = ↑q) : + g (ITensor.scalar _ _ c) = Real.exp (-(q : ℝ) * b) := by + have integer (x : K) (m : ℤ) (hm : v x = ↑(m : ℚ)) : + g (ITensor.scalar _ _ x) = Real.exp (-(m : ℝ) * b) := by + have hx : x ≠ 0 := by rintro rfl; simp at hm + have hi : v x⁻¹ = ↑((-m : ℤ) : ℚ) := by rw [v.map_inv, hm, Int.cast_neg]; rfl + apply le_antisymm (h _ _ hm.ge) + have he := h _ _ hi.ge + have e : g (ITensor.scalar O S x) * g (ITensor.scalar O S x⁻¹) = 1 := by + rw [← g.map_mul, ← ITensor.scalar_mul, mul_inv_cancel₀ hx, ITensor.scalar_one, map_one] + have H := mul_le_mul_of_nonneg_left he (ITensor.positive_scalar g hg x hx).le + rw [e, Int.cast_neg, neg_neg] at H + rw [neg_mul, Real.exp_neg, ← one_div, div_le_iff₀ (Real.exp_pos _)] + exact H + have hn : v (c ^ q.den) = ↑(q.num : ℚ) := by + rw [v.map_pow, hq, ← WithTop.coe_nsmul, nsmul_eq_mul, mul_comm, Rat.mul_den_eq_num] + have eq := integer _ _ hn + rw [ITensor.scalar_pow, map_pow] at eq + have hz : 0 ≤ g (ITensor.scalar O S c) := by + simpa using hg (ITensor.zero_le (ITensor.scalar O S c)) + apply (pow_left_inj₀ hz (Real.exp_pos _).le q.den_pos.ne').mp + rw [eq, ← Real.exp_nat_mul] + have he : (q : ℝ) * q.den = q.num := by exact_mod_cast q.mul_den_eq_num + rw [← he] + congr 1 + ring + +theorem exists_lift (hv : constants E K ≤ integralRing v) (f : Tensor E S →+* ℝ) + (hf : Monotone f) (b : ℝ) (hb : 0 < b) : + ∃ g : ITensor (integralRing v) S →+* ℝ, Monotone g ∧ + (∀ A, g (ITensor.fromBase hv A) = f A) ∧ + ∀ (c : K) (q : ℚ), v c = ↑q → g (ITensor.scalar _ _ c) = Real.exp (-(q : ℝ) * b) := by + obtain ⟨g, hg, he, hb⟩ := weighted_character v hv f hf b hb + have hp (c : K) (hc : c ∈ integralRing v) : g (ITensor.scalar _ _ c) ≤ 1 := by + simpa using hb c 0 hc + let φ (A : Raw K S) := g (ITensor.ofRaw A) + have hm {A B : Raw K S} (h : Restricts (integralRing v) A B) : φ B ≤ φ A := + ITensor.integral_mono g hg hv hp h + let p : ITensor (integralRing v) S →+* ℝ := + { toFun := Quotient.lift φ (fun _ _ h => le_antisymm (hm h.2) (hm h.1)) + map_zero' := map_zero g + map_one' := map_one g + map_add' := fun x y => Quotient.inductionOn₂ x y fun a b + => g.map_add (ITensor.ofRaw a) (ITensor.ofRaw b) + map_mul' := fun x y => Quotient.inductionOn₂ x y fun a b + => g.map_mul (ITensor.ofRaw a) (ITensor.ofRaw b) } + refine ⟨p, fun x y => Quotient.inductionOn₂ x y fun _ _ h => hm h, ?_, ?_⟩ + · intro A + exact Quotient.inductionOn A fun a => he (Tensor.ofRaw a) + · exact fun c q hq => scalar_values v g hg b hb c q hq + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +section +/- # Simultaneous bounds over the open valuation disk -/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Prices Motion K0 + +variable {E S : Type} [Field E] [Fintype S] [Nonempty S] +local notation "O" => integralRing (val E) + +/-- Uniform strict slack in finitely many price bounds suffices. -/ +def DiskSync (f : ITensor O S →+* ℝ) : Prop := + ∀ (I : Type) [Fintype I] (A : I → K0 E → ITensor O (S ⊕ Unit)), + (∀ i, ∃ d, ITensor.Family (A i) d) → + ∀ (p q : I → ℝ), (∀ i, p i < q i) → + (∀ z ∈ O, ∃ g : ITensor O (S ⊕ Unit) →+* ℝ, + Monotone g ∧ (∀ T, g (ITensor.pad Unit T) = f T) ∧ (∀ i, g (A i z) ≤ p i)) → + ∃ g : ITensor O (S ⊕ Unit) →+* ℝ, Monotone g ∧ (∀ T, g (ITensor.pad Unit T) = f T) ∧ + ∀ i z, 0 < val E z → g (A i z) ≤ q i + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- +# From the open valuation disk to its boundary + +At degree k use nodes of valuation at least 1/(k+1), with pairwise +differences of exactly that valuation. One factor t clears every +interpolation denominator. Its cost is independent of the power. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Prices Motion K0 + +variable {E S : Type} [Field E] [Infinite E] [Fintype S] [Nonempty S] +local notation "O" => integralRing (val E) + +omit [Infinite E] in +private theorem scale_basis {K : Type} [Field K] (V : Subring K) (φ : E →+* K) + (hc : ∀ a, φ a ∈ V) {s : K} (hs : s ∈ V) (hn : s ≠ 0) {k : ℕ} (u : Fin (k + 1) → E) + (x : K) (hx : x ∈ V) (i : Fin (k + 1)) : + s ^ (k + 1) * (Lagrange.basis Finset.univ (fun j => s * φ (u j)) i).eval x ∈ V := by + let v (i : Fin (k + 1)) := s * φ (u i) + have hv (j) : v j ∈ V := V.mul_mem hs (hc _) + have h (j : Fin (k + 1)) : s * (Lagrange.basisDivisor (v i) (v j)).eval x ∈ V := by + simp only [Lagrange.basisDivisor, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_sub, Polynomial.eval_X] + rw [← mul_assoc] + apply V.mul_mem _ (V.sub_mem hx (hv j)) + unfold v + rw [← mul_sub, mul_inv_rev, mul_left_comm, mul_inv_cancel₀ hn, mul_one, ← map_sub, ← map_inv₀] + exact hc _ + have hp := V.prod_mem (t := Finset.univ.erase i) (fun j _ => h j) + rw [Finset.prod_mul_distrib, Finset.prod_const, Finset.card_erase_of_mem (Finset.mem_univ _), + Finset.card_univ, Fintype.card_fin, Nat.add_sub_cancel] at hp + rw [pow_succ', mul_assoc, Lagrange.basis, Polynomial.eval_prod] + exact V.mul_mem hs hp + +private theorem small_nodes (k : ℕ) (x : K0 E) (hx : x ∈ O) : + ∃ v : Fin (k + 1) → K0 E, Function.Injective v ∧ (∀ i, 0 < val E (v i)) ∧ + ∀ i, t (E := E) 1 * (Lagrange.basis Finset.univ v i).eval x ∈ O := by + let s := t (E := E) (((k + 1 : ℕ) : ℚ)⁻¹) + have hs : 0 < val E s := by + rw [show val E s = _ from val_t _] + exact WithTop.coe_pos.mpr (by positivity) + have hn : s ≠ 0 := t_ne_zero _ + have he : s ^ (k + 1) = t (E := E) 1 := by + unfold s + rw [t_pow, mul_inv_cancel₀ (by positivity)] + let u : Fin (k + 1) ↪ E := Fin.valEmbedding.trans (Infinite.natEmbedding E) + let v i := s * C (u i) + have hi : Function.Injective v := by + intro i j h + change s * C (u i) = s * C (u j) at h + have hh : C (u i) = C (u j) := mul_left_cancel₀ hn h + have hh' : u i = u j := (C (E := E)).injective hh + exact u.injective hh' + have hc (a : E) : C a ∈ O := by + change 0 ≤ val E (C a) + by_cases e : a = 0 <;> simp [e] + have hv (i) : 0 < val E (v i) := by + change 0 < val E (s * C (u i)) + rw [AddValuation.map_mul] + exact hs.trans_le (le_add_of_nonneg_right (show 0 ≤ val E (C (u i)) from hc (u i))) + refine ⟨v, hi, hv, fun i => ?_⟩ + rw [← he] + exact scale_basis O C hc (show s ∈ O from hs.le) hn u x hx i + +/-- Any monotone valued character bounded on the open disk is bounded by +the same constant on the closed valuation disk. -/ +theorem Family.bound_disk {A : K0 E → ITensor O S} {d : ℕ} (h : Family A d) + (f : ITensor O S →+* ℝ) (hf : Monotone f) {r : ℝ} + (hr : ∀ x, 0 < val E x → f (A x) ≤ r) (x : K0 E) (hx : x ∈ O) : f (A x) ≤ r := by + have pos := positive_scalar f hf (t 1) (t_ne_zero _) + let H := 1 / f (scalar O S (t 1)) + have hH : 0 < H := one_div_pos.mpr pos + have hb (a : K0 E) (ha : t (E := E) 1 * a ∈ O) : f (scalar O S a) ≤ H := by + have he := hf (scalar_le_one O _ ha) + rw [scalar_mul, map_mul, map_one, mul_comm] at he + exact (le_div_iff₀ pos).mpr he + have hz (A : ITensor O S) : 0 ≤ f A := by simpa using hf (zero_le A) + have hr0 := (hz _).trans (hr 0 (by simp)) + refine TensorSpectrum.le_of_pow_le_polynomial_mul_pow r (f (A x)) (H * (d + 1)) 1 hr0 + (by positivity) fun n _ => ?_ + obtain ⟨v, hi, hv, hw⟩ := small_nodes (n * d) x hx + have he := hf ((h.pow n).weighted (by simp) v hi x) + rw [map_sum, map_pow] at he + refine he.trans ?_ + rw [Real.rpow_one] + calc + _ ≤ ∑ _i : Fin (n * d + 1), H * r ^ n := by + refine Finset.sum_le_sum fun i _ => ?_ + rw [map_mul, map_pow] + exact mul_le_mul (hb _ (hw i)) (pow_le_pow_left₀ (hz _) (hr _ (hv i)) _) + (pow_nonneg (hz _) _) hH.le + _ ≤ _ := by + rw [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul, + ← mul_assoc, mul_comm _ H, mul_assoc H (↑d + 1)] + apply mul_le_mul_of_nonneg_right _ (pow_nonneg hr0 n) + apply mul_le_mul_of_nonneg_left _ hH.le + push_cast + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- +# Recovering an ordinary simultaneous price + +A valued extension controls all positive-valuation shifts at once. +Power interpolation recovers the bound at each constant. It suffices +to have strict slack and finitely many families because each ordinary +closure test uses only a finite list of indices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral Prices Motion K0 Filter Topology + +variable {E F : Type} [Field E] [Field F] [Infinite E] [Infinite F] +local notation "O" => integralRing (val E) + +omit [Infinite F] in +/-- Passing all finite tests with arbitrarily small slack suffices. -/ +private theorem finite_slack {S I J : Type} [Fintype S] [Nonempty S] + (f : Tensor F S →+* ℝ) (hf : Monotone f) + (A : I → J → Tensor F (S ⊕ Unit)) (p : I → ℝ) + (h : ∀ (L : Finset I) (ε : ℝ), 0 < ε → + ∃ g : Tensor F (S ⊕ Unit) →+* ℝ, Monotone g ∧ (∀ T, g (Tensor.pad Unit T) = f T) ∧ + ∀ i ∈ L, ∀ j, g (A i j) ≤ p i + ε) : + ∃ g : Tensor F (S ⊕ Unit) →+* ℝ, Monotone g ∧ (∀ T, g (Tensor.pad Unit T) = f T) ∧ + ∀ i j, g (A i j) ≤ p i := by + classical + let X (i : I × J) := A i.1 i.2 + let P (i : I × J) := p i.1 + have test (w : List (I × J)) (T : Tensor F S) (ht : Tensor.pad Unit T ≤ (w.map X).prod) : + f T ≤ (w.map P).prod := by + let L := (w.map Prod.fst).toFinset + let q (ε : ℝ) := (w.map (fun i => P i + ε)).prod + have hm (ε : ℝ) (hε : 0 < ε) : f T ≤ q ε := by + obtain ⟨g, hg, he, hb⟩ := h L ε hε + have hw (u : List (I × J)) (hu : ∀ i ∈ u, i.1 ∈ L) : + g (u.map X).prod ≤ (u.map (fun i => P i + ε)).prod := by + induction u with + | nil => simp + | cons i u ih => + simp only [List.map_cons, List.prod_cons] + rw [g.map_mul] + have hn (B : Tensor F (S ⊕ Unit)) : 0 ≤ g B := by simpa using hg (Tensor.zero_le B) + have hl := hb i.1 (hu i (by simp)) i.2 + exact mul_le_mul hl (ih (fun a ha => hu a (by simp [ha]))) (hn _) ((hn _).trans hl) + exact ((he _).symm.trans_le (hg ht)).trans + (hw w fun i hi => List.mem_toFinset.mpr (List.mem_map.mpr ⟨i, hi, rfl⟩)) + have hc : Continuous q := by + unfold q + fun_prop + have hh : f T ≤ q 0 := ge_of_tendsto (hc.continuousAt.tendsto.mono_left + (show 𝓝[>] (0 : ℝ) ≤ 𝓝 0 from nhdsWithin_le_nhds)) (eventually_mem_nhdsWithin.mono hm) + simpa only [q, add_zero] using hh + obtain ⟨g, hg, he, hb⟩ := (Tensor.extension_iff f hf X P).mpr test + exact ⟨g, hg, he, fun i j => hb (i, j)⟩ + +theorem sharedPrice_of_disk [Algebra F (K0 E)] (hv : constants F (K0 E) ≤ O) + (hs : ∀ (S : Type) [Fintype S] [DecidableEq S] [Nonempty S] (f : ITensor O S →+* ℝ), + Monotone f → + (∀ (c : K0 E) (q : ℚ), val E c = ↑q → f (ITensor.scalar O S c) = Real.exp (-(q : ℝ))) → + DiskSync f) : SharedPrice F := by + intro S I _ _ _ f hf B X _ P p h + obtain ⟨g, hg, he, hval⟩ := exists_lift (val E) hv f hf 1 zero_lt_one + simp only [mul_one] at hval + let A i : K0 E → ITensor O (S ⊕ Unit) := ITensor.liftFamily (X i) (P i) + have hA i : ∃ d, ITensor.Family (A i) d := ITensor.of_polynomial _ _ + have hb (L : Finset I) (ε : ℝ) (hε : 0 < ε) : + ∃ k : Tensor F (S ⊕ Unit) →+* ℝ, Monotone k ∧ (∀ T, k (Tensor.pad Unit T) = f T) ∧ + ∀ i ∈ L, ∀ j, k (evalFamily (X i) (P i) j) ≤ p i + ε := by + obtain ⟨k, hk, hp, hl⟩ := hs S g hg hval L (fun i => A i.val) (fun i => hA i.val) + (fun i => p i.val) (fun i => p i.val + ε) (fun _ => lt_add_of_pos_right _ hε) + (fun z hz => by + obtain ⟨k, hk, hp, hl⟩ := ITensor.lift_shared hv f hf g hg he B X P p h z hz + exact ⟨k, hk, hp, fun i => hl i.val⟩) + refine ⟨k.comp (ITensor.fromBase hv), hk.comp (ITensor.fromBase_mono hv), ?_, ?_⟩ + · intro T + rw [RingHom.comp_apply, ITensor.fromBase_pad, hp, he] + · intro i hi z + rw [RingHom.comp_apply, ← ITensor.liftFamily_constant] + exact (hA i).choose_spec.bound_disk k hk (hl ⟨i, hi⟩) _ (hv ⟨z, rfl⟩) + obtain ⟨k, hk, hp, hl⟩ := finite_slack f hf (fun i => evalFamily (X i) (P i)) p hb + exact ⟨k, hk, hp, fun i z _ => hl i z⟩ + +/-- An uncountable field of constant parameters over any base. -/ +theorem uncountable_extension (F : Type) [Field F] : + ∃ (E : Type) (_ : Field E) (_ : Uncountable E) (_ : Algebra F (K0 E)), + constants F (K0 E) ≤ integralRing (val E) := by + let R := MvPolynomial ℝ F + let E := FractionRing R + have hu : Uncountable E := ((IsFractionRing.injective R E).comp + MvPolynomial.X_injective).uncountable + let _ : Algebra F (K0 E) := (C.comp (algebraMap F E)).toAlgebra + refine ⟨E, inferInstance, hu, inferInstance, ?_⟩ + rintro _ ⟨x, rfl⟩ + change 0 ≤ val E (C (algebraMap F E x)) + by_cases h : algebraMap F E x = 0 <;> simp [h] + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- # The spectral pseudometric on the additive group of disk shifts -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +open Spectral Prices Motion K0 Filter + +variable {F E S I U V : Type} [Field F] [Field E] [Algebra F (K0 E)] + [Fintype S] [Nonempty S] [DecidableEq S] [Fintype I] [Countable F] [Uncountable E] + (H : Problem F E S I) [Fintype U] [DecidableEq U] + +/-- The value specified by `H.price (idx ∘ p)`. -/ +def spectral (p : U → G E) := H.price (idx ∘ p) + +omit [Fintype I] [Countable F] [Uncountable E] in +theorem spectral_mono (p : U → G E) : Monotone (H.spectral p) := + (H.model _).point_mono H.inc + +omit [Fintype I] in +theorem spectral_pull [Finite I] [Fintype V] [DecidableEq V] (p : U → G E) (x : V → U) + (B : Tensor F (S ⊕ V)) : H.spectral (p ∘ x) B = H.spectral p (Tensor.place (Sum.map id x) B) := + H.price_pull (idx ∘ p) (fun i => (idx_pos (p i)).le) x B + +omit [Fintype I] in +theorem spectral_shift [Finite I] (p : U → G E) (g : G E) : + H.spectral (fun i => g * p i) = H.spectral p := by + let : Fintype I := Fintype.ofFinite I + unfold spectral + rw [show idx ∘ (fun i => g * p i) = translate (idx ∘ p) (idx g) by + funext i; exact (idx_mul _ _).trans (add_comm _ _)] + exact H.price_shift _ (fun i => (idx_pos (p i)).le) (idx_pos g).le + +/-- The value specified by `Tensor.dist (H.spectral (fun i : Bool => if i then x else y)) (.inr +true) (.inr false)`. -/ +def gap (x y : G E) : ℝ := + Tensor.dist (H.spectral (fun i : Bool => if i then x else y)) (.inr true) (.inr false) + +omit [Fintype I] in +theorem gap_eq [Finite I] (p : U → G E) (i j : U) : + H.gap (p i) (p j) = Tensor.dist (H.spectral p) (.inr i) (.inr j) := by + let : Fintype I := Fintype.ofFinite I + let x (t : Bool) := if t then i else j + unfold gap Tensor.dist + rw [show (fun t : Bool => if t then p i else p j) = p ∘ x by funext t; cases t <;> rfl, + spectral_pull, Tensor.place_wire] + rfl + +/-- Builds `PseudoMetricSpace (G E) where dist` with the specified `dist`, `dist_self`, +`dist_comm`, `let`. -/ +abbrev metric : PseudoMetricSpace (G E) where + dist := H.gap + dist_self x := (H.gap_eq (fun _ : Unit => x) () ()).trans (Tensor.dist_self _ _) + dist_comm x y := by + let p := ![x, y] + change H.gap (p 0) (p 1) = H.gap (p 1) (p 0) + rw [gap_eq, gap_eq, Tensor.dist_comm] + dist_triangle x y z := by + let p := ![x, y, z] + change H.gap (p 0) (p 2) ≤ H.gap (p 0) (p 1) + H.gap (p 1) (p 2) + rw [gap_eq, gap_eq, gap_eq] + exact Tensor.dist_triangle _ (H.spectral_mono p) _ _ _ + +omit [Fintype I] [Countable F] [Uncountable E] in +theorem gap_bound (x y : G E) : H.gap x y ≤ 1 := Tensor.dist_le_one _ (H.spectral_mono _) _ _ + +/-- The value specified by `Tensor.values 1 (H.spectral p) ∘ Tensor.place Sum.inr`. -/ +def values (p : U → G E) : Tensor F U → ℝ := + Tensor.values 1 (H.spectral p) ∘ Tensor.place Sum.inr + +omit [Fintype I] in +theorem value_wire [Finite I] (p : U → G E) (i j) : + H.values p (Tensor.wire F i j 2) = H.gap (p i) (p j) := by + let : Fintype I := Fintype.ofFinite I + rw [values, Function.comp_apply, Tensor.place_wire, gap_eq] + exact one_mul _ + +omit [Fintype I] in +theorem value_shift [Finite I] (p : U → G E) (g : G E) : + H.values (fun i => g * p i) = H.values p := by + let : Fintype I := Fintype.ofFinite I + unfold values + rw [spectral_shift] + +/-- The atlas of type `@Atlas F (G E) _ H.metric`, constructed using `H.metric`. -/ +def atlas : @Atlas F (G E) _ H.metric := by + let _ := H.metric + refine ⟨fun p => H.values p, ?_, fun p => H.value_wire p, ?_⟩ + · intro B _ _ _ p + have h : Tensor.values 1 (H.spectral p) ∈ Tensor.ordinary F (S ⊕ B) 1 := + ⟨1, ⟨zero_le_one, le_rfl⟩, _, H.spectral_mono p, rfl⟩ + refine ⟨1 * Fintype.card B, Tensor.ordinary_restrict h Sum.inr fun i j => ?_⟩ + exact (one_mul _).le.trans (Tensor.dist_le_one _ (H.spectral_mono p) _ _) + · intro B C _ _ _ _ _ _ p x + funext A + simp only [values, Function.comp_apply, Tensor.values, spectral_pull, ← Tensor.place_comp] + rfl + +omit [Fintype I] in +theorem value_star [Finite I] (a b : U → K0 E) (x : K0 E) (hx : 0 ≤ val E x) {n : ℕ} + (c : Fin n → K0 E) (r : Option (Fin n) → ℚ) + (hc : ∀ j, 0 ≤ val E (c j)) (hd : ∀ i j, i ≠ j → val E (c i - c j) = 0) + (hr : ∀ j, 0 < r j) (ha : ∀ i, 0 < val E (a i)) (hb : ∀ i, 0 < val E (b i)) + (ho : ∀ i, 0 < val E (t (-r none) * b i)) : + ∀ᶠ u : E in cocountable, ∀ A : Tensor F U, + H.values (fun i => Prices.Motion.K0.shift (aff a b x i)) A ≤ ∑ j, weight r j * + H.values (fun i => Prices.Motion.K0.shift (aff a b (armEnd c r (C u) j) i)) A := by + let : Fintype I := Fintype.ofFinite I + have prod {v y : K0 E} (hv : 0 < val E v) (hy : 0 ≤ val E y) : 0 < val E (v * y) := by + rw [(val E).map_mul] + exact hv.trans_le (le_add_of_nonneg_right hy) + have hm (i) := (val E).map_lt_add (ha i) (prod (hb i) hx) + have he (j y) (hy : 0 ≤ val E y) (i) : 0 < val E (aff a b (armEnd c r y j) i) := by + apply (val E).map_lt_add (ha i) + cases j with + | none => + rw [armEnd, ← mul_assoc, mul_comm (b i)] + exact prod (ho i) hy + | some j => + apply prod (hb i) ((val E).map_le_add (hc j) ?_) + rw [(val E).map_mul, val_t] + exact add_nonneg (WithTop.coe_nonneg.mpr (hr _).le) hy + have h := H.star a b x hx c r hc hd hr (fun i => (hm i).le) (fun j y hy i => (he j y hy i).le) + refine h.mono fun u hu A => ?_ + have eq (p : U → K0 E) (hp : ∀ i, 0 < val E (p i)) : + H.values (fun i => Prices.Motion.K0.shift (p i)) A = + Real.log (H.price p (Tensor.place Sum.inr A)) / Real.log 2 := by + have e : idx ∘ (fun i => Prices.Motion.K0.shift (p i)) = p := funext fun i => idx_shift (hp i) + simp only [values, spectral, e, Function.comp_apply, Tensor.values, one_mul] + have h' j := eq _ (he j _ (integral_C u)) + rw [eq (aff a b x) hm] + simp only [h', ← mul_div_assoc, ← Finset.sum_div] + exact div_le_div_of_nonneg_right (hu _) (Real.log_nonneg (by norm_num)) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +end + +/- +# Synchronization from collapse of the pinned sites + +Every finite tuple of shifts is realized by an assignment dominated +by its generic profile on ordinary tensors. If all its wire distances +vanish, integral transport identifies the sites even on valued inputs. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral ITensor Prices Motion K0 Assignment + +variable {F E S I : Type} [Field F] [Field E] [Algebra F (K0 E)] + [Fintype S] [Nonempty S] [DecidableEq S] [Fintype I] [Countable F] [Uncountable E] + +namespace Problem +variable (H : Problem F E S I) + +omit [Fintype I] in +private theorem joint_collapse [Finite I] {U : Type} [Finite U] [Nonempty U] + (h : ∀ x y, H.gap x y = 0) (x : U → G E) : + ∃ g : Assignment H.f Unit, ∀ i u, g.val (H.A i (idx (x u))) ≤ H.q i := by + classical + let : Fintype I := Fintype.ofFinite I + let : Fintype U := Fintype.ofFinite U + obtain ⟨g, hg, hb⟩ := H.price_controls (idx ∘ x) (fun i => (idx_pos _).le) (RingOf E).zero_mem + have hv (i j : U) : Assignment.dist H.inc g (.inr i) (.inr j) = 0 := by + have hw := hb (Tensor.wire F (.inr i) (.inr j) 2) + change g.point H.inc _ ≤ H.spectral x _ at hw + rw [Tensor.price_wire _ (g.point_mono H.inc) _ _ (by decide), + Tensor.price_wire _ (H.spectral_mono x) _ _ (by decide), ← H.gap_eq x, h] at hw + exact le_antisymm ((Real.rpow_le_rpow_left_iff (by norm_num)).mp hw) + (Assignment.dist_nonneg _ _ _ _) + let j := Classical.arbitrary U + refine ⟨g.atSite j, fun i u => ?_⟩ + rw [show g.atSite j = g.atSite u from pull_eq H.inc g _ _ (fun _ => hv j u)] + have e := hg u (some i) + change (g.atSite u).val (H.A i (idx (x u) + 0)) ≤ H.q i at e + simpa only [add_zero] using e + +omit [Fintype I] in +theorem collapse [Finite I] (h : ∀ x y, H.gap x y = 0) : + ∃ g : Assignment H.f Unit, ∀ i z, 0 < val E z → g.val (H.A i z) ≤ H.q i := by + classical + let : Fintype I := Fintype.ofFinite I + let A (j : I × G E) := H.A j.1 (idx j.2) + let p (j : I × G E) := H.q j.1 + have ht (w : List (I × G E)) : assisted (pad Unit) H.f (w.map A).prod ≤ (w.map p).prod := by + let L := insert 1 (w.map Prod.snd).toFinset + let _ : Nonempty ↥L := ⟨⟨1, Finset.mem_insert_self _ _⟩⟩ + obtain ⟨g, hg⟩ := H.joint_collapse h (fun x : L => x.val) + refine ((assisted_minimum H.f H.mono _).2 ⟨g.val, g.mono, g.old, rfl⟩).trans ?_ + have aux (v : List (I × G E)) (hv : ∀ j ∈ v, j.2 ∈ L) : + g.val (v.map A).prod ≤ (v.map p).prod := by + induction v with + | nil => simp + | cons j v ih => + simp only [List.map_cons, List.prod_cons] + rw [g.val.map_mul] + have hj := hg j.1 ⟨j.2, hv j (by simp)⟩ + exact mul_le_mul hj (ih (fun j h => hv _ (by simp [h]))) (g.nonneg _) ((g.nonneg _).trans + hj) + exact aux w fun j hj => Finset.mem_insert_of_mem (List.mem_toFinset.mpr (List.mem_map.mpr ⟨j, + hj, rfl⟩)) + obtain ⟨g, hg⟩ := (Assignment.exists_iff H.mono A p).mpr ht + exact ⟨g, fun i z hz => by simpa only [A, p, idx_shift hz] using hg (i, Prices.Motion.K0.shift z)⟩ + +end Problem + +theorem diskSync_of_collapse (inc : constants F (K0 E) ≤ RingOf E) + (f : ITensor (RingOf E) S →+* ℝ) (hf : Monotone f) + (hs : ∀ c (q : ℚ), val E c = ↑q → f (scalar _ _ c) = Real.exp (-(q : ℝ))) + (h : ∀ (I : Type) [Fintype I] (H : Problem F E S I), ∀ x y, H.gap x y = 0) : + DiskSync f := by + intro I _ A ha p q hp feas + have hh x (hx : x ∈ RingOf E) : ∃ g : Assignment f Unit, g.Supports (fun i => A i x) p := by + obtain ⟨g, hg, he, hp⟩ := feas x hx + exact ⟨⟨g, hg, he⟩, hp⟩ + let o := Classical.arbitrary S + obtain ⟨r, hr, hmin⟩ := pin_exists inc o hf (fun (x : RingOf E) i => A i x.val) q (fun x => by + obtain ⟨g, hg⟩ := hh x.val x.property + exact ⟨g, fun i => (hg i).trans (hp i).le⟩) + let H : Problem F E S I := + { inc := inc, f := f, mono := hf, scal := hs, o := o, A := A, poly := ha, p := p, q := q + slack := hp, feasible := hh, r := r, bound := hr + least := ⟨fun x hx => hmin.1 ⟨x, hx⟩, fun _ hv => hmin.2 (fun x => hv x.val x.property)⟩ } + obtain ⟨g, hg⟩ := H.collapse (h I H) + exact ⟨g.val, g.mono, g.old, hg⟩ + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- +# Rigidity of the pinned disk + +Compatibility gives an isometric action on the closed hull. +The submean comparison extends from orbit tests to the hull, +and continuity at the marked orbit point forces it to be fixed. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +open Spectral Prices Motion K0 Filter + +variable {F E S I : Type} [Field F] [Field E] [Algebra F (K0 E)] + [Fintype S] [Nonempty S] [DecidableEq S] [Fintype I] [Countable F] [Uncountable E] + (H : Problem F E S I) + +omit [Fintype I] in +private theorem gap_small [Finite I] (ε : ℝ) (hε : 0 < ε) : + ∃ N : ℚ, 0 < N ∧ ∀ g : G E, ↑N ≤ val E (idx g) → H.gap g 1 ≤ ε := by + let : Fintype I := Fintype.ofFinite I + obtain ⟨N, hN, h⟩ := H.continuity ε hε + refine ⟨N, hN, fun g hg => ?_⟩ + let z := idx ∘ (fun i : Bool => if i then g else 1) + have hz (i : Bool) : z i ∈ RingOf E := (idx_pos _).le + obtain ⟨x, hx, hp, hj⟩ := H.model_peak z hz + exact h (translate z x) (H.model z) (fun i => (RingOf E).add_mem (hz i) hx) + (by simpa [translate, z] using hg) hp.1 hj + +omit [Fintype I] in +theorem gap_eq_zero [Finite I] (hF : ∀ (Y : Type) [PseudoMetricSpace Y], + Leaves F E Y → False) (x y : G E) : H.gap x y = 0 := by + let : Fintype I := Fintype.ofFinite I + let _ := H.metric + obtain ⟨Y, _, _, _, _, C, B, o, hd, hp, hm⟩ := + H.atlas.action_hull H.gap_bound (fun _ _ _ _ p g => H.value_shift p g) + have he (p q : G E) : Dist.dist (p • o) (q • o) = H.gap p q := by + have h := congrFun (hp _ ![p, q]) (Tensor.wire F 0 1 2) + rw [B.wire, H.atlas.wire] at h + exact h + have mov : MovingAt E B o := by + intro S _ _ _ a b v hv n c r hc he hr ha hb ho + filter_upwards [H.value_star a b v hv c r hc he hr ha hb ho] with u hu T + simp only [hp] + exact hu T + have hs (ε : ℝ) (hε : 0 < ε) : ∃ b, 0 < b ∧ profile E o b < ε := by + obtain ⟨N, hN, h⟩ := H.gap_small _ (half_pos hε) + refine ⟨N, Rat.cast_pos.mpr hN, lt_of_le_of_lt ?_ (half_lt_self hε)⟩ + apply displacement_le + intro g hg + rw [_root_.dist_comm] + simpa using (he g 1).le.trans (h g ((mem_level _ _).mp hg)) + have hf := (Moving.of_dense mov C hd).constantValue C hm o hs hF + rw [← he, hf, hf, _root_.dist_self] + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.Problem +end + +section +/- +# Synchronization or contact + +Nonconstant motion supplies three fixed branches on the disk tree. +One-sided private products give contact on their homogeneous tangent, +and the tripod comparison propagates contact to every shape. +Otherwise all pinned profiles collapse, giving simultaneous pricing. +-/ + +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued + +theorem contact_of_not_shared {F : Type} [Field F] [Infinite F] [Countable F] + (h : ¬ Prices.SharedPrice F) : omega F = 9 / 4 ∧ Rectangle.Rigidity F := by + by_contra bad + apply h + obtain ⟨E, _, _, _, he⟩ := uncountable_extension F + refine sharedPrice_of_disk he fun S _ _ _ f hf hs => diskSync_of_collapse he f hf hs ?_ + exact fun I _ H => H.gap_eq_zero (fun _ _ t => bad t.contact) + +theorem shared_of_dual {F : Type} [Field F] [Infinite F] [Countable F] + (h : 1 / 2 < Rectangle.dual F 1 1) : Prices.SharedPrice F := by + by_contra bad + obtain ⟨hs, hr⟩ := contact_of_not_shared bad + exact h.ne' (Rectangle.dual_square hr hs) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued + +namespace MatrixMultiplicationAllFields.MatrixExponent + +/-- Descend the square and rectangular conclusions from the countable +algebraic closure. The network estimates can stay over the finite field. -/ +theorem contact_of_not_shared {F : Type} [Field F] [Finite F] + (h : ¬ Prices.SharedPrice (AlgebraicClosure F)) : omega F = 9 / 4 ∧ Rectangle.Rigidity F := by + let K := AlgebraicClosure F + have : Countable K := Cardinal.mk_le_aleph0_iff.mp + ((Algebra.IsAlgebraic.cardinalMk_le_max F K).trans (max_le Cardinal.mk_le_aleph0 le_rfl)) + obtain ⟨hs, hr⟩ := Valued.contact_of_not_shared h + refine ⟨(omega_extension F K).symm.trans hs, Or.inl fun a b c ha hb hc => ?_⟩ + exact (Rectangle.exponent_extension F K ha.le hb.le hc.le).symm.trans + (Rectangle.positive_shapes hr hs ha hb hc) + +theorem shared_of_saving {F : Type} [Field F] [Finite F] (h : omega F < 9 / 4) : + Prices.SharedPrice (AlgebraicClosure F) := by + by_contra bad + exact h.ne (contact_of_not_shared bad).1 + +end MatrixMultiplicationAllFields.MatrixExponent +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/StarWeights.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/StarWeights.lean new file mode 100644 index 0000000000..8570bd0217 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/StarWeights.lean @@ -0,0 +1,935 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.Extension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth +public import Mathlib.LinearAlgebra.Lagrange +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Placements +public import Mathlib.Algebra.Algebra.Tower +public import Mathlib.RingTheory.Valuation.Basic +public import Mathlib.LinearAlgebra.Dual.Lemmas +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.TreePrice + +/-! # Evaluating tensor prices on coordinate arrays -/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral + +variable {K S : Type} [Field K] [Fintype S] (O : Subring K) + +/-- Forgetting integrality makes every permitted restriction an ordinary one. -/ +def forget : ITensor O S →+* Tensor K S where + toFun := Quotient.map id fun _ _ h => ⟨h.1.forget, h.2.forget⟩ + map_zero' := rfl + map_one' := rfl + map_add' A B := Quotient.inductionOn₂ A B fun _ _ => rfl + map_mul' A B := Quotient.inductionOn₂ A B fun _ _ => rfl + +theorem forget_mono : Monotone (forget (S := S) O) := + fun x y => Quotient.inductionOn₂ x y fun _ _ h => h.forget + +variable [Nonempty S] (X Y : S → Type) [∀ s, Fintype (X s)] [∀ s, Fintype (Y s)] + +theorem table_mul (A : (∀ s, X s) → K) (B : (∀ s, Y s) → K) : + table O (fun s => X s × Y s) (fun x => A (fun s => (x s).1) * B (fun s => (x s).2)) = + table O X A * table O Y B := by + apply ofRaw_eq + refine equiv_coeff (fun _ => Equiv.refl _) fun x => ?_ + erw [Raw.coeff_mul, Raw.coeff_ofTable, Raw.coeff_ofTable, Raw.coeff_ofTable] + rfl + +theorem scalar_table (c : K) (A : (∀ s, X s) → K) : + table O X (c • A) = scalar O S c * table O X A := by + apply ofRaw_eq + refine equiv_coeff (fun s => (Equiv.punitProd (X s)).symm) fun x => ?_ + erw [Raw.coeff_mul, Raw.coeff_ofTable, Raw.coeff_ofTable, Raw.coeff_ofTable] + rfl + +theorem scalar_le_one (c : K) (hc : c ∈ O) : scalar O S c ≤ 1 := by + classical + refine ⟨fun s _ _ => Raw.weight c s, ?_, fun x => ?_⟩ + · intro s _ _ + dsimp only [Raw.weight] + split_ifs <;> simp [hc] + · erw [Raw.coeff_ofTable] + change c = ∑ _ : Unit, ∏ s : S, ∑ _ : Unit, Raw.weight c s * 1 + simp [Raw.weight] + +variable {O} + +theorem table_nonneg (f : ITensor O S →+* ℝ) (hf : Monotone f) + (A : (∀ s, X s) → K) : 0 ≤ f (table O X A) := by + rw [← map_zero f] + exact hf (zero_le _) + +theorem table_sum {I : Type*} (f : ITensor O S →+* ℝ) (hf : Monotone f) + (s : Finset I) (A : I → (∀ s, X s) → K) : + f (table O X (∑ i ∈ s, A i)) ≤ ∑ i ∈ s, f (table O X (A i)) := by + classical + induction s using Finset.induction_on with + | empty => simp [table_zero] + | insert i s hi ih => + rw [Finset.sum_insert hi, Finset.sum_insert hi] + refine (hf (table_add _ _ _ _)).trans ?_ + rw [map_add] + exact add_le_add le_rfl ih + +theorem table_span {I : Type*} (f : ITensor O S →+* ℝ) (hf : Monotone f) + (s : Finset I) (A : I → (∀ s, X s) → K) (r : I → K) (hr : ∀ i ∈ s, f (scalar O S (r i)) ≤ 1) : + f (table O X (∑ i ∈ s, r i • A i)) ≤ ∑ i ∈ s, f (table O X (A i)) := by + refine (table_sum X f hf _ _).trans (Finset.sum_le_sum fun i hi => ?_) + rw [scalar_table, map_mul] + exact mul_le_of_le_one_left (table_nonneg X f hf _) (hr i hi) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- +# Interpolation at integral nodes + +Pairwise unit differences keep the interpolation weights integral. +The linear overhead in degree disappears on taking tensor powers. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral + +variable {K S : Type} [Field K] [Fintype S] [Nonempty S] {O : Subring K} + +/-- The defining condition `∃ (X : S → Type) (_ : ∀ s, Fintype (X s)) (P : (∀ s, X s) → +Polynomial K), (∀ b, (P b).natDegree ≤ d) ∧ ∀ x, A x = table O X (fun b => (P b).eval x)`. -/ +def Family (A : K → ITensor O S) (d : ℕ) : Prop := + ∃ (X : S → Type) (_ : ∀ s, Fintype (X s)) (P : (∀ s, X s) → Polynomial K), + (∀ b, (P b).natDegree ≤ d) ∧ ∀ x, A x = table O X (fun b => (P b).eval x) + +variable {A B : K → ITensor O S} {d e : ℕ} + +theorem Family.mul (ha : Family A d) (hb : Family B e) : + Family (fun x => A x * B x) (d + e) := by + obtain ⟨X, _, P, hp, he⟩ := ha + obtain ⟨Y, _, Q, hq, hf⟩ := hb + refine ⟨fun s => X s × Y s, inferInstance, fun b => P (fun s => (b s).1) * Q (fun s => (b s).2), + fun b => Polynomial.natDegree_mul_le.trans (Nat.add_le_add (hp _) (hq _)), fun x => ?_⟩ + simp only [Polynomial.eval_mul, he, hf, ← table_mul] + +theorem Family.pow (h : Family A d) (n : ℕ) : + Family (fun x => A x ^ n) (n * d) := by + induction n with + | zero => + refine ⟨fun _ => Unit, inferInstance, fun _ => 1, by simp, fun x => ?_⟩ + simp only [pow_zero, Polynomial.eval_one] + exact scalar_one.symm + | succ n ih => simpa only [pow_succ, Nat.succ_mul] using ih.mul h + +theorem table_sum_le {I : Type*} (X : S → Type) [∀ s, Fintype (X s)] + (t : Finset I) (A : I → (∀ s, X s) → K) : + table O X (∑ i ∈ t, A i) ≤ ∑ i ∈ t, table O X (A i) := by + classical + induction t using Finset.induction_on with + | empty => simp [table_zero] + | insert i t hi ih => + rw [Finset.sum_insert hi, Finset.sum_insert hi] + refine (table_add O X _ _).trans ?_ + rw [add_comm (table O X (A i)), add_comm (table O X (A i))] + exact add_le_add_right _ _ _ ih + +theorem Family.weighted {I : Type*} [Fintype I] [DecidableEq I] + (h : Family A d) (hn : d < Fintype.card I) (v : I → K) (hv : Function.Injective v) + (x : K) : A x ≤ ∑ i, scalar O S ((Lagrange.basis Finset.univ v i).eval x) * A (v i) := by + obtain ⟨X, _, P, hp, he⟩ := h + let L (i : I) := (Lagrange.basis Finset.univ v i).eval x + have E : (fun b => (P b).eval x) = ∑ i, L i • (fun b => (P b).eval (v i)) := by + funext b + have hd : (P b).degree < (Finset.univ : Finset I).card := by + rw [Finset.card_univ] + exact Polynomial.degree_le_natDegree.trans_lt (WithBot.coe_lt_coe.mpr ((hp b).trans_lt hn)) + have hz := congrArg (Polynomial.eval x) (Lagrange.eq_interpolate hv.injOn hd) + simpa only [Lagrange.interpolate_apply, Polynomial.eval_finsetSum, Polynomial.eval_mul, + Polynomial.eval_C, Finset.sum_apply, Pi.smul_apply, smul_eq_mul, L, mul_comm] using hz + rw [he, E] + simp only [he] + simpa only [scalar_table] using + table_sum_le (O := O) X Finset.univ (fun i => L i • (fun b => (P b).eval (v i))) + +theorem Family.interpolate (h : Family A d) (f : ITensor O S →+* ℝ) (hf : Monotone f) + {V : Subring K} (hV : ∀ c ∈ V, f (scalar O S c) ≤ 1) + {n : ℕ} (hn : d < n) (v : Fin n → K) (hv : Function.Injective v) + (hi : ∀ i, v i ∈ V) (hu : ∀ i j, (v i - v j)⁻¹ ∈ V) (x : K) (hx : x ∈ V) : + f (A x) ≤ ∑ i, f (A (v i)) := by + let L (i : Fin n) := (Lagrange.basis Finset.univ v i).eval x + have hL (i : Fin n) : L i ∈ V := by + simp only [L, Lagrange.basis, Lagrange.basisDivisor, Polynomial.eval_prod, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_sub, Polynomial.eval_X] + exact V.prod_mem fun j _ => V.mul_mem (hu i j) (V.sub_mem hx (hi j)) + have e := hf (h.weighted (by simpa using hn) v hv x) + rw [map_sum] at e + refine e.trans (Finset.sum_le_sum fun i _ => ?_) + rw [f.map_mul] + have hp : 0 ≤ f (A (v i)) := by simpa using hf (zero_le (A (v i))) + exact mul_le_of_le_one_left hp (hV _ (hL i)) + +/-- The price at an integral parameter cannot exceed a uniform bound +on an infinite set of nodes having pairwise unit differences. -/ +theorem Family.bound_scalar (h : Family A d) (f : ITensor O S →+* ℝ) (hf : Monotone f) + {V : Subring K} (hV : ∀ c ∈ V, f (scalar O S c) ≤ 1) + {J : Type*} [Infinite J] (v : J → K) (hv : Function.Injective v) + (hi : ∀ i, v i ∈ V) (hu : ∀ i j, (v i - v j)⁻¹ ∈ V) + {r : ℝ} (hr : ∀ j, f (A (v j)) ≤ r) (x : K) (hx : x ∈ V) : f (A x) ≤ r := by + have hz (B : ITensor O S) : 0 ≤ f B := by simpa using hf (zero_le B) + have hr0 := (hz _).trans (hr (Classical.arbitrary J)) + refine TensorSpectrum.le_of_pow_le_polynomial_mul_pow r (f (A x)) (d + 1) 1 hr0 + (by positivity) fun n _ => ?_ + let w : Fin (n * d + 1) ↪ J := Fin.valEmbedding.trans (Infinite.natEmbedding J) + have he := (h.pow n).interpolate f hf hV (Nat.lt_succ_self (n * d)) (v ∘ w) + (hv.comp w.injective) (fun i => hi (w i)) (fun i j => hu (w i) (w j)) x hx + rw [Real.rpow_one] + calc + _ ≤ ∑ i, f (A (v (w i))) ^ n := by simpa only [map_pow, Function.comp_apply] using he + _ ≤ ∑ _i : Fin (n * d + 1), r ^ n := + Finset.sum_le_sum fun i _ => pow_le_pow_left₀ (hz _) (hr _) _ + _ ≤ _ := by + rw [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] + apply mul_le_mul_of_nonneg_right _ (pow_nonneg hr0 n) + push_cast + linarith + +theorem Family.bound (h : Family A d) (f : ITensor O S →+* ℝ) (hf : Monotone f) + {J : Type*} [Infinite J] (v : J → K) (hv : Function.Injective v) + (hi : ∀ i, v i ∈ O) (hu : ∀ i j, (v i - v j)⁻¹ ∈ O) + {r : ℝ} (hr : ∀ j, f (A (v j)) ≤ r) (x : K) (hx : x ∈ O) : f (A x) ≤ r := + h.bound_scalar f hf (fun c hc => by simpa using hf (scalar_le_one O c hc)) v hv hi hu hr x hx + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- +# Extracting base-field coefficients + +Linear functionals on the ambient field commute with restrictions over +the base. They give additive evaluations, prior to imposing valuation +cutoffs on the functionals. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral + +variable (E K : Type) [Field E] [Field K] [Algebra E K] + +/-- The value specified by `(algebraMap E K).range`. -/ +def constants : Subring K := (algebraMap E K).range + +variable {E K} {S : Type} [Fintype S] [Nonempty S] (l : K →ₗ[E] E) + +/-- The indexed operation `Raw.ofTable A.leg (fun x => l (A.coeff x))`. -/ +def sampleRaw (A : Raw K S) : Raw E S := Raw.ofTable A.leg (fun x => l (A.coeff x)) + +theorem sample_coeff (A : Raw K S) (x : ∀ s, A.leg s) : + (sampleRaw l A).coeff x = l (A.coeff x) := Raw.coeff_ofTable _ _ _ + +theorem Restricts.sample {A B : Raw K S} (h : Restricts (constants E K) A B) : + (sampleRaw l A).Restricts (sampleRaw l B) := by + classical + obtain ⟨L, hl, h⟩ := h + choose M he using hl + refine (Raw.restricts_iff _ _).mpr ⟨M, fun x => ?_⟩ + change (∀ s, B.leg s) at x + erw [sample_coeff, h, A.expand, map_sum] + refine Finset.sum_congr rfl fun y _ => ?_ + change (∀ s, A.leg s) at y + erw [sample_coeff] + rw [show (∏ s, L s (x s) (y s)) = algebraMap E K (∏ s, M s (x s) (y s)) by + rw [map_prod] + exact Finset.prod_congr rfl fun s _ => (he s _ _).symm] + rw [← Algebra.smul_def, map_smul, smul_eq_mul] + +omit [Nonempty S] in +private theorem side {X Y : S → Type} + {I J : Type} [Fintype I] [Fintype J] + (a : I → (s : S) → X s → K) (b : J → (s : S) → X s → E) + (h : ∀ x : ∀ s, X s, l (∑ i, ∏ s, a i s (x s)) = ∑ j, ∏ s, b j s (x s)) + (x : ∀ s, X s ⊕ Y s) : + l (∑ i, ∏ s, Sum.elim (a i s) (fun _ => 0) (x s)) = + ∑ j, ∏ s, Sum.elim (b j s) (fun _ => 0) (x s) := by + classical + by_cases hx : ∀ s, ∃ u, x s = .inl u + · choose u hu using hx + simpa only [hu, Sum.elim_inl] using h u + push Not at hx + obtain ⟨s, hs⟩ := hx + cases he : x s with + | inl v => exact (hs _ he).elim + | inr v => + rw [Finset.sum_eq_zero, map_zero, Finset.sum_eq_zero] + all_goals exact fun _ _ => Finset.prod_eq_zero (Finset.mem_univ s) (by rw [he]; rfl) + +theorem sample_add (A B : Raw K S) : + sampleRaw l (A + B) ≈ sampleRaw l A + sampleRaw l B := by + let X := sampleRaw l A + let Y := sampleRaw l B + refine Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_ + change (∀ s, A.leg s ⊕ B.leg s) at x + erw [sample_coeff] + change l (∑ i : A.term ⊕ B.term, ∏ s, (A + B).factor i s (x s)) = + ∑ j : X.term ⊕ Y.term, ∏ s, (X + Y).factor j s (x s) + rw [Fintype.sum_sum_type, Fintype.sum_sum_type, map_add] + refine congrArg₂ (· + ·) (side l A.factor X.factor (fun u => (sample_coeff l A u).symm) x) ?_ + have he := side l B.factor Y.factor (fun u => (sample_coeff l B u).symm) (fun s => (x s).swap) + convert he using 1 + · refine congrArg l (Finset.sum_congr rfl fun i _ => Finset.prod_congr rfl fun s _ => ?_) + cases x s <;> rfl + · refine Finset.sum_congr rfl fun i _ => Finset.prod_congr rfl fun s _ => ?_ + cases x s <;> rfl + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def sample : ITensor (constants E K) S →+ Tensor E S where + toFun := Quotient.map (sampleRaw l) fun _ _ h => ⟨h.1.sample l, h.2.sample l⟩ + map_zero' := Tensor.ofRaw_eq (Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => + (x (Classical.arbitrary S)).elim) + map_add' x y := Quotient.inductionOn₂ x y fun a b => Tensor.ofRaw_eq (sample_add l a b) + +theorem sample_mono : Monotone (sample (S := S) l) := + fun x y => Quotient.inductionOn₂ x y fun _ _ h => Restricts.sample l h + +theorem sample_table (X : S → Type) [∀ s, Fintype (X s)] (f : (∀ s, X s) → K) : + sample l (ITensor.table (constants E K) X f) = + Tensor.ofRaw (Raw.ofTable X fun x => l (f x)) := by + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_ + erw [sample_coeff, Raw.coeff_ofTable, Raw.coeff_ofTable] + rfl + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- # Changing coefficients and extending base-field tensors -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued + +open Spectral +variable {E K S : Type} [Fintype S] + +section +variable [CommRing E] [CommRing K] +variable {R : Subring E} {O : Subring K} + +theorem Restricts.map {A B : Raw E S} (h : Restricts R A B) (f : E →+* K) + (hf : ∀ x ∈ R, f x ∈ O) : Restricts O (A.map f) (B.map f) := by + obtain ⟨P, hp, he⟩ := h + exact ⟨Raw.mapRestrictionMaps P f, fun s x y => hf _ (hp s x y), + Raw.coeff_mapRestrictionMaps P f he⟩ + +namespace ITensor + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def map (f : E →+* K) (hf : ∀ x ∈ R, f x ∈ O) : ITensor R S →+* ITensor O S where + toFun := Quotient.map (fun A => A.map f) fun _ _ h => ⟨h.1.map f hf, h.2.map f hf⟩ + map_zero' := ofRaw_eq (relabel_of_relabels (Raw.map_zero_relabels f)) + map_one' := ofRaw_eq (relabel_of_relabels (Raw.map_one_relabels f)) + map_mul' X Y := Quotient.inductionOn₂ X Y fun A B => + ofRaw_eq (relabel_of_relabels (Raw.map_mul_relabels f A B)) + map_add' X Y := Quotient.inductionOn₂ X Y fun A B => + ofRaw_eq (relabel_of_relabels (Raw.map_add_relabels f A B)) + +theorem map_mono (f : E →+* K) (hf : ∀ x ∈ R, f x ∈ O) : Monotone (map (S := S) f hf) := + fun X Y => Quotient.inductionOn₂ X Y fun _ _ h => Restricts.map h f hf + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def top : Tensor K S →+* ITensor (⊤ : Subring K) S where + toFun := Quotient.map id fun _ _ h => ⟨top_restricts h.1, top_restricts h.2⟩ + map_zero' := rfl + map_one' := rfl + map_add' x y := Quotient.inductionOn₂ x y fun _ _ => rfl + map_mul' x y := Quotient.inductionOn₂ x y fun _ _ => rfl + +theorem top_mono : Monotone (top (K := K) (S := S)) := + fun X Y => Quotient.inductionOn₂ X Y fun _ _ h => top_restricts h + +end ITensor +end + +namespace ITensor + +variable [Field E] [Field K] [Algebra E K] {O : Subring K} + +/-- The indexed operation `(map (algebraMap E K) (fun x _ => hO ⟨x, rfl⟩)).comp top`. -/ +def fromBase (hO : constants E K ≤ O) : Tensor E S →+* ITensor O S := + (map (algebraMap E K) (fun x _ => hO ⟨x, rfl⟩)).comp top + +theorem fromBase_mono (hO : constants E K ≤ O) : Monotone (fromBase (S := S) hO) := + (map_mono (algebraMap E K) (fun x _ => hO ⟨x, rfl⟩)).comp top_mono + +variable [Nonempty S] (l : K →ₗ[E] E) + +theorem sample_mul (a : Tensor E S) (b : ITensor (constants E K) S) : + sample l (fromBase le_rfl a * b) = a * sample l b := by + refine Quotient.inductionOn₂ a b fun A B => ?_ + apply Tensor.ofRaw_eq + refine Raw.equiv_coeff (fun _ => Equiv.refl _) fun x => ?_ + erw [sample_coeff, Raw.coeff_mul, Raw.coeff_mul, sample_coeff, Raw.coeff_map, + ← Algebra.smul_def, map_smul, smul_eq_mul] + rfl + +theorem sample_scalar (c : K) (m : K →ₗ[E] E) (h : ∀ x, l (c * x) = m x) + (a : ITensor (constants E K) S) : sample l (scalar _ _ c * a) = sample m a := by + refine Quotient.inductionOn a fun A => ?_ + change sample l (scalar _ _ c * ofRaw A) = sample m (ofRaw A) + rw [← table_coeff (constants E K) A, ← scalar_table, sample_table, sample_table] + simp only [Pi.smul_apply, smul_eq_mul, h] + +end ITensor +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- +# Filtered linear measurements + +Take a supremum over any subspace of the base-field dual. The +resulting functional remains additive on block sums. Indeed along +a line through two witnesses, power interpolation shows that all +but finitely many parameters nearly achieve both bounds. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral Filter + +variable {E K S : Type} [Field E] [Field K] [Algebra E K] [Fintype S] [Nonempty S] + (f : Tensor E S →+* ℝ) (hf : Monotone f) +local notation "T" => ITensor (constants E K) S +local notation "D" => (K →ₗ[E] E) + +private theorem generic_line (hf : Monotone f) (X : T) (l m : D) {r : ℝ} {c : E} + (h : r < f (sample (l + c • m) X)) : + ∀ᶠ a : E in cofinite, r < f (sample (l + a • m) X) := by + classical + revert h + refine Quotient.inductionOn X fun A h => ?_ + let L (a : E) := ITensor.table ⊤ A.leg (fun x => (l + a • m) (A.coeff x)) + have hL : ITensor.Family L 1 := by + refine ⟨A.leg, inferInstance, fun x => Polynomial.C (l (A.coeff x)) + + Polynomial.X * Polynomial.C (m (A.coeff x)), ?_, ?_⟩ + · intro x + refine (Polynomial.natDegree_add_le _ _).trans (max_le (by simp) ?_) + exact Polynomial.natDegree_mul_le.trans (by simp) + · intro t + simp only [L, LinearMap.add_apply, LinearMap.smul_apply, smul_eq_mul, Polynomial.eval_add, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X] + let g := f.comp (ITensor.forget ⊤) + have hg : Monotone g := hf.comp (ITensor.forget_mono _) + change r < g (L c) at h + change ∀ᶠ a : E in cofinite, r < g (L a) + rw [eventually_cofinite] + by_contra hn + let _ : Infinite {a : E // ¬ r < g (L a)} := Set.Infinite.to_subtype hn + exact h.not_ge (hL.bound g hg (fun a : {a : E // ¬ r < g (L a)} => a.val) + Subtype.val_injective (fun _ => trivial) (fun _ _ => trivial) + (fun a => le_of_not_gt a.property) c trivial) + +theorem sample_bounded (hf : Monotone f) (A : T) : ∃ C : ℝ, ∀ l : D, f (sample l A) ≤ C := by + refine Quotient.inductionOn A fun A => ?_ + refine ⟨(∏ s, Fintype.card (A.leg s) : ℕ), fun l => ?_⟩ + have h := hf (Tensor.le_dimension (sampleRaw l A)) + rw [map_natCast] at h + exact h + +variable (U : Submodule E (K →ₗ[E] E)) + +/-- The supremum of `{r : ℝ | ∃ l : K →ₗ[E] E, l ∈ U ∧ f (sample l A) = r}`. -/ +def best (A : T) : ℝ := sSup {r : ℝ | ∃ l : K →ₗ[E] E, l ∈ U ∧ f (sample l A) = r} + +theorem best_le (A : T) {r : ℝ} (h : ∀ l ∈ U, f (sample l A) ≤ r) : best f U A ≤ r := by + refine csSup_le ⟨_, 0, U.zero_mem, rfl⟩ ?_ + rintro _ ⟨l, hl, rfl⟩ + exact h l hl + +include hf + +theorem le_best (A : T) (l : D) (hl : l ∈ U) : f (sample l A) ≤ best f U A := by + obtain ⟨C, hC⟩ := sample_bounded f hf A + refine le_csSup ⟨C, ?_⟩ ⟨l, hl, rfl⟩ + rintro _ ⟨m, _, rfl⟩ + exact hC m + +theorem best_nonneg (A : T) : 0 ≤ best f U A := by + refine le_trans ?_ (le_best f hf U A _ U.zero_mem) + rw [← map_zero f] + exact hf (Tensor.zero_le _) + +theorem best_mono : Monotone (best f U) := fun _ _ h => + best_le f U _ fun l hl => (hf (sample_mono l h)).trans (le_best f hf U _ l hl) + +theorem best_zero : best f U 0 = 0 := + le_antisymm (best_le f U _ fun _ _ => by simp) (best_nonneg f hf U _) + +theorem best_mul (A : Tensor E S) (B : T) : + best f U (ITensor.fromBase le_rfl A * B) = f A * best f U B := by + have h : 0 ≤ f A := by simpa using hf (Tensor.zero_le A) + apply le_antisymm + · refine best_le f U _ fun l hl => ?_ + rw [ITensor.sample_mul, map_mul] + exact mul_le_mul_of_nonneg_left (le_best f hf U B l hl) h + · rcases h.eq_or_lt with he | hp + · rw [← he, zero_mul] + exact best_nonneg f hf U _ + rw [mul_comm, ← le_div_iff₀ hp] + refine best_le f U _ fun l hl => ?_ + rw [le_div_iff₀ hp, mul_comm, ← map_mul, ← ITensor.sample_mul] + exact le_best f hf U _ l hl + +theorem best_add [Infinite E] (A B : T) : best f U (A + B) = best f U A + best f U B := by + apply le_antisymm + · refine best_le f U _ fun l hl => ?_ + rw [map_add, map_add] + exact add_le_add (le_best f hf U A l hl) (le_best f hf U B l hl) + · apply le_sub_iff_add_le.mp + refine best_le f U A fun l hl => ?_ + apply le_sub_comm.mp + refine best_le f U B fun m hm => ?_ + rw [le_sub_iff_add_le'] + refine le_of_forall_pos_le_add fun ε he => ?_ + have ha := generic_line f hf A l (m - l) (c := 0) (r := f (sample l A) - ε / 2) + (by simp only [zero_smul, add_zero]; linarith) + have hb := generic_line f hf B l (m - l) (c := 1) (r := f (sample m B) - ε / 2) + (by simp only [one_smul, add_sub_cancel]; linarith) + obtain ⟨c, h₁, h₂⟩ := (ha.and hb).exists + have h₃ := le_best f hf U (A + B) _ (U.add_mem hl (U.smul_mem c (U.sub_mem hm hl))) + rw [map_add, map_add] at h₃ + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- # Linear forms killing entries above a valuation cutoff -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral + +variable {E K S : Type} [Field E] [Field K] [Algebra E K] [Fintype S] [Nonempty S] + (v : AddValuation K (WithTop ℚ)) + +/-- Builds `Submodule E (K →ₗ[E] E) where carrier` with the specified `carrier`, `zero_mem'`, +`add_mem'`, `smul_mem'`. -/ +def cutoff (E : Type) [Field E] [Algebra E K] (r : ℚ) : Submodule E (K →ₗ[E] E) where + carrier := {l | ∀ x, (r : WithTop ℚ) < v x → l x = 0} + zero_mem' := fun _ _ => rfl + add_mem' hl hm x h := by rw [LinearMap.add_apply, hl x h, hm x h, add_zero] + smul_mem' a _ hl x h := by rw [LinearMap.smul_apply, hl x h, smul_zero] + +/-- Builds `Subring K where carrier` with the specified `carrier`, `zero_mem'`, `one_mem'`, +`add_mem'`. -/ +def integralRing : Subring K where + carrier := {x | 0 ≤ v x} + zero_mem' := by simp + one_mem' := by simp + add_mem' := v.map_le_add + neg_mem' h := by simpa only [Set.mem_ofPred_eq, v.map_neg] using h + mul_mem' h g := by simpa only [Set.mem_ofPred_eq, v.map_mul] using add_nonneg h g + +private theorem separates (hb : constants E K ≤ integralRing v) : + ∃ l ∈ cutoff v E 0, l 1 ≠ 0 := by + let V : Submodule E K := + { carrier := {x | 0 < v x} + zero_mem' := by simp + add_mem' := v.map_lt_add + smul_mem' := by + intro c x hx + change 0 < v (c • x) + rw [Algebra.smul_def, v.map_mul] + exact lt_of_lt_of_le hx (le_add_of_nonneg_left (hb ⟨c, rfl⟩)) } + have h : (1 : K) ∉ V := by simp [V] + obtain ⟨l, hl, he⟩ := Submodule.exists_dual_map_eq_bot_of_notMem h inferInstance + refine ⟨l, fun x hx => ?_, hl⟩ + have hv : l x ∈ V.map l := ⟨x, hx, rfl⟩ + simpa only [he, Submodule.mem_bot] using hv + +variable (f : Tensor E S →+* ℝ) (hf : Monotone f) +local notation "T" => ITensor (constants E K) S + +include hf + +theorem best_unit (hb : constants E K ≤ integralRing v) : 0 < best f (cutoff v E 0) 1 := by + obtain ⟨l, hl, he⟩ := separates v hb + have h : sample (S := S) l 1 ≠ 0 := by + intro h + have ht := (Tensor.ofRaw_eq_zero (sampleRaw l (1 : Raw K S))).mp h (fun _ => ()) + erw [sample_coeff] at ht + change l (∑ _ : Unit, ∏ _ : S, (1 : K)) = 0 at ht + simp only [Finset.prod_const_one, Fintype.sum_unique] at ht + exact he ht + have hh := hf (Tensor.one_le _ h) + rw [map_one] at hh + exact zero_lt_one.trans_le (hh.trans (le_best f hf _ _ _ hl)) + +theorem best_shift {r s : ℚ} (c : K) (hc : (r : WithTop ℚ) ≤ v c) (A : T) : + best f (cutoff v E s) (ITensor.scalar _ _ c * A) ≤ best f (cutoff v E (s - r)) A := by + refine best_le f _ _ fun l hl => ?_ + let m := l.comp (LinearMap.mulLeft E c) + have hm : m ∈ cutoff v E (s - r) := by + intro x hx + apply hl + have hh := WithTop.add_lt_add_left (WithTop.coe_ne_top (a := r)) hx + rw [← WithTop.coe_add, add_sub_cancel] at hh + change (s : WithTop ℚ) < v (c * x) + rw [v.map_mul] + exact hh.trans_le (add_le_add_left hc _) + rw [ITensor.sample_scalar l c m (fun _ => rfl)] + exact le_best f hf _ _ _ hm + +omit hf in +theorem exists_floor (c : K) : ∃ n : ℕ, (↑(-(n : ℚ)) : WithTop ℚ) ≤ v c := by + rcases eq_or_ne (v c) ⊤ with h | h + · exact ⟨0, by rw [h]; exact le_top⟩ + obtain ⟨q, hq⟩ := WithTop.ne_top_iff_exists.mp h + obtain ⟨n, hn⟩ := exists_nat_ge (-q) + exact ⟨n, hq ▸ WithTop.coe_le_coe.mpr (neg_le.mp hn)⟩ + +theorem best_floor (A : T) : ∃ n : ℕ, ∀ r : ℚ, r < -(n : ℚ) → best f (cutoff v E r) A = 0 := by + classical + refine Quotient.inductionOn A fun a => ?_ + choose n hn using fun x => exists_floor v (a.coeff x) + obtain ⟨N, hN⟩ := (Set.finite_range n).bddAbove + refine ⟨N, fun r hr => le_antisymm (best_le _ _ _ fun l hl => ?_) (best_nonneg f hf _ _)⟩ + have ht : sample l (ITensor.ofRaw a) = 0 := by + refine (Tensor.ofRaw_eq_zero _).mpr fun x => ?_ + change (∀ s, a.leg s) at x + rw [sample_coeff] + apply hl + have he : (n x : ℚ) ≤ N := Nat.cast_le.mpr (hN ⟨x, rfl⟩) + exact (WithTop.coe_lt_coe.mpr (hr.trans_le (neg_le_neg he))).trans_le (hn x) + change f (sample l (ITensor.ofRaw a)) ≤ 0 + rw [ht, map_zero] + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- +# Interpolation of assisted costs + +The one-copy envelope is additive. This permits bounding closures +of powers without asking a single extension to minimize at different +interpolation nodes. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Prices.ExtensionData + +variable {S T : Type*} [CommSemiring S] [CommSemiring T] [PartialOrder S] [PartialOrder T] + {pad : S → T} {f : S →+* ℝ} (H : ExtensionData pad f) + +include H + +theorem aided_nonneg (A : T) : 0 ≤ assisted pad f A := by + obtain ⟨g, hg, _, he⟩ := (H.assisted_minimum A).1 + rw [← he, ← map_zero g] + exact hg (H.zero _) + +theorem test_iff (A : T) (r : ℝ) : assisted pad f A ≤ r ↔ + ∀ n : ℕ, ∀ s, pad s ≤ A ^ n → f s ≤ r ^ n := by + obtain ⟨g, hg, he, e⟩ := (H.assisted_minimum A).1 + refine ⟨fun h n s hs => ?_, fun h => ?_⟩ + · rw [← he] + refine (hg hs).trans ?_ + rw [map_pow, e] + exact pow_le_pow_left₀ (H.aided_nonneg A) h _ + · obtain ⟨p, hp, ep, hr⟩ := (H.extension_iff (fun _ : Unit => A) (fun _ => r)).mpr + (by intro w s hs; simpa [List.prod_replicate] + using h w.length s (by simpa [List.prod_replicate] using hs)) + exact ((H.assisted_minimum _).2 ⟨p, hp, ep, rfl⟩).trans (hr ()) + +theorem test_with_loss (A : T) {r C : ℝ} (hr : 0 ≤ r) (hc : 0 < C) + (h : ∀ n : ℕ, 1 ≤ n → ∀ s, pad s ≤ A ^ n → f s ≤ C * ((n : ℝ) + 1) * r ^ n) : + assisted pad f A ≤ r := by + refine (H.test_iff A r).mpr fun n s hs => ?_ + by_cases hn : n = 0 + · subst n + rw [pow_zero, ← H.padLaw.one] at hs + simpa using H.mono ((H.padLaw.le_iff _ _).mp hs) + have hg : 0 ≤ f s := by + rw [← map_zero f] + exact H.mono ((H.padLaw.le_iff _ _).mp (H.padLaw.zero.symm ▸ H.zero _)) + have he (m : ℕ) : pad (s ^ m) ≤ (A ^ n) ^ m := by + induction m with + | zero => rw [pow_zero, pow_zero, H.padLaw.one] + | succ m ih => + rw [pow_succ, H.padLaw.mul, pow_succ'] + exact (H.mul _ _ _ hs).trans (by rw [mul_comm]; exact H.mul _ _ _ ih) + refine TensorSpectrum.le_of_pow_le_polynomial_mul_pow (r ^ n) (f s) (C * (n + + 1)) 1 (pow_nonneg hr _) + (by positivity) fun m hm => ?_ + have e := h (n * m) (Nat.mul_pos (by omega) hm) _ (by rw [pow_mul]; exact he m) + rw [map_pow, pow_mul, Nat.cast_mul] at e + rw [Real.rpow_one, mul_assoc C] + refine e.trans (mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left ?_ hc.le) (by positivity)) + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Prices.ExtensionData + +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Prices + +variable {K S U : Type} [Field K] [Fintype S] [Nonempty S] [Fintype U] {O : Subring K} + {A : K → ITensor O (S ⊕ U)} {d : ℕ} (h : Family A d) + (f : ITensor O S →+* ℝ) (hf : Monotone f) + +theorem Family.test_nodes (h : Family A d) (f : ITensor O S →+* ℝ) (hf : Monotone f) + (n : ℕ) (x : K) {s : ITensor O S} (hs : pad U s ≤ A x ^ n) + {I : Type*} [Fintype I] [DecidableEq I] + (v : I → K) (hi : Function.Injective v) (hd : n * d < Fintype.card I) : + f s ≤ ∑ i, f (scalar O S ((Lagrange.basis Finset.univ v i).eval x)) * + assisted (pad U) f (A (v i)) ^ n := by + let H := extensionData (U := U) f hf + obtain ⟨M, h1, hm, he, hc⟩ := H.padLaw.envelope H.add H.mul H.zero H.upper f hf + have ep (s : ITensor O S) : f s = M (pad U s) := by + simpa only [mul_one, h1] using (he s 1).symm + have ht := hm ((h.pow n).weighted hd v hi x) + rw [map_sum] at ht + refine ((ep s).trans_le ((hm hs).trans ht)).trans (Finset.sum_le_sum fun i _ => ?_) + rw [← pad_scalar, he] + refine mul_le_mul_of_nonneg_left ((hc _ _).mpr ?_) (by rw [← map_zero f]; exact hf (zero_le _)) + exact (H.test_iff _ _).mp le_rfl n + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- Interpolation nodes on the arms of a valuation star. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.Star + +open Prices.Motion Prices.Motion.K0 Finset +variable {E : Type} [Field E] {n : ℕ} + +open scoped Classical in +/-- Computes the arm by the application `Option (Fin n)`. -/ +abbrev Arm (n : ℕ) := Option (Fin n) + +open scoped Classical in +/-- The data for the data construction, including `c`, `hc`, `hd`, `r`, `hr`. -/ +structure Data (E : Type) [Field E] (n : ℕ) where + /-- The remaining component of type `Fin n → K0 E`. -/ + c : Fin n → K0 E + hc : ∀ j, 0 ≤ val E (c j) + hd : ∀ i j, i ≠ j → val E (c i - c j) = 0 + /-- The `Data` component of type `Arm n → ℚ`. -/ + r : Arm n → ℚ + hr : ∀ j, 0 < r j + /-- Embeds the coordinates as `ℕ ↪ E`. -/ + u : ℕ ↪ E + hu : ∀ i, u i ≠ 0 + +variable (D : Data E n) {m : Arm n → ℕ} + +open scoped Classical in +/-- Indexes the index by the coordinates of `Σ a, Fin (m a)`. -/ +abbrev Index (m : Arm n → ℕ) := Σ a, Fin (m a) + +open scoped Classical in +/-- Computes the node by the application `armEnd D.c D.r (C (D.u i.2.val)) i.1`. -/ +def node (i : Index m) := armEnd D.c D.r (C (D.u i.2.val)) i.1 + +open scoped Classical in +/-- The indexed operation `d.elim (-D.r none) (fun _ => 0)`. -/ +def shift (d : Arm n) : ℚ := d.elim (-D.r none) (fun _ => 0) + +open scoped Classical in +/-- In the case `some i, some j`, this construction gives `if i = j then D.r (some i) else 0`. -/ +def sep : Arm n → Arm n → ℚ + | some i, some j => if i = j then D.r (some i) else 0 + | _, _ => -D.r none + +open scoped Classical in +private theorem scaled (s : ℚ) {a : E} (h : a ≠ 0) : val E (t s * C a) = ↑s := by + rw [AddValuation.map_mul, val_C h, val_t, add_zero] + +open scoped Classical in +private theorem positive (j : Fin n) (k : ℕ) : 0 < val E (t (D.r (some j)) * C (D.u k)) := by + rw [scaled _ (D.hu _)] + exact WithTop.coe_pos.mpr (D.hr _) + +open scoped Classical in +private theorem integral (j : Fin n) (k : ℕ) : + 0 ≤ val E (D.c j + t (D.r (some j)) * C (D.u k)) := + (le_min (D.hc _) (positive D j k).le).trans ((val E).map_add _ _) + +open scoped Classical in +private theorem outer (k : ℕ) (x : K0 E) (hx : 0 ≤ val E x) : + val E (t (-D.r none) * C (D.u k) - x) = ↑(-D.r none) := by + have h : val E (t (-D.r none) * C (D.u k)) < val E (-x) := by + rw [scaled _ (D.hu _), AddValuation.map_neg] + exact (WithTop.coe_lt_coe.mpr (neg_neg_of_pos (D.hr none))).trans_le hx + rw [sub_eq_add_neg, AddValuation.map_add_of_distinct_val _ h.ne, min_eq_left h.le, + scaled _ (D.hu _)] + +open scoped Classical in +theorem distance (i j : Index m) (h : i ≠ j) : + val E (node D i - node D j) = ↑(sep D i.1 j.1) := by + have same (a : Arm n) (i j : Fin (m a)) (h : (⟨a, i⟩ : Index m) ≠ ⟨a, j⟩) (r : ℚ) : + val E (t r * C (D.u i.val) - t r * C (D.u j.val)) = ↑r := by + have hn : D.u i.val ≠ D.u j.val := fun e => + h (congrArg (Sigma.mk a) (Fin.ext (D.u.injective e))) + rw [← mul_sub, ← map_sub, scaled r (sub_ne_zero.mpr hn)] + obtain ⟨_ | a, i⟩ := i <;> obtain ⟨_ | b, j⟩ := j + · exact same none i j h _ + · exact outer D _ _ (integral D _ _) + · rw [AddValuation.map_sub_swap] + exact outer D _ _ (integral D _ _) + · simp only [node, armEnd, sep] + by_cases he : a = b + · subst b + rw [ite_eq_left rfl, add_sub_add_left_eq_sub] + exact same _ i j h _ + rw [ite_eq_right he] + let x := t (D.r (some a)) * C (D.u i.val) + let y := t (D.r (some b)) * C (D.u j.val) + have hh : val E (D.c a - D.c b) < val E (x - y) := by + rw [D.hd a b he] + exact (lt_min (positive D _ _) (positive D _ _)).trans_le ((val E).map_sub _ _) + change val E (D.c a + x - (D.c b + y)) = 0 + rw [show D.c a + x - (D.c b + y) = (D.c a - D.c b) + (x - y) by ring, + AddValuation.map_add_of_distinct_val _ hh.ne, min_eq_left hh.le, D.hd a b he] + +open scoped Classical in +theorem injective : Function.Injective (node D (m := m)) := by + intro i j e + by_contra h + have hb := distance D i j h + simp [e] at hb + +open scoped Classical in +private theorem node_bound (i : Index m) {x : K0 E} (hx : 0 ≤ val E x) : + ↑(shift D i.1) ≤ val E (x - node D i) := by + obtain ⟨_ | a, i⟩ := i + · rw [AddValuation.map_sub_swap] + exact (outer D _ _ hx).ge + · exact (le_min hx (integral D _ _)).trans ((val E).map_sub _ _) + +open scoped Classical in +theorem lagrange_bound (i : Index m) {x : K0 E} (hx : 0 ≤ val E x) : + ↑(∑ j ∈ univ.erase i, (shift D j.1 - sep D i.1 j.1)) ≤ + val E ((Lagrange.basis univ (node D) i).eval x) := by + let f (j : Index m) := (Lagrange.basisDivisor (node D i) (node D j)).eval x + let g (j : Index m) := shift D j.1 - sep D i.1 j.1 + have h (j : Index m) (hj : j ≠ i) : ↑(g j) ≤ val E (f j) := by + simp only [f, Lagrange.basisDivisor, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_sub, + Polynomial.eval_X, AddValuation.map_mul, AddValuation.map_inv, distance D i j hj.symm] + rw [show g j = -sep D i.1 j.1 + shift D j.1 by unfold g; ring, WithTop.coe_add] + exact add_le_add le_rfl (node_bound D j hx) + have H (s : Finset (Index m)) (hs : i ∉ s) : ↑(∑ j ∈ s, g j) ≤ val E (∏ j ∈ s, f j) := by + induction s using Finset.induction_on with + | empty => simp + | @insert j s hj ih => + rw [sum_insert hj, prod_insert hj, AddValuation.map_mul, WithTop.coe_add] + exact add_le_add (h j (fun he => hs (he ▸ mem_insert_self _ _))) + (ih (fun he => hs (mem_insert_of_mem he))) + rw [Lagrange.basis, Polynomial.eval_prod] + exact H _ (notMem_erase _ _) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.Star +end + +/- +# Choosing the numbers of interpolation nodes + +An inner arm contributes only when its end rate is below the mean. +Its nodes absorb that difference. Their combined multiplicity supplies +the required vanishing order for the outer arm. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.Star + +open Finset +variable {E : Type} [Field E] {n : ℕ} (D : Data E n) + +open scoped Classical in +/-- The sum of `(shift D j.1 - sep D i.1 j.1)` indexed by `j ∈ univ.erase i`. -/ +def credit {m : Arm n → ℕ} (i : Index m) := ∑ j ∈ univ.erase i, (shift D j.1 - sep D i.1 j.1) + +open scoped Classical in +private theorem credit_none (m : Arm n → ℕ) (i : Fin (m none)) : + credit D ⟨none, i⟩ = (∑ j, (m (some j) : ℚ)) * D.r none := by + unfold credit + rw [sum_erase_eq_sub (mem_univ _), Fintype.sum_sigma, Fintype.sum_option] + simp [shift, sep, sum_mul] + +open scoped Classical in +private theorem credit_some (m : Arm n → ℕ) (j : Fin n) (i : Fin (m (some j))) : + credit D ⟨some j, i⟩ = (1 - (m (some j) : ℚ)) * D.r (some j) := by + unfold credit + rw [sum_erase_eq_sub (mem_univ _), Fintype.sum_sigma, Fintype.sum_option] + simp [shift, sep] + ring + +variable (R : Arm n → ℝ) (μ : ℝ) (d N : ℕ) + +open scoped Classical in +/-- The quantity computed by `(μ - R j) / (D.r j : ℝ)`. -/ +def weight (j : Arm n) := (μ - R j) / (D.r j : ℝ) + +open scoped Classical in +/-- In the case `none`, this construction gives `N * d + 1`. -/ +def size : Arm n → ℕ + | none => N * d + 1 + | some j => ⌈(N : ℝ) * weight D R μ (some j)⌉₊ + +open scoped Classical in +theorem sufficient : N * d < Fintype.card (Index (size D R μ d N)) := by + simp only [Index, Fintype.card_sigma, Fintype.card_fin, Fintype.sum_option] + rw [show size D R μ d N none = N * d + 1 from rfl] + omega + +open scoped Classical in +theorem linear_size : ∃ C : ℝ, 0 < C ∧ ∀ N : ℕ, + (Fintype.card (Index (size D R μ d N)) : ℝ) ≤ C * (N + 1) := by + let c (j : Fin n) := ⌈weight D R μ (some j)⌉₊ + refine ⟨(d + 1 + ∑ j, c j : ℕ), by positivity, fun N => ?_⟩ + have hs (j : Fin n) : size D R μ d N (some j) ≤ N * c j := by + apply Nat.ceil_le.mpr + rw [Nat.cast_mul] + exact mul_le_mul_of_nonneg_left (Nat.le_ceil _) (Nat.cast_nonneg _) + have h := sum_le_sum (s := univ) (fun j _ => hs j) + rw [← mul_sum] at h + have hh : Fintype.card (Index (size D R μ d N)) ≤ (d + 1+∑ j, c j) * (N + 1) := by + simp only [Index, Fintype.card_sigma, Fintype.card_fin, Fintype.sum_option] + rw [show size D R μ d N none = N * d + 1 from rfl] + nlinarith only [h, Nat.zero_le (∑ j, c j)] + exact_mod_cast hh + +open scoped Classical in +theorem credit_bound (hμ : 0 ≤ ∑ j, weight D R μ j) (i : Index (size D R μ d N)) : + (N : ℝ) * (R i.1 - μ) ≤ credit D i := by + let m := size D R μ d N + have hr (j) : (0 : ℝ) < D.r j := Rat.cast_pos.mpr (D.hr j) + obtain ⟨_ | j, i⟩ := i + · rw [credit_none] + have hm (j : Fin n) : (N : ℝ) * weight D R μ (some j) ≤ m (some j) := Nat.le_ceil _ + have hsum := sum_le_sum (s := univ) (fun j _ => hm j) + rw [← mul_sum] at hsum + rw [Fintype.sum_option] at hμ + have h : (N : ℝ) * (-weight D R μ none) ≤ ∑ j, (m (some j) : ℝ) := + (mul_le_mul_of_nonneg_left (by linarith only [hμ]) (Nat.cast_nonneg _)).trans hsum + simp only [weight, ← neg_div, neg_sub, ← mul_div_assoc, div_le_iff₀ (hr _)] at h + simpa only [Rat.cast_mul, Rat.cast_sum, Rat.cast_natCast] using h + · rw [credit_some] + have hm : 0 < m (some j) := Nat.zero_lt_of_lt i.isLt + have hx := Nat.ceil_lt_add_one (Nat.ceil_pos.mp hm).le + change (m (some j) : ℝ) < (N : ℝ) * ((μ - R (some j)) / (D.r (some j) : ℝ)) + 1 at hx + rw [← mul_div_assoc, ← sub_lt_iff_lt_add, lt_div_iff₀ (hr _)] at hx + simp only [Rat.cast_mul, Rat.cast_sub, Rat.cast_one, Rat.cast_natCast] + linarith only [hx] + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.Star +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Uniform.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Uniform.lean new file mode 100644 index 0000000000..0615fd5356 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/MatrixExponent/Valued/Uniform.lean @@ -0,0 +1,919 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Valued.StarWeights +public import Mathlib.Data.Fintype.EquivFin +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Tensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Spectral.Place +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Sync +public import Mathlib.Order.Filter.Cocardinal +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Prices.Motion.Rigidity + +/-! +# A discounted state + +Integer thresholds suffice even for rational valuations. Summing the +filtered envelopes with geometric weights gives a positive additive +functional. After taking a character, powers recover rational shifts. +-/ + +@[expose] public section + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral + +variable {E K S : Type} [Field E] [Field K] [Algebra E K] [Infinite E] + [Fintype S] [Nonempty S] + +theorem weighted_state (v : AddValuation K (WithTop ℚ)) (hv : constants E K ≤ integralRing v) + (f : Tensor E S →+* ℝ) (hf : Monotone f) (b : ℝ) (hb : 0 < b) : + ∃ M : ITensor (constants E K) S →+ ℝ, Monotone M ∧ 0 < M 1 ∧ + (∀ A B, M (ITensor.fromBase le_rfl A * B) = f A * M B) ∧ + ∀ (c : K) (m : ℤ), (↑(m : ℚ) : WithTop ℚ) ≤ v c → + ∀ B, M (ITensor.scalar _ _ c * B) ≤ Real.exp (-(m : ℝ) * b) * M B := by + let T := ITensor (constants E K) S + let L (A : T) (n : ℤ) := Real.exp (-(n : ℝ) * b) * best f (cutoff v E n) A + have hp (A : T) (n : ℤ) : 0 ≤ L A n := + mul_nonneg (Real.exp_pos _).le (best_nonneg f hf _ _) + have sum (A : T) : Summable (L A) := by + apply summable_int_iff_summable_nat_and_neg.mpr + constructor + · obtain ⟨C, hC⟩ := sample_bounded f hf A + have hg := summable_geometric_of_lt_one (Real.exp_pos (-b)).le + (Real.exp_lt_one_iff.mpr (neg_neg_of_pos hb)) + refine Summable.of_nonneg_of_le (fun n => hp _ _) ?_ (hg.mul_right C) + intro n + unfold L + rw [Int.cast_natCast, neg_mul, ← mul_neg, Real.exp_nat_mul] + exact mul_le_mul_of_nonneg_left (best_le _ _ _ (fun l _ => hC l)) (by positivity) + · obtain ⟨m, hm⟩ := best_floor v f hf A + apply (summable_nat_add_iff (m + 1)).mp + have e : ∀ n : ℕ, L A (-(↑(n + (m + 1)) : ℤ)) = 0 := by + intro n + unfold L + rw [hm _ (by push_cast; linarith), mul_zero] + simpa only [e] using (summable_zero : Summable (fun _ : ℕ => (0 : ℝ))) + let M : T →+ ℝ := + { toFun := fun A => ∑' n, L A n + map_zero' := by simp [L, best_zero f hf] + map_add' := fun A B => by + rw [← (sum A).tsum_add (sum B)] + exact tsum_congr fun n => by unfold L; rw [best_add f hf, mul_add] } + refine ⟨M, ?_, ?_, ?_, ?_⟩ + · intro A B h + exact Summable.tsum_le_tsum (fun n => mul_le_mul_of_nonneg_left (best_mono f hf _ h) + (Real.exp_pos _).le) (sum A) (sum B) + · have h : 0 < L 1 0 := by simpa [L] using best_unit v f hf hv + exact h.trans_le ((sum _).le_tsum 0 fun n _ => hp _ n) + · intro A B + change (∑' n, L _ n) = _ * ∑' n, L _ n + rw [← tsum_mul_left] + exact tsum_congr fun n => by unfold L; rw [best_mul f hf, mul_left_comm] + · intro c m hc B + let A := ITensor.scalar (constants E K) S c * B + change (∑' n, L A n) ≤ _ * ∑' n, L B n + rw [← (Equiv.addRight m).tsum_eq (L A), ← tsum_mul_left] + refine Summable.tsum_le_tsum (fun n => ?_) + ((sum A).comp_injective (Equiv.addRight m).injective) ((sum B).mul_left _) + change L A (n + m) ≤ _ * L B n + unfold L + have h := best_shift v f hf (s := ↑(n + m)) c hc B + rw [Int.cast_add, add_sub_cancel_right] at h + rw [Int.cast_add, Int.cast_add, neg_add_rev, add_mul, Real.exp_add, ← mul_assoc] + exact mul_le_mul_of_nonneg_left h (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- # A multiplicative lift with valuation bounds -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral Prices + +variable {E K S : Type} [Field E] [Field K] [Algebra E K] [Infinite E] + [Fintype S] [Nonempty S] + +private theorem stable_sum {T I : Type*} [CommSemiring T] (M : T →+ ℝ) (A : I → T) (r : I → ℝ) + (hr : ∀ i, StableLE M (A i) 1 (r i)) (u : Finset I) : + StableLE M (∑ i ∈ u, A i) 1 (∑ i ∈ u, r i) := by + intro x + rw [Finset.sum_mul, map_sum, Finset.sum_mul] + exact Finset.sum_le_sum (fun i _ => hr i x) + +private theorem stable_nat {T : Type*} [CommSemiring T] (M : T →+ ℝ) {A : T} {r : ℝ} + (h : StableLE M A 1 r) (n : ℕ) : StableLE M (A * n) 1 (n * r) := by + intro x + rw [mul_comm A, mul_assoc, ← nsmul_eq_mul, map_nsmul, nsmul_eq_mul, mul_assoc] + exact mul_le_mul_of_nonneg_left (h x) (Nat.cast_nonneg n) + +theorem weighted_character (v : AddValuation K (WithTop ℚ)) (hv : constants E K ≤ integralRing v) + (f : Tensor E S →+* ℝ) (hf : Monotone f) (b : ℝ) (hb : 0 < b) : + ∃ g : ITensor (constants E K) S →+* ℝ, Monotone g ∧ + (∀ A, g (ITensor.fromBase le_rfl A) = f A) ∧ + ∀ (c : K) (m : ℤ), (↑(m : ℚ) : WithTop ℚ) ≤ v c → + g (ITensor.scalar _ _ c) ≤ Real.exp (-(m : ℝ) * b) := by + classical + let O := constants E K + let T := ITensor O S + obtain ⟨M, hm, h1, hf', hM⟩ := weighted_state v hv f hf b hb + have hs (c : K) : ∃ r ≥ 0, StableLE M (ITensor.scalar O S c) 1 r := by + obtain ⟨n, hn⟩ := exists_floor v c + have h := hM c (-n) (by simpa using hn) + exact ⟨_, (Real.exp_pos _).le, fun x => by rw [one_mul]; exact h x⟩ + have mono (x y : T) (h : x ≤ y) (u : T) : M (x * u) ≤ M (y * u) := by + rw [mul_comm x, mul_comm y] + exact hm (ITensor.mul_le_mul_left _ _ _ h) + have lower (A : T) : A ≠ 0 → ∃ c, StableLE M 1 A c := by + refine Quotient.inductionOn A fun a ha => ?_ + obtain ⟨x, hx⟩ := not_forall.mp fun he => ha ((ITensor.ofRaw_eq_zero a).mpr he) + obtain ⟨r, hr, h⟩ := hs (a.coeff x)⁻¹ + refine ⟨r, fun u => ?_⟩ + have e := h (ITensor.scalar O S (a.coeff x) * u) + rw [← mul_assoc, ← ITensor.scalar_mul, inv_mul_cancel₀ hx, ITensor.scalar_one, one_mul, + one_mul] at e + rw [one_mul] + exact e.trans (mul_le_mul_of_nonneg_left (mono _ _ (ITensor.scalar_coeff a x) _) hr) + have upper (A : T) : ∃ c ≥ 0, StableLE M A 1 c := by + refine Quotient.inductionOn A fun a => ?_ + let L (i : ∀ s, a.leg s) := ITensor.scalar O S (a.coeff i) + let B := ∑ i, L i + have hb (i : ∀ s, a.leg s) : L i ≤ B := by + unfold B + rw [← Finset.sum_erase_add _ _ (Finset.mem_univ i)] + simpa only [zero_add] using ITensor.add_le_add_right _ _ (L i) + (ITensor.zero_le (∑ j ∈ Finset.univ.erase i, L j)) + obtain ⟨n, hn⟩ := ITensor.table_bound O a.leg a.coeff B hb + rw [ITensor.table_coeff] at hn + choose r hr h using fun i => hs (a.coeff i) + have h' := stable_nat M (stable_sum M L r h Finset.univ) n + exact ⟨_, mul_nonneg (Nat.cast_nonneg _) (Finset.sum_nonneg fun i _ => hr i), + fun u => (mono _ _ hn u).trans (h' u)⟩ + have test : ProductBound (fun _ : Empty => (1 : T)) (fun _ => (1 : ℝ)) M := by + refine ⟨M 1, fun w => ?_⟩ + cases w with + | nil => simp + | cons i _ => exact i.elim + obtain ⟨g, hg, _, h⟩ := character_of_products ITensor.mul_le_mul_left ITensor.zero_le + (fun _ => zero_le_one) M hm h1 test lower upper + refine ⟨g, hg, ?_, ?_⟩ + · intro A + let X := ITensor.fromBase (show constants E K ≤ O from le_rfl) A + have e : ∀ y, M (X * y) = f A * M y := hf' A + apply le_antisymm + · simpa only [map_one, mul_one] using h X 1 (f A) (fun u => by rw [one_mul, e]) + · rcases le_or_gt (f A) 0 with hn | hn + · exact hn.trans (by rw [← map_zero g]; exact hg (ITensor.zero_le _)) + · have hl := h 1 X (f A)⁻¹ (fun u => by rw [one_mul, e, inv_mul_cancel_left₀ hn.ne']) + rwa [map_one, le_inv_mul_iff₀ hn, mul_one] at hl + · intro c m hc + simpa only [map_one, mul_one] using h (ITensor.scalar O S c) 1 (Real.exp (-(m : ℝ) * b)) + (fun u => by rw [one_mul]; exact hM c m hc u) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end + +/- +# Integral restriction by scalar interpolation + +In a uniform inequality for tensors polynomial in each of finitely +many scalars, integral scalars may replace constants one at a time. +Apply this to the entries of the local restriction matrices. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral + +variable {E K S : Type} [Field E] [Field K] [Algebra E K] [Infinite E] + [Fintype S] [Nonempty S] {O V : Subring K} + +theorem of_polynomial (X : S → Type) [∀ s, Fintype (X s)] + (P : (∀ s, X s) → Polynomial K) : + ∃ d, Family (fun a => table O X (fun x => (P x).eval a)) d := by + classical + obtain ⟨d, hd⟩ := (Set.finite_range (fun x => (P x).natDegree)).bddAbove + exact ⟨d, X, inferInstance, P, fun x => hd ⟨x, rfl⟩, fun _ => rfl⟩ + +theorem Family.bound_constants {A : K → ITensor O S} {d : ℕ} (h : Family A d) + (f : ITensor O S →+* ℝ) (hf : Monotone f) (hV : ∀ c ∈ V, f (scalar O S c) ≤ 1) + (hv : constants E K ≤ V) {r : ℝ} (hr : ∀ a ∈ constants E K, f (A a) ≤ r) + (c : K) (hc : c ∈ V) : f (A c) ≤ r := by + let φ := algebraMap E K + have hi (t : E) : φ t ∈ constants E K := ⟨t, rfl⟩ + refine h.bound_scalar f hf hV φ φ.injective (fun i => hv (hi i)) ?_ (fun i => hr _ (hi i)) c hc + intro i j + rw [← map_sub, ← map_inv₀] + exact hv (hi _) + +theorem bound_grid {I : Type} [Finite I] [DecidableEq I] (A : (I → K) → ITensor O S) + (ha : ∀ x i, ∃ d, Family (fun c => A (Function.update x i c)) d) + (f : ITensor O S →+* ℝ) (hf : Monotone f) (hV : ∀ c ∈ V, f (scalar O S c) ≤ 1) + (hv : constants E K ≤ V) {r : ℝ} (hr : ∀ x, (∀ i, x i ∈ constants E K) → f (A x) ≤ r) + (x : I → K) (hx : ∀ i, x i ∈ V) : f (A x) ≤ r := by + let : Fintype I := Fintype.ofFinite I + have H (t : Finset I) (y : I → K) (hy : ∀ i, y i ∈ V) + (hg : ∀ i ∉ t, y i ∈ constants E K) : f (A y) ≤ r := by + induction t using Finset.induction_on generalizing y with + | empty => exact hr y fun i => hg i (by simp) + | @insert i t _ ih => + obtain ⟨_, hi⟩ := ha y i + have hb (c : K) (hc : c ∈ constants E K) : f (A (Function.update y i c)) ≤ r := by + apply ih + · intro j + by_cases h : j = i + · simpa [h] using hv hc + · simpa [Function.update_of_ne h] using hy j + · intro j hj + by_cases h : j = i + · simpa [h] using hc + · simpa [Function.update_of_ne h] using hg j (by simp [hj, h]) + simpa using hi.bound_constants f hf hV hv hb (y i) (hy i) + exact H Finset.univ x hx fun _ h => (h (Finset.mem_univ _)).elim + +theorem integral_mono (f : ITensor (constants E K) S →+* ℝ) (hf : Monotone f) + (hv : constants E K ≤ V) (hs : ∀ c ∈ V, f (scalar _ _ c) ≤ 1) + {A B : Raw K S} (h : Restricts V A B) : f (ofRaw B) ≤ f (ofRaw A) := by + classical + let I := Σ s, B.leg s × A.leg s + let X (l : I → K) := table (constants E K) B.leg + (fun x => ∑ i : A.term, ∏ s, ∑ y, l ⟨s, x s, y⟩ * A.factor i s y) + have hp (l : I → K) (j : I) : ∃ d, Family (fun c => X (Function.update l j c)) d := by + let L (i : I) := if i = j then Polynomial.X else Polynomial.C (l i) + have e (i : I) (c : K) : (L i).eval c = Function.update l j c i := by + by_cases h : i = j <;> simp [L, h] + let P (x : ∀ s, B.leg s) := + ∑ i : A.term, ∏ s, ∑ y, L ⟨s, x s, y⟩ * Polynomial.C (A.factor i s y) + obtain ⟨d, hd⟩ := of_polynomial (O := constants E K) B.leg P + refine ⟨d, ?_⟩ + simpa only [P, Polynomial.eval_finsetSum, Polynomial.eval_prod, Polynomial.eval_mul, + Polynomial.eval_C, e] using hd + have hr (l : I → K) (hl : ∀ i, l i ∈ constants E K) : f (X l) ≤ f (ofRaw A) := by + apply hf + refine ⟨fun s x y => l ⟨s, x, y⟩, fun _ _ _ => hl _, fun x => ?_⟩ + exact Raw.coeff_ofTable _ _ _ + obtain ⟨L, hL, he⟩ := h + let l (i : I) := L i.1 i.2.1 i.2.2 + have hh := bound_grid X hp f hf hs hv hr l (fun i => hL _ _ _) + have e : X l = ofRaw B := by + unfold X l + rw [← table_coeff (constants E K) B] + exact congrArg _ (funext he).symm + rwa [e] at hh + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- +# Integral restrictions and change of sites + +A surjective grouping preserves sums. Arbitrary placements also allow +unused sites and preserve products, scalar weights and base-field tensors. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral + +variable {K S T R : Type} [Field K] {O : Subring K} + [Fintype S] [Fintype T] [Fintype R] [DecidableEq S] [DecidableEq T] [DecidableEq R] + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def place (f : T → S) : ITensor O T → ITensor O S := + Quotient.map (Raw.group f) fun _ _ h => ⟨h.1.group f, h.2.group f⟩ + +theorem place_ofRaw (f : T → S) (A : Raw K T) : + place f (ofRaw (O := O) A) = ofRaw (A.group f) := rfl + +theorem place_mono (f : T → S) : Monotone (place (O := O) f) := + fun A B => Quotient.inductionOn₂ A B fun _ _ h => Restricts.group h f + +theorem place_zero (f : T → S) : place f (0 : ITensor O T) = 0 := + ofRaw_eq (Raw.integral_group_zero f) + +theorem place_one (f : T → S) : place f (1 : ITensor O T) = 1 := + ofRaw_eq (Raw.integral_group_one f) + +theorem place_mul (f : T → S) (A B : ITensor O T) : + place f (A * B) = place f A * place f B := + Quotient.inductionOn₂ A B fun a b => ofRaw_eq (Raw.integral_group_mul f a b) + +theorem place_id (A : ITensor O S) : place id A = A := + Quotient.inductionOn A fun a => ofRaw_eq (Raw.integral_group_id a) + +theorem place_comp (f : T → S) (g : R → T) (A : ITensor O R) : + place (f ∘ g) A = place f (place g A) := + Quotient.inductionOn A fun a => ofRaw_eq (Raw.integral_group_comp f g a) + +theorem place_inl [Nonempty S] (A : ITensor O S) : + place (Sum.inl : S → S ⊕ T) A = pad T A := + Quotient.inductionOn A fun a => ofRaw_eq (Raw.integral_group_inl a) + +/-- Builds `ITensor O T →+* ITensor O S where toFun` with the specified `toFun`, `map_zero'`, +`map_one'`, `map_mul'`. -/ +def group (f : T → S) (hf : Function.Surjective f) : ITensor O T →+* ITensor O S where + toFun := place f + map_zero' := place_zero f + map_one' := place_one f + map_mul' := place_mul f + map_add' A B := Quotient.inductionOn₂ A B fun a b => ofRaw_eq (Raw.integral_group_add f hf a b) + +theorem place_eq_group (f : T → S) (hf : Function.Surjective f) (A : ITensor O T) : + place f A = group f hf A := rfl + +theorem group_mono (f : T → S) (hf : Function.Surjective f) : + Monotone (group (O := O) f hf) := place_mono f + +theorem group_pad [Nonempty S] (f : S ⊕ T → S) (hf : Function.Surjective f) + (h : ∀ s, f (.inl s) = s) (A : ITensor O S) : + group f hf (pad T A) = A := by + rw [← place_eq_group, ← place_inl, ← place_comp, show f ∘ Sum.inl = id from funext h, place_id] + +theorem place_add_le [Nonempty T] (f : T → S) (A B : ITensor O T) : + place f (A + B) ≤ place f A + place f B := by + let g : T ⊕ S → S := Sum.elim f id + have hg : Function.Surjective g := fun s => ⟨.inr s, rfl⟩ + have he (X : ITensor O T) : place f X = group g hg (pad S X) := by + rw [← place_eq_group, ← place_inl, ← place_comp] + rfl + rw [he, he, he, ← (group g hg).map_add] + exact group_mono g hg ((padding S).add_le A B) + +theorem place_scalar [Nonempty S] [Nonempty T] (f : T → S) (c : K) : + place f (scalar O T c) = scalar O S c := by + apply ofRaw_eq + refine equiv_coeff (fun s => Equiv.ofUnique (Raw.Fiber f s → Unit) Unit) fun x => ?_ + erw [Raw.coeff_group, Raw.coeff_ofTable, Raw.coeff_ofTable] + +variable {E : Type} [Field E] [Algebra E K] (hO : constants E K ≤ O) + +theorem place_fromBase (f : T → S) (A : Tensor E T) : + place f (fromBase hO A) = fromBase hO (Tensor.place f A) := by + refine Quotient.inductionOn A fun a => ofRaw_eq ?_ + refine relabel (Equiv.refl _) (fun _ => Equiv.refl _) fun i s x => ?_ + exact (map_prod (algebraMap E K) _ _).symm + +/-- Computes the wire by the application `fromBase hO (Tensor.wire E a b n)`. -/ +abbrev wire (a b : S) (n : ℕ) : ITensor O S := fromBase hO (Tensor.wire E a b n) + +theorem place_wire (f : T → S) (a b : T) (n : ℕ) : + place f (wire hO a b n) = wire hO (f a) (f b) n := by + simp only [wire, place_fromBase, Tensor.place_wire] + +theorem wire_ofRaw (a b : S) (n : ℕ) : + wire hO a b n = ofRaw (Raw.wire K a b n) := by + apply ofRaw_eq + refine relabel (Equiv.refl _) (fun _ => Equiv.refl _) fun i s x => ?_ + change Fin n at i x + change algebraMap E K (if x = Raw.port {a, b} s i then 1 else 0) = + if x = Raw.port {a, b} s i then 1 else 0 + split <;> simp + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- +# Constant tests suffice for a lifted price + +A restriction to an old-site tensor uses finitely many matrix entries. +Power interpolation bounds its value at integral entries by the uniform +bound at constant entries, even if the old tensor itself varies. +-/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral Prices + +variable {E K S U : Type} [Field E] [Field K] [Algebra E K] + [Fintype S] [Nonempty S] [Fintype U] {O : Subring K} (hv : constants E K ≤ O) + +theorem fromBase_table (X : S → Type) [∀ s, Fintype (X s)] (u : (∀ s, X s) → E) : + fromBase hv (Tensor.ofRaw (Raw.ofTable X u)) = table O X (fun x => algebraMap E K (u x)) := by + apply ofRaw_eq + refine equiv_coeff (fun _ => Equiv.refl _) fun x => ?_ + erw [Raw.coeff_map, Raw.coeff_ofTable, Raw.coeff_ofTable] + rfl + +variable [Infinite E] (f : Tensor E S →+* ℝ) (g : ITensor O S →+* ℝ) + (hg : Monotone g) (he : ∀ A, g (fromBase hv A) = f A) +include hg he + +theorem lift_test (A : Tensor E (S ⊕ U)) {r : ℝ} + (h : ∀ B, Tensor.pad U B ≤ A → f B ≤ r) + (B : ITensor O S) (hB : pad U B ≤ fromBase hv A) : g B ≤ r := by + classical + revert h hB + refine Quotient.inductionOn₂ A B fun a b h hB => ?_ + let φ := algebraMap E K + let I := Σ s, (Raw.pad U b).leg s × a.leg s + let w (x : ∀ s, b.leg s) : ∀ s, (Raw.pad U b).leg s := Sum.rec x (fun _ => ()) + let X (l : I → K) := table O b.leg + (fun x => ∑ i : a.term, ∏ s, ∑ y, l ⟨s, w x s, y⟩ * φ (a.factor i s y)) + have hp (l : I → K) (j : I) : ∃ d, Family (fun c => X (Function.update l j c)) d := by + let L (i : I) := if i = j then Polynomial.X else Polynomial.C (l i) + have e (i : I) (c : K) : (L i).eval c = Function.update l j c i := by + by_cases h : i = j <;> simp [L, h] + let P (x : ∀ s, b.leg s) := + ∑ i : a.term, ∏ s, ∑ y, L ⟨s, w x s, y⟩ * Polynomial.C (φ (a.factor i s y)) + obtain ⟨d, hd⟩ := of_polynomial (O := O) b.leg P + refine ⟨d, ?_⟩ + simpa only [P, Polynomial.eval_finsetSum, Polynomial.eval_prod, Polynomial.eval_mul, + Polynomial.eval_C, e] using hd + have hr (l : I → K) (hl : ∀ i, l i ∈ constants E K) : g (X l) ≤ r := by + choose v ev using hl + let F (x : ∀ s, b.leg s) := ∑ i : a.term, ∏ s, ∑ y, v ⟨s, w x s, y⟩ * a.factor i s y + let C := Raw.ofTable b.leg F + have e : X l = fromBase hv (Tensor.ofRaw C) := by + rw [show C = Raw.ofTable _ F from rfl, fromBase_table] + unfold X F + simp only [map_sum, map_prod, map_mul, ev] + rfl + rw [e, he] + apply h + refine ⟨fun s x y => v ⟨s, x, y⟩, fun x => ?_⟩ + erw [Raw.pad_coeff, Raw.coeff_ofTable] + have hx : w (fun s => x (.inl s)) = x := by funext j; cases j <;> rfl + unfold F + rw [hx] + obtain ⟨L, hi, hL⟩ := hB + let l (i : I) := L i.1 i.2.1 i.2.2 + have hz := bound_grid X hp g hg (fun c hc => by simpa using hg (scalar_le_one O c hc)) hv hr + l (fun i => hi _ _ _) + have e : X l = ofRaw b := by + rw [← table_coeff O b] + unfold X + apply congrArg + funext x + have H := hL (w x) + rw [Raw.pad_coeff] at H + exact H.symm + rw [e] at hz + exact hz + +theorem lift_assisted (hf : Monotone f) (A : Tensor E (S ⊕ U)) : + assisted (pad U) g (fromBase hv A) ≤ Tensor.assisted f A := by + obtain ⟨k, hk, ek, ea⟩ := (Tensor.assisted_minimum f hf A).1 + refine ((extensionData g hg).test_iff _ _).mpr fun n B hB => ?_ + rw [← map_pow] at hB + refine lift_test hv f g hg he _ ?_ B hB + intro C hC + rw [← ea, ← map_pow, ← ek] + exact hk hC + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- A submean bound on a valuation star by one Lagrange interpolation. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor + +open Prices Motion K0 Finset + +variable {E S U : Type} [Field E] [Fintype S] [Nonempty S] [Fintype U] + +open scoped Classical in +theorem scalar_bound {K : Type} [Field K] {v : AddValuation K (WithTop ℚ)} + {W : Subring K} (f : ITensor W S →+* ℝ) + (hscalar : ∀ (z : K) (q : ℚ), v z = ↑q → f (scalar W S z) = Real.exp (-(q : ℝ))) + {z : K} {q : ℚ} (hz : ↑q ≤ v z) : + f (scalar W S z) ≤ Real.exp (-(q : ℝ)) := by + by_cases h : z = 0 + · rw [h, show scalar W S 0 = 0 from (ofRaw_eq_zero _).mpr (fun y + => Spectral.Raw.coeff_ofTable _ _ y), + map_zero] + positivity + obtain ⟨p, hp⟩ := WithTop.ne_top_iff_exists.mp ((v).ne_top_iff.mpr h) + rw [hscalar z p hp.symm, Real.exp_le_exp] + exact neg_le_neg (Rat.cast_le.mpr (WithTop.coe_le_coe.mp (hz.trans_eq hp.symm))) + +variable {A : K0 E → ITensor (integralRing (K0.val E)) (S ⊕ U)} {d : ℕ} + +open scoped Classical in +/-- Bounds at the arm ends imply an upper bound at every integral +parameter. Lengths weight the logarithmic prices by their reciprocals. -/ +theorem Family.assisted_star [Infinite E] (h : Family A d) (f : ITensor (integralRing (K0.val E)) S + →+* ℝ) + (hf : Monotone f) + (hscalar : ∀ (z : K0 E) (q : ℚ), val E z = ↑q → f (scalar (integralRing (K0.val E)) S z) + = Real.exp (-(q : ℝ))) + {n : ℕ} (c : Fin n → K0 E) (hc : ∀ j, 0 ≤ val E (c j)) + (hd : ∀ i j, i ≠ j → val E (c i - c j) = 0) + (r : Option (Fin n) → ℚ) (hr : ∀ j, 0 < r j) (R : Option (Fin n) → ℝ) + (hR : ∀ j y, 0 ≤ val E y → assisted (pad U) f (A (armEnd c r y j)) ≤ Real.exp (R j)) + (μ : ℝ) (hμ : 0 ≤ ∑ j, (μ - R j) / (r j : ℝ)) + (x : K0 E) (hx : 0 ≤ val E x) : assisted (pad U) f (A x) ≤ Real.exp μ := by + let v := (Set.finite_singleton (0 : E)).infinite_compl.natEmbedding _ + let D : Star.Data E n := ⟨c, hc, hd, r, hr, v.trans (Function.Embedding.subtype _), + fun i => (v i).2⟩ + let H := extensionData (U := U) f hf + obtain ⟨C, hC, hb⟩ := Star.linear_size D R μ d + refine H.test_with_loss _ (Real.exp_nonneg _) hC fun N _ s hs => ?_ + let I := Star.Index (Star.size D R μ d N) + let w : I → K0 E := Star.node D + refine (h.test_nodes f hf N x hs w (Star.injective D) (Star.sufficient D R μ d N)).trans ?_ + calc + _ ≤ ∑ _i : I, Real.exp μ ^ N := by + refine sum_le_sum fun i _ => ?_ + have ha : assisted (pad U) f (A (w i)) ≤ Real.exp (R i.1) := + hR _ _ (by rw [val_C (D.hu _)]) + have hp := H.aided_nonneg (A (w i)) + have hl := scalar_bound f hscalar (Star.lagrange_bound D i hx) + refine (mul_le_mul hl (pow_le_pow_left₀ hp ha N) (pow_nonneg hp _) (Real.exp_nonneg _)).trans + ?_ + rw [← Real.exp_nat_mul, ← Real.exp_add, ← Real.exp_nat_mul, Real.exp_le_exp] + have hc := Star.credit_bound D R μ d N hμ i + unfold Star.credit at hc + linarith only [hc] + _ ≤ _ := by + rw [sum_const, card_univ, nsmul_eq_mul] + exact mul_le_mul_of_nonneg_right (hb N) (by positivity) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- # Uniform estimates for prices of polynomial tensors on a valuation disk -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor + +variable {K S : Type} [Field K] [Fintype S] [Nonempty S] + +private theorem poly (v : AddValuation K (WithTop ℚ)) (P : Polynomial K) : + ∃ q : ℚ, ∀ x y, 0 ≤ v x → 0 ≤ v y → ∀ m : ℚ, ↑m ≤ v (x - y) → + ↑q ≤ v (P.eval x) ∧ ↑(q + m) ≤ v (P.eval x - P.eval y) := by + induction P using Polynomial.induction_on with + | C a => + by_cases ha : a = 0 + · exact ⟨0, by simp [ha]⟩ + obtain ⟨q, hq⟩ := WithTop.ne_top_iff_exists.mp (v.ne_top_iff.mpr ha) + exact ⟨q, by simp [← hq]⟩ + | add A B ih ig => + obtain ⟨q, hq⟩ := ih + obtain ⟨r, hr⟩ := ig + refine ⟨min q r, fun x y hx hy m hm => ?_⟩ + obtain ⟨h, h'⟩ := hq x y hx hy m hm + obtain ⟨k, k'⟩ := hr x y hx hy m hm + simp only [Polynomial.eval_add] + rw [add_sub_add_comm] + constructor + · exact v.map_le_add ((WithTop.coe_le_coe.mpr (min_le_left _ _)).trans h) + ((WithTop.coe_le_coe.mpr (min_le_right _ _)).trans k) + · exact v.map_le_add ((WithTop.coe_le_coe.mpr (by gcongr; exact min_le_left _ _)).trans h') + ((WithTop.coe_le_coe.mpr (by gcongr; exact min_le_right _ _)).trans k') + | monomial n a ih => + obtain ⟨q, hq⟩ := ih + refine ⟨q, fun x y hx hy m hm => ?_⟩ + let P := Polynomial.C a * Polynomial.X ^ n + obtain ⟨h, h'⟩ := hq x y hx hy m hm + rw [pow_succ, ← mul_assoc] + change ↑q ≤ v ((P * Polynomial.X).eval x) ∧ + ↑(q + m) ≤ v ((P * Polynomial.X).eval x - (P * Polynomial.X).eval y) + simp only [Polynomial.eval_mul, Polynomial.eval_X] + constructor + · rw [v.map_mul]; exact h.trans (le_add_of_nonneg_right hx) + · rw [show P.eval x * x - P.eval y * y = + (P.eval x - P.eval y) * y + P.eval x * (x - y) by ring] + apply v.map_le_add + · rw [v.map_mul]; exact h'.trans (le_add_of_nonneg_right hy) + · rw [v.map_mul, WithTop.coe_add]; exact add_le_add h hm + +private theorem coordinate_bound [DecidableEq S] {R : Subring K} + (f : ITensor R S →+* ℝ) (hf : Monotone f) (X : S → Type) [∀ s, Fintype (X s)] + (a : (∀ s, X s) → K) : + f (table R X a) ≤ ∑ i, f (scalar R S (a i)) := by + classical + let F i x := if x = i then a i else 0 + have h : (∑ i, F i) = a := by ext x; simp [F] + calc + _ = f (table R X (∑ i, F i)) := by rw [h] + _ ≤ ∑ i, f (table R X (F i)) := table_sum X f hf _ _ + _ ≤ _ := Finset.sum_le_sum fun i _ => hf (table_single _ _ _ _) + +variable {ν : AddValuation K (WithTop ℚ)} +variable {A : K → ITensor (integralRing ν) S} {d : ℕ} + +theorem Family.uniform_bound (h : Family A d) : + ∃ B > (0 : ℝ), ∀ (g : ITensor (integralRing ν) S →+* ℝ), Monotone g → + (∀ (z : K) (r : ℚ), ν z = ↑r → g (scalar (integralRing ν) S z) = Real.exp (-(r : ℝ))) → + ∀ x y : K, x ∈ integralRing ν → y ∈ integralRing ν → ∀ m : ℚ, ↑m ≤ ν (x - y) → + g (A x) ≤ B ∧ |g (A x) - g (A y)| ≤ B * Real.exp (-(m : ℝ)) := by + classical + obtain ⟨X, _, P, _, he⟩ := h + choose q hq using fun i => poly ν (P i) + let B := ∑ i, Real.exp (-(q i : ℝ)) + have hB : 0 ≤ B := Finset.sum_nonneg fun _ _ => (Real.exp_pos _).le + refine ⟨B + 1, by linarith, fun g hg hv x y hx hy m hm => ?_⟩ + let v (x : K) (i : ∀ s, X s) := (P i).eval x + have ha : g (A x) ≤ B := by + rw [he] + refine (coordinate_bound g hg _ _).trans (Finset.sum_le_sum fun i _ => ?_) + exact scalar_bound g hv (hq i x y hx hy m hm).1 + have diff (x y : K) (hx : x ∈ integralRing ν) (hy : y ∈ integralRing ν) (hm : ↑m ≤ ν (x - y)) : + g (A x) - g (A y) ≤ B * Real.exp (-(m : ℝ)) := by + have hb : g (table (integralRing ν) X (v x - v y)) ≤ B * Real.exp (-(m : ℝ)) := by + unfold B + rw [Finset.sum_mul] + refine (coordinate_bound g hg _ _).trans (Finset.sum_le_sum fun i _ => ?_) + rw [← Real.exp_add, ← neg_add, ← Rat.cast_add] + exact scalar_bound g hv (hq i x y hx hy m hm).2 + have hw := hg (table_add (integralRing ν) X (v x - v y) (v y)) + rw [sub_add_cancel, map_add, ← he, ← he] at hw + linarith + have hm' : ↑m ≤ ν (y - x) := by rwa [AddValuation.map_sub_swap] + exact ⟨ha.trans (le_add_of_nonneg_right zero_le_one), + ((abs_sub_le_iff.mpr ⟨diff x y hx hy hm, diff y x hy hx hm'⟩)).trans + (mul_le_mul_of_nonneg_right (le_add_of_nonneg_right zero_le_one) (Real.exp_nonneg _))⟩ + +theorem Family.uniform_continuous (h : Family A d) {ε : ℝ} (hε : 0 < ε) : + ∃ m : ℚ, 0 < m ∧ ∀ (g : ITensor (integralRing ν) S →+* ℝ), Monotone g → + (∀ (z : K) (r : ℚ), ν z = ↑r → g (scalar (integralRing ν) S z) = Real.exp (-(r : ℝ))) → + ∀ x y : K, x ∈ integralRing ν → y ∈ integralRing ν → ↑m ≤ ν (x - y) → |g (A x) - g (A y)| ≤ ε + := by + obtain ⟨B, hB, hc⟩ := h.uniform_bound + obtain ⟨n, hn⟩ := exists_nat_gt (B / ε) + have hn' := (div_pos hB hε).trans hn + refine ⟨n, by exact_mod_cast hn', fun g hg hs x y hx hy hm => + ((hc g hg hs x y hx hy _ hm).2).trans ?_⟩ + rw [Rat.cast_natCast, Real.exp_neg, ← div_eq_mul_inv, div_le_iff₀ (Real.exp_pos _), mul_comm] + exact (div_le_iff₀ hε).mp (hn.le.trans (by linarith [Real.add_one_le_exp (n : ℝ)])) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- # Bounding the assisted cost throughout the valuation ring -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Prices + +variable {K S U : Type} [Field K] [Fintype S] [Nonempty S] [Fintype U] + {O : Subring K} {A : K → ITensor O (S ⊕ U)} {d : ℕ} + +/-- A uniform bound at infinitely many integral nodes with unit differences +extends to every integral argument, even with joint closures of powers. -/ +theorem Family.assisted_bound (h : Family A d) (f : ITensor O S →+* ℝ) (hf : Monotone f) + {J : Type*} [Infinite J] (v : J → K) (hv : Function.Injective v) + (hi : ∀ i, v i ∈ O) (hu : ∀ i j, (v i - v j)⁻¹ ∈ O) + {r : ℝ} (hr : ∀ j, assisted (pad U) f (A (v j)) ≤ r) (x : K) (hx : x ∈ O) : + assisted (pad U) f (A x) ≤ r := by + let H := extensionData (U := U) f hf + have hp := (H.aided_nonneg _).trans (hr (Classical.arbitrary J)) + refine H.test_with_loss _ hp (show 0 < (d : ℝ) + 1 by positivity) fun n _ s hs => ?_ + let w : Fin (n * d + 1) ↪ J := Fin.valEmbedding.trans (Infinite.natEmbedding J) + have hl (i : Fin (n * d + 1)) : (Lagrange.basis Finset.univ (v ∘ w) i).eval x ∈ O := by + simp only [Lagrange.basis, Lagrange.basisDivisor, Polynomial.eval_prod, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_sub, Polynomial.eval_X] + exact O.prod_mem fun j _ => O.mul_mem (hu _ _) (O.sub_mem hx (hi _)) + refine (h.test_nodes f hf n x hs (v ∘ w) (hv.comp w.injective) (by simp)).trans ?_ + calc + _ ≤ ∑ _i : Fin (n * d + 1), r ^ n := by + refine Finset.sum_le_sum fun i _ => ?_ + have hz := H.aided_nonneg (A (v (w i))) + have hb := hf (scalar_le_one O _ (hl i)) + rw [map_one] at hb + exact (mul_le_of_le_one_left (pow_nonneg hz _) hb).trans (pow_le_pow_left₀ hz (hr _) _) + _ ≤ _ := by + rw [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] + apply mul_le_mul_of_nonneg_right _ (pow_nonneg hp n) + push_cast + linarith + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- # Lifting simultaneous parameter tests to the integral ring -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +open Spectral Prices + +variable {F K S I : Type} [Field F] [Field K] [Algebra F K] + [Fintype S] [Nonempty S] {O : Subring K} (hv : constants F K ≤ O) + +theorem fromBase_pad (U : Type) [Fintype U] (A : Tensor F S) : + fromBase hv (Tensor.pad U A) = pad U (fromBase hv A) := by + classical + classical + rw [← place_inl, place_fromBase, Tensor.place_inl] + +theorem Family.list_prod {I : Type*} (A : I → K → ITensor O S) (h : ∀ i, ∃ d, Family (A i) d) + (w : List I) : ∃ d, Family (fun x => (w.map (fun i => A i x)).prod) d := by + induction w with + | nil => + refine ⟨0, fun _ => Unit, inferInstance, fun _ => 1, by simp, fun _ => ?_⟩ + simp only [List.map_nil, List.prod_nil, Polynomial.eval_one] + exact (scalar_one (S := S) (O := O)).symm + | cons i w ih => + obtain ⟨d, hd⟩ := h i + obtain ⟨e, he⟩ := ih + exact ⟨d + e, hd.mul he⟩ + +/-- Transforms the indexed data by `table O X (fun u => ((A u).map (algebraMap F K)).eval x)`. -/ +def liftFamily (X : S → Type) [∀ s, Fintype (X s)] (A : (∀ s, X s) → Polynomial F) + (x : K) : ITensor O S := + table O X (fun u => ((A u).map (algebraMap F K)).eval x) + +theorem liftFamily_constant (X : S → Type) [∀ s, Fintype (X s)] + (A : (∀ s, X s) → Polynomial F) (x : F) : + liftFamily X A (algebraMap F K x) = fromBase hv (evalFamily X A x) := by + unfold evalFamily liftFamily + rw [fromBase_table] + simp only [Polynomial.eval_map_apply] + +/-- For a fixed integral parameter, a lifted price passes all product +tests if the original tests hold off a finite set in the infinite base. -/ +theorem lift_shared [Infinite F] (f : Tensor F S →+* ℝ) (hf : Monotone f) + (g : ITensor O S →+* ℝ) (hg : Monotone g) (he : ∀ A, g (fromBase hv A) = f A) + (B : Finset F) (X : I → S ⊕ Unit → Type) [∀ i s, Fintype (X i s)] + (P : ∀ i, (∀ s, X i s) → Polynomial F) (p : I → ℝ) + (h : ∀ z ∉ B, ∀ w : List I, ∀ T, Tensor.pad Unit T ≤ + (w.map (fun i => evalFamily (X i) (P i) z)).prod → f T ≤ (w.map p).prod) + (z : K) (hz : z ∈ O) : + ∃ k : ITensor O (S ⊕ Unit) →+* ℝ, Monotone k ∧ (∀ T, k (pad Unit T) = g T) ∧ + ∀ i, k (liftFamily (X i) (P i) z) ≤ p i := by + classical + let A i : K → ITensor O (S ⊕ Unit) := liftFamily (X i) (P i) + have hA i : ∃ d, Family (A i) d := of_polynomial _ _ + let H := extensionData (U := Unit) g hg + apply (H.assisted_extension_iff _ p).mpr + intro w + obtain ⟨d, hd⟩ := Family.list_prod A hA w + let J := (↑B : Set F)ᶜ + let _ : Infinite J := B.finite_toSet.infinite_compl.to_subtype + let v (j : J) := algebraMap F K j.val + have hvi : Function.Injective v := fun _ _ h => Subtype.ext ((algebraMap F K).injective h) + refine hd.assisted_bound g hg v hvi (fun i => hv ⟨i.val, rfl⟩) ?_ ?_ z hz + · intro i j + simp only [v, ← map_sub, ← map_inv₀] + exact hv ⟨_, rfl⟩ + · intro i + let T j := evalFamily (X j) (P j) i.val + have ha : (w.map (fun j => A j (v i))).prod = fromBase hv (w.map T).prod := by + erw [map_list_prod (fromBase hv), List.map_map] + exact congrArg List.prod (List.map_congr_left fun j _ => liftFamily_constant hv _ _ _) + rw [ha] + exact (lift_assisted hv f g hg he hf _).trans + ((Tensor.assisted_extension_iff f hf T p).mp ((Tensor.extension_iff f hf T p).mpr (h i.val + i.property)) w) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- Generic constants maximize assisted values throughout the valuation disk. -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor + +open Prices Motion K0 Finset Filter + +variable {E S U : Type} [Field E] [Fintype S] [Nonempty S] [Fintype U] + +variable {A : K0 E → ITensor (integralRing (K0.val E)) (S ⊕ U)} {d : ℕ} (h : Family A d) + (f : ITensor (integralRing (K0.val E)) S →+* ℝ) (hf : Monotone f) + +include h hf + +open scoped Classical in +theorem Family.assisted_generic (x : K0 E) (hx : 0 ≤ val E x) (r : ℝ) + (hr : r < assisted (pad U) f (A x)) : + ∀ᶠ c : E in cofinite, r < assisted (pad U) f (A (C c)) := by + rw [eventually_cofinite] + by_contra hi + let B := {c : E | ¬ r < assisted (pad U) f (A (C c))} + let _ : Infinite B := (show B.Infinite from hi).to_subtype + have hc (a : E) : C a ∈ integralRing (K0.val E) := by + change 0 ≤ val E (C a) + by_cases ha : a = 0 <;> simp [ha] + apply hr.not_ge + refine h.assisted_bound f hf (fun a : B => C a.val) (fun _ _ h => Subtype.ext (C.injective h)) + (fun a => hc a.val) ?_ (fun a => le_of_not_gt a.property) x hx + intro i j + rw [← map_sub, ← map_inv₀] + exact hc _ + +open scoped Classical in +theorem Family.assisted_max : + ∀ᶠ c : E in cocountable, ∀ x : K0 E, 0 ≤ val E x → + assisted (pad U) f (A x) ≤ assisted (pad U) f (A (C c)) := by + have countable (p : E → ℚ → Prop) (hp : ∀ q, ∀ᶠ c in cocountable, p c q) : + ∀ᶠ c in cocountable, ∀ q, p c q := by + apply mem_cocountable.mpr + have h := Set.countable_iUnion (fun q => mem_cocountable.mp (hp q)) + refine h.mono fun c hc => ?_ + change ¬ (∀ q, p c q) at hc + obtain ⟨q, hq⟩ := not_forall.mp hc + exact Set.mem_iUnion.mpr ⟨q, hq⟩ + let g x := assisted (pad U) f (A x) + have hm : ∀ᶠ c : E in cocountable, ∀ r : ℚ, (∃ x, 0 ≤ val E x ∧ (r : ℝ) < g x) → + (r : ℝ) < g (C c) := by + apply countable + intro r + by_cases he : ∃ x, 0 ≤ val E x ∧ (r : ℝ) < g x + · obtain ⟨x, hx, hr⟩ := he + have hs := h.assisted_generic f hf x hx r hr + have he' : ∀ᶠ c : E in cocountable, (r : ℝ) < g (C c) := + mem_cocountable.mpr (mem_cofinite.mp hs).countable + exact he'.mono fun _ h _ => h + · exact Eventually.of_forall fun _ h => (he h).elim + refine hm.mono fun c hc x hx => ?_ + by_contra! h + obtain ⟨r, hr, hr'⟩ := exists_rat_btwn h + exact hr.not_gt (hc r ⟨x, hx, hr'⟩) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued.ITensor +end + +/- # Families of tensor products on a valuation disk -/ + +noncomputable section +namespace MatrixMultiplicationAllFields.MatrixExponent.Valued +open Spectral Prices Motion K0 ITensor Filter + +variable {E K S U : Type} [Field E] [Field K] [Fintype S] [Fintype U] [Nonempty S] {O : Subring K} + +theorem countable_tensor [Countable K] : Countable (Tensor K S) := by + classical + let B := Σ d : S → ℕ, ((∀ i, Fin (d i)) → K) + let repr (b : B) := Tensor.ofRaw (Raw.ofTable (fun i => Fin (b.1 i)) b.2) + have hs : Function.Surjective repr := by + intro A + refine Quotient.inductionOn A fun a => ?_ + let d s := Fintype.card (a.leg s) + let f s : Fin (d s) ≃ a.leg s := (Fintype.equivFin _).symm + let b : B := ⟨d, fun x => a.coeff (fun s => f s (x s))⟩ + refine ⟨b, Tensor.ofRaw_eq (Raw.equiv_coeff f ?_)⟩ + exact fun x => Raw.coeff_ofTable _ _ x + exact hs.countable + +namespace ITensor +variable {A : K → ITensor O S} {d : ℕ} + +theorem Family.constantValue (A : ITensor O S) : ∃ d, Family (fun _ => A) d := by + refine Quotient.inductionOn A fun a => ?_ + refine ⟨0, a.leg, inferInstance, fun i => Polynomial.C (a.coeff i), by simp, fun x => ?_⟩ + simp only [Polynomial.eval_C, table_coeff] + rfl + +theorem Family.affine (h : Family A d) (a b : K) : ∃ e, Family (fun s => A (a + b * s)) e := by + obtain ⟨X, _, P, _, h⟩ := h + let q := Polynomial.C a + Polynomial.C b * Polynomial.X + have e (x : K) : q.eval x = a + b * x := by + simp only [q, Polynomial.eval_add, Polynomial.eval_C, Polynomial.eval_mul, Polynomial.eval_X] + simpa only [Polynomial.eval_comp, e, h] using of_polynomial (O := O) X (fun i => (P i).comp q) + +theorem Family.place [Nonempty U] [DecidableEq S] [DecidableEq U] + (h : Family A d) (e : S → U) : ∃ n, Family (fun x => ITensor.place e (A x)) n := by + obtain ⟨X, _, P, _, hp⟩ := h + let L u := ∀ i : Raw.Fiber e u, X i + let R (a : ∀ u, L u) := P (fun s => a (e s) ⟨s, rfl⟩) + have eq (x) : ITensor.place e (A x) = table O L (fun a => (R a).eval x) := by + rw [hp] + refine ofRaw_eq (equiv_coeff (fun _ => Equiv.refl _) fun z => ?_) + erw [Raw.coeff_group, Raw.coeff_ofTable, Raw.coeff_ofTable] + rfl + simpa only [eq] using of_polynomial (O := O) L R + +end ITensor + +/-- Computes the ring of by the application `integralRing (val E)`. -/ +abbrev RingOf (E : Type) [Field E] : Subring (K0 E) := integralRing (val E) + +theorem C_mem (c : E) : C c ∈ RingOf E := by + change 0 ≤ val E (C c) + by_cases h : c = 0 <;> simp [h] + +/-- Countably many polynomial tests can be maximized simultaneously. +The additional supremum over j need not be attained. -/ +theorem generic_bounds {I J : Type*} [Countable I] (f : ITensor (RingOf E) S →+* ℝ) + (hf : Monotone f) (A : I → J → K0 E → ITensor (RingOf E) (S ⊕ U)) + (hA : ∀ i j, ∃ d, Family (A i j) d) : + ∀ᶠ c : E in cocountable, ∀ i r, (∀ j, assisted (pad U) f (A i j (C c)) ≤ r) → + ∀ j x, x ∈ RingOf E → assisted (pad U) f (A i j x) ≤ r := by + have := cocountable_countable E + apply eventually_countable_forall.mpr + intro i + let p j x := assisted (pad U) f (A i j x) + have ht : ∀ᶠ c : E in cocountable, ∀ t : ℚ, (∃ j x, x ∈ RingOf E ∧ ↑t < p j x) → + ∃ j, ↑t < p j (C c) := by + apply eventually_countable_forall.mpr + intro t + by_cases h : ∃ j x, x ∈ RingOf E ∧ ↑t < p j x + · obtain ⟨j, x, hx, ht⟩ := h + obtain ⟨_, hj⟩ := hA i j + exact (hj.assisted_max f hf).mono fun c hc _ => ⟨j, ht.trans_le (hc x hx)⟩ + · exact Eventually.of_forall fun _ hh => (h hh).elim + refine ht.mono fun c hc r hr j x hx => ?_ + by_contra! h + obtain ⟨t, h₁, h₂⟩ := exists_rat_btwn h + obtain ⟨k, hk⟩ := hc t ⟨j, x, hx, h₂⟩ + exact (h₁.trans hk).not_ge (hr k) + +end MatrixMultiplicationAllFields.MatrixExponent.Valued +end diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/AbsoluteTensorRank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/AbsoluteTensorRank.lean new file mode 100644 index 0000000000..0f8c053e26 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/AbsoluteTensorRank.lean @@ -0,0 +1,133 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.AlgebraicExtensionRank +public import Mathlib.RingTheory.Nullstellensatz +public import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure +public import Mathlib.FieldTheory.PrimeField +public import Mathlib.Algebra.Algebra.ZMod + +/-! # Asymptotic rank over all fields of a characteristic + +The polynomial equations expressing a decomposition over any field extension +have a solution over the algebraic closure. Combining this specialization +with finite-extension descent gives scalar invariance without an algebraicity +hypothesis, hence characteristic invariance for matrix multiplication tensors. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open MatrixMultiplication.Foundation + +section + +variable {F E : Type*} [Field F] [Field E] [Algebra F E] +variable (K : Type*) [Field K] [Algebra F K] [IsAlgClosed K] + +/-- Specialize a finite tuple to an algebraically closed field while preserving +all polynomial equalities over its ground field. -/ +theorem exists_specialization {V : Type*} [Finite V] (a : V → E) : + ∃ b : V → K, ∀ p : MvPolynomial V F, MvPolynomial.aeval a p = 0 → + MvPolynomial.aeval b p = 0 := by + let I := MvPolynomial.vanishingIdeal F {a} + obtain ⟨J, hJ, hIJ⟩ := Ideal.exists_le_maximal I (Ideal.IsPrime.ne_top (inferInstance : + I.IsPrime)) + obtain ⟨b, hb⟩ := MvPolynomial.eq_vanishingIdeal_singleton_of_isMaximal K hJ + refine ⟨b, fun p hp ↦ (MvPolynomial.mem_vanishingIdeal_singleton_iff b p).mp ?_⟩ + rw [← hb] + exact hIJ ((MvPolynomial.mem_vanishingIdeal_singleton_iff a p).mpr hp) + +/-- A finite tensor defined over `F` admitting an exact rank decomposition over +`E` admits one of the same size over an algebraically closed `K` extending `F`. -/ +theorem rankAtMost_of_extension_to_algClosed {X Y Z : Type*} + [Finite X] [Finite Y] [Finite Z] {T : Tensor F X Y Z} {r : ℕ} + (h : Tensor.RankAtMost (fun x y z ↦ algebraMap F E (T x y z)) r) : + Tensor.RankAtMost (fun x y z ↦ algebraMap F K (T x y z)) r := by + classical + obtain ⟨A, B, C, habc⟩ := h + let v : Fin r × (X ⊕ Y ⊕ Z) → E := fun p ↦ p.2.elim (A p.1) (Sum.elim (B p.1) (C p.1)) + obtain ⟨w, hw⟩ := exists_specialization (F := F) K v + refine ⟨fun i x ↦ w (i, .inl x), fun i y ↦ w (i, .inr (.inl y)), + fun i z ↦ w (i, .inr (.inr z)), ?_⟩ + funext x y z + let p : MvPolynomial (Fin r × (X ⊕ Y ⊕ Z)) F := MvPolynomial.C (T x y z) - ∑ i, + MvPolynomial.X (i, .inl x) * MvPolynomial.X (i, .inr (.inl y)) * MvPolynomial.X (i, + .inr (.inr z)) + have hp : MvPolynomial.aeval v p = 0 := by + simpa [p, v, Tensor.rankOne, sub_eq_zero] using congrFun (congrFun (congrFun habc x) y) z + simpa [p, Tensor.rankOne, sub_eq_zero] using hw p hp + +/-- A scalar extension of any transcendence degree preserves the asymptotic +rank of every finite three-tensor. -/ +theorem asymptoticRank_map_eq {X Y Z : Type*} [Finite X] [Finite Y] [Finite Z] + (T : Tensor F X Y Z) : + asymptoticRank (fun x y z ↦ algebraMap F E (T x y z)) = asymptoticRank T := by + apply le_antisymm (asymptoticRank_map_le T) + rw [← asymptoticRank_map_eq_of_isAlgebraic (K := AlgebraicClosure F) T] + apply le_ciInf + intro n + let U := fun x y z ↦ algebraMap F E (T x y z) + let V := fun x y z ↦ algebraMap F (AlgebraicClosure F) (T x y z) + have h : Tensor.RankAtMost (fun x y z ↦ algebraMap F E (Tensor.power T (n + 1) x y z)) + (tensorRank (Tensor.power U (n + 1))) := by + rw [← power_scalarExtension (K := E)] + exact rankAtMost_tensorRank _ + have hV := rankAtMost_of_extension_to_algClosed (AlgebraicClosure F) h + have hle : tensorRank (Tensor.power V (n + 1)) ≤ tensorRank (Tensor.power U (n + 1)) := by + apply tensorRank_le_of_rankAtMost + rw [← power_scalarExtension (K := AlgebraicClosure F)] at hV + exact hV + apply (ciInf_le (f := fun k : ℕ ↦ (tensorRank (Tensor.power V (k+1)) : ℝ) ^ ((k+1:ℝ)⁻¹)) + ⟨0, by rintro _ ⟨k, rfl⟩; positivity⟩ n).trans + exact Real.rpow_le_rpow (by positivity) (by exact_mod_cast hle) (by positivity) + +/-- All fields extending `F` give the same asymptotic rank to the matrix tensor. -/ +theorem asymptoticRank_matrixTensor_baseChange (F E : Type*) [Field F] [Field E] [Algebra F E] + (a b c : ℕ) : asymptoticRank (matrixTensor E a b c) = asymptoticRank (matrixTensor F a b c) + := by + convert asymptoticRank_map_eq (E := E) (matrixTensor F a b c) using 2 + funext x y z + simp only [matrixTensor, Tensor.matrixCoefficients] + split <;> simp + +/-- The rectangular matrix tensor's asymptotic rank depends only on the +characteristic, including characteristic zero. -/ +theorem asymptoticRank_matrixTensor_eq_of_ringChar_eq (F E : Type*) [Field F] [Field E] + (hchar : ringChar F = ringChar E) (a b c : ℕ) : + asymptoticRank (matrixTensor F a b c) = asymptoticRank (matrixTensor E a b c) := by + by_cases hzero : ringChar F = 0 + · let : CharZero F := (CharP.ringChar_zero_iff_CharZero F).mp hzero + let : CharZero E := (CharP.ringChar_zero_iff_CharZero E).mp (hchar.symm.trans hzero) + exact (asymptoticRank_matrixTensor_baseChange ℚ F a b c).trans + (asymptoticRank_matrixTensor_baseChange ℚ E a b c).symm + · let : Fact (ringChar F).Prime := ⟨(CharP.char_is_prime_or_zero F (ringChar F)).resolve_right + hzero⟩ + let : CharP E (ringChar F) := ringChar.eq_iff.mp hchar.symm + let : Algebra (ZMod (ringChar F)) E := ZMod.algebra _ _ + let : Algebra (ZMod (ringChar F)) F := ZMod.algebra _ _ + exact (asymptoticRank_matrixTensor_baseChange (ZMod (ringChar F)) F a b c).trans + (asymptoticRank_matrixTensor_baseChange (ZMod (ringChar F)) E a b c).symm + +/-- The characteristic-wise comparison in the notation `CharP F p`, with `p = 0` +allowed. -/ +theorem matrix_asymptoticRank_eq_of_charP (F G : Type*) [Field F] [Field G] + (p : ℕ) [CharP F p] [CharP G p] (x y z : ℕ) : + asymptoticRank (matrixTensor F x y z) = asymptoticRank (matrixTensor G x y z) := + asymptoticRank_matrixTensor_eq_of_ringChar_eq F G + ((ringChar.eq_iff.mpr (inferInstance : CharP F p)).trans + (ringChar.eq_iff.mpr (inferInstance : CharP G p)).symm) x y z + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/AlgebraicExtensionRank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/AlgebraicExtensionRank.lean new file mode 100644 index 0000000000..9b02e0fda2 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/AlgebraicExtensionRank.lean @@ -0,0 +1,73 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FiniteExtensionRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.RankCoefficients +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.PowerRank + +/-! # Asymptotic rank is invariant under algebraic scalar extension + +A decomposition of a fixed power has only finitely many coefficients. +Over an algebraic extension they lie in a finite-dimensional intermediate +field, so the finite-extension estimate applies to that power. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open MatrixMultiplication.Foundation + +section + +variable {F K X Y Z : Type*} [Field F] [Field K] [Algebra F K] + +variable [Finite X] [Finite Y] + +/-- Exact rank does not increase under extension, hence neither does +asymptotic rank. -/ +theorem asymptoticRank_map_le (T : Tensor F X Y Z) : + asymptoticRank (fun x y z => algebraMap F K (T x y z)) ≤ asymptoticRank T := by + let U := fun x y z => algebraMap F K (T x y z) + apply le_ciInf + intro n + have h := tensorRank_le_of_rankAtMost + ((rankAtMost_tensorRank (Tensor.power T (n+1))).map (algebraMap F K)) + rw [← power_scalarExtension] at h + apply (ciInf_le (f := fun k : ℕ => (tensorRank (Tensor.power U (k+1)) : ℝ) ^ ((k+1:ℝ)⁻¹)) + ⟨0, by rintro _ ⟨k, rfl⟩; positivity⟩ n).trans + apply Real.rpow_le_rpow (by positivity) _ (by positivity) + exact_mod_cast h + +/-- An algebraic extension leaves the asymptotic rank of every finite tensor unchanged. -/ +theorem asymptoticRank_map_eq_of_isAlgebraic [Algebra.IsAlgebraic F K] [Finite Z] + (T : Tensor F X Y Z) : + asymptoticRank (fun x y z => algebraMap F K (T x y z)) = asymptoticRank T := by + apply le_antisymm (asymptoticRank_map_le T) + apply le_ciInf + intro n + let U := fun x y z => algebraMap F K (T x y z) + let r := tensorRank (Tensor.power U (n+1)) + have h : Tensor.RankAtMost (fun x y z => algebraMap F K (Tensor.power T (n+1) x y z)) r := by + rw [← power_scalarExtension] + exact rankAtMost_tensorRank _ + obtain ⟨S, hS, hfin⟩ := exists_finiteDimensional_rankAtMost h + have hle := asymptoticRank_le_of_finiteExtension hfin + rw [asymptoticRank_power] at hle + have hroot := Real.rpow_le_rpow (pow_nonneg (asymptoticRank_nonneg T) (n+1)) hle + (inv_nonneg.mpr (Nat.cast_nonneg (n+1))) + rw [Real.pow_rpow_inv_natCast (asymptoticRank_nonneg _) (Nat.succ_ne_zero n)] at hroot + simpa only [Nat.cast_add, Nat.cast_one] using hroot + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/ArithmeticExponent.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/ArithmeticExponent.lean new file mode 100644 index 0000000000..8776583528 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/ArithmeticExponent.lean @@ -0,0 +1,204 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Asymptotic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Circuit +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Flattening + +/-! # Rectangular arithmetic exponents over a field + +The wire order is (12,23,31), so the product has dimensions +`(n31 × n12) × (n12 × n23)`. Correctness means polynomial identity over +the ground field, including when that field is finite. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open MatrixMultiplication.Arithmetic + +noncomputable section + +/-- Admissible exponents for the rounded rectangular formats, with positive slack. -/ +def FormalAdmissibleExponent (F : Type*) [Field F] (w12 w23 w31 τ : ℝ) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ N : ℕ, 1 ≤ N → + ∃ P : MatrixAlgorithm F (wireDimension N w31) (wireDimension N w12) (wireDimension N w23), + FormalCorrect P ∧ (P.cost : ℝ) ≤ C * (N : ℝ) ^ (τ + ε) + +/-- The arithmetic exponent in base size `N` at three prescribed wire weights. -/ +def formalOmega (F : Type*) [Field F] (w12 w23 w31 : ℝ) : ℝ := + sInf {τ : ℝ | FormalAdmissibleExponent F w12 w23 w31 τ} + +/-- The entrywise algorithm gives an admissible exponent in every weighted format. -/ +theorem formalAdmissibleExponent_naive (F : Type*) [Field F] {w12 w23 w31 : ℝ} + (h12 : 0 ≤ w12) (h23 : 0 ≤ w23) (h31 : 0 ≤ w31) : + FormalAdmissibleExponent F w12 w23 w31 (w12 + w23 + w31) := by + intro ε hε + refine ⟨16, by norm_num, ?_⟩ + intro N hN + refine ⟨Arithmetic.naiveAlgorithm _ _ _, formalCorrect_naiveAlgorithm F _ _ _, ?_⟩ + rw [Arithmetic.naiveAlgorithm_cost] + push_cast + have h : 1 ≤ (N : ℝ) := by exact_mod_cast hN + calc + _ ≤ 2 * (2 * (N : ℝ) ^ w31) * (2 * (N : ℝ) ^ w12) * (2 * (N : ℝ) ^ w23) := by + gcongr <;> apply wireDimension_le hN <;> assumption + _ = 16 * (N : ℝ) ^ (w12 + w23 + w31) := by + rw [Real.rpow_add (zero_lt_one.trans_le h), Real.rpow_add (zero_lt_one.trans_le h)] + ring + _ ≤ _ := mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow_of_exponent_le h (le_add_of_nonneg_right hε.le)) (by norm_num) + +/-- Positive slack allows the infimum itself as an admissible exponent. -/ +theorem formalOmega_admissible (F : Type*) [Field F] {w12 w23 w31 : ℝ} + (h12 : 0 ≤ w12) (h23 : 0 ≤ w23) (h31 : 0 ≤ w31) : + FormalAdmissibleExponent F w12 w23 w31 (formalOmega F w12 w23 w31) := by + intro ε hε + let S := {τ : ℝ | FormalAdmissibleExponent F w12 w23 w31 τ} + have hS : S.Nonempty := ⟨_, formalAdmissibleExponent_naive F h12 h23 h31⟩ + obtain ⟨τ, hτ, hclose⟩ := exists_lt_of_csInf_lt hS + (lt_add_of_pos_right (sInf S) (half_pos hε)) + obtain ⟨C, hC, hbound⟩ := hτ (ε / 2) (half_pos hε) + refine ⟨C, hC, fun N hN => ?_⟩ + obtain ⟨P, hP, hcost⟩ := hbound N hN + refine ⟨P, hP, hcost.trans (mul_le_mul_of_nonneg_left ?_ hC.le)⟩ + apply Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast hN) + change τ + ε / 2 ≤ sInf S + ε + linarith + +/-- A formal arithmetic cost bound also controls ordinary rank in each rounded format. -/ +theorem FormalAdmissibleExponent.rank_growth {F : Type*} [Field F] {w12 w23 w31 τ : ℝ} + (hτ : FormalAdmissibleExponent F w12 w23 w31 τ) (ε : ℝ) (hε : 0 < ε) : + ∃ C : ℝ, 0 < C ∧ ∀ N : ℕ, 1 ≤ N → + (tensorRank (matrixTensor F (wireDimension N w12) (wireDimension N w23) + (wireDimension N w31)) : ℝ) ≤ C * (N : ℝ) ^ (τ + ε) := by + obtain ⟨C, hC, hc⟩ := hτ ε hε + refine ⟨2 * C, by positivity, ?_⟩ + intro N hN + obtain ⟨P, hP, hcost⟩ := hc N hN + calc + _ ≤ (2 : ℝ) * P.cost := by exact_mod_cast matrixTensor_rank_le_twice_cost hP + _ ≤ 2 * (C * (N : ℝ) ^ (τ + ε)) := by linarith only [hcost] + _ = _ := by ring + +theorem matrixTensor_rank_pos (F : Type*) [Field F] {x y z : ℕ} + (hx : 0 < x) (hy : 0 < y) (hz : 0 < z) : 0 < tensorRank (matrixTensor F x y z) := + (Nat.mul_pos hz hx).trans_le ((le_max_left _ _).trans (matrix_flattening_le_tensorRank F hx hy + hz)) + +/-- Each logarithmic site load is a lower bound on the ordinary log-rank. -/ +theorem matrix_load_le_log_tensorRank (F : Type*) [Field F] {x y z : ℕ} + (hx : 0 < x) (hy : 0 < y) (hz : 0 < z) (i : Fin 3) : + loads (Real.logb 2 x) (Real.logb 2 y) (Real.logb 2 z) i ≤ + Real.logb 2 (tensorRank (matrixTensor F x y z)) := by + let r := tensorRank (matrixTensor F x y z) + have hlog {a b : ℕ} (ha : 0 < a) (hb : 0 < b) (hprod : a * b ≤ r) : + Real.logb 2 a + Real.logb 2 b ≤ Real.logb 2 r := by + rw [← Real.logb_mul (by positivity : (a : ℝ) ≠ 0) (by positivity : (b : ℝ) ≠ 0)] + apply Real.logb_le_logb_of_le (by norm_num) (by positivity) + exact_mod_cast hprod + obtain ⟨h₁, h₂, h₃⟩ := (max_le_iff.mp (matrix_flattening_le_tensorRank F hx hy hz)).imp_right + max_le_iff.mp + fin_cases i + · exact hlog hz hx h₁ + · exact hlog hx hy h₂ + · exact hlog hy hz h₃ + +/-- Every formal rectangular arithmetic exponent dominates each local dimension exponent. -/ +theorem FormalAdmissibleExponent.load_le {F : Type*} [Field F] {w12 w23 w31 τ : ℝ} + (hτ : FormalAdmissibleExponent F w12 w23 w31 τ) (i : Fin 3) : loads w12 w23 w31 i ≤ τ := by + apply le_of_dyadic_log_bound + intro ε hε + obtain ⟨C, hC, hbound⟩ := hτ.rank_growth ε hε + refine ⟨C, hC, fun k => ?_⟩ + have hdim (w : ℝ) := wireDimension_pos (N := 2 ^ k) (by positivity) w + apply (dyadic_load_le k _ _ _ i).trans + apply (matrix_load_le_log_tensorRank F (hdim w12) (hdim w23) (hdim w31) i).trans + exact Real.logb_le_logb_of_le (by norm_num) + (by exact_mod_cast matrixTensor_rank_pos F (hdim w12) (hdim w23) (hdim w31)) + (hbound _ (Nat.one_le_pow _ _ (by decide))) + +theorem load_le_formalOmega (F : Type*) [Field F] {w12 w23 w31 : ℝ} + (h12 : 0 ≤ w12) (h23 : 0 ≤ w23) (h31 : 0 ≤ w31) (i : Fin 3) : + loads w12 w23 w31 i ≤ formalOmega F w12 w23 w31 := + (formalOmega_admissible F h12 h23 h31).load_le i + +@[simp] theorem unit_weight_loads : loads 1 1 1 = fun _ => 2 := by + funext i + fin_cases i <;> norm_num [loads] + +private theorem loads_nonnegative {u v w : ℝ} (hu : 0 ≤ u) (hv : 0 ≤ v) (hw : 0 ≤ w) : + ∀ i, 0 ≤ loads u v w i := by + intro i + fin_cases i <;> dsimp [loads] <;> positivity + +section RankBound + +variable {F : Type*} [Field F] +variable (hfinite : ∀ (x y z : ℕ), 0 < x → 0 < y → 0 < z → + RadicalTest (loads (Real.logb 2 x) (Real.logb 2 y) (Real.logb 2 z)) + (Real.logb 2 (tensorRank (matrixTensor F x y z)))) + +include hfinite + +private theorem heightTest_of_matrix_rank_growth {w12 w23 w31 τ : ℝ} + (hgrowth : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ N : ℕ, 1 ≤ N → + (tensorRank (matrixTensor F (wireDimension N w12) (wireDimension N w23) + (wireDimension N w31)) : ℝ) ≤ C * (N : ℝ) ^ (τ + ε)) : + HeightTest (loads w12 w23 w31) τ := by + apply heightTest_of_polynomial_bound + intro ε hε + obtain ⟨C, hC, hc⟩ := hgrowth ε hε + refine ⟨C, hC, ?_⟩ + intro N hN + have hdim (w : ℝ) := wireDimension_pos (N := N) (by omega) w + have hlog (w : ℝ) : 0 ≤ Real.logb 2 (wireDimension N w) := + Real.logb_nonneg (by norm_num) (by exact_mod_cast hdim w) + have htest := (hfinite _ _ _ (hdim w12) (hdim w23) (hdim w31)).heightTest + (loads_nonnegative (hlog _) (hlog _) (hlog _)) + apply htest.mono + exact Real.logb_le_logb_of_le (by norm_num) + (by exact_mod_cast matrixTensor_rank_pos F (hdim w12) (hdim w23) (hdim w31)) (hc N hN) + +/-- Take the infimum over all polynomial growth bounds supplied by a circuit model. +The rank may be measured over a common extension of its field of constants. -/ +theorem radicalTest_sInf_of_matrix_rank_growth {w12 w23 w31 : ℝ} + (h12 : 0 ≤ w12) (h23 : 0 ≤ w23) (h31 : 0 ≤ w31) {S : Set ℝ} (hS : S.Nonempty) + (hgrowth : ∀ τ ∈ S, ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ N : ℕ, 1 ≤ N → + (tensorRank (matrixTensor F (wireDimension N w12) (wireDimension N w23) + (wireDimension N w31)) : ℝ) ≤ C * (N : ℝ) ^ (τ + ε)) : + RadicalTest (loads w12 w23 w31) (sInf S) := + (heightTest_sInf hS fun τ hτ => heightTest_of_matrix_rank_growth hfinite (hgrowth τ + hτ)).radicalTest + (loads_nonnegative h12 h23 h31) + +/-- The finite ordinary-rank inequality gives the rectangular arithmetic exponent inequality. -/ +theorem formalOmega_radicalTest_of_rank_bound {w12 w23 w31 : ℝ} + (h12 : 0 ≤ w12) (h23 : 0 ≤ w23) (h31 : 0 ≤ w31) : + RadicalTest (loads w12 w23 w31) (formalOmega F w12 w23 w31) := by + apply radicalTest_sInf_of_matrix_rank_growth hfinite h12 h23 h31 + (S := {τ | FormalAdmissibleExponent F w12 w23 w31 τ}) ⟨_, + formalAdmissibleExponent_naive F h12 h23 h31⟩ + exact fun _ hτ => hτ.rank_growth + +/-- The square exponent consequence of the finite ordinary-rank inequality. -/ +theorem formalOmega_square_lower_bound_of_rank_bound : + 3 / Real.sqrt 2 ≤ formalOmega F 1 1 1 := by + apply square_lower_bound + simpa only [unit_weight_loads] using formalOmega_radicalTest_of_rank_bound hfinite + (show (0 : ℝ) ≤ 1 by norm_num) (show (0 : ℝ) ≤ 1 by norm_num) (show (0 : ℝ) ≤ 1 by norm_num) + +end RankBound +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Asymptotic.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Asymptotic.lean new file mode 100644 index 0000000000..9743fdde0b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Asymptotic.lean @@ -0,0 +1,94 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Rank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Scaling + +/-! # From finite height bounds to arithmetic exponents + +Evaluate the finite bound at base sizes `2 ^ k`. Rounding each dimension +up only increases its logarithmic load. The logarithm of a constant in +a polynomial cost bound contributes a fixed additive term, which disappears +when the inequality holds at every dyadic scale. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open scoped BigOperators + +noncomputable section + +/-- Logarithmic site loads at the three rounded wire dimensions of base size `N`. -/ +def scaledLoads (N : ℕ) (w12 w23 w31 : ℝ) : Fin 3 → ℝ := + loads (Real.logb 2 (wireDimension N w12)) (Real.logb 2 (wireDimension N w23)) + (Real.logb 2 (wireDimension N w31)) + +/-- The dyadic loads dominate the real weights multiplied by the scale exponent. -/ +theorem dyadic_load_le (k : ℕ) (w12 w23 w31 : ℝ) (i : Fin 3) : + (k : ℝ) * loads w12 w23 w31 i ≤ scaledLoads (2 ^ k) w12 w23 w31 i := by + fin_cases i <;> dsimp [scaledLoads, loads] <;> rw [mul_add] <;> + exact add_le_add (dyadic_wireDimension_log_ge _ _) (dyadic_wireDimension_log_ge _ _) + +/-- A uniform polynomial bound at dyadic scales forces the growth exponent +to dominate the slope, independently of the multiplicative constant. -/ +theorem le_of_dyadic_log_bound {u τ : ℝ} + (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ k : ℕ, + (k : ℝ) * u ≤ Real.logb 2 (C * ((2 ^ k : ℕ) : ℝ) ^ (τ + ε))) : u ≤ τ := by + apply le_of_forall_pos_le_add + intro ε hε + obtain ⟨C, hC, hk⟩ := h ε hε + by_contra! hlt + obtain ⟨k, hlarge⟩ := exists_lt_nsmul (sub_pos.mpr hlt) (Real.logb 2 C) + rw [nsmul_eq_mul] at hlarge + have hbound := hk k + rw [Nat.cast_pow, Nat.cast_ofNat, Real.logb_mul hC.ne' (by positivity), + Real.logb_rpow_eq_mul_logb_of_pos (by positivity), Real.logb_pow, + Real.logb_self_eq_one (by norm_num), mul_one] at hbound + nlinarith only [hlarge, hbound] + +/-- A polynomial upper bound on the finite height-test parameter implies +the corresponding test on exponent loads, with all positive slack removed. -/ +theorem heightTest_of_polynomial_bound {w12 w23 w31 τ : ℝ} + (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ N : ℕ, 1 ≤ N → + HeightTest (scaledLoads N w12 w23 w31) (Real.logb 2 (C * (N : ℝ) ^ (τ + ε)))) : + HeightTest (loads w12 w23 w31) τ := by + intro a ha + let M := ∑ i, a i * loads w12 w23 w31 i + let D := ∑ i, Real.sqrt (1 + a i ^ 2) - 1 + have hD : 0 < D := heightDenom_pos a + change M ≤ τ * D + apply (div_le_iff₀ hD).mp + apply le_of_dyadic_log_bound + intro ε hε + obtain ⟨C, hC, hN⟩ := h ε hε + refine ⟨C, hC, fun k => ?_⟩ + rw [← mul_div_assoc, div_le_iff₀ hD] + have hstep : (k : ℝ) * M ≤ ∑ i, a i * scaledLoads (2 ^ k) w12 w23 w31 i := by + dsimp only [M] + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro i _ + rw [mul_left_comm] + exact mul_le_mul_of_nonneg_left (dyadic_load_le k _ _ _ i) (ha i).le + exact hstep.trans (hN (2 ^ k) (Nat.one_le_pow _ _ (by decide)) a ha) + +/-- Height tests pass to the infimum of any nonempty set of admissible exponents. -/ +theorem heightTest_sInf {m : Fin 3 → ℝ} {S : Set ℝ} (hS : S.Nonempty) + (h : ∀ τ ∈ S, HeightTest m τ) : HeightTest m (sInf S) := by + intro a ha + have hD := heightDenom_pos a + apply (div_le_iff₀ hD).mp + exact le_csInf hS fun τ hτ => (div_le_iff₀ hD).mpr (h τ hτ a ha) + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Circuit.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Circuit.lean new file mode 100644 index 0000000000..2f1171d5d8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Circuit.lean @@ -0,0 +1,174 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalCircuit +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Tensor +public import Mathlib.Algebra.MvPolynomial.PDeriv + +/-! # From formal scalar circuits to tensor rank + +At a product gate only two new products of linear forms enter the bidegree +`(1,1)` component. We maintain one shared list of these products across *all* +registers, so fan-out and multiple matrix entries incur no additional cost. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Arithmetic Foundation MvPolynomial +open scoped BigOperators +noncomputable section + +variable {F A B I R : Type*} [CommRing F] + +/-- Number of scalar multiplication gates. Register loads, additions and +subtractions contribute zero. -/ +def multiplicationCount : {r : ℕ} → Program F I r → ℕ + | _, .nil => 0 + | _, .step p (.mul _ _) => multiplicationCount p + 1 + | _, .step p _ => multiplicationCount p + +omit [CommRing F] in +theorem multiplicationCount_le_cost {r : ℕ} (p : Program F I r) : + multiplicationCount p ≤ p.cost := by + induction p with + | nil => rfl + | step p g ih => cases g <;> simp [multiplicationCount, Gate.cost] <;> omega + +/-- Formal polynomials over the disjoint sets of left and right input variables. -/ +abbrev InputPoly (F A B : Type*) [CommRing F] := MvPolynomial (A ⊕ B) F + +/-- The coefficient of the squarefree monomial indexed by a left and a right input. -/ +def mixedPart (p : InputPoly F A B) (x : A) (y : B) : F := + constantCoeff (pderiv (Sum.inr y) (pderiv (Sum.inl x) p)) + +private def leftPart (p : InputPoly F A B) (x : A) : F := + constantCoeff (pderiv (Sum.inl x) p) + +private def rightPart (p : InputPoly F A B) (y : B) : F := + constantCoeff (pderiv (Sum.inr y) p) + +private theorem mixedPart_mul (p q : InputPoly F A B) (x : A) (y : B) : + mixedPart (p * q) x y = + constantCoeff q * mixedPart p x y + constantCoeff p * mixedPart q x y + + leftPart p x * rightPart q y + leftPart q x * rightPart p y := by + simp only [mixedPart, leftPart, rightPart, pderiv_mul, map_add, map_mul] + ring + +theorem mixedPart_X (s : A ⊕ B) (x : A) (y : B) : + mixedPart (X s : InputPoly F A B) x y = 0 := by + classical + by_cases h : s = Sum.inl x + · subst s + simp [mixedPart] + · unfold mixedPart + rw [pderiv_X_of_ne h, map_zero, map_zero] + +/-- A common collection of products can be linearly recombined to give this register. -/ +private def InProductSpan {r : ℕ} (a : Fin r → A → F) (b : Fin r → B → F) + (p : InputPoly F A B) : Prop := + ∃ c : Fin r → F, ∀ x y, mixedPart p x y = ∑ t, a t x * b t y * c t + +private theorem inProductSpan_add {r : ℕ} {a : Fin r → A → F} {b : Fin r → B → F} + {p q : InputPoly F A B} (hp : InProductSpan a b p) (hq : InProductSpan a b q) : + InProductSpan a b (p + q) := by + obtain ⟨c, hc⟩ := hp + obtain ⟨d, hd⟩ := hq + refine ⟨c + d, fun x y => ?_⟩ + simp only [Pi.add_apply, mul_add, Finset.sum_add_distrib, ← hc, ← hd, mixedPart, map_add] + +private theorem inProductSpan_sub {r : ℕ} {a : Fin r → A → F} {b : Fin r → B → F} + {p q : InputPoly F A B} (hp : InProductSpan a b p) (hq : InProductSpan a b q) : + InProductSpan a b (p - q) := by + obtain ⟨c, hc⟩ := hp + obtain ⟨d, hd⟩ := hq + refine ⟨c - d, fun x y => ?_⟩ + simp only [Pi.sub_apply, mul_sub, Finset.sum_sub_distrib, ← hc, ← hd, mixedPart, map_sub] + +private theorem inProductSpan_insert {r : ℕ} {a : Fin r → A → F} {b : Fin r → B → F} + {p : InputPoly F A B} (hp : InProductSpan a b p) (u : A → F) (v : B → F) : + InProductSpan (Fin.cons u a) (Fin.cons v b) p := by + obtain ⟨c, hc⟩ := hp + refine ⟨Fin.cons 0 c, fun x y => ?_⟩ + simp [Fin.sum_univ_succ, hc] + +private theorem inProductSpan_mul {r : ℕ} {a : Fin r → A → F} {b : Fin r → B → F} + {p q : InputPoly F A B} (hp : InProductSpan a b p) (hq : InProductSpan a b q) : + InProductSpan (Fin.cons (leftPart p) (Fin.cons (leftPart q) a)) + (Fin.cons (rightPart q) (Fin.cons (rightPart p) b)) (p * q) := by + obtain ⟨c, hc⟩ := hp + obtain ⟨d, hd⟩ := hq + refine ⟨Fin.cons 1 (Fin.cons 1 (fun t => constantCoeff q * c t + constantCoeff p * d t)), + fun x y => ?_⟩ + simp only [Fin.sum_univ_succ, Fin.cons_zero, Fin.cons_succ, mul_one, mixedPart_mul, + hc, hd, Finset.mul_sum, mul_add, Finset.sum_add_distrib] + ring_nf + +private theorem registerProducts {r : ℕ} (p : Program F (A ⊕ B) r) : + ∃ (a : Fin (2 * multiplicationCount p) → A → F) (b : Fin (2 * multiplicationCount p) → B → F), + ∀ i, InProductSpan a b (registerPolynomial p i) := by + induction p with + | nil => exact ⟨Fin.elim0, Fin.elim0, fun i => i.elim0⟩ + | step p g ih => + obtain ⟨a, b, hab⟩ := ih + cases g with + | literal z => + refine ⟨a, b, Fin.cases ?_ hab⟩ + refine ⟨0, fun x y => ?_⟩ + simp [gatePolynomial, mixedPart] + | input s => + refine ⟨a, b, Fin.cases ?_ hab⟩ + refine ⟨0, fun x y => ?_⟩ + simp [gatePolynomial, mixedPart_X] + | add i j => exact ⟨a, b, Fin.cases (inProductSpan_add (hab i) (hab j)) hab⟩ + | sub i j => exact ⟨a, b, Fin.cases (inProductSpan_sub (hab i) (hab j)) hab⟩ + | mul i j => + simp only [multiplicationCount] + refine ⟨_, _, Fin.cases (inProductSpan_mul (hab i) (hab j)) (fun k => ?_)⟩ + exact inProductSpan_insert (inProductSpan_insert (hab k) _ _) _ _ + +private theorem matrixEntry_mixedPart {a b c : ℕ} (i : Fin a) (k : Fin c) + (x : Fin a × Fin b) (y : Fin b × Fin c) : + mixedPart (∑ j : Fin b, X (Sum.inl (i, j)) * X (Sum.inr (j, k)) : + InputPoly F (Fin a × Fin b) (Fin b × Fin c)) x y = + matrixTensor F b c a x y (k, i) := by + classical + rcases x with ⟨u, v⟩ + rcases y with ⟨w, z⟩ + simp [mixedPart, map_sum, pderiv_X, Pi.single_apply, apply_ite, + Tensor.matrixCoefficients, Prod.ext_iff, ite_and, eq_comm] + split_ifs <;> simp_all + +/-- A formal division-free rectangular matrix multiplication circuit with `s` +products gives an exact rank decomposition with at most `2s` simple tensors. -/ +theorem matrixTensor_rank_le_twice_multiplicationCount {a b c : ℕ} {P : MatrixAlgorithm F a b c} + (h : FormalCorrect P) : tensorRank (matrixTensor F b c a) ≤ 2 * multiplicationCount P.program + := by + classical + obtain ⟨u, v, huv⟩ := registerProducts P.program + choose w hw using huv + apply tensorRank_le_of_rankAtMost + refine ⟨u, v, fun t z => w (P.output z.2 z.1) t, ?_⟩ + funext x y z + rw [← matrixEntry_mixedPart, ← h z.2 z.1] + exact hw _ _ _ + +/-- The total number of operations also bounds the rank, with the same factor two. -/ +theorem matrixTensor_rank_le_twice_cost {a b c : ℕ} {P : MatrixAlgorithm F a b c} + (h : FormalCorrect P) : tensorRank (matrixTensor F b c a) ≤ 2 * P.cost := + (matrixTensor_rank_le_twice_multiplicationCount h).trans + (Nat.mul_le_mul_left 2 (multiplicationCount_le_cost _)) + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/DualExponent.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/DualExponent.lean new file mode 100644 index 0000000000..05774dd016 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/DualExponent.lean @@ -0,0 +1,49 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.ArithmeticExponent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Elongated + +/-! # The dual exponent of formal arithmetic matrix multiplication -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +/-- The supremum of `t ∈ [0, 1]` such that the formal arithmetic exponent of +the rectangular weights `(1,1,t)` is two. -/ +noncomputable def formalAlpha (F : Type*) [Field F] : ℝ := dualExponent (formalOmega F 1 1) + +theorem formalOmega_one_one_zero (F : Type*) [Field F] : formalOmega F 1 1 0 = 2 := by + let S := {τ : ℝ | FormalAdmissibleExponent F 1 1 0 τ} + have h0 : (0 : ℝ) ≤ 0 := le_rfl + have h1 : (0 : ℝ) ≤ 1 := zero_le_one + have hmem := formalAdmissibleExponent_naive F h1 h1 h0 + norm_num at hmem + have hbound : ∀ τ ∈ S, (2 : ℝ) ≤ τ := by + intro τ hτ + have h := FormalAdmissibleExponent.load_le (F := F) (w12 := 1) (w23 := 1) (w31 := 0) hτ 1 + norm_num [loads] at h + exact h + exact le_antisymm (csInf_le (s := S) ⟨2, hbound⟩ hmem) (le_csInf ⟨2, hmem⟩ hbound) + +/-- The exponent-two rectangular weights contain zero. An upper bound for +each admissible weight therefore bounds their supremum. -/ +theorem formalAlpha_le {F : Type*} [Field F] {b : ℝ} + (h : ∀ t ∈ Set.Icc (0 : ℝ) 1, formalOmega F 1 1 t = 2 → t ≤ b) : + formalAlpha F ≤ b := by + apply csSup_le (s := {t : ℝ | t ∈ Set.Icc 0 1 ∧ formalOmega F 1 1 t = 2}) + ⟨0, ⟨le_rfl, zero_le_one⟩, formalOmega_one_one_zero F⟩ + rintro t ⟨ht, hω⟩ + exact h t ht hω + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Elongated.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Elongated.lean new file mode 100644 index 0000000000..515c26a86a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Elongated.lean @@ -0,0 +1,169 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Rank + +/-! The exact threshold of the radical test for weights `(1,1,t)`. -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +noncomputable section + +section + +private theorem elongated_test_iff (t L : ℝ) : + RadicalTest (loads 1 1 t) L ↔ + 2 ≤ L ∧ 1 + t ≤ L ∧ L ≤ Real.sqrt (L ^ 2 - 2 ^ 2) + + 2 * Real.sqrt (L ^ 2 - (1 + t) ^ 2) := by + norm_num [RadicalTest, loads, Fin.forall_fin_succ, Fin.sum_univ_succ, add_comm t 1] + constructor + · rintro ⟨⟨hs, h₂, _⟩, h⟩ + exact ⟨h₂, hs, by linarith⟩ + · rintro ⟨h₂, hs, h⟩ + exact ⟨⟨hs, h₂, hs⟩, by linarith⟩ + +/-- The radical test at exponent two cuts off at exactly `√3 - 1`. -/ +theorem radicalTest_loads_two_iff {t : ℝ} (ht : 0 ≤ t) : + RadicalTest (loads 1 1 t) 2 ↔ t ≤ Real.sqrt 3 - 1 := by + rw [elongated_test_iff] + have hs := Real.sq_sqrt (by norm_num : 0 ≤ (3 : ℝ)) + have hsNonneg := Real.sqrt_nonneg 3 + norm_num + constructor + · rintro ⟨hle, h⟩ + have hrad := Real.sq_sqrt (show 0 ≤ 4 - (1 + t) ^ 2 by nlinarith) + nlinarith [Real.sqrt_nonneg (4 - (1 + t) ^ 2)] + · intro h + have hslt : Real.sqrt 3 ≤ 2 := by nlinarith + have hsq : (1 + t) ^ 2 ≤ 3 := by + nlinarith [sq_le_sq' (show -Real.sqrt 3 ≤ 1 + t by linarith) + (show 1 + t ≤ Real.sqrt 3 by linarith)] + have hrad := Real.sq_sqrt (show 0 ≤ 4 - (1 + t) ^ 2 by linarith) + exact ⟨by linarith, by nlinarith [Real.sqrt_nonneg (4 - (1 + t) ^ 2)]⟩ + +private theorem normalized_summand_strict {m L K : ℝ} + (hm : 0 < m) (hmL : m ≤ L) (hLK : L < K) : + Real.sqrt (L ^ 2 - m ^ 2) / L < Real.sqrt (K ^ 2 - m ^ 2) / K := by + have hL := hm.trans_le hmL + have hK := hL.trans hLK + have normalize (x : ℝ) (hx : 0 < x) : + Real.sqrt (x ^ 2 - m ^ 2) / x = Real.sqrt (1 - (m / x) ^ 2) := by + rw [show 1 - (m / x) ^ 2 = (x ^ 2 - m ^ 2) / x ^ 2 by field_simp] + rw [Real.sqrt_div' _ (sq_nonneg _), Real.sqrt_sq hx.le] + rw [normalize L hL, normalize K hK] + have hratio : m / K < m / L := div_lt_div_of_pos_left hm hL hLK + have hmax : m / L ≤ 1 := (div_le_one hL).2 hmL + have hnonneg : 0 ≤ m / K := by positivity + apply Real.sqrt_lt_sqrt + · nlinarith [sq_le_sq' (show -(1 : ℝ) ≤ m / L by linarith) hmax] + · nlinarith [sq_lt_sq' (show -(m / L) < m / K by linarith) hratio] + +/-- At and above `√3 - 1`, the closed-form expression in (6.2) is the least +real number admitted by the radical test. -/ +theorem isLeast_radicalTest_elongated {t : ℝ} (ht : Real.sqrt 3 - 1 ≤ t) : + IsLeast {L : ℝ | RadicalTest (loads 1 1 t) L} + (t * (t + 2) / Real.sqrt (t ^ 2 + 2 * t - 1)) := by + let s := 1 + t + let u := Real.sqrt (s ^ 2 - 2) + have hsq3 := Real.sq_sqrt (by norm_num : 0 ≤ (3 : ℝ)) + have hroot : 0 ≤ Real.sqrt 3 := Real.sqrt_nonneg 3 + have hs : Real.sqrt 3 ≤ s := by dsimp [s]; linarith + have hs₀ : 0 < s := (Real.sqrt_pos.2 (by norm_num : 0 < (3 : ℝ))).trans_le hs + have hs3 : 3 ≤ s ^ 2 := by nlinarith [sq_le_sq' (show -s ≤ Real.sqrt 3 by linarith) hs] + have hu₂ : u ^ 2 = s ^ 2 - 2 := Real.sq_sqrt (by linarith) + have hu : 1 ≤ u := by + nlinarith only [hu₂, hs3, show 0 ≤ u from Real.sqrt_nonneg _] + have hu₀ : 0 < u := by linarith + have huv : u * u⁻¹ = 1 := mul_inv_cancel₀ hu₀.ne' + have hv₀ : 0 < u⁻¹ := inv_pos.mpr hu₀ + have hv : u⁻¹ ≤ u := by nlinarith [mul_nonneg (sub_nonneg.mpr hu) hv₀.le] + let K := u + u⁻¹ + have hformula : t * (t + 2) / Real.sqrt (t ^ 2 + 2 * t - 1) = K := by + rw [show t ^ 2 + 2 * t - 1 = s ^ 2 - 2 by dsimp [s]; ring] + change t * (t + 2) / u = u + u⁻¹ + apply (div_eq_iff hu₀.ne').mpr + dsimp [s] at hu₂ + nlinarith only [hu₂, huv] + rw [hformula] + have hK₀ : 0 < K := add_pos hu₀ hv₀ + have hK₂ : K ^ 2 - 2 ^ 2 = (u - u⁻¹) ^ 2 := by dsimp [K]; nlinarith only [huv] + have hKs : K ^ 2 - s ^ 2 = (u⁻¹) ^ 2 := by dsimp [K]; nlinarith only [hu₂, huv] + have hKtwo : 2 ≤ K := le_of_sq_le_sq (by linarith only [hK₂, sq_nonneg (u - u⁻¹)]) hK₀.le + have hsK : s ≤ K := le_of_sq_le_sq (by linarith only [hKs, sq_nonneg (u⁻¹)]) hK₀.le + have h₁ : Real.sqrt (K ^ 2 - 2 ^ 2) = u - u⁻¹ := by + rw [hK₂, Real.sqrt_sq (sub_nonneg.mpr hv)] + have h₂ : Real.sqrt (K ^ 2 - s ^ 2) = u⁻¹ := by + rw [hKs, Real.sqrt_sq hv₀.le] + have heq : K = Real.sqrt (K ^ 2 - 2 ^ 2) + 2 * Real.sqrt (K ^ 2 - s ^ 2) := by + rw [h₁, h₂] + dsimp [K] + ring + constructor + · exact (elongated_test_iff ..).2 ⟨hKtwo, hsK, heq.le⟩ + · intro L hL + obtain ⟨hLtwo, hsL, hsum⟩ := (elongated_test_iff ..).1 hL + change L ≤ Real.sqrt (L ^ 2 - 2 ^ 2) + 2 * Real.sqrt (L ^ 2 - s ^ 2) at hsum + by_contra! hLK + have hL₀ : 0 < L := by linarith + have hl := (le_div_iff₀ hL₀).2 (show 1 * L ≤ _ by simpa using hsum) + have hk := (div_eq_iff hK₀.ne').2 (show _ = 1 * K by simpa using heq.symm) + rw [add_div, mul_div_assoc] at hl hk + linarith [normalized_summand_strict (by norm_num : (0 : ℝ) < 2) hLtwo hLK, + normalized_summand_strict hs₀ hsL hLK] + +/-- The complete solution of the radical inequality at elongated weights. -/ +theorem radicalTest_elongated_iff {t L : ℝ} (ht : 0 ≤ t) : + RadicalTest (loads 1 1 t) L ↔ + (if t ≤ Real.sqrt 3 - 1 then 2 else t * (t + 2) / Real.sqrt (t ^ 2 + 2 * t - 1)) ≤ L := by + have hm : ∀ i, 0 ≤ loads 1 1 t i := by + intro i + fin_cases i <;> simp [loads] <;> linarith + split_ifs with hc + · exact ⟨fun h => ((elongated_test_iff ..).1 h).1, + fun h => ((radicalTest_loads_two_iff ht).2 hc).mono hm h⟩ + · have hmin := isLeast_radicalTest_elongated (le_of_lt (lt_of_not_ge hc)) + exact ⟨fun h => hmin.2 h, fun h => hmin.1.mono hm h⟩ + +/-- With an aspect at least one, the threshold strictly exceeds the largest flattening. -/ +theorem flattening_lt_elongated_threshold {t : ℝ} (ht : 1 ≤ t) : + 1 + t < t * (t + 2) / Real.sqrt (t ^ 2 + 2 * t - 1) := by + have harg : 0 < t ^ 2 + 2 * t - 1 := by nlinarith [sq_nonneg t] + apply (lt_div_iff₀ (Real.sqrt_pos.2 harg)).2 + have hs := Real.sq_sqrt harg.le + have hsq : ((1 + t) * Real.sqrt (t ^ 2 + 2 * t - 1)) ^ 2 < (t * (t + 2)) ^ 2 := by + rw [mul_pow, hs] + ring_nf + linarith + nlinarith [mul_nonneg (show 0 ≤ t by linarith) (show 0 ≤ t + 2 by linarith), + mul_nonneg (show 0 ≤ 1 + t by linarith) (Real.sqrt_nonneg (t ^ 2 + 2 * t - 1))] + +/-- The dual exponent attached to the arithmetic exponent at weights `(1,1,t)`. -/ +def dualExponent (ω : ℝ → ℝ) : ℝ := + sSup {t : ℝ | t ∈ Set.Icc 0 1 ∧ ω t = 2} + +/-- The rectangular radical test implies the upper bound for the dual exponent. -/ +theorem dualExponent_le_of_radicalTest {ω : ℝ → ℝ} + (h : ∀ t ∈ Set.Icc (0 : ℝ) 1, RadicalTest (loads 1 1 t) (ω t)) : + dualExponent ω ≤ Real.sqrt 3 - 1 := by + unfold dualExponent + rcases Set.eq_empty_or_nonempty {t : ℝ | t ∈ Set.Icc 0 1 ∧ ω t = 2} with hEmpty | hNonempty + · rw [hEmpty, Real.sSup_empty] + nlinarith [Real.sq_sqrt (by norm_num : 0 ≤ (3 : ℝ)), Real.sqrt_nonneg 3] + · apply csSup_le hNonempty + rintro t ⟨ht, hω⟩ + exact (radicalTest_loads_two_iff ht.1).1 (hω ▸ h t ht) + +end + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/ExactExponent.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/ExactExponent.lean new file mode 100644 index 0000000000..9e0b03a4ea --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/ExactExponent.lean @@ -0,0 +1,80 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.RingFormula +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.DualExponent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.RectangularCircuitModel +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.SquareRankModel + +/-! +# Exact matrix multiplication exponents + +The square, dual, and rectangular exponents are computed over every field. +The circuit model uses division-free programs and tests correctness by polynomial identity. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +/-- The square matrix multiplication exponent over every field. -/ +theorem square_exponent (F : Type*) [Field F] : formalOmega F 1 1 1 = (9 : ℝ) / 4 := + (formalOmega_square_eq_omega F).trans (MatrixExponent.omega_eq F) + +/-- The dual matrix multiplication exponent over every field. -/ +theorem dual_exponent (F : Type*) [Field F] : formalAlpha F = (1 : ℝ) / 2 := by + obtain ⟨hs, hr⟩ := MatrixExponent.omega_eq_and_rigidity F + calc + formalAlpha F = MatrixExponent.Rectangle.dual F 1 1 := by + unfold formalAlpha dualExponent MatrixExponent.Rectangle.dual + congr 1 + ext t + simp only [Set.mem_ofPred_eq, min_self, one_add_one_eq_two] + apply and_congr_right + intro ht + rw [formalOmega_eq_integral, MatrixExponent.Integral.agreement F ht.1 zero_le_one zero_le_one, + MatrixExponent.Rectangle.cycle F ht.1 zero_le_one zero_le_one] + _ = (1 : ℝ) / 2 := MatrixExponent.Rectangle.dual_square hr hs + +private theorem benchmark_sorted (a b c : ℝ) : + MatrixExponent.Rectangle.U c b a = + let x := max a (max b c) + let z := min a (min b c) + let y := a + b + c - x - z + x + y + (max ((x + y) * z - x * y) 0) ^ 2 / (4 * x * y * z) := by + let x := max a (max b c) + let z := min a (min b c) + let y := a + b + c - x - z + change MatrixExponent.Rectangle.U c b a = MatrixExponent.Rectangle.benchmark x y z + have sorted (u v w : ℝ) (hw : w = z) + (huv : (u = x ∧ v = y) ∨ (u = y ∧ v = x)) : + MatrixExponent.Rectangle.benchmark u v w = MatrixExponent.Rectangle.benchmark x y z := by + rcases huv with ⟨hu, hv⟩ | ⟨hu, hv⟩ <;> rw [hu, hv, hw] + simp only [MatrixExponent.Rectangle.benchmark, add_comm y x, mul_comm y x, + show 4 * y * x = 4 * x * y by ring] + unfold MatrixExponent.Rectangle.U + split_ifs <;> apply sorted <;> dsimp only [x, y, z] <;> grind + +/-- The exact rectangular exponent with the nonnegative parts of the weights sorted +in descending order. On coordinate planes the correction term is zero. -/ +theorem rectangular_exponent (F : Type*) [Field F] (a b c : ℝ) : + formalOmega F a b c = + let A := max a 0 + let B := max b 0 + let C := max c 0 + let x := max A (max B C) + let z := min A (min B C) + let y := A + B + C - x - z + x + y + (max ((x + y) * z - x * y) 0) ^ 2 / (4 * x * y * z) := by + rw [formalOmega_max_zero F a b c, formalOmega_eq_integral, + MatrixExponent.Integral.exponent_eq F (le_max_right ..) (le_max_right ..) (le_max_right ..)] + exact benchmark_sorted _ _ _ + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FiniteExtensionRank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FiniteExtensionRank.lean new file mode 100644 index 0000000000..b37da36406 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FiniteExtensionRank.lean @@ -0,0 +1,116 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.RankLimit +public import Mathlib.LinearAlgebra.Dimension.Finite +public import Mathlib.Analysis.SpecialFunctions.Pow.Continuity +public import Mathlib.LinearAlgebra.FiniteDimensional.Defs + +/-! # Tensor rank under finite scalar extension + +Expand two sites of a decomposition in a fixed basis of the extension. +A linear retraction of the field inclusion contracts the third site. +The dimension cost is constant across tensor powers. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +noncomputable section + +open MatrixMultiplication.Foundation Filter +open scoped Topology + +section + +variable {F K X Y Z : Type*} [Field F] [Field K] [Algebra F K] + +/-- Kronecker powers commute with entrywise scalar extension. -/ +theorem power_scalarExtension (T : Tensor F X Y Z) (n : ℕ) : + Tensor.power (fun x y z => algebraMap F K (T x y z)) n = + fun x y z => algebraMap F K (Tensor.power T n x y z) := by + funext x y z + simp [Tensor.power] + +/-- A finite extension of degree `d` saves at most a factor of `d²` in tensor rank. -/ +theorem rankAtMost_of_finiteExtension [FiniteDimensional F K] {T : Tensor F X Y Z} + {r : ℕ} (h : Tensor.RankAtMost (fun x y z => algebraMap F K (T x y z)) r) : + Tensor.RankAtMost T (r * (Module.finrank F K) ^ 2) := by + classical + let d := Module.finrank F K + let b := Module.finBasis F K + obtain ⟨P, hP⟩ := (Algebra.linearMap F K).exists_leftInverse_of_injective + (LinearMap.ker_eq_bot.mpr (FaithfulSMul.algebraMap_injective F K)) + obtain ⟨A, B, C, hABC⟩ := h + let a (j : Fin r × Fin d × Fin d) (x : X) := b.repr (A j.1 x) j.2.1 + let a' (j : Fin r × Fin d × Fin d) (y : Y) := b.repr (B j.1 y) j.2.2 + let c (j : Fin r × Fin d × Fin d) (z : Z) := P (b j.2.1 * b j.2.2 * C j.1 z) + have hterm (i : Fin r) (x : X) (y : Y) (z : Z) : + P (Tensor.rankOne (A i) (B i) (C i) x y z) = + ∑ j : Fin d, ∑ k : Fin d, Tensor.rankOne (a (i,j,k)) (a' (i,j,k)) (c (i,j,k)) x y z := by + unfold Tensor.rankOne + conv_lhs => rw [← b.sum_repr (A i x), ← b.sum_repr (B i y)] + simp only [Finset.sum_mul, Finset.mul_sum, map_sum, a, a', c, + smul_mul_assoc, mul_smul_comm, map_smul, smul_eq_mul, mul_assoc] + rw [Finset.sum_comm] + simp only [mul_left_comm] + rfl + have heq : T = fun x y z => ∑ j, Tensor.rankOne (a j) (a' j) (c j) x y z := by + funext x y z + have he := LinearMap.congr_fun hP (T x y z) + change P (algebraMap F K (T x y z)) = T x y z at he + rw [← he, congrFun (congrFun (congrFun hABC x) y) z, map_sum] + simp only [Fintype.sum_prod_type, hterm] + rw [heq] + simpa only [Fintype.card_prod, Fintype.card_fin, sq, d] using + Tensor.rankAtMost_sum_rankOne a a' c + +variable [Finite X] [Finite Y] + +/-- A constant factor in a tensor-power rank bound disappears under roots. -/ +theorem asymptoticRank_le_of_power_bound (T : Tensor F X Y Z) {C r : ℕ} + (hC : 0 < C) (h : ∀ n : ℕ, tensorRank (Tensor.power T n) ≤ C * r ^ n) : + asymptoticRank T ≤ r := by + have hc : Tendsto (fun n : ℕ => (C : ℝ) ^ ((n : ℝ)⁻¹)) atTop (𝓝 1) := by + have hcont := Real.continuousAt_const_rpow (a := (C : ℝ)) (b := 0) (by positivity) + simpa only [Real.rpow_zero, Function.comp_def] using + hcont.tendsto.comp (tendsto_inv_atTop_zero.comp tendsto_natCast_atTop_atTop) + have hlim := hc.mul_const (r : ℝ) + rw [one_mul] at hlim + apply le_of_tendsto_of_tendsto (tendsto_tensorRank_power_root T) hlim + filter_upwards [eventually_ne_atTop (0 : ℕ)] with n hn + calc + (tensorRank (Tensor.power T n) : ℝ) ^ ((n : ℝ)⁻¹) ≤ + ((C : ℝ) * (r : ℝ) ^ n) ^ ((n : ℝ)⁻¹) := + Real.rpow_le_rpow (by positivity) (by exact_mod_cast h n) (by positivity) + _ = (C : ℝ) ^ ((n : ℝ)⁻¹) * r := by + rw [Real.mul_rpow (by positivity) (by positivity), + Real.pow_rpow_inv_natCast (by positivity) hn] + +/-- Any exact decomposition over a finite extension bounds the asymptotic rank +over the original field. -/ +theorem asymptoticRank_le_of_finiteExtension [FiniteDimensional F K] {T : Tensor F X Y Z} + {r : ℕ} (h : Tensor.RankAtMost (fun x y z => algebraMap F K (T x y z)) r) : + asymptoticRank T ≤ r := by + apply asymptoticRank_le_of_power_bound T (C := (Module.finrank F K) ^ 2) + (pow_pos Module.finrank_pos 2) + intro n + have hpow := h.power n + rw [power_scalarExtension] at hpow + simpa only [mul_comm] using tensorRank_le_of_rankAtMost (rankAtMost_of_finiteExtension hpow) + +end + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Flattening.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Flattening.lean new file mode 100644 index 0000000000..061da22896 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Flattening.lean @@ -0,0 +1,108 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Tensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.MatrixMinors +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorFlattening + +/-! # Flattening lower bounds in finite rectangular formats + +Each flattening contains an identity minor. Applying the argument to powers, +whose wire indices are tuples, preserves the lower bound on taking roots. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +noncomputable section + +section + +open MatrixMultiplication.Foundation + +section Finite + +variable {F A B C : Type*} [Field F] [Fintype A] [Fintype B] [Fintype C] + [DecidableEq A] [DecidableEq B] [DecidableEq C] + +omit [Fintype B] in +private theorem card_last_le_rank {r : ℕ} (b : B) + (h : Tensor.RankAtMost (Tensor.matrixCoefficients (K := F) A B C) r) : + Fintype.card C * Fintype.card A ≤ r := by + rw [← Fintype.card_prod] + apply h.card_le_of_identity (fun i : C × A => (i.2, b)) (fun i => (b, i.1)) id + intro i j + have hh := congrFun (congrFun (matrixMinor₃ (K := F) (A := A) (C := C) b) j) i + simpa [Matrix.one_apply, eq_comm] using hh + +/-- A rank decomposition bounds the cardinalities of all three local bases. -/ +theorem matrixCoefficients_flattenings {r : ℕ} (a : A) (b : B) (c : C) + (h : Tensor.RankAtMost (Tensor.matrixCoefficients (K := F) A B C) r) : + max (Fintype.card A * Fintype.card B) + (max (Fintype.card B * Fintype.card C) (Fintype.card C * Fintype.card A)) ≤ r := by + exact max_le (card_last_le_rank c (Tensor.matrixCoefficients_cyclic_rank h)) + (max_le (card_last_le_rank a + (Tensor.matrixCoefficients_cyclic_rank (Tensor.matrixCoefficients_cyclic_rank h))) + (card_last_le_rank b h)) + +end Finite + +variable (F : Type*) [Field F] {n12 n23 n31 : ℕ} + +/-- Reindexing the three sites of a tensor power by tuples of wire indices +turns it into a single larger matrix multiplication tensor. -/ +theorem matrix_power_rankAtMost (s : ℕ) : + Tensor.RankAtMost (Tensor.matrixCoefficients (K := F) + (Fin s → Fin n31) (Fin s → Fin n12) (Fin s → Fin n23)) + (tensorRank (Tensor.power (matrixTensor F n12 n23 n31) s)) := by + have h := (rankAtMost_tensorRank (Tensor.power (matrixTensor F n12 n23 n31) s)).pullback + (fun x : (Fin s → Fin n31) × (Fin s → Fin n12) => fun i => (x.1 i, x.2 i)) + (fun y : (Fin s → Fin n12) × (Fin s → Fin n23) => fun i => (y.1 i, y.2 i)) + (fun z : (Fin s → Fin n23) × (Fin s → Fin n31) => fun i => (z.1 i, z.2 i)) + convert h using 1 + funext x y z + exact (Tensor.matrixCoefficients_power s x y z).symm + +/-- The largest local dimension bounds ordinary rank from below. -/ +theorem matrix_flattening_le_tensorRank (h12 : 0 < n12) (h23 : 0 < n23) (h31 : 0 < n31) : + max (n31 * n12) (max (n12 * n23) (n23 * n31)) ≤ + tensorRank (matrixTensor F n12 n23 n31) := by + simpa using matrixCoefficients_flattenings + (F := F) (⟨0, h31⟩ : Fin n31) (⟨0, h12⟩ : Fin n12) (⟨0, h23⟩ : Fin n23) + (rankAtMost_tensorRank (matrixTensor F n12 n23 n31)) + +/-- The largest local dimension bounds asymptotic rank from below over every field. -/ +theorem matrix_flattening_le_asymptoticRank (h12 : 0 < n12) (h23 : 0 < n23) (h31 : 0 < n31) : + (max (n31 * n12) (max (n12 * n23) (n23 * n31)) : ℕ) ≤ + asymptoticRank (matrixTensor F n12 n23 n31) := by + apply le_ciInf + intro s + have h := matrixCoefficients_flattenings + (fun _ => (⟨0, h31⟩ : Fin n31)) (fun _ => (⟨0, h12⟩ : Fin n12)) + (fun _ => (⟨0, h23⟩ : Fin n23)) (matrix_power_rankAtMost F (s + 1)) + simp only [Fintype.card_pi_const, Fintype.card_fin, ← mul_pow] at h + apply (Real.le_rpow_inv_iff_of_pos (Nat.cast_nonneg _) (Nat.cast_nonneg _) + (show 0 < (s : ℝ) + 1 by positivity)).mpr + rw [← Nat.cast_succ, Real.rpow_natCast] + have hm (a b : ℕ) : max a b ^ (s+1) = max (a ^ (s+1)) (b ^ (s+1)) := + (pow_left_mono (n := s+1)).map_max + have hh : max (n31 * n12) (max (n12 * n23) (n23 * n31)) ^ (s+1) ≤ + tensorRank (Tensor.power (matrixTensor F n12 n23 n31) (s+1)) := by + simpa only [hm] using h + exact_mod_cast hh + +end + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalBlockFamily.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalBlockFamily.lean new file mode 100644 index 0000000000..27487f195d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalBlockFamily.lean @@ -0,0 +1,116 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalLinearExpr +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalSubstitute + +/-! # Polynomial output of recursive block program families -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Arithmetic Arithmetic.RecursiveBlock MvPolynomial +noncomputable section + +variable {F I J O : Type*} [Field F] + +/-- The formal polynomial at a designated output of a circuit family. -/ +def familyPolynomial (p : Family F I O) (o : O) : MvPolynomial I F := + registerPolynomial p.program (p.output o) + +/-- Composition of circuit families substitutes the inner output polynomials. -/ +theorem familyPolynomial_compose (p : Family F I J) (q : Family F J O) (o : O) : + familyPolynomial (p.compose q) o = + bind₁ (familyPolynomial p) (familyPolynomial q o) := + registerPolynomial_substitute p.program q.program p.output (q.output o) + +theorem registerPolynomial_mapInput (f : I → J) {r : ℕ} + (p : Program F I r) (i : Fin r) : + registerPolynomial (p.mapInput f) i = rename f (registerPolynomial p i) := by + induction p with + | nil => exact i.elim0 + | step p g ih => + refine Fin.cases ?_ (fun j => ih j) i + cases g <;> simp [Program.mapInput, Gate.mapInput, gatePolynomial, ih] + +private theorem familyPolynomial_parallel (r : ℕ) (p : Fin r → Family F I O) + (o : Fin r × O) : + familyPolynomial (Family.parallel r p) o = familyPolynomial (p o.1) o.2 := by + induction r with + | zero => exact o.1.elim0 + | succ r ih => + rcases o with ⟨i, o⟩ + refine Fin.cases ?_ (fun j => ?_) i + · exact registerPolynomial_append_old _ _ _ + · exact (registerPolynomial_append_new _ _ _).trans (ih _ (j, o)) + +/-- A copy of a circuit renames each variable by attaching its copy index. -/ +theorem familyPolynomial_copies (r : ℕ) (p : Family F I O) (o : Fin r × O) : + familyPolynomial (Family.copies r p) o = + rename (fun i => (o.1, i)) (familyPolynomial p o.2) := by + rw [Family.copies, familyPolynomial_parallel] + exact registerPolynomial_mapInput _ _ _ + +theorem familyPolynomial_ofMatrix {a b c : ℕ} (p : MatrixAlgorithm F a b c) + (o : Fin a × Fin c) : + familyPolynomial (Family.ofMatrix p) o = registerPolynomial p.program (p.output o.1 o.2) := + rfl + +/-- Compiling a family of expressions computes their formal polynomials. -/ +theorem familyPolynomial_expressions [Fintype O] (e : O → Expression F I) (o : O) : + familyPolynomial (Family.expressions e) o = expressionPolynomial (e o) := + registerPolynomial_expressions e o + +variable {n₁ n₂ n₃ r m₁ m₂ m₃ : ℕ} + +theorem familyPolynomial_inputFamily_left + (a : Fin r → Fin n₁ × Fin n₂ → F) (b : Fin r → Fin n₂ × Fin n₃ → F) + (q : Fin r) (s : Fin m₁) (t : Fin m₂) : + familyPolynomial (inputFamily (m₃ := m₃) a b) (q, .inl (s, t)) = + ∑ x, C (a q x) * X (.inl (join x.1 s, join x.2 t)) := by + rw [inputFamily, familyPolynomial_expressions, inputExpressions, expressionPolynomial_linear] + +theorem familyPolynomial_inputFamily_right + (a : Fin r → Fin n₁ × Fin n₂ → F) (b : Fin r → Fin n₂ × Fin n₃ → F) + (q : Fin r) (t : Fin m₂) (u : Fin m₃) : + familyPolynomial (inputFamily (m₁ := m₁) a b) (q, .inr (t, u)) = + ∑ y, C (b q y) * X (.inr (join y.1 t, join y.2 u)) := by + rw [inputFamily, familyPolynomial_expressions, inputExpressions, expressionPolynomial_linear] + +/-- Substitution into the output linear combinations joins the two output indices. -/ +theorem bind₁_outputFamily {V : Type*} (c : Fin r → Fin n₃ × Fin n₁ → F) + (v : Fin r × (Fin m₁ × Fin m₃) → MvPolynomial V F) + (i : Fin n₁) (k : Fin n₃) (s : Fin m₁) (u : Fin m₃) : + bind₁ v (familyPolynomial (outputFamily c) (join i s, join k u)) = + ∑ q, C (c q (k, i)) * v (q, (s, u)) := by + simp only [outputFamily, familyPolynomial_expressions, outputExpressions, + expressionPolynomial_linear, join, Equiv.symm_apply_apply, map_sum, map_mul, + bind₁_C_right, bind₁_X_right] + +/-- The formal products of the input block linear combinations computed by recursive copies. -/ +theorem familyPolynomial_recursiveProducts + (a : Fin r → Fin n₁ × Fin n₂ → F) (b : Fin r → Fin n₂ × Fin n₃ → F) + (P : MatrixAlgorithm F m₁ m₂ m₃) (hP : FormalCorrect P) + (q : Fin r) (s : Fin m₁) (u : Fin m₃) : + familyPolynomial (recursiveProducts a b P) (q, (s, u)) = + ∑ t : Fin m₂, + (∑ x, C (a q x) * X (.inl (join x.1 s, join x.2 t))) * + (∑ y, C (b q y) * X (.inr (join y.1 t, join y.2 u))) := by + rw [recursiveProducts, familyPolynomial_compose, familyPolynomial_copies, + familyPolynomial_ofMatrix, hP, bind₁_rename, map_sum] + simp only [map_mul, bind₁_X_right, Function.comp_apply, familyPolynomial_inputFamily_left, + familyPolynomial_inputFamily_right] + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalBlockStep.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalBlockStep.lean new file mode 100644 index 0000000000..3d9d5482f1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalBlockStep.lean @@ -0,0 +1,87 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalBlockFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Tensor +public import Mathlib.RingTheory.Localization.FractionRing + +/-! # Formal correctness of one rank-based block recursion -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Arithmetic Arithmetic.RecursiveBlock Foundation MvPolynomial +open scoped BigOperators + +noncomputable section + +variable {F : Type*} [Field F] {n₁ n₂ n₃ r m₁ m₂ m₃ : ℕ} + +private theorem polynomial_block_identity {I : Type*} + (a : Fin r → Fin n₁ × Fin n₂ → F) (b : Fin r → Fin n₂ × Fin n₃ → F) + (c : Fin r → Fin n₃ × Fin n₁ → F) + (h : Tensor.matrixCoefficients (K := F) (Fin n₁) (Fin n₂) (Fin n₃) = + fun x y z => ∑ q, Tensor.rankOne (a q) (b q) (c q) x y z) + (A : Matrix (Fin (n₁ * m₁)) (Fin (n₂ * m₂)) (MvPolynomial I F)) + (B : Matrix (Fin (n₂ * m₂)) (Fin (n₃ * m₃)) (MvPolynomial I F)) + (i : Fin n₁) (k : Fin n₃) (s : Fin m₁) (u : Fin m₃) : + (∑ q, C (c q (k,i)) * ∑ t : Fin m₂, + (∑ x, C (a q x) * A (join x.1 s) (join x.2 t)) * + (∑ y, C (b q y) * B (join y.1 t) (join y.2 u))) = + ∑ j, A (join i s) j * B j (join k u) := by + let K := FractionRing (MvPolynomial I F) + let ι := algebraMap (MvPolynomial I F) K + let φ : F →+* K := ι.comp C + have hK : Tensor.matrixCoefficients (K := K) (Fin n₁) (Fin n₂) (Fin n₃) = + fun x y z => ∑ q, Tensor.rankOne (φ ∘ a q) (φ ∘ b q) (φ ∘ c q) x y z := by + funext x y z + have he := congrArg φ (congrFun (congrFun (congrFun h x) y) z) + simpa [Tensor.matrixCoefficients, Tensor.rankOne, apply_ite] using he + apply IsFractionRing.injective (MvPolynomial I F) K + simp only [map_sum, map_mul] + exact block_identity (fun q => φ ∘ a q) (fun q => φ ∘ b q) (fun q => φ ∘ c q) hK + (fun x y => ι (A x y)) (fun x y => ι (B x y)) i k s u + +/-- Composing the three block linear maps with a correct smaller multiplication +algorithm preserves correctness as a polynomial identity over the ground field. -/ +theorem formalCorrect_blockAlgorithm (a : Fin r → Fin n₁ × Fin n₂ → F) + (b : Fin r → Fin n₂ × Fin n₃ → F) (c : Fin r → Fin n₃ × Fin n₁ → F) + (h : Tensor.matrixCoefficients (K := F) (Fin n₁) (Fin n₂) (Fin n₃) = + fun x y z => ∑ q, Tensor.rankOne (a q) (b q) (c q) x y z) + (P : MatrixAlgorithm F m₁ m₂ m₃) (hP : FormalCorrect P) : + FormalCorrect (algorithm a b c P) := by + intro i k + obtain ⟨⟨i,s⟩,rfl⟩ := finProdFinEquiv.surjective i + obtain ⟨⟨k,u⟩,rfl⟩ := finProdFinEquiv.surjective k + change familyPolynomial ((recursiveProducts a b P).compose (outputFamily c)) (join i s, join k u) + = _ + rw [familyPolynomial_compose, bind₁_outputFamily] + simp_rw [familyPolynomial_recursiveProducts a b P hP] + exact polynomial_block_identity (m₁ := m₁) (m₂ := m₂) (m₃ := m₃) + (I := MatrixInput (n₁*m₁) (n₂*m₂) (n₃*m₃)) a b c h + (fun x y => X (.inl (x,y))) (fun x y => X (.inr (x,y))) i k s u + +/-- A square rank formula produces a formally correct recursion step with linear +combination overhead proportional to the smaller matrices' area. -/ +theorem square_formal_block_step {n m r : ℕ} + (hr : Tensor.RankAtMost (matrixTensor F n n n) r) (P : MatrixAlgorithm F m m m) + (hP : FormalCorrect P) : ∃ Q : MatrixAlgorithm F (n*m) (n*m) (n*m), + FormalCorrect Q ∧ Q.cost ≤ r * P.cost + 6 * r * n ^ 2 * m ^ 2 := by + obtain ⟨a,b,c,h⟩ := hr + refine ⟨algorithm a b c P, formalCorrect_blockAlgorithm a b c h P hP, ?_⟩ + rw [algorithm_cost] + exact le_of_eq (by ring) + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalCircuit.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalCircuit.lean new file mode 100644 index 0000000000..0671a3a524 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalCircuit.lean @@ -0,0 +1,138 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Arithmetic.NaiveAlgorithm +public import Mathlib.Algebra.MvPolynomial.Eval + +/-! # Formal polynomial semantics for division-free arithmetic circuits + +Registers in the repository's straight-line programs can be interpreted in the +polynomial ring on the inputs. This distinguishes formal identities over a finite +field from equality of polynomial functions on its rational points. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Arithmetic MvPolynomial +open scoped BigOperators +noncomputable section + +variable {F I R : Type*} [CommRing F] + +/-- The polynomial produced at one gate from the polynomials in its registers. -/ +def gatePolynomial (g : Gate F I R) (v : R → MvPolynomial I F) : MvPolynomial I F := + g.casesOn (fun c => C c) (fun i => X i) + (fun i j => v i + v j) (fun i j => v i - v j) (fun i j => v i * v j) + +/-- Formal polynomial in each register of a straight-line program. -/ +def registerPolynomial : {r : ℕ} → Program F I r → Fin r → MvPolynomial I F + | _, .nil => Fin.elim0 + | _, .step p g => Fin.cases (gatePolynomial g (registerPolynomial p)) (registerPolynomial p) + +@[simp] theorem registerPolynomial_zero {r : ℕ} (p : Program F I r) (g : Gate F I (Fin r)) : + registerPolynomial (p.step g) 0 = gatePolynomial g (registerPolynomial p) := rfl + +@[simp] theorem registerPolynomial_succ {r : ℕ} (p : Program F I r) (g : Gate F I (Fin r)) + (i : Fin r) : registerPolynomial (p.step g) i.succ = registerPolynomial p i := rfl + +/-- Formal polynomial correctness for a division-free program, including over finite fields. -/ +def FormalCorrect {a b c : ℕ} (P : MatrixAlgorithm F a b c) : Prop := + ∀ i k, registerPolynomial P.program (P.output i k) = + ∑ j : Fin b, X (Sum.inl (i, j)) * X (Sum.inr (j, k)) + +private theorem gatePolynomial_mapRegister {S : Type*} (f : R → S) + (v : S → MvPolynomial I F) (g : Gate F I R) : + gatePolynomial (g.mapRegister f) v = gatePolynomial g (v ∘ f) := by + cases g <;> rfl + +theorem registerPolynomial_append_new {r s : ℕ} (p : Program F I r) + (q : Program F I s) (i : Fin s) : + registerPolynomial (p.append q) (Program.newIndex r s i) = registerPolynomial q i := by + induction q with + | nil => exact i.elim0 + | @step s q g ih => + refine Fin.cases ?_ (fun j => ?_) i + · simp only [Program.append, Program.newIndex_zero, registerPolynomial_zero, + gatePolynomial_mapRegister] + congr 1 + exact funext ih + · simpa only [Program.append, Program.newIndex_succ, registerPolynomial_succ] using ih j + +theorem registerPolynomial_append_old {r s : ℕ} (p : Program F I r) + (q : Program F I s) (i : Fin r) : + registerPolynomial (p.append q) (Program.oldIndex r s i) = registerPolynomial p i := by + induction q with + | nil => simp [Program.append] + | @step s q g ih => + simpa only [Program.append, Program.oldIndex_succ, registerPolynomial_succ] using ih + +end + +noncomputable section + +variable {F I : Type*} + +section +variable [CommRing F] + +/-- Interpret an arithmetic expression as a formal polynomial in its inputs. -/ +def expressionPolynomial : Expression F I → MvPolynomial I F + | .literal value => C value + | .input index => X index + | .add left right => expressionPolynomial left + expressionPolynomial right + | .sub left right => expressionPolynomial left - expressionPolynomial right + | .mul left right => expressionPolynomial left * expressionPolynomial right + +end + +variable [Field F] + +theorem registerPolynomial_compile (e : Expression F I) : + registerPolynomial e.compile.program e.compile.output = expressionPolynomial e := by + induction e <;> simp_all [Expression.compile, expressionPolynomial, gatePolynomial, + registerPolynomial_append_old, registerPolynomial_append_new] + +theorem registerPolynomial_compileFinFamily (n : ℕ) (f : Fin n → Expression F I) + (i : Fin n) : + registerPolynomial (Expression.compileFinFamily n f).program + ((Expression.compileFinFamily n f).output i) = expressionPolynomial (f i) := by + induction n with + | zero => exact i.elim0 + | succ n ih => + refine Fin.cases ?_ (fun j => ?_) i + · simp [Expression.compileFinFamily, registerPolynomial_append_old, registerPolynomial_compile] + · simp [Expression.compileFinFamily, registerPolynomial_append_new, ih] + +theorem registerPolynomial_compileFamily {O : Type*} [Fintype O] + (f : O → Expression F I) (i : O) : + registerPolynomial (Expression.compileFamily f).program ((Expression.compileFamily f).output i) + = expressionPolynomial (f i) := by + simp [Expression.compileFamily, registerPolynomial_compileFinFamily] + +theorem expressionPolynomial_sumFin {n : ℕ} (f : Fin n → Expression F I) : + expressionPolynomial (Expression.sumFin f) = ∑ i, expressionPolynomial (f i) := by + induction n with + | zero => simp [Expression.sumFin, expressionPolynomial] + | succ n ih => simp [Expression.sumFin, expressionPolynomial, ih, Fin.sum_univ_succ] + +/-- The usual entrywise algorithm computes the formal matrix product over every field. -/ +theorem formalCorrect_naiveAlgorithm (F : Type*) [Field F] (a b c : ℕ) : + FormalCorrect (naiveAlgorithm (F := F) a b c) := by + intro i k + simp [naiveAlgorithm, registerPolynomial_compileFamily, naiveEntry, expressionPolynomial_sumFin, + expressionPolynomial] + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalLinearExpr.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalLinearExpr.lean new file mode 100644 index 0000000000..199f9e6dcd --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalLinearExpr.lean @@ -0,0 +1,57 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalCircuit +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Arithmetic.RecursiveBlockPrograms + +/-! # Formal polynomials computed by families of linear expressions -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Arithmetic Arithmetic.RecursiveBlock MvPolynomial +open scoped BigOperators + +noncomputable section + +variable {F I O : Type*} [Field F] + +private theorem expressionPolynomial_linear_sumFin (n : ℕ) (f : Fin n → Expression F I) : + expressionPolynomial (LinearExpression.sumFin n f) = ∑ i, expressionPolynomial (f i) := by + induction n with + | zero => simp [LinearExpression.sumFin, expressionPolynomial] + | succ n ih => simp [LinearExpression.sumFin, expressionPolynomial, ih, Fin.sum_univ_succ] + +/-- A linear expression compiles to its coefficient-weighted sum of input variables. -/ +theorem expressionPolynomial_linear {Term : Type*} [Fintype Term] + (a : Term → F) (wire : Term → I) : + expressionPolynomial (LinearExpression.linear a wire) = ∑ i, C (a i) * X (wire i) := by + rw [LinearExpression.linear, expressionPolynomial_linear_sumFin] + exact (Fintype.equivFin Term).symm.sum_comp (fun i => C (a i) * X (wire i)) + +/-- The output polynomial of a compiled family is the polynomial of the selected expression. -/ +theorem registerPolynomial_expressions [Fintype O] (e : O → Expression F I) (o : O) : + registerPolynomial (Family.expressions e).program ((Family.expressions e).output o) = + expressionPolynomial (e o) := + registerPolynomial_compileFamily e o + +/-- Each output may sum over its own finite set of input terms. -/ +theorem registerPolynomial_expressions_linear [Fintype O] {Term : O → Type*} + [∀ o, Fintype (Term o)] (a : (o : O) → Term o → F) (wire : (o : O) → Term o → I) (o : O) : + let p := Family.expressions (fun j => LinearExpression.linear (a j) (wire j)) + registerPolynomial p.program (p.output o) = ∑ i, C (a o i) * X (wire o i) := + (registerPolynomial_expressions _ o).trans (expressionPolynomial_linear _ _) + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalPadding.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalPadding.lean new file mode 100644 index 0000000000..7d5fea84f6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalPadding.lean @@ -0,0 +1,71 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalCircuit +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Arithmetic.Padding + +/-! # Zero padding preserves formal matrix identities -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Arithmetic MvPolynomial +noncomputable section + +variable {F I J : Type*} + +section +variable [CommRing F] + +/-- Replacing each circuit input by a variable or a scalar realizes the +corresponding substitution on its formal output polynomial. -/ +theorem registerPolynomial_mapSource (f : I → J ⊕ F) {r : ℕ} + (p : Program F I r) (i : Fin r) : + registerPolynomial (p.mapSource f) i = + aeval (fun j => Sum.elim X C (f j) : I → MvPolynomial J F) (registerPolynomial p i) := by + induction p with + | nil => exact i.elim0 + | step p g ih => + refine Fin.cases ?_ (fun j => ih j) i + cases g with + | input j => + cases h : f j <;> simp [Program.mapSource, Gate.mapSource, gatePolynomial, h] + | literal z => simp [Program.mapSource, Gate.mapSource, gatePolynomial] + | add a b => simp [Program.mapSource, Gate.mapSource, gatePolynomial, ih] + | sub a b => simp [Program.mapSource, Gate.mapSource, gatePolynomial, ih] + | mul a b => simp [Program.mapSource, Gate.mapSource, gatePolynomial, ih] + +end + +variable [Field F] + +theorem FormalCorrect.pad {a b c A B C : ℕ} {P : MatrixAlgorithm F A B C} + (hP : FormalCorrect P) (ha : a ≤ A) (hb : b ≤ B) (hc : c ≤ C) : + FormalCorrect (P.pad ha hb hc) := by + intro i k + change registerPolynomial (P.program.mapSource _) (P.output (i.castLE ha) (k.castLE hc)) = _ + rw [registerPolynomial_mapSource, hP, map_sum] + simp only [map_mul, aeval_X] + symm + refine Fintype.sum_of_injective (Fin.castLE hb) (fun a b hab => Fin.ext (congrArg (fun v : Fin B + => v.val) hab)) + _ _ ?_ ?_ + · intro j hj + have hlarge : ¬ j.val < b := fun hsmall => hj ⟨⟨j.val, hsmall⟩, Fin.ext rfl⟩ + simp [padSource, hlarge, i.isLt] + · intro j + simp [padSource, i.isLt, j.isLt, k.isLt] + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalRecursion.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalRecursion.lean new file mode 100644 index 0000000000..1c6507207a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalRecursion.lean @@ -0,0 +1,114 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.ArithmeticExponent +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalPadding +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalBlockStep +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Rectangular.Growth + +/-! # Formal circuit cost of powering a square rank decomposition -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Arithmetic Foundation +noncomputable section + +variable {F : Type*} [Field F] + +private theorem formalCorrect_scalar : FormalCorrect (scalarAlgorithm F) := by + intro i k + fin_cases i + fin_cases k + change MvPolynomial.X (Sum.inl (0,0)) * MvPolynomial.X (Sum.inr (0,0)) = _ + simp + +/-- Pad a program at each power to cover every positive size, retaining formal correctness. -/ +private theorem squareAdmissible_of_power_costs {a : ℕ} (ha : 2 ≤ a) {τ : ℝ} (hτ : 0 ≤ τ) + (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ t : ℕ, + ∃ P : MatrixAlgorithm F (a ^ t) (a ^ t) (a ^ t), + FormalCorrect P ∧ (P.cost : ℝ) ≤ C * ((a : ℝ) ^ (τ + ε)) ^ t) : + FormalAdmissibleExponent F 1 1 1 τ := by + intro ε hε + have ha' : (0 : ℝ) < a := by exact_mod_cast (show 0 < a by omega) + obtain ⟨C, hC, hbound⟩ := h ε hε + refine ⟨C * (a : ℝ) ^ (τ + ε), by positivity, ?_⟩ + intro N hN + have hd : wireDimension N 1 = N := by simp [wireDimension] + rw [hd] + obtain ⟨t, hlow, hhigh⟩ := Foundation.Arithmetic.exists_power_cover ha hN + obtain ⟨P, hP, hcost⟩ := hbound t + refine ⟨P.pad hlow hlow hlow, hP.pad hlow hlow hlow, ?_⟩ + rw [MatrixAlgorithm.pad_cost_eq] + apply hcost.trans + calc + _ = C * ((a ^ t : ℕ) : ℝ) ^ (τ + ε) := by rw [Nat.cast_pow, Real.rpow_pow_comm ha'.le] + _ ≤ C * ((a : ℝ) * N) ^ (τ + ε) := mul_le_mul_of_nonneg_left + (Real.rpow_le_rpow (Nat.cast_nonneg _) (by exact_mod_cast hhigh) (by linarith)) hC.le + _ = _ := by rw [Real.mul_rpow ha'.le (Nat.cast_nonneg _)]; ring + +private theorem rpow_formalOmega_le_of_block_step {n R : ℕ} (hn : 2 ≤ n) + (hR : n * n ≤ R) + (hstep : ∀ (m : ℕ) (P : MatrixAlgorithm F m m m), FormalCorrect P → + ∃ Q : MatrixAlgorithm F (n * m) (n * m) (n * m), FormalCorrect Q ∧ + Q.cost ≤ R * P.cost + 6 * R * n ^ 2 * m ^ 2) : + (n : ℝ) ^ formalOmega F 1 1 1 ≤ R := by + have hn' : (1 : ℝ) < n := by exact_mod_cast (show 1 < n by omega) + have hR' : (0 : ℝ) < R := by + exact_mod_cast (Nat.mul_pos (by omega : 0 < n) (by omega : 0 < n)).trans_le hR + let τ := Real.logb (n : ℝ) R + have hrate : (n : ℝ) ^ τ = R := Real.rpow_logb (by linarith) hn'.ne' hR' + have hτ : 0 ≤ τ := Real.logb_nonneg hn' (by exact_mod_cast (show 1 ≤ R by nlinarith)) + let K := 6 * R * n ^ 2 + have powers (t : ℕ) : + ∃ P : MatrixAlgorithm F (n ^ t) (n ^ t) (n ^ t), + FormalCorrect P ∧ P.cost ≤ rectangularBlockCost n n R K t := by + induction t with + | zero => + simpa using (show ∃ P : MatrixAlgorithm F 1 1 1, FormalCorrect P ∧ P.cost ≤ 1 from + ⟨scalarAlgorithm F, formalCorrect_scalar, (scalarAlgorithm_cost F).le⟩) + | succ t ih => + obtain ⟨P, hP, hcost⟩ := ih + obtain ⟨Q, hQ, hrec⟩ := hstep (n^t) P hP + rw [pow_succ'] + refine ⟨Q, hQ, hrec.trans ?_⟩ + apply Nat.add_le_add (Nat.mul_le_mul_left R hcost) + change K * (n ^ t) ^ 2 ≤ K * ((n*n)^t + (n^2)^t) + rw [← pow_mul, Nat.mul_comm t 2, pow_mul] + exact Nat.mul_le_mul_left _ (Nat.le_add_left _ _) + have hadm : FormalAdmissibleExponent F 1 1 1 τ := by + apply squareAdmissible_of_power_costs hn hτ + intro ε hε + have hsize : ((n * n : ℕ) : ℝ) ≤ (n : ℝ) ^ τ := by rw [hrate]; exact_mod_cast hR + obtain ⟨C, hC, hCbound⟩ := rectangularBlockCost_bound (b := n) (R := R) (K := K) hn hε + hrate.ge hsize (by simpa [pow_two] using hsize) + refine ⟨C, hC, fun t => ?_⟩ + obtain ⟨P, hP, hc⟩ := powers t + exact ⟨P, hP, (Nat.cast_le.mpr hc).trans (hCbound t)⟩ + rw [← hrate] + apply Real.rpow_le_rpow_of_exponent_le hn'.le + exact csInf_le (s := {σ : ℝ | FormalAdmissibleExponent F 1 1 1 σ}) + ⟨loads 1 1 1 0, fun _ h => h.load_le 0⟩ hadm + +/-- A fixed square rank decomposition bounds the formal arithmetic exponent +over an arbitrary field, including finite fields. -/ +theorem rpow_formalOmega_le_tensorRank (F : Type*) [Field F] {n : ℕ} (hn : 2 ≤ n) : + (n : ℝ) ^ formalOmega F 1 1 1 ≤ tensorRank (matrixTensor F n n n) := by + apply rpow_formalOmega_le_of_block_step hn + · exact (le_max_left _ _).trans (matrix_flattening_le_tensorRank F (by omega) (by omega) (by + omega)) + · exact fun _ P hP => square_formal_block_step (rankAtMost_tensorRank _) P hP + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalSubstitute.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalSubstitute.lean new file mode 100644 index 0000000000..f523f03aff --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/FormalSubstitute.lean @@ -0,0 +1,66 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Arithmetic.ProgramComposition +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalCircuit +public import Mathlib.Algebra.MvPolynomial.Monad + +/-! # Formal polynomial semantics of program substitution -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Arithmetic MvPolynomial + +variable {F I J : Type*} [Field F] + +private theorem registerPolynomial_substitute_all {r s : ℕ} (p : Program F I r) + (q : Program F J s) (inputs : J → Fin r) : + (∀ i, registerPolynomial (p.substitute q inputs).program + ((p.substitute q inputs).oldOutput i) = registerPolynomial p i) ∧ + (∀ i, registerPolynomial (p.substitute q inputs).program + ((p.substitute q inputs).output i) = + bind₁ (fun j => registerPolynomial p (inputs j)) (registerPolynomial q i)) := by + induction q with + | nil => exact ⟨fun _ => rfl, fun i => i.elim0⟩ + | step q g ih => + obtain ⟨hold, hnew⟩ := ih + constructor + · intro i + cases g <;> exact hold i + · intro i + cases g <;> refine Fin.cases ?_ (fun j => hnew j) i + case literal value => + change C value = bind₁ _ (C value) + rw [bind₁_C_right] + case input index => + rw [registerPolynomial_zero, gatePolynomial, bind₁_X_right] + exact hold (inputs index) + case add left right => + rw [registerPolynomial_zero, gatePolynomial, map_add] + exact congrArg₂ (· + ·) (hnew left) (hnew right) + case sub left right => + rw [registerPolynomial_zero, gatePolynomial, map_sub] + exact congrArg₂ (· - ·) (hnew left) (hnew right) + case mul left right => + rw [registerPolynomial_zero, gatePolynomial, map_mul] + exact congrArg₂ (· * ·) (hnew left) (hnew right) + +/-- Substitution into a program acts on its register polynomials by polynomial substitution. -/ +theorem registerPolynomial_substitute {r s : ℕ} (p : Program F I r) + (q : Program F J s) (inputs : J → Fin r) (j : Fin s) : + registerPolynomial (p.substitute q inputs).program ((p.substitute q inputs).output j) = + bind₁ (fun i => registerPolynomial p (inputs i)) (registerPolynomial q j) := + (registerPolynomial_substitute_all p q inputs).2 j + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/MatrixMinors.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/MatrixMinors.lean new file mode 100644 index 0000000000..291a4f866c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/MatrixMinors.lean @@ -0,0 +1,55 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexMatrixTensor +public import Mathlib.Data.Matrix.Diagonal + +/-! # Identity minors of the matrix multiplication tensor + +Fixing the wire opposite a site selects a square submatrix of its flattening +with one row for every local index. The matching-wire rule makes this +submatrix the identity, independently of the scalar characteristic. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Foundation.Tensor + +variable {K A B C : Type*} [CommSemiring K] [DecidableEq A] [DecidableEq B] [DecidableEq C] + +/-- Fix the third wire and read off both indices of the first site. -/ +theorem matrixMinor₁ (k : C) : + Matrix.of (fun x x' : A × B => + matrixCoefficients (K := K) A B C x (x'.2, k) (k, x'.1)) = 1 := by + ext x x' + simp only [Matrix.of_apply, matrixCoefficients, Matrix.one_apply, Prod.ext_iff] + by_cases ha : x.1 = x'.1 <;> by_cases hb : x.2 = x'.2 <;> simp_all [eq_comm] + +/-- Fix the first wire and read off both indices of the second site. -/ +theorem matrixMinor₂ (i : A) : + Matrix.of (fun y y' : B × C => + matrixCoefficients (K := K) A B C (i, y'.1) y (y'.2, i)) = 1 := by + ext y y' + simp only [Matrix.of_apply, matrixCoefficients, Matrix.one_apply, Prod.ext_iff] + by_cases hb : y.1 = y'.1 <;> by_cases hc : y.2 = y'.2 <;> simp_all [eq_comm] + +/-- Fix the second wire and read off both indices of the third site. -/ +theorem matrixMinor₃ (j : B) : + Matrix.of (fun z z' : C × A => + matrixCoefficients (K := K) A B C (z'.2, j) (j, z'.1) z) = 1 := by + ext z z' + simp only [Matrix.of_apply, matrixCoefficients, Matrix.one_apply, Prod.ext_iff] + by_cases hc : z.1 = z'.1 <;> by_cases ha : z.2 = z'.2 <;> simp_all [eq_comm] + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/MatrixPower.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/MatrixPower.lean new file mode 100644 index 0000000000..e6524dde87 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/MatrixPower.lean @@ -0,0 +1,56 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Flattening + +/-! # Tensor powers of rectangular matrix multiplication -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open MatrixMultiplication.Foundation + +private theorem matrixCoefficients_rankAtMost_reindex {F A B C A' B' C' : Type*} + [Field F] [DecidableEq A] [DecidableEq B] [DecidableEq C] + [DecidableEq A'] [DecidableEq B'] [DecidableEq C'] + (f : A' ≃ A) (g : B' ≃ B) (j : C' ≃ C) {r : ℕ} + (h : Tensor.RankAtMost (Tensor.matrixCoefficients (K := F) A B C) r) : + Tensor.RankAtMost (Tensor.matrixCoefficients (K := F) A' B' C') r := by + have h' := h.pullback (Prod.map f g) (Prod.map g j) (Prod.map j f) + convert h' using 1 + funext x y z + simp [Tensor.pullback, Tensor.matrixCoefficients] + +/-- The `k`-fold tensor power of a matrix multiplication tensor has the same rank +as the matrix multiplication tensor with each wire dimension raised to `k`. -/ +theorem tensorRank_matrixTensor_power (F : Type*) [Field F] (a b c k : ℕ) : + tensorRank (Tensor.power (matrixTensor F a b c) k) = + tensorRank (matrixTensor F (a ^ k) (b ^ k) (c ^ k)) := by + let e (n : ℕ) : (Fin k → Fin n) ≃ Fin (n ^ k) := Fintype.equivFinOfCardEq (by simp) + apply le_antisymm <;> apply tensorRank_le_of_rankAtMost + · have h := matrixCoefficients_rankAtMost_reindex (e c) (e a) (e b) + (rankAtMost_tensorRank (matrixTensor F (a ^ k) (b ^ k) (c ^ k))) + have h' := h.pullback + (fun x : Fin k → Fin c × Fin a => (fun i => (x i).1, fun i => (x i).2)) + (fun y : Fin k → Fin a × Fin b => (fun i => (y i).1, fun i => (y i).2)) + (fun z : Fin k → Fin b × Fin c => (fun i => (z i).1, fun i => (z i).2)) + convert h' using 1 + funext x y z + exact Tensor.matrixCoefficients_power k + (fun i => (x i).1, fun i => (x i).2) + (fun i => (y i).1, fun i => (y i).2) + (fun i => (z i).1, fun i => (z i).2) + · exact matrixCoefficients_rankAtMost_reindex (e c).symm (e a).symm (e b).symm + (matrix_power_rankAtMost F k) + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/PowerRank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/PowerRank.lean new file mode 100644 index 0000000000..40f6bbc951 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/PowerRank.lean @@ -0,0 +1,101 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.RankLimit + +/-! # Powers of asymptotic tensor rank + +Flattening a rectangular array of indices identifies iterated powers with a +single Kronecker power. The rank-root limit along the multiples of a positive +integer then gives the corresponding power of asymptotic rank. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +noncomputable section + +open Filter MatrixMultiplication.Foundation +open scoped Topology + +section + +variable {F X Y Z : Type*} [Field F] [Finite X] [Finite Y] + +private def flattenWord {A : Type*} (k n : ℕ) : + (Fin k → Fin n → A) ≃ (Fin (k * n) → A) where + toFun x i := x (finProdFinEquiv.symm i).1 (finProdFinEquiv.symm i).2 + invFun x i j := x (finProdFinEquiv (i, j)) + left_inv x := by funext i j; simp + right_inv x := by funext i; exact congrArg x (finProdFinEquiv.apply_symm_apply i) + +/-- Iterated tensor powers have the rank of the power at the product of their indices. -/ +theorem tensorRank_power_power (T : Tensor F X Y Z) (n k : ℕ) : + tensorRank (Tensor.power (Tensor.power T n) k) = tensorRank (Tensor.power T (k * n)) := by + have heq : Tensor.power (Tensor.power T n) k = Tensor.pullback + (flattenWord k n) (flattenWord k n) (flattenWord k n) (Tensor.power T (k * n)) := by + funext x y z + simp only [Tensor.power, Tensor.pullback] + rw [← Fintype.prod_prod_type'] + exact finProdFinEquiv.symm.prod_comp + (fun i : Fin k × Fin n => T (x i.1 i.2) (y i.1 i.2) (z i.1 i.2)) |>.symm + apply le_antisymm + · rw [heq] + exact tensorRank_le_of_rankAtMost ((rankAtMost_tensorRank _).pullback _ _ _) + · apply tensorRank_le_of_rankAtMost + have h := (rankAtMost_tensorRank (Tensor.power (Tensor.power T n) k)).pullback + (flattenWord k n).symm (flattenWord k n).symm (flattenWord k n).symm + convert h using 1 + funext x y z + simp [heq, Tensor.pullback] + +private theorem tensorRank_power_zero (T : Tensor F X Y Z) : + tensorRank (Tensor.power T 0) = 1 := by + apply le_antisymm + · apply tensorRank_le_of_rankAtMost + convert Tensor.rankOne_rankAtMost (fun _ => (1 : F)) (fun _ => (1 : F)) (fun _ => (1 : F)) + using 1 + funext x y z + simp [Tensor.rankOne, Tensor.power] + · by_contra! h + have hz := rankAtMost_tensorRank (Tensor.power T 0) + rw [show tensorRank (Tensor.power T 0) = 0 by omega] at hz + obtain ⟨_, _, _, hzero⟩ := hz + have he := congrFun (congrFun (congrFun hzero Fin.elim0) Fin.elim0) Fin.elim0 + simp [Tensor.power] at he + +/-- Asymptotic rank is multiplicative on powers, including the zeroth power. -/ +theorem asymptoticRank_power (T : Tensor F X Y Z) (n : ℕ) : + asymptoticRank (Tensor.power T n) = asymptoticRank T ^ n := by + apply tendsto_nhds_unique (tendsto_tensorRank_power_root _) + by_cases hn : n = 0 + · subst n + simp [tensorRank_power_power, tensorRank_power_zero] + · have hseq : Tendsto (fun k : ℕ => k * n) atTop atTop := by + apply tendsto_atTop_mono (f := id) _ tendsto_id + intro k + exact Nat.le_mul_of_pos_right k (Nat.pos_of_ne_zero hn) + apply (((tendsto_tensorRank_power_root T).comp hseq).pow n).congr + intro k + simp only [Function.comp_apply, tensorRank_power_power, Nat.cast_mul] + rw [← Real.rpow_mul_natCast (Nat.cast_nonneg _)] + congr 1 + rw [mul_inv_rev] + have hn' : (n : ℝ) ≠ 0 := by exact_mod_cast hn + field_simp + +end + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Rank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Rank.lean new file mode 100644 index 0000000000..6b7724f120 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Rank.lean @@ -0,0 +1,232 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Analysis.Real.Sqrt +public import Mathlib.Analysis.SpecialFunctions.Log.Base +public import Mathlib.Data.Fin.VecNotation +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.FinCases +public import Mathlib.Tactic.FunProp +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.NormNum +public import Mathlib.Tactic.Positivity +public import Mathlib.Tactic.Ring + +/-! # The height and radical tests for rectangular matrix multiplication + +The load at a site is the sum of its incident logarithmic wire dimensions. +This file proves the equivalence of the two numerical tests in the rectangular +rank theorem, including the cases of zero loads and saturated flattenings. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open Filter +open scoped BigOperators Topology +noncomputable section + +/-- The three site loads for the cyclically ordered wires. -/ +def loads (w12 w23 w31 : ℝ) : Fin 3 → ℝ := ![w31 + w12, w12 + w23, w23 + w31] + +/-- Inequality (height-bound), tested at independently chosen positive heights. -/ +def HeightTest (m : Fin 3 → ℝ) (L : ℝ) : Prop := + ∀ a : Fin 3 → ℝ, (∀ i, 0 < a i) → + ∑ i, a i * m i ≤ L * (∑ i, Real.sqrt (1 + a i ^ 2) - 1) + +/-- The flattening and radical inequalities of the rectangular rank theorem. -/ +def RadicalTest (m : Fin 3 → ℝ) (L : ℝ) : Prop := + (∀ i, m i ≤ L) ∧ L ≤ ∑ i, Real.sqrt (L ^ 2 - m i ^ 2) + +/-- The diagonal-price upper bound is positive for every triple of heights. -/ +theorem heightDenom_pos (a : Fin 3 → ℝ) : 0 < ∑ i, Real.sqrt (1 + a i ^ 2) - 1 := by + have h i : 1 ≤ Real.sqrt (1 + a i ^ 2) := by + exact (Real.le_sqrt (by norm_num) (by positivity)).mpr (by nlinarith [sq_nonneg (a i)]) + rw [Fin.sum_univ_three] + linarith [h 0, h 1, h 2] + +theorem HeightTest.mono {m : Fin 3 → ℝ} {L U : ℝ} (h : HeightTest m L) (hLU : L ≤ U) : + HeightTest m U := by + intro a ha + exact (h a ha).trans (mul_le_mul_of_nonneg_right hLU (heightDenom_pos a).le) + +private theorem le_at_right_endpoint {f g : ℝ → ℝ} {x : ℝ} + (hf : Continuous f) (hg : Continuous g) (h : ∀ y, x < y → f y ≤ g y) : f x ≤ g x := by + apply le_of_tendsto_of_tendsto (b := 𝓝[>] x) hf.continuousAt.continuousWithinAt + hg.continuousAt.continuousWithinAt + filter_upwards [self_mem_nhdsWithin] with y hy using h y hy + +/-- Zero-height sites are obtained by approaching from positive heights. -/ +theorem HeightTest.nonnegHeights {m : Fin 3 → ℝ} {L : ℝ} (h : HeightTest m L) + (a : Fin 3 → ℝ) (ha : ∀ i, 0 ≤ a i) : + ∑ i, a i * m i ≤ L * (∑ i, Real.sqrt (1 + a i ^ 2) - 1) := by + let f (t : ℝ) := ∑ i, (a i + t) * m i + let g (t : ℝ) := L * (∑ i, Real.sqrt (1 + (a i + t) ^ 2) - 1) + have hf : Continuous f := by dsimp [f]; fun_prop + have hg : Continuous g := by dsimp [g]; fun_prop + have bound : f 0 ≤ g 0 := le_at_right_endpoint hf hg + (fun t ht => h (fun i => a i + t) (fun i => add_pos_of_nonneg_of_pos (ha i) ht)) + simpa [f, g] using bound + +theorem HeightTest.nonneg {m : Fin 3 → ℝ} {L : ℝ} (h : HeightTest m L) : 0 ≤ L := by + have hzero := h.nonnegHeights (fun _ => 0) (fun _ => le_rfl) + norm_num [Fin.sum_univ_three] at hzero + linarith + +/-- Sending one height to infinity gives the corresponding flattening inequality. -/ +theorem HeightTest.load_le {m : Fin 3 → ℝ} {L : ℝ} (h : HeightTest m L) (i : Fin 3) : + m i ≤ L := by + by_contra! hsmall + let x := (2 * L + 1) / (m i - L) + have hx : 0 < x := div_pos (by linarith [h.nonneg]) (sub_pos.mpr hsmall) + have hax := h.nonnegHeights (fun j => if j = i then x else 0) + (fun j => by split <;> positivity) + have hbound : x * m i ≤ L * (Real.sqrt (1 + x ^ 2) + 1) := by + fin_cases i <;> simp [Fin.sum_univ_three] at hax ⊢ <;> linarith + have hs : Real.sqrt (1 + x ^ 2) ≤ 1 + x := by + apply Real.sqrt_le_iff.mpr + constructor <;> nlinarith + have hden : x * (m i - L) = 2 * L + 1 := div_mul_cancel₀ _ (sub_ne_zero.mpr hsmall.ne') + nlinarith [mul_le_mul_of_nonneg_left hs h.nonneg] + +private theorem minimizing_height {p b : ℝ} (hb : 0 ≤ b) (hbp : b < p) : + let r := Real.sqrt (p ^ 2 - b ^ 2) + p * Real.sqrt (1 + (b / r) ^ 2) - (b / r) * b = r := by + dsimp only + let r := Real.sqrt (p ^ 2 - b ^ 2) + have hdiff : 0 < p ^ 2 - b ^ 2 := by + nlinarith [mul_pos (sub_pos.mpr hbp) (show 0 < p + b by linarith)] + have hr : 0 < r := Real.sqrt_pos.2 hdiff + have hrsq : r ^ 2 = p ^ 2 - b ^ 2 := Real.sq_sqrt hdiff.le + have hs : Real.sqrt (1 + (b / r) ^ 2) = p / r := by + apply (Real.sqrt_eq_iff_eq_sq (by positivity) (div_nonneg (hb.trans hbp.le) hr.le)).mpr + field_simp + nlinarith + change p * Real.sqrt (1 + (b / r) ^ 2) - (b / r) * b = r + rw [hs] + field_simp + nlinarith + +/-- Minimize each summand after increasing the rank parameter, then let it decrease to +its original value. This also handles sites with load equal to that parameter. -/ +theorem HeightTest.radicalTest {m : Fin 3 → ℝ} {L : ℝ} (h : HeightTest m L) + (hm : ∀ i, 0 ≤ m i) : RadicalTest m L := by + refine ⟨h.load_le, ?_⟩ + apply le_at_right_endpoint (f := id) (g := fun p => ∑ i, Real.sqrt (p ^ 2 - m i ^ 2)) + continuous_id (by fun_prop) + intro p hp + let a i := m i / Real.sqrt (p ^ 2 - m i ^ 2) + have htest := (h.mono hp.le).nonnegHeights a (fun i => div_nonneg (hm i) (Real.sqrt_nonneg _)) + have hmin : ∀ i, p * Real.sqrt (1 + a i ^ 2) - a i * m i = Real.sqrt (p ^ 2 - m i ^ 2) := + fun i => minimizing_height (hm i) (lt_of_le_of_lt (h.load_le i) hp) + change p ≤ _ + simp only [← hmin, Finset.sum_sub_distrib, ← Finset.mul_sum] + linarith + +/-- The converse variational inequality follows from the two-dimensional Cauchy inequality. -/ +theorem RadicalTest.heightTest {m : Fin 3 → ℝ} {L : ℝ} (h : RadicalTest m L) + (hm : ∀ i, 0 ≤ m i) : HeightTest m L := by + intro a ha + have hL := (hm 0).trans (h.1 0) + have hterm (i) : a i * m i + Real.sqrt (L ^ 2 - m i ^ 2) ≤ + L * Real.sqrt (1 + a i ^ 2) := by + let r := Real.sqrt (L ^ 2 - m i ^ 2) + have hr : r ^ 2 = L ^ 2 - m i ^ 2 := Real.sq_sqrt (by + nlinarith [mul_nonneg (sub_nonneg.mpr (h.1 i)) (add_nonneg hL (hm i))]) + have hs : Real.sqrt (1 + a i ^ 2) ^ 2 = 1 + a i ^ 2 := Real.sq_sqrt (by positivity) + change a i * m i + r ≤ _ + apply le_of_sq_le_sq _ (mul_nonneg hL (Real.sqrt_nonneg _)) + calc + (a i * m i + r) ^ 2 ≤ (a i * m i + r) ^ 2 + (a i * r - m i) ^ 2 + := le_add_of_nonneg_right (sq_nonneg _) + _ = (a i ^ 2 + 1) * (m i ^ 2 + r ^ 2) := by ring + _ = _ := by rw [hr, mul_pow, hs]; ring + have hsum := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hterm i) + rw [Finset.sum_add_distrib, ← Finset.mul_sum] at hsum + linarith [h.2] + +theorem heightTest_iff_radicalTest {m : Fin 3 → ℝ} {L : ℝ} (hm : ∀ i, 0 ≤ m i) : + HeightTest m L ↔ RadicalTest m L := ⟨(·.radicalTest hm), (·.heightTest hm)⟩ + +/-- Replacing log asymptotic rank by the logarithm of a larger rank measure +preserves both inequalities. -/ +theorem RadicalTest.mono {m : Fin 3 → ℝ} {L U : ℝ} (h : RadicalTest m L) + (hm : ∀ i, 0 ≤ m i) (hLU : L ≤ U) : RadicalTest m U := + ((h.heightTest hm).mono hLU).radicalTest hm + +/-- For three equal loads of size two the radical inequality gives the +superquadratic exponent constant. -/ +theorem square_lower_bound {L : ℝ} (h : RadicalTest (fun _ => 2) L) : + 3 / Real.sqrt 2 ≤ L := by + have hL : 2 ≤ L := h.1 0 + have hrad := h.2 + simp only [Fin.sum_univ_three] at hrad + have hsq := Real.sq_sqrt (show 0 ≤ L ^ 2 - 2 ^ 2 by nlinarith [sq_nonneg (L - 2)]) + have h2 : Real.sqrt 2 ^ 2 = 2 := Real.sq_sqrt (by norm_num) + apply (div_le_iff₀ (Real.sqrt_pos.2 (by norm_num))).mpr + apply le_of_sq_le_sq _ (mul_nonneg (by linarith) (Real.sqrt_nonneg _)) + rw [mul_pow, h2] + nlinarith [sq_le_sq' (by linarith [Real.sqrt_nonneg (L ^ 2 - 2 ^ 2)] : + -(3 * Real.sqrt (L ^ 2 - 2 ^ 2)) ≤ L) (by linarith : L ≤ 3 * Real.sqrt (L ^ 2 - 2 ^ 2))] + +theorem loads_nonneg {w12 w23 w31 : ℝ} (h12 : 0 ≤ w12) (h23 : 0 ≤ w23) + (h31 : 0 ≤ w31) (i : Fin 3) : 0 ≤ loads w12 w23 w31 i := by + fin_cases i <;> dsimp [loads] <;> positivity + +/-- The sum of the three wire weights always passes the radical test. -/ +theorem radicalTest_of_totalWireLoad_le {w12 w23 w31 L : ℝ} + (h12 : 0 ≤ w12) (h23 : 0 ≤ w23) (h31 : 0 ≤ w31) (htotal : w12 + w23 + w31 ≤ L) : + RadicalTest (loads w12 w23 w31) L := by + let m := loads w12 w23 w31 + have hbound (i : Fin 3) : m i ≤ L := by fin_cases i <;> dsimp [m, loads] <;> linarith + have hterm (i : Fin 3) : L - m i ≤ Real.sqrt (L ^ 2 - m i ^ 2) := by + apply Real.le_sqrt_of_sq_le + have hprod : 0 ≤ m i * (L - m i) := + mul_nonneg (loads_nonneg h12 h23 h31 i) (sub_nonneg.mpr (hbound i)) + nlinarith + refine ⟨hbound, ?_⟩ + have hsum := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hterm i) + simp only [Fin.sum_univ_three] at hsum ⊢ + dsimp [m, loads] at hsum ⊢ + linarith + +/-- At square order the log-rank bound is proportional to the base-two +logarithm of the order, including order one. -/ +theorem square_log_lower_bound {b L : ℝ} (h : HeightTest (loads b b b) L) : + 3 / Real.sqrt 2 * b ≤ L := by + have h2 : Real.sqrt 2 ^ 2 = 2 := Real.sq_sqrt (by norm_num) + have hden : Real.sqrt (1 + (2 * Real.sqrt 2) ^ 2) = 3 := by + apply (Real.sqrt_eq_iff_eq_sq (by positivity) (by norm_num)).mpr + nlinarith + have hh := h (fun _ => 2 * Real.sqrt 2) (fun _ => by positivity) + simp only [Fin.sum_univ_three, loads, Matrix.cons_val_zero, Matrix.cons_val_one, + Matrix.cons_val_two, hden] at hh + change 2 * Real.sqrt 2 * (b + b) + 2 * Real.sqrt 2 * (b + b) + + 2 * Real.sqrt 2 * (b + b) ≤ L * (3 + 3 + 3 - 1) at hh + have heq : 3 / Real.sqrt 2 = 3 * Real.sqrt 2 / 2 := by + field_simp + nlinarith + rw [heq] + linarith + +/-- A square tensor with the finite height bound at rank measure r has +rank measure at least the stated power of its order. -/ +theorem square_rpow_lower_bound {n r : ℝ} (hn : 0 < n) (hr : 0 < r) + (h : let b := Real.logb 2 n; HeightTest (loads b b b) (Real.logb 2 r)) : + n ^ (3 / Real.sqrt 2) ≤ r := by + apply (Real.logb_le_logb (by norm_num : (1 : ℝ) < 2) (Real.rpow_pos_of_pos hn _) hr).mp + rw [Real.logb_rpow_eq_mul_logb_of_pos hn] + exact square_log_lower_bound h + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/RankCoefficients.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/RankCoefficients.lean new file mode 100644 index 0000000000..df78ad733b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/RankCoefficients.lean @@ -0,0 +1,51 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Tensor +public import Mathlib.FieldTheory.IntermediateField.Adjoin.Basic + +/-! # Finite fields of definition for rank decompositions -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open MatrixMultiplication.Foundation + +section + +/-- A rank decomposition of a finite tensor over an algebraic extension is +already defined over a finite-dimensional intermediate field. -/ +theorem exists_finiteDimensional_rankAtMost {F K X Y Z : Type*} + [Field F] [Field K] [Algebra F K] [Algebra.IsAlgebraic F K] + [Finite X] [Finite Y] [Finite Z] {T : Tensor F X Y Z} {r : ℕ} + (h : Tensor.RankAtMost (fun x y z => algebraMap F K (T x y z)) r) : + ∃ S : IntermediateField F K, FiniteDimensional F S ∧ + Tensor.RankAtMost (fun x y z => algebraMap F S (T x y z)) r := by + rcases h with ⟨a, b, c, h⟩ + let coeff : Fin r × (X ⊕ Y ⊕ Z) → K := + fun p => p.2.elim (a p.1) (Sum.elim (b p.1) (c p.1)) + let S := IntermediateField.adjoin F (Set.range coeff) + have hmem (i : Fin r) (j : X ⊕ Y ⊕ Z) : coeff (i, j) ∈ S := + IntermediateField.subset_adjoin F _ ⟨(i, j), rfl⟩ + refine ⟨S, IntermediateField.finiteDimensional_adjoin + (fun x _ => (Algebra.IsAlgebraic.isAlgebraic (R := F) x).isIntegral), ?_⟩ + refine ⟨fun i x => ⟨a i x, hmem i (.inl x)⟩, + fun i y => ⟨b i y, hmem i (.inr (.inl y))⟩, + fun i z => ⟨c i z, hmem i (.inr (.inr z))⟩, ?_⟩ + funext x y z + apply Subtype.ext + simpa [Tensor.rankOne, IntermediateField.coe_sum] using congrFun (congrFun (congrFun h x) y) z + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/RankLimit.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/RankLimit.lean new file mode 100644 index 0000000000..5be2e0941c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/RankLimit.lean @@ -0,0 +1,122 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Tensor +public import Mathlib.Analysis.Subadditive + +/-! # The limit defining asymptotic tensor rank + +Splitting Kronecker powers gives a submultiplicative sequence of natural +ranks. Applying Fekete's lemma to their logarithms identifies the manuscript's +limit with the infimum of the positive-index rank roots. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +noncomputable section + +open Filter MatrixMultiplication.Foundation +open scoped Topology + +section + +/-- The positive-index root infimum is the limit for a natural-valued +submultiplicative sequence, including sequences with a zero term. -/ +theorem tendsto_root_of_submultiplicative (r : ℕ → ℕ) + (hmul : ∀ m n, r (m + n) ≤ r m * r n) : + Tendsto (fun n : ℕ => (r (n + 1) : ℝ) ^ ((n + 1 : ℝ)⁻¹)) atTop + (𝓝 (⨅ n : ℕ, (r (n + 1) : ℝ) ^ ((n + 1 : ℝ)⁻¹))) := by + let root (n : ℕ) := (r (n + 1) : ℝ) ^ ((n + 1 : ℝ)⁻¹) + change Tendsto root atTop (𝓝 (⨅ n, root n)) + have hnonneg n : 0 ≤ root n := Real.rpow_nonneg (Nat.cast_nonneg _) _ + have hbdd : BddBelow (Set.range root) := by + refine ⟨0, ?_⟩ + rintro _ ⟨n, rfl⟩ + exact hnonneg n + by_cases hz : ∃ k, r k = 0 + · obtain ⟨k, hk⟩ := hz + have heq (n : ℕ) (hn : k ≤ n) : root n = 0 := by + have h := hmul k (n + 1 - k) + rw [show k + (n + 1 - k) = n + 1 by omega, hk, zero_mul, Nat.le_zero] at h + simp [root, h, Real.zero_rpow (by positivity : ((n + 1 : ℝ)⁻¹) ≠ 0)] + have hinf : (⨅ n, root n) = 0 := + le_antisymm ((ciInf_le hbdd k).trans_eq (heq k le_rfl)) (le_ciInf hnonneg) + rw [hinf] + exact tendsto_const_nhds.congr' (eventually_atTop.mpr ⟨k, fun n hn => (heq n hn).symm⟩) + · push Not at hz + have hpos (n : ℕ) : (0 : ℝ) < r n := by exact_mod_cast Nat.pos_of_ne_zero (hz n) + let u (n : ℕ) := Real.log (r n) + have hsub : Subadditive u := by + intro m n + dsimp [u] + rw [← Real.log_mul (hpos m).ne' (hpos n).ne'] + apply Real.log_le_log (hpos _) + exact_mod_cast hmul m n + have hu : BddBelow (Set.range fun n : ℕ => u n / n) := by + refine ⟨0, ?_⟩ + rintro _ ⟨n, rfl⟩ + exact div_nonneg (Real.log_nonneg (by exact_mod_cast Nat.pos_of_ne_zero (hz n))) + (Nat.cast_nonneg _) + have hroot n : root n = Real.exp (u (n + 1) / (n + 1)) := by + dsimp only [root] + rw [Real.rpow_def_of_pos (hpos _)] + rfl + have hlim : Tendsto root atTop (𝓝 (Real.exp hsub.lim)) := by + have h := (Real.continuous_exp.continuousAt.tendsto.comp + ((hsub.tendsto_lim hu).comp (tendsto_add_atTop_nat 1))) + simpa only [Function.comp_def, Nat.cast_add, Nat.cast_one, ← hroot] using h + have hinf : (⨅ n, root n) = Real.exp hsub.lim := by + refine le_antisymm (ge_of_tendsto' hlim (ciInf_le hbdd)) (le_ciInf fun n => ?_) + rw [hroot, Real.exp_le_exp] + simpa only [Nat.cast_succ] using + hsub.lim_le_div hu (Nat.succ_ne_zero n) + rwa [hinf] + +variable {F X Y Z : Type*} [CommSemiring F] [Finite X] [Finite Y] + +private def splitPowerWord {A : Type*} (m n : ℕ) (x : Fin (m + n) → A) : + (Fin m → A) × (Fin n → A) := + (x ∘ Fin.castAdd n, x ∘ Fin.natAdd m) + +/-- Splitting each site's words into a prefix and suffix shows that the +rank of Kronecker powers is submultiplicative. -/ +theorem tensorRank_power_add_le (T : Tensor F X Y Z) (m n : ℕ) : + tensorRank (Tensor.power T (m + n)) ≤ + tensorRank (Tensor.power T m) * tensorRank (Tensor.power T n) := by + have h := ((rankAtMost_tensorRank (Tensor.power T m)).product + (rankAtMost_tensorRank (Tensor.power T n))).pullback + (splitPowerWord m n) (splitPowerWord m n) (splitPowerWord m n) + apply tensorRank_le_of_rankAtMost + have heq : Tensor.power T (m + n) = Tensor.pullback + (splitPowerWord m n) (splitPowerWord m n) (splitPowerWord m n) + (Tensor.product (Tensor.power T m) (Tensor.power T n)) := by + funext x y z + exact Fin.prod_univ_add (fun i => T (x i) (y i) (z i)) + rw [heq] + exact h + +/-- The tensor-power rank roots converge to asymptotic rank. -/ +theorem tendsto_tensorRank_power_root (T : Tensor F X Y Z) : + Tendsto (fun n : ℕ => (tensorRank (Tensor.power T n) : ℝ) ^ ((n : ℝ)⁻¹)) atTop + (𝓝 (asymptoticRank T)) := by + apply (tendsto_add_atTop_iff_nat 1).mp + simpa only [Nat.cast_add, Nat.cast_one, asymptoticRank] using + tendsto_root_of_submultiplicative (fun n => tensorRank (Tensor.power T n)) + (tensorRank_power_add_le T) + +end + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/RectangularCircuitModel.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/RectangularCircuitModel.lean new file mode 100644 index 0000000000..f291c5bed4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/RectangularCircuitModel.lean @@ -0,0 +1,182 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Integral.Model +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.ArithmeticExponent + +/-! # Cost-preserving translation between two division-free circuit models + +The integral model records a set of available polynomials, while the formal +model names registers. Both allow free loads of inputs and field constants. -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication.Arithmetic +open MatrixExponent + +variable {F : Type*} [Field F] {i j k : ℕ} + +private abbrev Inputs (i j k : ℕ) := MatrixInput i k j +private abbrev Poly (F : Type*) [Field F] (i j k : ℕ) := Integral.Poly F i j k + +/-- Reading the registers in order builds their polynomials at the same cost. -/ +private theorem program_build {r : ℕ} (p : Program F (Inputs i j k) r) : + ∃ T, Integral.Build (Integral.initial F i j k) p.cost T ∧ + Integral.initial F i j k ⊆ T ∧ ∀ t, registerPolynomial p t ∈ T := by + induction p with + | nil => exact ⟨_, .nil, Set.Subset.rfl, fun t => t.elim0⟩ + | step p g ih => + obtain ⟨T, build, initial, values⟩ := ih + have step (g : Gate F (Inputs i j k) _) {U : Set (Poly F i j k)} + (h : Integral.Build (Integral.initial F i j k) (p.cost + g.cost) U) + (old : T ⊆ U) (new : gatePolynomial g (registerPolynomial p) ∈ U) : + ∃ V, Integral.Build (Integral.initial F i j k) (p.step g).cost V ∧ + Integral.initial F i j k ⊆ V ∧ ∀ t, registerPolynomial (p.step g) t ∈ V := + ⟨U, h, initial.trans old, Fin.cases new (fun t => old (values t))⟩ + cases g with + | literal c => exact step _ build Set.Subset.rfl (initial (.inl ⟨c, rfl⟩)) + | input x => exact step _ build Set.Subset.rfl (initial (.inr ⟨x, rfl⟩)) + | add x y => + exact step _ (build.add (values x) (values y)) (Set.subset_insert ..) (Set.mem_insert ..) + | sub x y => + exact step _ (build.sub (values x) (values y)) (Set.subset_insert ..) (Set.mem_insert ..) + | mul x y => + exact step _ (build.mul (values x) (values y)) (Set.subset_insert ..) (Set.mem_insert ..) + +/-- A finite selection suffices even when the initially available constants form an infinite set. -/ +private def CanRead (T : Set (Poly F i j k)) (cost : ℕ) : Prop := + ∀ s : Finset (Poly F i j k), (↑s : Set _) ⊆ T → + ∃ (r : ℕ) (p : Program F (Inputs i j k) r), p.cost = cost ∧ + ∀ v ∈ s, ∃ t, registerPolynomial p t = v + +private theorem read_initial : CanRead (Integral.initial F i j k) 0 := by + classical + intro s hs + have load (v : s) : ∃ e : Expression F (Inputs i j k), + e.cost = 0 ∧ expressionPolynomial e = v.val := by + rcases hs v.property with ⟨c, hc⟩ | ⟨x, hx⟩ + · exact ⟨.literal c, rfl, hc⟩ + · exact ⟨.input x, rfl, hx⟩ + choose e cost value using load + let p := Expression.compileFamily e + refine ⟨_, p.program, p.cost_eq.trans (by simp [cost]), ?_⟩ + intro v hv + exact ⟨p.output ⟨v, hv⟩, (registerPolynomial_compileFamily e ⟨v, hv⟩).trans (value ⟨v, hv⟩)⟩ + +private theorem read_binary {T : Set (Poly F i j k)} {m : ℕ} (h : CanRead T m) + {x y : Poly F i j k} (hx : x ∈ T) (hy : y ∈ T) + (op : Poly F i j k → Poly F i j k → Poly F i j k) + (gate : ∀ {r : ℕ}, Fin r → Fin r → Gate F (Inputs i j k) (Fin r)) + (cost : ∀ {r} (a b : Fin r), (gate a b).cost = 1) + (value : ∀ {r} (a b : Fin r) (v : Fin r → Poly F i j k), + gatePolynomial (gate a b) v = op (v a) (v b)) : + CanRead (insert (op x y) T) (m + 1) := by + classical + intro s hs + let need := insert x (insert y (s.erase (op x y))) + have old : (↑need : Set _) ⊆ T := by + intro v hv + simp only [need, Finset.mem_coe, Finset.mem_insert, Finset.mem_erase] at hv + rcases hv with rfl | rfl | ⟨hne, hin⟩ + · exact hx + · exact hy + · exact (hs hin).resolve_left hne + obtain ⟨r, p, hp, read⟩ := h need old + obtain ⟨a, ha⟩ := read x (by simp [need]) + obtain ⟨b, hb⟩ := read y (by simp [need]) + refine ⟨_, p.step (gate a b), by simp [hp, cost], ?_⟩ + intro v hv + by_cases he : v = op x y + · exact ⟨0, by rw [registerPolynomial_zero, value, ha, hb, he]⟩ + · obtain ⟨t, ht⟩ := read v (by simp [need, he, hv]) + exact ⟨t.succ, ht⟩ + +private theorem read_build {T : Set (Poly F i j k)} {m : ℕ} + (h : Integral.Build (Integral.initial F i j k) m T) : CanRead T m := by + induction h with + | nil => exact read_initial + | add _ hx hy ih => + exact read_binary ih hx hy (· + ·) Gate.add (fun _ _ => rfl) (fun _ _ _ => rfl) + | sub _ hx hy ih => + exact read_binary ih hx hy (· - ·) Gate.sub (fun _ _ => rfl) (fun _ _ _ => rfl) + | mul _ hx hy ih => + exact read_binary ih hx hy (· * ·) Gate.mul (fun _ _ => rfl) (fun _ _ _ => rfl) + +/-- Integral circuits order dimensions as rows, columns, inner dimension. -/ +private theorem computes_iff {m : ℕ} : Integral.Computes F i j k m ↔ + ∃ p : MatrixAlgorithm F i k j, FormalCorrect p ∧ p.cost = m := by + classical + constructor + · rintro ⟨T, h, out⟩ + let s := Finset.univ.image (Integral.output F (i := i) (j := j) (k := k)) + obtain ⟨r, p, hp, read⟩ := read_build h s (by + rintro v hv + obtain ⟨q, _, rfl⟩ := Finset.mem_image.mp hv + exact out q) + have entry (q : Integral.Pos i j) := + read (Integral.output F q) (Finset.mem_image_of_mem _ (Finset.mem_univ q)) + choose idx hidx using entry + exact ⟨⟨r, p, fun a b => idx (a, b)⟩, fun a b => hidx (a, b), hp⟩ + · rintro ⟨p, correct, rfl⟩ + obtain ⟨T, build, _, read⟩ := program_build p.program + refine ⟨T, build, fun q => ?_⟩ + have eq : registerPolynomial p.program (p.output q.1 q.2) = Integral.output F q := + correct q.1 q.2 + rw [← eq] + exact read (p.output q.1 q.2) + +/-- The admissible exponents agree after translating wire order to matrix dimensions. -/ +theorem formalOmega_eq_integral (F : Type*) [Field F] (a b c : ℝ) : + formalOmega F a b c = Integral.exponent F c b a := by + unfold formalOmega Integral.exponent + congr 1 + ext τ + change FormalAdmissibleExponent F a b c τ ↔ Integral.Admissible F c b a τ + constructor + · intro h ε hε + obtain ⟨C, hC, bound⟩ := h ε hε + refine ⟨C, hC, fun n hn => ?_⟩ + obtain ⟨p, correct, cost⟩ := bound n hn + exact ⟨p.cost, computes_iff.mpr ⟨p, correct, rfl⟩, cost⟩ + · intro h ε hε + obtain ⟨C, hC, bound⟩ := h ε hε + refine ⟨C, hC, fun n hn => ?_⟩ + obtain ⟨m, hm, cost⟩ := bound n hn + obtain ⟨p, correct, rfl⟩ := computes_iff.mp hm + exact ⟨p, correct, cost⟩ + +private theorem wireDimension_max_zero {n : ℕ} (hn : 1 ≤ n) (w : ℝ) : + wireDimension n (max w 0) = wireDimension n w := by + rcases le_total 0 w with hw | hw + · rw [max_eq_left hw] + rw [max_eq_right hw] + have hn' : (1 : ℝ) ≤ n := by exact_mod_cast hn + simp only [wireDimension, Real.rpow_zero, Nat.ceil_one] + apply Nat.le_antisymm (Nat.ceil_pos.mpr (Real.rpow_pos_of_pos (by positivity) _)) + apply Nat.ceil_le.mpr + simpa using Real.rpow_le_rpow_of_exponent_le hn' hw + +/-- Negative weights and zero give the same rounded dimension at every admissible scale. -/ +theorem formalOmega_max_zero (F : Type*) [Field F] (a b c : ℝ) : + formalOmega F a b c = formalOmega F (max a 0) (max b 0) (max c 0) := by + unfold formalOmega + congr 1 + ext τ + change FormalAdmissibleExponent F a b c τ ↔ + FormalAdmissibleExponent F (max a 0) (max b 0) (max c 0) τ + constructor <;> intro h ε hε <;> obtain ⟨C, hC, bound⟩ := h ε hε <;> + refine ⟨C, hC, fun n hn => ?_⟩ + · rw [wireDimension_max_zero hn a, wireDimension_max_zero hn b, wireDimension_max_zero hn c] + exact bound n hn + · have hp := bound n hn + rw [wireDimension_max_zero hn a, wireDimension_max_zero hn b, wireDimension_max_zero hn c] at hp + exact hp + +end MatrixMultiplicationAllFields.SpectralBooks diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Scaling.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Scaling.lean new file mode 100644 index 0000000000..5f174eb2ac --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Scaling.lean @@ -0,0 +1,84 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.Floor.Ring +public import Mathlib.Analysis.SpecialFunctions.Log.Base +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.NormNum +public import Mathlib.Tactic.Positivity + +/-! # Logarithmic scaling of rectangular wire dimensions -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open Filter +open scoped Topology + +noncomputable section + +/-- The integer wire dimension at scale `N` and weight `w`. -/ +def wireDimension (N : ℕ) (w : ℝ) : ℕ := ⌈(N : ℝ) ^ w⌉₊ + +theorem wireDimension_pos {N : ℕ} (hN : 0 < N) (w : ℝ) : 0 < wireDimension N w := by + exact Nat.ceil_pos.mpr (Real.rpow_pos_of_pos (by exact_mod_cast hN) _) + +theorem wireDimension_log_ge {N : ℕ} (hN : 0 < N) (w : ℝ) : + w * Real.logb 2 N ≤ Real.logb 2 (wireDimension N w) := by + have h : 0 < (N : ℝ) := by exact_mod_cast hN + rw [← Real.logb_rpow_eq_mul_logb_of_pos h] + exact Real.logb_le_logb_of_le (by norm_num) (Real.rpow_pos_of_pos h w) (Nat.le_ceil _) + +theorem dyadic_wireDimension_log_ge (k : ℕ) (w : ℝ) : + (k : ℝ) * w ≤ Real.logb 2 (wireDimension (2 ^ k) w) := by + have h := wireDimension_log_ge (N := 2 ^ k) (by positivity) w + push_cast at h + rw [Real.logb_pow, Real.logb_self_eq_one (by norm_num), mul_one, mul_comm] at h + exact h + +/-- For positive scales and nonnegative weights, rounding costs a factor of at most two. -/ +theorem wireDimension_le {N : ℕ} (hN : 1 ≤ N) {w : ℝ} (hw : 0 ≤ w) : + (wireDimension N w : ℝ) ≤ 2 * (N : ℝ) ^ w := by + have hp : 1 ≤ (N : ℝ) ^ w := Real.one_le_rpow (by exact_mod_cast hN) hw + unfold wireDimension + linarith [Nat.ceil_lt_add_one (zero_le_one.trans hp)] + +/-- Rounding a wire dimension up adds at most one bit for nonnegative weights. -/ +theorem wireDimension_log_le {N : ℕ} (hN : 0 < N) {w : ℝ} (hw : 0 ≤ w) : + Real.logb 2 (wireDimension N w) ≤ 1 + w * Real.logb 2 N := by + calc + _ ≤ Real.logb 2 (2 * (N : ℝ) ^ w) := + Real.logb_le_logb_of_le (by norm_num) (by exact_mod_cast wireDimension_pos hN w) + (wireDimension_le hN hw) + _ = _ := by rw [Real.logb_mul (by norm_num) (by positivity), + Real.logb_self_eq_one (by norm_num), Real.logb_rpow_eq_mul_logb_of_pos (by positivity)] + +/-- The normalized logarithmic dimension converges to the wire weight. -/ +theorem tendsto_log_wireDimension_div {w : ℝ} (hw : 0 ≤ w) : + Tendsto (fun N : ℕ ↦ Real.logb 2 (wireDimension N w) / Real.logb 2 N) atTop (𝓝 w) := by + have ht : Tendsto (fun N : ℕ ↦ (Real.logb 2 N)⁻¹) atTop (𝓝 0) := + tendsto_inv_atTop_zero.comp ((Real.tendsto_logb_atTop (by norm_num)).comp + tendsto_natCast_atTop_atTop) + apply tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds + (show Tendsto (fun N : ℕ ↦ (Real.logb 2 N)⁻¹ + w) atTop (𝓝 w) by + simpa using ht.add_const w) + · filter_upwards [eventually_gt_atTop 1] with N hN + have hd := Real.logb_pos (b := 2) (by norm_num) (x := (N : ℝ)) (by exact_mod_cast hN) + exact (le_div_iff₀ hd).mpr (wireDimension_log_ge (by omega) w) + · filter_upwards [eventually_gt_atTop 1] with N hN + have hd := Real.logb_pos (b := 2) (by norm_num) (x := (N : ℝ)) (by exact_mod_cast hN) + apply (div_le_iff₀ hd).mpr + rw [add_mul, inv_mul_cancel₀ hd.ne'] + exact wireDimension_log_le (by omega) hw + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/SquareExponent.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/SquareExponent.lean new file mode 100644 index 0000000000..9c1dcb5155 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/SquareExponent.lean @@ -0,0 +1,110 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.FormalRecursion +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.AbsoluteTensorRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.MatrixPower + +/-! # Tensor powers and the square arithmetic exponent -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +open Foundation Filter +open scoped Topology + +noncomputable section + +/-- Polynomial rank growth at unit wire weights bounds the asymptotic rank of +each fixed square format, after taking roots along tensor powers. -/ +theorem square_asymptoticRank_le_of_rank_growth (F : Type*) [Field F] {n : ℕ} (hn : 0 < n) + {ω : ℝ} (hgrowth : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ ∀ N : ℕ, 1 ≤ N → + (tensorRank (matrixTensor F (wireDimension N 1) (wireDimension N 1) (wireDimension N 1)) : ℝ) + ≤ C * (N : ℝ) ^ (ω + ε)) : + asymptoticRank (matrixTensor F n n n) ≤ (n : ℝ) ^ ω := by + have hn' : (n : ℝ) ≠ 0 := by positivity + have hcont : Continuous fun ε : ℝ => (n : ℝ) ^ (ω + ε) := + (Real.continuous_const_rpow hn').comp (continuous_const.add continuous_id) + have hlim : Tendsto (fun ε : ℝ => (n : ℝ) ^ (ω + ε)) (𝓝[>] 0) (𝓝 ((n : ℝ) ^ ω)) := by + simpa using (hcont.continuousAt (x := 0) |>.continuousWithinAt (s := Set.Ioi 0)).tendsto + apply ge_of_tendsto hlim + filter_upwards [self_mem_nhdsWithin] with ε hε + obtain ⟨C, hC, hbound⟩ := hgrowth ε hε + let r := (n : ℝ) ^ (ω + ε) + have wd (N : ℕ) : wireDimension N 1 = N := by simp [wireDimension] + have hr : 0 ≤ r := Real.rpow_nonneg (Nat.cast_nonneg _) _ + have hroot : Tendsto (fun k : ℕ => C ^ ((k : ℝ)⁻¹)) atTop (𝓝 1) := by + simpa only [Real.rpow_zero, Function.comp_def] using + (Real.continuousAt_const_rpow (a := C) (b := 0) hC.ne').tendsto.comp + (tendsto_inv_atTop_zero.comp tendsto_natCast_atTop_atTop) + apply le_of_tendsto_of_tendsto (tendsto_tensorRank_power_root _) + (show Tendsto (fun k : ℕ => C ^ ((k : ℝ)⁻¹) * r) atTop (𝓝 r) by simpa using hroot.mul_const r) + filter_upwards [eventually_ne_atTop (0 : ℕ)] with k hk + have hg : (tensorRank (Tensor.power (matrixTensor F n n n) k) : ℝ) ≤ C * r ^ k := by + rw [tensorRank_matrixTensor_power] + have hb := hbound (n ^ k) (Nat.one_le_pow _ _ hn) + rw [wd] at hb + simpa only [Nat.cast_pow, + ← Real.rpow_natCast_mul (Nat.cast_nonneg n), mul_comm (k : ℝ), Real.rpow_mul_natCast + (Nat.cast_nonneg n)] using hb + calc + _ ≤ (C * r ^ k) ^ ((k : ℝ)⁻¹) := Real.rpow_le_rpow (by positivity) hg (by positivity) + _ = _ := by rw [Real.mul_rpow hC.le (pow_nonneg hr _), Real.pow_rpow_inv_natCast hr hk] + +/-- Formal square circuits bound asymptotic rank over their ground field. -/ +theorem square_asymptoticRank_le_rpow_formalOmega (F : Type*) [Field F] {n : ℕ} (hn : 0 < n) : + asymptoticRank (matrixTensor F n n n) ≤ (n : ℝ) ^ formalOmega F 1 1 1 := + square_asymptoticRank_le_of_rank_growth F hn + (formalOmega_admissible F (by norm_num) (by norm_num) (by norm_num)).rank_growth + +/-- A uniform bound on the exponent from each finite square rank formula also holds +for the asymptotic rank, by applying it at each power of the fixed order. -/ +theorem rpow_formalOmega_le_asymptoticRank (F : Type*) [Field F] {n : ℕ} (hn : 2 ≤ n) : + (n : ℝ) ^ formalOmega F 1 1 1 ≤ asymptoticRank (matrixTensor F n n n) := by + apply le_ciInf + intro k + rw [tensorRank_matrixTensor_power] + apply (Real.le_rpow_inv_iff_of_pos (by positivity) (by positivity) + (show 0 < (k : ℝ) + 1 by positivity)).mpr + rw [← Nat.cast_succ, Real.rpow_natCast, Real.rpow_pow_comm (Nat.cast_nonneg n), ← Nat.cast_pow] + apply rpow_formalOmega_le_tensorRank + exact hn.trans (le_self_pow (by omega) (by omega)) + +/-- At every square order at least two, asymptotic rank equals the order +raised to the formal arithmetic exponent over the same field. -/ +theorem square_asymptoticRank_eq_rpow_formalOmega (F : Type*) [Field F] {n : ℕ} (hn : 2 ≤ n) : + asymptoticRank (matrixTensor F n n n) = (n : ℝ) ^ formalOmega F 1 1 1 := + le_antisymm (square_asymptoticRank_le_rpow_formalOmega F (by omega)) + (rpow_formalOmega_le_asymptoticRank F hn) + +/-- The square arithmetic exponent, defined by formal identities, depends only +on the characteristic of the field. -/ +theorem formalOmega_square_eq_of_ringChar_eq (F E : Type*) [Field F] [Field E] + (hchar : ringChar F = ringChar E) : formalOmega F 1 1 1 = formalOmega E 1 1 1 := by + have h := asymptoticRank_matrixTensor_eq_of_ringChar_eq F E hchar 2 2 2 + rw [square_asymptoticRank_eq_rpow_formalOmega F (by decide), + square_asymptoticRank_eq_rpow_formalOmega E (by decide)] at h + exact (Real.rpow_right_inj (by norm_num) (by norm_num)).mp h + +/-- The finite asymptotic-rank radical inequality at order two alone would force +the superquadratic arithmetic lower bound over the same field. -/ +theorem formalOmega_square_lower_bound_of_order_two (F : Type*) [Field F] + (h : RadicalTest (fun _ => 2) (Real.logb 2 (asymptoticRank (matrixTensor F 2 2 2)))) : + 3 / Real.sqrt 2 ≤ formalOmega F 1 1 1 := by + rw [square_asymptoticRank_eq_rpow_formalOmega F (by decide), Nat.cast_ofNat, + Real.logb_rpow (by norm_num) (by norm_num)] at h + exact square_lower_bound h + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/SquareRankModel.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/SquareRankModel.lean new file mode 100644 index 0000000000..ac07d41e31 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/SquareRankModel.lean @@ -0,0 +1,64 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.FieldExtension +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.SquareExponent + +/-! # Square tensor rank in the rational and division-free circuit models -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +/-- The output coordinates in a circuit are (row, column). In the cyclic tensor they are +(column, row). Swapping the last two indices identifies the two rank decompositions. -/ +private theorem square_rank_iff {F : Type*} [Field F] {n r : ℕ} : + MatrixExponent.RankLE F n r ↔ Tensor.RankAtMost (matrixTensor F n n n) r := by + constructor + · rintro ⟨a, b, c, h⟩ + refine ⟨a, b, fun i z => c i z.swap, ?_⟩ + funext x y z + simpa [matrixTensor, Tensor.matrixCoefficients, Tensor.rankOne, and_comm, and_left_comm, + eq_comm] using (h x y z.swap).symm + · rintro ⟨a, b, c, h⟩ + refine ⟨a, b, fun i z => c i z.swap, ?_⟩ + intro x y z + simpa [matrixTensor, Tensor.matrixCoefficients, Tensor.rankOne, and_comm, and_left_comm, + eq_comm] using (congrFun (congrFun (congrFun h x) y) z.swap).symm + +private theorem rpow_omega_le_asymptoticRank (F : Type*) [Field F] {n : ℕ} (hn : 2 ≤ n) : + (n : ℝ) ^ MatrixExponent.omega F ≤ asymptoticRank (matrixTensor F n n n) := by + apply le_ciInf + intro k + rw [tensorRank_matrixTensor_power] + apply (Real.le_rpow_inv_iff_of_pos (by positivity) (by positivity) + (show 0 < (k : ℝ) + 1 by positivity)).mpr + rw [← Nat.cast_succ, Real.rpow_natCast, Real.rpow_pow_comm (Nat.cast_nonneg n), ← Nat.cast_pow] + by_contra! h + let m := n ^ (k + 1) + have hr := square_rank_iff.mpr (rankAtMost_tensorRank (matrixTensor F m m m)) + exact (lt_irrefl (MatrixExponent.omega F)) (MatrixExponent.omega_lt_of_rank + (hn.trans (le_self_pow (by omega) (by omega))) hr h) + +/-- Finite square tensor ranks determine the same exponent for both circuit models. -/ +theorem formalOmega_square_eq_omega (F : Type*) [Field F] : + formalOmega F 1 1 1 = MatrixExponent.omega F := by + apply le_antisymm + · by_contra! h + obtain ⟨n, r, hn, rank, small⟩ := MatrixExponent.omega_lt_iff_rank.mp h + have le := tensorRank_le_of_rankAtMost (square_rank_iff.mp rank) + exact (not_lt_of_ge ((rpow_formalOmega_le_tensorRank F hn).trans (Nat.cast_le.mpr le))) small + · have h := rpow_omega_le_asymptoticRank F (n := 2) (by decide) + rw [square_asymptoticRank_eq_rpow_formalOmega F (by decide)] at h + exact (Real.rpow_le_rpow_left_iff (by norm_num : (1 : ℝ) < (2 : ℕ))).mp h + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Tensor.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Tensor.lean new file mode 100644 index 0000000000..92294396c1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/SpectralBooks/Tensor.lean @@ -0,0 +1,98 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexMatrixTensor +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Analysis.SpecialFunctions.Pow.Real + +/-! +# Rectangular matrix multiplication tensors + +We use the finite coefficient tensors and Kronecker powers from the matrix +multiplication library. The dimensions are the shared wire sizes, in the +cyclic order `12, 23, 31`. The first site's coordinates are consequently +indexed by `Fin n31 × Fin n12`. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields +namespace SpectralBooks + +open MatrixMultiplicationAllFields.MatrixMultiplication + +noncomputable section + +open MatrixMultiplication.Foundation +open scoped BigOperators + +section + +section Rank + +variable {F X Y Z : Type*} [CommSemiring F] [Finite X] [Finite Y] + +/-- Expanding in the coordinate bases of the first two sites gives a finite +decomposition into simple tensors. -/ +theorem exists_rankAtMost (T : Tensor F X Y Z) : + ∃ r, Tensor.RankAtMost T r := by + classical + let : Fintype X := Fintype.ofFinite X + let : Fintype Y := Fintype.ofFinite Y + let a : X × Y → X → F := fun p x => if p.1 = x then 1 else 0 + let b : X × Y → Y → F := fun p y => if p.2 = y then 1 else 0 + let c : X × Y → Z → F := fun p => T p.1 p.2 + refine ⟨Fintype.card (X × Y), ?_⟩ + have h : T = fun x y z => ∑ p, Tensor.rankOne (a p) (b p) (c p) x y z := by + funext x y z + simp [a, b, c, Tensor.rankOne, Fintype.sum_prod_type, ite_mul, mul_ite] + rw [h] + exact Tensor.rankAtMost_sum_rankOne a b c + +/-- The least number of simple tensors in a decomposition over the coefficient semiring. -/ +def tensorRank (T : Tensor F X Y Z) : ℕ := by + classical + exact Nat.find (exists_rankAtMost T) + +theorem rankAtMost_tensorRank (T : Tensor F X Y Z) : Tensor.RankAtMost T (tensorRank T) := by + classical + exact Nat.find_spec (exists_rankAtMost T) + +theorem tensorRank_le_of_rankAtMost {T : Tensor F X Y Z} {r : ℕ} + (h : Tensor.RankAtMost T r) : tensorRank T ≤ r := by + classical + exact Nat.find_min' (exists_rankAtMost T) h + +/-- The infimum of the positive tensor-power rank roots. -/ +def asymptoticRank (T : Tensor F X Y Z) : ℝ := + ⨅ n : ℕ, (tensorRank (Tensor.power T (n + 1)) : ℝ) ^ ((n + 1 : ℝ)⁻¹) + +theorem asymptoticRank_nonneg (T : Tensor F X Y Z) : 0 ≤ asymptoticRank T := + le_ciInf (fun _ => Real.rpow_nonneg (Nat.cast_nonneg _) _) + +theorem asymptoticRank_le_tensorRank (T : Tensor F X Y Z) : + asymptoticRank T ≤ tensorRank T := by + have hu := ciInf_le ⟨(0 : ℝ), by rintro _ ⟨n, rfl⟩; positivity⟩ (0 : ℕ) + (f := fun n : ℕ => (tensorRank (Tensor.power T (n + 1)) : ℝ) ^ ((n + 1 : ℝ)⁻¹)) + have h₁ := tensorRank_le_of_rankAtMost ((rankAtMost_tensorRank T).power 1) + simp only [pow_one] at h₁ + apply le_trans _ (Nat.cast_le (α := ℝ) |>.mpr h₁) + simpa [asymptoticRank] using hu + +end Rank + +/-- The coefficient of the cyclic pattern `e_{ki} ⊗ e_{ij} ⊗ e_{jk}` is one. -/ +abbrev matrixTensor (F : Type*) [CommSemiring F] (n12 n23 n31 : ℕ) := + Tensor.matrixCoefficients (K := F) (Fin n31) (Fin n12) (Fin n23) + +end + +end + +end SpectralBooks +end MatrixMultiplicationAllFields diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/Catalyst.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/Catalyst.lean new file mode 100644 index 0000000000..27be2001a1 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/Catalyst.lean @@ -0,0 +1,150 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.Ring +public import Lean.Elab.Tactic.Omega + +/-! +# Catalysts in the additive-state obstruction + +All comparisons retain the catalyst. In particular the multiplicative induction +below keeps a single copy of `s`; it neither cancels `s` nor substitutes `s^j`. +The hypotheses are elementary ordered-semiring laws, to be instantiated by the +concrete tensor restriction semiring. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +/-- The stable equality supplied by a cleared finite additive certificate. -/ +def StableEquality (a b : S) : Prop := ∃ c : S, a + c = b + c + +omit [PartialOrder S] in +theorem StableEquality.refl (a : S) : StableEquality a a := ⟨0, rfl⟩ + +omit [PartialOrder S] in +theorem StableEquality.symm {a b : S} (h : StableEquality a b) : + StableEquality b a := by + obtain ⟨c, hc⟩ := h + exact ⟨c, hc.symm⟩ + +omit [PartialOrder S] in +theorem StableEquality.trans {a b c : S} + (hab : StableEquality a b) (hbc : StableEquality b c) : + StableEquality a c := by + obtain ⟨u, hu⟩ := hab + obtain ⟨v, hv⟩ := hbc + refine ⟨u + v, ?_⟩ + calc + a + (u + v) = (a + u) + v := by ring + _ = (b + u) + v := by rw [hu] + _ = (b + v) + u := by ring + _ = (c + v) + u := by rw [hv] + _ = c + (u + v) := by ring + +omit [PartialOrder S] in +theorem StableEquality.add {a b c d : S} + (hab : StableEquality a b) (hcd : StableEquality c d) : + StableEquality (a + c) (b + d) := by + obtain ⟨u, hu⟩ := hab + obtain ⟨v, hv⟩ := hcd + refine ⟨u + v, ?_⟩ + calc + a + c + (u + v) = (a + u) + (c + v) := by ring + _ = (b + u) + (d + v) := by rw [hu, hv] + _ = b + d + (u + v) := by ring + +theorem stable_certificate_to_catalyst + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + {m k : ℕ} {T s x y : S} (hxy : x ≤ y) + (hstable : StableEquality ((m : S) + y + T * s) (x + (k : S) * s)) : + ∃ D : S, D + (m : S) + T * s ≤ D + (k : S) * s := by + obtain ⟨c, hc⟩ := hstable + refine ⟨y + c, ?_⟩ + calc + y + c + (m : S) + T * s = ((m : S) + y + T * s) + c := by ring + _ = (x + (k : S) * s) + c := hc + _ = x + ((k : S) * s + c) := by ring + _ ≤ y + ((k : S) * s + c) := hadd _ _ _ hxy + _ = y + c + (k : S) * s := by ring + +omit [PartialOrder S] in +theorem additiveMap_natCast (F : S →+ ℕ) (hF : F 1 = 1) (n : ℕ) : + F (n : S) = n := by + induction n with + | zero => simp only [Nat.cast_zero, F.map_zero] + | succ n ih => rw [Nat.cast_succ, F.map_add, ih, hF] + +/-- Additive flattening rank, not ordinary tensor rank, rules out `s = 0`. -/ +theorem catalyst_nonzero (F : S →+ ℕ) (hF : F 1 = 1) (hmono : Monotone F) + {D T s : S} {m k : ℕ} (hm : 0 < m) + (h : D + (m : S) + T * s ≤ D + (k : S) * s) : s ≠ 0 := by + intro hs + subst s + have h' := hmono h + simp only [mul_zero, add_zero, F.map_add, additiveMap_natCast F hF] at h' + omega + +/-- Additive iteration retains one fixed `D`, while both gains scale with `n`. -/ +theorem catalyst_additive_iteration + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + {D T s : S} {m k : ℕ} + (h : D + (m : S) + T * s ≤ D + (k : S) * s) (n : ℕ) : + D + (n : S) * (m : S) + (n : S) * (T * s) ≤ + D + (n : S) * ((k : S) * s) := by + induction n with + | zero => simp only [Nat.cast_zero, zero_mul, add_zero, le_refl] + | succ n ih => + rw [Nat.cast_succ] + calc + D + ((n : S) + 1) * (m : S) + ((n : S) + 1) * (T * s) = + (D + (m : S) + T * s) + ((n : S) * (m : S) + (n : S) * (T * s)) := by ring + _ ≤ (D + (k : S) * s) + ((n : S) * (m : S) + (n : S) * (T * s)) := + hadd _ _ _ h + _ = (D + (n : S) * (m : S) + (n : S) * (T * s)) + (k : S) * s := by ring + _ ≤ (D + (n : S) * ((k : S) * s)) + (k : S) * s := hadd _ _ _ ih + _ = D + ((n : S) + 1) * ((k : S) * s) := by ring + +/-- Absorb the fixed catalyst using its rank bound and `1 ≤ s`. -/ +theorem catalyst_absorbed_comparison + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + (hmul : ∀ a b c : S, a ≤ b → c * a ≤ c * b) + (hzero : ∀ a : S, 0 ≤ a) + {D T s : S} {m k r : ℕ} (hD : D ≤ (r : S)) (hs : 1 ≤ s) + (h : D + (m : S) + T * s ≤ D + (k : S) * s) (n : ℕ) : + (n : S) * T * s ≤ ((n * k + r : ℕ) : S) * s := by + have hDs : D ≤ (r : S) * s := + hD.trans (by simpa only [mul_one] using hmul 1 s (r : S) hs) + calc + (n : S) * T * s = 0 + ((n : S) * (T * s)) := by ring + _ ≤ (D + (n : S) * (m : S)) + ((n : S) * (T * s)) := + hadd _ _ _ (hzero _) + _ ≤ D + (n : S) * ((k : S) * s) := catalyst_additive_iteration hadd h n + _ ≤ (r : S) * s + (n : S) * ((k : S) * s) := hadd _ _ _ hDs + _ = ((n * k + r : ℕ) : S) * s := by rw [Nat.cast_add, Nat.cast_mul]; ring + +/-- Iteration of a catalytic multiplicative comparison does not cancel the tensor. -/ +theorem catalytic_power_iteration + (hmul : ∀ a b c : S, a ≤ b → c * a ≤ c * b) + {a b s : S} (h : b * s ≤ a * s) (j : ℕ) : + b ^ j * s ≤ a ^ j * s := by + induction j with + | zero => simp only [pow_zero, one_mul, le_refl] + | succ j ih => + calc + b ^ (j + 1) * s = b ^ j * (b * s) := by ring + _ ≤ b ^ j * (a * s) := hmul _ _ _ h + _ = a * (b ^ j * s) := by ring + _ ≤ a * (a ^ j * s) := hmul _ _ _ ih + _ = a ^ (j + 1) * s := by ring + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/Finite.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/Finite.lean new file mode 100644 index 0000000000..beb43d3d50 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/Finite.lean @@ -0,0 +1,82 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Additive.States +public import Mathlib.Data.Finset.Union +public import Mathlib.Tactic.Positivity + +/-! The compactness obstruction can be restricted to finitely many coordinates, +including the unit. Outside those coordinates, zero is a valid box coordinate. +This is the concrete finite-dimensional input to rational linear elimination. -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open Set + +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +/-- The semiring elements whose assigned values occur in the constraint. -/ +noncomputable def StateConstraint.coordinates (T : S) : StateConstraint S → Finset S := by + classical + exact fun c => match c with + | .zero => {0} + | .one => {1} + | .add x y => {x + y, x, y} + | .order x y _ => {x, y} + | .detect s => {T * s, s} + +theorem StateConstraint.holds_congr (T : S) (k : ℕ) (c : StateConstraint S) + {f g : S → ℝ} (h : ∀ x ∈ c.coordinates T, f x = g x) : + c.Holds T k f ↔ c.Holds T k g := by + classical + cases c with + | zero => simp only [StateConstraint.Holds, h 0 (by simp [StateConstraint.coordinates])] + | one => simp only [StateConstraint.Holds, h 1 (by simp [StateConstraint.coordinates])] + | add x y => + simp only [StateConstraint.Holds, h (x + y) (by simp [StateConstraint.coordinates]), + h x (by simp [StateConstraint.coordinates]), h y (by simp [StateConstraint.coordinates])] + | order x y hxy => + simp only [StateConstraint.Holds, h x (by simp [StateConstraint.coordinates]), + h y (by simp [StateConstraint.coordinates])] + | detect s => + simp only [StateConstraint.Holds, h (T * s) (by simp [StateConstraint.coordinates]), + h s (by simp [StateConstraint.coordinates])] + +/-- A finite obstruction includes only these coordinate bounds; no infinite +system is passed silently to the finite rational cone theorem. -/ +theorem finite_coordinate_obstruction (T : S) (k : ℕ) (R : S → ℕ) + (hnone : stateSet T k = ∅) : + ∃ (F : Finset (StateConstraint S)) (U : Finset S), + 0 ∈ U ∧ 1 ∈ U ∧ + (∀ c ∈ F, c.coordinates T ⊆ U) ∧ + ¬ ∃ f : S → ℝ, (∀ s ∈ U, f s ∈ Icc 0 (R s : ℝ)) ∧ + ∀ c ∈ F, c.Holds T k f := by + classical + obtain ⟨F, hF⟩ := finite_inconsistent_subsystem T k R hnone + let U : Finset S := {0, 1} ∪ F.biUnion (fun c => c.coordinates T) + have hsub : ∀ c ∈ F, c.coordinates T ⊆ U := by + intro c hc x hx + exact Finset.mem_union.mpr (Or.inr (Finset.mem_biUnion.mpr ⟨c, hc, hx⟩)) + refine ⟨F, U, by simp [U], by simp [U], hsub, ?_⟩ + rintro ⟨f, hbox, hconstraints⟩ + let g : S → ℝ := fun s => if s ∈ U then f s else 0 + apply hF + refine ⟨g, ?_, ?_⟩ + · intro s + by_cases hs : s ∈ U + · simpa only [g, ite_eq_left hs] using hbox s hs + · simp only [g, ite_eq_right hs, mem_Icc, le_refl, true_and] + positivity + · intro c hc + apply (c.holds_congr T k (f := f) (g := g) ?_).mp (hconstraints c hc) + intro x hx + simp only [g, ite_eq_left (hsub c hc hx)] + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/RankAnalysis.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/RankAnalysis.lean new file mode 100644 index 0000000000..f72de80c0b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/RankAnalysis.lean @@ -0,0 +1,98 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Order.ConditionallyCompleteLattice.Basic +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.NormNum +public import Lean.Elab.Tactic.Omega +public import Mathlib.Tactic.Positivity + +/-! Infimum lemmas for the exact rank exponent. The concrete definition in +`RankExponent` uses the actual rank of square complex matrix tensors. -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +/-- The logarithmic rank ratios `log (R d) / log d` for integer sizes `d ≥ 2`. -/ +def rankExponentSet (R : ℕ → ℕ) : Set ℝ := + {q | ∃ d : ℕ, 2 ≤ d ∧ q = Real.log (R d : ℝ) / Real.log (d : ℝ)} + +/-- The infimum of the logarithmic rank ratios over sizes at least two. -/ +noncomputable def rankExponent (R : ℕ → ℕ) : ℝ := sInf (rankExponentSet R) + +theorem rankExponentSet_nonempty (R : ℕ → ℕ) : (rankExponentSet R).Nonempty := + ⟨_, 2, le_rfl, rfl⟩ + +theorem two_le_logRank {R : ℕ → ℕ} (hR : ∀ d, d ^ 2 ≤ R d) + {d : ℕ} (hd : 2 ≤ d) : + (2 : ℝ) ≤ Real.log (R d : ℝ) / Real.log (d : ℝ) := by + have hd1 : (1 : ℝ) < d := by exact_mod_cast (show 1 < d by omega) + have hd0 : (0 : ℝ) < d := lt_trans zero_lt_one hd1 + have hbound : (d : ℝ) ^ 2 ≤ R d := by exact_mod_cast hR d + have hlog := Real.log_le_log (pow_pos hd0 2) hbound + rw [Real.log_pow] at hlog + exact (le_div_iff₀ (Real.log_pos hd1)).mpr (by simpa using hlog) + +theorem rankExponentSet_bddBelow {R : ℕ → ℕ} (hR : ∀ d, d ^ 2 ≤ R d) : + BddBelow (rankExponentSet R) := by + refine ⟨2, ?_⟩ + rintro _ ⟨d, hd, rfl⟩ + exact two_le_logRank hR hd + +theorem two_le_rankExponent {R : ℕ → ℕ} (hR : ∀ d, d ^ 2 ≤ R d) : + 2 ≤ rankExponent R := by + apply le_csInf (rankExponentSet_nonempty R) + rintro _ ⟨d, hd, rfl⟩ + exact two_le_logRank hR hd + +theorem rankExponent_le_logRank {R : ℕ → ℕ} (hR : ∀ d, d ^ 2 ≤ R d) + {d : ℕ} (hd : 2 ≤ d) : + rankExponent R ≤ Real.log (R d : ℝ) / Real.log (d : ℝ) := + csInf_le (rankExponentSet_bddBelow hR) ⟨d, hd, rfl⟩ + +theorem rankExponent_le_three {R : ℕ → ℕ} (hR : ∀ d, d ^ 2 ≤ R d) + (hupper : ∀ d, R d ≤ d ^ 3) : rankExponent R ≤ 3 := by + have hlow : (0 : ℝ) < R 2 := by + have h := hR 2 + exact_mod_cast (show 0 < R 2 by omega) + have hbound : (R 2 : ℝ) ≤ (2 : ℝ) ^ 3 := by exact_mod_cast hupper 2 + have hlog := Real.log_le_log hlow hbound + rw [Real.log_pow] at hlog + have hquot : Real.log (R 2 : ℝ) / Real.log 2 ≤ (3 : ℝ) := + (div_le_iff₀ (Real.log_pos (by norm_num : (1 : ℝ) < 2))).mpr + (by simpa using hlog) + exact (rankExponent_le_logRank hR (d := 2) le_rfl).trans hquot + +/-- The infimum gives a lower bound for every individual exact rank. -/ +theorem rpow_rankExponent_le_rank {R : ℕ → ℕ} (hR : ∀ d, d ^ 2 ≤ R d) + {d : ℕ} (hd : 2 ≤ d) : + (d : ℝ) ^ rankExponent R ≤ R d := by + have hd1 : (1 : ℝ) < d := by exact_mod_cast (show 1 < d by omega) + have hd0 : (0 : ℝ) < d := lt_trans zero_lt_one hd1 + have hbound : (d : ℝ) ^ 2 ≤ R d := by exact_mod_cast hR d + have hRpos : (0 : ℝ) < R d := (pow_pos hd0 2).trans_le hbound + apply (Real.rpow_le_iff_le_log hd0 hRpos).mpr + exact (le_div_iff₀ (Real.log_pos hd1)).mp (rankExponent_le_logRank hR hd) + +/-- Positive slack supplies a finite block; the infimum need not be attained. -/ +theorem exists_rank_lt_rpow {R : ℕ → ℕ} + {δ : ℝ} (hδ : 0 < δ) : + ∃ u : ℕ, 2 ≤ u ∧ (R u : ℝ) < (u : ℝ) ^ (rankExponent R + δ) := by + obtain ⟨q, hq, hlt⟩ := exists_lt_of_csInf_lt (rankExponentSet_nonempty R) + (show sInf (rankExponentSet R) < rankExponent R + δ by + change rankExponent R < rankExponent R + δ + linarith) + obtain ⟨u, hu, rfl⟩ := hq + have hu1 : (1 : ℝ) < u := by exact_mod_cast (show 1 < u by omega) + have hu0 : (0 : ℝ) < u := lt_trans zero_lt_one hu1 + refine ⟨u, hu, Real.lt_rpow_of_log_lt hu0 ?_⟩ + exact (div_lt_iff₀ (Real.log_pos hu1)).mp hlt + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/States.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/States.lean new file mode 100644 index 0000000000..a8db377d6b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Additive/States.lean @@ -0,0 +1,163 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.Convex.Basic +public import Mathlib.Topology.Algebra.Ring.Real +public import Mathlib.Topology.Order.Compact +public import Mathlib.Topology.Compactness.Compact +public import Mathlib.Topology.Algebra.Ring.Basic +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Ring + +/-! +# The compact space of additive detecting states + +This file proves the topological reduction to a finite inconsistent system. It +does not assert that this system has a solution: ruling out a finite obstruction +also requires the integer cone certificate and the tensor rank-growth argument. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open Set + +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +/-- Normalized additive monotone states with the additional detection inequality. +Multiplicativity is deliberately not included. -/ +def stateSet (T : S) (k : ℕ) : Set (S → ℝ) := + {f | f 0 = 0 ∧ f 1 = 1 ∧ (∀ x y, f (x + y) = f x + f y) ∧ + Monotone f ∧ ∀ s, (k : ℝ) * f s ≤ f (T * s)} + +/-- Individual conditions, each of which uses only finitely many coordinates. -/ +inductive StateConstraint (S : Type*) [CommSemiring S] [PartialOrder S] where + | zero + | one + | add (x y : S) + | order (x y : S) (h : x ≤ y) + | detect (s : S) + +/-- Tests the normalization, additivity, order, or detection requirement represented by the +constraint. -/ +def StateConstraint.Holds (T : S) (k : ℕ) (f : S → ℝ) : + StateConstraint S → Prop + | .zero => f 0 = 0 + | .one => f 1 = 1 + | .add x y => f (x + y) = f x + f y + | .order x y _ => f x ≤ f y + | .detect s => (k : ℝ) * f s ≤ f (T * s) + +theorem mem_stateSet_iff (T : S) (k : ℕ) (f : S → ℝ) : + f ∈ stateSet T k ↔ ∀ c : StateConstraint S, c.Holds T k f := by + constructor + · rintro ⟨hzero, hone, hadd, hmono, hdetect⟩ c + cases c with + | zero => exact hzero + | one => exact hone + | add x y => exact hadd x y + | order x y h => exact hmono h + | detect s => exact hdetect s + · intro h + exact ⟨h .zero, h .one, fun x y => h (.add x y), + fun _ _ hxy => h (.order _ _ hxy), fun s => h (.detect s)⟩ + +theorem StateConstraint.isClosed (T : S) (k : ℕ) (c : StateConstraint S) : + IsClosed {f : S → ℝ | c.Holds T k f} := by + cases c with + | zero => exact isClosed_eq (continuous_apply 0) continuous_const + | one => exact isClosed_eq (continuous_apply 1) continuous_const + | add x y => + exact isClosed_eq (continuous_apply (x + y)) + ((continuous_apply x).add (continuous_apply y)) + | order x y _ => exact isClosed_le (continuous_apply x) (continuous_apply y) + | detect s => + exact isClosed_le (continuous_const.mul (continuous_apply s)) + (continuous_apply (T * s)) + +theorem stateSet_isClosed (T : S) (k : ℕ) : IsClosed (stateSet T k) := by + have heq : stateSet T k = ⋂ c : StateConstraint S, {f | c.Holds T k f} := by + ext f + simp only [mem_iInter, mem_ofPred_eq, mem_stateSet_iff] + rw [heq] + exact isClosed_iInter fun c => c.isClosed T k + +theorem state_natCast {T : S} {k : ℕ} {f : S → ℝ} + (hf : f ∈ stateSet T k) (n : ℕ) : f (n : S) = (n : ℝ) := by + induction n with + | zero => simpa only [Nat.cast_zero] using hf.1 + | succ n ih => + rw [Nat.cast_succ, hf.2.2.1, ih, hf.2.1, Nat.cast_succ] + +/-- The coordinate box uses ordinary rank only as a finite upper bound. -/ +def coordinateBox (R : S → ℕ) : Set (S → ℝ) := + {f | ∀ s, f s ∈ Icc 0 (R s : ℝ)} + +omit [CommSemiring S] [PartialOrder S] in +theorem coordinateBox_isCompact (R : S → ℕ) : IsCompact (coordinateBox R) := + isCompact_pi_infinite fun _ => isCompact_Icc + +theorem stateSet_subset_coordinateBox (T : S) (k : ℕ) (R : S → ℕ) + (hzero : ∀ s : S, 0 ≤ s) (hR : ∀ s : S, s ≤ (R s : S)) : + stateSet T k ⊆ coordinateBox R := by + intro f hf s + constructor + · simpa only [hf.1] using hf.2.2.2.1 (hzero s) + · simpa only [state_natCast hf] using hf.2.2.2.1 (hR s) + +theorem stateSet_isCompact (T : S) (k : ℕ) (R : S → ℕ) + (hzero : ∀ s : S, 0 ≤ s) (hR : ∀ s : S, s ≤ (R s : S)) : + IsCompact (stateSet T k) := + (coordinateBox_isCompact R).of_isClosed_subset (stateSet_isClosed T k) + (stateSet_subset_coordinateBox T k R hzero hR) + +theorem stateSet_convex (T : S) (k : ℕ) : Convex ℝ (stateSet T k) := by + intro f hf g hg a b ha hb hab + change a * f 0 + b * g 0 = 0 ∧ a * f 1 + b * g 1 = 1 ∧ + (∀ x y, a * f (x + y) + b * g (x + y) = + (a * f x + b * g x) + (a * f y + b * g y)) ∧ + Monotone (fun x => a * f x + b * g x) ∧ + ∀ s, (k : ℝ) * (a * f s + b * g s) ≤ + a * f (T * s) + b * g (T * s) + refine ⟨by rw [hf.1, hg.1]; ring, by simpa [hf.2.1, hg.2.1] using hab, ?_, ?_, ?_⟩ + · intro x y + rw [hf.2.2.1, hg.2.2.1] + ring + · intro x y hxy + exact add_le_add (mul_le_mul_of_nonneg_left (hf.2.2.2.1 hxy) ha) + (mul_le_mul_of_nonneg_left (hg.2.2.2.1 hxy) hb) + · intro s + have h := add_le_add (mul_le_mul_of_nonneg_left (hf.2.2.2.2 s) ha) + (mul_le_mul_of_nonneg_left (hg.2.2.2.2 s) hb) + nlinarith + +/-- Compactness gives an actual finite subsystem when no state exists. -/ +theorem finite_inconsistent_subsystem (T : S) (k : ℕ) (R : S → ℕ) + (hnone : stateSet T k = ∅) : + ∃ F : Finset (StateConstraint S), + ¬ ∃ f ∈ coordinateBox R, ∀ c ∈ F, c.Holds T k f := by + have hempty : (coordinateBox R ∩ + ⋂ c : StateConstraint S, {f | c.Holds T k f}) = ∅ := by + apply eq_empty_iff_forall_notMem.mpr + rintro f ⟨_, hf⟩ + have hstate : f ∈ stateSet T k := (mem_stateSet_iff T k f).mpr + (by simpa only [mem_iInter, mem_ofPred_eq] using hf) + rw [hnone] at hstate + exact hstate + obtain ⟨F, hF⟩ := (coordinateBox_isCompact R).elim_finite_subfamily_closed + (fun c : StateConstraint S => {f | c.Holds T k f}) + (fun c => c.isClosed T k) (Set.disjoint_iff_inter_eq_empty.mpr hempty) + refine ⟨F, ?_⟩ + rintro ⟨f, hf, hconstraints⟩ + have hmem : f ∈ coordinateBox R ∩ + ⋂ c ∈ F, {f | c.Holds T k f} := + ⟨hf, by simpa only [mem_iInter, mem_ofPred_eq] using hconstraints⟩ + exact Set.disjoint_left.mp hF hmem.1 hmem.2 + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Denominators.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Denominators.lean new file mode 100644 index 0000000000..1685e8c857 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Denominators.lean @@ -0,0 +1,81 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Data.Rat.Lemmas +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Algebra.Order.BigOperators.GroupWithZero.Finset + +/-! +# Clearing denominators in finite rational cones + +A single positive natural number clears every denominator of a finite rational +coefficient vector. The resulting integer vector preserves nonnegativity. The +last two lemmas transport finite linear identities through this construction. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum.AdditiveCone + +open scoped BigOperators + +/-- A common positive denominator for a finite rational vector, with signs +preserved coordinatewise. The product construction includes the empty type. -/ +theorem exists_pos_nat_mul_eq_int {ι : Type*} [Finite ι] (c : ι → ℚ) : + ∃ m : ℕ, 0 < m ∧ ∃ z : ι → ℤ, + (∀ i, (z i : ℚ) = (m : ℚ) * c i) ∧ + (∀ i, 0 ≤ c i → 0 ≤ z i) := by + classical + let : Fintype ι := Fintype.ofFinite ι + let m : ℕ := ∏ i, (c i).den + let z : ι → ℤ := fun i => + (∏ j ∈ Finset.univ.erase i, (c j).den : ℕ) * (c i).num + have hm : 0 < m := Nat.pos_of_ne_zero (Finset.prod_ne_zero_iff.mpr fun i _ => (c i).den_pos.ne') + refine ⟨m, hm, z, ?_, ?_⟩ + · intro i + have hprod : m = (∏ j ∈ Finset.univ.erase i, (c j).den) * (c i).den := + (Finset.prod_erase_mul Finset.univ (fun j => (c j).den) + (Finset.mem_univ i)).symm + dsimp only [z] + simp only [Int.cast_mul, Int.cast_natCast] + rw [hprod, Nat.cast_mul, mul_assoc, Rat.den_mul_eq_num] + · intro i hi + exact Int.mul_nonneg (Int.natCast_nonneg _) (Rat.num_nonneg.mpr hi) + +/-- A nonnegative rational coefficient vector has a positive integral scaling +which is a nonnegative integer coefficient vector. -/ +theorem exists_nonneg_int_scaling {ι : Type*} [Finite ι] + (c : ι → ℚ) (hc : ∀ i, 0 ≤ c i) : + ∃ m : ℕ, 0 < m ∧ ∃ z : ι → ℤ, + (∀ i, 0 ≤ z i) ∧ (∀ i, (z i : ℚ) = (m : ℚ) * c i) := by + let : Fintype ι := Fintype.ofFinite ι + obtain ⟨m, hm, z, hz, hnonneg⟩ := exists_pos_nat_mul_eq_int c + exact ⟨m, hm, z, fun i => hnonneg i (hc i), hz⟩ + +/-- Scaling rational coefficients scales each finite integer linear form. -/ +theorem cast_sum_mul_of_cleared {ι : Type*} [Fintype ι] + {c : ι → ℚ} {z : ι → ℤ} {m : ℕ} + (hz : ∀ i, (z i : ℚ) = (m : ℚ) * c i) (v : ι → ℤ) : + ((∑ i, z i * v i : ℤ) : ℚ) = (m : ℚ) * ∑ i, c i * (v i : ℚ) := by + rw [Int.cast_sum, Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + rw [Int.cast_mul, hz i, mul_assoc] + +/-- A rational linear identity becomes an integer linear identity once its +coefficients have been cleared. -/ +theorem sum_mul_eq_nat_mul_of_cleared {ι : Type*} [Fintype ι] + {c : ι → ℚ} {z : ι → ℤ} {m : ℕ} + (hz : ∀ i, (z i : ℚ) = (m : ℚ) * c i) (v : ι → ℤ) (b : ℤ) + (h : ∑ i, c i * (v i : ℚ) = (b : ℚ)) : + ∑ i, z i * v i = (m : ℤ) * b := by + apply Rat.intCast_injective + rw [cast_sum_mul_of_cleared hz v, h, Int.cast_mul, Int.cast_natCast] + +end MatrixMultiplicationAllFields.TensorSpectrum.AdditiveCone diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Encoding.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Encoding.lean new file mode 100644 index 0000000000..4bc308dd8d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Encoding.lean @@ -0,0 +1,281 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Additive.Finite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Stable +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Data.Fintype.EquivFin + +/-! +# From absence of additive states to an actual catalyst + +Finite coordinate bounds and state constraints are encoded by integer vectors. +Their integer cone certificate is evaluated in the stable additive group, so +the final inequality retains the catalyst and requires no cancellation in `S`. +-/ + +@[expose] public section + +open scoped BigOperators + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open MatrixMultiplicationAllFields.TensorSpectrum.AdditiveCone + +namespace FiniteStateEncoding + +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +/-- Numbers the elements of the finite support by consecutive coordinate indices. -/ +noncomputable def coordinateEquiv (U : Finset S) := + Fintype.equivFin {s : S // s ∈ U} + +/-- Recovers the supported semiring element at a coordinate index. -/ +noncomputable def coordinate (U : Finset S) + (j : Fin (Fintype.card {s : S // s ∈ U})) : S := + ((coordinateEquiv U).symm j).val + +/-- The coordinate unit vector for a supported element, or zero outside the support. -/ +noncomputable def basis (U : Finset S) (s : S) : + Fin (Fintype.card {s : S // s ∈ U}) → ℤ := by + classical + exact if hs : s ∈ U then Pi.single (coordinateEquiv U ⟨s, hs⟩) 1 else 0 + +/-- Evaluates an integer coefficient vector against a real assignment to the coordinates. -/ +def realEvaluate {n : ℕ} (L : Fin n → ℝ) (z : Fin n → ℤ) : ℝ := + ∑ j, (z j : ℝ) * L j + +theorem realEvaluate_sub {n : ℕ} (L : Fin n → ℝ) (a b : Fin n → ℤ) : + realEvaluate L (fun j => a j - b j) = realEvaluate L a - realEvaluate L b := by + simp [realEvaluate, Int.cast_sub, sub_mul, Finset.sum_sub_distrib] + +theorem realEvaluate_scalar {n : ℕ} (L : Fin n → ℝ) (c : ℤ) (a : Fin n → ℤ) : + realEvaluate L (fun j => c * a j) = (c : ℝ) * realEvaluate L a := by + simp [realEvaluate, Int.cast_mul, mul_assoc, Finset.mul_sum] + +theorem evaluate_sub {G : Type*} [AddCommGroup G] {n : ℕ} + (v : Fin n → G) (a b : Fin n → ℤ) : + evaluate v (fun j => a j - b j) = evaluate v a - evaluate v b := by + simp only [evaluate, sub_eq_add_neg, add_zsmul, neg_zsmul, + Finset.sum_add_distrib, Finset.sum_neg_distrib] + +omit [CommSemiring S] [PartialOrder S] in +theorem evaluate_basis_index {G : Type*} [AddCommGroup G] + (U : Finset S) (v : Fin (Fintype.card {s : S // s ∈ U}) → G) + (s : S) (hs : s ∈ U) : + evaluate v (basis U s) = v (coordinateEquiv U ⟨s, hs⟩) := by + classical + rw [basis, dite_eq_left hs] + unfold evaluate + rw [Fintype.sum_eq_single (coordinateEquiv U ⟨s, hs⟩), + Pi.single_eq_same, one_zsmul] + intro j hj + rw [Pi.single_eq_of_ne hj, zero_zsmul] + +omit [PartialOrder S] in +theorem evaluate_basis (U : Finset S) (s : S) (hs : s ∈ U) : + evaluate (fun j => StableGroup.embed (coordinate U j)) (basis U s) = + StableGroup.embed s := by + rw [evaluate_basis_index U _ s hs] + simp [coordinate] + +omit [PartialOrder S] in +theorem embed_nat_mul (n : ℕ) (s : S) : + (n : ℤ) • StableGroup.embed s = StableGroup.embed ((n : S) * s) := by + rw [natCast_zsmul] + simpa only [nsmul_eq_mul] using ((StableGroup.embed (S := S)).map_nsmul n s).symm + +/-- Indexes coordinate lower bounds, coordinate upper bounds, and inequalities from the finite +constraints. -/ +abbrev InequalityIndex (U : Finset S) (F : Finset (StateConstraint S)) := + {s : S // s ∈ U} ⊕ ({s : S // s ∈ U} ⊕ {c : StateConstraint S // c ∈ F}) + +/-- The integer coefficients of the indexed inequality in the finite system. -/ +noncomputable def inequality (T : S) (k : ℕ) (R : S → ℕ) + (U : Finset S) (F : Finset (StateConstraint S)) : + InequalityIndex U F → Fin (Fintype.card {s : S // s ∈ U}) → ℤ + | .inl s => basis U s.val + | .inr (.inl s) => fun j => (R s.val : ℤ) * basis U 1 j - basis U s.val j + | .inr (.inr c) => match c.val with + | .order x y _ => fun j => basis U y j - basis U x j + | .detect s => fun j => basis U (T * s) j - (k : ℤ) * basis U s j + | _ => 0 + +/-- The integer coefficients of the zero and additivity relations. -/ +noncomputable def relation (U : Finset S) (F : Finset (StateConstraint S)) : + {c : StateConstraint S // c ∈ F} → Fin (Fintype.card {s : S // s ∈ U}) → ℤ + | ⟨.zero, _⟩ => basis U 0 + | ⟨.add x y, _⟩ => fun j => basis U (x + y) j - basis U x j - basis U y j + | _ => 0 + +/-- Selects the left-hand element in the comparison encoded by an inequality index. -/ +def leftElement (U : Finset S) (F : Finset (StateConstraint S)) : + InequalityIndex U F → S + | .inl _ => 0 + | .inr (.inl s) => s.val + | .inr (.inr c) => match c.val with + | .order x _ _ => x + | _ => 0 + +/-- Selects the right-hand element in the comparison encoded by an inequality index. -/ +def rightElement (R : S → ℕ) (U : Finset S) (F : Finset (StateConstraint S)) : + InequalityIndex U F → S + | .inl s => s.val + | .inr (.inl s) => (R s.val : S) + | .inr (.inr c) => match c.val with + | .order _ y _ => y + | _ => 0 + +/-- Selects the element of a detection constraint and returns zero on the remaining indices. -/ +def detectionElement (U : Finset S) (F : Finset (StateConstraint S)) : + InequalityIndex U F → S + | .inr (.inr ⟨.detect s, _⟩) => s + | _ => 0 + +theorem left_le_right (R : S → ℕ) (U : Finset S) (F : Finset (StateConstraint S)) + (hzero : ∀ s : S, 0 ≤ s) (hR : ∀ s : S, s ≤ (R s : S)) : + ∀ i, leftElement U F i ≤ rightElement R U F i := by + rintro (s | (s | ⟨c, hc⟩)) + · exact hzero s.val + · exact hR s.val + · cases c <;> simp only [leftElement, rightElement, le_refl] + assumption + +theorem inequality_evaluate (T : S) (k : ℕ) (R : S → ℕ) + (U : Finset S) (F : Finset (StateConstraint S)) (h1 : 1 ∈ U) + (hcoords : ∀ c ∈ F, c.coordinates T ⊆ U) : + ∀ i, evaluate (fun j => StableGroup.embed (coordinate U j)) + (inequality T k R U F i) = + (StableGroup.embed (rightElement R U F i) - + StableGroup.embed (leftElement U F i)) + + (StableGroup.embed (T * detectionElement U F i) - + StableGroup.embed ((k : S) * detectionElement U F i)) := by + rintro (s | (s | ⟨c, hc⟩)) + · simpa only [inequality, rightElement, leftElement, detectionElement, + mul_zero, map_zero, sub_zero, sub_self, add_zero] using evaluate_basis U s.val s.property + · simp only [inequality, rightElement, leftElement, detectionElement, + evaluate_sub, evaluate_scalar, evaluate_basis U 1 h1, + evaluate_basis U s.val s.property, embed_nat_mul, mul_one, + mul_zero, map_zero, sub_self, add_zero] + · cases c with + | zero => simp [inequality, rightElement, leftElement, detectionElement, evaluate] + | one => simp [inequality, rightElement, leftElement, detectionElement, evaluate] + | add x y => simp [inequality, rightElement, leftElement, detectionElement, evaluate] + | order x y hxy => + have hx : x ∈ U := hcoords (.order x y hxy) hc (by simp [StateConstraint.coordinates]) + have hy : y ∈ U := hcoords (.order x y hxy) hc (by simp [StateConstraint.coordinates]) + simp only [inequality, rightElement, leftElement, detectionElement, + evaluate_sub, evaluate_basis U x hx, evaluate_basis U y hy, + mul_zero, map_zero, sub_self, add_zero] + | detect s => + have hs : s ∈ U := hcoords (.detect s) hc (by simp [StateConstraint.coordinates]) + have hTs : T * s ∈ U := hcoords (.detect s) hc (by simp [StateConstraint.coordinates]) + simp only [inequality, rightElement, leftElement, detectionElement, + evaluate_sub, evaluate_scalar, evaluate_basis U s hs, + evaluate_basis U (T * s) hTs, embed_nat_mul, map_zero, sub_self, zero_add] + +theorem relation_evaluate (T : S) (U : Finset S) (F : Finset (StateConstraint S)) + (h0 : 0 ∈ U) (hcoords : ∀ c ∈ F, c.coordinates T ⊆ U) : + ∀ c, evaluate (fun j => StableGroup.embed (coordinate U j)) (relation U F c) = 0 := by + rintro ⟨c, hc⟩ + cases c with + | zero => simpa only [relation, map_zero] using evaluate_basis U 0 h0 + | one => simp [relation, evaluate] + | add x y => + have hx : x ∈ U := hcoords (.add x y) hc (by simp [StateConstraint.coordinates]) + have hy : y ∈ U := hcoords (.add x y) hc (by simp [StateConstraint.coordinates]) + have hxy : x + y ∈ U := hcoords (.add x y) hc (by simp [StateConstraint.coordinates]) + simp only [relation, evaluate_sub, evaluate_basis U x hx, + evaluate_basis U y hy, evaluate_basis U (x + y) hxy] + rw [(StableGroup.embed (S := S)).map_add x y] + abel + | order x y hxy => simp [relation, evaluate] + | detect s => simp [relation, evaluate] + +theorem no_normalized_functional (T : S) (k : ℕ) (R : S → ℕ) + (U : Finset S) (F : Finset (StateConstraint S)) + (hinconsistent : ¬ ∃ f : S → ℝ, + (∀ s ∈ U, f s ∈ Set.Icc 0 (R s : ℝ)) ∧ ∀ c ∈ F, c.Holds T k f) : + ¬ ∃ L : Fin (Fintype.card {s : S // s ∈ U}) → ℝ, + realEvaluate L (basis U 1) = 1 ∧ + (∀ i, 0 ≤ realEvaluate L (inequality T k R U F i)) ∧ + (∀ c, realEvaluate L (relation U F c) = 0) := by + rintro ⟨L, hunit, hineq, hrel⟩ + let f : S → ℝ := fun s => realEvaluate L (basis U s) + apply hinconsistent + refine ⟨f, ?_, ?_⟩ + · intro s hs + have hlo := hineq (.inl ⟨s, hs⟩) + have hhi := hineq (.inr (.inl ⟨s, hs⟩)) + change 0 ≤ f s at hlo + change 0 ≤ realEvaluate L (fun j => (R s : ℤ) * basis U 1 j - basis U s j) at hhi + rw [realEvaluate_sub, realEvaluate_scalar, hunit] at hhi + simp only [Int.cast_natCast, mul_one] at hhi + exact ⟨hlo, by change f s ≤ (R s : ℝ); change 0 ≤ (R s : ℝ) - f s at hhi; linarith⟩ + · intro c hc + cases c with + | zero => exact hrel ⟨.zero, hc⟩ + | one => exact hunit + | add x y => + have h := hrel ⟨.add x y, hc⟩ + change realEvaluate L (fun j => basis U (x + y) j - basis U x j - basis U y j) = 0 at h + rw [realEvaluate_sub, realEvaluate_sub] at h + change f (x + y) - f x - f y = 0 at h + change f (x + y) = f x + f y + linarith + | order x y hxy => + have h := hineq (.inr (.inr ⟨.order x y hxy, hc⟩)) + change 0 ≤ realEvaluate L (fun j => basis U y j - basis U x j) at h + rw [realEvaluate_sub] at h + change 0 ≤ f y - f x at h + change f x ≤ f y + linarith + | detect s => + have h := hineq (.inr (.inr ⟨.detect s, hc⟩)) + change 0 ≤ realEvaluate L (fun j => basis U (T * s) j - (k : ℤ) * basis U s j) at h + rw [realEvaluate_sub, realEvaluate_scalar] at h + simp only [Int.cast_natCast] at h + change 0 ≤ f (T * s) - (k : ℝ) * f s at h + change (k : ℝ) * f s ≤ f (T * s) + linarith + +end FiniteStateEncoding + +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +/-- Failure of the normalized additive monotone state space produces a genuine +strict positive integer gain with one catalyst. All finite encoding and cone +steps are proved from the given semiring and order hypotheses. -/ +theorem catalyst_of_no_state (T : S) (k : ℕ) (R : S → ℕ) + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + (hzero : ∀ s : S, 0 ≤ s) (hR : ∀ s : S, s ≤ (R s : S)) + (hnone : stateSet T k = ∅) : + ∃ m : ℕ, 0 < m ∧ ∃ D s : S, D + (m : S) + T * s ≤ D + (k : S) * s := by + classical + obtain ⟨F, U, h0, h1, hcoords, hbad⟩ := finite_coordinate_obstruction T k R hnone + let g := FiniteStateEncoding.inequality T k R U F + let r := FiniteStateEncoding.relation U F + let unit := FiniteStateEncoding.basis U (1 : S) + obtain ⟨m, hm, c, d, hc, hcertificate⟩ := + integer_cone_certificate_of_no_state g r unit + (FiniteStateEncoding.no_normalized_functional T k R U F hbad) + have hmNat : 0 < m.toNat := by omega + have hmCast : (m.toNat : ℤ) = m := Int.toNat_of_nonneg (le_of_lt hm) + obtain ⟨X, Y, s, hXY, hstable⟩ := stable_certificate_of_integer_cone hadd + (FiniteStateEncoding.coordinate U) g r unit m.toNat k T c d hc + (FiniteStateEncoding.leftElement U F) (FiniteStateEncoding.rightElement R U F) + (FiniteStateEncoding.detectionElement U F) + (FiniteStateEncoding.left_le_right R U F hzero hR) + (FiniteStateEncoding.evaluate_basis U 1 h1) + (FiniteStateEncoding.inequality_evaluate T k R U F h1 hcoords) + (FiniteStateEncoding.relation_evaluate T U F h0 hcoords) + (by simpa only [hmCast] using hcertificate) + obtain ⟨D, hD⟩ := stable_certificate_to_catalyst hadd hXY hstable + exact ⟨m.toNat, hmNat, D, s, hD⟩ + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Integer.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Integer.lean new file mode 100644 index 0000000000..b30057885b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Integer.lean @@ -0,0 +1,156 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Rational +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Denominators +public import Mathlib.Data.Rat.BigOperators +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.Linarith + +/-! +# Integer finite obstruction + +Integer-coefficient affine inequalities inherit a nonnegative integer +infeasibility certificate from rational Fourier–Motzkin elimination. Paired +rows encode additive relations and normalization without quotienting a real +vector space or assuming a closed-cone theorem. +-/ + +@[expose] public section + +open scoped BigOperators + +namespace MatrixMultiplicationAllFields.TensorSpectrum.AdditiveCone + +universe u + +/-- Farkas certificate with integer weights for a real-infeasible integer system. -/ +theorem integer_certificate_of_no_real_solution {ι : Type u} [Fintype ι] {n : ℕ} + (a : ι → Fin n → ℤ) (b : ι → ℤ) + (h : ¬ ∃ x : Fin n → ℝ, + ∀ i, 0 ≤ (∑ k, (a i k : ℝ) * x k) + (b i : ℝ)) : + ∃ c : ι → ℤ, (∀ i, 0 ≤ c i) ∧ + (∀ k, ∑ i, c i * a i k = 0) ∧ (∑ i, c i * b i) < 0 := by + classical + have hq : ¬ ∃ x : Fin n → ℚ, + ∀ i, 0 ≤ (∑ k, (a i k : ℚ) * x k) + (b i : ℚ) := by + rintro ⟨x, hx⟩ + apply h + refine ⟨fun k => (x k : ℝ), ?_⟩ + intro i + change (0 : ℝ) ≤ (∑ k, (a i k : ℝ) * (x k : ℝ)) + (b i : ℝ) + exact_mod_cast hx i + obtain ⟨c⟩ := rational_certificate_of_infeasible + (fun i k => (a i k : ℚ)) (fun i => (b i : ℚ)) hq + obtain ⟨m, hm, z, hz, hzpos⟩ := exists_pos_nat_mul_eq_int c.weight + have hm' : (0 : ℚ) < m := by exact_mod_cast hm + refine ⟨z, (fun i => hzpos i (c.nonneg i)), ?_, ?_⟩ + · intro k + have heq : (∑ i, (z i : ℚ) * (a i k : ℚ)) = 0 := by + simp_rw [hz] + rw [show (∑ i, (m : ℚ) * c.weight i * (a i k : ℚ)) = + (m : ℚ) * (∑ i, c.weight i * (a i k : ℚ)) by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro i hi + ring] + rw [c.cancel, mul_zero] + exact_mod_cast heq + · have hneg : (∑ i, (z i : ℚ) * (b i : ℚ)) < 0 := by + simp_rw [hz] + rw [show (∑ i, (m : ℚ) * c.weight i * (b i : ℚ)) = + (m : ℚ) * (∑ i, c.weight i * (b i : ℚ)) by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro i hi + ring] + exact mul_neg_of_pos_of_neg hm' c.negative + exact_mod_cast hneg + +private abbrev NormalizedRow (ι κ : Type u) := ι ⊕ (κ ⊕ (κ ⊕ Bool)) + +private def normalizedCoefficients {ι κ : Type u} {n : ℕ} + (g : ι → Fin n → ℤ) (r : κ → Fin n → ℤ) (unit : Fin n → ℤ) : + NormalizedRow ι κ → Fin n → ℤ + | Sum.inl i => g i + | Sum.inr (Sum.inl j) => r j + | Sum.inr (Sum.inr (Sum.inl j)) => fun k => -r j k + | Sum.inr (Sum.inr (Sum.inr true)) => unit + | Sum.inr (Sum.inr (Sum.inr false)) => fun k => -unit k + +private def normalizedConstants {ι κ : Type u} : NormalizedRow ι κ → ℤ + | Sum.inl _ => 0 + | Sum.inr (Sum.inl _) => 0 + | Sum.inr (Sum.inr (Sum.inl _)) => 0 + | Sum.inr (Sum.inr (Sum.inr true)) => -1 + | Sum.inr (Sum.inr (Sum.inr false)) => 1 + +/-- A finite integer certificate for failure of additive-state feasibility. + +Failure of a normalized real functional that kills the additive relations and +is nonnegative on the inequality vectors yields a strictly positive integer +multiple of the negative unit, with nonnegative integer cone coefficients and +unrestricted integer relation coefficients. +-/ +theorem integer_cone_certificate_of_no_state + {ι κ : Type u} [Fintype ι] [Fintype κ] {n : ℕ} + (g : ι → Fin n → ℤ) (r : κ → Fin n → ℤ) (unit : Fin n → ℤ) + (h : ¬ ∃ L : Fin n → ℝ, + (∑ k, (unit k : ℝ) * L k) = 1 ∧ + (∀ i, 0 ≤ ∑ k, (g i k : ℝ) * L k) ∧ + (∀ j, (∑ k, (r j k : ℝ) * L k) = 0)) : + ∃ m : ℤ, 0 < m ∧ ∃ c : ι → ℤ, ∃ d : κ → ℤ, + (∀ i, 0 ≤ c i) ∧ + ∀ k, -m * unit k = (∑ i, c i * g i k) + ∑ j, d j * r j k := by + classical + let a := normalizedCoefficients g r unit + let b : NormalizedRow ι κ → ℤ := normalizedConstants + have hsys : ¬ ∃ L : Fin n → ℝ, + ∀ i, 0 ≤ (∑ k, (a i k : ℝ) * L k) + (b i : ℝ) := by + rintro ⟨L, hL⟩ + apply h + refine ⟨L, ?_, ?_, ?_⟩ + · have hp := hL (Sum.inr (Sum.inr (Sum.inr true))) + have hn := hL (Sum.inr (Sum.inr (Sum.inr false))) + simp only [a, b, normalizedCoefficients, normalizedConstants, + Int.cast_neg, Int.cast_one, neg_mul, Finset.sum_neg_distrib] at hp hn + linarith + · intro i + have hi := hL (Sum.inl i) + simpa only [a, b, normalizedCoefficients, normalizedConstants, + Int.cast_zero, add_zero] using hi + · intro j + have hp := hL (Sum.inr (Sum.inl j)) + have hn := hL (Sum.inr (Sum.inr (Sum.inl j))) + simp only [a, b, normalizedCoefficients, normalizedConstants, + Int.cast_neg, Int.cast_zero, neg_mul, Finset.sum_neg_distrib, add_zero] at hp hn + linarith + obtain ⟨w, hwpos, hwzero, hwneg⟩ := + integer_certificate_of_no_real_solution a b hsys + let α := w (Sum.inr (Sum.inr (Sum.inr true))) + let β := w (Sum.inr (Sum.inr (Sum.inr false))) + let c : ι → ℤ := fun i => w (Sum.inl i) + let d : κ → ℤ := fun j => + w (Sum.inr (Sum.inl j)) - w (Sum.inr (Sum.inr (Sum.inl j))) + have hm : 0 < α - β := by + have hneg : -α + β < 0 := by + simpa [b, normalizedConstants, Fintype.sum_sum_type, α, β] using hwneg + linarith + refine ⟨α - β, hm, c, d, (fun i => hwpos (Sum.inl i)), ?_⟩ + intro k + have heq := hwzero k + have heq' : (∑ i, c i * g i k) + (∑ j, d j * r j k) + + (α - β) * unit k = 0 := by + simp only [a, normalizedCoefficients, Fintype.sum_sum_type, + Fintype.sum_bool, mul_neg, Finset.sum_neg_distrib] at heq + simp only [d, sub_mul, Finset.sum_sub_distrib] + dsimp [c, α, β] at * + linarith + linarith + +end MatrixMultiplicationAllFields.TensorSpectrum.AdditiveCone diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Interval.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Interval.lean new file mode 100644 index 0000000000..2dc090ea0a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Interval.lean @@ -0,0 +1,88 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.Field.Basic +public import Mathlib.Data.Fintype.EquivFin +public import Mathlib.Algebra.Order.Field.Rat +public import Mathlib.Data.Finset.Max +public import Mathlib.Data.Fintype.Basic +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Ring + +/-! +# Reconstruction of one rational variable + +The compatibility conditions produced by eliminating one variable from a finite +system of affine inequalities suffice to reconstruct that variable over `ℚ`. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +/-- The one-variable reconstruction step of Fourier--Motzkin elimination. +Zero coefficients require a nonnegative constant, and each positive/negative +pair requires a nonnegative elimination combination. These conditions suffice +for a rational solution to every original inequality. -/ +theorem exists_nonneg_affine_of_pairwise {ι : Type*} [Finite ι] + (a b : ι → ℚ) + (hzero : ∀ i, a i = 0 → 0 ≤ b i) + (hpair : ∀ i j, 0 < a i → a j < 0 → + 0 ≤ (-a j) * b i + a i * b j) : + ∃ x : ℚ, ∀ i, 0 ≤ a i * x + b i := by + classical + let : Fintype ι := Fintype.ofFinite ι + let P : Finset ι := Finset.univ.filter (fun i => 0 < a i) + by_cases hP : P.Nonempty + · obtain ⟨p, hpP, hmax⟩ := P.exists_max_image (fun i => -b i / a i) hP + have hp : 0 < a p := (Finset.mem_filter.mp hpP).2 + have hpx : a p * (-b p / a p) = -b p := + mul_div_cancel₀ _ (ne_of_gt hp) + refine ⟨-b p / a p, ?_⟩ + intro i + rcases lt_trichotomy (a i) 0 with hi | hi | hi + · have hprod : 0 ≤ a p * (a i * (-b p / a p) + b i) := by + calc + 0 ≤ (-a i) * b p + a p * b i := hpair p i hp hi + _ = a i * (a p * (-b p / a p)) + a p * b i := by + rw [hpx] + ring + _ = a p * (a i * (-b p / a p) + b i) := by ring + exact nonneg_of_mul_nonneg_right hprod hp + · simpa [hi] using hzero i hi + · have hiP : i ∈ P := Finset.mem_filter.mpr ⟨Finset.mem_univ i, hi⟩ + have hbound : -b i ≤ a i * (-b p / a p) := + (div_le_iff₀' hi).mp (hmax i hiP) + linarith only [hbound] + · have hnonpos : ∀ i, a i ≤ 0 := by + intro i + apply le_of_not_gt + intro hi + exact hP ⟨i, Finset.mem_filter.mpr ⟨Finset.mem_univ i, hi⟩⟩ + let N : Finset ι := Finset.univ.filter (fun i => a i < 0) + by_cases hN : N.Nonempty + · obtain ⟨n, hnN, hmin⟩ := N.exists_min_image (fun i => -b i / a i) hN + refine ⟨-b n / a n, ?_⟩ + intro i + by_cases hi : a i < 0 + · have hiN : i ∈ N := Finset.mem_filter.mpr ⟨Finset.mem_univ i, hi⟩ + have hbound : -b i ≤ a i * (-b n / a n) := + (le_div_iff_of_neg' hi).mp (hmin i hiN) + linarith only [hbound] + · have hi0 : a i = 0 := le_antisymm (hnonpos i) (le_of_not_gt hi) + simpa [hi0] using hzero i hi0 + · refine ⟨0, ?_⟩ + intro i + have hnonneg : 0 ≤ a i := by + apply le_of_not_gt + intro hi + exact hN ⟨i, Finset.mem_filter.mpr ⟨Finset.mem_univ i, hi⟩⟩ + have hi0 : a i = 0 := le_antisymm (hnonpos i) hnonneg + simpa using hzero i hi0 + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Rational.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Rational.lean new file mode 100644 index 0000000000..bd7b288b6a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Rational.lean @@ -0,0 +1,206 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Interval +public import Mathlib.Algebra.BigOperators.Fin +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Data.Fintype.Sum +public import Mathlib.Data.Fintype.Prod +public import Mathlib.Tactic.NormNum +public import Mathlib.Tactic.Ring + +/-! +# Finite rational alternatives + +Fourier–Motzkin elimination proves the rational Farkas alternative directly. +The proof keeps the nonnegative combination of original rows at every +elimination step. Consequently the obstruction has rational coefficients; +neither a real separation theorem nor a rational-density premise is assumed. +-/ + +@[expose] public section + +open scoped BigOperators + +namespace MatrixMultiplicationAllFields.TensorSpectrum.AdditiveCone + +universe u + +/-- A negative constant obtained as a nonnegative rational combination of rows. -/ +structure RationalCertificate {ι : Type u} [Fintype ι] {n : ℕ} + (a : ι → Fin n → ℚ) (b : ι → ℚ) where + /-- Assigns a rational coefficient to each generator of the certificate. -/ + weight : ι → ℚ + nonneg : ∀ i, 0 ≤ weight i + cancel : ∀ k, ∑ i, weight i * a i k = 0 + negative : ∑ i, weight i * b i < 0 + +theorem weighted_sum_assoc {ι κ : Type*} [Fintype ι] [Fintype κ] + (d : κ → ℚ) (w : κ → ι → ℚ) (v : ι → ℚ) : + (∑ i, (∑ j, d j * w j i) * v i) = + ∑ j, d j * (∑ i, w j i * v i) := by + simp_rw [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro j hj + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro i hi + ring + +private abbrev EliminationIndex {ι : Type u} {n : ℕ} + (a : ι → Fin (n + 1) → ℚ) := + {i : ι // a i 0 = 0} ⊕ + ({i : ι // 0 < a i 0} × {i : ι // a i 0 < 0}) + +private noncomputable def eliminationWeight {ι : Type u} {n : ℕ} + (a : ι → Fin (n + 1) → ℚ) (j : EliminationIndex a) (i : ι) : ℚ := by + classical + exact match j with + | Sum.inl z => if i = z.val then 1 else 0 + | Sum.inr p => + (if i = p.1.val then -a p.2.val 0 else 0) + + (if i = p.2.val then a p.1.val 0 else 0) + +private theorem eliminationWeight_nonneg {ι : Type u} {n : ℕ} + (a : ι → Fin (n + 1) → ℚ) (j : EliminationIndex a) (i : ι) : + 0 ≤ eliminationWeight a j i := by + classical + cases j with + | inl z => simp only [eliminationWeight]; split <;> norm_num + | inr p => + simp only [eliminationWeight] + apply add_nonneg + · split + · exact neg_nonneg.mpr p.2.property.le + · exact le_rfl + · split + · exact p.1.property.le + · exact le_rfl + +private theorem eliminationWeight_zero {ι : Type u} [Fintype ι] {n : ℕ} + (a : ι → Fin (n + 1) → ℚ) (z : {i : ι // a i 0 = 0}) + (v : ι → ℚ) : + (∑ i, eliminationWeight a (Sum.inl z) i * v i) = v z.val := by + classical + simp [eliminationWeight] + +private theorem eliminationWeight_pair {ι : Type u} [Fintype ι] {n : ℕ} + (a : ι → Fin (n + 1) → ℚ) + (p : {i : ι // 0 < a i 0} × {i : ι // a i 0 < 0}) (v : ι → ℚ) : + (∑ i, eliminationWeight a (Sum.inr p) i * v i) = + (-a p.2.val 0) * v p.1.val + a p.1.val 0 * v p.2.val := by + classical + simp [eliminationWeight, add_mul, Finset.sum_add_distrib, ite_mul] + +private theorem eliminationWeight_head {ι : Type u} [Fintype ι] {n : ℕ} + (a : ι → Fin (n + 1) → ℚ) (j : EliminationIndex a) : + (∑ i, eliminationWeight a j i * a i 0) = 0 := by + cases j with + | inl z => rw [eliminationWeight_zero]; exact z.property + | inr p => rw [eliminationWeight_pair]; ring + +/-- A finite rational affine system has a solution or a rational obstruction. + The alternatives are constructed by elimination of one coordinate at a time. -/ +theorem rational_alternative (n : ℕ) : + ∀ {ι : Type u} [Fintype ι] (a : ι → Fin n → ℚ) (b : ι → ℚ), + (∃ x : Fin n → ℚ, ∀ i, 0 ≤ (∑ k, a i k * x k) + b i) ∨ + Nonempty (RationalCertificate a b) := by + classical + induction n with + | zero => + intro ι _ a b + by_cases h : ∀ i, 0 ≤ b i + · left + exact ⟨Fin.elim0, by simpa using h⟩ + · right + obtain ⟨i, hi⟩ := not_forall.mp h + have hi : b i < 0 := lt_of_not_ge hi + refine ⟨{ + weight := fun j => if j = i then 1 else 0 + nonneg := ?_ + cancel := ?_ + negative := ?_ + }⟩ + · intro j; split <;> norm_num + · intro k; exact Fin.elim0 k + · simpa using hi + | succ n ih => + intro ι _ a b + let J := EliminationIndex a + let : Fintype J := inferInstanceAs (Fintype (EliminationIndex a)) + let w : J → ι → ℚ := eliminationWeight a + let a' : J → Fin n → ℚ := fun j k => ∑ i, w j i * a i k.succ + let b' : J → ℚ := fun j => ∑ i, w j i * b i + rcases ih a' b' with h | hc + · obtain ⟨x, hx⟩ := h + let residual : ι → ℚ := fun i => (∑ k, a i k.succ * x k) + b i + have hres (j : J) : 0 ≤ ∑ i, w j i * residual i := by + have heq : (∑ i, w j i * residual i) = + (∑ k, a' j k * x k) + b' j := by + simp only [residual, mul_add, Finset.sum_add_distrib, b', a'] + congr 1 + simp_rw [Finset.mul_sum, Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro k hk + apply Finset.sum_congr rfl + intro i hi + ring + rw [heq] + exact hx j + have hz : ∀ i, a i 0 = 0 → 0 ≤ residual i := by + intro i hi + have h := hres (Sum.inl ⟨i, hi⟩) + simpa only [w, eliminationWeight_zero] using h + have hp : ∀ i j, 0 < a i 0 → a j 0 < 0 → + 0 ≤ (-a j 0) * residual i + a i 0 * residual j := by + intro i j hi hj + have h := hres (Sum.inr (⟨i, hi⟩, ⟨j, hj⟩)) + simpa only [w, eliminationWeight_pair] using h + obtain ⟨x₀, hx₀⟩ := TensorSpectrum.exists_nonneg_affine_of_pairwise + (fun i => a i 0) residual hz hp + left + refine ⟨Fin.cases x₀ x, ?_⟩ + intro i + simpa only [Fin.sum_univ_succ, Fin.cases_zero, Fin.cases_succ, + residual, add_assoc] using hx₀ i + · let c := Classical.choice hc + right + refine ⟨{ + weight := fun i => ∑ j, c.weight j * w j i + nonneg := ?_ + cancel := ?_ + negative := ?_ + }⟩ + · intro i + exact Finset.sum_nonneg fun j hj => + mul_nonneg (c.nonneg j) (eliminationWeight_nonneg a j i) + · intro k + refine Fin.cases ?_ (fun k => ?_) k + · rw [weighted_sum_assoc] + have hhead (j : J) : (∑ i, w j i * a i 0) = 0 := + eliminationWeight_head a j + simp_rw [hhead, mul_zero] + simp + · rw [weighted_sum_assoc] + exact c.cancel k + · rw [weighted_sum_assoc] + exact c.negative + +/-- Infeasibility produces an actual certificate, rather than an assumed + separation functional or a real coefficient vector. -/ +theorem rational_certificate_of_infeasible {ι : Type u} [Fintype ι] {n : ℕ} + (a : ι → Fin n → ℚ) (b : ι → ℚ) + (h : ¬ ∃ x : Fin n → ℚ, ∀ i, 0 ≤ (∑ k, a i k * x k) + b i) : + Nonempty (RationalCertificate a b) := by + rcases rational_alternative n a b with hs | hc + · exact False.elim (h hs) + · exact hc + +end MatrixMultiplicationAllFields.TensorSpectrum.AdditiveCone diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Stable.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Stable.lean new file mode 100644 index 0000000000..bcbf71c10e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/Stable.lean @@ -0,0 +1,173 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.Integer +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.AdditiveCone.StableGroup +public import Mathlib.Algebra.BigOperators.Module +public import Mathlib.Algebra.Module.BigOperators +public import Mathlib.Algebra.Module.NatInt +public import Mathlib.Tactic.Abel + +/-! Integer cone certificates evaluate in the actual additive group completion. +The resulting equality supplies a catalyst; no cancellation law for the +underlying semiring is imposed. -/ + +@[expose] public section + +open scoped BigOperators + +namespace MatrixMultiplicationAllFields.TensorSpectrum.AdditiveCone + +universe u + +section Evaluation + +variable {G : Type*} [AddCommGroup G] {n : ℕ} + +/-- Evaluates the finite linear combination with the given coefficients and generators. -/ +def evaluate (v : Fin n → G) (z : Fin n → ℤ) : G := ∑ k, z k • v k + +theorem evaluate_add (v : Fin n → G) (a b : Fin n → ℤ) : + evaluate v (fun k => a k + b k) = evaluate v a + evaluate v b := by + simp [evaluate, add_zsmul, Finset.sum_add_distrib] + +theorem evaluate_scalar (v : Fin n → G) (c : ℤ) (a : Fin n → ℤ) : + evaluate v (fun k => c * a k) = c • evaluate v a := by + simp [evaluate, mul_smul, Finset.smul_sum] + +theorem evaluate_sum {ι : Type*} [Fintype ι] + (v : Fin n → G) (a : ι → Fin n → ℤ) : + evaluate v (fun k => ∑ i, a i k) = ∑ i, evaluate v (a i) := by + simp only [evaluate, Finset.sum_smul] + rw [Finset.sum_comm] + +theorem evaluate_certificate {ι κ : Type*} [Fintype ι] [Fintype κ] + (v : Fin n → G) (g : ι → Fin n → ℤ) (r : κ → Fin n → ℤ) + (unit : Fin n → ℤ) (m : ℤ) (c : ι → ℤ) (d : κ → ℤ) + (h : ∀ k, -m * unit k = (∑ i, c i * g i k) + ∑ j, d j * r j k) : + (-m) • evaluate v unit = + (∑ i, c i • evaluate v (g i)) + ∑ j, d j • evaluate v (r j) := by + have h' := congrArg (evaluate v) (funext h) + simpa only [evaluate_scalar, evaluate_add, evaluate_sum] using h' + +end Evaluation + +section Stable + +open MatrixMultiplicationAllFields.TensorSpectrum + +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +private theorem nsmul_le_nsmul_of_add + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + {a b : S} (h : a ≤ b) (n : ℕ) : n • a ≤ n • b := by + induction n with + | zero => simp + | succ n ih => + simp only [succ_nsmul] + exact (hadd _ _ _ ih).trans (by + simpa only [add_comm] using hadd _ _ (n • b) h) + +private theorem sum_le_sum_of_add {ι : Type*} + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + (F : Finset ι) (a b : ι → S) (h : ∀ i ∈ F, a i ≤ b i) : + ∑ i ∈ F, a i ≤ ∑ i ∈ F, b i := by + classical + induction F using Finset.induction_on with + | empty => simp + | @insert i F hi ih => + simp only [Finset.sum_insert hi] + apply (hadd _ _ _ (h i (Finset.mem_insert_self _ _))).trans + have hF := ih (fun j hj => h j (Finset.mem_insert_of_mem hj)) + simpa only [add_comm] using hadd _ _ (b i) hF + +omit [PartialOrder S] in +private theorem embed_natCast (m : ℕ) : + StableGroup.embed (S := S) (m : S) = m • StableGroup.embed (S := S) 1 := by + have h := (StableGroup.embed (S := S)).map_nsmul m 1 + simpa only [nsmul_eq_mul, mul_one] using h + +omit [PartialOrder S] in +/-- Rearranging a group-completion equality gives precisely the stable equality +required by the catalytic argument. -/ +theorem stable_of_group_balance (m k : ℕ) (T s x y : S) + (h : (-((m : ℕ) : ℤ)) • StableGroup.embed (S := S) 1 = + (StableGroup.embed y - StableGroup.embed x) + + (StableGroup.embed (T * s) - StableGroup.embed ((k : S) * s))) : + StableEquality ((m : S) + y + T * s) (x + (k : S) * s) := by + apply (StableGroup.embed_eq_embed_iff _ _).mp + rw [(StableGroup.embed (S := S)).map_add ((m : S) + y) (T * s), + (StableGroup.embed (S := S)).map_add (m : S) y, + (StableGroup.embed (S := S)).map_add x ((k : S) * s)] + have hm : (-((m : ℕ) : ℤ)) • StableGroup.embed (S := S) 1 = + -StableGroup.embed (S := S) (m : S) := by + rw [neg_smul, natCast_zsmul, ← embed_natCast] + rw [hm] at h + have h' := congrArg (fun z => StableGroup.embed (S := S) (m : S) + + StableGroup.embed x + StableGroup.embed ((k : S) * s) + z) h + have heq : StableGroup.embed x + StableGroup.embed ((k : S) * s) = + StableGroup.embed (S := S) (m : S) + StableGroup.embed y + + StableGroup.embed (T * s) := by + convert h' using 1 <;> abel + exact heq.symm + +/-- Evaluate and combine a finite integer cone certificate. Each row consists +of a monotonicity difference and a detection difference; either summand may be +zero. The unrestricted additive-relation coefficients disappear only because +their images have been proved to be zero in the group completion. -/ +theorem stable_certificate_of_integer_cone + {ι κ : Type u} [Fintype ι] [Fintype κ] {n : ℕ} + (hadd : ∀ a b c : S, a ≤ b → a + c ≤ b + c) + (v : Fin n → S) (g : ι → Fin n → ℤ) (r : κ → Fin n → ℤ) + (unit : Fin n → ℤ) (m k : ℕ) (T : S) + (c : ι → ℤ) (d : κ → ℤ) (hc : ∀ i, 0 ≤ c i) + (x y s : ι → S) (hxy : ∀ i, x i ≤ y i) + (hunit : evaluate (fun j => StableGroup.embed (v j)) unit = StableGroup.embed 1) + (hg : ∀ i, evaluate (fun j => StableGroup.embed (v j)) (g i) = + (StableGroup.embed (y i) - StableGroup.embed (x i)) + + (StableGroup.embed (T * s i) - StableGroup.embed ((k : S) * s i))) + (hr : ∀ j, evaluate (fun j => StableGroup.embed (v j)) (r j) = 0) + (hcertificate : ∀ j, -((m : ℕ) : ℤ) * unit j = + (∑ i, c i * g i j) + ∑ q, d q * r q j) : + ∃ X Y s' : S, X ≤ Y ∧ + StableEquality ((m : S) + Y + T * s') (X + (k : S) * s') := by + classical + let cN : ι → ℕ := fun i => (c i).toNat + have hcN (i : ι) : (cN i : ℤ) = c i := Int.toNat_of_nonneg (hc i) + let X : S := ∑ i, cN i • x i + let Y : S := ∑ i, cN i • y i + let s' : S := ∑ i, cN i • s i + refine ⟨X, Y, s', ?_, ?_⟩ + · exact sum_le_sum_of_add hadd Finset.univ _ _ + (fun i hi => nsmul_le_nsmul_of_add hadd (hxy i) (cN i)) + · apply stable_of_group_balance m k T s' X Y + have heq := evaluate_certificate (fun j => StableGroup.embed (v j)) + g r unit (m : ℤ) c d hcertificate + simp only [hunit, hr, smul_zero, Finset.sum_const_zero, add_zero] at heq + rw [heq] + simp_rw [hg] + have hscale (i : ι) (z : StableGroup S) : c i • z = cN i • z := by + rw [← hcN i, natCast_zsmul] + simp_rw [hscale, smul_add, smul_sub, Finset.sum_add_distrib, + Finset.sum_sub_distrib] + have hsum (a : ι → S) : (∑ i, cN i • StableGroup.embed (a i)) = + StableGroup.embed (∑ i, cN i • a i) := by + simp only [map_sum, map_nsmul] + rw [hsum y, hsum x, hsum (fun i => T * s i), hsum (fun i => (k : S) * s i)] + have hmul (a : S) : (∑ i, cN i • (a * s i)) = a * s' := by + dsimp [s'] + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro i hi + simp only [nsmul_eq_mul] + ring + rw [hmul T, hmul (k : S)] + +end Stable + +end MatrixMultiplicationAllFields.TensorSpectrum.AdditiveCone diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/StableGroup.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/StableGroup.lean new file mode 100644 index 0000000000..36f8baaab8 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/AdditiveCone/StableGroup.lean @@ -0,0 +1,183 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Additive.Catalyst +public import Mathlib.Data.Quot + +/-! +# The stable additive group of a commutative semiring + +Pairs represent formal differences. Two pairs agree if their cross sums become +equal after adding one common catalyst. This relation works without cancellation +in the original semiring. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +variable {S : Type*} [CommSemiring S] + +/-- Equates two formal differences when adding a common stabilizing element makes the cross sums +equal. -/ +def stablePairRel (p q : S × S) : Prop := + ∃ c : S, p.1 + q.2 + c = q.1 + p.2 + c + +theorem stablePairRel_refl (p : S × S) : stablePairRel p p := + ⟨0, rfl⟩ + +theorem stablePairRel_symm {p q : S × S} + (h : stablePairRel p q) : stablePairRel q p := by + obtain ⟨c, hc⟩ := h + exact ⟨c, hc.symm⟩ + +theorem stablePairRel_trans {p q r : S × S} + (hpq : stablePairRel p q) (hqr : stablePairRel q r) : + stablePairRel p r := by + obtain ⟨c, hc⟩ := hpq + obtain ⟨d, hd⟩ := hqr + refine ⟨q.2 + c + d, ?_⟩ + calc + p.1 + r.2 + (q.2 + c + d) = (p.1 + q.2 + c) + (r.2 + d) := by ring + _ = (q.1 + p.2 + c) + (r.2 + d) := by rw [hc] + _ = (q.1 + r.2 + d) + (p.2 + c) := by ring + _ = (r.1 + q.2 + d) + (p.2 + c) := by rw [hd] + _ = r.1 + p.2 + (q.2 + c + d) := by ring + +/-- The equivalence relation on pairs used to form the additive group of formal differences. -/ +def stablePairSetoid (S : Type*) [CommSemiring S] : Setoid (S × S) where + r := stablePairRel + iseqv := ⟨stablePairRel_refl, stablePairRel_symm, stablePairRel_trans⟩ + +/-- The additive group obtained by identifying formal differences whose cross +sums agree after adjoining one common catalyst. -/ +def StableGroup (S : Type*) [CommSemiring S] := Quotient (stablePairSetoid S) + +namespace StableGroup + +/-- The formal difference represented by `(a, b)`. -/ +def mk (a b : S) : StableGroup S := Quotient.mk _ (a, b) + +@[simp] +theorem mk_eq_mk_iff (a b c d : S) : + mk a b = mk c d ↔ ∃ u : S, a + d + u = c + b + u := + Quotient.eq + +theorem stablePairRel_add {p p' q q' : S × S} + (hp : stablePairRel p p') (hq : stablePairRel q q') : + stablePairRel (p.1 + q.1, p.2 + q.2) (p'.1 + q'.1, p'.2 + q'.2) := by + obtain ⟨c, hc⟩ := hp + obtain ⟨d, hd⟩ := hq + refine ⟨c + d, ?_⟩ + change (p.1 + q.1) + (p'.2 + q'.2) + (c + d) = + (p'.1 + q'.1) + (p.2 + q.2) + (c + d) + calc + (p.1 + q.1) + (p'.2 + q'.2) + (c + d) = + (p.1 + p'.2 + c) + (q.1 + q'.2 + d) := by ring + _ = (p'.1 + p.2 + c) + (q'.1 + q.2 + d) := by rw [hc, hd] + _ = (p'.1 + q'.1) + (p.2 + q.2) + (c + d) := by ring + +theorem stablePairRel_swap {p q : S × S} + (h : stablePairRel p q) : stablePairRel (p.2, p.1) (q.2, q.1) := by + obtain ⟨c, hc⟩ := h + refine ⟨c, ?_⟩ + change p.2 + q.1 + c = q.2 + p.1 + c + simpa only [add_comm] using hc.symm + +instance : Zero (StableGroup S) := ⟨mk 0 0⟩ + +instance : Add (StableGroup S) := + ⟨Quotient.map₂ (fun p q : S × S => (p.1 + q.1, p.2 + q.2)) + (fun _ _ hp _ _ hq => stablePairRel_add hp hq)⟩ + +instance : Neg (StableGroup S) := + ⟨Quotient.map (fun p : S × S => (p.2, p.1)) + (fun _ _ h => stablePairRel_swap h)⟩ + +@[simp] +theorem mk_zero_zero : mk (0 : S) 0 = 0 := rfl + +@[simp] +theorem mk_add (a b c d : S) : mk a b + mk c d = mk (a + c) (b + d) := rfl + +@[simp] +theorem mk_neg (a b : S) : -mk a b = mk b a := rfl + +instance : AddCommGroup (StableGroup S) where + zero := 0 + add := (· + ·) + neg := Neg.neg + add_assoc x y z := by + refine Quotient.inductionOn₃ x y z ?_ + intro p q r + change mk ((p.1 + q.1) + r.1) ((p.2 + q.2) + r.2) = + mk (p.1 + (q.1 + r.1)) (p.2 + (q.2 + r.2)) + simp only [add_assoc] + zero_add x := by + refine Quotient.inductionOn x ?_ + intro p + change mk (0 + p.1) (0 + p.2) = mk p.1 p.2 + simp only [zero_add] + add_zero x := by + refine Quotient.inductionOn x ?_ + intro p + change mk (p.1 + 0) (p.2 + 0) = mk p.1 p.2 + simp only [add_zero] + add_comm x y := by + refine Quotient.inductionOn₂ x y ?_ + intro p q + change mk (p.1 + q.1) (p.2 + q.2) = mk (q.1 + p.1) (q.2 + p.2) + simp only [add_comm] + neg_add_cancel x := by + refine Quotient.inductionOn x ?_ + intro p + change mk (p.2 + p.1) (p.1 + p.2) = mk 0 0 + apply Quotient.sound + exact ⟨0, by change (p.2 + p.1) + 0 + 0 = 0 + (p.1 + p.2) + 0; ring⟩ + nsmul := nsmulRec + zsmul := zsmulRec + +/-- Every stable group element is represented by one pair. -/ +theorem exists_mk (x : StableGroup S) : ∃ a b : S, x = mk a b := by + refine Quotient.inductionOn x ?_ + intro p + exact ⟨p.1, p.2, rfl⟩ + +/-- The canonical additive map into the stable group. -/ +def embed : S →+ StableGroup S where + toFun a := mk a 0 + map_zero' := rfl + map_add' a b := by + change mk (a + b) 0 = mk (a + b) (0 + 0) + rw [zero_add] + +@[simp] +theorem embed_apply (a : S) : embed a = mk a 0 := rfl + +/-- Equality of embedded semiring elements is exactly stable equality. -/ +theorem embed_eq_embed_iff (a b : S) : + embed a = embed b ↔ StableEquality a b := by + change mk a 0 = mk b 0 ↔ ∃ c : S, a + c = b + c + rw [mk_eq_mk_iff] + simp only [add_zero] + +/-- A pair is zero exactly when its two entries are stably equal. -/ +theorem mk_eq_zero_iff (a b : S) : mk a b = 0 ↔ StableEquality a b := by + change mk a b = mk 0 0 ↔ ∃ c : S, a + c = b + c + rw [mk_eq_mk_iff] + simp only [zero_add, add_zero] + +/-- Formal pairs are differences of canonical embedded elements. -/ +theorem mk_eq_sub_embed (a b : S) : mk a b = embed a - embed b := by + rw [sub_eq_add_neg] + change mk a b = mk (a + 0) (0 + b) + simp only [add_zero, zero_add] + +end StableGroup + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Blocks.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Blocks.lean new file mode 100644 index 0000000000..81e95b9c88 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Blocks.lean @@ -0,0 +1,74 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensor + +/-! +# Heterogeneous tensor direct sums + +Local block diagonal matrices restrict the two summands independently. +-/ + +@[expose] public section + +open scoped BigOperators + +namespace MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +variable {K X Y Z U V W X' Y' Z' U' V' W' : Type*} [CommSemiring K] + +/-- Direct sum of tensors whose three coordinate spaces may all differ. -/ +def blockSum (T : Tensor K X Y Z) (S : Tensor K U V W) : + Tensor K (X ⊕ U) (Y ⊕ V) (Z ⊕ W) + | .inl x, .inl y, .inl z => T x y z + | .inr u, .inr v, .inr w => S u v w + | _, _, _ => 0 + +/-- Assemble branches with a common first leg and matching sector labels on the other legs. -/ +def sharedFirst {M : ℕ} (A : Fin M → Tensor K X Y Z) : + Tensor K X (Fin M × Y) (Fin M × Z) := + fun x y z => if y.1 = z.1 then A y.1 x y.2 z.2 else 0 + +/-- Block diagonal local coefficient matrix, with no cross-summand maps. -/ +def blockMatrix (A : X' → X → K) (D : U' → U → K) : + (X' ⊕ U') → (X ⊕ U) → K + | .inl x', .inl x => A x' x + | .inr u', .inr u => D u' u + | _, _ => 0 + +@[simp] theorem blockSum_inl (T : Tensor K X Y Z) (S : Tensor K U V W) + (x : X) (y : Y) (z : Z) : + blockSum T S (.inl x) (.inl y) (.inl z) = T x y z := rfl + +@[simp] theorem blockSum_inr (T : Tensor K X Y Z) (S : Tensor K U V W) + (u : U) (v : V) (w : W) : + blockSum T S (.inr u) (.inr v) (.inr w) = S u v w := rfl + +/-- Independent restrictions on the two summands combine into one restriction +on their full direct sum, including every vanishing cross coefficient. -/ +theorem restrict_blockSum + [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] [Fintype W] + (A : X' → X → K) (B : Y' → Y → K) (C : Z' → Z → K) + (D : U' → U → K) (E : V' → V → K) (F : W' → W → K) + (T : Tensor K X Y Z) (S : Tensor K U V W) : + Tensor.restrict (blockMatrix A D) (blockMatrix B E) (blockMatrix C F) + (blockSum T S) = blockSum (Tensor.restrict A B C T) (Tensor.restrict D E F S) := by + funext x y z + rcases x with x | u <;> rcases y with y | v <;> rcases z with z | w <;> + simp [Tensor.restrict, blockSum, blockMatrix, Fintype.sum_sum_type] + +/-- Relabel the coordinates of each summand independently. -/ +theorem pullback_blockSum (T : Tensor K X Y Z) (S : Tensor K U V W) + (a : X' → X) (b : Y' → Y) (c : Z' → Z) + (d : U' → U) (e : V' → V) (f : W' → W) : + Tensor.pullback (Sum.map a d) (Sum.map b e) (Sum.map c f) (blockSum T S) = + blockSum (Tensor.pullback a b c T) (Tensor.pullback d e f S) := by + funext x y z + rcases x with x | u <;> rcases y with y | v <;> rcases z with z | w <;> rfl + +end MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/CharacterDegeneration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/CharacterDegeneration.lean new file mode 100644 index 0000000000..d6f88cbf54 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/CharacterDegeneration.lean @@ -0,0 +1,85 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors + +/-! +# Character monotonicity under polynomial restriction + +A linear number of copies in a tensor-power bound disappears after taking +the limit. The finite interpolation proof supplies that bound. +-/ + +@[expose] public section + +noncomputable section + +open scoped NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +variable {R : Type*} [CommSemiring R] + +theorem Character.polynomial_constant_le (f : Character R) + {X Y Z U V W : Type*} + [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] [Fintype W] + (T : Tensor R X Y Z) (D : Tensor R U V W) (K : ℕ) + (hrestrict : ∀ j : ℕ, Tensor.power D j ∈ LocalTensor.orbit + (Tensor.directSum (fun _ : Fin (K * j + 1) => Tensor.power T j))) : + f (ofTensor D) ≤ f (ofTensor T) := by + have hpower : ∀ j : ℕ, + (f (ofTensor D)) ^ j ≤ (K * j + 1 : ℝ≥0) * (f (ofTensor T)) ^ j := by + intro j + have hr := hrestrict j + have hmono := f.monotone' (ofTensor_le hr) + simpa only [Character.map_directSum_const, Character.map_power_tensor, + Nat.cast_add, Nat.cast_mul, Nat.cast_one] using hmono + have hreal := le_of_pow_le_linear_mul_pow + (f (ofTensor T) : ℝ) (f (ofTensor D) : ℝ) (K : ℝ) + (f (ofTensor T)).coe_nonneg + (fun j => by exact_mod_cast hpower j) + exact_mod_cast hreal + +open PolynomialTensors (polynomialTensor) + +/-- The coefficient at the constant input monomials is one. -/ +theorem Character.polynomial_value_pos (f : Character R) (a b : ℕ) + (ha : 1 ≤ a) (hb : 1 ≤ b) : + 0 < (f (ofTensor (polynomialTensor a b)) : ℝ) := by + have hunit : ∃ i j k, polynomialTensor (K := R) a b i j k = 1 := + ⟨⟨0, by omega⟩, ⟨0, by omega⟩, ⟨0, by omega⟩, by simp [polynomialTensor]⟩ + have h := f.monotone' (ofTensor_le (CoefficientTensor.unit_restricts_natTensor_one hunit)) + have hone : ofTensor (CoefficientTensor.natTensor 1) = (1 : TensorClass R) := by + simpa only [Nat.cast_one] using (natCast_eq_ofTensor_natTensor 1).symm + have hnn : 1 ≤ f (ofTensor (polynomialTensor a b)) := calc + 1 = f.toHom (ofTensor (CoefficientTensor.natTensor 1)) := by + rw [hone] + exact f.toHom.map_one.symm + _ ≤ f.toHom (ofTensor (polynomialTensor a b)) := h + have hr : (1 : ℝ) ≤ f (ofTensor (polynomialTensor a b)) := by exact_mod_cast hnn + exact zero_lt_one.trans_le hr + +theorem Character.polynomial_value_le_of_rankAtMost (f : Character R) (a b : ℕ) + (ha : 1 ≤ a) (hb : 1 ≤ b) + (h : Tensor.RankAtMost (polynomialTensor (K := R) a b) (a + b - 1)) : + (f (ofTensor (polynomialTensor a b)) : ℝ) ≤ (a : ℝ) + (b : ℝ) - 1 := by + have hRank : rank (ofTensor (polynomialTensor (K := R) a b)) ≤ a + b - 1 := by + rw [rank_ofTensor] + exact (CoefficientTensor.rank_le_iff _ _).mpr h + have hnn : f (ofTensor (polynomialTensor a b)) ≤ (a + b - 1 : ℕ) := + (f.le_rank _).trans (Nat.cast_le.mpr hRank) + have hr : (f (ofTensor (polynomialTensor a b)) : ℝ) ≤ ((a + b - 1 : ℕ) : ℝ) := by + exact_mod_cast hnn + have hab : 1 ≤ a + b := by omega + simpa only [Nat.cast_sub hab, Nat.cast_add, Nat.cast_one] using hr + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/CharacterPower.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/CharacterPower.lean new file mode 100644 index 0000000000..d1a910b89a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/CharacterPower.lean @@ -0,0 +1,127 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.Archimedean.Basic +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.NormNum +public import Mathlib.Tactic.Positivity + +/-! +# The power law for a monotone multiplicative function + +On the positive integers, a multiplicative, monotone real-valued function with +`1 ≤ f n ≤ n` is a real power. No power representation is an input. The proof +compares `n ^ k` with two successive powers of `m`; the resulting bounded error +forces the logarithmic slopes to agree by the Archimedean property. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +private theorem positiveNat_map_pow + (f : ℕ → ℝ) (hone : f 1 = 1) + (hmul : ∀ m n : ℕ, 1 ≤ m → 1 ≤ n → f (m * n) = f m * f n) + (n : ℕ) (hn : 1 ≤ n) (k : ℕ) : f (n ^ k) = f n ^ k := by + induction k with + | zero => simpa using hone + | succ k ih => + rw [pow_succ, hmul (n ^ k) n (Nat.one_le_pow k n (by omega)) hn, + ih, pow_succ] + +/-- Monotonicity and multiplicativity force equal logarithmic slopes. +The orientation here is useful without dividing by either logarithm. -/ +theorem monotone_multiplicative_log_cross_le + (f : ℕ → ℝ) (hone : f 1 = 1) + (hmul : ∀ m n : ℕ, 1 ≤ m → 1 ≤ n → f (m * n) = f m * f n) + (hmono : ∀ m n : ℕ, 1 ≤ m → m ≤ n → f m ≤ f n) + (hlower : ∀ n : ℕ, 1 ≤ n → 1 ≤ f n) + (n m : ℕ) (hn : 1 ≤ n) (hm : 1 < m) : + Real.log (f n) * Real.log (m : ℝ) ≤ + Real.log (f m) * Real.log (n : ℝ) := by + have hm1 : 1 ≤ m := hm.le + have hmR : 0 < (m : ℝ) := by exact_mod_cast (show 0 < m by omega) + have hfn : 0 < f n := lt_of_lt_of_le zero_lt_one (hlower n hn) + have hlogm : 0 < Real.log (m : ℝ) := + Real.log_pos (by exact_mod_cast hm) + have hlogfm : 0 ≤ Real.log (f m) := Real.log_nonneg (hlower m hm1) + have hbounded (k : ℕ) : + (k : ℝ) * (Real.log (f n) * Real.log (m : ℝ) - + Real.log (f m) * Real.log (n : ℝ)) ≤ + Real.log (f m) * Real.log (m : ℝ) := by + obtain ⟨j, hjlower, hjupper⟩ := + exists_nat_pow_near (Nat.one_le_pow k n (by omega)) hm + have hpower_lower : (m : ℝ) ^ j ≤ (n : ℝ) ^ k := by + exact_mod_cast hjlower + have hlogs_lower : (j : ℝ) * Real.log (m : ℝ) ≤ + (k : ℝ) * Real.log (n : ℝ) := by + simpa only [Real.log_pow] using + Real.log_le_log (pow_pos hmR j) hpower_lower + have hvalues : f n ^ k ≤ f m ^ (j + 1) := by + rw [← positiveNat_map_pow f hone hmul n hn k, + ← positiveNat_map_pow f hone hmul m hm1 (j + 1)] + exact hmono (n ^ k) (m ^ (j + 1)) + (Nat.one_le_pow k n (by omega)) hjupper.le + have hlogs_upper : (k : ℝ) * Real.log (f n) ≤ + ((j : ℝ) + 1) * Real.log (f m) := by + simpa only [Real.log_pow, Nat.cast_add, Nat.cast_one] using + Real.log_le_log (pow_pos hfn k) hvalues + have h₁ := mul_le_mul_of_nonneg_right hlogs_upper hlogm.le + have h₂ := mul_le_mul_of_nonneg_right hlogs_lower hlogfm + nlinarith + by_contra hnot + have hpositive : 0 < Real.log (f n) * Real.log (m : ℝ) - + Real.log (f m) * Real.log (n : ℝ) := sub_pos.mpr (lt_of_not_ge hnot) + obtain ⟨k, hk⟩ := exists_lt_nsmul hpositive + (Real.log (f m) * Real.log (m : ℝ)) + rw [nsmul_eq_mul] at hk + exact (not_lt_of_ge (hbounded k)) hk + +/-- Every monotone multiplicative function between `1` and the identity on the +positive natural numbers has a single exponent in `[0,1]`. There is no +restriction on its unused value at zero. -/ +theorem exists_power_of_monotone_multiplicative + (f : ℕ → ℝ) + (hmul : ∀ m n : ℕ, 1 ≤ m → 1 ≤ n → f (m * n) = f m * f n) + (hmono : ∀ m n : ℕ, 1 ≤ m → m ≤ n → f m ≤ f n) + (hbound : ∀ n : ℕ, 1 ≤ n → 1 ≤ f n ∧ f n ≤ (n : ℝ)) : + ∃ p : ℝ, 0 ≤ p ∧ p ≤ 1 ∧ ∀ n : ℕ, 1 ≤ n → f n = (n : ℝ) ^ p := by + have hone : f 1 = 1 := by + have h := hbound 1 le_rfl + exact le_antisymm (by simpa using h.2) h.1 + have hlower : ∀ n : ℕ, 1 ≤ n → 1 ≤ f n := fun n hn => (hbound n hn).1 + have hlog2 : 0 < Real.log (2 : ℝ) := Real.log_pos (by norm_num) + have hf2pos : 0 < f 2 := lt_of_lt_of_le zero_lt_one (hlower 2 (by omega)) + have hf2log : 0 ≤ Real.log (f 2) := Real.log_nonneg (hlower 2 (by omega)) + have hf2upper : Real.log (f 2) ≤ Real.log (2 : ℝ) := + Real.log_le_log hf2pos (by simpa using (hbound 2 (by omega)).2) + refine ⟨Real.log (f 2) / Real.log (2 : ℝ), div_nonneg hf2log hlog2.le, + (div_le_one hlog2).2 hf2upper, ?_⟩ + intro n hn + by_cases hn1 : n = 1 + · subst n + simp only [Nat.cast_one, Real.one_rpow, hone] + have hn2 : 1 < n := by omega + have hleft := monotone_multiplicative_log_cross_le f hone hmul hmono hlower + n 2 hn (by omega) + have hright := monotone_multiplicative_log_cross_le f hone hmul hmono hlower + 2 n (by omega) hn2 + have hcross : Real.log (f n) * Real.log (2 : ℝ) = + Real.log (f 2) * Real.log (n : ℝ) := by + exact le_antisymm (by simpa using hleft) (by simpa using hright) + have hlog : Real.log (f n) = + Real.log (n : ℝ) * (Real.log (f 2) / Real.log (2 : ℝ)) := by + rw [← mul_div_assoc] + apply (eq_div_iff hlog2.ne').2 + simpa only [mul_comm] using hcross + have hnR : 0 < (n : ℝ) := by exact_mod_cast (show 0 < n by omega) + have hfn : 0 < f n := lt_of_lt_of_le zero_lt_one (hlower n hn) + rw [Real.rpow_def_of_pos hnR, ← hlog, Real.exp_log hfn] + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Growth.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Growth.lean new file mode 100644 index 0000000000..70d470f4f5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Growth.lean @@ -0,0 +1,141 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.NormNum +public import Mathlib.Tactic.Positivity +public import Mathlib.Tactic.Ring + +/-! +# Exact scalar growth from the diagonal inequalities + +The auxiliary sequence `growthFactor` starts at index zero. Cubing its recurrence gives +the lower bound `n + 1 ≤ (growthFactor n)^3`. +Thus no logarithmic asymptotic estimate is needed for this component. + +This module proves only the scalar consequence of the two diagonal inequalities. +It does not assume or assert that a tensor character supplies those inequalities. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +/-- The product of the first `n` factors `1 + 1 / (3 * j)`, indexed from `j = 1`. -/ +noncomputable def growthFactor : ℕ → ℝ + | 0 => 1 + | n + 1 => (1 + 1 / (3 * ((n : ℝ) + 1))) * growthFactor n + +theorem growthFactor_pos (n : ℕ) : 0 < growthFactor n := by + induction n with + | zero => norm_num [growthFactor] + | succ n ih => + rw [growthFactor] + positivity + +theorem growthFactor_cube (n : ℕ) : (n : ℝ) + 1 ≤ growthFactor n ^ 3 := by + induction n with + | zero => norm_num [growthFactor] + | succ n ih => + let a : ℝ := (n : ℝ) + 1 + let u : ℝ := 1 / (3 * a) + have ha : 0 < a := by dsimp [a]; positivity + have hu : 0 ≤ u := by dsimp [u]; positivity + have hau : 3 * a * u = 1 := by + dsimp [u] + field_simp + have hstep : a + 1 ≤ (1 + u) ^ 3 * a := by + have h₂ : 0 ≤ a * u ^ 2 := mul_nonneg ha.le (sq_nonneg u) + have h₃ : 0 ≤ a * u ^ 3 := mul_nonneg ha.le (pow_nonneg hu 3) + nlinarith + have ih' : a ≤ growthFactor n ^ 3 := ih + have hfactor : 0 ≤ (1 + u) ^ 3 := by positivity + have hmul := mul_le_mul_of_nonneg_left ih' hfactor + change ((n + 1 : ℕ) : ℝ) + 1 ≤ + ((1 + 1 / (3 * ((n : ℝ) + 1))) * growthFactor n) ^ 3 + rw [mul_pow] + push_cast + exact hstep.trans hmul + +theorem diagonal_lower_bounds + (D g : ℕ → ℝ) + (hD : D 1 = 1) (hg : g 1 = 1) + (hupper : ∀ a : ℕ, 1 ≤ a → + D a ≤ ((3 * (a : ℝ) - 1) / 2) * g a) + (hstep : ∀ a : ℕ, 1 ≤ a → + D a + g a + g (a + 1) ≤ D (a + 1)) + (n : ℕ) : + growthFactor n ≤ g (n + 1) ∧ + ((3 * ((n : ℝ) + 1) - 1) / 2) * growthFactor n ≤ D (n + 1) := by + induction n with + | zero => norm_num [growthFactor, hD, hg] + | succ n ih => + let a : ℝ := (n : ℝ) + 1 + let u : ℝ := 1 / (3 * a) + let G : ℝ := growthFactor n + have ha : 0 < a := by dsimp [a]; positivity + have hden : 3 * a ≠ 0 := ne_of_gt (by positivity) + have hupper' := hupper (n + 1 + 1) (by omega) + have hstep' := hstep (n + 1) (by omega) + have hgprev : G ≤ g (n + 1) := ih.1 + have hDprev : ((3 * a - 1) / 2) * G ≤ D (n + 1) := ih.2 + have hupper'' : D (n + 1 + 1) ≤ + ((3 * (a + 1) - 1) / 2) * g (n + 1 + 1) := by + simpa [a, Nat.cast_add, Nat.cast_one] using hupper' + have hidentity : 3 * a * ((1 + u) * G) = (3 * a + 1) * G := by + dsimp [u] + field_simp + have hgnext : (1 + u) * G ≤ g (n + 1 + 1) := by + apply (mul_le_mul_iff_right₀ (show 0 < 3 * a by positivity)).mp + rw [hidentity] + nlinarith [hupper'', hstep', hgprev, hDprev] + have hDidentity : + ((3 * (a + 1) - 1) / 2) * ((1 + u) * G) = + ((3 * a - 1) / 2) * G + G + (1 + u) * G := by + dsimp [u] + field_simp; ring + have hDnext : ((3 * (a + 1) - 1) / 2) * ((1 + u) * G) ≤ + D (n + 1 + 1) := by + rw [hDidentity] + exact (add_le_add (add_le_add hDprev hgprev) hgnext).trans hstep' + constructor + · simpa [growthFactor, a, u, G] using hgnext + · simpa [growthFactor, a, u, G, Nat.cast_add, Nat.cast_one] using hDnext + +theorem diagonalCubicGrowth + (D g : ℕ → ℝ) + (hD : D 1 = 1) (hg : g 1 = 1) + (hupper : ∀ a : ℕ, 1 ≤ a → + D a ≤ ((3 * (a : ℝ) - 1) / 2) * g a) + (hstep : ∀ a : ℕ, 1 ≤ a → + D a + g a + g (a + 1) ≤ D (a + 1)) : + ∀ a : ℕ, 1 ≤ a → (a : ℝ) ^ 4 ≤ (D a) ^ 3 := by + intro a ha + obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : a ≠ 0) + have hlow := (diagonal_lower_bounds D g hD hg hupper hstep n).2 + have hG : 0 ≤ growthFactor n := (growthFactor_pos n).le + have hn : 0 ≤ (n : ℝ) := Nat.cast_nonneg n + have hcoef : (n : ℝ) + 1 ≤ (3 * ((n : ℝ) + 1) - 1) / 2 := by + linarith + have hprod : ((n : ℝ) + 1) * growthFactor n ≤ D (n + 1) := + (mul_le_mul_of_nonneg_right hcoef hG).trans hlow + have hprodnonneg : 0 ≤ ((n : ℝ) + 1) * growthFactor n := by positivity + have hcube := pow_le_pow_left₀ hprodnonneg hprod 3 + have hGc := growthFactor_cube n + have hmult := mul_le_mul_of_nonneg_left hGc + (show 0 ≤ ((n : ℝ) + 1) ^ 3 by positivity) + push_cast + calc + ((n : ℝ) + 1) ^ 4 = ((n : ℝ) + 1) ^ 3 * ((n : ℝ) + 1) := by ring + _ ≤ ((n : ℝ) + 1) ^ 3 * growthFactor n ^ 3 := hmult + _ = (((n : ℝ) + 1) * growthFactor n) ^ 3 := (mul_pow _ _ _).symm + _ ≤ (D (n + 1)) ^ 3 := hcube + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/GrowthRow.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/GrowthRow.lean new file mode 100644 index 0000000000..3457fbf8ae --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/GrowthRow.lean @@ -0,0 +1,120 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring +public import Mathlib.Algebra.Order.Archimedean.Real.Basic +public import Mathlib.Order.ConditionallyCompleteLattice.Basic + +/-! +# Finite row bounds + +For a concave positive row, one application of tripling bounds the row value +by a shifted index times the current increment. Finite secant inequalities +then give the same bound for every increment. Taking the infimum supplies +the slope required by the diagonal argument, without an asymptotic limit. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +/-- The increment from the `n`th row to its successor. -/ +def rowDifference (x : ℕ → ℝ) (n : ℕ) : ℝ := x (n + 1) - x n + +theorem row_secant_bounds + (x : ℕ → ℝ) (hdec : Antitone (rowDifference x)) (n k : ℕ) : + x (n + k) ≤ x n + (k : ℝ) * rowDifference x n ∧ + x n + (k : ℝ) * rowDifference x (n + k) ≤ x (n + k) := by + induction k with + | zero => simp + | succ k ih => + have hdn := hdec (show n ≤ n + k by omega) + have hdk := hdec (show n + k ≤ n + (k + 1) by omega) + have hscaled := mul_le_mul_of_nonneg_left hdk (Nat.cast_nonneg k : (0 : ℝ) ≤ k) + have hdelta : x (n + (k + 1)) = x (n + k) + rowDifference x (n + k) := by + dsimp [rowDifference] + simp only [Nat.add_assoc] + ring + constructor + · push_cast + linarith [ih.1] + · push_cast + linarith [ih.2] + +theorem row_local_bound + (x : ℕ → ℝ) (a : ℕ) + (hdec : Antitone (rowDifference x)) + (htrip : ∀ n : ℕ, 3 * x n ≤ x (3 * n + a + 1)) + (n : ℕ) : + x n ≤ ((n : ℝ) + ((a : ℝ) + 1) / 2) * rowDifference x n := by + have hsec := (row_secant_bounds x hdec n (2 * n + a + 1)).1 + have hindex : n + (2 * n + a + 1) = 3 * n + a + 1 := by omega + rw [hindex] at hsec + push_cast at hsec + have ht := htrip n + nlinarith + +theorem row_bound_by_every_increment + (x : ℕ → ℝ) (a : ℕ) + (hdec : Antitone (rowDifference x)) + (htrip : ∀ n : ℕ, 3 * x n ≤ x (3 * n + a + 1)) + (n m : ℕ) : + x n ≤ ((n : ℝ) + ((a : ℝ) + 1) / 2) * rowDifference x m := by + rcases le_total n m with hnm | hmn + · obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le hnm + have hlo := (row_secant_bounds x hdec n k).2 + have hup := row_local_bound x a hdec htrip (n + k) + push_cast at hup + linarith + · have hd := hdec hmn + have hc : 0 ≤ (n : ℝ) + ((a : ℝ) + 1) / 2 := by positivity + exact (row_local_bound x a hdec htrip n).trans + (mul_le_mul_of_nonneg_left hd hc) + +/-- The infimum of the successive row increments. -/ +noncomputable def rowSlope (x : ℕ → ℝ) : ℝ := sInf (Set.range (rowDifference x)) + +theorem row_slope_properties + (x : ℕ → ℝ) (a : ℕ) + (hpos : ∀ n : ℕ, 0 < x n) + (hdec : Antitone (rowDifference x)) + (htrip : ∀ n : ℕ, 3 * x n ≤ x (3 * n + a + 1)) : + 0 ≤ rowSlope x ∧ + (∀ n : ℕ, rowSlope x ≤ rowDifference x n) ∧ + (∀ n : ℕ, x n ≤ ((n : ℝ) + ((a : ℝ) + 1) / 2) * rowSlope x) := by + have hdnonneg : ∀ n : ℕ, 0 ≤ rowDifference x n := by + intro n + have hlocal := row_local_bound x a hdec htrip n + have hc : 0 ≤ (n : ℝ) + ((a : ℝ) + 1) / 2 := by positivity + by_contra! hneg + have hm := mul_nonpos_of_nonneg_of_nonpos hc hneg.le + linarith [hpos n] + have hne : (Set.range (rowDifference x)).Nonempty := ⟨rowDifference x 0, 0, rfl⟩ + have hbounded : BddBelow (Set.range (rowDifference x)) := by + refine ⟨0, ?_⟩ + rintro y ⟨n, rfl⟩ + exact hdnonneg n + refine ⟨?_, ?_, ?_⟩ + · apply le_csInf hne + rintro y ⟨n, rfl⟩ + exact hdnonneg n + · intro n + exact csInf_le hbounded ⟨n, rfl⟩ + · intro n + have hc : 0 < (n : ℝ) + ((a : ℝ) + 1) / 2 := by positivity + have hratio : x n / ((n : ℝ) + ((a : ℝ) + 1) / 2) ≤ rowSlope x := by + apply le_csInf hne + rintro y ⟨m, rfl⟩ + apply (div_le_iff₀ hc).mpr + simpa [mul_comm] using row_bound_by_every_increment x a hdec htrip n m + have hout := (div_le_iff₀ hc).mp hratio + simpa [mul_comm] using hout + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/MatrixRank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/MatrixRank.lean new file mode 100644 index 0000000000..f35996c886 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/MatrixRank.lean @@ -0,0 +1,28 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Group.Finset.Basic +public import Mathlib.Algebra.Ring.Defs +public import Mathlib.Data.Fintype.Fin + +/-! # Coefficient rank for rectangular matrix multiplication -/ + +@[expose] public section + +open scoped BigOperators + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +/-- A rank decomposition indexed by the two input positions and the output position. -/ +def MatrixRank (F : Type*) [CommSemiring F] (i j k r : ℕ) : Prop := + ∃ (a : Fin r → (Fin i × Fin k) → F) (b : Fin r → (Fin k × Fin j) → F) + (c : Fin r → (Fin i × Fin j) → F), + ∀ x y z, ∑ l : Fin r, a l x * b l y * c l z = + if x.1 = z.1 ∧ x.2 = y.1 ∧ y.2 = z.2 then 1 else 0 + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Averages.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Averages.lean new file mode 100644 index 0000000000..10a8165490 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Averages.lean @@ -0,0 +1,268 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Projective +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Growth +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Positivity + +/-! +# Positive weighted averages of a projective orbit + +These elementary finite identities supply the approximate eigenvectors used in +the compactness argument. Every average is a convex combination of actual +members of the invariant set. No fixed-point theorem is assumed here. +-/ + +@[expose] public section + +noncomputable section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open scoped BigOperators +open Set + +variable {S : Type*} [CommMonoidWithZero S] + +/-- Iteration of the normalized multiplication map, starting at `f₀`. -/ +def projectiveOrbit (z : S) (f₀ : S → ℝ) : ℕ → S → ℝ + | 0 => f₀ + | n + 1 => projective z (projectiveOrbit z f₀ n) + +/-- The unnormalized mass of the `n`th translated function. -/ +def projectiveMass (z : S) (f₀ : S → ℝ) (n : ℕ) : ℝ := f₀ (z ^ n) + +theorem projectiveOrbit_mem (K : Set (S → ℝ)) (z : S) (f₀ : S → ℝ) + (hf₀ : f₀ ∈ K) (hinvariant : MapsTo (projective z) K K) (n : ℕ) : + projectiveOrbit z f₀ n ∈ K := by + induction n with + | zero => exact hf₀ + | succ n ih => exact hinvariant ih + +/-- Undoing all normalizations in the orbit gives the original translate. -/ +theorem projectiveOrbit_normalized (z : S) (f₀ : S → ℝ) + (hunit : f₀ 1 = 1) + (hz : ∀ n, projectiveOrbit z f₀ n z ≠ 0) (n : ℕ) (x : S) : + f₀ (z ^ n * x) = projectiveMass z f₀ n * projectiveOrbit z f₀ n x := by + induction n generalizing x with + | zero => simp [projectiveMass, projectiveOrbit, hunit] + | succ n ih => + have hm : projectiveMass z f₀ (n + 1) = + projectiveMass z f₀ n * projectiveOrbit z f₀ n z := by + simpa only [projectiveMass, pow_succ] using ih z + calc + f₀ (z ^ (n + 1) * x) = f₀ (z ^ n * (z * x)) := by + rw [pow_succ, mul_assoc] + _ = projectiveMass z f₀ n * projectiveOrbit z f₀ n (z * x) := ih (z * x) + _ = projectiveMass z f₀ (n + 1) * + (projectiveOrbit z f₀ n (z * x) / projectiveOrbit z f₀ n z) := by + rw [hm] + field_simp [hz n] + _ = projectiveMass z f₀ (n + 1) * projectiveOrbit z f₀ (n + 1) x := rfl + +theorem projectiveMass_succ (z : S) (f₀ : S → ℝ) (hunit : f₀ 1 = 1) + (hz : ∀ n, projectiveOrbit z f₀ n z ≠ 0) (n : ℕ) : + projectiveMass z f₀ (n + 1) = + projectiveMass z f₀ n * projectiveOrbit z f₀ n z := by + simpa only [projectiveMass, pow_succ] using + projectiveOrbit_normalized z f₀ hunit hz n z + +theorem projectiveMass_one_le (K : Set (S → ℝ)) (z : S) (f₀ : S → ℝ) + (hf₀ : f₀ ∈ K) (hunit : f₀ 1 = 1) + (hlower : ∀ f ∈ K, 1 ≤ f z) + (hinvariant : MapsTo (projective z) K K) (n : ℕ) : + 1 ≤ projectiveMass z f₀ n := by + have ho : ∀ k, 1 ≤ projectiveOrbit z f₀ k z := fun k => + hlower _ (projectiveOrbit_mem K z f₀ hf₀ hinvariant k) + have hz : ∀ k, projectiveOrbit z f₀ k z ≠ 0 := fun k => + ne_of_gt (lt_of_lt_of_le zero_lt_one (ho k)) + induction n with + | zero => simp [projectiveMass, hunit] + | succ n ih => + rw [projectiveMass_succ z f₀ hunit hz n] + calc + (1 : ℝ) = 1 * 1 := by ring + _ ≤ projectiveMass z f₀ n * projectiveOrbit z f₀ n z := + mul_le_mul ih (ho n) zero_le_one (le_trans zero_le_one ih) + +theorem projectiveMass_le_pow (K : Set (S → ℝ)) (z : S) (f₀ : S → ℝ) + (hf₀ : f₀ ∈ K) (hunit : f₀ 1 = 1) + (hlower : ∀ f ∈ K, 1 ≤ f z) + (hinvariant : MapsTo (projective z) K K) + (M : ℝ) (hupper : ∀ f ∈ K, f z ≤ M) (n : ℕ) : + projectiveMass z f₀ n ≤ M ^ n := by + have ho : ∀ k, 1 ≤ projectiveOrbit z f₀ k z := fun k => + hlower _ (projectiveOrbit_mem K z f₀ hf₀ hinvariant k) + have hz : ∀ k, projectiveOrbit z f₀ k z ≠ 0 := fun k => + ne_of_gt (lt_of_lt_of_le zero_lt_one (ho k)) + have hM : 0 ≤ M := le_trans zero_le_one (le_trans (hlower f₀ hf₀) (hupper f₀ hf₀)) + induction n with + | zero => simp [projectiveMass, hunit] + | succ n ih => + rw [projectiveMass_succ z f₀ hunit hz n, pow_succ] + exact mul_le_mul ih + (hupper _ (projectiveOrbit_mem K z f₀ hf₀ hinvariant n)) + (le_trans zero_le_one (ho n)) (pow_nonneg hM n) + +/-- A finite positive weighted mean, with its denominator kept explicit. -/ +def positiveWeightedMean (w : ℕ → ℝ) (u : ℕ → S → ℝ) (n : ℕ) : S → ℝ := + fun x => (∑ k ∈ Finset.range (n + 1), w k * u k x) / + (∑ k ∈ Finset.range (n + 1), w k) + +theorem positive_weight_sum (w : ℕ → ℝ) (hw : ∀ k, 0 < w k) (n : ℕ) : + 0 < ∑ k ∈ Finset.range (n + 1), w k := by + induction n with + | zero => simpa using hw 0 + | succ n ih => + rw [Finset.sum_range_succ] + exact add_pos ih (hw (n + 1)) + +omit [CommMonoidWithZero S] in +/-- Binary convexity suffices for membership of all finite weighted means. -/ +theorem positiveWeightedMean_mem (K : Set (S → ℝ)) (hconvex : Convex ℝ K) + (w : ℕ → ℝ) (u : ℕ → S → ℝ) + (hw : ∀ k, 0 < w k) (hu : ∀ k, u k ∈ K) (n : ℕ) : + positiveWeightedMean w u n ∈ K := by + induction n with + | zero => + have heq : positiveWeightedMean w u 0 = u 0 := by + funext x + simp [positiveWeightedMean, ne_of_gt (hw 0)] + rw [heq] + exact hu 0 + | succ n ih => + let W : ℝ := ∑ k ∈ Finset.range (n + 1), w k + have hW : 0 < W := positive_weight_sum w hw n + have hden : 0 < W + w (n + 1) := add_pos hW (hw (n + 1)) + have ha : 0 ≤ W / (W + w (n + 1)) := div_nonneg hW.le hden.le + have hb : 0 ≤ w (n + 1) / (W + w (n + 1)) := + div_nonneg (hw (n + 1)).le hden.le + have hab : W / (W + w (n + 1)) + w (n + 1) / (W + w (n + 1)) = 1 := by + rw [← add_div, div_self hden.ne'] + have hmem := hconvex ih (hu (n + 1)) ha hb hab + have heq : positiveWeightedMean w u (n + 1) = + (W / (W + w (n + 1))) • positiveWeightedMean w u n + + (w (n + 1) / (W + w (n + 1))) • u (n + 1) := by + funext x + simp only [positiveWeightedMean, Pi.add_apply, + Pi.smul_apply, smul_eq_mul] + rw [Finset.sum_range_succ (fun k => w k * u k x) (n + 1), + Finset.sum_range_succ w (n + 1)] + change ((∑ k ∈ Finset.range (n + 1), w k * u k x) + w (n + 1) * u (n + 1) x) / + (W + w (n + 1)) = + (W / (W + w (n + 1))) * + ((∑ k ∈ Finset.range (n + 1), w k * u k x) / W) + + (w (n + 1) / (W + w (n + 1))) * u (n + 1) x + field_simp [hW.ne', hden.ne'] + rw [heq] + exact hmem + +/-- The finite unnormalized power-series sum of the translated coordinates. -/ +def projectiveSum (z : S) (f₀ : S → ℝ) (s : ℝ) (n : ℕ) (x : S) : ℝ := + ∑ k ∈ Finset.range (n + 1), f₀ (z ^ k * x) / s ^ k + +/-- Its normalized mean; its mass denominator is exactly the scalar growth API. -/ +def projectiveAverage (z : S) (f₀ : S → ℝ) (s : ℝ) (n : ℕ) : S → ℝ := + fun x => projectiveSum z f₀ s n x / + MultiplicativeGrowth.weightedSum (projectiveMass z f₀) s n + +theorem projective_weightedSum_pos (K : Set (S → ℝ)) (z : S) (f₀ : S → ℝ) + (hf₀ : f₀ ∈ K) (hunit : f₀ 1 = 1) + (hlower : ∀ f ∈ K, 1 ≤ f z) + (hinvariant : MapsTo (projective z) K K) (s : ℝ) (hs : 0 < s) (n : ℕ) : + 0 < MultiplicativeGrowth.weightedSum (projectiveMass z f₀) s n := by + apply positive_weight_sum + intro k + exact div_pos + (lt_of_lt_of_le zero_lt_one (projectiveMass_one_le K z f₀ hf₀ hunit hlower hinvariant k)) + (pow_pos hs k) + +theorem projectiveAverage_eq_weightedMean (z : S) (f₀ : S → ℝ) + (hunit : f₀ 1 = 1) (hz : ∀ n, projectiveOrbit z f₀ n z ≠ 0) + (s : ℝ) (n : ℕ) : + projectiveAverage z f₀ s n = + positiveWeightedMean (fun k => projectiveMass z f₀ k / s ^ k) + (projectiveOrbit z f₀) n := by + funext x + simp only [projectiveAverage, projectiveSum, positiveWeightedMean, + MultiplicativeGrowth.weightedSum] + congr 1 + apply Finset.sum_congr rfl + intro k _ + rw [projectiveOrbit_normalized z f₀ hunit hz k x] + ring + +theorem projectiveAverage_mem (K : Set (S → ℝ)) (hconvex : Convex ℝ K) + (z : S) (f₀ : S → ℝ) (hf₀ : f₀ ∈ K) (hunit : f₀ 1 = 1) + (hlower : ∀ f ∈ K, 1 ≤ f z) + (hinvariant : MapsTo (projective z) K K) (s : ℝ) (hs : 0 < s) (n : ℕ) : + projectiveAverage z f₀ s n ∈ K := by + have hz : ∀ k, projectiveOrbit z f₀ k z ≠ 0 := fun k => + ne_of_gt (lt_of_lt_of_le zero_lt_one + (hlower _ (projectiveOrbit_mem K z f₀ hf₀ hinvariant k))) + rw [projectiveAverage_eq_weightedMean z f₀ hunit hz s n] + apply positiveWeightedMean_mem K hconvex + · intro k + exact div_pos + (lt_of_lt_of_le zero_lt_one + (projectiveMass_one_le K z f₀ hf₀ hunit hlower hinvariant k)) + (pow_pos hs k) + · exact projectiveOrbit_mem K z f₀ hf₀ hinvariant + +theorem projectiveSum_succ (z : S) (f₀ : S → ℝ) (s : ℝ) (n : ℕ) (x : S) : + projectiveSum z f₀ s (n + 1) x = + projectiveSum z f₀ s n x + f₀ (z ^ (n + 1) * x) / s ^ (n + 1) := by + exact Finset.sum_range_succ _ _ + +/-- The telescoping identity before dividing by the total weight. -/ +theorem projectiveSum_residual (z : S) (f₀ : S → ℝ) (s : ℝ) (hs : 0 < s) + (n : ℕ) (x : S) : + projectiveSum z f₀ s n (z * x) - s * projectiveSum z f₀ s n x = + s * (f₀ (z ^ (n + 1) * x) / s ^ (n + 1) - f₀ x) := by + have hshift (k : ℕ) : + f₀ (z ^ k * (z * x)) / s ^ k = + s * (f₀ (z ^ (k + 1) * x) / s ^ (k + 1)) := by + rw [show z ^ (k + 1) * x = z ^ k * (z * x) by rw [pow_succ, mul_assoc]] + rw [pow_succ] + field_simp [hs.ne'] + induction n with + | zero => + simp only [projectiveSum, Finset.sum_range_one, pow_zero, one_mul, div_one, + zero_add, pow_one] + field_simp [hs.ne'] + | succ n ih => + rw [projectiveSum_succ, projectiveSum_succ] + have h := hshift (n + 1) + linarith + +/-- The sole boundary terms of the normalized approximate-eigenvector equation. -/ +theorem projectiveAverage_residual (z : S) (f₀ : S → ℝ) + (hunit : f₀ 1 = 1) (hz : ∀ n, projectiveOrbit z f₀ n z ≠ 0) + (s : ℝ) (hs : 0 < s) (n : ℕ) (x : S) : + projectiveAverage z f₀ s n (z * x) - s * projectiveAverage z f₀ s n x = + s * ((projectiveMass z f₀ (n + 1) / s ^ (n + 1) / + MultiplicativeGrowth.weightedSum (projectiveMass z f₀) s n) * + projectiveOrbit z f₀ (n + 1) x - + f₀ x / MultiplicativeGrowth.weightedSum (projectiveMass z f₀) s n) := by + unfold projectiveAverage + calc + projectiveSum z f₀ s n (z * x) / + MultiplicativeGrowth.weightedSum (projectiveMass z f₀) s n - + s * (projectiveSum z f₀ s n x / + MultiplicativeGrowth.weightedSum (projectiveMass z f₀) s n) = + (projectiveSum z f₀ s n (z * x) - s * projectiveSum z f₀ s n x) / + MultiplicativeGrowth.weightedSum (projectiveMass z f₀) s n := by ring + _ = _ := by + rw [projectiveSum_residual z f₀ s hs n x, + projectiveOrbit_normalized z f₀ hunit hz (n + 1) x] + ring + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Character.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Character.lean new file mode 100644 index 0000000000..133ddf5544 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Character.lean @@ -0,0 +1,105 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.FixedPoint +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Finite +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.States +public import Mathlib.Basic.NNReal.Defs + +/-! +# Multiplicativity of a compact convex tensor-state space + +Finite weighted orbit averages give the projective fixed points. Iterating +through their fixed-point slices constructs a character from a nonempty +compact convex space of additive detecting states. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open Set +open scoped NNReal + +section Monoid + +variable {S : Type*} [CommMonoidWithZero S] + +theorem multiplicative_point_of_compact_convex + (K : Set (S → ℝ)) (B : S → ℝ) + (hK : K.Nonempty) (hcompact : IsCompact K) (hconvex : Convex ℝ K) + (hzero : ∀ f ∈ K, f 0 = 0) (hunit : ∀ f ∈ K, f 1 = 1) + (hbound : ∀ f ∈ K, ∀ x, 0 ≤ f x ∧ f x ≤ B x) + (hlower : ∀ f ∈ K, ∀ z : S, z ≠ 0 → 1 ≤ f z) + (hinvariant : ∀ z : S, z ≠ 0 → MapsTo (projective z) K K) : + ∃ f ∈ K, ∀ z x, f (z * x) = f z * f x := by + apply multiplicative_of_finite_common_points K hcompact hzero + apply finite_common_points_of_slice_fixedPoints K hK hcompact hconvex hunit + (fun f hf z hz => (zero_lt_one.trans_le (hlower f hf z hz)).ne') hinvariant + intro L hLK hL hLc hLv hLi z hz + exact projective_fixedPoint_of_compact_convex L z B hL hLc hLv + (fun f hf => hunit f (hLK hf)) + (fun f hf => hbound f (hLK hf)) + (fun f hf => hlower f (hLK hf) z hz) (hLi z hz) + +end Monoid + +section Semiring + +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +/-- Construct a monotone real semiring character from a nonempty space of +additive detecting states. -/ +theorem exists_character_of_nonempty_stateSet + (T : S) (k : ℕ) (R : S → ℕ) + (hzero : ∀ x : S, 0 ≤ x) + (hunit : ∀ z : S, z ≠ 0 → 1 ≤ z) + (hR : ∀ x : S, x ≤ (R x : S)) + (hmul : ∀ z : S, Monotone (fun x : S => z * x)) + (hnonempty : (stateSet T k).Nonempty) : + ∃ χ : S →+* ℝ, Monotone χ ∧ (k : ℝ) ≤ χ T := by + have hbound : ∀ f ∈ stateSet T k, ∀ x, 0 ≤ f x ∧ f x ≤ (R x : ℝ) := + fun f hf => stateSet_subset_coordinateBox T k R hzero hR hf + obtain ⟨f, hf, hfmul⟩ := multiplicative_point_of_compact_convex (stateSet T k) + (fun x => (R x : ℝ)) hnonempty (stateSet_isCompact T k R hzero hR) + (stateSet_convex T k) (fun _ hf => hf.1) (fun _ hf => hf.2.1) hbound + (fun f hf z hz => state_one_le hf hunit hz) + (fun z hz => projective_mapsTo_stateSet T k hunit hmul hz) + have hfixed : ∀ z : S, z ≠ 0 → projective z f = f := by + intro z hz + exact (projective_fixed_iff z f (state_pos hf hunit hz).ne').mpr (hfmul z) + obtain ⟨χ, hmono, hdetect, _⟩ := character_of_common_fixedPoint T k hunit f hf hfixed + exact ⟨χ, hmono, hdetect⟩ + +/-- The same character with its nonnegative codomain made explicit. -/ +theorem exists_nnreal_character_of_nonempty_stateSet + (T : S) (k : ℕ) (R : S → ℕ) + (hzero : ∀ x : S, 0 ≤ x) + (hunit : ∀ z : S, z ≠ 0 → 1 ≤ z) + (hR : ∀ x : S, x ≤ (R x : S)) + (hmul : ∀ z : S, Monotone (fun x : S => z * x)) + (hnonempty : (stateSet T k).Nonempty) : + ∃ χ : S →+* ℝ≥0, Monotone χ ∧ (k : ℝ≥0) ≤ χ T := by + obtain ⟨χ, hmono, hk⟩ := exists_character_of_nonempty_stateSet T k R + hzero hunit hR hmul hnonempty + have hnonneg : ∀ x, 0 ≤ χ x := by + intro x + simpa only [map_zero] using hmono (hzero x) + let ψ : S →+* ℝ≥0 := + { toFun := fun x => ⟨χ x, hnonneg x⟩ + map_zero' := by apply Subtype.ext; exact map_zero χ + map_one' := by apply Subtype.ext; exact map_one χ + map_add' := by intro x y; apply Subtype.ext; exact map_add χ x y + map_mul' := by intro x y; apply Subtype.ext; exact map_mul χ x y } + refine ⟨ψ, fun _ _ h => hmono h, ?_⟩ + change ((k : ℝ≥0) : ℝ) ≤ χ T + simpa only [NNReal.coe_natCast] using hk + +end Semiring + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Compactness.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Compactness.lean new file mode 100644 index 0000000000..2490b3e88a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Compactness.lean @@ -0,0 +1,88 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Projective +public import Mathlib.Tactic.Linarith + +/-! +# Compactness for approximate projective eigenstates + +An arbitrary product of real lines need not be sequentially compact. This file +therefore uses the finite-intersection property of the compact state set, rather +than selecting an unjustified convergent subsequence of approximate states. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open Set + +variable {S : Type*} [CommMonoidWithZero S] + +private theorem finite_positive_lower_bound (F : Finset {ε : ℝ // 0 < ε}) : + ∃ δ : ℝ, 0 < δ ∧ ∀ ε ∈ F, δ ≤ ε.val := by + classical + induction F using Finset.induction_on with + | empty => exact ⟨1, zero_lt_one, by simp⟩ + | @insert ε F _ ih => + obtain ⟨δ, hδ, hF⟩ := ih + refine ⟨min ε.val δ, lt_min ε.property hδ, ?_⟩ + intro η hη + rcases Finset.mem_insert.mp hη with rfl | hη + · exact min_le_left _ _ + · exact (min_le_right _ _).trans (hF η hη) + +/-- Coordinatewise residual bounds with a common error parameter are enough to +obtain an exact eigenstate in an arbitrary compact subset of the product space. -/ +theorem eigenstate_of_approximate (K : Set (S → ℝ)) (z : S) (r : ℝ) + (B : S → ℝ) (hB : ∀ x, 0 ≤ B x) (hcompact : IsCompact K) + (happrox : ∀ ε : ℝ, 0 < ε → + ∃ f ∈ K, ∀ x, |f (z * x) - r * f x| ≤ ε * B x) : + ∃ f ∈ K, f ∈ eigenSlice z r := by + let A : {ε : ℝ // 0 < ε} → Set (S → ℝ) := + fun ε => {f | ∀ x, |f (z * x) - r * f x| ≤ ε.val * B x} + have hclosed : ∀ ε, IsClosed (A ε) := by + intro ε + have heq : A ε = ⋂ x : S, + {f : S → ℝ | |f (z * x) - r * f x| ≤ ε.val * B x} := by + ext f + simp only [A, mem_ofPred_eq, mem_iInter] + rw [heq] + exact isClosed_iInter fun x => isClosed_le + (((continuous_apply (z * x)).sub (continuous_const.mul (continuous_apply x))).abs) + continuous_const + have hfinite : ∀ F : Finset {ε : ℝ // 0 < ε}, + (K ∩ ⋂ ε ∈ F, A ε).Nonempty := by + intro F + obtain ⟨δ, hδ, hF⟩ := finite_positive_lower_bound F + obtain ⟨f, hf, hres⟩ := happrox δ hδ + refine ⟨f, hf, ?_⟩ + simp only [mem_iInter, A, mem_ofPred_eq] + intro ε hε x + exact (hres x).trans (mul_le_mul_of_nonneg_right (hF ε hε) (hB x)) + obtain ⟨f, hf, hall⟩ := hcompact.inter_iInter_nonempty A hclosed hfinite + refine ⟨f, hf, ?_⟩ + intro x + have hres : ∀ ε : ℝ, 0 < ε → |f (z * x) - r * f x| ≤ ε * B x := by + intro ε hε + exact (mem_iInter.mp hall ⟨ε, hε⟩) x + have habs : |f (z * x) - r * f x| = 0 := by + apply le_antisymm _ (abs_nonneg _) + by_contra hnot + have hp : 0 < |f (z * x) - r * f x| := lt_of_not_ge hnot + have hden : 0 < B x + 1 := by linarith [hB x] + let ε := |f (z * x) - r * f x| / (B x + 1) + have hε : 0 < ε := div_pos hp hden + have heq : ε * (B x + 1) = |f (z * x) - r * f x| := + div_mul_cancel₀ _ hden.ne' + have hbound := hres ε hε + nlinarith + exact sub_eq_zero.mp (abs_eq_zero.mp habs) + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Error.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Error.lean new file mode 100644 index 0000000000..c6de19994a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Error.lean @@ -0,0 +1,47 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Ring + +/-! # Residual bound for projective tensor averages -/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +/-- The error estimate for a normalized finite orbit average. The two boundary +weights and the change in the candidate eigenvalue are charged explicitly. -/ +theorem projective_residual_error_bound + (t u v w q d s r M B η : ℝ) + (hu : 0 ≤ u ∧ u ≤ B) (hv : 0 ≤ v ∧ v ≤ B) (hw : 0 ≤ w ∧ w ≤ B) + (hq : 0 ≤ q ∧ q ≤ η) (hd : 0 ≤ d ∧ d ≤ η) + (hs : 0 ≤ s ∧ s ≤ M) (hr : 0 ≤ r - s ∧ r - s ≤ η) + (hres : t - s * u = s * (q * v - d * w)) : + |t - r * u| ≤ (2 * M + 1) * η * B := by + have hB : 0 ≤ B := hu.1.trans hu.2 + have hη : 0 ≤ η := hq.1.trans hq.2 + have hqv : 0 ≤ q * v := mul_nonneg hq.1 hv.1 + have hdw : 0 ≤ d * w := mul_nonneg hd.1 hw.1 + have hqv_le : q * v ≤ η * B := mul_le_mul hq.2 hv.2 hv.1 hη + have hdw_le : d * w ≤ η * B := mul_le_mul hd.2 hw.2 hw.1 hη + have hsqv : s * (q * v) ≤ M * (η * B) := + mul_le_mul hs.2 hqv_le hqv (hs.1.trans hs.2) + have hsdw : s * (d * w) ≤ M * (η * B) := + mul_le_mul hs.2 hdw_le hdw (hs.1.trans hs.2) + have hru : (r - s) * u ≤ η * B := mul_le_mul hr.2 hu.2 hu.1 hη + have hs_qv : 0 ≤ s * (q * v) := mul_nonneg hs.1 hqv + have hs_dw : 0 ≤ s * (d * w) := mul_nonneg hs.1 hdw + have hr_u : 0 ≤ (r - s) * u := mul_nonneg hr.1 hu.1 + have hmain : t - r * u = s * (q * v) - s * (d * w) - (r - s) * u := by + nlinarith [hres] + apply abs_le.mpr + constructor <;> nlinarith + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Finite.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Finite.lean new file mode 100644 index 0000000000..3957f6ed42 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Finite.lean @@ -0,0 +1,65 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Projective + +/-! +# Finite iteration through frozen affine slices + +Finite induction keeps an invariant affine slice after each map. A fixed-point +witness on each slice supplies a common fixed point for the finite family. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open Set + +variable {S : Type*} [CommMonoidWithZero S] + +theorem finite_common_points_of_slice_fixedPoints + (K : Set (S → ℝ)) (hK : K.Nonempty) (hcompact : IsCompact K) + (hconvex : Convex ℝ K) (hunit : ∀ f ∈ K, f 1 = 1) + (hpos : ∀ f ∈ K, ∀ z : S, z ≠ 0 → f z ≠ 0) + (hinvariant : ∀ z : S, z ≠ 0 → MapsTo (projective z) K K) + (hfixed : ∀ L : Set (S → ℝ), L ⊆ K → L.Nonempty → IsCompact L → + Convex ℝ L → (∀ z : S, z ≠ 0 → MapsTo (projective z) L L) → + ∀ z : S, z ≠ 0 → ∃ f ∈ L, projective z f = f) : + ∀ F : Finset {z : S // z ≠ 0}, + ∃ f ∈ K, ∀ z ∈ F, f ∈ multiplicativeSet z.val := by + classical + have hslices : ∀ F : Finset {z : S // z ≠ 0}, + ∃ L : Set (S → ℝ), L ⊆ K ∧ L.Nonempty ∧ IsCompact L ∧ Convex ℝ L ∧ + (∀ z : S, z ≠ 0 → MapsTo (projective z) L L) ∧ + (∀ f ∈ L, ∀ z ∈ F, f ∈ multiplicativeSet z.val) := by + intro F + induction F using Finset.induction_on with + | empty => + exact ⟨K, subset_rfl, hK, hcompact, hconvex, hinvariant, by simp⟩ + | @insert z F _ ih => + obtain ⟨L, hLK, hL, hLc, hLv, hLi, hLF⟩ := ih + obtain ⟨f, hf, hfx⟩ := hfixed L hLK hL hLc hLv hLi z.val z.property + let L' := L ∩ eigenSlice z.val (f z.val) + have hfrozen := freeze_fixedPoint L z.val f hLc hLv hf hfx + (hpos f (hLK hf) z.val z.property) hLi + change f ∈ L' ∧ IsCompact L' ∧ Convex ℝ L' ∧ + (∀ w, w ≠ 0 → MapsTo (projective w) L' L') at hfrozen + refine ⟨L', fun g hg => hLK hg.1, ⟨f, hfrozen.1⟩, + hfrozen.2.1, hfrozen.2.2.1, hfrozen.2.2.2, ?_⟩ + intro g hg w hw + rcases Finset.mem_insert.mp hw with hw | hw + · rw [hw] + exact eigenSlice_mem_multiplicativeSet z.val (f z.val) g hg.2 + (hunit g (hLK hg.1)) + · exact hLF g hg.1 w hw + intro F + obtain ⟨L, hLK, ⟨f, hf⟩, _, _, _, hLF⟩ := hslices F + exact ⟨f, hLK hf, hLF f hf⟩ + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/FixedPoint.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/FixedPoint.lean new file mode 100644 index 0000000000..b5bd7acf0d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/FixedPoint.lean @@ -0,0 +1,106 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Averages +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Compactness +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Error + +/-! +# A compact convex fixed-point theorem for normalized multiplication + +Finite geometric averages supply approximate eigenstates; compactness of the +whole state set supplies an exact eigenstate. No general Schauder theorem or +fixed-point premise is assumed. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open Set + +variable {S : Type*} [CommMonoidWithZero S] + +/-- A nonempty compact convex set of normalized positive functions, preserved by +normalized multiplication, contains a fixed point of that map. -/ +theorem projective_fixedPoint_of_compact_convex + (K : Set (S → ℝ)) (z : S) (B : S → ℝ) + (hK : K.Nonempty) (hcompact : IsCompact K) (hconvex : Convex ℝ K) + (hunit : ∀ f ∈ K, f 1 = 1) + (hbound : ∀ f ∈ K, ∀ x, 0 ≤ f x ∧ f x ≤ B x) + (hlower : ∀ f ∈ K, 1 ≤ f z) + (hinvariant : MapsTo (projective z) K K) : + ∃ f ∈ K, projective z f = f := by + obtain ⟨f₀, hf₀⟩ := hK + have hunit₀ : f₀ 1 = 1 := hunit f₀ hf₀ + have hB : ∀ x, 0 ≤ B x := fun x => (hbound f₀ hf₀ x).1.trans (hbound f₀ hf₀ x).2 + have hM : 1 ≤ B z := (hlower f₀ hf₀).trans (hbound f₀ hf₀ z).2 + have ha : ∀ n, 1 ≤ projectiveMass z f₀ n := + projectiveMass_one_le K z f₀ hf₀ hunit₀ hlower hinvariant + have haM : ∀ n, projectiveMass z f₀ n ≤ (B z) ^ n := + projectiveMass_le_pow K z f₀ hf₀ hunit₀ hlower hinvariant (B z) + (fun f hf => (hbound f hf z).2) + have ho : ∀ n, projectiveOrbit z f₀ n ∈ K := + projectiveOrbit_mem K z f₀ hf₀ hinvariant + have hz : ∀ n, projectiveOrbit z f₀ n z ≠ 0 := fun n => + (zero_lt_one.trans_le (hlower _ (ho n))).ne' + obtain ⟨r, hr1, hrM, hweights⟩ := + MultiplicativeGrowth.exists_approximate_weights (projectiveMass z f₀) (B z) + ha hM haM + have happrox : ∀ ε : ℝ, 0 < ε → + ∃ f ∈ K, ∀ x, |f (z * x) - r * f x| ≤ ε * B x := by + intro ε hε + let η : ℝ := ε / (2 * B z + 1) + have hden : 0 < 2 * B z + 1 := by linarith + have hη : 0 < η := div_pos hε hden + have hηeq : (2 * B z + 1) * η = ε := by + dsimp [η] + field_simp [hden.ne'] + obtain ⟨s, n, hs, hsr, hclose, hlarge, hterminal⟩ := hweights η hη (1 / η) + let A : ℝ := MultiplicativeGrowth.weightedSum (projectiveMass z f₀) s n + have hA : 0 < A := + projective_weightedSum_pos K z f₀ hf₀ hunit₀ hlower hinvariant s hs n + let q : ℝ := projectiveMass z f₀ (n + 1) / s ^ (n + 1) / A + let d : ℝ := 1 / A + have hq0 : 0 ≤ q := + div_nonneg (div_nonneg (zero_le_one.trans (ha (n + 1))) (pow_nonneg hs.le _)) hA.le + have hqη : q ≤ η := ((div_lt_iff₀ hA).mpr hterminal).le + have hd0 : 0 ≤ d := div_nonneg zero_le_one hA.le + have hdη : d ≤ η := by + apply (div_le_iff₀ hA).mpr + have h := (div_lt_iff₀ hη).mp hlarge + nlinarith + let f := projectiveAverage z f₀ s n + have hf : f ∈ K := projectiveAverage_mem K hconvex z f₀ hf₀ hunit₀ hlower + hinvariant s hs n + refine ⟨f, hf, ?_⟩ + intro x + have hres : f (z * x) - s * f x = + s * (q * projectiveOrbit z f₀ (n + 1) x - d * f₀ x) := by + calc + f (z * x) - s * f x = + s * (q * projectiveOrbit z f₀ (n + 1) x - f₀ x / A) := + projectiveAverage_residual z f₀ hunit₀ hz s hs n x + _ = s * (q * projectiveOrbit z f₀ (n + 1) x - d * f₀ x) := by + dsimp [d] + ring + have herr := projective_residual_error_bound + (f (z * x)) (f x) (projectiveOrbit z f₀ (n + 1) x) (f₀ x) + q d s r (B z) (B x) η (hbound f hf x) + (hbound _ (ho (n + 1)) x) (hbound f₀ hf₀ x) + ⟨hq0, hqη⟩ ⟨hd0, hdη⟩ ⟨hs.le, hsr.le.trans hrM⟩ + ⟨sub_nonneg.mpr hsr.le, hclose.le⟩ hres + calc + |f (z * x) - r * f x| ≤ (2 * B z + 1) * η * B x := herr + _ = ε * B x := by rw [hηeq] + obtain ⟨f, hf, heigen⟩ := eigenstate_of_approximate K z r B hB hcompact happrox + refine ⟨f, hf, ?_⟩ + exact (projective_fixed_iff z f (zero_lt_one.trans_le (hlower f hf)).ne').mpr + (eigenSlice_mem_multiplicativeSet z r f heigen (hunit f hf)) + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Growth.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Growth.lean new file mode 100644 index 0000000000..3f25bc0ba6 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Growth.lean @@ -0,0 +1,269 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.NormNum +public import Mathlib.Tactic.Positivity +public import Mathlib.Tactic.Ring + +/-! +# Finite orbit weights for the projective fixed-point argument + +For a positive sequence with exponential upper bounds, choose its critical +geometric growth rate. Finite geometric weighted sums then have arbitrarily +large mass and arbitrarily small final-term fraction at rates approaching the +critical rate from below. This is the scalar ingredient of the compact convex +projective fixed-point proof; it uses no general fixed-point theorem. + +The sums include indices `0, ..., n`. The terminal term is indexed by `n + 1`. +-/ + +@[expose] public section + +noncomputable section + +namespace MatrixMultiplicationAllFields.TensorSpectrum.MultiplicativeGrowth + +open Set + +/-- The normalization of a finite geometrically weighted orbit. -/ +def weightedSum (a : ℕ → ℝ) (s : ℝ) (n : ℕ) : ℝ := + ∑ k ∈ Finset.range (n + 1), a k / s ^ k + +theorem weightedSum_zero (a : ℕ → ℝ) (s : ℝ) : + weightedSum a s 0 = a 0 := by + simp [weightedSum] + +theorem weightedSum_succ (a : ℕ → ℝ) (s : ℝ) (n : ℕ) : + weightedSum a s (n + 1) = weightedSum a s n + a (n + 1) / s ^ (n + 1) := by + simp only [weightedSum, Finset.sum_range_succ] + +theorem weightedSum_mono (a : ℕ → ℝ) (s : ℝ) + (ha : ∀ n, 0 ≤ a n) (hs : 0 < s) : Monotone (weightedSum a s) := by + apply monotone_nat_of_le_succ + intro n + rw [weightedSum_succ] + exact le_add_of_nonneg_right (div_nonneg (ha _) (pow_nonneg hs.le _)) + +theorem weightedSum_term_le (a : ℕ → ℝ) (s : ℝ) + (ha : ∀ n, 0 ≤ a n) (hs : 0 < s) (n : ℕ) : + a n / s ^ n ≤ weightedSum a s n := by + apply Finset.single_le_sum (fun k _ => div_nonneg (ha k) (pow_nonneg hs.le k)) + exact Finset.mem_range.mpr (Nat.lt_succ_self n) + +theorem one_le_weightedSum (a : ℕ → ℝ) (s : ℝ) + (ha : ∀ n, 1 ≤ a n) (hs : 0 < s) (n : ℕ) : + 1 ≤ weightedSum a s n := by + have hm := weightedSum_mono a s (fun k => (ha k).trans' zero_le_one) hs + calc + 1 ≤ a 0 := ha 0 + _ = weightedSum a s 0 := (weightedSum_zero a s).symm + _ ≤ weightedSum a s n := hm (Nat.zero_le n) + +/-- Bernoulli's elementary inequality is enough for the only unboundedness +argument below. -/ +private theorem exists_pow_gt (q : ℝ) (hq : 1 < q) (C : ℝ) : + ∃ n : ℕ, C < q ^ n := by + have hq0 : 0 < q := lt_trans zero_lt_one hq + have hbern : ∀ n : ℕ, 1 + (n : ℝ) * (q - 1) ≤ q ^ n := by + intro n + induction n with + | zero => simp + | succ n ih => + have hn : 0 ≤ (n : ℝ) := Nat.cast_nonneg n + have hextra : 0 ≤ (n : ℝ) * (q - 1) ^ 2 := mul_nonneg hn (sq_nonneg _) + calc + 1 + ((n + 1 : ℕ) : ℝ) * (q - 1) ≤ + (1 + (n : ℝ) * (q - 1)) * q := by + push_cast + nlinarith + _ ≤ q ^ n * q := mul_le_mul_of_nonneg_right ih hq0.le + _ = q ^ (n + 1) := (pow_succ q n).symm + obtain ⟨n, hn⟩ := exists_nat_gt ((C - 1) / (q - 1)) + have hden : 0 < q - 1 := by linarith + have hlarge := (div_lt_iff₀ hden).mp hn + exact ⟨n, (by linarith : C < 1 + (n : ℝ) * (q - 1)).trans_le (hbern n)⟩ + +/-- A positive multiple of a strictly faster geometric sequence cannot be +bounded above by any fixed multiple of a slower one. -/ +private theorem not_geometric_domination (u v A B : ℝ) + (hv : 0 < v) (hvu : v < u) (hA : 0 < A) : + ¬ (∀ n : ℕ, A * u ^ n ≤ B * v ^ n) := by + intro h + have hratio : 1 < u / v := (lt_div_iff₀ hv).mpr (by simpa using hvu) + obtain ⟨n, hn⟩ := exists_pow_gt (u / v) hratio (B / A) + rw [div_pow] at hn + have hcross := (div_lt_div_iff₀ hA (pow_pos hv n)).mp hn + have hbad := h n + nlinarith + +/-- Rates that give a uniform geometric upper bound for the scalar orbit. -/ +private def geometricRates (a : ℕ → ℝ) : Set ℝ := + {t | 0 < t ∧ ∃ C : ℝ, 0 < C ∧ ∀ n : ℕ, a n ≤ C * t ^ n} + +private theorem geometricRates_upward (a : ℕ → ℝ) {t u : ℝ} + (ht : t ∈ geometricRates a) (htu : t ≤ u) : u ∈ geometricRates a := by + obtain ⟨ht0, C, hC, hbound⟩ := ht + refine ⟨ht0.trans_le htu, C, hC, ?_⟩ + intro n + exact (hbound n).trans + (mul_le_mul_of_nonneg_left (pow_le_pow_left₀ ht0.le htu n) hC.le) + +private theorem geometricRates_one_le (a : ℕ → ℝ) + (ha : ∀ n, 1 ≤ a n) {t : ℝ} (ht : t ∈ geometricRates a) : 1 ≤ t := by + by_contra hnot + have ht1 : t < 1 := lt_of_not_ge hnot + obtain ⟨ht0, C, hC, hbound⟩ := ht + apply not_geometric_domination 1 t 1 C ht0 ht1 zero_lt_one + intro n + simpa only [one_pow, one_mul] using (ha n).trans (hbound n) + +private theorem above_inf_mem_geometricRates (a : ℕ → ℝ) + (hne : (geometricRates a).Nonempty) {t : ℝ} + (ht : sInf (geometricRates a) < t) : t ∈ geometricRates a := by + by_contra hnot + have hlow : t ≤ sInf (geometricRates a) := by + apply le_csInf hne + intro q hq + by_contra hqt + have hqt' : q < t := lt_of_not_ge hqt + exact hnot (geometricRates_upward a hq hqt'.le) + exact (not_le_of_gt ht) hlow + +/-- Below the critical rate, the normalizing masses are unbounded. -/ +private theorem weightedSum_unbounded (a : ℕ → ℝ) + (ha : ∀ n, 1 ≤ a n) (hbelow : BddBelow (geometricRates a)) + {s : ℝ} (hs : 0 < s) (hsr : s < sInf (geometricRates a)) (L : ℝ) : + ∃ n : ℕ, L < weightedSum a s n := by + by_contra hnot + have hbound : ∀ n : ℕ, weightedSum a s n ≤ L := by + intro n + exact le_of_not_gt (fun hn => hnot ⟨n, hn⟩) + have hL : 0 < L := lt_of_lt_of_le zero_lt_one + ((one_le_weightedSum a s ha hs 0).trans (hbound 0)) + have hrate : s ∈ geometricRates a := by + refine ⟨hs, L, hL, ?_⟩ + intro n + apply (div_le_iff₀ (pow_pos hs n)).mp + exact (weightedSum_term_le a s (fun k => (ha k).trans' zero_le_one) hs n).trans + (hbound n) + exact (not_le_of_gt hsr) (csInf_le hbelow hrate) + +/-- Fix any rate below the critical rate whose relative distance is small. +There are arbitrarily large normalizing masses with a small terminal fraction. +The proof is a contradiction between two distinct geometric growth rates. -/ +private theorem near_rate_weights (a : ℕ → ℝ) + (ha : ∀ n, 1 ≤ a n) (hne : (geometricRates a).Nonempty) + (hbelow : BddBelow (geometricRates a)) + {s ε : ℝ} (hs : 0 < s) (hε : 0 < ε) + (hsr : s < sInf (geometricRates a)) + (hgap : sInf (geometricRates a) < s * (1 + ε)) (L : ℝ) : + ∃ n : ℕ, L < weightedSum a s n ∧ + a (n + 1) / s ^ (n + 1) < ε * weightedSum a s n := by + by_contra hnot + let r : ℝ := sInf (geometricRates a) + let u : ℝ := s * (1 + ε) + let t : ℝ := (r + u) / 2 + have hrt : r < t := by dsimp [r, t, u]; linarith + have htu : t < u := by dsimp [r, t, u]; linarith + obtain ⟨ht0, C, hC, hCbound⟩ := above_inf_mem_geometricRates a hne hrt + obtain ⟨N, hN⟩ := weightedSum_unbounded a ha hbelow hs hsr L + have hmono := weightedSum_mono a s (fun k => (ha k).trans' zero_le_one) hs + have hmass : 0 < weightedSum a s N := + zero_lt_one.trans_le (one_le_weightedSum a s ha hs N) + have hterminal : ∀ k : ℕ, + ε * weightedSum a s (N + k) ≤ a (N + k + 1) / s ^ (N + k + 1) := by + intro k + have hlarge : L < weightedSum a s (N + k) := + hN.trans_le (hmono (Nat.le_add_right N k)) + exact le_of_not_gt (fun hsmall => hnot ⟨N + k, hlarge, hsmall⟩) + have hstep : ∀ k : ℕ, + (1 + ε) * weightedSum a s (N + k) ≤ weightedSum a s (N + (k + 1)) := by + intro k + rw [show N + (k + 1) = (N + k) + 1 by omega, weightedSum_succ] + have hterm := hterminal k + nlinarith + have hgrowth : ∀ k : ℕ, + weightedSum a s N * (1 + ε) ^ k ≤ weightedSum a s (N + k) := by + intro k + induction k with + | zero => simp + | succ k ih => + calc + weightedSum a s N * (1 + ε) ^ (k + 1) = + (1 + ε) * (weightedSum a s N * (1 + ε) ^ k) := by + rw [pow_succ] + ring + _ ≤ (1 + ε) * weightedSum a s (N + k) := + mul_le_mul_of_nonneg_left ih (by linarith) + _ ≤ weightedSum a s (N + (k + 1)) := hstep k + let A : ℝ := ε * weightedSum a s N * s ^ (N + 1) + have hA : 0 < A := by dsimp [A]; positivity + apply not_geometric_domination u t A (C * t ^ (N + 1)) ht0 htu hA + intro k + calc + A * u ^ k = (ε * (weightedSum a s N * (1 + ε) ^ k)) * + s ^ (N + k + 1) := by + dsimp [A, u] + rw [mul_pow, show N + k + 1 = (N + 1) + k by omega, pow_add] + ring + _ ≤ (ε * weightedSum a s (N + k)) * s ^ (N + k + 1) := + mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_left (hgrowth k) hε.le) (pow_nonneg hs.le _) + _ ≤ a (N + k + 1) := (le_div_iff₀ (pow_pos hs _)).mp (hterminal k) + _ ≤ C * t ^ (N + k + 1) := hCbound _ + _ = (C * t ^ (N + 1)) * t ^ k := by + rw [show N + k + 1 = (N + 1) + k by omega, pow_add] + ring + +/-- Weights for approximate eigenvectors of normalized multiplication. +The rate `r` is fixed before the error tolerance and required mass are chosen. -/ +theorem exists_approximate_weights (a : ℕ → ℝ) (M : ℝ) + (ha : ∀ n, 1 ≤ a n) (hM : 1 ≤ M) (haM : ∀ n, a n ≤ M ^ n) : + ∃ r : ℝ, 1 ≤ r ∧ r ≤ M ∧ + ∀ ε : ℝ, 0 < ε → ∀ L : ℝ, + ∃ s : ℝ, ∃ n : ℕ, 0 < s ∧ s < r ∧ r - s < ε ∧ + L < weightedSum a s n ∧ + a (n + 1) / s ^ (n + 1) < ε * weightedSum a s n := by + have hMmem : M ∈ geometricRates a := by + refine ⟨zero_lt_one.trans_le hM, 1, zero_lt_one, ?_⟩ + intro n + simpa only [one_mul] using haM n + have hne : (geometricRates a).Nonempty := ⟨M, hMmem⟩ + have hbelow : BddBelow (geometricRates a) := + ⟨1, fun _ ht => geometricRates_one_le a ha ht⟩ + let r : ℝ := sInf (geometricRates a) + have hr1 : 1 ≤ r := le_csInf hne (fun _ ht => geometricRates_one_le a ha ht) + have hrM : r ≤ M := csInf_le hbelow hMmem + have hr0 : 0 < r := zero_lt_one.trans_le hr1 + refine ⟨r, hr1, hrM, ?_⟩ + intro ε hε L + let e : ℝ := min (ε / (2 * r)) (ε / 2) + have he0 : 0 < e := by dsimp [e]; positivity + have heε : e < ε := (min_le_right _ _).trans_lt (by linarith) + have hre : r * e ≤ ε / 2 := by + have he := (le_div_iff₀ (show 0 < 2 * r by positivity)).mp + (show e ≤ ε / (2 * r) from min_le_left _ _) + nlinarith + let s : ℝ := r / (1 + e) + have hs : 0 < s := by dsimp [s]; positivity + have hseq : s * (1 + e) = r := by + dsimp [s] + exact div_mul_cancel₀ r (by positivity) + have hsr : s < r := by nlinarith + have hclose : r - s < ε := by + have hse := mul_le_mul_of_nonneg_right hsr.le he0.le + nlinarith + have hgap : r < s * (1 + ε) := by nlinarith + obtain ⟨n, hlarge, hsmall⟩ := near_rate_weights a ha hne hbelow hs hε hsr hgap L + exact ⟨s, n, hs, hsr, hclose, hlarge, hsmall⟩ + +end MatrixMultiplicationAllFields.TensorSpectrum.MultiplicativeGrowth diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Projective.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Projective.lean new file mode 100644 index 0000000000..fc4979b25b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/Projective.lean @@ -0,0 +1,156 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.Convex.Basic +public import Mathlib.Topology.Algebra.Field +public import Mathlib.Topology.Compactness.Compact +public import Mathlib.Topology.Algebra.Ring.Real +public import Mathlib.Topology.Order.Compact +public import Mathlib.Tactic.Ring + +/-! +# Projective maps and affine slices of fixed points + +These lemmas isolate the actual maps used by the character construction. A +frozen eigenvalue slice is convex; the full nonlinear fixed set is only claimed +to be closed. The last lemma is the compact finite-intersection step, not an +existence theorem for the required finite common fixed points. +-/ + +@[expose] public section + +noncomputable section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open Set + +variable {S : Type*} [CommMonoidWithZero S] + +/-- Evaluation after multiplication by `z`, normalized by the value of `z`. -/ +def projective (z : S) (f : S → ℝ) : S → ℝ := + fun x => f (z * x) / f z + +/-- Freeze the eigenvalue as a real constant, retaining affine equations. -/ +def eigenSlice (z : S) (c : ℝ) : Set (S → ℝ) := + {f | ∀ x, f (z * x) = c * f x} + +/-- The original nonlinear multiplicativity equations for one multiplier. -/ +def multiplicativeSet (z : S) : Set (S → ℝ) := + {f | ∀ x, f (z * x) = f z * f x} + +theorem projective_one (z : S) (f : S → ℝ) (hz : f z ≠ 0) : + projective z f 1 = 1 := by + simp [projective, hz] + +theorem projective_zero (z : S) (f : S → ℝ) (hzero : f 0 = 0) : + projective z f 0 = 0 := by + simp [projective, hzero] + +theorem projective_fixed_iff (z : S) (f : S → ℝ) (hz : f z ≠ 0) : + projective z f = f ↔ f ∈ multiplicativeSet z := by + constructor + · intro h x + have hx := congrFun h x + change f (z * x) / f z = f x at hx + exact (div_eq_iff hz).mp hx |>.trans (mul_comm _ _) + · intro h + funext x + change f (z * x) / f z = f x + rw [h x, mul_div_cancel_left₀ _ hz] + +theorem continuousOn_projective (z : S) (K : Set (S → ℝ)) + (hz : ∀ f ∈ K, f z ≠ 0) : ContinuousOn (projective z) K := by + apply continuousOn_pi.2 + intro x + exact (continuous_apply (z * x)).continuousOn.div + (continuous_apply z).continuousOn hz + +theorem eigenSlice_isClosed (z : S) (c : ℝ) : IsClosed (eigenSlice z c) := by + have h : eigenSlice z c = ⋂ x : S, {f : S → ℝ | f (z * x) = c * f x} := by + ext f + simp only [eigenSlice, mem_ofPred_eq, mem_iInter] + rw [h] + exact isClosed_iInter fun x => + isClosed_eq (continuous_apply (z * x)) (continuous_const.mul (continuous_apply x)) + +theorem eigenSlice_convex (z : S) (c : ℝ) : Convex ℝ (eigenSlice z c) := by + intro f hf g hg a b _ _ _ x + change a * f (z * x) + b * g (z * x) = c * (a * f x + b * g x) + rw [hf x, hg x] + ring + +theorem multiplicativeSet_isClosed (z : S) : IsClosed (multiplicativeSet z) := by + have h : multiplicativeSet z = + ⋂ x : S, {f : S → ℝ | f (z * x) = f z * f x} := by + ext f + simp only [multiplicativeSet, mem_ofPred_eq, mem_iInter] + rw [h] + exact isClosed_iInter fun x => isClosed_eq (continuous_apply (z * x)) + ((continuous_apply z).mul (continuous_apply x)) + +/-- All other projective maps preserve every frozen equation. No cancellation +or division by a possibly zero coordinate is needed for this algebraic fact. -/ +theorem projective_mem_eigenSlice (z w : S) (c : ℝ) (f : S → ℝ) + (hf : f ∈ eigenSlice z c) : projective w f ∈ eigenSlice z c := by + intro x + change f (w * (z * x)) / f w = c * (f (w * x) / f w) + rw [show w * (z * x) = z * (w * x) by ac_rfl, hf (w * x)] + ring + +theorem eigenSlice_eigenvalue (z : S) (c : ℝ) (f : S → ℝ) + (hf : f ∈ eigenSlice z c) (hunit : f 1 = 1) : f z = c := by + simpa only [mul_one, hunit] using hf 1 + +theorem eigenSlice_mem_multiplicativeSet (z : S) (c : ℝ) (f : S → ℝ) + (hf : f ∈ eigenSlice z c) (hunit : f 1 = 1) : + f ∈ multiplicativeSet z := by + intro x + rw [hf x, eigenSlice_eigenvalue z c f hf hunit] + +/-- Once a fixed point is obtained, freezing its eigenvalue preserves that +witness and yields a compact convex slice invariant under every projective map. -/ +theorem freeze_fixedPoint (K : Set (S → ℝ)) (z : S) (f : S → ℝ) + (hcompact : IsCompact K) (hconvex : Convex ℝ K) (hf : f ∈ K) + (hfixed : projective z f = f) (hz : f z ≠ 0) + (hinvariant : ∀ w, w ≠ 0 → MapsTo (projective w) K K) : + let L := K ∩ eigenSlice z (f z) + f ∈ L ∧ IsCompact L ∧ Convex ℝ L ∧ + (∀ w, w ≠ 0 → MapsTo (projective w) L L) := by + dsimp only + refine ⟨⟨hf, (projective_fixed_iff z f hz).mp hfixed⟩, + hcompact.inter_right (eigenSlice_isClosed z (f z)), + hconvex.inter (eigenSlice_convex z (f z)), ?_⟩ + intro w hw g hg + exact ⟨hinvariant w hw hg.1, projective_mem_eigenSlice z w (f z) g hg.2⟩ + +/-- Compactness yields a multiplicative state from common fixed points for +every finite family of normalized multiplication maps. -/ +theorem multiplicative_of_finite_common_points + (K : Set (S → ℝ)) (hcompact : IsCompact K) + (hzero : ∀ f ∈ K, f 0 = 0) + (hfinite : ∀ F : Finset {z : S // z ≠ 0}, + ∃ f ∈ K, ∀ z ∈ F, f ∈ multiplicativeSet z.val) : + ∃ f ∈ K, ∀ z x, f (z * x) = f z * f x := by + have hnonempty : (K ∩ ⋂ z : {z : S // z ≠ 0}, multiplicativeSet z.val).Nonempty := by + apply hcompact.inter_iInter_nonempty + (fun z : {z : S // z ≠ 0} => multiplicativeSet z.val) + (fun z => multiplicativeSet_isClosed z.val) + intro F + obtain ⟨f, hf, hF⟩ := hfinite F + refine ⟨f, hf, ?_⟩ + simp only [mem_iInter] + exact hF + obtain ⟨f, hf, hall⟩ := hnonempty + refine ⟨f, hf, ?_⟩ + intro z x + by_cases hz : z = 0 + · simp [hz, hzero f hf] + · exact (mem_iInter.mp hall ⟨z, hz⟩) x + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/States.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/States.lean new file mode 100644 index 0000000000..b881fdf36b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/Multiplicative/States.lean @@ -0,0 +1,90 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Additive.States +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Multiplicative.Projective + +/-! +# State preservation by normalized multiplication + +The order hypotheses here are the concrete tensor restriction properties. In +particular the lower bound on nonzero tensors proves the denominator is positive; +it is not a separate premise about a proposed character. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open Set + +variable {S : Type*} [CommSemiring S] [PartialOrder S] + +theorem state_one_le {T : S} {k : ℕ} {f : S → ℝ} + (hf : f ∈ stateSet T k) (hunit : ∀ z : S, z ≠ 0 → 1 ≤ z) + {z : S} (hz : z ≠ 0) : 1 ≤ f z := by + simpa only [hf.2.1] using hf.2.2.2.1 (hunit z hz) + +theorem state_pos {T : S} {k : ℕ} {f : S → ℝ} + (hf : f ∈ stateSet T k) (hunit : ∀ z : S, z ≠ 0 → 1 ≤ z) + {z : S} (hz : z ≠ 0) : 0 < f z := + lt_of_lt_of_le zero_lt_one (state_one_le hf hunit hz) + +/-- Every projective map preserves all five defining state conditions, including +the detecting inequalities for every tensor. -/ +theorem projective_mem_stateSet {T : S} {k : ℕ} {f : S → ℝ} + (hf : f ∈ stateSet T k) (hunit : ∀ z : S, z ≠ 0 → 1 ≤ z) + (hmul : ∀ z : S, Monotone (fun x : S => z * x)) + {z : S} (hz : z ≠ 0) : projective z f ∈ stateSet T k := by + have hpos : 0 < f z := state_pos hf hunit hz + refine ⟨projective_zero z f hf.1, projective_one z f hpos.ne', ?_, ?_, ?_⟩ + · intro x y + change f (z * (x + y)) / f z = f (z * x) / f z + f (z * y) / f z + rw [mul_add, hf.2.2.1, add_div] + · intro x y hxy + exact div_le_div_of_nonneg_right (hf.2.2.2.1 (hmul z hxy)) hpos.le + · intro s + change (k : ℝ) * (f (z * s) / f z) ≤ f (z * (T * s)) / f z + rw [show z * (T * s) = T * (z * s) by ac_rfl, ← mul_div_assoc] + exact div_le_div_of_nonneg_right (hf.2.2.2.2 (z * s)) hpos.le + +theorem projective_mapsTo_stateSet (T : S) (k : ℕ) + (hunit : ∀ z : S, z ≠ 0 → 1 ≤ z) + (hmul : ∀ z : S, Monotone (fun x : S => z * x)) + {z : S} (hz : z ≠ 0) : + MapsTo (projective z) (stateSet T k) (stateSet T k) := + fun _ hf => projective_mem_stateSet hf hunit hmul hz + +theorem projective_continuousOn_stateSet (T : S) (k : ℕ) + (hunit : ∀ z : S, z ≠ 0 → 1 ≤ z) + {z : S} (hz : z ≠ 0) : ContinuousOn (projective z) (stateSet T k) := + continuousOn_projective z (stateSet T k) fun _ hf => (state_pos hf hunit hz).ne' + +/-- A simultaneous fixed point of the actual state maps is a monotone semiring +character, and the detection inequality at the unit yields its required value. -/ +theorem character_of_common_fixedPoint (T : S) (k : ℕ) + (hunit : ∀ z : S, z ≠ 0 → 1 ≤ z) + (f : S → ℝ) (hf : f ∈ stateSet T k) + (hfixed : ∀ z : S, z ≠ 0 → projective z f = f) : + ∃ χ : S →+* ℝ, Monotone χ ∧ (k : ℝ) ≤ χ T ∧ ∀ x, χ x = f x := by + have hmul : ∀ x y : S, f (x * y) = f x * f y := by + intro x y + by_cases hx : x = 0 + · simp [hx, hf.1] + · exact (projective_fixed_iff x f (state_pos hf hunit hx).ne').mp (hfixed x hx) y + let χ : S →+* ℝ := + { toFun := f + map_zero' := hf.1 + map_one' := hf.2.1 + map_add' := hf.2.2.1 + map_mul' := hmul } + refine ⟨χ, hf.2.2.2.1, ?_, fun _ => rfl⟩ + change (k : ℝ) ≤ f T + simpa only [mul_one, hf.2.1] using hf.2.2.2.2 1 + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialCharacterBounds.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialCharacterBounds.lean new file mode 100644 index 0000000000..1e7325b9e4 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialCharacterBounds.lean @@ -0,0 +1,148 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterDegeneration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDirectSum +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialFiltrationFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialSectorFamily +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationPolynomial + +/-! +# Character bounds for the determinant, tripling and separation families + +A character evaluates the shared polynomial degenerations through its +semiring operations. The actual restriction inequalities come from the +coefficient model. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +open PolynomialTensors + +/-- A coefficient model's comparison for a bounded polynomial restriction family. -/ +abbrev Character.PolynomialBound {K : Type*} [CommSemiring K] (f : Character K) + (node : K → Prop) : Prop := + ∀ {X Y Z U V W : Type} [Fintype X] [Fintype Y] [Fintype Z] + [Fintype U] [Fintype V] [Fintype W] + (T : Tensor K X Y Z) (D : Tensor K U V W) (P : Tensor (Polynomial K) U V W) (degree : ℕ), + (∀ u v w, (P u v w).coeff 0 = D u v w) → + (∀ u v w, (P u v w).degree ≤ degree) → + (∀ t, node t → (fun u v w => (P u v w).eval t) ∈ LocalTensor.orbit T) → + f (ofTensor D) ≤ f (ofTensor T) + +section Determinant + +variable {K : Type*} [CommRing K] + +theorem binaryDotTensor_class : ofTensor (binaryDotTensor (K := K)) = dotX 2 := by + have heq : Tensor.pullback (Equiv.refl Unit) finTwoEquiv finTwoEquiv + (binaryDotTensor (K := K)) = CoefficientTensor.dotXCoeff 2 := by + funext x y z + simp [Tensor.pullback, TensorSpectrum.PolynomialTensors.binaryDotTensor, + CoefficientTensor.dotXCoeff] + change ofTensor binaryDotTensor = ofTensor (CoefficientTensor.dotXCoeff 2) + rw [← heq] + exact (ofTensor_pullback_equiv _ _ _ _).symm + +theorem Character.determinant_graded_le (f : Character K) (a b : ℕ) + (h : f (ofTensor (determinantGradedTensor a b)) ≤ f (ofTensor + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor))) : + (f (ofTensor (determinantGradedTensor a b)) : ℝ) ≤ + (2 : ℝ) ^ f.pX * (f (ofTensor (polynomialTensor (a + 1) (b + 2))) : ℝ) := by + rw [← ofTensor_mul, Character.map_mul, binaryDotTensor_class] at h + have hr : (f (ofTensor (determinantGradedTensor a b)) : ℝ) ≤ + (f (ofTensor (polynomialTensor (a + 1) (b + 2))) : ℝ) * f.dotXValue 2 := by + exact_mod_cast h + rw [f.dotXValue_eq_rpow 2 (by decide), mul_comm] at hr + exact hr + +theorem Character.determinant_graded_le_of_evaluation (f : Character K) {node : K → Prop} + (compare : f.PolynomialBound node) (a b : ℕ) + (heval : ∀ t, node t → (fun i y z => (determinantPolynomialFamily a b i y z).eval t) ∈ + LocalTensor.orbit (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor)) : + (f (ofTensor (determinantGradedTensor a b)) : ℝ) ≤ + (2 : ℝ) ^ f.pX * (f (ofTensor (polynomialTensor (a + 1) (b + 2))) : ℝ) := + f.determinant_graded_le a b (compare + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) + (determinantGradedTensor a b) (determinantPolynomialFamily a b) 1 + (fun i y z => congrFun (congrFun (congrFun + (determinantPolynomialFamily_coeff_zero a b) i) y) z) + (determinantPolynomialFamily_degree_le a b) heval) + +end Determinant + +variable {K : Type*} [CommSemiring K] + +theorem Character.tripling_graded_le (f : Character K) (a h : ℕ) + (hpower : ∀ j : ℕ, + Tensor.power (triplingSectorTensor (K := K) a h) j ∈ LocalTensor.orbit + (Tensor.directSum (fun _ : Fin (1 * j + 1) => + Tensor.power (polynomialTensor a (triplingWidth a h)) j))) : + (f (ofTensor (triplingSectorTensor a h)) : ℝ) ≤ + (f (ofTensor (polynomialTensor a (3 * h + a - 1))) : ℝ) := by + exact_mod_cast f.polynomial_constant_le + (polynomialTensor a (triplingWidth a h)) (triplingSectorTensor a h) 1 hpower +theorem Character.tripling_graded_le_of_evaluation (f : Character K) {node : K → Prop} + (compare : f.PolynomialBound node) (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (heval : ∀ t, node t → (fun x y z => (triplingPolynomialFamily a h ha hh x y z).eval t) ∈ + LocalTensor.orbit (polynomialTensor a (triplingWidth a h))) : + (f (ofTensor (triplingSectorTensor a h)) : ℝ) ≤ + (f (ofTensor (polynomialTensor a (3 * h + a - 1))) : ℝ) := by + exact_mod_cast compare (polynomialTensor a (triplingWidth a h)) (triplingSectorTensor a h) + (triplingPolynomialFamily a h ha hh) 1 + (triplingPolynomialFamily_coeff_zero a h ha hh) + (triplingPolynomialFamily_degree_le a h ha hh) heval + +theorem Character.charged_separation (f : Character K) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {M : ℕ} (factor : ℕ) (A : Fin M → Tensor K X Y Z) + (h : f (ofTensor (Separation.separated A)) ≤ f (ofTensor + (Tensor.directSum (fun _ : Fin (factor * M) => Tensor.sharedFirst A)))) : + (∑ h, f (ofTensor (A h))) * + f (ofTensor (Separation.dotPairingX (Fin M))) ≤ + ((factor : ℝ≥0) * M) * f (ofTensor (Tensor.sharedFirst A)) := by + rw [Character.map_directSum_const] at h + have houtput : f (ofTensor (Separation.separated A)) = + (∑ h, f (ofTensor (A h))) * + f (ofTensor (Separation.dotPairingX (Fin M))) := by + unfold Separation.separated + rw [Character.map_directSum_fin] + simp only [← ofTensor_mul, Character.map_mul, Finset.sum_mul] + rw [houtput] at h + simpa only [Nat.cast_mul] using h + +/-- Equal branch values let the number of branches cancel in the separation bound. -/ +theorem Character.charged_separation_equal (f : Character K) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {M : ℕ} (factor : ℕ) (hM : 0 < M) (A : Fin M → Tensor K X Y Z) + (c : ℝ≥0) (hvalue : ∀ h, f (ofTensor (A h)) = c) + (h : (∑ i, f (ofTensor (A i))) * f (ofTensor (Separation.dotPairingX (Fin M))) ≤ + ((factor : ℝ≥0) * M) * f (ofTensor (Tensor.sharedFirst A))) : + c * f (ofTensor (Separation.dotPairingX (Fin M))) ≤ + (factor : ℝ≥0) * f (ofTensor (Tensor.sharedFirst A)) := by + simp only [hvalue, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + nsmul_eq_mul] at h + have hM' : (0 : ℝ≥0) < M := by exact_mod_cast hM + apply (mul_le_mul_iff_right₀ hM').mp + calc + (M : ℝ≥0) * (c * f (ofTensor (Separation.dotPairingX (Fin M)))) = + ((M : ℝ≥0) * c) * f (ofTensor (Separation.dotPairingX (Fin M))) := + (mul_assoc _ _ _).symm + _ ≤ ((factor : ℝ≥0) * M) * f (ofTensor (Tensor.sharedFirst A)) := h + _ = (M : ℝ≥0) * ((factor : ℝ≥0) * f (ofTensor (Tensor.sharedFirst A))) := by ring + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialFiltration.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialFiltration.lean new file mode 100644 index 0000000000..17133d54ea --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialFiltration.lean @@ -0,0 +1,244 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors + +/-! # The determinant change of basis for convolution -/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + +variable {K : Type*} [CommRing K] + +/-- Returns `1` when `j = i` holds, and `0` otherwise. -/ +def delta {ι : Type*} [DecidableEq ι] (i j : ι) : K := + if j = i then 1 else 0 + +/-- Two copies of convolution with their first input genuinely shared. -/ +def doubledPolynomialTensor (a b : ℕ) : + Tensor K (Fin (a + 1)) (Fin (b + 2) ⊕ Fin (b + 2)) + (Fin (a + b + 2) ⊕ Fin (a + b + 2)) + | i, Sum.inl j, Sum.inl k => if i.val + j.val = k.val then 1 else 0 + | _, Sum.inl _, Sum.inr _ => 0 + | _, Sum.inr _, Sum.inl _ => 0 + | i, Sum.inr j, Sum.inr k => if i.val + j.val = k.val then 1 else 0 + +/-- The two-dimensional dot pairing with a singleton first leg. -/ +def binaryDotTensor : Tensor K Unit Bool Bool := + fun _ y z => if y = z then 1 else 0 + +/-- In the case `Sum.inl j`, this construction gives `(j, false)`. -/ +def doubleIndexEquiv (n : ℕ) : (Fin n ⊕ Fin n) ≃ (Fin n × Bool) where + toFun + | Sum.inl j => (j, false) + | Sum.inr j => (j, true) + invFun + | (j, false) => Sum.inl j + | (j, true) => Sum.inr j + left_inv := by intro j; cases j <;> rfl + right_inv := by rintro ⟨j, b⟩; cases b <;> rfl + +/-- Reindexes `(Fin (a + b + 2) ⊕ Fin (a + b + 2))` and `(Fin (a + 1 + (b + 2) - 1) × Bool)` by +an equivalence. -/ +def doubleOutputEquiv (a b : ℕ) : + (Fin (a + b + 2) ⊕ Fin (a + b + 2)) ≃ + (Fin (a + 1 + (b + 2) - 1) × Bool) := + (doubleIndexEquiv (a + b + 2)).trans + (Equiv.prodCongr (finCongr (by omega)) (Equiv.refl Bool)) + +/-- The doubled coefficient tensor really is convolution tensored with the +two-dimensional dot pairing, after only coordinate equivalences. -/ +theorem doubledPolynomialTensor_product (a b : ℕ) : + Tensor.pullback (fun i => (i, ())) (doubleIndexEquiv (b + 2)) + (doubleOutputEquiv a b) + (Tensor.product ((polynomialTensor (K := K)) (a + 1) (b + 2)) binaryDotTensor) = + doubledPolynomialTensor a b := by + funext i y z + cases y <;> cases z <;> + simp [Tensor.pullback, Tensor.product, polynomialTensor, binaryDotTensor, + doubleIndexEquiv, doubleOutputEquiv, doubledPolynomialTensor] + +/-- The quotient lifts are `S_0,...,S_(b+1),W_(b+1)`; the remaining +new vectors are `W_j-S_(j+1)` for `j=0,...,b`. -/ +def determinantInputMap (b : ℕ) : + (Fin (b + 3) ⊕ Fin (b + 1)) → + (Fin (b + 2) ⊕ Fin (b + 2)) → K + | Sum.inl j, v => + if h : j.val < b + 2 then + delta (Sum.inl ⟨j.val, h⟩) v + else delta (Sum.inr ⟨b + 1, by omega⟩) v + | Sum.inr j, v => + delta (Sum.inr ⟨j.val, by omega⟩) v - + delta (Sum.inl ⟨j.val + 1, by omega⟩) v + +/-- Coordinates of old output basis vectors in the new basis. These are the +dual local substitutions required on the tensor's third leg. -/ +def determinantOutputMap (a b : ℕ) : + (Fin (a + b + 3) ⊕ Fin (a + b + 1)) → + (Fin (a + b + 2) ⊕ Fin (a + b + 2)) → K + | Sum.inl k, Sum.inl j => if j.val = k.val then 1 else 0 + | Sum.inl k, Sum.inr j => if j.val + 1 = k.val then 1 else 0 + | Sum.inr _, Sum.inl _ => 0 + | Sum.inr k, Sum.inr j => if j.val = k.val then 1 else 0 + +/-- The whole transformed tensor, including the cross block. -/ +def determinantAdaptedTensor (a b : ℕ) : + Tensor K (Fin (a + 1)) (Fin (b + 3) ⊕ Fin (b + 1)) + (Fin (a + b + 3) ⊕ Fin (a + b + 1)) + | i, Sum.inl j, Sum.inl k => if i.val + j.val = k.val then 1 else 0 + | i, Sum.inl j, Sum.inr k => + if j.val = b + 2 ∧ i.val + b + 1 = k.val then 1 else 0 + | _, Sum.inr _, Sum.inl _ => 0 + | i, Sum.inr j, Sum.inr k => if i.val + j.val = k.val then 1 else 0 + +private theorem doubled_left (a b : ℕ) (i : Fin (a + 1)) (j : Fin (b + 2)) : + (doubledPolynomialTensor (K := K)) a b i (Sum.inl j) = + delta (Sum.inl (⟨i.val + j.val, by omega⟩ : Fin (a + b + 2))) := by + funext z + cases z with + | inl k => simp [doubledPolynomialTensor, delta, Fin.ext_iff, eq_comm] + | inr k => simp [doubledPolynomialTensor, delta] + +private theorem doubled_right (a b : ℕ) (i : Fin (a + 1)) (j : Fin (b + 2)) : + (doubledPolynomialTensor (K := K)) a b i (Sum.inr j) = + delta (Sum.inr (⟨i.val + j.val, by omega⟩ : Fin (a + b + 2))) := by + funext z + cases z with + | inl k => simp [doubledPolynomialTensor, delta] + | inr k => simp [doubledPolynomialTensor, delta, Fin.ext_iff, eq_comm] + +private theorem restrict_single_second {X Y Z Y' Z' : Type*} + [Fintype X] [Fintype Y] [Fintype Z] + [DecidableEq X] [DecidableEq Y] + (T : Tensor K X Y Z) (B : Y' → Y → K) (C : Z' → Z → K) + (x : X) (y : Y') (z : Z') (v : Y) + (hB : B y = delta v) : + Tensor.restrict delta B C T x y z = ∑ w, C z w * T x v w := by + classical + simp [Tensor.restrict, hB, delta, ite_mul, mul_ite] + +private theorem restrict_difference_second {X Y Z Y' Z' : Type*} + [Fintype X] [Fintype Y] [Fintype Z] + [DecidableEq X] [DecidableEq Y] + (T : Tensor K X Y Z) (B : Y' → Y → K) (C : Z' → Z → K) + (x : X) (y : Y') (z : Z') (v w : Y) + (hB : B y = fun u => delta v u - delta w u) : + Tensor.restrict delta B C T x y z = + (∑ u, C z u * T x v u) - ∑ u, C z u * T x w u := by + classical + simp [Tensor.restrict, hB, delta, ite_mul, + sub_mul, Finset.sum_sub_distrib] + +/-- The simultaneous basis change is an actual three-leg restriction. In +particular no branch-specific first-input substitution is used. -/ +theorem determinant_basis_change (a b : ℕ) : + Tensor.restrict (delta (K := K)) (determinantInputMap b) (determinantOutputMap a b) + (doubledPolynomialTensor a b) = determinantAdaptedTensor a b := by + funext i y z + cases y with + | inl j => + by_cases hj : j.val < b + 2 + · rw [restrict_single_second (doubledPolynomialTensor a b) + (determinantInputMap b) (determinantOutputMap a b) i (Sum.inl j) z + (Sum.inl ⟨j.val, hj⟩) (by funext v; simp [determinantInputMap, hj])] + rw [doubled_left] + simp only [delta, mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', + Finset.mem_univ, ite_true] + cases z with + | inl k => rfl + | inr k => simp [determinantOutputMap, determinantAdaptedTensor, + show j.val ≠ b + 2 by omega] + · have hlast : j.val = b + 2 := by omega + rw [restrict_single_second (doubledPolynomialTensor a b) + (determinantInputMap b) (determinantOutputMap a b) i (Sum.inl j) z + (Sum.inr ⟨b + 1, by omega⟩) (by funext v; simp [determinantInputMap, hj])] + rw [doubled_right] + simp only [delta, mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', + Finset.mem_univ, ite_true] + cases z with + | inl k => + simp [determinantOutputMap, determinantAdaptedTensor, hlast, + Nat.add_assoc] + | inr k => simp [determinantOutputMap, determinantAdaptedTensor, hlast, + Nat.add_assoc] + | inr j => + rw [restrict_difference_second _ _ _ i (Sum.inr j) z + (Sum.inr ⟨j.val, by omega⟩) (Sum.inl ⟨j.val + 1, by omega⟩) rfl] + rw [doubled_right, doubled_left] + simp only [delta, mul_ite, mul_one, mul_zero, Finset.sum_ite_eq', + Finset.mem_univ, ite_true] + cases z with + | inl k => simp [determinantOutputMap, determinantAdaptedTensor, Nat.add_assoc] + | inr k => simp [determinantOutputMap, determinantAdaptedTensor] + +/-- The two retained diagonal branches, still sharing the same first leg. -/ +def determinantGradedTensor (a b : ℕ) : + Tensor K (Fin (a + 1)) (Fin (b + 3) ⊕ Fin (b + 1)) + (Fin (a + b + 3) ⊕ Fin (a + b + 1)) + | i, Sum.inl j, Sum.inl k => if i.val + j.val = k.val then 1 else 0 + | _, Sum.inl _, Sum.inr _ => 0 + | _, Sum.inr _, Sum.inl _ => 0 + | i, Sum.inr j, Sum.inr k => if i.val + j.val = k.val then 1 else 0 + +theorem determinantGraded_quotient (a b : ℕ) (i : Fin (a + 1)) + (j : Fin (b + 3)) (k : Fin (a + 1 + (b + 3) - 1)) : + (determinantGradedTensor (K := K)) a b i (Sum.inl j) + (Sum.inl (Fin.cast (by omega) k)) = + polynomialTensor (a + 1) (b + 3) i j k := by + rfl + +theorem determinantGraded_kernel (a b : ℕ) (i : Fin (a + 1)) + (j : Fin (b + 1)) (k : Fin (a + 1 + (b + 1) - 1)) : + (determinantGradedTensor (K := K)) a b i (Sum.inr j) + (Sum.inr (Fin.cast (by omega) k)) = + polynomialTensor (a + 1) (b + 1) i j k := by + rfl + +@[simp] theorem determinantGraded_quotient_kernel (a b : ℕ) (i : Fin (a + 1)) + (j : Fin (b + 3)) (k : Fin (a + b + 1)) : + (determinantGradedTensor (K := K)) a b i (Sum.inl j) (Sum.inr k) = 0 := rfl + +@[simp] theorem determinantGraded_kernel_quotient (a b : ℕ) (i : Fin (a + 1)) + (j : Fin (b + 1)) (k : Fin (a + b + 3)) : + (determinantGradedTensor (K := K)) a b i (Sum.inr j) (Sum.inl k) = 0 := rfl + +/-- In the case `Sum.inl _`, this construction gives `0`. -/ +def determinantInputWeight (b : ℕ) : (Fin (b + 3) ⊕ Fin (b + 1)) → ℤ + | Sum.inl _ => 0 + | Sum.inr _ => -1 + +/-- In the case `Sum.inl _`, this construction gives `0`. -/ +def determinantOutputWeight (a b : ℕ) : + (Fin (a + b + 3) ⊕ Fin (a + b + 1)) → ℤ + | Sum.inl _ => 0 + | Sum.inr _ => 1 + +theorem determinant_supported_weight (a b : ℕ) + (i : Fin (a + 1)) (y : Fin (b + 3) ⊕ Fin (b + 1)) + (z : Fin (a + b + 3) ⊕ Fin (a + b + 1)) + (h : (determinantAdaptedTensor (K := K)) a b i y z ≠ 0) : + 0 ≤ (0 : ℤ) + determinantInputWeight b y + determinantOutputWeight a b z := by + cases y <;> cases z <;> + simp_all [determinantAdaptedTensor, determinantInputWeight, determinantOutputWeight] + +theorem determinant_weightedLimit (a b : ℕ) : + weightedLimit ((determinantAdaptedTensor (K := K)) a b) (fun _ => 0) + (determinantInputWeight b) (determinantOutputWeight a b) = + determinantGradedTensor a b := by + funext i y z + cases y <;> cases z <;> + simp [weightedLimit, determinantAdaptedTensor, determinantGradedTensor, + determinantInputWeight, determinantOutputWeight] + +end MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialFiltrationFamily.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialFiltrationFamily.lean new file mode 100644 index 0000000000..c779e96383 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialFiltrationFamily.lean @@ -0,0 +1,86 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.WeightedPolynomials +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialFiltration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.LocalTensor + +/-! +# The finite-degree determinant family + +The constant coefficient is the two-branch graded tensor. Every nonzero +evaluation is an actual restriction of the original convolution tensor times +the two-dimensional pairing. These explicit data, rather than continuity of +an arbitrary tensor character, are the inputs to finite interpolation. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + +variable {K : Type*} [CommRing K] + +theorem determinantAdapted_mem_restrictionOrbit (a b : ℕ) : + determinantAdaptedTensor (K := K) a b ∈ LocalTensor.orbit + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) := by + have hd : doubledPolynomialTensor (K := K) a b ∈ LocalTensor.orbit + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) := by + rw [← doubledPolynomialTensor_product, Tensor.pullback_eq_restrict] + exact ⟨_, _, _, rfl⟩ + have h := LocalTensor.restrict_mem hd + (fun i' i : Fin (a + 1) => if i = i' then (1 : K) else 0) + (determinantInputMap b) (determinantOutputMap a b) + have he : Tensor.restrict + (fun i' i : Fin (a + 1) => if i = i' then (1 : K) else 0) + (determinantInputMap b) (determinantOutputMap a b) + (doubledPolynomialTensor a b) = determinantAdaptedTensor a b := + determinant_basis_change a b + rwa [he] at h + +/-- Coefficients are constant or linear in the degeneration parameter. -/ +def determinantPolynomialFamily (a b : ℕ) : + Tensor (Polynomial K) (Fin (a + 1)) (Fin (b + 3) ⊕ Fin (b + 1)) + (Fin (a + b + 3) ⊕ Fin (a + b + 1)) := + weightedPolynomial (determinantAdaptedTensor a b) (fun _ => 0) + (determinantInputWeight b) (determinantOutputWeight a b) + +theorem determinantPolynomialFamily_coeff_zero (a b : ℕ) : + (fun i y z => (determinantPolynomialFamily (K := K) a b i y z).coeff 0) = + determinantGradedTensor a b := by + funext i y z + rw [determinantPolynomialFamily, weightedPolynomial_coeff_zero + (determinantAdaptedTensor a b) (fun _ => 0) + (determinantInputWeight b) (determinantOutputWeight a b) + (determinant_supported_weight a b)] + exact congrFun (congrFun (congrFun (determinant_weightedLimit a b) i) y) z + +theorem determinantPolynomialFamily_degree_le (a b : ℕ) + (i : Fin (a + 1)) (y : Fin (b + 3) ⊕ Fin (b + 1)) + (z : Fin (a + b + 3) ⊕ Fin (a + b + 1)) : + (determinantPolynomialFamily (K := K) a b i y z).degree ≤ (1 : ℕ) := by + apply weightedPolynomial_degree_le + intro i' y' z' hc + cases y' <;> cases z' <;> + simp_all [determinantAdaptedTensor, determinantInputWeight, determinantOutputWeight] + +theorem determinantPolynomialFamily_eval_mem_restrictionOrbit (a b : ℕ) (t : K) + (he : (fun i y z => (determinantPolynomialFamily a b i y z).eval t) ∈ + LocalTensor.orbit (determinantAdaptedTensor a b)) : + (fun i y z => (determinantPolynomialFamily a b i y z).eval t) ∈ + LocalTensor.orbit + (Tensor.product (polynomialTensor (a + 1) (b + 2)) binaryDotTensor) := + LocalTensor.orbit_trans (determinantAdapted_mem_restrictionOrbit a b) he + +end MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialGrowth.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialGrowth.lean new file mode 100644 index 0000000000..bf3835960a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialGrowth.lean @@ -0,0 +1,208 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagPolynomialBranches +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPermutationPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Weighted + +/-! +# The weighted growth bound for actual tensor characters + +Use the optimized tag inequality on the determinant and tripling +degenerations for each leg permutation separately. +-/ + +@[expose] public section + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +namespace MatrixMultiplicationAllFields.TensorSpectrum.PolynomialGrowth + +open TensorClass TagHeterogeneous +open PolynomialTensors (polynomialTensor determinantGradedTensor triplingSectorTensor) + +variable {K : Type} [CommRing K] + +/-- The quantity computed by `f (ofTensor (polynomialTensor (m + 1) (n + 1)))`. -/ +def poly (f : Character K) (m n : ℕ) : ℝ := + f (ofTensor (polynomialTensor (m + 1) (n + 1))) + +section Bounds + +variable (hpositive : + ∀ (f : Character K) (a b : ℕ), 1 ≤ a → 1 ≤ b → + 0 < (f (ofTensor (polynomialTensor a b)) : ℝ)) + +include hpositive in +/-- Positivity for every padded determinant branch follows from the already +established positive polynomial character values. -/ +private theorem determinant_family_value_pos (f : Character K) (a b : ℕ) (j : Fin 2) : + 0 < (f (TensorClass.ofTensor + (twoFamily (determinantQuotientTensor a b) (determinantKernelTensor a b) j)) : ℝ) := by + rw [ofTensor_determinant_family] + fin_cases j <;> simp only + · exact hpositive f _ _ (by omega) (by omega) + · exact hpositive f _ _ (by omega) (by omega) + +include hpositive in +/-- The positive middle value uses the actual permuted character. -/ +private theorem tripling_middle_value_pos (f : Character K) (a h : ℕ) + (ha : 1 ≤ a) (hh : 1 ≤ h) : + 0 < (f (TensorClass.ofTensor (triplingMiddleTensor a h)) : ℝ) := by + rw [ofTensor_triplingMiddle] + have hp := hpositive (f.permuted 2) a h ha hh + simpa [TensorClass.Character.permuted_apply, TensorClass.permute, + TensorClass.permuteHom, TensorClass.swapYZHom] using hp + +include hpositive in +/-- These strict positive values are the hypotheses of the uniform tag +inequality, including the padded and reversed middle branch. -/ +private theorem tripling_family_value_pos (f : Character K) (a h : ℕ) + (ha : 1 ≤ a) (hh : 1 ≤ h) (j : Fin 3) : + 0 < (f (TensorClass.ofTensor + (threeFamily (polynomialTensor a h) (triplingMiddleTensor a h) + (polynomialTensor a h) j)) : ℝ) := by + rw [ofTensor_threeFamily] + fin_cases j <;> simp only + · exact hpositive f _ _ ha hh + · exact tripling_middle_value_pos hpositive f a h ha hh + · exact hpositive f _ _ ha hh + +include hpositive in +private theorem poly_pos (f : Character K) (m n : ℕ) : 0 < poly f m n := + hpositive f _ _ (by omega) (by omega) + +variable (htag : + ∀ (f : Character K) {X Y Z : Type} [Fintype X] [Fintype Y] [Fintype Z] + {s : ℕ}, 0 < s → ∀ A : Fin s → Tensor K X Y Z, + (∀ i, 0 < (f (ofTensor (A i)) : ℝ)) → 0 < f.pX → + (∑ i, (f (ofTensor (A i)) : ℝ) ^ (1 / f.pX)) ^ f.pX ≤ + (f (ofTensor (Tensor.sharedFirst A)) : ℝ)) + +variable (hdet : + ∀ (f : Character K) (a b : ℕ), + (f (ofTensor (determinantGradedTensor a b)) : ℝ) ≤ + (2 : ℝ) ^ f.pX * (f (ofTensor (polynomialTensor (a + 1) (b + 2))) : ℝ)) + +include hpositive htag hdet in +private theorem concave (f : Character K) (hp : 0 < f.pX) (m n : ℕ) : + poly f m (n + 2) ^ (1 / f.pX) + poly f m n ^ (1 / f.pX) ≤ + 2 * poly f m (n + 1) ^ (1 / f.pX) := by + have h := htag f (by decide : 0 < 2) _ + (determinant_family_value_pos hpositive f m n) hp + rw [ofTensor_determinant_uniform] at h + have ht := h.trans (hdet f m n) + simp only [ofTensor_determinant_family, Fin.sum_univ_two, Matrix.cons_val_zero, + Matrix.cons_val_one] at ht + change (poly f m (n + 2) ^ (1 / f.pX) + poly f m n ^ (1 / f.pX)) ^ f.pX ≤ + (2 : ℝ) ^ f.pX * poly f m (n + 1) at ht + have h₁ := poly_pos hpositive f m n + have h₂ := poly_pos hpositive f m (n + 2) + have he := root_le hp (by positivity) ht + rwa [Real.mul_rpow (by positivity) (poly_pos hpositive f _ _).le, ← Real.rpow_mul (by norm_num), + mul_one_div_cancel hp.ne', Real.rpow_one] at he + +variable (htrip : + ∀ (f : Character K) (a h : ℕ), 1 ≤ a → 1 ≤ h → + (f (ofTensor (triplingSectorTensor a h)) : ℝ) ≤ + (f (ofTensor (polynomialTensor a (3 * h + a - 1))) : ℝ)) + +include hpositive htag hdet htrip in +theorem poly_row (f : Character K) (hp : 0 < f.pX) (m : ℕ) : + Row (fun n => poly f m n ^ (1 / f.pX)) + (fun n => (f (swapYZ (ofTensor (polynomialTensor (m + 1) (n + 1)))) : ℝ) ^ (1 / f.pX)) m := by + refine ⟨fun n => Real.rpow_pos_of_pos (poly_pos hpositive f _ _) _, ?_, ?_⟩ + · apply antitone_nat_of_succ_le + intro n + simp only [TensorSpectrum.rowDifference, Nat.add_assoc, Nat.reduceAdd] + linarith only [concave hpositive htag hdet f hp m n] + · intro n + have h := htag f (by decide : 0 < 3) _ + (tripling_family_value_pos hpositive f (m + 1) (n + 1) (by omega) (by omega)) hp + rw [ofTensor_tripling_uniform] at h + have ht := h.trans (htrip f (m + 1) (n + 1) (by omega) (by omega)) + simp only [ofTensor_tripling_family, Fin.sum_univ_three, Matrix.cons_val_zero, + Matrix.cons_val_one, Matrix.cons_val_two, Matrix.head_cons, Matrix.tail_cons] at ht + rw [show 3 * (n + 1) + (m + 1) - 1 = (3 * n + m + 2) + 1 by omega] at ht + have he := root_le hp (by positivity) ht + unfold poly + linarith only [he] + +private def price (f : Character K) (i : Fin 6) (m n : ℕ) : ℝ := + Real.log (poly (f.permuted i) m n) + +variable (hupper : + ∀ (f : Character K) (a b : ℕ), 1 ≤ a → 1 ≤ b → + (f (ofTensor (polynomialTensor a b)) : ℝ) ≤ (a : ℝ) + (b : ℝ) - 1) + +include hpositive hupper in +private theorem price_bound (f : Character K) (i : Fin 6) : LogBound (price f i) := by + intro m n + apply Real.log_le_log (poly_pos hpositive _ _ _) + have h := hupper (f.permuted i) (m + 1) (n + 1) (by omega) (by omega) + push_cast at h + unfold poly + linarith + +private theorem price_swap (f : Character K) (i : Fin 6) : + Function.swap (price f i) = price f (permuteSwapXY i) := by + funext m n + unfold Function.swap price poly + rw [← swapXY_polynomialTensor (m + 1) (n + 1), f.permuted_swapXY] + +include hpositive htag hdet htrip in +private theorem paired_prices (f : Character K) (i j : Fin 6) {d : ℝ} + (hd : 0 < d) (hi : (f.permuted i).pX = d) (hj : (f.permuted j).pX = d) + (hij : permuteSwapYZ i = j) (hji : permuteSwapYZ j = i) : + Increments (price f i) (price f j) d := by + apply increments_of_rows hd (poly_pos hpositive _) (poly_pos hpositive _) + · intro m + have h := poly_row hpositive htag hdet htrip (f.permuted i) (hi.symm ▸ hd) m + simp only [hi, f.permuted_swapYZ, hij] at h + exact h + · intro m + have h := poly_row hpositive htag hdet htrip (f.permuted j) (hj.symm ▸ hd) m + simp only [hj, f.permuted_swapYZ, hji] at h + exact h + +include hpositive htag hdet htrip hupper in +theorem character_bound (f : Character K) (A B C : ℕ) + (hA : 0 < A) (hB : 0 < B) (hC : 0 < C) : + 4 * (f.pX * B * C + f.pY * A * C + f.pZ * A * B) ≤ ((A : ℝ) + B + C) ^ 2 := by + have h (x : ℝ) (hx : x ≤ 1) (i j : ℕ) : x * i * j ≤ (i : ℝ) * j := + mul_le_mul_of_nonneg_right (mul_le_of_le_one_left (by positivity) hx) (by positivity) + have h₁ := h _ f.pX_le_one B C + have h₂ := h _ f.pY_le_one A C + have h₃ := h _ f.pZ_le_one A B + rcases eq_or_lt_of_le f.pX_nonneg with hx | hx + · rw [← hx] + linarith only [h₂, h₃, sq_nonneg ((A : ℝ) - B - C)] + rcases eq_or_lt_of_le f.pY_nonneg with hy | hy + · rw [← hy] + linarith only [h₁, h₃, sq_nonneg ((B : ℝ) - A - C)] + rcases eq_or_lt_of_le f.pZ_nonneg with hz | hz + · rw [← hz] + linarith only [h₁, h₂, sq_nonneg ((C : ℝ) - A - B)] + refine weighted_growth hx.le hy.le hz.le ?_ ?_ ?_ + (price_bound hpositive hupper f 0) (price_bound hpositive hupper f 2) + (price_bound hpositive hupper f 3) hA hB hC + · exact paired_prices hpositive htag hdet htrip f 0 2 hx + (by rw [f.permuted_pX]; rfl) (by rw [f.permuted_pX]; rfl) rfl rfl + · rw [price_swap] + exact paired_prices hpositive htag hdet htrip f 1 3 hy + (by rw [f.permuted_pX]; rfl) (by rw [f.permuted_pX]; rfl) rfl rfl + · rw [price_swap, price_swap] + exact paired_prices hpositive htag hdet htrip f 4 5 hz + (by rw [f.permuted_pX]; rfl) (by rw [f.permuted_pX]; rfl) rfl rfl + +end Bounds + +end MatrixMultiplicationAllFields.TensorSpectrum.PolynomialGrowth diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialRank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialRank.lean new file mode 100644 index 0000000000..dfb915b45d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialRank.lean @@ -0,0 +1,57 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors +public import Lean.Elab.Tactic.Omega + +/-! +# Rank of polynomial multiplication by interpolation + +An evaluation family and its interpolation coefficients give one rank-one term +per node. All interpolation identities are supplied by the coefficient model. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + +variable {K : Type*} [CommSemiring K] [Nontrivial K] + +/-- The evaluation and interpolation witnesses give the usual convolution rank bound. -/ +theorem polynomialTensor_rankAtMost_of_interpolation (a b : ℕ) + (nodes : Fin (a + b - 1) → K) (weight : Fin (a + b - 1) → ℕ → K) + (coefficientIdentity : ∀ (p : Polynomial K) (d : ℕ), + p.degree < Fintype.card (Fin (a + b - 1)) → + p.coeff d = ∑ t, p.eval (nodes t) * weight t d) : + Tensor.RankAtMost (polynomialTensor (K := K) a b) (a + b - 1) := by + classical + refine ⟨(fun t i => nodes t ^ i.val), + (fun t j => nodes t ^ j.val), + (fun t k => weight t k.val), ?_⟩ + funext i j k + have hsum : i.val + j.val < a + b - 1 := by + have hi := i.isLt + have hj := j.isLt + omega + have hdegree : ((Polynomial.X : Polynomial K) ^ (i.val + j.val)).degree < + Fintype.card (Fin (a + b - 1)) := by + rw [Polynomial.degree_X_pow, Fintype.card_fin] + exact WithBot.coe_lt_coe.mpr hsum + have hcoeff := coefficientIdentity + ((Polynomial.X : Polynomial K) ^ (i.val + j.val)) k.val hdegree + refine (polynomialTensor_eq_coeff (K := K) a b i j k).trans ?_ + simpa only [Polynomial.eval_pow, Polynomial.eval_X, Polynomial.eval_mul, + Tensor.rankOne, pow_add] + using hcoeff + +end MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialSectorFamily.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialSectorFamily.lean new file mode 100644 index 0000000000..52bc8e38e3 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialSectorFamily.lean @@ -0,0 +1,102 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.WeightedPolynomials +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialSectors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.LocalTensor + +/-! +# The polynomial witness for the three-sector degeneration + +Every coefficient has degree at most one. Its constant coefficient is the +entire shared-first-input sector assembly. At each nonzero parameter the +evaluated tensor is an actual restriction of the original polynomial tensor. +These explicit facts support interpolation without assuming that an arbitrary +tensor character preserves topological limits. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + +variable {K : Type*} [CommSemiring K] + +/-- The same family as the diagonal degeneration, expressed in the complete +sector bases on the last two legs. The first input is unchanged. -/ +def triplingPolynomialFamily (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + Tensor (Polynomial K) (Fin a) (TriplingY a h) (TriplingZ a h) := + Tensor.pullback id (triplingYEquiv a h ha hh) (triplingZEquiv a h ha hh) + (weightedPolynomial (polynomialTensor a (triplingWidth a h)) + (fun _ => 0) (fun y => triplingYWeight a h y.val) + (fun z => triplingZWeight a h z.val)) + +theorem tripling_source_weights_nonneg (a h : ℕ) (ha : 1 ≤ a) + (x : Fin a) (y : Fin (triplingWidth a h)) + (z : Fin (a + triplingWidth a h - 1)) + (hc : polynomialTensor (K := K) a (triplingWidth a h) x y z ≠ 0) : + 0 ≤ (0 : ℤ) + triplingYWeight a h y.val + triplingZWeight a h z.val := by + have hs : x.val + y.val = z.val := by + by_contra hn + exact hc (by simp [polynomialTensor, hn]) + simpa using tripling_weight_nonneg ha x.isLt hs + +private theorem tripling_weights_toNat_le_one (a h y z : ℕ) : + ((0 : ℤ) + triplingYWeight a h y + triplingZWeight a h z).toNat ≤ 1 := by + unfold triplingYWeight triplingZWeight + split_ifs <;> decide + +/-- The constant coefficient retains all three branches, including their +vanishing cross-sector coefficients, in one shared first-input basis. -/ +theorem triplingPolynomialFamily_coeff_zero (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (x : Fin a) (y : TriplingY a h) (z : TriplingZ a h) : + (triplingPolynomialFamily (K := K) a h ha hh x y z).coeff 0 = + triplingSectorTensor a h x y z := by + change (weightedPolynomial (polynomialTensor a (triplingWidth a h)) + (fun _ => 0) (fun y => triplingYWeight a h y.val) + (fun z => triplingZWeight a h z.val) x + (triplingYEquiv a h ha hh y) (triplingZEquiv a h ha hh z)).coeff 0 = _ + rw [weightedPolynomial_coeff_zero _ _ _ _ (tripling_source_weights_nonneg a h ha)] + exact congrFun (congrFun (congrFun (triplingGraded_sector_assembly a h ha hh) x) y) z + +/-- There is no growing or unspecified approximation degree: every coordinate +of this explicit family has degree at most one. -/ +theorem triplingPolynomialFamily_degree_le (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (x : Fin a) (y : TriplingY a h) (z : TriplingZ a h) : + (triplingPolynomialFamily (K := K) a h ha hh x y z).degree ≤ (1 : ℕ) := by + exact weightedPolynomial_degree_le (polynomialTensor a (triplingWidth a h)) + (fun _ => 0) (fun y => triplingYWeight a h y.val) + (fun z => triplingZWeight a h z.val) (D := 1) + (fun _ y z _ => tripling_weights_toNat_le_one a h y.val z.val) + x (triplingYEquiv a h ha hh y) (triplingZEquiv a h ha hh z) + +/-- A weighted restriction yields the same evaluated tensor in the sector bases. -/ +theorem triplingPolynomialFamily_eval_mem_restrictionOrbit + (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) (t : K) + (he : (fun x y z => (weightedPolynomial (polynomialTensor a (triplingWidth a h)) + (fun _ => 0) (fun y => triplingYWeight a h y.val) + (fun z => triplingZWeight a h z.val) x y z).eval t) ∈ + LocalTensor.orbit (polynomialTensor a (triplingWidth a h))) : + (fun x y z => (triplingPolynomialFamily a h ha hh x y z).eval t) ∈ + LocalTensor.orbit (polynomialTensor a (triplingWidth a h)) := by + classical + let E : Tensor K (Fin a) (Fin (triplingWidth a h)) (Fin (a + triplingWidth a h - 1)) := + fun x y z => (weightedPolynomial (polynomialTensor a (triplingWidth a h)) + (fun _ => 0) (fun y => triplingYWeight a h y.val) + (fun z => triplingZWeight a h z.val) x y z).eval t + change Tensor.pullback id (triplingYEquiv a h ha hh) (triplingZEquiv a h ha hh) E ∈ _ + rw [Tensor.pullback_eq_restrict] + exact LocalTensor.restrict_mem he _ _ _ + +end MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialSectors.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialSectors.lean new file mode 100644 index 0000000000..c86b399e71 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialSectors.lean @@ -0,0 +1,435 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors + +/-! # Tripling sector coordinates and tensor assembly -/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + +variable {K : Type*} [CommSemiring K] + +/-- The second input length in the tripling construction. -/ +def triplingWidth (a h : ℕ) : ℕ := 3 * h + a - 1 + +/-- The middle interval of the second input has weight one. -/ +def triplingYWeight (a h y : ℕ) : ℤ := + if h ≤ y ∧ y < 2 * h + a - 1 then 1 else 0 + +/-- The middle output-dual interval has weight minus one. -/ +def triplingZWeight (a h z : ℕ) : ℤ := + if h + a - 1 ≤ z ∧ z < 2 * h + a - 1 then -1 else 0 + +/-- The three matched pairs of intervals, expressed with exclusive upper bounds. -/ +def triplingMatched (a h y z : ℕ) : Prop := + (y < h ∧ z < h + a - 1) ∨ + (h ≤ y ∧ y < 2 * h + a - 1 ∧ h + a - 1 ≤ z ∧ z < 2 * h + a - 1) ∨ + (2 * h + a - 1 ≤ y ∧ 2 * h + a - 1 ≤ z) + +instance triplingMatchedDecidable (a h y z : ℕ) : Decidable (triplingMatched a h y z) := by + unfold triplingMatched + infer_instance + +theorem tripling_support_left {a h x y z : ℕ} + (ha : 1 ≤ a) (hx : x < a) (hy : y < h) (hs : x + y = z) : + z < h + a - 1 := by omega + +theorem tripling_support_right {a h x y z : ℕ} + (hy : 2 * h + a - 1 ≤ y) (hs : x + y = z) : + 2 * h + a - 1 ≤ z := by omega + +/-- A supported middle output can only come from the middle second input. -/ +theorem tripling_support_middle {a h x y z : ℕ} + (ha : 1 ≤ a) (hx : x < a) (hs : x + y = z) + (hz : h + a - 1 ≤ z ∧ z < 2 * h + a - 1) : + h ≤ y ∧ y < 2 * h + a - 1 := by omega + +/-- No nonzero convolution coefficient has a negative total weight. -/ +theorem tripling_weight_nonneg {a h x y z : ℕ} + (ha : 1 ≤ a) (hx : x < a) (hs : x + y = z) : + 0 ≤ triplingYWeight a h y + triplingZWeight a h z := by + unfold triplingYWeight triplingZWeight + split_ifs <;> omega + +/-- Precisely the three matched sectors survive in weight zero. -/ +theorem tripling_weight_zero_iff {a h x y z : ℕ} + (ha : 1 ≤ a) (hx : x < a) (hs : x + y = z) : + triplingYWeight a h y + triplingZWeight a h z = 0 ↔ + triplingMatched a h y z := by + unfold triplingYWeight triplingZWeight triplingMatched + split_ifs <;> omega + +/-- Every term that disappears has weight exactly one, and goes from the +middle second-input sector to one of the two outer output sectors. -/ +theorem tripling_weight_one_iff {a h y z : ℕ} + (ha : 1 ≤ a) : + triplingYWeight a h y + triplingZWeight a h z = 1 ↔ + h ≤ y ∧ y < 2 * h + a - 1 ∧ + (z < h + a - 1 ∨ 2 * h + a - 1 ≤ z) := by + unfold triplingYWeight triplingZWeight + split_ifs <;> omega + +/-- The simultaneous weight-zero tensor, with one unchanged shared first leg. -/ +def triplingGraded (a h : ℕ) : + Tensor K (Fin a) (Fin (triplingWidth a h)) (Fin (a + triplingWidth a h - 1)) := + weightedLimit (polynomialTensor a (triplingWidth a h)) (fun _ => 0) + (fun y => triplingYWeight a h y.val) (fun z => triplingZWeight a h z.val) + +theorem triplingGraded_of_weights (a h : ℕ) + (x : Fin a) (y : Fin (triplingWidth a h)) + (z : Fin (a + triplingWidth a h - 1)) + (hw : triplingYWeight a h y.val + triplingZWeight a h z.val = 0) : + (triplingGraded (K := K)) a h x y z = polynomialTensor a (triplingWidth a h) x y z := by + simp [triplingGraded, weightedLimit, hw] + +/-- The full coefficient formula includes all vanishing cross-sector terms. -/ +theorem triplingGraded_coefficient (a h : ℕ) (ha : 1 ≤ a) + (x : Fin a) (y : Fin (triplingWidth a h)) + (z : Fin (a + triplingWidth a h - 1)) : + (triplingGraded (K := K)) a h x y z = + if x.val + y.val = z.val ∧ triplingMatched a h y.val z.val then 1 else 0 := by + classical + by_cases hs : x.val + y.val = z.val + · have hw := tripling_weight_zero_iff (h := h) ha x.isLt hs + simp [triplingGraded, weightedLimit, polynomialTensor, hs, hw] + · simp [triplingGraded, weightedLimit, polynomialTensor, hs] + +/-- Translate a coordinate into the left second-input sector. -/ +def triplingLeftY (a h : ℕ) (ha : 1 ≤ a) (j : Fin h) : Fin (triplingWidth a h) := + ⟨j.val, by have hj := j.isLt; dsimp [triplingWidth]; omega⟩ + +/-- Translate a coordinate into the left output sector. -/ +def triplingLeftZ (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (k : Fin (a + h - 1)) : Fin (a + triplingWidth a h - 1) := + ⟨k.val, by have hk := k.isLt; dsimp [triplingWidth]; omega⟩ + +/-- Translate a coordinate into the middle second-input sector. -/ +def triplingMiddleY (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (k : Fin (a + h - 1)) : Fin (triplingWidth a h) := + ⟨h + k.val, by have hk := k.isLt; dsimp [triplingWidth]; omega⟩ + +/-- Translate a coordinate into the middle output sector. -/ +def triplingMiddleZ (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (j : Fin h) : Fin (a + triplingWidth a h - 1) := + ⟨h + a - 1 + j.val, by have hj := j.isLt; dsimp [triplingWidth]; omega⟩ + +/-- Translate a coordinate into the right second-input sector. -/ +def triplingRightY (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (j : Fin h) : Fin (triplingWidth a h) := + ⟨2 * h + a - 1 + j.val, by have hj := j.isLt; dsimp [triplingWidth]; omega⟩ + +/-- Translate a coordinate into the right output sector. -/ +def triplingRightZ (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (k : Fin (a + h - 1)) : Fin (a + triplingWidth a h - 1) := + ⟨2 * h + a - 1 + k.val, by have hk := k.isLt; dsimp [triplingWidth]; omega⟩ + +/-- Reversal used only in the middle branch identification. -/ +def triplingReverse {a : ℕ} (u : Fin a) : Fin a := + ⟨a - 1 - u.val, by have hu := u.isLt; omega⟩ + +theorem triplingReverse_involutive {a : ℕ} (u : Fin a) : + triplingReverse (triplingReverse u) = u := by + apply Fin.ext + have hu := u.isLt + dsimp [triplingReverse] + omega + +theorem tripling_left_weights (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (j : Fin h) (k : Fin (a + h - 1)) : + triplingYWeight a h (triplingLeftY a h ha j).val + + triplingZWeight a h (triplingLeftZ a h ha hh k).val = 0 := by + have hj := j.isLt + have hk := k.isLt + dsimp [triplingYWeight, triplingZWeight, triplingLeftY, triplingLeftZ] + split_ifs <;> omega + +theorem tripling_middle_weights (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (k : Fin (a + h - 1)) (j : Fin h) : + triplingYWeight a h (triplingMiddleY a h ha hh k).val + + triplingZWeight a h (triplingMiddleZ a h ha hh j).val = 0 := by + have hj := j.isLt + have hk := k.isLt + dsimp [triplingYWeight, triplingZWeight, triplingMiddleY, triplingMiddleZ] + split_ifs <;> omega + +theorem tripling_right_weights (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (j : Fin h) (k : Fin (a + h - 1)) : + triplingYWeight a h (triplingRightY a h ha hh j).val + + triplingZWeight a h (triplingRightZ a h ha hh k).val = 0 := by + dsimp [triplingYWeight, triplingZWeight, triplingRightY, triplingRightZ] + split_ifs <;> omega + +/-- The left branch is exactly polynomial multiplication of lengths `a,h`. -/ +theorem tripling_left_coefficient (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (x : Fin a) (j : Fin h) (k : Fin (a + h - 1)) : + (triplingGraded (K := K)) a h x (triplingLeftY a h ha j) (triplingLeftZ a h ha hh k) = + polynomialTensor a h x j k := by + rw [triplingGraded_of_weights a h x _ _ (tripling_left_weights a h ha hh j k)] + rfl + +/-- The right branch is the same tensor after translations on the last two legs. -/ +theorem tripling_right_coefficient (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (x : Fin a) (j : Fin h) (k : Fin (a + h - 1)) : + (triplingGraded (K := K)) a h x (triplingRightY a h ha hh j) (triplingRightZ a h ha hh k) = + polynomialTensor a h x j k := by + rw [triplingGraded_of_weights a h x _ _ (tripling_right_weights a h ha hh j k)] + have hs : x.val + (2 * h + a - 1 + j.val) = 2 * h + a - 1 + k.val ↔ + x.val + j.val = k.val := by omega + simp only [polynomialTensor, triplingRightY, triplingRightZ, hs] + +/-- In the middle branch the second and third tensor legs are exchanged, and +the first basis is reversed. This identity does not reverse the first basis +of either outer branch or of the whole simultaneous degeneration. -/ +theorem tripling_middle_coefficient (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (u : Fin a) (k : Fin (a + h - 1)) (j : Fin h) : + (triplingGraded (K := K)) a h (triplingReverse u) + (triplingMiddleY a h ha hh k) (triplingMiddleZ a h ha hh j) = + polynomialTensor a h u j k := by + rw [triplingGraded_of_weights a h (triplingReverse u) _ _ + (tripling_middle_weights a h ha hh k j)] + have hu := u.isLt + have hs : a - 1 - u.val + (h + k.val) = h + a - 1 + j.val ↔ + u.val + j.val = k.val := by omega + simp only [polynomialTensor, triplingReverse, triplingMiddleY, triplingMiddleZ, hs] + +/-- The three second-input images are pairwise disjoint. -/ +theorem tripling_second_sectors_disjoint (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (j₁ j₂ : Fin h) (k : Fin (a + h - 1)) : + triplingLeftY a h ha j₁ ≠ triplingMiddleY a h ha hh k ∧ + triplingMiddleY a h ha hh k ≠ triplingRightY a h ha hh j₂ ∧ + triplingLeftY a h ha j₁ ≠ triplingRightY a h ha hh j₂ := by + have hj₁ := j₁.isLt + have hk := k.isLt + constructor + · intro he + have hv := congrArg Fin.val he + dsimp [triplingLeftY, triplingMiddleY] at hv + omega + constructor + · intro he + have hv := congrArg Fin.val he + dsimp [triplingMiddleY, triplingRightY] at hv + omega + · intro he + have hv := congrArg Fin.val he + dsimp [triplingLeftY, triplingRightY] at hv + omega + +/-- The three output images are pairwise disjoint as well. -/ +theorem tripling_output_sectors_disjoint (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) + (k₁ k₂ : Fin (a + h - 1)) (j : Fin h) : + triplingLeftZ a h ha hh k₁ ≠ triplingMiddleZ a h ha hh j ∧ + triplingMiddleZ a h ha hh j ≠ triplingRightZ a h ha hh k₂ ∧ + triplingLeftZ a h ha hh k₁ ≠ triplingRightZ a h ha hh k₂ := by + have hk₁ := k₁.isLt + have hj := j.isLt + constructor + · intro he + have hv := congrArg Fin.val he + dsimp [triplingLeftZ, triplingMiddleZ] at hv + omega + constructor + · intro he + have hv := congrArg Fin.val he + dsimp [triplingMiddleZ, triplingRightZ] at hv + omega + · intro he + have hv := congrArg Fin.val he + dsimp [triplingLeftZ, triplingRightZ] at hv + omega + +/-- The three complete second-input sectors, before forgetting their labels. -/ +abbrev TriplingY (a h : ℕ) := Fin h ⊕ (Fin (a + h - 1) ⊕ Fin h) + +/-- The corresponding complete output sectors. -/ +abbrev TriplingZ (a h : ℕ) := Fin (a + h - 1) ⊕ (Fin h ⊕ Fin (a + h - 1)) + +/-- In the case `.inl j`, this construction gives `triplingLeftY a h ha j`. -/ +def triplingYMap (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + TriplingY a h → Fin (triplingWidth a h) + | .inl j => triplingLeftY a h ha j + | .inr (.inl k) => triplingMiddleY a h ha hh k + | .inr (.inr j) => triplingRightY a h ha hh j + +/-- In the case `.inl k`, this construction gives `triplingLeftZ a h ha hh k`. -/ +def triplingZMap (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + TriplingZ a h → Fin (a + triplingWidth a h - 1) + | .inl k => triplingLeftZ a h ha hh k + | .inr (.inl j) => triplingMiddleZ a h ha hh j + | .inr (.inr k) => triplingRightZ a h ha hh k + +theorem triplingYMap_injective (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + Function.Injective (triplingYMap a h ha hh) := by + intro u v he + rcases u with j | (k | j) <;> rcases v with j' | (k' | j') + all_goals + have hv := congrArg Fin.val he + simp only [triplingYMap, triplingLeftY, triplingMiddleY, triplingRightY] at hv + first + | (exfalso; omega) + | (simp only [Sum.inl.injEq, Sum.inr.injEq]; apply Fin.ext; omega) + +theorem triplingZMap_injective (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + Function.Injective (triplingZMap a h ha hh) := by + intro u v he + rcases u with k | (j | k) <;> rcases v with k' | (j' | k') + all_goals + have hv := congrArg Fin.val he + simp only [triplingZMap, triplingLeftZ, triplingMiddleZ, triplingRightZ] at hv + first + | (exfalso; omega) + | (simp only [Sum.inl.injEq, Sum.inr.injEq]; apply Fin.ext; omega) + +/-- All second-input coordinates occur in exactly one sector. -/ +theorem triplingYMap_surjective (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + Function.Surjective (triplingYMap a h ha hh) := by + intro y + have hy := y.isLt + dsimp [triplingWidth] at hy + by_cases hl : y.val < h + · refine ⟨.inl ⟨y.val, hl⟩, ?_⟩ + apply Fin.ext + rfl + · by_cases hm : y.val < 2 * h + a - 1 + · refine ⟨.inr (.inl ⟨y.val - h, by omega⟩), ?_⟩ + apply Fin.ext + dsimp [triplingYMap, triplingMiddleY] + omega + · refine ⟨.inr (.inr ⟨y.val - (2 * h + a - 1), by omega⟩), ?_⟩ + apply Fin.ext + dsimp [triplingYMap, triplingRightY] + omega + +/-- All output coordinates occur in exactly one corresponding sector. -/ +theorem triplingZMap_surjective (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + Function.Surjective (triplingZMap a h ha hh) := by + intro z + have hz := z.isLt + dsimp [triplingWidth] at hz + by_cases hl : z.val < h + a - 1 + · refine ⟨.inl ⟨z.val, by omega⟩, ?_⟩ + apply Fin.ext + rfl + · by_cases hm : z.val < 2 * h + a - 1 + · refine ⟨.inr (.inl ⟨z.val - (h + a - 1), by omega⟩), ?_⟩ + apply Fin.ext + dsimp [triplingZMap, triplingMiddleZ] + omega + · refine ⟨.inr (.inr ⟨z.val - (2 * h + a - 1), by omega⟩), ?_⟩ + apply Fin.ext + dsimp [triplingZMap, triplingRightZ] + omega + +/-- A single simultaneous second-input basis equivalence. -/ +def triplingYEquiv (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + TriplingY a h ≃ Fin (triplingWidth a h) := + Equiv.ofBijective (triplingYMap a h ha hh) + ⟨triplingYMap_injective a h ha hh, triplingYMap_surjective a h ha hh⟩ + +/-- A single simultaneous output basis equivalence. -/ +def triplingZEquiv (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + TriplingZ a h ≃ Fin (a + triplingWidth a h - 1) := + Equiv.ofBijective (triplingZMap a h ha hh) + ⟨triplingZMap_injective a h ha hh, triplingZMap_surjective a h ha hh⟩ + +/-- The actual common-first-input assembly. Its middle summand, in the same +first-input coordinates as the outer summands, has reversed first coefficients. +Every cross-sector coefficient is zero. -/ +def triplingSectorTensor (a h : ℕ) : Tensor K (Fin a) (TriplingY a h) (TriplingZ a h) + | x, .inl j, .inl k => polynomialTensor a h x j k + | x, .inr (.inl k), .inr (.inl j) => polynomialTensor a h (triplingReverse x) j k + | x, .inr (.inr j), .inr (.inr k) => polynomialTensor a h x j k + | _, _, _ => 0 + +/-- Reindexing the last two legs by their single complete sector equivalences +gives the full assembled tensor. The first input is literally unchanged. -/ +theorem triplingGraded_sector_assembly (a h : ℕ) (ha : 1 ≤ a) (hh : 1 ≤ h) : + (fun x y z => (triplingGraded (K := K)) a h x + (triplingYEquiv a h ha hh y) (triplingZEquiv a h ha hh z)) = + triplingSectorTensor a h := by + funext x y z + change triplingGraded a h x (triplingYMap a h ha hh y) + (triplingZMap a h ha hh z) = triplingSectorTensor a h x y z + rcases y with j | (k | j) <;> rcases z with k' | (j' | k') + · exact tripling_left_coefficient a h ha hh x j k' + · rw [triplingGraded_coefficient a h ha] + have hj := j.isLt + have hx := x.isLt + have hn : ¬(x.val + (triplingYMap a h ha hh (.inl j)).val = + (triplingZMap a h ha hh (.inr (.inl j'))).val ∧ + triplingMatched a h (triplingYMap a h ha hh (.inl j)).val + (triplingZMap a h ha hh (.inr (.inl j'))).val) := by + dsimp [triplingMatched, triplingYMap, triplingZMap, triplingLeftY, + triplingMiddleZ] + omega + simp only [hn, ite_false, triplingSectorTensor] + · rw [triplingGraded_coefficient a h ha] + have hj := j.isLt + have hx := x.isLt + have hn : ¬(x.val + (triplingYMap a h ha hh (.inl j)).val = + (triplingZMap a h ha hh (.inr (.inr k'))).val ∧ + triplingMatched a h (triplingYMap a h ha hh (.inl j)).val + (triplingZMap a h ha hh (.inr (.inr k'))).val) := by + dsimp [triplingMatched, triplingYMap, triplingZMap, triplingLeftY, + triplingRightZ] + omega + simp only [hn, ite_false, triplingSectorTensor] + · rw [triplingGraded_coefficient a h ha] + have hk := k.isLt + have hk' := k'.isLt + have hn : ¬(x.val + (triplingYMap a h ha hh (.inr (.inl k))).val = + (triplingZMap a h ha hh (.inl k')).val ∧ + triplingMatched a h (triplingYMap a h ha hh (.inr (.inl k))).val + (triplingZMap a h ha hh (.inl k')).val) := by + dsimp [triplingMatched, triplingYMap, triplingZMap, triplingMiddleY, + triplingLeftZ] + omega + simp only [hn, ite_false, triplingSectorTensor] + · simpa only [triplingReverse_involutive, triplingYMap, triplingZMap, + triplingSectorTensor] using + tripling_middle_coefficient a h ha hh (triplingReverse x) k j' + · rw [triplingGraded_coefficient a h ha] + have hk := k.isLt + have hn : ¬(x.val + (triplingYMap a h ha hh (.inr (.inl k))).val = + (triplingZMap a h ha hh (.inr (.inr k'))).val ∧ + triplingMatched a h (triplingYMap a h ha hh (.inr (.inl k))).val + (triplingZMap a h ha hh (.inr (.inr k'))).val) := by + dsimp [triplingMatched, triplingYMap, triplingZMap, triplingMiddleY, + triplingRightZ] + omega + simp only [hn, ite_false, triplingSectorTensor] + · rw [triplingGraded_coefficient a h ha] + have hk' := k'.isLt + have hn : ¬(x.val + (triplingYMap a h ha hh (.inr (.inr j))).val = + (triplingZMap a h ha hh (.inl k')).val ∧ + triplingMatched a h (triplingYMap a h ha hh (.inr (.inr j))).val + (triplingZMap a h ha hh (.inl k')).val) := by + dsimp [triplingMatched, triplingYMap, triplingZMap, triplingRightY, + triplingLeftZ] + omega + simp only [hn, ite_false, triplingSectorTensor] + · rw [triplingGraded_coefficient a h ha] + have hj' := j'.isLt + have hn : ¬(x.val + (triplingYMap a h ha hh (.inr (.inr j))).val = + (triplingZMap a h ha hh (.inr (.inl j'))).val ∧ + triplingMatched a h (triplingYMap a h ha hh (.inr (.inr j))).val + (triplingZMap a h ha hh (.inr (.inl j'))).val) := by + dsimp [triplingMatched, triplingYMap, triplingZMap, triplingRightY, + triplingMiddleZ] + omega + simp only [hn, ite_false, triplingSectorTensor] + · exact tripling_right_coefficient a h ha hh x j k' + +end MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialTensors.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialTensors.lean new file mode 100644 index 0000000000..646399a91c --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/PolynomialTensors.lean @@ -0,0 +1,101 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Polynomial.ComplexPolynomialApproximation +public import Lean.Elab.Tactic.Omega + +/-! # Convolution tensors and diagonal coefficient weights -/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + +variable {K : Type*} [CommSemiring K] + +/-- Multiplication of polynomials with `a` and `b` coefficients, with every +output coefficient retained. -/ +def polynomialTensor (a b : ℕ) : + Tensor K (Fin a) (Fin b) (Fin (a + b - 1)) := + fun i j k => if i.val + j.val = k.val then 1 else 0 + +@[simp] theorem polynomialTensor_apply (a b : ℕ) + (i : Fin a) (j : Fin b) (k : Fin (a + b - 1)) : + (polynomialTensor (K := K)) a b i j k = if i.val + j.val = k.val then 1 else 0 := rfl + +/-- The tensor coefficient is the coefficient of the product of the two input +monomials. -/ +theorem polynomialTensor_eq_coeff (a b : ℕ) + (i : Fin a) (j : Fin b) (k : Fin (a + b - 1)) : + polynomialTensor a b i j k = + ((Polynomial.X : Polynomial K) ^ (i.val + j.val)).coeff k.val := by + simp [polynomialTensor, Polynomial.coeff_X_pow, eq_comm] + +/-- Commuting the input factors only reindexes the equal-sized output space. -/ +theorem polynomialTensor_swap (a b : ℕ) + (i : Fin a) (j : Fin b) (k : Fin (a + b - 1)) : + (polynomialTensor (K := K)) a b i j k = + polynomialTensor b a j i (Fin.cast (by omega) k) := by + simp [polynomialTensor, Nat.add_comm] + +/-- With a scalar as the first input, multiplication is the identity pairing +between the second input and output coefficient coordinates. -/ +theorem polynomialTensor_one_left (b : ℕ) + (i : Fin 1) (j : Fin b) (k : Fin (1 + b - 1)) : + (polynomialTensor (K := K)) 1 b i j k = if j.val = k.val then 1 else 0 := by + simp [polynomialTensor] + +variable {X Y Z : Type*} + +/-- The part of a tensor with total diagonal weight zero. -/ +def weightedLimit (T : Tensor K X Y Z) + (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) : Tensor K X Y Z := + fun x y z => if wx x + wy y + wz z = 0 then T x y z else 0 + +/-- The polynomial coefficient family. Negative total weights +occur only at zero coefficients in the degeneration theorem. -/ +def weightedFamily (T : Tensor K X Y Z) + (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) + (t : K) : Tensor K X Y Z := + fun x y z => t ^ (wx x + wy y + wz z).toNat * T x y z + +theorem weightedFamily_zero (T : Tensor K X Y Z) + (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) + (h : ∀ x y z, T x y z ≠ 0 → 0 ≤ wx x + wy y + wz z) : + weightedFamily T wx wy wz 0 = weightedLimit T wx wy wz := by + funext x y z + by_cases hT : T x y z = 0 + · simp [weightedFamily, weightedLimit, hT] + · have hnonneg := h x y z hT + by_cases hw : wx x + wy y + wz z = 0 + · simp [weightedFamily, weightedLimit, hw] + · have hnatne : (wx x + wy y + wz z).toNat ≠ 0 := by + intro he + have hc := Int.toNat_of_nonneg hnonneg + rw [he] at hc + exact hw hc.symm + simp [weightedFamily, weightedLimit, hw, zero_pow hnatne] + +/-- Diagonal local coefficient matrices multiply the three corresponding +coefficient factors, with all off-diagonal contributions vanishing. -/ +theorem restrict_diagonal [Fintype X] [Fintype Y] [Fintype Z] + [DecidableEq X] [DecidableEq Y] [DecidableEq Z] + (T : Tensor K X Y Z) (a : X → K) (b : Y → K) (c : Z → K) : + Tensor.restrict (fun x' x => if x = x' then a x else 0) + (fun y' y => if y = y' then b y else 0) + (fun z' z => if z = z' then c z else 0) T = + fun x y z => a x * b y * c z * T x y z := by + classical + funext x y z + simp [Tensor.restrict, ite_mul, mul_ite] + +end MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/RankDescent.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/RankDescent.lean new file mode 100644 index 0000000000..7c1cf7cf63 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/RankDescent.lean @@ -0,0 +1,60 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensor +public import Mathlib.LinearAlgebra.Basis.Basic +public import Mathlib.Logic.Equiv.Fin.Basic + +/-! +# Descent of rank along a finite algebra basis + +Expand the two input legs in the basis and apply a linear functional to the +output. The functional sending one to one recovers the original coefficients. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +open scoped BigOperators + +/-- A basis of size `d` gives a rank bound with `d²` copies of each term. -/ +theorem RankAtMost.descend_algebra {R L X Y Z : Type*} [CommSemiring R] [CommSemiring L] + [Algebra R L] {d r : ℕ} (B : Module.Basis (Fin d) R L) (π : L →ₗ[R] R) + (hπ : π 1 = 1) {T : Tensor R X Y Z} + (h : RankAtMost (fun x y z => algebraMap R L (T x y z)) r) : + RankAtMost T (r * d ^ 2) := by + classical + obtain ⟨a, b, c, habc⟩ := h + have expand (u v w : L) : + ∑ l : Fin d, ∑ m : Fin d, B.repr u l * B.repr v m * π (B l * B m * w) = + π (u * v * w) := by + conv_rhs => + rw [← B.sum_repr u, Finset.sum_mul, Finset.sum_mul, map_sum] + apply Finset.sum_congr rfl + intro l _ + conv_rhs => + rw [← B.sum_repr v, Finset.mul_sum, Finset.sum_mul, map_sum] + apply Finset.sum_congr rfl + intro m _ + rw [smul_mul_assoc, mul_smul_comm, smul_mul_assoc, smul_mul_assoc, map_smul, map_smul, + smul_eq_mul, smul_eq_mul, mul_assoc] + rw [pow_two] + let e : Fin r × Fin d × Fin d ≃ Fin (r * (d * d)) := + ((Equiv.refl (Fin r)).prodCongr finProdFinEquiv).trans finProdFinEquiv + refine ⟨fun l x => B.repr (a (e.symm l).1 x) (e.symm l).2.1, + fun l y => B.repr (b (e.symm l).1 y) (e.symm l).2.2, + fun l z => π (B (e.symm l).2.1 * B (e.symm l).2.2 * c (e.symm l).1 z), ?_⟩ + funext x y z + rw [← e.sum_comp] + simp only [rankOne, Equiv.symm_apply_apply, Fintype.sum_prod_type, expand, ← map_sum] + have hxyz : algebraMap R L (T x y z) = ∑ i, a i x * b i y * c i z := + congrFun (congrFun (congrFun habc x) y) z + rw [← hxyz, Algebra.algebraMap_eq_smul_one, map_smul, hπ, smul_eq_mul, mul_one] + +end MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/RectangularRank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/RectangularRank.lean new file mode 100644 index 0000000000..91af4cd605 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/RectangularRank.lean @@ -0,0 +1,75 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.Rectangle.Bounds + +/-! +# Rank and character bounds for products of three dot tensors + +The singleton legs implement the cyclic identification of the matrix +coordinates. The rounded side lengths give the corresponding price bound. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent.Rectangle + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +variable {K : Type*} [CommSemiring K] + +/-- The quantity computed by `dotX j * dotY i * dotZ k`. -/ +def dots (i j k : ℕ) : TensorClass K := dotX j * dotY i * dotZ k + +theorem dots_power (i j k t : ℕ) : dots (K := K) (i ^ t) (j ^ t) (k ^ t) = (dots i j k) ^ t := by + induction t with + | zero => simp [dots] + | succ t ih => + rw [pow_succ, pow_succ, pow_succ, pow_succ, ← ih] + simp only [dots, ← dotX_mul, ← dotY_mul, ← dotZ_mul] + exact (congrArg (· * _) (mul_mul_mul_comm _ _ _ _)).trans (mul_mul_mul_comm _ _ _ _) + +theorem rank_of_dots {i j k r : ℕ} (h : dots i j k ≤ (r : TensorClass K)) : + MatrixRank K i j k r := by + have hr := (TensorClass.rank_mono h).trans (show TensorClass.rank (r : TensorClass K) ≤ r by + rw [natCast_eq_ofTensor_natTensor, rank_ofTensor] + exact (CoefficientTensor.rank_le_iff _ _).mpr (CoefficientTensor.rankAtMost_natTensor r)) + rw [dots, dotX, dotY, dotZ, ofTensor_mul, ofTensor_mul, rank_ofTensor] at hr + obtain ⟨a, b, c, he⟩ := (CoefficientTensor.rank_le_iff _ _).mp hr + refine ⟨fun l x => a l (((), x.1), x.2), fun l y => b l ((y.2, ()), y.1), + fun l z => c l ((z.2, z.1), ()), fun x y z => ?_⟩ + have hh := congrFun (congrFun (congrFun he (((), x.1), x.2)) ((y.2, ()), y.1)) ((z.2, z.1), ()) + refine hh.symm.trans ?_ + simp [Tensor.product, CoefficientTensor.dotXCoeff, + CoefficientTensor.dotYCoeff, CoefficientTensor.dotZCoeff, ite_and] + grind + +theorem price_dots (f : Character K) {n : ℕ} (hn : 0 < n) {a b c : ℝ} + (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + (f (dots (side n a) (side n b) (side n c)) : ℝ) ≤ + 8 * (n : ℝ) ^ (b * f.pX + a * f.pY + c * f.pZ) := by + simp only [dots, Character.map_mul, NNReal.coe_mul] + change f.dotXValue _ * f.dotYValue _ * f.dotZValue _ ≤ _ + rw [f.dotXValue_eq_rpow _ (side_pos hn b), f.dotYValue_eq_rpow _ (side_pos hn a), + f.dotZValue_eq_rpow _ (side_pos hn c)] + have hn₀ : 0 < (n : ℝ) := by positivity + calc + _ ≤ (2 * (n : ℝ) ^ (b * f.pX)) * (2 * (n : ℝ) ^ (a * f.pY)) * + (2 * (n : ℝ) ^ (c * f.pZ)) := by + gcongr + · exact rounded_dot hn hb f.pX_nonneg f.pX_le_one + · exact rounded_dot hn ha f.pY_nonneg f.pY_le_one + · exact rounded_dot hn hc f.pZ_nonneg f.pZ_le_one + _ = _ := by rw [Real.rpow_add hn₀, Real.rpow_add hn₀]; ring + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/RestrictionInterpolation.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/RestrictionInterpolation.lean new file mode 100644 index 0000000000..197021a4ae --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/RestrictionInterpolation.lean @@ -0,0 +1,186 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.LocalTensor +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Polynomial.ComplexPolynomialApproximation +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorRestrictionComposition +public import Mathlib.Tactic.Choose + +/-! +# Local restrictions of sums and polynomial powers + +Linear combinations of restrictions use one independent source copy per +summand. Coefficients and evaluations of a polynomial word use the actual tensor power. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixExponent +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.RestrictionInterpolation + +variable {R : Type*} [CommSemiring R] + +section RestrictionAlgebra + +variable {X Y Z U V W : Type*} +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- Independent maps on each full source copy may have the same target. The +result is the sum of their restricted tensors, with no cross-copy terms. -/ +theorem restrict_directSum_sum {ι : Type*} [Fintype ι] [DecidableEq ι] + (T : ι → Tensor R X Y Z) + (a : ι → U → X → R) (b : ι → V → Y → R) (c : ι → W → Z → R) : + Tensor.restrict (fun u x => a x.1 u x.2) + (fun v y => b y.1 v y.2) (fun w z => c z.1 w z.2) + (Tensor.directSum T) = + fun u v w => ∑ i, Tensor.restrict (a i) (b i) (c i) (T i) u v w := by + classical + funext u v w + simp [Tensor.restrict, Tensor.directSum, Fintype.sum_prod_type, + ite_and, mul_ite] + +/-- Scaling one local map scales the whole restricted coefficient tensor. -/ +theorem restrict_scale_first (T : Tensor R X Y Z) + (a : U → X → R) (b : V → Y → R) (c : W → Z → R) (s : R) : + Tensor.restrict (fun u x => s * a u x) b c T = + fun u v w => s * Tensor.restrict a b c T u v w := by + funext u v w + simp only [Tensor.restrict, Finset.mul_sum] + apply Finset.sum_congr rfl + intro x hx + apply Finset.sum_congr rfl + intro y hy + apply Finset.sum_congr rfl + intro z hz + ring + +/-- Tensor products of the local maps give a local restriction of every power. +Every input coordinate in every position is summed independently. -/ +theorem restrict_power (T : Tensor R X Y Z) + (a : U → X → R) (b : V → Y → R) (c : W → Z → R) (j : ℕ) : + Tensor.restrict + (fun u x => ∏ i, a (u i) (x i)) + (fun v y => ∏ i, b (v i) (y i)) + (fun w z => ∏ i, c (w i) (z i)) (Tensor.power T j) = + Tensor.power (Tensor.restrict a b c T) j := by + funext u v w + simp only [Tensor.restrict, Tensor.power, Fintype.prod_sum, + Finset.prod_mul_distrib] + +theorem power_mem_restrictionOrbit {T : Tensor R X Y Z} + {S : Tensor R U V W} (h : S ∈ LocalTensor.orbit T) (j : ℕ) : + Tensor.power S j ∈ LocalTensor.orbit (Tensor.power T j) := by + rcases h with ⟨a, b, c, rfl⟩ + exact ⟨(fun u x => ∏ i, a (u i) (x i)), + (fun v y => ∏ i, b (v i) (y i)), + (fun w z => ∏ i, c (w i) (z i)), (restrict_power T a b c j).symm⟩ + +end RestrictionAlgebra + +section Coefficients + +variable {X Y Z U V W : Type*} [Fintype X] [Fintype Y] [Fintype Z] + +/-- Combine actual restrictions of one tensor by scaling the maps from each source copy. -/ +theorem weighted_sum_of_restrictions {ι : Type*} [Fintype ι] [DecidableEq ι] + (T : Tensor R X Y Z) (A : ι → Tensor R U V W) (weight : ι → R) + (hA : ∀ i, A i ∈ LocalTensor.orbit T) : + (fun u v w => ∑ i, weight i * A i u v w) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : ι => T)) := by + classical + choose a b c he using hA + refine ⟨fun u x => weight x.1 * a x.1 u x.2, + fun v y => b y.1 v y.2, fun w z => c z.1 w z.2, ?_⟩ + rw [restrict_directSum_sum (fun _ : ι => T) (fun i u x => weight i * a i u x) b c] + funext u v w + apply Finset.sum_congr rfl + intro i hi + rw [he i, restrict_scale_first] + +/-- A coefficient identity and the restrictions at its nodes give a restriction +of the coefficient from the charged direct sum. -/ +theorem coefficient_mem_restrictionOrbit {ι : Type*} [Fintype ι] [DecidableEq ι] + (T : Tensor R X Y Z) (P : Tensor (Polynomial R) U V W) + (nodes weight : ι → R) (d : ℕ) + (heval : ∀ i, (fun u v w => (P u v w).eval (nodes i)) ∈ LocalTensor.orbit T) + (hcoeff : ∀ u v w, (P u v w).coeff d = ∑ i, weight i * (P u v w).eval (nodes i)) : + (fun u v w => (P u v w).coeff d) ∈ LocalTensor.orbit (Tensor.directSum (fun _ : ι => T)) := by + rw [show (fun u v w => (P u v w).coeff d) = _ from funext fun u => + funext fun v => funext fun w => hcoeff u v w] + exact weighted_sum_of_restrictions T (fun i u v w => (P u v w).eval (nodes i)) weight heval + +end Coefficients + +variable {U V W : Type*} + +theorem polynomial_power_constant (P : Tensor (Polynomial R) U V W) (j : ℕ) : + (fun u v w => (Tensor.power P j u v w).coeff 0) = + Tensor.power (fun u v w => (P u v w).coeff 0) j := by + funext u v w + simp only [Tensor.power, Polynomial.coeff_zero_prod] + +theorem polynomial_power_eval (P : Tensor (Polynomial R) U V W) (j : ℕ) (t : R) : + (fun u v w => (Tensor.power P j u v w).eval t) = + Tensor.power (fun u v w => (P u v w).eval t) j := by + funext u v w + simp only [Tensor.power, Polynomial.eval_prod] + +theorem polynomial_power_degree (P : Tensor (Polynomial R) U V W) (K j : ℕ) + (hdegree : ∀ u v w, (P u v w).degree ≤ K) + (u : Fin j → U) (v : Fin j → V) (w : Fin j → W) : + (Tensor.power P j u v w).degree ≤ K * j := by + apply Polynomial.degree_le_of_natDegree_le + calc + (Tensor.power P j u v w).natDegree ≤ + ∑ i, (P (u i) (v i) (w i)).natDegree := Polynomial.natDegree_prod_le _ _ + _ ≤ ∑ _i : Fin j, K := by + apply Finset.sum_le_sum + intro i hi + exact Polynomial.natDegree_le_of_degree_le (hdegree (u i) (v i) (w i)) + _ = K * j := by simp [Nat.mul_comm] + +/-- Lift coefficient extraction to tensor powers and recover the constant tensor. -/ +theorem polynomial_power_mem_restrictionOrbit + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor R X Y Z) (D : Tensor R U V W) + (P : Tensor (Polynomial R) U V W) (K : ℕ) + (hconstant : ∀ u v w, (P u v w).coeff 0 = D u v w) + (hdegree : ∀ u v w, (P u v w).degree ≤ K) + (goodNode : R → Prop) + (heval : ∀ t, goodNode t → + (fun u v w => (P u v w).eval t) ∈ LocalTensor.orbit T) + (j : ℕ) + (extract : + (∀ t, goodNode t → (fun u v w => (Tensor.power P j u v w).eval t) ∈ + LocalTensor.orbit (Tensor.power T j)) → + (∀ u v w, (Tensor.power P j u v w).degree < Fintype.card (Fin (K * j + 1))) → + (fun u v w => (Tensor.power P j u v w).coeff 0) ∈ LocalTensor.orbit + (Tensor.directSum (fun _ : Fin (K * j + 1) => Tensor.power T j))) : + Tensor.power D j ∈ LocalTensor.orbit + (Tensor.directSum (fun _ : Fin (K * j + 1) => Tensor.power T j)) := by + have hevalpower (t : R) (ht : goodNode t) : + (fun u v w => (Tensor.power P j u v w).eval t) ∈ + LocalTensor.orbit (Tensor.power T j) := by + rw [polynomial_power_eval] + exact power_mem_restrictionOrbit (heval t ht) j + have hdegreepower (u v w) : (Tensor.power P j u v w).degree < + Fintype.card (Fin (K * j + 1)) := by + simp only [Fintype.card_fin] + exact lt_of_le_of_lt (polynomial_power_degree P K j hdegree u v w) + (WithBot.coe_lt_coe.mpr (Nat.lt_succ_self (K * j))) + have h := extract hevalpower hdegreepower + rw [polynomial_power_constant, show (fun u v w => (P u v w).coeff 0) = D from + funext fun u => funext fun v => funext fun w => hconstant u v w] at h + exact h + +end MatrixMultiplicationAllFields.TensorSpectrum.RestrictionInterpolation diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/SeparationFourier.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/SeparationFourier.lean new file mode 100644 index 0000000000..d80e15db01 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/SeparationFourier.lean @@ -0,0 +1,174 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationPolynomial +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Blocks +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.LocalTensor + +/-! +# Local Fourier restriction of a shared tensor + +The averaging identity and the integer power law determine the projected +coefficients. The number of complete source copies is an input. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixExponent +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.Separation + +variable {R X Y Z : Type*} [CommSemiring R] + +/-- Copy a specified source coordinate with a scalar depending only on the +target coordinate and the source's direct-sum copy number. -/ +def copyLocal {L : ℕ} {S T : Type*} [DecidableEq S] + (f : T → S) (a : T → Fin L → R) : T → (Fin L × S) → R := + fun t s => if s.2 = f t then a t s.1 else 0 + +section CopyCalculation + +variable {L : ℕ} {X' Y' Z' : Type*} +variable [Fintype X] [Fintype Y] [Fintype Z] +variable [DecidableEq X] [DecidableEq Y] [DecidableEq Z] + +/-- Summing the full source copies, rather than target coordinate labels, is +what produces the Fourier average. All three source copy indices must agree. -/ +theorem restrict_copies (T : Tensor R X Y Z) + (fx : X' → X) (fy : Y' → Y) (fz : Z' → Z) + (a : X' → Fin L → R) (b : Y' → Fin L → R) (c : Z' → Fin L → R) : + Tensor.restrict (copyLocal fx a) (copyLocal fy b) (copyLocal fz c) + (Tensor.directSum (fun _ : Fin L => T)) = + fun x y z => (∑ r, a x r * b y r * c z r) * T (fx x) (fy y) (fz z) := by + funext x y z + simp [Tensor.restrict, Tensor.directSum, copyLocal, Fintype.sum_prod_type, + ite_and, ite_mul, mul_ite, ← Finset.sum_mul] + +omit [DecidableEq X] [DecidableEq Y] [DecidableEq Z] in +/-- Scaling each target coordinate is itself a local linear operation. -/ +theorem restrict_scaled (T : Tensor R X Y Z) + (a : X' → X → R) (b : Y' → Y → R) (c : Z' → Z → R) + (u : X' → R) (v : Y' → R) (w : Z' → R) : + Tensor.restrict (fun x i => u x * a x i) + (fun y j => v y * b y j) (fun z k => w z * c z k) T = + fun x y z => u x * v y * w z * Tensor.restrict a b c T x y z := by + funext x y z + simp only [Tensor.restrict, Finset.mul_sum] + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + apply Finset.sum_congr rfl + intro k hk + ring + +end CopyCalculation + +section Projection + +variable {M L : ℕ} +variable [Fintype X] [Fintype Y] [Fintype Z] +variable [DecidableEq X] [DecidableEq Y] [DecidableEq Z] + +/-- The Fourier substitution on the first leg. -/ +def fourierX (power : ℤ → R) : + (Fin M × (X × Unit)) → (Fin L × X) → R := + copyLocal (fun x => x.2.1) + (fun x r => power ((r : ℤ) * (2 * (x.1 : ℤ)))) + +/-- The Fourier substitution on the second leg. -/ +def fourierY (power : ℤ → R) : + (Fin M × (Y × Fin M)) → (Fin L × (Fin M × Y)) → R := + copyLocal (fun y => (y.1, y.2.1)) + (fun y r => power ((r : ℤ) * ((y.2.2 : ℤ) - (y.1 : ℤ)))) + +/-- The Fourier substitution on the third leg. -/ +def fourierZ (power : ℤ → R) (w : Fin L → R) : + (Fin M × (Z × Fin M)) → (Fin L × (Fin M × Z)) → R := + copyLocal (fun z => (z.1, z.2.1)) + (fun z r => w r * + power ((r : ℤ) * (-(z.2.2 : ℤ) - (z.1 : ℤ)))) + +/-- The actual independent local maps give exactly the projected tensor. -/ +theorem fourier_restrict (A : Fin M → Tensor R X Y Z) + (power : ℤ → R) (w : Fin L → R) (hadd : ∀ a b, power (a + b) = power a * power b) + (haverage : ∀ e : ℤ, -(3 * (M : ℤ)) < e → e < 3 * (M : ℤ) → + (∑ r : Fin L, w r * power ((r : ℤ) * e)) = if e = 0 then 1 else 0) : + Tensor.restrict (fourierX power) (fourierY power) (fourierZ power w) + (Tensor.directSum (fun _ : Fin L => Tensor.sharedFirst A)) = projected A := by + classical + rw [fourierX, fourierY, fourierZ, restrict_copies] + funext x y z + by_cases hyz : y.1 = z.1 + · have hphase : (∑ r : Fin L, + power ((r : ℤ) * (2 * (x.1 : ℤ))) * + power ((r : ℤ) * ((y.2.2 : ℤ) - (y.1 : ℤ))) * + (w r * + power ((r : ℤ) * (-(z.2.2 : ℤ) - (z.1 : ℤ))))) = + if phase y.1 x.1 y.2.2 z.2.2 = 0 then 1 else 0 := by + calc + _ = ∑ r : Fin L, w r * power ((r : ℤ) * phase y.1 x.1 y.2.2 z.2.2) := by + apply Finset.sum_congr rfl + intro r hr + rw [← hyz] + calc + _ = w r * + ((power ((r : ℤ) * (2 * (x.1 : ℤ))) * + power ((r : ℤ) * ((y.2.2 : ℤ) - (y.1 : ℤ)))) * + power ((r : ℤ) * (-(z.2.2 : ℤ) - (y.1 : ℤ)))) := by ring + _ = _ := by + rw [← hadd, ← hadd] + congr 2 + dsimp [phase] + ring + _ = _ := by + apply haverage <;> unfold phase <;> omega + rw [hphase] + simp [Tensor.sharedFirst, projected, hyz, ite_mul] + · simp [Tensor.sharedFirst, projected, hyz] + +/-- Realize a polynomial evaluation as a restriction using the Fourier maps +scaled by the signed coordinate weights. -/ +theorem separationPolynomial_specializes (A : Fin M → Tensor R X Y Z) + (power : ℤ → R) (w : Fin L → R) (t : R) (integerPower : ℤ → R) + (projection : Tensor.restrict (fourierX power) (fourierY power) (fourierZ power w) + (Tensor.directSum (fun _ : Fin L => Tensor.sharedFirst A)) = projected A) + (evaluation : (fun x y z => (separationPolynomial A x y z).eval t) = + fun x y z => integerPower (weightX x) * integerPower (weightY y) * + integerPower (weightZ z) * projected A x y z) : + (fun x y z => (separationPolynomial A x y z).eval t) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : Fin L => Tensor.sharedFirst A)) := by + refine ⟨(fun x i => integerPower (weightX x) * fourierX power x i), + (fun y j => integerPower (weightY y) * fourierY power y j), + (fun z k => integerPower (weightZ z) * fourierZ power w z k), ?_⟩ + rw [restrict_scaled, projection] + exact evaluation + +end Projection + +/-- Package the polynomial and its specialization certificates for a specified +number of shared source copies and a specified set of evaluation points. -/ +theorem finite_charged_separation {M L : ℕ} [Fintype X] [Fintype Y] [Fintype Z] + (A : Fin M → Tensor R X Y Z) (valid : R → Prop) + (specializes : ∀ t, valid t → (fun x y z => (separationPolynomial A x y z).eval t) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : Fin L => Tensor.sharedFirst A))) : + ∃ P : Tensor (Polynomial R) (Fin M × (X × Unit)) + (Fin M × (Y × Fin M)) (Fin M × (Z × Fin M)), + (∀ x y z, (P x y z).coeff 0 = separated A x y z) ∧ + (∀ x y z, (P x y z).degree ≤ ((M - 1) ^ 2 : ℕ)) ∧ + (∀ t, valid t → (fun x y z => (P x y z).eval t) ∈ + LocalTensor.orbit (Tensor.directSum (fun _ : Fin L => Tensor.sharedFirst A))) := by + refine ⟨separationPolynomial A, ?_, separationPolynomial_degree A, specializes⟩ + intro x y z + exact congrFun (congrFun (congrFun (separationPolynomial_constant A) x) y) z + +end MatrixMultiplicationAllFields.TensorSpectrum.Separation diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/SeparationPolynomial.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/SeparationPolynomial.lean new file mode 100644 index 0000000000..2e03d9ba57 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/SeparationPolynomial.lean @@ -0,0 +1,145 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.SeparationWeights +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Polynomial.ComplexPolynomialApproximation +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorBatching + +/-! +# The charged separation polynomial + +The zero coefficient is the exact separated sum and the degree depends on +the difference of the branch indices. Evaluation uses a multiplicative map +on the integer coordinate weights. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.Separation + +variable {R X Y Z : Type*} [CommSemiring R] {M : ℕ} + +/-- The auxiliary pairing has one coordinate on the first leg. -/ +def dotPairingX (U : Type*) [DecidableEq U] : Tensor R Unit U U := + fun _ u v => if u = v then 1 else 0 + +/-- Every branch in this output has its own first-leg space. -/ +def separated {M : ℕ} (A : Fin M → Tensor R X Y Z) : + Tensor R (Fin M × (X × Unit)) (Fin M × (Y × Fin M)) + (Fin M × (Z × Fin M)) := + Tensor.directSum (fun h => Tensor.product (A h) (dotPairingX (Fin M))) + +/-- The integer projected by the finite Fourier average. Labels are numbered +from zero here; translating all four labels by one leaves this phase unchanged. -/ +def phase {M : ℕ} (h g u v : Fin M) : ℤ := + (u : ℤ) - (v : ℤ) + 2 * ((g : ℤ) - (h : ℤ)) + +/-- Evaluates `if y.1 = z.1 ∧ phase y.1 x.1 y.2.2 z.2.2 = 0 then A y.1 x.2.1 y.2.1 z.2.1 else 0` +at the input `x y z`. -/ +def projected (A : Fin M → Tensor R X Y Z) : + Tensor R (Fin M × (X × Unit)) (Fin M × (Y × Fin M)) + (Fin M × (Z × Fin M)) := + fun x y z => if y.1 = z.1 ∧ phase y.1 x.1 y.2.2 z.2.2 = 0 + then A y.1 x.2.1 y.2.1 z.2.1 else 0 + +/-- The degree of a projected monomial, already known to be nonnegative. -/ +def squareDegree (h g : Fin M) : ℕ := + squareExponent g h + +/-- This is a polynomial array even though the individual local weights used +to realize its nonzero evaluations can be negative. -/ +def separationPolynomial (A : Fin M → Tensor R X Y Z) : + Tensor (Polynomial R) (Fin M × (X × Unit)) (Fin M × (Y × Fin M)) + (Fin M × (Z × Fin M)) := + fun x y z => if y.1 = z.1 ∧ phase y.1 x.1 y.2.2 z.2.2 = 0 + then Polynomial.monomial (squareDegree y.1 x.1) (A y.1 x.2.1 y.2.1 z.2.1) + else 0 + +theorem squareDegree_eq_zero_iff (h g : Fin M) : squareDegree h g = 0 ↔ g = h := by + exact squareExponent_eq_zero_iff g h + +/-- The zero coefficient is the full direct sum with an auxiliary dot product. -/ +theorem separationPolynomial_constant (A : Fin M → Tensor R X Y Z) : + (fun x y z => (separationPolynomial A x y z).coeff 0) = separated A := by + funext x y z + by_cases hxy : x.1 = y.1 + · by_cases hyz : y.1 = z.1 + · by_cases huv : y.2.2 = z.2.2 + · simp [separationPolynomial, separated, Tensor.directSum, Tensor.product, + dotPairingX, phase, squareDegree, squareExponent, hxy, hyz, huv] + · have hp : phase y.1 x.1 y.2.2 z.2.2 ≠ 0 := by + intro hp + have heq : (y.2.2 : ℤ) = (z.2.2 : ℤ) := by + simpa [phase, hxy, sub_eq_zero] using hp + exact huv (Fin.ext (by exact_mod_cast heq)) + have hsupport : ¬(y.1 = z.1 ∧ phase y.1 x.1 y.2.2 z.2.2 = 0) := + fun h => hp h.2 + simp only [separationPolynomial, ite_eq_right hsupport] + simp [separated, Tensor.directSum, Tensor.product, dotPairingX, hxy, hyz, huv] + · have hxz : x.1 ≠ z.1 := by simpa [hxy] using hyz + simp [separationPolynomial, separated, Tensor.directSum, hyz, hxz] + · have hdegree : squareDegree y.1 x.1 ≠ 0 := by + exact fun h => hxy ((squareDegree_eq_zero_iff y.1 x.1).mp h) + by_cases hs : y.1 = z.1 ∧ phase y.1 x.1 y.2.2 z.2.2 = 0 + · simp only [separationPolynomial, ite_eq_left hs] + simp [separated, Tensor.directSum, hxy, + Polynomial.coeff_monomial, hdegree] + · simp [separationPolynomial, hs, separated, Tensor.directSum, hxy] + +theorem separationPolynomial_degree (A : Fin M → Tensor R X Y Z) + (x : Fin M × (X × Unit)) (y : Fin M × (Y × Fin M)) + (z : Fin M × (Z × Fin M)) : + (separationPolynomial A x y z).degree ≤ ((M - 1) ^ 2 : ℕ) := by + apply Polynomial.degree_le_of_natDegree_le + unfold separationPolynomial + split_ifs + · exact le_trans (Polynomial.natDegree_monomial_le _) + (squareExponent_le x.1 y.1) + · simp + +/-- The quantity computed by `(x.1 : ℤ) ^ 2`. -/ +def weightX (x : Fin M × (X × Unit)) : ℤ := (x.1 : ℤ) ^ 2 + +/-- The quantity computed by `(y.1 : ℤ) * (y.2.2 : ℤ) - (y.1 : ℤ) ^ 2`. -/ +def weightY (y : Fin M × (Y × Fin M)) : ℤ := + (y.1 : ℤ) * (y.2.2 : ℤ) - (y.1 : ℤ) ^ 2 + +/-- The quantity computed by `-(z.1 : ℤ) * (z.2.2 : ℤ)`. -/ +def weightZ (z : Fin M × (Z × Fin M)) : ℤ := + -(z.1 : ℤ) * (z.2.2 : ℤ) + +/-- On the complete projected support, the local weights add to the actual +polynomial degree, including all zero and mismatched coefficients. -/ +theorem separationPolynomial_eval (A : Fin M → Tensor R X Y Z) + (t : R) (integerPower : ℤ → R) + (hadd : ∀ a b, integerPower (a + b) = integerPower a * integerPower b) + (hnat : ∀ n : ℕ, integerPower n = t ^ n) : + (fun x y z => (separationPolynomial A x y z).eval t) = + fun x y z => integerPower (weightX x) * integerPower (weightY y) * + integerPower (weightZ z) * projected A x y z := by + funext x y z + by_cases hs : y.1 = z.1 ∧ phase y.1 x.1 y.2.2 z.2.2 = 0 + · have hsum : weightX x + weightY y + weightZ z = + ((x.1 : ℤ) - (y.1 : ℤ)) ^ 2 := by + dsimp [weightX, weightY, weightZ] + rw [← hs.1] + have hp := hs.2 + dsimp [phase] at hp + nlinarith + have hcast : (squareDegree y.1 x.1 : ℤ) = ((x.1 : ℤ) - (y.1 : ℤ)) ^ 2 := + Int.toNat_of_nonneg (sq_nonneg _) + simp only [separationPolynomial, projected, ite_eq_left hs, Polynomial.eval_monomial] + rw [← hadd, ← hadd, hsum, ← hcast, hnat, mul_comm] + · simp [separationPolynomial, projected, hs] + +end MatrixMultiplicationAllFields.TensorSpectrum.Separation diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/SeparationWeights.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/SeparationWeights.lean new file mode 100644 index 0000000000..2cd22c7bfd --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/SeparationWeights.lean @@ -0,0 +1,123 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.Order.Ring.Int +public import Mathlib.Data.Fin.Basic +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Positivity +public import Mathlib.Tactic.Ring + +/-! +# Integer phases and weights for auxiliary separation + +The phase modulus `5M` has no nonzero multiple on the label interval. After +projection, the Laurent weight is a square and vanishes exactly when the +sector guess and the auxiliary labels agree. These are local identities; +they do not assert the tensor separation or its tag inequality. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum.Separation + +theorem dvd_iff_eq_zero_of_bounds (N x : ℤ) (hN : 0 < N) + (hlo : -N < x) (hhi : x < N) : (N ∣ x ↔ x = 0) := by + constructor + · rintro ⟨k, hk⟩ + by_cases hzero : k = 0 + · simpa [hzero] using hk + · rcases lt_or_gt_of_ne hzero with hneg | hpos + · have hmul := mul_le_mul_of_nonneg_left (show k ≤ -1 by omega) hN.le + nlinarith + · have hmul := mul_le_mul_of_nonneg_left (show 1 ≤ k by omega) hN.le + nlinarith + · rintro rfl + exact dvd_zero N + +/-- Convert a finite index to its one-based label. -/ +theorem projection_does_not_wrap + (M h g u v : ℤ) + (hM : 1 ≤ M) (hh0 : 1 ≤ h) (hhM : h ≤ M) + (hg0 : 1 ≤ g) (hgM : g ≤ M) + (hu0 : 1 ≤ u) (huM : u ≤ M) + (hv0 : 1 ≤ v) (hvM : v ≤ M) : + ((5 * M ∣ u - v + 2 * (g - h)) ↔ u - v + 2 * (g - h) = 0) := by + exact dvd_iff_eq_zero_of_bounds (5 * M) (u - v + 2 * (g - h)) + (by omega) (by omega) (by omega) + +/-- The same no-wrap property for finite labels numbered from zero. -/ +theorem projection_does_not_wrap_fin {M : ℕ} (h g u v : Fin M) : + ((5 * (M : ℤ) ∣ (u.val : ℤ) - v.val + 2 * ((g.val : ℤ) - h.val)) ↔ + (u.val : ℤ) - v.val + 2 * ((g.val : ℤ) - h.val) = 0) := by + have hh := h.isLt + have hg := g.isLt + have hu := u.isLt + have hv := v.isLt + exact dvd_iff_eq_zero_of_bounds (5 * (M : ℤ)) + ((u.val : ℤ) - v.val + 2 * ((g.val : ℤ) - h.val)) + (by omega) (by omega) (by omega) + +/-- The weight identity is independent of the choice of zero- or one-based +labels. -/ +theorem projected_square_weight + (h g u v : ℤ) (hphase : u - v + 2 * (g - h) = 0) : + g ^ 2 + h * u - h ^ 2 - h * v = (g - h) ^ 2 ∧ + 0 ≤ g ^ 2 + h * u - h ^ 2 - h * v ∧ + (g ^ 2 + h * u - h ^ 2 - h * v = 0 ↔ g = h ∧ u = v) := by + have hweight : g ^ 2 + h * u - h ^ 2 - h * v = (g - h) ^ 2 := by + calc + g ^ 2 + h * u - h ^ 2 - h * v = + (g - h) ^ 2 + h * (u - v + 2 * (g - h)) := by ring + _ = (g - h) ^ 2 := by rw [hphase]; ring + refine ⟨hweight, ?_, ?_⟩ + · rw [hweight] + exact sq_nonneg _ + · rw [hweight] + constructor + · intro hz + have hdiff : g - h = 0 := sq_eq_zero_iff.mp hz + constructor <;> omega + · rintro ⟨rfl, rfl⟩ + simp + +/-- The nonnegative exponent used after the Fourier projection. -/ +def squareExponent {M : ℕ} (g h : Fin M) : ℕ := + Int.toNat (((g.val : ℤ) - h.val) ^ 2) + +theorem squareExponent_eq_zero_iff {M : ℕ} (g h : Fin M) : + squareExponent g h = 0 ↔ g = h := by + constructor + · intro he + have hnonneg : 0 ≤ ((g.val : ℤ) - h.val) ^ 2 := sq_nonneg _ + have hz : ((g.val : ℤ) - h.val) ^ 2 = 0 := by + unfold squareExponent at he + omega + have hdiff : (g.val : ℤ) - h.val = 0 := sq_eq_zero_iff.mp hz + apply Fin.ext + omega + · rintro rfl + simp [squareExponent] + +theorem squareExponent_le {M : ℕ} (g h : Fin M) : + squareExponent g h ≤ (M - 1) ^ 2 := by + have hg := g.isLt + have hh := h.isLt + have hlow : -((M - 1 : ℕ) : ℤ) ≤ (g.val : ℤ) - h.val := by omega + have hhigh : (g.val : ℤ) - h.val ≤ ((M - 1 : ℕ) : ℤ) := by omega + have hprod : + 0 ≤ (((M - 1 : ℕ) : ℤ) - ((g.val : ℤ) - h.val)) * + (((M - 1 : ℕ) : ℤ) + ((g.val : ℤ) - h.val)) := + mul_nonneg (by omega) (by omega) + have hsq : ((g.val : ℤ) - h.val) ^ 2 ≤ (((M - 1 : ℕ) : ℤ)) ^ 2 := by + nlinarith + have hcast : ((g.val : ℤ) - h.val) ^ 2 ≤ (((M - 1) ^ 2 : ℕ) : ℤ) := by + simpa only [Nat.cast_pow] using hsq + unfold squareExponent + omega + +end MatrixMultiplicationAllFields.TensorSpectrum.Separation diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagEntropy.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagEntropy.lean new file mode 100644 index 0000000000..b5057e7aab --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagEntropy.lean @@ -0,0 +1,250 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Algebra.BigOperators.Field +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Ring + +/-! +# The finite weighted entropy inequality + +The positive-parameter inequality is the weighted arithmetic--geometric mean +inequality applied to `c i ^ (1 / p) / q i`. Zero weights contribute the factor +one, and are treated before taking logarithms. The logarithmic AM--GM argument +below uses only `Real.log_le_sub_one_of_pos`. + +The zero-parameter endpoint has a separate pointwise hypothesis: if every +`c i ≤ x`, then the weighted product is at most `x`. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open scoped BigOperators + +private theorem fin_nonempty_of_probability_sum {s : ℕ} (q : Fin s → ℝ) + (hqsum : ∑ i, q i = 1) : Nonempty (Fin s) := by + cases s with + | zero => simp at hqsum + | succ s => exact ⟨0⟩ + +/-- The logarithmic weighted AM--GM inequality, with an upper bound on the +weighted arithmetic mean. The weights may vanish. -/ +theorem weighted_log_le_log_of_sum_le {s : ℕ} + (q a : Fin s → ℝ) (B : ℝ) + (hq : ∀ i, 0 ≤ q i) (hqsum : ∑ i, q i = 1) + (ha : ∀ i, 0 < a i) (hB : 0 < B) + (hmean : ∑ i, q i * a i ≤ B) : + ∑ i, q i * Real.log (a i) ≤ Real.log B := by + have hterm (i : Fin s) : + q i * (Real.log (a i) - Real.log B) ≤ q i * (a i / B - 1) := by + simpa only [Real.log_div (ha i).ne' hB.ne'] using + mul_le_mul_of_nonneg_left + (Real.log_le_sub_one_of_pos (div_pos (ha i) hB)) (hq i) + have hsum := Finset.sum_le_sum (fun i (_ : i ∈ (Finset.univ : Finset (Fin s))) => + hterm i) + have hsum' : + (∑ i, q i * Real.log (a i)) - Real.log B ≤ + (∑ i, q i * a i) / B - 1 := by + simpa only [mul_sub, ← mul_div_assoc, mul_one, Finset.sum_sub_distrib, + ← Finset.sum_mul, hqsum, one_mul, ← Finset.sum_div] using hsum + have hdiv : (∑ i, q i * a i) / B ≤ 1 := + (div_le_iff₀ hB).2 (by simpa only [one_mul] using hmean) + linarith + +/-- A product form of weighted AM--GM, proved from its logarithmic form. -/ +theorem weighted_geometric_mean_le_of_sum_le {s : ℕ} + (q a : Fin s → ℝ) (B : ℝ) + (hq : ∀ i, 0 ≤ q i) (hqsum : ∑ i, q i = 1) + (ha : ∀ i, 0 < a i) (hB : 0 < B) + (hmean : ∑ i, q i * a i ≤ B) : + ∏ i, (a i) ^ (q i) ≤ B := by + apply (Real.log_le_log_iff + (Finset.prod_pos (fun i _ => Real.rpow_pos_of_pos (ha i) (q i))) hB).1 + calc + Real.log (∏ i, (a i) ^ (q i)) = ∑ i, q i * Real.log (a i) := by + rw [Real.log_prod (fun i _ => (Real.rpow_pos_of_pos (ha i) (q i)).ne')] + exact Finset.sum_congr rfl (fun i _ => Real.log_rpow (ha i) (q i)) + _ ≤ Real.log B := weighted_log_le_log_of_sum_le q a B hq hqsum ha hB hmean + +/-- The finite entropy/tag inequality for a positive real parameter. +The convention `x ^ (0 : ℝ) = 1` includes every zero weight. -/ +theorem tag_entropy_product_le {s : ℕ} + (p : ℝ) (c q : Fin s → ℝ) + (hp : 0 < p) (hc : ∀ i, 0 < c i) + (hq : ∀ i, 0 ≤ q i) (hqsum : ∑ i, q i = 1) : + (∏ i, (c i / (q i) ^ p) ^ (q i)) ≤ + (∑ i, (c i) ^ (1 / p)) ^ p := by + classical + let a : Fin s → ℝ := fun i => if q i = 0 then 1 else (c i) ^ (1 / p) / q i + let B : ℝ := ∑ i, (c i) ^ (1 / p) + have ha : ∀ i, 0 < a i := by + intro i + by_cases hi : q i = 0 + · simp [a, hi] + · have hqi : 0 < q i := lt_of_le_of_ne (hq i) (Ne.symm hi) + simpa only [a, ite_eq_right hi] using + div_pos (Real.rpow_pos_of_pos (hc i) (1 / p)) hqi + have : Nonempty (Fin s) := fin_nonempty_of_probability_sum q hqsum + have hB : 0 < B := + Finset.sum_pos (fun i _ => Real.rpow_pos_of_pos (hc i) (1 / p)) + Finset.univ_nonempty + have hmean : ∑ i, q i * a i ≤ B := by + apply Finset.sum_le_sum + intro i _ + by_cases hi : q i = 0 + · simpa only [hi, zero_mul] using (Real.rpow_pos_of_pos (hc i) (1 / p)).le + · have hcancel : q i * a i = (c i) ^ (1 / p) := by + simp only [a, ite_eq_right hi] + field_simp [hi] + exact hcancel.le + have hlog := weighted_log_le_log_of_sum_le q a B hq hqsum ha hB hmean + have hfactor_pos (i : Fin s) : 0 < (c i / (q i) ^ p) ^ (q i) := by + by_cases hi : q i = 0 + · simp only [hi, Real.rpow_zero, zero_lt_one] + · have hqi : 0 < q i := lt_of_le_of_ne (hq i) (Ne.symm hi) + exact Real.rpow_pos_of_pos + (div_pos (hc i) (Real.rpow_pos_of_pos hqi p)) (q i) + have hfactor_log (i : Fin s) : + Real.log ((c i / (q i) ^ p) ^ (q i)) = p * (q i * Real.log (a i)) := by + by_cases hi : q i = 0 + · simp [hi] + · have hqi : 0 < q i := lt_of_le_of_ne (hq i) (Ne.symm hi) + rw [Real.log_rpow (div_pos (hc i) (Real.rpow_pos_of_pos hqi p)), + Real.log_div (hc i).ne' (Real.rpow_pos_of_pos hqi p).ne', + Real.log_rpow hqi p] + simp only [a, ite_eq_right hi] + rw [Real.log_div (Real.rpow_pos_of_pos (hc i) (1 / p)).ne' hqi.ne', + Real.log_rpow (hc i) (1 / p)] + field_simp [hp.ne'] + apply (Real.log_le_log_iff + (Finset.prod_pos (fun i _ => hfactor_pos i)) (Real.rpow_pos_of_pos hB p)).1 + change Real.log (∏ i, (c i / (q i) ^ p) ^ (q i)) ≤ Real.log (B ^ p) + rw [Real.log_prod (fun i _ => (hfactor_pos i).ne'), Real.log_rpow hB p] + calc + (∑ i, Real.log ((c i / (q i) ^ p) ^ (q i))) = + p * (∑ i, q i * Real.log (a i)) := by + simp_rw [hfactor_log] + exact (Finset.mul_sum _ _ _).symm + _ ≤ p * Real.log B := mul_le_mul_of_nonneg_left hlog hp.le + +/-- Compose the entropy inequality with a bound on the optimized power sum. -/ +theorem tag_entropy_product_le_of_bound {s : ℕ} + (p x : ℝ) (c q : Fin s → ℝ) + (hp : 0 < p) (hc : ∀ i, 0 < c i) + (hq : ∀ i, 0 ≤ q i) (hqsum : ∑ i, q i = 1) + (hbound : (∑ i, (c i) ^ (1 / p)) ^ p ≤ x) : + (∏ i, (c i / (q i) ^ p) ^ (q i)) ≤ x := + (tag_entropy_product_le p c q hp hc hq hqsum).trans hbound + +/-- A weighted product of positive numbers is bounded by any pointwise upper +bound. This is the endpoint needed when the tag parameter is zero. -/ +theorem weighted_geometric_mean_le_of_pointwise {s : ℕ} + (c q : Fin s → ℝ) (x : ℝ) + (hc : ∀ i, 0 < c i) (hq : ∀ i, 0 ≤ q i) + (hqsum : ∑ i, q i = 1) (hcx : ∀ i, c i ≤ x) : + (∏ i, (c i) ^ (q i)) ≤ x := by + have : Nonempty (Fin s) := fin_nonempty_of_probability_sum q hqsum + obtain ⟨i⟩ := ‹Nonempty (Fin s)› + have hx : 0 < x := (hc i).trans_le (hcx i) + apply weighted_geometric_mean_le_of_sum_le q c x hq hqsum hc hx + calc + (∑ i, q i * c i) ≤ ∑ i, q i * x := + Finset.sum_le_sum (fun i _ => mul_le_mul_of_nonneg_left (hcx i) (hq i)) + _ = x := by rw [← Finset.sum_mul, hqsum, one_mul] + +/-- The zero-parameter tag inequality, in the same product notation as the +positive-parameter result. No limiting convention for `1 / p` is used. -/ +theorem tag_entropy_product_zero_le {s : ℕ} + (c q : Fin s → ℝ) (x : ℝ) + (hc : ∀ i, 0 < c i) (hq : ∀ i, 0 ≤ q i) + (hqsum : ∑ i, q i = 1) (hcx : ∀ i, c i ≤ x) : + (∏ i, (c i / (q i) ^ (0 : ℝ)) ^ (q i)) ≤ x := by + simpa only [Real.rpow_zero, div_one] using + weighted_geometric_mean_le_of_pointwise c q x hc hq hqsum hcx + +/-- Rewrite the quotient product as the exponential of the Shannon entropy +times the unnormalized weighted product. This identity also holds at `p = 0` +and at zero weights; it requires no normalization of the weights. -/ +theorem tag_entropy_product_eq_exp {s : ℕ} + (p : ℝ) (c q : Fin s → ℝ) + (hc : ∀ i, 0 < c i) (hq : ∀ i, 0 ≤ q i) : + (∏ i, (c i / (q i) ^ p) ^ (q i)) = + Real.exp (p * (-(∑ i, q i * Real.log (q i)))) * + (∏ i, (c i) ^ (q i)) := by + have hfactor_pos (i : Fin s) : 0 < (c i / (q i) ^ p) ^ (q i) := by + by_cases hi : q i = 0 + · simp only [hi, Real.rpow_zero, zero_lt_one] + · have hqi : 0 < q i := lt_of_le_of_ne (hq i) (Ne.symm hi) + exact Real.rpow_pos_of_pos + (div_pos (hc i) (Real.rpow_pos_of_pos hqi p)) (q i) + have hfactor_log (i : Fin s) : + Real.log ((c i / (q i) ^ p) ^ (q i)) = + q i * Real.log (c i) - p * (q i * Real.log (q i)) := by + by_cases hi : q i = 0 + · simp [hi] + · have hqi : 0 < q i := lt_of_le_of_ne (hq i) (Ne.symm hi) + rw [Real.log_rpow (div_pos (hc i) (Real.rpow_pos_of_pos hqi p)), + Real.log_div (hc i).ne' (Real.rpow_pos_of_pos hqi p).ne', + Real.log_rpow hqi p] + ring + have hcprod : 0 < ∏ i, (c i) ^ (q i) := + Finset.prod_pos (fun i _ => Real.rpow_pos_of_pos (hc i) (q i)) + apply Real.log_injOn_pos (Finset.prod_pos (fun i _ => hfactor_pos i)) + (mul_pos (Real.exp_pos _) hcprod) + calc + Real.log (∏ i, (c i / (q i) ^ p) ^ (q i)) = + ∑ i, (q i * Real.log (c i) - p * (q i * Real.log (q i))) := by + rw [Real.log_prod (fun i _ => (hfactor_pos i).ne')] + exact Finset.sum_congr rfl (fun i _ => hfactor_log i) + _ = p * (-(∑ i, q i * Real.log (q i))) + + ∑ i, q i * Real.log (c i) := by + rw [Finset.sum_sub_distrib, ← Finset.mul_sum] + ring + _ = Real.log (Real.exp (p * (-(∑ i, q i * Real.log (q i)))) * + (∏ i, (c i) ^ (q i))) := by + rw [Real.log_mul (Real.exp_pos _).ne' hcprod.ne', Real.log_exp, + Real.log_prod (fun i _ => (Real.rpow_pos_of_pos (hc i) (q i)).ne')] + congr 1 + exact (Finset.sum_congr rfl (fun i _ => Real.log_rpow (hc i) (q i))).symm + +/-- The positive-parameter entropy inequality in exponential notation. -/ +theorem tag_entropy_exp_le {s : ℕ} + (p : ℝ) (c q : Fin s → ℝ) + (hp : 0 < p) (hc : ∀ i, 0 < c i) + (hq : ∀ i, 0 ≤ q i) (hqsum : ∑ i, q i = 1) : + Real.exp (p * (-(∑ i, q i * Real.log (q i)))) * + (∏ i, (c i) ^ (q i)) ≤ (∑ i, (c i) ^ (1 / p)) ^ p := by + rw [← tag_entropy_product_eq_exp p c q hc hq] + exact tag_entropy_product_le p c q hp hc hq hqsum + +/-- Compose the exponential entropy inequality with an optimized power-sum +bound, without further assumptions on the auxiliary parameter `x`. -/ +theorem tag_entropy_exp_le_of_bound {s : ℕ} + (p x : ℝ) (c q : Fin s → ℝ) + (hp : 0 < p) (hc : ∀ i, 0 < c i) + (hq : ∀ i, 0 ≤ q i) (hqsum : ∑ i, q i = 1) + (hbound : (∑ i, (c i) ^ (1 / p)) ^ p ≤ x) : + Real.exp (p * (-(∑ i, q i * Real.log (q i)))) * + (∏ i, (c i) ^ (q i)) ≤ x := + (tag_entropy_exp_le p c q hp hc hq hqsum).trans hbound + +/-- The zero-parameter endpoint in exponential entropy notation. -/ +theorem tag_entropy_exp_zero_le {s : ℕ} + (c q : Fin s → ℝ) (x : ℝ) + (hc : ∀ i, 0 < c i) (hq : ∀ i, 0 ≤ q i) + (hqsum : ∑ i, q i = 1) (hcx : ∀ i, c i ≤ x) : + Real.exp ((0 : ℝ) * (-(∑ i, q i * Real.log (q i)))) * + (∏ i, (c i) ^ (q i)) ≤ x := by + simpa only [zero_mul, Real.exp_zero, one_mul] using + weighted_geometric_mean_le_of_pointwise c q x hc hq hqsum hcx + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagFiberBounds.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagFiberBounds.lean new file mode 100644 index 0000000000..99984a2999 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagFiberBounds.lean @@ -0,0 +1,86 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagTensorWords +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPowers + +/-! +# The exact finite-word character inequality + +Every count fiber is selected by actual local coordinate maps from a tensor +power of the original shared-input tensor. Charged separation is then applied +to that finite fiber. This is the tensor input to the later scalar limit; +neither the separation nor the word restriction is an assumption here. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +variable {K : Type*} [CommSemiring K] + +theorem Character.shared_branch_le (f : Character K) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s : ℕ} (A : Fin s → Tensor K X Y Z) (i : Fin s) : + f (ofTensor (A i)) ≤ f (ofTensor (TagTensorWords.sharedLabels A)) := by + have hr := CoefficientTensor.Restricts.pullback (TagTensorWords.sharedLabels A) + id (fun y => (i, y)) (fun z => (i, z)) + have heq : Tensor.pullback id (fun y => (i, y)) (fun z => (i, z)) + (TagTensorWords.sharedLabels A) = A i := by + funext x y z + simp [Tensor.pullback, TagTensorWords.sharedLabels] + rw [heq] at hr + exact f.monotone' (ofTensor_le hr) + +/-- The finite word-fiber bound using the charged separation inequality. -/ +theorem Character.tag_count_fiber (f : Character K) + {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + {s N : ℕ} (A : Fin s → Tensor K X Y Z) + (c : TagWords.CountVector s N) (hc : 0 < (TagWords.fiber c).card) (factor : ℝ≥0) + (hcharge : ∀ {M : ℕ}, 0 < M → + ∀ (B : Fin M → Tensor K (Fin N → X) (Fin N → Y) (Fin N → Z)) (C : ℝ≥0), + (∀ i, f (ofTensor (B i)) = C) → + C * f (dotX M) ≤ factor * f (ofTensor (TagTensorWords.sharedLabels B))) : + ((TagWords.fiber c).card : ℝ) ^ f.pX * + TagWords.countWeight (fun i => (f (ofTensor (A i)) : ℝ)) c ≤ + (factor : ℝ) * (f (ofTensor (TagTensorWords.sharedLabels A)) : ℝ) ^ N := by + classical + let M := (TagWords.fiber c).card + let e : Fin M ≃ {w // w ∈ TagWords.fiber c} := + (Fintype.equivFinOfCardEq (Fintype.card_coe (TagWords.fiber c))).symm + let B := fun i : Fin M => TagTensorWords.wordBranch A (e i).val + let C : ℝ≥0 := TagWords.countWeight (fun i => f (ofTensor (A i))) c + have hvalue : ∀ i, f (ofTensor (B i)) = C := by + intro i + exact TagTensorWords.map_wordBranch_of_mem_fiber f A (e i).property + have hsep := hcharge hc B C hvalue + have hselect := TagTensorWords.restricts_power_shared_fiber_enumeration A c e + have hmono : f (ofTensor (TagTensorWords.sharedLabels B)) ≤ + (f (ofTensor (TagTensorWords.sharedLabels A))) ^ N := by + have h := f.monotone' (ofTensor_le hselect) + simpa only [Character.map_power_tensor] using h + have hfinite : C * f (dotX M) ≤ + factor * (f (ofTensor (TagTensorWords.sharedLabels A))) ^ N := + hsep.trans (mul_le_mul_of_nonneg_left hmono (by positivity)) + have hreal : (C : ℝ) * f.dotXValue M ≤ + (factor : ℝ) * (f (ofTensor (TagTensorWords.sharedLabels A)) : ℝ) ^ N := by + exact_mod_cast hfinite + rw [f.dotXValue_eq_rpow M (Nat.succ_le_iff.mpr hc)] at hreal + have hC : (C : ℝ) = + TagWords.countWeight (fun i => (f (ofTensor (A i)) : ℝ)) c := by + simp [C, TagWords.countWeight] + rw [hC, mul_comm] at hreal + exact hreal + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagGrowth.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagGrowth.lean new file mode 100644 index 0000000000..57a7986a7d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagGrowth.lean @@ -0,0 +1,85 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Analysis.SpecificLimits.Normed +public import Mathlib.Analysis.SpecialFunctions.Pow.Real +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.NormNum +public import Mathlib.Tactic.Positivity +public import Mathlib.Tactic.Ring + +/-! +# Removing polynomial overhead from tensor-power inequalities + +A fixed polynomial factor cannot compensate for a strictly smaller exponential +base. The exponent of the overhead may be any fixed nonnegative real number. +This is the scalar limit step used after the finite-word tag decomposition. +-/ + +@[expose] public section + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +open Filter Asymptotics + +/-- Remove a fixed real polynomial overhead from an inequality valid for every +positive tensor power. This statement includes zero exponential bases. -/ +theorem le_of_pow_le_polynomial_mul_pow + (A B C q : ℝ) (hA : 0 ≤ A) (hC : 0 < C) + (h : ∀ N : ℕ, 1 ≤ N → + B ^ N ≤ C * ((N : ℝ) + 1) ^ q * A ^ N) : B ≤ A := by + by_contra hnot + have hAB : A < B := lt_of_not_ge hnot + have hBpos : 0 < B := hA.trans_lt hAB + obtain ⟨k, hqk⟩ := exists_nat_ge q + have hnorm : ‖A‖ < B := by + simpa only [Real.norm_eq_abs, abs_of_nonneg hA] using hAB + have hsmall : ∀ᶠ N : ℕ in atTop, + ‖(C * (2 : ℝ) ^ k) * ((N : ℝ) ^ k * A ^ N)‖ ≤ + (1 / 2 : ℝ) * ‖B ^ N‖ := + ((isLittleO_pow_const_mul_const_pow_const_pow_of_norm_lt k hnorm).const_mul_left + (C * (2 : ℝ) ^ k)).def (by norm_num) + obtain ⟨N, hN, hsmallN⟩ := ((eventually_ge_atTop (1 : ℕ)).and hsmall).exists + have hNreal : 1 ≤ (N : ℝ) := by exact_mod_cast hN + have hpoly : ((N : ℝ) + 1) ^ q ≤ (2 : ℝ) ^ k * (N : ℝ) ^ k := by + calc + ((N : ℝ) + 1) ^ q ≤ ((N : ℝ) + 1) ^ (k : ℝ) := + Real.rpow_le_rpow_of_exponent_le (by linarith) hqk + _ = ((N : ℝ) + 1) ^ k := Real.rpow_natCast _ _ + _ ≤ (2 * (N : ℝ)) ^ k := + pow_le_pow_left₀ (by positivity) (by linarith) k + _ = (2 : ℝ) ^ k * (N : ℝ) ^ k := mul_pow _ _ _ + have hlarge : B ^ N ≤ (C * (2 : ℝ) ^ k) * ((N : ℝ) ^ k * A ^ N) := by + calc + B ^ N ≤ C * ((N : ℝ) + 1) ^ q * A ^ N := h N hN + _ ≤ C * ((2 : ℝ) ^ k * (N : ℝ) ^ k) * A ^ N := + mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hpoly hC.le) + (pow_nonneg hA N) + _ = (C * (2 : ℝ) ^ k) * ((N : ℝ) ^ k * A ^ N) := by ring + have hnonneg : 0 ≤ (C * (2 : ℝ) ^ k) * ((N : ℝ) ^ k * A ^ N) := by + positivity + have hsmall' : (C * (2 : ℝ) ^ k) * ((N : ℝ) ^ k * A ^ N) ≤ + (1 / 2 : ℝ) * B ^ N := by + simpa only [Real.norm_eq_abs, abs_of_nonneg hnonneg, + abs_of_nonneg (pow_nonneg hBpos.le N)] using hsmallN + have hBN : 0 < B ^ N := pow_pos hBpos N + linarith + +/-- Linear overhead in all powers does not increase the exponential rate. -/ +theorem le_of_pow_le_linear_mul_pow (a b K : ℝ) (ha : 0 ≤ a) + (h : ∀ n : ℕ, b ^ n ≤ (K * (n : ℝ) + 1) * a ^ n) : b ≤ a := by + refine le_of_pow_le_polynomial_mul_pow a b (max K 1) 1 ha + (zero_lt_one.trans_le (le_max_right _ _)) ?_ + intro n _ + apply (h n).trans + rw [Real.rpow_one, mul_add, mul_one] + exact mul_le_mul_of_nonneg_right + (add_le_add (mul_le_mul_of_nonneg_right (le_max_left _ _) (Nat.cast_nonneg n)) + (le_max_right _ _)) (pow_nonneg ha n) + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagHeterogeneous.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagHeterogeneous.lean new file mode 100644 index 0000000000..7923a38e39 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagHeterogeneous.lean @@ -0,0 +1,251 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClass +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialSectors +public import Mathlib.Tactic.FinCases + +/-! +# Heterogeneous shared-first-leg tensors + +Padding a branch adds only zero coordinates. The extra uniform labels used by +the separation construction are removed by actual independent local maps. +The first leg is shared throughout; no direct-sum additivity is used here. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TagHeterogeneous + +variable {K : Type*} [CommSemiring K] + +open PolynomialTensors (polynomialTensor triplingReverse triplingSectorTensor) + +variable {X Y Z Y₀ Z₀ Y₁ Z₁ Y₂ Z₂ : Type*} + +/-- Two heterogeneous branches with one common first coordinate. -/ +def sharedTwo (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) : + Tensor K X (Y₀ ⊕ Y₁) (Z₀ ⊕ Z₁) + | x, .inl y, .inl z => T x y z + | x, .inr y, .inr z => S x y z + | _, _, _ => 0 + +/-- Zero extension into the left summand on the last two legs. -/ +def padLeft (T : Tensor K X Y₀ Z₀) : Tensor K X (Y₀ ⊕ Y₁) (Z₀ ⊕ Z₁) + | x, .inl y, .inl z => T x y z + | _, _, _ => 0 + +/-- Zero extension into the right summand on the last two legs. -/ +def padRight (T : Tensor K X Y₁ Z₁) : Tensor K X (Y₀ ⊕ Y₁) (Z₀ ⊕ Z₁) + | x, .inr y, .inr z => T x y z + | _, _, _ => 0 + +section Padding + +variable [Fintype X] [Fintype Y₀] [Fintype Z₀] +variable [Fintype Y₁] [Fintype Z₁] + +/-- Zero padding is an equivalence under mutual actual restriction. -/ +theorem ofTensor_padLeft (T : Tensor K X Y₀ Z₀) : + TensorClass.ofTensor (padLeft (Y₁ := Y₁) (Z₁ := Z₁) T) = + TensorClass.ofTensor T := by + classical + apply TensorClass.ofTensor_eq + · have h := CoefficientTensor.Restricts.pullback + (padLeft (Y₁ := Y₁) (Z₁ := Z₁) T) id Sum.inl Sum.inl + exact h + · refine ⟨(fun x i => if i = x then 1 else 0), + (fun y j => match y with + | .inl v => if j = v then 1 else 0 + | .inr _ => 0), + (fun z k => match z with + | .inl v => if k = v then 1 else 0 + | .inr _ => 0), ?_⟩ + funext x y z + cases y <;> cases z <;> + simp [padLeft, Tensor.restrict, ite_mul, mul_ite] + +/-- Right zero padding also has explicit inclusion and projection maps. -/ +theorem ofTensor_padRight (T : Tensor K X Y₁ Z₁) : + TensorClass.ofTensor (padRight (Y₀ := Y₀) (Z₀ := Z₀) T) = + TensorClass.ofTensor T := by + classical + apply TensorClass.ofTensor_eq + · have h := CoefficientTensor.Restricts.pullback + (padRight (Y₀ := Y₀) (Z₀ := Z₀) T) id Sum.inr Sum.inr + exact h + · refine ⟨(fun x i => if i = x then 1 else 0), + (fun y j => match y with + | .inl _ => 0 + | .inr v => if j = v then 1 else 0), + (fun z k => match z with + | .inl _ => 0 + | .inr v => if k = v then 1 else 0), ?_⟩ + funext x y z + cases y <;> cases z <;> + simp [padRight, Tensor.restrict, ite_mul, mul_ite] + +end Padding + +/-- Keep just one matched pair of sectors in a common ambient tensor. -/ +def maskedFamily {M : ℕ} (ly : Y → Fin M) (lz : Z → Fin M) + (T : Tensor K X Y Z) (h : Fin M) : Tensor K X Y Z := + fun x y z => if ly y = h ∧ lz z = h then T x y z else 0 + +section Labels + +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- Redundant labels are removed by selecting each coordinate's own sector; +the reverse maps are the corresponding zero extensions. -/ +theorem ofTensor_shared_maskedFamily {M : ℕ} + (ly : Y → Fin M) (lz : Z → Fin M) (T : Tensor K X Y Z) + (hcross : ∀ x y z, ly y ≠ lz z → T x y z = 0) : + TensorClass.ofTensor (Tensor.sharedFirst (maskedFamily ly lz T)) = + TensorClass.ofTensor T := by + classical + apply TensorClass.ofTensor_eq + · have hp : Tensor.pullback id (fun y => (ly y, y)) (fun z => (lz z, z)) + (Tensor.sharedFirst (maskedFamily ly lz T)) = T := by + funext x y z + by_cases h : ly y = lz z + · simp [Tensor.pullback, Tensor.sharedFirst, maskedFamily, h] + · simp [Tensor.pullback, Tensor.sharedFirst, h, hcross x y z h] + simpa only [hp] using + (CoefficientTensor.Restricts.pullback (Tensor.sharedFirst (maskedFamily ly lz T)) + id (fun y => (ly y, y)) (fun z => (lz z, z))) + · refine ⟨(fun x i => if i = x then 1 else 0), + (fun y j => if j = y.2 then if ly y.2 = y.1 then 1 else 0 else 0), + (fun z k => if k = z.2 then if lz z.2 = z.1 then 1 else 0 else 0), ?_⟩ + funext x y z + by_cases h : y.1 = z.1 + · simp [Tensor.restrict, Tensor.sharedFirst, maskedFamily, h, + ite_mul, mul_ite] + split_ifs <;> simp_all + · by_cases hy : ly y.2 = y.1 + · by_cases hz : lz z.2 = z.1 + · have hc : T x y.2 z.2 = 0 := hcross _ _ _ (by simpa [hy, hz] using h) + simp [Tensor.restrict, Tensor.sharedFirst, h, hy, hz, + hc, ite_mul, mul_ite] + · simp [Tensor.restrict, Tensor.sharedFirst, h, hy, hz, + mul_ite] + · simp [Tensor.restrict, Tensor.sharedFirst, h, hy, + mul_ite] + +end Labels + +/-- A two-sector label independent of the coordinate inside the sector. -/ +def twoLabel : Y₀ ⊕ Y₁ → Fin 2 + | .inl _ => 0 + | .inr _ => 1 + +/-- Both branches now use the same ambient last two legs. -/ +def twoFamily (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) : + Fin 2 → Tensor K X (Y₀ ⊕ Y₁) (Z₀ ⊕ Z₁) := + ![padLeft T, padRight S] + +theorem twoFamily_eq_maskedFamily + (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) : + twoFamily T S = maskedFamily twoLabel twoLabel (sharedTwo T S) := by + funext h x y z + fin_cases h <;> cases y <;> cases z <;> + simp [twoFamily, maskedFamily, twoLabel, sharedTwo, padLeft, padRight] + +theorem ofTensor_shared_twoFamily + [Fintype X] [Fintype Y₀] [Fintype Z₀] [Fintype Y₁] [Fintype Z₁] + (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) : + TensorClass.ofTensor (Tensor.sharedFirst (twoFamily T S)) = + TensorClass.ofTensor (sharedTwo T S) := by + rw [twoFamily_eq_maskedFamily] + apply ofTensor_shared_maskedFamily + intro x y z h + cases y <;> cases z <;> simp_all [sharedTwo, twoLabel] + +theorem ofTensor_twoFamily + [Fintype X] [Fintype Y₀] [Fintype Z₀] [Fintype Y₁] [Fintype Z₁] + (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) (h : Fin 2) : + TensorClass.ofTensor (twoFamily T S h) = + ![TensorClass.ofTensor T, TensorClass.ofTensor S] h := by + fin_cases h <;> simp [twoFamily, ofTensor_padLeft, ofTensor_padRight] + +/-- Three heterogeneous branches, still sharing one first leg. -/ +def sharedThree (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) + (U : Tensor K X Y₂ Z₂) : + Tensor K X (Y₀ ⊕ (Y₁ ⊕ Y₂)) (Z₀ ⊕ (Z₁ ⊕ Z₂)) := + sharedTwo T (sharedTwo S U) + +/-- In the case `.inl _`, this construction gives `0`. -/ +def threeLabel : Y₀ ⊕ (Y₁ ⊕ Y₂) → Fin 3 + | .inl _ => 0 + | .inr (.inl _) => 1 + | .inr (.inr _) => 2 + +/-- The three padded branches used by the uniform tag theorem. -/ +def threeFamily (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) + (U : Tensor K X Y₂ Z₂) : + Fin 3 → Tensor K X (Y₀ ⊕ (Y₁ ⊕ Y₂)) (Z₀ ⊕ (Z₁ ⊕ Z₂)) := + ![padLeft T, padRight (padLeft S), padRight (padRight U)] + +theorem threeFamily_eq_maskedFamily + (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) + (U : Tensor K X Y₂ Z₂) : + threeFamily T S U = maskedFamily threeLabel threeLabel (sharedThree T S U) := by + funext h x y z + fin_cases h <;> rcases y with y | (y | y) <;> rcases z with z | (z | z) <;> + simp [threeFamily, maskedFamily, threeLabel, sharedThree, sharedTwo, padLeft, padRight] + +theorem ofTensor_shared_threeFamily + [Fintype X] [Fintype Y₀] [Fintype Z₀] [Fintype Y₁] [Fintype Z₁] + [Fintype Y₂] [Fintype Z₂] + (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) + (U : Tensor K X Y₂ Z₂) : + TensorClass.ofTensor (Tensor.sharedFirst (threeFamily T S U)) = + TensorClass.ofTensor (sharedThree T S U) := by + rw [threeFamily_eq_maskedFamily] + apply ofTensor_shared_maskedFamily + intro x y z h + rcases y with y | (y | y) <;> rcases z with z | (z | z) <;> + simp_all [sharedThree, sharedTwo, threeLabel] + +theorem ofTensor_threeFamily + [Fintype X] [Fintype Y₀] [Fintype Z₀] [Fintype Y₁] [Fintype Z₁] + [Fintype Y₂] [Fintype Z₂] + (T : Tensor K X Y₀ Z₀) (S : Tensor K X Y₁ Z₁) + (U : Tensor K X Y₂ Z₂) (h : Fin 3) : + TensorClass.ofTensor (threeFamily T S U h) = + ![TensorClass.ofTensor T, TensorClass.ofTensor S, TensorClass.ofTensor U] h := by + fin_cases h <;> simp [threeFamily, ofTensor_padLeft, ofTensor_padRight] + +/-- The middle polynomial branch keeps its original first-leg reversal. -/ +def triplingMiddleTensor (a h : ℕ) : + Tensor K (Fin a) (Fin (a + h - 1)) (Fin h) := + fun x k j => polynomialTensor a h (triplingReverse x) j k + +/-- The actual polynomial sector assembly is exactly a heterogeneous shared +tensor; in particular all six mismatched sector blocks remain zero. -/ +theorem triplingSectorTensor_eq_sharedThree (a h : ℕ) : + triplingSectorTensor (K := K) a h = sharedThree (polynomialTensor a h) + (triplingMiddleTensor a h) (polynomialTensor a h) := by + funext x y z + rcases y with y | (y | y) <;> rcases z with z | (z | z) <;> rfl + +/-- This is the exact uniform-tag input representing the three-sector +polynomial degeneration, with a literal common first-input space. -/ +theorem ofTensor_tripling_uniform (a h : ℕ) : + TensorClass.ofTensor (Tensor.sharedFirst + (threeFamily (polynomialTensor (K := K) a h) (triplingMiddleTensor a h) + (polynomialTensor a h))) = TensorClass.ofTensor (triplingSectorTensor a h) := by + rw [ofTensor_shared_threeFamily, triplingSectorTensor_eq_sharedThree] + +end MatrixMultiplicationAllFields.TensorSpectrum.TagHeterogeneous diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagOptimized.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagOptimized.lean new file mode 100644 index 0000000000..2262c907fc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagOptimized.lean @@ -0,0 +1,114 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagWords +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagGrowth + +/-! +# Optimizing the finite-fiber tag bound + +The hypothesis here is the numeric inequality for each actual nonempty word +fiber. Its tensor-theoretic proof belongs to the restriction construction. +Taking roots of the letter weights makes the largest fiber capture the desired +sum; the remaining count of possible fibers is only polynomial in the power. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +/-- A real power distributes over a finite product of nonnegative factors. -/ +theorem finset_prod_rpow_nonneg {ι : Type*} (t : Finset ι) (a : ι → ℝ) + (p : ℝ) (ha : ∀ i ∈ t, 0 ≤ a i) : + (∏ i ∈ t, a i) ^ p = ∏ i ∈ t, (a i) ^ p := by + classical + revert ha + induction t using Finset.induction_on with + | empty => intro ha; simp + | @insert i t hi ih => + intro ha + have hai : 0 ≤ a i := ha i (Finset.mem_insert_self i t) + have hat : ∀ j ∈ t, 0 ≤ a j := + fun j hj => ha j (Finset.mem_insert_of_mem hj) + rw [Finset.prod_insert hi, Finset.prod_insert hi, + Real.mul_rpow hai (Finset.prod_nonneg hat), ih hat] + +/-- Powering a count weight is equivalent to powering its letter weights. -/ +theorem countWeight_rpow {s N : ℕ} (a : Fin s → ℝ) + (ha : ∀ i, 0 ≤ a i) (v : TagWords.CountVector s N) (p : ℝ) : + (TagWords.countWeight a v) ^ p = + TagWords.countWeight (fun i => (a i) ^ p) v := by + classical + unfold TagWords.countWeight + rw [finset_prod_rpow_nonneg Finset.univ _ p + (fun i _ => pow_nonneg (ha i) (v i).val)] + apply Finset.prod_congr rfl + intro i _ + exact (Real.rpow_pow_comm (ha i) p (v i).val).symm + +/-- The positive constant and the polynomial number of count vectors disappear in the tensor-power +limit. The premise uses each fiber's actual finite cardinality. -/ +theorem tag_optimized_of_fiber_bounds (factor : ℝ) (hfactor : 0 < factor) + {s : ℕ} (hs : 0 < s) (p : ℝ) (hp : 0 < p) + (c : Fin s → ℝ) (hc : ∀ i, 0 < c i) (x : ℝ) (hx : 0 ≤ x) + (hfinite : ∀ N : ℕ, 1 ≤ N → ∀ v : TagWords.CountVector s N, + 0 < (TagWords.fiber v).card → + ((TagWords.fiber v).card : ℝ) ^ p * TagWords.countWeight c v ≤ + factor * x ^ N) : + (∑ i, (c i) ^ (1 / p)) ^ p ≤ x := by + classical + let a : Fin s → ℝ := fun i => (c i) ^ (1 / p) + have ha : ∀ i, 0 < a i := fun i => Real.rpow_pos_of_pos (hc i) _ + have haroot : ∀ i, (a i) ^ p = c i := by + intro i + simpa only [a, one_div] using Real.rpow_inv_rpow (hc i).le hp.ne' + have hasum : 0 < ∑ i, a i := by + let i₀ : Fin s := ⟨0, hs⟩ + exact (ha i₀).trans_le + (Finset.single_le_sum (fun i _ => (ha i).le) (Finset.mem_univ i₀)) + apply le_of_pow_le_polynomial_mul_pow x ((∑ i, a i) ^ p) factor ((s : ℝ) * p) + hx hfactor + intro N hN + obtain ⟨v, hv, havg⟩ := + TagWords.exists_nonempty_fiberMass_ge_average (N := N) a hasum + have hcount : 0 ≤ TagWords.countWeight a v := + Finset.prod_nonneg (fun i _ => pow_nonneg (ha i).le (v i).val) + have hmass : 0 ≤ TagWords.fiberMass a v := + mul_nonneg (Nat.cast_nonneg _) hcount + have hraw : (∑ i, a i) ^ N ≤ + ((N : ℝ) + 1) ^ s * TagWords.fiberMass a v := by + have hden : 0 < ((N : ℝ) + 1) ^ s := by positivity + simpa only [mul_comm] using (div_le_iff₀ hden).mp havg + have hmasspow : (TagWords.fiberMass a v) ^ p = + ((TagWords.fiber v).card : ℝ) ^ p * TagWords.countWeight c v := by + unfold TagWords.fiberMass + rw [Real.mul_rpow (Nat.cast_nonneg _) hcount, + countWeight_rpow a (fun i => (ha i).le) v p] + simp_rw [haroot] + have hbound : (TagWords.fiberMass a v) ^ p ≤ factor * x ^ N := by + rw [hmasspow] + exact hfinite N hN v (Finset.card_pos.mpr hv) + have hraise := Real.rpow_le_rpow (pow_nonneg hasum.le N) hraw hp.le + have hdenpow : (((N : ℝ) + 1) ^ s) ^ p = + ((N : ℝ) + 1) ^ ((s : ℝ) * p) := + (Real.rpow_natCast_mul (by positivity) s p).symm + calc + ((∑ i, a i) ^ p) ^ N = ((∑ i, a i) ^ N) ^ p := + Real.rpow_pow_comm hasum.le p N + _ ≤ (((N : ℝ) + 1) ^ s * TagWords.fiberMass a v) ^ p := hraise + _ = ((N : ℝ) + 1) ^ ((s : ℝ) * p) * (TagWords.fiberMass a v) ^ p := by + rw [Real.mul_rpow (by positivity) hmass, hdenpow] + _ ≤ ((N : ℝ) + 1) ^ ((s : ℝ) * p) * (factor * x ^ N) := + mul_le_mul_of_nonneg_left hbound (Real.rpow_nonneg (by positivity) _) + _ = factor * ((N : ℝ) + 1) ^ ((s : ℝ) * p) * x ^ N := by ring + +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagPolynomialBranches.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagPolynomialBranches.lean new file mode 100644 index 0000000000..6322cb25cc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagPolynomialBranches.lean @@ -0,0 +1,106 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagHeterogeneous +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialFiltration +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPermutations + +/-! +# Polynomial branches in the heterogeneous tag construction + +The determinant branches retain their actual output coordinates; finite +coordinate equivalences identify their classes with polynomial multiplication. +The middle tripling branch is a last-two-leg swap followed by the stated +invertible reversal of the shared first coordinate. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TagHeterogeneous + +variable {K : Type*} [CommRing K] + +open PolynomialTensors (polynomialTensor determinantGradedTensor + triplingReverse triplingReverse_involutive) + +/-- The larger retained branch of the determinant filtration. -/ +def determinantQuotientTensor (a b : ℕ) : + Tensor K (Fin (a + 1)) (Fin (b + 3)) (Fin (a + b + 3)) := + Tensor.pullback (Equiv.refl _) (Equiv.refl _) (finCongr (by omega)) + (polynomialTensor (a + 1) (b + 3)) + +/-- The smaller retained branch of the determinant filtration. -/ +def determinantKernelTensor (a b : ℕ) : + Tensor K (Fin (a + 1)) (Fin (b + 1)) (Fin (a + b + 1)) := + Tensor.pullback (Equiv.refl _) (Equiv.refl _) (finCongr (by omega)) + (polynomialTensor (a + 1) (b + 1)) + +theorem determinantGradedTensor_eq_sharedTwo (a b : ℕ) : + determinantGradedTensor (K := K) a b = + sharedTwo (determinantQuotientTensor a b) (determinantKernelTensor a b) := by + funext i j k + cases j <;> cases k <;> rfl + +theorem ofTensor_determinantQuotient (a b : ℕ) : + TensorClass.ofTensor (determinantQuotientTensor (K := K) a b) = + TensorClass.ofTensor (polynomialTensor (a + 1) (b + 3)) := by + apply TensorClass.ofTensor_pullback_equiv + +theorem ofTensor_determinantKernel (a b : ℕ) : + TensorClass.ofTensor (determinantKernelTensor (K := K) a b) = + TensorClass.ofTensor (polynomialTensor (a + 1) (b + 1)) := by + apply TensorClass.ofTensor_pullback_equiv + +/-- The uniform separation input is the whole graded determinant tensor. -/ +theorem ofTensor_determinant_uniform (a b : ℕ) : + TensorClass.ofTensor (Tensor.sharedFirst + (twoFamily (determinantQuotientTensor (K := K) a b) (determinantKernelTensor a b))) = + TensorClass.ofTensor (determinantGradedTensor a b) := by + rw [ofTensor_shared_twoFamily, determinantGradedTensor_eq_sharedTwo] + +/-- Both original polynomial branches survive zero padding exactly. -/ +theorem ofTensor_determinant_family (a b : ℕ) (j : Fin 2) : + TensorClass.ofTensor + (twoFamily (determinantQuotientTensor (K := K) a b) (determinantKernelTensor a b) j) = + ![TensorClass.ofTensor (polynomialTensor (a + 1) (b + 3)), + TensorClass.ofTensor (polynomialTensor (a + 1) (b + 1))] j := by + rw [ofTensor_twoFamily, ofTensor_determinantQuotient, ofTensor_determinantKernel] + +/-- This reversal is an actual equivalence, including the empty finite type. -/ +def triplingReverseEquiv (a : ℕ) : Fin a ≃ Fin a where + toFun := triplingReverse + invFun := triplingReverse + left_inv := triplingReverse_involutive + right_inv := triplingReverse_involutive + +/-- The middle branch is evaluated using the permuted character. Its +first-coordinate reversal is removed only by an invertible local map. -/ +theorem ofTensor_triplingMiddle (a h : ℕ) : + TensorClass.ofTensor (triplingMiddleTensor (K := K) a h) = + TensorClass.swapYZ (TensorClass.ofTensor (polynomialTensor a h)) := by + have heq : triplingMiddleTensor (K := K) a h = + Tensor.pullback (triplingReverseEquiv a) (Equiv.refl _) (Equiv.refl _) + (CoefficientTensor.swapYZ (polynomialTensor a h)) := rfl + rw [heq, TensorClass.ofTensor_pullback_equiv, TensorClass.swapYZ_ofTensor] + +theorem ofTensor_tripling_family (a h : ℕ) (j : Fin 3) : + TensorClass.ofTensor + (threeFamily (polynomialTensor (K := K) a h) (triplingMiddleTensor a h) + (polynomialTensor a h) j) = + ![TensorClass.ofTensor (polynomialTensor a h), + TensorClass.swapYZ (TensorClass.ofTensor (polynomialTensor a h)), + TensorClass.ofTensor (polynomialTensor a h)] j := by + rw [ofTensor_threeFamily, ofTensor_triplingMiddle] + +end MatrixMultiplicationAllFields.TensorSpectrum.TagHeterogeneous diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagTensorWords.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagTensorWords.lean new file mode 100644 index 0000000000..97eb103755 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagTensorWords.lean @@ -0,0 +1,228 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPowers +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TagWords + +/-! +# Coefficient tensor words and matched-label restrictions + +Tensor powers of a shared-first-leg tensor have one branch for each word. +The regrouping below preserves all coefficients, including the zero +coefficients between different words. Selecting words by an injection is an +actual local restriction. Multiplicativity is then applied to the actual +tensor product represented by each word. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TagTensorWords + +variable {K : Type*} [CommSemiring K] + +variable {X Y Z : Type*} + +/-- A shared-first-leg tensor with an arbitrary finite label type. -/ +def sharedLabels {ι : Type*} [DecidableEq ι] (A : ι → Tensor K X Y Z) : + Tensor K X (ι × Y) (ι × Z) := + fun x y z => if y.1 = z.1 then A y.1 x y.2 z.2 else 0 + +/-- One actual tensor factor per position, without identifying positions or +discarding any coefficients. -/ +def tensorWord {N : ℕ} (B : Fin N → Tensor K X Y Z) : + Tensor K (Fin N → X) (Fin N → Y) (Fin N → Z) := + fun x y z => ∏ j, B j (x j) (y j) (z j) + +/-- A word specifies which branch occupies each tensor position. -/ +def wordBranch {s N : ℕ} (A : Fin s → Tensor K X Y Z) + (w : TagWords.Word s N) : + Tensor K (Fin N → X) (Fin N → Y) (Fin N → Z) := + tensorWord (fun j => A (w j)) + +/-- Put a word of labels and a word of coordinates back into coordinate pairs. -/ +def joinCoordinates (N : ℕ) (ι U : Type*) : + ((Fin N → ι) × (Fin N → U)) ≃ (Fin N → ι × U) where + toFun p j := (p.1 j, p.2 j) + invFun f := (fun j => (f j).1, fun j => (f j).2) + left_inv p := by + rcases p with ⟨a, b⟩ + rfl + right_inv f := by + funext j + exact Prod.eta (f j) + +/-- Regrouping the second and third coordinates of the full tensor power +produces exactly the shared tensor of word branches. -/ +theorem power_shared_pullback {s N : ℕ} (A : Fin s → Tensor K X Y Z) : + Tensor.pullback (Equiv.refl (Fin N → X)) + (joinCoordinates N (Fin s) Y) (joinCoordinates N (Fin s) Z) + (Tensor.power (sharedLabels A) N) = sharedLabels (wordBranch A) := by + classical + funext x y z + by_cases h : y.1 = z.1 + · simp only [Tensor.pullback, Equiv.refl_apply, Tensor.power, + sharedLabels, ite_eq_left h, wordBranch, tensorWord] + apply Finset.prod_congr rfl + intro j hj + simp [joinCoordinates, + congrFun h j] + · have hex : ∃ j, y.1 j ≠ z.1 j := by + by_contra hnone + apply h + funext j + by_contra hj + exact hnone ⟨j, hj⟩ + obtain ⟨j, hj⟩ := hex + simp only [Tensor.pullback, Equiv.refl_apply, Tensor.power, + sharedLabels, ite_eq_right h] + apply Finset.prod_eq_zero (Finset.mem_univ j) + simp [joinCoordinates, hj] + +section Restriction + +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- The regrouping is implemented by three actual coordinate pullbacks. -/ +theorem restricts_power_shared_words {s N : ℕ} + (A : Fin s → Tensor K X Y Z) : + CoefficientTensor.Restricts (Tensor.power (sharedLabels A) N) + (sharedLabels (wordBranch (N := N) A)) := by + rw [← power_shared_pullback] + exact CoefficientTensor.Restricts.pullback _ _ _ _ + +/-- The regrouping is invertible, so it also identifies the tensor classes. -/ +theorem ofTensor_shared_words {s N : ℕ} (A : Fin s → Tensor K X Y Z) : + TensorClass.ofTensor (sharedLabels (wordBranch (N := N) A)) = + TensorClass.ofTensor (sharedLabels A) ^ N := by + rw [← power_shared_pullback, TensorClass.ofTensor_pullback_equiv, + TensorClass.ofTensor_power] + +omit [Fintype X] [Fintype Y] [Fintype Z] in +/-- An injection on branch labels preserves the equality test between labels. -/ +theorem shared_injective_pullback {ι κ : Type*} + [DecidableEq ι] [DecidableEq κ] + (A : ι → Tensor K X Y Z) (e : κ → ι) (he : Function.Injective e) : + Tensor.pullback id (fun y : κ × Y => (e y.1, y.2)) + (fun z : κ × Z => (e z.1, z.2)) (sharedLabels A) = + sharedLabels (fun i => A (e i)) := by + funext x y z + by_cases h : y.1 = z.1 + · simp [Tensor.pullback, sharedLabels, h] + · have h' : e y.1 ≠ e z.1 := fun h' => h (he h') + simp [Tensor.pullback, sharedLabels, h, h'] + +/-- Selecting any set of matched labels is an actual local restriction. -/ +theorem restricts_shared_injective {ι κ : Type*} + [Fintype ι] [DecidableEq ι] [DecidableEq κ] + (A : ι → Tensor K X Y Z) (e : κ → ι) (he : Function.Injective e) : + CoefficientTensor.Restricts (sharedLabels A) (sharedLabels (fun i => A (e i))) := by + rw [← shared_injective_pullback A e he] + exact CoefficientTensor.Restricts.pullback _ _ _ _ + +/-- This target uses the precise `Fin M` shared tensor accepted by the charged +separation construction. The label map may enumerate any selected word set. -/ +theorem restricts_power_shared_selected {s N M : ℕ} + (A : Fin s → Tensor K X Y Z) (e : Fin M → TagWords.Word s N) + (he : Function.Injective e) : + CoefficientTensor.Restricts (Tensor.power (sharedLabels A) N) + (sharedLabels (fun i => wordBranch A (e i))) := by + have h := (restricts_power_shared_words A).trans + (restricts_shared_injective (wordBranch A) e he) + exact h + +/-- In particular, the words in a count fiber can be retained together. -/ +theorem restricts_power_shared_fiber {s N : ℕ} + (A : Fin s → Tensor K X Y Z) (c : TagWords.CountVector s N) : + CoefficientTensor.Restricts (Tensor.power (sharedLabels A) N) + (sharedLabels (fun w : {w // w ∈ TagWords.fiber c} => wordBranch A w.val)) := by + exact (restricts_power_shared_words A).trans + (restricts_shared_injective (wordBranch A) Subtype.val Subtype.val_injective) + +/-- Every finite enumeration of a count fiber provides the exact input needed +by charged separation, with multiplicity equal to the number of selected words. -/ +theorem restricts_power_shared_fiber_enumeration {s N M : ℕ} + (A : Fin s → Tensor K X Y Z) (c : TagWords.CountVector s N) + (e : Fin M ≃ {w // w ∈ TagWords.fiber c}) : + CoefficientTensor.Restricts (Tensor.power (sharedLabels A) N) + (sharedLabels (fun i => wordBranch A (e i).val)) := by + exact restricts_power_shared_selected A (fun i => (e i).val) + (Subtype.val_injective.comp e.injective) + +end Restriction + +/-- Split off the first tensor position, leaving every remaining coordinate. -/ +def headTailCoordinates (N : ℕ) (U : Type*) : + (Fin (N + 1) → U) ≃ U × (Fin N → U) where + toFun f := (f 0, fun j => f j.succ) + invFun p := Fin.cases p.1 p.2 + left_inv f := by + funext j + refine Fin.cases ?_ (fun k => ?_) j <;> rfl + right_inv p := by + rcases p with ⟨u, f⟩ + rfl + +section Character + +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- The class of a coefficient tensor word is the product of the factor +classes. This is proved by actual invertible coordinate regroupings. -/ +theorem ofTensor_tensorWord {N : ℕ} (B : Fin N → Tensor K X Y Z) : + TensorClass.ofTensor (tensorWord B) = ∏ j, TensorClass.ofTensor (B j) := by + induction N with + | zero => + rw [show (∏ j : Fin 0, TensorClass.ofTensor (B j)) = 1 by simp] + change TensorClass.ofTensor (tensorWord B) = + TensorClass.ofTensor TensorClass.unitTensor + have heq : Tensor.pullback (Equiv.ofUnique (Fin 0 → X) PUnit) + (Equiv.ofUnique (Fin 0 → Y) PUnit) (Equiv.ofUnique (Fin 0 → Z) PUnit) + TensorClass.unitTensor = tensorWord B := by + funext x y z + simp [Tensor.pullback, tensorWord, TensorClass.unitTensor] + rw [← heq] + exact TensorClass.ofTensor_pullback_equiv _ _ _ _ + | succ N ih => + rw [Fin.prod_univ_succ, ← ih (fun j => B j.succ), TensorClass.ofTensor_mul] + have heq : Tensor.pullback (headTailCoordinates N X) + (headTailCoordinates N Y) (headTailCoordinates N Z) + (Tensor.product (B 0) (tensorWord (fun j => B j.succ))) = tensorWord B := by + funext x y z + simp [Tensor.pullback, Tensor.product, tensorWord, headTailCoordinates, + Fin.prod_univ_succ] + rw [← heq] + exact TensorClass.ofTensor_pullback_equiv _ _ _ _ + +/-- A character evaluates a word branch as the finite product of the values +of the chosen branches; there is no separate multiplicativity assumption. -/ +theorem map_wordBranch (f : TensorClass.Character K) {s N : ℕ} + (A : Fin s → Tensor K X Y Z) (w : TagWords.Word s N) : + f (TensorClass.ofTensor (wordBranch A w)) = + TagWords.wordWeight (fun i => f (TensorClass.ofTensor (A i))) w := by + unfold wordBranch TagWords.wordWeight + rw [ofTensor_tensorWord] + exact map_prod f.toHom _ _ + +/-- Every word in a fixed count fiber has the same character value. -/ +theorem map_wordBranch_of_mem_fiber (f : TensorClass.Character K) {s N : ℕ} + (A : Fin s → Tensor K X Y Z) {c : TagWords.CountVector s N} + {w : TagWords.Word s N} (hw : w ∈ TagWords.fiber c) : + f (TensorClass.ofTensor (wordBranch A w)) = + TagWords.countWeight (fun i => f (TensorClass.ofTensor (A i))) c := by + rw [map_wordBranch] + exact TagWords.wordWeight_eq_of_mem_fiber _ hw + +end Character + +end MatrixMultiplicationAllFields.TensorSpectrum.TagTensorWords diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagWords.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagWords.lean new file mode 100644 index 0000000000..888baf9808 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TagWords.lean @@ -0,0 +1,174 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Data.Fintype.BigOperators +public import Mathlib.Basic.Real.Basic +public import Mathlib.Tactic.Positivity + +/-! +# Exact finite word fibers for the tag inequality + +Length-`N` words over `s` letters are grouped by their occurrence counts. +The ambient count-vector space has exactly `(N + 1)^s` elements. Finite +distributivity gives the total weight, so one fiber has at least the average +weight. There are no tensor, asymptotic, or factorial assumptions here. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TagWords + +/-- A word of length `N` over the alphabet of `s` tags. -/ +abbrev Word (s N : ℕ) := Fin N → Fin s + +/-- Stores the number of occurrences of each tag, with each count bounded by the word length. -/ +abbrev CountVector (s N : ℕ) := Fin s → Fin (N + 1) + +/-- Number of positions occupied by the specified letter. -/ +def occurrences {s N : ℕ} (w : Word s N) (i : Fin s) : ℕ := + (Finset.univ.filter (fun j => w j = i)).card + +theorem occurrences_le {s N : ℕ} (w : Word s N) (i : Fin s) : + occurrences w i ≤ N := by + simpa [occurrences] using + (Finset.card_le_card (Finset.filter_subset (fun j => w j = i) Finset.univ)) + +/-- Every occurrence count lies between zero and the word length. -/ +def countVector {s N : ℕ} (w : Word s N) : CountVector s N := + fun i => ⟨occurrences w i, Nat.lt_succ_of_le (occurrences_le w i)⟩ + +@[simp] theorem countVector_val {s N : ℕ} (w : Word s N) (i : Fin s) : + (countVector w i).val = occurrences w i := rfl + +theorem card_countVector (s N : ℕ) : + Fintype.card (CountVector s N) = (N + 1) ^ s := by + simp [CountVector] + +theorem sum_occurrences {s N : ℕ} (w : Word s N) : + ∑ i, occurrences w i = N := by + simpa [occurrences] using + (Finset.sum_fiberwise' Finset.univ w (fun _ : Fin s => (1 : ℕ))) + +/-- The finite set of words having exactly this count vector. -/ +def fiber {s N : ℕ} (c : CountVector s N) : Finset (Word s N) := + Finset.univ.filter (fun w => countVector w = c) + +@[simp] theorem mem_fiber {s N : ℕ} (w : Word s N) (c : CountVector s N) : + w ∈ fiber c ↔ countVector w = c := by + simp [fiber] + +theorem disjoint_fiber {s N : ℕ} {c d : CountVector s N} (h : c ≠ d) : + Disjoint (fiber c) (fiber d) := by + apply Finset.disjoint_left.mpr + intro w hc hd + exact h (((mem_fiber w c).mp hc).symm.trans ((mem_fiber w d).mp hd)) + +section Weights + +variable {R : Type*} [CommMonoid R] {s N : ℕ} + +/-- The weight obtained by multiplying the weights of the successive letters. -/ +def wordWeight (a : Fin s → R) (w : Word s N) : R := + ∏ j, a (w j) + +/-- The weight obtained by raising each tag weight to its occurrence count and multiplying the +results. -/ +def countWeight (a : Fin s → R) (c : CountVector s N) : R := + ∏ i, a i ^ (c i).val + +/-- Grouping positions by their letters identifies the common weight of a +count fiber. This is an exact finite product identity. -/ +theorem wordWeight_eq_countWeight (a : Fin s → R) (w : Word s N) : + wordWeight a w = countWeight a (countVector w) := by + classical + simpa [wordWeight, countWeight, countVector, occurrences] using + (Finset.prod_fiberwise' Finset.univ w a).symm + +theorem wordWeight_eq_of_mem_fiber (a : Fin s → R) + {c : CountVector s N} {w : Word s N} (hw : w ∈ fiber c) : + wordWeight a w = countWeight a c := by + rw [wordWeight_eq_countWeight, (mem_fiber w c).mp hw] + +end Weights + +section Mass + +variable {R : Type*} [CommSemiring R] {s N : ℕ} + +/-- Fiber mass is its actual cardinality times its common word weight. -/ +def fiberMass (a : Fin s → R) (c : CountVector s N) : R := + (fiber c).card * countWeight a c + +theorem sum_fiber_wordWeight (a : Fin s → R) (c : CountVector s N) : + ∑ w ∈ fiber c, wordWeight a w = fiberMass a c := by + calc + ∑ w ∈ fiber c, wordWeight a w = ∑ _w ∈ fiber c, countWeight a c := by + apply Finset.sum_congr rfl + intro w hw + exact wordWeight_eq_of_mem_fiber a hw + _ = fiberMass a c := by simp [fiberMass] + +/-- Finite distributivity over all length-`N` words. -/ +theorem sum_wordWeight (a : Fin s → R) : + ∑ w : Word s N, wordWeight a w = (∑ i, a i) ^ N := by + exact (Fintype.sum_pow a N).symm + +/-- The fibers partition all words, including empty fibers without changing +the total mass. -/ +theorem sum_fiberMass (a : Fin s → R) : + ∑ c : CountVector s N, fiberMass a c = (∑ i, a i) ^ N := by + calc + ∑ c : CountVector s N, fiberMass a c = + ∑ c : CountVector s N, ∑ w ∈ fiber c, wordWeight a w := by + apply Finset.sum_congr rfl + intro c hc + exact (sum_fiber_wordWeight a c).symm + _ = ∑ w : Word s N, wordWeight a w := by + exact Finset.sum_fiberwise Finset.univ countVector (wordWeight a) + _ = (∑ i, a i) ^ N := sum_wordWeight a + +end Mass + +/-- Exact polynomial-overhead bound, before any limit is taken. -/ +theorem exists_fiberMass_ge_average {s N : ℕ} (a : Fin s → ℝ) : + ∃ c : CountVector s N, + (∑ i, a i) ^ N / ((N : ℝ) + 1) ^ s ≤ fiberMass a c := by + classical + have hd : ((N : ℝ) + 1) ^ s ≠ 0 := by positivity + have hsum : + (∑ _c : CountVector s N, (∑ i, a i) ^ N / ((N : ℝ) + 1) ^ s) = + (∑ i, a i) ^ N := by + simp only [Finset.sum_const, Finset.card_univ, card_countVector, nsmul_eq_mul, + Nat.cast_pow, Nat.cast_add, Nat.cast_one] + exact mul_div_cancel₀ _ hd + obtain ⟨c, hc, hbound⟩ := Finset.exists_le_of_sum_le + (s := Finset.univ) Finset.univ_nonempty + (f := fun _c : CountVector s N => (∑ i, a i) ^ N / ((N : ℝ) + 1) ^ s) + (g := fiberMass a) (by rw [hsum, sum_fiberMass]) + exact ⟨c, hbound⟩ + +/-- A positive total gives a genuinely nonempty selected word fiber. -/ +theorem exists_nonempty_fiberMass_ge_average {s N : ℕ} (a : Fin s → ℝ) + (ha : 0 < ∑ i, a i) : + ∃ c : CountVector s N, (fiber c).Nonempty ∧ + (∑ i, a i) ^ N / ((N : ℝ) + 1) ^ s ≤ fiberMass a c := by + obtain ⟨c, hc⟩ := exists_fiberMass_ge_average (N := N) a + have hmass : 0 < fiberMass a c := + lt_of_lt_of_le (div_pos (pow_pos ha N) (by positivity)) hc + have hcard : (fiber c).card ≠ 0 := by + intro hzero + simp [fiberMass, hzero] at hmass + exact ⟨c, Finset.card_pos.mp (Nat.pos_of_ne_zero hcard), hc⟩ + +end MatrixMultiplicationAllFields.TensorSpectrum.TagWords diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorCharacterPermutationPowers.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorCharacterPermutationPowers.lean new file mode 100644 index 0000000000..c7f4f8e531 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorCharacterPermutationPowers.lean @@ -0,0 +1,138 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassPermutations +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorCharacterPowers + +/-! +# The exponents of the six permuted characters + +The exponent identities below follow from evaluating the actual pairings at +dimension two. In particular, they do not depend on how the power-law witnesses +were chosen. Polynomial multiplication with one scalar input is identified +with the corresponding actual pairing by explicit coordinate equivalences. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +variable {K : Type*} [CommSemiring K] + +open PolynomialTensors (polynomialTensor) + +/-- Scalar polynomial input and full output give the first-leg pairing, +including the empty second input case. -/ +theorem polynomialTensor_one_left_class (n : ℕ) : + ofTensor (polynomialTensor (K := K) 1 n) = dotX n := by + let u : Fin 1 ≃ Unit := Equiv.ofUnique _ _ + let e : Fin (1 + n - 1) ≃ Fin n := finCongr (by omega) + have h : polynomialTensor (K := K) 1 n = + Tensor.pullback u (Equiv.refl _) e (CoefficientTensor.dotXCoeff n) := by + funext i j k + simp [Tensor.pullback, CoefficientTensor.dotXCoeff, + Fin.ext_iff, e] + change ofTensor (polynomialTensor 1 n) = ofTensor (CoefficientTensor.dotXCoeff n) + rw [h] + exact ofTensor_pullback_equiv _ _ _ _ + +namespace Character + +theorem permuted_dotXValue (f : Character K) (i : Fin 6) (n : ℕ) : + (f.permuted i).dotXValue n = + ![f.dotXValue n, f.dotYValue n, f.dotXValue n, + f.dotYValue n, f.dotZValue n, f.dotZValue n] i := by + unfold dotXValue + rw [f.permuted_dotX] + fin_cases i <;> rfl + +/-- The first-leg exponents of the six actual characters, with their +multiplicities. Uniqueness is forced by the value at dimension two. -/ +theorem permuted_pX (f : Character K) (i : Fin 6) : + (f.permuted i).pX = ![f.pX, f.pY, f.pX, f.pY, f.pZ, f.pZ] i := by + apply (Real.rpow_right_inj (by norm_num : (0 : ℝ) < 2) (by norm_num)).mp + have hvalue := (f.permuted i).dotXValue_eq_rpow 2 (by norm_num) + simp only [Nat.cast_ofNat] at hvalue + rw [← hvalue, permuted_dotXValue] + simp only [f.dotXValue_eq_rpow 2 (by norm_num), + f.dotYValue_eq_rpow 2 (by norm_num), f.dotZValue_eq_rpow 2 (by norm_num), + Nat.cast_ofNat] + fin_cases i <;> rfl + +theorem sum_permuted_pX (f : Character K) : + (∑ i : Fin 6, (f.permuted i).pX) = 2 * (f.pX + f.pY + f.pZ) := by + simp [permuted_pX, Fin.sum_univ_succ] + ring + +/-- The average of the character's three pairing exponents. -/ +def meanExponent (f : Character K) : ℝ := (f.pX + f.pY + f.pZ) / 3 + +theorem meanExponent_nonneg (f : Character K) : 0 ≤ f.meanExponent := + div_nonneg f.sum_exponents_nonneg (by norm_num) + +theorem meanExponent_le_one (f : Character K) : f.meanExponent ≤ 1 := by + unfold meanExponent + linarith [f.sum_exponents_le_three] + +theorem sum_exponents_eq_three_meanExponent (f : Character K) : + f.pX + f.pY + f.pZ = 3 * f.meanExponent := by + unfold meanExponent + ring + +theorem sum_permuted_pX_eq_six_meanExponent (f : Character K) : + (∑ i : Fin 6, (f.permuted i).pX) = 6 * f.meanExponent := by + rw [sum_permuted_pX] + unfold meanExponent + ring + +/-- A permutation cannot change the sum of the three exponents, since it +preserves the square matrix multiplication tensor at every dimension. -/ +theorem sum_exponents_permuted (f : Character K) (i : Fin 6) : + (f.permuted i).pX + (f.permuted i).pY + (f.permuted i).pZ = + f.pX + f.pY + f.pZ := by + apply (Real.rpow_right_inj (by norm_num : (0 : ℝ) < 2) (by norm_num)).mp + have hleft := (f.permuted i).square_value_eq_rpow 2 (by norm_num) + have hright := f.square_value_eq_rpow 2 (by norm_num) + simp only [Nat.cast_ofNat] at hleft hright + rw [← hleft, ← hright, f.permuted_square] + +@[simp] theorem meanExponent_permuted (f : Character K) (i : Fin 6) : + (f.permuted i).meanExponent = f.meanExponent := by + unfold meanExponent + rw [sum_exponents_permuted] + +theorem permuted_polynomialTensor_one_left_value + (f : Character K) (i : Fin 6) (n : ℕ) (hn : 1 ≤ n) : + (f.permuted i (ofTensor (polynomialTensor 1 n)) : ℝ) = + (n : ℝ) ^ (f.permuted i).pX := by + rw [polynomialTensor_one_left_class] + exact (f.permuted i).dotXValue_eq_rpow n hn + +/-- The six boundary values are the powers with exponents +`pX, pY, pX, pY, pZ, pZ`. -/ +theorem permuted_polynomialTensor_one_left_vector + (f : Character K) (i : Fin 6) (n : ℕ) (hn : 1 ≤ n) : + (f.permuted i (ofTensor (polynomialTensor 1 n)) : ℝ) = + (n : ℝ) ^ (![f.pX, f.pY, f.pX, f.pY, f.pZ, f.pZ] i) := by + rw [permuted_polynomialTensor_one_left_value f i n hn, permuted_pX] + +theorem permuted_polynomialTensor_one_right_value + (f : Character K) (i : Fin 6) (n : ℕ) (hn : 1 ≤ n) : + (f.permuted i (ofTensor (polynomialTensor n 1)) : ℝ) = + (n : ℝ) ^ (f.permuted (permuteSwapXY i)).pX := by + rw [← swapXY_polynomialTensor 1 n, f.permuted_swapXY] + exact f.permuted_polynomialTensor_one_left_value (permuteSwapXY i) n hn + +end Character +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorCharacterPowers.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorCharacterPowers.lean new file mode 100644 index 0000000000..e6ab76f83f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorCharacterPowers.lean @@ -0,0 +1,124 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.CharacterPower + +/-! +# Character exponents of the auxiliary pairings + +The power laws follow from the actual coordinate restrictions and product +identities. Their exponents are constructed here, rather than supplied as +assumptions about a character. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character + +variable {K : Type*} [CommSemiring K] + +theorem exists_dotX_power (f : Character K) : + ∃ p : ℝ, 0 ≤ p ∧ p ≤ 1 ∧ + ∀ n : ℕ, 1 ≤ n → f.dotXValue n = (n : ℝ) ^ p := by + apply TensorSpectrum.exists_power_of_monotone_multiplicative f.dotXValue + · intro m n hm hn + exact f.dotXValue_mul m n + · intro m n hm hmn + exact f.dotXValue_mono hmn + · intro n hn + exact ⟨f.one_le_dotXValue (Nat.lt_of_lt_of_le Nat.zero_lt_one hn), + f.dotXValue_le n⟩ + +theorem exists_dotY_power (f : Character K) : + ∃ p : ℝ, 0 ≤ p ∧ p ≤ 1 ∧ + ∀ n : ℕ, 1 ≤ n → f.dotYValue n = (n : ℝ) ^ p := by + apply TensorSpectrum.exists_power_of_monotone_multiplicative f.dotYValue + · intro m n hm hn + exact f.dotYValue_mul m n + · intro m n hm hmn + exact f.dotYValue_mono hmn + · intro n hn + exact ⟨f.one_le_dotYValue (Nat.lt_of_lt_of_le Nat.zero_lt_one hn), + f.dotYValue_le n⟩ + +theorem exists_dotZ_power (f : Character K) : + ∃ p : ℝ, 0 ≤ p ∧ p ≤ 1 ∧ + ∀ n : ℕ, 1 ≤ n → f.dotZValue n = (n : ℝ) ^ p := by + apply TensorSpectrum.exists_power_of_monotone_multiplicative f.dotZValue + · intro m n hm hn + exact f.dotZValue_mul m n + · intro m n hm hmn + exact f.dotZValue_mono hmn + · intro n hn + exact ⟨f.one_le_dotZValue (Nat.lt_of_lt_of_le Nat.zero_lt_one hn), + f.dotZValue_le n⟩ + +/-- Computes the p x by the application `Classical.choose f.exists_dotX_power`. -/ +noncomputable def pX (f : Character K) : ℝ := Classical.choose f.exists_dotX_power +/-- Computes the p y by the application `Classical.choose f.exists_dotY_power`. -/ +noncomputable def pY (f : Character K) : ℝ := Classical.choose f.exists_dotY_power +/-- Computes the p z by the application `Classical.choose f.exists_dotZ_power`. -/ +noncomputable def pZ (f : Character K) : ℝ := Classical.choose f.exists_dotZ_power + +theorem pX_nonneg (f : Character K) : 0 ≤ f.pX := + (Classical.choose_spec f.exists_dotX_power).1 + +theorem pY_nonneg (f : Character K) : 0 ≤ f.pY := + (Classical.choose_spec f.exists_dotY_power).1 + +theorem pZ_nonneg (f : Character K) : 0 ≤ f.pZ := + (Classical.choose_spec f.exists_dotZ_power).1 + +theorem pX_le_one (f : Character K) : f.pX ≤ 1 := + (Classical.choose_spec f.exists_dotX_power).2.1 + +theorem pY_le_one (f : Character K) : f.pY ≤ 1 := + (Classical.choose_spec f.exists_dotY_power).2.1 + +theorem pZ_le_one (f : Character K) : f.pZ ≤ 1 := + (Classical.choose_spec f.exists_dotZ_power).2.1 + +theorem dotXValue_eq_rpow (f : Character K) (n : ℕ) (hn : 1 ≤ n) : + f.dotXValue n = (n : ℝ) ^ f.pX := + (Classical.choose_spec f.exists_dotX_power).2.2 n hn + +theorem dotYValue_eq_rpow (f : Character K) (n : ℕ) (hn : 1 ≤ n) : + f.dotYValue n = (n : ℝ) ^ f.pY := + (Classical.choose_spec f.exists_dotY_power).2.2 n hn + +theorem dotZValue_eq_rpow (f : Character K) (n : ℕ) (hn : 1 ≤ n) : + f.dotZValue n = (n : ℝ) ^ f.pZ := + (Classical.choose_spec f.exists_dotZ_power).2.2 n hn + +theorem square_value_eq_rpow (f : Character K) (n : ℕ) (hn : 1 ≤ n) : + (f (square n) : ℝ) = (n : ℝ) ^ (f.pX + f.pY + f.pZ) := by + have hnR : 0 < (n : ℝ) := by + exact_mod_cast (Nat.lt_of_lt_of_le Nat.zero_lt_one hn) + rw [← f.dotValues_product n, f.dotXValue_eq_rpow n hn, + f.dotYValue_eq_rpow n hn, f.dotZValue_eq_rpow n hn, + ← Real.rpow_add hnR, ← Real.rpow_add hnR] + +theorem sum_exponents_nonneg (f : Character K) : 0 ≤ f.pX + f.pY + f.pZ := + add_nonneg (add_nonneg f.pX_nonneg f.pY_nonneg) f.pZ_nonneg + +theorem sum_exponents_le_three (f : Character K) : f.pX + f.pY + f.pZ ≤ 3 := by + have hx := f.pX_le_one + have hy := f.pY_le_one + have hz := f.pZ_le_one + linarith + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass.Character + +variable {K : Type*} [CommSemiring K] diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClass.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClass.lean new file mode 100644 index 0000000000..c01a41b9b9 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClass.lean @@ -0,0 +1,335 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import Mathlib.Logic.Equiv.Fin.Basic +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.LocalTensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.Blocks +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexMatrixTensor + +/-! # Finite coefficient tensors and the mutual restriction quotient -/ + +@[expose] public section + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +variable {K : Type*} [CommSemiring K] + +namespace CoefficientTensor + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +variable {X Y Z U V W X' Y' Z' : Type*} +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- `Restricts A B` means that the source `A` restricts to the target `B`. -/ +def Restricts (A : Tensor K X Y Z) (B : Tensor K U V W) : Prop := + B ∈ MatrixExponent.LocalTensor.orbit A + +theorem Restricts.refl (A : Tensor K X Y Z) : Restricts A A := by + classical + exact ⟨_, _, _, (Tensor.restrict_identity A).symm⟩ + +theorem Restricts.trans [Fintype U] [Fintype V] [Fintype W] + {A : Tensor K X Y Z} {B : Tensor K U V W} {C : Tensor K X' Y' Z'} + (hAB : Restricts A B) (hBC : Restricts B C) : Restricts A C := by + rcases hAB with ⟨a, b, c, rfl⟩ + rcases hBC with ⟨d, e, f, rfl⟩ + exact ⟨Tensor.composeRestrictionMatrix d a, Tensor.composeRestrictionMatrix e b, + Tensor.composeRestrictionMatrix f c, Tensor.restrict_restrict a b c d e f A⟩ + +theorem Restricts.pullback (A : Tensor K X Y Z) + (f : U → X) (g : V → Y) (h : W → Z) : + Restricts A (Tensor.pullback f g h A) := by + classical + exact ⟨_, _, _, Tensor.pullback_eq_restrict f g h A⟩ + +theorem Restricts.rankAtMost {A : Tensor K X Y Z} {B : Tensor K U V W} + {r : ℕ} (hAB : Restricts A B) (hA : Tensor.RankAtMost A r) : + Tensor.RankAtMost B r := by + rcases hAB with ⟨a, b, c, rfl⟩ + exact hA.restrict a b c + +variable {X Y Z U V W X' Y' Z' U' V' W' : Type*} +variable [Fintype X] [Fintype Y] [Fintype Z] +variable [Fintype U] [Fintype V] [Fintype W] + +/-- Restriction is compatible with heterogeneous tensor direct sums. -/ +theorem Restricts.blockSum + {T : Tensor K X Y Z} {T' : Tensor K X' Y' Z'} + {S : Tensor K U V W} {S' : Tensor K U' V' W'} + (hT : Restricts T T') (hS : Restricts S S') : + Restricts (blockSum T S) (blockSum T' S') := by + rcases hT with ⟨A, B, C, rfl⟩ + rcases hS with ⟨D, E, F, rfl⟩ + exact ⟨blockMatrix A D, blockMatrix B E, blockMatrix C F, + (restrict_blockSum A B C D E F T S).symm⟩ + +/-- Restriction is compatible with tensor products through the actual products +of the three local coefficient matrices. -/ +theorem Restricts.product + {T : Tensor K X Y Z} {T' : Tensor K X' Y' Z'} + {S : Tensor K U V W} {S' : Tensor K U' V' W'} + (hT : Restricts T T') (hS : Restricts S S') : + Restricts (Tensor.product T S) (Tensor.product T' S') := by + rcases hT with ⟨A, B, C, rfl⟩ + rcases hS with ⟨D, E, F, rfl⟩ + exact ⟨fun x u => A x.1 u.1 * D x.2 u.2, + fun y v => B y.1 v.1 * E y.2 v.2, + fun z w => C z.1 w.1 * F z.2 w.2, + (Tensor.restrict_product A B C D E F T S).symm⟩ + + +/-- Injective index maps preserve all three shared-index equalities of a matrix +tensor, including its zero coefficients. -/ +theorem matrixCoefficients_pullback_injective + {K A B C X Y Z : Type*} [CommSemiring K] + [DecidableEq A] [DecidableEq B] [DecidableEq C] + [DecidableEq X] [DecidableEq Y] [DecidableEq Z] + (a : X → A) (b : Y → B) (c : Z → C) + (ha : Function.Injective a) (hb : Function.Injective b) (hc : Function.Injective c) : + Tensor.pullback (Prod.map a b) (Prod.map b c) (Prod.map c a) + (Tensor.matrixCoefficients (K := K) A B C) = + Tensor.matrixCoefficients (K := K) X Y Z := by + funext x y z + change (if b x.2 = b y.1 ∧ c y.2 = c z.1 ∧ a z.2 = a x.1 then (1 : K) else 0) = + if x.2 = y.1 ∧ y.2 = z.1 ∧ z.2 = x.1 then 1 else 0 + simp only [ha.eq_iff, hb.eq_iff, hc.eq_iff] + +/-- The matrix multiplication tensor with the same dimension on all three wires. -/ +abbrev squareMatrixTensor (n : ℕ) := Tensor.matrixCoefficients (K := K) (Fin n) (Fin n) (Fin n) + +/-- Pair the row indices and column indices separately, then enumerate each +pair by the standard equivalence with `Fin (n * m)`. -/ +def squareProductCoordinates (n m : ℕ) : + ((Fin n × Fin n) × (Fin m × Fin m)) ≃ (Fin (n * m) × Fin (n * m)) where + toFun p := (finProdFinEquiv (p.1.1, p.2.1), finProdFinEquiv (p.1.2, p.2.2)) + invFun p := + ((((finProdFinEquiv : Fin n × Fin m ≃ Fin (n * m)).symm p.1).1, + ((finProdFinEquiv : Fin n × Fin m ≃ Fin (n * m)).symm p.2).1), + (((finProdFinEquiv : Fin n × Fin m ≃ Fin (n * m)).symm p.1).2, + ((finProdFinEquiv : Fin n × Fin m ≃ Fin (n * m)).symm p.2).2)) + left_inv p := by + rcases p with ⟨⟨i, j⟩, ⟨u, v⟩⟩ + simp only [Equiv.symm_apply_apply] + right_inv p := by + rcases p with ⟨i, j⟩ + simp only [Prod.mk.eta, Equiv.apply_symm_apply] + +/-- The product of two square matrix tensors is the larger square tensor under +an explicit bijective relabeling of each local coordinate space. -/ +theorem square_product_pullback (n m : ℕ) : + Tensor.pullback (squareProductCoordinates n m) (squareProductCoordinates n m) + (squareProductCoordinates n m) (squareMatrixTensor (K := K) (n * m)) = + Tensor.product (squareMatrixTensor (K := K) n) (squareMatrixTensor (K := K) m) := by + let e : (Fin n × Fin m) ≃ Fin (n * m) := finProdFinEquiv + have he := matrixCoefficients_pullback_injective (K := K) e e e + e.injective e.injective e.injective + funext x y z + let x' : (Fin n × Fin m) × (Fin n × Fin m) := ((x.1.1, x.2.1), (x.1.2, x.2.2)) + let y' : (Fin n × Fin m) × (Fin n × Fin m) := ((y.1.1, y.2.1), (y.1.2, y.2.2)) + let z' : (Fin n × Fin m) × (Fin n × Fin m) := ((z.1.1, z.2.1), (z.1.2, z.2.2)) + calc + _ = Tensor.matrixCoefficients (K := K) (Fin n × Fin m) (Fin n × Fin m) + (Fin n × Fin m) x' y' z' := congrFun (congrFun (congrFun he x') y') z' + _ = _ := (Tensor.matrixCoefficients_product (K := K) x' y' z').symm + +/-- Taking the first `n` indices in each matrix direction is an actual local +restriction of the larger matrix multiplication tensor. -/ +theorem square_restricts_of_le {n m : ℕ} (h : n ≤ m) : + Restricts (squareMatrixTensor (K := K) m) (squareMatrixTensor (K := K) n) := by + let e : Fin n → Fin m := fun i => ⟨i.val, lt_of_lt_of_le i.isLt h⟩ + have he : Function.Injective e := by + intro i j hij + apply Fin.ext + exact congrArg (fun k : Fin m => k.val) hij + have hr := Restricts.pullback (squareMatrixTensor (K := K) m) + (Prod.map e e) (Prod.map e e) (Prod.map e e) + have hp := matrixCoefficients_pullback_injective (K := K) e e e he he he + change Tensor.pullback (Prod.map e e) (Prod.map e e) (Prod.map e e) + (squareMatrixTensor (K := K) m) = squareMatrixTensor (K := K) n at hp + rwa [hp] at hr + +/-- The usual cubic tensor decomposition, with one term for each triple of +matrix indices rather than one term for each ambient coefficient. -/ +theorem square_rankAtMost_cubic (n : ℕ) : + Tensor.RankAtMost (squareMatrixTensor (K := K) n) (n ^ 3) := by + let a : (Fin n × Fin n × Fin n) → (Fin n × Fin n) → K := + fun p x => if p.1 = x.1 ∧ p.2.1 = x.2 then 1 else 0 + let b : (Fin n × Fin n × Fin n) → (Fin n × Fin n) → K := + fun p y => if p.2.1 = y.1 ∧ p.2.2 = y.2 then 1 else 0 + let c : (Fin n × Fin n × Fin n) → (Fin n × Fin n) → K := + fun p z => if p.2.2 = z.1 ∧ z.2 = p.1 then 1 else 0 + have hr := Tensor.rankAtMost_sum_rankOne a b c + have heq : (fun x y z => ∑ p, Tensor.rankOne (a p) (b p) (c p) x y z) = + squareMatrixTensor (K := K) n := by + funext x y z + rw [Finset.sum_eq_single (x.1, x.2, y.2)] + · by_cases hxy : x.2 = y.1 <;> by_cases hyz : y.2 = z.1 <;> + by_cases hzx : z.2 = x.1 <;> + simp [a, b, c, Tensor.rankOne, squareMatrixTensor, Tensor.matrixCoefficients, hxy, hyz, + hzx] + · intro p hp hne + by_cases hi : p.1 = x.1 + · by_cases hj : p.2.1 = x.2 + · by_cases hk : p.2.2 = y.2 + · exact (hne (Prod.ext hi (Prod.ext hj hk))).elim + · simp [a, b, c, Tensor.rankOne, hk] + · simp [a, b, c, Tensor.rankOne, hj] + · simp [a, b, c, Tensor.rankOne, hi] + · simp + rw [heq] at hr + simpa [Fintype.card_prod, Fintype.card_fin, pow_succ, mul_assoc] using hr + +end CoefficientTensor + +/-- A finite coefficient tensor with an explicit dimension on every leg. -/ +structure TensorRep (K : Type*) where + /-- The size of the first tensor leg. -/ + xDim : ℕ + /-- The size of the second tensor leg. -/ + yDim : ℕ + /-- The size of the third tensor leg. -/ + zDim : ℕ + /-- The `(TensorRep K)` component of type `Tensor K (Fin xDim) (Fin yDim) (Fin zDim)`. -/ + coeff : Tensor K (Fin xDim) (Fin yDim) (Fin zDim) + +namespace TensorRep + +/-- Encode arbitrary finite coordinates by their canonical finite enumeration. -/ +noncomputable def ofTensor {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor K X Y Z) : (TensorRep K) where + xDim := Fintype.card X + yDim := Fintype.card Y + zDim := Fintype.card Z + coeff := Tensor.pullback (Fintype.equivFin X).symm + (Fintype.equivFin Y).symm (Fintype.equivFin Z).symm T + +/-- Requires `CoefficientTensor.Restricts A.coeff B.coeff`. -/ +def Restricts (A B : (TensorRep K)) : Prop := CoefficientTensor.Restricts A.coeff B.coeff + +theorem Restricts.refl (A : (TensorRep K)) : Restricts A A := + CoefficientTensor.Restricts.refl A.coeff + +theorem Restricts.trans {A B C : (TensorRep K)} + (hAB : Restricts A B) (hBC : Restricts B C) : Restricts A C := + CoefficientTensor.Restricts.trans hAB hBC + +theorem restricts_ofTensor {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor K X Y Z) : + CoefficientTensor.Restricts T (ofTensor T).coeff := + CoefficientTensor.Restricts.pullback T _ _ _ + +theorem ofTensor_restricts {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor K X Y Z) : + CoefficientTensor.Restricts (ofTensor T).coeff T := by + have h := CoefficientTensor.Restricts.pullback (ofTensor T).coeff + (Fintype.equivFin X) (Fintype.equivFin Y) (Fintype.equivFin Z) + have heq : Tensor.pullback (Fintype.equivFin X) (Fintype.equivFin Y) + (Fintype.equivFin Z) (ofTensor T).coeff = T := by + funext x y z + simp only [ofTensor, Tensor.pullback, Equiv.symm_apply_apply] + rcases h with ⟨a, b, c, hc⟩ + exact ⟨a, b, c, heq.symm.trans hc⟩ + +theorem Restricts.ofTensor {X Y Z U V W : Type*} + [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] [Fintype W] + {T : Tensor K X Y Z} {U' : Tensor K U V W} + (h : CoefficientTensor.Restricts T U') : Restricts (ofTensor T) (ofTensor U') := + (ofTensor_restricts T).trans (h.trans (restricts_ofTensor U')) + +/-- Mutual actual restriction, allowing unused or zero coordinates. -/ +def Equivalent (A B : (TensorRep K)) : Prop := Restricts A B ∧ Restricts B A + +instance mutualRestriction : Setoid (TensorRep K) where + r := Equivalent + iseqv := ⟨fun A => ⟨.refl A, .refl A⟩, + fun h => ⟨h.2, h.1⟩, + fun hAB hBC => ⟨hAB.1.trans hBC.1, hBC.2.trans hAB.2⟩⟩ + +theorem equivalent_ofTensor_coeff (A : (TensorRep K)) : Equivalent (ofTensor A.coeff) A := + ⟨ofTensor_restricts A.coeff, restricts_ofTensor A.coeff⟩ + +end TensorRep + +/-- Finite coefficient tensors modulo mutual restriction. -/ +def TensorClass (K : Type*) [CommSemiring K] := + Quotient (TensorRep.mutualRestriction (K := K)) + +namespace TensorClass + +/-- Sends the representative to its class in the quotient. -/ +def ofRep (A : (TensorRep K)) : (TensorClass K) := Quotient.mk _ A + +/-- Computes the of tensor by the application `ofRep (TensorRep.ofTensor T)`. -/ +noncomputable def ofTensor {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor K X Y Z) : (TensorClass K) := ofRep (TensorRep.ofTensor T) + +theorem ofRep_eq {A B : (TensorRep K)} (h : TensorRep.Equivalent A B) : + ofRep A = ofRep B := Quotient.sound h + +theorem ofTensor_coeff (A : (TensorRep K)) : ofTensor A.coeff = ofRep A := + ofRep_eq (TensorRep.equivalent_ofTensor_coeff A) + +theorem ofTensor_eq {X Y Z U V W : Type*} + [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] [Fintype W] + {T : Tensor K X Y Z} {S : Tensor K U V W} + (hTS : CoefficientTensor.Restricts T S) + (hST : CoefficientTensor.Restricts S T) : ofTensor T = ofTensor S := + ofRep_eq ⟨TensorRep.Restricts.ofTensor hTS, TensorRep.Restricts.ofTensor hST⟩ + +theorem ofTensor_pullback_equiv {X Y Z U V W : Type*} + [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] [Fintype W] + (T : Tensor K X Y Z) (f : U ≃ X) (g : V ≃ Y) (h : W ≃ Z) : + ofTensor (Tensor.pullback f g h T) = ofTensor T := by + apply ofTensor_eq + · have h' := CoefficientTensor.Restricts.pullback (Tensor.pullback f g h T) + f.symm g.symm h.symm + have heq : Tensor.pullback f.symm g.symm h.symm (Tensor.pullback f g h T) = T := by + funext x y z + simp only [Tensor.pullback, Equiv.apply_symm_apply] + rw [heq] at h' + exact h' + · exact CoefficientTensor.Restricts.pullback T f g h + +instance : LE (TensorClass K) where + le A B := Quotient.liftOn₂ A B (fun a b => TensorRep.Restricts b a) (by + intro A B A' B' hA hB + apply propext + exact ⟨fun h => hB.2.trans (h.trans hA.1), + fun h => hB.1.trans (h.trans hA.2)⟩) + +instance : PartialOrder (TensorClass K) where + le := (· ≤ ·) + le_refl := by + intro A + induction A using Quotient.inductionOn with | h a => + exact TensorRep.Restricts.refl a + le_trans := by + intro A B C + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + induction C using Quotient.inductionOn with | h C => + exact fun hAB hBC => TensorRep.Restricts.trans hBC hAB + le_antisymm := by + intro A B + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + exact fun hAB hBA => Quotient.sound ⟨hBA, hAB⟩ + +theorem ofTensor_le {X Y Z U V W : Type*} + [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] [Fintype W] + {T : Tensor K X Y Z} {S : Tensor K U V W} + (h : CoefficientTensor.Restricts T S) : ofTensor S ≤ ofTensor T := + TensorRep.Restricts.ofTensor h + +end TensorClass +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassCharacter.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassCharacter.lean new file mode 100644 index 0000000000..dfe5892bf5 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassCharacter.lean @@ -0,0 +1,44 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassSemiring +public import Mathlib.Basic.NNReal.Defs + +/-! +# Characters on tensor classes + +Characters take values in the nonnegative reals and preserve order and the semiring operations. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +variable {K : Type*} [CommSemiring K] + +/-- A semiring homomorphism to nonnegative reals that preserves the local restriction order. -/ +structure Character (K : Type*) [CommSemiring K] where + /-- The underlying semiring homomorphism. -/ + toHom : (TensorClass K) →+* ℝ≥0 + monotone' : Monotone toHom + +noncomputable instance : CoeFun (Character K) (fun _ => TensorClass K → ℝ≥0) := ⟨fun f => f.toHom⟩ + +@[simp] theorem Character.map_zero (f : (Character K)) : f 0 = 0 := f.toHom.map_zero +@[simp] theorem Character.map_one (f : (Character K)) : f 1 = 1 := f.toHom.map_one +@[simp] theorem Character.map_add (f : (Character K)) (A B : (TensorClass K)) : + f (A + B) = f A + f B := f.toHom.map_add A B +@[simp] theorem Character.map_mul (f : (Character K)) (A B : (TensorClass K)) : + f (A * B) = f A * f B := f.toHom.map_mul A B + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassDirectSum.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassDirectSum.lean new file mode 100644 index 0000000000..9bceaa014f --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassDirectSum.lean @@ -0,0 +1,79 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRankOrder + +/-! +# Character values of full direct sums + +Every summand has independent coordinates on all three legs. This file does +not apply additivity to a tensor whose first leg is shared. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +variable {K : Type*} [CommSemiring K] + +private def headTailProduct (n : ℕ) (X : Type*) : + (Fin (n + 1) × X) ≃ X ⊕ (Fin n × X) where + toFun p := Fin.cases (Sum.inl p.2) (fun i => Sum.inr (i, p.2)) p.1 + invFun + | .inl x => (0, x) + | .inr p => (p.1.succ, p.2) + left_inv p := by + rcases p with ⟨i, x⟩ + refine Fin.cases ?_ (fun j => ?_) i <;> rfl + right_inv p := by + rcases p with x | ⟨i, x⟩ <;> rfl + +theorem ofTensor_directSum_fin {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (n : ℕ) + (A : Fin n → Tensor K X Y Z) : + ofTensor (Tensor.directSum A) = ∑ i, ofTensor (A i) := by + classical + induction n with + | zero => + have hzero : Tensor.directSum A = 0 := by + funext x + exact Fin.elim0 x.1 + rw [hzero, ofTensor_zero] + simp + | succ n ih => + rw [Fin.sum_univ_succ, ← ih (fun i => A i.succ), ofTensor_add] + have heq : Tensor.pullback (headTailProduct n X) (headTailProduct n Y) + (headTailProduct n Z) + (Tensor.blockSum (A 0) (Tensor.directSum (fun i => A i.succ))) = + Tensor.directSum A := by + funext x y z + rcases x with ⟨i, x⟩ + rcases y with ⟨j, y⟩ + rcases z with ⟨k, z⟩ + refine Fin.cases ?_ (fun i => ?_) i <;> + refine Fin.cases ?_ (fun j => ?_) j <;> + refine Fin.cases ?_ (fun k => ?_) k <;> + simp [Tensor.pullback, headTailProduct, Tensor.blockSum, + Tensor.directSum, eq_comm] + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem Character.map_directSum_fin (f : Character K) {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (n : ℕ) + (A : Fin n → Tensor K X Y Z) : + f (ofTensor (Tensor.directSum A)) = ∑ i, f (ofTensor (A i)) := by + rw [ofTensor_directSum_fin] + exact map_sum f.toHom _ _ + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassDots.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassDots.lean new file mode 100644 index 0000000000..33ecfa671a --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassDots.lean @@ -0,0 +1,389 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRankOrder + +/-! +# The three auxiliary pairings as actual tensor classes + +The singleton leg is named in each pairing. Dimension comparisons select +coordinates, multiplication pairs coordinates, and the product of the three +orientations is the square matrix multiplication tensor. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +variable {K : Type*} [CommSemiring K] +namespace CoefficientTensor + +/-- Evaluates `if y = z then 1 else 0` at the input `_ y z`. -/ +def dotXCoeff (n : ℕ) : Tensor K Unit (Fin n) (Fin n) := + fun _ y z => if y = z then 1 else 0 + +/-- Evaluates `if x = z then 1 else 0` at the input `x _ z`. -/ +def dotYCoeff (n : ℕ) : Tensor K (Fin n) Unit (Fin n) := + fun x _ z => if x = z then 1 else 0 + +/-- Evaluates `if x = y then 1 else 0` at the input `x y _`. -/ +def dotZCoeff (n : ℕ) : Tensor K (Fin n) (Fin n) Unit := + fun x y _ => if x = y then 1 else 0 + +theorem dotX_restricts_of_le {m n : ℕ} (h : m ≤ n) : + Restricts (dotXCoeff (K := K) n) (dotXCoeff m) := by + have hp := Restricts.pullback (dotXCoeff (K := K) n) id (Fin.castLE h) (Fin.castLE h) + have heq : Tensor.pullback id (Fin.castLE h) (Fin.castLE h) (dotXCoeff (K := K) n) = + dotXCoeff m := by + funext x y z + simp [Tensor.pullback, dotXCoeff, Fin.ext_iff] + rwa [heq] at hp + +theorem dotY_restricts_of_le {m n : ℕ} (h : m ≤ n) : + Restricts (dotYCoeff (K := K) n) (dotYCoeff m) := by + have hp := Restricts.pullback (dotYCoeff (K := K) n) (Fin.castLE h) id (Fin.castLE h) + have heq : Tensor.pullback (Fin.castLE h) id (Fin.castLE h) (dotYCoeff (K := K) n) = + dotYCoeff m := by + funext x y z + simp [Tensor.pullback, dotYCoeff, Fin.ext_iff] + rwa [heq] at hp + +theorem dotZ_restricts_of_le {m n : ℕ} (h : m ≤ n) : + Restricts (dotZCoeff (K := K) n) (dotZCoeff m) := by + have hp := Restricts.pullback (dotZCoeff (K := K) n) (Fin.castLE h) (Fin.castLE h) id + have heq : Tensor.pullback (Fin.castLE h) (Fin.castLE h) id (dotZCoeff (K := K) n) = + dotZCoeff m := by + funext x y z + simp [Tensor.pullback, dotZCoeff, Fin.ext_iff] + rwa [heq] at hp + +theorem dotX_rankAtMost (n : ℕ) : Tensor.RankAtMost (dotXCoeff (K := K) n) n := by + refine ⟨fun _ _ => 1, fun i y => if i = y then 1 else 0, + fun i z => if i = z then 1 else 0, ?_⟩ + funext x y z + simp [dotXCoeff, Tensor.rankOne, mul_ite, eq_comm] + +theorem dotY_rankAtMost (n : ℕ) : Tensor.RankAtMost (dotYCoeff (K := K) n) n := by + refine ⟨fun i x => if i = x then 1 else 0, fun _ _ => 1, + fun i z => if i = z then 1 else 0, ?_⟩ + funext x y z + simp [dotYCoeff, Tensor.rankOne, mul_ite, eq_comm] + +theorem dotZ_rankAtMost (n : ℕ) : Tensor.RankAtMost (dotZCoeff (K := K) n) n := by + refine ⟨fun i x => if i = x then 1 else 0, + fun i y => if i = y then 1 else 0, fun _ _ => 1, ?_⟩ + funext x y z + simp [dotZCoeff, Tensor.rankOne, mul_ite, eq_comm] + +/-- Reindexes `(Unit × Unit)` and `Unit where toFun _` by an equivalence. -/ +def dotUnitProduct : (Unit × Unit) ≃ Unit where + toFun _ := () + invFun _ := ((), ()) + left_inv x := by rcases x with ⟨⟨⟩, ⟨⟩⟩; rfl + right_inv x := by cases x; rfl + +theorem dotX_product_pullback (m n : ℕ) : + Tensor.pullback dotUnitProduct + (finProdFinEquiv : Fin m × Fin n ≃ Fin (m * n)) finProdFinEquiv + (dotXCoeff (K := K) (m * n)) = Tensor.product (dotXCoeff m) (dotXCoeff n) := by + funext x y z + rcases y with ⟨y₁, y₂⟩ + rcases z with ⟨z₁, z₂⟩ + by_cases h₁ : y₁ = z₁ <;> by_cases h₂ : y₂ = z₂ <;> + simp [Tensor.pullback, dotXCoeff, Tensor.product, Prod.mk.injEq, h₁, h₂] + +theorem dotY_product_pullback (m n : ℕ) : + Tensor.pullback (finProdFinEquiv : Fin m × Fin n ≃ Fin (m * n)) + dotUnitProduct finProdFinEquiv (dotYCoeff (K := K) (m * n)) = + Tensor.product (dotYCoeff m) (dotYCoeff n) := by + funext x y z + rcases x with ⟨x₁, x₂⟩ + rcases z with ⟨z₁, z₂⟩ + by_cases h₁ : x₁ = z₁ <;> by_cases h₂ : x₂ = z₂ <;> + simp [Tensor.pullback, dotYCoeff, Tensor.product, Prod.mk.injEq, h₁, h₂] + +theorem dotZ_product_pullback (m n : ℕ) : + Tensor.pullback (finProdFinEquiv : Fin m × Fin n ≃ Fin (m * n)) + finProdFinEquiv dotUnitProduct (dotZCoeff (K := K) (m * n)) = + Tensor.product (dotZCoeff m) (dotZCoeff n) := by + funext x y z + rcases x with ⟨x₁, x₂⟩ + rcases y with ⟨y₁, y₂⟩ + by_cases h₁ : x₁ = y₁ <;> by_cases h₂ : x₂ = y₂ <;> + simp [Tensor.pullback, dotZCoeff, Tensor.product, Prod.mk.injEq, h₁, h₂] + +/-- The two nonsingleton coordinates on the first leg become row and column. -/ +def dotTripleX (n : ℕ) : ((Unit × Fin n) × Fin n) ≃ (Fin n × Fin n) where + toFun x := (x.1.2, x.2) + invFun x := (((), x.1), x.2) + left_inv x := by rcases x with ⟨⟨⟨⟩, i⟩, j⟩; rfl + right_inv x := by cases x; rfl + +/-- The middle leg pairs the second index with the third. -/ +def dotTripleY (n : ℕ) : ((Fin n × Unit) × Fin n) ≃ (Fin n × Fin n) where + toFun y := (y.2, y.1.1) + invFun y := ((y.2, ()), y.1) + left_inv y := by rcases y with ⟨⟨i, ⟨⟩⟩, j⟩; rfl + right_inv y := by cases y; rfl + +/-- The final leg pairs the third index with the first. -/ +def dotTripleZ (n : ℕ) : ((Fin n × Fin n) × Unit) ≃ (Fin n × Fin n) where + toFun z := z.1 + invFun z := (z, ()) + left_inv z := by rcases z with ⟨⟨i, j⟩, ⟨⟩⟩; rfl + right_inv z := rfl + +theorem dotTriple_pullback (n : ℕ) : + Tensor.pullback (dotTripleX n) (dotTripleY n) (dotTripleZ n) + (squareMatrixTensor (K := K) n) = + Tensor.product (Tensor.product (dotXCoeff n) (dotYCoeff n)) (dotZCoeff n) := by + funext x y z + by_cases hx : x.1.2 = z.1.2 <;> + by_cases hy : y.1.1 = z.1.1 <;> + by_cases hz : x.2 = y.2 <;> + simp [Tensor.pullback, Tensor.matrixCoefficients, Tensor.product, + dotTripleX, dotTripleY, dotTripleZ, dotXCoeff, dotYCoeff, dotZCoeff, + hx, hy, hz, eq_comm] + +end CoefficientTensor + +namespace TensorClass + +/-- The tensor class of multiplying two square matrices. -/ +noncomputable def square (n : ℕ) : TensorClass K := + ofTensor (CoefficientTensor.squareMatrixTensor n) + +theorem square_mul (n m : ℕ) : square (K := K) n * square m = square (n * m) := by + unfold square + rw [ofTensor_mul, ← CoefficientTensor.square_product_pullback] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem square_mono {n m : ℕ} (h : n ≤ m) : square (K := K) n ≤ square m := + ofTensor_le (CoefficientTensor.square_restricts_of_le h) + +@[simp] theorem square_one : square (K := K) 1 = 1 := by + let e : (Fin 1 × Fin 1) ≃ PUnit := + { toFun := fun _ => PUnit.unit + invFun := fun _ => (0, 0) + left_inv := fun _ => Subsingleton.elim _ _ + right_inv := fun _ => Subsingleton.elim _ _ } + have heq : Tensor.pullback e e e unitTensor = + CoefficientTensor.squareMatrixTensor (K := K) 1 := by + funext x y z + have h₁ : x.2 = y.1 := Subsingleton.elim _ _ + have h₂ : y.2 = z.1 := Subsingleton.elim _ _ + have h₃ : z.2 = x.1 := Subsingleton.elim _ _ + simp [Tensor.pullback, unitTensor, CoefficientTensor.squareMatrixTensor, + Tensor.matrixCoefficients, h₁, h₂, h₃] + change ofTensor (CoefficientTensor.squareMatrixTensor (K := K) 1) = ofTensor unitTensor + rw [← heq] + exact ofTensor_pullback_equiv _ e e e + +theorem square_pow (n j : ℕ) : square (K := K) (n ^ j) = square n ^ j := by + induction j with + | zero => simp + | succ j ih => rw [pow_succ, ← square_mul, ih, pow_succ] + +/-- The rank here is the least size of an actual rank-one decomposition. -/ +theorem rank_square_le (n : ℕ) : rank (square (K := K) n) ≤ n ^ 3 := by + rw [square, rank_ofTensor] + exact (CoefficientTensor.rank_le_iff _ _).mpr + (CoefficientTensor.square_rankAtMost_cubic n) + +/-- Computes the dot x by the application `ofTensor (CoefficientTensor.dotXCoeff n)`. -/ +noncomputable def dotX (n : ℕ) : TensorClass K := ofTensor (CoefficientTensor.dotXCoeff n) +/-- Computes the dot y by the application `ofTensor (CoefficientTensor.dotYCoeff n)`. -/ +noncomputable def dotY (n : ℕ) : TensorClass K := ofTensor (CoefficientTensor.dotYCoeff n) +/-- Computes the dot z by the application `ofTensor (CoefficientTensor.dotZCoeff n)`. -/ +noncomputable def dotZ (n : ℕ) : TensorClass K := ofTensor (CoefficientTensor.dotZCoeff n) + +theorem dotX_mono {m n : ℕ} (h : m ≤ n) : dotX (K := K) m ≤ dotX n := + ofTensor_le (CoefficientTensor.dotX_restricts_of_le h) + +theorem dotY_mono {m n : ℕ} (h : m ≤ n) : dotY (K := K) m ≤ dotY n := + ofTensor_le (CoefficientTensor.dotY_restricts_of_le h) + +theorem dotZ_mono {m n : ℕ} (h : m ≤ n) : dotZ (K := K) m ≤ dotZ n := + ofTensor_le (CoefficientTensor.dotZ_restricts_of_le h) + +theorem rank_dotX_le (n : ℕ) : rank (dotX (K := K) n) ≤ n := by + rw [dotX, rank_ofTensor] + exact (CoefficientTensor.rank_le_iff _ _).mpr (CoefficientTensor.dotX_rankAtMost n) + +theorem rank_dotY_le (n : ℕ) : rank (dotY (K := K) n) ≤ n := by + rw [dotY, rank_ofTensor] + exact (CoefficientTensor.rank_le_iff _ _).mpr (CoefficientTensor.dotY_rankAtMost n) + +theorem rank_dotZ_le (n : ℕ) : rank (dotZ (K := K) n) ≤ n := by + rw [dotZ, rank_ofTensor] + exact (CoefficientTensor.rank_le_iff _ _).mpr (CoefficientTensor.dotZ_rankAtMost n) + +theorem dotX_mul (m n : ℕ) : dotX (K := K) m * dotX n = dotX (m * n) := by + unfold dotX + rw [ofTensor_mul, ← CoefficientTensor.dotX_product_pullback] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem dotY_mul (m n : ℕ) : dotY (K := K) m * dotY n = dotY (m * n) := by + unfold dotY + rw [ofTensor_mul, ← CoefficientTensor.dotY_product_pullback] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem dotZ_mul (m n : ℕ) : dotZ (K := K) m * dotZ n = dotZ (m * n) := by + unfold dotZ + rw [ofTensor_mul, ← CoefficientTensor.dotZ_product_pullback] + exact ofTensor_pullback_equiv _ _ _ _ + +@[simp] theorem dotX_one : dotX (K := K) 1 = 1 := by + let u : Unit ≃ PUnit := Equiv.ofUnique _ _ + let e : Fin 1 ≃ PUnit := Equiv.ofUnique _ _ + have heq : Tensor.pullback u e e unitTensor = CoefficientTensor.dotXCoeff (K := K) 1 := by + funext x y z + simp [Tensor.pullback, TensorClass.unitTensor, + CoefficientTensor.dotXCoeff, Subsingleton.elim y z] + change ofTensor (CoefficientTensor.dotXCoeff 1) = ofTensor unitTensor + rw [← heq] + exact ofTensor_pullback_equiv _ u e e + +@[simp] theorem dotY_one : dotY (K := K) 1 = 1 := by + let u : Unit ≃ PUnit := Equiv.ofUnique _ _ + let e : Fin 1 ≃ PUnit := Equiv.ofUnique _ _ + have heq : Tensor.pullback e u e unitTensor = CoefficientTensor.dotYCoeff (K := K) 1 := by + funext x y z + simp [Tensor.pullback, TensorClass.unitTensor, + CoefficientTensor.dotYCoeff, Subsingleton.elim x z] + change ofTensor (CoefficientTensor.dotYCoeff 1) = ofTensor unitTensor + rw [← heq] + exact ofTensor_pullback_equiv _ e u e + +@[simp] theorem dotZ_one : dotZ (K := K) 1 = 1 := by + let u : Unit ≃ PUnit := Equiv.ofUnique _ _ + let e : Fin 1 ≃ PUnit := Equiv.ofUnique _ _ + have heq : Tensor.pullback e e u unitTensor = CoefficientTensor.dotZCoeff (K := K) 1 := by + funext x y z + simp [Tensor.pullback, TensorClass.unitTensor, + CoefficientTensor.dotZCoeff, Subsingleton.elim x y] + change ofTensor (CoefficientTensor.dotZCoeff 1) = ofTensor unitTensor + rw [← heq] + exact ofTensor_pullback_equiv _ e e u + +theorem one_le_dotX {n : ℕ} (hn : 0 < n) : 1 ≤ dotX (K := K) n := by + simpa only [dotX_one] using dotX_mono (Nat.succ_le_iff.mpr hn) + +theorem one_le_dotY {n : ℕ} (hn : 0 < n) : 1 ≤ dotY (K := K) n := by + simpa only [dotY_one] using dotY_mono (Nat.succ_le_iff.mpr hn) + +theorem one_le_dotZ {n : ℕ} (hn : 0 < n) : 1 ≤ dotZ (K := K) n := by + simpa only [dotZ_one] using dotZ_mono (Nat.succ_le_iff.mpr hn) + +theorem dotX_mul_dotY_mul_dotZ (n : ℕ) : dotX (K := K) n * dotY n * dotZ n = square n := by + unfold dotX dotY dotZ square + rw [ofTensor_mul, ofTensor_mul, ← CoefficientTensor.dotTriple_pullback] + exact ofTensor_pullback_equiv _ _ _ _ + +namespace Character + +theorem dotX_le (f : Character K) (n : ℕ) : f (dotX n) ≤ n := + (f.le_rank _).trans (Nat.cast_le.mpr (rank_dotX_le n)) + +theorem dotY_le (f : Character K) (n : ℕ) : f (dotY n) ≤ n := + (f.le_rank _).trans (Nat.cast_le.mpr (rank_dotY_le n)) + +theorem dotZ_le (f : Character K) (n : ℕ) : f (dotZ n) ≤ n := + (f.le_rank _).trans (Nat.cast_le.mpr (rank_dotZ_le n)) + +theorem one_le_dotX (f : Character K) {n : ℕ} (hn : 0 < n) : 1 ≤ f (dotX n) := by + simpa only [map_one] using f.monotone' (TensorClass.one_le_dotX hn) + +theorem one_le_dotY (f : Character K) {n : ℕ} (hn : 0 < n) : 1 ≤ f (dotY n) := by + simpa only [map_one] using f.monotone' (TensorClass.one_le_dotY hn) + +theorem one_le_dotZ (f : Character K) {n : ℕ} (hn : 0 < n) : 1 ≤ f (dotZ n) := by + simpa only [map_one] using f.monotone' (TensorClass.one_le_dotZ hn) + +/-- Computes the dot xvalue by the application `f (dotX n)`. -/ +noncomputable def dotXValue (f : Character K) (n : ℕ) : ℝ := f (dotX n) +/-- Computes the dot yvalue by the application `f (dotY n)`. -/ +noncomputable def dotYValue (f : Character K) (n : ℕ) : ℝ := f (dotY n) +/-- Computes the dot zvalue by the application `f (dotZ n)`. -/ +noncomputable def dotZValue (f : Character K) (n : ℕ) : ℝ := f (dotZ n) + +theorem dotXValue_nonneg (f : Character K) (n : ℕ) : 0 ≤ f.dotXValue n := + (f (dotX n)).coe_nonneg + +theorem dotYValue_nonneg (f : Character K) (n : ℕ) : 0 ≤ f.dotYValue n := + (f (dotY n)).coe_nonneg + +theorem dotZValue_nonneg (f : Character K) (n : ℕ) : 0 ≤ f.dotZValue n := + (f (dotZ n)).coe_nonneg + +theorem dotXValue_le (f : Character K) (n : ℕ) : f.dotXValue n ≤ n := by + exact_mod_cast f.dotX_le n + +theorem dotYValue_le (f : Character K) (n : ℕ) : f.dotYValue n ≤ n := by + exact_mod_cast f.dotY_le n + +theorem dotZValue_le (f : Character K) (n : ℕ) : f.dotZValue n ≤ n := by + exact_mod_cast f.dotZ_le n + +theorem one_le_dotXValue (f : Character K) {n : ℕ} (hn : 0 < n) : 1 ≤ f.dotXValue n := by + exact_mod_cast f.one_le_dotX hn + +theorem one_le_dotYValue (f : Character K) {n : ℕ} (hn : 0 < n) : 1 ≤ f.dotYValue n := by + exact_mod_cast f.one_le_dotY hn + +theorem one_le_dotZValue (f : Character K) {n : ℕ} (hn : 0 < n) : 1 ≤ f.dotZValue n := by + exact_mod_cast f.one_le_dotZ hn + +theorem dotXValue_mono (f : Character K) : Monotone f.dotXValue := by + intro m n h + exact_mod_cast f.monotone' (TensorClass.dotX_mono h) + +theorem dotYValue_mono (f : Character K) : Monotone f.dotYValue := by + intro m n h + exact_mod_cast f.monotone' (TensorClass.dotY_mono h) + +theorem dotZValue_mono (f : Character K) : Monotone f.dotZValue := by + intro m n h + exact_mod_cast f.monotone' (TensorClass.dotZ_mono h) + +theorem dotXValue_mul (f : Character K) (m n : ℕ) : + f.dotXValue (m * n) = f.dotXValue m * f.dotXValue n := by + simp only [dotXValue, ← dotX_mul, map_mul, NNReal.coe_mul] + +theorem dotYValue_mul (f : Character K) (m n : ℕ) : + f.dotYValue (m * n) = f.dotYValue m * f.dotYValue n := by + simp only [dotYValue, ← dotY_mul, map_mul, NNReal.coe_mul] + +theorem dotZValue_mul (f : Character K) (m n : ℕ) : + f.dotZValue (m * n) = f.dotZValue m * f.dotZValue n := by + simp only [dotZValue, ← dotZ_mul, map_mul, NNReal.coe_mul] + +@[simp] theorem dotXValue_one (f : Character K) : f.dotXValue 1 = 1 := by + simp [dotXValue] + +@[simp] theorem dotYValue_one (f : Character K) : f.dotYValue 1 = 1 := by + simp [dotYValue] + +@[simp] theorem dotZValue_one (f : Character K) : f.dotZValue 1 = 1 := by + simp [dotZValue] + +theorem dotValues_product (f : Character K) (n : ℕ) : + f.dotXValue n * f.dotYValue n * f.dotZValue n = f (square n) := by + simp only [dotXValue, dotYValue, dotZValue, ← NNReal.coe_mul, ← map_mul, + dotX_mul_dotY_mul_dotZ] + +end Character + +end TensorClass +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassPermutations.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassPermutations.lean new file mode 100644 index 0000000000..d96a51461e --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassPermutations.lean @@ -0,0 +1,380 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassDots +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors +public import Mathlib.Data.Fin.VecNotation +public import Mathlib.Data.Multiset.AddSub +public import Mathlib.Tactic.FinCases + +/-! +# Permuting the three actual tensor legs + +The two adjacent swaps act on coefficient arrays and on their actual local +restriction witnesses. Their quotient actions preserve the semiring operations. +The six induced characters therefore remain normalized restriction-monotone +characters; their six values form a multiset invariant under either swap. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +variable {K : Type*} [CommSemiring K] + +open PolynomialTensors (polynomialTensor) +namespace CoefficientTensor + +variable {X Y Z U V W : Type*} + +/-- Evaluates `T x y z` at the input `y x z`. -/ +def swapXY (T : Tensor K X Y Z) : Tensor K Y X Z := fun y x z => T x y z +/-- Evaluates `T x y z` at the input `x z y`. -/ +def swapYZ (T : Tensor K X Y Z) : Tensor K X Z Y := fun x z y => T x y z + +theorem Restricts.swapXY [Fintype X] [Fintype Y] [Fintype Z] + {T : Tensor K X Y Z} {S : Tensor K U V W} (h : Restricts T S) : + Restricts (swapXY T) (swapXY S) := by + rcases h with ⟨a, b, c, rfl⟩ + refine ⟨b, a, c, ?_⟩ + funext y x z + simp only [CoefficientTensor.swapXY, Tensor.restrict] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro j hj + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro k hk + ring + +theorem Restricts.swapYZ [Fintype X] [Fintype Y] [Fintype Z] + {T : Tensor K X Y Z} {S : Tensor K U V W} (h : Restricts T S) : + Restricts (swapYZ T) (swapYZ S) := by + rcases h with ⟨a, b, c, rfl⟩ + refine ⟨a, c, b, ?_⟩ + funext x z y + simp only [CoefficientTensor.swapYZ, Tensor.restrict] + apply Finset.sum_congr rfl + intro i hi + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro k hk + apply Finset.sum_congr rfl + intro j hj + ring + +theorem swapXY_blockSum (T : Tensor K X Y Z) (S : Tensor K U V W) : + swapXY (blockSum T S) = blockSum (swapXY T) (swapXY S) := by + funext x y z + rcases x with x | x <;> rcases y with y | y <;> rcases z with z | z <;> rfl + +theorem swapYZ_blockSum (T : Tensor K X Y Z) (S : Tensor K U V W) : + swapYZ (blockSum T S) = blockSum (swapYZ T) (swapYZ S) := by + funext x y z + rcases x with x | x <;> rcases y with y | y <;> rcases z with z | z <;> rfl + +theorem swapXY_product (T : Tensor K X Y Z) (S : Tensor K U V W) : + swapXY (Tensor.product T S) = Tensor.product (swapXY T) (swapXY S) := rfl + +theorem swapYZ_product (T : Tensor K X Y Z) (S : Tensor K U V W) : + swapYZ (Tensor.product T S) = Tensor.product (swapYZ T) (swapYZ S) := rfl + +end CoefficientTensor + +namespace TensorRep + +/-- Builds `TensorRep where xDim` with the specified `xDim`, `yDim`, `zDim`, `coeff`. -/ +def swapXY (T : TensorRep K) : TensorRep K where + xDim := T.yDim + yDim := T.xDim + zDim := T.zDim + coeff := CoefficientTensor.swapXY T.coeff + +/-- Builds `TensorRep where xDim` with the specified `xDim`, `yDim`, `zDim`, `coeff`. -/ +def swapYZ (T : TensorRep K) : TensorRep K where + xDim := T.xDim + yDim := T.zDim + zDim := T.yDim + coeff := CoefficientTensor.swapYZ T.coeff + +theorem Restricts.swapXY {T S : (TensorRep K)} (h : Restricts T S) : + Restricts (swapXY T) (swapXY S) := CoefficientTensor.Restricts.swapXY h + +theorem Restricts.swapYZ {T S : (TensorRep K)} (h : Restricts T S) : + Restricts (swapYZ T) (swapYZ S) := CoefficientTensor.Restricts.swapYZ h + +end TensorRep + +namespace TensorClass + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def swapXY : TensorClass K → (TensorClass K) := + Quotient.map TensorRep.swapXY (fun _ _ h => + ⟨TensorRep.Restricts.swapXY h.1, TensorRep.Restricts.swapXY h.2⟩) + +/-- Applies the operation on representatives under the induced quotient relation. -/ +def swapYZ : TensorClass K → (TensorClass K) := + Quotient.map TensorRep.swapYZ (fun _ _ h => + ⟨TensorRep.Restricts.swapYZ h.1, TensorRep.Restricts.swapYZ h.2⟩) + +@[simp] theorem swapXY_ofTensor {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (T : Tensor K X Y Z) : + swapXY (ofTensor T) = ofTensor (CoefficientTensor.swapXY T) := rfl + +@[simp] theorem swapYZ_ofTensor {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (T : Tensor K X Y Z) : + swapYZ (ofTensor T) = ofTensor (CoefficientTensor.swapYZ T) := rfl + +@[simp] theorem swapXY_swapXY (T : TensorClass K) : swapXY (swapXY T) = T := by + induction T using Quotient.inductionOn with | h T => rfl + +@[simp] theorem swapYZ_swapYZ (T : TensorClass K) : swapYZ (swapYZ T) = T := by + induction T using Quotient.inductionOn with | h T => rfl + +theorem swap_braid (T : TensorClass K) : + swapXY (swapYZ (swapXY T)) = swapYZ (swapXY (swapYZ T)) := by + induction T using Quotient.inductionOn with | h T => rfl + +theorem swapXY_mono : Monotone (swapXY (K := K)) := by + intro A B h + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + exact TensorRep.Restricts.swapXY h + +theorem swapYZ_mono : Monotone (swapYZ (K := K)) := by + intro A B h + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + exact TensorRep.Restricts.swapYZ h + +@[simp] theorem swapXY_zero : swapXY (0 : TensorClass K) = 0 := by + change swapXY (ofTensor emptyTensor) = ofTensor emptyTensor + rw [swapXY_ofTensor] + congr 1 + funext x + exact x.elim + +@[simp] theorem swapYZ_zero : swapYZ (0 : TensorClass K) = 0 := by + change swapYZ (ofTensor emptyTensor) = ofTensor emptyTensor + rw [swapYZ_ofTensor] + congr 1 + funext x + exact x.elim + +@[simp] theorem swapXY_one : swapXY (1 : TensorClass K) = 1 := rfl +@[simp] theorem swapYZ_one : swapYZ (1 : TensorClass K) = 1 := rfl + +@[simp] theorem swapXY_add (A B : TensorClass K) : swapXY (A + B) = swapXY A + swapXY B := by + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + change swapXY (ofRep A + ofRep B) = swapXY (ofRep A) + swapXY (ofRep B) + rw [← ofTensor_coeff A, ← ofTensor_coeff B] + simp only [ofTensor_add, swapXY_ofTensor, CoefficientTensor.swapXY_blockSum] + +@[simp] theorem swapYZ_add (A B : TensorClass K) : swapYZ (A + B) = swapYZ A + swapYZ B := by + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + change swapYZ (ofRep A + ofRep B) = swapYZ (ofRep A) + swapYZ (ofRep B) + rw [← ofTensor_coeff A, ← ofTensor_coeff B] + simp only [ofTensor_add, swapYZ_ofTensor, CoefficientTensor.swapYZ_blockSum] + +@[simp] theorem swapXY_mul (A B : TensorClass K) : swapXY (A * B) = swapXY A * swapXY B := by + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + change swapXY (ofRep A * ofRep B) = swapXY (ofRep A) * swapXY (ofRep B) + rw [← ofTensor_coeff A, ← ofTensor_coeff B] + simp only [ofTensor_mul, swapXY_ofTensor, CoefficientTensor.swapXY_product] + +@[simp] theorem swapYZ_mul (A B : TensorClass K) : swapYZ (A * B) = swapYZ A * swapYZ B := by + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + change swapYZ (ofRep A * ofRep B) = swapYZ (ofRep A) * swapYZ (ofRep B) + rw [← ofTensor_coeff A, ← ofTensor_coeff B] + simp only [ofTensor_mul, swapYZ_ofTensor, CoefficientTensor.swapYZ_product] + +/-- Builds `TensorClass →+* (TensorClass K) where toFun` with the specified `toFun`, `map_zero'`, +`map_one'`, `map_add'`. -/ +def swapXYHom : TensorClass K →+* (TensorClass K) where + toFun := swapXY + map_zero' := swapXY_zero + map_one' := swapXY_one + map_add' := swapXY_add + map_mul' := swapXY_mul + +/-- Builds `TensorClass →+* (TensorClass K) where toFun` with the specified `toFun`, `map_zero'`, +`map_one'`, `map_add'`. -/ +def swapYZHom : TensorClass K →+* (TensorClass K) where + toFun := swapYZ + map_zero' := swapYZ_zero + map_one' := swapYZ_one + map_add' := swapYZ_add + map_mul' := swapYZ_mul + +/-- All six permutations, in the order `id, XY, YZ, XY·YZ, YZ·XY, XY·YZ·XY`. -/ +def permuteHom : Fin 6 → (TensorClass K) →+* (TensorClass K) := + ![RingHom.id _, swapXYHom, swapYZHom, swapXYHom.comp swapYZHom, + swapYZHom.comp swapXYHom, swapXYHom.comp (swapYZHom.comp swapXYHom)] + +/-- Computes the permute by the application `permuteHom i T`. -/ +def permute (i : Fin 6) (T : TensorClass K) : TensorClass K := permuteHom i T + +theorem permute_mono (i : Fin 6) : Monotone (permute (K := K) i) := by + fin_cases i + · exact monotone_id + · exact swapXY_mono + · exact swapYZ_mono + · exact swapXY_mono.comp swapYZ_mono + · exact swapYZ_mono.comp swapXY_mono + · exact swapXY_mono.comp (swapYZ_mono.comp swapXY_mono) + +/-- Composing an actual tensor character with any of the six leg permutations +again gives a normalized monotone semiring character. -/ +def Character.permuted (f : Character K) (i : Fin 6) : Character K where + toHom := f.toHom.comp (permuteHom i) + monotone' := f.monotone'.comp (permute_mono i) + +@[simp] theorem Character.permuted_apply (f : Character K) (i : Fin 6) (T : TensorClass K) : + f.permuted i T = f (permute i T) := rfl + +/-- Right multiplication of the six leg permutations by the first swap. -/ +def permuteSwapXY : Fin 6 ≃ Fin 6 where + toFun := ![1, 0, 4, 5, 2, 3] + invFun := ![1, 0, 4, 5, 2, 3] + left_inv i := by fin_cases i <;> rfl + right_inv i := by fin_cases i <;> rfl + +/-- Right multiplication of the six leg permutations by the second swap. -/ +def permuteSwapYZ : Fin 6 ≃ Fin 6 where + toFun := ![2, 3, 0, 1, 5, 4] + invFun := ![2, 3, 0, 1, 5, 4] + left_inv i := by fin_cases i <;> rfl + right_inv i := by fin_cases i <;> rfl + +theorem permute_swapXY (i : Fin 6) (T : TensorClass K) : + permute i (swapXY T) = permute (permuteSwapXY i) T := by + fin_cases i <;> + simp [permute, permuteHom, permuteSwapXY, swapXYHom, swapYZHom] + +theorem permute_swapYZ (i : Fin 6) (T : TensorClass K) : + permute i (swapYZ T) = permute (permuteSwapYZ i) T := by + fin_cases i <;> + simp [permute, permuteHom, permuteSwapYZ, swapXYHom, swapYZHom, swap_braid] + +theorem Character.permuted_swapXY (f : Character K) (i : Fin 6) (T : TensorClass K) : + f.permuted i (swapXY T) = f.permuted (permuteSwapXY i) T := by + simp only [Character.permuted_apply, permute_swapXY] + +theorem Character.permuted_swapYZ (f : Character K) (i : Fin 6) (T : TensorClass K) : + f.permuted i (swapYZ T) = f.permuted (permuteSwapYZ i) T := by + simp only [Character.permuted_apply, permute_swapYZ] + +/-- Multiplicities are retained even when different permutations have equal +character values. -/ +def Character.sixValues (f : Character K) (T : TensorClass K) : Multiset ℝ≥0 := + {f T} + {f (swapXY T)} + {f (swapYZ T)} + + {f (swapXY (swapYZ T))} + {f (swapYZ (swapXY T))} + + {f (swapXY (swapYZ (swapXY T)))} + +theorem Character.sixValues_swapXY (f : Character K) (T : TensorClass K) : + f.sixValues (swapXY T) = f.sixValues T := by + simp only [Character.sixValues, swapXY_swapXY] + ac_rfl + +theorem Character.sixValues_swapYZ (f : Character K) (T : TensorClass K) : + f.sixValues (swapYZ T) = f.sixValues T := by + have hfour : swapXY (swapYZ (swapXY (swapYZ T))) = swapYZ (swapXY T) := by + rw [swap_braid, swapYZ_swapYZ] + rw [Character.sixValues, hfour] + simp only [Character.sixValues, swapYZ_swapYZ, ← swap_braid] + ac_rfl + +/-- Swapping the two polynomial inputs is a literal coefficient reindexing. -/ +theorem swapXY_polynomialTensor (a b : ℕ) : + swapXY (ofTensor (polynomialTensor (K := K) a b)) = ofTensor (polynomialTensor b a) := by + rw [swapXY_ofTensor] + let e : Fin (a + b - 1) ≃ Fin (b + a - 1) := finCongr (by omega) + have h : CoefficientTensor.swapXY (polynomialTensor (K := K) a b) = + Tensor.pullback (Equiv.refl _) (Equiv.refl _) e (polynomialTensor b a) := by + funext j i k + simp [CoefficientTensor.swapXY, Tensor.pullback, polynomialTensor, e, Nat.add_comm] + rw [h] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem Character.sixValues_polynomialTensor_swap (f : Character K) (a b : ℕ) : + f.sixValues (ofTensor (polynomialTensor a b)) = + f.sixValues (ofTensor (polynomialTensor b a)) := by + rw [← swapXY_polynomialTensor a b, f.sixValues_swapXY] + +@[simp] theorem swapXY_dotX (n : ℕ) : swapXY (dotX (K := K) n) = dotY n := by + rw [dotX, swapXY_ofTensor] + rfl + +@[simp] theorem swapXY_dotY (n : ℕ) : swapXY (dotY (K := K) n) = dotX n := by + rw [← swapXY_dotX, swapXY_swapXY] + +@[simp] theorem swapXY_dotZ (n : ℕ) : swapXY (dotZ (K := K) n) = dotZ n := by + rw [dotZ, swapXY_ofTensor] + congr 1 + funext x y z + simp [CoefficientTensor.swapXY, CoefficientTensor.dotZCoeff, eq_comm] + +@[simp] theorem swapYZ_dotX (n : ℕ) : swapYZ (dotX (K := K) n) = dotX n := by + rw [dotX, swapYZ_ofTensor] + congr 1 + funext x y z + simp [CoefficientTensor.swapYZ, CoefficientTensor.dotXCoeff, eq_comm] + +@[simp] theorem swapYZ_dotY (n : ℕ) : swapYZ (dotY (K := K) n) = dotZ n := by + rw [dotY, swapYZ_ofTensor] + rfl + +@[simp] theorem swapYZ_dotZ (n : ℕ) : swapYZ (dotZ (K := K) n) = dotY n := by + rw [← swapYZ_dotY, swapYZ_swapYZ] + +@[simp] theorem swapXY_square (n : ℕ) : swapXY (square (K := K) n) = square n := by + rw [← dotX_mul_dotY_mul_dotZ] + simp only [swapXY_mul, swapXY_dotX, swapXY_dotY, swapXY_dotZ] + ac_rfl + +@[simp] theorem swapYZ_square (n : ℕ) : swapYZ (square (K := K) n) = square n := by + rw [← dotX_mul_dotY_mul_dotZ] + simp only [swapYZ_mul, swapYZ_dotX, swapYZ_dotY, swapYZ_dotZ] + ac_rfl + +@[simp] theorem permute_square (i : Fin 6) (n : ℕ) : permute i (square (K := K) n) = square n := by + fin_cases i <;> + simp [permute, permuteHom, swapXYHom, swapYZHom] + +theorem Character.permuted_square (f : Character K) (i : Fin 6) (n : ℕ) : + f.permuted i (square n) = f (square n) := by + rw [Character.permuted_apply, permute_square] + +/-- Each of the three singleton-leg orientations occurs exactly twice among +the first-leg pairings evaluated by the six permuted characters. -/ +theorem Character.permuted_dotX (f : Character K) (i : Fin 6) (n : ℕ) : + f.permuted i (dotX n) = ![f (dotX n), f (dotY n), f (dotX n), + f (dotY n), f (dotZ n), f (dotZ n)] i := by + fin_cases i <;> + simp [Character.permuted_apply, permute, permuteHom, swapXYHom, swapYZHom] + +theorem Character.sixValues_dotX (f : Character K) (n : ℕ) : + f.sixValues (dotX n) = + ({f (dotX n)} + {f (dotY n)} + {f (dotZ n)}) + + ({f (dotX n)} + {f (dotY n)} + {f (dotZ n)}) := by + simp only [Character.sixValues, swapXY_dotX, swapYZ_dotX, swapYZ_dotY, swapXY_dotZ] + ac_rfl + +end TensorClass +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassPowers.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassPowers.lean new file mode 100644 index 0000000000..cc46dc6b6b --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassPowers.lean @@ -0,0 +1,87 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRankOrder + +/-! +# Tensor powers and full repeated direct sums in the quotient + +These bridges preserve the actual coefficient tensors used by interpolation. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +variable {K : Type*} [CommSemiring K] + +private def finSuccFunctions (n : ℕ) (X : Type*) : + (Fin (n + 1) → X) ≃ X × (Fin n → X) where + toFun f := (f 0, fun i => f i.succ) + invFun p := Fin.cases p.1 p.2 + left_inv f := by + funext i + refine Fin.cases ?_ (fun j => ?_) i <;> rfl + right_inv p := by + rcases p with ⟨x, f⟩ + rfl + +theorem ofTensor_power {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor K X Y Z) (n : ℕ) : + ofTensor (Tensor.power T n) = (ofTensor T) ^ n := by + induction n with + | zero => + rw [pow_zero] + change ofTensor (Tensor.power T 0) = ofTensor unitTensor + have heq : Tensor.pullback (Equiv.ofUnique (Fin 0 → X) PUnit) + (Equiv.ofUnique (Fin 0 → Y) PUnit) (Equiv.ofUnique (Fin 0 → Z) PUnit) + unitTensor = Tensor.power T 0 := by + funext x y z + simp [Tensor.pullback, Tensor.power, unitTensor] + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + | succ n ih => + rw [pow_succ', ← ih, ofTensor_mul] + have heq : Tensor.pullback (finSuccFunctions n X) (finSuccFunctions n Y) + (finSuccFunctions n Z) (Tensor.product T (Tensor.power T n)) = + Tensor.power T (n + 1) := by + funext x y z + simp [Tensor.pullback, Tensor.product, Tensor.power, finSuccFunctions, + Fin.prod_univ_succ] + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem ofTensor_directSum_const {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor K X Y Z) (n : ℕ) : + ofTensor (Tensor.directSum (fun _ : Fin n => T)) = + (n : (TensorClass K)) * ofTensor T := by + rw [natCast_eq_ofTensor_natTensor, ofTensor_mul] + congr 1 + funext x y z + simp only [Tensor.directSum, Tensor.product, CoefficientTensor.natTensor, Tensor.diagonal] + split_ifs <;> simp + +theorem Character.map_power_tensor (f : (Character K)) {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (T : Tensor K X Y Z) (n : ℕ) : + f (ofTensor (Tensor.power T n)) = (f (ofTensor T)) ^ n := by + rw [ofTensor_power] + exact f.toHom.map_pow _ _ + +theorem Character.map_directSum_const (f : (Character K)) {X Y Z : Type*} + [Fintype X] [Fintype Y] [Fintype Z] (T : Tensor K X Y Z) (n : ℕ) : + f (ofTensor (Tensor.directSum (fun _ : Fin n => T))) = + (n : ℝ≥0) * f (ofTensor T) := by + rw [ofTensor_directSum_const, Character.map_mul, Character.map_natCast] + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassRank.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassRank.lean new file mode 100644 index 0000000000..db9458201d --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassRank.lean @@ -0,0 +1,248 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.SpectralBooks.Tensor +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClass +public import LeanPool.MatrixMultiplicationAllFields.LinearAlgebra.MatrixMultiplication.Tensor.ComplexTensorBatching + +/-! +# Actual finite tensor rank + +The natural tensor is the diagonal coefficient tensor. Its local restrictions +are exactly the tensors admitting the corresponding number of rank-one terms. +Every finite coefficient tensor has such a decomposition, obtained by expanding +its individual coefficients. Exact rank is therefore a genuine minimum. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum + +variable {K : Type*} [CommSemiring K] +namespace CoefficientTensor + +/-- The diagonal tensor with `n` independent scalar products. -/ +def natTensor (n : ℕ) : Tensor K (Fin n) (Fin n) (Fin n) := + Tensor.diagonal (K := K) (Fin n) + +theorem restrict_natTensor {X Y Z : Type*} (n : ℕ) + (a : X → Fin n → K) (b : Y → Fin n → K) (c : Z → Fin n → K) : + Tensor.restrict a b c (natTensor n) = + fun x y z => ∑ i, a x i * b y i * c z i := by + classical + funext x y z + simp [Tensor.restrict, natTensor, Tensor.diagonal, mul_ite, ite_and] + +theorem rankAtMost_natTensor (n : ℕ) : Tensor.RankAtMost (natTensor (K := K) n) n := by + simpa only [natTensor, Fintype.card_fin] using Tensor.diagonal_rankAtMost (K := K) (Fin n) + +/-- This equivalence exposes all three local matrices of the restriction. -/ +theorem rankAtMost_iff_natTensor_restricts {X Y Z : Type*} + (T : Tensor K X Y Z) (n : ℕ) : + Tensor.RankAtMost T n ↔ Restricts (natTensor n) T := by + constructor + · rintro ⟨a, b, c, h⟩ + refine ⟨fun x i => a i x, fun y i => b i y, fun z i => c i z, ?_⟩ + simpa only [restrict_natTensor, Tensor.rankOne] using h + · intro h + exact h.rankAtMost (rankAtMost_natTensor n) + +/-- The diagonal tensor on a sum of dimensions separates into its two blocks +under the actual standard bijection of finite coordinate sets. -/ +theorem natTensor_add_pullback (r s : ℕ) : + Tensor.pullback (finSumFinEquiv : Fin r ⊕ Fin s ≃ Fin (r + s)) + finSumFinEquiv finSumFinEquiv (natTensor (K := K) (r + s)) = + blockSum (natTensor r) (natTensor (K := K) s) := by + funext x y z + simp only [Tensor.pullback, natTensor, Tensor.diagonal, Equiv.apply_eq_iff_eq] + rcases x with x | x <;> rcases y with y | y <;> rcases z with z | z <;> + simp [blockSum, Tensor.diagonal] + +theorem natTensor_add_restricts (r s : ℕ) : + Restricts (natTensor (K := K) (r + s)) (blockSum (natTensor r) (natTensor (K := K) s)) := by + have h := Restricts.pullback (natTensor (K := K) (r + s)) + (finSumFinEquiv : Fin r ⊕ Fin s ≃ Fin (r + s)) finSumFinEquiv finSumFinEquiv + rwa [natTensor_add_pullback] at h + +theorem rankAtMost_blockSum {X Y Z U V W : Type*} + {T : Tensor K X Y Z} {S : Tensor K U V W} {r s : ℕ} + (hT : Tensor.RankAtMost T r) (hS : Tensor.RankAtMost S s) : + Tensor.RankAtMost (blockSum T S) (r + s) := by + apply (rankAtMost_iff_natTensor_restricts (blockSum T S) (r + s)).mpr + exact (natTensor_add_restricts r s).trans + (((rankAtMost_iff_natTensor_restricts T r).mp hT).blockSum + ((rankAtMost_iff_natTensor_restricts S s).mp hS)) + +variable {X Y Z U V W : Type*} + +section Coordinates + +variable [Fintype X] [Fintype Y] [Fintype Z] + +/-- Selecting the first coordinates realizes the usual comparison of diagonal +tensors by actual local coefficient matrices. -/ +theorem natTensor_restricts_of_le {r s : ℕ} (h : r ≤ s) : + Restricts (natTensor (K := K) s) (natTensor r) := by + have hp := Restricts.pullback (natTensor (K := K) s) + (Fin.castLE h) (Fin.castLE h) (Fin.castLE h) + have heq : Tensor.pullback (Fin.castLE h) (Fin.castLE h) (Fin.castLE h) + (natTensor (K := K) s) = natTensor r := by + funext x y z + simp [Tensor.pullback, natTensor, Tensor.diagonal, Fin.ext_iff] + rwa [heq] at hp + +omit [Fintype X] [Fintype Y] [Fintype Z] in +theorem rankAtMost_mono {T : Tensor K X Y Z} {r s : ℕ} + (hT : Tensor.RankAtMost T r) (hrs : r ≤ s) : Tensor.RankAtMost T s := by + apply (rankAtMost_iff_natTensor_restricts T s).mpr + exact (natTensor_restricts_of_le hrs).trans + ((rankAtMost_iff_natTensor_restricts T r).mp hT) + +/-- Select one coefficient and scale the first map to obtain the unit tensor. -/ +theorem scaled_restricts_natTensor_one {T : Tensor K X Y Z} + (x : X) (y : Y) (z : Z) (scale : K) (hscale : scale * T x y z = 1) : + Restricts T (natTensor 1) := by + classical + refine ⟨fun _ i => if i = x then scale else 0, + fun _ j => if j = y then 1 else 0, + fun _ k => if k = z then 1 else 0, ?_⟩ + funext i j k + have hij : i = j := Subsingleton.elim _ _ + have hik : i = k := Subsingleton.elim _ _ + subst j + subst k + simp [Tensor.restrict, natTensor, Tensor.diagonal, ite_mul, mul_ite, hscale] + +theorem unit_restricts_natTensor_one {T : Tensor K X Y Z} (hT : ∃ x y z, T x y z = 1) : + Restricts T (natTensor 1) := by + obtain ⟨x, y, z, hxyz⟩ := hT + exact scaled_restricts_natTensor_one x y z 1 (by rw [one_mul, hxyz]) + +end Coordinates + +section Rank + +variable [Finite X] [Finite Y] + +/-- The least size of an actual rank-one decomposition. -/ +noncomputable def rank (T : Tensor K X Y Z) : ℕ := SpectralBooks.tensorRank T + +theorem rank_spec (T : Tensor K X Y Z) : Tensor.RankAtMost T (rank T) := + SpectralBooks.rankAtMost_tensorRank T + +theorem rank_le_iff (T : Tensor K X Y Z) (n : ℕ) : + rank T ≤ n ↔ Tensor.RankAtMost T n := + ⟨rankAtMost_mono (rank_spec T), SpectralBooks.tensorRank_le_of_rankAtMost⟩ + +end Rank + +theorem rank_mono [Fintype X] [Fintype Y] [Fintype Z] [Finite U] [Finite V] + {T : Tensor K X Y Z} {S : Tensor K U V W} (h : Restricts T S) : + rank S ≤ rank T := + (rank_le_iff S _).mpr (h.rankAtMost (rank_spec T)) + +theorem rank_product_le [Finite X] [Finite Y] [Finite U] [Finite V] + (T : Tensor K X Y Z) (S : Tensor K U V W) : + rank (Tensor.product T S) ≤ rank T * rank S := + (rank_le_iff _ _).mpr ((rank_spec T).product (rank_spec S)) + +theorem rank_blockSum_le [Finite X] [Finite Y] [Finite U] [Finite V] + (T : Tensor K X Y Z) (S : Tensor K U V W) : + rank (blockSum T S) ≤ rank T + rank S := + (rank_le_iff _ _).mpr (rankAtMost_blockSum (rank_spec T) (rank_spec S)) + +theorem rank_eq_zero_iff [Finite X] [Finite Y] (T : Tensor K X Y Z) : rank T = 0 ↔ T = 0 := by + constructor + · intro h + have hr := rank_spec T + rw [h] at hr + rcases hr with ⟨a, b, c, heq⟩ + funext x y z + simpa using congrFun (congrFun (congrFun heq x) y) z + · rintro rfl + exact Nat.eq_zero_of_le_zero + ((rank_le_iff (0 : Tensor K X Y Z) 0).mpr Tensor.rankAtMost_zero) + +end CoefficientTensor + +namespace TensorRep + +/-- Uses `CoefficientTensor.rank T.coeff` as the representation. -/ +noncomputable def rank (T : (TensorRep K)) : ℕ := CoefficientTensor.rank T.coeff + +theorem Restricts.rank_le {A B : (TensorRep K)} (h : Restricts A B) : rank B ≤ rank A := + CoefficientTensor.rank_mono h + +theorem Equivalent.rank_eq {A B : (TensorRep K)} (h : Equivalent A B) : rank A = rank B := + Nat.le_antisymm (Restricts.rank_le h.2) (Restricts.rank_le h.1) + +end TensorRep + +namespace TensorClass + +theorem ofTensor_natTensor_add (r s : ℕ) : + ofTensor (CoefficientTensor.natTensor (K := K) (r + s)) = + ofTensor (Tensor.blockSum + (CoefficientTensor.natTensor r) (CoefficientTensor.natTensor s)) := by + have h := ofTensor_pullback_equiv (CoefficientTensor.natTensor (K := K) (r + s)) + (finSumFinEquiv : Fin r ⊕ Fin s ≃ Fin (r + s)) finSumFinEquiv finSumFinEquiv + rw [CoefficientTensor.natTensor_add_pullback] at h + exact h.symm + +theorem ofTensor_natTensor_one : + ofTensor (CoefficientTensor.natTensor 1) = + ofTensor (fun (_ _ _ : PUnit) => (1 : K)) := by + let e : PUnit ≃ Fin 1 := Equiv.ofUnique _ _ + have h := ofTensor_pullback_equiv (CoefficientTensor.natTensor (K := K) 1) e e e + have heq : Tensor.pullback e e e (CoefficientTensor.natTensor 1) = + fun (_ _ _ : PUnit) => (1 : K) := by + funext x y z + have hxy : x = y := Subsingleton.elim _ _ + have hxz : x = z := Subsingleton.elim _ _ + subst y + subst z + simp [Tensor.pullback, CoefficientTensor.natTensor, Tensor.diagonal] + rw [heq] at h + exact h.symm + +theorem ofTensor_natTensor_zero : + ofTensor (CoefficientTensor.natTensor 0) = + ofTensor (0 : Tensor K Empty Empty Empty) := by + apply ofTensor_eq + · refine ⟨fun _ _ => 0, fun _ _ => 0, fun _ _ => 0, ?_⟩ + funext x + exact Empty.elim x + · refine ⟨fun _ _ => 0, fun _ _ => 0, fun _ _ => 0, ?_⟩ + funext x + exact Fin.elim0 x + +/-- Exact rank is invariant under mutual local restriction. -/ +noncomputable def rank : (TensorClass K) → ℕ := + Quotient.lift TensorRep.rank (fun _ _ h => TensorRep.Equivalent.rank_eq h) + +@[simp] theorem rank_ofRep (T : (TensorRep K)) : rank (ofRep T) = T.rank := rfl + +theorem rank_mono {A B : (TensorClass K)} (h : A ≤ B) : rank A ≤ rank B := by + induction A using Quotient.inductionOn with | h A => + induction B using Quotient.inductionOn with | h B => + exact TensorRep.Restricts.rank_le h + +theorem rank_ofTensor {X Y Z : Type*} (T : Tensor K X Y Z) [Fintype X] [Fintype Y] [Fintype Z] : + rank (ofTensor T) = CoefficientTensor.rank T := by + apply Nat.le_antisymm + · exact CoefficientTensor.rank_mono (TensorRep.restricts_ofTensor T) + · exact CoefficientTensor.rank_mono (TensorRep.ofTensor_restricts T) + +end TensorClass +end MatrixMultiplicationAllFields.TensorSpectrum diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassRankOrder.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassRankOrder.lean new file mode 100644 index 0000000000..8e71d6d815 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassRankOrder.lean @@ -0,0 +1,100 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassRank +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClassCharacter + +/-! +# Rank bounds and the concrete tensor order + +Natural numbers in the quotient semiring are precisely the diagonal tensors. +These lemmas connect ordinary finite decompositions to the order used by states. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +variable {K : Type*} [CommSemiring K] + +open CoefficientTensor (natTensor rankAtMost_iff_natTensor_restricts) + +theorem ofTensor_zero {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] : + ofTensor (0 : Tensor K X Y Z) = 0 := by + change ofTensor (0 : Tensor K X Y Z) = ofTensor emptyTensor + apply ofTensor_eq + · refine ⟨fun x => x.elim, fun y => y.elim, fun z => z.elim, ?_⟩ + funext x + exact x.elim + · refine ⟨fun _ _ => 0, fun _ _ => 0, fun _ _ => 0, ?_⟩ + funext x y z + simp [Tensor.restrict] + +theorem natCast_eq_ofTensor_natTensor (n : ℕ) : + (n : (TensorClass K)) = ofTensor (natTensor n) := by + induction n with + | zero => + rw [Nat.cast_zero, ofTensor_natTensor_zero] + exact ofTensor_zero.symm + | succ n ih => + rw [Nat.cast_succ, ih, ofTensor_natTensor_add n 1, ← ofTensor_add, + ofTensor_natTensor_one] + rfl + +theorem rank_add_le (A B : (TensorClass K)) : rank (A + B) ≤ rank A + rank B := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + change rank (ofRep a + ofRep b) ≤ rank (ofRep a) + rank (ofRep b) + rw [← ofTensor_coeff a, ← ofTensor_coeff b, ofTensor_add] + simp only [rank_ofTensor] + exact CoefficientTensor.rank_blockSum_le _ _ + +theorem rank_mul_le (A B : (TensorClass K)) : rank (A * B) ≤ rank A * rank B := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + change rank (ofRep a * ofRep b) ≤ rank (ofRep a) * rank (ofRep b) + rw [← ofTensor_coeff a, ← ofTensor_coeff b, ofTensor_mul] + simp only [rank_ofTensor] + exact CoefficientTensor.rank_product_le _ _ + +theorem le_rank_natCast (A : (TensorClass K)) : A ≤ (rank A : (TensorClass K)) := by + induction A using Quotient.inductionOn with | h a => + change ofRep a ≤ (rank (ofRep a) : (TensorClass K)) + rw [← ofTensor_coeff a, rank_ofTensor, natCast_eq_ofTensor_natTensor] + exact ofTensor_le ((rankAtMost_iff_natTensor_restricts _ _).mp + (CoefficientTensor.rank_spec a.coeff)) + +theorem rank_eq_zero_iff (A : (TensorClass K)) : rank A = 0 ↔ A = 0 := by + constructor + · intro h + have hle := le_rank_natCast A + rw [h, Nat.cast_zero] at hle + exact le_antisymm hle (zero_le A) + · rintro rfl + change rank (ofTensor (emptyTensor (K := K))) = 0 + rw [rank_ofTensor, CoefficientTensor.rank_eq_zero_iff] + funext x + exact x.elim + +theorem mul_le_rank_mul (z x : (TensorClass K)) : z * x ≤ (rank x : (TensorClass K)) * z := by + rw [mul_comm (rank x : (TensorClass K)) z] + exact mul_mono (le_refl z) (le_rank_natCast x) + +theorem Character.map_natCast (f : (Character K)) (n : ℕ) : f n = n := + _root_.map_natCast f.toHom n + +theorem Character.le_rank (f : (Character K)) (A : (TensorClass K)) : f A ≤ rank A := by + have h := f.monotone' (le_rank_natCast A) + simpa only [Character.map_natCast] using h + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassSemiring.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassSemiring.lean new file mode 100644 index 0000000000..a110a110bc --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/TensorClassSemiring.lean @@ -0,0 +1,229 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.TensorClass + +/-! # The commutative semiring of finite tensor classes -/ + +@[expose] public section + +noncomputable section + +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.TensorClass + +variable {K : Type*} [CommSemiring K] + +noncomputable instance : Add (TensorClass K) where + add A B := Quotient.liftOn₂ A B + (fun a b => ofTensor (blockSum a.coeff b.coeff)) (by + intro a b a' b' ha hb + exact ofTensor_eq (ha.1.blockSum hb.1) (ha.2.blockSum hb.2)) + +noncomputable instance : Mul (TensorClass K) where + mul A B := Quotient.liftOn₂ A B + (fun a b => ofTensor (Tensor.product a.coeff b.coeff)) (by + intro a b a' b' ha hb + exact ofTensor_eq (ha.1.product hb.1) (ha.2.product hb.2)) + +/-- Evaluates `nomatch x` at the input `x`. -/ +def emptyTensor : Tensor K Empty Empty Empty := fun x => nomatch x +/-- Evaluates `1` at the input `_ _ _`. -/ +def unitTensor : Tensor K PUnit.{1} PUnit.{1} PUnit.{1} := fun _ _ _ => 1 + +noncomputable instance : Zero (TensorClass K) := ⟨ofTensor emptyTensor⟩ +noncomputable instance : One (TensorClass K) := ⟨ofTensor unitTensor⟩ + +theorem ofTensor_add {X Y Z U V W : Type*} + [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] [Fintype W] + (T : Tensor K X Y Z) (S : Tensor K U V W) : + ofTensor T + ofTensor S = ofTensor (blockSum T S) := by + apply ofTensor_eq + · exact (TensorRep.ofTensor_restricts T).blockSum (TensorRep.ofTensor_restricts S) + · exact (TensorRep.restricts_ofTensor T).blockSum (TensorRep.restricts_ofTensor S) + +theorem ofTensor_mul {X Y Z U V W : Type*} + [Fintype X] [Fintype Y] [Fintype Z] [Fintype U] [Fintype V] [Fintype W] + (T : Tensor K X Y Z) (S : Tensor K U V W) : + ofTensor T * ofTensor S = ofTensor (Tensor.product T S) := by + apply ofTensor_eq + · exact (TensorRep.ofTensor_restricts T).product (TensorRep.ofTensor_restricts S) + · exact (TensorRep.restricts_ofTensor T).product (TensorRep.restricts_ofTensor S) + +theorem add_comm_aux (A B : (TensorClass K)) : A + B = B + A := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + change ofRep a + ofRep b = ofRep b + ofRep a + rw [← ofTensor_coeff a, ← ofTensor_coeff b, ofTensor_add, ofTensor_add] + have heq : Tensor.pullback (Equiv.sumComm _ _) (Equiv.sumComm _ _) + (Equiv.sumComm _ _) (blockSum b.coeff a.coeff) = blockSum a.coeff b.coeff := by + funext x y z + rcases x with x | x <;> rcases y with y | y <;> rcases z with z | z <;> rfl + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem add_assoc_aux (A B C : (TensorClass K)) : (A + B) + C = A + (B + C) := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + induction C using Quotient.inductionOn with | h c => + change (ofRep a + ofRep b) + ofRep c = ofRep a + (ofRep b + ofRep c) + rw [← ofTensor_coeff a, ← ofTensor_coeff b, ← ofTensor_coeff c] + simp only [ofTensor_add] + have heq : Tensor.pullback (Equiv.sumAssoc _ _ _) (Equiv.sumAssoc _ _ _) + (Equiv.sumAssoc _ _ _) (blockSum a.coeff (blockSum b.coeff c.coeff)) = + blockSum (blockSum a.coeff b.coeff) c.coeff := by + funext x y z + rcases x with (x | x) | x <;> rcases y with (y | y) | y <;> + rcases z with (z | z) | z <;> rfl + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem zero_add_aux (A : (TensorClass K)) : 0 + A = A := by + induction A using Quotient.inductionOn with | h a => + change 0 + ofRep a = ofRep a + rw [← ofTensor_coeff a] + change ofTensor emptyTensor + ofTensor a.coeff = _ + rw [ofTensor_add] + have heq : Tensor.pullback (Equiv.emptySum Empty _) (Equiv.emptySum Empty _) + (Equiv.emptySum Empty _) a.coeff = blockSum emptyTensor a.coeff := by + funext x y z + rcases x with x | x + · exact x.elim + rcases y with y | y + · exact y.elim + rcases z with z | z + · exact z.elim + rfl + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem mul_comm_aux (A B : (TensorClass K)) : A * B = B * A := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + change ofRep a * ofRep b = ofRep b * ofRep a + rw [← ofTensor_coeff a, ← ofTensor_coeff b, ofTensor_mul, ofTensor_mul] + have heq : Tensor.pullback (Equiv.prodComm _ _) (Equiv.prodComm _ _) + (Equiv.prodComm _ _) (Tensor.product b.coeff a.coeff) = + Tensor.product a.coeff b.coeff := by + funext x y z + exact mul_comm _ _ + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem mul_assoc_aux (A B C : (TensorClass K)) : (A * B) * C = A * (B * C) := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + induction C using Quotient.inductionOn with | h c => + change (ofRep a * ofRep b) * ofRep c = ofRep a * (ofRep b * ofRep c) + rw [← ofTensor_coeff a, ← ofTensor_coeff b, ← ofTensor_coeff c] + simp only [ofTensor_mul] + have heq : Tensor.pullback (Equiv.prodAssoc _ _ _) (Equiv.prodAssoc _ _ _) + (Equiv.prodAssoc _ _ _) (Tensor.product a.coeff (Tensor.product b.coeff c.coeff)) = + Tensor.product (Tensor.product a.coeff b.coeff) c.coeff := by + funext x y z + exact (mul_assoc _ _ _).symm + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem one_mul_aux (A : (TensorClass K)) : 1 * A = A := by + induction A using Quotient.inductionOn with | h a => + change 1 * ofRep a = ofRep a + rw [← ofTensor_coeff a] + change ofTensor unitTensor * ofTensor a.coeff = _ + rw [ofTensor_mul] + have heq : Tensor.pullback (Equiv.punitProd _) (Equiv.punitProd _) + (Equiv.punitProd _) a.coeff = Tensor.product unitTensor a.coeff := by + funext x y z + exact (one_mul _).symm + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + +theorem zero_mul_aux (A : (TensorClass K)) : 0 * A = 0 := by + induction A using Quotient.inductionOn with | h a => + change 0 * ofRep a = 0 + rw [← ofTensor_coeff a] + change ofTensor emptyTensor * ofTensor a.coeff = ofTensor emptyTensor + rw [ofTensor_mul] + apply ofTensor_eq + · refine ⟨fun x => x.elim, fun y => y.elim, fun z => z.elim, ?_⟩ + funext x + exact x.elim + · refine ⟨fun x => x.1.elim, fun y => y.1.elim, fun z => z.1.elim, ?_⟩ + funext x + exact x.1.elim + +theorem left_distrib_aux (A B C : (TensorClass K)) : A * (B + C) = A * B + A * C := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + induction C using Quotient.inductionOn with | h c => + change ofRep a * (ofRep b + ofRep c) = ofRep a * ofRep b + ofRep a * ofRep c + rw [← ofTensor_coeff a, ← ofTensor_coeff b, ← ofTensor_coeff c] + simp only [ofTensor_add, ofTensor_mul] + have heq : Tensor.pullback (Equiv.prodSumDistrib _ _ _) (Equiv.prodSumDistrib _ _ _) + (Equiv.prodSumDistrib _ _ _) + (blockSum (Tensor.product a.coeff b.coeff) (Tensor.product a.coeff c.coeff)) = + Tensor.product a.coeff (blockSum b.coeff c.coeff) := by + funext x y z + rcases x with ⟨x, x'⟩ + rcases y with ⟨y, y'⟩ + rcases z with ⟨z, z'⟩ + rcases x' with x' | x' <;> rcases y' with y' | y' <;> rcases z' with z' | z' <;> + simp [Tensor.pullback, Tensor.product, blockSum, Equiv.prodSumDistrib] + rw [← heq] + exact ofTensor_pullback_equiv _ _ _ _ + +noncomputable instance : CommSemiring (TensorClass K) where + add := (· + ·) + mul := (· * ·) + zero := 0 + one := 1 + nsmul := nsmulRec + nsmul_zero := by intros; rfl + nsmul_succ := by intros; rfl + add_assoc := add_assoc_aux + add_comm := add_comm_aux + zero_add := zero_add_aux + add_zero A := by rw [add_comm_aux]; exact zero_add_aux A + mul_assoc := mul_assoc_aux + mul_comm := mul_comm_aux + one_mul := one_mul_aux + mul_one A := by rw [mul_comm_aux]; exact one_mul_aux A + zero_mul := zero_mul_aux + mul_zero A := by rw [mul_comm_aux]; exact zero_mul_aux A + left_distrib := left_distrib_aux + right_distrib A B C := by + rw [mul_comm_aux, left_distrib_aux, mul_comm_aux C A, mul_comm_aux C B] + +theorem add_mono {A B C D : (TensorClass K)} (hAB : A ≤ B) (hCD : C ≤ D) : + A + C ≤ B + D := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + induction C using Quotient.inductionOn with | h c => + induction D using Quotient.inductionOn with | h d => + exact TensorRep.Restricts.ofTensor (hAB.blockSum hCD) + +theorem mul_mono {A B C D : (TensorClass K)} (hAB : A ≤ B) (hCD : C ≤ D) : + A * C ≤ B * D := by + induction A using Quotient.inductionOn with | h a => + induction B using Quotient.inductionOn with | h b => + induction C using Quotient.inductionOn with | h c => + induction D using Quotient.inductionOn with | h d => + exact TensorRep.Restricts.ofTensor (hAB.product hCD) + +theorem zero_le (A : (TensorClass K)) : 0 ≤ A := by + induction A using Quotient.inductionOn with | h a => + change 0 ≤ ofRep a + rw [← ofTensor_coeff a] + apply ofTensor_le + refine ⟨fun x => x.elim, fun y => y.elim, fun z => z.elim, ?_⟩ + funext x + exact x.elim + +end MatrixMultiplicationAllFields.TensorSpectrum.TensorClass diff --git a/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/WeightedPolynomials.lean b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/WeightedPolynomials.lean new file mode 100644 index 0000000000..75790ba534 --- /dev/null +++ b/LeanPool/ExactMatrixExponents/LinearAlgebra/TensorSpectrum/WeightedPolynomials.lean @@ -0,0 +1,116 @@ +/- +Copyright (c) 2026 the original authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: OpenAI +-/ +/- Modified by Lean Pool contributors for this port. -/ +module + +public import LeanPool.ExactMatrixExponents.LinearAlgebra.TensorSpectrum.PolynomialTensors +public import LeanPool.ExactMatrixExponents.LinearAlgebra.MatrixExponent.LocalTensor + +/-! +# Explicit polynomial families for diagonal weight degenerations + +The diagonal degeneration has a polynomial coefficient family, not merely a +topological limit. Its constant coefficient is the retained tensor. Its degree +is controlled by the supported total weights. At every nonzero parameter its +evaluation is an exact restriction of the source tensor. These are the inputs +needed to extract tensor powers by finite interpolation. +-/ + +@[expose] public section + +noncomputable section + +open scoped BigOperators NNReal +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation +open MatrixMultiplicationAllFields.MatrixExponent +open MatrixMultiplicationAllFields.MatrixMultiplication.Foundation.Tensor + +namespace MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors + +variable {K : Type*} [CommSemiring K] + +variable {X Y Z : Type*} + +/-- The monomial family associated to three integer coordinate weights. -/ +def weightedPolynomial (T : Tensor K X Y Z) + (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) : + Tensor (Polynomial K) X Y Z := + fun x y z => Polynomial.monomial (wx x + wy y + wz z).toNat (T x y z) + +/-- Polynomial evaluation agrees with the continuous coefficient family used +in the degeneration proof, including at the parameter zero. -/ +theorem weightedPolynomial_eval (T : Tensor K X Y Z) + (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) (t : K) : + (fun x y z => (weightedPolynomial T wx wy wz x y z).eval t) = + weightedFamily T wx wy wz t := by + funext x y z + simp [weightedPolynomial, weightedFamily, Polynomial.eval_monomial, mul_comm] + +/-- The constant coefficient keeps precisely the supported weight-zero terms. -/ +theorem weightedPolynomial_coeff_zero (T : Tensor K X Y Z) + (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) + (h : ∀ x y z, T x y z ≠ 0 → 0 ≤ wx x + wy y + wz z) + (x : X) (y : Y) (z : Z) : + (weightedPolynomial T wx wy wz x y z).coeff 0 = + weightedLimit T wx wy wz x y z := by + have heq := (weightedPolynomial_eval T wx wy wz 0).trans + (weightedFamily_zero T wx wy wz h) + simpa only [Polynomial.coeff_zero_eq_eval_zero] using + congrFun (congrFun (congrFun heq x) y) z + +/-- A degree bound is needed only on supported coefficients. Unsupported +coordinates are the zero polynomial, regardless of their assigned weights. -/ +theorem weightedPolynomial_natDegree_le (T : Tensor K X Y Z) + (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) {D : ℕ} + (hD : ∀ x y z, T x y z ≠ 0 → (wx x + wy y + wz z).toNat ≤ D) + (x : X) (y : Y) (z : Z) : + (weightedPolynomial T wx wy wz x y z).natDegree ≤ D := by + by_cases hT : T x y z = 0 + · simp [weightedPolynomial, hT] + · exact (Polynomial.natDegree_monomial_le (T x y z)).trans (hD x y z hT) + +/-- The same degree bound in the form used by polynomial interpolation. -/ +theorem weightedPolynomial_degree_le (T : Tensor K X Y Z) + (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) {D : ℕ} + (hD : ∀ x y z, T x y z ≠ 0 → (wx x + wy y + wz z).toNat ≤ D) + (x : X) (y : Y) (z : Z) : + (weightedPolynomial T wx wy wz x y z).degree ≤ D := + Polynomial.degree_le_of_natDegree_le + (weightedPolynomial_natDegree_le T wx wy wz hD x y z) + +/-- A weight-zero/weight-one support split gives degree at most one. This is +the bound used by the determinant filtration and the three-sector split. -/ +theorem weightedPolynomial_degree_le_one (T : Tensor K X Y Z) + (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) + (h : ∀ x y z, T x y z ≠ 0 → + wx x + wy y + wz z = 0 ∨ wx x + wy y + wz z = 1) + (x : X) (y : Y) (z : Z) : + (weightedPolynomial T wx wy wz x y z).degree ≤ (1 : ℕ) := by + apply weightedPolynomial_degree_le T wx wy wz + intro u v w hT + rcases h u v w hT with hw | hw <;> simp [hw] + +theorem weightedFamily_mem_restrictionOrbit + [Fintype X] [Fintype Y] [Fintype Z] + (T : Tensor K X Y Z) (wx : X → ℤ) (wy : Y → ℤ) (wz : Z → ℤ) + (h : ∀ x y z, T x y z ≠ 0 → 0 ≤ wx x + wy y + wz z) + (t : K) (power : ℤ → K) + (hadd : ∀ a b, power (a + b) = power a * power b) + (hnat : ∀ n : ℕ, power n = t ^ n) : + weightedFamily T wx wy wz t ∈ LocalTensor.orbit T := by + classical + refine ⟨(fun x' x => if x = x' then power (wx x) else 0), + (fun y' y => if y = y' then power (wy y) else 0), + (fun z' z => if z = z' then power (wz z) else 0), ?_⟩ + rw [restrict_diagonal] + funext x y z + by_cases hT : T x y z = 0 + · simp [weightedFamily, hT] + · have hnonneg := h x y z hT + dsimp [weightedFamily] + rw [← hnat, Int.toNat_of_nonneg hnonneg, hadd, hadd] + +end MatrixMultiplicationAllFields.TensorSpectrum.PolynomialTensors diff --git a/LeanPool/projects/exact-matrix-exponents.yaml b/LeanPool/projects/exact-matrix-exponents.yaml new file mode 100644 index 0000000000..dc5d38b733 --- /dev/null +++ b/LeanPool/projects/exact-matrix-exponents.yaml @@ -0,0 +1,43 @@ +slug: exact-matrix-exponents +title: Exact square, dual and rectangular matrix multiplication exponents +summary: Determines the arithmetic exponent of square matrix multiplication as 9/4 + over every field and the dual exponent as 1/2. It also gives a symmetric formula + for the rectangular exponent, using formal polynomial identities in division-free + arithmetic programs. The pinned Lean source states all three exact results. + The accompanying preprint gives the square equality for circuits allowing + division and states bounds for the dual exponent and rectangular rank. +branch: algebraic complexity theory +entry_module: LeanPool.ExactMatrixExponents +authors: +- OpenAI +source: + url: https://github.com/openai/math/blob/3344da59991ed94f9ba711217b29c1d760badfa6/lean/OAI/LinearAlgebra/SpectralBooks/ExactExponent.lean + github_repo: openai/math + commit: 3344da59991ed94f9ba711217b29c1d760badfa6 + paper_url: https://github.com/openai/math/blob/3344da59991ed94f9ba711217b29c1d760badfa6/preprints/The-matrix-multiplication-exponent-is-nine-fourths-November-24-2026/paper.pdf +license: Apache-2.0 +status: verified +provenance: AI +main_declarations: +- MatrixMultiplicationAllFields.SpectralBooks.square_exponent +- MatrixMultiplicationAllFields.SpectralBooks.dual_exponent +- MatrixMultiplicationAllFields.SpectralBooks.rectangular_exponent +main_results: +- declaration: MatrixMultiplicationAllFields.SpectralBooks.square_exponent + informal: Over every field, the exponent of division-free square matrix multiplication + in the formal polynomial model is 9/4. +- declaration: MatrixMultiplicationAllFields.SpectralBooks.dual_exponent + informal: The dual exponent for multiplying rectangular matrices is 1/2 over + every field. +- declaration: MatrixMultiplicationAllFields.SpectralBooks.rectangular_exponent + informal: Over every field, the exact rectangular exponent is a symmetric function + of the three nonnegative parts of its dimension weights. +tags: +- matrix-multiplication +- arithmetic-complexity +- tensor-rank +- rectangular-exponents +msc: +- 68Q17 +- 15A69 +- 68Q25